diff --git a/.github/ISSUE_TEMPLATE/bug-report.md b/.github/ISSUE_TEMPLATE/bug-report.md index b2da09c12413..cc2ac6375ead 100644 --- a/.github/ISSUE_TEMPLATE/bug-report.md +++ b/.github/ISSUE_TEMPLATE/bug-report.md @@ -1,7 +1,8 @@ --- name: Bug Report about: Create a report to help us squash bugs! - +title: "[Bug]: " +labels: "T:Bug" --- Running linter" @go install github.com/golangci/golangci-lint/cmd/golangci-lint@$(golangci_version) - @$(golangci_lint_cmd) run --timeout=10m + @./scripts/go-lint-all.bash --timeout=15m lint-fix: @echo "--> Running linter" @go install github.com/golangci/golangci-lint/cmd/golangci-lint@$(golangci_version) - @$(golangci_lint_cmd) run --fix --out-format=tab --issues-exit-code=0 + @./scripts/go-lint-all.bash --fix .PHONY: lint lint-fix -format: - @go install github.com/golangci/golangci-lint/cmd/golangci-lint@$(golangci_version) - $(golangci_lint_cmd) run --fix -.PHONY: format - ############################################################################### ### Protobuf ### ############################################################################### diff --git a/RELEASE_PROCESS.md b/RELEASE_PROCESS.md index da883e391111..3b0da040a0db 100644 --- a/RELEASE_PROCESS.md +++ b/RELEASE_PROCESS.md @@ -120,7 +120,7 @@ ways in stable releases and `main` branch. ### Migrations -To smoothen the update to the latest stable release, the SDK includes a set of CLI commands for managing migrations between SDK versions, under the `migrate` subcommand. Only migration scripts between stable releases are included. For the current major release, and later, migrations are supported. +See the SDK's policy on migrations [here](https://docs.cosmos.network/main/migrations/intro). ### What qualifies as a Stable Release Update (SRU) diff --git a/SECURITY.md b/SECURITY.md index 302c84aa6cfb..636d34e850ad 100644 --- a/SECURITY.md +++ b/SECURITY.md @@ -1,131 +1,79 @@ -# Security - -> **IMPORTANT**: If you find a security issue, you can -report it to our [bug bounty program](https://hackerone.com/cosmos) on HackerOne. *DO NOT* open a public issue on the repository. - -## Bug Bounty - -As part of our [Coordinated Vulnerability Disclosure Policy](https://tendermint.com/security), we operate a -[bug bounty program](https://hackerone.com/cosmos) with Hacker One. - -See the policy linked above for more details on submissions and rewards and read -this [blog post](https://blog.cosmos.network/bug-bounty-program-for-tendermint-cosmos-833c67693586) for the program scope. - -The following is a list of examples of the kinds of bugs we're most interested -in for the Cosmos SDK. See [here](https://github.com/cometbft/cometbft/blob/master/SECURITY.md) for vulnerabilities we are interested -in for CometBFT and other lower-level libraries (eg. [IAVL](https://github.com/cosmos/iavl)). - -### Core packages - -* [`/baseapp`](https://github.com/cosmos/cosmos-sdk/tree/main/baseapp) -* [`/crypto`](https://github.com/cosmos/cosmos-sdk/tree/main/crypto) -* [`/types`](https://github.com/cosmos/cosmos-sdk/tree/main/types) -* [`/store`](https://github.com/cosmos/cosmos-sdk/tree/main/store) - -### Modules - -* [`x/auth`](https://github.com/cosmos/cosmos-sdk/tree/main/x/auth) -* [`x/bank`](https://github.com/cosmos/cosmos-sdk/tree/main/x/bank) -* [`x/staking`](https://github.com/cosmos/cosmos-sdk/tree/main/x/staking) -* [`x/slashing`](https://github.com/cosmos/cosmos-sdk/tree/main/x/slashing) -* [`x/evidence`](https://github.com/cosmos/cosmos-sdk/tree/main/x/evidence) -* [`x/distribution`](https://github.com/cosmos/cosmos-sdk/tree/main/x/distribution) -* [`x/mint`](https://github.com/cosmos/cosmos-sdk/tree/main/x/mint) - -We are interested in bugs in other modules, however the above are most likely to -have significant vulnerabilities, due to the complexity / nuance involved. We -also recommend you to read the [specification](https://github.com/cosmos/cosmos-sdk/blob/main/docs/building-modules/README.md) of each module before digging into -the code. - -### How we process Tx parameters - -* Integer operations on tx parameters, especially `sdk.Int` / `sdk.Dec` -* Gas calculation & parameter choices -* Tx signature verification (see [`x/auth/ante`](https://github.com/cosmos/cosmos-sdk/tree/main/x/auth/ante)) -* Possible Node DoS vectors (perhaps due to gas weighting / non constant timing) - -### Handling private keys - -* HD key derivation, local and Ledger, and all key-management functionality -* Side-channel attack vectors with our implementations - * e.g. key exfiltration based on time or memory-access patterns when decrypting privkey - -## Disclosure Process - -The Cosmos SDK team uses the following disclosure process: - -1. After a security report is received, the Cosmos SDK team works to verify the issue and confirm its severity level using Common Vulnerability Scoring System (CVSS). -1. The Cosmos SDK team collaborates with the CometBFT and Gaia teams to determine the vulnerability’s potential impact on the Cosmos Hub and partners. -1. Patches are prepared in private repositories for eligible releases of Cosmos SDK. See [Stable Release Policy](https://github.com/cosmos/cosmos-sdk/blob/main/RELEASE_PROCESS.md#stable-release-policy) for a list of eligible releases. -1. If it is determined that a CVE-ID is required, we request a CVE through a CVE Numbering Authority. -1. We notify the community that a security release is coming to give users time to prepare their systems for the update. Notifications can include forum posts, tweets, and emails to partners and validators. -1. 24 hours after the notification, fixes are applied publicly and new releases are issued. -1. The Gaia team updates their CometBFT and Cosmos SDK dependencies to use these releases and then issues new Gaia releases. -1. After releases are available for CometBFT, Cosmos SDK, and Gaia, we notify the community again through the same channels. We also publish a Security Advisory on Github and publish the CVE, as long as the Security Advisory and the CVE do not include information on how to exploit these vulnerabilities beyond the information that is available in the patch. -1. After the community is notified, CometBFT pays out any relevant bug bounties to submitters. -1. One week after the releases go out, we publish a post with details and our response to the vulnerability. - -This process can take some time. Every effort is made to handle the bug in as timely a manner as possible. However, it's important that we follow this security process to ensure that disclosures are handled consistently and to keep Cosmos SDK and its downstream dependent projects--including but not limited to Gaia and the Cosmos Hub--as secure as possible. - -### Disclosure Communications - -Communications to partners usually include the following details: - -1. Affected version or versions -1. New release version -1. Impact on user funds -1. For timed releases, a date and time that the new release will be made available -1. Impact on the partners if upgrades are not completed in a timely manner -1. Potential required actions if an adverse condition arises during the security release process - -An example notice looks like: - -```text -Dear Cosmos SDK partners, - -A critical security vulnerability has been identified in Cosmos SDK vX.X.X. -User funds are NOT at risk; however, the vulnerability can result in a chain halt. - -This notice is to inform you that on [[**March 1 at 1pm EST/6pm UTC**]], we will be releasing Cosmos SDK vX.X.Y to fix the security issue. -We ask all validators to upgrade their nodes ASAP. - -If the chain halts, validators with sufficient voting power must upgrade and come online for the chain to resume. -``` - -### Example Timeline - -The following timeline is an example of triage and response. Each task identifies the required roles and team members; however, multiple people can play each role and each person may play multiple roles. - -#### 24+ Hours Before Release Time - -1. Request CVE number (ADMIN) -1. Gather emails and other contact info for validators (COMMS LEAD) -1. Test fixes on a testnet (COSMOS SDK ENG) -1. Write “Security Advisory” for forum (COSMOS SDK LEAD) - -#### 24 Hours Before Release Time - -1. Post “Security Advisory” pre-notification on forum (COSMOS SDK LEAD) -1. Post Tweet linking to forum post (COMMS LEAD) -1. Announce security advisory/link to post in various other social channels (Telegram, Discord) (COMMS LEAD) -1. Send emails to partners or other users (PARTNERSHIPS LEAD) - -#### Release Time - -1. Cut Cosmos SDK releases for eligible versions (COSMOS SDK ENG) -1. Cut Gaia release for eligible versions (GAIA ENG) -1. Post “Security releases” on forum (COSMOS SDK LEAD) -1. Post new Tweet linking to forum post (COMMS LEAD) -1. Remind everyone using social channels (Telegram, Discord) that the release is out (COMMS LEAD) -1. Send emails to validators and other users (COMMS LEAD) -1. Publish Security Advisory and CVE if the CVE has no sensitive information (ADMIN) - -#### After Release Time - -1. Write forum post with exploit details (COSMOS SDK LEAD) -1. Approve payout on HackerOne for submitter (ADMIN) - -#### 7 Days After Release Time - -1. Publish CVE if it has not yet been published (ADMIN) -1. Publish forum post with exploit details (COSMOS SDK ENG, COSMOS SDK LEAD) +# Coordinated Vulnerability Disclosure Policy + +The Cosmos ecosystem believes that strong security is a blend of highly +technical security researchers who care about security and the forward +progression of the ecosystem and the attentiveness and openness of Cosmos core +contributors to help continually secure our operations. + +> **IMPORTANT**: *DO NOT* open public issues on this repository for security +> vulnerabilities. + +## Scope + +| Scope | +|-----------------------| +| last release (tagged) | +| main branch | + +The latest **release tag** of this repository is supported for security updates +as well as the **main** branch. Security vulnerabilities should be reported if +the vulnerability can be reproduced on either one of those. + +## Reporting a Vulnerability + +| Reporting methods | +|---------------------------------------------------------------| +| [GitHub Private Vulnerability Reporting][gh-private-advisory] | +| [HackerOne bug bounty program][h1] | + +All security vulnerabilities can be reported under GitHub's [Private +vulnerability reporting][gh-private-advisory] system. This will open a private +issue for the developers. Try to fill in as much of the questions as possible. +If you are not familiar with the CVSS system for assessing vulnerabilities, just +use the Low/High/Critical severity ratings. A partially filled in report for a +critical vulnerability is still better than no report at all. + +Vulnerabilities associated with the **Go, Rust or Protobuf code** of the +repository may be eligible for a [bug bounty][h1]. Please see the bug bounty +page for more details on submissions and rewards. If you think the vulnerability +is eligible for a payout, **report on HackerOne first**. + +Vulnerabilities in services and their source codes (JavaScript, web page, Google +Workspace) are not in scope for the bug bounty program, but they are welcome to +be reported in GitHub. + +### Guidelines + +We require that all researchers: + +* Abide by this policy to disclose vulnerabilities, and avoid posting + vulnerability information in public places, including GitHub, Discord, + Telegram, and Twitter. +* Make every effort to avoid privacy violations, degradation of user experience, + disruption to production systems (including but not limited to the Cosmos + Hub), and destruction of data. +* Keep any information about vulnerabilities that you’ve discovered confidential + between yourself and the Cosmos engineering team until the issue has been + resolved and disclosed. +* Avoid posting personally identifiable information, privately or publicly. + +If you follow these guidelines when reporting an issue to us, we commit to: + +* Not pursue or support any legal action related to your research on this + vulnerability +* Work with you to understand, resolve and ultimately disclose the issue in a + timely fashion + +### More information + +* See [TIMELINE.md] for an example timeline of a disclosure. +* See [DISCLOSURE.md] to see more into the inner workings of the disclosure + process. +* See [EXAMPLES.md] for some of the examples that we are interested in for the + bug bounty program. + +[gh-private-advisory]: /../../security/advisories/new +[h1]: https://hackerone.com/cosmos +[TIMELINE.md]: https://github.com/cosmos/security/blob/main/TIMELINE.md +[DISCLOSURE.md]: https://github.com/cosmos/security/blob/main/DISCLOSURE.md +[EXAMPLES.md]: https://github.com/cosmos/security/blob/main/EXAMPLES.md diff --git a/UPGRADING.md b/UPGRADING.md index 19da06f04ccd..f2fafaa33a11 100644 --- a/UPGRADING.md +++ b/UPGRADING.md @@ -62,6 +62,26 @@ The `gogoproto.goproto_stringer = false` annotation has been removed from most p Previously, all modules were required to be set in `OrderBeginBlockers`, `OrderEndBlockers` and `OrderInitGenesis / OrderExportGenesis` in `app.go` / `app_config.go`. This is no longer the case, the assertion has been loosened to only require modules implementing, respectively, the `module.BeginBlockAppModule`, `module.EndBlockAppModule` and `module.HasGenesis` interfaces. +### Modules Keepers + +The following modules `NewKeeper` function now take a `KVStoreService` instead of a `StoreKey`: + +* `x/auth` +* `x/consensus` +* `x/feegrant` +* `x/nft` + +When not using depinject, the `runtime.NewKVStoreService` method can be used to create a `KVStoreService` from a `StoreKey`: + +```diff +app.ConsensusParamsKeeper = consensusparamkeeper.NewKeeper( + appCodec, +- keys[consensusparamtypes.StoreKey] ++ runtime.NewKVStoreService(keys[consensusparamtypes.StoreKey]), + authtypes.NewModuleAddress(govtypes.ModuleName).String(), +) +``` + ### Packages #### Store @@ -73,20 +93,27 @@ References to `types/store.go` which contained aliases for store types have been The `store` module is extracted to have a separate go.mod file which allows it be a standalone module. All the store imports are now renamed to use `cosmossdk.io/store` instead of `github.com/cosmos/cosmos-sdk/store` across the SDK. +#### Client + +The return type of the interface method `TxConfig.SignModeHandler()` has been changed from `x/auth/signing.SignModeHandler` to `x/tx/signing.HandlerMap`. This change is transparent to most users as the `TxConfig` interface is typically implemented by private `x/auth/tx.config` struct (as returned by `auth.NewTxConfig`) which has been updated to return the new type. If users have implemented their own `TxConfig` interface, they will need to update their implementation to return the new type. + ### Modules -#### `x/capability` +#### `**all**` -Capability was moved to [IBC-GO](https://github.com/cosmos/ibc-go). IBC V8 will contain the necessary changes to incorporate the new module location +[RFC 001](https://docs.cosmos.network/main/rfc/rfc-001-tx-validation) has defined a simplification of the message validation process for modules. +The `sdk.Msg` interface has been updated to not require the implementation of the `ValidateBasic` method. +It is now recommended to validate message directly in the message server. When the validation is performed in the message server, the `ValidateBasic` method on a message is no longer required and can be removed. -#### `x/consensus` +#### `x/auth` -The `NewKeeper` method now takes a `KVStoreService` instead of a `StoreKey`. When not using depinject, the `runtime.NewKVStoreService` method can be used to create a `KVStoreService` from a `StoreKey`. +Methods in the `AccountKeeper` now use `context.Context` instead of `sdk.Context`. Any module that has an interface for it will need to update and re-generate mocks if needed. -```diff -- app.ConsensusParamsKeeper = consensusparamkeeper.NewKeeper(appCodec, keys[consensusparamtypes.StoreKey], authtypes.NewModuleAddress(govtypes.ModuleName).String()) -+ app.ConsensusParamsKeeper = consensusparamkeeper.NewKeeper(appCodec, runtime.NewKVStoreService(keys[consensusparamtypes.StoreKey]), authtypes.NewModuleAddress(govtypes.ModuleName).String()) -``` +For ante handler construction via `ante.NewAnteHandler`, the field `ante.HandlerOptions.SignModeHandler` has been updated to `x/tx/signing/HandlerMap` from `x/auth/signing/SignModeHandler`. Callers typically fetch this value from `client.TxConfig.SignModeHandler()` (which is also changed) so this change should be transparent to most users. + +#### `x/capability` + +Capability was moved to [IBC-GO](https://github.com/cosmos/ibc-go). IBC V8 will contain the necessary changes to incorporate the new module location #### `x/gov` diff --git a/api/cosmos/base/node/v1beta1/query.pulsar.go b/api/cosmos/base/node/v1beta1/query.pulsar.go index 600b4d5d3668..ff8148beebbb 100644 --- a/api/cosmos/base/node/v1beta1/query.pulsar.go +++ b/api/cosmos/base/node/v1beta1/query.pulsar.go @@ -4,10 +4,12 @@ package nodev1beta1 import ( fmt "fmt" runtime "github.com/cosmos/cosmos-proto/runtime" + _ "github.com/cosmos/gogoproto/gogoproto" _ "google.golang.org/genproto/googleapis/api/annotations" protoreflect "google.golang.org/protobuf/reflect/protoreflect" protoiface "google.golang.org/protobuf/runtime/protoiface" protoimpl "google.golang.org/protobuf/runtime/protoimpl" + timestamppb "google.golang.org/protobuf/types/known/timestamppb" io "io" reflect "reflect" sync "sync" @@ -370,14 +372,18 @@ func (x *fastReflection_ConfigRequest) ProtoMethods() *protoiface.Methods { } var ( - md_ConfigResponse protoreflect.MessageDescriptor - fd_ConfigResponse_minimum_gas_price protoreflect.FieldDescriptor + md_ConfigResponse protoreflect.MessageDescriptor + fd_ConfigResponse_minimum_gas_price protoreflect.FieldDescriptor + fd_ConfigResponse_pruning_keep_recent protoreflect.FieldDescriptor + fd_ConfigResponse_pruning_interval protoreflect.FieldDescriptor ) func init() { file_cosmos_base_node_v1beta1_query_proto_init() md_ConfigResponse = File_cosmos_base_node_v1beta1_query_proto.Messages().ByName("ConfigResponse") fd_ConfigResponse_minimum_gas_price = md_ConfigResponse.Fields().ByName("minimum_gas_price") + fd_ConfigResponse_pruning_keep_recent = md_ConfigResponse.Fields().ByName("pruning_keep_recent") + fd_ConfigResponse_pruning_interval = md_ConfigResponse.Fields().ByName("pruning_interval") } var _ protoreflect.Message = (*fastReflection_ConfigResponse)(nil) @@ -451,6 +457,938 @@ func (x *fastReflection_ConfigResponse) Range(f func(protoreflect.FieldDescripto return } } + if x.PruningKeepRecent != "" { + value := protoreflect.ValueOfString(x.PruningKeepRecent) + if !f(fd_ConfigResponse_pruning_keep_recent, value) { + return + } + } + if x.PruningInterval != "" { + value := protoreflect.ValueOfString(x.PruningInterval) + if !f(fd_ConfigResponse_pruning_interval, value) { + return + } + } +} + +// Has reports whether a field is populated. +// +// Some fields have the property of nullability where it is possible to +// distinguish between the default value of a field and whether the field +// was explicitly populated with the default value. Singular message fields, +// member fields of a oneof, and proto2 scalar fields are nullable. Such +// fields are populated only if explicitly set. +// +// In other cases (aside from the nullable cases above), +// a proto3 scalar field is populated if it contains a non-zero value, and +// a repeated field is populated if it is non-empty. +func (x *fastReflection_ConfigResponse) Has(fd protoreflect.FieldDescriptor) bool { + switch fd.FullName() { + case "cosmos.base.node.v1beta1.ConfigResponse.minimum_gas_price": + return x.MinimumGasPrice != "" + case "cosmos.base.node.v1beta1.ConfigResponse.pruning_keep_recent": + return x.PruningKeepRecent != "" + case "cosmos.base.node.v1beta1.ConfigResponse.pruning_interval": + return x.PruningInterval != "" + default: + if fd.IsExtension() { + panic(fmt.Errorf("proto3 declared messages do not support extensions: cosmos.base.node.v1beta1.ConfigResponse")) + } + panic(fmt.Errorf("message cosmos.base.node.v1beta1.ConfigResponse does not contain field %s", fd.FullName())) + } +} + +// Clear clears the field such that a subsequent Has call reports false. +// +// Clearing an extension field clears both the extension type and value +// associated with the given field number. +// +// Clear is a mutating operation and unsafe for concurrent use. +func (x *fastReflection_ConfigResponse) Clear(fd protoreflect.FieldDescriptor) { + switch fd.FullName() { + case "cosmos.base.node.v1beta1.ConfigResponse.minimum_gas_price": + x.MinimumGasPrice = "" + case "cosmos.base.node.v1beta1.ConfigResponse.pruning_keep_recent": + x.PruningKeepRecent = "" + case "cosmos.base.node.v1beta1.ConfigResponse.pruning_interval": + x.PruningInterval = "" + default: + if fd.IsExtension() { + panic(fmt.Errorf("proto3 declared messages do not support extensions: cosmos.base.node.v1beta1.ConfigResponse")) + } + panic(fmt.Errorf("message cosmos.base.node.v1beta1.ConfigResponse does not contain field %s", fd.FullName())) + } +} + +// Get retrieves the value for a field. +// +// For unpopulated scalars, it returns the default value, where +// the default value of a bytes scalar is guaranteed to be a copy. +// For unpopulated composite types, it returns an empty, read-only view +// of the value; to obtain a mutable reference, use Mutable. +func (x *fastReflection_ConfigResponse) Get(descriptor protoreflect.FieldDescriptor) protoreflect.Value { + switch descriptor.FullName() { + case "cosmos.base.node.v1beta1.ConfigResponse.minimum_gas_price": + value := x.MinimumGasPrice + return protoreflect.ValueOfString(value) + case "cosmos.base.node.v1beta1.ConfigResponse.pruning_keep_recent": + value := x.PruningKeepRecent + return protoreflect.ValueOfString(value) + case "cosmos.base.node.v1beta1.ConfigResponse.pruning_interval": + value := x.PruningInterval + return protoreflect.ValueOfString(value) + default: + if descriptor.IsExtension() { + panic(fmt.Errorf("proto3 declared messages do not support extensions: cosmos.base.node.v1beta1.ConfigResponse")) + } + panic(fmt.Errorf("message cosmos.base.node.v1beta1.ConfigResponse does not contain field %s", descriptor.FullName())) + } +} + +// Set stores the value for a field. +// +// For a field belonging to a oneof, it implicitly clears any other field +// that may be currently set within the same oneof. +// For extension fields, it implicitly stores the provided ExtensionType. +// When setting a composite type, it is unspecified whether the stored value +// aliases the source's memory in any way. If the composite value is an +// empty, read-only value, then it panics. +// +// Set is a mutating operation and unsafe for concurrent use. +func (x *fastReflection_ConfigResponse) Set(fd protoreflect.FieldDescriptor, value protoreflect.Value) { + switch fd.FullName() { + case "cosmos.base.node.v1beta1.ConfigResponse.minimum_gas_price": + x.MinimumGasPrice = value.Interface().(string) + case "cosmos.base.node.v1beta1.ConfigResponse.pruning_keep_recent": + x.PruningKeepRecent = value.Interface().(string) + case "cosmos.base.node.v1beta1.ConfigResponse.pruning_interval": + x.PruningInterval = value.Interface().(string) + default: + if fd.IsExtension() { + panic(fmt.Errorf("proto3 declared messages do not support extensions: cosmos.base.node.v1beta1.ConfigResponse")) + } + panic(fmt.Errorf("message cosmos.base.node.v1beta1.ConfigResponse does not contain field %s", fd.FullName())) + } +} + +// Mutable returns a mutable reference to a composite type. +// +// If the field is unpopulated, it may allocate a composite value. +// For a field belonging to a oneof, it implicitly clears any other field +// that may be currently set within the same oneof. +// For extension fields, it implicitly stores the provided ExtensionType +// if not already stored. +// It panics if the field does not contain a composite type. +// +// Mutable is a mutating operation and unsafe for concurrent use. +func (x *fastReflection_ConfigResponse) Mutable(fd protoreflect.FieldDescriptor) protoreflect.Value { + switch fd.FullName() { + case "cosmos.base.node.v1beta1.ConfigResponse.minimum_gas_price": + panic(fmt.Errorf("field minimum_gas_price of message cosmos.base.node.v1beta1.ConfigResponse is not mutable")) + case "cosmos.base.node.v1beta1.ConfigResponse.pruning_keep_recent": + panic(fmt.Errorf("field pruning_keep_recent of message cosmos.base.node.v1beta1.ConfigResponse is not mutable")) + case "cosmos.base.node.v1beta1.ConfigResponse.pruning_interval": + panic(fmt.Errorf("field pruning_interval of message cosmos.base.node.v1beta1.ConfigResponse is not mutable")) + default: + if fd.IsExtension() { + panic(fmt.Errorf("proto3 declared messages do not support extensions: cosmos.base.node.v1beta1.ConfigResponse")) + } + panic(fmt.Errorf("message cosmos.base.node.v1beta1.ConfigResponse does not contain field %s", fd.FullName())) + } +} + +// NewField returns a new value that is assignable to the field +// for the given descriptor. For scalars, this returns the default value. +// For lists, maps, and messages, this returns a new, empty, mutable value. +func (x *fastReflection_ConfigResponse) NewField(fd protoreflect.FieldDescriptor) protoreflect.Value { + switch fd.FullName() { + case "cosmos.base.node.v1beta1.ConfigResponse.minimum_gas_price": + return protoreflect.ValueOfString("") + case "cosmos.base.node.v1beta1.ConfigResponse.pruning_keep_recent": + return protoreflect.ValueOfString("") + case "cosmos.base.node.v1beta1.ConfigResponse.pruning_interval": + return protoreflect.ValueOfString("") + default: + if fd.IsExtension() { + panic(fmt.Errorf("proto3 declared messages do not support extensions: cosmos.base.node.v1beta1.ConfigResponse")) + } + panic(fmt.Errorf("message cosmos.base.node.v1beta1.ConfigResponse does not contain field %s", fd.FullName())) + } +} + +// WhichOneof reports which field within the oneof is populated, +// returning nil if none are populated. +// It panics if the oneof descriptor does not belong to this message. +func (x *fastReflection_ConfigResponse) WhichOneof(d protoreflect.OneofDescriptor) protoreflect.FieldDescriptor { + switch d.FullName() { + default: + panic(fmt.Errorf("%s is not a oneof field in cosmos.base.node.v1beta1.ConfigResponse", d.FullName())) + } + panic("unreachable") +} + +// GetUnknown retrieves the entire list of unknown fields. +// The caller may only mutate the contents of the RawFields +// if the mutated bytes are stored back into the message with SetUnknown. +func (x *fastReflection_ConfigResponse) GetUnknown() protoreflect.RawFields { + return x.unknownFields +} + +// SetUnknown stores an entire list of unknown fields. +// The raw fields must be syntactically valid according to the wire format. +// An implementation may panic if this is not the case. +// Once stored, the caller must not mutate the content of the RawFields. +// An empty RawFields may be passed to clear the fields. +// +// SetUnknown is a mutating operation and unsafe for concurrent use. +func (x *fastReflection_ConfigResponse) SetUnknown(fields protoreflect.RawFields) { + x.unknownFields = fields +} + +// IsValid reports whether the message is valid. +// +// An invalid message is an empty, read-only value. +// +// An invalid message often corresponds to a nil pointer of the concrete +// message type, but the details are implementation dependent. +// Validity is not part of the protobuf data model, and may not +// be preserved in marshaling or other operations. +func (x *fastReflection_ConfigResponse) IsValid() bool { + return x != nil +} + +// ProtoMethods returns optional fastReflectionFeature-path implementations of various operations. +// This method may return nil. +// +// The returned methods type is identical to +// "google.golang.org/protobuf/runtime/protoiface".Methods. +// Consult the protoiface package documentation for details. +func (x *fastReflection_ConfigResponse) ProtoMethods() *protoiface.Methods { + size := func(input protoiface.SizeInput) protoiface.SizeOutput { + x := input.Message.Interface().(*ConfigResponse) + if x == nil { + return protoiface.SizeOutput{ + NoUnkeyedLiterals: input.NoUnkeyedLiterals, + Size: 0, + } + } + options := runtime.SizeInputToOptions(input) + _ = options + var n int + var l int + _ = l + l = len(x.MinimumGasPrice) + if l > 0 { + n += 1 + l + runtime.Sov(uint64(l)) + } + l = len(x.PruningKeepRecent) + if l > 0 { + n += 1 + l + runtime.Sov(uint64(l)) + } + l = len(x.PruningInterval) + if l > 0 { + n += 1 + l + runtime.Sov(uint64(l)) + } + if x.unknownFields != nil { + n += len(x.unknownFields) + } + return protoiface.SizeOutput{ + NoUnkeyedLiterals: input.NoUnkeyedLiterals, + Size: n, + } + } + + marshal := func(input protoiface.MarshalInput) (protoiface.MarshalOutput, error) { + x := input.Message.Interface().(*ConfigResponse) + if x == nil { + return protoiface.MarshalOutput{ + NoUnkeyedLiterals: input.NoUnkeyedLiterals, + Buf: input.Buf, + }, nil + } + options := runtime.MarshalInputToOptions(input) + _ = options + size := options.Size(x) + dAtA := make([]byte, size) + i := len(dAtA) + _ = i + var l int + _ = l + if x.unknownFields != nil { + i -= len(x.unknownFields) + copy(dAtA[i:], x.unknownFields) + } + if len(x.PruningInterval) > 0 { + i -= len(x.PruningInterval) + copy(dAtA[i:], x.PruningInterval) + i = runtime.EncodeVarint(dAtA, i, uint64(len(x.PruningInterval))) + i-- + dAtA[i] = 0x1a + } + if len(x.PruningKeepRecent) > 0 { + i -= len(x.PruningKeepRecent) + copy(dAtA[i:], x.PruningKeepRecent) + i = runtime.EncodeVarint(dAtA, i, uint64(len(x.PruningKeepRecent))) + i-- + dAtA[i] = 0x12 + } + if len(x.MinimumGasPrice) > 0 { + i -= len(x.MinimumGasPrice) + copy(dAtA[i:], x.MinimumGasPrice) + i = runtime.EncodeVarint(dAtA, i, uint64(len(x.MinimumGasPrice))) + i-- + dAtA[i] = 0xa + } + if input.Buf != nil { + input.Buf = append(input.Buf, dAtA...) + } else { + input.Buf = dAtA + } + return protoiface.MarshalOutput{ + NoUnkeyedLiterals: input.NoUnkeyedLiterals, + Buf: input.Buf, + }, nil + } + unmarshal := func(input protoiface.UnmarshalInput) (protoiface.UnmarshalOutput, error) { + x := input.Message.Interface().(*ConfigResponse) + if x == nil { + return protoiface.UnmarshalOutput{ + NoUnkeyedLiterals: input.NoUnkeyedLiterals, + Flags: input.Flags, + }, nil + } + options := runtime.UnmarshalInputToOptions(input) + _ = options + dAtA := input.Buf + l := len(dAtA) + iNdEx := 0 + for iNdEx < l { + preIndex := iNdEx + var wire uint64 + for shift := uint(0); ; shift += 7 { + if shift >= 64 { + return protoiface.UnmarshalOutput{NoUnkeyedLiterals: input.NoUnkeyedLiterals, Flags: input.Flags}, runtime.ErrIntOverflow + } + if iNdEx >= l { + return protoiface.UnmarshalOutput{NoUnkeyedLiterals: input.NoUnkeyedLiterals, Flags: input.Flags}, io.ErrUnexpectedEOF + } + b := dAtA[iNdEx] + iNdEx++ + wire |= uint64(b&0x7F) << shift + if b < 0x80 { + break + } + } + fieldNum := int32(wire >> 3) + wireType := int(wire & 0x7) + if wireType == 4 { + return protoiface.UnmarshalOutput{NoUnkeyedLiterals: input.NoUnkeyedLiterals, Flags: input.Flags}, fmt.Errorf("proto: ConfigResponse: wiretype end group for non-group") + } + if fieldNum <= 0 { + return protoiface.UnmarshalOutput{NoUnkeyedLiterals: input.NoUnkeyedLiterals, Flags: input.Flags}, fmt.Errorf("proto: ConfigResponse: illegal tag %d (wire type %d)", fieldNum, wire) + } + switch fieldNum { + case 1: + if wireType != 2 { + return protoiface.UnmarshalOutput{NoUnkeyedLiterals: input.NoUnkeyedLiterals, Flags: input.Flags}, fmt.Errorf("proto: wrong wireType = %d for field MinimumGasPrice", wireType) + } + var stringLen uint64 + for shift := uint(0); ; shift += 7 { + if shift >= 64 { + return protoiface.UnmarshalOutput{NoUnkeyedLiterals: input.NoUnkeyedLiterals, Flags: input.Flags}, runtime.ErrIntOverflow + } + if iNdEx >= l { + return protoiface.UnmarshalOutput{NoUnkeyedLiterals: input.NoUnkeyedLiterals, Flags: input.Flags}, io.ErrUnexpectedEOF + } + b := dAtA[iNdEx] + iNdEx++ + stringLen |= uint64(b&0x7F) << shift + if b < 0x80 { + break + } + } + intStringLen := int(stringLen) + if intStringLen < 0 { + return protoiface.UnmarshalOutput{NoUnkeyedLiterals: input.NoUnkeyedLiterals, Flags: input.Flags}, runtime.ErrInvalidLength + } + postIndex := iNdEx + intStringLen + if postIndex < 0 { + return protoiface.UnmarshalOutput{NoUnkeyedLiterals: input.NoUnkeyedLiterals, Flags: input.Flags}, runtime.ErrInvalidLength + } + if postIndex > l { + return protoiface.UnmarshalOutput{NoUnkeyedLiterals: input.NoUnkeyedLiterals, Flags: input.Flags}, io.ErrUnexpectedEOF + } + x.MinimumGasPrice = string(dAtA[iNdEx:postIndex]) + iNdEx = postIndex + case 2: + if wireType != 2 { + return protoiface.UnmarshalOutput{NoUnkeyedLiterals: input.NoUnkeyedLiterals, Flags: input.Flags}, fmt.Errorf("proto: wrong wireType = %d for field PruningKeepRecent", wireType) + } + var stringLen uint64 + for shift := uint(0); ; shift += 7 { + if shift >= 64 { + return protoiface.UnmarshalOutput{NoUnkeyedLiterals: input.NoUnkeyedLiterals, Flags: input.Flags}, runtime.ErrIntOverflow + } + if iNdEx >= l { + return protoiface.UnmarshalOutput{NoUnkeyedLiterals: input.NoUnkeyedLiterals, Flags: input.Flags}, io.ErrUnexpectedEOF + } + b := dAtA[iNdEx] + iNdEx++ + stringLen |= uint64(b&0x7F) << shift + if b < 0x80 { + break + } + } + intStringLen := int(stringLen) + if intStringLen < 0 { + return protoiface.UnmarshalOutput{NoUnkeyedLiterals: input.NoUnkeyedLiterals, Flags: input.Flags}, runtime.ErrInvalidLength + } + postIndex := iNdEx + intStringLen + if postIndex < 0 { + return protoiface.UnmarshalOutput{NoUnkeyedLiterals: input.NoUnkeyedLiterals, Flags: input.Flags}, runtime.ErrInvalidLength + } + if postIndex > l { + return protoiface.UnmarshalOutput{NoUnkeyedLiterals: input.NoUnkeyedLiterals, Flags: input.Flags}, io.ErrUnexpectedEOF + } + x.PruningKeepRecent = string(dAtA[iNdEx:postIndex]) + iNdEx = postIndex + case 3: + if wireType != 2 { + return protoiface.UnmarshalOutput{NoUnkeyedLiterals: input.NoUnkeyedLiterals, Flags: input.Flags}, fmt.Errorf("proto: wrong wireType = %d for field PruningInterval", wireType) + } + var stringLen uint64 + for shift := uint(0); ; shift += 7 { + if shift >= 64 { + return protoiface.UnmarshalOutput{NoUnkeyedLiterals: input.NoUnkeyedLiterals, Flags: input.Flags}, runtime.ErrIntOverflow + } + if iNdEx >= l { + return protoiface.UnmarshalOutput{NoUnkeyedLiterals: input.NoUnkeyedLiterals, Flags: input.Flags}, io.ErrUnexpectedEOF + } + b := dAtA[iNdEx] + iNdEx++ + stringLen |= uint64(b&0x7F) << shift + if b < 0x80 { + break + } + } + intStringLen := int(stringLen) + if intStringLen < 0 { + return protoiface.UnmarshalOutput{NoUnkeyedLiterals: input.NoUnkeyedLiterals, Flags: input.Flags}, runtime.ErrInvalidLength + } + postIndex := iNdEx + intStringLen + if postIndex < 0 { + return protoiface.UnmarshalOutput{NoUnkeyedLiterals: input.NoUnkeyedLiterals, Flags: input.Flags}, runtime.ErrInvalidLength + } + if postIndex > l { + return protoiface.UnmarshalOutput{NoUnkeyedLiterals: input.NoUnkeyedLiterals, Flags: input.Flags}, io.ErrUnexpectedEOF + } + x.PruningInterval = string(dAtA[iNdEx:postIndex]) + iNdEx = postIndex + default: + iNdEx = preIndex + skippy, err := runtime.Skip(dAtA[iNdEx:]) + if err != nil { + return protoiface.UnmarshalOutput{NoUnkeyedLiterals: input.NoUnkeyedLiterals, Flags: input.Flags}, err + } + if (skippy < 0) || (iNdEx+skippy) < 0 { + return protoiface.UnmarshalOutput{NoUnkeyedLiterals: input.NoUnkeyedLiterals, Flags: input.Flags}, runtime.ErrInvalidLength + } + if (iNdEx + skippy) > l { + return protoiface.UnmarshalOutput{NoUnkeyedLiterals: input.NoUnkeyedLiterals, Flags: input.Flags}, io.ErrUnexpectedEOF + } + if !options.DiscardUnknown { + x.unknownFields = append(x.unknownFields, dAtA[iNdEx:iNdEx+skippy]...) + } + iNdEx += skippy + } + } + + if iNdEx > l { + return protoiface.UnmarshalOutput{NoUnkeyedLiterals: input.NoUnkeyedLiterals, Flags: input.Flags}, io.ErrUnexpectedEOF + } + return protoiface.UnmarshalOutput{NoUnkeyedLiterals: input.NoUnkeyedLiterals, Flags: input.Flags}, nil + } + return &protoiface.Methods{ + NoUnkeyedLiterals: struct{}{}, + Flags: protoiface.SupportMarshalDeterministic | protoiface.SupportUnmarshalDiscardUnknown, + Size: size, + Marshal: marshal, + Unmarshal: unmarshal, + Merge: nil, + CheckInitialized: nil, + } +} + +var ( + md_StatusRequest protoreflect.MessageDescriptor +) + +func init() { + file_cosmos_base_node_v1beta1_query_proto_init() + md_StatusRequest = File_cosmos_base_node_v1beta1_query_proto.Messages().ByName("StatusRequest") +} + +var _ protoreflect.Message = (*fastReflection_StatusRequest)(nil) + +type fastReflection_StatusRequest StatusRequest + +func (x *StatusRequest) ProtoReflect() protoreflect.Message { + return (*fastReflection_StatusRequest)(x) +} + +func (x *StatusRequest) slowProtoReflect() protoreflect.Message { + mi := &file_cosmos_base_node_v1beta1_query_proto_msgTypes[2] + if protoimpl.UnsafeEnabled && x != nil { + ms := protoimpl.X.MessageStateOf(protoimpl.Pointer(x)) + if ms.LoadMessageInfo() == nil { + ms.StoreMessageInfo(mi) + } + return ms + } + return mi.MessageOf(x) +} + +var _fastReflection_StatusRequest_messageType fastReflection_StatusRequest_messageType +var _ protoreflect.MessageType = fastReflection_StatusRequest_messageType{} + +type fastReflection_StatusRequest_messageType struct{} + +func (x fastReflection_StatusRequest_messageType) Zero() protoreflect.Message { + return (*fastReflection_StatusRequest)(nil) +} +func (x fastReflection_StatusRequest_messageType) New() protoreflect.Message { + return new(fastReflection_StatusRequest) +} +func (x fastReflection_StatusRequest_messageType) Descriptor() protoreflect.MessageDescriptor { + return md_StatusRequest +} + +// Descriptor returns message descriptor, which contains only the protobuf +// type information for the message. +func (x *fastReflection_StatusRequest) Descriptor() protoreflect.MessageDescriptor { + return md_StatusRequest +} + +// Type returns the message type, which encapsulates both Go and protobuf +// type information. If the Go type information is not needed, +// it is recommended that the message descriptor be used instead. +func (x *fastReflection_StatusRequest) Type() protoreflect.MessageType { + return _fastReflection_StatusRequest_messageType +} + +// New returns a newly allocated and mutable empty message. +func (x *fastReflection_StatusRequest) New() protoreflect.Message { + return new(fastReflection_StatusRequest) +} + +// Interface unwraps the message reflection interface and +// returns the underlying ProtoMessage interface. +func (x *fastReflection_StatusRequest) Interface() protoreflect.ProtoMessage { + return (*StatusRequest)(x) +} + +// Range iterates over every populated field in an undefined order, +// calling f for each field descriptor and value encountered. +// Range returns immediately if f returns false. +// While iterating, mutating operations may only be performed +// on the current field descriptor. +func (x *fastReflection_StatusRequest) Range(f func(protoreflect.FieldDescriptor, protoreflect.Value) bool) { +} + +// Has reports whether a field is populated. +// +// Some fields have the property of nullability where it is possible to +// distinguish between the default value of a field and whether the field +// was explicitly populated with the default value. Singular message fields, +// member fields of a oneof, and proto2 scalar fields are nullable. Such +// fields are populated only if explicitly set. +// +// In other cases (aside from the nullable cases above), +// a proto3 scalar field is populated if it contains a non-zero value, and +// a repeated field is populated if it is non-empty. +func (x *fastReflection_StatusRequest) Has(fd protoreflect.FieldDescriptor) bool { + switch fd.FullName() { + default: + if fd.IsExtension() { + panic(fmt.Errorf("proto3 declared messages do not support extensions: cosmos.base.node.v1beta1.StatusRequest")) + } + panic(fmt.Errorf("message cosmos.base.node.v1beta1.StatusRequest does not contain field %s", fd.FullName())) + } +} + +// Clear clears the field such that a subsequent Has call reports false. +// +// Clearing an extension field clears both the extension type and value +// associated with the given field number. +// +// Clear is a mutating operation and unsafe for concurrent use. +func (x *fastReflection_StatusRequest) Clear(fd protoreflect.FieldDescriptor) { + switch fd.FullName() { + default: + if fd.IsExtension() { + panic(fmt.Errorf("proto3 declared messages do not support extensions: cosmos.base.node.v1beta1.StatusRequest")) + } + panic(fmt.Errorf("message cosmos.base.node.v1beta1.StatusRequest does not contain field %s", fd.FullName())) + } +} + +// Get retrieves the value for a field. +// +// For unpopulated scalars, it returns the default value, where +// the default value of a bytes scalar is guaranteed to be a copy. +// For unpopulated composite types, it returns an empty, read-only view +// of the value; to obtain a mutable reference, use Mutable. +func (x *fastReflection_StatusRequest) Get(descriptor protoreflect.FieldDescriptor) protoreflect.Value { + switch descriptor.FullName() { + default: + if descriptor.IsExtension() { + panic(fmt.Errorf("proto3 declared messages do not support extensions: cosmos.base.node.v1beta1.StatusRequest")) + } + panic(fmt.Errorf("message cosmos.base.node.v1beta1.StatusRequest does not contain field %s", descriptor.FullName())) + } +} + +// Set stores the value for a field. +// +// For a field belonging to a oneof, it implicitly clears any other field +// that may be currently set within the same oneof. +// For extension fields, it implicitly stores the provided ExtensionType. +// When setting a composite type, it is unspecified whether the stored value +// aliases the source's memory in any way. If the composite value is an +// empty, read-only value, then it panics. +// +// Set is a mutating operation and unsafe for concurrent use. +func (x *fastReflection_StatusRequest) Set(fd protoreflect.FieldDescriptor, value protoreflect.Value) { + switch fd.FullName() { + default: + if fd.IsExtension() { + panic(fmt.Errorf("proto3 declared messages do not support extensions: cosmos.base.node.v1beta1.StatusRequest")) + } + panic(fmt.Errorf("message cosmos.base.node.v1beta1.StatusRequest does not contain field %s", fd.FullName())) + } +} + +// Mutable returns a mutable reference to a composite type. +// +// If the field is unpopulated, it may allocate a composite value. +// For a field belonging to a oneof, it implicitly clears any other field +// that may be currently set within the same oneof. +// For extension fields, it implicitly stores the provided ExtensionType +// if not already stored. +// It panics if the field does not contain a composite type. +// +// Mutable is a mutating operation and unsafe for concurrent use. +func (x *fastReflection_StatusRequest) Mutable(fd protoreflect.FieldDescriptor) protoreflect.Value { + switch fd.FullName() { + default: + if fd.IsExtension() { + panic(fmt.Errorf("proto3 declared messages do not support extensions: cosmos.base.node.v1beta1.StatusRequest")) + } + panic(fmt.Errorf("message cosmos.base.node.v1beta1.StatusRequest does not contain field %s", fd.FullName())) + } +} + +// NewField returns a new value that is assignable to the field +// for the given descriptor. For scalars, this returns the default value. +// For lists, maps, and messages, this returns a new, empty, mutable value. +func (x *fastReflection_StatusRequest) NewField(fd protoreflect.FieldDescriptor) protoreflect.Value { + switch fd.FullName() { + default: + if fd.IsExtension() { + panic(fmt.Errorf("proto3 declared messages do not support extensions: cosmos.base.node.v1beta1.StatusRequest")) + } + panic(fmt.Errorf("message cosmos.base.node.v1beta1.StatusRequest does not contain field %s", fd.FullName())) + } +} + +// WhichOneof reports which field within the oneof is populated, +// returning nil if none are populated. +// It panics if the oneof descriptor does not belong to this message. +func (x *fastReflection_StatusRequest) WhichOneof(d protoreflect.OneofDescriptor) protoreflect.FieldDescriptor { + switch d.FullName() { + default: + panic(fmt.Errorf("%s is not a oneof field in cosmos.base.node.v1beta1.StatusRequest", d.FullName())) + } + panic("unreachable") +} + +// GetUnknown retrieves the entire list of unknown fields. +// The caller may only mutate the contents of the RawFields +// if the mutated bytes are stored back into the message with SetUnknown. +func (x *fastReflection_StatusRequest) GetUnknown() protoreflect.RawFields { + return x.unknownFields +} + +// SetUnknown stores an entire list of unknown fields. +// The raw fields must be syntactically valid according to the wire format. +// An implementation may panic if this is not the case. +// Once stored, the caller must not mutate the content of the RawFields. +// An empty RawFields may be passed to clear the fields. +// +// SetUnknown is a mutating operation and unsafe for concurrent use. +func (x *fastReflection_StatusRequest) SetUnknown(fields protoreflect.RawFields) { + x.unknownFields = fields +} + +// IsValid reports whether the message is valid. +// +// An invalid message is an empty, read-only value. +// +// An invalid message often corresponds to a nil pointer of the concrete +// message type, but the details are implementation dependent. +// Validity is not part of the protobuf data model, and may not +// be preserved in marshaling or other operations. +func (x *fastReflection_StatusRequest) IsValid() bool { + return x != nil +} + +// ProtoMethods returns optional fastReflectionFeature-path implementations of various operations. +// This method may return nil. +// +// The returned methods type is identical to +// "google.golang.org/protobuf/runtime/protoiface".Methods. +// Consult the protoiface package documentation for details. +func (x *fastReflection_StatusRequest) ProtoMethods() *protoiface.Methods { + size := func(input protoiface.SizeInput) protoiface.SizeOutput { + x := input.Message.Interface().(*StatusRequest) + if x == nil { + return protoiface.SizeOutput{ + NoUnkeyedLiterals: input.NoUnkeyedLiterals, + Size: 0, + } + } + options := runtime.SizeInputToOptions(input) + _ = options + var n int + var l int + _ = l + if x.unknownFields != nil { + n += len(x.unknownFields) + } + return protoiface.SizeOutput{ + NoUnkeyedLiterals: input.NoUnkeyedLiterals, + Size: n, + } + } + + marshal := func(input protoiface.MarshalInput) (protoiface.MarshalOutput, error) { + x := input.Message.Interface().(*StatusRequest) + if x == nil { + return protoiface.MarshalOutput{ + NoUnkeyedLiterals: input.NoUnkeyedLiterals, + Buf: input.Buf, + }, nil + } + options := runtime.MarshalInputToOptions(input) + _ = options + size := options.Size(x) + dAtA := make([]byte, size) + i := len(dAtA) + _ = i + var l int + _ = l + if x.unknownFields != nil { + i -= len(x.unknownFields) + copy(dAtA[i:], x.unknownFields) + } + if input.Buf != nil { + input.Buf = append(input.Buf, dAtA...) + } else { + input.Buf = dAtA + } + return protoiface.MarshalOutput{ + NoUnkeyedLiterals: input.NoUnkeyedLiterals, + Buf: input.Buf, + }, nil + } + unmarshal := func(input protoiface.UnmarshalInput) (protoiface.UnmarshalOutput, error) { + x := input.Message.Interface().(*StatusRequest) + if x == nil { + return protoiface.UnmarshalOutput{ + NoUnkeyedLiterals: input.NoUnkeyedLiterals, + Flags: input.Flags, + }, nil + } + options := runtime.UnmarshalInputToOptions(input) + _ = options + dAtA := input.Buf + l := len(dAtA) + iNdEx := 0 + for iNdEx < l { + preIndex := iNdEx + var wire uint64 + for shift := uint(0); ; shift += 7 { + if shift >= 64 { + return protoiface.UnmarshalOutput{NoUnkeyedLiterals: input.NoUnkeyedLiterals, Flags: input.Flags}, runtime.ErrIntOverflow + } + if iNdEx >= l { + return protoiface.UnmarshalOutput{NoUnkeyedLiterals: input.NoUnkeyedLiterals, Flags: input.Flags}, io.ErrUnexpectedEOF + } + b := dAtA[iNdEx] + iNdEx++ + wire |= uint64(b&0x7F) << shift + if b < 0x80 { + break + } + } + fieldNum := int32(wire >> 3) + wireType := int(wire & 0x7) + if wireType == 4 { + return protoiface.UnmarshalOutput{NoUnkeyedLiterals: input.NoUnkeyedLiterals, Flags: input.Flags}, fmt.Errorf("proto: StatusRequest: wiretype end group for non-group") + } + if fieldNum <= 0 { + return protoiface.UnmarshalOutput{NoUnkeyedLiterals: input.NoUnkeyedLiterals, Flags: input.Flags}, fmt.Errorf("proto: StatusRequest: illegal tag %d (wire type %d)", fieldNum, wire) + } + switch fieldNum { + default: + iNdEx = preIndex + skippy, err := runtime.Skip(dAtA[iNdEx:]) + if err != nil { + return protoiface.UnmarshalOutput{NoUnkeyedLiterals: input.NoUnkeyedLiterals, Flags: input.Flags}, err + } + if (skippy < 0) || (iNdEx+skippy) < 0 { + return protoiface.UnmarshalOutput{NoUnkeyedLiterals: input.NoUnkeyedLiterals, Flags: input.Flags}, runtime.ErrInvalidLength + } + if (iNdEx + skippy) > l { + return protoiface.UnmarshalOutput{NoUnkeyedLiterals: input.NoUnkeyedLiterals, Flags: input.Flags}, io.ErrUnexpectedEOF + } + if !options.DiscardUnknown { + x.unknownFields = append(x.unknownFields, dAtA[iNdEx:iNdEx+skippy]...) + } + iNdEx += skippy + } + } + + if iNdEx > l { + return protoiface.UnmarshalOutput{NoUnkeyedLiterals: input.NoUnkeyedLiterals, Flags: input.Flags}, io.ErrUnexpectedEOF + } + return protoiface.UnmarshalOutput{NoUnkeyedLiterals: input.NoUnkeyedLiterals, Flags: input.Flags}, nil + } + return &protoiface.Methods{ + NoUnkeyedLiterals: struct{}{}, + Flags: protoiface.SupportMarshalDeterministic | protoiface.SupportUnmarshalDiscardUnknown, + Size: size, + Marshal: marshal, + Unmarshal: unmarshal, + Merge: nil, + CheckInitialized: nil, + } +} + +var ( + md_StatusResponse protoreflect.MessageDescriptor + fd_StatusResponse_earliest_store_height protoreflect.FieldDescriptor + fd_StatusResponse_height protoreflect.FieldDescriptor + fd_StatusResponse_timestamp protoreflect.FieldDescriptor + fd_StatusResponse_app_hash protoreflect.FieldDescriptor + fd_StatusResponse_validator_hash protoreflect.FieldDescriptor +) + +func init() { + file_cosmos_base_node_v1beta1_query_proto_init() + md_StatusResponse = File_cosmos_base_node_v1beta1_query_proto.Messages().ByName("StatusResponse") + fd_StatusResponse_earliest_store_height = md_StatusResponse.Fields().ByName("earliest_store_height") + fd_StatusResponse_height = md_StatusResponse.Fields().ByName("height") + fd_StatusResponse_timestamp = md_StatusResponse.Fields().ByName("timestamp") + fd_StatusResponse_app_hash = md_StatusResponse.Fields().ByName("app_hash") + fd_StatusResponse_validator_hash = md_StatusResponse.Fields().ByName("validator_hash") +} + +var _ protoreflect.Message = (*fastReflection_StatusResponse)(nil) + +type fastReflection_StatusResponse StatusResponse + +func (x *StatusResponse) ProtoReflect() protoreflect.Message { + return (*fastReflection_StatusResponse)(x) +} + +func (x *StatusResponse) slowProtoReflect() protoreflect.Message { + mi := &file_cosmos_base_node_v1beta1_query_proto_msgTypes[3] + if protoimpl.UnsafeEnabled && x != nil { + ms := protoimpl.X.MessageStateOf(protoimpl.Pointer(x)) + if ms.LoadMessageInfo() == nil { + ms.StoreMessageInfo(mi) + } + return ms + } + return mi.MessageOf(x) +} + +var _fastReflection_StatusResponse_messageType fastReflection_StatusResponse_messageType +var _ protoreflect.MessageType = fastReflection_StatusResponse_messageType{} + +type fastReflection_StatusResponse_messageType struct{} + +func (x fastReflection_StatusResponse_messageType) Zero() protoreflect.Message { + return (*fastReflection_StatusResponse)(nil) +} +func (x fastReflection_StatusResponse_messageType) New() protoreflect.Message { + return new(fastReflection_StatusResponse) +} +func (x fastReflection_StatusResponse_messageType) Descriptor() protoreflect.MessageDescriptor { + return md_StatusResponse +} + +// Descriptor returns message descriptor, which contains only the protobuf +// type information for the message. +func (x *fastReflection_StatusResponse) Descriptor() protoreflect.MessageDescriptor { + return md_StatusResponse +} + +// Type returns the message type, which encapsulates both Go and protobuf +// type information. If the Go type information is not needed, +// it is recommended that the message descriptor be used instead. +func (x *fastReflection_StatusResponse) Type() protoreflect.MessageType { + return _fastReflection_StatusResponse_messageType +} + +// New returns a newly allocated and mutable empty message. +func (x *fastReflection_StatusResponse) New() protoreflect.Message { + return new(fastReflection_StatusResponse) +} + +// Interface unwraps the message reflection interface and +// returns the underlying ProtoMessage interface. +func (x *fastReflection_StatusResponse) Interface() protoreflect.ProtoMessage { + return (*StatusResponse)(x) +} + +// Range iterates over every populated field in an undefined order, +// calling f for each field descriptor and value encountered. +// Range returns immediately if f returns false. +// While iterating, mutating operations may only be performed +// on the current field descriptor. +func (x *fastReflection_StatusResponse) Range(f func(protoreflect.FieldDescriptor, protoreflect.Value) bool) { + if x.EarliestStoreHeight != uint64(0) { + value := protoreflect.ValueOfUint64(x.EarliestStoreHeight) + if !f(fd_StatusResponse_earliest_store_height, value) { + return + } + } + if x.Height != uint64(0) { + value := protoreflect.ValueOfUint64(x.Height) + if !f(fd_StatusResponse_height, value) { + return + } + } + if x.Timestamp != nil { + value := protoreflect.ValueOfMessage(x.Timestamp.ProtoReflect()) + if !f(fd_StatusResponse_timestamp, value) { + return + } + } + if len(x.AppHash) != 0 { + value := protoreflect.ValueOfBytes(x.AppHash) + if !f(fd_StatusResponse_app_hash, value) { + return + } + } + if len(x.ValidatorHash) != 0 { + value := protoreflect.ValueOfBytes(x.ValidatorHash) + if !f(fd_StatusResponse_validator_hash, value) { + return + } + } } // Has reports whether a field is populated. @@ -464,15 +1402,23 @@ func (x *fastReflection_ConfigResponse) Range(f func(protoreflect.FieldDescripto // In other cases (aside from the nullable cases above), // a proto3 scalar field is populated if it contains a non-zero value, and // a repeated field is populated if it is non-empty. -func (x *fastReflection_ConfigResponse) Has(fd protoreflect.FieldDescriptor) bool { +func (x *fastReflection_StatusResponse) Has(fd protoreflect.FieldDescriptor) bool { switch fd.FullName() { - case "cosmos.base.node.v1beta1.ConfigResponse.minimum_gas_price": - return x.MinimumGasPrice != "" + case "cosmos.base.node.v1beta1.StatusResponse.earliest_store_height": + return x.EarliestStoreHeight != uint64(0) + case "cosmos.base.node.v1beta1.StatusResponse.height": + return x.Height != uint64(0) + case "cosmos.base.node.v1beta1.StatusResponse.timestamp": + return x.Timestamp != nil + case "cosmos.base.node.v1beta1.StatusResponse.app_hash": + return len(x.AppHash) != 0 + case "cosmos.base.node.v1beta1.StatusResponse.validator_hash": + return len(x.ValidatorHash) != 0 default: if fd.IsExtension() { - panic(fmt.Errorf("proto3 declared messages do not support extensions: cosmos.base.node.v1beta1.ConfigResponse")) + panic(fmt.Errorf("proto3 declared messages do not support extensions: cosmos.base.node.v1beta1.StatusResponse")) } - panic(fmt.Errorf("message cosmos.base.node.v1beta1.ConfigResponse does not contain field %s", fd.FullName())) + panic(fmt.Errorf("message cosmos.base.node.v1beta1.StatusResponse does not contain field %s", fd.FullName())) } } @@ -482,15 +1428,23 @@ func (x *fastReflection_ConfigResponse) Has(fd protoreflect.FieldDescriptor) boo // associated with the given field number. // // Clear is a mutating operation and unsafe for concurrent use. -func (x *fastReflection_ConfigResponse) Clear(fd protoreflect.FieldDescriptor) { +func (x *fastReflection_StatusResponse) Clear(fd protoreflect.FieldDescriptor) { switch fd.FullName() { - case "cosmos.base.node.v1beta1.ConfigResponse.minimum_gas_price": - x.MinimumGasPrice = "" + case "cosmos.base.node.v1beta1.StatusResponse.earliest_store_height": + x.EarliestStoreHeight = uint64(0) + case "cosmos.base.node.v1beta1.StatusResponse.height": + x.Height = uint64(0) + case "cosmos.base.node.v1beta1.StatusResponse.timestamp": + x.Timestamp = nil + case "cosmos.base.node.v1beta1.StatusResponse.app_hash": + x.AppHash = nil + case "cosmos.base.node.v1beta1.StatusResponse.validator_hash": + x.ValidatorHash = nil default: if fd.IsExtension() { - panic(fmt.Errorf("proto3 declared messages do not support extensions: cosmos.base.node.v1beta1.ConfigResponse")) + panic(fmt.Errorf("proto3 declared messages do not support extensions: cosmos.base.node.v1beta1.StatusResponse")) } - panic(fmt.Errorf("message cosmos.base.node.v1beta1.ConfigResponse does not contain field %s", fd.FullName())) + panic(fmt.Errorf("message cosmos.base.node.v1beta1.StatusResponse does not contain field %s", fd.FullName())) } } @@ -500,16 +1454,28 @@ func (x *fastReflection_ConfigResponse) Clear(fd protoreflect.FieldDescriptor) { // the default value of a bytes scalar is guaranteed to be a copy. // For unpopulated composite types, it returns an empty, read-only view // of the value; to obtain a mutable reference, use Mutable. -func (x *fastReflection_ConfigResponse) Get(descriptor protoreflect.FieldDescriptor) protoreflect.Value { +func (x *fastReflection_StatusResponse) Get(descriptor protoreflect.FieldDescriptor) protoreflect.Value { switch descriptor.FullName() { - case "cosmos.base.node.v1beta1.ConfigResponse.minimum_gas_price": - value := x.MinimumGasPrice - return protoreflect.ValueOfString(value) + case "cosmos.base.node.v1beta1.StatusResponse.earliest_store_height": + value := x.EarliestStoreHeight + return protoreflect.ValueOfUint64(value) + case "cosmos.base.node.v1beta1.StatusResponse.height": + value := x.Height + return protoreflect.ValueOfUint64(value) + case "cosmos.base.node.v1beta1.StatusResponse.timestamp": + value := x.Timestamp + return protoreflect.ValueOfMessage(value.ProtoReflect()) + case "cosmos.base.node.v1beta1.StatusResponse.app_hash": + value := x.AppHash + return protoreflect.ValueOfBytes(value) + case "cosmos.base.node.v1beta1.StatusResponse.validator_hash": + value := x.ValidatorHash + return protoreflect.ValueOfBytes(value) default: if descriptor.IsExtension() { - panic(fmt.Errorf("proto3 declared messages do not support extensions: cosmos.base.node.v1beta1.ConfigResponse")) + panic(fmt.Errorf("proto3 declared messages do not support extensions: cosmos.base.node.v1beta1.StatusResponse")) } - panic(fmt.Errorf("message cosmos.base.node.v1beta1.ConfigResponse does not contain field %s", descriptor.FullName())) + panic(fmt.Errorf("message cosmos.base.node.v1beta1.StatusResponse does not contain field %s", descriptor.FullName())) } } @@ -523,15 +1489,23 @@ func (x *fastReflection_ConfigResponse) Get(descriptor protoreflect.FieldDescrip // empty, read-only value, then it panics. // // Set is a mutating operation and unsafe for concurrent use. -func (x *fastReflection_ConfigResponse) Set(fd protoreflect.FieldDescriptor, value protoreflect.Value) { +func (x *fastReflection_StatusResponse) Set(fd protoreflect.FieldDescriptor, value protoreflect.Value) { switch fd.FullName() { - case "cosmos.base.node.v1beta1.ConfigResponse.minimum_gas_price": - x.MinimumGasPrice = value.Interface().(string) + case "cosmos.base.node.v1beta1.StatusResponse.earliest_store_height": + x.EarliestStoreHeight = value.Uint() + case "cosmos.base.node.v1beta1.StatusResponse.height": + x.Height = value.Uint() + case "cosmos.base.node.v1beta1.StatusResponse.timestamp": + x.Timestamp = value.Message().Interface().(*timestamppb.Timestamp) + case "cosmos.base.node.v1beta1.StatusResponse.app_hash": + x.AppHash = value.Bytes() + case "cosmos.base.node.v1beta1.StatusResponse.validator_hash": + x.ValidatorHash = value.Bytes() default: if fd.IsExtension() { - panic(fmt.Errorf("proto3 declared messages do not support extensions: cosmos.base.node.v1beta1.ConfigResponse")) + panic(fmt.Errorf("proto3 declared messages do not support extensions: cosmos.base.node.v1beta1.StatusResponse")) } - panic(fmt.Errorf("message cosmos.base.node.v1beta1.ConfigResponse does not contain field %s", fd.FullName())) + panic(fmt.Errorf("message cosmos.base.node.v1beta1.StatusResponse does not contain field %s", fd.FullName())) } } @@ -545,40 +1519,60 @@ func (x *fastReflection_ConfigResponse) Set(fd protoreflect.FieldDescriptor, val // It panics if the field does not contain a composite type. // // Mutable is a mutating operation and unsafe for concurrent use. -func (x *fastReflection_ConfigResponse) Mutable(fd protoreflect.FieldDescriptor) protoreflect.Value { +func (x *fastReflection_StatusResponse) Mutable(fd protoreflect.FieldDescriptor) protoreflect.Value { switch fd.FullName() { - case "cosmos.base.node.v1beta1.ConfigResponse.minimum_gas_price": - panic(fmt.Errorf("field minimum_gas_price of message cosmos.base.node.v1beta1.ConfigResponse is not mutable")) + case "cosmos.base.node.v1beta1.StatusResponse.timestamp": + if x.Timestamp == nil { + x.Timestamp = new(timestamppb.Timestamp) + } + return protoreflect.ValueOfMessage(x.Timestamp.ProtoReflect()) + case "cosmos.base.node.v1beta1.StatusResponse.earliest_store_height": + panic(fmt.Errorf("field earliest_store_height of message cosmos.base.node.v1beta1.StatusResponse is not mutable")) + case "cosmos.base.node.v1beta1.StatusResponse.height": + panic(fmt.Errorf("field height of message cosmos.base.node.v1beta1.StatusResponse is not mutable")) + case "cosmos.base.node.v1beta1.StatusResponse.app_hash": + panic(fmt.Errorf("field app_hash of message cosmos.base.node.v1beta1.StatusResponse is not mutable")) + case "cosmos.base.node.v1beta1.StatusResponse.validator_hash": + panic(fmt.Errorf("field validator_hash of message cosmos.base.node.v1beta1.StatusResponse is not mutable")) default: if fd.IsExtension() { - panic(fmt.Errorf("proto3 declared messages do not support extensions: cosmos.base.node.v1beta1.ConfigResponse")) + panic(fmt.Errorf("proto3 declared messages do not support extensions: cosmos.base.node.v1beta1.StatusResponse")) } - panic(fmt.Errorf("message cosmos.base.node.v1beta1.ConfigResponse does not contain field %s", fd.FullName())) + panic(fmt.Errorf("message cosmos.base.node.v1beta1.StatusResponse does not contain field %s", fd.FullName())) } } // NewField returns a new value that is assignable to the field // for the given descriptor. For scalars, this returns the default value. // For lists, maps, and messages, this returns a new, empty, mutable value. -func (x *fastReflection_ConfigResponse) NewField(fd protoreflect.FieldDescriptor) protoreflect.Value { +func (x *fastReflection_StatusResponse) NewField(fd protoreflect.FieldDescriptor) protoreflect.Value { switch fd.FullName() { - case "cosmos.base.node.v1beta1.ConfigResponse.minimum_gas_price": - return protoreflect.ValueOfString("") + case "cosmos.base.node.v1beta1.StatusResponse.earliest_store_height": + return protoreflect.ValueOfUint64(uint64(0)) + case "cosmos.base.node.v1beta1.StatusResponse.height": + return protoreflect.ValueOfUint64(uint64(0)) + case "cosmos.base.node.v1beta1.StatusResponse.timestamp": + m := new(timestamppb.Timestamp) + return protoreflect.ValueOfMessage(m.ProtoReflect()) + case "cosmos.base.node.v1beta1.StatusResponse.app_hash": + return protoreflect.ValueOfBytes(nil) + case "cosmos.base.node.v1beta1.StatusResponse.validator_hash": + return protoreflect.ValueOfBytes(nil) default: if fd.IsExtension() { - panic(fmt.Errorf("proto3 declared messages do not support extensions: cosmos.base.node.v1beta1.ConfigResponse")) + panic(fmt.Errorf("proto3 declared messages do not support extensions: cosmos.base.node.v1beta1.StatusResponse")) } - panic(fmt.Errorf("message cosmos.base.node.v1beta1.ConfigResponse does not contain field %s", fd.FullName())) + panic(fmt.Errorf("message cosmos.base.node.v1beta1.StatusResponse does not contain field %s", fd.FullName())) } } // WhichOneof reports which field within the oneof is populated, // returning nil if none are populated. // It panics if the oneof descriptor does not belong to this message. -func (x *fastReflection_ConfigResponse) WhichOneof(d protoreflect.OneofDescriptor) protoreflect.FieldDescriptor { +func (x *fastReflection_StatusResponse) WhichOneof(d protoreflect.OneofDescriptor) protoreflect.FieldDescriptor { switch d.FullName() { default: - panic(fmt.Errorf("%s is not a oneof field in cosmos.base.node.v1beta1.ConfigResponse", d.FullName())) + panic(fmt.Errorf("%s is not a oneof field in cosmos.base.node.v1beta1.StatusResponse", d.FullName())) } panic("unreachable") } @@ -586,7 +1580,7 @@ func (x *fastReflection_ConfigResponse) WhichOneof(d protoreflect.OneofDescripto // GetUnknown retrieves the entire list of unknown fields. // The caller may only mutate the contents of the RawFields // if the mutated bytes are stored back into the message with SetUnknown. -func (x *fastReflection_ConfigResponse) GetUnknown() protoreflect.RawFields { +func (x *fastReflection_StatusResponse) GetUnknown() protoreflect.RawFields { return x.unknownFields } @@ -597,7 +1591,7 @@ func (x *fastReflection_ConfigResponse) GetUnknown() protoreflect.RawFields { // An empty RawFields may be passed to clear the fields. // // SetUnknown is a mutating operation and unsafe for concurrent use. -func (x *fastReflection_ConfigResponse) SetUnknown(fields protoreflect.RawFields) { +func (x *fastReflection_StatusResponse) SetUnknown(fields protoreflect.RawFields) { x.unknownFields = fields } @@ -609,7 +1603,7 @@ func (x *fastReflection_ConfigResponse) SetUnknown(fields protoreflect.RawFields // message type, but the details are implementation dependent. // Validity is not part of the protobuf data model, and may not // be preserved in marshaling or other operations. -func (x *fastReflection_ConfigResponse) IsValid() bool { +func (x *fastReflection_StatusResponse) IsValid() bool { return x != nil } @@ -619,9 +1613,9 @@ func (x *fastReflection_ConfigResponse) IsValid() bool { // The returned methods type is identical to // "google.golang.org/protobuf/runtime/protoiface".Methods. // Consult the protoiface package documentation for details. -func (x *fastReflection_ConfigResponse) ProtoMethods() *protoiface.Methods { +func (x *fastReflection_StatusResponse) ProtoMethods() *protoiface.Methods { size := func(input protoiface.SizeInput) protoiface.SizeOutput { - x := input.Message.Interface().(*ConfigResponse) + x := input.Message.Interface().(*StatusResponse) if x == nil { return protoiface.SizeOutput{ NoUnkeyedLiterals: input.NoUnkeyedLiterals, @@ -633,7 +1627,21 @@ func (x *fastReflection_ConfigResponse) ProtoMethods() *protoiface.Methods { var n int var l int _ = l - l = len(x.MinimumGasPrice) + if x.EarliestStoreHeight != 0 { + n += 1 + runtime.Sov(uint64(x.EarliestStoreHeight)) + } + if x.Height != 0 { + n += 1 + runtime.Sov(uint64(x.Height)) + } + if x.Timestamp != nil { + l = options.Size(x.Timestamp) + n += 1 + l + runtime.Sov(uint64(l)) + } + l = len(x.AppHash) + if l > 0 { + n += 1 + l + runtime.Sov(uint64(l)) + } + l = len(x.ValidatorHash) if l > 0 { n += 1 + l + runtime.Sov(uint64(l)) } @@ -647,7 +1655,7 @@ func (x *fastReflection_ConfigResponse) ProtoMethods() *protoiface.Methods { } marshal := func(input protoiface.MarshalInput) (protoiface.MarshalOutput, error) { - x := input.Message.Interface().(*ConfigResponse) + x := input.Message.Interface().(*StatusResponse) if x == nil { return protoiface.MarshalOutput{ NoUnkeyedLiterals: input.NoUnkeyedLiterals, @@ -666,12 +1674,43 @@ func (x *fastReflection_ConfigResponse) ProtoMethods() *protoiface.Methods { i -= len(x.unknownFields) copy(dAtA[i:], x.unknownFields) } - if len(x.MinimumGasPrice) > 0 { - i -= len(x.MinimumGasPrice) - copy(dAtA[i:], x.MinimumGasPrice) - i = runtime.EncodeVarint(dAtA, i, uint64(len(x.MinimumGasPrice))) + if len(x.ValidatorHash) > 0 { + i -= len(x.ValidatorHash) + copy(dAtA[i:], x.ValidatorHash) + i = runtime.EncodeVarint(dAtA, i, uint64(len(x.ValidatorHash))) i-- - dAtA[i] = 0xa + dAtA[i] = 0x2a + } + if len(x.AppHash) > 0 { + i -= len(x.AppHash) + copy(dAtA[i:], x.AppHash) + i = runtime.EncodeVarint(dAtA, i, uint64(len(x.AppHash))) + i-- + dAtA[i] = 0x22 + } + if x.Timestamp != nil { + encoded, err := options.Marshal(x.Timestamp) + if err != nil { + return protoiface.MarshalOutput{ + NoUnkeyedLiterals: input.NoUnkeyedLiterals, + Buf: input.Buf, + }, err + } + i -= len(encoded) + copy(dAtA[i:], encoded) + i = runtime.EncodeVarint(dAtA, i, uint64(len(encoded))) + i-- + dAtA[i] = 0x1a + } + if x.Height != 0 { + i = runtime.EncodeVarint(dAtA, i, uint64(x.Height)) + i-- + dAtA[i] = 0x10 + } + if x.EarliestStoreHeight != 0 { + i = runtime.EncodeVarint(dAtA, i, uint64(x.EarliestStoreHeight)) + i-- + dAtA[i] = 0x8 } if input.Buf != nil { input.Buf = append(input.Buf, dAtA...) @@ -684,7 +1723,7 @@ func (x *fastReflection_ConfigResponse) ProtoMethods() *protoiface.Methods { }, nil } unmarshal := func(input protoiface.UnmarshalInput) (protoiface.UnmarshalOutput, error) { - x := input.Message.Interface().(*ConfigResponse) + x := input.Message.Interface().(*StatusResponse) if x == nil { return protoiface.UnmarshalOutput{ NoUnkeyedLiterals: input.NoUnkeyedLiterals, @@ -716,17 +1755,55 @@ func (x *fastReflection_ConfigResponse) ProtoMethods() *protoiface.Methods { fieldNum := int32(wire >> 3) wireType := int(wire & 0x7) if wireType == 4 { - return protoiface.UnmarshalOutput{NoUnkeyedLiterals: input.NoUnkeyedLiterals, Flags: input.Flags}, fmt.Errorf("proto: ConfigResponse: wiretype end group for non-group") + return protoiface.UnmarshalOutput{NoUnkeyedLiterals: input.NoUnkeyedLiterals, Flags: input.Flags}, fmt.Errorf("proto: StatusResponse: wiretype end group for non-group") } if fieldNum <= 0 { - return protoiface.UnmarshalOutput{NoUnkeyedLiterals: input.NoUnkeyedLiterals, Flags: input.Flags}, fmt.Errorf("proto: ConfigResponse: illegal tag %d (wire type %d)", fieldNum, wire) + return protoiface.UnmarshalOutput{NoUnkeyedLiterals: input.NoUnkeyedLiterals, Flags: input.Flags}, fmt.Errorf("proto: StatusResponse: illegal tag %d (wire type %d)", fieldNum, wire) } switch fieldNum { case 1: + if wireType != 0 { + return protoiface.UnmarshalOutput{NoUnkeyedLiterals: input.NoUnkeyedLiterals, Flags: input.Flags}, fmt.Errorf("proto: wrong wireType = %d for field EarliestStoreHeight", wireType) + } + x.EarliestStoreHeight = 0 + for shift := uint(0); ; shift += 7 { + if shift >= 64 { + return protoiface.UnmarshalOutput{NoUnkeyedLiterals: input.NoUnkeyedLiterals, Flags: input.Flags}, runtime.ErrIntOverflow + } + if iNdEx >= l { + return protoiface.UnmarshalOutput{NoUnkeyedLiterals: input.NoUnkeyedLiterals, Flags: input.Flags}, io.ErrUnexpectedEOF + } + b := dAtA[iNdEx] + iNdEx++ + x.EarliestStoreHeight |= uint64(b&0x7F) << shift + if b < 0x80 { + break + } + } + case 2: + if wireType != 0 { + return protoiface.UnmarshalOutput{NoUnkeyedLiterals: input.NoUnkeyedLiterals, Flags: input.Flags}, fmt.Errorf("proto: wrong wireType = %d for field Height", wireType) + } + x.Height = 0 + for shift := uint(0); ; shift += 7 { + if shift >= 64 { + return protoiface.UnmarshalOutput{NoUnkeyedLiterals: input.NoUnkeyedLiterals, Flags: input.Flags}, runtime.ErrIntOverflow + } + if iNdEx >= l { + return protoiface.UnmarshalOutput{NoUnkeyedLiterals: input.NoUnkeyedLiterals, Flags: input.Flags}, io.ErrUnexpectedEOF + } + b := dAtA[iNdEx] + iNdEx++ + x.Height |= uint64(b&0x7F) << shift + if b < 0x80 { + break + } + } + case 3: if wireType != 2 { - return protoiface.UnmarshalOutput{NoUnkeyedLiterals: input.NoUnkeyedLiterals, Flags: input.Flags}, fmt.Errorf("proto: wrong wireType = %d for field MinimumGasPrice", wireType) + return protoiface.UnmarshalOutput{NoUnkeyedLiterals: input.NoUnkeyedLiterals, Flags: input.Flags}, fmt.Errorf("proto: wrong wireType = %d for field Timestamp", wireType) } - var stringLen uint64 + var msglen int for shift := uint(0); ; shift += 7 { if shift >= 64 { return protoiface.UnmarshalOutput{NoUnkeyedLiterals: input.NoUnkeyedLiterals, Flags: input.Flags}, runtime.ErrIntOverflow @@ -736,23 +1813,95 @@ func (x *fastReflection_ConfigResponse) ProtoMethods() *protoiface.Methods { } b := dAtA[iNdEx] iNdEx++ - stringLen |= uint64(b&0x7F) << shift + msglen |= int(b&0x7F) << shift if b < 0x80 { break } } - intStringLen := int(stringLen) - if intStringLen < 0 { + if msglen < 0 { return protoiface.UnmarshalOutput{NoUnkeyedLiterals: input.NoUnkeyedLiterals, Flags: input.Flags}, runtime.ErrInvalidLength } - postIndex := iNdEx + intStringLen + postIndex := iNdEx + msglen if postIndex < 0 { return protoiface.UnmarshalOutput{NoUnkeyedLiterals: input.NoUnkeyedLiterals, Flags: input.Flags}, runtime.ErrInvalidLength } if postIndex > l { return protoiface.UnmarshalOutput{NoUnkeyedLiterals: input.NoUnkeyedLiterals, Flags: input.Flags}, io.ErrUnexpectedEOF } - x.MinimumGasPrice = string(dAtA[iNdEx:postIndex]) + if x.Timestamp == nil { + x.Timestamp = ×tamppb.Timestamp{} + } + if err := options.Unmarshal(dAtA[iNdEx:postIndex], x.Timestamp); err != nil { + return protoiface.UnmarshalOutput{NoUnkeyedLiterals: input.NoUnkeyedLiterals, Flags: input.Flags}, err + } + iNdEx = postIndex + case 4: + if wireType != 2 { + return protoiface.UnmarshalOutput{NoUnkeyedLiterals: input.NoUnkeyedLiterals, Flags: input.Flags}, fmt.Errorf("proto: wrong wireType = %d for field AppHash", wireType) + } + var byteLen int + for shift := uint(0); ; shift += 7 { + if shift >= 64 { + return protoiface.UnmarshalOutput{NoUnkeyedLiterals: input.NoUnkeyedLiterals, Flags: input.Flags}, runtime.ErrIntOverflow + } + if iNdEx >= l { + return protoiface.UnmarshalOutput{NoUnkeyedLiterals: input.NoUnkeyedLiterals, Flags: input.Flags}, io.ErrUnexpectedEOF + } + b := dAtA[iNdEx] + iNdEx++ + byteLen |= int(b&0x7F) << shift + if b < 0x80 { + break + } + } + if byteLen < 0 { + return protoiface.UnmarshalOutput{NoUnkeyedLiterals: input.NoUnkeyedLiterals, Flags: input.Flags}, runtime.ErrInvalidLength + } + postIndex := iNdEx + byteLen + if postIndex < 0 { + return protoiface.UnmarshalOutput{NoUnkeyedLiterals: input.NoUnkeyedLiterals, Flags: input.Flags}, runtime.ErrInvalidLength + } + if postIndex > l { + return protoiface.UnmarshalOutput{NoUnkeyedLiterals: input.NoUnkeyedLiterals, Flags: input.Flags}, io.ErrUnexpectedEOF + } + x.AppHash = append(x.AppHash[:0], dAtA[iNdEx:postIndex]...) + if x.AppHash == nil { + x.AppHash = []byte{} + } + iNdEx = postIndex + case 5: + if wireType != 2 { + return protoiface.UnmarshalOutput{NoUnkeyedLiterals: input.NoUnkeyedLiterals, Flags: input.Flags}, fmt.Errorf("proto: wrong wireType = %d for field ValidatorHash", wireType) + } + var byteLen int + for shift := uint(0); ; shift += 7 { + if shift >= 64 { + return protoiface.UnmarshalOutput{NoUnkeyedLiterals: input.NoUnkeyedLiterals, Flags: input.Flags}, runtime.ErrIntOverflow + } + if iNdEx >= l { + return protoiface.UnmarshalOutput{NoUnkeyedLiterals: input.NoUnkeyedLiterals, Flags: input.Flags}, io.ErrUnexpectedEOF + } + b := dAtA[iNdEx] + iNdEx++ + byteLen |= int(b&0x7F) << shift + if b < 0x80 { + break + } + } + if byteLen < 0 { + return protoiface.UnmarshalOutput{NoUnkeyedLiterals: input.NoUnkeyedLiterals, Flags: input.Flags}, runtime.ErrInvalidLength + } + postIndex := iNdEx + byteLen + if postIndex < 0 { + return protoiface.UnmarshalOutput{NoUnkeyedLiterals: input.NoUnkeyedLiterals, Flags: input.Flags}, runtime.ErrInvalidLength + } + if postIndex > l { + return protoiface.UnmarshalOutput{NoUnkeyedLiterals: input.NoUnkeyedLiterals, Flags: input.Flags}, io.ErrUnexpectedEOF + } + x.ValidatorHash = append(x.ValidatorHash[:0], dAtA[iNdEx:postIndex]...) + if x.ValidatorHash == nil { + x.ValidatorHash = []byte{} + } iNdEx = postIndex default: iNdEx = preIndex @@ -836,6 +1985,9 @@ type ConfigResponse struct { unknownFields protoimpl.UnknownFields MinimumGasPrice string `protobuf:"bytes,1,opt,name=minimum_gas_price,json=minimumGasPrice,proto3" json:"minimum_gas_price,omitempty"` + // pruning settings + PruningKeepRecent string `protobuf:"bytes,2,opt,name=pruning_keep_recent,json=pruningKeepRecent,proto3" json:"pruning_keep_recent,omitempty"` + PruningInterval string `protobuf:"bytes,3,opt,name=pruning_interval,json=pruningInterval,proto3" json:"pruning_interval,omitempty"` } func (x *ConfigResponse) Reset() { @@ -865,6 +2017,115 @@ func (x *ConfigResponse) GetMinimumGasPrice() string { return "" } +func (x *ConfigResponse) GetPruningKeepRecent() string { + if x != nil { + return x.PruningKeepRecent + } + return "" +} + +func (x *ConfigResponse) GetPruningInterval() string { + if x != nil { + return x.PruningInterval + } + return "" +} + +// StateRequest defines the request structure for the status of a node. +type StatusRequest struct { + state protoimpl.MessageState + sizeCache protoimpl.SizeCache + unknownFields protoimpl.UnknownFields +} + +func (x *StatusRequest) Reset() { + *x = StatusRequest{} + if protoimpl.UnsafeEnabled { + mi := &file_cosmos_base_node_v1beta1_query_proto_msgTypes[2] + ms := protoimpl.X.MessageStateOf(protoimpl.Pointer(x)) + ms.StoreMessageInfo(mi) + } +} + +func (x *StatusRequest) String() string { + return protoimpl.X.MessageStringOf(x) +} + +func (*StatusRequest) ProtoMessage() {} + +// Deprecated: Use StatusRequest.ProtoReflect.Descriptor instead. +func (*StatusRequest) Descriptor() ([]byte, []int) { + return file_cosmos_base_node_v1beta1_query_proto_rawDescGZIP(), []int{2} +} + +// StateResponse defines the response structure for the status of a node. +type StatusResponse struct { + state protoimpl.MessageState + sizeCache protoimpl.SizeCache + unknownFields protoimpl.UnknownFields + + EarliestStoreHeight uint64 `protobuf:"varint,1,opt,name=earliest_store_height,json=earliestStoreHeight,proto3" json:"earliest_store_height,omitempty"` // earliest block height available in the store + Height uint64 `protobuf:"varint,2,opt,name=height,proto3" json:"height,omitempty"` // current block height + Timestamp *timestamppb.Timestamp `protobuf:"bytes,3,opt,name=timestamp,proto3" json:"timestamp,omitempty"` // block height timestamp + AppHash []byte `protobuf:"bytes,4,opt,name=app_hash,json=appHash,proto3" json:"app_hash,omitempty"` // app hash of the current block + ValidatorHash []byte `protobuf:"bytes,5,opt,name=validator_hash,json=validatorHash,proto3" json:"validator_hash,omitempty"` // validator hash provided by the consensus header +} + +func (x *StatusResponse) Reset() { + *x = StatusResponse{} + if protoimpl.UnsafeEnabled { + mi := &file_cosmos_base_node_v1beta1_query_proto_msgTypes[3] + ms := protoimpl.X.MessageStateOf(protoimpl.Pointer(x)) + ms.StoreMessageInfo(mi) + } +} + +func (x *StatusResponse) String() string { + return protoimpl.X.MessageStringOf(x) +} + +func (*StatusResponse) ProtoMessage() {} + +// Deprecated: Use StatusResponse.ProtoReflect.Descriptor instead. +func (*StatusResponse) Descriptor() ([]byte, []int) { + return file_cosmos_base_node_v1beta1_query_proto_rawDescGZIP(), []int{3} +} + +func (x *StatusResponse) GetEarliestStoreHeight() uint64 { + if x != nil { + return x.EarliestStoreHeight + } + return 0 +} + +func (x *StatusResponse) GetHeight() uint64 { + if x != nil { + return x.Height + } + return 0 +} + +func (x *StatusResponse) GetTimestamp() *timestamppb.Timestamp { + if x != nil { + return x.Timestamp + } + return nil +} + +func (x *StatusResponse) GetAppHash() []byte { + if x != nil { + return x.AppHash + } + return nil +} + +func (x *StatusResponse) GetValidatorHash() []byte { + if x != nil { + return x.ValidatorHash + } + return nil +} + var File_cosmos_base_node_v1beta1_query_proto protoreflect.FileDescriptor var file_cosmos_base_node_v1beta1_query_proto_rawDesc = []byte{ @@ -873,36 +2134,69 @@ var file_cosmos_base_node_v1beta1_query_proto_rawDesc = []byte{ 0x2e, 0x70, 0x72, 0x6f, 0x74, 0x6f, 0x12, 0x18, 0x63, 0x6f, 0x73, 0x6d, 0x6f, 0x73, 0x2e, 0x62, 0x61, 0x73, 0x65, 0x2e, 0x6e, 0x6f, 0x64, 0x65, 0x2e, 0x76, 0x31, 0x62, 0x65, 0x74, 0x61, 0x31, 0x1a, 0x1c, 0x67, 0x6f, 0x6f, 0x67, 0x6c, 0x65, 0x2f, 0x61, 0x70, 0x69, 0x2f, 0x61, 0x6e, 0x6e, - 0x6f, 0x74, 0x61, 0x74, 0x69, 0x6f, 0x6e, 0x73, 0x2e, 0x70, 0x72, 0x6f, 0x74, 0x6f, 0x22, 0x0f, - 0x0a, 0x0d, 0x43, 0x6f, 0x6e, 0x66, 0x69, 0x67, 0x52, 0x65, 0x71, 0x75, 0x65, 0x73, 0x74, 0x22, - 0x3c, 0x0a, 0x0e, 0x43, 0x6f, 0x6e, 0x66, 0x69, 0x67, 0x52, 0x65, 0x73, 0x70, 0x6f, 0x6e, 0x73, - 0x65, 0x12, 0x2a, 0x0a, 0x11, 0x6d, 0x69, 0x6e, 0x69, 0x6d, 0x75, 0x6d, 0x5f, 0x67, 0x61, 0x73, - 0x5f, 0x70, 0x72, 0x69, 0x63, 0x65, 0x18, 0x01, 0x20, 0x01, 0x28, 0x09, 0x52, 0x0f, 0x6d, 0x69, - 0x6e, 0x69, 0x6d, 0x75, 0x6d, 0x47, 0x61, 0x73, 0x50, 0x72, 0x69, 0x63, 0x65, 0x32, 0x91, 0x01, - 0x0a, 0x07, 0x53, 0x65, 0x72, 0x76, 0x69, 0x63, 0x65, 0x12, 0x85, 0x01, 0x0a, 0x06, 0x43, 0x6f, - 0x6e, 0x66, 0x69, 0x67, 0x12, 0x27, 0x2e, 0x63, 0x6f, 0x73, 0x6d, 0x6f, 0x73, 0x2e, 0x62, 0x61, - 0x73, 0x65, 0x2e, 0x6e, 0x6f, 0x64, 0x65, 0x2e, 0x76, 0x31, 0x62, 0x65, 0x74, 0x61, 0x31, 0x2e, - 0x43, 0x6f, 0x6e, 0x66, 0x69, 0x67, 0x52, 0x65, 0x71, 0x75, 0x65, 0x73, 0x74, 0x1a, 0x28, 0x2e, - 0x63, 0x6f, 0x73, 0x6d, 0x6f, 0x73, 0x2e, 0x62, 0x61, 0x73, 0x65, 0x2e, 0x6e, 0x6f, 0x64, 0x65, - 0x2e, 0x76, 0x31, 0x62, 0x65, 0x74, 0x61, 0x31, 0x2e, 0x43, 0x6f, 0x6e, 0x66, 0x69, 0x67, 0x52, - 0x65, 0x73, 0x70, 0x6f, 0x6e, 0x73, 0x65, 0x22, 0x28, 0x82, 0xd3, 0xe4, 0x93, 0x02, 0x22, 0x12, - 0x20, 0x2f, 0x63, 0x6f, 0x73, 0x6d, 0x6f, 0x73, 0x2f, 0x62, 0x61, 0x73, 0x65, 0x2f, 0x6e, 0x6f, - 0x64, 0x65, 0x2f, 0x76, 0x31, 0x62, 0x65, 0x74, 0x61, 0x31, 0x2f, 0x63, 0x6f, 0x6e, 0x66, 0x69, - 0x67, 0x42, 0xe4, 0x01, 0x0a, 0x1c, 0x63, 0x6f, 0x6d, 0x2e, 0x63, 0x6f, 0x73, 0x6d, 0x6f, 0x73, - 0x2e, 0x62, 0x61, 0x73, 0x65, 0x2e, 0x6e, 0x6f, 0x64, 0x65, 0x2e, 0x76, 0x31, 0x62, 0x65, 0x74, - 0x61, 0x31, 0x42, 0x0a, 0x51, 0x75, 0x65, 0x72, 0x79, 0x50, 0x72, 0x6f, 0x74, 0x6f, 0x50, 0x01, - 0x5a, 0x35, 0x63, 0x6f, 0x73, 0x6d, 0x6f, 0x73, 0x73, 0x64, 0x6b, 0x2e, 0x69, 0x6f, 0x2f, 0x61, - 0x70, 0x69, 0x2f, 0x63, 0x6f, 0x73, 0x6d, 0x6f, 0x73, 0x2f, 0x62, 0x61, 0x73, 0x65, 0x2f, 0x6e, - 0x6f, 0x64, 0x65, 0x2f, 0x76, 0x31, 0x62, 0x65, 0x74, 0x61, 0x31, 0x3b, 0x6e, 0x6f, 0x64, 0x65, - 0x76, 0x31, 0x62, 0x65, 0x74, 0x61, 0x31, 0xa2, 0x02, 0x03, 0x43, 0x42, 0x4e, 0xaa, 0x02, 0x18, - 0x43, 0x6f, 0x73, 0x6d, 0x6f, 0x73, 0x2e, 0x42, 0x61, 0x73, 0x65, 0x2e, 0x4e, 0x6f, 0x64, 0x65, - 0x2e, 0x56, 0x31, 0x62, 0x65, 0x74, 0x61, 0x31, 0xca, 0x02, 0x18, 0x43, 0x6f, 0x73, 0x6d, 0x6f, - 0x73, 0x5c, 0x42, 0x61, 0x73, 0x65, 0x5c, 0x4e, 0x6f, 0x64, 0x65, 0x5c, 0x56, 0x31, 0x62, 0x65, - 0x74, 0x61, 0x31, 0xe2, 0x02, 0x24, 0x43, 0x6f, 0x73, 0x6d, 0x6f, 0x73, 0x5c, 0x42, 0x61, 0x73, - 0x65, 0x5c, 0x4e, 0x6f, 0x64, 0x65, 0x5c, 0x56, 0x31, 0x62, 0x65, 0x74, 0x61, 0x31, 0x5c, 0x47, - 0x50, 0x42, 0x4d, 0x65, 0x74, 0x61, 0x64, 0x61, 0x74, 0x61, 0xea, 0x02, 0x1b, 0x43, 0x6f, 0x73, - 0x6d, 0x6f, 0x73, 0x3a, 0x3a, 0x42, 0x61, 0x73, 0x65, 0x3a, 0x3a, 0x4e, 0x6f, 0x64, 0x65, 0x3a, - 0x3a, 0x56, 0x31, 0x62, 0x65, 0x74, 0x61, 0x31, 0x62, 0x06, 0x70, 0x72, 0x6f, 0x74, 0x6f, 0x33, + 0x6f, 0x74, 0x61, 0x74, 0x69, 0x6f, 0x6e, 0x73, 0x2e, 0x70, 0x72, 0x6f, 0x74, 0x6f, 0x1a, 0x1f, + 0x67, 0x6f, 0x6f, 0x67, 0x6c, 0x65, 0x2f, 0x70, 0x72, 0x6f, 0x74, 0x6f, 0x62, 0x75, 0x66, 0x2f, + 0x74, 0x69, 0x6d, 0x65, 0x73, 0x74, 0x61, 0x6d, 0x70, 0x2e, 0x70, 0x72, 0x6f, 0x74, 0x6f, 0x1a, + 0x14, 0x67, 0x6f, 0x67, 0x6f, 0x70, 0x72, 0x6f, 0x74, 0x6f, 0x2f, 0x67, 0x6f, 0x67, 0x6f, 0x2e, + 0x70, 0x72, 0x6f, 0x74, 0x6f, 0x22, 0x0f, 0x0a, 0x0d, 0x43, 0x6f, 0x6e, 0x66, 0x69, 0x67, 0x52, + 0x65, 0x71, 0x75, 0x65, 0x73, 0x74, 0x22, 0x97, 0x01, 0x0a, 0x0e, 0x43, 0x6f, 0x6e, 0x66, 0x69, + 0x67, 0x52, 0x65, 0x73, 0x70, 0x6f, 0x6e, 0x73, 0x65, 0x12, 0x2a, 0x0a, 0x11, 0x6d, 0x69, 0x6e, + 0x69, 0x6d, 0x75, 0x6d, 0x5f, 0x67, 0x61, 0x73, 0x5f, 0x70, 0x72, 0x69, 0x63, 0x65, 0x18, 0x01, + 0x20, 0x01, 0x28, 0x09, 0x52, 0x0f, 0x6d, 0x69, 0x6e, 0x69, 0x6d, 0x75, 0x6d, 0x47, 0x61, 0x73, + 0x50, 0x72, 0x69, 0x63, 0x65, 0x12, 0x2e, 0x0a, 0x13, 0x70, 0x72, 0x75, 0x6e, 0x69, 0x6e, 0x67, + 0x5f, 0x6b, 0x65, 0x65, 0x70, 0x5f, 0x72, 0x65, 0x63, 0x65, 0x6e, 0x74, 0x18, 0x02, 0x20, 0x01, + 0x28, 0x09, 0x52, 0x11, 0x70, 0x72, 0x75, 0x6e, 0x69, 0x6e, 0x67, 0x4b, 0x65, 0x65, 0x70, 0x52, + 0x65, 0x63, 0x65, 0x6e, 0x74, 0x12, 0x29, 0x0a, 0x10, 0x70, 0x72, 0x75, 0x6e, 0x69, 0x6e, 0x67, + 0x5f, 0x69, 0x6e, 0x74, 0x65, 0x72, 0x76, 0x61, 0x6c, 0x18, 0x03, 0x20, 0x01, 0x28, 0x09, 0x52, + 0x0f, 0x70, 0x72, 0x75, 0x6e, 0x69, 0x6e, 0x67, 0x49, 0x6e, 0x74, 0x65, 0x72, 0x76, 0x61, 0x6c, + 0x22, 0x0f, 0x0a, 0x0d, 0x53, 0x74, 0x61, 0x74, 0x75, 0x73, 0x52, 0x65, 0x71, 0x75, 0x65, 0x73, + 0x74, 0x22, 0xde, 0x01, 0x0a, 0x0e, 0x53, 0x74, 0x61, 0x74, 0x75, 0x73, 0x52, 0x65, 0x73, 0x70, + 0x6f, 0x6e, 0x73, 0x65, 0x12, 0x32, 0x0a, 0x15, 0x65, 0x61, 0x72, 0x6c, 0x69, 0x65, 0x73, 0x74, + 0x5f, 0x73, 0x74, 0x6f, 0x72, 0x65, 0x5f, 0x68, 0x65, 0x69, 0x67, 0x68, 0x74, 0x18, 0x01, 0x20, + 0x01, 0x28, 0x04, 0x52, 0x13, 0x65, 0x61, 0x72, 0x6c, 0x69, 0x65, 0x73, 0x74, 0x53, 0x74, 0x6f, + 0x72, 0x65, 0x48, 0x65, 0x69, 0x67, 0x68, 0x74, 0x12, 0x16, 0x0a, 0x06, 0x68, 0x65, 0x69, 0x67, + 0x68, 0x74, 0x18, 0x02, 0x20, 0x01, 0x28, 0x04, 0x52, 0x06, 0x68, 0x65, 0x69, 0x67, 0x68, 0x74, + 0x12, 0x3e, 0x0a, 0x09, 0x74, 0x69, 0x6d, 0x65, 0x73, 0x74, 0x61, 0x6d, 0x70, 0x18, 0x03, 0x20, + 0x01, 0x28, 0x0b, 0x32, 0x1a, 0x2e, 0x67, 0x6f, 0x6f, 0x67, 0x6c, 0x65, 0x2e, 0x70, 0x72, 0x6f, + 0x74, 0x6f, 0x62, 0x75, 0x66, 0x2e, 0x54, 0x69, 0x6d, 0x65, 0x73, 0x74, 0x61, 0x6d, 0x70, 0x42, + 0x04, 0x90, 0xdf, 0x1f, 0x01, 0x52, 0x09, 0x74, 0x69, 0x6d, 0x65, 0x73, 0x74, 0x61, 0x6d, 0x70, + 0x12, 0x19, 0x0a, 0x08, 0x61, 0x70, 0x70, 0x5f, 0x68, 0x61, 0x73, 0x68, 0x18, 0x04, 0x20, 0x01, + 0x28, 0x0c, 0x52, 0x07, 0x61, 0x70, 0x70, 0x48, 0x61, 0x73, 0x68, 0x12, 0x25, 0x0a, 0x0e, 0x76, + 0x61, 0x6c, 0x69, 0x64, 0x61, 0x74, 0x6f, 0x72, 0x5f, 0x68, 0x61, 0x73, 0x68, 0x18, 0x05, 0x20, + 0x01, 0x28, 0x0c, 0x52, 0x0d, 0x76, 0x61, 0x6c, 0x69, 0x64, 0x61, 0x74, 0x6f, 0x72, 0x48, 0x61, + 0x73, 0x68, 0x32, 0x99, 0x02, 0x0a, 0x07, 0x53, 0x65, 0x72, 0x76, 0x69, 0x63, 0x65, 0x12, 0x85, + 0x01, 0x0a, 0x06, 0x43, 0x6f, 0x6e, 0x66, 0x69, 0x67, 0x12, 0x27, 0x2e, 0x63, 0x6f, 0x73, 0x6d, + 0x6f, 0x73, 0x2e, 0x62, 0x61, 0x73, 0x65, 0x2e, 0x6e, 0x6f, 0x64, 0x65, 0x2e, 0x76, 0x31, 0x62, + 0x65, 0x74, 0x61, 0x31, 0x2e, 0x43, 0x6f, 0x6e, 0x66, 0x69, 0x67, 0x52, 0x65, 0x71, 0x75, 0x65, + 0x73, 0x74, 0x1a, 0x28, 0x2e, 0x63, 0x6f, 0x73, 0x6d, 0x6f, 0x73, 0x2e, 0x62, 0x61, 0x73, 0x65, + 0x2e, 0x6e, 0x6f, 0x64, 0x65, 0x2e, 0x76, 0x31, 0x62, 0x65, 0x74, 0x61, 0x31, 0x2e, 0x43, 0x6f, + 0x6e, 0x66, 0x69, 0x67, 0x52, 0x65, 0x73, 0x70, 0x6f, 0x6e, 0x73, 0x65, 0x22, 0x28, 0x82, 0xd3, + 0xe4, 0x93, 0x02, 0x22, 0x12, 0x20, 0x2f, 0x63, 0x6f, 0x73, 0x6d, 0x6f, 0x73, 0x2f, 0x62, 0x61, + 0x73, 0x65, 0x2f, 0x6e, 0x6f, 0x64, 0x65, 0x2f, 0x76, 0x31, 0x62, 0x65, 0x74, 0x61, 0x31, 0x2f, + 0x63, 0x6f, 0x6e, 0x66, 0x69, 0x67, 0x12, 0x85, 0x01, 0x0a, 0x06, 0x53, 0x74, 0x61, 0x74, 0x75, + 0x73, 0x12, 0x27, 0x2e, 0x63, 0x6f, 0x73, 0x6d, 0x6f, 0x73, 0x2e, 0x62, 0x61, 0x73, 0x65, 0x2e, + 0x6e, 0x6f, 0x64, 0x65, 0x2e, 0x76, 0x31, 0x62, 0x65, 0x74, 0x61, 0x31, 0x2e, 0x53, 0x74, 0x61, + 0x74, 0x75, 0x73, 0x52, 0x65, 0x71, 0x75, 0x65, 0x73, 0x74, 0x1a, 0x28, 0x2e, 0x63, 0x6f, 0x73, + 0x6d, 0x6f, 0x73, 0x2e, 0x62, 0x61, 0x73, 0x65, 0x2e, 0x6e, 0x6f, 0x64, 0x65, 0x2e, 0x76, 0x31, + 0x62, 0x65, 0x74, 0x61, 0x31, 0x2e, 0x53, 0x74, 0x61, 0x74, 0x75, 0x73, 0x52, 0x65, 0x73, 0x70, + 0x6f, 0x6e, 0x73, 0x65, 0x22, 0x28, 0x82, 0xd3, 0xe4, 0x93, 0x02, 0x22, 0x12, 0x20, 0x2f, 0x63, + 0x6f, 0x73, 0x6d, 0x6f, 0x73, 0x2f, 0x62, 0x61, 0x73, 0x65, 0x2f, 0x6e, 0x6f, 0x64, 0x65, 0x2f, + 0x76, 0x31, 0x62, 0x65, 0x74, 0x61, 0x31, 0x2f, 0x73, 0x74, 0x61, 0x74, 0x75, 0x73, 0x42, 0xe4, + 0x01, 0x0a, 0x1c, 0x63, 0x6f, 0x6d, 0x2e, 0x63, 0x6f, 0x73, 0x6d, 0x6f, 0x73, 0x2e, 0x62, 0x61, + 0x73, 0x65, 0x2e, 0x6e, 0x6f, 0x64, 0x65, 0x2e, 0x76, 0x31, 0x62, 0x65, 0x74, 0x61, 0x31, 0x42, + 0x0a, 0x51, 0x75, 0x65, 0x72, 0x79, 0x50, 0x72, 0x6f, 0x74, 0x6f, 0x50, 0x01, 0x5a, 0x35, 0x63, + 0x6f, 0x73, 0x6d, 0x6f, 0x73, 0x73, 0x64, 0x6b, 0x2e, 0x69, 0x6f, 0x2f, 0x61, 0x70, 0x69, 0x2f, + 0x63, 0x6f, 0x73, 0x6d, 0x6f, 0x73, 0x2f, 0x62, 0x61, 0x73, 0x65, 0x2f, 0x6e, 0x6f, 0x64, 0x65, + 0x2f, 0x76, 0x31, 0x62, 0x65, 0x74, 0x61, 0x31, 0x3b, 0x6e, 0x6f, 0x64, 0x65, 0x76, 0x31, 0x62, + 0x65, 0x74, 0x61, 0x31, 0xa2, 0x02, 0x03, 0x43, 0x42, 0x4e, 0xaa, 0x02, 0x18, 0x43, 0x6f, 0x73, + 0x6d, 0x6f, 0x73, 0x2e, 0x42, 0x61, 0x73, 0x65, 0x2e, 0x4e, 0x6f, 0x64, 0x65, 0x2e, 0x56, 0x31, + 0x62, 0x65, 0x74, 0x61, 0x31, 0xca, 0x02, 0x18, 0x43, 0x6f, 0x73, 0x6d, 0x6f, 0x73, 0x5c, 0x42, + 0x61, 0x73, 0x65, 0x5c, 0x4e, 0x6f, 0x64, 0x65, 0x5c, 0x56, 0x31, 0x62, 0x65, 0x74, 0x61, 0x31, + 0xe2, 0x02, 0x24, 0x43, 0x6f, 0x73, 0x6d, 0x6f, 0x73, 0x5c, 0x42, 0x61, 0x73, 0x65, 0x5c, 0x4e, + 0x6f, 0x64, 0x65, 0x5c, 0x56, 0x31, 0x62, 0x65, 0x74, 0x61, 0x31, 0x5c, 0x47, 0x50, 0x42, 0x4d, + 0x65, 0x74, 0x61, 0x64, 0x61, 0x74, 0x61, 0xea, 0x02, 0x1b, 0x43, 0x6f, 0x73, 0x6d, 0x6f, 0x73, + 0x3a, 0x3a, 0x42, 0x61, 0x73, 0x65, 0x3a, 0x3a, 0x4e, 0x6f, 0x64, 0x65, 0x3a, 0x3a, 0x56, 0x31, + 0x62, 0x65, 0x74, 0x61, 0x31, 0x62, 0x06, 0x70, 0x72, 0x6f, 0x74, 0x6f, 0x33, } var ( @@ -917,19 +2211,25 @@ func file_cosmos_base_node_v1beta1_query_proto_rawDescGZIP() []byte { return file_cosmos_base_node_v1beta1_query_proto_rawDescData } -var file_cosmos_base_node_v1beta1_query_proto_msgTypes = make([]protoimpl.MessageInfo, 2) +var file_cosmos_base_node_v1beta1_query_proto_msgTypes = make([]protoimpl.MessageInfo, 4) var file_cosmos_base_node_v1beta1_query_proto_goTypes = []interface{}{ - (*ConfigRequest)(nil), // 0: cosmos.base.node.v1beta1.ConfigRequest - (*ConfigResponse)(nil), // 1: cosmos.base.node.v1beta1.ConfigResponse + (*ConfigRequest)(nil), // 0: cosmos.base.node.v1beta1.ConfigRequest + (*ConfigResponse)(nil), // 1: cosmos.base.node.v1beta1.ConfigResponse + (*StatusRequest)(nil), // 2: cosmos.base.node.v1beta1.StatusRequest + (*StatusResponse)(nil), // 3: cosmos.base.node.v1beta1.StatusResponse + (*timestamppb.Timestamp)(nil), // 4: google.protobuf.Timestamp } var file_cosmos_base_node_v1beta1_query_proto_depIdxs = []int32{ - 0, // 0: cosmos.base.node.v1beta1.Service.Config:input_type -> cosmos.base.node.v1beta1.ConfigRequest - 1, // 1: cosmos.base.node.v1beta1.Service.Config:output_type -> cosmos.base.node.v1beta1.ConfigResponse - 1, // [1:2] is the sub-list for method output_type - 0, // [0:1] is the sub-list for method input_type - 0, // [0:0] is the sub-list for extension type_name - 0, // [0:0] is the sub-list for extension extendee - 0, // [0:0] is the sub-list for field type_name + 4, // 0: cosmos.base.node.v1beta1.StatusResponse.timestamp:type_name -> google.protobuf.Timestamp + 0, // 1: cosmos.base.node.v1beta1.Service.Config:input_type -> cosmos.base.node.v1beta1.ConfigRequest + 2, // 2: cosmos.base.node.v1beta1.Service.Status:input_type -> cosmos.base.node.v1beta1.StatusRequest + 1, // 3: cosmos.base.node.v1beta1.Service.Config:output_type -> cosmos.base.node.v1beta1.ConfigResponse + 3, // 4: cosmos.base.node.v1beta1.Service.Status:output_type -> cosmos.base.node.v1beta1.StatusResponse + 3, // [3:5] is the sub-list for method output_type + 1, // [1:3] is the sub-list for method input_type + 1, // [1:1] is the sub-list for extension type_name + 1, // [1:1] is the sub-list for extension extendee + 0, // [0:1] is the sub-list for field type_name } func init() { file_cosmos_base_node_v1beta1_query_proto_init() } @@ -962,6 +2262,30 @@ func file_cosmos_base_node_v1beta1_query_proto_init() { return nil } } + file_cosmos_base_node_v1beta1_query_proto_msgTypes[2].Exporter = func(v interface{}, i int) interface{} { + switch v := v.(*StatusRequest); i { + case 0: + return &v.state + case 1: + return &v.sizeCache + case 2: + return &v.unknownFields + default: + return nil + } + } + file_cosmos_base_node_v1beta1_query_proto_msgTypes[3].Exporter = func(v interface{}, i int) interface{} { + switch v := v.(*StatusResponse); i { + case 0: + return &v.state + case 1: + return &v.sizeCache + case 2: + return &v.unknownFields + default: + return nil + } + } } type x struct{} out := protoimpl.TypeBuilder{ @@ -969,7 +2293,7 @@ func file_cosmos_base_node_v1beta1_query_proto_init() { GoPackagePath: reflect.TypeOf(x{}).PkgPath(), RawDescriptor: file_cosmos_base_node_v1beta1_query_proto_rawDesc, NumEnums: 0, - NumMessages: 2, + NumMessages: 4, NumExtensions: 0, NumServices: 1, }, diff --git a/api/cosmos/base/node/v1beta1/query_grpc.pb.go b/api/cosmos/base/node/v1beta1/query_grpc.pb.go index c98b25f0e90c..cc79672ab921 100644 --- a/api/cosmos/base/node/v1beta1/query_grpc.pb.go +++ b/api/cosmos/base/node/v1beta1/query_grpc.pb.go @@ -20,6 +20,7 @@ const _ = grpc.SupportPackageIsVersion7 const ( Service_Config_FullMethodName = "/cosmos.base.node.v1beta1.Service/Config" + Service_Status_FullMethodName = "/cosmos.base.node.v1beta1.Service/Status" ) // ServiceClient is the client API for Service service. @@ -28,6 +29,8 @@ const ( type ServiceClient interface { // Config queries for the operator configuration. Config(ctx context.Context, in *ConfigRequest, opts ...grpc.CallOption) (*ConfigResponse, error) + // Status queries for the node status. + Status(ctx context.Context, in *StatusRequest, opts ...grpc.CallOption) (*StatusResponse, error) } type serviceClient struct { @@ -47,12 +50,23 @@ func (c *serviceClient) Config(ctx context.Context, in *ConfigRequest, opts ...g return out, nil } +func (c *serviceClient) Status(ctx context.Context, in *StatusRequest, opts ...grpc.CallOption) (*StatusResponse, error) { + out := new(StatusResponse) + err := c.cc.Invoke(ctx, Service_Status_FullMethodName, in, out, opts...) + if err != nil { + return nil, err + } + return out, nil +} + // ServiceServer is the server API for Service service. // All implementations must embed UnimplementedServiceServer // for forward compatibility type ServiceServer interface { // Config queries for the operator configuration. Config(context.Context, *ConfigRequest) (*ConfigResponse, error) + // Status queries for the node status. + Status(context.Context, *StatusRequest) (*StatusResponse, error) mustEmbedUnimplementedServiceServer() } @@ -63,6 +77,9 @@ type UnimplementedServiceServer struct { func (UnimplementedServiceServer) Config(context.Context, *ConfigRequest) (*ConfigResponse, error) { return nil, status.Errorf(codes.Unimplemented, "method Config not implemented") } +func (UnimplementedServiceServer) Status(context.Context, *StatusRequest) (*StatusResponse, error) { + return nil, status.Errorf(codes.Unimplemented, "method Status not implemented") +} func (UnimplementedServiceServer) mustEmbedUnimplementedServiceServer() {} // UnsafeServiceServer may be embedded to opt out of forward compatibility for this service. @@ -94,6 +111,24 @@ func _Service_Config_Handler(srv interface{}, ctx context.Context, dec func(inte return interceptor(ctx, in, info, handler) } +func _Service_Status_Handler(srv interface{}, ctx context.Context, dec func(interface{}) error, interceptor grpc.UnaryServerInterceptor) (interface{}, error) { + in := new(StatusRequest) + if err := dec(in); err != nil { + return nil, err + } + if interceptor == nil { + return srv.(ServiceServer).Status(ctx, in) + } + info := &grpc.UnaryServerInfo{ + Server: srv, + FullMethod: Service_Status_FullMethodName, + } + handler := func(ctx context.Context, req interface{}) (interface{}, error) { + return srv.(ServiceServer).Status(ctx, req.(*StatusRequest)) + } + return interceptor(ctx, in, info, handler) +} + // Service_ServiceDesc is the grpc.ServiceDesc for Service service. // It's only intended for direct use with grpc.RegisterService, // and not to be introspected or modified (even as a copy) @@ -105,6 +140,10 @@ var Service_ServiceDesc = grpc.ServiceDesc{ MethodName: "Config", Handler: _Service_Config_Handler, }, + { + MethodName: "Status", + Handler: _Service_Status_Handler, + }, }, Streams: []grpc.StreamDesc{}, Metadata: "cosmos/base/node/v1beta1/query.proto", diff --git a/api/cosmos/circuit/module/v1/module.pulsar.go b/api/cosmos/circuit/module/v1/module.pulsar.go new file mode 100644 index 000000000000..d5948ea22b58 --- /dev/null +++ b/api/cosmos/circuit/module/v1/module.pulsar.go @@ -0,0 +1,578 @@ +// Code generated by protoc-gen-go-pulsar. DO NOT EDIT. +package modulev1 + +import ( + _ "cosmossdk.io/api/cosmos/app/v1alpha1" + fmt "fmt" + runtime "github.com/cosmos/cosmos-proto/runtime" + protoreflect "google.golang.org/protobuf/reflect/protoreflect" + protoiface "google.golang.org/protobuf/runtime/protoiface" + protoimpl "google.golang.org/protobuf/runtime/protoimpl" + io "io" + reflect "reflect" + sync "sync" +) + +var ( + md_Module protoreflect.MessageDescriptor + fd_Module_authority protoreflect.FieldDescriptor +) + +func init() { + file_cosmos_circuit_module_v1_module_proto_init() + md_Module = File_cosmos_circuit_module_v1_module_proto.Messages().ByName("Module") + fd_Module_authority = md_Module.Fields().ByName("authority") +} + +var _ protoreflect.Message = (*fastReflection_Module)(nil) + +type fastReflection_Module Module + +func (x *Module) ProtoReflect() protoreflect.Message { + return (*fastReflection_Module)(x) +} + +func (x *Module) slowProtoReflect() protoreflect.Message { + mi := &file_cosmos_circuit_module_v1_module_proto_msgTypes[0] + if protoimpl.UnsafeEnabled && x != nil { + ms := protoimpl.X.MessageStateOf(protoimpl.Pointer(x)) + if ms.LoadMessageInfo() == nil { + ms.StoreMessageInfo(mi) + } + return ms + } + return mi.MessageOf(x) +} + +var _fastReflection_Module_messageType fastReflection_Module_messageType +var _ protoreflect.MessageType = fastReflection_Module_messageType{} + +type fastReflection_Module_messageType struct{} + +func (x fastReflection_Module_messageType) Zero() protoreflect.Message { + return (*fastReflection_Module)(nil) +} +func (x fastReflection_Module_messageType) New() protoreflect.Message { + return new(fastReflection_Module) +} +func (x fastReflection_Module_messageType) Descriptor() protoreflect.MessageDescriptor { + return md_Module +} + +// Descriptor returns message descriptor, which contains only the protobuf +// type information for the message. +func (x *fastReflection_Module) Descriptor() protoreflect.MessageDescriptor { + return md_Module +} + +// Type returns the message type, which encapsulates both Go and protobuf +// type information. If the Go type information is not needed, +// it is recommended that the message descriptor be used instead. +func (x *fastReflection_Module) Type() protoreflect.MessageType { + return _fastReflection_Module_messageType +} + +// New returns a newly allocated and mutable empty message. +func (x *fastReflection_Module) New() protoreflect.Message { + return new(fastReflection_Module) +} + +// Interface unwraps the message reflection interface and +// returns the underlying ProtoMessage interface. +func (x *fastReflection_Module) Interface() protoreflect.ProtoMessage { + return (*Module)(x) +} + +// Range iterates over every populated field in an undefined order, +// calling f for each field descriptor and value encountered. +// Range returns immediately if f returns false. +// While iterating, mutating operations may only be performed +// on the current field descriptor. +func (x *fastReflection_Module) Range(f func(protoreflect.FieldDescriptor, protoreflect.Value) bool) { + if x.Authority != "" { + value := protoreflect.ValueOfString(x.Authority) + if !f(fd_Module_authority, value) { + return + } + } +} + +// Has reports whether a field is populated. +// +// Some fields have the property of nullability where it is possible to +// distinguish between the default value of a field and whether the field +// was explicitly populated with the default value. Singular message fields, +// member fields of a oneof, and proto2 scalar fields are nullable. Such +// fields are populated only if explicitly set. +// +// In other cases (aside from the nullable cases above), +// a proto3 scalar field is populated if it contains a non-zero value, and +// a repeated field is populated if it is non-empty. +func (x *fastReflection_Module) Has(fd protoreflect.FieldDescriptor) bool { + switch fd.FullName() { + case "cosmos.circuit.module.v1.Module.authority": + return x.Authority != "" + default: + if fd.IsExtension() { + panic(fmt.Errorf("proto3 declared messages do not support extensions: cosmos.circuit.module.v1.Module")) + } + panic(fmt.Errorf("message cosmos.circuit.module.v1.Module does not contain field %s", fd.FullName())) + } +} + +// Clear clears the field such that a subsequent Has call reports false. +// +// Clearing an extension field clears both the extension type and value +// associated with the given field number. +// +// Clear is a mutating operation and unsafe for concurrent use. +func (x *fastReflection_Module) Clear(fd protoreflect.FieldDescriptor) { + switch fd.FullName() { + case "cosmos.circuit.module.v1.Module.authority": + x.Authority = "" + default: + if fd.IsExtension() { + panic(fmt.Errorf("proto3 declared messages do not support extensions: cosmos.circuit.module.v1.Module")) + } + panic(fmt.Errorf("message cosmos.circuit.module.v1.Module does not contain field %s", fd.FullName())) + } +} + +// Get retrieves the value for a field. +// +// For unpopulated scalars, it returns the default value, where +// the default value of a bytes scalar is guaranteed to be a copy. +// For unpopulated composite types, it returns an empty, read-only view +// of the value; to obtain a mutable reference, use Mutable. +func (x *fastReflection_Module) Get(descriptor protoreflect.FieldDescriptor) protoreflect.Value { + switch descriptor.FullName() { + case "cosmos.circuit.module.v1.Module.authority": + value := x.Authority + return protoreflect.ValueOfString(value) + default: + if descriptor.IsExtension() { + panic(fmt.Errorf("proto3 declared messages do not support extensions: cosmos.circuit.module.v1.Module")) + } + panic(fmt.Errorf("message cosmos.circuit.module.v1.Module does not contain field %s", descriptor.FullName())) + } +} + +// Set stores the value for a field. +// +// For a field belonging to a oneof, it implicitly clears any other field +// that may be currently set within the same oneof. +// For extension fields, it implicitly stores the provided ExtensionType. +// When setting a composite type, it is unspecified whether the stored value +// aliases the source's memory in any way. If the composite value is an +// empty, read-only value, then it panics. +// +// Set is a mutating operation and unsafe for concurrent use. +func (x *fastReflection_Module) Set(fd protoreflect.FieldDescriptor, value protoreflect.Value) { + switch fd.FullName() { + case "cosmos.circuit.module.v1.Module.authority": + x.Authority = value.Interface().(string) + default: + if fd.IsExtension() { + panic(fmt.Errorf("proto3 declared messages do not support extensions: cosmos.circuit.module.v1.Module")) + } + panic(fmt.Errorf("message cosmos.circuit.module.v1.Module does not contain field %s", fd.FullName())) + } +} + +// Mutable returns a mutable reference to a composite type. +// +// If the field is unpopulated, it may allocate a composite value. +// For a field belonging to a oneof, it implicitly clears any other field +// that may be currently set within the same oneof. +// For extension fields, it implicitly stores the provided ExtensionType +// if not already stored. +// It panics if the field does not contain a composite type. +// +// Mutable is a mutating operation and unsafe for concurrent use. +func (x *fastReflection_Module) Mutable(fd protoreflect.FieldDescriptor) protoreflect.Value { + switch fd.FullName() { + case "cosmos.circuit.module.v1.Module.authority": + panic(fmt.Errorf("field authority of message cosmos.circuit.module.v1.Module is not mutable")) + default: + if fd.IsExtension() { + panic(fmt.Errorf("proto3 declared messages do not support extensions: cosmos.circuit.module.v1.Module")) + } + panic(fmt.Errorf("message cosmos.circuit.module.v1.Module does not contain field %s", fd.FullName())) + } +} + +// NewField returns a new value that is assignable to the field +// for the given descriptor. For scalars, this returns the default value. +// For lists, maps, and messages, this returns a new, empty, mutable value. +func (x *fastReflection_Module) NewField(fd protoreflect.FieldDescriptor) protoreflect.Value { + switch fd.FullName() { + case "cosmos.circuit.module.v1.Module.authority": + return protoreflect.ValueOfString("") + default: + if fd.IsExtension() { + panic(fmt.Errorf("proto3 declared messages do not support extensions: cosmos.circuit.module.v1.Module")) + } + panic(fmt.Errorf("message cosmos.circuit.module.v1.Module does not contain field %s", fd.FullName())) + } +} + +// WhichOneof reports which field within the oneof is populated, +// returning nil if none are populated. +// It panics if the oneof descriptor does not belong to this message. +func (x *fastReflection_Module) WhichOneof(d protoreflect.OneofDescriptor) protoreflect.FieldDescriptor { + switch d.FullName() { + default: + panic(fmt.Errorf("%s is not a oneof field in cosmos.circuit.module.v1.Module", d.FullName())) + } + panic("unreachable") +} + +// GetUnknown retrieves the entire list of unknown fields. +// The caller may only mutate the contents of the RawFields +// if the mutated bytes are stored back into the message with SetUnknown. +func (x *fastReflection_Module) GetUnknown() protoreflect.RawFields { + return x.unknownFields +} + +// SetUnknown stores an entire list of unknown fields. +// The raw fields must be syntactically valid according to the wire format. +// An implementation may panic if this is not the case. +// Once stored, the caller must not mutate the content of the RawFields. +// An empty RawFields may be passed to clear the fields. +// +// SetUnknown is a mutating operation and unsafe for concurrent use. +func (x *fastReflection_Module) SetUnknown(fields protoreflect.RawFields) { + x.unknownFields = fields +} + +// IsValid reports whether the message is valid. +// +// An invalid message is an empty, read-only value. +// +// An invalid message often corresponds to a nil pointer of the concrete +// message type, but the details are implementation dependent. +// Validity is not part of the protobuf data model, and may not +// be preserved in marshaling or other operations. +func (x *fastReflection_Module) IsValid() bool { + return x != nil +} + +// ProtoMethods returns optional fastReflectionFeature-path implementations of various operations. +// This method may return nil. +// +// The returned methods type is identical to +// "google.golang.org/protobuf/runtime/protoiface".Methods. +// Consult the protoiface package documentation for details. +func (x *fastReflection_Module) ProtoMethods() *protoiface.Methods { + size := func(input protoiface.SizeInput) protoiface.SizeOutput { + x := input.Message.Interface().(*Module) + if x == nil { + return protoiface.SizeOutput{ + NoUnkeyedLiterals: input.NoUnkeyedLiterals, + Size: 0, + } + } + options := runtime.SizeInputToOptions(input) + _ = options + var n int + var l int + _ = l + l = len(x.Authority) + if l > 0 { + n += 1 + l + runtime.Sov(uint64(l)) + } + if x.unknownFields != nil { + n += len(x.unknownFields) + } + return protoiface.SizeOutput{ + NoUnkeyedLiterals: input.NoUnkeyedLiterals, + Size: n, + } + } + + marshal := func(input protoiface.MarshalInput) (protoiface.MarshalOutput, error) { + x := input.Message.Interface().(*Module) + if x == nil { + return protoiface.MarshalOutput{ + NoUnkeyedLiterals: input.NoUnkeyedLiterals, + Buf: input.Buf, + }, nil + } + options := runtime.MarshalInputToOptions(input) + _ = options + size := options.Size(x) + dAtA := make([]byte, size) + i := len(dAtA) + _ = i + var l int + _ = l + if x.unknownFields != nil { + i -= len(x.unknownFields) + copy(dAtA[i:], x.unknownFields) + } + if len(x.Authority) > 0 { + i -= len(x.Authority) + copy(dAtA[i:], x.Authority) + i = runtime.EncodeVarint(dAtA, i, uint64(len(x.Authority))) + i-- + dAtA[i] = 0xa + } + if input.Buf != nil { + input.Buf = append(input.Buf, dAtA...) + } else { + input.Buf = dAtA + } + return protoiface.MarshalOutput{ + NoUnkeyedLiterals: input.NoUnkeyedLiterals, + Buf: input.Buf, + }, nil + } + unmarshal := func(input protoiface.UnmarshalInput) (protoiface.UnmarshalOutput, error) { + x := input.Message.Interface().(*Module) + if x == nil { + return protoiface.UnmarshalOutput{ + NoUnkeyedLiterals: input.NoUnkeyedLiterals, + Flags: input.Flags, + }, nil + } + options := runtime.UnmarshalInputToOptions(input) + _ = options + dAtA := input.Buf + l := len(dAtA) + iNdEx := 0 + for iNdEx < l { + preIndex := iNdEx + var wire uint64 + for shift := uint(0); ; shift += 7 { + if shift >= 64 { + return protoiface.UnmarshalOutput{NoUnkeyedLiterals: input.NoUnkeyedLiterals, Flags: input.Flags}, runtime.ErrIntOverflow + } + if iNdEx >= l { + return protoiface.UnmarshalOutput{NoUnkeyedLiterals: input.NoUnkeyedLiterals, Flags: input.Flags}, io.ErrUnexpectedEOF + } + b := dAtA[iNdEx] + iNdEx++ + wire |= uint64(b&0x7F) << shift + if b < 0x80 { + break + } + } + fieldNum := int32(wire >> 3) + wireType := int(wire & 0x7) + if wireType == 4 { + return protoiface.UnmarshalOutput{NoUnkeyedLiterals: input.NoUnkeyedLiterals, Flags: input.Flags}, fmt.Errorf("proto: Module: wiretype end group for non-group") + } + if fieldNum <= 0 { + return protoiface.UnmarshalOutput{NoUnkeyedLiterals: input.NoUnkeyedLiterals, Flags: input.Flags}, fmt.Errorf("proto: Module: illegal tag %d (wire type %d)", fieldNum, wire) + } + switch fieldNum { + case 1: + if wireType != 2 { + return protoiface.UnmarshalOutput{NoUnkeyedLiterals: input.NoUnkeyedLiterals, Flags: input.Flags}, fmt.Errorf("proto: wrong wireType = %d for field Authority", wireType) + } + var stringLen uint64 + for shift := uint(0); ; shift += 7 { + if shift >= 64 { + return protoiface.UnmarshalOutput{NoUnkeyedLiterals: input.NoUnkeyedLiterals, Flags: input.Flags}, runtime.ErrIntOverflow + } + if iNdEx >= l { + return protoiface.UnmarshalOutput{NoUnkeyedLiterals: input.NoUnkeyedLiterals, Flags: input.Flags}, io.ErrUnexpectedEOF + } + b := dAtA[iNdEx] + iNdEx++ + stringLen |= uint64(b&0x7F) << shift + if b < 0x80 { + break + } + } + intStringLen := int(stringLen) + if intStringLen < 0 { + return protoiface.UnmarshalOutput{NoUnkeyedLiterals: input.NoUnkeyedLiterals, Flags: input.Flags}, runtime.ErrInvalidLength + } + postIndex := iNdEx + intStringLen + if postIndex < 0 { + return protoiface.UnmarshalOutput{NoUnkeyedLiterals: input.NoUnkeyedLiterals, Flags: input.Flags}, runtime.ErrInvalidLength + } + if postIndex > l { + return protoiface.UnmarshalOutput{NoUnkeyedLiterals: input.NoUnkeyedLiterals, Flags: input.Flags}, io.ErrUnexpectedEOF + } + x.Authority = string(dAtA[iNdEx:postIndex]) + iNdEx = postIndex + default: + iNdEx = preIndex + skippy, err := runtime.Skip(dAtA[iNdEx:]) + if err != nil { + return protoiface.UnmarshalOutput{NoUnkeyedLiterals: input.NoUnkeyedLiterals, Flags: input.Flags}, err + } + if (skippy < 0) || (iNdEx+skippy) < 0 { + return protoiface.UnmarshalOutput{NoUnkeyedLiterals: input.NoUnkeyedLiterals, Flags: input.Flags}, runtime.ErrInvalidLength + } + if (iNdEx + skippy) > l { + return protoiface.UnmarshalOutput{NoUnkeyedLiterals: input.NoUnkeyedLiterals, Flags: input.Flags}, io.ErrUnexpectedEOF + } + if !options.DiscardUnknown { + x.unknownFields = append(x.unknownFields, dAtA[iNdEx:iNdEx+skippy]...) + } + iNdEx += skippy + } + } + + if iNdEx > l { + return protoiface.UnmarshalOutput{NoUnkeyedLiterals: input.NoUnkeyedLiterals, Flags: input.Flags}, io.ErrUnexpectedEOF + } + return protoiface.UnmarshalOutput{NoUnkeyedLiterals: input.NoUnkeyedLiterals, Flags: input.Flags}, nil + } + return &protoiface.Methods{ + NoUnkeyedLiterals: struct{}{}, + Flags: protoiface.SupportMarshalDeterministic | protoiface.SupportUnmarshalDiscardUnknown, + Size: size, + Marshal: marshal, + Unmarshal: unmarshal, + Merge: nil, + CheckInitialized: nil, + } +} + +// Code generated by protoc-gen-go. DO NOT EDIT. +// versions: +// protoc-gen-go v1.27.0 +// protoc (unknown) +// source: cosmos/circuit/module/v1/module.proto + +const ( + // Verify that this generated code is sufficiently up-to-date. + _ = protoimpl.EnforceVersion(20 - protoimpl.MinVersion) + // Verify that runtime/protoimpl is sufficiently up-to-date. + _ = protoimpl.EnforceVersion(protoimpl.MaxVersion - 20) +) + +// Module is the config object of the circuit module. +type Module struct { + state protoimpl.MessageState + sizeCache protoimpl.SizeCache + unknownFields protoimpl.UnknownFields + + // authority defines the custom module authority. If not set, defaults to the governance module. + Authority string `protobuf:"bytes,1,opt,name=authority,proto3" json:"authority,omitempty"` +} + +func (x *Module) Reset() { + *x = Module{} + if protoimpl.UnsafeEnabled { + mi := &file_cosmos_circuit_module_v1_module_proto_msgTypes[0] + ms := protoimpl.X.MessageStateOf(protoimpl.Pointer(x)) + ms.StoreMessageInfo(mi) + } +} + +func (x *Module) String() string { + return protoimpl.X.MessageStringOf(x) +} + +func (*Module) ProtoMessage() {} + +// Deprecated: Use Module.ProtoReflect.Descriptor instead. +func (*Module) Descriptor() ([]byte, []int) { + return file_cosmos_circuit_module_v1_module_proto_rawDescGZIP(), []int{0} +} + +func (x *Module) GetAuthority() string { + if x != nil { + return x.Authority + } + return "" +} + +var File_cosmos_circuit_module_v1_module_proto protoreflect.FileDescriptor + +var file_cosmos_circuit_module_v1_module_proto_rawDesc = []byte{ + 0x0a, 0x25, 0x63, 0x6f, 0x73, 0x6d, 0x6f, 0x73, 0x2f, 0x63, 0x69, 0x72, 0x63, 0x75, 0x69, 0x74, + 0x2f, 0x6d, 0x6f, 0x64, 0x75, 0x6c, 0x65, 0x2f, 0x76, 0x31, 0x2f, 0x6d, 0x6f, 0x64, 0x75, 0x6c, + 0x65, 0x2e, 0x70, 0x72, 0x6f, 0x74, 0x6f, 0x12, 0x18, 0x63, 0x6f, 0x73, 0x6d, 0x6f, 0x73, 0x2e, + 0x63, 0x69, 0x72, 0x63, 0x75, 0x69, 0x74, 0x2e, 0x6d, 0x6f, 0x64, 0x75, 0x6c, 0x65, 0x2e, 0x76, + 0x31, 0x1a, 0x20, 0x63, 0x6f, 0x73, 0x6d, 0x6f, 0x73, 0x2f, 0x61, 0x70, 0x70, 0x2f, 0x76, 0x31, + 0x61, 0x6c, 0x70, 0x68, 0x61, 0x31, 0x2f, 0x6d, 0x6f, 0x64, 0x75, 0x6c, 0x65, 0x2e, 0x70, 0x72, + 0x6f, 0x74, 0x6f, 0x22, 0x46, 0x0a, 0x06, 0x4d, 0x6f, 0x64, 0x75, 0x6c, 0x65, 0x12, 0x1c, 0x0a, + 0x09, 0x61, 0x75, 0x74, 0x68, 0x6f, 0x72, 0x69, 0x74, 0x79, 0x18, 0x01, 0x20, 0x01, 0x28, 0x09, + 0x52, 0x09, 0x61, 0x75, 0x74, 0x68, 0x6f, 0x72, 0x69, 0x74, 0x79, 0x3a, 0x1e, 0xba, 0xc0, 0x96, + 0xda, 0x01, 0x18, 0x0a, 0x16, 0x63, 0x6f, 0x73, 0x6d, 0x6f, 0x73, 0x73, 0x64, 0x6b, 0x2e, 0x69, + 0x6f, 0x2f, 0x78, 0x2f, 0x63, 0x69, 0x72, 0x63, 0x75, 0x69, 0x74, 0x42, 0xe2, 0x01, 0x0a, 0x1c, + 0x63, 0x6f, 0x6d, 0x2e, 0x63, 0x6f, 0x73, 0x6d, 0x6f, 0x73, 0x2e, 0x63, 0x69, 0x72, 0x63, 0x75, + 0x69, 0x74, 0x2e, 0x6d, 0x6f, 0x64, 0x75, 0x6c, 0x65, 0x2e, 0x76, 0x31, 0x42, 0x0b, 0x4d, 0x6f, + 0x64, 0x75, 0x6c, 0x65, 0x50, 0x72, 0x6f, 0x74, 0x6f, 0x50, 0x01, 0x5a, 0x32, 0x63, 0x6f, 0x73, + 0x6d, 0x6f, 0x73, 0x73, 0x64, 0x6b, 0x2e, 0x69, 0x6f, 0x2f, 0x61, 0x70, 0x69, 0x2f, 0x63, 0x6f, + 0x73, 0x6d, 0x6f, 0x73, 0x2f, 0x63, 0x69, 0x72, 0x63, 0x75, 0x69, 0x74, 0x2f, 0x6d, 0x6f, 0x64, + 0x75, 0x6c, 0x65, 0x2f, 0x76, 0x31, 0x3b, 0x6d, 0x6f, 0x64, 0x75, 0x6c, 0x65, 0x76, 0x31, 0xa2, + 0x02, 0x03, 0x43, 0x43, 0x4d, 0xaa, 0x02, 0x18, 0x43, 0x6f, 0x73, 0x6d, 0x6f, 0x73, 0x2e, 0x43, + 0x69, 0x72, 0x63, 0x75, 0x69, 0x74, 0x2e, 0x4d, 0x6f, 0x64, 0x75, 0x6c, 0x65, 0x2e, 0x56, 0x31, + 0xca, 0x02, 0x18, 0x43, 0x6f, 0x73, 0x6d, 0x6f, 0x73, 0x5c, 0x43, 0x69, 0x72, 0x63, 0x75, 0x69, + 0x74, 0x5c, 0x4d, 0x6f, 0x64, 0x75, 0x6c, 0x65, 0x5c, 0x56, 0x31, 0xe2, 0x02, 0x24, 0x43, 0x6f, + 0x73, 0x6d, 0x6f, 0x73, 0x5c, 0x43, 0x69, 0x72, 0x63, 0x75, 0x69, 0x74, 0x5c, 0x4d, 0x6f, 0x64, + 0x75, 0x6c, 0x65, 0x5c, 0x56, 0x31, 0x5c, 0x47, 0x50, 0x42, 0x4d, 0x65, 0x74, 0x61, 0x64, 0x61, + 0x74, 0x61, 0xea, 0x02, 0x1b, 0x43, 0x6f, 0x73, 0x6d, 0x6f, 0x73, 0x3a, 0x3a, 0x43, 0x69, 0x72, + 0x63, 0x75, 0x69, 0x74, 0x3a, 0x3a, 0x4d, 0x6f, 0x64, 0x75, 0x6c, 0x65, 0x3a, 0x3a, 0x56, 0x31, + 0x62, 0x06, 0x70, 0x72, 0x6f, 0x74, 0x6f, 0x33, +} + +var ( + file_cosmos_circuit_module_v1_module_proto_rawDescOnce sync.Once + file_cosmos_circuit_module_v1_module_proto_rawDescData = file_cosmos_circuit_module_v1_module_proto_rawDesc +) + +func file_cosmos_circuit_module_v1_module_proto_rawDescGZIP() []byte { + file_cosmos_circuit_module_v1_module_proto_rawDescOnce.Do(func() { + file_cosmos_circuit_module_v1_module_proto_rawDescData = protoimpl.X.CompressGZIP(file_cosmos_circuit_module_v1_module_proto_rawDescData) + }) + return file_cosmos_circuit_module_v1_module_proto_rawDescData +} + +var file_cosmos_circuit_module_v1_module_proto_msgTypes = make([]protoimpl.MessageInfo, 1) +var file_cosmos_circuit_module_v1_module_proto_goTypes = []interface{}{ + (*Module)(nil), // 0: cosmos.circuit.module.v1.Module +} +var file_cosmos_circuit_module_v1_module_proto_depIdxs = []int32{ + 0, // [0:0] is the sub-list for method output_type + 0, // [0:0] is the sub-list for method input_type + 0, // [0:0] is the sub-list for extension type_name + 0, // [0:0] is the sub-list for extension extendee + 0, // [0:0] is the sub-list for field type_name +} + +func init() { file_cosmos_circuit_module_v1_module_proto_init() } +func file_cosmos_circuit_module_v1_module_proto_init() { + if File_cosmos_circuit_module_v1_module_proto != nil { + return + } + if !protoimpl.UnsafeEnabled { + file_cosmos_circuit_module_v1_module_proto_msgTypes[0].Exporter = func(v interface{}, i int) interface{} { + switch v := v.(*Module); i { + case 0: + return &v.state + case 1: + return &v.sizeCache + case 2: + return &v.unknownFields + default: + return nil + } + } + } + type x struct{} + out := protoimpl.TypeBuilder{ + File: protoimpl.DescBuilder{ + GoPackagePath: reflect.TypeOf(x{}).PkgPath(), + RawDescriptor: file_cosmos_circuit_module_v1_module_proto_rawDesc, + NumEnums: 0, + NumMessages: 1, + NumExtensions: 0, + NumServices: 0, + }, + GoTypes: file_cosmos_circuit_module_v1_module_proto_goTypes, + DependencyIndexes: file_cosmos_circuit_module_v1_module_proto_depIdxs, + MessageInfos: file_cosmos_circuit_module_v1_module_proto_msgTypes, + }.Build() + File_cosmos_circuit_module_v1_module_proto = out.File + file_cosmos_circuit_module_v1_module_proto_rawDesc = nil + file_cosmos_circuit_module_v1_module_proto_goTypes = nil + file_cosmos_circuit_module_v1_module_proto_depIdxs = nil +} diff --git a/api/cosmos/circuit/v1/query.pulsar.go b/api/cosmos/circuit/v1/query.pulsar.go new file mode 100644 index 000000000000..9fd4c339f1a1 --- /dev/null +++ b/api/cosmos/circuit/v1/query.pulsar.go @@ -0,0 +1,3177 @@ +// Code generated by protoc-gen-go-pulsar. DO NOT EDIT. +package circuitv1 + +import ( + v1beta1 "cosmossdk.io/api/cosmos/base/query/v1beta1" + _ "cosmossdk.io/api/cosmos/msg/v1" + _ "cosmossdk.io/api/cosmos/query/v1" + fmt "fmt" + runtime "github.com/cosmos/cosmos-proto/runtime" + _ "google.golang.org/genproto/googleapis/api/annotations" + protoreflect "google.golang.org/protobuf/reflect/protoreflect" + protoiface "google.golang.org/protobuf/runtime/protoiface" + protoimpl "google.golang.org/protobuf/runtime/protoimpl" + io "io" + reflect "reflect" + sync "sync" +) + +var ( + md_QueryAccountRequest protoreflect.MessageDescriptor + fd_QueryAccountRequest_address protoreflect.FieldDescriptor +) + +func init() { + file_cosmos_circuit_v1_query_proto_init() + md_QueryAccountRequest = File_cosmos_circuit_v1_query_proto.Messages().ByName("QueryAccountRequest") + fd_QueryAccountRequest_address = md_QueryAccountRequest.Fields().ByName("address") +} + +var _ protoreflect.Message = (*fastReflection_QueryAccountRequest)(nil) + +type fastReflection_QueryAccountRequest QueryAccountRequest + +func (x *QueryAccountRequest) ProtoReflect() protoreflect.Message { + return (*fastReflection_QueryAccountRequest)(x) +} + +func (x *QueryAccountRequest) slowProtoReflect() protoreflect.Message { + mi := &file_cosmos_circuit_v1_query_proto_msgTypes[0] + if protoimpl.UnsafeEnabled && x != nil { + ms := protoimpl.X.MessageStateOf(protoimpl.Pointer(x)) + if ms.LoadMessageInfo() == nil { + ms.StoreMessageInfo(mi) + } + return ms + } + return mi.MessageOf(x) +} + +var _fastReflection_QueryAccountRequest_messageType fastReflection_QueryAccountRequest_messageType +var _ protoreflect.MessageType = fastReflection_QueryAccountRequest_messageType{} + +type fastReflection_QueryAccountRequest_messageType struct{} + +func (x fastReflection_QueryAccountRequest_messageType) Zero() protoreflect.Message { + return (*fastReflection_QueryAccountRequest)(nil) +} +func (x fastReflection_QueryAccountRequest_messageType) New() protoreflect.Message { + return new(fastReflection_QueryAccountRequest) +} +func (x fastReflection_QueryAccountRequest_messageType) Descriptor() protoreflect.MessageDescriptor { + return md_QueryAccountRequest +} + +// Descriptor returns message descriptor, which contains only the protobuf +// type information for the message. +func (x *fastReflection_QueryAccountRequest) Descriptor() protoreflect.MessageDescriptor { + return md_QueryAccountRequest +} + +// Type returns the message type, which encapsulates both Go and protobuf +// type information. If the Go type information is not needed, +// it is recommended that the message descriptor be used instead. +func (x *fastReflection_QueryAccountRequest) Type() protoreflect.MessageType { + return _fastReflection_QueryAccountRequest_messageType +} + +// New returns a newly allocated and mutable empty message. +func (x *fastReflection_QueryAccountRequest) New() protoreflect.Message { + return new(fastReflection_QueryAccountRequest) +} + +// Interface unwraps the message reflection interface and +// returns the underlying ProtoMessage interface. +func (x *fastReflection_QueryAccountRequest) Interface() protoreflect.ProtoMessage { + return (*QueryAccountRequest)(x) +} + +// Range iterates over every populated field in an undefined order, +// calling f for each field descriptor and value encountered. +// Range returns immediately if f returns false. +// While iterating, mutating operations may only be performed +// on the current field descriptor. +func (x *fastReflection_QueryAccountRequest) Range(f func(protoreflect.FieldDescriptor, protoreflect.Value) bool) { + if x.Address != "" { + value := protoreflect.ValueOfString(x.Address) + if !f(fd_QueryAccountRequest_address, value) { + return + } + } +} + +// Has reports whether a field is populated. +// +// Some fields have the property of nullability where it is possible to +// distinguish between the default value of a field and whether the field +// was explicitly populated with the default value. Singular message fields, +// member fields of a oneof, and proto2 scalar fields are nullable. Such +// fields are populated only if explicitly set. +// +// In other cases (aside from the nullable cases above), +// a proto3 scalar field is populated if it contains a non-zero value, and +// a repeated field is populated if it is non-empty. +func (x *fastReflection_QueryAccountRequest) Has(fd protoreflect.FieldDescriptor) bool { + switch fd.FullName() { + case "cosmos.circuit.v1.QueryAccountRequest.address": + return x.Address != "" + default: + if fd.IsExtension() { + panic(fmt.Errorf("proto3 declared messages do not support extensions: cosmos.circuit.v1.QueryAccountRequest")) + } + panic(fmt.Errorf("message cosmos.circuit.v1.QueryAccountRequest does not contain field %s", fd.FullName())) + } +} + +// Clear clears the field such that a subsequent Has call reports false. +// +// Clearing an extension field clears both the extension type and value +// associated with the given field number. +// +// Clear is a mutating operation and unsafe for concurrent use. +func (x *fastReflection_QueryAccountRequest) Clear(fd protoreflect.FieldDescriptor) { + switch fd.FullName() { + case "cosmos.circuit.v1.QueryAccountRequest.address": + x.Address = "" + default: + if fd.IsExtension() { + panic(fmt.Errorf("proto3 declared messages do not support extensions: cosmos.circuit.v1.QueryAccountRequest")) + } + panic(fmt.Errorf("message cosmos.circuit.v1.QueryAccountRequest does not contain field %s", fd.FullName())) + } +} + +// Get retrieves the value for a field. +// +// For unpopulated scalars, it returns the default value, where +// the default value of a bytes scalar is guaranteed to be a copy. +// For unpopulated composite types, it returns an empty, read-only view +// of the value; to obtain a mutable reference, use Mutable. +func (x *fastReflection_QueryAccountRequest) Get(descriptor protoreflect.FieldDescriptor) protoreflect.Value { + switch descriptor.FullName() { + case "cosmos.circuit.v1.QueryAccountRequest.address": + value := x.Address + return protoreflect.ValueOfString(value) + default: + if descriptor.IsExtension() { + panic(fmt.Errorf("proto3 declared messages do not support extensions: cosmos.circuit.v1.QueryAccountRequest")) + } + panic(fmt.Errorf("message cosmos.circuit.v1.QueryAccountRequest does not contain field %s", descriptor.FullName())) + } +} + +// Set stores the value for a field. +// +// For a field belonging to a oneof, it implicitly clears any other field +// that may be currently set within the same oneof. +// For extension fields, it implicitly stores the provided ExtensionType. +// When setting a composite type, it is unspecified whether the stored value +// aliases the source's memory in any way. If the composite value is an +// empty, read-only value, then it panics. +// +// Set is a mutating operation and unsafe for concurrent use. +func (x *fastReflection_QueryAccountRequest) Set(fd protoreflect.FieldDescriptor, value protoreflect.Value) { + switch fd.FullName() { + case "cosmos.circuit.v1.QueryAccountRequest.address": + x.Address = value.Interface().(string) + default: + if fd.IsExtension() { + panic(fmt.Errorf("proto3 declared messages do not support extensions: cosmos.circuit.v1.QueryAccountRequest")) + } + panic(fmt.Errorf("message cosmos.circuit.v1.QueryAccountRequest does not contain field %s", fd.FullName())) + } +} + +// Mutable returns a mutable reference to a composite type. +// +// If the field is unpopulated, it may allocate a composite value. +// For a field belonging to a oneof, it implicitly clears any other field +// that may be currently set within the same oneof. +// For extension fields, it implicitly stores the provided ExtensionType +// if not already stored. +// It panics if the field does not contain a composite type. +// +// Mutable is a mutating operation and unsafe for concurrent use. +func (x *fastReflection_QueryAccountRequest) Mutable(fd protoreflect.FieldDescriptor) protoreflect.Value { + switch fd.FullName() { + case "cosmos.circuit.v1.QueryAccountRequest.address": + panic(fmt.Errorf("field address of message cosmos.circuit.v1.QueryAccountRequest is not mutable")) + default: + if fd.IsExtension() { + panic(fmt.Errorf("proto3 declared messages do not support extensions: cosmos.circuit.v1.QueryAccountRequest")) + } + panic(fmt.Errorf("message cosmos.circuit.v1.QueryAccountRequest does not contain field %s", fd.FullName())) + } +} + +// NewField returns a new value that is assignable to the field +// for the given descriptor. For scalars, this returns the default value. +// For lists, maps, and messages, this returns a new, empty, mutable value. +func (x *fastReflection_QueryAccountRequest) NewField(fd protoreflect.FieldDescriptor) protoreflect.Value { + switch fd.FullName() { + case "cosmos.circuit.v1.QueryAccountRequest.address": + return protoreflect.ValueOfString("") + default: + if fd.IsExtension() { + panic(fmt.Errorf("proto3 declared messages do not support extensions: cosmos.circuit.v1.QueryAccountRequest")) + } + panic(fmt.Errorf("message cosmos.circuit.v1.QueryAccountRequest does not contain field %s", fd.FullName())) + } +} + +// WhichOneof reports which field within the oneof is populated, +// returning nil if none are populated. +// It panics if the oneof descriptor does not belong to this message. +func (x *fastReflection_QueryAccountRequest) WhichOneof(d protoreflect.OneofDescriptor) protoreflect.FieldDescriptor { + switch d.FullName() { + default: + panic(fmt.Errorf("%s is not a oneof field in cosmos.circuit.v1.QueryAccountRequest", d.FullName())) + } + panic("unreachable") +} + +// GetUnknown retrieves the entire list of unknown fields. +// The caller may only mutate the contents of the RawFields +// if the mutated bytes are stored back into the message with SetUnknown. +func (x *fastReflection_QueryAccountRequest) GetUnknown() protoreflect.RawFields { + return x.unknownFields +} + +// SetUnknown stores an entire list of unknown fields. +// The raw fields must be syntactically valid according to the wire format. +// An implementation may panic if this is not the case. +// Once stored, the caller must not mutate the content of the RawFields. +// An empty RawFields may be passed to clear the fields. +// +// SetUnknown is a mutating operation and unsafe for concurrent use. +func (x *fastReflection_QueryAccountRequest) SetUnknown(fields protoreflect.RawFields) { + x.unknownFields = fields +} + +// IsValid reports whether the message is valid. +// +// An invalid message is an empty, read-only value. +// +// An invalid message often corresponds to a nil pointer of the concrete +// message type, but the details are implementation dependent. +// Validity is not part of the protobuf data model, and may not +// be preserved in marshaling or other operations. +func (x *fastReflection_QueryAccountRequest) IsValid() bool { + return x != nil +} + +// ProtoMethods returns optional fastReflectionFeature-path implementations of various operations. +// This method may return nil. +// +// The returned methods type is identical to +// "google.golang.org/protobuf/runtime/protoiface".Methods. +// Consult the protoiface package documentation for details. +func (x *fastReflection_QueryAccountRequest) ProtoMethods() *protoiface.Methods { + size := func(input protoiface.SizeInput) protoiface.SizeOutput { + x := input.Message.Interface().(*QueryAccountRequest) + if x == nil { + return protoiface.SizeOutput{ + NoUnkeyedLiterals: input.NoUnkeyedLiterals, + Size: 0, + } + } + options := runtime.SizeInputToOptions(input) + _ = options + var n int + var l int + _ = l + l = len(x.Address) + if l > 0 { + n += 1 + l + runtime.Sov(uint64(l)) + } + if x.unknownFields != nil { + n += len(x.unknownFields) + } + return protoiface.SizeOutput{ + NoUnkeyedLiterals: input.NoUnkeyedLiterals, + Size: n, + } + } + + marshal := func(input protoiface.MarshalInput) (protoiface.MarshalOutput, error) { + x := input.Message.Interface().(*QueryAccountRequest) + if x == nil { + return protoiface.MarshalOutput{ + NoUnkeyedLiterals: input.NoUnkeyedLiterals, + Buf: input.Buf, + }, nil + } + options := runtime.MarshalInputToOptions(input) + _ = options + size := options.Size(x) + dAtA := make([]byte, size) + i := len(dAtA) + _ = i + var l int + _ = l + if x.unknownFields != nil { + i -= len(x.unknownFields) + copy(dAtA[i:], x.unknownFields) + } + if len(x.Address) > 0 { + i -= len(x.Address) + copy(dAtA[i:], x.Address) + i = runtime.EncodeVarint(dAtA, i, uint64(len(x.Address))) + i-- + dAtA[i] = 0xa + } + if input.Buf != nil { + input.Buf = append(input.Buf, dAtA...) + } else { + input.Buf = dAtA + } + return protoiface.MarshalOutput{ + NoUnkeyedLiterals: input.NoUnkeyedLiterals, + Buf: input.Buf, + }, nil + } + unmarshal := func(input protoiface.UnmarshalInput) (protoiface.UnmarshalOutput, error) { + x := input.Message.Interface().(*QueryAccountRequest) + if x == nil { + return protoiface.UnmarshalOutput{ + NoUnkeyedLiterals: input.NoUnkeyedLiterals, + Flags: input.Flags, + }, nil + } + options := runtime.UnmarshalInputToOptions(input) + _ = options + dAtA := input.Buf + l := len(dAtA) + iNdEx := 0 + for iNdEx < l { + preIndex := iNdEx + var wire uint64 + for shift := uint(0); ; shift += 7 { + if shift >= 64 { + return protoiface.UnmarshalOutput{NoUnkeyedLiterals: input.NoUnkeyedLiterals, Flags: input.Flags}, runtime.ErrIntOverflow + } + if iNdEx >= l { + return protoiface.UnmarshalOutput{NoUnkeyedLiterals: input.NoUnkeyedLiterals, Flags: input.Flags}, io.ErrUnexpectedEOF + } + b := dAtA[iNdEx] + iNdEx++ + wire |= uint64(b&0x7F) << shift + if b < 0x80 { + break + } + } + fieldNum := int32(wire >> 3) + wireType := int(wire & 0x7) + if wireType == 4 { + return protoiface.UnmarshalOutput{NoUnkeyedLiterals: input.NoUnkeyedLiterals, Flags: input.Flags}, fmt.Errorf("proto: QueryAccountRequest: wiretype end group for non-group") + } + if fieldNum <= 0 { + return protoiface.UnmarshalOutput{NoUnkeyedLiterals: input.NoUnkeyedLiterals, Flags: input.Flags}, fmt.Errorf("proto: QueryAccountRequest: illegal tag %d (wire type %d)", fieldNum, wire) + } + switch fieldNum { + case 1: + if wireType != 2 { + return protoiface.UnmarshalOutput{NoUnkeyedLiterals: input.NoUnkeyedLiterals, Flags: input.Flags}, fmt.Errorf("proto: wrong wireType = %d for field Address", wireType) + } + var stringLen uint64 + for shift := uint(0); ; shift += 7 { + if shift >= 64 { + return protoiface.UnmarshalOutput{NoUnkeyedLiterals: input.NoUnkeyedLiterals, Flags: input.Flags}, runtime.ErrIntOverflow + } + if iNdEx >= l { + return protoiface.UnmarshalOutput{NoUnkeyedLiterals: input.NoUnkeyedLiterals, Flags: input.Flags}, io.ErrUnexpectedEOF + } + b := dAtA[iNdEx] + iNdEx++ + stringLen |= uint64(b&0x7F) << shift + if b < 0x80 { + break + } + } + intStringLen := int(stringLen) + if intStringLen < 0 { + return protoiface.UnmarshalOutput{NoUnkeyedLiterals: input.NoUnkeyedLiterals, Flags: input.Flags}, runtime.ErrInvalidLength + } + postIndex := iNdEx + intStringLen + if postIndex < 0 { + return protoiface.UnmarshalOutput{NoUnkeyedLiterals: input.NoUnkeyedLiterals, Flags: input.Flags}, runtime.ErrInvalidLength + } + if postIndex > l { + return protoiface.UnmarshalOutput{NoUnkeyedLiterals: input.NoUnkeyedLiterals, Flags: input.Flags}, io.ErrUnexpectedEOF + } + x.Address = string(dAtA[iNdEx:postIndex]) + iNdEx = postIndex + default: + iNdEx = preIndex + skippy, err := runtime.Skip(dAtA[iNdEx:]) + if err != nil { + return protoiface.UnmarshalOutput{NoUnkeyedLiterals: input.NoUnkeyedLiterals, Flags: input.Flags}, err + } + if (skippy < 0) || (iNdEx+skippy) < 0 { + return protoiface.UnmarshalOutput{NoUnkeyedLiterals: input.NoUnkeyedLiterals, Flags: input.Flags}, runtime.ErrInvalidLength + } + if (iNdEx + skippy) > l { + return protoiface.UnmarshalOutput{NoUnkeyedLiterals: input.NoUnkeyedLiterals, Flags: input.Flags}, io.ErrUnexpectedEOF + } + if !options.DiscardUnknown { + x.unknownFields = append(x.unknownFields, dAtA[iNdEx:iNdEx+skippy]...) + } + iNdEx += skippy + } + } + + if iNdEx > l { + return protoiface.UnmarshalOutput{NoUnkeyedLiterals: input.NoUnkeyedLiterals, Flags: input.Flags}, io.ErrUnexpectedEOF + } + return protoiface.UnmarshalOutput{NoUnkeyedLiterals: input.NoUnkeyedLiterals, Flags: input.Flags}, nil + } + return &protoiface.Methods{ + NoUnkeyedLiterals: struct{}{}, + Flags: protoiface.SupportMarshalDeterministic | protoiface.SupportUnmarshalDiscardUnknown, + Size: size, + Marshal: marshal, + Unmarshal: unmarshal, + Merge: nil, + CheckInitialized: nil, + } +} + +var ( + md_AccountResponse protoreflect.MessageDescriptor + fd_AccountResponse_permission protoreflect.FieldDescriptor +) + +func init() { + file_cosmos_circuit_v1_query_proto_init() + md_AccountResponse = File_cosmos_circuit_v1_query_proto.Messages().ByName("AccountResponse") + fd_AccountResponse_permission = md_AccountResponse.Fields().ByName("permission") +} + +var _ protoreflect.Message = (*fastReflection_AccountResponse)(nil) + +type fastReflection_AccountResponse AccountResponse + +func (x *AccountResponse) ProtoReflect() protoreflect.Message { + return (*fastReflection_AccountResponse)(x) +} + +func (x *AccountResponse) slowProtoReflect() protoreflect.Message { + mi := &file_cosmos_circuit_v1_query_proto_msgTypes[1] + if protoimpl.UnsafeEnabled && x != nil { + ms := protoimpl.X.MessageStateOf(protoimpl.Pointer(x)) + if ms.LoadMessageInfo() == nil { + ms.StoreMessageInfo(mi) + } + return ms + } + return mi.MessageOf(x) +} + +var _fastReflection_AccountResponse_messageType fastReflection_AccountResponse_messageType +var _ protoreflect.MessageType = fastReflection_AccountResponse_messageType{} + +type fastReflection_AccountResponse_messageType struct{} + +func (x fastReflection_AccountResponse_messageType) Zero() protoreflect.Message { + return (*fastReflection_AccountResponse)(nil) +} +func (x fastReflection_AccountResponse_messageType) New() protoreflect.Message { + return new(fastReflection_AccountResponse) +} +func (x fastReflection_AccountResponse_messageType) Descriptor() protoreflect.MessageDescriptor { + return md_AccountResponse +} + +// Descriptor returns message descriptor, which contains only the protobuf +// type information for the message. +func (x *fastReflection_AccountResponse) Descriptor() protoreflect.MessageDescriptor { + return md_AccountResponse +} + +// Type returns the message type, which encapsulates both Go and protobuf +// type information. If the Go type information is not needed, +// it is recommended that the message descriptor be used instead. +func (x *fastReflection_AccountResponse) Type() protoreflect.MessageType { + return _fastReflection_AccountResponse_messageType +} + +// New returns a newly allocated and mutable empty message. +func (x *fastReflection_AccountResponse) New() protoreflect.Message { + return new(fastReflection_AccountResponse) +} + +// Interface unwraps the message reflection interface and +// returns the underlying ProtoMessage interface. +func (x *fastReflection_AccountResponse) Interface() protoreflect.ProtoMessage { + return (*AccountResponse)(x) +} + +// Range iterates over every populated field in an undefined order, +// calling f for each field descriptor and value encountered. +// Range returns immediately if f returns false. +// While iterating, mutating operations may only be performed +// on the current field descriptor. +func (x *fastReflection_AccountResponse) Range(f func(protoreflect.FieldDescriptor, protoreflect.Value) bool) { + if x.Permission != nil { + value := protoreflect.ValueOfMessage(x.Permission.ProtoReflect()) + if !f(fd_AccountResponse_permission, value) { + return + } + } +} + +// Has reports whether a field is populated. +// +// Some fields have the property of nullability where it is possible to +// distinguish between the default value of a field and whether the field +// was explicitly populated with the default value. Singular message fields, +// member fields of a oneof, and proto2 scalar fields are nullable. Such +// fields are populated only if explicitly set. +// +// In other cases (aside from the nullable cases above), +// a proto3 scalar field is populated if it contains a non-zero value, and +// a repeated field is populated if it is non-empty. +func (x *fastReflection_AccountResponse) Has(fd protoreflect.FieldDescriptor) bool { + switch fd.FullName() { + case "cosmos.circuit.v1.AccountResponse.permission": + return x.Permission != nil + default: + if fd.IsExtension() { + panic(fmt.Errorf("proto3 declared messages do not support extensions: cosmos.circuit.v1.AccountResponse")) + } + panic(fmt.Errorf("message cosmos.circuit.v1.AccountResponse does not contain field %s", fd.FullName())) + } +} + +// Clear clears the field such that a subsequent Has call reports false. +// +// Clearing an extension field clears both the extension type and value +// associated with the given field number. +// +// Clear is a mutating operation and unsafe for concurrent use. +func (x *fastReflection_AccountResponse) Clear(fd protoreflect.FieldDescriptor) { + switch fd.FullName() { + case "cosmos.circuit.v1.AccountResponse.permission": + x.Permission = nil + default: + if fd.IsExtension() { + panic(fmt.Errorf("proto3 declared messages do not support extensions: cosmos.circuit.v1.AccountResponse")) + } + panic(fmt.Errorf("message cosmos.circuit.v1.AccountResponse does not contain field %s", fd.FullName())) + } +} + +// Get retrieves the value for a field. +// +// For unpopulated scalars, it returns the default value, where +// the default value of a bytes scalar is guaranteed to be a copy. +// For unpopulated composite types, it returns an empty, read-only view +// of the value; to obtain a mutable reference, use Mutable. +func (x *fastReflection_AccountResponse) Get(descriptor protoreflect.FieldDescriptor) protoreflect.Value { + switch descriptor.FullName() { + case "cosmos.circuit.v1.AccountResponse.permission": + value := x.Permission + return protoreflect.ValueOfMessage(value.ProtoReflect()) + default: + if descriptor.IsExtension() { + panic(fmt.Errorf("proto3 declared messages do not support extensions: cosmos.circuit.v1.AccountResponse")) + } + panic(fmt.Errorf("message cosmos.circuit.v1.AccountResponse does not contain field %s", descriptor.FullName())) + } +} + +// Set stores the value for a field. +// +// For a field belonging to a oneof, it implicitly clears any other field +// that may be currently set within the same oneof. +// For extension fields, it implicitly stores the provided ExtensionType. +// When setting a composite type, it is unspecified whether the stored value +// aliases the source's memory in any way. If the composite value is an +// empty, read-only value, then it panics. +// +// Set is a mutating operation and unsafe for concurrent use. +func (x *fastReflection_AccountResponse) Set(fd protoreflect.FieldDescriptor, value protoreflect.Value) { + switch fd.FullName() { + case "cosmos.circuit.v1.AccountResponse.permission": + x.Permission = value.Message().Interface().(*Permissions) + default: + if fd.IsExtension() { + panic(fmt.Errorf("proto3 declared messages do not support extensions: cosmos.circuit.v1.AccountResponse")) + } + panic(fmt.Errorf("message cosmos.circuit.v1.AccountResponse does not contain field %s", fd.FullName())) + } +} + +// Mutable returns a mutable reference to a composite type. +// +// If the field is unpopulated, it may allocate a composite value. +// For a field belonging to a oneof, it implicitly clears any other field +// that may be currently set within the same oneof. +// For extension fields, it implicitly stores the provided ExtensionType +// if not already stored. +// It panics if the field does not contain a composite type. +// +// Mutable is a mutating operation and unsafe for concurrent use. +func (x *fastReflection_AccountResponse) Mutable(fd protoreflect.FieldDescriptor) protoreflect.Value { + switch fd.FullName() { + case "cosmos.circuit.v1.AccountResponse.permission": + if x.Permission == nil { + x.Permission = new(Permissions) + } + return protoreflect.ValueOfMessage(x.Permission.ProtoReflect()) + default: + if fd.IsExtension() { + panic(fmt.Errorf("proto3 declared messages do not support extensions: cosmos.circuit.v1.AccountResponse")) + } + panic(fmt.Errorf("message cosmos.circuit.v1.AccountResponse does not contain field %s", fd.FullName())) + } +} + +// NewField returns a new value that is assignable to the field +// for the given descriptor. For scalars, this returns the default value. +// For lists, maps, and messages, this returns a new, empty, mutable value. +func (x *fastReflection_AccountResponse) NewField(fd protoreflect.FieldDescriptor) protoreflect.Value { + switch fd.FullName() { + case "cosmos.circuit.v1.AccountResponse.permission": + m := new(Permissions) + return protoreflect.ValueOfMessage(m.ProtoReflect()) + default: + if fd.IsExtension() { + panic(fmt.Errorf("proto3 declared messages do not support extensions: cosmos.circuit.v1.AccountResponse")) + } + panic(fmt.Errorf("message cosmos.circuit.v1.AccountResponse does not contain field %s", fd.FullName())) + } +} + +// WhichOneof reports which field within the oneof is populated, +// returning nil if none are populated. +// It panics if the oneof descriptor does not belong to this message. +func (x *fastReflection_AccountResponse) WhichOneof(d protoreflect.OneofDescriptor) protoreflect.FieldDescriptor { + switch d.FullName() { + default: + panic(fmt.Errorf("%s is not a oneof field in cosmos.circuit.v1.AccountResponse", d.FullName())) + } + panic("unreachable") +} + +// GetUnknown retrieves the entire list of unknown fields. +// The caller may only mutate the contents of the RawFields +// if the mutated bytes are stored back into the message with SetUnknown. +func (x *fastReflection_AccountResponse) GetUnknown() protoreflect.RawFields { + return x.unknownFields +} + +// SetUnknown stores an entire list of unknown fields. +// The raw fields must be syntactically valid according to the wire format. +// An implementation may panic if this is not the case. +// Once stored, the caller must not mutate the content of the RawFields. +// An empty RawFields may be passed to clear the fields. +// +// SetUnknown is a mutating operation and unsafe for concurrent use. +func (x *fastReflection_AccountResponse) SetUnknown(fields protoreflect.RawFields) { + x.unknownFields = fields +} + +// IsValid reports whether the message is valid. +// +// An invalid message is an empty, read-only value. +// +// An invalid message often corresponds to a nil pointer of the concrete +// message type, but the details are implementation dependent. +// Validity is not part of the protobuf data model, and may not +// be preserved in marshaling or other operations. +func (x *fastReflection_AccountResponse) IsValid() bool { + return x != nil +} + +// ProtoMethods returns optional fastReflectionFeature-path implementations of various operations. +// This method may return nil. +// +// The returned methods type is identical to +// "google.golang.org/protobuf/runtime/protoiface".Methods. +// Consult the protoiface package documentation for details. +func (x *fastReflection_AccountResponse) ProtoMethods() *protoiface.Methods { + size := func(input protoiface.SizeInput) protoiface.SizeOutput { + x := input.Message.Interface().(*AccountResponse) + if x == nil { + return protoiface.SizeOutput{ + NoUnkeyedLiterals: input.NoUnkeyedLiterals, + Size: 0, + } + } + options := runtime.SizeInputToOptions(input) + _ = options + var n int + var l int + _ = l + if x.Permission != nil { + l = options.Size(x.Permission) + n += 1 + l + runtime.Sov(uint64(l)) + } + if x.unknownFields != nil { + n += len(x.unknownFields) + } + return protoiface.SizeOutput{ + NoUnkeyedLiterals: input.NoUnkeyedLiterals, + Size: n, + } + } + + marshal := func(input protoiface.MarshalInput) (protoiface.MarshalOutput, error) { + x := input.Message.Interface().(*AccountResponse) + if x == nil { + return protoiface.MarshalOutput{ + NoUnkeyedLiterals: input.NoUnkeyedLiterals, + Buf: input.Buf, + }, nil + } + options := runtime.MarshalInputToOptions(input) + _ = options + size := options.Size(x) + dAtA := make([]byte, size) + i := len(dAtA) + _ = i + var l int + _ = l + if x.unknownFields != nil { + i -= len(x.unknownFields) + copy(dAtA[i:], x.unknownFields) + } + if x.Permission != nil { + encoded, err := options.Marshal(x.Permission) + if err != nil { + return protoiface.MarshalOutput{ + NoUnkeyedLiterals: input.NoUnkeyedLiterals, + Buf: input.Buf, + }, err + } + i -= len(encoded) + copy(dAtA[i:], encoded) + i = runtime.EncodeVarint(dAtA, i, uint64(len(encoded))) + i-- + dAtA[i] = 0xa + } + if input.Buf != nil { + input.Buf = append(input.Buf, dAtA...) + } else { + input.Buf = dAtA + } + return protoiface.MarshalOutput{ + NoUnkeyedLiterals: input.NoUnkeyedLiterals, + Buf: input.Buf, + }, nil + } + unmarshal := func(input protoiface.UnmarshalInput) (protoiface.UnmarshalOutput, error) { + x := input.Message.Interface().(*AccountResponse) + if x == nil { + return protoiface.UnmarshalOutput{ + NoUnkeyedLiterals: input.NoUnkeyedLiterals, + Flags: input.Flags, + }, nil + } + options := runtime.UnmarshalInputToOptions(input) + _ = options + dAtA := input.Buf + l := len(dAtA) + iNdEx := 0 + for iNdEx < l { + preIndex := iNdEx + var wire uint64 + for shift := uint(0); ; shift += 7 { + if shift >= 64 { + return protoiface.UnmarshalOutput{NoUnkeyedLiterals: input.NoUnkeyedLiterals, Flags: input.Flags}, runtime.ErrIntOverflow + } + if iNdEx >= l { + return protoiface.UnmarshalOutput{NoUnkeyedLiterals: input.NoUnkeyedLiterals, Flags: input.Flags}, io.ErrUnexpectedEOF + } + b := dAtA[iNdEx] + iNdEx++ + wire |= uint64(b&0x7F) << shift + if b < 0x80 { + break + } + } + fieldNum := int32(wire >> 3) + wireType := int(wire & 0x7) + if wireType == 4 { + return protoiface.UnmarshalOutput{NoUnkeyedLiterals: input.NoUnkeyedLiterals, Flags: input.Flags}, fmt.Errorf("proto: AccountResponse: wiretype end group for non-group") + } + if fieldNum <= 0 { + return protoiface.UnmarshalOutput{NoUnkeyedLiterals: input.NoUnkeyedLiterals, Flags: input.Flags}, fmt.Errorf("proto: AccountResponse: illegal tag %d (wire type %d)", fieldNum, wire) + } + switch fieldNum { + case 1: + if wireType != 2 { + return protoiface.UnmarshalOutput{NoUnkeyedLiterals: input.NoUnkeyedLiterals, Flags: input.Flags}, fmt.Errorf("proto: wrong wireType = %d for field Permission", wireType) + } + var msglen int + for shift := uint(0); ; shift += 7 { + if shift >= 64 { + return protoiface.UnmarshalOutput{NoUnkeyedLiterals: input.NoUnkeyedLiterals, Flags: input.Flags}, runtime.ErrIntOverflow + } + if iNdEx >= l { + return protoiface.UnmarshalOutput{NoUnkeyedLiterals: input.NoUnkeyedLiterals, Flags: input.Flags}, io.ErrUnexpectedEOF + } + b := dAtA[iNdEx] + iNdEx++ + msglen |= int(b&0x7F) << shift + if b < 0x80 { + break + } + } + if msglen < 0 { + return protoiface.UnmarshalOutput{NoUnkeyedLiterals: input.NoUnkeyedLiterals, Flags: input.Flags}, runtime.ErrInvalidLength + } + postIndex := iNdEx + msglen + if postIndex < 0 { + return protoiface.UnmarshalOutput{NoUnkeyedLiterals: input.NoUnkeyedLiterals, Flags: input.Flags}, runtime.ErrInvalidLength + } + if postIndex > l { + return protoiface.UnmarshalOutput{NoUnkeyedLiterals: input.NoUnkeyedLiterals, Flags: input.Flags}, io.ErrUnexpectedEOF + } + if x.Permission == nil { + x.Permission = &Permissions{} + } + if err := options.Unmarshal(dAtA[iNdEx:postIndex], x.Permission); err != nil { + return protoiface.UnmarshalOutput{NoUnkeyedLiterals: input.NoUnkeyedLiterals, Flags: input.Flags}, err + } + iNdEx = postIndex + default: + iNdEx = preIndex + skippy, err := runtime.Skip(dAtA[iNdEx:]) + if err != nil { + return protoiface.UnmarshalOutput{NoUnkeyedLiterals: input.NoUnkeyedLiterals, Flags: input.Flags}, err + } + if (skippy < 0) || (iNdEx+skippy) < 0 { + return protoiface.UnmarshalOutput{NoUnkeyedLiterals: input.NoUnkeyedLiterals, Flags: input.Flags}, runtime.ErrInvalidLength + } + if (iNdEx + skippy) > l { + return protoiface.UnmarshalOutput{NoUnkeyedLiterals: input.NoUnkeyedLiterals, Flags: input.Flags}, io.ErrUnexpectedEOF + } + if !options.DiscardUnknown { + x.unknownFields = append(x.unknownFields, dAtA[iNdEx:iNdEx+skippy]...) + } + iNdEx += skippy + } + } + + if iNdEx > l { + return protoiface.UnmarshalOutput{NoUnkeyedLiterals: input.NoUnkeyedLiterals, Flags: input.Flags}, io.ErrUnexpectedEOF + } + return protoiface.UnmarshalOutput{NoUnkeyedLiterals: input.NoUnkeyedLiterals, Flags: input.Flags}, nil + } + return &protoiface.Methods{ + NoUnkeyedLiterals: struct{}{}, + Flags: protoiface.SupportMarshalDeterministic | protoiface.SupportUnmarshalDiscardUnknown, + Size: size, + Marshal: marshal, + Unmarshal: unmarshal, + Merge: nil, + CheckInitialized: nil, + } +} + +var ( + md_QueryAccountsRequest protoreflect.MessageDescriptor + fd_QueryAccountsRequest_pagination protoreflect.FieldDescriptor +) + +func init() { + file_cosmos_circuit_v1_query_proto_init() + md_QueryAccountsRequest = File_cosmos_circuit_v1_query_proto.Messages().ByName("QueryAccountsRequest") + fd_QueryAccountsRequest_pagination = md_QueryAccountsRequest.Fields().ByName("pagination") +} + +var _ protoreflect.Message = (*fastReflection_QueryAccountsRequest)(nil) + +type fastReflection_QueryAccountsRequest QueryAccountsRequest + +func (x *QueryAccountsRequest) ProtoReflect() protoreflect.Message { + return (*fastReflection_QueryAccountsRequest)(x) +} + +func (x *QueryAccountsRequest) slowProtoReflect() protoreflect.Message { + mi := &file_cosmos_circuit_v1_query_proto_msgTypes[2] + if protoimpl.UnsafeEnabled && x != nil { + ms := protoimpl.X.MessageStateOf(protoimpl.Pointer(x)) + if ms.LoadMessageInfo() == nil { + ms.StoreMessageInfo(mi) + } + return ms + } + return mi.MessageOf(x) +} + +var _fastReflection_QueryAccountsRequest_messageType fastReflection_QueryAccountsRequest_messageType +var _ protoreflect.MessageType = fastReflection_QueryAccountsRequest_messageType{} + +type fastReflection_QueryAccountsRequest_messageType struct{} + +func (x fastReflection_QueryAccountsRequest_messageType) Zero() protoreflect.Message { + return (*fastReflection_QueryAccountsRequest)(nil) +} +func (x fastReflection_QueryAccountsRequest_messageType) New() protoreflect.Message { + return new(fastReflection_QueryAccountsRequest) +} +func (x fastReflection_QueryAccountsRequest_messageType) Descriptor() protoreflect.MessageDescriptor { + return md_QueryAccountsRequest +} + +// Descriptor returns message descriptor, which contains only the protobuf +// type information for the message. +func (x *fastReflection_QueryAccountsRequest) Descriptor() protoreflect.MessageDescriptor { + return md_QueryAccountsRequest +} + +// Type returns the message type, which encapsulates both Go and protobuf +// type information. If the Go type information is not needed, +// it is recommended that the message descriptor be used instead. +func (x *fastReflection_QueryAccountsRequest) Type() protoreflect.MessageType { + return _fastReflection_QueryAccountsRequest_messageType +} + +// New returns a newly allocated and mutable empty message. +func (x *fastReflection_QueryAccountsRequest) New() protoreflect.Message { + return new(fastReflection_QueryAccountsRequest) +} + +// Interface unwraps the message reflection interface and +// returns the underlying ProtoMessage interface. +func (x *fastReflection_QueryAccountsRequest) Interface() protoreflect.ProtoMessage { + return (*QueryAccountsRequest)(x) +} + +// Range iterates over every populated field in an undefined order, +// calling f for each field descriptor and value encountered. +// Range returns immediately if f returns false. +// While iterating, mutating operations may only be performed +// on the current field descriptor. +func (x *fastReflection_QueryAccountsRequest) Range(f func(protoreflect.FieldDescriptor, protoreflect.Value) bool) { + if x.Pagination != nil { + value := protoreflect.ValueOfMessage(x.Pagination.ProtoReflect()) + if !f(fd_QueryAccountsRequest_pagination, value) { + return + } + } +} + +// Has reports whether a field is populated. +// +// Some fields have the property of nullability where it is possible to +// distinguish between the default value of a field and whether the field +// was explicitly populated with the default value. Singular message fields, +// member fields of a oneof, and proto2 scalar fields are nullable. Such +// fields are populated only if explicitly set. +// +// In other cases (aside from the nullable cases above), +// a proto3 scalar field is populated if it contains a non-zero value, and +// a repeated field is populated if it is non-empty. +func (x *fastReflection_QueryAccountsRequest) Has(fd protoreflect.FieldDescriptor) bool { + switch fd.FullName() { + case "cosmos.circuit.v1.QueryAccountsRequest.pagination": + return x.Pagination != nil + default: + if fd.IsExtension() { + panic(fmt.Errorf("proto3 declared messages do not support extensions: cosmos.circuit.v1.QueryAccountsRequest")) + } + panic(fmt.Errorf("message cosmos.circuit.v1.QueryAccountsRequest does not contain field %s", fd.FullName())) + } +} + +// Clear clears the field such that a subsequent Has call reports false. +// +// Clearing an extension field clears both the extension type and value +// associated with the given field number. +// +// Clear is a mutating operation and unsafe for concurrent use. +func (x *fastReflection_QueryAccountsRequest) Clear(fd protoreflect.FieldDescriptor) { + switch fd.FullName() { + case "cosmos.circuit.v1.QueryAccountsRequest.pagination": + x.Pagination = nil + default: + if fd.IsExtension() { + panic(fmt.Errorf("proto3 declared messages do not support extensions: cosmos.circuit.v1.QueryAccountsRequest")) + } + panic(fmt.Errorf("message cosmos.circuit.v1.QueryAccountsRequest does not contain field %s", fd.FullName())) + } +} + +// Get retrieves the value for a field. +// +// For unpopulated scalars, it returns the default value, where +// the default value of a bytes scalar is guaranteed to be a copy. +// For unpopulated composite types, it returns an empty, read-only view +// of the value; to obtain a mutable reference, use Mutable. +func (x *fastReflection_QueryAccountsRequest) Get(descriptor protoreflect.FieldDescriptor) protoreflect.Value { + switch descriptor.FullName() { + case "cosmos.circuit.v1.QueryAccountsRequest.pagination": + value := x.Pagination + return protoreflect.ValueOfMessage(value.ProtoReflect()) + default: + if descriptor.IsExtension() { + panic(fmt.Errorf("proto3 declared messages do not support extensions: cosmos.circuit.v1.QueryAccountsRequest")) + } + panic(fmt.Errorf("message cosmos.circuit.v1.QueryAccountsRequest does not contain field %s", descriptor.FullName())) + } +} + +// Set stores the value for a field. +// +// For a field belonging to a oneof, it implicitly clears any other field +// that may be currently set within the same oneof. +// For extension fields, it implicitly stores the provided ExtensionType. +// When setting a composite type, it is unspecified whether the stored value +// aliases the source's memory in any way. If the composite value is an +// empty, read-only value, then it panics. +// +// Set is a mutating operation and unsafe for concurrent use. +func (x *fastReflection_QueryAccountsRequest) Set(fd protoreflect.FieldDescriptor, value protoreflect.Value) { + switch fd.FullName() { + case "cosmos.circuit.v1.QueryAccountsRequest.pagination": + x.Pagination = value.Message().Interface().(*v1beta1.PageRequest) + default: + if fd.IsExtension() { + panic(fmt.Errorf("proto3 declared messages do not support extensions: cosmos.circuit.v1.QueryAccountsRequest")) + } + panic(fmt.Errorf("message cosmos.circuit.v1.QueryAccountsRequest does not contain field %s", fd.FullName())) + } +} + +// Mutable returns a mutable reference to a composite type. +// +// If the field is unpopulated, it may allocate a composite value. +// For a field belonging to a oneof, it implicitly clears any other field +// that may be currently set within the same oneof. +// For extension fields, it implicitly stores the provided ExtensionType +// if not already stored. +// It panics if the field does not contain a composite type. +// +// Mutable is a mutating operation and unsafe for concurrent use. +func (x *fastReflection_QueryAccountsRequest) Mutable(fd protoreflect.FieldDescriptor) protoreflect.Value { + switch fd.FullName() { + case "cosmos.circuit.v1.QueryAccountsRequest.pagination": + if x.Pagination == nil { + x.Pagination = new(v1beta1.PageRequest) + } + return protoreflect.ValueOfMessage(x.Pagination.ProtoReflect()) + default: + if fd.IsExtension() { + panic(fmt.Errorf("proto3 declared messages do not support extensions: cosmos.circuit.v1.QueryAccountsRequest")) + } + panic(fmt.Errorf("message cosmos.circuit.v1.QueryAccountsRequest does not contain field %s", fd.FullName())) + } +} + +// NewField returns a new value that is assignable to the field +// for the given descriptor. For scalars, this returns the default value. +// For lists, maps, and messages, this returns a new, empty, mutable value. +func (x *fastReflection_QueryAccountsRequest) NewField(fd protoreflect.FieldDescriptor) protoreflect.Value { + switch fd.FullName() { + case "cosmos.circuit.v1.QueryAccountsRequest.pagination": + m := new(v1beta1.PageRequest) + return protoreflect.ValueOfMessage(m.ProtoReflect()) + default: + if fd.IsExtension() { + panic(fmt.Errorf("proto3 declared messages do not support extensions: cosmos.circuit.v1.QueryAccountsRequest")) + } + panic(fmt.Errorf("message cosmos.circuit.v1.QueryAccountsRequest does not contain field %s", fd.FullName())) + } +} + +// WhichOneof reports which field within the oneof is populated, +// returning nil if none are populated. +// It panics if the oneof descriptor does not belong to this message. +func (x *fastReflection_QueryAccountsRequest) WhichOneof(d protoreflect.OneofDescriptor) protoreflect.FieldDescriptor { + switch d.FullName() { + default: + panic(fmt.Errorf("%s is not a oneof field in cosmos.circuit.v1.QueryAccountsRequest", d.FullName())) + } + panic("unreachable") +} + +// GetUnknown retrieves the entire list of unknown fields. +// The caller may only mutate the contents of the RawFields +// if the mutated bytes are stored back into the message with SetUnknown. +func (x *fastReflection_QueryAccountsRequest) GetUnknown() protoreflect.RawFields { + return x.unknownFields +} + +// SetUnknown stores an entire list of unknown fields. +// The raw fields must be syntactically valid according to the wire format. +// An implementation may panic if this is not the case. +// Once stored, the caller must not mutate the content of the RawFields. +// An empty RawFields may be passed to clear the fields. +// +// SetUnknown is a mutating operation and unsafe for concurrent use. +func (x *fastReflection_QueryAccountsRequest) SetUnknown(fields protoreflect.RawFields) { + x.unknownFields = fields +} + +// IsValid reports whether the message is valid. +// +// An invalid message is an empty, read-only value. +// +// An invalid message often corresponds to a nil pointer of the concrete +// message type, but the details are implementation dependent. +// Validity is not part of the protobuf data model, and may not +// be preserved in marshaling or other operations. +func (x *fastReflection_QueryAccountsRequest) IsValid() bool { + return x != nil +} + +// ProtoMethods returns optional fastReflectionFeature-path implementations of various operations. +// This method may return nil. +// +// The returned methods type is identical to +// "google.golang.org/protobuf/runtime/protoiface".Methods. +// Consult the protoiface package documentation for details. +func (x *fastReflection_QueryAccountsRequest) ProtoMethods() *protoiface.Methods { + size := func(input protoiface.SizeInput) protoiface.SizeOutput { + x := input.Message.Interface().(*QueryAccountsRequest) + if x == nil { + return protoiface.SizeOutput{ + NoUnkeyedLiterals: input.NoUnkeyedLiterals, + Size: 0, + } + } + options := runtime.SizeInputToOptions(input) + _ = options + var n int + var l int + _ = l + if x.Pagination != nil { + l = options.Size(x.Pagination) + n += 1 + l + runtime.Sov(uint64(l)) + } + if x.unknownFields != nil { + n += len(x.unknownFields) + } + return protoiface.SizeOutput{ + NoUnkeyedLiterals: input.NoUnkeyedLiterals, + Size: n, + } + } + + marshal := func(input protoiface.MarshalInput) (protoiface.MarshalOutput, error) { + x := input.Message.Interface().(*QueryAccountsRequest) + if x == nil { + return protoiface.MarshalOutput{ + NoUnkeyedLiterals: input.NoUnkeyedLiterals, + Buf: input.Buf, + }, nil + } + options := runtime.MarshalInputToOptions(input) + _ = options + size := options.Size(x) + dAtA := make([]byte, size) + i := len(dAtA) + _ = i + var l int + _ = l + if x.unknownFields != nil { + i -= len(x.unknownFields) + copy(dAtA[i:], x.unknownFields) + } + if x.Pagination != nil { + encoded, err := options.Marshal(x.Pagination) + if err != nil { + return protoiface.MarshalOutput{ + NoUnkeyedLiterals: input.NoUnkeyedLiterals, + Buf: input.Buf, + }, err + } + i -= len(encoded) + copy(dAtA[i:], encoded) + i = runtime.EncodeVarint(dAtA, i, uint64(len(encoded))) + i-- + dAtA[i] = 0xa + } + if input.Buf != nil { + input.Buf = append(input.Buf, dAtA...) + } else { + input.Buf = dAtA + } + return protoiface.MarshalOutput{ + NoUnkeyedLiterals: input.NoUnkeyedLiterals, + Buf: input.Buf, + }, nil + } + unmarshal := func(input protoiface.UnmarshalInput) (protoiface.UnmarshalOutput, error) { + x := input.Message.Interface().(*QueryAccountsRequest) + if x == nil { + return protoiface.UnmarshalOutput{ + NoUnkeyedLiterals: input.NoUnkeyedLiterals, + Flags: input.Flags, + }, nil + } + options := runtime.UnmarshalInputToOptions(input) + _ = options + dAtA := input.Buf + l := len(dAtA) + iNdEx := 0 + for iNdEx < l { + preIndex := iNdEx + var wire uint64 + for shift := uint(0); ; shift += 7 { + if shift >= 64 { + return protoiface.UnmarshalOutput{NoUnkeyedLiterals: input.NoUnkeyedLiterals, Flags: input.Flags}, runtime.ErrIntOverflow + } + if iNdEx >= l { + return protoiface.UnmarshalOutput{NoUnkeyedLiterals: input.NoUnkeyedLiterals, Flags: input.Flags}, io.ErrUnexpectedEOF + } + b := dAtA[iNdEx] + iNdEx++ + wire |= uint64(b&0x7F) << shift + if b < 0x80 { + break + } + } + fieldNum := int32(wire >> 3) + wireType := int(wire & 0x7) + if wireType == 4 { + return protoiface.UnmarshalOutput{NoUnkeyedLiterals: input.NoUnkeyedLiterals, Flags: input.Flags}, fmt.Errorf("proto: QueryAccountsRequest: wiretype end group for non-group") + } + if fieldNum <= 0 { + return protoiface.UnmarshalOutput{NoUnkeyedLiterals: input.NoUnkeyedLiterals, Flags: input.Flags}, fmt.Errorf("proto: QueryAccountsRequest: illegal tag %d (wire type %d)", fieldNum, wire) + } + switch fieldNum { + case 1: + if wireType != 2 { + return protoiface.UnmarshalOutput{NoUnkeyedLiterals: input.NoUnkeyedLiterals, Flags: input.Flags}, fmt.Errorf("proto: wrong wireType = %d for field Pagination", wireType) + } + var msglen int + for shift := uint(0); ; shift += 7 { + if shift >= 64 { + return protoiface.UnmarshalOutput{NoUnkeyedLiterals: input.NoUnkeyedLiterals, Flags: input.Flags}, runtime.ErrIntOverflow + } + if iNdEx >= l { + return protoiface.UnmarshalOutput{NoUnkeyedLiterals: input.NoUnkeyedLiterals, Flags: input.Flags}, io.ErrUnexpectedEOF + } + b := dAtA[iNdEx] + iNdEx++ + msglen |= int(b&0x7F) << shift + if b < 0x80 { + break + } + } + if msglen < 0 { + return protoiface.UnmarshalOutput{NoUnkeyedLiterals: input.NoUnkeyedLiterals, Flags: input.Flags}, runtime.ErrInvalidLength + } + postIndex := iNdEx + msglen + if postIndex < 0 { + return protoiface.UnmarshalOutput{NoUnkeyedLiterals: input.NoUnkeyedLiterals, Flags: input.Flags}, runtime.ErrInvalidLength + } + if postIndex > l { + return protoiface.UnmarshalOutput{NoUnkeyedLiterals: input.NoUnkeyedLiterals, Flags: input.Flags}, io.ErrUnexpectedEOF + } + if x.Pagination == nil { + x.Pagination = &v1beta1.PageRequest{} + } + if err := options.Unmarshal(dAtA[iNdEx:postIndex], x.Pagination); err != nil { + return protoiface.UnmarshalOutput{NoUnkeyedLiterals: input.NoUnkeyedLiterals, Flags: input.Flags}, err + } + iNdEx = postIndex + default: + iNdEx = preIndex + skippy, err := runtime.Skip(dAtA[iNdEx:]) + if err != nil { + return protoiface.UnmarshalOutput{NoUnkeyedLiterals: input.NoUnkeyedLiterals, Flags: input.Flags}, err + } + if (skippy < 0) || (iNdEx+skippy) < 0 { + return protoiface.UnmarshalOutput{NoUnkeyedLiterals: input.NoUnkeyedLiterals, Flags: input.Flags}, runtime.ErrInvalidLength + } + if (iNdEx + skippy) > l { + return protoiface.UnmarshalOutput{NoUnkeyedLiterals: input.NoUnkeyedLiterals, Flags: input.Flags}, io.ErrUnexpectedEOF + } + if !options.DiscardUnknown { + x.unknownFields = append(x.unknownFields, dAtA[iNdEx:iNdEx+skippy]...) + } + iNdEx += skippy + } + } + + if iNdEx > l { + return protoiface.UnmarshalOutput{NoUnkeyedLiterals: input.NoUnkeyedLiterals, Flags: input.Flags}, io.ErrUnexpectedEOF + } + return protoiface.UnmarshalOutput{NoUnkeyedLiterals: input.NoUnkeyedLiterals, Flags: input.Flags}, nil + } + return &protoiface.Methods{ + NoUnkeyedLiterals: struct{}{}, + Flags: protoiface.SupportMarshalDeterministic | protoiface.SupportUnmarshalDiscardUnknown, + Size: size, + Marshal: marshal, + Unmarshal: unmarshal, + Merge: nil, + CheckInitialized: nil, + } +} + +var _ protoreflect.List = (*_AccountsResponse_1_list)(nil) + +type _AccountsResponse_1_list struct { + list *[]*GenesisAccountPermissions +} + +func (x *_AccountsResponse_1_list) Len() int { + if x.list == nil { + return 0 + } + return len(*x.list) +} + +func (x *_AccountsResponse_1_list) Get(i int) protoreflect.Value { + return protoreflect.ValueOfMessage((*x.list)[i].ProtoReflect()) +} + +func (x *_AccountsResponse_1_list) Set(i int, value protoreflect.Value) { + valueUnwrapped := value.Message() + concreteValue := valueUnwrapped.Interface().(*GenesisAccountPermissions) + (*x.list)[i] = concreteValue +} + +func (x *_AccountsResponse_1_list) Append(value protoreflect.Value) { + valueUnwrapped := value.Message() + concreteValue := valueUnwrapped.Interface().(*GenesisAccountPermissions) + *x.list = append(*x.list, concreteValue) +} + +func (x *_AccountsResponse_1_list) AppendMutable() protoreflect.Value { + v := new(GenesisAccountPermissions) + *x.list = append(*x.list, v) + return protoreflect.ValueOfMessage(v.ProtoReflect()) +} + +func (x *_AccountsResponse_1_list) Truncate(n int) { + for i := n; i < len(*x.list); i++ { + (*x.list)[i] = nil + } + *x.list = (*x.list)[:n] +} + +func (x *_AccountsResponse_1_list) NewElement() protoreflect.Value { + v := new(GenesisAccountPermissions) + return protoreflect.ValueOfMessage(v.ProtoReflect()) +} + +func (x *_AccountsResponse_1_list) IsValid() bool { + return x.list != nil +} + +var ( + md_AccountsResponse protoreflect.MessageDescriptor + fd_AccountsResponse_accounts protoreflect.FieldDescriptor + fd_AccountsResponse_pagination protoreflect.FieldDescriptor +) + +func init() { + file_cosmos_circuit_v1_query_proto_init() + md_AccountsResponse = File_cosmos_circuit_v1_query_proto.Messages().ByName("AccountsResponse") + fd_AccountsResponse_accounts = md_AccountsResponse.Fields().ByName("accounts") + fd_AccountsResponse_pagination = md_AccountsResponse.Fields().ByName("pagination") +} + +var _ protoreflect.Message = (*fastReflection_AccountsResponse)(nil) + +type fastReflection_AccountsResponse AccountsResponse + +func (x *AccountsResponse) ProtoReflect() protoreflect.Message { + return (*fastReflection_AccountsResponse)(x) +} + +func (x *AccountsResponse) slowProtoReflect() protoreflect.Message { + mi := &file_cosmos_circuit_v1_query_proto_msgTypes[3] + if protoimpl.UnsafeEnabled && x != nil { + ms := protoimpl.X.MessageStateOf(protoimpl.Pointer(x)) + if ms.LoadMessageInfo() == nil { + ms.StoreMessageInfo(mi) + } + return ms + } + return mi.MessageOf(x) +} + +var _fastReflection_AccountsResponse_messageType fastReflection_AccountsResponse_messageType +var _ protoreflect.MessageType = fastReflection_AccountsResponse_messageType{} + +type fastReflection_AccountsResponse_messageType struct{} + +func (x fastReflection_AccountsResponse_messageType) Zero() protoreflect.Message { + return (*fastReflection_AccountsResponse)(nil) +} +func (x fastReflection_AccountsResponse_messageType) New() protoreflect.Message { + return new(fastReflection_AccountsResponse) +} +func (x fastReflection_AccountsResponse_messageType) Descriptor() protoreflect.MessageDescriptor { + return md_AccountsResponse +} + +// Descriptor returns message descriptor, which contains only the protobuf +// type information for the message. +func (x *fastReflection_AccountsResponse) Descriptor() protoreflect.MessageDescriptor { + return md_AccountsResponse +} + +// Type returns the message type, which encapsulates both Go and protobuf +// type information. If the Go type information is not needed, +// it is recommended that the message descriptor be used instead. +func (x *fastReflection_AccountsResponse) Type() protoreflect.MessageType { + return _fastReflection_AccountsResponse_messageType +} + +// New returns a newly allocated and mutable empty message. +func (x *fastReflection_AccountsResponse) New() protoreflect.Message { + return new(fastReflection_AccountsResponse) +} + +// Interface unwraps the message reflection interface and +// returns the underlying ProtoMessage interface. +func (x *fastReflection_AccountsResponse) Interface() protoreflect.ProtoMessage { + return (*AccountsResponse)(x) +} + +// Range iterates over every populated field in an undefined order, +// calling f for each field descriptor and value encountered. +// Range returns immediately if f returns false. +// While iterating, mutating operations may only be performed +// on the current field descriptor. +func (x *fastReflection_AccountsResponse) Range(f func(protoreflect.FieldDescriptor, protoreflect.Value) bool) { + if len(x.Accounts) != 0 { + value := protoreflect.ValueOfList(&_AccountsResponse_1_list{list: &x.Accounts}) + if !f(fd_AccountsResponse_accounts, value) { + return + } + } + if x.Pagination != nil { + value := protoreflect.ValueOfMessage(x.Pagination.ProtoReflect()) + if !f(fd_AccountsResponse_pagination, value) { + return + } + } +} + +// Has reports whether a field is populated. +// +// Some fields have the property of nullability where it is possible to +// distinguish between the default value of a field and whether the field +// was explicitly populated with the default value. Singular message fields, +// member fields of a oneof, and proto2 scalar fields are nullable. Such +// fields are populated only if explicitly set. +// +// In other cases (aside from the nullable cases above), +// a proto3 scalar field is populated if it contains a non-zero value, and +// a repeated field is populated if it is non-empty. +func (x *fastReflection_AccountsResponse) Has(fd protoreflect.FieldDescriptor) bool { + switch fd.FullName() { + case "cosmos.circuit.v1.AccountsResponse.accounts": + return len(x.Accounts) != 0 + case "cosmos.circuit.v1.AccountsResponse.pagination": + return x.Pagination != nil + default: + if fd.IsExtension() { + panic(fmt.Errorf("proto3 declared messages do not support extensions: cosmos.circuit.v1.AccountsResponse")) + } + panic(fmt.Errorf("message cosmos.circuit.v1.AccountsResponse does not contain field %s", fd.FullName())) + } +} + +// Clear clears the field such that a subsequent Has call reports false. +// +// Clearing an extension field clears both the extension type and value +// associated with the given field number. +// +// Clear is a mutating operation and unsafe for concurrent use. +func (x *fastReflection_AccountsResponse) Clear(fd protoreflect.FieldDescriptor) { + switch fd.FullName() { + case "cosmos.circuit.v1.AccountsResponse.accounts": + x.Accounts = nil + case "cosmos.circuit.v1.AccountsResponse.pagination": + x.Pagination = nil + default: + if fd.IsExtension() { + panic(fmt.Errorf("proto3 declared messages do not support extensions: cosmos.circuit.v1.AccountsResponse")) + } + panic(fmt.Errorf("message cosmos.circuit.v1.AccountsResponse does not contain field %s", fd.FullName())) + } +} + +// Get retrieves the value for a field. +// +// For unpopulated scalars, it returns the default value, where +// the default value of a bytes scalar is guaranteed to be a copy. +// For unpopulated composite types, it returns an empty, read-only view +// of the value; to obtain a mutable reference, use Mutable. +func (x *fastReflection_AccountsResponse) Get(descriptor protoreflect.FieldDescriptor) protoreflect.Value { + switch descriptor.FullName() { + case "cosmos.circuit.v1.AccountsResponse.accounts": + if len(x.Accounts) == 0 { + return protoreflect.ValueOfList(&_AccountsResponse_1_list{}) + } + listValue := &_AccountsResponse_1_list{list: &x.Accounts} + return protoreflect.ValueOfList(listValue) + case "cosmos.circuit.v1.AccountsResponse.pagination": + value := x.Pagination + return protoreflect.ValueOfMessage(value.ProtoReflect()) + default: + if descriptor.IsExtension() { + panic(fmt.Errorf("proto3 declared messages do not support extensions: cosmos.circuit.v1.AccountsResponse")) + } + panic(fmt.Errorf("message cosmos.circuit.v1.AccountsResponse does not contain field %s", descriptor.FullName())) + } +} + +// Set stores the value for a field. +// +// For a field belonging to a oneof, it implicitly clears any other field +// that may be currently set within the same oneof. +// For extension fields, it implicitly stores the provided ExtensionType. +// When setting a composite type, it is unspecified whether the stored value +// aliases the source's memory in any way. If the composite value is an +// empty, read-only value, then it panics. +// +// Set is a mutating operation and unsafe for concurrent use. +func (x *fastReflection_AccountsResponse) Set(fd protoreflect.FieldDescriptor, value protoreflect.Value) { + switch fd.FullName() { + case "cosmos.circuit.v1.AccountsResponse.accounts": + lv := value.List() + clv := lv.(*_AccountsResponse_1_list) + x.Accounts = *clv.list + case "cosmos.circuit.v1.AccountsResponse.pagination": + x.Pagination = value.Message().Interface().(*v1beta1.PageResponse) + default: + if fd.IsExtension() { + panic(fmt.Errorf("proto3 declared messages do not support extensions: cosmos.circuit.v1.AccountsResponse")) + } + panic(fmt.Errorf("message cosmos.circuit.v1.AccountsResponse does not contain field %s", fd.FullName())) + } +} + +// Mutable returns a mutable reference to a composite type. +// +// If the field is unpopulated, it may allocate a composite value. +// For a field belonging to a oneof, it implicitly clears any other field +// that may be currently set within the same oneof. +// For extension fields, it implicitly stores the provided ExtensionType +// if not already stored. +// It panics if the field does not contain a composite type. +// +// Mutable is a mutating operation and unsafe for concurrent use. +func (x *fastReflection_AccountsResponse) Mutable(fd protoreflect.FieldDescriptor) protoreflect.Value { + switch fd.FullName() { + case "cosmos.circuit.v1.AccountsResponse.accounts": + if x.Accounts == nil { + x.Accounts = []*GenesisAccountPermissions{} + } + value := &_AccountsResponse_1_list{list: &x.Accounts} + return protoreflect.ValueOfList(value) + case "cosmos.circuit.v1.AccountsResponse.pagination": + if x.Pagination == nil { + x.Pagination = new(v1beta1.PageResponse) + } + return protoreflect.ValueOfMessage(x.Pagination.ProtoReflect()) + default: + if fd.IsExtension() { + panic(fmt.Errorf("proto3 declared messages do not support extensions: cosmos.circuit.v1.AccountsResponse")) + } + panic(fmt.Errorf("message cosmos.circuit.v1.AccountsResponse does not contain field %s", fd.FullName())) + } +} + +// NewField returns a new value that is assignable to the field +// for the given descriptor. For scalars, this returns the default value. +// For lists, maps, and messages, this returns a new, empty, mutable value. +func (x *fastReflection_AccountsResponse) NewField(fd protoreflect.FieldDescriptor) protoreflect.Value { + switch fd.FullName() { + case "cosmos.circuit.v1.AccountsResponse.accounts": + list := []*GenesisAccountPermissions{} + return protoreflect.ValueOfList(&_AccountsResponse_1_list{list: &list}) + case "cosmos.circuit.v1.AccountsResponse.pagination": + m := new(v1beta1.PageResponse) + return protoreflect.ValueOfMessage(m.ProtoReflect()) + default: + if fd.IsExtension() { + panic(fmt.Errorf("proto3 declared messages do not support extensions: cosmos.circuit.v1.AccountsResponse")) + } + panic(fmt.Errorf("message cosmos.circuit.v1.AccountsResponse does not contain field %s", fd.FullName())) + } +} + +// WhichOneof reports which field within the oneof is populated, +// returning nil if none are populated. +// It panics if the oneof descriptor does not belong to this message. +func (x *fastReflection_AccountsResponse) WhichOneof(d protoreflect.OneofDescriptor) protoreflect.FieldDescriptor { + switch d.FullName() { + default: + panic(fmt.Errorf("%s is not a oneof field in cosmos.circuit.v1.AccountsResponse", d.FullName())) + } + panic("unreachable") +} + +// GetUnknown retrieves the entire list of unknown fields. +// The caller may only mutate the contents of the RawFields +// if the mutated bytes are stored back into the message with SetUnknown. +func (x *fastReflection_AccountsResponse) GetUnknown() protoreflect.RawFields { + return x.unknownFields +} + +// SetUnknown stores an entire list of unknown fields. +// The raw fields must be syntactically valid according to the wire format. +// An implementation may panic if this is not the case. +// Once stored, the caller must not mutate the content of the RawFields. +// An empty RawFields may be passed to clear the fields. +// +// SetUnknown is a mutating operation and unsafe for concurrent use. +func (x *fastReflection_AccountsResponse) SetUnknown(fields protoreflect.RawFields) { + x.unknownFields = fields +} + +// IsValid reports whether the message is valid. +// +// An invalid message is an empty, read-only value. +// +// An invalid message often corresponds to a nil pointer of the concrete +// message type, but the details are implementation dependent. +// Validity is not part of the protobuf data model, and may not +// be preserved in marshaling or other operations. +func (x *fastReflection_AccountsResponse) IsValid() bool { + return x != nil +} + +// ProtoMethods returns optional fastReflectionFeature-path implementations of various operations. +// This method may return nil. +// +// The returned methods type is identical to +// "google.golang.org/protobuf/runtime/protoiface".Methods. +// Consult the protoiface package documentation for details. +func (x *fastReflection_AccountsResponse) ProtoMethods() *protoiface.Methods { + size := func(input protoiface.SizeInput) protoiface.SizeOutput { + x := input.Message.Interface().(*AccountsResponse) + if x == nil { + return protoiface.SizeOutput{ + NoUnkeyedLiterals: input.NoUnkeyedLiterals, + Size: 0, + } + } + options := runtime.SizeInputToOptions(input) + _ = options + var n int + var l int + _ = l + if len(x.Accounts) > 0 { + for _, e := range x.Accounts { + l = options.Size(e) + n += 1 + l + runtime.Sov(uint64(l)) + } + } + if x.Pagination != nil { + l = options.Size(x.Pagination) + n += 1 + l + runtime.Sov(uint64(l)) + } + if x.unknownFields != nil { + n += len(x.unknownFields) + } + return protoiface.SizeOutput{ + NoUnkeyedLiterals: input.NoUnkeyedLiterals, + Size: n, + } + } + + marshal := func(input protoiface.MarshalInput) (protoiface.MarshalOutput, error) { + x := input.Message.Interface().(*AccountsResponse) + if x == nil { + return protoiface.MarshalOutput{ + NoUnkeyedLiterals: input.NoUnkeyedLiterals, + Buf: input.Buf, + }, nil + } + options := runtime.MarshalInputToOptions(input) + _ = options + size := options.Size(x) + dAtA := make([]byte, size) + i := len(dAtA) + _ = i + var l int + _ = l + if x.unknownFields != nil { + i -= len(x.unknownFields) + copy(dAtA[i:], x.unknownFields) + } + if x.Pagination != nil { + encoded, err := options.Marshal(x.Pagination) + if err != nil { + return protoiface.MarshalOutput{ + NoUnkeyedLiterals: input.NoUnkeyedLiterals, + Buf: input.Buf, + }, err + } + i -= len(encoded) + copy(dAtA[i:], encoded) + i = runtime.EncodeVarint(dAtA, i, uint64(len(encoded))) + i-- + dAtA[i] = 0x12 + } + if len(x.Accounts) > 0 { + for iNdEx := len(x.Accounts) - 1; iNdEx >= 0; iNdEx-- { + encoded, err := options.Marshal(x.Accounts[iNdEx]) + if err != nil { + return protoiface.MarshalOutput{ + NoUnkeyedLiterals: input.NoUnkeyedLiterals, + Buf: input.Buf, + }, err + } + i -= len(encoded) + copy(dAtA[i:], encoded) + i = runtime.EncodeVarint(dAtA, i, uint64(len(encoded))) + i-- + dAtA[i] = 0xa + } + } + if input.Buf != nil { + input.Buf = append(input.Buf, dAtA...) + } else { + input.Buf = dAtA + } + return protoiface.MarshalOutput{ + NoUnkeyedLiterals: input.NoUnkeyedLiterals, + Buf: input.Buf, + }, nil + } + unmarshal := func(input protoiface.UnmarshalInput) (protoiface.UnmarshalOutput, error) { + x := input.Message.Interface().(*AccountsResponse) + if x == nil { + return protoiface.UnmarshalOutput{ + NoUnkeyedLiterals: input.NoUnkeyedLiterals, + Flags: input.Flags, + }, nil + } + options := runtime.UnmarshalInputToOptions(input) + _ = options + dAtA := input.Buf + l := len(dAtA) + iNdEx := 0 + for iNdEx < l { + preIndex := iNdEx + var wire uint64 + for shift := uint(0); ; shift += 7 { + if shift >= 64 { + return protoiface.UnmarshalOutput{NoUnkeyedLiterals: input.NoUnkeyedLiterals, Flags: input.Flags}, runtime.ErrIntOverflow + } + if iNdEx >= l { + return protoiface.UnmarshalOutput{NoUnkeyedLiterals: input.NoUnkeyedLiterals, Flags: input.Flags}, io.ErrUnexpectedEOF + } + b := dAtA[iNdEx] + iNdEx++ + wire |= uint64(b&0x7F) << shift + if b < 0x80 { + break + } + } + fieldNum := int32(wire >> 3) + wireType := int(wire & 0x7) + if wireType == 4 { + return protoiface.UnmarshalOutput{NoUnkeyedLiterals: input.NoUnkeyedLiterals, Flags: input.Flags}, fmt.Errorf("proto: AccountsResponse: wiretype end group for non-group") + } + if fieldNum <= 0 { + return protoiface.UnmarshalOutput{NoUnkeyedLiterals: input.NoUnkeyedLiterals, Flags: input.Flags}, fmt.Errorf("proto: AccountsResponse: illegal tag %d (wire type %d)", fieldNum, wire) + } + switch fieldNum { + case 1: + if wireType != 2 { + return protoiface.UnmarshalOutput{NoUnkeyedLiterals: input.NoUnkeyedLiterals, Flags: input.Flags}, fmt.Errorf("proto: wrong wireType = %d for field Accounts", wireType) + } + var msglen int + for shift := uint(0); ; shift += 7 { + if shift >= 64 { + return protoiface.UnmarshalOutput{NoUnkeyedLiterals: input.NoUnkeyedLiterals, Flags: input.Flags}, runtime.ErrIntOverflow + } + if iNdEx >= l { + return protoiface.UnmarshalOutput{NoUnkeyedLiterals: input.NoUnkeyedLiterals, Flags: input.Flags}, io.ErrUnexpectedEOF + } + b := dAtA[iNdEx] + iNdEx++ + msglen |= int(b&0x7F) << shift + if b < 0x80 { + break + } + } + if msglen < 0 { + return protoiface.UnmarshalOutput{NoUnkeyedLiterals: input.NoUnkeyedLiterals, Flags: input.Flags}, runtime.ErrInvalidLength + } + postIndex := iNdEx + msglen + if postIndex < 0 { + return protoiface.UnmarshalOutput{NoUnkeyedLiterals: input.NoUnkeyedLiterals, Flags: input.Flags}, runtime.ErrInvalidLength + } + if postIndex > l { + return protoiface.UnmarshalOutput{NoUnkeyedLiterals: input.NoUnkeyedLiterals, Flags: input.Flags}, io.ErrUnexpectedEOF + } + x.Accounts = append(x.Accounts, &GenesisAccountPermissions{}) + if err := options.Unmarshal(dAtA[iNdEx:postIndex], x.Accounts[len(x.Accounts)-1]); err != nil { + return protoiface.UnmarshalOutput{NoUnkeyedLiterals: input.NoUnkeyedLiterals, Flags: input.Flags}, err + } + iNdEx = postIndex + case 2: + if wireType != 2 { + return protoiface.UnmarshalOutput{NoUnkeyedLiterals: input.NoUnkeyedLiterals, Flags: input.Flags}, fmt.Errorf("proto: wrong wireType = %d for field Pagination", wireType) + } + var msglen int + for shift := uint(0); ; shift += 7 { + if shift >= 64 { + return protoiface.UnmarshalOutput{NoUnkeyedLiterals: input.NoUnkeyedLiterals, Flags: input.Flags}, runtime.ErrIntOverflow + } + if iNdEx >= l { + return protoiface.UnmarshalOutput{NoUnkeyedLiterals: input.NoUnkeyedLiterals, Flags: input.Flags}, io.ErrUnexpectedEOF + } + b := dAtA[iNdEx] + iNdEx++ + msglen |= int(b&0x7F) << shift + if b < 0x80 { + break + } + } + if msglen < 0 { + return protoiface.UnmarshalOutput{NoUnkeyedLiterals: input.NoUnkeyedLiterals, Flags: input.Flags}, runtime.ErrInvalidLength + } + postIndex := iNdEx + msglen + if postIndex < 0 { + return protoiface.UnmarshalOutput{NoUnkeyedLiterals: input.NoUnkeyedLiterals, Flags: input.Flags}, runtime.ErrInvalidLength + } + if postIndex > l { + return protoiface.UnmarshalOutput{NoUnkeyedLiterals: input.NoUnkeyedLiterals, Flags: input.Flags}, io.ErrUnexpectedEOF + } + if x.Pagination == nil { + x.Pagination = &v1beta1.PageResponse{} + } + if err := options.Unmarshal(dAtA[iNdEx:postIndex], x.Pagination); err != nil { + return protoiface.UnmarshalOutput{NoUnkeyedLiterals: input.NoUnkeyedLiterals, Flags: input.Flags}, err + } + iNdEx = postIndex + default: + iNdEx = preIndex + skippy, err := runtime.Skip(dAtA[iNdEx:]) + if err != nil { + return protoiface.UnmarshalOutput{NoUnkeyedLiterals: input.NoUnkeyedLiterals, Flags: input.Flags}, err + } + if (skippy < 0) || (iNdEx+skippy) < 0 { + return protoiface.UnmarshalOutput{NoUnkeyedLiterals: input.NoUnkeyedLiterals, Flags: input.Flags}, runtime.ErrInvalidLength + } + if (iNdEx + skippy) > l { + return protoiface.UnmarshalOutput{NoUnkeyedLiterals: input.NoUnkeyedLiterals, Flags: input.Flags}, io.ErrUnexpectedEOF + } + if !options.DiscardUnknown { + x.unknownFields = append(x.unknownFields, dAtA[iNdEx:iNdEx+skippy]...) + } + iNdEx += skippy + } + } + + if iNdEx > l { + return protoiface.UnmarshalOutput{NoUnkeyedLiterals: input.NoUnkeyedLiterals, Flags: input.Flags}, io.ErrUnexpectedEOF + } + return protoiface.UnmarshalOutput{NoUnkeyedLiterals: input.NoUnkeyedLiterals, Flags: input.Flags}, nil + } + return &protoiface.Methods{ + NoUnkeyedLiterals: struct{}{}, + Flags: protoiface.SupportMarshalDeterministic | protoiface.SupportUnmarshalDiscardUnknown, + Size: size, + Marshal: marshal, + Unmarshal: unmarshal, + Merge: nil, + CheckInitialized: nil, + } +} + +var ( + md_QueryDisabledListRequest protoreflect.MessageDescriptor +) + +func init() { + file_cosmos_circuit_v1_query_proto_init() + md_QueryDisabledListRequest = File_cosmos_circuit_v1_query_proto.Messages().ByName("QueryDisabledListRequest") +} + +var _ protoreflect.Message = (*fastReflection_QueryDisabledListRequest)(nil) + +type fastReflection_QueryDisabledListRequest QueryDisabledListRequest + +func (x *QueryDisabledListRequest) ProtoReflect() protoreflect.Message { + return (*fastReflection_QueryDisabledListRequest)(x) +} + +func (x *QueryDisabledListRequest) slowProtoReflect() protoreflect.Message { + mi := &file_cosmos_circuit_v1_query_proto_msgTypes[4] + if protoimpl.UnsafeEnabled && x != nil { + ms := protoimpl.X.MessageStateOf(protoimpl.Pointer(x)) + if ms.LoadMessageInfo() == nil { + ms.StoreMessageInfo(mi) + } + return ms + } + return mi.MessageOf(x) +} + +var _fastReflection_QueryDisabledListRequest_messageType fastReflection_QueryDisabledListRequest_messageType +var _ protoreflect.MessageType = fastReflection_QueryDisabledListRequest_messageType{} + +type fastReflection_QueryDisabledListRequest_messageType struct{} + +func (x fastReflection_QueryDisabledListRequest_messageType) Zero() protoreflect.Message { + return (*fastReflection_QueryDisabledListRequest)(nil) +} +func (x fastReflection_QueryDisabledListRequest_messageType) New() protoreflect.Message { + return new(fastReflection_QueryDisabledListRequest) +} +func (x fastReflection_QueryDisabledListRequest_messageType) Descriptor() protoreflect.MessageDescriptor { + return md_QueryDisabledListRequest +} + +// Descriptor returns message descriptor, which contains only the protobuf +// type information for the message. +func (x *fastReflection_QueryDisabledListRequest) Descriptor() protoreflect.MessageDescriptor { + return md_QueryDisabledListRequest +} + +// Type returns the message type, which encapsulates both Go and protobuf +// type information. If the Go type information is not needed, +// it is recommended that the message descriptor be used instead. +func (x *fastReflection_QueryDisabledListRequest) Type() protoreflect.MessageType { + return _fastReflection_QueryDisabledListRequest_messageType +} + +// New returns a newly allocated and mutable empty message. +func (x *fastReflection_QueryDisabledListRequest) New() protoreflect.Message { + return new(fastReflection_QueryDisabledListRequest) +} + +// Interface unwraps the message reflection interface and +// returns the underlying ProtoMessage interface. +func (x *fastReflection_QueryDisabledListRequest) Interface() protoreflect.ProtoMessage { + return (*QueryDisabledListRequest)(x) +} + +// Range iterates over every populated field in an undefined order, +// calling f for each field descriptor and value encountered. +// Range returns immediately if f returns false. +// While iterating, mutating operations may only be performed +// on the current field descriptor. +func (x *fastReflection_QueryDisabledListRequest) Range(f func(protoreflect.FieldDescriptor, protoreflect.Value) bool) { +} + +// Has reports whether a field is populated. +// +// Some fields have the property of nullability where it is possible to +// distinguish between the default value of a field and whether the field +// was explicitly populated with the default value. Singular message fields, +// member fields of a oneof, and proto2 scalar fields are nullable. Such +// fields are populated only if explicitly set. +// +// In other cases (aside from the nullable cases above), +// a proto3 scalar field is populated if it contains a non-zero value, and +// a repeated field is populated if it is non-empty. +func (x *fastReflection_QueryDisabledListRequest) Has(fd protoreflect.FieldDescriptor) bool { + switch fd.FullName() { + default: + if fd.IsExtension() { + panic(fmt.Errorf("proto3 declared messages do not support extensions: cosmos.circuit.v1.QueryDisabledListRequest")) + } + panic(fmt.Errorf("message cosmos.circuit.v1.QueryDisabledListRequest does not contain field %s", fd.FullName())) + } +} + +// Clear clears the field such that a subsequent Has call reports false. +// +// Clearing an extension field clears both the extension type and value +// associated with the given field number. +// +// Clear is a mutating operation and unsafe for concurrent use. +func (x *fastReflection_QueryDisabledListRequest) Clear(fd protoreflect.FieldDescriptor) { + switch fd.FullName() { + default: + if fd.IsExtension() { + panic(fmt.Errorf("proto3 declared messages do not support extensions: cosmos.circuit.v1.QueryDisabledListRequest")) + } + panic(fmt.Errorf("message cosmos.circuit.v1.QueryDisabledListRequest does not contain field %s", fd.FullName())) + } +} + +// Get retrieves the value for a field. +// +// For unpopulated scalars, it returns the default value, where +// the default value of a bytes scalar is guaranteed to be a copy. +// For unpopulated composite types, it returns an empty, read-only view +// of the value; to obtain a mutable reference, use Mutable. +func (x *fastReflection_QueryDisabledListRequest) Get(descriptor protoreflect.FieldDescriptor) protoreflect.Value { + switch descriptor.FullName() { + default: + if descriptor.IsExtension() { + panic(fmt.Errorf("proto3 declared messages do not support extensions: cosmos.circuit.v1.QueryDisabledListRequest")) + } + panic(fmt.Errorf("message cosmos.circuit.v1.QueryDisabledListRequest does not contain field %s", descriptor.FullName())) + } +} + +// Set stores the value for a field. +// +// For a field belonging to a oneof, it implicitly clears any other field +// that may be currently set within the same oneof. +// For extension fields, it implicitly stores the provided ExtensionType. +// When setting a composite type, it is unspecified whether the stored value +// aliases the source's memory in any way. If the composite value is an +// empty, read-only value, then it panics. +// +// Set is a mutating operation and unsafe for concurrent use. +func (x *fastReflection_QueryDisabledListRequest) Set(fd protoreflect.FieldDescriptor, value protoreflect.Value) { + switch fd.FullName() { + default: + if fd.IsExtension() { + panic(fmt.Errorf("proto3 declared messages do not support extensions: cosmos.circuit.v1.QueryDisabledListRequest")) + } + panic(fmt.Errorf("message cosmos.circuit.v1.QueryDisabledListRequest does not contain field %s", fd.FullName())) + } +} + +// Mutable returns a mutable reference to a composite type. +// +// If the field is unpopulated, it may allocate a composite value. +// For a field belonging to a oneof, it implicitly clears any other field +// that may be currently set within the same oneof. +// For extension fields, it implicitly stores the provided ExtensionType +// if not already stored. +// It panics if the field does not contain a composite type. +// +// Mutable is a mutating operation and unsafe for concurrent use. +func (x *fastReflection_QueryDisabledListRequest) Mutable(fd protoreflect.FieldDescriptor) protoreflect.Value { + switch fd.FullName() { + default: + if fd.IsExtension() { + panic(fmt.Errorf("proto3 declared messages do not support extensions: cosmos.circuit.v1.QueryDisabledListRequest")) + } + panic(fmt.Errorf("message cosmos.circuit.v1.QueryDisabledListRequest does not contain field %s", fd.FullName())) + } +} + +// NewField returns a new value that is assignable to the field +// for the given descriptor. For scalars, this returns the default value. +// For lists, maps, and messages, this returns a new, empty, mutable value. +func (x *fastReflection_QueryDisabledListRequest) NewField(fd protoreflect.FieldDescriptor) protoreflect.Value { + switch fd.FullName() { + default: + if fd.IsExtension() { + panic(fmt.Errorf("proto3 declared messages do not support extensions: cosmos.circuit.v1.QueryDisabledListRequest")) + } + panic(fmt.Errorf("message cosmos.circuit.v1.QueryDisabledListRequest does not contain field %s", fd.FullName())) + } +} + +// WhichOneof reports which field within the oneof is populated, +// returning nil if none are populated. +// It panics if the oneof descriptor does not belong to this message. +func (x *fastReflection_QueryDisabledListRequest) WhichOneof(d protoreflect.OneofDescriptor) protoreflect.FieldDescriptor { + switch d.FullName() { + default: + panic(fmt.Errorf("%s is not a oneof field in cosmos.circuit.v1.QueryDisabledListRequest", d.FullName())) + } + panic("unreachable") +} + +// GetUnknown retrieves the entire list of unknown fields. +// The caller may only mutate the contents of the RawFields +// if the mutated bytes are stored back into the message with SetUnknown. +func (x *fastReflection_QueryDisabledListRequest) GetUnknown() protoreflect.RawFields { + return x.unknownFields +} + +// SetUnknown stores an entire list of unknown fields. +// The raw fields must be syntactically valid according to the wire format. +// An implementation may panic if this is not the case. +// Once stored, the caller must not mutate the content of the RawFields. +// An empty RawFields may be passed to clear the fields. +// +// SetUnknown is a mutating operation and unsafe for concurrent use. +func (x *fastReflection_QueryDisabledListRequest) SetUnknown(fields protoreflect.RawFields) { + x.unknownFields = fields +} + +// IsValid reports whether the message is valid. +// +// An invalid message is an empty, read-only value. +// +// An invalid message often corresponds to a nil pointer of the concrete +// message type, but the details are implementation dependent. +// Validity is not part of the protobuf data model, and may not +// be preserved in marshaling or other operations. +func (x *fastReflection_QueryDisabledListRequest) IsValid() bool { + return x != nil +} + +// ProtoMethods returns optional fastReflectionFeature-path implementations of various operations. +// This method may return nil. +// +// The returned methods type is identical to +// "google.golang.org/protobuf/runtime/protoiface".Methods. +// Consult the protoiface package documentation for details. +func (x *fastReflection_QueryDisabledListRequest) ProtoMethods() *protoiface.Methods { + size := func(input protoiface.SizeInput) protoiface.SizeOutput { + x := input.Message.Interface().(*QueryDisabledListRequest) + if x == nil { + return protoiface.SizeOutput{ + NoUnkeyedLiterals: input.NoUnkeyedLiterals, + Size: 0, + } + } + options := runtime.SizeInputToOptions(input) + _ = options + var n int + var l int + _ = l + if x.unknownFields != nil { + n += len(x.unknownFields) + } + return protoiface.SizeOutput{ + NoUnkeyedLiterals: input.NoUnkeyedLiterals, + Size: n, + } + } + + marshal := func(input protoiface.MarshalInput) (protoiface.MarshalOutput, error) { + x := input.Message.Interface().(*QueryDisabledListRequest) + if x == nil { + return protoiface.MarshalOutput{ + NoUnkeyedLiterals: input.NoUnkeyedLiterals, + Buf: input.Buf, + }, nil + } + options := runtime.MarshalInputToOptions(input) + _ = options + size := options.Size(x) + dAtA := make([]byte, size) + i := len(dAtA) + _ = i + var l int + _ = l + if x.unknownFields != nil { + i -= len(x.unknownFields) + copy(dAtA[i:], x.unknownFields) + } + if input.Buf != nil { + input.Buf = append(input.Buf, dAtA...) + } else { + input.Buf = dAtA + } + return protoiface.MarshalOutput{ + NoUnkeyedLiterals: input.NoUnkeyedLiterals, + Buf: input.Buf, + }, nil + } + unmarshal := func(input protoiface.UnmarshalInput) (protoiface.UnmarshalOutput, error) { + x := input.Message.Interface().(*QueryDisabledListRequest) + if x == nil { + return protoiface.UnmarshalOutput{ + NoUnkeyedLiterals: input.NoUnkeyedLiterals, + Flags: input.Flags, + }, nil + } + options := runtime.UnmarshalInputToOptions(input) + _ = options + dAtA := input.Buf + l := len(dAtA) + iNdEx := 0 + for iNdEx < l { + preIndex := iNdEx + var wire uint64 + for shift := uint(0); ; shift += 7 { + if shift >= 64 { + return protoiface.UnmarshalOutput{NoUnkeyedLiterals: input.NoUnkeyedLiterals, Flags: input.Flags}, runtime.ErrIntOverflow + } + if iNdEx >= l { + return protoiface.UnmarshalOutput{NoUnkeyedLiterals: input.NoUnkeyedLiterals, Flags: input.Flags}, io.ErrUnexpectedEOF + } + b := dAtA[iNdEx] + iNdEx++ + wire |= uint64(b&0x7F) << shift + if b < 0x80 { + break + } + } + fieldNum := int32(wire >> 3) + wireType := int(wire & 0x7) + if wireType == 4 { + return protoiface.UnmarshalOutput{NoUnkeyedLiterals: input.NoUnkeyedLiterals, Flags: input.Flags}, fmt.Errorf("proto: QueryDisabledListRequest: wiretype end group for non-group") + } + if fieldNum <= 0 { + return protoiface.UnmarshalOutput{NoUnkeyedLiterals: input.NoUnkeyedLiterals, Flags: input.Flags}, fmt.Errorf("proto: QueryDisabledListRequest: illegal tag %d (wire type %d)", fieldNum, wire) + } + switch fieldNum { + default: + iNdEx = preIndex + skippy, err := runtime.Skip(dAtA[iNdEx:]) + if err != nil { + return protoiface.UnmarshalOutput{NoUnkeyedLiterals: input.NoUnkeyedLiterals, Flags: input.Flags}, err + } + if (skippy < 0) || (iNdEx+skippy) < 0 { + return protoiface.UnmarshalOutput{NoUnkeyedLiterals: input.NoUnkeyedLiterals, Flags: input.Flags}, runtime.ErrInvalidLength + } + if (iNdEx + skippy) > l { + return protoiface.UnmarshalOutput{NoUnkeyedLiterals: input.NoUnkeyedLiterals, Flags: input.Flags}, io.ErrUnexpectedEOF + } + if !options.DiscardUnknown { + x.unknownFields = append(x.unknownFields, dAtA[iNdEx:iNdEx+skippy]...) + } + iNdEx += skippy + } + } + + if iNdEx > l { + return protoiface.UnmarshalOutput{NoUnkeyedLiterals: input.NoUnkeyedLiterals, Flags: input.Flags}, io.ErrUnexpectedEOF + } + return protoiface.UnmarshalOutput{NoUnkeyedLiterals: input.NoUnkeyedLiterals, Flags: input.Flags}, nil + } + return &protoiface.Methods{ + NoUnkeyedLiterals: struct{}{}, + Flags: protoiface.SupportMarshalDeterministic | protoiface.SupportUnmarshalDiscardUnknown, + Size: size, + Marshal: marshal, + Unmarshal: unmarshal, + Merge: nil, + CheckInitialized: nil, + } +} + +var _ protoreflect.List = (*_DisabledListResponse_1_list)(nil) + +type _DisabledListResponse_1_list struct { + list *[]string +} + +func (x *_DisabledListResponse_1_list) Len() int { + if x.list == nil { + return 0 + } + return len(*x.list) +} + +func (x *_DisabledListResponse_1_list) Get(i int) protoreflect.Value { + return protoreflect.ValueOfString((*x.list)[i]) +} + +func (x *_DisabledListResponse_1_list) Set(i int, value protoreflect.Value) { + valueUnwrapped := value.String() + concreteValue := valueUnwrapped + (*x.list)[i] = concreteValue +} + +func (x *_DisabledListResponse_1_list) Append(value protoreflect.Value) { + valueUnwrapped := value.String() + concreteValue := valueUnwrapped + *x.list = append(*x.list, concreteValue) +} + +func (x *_DisabledListResponse_1_list) AppendMutable() protoreflect.Value { + panic(fmt.Errorf("AppendMutable can not be called on message DisabledListResponse at list field DisabledList as it is not of Message kind")) +} + +func (x *_DisabledListResponse_1_list) Truncate(n int) { + *x.list = (*x.list)[:n] +} + +func (x *_DisabledListResponse_1_list) NewElement() protoreflect.Value { + v := "" + return protoreflect.ValueOfString(v) +} + +func (x *_DisabledListResponse_1_list) IsValid() bool { + return x.list != nil +} + +var ( + md_DisabledListResponse protoreflect.MessageDescriptor + fd_DisabledListResponse_disabled_list protoreflect.FieldDescriptor +) + +func init() { + file_cosmos_circuit_v1_query_proto_init() + md_DisabledListResponse = File_cosmos_circuit_v1_query_proto.Messages().ByName("DisabledListResponse") + fd_DisabledListResponse_disabled_list = md_DisabledListResponse.Fields().ByName("disabled_list") +} + +var _ protoreflect.Message = (*fastReflection_DisabledListResponse)(nil) + +type fastReflection_DisabledListResponse DisabledListResponse + +func (x *DisabledListResponse) ProtoReflect() protoreflect.Message { + return (*fastReflection_DisabledListResponse)(x) +} + +func (x *DisabledListResponse) slowProtoReflect() protoreflect.Message { + mi := &file_cosmos_circuit_v1_query_proto_msgTypes[5] + if protoimpl.UnsafeEnabled && x != nil { + ms := protoimpl.X.MessageStateOf(protoimpl.Pointer(x)) + if ms.LoadMessageInfo() == nil { + ms.StoreMessageInfo(mi) + } + return ms + } + return mi.MessageOf(x) +} + +var _fastReflection_DisabledListResponse_messageType fastReflection_DisabledListResponse_messageType +var _ protoreflect.MessageType = fastReflection_DisabledListResponse_messageType{} + +type fastReflection_DisabledListResponse_messageType struct{} + +func (x fastReflection_DisabledListResponse_messageType) Zero() protoreflect.Message { + return (*fastReflection_DisabledListResponse)(nil) +} +func (x fastReflection_DisabledListResponse_messageType) New() protoreflect.Message { + return new(fastReflection_DisabledListResponse) +} +func (x fastReflection_DisabledListResponse_messageType) Descriptor() protoreflect.MessageDescriptor { + return md_DisabledListResponse +} + +// Descriptor returns message descriptor, which contains only the protobuf +// type information for the message. +func (x *fastReflection_DisabledListResponse) Descriptor() protoreflect.MessageDescriptor { + return md_DisabledListResponse +} + +// Type returns the message type, which encapsulates both Go and protobuf +// type information. If the Go type information is not needed, +// it is recommended that the message descriptor be used instead. +func (x *fastReflection_DisabledListResponse) Type() protoreflect.MessageType { + return _fastReflection_DisabledListResponse_messageType +} + +// New returns a newly allocated and mutable empty message. +func (x *fastReflection_DisabledListResponse) New() protoreflect.Message { + return new(fastReflection_DisabledListResponse) +} + +// Interface unwraps the message reflection interface and +// returns the underlying ProtoMessage interface. +func (x *fastReflection_DisabledListResponse) Interface() protoreflect.ProtoMessage { + return (*DisabledListResponse)(x) +} + +// Range iterates over every populated field in an undefined order, +// calling f for each field descriptor and value encountered. +// Range returns immediately if f returns false. +// While iterating, mutating operations may only be performed +// on the current field descriptor. +func (x *fastReflection_DisabledListResponse) Range(f func(protoreflect.FieldDescriptor, protoreflect.Value) bool) { + if len(x.DisabledList) != 0 { + value := protoreflect.ValueOfList(&_DisabledListResponse_1_list{list: &x.DisabledList}) + if !f(fd_DisabledListResponse_disabled_list, value) { + return + } + } +} + +// Has reports whether a field is populated. +// +// Some fields have the property of nullability where it is possible to +// distinguish between the default value of a field and whether the field +// was explicitly populated with the default value. Singular message fields, +// member fields of a oneof, and proto2 scalar fields are nullable. Such +// fields are populated only if explicitly set. +// +// In other cases (aside from the nullable cases above), +// a proto3 scalar field is populated if it contains a non-zero value, and +// a repeated field is populated if it is non-empty. +func (x *fastReflection_DisabledListResponse) Has(fd protoreflect.FieldDescriptor) bool { + switch fd.FullName() { + case "cosmos.circuit.v1.DisabledListResponse.disabled_list": + return len(x.DisabledList) != 0 + default: + if fd.IsExtension() { + panic(fmt.Errorf("proto3 declared messages do not support extensions: cosmos.circuit.v1.DisabledListResponse")) + } + panic(fmt.Errorf("message cosmos.circuit.v1.DisabledListResponse does not contain field %s", fd.FullName())) + } +} + +// Clear clears the field such that a subsequent Has call reports false. +// +// Clearing an extension field clears both the extension type and value +// associated with the given field number. +// +// Clear is a mutating operation and unsafe for concurrent use. +func (x *fastReflection_DisabledListResponse) Clear(fd protoreflect.FieldDescriptor) { + switch fd.FullName() { + case "cosmos.circuit.v1.DisabledListResponse.disabled_list": + x.DisabledList = nil + default: + if fd.IsExtension() { + panic(fmt.Errorf("proto3 declared messages do not support extensions: cosmos.circuit.v1.DisabledListResponse")) + } + panic(fmt.Errorf("message cosmos.circuit.v1.DisabledListResponse does not contain field %s", fd.FullName())) + } +} + +// Get retrieves the value for a field. +// +// For unpopulated scalars, it returns the default value, where +// the default value of a bytes scalar is guaranteed to be a copy. +// For unpopulated composite types, it returns an empty, read-only view +// of the value; to obtain a mutable reference, use Mutable. +func (x *fastReflection_DisabledListResponse) Get(descriptor protoreflect.FieldDescriptor) protoreflect.Value { + switch descriptor.FullName() { + case "cosmos.circuit.v1.DisabledListResponse.disabled_list": + if len(x.DisabledList) == 0 { + return protoreflect.ValueOfList(&_DisabledListResponse_1_list{}) + } + listValue := &_DisabledListResponse_1_list{list: &x.DisabledList} + return protoreflect.ValueOfList(listValue) + default: + if descriptor.IsExtension() { + panic(fmt.Errorf("proto3 declared messages do not support extensions: cosmos.circuit.v1.DisabledListResponse")) + } + panic(fmt.Errorf("message cosmos.circuit.v1.DisabledListResponse does not contain field %s", descriptor.FullName())) + } +} + +// Set stores the value for a field. +// +// For a field belonging to a oneof, it implicitly clears any other field +// that may be currently set within the same oneof. +// For extension fields, it implicitly stores the provided ExtensionType. +// When setting a composite type, it is unspecified whether the stored value +// aliases the source's memory in any way. If the composite value is an +// empty, read-only value, then it panics. +// +// Set is a mutating operation and unsafe for concurrent use. +func (x *fastReflection_DisabledListResponse) Set(fd protoreflect.FieldDescriptor, value protoreflect.Value) { + switch fd.FullName() { + case "cosmos.circuit.v1.DisabledListResponse.disabled_list": + lv := value.List() + clv := lv.(*_DisabledListResponse_1_list) + x.DisabledList = *clv.list + default: + if fd.IsExtension() { + panic(fmt.Errorf("proto3 declared messages do not support extensions: cosmos.circuit.v1.DisabledListResponse")) + } + panic(fmt.Errorf("message cosmos.circuit.v1.DisabledListResponse does not contain field %s", fd.FullName())) + } +} + +// Mutable returns a mutable reference to a composite type. +// +// If the field is unpopulated, it may allocate a composite value. +// For a field belonging to a oneof, it implicitly clears any other field +// that may be currently set within the same oneof. +// For extension fields, it implicitly stores the provided ExtensionType +// if not already stored. +// It panics if the field does not contain a composite type. +// +// Mutable is a mutating operation and unsafe for concurrent use. +func (x *fastReflection_DisabledListResponse) Mutable(fd protoreflect.FieldDescriptor) protoreflect.Value { + switch fd.FullName() { + case "cosmos.circuit.v1.DisabledListResponse.disabled_list": + if x.DisabledList == nil { + x.DisabledList = []string{} + } + value := &_DisabledListResponse_1_list{list: &x.DisabledList} + return protoreflect.ValueOfList(value) + default: + if fd.IsExtension() { + panic(fmt.Errorf("proto3 declared messages do not support extensions: cosmos.circuit.v1.DisabledListResponse")) + } + panic(fmt.Errorf("message cosmos.circuit.v1.DisabledListResponse does not contain field %s", fd.FullName())) + } +} + +// NewField returns a new value that is assignable to the field +// for the given descriptor. For scalars, this returns the default value. +// For lists, maps, and messages, this returns a new, empty, mutable value. +func (x *fastReflection_DisabledListResponse) NewField(fd protoreflect.FieldDescriptor) protoreflect.Value { + switch fd.FullName() { + case "cosmos.circuit.v1.DisabledListResponse.disabled_list": + list := []string{} + return protoreflect.ValueOfList(&_DisabledListResponse_1_list{list: &list}) + default: + if fd.IsExtension() { + panic(fmt.Errorf("proto3 declared messages do not support extensions: cosmos.circuit.v1.DisabledListResponse")) + } + panic(fmt.Errorf("message cosmos.circuit.v1.DisabledListResponse does not contain field %s", fd.FullName())) + } +} + +// WhichOneof reports which field within the oneof is populated, +// returning nil if none are populated. +// It panics if the oneof descriptor does not belong to this message. +func (x *fastReflection_DisabledListResponse) WhichOneof(d protoreflect.OneofDescriptor) protoreflect.FieldDescriptor { + switch d.FullName() { + default: + panic(fmt.Errorf("%s is not a oneof field in cosmos.circuit.v1.DisabledListResponse", d.FullName())) + } + panic("unreachable") +} + +// GetUnknown retrieves the entire list of unknown fields. +// The caller may only mutate the contents of the RawFields +// if the mutated bytes are stored back into the message with SetUnknown. +func (x *fastReflection_DisabledListResponse) GetUnknown() protoreflect.RawFields { + return x.unknownFields +} + +// SetUnknown stores an entire list of unknown fields. +// The raw fields must be syntactically valid according to the wire format. +// An implementation may panic if this is not the case. +// Once stored, the caller must not mutate the content of the RawFields. +// An empty RawFields may be passed to clear the fields. +// +// SetUnknown is a mutating operation and unsafe for concurrent use. +func (x *fastReflection_DisabledListResponse) SetUnknown(fields protoreflect.RawFields) { + x.unknownFields = fields +} + +// IsValid reports whether the message is valid. +// +// An invalid message is an empty, read-only value. +// +// An invalid message often corresponds to a nil pointer of the concrete +// message type, but the details are implementation dependent. +// Validity is not part of the protobuf data model, and may not +// be preserved in marshaling or other operations. +func (x *fastReflection_DisabledListResponse) IsValid() bool { + return x != nil +} + +// ProtoMethods returns optional fastReflectionFeature-path implementations of various operations. +// This method may return nil. +// +// The returned methods type is identical to +// "google.golang.org/protobuf/runtime/protoiface".Methods. +// Consult the protoiface package documentation for details. +func (x *fastReflection_DisabledListResponse) ProtoMethods() *protoiface.Methods { + size := func(input protoiface.SizeInput) protoiface.SizeOutput { + x := input.Message.Interface().(*DisabledListResponse) + if x == nil { + return protoiface.SizeOutput{ + NoUnkeyedLiterals: input.NoUnkeyedLiterals, + Size: 0, + } + } + options := runtime.SizeInputToOptions(input) + _ = options + var n int + var l int + _ = l + if len(x.DisabledList) > 0 { + for _, s := range x.DisabledList { + l = len(s) + n += 1 + l + runtime.Sov(uint64(l)) + } + } + if x.unknownFields != nil { + n += len(x.unknownFields) + } + return protoiface.SizeOutput{ + NoUnkeyedLiterals: input.NoUnkeyedLiterals, + Size: n, + } + } + + marshal := func(input protoiface.MarshalInput) (protoiface.MarshalOutput, error) { + x := input.Message.Interface().(*DisabledListResponse) + if x == nil { + return protoiface.MarshalOutput{ + NoUnkeyedLiterals: input.NoUnkeyedLiterals, + Buf: input.Buf, + }, nil + } + options := runtime.MarshalInputToOptions(input) + _ = options + size := options.Size(x) + dAtA := make([]byte, size) + i := len(dAtA) + _ = i + var l int + _ = l + if x.unknownFields != nil { + i -= len(x.unknownFields) + copy(dAtA[i:], x.unknownFields) + } + if len(x.DisabledList) > 0 { + for iNdEx := len(x.DisabledList) - 1; iNdEx >= 0; iNdEx-- { + i -= len(x.DisabledList[iNdEx]) + copy(dAtA[i:], x.DisabledList[iNdEx]) + i = runtime.EncodeVarint(dAtA, i, uint64(len(x.DisabledList[iNdEx]))) + i-- + dAtA[i] = 0xa + } + } + if input.Buf != nil { + input.Buf = append(input.Buf, dAtA...) + } else { + input.Buf = dAtA + } + return protoiface.MarshalOutput{ + NoUnkeyedLiterals: input.NoUnkeyedLiterals, + Buf: input.Buf, + }, nil + } + unmarshal := func(input protoiface.UnmarshalInput) (protoiface.UnmarshalOutput, error) { + x := input.Message.Interface().(*DisabledListResponse) + if x == nil { + return protoiface.UnmarshalOutput{ + NoUnkeyedLiterals: input.NoUnkeyedLiterals, + Flags: input.Flags, + }, nil + } + options := runtime.UnmarshalInputToOptions(input) + _ = options + dAtA := input.Buf + l := len(dAtA) + iNdEx := 0 + for iNdEx < l { + preIndex := iNdEx + var wire uint64 + for shift := uint(0); ; shift += 7 { + if shift >= 64 { + return protoiface.UnmarshalOutput{NoUnkeyedLiterals: input.NoUnkeyedLiterals, Flags: input.Flags}, runtime.ErrIntOverflow + } + if iNdEx >= l { + return protoiface.UnmarshalOutput{NoUnkeyedLiterals: input.NoUnkeyedLiterals, Flags: input.Flags}, io.ErrUnexpectedEOF + } + b := dAtA[iNdEx] + iNdEx++ + wire |= uint64(b&0x7F) << shift + if b < 0x80 { + break + } + } + fieldNum := int32(wire >> 3) + wireType := int(wire & 0x7) + if wireType == 4 { + return protoiface.UnmarshalOutput{NoUnkeyedLiterals: input.NoUnkeyedLiterals, Flags: input.Flags}, fmt.Errorf("proto: DisabledListResponse: wiretype end group for non-group") + } + if fieldNum <= 0 { + return protoiface.UnmarshalOutput{NoUnkeyedLiterals: input.NoUnkeyedLiterals, Flags: input.Flags}, fmt.Errorf("proto: DisabledListResponse: illegal tag %d (wire type %d)", fieldNum, wire) + } + switch fieldNum { + case 1: + if wireType != 2 { + return protoiface.UnmarshalOutput{NoUnkeyedLiterals: input.NoUnkeyedLiterals, Flags: input.Flags}, fmt.Errorf("proto: wrong wireType = %d for field DisabledList", wireType) + } + var stringLen uint64 + for shift := uint(0); ; shift += 7 { + if shift >= 64 { + return protoiface.UnmarshalOutput{NoUnkeyedLiterals: input.NoUnkeyedLiterals, Flags: input.Flags}, runtime.ErrIntOverflow + } + if iNdEx >= l { + return protoiface.UnmarshalOutput{NoUnkeyedLiterals: input.NoUnkeyedLiterals, Flags: input.Flags}, io.ErrUnexpectedEOF + } + b := dAtA[iNdEx] + iNdEx++ + stringLen |= uint64(b&0x7F) << shift + if b < 0x80 { + break + } + } + intStringLen := int(stringLen) + if intStringLen < 0 { + return protoiface.UnmarshalOutput{NoUnkeyedLiterals: input.NoUnkeyedLiterals, Flags: input.Flags}, runtime.ErrInvalidLength + } + postIndex := iNdEx + intStringLen + if postIndex < 0 { + return protoiface.UnmarshalOutput{NoUnkeyedLiterals: input.NoUnkeyedLiterals, Flags: input.Flags}, runtime.ErrInvalidLength + } + if postIndex > l { + return protoiface.UnmarshalOutput{NoUnkeyedLiterals: input.NoUnkeyedLiterals, Flags: input.Flags}, io.ErrUnexpectedEOF + } + x.DisabledList = append(x.DisabledList, string(dAtA[iNdEx:postIndex])) + iNdEx = postIndex + default: + iNdEx = preIndex + skippy, err := runtime.Skip(dAtA[iNdEx:]) + if err != nil { + return protoiface.UnmarshalOutput{NoUnkeyedLiterals: input.NoUnkeyedLiterals, Flags: input.Flags}, err + } + if (skippy < 0) || (iNdEx+skippy) < 0 { + return protoiface.UnmarshalOutput{NoUnkeyedLiterals: input.NoUnkeyedLiterals, Flags: input.Flags}, runtime.ErrInvalidLength + } + if (iNdEx + skippy) > l { + return protoiface.UnmarshalOutput{NoUnkeyedLiterals: input.NoUnkeyedLiterals, Flags: input.Flags}, io.ErrUnexpectedEOF + } + if !options.DiscardUnknown { + x.unknownFields = append(x.unknownFields, dAtA[iNdEx:iNdEx+skippy]...) + } + iNdEx += skippy + } + } + + if iNdEx > l { + return protoiface.UnmarshalOutput{NoUnkeyedLiterals: input.NoUnkeyedLiterals, Flags: input.Flags}, io.ErrUnexpectedEOF + } + return protoiface.UnmarshalOutput{NoUnkeyedLiterals: input.NoUnkeyedLiterals, Flags: input.Flags}, nil + } + return &protoiface.Methods{ + NoUnkeyedLiterals: struct{}{}, + Flags: protoiface.SupportMarshalDeterministic | protoiface.SupportUnmarshalDiscardUnknown, + Size: size, + Marshal: marshal, + Unmarshal: unmarshal, + Merge: nil, + CheckInitialized: nil, + } +} + +// Code generated by protoc-gen-go. DO NOT EDIT. +// versions: +// protoc-gen-go v1.27.0 +// protoc (unknown) +// source: cosmos/circuit/v1/query.proto + +const ( + // Verify that this generated code is sufficiently up-to-date. + _ = protoimpl.EnforceVersion(20 - protoimpl.MinVersion) + // Verify that runtime/protoimpl is sufficiently up-to-date. + _ = protoimpl.EnforceVersion(protoimpl.MaxVersion - 20) +) + +// QueryAccountRequest is the request type for the Query/Account RPC method. +type QueryAccountRequest struct { + state protoimpl.MessageState + sizeCache protoimpl.SizeCache + unknownFields protoimpl.UnknownFields + + Address string `protobuf:"bytes,1,opt,name=address,proto3" json:"address,omitempty"` +} + +func (x *QueryAccountRequest) Reset() { + *x = QueryAccountRequest{} + if protoimpl.UnsafeEnabled { + mi := &file_cosmos_circuit_v1_query_proto_msgTypes[0] + ms := protoimpl.X.MessageStateOf(protoimpl.Pointer(x)) + ms.StoreMessageInfo(mi) + } +} + +func (x *QueryAccountRequest) String() string { + return protoimpl.X.MessageStringOf(x) +} + +func (*QueryAccountRequest) ProtoMessage() {} + +// Deprecated: Use QueryAccountRequest.ProtoReflect.Descriptor instead. +func (*QueryAccountRequest) Descriptor() ([]byte, []int) { + return file_cosmos_circuit_v1_query_proto_rawDescGZIP(), []int{0} +} + +func (x *QueryAccountRequest) GetAddress() string { + if x != nil { + return x.Address + } + return "" +} + +// AccountResponse is the response type for the Query/Account RPC method. +type AccountResponse struct { + state protoimpl.MessageState + sizeCache protoimpl.SizeCache + unknownFields protoimpl.UnknownFields + + Permission *Permissions `protobuf:"bytes,1,opt,name=permission,proto3" json:"permission,omitempty"` +} + +func (x *AccountResponse) Reset() { + *x = AccountResponse{} + if protoimpl.UnsafeEnabled { + mi := &file_cosmos_circuit_v1_query_proto_msgTypes[1] + ms := protoimpl.X.MessageStateOf(protoimpl.Pointer(x)) + ms.StoreMessageInfo(mi) + } +} + +func (x *AccountResponse) String() string { + return protoimpl.X.MessageStringOf(x) +} + +func (*AccountResponse) ProtoMessage() {} + +// Deprecated: Use AccountResponse.ProtoReflect.Descriptor instead. +func (*AccountResponse) Descriptor() ([]byte, []int) { + return file_cosmos_circuit_v1_query_proto_rawDescGZIP(), []int{1} +} + +func (x *AccountResponse) GetPermission() *Permissions { + if x != nil { + return x.Permission + } + return nil +} + +// QueryAccountsRequest is the request type for the Query/Accounts RPC method. +type QueryAccountsRequest struct { + state protoimpl.MessageState + sizeCache protoimpl.SizeCache + unknownFields protoimpl.UnknownFields + + // pagination defines an optional pagination for the request. + Pagination *v1beta1.PageRequest `protobuf:"bytes,1,opt,name=pagination,proto3" json:"pagination,omitempty"` +} + +func (x *QueryAccountsRequest) Reset() { + *x = QueryAccountsRequest{} + if protoimpl.UnsafeEnabled { + mi := &file_cosmos_circuit_v1_query_proto_msgTypes[2] + ms := protoimpl.X.MessageStateOf(protoimpl.Pointer(x)) + ms.StoreMessageInfo(mi) + } +} + +func (x *QueryAccountsRequest) String() string { + return protoimpl.X.MessageStringOf(x) +} + +func (*QueryAccountsRequest) ProtoMessage() {} + +// Deprecated: Use QueryAccountsRequest.ProtoReflect.Descriptor instead. +func (*QueryAccountsRequest) Descriptor() ([]byte, []int) { + return file_cosmos_circuit_v1_query_proto_rawDescGZIP(), []int{2} +} + +func (x *QueryAccountsRequest) GetPagination() *v1beta1.PageRequest { + if x != nil { + return x.Pagination + } + return nil +} + +// AccountsResponse is the response type for the Query/Accounts RPC method. +type AccountsResponse struct { + state protoimpl.MessageState + sizeCache protoimpl.SizeCache + unknownFields protoimpl.UnknownFields + + Accounts []*GenesisAccountPermissions `protobuf:"bytes,1,rep,name=accounts,proto3" json:"accounts,omitempty"` + // pagination defines the pagination in the response. + Pagination *v1beta1.PageResponse `protobuf:"bytes,2,opt,name=pagination,proto3" json:"pagination,omitempty"` +} + +func (x *AccountsResponse) Reset() { + *x = AccountsResponse{} + if protoimpl.UnsafeEnabled { + mi := &file_cosmos_circuit_v1_query_proto_msgTypes[3] + ms := protoimpl.X.MessageStateOf(protoimpl.Pointer(x)) + ms.StoreMessageInfo(mi) + } +} + +func (x *AccountsResponse) String() string { + return protoimpl.X.MessageStringOf(x) +} + +func (*AccountsResponse) ProtoMessage() {} + +// Deprecated: Use AccountsResponse.ProtoReflect.Descriptor instead. +func (*AccountsResponse) Descriptor() ([]byte, []int) { + return file_cosmos_circuit_v1_query_proto_rawDescGZIP(), []int{3} +} + +func (x *AccountsResponse) GetAccounts() []*GenesisAccountPermissions { + if x != nil { + return x.Accounts + } + return nil +} + +func (x *AccountsResponse) GetPagination() *v1beta1.PageResponse { + if x != nil { + return x.Pagination + } + return nil +} + +// QueryDisableListRequest is the request type for the Query/DisabledList RPC method. +type QueryDisabledListRequest struct { + state protoimpl.MessageState + sizeCache protoimpl.SizeCache + unknownFields protoimpl.UnknownFields +} + +func (x *QueryDisabledListRequest) Reset() { + *x = QueryDisabledListRequest{} + if protoimpl.UnsafeEnabled { + mi := &file_cosmos_circuit_v1_query_proto_msgTypes[4] + ms := protoimpl.X.MessageStateOf(protoimpl.Pointer(x)) + ms.StoreMessageInfo(mi) + } +} + +func (x *QueryDisabledListRequest) String() string { + return protoimpl.X.MessageStringOf(x) +} + +func (*QueryDisabledListRequest) ProtoMessage() {} + +// Deprecated: Use QueryDisabledListRequest.ProtoReflect.Descriptor instead. +func (*QueryDisabledListRequest) Descriptor() ([]byte, []int) { + return file_cosmos_circuit_v1_query_proto_rawDescGZIP(), []int{4} +} + +// DisabledListResponse is the response type for the Query/DisabledList RPC method. +type DisabledListResponse struct { + state protoimpl.MessageState + sizeCache protoimpl.SizeCache + unknownFields protoimpl.UnknownFields + + DisabledList []string `protobuf:"bytes,1,rep,name=disabled_list,json=disabledList,proto3" json:"disabled_list,omitempty"` +} + +func (x *DisabledListResponse) Reset() { + *x = DisabledListResponse{} + if protoimpl.UnsafeEnabled { + mi := &file_cosmos_circuit_v1_query_proto_msgTypes[5] + ms := protoimpl.X.MessageStateOf(protoimpl.Pointer(x)) + ms.StoreMessageInfo(mi) + } +} + +func (x *DisabledListResponse) String() string { + return protoimpl.X.MessageStringOf(x) +} + +func (*DisabledListResponse) ProtoMessage() {} + +// Deprecated: Use DisabledListResponse.ProtoReflect.Descriptor instead. +func (*DisabledListResponse) Descriptor() ([]byte, []int) { + return file_cosmos_circuit_v1_query_proto_rawDescGZIP(), []int{5} +} + +func (x *DisabledListResponse) GetDisabledList() []string { + if x != nil { + return x.DisabledList + } + return nil +} + +var File_cosmos_circuit_v1_query_proto protoreflect.FileDescriptor + +var file_cosmos_circuit_v1_query_proto_rawDesc = []byte{ + 0x0a, 0x1d, 0x63, 0x6f, 0x73, 0x6d, 0x6f, 0x73, 0x2f, 0x63, 0x69, 0x72, 0x63, 0x75, 0x69, 0x74, + 0x2f, 0x76, 0x31, 0x2f, 0x71, 0x75, 0x65, 0x72, 0x79, 0x2e, 0x70, 0x72, 0x6f, 0x74, 0x6f, 0x12, + 0x11, 0x63, 0x6f, 0x73, 0x6d, 0x6f, 0x73, 0x2e, 0x63, 0x69, 0x72, 0x63, 0x75, 0x69, 0x74, 0x2e, + 0x76, 0x31, 0x1a, 0x2a, 0x63, 0x6f, 0x73, 0x6d, 0x6f, 0x73, 0x2f, 0x62, 0x61, 0x73, 0x65, 0x2f, + 0x71, 0x75, 0x65, 0x72, 0x79, 0x2f, 0x76, 0x31, 0x62, 0x65, 0x74, 0x61, 0x31, 0x2f, 0x70, 0x61, + 0x67, 0x69, 0x6e, 0x61, 0x74, 0x69, 0x6f, 0x6e, 0x2e, 0x70, 0x72, 0x6f, 0x74, 0x6f, 0x1a, 0x17, + 0x63, 0x6f, 0x73, 0x6d, 0x6f, 0x73, 0x2f, 0x6d, 0x73, 0x67, 0x2f, 0x76, 0x31, 0x2f, 0x6d, 0x73, + 0x67, 0x2e, 0x70, 0x72, 0x6f, 0x74, 0x6f, 0x1a, 0x1d, 0x63, 0x6f, 0x73, 0x6d, 0x6f, 0x73, 0x2f, + 0x63, 0x69, 0x72, 0x63, 0x75, 0x69, 0x74, 0x2f, 0x76, 0x31, 0x2f, 0x74, 0x79, 0x70, 0x65, 0x73, + 0x2e, 0x70, 0x72, 0x6f, 0x74, 0x6f, 0x1a, 0x1c, 0x67, 0x6f, 0x6f, 0x67, 0x6c, 0x65, 0x2f, 0x61, + 0x70, 0x69, 0x2f, 0x61, 0x6e, 0x6e, 0x6f, 0x74, 0x61, 0x74, 0x69, 0x6f, 0x6e, 0x73, 0x2e, 0x70, + 0x72, 0x6f, 0x74, 0x6f, 0x1a, 0x1b, 0x63, 0x6f, 0x73, 0x6d, 0x6f, 0x73, 0x2f, 0x71, 0x75, 0x65, + 0x72, 0x79, 0x2f, 0x76, 0x31, 0x2f, 0x71, 0x75, 0x65, 0x72, 0x79, 0x2e, 0x70, 0x72, 0x6f, 0x74, + 0x6f, 0x22, 0x2f, 0x0a, 0x13, 0x51, 0x75, 0x65, 0x72, 0x79, 0x41, 0x63, 0x63, 0x6f, 0x75, 0x6e, + 0x74, 0x52, 0x65, 0x71, 0x75, 0x65, 0x73, 0x74, 0x12, 0x18, 0x0a, 0x07, 0x61, 0x64, 0x64, 0x72, + 0x65, 0x73, 0x73, 0x18, 0x01, 0x20, 0x01, 0x28, 0x09, 0x52, 0x07, 0x61, 0x64, 0x64, 0x72, 0x65, + 0x73, 0x73, 0x22, 0x51, 0x0a, 0x0f, 0x41, 0x63, 0x63, 0x6f, 0x75, 0x6e, 0x74, 0x52, 0x65, 0x73, + 0x70, 0x6f, 0x6e, 0x73, 0x65, 0x12, 0x3e, 0x0a, 0x0a, 0x70, 0x65, 0x72, 0x6d, 0x69, 0x73, 0x73, + 0x69, 0x6f, 0x6e, 0x18, 0x01, 0x20, 0x01, 0x28, 0x0b, 0x32, 0x1e, 0x2e, 0x63, 0x6f, 0x73, 0x6d, + 0x6f, 0x73, 0x2e, 0x63, 0x69, 0x72, 0x63, 0x75, 0x69, 0x74, 0x2e, 0x76, 0x31, 0x2e, 0x50, 0x65, + 0x72, 0x6d, 0x69, 0x73, 0x73, 0x69, 0x6f, 0x6e, 0x73, 0x52, 0x0a, 0x70, 0x65, 0x72, 0x6d, 0x69, + 0x73, 0x73, 0x69, 0x6f, 0x6e, 0x22, 0x5e, 0x0a, 0x14, 0x51, 0x75, 0x65, 0x72, 0x79, 0x41, 0x63, + 0x63, 0x6f, 0x75, 0x6e, 0x74, 0x73, 0x52, 0x65, 0x71, 0x75, 0x65, 0x73, 0x74, 0x12, 0x46, 0x0a, + 0x0a, 0x70, 0x61, 0x67, 0x69, 0x6e, 0x61, 0x74, 0x69, 0x6f, 0x6e, 0x18, 0x01, 0x20, 0x01, 0x28, + 0x0b, 0x32, 0x26, 0x2e, 0x63, 0x6f, 0x73, 0x6d, 0x6f, 0x73, 0x2e, 0x62, 0x61, 0x73, 0x65, 0x2e, + 0x71, 0x75, 0x65, 0x72, 0x79, 0x2e, 0x76, 0x31, 0x62, 0x65, 0x74, 0x61, 0x31, 0x2e, 0x50, 0x61, + 0x67, 0x65, 0x52, 0x65, 0x71, 0x75, 0x65, 0x73, 0x74, 0x52, 0x0a, 0x70, 0x61, 0x67, 0x69, 0x6e, + 0x61, 0x74, 0x69, 0x6f, 0x6e, 0x22, 0xa5, 0x01, 0x0a, 0x10, 0x41, 0x63, 0x63, 0x6f, 0x75, 0x6e, + 0x74, 0x73, 0x52, 0x65, 0x73, 0x70, 0x6f, 0x6e, 0x73, 0x65, 0x12, 0x48, 0x0a, 0x08, 0x61, 0x63, + 0x63, 0x6f, 0x75, 0x6e, 0x74, 0x73, 0x18, 0x01, 0x20, 0x03, 0x28, 0x0b, 0x32, 0x2c, 0x2e, 0x63, + 0x6f, 0x73, 0x6d, 0x6f, 0x73, 0x2e, 0x63, 0x69, 0x72, 0x63, 0x75, 0x69, 0x74, 0x2e, 0x76, 0x31, + 0x2e, 0x47, 0x65, 0x6e, 0x65, 0x73, 0x69, 0x73, 0x41, 0x63, 0x63, 0x6f, 0x75, 0x6e, 0x74, 0x50, + 0x65, 0x72, 0x6d, 0x69, 0x73, 0x73, 0x69, 0x6f, 0x6e, 0x73, 0x52, 0x08, 0x61, 0x63, 0x63, 0x6f, + 0x75, 0x6e, 0x74, 0x73, 0x12, 0x47, 0x0a, 0x0a, 0x70, 0x61, 0x67, 0x69, 0x6e, 0x61, 0x74, 0x69, + 0x6f, 0x6e, 0x18, 0x02, 0x20, 0x01, 0x28, 0x0b, 0x32, 0x27, 0x2e, 0x63, 0x6f, 0x73, 0x6d, 0x6f, + 0x73, 0x2e, 0x62, 0x61, 0x73, 0x65, 0x2e, 0x71, 0x75, 0x65, 0x72, 0x79, 0x2e, 0x76, 0x31, 0x62, + 0x65, 0x74, 0x61, 0x31, 0x2e, 0x50, 0x61, 0x67, 0x65, 0x52, 0x65, 0x73, 0x70, 0x6f, 0x6e, 0x73, + 0x65, 0x52, 0x0a, 0x70, 0x61, 0x67, 0x69, 0x6e, 0x61, 0x74, 0x69, 0x6f, 0x6e, 0x22, 0x1a, 0x0a, + 0x18, 0x51, 0x75, 0x65, 0x72, 0x79, 0x44, 0x69, 0x73, 0x61, 0x62, 0x6c, 0x65, 0x64, 0x4c, 0x69, + 0x73, 0x74, 0x52, 0x65, 0x71, 0x75, 0x65, 0x73, 0x74, 0x22, 0x3b, 0x0a, 0x14, 0x44, 0x69, 0x73, + 0x61, 0x62, 0x6c, 0x65, 0x64, 0x4c, 0x69, 0x73, 0x74, 0x52, 0x65, 0x73, 0x70, 0x6f, 0x6e, 0x73, + 0x65, 0x12, 0x23, 0x0a, 0x0d, 0x64, 0x69, 0x73, 0x61, 0x62, 0x6c, 0x65, 0x64, 0x5f, 0x6c, 0x69, + 0x73, 0x74, 0x18, 0x01, 0x20, 0x03, 0x28, 0x09, 0x52, 0x0c, 0x64, 0x69, 0x73, 0x61, 0x62, 0x6c, + 0x65, 0x64, 0x4c, 0x69, 0x73, 0x74, 0x32, 0xb4, 0x03, 0x0a, 0x05, 0x51, 0x75, 0x65, 0x72, 0x79, + 0x12, 0x89, 0x01, 0x0a, 0x07, 0x41, 0x63, 0x63, 0x6f, 0x75, 0x6e, 0x74, 0x12, 0x26, 0x2e, 0x63, + 0x6f, 0x73, 0x6d, 0x6f, 0x73, 0x2e, 0x63, 0x69, 0x72, 0x63, 0x75, 0x69, 0x74, 0x2e, 0x76, 0x31, + 0x2e, 0x51, 0x75, 0x65, 0x72, 0x79, 0x41, 0x63, 0x63, 0x6f, 0x75, 0x6e, 0x74, 0x52, 0x65, 0x71, + 0x75, 0x65, 0x73, 0x74, 0x1a, 0x22, 0x2e, 0x63, 0x6f, 0x73, 0x6d, 0x6f, 0x73, 0x2e, 0x63, 0x69, + 0x72, 0x63, 0x75, 0x69, 0x74, 0x2e, 0x76, 0x31, 0x2e, 0x41, 0x63, 0x63, 0x6f, 0x75, 0x6e, 0x74, + 0x52, 0x65, 0x73, 0x70, 0x6f, 0x6e, 0x73, 0x65, 0x22, 0x32, 0x88, 0xe7, 0xb0, 0x2a, 0x01, 0x82, + 0xd3, 0xe4, 0x93, 0x02, 0x27, 0x12, 0x25, 0x2f, 0x63, 0x6f, 0x73, 0x6d, 0x6f, 0x73, 0x2f, 0x63, + 0x69, 0x72, 0x63, 0x75, 0x69, 0x74, 0x2f, 0x76, 0x31, 0x2f, 0x61, 0x63, 0x63, 0x6f, 0x75, 0x6e, + 0x74, 0x73, 0x2f, 0x7b, 0x61, 0x64, 0x64, 0x72, 0x65, 0x73, 0x73, 0x7d, 0x12, 0x82, 0x01, 0x0a, + 0x08, 0x41, 0x63, 0x63, 0x6f, 0x75, 0x6e, 0x74, 0x73, 0x12, 0x27, 0x2e, 0x63, 0x6f, 0x73, 0x6d, + 0x6f, 0x73, 0x2e, 0x63, 0x69, 0x72, 0x63, 0x75, 0x69, 0x74, 0x2e, 0x76, 0x31, 0x2e, 0x51, 0x75, + 0x65, 0x72, 0x79, 0x41, 0x63, 0x63, 0x6f, 0x75, 0x6e, 0x74, 0x73, 0x52, 0x65, 0x71, 0x75, 0x65, + 0x73, 0x74, 0x1a, 0x23, 0x2e, 0x63, 0x6f, 0x73, 0x6d, 0x6f, 0x73, 0x2e, 0x63, 0x69, 0x72, 0x63, + 0x75, 0x69, 0x74, 0x2e, 0x76, 0x31, 0x2e, 0x41, 0x63, 0x63, 0x6f, 0x75, 0x6e, 0x74, 0x73, 0x52, + 0x65, 0x73, 0x70, 0x6f, 0x6e, 0x73, 0x65, 0x22, 0x28, 0x88, 0xe7, 0xb0, 0x2a, 0x01, 0x82, 0xd3, + 0xe4, 0x93, 0x02, 0x1d, 0x12, 0x1b, 0x2f, 0x63, 0x6f, 0x73, 0x6d, 0x6f, 0x73, 0x2f, 0x63, 0x69, + 0x72, 0x63, 0x75, 0x69, 0x74, 0x2f, 0x76, 0x31, 0x2f, 0x61, 0x63, 0x63, 0x6f, 0x75, 0x6e, 0x74, + 0x73, 0x12, 0x92, 0x01, 0x0a, 0x0c, 0x44, 0x69, 0x73, 0x61, 0x62, 0x6c, 0x65, 0x64, 0x4c, 0x69, + 0x73, 0x74, 0x12, 0x2b, 0x2e, 0x63, 0x6f, 0x73, 0x6d, 0x6f, 0x73, 0x2e, 0x63, 0x69, 0x72, 0x63, + 0x75, 0x69, 0x74, 0x2e, 0x76, 0x31, 0x2e, 0x51, 0x75, 0x65, 0x72, 0x79, 0x44, 0x69, 0x73, 0x61, + 0x62, 0x6c, 0x65, 0x64, 0x4c, 0x69, 0x73, 0x74, 0x52, 0x65, 0x71, 0x75, 0x65, 0x73, 0x74, 0x1a, + 0x27, 0x2e, 0x63, 0x6f, 0x73, 0x6d, 0x6f, 0x73, 0x2e, 0x63, 0x69, 0x72, 0x63, 0x75, 0x69, 0x74, + 0x2e, 0x76, 0x31, 0x2e, 0x44, 0x69, 0x73, 0x61, 0x62, 0x6c, 0x65, 0x64, 0x4c, 0x69, 0x73, 0x74, + 0x52, 0x65, 0x73, 0x70, 0x6f, 0x6e, 0x73, 0x65, 0x22, 0x2c, 0x88, 0xe7, 0xb0, 0x2a, 0x01, 0x82, + 0xd3, 0xe4, 0x93, 0x02, 0x21, 0x12, 0x1f, 0x2f, 0x63, 0x6f, 0x73, 0x6d, 0x6f, 0x73, 0x2f, 0x63, + 0x69, 0x72, 0x63, 0x75, 0x69, 0x74, 0x2f, 0x76, 0x31, 0x2f, 0x64, 0x69, 0x73, 0x61, 0x62, 0x6c, + 0x65, 0x5f, 0x6c, 0x69, 0x73, 0x74, 0x1a, 0x05, 0x80, 0xe7, 0xb0, 0x2a, 0x01, 0x42, 0xb7, 0x01, + 0x0a, 0x15, 0x63, 0x6f, 0x6d, 0x2e, 0x63, 0x6f, 0x73, 0x6d, 0x6f, 0x73, 0x2e, 0x63, 0x69, 0x72, + 0x63, 0x75, 0x69, 0x74, 0x2e, 0x76, 0x31, 0x42, 0x0a, 0x51, 0x75, 0x65, 0x72, 0x79, 0x50, 0x72, + 0x6f, 0x74, 0x6f, 0x50, 0x01, 0x5a, 0x2c, 0x63, 0x6f, 0x73, 0x6d, 0x6f, 0x73, 0x73, 0x64, 0x6b, + 0x2e, 0x69, 0x6f, 0x2f, 0x61, 0x70, 0x69, 0x2f, 0x63, 0x6f, 0x73, 0x6d, 0x6f, 0x73, 0x2f, 0x63, + 0x69, 0x72, 0x63, 0x75, 0x69, 0x74, 0x2f, 0x76, 0x31, 0x3b, 0x63, 0x69, 0x72, 0x63, 0x75, 0x69, + 0x74, 0x76, 0x31, 0xa2, 0x02, 0x03, 0x43, 0x43, 0x58, 0xaa, 0x02, 0x11, 0x43, 0x6f, 0x73, 0x6d, + 0x6f, 0x73, 0x2e, 0x43, 0x69, 0x72, 0x63, 0x75, 0x69, 0x74, 0x2e, 0x56, 0x31, 0xca, 0x02, 0x11, + 0x43, 0x6f, 0x73, 0x6d, 0x6f, 0x73, 0x5c, 0x43, 0x69, 0x72, 0x63, 0x75, 0x69, 0x74, 0x5c, 0x56, + 0x31, 0xe2, 0x02, 0x1d, 0x43, 0x6f, 0x73, 0x6d, 0x6f, 0x73, 0x5c, 0x43, 0x69, 0x72, 0x63, 0x75, + 0x69, 0x74, 0x5c, 0x56, 0x31, 0x5c, 0x47, 0x50, 0x42, 0x4d, 0x65, 0x74, 0x61, 0x64, 0x61, 0x74, + 0x61, 0xea, 0x02, 0x13, 0x43, 0x6f, 0x73, 0x6d, 0x6f, 0x73, 0x3a, 0x3a, 0x43, 0x69, 0x72, 0x63, + 0x75, 0x69, 0x74, 0x3a, 0x3a, 0x56, 0x31, 0x62, 0x06, 0x70, 0x72, 0x6f, 0x74, 0x6f, 0x33, +} + +var ( + file_cosmos_circuit_v1_query_proto_rawDescOnce sync.Once + file_cosmos_circuit_v1_query_proto_rawDescData = file_cosmos_circuit_v1_query_proto_rawDesc +) + +func file_cosmos_circuit_v1_query_proto_rawDescGZIP() []byte { + file_cosmos_circuit_v1_query_proto_rawDescOnce.Do(func() { + file_cosmos_circuit_v1_query_proto_rawDescData = protoimpl.X.CompressGZIP(file_cosmos_circuit_v1_query_proto_rawDescData) + }) + return file_cosmos_circuit_v1_query_proto_rawDescData +} + +var file_cosmos_circuit_v1_query_proto_msgTypes = make([]protoimpl.MessageInfo, 6) +var file_cosmos_circuit_v1_query_proto_goTypes = []interface{}{ + (*QueryAccountRequest)(nil), // 0: cosmos.circuit.v1.QueryAccountRequest + (*AccountResponse)(nil), // 1: cosmos.circuit.v1.AccountResponse + (*QueryAccountsRequest)(nil), // 2: cosmos.circuit.v1.QueryAccountsRequest + (*AccountsResponse)(nil), // 3: cosmos.circuit.v1.AccountsResponse + (*QueryDisabledListRequest)(nil), // 4: cosmos.circuit.v1.QueryDisabledListRequest + (*DisabledListResponse)(nil), // 5: cosmos.circuit.v1.DisabledListResponse + (*Permissions)(nil), // 6: cosmos.circuit.v1.Permissions + (*v1beta1.PageRequest)(nil), // 7: cosmos.base.query.v1beta1.PageRequest + (*GenesisAccountPermissions)(nil), // 8: cosmos.circuit.v1.GenesisAccountPermissions + (*v1beta1.PageResponse)(nil), // 9: cosmos.base.query.v1beta1.PageResponse +} +var file_cosmos_circuit_v1_query_proto_depIdxs = []int32{ + 6, // 0: cosmos.circuit.v1.AccountResponse.permission:type_name -> cosmos.circuit.v1.Permissions + 7, // 1: cosmos.circuit.v1.QueryAccountsRequest.pagination:type_name -> cosmos.base.query.v1beta1.PageRequest + 8, // 2: cosmos.circuit.v1.AccountsResponse.accounts:type_name -> cosmos.circuit.v1.GenesisAccountPermissions + 9, // 3: cosmos.circuit.v1.AccountsResponse.pagination:type_name -> cosmos.base.query.v1beta1.PageResponse + 0, // 4: cosmos.circuit.v1.Query.Account:input_type -> cosmos.circuit.v1.QueryAccountRequest + 2, // 5: cosmos.circuit.v1.Query.Accounts:input_type -> cosmos.circuit.v1.QueryAccountsRequest + 4, // 6: cosmos.circuit.v1.Query.DisabledList:input_type -> cosmos.circuit.v1.QueryDisabledListRequest + 1, // 7: cosmos.circuit.v1.Query.Account:output_type -> cosmos.circuit.v1.AccountResponse + 3, // 8: cosmos.circuit.v1.Query.Accounts:output_type -> cosmos.circuit.v1.AccountsResponse + 5, // 9: cosmos.circuit.v1.Query.DisabledList:output_type -> cosmos.circuit.v1.DisabledListResponse + 7, // [7:10] is the sub-list for method output_type + 4, // [4:7] is the sub-list for method input_type + 4, // [4:4] is the sub-list for extension type_name + 4, // [4:4] is the sub-list for extension extendee + 0, // [0:4] is the sub-list for field type_name +} + +func init() { file_cosmos_circuit_v1_query_proto_init() } +func file_cosmos_circuit_v1_query_proto_init() { + if File_cosmos_circuit_v1_query_proto != nil { + return + } + file_cosmos_circuit_v1_types_proto_init() + if !protoimpl.UnsafeEnabled { + file_cosmos_circuit_v1_query_proto_msgTypes[0].Exporter = func(v interface{}, i int) interface{} { + switch v := v.(*QueryAccountRequest); i { + case 0: + return &v.state + case 1: + return &v.sizeCache + case 2: + return &v.unknownFields + default: + return nil + } + } + file_cosmos_circuit_v1_query_proto_msgTypes[1].Exporter = func(v interface{}, i int) interface{} { + switch v := v.(*AccountResponse); i { + case 0: + return &v.state + case 1: + return &v.sizeCache + case 2: + return &v.unknownFields + default: + return nil + } + } + file_cosmos_circuit_v1_query_proto_msgTypes[2].Exporter = func(v interface{}, i int) interface{} { + switch v := v.(*QueryAccountsRequest); i { + case 0: + return &v.state + case 1: + return &v.sizeCache + case 2: + return &v.unknownFields + default: + return nil + } + } + file_cosmos_circuit_v1_query_proto_msgTypes[3].Exporter = func(v interface{}, i int) interface{} { + switch v := v.(*AccountsResponse); i { + case 0: + return &v.state + case 1: + return &v.sizeCache + case 2: + return &v.unknownFields + default: + return nil + } + } + file_cosmos_circuit_v1_query_proto_msgTypes[4].Exporter = func(v interface{}, i int) interface{} { + switch v := v.(*QueryDisabledListRequest); i { + case 0: + return &v.state + case 1: + return &v.sizeCache + case 2: + return &v.unknownFields + default: + return nil + } + } + file_cosmos_circuit_v1_query_proto_msgTypes[5].Exporter = func(v interface{}, i int) interface{} { + switch v := v.(*DisabledListResponse); i { + case 0: + return &v.state + case 1: + return &v.sizeCache + case 2: + return &v.unknownFields + default: + return nil + } + } + } + type x struct{} + out := protoimpl.TypeBuilder{ + File: protoimpl.DescBuilder{ + GoPackagePath: reflect.TypeOf(x{}).PkgPath(), + RawDescriptor: file_cosmos_circuit_v1_query_proto_rawDesc, + NumEnums: 0, + NumMessages: 6, + NumExtensions: 0, + NumServices: 1, + }, + GoTypes: file_cosmos_circuit_v1_query_proto_goTypes, + DependencyIndexes: file_cosmos_circuit_v1_query_proto_depIdxs, + MessageInfos: file_cosmos_circuit_v1_query_proto_msgTypes, + }.Build() + File_cosmos_circuit_v1_query_proto = out.File + file_cosmos_circuit_v1_query_proto_rawDesc = nil + file_cosmos_circuit_v1_query_proto_goTypes = nil + file_cosmos_circuit_v1_query_proto_depIdxs = nil +} diff --git a/api/cosmos/circuit/v1/query_grpc.pb.go b/api/cosmos/circuit/v1/query_grpc.pb.go new file mode 100644 index 000000000000..6218b68d8bd1 --- /dev/null +++ b/api/cosmos/circuit/v1/query_grpc.pb.go @@ -0,0 +1,189 @@ +// Code generated by protoc-gen-go-grpc. DO NOT EDIT. +// versions: +// - protoc-gen-go-grpc v1.3.0 +// - protoc (unknown) +// source: cosmos/circuit/v1/query.proto + +package circuitv1 + +import ( + context "context" + grpc "google.golang.org/grpc" + codes "google.golang.org/grpc/codes" + status "google.golang.org/grpc/status" +) + +// This is a compile-time assertion to ensure that this generated file +// is compatible with the grpc package it is being compiled against. +// Requires gRPC-Go v1.32.0 or later. +const _ = grpc.SupportPackageIsVersion7 + +const ( + Query_Account_FullMethodName = "/cosmos.circuit.v1.Query/Account" + Query_Accounts_FullMethodName = "/cosmos.circuit.v1.Query/Accounts" + Query_DisabledList_FullMethodName = "/cosmos.circuit.v1.Query/DisabledList" +) + +// QueryClient is the client API for Query service. +// +// For semantics around ctx use and closing/ending streaming RPCs, please refer to https://pkg.go.dev/google.golang.org/grpc/?tab=doc#ClientConn.NewStream. +type QueryClient interface { + // Account returns account permissions. + Account(ctx context.Context, in *QueryAccountRequest, opts ...grpc.CallOption) (*AccountResponse, error) + // Account returns account permissions. + Accounts(ctx context.Context, in *QueryAccountsRequest, opts ...grpc.CallOption) (*AccountsResponse, error) + // DisabledList returns a list of disabled message urls + DisabledList(ctx context.Context, in *QueryDisabledListRequest, opts ...grpc.CallOption) (*DisabledListResponse, error) +} + +type queryClient struct { + cc grpc.ClientConnInterface +} + +func NewQueryClient(cc grpc.ClientConnInterface) QueryClient { + return &queryClient{cc} +} + +func (c *queryClient) Account(ctx context.Context, in *QueryAccountRequest, opts ...grpc.CallOption) (*AccountResponse, error) { + out := new(AccountResponse) + err := c.cc.Invoke(ctx, Query_Account_FullMethodName, in, out, opts...) + if err != nil { + return nil, err + } + return out, nil +} + +func (c *queryClient) Accounts(ctx context.Context, in *QueryAccountsRequest, opts ...grpc.CallOption) (*AccountsResponse, error) { + out := new(AccountsResponse) + err := c.cc.Invoke(ctx, Query_Accounts_FullMethodName, in, out, opts...) + if err != nil { + return nil, err + } + return out, nil +} + +func (c *queryClient) DisabledList(ctx context.Context, in *QueryDisabledListRequest, opts ...grpc.CallOption) (*DisabledListResponse, error) { + out := new(DisabledListResponse) + err := c.cc.Invoke(ctx, Query_DisabledList_FullMethodName, in, out, opts...) + if err != nil { + return nil, err + } + return out, nil +} + +// QueryServer is the server API for Query service. +// All implementations must embed UnimplementedQueryServer +// for forward compatibility +type QueryServer interface { + // Account returns account permissions. + Account(context.Context, *QueryAccountRequest) (*AccountResponse, error) + // Account returns account permissions. + Accounts(context.Context, *QueryAccountsRequest) (*AccountsResponse, error) + // DisabledList returns a list of disabled message urls + DisabledList(context.Context, *QueryDisabledListRequest) (*DisabledListResponse, error) + mustEmbedUnimplementedQueryServer() +} + +// UnimplementedQueryServer must be embedded to have forward compatible implementations. +type UnimplementedQueryServer struct { +} + +func (UnimplementedQueryServer) Account(context.Context, *QueryAccountRequest) (*AccountResponse, error) { + return nil, status.Errorf(codes.Unimplemented, "method Account not implemented") +} +func (UnimplementedQueryServer) Accounts(context.Context, *QueryAccountsRequest) (*AccountsResponse, error) { + return nil, status.Errorf(codes.Unimplemented, "method Accounts not implemented") +} +func (UnimplementedQueryServer) DisabledList(context.Context, *QueryDisabledListRequest) (*DisabledListResponse, error) { + return nil, status.Errorf(codes.Unimplemented, "method DisabledList not implemented") +} +func (UnimplementedQueryServer) mustEmbedUnimplementedQueryServer() {} + +// UnsafeQueryServer may be embedded to opt out of forward compatibility for this service. +// Use of this interface is not recommended, as added methods to QueryServer will +// result in compilation errors. +type UnsafeQueryServer interface { + mustEmbedUnimplementedQueryServer() +} + +func RegisterQueryServer(s grpc.ServiceRegistrar, srv QueryServer) { + s.RegisterService(&Query_ServiceDesc, srv) +} + +func _Query_Account_Handler(srv interface{}, ctx context.Context, dec func(interface{}) error, interceptor grpc.UnaryServerInterceptor) (interface{}, error) { + in := new(QueryAccountRequest) + if err := dec(in); err != nil { + return nil, err + } + if interceptor == nil { + return srv.(QueryServer).Account(ctx, in) + } + info := &grpc.UnaryServerInfo{ + Server: srv, + FullMethod: Query_Account_FullMethodName, + } + handler := func(ctx context.Context, req interface{}) (interface{}, error) { + return srv.(QueryServer).Account(ctx, req.(*QueryAccountRequest)) + } + return interceptor(ctx, in, info, handler) +} + +func _Query_Accounts_Handler(srv interface{}, ctx context.Context, dec func(interface{}) error, interceptor grpc.UnaryServerInterceptor) (interface{}, error) { + in := new(QueryAccountsRequest) + if err := dec(in); err != nil { + return nil, err + } + if interceptor == nil { + return srv.(QueryServer).Accounts(ctx, in) + } + info := &grpc.UnaryServerInfo{ + Server: srv, + FullMethod: Query_Accounts_FullMethodName, + } + handler := func(ctx context.Context, req interface{}) (interface{}, error) { + return srv.(QueryServer).Accounts(ctx, req.(*QueryAccountsRequest)) + } + return interceptor(ctx, in, info, handler) +} + +func _Query_DisabledList_Handler(srv interface{}, ctx context.Context, dec func(interface{}) error, interceptor grpc.UnaryServerInterceptor) (interface{}, error) { + in := new(QueryDisabledListRequest) + if err := dec(in); err != nil { + return nil, err + } + if interceptor == nil { + return srv.(QueryServer).DisabledList(ctx, in) + } + info := &grpc.UnaryServerInfo{ + Server: srv, + FullMethod: Query_DisabledList_FullMethodName, + } + handler := func(ctx context.Context, req interface{}) (interface{}, error) { + return srv.(QueryServer).DisabledList(ctx, req.(*QueryDisabledListRequest)) + } + return interceptor(ctx, in, info, handler) +} + +// Query_ServiceDesc is the grpc.ServiceDesc for Query service. +// It's only intended for direct use with grpc.RegisterService, +// and not to be introspected or modified (even as a copy) +var Query_ServiceDesc = grpc.ServiceDesc{ + ServiceName: "cosmos.circuit.v1.Query", + HandlerType: (*QueryServer)(nil), + Methods: []grpc.MethodDesc{ + { + MethodName: "Account", + Handler: _Query_Account_Handler, + }, + { + MethodName: "Accounts", + Handler: _Query_Accounts_Handler, + }, + { + MethodName: "DisabledList", + Handler: _Query_DisabledList_Handler, + }, + }, + Streams: []grpc.StreamDesc{}, + Metadata: "cosmos/circuit/v1/query.proto", +} diff --git a/api/cosmos/circuit/v1/tx.pulsar.go b/api/cosmos/circuit/v1/tx.pulsar.go index 42721c7fe160..ca2f3e5012e4 100644 --- a/api/cosmos/circuit/v1/tx.pulsar.go +++ b/api/cosmos/circuit/v1/tx.pulsar.go @@ -204,7 +204,7 @@ func (x *fastReflection_MsgAuthorizeCircuitBreaker) Set(fd protoreflect.FieldDes case "cosmos.circuit.v1.MsgAuthorizeCircuitBreaker.grantee": x.Grantee = value.Interface().(string) case "cosmos.circuit.v1.MsgAuthorizeCircuitBreaker.permissions": - x.Permissions = value.Message().Interface().(*CircuitBreakerPermissions) + x.Permissions = value.Message().Interface().(*Permissions) default: if fd.IsExtension() { panic(fmt.Errorf("proto3 declared messages do not support extensions: cosmos.circuit.v1.MsgAuthorizeCircuitBreaker")) @@ -227,7 +227,7 @@ func (x *fastReflection_MsgAuthorizeCircuitBreaker) Mutable(fd protoreflect.Fiel switch fd.FullName() { case "cosmos.circuit.v1.MsgAuthorizeCircuitBreaker.permissions": if x.Permissions == nil { - x.Permissions = new(CircuitBreakerPermissions) + x.Permissions = new(Permissions) } return protoreflect.ValueOfMessage(x.Permissions.ProtoReflect()) case "cosmos.circuit.v1.MsgAuthorizeCircuitBreaker.granter": @@ -252,7 +252,7 @@ func (x *fastReflection_MsgAuthorizeCircuitBreaker) NewField(fd protoreflect.Fie case "cosmos.circuit.v1.MsgAuthorizeCircuitBreaker.grantee": return protoreflect.ValueOfString("") case "cosmos.circuit.v1.MsgAuthorizeCircuitBreaker.permissions": - m := new(CircuitBreakerPermissions) + m := new(Permissions) return protoreflect.ValueOfMessage(m.ProtoReflect()) default: if fd.IsExtension() { @@ -535,7 +535,7 @@ func (x *fastReflection_MsgAuthorizeCircuitBreaker) ProtoMethods() *protoiface.M return protoiface.UnmarshalOutput{NoUnkeyedLiterals: input.NoUnkeyedLiterals, Flags: input.Flags}, io.ErrUnexpectedEOF } if x.Permissions == nil { - x.Permissions = &CircuitBreakerPermissions{} + x.Permissions = &Permissions{} } if err := options.Unmarshal(dAtA[iNdEx:postIndex], x.Permissions); err != nil { return protoiface.UnmarshalOutput{NoUnkeyedLiterals: input.NoUnkeyedLiterals, Flags: input.Flags}, err @@ -577,12 +577,14 @@ func (x *fastReflection_MsgAuthorizeCircuitBreaker) ProtoMethods() *protoiface.M } var ( - md_MsgAuthorizeCircuitBreakerResponse protoreflect.MessageDescriptor + md_MsgAuthorizeCircuitBreakerResponse protoreflect.MessageDescriptor + fd_MsgAuthorizeCircuitBreakerResponse_success protoreflect.FieldDescriptor ) func init() { file_cosmos_circuit_v1_tx_proto_init() md_MsgAuthorizeCircuitBreakerResponse = File_cosmos_circuit_v1_tx_proto.Messages().ByName("MsgAuthorizeCircuitBreakerResponse") + fd_MsgAuthorizeCircuitBreakerResponse_success = md_MsgAuthorizeCircuitBreakerResponse.Fields().ByName("success") } var _ protoreflect.Message = (*fastReflection_MsgAuthorizeCircuitBreakerResponse)(nil) @@ -650,421 +652,9 @@ func (x *fastReflection_MsgAuthorizeCircuitBreakerResponse) Interface() protoref // While iterating, mutating operations may only be performed // on the current field descriptor. func (x *fastReflection_MsgAuthorizeCircuitBreakerResponse) Range(f func(protoreflect.FieldDescriptor, protoreflect.Value) bool) { -} - -// Has reports whether a field is populated. -// -// Some fields have the property of nullability where it is possible to -// distinguish between the default value of a field and whether the field -// was explicitly populated with the default value. Singular message fields, -// member fields of a oneof, and proto2 scalar fields are nullable. Such -// fields are populated only if explicitly set. -// -// In other cases (aside from the nullable cases above), -// a proto3 scalar field is populated if it contains a non-zero value, and -// a repeated field is populated if it is non-empty. -func (x *fastReflection_MsgAuthorizeCircuitBreakerResponse) Has(fd protoreflect.FieldDescriptor) bool { - switch fd.FullName() { - default: - if fd.IsExtension() { - panic(fmt.Errorf("proto3 declared messages do not support extensions: cosmos.circuit.v1.MsgAuthorizeCircuitBreakerResponse")) - } - panic(fmt.Errorf("message cosmos.circuit.v1.MsgAuthorizeCircuitBreakerResponse does not contain field %s", fd.FullName())) - } -} - -// Clear clears the field such that a subsequent Has call reports false. -// -// Clearing an extension field clears both the extension type and value -// associated with the given field number. -// -// Clear is a mutating operation and unsafe for concurrent use. -func (x *fastReflection_MsgAuthorizeCircuitBreakerResponse) Clear(fd protoreflect.FieldDescriptor) { - switch fd.FullName() { - default: - if fd.IsExtension() { - panic(fmt.Errorf("proto3 declared messages do not support extensions: cosmos.circuit.v1.MsgAuthorizeCircuitBreakerResponse")) - } - panic(fmt.Errorf("message cosmos.circuit.v1.MsgAuthorizeCircuitBreakerResponse does not contain field %s", fd.FullName())) - } -} - -// Get retrieves the value for a field. -// -// For unpopulated scalars, it returns the default value, where -// the default value of a bytes scalar is guaranteed to be a copy. -// For unpopulated composite types, it returns an empty, read-only view -// of the value; to obtain a mutable reference, use Mutable. -func (x *fastReflection_MsgAuthorizeCircuitBreakerResponse) Get(descriptor protoreflect.FieldDescriptor) protoreflect.Value { - switch descriptor.FullName() { - default: - if descriptor.IsExtension() { - panic(fmt.Errorf("proto3 declared messages do not support extensions: cosmos.circuit.v1.MsgAuthorizeCircuitBreakerResponse")) - } - panic(fmt.Errorf("message cosmos.circuit.v1.MsgAuthorizeCircuitBreakerResponse does not contain field %s", descriptor.FullName())) - } -} - -// Set stores the value for a field. -// -// For a field belonging to a oneof, it implicitly clears any other field -// that may be currently set within the same oneof. -// For extension fields, it implicitly stores the provided ExtensionType. -// When setting a composite type, it is unspecified whether the stored value -// aliases the source's memory in any way. If the composite value is an -// empty, read-only value, then it panics. -// -// Set is a mutating operation and unsafe for concurrent use. -func (x *fastReflection_MsgAuthorizeCircuitBreakerResponse) Set(fd protoreflect.FieldDescriptor, value protoreflect.Value) { - switch fd.FullName() { - default: - if fd.IsExtension() { - panic(fmt.Errorf("proto3 declared messages do not support extensions: cosmos.circuit.v1.MsgAuthorizeCircuitBreakerResponse")) - } - panic(fmt.Errorf("message cosmos.circuit.v1.MsgAuthorizeCircuitBreakerResponse does not contain field %s", fd.FullName())) - } -} - -// Mutable returns a mutable reference to a composite type. -// -// If the field is unpopulated, it may allocate a composite value. -// For a field belonging to a oneof, it implicitly clears any other field -// that may be currently set within the same oneof. -// For extension fields, it implicitly stores the provided ExtensionType -// if not already stored. -// It panics if the field does not contain a composite type. -// -// Mutable is a mutating operation and unsafe for concurrent use. -func (x *fastReflection_MsgAuthorizeCircuitBreakerResponse) Mutable(fd protoreflect.FieldDescriptor) protoreflect.Value { - switch fd.FullName() { - default: - if fd.IsExtension() { - panic(fmt.Errorf("proto3 declared messages do not support extensions: cosmos.circuit.v1.MsgAuthorizeCircuitBreakerResponse")) - } - panic(fmt.Errorf("message cosmos.circuit.v1.MsgAuthorizeCircuitBreakerResponse does not contain field %s", fd.FullName())) - } -} - -// NewField returns a new value that is assignable to the field -// for the given descriptor. For scalars, this returns the default value. -// For lists, maps, and messages, this returns a new, empty, mutable value. -func (x *fastReflection_MsgAuthorizeCircuitBreakerResponse) NewField(fd protoreflect.FieldDescriptor) protoreflect.Value { - switch fd.FullName() { - default: - if fd.IsExtension() { - panic(fmt.Errorf("proto3 declared messages do not support extensions: cosmos.circuit.v1.MsgAuthorizeCircuitBreakerResponse")) - } - panic(fmt.Errorf("message cosmos.circuit.v1.MsgAuthorizeCircuitBreakerResponse does not contain field %s", fd.FullName())) - } -} - -// WhichOneof reports which field within the oneof is populated, -// returning nil if none are populated. -// It panics if the oneof descriptor does not belong to this message. -func (x *fastReflection_MsgAuthorizeCircuitBreakerResponse) WhichOneof(d protoreflect.OneofDescriptor) protoreflect.FieldDescriptor { - switch d.FullName() { - default: - panic(fmt.Errorf("%s is not a oneof field in cosmos.circuit.v1.MsgAuthorizeCircuitBreakerResponse", d.FullName())) - } - panic("unreachable") -} - -// GetUnknown retrieves the entire list of unknown fields. -// The caller may only mutate the contents of the RawFields -// if the mutated bytes are stored back into the message with SetUnknown. -func (x *fastReflection_MsgAuthorizeCircuitBreakerResponse) GetUnknown() protoreflect.RawFields { - return x.unknownFields -} - -// SetUnknown stores an entire list of unknown fields. -// The raw fields must be syntactically valid according to the wire format. -// An implementation may panic if this is not the case. -// Once stored, the caller must not mutate the content of the RawFields. -// An empty RawFields may be passed to clear the fields. -// -// SetUnknown is a mutating operation and unsafe for concurrent use. -func (x *fastReflection_MsgAuthorizeCircuitBreakerResponse) SetUnknown(fields protoreflect.RawFields) { - x.unknownFields = fields -} - -// IsValid reports whether the message is valid. -// -// An invalid message is an empty, read-only value. -// -// An invalid message often corresponds to a nil pointer of the concrete -// message type, but the details are implementation dependent. -// Validity is not part of the protobuf data model, and may not -// be preserved in marshaling or other operations. -func (x *fastReflection_MsgAuthorizeCircuitBreakerResponse) IsValid() bool { - return x != nil -} - -// ProtoMethods returns optional fastReflectionFeature-path implementations of various operations. -// This method may return nil. -// -// The returned methods type is identical to -// "google.golang.org/protobuf/runtime/protoiface".Methods. -// Consult the protoiface package documentation for details. -func (x *fastReflection_MsgAuthorizeCircuitBreakerResponse) ProtoMethods() *protoiface.Methods { - size := func(input protoiface.SizeInput) protoiface.SizeOutput { - x := input.Message.Interface().(*MsgAuthorizeCircuitBreakerResponse) - if x == nil { - return protoiface.SizeOutput{ - NoUnkeyedLiterals: input.NoUnkeyedLiterals, - Size: 0, - } - } - options := runtime.SizeInputToOptions(input) - _ = options - var n int - var l int - _ = l - if x.unknownFields != nil { - n += len(x.unknownFields) - } - return protoiface.SizeOutput{ - NoUnkeyedLiterals: input.NoUnkeyedLiterals, - Size: n, - } - } - - marshal := func(input protoiface.MarshalInput) (protoiface.MarshalOutput, error) { - x := input.Message.Interface().(*MsgAuthorizeCircuitBreakerResponse) - if x == nil { - return protoiface.MarshalOutput{ - NoUnkeyedLiterals: input.NoUnkeyedLiterals, - Buf: input.Buf, - }, nil - } - options := runtime.MarshalInputToOptions(input) - _ = options - size := options.Size(x) - dAtA := make([]byte, size) - i := len(dAtA) - _ = i - var l int - _ = l - if x.unknownFields != nil { - i -= len(x.unknownFields) - copy(dAtA[i:], x.unknownFields) - } - if input.Buf != nil { - input.Buf = append(input.Buf, dAtA...) - } else { - input.Buf = dAtA - } - return protoiface.MarshalOutput{ - NoUnkeyedLiterals: input.NoUnkeyedLiterals, - Buf: input.Buf, - }, nil - } - unmarshal := func(input protoiface.UnmarshalInput) (protoiface.UnmarshalOutput, error) { - x := input.Message.Interface().(*MsgAuthorizeCircuitBreakerResponse) - if x == nil { - return protoiface.UnmarshalOutput{ - NoUnkeyedLiterals: input.NoUnkeyedLiterals, - Flags: input.Flags, - }, nil - } - options := runtime.UnmarshalInputToOptions(input) - _ = options - dAtA := input.Buf - l := len(dAtA) - iNdEx := 0 - for iNdEx < l { - preIndex := iNdEx - var wire uint64 - for shift := uint(0); ; shift += 7 { - if shift >= 64 { - return protoiface.UnmarshalOutput{NoUnkeyedLiterals: input.NoUnkeyedLiterals, Flags: input.Flags}, runtime.ErrIntOverflow - } - if iNdEx >= l { - return protoiface.UnmarshalOutput{NoUnkeyedLiterals: input.NoUnkeyedLiterals, Flags: input.Flags}, io.ErrUnexpectedEOF - } - b := dAtA[iNdEx] - iNdEx++ - wire |= uint64(b&0x7F) << shift - if b < 0x80 { - break - } - } - fieldNum := int32(wire >> 3) - wireType := int(wire & 0x7) - if wireType == 4 { - return protoiface.UnmarshalOutput{NoUnkeyedLiterals: input.NoUnkeyedLiterals, Flags: input.Flags}, fmt.Errorf("proto: MsgAuthorizeCircuitBreakerResponse: wiretype end group for non-group") - } - if fieldNum <= 0 { - return protoiface.UnmarshalOutput{NoUnkeyedLiterals: input.NoUnkeyedLiterals, Flags: input.Flags}, fmt.Errorf("proto: MsgAuthorizeCircuitBreakerResponse: illegal tag %d (wire type %d)", fieldNum, wire) - } - switch fieldNum { - default: - iNdEx = preIndex - skippy, err := runtime.Skip(dAtA[iNdEx:]) - if err != nil { - return protoiface.UnmarshalOutput{NoUnkeyedLiterals: input.NoUnkeyedLiterals, Flags: input.Flags}, err - } - if (skippy < 0) || (iNdEx+skippy) < 0 { - return protoiface.UnmarshalOutput{NoUnkeyedLiterals: input.NoUnkeyedLiterals, Flags: input.Flags}, runtime.ErrInvalidLength - } - if (iNdEx + skippy) > l { - return protoiface.UnmarshalOutput{NoUnkeyedLiterals: input.NoUnkeyedLiterals, Flags: input.Flags}, io.ErrUnexpectedEOF - } - if !options.DiscardUnknown { - x.unknownFields = append(x.unknownFields, dAtA[iNdEx:iNdEx+skippy]...) - } - iNdEx += skippy - } - } - - if iNdEx > l { - return protoiface.UnmarshalOutput{NoUnkeyedLiterals: input.NoUnkeyedLiterals, Flags: input.Flags}, io.ErrUnexpectedEOF - } - return protoiface.UnmarshalOutput{NoUnkeyedLiterals: input.NoUnkeyedLiterals, Flags: input.Flags}, nil - } - return &protoiface.Methods{ - NoUnkeyedLiterals: struct{}{}, - Flags: protoiface.SupportMarshalDeterministic | protoiface.SupportUnmarshalDiscardUnknown, - Size: size, - Marshal: marshal, - Unmarshal: unmarshal, - Merge: nil, - CheckInitialized: nil, - } -} - -var _ protoreflect.List = (*_CircuitBreakerPermissions_2_list)(nil) - -type _CircuitBreakerPermissions_2_list struct { - list *[]string -} - -func (x *_CircuitBreakerPermissions_2_list) Len() int { - if x.list == nil { - return 0 - } - return len(*x.list) -} - -func (x *_CircuitBreakerPermissions_2_list) Get(i int) protoreflect.Value { - return protoreflect.ValueOfString((*x.list)[i]) -} - -func (x *_CircuitBreakerPermissions_2_list) Set(i int, value protoreflect.Value) { - valueUnwrapped := value.String() - concreteValue := valueUnwrapped - (*x.list)[i] = concreteValue -} - -func (x *_CircuitBreakerPermissions_2_list) Append(value protoreflect.Value) { - valueUnwrapped := value.String() - concreteValue := valueUnwrapped - *x.list = append(*x.list, concreteValue) -} - -func (x *_CircuitBreakerPermissions_2_list) AppendMutable() protoreflect.Value { - panic(fmt.Errorf("AppendMutable can not be called on message CircuitBreakerPermissions at list field LimitMsgTypes as it is not of Message kind")) -} - -func (x *_CircuitBreakerPermissions_2_list) Truncate(n int) { - *x.list = (*x.list)[:n] -} - -func (x *_CircuitBreakerPermissions_2_list) NewElement() protoreflect.Value { - v := "" - return protoreflect.ValueOfString(v) -} - -func (x *_CircuitBreakerPermissions_2_list) IsValid() bool { - return x.list != nil -} - -var ( - md_CircuitBreakerPermissions protoreflect.MessageDescriptor - fd_CircuitBreakerPermissions_level protoreflect.FieldDescriptor - fd_CircuitBreakerPermissions_limit_msg_types protoreflect.FieldDescriptor -) - -func init() { - file_cosmos_circuit_v1_tx_proto_init() - md_CircuitBreakerPermissions = File_cosmos_circuit_v1_tx_proto.Messages().ByName("CircuitBreakerPermissions") - fd_CircuitBreakerPermissions_level = md_CircuitBreakerPermissions.Fields().ByName("level") - fd_CircuitBreakerPermissions_limit_msg_types = md_CircuitBreakerPermissions.Fields().ByName("limit_msg_types") -} - -var _ protoreflect.Message = (*fastReflection_CircuitBreakerPermissions)(nil) - -type fastReflection_CircuitBreakerPermissions CircuitBreakerPermissions - -func (x *CircuitBreakerPermissions) ProtoReflect() protoreflect.Message { - return (*fastReflection_CircuitBreakerPermissions)(x) -} - -func (x *CircuitBreakerPermissions) slowProtoReflect() protoreflect.Message { - mi := &file_cosmos_circuit_v1_tx_proto_msgTypes[2] - if protoimpl.UnsafeEnabled && x != nil { - ms := protoimpl.X.MessageStateOf(protoimpl.Pointer(x)) - if ms.LoadMessageInfo() == nil { - ms.StoreMessageInfo(mi) - } - return ms - } - return mi.MessageOf(x) -} - -var _fastReflection_CircuitBreakerPermissions_messageType fastReflection_CircuitBreakerPermissions_messageType -var _ protoreflect.MessageType = fastReflection_CircuitBreakerPermissions_messageType{} - -type fastReflection_CircuitBreakerPermissions_messageType struct{} - -func (x fastReflection_CircuitBreakerPermissions_messageType) Zero() protoreflect.Message { - return (*fastReflection_CircuitBreakerPermissions)(nil) -} -func (x fastReflection_CircuitBreakerPermissions_messageType) New() protoreflect.Message { - return new(fastReflection_CircuitBreakerPermissions) -} -func (x fastReflection_CircuitBreakerPermissions_messageType) Descriptor() protoreflect.MessageDescriptor { - return md_CircuitBreakerPermissions -} - -// Descriptor returns message descriptor, which contains only the protobuf -// type information for the message. -func (x *fastReflection_CircuitBreakerPermissions) Descriptor() protoreflect.MessageDescriptor { - return md_CircuitBreakerPermissions -} - -// Type returns the message type, which encapsulates both Go and protobuf -// type information. If the Go type information is not needed, -// it is recommended that the message descriptor be used instead. -func (x *fastReflection_CircuitBreakerPermissions) Type() protoreflect.MessageType { - return _fastReflection_CircuitBreakerPermissions_messageType -} - -// New returns a newly allocated and mutable empty message. -func (x *fastReflection_CircuitBreakerPermissions) New() protoreflect.Message { - return new(fastReflection_CircuitBreakerPermissions) -} - -// Interface unwraps the message reflection interface and -// returns the underlying ProtoMessage interface. -func (x *fastReflection_CircuitBreakerPermissions) Interface() protoreflect.ProtoMessage { - return (*CircuitBreakerPermissions)(x) -} - -// Range iterates over every populated field in an undefined order, -// calling f for each field descriptor and value encountered. -// Range returns immediately if f returns false. -// While iterating, mutating operations may only be performed -// on the current field descriptor. -func (x *fastReflection_CircuitBreakerPermissions) Range(f func(protoreflect.FieldDescriptor, protoreflect.Value) bool) { - if x.Level != 0 { - value := protoreflect.ValueOfEnum((protoreflect.EnumNumber)(x.Level)) - if !f(fd_CircuitBreakerPermissions_level, value) { - return - } - } - if len(x.LimitMsgTypes) != 0 { - value := protoreflect.ValueOfList(&_CircuitBreakerPermissions_2_list{list: &x.LimitMsgTypes}) - if !f(fd_CircuitBreakerPermissions_limit_msg_types, value) { + if x.Success != false { + value := protoreflect.ValueOfBool(x.Success) + if !f(fd_MsgAuthorizeCircuitBreakerResponse_success, value) { return } } @@ -1081,17 +671,15 @@ func (x *fastReflection_CircuitBreakerPermissions) Range(f func(protoreflect.Fie // In other cases (aside from the nullable cases above), // a proto3 scalar field is populated if it contains a non-zero value, and // a repeated field is populated if it is non-empty. -func (x *fastReflection_CircuitBreakerPermissions) Has(fd protoreflect.FieldDescriptor) bool { +func (x *fastReflection_MsgAuthorizeCircuitBreakerResponse) Has(fd protoreflect.FieldDescriptor) bool { switch fd.FullName() { - case "cosmos.circuit.v1.CircuitBreakerPermissions.level": - return x.Level != 0 - case "cosmos.circuit.v1.CircuitBreakerPermissions.limit_msg_types": - return len(x.LimitMsgTypes) != 0 + case "cosmos.circuit.v1.MsgAuthorizeCircuitBreakerResponse.success": + return x.Success != false default: if fd.IsExtension() { - panic(fmt.Errorf("proto3 declared messages do not support extensions: cosmos.circuit.v1.CircuitBreakerPermissions")) + panic(fmt.Errorf("proto3 declared messages do not support extensions: cosmos.circuit.v1.MsgAuthorizeCircuitBreakerResponse")) } - panic(fmt.Errorf("message cosmos.circuit.v1.CircuitBreakerPermissions does not contain field %s", fd.FullName())) + panic(fmt.Errorf("message cosmos.circuit.v1.MsgAuthorizeCircuitBreakerResponse does not contain field %s", fd.FullName())) } } @@ -1101,17 +689,15 @@ func (x *fastReflection_CircuitBreakerPermissions) Has(fd protoreflect.FieldDesc // associated with the given field number. // // Clear is a mutating operation and unsafe for concurrent use. -func (x *fastReflection_CircuitBreakerPermissions) Clear(fd protoreflect.FieldDescriptor) { +func (x *fastReflection_MsgAuthorizeCircuitBreakerResponse) Clear(fd protoreflect.FieldDescriptor) { switch fd.FullName() { - case "cosmos.circuit.v1.CircuitBreakerPermissions.level": - x.Level = 0 - case "cosmos.circuit.v1.CircuitBreakerPermissions.limit_msg_types": - x.LimitMsgTypes = nil + case "cosmos.circuit.v1.MsgAuthorizeCircuitBreakerResponse.success": + x.Success = false default: if fd.IsExtension() { - panic(fmt.Errorf("proto3 declared messages do not support extensions: cosmos.circuit.v1.CircuitBreakerPermissions")) + panic(fmt.Errorf("proto3 declared messages do not support extensions: cosmos.circuit.v1.MsgAuthorizeCircuitBreakerResponse")) } - panic(fmt.Errorf("message cosmos.circuit.v1.CircuitBreakerPermissions does not contain field %s", fd.FullName())) + panic(fmt.Errorf("message cosmos.circuit.v1.MsgAuthorizeCircuitBreakerResponse does not contain field %s", fd.FullName())) } } @@ -1121,22 +707,16 @@ func (x *fastReflection_CircuitBreakerPermissions) Clear(fd protoreflect.FieldDe // the default value of a bytes scalar is guaranteed to be a copy. // For unpopulated composite types, it returns an empty, read-only view // of the value; to obtain a mutable reference, use Mutable. -func (x *fastReflection_CircuitBreakerPermissions) Get(descriptor protoreflect.FieldDescriptor) protoreflect.Value { +func (x *fastReflection_MsgAuthorizeCircuitBreakerResponse) Get(descriptor protoreflect.FieldDescriptor) protoreflect.Value { switch descriptor.FullName() { - case "cosmos.circuit.v1.CircuitBreakerPermissions.level": - value := x.Level - return protoreflect.ValueOfEnum((protoreflect.EnumNumber)(value)) - case "cosmos.circuit.v1.CircuitBreakerPermissions.limit_msg_types": - if len(x.LimitMsgTypes) == 0 { - return protoreflect.ValueOfList(&_CircuitBreakerPermissions_2_list{}) - } - listValue := &_CircuitBreakerPermissions_2_list{list: &x.LimitMsgTypes} - return protoreflect.ValueOfList(listValue) + case "cosmos.circuit.v1.MsgAuthorizeCircuitBreakerResponse.success": + value := x.Success + return protoreflect.ValueOfBool(value) default: if descriptor.IsExtension() { - panic(fmt.Errorf("proto3 declared messages do not support extensions: cosmos.circuit.v1.CircuitBreakerPermissions")) + panic(fmt.Errorf("proto3 declared messages do not support extensions: cosmos.circuit.v1.MsgAuthorizeCircuitBreakerResponse")) } - panic(fmt.Errorf("message cosmos.circuit.v1.CircuitBreakerPermissions does not contain field %s", descriptor.FullName())) + panic(fmt.Errorf("message cosmos.circuit.v1.MsgAuthorizeCircuitBreakerResponse does not contain field %s", descriptor.FullName())) } } @@ -1150,19 +730,15 @@ func (x *fastReflection_CircuitBreakerPermissions) Get(descriptor protoreflect.F // empty, read-only value, then it panics. // // Set is a mutating operation and unsafe for concurrent use. -func (x *fastReflection_CircuitBreakerPermissions) Set(fd protoreflect.FieldDescriptor, value protoreflect.Value) { +func (x *fastReflection_MsgAuthorizeCircuitBreakerResponse) Set(fd protoreflect.FieldDescriptor, value protoreflect.Value) { switch fd.FullName() { - case "cosmos.circuit.v1.CircuitBreakerPermissions.level": - x.Level = (CircuitBreakerPermissions_Level)(value.Enum()) - case "cosmos.circuit.v1.CircuitBreakerPermissions.limit_msg_types": - lv := value.List() - clv := lv.(*_CircuitBreakerPermissions_2_list) - x.LimitMsgTypes = *clv.list + case "cosmos.circuit.v1.MsgAuthorizeCircuitBreakerResponse.success": + x.Success = value.Bool() default: if fd.IsExtension() { - panic(fmt.Errorf("proto3 declared messages do not support extensions: cosmos.circuit.v1.CircuitBreakerPermissions")) + panic(fmt.Errorf("proto3 declared messages do not support extensions: cosmos.circuit.v1.MsgAuthorizeCircuitBreakerResponse")) } - panic(fmt.Errorf("message cosmos.circuit.v1.CircuitBreakerPermissions does not contain field %s", fd.FullName())) + panic(fmt.Errorf("message cosmos.circuit.v1.MsgAuthorizeCircuitBreakerResponse does not contain field %s", fd.FullName())) } } @@ -1176,49 +752,40 @@ func (x *fastReflection_CircuitBreakerPermissions) Set(fd protoreflect.FieldDesc // It panics if the field does not contain a composite type. // // Mutable is a mutating operation and unsafe for concurrent use. -func (x *fastReflection_CircuitBreakerPermissions) Mutable(fd protoreflect.FieldDescriptor) protoreflect.Value { +func (x *fastReflection_MsgAuthorizeCircuitBreakerResponse) Mutable(fd protoreflect.FieldDescriptor) protoreflect.Value { switch fd.FullName() { - case "cosmos.circuit.v1.CircuitBreakerPermissions.limit_msg_types": - if x.LimitMsgTypes == nil { - x.LimitMsgTypes = []string{} - } - value := &_CircuitBreakerPermissions_2_list{list: &x.LimitMsgTypes} - return protoreflect.ValueOfList(value) - case "cosmos.circuit.v1.CircuitBreakerPermissions.level": - panic(fmt.Errorf("field level of message cosmos.circuit.v1.CircuitBreakerPermissions is not mutable")) + case "cosmos.circuit.v1.MsgAuthorizeCircuitBreakerResponse.success": + panic(fmt.Errorf("field success of message cosmos.circuit.v1.MsgAuthorizeCircuitBreakerResponse is not mutable")) default: if fd.IsExtension() { - panic(fmt.Errorf("proto3 declared messages do not support extensions: cosmos.circuit.v1.CircuitBreakerPermissions")) + panic(fmt.Errorf("proto3 declared messages do not support extensions: cosmos.circuit.v1.MsgAuthorizeCircuitBreakerResponse")) } - panic(fmt.Errorf("message cosmos.circuit.v1.CircuitBreakerPermissions does not contain field %s", fd.FullName())) + panic(fmt.Errorf("message cosmos.circuit.v1.MsgAuthorizeCircuitBreakerResponse does not contain field %s", fd.FullName())) } } // NewField returns a new value that is assignable to the field // for the given descriptor. For scalars, this returns the default value. // For lists, maps, and messages, this returns a new, empty, mutable value. -func (x *fastReflection_CircuitBreakerPermissions) NewField(fd protoreflect.FieldDescriptor) protoreflect.Value { +func (x *fastReflection_MsgAuthorizeCircuitBreakerResponse) NewField(fd protoreflect.FieldDescriptor) protoreflect.Value { switch fd.FullName() { - case "cosmos.circuit.v1.CircuitBreakerPermissions.level": - return protoreflect.ValueOfEnum(0) - case "cosmos.circuit.v1.CircuitBreakerPermissions.limit_msg_types": - list := []string{} - return protoreflect.ValueOfList(&_CircuitBreakerPermissions_2_list{list: &list}) + case "cosmos.circuit.v1.MsgAuthorizeCircuitBreakerResponse.success": + return protoreflect.ValueOfBool(false) default: if fd.IsExtension() { - panic(fmt.Errorf("proto3 declared messages do not support extensions: cosmos.circuit.v1.CircuitBreakerPermissions")) + panic(fmt.Errorf("proto3 declared messages do not support extensions: cosmos.circuit.v1.MsgAuthorizeCircuitBreakerResponse")) } - panic(fmt.Errorf("message cosmos.circuit.v1.CircuitBreakerPermissions does not contain field %s", fd.FullName())) + panic(fmt.Errorf("message cosmos.circuit.v1.MsgAuthorizeCircuitBreakerResponse does not contain field %s", fd.FullName())) } } // WhichOneof reports which field within the oneof is populated, // returning nil if none are populated. // It panics if the oneof descriptor does not belong to this message. -func (x *fastReflection_CircuitBreakerPermissions) WhichOneof(d protoreflect.OneofDescriptor) protoreflect.FieldDescriptor { +func (x *fastReflection_MsgAuthorizeCircuitBreakerResponse) WhichOneof(d protoreflect.OneofDescriptor) protoreflect.FieldDescriptor { switch d.FullName() { default: - panic(fmt.Errorf("%s is not a oneof field in cosmos.circuit.v1.CircuitBreakerPermissions", d.FullName())) + panic(fmt.Errorf("%s is not a oneof field in cosmos.circuit.v1.MsgAuthorizeCircuitBreakerResponse", d.FullName())) } panic("unreachable") } @@ -1226,7 +793,7 @@ func (x *fastReflection_CircuitBreakerPermissions) WhichOneof(d protoreflect.One // GetUnknown retrieves the entire list of unknown fields. // The caller may only mutate the contents of the RawFields // if the mutated bytes are stored back into the message with SetUnknown. -func (x *fastReflection_CircuitBreakerPermissions) GetUnknown() protoreflect.RawFields { +func (x *fastReflection_MsgAuthorizeCircuitBreakerResponse) GetUnknown() protoreflect.RawFields { return x.unknownFields } @@ -1237,7 +804,7 @@ func (x *fastReflection_CircuitBreakerPermissions) GetUnknown() protoreflect.Raw // An empty RawFields may be passed to clear the fields. // // SetUnknown is a mutating operation and unsafe for concurrent use. -func (x *fastReflection_CircuitBreakerPermissions) SetUnknown(fields protoreflect.RawFields) { +func (x *fastReflection_MsgAuthorizeCircuitBreakerResponse) SetUnknown(fields protoreflect.RawFields) { x.unknownFields = fields } @@ -1249,7 +816,7 @@ func (x *fastReflection_CircuitBreakerPermissions) SetUnknown(fields protoreflec // message type, but the details are implementation dependent. // Validity is not part of the protobuf data model, and may not // be preserved in marshaling or other operations. -func (x *fastReflection_CircuitBreakerPermissions) IsValid() bool { +func (x *fastReflection_MsgAuthorizeCircuitBreakerResponse) IsValid() bool { return x != nil } @@ -1259,9 +826,9 @@ func (x *fastReflection_CircuitBreakerPermissions) IsValid() bool { // The returned methods type is identical to // "google.golang.org/protobuf/runtime/protoiface".Methods. // Consult the protoiface package documentation for details. -func (x *fastReflection_CircuitBreakerPermissions) ProtoMethods() *protoiface.Methods { +func (x *fastReflection_MsgAuthorizeCircuitBreakerResponse) ProtoMethods() *protoiface.Methods { size := func(input protoiface.SizeInput) protoiface.SizeOutput { - x := input.Message.Interface().(*CircuitBreakerPermissions) + x := input.Message.Interface().(*MsgAuthorizeCircuitBreakerResponse) if x == nil { return protoiface.SizeOutput{ NoUnkeyedLiterals: input.NoUnkeyedLiterals, @@ -1273,14 +840,8 @@ func (x *fastReflection_CircuitBreakerPermissions) ProtoMethods() *protoiface.Me var n int var l int _ = l - if x.Level != 0 { - n += 1 + runtime.Sov(uint64(x.Level)) - } - if len(x.LimitMsgTypes) > 0 { - for _, s := range x.LimitMsgTypes { - l = len(s) - n += 1 + l + runtime.Sov(uint64(l)) - } + if x.Success { + n += 2 } if x.unknownFields != nil { n += len(x.unknownFields) @@ -1292,7 +853,7 @@ func (x *fastReflection_CircuitBreakerPermissions) ProtoMethods() *protoiface.Me } marshal := func(input protoiface.MarshalInput) (protoiface.MarshalOutput, error) { - x := input.Message.Interface().(*CircuitBreakerPermissions) + x := input.Message.Interface().(*MsgAuthorizeCircuitBreakerResponse) if x == nil { return protoiface.MarshalOutput{ NoUnkeyedLiterals: input.NoUnkeyedLiterals, @@ -1311,17 +872,13 @@ func (x *fastReflection_CircuitBreakerPermissions) ProtoMethods() *protoiface.Me i -= len(x.unknownFields) copy(dAtA[i:], x.unknownFields) } - if len(x.LimitMsgTypes) > 0 { - for iNdEx := len(x.LimitMsgTypes) - 1; iNdEx >= 0; iNdEx-- { - i -= len(x.LimitMsgTypes[iNdEx]) - copy(dAtA[i:], x.LimitMsgTypes[iNdEx]) - i = runtime.EncodeVarint(dAtA, i, uint64(len(x.LimitMsgTypes[iNdEx]))) - i-- - dAtA[i] = 0x12 + if x.Success { + i-- + if x.Success { + dAtA[i] = 1 + } else { + dAtA[i] = 0 } - } - if x.Level != 0 { - i = runtime.EncodeVarint(dAtA, i, uint64(x.Level)) i-- dAtA[i] = 0x8 } @@ -1336,7 +893,7 @@ func (x *fastReflection_CircuitBreakerPermissions) ProtoMethods() *protoiface.Me }, nil } unmarshal := func(input protoiface.UnmarshalInput) (protoiface.UnmarshalOutput, error) { - x := input.Message.Interface().(*CircuitBreakerPermissions) + x := input.Message.Interface().(*MsgAuthorizeCircuitBreakerResponse) if x == nil { return protoiface.UnmarshalOutput{ NoUnkeyedLiterals: input.NoUnkeyedLiterals, @@ -1368,36 +925,17 @@ func (x *fastReflection_CircuitBreakerPermissions) ProtoMethods() *protoiface.Me fieldNum := int32(wire >> 3) wireType := int(wire & 0x7) if wireType == 4 { - return protoiface.UnmarshalOutput{NoUnkeyedLiterals: input.NoUnkeyedLiterals, Flags: input.Flags}, fmt.Errorf("proto: CircuitBreakerPermissions: wiretype end group for non-group") + return protoiface.UnmarshalOutput{NoUnkeyedLiterals: input.NoUnkeyedLiterals, Flags: input.Flags}, fmt.Errorf("proto: MsgAuthorizeCircuitBreakerResponse: wiretype end group for non-group") } if fieldNum <= 0 { - return protoiface.UnmarshalOutput{NoUnkeyedLiterals: input.NoUnkeyedLiterals, Flags: input.Flags}, fmt.Errorf("proto: CircuitBreakerPermissions: illegal tag %d (wire type %d)", fieldNum, wire) + return protoiface.UnmarshalOutput{NoUnkeyedLiterals: input.NoUnkeyedLiterals, Flags: input.Flags}, fmt.Errorf("proto: MsgAuthorizeCircuitBreakerResponse: illegal tag %d (wire type %d)", fieldNum, wire) } switch fieldNum { case 1: if wireType != 0 { - return protoiface.UnmarshalOutput{NoUnkeyedLiterals: input.NoUnkeyedLiterals, Flags: input.Flags}, fmt.Errorf("proto: wrong wireType = %d for field Level", wireType) - } - x.Level = 0 - for shift := uint(0); ; shift += 7 { - if shift >= 64 { - return protoiface.UnmarshalOutput{NoUnkeyedLiterals: input.NoUnkeyedLiterals, Flags: input.Flags}, runtime.ErrIntOverflow - } - if iNdEx >= l { - return protoiface.UnmarshalOutput{NoUnkeyedLiterals: input.NoUnkeyedLiterals, Flags: input.Flags}, io.ErrUnexpectedEOF - } - b := dAtA[iNdEx] - iNdEx++ - x.Level |= CircuitBreakerPermissions_Level(b&0x7F) << shift - if b < 0x80 { - break - } - } - case 2: - if wireType != 2 { - return protoiface.UnmarshalOutput{NoUnkeyedLiterals: input.NoUnkeyedLiterals, Flags: input.Flags}, fmt.Errorf("proto: wrong wireType = %d for field LimitMsgTypes", wireType) + return protoiface.UnmarshalOutput{NoUnkeyedLiterals: input.NoUnkeyedLiterals, Flags: input.Flags}, fmt.Errorf("proto: wrong wireType = %d for field Success", wireType) } - var stringLen uint64 + var v int for shift := uint(0); ; shift += 7 { if shift >= 64 { return protoiface.UnmarshalOutput{NoUnkeyedLiterals: input.NoUnkeyedLiterals, Flags: input.Flags}, runtime.ErrIntOverflow @@ -1407,24 +945,12 @@ func (x *fastReflection_CircuitBreakerPermissions) ProtoMethods() *protoiface.Me } b := dAtA[iNdEx] iNdEx++ - stringLen |= uint64(b&0x7F) << shift + v |= int(b&0x7F) << shift if b < 0x80 { break } } - intStringLen := int(stringLen) - if intStringLen < 0 { - return protoiface.UnmarshalOutput{NoUnkeyedLiterals: input.NoUnkeyedLiterals, Flags: input.Flags}, runtime.ErrInvalidLength - } - postIndex := iNdEx + intStringLen - if postIndex < 0 { - return protoiface.UnmarshalOutput{NoUnkeyedLiterals: input.NoUnkeyedLiterals, Flags: input.Flags}, runtime.ErrInvalidLength - } - if postIndex > l { - return protoiface.UnmarshalOutput{NoUnkeyedLiterals: input.NoUnkeyedLiterals, Flags: input.Flags}, io.ErrUnexpectedEOF - } - x.LimitMsgTypes = append(x.LimitMsgTypes, string(dAtA[iNdEx:postIndex])) - iNdEx = postIndex + x.Success = bool(v != 0) default: iNdEx = preIndex skippy, err := runtime.Skip(dAtA[iNdEx:]) @@ -1528,7 +1054,7 @@ func (x *MsgTripCircuitBreaker) ProtoReflect() protoreflect.Message { } func (x *MsgTripCircuitBreaker) slowProtoReflect() protoreflect.Message { - mi := &file_cosmos_circuit_v1_tx_proto_msgTypes[3] + mi := &file_cosmos_circuit_v1_tx_proto_msgTypes[2] if protoimpl.UnsafeEnabled && x != nil { ms := protoimpl.X.MessageStateOf(protoimpl.Pointer(x)) if ms.LoadMessageInfo() == nil { @@ -2005,12 +1531,14 @@ func (x *fastReflection_MsgTripCircuitBreaker) ProtoMethods() *protoiface.Method } var ( - md_MsgTripCircuitBreakerResponse protoreflect.MessageDescriptor + md_MsgTripCircuitBreakerResponse protoreflect.MessageDescriptor + fd_MsgTripCircuitBreakerResponse_success protoreflect.FieldDescriptor ) func init() { file_cosmos_circuit_v1_tx_proto_init() md_MsgTripCircuitBreakerResponse = File_cosmos_circuit_v1_tx_proto.Messages().ByName("MsgTripCircuitBreakerResponse") + fd_MsgTripCircuitBreakerResponse_success = md_MsgTripCircuitBreakerResponse.Fields().ByName("success") } var _ protoreflect.Message = (*fastReflection_MsgTripCircuitBreakerResponse)(nil) @@ -2022,7 +1550,7 @@ func (x *MsgTripCircuitBreakerResponse) ProtoReflect() protoreflect.Message { } func (x *MsgTripCircuitBreakerResponse) slowProtoReflect() protoreflect.Message { - mi := &file_cosmos_circuit_v1_tx_proto_msgTypes[4] + mi := &file_cosmos_circuit_v1_tx_proto_msgTypes[3] if protoimpl.UnsafeEnabled && x != nil { ms := protoimpl.X.MessageStateOf(protoimpl.Pointer(x)) if ms.LoadMessageInfo() == nil { @@ -2078,6 +1606,12 @@ func (x *fastReflection_MsgTripCircuitBreakerResponse) Interface() protoreflect. // While iterating, mutating operations may only be performed // on the current field descriptor. func (x *fastReflection_MsgTripCircuitBreakerResponse) Range(f func(protoreflect.FieldDescriptor, protoreflect.Value) bool) { + if x.Success != false { + value := protoreflect.ValueOfBool(x.Success) + if !f(fd_MsgTripCircuitBreakerResponse_success, value) { + return + } + } } // Has reports whether a field is populated. @@ -2093,6 +1627,8 @@ func (x *fastReflection_MsgTripCircuitBreakerResponse) Range(f func(protoreflect // a repeated field is populated if it is non-empty. func (x *fastReflection_MsgTripCircuitBreakerResponse) Has(fd protoreflect.FieldDescriptor) bool { switch fd.FullName() { + case "cosmos.circuit.v1.MsgTripCircuitBreakerResponse.success": + return x.Success != false default: if fd.IsExtension() { panic(fmt.Errorf("proto3 declared messages do not support extensions: cosmos.circuit.v1.MsgTripCircuitBreakerResponse")) @@ -2109,6 +1645,8 @@ func (x *fastReflection_MsgTripCircuitBreakerResponse) Has(fd protoreflect.Field // Clear is a mutating operation and unsafe for concurrent use. func (x *fastReflection_MsgTripCircuitBreakerResponse) Clear(fd protoreflect.FieldDescriptor) { switch fd.FullName() { + case "cosmos.circuit.v1.MsgTripCircuitBreakerResponse.success": + x.Success = false default: if fd.IsExtension() { panic(fmt.Errorf("proto3 declared messages do not support extensions: cosmos.circuit.v1.MsgTripCircuitBreakerResponse")) @@ -2125,6 +1663,9 @@ func (x *fastReflection_MsgTripCircuitBreakerResponse) Clear(fd protoreflect.Fie // of the value; to obtain a mutable reference, use Mutable. func (x *fastReflection_MsgTripCircuitBreakerResponse) Get(descriptor protoreflect.FieldDescriptor) protoreflect.Value { switch descriptor.FullName() { + case "cosmos.circuit.v1.MsgTripCircuitBreakerResponse.success": + value := x.Success + return protoreflect.ValueOfBool(value) default: if descriptor.IsExtension() { panic(fmt.Errorf("proto3 declared messages do not support extensions: cosmos.circuit.v1.MsgTripCircuitBreakerResponse")) @@ -2145,6 +1686,8 @@ func (x *fastReflection_MsgTripCircuitBreakerResponse) Get(descriptor protorefle // Set is a mutating operation and unsafe for concurrent use. func (x *fastReflection_MsgTripCircuitBreakerResponse) Set(fd protoreflect.FieldDescriptor, value protoreflect.Value) { switch fd.FullName() { + case "cosmos.circuit.v1.MsgTripCircuitBreakerResponse.success": + x.Success = value.Bool() default: if fd.IsExtension() { panic(fmt.Errorf("proto3 declared messages do not support extensions: cosmos.circuit.v1.MsgTripCircuitBreakerResponse")) @@ -2165,6 +1708,8 @@ func (x *fastReflection_MsgTripCircuitBreakerResponse) Set(fd protoreflect.Field // Mutable is a mutating operation and unsafe for concurrent use. func (x *fastReflection_MsgTripCircuitBreakerResponse) Mutable(fd protoreflect.FieldDescriptor) protoreflect.Value { switch fd.FullName() { + case "cosmos.circuit.v1.MsgTripCircuitBreakerResponse.success": + panic(fmt.Errorf("field success of message cosmos.circuit.v1.MsgTripCircuitBreakerResponse is not mutable")) default: if fd.IsExtension() { panic(fmt.Errorf("proto3 declared messages do not support extensions: cosmos.circuit.v1.MsgTripCircuitBreakerResponse")) @@ -2178,6 +1723,8 @@ func (x *fastReflection_MsgTripCircuitBreakerResponse) Mutable(fd protoreflect.F // For lists, maps, and messages, this returns a new, empty, mutable value. func (x *fastReflection_MsgTripCircuitBreakerResponse) NewField(fd protoreflect.FieldDescriptor) protoreflect.Value { switch fd.FullName() { + case "cosmos.circuit.v1.MsgTripCircuitBreakerResponse.success": + return protoreflect.ValueOfBool(false) default: if fd.IsExtension() { panic(fmt.Errorf("proto3 declared messages do not support extensions: cosmos.circuit.v1.MsgTripCircuitBreakerResponse")) @@ -2247,6 +1794,9 @@ func (x *fastReflection_MsgTripCircuitBreakerResponse) ProtoMethods() *protoifac var n int var l int _ = l + if x.Success { + n += 2 + } if x.unknownFields != nil { n += len(x.unknownFields) } @@ -2276,6 +1826,16 @@ func (x *fastReflection_MsgTripCircuitBreakerResponse) ProtoMethods() *protoifac i -= len(x.unknownFields) copy(dAtA[i:], x.unknownFields) } + if x.Success { + i-- + if x.Success { + dAtA[i] = 1 + } else { + dAtA[i] = 0 + } + i-- + dAtA[i] = 0x8 + } if input.Buf != nil { input.Buf = append(input.Buf, dAtA...) } else { @@ -2325,6 +1885,26 @@ func (x *fastReflection_MsgTripCircuitBreakerResponse) ProtoMethods() *protoifac return protoiface.UnmarshalOutput{NoUnkeyedLiterals: input.NoUnkeyedLiterals, Flags: input.Flags}, fmt.Errorf("proto: MsgTripCircuitBreakerResponse: illegal tag %d (wire type %d)", fieldNum, wire) } switch fieldNum { + case 1: + if wireType != 0 { + return protoiface.UnmarshalOutput{NoUnkeyedLiterals: input.NoUnkeyedLiterals, Flags: input.Flags}, fmt.Errorf("proto: wrong wireType = %d for field Success", wireType) + } + var v int + for shift := uint(0); ; shift += 7 { + if shift >= 64 { + return protoiface.UnmarshalOutput{NoUnkeyedLiterals: input.NoUnkeyedLiterals, Flags: input.Flags}, runtime.ErrIntOverflow + } + if iNdEx >= l { + return protoiface.UnmarshalOutput{NoUnkeyedLiterals: input.NoUnkeyedLiterals, Flags: input.Flags}, io.ErrUnexpectedEOF + } + b := dAtA[iNdEx] + iNdEx++ + v |= int(b&0x7F) << shift + if b < 0x80 { + break + } + } + x.Success = bool(v != 0) default: iNdEx = preIndex skippy, err := runtime.Skip(dAtA[iNdEx:]) @@ -2428,7 +2008,7 @@ func (x *MsgResetCircuitBreaker) ProtoReflect() protoreflect.Message { } func (x *MsgResetCircuitBreaker) slowProtoReflect() protoreflect.Message { - mi := &file_cosmos_circuit_v1_tx_proto_msgTypes[5] + mi := &file_cosmos_circuit_v1_tx_proto_msgTypes[4] if protoimpl.UnsafeEnabled && x != nil { ms := protoimpl.X.MessageStateOf(protoimpl.Pointer(x)) if ms.LoadMessageInfo() == nil { @@ -2905,12 +2485,14 @@ func (x *fastReflection_MsgResetCircuitBreaker) ProtoMethods() *protoiface.Metho } var ( - md_MsgResetCircuitBreakerResponse protoreflect.MessageDescriptor + md_MsgResetCircuitBreakerResponse protoreflect.MessageDescriptor + fd_MsgResetCircuitBreakerResponse_success protoreflect.FieldDescriptor ) func init() { file_cosmos_circuit_v1_tx_proto_init() md_MsgResetCircuitBreakerResponse = File_cosmos_circuit_v1_tx_proto.Messages().ByName("MsgResetCircuitBreakerResponse") + fd_MsgResetCircuitBreakerResponse_success = md_MsgResetCircuitBreakerResponse.Fields().ByName("success") } var _ protoreflect.Message = (*fastReflection_MsgResetCircuitBreakerResponse)(nil) @@ -2922,7 +2504,7 @@ func (x *MsgResetCircuitBreakerResponse) ProtoReflect() protoreflect.Message { } func (x *MsgResetCircuitBreakerResponse) slowProtoReflect() protoreflect.Message { - mi := &file_cosmos_circuit_v1_tx_proto_msgTypes[6] + mi := &file_cosmos_circuit_v1_tx_proto_msgTypes[5] if protoimpl.UnsafeEnabled && x != nil { ms := protoimpl.X.MessageStateOf(protoimpl.Pointer(x)) if ms.LoadMessageInfo() == nil { @@ -2978,6 +2560,12 @@ func (x *fastReflection_MsgResetCircuitBreakerResponse) Interface() protoreflect // While iterating, mutating operations may only be performed // on the current field descriptor. func (x *fastReflection_MsgResetCircuitBreakerResponse) Range(f func(protoreflect.FieldDescriptor, protoreflect.Value) bool) { + if x.Success != false { + value := protoreflect.ValueOfBool(x.Success) + if !f(fd_MsgResetCircuitBreakerResponse_success, value) { + return + } + } } // Has reports whether a field is populated. @@ -2993,6 +2581,8 @@ func (x *fastReflection_MsgResetCircuitBreakerResponse) Range(f func(protoreflec // a repeated field is populated if it is non-empty. func (x *fastReflection_MsgResetCircuitBreakerResponse) Has(fd protoreflect.FieldDescriptor) bool { switch fd.FullName() { + case "cosmos.circuit.v1.MsgResetCircuitBreakerResponse.success": + return x.Success != false default: if fd.IsExtension() { panic(fmt.Errorf("proto3 declared messages do not support extensions: cosmos.circuit.v1.MsgResetCircuitBreakerResponse")) @@ -3009,6 +2599,8 @@ func (x *fastReflection_MsgResetCircuitBreakerResponse) Has(fd protoreflect.Fiel // Clear is a mutating operation and unsafe for concurrent use. func (x *fastReflection_MsgResetCircuitBreakerResponse) Clear(fd protoreflect.FieldDescriptor) { switch fd.FullName() { + case "cosmos.circuit.v1.MsgResetCircuitBreakerResponse.success": + x.Success = false default: if fd.IsExtension() { panic(fmt.Errorf("proto3 declared messages do not support extensions: cosmos.circuit.v1.MsgResetCircuitBreakerResponse")) @@ -3025,6 +2617,9 @@ func (x *fastReflection_MsgResetCircuitBreakerResponse) Clear(fd protoreflect.Fi // of the value; to obtain a mutable reference, use Mutable. func (x *fastReflection_MsgResetCircuitBreakerResponse) Get(descriptor protoreflect.FieldDescriptor) protoreflect.Value { switch descriptor.FullName() { + case "cosmos.circuit.v1.MsgResetCircuitBreakerResponse.success": + value := x.Success + return protoreflect.ValueOfBool(value) default: if descriptor.IsExtension() { panic(fmt.Errorf("proto3 declared messages do not support extensions: cosmos.circuit.v1.MsgResetCircuitBreakerResponse")) @@ -3045,6 +2640,8 @@ func (x *fastReflection_MsgResetCircuitBreakerResponse) Get(descriptor protorefl // Set is a mutating operation and unsafe for concurrent use. func (x *fastReflection_MsgResetCircuitBreakerResponse) Set(fd protoreflect.FieldDescriptor, value protoreflect.Value) { switch fd.FullName() { + case "cosmos.circuit.v1.MsgResetCircuitBreakerResponse.success": + x.Success = value.Bool() default: if fd.IsExtension() { panic(fmt.Errorf("proto3 declared messages do not support extensions: cosmos.circuit.v1.MsgResetCircuitBreakerResponse")) @@ -3065,6 +2662,8 @@ func (x *fastReflection_MsgResetCircuitBreakerResponse) Set(fd protoreflect.Fiel // Mutable is a mutating operation and unsafe for concurrent use. func (x *fastReflection_MsgResetCircuitBreakerResponse) Mutable(fd protoreflect.FieldDescriptor) protoreflect.Value { switch fd.FullName() { + case "cosmos.circuit.v1.MsgResetCircuitBreakerResponse.success": + panic(fmt.Errorf("field success of message cosmos.circuit.v1.MsgResetCircuitBreakerResponse is not mutable")) default: if fd.IsExtension() { panic(fmt.Errorf("proto3 declared messages do not support extensions: cosmos.circuit.v1.MsgResetCircuitBreakerResponse")) @@ -3078,6 +2677,8 @@ func (x *fastReflection_MsgResetCircuitBreakerResponse) Mutable(fd protoreflect. // For lists, maps, and messages, this returns a new, empty, mutable value. func (x *fastReflection_MsgResetCircuitBreakerResponse) NewField(fd protoreflect.FieldDescriptor) protoreflect.Value { switch fd.FullName() { + case "cosmos.circuit.v1.MsgResetCircuitBreakerResponse.success": + return protoreflect.ValueOfBool(false) default: if fd.IsExtension() { panic(fmt.Errorf("proto3 declared messages do not support extensions: cosmos.circuit.v1.MsgResetCircuitBreakerResponse")) @@ -3147,6 +2748,9 @@ func (x *fastReflection_MsgResetCircuitBreakerResponse) ProtoMethods() *protoifa var n int var l int _ = l + if x.Success { + n += 2 + } if x.unknownFields != nil { n += len(x.unknownFields) } @@ -3176,6 +2780,16 @@ func (x *fastReflection_MsgResetCircuitBreakerResponse) ProtoMethods() *protoifa i -= len(x.unknownFields) copy(dAtA[i:], x.unknownFields) } + if x.Success { + i-- + if x.Success { + dAtA[i] = 1 + } else { + dAtA[i] = 0 + } + i-- + dAtA[i] = 0x8 + } if input.Buf != nil { input.Buf = append(input.Buf, dAtA...) } else { @@ -3225,6 +2839,26 @@ func (x *fastReflection_MsgResetCircuitBreakerResponse) ProtoMethods() *protoifa return protoiface.UnmarshalOutput{NoUnkeyedLiterals: input.NoUnkeyedLiterals, Flags: input.Flags}, fmt.Errorf("proto: MsgResetCircuitBreakerResponse: illegal tag %d (wire type %d)", fieldNum, wire) } switch fieldNum { + case 1: + if wireType != 0 { + return protoiface.UnmarshalOutput{NoUnkeyedLiterals: input.NoUnkeyedLiterals, Flags: input.Flags}, fmt.Errorf("proto: wrong wireType = %d for field Success", wireType) + } + var v int + for shift := uint(0); ; shift += 7 { + if shift >= 64 { + return protoiface.UnmarshalOutput{NoUnkeyedLiterals: input.NoUnkeyedLiterals, Flags: input.Flags}, runtime.ErrIntOverflow + } + if iNdEx >= l { + return protoiface.UnmarshalOutput{NoUnkeyedLiterals: input.NoUnkeyedLiterals, Flags: input.Flags}, io.ErrUnexpectedEOF + } + b := dAtA[iNdEx] + iNdEx++ + v |= int(b&0x7F) << shift + if b < 0x80 { + break + } + } + x.Success = bool(v != 0) default: iNdEx = preIndex skippy, err := runtime.Skip(dAtA[iNdEx:]) @@ -3273,69 +2907,6 @@ const ( _ = protoimpl.EnforceVersion(protoimpl.MaxVersion - 20) ) -// Level is the permission level. -type CircuitBreakerPermissions_Level int32 - -const ( - // LEVEL_NONE_UNSPECIFIED indicates that the account will have no circuit - // breaker permissions. - CircuitBreakerPermissions_LEVEL_NONE_UNSPECIFIED CircuitBreakerPermissions_Level = 0 - // LEVEL_SOME_MSGS indicates that the account will have permission to - // trip or reset the circuit breaker for some Msg type URLs. If this level - // is chosen, a non-empty list of Msg type URLs must be provided in - // limit_type_urls. - CircuitBreakerPermissions_LEVEL_SOME_MSGS CircuitBreakerPermissions_Level = 1 - // LEVEL_ALL_MSGS indicates that the account can trip or reset the circuit - // breaker for Msg's of all type URLs. - CircuitBreakerPermissions_LEVEL_ALL_MSGS CircuitBreakerPermissions_Level = 2 - // LEVEL_SUPER_ADMIN indicates that the account can take all circuit breaker - // actions and can grant permissions to other accounts. - CircuitBreakerPermissions_LEVEL_SUPER_ADMIN CircuitBreakerPermissions_Level = 3 -) - -// Enum value maps for CircuitBreakerPermissions_Level. -var ( - CircuitBreakerPermissions_Level_name = map[int32]string{ - 0: "LEVEL_NONE_UNSPECIFIED", - 1: "LEVEL_SOME_MSGS", - 2: "LEVEL_ALL_MSGS", - 3: "LEVEL_SUPER_ADMIN", - } - CircuitBreakerPermissions_Level_value = map[string]int32{ - "LEVEL_NONE_UNSPECIFIED": 0, - "LEVEL_SOME_MSGS": 1, - "LEVEL_ALL_MSGS": 2, - "LEVEL_SUPER_ADMIN": 3, - } -) - -func (x CircuitBreakerPermissions_Level) Enum() *CircuitBreakerPermissions_Level { - p := new(CircuitBreakerPermissions_Level) - *p = x - return p -} - -func (x CircuitBreakerPermissions_Level) String() string { - return protoimpl.X.EnumStringOf(x.Descriptor(), protoreflect.EnumNumber(x)) -} - -func (CircuitBreakerPermissions_Level) Descriptor() protoreflect.EnumDescriptor { - return file_cosmos_circuit_v1_tx_proto_enumTypes[0].Descriptor() -} - -func (CircuitBreakerPermissions_Level) Type() protoreflect.EnumType { - return &file_cosmos_circuit_v1_tx_proto_enumTypes[0] -} - -func (x CircuitBreakerPermissions_Level) Number() protoreflect.EnumNumber { - return protoreflect.EnumNumber(x) -} - -// Deprecated: Use CircuitBreakerPermissions_Level.Descriptor instead. -func (CircuitBreakerPermissions_Level) EnumDescriptor() ([]byte, []int) { - return file_cosmos_circuit_v1_tx_proto_rawDescGZIP(), []int{2, 0} -} - // MsgAuthorizeCircuitBreaker defines the Msg/AuthorizeCircuitBreaker request type. type MsgAuthorizeCircuitBreaker struct { state protoimpl.MessageState @@ -3350,7 +2921,7 @@ type MsgAuthorizeCircuitBreaker struct { // permissions are the circuit breaker permissions that the grantee receives. // These will overwrite any existing permissions. LEVEL_NONE_UNSPECIFIED can // be specified to revoke all permissions. - Permissions *CircuitBreakerPermissions `protobuf:"bytes,3,opt,name=permissions,proto3" json:"permissions,omitempty"` + Permissions *Permissions `protobuf:"bytes,3,opt,name=permissions,proto3" json:"permissions,omitempty"` } func (x *MsgAuthorizeCircuitBreaker) Reset() { @@ -3387,7 +2958,7 @@ func (x *MsgAuthorizeCircuitBreaker) GetGrantee() string { return "" } -func (x *MsgAuthorizeCircuitBreaker) GetPermissions() *CircuitBreakerPermissions { +func (x *MsgAuthorizeCircuitBreaker) GetPermissions() *Permissions { if x != nil { return x.Permissions } @@ -3399,6 +2970,8 @@ type MsgAuthorizeCircuitBreakerResponse struct { state protoimpl.MessageState sizeCache protoimpl.SizeCache unknownFields protoimpl.UnknownFields + + Success bool `protobuf:"varint,1,opt,name=success,proto3" json:"success,omitempty"` } func (x *MsgAuthorizeCircuitBreakerResponse) Reset() { @@ -3421,53 +2994,11 @@ func (*MsgAuthorizeCircuitBreakerResponse) Descriptor() ([]byte, []int) { return file_cosmos_circuit_v1_tx_proto_rawDescGZIP(), []int{1} } -// CircuitBreakerPermissions are the permissions that an account has to trip -// or reset the circuit breaker. -type CircuitBreakerPermissions struct { - state protoimpl.MessageState - sizeCache protoimpl.SizeCache - unknownFields protoimpl.UnknownFields - - // level is the level of permissions granted to this account. - Level CircuitBreakerPermissions_Level `protobuf:"varint,1,opt,name=level,proto3,enum=cosmos.circuit.v1.CircuitBreakerPermissions_Level" json:"level,omitempty"` - // limit_msg_types is used with LEVEL_SOME_MSGS to limit the lists of Msg type - // name that the account can pause. It is an error to use limit_msg_types with - // a level other than LEVEL_SOME_MSGS. - LimitMsgTypes []string `protobuf:"bytes,2,rep,name=limit_msg_types,json=limitMsgTypes,proto3" json:"limit_msg_types,omitempty"` -} - -func (x *CircuitBreakerPermissions) Reset() { - *x = CircuitBreakerPermissions{} - if protoimpl.UnsafeEnabled { - mi := &file_cosmos_circuit_v1_tx_proto_msgTypes[2] - ms := protoimpl.X.MessageStateOf(protoimpl.Pointer(x)) - ms.StoreMessageInfo(mi) - } -} - -func (x *CircuitBreakerPermissions) String() string { - return protoimpl.X.MessageStringOf(x) -} - -func (*CircuitBreakerPermissions) ProtoMessage() {} - -// Deprecated: Use CircuitBreakerPermissions.ProtoReflect.Descriptor instead. -func (*CircuitBreakerPermissions) Descriptor() ([]byte, []int) { - return file_cosmos_circuit_v1_tx_proto_rawDescGZIP(), []int{2} -} - -func (x *CircuitBreakerPermissions) GetLevel() CircuitBreakerPermissions_Level { +func (x *MsgAuthorizeCircuitBreakerResponse) GetSuccess() bool { if x != nil { - return x.Level + return x.Success } - return CircuitBreakerPermissions_LEVEL_NONE_UNSPECIFIED -} - -func (x *CircuitBreakerPermissions) GetLimitMsgTypes() []string { - if x != nil { - return x.LimitMsgTypes - } - return nil + return false } // MsgTripCircuitBreaker defines the Msg/TripCircuitBreaker request type. @@ -3489,7 +3020,7 @@ type MsgTripCircuitBreaker struct { func (x *MsgTripCircuitBreaker) Reset() { *x = MsgTripCircuitBreaker{} if protoimpl.UnsafeEnabled { - mi := &file_cosmos_circuit_v1_tx_proto_msgTypes[3] + mi := &file_cosmos_circuit_v1_tx_proto_msgTypes[2] ms := protoimpl.X.MessageStateOf(protoimpl.Pointer(x)) ms.StoreMessageInfo(mi) } @@ -3503,7 +3034,7 @@ func (*MsgTripCircuitBreaker) ProtoMessage() {} // Deprecated: Use MsgTripCircuitBreaker.ProtoReflect.Descriptor instead. func (*MsgTripCircuitBreaker) Descriptor() ([]byte, []int) { - return file_cosmos_circuit_v1_tx_proto_rawDescGZIP(), []int{3} + return file_cosmos_circuit_v1_tx_proto_rawDescGZIP(), []int{2} } func (x *MsgTripCircuitBreaker) GetAuthority() string { @@ -3525,12 +3056,14 @@ type MsgTripCircuitBreakerResponse struct { state protoimpl.MessageState sizeCache protoimpl.SizeCache unknownFields protoimpl.UnknownFields + + Success bool `protobuf:"varint,1,opt,name=success,proto3" json:"success,omitempty"` } func (x *MsgTripCircuitBreakerResponse) Reset() { *x = MsgTripCircuitBreakerResponse{} if protoimpl.UnsafeEnabled { - mi := &file_cosmos_circuit_v1_tx_proto_msgTypes[4] + mi := &file_cosmos_circuit_v1_tx_proto_msgTypes[3] ms := protoimpl.X.MessageStateOf(protoimpl.Pointer(x)) ms.StoreMessageInfo(mi) } @@ -3544,7 +3077,14 @@ func (*MsgTripCircuitBreakerResponse) ProtoMessage() {} // Deprecated: Use MsgTripCircuitBreakerResponse.ProtoReflect.Descriptor instead. func (*MsgTripCircuitBreakerResponse) Descriptor() ([]byte, []int) { - return file_cosmos_circuit_v1_tx_proto_rawDescGZIP(), []int{4} + return file_cosmos_circuit_v1_tx_proto_rawDescGZIP(), []int{3} +} + +func (x *MsgTripCircuitBreakerResponse) GetSuccess() bool { + if x != nil { + return x.Success + } + return false } // MsgResetCircuitBreaker defines the Msg/ResetCircuitBreaker request type. @@ -3564,7 +3104,7 @@ type MsgResetCircuitBreaker struct { func (x *MsgResetCircuitBreaker) Reset() { *x = MsgResetCircuitBreaker{} if protoimpl.UnsafeEnabled { - mi := &file_cosmos_circuit_v1_tx_proto_msgTypes[5] + mi := &file_cosmos_circuit_v1_tx_proto_msgTypes[4] ms := protoimpl.X.MessageStateOf(protoimpl.Pointer(x)) ms.StoreMessageInfo(mi) } @@ -3578,7 +3118,7 @@ func (*MsgResetCircuitBreaker) ProtoMessage() {} // Deprecated: Use MsgResetCircuitBreaker.ProtoReflect.Descriptor instead. func (*MsgResetCircuitBreaker) Descriptor() ([]byte, []int) { - return file_cosmos_circuit_v1_tx_proto_rawDescGZIP(), []int{5} + return file_cosmos_circuit_v1_tx_proto_rawDescGZIP(), []int{4} } func (x *MsgResetCircuitBreaker) GetAuthority() string { @@ -3600,12 +3140,14 @@ type MsgResetCircuitBreakerResponse struct { state protoimpl.MessageState sizeCache protoimpl.SizeCache unknownFields protoimpl.UnknownFields + + Success bool `protobuf:"varint,1,opt,name=success,proto3" json:"success,omitempty"` } func (x *MsgResetCircuitBreakerResponse) Reset() { *x = MsgResetCircuitBreakerResponse{} if protoimpl.UnsafeEnabled { - mi := &file_cosmos_circuit_v1_tx_proto_msgTypes[6] + mi := &file_cosmos_circuit_v1_tx_proto_msgTypes[5] ms := protoimpl.X.MessageStateOf(protoimpl.Pointer(x)) ms.StoreMessageInfo(mi) } @@ -3619,7 +3161,14 @@ func (*MsgResetCircuitBreakerResponse) ProtoMessage() {} // Deprecated: Use MsgResetCircuitBreakerResponse.ProtoReflect.Descriptor instead. func (*MsgResetCircuitBreakerResponse) Descriptor() ([]byte, []int) { - return file_cosmos_circuit_v1_tx_proto_rawDescGZIP(), []int{6} + return file_cosmos_circuit_v1_tx_proto_rawDescGZIP(), []int{5} +} + +func (x *MsgResetCircuitBreakerResponse) GetSuccess() bool { + if x != nil { + return x.Success + } + return false } var File_cosmos_circuit_v1_tx_proto protoreflect.FileDescriptor @@ -3629,89 +3178,79 @@ var file_cosmos_circuit_v1_tx_proto_rawDesc = []byte{ 0x2f, 0x76, 0x31, 0x2f, 0x74, 0x78, 0x2e, 0x70, 0x72, 0x6f, 0x74, 0x6f, 0x12, 0x11, 0x63, 0x6f, 0x73, 0x6d, 0x6f, 0x73, 0x2e, 0x63, 0x69, 0x72, 0x63, 0x75, 0x69, 0x74, 0x2e, 0x76, 0x31, 0x1a, 0x17, 0x63, 0x6f, 0x73, 0x6d, 0x6f, 0x73, 0x2f, 0x6d, 0x73, 0x67, 0x2f, 0x76, 0x31, 0x2f, 0x6d, - 0x73, 0x67, 0x2e, 0x70, 0x72, 0x6f, 0x74, 0x6f, 0x22, 0xae, 0x01, 0x0a, 0x1a, 0x4d, 0x73, 0x67, - 0x41, 0x75, 0x74, 0x68, 0x6f, 0x72, 0x69, 0x7a, 0x65, 0x43, 0x69, 0x72, 0x63, 0x75, 0x69, 0x74, - 0x42, 0x72, 0x65, 0x61, 0x6b, 0x65, 0x72, 0x12, 0x18, 0x0a, 0x07, 0x67, 0x72, 0x61, 0x6e, 0x74, - 0x65, 0x72, 0x18, 0x01, 0x20, 0x01, 0x28, 0x09, 0x52, 0x07, 0x67, 0x72, 0x61, 0x6e, 0x74, 0x65, - 0x72, 0x12, 0x18, 0x0a, 0x07, 0x67, 0x72, 0x61, 0x6e, 0x74, 0x65, 0x65, 0x18, 0x02, 0x20, 0x01, - 0x28, 0x09, 0x52, 0x07, 0x67, 0x72, 0x61, 0x6e, 0x74, 0x65, 0x65, 0x12, 0x4e, 0x0a, 0x0b, 0x70, - 0x65, 0x72, 0x6d, 0x69, 0x73, 0x73, 0x69, 0x6f, 0x6e, 0x73, 0x18, 0x03, 0x20, 0x01, 0x28, 0x0b, - 0x32, 0x2c, 0x2e, 0x63, 0x6f, 0x73, 0x6d, 0x6f, 0x73, 0x2e, 0x63, 0x69, 0x72, 0x63, 0x75, 0x69, - 0x74, 0x2e, 0x76, 0x31, 0x2e, 0x43, 0x69, 0x72, 0x63, 0x75, 0x69, 0x74, 0x42, 0x72, 0x65, 0x61, - 0x6b, 0x65, 0x72, 0x50, 0x65, 0x72, 0x6d, 0x69, 0x73, 0x73, 0x69, 0x6f, 0x6e, 0x73, 0x52, 0x0b, - 0x70, 0x65, 0x72, 0x6d, 0x69, 0x73, 0x73, 0x69, 0x6f, 0x6e, 0x73, 0x3a, 0x0c, 0x82, 0xe7, 0xb0, - 0x2a, 0x07, 0x67, 0x72, 0x61, 0x6e, 0x74, 0x65, 0x72, 0x22, 0x24, 0x0a, 0x22, 0x4d, 0x73, 0x67, - 0x41, 0x75, 0x74, 0x68, 0x6f, 0x72, 0x69, 0x7a, 0x65, 0x43, 0x69, 0x72, 0x63, 0x75, 0x69, 0x74, - 0x42, 0x72, 0x65, 0x61, 0x6b, 0x65, 0x72, 0x52, 0x65, 0x73, 0x70, 0x6f, 0x6e, 0x73, 0x65, 0x22, - 0xf2, 0x01, 0x0a, 0x19, 0x43, 0x69, 0x72, 0x63, 0x75, 0x69, 0x74, 0x42, 0x72, 0x65, 0x61, 0x6b, - 0x65, 0x72, 0x50, 0x65, 0x72, 0x6d, 0x69, 0x73, 0x73, 0x69, 0x6f, 0x6e, 0x73, 0x12, 0x48, 0x0a, - 0x05, 0x6c, 0x65, 0x76, 0x65, 0x6c, 0x18, 0x01, 0x20, 0x01, 0x28, 0x0e, 0x32, 0x32, 0x2e, 0x63, - 0x6f, 0x73, 0x6d, 0x6f, 0x73, 0x2e, 0x63, 0x69, 0x72, 0x63, 0x75, 0x69, 0x74, 0x2e, 0x76, 0x31, - 0x2e, 0x43, 0x69, 0x72, 0x63, 0x75, 0x69, 0x74, 0x42, 0x72, 0x65, 0x61, 0x6b, 0x65, 0x72, 0x50, - 0x65, 0x72, 0x6d, 0x69, 0x73, 0x73, 0x69, 0x6f, 0x6e, 0x73, 0x2e, 0x4c, 0x65, 0x76, 0x65, 0x6c, - 0x52, 0x05, 0x6c, 0x65, 0x76, 0x65, 0x6c, 0x12, 0x26, 0x0a, 0x0f, 0x6c, 0x69, 0x6d, 0x69, 0x74, - 0x5f, 0x6d, 0x73, 0x67, 0x5f, 0x74, 0x79, 0x70, 0x65, 0x73, 0x18, 0x02, 0x20, 0x03, 0x28, 0x09, - 0x52, 0x0d, 0x6c, 0x69, 0x6d, 0x69, 0x74, 0x4d, 0x73, 0x67, 0x54, 0x79, 0x70, 0x65, 0x73, 0x22, - 0x63, 0x0a, 0x05, 0x4c, 0x65, 0x76, 0x65, 0x6c, 0x12, 0x1a, 0x0a, 0x16, 0x4c, 0x45, 0x56, 0x45, - 0x4c, 0x5f, 0x4e, 0x4f, 0x4e, 0x45, 0x5f, 0x55, 0x4e, 0x53, 0x50, 0x45, 0x43, 0x49, 0x46, 0x49, - 0x45, 0x44, 0x10, 0x00, 0x12, 0x13, 0x0a, 0x0f, 0x4c, 0x45, 0x56, 0x45, 0x4c, 0x5f, 0x53, 0x4f, - 0x4d, 0x45, 0x5f, 0x4d, 0x53, 0x47, 0x53, 0x10, 0x01, 0x12, 0x12, 0x0a, 0x0e, 0x4c, 0x45, 0x56, - 0x45, 0x4c, 0x5f, 0x41, 0x4c, 0x4c, 0x5f, 0x4d, 0x53, 0x47, 0x53, 0x10, 0x02, 0x12, 0x15, 0x0a, - 0x11, 0x4c, 0x45, 0x56, 0x45, 0x4c, 0x5f, 0x53, 0x55, 0x50, 0x45, 0x52, 0x5f, 0x41, 0x44, 0x4d, - 0x49, 0x4e, 0x10, 0x03, 0x22, 0x69, 0x0a, 0x15, 0x4d, 0x73, 0x67, 0x54, 0x72, 0x69, 0x70, 0x43, - 0x69, 0x72, 0x63, 0x75, 0x69, 0x74, 0x42, 0x72, 0x65, 0x61, 0x6b, 0x65, 0x72, 0x12, 0x1c, 0x0a, - 0x09, 0x61, 0x75, 0x74, 0x68, 0x6f, 0x72, 0x69, 0x74, 0x79, 0x18, 0x01, 0x20, 0x01, 0x28, 0x09, - 0x52, 0x09, 0x61, 0x75, 0x74, 0x68, 0x6f, 0x72, 0x69, 0x74, 0x79, 0x12, 0x22, 0x0a, 0x0d, 0x6d, - 0x73, 0x67, 0x5f, 0x74, 0x79, 0x70, 0x65, 0x5f, 0x75, 0x72, 0x6c, 0x73, 0x18, 0x02, 0x20, 0x03, - 0x28, 0x09, 0x52, 0x0b, 0x6d, 0x73, 0x67, 0x54, 0x79, 0x70, 0x65, 0x55, 0x72, 0x6c, 0x73, 0x3a, - 0x0e, 0x82, 0xe7, 0xb0, 0x2a, 0x09, 0x61, 0x75, 0x74, 0x68, 0x6f, 0x72, 0x69, 0x74, 0x79, 0x22, - 0x1f, 0x0a, 0x1d, 0x4d, 0x73, 0x67, 0x54, 0x72, 0x69, 0x70, 0x43, 0x69, 0x72, 0x63, 0x75, 0x69, + 0x73, 0x67, 0x2e, 0x70, 0x72, 0x6f, 0x74, 0x6f, 0x1a, 0x1d, 0x63, 0x6f, 0x73, 0x6d, 0x6f, 0x73, + 0x2f, 0x63, 0x69, 0x72, 0x63, 0x75, 0x69, 0x74, 0x2f, 0x76, 0x31, 0x2f, 0x74, 0x79, 0x70, 0x65, + 0x73, 0x2e, 0x70, 0x72, 0x6f, 0x74, 0x6f, 0x22, 0xa0, 0x01, 0x0a, 0x1a, 0x4d, 0x73, 0x67, 0x41, + 0x75, 0x74, 0x68, 0x6f, 0x72, 0x69, 0x7a, 0x65, 0x43, 0x69, 0x72, 0x63, 0x75, 0x69, 0x74, 0x42, + 0x72, 0x65, 0x61, 0x6b, 0x65, 0x72, 0x12, 0x18, 0x0a, 0x07, 0x67, 0x72, 0x61, 0x6e, 0x74, 0x65, + 0x72, 0x18, 0x01, 0x20, 0x01, 0x28, 0x09, 0x52, 0x07, 0x67, 0x72, 0x61, 0x6e, 0x74, 0x65, 0x72, + 0x12, 0x18, 0x0a, 0x07, 0x67, 0x72, 0x61, 0x6e, 0x74, 0x65, 0x65, 0x18, 0x02, 0x20, 0x01, 0x28, + 0x09, 0x52, 0x07, 0x67, 0x72, 0x61, 0x6e, 0x74, 0x65, 0x65, 0x12, 0x40, 0x0a, 0x0b, 0x70, 0x65, + 0x72, 0x6d, 0x69, 0x73, 0x73, 0x69, 0x6f, 0x6e, 0x73, 0x18, 0x03, 0x20, 0x01, 0x28, 0x0b, 0x32, + 0x1e, 0x2e, 0x63, 0x6f, 0x73, 0x6d, 0x6f, 0x73, 0x2e, 0x63, 0x69, 0x72, 0x63, 0x75, 0x69, 0x74, + 0x2e, 0x76, 0x31, 0x2e, 0x50, 0x65, 0x72, 0x6d, 0x69, 0x73, 0x73, 0x69, 0x6f, 0x6e, 0x73, 0x52, + 0x0b, 0x70, 0x65, 0x72, 0x6d, 0x69, 0x73, 0x73, 0x69, 0x6f, 0x6e, 0x73, 0x3a, 0x0c, 0x82, 0xe7, + 0xb0, 0x2a, 0x07, 0x67, 0x72, 0x61, 0x6e, 0x74, 0x65, 0x72, 0x22, 0x3e, 0x0a, 0x22, 0x4d, 0x73, + 0x67, 0x41, 0x75, 0x74, 0x68, 0x6f, 0x72, 0x69, 0x7a, 0x65, 0x43, 0x69, 0x72, 0x63, 0x75, 0x69, 0x74, 0x42, 0x72, 0x65, 0x61, 0x6b, 0x65, 0x72, 0x52, 0x65, 0x73, 0x70, 0x6f, 0x6e, 0x73, 0x65, + 0x12, 0x18, 0x0a, 0x07, 0x73, 0x75, 0x63, 0x63, 0x65, 0x73, 0x73, 0x18, 0x01, 0x20, 0x01, 0x28, + 0x08, 0x52, 0x07, 0x73, 0x75, 0x63, 0x63, 0x65, 0x73, 0x73, 0x22, 0x69, 0x0a, 0x15, 0x4d, 0x73, + 0x67, 0x54, 0x72, 0x69, 0x70, 0x43, 0x69, 0x72, 0x63, 0x75, 0x69, 0x74, 0x42, 0x72, 0x65, 0x61, + 0x6b, 0x65, 0x72, 0x12, 0x1c, 0x0a, 0x09, 0x61, 0x75, 0x74, 0x68, 0x6f, 0x72, 0x69, 0x74, 0x79, + 0x18, 0x01, 0x20, 0x01, 0x28, 0x09, 0x52, 0x09, 0x61, 0x75, 0x74, 0x68, 0x6f, 0x72, 0x69, 0x74, + 0x79, 0x12, 0x22, 0x0a, 0x0d, 0x6d, 0x73, 0x67, 0x5f, 0x74, 0x79, 0x70, 0x65, 0x5f, 0x75, 0x72, + 0x6c, 0x73, 0x18, 0x02, 0x20, 0x03, 0x28, 0x09, 0x52, 0x0b, 0x6d, 0x73, 0x67, 0x54, 0x79, 0x70, + 0x65, 0x55, 0x72, 0x6c, 0x73, 0x3a, 0x0e, 0x82, 0xe7, 0xb0, 0x2a, 0x09, 0x61, 0x75, 0x74, 0x68, + 0x6f, 0x72, 0x69, 0x74, 0x79, 0x22, 0x39, 0x0a, 0x1d, 0x4d, 0x73, 0x67, 0x54, 0x72, 0x69, 0x70, + 0x43, 0x69, 0x72, 0x63, 0x75, 0x69, 0x74, 0x42, 0x72, 0x65, 0x61, 0x6b, 0x65, 0x72, 0x52, 0x65, + 0x73, 0x70, 0x6f, 0x6e, 0x73, 0x65, 0x12, 0x18, 0x0a, 0x07, 0x73, 0x75, 0x63, 0x63, 0x65, 0x73, + 0x73, 0x18, 0x01, 0x20, 0x01, 0x28, 0x08, 0x52, 0x07, 0x73, 0x75, 0x63, 0x63, 0x65, 0x73, 0x73, 0x22, 0x6a, 0x0a, 0x16, 0x4d, 0x73, 0x67, 0x52, 0x65, 0x73, 0x65, 0x74, 0x43, 0x69, 0x72, 0x63, 0x75, 0x69, 0x74, 0x42, 0x72, 0x65, 0x61, 0x6b, 0x65, 0x72, 0x12, 0x1c, 0x0a, 0x09, 0x61, 0x75, 0x74, 0x68, 0x6f, 0x72, 0x69, 0x74, 0x79, 0x18, 0x01, 0x20, 0x01, 0x28, 0x09, 0x52, 0x09, 0x61, 0x75, 0x74, 0x68, 0x6f, 0x72, 0x69, 0x74, 0x79, 0x12, 0x22, 0x0a, 0x0d, 0x6d, 0x73, 0x67, 0x5f, 0x74, 0x79, 0x70, 0x65, 0x5f, 0x75, 0x72, 0x6c, 0x73, 0x18, 0x03, 0x20, 0x03, 0x28, 0x09, 0x52, 0x0b, 0x6d, 0x73, 0x67, 0x54, 0x79, 0x70, 0x65, 0x55, 0x72, 0x6c, 0x73, 0x3a, 0x0e, 0x82, 0xe7, - 0xb0, 0x2a, 0x09, 0x61, 0x75, 0x74, 0x68, 0x6f, 0x72, 0x69, 0x74, 0x79, 0x22, 0x20, 0x0a, 0x1e, + 0xb0, 0x2a, 0x09, 0x61, 0x75, 0x74, 0x68, 0x6f, 0x72, 0x69, 0x74, 0x79, 0x22, 0x3a, 0x0a, 0x1e, 0x4d, 0x73, 0x67, 0x52, 0x65, 0x73, 0x65, 0x74, 0x43, 0x69, 0x72, 0x63, 0x75, 0x69, 0x74, 0x42, - 0x72, 0x65, 0x61, 0x6b, 0x65, 0x72, 0x52, 0x65, 0x73, 0x70, 0x6f, 0x6e, 0x73, 0x65, 0x32, 0xf4, - 0x02, 0x0a, 0x03, 0x4d, 0x73, 0x67, 0x12, 0x7f, 0x0a, 0x17, 0x41, 0x75, 0x74, 0x68, 0x6f, 0x72, - 0x69, 0x7a, 0x65, 0x43, 0x69, 0x72, 0x63, 0x75, 0x69, 0x74, 0x42, 0x72, 0x65, 0x61, 0x6b, 0x65, - 0x72, 0x12, 0x2d, 0x2e, 0x63, 0x6f, 0x73, 0x6d, 0x6f, 0x73, 0x2e, 0x63, 0x69, 0x72, 0x63, 0x75, - 0x69, 0x74, 0x2e, 0x76, 0x31, 0x2e, 0x4d, 0x73, 0x67, 0x41, 0x75, 0x74, 0x68, 0x6f, 0x72, 0x69, - 0x7a, 0x65, 0x43, 0x69, 0x72, 0x63, 0x75, 0x69, 0x74, 0x42, 0x72, 0x65, 0x61, 0x6b, 0x65, 0x72, - 0x1a, 0x35, 0x2e, 0x63, 0x6f, 0x73, 0x6d, 0x6f, 0x73, 0x2e, 0x63, 0x69, 0x72, 0x63, 0x75, 0x69, - 0x74, 0x2e, 0x76, 0x31, 0x2e, 0x4d, 0x73, 0x67, 0x41, 0x75, 0x74, 0x68, 0x6f, 0x72, 0x69, 0x7a, - 0x65, 0x43, 0x69, 0x72, 0x63, 0x75, 0x69, 0x74, 0x42, 0x72, 0x65, 0x61, 0x6b, 0x65, 0x72, 0x52, - 0x65, 0x73, 0x70, 0x6f, 0x6e, 0x73, 0x65, 0x12, 0x70, 0x0a, 0x12, 0x54, 0x72, 0x69, 0x70, 0x43, - 0x69, 0x72, 0x63, 0x75, 0x69, 0x74, 0x42, 0x72, 0x65, 0x61, 0x6b, 0x65, 0x72, 0x12, 0x28, 0x2e, - 0x63, 0x6f, 0x73, 0x6d, 0x6f, 0x73, 0x2e, 0x63, 0x69, 0x72, 0x63, 0x75, 0x69, 0x74, 0x2e, 0x76, - 0x31, 0x2e, 0x4d, 0x73, 0x67, 0x54, 0x72, 0x69, 0x70, 0x43, 0x69, 0x72, 0x63, 0x75, 0x69, 0x74, - 0x42, 0x72, 0x65, 0x61, 0x6b, 0x65, 0x72, 0x1a, 0x30, 0x2e, 0x63, 0x6f, 0x73, 0x6d, 0x6f, 0x73, + 0x72, 0x65, 0x61, 0x6b, 0x65, 0x72, 0x52, 0x65, 0x73, 0x70, 0x6f, 0x6e, 0x73, 0x65, 0x12, 0x18, + 0x0a, 0x07, 0x73, 0x75, 0x63, 0x63, 0x65, 0x73, 0x73, 0x18, 0x01, 0x20, 0x01, 0x28, 0x08, 0x52, + 0x07, 0x73, 0x75, 0x63, 0x63, 0x65, 0x73, 0x73, 0x32, 0xf4, 0x02, 0x0a, 0x03, 0x4d, 0x73, 0x67, + 0x12, 0x7f, 0x0a, 0x17, 0x41, 0x75, 0x74, 0x68, 0x6f, 0x72, 0x69, 0x7a, 0x65, 0x43, 0x69, 0x72, + 0x63, 0x75, 0x69, 0x74, 0x42, 0x72, 0x65, 0x61, 0x6b, 0x65, 0x72, 0x12, 0x2d, 0x2e, 0x63, 0x6f, + 0x73, 0x6d, 0x6f, 0x73, 0x2e, 0x63, 0x69, 0x72, 0x63, 0x75, 0x69, 0x74, 0x2e, 0x76, 0x31, 0x2e, + 0x4d, 0x73, 0x67, 0x41, 0x75, 0x74, 0x68, 0x6f, 0x72, 0x69, 0x7a, 0x65, 0x43, 0x69, 0x72, 0x63, + 0x75, 0x69, 0x74, 0x42, 0x72, 0x65, 0x61, 0x6b, 0x65, 0x72, 0x1a, 0x35, 0x2e, 0x63, 0x6f, 0x73, + 0x6d, 0x6f, 0x73, 0x2e, 0x63, 0x69, 0x72, 0x63, 0x75, 0x69, 0x74, 0x2e, 0x76, 0x31, 0x2e, 0x4d, + 0x73, 0x67, 0x41, 0x75, 0x74, 0x68, 0x6f, 0x72, 0x69, 0x7a, 0x65, 0x43, 0x69, 0x72, 0x63, 0x75, + 0x69, 0x74, 0x42, 0x72, 0x65, 0x61, 0x6b, 0x65, 0x72, 0x52, 0x65, 0x73, 0x70, 0x6f, 0x6e, 0x73, + 0x65, 0x12, 0x70, 0x0a, 0x12, 0x54, 0x72, 0x69, 0x70, 0x43, 0x69, 0x72, 0x63, 0x75, 0x69, 0x74, + 0x42, 0x72, 0x65, 0x61, 0x6b, 0x65, 0x72, 0x12, 0x28, 0x2e, 0x63, 0x6f, 0x73, 0x6d, 0x6f, 0x73, 0x2e, 0x63, 0x69, 0x72, 0x63, 0x75, 0x69, 0x74, 0x2e, 0x76, 0x31, 0x2e, 0x4d, 0x73, 0x67, 0x54, 0x72, 0x69, 0x70, 0x43, 0x69, 0x72, 0x63, 0x75, 0x69, 0x74, 0x42, 0x72, 0x65, 0x61, 0x6b, 0x65, - 0x72, 0x52, 0x65, 0x73, 0x70, 0x6f, 0x6e, 0x73, 0x65, 0x12, 0x73, 0x0a, 0x13, 0x52, 0x65, 0x73, + 0x72, 0x1a, 0x30, 0x2e, 0x63, 0x6f, 0x73, 0x6d, 0x6f, 0x73, 0x2e, 0x63, 0x69, 0x72, 0x63, 0x75, + 0x69, 0x74, 0x2e, 0x76, 0x31, 0x2e, 0x4d, 0x73, 0x67, 0x54, 0x72, 0x69, 0x70, 0x43, 0x69, 0x72, + 0x63, 0x75, 0x69, 0x74, 0x42, 0x72, 0x65, 0x61, 0x6b, 0x65, 0x72, 0x52, 0x65, 0x73, 0x70, 0x6f, + 0x6e, 0x73, 0x65, 0x12, 0x73, 0x0a, 0x13, 0x52, 0x65, 0x73, 0x65, 0x74, 0x43, 0x69, 0x72, 0x63, + 0x75, 0x69, 0x74, 0x42, 0x72, 0x65, 0x61, 0x6b, 0x65, 0x72, 0x12, 0x29, 0x2e, 0x63, 0x6f, 0x73, + 0x6d, 0x6f, 0x73, 0x2e, 0x63, 0x69, 0x72, 0x63, 0x75, 0x69, 0x74, 0x2e, 0x76, 0x31, 0x2e, 0x4d, + 0x73, 0x67, 0x52, 0x65, 0x73, 0x65, 0x74, 0x43, 0x69, 0x72, 0x63, 0x75, 0x69, 0x74, 0x42, 0x72, + 0x65, 0x61, 0x6b, 0x65, 0x72, 0x1a, 0x31, 0x2e, 0x63, 0x6f, 0x73, 0x6d, 0x6f, 0x73, 0x2e, 0x63, + 0x69, 0x72, 0x63, 0x75, 0x69, 0x74, 0x2e, 0x76, 0x31, 0x2e, 0x4d, 0x73, 0x67, 0x52, 0x65, 0x73, 0x65, 0x74, 0x43, 0x69, 0x72, 0x63, 0x75, 0x69, 0x74, 0x42, 0x72, 0x65, 0x61, 0x6b, 0x65, 0x72, - 0x12, 0x29, 0x2e, 0x63, 0x6f, 0x73, 0x6d, 0x6f, 0x73, 0x2e, 0x63, 0x69, 0x72, 0x63, 0x75, 0x69, - 0x74, 0x2e, 0x76, 0x31, 0x2e, 0x4d, 0x73, 0x67, 0x52, 0x65, 0x73, 0x65, 0x74, 0x43, 0x69, 0x72, - 0x63, 0x75, 0x69, 0x74, 0x42, 0x72, 0x65, 0x61, 0x6b, 0x65, 0x72, 0x1a, 0x31, 0x2e, 0x63, 0x6f, - 0x73, 0x6d, 0x6f, 0x73, 0x2e, 0x63, 0x69, 0x72, 0x63, 0x75, 0x69, 0x74, 0x2e, 0x76, 0x31, 0x2e, - 0x4d, 0x73, 0x67, 0x52, 0x65, 0x73, 0x65, 0x74, 0x43, 0x69, 0x72, 0x63, 0x75, 0x69, 0x74, 0x42, - 0x72, 0x65, 0x61, 0x6b, 0x65, 0x72, 0x52, 0x65, 0x73, 0x70, 0x6f, 0x6e, 0x73, 0x65, 0x1a, 0x05, - 0x80, 0xe7, 0xb0, 0x2a, 0x01, 0x42, 0xb4, 0x01, 0x0a, 0x15, 0x63, 0x6f, 0x6d, 0x2e, 0x63, 0x6f, - 0x73, 0x6d, 0x6f, 0x73, 0x2e, 0x63, 0x69, 0x72, 0x63, 0x75, 0x69, 0x74, 0x2e, 0x76, 0x31, 0x42, - 0x07, 0x54, 0x78, 0x50, 0x72, 0x6f, 0x74, 0x6f, 0x50, 0x01, 0x5a, 0x2c, 0x63, 0x6f, 0x73, 0x6d, - 0x6f, 0x73, 0x73, 0x64, 0x6b, 0x2e, 0x69, 0x6f, 0x2f, 0x61, 0x70, 0x69, 0x2f, 0x63, 0x6f, 0x73, - 0x6d, 0x6f, 0x73, 0x2f, 0x63, 0x69, 0x72, 0x63, 0x75, 0x69, 0x74, 0x2f, 0x76, 0x31, 0x3b, 0x63, - 0x69, 0x72, 0x63, 0x75, 0x69, 0x74, 0x76, 0x31, 0xa2, 0x02, 0x03, 0x43, 0x43, 0x58, 0xaa, 0x02, - 0x11, 0x43, 0x6f, 0x73, 0x6d, 0x6f, 0x73, 0x2e, 0x43, 0x69, 0x72, 0x63, 0x75, 0x69, 0x74, 0x2e, - 0x56, 0x31, 0xca, 0x02, 0x11, 0x43, 0x6f, 0x73, 0x6d, 0x6f, 0x73, 0x5c, 0x43, 0x69, 0x72, 0x63, - 0x75, 0x69, 0x74, 0x5c, 0x56, 0x31, 0xe2, 0x02, 0x1d, 0x43, 0x6f, 0x73, 0x6d, 0x6f, 0x73, 0x5c, - 0x43, 0x69, 0x72, 0x63, 0x75, 0x69, 0x74, 0x5c, 0x56, 0x31, 0x5c, 0x47, 0x50, 0x42, 0x4d, 0x65, - 0x74, 0x61, 0x64, 0x61, 0x74, 0x61, 0xea, 0x02, 0x13, 0x43, 0x6f, 0x73, 0x6d, 0x6f, 0x73, 0x3a, - 0x3a, 0x43, 0x69, 0x72, 0x63, 0x75, 0x69, 0x74, 0x3a, 0x3a, 0x56, 0x31, 0x62, 0x06, 0x70, 0x72, - 0x6f, 0x74, 0x6f, 0x33, + 0x52, 0x65, 0x73, 0x70, 0x6f, 0x6e, 0x73, 0x65, 0x1a, 0x05, 0x80, 0xe7, 0xb0, 0x2a, 0x01, 0x42, + 0xb4, 0x01, 0x0a, 0x15, 0x63, 0x6f, 0x6d, 0x2e, 0x63, 0x6f, 0x73, 0x6d, 0x6f, 0x73, 0x2e, 0x63, + 0x69, 0x72, 0x63, 0x75, 0x69, 0x74, 0x2e, 0x76, 0x31, 0x42, 0x07, 0x54, 0x78, 0x50, 0x72, 0x6f, + 0x74, 0x6f, 0x50, 0x01, 0x5a, 0x2c, 0x63, 0x6f, 0x73, 0x6d, 0x6f, 0x73, 0x73, 0x64, 0x6b, 0x2e, + 0x69, 0x6f, 0x2f, 0x61, 0x70, 0x69, 0x2f, 0x63, 0x6f, 0x73, 0x6d, 0x6f, 0x73, 0x2f, 0x63, 0x69, + 0x72, 0x63, 0x75, 0x69, 0x74, 0x2f, 0x76, 0x31, 0x3b, 0x63, 0x69, 0x72, 0x63, 0x75, 0x69, 0x74, + 0x76, 0x31, 0xa2, 0x02, 0x03, 0x43, 0x43, 0x58, 0xaa, 0x02, 0x11, 0x43, 0x6f, 0x73, 0x6d, 0x6f, + 0x73, 0x2e, 0x43, 0x69, 0x72, 0x63, 0x75, 0x69, 0x74, 0x2e, 0x56, 0x31, 0xca, 0x02, 0x11, 0x43, + 0x6f, 0x73, 0x6d, 0x6f, 0x73, 0x5c, 0x43, 0x69, 0x72, 0x63, 0x75, 0x69, 0x74, 0x5c, 0x56, 0x31, + 0xe2, 0x02, 0x1d, 0x43, 0x6f, 0x73, 0x6d, 0x6f, 0x73, 0x5c, 0x43, 0x69, 0x72, 0x63, 0x75, 0x69, + 0x74, 0x5c, 0x56, 0x31, 0x5c, 0x47, 0x50, 0x42, 0x4d, 0x65, 0x74, 0x61, 0x64, 0x61, 0x74, 0x61, + 0xea, 0x02, 0x13, 0x43, 0x6f, 0x73, 0x6d, 0x6f, 0x73, 0x3a, 0x3a, 0x43, 0x69, 0x72, 0x63, 0x75, + 0x69, 0x74, 0x3a, 0x3a, 0x56, 0x31, 0x62, 0x06, 0x70, 0x72, 0x6f, 0x74, 0x6f, 0x33, } var ( @@ -3726,32 +3265,29 @@ func file_cosmos_circuit_v1_tx_proto_rawDescGZIP() []byte { return file_cosmos_circuit_v1_tx_proto_rawDescData } -var file_cosmos_circuit_v1_tx_proto_enumTypes = make([]protoimpl.EnumInfo, 1) -var file_cosmos_circuit_v1_tx_proto_msgTypes = make([]protoimpl.MessageInfo, 7) +var file_cosmos_circuit_v1_tx_proto_msgTypes = make([]protoimpl.MessageInfo, 6) var file_cosmos_circuit_v1_tx_proto_goTypes = []interface{}{ - (CircuitBreakerPermissions_Level)(0), // 0: cosmos.circuit.v1.CircuitBreakerPermissions.Level - (*MsgAuthorizeCircuitBreaker)(nil), // 1: cosmos.circuit.v1.MsgAuthorizeCircuitBreaker - (*MsgAuthorizeCircuitBreakerResponse)(nil), // 2: cosmos.circuit.v1.MsgAuthorizeCircuitBreakerResponse - (*CircuitBreakerPermissions)(nil), // 3: cosmos.circuit.v1.CircuitBreakerPermissions - (*MsgTripCircuitBreaker)(nil), // 4: cosmos.circuit.v1.MsgTripCircuitBreaker - (*MsgTripCircuitBreakerResponse)(nil), // 5: cosmos.circuit.v1.MsgTripCircuitBreakerResponse - (*MsgResetCircuitBreaker)(nil), // 6: cosmos.circuit.v1.MsgResetCircuitBreaker - (*MsgResetCircuitBreakerResponse)(nil), // 7: cosmos.circuit.v1.MsgResetCircuitBreakerResponse + (*MsgAuthorizeCircuitBreaker)(nil), // 0: cosmos.circuit.v1.MsgAuthorizeCircuitBreaker + (*MsgAuthorizeCircuitBreakerResponse)(nil), // 1: cosmos.circuit.v1.MsgAuthorizeCircuitBreakerResponse + (*MsgTripCircuitBreaker)(nil), // 2: cosmos.circuit.v1.MsgTripCircuitBreaker + (*MsgTripCircuitBreakerResponse)(nil), // 3: cosmos.circuit.v1.MsgTripCircuitBreakerResponse + (*MsgResetCircuitBreaker)(nil), // 4: cosmos.circuit.v1.MsgResetCircuitBreaker + (*MsgResetCircuitBreakerResponse)(nil), // 5: cosmos.circuit.v1.MsgResetCircuitBreakerResponse + (*Permissions)(nil), // 6: cosmos.circuit.v1.Permissions } var file_cosmos_circuit_v1_tx_proto_depIdxs = []int32{ - 3, // 0: cosmos.circuit.v1.MsgAuthorizeCircuitBreaker.permissions:type_name -> cosmos.circuit.v1.CircuitBreakerPermissions - 0, // 1: cosmos.circuit.v1.CircuitBreakerPermissions.level:type_name -> cosmos.circuit.v1.CircuitBreakerPermissions.Level - 1, // 2: cosmos.circuit.v1.Msg.AuthorizeCircuitBreaker:input_type -> cosmos.circuit.v1.MsgAuthorizeCircuitBreaker - 4, // 3: cosmos.circuit.v1.Msg.TripCircuitBreaker:input_type -> cosmos.circuit.v1.MsgTripCircuitBreaker - 6, // 4: cosmos.circuit.v1.Msg.ResetCircuitBreaker:input_type -> cosmos.circuit.v1.MsgResetCircuitBreaker - 2, // 5: cosmos.circuit.v1.Msg.AuthorizeCircuitBreaker:output_type -> cosmos.circuit.v1.MsgAuthorizeCircuitBreakerResponse - 5, // 6: cosmos.circuit.v1.Msg.TripCircuitBreaker:output_type -> cosmos.circuit.v1.MsgTripCircuitBreakerResponse - 7, // 7: cosmos.circuit.v1.Msg.ResetCircuitBreaker:output_type -> cosmos.circuit.v1.MsgResetCircuitBreakerResponse - 5, // [5:8] is the sub-list for method output_type - 2, // [2:5] is the sub-list for method input_type - 2, // [2:2] is the sub-list for extension type_name - 2, // [2:2] is the sub-list for extension extendee - 0, // [0:2] is the sub-list for field type_name + 6, // 0: cosmos.circuit.v1.MsgAuthorizeCircuitBreaker.permissions:type_name -> cosmos.circuit.v1.Permissions + 0, // 1: cosmos.circuit.v1.Msg.AuthorizeCircuitBreaker:input_type -> cosmos.circuit.v1.MsgAuthorizeCircuitBreaker + 2, // 2: cosmos.circuit.v1.Msg.TripCircuitBreaker:input_type -> cosmos.circuit.v1.MsgTripCircuitBreaker + 4, // 3: cosmos.circuit.v1.Msg.ResetCircuitBreaker:input_type -> cosmos.circuit.v1.MsgResetCircuitBreaker + 1, // 4: cosmos.circuit.v1.Msg.AuthorizeCircuitBreaker:output_type -> cosmos.circuit.v1.MsgAuthorizeCircuitBreakerResponse + 3, // 5: cosmos.circuit.v1.Msg.TripCircuitBreaker:output_type -> cosmos.circuit.v1.MsgTripCircuitBreakerResponse + 5, // 6: cosmos.circuit.v1.Msg.ResetCircuitBreaker:output_type -> cosmos.circuit.v1.MsgResetCircuitBreakerResponse + 4, // [4:7] is the sub-list for method output_type + 1, // [1:4] is the sub-list for method input_type + 1, // [1:1] is the sub-list for extension type_name + 1, // [1:1] is the sub-list for extension extendee + 0, // [0:1] is the sub-list for field type_name } func init() { file_cosmos_circuit_v1_tx_proto_init() } @@ -3759,6 +3295,7 @@ func file_cosmos_circuit_v1_tx_proto_init() { if File_cosmos_circuit_v1_tx_proto != nil { return } + file_cosmos_circuit_v1_types_proto_init() if !protoimpl.UnsafeEnabled { file_cosmos_circuit_v1_tx_proto_msgTypes[0].Exporter = func(v interface{}, i int) interface{} { switch v := v.(*MsgAuthorizeCircuitBreaker); i { @@ -3785,18 +3322,6 @@ func file_cosmos_circuit_v1_tx_proto_init() { } } file_cosmos_circuit_v1_tx_proto_msgTypes[2].Exporter = func(v interface{}, i int) interface{} { - switch v := v.(*CircuitBreakerPermissions); i { - case 0: - return &v.state - case 1: - return &v.sizeCache - case 2: - return &v.unknownFields - default: - return nil - } - } - file_cosmos_circuit_v1_tx_proto_msgTypes[3].Exporter = func(v interface{}, i int) interface{} { switch v := v.(*MsgTripCircuitBreaker); i { case 0: return &v.state @@ -3808,7 +3333,7 @@ func file_cosmos_circuit_v1_tx_proto_init() { return nil } } - file_cosmos_circuit_v1_tx_proto_msgTypes[4].Exporter = func(v interface{}, i int) interface{} { + file_cosmos_circuit_v1_tx_proto_msgTypes[3].Exporter = func(v interface{}, i int) interface{} { switch v := v.(*MsgTripCircuitBreakerResponse); i { case 0: return &v.state @@ -3820,7 +3345,7 @@ func file_cosmos_circuit_v1_tx_proto_init() { return nil } } - file_cosmos_circuit_v1_tx_proto_msgTypes[5].Exporter = func(v interface{}, i int) interface{} { + file_cosmos_circuit_v1_tx_proto_msgTypes[4].Exporter = func(v interface{}, i int) interface{} { switch v := v.(*MsgResetCircuitBreaker); i { case 0: return &v.state @@ -3832,7 +3357,7 @@ func file_cosmos_circuit_v1_tx_proto_init() { return nil } } - file_cosmos_circuit_v1_tx_proto_msgTypes[6].Exporter = func(v interface{}, i int) interface{} { + file_cosmos_circuit_v1_tx_proto_msgTypes[5].Exporter = func(v interface{}, i int) interface{} { switch v := v.(*MsgResetCircuitBreakerResponse); i { case 0: return &v.state @@ -3850,14 +3375,13 @@ func file_cosmos_circuit_v1_tx_proto_init() { File: protoimpl.DescBuilder{ GoPackagePath: reflect.TypeOf(x{}).PkgPath(), RawDescriptor: file_cosmos_circuit_v1_tx_proto_rawDesc, - NumEnums: 1, - NumMessages: 7, + NumEnums: 0, + NumMessages: 6, NumExtensions: 0, NumServices: 1, }, GoTypes: file_cosmos_circuit_v1_tx_proto_goTypes, DependencyIndexes: file_cosmos_circuit_v1_tx_proto_depIdxs, - EnumInfos: file_cosmos_circuit_v1_tx_proto_enumTypes, MessageInfos: file_cosmos_circuit_v1_tx_proto_msgTypes, }.Build() File_cosmos_circuit_v1_tx_proto = out.File diff --git a/api/cosmos/circuit/v1/types.pulsar.go b/api/cosmos/circuit/v1/types.pulsar.go new file mode 100644 index 000000000000..56e4c0e89292 --- /dev/null +++ b/api/cosmos/circuit/v1/types.pulsar.go @@ -0,0 +1,2018 @@ +// Code generated by protoc-gen-go-pulsar. DO NOT EDIT. +package circuitv1 + +import ( + fmt "fmt" + runtime "github.com/cosmos/cosmos-proto/runtime" + protoreflect "google.golang.org/protobuf/reflect/protoreflect" + protoiface "google.golang.org/protobuf/runtime/protoiface" + protoimpl "google.golang.org/protobuf/runtime/protoimpl" + io "io" + reflect "reflect" + sync "sync" +) + +var _ protoreflect.List = (*_Permissions_2_list)(nil) + +type _Permissions_2_list struct { + list *[]string +} + +func (x *_Permissions_2_list) Len() int { + if x.list == nil { + return 0 + } + return len(*x.list) +} + +func (x *_Permissions_2_list) Get(i int) protoreflect.Value { + return protoreflect.ValueOfString((*x.list)[i]) +} + +func (x *_Permissions_2_list) Set(i int, value protoreflect.Value) { + valueUnwrapped := value.String() + concreteValue := valueUnwrapped + (*x.list)[i] = concreteValue +} + +func (x *_Permissions_2_list) Append(value protoreflect.Value) { + valueUnwrapped := value.String() + concreteValue := valueUnwrapped + *x.list = append(*x.list, concreteValue) +} + +func (x *_Permissions_2_list) AppendMutable() protoreflect.Value { + panic(fmt.Errorf("AppendMutable can not be called on message Permissions at list field LimitTypeUrls as it is not of Message kind")) +} + +func (x *_Permissions_2_list) Truncate(n int) { + *x.list = (*x.list)[:n] +} + +func (x *_Permissions_2_list) NewElement() protoreflect.Value { + v := "" + return protoreflect.ValueOfString(v) +} + +func (x *_Permissions_2_list) IsValid() bool { + return x.list != nil +} + +var ( + md_Permissions protoreflect.MessageDescriptor + fd_Permissions_level protoreflect.FieldDescriptor + fd_Permissions_limit_type_urls protoreflect.FieldDescriptor +) + +func init() { + file_cosmos_circuit_v1_types_proto_init() + md_Permissions = File_cosmos_circuit_v1_types_proto.Messages().ByName("Permissions") + fd_Permissions_level = md_Permissions.Fields().ByName("level") + fd_Permissions_limit_type_urls = md_Permissions.Fields().ByName("limit_type_urls") +} + +var _ protoreflect.Message = (*fastReflection_Permissions)(nil) + +type fastReflection_Permissions Permissions + +func (x *Permissions) ProtoReflect() protoreflect.Message { + return (*fastReflection_Permissions)(x) +} + +func (x *Permissions) slowProtoReflect() protoreflect.Message { + mi := &file_cosmos_circuit_v1_types_proto_msgTypes[0] + if protoimpl.UnsafeEnabled && x != nil { + ms := protoimpl.X.MessageStateOf(protoimpl.Pointer(x)) + if ms.LoadMessageInfo() == nil { + ms.StoreMessageInfo(mi) + } + return ms + } + return mi.MessageOf(x) +} + +var _fastReflection_Permissions_messageType fastReflection_Permissions_messageType +var _ protoreflect.MessageType = fastReflection_Permissions_messageType{} + +type fastReflection_Permissions_messageType struct{} + +func (x fastReflection_Permissions_messageType) Zero() protoreflect.Message { + return (*fastReflection_Permissions)(nil) +} +func (x fastReflection_Permissions_messageType) New() protoreflect.Message { + return new(fastReflection_Permissions) +} +func (x fastReflection_Permissions_messageType) Descriptor() protoreflect.MessageDescriptor { + return md_Permissions +} + +// Descriptor returns message descriptor, which contains only the protobuf +// type information for the message. +func (x *fastReflection_Permissions) Descriptor() protoreflect.MessageDescriptor { + return md_Permissions +} + +// Type returns the message type, which encapsulates both Go and protobuf +// type information. If the Go type information is not needed, +// it is recommended that the message descriptor be used instead. +func (x *fastReflection_Permissions) Type() protoreflect.MessageType { + return _fastReflection_Permissions_messageType +} + +// New returns a newly allocated and mutable empty message. +func (x *fastReflection_Permissions) New() protoreflect.Message { + return new(fastReflection_Permissions) +} + +// Interface unwraps the message reflection interface and +// returns the underlying ProtoMessage interface. +func (x *fastReflection_Permissions) Interface() protoreflect.ProtoMessage { + return (*Permissions)(x) +} + +// Range iterates over every populated field in an undefined order, +// calling f for each field descriptor and value encountered. +// Range returns immediately if f returns false. +// While iterating, mutating operations may only be performed +// on the current field descriptor. +func (x *fastReflection_Permissions) Range(f func(protoreflect.FieldDescriptor, protoreflect.Value) bool) { + if x.Level != 0 { + value := protoreflect.ValueOfEnum((protoreflect.EnumNumber)(x.Level)) + if !f(fd_Permissions_level, value) { + return + } + } + if len(x.LimitTypeUrls) != 0 { + value := protoreflect.ValueOfList(&_Permissions_2_list{list: &x.LimitTypeUrls}) + if !f(fd_Permissions_limit_type_urls, value) { + return + } + } +} + +// Has reports whether a field is populated. +// +// Some fields have the property of nullability where it is possible to +// distinguish between the default value of a field and whether the field +// was explicitly populated with the default value. Singular message fields, +// member fields of a oneof, and proto2 scalar fields are nullable. Such +// fields are populated only if explicitly set. +// +// In other cases (aside from the nullable cases above), +// a proto3 scalar field is populated if it contains a non-zero value, and +// a repeated field is populated if it is non-empty. +func (x *fastReflection_Permissions) Has(fd protoreflect.FieldDescriptor) bool { + switch fd.FullName() { + case "cosmos.circuit.v1.Permissions.level": + return x.Level != 0 + case "cosmos.circuit.v1.Permissions.limit_type_urls": + return len(x.LimitTypeUrls) != 0 + default: + if fd.IsExtension() { + panic(fmt.Errorf("proto3 declared messages do not support extensions: cosmos.circuit.v1.Permissions")) + } + panic(fmt.Errorf("message cosmos.circuit.v1.Permissions does not contain field %s", fd.FullName())) + } +} + +// Clear clears the field such that a subsequent Has call reports false. +// +// Clearing an extension field clears both the extension type and value +// associated with the given field number. +// +// Clear is a mutating operation and unsafe for concurrent use. +func (x *fastReflection_Permissions) Clear(fd protoreflect.FieldDescriptor) { + switch fd.FullName() { + case "cosmos.circuit.v1.Permissions.level": + x.Level = 0 + case "cosmos.circuit.v1.Permissions.limit_type_urls": + x.LimitTypeUrls = nil + default: + if fd.IsExtension() { + panic(fmt.Errorf("proto3 declared messages do not support extensions: cosmos.circuit.v1.Permissions")) + } + panic(fmt.Errorf("message cosmos.circuit.v1.Permissions does not contain field %s", fd.FullName())) + } +} + +// Get retrieves the value for a field. +// +// For unpopulated scalars, it returns the default value, where +// the default value of a bytes scalar is guaranteed to be a copy. +// For unpopulated composite types, it returns an empty, read-only view +// of the value; to obtain a mutable reference, use Mutable. +func (x *fastReflection_Permissions) Get(descriptor protoreflect.FieldDescriptor) protoreflect.Value { + switch descriptor.FullName() { + case "cosmos.circuit.v1.Permissions.level": + value := x.Level + return protoreflect.ValueOfEnum((protoreflect.EnumNumber)(value)) + case "cosmos.circuit.v1.Permissions.limit_type_urls": + if len(x.LimitTypeUrls) == 0 { + return protoreflect.ValueOfList(&_Permissions_2_list{}) + } + listValue := &_Permissions_2_list{list: &x.LimitTypeUrls} + return protoreflect.ValueOfList(listValue) + default: + if descriptor.IsExtension() { + panic(fmt.Errorf("proto3 declared messages do not support extensions: cosmos.circuit.v1.Permissions")) + } + panic(fmt.Errorf("message cosmos.circuit.v1.Permissions does not contain field %s", descriptor.FullName())) + } +} + +// Set stores the value for a field. +// +// For a field belonging to a oneof, it implicitly clears any other field +// that may be currently set within the same oneof. +// For extension fields, it implicitly stores the provided ExtensionType. +// When setting a composite type, it is unspecified whether the stored value +// aliases the source's memory in any way. If the composite value is an +// empty, read-only value, then it panics. +// +// Set is a mutating operation and unsafe for concurrent use. +func (x *fastReflection_Permissions) Set(fd protoreflect.FieldDescriptor, value protoreflect.Value) { + switch fd.FullName() { + case "cosmos.circuit.v1.Permissions.level": + x.Level = (Permissions_Level)(value.Enum()) + case "cosmos.circuit.v1.Permissions.limit_type_urls": + lv := value.List() + clv := lv.(*_Permissions_2_list) + x.LimitTypeUrls = *clv.list + default: + if fd.IsExtension() { + panic(fmt.Errorf("proto3 declared messages do not support extensions: cosmos.circuit.v1.Permissions")) + } + panic(fmt.Errorf("message cosmos.circuit.v1.Permissions does not contain field %s", fd.FullName())) + } +} + +// Mutable returns a mutable reference to a composite type. +// +// If the field is unpopulated, it may allocate a composite value. +// For a field belonging to a oneof, it implicitly clears any other field +// that may be currently set within the same oneof. +// For extension fields, it implicitly stores the provided ExtensionType +// if not already stored. +// It panics if the field does not contain a composite type. +// +// Mutable is a mutating operation and unsafe for concurrent use. +func (x *fastReflection_Permissions) Mutable(fd protoreflect.FieldDescriptor) protoreflect.Value { + switch fd.FullName() { + case "cosmos.circuit.v1.Permissions.limit_type_urls": + if x.LimitTypeUrls == nil { + x.LimitTypeUrls = []string{} + } + value := &_Permissions_2_list{list: &x.LimitTypeUrls} + return protoreflect.ValueOfList(value) + case "cosmos.circuit.v1.Permissions.level": + panic(fmt.Errorf("field level of message cosmos.circuit.v1.Permissions is not mutable")) + default: + if fd.IsExtension() { + panic(fmt.Errorf("proto3 declared messages do not support extensions: cosmos.circuit.v1.Permissions")) + } + panic(fmt.Errorf("message cosmos.circuit.v1.Permissions does not contain field %s", fd.FullName())) + } +} + +// NewField returns a new value that is assignable to the field +// for the given descriptor. For scalars, this returns the default value. +// For lists, maps, and messages, this returns a new, empty, mutable value. +func (x *fastReflection_Permissions) NewField(fd protoreflect.FieldDescriptor) protoreflect.Value { + switch fd.FullName() { + case "cosmos.circuit.v1.Permissions.level": + return protoreflect.ValueOfEnum(0) + case "cosmos.circuit.v1.Permissions.limit_type_urls": + list := []string{} + return protoreflect.ValueOfList(&_Permissions_2_list{list: &list}) + default: + if fd.IsExtension() { + panic(fmt.Errorf("proto3 declared messages do not support extensions: cosmos.circuit.v1.Permissions")) + } + panic(fmt.Errorf("message cosmos.circuit.v1.Permissions does not contain field %s", fd.FullName())) + } +} + +// WhichOneof reports which field within the oneof is populated, +// returning nil if none are populated. +// It panics if the oneof descriptor does not belong to this message. +func (x *fastReflection_Permissions) WhichOneof(d protoreflect.OneofDescriptor) protoreflect.FieldDescriptor { + switch d.FullName() { + default: + panic(fmt.Errorf("%s is not a oneof field in cosmos.circuit.v1.Permissions", d.FullName())) + } + panic("unreachable") +} + +// GetUnknown retrieves the entire list of unknown fields. +// The caller may only mutate the contents of the RawFields +// if the mutated bytes are stored back into the message with SetUnknown. +func (x *fastReflection_Permissions) GetUnknown() protoreflect.RawFields { + return x.unknownFields +} + +// SetUnknown stores an entire list of unknown fields. +// The raw fields must be syntactically valid according to the wire format. +// An implementation may panic if this is not the case. +// Once stored, the caller must not mutate the content of the RawFields. +// An empty RawFields may be passed to clear the fields. +// +// SetUnknown is a mutating operation and unsafe for concurrent use. +func (x *fastReflection_Permissions) SetUnknown(fields protoreflect.RawFields) { + x.unknownFields = fields +} + +// IsValid reports whether the message is valid. +// +// An invalid message is an empty, read-only value. +// +// An invalid message often corresponds to a nil pointer of the concrete +// message type, but the details are implementation dependent. +// Validity is not part of the protobuf data model, and may not +// be preserved in marshaling or other operations. +func (x *fastReflection_Permissions) IsValid() bool { + return x != nil +} + +// ProtoMethods returns optional fastReflectionFeature-path implementations of various operations. +// This method may return nil. +// +// The returned methods type is identical to +// "google.golang.org/protobuf/runtime/protoiface".Methods. +// Consult the protoiface package documentation for details. +func (x *fastReflection_Permissions) ProtoMethods() *protoiface.Methods { + size := func(input protoiface.SizeInput) protoiface.SizeOutput { + x := input.Message.Interface().(*Permissions) + if x == nil { + return protoiface.SizeOutput{ + NoUnkeyedLiterals: input.NoUnkeyedLiterals, + Size: 0, + } + } + options := runtime.SizeInputToOptions(input) + _ = options + var n int + var l int + _ = l + if x.Level != 0 { + n += 1 + runtime.Sov(uint64(x.Level)) + } + if len(x.LimitTypeUrls) > 0 { + for _, s := range x.LimitTypeUrls { + l = len(s) + n += 1 + l + runtime.Sov(uint64(l)) + } + } + if x.unknownFields != nil { + n += len(x.unknownFields) + } + return protoiface.SizeOutput{ + NoUnkeyedLiterals: input.NoUnkeyedLiterals, + Size: n, + } + } + + marshal := func(input protoiface.MarshalInput) (protoiface.MarshalOutput, error) { + x := input.Message.Interface().(*Permissions) + if x == nil { + return protoiface.MarshalOutput{ + NoUnkeyedLiterals: input.NoUnkeyedLiterals, + Buf: input.Buf, + }, nil + } + options := runtime.MarshalInputToOptions(input) + _ = options + size := options.Size(x) + dAtA := make([]byte, size) + i := len(dAtA) + _ = i + var l int + _ = l + if x.unknownFields != nil { + i -= len(x.unknownFields) + copy(dAtA[i:], x.unknownFields) + } + if len(x.LimitTypeUrls) > 0 { + for iNdEx := len(x.LimitTypeUrls) - 1; iNdEx >= 0; iNdEx-- { + i -= len(x.LimitTypeUrls[iNdEx]) + copy(dAtA[i:], x.LimitTypeUrls[iNdEx]) + i = runtime.EncodeVarint(dAtA, i, uint64(len(x.LimitTypeUrls[iNdEx]))) + i-- + dAtA[i] = 0x12 + } + } + if x.Level != 0 { + i = runtime.EncodeVarint(dAtA, i, uint64(x.Level)) + i-- + dAtA[i] = 0x8 + } + if input.Buf != nil { + input.Buf = append(input.Buf, dAtA...) + } else { + input.Buf = dAtA + } + return protoiface.MarshalOutput{ + NoUnkeyedLiterals: input.NoUnkeyedLiterals, + Buf: input.Buf, + }, nil + } + unmarshal := func(input protoiface.UnmarshalInput) (protoiface.UnmarshalOutput, error) { + x := input.Message.Interface().(*Permissions) + if x == nil { + return protoiface.UnmarshalOutput{ + NoUnkeyedLiterals: input.NoUnkeyedLiterals, + Flags: input.Flags, + }, nil + } + options := runtime.UnmarshalInputToOptions(input) + _ = options + dAtA := input.Buf + l := len(dAtA) + iNdEx := 0 + for iNdEx < l { + preIndex := iNdEx + var wire uint64 + for shift := uint(0); ; shift += 7 { + if shift >= 64 { + return protoiface.UnmarshalOutput{NoUnkeyedLiterals: input.NoUnkeyedLiterals, Flags: input.Flags}, runtime.ErrIntOverflow + } + if iNdEx >= l { + return protoiface.UnmarshalOutput{NoUnkeyedLiterals: input.NoUnkeyedLiterals, Flags: input.Flags}, io.ErrUnexpectedEOF + } + b := dAtA[iNdEx] + iNdEx++ + wire |= uint64(b&0x7F) << shift + if b < 0x80 { + break + } + } + fieldNum := int32(wire >> 3) + wireType := int(wire & 0x7) + if wireType == 4 { + return protoiface.UnmarshalOutput{NoUnkeyedLiterals: input.NoUnkeyedLiterals, Flags: input.Flags}, fmt.Errorf("proto: Permissions: wiretype end group for non-group") + } + if fieldNum <= 0 { + return protoiface.UnmarshalOutput{NoUnkeyedLiterals: input.NoUnkeyedLiterals, Flags: input.Flags}, fmt.Errorf("proto: Permissions: illegal tag %d (wire type %d)", fieldNum, wire) + } + switch fieldNum { + case 1: + if wireType != 0 { + return protoiface.UnmarshalOutput{NoUnkeyedLiterals: input.NoUnkeyedLiterals, Flags: input.Flags}, fmt.Errorf("proto: wrong wireType = %d for field Level", wireType) + } + x.Level = 0 + for shift := uint(0); ; shift += 7 { + if shift >= 64 { + return protoiface.UnmarshalOutput{NoUnkeyedLiterals: input.NoUnkeyedLiterals, Flags: input.Flags}, runtime.ErrIntOverflow + } + if iNdEx >= l { + return protoiface.UnmarshalOutput{NoUnkeyedLiterals: input.NoUnkeyedLiterals, Flags: input.Flags}, io.ErrUnexpectedEOF + } + b := dAtA[iNdEx] + iNdEx++ + x.Level |= Permissions_Level(b&0x7F) << shift + if b < 0x80 { + break + } + } + case 2: + if wireType != 2 { + return protoiface.UnmarshalOutput{NoUnkeyedLiterals: input.NoUnkeyedLiterals, Flags: input.Flags}, fmt.Errorf("proto: wrong wireType = %d for field LimitTypeUrls", wireType) + } + var stringLen uint64 + for shift := uint(0); ; shift += 7 { + if shift >= 64 { + return protoiface.UnmarshalOutput{NoUnkeyedLiterals: input.NoUnkeyedLiterals, Flags: input.Flags}, runtime.ErrIntOverflow + } + if iNdEx >= l { + return protoiface.UnmarshalOutput{NoUnkeyedLiterals: input.NoUnkeyedLiterals, Flags: input.Flags}, io.ErrUnexpectedEOF + } + b := dAtA[iNdEx] + iNdEx++ + stringLen |= uint64(b&0x7F) << shift + if b < 0x80 { + break + } + } + intStringLen := int(stringLen) + if intStringLen < 0 { + return protoiface.UnmarshalOutput{NoUnkeyedLiterals: input.NoUnkeyedLiterals, Flags: input.Flags}, runtime.ErrInvalidLength + } + postIndex := iNdEx + intStringLen + if postIndex < 0 { + return protoiface.UnmarshalOutput{NoUnkeyedLiterals: input.NoUnkeyedLiterals, Flags: input.Flags}, runtime.ErrInvalidLength + } + if postIndex > l { + return protoiface.UnmarshalOutput{NoUnkeyedLiterals: input.NoUnkeyedLiterals, Flags: input.Flags}, io.ErrUnexpectedEOF + } + x.LimitTypeUrls = append(x.LimitTypeUrls, string(dAtA[iNdEx:postIndex])) + iNdEx = postIndex + default: + iNdEx = preIndex + skippy, err := runtime.Skip(dAtA[iNdEx:]) + if err != nil { + return protoiface.UnmarshalOutput{NoUnkeyedLiterals: input.NoUnkeyedLiterals, Flags: input.Flags}, err + } + if (skippy < 0) || (iNdEx+skippy) < 0 { + return protoiface.UnmarshalOutput{NoUnkeyedLiterals: input.NoUnkeyedLiterals, Flags: input.Flags}, runtime.ErrInvalidLength + } + if (iNdEx + skippy) > l { + return protoiface.UnmarshalOutput{NoUnkeyedLiterals: input.NoUnkeyedLiterals, Flags: input.Flags}, io.ErrUnexpectedEOF + } + if !options.DiscardUnknown { + x.unknownFields = append(x.unknownFields, dAtA[iNdEx:iNdEx+skippy]...) + } + iNdEx += skippy + } + } + + if iNdEx > l { + return protoiface.UnmarshalOutput{NoUnkeyedLiterals: input.NoUnkeyedLiterals, Flags: input.Flags}, io.ErrUnexpectedEOF + } + return protoiface.UnmarshalOutput{NoUnkeyedLiterals: input.NoUnkeyedLiterals, Flags: input.Flags}, nil + } + return &protoiface.Methods{ + NoUnkeyedLiterals: struct{}{}, + Flags: protoiface.SupportMarshalDeterministic | protoiface.SupportUnmarshalDiscardUnknown, + Size: size, + Marshal: marshal, + Unmarshal: unmarshal, + Merge: nil, + CheckInitialized: nil, + } +} + +var ( + md_GenesisAccountPermissions protoreflect.MessageDescriptor + fd_GenesisAccountPermissions_address protoreflect.FieldDescriptor + fd_GenesisAccountPermissions_permissions protoreflect.FieldDescriptor +) + +func init() { + file_cosmos_circuit_v1_types_proto_init() + md_GenesisAccountPermissions = File_cosmos_circuit_v1_types_proto.Messages().ByName("GenesisAccountPermissions") + fd_GenesisAccountPermissions_address = md_GenesisAccountPermissions.Fields().ByName("address") + fd_GenesisAccountPermissions_permissions = md_GenesisAccountPermissions.Fields().ByName("permissions") +} + +var _ protoreflect.Message = (*fastReflection_GenesisAccountPermissions)(nil) + +type fastReflection_GenesisAccountPermissions GenesisAccountPermissions + +func (x *GenesisAccountPermissions) ProtoReflect() protoreflect.Message { + return (*fastReflection_GenesisAccountPermissions)(x) +} + +func (x *GenesisAccountPermissions) slowProtoReflect() protoreflect.Message { + mi := &file_cosmos_circuit_v1_types_proto_msgTypes[1] + if protoimpl.UnsafeEnabled && x != nil { + ms := protoimpl.X.MessageStateOf(protoimpl.Pointer(x)) + if ms.LoadMessageInfo() == nil { + ms.StoreMessageInfo(mi) + } + return ms + } + return mi.MessageOf(x) +} + +var _fastReflection_GenesisAccountPermissions_messageType fastReflection_GenesisAccountPermissions_messageType +var _ protoreflect.MessageType = fastReflection_GenesisAccountPermissions_messageType{} + +type fastReflection_GenesisAccountPermissions_messageType struct{} + +func (x fastReflection_GenesisAccountPermissions_messageType) Zero() protoreflect.Message { + return (*fastReflection_GenesisAccountPermissions)(nil) +} +func (x fastReflection_GenesisAccountPermissions_messageType) New() protoreflect.Message { + return new(fastReflection_GenesisAccountPermissions) +} +func (x fastReflection_GenesisAccountPermissions_messageType) Descriptor() protoreflect.MessageDescriptor { + return md_GenesisAccountPermissions +} + +// Descriptor returns message descriptor, which contains only the protobuf +// type information for the message. +func (x *fastReflection_GenesisAccountPermissions) Descriptor() protoreflect.MessageDescriptor { + return md_GenesisAccountPermissions +} + +// Type returns the message type, which encapsulates both Go and protobuf +// type information. If the Go type information is not needed, +// it is recommended that the message descriptor be used instead. +func (x *fastReflection_GenesisAccountPermissions) Type() protoreflect.MessageType { + return _fastReflection_GenesisAccountPermissions_messageType +} + +// New returns a newly allocated and mutable empty message. +func (x *fastReflection_GenesisAccountPermissions) New() protoreflect.Message { + return new(fastReflection_GenesisAccountPermissions) +} + +// Interface unwraps the message reflection interface and +// returns the underlying ProtoMessage interface. +func (x *fastReflection_GenesisAccountPermissions) Interface() protoreflect.ProtoMessage { + return (*GenesisAccountPermissions)(x) +} + +// Range iterates over every populated field in an undefined order, +// calling f for each field descriptor and value encountered. +// Range returns immediately if f returns false. +// While iterating, mutating operations may only be performed +// on the current field descriptor. +func (x *fastReflection_GenesisAccountPermissions) Range(f func(protoreflect.FieldDescriptor, protoreflect.Value) bool) { + if x.Address != "" { + value := protoreflect.ValueOfString(x.Address) + if !f(fd_GenesisAccountPermissions_address, value) { + return + } + } + if x.Permissions != nil { + value := protoreflect.ValueOfMessage(x.Permissions.ProtoReflect()) + if !f(fd_GenesisAccountPermissions_permissions, value) { + return + } + } +} + +// Has reports whether a field is populated. +// +// Some fields have the property of nullability where it is possible to +// distinguish between the default value of a field and whether the field +// was explicitly populated with the default value. Singular message fields, +// member fields of a oneof, and proto2 scalar fields are nullable. Such +// fields are populated only if explicitly set. +// +// In other cases (aside from the nullable cases above), +// a proto3 scalar field is populated if it contains a non-zero value, and +// a repeated field is populated if it is non-empty. +func (x *fastReflection_GenesisAccountPermissions) Has(fd protoreflect.FieldDescriptor) bool { + switch fd.FullName() { + case "cosmos.circuit.v1.GenesisAccountPermissions.address": + return x.Address != "" + case "cosmos.circuit.v1.GenesisAccountPermissions.permissions": + return x.Permissions != nil + default: + if fd.IsExtension() { + panic(fmt.Errorf("proto3 declared messages do not support extensions: cosmos.circuit.v1.GenesisAccountPermissions")) + } + panic(fmt.Errorf("message cosmos.circuit.v1.GenesisAccountPermissions does not contain field %s", fd.FullName())) + } +} + +// Clear clears the field such that a subsequent Has call reports false. +// +// Clearing an extension field clears both the extension type and value +// associated with the given field number. +// +// Clear is a mutating operation and unsafe for concurrent use. +func (x *fastReflection_GenesisAccountPermissions) Clear(fd protoreflect.FieldDescriptor) { + switch fd.FullName() { + case "cosmos.circuit.v1.GenesisAccountPermissions.address": + x.Address = "" + case "cosmos.circuit.v1.GenesisAccountPermissions.permissions": + x.Permissions = nil + default: + if fd.IsExtension() { + panic(fmt.Errorf("proto3 declared messages do not support extensions: cosmos.circuit.v1.GenesisAccountPermissions")) + } + panic(fmt.Errorf("message cosmos.circuit.v1.GenesisAccountPermissions does not contain field %s", fd.FullName())) + } +} + +// Get retrieves the value for a field. +// +// For unpopulated scalars, it returns the default value, where +// the default value of a bytes scalar is guaranteed to be a copy. +// For unpopulated composite types, it returns an empty, read-only view +// of the value; to obtain a mutable reference, use Mutable. +func (x *fastReflection_GenesisAccountPermissions) Get(descriptor protoreflect.FieldDescriptor) protoreflect.Value { + switch descriptor.FullName() { + case "cosmos.circuit.v1.GenesisAccountPermissions.address": + value := x.Address + return protoreflect.ValueOfString(value) + case "cosmos.circuit.v1.GenesisAccountPermissions.permissions": + value := x.Permissions + return protoreflect.ValueOfMessage(value.ProtoReflect()) + default: + if descriptor.IsExtension() { + panic(fmt.Errorf("proto3 declared messages do not support extensions: cosmos.circuit.v1.GenesisAccountPermissions")) + } + panic(fmt.Errorf("message cosmos.circuit.v1.GenesisAccountPermissions does not contain field %s", descriptor.FullName())) + } +} + +// Set stores the value for a field. +// +// For a field belonging to a oneof, it implicitly clears any other field +// that may be currently set within the same oneof. +// For extension fields, it implicitly stores the provided ExtensionType. +// When setting a composite type, it is unspecified whether the stored value +// aliases the source's memory in any way. If the composite value is an +// empty, read-only value, then it panics. +// +// Set is a mutating operation and unsafe for concurrent use. +func (x *fastReflection_GenesisAccountPermissions) Set(fd protoreflect.FieldDescriptor, value protoreflect.Value) { + switch fd.FullName() { + case "cosmos.circuit.v1.GenesisAccountPermissions.address": + x.Address = value.Interface().(string) + case "cosmos.circuit.v1.GenesisAccountPermissions.permissions": + x.Permissions = value.Message().Interface().(*Permissions) + default: + if fd.IsExtension() { + panic(fmt.Errorf("proto3 declared messages do not support extensions: cosmos.circuit.v1.GenesisAccountPermissions")) + } + panic(fmt.Errorf("message cosmos.circuit.v1.GenesisAccountPermissions does not contain field %s", fd.FullName())) + } +} + +// Mutable returns a mutable reference to a composite type. +// +// If the field is unpopulated, it may allocate a composite value. +// For a field belonging to a oneof, it implicitly clears any other field +// that may be currently set within the same oneof. +// For extension fields, it implicitly stores the provided ExtensionType +// if not already stored. +// It panics if the field does not contain a composite type. +// +// Mutable is a mutating operation and unsafe for concurrent use. +func (x *fastReflection_GenesisAccountPermissions) Mutable(fd protoreflect.FieldDescriptor) protoreflect.Value { + switch fd.FullName() { + case "cosmos.circuit.v1.GenesisAccountPermissions.permissions": + if x.Permissions == nil { + x.Permissions = new(Permissions) + } + return protoreflect.ValueOfMessage(x.Permissions.ProtoReflect()) + case "cosmos.circuit.v1.GenesisAccountPermissions.address": + panic(fmt.Errorf("field address of message cosmos.circuit.v1.GenesisAccountPermissions is not mutable")) + default: + if fd.IsExtension() { + panic(fmt.Errorf("proto3 declared messages do not support extensions: cosmos.circuit.v1.GenesisAccountPermissions")) + } + panic(fmt.Errorf("message cosmos.circuit.v1.GenesisAccountPermissions does not contain field %s", fd.FullName())) + } +} + +// NewField returns a new value that is assignable to the field +// for the given descriptor. For scalars, this returns the default value. +// For lists, maps, and messages, this returns a new, empty, mutable value. +func (x *fastReflection_GenesisAccountPermissions) NewField(fd protoreflect.FieldDescriptor) protoreflect.Value { + switch fd.FullName() { + case "cosmos.circuit.v1.GenesisAccountPermissions.address": + return protoreflect.ValueOfString("") + case "cosmos.circuit.v1.GenesisAccountPermissions.permissions": + m := new(Permissions) + return protoreflect.ValueOfMessage(m.ProtoReflect()) + default: + if fd.IsExtension() { + panic(fmt.Errorf("proto3 declared messages do not support extensions: cosmos.circuit.v1.GenesisAccountPermissions")) + } + panic(fmt.Errorf("message cosmos.circuit.v1.GenesisAccountPermissions does not contain field %s", fd.FullName())) + } +} + +// WhichOneof reports which field within the oneof is populated, +// returning nil if none are populated. +// It panics if the oneof descriptor does not belong to this message. +func (x *fastReflection_GenesisAccountPermissions) WhichOneof(d protoreflect.OneofDescriptor) protoreflect.FieldDescriptor { + switch d.FullName() { + default: + panic(fmt.Errorf("%s is not a oneof field in cosmos.circuit.v1.GenesisAccountPermissions", d.FullName())) + } + panic("unreachable") +} + +// GetUnknown retrieves the entire list of unknown fields. +// The caller may only mutate the contents of the RawFields +// if the mutated bytes are stored back into the message with SetUnknown. +func (x *fastReflection_GenesisAccountPermissions) GetUnknown() protoreflect.RawFields { + return x.unknownFields +} + +// SetUnknown stores an entire list of unknown fields. +// The raw fields must be syntactically valid according to the wire format. +// An implementation may panic if this is not the case. +// Once stored, the caller must not mutate the content of the RawFields. +// An empty RawFields may be passed to clear the fields. +// +// SetUnknown is a mutating operation and unsafe for concurrent use. +func (x *fastReflection_GenesisAccountPermissions) SetUnknown(fields protoreflect.RawFields) { + x.unknownFields = fields +} + +// IsValid reports whether the message is valid. +// +// An invalid message is an empty, read-only value. +// +// An invalid message often corresponds to a nil pointer of the concrete +// message type, but the details are implementation dependent. +// Validity is not part of the protobuf data model, and may not +// be preserved in marshaling or other operations. +func (x *fastReflection_GenesisAccountPermissions) IsValid() bool { + return x != nil +} + +// ProtoMethods returns optional fastReflectionFeature-path implementations of various operations. +// This method may return nil. +// +// The returned methods type is identical to +// "google.golang.org/protobuf/runtime/protoiface".Methods. +// Consult the protoiface package documentation for details. +func (x *fastReflection_GenesisAccountPermissions) ProtoMethods() *protoiface.Methods { + size := func(input protoiface.SizeInput) protoiface.SizeOutput { + x := input.Message.Interface().(*GenesisAccountPermissions) + if x == nil { + return protoiface.SizeOutput{ + NoUnkeyedLiterals: input.NoUnkeyedLiterals, + Size: 0, + } + } + options := runtime.SizeInputToOptions(input) + _ = options + var n int + var l int + _ = l + l = len(x.Address) + if l > 0 { + n += 1 + l + runtime.Sov(uint64(l)) + } + if x.Permissions != nil { + l = options.Size(x.Permissions) + n += 1 + l + runtime.Sov(uint64(l)) + } + if x.unknownFields != nil { + n += len(x.unknownFields) + } + return protoiface.SizeOutput{ + NoUnkeyedLiterals: input.NoUnkeyedLiterals, + Size: n, + } + } + + marshal := func(input protoiface.MarshalInput) (protoiface.MarshalOutput, error) { + x := input.Message.Interface().(*GenesisAccountPermissions) + if x == nil { + return protoiface.MarshalOutput{ + NoUnkeyedLiterals: input.NoUnkeyedLiterals, + Buf: input.Buf, + }, nil + } + options := runtime.MarshalInputToOptions(input) + _ = options + size := options.Size(x) + dAtA := make([]byte, size) + i := len(dAtA) + _ = i + var l int + _ = l + if x.unknownFields != nil { + i -= len(x.unknownFields) + copy(dAtA[i:], x.unknownFields) + } + if x.Permissions != nil { + encoded, err := options.Marshal(x.Permissions) + if err != nil { + return protoiface.MarshalOutput{ + NoUnkeyedLiterals: input.NoUnkeyedLiterals, + Buf: input.Buf, + }, err + } + i -= len(encoded) + copy(dAtA[i:], encoded) + i = runtime.EncodeVarint(dAtA, i, uint64(len(encoded))) + i-- + dAtA[i] = 0x12 + } + if len(x.Address) > 0 { + i -= len(x.Address) + copy(dAtA[i:], x.Address) + i = runtime.EncodeVarint(dAtA, i, uint64(len(x.Address))) + i-- + dAtA[i] = 0xa + } + if input.Buf != nil { + input.Buf = append(input.Buf, dAtA...) + } else { + input.Buf = dAtA + } + return protoiface.MarshalOutput{ + NoUnkeyedLiterals: input.NoUnkeyedLiterals, + Buf: input.Buf, + }, nil + } + unmarshal := func(input protoiface.UnmarshalInput) (protoiface.UnmarshalOutput, error) { + x := input.Message.Interface().(*GenesisAccountPermissions) + if x == nil { + return protoiface.UnmarshalOutput{ + NoUnkeyedLiterals: input.NoUnkeyedLiterals, + Flags: input.Flags, + }, nil + } + options := runtime.UnmarshalInputToOptions(input) + _ = options + dAtA := input.Buf + l := len(dAtA) + iNdEx := 0 + for iNdEx < l { + preIndex := iNdEx + var wire uint64 + for shift := uint(0); ; shift += 7 { + if shift >= 64 { + return protoiface.UnmarshalOutput{NoUnkeyedLiterals: input.NoUnkeyedLiterals, Flags: input.Flags}, runtime.ErrIntOverflow + } + if iNdEx >= l { + return protoiface.UnmarshalOutput{NoUnkeyedLiterals: input.NoUnkeyedLiterals, Flags: input.Flags}, io.ErrUnexpectedEOF + } + b := dAtA[iNdEx] + iNdEx++ + wire |= uint64(b&0x7F) << shift + if b < 0x80 { + break + } + } + fieldNum := int32(wire >> 3) + wireType := int(wire & 0x7) + if wireType == 4 { + return protoiface.UnmarshalOutput{NoUnkeyedLiterals: input.NoUnkeyedLiterals, Flags: input.Flags}, fmt.Errorf("proto: GenesisAccountPermissions: wiretype end group for non-group") + } + if fieldNum <= 0 { + return protoiface.UnmarshalOutput{NoUnkeyedLiterals: input.NoUnkeyedLiterals, Flags: input.Flags}, fmt.Errorf("proto: GenesisAccountPermissions: illegal tag %d (wire type %d)", fieldNum, wire) + } + switch fieldNum { + case 1: + if wireType != 2 { + return protoiface.UnmarshalOutput{NoUnkeyedLiterals: input.NoUnkeyedLiterals, Flags: input.Flags}, fmt.Errorf("proto: wrong wireType = %d for field Address", wireType) + } + var stringLen uint64 + for shift := uint(0); ; shift += 7 { + if shift >= 64 { + return protoiface.UnmarshalOutput{NoUnkeyedLiterals: input.NoUnkeyedLiterals, Flags: input.Flags}, runtime.ErrIntOverflow + } + if iNdEx >= l { + return protoiface.UnmarshalOutput{NoUnkeyedLiterals: input.NoUnkeyedLiterals, Flags: input.Flags}, io.ErrUnexpectedEOF + } + b := dAtA[iNdEx] + iNdEx++ + stringLen |= uint64(b&0x7F) << shift + if b < 0x80 { + break + } + } + intStringLen := int(stringLen) + if intStringLen < 0 { + return protoiface.UnmarshalOutput{NoUnkeyedLiterals: input.NoUnkeyedLiterals, Flags: input.Flags}, runtime.ErrInvalidLength + } + postIndex := iNdEx + intStringLen + if postIndex < 0 { + return protoiface.UnmarshalOutput{NoUnkeyedLiterals: input.NoUnkeyedLiterals, Flags: input.Flags}, runtime.ErrInvalidLength + } + if postIndex > l { + return protoiface.UnmarshalOutput{NoUnkeyedLiterals: input.NoUnkeyedLiterals, Flags: input.Flags}, io.ErrUnexpectedEOF + } + x.Address = string(dAtA[iNdEx:postIndex]) + iNdEx = postIndex + case 2: + if wireType != 2 { + return protoiface.UnmarshalOutput{NoUnkeyedLiterals: input.NoUnkeyedLiterals, Flags: input.Flags}, fmt.Errorf("proto: wrong wireType = %d for field Permissions", wireType) + } + var msglen int + for shift := uint(0); ; shift += 7 { + if shift >= 64 { + return protoiface.UnmarshalOutput{NoUnkeyedLiterals: input.NoUnkeyedLiterals, Flags: input.Flags}, runtime.ErrIntOverflow + } + if iNdEx >= l { + return protoiface.UnmarshalOutput{NoUnkeyedLiterals: input.NoUnkeyedLiterals, Flags: input.Flags}, io.ErrUnexpectedEOF + } + b := dAtA[iNdEx] + iNdEx++ + msglen |= int(b&0x7F) << shift + if b < 0x80 { + break + } + } + if msglen < 0 { + return protoiface.UnmarshalOutput{NoUnkeyedLiterals: input.NoUnkeyedLiterals, Flags: input.Flags}, runtime.ErrInvalidLength + } + postIndex := iNdEx + msglen + if postIndex < 0 { + return protoiface.UnmarshalOutput{NoUnkeyedLiterals: input.NoUnkeyedLiterals, Flags: input.Flags}, runtime.ErrInvalidLength + } + if postIndex > l { + return protoiface.UnmarshalOutput{NoUnkeyedLiterals: input.NoUnkeyedLiterals, Flags: input.Flags}, io.ErrUnexpectedEOF + } + if x.Permissions == nil { + x.Permissions = &Permissions{} + } + if err := options.Unmarshal(dAtA[iNdEx:postIndex], x.Permissions); err != nil { + return protoiface.UnmarshalOutput{NoUnkeyedLiterals: input.NoUnkeyedLiterals, Flags: input.Flags}, err + } + iNdEx = postIndex + default: + iNdEx = preIndex + skippy, err := runtime.Skip(dAtA[iNdEx:]) + if err != nil { + return protoiface.UnmarshalOutput{NoUnkeyedLiterals: input.NoUnkeyedLiterals, Flags: input.Flags}, err + } + if (skippy < 0) || (iNdEx+skippy) < 0 { + return protoiface.UnmarshalOutput{NoUnkeyedLiterals: input.NoUnkeyedLiterals, Flags: input.Flags}, runtime.ErrInvalidLength + } + if (iNdEx + skippy) > l { + return protoiface.UnmarshalOutput{NoUnkeyedLiterals: input.NoUnkeyedLiterals, Flags: input.Flags}, io.ErrUnexpectedEOF + } + if !options.DiscardUnknown { + x.unknownFields = append(x.unknownFields, dAtA[iNdEx:iNdEx+skippy]...) + } + iNdEx += skippy + } + } + + if iNdEx > l { + return protoiface.UnmarshalOutput{NoUnkeyedLiterals: input.NoUnkeyedLiterals, Flags: input.Flags}, io.ErrUnexpectedEOF + } + return protoiface.UnmarshalOutput{NoUnkeyedLiterals: input.NoUnkeyedLiterals, Flags: input.Flags}, nil + } + return &protoiface.Methods{ + NoUnkeyedLiterals: struct{}{}, + Flags: protoiface.SupportMarshalDeterministic | protoiface.SupportUnmarshalDiscardUnknown, + Size: size, + Marshal: marshal, + Unmarshal: unmarshal, + Merge: nil, + CheckInitialized: nil, + } +} + +var _ protoreflect.List = (*_GenesisState_1_list)(nil) + +type _GenesisState_1_list struct { + list *[]*GenesisAccountPermissions +} + +func (x *_GenesisState_1_list) Len() int { + if x.list == nil { + return 0 + } + return len(*x.list) +} + +func (x *_GenesisState_1_list) Get(i int) protoreflect.Value { + return protoreflect.ValueOfMessage((*x.list)[i].ProtoReflect()) +} + +func (x *_GenesisState_1_list) Set(i int, value protoreflect.Value) { + valueUnwrapped := value.Message() + concreteValue := valueUnwrapped.Interface().(*GenesisAccountPermissions) + (*x.list)[i] = concreteValue +} + +func (x *_GenesisState_1_list) Append(value protoreflect.Value) { + valueUnwrapped := value.Message() + concreteValue := valueUnwrapped.Interface().(*GenesisAccountPermissions) + *x.list = append(*x.list, concreteValue) +} + +func (x *_GenesisState_1_list) AppendMutable() protoreflect.Value { + v := new(GenesisAccountPermissions) + *x.list = append(*x.list, v) + return protoreflect.ValueOfMessage(v.ProtoReflect()) +} + +func (x *_GenesisState_1_list) Truncate(n int) { + for i := n; i < len(*x.list); i++ { + (*x.list)[i] = nil + } + *x.list = (*x.list)[:n] +} + +func (x *_GenesisState_1_list) NewElement() protoreflect.Value { + v := new(GenesisAccountPermissions) + return protoreflect.ValueOfMessage(v.ProtoReflect()) +} + +func (x *_GenesisState_1_list) IsValid() bool { + return x.list != nil +} + +var _ protoreflect.List = (*_GenesisState_2_list)(nil) + +type _GenesisState_2_list struct { + list *[]string +} + +func (x *_GenesisState_2_list) Len() int { + if x.list == nil { + return 0 + } + return len(*x.list) +} + +func (x *_GenesisState_2_list) Get(i int) protoreflect.Value { + return protoreflect.ValueOfString((*x.list)[i]) +} + +func (x *_GenesisState_2_list) Set(i int, value protoreflect.Value) { + valueUnwrapped := value.String() + concreteValue := valueUnwrapped + (*x.list)[i] = concreteValue +} + +func (x *_GenesisState_2_list) Append(value protoreflect.Value) { + valueUnwrapped := value.String() + concreteValue := valueUnwrapped + *x.list = append(*x.list, concreteValue) +} + +func (x *_GenesisState_2_list) AppendMutable() protoreflect.Value { + panic(fmt.Errorf("AppendMutable can not be called on message GenesisState at list field DisabledTypeUrls as it is not of Message kind")) +} + +func (x *_GenesisState_2_list) Truncate(n int) { + *x.list = (*x.list)[:n] +} + +func (x *_GenesisState_2_list) NewElement() protoreflect.Value { + v := "" + return protoreflect.ValueOfString(v) +} + +func (x *_GenesisState_2_list) IsValid() bool { + return x.list != nil +} + +var ( + md_GenesisState protoreflect.MessageDescriptor + fd_GenesisState_account_permissions protoreflect.FieldDescriptor + fd_GenesisState_disabled_type_urls protoreflect.FieldDescriptor +) + +func init() { + file_cosmos_circuit_v1_types_proto_init() + md_GenesisState = File_cosmos_circuit_v1_types_proto.Messages().ByName("GenesisState") + fd_GenesisState_account_permissions = md_GenesisState.Fields().ByName("account_permissions") + fd_GenesisState_disabled_type_urls = md_GenesisState.Fields().ByName("disabled_type_urls") +} + +var _ protoreflect.Message = (*fastReflection_GenesisState)(nil) + +type fastReflection_GenesisState GenesisState + +func (x *GenesisState) ProtoReflect() protoreflect.Message { + return (*fastReflection_GenesisState)(x) +} + +func (x *GenesisState) slowProtoReflect() protoreflect.Message { + mi := &file_cosmos_circuit_v1_types_proto_msgTypes[2] + if protoimpl.UnsafeEnabled && x != nil { + ms := protoimpl.X.MessageStateOf(protoimpl.Pointer(x)) + if ms.LoadMessageInfo() == nil { + ms.StoreMessageInfo(mi) + } + return ms + } + return mi.MessageOf(x) +} + +var _fastReflection_GenesisState_messageType fastReflection_GenesisState_messageType +var _ protoreflect.MessageType = fastReflection_GenesisState_messageType{} + +type fastReflection_GenesisState_messageType struct{} + +func (x fastReflection_GenesisState_messageType) Zero() protoreflect.Message { + return (*fastReflection_GenesisState)(nil) +} +func (x fastReflection_GenesisState_messageType) New() protoreflect.Message { + return new(fastReflection_GenesisState) +} +func (x fastReflection_GenesisState_messageType) Descriptor() protoreflect.MessageDescriptor { + return md_GenesisState +} + +// Descriptor returns message descriptor, which contains only the protobuf +// type information for the message. +func (x *fastReflection_GenesisState) Descriptor() protoreflect.MessageDescriptor { + return md_GenesisState +} + +// Type returns the message type, which encapsulates both Go and protobuf +// type information. If the Go type information is not needed, +// it is recommended that the message descriptor be used instead. +func (x *fastReflection_GenesisState) Type() protoreflect.MessageType { + return _fastReflection_GenesisState_messageType +} + +// New returns a newly allocated and mutable empty message. +func (x *fastReflection_GenesisState) New() protoreflect.Message { + return new(fastReflection_GenesisState) +} + +// Interface unwraps the message reflection interface and +// returns the underlying ProtoMessage interface. +func (x *fastReflection_GenesisState) Interface() protoreflect.ProtoMessage { + return (*GenesisState)(x) +} + +// Range iterates over every populated field in an undefined order, +// calling f for each field descriptor and value encountered. +// Range returns immediately if f returns false. +// While iterating, mutating operations may only be performed +// on the current field descriptor. +func (x *fastReflection_GenesisState) Range(f func(protoreflect.FieldDescriptor, protoreflect.Value) bool) { + if len(x.AccountPermissions) != 0 { + value := protoreflect.ValueOfList(&_GenesisState_1_list{list: &x.AccountPermissions}) + if !f(fd_GenesisState_account_permissions, value) { + return + } + } + if len(x.DisabledTypeUrls) != 0 { + value := protoreflect.ValueOfList(&_GenesisState_2_list{list: &x.DisabledTypeUrls}) + if !f(fd_GenesisState_disabled_type_urls, value) { + return + } + } +} + +// Has reports whether a field is populated. +// +// Some fields have the property of nullability where it is possible to +// distinguish between the default value of a field and whether the field +// was explicitly populated with the default value. Singular message fields, +// member fields of a oneof, and proto2 scalar fields are nullable. Such +// fields are populated only if explicitly set. +// +// In other cases (aside from the nullable cases above), +// a proto3 scalar field is populated if it contains a non-zero value, and +// a repeated field is populated if it is non-empty. +func (x *fastReflection_GenesisState) Has(fd protoreflect.FieldDescriptor) bool { + switch fd.FullName() { + case "cosmos.circuit.v1.GenesisState.account_permissions": + return len(x.AccountPermissions) != 0 + case "cosmos.circuit.v1.GenesisState.disabled_type_urls": + return len(x.DisabledTypeUrls) != 0 + default: + if fd.IsExtension() { + panic(fmt.Errorf("proto3 declared messages do not support extensions: cosmos.circuit.v1.GenesisState")) + } + panic(fmt.Errorf("message cosmos.circuit.v1.GenesisState does not contain field %s", fd.FullName())) + } +} + +// Clear clears the field such that a subsequent Has call reports false. +// +// Clearing an extension field clears both the extension type and value +// associated with the given field number. +// +// Clear is a mutating operation and unsafe for concurrent use. +func (x *fastReflection_GenesisState) Clear(fd protoreflect.FieldDescriptor) { + switch fd.FullName() { + case "cosmos.circuit.v1.GenesisState.account_permissions": + x.AccountPermissions = nil + case "cosmos.circuit.v1.GenesisState.disabled_type_urls": + x.DisabledTypeUrls = nil + default: + if fd.IsExtension() { + panic(fmt.Errorf("proto3 declared messages do not support extensions: cosmos.circuit.v1.GenesisState")) + } + panic(fmt.Errorf("message cosmos.circuit.v1.GenesisState does not contain field %s", fd.FullName())) + } +} + +// Get retrieves the value for a field. +// +// For unpopulated scalars, it returns the default value, where +// the default value of a bytes scalar is guaranteed to be a copy. +// For unpopulated composite types, it returns an empty, read-only view +// of the value; to obtain a mutable reference, use Mutable. +func (x *fastReflection_GenesisState) Get(descriptor protoreflect.FieldDescriptor) protoreflect.Value { + switch descriptor.FullName() { + case "cosmos.circuit.v1.GenesisState.account_permissions": + if len(x.AccountPermissions) == 0 { + return protoreflect.ValueOfList(&_GenesisState_1_list{}) + } + listValue := &_GenesisState_1_list{list: &x.AccountPermissions} + return protoreflect.ValueOfList(listValue) + case "cosmos.circuit.v1.GenesisState.disabled_type_urls": + if len(x.DisabledTypeUrls) == 0 { + return protoreflect.ValueOfList(&_GenesisState_2_list{}) + } + listValue := &_GenesisState_2_list{list: &x.DisabledTypeUrls} + return protoreflect.ValueOfList(listValue) + default: + if descriptor.IsExtension() { + panic(fmt.Errorf("proto3 declared messages do not support extensions: cosmos.circuit.v1.GenesisState")) + } + panic(fmt.Errorf("message cosmos.circuit.v1.GenesisState does not contain field %s", descriptor.FullName())) + } +} + +// Set stores the value for a field. +// +// For a field belonging to a oneof, it implicitly clears any other field +// that may be currently set within the same oneof. +// For extension fields, it implicitly stores the provided ExtensionType. +// When setting a composite type, it is unspecified whether the stored value +// aliases the source's memory in any way. If the composite value is an +// empty, read-only value, then it panics. +// +// Set is a mutating operation and unsafe for concurrent use. +func (x *fastReflection_GenesisState) Set(fd protoreflect.FieldDescriptor, value protoreflect.Value) { + switch fd.FullName() { + case "cosmos.circuit.v1.GenesisState.account_permissions": + lv := value.List() + clv := lv.(*_GenesisState_1_list) + x.AccountPermissions = *clv.list + case "cosmos.circuit.v1.GenesisState.disabled_type_urls": + lv := value.List() + clv := lv.(*_GenesisState_2_list) + x.DisabledTypeUrls = *clv.list + default: + if fd.IsExtension() { + panic(fmt.Errorf("proto3 declared messages do not support extensions: cosmos.circuit.v1.GenesisState")) + } + panic(fmt.Errorf("message cosmos.circuit.v1.GenesisState does not contain field %s", fd.FullName())) + } +} + +// Mutable returns a mutable reference to a composite type. +// +// If the field is unpopulated, it may allocate a composite value. +// For a field belonging to a oneof, it implicitly clears any other field +// that may be currently set within the same oneof. +// For extension fields, it implicitly stores the provided ExtensionType +// if not already stored. +// It panics if the field does not contain a composite type. +// +// Mutable is a mutating operation and unsafe for concurrent use. +func (x *fastReflection_GenesisState) Mutable(fd protoreflect.FieldDescriptor) protoreflect.Value { + switch fd.FullName() { + case "cosmos.circuit.v1.GenesisState.account_permissions": + if x.AccountPermissions == nil { + x.AccountPermissions = []*GenesisAccountPermissions{} + } + value := &_GenesisState_1_list{list: &x.AccountPermissions} + return protoreflect.ValueOfList(value) + case "cosmos.circuit.v1.GenesisState.disabled_type_urls": + if x.DisabledTypeUrls == nil { + x.DisabledTypeUrls = []string{} + } + value := &_GenesisState_2_list{list: &x.DisabledTypeUrls} + return protoreflect.ValueOfList(value) + default: + if fd.IsExtension() { + panic(fmt.Errorf("proto3 declared messages do not support extensions: cosmos.circuit.v1.GenesisState")) + } + panic(fmt.Errorf("message cosmos.circuit.v1.GenesisState does not contain field %s", fd.FullName())) + } +} + +// NewField returns a new value that is assignable to the field +// for the given descriptor. For scalars, this returns the default value. +// For lists, maps, and messages, this returns a new, empty, mutable value. +func (x *fastReflection_GenesisState) NewField(fd protoreflect.FieldDescriptor) protoreflect.Value { + switch fd.FullName() { + case "cosmos.circuit.v1.GenesisState.account_permissions": + list := []*GenesisAccountPermissions{} + return protoreflect.ValueOfList(&_GenesisState_1_list{list: &list}) + case "cosmos.circuit.v1.GenesisState.disabled_type_urls": + list := []string{} + return protoreflect.ValueOfList(&_GenesisState_2_list{list: &list}) + default: + if fd.IsExtension() { + panic(fmt.Errorf("proto3 declared messages do not support extensions: cosmos.circuit.v1.GenesisState")) + } + panic(fmt.Errorf("message cosmos.circuit.v1.GenesisState does not contain field %s", fd.FullName())) + } +} + +// WhichOneof reports which field within the oneof is populated, +// returning nil if none are populated. +// It panics if the oneof descriptor does not belong to this message. +func (x *fastReflection_GenesisState) WhichOneof(d protoreflect.OneofDescriptor) protoreflect.FieldDescriptor { + switch d.FullName() { + default: + panic(fmt.Errorf("%s is not a oneof field in cosmos.circuit.v1.GenesisState", d.FullName())) + } + panic("unreachable") +} + +// GetUnknown retrieves the entire list of unknown fields. +// The caller may only mutate the contents of the RawFields +// if the mutated bytes are stored back into the message with SetUnknown. +func (x *fastReflection_GenesisState) GetUnknown() protoreflect.RawFields { + return x.unknownFields +} + +// SetUnknown stores an entire list of unknown fields. +// The raw fields must be syntactically valid according to the wire format. +// An implementation may panic if this is not the case. +// Once stored, the caller must not mutate the content of the RawFields. +// An empty RawFields may be passed to clear the fields. +// +// SetUnknown is a mutating operation and unsafe for concurrent use. +func (x *fastReflection_GenesisState) SetUnknown(fields protoreflect.RawFields) { + x.unknownFields = fields +} + +// IsValid reports whether the message is valid. +// +// An invalid message is an empty, read-only value. +// +// An invalid message often corresponds to a nil pointer of the concrete +// message type, but the details are implementation dependent. +// Validity is not part of the protobuf data model, and may not +// be preserved in marshaling or other operations. +func (x *fastReflection_GenesisState) IsValid() bool { + return x != nil +} + +// ProtoMethods returns optional fastReflectionFeature-path implementations of various operations. +// This method may return nil. +// +// The returned methods type is identical to +// "google.golang.org/protobuf/runtime/protoiface".Methods. +// Consult the protoiface package documentation for details. +func (x *fastReflection_GenesisState) ProtoMethods() *protoiface.Methods { + size := func(input protoiface.SizeInput) protoiface.SizeOutput { + x := input.Message.Interface().(*GenesisState) + if x == nil { + return protoiface.SizeOutput{ + NoUnkeyedLiterals: input.NoUnkeyedLiterals, + Size: 0, + } + } + options := runtime.SizeInputToOptions(input) + _ = options + var n int + var l int + _ = l + if len(x.AccountPermissions) > 0 { + for _, e := range x.AccountPermissions { + l = options.Size(e) + n += 1 + l + runtime.Sov(uint64(l)) + } + } + if len(x.DisabledTypeUrls) > 0 { + for _, s := range x.DisabledTypeUrls { + l = len(s) + n += 1 + l + runtime.Sov(uint64(l)) + } + } + if x.unknownFields != nil { + n += len(x.unknownFields) + } + return protoiface.SizeOutput{ + NoUnkeyedLiterals: input.NoUnkeyedLiterals, + Size: n, + } + } + + marshal := func(input protoiface.MarshalInput) (protoiface.MarshalOutput, error) { + x := input.Message.Interface().(*GenesisState) + if x == nil { + return protoiface.MarshalOutput{ + NoUnkeyedLiterals: input.NoUnkeyedLiterals, + Buf: input.Buf, + }, nil + } + options := runtime.MarshalInputToOptions(input) + _ = options + size := options.Size(x) + dAtA := make([]byte, size) + i := len(dAtA) + _ = i + var l int + _ = l + if x.unknownFields != nil { + i -= len(x.unknownFields) + copy(dAtA[i:], x.unknownFields) + } + if len(x.DisabledTypeUrls) > 0 { + for iNdEx := len(x.DisabledTypeUrls) - 1; iNdEx >= 0; iNdEx-- { + i -= len(x.DisabledTypeUrls[iNdEx]) + copy(dAtA[i:], x.DisabledTypeUrls[iNdEx]) + i = runtime.EncodeVarint(dAtA, i, uint64(len(x.DisabledTypeUrls[iNdEx]))) + i-- + dAtA[i] = 0x12 + } + } + if len(x.AccountPermissions) > 0 { + for iNdEx := len(x.AccountPermissions) - 1; iNdEx >= 0; iNdEx-- { + encoded, err := options.Marshal(x.AccountPermissions[iNdEx]) + if err != nil { + return protoiface.MarshalOutput{ + NoUnkeyedLiterals: input.NoUnkeyedLiterals, + Buf: input.Buf, + }, err + } + i -= len(encoded) + copy(dAtA[i:], encoded) + i = runtime.EncodeVarint(dAtA, i, uint64(len(encoded))) + i-- + dAtA[i] = 0xa + } + } + if input.Buf != nil { + input.Buf = append(input.Buf, dAtA...) + } else { + input.Buf = dAtA + } + return protoiface.MarshalOutput{ + NoUnkeyedLiterals: input.NoUnkeyedLiterals, + Buf: input.Buf, + }, nil + } + unmarshal := func(input protoiface.UnmarshalInput) (protoiface.UnmarshalOutput, error) { + x := input.Message.Interface().(*GenesisState) + if x == nil { + return protoiface.UnmarshalOutput{ + NoUnkeyedLiterals: input.NoUnkeyedLiterals, + Flags: input.Flags, + }, nil + } + options := runtime.UnmarshalInputToOptions(input) + _ = options + dAtA := input.Buf + l := len(dAtA) + iNdEx := 0 + for iNdEx < l { + preIndex := iNdEx + var wire uint64 + for shift := uint(0); ; shift += 7 { + if shift >= 64 { + return protoiface.UnmarshalOutput{NoUnkeyedLiterals: input.NoUnkeyedLiterals, Flags: input.Flags}, runtime.ErrIntOverflow + } + if iNdEx >= l { + return protoiface.UnmarshalOutput{NoUnkeyedLiterals: input.NoUnkeyedLiterals, Flags: input.Flags}, io.ErrUnexpectedEOF + } + b := dAtA[iNdEx] + iNdEx++ + wire |= uint64(b&0x7F) << shift + if b < 0x80 { + break + } + } + fieldNum := int32(wire >> 3) + wireType := int(wire & 0x7) + if wireType == 4 { + return protoiface.UnmarshalOutput{NoUnkeyedLiterals: input.NoUnkeyedLiterals, Flags: input.Flags}, fmt.Errorf("proto: GenesisState: wiretype end group for non-group") + } + if fieldNum <= 0 { + return protoiface.UnmarshalOutput{NoUnkeyedLiterals: input.NoUnkeyedLiterals, Flags: input.Flags}, fmt.Errorf("proto: GenesisState: illegal tag %d (wire type %d)", fieldNum, wire) + } + switch fieldNum { + case 1: + if wireType != 2 { + return protoiface.UnmarshalOutput{NoUnkeyedLiterals: input.NoUnkeyedLiterals, Flags: input.Flags}, fmt.Errorf("proto: wrong wireType = %d for field AccountPermissions", wireType) + } + var msglen int + for shift := uint(0); ; shift += 7 { + if shift >= 64 { + return protoiface.UnmarshalOutput{NoUnkeyedLiterals: input.NoUnkeyedLiterals, Flags: input.Flags}, runtime.ErrIntOverflow + } + if iNdEx >= l { + return protoiface.UnmarshalOutput{NoUnkeyedLiterals: input.NoUnkeyedLiterals, Flags: input.Flags}, io.ErrUnexpectedEOF + } + b := dAtA[iNdEx] + iNdEx++ + msglen |= int(b&0x7F) << shift + if b < 0x80 { + break + } + } + if msglen < 0 { + return protoiface.UnmarshalOutput{NoUnkeyedLiterals: input.NoUnkeyedLiterals, Flags: input.Flags}, runtime.ErrInvalidLength + } + postIndex := iNdEx + msglen + if postIndex < 0 { + return protoiface.UnmarshalOutput{NoUnkeyedLiterals: input.NoUnkeyedLiterals, Flags: input.Flags}, runtime.ErrInvalidLength + } + if postIndex > l { + return protoiface.UnmarshalOutput{NoUnkeyedLiterals: input.NoUnkeyedLiterals, Flags: input.Flags}, io.ErrUnexpectedEOF + } + x.AccountPermissions = append(x.AccountPermissions, &GenesisAccountPermissions{}) + if err := options.Unmarshal(dAtA[iNdEx:postIndex], x.AccountPermissions[len(x.AccountPermissions)-1]); err != nil { + return protoiface.UnmarshalOutput{NoUnkeyedLiterals: input.NoUnkeyedLiterals, Flags: input.Flags}, err + } + iNdEx = postIndex + case 2: + if wireType != 2 { + return protoiface.UnmarshalOutput{NoUnkeyedLiterals: input.NoUnkeyedLiterals, Flags: input.Flags}, fmt.Errorf("proto: wrong wireType = %d for field DisabledTypeUrls", wireType) + } + var stringLen uint64 + for shift := uint(0); ; shift += 7 { + if shift >= 64 { + return protoiface.UnmarshalOutput{NoUnkeyedLiterals: input.NoUnkeyedLiterals, Flags: input.Flags}, runtime.ErrIntOverflow + } + if iNdEx >= l { + return protoiface.UnmarshalOutput{NoUnkeyedLiterals: input.NoUnkeyedLiterals, Flags: input.Flags}, io.ErrUnexpectedEOF + } + b := dAtA[iNdEx] + iNdEx++ + stringLen |= uint64(b&0x7F) << shift + if b < 0x80 { + break + } + } + intStringLen := int(stringLen) + if intStringLen < 0 { + return protoiface.UnmarshalOutput{NoUnkeyedLiterals: input.NoUnkeyedLiterals, Flags: input.Flags}, runtime.ErrInvalidLength + } + postIndex := iNdEx + intStringLen + if postIndex < 0 { + return protoiface.UnmarshalOutput{NoUnkeyedLiterals: input.NoUnkeyedLiterals, Flags: input.Flags}, runtime.ErrInvalidLength + } + if postIndex > l { + return protoiface.UnmarshalOutput{NoUnkeyedLiterals: input.NoUnkeyedLiterals, Flags: input.Flags}, io.ErrUnexpectedEOF + } + x.DisabledTypeUrls = append(x.DisabledTypeUrls, string(dAtA[iNdEx:postIndex])) + iNdEx = postIndex + default: + iNdEx = preIndex + skippy, err := runtime.Skip(dAtA[iNdEx:]) + if err != nil { + return protoiface.UnmarshalOutput{NoUnkeyedLiterals: input.NoUnkeyedLiterals, Flags: input.Flags}, err + } + if (skippy < 0) || (iNdEx+skippy) < 0 { + return protoiface.UnmarshalOutput{NoUnkeyedLiterals: input.NoUnkeyedLiterals, Flags: input.Flags}, runtime.ErrInvalidLength + } + if (iNdEx + skippy) > l { + return protoiface.UnmarshalOutput{NoUnkeyedLiterals: input.NoUnkeyedLiterals, Flags: input.Flags}, io.ErrUnexpectedEOF + } + if !options.DiscardUnknown { + x.unknownFields = append(x.unknownFields, dAtA[iNdEx:iNdEx+skippy]...) + } + iNdEx += skippy + } + } + + if iNdEx > l { + return protoiface.UnmarshalOutput{NoUnkeyedLiterals: input.NoUnkeyedLiterals, Flags: input.Flags}, io.ErrUnexpectedEOF + } + return protoiface.UnmarshalOutput{NoUnkeyedLiterals: input.NoUnkeyedLiterals, Flags: input.Flags}, nil + } + return &protoiface.Methods{ + NoUnkeyedLiterals: struct{}{}, + Flags: protoiface.SupportMarshalDeterministic | protoiface.SupportUnmarshalDiscardUnknown, + Size: size, + Marshal: marshal, + Unmarshal: unmarshal, + Merge: nil, + CheckInitialized: nil, + } +} + +// Code generated by protoc-gen-go. DO NOT EDIT. +// versions: +// protoc-gen-go v1.27.0 +// protoc (unknown) +// source: cosmos/circuit/v1/types.proto + +const ( + // Verify that this generated code is sufficiently up-to-date. + _ = protoimpl.EnforceVersion(20 - protoimpl.MinVersion) + // Verify that runtime/protoimpl is sufficiently up-to-date. + _ = protoimpl.EnforceVersion(protoimpl.MaxVersion - 20) +) + +// Level is the permission level. +type Permissions_Level int32 + +const ( + // LEVEL_NONE_UNSPECIFIED indicates that the account will have no circuit + // breaker permissions. + Permissions_LEVEL_NONE_UNSPECIFIED Permissions_Level = 0 + // LEVEL_SOME_MSGS indicates that the account will have permission to + // trip or reset the circuit breaker for some Msg type URLs. If this level + // is chosen, a non-empty list of Msg type URLs must be provided in + // limit_type_urls. + Permissions_LEVEL_SOME_MSGS Permissions_Level = 1 + // LEVEL_ALL_MSGS indicates that the account can trip or reset the circuit + // breaker for Msg's of all type URLs. + Permissions_LEVEL_ALL_MSGS Permissions_Level = 2 + // LEVEL_SUPER_ADMIN indicates that the account can take all circuit breaker + // actions and can grant permissions to other accounts. + Permissions_LEVEL_SUPER_ADMIN Permissions_Level = 3 +) + +// Enum value maps for Permissions_Level. +var ( + Permissions_Level_name = map[int32]string{ + 0: "LEVEL_NONE_UNSPECIFIED", + 1: "LEVEL_SOME_MSGS", + 2: "LEVEL_ALL_MSGS", + 3: "LEVEL_SUPER_ADMIN", + } + Permissions_Level_value = map[string]int32{ + "LEVEL_NONE_UNSPECIFIED": 0, + "LEVEL_SOME_MSGS": 1, + "LEVEL_ALL_MSGS": 2, + "LEVEL_SUPER_ADMIN": 3, + } +) + +func (x Permissions_Level) Enum() *Permissions_Level { + p := new(Permissions_Level) + *p = x + return p +} + +func (x Permissions_Level) String() string { + return protoimpl.X.EnumStringOf(x.Descriptor(), protoreflect.EnumNumber(x)) +} + +func (Permissions_Level) Descriptor() protoreflect.EnumDescriptor { + return file_cosmos_circuit_v1_types_proto_enumTypes[0].Descriptor() +} + +func (Permissions_Level) Type() protoreflect.EnumType { + return &file_cosmos_circuit_v1_types_proto_enumTypes[0] +} + +func (x Permissions_Level) Number() protoreflect.EnumNumber { + return protoreflect.EnumNumber(x) +} + +// Deprecated: Use Permissions_Level.Descriptor instead. +func (Permissions_Level) EnumDescriptor() ([]byte, []int) { + return file_cosmos_circuit_v1_types_proto_rawDescGZIP(), []int{0, 0} +} + +// Permissions are the permissions that an account has to trip +// or reset the circuit breaker. +type Permissions struct { + state protoimpl.MessageState + sizeCache protoimpl.SizeCache + unknownFields protoimpl.UnknownFields + + // level is the level of permissions granted to this account. + Level Permissions_Level `protobuf:"varint,1,opt,name=level,proto3,enum=cosmos.circuit.v1.Permissions_Level" json:"level,omitempty"` + // limit_type_urls is used with LEVEL_SOME_MSGS to limit the lists of Msg type + // URLs that the account can trip. It is an error to use limit_type_urls with + // a level other than LEVEL_SOME_MSGS. + LimitTypeUrls []string `protobuf:"bytes,2,rep,name=limit_type_urls,json=limitTypeUrls,proto3" json:"limit_type_urls,omitempty"` +} + +func (x *Permissions) Reset() { + *x = Permissions{} + if protoimpl.UnsafeEnabled { + mi := &file_cosmos_circuit_v1_types_proto_msgTypes[0] + ms := protoimpl.X.MessageStateOf(protoimpl.Pointer(x)) + ms.StoreMessageInfo(mi) + } +} + +func (x *Permissions) String() string { + return protoimpl.X.MessageStringOf(x) +} + +func (*Permissions) ProtoMessage() {} + +// Deprecated: Use Permissions.ProtoReflect.Descriptor instead. +func (*Permissions) Descriptor() ([]byte, []int) { + return file_cosmos_circuit_v1_types_proto_rawDescGZIP(), []int{0} +} + +func (x *Permissions) GetLevel() Permissions_Level { + if x != nil { + return x.Level + } + return Permissions_LEVEL_NONE_UNSPECIFIED +} + +func (x *Permissions) GetLimitTypeUrls() []string { + if x != nil { + return x.LimitTypeUrls + } + return nil +} + +// GenesisAccountPermissions is the account permissions for the circuit breaker in genesis +type GenesisAccountPermissions struct { + state protoimpl.MessageState + sizeCache protoimpl.SizeCache + unknownFields protoimpl.UnknownFields + + Address string `protobuf:"bytes,1,opt,name=address,proto3" json:"address,omitempty"` + Permissions *Permissions `protobuf:"bytes,2,opt,name=permissions,proto3" json:"permissions,omitempty"` +} + +func (x *GenesisAccountPermissions) Reset() { + *x = GenesisAccountPermissions{} + if protoimpl.UnsafeEnabled { + mi := &file_cosmos_circuit_v1_types_proto_msgTypes[1] + ms := protoimpl.X.MessageStateOf(protoimpl.Pointer(x)) + ms.StoreMessageInfo(mi) + } +} + +func (x *GenesisAccountPermissions) String() string { + return protoimpl.X.MessageStringOf(x) +} + +func (*GenesisAccountPermissions) ProtoMessage() {} + +// Deprecated: Use GenesisAccountPermissions.ProtoReflect.Descriptor instead. +func (*GenesisAccountPermissions) Descriptor() ([]byte, []int) { + return file_cosmos_circuit_v1_types_proto_rawDescGZIP(), []int{1} +} + +func (x *GenesisAccountPermissions) GetAddress() string { + if x != nil { + return x.Address + } + return "" +} + +func (x *GenesisAccountPermissions) GetPermissions() *Permissions { + if x != nil { + return x.Permissions + } + return nil +} + +// GenesisState is the state that must be provided at genesis. +type GenesisState struct { + state protoimpl.MessageState + sizeCache protoimpl.SizeCache + unknownFields protoimpl.UnknownFields + + AccountPermissions []*GenesisAccountPermissions `protobuf:"bytes,1,rep,name=account_permissions,json=accountPermissions,proto3" json:"account_permissions,omitempty"` + DisabledTypeUrls []string `protobuf:"bytes,2,rep,name=disabled_type_urls,json=disabledTypeUrls,proto3" json:"disabled_type_urls,omitempty"` +} + +func (x *GenesisState) Reset() { + *x = GenesisState{} + if protoimpl.UnsafeEnabled { + mi := &file_cosmos_circuit_v1_types_proto_msgTypes[2] + ms := protoimpl.X.MessageStateOf(protoimpl.Pointer(x)) + ms.StoreMessageInfo(mi) + } +} + +func (x *GenesisState) String() string { + return protoimpl.X.MessageStringOf(x) +} + +func (*GenesisState) ProtoMessage() {} + +// Deprecated: Use GenesisState.ProtoReflect.Descriptor instead. +func (*GenesisState) Descriptor() ([]byte, []int) { + return file_cosmos_circuit_v1_types_proto_rawDescGZIP(), []int{2} +} + +func (x *GenesisState) GetAccountPermissions() []*GenesisAccountPermissions { + if x != nil { + return x.AccountPermissions + } + return nil +} + +func (x *GenesisState) GetDisabledTypeUrls() []string { + if x != nil { + return x.DisabledTypeUrls + } + return nil +} + +var File_cosmos_circuit_v1_types_proto protoreflect.FileDescriptor + +var file_cosmos_circuit_v1_types_proto_rawDesc = []byte{ + 0x0a, 0x1d, 0x63, 0x6f, 0x73, 0x6d, 0x6f, 0x73, 0x2f, 0x63, 0x69, 0x72, 0x63, 0x75, 0x69, 0x74, + 0x2f, 0x76, 0x31, 0x2f, 0x74, 0x79, 0x70, 0x65, 0x73, 0x2e, 0x70, 0x72, 0x6f, 0x74, 0x6f, 0x12, + 0x11, 0x63, 0x6f, 0x73, 0x6d, 0x6f, 0x73, 0x2e, 0x63, 0x69, 0x72, 0x63, 0x75, 0x69, 0x74, 0x2e, + 0x76, 0x31, 0x22, 0xd6, 0x01, 0x0a, 0x0b, 0x50, 0x65, 0x72, 0x6d, 0x69, 0x73, 0x73, 0x69, 0x6f, + 0x6e, 0x73, 0x12, 0x3a, 0x0a, 0x05, 0x6c, 0x65, 0x76, 0x65, 0x6c, 0x18, 0x01, 0x20, 0x01, 0x28, + 0x0e, 0x32, 0x24, 0x2e, 0x63, 0x6f, 0x73, 0x6d, 0x6f, 0x73, 0x2e, 0x63, 0x69, 0x72, 0x63, 0x75, + 0x69, 0x74, 0x2e, 0x76, 0x31, 0x2e, 0x50, 0x65, 0x72, 0x6d, 0x69, 0x73, 0x73, 0x69, 0x6f, 0x6e, + 0x73, 0x2e, 0x4c, 0x65, 0x76, 0x65, 0x6c, 0x52, 0x05, 0x6c, 0x65, 0x76, 0x65, 0x6c, 0x12, 0x26, + 0x0a, 0x0f, 0x6c, 0x69, 0x6d, 0x69, 0x74, 0x5f, 0x74, 0x79, 0x70, 0x65, 0x5f, 0x75, 0x72, 0x6c, + 0x73, 0x18, 0x02, 0x20, 0x03, 0x28, 0x09, 0x52, 0x0d, 0x6c, 0x69, 0x6d, 0x69, 0x74, 0x54, 0x79, + 0x70, 0x65, 0x55, 0x72, 0x6c, 0x73, 0x22, 0x63, 0x0a, 0x05, 0x4c, 0x65, 0x76, 0x65, 0x6c, 0x12, + 0x1a, 0x0a, 0x16, 0x4c, 0x45, 0x56, 0x45, 0x4c, 0x5f, 0x4e, 0x4f, 0x4e, 0x45, 0x5f, 0x55, 0x4e, + 0x53, 0x50, 0x45, 0x43, 0x49, 0x46, 0x49, 0x45, 0x44, 0x10, 0x00, 0x12, 0x13, 0x0a, 0x0f, 0x4c, + 0x45, 0x56, 0x45, 0x4c, 0x5f, 0x53, 0x4f, 0x4d, 0x45, 0x5f, 0x4d, 0x53, 0x47, 0x53, 0x10, 0x01, + 0x12, 0x12, 0x0a, 0x0e, 0x4c, 0x45, 0x56, 0x45, 0x4c, 0x5f, 0x41, 0x4c, 0x4c, 0x5f, 0x4d, 0x53, + 0x47, 0x53, 0x10, 0x02, 0x12, 0x15, 0x0a, 0x11, 0x4c, 0x45, 0x56, 0x45, 0x4c, 0x5f, 0x53, 0x55, + 0x50, 0x45, 0x52, 0x5f, 0x41, 0x44, 0x4d, 0x49, 0x4e, 0x10, 0x03, 0x22, 0x77, 0x0a, 0x19, 0x47, + 0x65, 0x6e, 0x65, 0x73, 0x69, 0x73, 0x41, 0x63, 0x63, 0x6f, 0x75, 0x6e, 0x74, 0x50, 0x65, 0x72, + 0x6d, 0x69, 0x73, 0x73, 0x69, 0x6f, 0x6e, 0x73, 0x12, 0x18, 0x0a, 0x07, 0x61, 0x64, 0x64, 0x72, + 0x65, 0x73, 0x73, 0x18, 0x01, 0x20, 0x01, 0x28, 0x09, 0x52, 0x07, 0x61, 0x64, 0x64, 0x72, 0x65, + 0x73, 0x73, 0x12, 0x40, 0x0a, 0x0b, 0x70, 0x65, 0x72, 0x6d, 0x69, 0x73, 0x73, 0x69, 0x6f, 0x6e, + 0x73, 0x18, 0x02, 0x20, 0x01, 0x28, 0x0b, 0x32, 0x1e, 0x2e, 0x63, 0x6f, 0x73, 0x6d, 0x6f, 0x73, + 0x2e, 0x63, 0x69, 0x72, 0x63, 0x75, 0x69, 0x74, 0x2e, 0x76, 0x31, 0x2e, 0x50, 0x65, 0x72, 0x6d, + 0x69, 0x73, 0x73, 0x69, 0x6f, 0x6e, 0x73, 0x52, 0x0b, 0x70, 0x65, 0x72, 0x6d, 0x69, 0x73, 0x73, + 0x69, 0x6f, 0x6e, 0x73, 0x22, 0x9b, 0x01, 0x0a, 0x0c, 0x47, 0x65, 0x6e, 0x65, 0x73, 0x69, 0x73, + 0x53, 0x74, 0x61, 0x74, 0x65, 0x12, 0x5d, 0x0a, 0x13, 0x61, 0x63, 0x63, 0x6f, 0x75, 0x6e, 0x74, + 0x5f, 0x70, 0x65, 0x72, 0x6d, 0x69, 0x73, 0x73, 0x69, 0x6f, 0x6e, 0x73, 0x18, 0x01, 0x20, 0x03, + 0x28, 0x0b, 0x32, 0x2c, 0x2e, 0x63, 0x6f, 0x73, 0x6d, 0x6f, 0x73, 0x2e, 0x63, 0x69, 0x72, 0x63, + 0x75, 0x69, 0x74, 0x2e, 0x76, 0x31, 0x2e, 0x47, 0x65, 0x6e, 0x65, 0x73, 0x69, 0x73, 0x41, 0x63, + 0x63, 0x6f, 0x75, 0x6e, 0x74, 0x50, 0x65, 0x72, 0x6d, 0x69, 0x73, 0x73, 0x69, 0x6f, 0x6e, 0x73, + 0x52, 0x12, 0x61, 0x63, 0x63, 0x6f, 0x75, 0x6e, 0x74, 0x50, 0x65, 0x72, 0x6d, 0x69, 0x73, 0x73, + 0x69, 0x6f, 0x6e, 0x73, 0x12, 0x2c, 0x0a, 0x12, 0x64, 0x69, 0x73, 0x61, 0x62, 0x6c, 0x65, 0x64, + 0x5f, 0x74, 0x79, 0x70, 0x65, 0x5f, 0x75, 0x72, 0x6c, 0x73, 0x18, 0x02, 0x20, 0x03, 0x28, 0x09, + 0x52, 0x10, 0x64, 0x69, 0x73, 0x61, 0x62, 0x6c, 0x65, 0x64, 0x54, 0x79, 0x70, 0x65, 0x55, 0x72, + 0x6c, 0x73, 0x42, 0xb7, 0x01, 0x0a, 0x15, 0x63, 0x6f, 0x6d, 0x2e, 0x63, 0x6f, 0x73, 0x6d, 0x6f, + 0x73, 0x2e, 0x63, 0x69, 0x72, 0x63, 0x75, 0x69, 0x74, 0x2e, 0x76, 0x31, 0x42, 0x0a, 0x54, 0x79, + 0x70, 0x65, 0x73, 0x50, 0x72, 0x6f, 0x74, 0x6f, 0x50, 0x01, 0x5a, 0x2c, 0x63, 0x6f, 0x73, 0x6d, + 0x6f, 0x73, 0x73, 0x64, 0x6b, 0x2e, 0x69, 0x6f, 0x2f, 0x61, 0x70, 0x69, 0x2f, 0x63, 0x6f, 0x73, + 0x6d, 0x6f, 0x73, 0x2f, 0x63, 0x69, 0x72, 0x63, 0x75, 0x69, 0x74, 0x2f, 0x76, 0x31, 0x3b, 0x63, + 0x69, 0x72, 0x63, 0x75, 0x69, 0x74, 0x76, 0x31, 0xa2, 0x02, 0x03, 0x43, 0x43, 0x58, 0xaa, 0x02, + 0x11, 0x43, 0x6f, 0x73, 0x6d, 0x6f, 0x73, 0x2e, 0x43, 0x69, 0x72, 0x63, 0x75, 0x69, 0x74, 0x2e, + 0x56, 0x31, 0xca, 0x02, 0x11, 0x43, 0x6f, 0x73, 0x6d, 0x6f, 0x73, 0x5c, 0x43, 0x69, 0x72, 0x63, + 0x75, 0x69, 0x74, 0x5c, 0x56, 0x31, 0xe2, 0x02, 0x1d, 0x43, 0x6f, 0x73, 0x6d, 0x6f, 0x73, 0x5c, + 0x43, 0x69, 0x72, 0x63, 0x75, 0x69, 0x74, 0x5c, 0x56, 0x31, 0x5c, 0x47, 0x50, 0x42, 0x4d, 0x65, + 0x74, 0x61, 0x64, 0x61, 0x74, 0x61, 0xea, 0x02, 0x13, 0x43, 0x6f, 0x73, 0x6d, 0x6f, 0x73, 0x3a, + 0x3a, 0x43, 0x69, 0x72, 0x63, 0x75, 0x69, 0x74, 0x3a, 0x3a, 0x56, 0x31, 0x62, 0x06, 0x70, 0x72, + 0x6f, 0x74, 0x6f, 0x33, +} + +var ( + file_cosmos_circuit_v1_types_proto_rawDescOnce sync.Once + file_cosmos_circuit_v1_types_proto_rawDescData = file_cosmos_circuit_v1_types_proto_rawDesc +) + +func file_cosmos_circuit_v1_types_proto_rawDescGZIP() []byte { + file_cosmos_circuit_v1_types_proto_rawDescOnce.Do(func() { + file_cosmos_circuit_v1_types_proto_rawDescData = protoimpl.X.CompressGZIP(file_cosmos_circuit_v1_types_proto_rawDescData) + }) + return file_cosmos_circuit_v1_types_proto_rawDescData +} + +var file_cosmos_circuit_v1_types_proto_enumTypes = make([]protoimpl.EnumInfo, 1) +var file_cosmos_circuit_v1_types_proto_msgTypes = make([]protoimpl.MessageInfo, 3) +var file_cosmos_circuit_v1_types_proto_goTypes = []interface{}{ + (Permissions_Level)(0), // 0: cosmos.circuit.v1.Permissions.Level + (*Permissions)(nil), // 1: cosmos.circuit.v1.Permissions + (*GenesisAccountPermissions)(nil), // 2: cosmos.circuit.v1.GenesisAccountPermissions + (*GenesisState)(nil), // 3: cosmos.circuit.v1.GenesisState +} +var file_cosmos_circuit_v1_types_proto_depIdxs = []int32{ + 0, // 0: cosmos.circuit.v1.Permissions.level:type_name -> cosmos.circuit.v1.Permissions.Level + 1, // 1: cosmos.circuit.v1.GenesisAccountPermissions.permissions:type_name -> cosmos.circuit.v1.Permissions + 2, // 2: cosmos.circuit.v1.GenesisState.account_permissions:type_name -> cosmos.circuit.v1.GenesisAccountPermissions + 3, // [3:3] is the sub-list for method output_type + 3, // [3:3] is the sub-list for method input_type + 3, // [3:3] is the sub-list for extension type_name + 3, // [3:3] is the sub-list for extension extendee + 0, // [0:3] is the sub-list for field type_name +} + +func init() { file_cosmos_circuit_v1_types_proto_init() } +func file_cosmos_circuit_v1_types_proto_init() { + if File_cosmos_circuit_v1_types_proto != nil { + return + } + if !protoimpl.UnsafeEnabled { + file_cosmos_circuit_v1_types_proto_msgTypes[0].Exporter = func(v interface{}, i int) interface{} { + switch v := v.(*Permissions); i { + case 0: + return &v.state + case 1: + return &v.sizeCache + case 2: + return &v.unknownFields + default: + return nil + } + } + file_cosmos_circuit_v1_types_proto_msgTypes[1].Exporter = func(v interface{}, i int) interface{} { + switch v := v.(*GenesisAccountPermissions); i { + case 0: + return &v.state + case 1: + return &v.sizeCache + case 2: + return &v.unknownFields + default: + return nil + } + } + file_cosmos_circuit_v1_types_proto_msgTypes[2].Exporter = func(v interface{}, i int) interface{} { + switch v := v.(*GenesisState); i { + case 0: + return &v.state + case 1: + return &v.sizeCache + case 2: + return &v.unknownFields + default: + return nil + } + } + } + type x struct{} + out := protoimpl.TypeBuilder{ + File: protoimpl.DescBuilder{ + GoPackagePath: reflect.TypeOf(x{}).PkgPath(), + RawDescriptor: file_cosmos_circuit_v1_types_proto_rawDesc, + NumEnums: 1, + NumMessages: 3, + NumExtensions: 0, + NumServices: 0, + }, + GoTypes: file_cosmos_circuit_v1_types_proto_goTypes, + DependencyIndexes: file_cosmos_circuit_v1_types_proto_depIdxs, + EnumInfos: file_cosmos_circuit_v1_types_proto_enumTypes, + MessageInfos: file_cosmos_circuit_v1_types_proto_msgTypes, + }.Build() + File_cosmos_circuit_v1_types_proto = out.File + file_cosmos_circuit_v1_types_proto_rawDesc = nil + file_cosmos_circuit_v1_types_proto_goTypes = nil + file_cosmos_circuit_v1_types_proto_depIdxs = nil +} diff --git a/api/cosmos/crypto/ed25519/keys.pulsar.go b/api/cosmos/crypto/ed25519/keys.pulsar.go index 13e2cf837e49..ed9f5a0dc64a 100644 --- a/api/cosmos/crypto/ed25519/keys.pulsar.go +++ b/api/cosmos/crypto/ed25519/keys.pulsar.go @@ -911,7 +911,7 @@ func (x *PubKey) GetKey() []byte { return nil } -// Deprecated: PrivKey defines a ed25519 private key. +// PrivKey defines a ed25519 private key. // NOTE: ed25519 keys must not be used in SDK apps except in a tendermint validator context. type PrivKey struct { state protoimpl.MessageState diff --git a/api/cosmos/distribution/v1beta1/tx.pulsar.go b/api/cosmos/distribution/v1beta1/tx.pulsar.go index ca4df29996d9..c9edc6f59342 100644 --- a/api/cosmos/distribution/v1beta1/tx.pulsar.go +++ b/api/cosmos/distribution/v1beta1/tx.pulsar.go @@ -5549,7 +5549,7 @@ func (x *_MsgDepositValidatorRewardsPool_3_list) IsValid() bool { var ( md_MsgDepositValidatorRewardsPool protoreflect.MessageDescriptor - fd_MsgDepositValidatorRewardsPool_authority protoreflect.FieldDescriptor + fd_MsgDepositValidatorRewardsPool_depositor protoreflect.FieldDescriptor fd_MsgDepositValidatorRewardsPool_validator_address protoreflect.FieldDescriptor fd_MsgDepositValidatorRewardsPool_amount protoreflect.FieldDescriptor ) @@ -5557,7 +5557,7 @@ var ( func init() { file_cosmos_distribution_v1beta1_tx_proto_init() md_MsgDepositValidatorRewardsPool = File_cosmos_distribution_v1beta1_tx_proto.Messages().ByName("MsgDepositValidatorRewardsPool") - fd_MsgDepositValidatorRewardsPool_authority = md_MsgDepositValidatorRewardsPool.Fields().ByName("authority") + fd_MsgDepositValidatorRewardsPool_depositor = md_MsgDepositValidatorRewardsPool.Fields().ByName("depositor") fd_MsgDepositValidatorRewardsPool_validator_address = md_MsgDepositValidatorRewardsPool.Fields().ByName("validator_address") fd_MsgDepositValidatorRewardsPool_amount = md_MsgDepositValidatorRewardsPool.Fields().ByName("amount") } @@ -5627,9 +5627,9 @@ func (x *fastReflection_MsgDepositValidatorRewardsPool) Interface() protoreflect // While iterating, mutating operations may only be performed // on the current field descriptor. func (x *fastReflection_MsgDepositValidatorRewardsPool) Range(f func(protoreflect.FieldDescriptor, protoreflect.Value) bool) { - if x.Authority != "" { - value := protoreflect.ValueOfString(x.Authority) - if !f(fd_MsgDepositValidatorRewardsPool_authority, value) { + if x.Depositor != "" { + value := protoreflect.ValueOfString(x.Depositor) + if !f(fd_MsgDepositValidatorRewardsPool_depositor, value) { return } } @@ -5660,8 +5660,8 @@ func (x *fastReflection_MsgDepositValidatorRewardsPool) Range(f func(protoreflec // a repeated field is populated if it is non-empty. func (x *fastReflection_MsgDepositValidatorRewardsPool) Has(fd protoreflect.FieldDescriptor) bool { switch fd.FullName() { - case "cosmos.distribution.v1beta1.MsgDepositValidatorRewardsPool.authority": - return x.Authority != "" + case "cosmos.distribution.v1beta1.MsgDepositValidatorRewardsPool.depositor": + return x.Depositor != "" case "cosmos.distribution.v1beta1.MsgDepositValidatorRewardsPool.validator_address": return x.ValidatorAddress != "" case "cosmos.distribution.v1beta1.MsgDepositValidatorRewardsPool.amount": @@ -5682,8 +5682,8 @@ func (x *fastReflection_MsgDepositValidatorRewardsPool) Has(fd protoreflect.Fiel // Clear is a mutating operation and unsafe for concurrent use. func (x *fastReflection_MsgDepositValidatorRewardsPool) Clear(fd protoreflect.FieldDescriptor) { switch fd.FullName() { - case "cosmos.distribution.v1beta1.MsgDepositValidatorRewardsPool.authority": - x.Authority = "" + case "cosmos.distribution.v1beta1.MsgDepositValidatorRewardsPool.depositor": + x.Depositor = "" case "cosmos.distribution.v1beta1.MsgDepositValidatorRewardsPool.validator_address": x.ValidatorAddress = "" case "cosmos.distribution.v1beta1.MsgDepositValidatorRewardsPool.amount": @@ -5704,8 +5704,8 @@ func (x *fastReflection_MsgDepositValidatorRewardsPool) Clear(fd protoreflect.Fi // of the value; to obtain a mutable reference, use Mutable. func (x *fastReflection_MsgDepositValidatorRewardsPool) Get(descriptor protoreflect.FieldDescriptor) protoreflect.Value { switch descriptor.FullName() { - case "cosmos.distribution.v1beta1.MsgDepositValidatorRewardsPool.authority": - value := x.Authority + case "cosmos.distribution.v1beta1.MsgDepositValidatorRewardsPool.depositor": + value := x.Depositor return protoreflect.ValueOfString(value) case "cosmos.distribution.v1beta1.MsgDepositValidatorRewardsPool.validator_address": value := x.ValidatorAddress @@ -5736,8 +5736,8 @@ func (x *fastReflection_MsgDepositValidatorRewardsPool) Get(descriptor protorefl // Set is a mutating operation and unsafe for concurrent use. func (x *fastReflection_MsgDepositValidatorRewardsPool) Set(fd protoreflect.FieldDescriptor, value protoreflect.Value) { switch fd.FullName() { - case "cosmos.distribution.v1beta1.MsgDepositValidatorRewardsPool.authority": - x.Authority = value.Interface().(string) + case "cosmos.distribution.v1beta1.MsgDepositValidatorRewardsPool.depositor": + x.Depositor = value.Interface().(string) case "cosmos.distribution.v1beta1.MsgDepositValidatorRewardsPool.validator_address": x.ValidatorAddress = value.Interface().(string) case "cosmos.distribution.v1beta1.MsgDepositValidatorRewardsPool.amount": @@ -5770,8 +5770,8 @@ func (x *fastReflection_MsgDepositValidatorRewardsPool) Mutable(fd protoreflect. } value := &_MsgDepositValidatorRewardsPool_3_list{list: &x.Amount} return protoreflect.ValueOfList(value) - case "cosmos.distribution.v1beta1.MsgDepositValidatorRewardsPool.authority": - panic(fmt.Errorf("field authority of message cosmos.distribution.v1beta1.MsgDepositValidatorRewardsPool is not mutable")) + case "cosmos.distribution.v1beta1.MsgDepositValidatorRewardsPool.depositor": + panic(fmt.Errorf("field depositor of message cosmos.distribution.v1beta1.MsgDepositValidatorRewardsPool is not mutable")) case "cosmos.distribution.v1beta1.MsgDepositValidatorRewardsPool.validator_address": panic(fmt.Errorf("field validator_address of message cosmos.distribution.v1beta1.MsgDepositValidatorRewardsPool is not mutable")) default: @@ -5787,7 +5787,7 @@ func (x *fastReflection_MsgDepositValidatorRewardsPool) Mutable(fd protoreflect. // For lists, maps, and messages, this returns a new, empty, mutable value. func (x *fastReflection_MsgDepositValidatorRewardsPool) NewField(fd protoreflect.FieldDescriptor) protoreflect.Value { switch fd.FullName() { - case "cosmos.distribution.v1beta1.MsgDepositValidatorRewardsPool.authority": + case "cosmos.distribution.v1beta1.MsgDepositValidatorRewardsPool.depositor": return protoreflect.ValueOfString("") case "cosmos.distribution.v1beta1.MsgDepositValidatorRewardsPool.validator_address": return protoreflect.ValueOfString("") @@ -5863,7 +5863,7 @@ func (x *fastReflection_MsgDepositValidatorRewardsPool) ProtoMethods() *protoifa var n int var l int _ = l - l = len(x.Authority) + l = len(x.Depositor) if l > 0 { n += 1 + l + runtime.Sov(uint64(l)) } @@ -5929,10 +5929,10 @@ func (x *fastReflection_MsgDepositValidatorRewardsPool) ProtoMethods() *protoifa i-- dAtA[i] = 0x12 } - if len(x.Authority) > 0 { - i -= len(x.Authority) - copy(dAtA[i:], x.Authority) - i = runtime.EncodeVarint(dAtA, i, uint64(len(x.Authority))) + if len(x.Depositor) > 0 { + i -= len(x.Depositor) + copy(dAtA[i:], x.Depositor) + i = runtime.EncodeVarint(dAtA, i, uint64(len(x.Depositor))) i-- dAtA[i] = 0xa } @@ -5987,7 +5987,7 @@ func (x *fastReflection_MsgDepositValidatorRewardsPool) ProtoMethods() *protoifa switch fieldNum { case 1: if wireType != 2 { - return protoiface.UnmarshalOutput{NoUnkeyedLiterals: input.NoUnkeyedLiterals, Flags: input.Flags}, fmt.Errorf("proto: wrong wireType = %d for field Authority", wireType) + return protoiface.UnmarshalOutput{NoUnkeyedLiterals: input.NoUnkeyedLiterals, Flags: input.Flags}, fmt.Errorf("proto: wrong wireType = %d for field Depositor", wireType) } var stringLen uint64 for shift := uint(0); ; shift += 7 { @@ -6015,7 +6015,7 @@ func (x *fastReflection_MsgDepositValidatorRewardsPool) ProtoMethods() *protoifa if postIndex > l { return protoiface.UnmarshalOutput{NoUnkeyedLiterals: input.NoUnkeyedLiterals, Flags: input.Flags}, io.ErrUnexpectedEOF } - x.Authority = string(dAtA[iNdEx:postIndex]) + x.Depositor = string(dAtA[iNdEx:postIndex]) iNdEx = postIndex case 2: if wireType != 2 { @@ -6966,7 +6966,7 @@ type MsgDepositValidatorRewardsPool struct { sizeCache protoimpl.SizeCache unknownFields protoimpl.UnknownFields - Authority string `protobuf:"bytes,1,opt,name=authority,proto3" json:"authority,omitempty"` + Depositor string `protobuf:"bytes,1,opt,name=depositor,proto3" json:"depositor,omitempty"` ValidatorAddress string `protobuf:"bytes,2,opt,name=validator_address,json=validatorAddress,proto3" json:"validator_address,omitempty"` Amount []*v1beta1.Coin `protobuf:"bytes,3,rep,name=amount,proto3" json:"amount,omitempty"` } @@ -6991,9 +6991,9 @@ func (*MsgDepositValidatorRewardsPool) Descriptor() ([]byte, []int) { return file_cosmos_distribution_v1beta1_tx_proto_rawDescGZIP(), []int{12} } -func (x *MsgDepositValidatorRewardsPool) GetAuthority() string { +func (x *MsgDepositValidatorRewardsPool) GetDepositor() string { if x != nil { - return x.Authority + return x.Depositor } return "" } @@ -7180,10 +7180,10 @@ var file_cosmos_distribution_v1beta1_tx_proto_rawDesc = []byte{ 0x65, 0x6e, 0x64, 0x52, 0x65, 0x73, 0x70, 0x6f, 0x6e, 0x73, 0x65, 0x22, 0xdc, 0x02, 0x0a, 0x1e, 0x4d, 0x73, 0x67, 0x44, 0x65, 0x70, 0x6f, 0x73, 0x69, 0x74, 0x56, 0x61, 0x6c, 0x69, 0x64, 0x61, 0x74, 0x6f, 0x72, 0x52, 0x65, 0x77, 0x61, 0x72, 0x64, 0x73, 0x50, 0x6f, 0x6f, 0x6c, 0x12, 0x36, - 0x0a, 0x09, 0x61, 0x75, 0x74, 0x68, 0x6f, 0x72, 0x69, 0x74, 0x79, 0x18, 0x01, 0x20, 0x01, 0x28, + 0x0a, 0x09, 0x64, 0x65, 0x70, 0x6f, 0x73, 0x69, 0x74, 0x6f, 0x72, 0x18, 0x01, 0x20, 0x01, 0x28, 0x09, 0x42, 0x18, 0xd2, 0xb4, 0x2d, 0x14, 0x63, 0x6f, 0x73, 0x6d, 0x6f, 0x73, 0x2e, 0x41, 0x64, - 0x64, 0x72, 0x65, 0x73, 0x73, 0x53, 0x74, 0x72, 0x69, 0x6e, 0x67, 0x52, 0x09, 0x61, 0x75, 0x74, - 0x68, 0x6f, 0x72, 0x69, 0x74, 0x79, 0x12, 0x45, 0x0a, 0x11, 0x76, 0x61, 0x6c, 0x69, 0x64, 0x61, + 0x64, 0x72, 0x65, 0x73, 0x73, 0x53, 0x74, 0x72, 0x69, 0x6e, 0x67, 0x52, 0x09, 0x64, 0x65, 0x70, + 0x6f, 0x73, 0x69, 0x74, 0x6f, 0x72, 0x12, 0x45, 0x0a, 0x11, 0x76, 0x61, 0x6c, 0x69, 0x64, 0x61, 0x74, 0x6f, 0x72, 0x5f, 0x61, 0x64, 0x64, 0x72, 0x65, 0x73, 0x73, 0x18, 0x02, 0x20, 0x01, 0x28, 0x09, 0x42, 0x18, 0xd2, 0xb4, 0x2d, 0x14, 0x63, 0x6f, 0x73, 0x6d, 0x6f, 0x73, 0x2e, 0x41, 0x64, 0x64, 0x72, 0x65, 0x73, 0x73, 0x53, 0x74, 0x72, 0x69, 0x6e, 0x67, 0x52, 0x10, 0x76, 0x61, 0x6c, @@ -7196,7 +7196,7 @@ var file_cosmos_distribution_v1beta1_tx_proto_rawDesc = []byte{ 0x79, 0x70, 0x65, 0x73, 0x2e, 0x43, 0x6f, 0x69, 0x6e, 0x73, 0x9a, 0xe7, 0xb0, 0x2a, 0x0c, 0x6c, 0x65, 0x67, 0x61, 0x63, 0x79, 0x5f, 0x63, 0x6f, 0x69, 0x6e, 0x73, 0xa8, 0xe7, 0xb0, 0x2a, 0x01, 0x52, 0x06, 0x61, 0x6d, 0x6f, 0x75, 0x6e, 0x74, 0x3a, 0x40, 0x88, 0xa0, 0x1f, 0x00, 0xe8, 0xa0, - 0x1f, 0x00, 0x82, 0xe7, 0xb0, 0x2a, 0x09, 0x61, 0x75, 0x74, 0x68, 0x6f, 0x72, 0x69, 0x74, 0x79, + 0x1f, 0x00, 0x82, 0xe7, 0xb0, 0x2a, 0x09, 0x64, 0x65, 0x70, 0x6f, 0x73, 0x69, 0x74, 0x6f, 0x72, 0x8a, 0xe7, 0xb0, 0x2a, 0x25, 0x63, 0x6f, 0x73, 0x6d, 0x6f, 0x73, 0x2d, 0x73, 0x64, 0x6b, 0x2f, 0x64, 0x69, 0x73, 0x74, 0x72, 0x2f, 0x4d, 0x73, 0x67, 0x44, 0x65, 0x70, 0x6f, 0x73, 0x69, 0x74, 0x56, 0x61, 0x6c, 0x52, 0x65, 0x77, 0x61, 0x72, 0x64, 0x73, 0x22, 0x28, 0x0a, 0x26, 0x4d, 0x73, diff --git a/api/cosmos/slashing/v1beta1/slashing.pulsar.go b/api/cosmos/slashing/v1beta1/slashing.pulsar.go index 0b70d3683cd5..f5de168f40e0 100644 --- a/api/cosmos/slashing/v1beta1/slashing.pulsar.go +++ b/api/cosmos/slashing/v1beta1/slashing.pulsar.go @@ -1416,19 +1416,20 @@ type ValidatorSigningInfo struct { unknownFields protoimpl.UnknownFields Address string `protobuf:"bytes,1,opt,name=address,proto3" json:"address,omitempty"` - // Height at which validator was first a candidate OR was unjailed + // Height at which validator was first a candidate OR was un-jailed StartHeight int64 `protobuf:"varint,2,opt,name=start_height,json=startHeight,proto3" json:"start_height,omitempty"` - // Index which is incremented each time the validator was a bonded - // in a block and may have signed a precommit or not. This in conjunction with the - // `SignedBlocksWindow` param determines the index in the `MissedBlocksBitArray`. + // Index which is incremented every time a validator is bonded in a block and + // _may_ have signed a pre-commit or not. This in conjunction with the + // signed_blocks_window param determines the index in the missed block bitmap. IndexOffset int64 `protobuf:"varint,3,opt,name=index_offset,json=indexOffset,proto3" json:"index_offset,omitempty"` // Timestamp until which the validator is jailed due to liveness downtime. JailedUntil *timestamppb.Timestamp `protobuf:"bytes,4,opt,name=jailed_until,json=jailedUntil,proto3" json:"jailed_until,omitempty"` - // Whether or not a validator has been tombstoned (killed out of validator set). It is set - // once the validator commits an equivocation or for any other configured misbehiavor. + // Whether or not a validator has been tombstoned (killed out of validator + // set). It is set once the validator commits an equivocation or for any other + // configured misbehavior. Tombstoned bool `protobuf:"varint,5,opt,name=tombstoned,proto3" json:"tombstoned,omitempty"` - // A counter kept to avoid unnecessary array reads. - // Note that `Sum(MissedBlocksBitArray)` always equals `MissedBlocksCounter`. + // A counter of missed (unsigned) blocks. It is used to avoid unnecessary + // reads in the missed block bitmap. MissedBlocksCounter int64 `protobuf:"varint,6,opt,name=missed_blocks_counter,json=missedBlocksCounter,proto3" json:"missed_blocks_counter,omitempty"` } diff --git a/api/cosmos/store/v1beta1/commit_info.pulsar.go b/api/cosmos/store/v1beta1/commit_info.pulsar.go index 1f15079352d5..c3fb16e6a275 100644 --- a/api/cosmos/store/v1beta1/commit_info.pulsar.go +++ b/api/cosmos/store/v1beta1/commit_info.pulsar.go @@ -8,6 +8,7 @@ import ( protoreflect "google.golang.org/protobuf/reflect/protoreflect" protoiface "google.golang.org/protobuf/runtime/protoiface" protoimpl "google.golang.org/protobuf/runtime/protoimpl" + timestamppb "google.golang.org/protobuf/types/known/timestamppb" io "io" reflect "reflect" sync "sync" @@ -68,6 +69,7 @@ var ( md_CommitInfo protoreflect.MessageDescriptor fd_CommitInfo_version protoreflect.FieldDescriptor fd_CommitInfo_store_infos protoreflect.FieldDescriptor + fd_CommitInfo_timestamp protoreflect.FieldDescriptor ) func init() { @@ -75,6 +77,7 @@ func init() { md_CommitInfo = File_cosmos_store_v1beta1_commit_info_proto.Messages().ByName("CommitInfo") fd_CommitInfo_version = md_CommitInfo.Fields().ByName("version") fd_CommitInfo_store_infos = md_CommitInfo.Fields().ByName("store_infos") + fd_CommitInfo_timestamp = md_CommitInfo.Fields().ByName("timestamp") } var _ protoreflect.Message = (*fastReflection_CommitInfo)(nil) @@ -154,6 +157,12 @@ func (x *fastReflection_CommitInfo) Range(f func(protoreflect.FieldDescriptor, p return } } + if x.Timestamp != nil { + value := protoreflect.ValueOfMessage(x.Timestamp.ProtoReflect()) + if !f(fd_CommitInfo_timestamp, value) { + return + } + } } // Has reports whether a field is populated. @@ -173,6 +182,8 @@ func (x *fastReflection_CommitInfo) Has(fd protoreflect.FieldDescriptor) bool { return x.Version != int64(0) case "cosmos.store.v1beta1.CommitInfo.store_infos": return len(x.StoreInfos) != 0 + case "cosmos.store.v1beta1.CommitInfo.timestamp": + return x.Timestamp != nil default: if fd.IsExtension() { panic(fmt.Errorf("proto3 declared messages do not support extensions: cosmos.store.v1beta1.CommitInfo")) @@ -193,6 +204,8 @@ func (x *fastReflection_CommitInfo) Clear(fd protoreflect.FieldDescriptor) { x.Version = int64(0) case "cosmos.store.v1beta1.CommitInfo.store_infos": x.StoreInfos = nil + case "cosmos.store.v1beta1.CommitInfo.timestamp": + x.Timestamp = nil default: if fd.IsExtension() { panic(fmt.Errorf("proto3 declared messages do not support extensions: cosmos.store.v1beta1.CommitInfo")) @@ -218,6 +231,9 @@ func (x *fastReflection_CommitInfo) Get(descriptor protoreflect.FieldDescriptor) } listValue := &_CommitInfo_2_list{list: &x.StoreInfos} return protoreflect.ValueOfList(listValue) + case "cosmos.store.v1beta1.CommitInfo.timestamp": + value := x.Timestamp + return protoreflect.ValueOfMessage(value.ProtoReflect()) default: if descriptor.IsExtension() { panic(fmt.Errorf("proto3 declared messages do not support extensions: cosmos.store.v1beta1.CommitInfo")) @@ -244,6 +260,8 @@ func (x *fastReflection_CommitInfo) Set(fd protoreflect.FieldDescriptor, value p lv := value.List() clv := lv.(*_CommitInfo_2_list) x.StoreInfos = *clv.list + case "cosmos.store.v1beta1.CommitInfo.timestamp": + x.Timestamp = value.Message().Interface().(*timestamppb.Timestamp) default: if fd.IsExtension() { panic(fmt.Errorf("proto3 declared messages do not support extensions: cosmos.store.v1beta1.CommitInfo")) @@ -270,6 +288,11 @@ func (x *fastReflection_CommitInfo) Mutable(fd protoreflect.FieldDescriptor) pro } value := &_CommitInfo_2_list{list: &x.StoreInfos} return protoreflect.ValueOfList(value) + case "cosmos.store.v1beta1.CommitInfo.timestamp": + if x.Timestamp == nil { + x.Timestamp = new(timestamppb.Timestamp) + } + return protoreflect.ValueOfMessage(x.Timestamp.ProtoReflect()) case "cosmos.store.v1beta1.CommitInfo.version": panic(fmt.Errorf("field version of message cosmos.store.v1beta1.CommitInfo is not mutable")) default: @@ -290,6 +313,9 @@ func (x *fastReflection_CommitInfo) NewField(fd protoreflect.FieldDescriptor) pr case "cosmos.store.v1beta1.CommitInfo.store_infos": list := []*StoreInfo{} return protoreflect.ValueOfList(&_CommitInfo_2_list{list: &list}) + case "cosmos.store.v1beta1.CommitInfo.timestamp": + m := new(timestamppb.Timestamp) + return protoreflect.ValueOfMessage(m.ProtoReflect()) default: if fd.IsExtension() { panic(fmt.Errorf("proto3 declared messages do not support extensions: cosmos.store.v1beta1.CommitInfo")) @@ -368,6 +394,10 @@ func (x *fastReflection_CommitInfo) ProtoMethods() *protoiface.Methods { n += 1 + l + runtime.Sov(uint64(l)) } } + if x.Timestamp != nil { + l = options.Size(x.Timestamp) + n += 1 + l + runtime.Sov(uint64(l)) + } if x.unknownFields != nil { n += len(x.unknownFields) } @@ -397,6 +427,20 @@ func (x *fastReflection_CommitInfo) ProtoMethods() *protoiface.Methods { i -= len(x.unknownFields) copy(dAtA[i:], x.unknownFields) } + if x.Timestamp != nil { + encoded, err := options.Marshal(x.Timestamp) + if err != nil { + return protoiface.MarshalOutput{ + NoUnkeyedLiterals: input.NoUnkeyedLiterals, + Buf: input.Buf, + }, err + } + i -= len(encoded) + copy(dAtA[i:], encoded) + i = runtime.EncodeVarint(dAtA, i, uint64(len(encoded))) + i-- + dAtA[i] = 0x1a + } if len(x.StoreInfos) > 0 { for iNdEx := len(x.StoreInfos) - 1; iNdEx >= 0; iNdEx-- { encoded, err := options.Marshal(x.StoreInfos[iNdEx]) @@ -520,6 +564,42 @@ func (x *fastReflection_CommitInfo) ProtoMethods() *protoiface.Methods { return protoiface.UnmarshalOutput{NoUnkeyedLiterals: input.NoUnkeyedLiterals, Flags: input.Flags}, err } iNdEx = postIndex + case 3: + if wireType != 2 { + return protoiface.UnmarshalOutput{NoUnkeyedLiterals: input.NoUnkeyedLiterals, Flags: input.Flags}, fmt.Errorf("proto: wrong wireType = %d for field Timestamp", wireType) + } + var msglen int + for shift := uint(0); ; shift += 7 { + if shift >= 64 { + return protoiface.UnmarshalOutput{NoUnkeyedLiterals: input.NoUnkeyedLiterals, Flags: input.Flags}, runtime.ErrIntOverflow + } + if iNdEx >= l { + return protoiface.UnmarshalOutput{NoUnkeyedLiterals: input.NoUnkeyedLiterals, Flags: input.Flags}, io.ErrUnexpectedEOF + } + b := dAtA[iNdEx] + iNdEx++ + msglen |= int(b&0x7F) << shift + if b < 0x80 { + break + } + } + if msglen < 0 { + return protoiface.UnmarshalOutput{NoUnkeyedLiterals: input.NoUnkeyedLiterals, Flags: input.Flags}, runtime.ErrInvalidLength + } + postIndex := iNdEx + msglen + if postIndex < 0 { + return protoiface.UnmarshalOutput{NoUnkeyedLiterals: input.NoUnkeyedLiterals, Flags: input.Flags}, runtime.ErrInvalidLength + } + if postIndex > l { + return protoiface.UnmarshalOutput{NoUnkeyedLiterals: input.NoUnkeyedLiterals, Flags: input.Flags}, io.ErrUnexpectedEOF + } + if x.Timestamp == nil { + x.Timestamp = ×tamppb.Timestamp{} + } + if err := options.Unmarshal(dAtA[iNdEx:postIndex], x.Timestamp); err != nil { + return protoiface.UnmarshalOutput{NoUnkeyedLiterals: input.NoUnkeyedLiterals, Flags: input.Flags}, err + } + iNdEx = postIndex default: iNdEx = preIndex skippy, err := runtime.Skip(dAtA[iNdEx:]) @@ -1544,8 +1624,9 @@ type CommitInfo struct { sizeCache protoimpl.SizeCache unknownFields protoimpl.UnknownFields - Version int64 `protobuf:"varint,1,opt,name=version,proto3" json:"version,omitempty"` - StoreInfos []*StoreInfo `protobuf:"bytes,2,rep,name=store_infos,json=storeInfos,proto3" json:"store_infos,omitempty"` + Version int64 `protobuf:"varint,1,opt,name=version,proto3" json:"version,omitempty"` + StoreInfos []*StoreInfo `protobuf:"bytes,2,rep,name=store_infos,json=storeInfos,proto3" json:"store_infos,omitempty"` + Timestamp *timestamppb.Timestamp `protobuf:"bytes,3,opt,name=timestamp,proto3" json:"timestamp,omitempty"` } func (x *CommitInfo) Reset() { @@ -1582,6 +1663,13 @@ func (x *CommitInfo) GetStoreInfos() []*StoreInfo { return nil } +func (x *CommitInfo) GetTimestamp() *timestamppb.Timestamp { + if x != nil { + return x.Timestamp + } + return nil +} + // StoreInfo defines store-specific commit information. It contains a reference // between a store name and the commit ID. type StoreInfo struct { @@ -1680,38 +1768,44 @@ var file_cosmos_store_v1beta1_commit_info_proto_rawDesc = []byte{ 0x66, 0x6f, 0x2e, 0x70, 0x72, 0x6f, 0x74, 0x6f, 0x12, 0x14, 0x63, 0x6f, 0x73, 0x6d, 0x6f, 0x73, 0x2e, 0x73, 0x74, 0x6f, 0x72, 0x65, 0x2e, 0x76, 0x31, 0x62, 0x65, 0x74, 0x61, 0x31, 0x1a, 0x14, 0x67, 0x6f, 0x67, 0x6f, 0x70, 0x72, 0x6f, 0x74, 0x6f, 0x2f, 0x67, 0x6f, 0x67, 0x6f, 0x2e, 0x70, - 0x72, 0x6f, 0x74, 0x6f, 0x22, 0x6e, 0x0a, 0x0a, 0x43, 0x6f, 0x6d, 0x6d, 0x69, 0x74, 0x49, 0x6e, - 0x66, 0x6f, 0x12, 0x18, 0x0a, 0x07, 0x76, 0x65, 0x72, 0x73, 0x69, 0x6f, 0x6e, 0x18, 0x01, 0x20, - 0x01, 0x28, 0x03, 0x52, 0x07, 0x76, 0x65, 0x72, 0x73, 0x69, 0x6f, 0x6e, 0x12, 0x46, 0x0a, 0x0b, - 0x73, 0x74, 0x6f, 0x72, 0x65, 0x5f, 0x69, 0x6e, 0x66, 0x6f, 0x73, 0x18, 0x02, 0x20, 0x03, 0x28, - 0x0b, 0x32, 0x1f, 0x2e, 0x63, 0x6f, 0x73, 0x6d, 0x6f, 0x73, 0x2e, 0x73, 0x74, 0x6f, 0x72, 0x65, - 0x2e, 0x76, 0x31, 0x62, 0x65, 0x74, 0x61, 0x31, 0x2e, 0x53, 0x74, 0x6f, 0x72, 0x65, 0x49, 0x6e, - 0x66, 0x6f, 0x42, 0x04, 0xc8, 0xde, 0x1f, 0x00, 0x52, 0x0a, 0x73, 0x74, 0x6f, 0x72, 0x65, 0x49, - 0x6e, 0x66, 0x6f, 0x73, 0x22, 0x62, 0x0a, 0x09, 0x53, 0x74, 0x6f, 0x72, 0x65, 0x49, 0x6e, 0x66, - 0x6f, 0x12, 0x12, 0x0a, 0x04, 0x6e, 0x61, 0x6d, 0x65, 0x18, 0x01, 0x20, 0x01, 0x28, 0x09, 0x52, - 0x04, 0x6e, 0x61, 0x6d, 0x65, 0x12, 0x41, 0x0a, 0x09, 0x63, 0x6f, 0x6d, 0x6d, 0x69, 0x74, 0x5f, - 0x69, 0x64, 0x18, 0x02, 0x20, 0x01, 0x28, 0x0b, 0x32, 0x1e, 0x2e, 0x63, 0x6f, 0x73, 0x6d, 0x6f, - 0x73, 0x2e, 0x73, 0x74, 0x6f, 0x72, 0x65, 0x2e, 0x76, 0x31, 0x62, 0x65, 0x74, 0x61, 0x31, 0x2e, - 0x43, 0x6f, 0x6d, 0x6d, 0x69, 0x74, 0x49, 0x44, 0x42, 0x04, 0xc8, 0xde, 0x1f, 0x00, 0x52, 0x08, - 0x63, 0x6f, 0x6d, 0x6d, 0x69, 0x74, 0x49, 0x64, 0x22, 0x3e, 0x0a, 0x08, 0x43, 0x6f, 0x6d, 0x6d, - 0x69, 0x74, 0x49, 0x44, 0x12, 0x18, 0x0a, 0x07, 0x76, 0x65, 0x72, 0x73, 0x69, 0x6f, 0x6e, 0x18, - 0x01, 0x20, 0x01, 0x28, 0x03, 0x52, 0x07, 0x76, 0x65, 0x72, 0x73, 0x69, 0x6f, 0x6e, 0x12, 0x12, - 0x0a, 0x04, 0x68, 0x61, 0x73, 0x68, 0x18, 0x02, 0x20, 0x01, 0x28, 0x0c, 0x52, 0x04, 0x68, 0x61, - 0x73, 0x68, 0x3a, 0x04, 0x98, 0xa0, 0x1f, 0x00, 0x42, 0xd1, 0x01, 0x0a, 0x18, 0x63, 0x6f, 0x6d, + 0x72, 0x6f, 0x74, 0x6f, 0x1a, 0x1f, 0x67, 0x6f, 0x6f, 0x67, 0x6c, 0x65, 0x2f, 0x70, 0x72, 0x6f, + 0x74, 0x6f, 0x62, 0x75, 0x66, 0x2f, 0x74, 0x69, 0x6d, 0x65, 0x73, 0x74, 0x61, 0x6d, 0x70, 0x2e, + 0x70, 0x72, 0x6f, 0x74, 0x6f, 0x22, 0xb2, 0x01, 0x0a, 0x0a, 0x43, 0x6f, 0x6d, 0x6d, 0x69, 0x74, + 0x49, 0x6e, 0x66, 0x6f, 0x12, 0x18, 0x0a, 0x07, 0x76, 0x65, 0x72, 0x73, 0x69, 0x6f, 0x6e, 0x18, + 0x01, 0x20, 0x01, 0x28, 0x03, 0x52, 0x07, 0x76, 0x65, 0x72, 0x73, 0x69, 0x6f, 0x6e, 0x12, 0x46, + 0x0a, 0x0b, 0x73, 0x74, 0x6f, 0x72, 0x65, 0x5f, 0x69, 0x6e, 0x66, 0x6f, 0x73, 0x18, 0x02, 0x20, + 0x03, 0x28, 0x0b, 0x32, 0x1f, 0x2e, 0x63, 0x6f, 0x73, 0x6d, 0x6f, 0x73, 0x2e, 0x73, 0x74, 0x6f, + 0x72, 0x65, 0x2e, 0x76, 0x31, 0x62, 0x65, 0x74, 0x61, 0x31, 0x2e, 0x53, 0x74, 0x6f, 0x72, 0x65, + 0x49, 0x6e, 0x66, 0x6f, 0x42, 0x04, 0xc8, 0xde, 0x1f, 0x00, 0x52, 0x0a, 0x73, 0x74, 0x6f, 0x72, + 0x65, 0x49, 0x6e, 0x66, 0x6f, 0x73, 0x12, 0x42, 0x0a, 0x09, 0x74, 0x69, 0x6d, 0x65, 0x73, 0x74, + 0x61, 0x6d, 0x70, 0x18, 0x03, 0x20, 0x01, 0x28, 0x0b, 0x32, 0x1a, 0x2e, 0x67, 0x6f, 0x6f, 0x67, + 0x6c, 0x65, 0x2e, 0x70, 0x72, 0x6f, 0x74, 0x6f, 0x62, 0x75, 0x66, 0x2e, 0x54, 0x69, 0x6d, 0x65, + 0x73, 0x74, 0x61, 0x6d, 0x70, 0x42, 0x08, 0xc8, 0xde, 0x1f, 0x00, 0x90, 0xdf, 0x1f, 0x01, 0x52, + 0x09, 0x74, 0x69, 0x6d, 0x65, 0x73, 0x74, 0x61, 0x6d, 0x70, 0x22, 0x62, 0x0a, 0x09, 0x53, 0x74, + 0x6f, 0x72, 0x65, 0x49, 0x6e, 0x66, 0x6f, 0x12, 0x12, 0x0a, 0x04, 0x6e, 0x61, 0x6d, 0x65, 0x18, + 0x01, 0x20, 0x01, 0x28, 0x09, 0x52, 0x04, 0x6e, 0x61, 0x6d, 0x65, 0x12, 0x41, 0x0a, 0x09, 0x63, + 0x6f, 0x6d, 0x6d, 0x69, 0x74, 0x5f, 0x69, 0x64, 0x18, 0x02, 0x20, 0x01, 0x28, 0x0b, 0x32, 0x1e, 0x2e, 0x63, 0x6f, 0x73, 0x6d, 0x6f, 0x73, 0x2e, 0x73, 0x74, 0x6f, 0x72, 0x65, 0x2e, 0x76, 0x31, - 0x62, 0x65, 0x74, 0x61, 0x31, 0x42, 0x0f, 0x43, 0x6f, 0x6d, 0x6d, 0x69, 0x74, 0x49, 0x6e, 0x66, - 0x6f, 0x50, 0x72, 0x6f, 0x74, 0x6f, 0x50, 0x01, 0x5a, 0x32, 0x63, 0x6f, 0x73, 0x6d, 0x6f, 0x73, - 0x73, 0x64, 0x6b, 0x2e, 0x69, 0x6f, 0x2f, 0x61, 0x70, 0x69, 0x2f, 0x63, 0x6f, 0x73, 0x6d, 0x6f, - 0x73, 0x2f, 0x73, 0x74, 0x6f, 0x72, 0x65, 0x2f, 0x76, 0x31, 0x62, 0x65, 0x74, 0x61, 0x31, 0x3b, - 0x73, 0x74, 0x6f, 0x72, 0x65, 0x76, 0x31, 0x62, 0x65, 0x74, 0x61, 0x31, 0xa2, 0x02, 0x03, 0x43, - 0x53, 0x58, 0xaa, 0x02, 0x14, 0x43, 0x6f, 0x73, 0x6d, 0x6f, 0x73, 0x2e, 0x53, 0x74, 0x6f, 0x72, - 0x65, 0x2e, 0x56, 0x31, 0x62, 0x65, 0x74, 0x61, 0x31, 0xca, 0x02, 0x14, 0x43, 0x6f, 0x73, 0x6d, - 0x6f, 0x73, 0x5c, 0x53, 0x74, 0x6f, 0x72, 0x65, 0x5c, 0x56, 0x31, 0x62, 0x65, 0x74, 0x61, 0x31, - 0xe2, 0x02, 0x20, 0x43, 0x6f, 0x73, 0x6d, 0x6f, 0x73, 0x5c, 0x53, 0x74, 0x6f, 0x72, 0x65, 0x5c, - 0x56, 0x31, 0x62, 0x65, 0x74, 0x61, 0x31, 0x5c, 0x47, 0x50, 0x42, 0x4d, 0x65, 0x74, 0x61, 0x64, - 0x61, 0x74, 0x61, 0xea, 0x02, 0x16, 0x43, 0x6f, 0x73, 0x6d, 0x6f, 0x73, 0x3a, 0x3a, 0x53, 0x74, - 0x6f, 0x72, 0x65, 0x3a, 0x3a, 0x56, 0x31, 0x62, 0x65, 0x74, 0x61, 0x31, 0x62, 0x06, 0x70, 0x72, - 0x6f, 0x74, 0x6f, 0x33, + 0x62, 0x65, 0x74, 0x61, 0x31, 0x2e, 0x43, 0x6f, 0x6d, 0x6d, 0x69, 0x74, 0x49, 0x44, 0x42, 0x04, + 0xc8, 0xde, 0x1f, 0x00, 0x52, 0x08, 0x63, 0x6f, 0x6d, 0x6d, 0x69, 0x74, 0x49, 0x64, 0x22, 0x3e, + 0x0a, 0x08, 0x43, 0x6f, 0x6d, 0x6d, 0x69, 0x74, 0x49, 0x44, 0x12, 0x18, 0x0a, 0x07, 0x76, 0x65, + 0x72, 0x73, 0x69, 0x6f, 0x6e, 0x18, 0x01, 0x20, 0x01, 0x28, 0x03, 0x52, 0x07, 0x76, 0x65, 0x72, + 0x73, 0x69, 0x6f, 0x6e, 0x12, 0x12, 0x0a, 0x04, 0x68, 0x61, 0x73, 0x68, 0x18, 0x02, 0x20, 0x01, + 0x28, 0x0c, 0x52, 0x04, 0x68, 0x61, 0x73, 0x68, 0x3a, 0x04, 0x98, 0xa0, 0x1f, 0x00, 0x42, 0xd1, + 0x01, 0x0a, 0x18, 0x63, 0x6f, 0x6d, 0x2e, 0x63, 0x6f, 0x73, 0x6d, 0x6f, 0x73, 0x2e, 0x73, 0x74, + 0x6f, 0x72, 0x65, 0x2e, 0x76, 0x31, 0x62, 0x65, 0x74, 0x61, 0x31, 0x42, 0x0f, 0x43, 0x6f, 0x6d, + 0x6d, 0x69, 0x74, 0x49, 0x6e, 0x66, 0x6f, 0x50, 0x72, 0x6f, 0x74, 0x6f, 0x50, 0x01, 0x5a, 0x32, + 0x63, 0x6f, 0x73, 0x6d, 0x6f, 0x73, 0x73, 0x64, 0x6b, 0x2e, 0x69, 0x6f, 0x2f, 0x61, 0x70, 0x69, + 0x2f, 0x63, 0x6f, 0x73, 0x6d, 0x6f, 0x73, 0x2f, 0x73, 0x74, 0x6f, 0x72, 0x65, 0x2f, 0x76, 0x31, + 0x62, 0x65, 0x74, 0x61, 0x31, 0x3b, 0x73, 0x74, 0x6f, 0x72, 0x65, 0x76, 0x31, 0x62, 0x65, 0x74, + 0x61, 0x31, 0xa2, 0x02, 0x03, 0x43, 0x53, 0x58, 0xaa, 0x02, 0x14, 0x43, 0x6f, 0x73, 0x6d, 0x6f, + 0x73, 0x2e, 0x53, 0x74, 0x6f, 0x72, 0x65, 0x2e, 0x56, 0x31, 0x62, 0x65, 0x74, 0x61, 0x31, 0xca, + 0x02, 0x14, 0x43, 0x6f, 0x73, 0x6d, 0x6f, 0x73, 0x5c, 0x53, 0x74, 0x6f, 0x72, 0x65, 0x5c, 0x56, + 0x31, 0x62, 0x65, 0x74, 0x61, 0x31, 0xe2, 0x02, 0x20, 0x43, 0x6f, 0x73, 0x6d, 0x6f, 0x73, 0x5c, + 0x53, 0x74, 0x6f, 0x72, 0x65, 0x5c, 0x56, 0x31, 0x62, 0x65, 0x74, 0x61, 0x31, 0x5c, 0x47, 0x50, + 0x42, 0x4d, 0x65, 0x74, 0x61, 0x64, 0x61, 0x74, 0x61, 0xea, 0x02, 0x16, 0x43, 0x6f, 0x73, 0x6d, + 0x6f, 0x73, 0x3a, 0x3a, 0x53, 0x74, 0x6f, 0x72, 0x65, 0x3a, 0x3a, 0x56, 0x31, 0x62, 0x65, 0x74, + 0x61, 0x31, 0x62, 0x06, 0x70, 0x72, 0x6f, 0x74, 0x6f, 0x33, } var ( @@ -1728,18 +1822,20 @@ func file_cosmos_store_v1beta1_commit_info_proto_rawDescGZIP() []byte { var file_cosmos_store_v1beta1_commit_info_proto_msgTypes = make([]protoimpl.MessageInfo, 3) var file_cosmos_store_v1beta1_commit_info_proto_goTypes = []interface{}{ - (*CommitInfo)(nil), // 0: cosmos.store.v1beta1.CommitInfo - (*StoreInfo)(nil), // 1: cosmos.store.v1beta1.StoreInfo - (*CommitID)(nil), // 2: cosmos.store.v1beta1.CommitID + (*CommitInfo)(nil), // 0: cosmos.store.v1beta1.CommitInfo + (*StoreInfo)(nil), // 1: cosmos.store.v1beta1.StoreInfo + (*CommitID)(nil), // 2: cosmos.store.v1beta1.CommitID + (*timestamppb.Timestamp)(nil), // 3: google.protobuf.Timestamp } var file_cosmos_store_v1beta1_commit_info_proto_depIdxs = []int32{ 1, // 0: cosmos.store.v1beta1.CommitInfo.store_infos:type_name -> cosmos.store.v1beta1.StoreInfo - 2, // 1: cosmos.store.v1beta1.StoreInfo.commit_id:type_name -> cosmos.store.v1beta1.CommitID - 2, // [2:2] is the sub-list for method output_type - 2, // [2:2] is the sub-list for method input_type - 2, // [2:2] is the sub-list for extension type_name - 2, // [2:2] is the sub-list for extension extendee - 0, // [0:2] is the sub-list for field type_name + 3, // 1: cosmos.store.v1beta1.CommitInfo.timestamp:type_name -> google.protobuf.Timestamp + 2, // 2: cosmos.store.v1beta1.StoreInfo.commit_id:type_name -> cosmos.store.v1beta1.CommitID + 3, // [3:3] is the sub-list for method output_type + 3, // [3:3] is the sub-list for method input_type + 3, // [3:3] is the sub-list for extension type_name + 3, // [3:3] is the sub-list for extension extendee + 0, // [0:3] is the sub-list for field type_name } func init() { file_cosmos_store_v1beta1_commit_info_proto_init() } diff --git a/api/go.mod b/api/go.mod index 7b0c6deddefb..8a05b791c294 100644 --- a/api/go.mod +++ b/api/go.mod @@ -4,7 +4,7 @@ go 1.20 require ( github.com/cosmos/cosmos-proto v1.0.0-beta.3 - github.com/cosmos/gogoproto v1.4.6 + github.com/cosmos/gogoproto v1.4.7 google.golang.org/genproto v0.0.0-20230320184635-7606e756e683 google.golang.org/grpc v1.54.0 google.golang.org/protobuf v1.30.0 diff --git a/api/go.sum b/api/go.sum index 52fca66c230d..3ac54a516286 100644 --- a/api/go.sum +++ b/api/go.sum @@ -1,7 +1,7 @@ github.com/cosmos/cosmos-proto v1.0.0-beta.3 h1:VitvZ1lPORTVxkmF2fAp3IiA61xVwArQYKXTdEcpW6o= github.com/cosmos/cosmos-proto v1.0.0-beta.3/go.mod h1:t8IASdLaAq+bbHbjq4p960BvcTqtwuAxid3b/2rOD6I= -github.com/cosmos/gogoproto v1.4.6 h1:Ee7z15dWJaGlgM2rWrK8N2IX7PQcuccu8oG68jp5RL4= -github.com/cosmos/gogoproto v1.4.6/go.mod h1:VS/ASYmPgv6zkPKLjR9EB91lwbLHOzaGCirmKKhncfI= +github.com/cosmos/gogoproto v1.4.7 h1:RzYKVnsEC7UIkDnhTIkqEB7LnIQbsySvmNEqPCiPevk= +github.com/cosmos/gogoproto v1.4.7/go.mod h1:gxGePp9qedovvl/StQL2BIJ6qlIBn1+9YxR0IulGBKA= github.com/golang/protobuf v1.5.0/go.mod h1:FsONVRAS9T7sI+LIUmWTfcYkHO4aIWwzhcaSAoJOfIk= github.com/golang/protobuf v1.5.3 h1:KhyjKVUg7Usr/dYsdSqoFveMYd5ko72D+zANwlG1mmg= github.com/golang/protobuf v1.5.3/go.mod h1:XVQd3VNwM+JqD3oG2Ue2ip4fOMUkwXdXDdiuN0vRsmY= diff --git a/baseapp/abci.go b/baseapp/abci.go index 09c22b6e3a3e..8dd1aaec0ba8 100644 --- a/baseapp/abci.go +++ b/baseapp/abci.go @@ -17,6 +17,7 @@ import ( grpcstatus "google.golang.org/grpc/status" errorsmod "cosmossdk.io/errors" + "cosmossdk.io/store/rootmulti" snapshottypes "cosmossdk.io/store/snapshots/types" storetypes "cosmossdk.io/store/types" @@ -47,13 +48,14 @@ func (app *BaseApp) InitChain(req abci.RequestInitChain) (res abci.ResponseInitC app.logger.Info("InitChain", "initialHeight", req.InitialHeight, "chainID", req.ChainId) - // If req.InitialHeight is > 1, then we set the initial version in the - // stores. + // Set the initial height, which will be used to determine if we are proposing + // or processing the first block or not. + app.initialHeight = req.InitialHeight + + // if req.InitialHeight is > 1, then we set the initial version on all stores if req.InitialHeight > 1 { - app.initialHeight = req.InitialHeight - initHeader = cmtproto.Header{ChainID: req.ChainId, Height: req.InitialHeight, Time: req.Time} - err := app.cms.SetInitialVersion(req.InitialHeight) - if err != nil { + initHeader.Height = req.InitialHeight + if err := app.cms.SetInitialVersion(req.InitialHeight); err != nil { panic(err) } } @@ -66,7 +68,7 @@ func (app *BaseApp) InitChain(req abci.RequestInitChain) (res abci.ResponseInitC // done after the deliver state and context have been set as it's persisted // to state. if req.ConsensusParams != nil { - err := app.StoreConsensusParams(app.deliverState.ctx, req.ConsensusParams) + err := app.StoreConsensusParams(app.deliverState.ctx, *req.ConsensusParams) if err != nil { panic(err) } @@ -238,9 +240,8 @@ func (app *BaseApp) EndBlock(req abci.RequestEndBlock) (res abci.ResponseEndBloc res.Events = sdk.MarkEventsToIndex(res.Events, app.indexEvents) } - if cp := app.GetConsensusParams(app.deliverState.ctx); cp != nil { - res.ConsensusParamUpdates = cp - } + cp := app.GetConsensusParams(app.deliverState.ctx) + res.ConsensusParamUpdates = &cp // call the streaming service hook with the EndBlock messages for _, abciListener := range app.streamingManager.ABCIListeners { @@ -456,6 +457,11 @@ func (app *BaseApp) Commit() abci.ResponseCommit { header := app.deliverState.ctx.BlockHeader() retainHeight := app.GetBlockRetentionHeight(header.Height) + rms, ok := app.cms.(*rootmulti.Store) + if ok { + rms.SetCommitHeader(header) + } + // Write the DeliverTx state into branched storage and commit the MultiStore. // The write to the DeliverTx state writes all state transitions to the root // MultiStore (app.cms) so when Commit() is called is persists those values. @@ -810,6 +816,16 @@ func (app *BaseApp) CreateQueryContext(height int64, prove bool) (sdk.Context, e WithMinGasPrices(app.minGasPrices). WithBlockHeight(height) + if height != lastBlockHeight { + rms, ok := app.cms.(*rootmulti.Store) + if ok { + cInfo, err := rms.GetCommitInfo(height) + if cInfo != nil && err == nil { + ctx = ctx.WithBlockTime(cInfo.Timestamp) + } + } + } + return ctx, nil } @@ -864,7 +880,7 @@ func (app *BaseApp) GetBlockRetentionHeight(commitHeight int64) int64 { // on the unbonding period and block commitment time as the two should be // equivalent. cp := app.GetConsensusParams(app.deliverState.ctx) - if cp != nil && cp.Evidence != nil && cp.Evidence.MaxAgeNumBlocks > 0 { + if cp.Evidence != nil && cp.Evidence.MaxAgeNumBlocks > 0 { retentionHeight = commitHeight - cp.Evidence.MaxAgeNumBlocks } @@ -1002,11 +1018,13 @@ func SplitABCIQueryPath(requestPath string) (path []string) { // ProcessProposal. We use deliverState on the first block to be able to access // any state changes made in InitChain. func (app *BaseApp) getContextForProposal(ctx sdk.Context, height int64) sdk.Context { - if height == 1 { + if height == app.initialHeight { ctx, _ = app.deliverState.ctx.CacheContext() + // clear all context data set during InitChain to avoid inconsistent behavior ctx = ctx.WithBlockHeader(cmtproto.Header{}) return ctx } + return ctx } diff --git a/baseapp/abci_test.go b/baseapp/abci_test.go index b4e4abca0247..cc762dad42c0 100644 --- a/baseapp/abci_test.go +++ b/baseapp/abci_test.go @@ -1407,6 +1407,7 @@ func TestABCI_Proposal_Read_State_PrepareProposal(t *testing.T) { suite := NewBaseAppSuite(t, setInitChainerOpt, prepareOpt) suite.baseApp.InitChain(abci.RequestInitChain{ + InitialHeight: 1, ConsensusParams: &cmtproto.ConsensusParams{}, }) diff --git a/baseapp/baseapp.go b/baseapp/baseapp.go index 1b3f627034a9..bf29ecc83f48 100644 --- a/baseapp/baseapp.go +++ b/baseapp/baseapp.go @@ -48,7 +48,7 @@ const ( var _ abci.Application = (*BaseApp)(nil) // BaseApp reflects the ABCI application implementation. -type BaseApp struct { //nolint: maligned +type BaseApp struct { // initialized on creation logger log.Logger name string // application name from abci.Info @@ -434,29 +434,25 @@ func (app *BaseApp) setState(mode runTxMode, header cmtproto.Header) { // GetConsensusParams returns the current consensus parameters from the BaseApp's // ParamStore. If the BaseApp has no ParamStore defined, nil is returned. -func (app *BaseApp) GetConsensusParams(ctx sdk.Context) *cmtproto.ConsensusParams { +func (app *BaseApp) GetConsensusParams(ctx sdk.Context) cmtproto.ConsensusParams { if app.paramStore == nil { - return nil + return cmtproto.ConsensusParams{} } cp, err := app.paramStore.Get(ctx) if err != nil { - panic(err) + panic(fmt.Errorf("consensus key is nil: %w", err)) } return cp } // StoreConsensusParams sets the consensus parameters to the baseapp's param store. -func (app *BaseApp) StoreConsensusParams(ctx sdk.Context, cp *cmtproto.ConsensusParams) error { +func (app *BaseApp) StoreConsensusParams(ctx sdk.Context, cp cmtproto.ConsensusParams) error { if app.paramStore == nil { panic("cannot store consensus params with no params store set") } - if cp == nil { - return nil - } - return app.paramStore.Set(ctx, cp) // We're explicitly not storing the CometBFT app_version in the param store. It's // stored instead in the x/upgrade store, with its own bump logic. @@ -474,7 +470,7 @@ func (app *BaseApp) AddRunTxRecoveryHandler(handlers ...RecoveryHandler) { // one. func (app *BaseApp) GetMaximumBlockGas(ctx sdk.Context) uint64 { cp := app.GetConsensusParams(ctx) - if cp == nil || cp.Block == nil { + if cp.Block == nil { return 0 } @@ -497,19 +493,21 @@ func (app *BaseApp) validateHeight(req abci.RequestBeginBlock) error { return fmt.Errorf("invalid height: %d", req.Header.Height) } - // expectedHeight holds the expected height to validate. + lastBlockHeight := app.LastBlockHeight() + + // expectedHeight holds the expected height to validate var expectedHeight int64 - if app.LastBlockHeight() == 0 && app.initialHeight > 1 { - // In this case, we're validating the first block of the chain (no - // previous commit). The height we're expecting is the initial height. + if lastBlockHeight == 0 && app.initialHeight > 1 { + // In this case, we're validating the first block of the chain, i.e no + // previous commit. The height we're expecting is the initial height. expectedHeight = app.initialHeight } else { // This case can mean two things: - // - either there was already a previous commit in the store, in which - // case we increment the version from there, - // - or there was no previous commit, and initial version was not set, - // in which case we start at version 1. - expectedHeight = app.LastBlockHeight() + 1 + // + // - Either there was already a previous commit in the store, in which + // case we increment the version from there. + // - Or there was no previous commit, in which case we start at version 1. + expectedHeight = lastBlockHeight + 1 } if req.Header.Height != expectedHeight { @@ -526,8 +524,12 @@ func validateBasicTxMsgs(msgs []sdk.Msg) error { } for _, msg := range msgs { - err := msg.ValidateBasic() - if err != nil { + m, ok := msg.(sdk.HasValidateBasic) + if !ok { + continue + } + + if err := m.ValidateBasic(); err != nil { return err } } @@ -865,7 +867,7 @@ func (app *BaseApp) PrepareProposalVerifyTx(tx sdk.Tx) ([]byte, error) { return nil, err } - _, _, _, _, err = app.runTx(runTxPrepareProposal, bz) //nolint:dogsled + _, _, _, _, err = app.runTx(runTxPrepareProposal, bz) if err != nil { return nil, err } @@ -884,7 +886,7 @@ func (app *BaseApp) ProcessProposalVerifyTx(txBz []byte) (sdk.Tx, error) { return nil, err } - _, _, _, _, err = app.runTx(runTxProcessProposal, txBz) //nolint:dogsled + _, _, _, _, err = app.runTx(runTxProcessProposal, txBz) if err != nil { return nil, err } diff --git a/baseapp/baseapp_test.go b/baseapp/baseapp_test.go index 47b06cf5ddf9..5b367c729bda 100644 --- a/baseapp/baseapp_test.go +++ b/baseapp/baseapp_test.go @@ -67,7 +67,7 @@ func NewBaseAppSuite(t *testing.T, opts ...func(*baseapp.BaseApp)) *BaseAppSuite app.SetInterfaceRegistry(cdc.InterfaceRegistry()) app.MsgServiceRouter().SetInterfaceRegistry(cdc.InterfaceRegistry()) app.MountStores(capKey1, capKey2) - app.SetParamStore(¶mStore{db: dbm.NewMemDB()}) + app.SetParamStore(paramStore{db: dbm.NewMemDB()}) app.SetTxDecoder(txConfig.TxDecoder()) app.SetTxEncoder(txConfig.TxEncoder()) @@ -587,16 +587,16 @@ func TestGetMaximumBlockGas(t *testing.T) { suite.baseApp.InitChain(abci.RequestInitChain{}) ctx := suite.baseApp.NewContext(true, cmtproto.Header{}) - suite.baseApp.StoreConsensusParams(ctx, &cmtproto.ConsensusParams{Block: &cmtproto.BlockParams{MaxGas: 0}}) + suite.baseApp.StoreConsensusParams(ctx, cmtproto.ConsensusParams{Block: &cmtproto.BlockParams{MaxGas: 0}}) require.Equal(t, uint64(0), suite.baseApp.GetMaximumBlockGas(ctx)) - suite.baseApp.StoreConsensusParams(ctx, &cmtproto.ConsensusParams{Block: &cmtproto.BlockParams{MaxGas: -1}}) + suite.baseApp.StoreConsensusParams(ctx, cmtproto.ConsensusParams{Block: &cmtproto.BlockParams{MaxGas: -1}}) require.Equal(t, uint64(0), suite.baseApp.GetMaximumBlockGas(ctx)) - suite.baseApp.StoreConsensusParams(ctx, &cmtproto.ConsensusParams{Block: &cmtproto.BlockParams{MaxGas: 5000000}}) + suite.baseApp.StoreConsensusParams(ctx, cmtproto.ConsensusParams{Block: &cmtproto.BlockParams{MaxGas: 5000000}}) require.Equal(t, uint64(5000000), suite.baseApp.GetMaximumBlockGas(ctx)) - suite.baseApp.StoreConsensusParams(ctx, &cmtproto.ConsensusParams{Block: &cmtproto.BlockParams{MaxGas: -5000000}}) + suite.baseApp.StoreConsensusParams(ctx, cmtproto.ConsensusParams{Block: &cmtproto.BlockParams{MaxGas: -5000000}}) require.Panics(t, func() { suite.baseApp.GetMaximumBlockGas(ctx) }) } diff --git a/baseapp/block_gas_test.go b/baseapp/block_gas_test.go index 86ec9664350e..105cb4f29066 100644 --- a/baseapp/block_gas_test.go +++ b/baseapp/block_gas_test.go @@ -5,15 +5,15 @@ import ( "math" "testing" - "cosmossdk.io/depinject" - "cosmossdk.io/log" - sdkmath "cosmossdk.io/math" abci "github.com/cometbft/cometbft/abci/types" cmtjson "github.com/cometbft/cometbft/libs/json" cmtproto "github.com/cometbft/cometbft/proto/tendermint/types" dbm "github.com/cosmos/cosmos-db" "github.com/stretchr/testify/require" + "cosmossdk.io/depinject" + "cosmossdk.io/log" + sdkmath "cosmossdk.io/math" store "cosmossdk.io/store/types" baseapptestutil "github.com/cosmos/cosmos-sdk/baseapp/testutil" @@ -173,7 +173,7 @@ func TestBaseApp_BlockGas(t *testing.T) { require.Equal(t, []byte("ok"), okValue) } // check block gas is always consumed - baseGas := uint64(51732) // baseGas is the gas consumed before tx msg + baseGas := uint64(50702) // baseGas is the gas consumed before tx msg expGasConsumed := addUint64Saturating(tc.gasToConsume, baseGas) if expGasConsumed > txtypes.MaxGasWanted { // capped by gasLimit @@ -190,7 +190,11 @@ func TestBaseApp_BlockGas(t *testing.T) { } } -func createTestTx(txConfig client.TxConfig, txBuilder client.TxBuilder, privs []cryptotypes.PrivKey, accNums []uint64, accSeqs []uint64, chainID string) (xauthsigning.Tx, []byte, error) { +func createTestTx(txConfig client.TxConfig, txBuilder client.TxBuilder, privs []cryptotypes.PrivKey, accNums, accSeqs []uint64, chainID string) (xauthsigning.Tx, []byte, error) { + defaultSignMode, err := xauthsigning.APISignModeToInternal(txConfig.SignModeHandler().DefaultMode()) + if err != nil { + return nil, nil, err + } // First round: we gather all the signer infos. We use the "set empty // signature" hack to do that. var sigsV2 []signing.SignatureV2 @@ -198,7 +202,7 @@ func createTestTx(txConfig client.TxConfig, txBuilder client.TxBuilder, privs [] sigV2 := signing.SignatureV2{ PubKey: priv.PubKey(), Data: &signing.SingleSignatureData{ - SignMode: txConfig.SignModeHandler().DefaultMode(), + SignMode: defaultSignMode, Signature: nil, }, Sequence: accSeqs[i], @@ -206,7 +210,7 @@ func createTestTx(txConfig client.TxConfig, txBuilder client.TxBuilder, privs [] sigsV2 = append(sigsV2, sigV2) } - err := txBuilder.SetSignatures(sigsV2...) + err = txBuilder.SetSignatures(sigsV2...) if err != nil { return nil, nil, err } @@ -219,9 +223,10 @@ func createTestTx(txConfig client.TxConfig, txBuilder client.TxBuilder, privs [] ChainID: chainID, AccountNumber: accNums[i], Sequence: accSeqs[i], + PubKey: priv.PubKey(), } sigV2, err := tx.SignWithPrivKey( - nil, txConfig.SignModeHandler().DefaultMode(), signerData, //nolint:staticcheck + context.TODO(), defaultSignMode, signerData, txBuilder, priv, txConfig, accSeqs[i]) if err != nil { return nil, nil, err diff --git a/baseapp/msg_service_router.go b/baseapp/msg_service_router.go index ed08986d47e7..6a782b8b01c1 100644 --- a/baseapp/msg_service_router.go +++ b/baseapp/msg_service_router.go @@ -115,16 +115,19 @@ func (msr *MsgServiceRouter) RegisterService(sd *grpc.ServiceDesc, handler inter ) } - msr.routes[requestTypeName] = func(ctx sdk.Context, req sdk.Msg) (*sdk.Result, error) { + msr.routes[requestTypeName] = func(ctx sdk.Context, msg sdk.Msg) (*sdk.Result, error) { ctx = ctx.WithEventManager(sdk.NewEventManager()) interceptor := func(goCtx context.Context, _ interface{}, _ *grpc.UnaryServerInfo, handler grpc.UnaryHandler) (interface{}, error) { goCtx = context.WithValue(goCtx, sdk.SdkContextKey, ctx) - return handler(goCtx, req) + return handler(goCtx, msg) } - if err := req.ValidateBasic(); err != nil { - return nil, err + if m, ok := msg.(sdk.HasValidateBasic); ok { + if err := m.ValidateBasic(); err != nil { + return nil, err + } } + // Call the method handler from the service description with the handler object. // We don't do any decoding here because the decoding was already done. res, err := methodHandler(handler, ctx, noopDecoder, interceptor) diff --git a/baseapp/msg_service_router_test.go b/baseapp/msg_service_router_test.go index 16f780e078f0..3d0b637462cd 100644 --- a/baseapp/msg_service_router_test.go +++ b/baseapp/msg_service_router_test.go @@ -1,6 +1,7 @@ package baseapp_test import ( + "context" "testing" abci "github.com/cometbft/cometbft/abci/types" @@ -94,6 +95,9 @@ func TestMsgService(t *testing.T) { // set the TxDecoder in the BaseApp for minimal tx simulations app.SetTxDecoder(txConfig.TxDecoder()) + defaultSignMode, err := authsigning.APISignModeToInternal(txConfig.SignModeHandler().DefaultMode()) + require.NoError(t, err) + testdata.RegisterInterfaces(interfaceRegistry) testdata.RegisterMsgServer( app.MsgServiceRouter(), @@ -114,7 +118,7 @@ func TestMsgService(t *testing.T) { sigV2 := signing.SignatureV2{ PubKey: priv.PubKey(), Data: &signing.SingleSignatureData{ - SignMode: txConfig.SignModeHandler().DefaultMode(), + SignMode: defaultSignMode, Signature: nil, }, Sequence: 0, @@ -128,9 +132,10 @@ func TestMsgService(t *testing.T) { ChainID: "test", AccountNumber: 0, Sequence: 0, + PubKey: priv.PubKey(), } sigV2, err = tx.SignWithPrivKey( - nil, txConfig.SignModeHandler().DefaultMode(), signerData, //nolint:staticcheck // SA1019: txConfig.SignModeHandler().DefaultMode() is deprecated: use txConfig.SignModeHandler().DefaultMode() instead. + context.TODO(), defaultSignMode, signerData, txBuilder, priv, txConfig, 0) require.NoError(t, err) err = txBuilder.SetSignatures(sigV2) diff --git a/baseapp/params.go b/baseapp/params.go index 35628f5870dc..329ec1255b6f 100644 --- a/baseapp/params.go +++ b/baseapp/params.go @@ -9,7 +9,7 @@ import ( // ParamStore defines the interface the parameter store used by the BaseApp must // fulfill. type ParamStore interface { - Get(ctx context.Context) (*cmtproto.ConsensusParams, error) + Get(ctx context.Context) (cmtproto.ConsensusParams, error) Has(ctx context.Context) (bool, error) - Set(ctx context.Context, cp *cmtproto.ConsensusParams) error + Set(ctx context.Context, cp cmtproto.ConsensusParams) error } diff --git a/baseapp/params_legacy.go b/baseapp/params_legacy.go index c8770cc6c091..13fd34add70e 100644 --- a/baseapp/params_legacy.go +++ b/baseapp/params_legacy.go @@ -138,10 +138,13 @@ func GetConsensusParams(ctx sdk.Context, paramStore LegacyParamStore) *cmtproto. return cp } -func MigrateParams(ctx sdk.Context, lps LegacyParamStore, ps ParamStore) { +func MigrateParams(ctx sdk.Context, lps LegacyParamStore, ps ParamStore) error { if cp := GetConsensusParams(ctx, lps); cp != nil { - ps.Set(ctx, cp) + if err := ps.Set(ctx, *cp); err != nil { + return err + } } else { ctx.Logger().Info("warning: consensus parameters are undefined; skipping migration") } + return nil } diff --git a/baseapp/testutil/messages.pb.go b/baseapp/testutil/messages.pb.go index 6ab32a7ce418..533a75289217 100644 --- a/baseapp/testutil/messages.pb.go +++ b/baseapp/testutil/messages.pb.go @@ -7,6 +7,7 @@ import ( context "context" fmt "fmt" _ "github.com/cosmos/cosmos-sdk/codec/types" + _ "github.com/cosmos/cosmos-sdk/types/msgservice" _ "github.com/cosmos/gogoproto/gogoproto" grpc1 "github.com/cosmos/gogoproto/grpc" proto "github.com/cosmos/gogoproto/proto" @@ -276,30 +277,32 @@ func init() { func init() { proto.RegisterFile("messages.proto", fileDescriptor_4dc296cbfe5ffcd5) } var fileDescriptor_4dc296cbfe5ffcd5 = []byte{ - // 364 bytes of a gzipped FileDescriptorProto - 0x1f, 0x8b, 0x08, 0x00, 0x00, 0x00, 0x00, 0x00, 0x02, 0xff, 0xac, 0x92, 0x4f, 0x6b, 0xe2, 0x50, - 0x14, 0xc5, 0xcd, 0x84, 0x51, 0xe7, 0xea, 0xcc, 0x48, 0x90, 0x21, 0x66, 0x20, 0x48, 0x16, 0x83, - 0x1b, 0x13, 0xc8, 0xec, 0xc6, 0xdd, 0x0c, 0x83, 0x2d, 0xc5, 0x0a, 0x29, 0x74, 0xd1, 0x8d, 0xbc, - 0xc4, 0xeb, 0x33, 0x98, 0xbc, 0x17, 0xf2, 0x5e, 0x0a, 0x7e, 0x8b, 0x7e, 0xac, 0x2e, 0x5d, 0x76, - 0x59, 0xf4, 0x8b, 0x94, 0xfc, 0xd3, 0x2e, 0x6a, 0x57, 0x5d, 0xe5, 0x9c, 0x73, 0xc9, 0xef, 0xe4, - 0x5e, 0x02, 0xdf, 0x62, 0x14, 0x82, 0x50, 0x14, 0x76, 0x92, 0x72, 0xc9, 0x8d, 0x3e, 0xe5, 0x94, - 0x17, 0xd2, 0xc9, 0x55, 0x95, 0x0e, 0x28, 0xe7, 0x34, 0x42, 0xa7, 0x70, 0x7e, 0xb6, 0x72, 0x08, - 0xdb, 0x96, 0x23, 0xeb, 0x1a, 0x60, 0x26, 0xe8, 0x3f, 0x9e, 0x31, 0x89, 0xa9, 0xa6, 0x43, 0x2b, - 0x28, 0xa5, 0xae, 0x0c, 0x95, 0x91, 0xea, 0xd5, 0x56, 0xfb, 0x05, 0xdf, 0x57, 0x24, 0x8c, 0x16, - 0x9c, 0x2d, 0xd6, 0x84, 0x2d, 0x23, 0x4c, 0xf5, 0x4f, 0x43, 0x65, 0xd4, 0xf6, 0xbe, 0xe6, 0xf1, - 0x9c, 0x5d, 0x94, 0xa1, 0x35, 0x87, 0xce, 0x89, 0xe7, 0x7e, 0x00, 0xd0, 0x00, 0x3d, 0x07, 0xa6, - 0x48, 0x24, 0x56, 0x58, 0x0f, 0x45, 0xc2, 0x99, 0x40, 0x6b, 0x56, 0x94, 0x5d, 0xe1, 0xf6, 0x96, - 0x44, 0x19, 0x6a, 0x3d, 0x50, 0x37, 0xb8, 0x2d, 0x8a, 0xba, 0x5e, 0x2e, 0xb5, 0x3e, 0x7c, 0xbe, - 0xcf, 0x47, 0x05, 0xba, 0xeb, 0x95, 0x46, 0xfb, 0x01, 0x4d, 0x11, 0x52, 0x86, 0xa9, 0xae, 0x0e, - 0x95, 0xd1, 0x17, 0xaf, 0x72, 0xd6, 0x4f, 0x18, 0x1c, 0xab, 0x6a, 0x68, 0xdd, 0xe5, 0xfe, 0x87, - 0x56, 0x7d, 0xa5, 0x3f, 0xd0, 0xbb, 0x64, 0x41, 0x8a, 0x31, 0x32, 0x59, 0x67, 0x1d, 0xfb, 0xb4, - 0xb6, 0x31, 0xb0, 0xcf, 0x7d, 0xb2, 0x3b, 0x85, 0xf6, 0xf1, 0x38, 0x93, 0x37, 0x38, 0xdd, 0x57, - 0x1c, 0xf7, 0x3d, 0xd0, 0x04, 0xda, 0xc7, 0xc5, 0x1d, 0x50, 0x6f, 0x50, 0x96, 0xef, 0xd6, 0xa1, - 0x61, 0xd8, 0x67, 0x97, 0xf9, 0x3b, 0x7d, 0xdc, 0x9b, 0xca, 0x6e, 0x6f, 0x2a, 0xcf, 0x7b, 0x53, - 0x79, 0x38, 0x98, 0x8d, 0xdd, 0xc1, 0x6c, 0x3c, 0x1d, 0xcc, 0xc6, 0xdd, 0x98, 0x86, 0x72, 0x9d, - 0xf9, 0x76, 0xc0, 0x63, 0x27, 0xe0, 0x22, 0xe6, 0xa2, 0x7a, 0x8c, 0xc5, 0x72, 0xe3, 0xf8, 0x44, - 0x20, 0x49, 0x12, 0x47, 0xa2, 0x90, 0x99, 0x0c, 0x23, 0xbf, 0x59, 0xfc, 0x45, 0xbf, 0x5f, 0x02, - 0x00, 0x00, 0xff, 0xff, 0x23, 0xdc, 0x12, 0x4d, 0x88, 0x02, 0x00, 0x00, + // 387 bytes of a gzipped FileDescriptorProto + 0x1f, 0x8b, 0x08, 0x00, 0x00, 0x00, 0x00, 0x00, 0x02, 0xff, 0xac, 0x92, 0xcf, 0xca, 0xd3, 0x40, + 0x14, 0xc5, 0x1b, 0x83, 0xdf, 0x57, 0x6f, 0xab, 0x96, 0x50, 0x34, 0x8d, 0x10, 0x4a, 0x16, 0x52, + 0x84, 0x66, 0x30, 0xee, 0xda, 0x9d, 0x22, 0x55, 0x44, 0x0b, 0x11, 0x5c, 0x74, 0x53, 0x26, 0xe9, + 0xed, 0x34, 0x34, 0x99, 0x09, 0x99, 0x49, 0xa1, 0x5b, 0x9f, 0xc0, 0x47, 0xf1, 0x31, 0x5c, 0x76, + 0xe9, 0x52, 0xda, 0x85, 0xaf, 0x21, 0xf9, 0xd7, 0xba, 0xb0, 0xae, 0xbe, 0xd5, 0xdc, 0x73, 0x2e, + 0xf9, 0x9d, 0xcc, 0x61, 0xe0, 0x51, 0x82, 0x52, 0x52, 0x86, 0xd2, 0x4d, 0x33, 0xa1, 0x84, 0xf5, + 0x34, 0x14, 0x32, 0x11, 0x92, 0x24, 0x92, 0x91, 0xdd, 0xcb, 0xe2, 0xa8, 0x17, 0x7d, 0x26, 0x98, + 0x28, 0x47, 0x52, 0x4c, 0xb5, 0x3b, 0x60, 0x42, 0xb0, 0x18, 0x49, 0xa9, 0x82, 0x7c, 0x4d, 0x28, + 0xdf, 0x57, 0x2b, 0xe7, 0x13, 0xc0, 0x47, 0xc9, 0xde, 0x88, 0x9c, 0x2b, 0xcc, 0x0c, 0x13, 0x6e, + 0xc3, 0x6a, 0x34, 0xb5, 0xa1, 0x36, 0xd2, 0xfd, 0x46, 0x1a, 0xcf, 0xe1, 0xf1, 0x9a, 0x46, 0xf1, + 0x52, 0xf0, 0xe5, 0x86, 0xf2, 0x55, 0x8c, 0x99, 0x79, 0x6f, 0xa8, 0x8d, 0xda, 0xfe, 0xc3, 0xc2, + 0x9e, 0xf3, 0x77, 0x95, 0xe9, 0xcc, 0xa1, 0x73, 0xe1, 0x79, 0x77, 0x00, 0xb4, 0xc0, 0x2c, 0x80, + 0x19, 0x52, 0x85, 0x35, 0xd6, 0x47, 0x99, 0x0a, 0x2e, 0xd1, 0x59, 0x94, 0x61, 0x1f, 0x70, 0xff, + 0x85, 0xc6, 0x39, 0x1a, 0x3d, 0xd0, 0xb7, 0xb8, 0x2f, 0x83, 0xba, 0x7e, 0x31, 0x1a, 0x7d, 0xb8, + 0xbf, 0x2b, 0x56, 0x25, 0xba, 0xeb, 0x57, 0xc2, 0x78, 0x02, 0x37, 0x32, 0x62, 0x1c, 0x33, 0x53, + 0x1f, 0x6a, 0xa3, 0x07, 0x7e, 0xad, 0x26, 0x9d, 0xaf, 0xbf, 0xbf, 0xbf, 0xa8, 0x85, 0xf3, 0x0c, + 0x06, 0xe7, 0xdc, 0x26, 0xa1, 0x09, 0xf6, 0xde, 0xc2, 0x6d, 0x53, 0xd9, 0x04, 0x7a, 0xef, 0x79, + 0x98, 0x61, 0x82, 0x5c, 0x35, 0x5e, 0xc7, 0xbd, 0x74, 0x60, 0x0d, 0xdc, 0x6b, 0xff, 0xef, 0xcd, + 0xa0, 0x7d, 0x6e, 0x6a, 0xfa, 0x0f, 0x4e, 0xf7, 0x2f, 0x8e, 0xf7, 0x3f, 0xd0, 0x14, 0xda, 0xe7, + 0x16, 0x08, 0xe8, 0x9f, 0x51, 0x55, 0xdf, 0x36, 0xa6, 0x65, 0xb9, 0x57, 0x2f, 0xf3, 0x7a, 0xf6, + 0xe3, 0x68, 0x6b, 0x87, 0xa3, 0xad, 0xfd, 0x3a, 0xda, 0xda, 0xb7, 0x93, 0xdd, 0x3a, 0x9c, 0xec, + 0xd6, 0xcf, 0x93, 0xdd, 0x5a, 0x8c, 0x59, 0xa4, 0x36, 0x79, 0xe0, 0x86, 0x22, 0x21, 0xf5, 0x8b, + 0xab, 0x8e, 0xb1, 0x5c, 0x6d, 0x49, 0x40, 0x25, 0xd2, 0x34, 0x25, 0x0a, 0xa5, 0xca, 0x55, 0x14, + 0x07, 0x37, 0xe5, 0x93, 0x7a, 0xf5, 0x27, 0x00, 0x00, 0xff, 0xff, 0xea, 0x9d, 0x1c, 0xeb, 0xae, + 0x02, 0x00, 0x00, } // Reference imports to suppress errors if they are not otherwise used. diff --git a/baseapp/testutil/messages.proto b/baseapp/testutil/messages.proto index 6a04a94e5c2b..f5e1fb4b5684 100644 --- a/baseapp/testutil/messages.proto +++ b/baseapp/testutil/messages.proto @@ -1,5 +1,6 @@ syntax = "proto3"; +import "cosmos/msg/v1/msg.proto"; import "gogoproto/gogo.proto"; import "google/protobuf/any.proto"; @@ -18,6 +19,8 @@ message MsgCounter2 { message MsgCreateCounterResponse {} message MsgKeyValue { + option (cosmos.msg.v1.signer) = "signer"; + bytes key = 1; bytes value = 2; string signer = 3; diff --git a/baseapp/utils_test.go b/baseapp/utils_test.go index 385184af5e77..cbdee8a0c347 100644 --- a/baseapp/utils_test.go +++ b/baseapp/utils_test.go @@ -241,7 +241,7 @@ type paramStore struct { var _ baseapp.ParamStore = (*paramStore)(nil) -func (ps *paramStore) Set(_ context.Context, value *cmtproto.ConsensusParams) error { +func (ps paramStore) Set(_ context.Context, value cmtproto.ConsensusParams) error { bz, err := json.Marshal(value) if err != nil { return err @@ -250,26 +250,26 @@ func (ps *paramStore) Set(_ context.Context, value *cmtproto.ConsensusParams) er return ps.db.Set(ParamStoreKey, bz) } -func (ps *paramStore) Has(_ context.Context) (bool, error) { +func (ps paramStore) Has(_ context.Context) (bool, error) { return ps.db.Has(ParamStoreKey) } -func (ps paramStore) Get(ctx context.Context) (*cmtproto.ConsensusParams, error) { +func (ps paramStore) Get(_ context.Context) (cmtproto.ConsensusParams, error) { bz, err := ps.db.Get(ParamStoreKey) if err != nil { - return nil, err + return cmtproto.ConsensusParams{}, err } if len(bz) == 0 { - return nil, errors.New("params not found") + return cmtproto.ConsensusParams{}, errors.New("params not found") } var params cmtproto.ConsensusParams if err := json.Unmarshal(bz, ¶ms); err != nil { - return nil, err + return cmtproto.ConsensusParams{}, err } - return ¶ms, nil + return params, nil } func setTxSignature(t *testing.T, builder client.TxBuilder, nonce uint64) { diff --git a/client/account_retriever.go b/client/account_retriever.go index 24de5423e2ea..c1f2a060a87f 100644 --- a/client/account_retriever.go +++ b/client/account_retriever.go @@ -20,7 +20,7 @@ type AccountRetriever interface { GetAccount(clientCtx Context, addr sdk.AccAddress) (Account, error) GetAccountWithHeight(clientCtx Context, addr sdk.AccAddress) (Account, int64, error) EnsureExists(clientCtx Context, addr sdk.AccAddress) error - GetAccountNumberSequence(clientCtx Context, addr sdk.AccAddress) (accNum uint64, accSeq uint64, err error) + GetAccountNumberSequence(clientCtx Context, addr sdk.AccAddress) (accNum, accSeq uint64, err error) } var _ AccountRetriever = (*MockAccountRetriever)(nil) diff --git a/client/broadcast.go b/client/broadcast.go index cfc2e9a7689b..5598cbcebaa1 100644 --- a/client/broadcast.go +++ b/client/broadcast.go @@ -117,7 +117,7 @@ func (ctx Context) BroadcastTxAsync(txBytes []byte) (*sdk.TxResponse, error) { // TxServiceBroadcast is a helper function to broadcast a Tx with the correct gRPC types // from the tx service. Calls `clientCtx.BroadcastTx` under the hood. -func TxServiceBroadcast(grpcCtx context.Context, clientCtx Context, req *tx.BroadcastTxRequest) (*tx.BroadcastTxResponse, error) { +func TxServiceBroadcast(_ context.Context, clientCtx Context, req *tx.BroadcastTxRequest) (*tx.BroadcastTxResponse, error) { if req == nil || req.TxBytes == nil { return nil, status.Error(codes.InvalidArgument, "invalid empty tx") } diff --git a/client/broadcast_test.go b/client/broadcast_test.go index 83970e54854a..fcd7d1d604ac 100644 --- a/client/broadcast_test.go +++ b/client/broadcast_test.go @@ -21,11 +21,11 @@ type MockClient struct { err error } -func (c MockClient) BroadcastTxAsync(ctx context.Context, tx cmttypes.Tx) (*coretypes.ResultBroadcastTx, error) { +func (c MockClient) BroadcastTxAsync(_ context.Context, _ cmttypes.Tx) (*coretypes.ResultBroadcastTx, error) { return nil, c.err } -func (c MockClient) BroadcastTxSync(ctx context.Context, tx cmttypes.Tx) (*coretypes.ResultBroadcastTx, error) { +func (c MockClient) BroadcastTxSync(_ context.Context, _ cmttypes.Tx) (*coretypes.ResultBroadcastTx, error) { return nil, c.err } diff --git a/client/cmd.go b/client/cmd.go index 2822512fd5eb..83b46028960b 100644 --- a/client/cmd.go +++ b/client/cmd.go @@ -6,7 +6,6 @@ import ( "strings" "github.com/cockroachdb/errors" - "github.com/cometbft/cometbft/libs/cli" "github.com/spf13/cobra" "github.com/spf13/pflag" "google.golang.org/grpc" @@ -92,8 +91,8 @@ func ValidateCmd(cmd *cobra.Command, args []string) error { // - client.Context field pre-populated & flag not set: uses pre-populated value // - client.Context field pre-populated & flag set: uses set flag value func ReadPersistentCommandFlags(clientCtx Context, flagSet *pflag.FlagSet) (Context, error) { - if clientCtx.OutputFormat == "" || flagSet.Changed(cli.OutputFlag) { - output, _ := flagSet.GetString(cli.OutputFlag) + if clientCtx.OutputFormat == "" || flagSet.Changed(flags.FlagOutput) { + output, _ := flagSet.GetString(flags.FlagOutput) clientCtx = clientCtx.WithOutputFormat(output) } @@ -305,8 +304,8 @@ func readTxCommandFlags(clientCtx Context, flagSet *pflag.FlagSet) (Context, err if isAux { // If the user didn't explicitly set an --output flag, use JSON by // default. - if clientCtx.OutputFormat == "" || !flagSet.Changed(cli.OutputFlag) { - clientCtx = clientCtx.WithOutputFormat("json") + if clientCtx.OutputFormat == "" || !flagSet.Changed(flags.FlagOutput) { + clientCtx = clientCtx.WithOutputFormat(flags.OutputFormatJSON) } // If the user didn't explicitly set a --sign-mode flag, use diff --git a/client/config/config_test.go b/client/config/config_test.go index 64e28ccc3d76..c5630f22a378 100644 --- a/client/config/config_test.go +++ b/client/config/config_test.go @@ -24,12 +24,12 @@ const ( // initClientContext initiates client Context for tests func initClientContext(t *testing.T, envVar string) (client.Context, func()) { home := t.TempDir() - chainId := "test-chain" //nolint:revive + chainID := "test-chain" clientCtx := client.Context{}. WithHomeDir(home). WithViper(""). WithCodec(codec.NewProtoCodec(codectypes.NewInterfaceRegistry())). - WithChainID(chainId) + WithChainID(chainID) require.NoError(t, clientCtx.Viper.BindEnv(nodeEnv)) if envVar != "" { @@ -38,7 +38,7 @@ func initClientContext(t *testing.T, envVar string) (client.Context, func()) { clientCtx, err := config.ReadFromClientConfig(clientCtx) require.NoError(t, err) - require.Equal(t, clientCtx.ChainID, chainId) + require.Equal(t, clientCtx.ChainID, chainID) return clientCtx, func() { _ = os.RemoveAll(home) } } diff --git a/client/context_test.go b/client/context_test.go index bc531042188a..9ea673b64f91 100644 --- a/client/context_test.go +++ b/client/context_test.go @@ -32,10 +32,10 @@ func TestContext_PrintProto(t *testing.T) { Size_: "big", Name: "Spot", } - any, err := types.NewAnyWithValue(animal) + anyAnimal, err := types.NewAnyWithValue(animal) require.NoError(t, err) hasAnimal := &testdata.HasAnimal{ - Animal: any, + Animal: anyAnimal, X: 10, } @@ -46,7 +46,7 @@ func TestContext_PrintProto(t *testing.T) { // json buf := &bytes.Buffer{} ctx = ctx.WithOutput(buf) - ctx.OutputFormat = "json" //nolint:goconst + ctx.OutputFormat = flags.OutputFormatJSON err = ctx.PrintProto(hasAnimal) require.NoError(t, err) require.Equal(t, @@ -56,7 +56,7 @@ func TestContext_PrintProto(t *testing.T) { // yaml buf = &bytes.Buffer{} ctx = ctx.WithOutput(buf) - ctx.OutputFormat = "text" //nolint:goconst + ctx.OutputFormat = flags.OutputFormatText err = ctx.PrintProto(hasAnimal) require.NoError(t, err) require.Equal(t, @@ -75,10 +75,10 @@ func TestContext_PrintObjectLegacy(t *testing.T) { Size_: "big", Name: "Spot", } - any, err := types.NewAnyWithValue(animal) + anyAnimal, err := types.NewAnyWithValue(animal) require.NoError(t, err) hasAnimal := &testdata.HasAnimal{ - Animal: any, + Animal: anyAnimal, X: 10, } @@ -89,7 +89,7 @@ func TestContext_PrintObjectLegacy(t *testing.T) { // json buf := &bytes.Buffer{} ctx = ctx.WithOutput(buf) - ctx.OutputFormat = "json" + ctx.OutputFormat = flags.OutputFormatJSON err = ctx.PrintObjectLegacy(hasAnimal) require.NoError(t, err) require.Equal(t, @@ -99,7 +99,7 @@ func TestContext_PrintObjectLegacy(t *testing.T) { // yaml buf = &bytes.Buffer{} ctx = ctx.WithOutput(buf) - ctx.OutputFormat = "text" + ctx.OutputFormat = flags.OutputFormatText err = ctx.PrintObjectLegacy(hasAnimal) require.NoError(t, err) require.Equal(t, @@ -121,7 +121,7 @@ func TestContext_PrintRaw(t *testing.T) { // json buf := &bytes.Buffer{} ctx = ctx.WithOutput(buf) - ctx.OutputFormat = "json" + ctx.OutputFormat = flags.OutputFormatJSON err := ctx.PrintRaw(hasAnimal) require.NoError(t, err) require.Equal(t, @@ -131,7 +131,7 @@ func TestContext_PrintRaw(t *testing.T) { // yaml buf = &bytes.Buffer{} ctx = ctx.WithOutput(buf) - ctx.OutputFormat = "text" + ctx.OutputFormat = flags.OutputFormatText err = ctx.PrintRaw(hasAnimal) require.NoError(t, err) require.Equal(t, diff --git a/client/debug/main.go b/client/debug/main.go index f5a033c5279a..17dd0ba2a19f 100644 --- a/client/debug/main.go +++ b/client/debug/main.go @@ -90,7 +90,7 @@ func bytesToPubkey(bz []byte, keytype string) (cryptotypes.PubKey, bool) { // getPubKeyFromRawString returns a PubKey (PubKeyEd25519 or PubKeySecp256k1) by attempting // to decode the pubkey string from hex, base64, and finally bech32. If all // encodings fail, an error is returned. -func getPubKeyFromRawString(pkstr string, keytype string) (cryptotypes.PubKey, error) { +func getPubKeyFromRawString(pkstr, keytype string) (cryptotypes.PubKey, error) { // Try hex decoding bz, err := hex.DecodeString(pkstr) if err == nil { diff --git a/client/flags/flags.go b/client/flags/flags.go index c06aad1e6b07..a2d918edde9a 100644 --- a/client/flags/flags.go +++ b/client/flags/flags.go @@ -4,7 +4,6 @@ import ( "fmt" "strconv" - cmtcli "github.com/cometbft/cometbft/libs/cli" "github.com/spf13/cobra" "github.com/spf13/pflag" @@ -45,7 +44,7 @@ const ( // List of CLI flags const ( - FlagHome = cmtcli.HomeFlag + FlagHome = "home" FlagKeyringDir = "keyring-dir" FlagUseLedger = "ledger" FlagChainID = "chain-id" @@ -86,13 +85,18 @@ const ( FlagInitHeight = "initial-height" // FlagOutput is the flag to set the output format. // This differs from FlagOutputDocument that is used to set the output file. - FlagOutput = cmtcli.OutputFlag - + FlagOutput = "output" // Logging flags FlagLogLevel = "log_level" FlagLogFormat = "log_format" ) +// List of supported output formats +const ( + OutputFormatJSON = "json" + OutputFormatText = "text" +) + // LineBreak can be included in a command list to provide a blank line // to help with readability var LineBreak = &cobra.Command{Run: func(*cobra.Command, []string) {}} @@ -113,7 +117,7 @@ func AddQueryFlagsToCmd(cmd *cobra.Command) { // AddTxFlagsToCmd adds common flags to a module tx command. func AddTxFlagsToCmd(cmd *cobra.Command) { f := cmd.Flags() - f.StringP(FlagOutput, "o", "json", "Output format (text|json)") + f.StringP(FlagOutput, "o", OutputFormatJSON, "Output format (text|json)") f.String(FlagFrom, "", "Name or address of private key with which to sign") f.Uint64P(FlagAccountNumber, "a", 0, "The account number of the signing account (offline mode only)") f.Uint64P(FlagSequence, "s", 0, "The sequence number of the signing account (offline mode only)") diff --git a/client/fuzz_test.go b/client/fuzz_test.go new file mode 100644 index 000000000000..a28a0b4d9c3a --- /dev/null +++ b/client/fuzz_test.go @@ -0,0 +1,60 @@ +package client_test + +import ( + "context" + "testing" + + "google.golang.org/grpc" + "google.golang.org/grpc/metadata" + + "github.com/cosmos/cosmos-sdk/testutil/testdata" + sdk "github.com/cosmos/cosmos-sdk/types" + "github.com/cosmos/cosmos-sdk/x/bank/types" +) + +type fuzzSuite struct { + IntegrationTestSuite +} + +func (fz *fuzzSuite) FuzzQueryBalance(f *testing.F) { + if testing.Short() { + f.Skip("In -short mode") + } + + // gRPC query to test service should work + testRes, err := fz.testClient.Echo(context.Background(), &testdata.EchoRequest{Message: "hello"}) + fz.Require().NoError(err) + fz.Require().Equal("hello", testRes.Message) + + // 1. Generate some seeds. + bz, err := fz.cdc.Marshal(&types.QueryBalanceRequest{ + Address: fz.genesisAccount.GetAddress().String(), + Denom: sdk.DefaultBondDenom, + }) + fz.Require().NoError(err) + f.Add(bz) + + // 2. Now fuzz it and ensure that we don't get any panics. + ctx := context.Background() + f.Fuzz(func(t *testing.T, in []byte) { + qbReq := new(types.QueryBalanceRequest) + if err := fz.cdc.Unmarshal(in, qbReq); err != nil { + return + } + + // gRPC query to bank service should work + var header metadata.MD + _, _ = fz.bankClient.Balance( + ctx, + qbReq, + grpc.Header(&header), + ) + }) +} + +func FuzzQueryBalance(f *testing.F) { + fzs := new(fuzzSuite) + fzs.SetT(new(testing.T)) + fzs.SetupSuite() + fzs.FuzzQueryBalance(f) +} diff --git a/client/grpc/cmtservice/service.go b/client/grpc/cmtservice/service.go index 82b23d75ebe8..9bf9bb4fb78f 100644 --- a/client/grpc/cmtservice/service.go +++ b/client/grpc/cmtservice/service.go @@ -183,7 +183,7 @@ func validatorsOutput(ctx context.Context, cctx client.Context, height *int64, p } // GetNodeInfo implements ServiceServer.GetNodeInfo -func (s queryServer) GetNodeInfo(ctx context.Context, req *GetNodeInfoRequest) (*GetNodeInfoResponse, error) { +func (s queryServer) GetNodeInfo(ctx context.Context, _ *GetNodeInfoRequest) (*GetNodeInfoResponse, error) { status, err := getNodeStatus(ctx, s.clientCtx) if err != nil { return nil, err @@ -218,7 +218,7 @@ func (s queryServer) GetNodeInfo(ctx context.Context, req *GetNodeInfoRequest) ( return &resp, nil } -func (s queryServer) ABCIQuery(ctx context.Context, req *ABCIQueryRequest) (*ABCIQueryResponse, error) { +func (s queryServer) ABCIQuery(_ context.Context, req *ABCIQueryRequest) (*ABCIQueryResponse, error) { if s.queryFn == nil { return nil, status.Error(codes.Internal, "ABCI Query handler undefined") } diff --git a/client/grpc/node/query.pb.go b/client/grpc/node/query.pb.go index e0c097fd8ef6..8e56808aa627 100644 --- a/client/grpc/node/query.pb.go +++ b/client/grpc/node/query.pb.go @@ -6,21 +6,26 @@ package node import ( context "context" fmt "fmt" + _ "github.com/cosmos/gogoproto/gogoproto" grpc1 "github.com/cosmos/gogoproto/grpc" proto "github.com/cosmos/gogoproto/proto" + github_com_cosmos_gogoproto_types "github.com/cosmos/gogoproto/types" _ "google.golang.org/genproto/googleapis/api/annotations" grpc "google.golang.org/grpc" codes "google.golang.org/grpc/codes" status "google.golang.org/grpc/status" + _ "google.golang.org/protobuf/types/known/timestamppb" io "io" math "math" math_bits "math/bits" + time "time" ) // Reference imports to suppress errors if they are not otherwise used. var _ = proto.Marshal var _ = fmt.Errorf var _ = math.Inf +var _ = time.Kitchen // This is a compile-time assertion to ensure that this generated file // is compatible with the proto package it is being compiled against. @@ -68,6 +73,9 @@ var xxx_messageInfo_ConfigRequest proto.InternalMessageInfo // ConfigResponse defines the response structure for the Config gRPC query. type ConfigResponse struct { MinimumGasPrice string `protobuf:"bytes,1,opt,name=minimum_gas_price,json=minimumGasPrice,proto3" json:"minimum_gas_price,omitempty"` + // pruning settings + PruningKeepRecent string `protobuf:"bytes,2,opt,name=pruning_keep_recent,json=pruningKeepRecent,proto3" json:"pruning_keep_recent,omitempty"` + PruningInterval string `protobuf:"bytes,3,opt,name=pruning_interval,json=pruningInterval,proto3" json:"pruning_interval,omitempty"` } func (m *ConfigResponse) Reset() { *m = ConfigResponse{} } @@ -110,9 +118,139 @@ func (m *ConfigResponse) GetMinimumGasPrice() string { return "" } +func (m *ConfigResponse) GetPruningKeepRecent() string { + if m != nil { + return m.PruningKeepRecent + } + return "" +} + +func (m *ConfigResponse) GetPruningInterval() string { + if m != nil { + return m.PruningInterval + } + return "" +} + +// StateRequest defines the request structure for the status of a node. +type StatusRequest struct { +} + +func (m *StatusRequest) Reset() { *m = StatusRequest{} } +func (m *StatusRequest) String() string { return proto.CompactTextString(m) } +func (*StatusRequest) ProtoMessage() {} +func (*StatusRequest) Descriptor() ([]byte, []int) { + return fileDescriptor_8324226a07064341, []int{2} +} +func (m *StatusRequest) XXX_Unmarshal(b []byte) error { + return m.Unmarshal(b) +} +func (m *StatusRequest) XXX_Marshal(b []byte, deterministic bool) ([]byte, error) { + if deterministic { + return xxx_messageInfo_StatusRequest.Marshal(b, m, deterministic) + } else { + b = b[:cap(b)] + n, err := m.MarshalToSizedBuffer(b) + if err != nil { + return nil, err + } + return b[:n], nil + } +} +func (m *StatusRequest) XXX_Merge(src proto.Message) { + xxx_messageInfo_StatusRequest.Merge(m, src) +} +func (m *StatusRequest) XXX_Size() int { + return m.Size() +} +func (m *StatusRequest) XXX_DiscardUnknown() { + xxx_messageInfo_StatusRequest.DiscardUnknown(m) +} + +var xxx_messageInfo_StatusRequest proto.InternalMessageInfo + +// StateResponse defines the response structure for the status of a node. +type StatusResponse struct { + EarliestStoreHeight uint64 `protobuf:"varint,1,opt,name=earliest_store_height,json=earliestStoreHeight,proto3" json:"earliest_store_height,omitempty"` + Height uint64 `protobuf:"varint,2,opt,name=height,proto3" json:"height,omitempty"` + Timestamp *time.Time `protobuf:"bytes,3,opt,name=timestamp,proto3,stdtime" json:"timestamp,omitempty"` + AppHash []byte `protobuf:"bytes,4,opt,name=app_hash,json=appHash,proto3" json:"app_hash,omitempty"` + ValidatorHash []byte `protobuf:"bytes,5,opt,name=validator_hash,json=validatorHash,proto3" json:"validator_hash,omitempty"` +} + +func (m *StatusResponse) Reset() { *m = StatusResponse{} } +func (m *StatusResponse) String() string { return proto.CompactTextString(m) } +func (*StatusResponse) ProtoMessage() {} +func (*StatusResponse) Descriptor() ([]byte, []int) { + return fileDescriptor_8324226a07064341, []int{3} +} +func (m *StatusResponse) XXX_Unmarshal(b []byte) error { + return m.Unmarshal(b) +} +func (m *StatusResponse) XXX_Marshal(b []byte, deterministic bool) ([]byte, error) { + if deterministic { + return xxx_messageInfo_StatusResponse.Marshal(b, m, deterministic) + } else { + b = b[:cap(b)] + n, err := m.MarshalToSizedBuffer(b) + if err != nil { + return nil, err + } + return b[:n], nil + } +} +func (m *StatusResponse) XXX_Merge(src proto.Message) { + xxx_messageInfo_StatusResponse.Merge(m, src) +} +func (m *StatusResponse) XXX_Size() int { + return m.Size() +} +func (m *StatusResponse) XXX_DiscardUnknown() { + xxx_messageInfo_StatusResponse.DiscardUnknown(m) +} + +var xxx_messageInfo_StatusResponse proto.InternalMessageInfo + +func (m *StatusResponse) GetEarliestStoreHeight() uint64 { + if m != nil { + return m.EarliestStoreHeight + } + return 0 +} + +func (m *StatusResponse) GetHeight() uint64 { + if m != nil { + return m.Height + } + return 0 +} + +func (m *StatusResponse) GetTimestamp() *time.Time { + if m != nil { + return m.Timestamp + } + return nil +} + +func (m *StatusResponse) GetAppHash() []byte { + if m != nil { + return m.AppHash + } + return nil +} + +func (m *StatusResponse) GetValidatorHash() []byte { + if m != nil { + return m.ValidatorHash + } + return nil +} + func init() { proto.RegisterType((*ConfigRequest)(nil), "cosmos.base.node.v1beta1.ConfigRequest") proto.RegisterType((*ConfigResponse)(nil), "cosmos.base.node.v1beta1.ConfigResponse") + proto.RegisterType((*StatusRequest)(nil), "cosmos.base.node.v1beta1.StatusRequest") + proto.RegisterType((*StatusResponse)(nil), "cosmos.base.node.v1beta1.StatusResponse") } func init() { @@ -120,25 +258,39 @@ func init() { } var fileDescriptor_8324226a07064341 = []byte{ - // 282 bytes of a gzipped FileDescriptorProto - 0x1f, 0x8b, 0x08, 0x00, 0x00, 0x00, 0x00, 0x00, 0x02, 0xff, 0x84, 0x90, 0xb1, 0x4b, 0xc3, 0x40, - 0x18, 0xc5, 0x73, 0x0e, 0x15, 0x0f, 0xb4, 0x98, 0xa9, 0x14, 0x39, 0x4a, 0x10, 0x0c, 0x42, 0xef, - 0xa8, 0xae, 0x4e, 0x3a, 0x74, 0x95, 0xba, 0xb9, 0x94, 0xcb, 0xf5, 0xf3, 0x3c, 0x6c, 0xee, 0x4b, - 0x73, 0x97, 0x82, 0xab, 0xe0, 0xae, 0xf8, 0x4f, 0x39, 0x16, 0x5c, 0x1c, 0x25, 0xf1, 0x0f, 0x91, - 0x24, 0xed, 0xe0, 0x50, 0x3a, 0x1d, 0xbc, 0xfb, 0xbd, 0xf7, 0x3d, 0x1e, 0x3d, 0x55, 0xe8, 0x52, - 0x74, 0x22, 0x91, 0x0e, 0x84, 0xc5, 0x19, 0x88, 0xe5, 0x28, 0x01, 0x2f, 0x47, 0x62, 0x51, 0x40, - 0xfe, 0xcc, 0xb3, 0x1c, 0x3d, 0x86, 0xbd, 0x96, 0xe2, 0x35, 0xc5, 0x6b, 0x8a, 0xaf, 0xa9, 0xfe, - 0x89, 0x46, 0xd4, 0x73, 0x10, 0x32, 0x33, 0x42, 0x5a, 0x8b, 0x5e, 0x7a, 0x83, 0xd6, 0xb5, 0xbe, - 0xa8, 0x4b, 0x0f, 0x6f, 0xd0, 0x3e, 0x18, 0x3d, 0x81, 0x45, 0x01, 0xce, 0x47, 0x57, 0xf4, 0x68, - 0x23, 0xb8, 0x0c, 0xad, 0x83, 0xf0, 0x9c, 0x1e, 0xa7, 0xc6, 0x9a, 0xb4, 0x48, 0xa7, 0x5a, 0xba, - 0x69, 0x96, 0x1b, 0x05, 0x3d, 0x32, 0x20, 0xf1, 0xc1, 0xa4, 0xbb, 0xfe, 0x18, 0x4b, 0x77, 0x5b, - 0xcb, 0x17, 0xef, 0x84, 0xee, 0xdf, 0x41, 0xbe, 0x34, 0x0a, 0xc2, 0x57, 0x42, 0x3b, 0x6d, 0x54, - 0x78, 0xc6, 0xb7, 0xd5, 0xe3, 0xff, 0xae, 0xf7, 0xe3, 0xdd, 0x60, 0xdb, 0x2a, 0x8a, 0x5f, 0xbe, - 0x7e, 0x3f, 0xf6, 0xa2, 0x70, 0x20, 0xb6, 0xee, 0xa3, 0x1a, 0xc7, 0xf5, 0xf8, 0xb3, 0x64, 0x64, - 0x55, 0x32, 0xf2, 0x53, 0x32, 0xf2, 0x56, 0xb1, 0x60, 0x55, 0xb1, 0xe0, 0xbb, 0x62, 0xc1, 0xfd, - 0x50, 0x1b, 0xff, 0x58, 0x24, 0x5c, 0x61, 0xba, 0x49, 0x69, 0x9f, 0xa1, 0x9b, 0x3d, 0x09, 0x35, - 0x37, 0x60, 0xbd, 0xd0, 0x79, 0xa6, 0x9a, 0xdc, 0xa4, 0xd3, 0x4c, 0x76, 0xf9, 0x17, 0x00, 0x00, - 0xff, 0xff, 0x7d, 0x46, 0xb4, 0x93, 0x92, 0x01, 0x00, 0x00, + // 506 bytes of a gzipped FileDescriptorProto + 0x1f, 0x8b, 0x08, 0x00, 0x00, 0x00, 0x00, 0x00, 0x02, 0xff, 0x8c, 0x92, 0xc1, 0x6f, 0xd3, 0x3e, + 0x1c, 0xc5, 0x9b, 0xfe, 0xfa, 0xeb, 0x98, 0x61, 0x1d, 0xcb, 0x00, 0x95, 0x0a, 0x65, 0x55, 0x05, + 0xa2, 0x20, 0xcd, 0xd6, 0xca, 0x9d, 0xc3, 0x38, 0x6c, 0x88, 0x0b, 0x4a, 0x39, 0x71, 0x89, 0xdc, + 0xf4, 0xbb, 0xc4, 0x5a, 0x62, 0x7b, 0xb6, 0x53, 0x89, 0x2b, 0x12, 0xf7, 0x49, 0x1c, 0x10, 0xff, + 0x11, 0xc7, 0x49, 0x5c, 0x38, 0x01, 0x6a, 0xf9, 0x43, 0x50, 0x6c, 0x67, 0xa8, 0x87, 0x0d, 0x4e, + 0xb1, 0xdf, 0xfb, 0xd8, 0x79, 0x7a, 0x5f, 0xa3, 0x87, 0xa9, 0xd0, 0xa5, 0xd0, 0x64, 0x46, 0x35, + 0x10, 0x2e, 0xe6, 0x40, 0x16, 0x07, 0x33, 0x30, 0xf4, 0x80, 0x9c, 0x55, 0xa0, 0xde, 0x61, 0xa9, + 0x84, 0x11, 0x61, 0xdf, 0x51, 0xb8, 0xa6, 0x70, 0x4d, 0x61, 0x4f, 0x0d, 0x1e, 0x64, 0x42, 0x64, + 0x05, 0x10, 0x2a, 0x19, 0xa1, 0x9c, 0x0b, 0x43, 0x0d, 0x13, 0x5c, 0xbb, 0x73, 0x83, 0x3d, 0xef, + 0xda, 0xdd, 0xac, 0x3a, 0x21, 0x86, 0x95, 0xa0, 0x0d, 0x2d, 0xa5, 0x07, 0xee, 0x64, 0x22, 0x13, + 0x76, 0x49, 0xea, 0x95, 0x53, 0x47, 0xdb, 0x68, 0xeb, 0x85, 0xe0, 0x27, 0x2c, 0x8b, 0xe1, 0xac, + 0x02, 0x6d, 0x46, 0x9f, 0x02, 0xd4, 0x6b, 0x14, 0x2d, 0x05, 0xd7, 0x10, 0x3e, 0x45, 0x3b, 0x25, + 0xe3, 0xac, 0xac, 0xca, 0x24, 0xa3, 0x3a, 0x91, 0x8a, 0xa5, 0xd0, 0x0f, 0x86, 0xc1, 0x78, 0x33, + 0xde, 0xf6, 0xc6, 0x11, 0xd5, 0xaf, 0x6b, 0x39, 0xc4, 0x68, 0x57, 0xaa, 0x8a, 0x33, 0x9e, 0x25, + 0xa7, 0x00, 0x32, 0x51, 0x90, 0x02, 0x37, 0xfd, 0xb6, 0xa5, 0x77, 0xbc, 0xf5, 0x0a, 0x40, 0xc6, + 0xd6, 0x08, 0x9f, 0xa0, 0xdb, 0x0d, 0xcf, 0xb8, 0x01, 0xb5, 0xa0, 0x45, 0xff, 0x3f, 0x77, 0xb5, + 0xd7, 0x5f, 0x7a, 0xb9, 0x8e, 0x3a, 0x35, 0xd4, 0x54, 0xba, 0x89, 0xfa, 0x3d, 0x40, 0xbd, 0x46, + 0xf1, 0x51, 0x27, 0xe8, 0x2e, 0x50, 0x55, 0x30, 0xd0, 0x26, 0xd1, 0x46, 0x28, 0x48, 0x72, 0x60, + 0x59, 0x6e, 0x6c, 0xdc, 0x4e, 0xbc, 0xdb, 0x98, 0xd3, 0xda, 0x3b, 0xb6, 0x56, 0x78, 0x0f, 0x75, + 0x3d, 0xd4, 0xb6, 0x90, 0xdf, 0x85, 0xcf, 0xd1, 0xe6, 0x65, 0x87, 0x36, 0xd3, 0xcd, 0xc9, 0x00, + 0xbb, 0x96, 0x71, 0xd3, 0x32, 0x7e, 0xd3, 0x10, 0x87, 0x9d, 0xf3, 0x1f, 0x7b, 0x41, 0xfc, 0xe7, + 0x48, 0x78, 0x1f, 0xdd, 0xa0, 0x52, 0x26, 0x39, 0xd5, 0x79, 0xbf, 0x33, 0x0c, 0xc6, 0xb7, 0xe2, + 0x0d, 0x2a, 0xe5, 0x31, 0xd5, 0x79, 0xf8, 0x08, 0xf5, 0x16, 0xb4, 0x60, 0x73, 0x6a, 0x84, 0x72, + 0xc0, 0xff, 0x16, 0xd8, 0xba, 0x54, 0x6b, 0x6c, 0xf2, 0xb9, 0x8d, 0x36, 0xa6, 0xa0, 0x16, 0x75, + 0xb1, 0x1f, 0x02, 0xd4, 0x75, 0x73, 0x09, 0x1f, 0xe3, 0xab, 0xde, 0x08, 0x5e, 0x9b, 0xe5, 0x60, + 0xfc, 0x77, 0xd0, 0xf5, 0x36, 0x1a, 0xbf, 0xff, 0xfa, 0xeb, 0x63, 0x7b, 0x14, 0x0e, 0xc9, 0x95, + 0x8f, 0x34, 0x75, 0x3f, 0xaf, 0x73, 0xb8, 0xd2, 0xaf, 0xcb, 0xb1, 0x36, 0xa8, 0xeb, 0x72, 0xac, + 0xcf, 0xef, 0x5f, 0x72, 0x68, 0x7b, 0xe2, 0xf0, 0xe8, 0xcb, 0x32, 0x0a, 0x2e, 0x96, 0x51, 0xf0, + 0x73, 0x19, 0x05, 0xe7, 0xab, 0xa8, 0x75, 0xb1, 0x8a, 0x5a, 0xdf, 0x56, 0x51, 0xeb, 0xed, 0x7e, + 0xc6, 0x4c, 0x5e, 0xcd, 0x70, 0x2a, 0xca, 0xe6, 0x16, 0xf7, 0xd9, 0xd7, 0xf3, 0x53, 0x92, 0x16, + 0x0c, 0xb8, 0x21, 0x99, 0x92, 0xa9, 0xbd, 0x77, 0xd6, 0xb5, 0xb3, 0x7c, 0xf6, 0x3b, 0x00, 0x00, + 0xff, 0xff, 0x89, 0x73, 0x23, 0x6e, 0x9f, 0x03, 0x00, 0x00, } // Reference imports to suppress errors if they are not otherwise used. @@ -155,6 +307,8 @@ const _ = grpc.SupportPackageIsVersion4 type ServiceClient interface { // Config queries for the operator configuration. Config(ctx context.Context, in *ConfigRequest, opts ...grpc.CallOption) (*ConfigResponse, error) + // Status queries for the node status. + Status(ctx context.Context, in *StatusRequest, opts ...grpc.CallOption) (*StatusResponse, error) } type serviceClient struct { @@ -174,10 +328,21 @@ func (c *serviceClient) Config(ctx context.Context, in *ConfigRequest, opts ...g return out, nil } +func (c *serviceClient) Status(ctx context.Context, in *StatusRequest, opts ...grpc.CallOption) (*StatusResponse, error) { + out := new(StatusResponse) + err := c.cc.Invoke(ctx, "/cosmos.base.node.v1beta1.Service/Status", in, out, opts...) + if err != nil { + return nil, err + } + return out, nil +} + // ServiceServer is the server API for Service service. type ServiceServer interface { // Config queries for the operator configuration. Config(context.Context, *ConfigRequest) (*ConfigResponse, error) + // Status queries for the node status. + Status(context.Context, *StatusRequest) (*StatusResponse, error) } // UnimplementedServiceServer can be embedded to have forward compatible implementations. @@ -187,6 +352,9 @@ type UnimplementedServiceServer struct { func (*UnimplementedServiceServer) Config(ctx context.Context, req *ConfigRequest) (*ConfigResponse, error) { return nil, status.Errorf(codes.Unimplemented, "method Config not implemented") } +func (*UnimplementedServiceServer) Status(ctx context.Context, req *StatusRequest) (*StatusResponse, error) { + return nil, status.Errorf(codes.Unimplemented, "method Status not implemented") +} func RegisterServiceServer(s grpc1.Server, srv ServiceServer) { s.RegisterService(&_Service_serviceDesc, srv) @@ -210,6 +378,24 @@ func _Service_Config_Handler(srv interface{}, ctx context.Context, dec func(inte return interceptor(ctx, in, info, handler) } +func _Service_Status_Handler(srv interface{}, ctx context.Context, dec func(interface{}) error, interceptor grpc.UnaryServerInterceptor) (interface{}, error) { + in := new(StatusRequest) + if err := dec(in); err != nil { + return nil, err + } + if interceptor == nil { + return srv.(ServiceServer).Status(ctx, in) + } + info := &grpc.UnaryServerInfo{ + Server: srv, + FullMethod: "/cosmos.base.node.v1beta1.Service/Status", + } + handler := func(ctx context.Context, req interface{}) (interface{}, error) { + return srv.(ServiceServer).Status(ctx, req.(*StatusRequest)) + } + return interceptor(ctx, in, info, handler) +} + var _Service_serviceDesc = grpc.ServiceDesc{ ServiceName: "cosmos.base.node.v1beta1.Service", HandlerType: (*ServiceServer)(nil), @@ -218,6 +404,10 @@ var _Service_serviceDesc = grpc.ServiceDesc{ MethodName: "Config", Handler: _Service_Config_Handler, }, + { + MethodName: "Status", + Handler: _Service_Status_Handler, + }, }, Streams: []grpc.StreamDesc{}, Metadata: "cosmos/base/node/v1beta1/query.proto", @@ -266,6 +456,20 @@ func (m *ConfigResponse) MarshalToSizedBuffer(dAtA []byte) (int, error) { _ = i var l int _ = l + if len(m.PruningInterval) > 0 { + i -= len(m.PruningInterval) + copy(dAtA[i:], m.PruningInterval) + i = encodeVarintQuery(dAtA, i, uint64(len(m.PruningInterval))) + i-- + dAtA[i] = 0x1a + } + if len(m.PruningKeepRecent) > 0 { + i -= len(m.PruningKeepRecent) + copy(dAtA[i:], m.PruningKeepRecent) + i = encodeVarintQuery(dAtA, i, uint64(len(m.PruningKeepRecent))) + i-- + dAtA[i] = 0x12 + } if len(m.MinimumGasPrice) > 0 { i -= len(m.MinimumGasPrice) copy(dAtA[i:], m.MinimumGasPrice) @@ -276,6 +480,86 @@ func (m *ConfigResponse) MarshalToSizedBuffer(dAtA []byte) (int, error) { return len(dAtA) - i, nil } +func (m *StatusRequest) Marshal() (dAtA []byte, err error) { + size := m.Size() + dAtA = make([]byte, size) + n, err := m.MarshalToSizedBuffer(dAtA[:size]) + if err != nil { + return nil, err + } + return dAtA[:n], nil +} + +func (m *StatusRequest) MarshalTo(dAtA []byte) (int, error) { + size := m.Size() + return m.MarshalToSizedBuffer(dAtA[:size]) +} + +func (m *StatusRequest) MarshalToSizedBuffer(dAtA []byte) (int, error) { + i := len(dAtA) + _ = i + var l int + _ = l + return len(dAtA) - i, nil +} + +func (m *StatusResponse) Marshal() (dAtA []byte, err error) { + size := m.Size() + dAtA = make([]byte, size) + n, err := m.MarshalToSizedBuffer(dAtA[:size]) + if err != nil { + return nil, err + } + return dAtA[:n], nil +} + +func (m *StatusResponse) MarshalTo(dAtA []byte) (int, error) { + size := m.Size() + return m.MarshalToSizedBuffer(dAtA[:size]) +} + +func (m *StatusResponse) MarshalToSizedBuffer(dAtA []byte) (int, error) { + i := len(dAtA) + _ = i + var l int + _ = l + if len(m.ValidatorHash) > 0 { + i -= len(m.ValidatorHash) + copy(dAtA[i:], m.ValidatorHash) + i = encodeVarintQuery(dAtA, i, uint64(len(m.ValidatorHash))) + i-- + dAtA[i] = 0x2a + } + if len(m.AppHash) > 0 { + i -= len(m.AppHash) + copy(dAtA[i:], m.AppHash) + i = encodeVarintQuery(dAtA, i, uint64(len(m.AppHash))) + i-- + dAtA[i] = 0x22 + } + if m.Timestamp != nil { + n1, err1 := github_com_cosmos_gogoproto_types.StdTimeMarshalTo(*m.Timestamp, dAtA[i-github_com_cosmos_gogoproto_types.SizeOfStdTime(*m.Timestamp):]) + if err1 != nil { + return 0, err1 + } + i -= n1 + i = encodeVarintQuery(dAtA, i, uint64(n1)) + i-- + dAtA[i] = 0x1a + } + if m.Height != 0 { + i = encodeVarintQuery(dAtA, i, uint64(m.Height)) + i-- + dAtA[i] = 0x10 + } + if m.EarliestStoreHeight != 0 { + i = encodeVarintQuery(dAtA, i, uint64(m.EarliestStoreHeight)) + i-- + dAtA[i] = 0x8 + } + return len(dAtA) - i, nil +} + func encodeVarintQuery(dAtA []byte, offset int, v uint64) int { offset -= sovQuery(v) base := offset @@ -306,6 +590,50 @@ func (m *ConfigResponse) Size() (n int) { if l > 0 { n += 1 + l + sovQuery(uint64(l)) } + l = len(m.PruningKeepRecent) + if l > 0 { + n += 1 + l + sovQuery(uint64(l)) + } + l = len(m.PruningInterval) + if l > 0 { + n += 1 + l + sovQuery(uint64(l)) + } + return n +} + +func (m *StatusRequest) Size() (n int) { + if m == nil { + return 0 + } + var l int + _ = l + return n +} + +func (m *StatusResponse) Size() (n int) { + if m == nil { + return 0 + } + var l int + _ = l + if m.EarliestStoreHeight != 0 { + n += 1 + sovQuery(uint64(m.EarliestStoreHeight)) + } + if m.Height != 0 { + n += 1 + sovQuery(uint64(m.Height)) + } + if m.Timestamp != nil { + l = github_com_cosmos_gogoproto_types.SizeOfStdTime(*m.Timestamp) + n += 1 + l + sovQuery(uint64(l)) + } + l = len(m.AppHash) + if l > 0 { + n += 1 + l + sovQuery(uint64(l)) + } + l = len(m.ValidatorHash) + if l > 0 { + n += 1 + l + sovQuery(uint64(l)) + } return n } @@ -426,6 +754,312 @@ func (m *ConfigResponse) Unmarshal(dAtA []byte) error { } m.MinimumGasPrice = string(dAtA[iNdEx:postIndex]) iNdEx = postIndex + case 2: + if wireType != 2 { + return fmt.Errorf("proto: wrong wireType = %d for field PruningKeepRecent", wireType) + } + var stringLen uint64 + for shift := uint(0); ; shift += 7 { + if shift >= 64 { + return ErrIntOverflowQuery + } + if iNdEx >= l { + return io.ErrUnexpectedEOF + } + b := dAtA[iNdEx] + iNdEx++ + stringLen |= uint64(b&0x7F) << shift + if b < 0x80 { + break + } + } + intStringLen := int(stringLen) + if intStringLen < 0 { + return ErrInvalidLengthQuery + } + postIndex := iNdEx + intStringLen + if postIndex < 0 { + return ErrInvalidLengthQuery + } + if postIndex > l { + return io.ErrUnexpectedEOF + } + m.PruningKeepRecent = string(dAtA[iNdEx:postIndex]) + iNdEx = postIndex + case 3: + if wireType != 2 { + return fmt.Errorf("proto: wrong wireType = %d for field PruningInterval", wireType) + } + var stringLen uint64 + for shift := uint(0); ; shift += 7 { + if shift >= 64 { + return ErrIntOverflowQuery + } + if iNdEx >= l { + return io.ErrUnexpectedEOF + } + b := dAtA[iNdEx] + iNdEx++ + stringLen |= uint64(b&0x7F) << shift + if b < 0x80 { + break + } + } + intStringLen := int(stringLen) + if intStringLen < 0 { + return ErrInvalidLengthQuery + } + postIndex := iNdEx + intStringLen + if postIndex < 0 { + return ErrInvalidLengthQuery + } + if postIndex > l { + return io.ErrUnexpectedEOF + } + m.PruningInterval = string(dAtA[iNdEx:postIndex]) + iNdEx = postIndex + default: + iNdEx = preIndex + skippy, err := skipQuery(dAtA[iNdEx:]) + if err != nil { + return err + } + if (skippy < 0) || (iNdEx+skippy) < 0 { + return ErrInvalidLengthQuery + } + if (iNdEx + skippy) > l { + return io.ErrUnexpectedEOF + } + iNdEx += skippy + } + } + + if iNdEx > l { + return io.ErrUnexpectedEOF + } + return nil +} +func (m *StatusRequest) Unmarshal(dAtA []byte) error { + l := len(dAtA) + iNdEx := 0 + for iNdEx < l { + preIndex := iNdEx + var wire uint64 + for shift := uint(0); ; shift += 7 { + if shift >= 64 { + return ErrIntOverflowQuery + } + if iNdEx >= l { + return io.ErrUnexpectedEOF + } + b := dAtA[iNdEx] + iNdEx++ + wire |= uint64(b&0x7F) << shift + if b < 0x80 { + break + } + } + fieldNum := int32(wire >> 3) + wireType := int(wire & 0x7) + if wireType == 4 { + return fmt.Errorf("proto: StatusRequest: wiretype end group for non-group") + } + if fieldNum <= 0 { + return fmt.Errorf("proto: StatusRequest: illegal tag %d (wire type %d)", fieldNum, wire) + } + switch fieldNum { + default: + iNdEx = preIndex + skippy, err := skipQuery(dAtA[iNdEx:]) + if err != nil { + return err + } + if (skippy < 0) || (iNdEx+skippy) < 0 { + return ErrInvalidLengthQuery + } + if (iNdEx + skippy) > l { + return io.ErrUnexpectedEOF + } + iNdEx += skippy + } + } + + if iNdEx > l { + return io.ErrUnexpectedEOF + } + return nil +} +func (m *StatusResponse) Unmarshal(dAtA []byte) error { + l := len(dAtA) + iNdEx := 0 + for iNdEx < l { + preIndex := iNdEx + var wire uint64 + for shift := uint(0); ; shift += 7 { + if shift >= 64 { + return ErrIntOverflowQuery + } + if iNdEx >= l { + return io.ErrUnexpectedEOF + } + b := dAtA[iNdEx] + iNdEx++ + wire |= uint64(b&0x7F) << shift + if b < 0x80 { + break + } + } + fieldNum := int32(wire >> 3) + wireType := int(wire & 0x7) + if wireType == 4 { + return fmt.Errorf("proto: StatusResponse: wiretype end group for non-group") + } + if fieldNum <= 0 { + return fmt.Errorf("proto: StatusResponse: illegal tag %d (wire type %d)", fieldNum, wire) + } + switch fieldNum { + case 1: + if wireType != 0 { + return fmt.Errorf("proto: wrong wireType = %d for field EarliestStoreHeight", wireType) + } + m.EarliestStoreHeight = 0 + for shift := uint(0); ; shift += 7 { + if shift >= 64 { + return ErrIntOverflowQuery + } + if iNdEx >= l { + return io.ErrUnexpectedEOF + } + b := dAtA[iNdEx] + iNdEx++ + m.EarliestStoreHeight |= uint64(b&0x7F) << shift + if b < 0x80 { + break + } + } + case 2: + if wireType != 0 { + return fmt.Errorf("proto: wrong wireType = %d for field Height", wireType) + } + m.Height = 0 + for shift := uint(0); ; shift += 7 { + if shift >= 64 { + return ErrIntOverflowQuery + } + if iNdEx >= l { + return io.ErrUnexpectedEOF + } + b := dAtA[iNdEx] + iNdEx++ + m.Height |= uint64(b&0x7F) << shift + if b < 0x80 { + break + } + } + case 3: + if wireType != 2 { + return fmt.Errorf("proto: wrong wireType = %d for field Timestamp", wireType) + } + var msglen int + for shift := uint(0); ; shift += 7 { + if shift >= 64 { + return ErrIntOverflowQuery + } + if iNdEx >= l { + return io.ErrUnexpectedEOF + } + b := dAtA[iNdEx] + iNdEx++ + msglen |= int(b&0x7F) << shift + if b < 0x80 { + break + } + } + if msglen < 0 { + return ErrInvalidLengthQuery + } + postIndex := iNdEx + msglen + if postIndex < 0 { + return ErrInvalidLengthQuery + } + if postIndex > l { + return io.ErrUnexpectedEOF + } + if m.Timestamp == nil { + m.Timestamp = new(time.Time) + } + if err := github_com_cosmos_gogoproto_types.StdTimeUnmarshal(m.Timestamp, dAtA[iNdEx:postIndex]); err != nil { + return err + } + iNdEx = postIndex + case 4: + if wireType != 2 { + return fmt.Errorf("proto: wrong wireType = %d for field AppHash", wireType) + } + var byteLen int + for shift := uint(0); ; shift += 7 { + if shift >= 64 { + return ErrIntOverflowQuery + } + if iNdEx >= l { + return io.ErrUnexpectedEOF + } + b := dAtA[iNdEx] + iNdEx++ + byteLen |= int(b&0x7F) << shift + if b < 0x80 { + break + } + } + if byteLen < 0 { + return ErrInvalidLengthQuery + } + postIndex := iNdEx + byteLen + if postIndex < 0 { + return ErrInvalidLengthQuery + } + if postIndex > l { + return io.ErrUnexpectedEOF + } + m.AppHash = append(m.AppHash[:0], dAtA[iNdEx:postIndex]...) + if m.AppHash == nil { + m.AppHash = []byte{} + } + iNdEx = postIndex + case 5: + if wireType != 2 { + return fmt.Errorf("proto: wrong wireType = %d for field ValidatorHash", wireType) + } + var byteLen int + for shift := uint(0); ; shift += 7 { + if shift >= 64 { + return ErrIntOverflowQuery + } + if iNdEx >= l { + return io.ErrUnexpectedEOF + } + b := dAtA[iNdEx] + iNdEx++ + byteLen |= int(b&0x7F) << shift + if b < 0x80 { + break + } + } + if byteLen < 0 { + return ErrInvalidLengthQuery + } + postIndex := iNdEx + byteLen + if postIndex < 0 { + return ErrInvalidLengthQuery + } + if postIndex > l { + return io.ErrUnexpectedEOF + } + m.ValidatorHash = append(m.ValidatorHash[:0], dAtA[iNdEx:postIndex]...) + if m.ValidatorHash == nil { + m.ValidatorHash = []byte{} + } + iNdEx = postIndex default: iNdEx = preIndex skippy, err := skipQuery(dAtA[iNdEx:]) diff --git a/client/grpc/node/query.pb.gw.go b/client/grpc/node/query.pb.gw.go index c579f6e54575..d83f060bc4dd 100644 --- a/client/grpc/node/query.pb.gw.go +++ b/client/grpc/node/query.pb.gw.go @@ -51,6 +51,24 @@ func local_request_Service_Config_0(ctx context.Context, marshaler runtime.Marsh } +func request_Service_Status_0(ctx context.Context, marshaler runtime.Marshaler, client ServiceClient, req *http.Request, pathParams map[string]string) (proto.Message, runtime.ServerMetadata, error) { + var protoReq StatusRequest + var metadata runtime.ServerMetadata + + msg, err := client.Status(ctx, &protoReq, grpc.Header(&metadata.HeaderMD), grpc.Trailer(&metadata.TrailerMD)) + return msg, metadata, err + +} + +func local_request_Service_Status_0(ctx context.Context, marshaler runtime.Marshaler, server ServiceServer, req *http.Request, pathParams map[string]string) (proto.Message, runtime.ServerMetadata, error) { + var protoReq StatusRequest + var metadata runtime.ServerMetadata + + msg, err := server.Status(ctx, &protoReq) + return msg, metadata, err + +} + // RegisterServiceHandlerServer registers the http handlers for service Service to "mux". // UnaryRPC :call ServiceServer directly. // StreamingRPC :currently unsupported pending https://github.com/grpc/grpc-go/issues/906. @@ -80,6 +98,29 @@ func RegisterServiceHandlerServer(ctx context.Context, mux *runtime.ServeMux, se }) + mux.Handle("GET", pattern_Service_Status_0, func(w http.ResponseWriter, req *http.Request, pathParams map[string]string) { + ctx, cancel := context.WithCancel(req.Context()) + defer cancel() + var stream runtime.ServerTransportStream + ctx = grpc.NewContextWithServerTransportStream(ctx, &stream) + inboundMarshaler, outboundMarshaler := runtime.MarshalerForRequest(mux, req) + rctx, err := runtime.AnnotateIncomingContext(ctx, mux, req) + if err != nil { + runtime.HTTPError(ctx, mux, outboundMarshaler, w, req, err) + return + } + resp, md, err := local_request_Service_Status_0(rctx, inboundMarshaler, server, req, pathParams) + md.HeaderMD, md.TrailerMD = metadata.Join(md.HeaderMD, stream.Header()), metadata.Join(md.TrailerMD, stream.Trailer()) + ctx = runtime.NewServerMetadataContext(ctx, md) + if err != nil { + runtime.HTTPError(ctx, mux, outboundMarshaler, w, req, err) + return + } + + forward_Service_Status_0(ctx, mux, outboundMarshaler, w, req, resp, mux.GetForwardResponseOptions()...) + + }) + return nil } @@ -141,13 +182,37 @@ func RegisterServiceHandlerClient(ctx context.Context, mux *runtime.ServeMux, cl }) + mux.Handle("GET", pattern_Service_Status_0, func(w http.ResponseWriter, req *http.Request, pathParams map[string]string) { + ctx, cancel := context.WithCancel(req.Context()) + defer cancel() + inboundMarshaler, outboundMarshaler := runtime.MarshalerForRequest(mux, req) + rctx, err := runtime.AnnotateContext(ctx, mux, req) + if err != nil { + runtime.HTTPError(ctx, mux, outboundMarshaler, w, req, err) + return + } + resp, md, err := request_Service_Status_0(rctx, inboundMarshaler, client, req, pathParams) + ctx = runtime.NewServerMetadataContext(ctx, md) + if err != nil { + runtime.HTTPError(ctx, mux, outboundMarshaler, w, req, err) + return + } + + forward_Service_Status_0(ctx, mux, outboundMarshaler, w, req, resp, mux.GetForwardResponseOptions()...) + + }) + return nil } var ( pattern_Service_Config_0 = runtime.MustPattern(runtime.NewPattern(1, []int{2, 0, 2, 1, 2, 2, 2, 3, 2, 4}, []string{"cosmos", "base", "node", "v1beta1", "config"}, "", runtime.AssumeColonVerbOpt(false))) + + pattern_Service_Status_0 = runtime.MustPattern(runtime.NewPattern(1, []int{2, 0, 2, 1, 2, 2, 2, 3, 2, 4}, []string{"cosmos", "base", "node", "v1beta1", "status"}, "", runtime.AssumeColonVerbOpt(false))) ) var ( forward_Service_Config_0 = runtime.ForwardResponseMessage + + forward_Service_Status_0 = runtime.ForwardResponseMessage ) diff --git a/client/grpc/node/service.go b/client/grpc/node/service.go index bf176e12dbcb..0d4f27a42932 100644 --- a/client/grpc/node/service.go +++ b/client/grpc/node/service.go @@ -7,12 +7,13 @@ import ( "github.com/grpc-ecosystem/grpc-gateway/runtime" "github.com/cosmos/cosmos-sdk/client" + "github.com/cosmos/cosmos-sdk/server/config" sdk "github.com/cosmos/cosmos-sdk/types" ) // RegisterNodeService registers the node gRPC service on the provided gRPC router. -func RegisterNodeService(clientCtx client.Context, server gogogrpc.Server) { - RegisterServiceServer(server, NewQueryServer(clientCtx)) +func RegisterNodeService(clientCtx client.Context, server gogogrpc.Server, cfg config.Config) { + RegisterServiceServer(server, NewQueryServer(clientCtx, cfg)) } // RegisterGRPCGatewayRoutes mounts the node gRPC service's GRPC-gateway routes @@ -25,9 +26,10 @@ var _ ServiceServer = queryServer{} type queryServer struct { clientCtx client.Context + cfg config.Config } -func NewQueryServer(clientCtx client.Context) ServiceServer { +func NewQueryServer(clientCtx client.Context, cfg config.Config) ServiceServer { return queryServer{ clientCtx: clientCtx, } @@ -37,6 +39,25 @@ func (s queryServer) Config(ctx context.Context, _ *ConfigRequest) (*ConfigRespo sdkCtx := sdk.UnwrapSDKContext(ctx) return &ConfigResponse{ - MinimumGasPrice: sdkCtx.MinGasPrices().String(), + MinimumGasPrice: sdkCtx.MinGasPrices().String(), + PruningKeepRecent: s.cfg.PruningKeepRecent, + PruningInterval: s.cfg.PruningInterval, + }, nil +} + +func (s queryServer) Status(ctx context.Context, _ *StatusRequest) (*StatusResponse, error) { + sdkCtx := sdk.UnwrapSDKContext(ctx) + + blockTime := sdkCtx.BlockTime() + + return &StatusResponse{ + // TODO: Get earliest version from store. + // + // Ref: ... + // EarliestStoreHeight: sdkCtx.MultiStore(), + Height: uint64(sdkCtx.BlockHeight()), + Timestamp: &blockTime, + AppHash: sdkCtx.BlockHeader().AppHash, + ValidatorHash: sdkCtx.BlockHeader().NextValidatorsHash, }, nil } diff --git a/client/grpc/node/service_test.go b/client/grpc/node/service_test.go index 654b27c6f7e7..2cbc07d3dda8 100644 --- a/client/grpc/node/service_test.go +++ b/client/grpc/node/service_test.go @@ -6,11 +6,12 @@ import ( "github.com/stretchr/testify/require" "github.com/cosmos/cosmos-sdk/client" + "github.com/cosmos/cosmos-sdk/server/config" sdk "github.com/cosmos/cosmos-sdk/types" ) func TestServiceServer_Config(t *testing.T) { - svr := NewQueryServer(client.Context{}) + svr := NewQueryServer(client.Context{}, *config.DefaultConfig()) ctx := sdk.Context{}.WithMinGasPrices(sdk.NewDecCoins(sdk.NewInt64DecCoin("stake", 15))) resp, err := svr.Config(ctx, &ConfigRequest{}) diff --git a/client/grpc_query.go b/client/grpc_query.go index 534211518367..6ae3d9b8b869 100644 --- a/client/grpc_query.go +++ b/client/grpc_query.go @@ -2,12 +2,10 @@ package client import ( gocontext "context" - "errors" "fmt" "reflect" "strconv" - proto "github.com/cosmos/gogoproto/proto" "google.golang.org/grpc/encoding" "github.com/cosmos/cosmos-sdk/codec" @@ -29,7 +27,7 @@ var _ gogogrpc.ClientConn = Context{} // fallBackCodec is used by Context in case Codec is not set. // it can process every gRPC type, except the ones which contain // interfaces in their types. -var fallBackCodec = codec.NewProtoCodec(failingInterfaceRegistry{}) +var fallBackCodec = codec.NewProtoCodec(types.NewInterfaceRegistry()) // Invoke implements the grpc ClientConn.Invoke method func (ctx Context) Invoke(grpcCtx gocontext.Context, method string, req, reply interface{}, opts ...grpc.CallOption) (err error) { @@ -143,41 +141,3 @@ func (ctx Context) gRPCCodec() encoding.Codec { return pc.GRPCCodec() } - -var _ types.InterfaceRegistry = failingInterfaceRegistry{} - -// failingInterfaceRegistry is used by the fallback codec -// in case Context's Codec is not set. -type failingInterfaceRegistry struct{} - -// errCodecNotSet is return by failingInterfaceRegistry in case there are attempt to decode -// or encode a type which contains an interface field. -var errCodecNotSet = errors.New("client: cannot encode or decode type which requires the application specific codec") - -func (f failingInterfaceRegistry) UnpackAny(any *types.Any, iface interface{}) error { - return errCodecNotSet -} - -func (f failingInterfaceRegistry) Resolve(typeURL string) (proto.Message, error) { - return nil, errCodecNotSet -} - -func (f failingInterfaceRegistry) RegisterInterface(protoName string, iface interface{}, impls ...proto.Message) { - panic("cannot be called") -} - -func (f failingInterfaceRegistry) RegisterImplementations(iface interface{}, impls ...proto.Message) { - panic("cannot be called") -} - -func (f failingInterfaceRegistry) ListAllInterfaces() []string { - panic("cannot be called") -} - -func (f failingInterfaceRegistry) ListImplementations(ifaceTypeURL string) []string { - panic("cannot be called") -} - -func (f failingInterfaceRegistry) EnsureRegistered(iface interface{}) error { - panic("cannot be called") -} diff --git a/client/grpc_query_test.go b/client/grpc_query_test.go index f0594fc228f4..fd43d6cf812c 100644 --- a/client/grpc_query_test.go +++ b/client/grpc_query_test.go @@ -33,6 +33,7 @@ type IntegrationTestSuite struct { suite.Suite ctx sdk.Context + cdc codec.Codec genesisAccount *authtypes.BaseAccount bankClient types.QueryClient testClient testdata.QueryClient @@ -96,6 +97,7 @@ func (s *IntegrationTestSuite) SetupSuite() { // end of app init s.ctx = app.BaseApp.NewContext(false, cmtproto.Header{}) + s.cdc = cdc queryHelper := baseapp.NewQueryServerTestHelper(s.ctx, interfaceRegistry) types.RegisterQueryServer(queryHelper, bankKeeper) testdata.RegisterQueryServer(queryHelper, testdata.QueryImpl{}) diff --git a/client/internal_client_test.go b/client/internal_client_test.go deleted file mode 100644 index 6d6cacb87f82..000000000000 --- a/client/internal_client_test.go +++ /dev/null @@ -1,31 +0,0 @@ -package client - -import ( - "testing" - - "github.com/stretchr/testify/require" -) - -func TestFailingInterfaceRegistry(t *testing.T) { - reg := failingInterfaceRegistry{} - - require.Error(t, reg.UnpackAny(nil, nil)) - _, err := reg.Resolve("") - require.Error(t, err) - - require.Panics(t, func() { - reg.RegisterInterface("", nil) - }) - require.Panics(t, func() { - reg.RegisterImplementations(nil, nil) - }) - require.Panics(t, func() { - reg.ListAllInterfaces() - }) - require.Panics(t, func() { - reg.ListImplementations("") - }) - require.Panics(t, func() { - reg.EnsureRegistered(nil) - }) -} diff --git a/client/keys/add.go b/client/keys/add.go index a38fa798ca2b..4392f90bf25f 100644 --- a/client/keys/add.go +++ b/client/keys/add.go @@ -229,8 +229,8 @@ func runAddCmd(ctx client.Context, cmd *cobra.Command, args []string, inBuf *buf // Get bip39 mnemonic var mnemonic, bip39Passphrase string - recover, _ := cmd.Flags().GetBool(flagRecover) - if recover { + recoverFlag, _ := cmd.Flags().GetBool(flagRecover) + if recoverFlag { mnemonic, err = input.GetString("Enter your bip39 mnemonic", inBuf) if err != nil { return err @@ -291,7 +291,7 @@ func runAddCmd(ctx client.Context, cmd *cobra.Command, args []string, inBuf *buf } // Recover key from seed passphrase - if recover { + if recoverFlag { // Hide mnemonic from output showMnemonic = false mnemonic = "" @@ -302,7 +302,7 @@ func runAddCmd(ctx client.Context, cmd *cobra.Command, args []string, inBuf *buf func printCreate(cmd *cobra.Command, k *keyring.Record, showMnemonic bool, mnemonic, outputFormat string) error { switch outputFormat { - case OutputFormatText: + case flags.OutputFormatText: cmd.PrintErrln() if err := printKeyringRecord(cmd.OutOrStdout(), k, MkAccKeyOutput, outputFormat); err != nil { return err @@ -314,7 +314,7 @@ func printCreate(cmd *cobra.Command, k *keyring.Record, showMnemonic bool, mnemo return fmt.Errorf("failed to print mnemonic: %v", err) } } - case OutputFormatJSON: + case flags.OutputFormatJSON: out, err := MkAccKeyOutput(k) if err != nil { return err diff --git a/client/keys/add_ledger_test.go b/client/keys/add_ledger_test.go index 1bcc62aa5654..289200e3fe29 100644 --- a/client/keys/add_ledger_test.go +++ b/client/keys/add_ledger_test.go @@ -10,7 +10,6 @@ import ( "io" "testing" - "github.com/cometbft/cometbft/libs/cli" "github.com/stretchr/testify/require" "github.com/cosmos/cosmos-sdk/client" @@ -54,7 +53,7 @@ func Test_runAddCmdLedgerWithCustomCoinType(t *testing.T) { fmt.Sprintf("--%s=0", flagAccount), fmt.Sprintf("--%s=0", flagIndex), fmt.Sprintf("--%s=330", flagCoinType), - fmt.Sprintf("--%s=%s", cli.OutputFlag, OutputFormatText), + fmt.Sprintf("--%s=%s", flags.FlagOutput, flags.OutputFormatText), fmt.Sprintf("--%s=%s", flags.FlagKeyType, hd.Secp256k1Type), fmt.Sprintf("--%s=%s", flags.FlagKeyringBackend, keyring.BackendTest), }) @@ -104,7 +103,7 @@ func Test_runAddCmdLedger(t *testing.T) { cmd.SetArgs([]string{ "keyname1", fmt.Sprintf("--%s=true", flags.FlagUseLedger), - fmt.Sprintf("--%s=%s", cli.OutputFlag, OutputFormatText), + fmt.Sprintf("--%s=%s", flags.FlagOutput, flags.OutputFormatText), fmt.Sprintf("--%s=%s", flags.FlagKeyType, hd.Secp256k1Type), fmt.Sprintf("--%s=%d", flagCoinType, sdk.CoinType), fmt.Sprintf("--%s=%s", flags.FlagKeyringBackend, keyring.BackendTest), diff --git a/client/keys/add_test.go b/client/keys/add_test.go index 1f28fcddbc3a..f275d001ab38 100644 --- a/client/keys/add_test.go +++ b/client/keys/add_test.go @@ -7,7 +7,6 @@ import ( "io" "testing" - "github.com/cometbft/cometbft/libs/cli" "github.com/stretchr/testify/require" "github.com/cosmos/cosmos-sdk/client" @@ -43,7 +42,7 @@ func Test_runAddCmdBasic(t *testing.T) { cmd.SetArgs([]string{ "keyname1", fmt.Sprintf("--%s=%s", flags.FlagHome, kbHome), - fmt.Sprintf("--%s=%s", cli.OutputFlag, OutputFormatText), + fmt.Sprintf("--%s=%s", flags.FlagOutput, flags.OutputFormatText), fmt.Sprintf("--%s=%s", flags.FlagKeyType, hd.Secp256k1Type), fmt.Sprintf("--%s=%s", flags.FlagKeyringBackend, keyring.BackendTest), }) @@ -56,7 +55,7 @@ func Test_runAddCmdBasic(t *testing.T) { cmd.SetArgs([]string{ "keyname2", fmt.Sprintf("--%s=%s", flags.FlagHome, kbHome), - fmt.Sprintf("--%s=%s", cli.OutputFlag, OutputFormatText), + fmt.Sprintf("--%s=%s", flags.FlagOutput, flags.OutputFormatText), fmt.Sprintf("--%s=%s", flags.FlagKeyType, hd.Secp256k1Type), fmt.Sprintf("--%s=%s", flags.FlagKeyringBackend, keyring.BackendTest), }) @@ -70,7 +69,7 @@ func Test_runAddCmdBasic(t *testing.T) { cmd.SetArgs([]string{ "keyname4", fmt.Sprintf("--%s=%s", flags.FlagHome, kbHome), - fmt.Sprintf("--%s=%s", cli.OutputFlag, OutputFormatText), + fmt.Sprintf("--%s=%s", flags.FlagOutput, flags.OutputFormatText), fmt.Sprintf("--%s=%s", flags.FlagKeyType, hd.Secp256k1Type), fmt.Sprintf("--%s=%s", flags.FlagKeyringBackend, keyring.BackendTest), }) @@ -82,7 +81,7 @@ func Test_runAddCmdBasic(t *testing.T) { "keyname5", fmt.Sprintf("--%s=%s", flags.FlagHome, kbHome), fmt.Sprintf("--%s=true", flags.FlagDryRun), - fmt.Sprintf("--%s=%s", cli.OutputFlag, OutputFormatText), + fmt.Sprintf("--%s=%s", flags.FlagOutput, flags.OutputFormatText), fmt.Sprintf("--%s=%s", flags.FlagKeyType, hd.Secp256k1Type), }) @@ -245,7 +244,7 @@ func TestAddRecoverFileBackend(t *testing.T) { cmd.SetArgs([]string{ "keyname1", fmt.Sprintf("--%s=%s", flags.FlagHome, kbHome), - fmt.Sprintf("--%s=%s", cli.OutputFlag, OutputFormatText), + fmt.Sprintf("--%s=%s", flags.FlagOutput, flags.OutputFormatText), fmt.Sprintf("--%s=%s", flags.FlagKeyType, hd.Secp256k1Type), fmt.Sprintf("--%s=%s", flags.FlagKeyringBackend, keyring.BackendFile), fmt.Sprintf("--%s", flagRecover), diff --git a/client/keys/import_test.go b/client/keys/import_test.go index 59cdf044d9cf..d9b9d0fee79f 100644 --- a/client/keys/import_test.go +++ b/client/keys/import_test.go @@ -94,7 +94,7 @@ HbP+c6JmeJy9JXe2rbbF1QtCX1gLqGcDQPBXiCtFvP7/8wTZtVOPj8vREzhZ9ElO t.Cleanup(cleanupKeys(t, kb, "keyname1")) keyfile := filepath.Join(kbHome, "key.asc") - require.NoError(t, os.WriteFile(keyfile, []byte(armoredKey), 0o644)) //nolint:gosec + require.NoError(t, os.WriteFile(keyfile, []byte(armoredKey), 0o600)) defer func() { _ = os.RemoveAll(kbHome) diff --git a/client/keys/list.go b/client/keys/list.go index 241c04d8722f..e3b3e4f8aea5 100644 --- a/client/keys/list.go +++ b/client/keys/list.go @@ -1,6 +1,7 @@ package keys import ( + "github.com/cosmos/cosmos-sdk/client/flags" "github.com/spf13/cobra" "github.com/cosmos/cosmos-sdk/client" @@ -33,7 +34,7 @@ func runListCmd(cmd *cobra.Command, _ []string) error { return err } - if len(records) == 0 { + if len(records) == 0 && clientCtx.OutputFormat == flags.OutputFormatText { cmd.Println("No records were found in keyring") return nil } diff --git a/client/keys/output.go b/client/keys/output.go index 893233498185..1ec5eed6a62c 100644 --- a/client/keys/output.go +++ b/client/keys/output.go @@ -21,7 +21,7 @@ type KeyOutput struct { } // NewKeyOutput creates a default KeyOutput instance without Mnemonic, Threshold and PubKeys -func NewKeyOutput(name string, keyType keyring.KeyType, a sdk.Address, pk cryptotypes.PubKey) (KeyOutput, error) { //nolint:interfacer +func NewKeyOutput(name string, keyType keyring.KeyType, a sdk.Address, pk cryptotypes.PubKey) (KeyOutput, error) { apk, err := codectypes.NewAnyWithValue(pk) if err != nil { return KeyOutput{}, err diff --git a/client/keys/parse.go b/client/keys/parse.go index fc0344c19827..dc009f56d43c 100644 --- a/client/keys/parse.go +++ b/client/keys/parse.go @@ -8,10 +8,10 @@ import ( "io" "strings" - "github.com/cometbft/cometbft/libs/cli" "github.com/spf13/cobra" "sigs.k8s.io/yaml" + "github.com/cosmos/cosmos-sdk/client/flags" sdk "github.com/cosmos/cosmos-sdk/types" "github.com/cosmos/cosmos-sdk/types/bech32" ) @@ -98,7 +98,7 @@ func doParseKey(cmd *cobra.Command, config *sdk.Config, args []string) error { return errors.New("couldn't parse empty input") } - output, _ := cmd.Flags().GetString(cli.OutputFlag) + output, _ := cmd.Flags().GetString(flags.FlagOutput) if !(runFromBech32(outstream, addr, output) || runFromHex(config, outstream, addr, output)) { return errors.New("couldn't find valid bech32 nor hex data") } @@ -137,10 +137,10 @@ func displayParseKeyInfo(w io.Writer, stringer fmt.Stringer, output string) { ) switch output { - case OutputFormatText: + case flags.OutputFormatText: out, err = yaml.Marshal(&stringer) - case OutputFormatJSON: + case flags.OutputFormatJSON: out, err = json.Marshal(&stringer) } diff --git a/client/keys/root.go b/client/keys/root.go index 855a50798168..92fd3ae2e339 100644 --- a/client/keys/root.go +++ b/client/keys/root.go @@ -1,7 +1,6 @@ package keys import ( - "github.com/cometbft/cometbft/libs/cli" "github.com/spf13/cobra" "github.com/cosmos/cosmos-sdk/client/flags" @@ -52,7 +51,7 @@ The pass backend requires GnuPG: https://gnupg.org/ ) cmd.PersistentFlags().String(flags.FlagHome, defaultNodeHome, "The application home directory") - cmd.PersistentFlags().String(cli.OutputFlag, "text", "Output format (text|json)") + cmd.PersistentFlags().String(flags.FlagOutput, "text", "Output format (text|json)") flags.AddKeyringFlags(cmd.PersistentFlags()) return cmd diff --git a/client/keys/show.go b/client/keys/show.go index 21c800b48227..c65a000409d1 100644 --- a/client/keys/show.go +++ b/client/keys/show.go @@ -4,12 +4,12 @@ import ( "errors" "fmt" - "github.com/cometbft/cometbft/libs/cli" "github.com/spf13/cobra" errorsmod "cosmossdk.io/errors" "github.com/cosmos/cosmos-sdk/client" + "github.com/cosmos/cosmos-sdk/client/flags" "github.com/cosmos/cosmos-sdk/crypto/keyring" "github.com/cosmos/cosmos-sdk/crypto/keys/multisig" "github.com/cosmos/cosmos-sdk/crypto/ledger" @@ -97,7 +97,7 @@ func runShowCmd(cmd *cobra.Command, args []string) (err error) { isShowDevice, _ := cmd.Flags().GetBool(FlagDevice) isOutputSet := false - tmp := cmd.Flag(cli.OutputFlag) + tmp := cmd.Flag(flags.FlagOutput) if tmp != nil { isOutputSet = tmp.Changed } @@ -117,7 +117,7 @@ func runShowCmd(cmd *cobra.Command, args []string) (err error) { } if isOutputSet { - clientCtx.OutputFormat, _ = cmd.Flags().GetString(cli.OutputFlag) + clientCtx.OutputFormat, _ = cmd.Flags().GetString(flags.FlagOutput) } switch { diff --git a/client/keys/utils.go b/client/keys/utils.go index ccd8cce8b0ce..40b800757cca 100644 --- a/client/keys/utils.go +++ b/client/keys/utils.go @@ -7,15 +7,10 @@ import ( "sigs.k8s.io/yaml" + "github.com/cosmos/cosmos-sdk/client/flags" cryptokeyring "github.com/cosmos/cosmos-sdk/crypto/keyring" ) -// available output formats. -const ( - OutputFormatText = "text" - OutputFormatJSON = "json" -) - type bechKeyOutFn func(k *cryptokeyring.Record) (KeyOutput, error) func printKeyringRecord(w io.Writer, k *cryptokeyring.Record, bechKeyOut bechKeyOutFn, output string) error { @@ -25,12 +20,12 @@ func printKeyringRecord(w io.Writer, k *cryptokeyring.Record, bechKeyOut bechKey } switch output { - case OutputFormatText: + case flags.OutputFormatText: if err := printTextRecords(w, []KeyOutput{ko}); err != nil { return err } - case OutputFormatJSON: + case flags.OutputFormatJSON: out, err := json.Marshal(ko) if err != nil { return err @@ -51,12 +46,12 @@ func printKeyringRecords(w io.Writer, records []*cryptokeyring.Record, output st } switch output { - case OutputFormatText: + case flags.OutputFormatText: if err := printTextRecords(w, kos); err != nil { return err } - case OutputFormatJSON: + case flags.OutputFormatJSON: out, err := json.Marshal(kos) if err != nil { return err diff --git a/client/rpc/block.go b/client/rpc/block.go index 5b7540f6df14..93c710a857c5 100644 --- a/client/rpc/block.go +++ b/client/rpc/block.go @@ -47,7 +47,7 @@ func GetChainHeight(clientCtx client.Context) (int64, error) { // tx.height = 5 # all txs of the fifth block // // For more information, see the /subscribe CometBFT RPC endpoint documentation -func QueryBlocks(clientCtx client.Context, page, limit int, query string, orderBy string) (*sdk.SearchBlocksResult, error) { +func QueryBlocks(clientCtx client.Context, page, limit int, query, orderBy string) (*sdk.SearchBlocksResult, error) { node, err := clientCtx.GetNode() if err != nil { return nil, err diff --git a/client/rpc/rpc_test.go b/client/rpc/rpc_test.go index 5eb3b866f173..3bd9c39ec867 100644 --- a/client/rpc/rpc_test.go +++ b/client/rpc/rpc_test.go @@ -15,6 +15,7 @@ import ( clitestutil "github.com/cosmos/cosmos-sdk/testutil/cli" "github.com/cosmos/cosmos-sdk/testutil/network" "github.com/cosmos/cosmos-sdk/testutil/testdata" + "github.com/cosmos/cosmos-sdk/types/address" grpctypes "github.com/cosmos/cosmos-sdk/types/grpc" banktypes "github.com/cosmos/cosmos-sdk/x/bank/types" ) @@ -55,6 +56,7 @@ func (s *IntegrationTestSuite) TestStatusCommand() { } func (s *IntegrationTestSuite) TestCLIQueryConn() { + s.T().Skip("data race in comet is causing this to fail") var header metadata.MD testClient := testdata.NewQueryClient(s.network.Validators[0].ClientCtx) @@ -108,7 +110,7 @@ func (s *IntegrationTestSuite) TestQueryABCIHeight() { req := abci.RequestQuery{ Path: fmt.Sprintf("store/%s/key", banktypes.StoreKey), Height: tc.reqHeight, - Data: banktypes.CreateAccountBalancesPrefix(val.Address), + Data: address.MustLengthPrefix(val.Address), Prove: true, } diff --git a/client/test_helpers.go b/client/test_helpers.go index 214184b50f17..8c7c27a674c1 100644 --- a/client/test_helpers.go +++ b/client/test_helpers.go @@ -74,7 +74,7 @@ func (t TestAccountRetriever) EnsureExists(_ Context, addr sdk.AccAddress) error } // GetAccountNumberSequence implements AccountRetriever.GetAccountNumberSequence -func (t TestAccountRetriever) GetAccountNumberSequence(_ Context, addr sdk.AccAddress) (accNum uint64, accSeq uint64, err error) { +func (t TestAccountRetriever) GetAccountNumberSequence(_ Context, addr sdk.AccAddress) (accNum, accSeq uint64, err error) { acc, ok := t.Accounts[addr.String()] if !ok { return 0, 0, fmt.Errorf("account %s not found", addr) diff --git a/client/testdata/fuzz/FuzzQueryBalance/4bf93f2225e526ac b/client/testdata/fuzz/FuzzQueryBalance/4bf93f2225e526ac new file mode 100644 index 000000000000..73d7776fdb93 --- /dev/null +++ b/client/testdata/fuzz/FuzzQueryBalance/4bf93f2225e526ac @@ -0,0 +1,2 @@ +go test fuzz v1 +[]byte("\n-cosmos1wrq8cagsama0xwf2vmlzgrkyynfsxuyhturvyz\x12\x0500000") diff --git a/client/tx/aux_builder.go b/client/tx/aux_builder.go index 331f4a8459e1..0ad68502f2f4 100644 --- a/client/tx/aux_builder.go +++ b/client/tx/aux_builder.go @@ -95,14 +95,14 @@ func (b *AuxTxBuilder) SetSequence(accSeq uint64) { // SetPubKey sets the aux signer's pubkey in the AuxSignerData. func (b *AuxTxBuilder) SetPubKey(pk cryptotypes.PubKey) error { - any, err := codectypes.NewAnyWithValue(pk) + anyAnimal, err := codectypes.NewAnyWithValue(pk) if err != nil { return err } b.checkEmptyFields() - b.auxSignerData.SignDoc.PublicKey = any + b.auxSignerData.SignDoc.PublicKey = anyAnimal return nil } diff --git a/client/tx/factory.go b/client/tx/factory.go index d642991a4426..2586fcf5dc79 100644 --- a/client/tx/factory.go +++ b/client/tx/factory.go @@ -168,7 +168,7 @@ func (f Factory) WithFees(fees string) Factory { } // WithTips returns a copy of the Factory with an updated tip. -func (f Factory) WithTips(tip string, tipper string) Factory { +func (f Factory) WithTips(tip, tipper string) Factory { parsedTips, err := sdk.ParseCoinsNormalized(tip) if err != nil { panic(err) diff --git a/client/tx/tx.go b/client/tx/tx.go index 86c0caaa06ac..78de623a460e 100644 --- a/client/tx/tx.go +++ b/client/tx/tx.go @@ -40,7 +40,12 @@ func GenerateOrBroadcastTxWithFactory(clientCtx client.Context, txf Factory, msg // Right now, we're factorizing that call inside this function. // ref: https://github.com/cosmos/cosmos-sdk/pull/9236#discussion_r623803504 for _, msg := range msgs { - if err := msg.ValidateBasic(); err != nil { + m, ok := msg.(sdk.HasValidateBasic) + if !ok { + continue + } + + if err := m.ValidateBasic(); err != nil { return err } } @@ -107,11 +112,11 @@ func BroadcastTx(clientCtx client.Context, txf Factory, msgs ...sdk.Msg) error { buf := bufio.NewReader(os.Stdin) ok, err := input.GetConfirmation("confirm transaction before signing and broadcasting", buf, os.Stderr) if err != nil { - _, _ = fmt.Fprintf(os.Stderr, "error: %v\ncancelled transaction\n", err) + _, _ = fmt.Fprintf(os.Stderr, "error: %v\ncanceled transaction\n", err) return err } if !ok { - _, _ = fmt.Fprintln(os.Stderr, "cancelled transaction") + _, _ = fmt.Fprintln(os.Stderr, "canceled transaction") return nil } } @@ -167,7 +172,8 @@ func SignWithPrivKey( var sigV2 signing.SignatureV2 // Generate the bytes to be signed. - signBytes, err := authsigning.GetSignBytesWithContext(txConfig.SignModeHandler(), ctx, signMode, signerData, txBuilder.GetTx()) + signBytes, err := authsigning.GetSignBytesAdapter( + ctx, txConfig.TxEncoder(), txConfig.SignModeHandler(), signMode, signerData, txBuilder.GetTx()) if err != nil { return sigV2, err } @@ -243,10 +249,14 @@ func Sign(ctx context.Context, txf Factory, name string, txBuilder client.TxBuil return errors.New("keybase must be set prior to signing a transaction") } + var err error signMode := txf.signMode if signMode == signing.SignMode_SIGN_MODE_UNSPECIFIED { // use the SignModeHandler's default mode if unspecified - signMode = txf.txConfig.SignModeHandler().DefaultMode() + signMode, err = authsigning.APISignModeToInternal(txf.txConfig.SignModeHandler().DefaultMode()) + if err != nil { + return err + } } k, err := txf.keybase.Key(name) @@ -308,8 +318,9 @@ func Sign(ctx context.Context, txf Factory, name string, txBuilder client.TxBuil return err } - // Generate the bytes to be signed. - bytesToSign, err := authsigning.GetSignBytesWithContext(txf.txConfig.SignModeHandler(), ctx, signMode, signerData, txBuilder.GetTx()) + bytesToSign, err := authsigning.GetSignBytesAdapter( + ctx, txf.txConfig.TxEncoder(), txf.txConfig.SignModeHandler(), + signMode, signerData, txBuilder.GetTx()) if err != nil { return err } diff --git a/client/tx/tx_test.go b/client/tx/tx_test.go index 788b96c2f2f3..20d0a642d860 100644 --- a/client/tx/tx_test.go +++ b/client/tx/tx_test.go @@ -1,15 +1,16 @@ package tx_test import ( - gocontext "context" + "context" "fmt" "strings" "testing" - sdkmath "cosmossdk.io/math" "github.com/stretchr/testify/require" "google.golang.org/grpc" + sdkmath "cosmossdk.io/math" + "github.com/cosmos/cosmos-sdk/client" "github.com/cosmos/cosmos-sdk/client/tx" "github.com/cosmos/cosmos-sdk/codec" @@ -28,7 +29,7 @@ import ( banktypes "github.com/cosmos/cosmos-sdk/x/bank/types" ) -func newTestTxConfig(t *testing.T) (client.TxConfig, codec.Codec) { +func newTestTxConfig() (client.TxConfig, codec.Codec) { encodingConfig := moduletestutil.MakeTestEncodingConfig() return authtx.NewTxConfig(codec.NewProtoCodec(encodingConfig.InterfaceRegistry), authtx.DefaultSignModes), encodingConfig.Codec } @@ -40,7 +41,7 @@ type mockContext struct { wantErr bool } -func (m mockContext) Invoke(grpcCtx gocontext.Context, method string, req, reply interface{}, opts ...grpc.CallOption) (err error) { +func (m mockContext) Invoke(_ context.Context, _ string, _, reply interface{}, _ ...grpc.CallOption) (err error) { if m.wantErr { return fmt.Errorf("mock err") } @@ -53,7 +54,7 @@ func (m mockContext) Invoke(grpcCtx gocontext.Context, method string, req, reply return nil } -func (mockContext) NewStream(gocontext.Context, *grpc.StreamDesc, string, ...grpc.CallOption) (grpc.ClientStream, error) { +func (mockContext) NewStream(context.Context, *grpc.StreamDesc, string, ...grpc.CallOption) (grpc.ClientStream, error) { panic("not implemented") } @@ -77,11 +78,13 @@ func TestCalculateGas(t *testing.T) { for _, tc := range testCases { stc := tc - txCfg, _ := newTestTxConfig(t) + txCfg, _ := newTestTxConfig() + defaultSignMode, err := signing.APISignModeToInternal(txCfg.SignModeHandler().DefaultMode()) + require.NoError(t, err) txf := tx.Factory{}. WithChainID("test-chain"). - WithTxConfig(txCfg).WithSignMode(txCfg.SignModeHandler().DefaultMode()) + WithTxConfig(txCfg).WithSignMode(defaultSignMode) t.Run(stc.name, func(t *testing.T) { mockClientCtx := mockContext{ @@ -103,7 +106,9 @@ func TestCalculateGas(t *testing.T) { } func TestBuildSimTx(t *testing.T) { - txCfg, cdc := newTestTxConfig(t) + txCfg, cdc := newTestTxConfig() + defaultSignMode, err := signing.APISignModeToInternal(txCfg.SignModeHandler().DefaultMode()) + require.NoError(t, err) kb, err := keyring.New(t.Name(), "test", t.TempDir(), nil, cdc) require.NoError(t, err) @@ -119,7 +124,7 @@ func TestBuildSimTx(t *testing.T) { WithFees("50stake"). WithMemo("memo"). WithChainID("test-chain"). - WithSignMode(txCfg.SignModeHandler().DefaultMode()). + WithSignMode(defaultSignMode). WithKeybase(kb) msg := banktypes.NewMsgSend(sdk.AccAddress("from"), sdk.AccAddress("to"), nil) @@ -129,7 +134,7 @@ func TestBuildSimTx(t *testing.T) { } func TestBuildUnsignedTx(t *testing.T) { - txConfig, cdc := newTestTxConfig(t) + txConfig, cdc := newTestTxConfig() kb, err := keyring.New(t.Name(), "test", t.TempDir(), nil, cdc) require.NoError(t, err) @@ -158,7 +163,7 @@ func TestBuildUnsignedTx(t *testing.T) { } func TestMnemonicInMemo(t *testing.T) { - txConfig, cdc := newTestTxConfig(t) + txConfig, cdc := newTestTxConfig() kb, err := keyring.New(t.Name(), "test", t.TempDir(), nil, cdc) require.NoError(t, err) @@ -207,7 +212,7 @@ func TestMnemonicInMemo(t *testing.T) { } func TestSign(t *testing.T) { - txConfig, cdc := newTestTxConfig(t) + txConfig, cdc := newTestTxConfig() requireT := require.New(t) path := hd.CreateHDPath(118, 0, 0).String() kb, err := keyring.New(t.Name(), "test", t.TempDir(), nil, cdc) @@ -347,7 +352,7 @@ func TestSign(t *testing.T) { var prevSigs []signingtypes.SignatureV2 for _, tc := range testCases { t.Run(tc.name, func(t *testing.T) { - err = tx.Sign(nil, tc.txf, tc.from, tc.txb, tc.overwrite) //nolint:staticcheck + err = tx.Sign(context.TODO(), tc.txf, tc.from, tc.txb, tc.overwrite) if len(tc.expectedPKs) == 0 { requireT.Error(err) } else { @@ -363,7 +368,7 @@ func TestSign(t *testing.T) { } func TestPreprocessHook(t *testing.T) { - txConfig, cdc := newTestTxConfig(t) + txConfig, cdc := newTestTxConfig() requireT := require.New(t) path := hd.CreateHDPath(118, 0, 0).String() kb, err := keyring.New(t.Name(), "test", t.TempDir(), nil, cdc) @@ -418,7 +423,7 @@ func TestPreprocessHook(t *testing.T) { txb, err := txfDirect.BuildUnsignedTx(msg1, msg2) requireT.NoError(err) - err = tx.Sign(nil, txfDirect, from, txb, false) //nolint:staticcheck + err = tx.Sign(context.TODO(), txfDirect, from, txb, false) requireT.NoError(err) // Run preprocessing diff --git a/client/tx_config.go b/client/tx_config.go index 5c5fd2695e40..2d56976a63b0 100644 --- a/client/tx_config.go +++ b/client/tx_config.go @@ -1,6 +1,7 @@ package client import ( + txsigning "cosmossdk.io/x/tx/signing" sdk "github.com/cosmos/cosmos-sdk/types" "github.com/cosmos/cosmos-sdk/types/tx" signingtypes "github.com/cosmos/cosmos-sdk/types/tx/signing" @@ -27,7 +28,7 @@ type ( NewTxBuilder() TxBuilder WrapTxBuilder(sdk.Tx) (TxBuilder, error) - SignModeHandler() signing.SignModeHandler + SignModeHandler() *txsigning.HandlerMap } // TxBuilder defines an interface which an application-defined concrete transaction diff --git a/client/v2/autocli/app.go b/client/v2/autocli/app.go index d42838765f84..280afce7e979 100644 --- a/client/v2/autocli/app.go +++ b/client/v2/autocli/app.go @@ -132,7 +132,7 @@ func (appOptions AppOptions) EnhanceRootCommandWithBuilder(rootCmd *cobra.Comman enhanceMsg := func(cmd *cobra.Command, modOpts *autocliv1.ModuleOptions, moduleName string) error { txCmdDesc := modOpts.Tx if txCmdDesc != nil { - subCmd := topLevelCmd(moduleName, fmt.Sprintf("Transations commands for the %s module", moduleName)) + subCmd := topLevelCmd(moduleName, fmt.Sprintf("Transactions commands for the %s module", moduleName)) err := builder.AddQueryServiceCommands(cmd, txCmdDesc) if err != nil { return err diff --git a/client/v2/autocli/common.go b/client/v2/autocli/common.go index d7a462ff23bf..610d59c9e5e0 100644 --- a/client/v2/autocli/common.go +++ b/client/v2/autocli/common.go @@ -121,5 +121,5 @@ func (b *Builder) outOrStdoutFormat(cmd *cobra.Command, out []byte) error { } _, err = fmt.Fprintln(cmd.OutOrStdout(), string(out)) - return nil + return err } diff --git a/client/v2/autocli/common_test.go b/client/v2/autocli/common_test.go index a625d3068e57..98730c3f998a 100644 --- a/client/v2/autocli/common_test.go +++ b/client/v2/autocli/common_test.go @@ -49,7 +49,8 @@ func testExecCommon(t *testing.T, buildModuleCommand func(string, *Builder) (*co Builder: flag.Builder{ GetClientConn: func() (grpc.ClientConnInterface, error) { return conn, nil - }}, + }, + }, GetClientConn: func(*cobra.Command) (grpc.ClientConnInterface, error) { return conn, nil }, diff --git a/client/v2/autocli/flag/binary.go b/client/v2/autocli/flag/binary.go new file mode 100644 index 000000000000..901b400eb92d --- /dev/null +++ b/client/v2/autocli/flag/binary.go @@ -0,0 +1,63 @@ +package flag + +import ( + "context" + "encoding/base64" + "encoding/hex" + "os" + + "github.com/cockroachdb/errors" + "google.golang.org/protobuf/reflect/protoreflect" +) + +type binaryType struct{} + +var _ Value = (*fileBinaryValue)(nil) + +func (f binaryType) NewValue(_ context.Context, _ *Builder) Value { + return &fileBinaryValue{} +} + +func (f binaryType) DefaultValue() string { + return "" +} + +// fileBinaryValue is a Value that holds a binary file. +type fileBinaryValue struct { + value []byte +} + +func (f *fileBinaryValue) Get(protoreflect.Value) (protoreflect.Value, error) { + return protoreflect.ValueOfBytes(f.value), nil +} + +func (f *fileBinaryValue) String() string { + return string(f.value) +} + +// Set implements the flag.Value interface for binary files, with exceptions. +// If the input string is a valid file path, the value will be the content of that file. +// If the input string is a valid hex or base64 string, the value will be the decoded form of that string. +// If the input string is not a valid file path, hex string, or base64 string, Set will return an error. +func (f *fileBinaryValue) Set(s string) error { + if data, err := os.ReadFile(s); err == nil { + f.value = data + return nil + } + + if data, err := hex.DecodeString(s); err == nil { + f.value = data + return nil + } + + if data, err := base64.StdEncoding.DecodeString(s); err == nil { + f.value = data + return nil + } + + return errors.New("input string is neither a valid file path, hex, or base64 encoded") +} + +func (f *fileBinaryValue) Type() string { + return "binary" +} diff --git a/client/v2/autocli/flag/builder.go b/client/v2/autocli/flag/builder.go index 31c2389a6fc6..5b4ae5f7eca6 100644 --- a/client/v2/autocli/flag/builder.go +++ b/client/v2/autocli/flag/builder.go @@ -34,6 +34,7 @@ func (b *Builder) init() { b.messageFlagTypes = map[protoreflect.FullName]Type{} b.messageFlagTypes["google.protobuf.Timestamp"] = timestampType{} b.messageFlagTypes["google.protobuf.Duration"] = durationType{} + b.messageFlagTypes["cosmos.base.v1beta1.Coin"] = coinType{} } if b.scalarFlagTypes == nil { diff --git a/client/v2/autocli/flag/coin.go b/client/v2/autocli/flag/coin.go new file mode 100644 index 000000000000..f2abd593ed56 --- /dev/null +++ b/client/v2/autocli/flag/coin.go @@ -0,0 +1,48 @@ +package flag + +import ( + "context" + + basev1beta1 "cosmossdk.io/api/cosmos/base/v1beta1" + "cosmossdk.io/core/coins" + "google.golang.org/protobuf/reflect/protoreflect" +) + +type coinType struct{} + +type coinValue struct { + value *basev1beta1.Coin +} + +func (c coinType) NewValue(_ context.Context, _ *Builder) Value { + return &coinValue{} +} + +func (c coinType) DefaultValue() string { + stringCoin, _ := coins.FormatCoins([]*basev1beta1.Coin{}, nil) + return stringCoin +} + +func (c *coinValue) Get(protoreflect.Value) (protoreflect.Value, error) { + if c.value == nil { + return protoreflect.Value{}, nil + } + return protoreflect.ValueOfMessage(c.value.ProtoReflect()), nil +} + +func (c *coinValue) String() string { + return c.value.String() +} + +func (c *coinValue) Set(stringValue string) error { + coin, err := coins.ParseCoin(stringValue) + if err != nil { + return err + } + c.value = coin + return nil +} + +func (c *coinValue) Type() string { + return "cosmos.base.v1beta1.Coin" +} diff --git a/client/v2/autocli/flag/duration.go b/client/v2/autocli/flag/duration.go index 5e02c00d29e6..cf9fe67af495 100644 --- a/client/v2/autocli/flag/duration.go +++ b/client/v2/autocli/flag/duration.go @@ -10,11 +10,11 @@ import ( type durationType struct{} -func (t durationType) NewValue(context.Context, *Builder) Value { +func (d durationType) NewValue(context.Context, *Builder) Value { return &durationValue{} } -func (t durationType) DefaultValue() string { +func (d durationType) DefaultValue() string { return "" } @@ -22,30 +22,30 @@ type durationValue struct { value *durationpb.Duration } -func (a durationValue) Get(protoreflect.Value) (protoreflect.Value, error) { - if a.value == nil { +func (d durationValue) Get(protoreflect.Value) (protoreflect.Value, error) { + if d.value == nil { return protoreflect.Value{}, nil } - return protoreflect.ValueOfMessage(a.value.ProtoReflect()), nil + return protoreflect.ValueOfMessage(d.value.ProtoReflect()), nil } -func (v durationValue) String() string { - if v.value == nil { +func (d durationValue) String() string { + if d.value == nil { return "" } - return v.value.AsDuration().String() + return d.value.AsDuration().String() } -func (v *durationValue) Set(s string) error { +func (d *durationValue) Set(s string) error { dur, err := time.ParseDuration(s) if err != nil { return err } - v.value = durationpb.New(dur) + d.value = durationpb.New(dur) return nil } -func (v durationValue) Type() string { +func (d durationValue) Type() string { return "duration" } diff --git a/client/v2/autocli/flag/field.go b/client/v2/autocli/flag/field.go index b2c385ac95da..40577e4ee7eb 100644 --- a/client/v2/autocli/flag/field.go +++ b/client/v2/autocli/flag/field.go @@ -98,6 +98,8 @@ func (b *Builder) resolveFlagTypeBasic(field protoreflect.FieldDescriptor) Type } switch field.Kind() { + case protoreflect.BytesKind: + return binaryType{} case protoreflect.EnumKind: return enumType{enum: field.Enum()} case protoreflect.MessageKind: diff --git a/client/v2/autocli/flag/simple.go b/client/v2/autocli/flag/simple.go index d4ed6d4464e3..a64c565e22f4 100644 --- a/client/v2/autocli/flag/simple.go +++ b/client/v2/autocli/flag/simple.go @@ -7,9 +7,6 @@ import ( func bindSimpleFlag(flagSet *pflag.FlagSet, kind protoreflect.Kind, name, shorthand, usage string) HasValue { switch kind { - case protoreflect.BytesKind: - val := flagSet.BytesBase64P(name, shorthand, nil, usage) - return newSimpleValue(val, protoreflect.ValueOfBytes) case protoreflect.StringKind: val := flagSet.StringP(name, shorthand, "", usage) return newSimpleValue(val, protoreflect.ValueOfString) diff --git a/client/v2/autocli/flag/timestamp.go b/client/v2/autocli/flag/timestamp.go index 799dab4f32bf..c759c70f2178 100644 --- a/client/v2/autocli/flag/timestamp.go +++ b/client/v2/autocli/flag/timestamp.go @@ -29,22 +29,22 @@ func (t timestampValue) Get(protoreflect.Value) (protoreflect.Value, error) { return protoreflect.ValueOfMessage(t.value.ProtoReflect()), nil } -func (v timestampValue) String() string { - if v.value == nil { +func (t timestampValue) String() string { + if t.value == nil { return "" } - return v.value.AsTime().Format(time.RFC3339) + return t.value.AsTime().Format(time.RFC3339) } -func (v *timestampValue) Set(s string) error { - t, err := time.Parse(time.RFC3339, s) +func (t *timestampValue) Set(s string) error { + time, err := time.Parse(time.RFC3339, s) if err != nil { return err } - v.value = timestamppb.New(t) + t.value = timestamppb.New(time) return nil } -func (v timestampValue) Type() string { +func (t timestampValue) Type() string { return "timestamp (RFC 3339)" } diff --git a/client/v2/autocli/msg.go b/client/v2/autocli/msg.go index 14b5e8113be6..c15d750756d4 100644 --- a/client/v2/autocli/msg.go +++ b/client/v2/autocli/msg.go @@ -19,7 +19,7 @@ func (b *Builder) BuildMsgCommand(moduleOptions map[string]*autocliv1.ModuleOpti enhanceMsg := func(cmd *cobra.Command, modOpts *autocliv1.ModuleOptions, moduleName string) error { txCmdDesc := modOpts.Tx if txCmdDesc != nil { - subCmd := topLevelCmd(moduleName, fmt.Sprintf("Transations commands for the %s module", moduleName)) + subCmd := topLevelCmd(moduleName, fmt.Sprintf("Transactions commands for the %s module", moduleName)) err := b.AddMsgServiceCommands(subCmd, txCmdDesc) if err != nil { return err diff --git a/client/v2/autocli/msg_test.go b/client/v2/autocli/msg_test.go index b46c11974c16..1bd0d11bc70a 100644 --- a/client/v2/autocli/msg_test.go +++ b/client/v2/autocli/msg_test.go @@ -17,7 +17,7 @@ import ( ) var buildModuleMsgCommand = func(moduleName string, b *Builder) (*cobra.Command, error) { - cmd := topLevelCmd(moduleName, fmt.Sprintf("Transations commands for the %s module", moduleName)) + cmd := topLevelCmd(moduleName, fmt.Sprintf("Transactions commands for the %s module", moduleName)) err := b.AddMsgServiceCommands(cmd, testCmdMsgDesc) return cmd, err @@ -102,7 +102,7 @@ var testCmdMsgDesc = &autocliv1.ServiceCommandDescriptor{ func TestMsgOptions(t *testing.T) { conn := testExecCommon(t, buildModuleMsgCommand, - "send", "5", "6", `{"denom":"foo","amount":"1"}`, + "send", "5", "6", "1foo", "--uint32", "7", "--u64", "8", "--output", "json", @@ -118,12 +118,12 @@ func TestMsgOptions(t *testing.T) { func TestMsgOutputFormat(t *testing.T) { conn := testExecCommon(t, buildModuleMsgCommand, - "send", "5", "6", `{"denom":"foo","amount":"1"}`, + "send", "5", "6", "1foo", "--output", "json", ) assert.Assert(t, strings.Contains(conn.out.String(), "{")) conn = testExecCommon(t, buildModuleMsgCommand, - "send", "5", "6", `{"denom":"foo","amount":"1"}`, + "send", "5", "6", "1foo", "--output", "text", ) @@ -164,8 +164,8 @@ func TestEverythingMsg(t *testing.T) { "send", "1", "abc", - `{"denom":"foo","amount":"1234"}`, - `{"denom":"bar","amount":"4321"}`, + "1234foo", + "4321foo", "--output", "json", "--a-bool", "--an-enum", "two", @@ -177,7 +177,7 @@ func TestEverythingMsg(t *testing.T) { "--i64", "-234602347", "--str", "def", "--timestamp", "2019-01-02T00:01:02Z", - "--a-coin", `{"denom":"foo","amount":"100000"}`, + "--a-coin", "10000000foo", "--an-address", "cosmos1y74p8wyy4enfhfn342njve6cjmj5c8dtl6emdk", "--bz", "c2RncXdlZndkZ3NkZw==", "--page-count-total", @@ -281,7 +281,7 @@ func TestErrorBuildMsgCommand(t *testing.T) { func TestNotFoundErrorsMsg(t *testing.T) { b := &Builder{} buildModuleMsgCommand := func(moduleName string, cmdDescriptor *autocliv1.ServiceCommandDescriptor) (*cobra.Command, error) { - cmd := topLevelCmd(moduleName, fmt.Sprintf("Transations commands for the %s module", moduleName)) + cmd := topLevelCmd(moduleName, fmt.Sprintf("Transactions commands for the %s module", moduleName)) err := b.AddMsgServiceCommands(cmd, cmdDescriptor) return cmd, err @@ -331,7 +331,7 @@ func TestEnhanceMessageCommand(t *testing.T) { enhanceMsg := func(cmd *cobra.Command, modOpts *autocliv1.ModuleOptions, moduleName string) error { txCmdDesc := modOpts.Tx if txCmdDesc != nil { - subCmd := topLevelCmd(moduleName, fmt.Sprintf("Transations commands for the %s module", moduleName)) + subCmd := topLevelCmd(moduleName, fmt.Sprintf("Transactions commands for the %s module", moduleName)) err := b.AddMsgServiceCommands(cmd, txCmdDesc) if err != nil { return err @@ -367,7 +367,3 @@ func TestEnhanceMessageCommand(t *testing.T) { err = b.enhanceCommandCommon(cmd, options, customCommands, enhanceMsg) assert.NilError(t, err) } - -type testMessageServer struct { - testpb.UnimplementedMsgServer -} diff --git a/client/v2/autocli/query_test.go b/client/v2/autocli/query_test.go index d514a3899a03..434543ff9ff5 100644 --- a/client/v2/autocli/query_test.go +++ b/client/v2/autocli/query_test.go @@ -4,6 +4,7 @@ import ( "bytes" "context" "fmt" + "os" "strings" "testing" @@ -72,6 +73,15 @@ var testCmdDesc = &autocliv1.ServiceCommandDescriptor{ "hidden_bool": { Hidden: true, }, + "a_coin": { + Usage: "some random coin", + }, + "duration": { + Usage: "some random duration", + }, + "bz": { + Usage: "some bytes", + }, }, }, }, @@ -98,13 +108,26 @@ var testCmdDesc = &autocliv1.ServiceCommandDescriptor{ }, } +func TestCoin(t *testing.T) { + conn := testExecCommon(t, buildModuleQueryCommand, + "echo", + "1", + "abc", + "1234foo", + "4321bar", + "--a-coin", "100000foo", + "--duration", "4h3s", + ) + assert.DeepEqual(t, conn.lastRequest, conn.lastResponse.(*testpb.EchoResponse).Request, protocmp.Transform()) +} + func TestEverything(t *testing.T) { conn := testExecCommon(t, buildModuleQueryCommand, "echo", "1", "abc", - `{"denom":"foo","amount":"1234"}`, - `{"denom":"bar","amount":"4321"}`, + "123.123123124foo", + "4321bar", "--a-bool", "--an-enum", "one", "--a-message", `{"bar":"abc", "baz":-3}`, @@ -115,7 +138,7 @@ func TestEverything(t *testing.T) { "--i64", "-234602347", "--str", "def", "--timestamp", "2019-01-02T00:01:02Z", - "--a-coin", `{"denom":"foo","amount":"100000"}`, + "--a-coin", "100000foo", "--an-address", "cosmos1y74p8wyy4enfhfn342njve6cjmj5c8dtl6emdk", "--bz", "c2RncXdlZndkZ3NkZw==", "--page-count-total", @@ -140,13 +163,16 @@ func TestEverything(t *testing.T) { "--uints", "1,2,3", "--uints", "4", ) + errOut := conn.errorOut.String() + res := conn.out.String() + fmt.Println(errOut, res) assert.DeepEqual(t, conn.lastRequest, conn.lastResponse.(*testpb.EchoResponse).Request, protocmp.Transform()) } func TestJSONParsing(t *testing.T) { conn := testExecCommon(t, buildModuleQueryCommand, "echo", - "1", "abc", `{"denom":"foo","amount":"1"}`, + "1", "abc", "1foo", "--some-messages", `{"bar":"baz"}`, "-u", "27", // shorthand ) @@ -154,18 +180,17 @@ func TestJSONParsing(t *testing.T) { conn = testExecCommon(t, buildModuleQueryCommand, "echo", - "1", "abc", `{"denom":"foo","amount":"1"}`, + "1", "abc", "1foo", "--some-messages", "testdata/some_message.json", "-u", "27", // shorthand ) assert.DeepEqual(t, conn.lastRequest, conn.lastResponse.(*testpb.EchoResponse).Request, protocmp.Transform()) - } func TestOptions(t *testing.T) { conn := testExecCommon(t, buildModuleQueryCommand, "echo", - "1", "abc", `{"denom":"foo","amount":"1"}`, + "1", "abc", "123foo", "-u", "27", // shorthand "--u64", "5", // no opt default value ) @@ -175,24 +200,92 @@ func TestOptions(t *testing.T) { assert.Equal(t, uint64(5), lastReq.U64) // no opt default value got set } +func TestBinaryFlag(t *testing.T) { + // Create a temporary file with some content + tempFile, err := os.Open("testdata/file.test") + if err != nil { + t.Fatal(err) + } + content := []byte("this is just a test file") + if err := tempFile.Close(); err != nil { + t.Fatal(err) + } + + // Test cases + tests := []struct { + name string + input string + expected []byte + hasError bool + err string + }{ + { + name: "Valid file path with extension", + input: tempFile.Name(), + expected: content, + hasError: false, + err: "", + }, + { + name: "Valid hex-encoded string", + input: "68656c6c6f20776f726c64", + expected: []byte("hello world"), + hasError: false, + err: "", + }, + { + name: "Valid base64-encoded string", + input: "SGVsbG8gV29ybGQ=", + expected: []byte("Hello World"), + hasError: false, + err: "", + }, + { + name: "Invalid input (not a file path or encoded string)", + input: "not a file or encoded string", + expected: nil, + hasError: true, + err: "input string is neither a valid file path, hex, or base64 encoded", + }, + } + + // Run test cases + for _, tc := range tests { + t.Run(tc.name, func(t *testing.T) { + conn := testExecCommon(t, buildModuleQueryCommand, + "echo", + "1", "abc", `{"denom":"foo","amount":"1"}`, + "--bz", tc.input, + ) + errorOut := conn.errorOut.String() + if errorOut == "" { + lastReq := conn.lastRequest.(*testpb.EchoRequest) + assert.DeepEqual(t, tc.expected, lastReq.Bz) + } else { + assert.Assert(t, strings.Contains(conn.errorOut.String(), tc.err)) + } + }) + } +} + func TestAddressValidation(t *testing.T) { conn := testExecCommon(t, buildModuleQueryCommand, "echo", - "1", "abc", `{"denom":"foo","amount":"1"}`, + "1", "abc", "1foo", "--an-address", "cosmos1y74p8wyy4enfhfn342njve6cjmj5c8dtl6emdk", ) assert.Equal(t, "", conn.errorOut.String()) conn = testExecCommon(t, buildModuleQueryCommand, "echo", - "1", "abc", `{"denom":"foo","amount":"1"}`, + "1", "abc", "1foo", "--an-address", "regen1y74p8wyy4enfhfn342njve6cjmj5c8dtl6emdk", ) assert.Assert(t, strings.Contains(conn.errorOut.String(), "Error: invalid argument")) conn = testExecCommon(t, buildModuleQueryCommand, "echo", - "1", "abc", `{"denom":"foo","amount":"1"}`, + "1", "abc", "1foo", "--an-address", "cosmps1BAD_ENCODING", ) assert.Assert(t, strings.Contains(conn.errorOut.String(), "Error: invalid argument")) @@ -201,13 +294,13 @@ func TestAddressValidation(t *testing.T) { func TestOutputFormat(t *testing.T) { conn := testExecCommon(t, buildModuleQueryCommand, "echo", - "1", "abc", `{"denom":"foo","amount":"1"}`, + "1", "abc", "1foo", "--output", "json", ) assert.Assert(t, strings.Contains(conn.out.String(), "{")) conn = testExecCommon(t, buildModuleQueryCommand, "echo", - "1", "abc", `{"denom":"foo","amount":"1"}`, + "1", "abc", "1foo", "--output", "text", ) fmt.Println(conn.out.String()) @@ -319,7 +412,7 @@ type testClientConn struct { errorOut *bytes.Buffer } -func (t *testClientConn) Invoke(ctx context.Context, method string, args interface{}, reply interface{}, opts ...grpc.CallOption) error { +func (t *testClientConn) Invoke(ctx context.Context, method string, args, reply interface{}, opts ...grpc.CallOption) error { err := t.ClientConn.Invoke(ctx, method, args, reply, opts...) t.lastRequest = args t.lastResponse = reply diff --git a/client/v2/autocli/testdata/file.test b/client/v2/autocli/testdata/file.test new file mode 100644 index 000000000000..2808f24d9df9 --- /dev/null +++ b/client/v2/autocli/testdata/file.test @@ -0,0 +1 @@ +this is just a test file \ No newline at end of file diff --git a/client/v2/autocli/testdata/help-deprecated-msg.golden b/client/v2/autocli/testdata/help-deprecated-msg.golden index 8836c5101ea3..810a532a6036 100644 --- a/client/v2/autocli/testdata/help-deprecated-msg.golden +++ b/client/v2/autocli/testdata/help-deprecated-msg.golden @@ -6,7 +6,7 @@ Usage: Flags: --a-bool - --a-coin cosmos.base.v1beta1.Coin (json) + --a-coin cosmos.base.v1beta1.Coin --a-message testpb.AMessage (json) -a, --account-number uint The account number of the signing account (offline mode only) --an-address bech32 account address key name @@ -14,7 +14,7 @@ Flags: --aux Generate aux signer data instead of sending a tx --bools bools (default []) -b, --broadcast-mode string Transaction broadcasting mode (sync|async) (default "sync") - --bz bytesBase64 + --bz binary --chain-id string The network chain ID --deprecated-field string --dry-run ignore the --gas flag and perform a simulation of a transaction, but don't broadcast it (when enabled, the local Keybase is not accessible) @@ -41,13 +41,13 @@ Flags: --offline Offline mode (does not allow any online functionality) -o, --output string Output format (text|json) (default "json") --page-count-total - --page-key bytesBase64 + --page-key binary --page-limit uint --page-offset uint --page-reverse --positional1 int32 --positional2 string - --positional3-varargs cosmos.base.v1beta1.Coin (json) (repeated) + --positional3-varargs cosmos.base.v1beta1.Coin (repeated) -s, --sequence uint The sequence number of the signing account (offline mode only) --shorthand-deprecated-field string --sign-mode string Choose sign mode (direct|amino-json|direct-aux), this is an advanced feature diff --git a/client/v2/autocli/testdata/help-deprecated.golden b/client/v2/autocli/testdata/help-deprecated.golden index e781139e8e2c..963da0986bec 100644 --- a/client/v2/autocli/testdata/help-deprecated.golden +++ b/client/v2/autocli/testdata/help-deprecated.golden @@ -4,12 +4,12 @@ Usage: Flags: --a-bool - --a-coin cosmos.base.v1beta1.Coin (json) + --a-coin cosmos.base.v1beta1.Coin --a-message testpb.AMessage (json) --an-address bech32 account address key name --an-enum Enum (unspecified | one | two | five | neg-three) (default unspecified) --bools bools (default []) - --bz bytesBase64 + --bz binary --deprecated-field string --duration duration --durations duration (repeated) @@ -24,13 +24,13 @@ Flags: --node string : to CometBFT RPC interface for this chain (default "tcp://localhost:26657") -o, --output string Output format (text|json) (default "text") --page-count-total - --page-key bytesBase64 + --page-key binary --page-limit uint --page-offset uint --page-reverse --positional1 int32 --positional2 string - --positional3-varargs cosmos.base.v1beta1.Coin (json) (repeated) + --positional3-varargs cosmos.base.v1beta1.Coin (repeated) --shorthand-deprecated-field string --some-messages testpb.AMessage (json) (repeated) --str string diff --git a/client/v2/autocli/testdata/help-echo-msg.golden b/client/v2/autocli/testdata/help-echo-msg.golden index aaca2983aa25..b029bd2efe20 100644 --- a/client/v2/autocli/testdata/help-echo-msg.golden +++ b/client/v2/autocli/testdata/help-echo-msg.golden @@ -11,7 +11,7 @@ send 1 abc {} Flags: --a-bool - --a-coin cosmos.base.v1beta1.Coin (json) + --a-coin cosmos.base.v1beta1.Coin --a-message testpb.AMessage (json) -a, --account-number uint The account number of the signing account (offline mode only) --an-address bech32 account address key name @@ -19,7 +19,7 @@ Flags: --aux Generate aux signer data instead of sending a tx --bools bools (default []) -b, --broadcast-mode string Transaction broadcasting mode (sync|async) (default "sync") - --bz bytesBase64 + --bz binary --chain-id string The network chain ID --deprecated-field string (DEPRECATED: don't use this) --dry-run ignore the --gas flag and perform a simulation of a transaction, but don't broadcast it (when enabled, the local Keybase is not accessible) @@ -45,7 +45,7 @@ Flags: --offline Offline mode (does not allow any online functionality) -o, --output string Output format (text|json) (default "json") --page-count-total - --page-key bytesBase64 + --page-key binary --page-limit uint --page-offset uint --page-reverse diff --git a/client/v2/autocli/testdata/help-echo.golden b/client/v2/autocli/testdata/help-echo.golden index 7728612c2344..9e5f52f6da78 100644 --- a/client/v2/autocli/testdata/help-echo.golden +++ b/client/v2/autocli/testdata/help-echo.golden @@ -11,14 +11,14 @@ echo 1 abc {} Flags: --a-bool - --a-coin cosmos.base.v1beta1.Coin (json) + --a-coin cosmos.base.v1beta1.Coin some random coin --a-message testpb.AMessage (json) --an-address bech32 account address key name --an-enum Enum (unspecified | one | two | five | neg-three) (default unspecified) --bools bools (default []) - --bz bytesBase64 + --bz binary some bytes --deprecated-field string (DEPRECATED: don't use this) - --duration duration + --duration duration some random duration --durations duration (repeated) --enums Enum (unspecified | one | two | five | neg-three) (repeated) --grpc-addr string the gRPC endpoint to use for this chain @@ -30,7 +30,7 @@ Flags: --node string : to CometBFT RPC interface for this chain (default "tcp://localhost:26657") -o, --output string Output format (text|json) (default "text") --page-count-total - --page-key bytesBase64 + --page-key binary --page-limit uint --page-offset uint --page-reverse diff --git a/client/v2/autocli/testdata/help-toplevel-msg.golden b/client/v2/autocli/testdata/help-toplevel-msg.golden index 12fdc0fbdc4f..0eac1e006f1f 100644 --- a/client/v2/autocli/testdata/help-toplevel-msg.golden +++ b/client/v2/autocli/testdata/help-toplevel-msg.golden @@ -1,4 +1,4 @@ -Transations commands for the test module +Transactions commands for the test module Usage: test [flags] diff --git a/client/v2/go.mod b/client/v2/go.mod index aaa1b715833d..cc0c833ce124 100644 --- a/client/v2/go.mod +++ b/client/v2/go.mod @@ -3,13 +3,13 @@ module cosmossdk.io/client/v2 go 1.20 require ( - cosmossdk.io/api v0.3.2-0.20230313131911-55bf5d4efbe7 - cosmossdk.io/core v0.6.1 + cosmossdk.io/api v0.4.0 + cosmossdk.io/core v0.6.2-0.20230323161322-ccd8d40119e4 cosmossdk.io/depinject v1.0.0-alpha.3 github.com/cockroachdb/errors v1.9.1 github.com/cosmos/cosmos-proto v1.0.0-beta.3 - github.com/cosmos/cosmos-sdk v0.46.0-beta2.0.20230321173237-fe77d4bca302 - github.com/spf13/cobra v1.6.1 + github.com/cosmos/cosmos-sdk v0.46.0-beta2.0.20230418140744-0dde947d0ab7 + github.com/spf13/cobra v1.7.0 github.com/spf13/pflag v1.0.5 google.golang.org/grpc v1.54.0 google.golang.org/protobuf v1.30.0 @@ -18,11 +18,12 @@ require ( ) require ( - cosmossdk.io/collections v0.0.0-20230309163709-87da587416ba // indirect + cosmossdk.io/collections v0.1.0 // indirect cosmossdk.io/errors v1.0.0-beta.7 // indirect - cosmossdk.io/log v0.1.0 // indirect + cosmossdk.io/log v1.0.0 // indirect cosmossdk.io/math v1.0.0 // indirect - cosmossdk.io/store v0.1.0-alpha.1 // indirect + cosmossdk.io/store v0.1.0-alpha.1.0.20230328185921-37ba88872dbc // indirect + cosmossdk.io/x/tx v0.5.1-0.20230407182919-057d2e09bd63 // indirect filippo.io/edwards25519 v1.0.0 // indirect github.com/99designs/go-keychain v0.0.0-20191008050251-8e49817e8af4 // indirect github.com/99designs/keyring v1.2.1 // indirect @@ -34,22 +35,22 @@ require ( github.com/btcsuite/btcd/btcec/v2 v2.3.2 // indirect github.com/cespare/xxhash/v2 v2.2.0 // indirect github.com/cockroachdb/logtags v0.0.0-20230118201751-21c54148d20b // indirect - github.com/cockroachdb/pebble v0.0.0-20230315223031-1e5ddd10389e // indirect + github.com/cockroachdb/pebble v0.0.0-20230412222916-60cfeb46143b // indirect github.com/cockroachdb/redact v1.1.3 // indirect - github.com/cometbft/cometbft v0.37.0 // indirect + github.com/cometbft/cometbft v0.37.1-0.20230411132551-3a91d155e664 // indirect github.com/confio/ics23/go v0.9.0 // indirect github.com/cosmos/btcutil v1.0.5 // indirect github.com/cosmos/cosmos-db v1.0.0-rc.1 // indirect github.com/cosmos/go-bip39 v1.0.0 // indirect - github.com/cosmos/gogoproto v1.4.6 // indirect + github.com/cosmos/gogoproto v1.4.8 // indirect github.com/cosmos/iavl v0.21.0-beta.1 // indirect github.com/cosmos/ledger-cosmos-go v0.13.0 // indirect github.com/danieljoos/wincred v1.1.2 // indirect github.com/davecgh/go-spew v1.1.1 // indirect - github.com/decred/dcrd/dcrec/secp256k1/v4 v4.1.0 // indirect + github.com/decred/dcrd/dcrec/secp256k1/v4 v4.2.0 // indirect github.com/dvsekhvalnov/jose2go v1.5.0 // indirect github.com/fsnotify/fsnotify v1.6.0 // indirect - github.com/getsentry/sentry-go v0.19.0 // indirect + github.com/getsentry/sentry-go v0.20.0 // indirect github.com/go-kit/kit v0.12.0 // indirect github.com/go-kit/log v0.2.1 // indirect github.com/go-logfmt/logfmt v0.6.0 // indirect @@ -69,11 +70,11 @@ require ( github.com/hashicorp/hcl v1.0.0 // indirect github.com/hdevalence/ed25519consensus v0.1.0 // indirect github.com/inconshreveable/mousetrap v1.1.0 // indirect - github.com/klauspost/compress v1.16.3 // indirect + github.com/klauspost/compress v1.16.5 // indirect github.com/kr/pretty v0.3.1 // indirect github.com/kr/text v0.2.0 // indirect github.com/libp2p/go-buffer-pool v0.1.0 // indirect - github.com/linxGnu/grocksdb v1.7.15 // indirect + github.com/linxGnu/grocksdb v1.7.16 // indirect github.com/magiconair/properties v1.8.7 // indirect github.com/mattn/go-colorable v0.1.13 // indirect github.com/mattn/go-isatty v0.0.18 // indirect @@ -84,13 +85,13 @@ require ( github.com/pelletier/go-toml/v2 v2.0.7 // indirect github.com/petermattis/goid v0.0.0-20230317030725-371a4b8eda08 // indirect github.com/pkg/errors v0.9.1 // indirect - github.com/prometheus/client_golang v1.14.0 // indirect + github.com/prometheus/client_golang v1.15.0 // indirect github.com/prometheus/client_model v0.3.0 // indirect github.com/prometheus/common v0.42.0 // indirect github.com/prometheus/procfs v0.9.0 // indirect github.com/rcrowley/go-metrics v0.0.0-20201227073835-cf1acfcdf475 // indirect - github.com/rogpeppe/go-internal v1.9.0 // indirect - github.com/rs/zerolog v1.29.0 // indirect + github.com/rogpeppe/go-internal v1.10.0 // indirect + github.com/rs/zerolog v1.29.1 // indirect github.com/sasha-s/go-deadlock v0.3.1 // indirect github.com/spf13/afero v1.9.3 // indirect github.com/spf13/cast v1.5.0 // indirect @@ -102,13 +103,13 @@ require ( github.com/tidwall/btree v1.6.0 // indirect github.com/zondax/hid v0.9.1 // indirect github.com/zondax/ledger-go v0.14.1 // indirect - golang.org/x/crypto v0.7.0 // indirect + golang.org/x/crypto v0.8.0 // indirect golang.org/x/exp v0.0.0-20230321023759-10a507213a29 // indirect - golang.org/x/net v0.8.0 // indirect - golang.org/x/sys v0.6.0 // indirect - golang.org/x/term v0.6.0 // indirect - golang.org/x/text v0.8.0 // indirect - google.golang.org/genproto v0.0.0-20230320184635-7606e756e683 // indirect + golang.org/x/net v0.9.0 // indirect + golang.org/x/sys v0.7.0 // indirect + golang.org/x/term v0.7.0 // indirect + golang.org/x/text v0.9.0 // indirect + google.golang.org/genproto v0.0.0-20230410155749-daa745c078e1 // indirect gopkg.in/ini.v1 v1.67.0 // indirect gopkg.in/yaml.v2 v2.4.0 // indirect gopkg.in/yaml.v3 v3.0.1 // indirect diff --git a/client/v2/go.sum b/client/v2/go.sum index 8041962d4460..ea343032470a 100644 --- a/client/v2/go.sum +++ b/client/v2/go.sum @@ -35,23 +35,24 @@ cloud.google.com/go/storage v1.6.0/go.mod h1:N7U0C8pVQ/+NIKOBQyamJIeKQKkZ+mxpohl cloud.google.com/go/storage v1.8.0/go.mod h1:Wv1Oy7z6Yz3DshWRJFhqM/UCfaWIRTdp0RXyy7KQOVs= cloud.google.com/go/storage v1.10.0/go.mod h1:FLPqc6j+Ki4BU591ie1oL6qBQGu2Bl/tZ9ullr3+Kg0= cloud.google.com/go/storage v1.14.0/go.mod h1:GrKmX003DSIwi9o29oFT7YDnHYwZoctc3fOKtUw0Xmo= -cosmossdk.io/api v0.3.2-0.20230313131911-55bf5d4efbe7 h1:4LrWK+uGP5IxznxtHHsHD+ZBs2+oZRH2loYOGjHLzZM= -cosmossdk.io/api v0.3.2-0.20230313131911-55bf5d4efbe7/go.mod h1:yVns7mKgcsG+hZW/3C5FdJtC6QYWdFIcRlKb9+5HV5g= -cosmossdk.io/collections v0.0.0-20230309163709-87da587416ba h1:S4PYij/tX3Op/hwenVEN9D+M27JRcwSwVqE3UA0BnwM= -cosmossdk.io/collections v0.0.0-20230309163709-87da587416ba/go.mod h1:lpS+G8bGC2anqzWdndTzjnQnuMO/qAcgZUkGJp4i3rc= -cosmossdk.io/core v0.6.1 h1:OBy7TI2W+/gyn2z40vVvruK3di+cAluinA6cybFbE7s= -cosmossdk.io/core v0.6.1/go.mod h1:g3MMBCBXtxbDWBURDVnJE7XML4BG5qENhs0gzkcpuFA= +cosmossdk.io/api v0.4.0 h1:x90DmdidP6EhzktAa/6/IofSHidDnPjahdlrUvyQZQw= +cosmossdk.io/api v0.4.0/go.mod h1:TWDzBhUBhI1LhSf2XSYpfIBf6D4mbLu/fvzvDfhcaYM= +cosmossdk.io/collections v0.1.0 h1:nzJGeiq32KnZroSrhB6rPifw4I85Cgmzw/YAmr4luv8= +cosmossdk.io/collections v0.1.0/go.mod h1:xbauc0YsbUF8qKMVeBZl0pFCunxBIhKN/WlxpZ3lBuo= +cosmossdk.io/core v0.6.2-0.20230323161322-ccd8d40119e4 h1:l1scDTT2VX18ZuR6P0irvT/bAP0h4297D/Lka5nz2vE= +cosmossdk.io/core v0.6.2-0.20230323161322-ccd8d40119e4/go.mod h1:J8R0E7soOpQFVqFiFd7EKepXCPpINa2n2t2EqbEsXnY= cosmossdk.io/depinject v1.0.0-alpha.3 h1:6evFIgj//Y3w09bqOUOzEpFj5tsxBqdc5CfkO7z+zfw= cosmossdk.io/depinject v1.0.0-alpha.3/go.mod h1:eRbcdQ7MRpIPEM5YUJh8k97nxHpYbc3sMUnEtt8HPWU= cosmossdk.io/errors v1.0.0-beta.7 h1:gypHW76pTQGVnHKo6QBkb4yFOJjC+sUGRc5Al3Odj1w= cosmossdk.io/errors v1.0.0-beta.7/go.mod h1:mz6FQMJRku4bY7aqS/Gwfcmr/ue91roMEKAmDUDpBfE= -cosmossdk.io/log v0.1.0 h1:Vnexi+KzUCjmqq/m93teAxjt5biWFfZ5PI1imx2IJw8= -cosmossdk.io/log v0.1.0/go.mod h1:p95Wq6mDY3SREMc4y7+QU9Uwy3nyvfpWGD1iSaFkVFs= +cosmossdk.io/log v1.0.0 h1:NGKZ/A5rd4PduDfoscgABklX557PWjQINbosZy/m3Jk= +cosmossdk.io/log v1.0.0/go.mod h1:CwX9BLiBruZb7lzLlRr3R231d/fVPUXk8gAdV4LQap0= cosmossdk.io/math v1.0.0 h1:ro9w7eKx23om2tZz/VM2Pf+z2WAbGX1yDQQOJ6iGeJw= cosmossdk.io/math v1.0.0/go.mod h1:Ygz4wBHrgc7g0N+8+MrnTfS9LLn9aaTGa9hKopuym5k= -cosmossdk.io/store v0.1.0-alpha.1 h1:NGomhLUXzAxvK4OF8+yP6eNUG5i4LwzOzx+S494pTCg= -cosmossdk.io/store v0.1.0-alpha.1/go.mod h1:kmCMbhrleCZ6rDZPY/EGNldNvPebFNyVPFYp+pv05/k= -cosmossdk.io/x/tx v0.3.1-0.20230321155358-6522dd1731b5 h1:AlvyRc7f7Py1mv254vrqjIIuykCnitHIz2T+nup3bU0= +cosmossdk.io/store v0.1.0-alpha.1.0.20230328185921-37ba88872dbc h1:9piuA+NYmhe+SyMPtMoboLw/djgDbrI3dD5TG020Tnk= +cosmossdk.io/store v0.1.0-alpha.1.0.20230328185921-37ba88872dbc/go.mod h1:UFF5rmjN7WYVfxo6ArdY/l1+yyWMURBWOmSJypGqFHQ= +cosmossdk.io/x/tx v0.5.1-0.20230407182919-057d2e09bd63 h1:zHqj2VwZ/MStFmR7SUe/7gErOFhL9v2rkjmWPB/st34= +cosmossdk.io/x/tx v0.5.1-0.20230407182919-057d2e09bd63/go.mod h1:Oh3Kh+IPOfMEILNxVd2e8SLqRrIjYHpdGBfDg4ghU/k= dmitri.shuralyov.com/gpu/mtl v0.0.0-20190408044501-666a987793e9/go.mod h1:H6x//7gZCb22OMCxBHrMx7a5I7Hp++hsVxbQ4BYO7hU= filippo.io/edwards25519 v1.0.0 h1:0wAIcmJUqRdI8IJ/3eGi5/HwXZWPujYXXlkrQogz0Ek= filippo.io/edwards25519 v1.0.0/go.mod h1:N1IkdkCkiLB6tki+MYJoSx2JTY9NUlxZE7eHn5EwJns= @@ -117,34 +118,34 @@ github.com/cockroachdb/errors v1.9.1/go.mod h1:2sxOtL2WIc096WSZqZ5h8fa17rdDq9HZO github.com/cockroachdb/logtags v0.0.0-20211118104740-dabe8e521a4f/go.mod h1:Vz9DsVWQQhf3vs21MhPMZpMGSht7O/2vFW2xusFUVOs= github.com/cockroachdb/logtags v0.0.0-20230118201751-21c54148d20b h1:r6VH0faHjZeQy818SGhaone5OnYfxFR/+AzdY3sf5aE= github.com/cockroachdb/logtags v0.0.0-20230118201751-21c54148d20b/go.mod h1:Vz9DsVWQQhf3vs21MhPMZpMGSht7O/2vFW2xusFUVOs= -github.com/cockroachdb/pebble v0.0.0-20230315223031-1e5ddd10389e h1:CDuLmyaZ1pD4OJHHtubKqgu/Byw5zAnm+gArJsyj96Q= -github.com/cockroachdb/pebble v0.0.0-20230315223031-1e5ddd10389e/go.mod h1:9lRMC4XN3/BLPtIp6kAKwIaHu369NOf2rMucPzipz50= +github.com/cockroachdb/pebble v0.0.0-20230412222916-60cfeb46143b h1:92ve6F1Pls/eqd+V+102lOMRJatgpqqsQvbT9Bl/fjg= +github.com/cockroachdb/pebble v0.0.0-20230412222916-60cfeb46143b/go.mod h1:9lRMC4XN3/BLPtIp6kAKwIaHu369NOf2rMucPzipz50= github.com/cockroachdb/redact v1.1.3 h1:AKZds10rFSIj7qADf0g46UixK8NNLwWTNdCIGS5wfSQ= github.com/cockroachdb/redact v1.1.3/go.mod h1:BVNblN9mBWFyMyqK1k3AAiSxhvhfK2oOZZ2lK+dpvRg= github.com/codegangsta/inject v0.0.0-20150114235600-33e0aa1cb7c0/go.mod h1:4Zcjuz89kmFXt9morQgcfYZAYZ5n8WHjt81YYWIwtTM= -github.com/cometbft/cometbft v0.37.0 h1:M005vBaSaugvYYmNZwJOopynQSjwLoDTwflnQ/I/eYk= -github.com/cometbft/cometbft v0.37.0/go.mod h1:Y2MMMN//O5K4YKd8ze4r9jmk4Y7h0ajqILXbH5JQFVs= +github.com/cometbft/cometbft v0.37.1-0.20230411132551-3a91d155e664 h1:BbCkbnaU3R603XpnbqvuDU8Kfv+hjhiFILOHhVFntsw= +github.com/cometbft/cometbft v0.37.1-0.20230411132551-3a91d155e664/go.mod h1:Y2MMMN//O5K4YKd8ze4r9jmk4Y7h0ajqILXbH5JQFVs= github.com/cometbft/cometbft-db v0.7.0 h1:uBjbrBx4QzU0zOEnU8KxoDl18dMNgDh+zZRUE0ucsbo= github.com/confio/ics23/go v0.9.0 h1:cWs+wdbS2KRPZezoaaj+qBleXgUk5WOQFMP3CQFGTr4= github.com/confio/ics23/go v0.9.0/go.mod h1:4LPZ2NYqnYIVRklaozjNR1FScgDJ2s5Xrp+e/mYVRak= github.com/coreos/etcd v3.3.10+incompatible/go.mod h1:uF7uidLiAD3TWHmW31ZFd/JWoc32PjwdhPthX9715RE= github.com/coreos/go-etcd v2.0.0+incompatible/go.mod h1:Jez6KQU2B/sWsbdaef3ED8NzMklzPG4d5KIOhIy30Tk= github.com/coreos/go-semver v0.2.0/go.mod h1:nnelYz7RCh+5ahJtPPxZlU+153eP4D4r3EedlOD2RNk= -github.com/coreos/go-systemd/v22 v22.3.3-0.20220203105225-a9a7ef127534/go.mod h1:Y58oyj3AT4RCenI/lSvhwexgC+NSVTIJ3seZv2GcEnc= +github.com/coreos/go-systemd/v22 v22.5.0/go.mod h1:Y58oyj3AT4RCenI/lSvhwexgC+NSVTIJ3seZv2GcEnc= github.com/cosmos/btcutil v1.0.5 h1:t+ZFcX77LpKtDBhjucvnOH8C2l2ioGsBNEQ3jef8xFk= github.com/cosmos/btcutil v1.0.5/go.mod h1:IyB7iuqZMJlthe2tkIFL33xPyzbFYP0XVdS8P5lUPis= github.com/cosmos/cosmos-db v1.0.0-rc.1 h1:SjnT8B6WKMW9WEIX32qMhnEEKcI7ZP0+G1Sa9HD3nmY= github.com/cosmos/cosmos-db v1.0.0-rc.1/go.mod h1:Dnmk3flSf5lkwCqvvjNpoxjpXzhxnCAFzKHlbaForso= github.com/cosmos/cosmos-proto v1.0.0-beta.3 h1:VitvZ1lPORTVxkmF2fAp3IiA61xVwArQYKXTdEcpW6o= github.com/cosmos/cosmos-proto v1.0.0-beta.3/go.mod h1:t8IASdLaAq+bbHbjq4p960BvcTqtwuAxid3b/2rOD6I= -github.com/cosmos/cosmos-sdk v0.46.0-beta2.0.20230321173237-fe77d4bca302 h1:wffm9LPPG/FBW/tSRdJp2DCgkJQRX+Zsbdmn4I0aWeQ= -github.com/cosmos/cosmos-sdk v0.46.0-beta2.0.20230321173237-fe77d4bca302/go.mod h1:HzOsWXtPxhO8+Y8P4Ru+G3UWx6dTkpGXU9yvT35VEuI= +github.com/cosmos/cosmos-sdk v0.46.0-beta2.0.20230418140744-0dde947d0ab7 h1:+Q/K5pdQdQjp21gIxlQgGy4dOZk9gUBSQmJCYIf1bWA= +github.com/cosmos/cosmos-sdk v0.46.0-beta2.0.20230418140744-0dde947d0ab7/go.mod h1:BPvKPN63ettXrpz67uM1rHEqX/UVVkAfceFCPyp217E= github.com/cosmos/go-bip39 v0.0.0-20180819234021-555e2067c45d/go.mod h1:tSxLoYXyBmiFeKpvmq4dzayMdCjCnu8uqmCysIGBT2Y= github.com/cosmos/go-bip39 v1.0.0 h1:pcomnQdrdH22njcAatO0yWojsUnCO3y2tNoV1cb6hHY= github.com/cosmos/go-bip39 v1.0.0/go.mod h1:RNJv0H/pOIVgxw6KS7QeX2a0Uo0aKUlfhZ4xuwvCdJw= github.com/cosmos/gogogateway v1.2.0 h1:Ae/OivNhp8DqBi/sh2A8a1D0y638GpL3tkmLQAiKxTE= -github.com/cosmos/gogoproto v1.4.6 h1:Ee7z15dWJaGlgM2rWrK8N2IX7PQcuccu8oG68jp5RL4= -github.com/cosmos/gogoproto v1.4.6/go.mod h1:VS/ASYmPgv6zkPKLjR9EB91lwbLHOzaGCirmKKhncfI= +github.com/cosmos/gogoproto v1.4.8 h1:BrHKc6WFZt8+jRV71vKSQE+JrfF+JAnzrKo2VP7wIZ4= +github.com/cosmos/gogoproto v1.4.8/go.mod h1:hnb0DIEWTv+wdNzNcqus5xCQXq5+CXauq1FJuurRfVY= github.com/cosmos/iavl v0.21.0-beta.1 h1:fBQeBc8HLZ14plJNcmGfaOXSSMLVEHvEQXiTXSD76m0= github.com/cosmos/iavl v0.21.0-beta.1/go.mod h1:25YJYzilTErJ2mKfNB3xyWL9IsCwEQdNzdIutg2mh3U= github.com/cosmos/ledger-cosmos-go v0.13.0 h1:ex0CvCxToSR7j5WjrghPu2Bu9sSXKikjnVvUryNnx4s= @@ -160,9 +161,9 @@ github.com/danieljoos/wincred v1.1.2/go.mod h1:GijpziifJoIBfYh+S7BbkdUTU4LfM+QnG github.com/davecgh/go-spew v1.1.0/go.mod h1:J7Y8YcW2NihsgmVo/mv3lAwl/skON4iLHjSsI+c5H38= github.com/davecgh/go-spew v1.1.1 h1:vj9j/u1bqnvCEfJOwUhtlOARqs3+rkHYY13jYWTU97c= github.com/davecgh/go-spew v1.1.1/go.mod h1:J7Y8YcW2NihsgmVo/mv3lAwl/skON4iLHjSsI+c5H38= -github.com/decred/dcrd/crypto/blake256 v1.0.0 h1:/8DMNYp9SGi5f0w7uCm6d6M4OU2rGFK09Y2A4Xv7EE0= -github.com/decred/dcrd/dcrec/secp256k1/v4 v4.1.0 h1:HbphB4TFFXpv7MNrT52FGrrgVXF1owhMVTHFZIlnvd4= -github.com/decred/dcrd/dcrec/secp256k1/v4 v4.1.0/go.mod h1:DZGJHZMqrU4JJqFAWUS2UO1+lbSKsdiOoYi9Zzey7Fc= +github.com/decred/dcrd/crypto/blake256 v1.0.1 h1:7PltbUIQB7u/FfZ39+DGa/ShuMyJ5ilcvdfma9wOH6Y= +github.com/decred/dcrd/dcrec/secp256k1/v4 v4.2.0 h1:8UrgZ3GkP4i/CLijOJx79Yu+etlyjdBU4sfcs2WYQMs= +github.com/decred/dcrd/dcrec/secp256k1/v4 v4.2.0/go.mod h1:v57UDF4pDQJcEfFUCRop3lJL149eHGSe9Jvczhzjo/0= github.com/desertbit/timer v0.0.0-20180107155436-c41aec40b27f h1:U5y3Y5UE0w7amNe7Z5G/twsBW0KEalRQXZzf8ufSh9I= github.com/dgraph-io/badger v1.6.0 h1:DshxFxZWXUcO0xX476VJC07Xsr6ZCBVRHKZ93Oh7Evo= github.com/dgraph-io/badger v1.6.0/go.mod h1:zwt7syl517jmP8s94KqSxTlM6IMsdhYy6psNgSztDR4= @@ -196,8 +197,8 @@ github.com/fsnotify/fsnotify v1.6.0 h1:n+5WquG0fcWoWp6xPWfHdbskMCQaFnG6PfBrh1Ky4 github.com/fsnotify/fsnotify v1.6.0/go.mod h1:sl3t1tCWJFWoRz9R8WJCbQihKKwmorjAbSClcnxKAGw= github.com/gavv/httpexpect v2.0.0+incompatible/go.mod h1:x+9tiU1YnrOvnB725RkpoLv1M62hOWzwo5OXotisrKc= github.com/getsentry/sentry-go v0.12.0/go.mod h1:NSap0JBYWzHND8oMbyi0+XZhUalc1TBdRL1M71JZW2c= -github.com/getsentry/sentry-go v0.19.0 h1:BcCH3CN5tXt5aML+gwmbFwVptLLQA+eT866fCO9wVOM= -github.com/getsentry/sentry-go v0.19.0/go.mod h1:y3+lGEFEFexZtpbG1GUE2WD/f9zGyKYwpEqryTOC/nE= +github.com/getsentry/sentry-go v0.20.0 h1:bwXW98iMRIWxn+4FgPW7vMrjmbym6HblXALmhjHmQaQ= +github.com/getsentry/sentry-go v0.20.0/go.mod h1:lc76E2QywIyW8WuBnwl8Lc4bkmQH4+w1gwTf25trprY= github.com/ghodss/yaml v1.0.0/go.mod h1:4dBDuWmgqj2HViK6kFavaiC9ZROes6MMH2rRYeMEF04= github.com/gin-contrib/sse v0.0.0-20190301062529-5545eab6dad3/go.mod h1:VJ0WA2NBN22VlZ2dKZQPAPnyWw5XTlK1KymzLKsr59s= github.com/gin-gonic/gin v1.4.0/go.mod h1:OW2EZn3DO8Ln9oIKOvM++LBO+5UPHJJDH72/q/3rZdM= @@ -354,7 +355,6 @@ github.com/ianlancetaylor/demangle v0.0.0-20200824232613-28f6c0f3b639/go.mod h1: github.com/imkira/go-interpol v1.1.0/go.mod h1:z0h2/2T3XF8kyEPpRgJ3kmNv+C43p+I/CoI+jC3w2iA= github.com/improbable-eng/grpc-web v0.15.0 h1:BN+7z6uNXZ1tQGcNAuaU1YjsLTApzkjt2tzCixLaUPQ= github.com/inconshreveable/mousetrap v1.0.0/go.mod h1:PxqpIevigyE2G7u3NXJIT2ANytuPF1OarO4DADm73n8= -github.com/inconshreveable/mousetrap v1.0.1/go.mod h1:vpF70FUmC8bwa3OWnCshd2FqLfsEA9PFc4w1p2J65bw= github.com/inconshreveable/mousetrap v1.1.0 h1:wN+x4NVGpMsO7ErUn/mUI3vEoE6Jt13X2s0bqwp9tc8= github.com/inconshreveable/mousetrap v1.1.0/go.mod h1:vpF70FUmC8bwa3OWnCshd2FqLfsEA9PFc4w1p2J65bw= github.com/iris-contrib/blackfriday v2.0.0+incompatible/go.mod h1:UzZ2bDEoaSGPbkg6SAB4att1aAwTmVIx/5gCVqeyUdI= @@ -379,8 +379,8 @@ github.com/kisielk/errcheck v1.5.0/go.mod h1:pFxgyoBC7bSaBwPgfKdkLd5X25qrDl4LWUI github.com/kisielk/gotool v1.0.0/go.mod h1:XhKaO+MFFWcvkIS/tQcRk01m1F5IRFswLeQ+oQHNcck= github.com/klauspost/compress v1.8.2/go.mod h1:RyIbtBH6LamlWaDj8nUwkbUhJ87Yi3uG0guNDohfE1A= github.com/klauspost/compress v1.9.7/go.mod h1:RyIbtBH6LamlWaDj8nUwkbUhJ87Yi3uG0guNDohfE1A= -github.com/klauspost/compress v1.16.3 h1:XuJt9zzcnaz6a16/OU53ZjWp/v7/42WcR5t2a0PcNQY= -github.com/klauspost/compress v1.16.3/go.mod h1:ntbaceVETuRiXiv4DpjP66DpAtAGkEQskQzEyD//IeE= +github.com/klauspost/compress v1.16.5 h1:IFV2oUNUzZaz+XyusxpLzpzS8Pt5rh0Z16For/djlyI= +github.com/klauspost/compress v1.16.5/go.mod h1:ntbaceVETuRiXiv4DpjP66DpAtAGkEQskQzEyD//IeE= github.com/klauspost/cpuid v1.2.1/go.mod h1:Pj4uuM528wm8OyEC2QMXAi2YiTZ96dNQPGgoMS4s3ek= github.com/konsorten/go-windows-terminal-sequences v1.0.1/go.mod h1:T0+1ngSBFLxvqU3pZ+m/2kptfBszLMUkC4ZK/EgS/cQ= github.com/kr/fs v0.1.0/go.mod h1:FFnZGqtBN9Gxj7eW1uZ42v5BccTP0vu6NEaFoC2HwRg= @@ -398,8 +398,8 @@ github.com/labstack/gommon v0.3.0/go.mod h1:MULnywXg0yavhxWKc+lOruYdAhDwPK9wf0OL github.com/lib/pq v1.10.7 h1:p7ZhMD+KsSRozJr34udlUrhboJwWAgCg34+/ZZNvZZw= github.com/libp2p/go-buffer-pool v0.1.0 h1:oK4mSFcQz7cTQIfqbe4MIj9gLW+mnanjyFtc6cdF0Y8= github.com/libp2p/go-buffer-pool v0.1.0/go.mod h1:N+vh8gMqimBzdKkSMVuydVDq+UV5QTWy5HSiZacSbPg= -github.com/linxGnu/grocksdb v1.7.15 h1:AEhP28lkeAybv5UYNYviYISpR6bJejEnKuYbnWAnxx0= -github.com/linxGnu/grocksdb v1.7.15/go.mod h1:pY55D0o+r8yUYLq70QmhdudxYvoDb9F+9puf4m3/W+U= +github.com/linxGnu/grocksdb v1.7.16 h1:Q2co1xrpdkr5Hx3Fp+f+f7fRGhQFQhvi/+226dtLmA8= +github.com/linxGnu/grocksdb v1.7.16/go.mod h1:JkS7pl5qWpGpuVb3bPqTz8nC12X3YtPZT+Xq7+QfQo4= github.com/magiconair/properties v1.8.0/go.mod h1:PppfXfuXeibc/6YijjN8zIbojt8czPbwD3XqdrwzmxQ= github.com/magiconair/properties v1.8.7 h1:IeQXZAiQcpL9mgcAe1Nu6cX9LLw6ExEHKjN0VQdvPDY= github.com/magiconair/properties v1.8.7/go.mod h1:Dhd985XPs7jluiymwWYZ0G4Z61jb3vdS329zhj2hYo0= @@ -482,8 +482,8 @@ github.com/pmezard/go-difflib v1.0.0/go.mod h1:iKH77koFhYxTK1pcRnkKkqfTogsbg7gZN github.com/prometheus/client_golang v0.9.1/go.mod h1:7SWBe2y4D6OKWSNQJUaRYU/AaXPKyh/dDVn+NZz0KFw= github.com/prometheus/client_golang v1.0.0/go.mod h1:db9x61etRT2tGnBNRi70OPL5FsnadC4Ky3P0J6CfImo= github.com/prometheus/client_golang v1.4.0/go.mod h1:e9GMxYsXl05ICDXkRhurwBS4Q3OK1iX/F2sw+iXX5zU= -github.com/prometheus/client_golang v1.14.0 h1:nJdhIvne2eSX/XRAFV9PcvFFRbrjbcTUj0VP62TMhnw= -github.com/prometheus/client_golang v1.14.0/go.mod h1:8vpkKitgIVNcqrRBWh1C4TIUQgYNtG/XQE4E/Zae36Y= +github.com/prometheus/client_golang v1.15.0 h1:5fCgGYogn0hFdhyhLbw7hEsWxufKtY9klyvdNfFlFhM= +github.com/prometheus/client_golang v1.15.0/go.mod h1:e9yaBhRPU2pPNsZwE+JdQl0KEt1N9XgF6zxWmaC0xOk= github.com/prometheus/client_model v0.0.0-20180712105110-5c3871d89910/go.mod h1:MbSGuTsp3dbXC40dX6PRTWyKYBIrTGTE9sqQNg2J8bo= github.com/prometheus/client_model v0.0.0-20190129233127-fd36f4220a90/go.mod h1:xMI15A0UPsDsEKsMN9yxemIoYk6Tm2C1GtYGdfGttqA= github.com/prometheus/client_model v0.0.0-20190812154241-14fe0d1b01d4/go.mod h1:xMI15A0UPsDsEKsMN9yxemIoYk6Tm2C1GtYGdfGttqA= @@ -506,12 +506,13 @@ github.com/rogpeppe/fastuuid v1.2.0/go.mod h1:jVj6XXZzXRy/MSR5jhDC/2q6DgLz+nrA6L github.com/rogpeppe/go-internal v1.3.0/go.mod h1:M8bDsm7K2OlrFYOpmOWEs/qY81heoFRclV5y23lUDJ4= github.com/rogpeppe/go-internal v1.6.1/go.mod h1:xXDCJY+GAPziupqXw64V24skbSoqbTEfhy4qGm1nDQc= github.com/rogpeppe/go-internal v1.8.1/go.mod h1:JeRgkft04UBgHMgCIwADu4Pn6Mtm5d4nPKWu0nJ5d+o= -github.com/rogpeppe/go-internal v1.9.0 h1:73kH8U+JUqXU8lRuOHeVHaa/SZPifC7BkcraZVejAe8= github.com/rogpeppe/go-internal v1.9.0/go.mod h1:WtVeX8xhTBvf0smdhujwtBcq4Qrzq/fJaraNFVN+nFs= +github.com/rogpeppe/go-internal v1.10.0 h1:TMyTOH3F/DB16zRVcYyreMH6GnZZrwQVAoYjRBZyWFQ= +github.com/rogpeppe/go-internal v1.10.0/go.mod h1:UQnix2H7Ngw/k4C5ijL5+65zddjncjaFoBhdsK/akog= github.com/rs/cors v1.8.3 h1:O+qNyWn7Z+F9M0ILBHgMVPuB1xTOucVd5gtaYyXBpRo= github.com/rs/xid v1.4.0/go.mod h1:trrq9SKmegXys3aeAKXMUTdJsYXVwGY3RLcfgqegfbg= -github.com/rs/zerolog v1.29.0 h1:Zes4hju04hjbvkVkOhdl2HpZa+0PmVwigmo8XoORE5w= -github.com/rs/zerolog v1.29.0/go.mod h1:NILgTygv/Uej1ra5XxGf82ZFSLk58MFGAUS2o6usyD0= +github.com/rs/zerolog v1.29.1 h1:cO+d60CHkknCbvzEWxP0S9K6KqyTjrCNUy1LdQLCGPc= +github.com/rs/zerolog v1.29.1/go.mod h1:Le6ESbR7hc+DP6Lt1THiV8CQSdkkNrd3R0XbEgp3ZBU= github.com/russross/blackfriday v1.5.2/go.mod h1:JO/DiYxRf+HjHt06OyowR9PTA263kcR/rfWxYHBV53g= github.com/russross/blackfriday/v2 v2.1.0/go.mod h1:+Rmxgy9KzJVeS9/2gXHxylqXiyQDYRxCVz55jmeOWTM= github.com/ryanuber/columnize v2.1.0+incompatible/go.mod h1:sm1tb6uqfes/u+d4ooFouqFdy9/2g9QGwK3SQygK0Ts= @@ -531,8 +532,8 @@ github.com/spf13/cast v1.3.0/go.mod h1:Qx5cxh0v+4UWYiBimWS+eyWzqEqokIECu5etghLkU github.com/spf13/cast v1.5.0 h1:rj3WzYc11XZaIZMPKmwP96zkFEnnAmV8s6XbB2aY32w= github.com/spf13/cast v1.5.0/go.mod h1:SpXXQ5YoyJw6s3/6cMTQuxvgRl3PCJiyaX9p6b155UU= github.com/spf13/cobra v0.0.5/go.mod h1:3K3wKZymM7VvHMDS9+Akkh4K60UwM26emMESw8tLCHU= -github.com/spf13/cobra v1.6.1 h1:o94oiPyS4KD1mPy2fmcYYHHfCxLqYjJOhGsCHFZtEzA= -github.com/spf13/cobra v1.6.1/go.mod h1:IOw/AERYS7UzyrGinqmz6HLUo219MORXGxhbaJUqzrY= +github.com/spf13/cobra v1.7.0 h1:hyqWnYt1ZQShIddO5kBpj3vu05/++x6tJ6dg8EC572I= +github.com/spf13/cobra v1.7.0/go.mod h1:uLxZILRyS/50WlhOIKD7W6V5bgeIt+4sICxh6uRMrb0= github.com/spf13/jwalterweatherman v1.0.0/go.mod h1:cQK4TGJAtQXfYWX+Ddv3mKDzgVb68N+wFjFa4jdeBTo= github.com/spf13/jwalterweatherman v1.1.0 h1:ue6voC5bR5F8YxI5S67j9i582FU4Qvo2bmqnqMYADFk= github.com/spf13/jwalterweatherman v1.1.0/go.mod h1:aNWZUN0dPAAO/Ljvb5BEdw96iTZ0EXowPYD95IqWIGo= @@ -617,8 +618,8 @@ golang.org/x/crypto v0.0.0-20210322153248-0c34fe9e7dc2/go.mod h1:T9bdIzuCu7OtxOm golang.org/x/crypto v0.0.0-20210421170649-83a5a9bb288b/go.mod h1:T9bdIzuCu7OtxOm1hfPfRQxPLYneinmdGuTeoZ9dtd4= golang.org/x/crypto v0.0.0-20210921155107-089bfa567519/go.mod h1:GvvjBRRGRdwPK5ydBHafDWAxML/pGHZbMvKqRZ5+Abc= golang.org/x/crypto v0.0.0-20211108221036-ceb1ce70b4fa/go.mod h1:GvvjBRRGRdwPK5ydBHafDWAxML/pGHZbMvKqRZ5+Abc= -golang.org/x/crypto v0.7.0 h1:AvwMYaRytfdeVt3u6mLaxYtErKYjxA2OXjJ1HHq6t3A= -golang.org/x/crypto v0.7.0/go.mod h1:pYwdfH91IfpZVANVyUOhSIPZaFoJGxTFbZhFTx+dXZU= +golang.org/x/crypto v0.8.0 h1:pd9TJtTueMTVQXzk8E2XESSMQDj/U7OUu0PqJqPXQjQ= +golang.org/x/crypto v0.8.0/go.mod h1:mRqEX+O9/h5TFCrQhkgjo2yKi0yYA+9ecGkdQoHrywE= golang.org/x/exp v0.0.0-20190121172915-509febef88a4/go.mod h1:CJ0aWSM057203Lf6IL+f9T1iT9GByDxfZKAQTCR3kQA= golang.org/x/exp v0.0.0-20190306152737-a1d7652674e8/go.mod h1:CJ0aWSM057203Lf6IL+f9T1iT9GByDxfZKAQTCR3kQA= golang.org/x/exp v0.0.0-20190510132918-efd6b22b2522/go.mod h1:ZjyILWgesfNpC6sMxTJOJm9Kp84zZh5NQWvqDGG3Qr8= @@ -699,8 +700,8 @@ golang.org/x/net v0.0.0-20210428140749-89ef3d95e781/go.mod h1:OJAsFXCWl8Ukc7SiCT golang.org/x/net v0.0.0-20211008194852-3b03d305991f/go.mod h1:9nx3DQGgdP8bBQD5qxJ1jj9UTztislL4KSBs9R2vV5Y= golang.org/x/net v0.0.0-20220225172249-27dd8689420f/go.mod h1:CfG3xpIq0wQ8r1q4Su4UZFWDARRcnwPjda9FqA0JpMk= golang.org/x/net v0.0.0-20220607020251-c690dde0001d/go.mod h1:XRhObCWvk6IyKnWLug+ECip1KBveYUHfp+8e9klMJ9c= -golang.org/x/net v0.8.0 h1:Zrh2ngAOFYneWTAIAPethzeaQLuHwhuBkuV6ZiRnUaQ= -golang.org/x/net v0.8.0/go.mod h1:QVkue5JL9kW//ek3r6jTKnTFis1tRmNAW2P1shuFdJc= +golang.org/x/net v0.9.0 h1:aWJ/m6xSmxWBx+V0XRHTlrYrPG56jKsLdTFmsSsCzOM= +golang.org/x/net v0.9.0/go.mod h1:d48xBJpPfHeWQsugry2m+kC02ZBRGRgulfHnEXEuWns= golang.org/x/oauth2 v0.0.0-20180821212333-d2e6202438be/go.mod h1:N/0e6XlmueqKjAGxoOufVs8QHGRruUQn6yWY3a++T0U= golang.org/x/oauth2 v0.0.0-20190226205417-e64efc72b421/go.mod h1:gOpvHmFTYa4IltrdGE7lF6nIHvwfUNPOp7c8zoXwtLw= golang.org/x/oauth2 v0.0.0-20190604053449-0f29369cfe45/go.mod h1:gOpvHmFTYa4IltrdGE7lF6nIHvwfUNPOp7c8zoXwtLw= @@ -783,12 +784,13 @@ golang.org/x/sys v0.0.0-20220412211240-33da011f77ad/go.mod h1:oPkhp1MJrh7nUepCBc golang.org/x/sys v0.0.0-20220520151302-bc2c85ada10a/go.mod h1:oPkhp1MJrh7nUepCBck5+mAzfO9JrbApNNgaTdGDITg= golang.org/x/sys v0.0.0-20220811171246-fbc7d0a398ab/go.mod h1:oPkhp1MJrh7nUepCBck5+mAzfO9JrbApNNgaTdGDITg= golang.org/x/sys v0.0.0-20220908164124-27713097b956/go.mod h1:oPkhp1MJrh7nUepCBck5+mAzfO9JrbApNNgaTdGDITg= -golang.org/x/sys v0.6.0 h1:MVltZSvRTcU2ljQOhs94SXPftV6DCNnZViHeQps87pQ= golang.org/x/sys v0.6.0/go.mod h1:oPkhp1MJrh7nUepCBck5+mAzfO9JrbApNNgaTdGDITg= +golang.org/x/sys v0.7.0 h1:3jlCCIQZPdOYu1h8BkNvLz8Kgwtae2cagcG/VamtZRU= +golang.org/x/sys v0.7.0/go.mod h1:oPkhp1MJrh7nUepCBck5+mAzfO9JrbApNNgaTdGDITg= golang.org/x/term v0.0.0-20201126162022-7de9c90e9dd1/go.mod h1:bj7SfCRtBDWHUb9snDiAeCFNEtKQo2Wmx5Cou7ajbmo= golang.org/x/term v0.0.0-20210927222741-03fcf44c2211/go.mod h1:jbD1KX2456YbFQfuXm/mYQcufACuNUgVhRMnK/tPxf8= -golang.org/x/term v0.6.0 h1:clScbb1cHjoCkyRbWwBEUZ5H/tIFu5TAXIqaZD0Gcjw= -golang.org/x/term v0.6.0/go.mod h1:m6U89DPEgQRMq3DNkDClhWw02AUbt2daBVO4cn4Hv9U= +golang.org/x/term v0.7.0 h1:BEvjmm5fURWqcfbSKTdpkDXYBrUS1c0m8agp14W48vQ= +golang.org/x/term v0.7.0/go.mod h1:P32HKFT3hSsZrRxla30E9HqToFYAQPCMs/zFMBUFqPY= golang.org/x/text v0.0.0-20170915032832-14c0d48ead0c/go.mod h1:NqM8EUOU14njkJ3fqMW+pc6Ldnwhi/IjpwHt7yyuwOQ= golang.org/x/text v0.3.0/go.mod h1:NqM8EUOU14njkJ3fqMW+pc6Ldnwhi/IjpwHt7yyuwOQ= golang.org/x/text v0.3.1-0.20180807135948-17ff2d5776d2/go.mod h1:NqM8EUOU14njkJ3fqMW+pc6Ldnwhi/IjpwHt7yyuwOQ= @@ -798,8 +800,8 @@ golang.org/x/text v0.3.4/go.mod h1:5Zoc/QRtKVWzQhOtBMvqHzDpF6irO9z98xDceosuGiQ= golang.org/x/text v0.3.5/go.mod h1:5Zoc/QRtKVWzQhOtBMvqHzDpF6irO9z98xDceosuGiQ= golang.org/x/text v0.3.6/go.mod h1:5Zoc/QRtKVWzQhOtBMvqHzDpF6irO9z98xDceosuGiQ= golang.org/x/text v0.3.7/go.mod h1:u+2+/6zg+i71rQMx5EYifcz6MCKuco9NR6JIITiCfzQ= -golang.org/x/text v0.8.0 h1:57P1ETyNKtuIjB4SRd15iJxuhj8Gc416Y78H3qgMh68= -golang.org/x/text v0.8.0/go.mod h1:e1OnstbJyHTd6l/uOt8jFFHp6TRDWZR/bV3emEE/zU8= +golang.org/x/text v0.9.0 h1:2sjJmO8cDvYveuX97RDLsxlyUxLl+GHoLxBiRdHllBE= +golang.org/x/text v0.9.0/go.mod h1:e1OnstbJyHTd6l/uOt8jFFHp6TRDWZR/bV3emEE/zU8= golang.org/x/time v0.0.0-20181108054448-85acf8d2951c/go.mod h1:tRJNPiyCQ0inRvYxbN9jk5I+vvW/OXSQhTDSoE431IQ= golang.org/x/time v0.0.0-20190308202827-9d24e82272b4/go.mod h1:tRJNPiyCQ0inRvYxbN9jk5I+vvW/OXSQhTDSoE431IQ= golang.org/x/time v0.0.0-20191024005414-555d28b269f0/go.mod h1:tRJNPiyCQ0inRvYxbN9jk5I+vvW/OXSQhTDSoE431IQ= @@ -929,8 +931,8 @@ google.golang.org/genproto v0.0.0-20201214200347-8c77b98c765d/go.mod h1:FWY/as6D google.golang.org/genproto v0.0.0-20210108203827-ffc7fda8c3d7/go.mod h1:FWY/as6DDZQgahTzZj3fqbO1CbirC29ZNUFHwi0/+no= google.golang.org/genproto v0.0.0-20210226172003-ab064af71705/go.mod h1:FWY/as6DDZQgahTzZj3fqbO1CbirC29ZNUFHwi0/+no= google.golang.org/genproto v0.0.0-20210624195500-8bfb893ecb84/go.mod h1:SzzZ/N+nwJDaO1kznhnlzqS8ocJICar6hYhVyhi++24= -google.golang.org/genproto v0.0.0-20230320184635-7606e756e683 h1:khxVcsk/FhnzxMKOyD+TDGwjbEOpcPuIpmafPGFmhMA= -google.golang.org/genproto v0.0.0-20230320184635-7606e756e683/go.mod h1:NWraEVixdDnqcqQ30jipen1STv2r/n24Wb7twVTGR4s= +google.golang.org/genproto v0.0.0-20230410155749-daa745c078e1 h1:KpwkzHKEF7B9Zxg18WzOa7djJ+Ha5DzthMyZYQfEn2A= +google.golang.org/genproto v0.0.0-20230410155749-daa745c078e1/go.mod h1:nKE/iIaLqn2bQwXBg8f1g2Ylh6r5MN5CmZvuzZCgsCU= google.golang.org/grpc v1.12.0/go.mod h1:yo6s7OP7yaDglbqo1J04qKzAhqBH6lvTonzMVmEdcZw= google.golang.org/grpc v1.19.0/go.mod h1:mqu4LbDTu4XGKhr4mRzUsmM4RtVoemTSY81AxZiDr8c= google.golang.org/grpc v1.20.1/go.mod h1:10oTOabMzJvdu6/UiuZezV6QK5dSlG84ov/aaiqXj38= diff --git a/codec/amino_codec.go b/codec/amino_codec.go index d77acbc7e8e0..2b1e02864513 100644 --- a/codec/amino_codec.go +++ b/codec/amino_codec.go @@ -1,18 +1,25 @@ package codec import ( + "fmt" + "github.com/cosmos/gogoproto/proto" + protov2 "google.golang.org/protobuf/proto" + + "github.com/cosmos/cosmos-sdk/codec/types" ) -// AminoCodec defines a codec that utilizes Codec for both binary and JSON -// encoding. +// Deprecated: AminoCodec defines a codec that utilizes Codec for both binary and JSON +// encoding. Any usage of amino should be done using the LegacyAmino type directly. +// Usage of amino with the Codec type is not well-supported and may be removed in the future. type AminoCodec struct { *LegacyAmino } var _ Codec = &AminoCodec{} -// NewAminoCodec returns a reference to a new AminoCodec +// Deprecated: NewAminoCodec returns a reference to a new AminoCodec. +// Use NewLegacyAmino instead. func NewAminoCodec(codec *LegacyAmino) *AminoCodec { return &AminoCodec{LegacyAmino: codec} } @@ -124,3 +131,21 @@ func (ac *AminoCodec) MarshalInterfaceJSON(i proto.Message) ([]byte, error) { func (ac *AminoCodec) UnmarshalInterfaceJSON(bz []byte, ptr interface{}) error { return ac.LegacyAmino.UnmarshalJSON(bz, ptr) } + +func (ac *AminoCodec) GetMsgAnySigners(*types.Any) ([]string, protov2.Message, error) { + return nil, nil, fmt.Errorf("amino codec does not support getting msg signers") +} + +func (ac *AminoCodec) GetMsgV1Signers(proto.Message) ([]string, protov2.Message, error) { + return nil, nil, fmt.Errorf("amino codec does not support getting msg signers") +} + +func (ac *AminoCodec) GetMsgV2Signers(protov2.Message) ([]string, error) { + return nil, fmt.Errorf("amino codec does not support getting msg signers") +} + +func (ac *AminoCodec) InterfaceRegistry() types.InterfaceRegistry { + panic("amino codec does not support interface registry") +} + +func (ac *AminoCodec) mustEmbedCodec() {} diff --git a/codec/codec.go b/codec/codec.go index 5fe0e98e89f3..7bdaffa69bf5 100644 --- a/codec/codec.go +++ b/codec/codec.go @@ -3,6 +3,7 @@ package codec import ( "github.com/cosmos/gogoproto/proto" "google.golang.org/grpc/encoding" + protov2 "google.golang.org/protobuf/proto" "github.com/cosmos/cosmos-sdk/codec/types" ) @@ -18,6 +19,26 @@ type ( Codec interface { BinaryCodec JSONCodec + + // InterfaceRegistry returns the interface registry. + InterfaceRegistry() types.InterfaceRegistry + + // GetMsgAnySigners returns the signers of the given message encoded in a protobuf Any + // as well as the decoded google.golang.org/protobuf/proto.Message that was used to + // extract the signers so that this can be used in other contexts. + GetMsgAnySigners(msg *types.Any) ([]string, protov2.Message, error) + + // GetMsgV2Signers returns the signers of the given message. + GetMsgV2Signers(msg protov2.Message) ([]string, error) + + // GetMsgV1Signers returns the signers of the given message plus the + // decoded google.golang.org/protobuf/proto.Message that was used to extract the + // signers so that this can be used in other contexts. + GetMsgV1Signers(msg proto.Message) ([]string, protov2.Message, error) + + // mustEmbedCodec requires that all implementations of Codec embed an official implementation from the codec + // package. This allows new methods to be added to the Codec interface without breaking backwards compatibility. + mustEmbedCodec() } BinaryCodec interface { diff --git a/codec/proto_codec.go b/codec/proto_codec.go index ed71b8f897a3..965954ae2df0 100644 --- a/codec/proto_codec.go +++ b/codec/proto_codec.go @@ -6,11 +6,14 @@ import ( "fmt" "strings" + "github.com/cosmos/cosmos-proto/anyutil" + "github.com/cosmos/gogoproto/jsonpb" + gogoproto "github.com/cosmos/gogoproto/proto" "google.golang.org/grpc/encoding" "google.golang.org/protobuf/proto" + "google.golang.org/protobuf/types/known/anypb" - "github.com/cosmos/gogoproto/jsonpb" - gogoproto "github.com/cosmos/gogoproto/proto" + "cosmossdk.io/x/tx/signing" "github.com/cosmos/cosmos-sdk/codec/types" ) @@ -26,6 +29,7 @@ type ProtoCodecMarshaler interface { // encoding. type ProtoCodec struct { interfaceRegistry types.InterfaceRegistry + getSignersCtx *signing.GetSignersContext } var ( @@ -35,7 +39,17 @@ var ( // NewProtoCodec returns a reference to a new ProtoCodec func NewProtoCodec(interfaceRegistry types.InterfaceRegistry) *ProtoCodec { - return &ProtoCodec{interfaceRegistry: interfaceRegistry} + getSignersCtx, err := signing.NewGetSignersContext( + signing.GetSignersOptions{ + ProtoFiles: interfaceRegistry, + }) + if err != nil { + panic(err) + } + return &ProtoCodec{ + interfaceRegistry: interfaceRegistry, + getSignersCtx: getSignersCtx, + } } // Marshal implements BinaryMarshaler.Marshal method. @@ -137,9 +151,7 @@ func (pc *ProtoCodec) MustUnmarshalLengthPrefixed(bz []byte, ptr gogoproto.Messa // it marshals to JSON using proto codec. // NOTE: this function must be used with a concrete type which // implements proto.Message. For interface please use the codec.MarshalInterfaceJSON -// -//nolint:stdmethods -func (pc *ProtoCodec) MarshalJSON(o gogoproto.Message) ([]byte, error) { +func (pc *ProtoCodec) MarshalJSON(o gogoproto.Message) ([]byte, error) { //nolint:stdmethods // we don't want to implement Marshaler interface if o == nil { return nil, fmt.Errorf("cannot protobuf JSON encode nil") } @@ -186,7 +198,7 @@ func (pc *ProtoCodec) MustUnmarshalJSON(bz []byte, ptr gogoproto.Message) { } } -// MarshalInterface is a convenience function for proto marshalling interfaces. It packs +// MarshalInterface is a convenience function for proto marshaling interfaces. It packs // the provided value, which must be an interface, in an Any and then marshals it to bytes. // NOTE: to marshal a concrete type, you should use Marshal instead func (pc *ProtoCodec) MarshalInterface(i gogoproto.Message) ([]byte, error) { @@ -224,7 +236,7 @@ func (pc *ProtoCodec) UnmarshalInterface(bz []byte, ptr interface{}) error { return pc.UnpackAny(any, ptr) } -// MarshalInterfaceJSON is a convenience function for proto marshalling interfaces. It +// MarshalInterfaceJSON is a convenience function for proto marshaling interfaces. It // packs the provided value in an Any and then marshals it to bytes. // NOTE: to marshal a concrete type, you should use MarshalJSON instead func (pc *ProtoCodec) MarshalInterfaceJSON(x gogoproto.Message) ([]byte, error) { @@ -265,11 +277,42 @@ func (pc *ProtoCodec) InterfaceRegistry() types.InterfaceRegistry { return pc.interfaceRegistry } +func (pc ProtoCodec) GetMsgAnySigners(msg *types.Any) ([]string, proto.Message, error) { + msgv2, err := anyutil.Unpack(&anypb.Any{ + TypeUrl: msg.TypeUrl, + Value: msg.Value, + }, pc.interfaceRegistry, nil) + if err != nil { + return nil, nil, err + } + + signers, err := pc.getSignersCtx.GetSigners(msgv2) + return signers, msgv2, err +} + +func (pc *ProtoCodec) GetMsgV2Signers(msg proto.Message) ([]string, error) { + return pc.getSignersCtx.GetSigners(msg) +} + +func (pc *ProtoCodec) GetMsgV1Signers(msg gogoproto.Message) ([]string, proto.Message, error) { + if msgV2, ok := msg.(proto.Message); ok { + signers, err := pc.getSignersCtx.GetSigners(msgV2) + return signers, msgV2, err + } + a, err := types.NewAnyWithValue(msg) + if err != nil { + return nil, nil, err + } + return pc.GetMsgAnySigners(a) +} + // GRPCCodec returns the gRPC Codec for this specific ProtoCodec func (pc *ProtoCodec) GRPCCodec() encoding.Codec { return &grpcProtoCodec{cdc: pc} } +func (pc *ProtoCodec) mustEmbedCodec() {} + var errUnknownProtoType = errors.New("codec: unknown proto type") // sentinel error // grpcProtoCodec is the implementation of the gRPC proto codec. diff --git a/codec/proto_codec_test.go b/codec/proto_codec_test.go index 9838be6b6cf2..f0591dad4ef1 100644 --- a/codec/proto_codec_test.go +++ b/codec/proto_codec_test.go @@ -5,15 +5,19 @@ import ( "reflect" "testing" + bankv1beta1 "cosmossdk.io/api/cosmos/bank/v1beta1" + basev1beta1 "cosmossdk.io/api/cosmos/base/v1beta1" "github.com/cosmos/gogoproto/proto" "github.com/stretchr/testify/require" "google.golang.org/grpc/codes" "google.golang.org/grpc/encoding" "google.golang.org/grpc/status" + protov2 "google.golang.org/protobuf/proto" "github.com/cosmos/cosmos-sdk/codec" "github.com/cosmos/cosmos-sdk/codec/types" "github.com/cosmos/cosmos-sdk/testutil/testdata" + sdk "github.com/cosmos/cosmos-sdk/types" banktypes "github.com/cosmos/cosmos-sdk/x/bank/types" ) @@ -168,3 +172,35 @@ func BenchmarkProtoCodecMarshalLengthPrefixed(b *testing.B) { b.SetBytes(int64(len(blob))) } } + +func TestGetSigners(t *testing.T) { + interfaceRegistry := types.NewInterfaceRegistry() + cdc := codec.NewProtoCodec(interfaceRegistry) + testAddr := sdk.AccAddress([]byte("test")) + testAddrStr := testAddr.String() + testAddr2 := sdk.AccAddress([]byte("test2")) + testAddrStr2 := testAddr2.String() + + msgSendV1 := banktypes.NewMsgSend(testAddr, testAddr2, sdk.NewCoins(sdk.NewCoin("foo", sdk.NewInt(1)))) + msgSendV2 := &bankv1beta1.MsgSend{ + FromAddress: testAddrStr, + ToAddress: testAddrStr2, + Amount: []*basev1beta1.Coin{{Denom: "foo", Amount: "1"}}, + } + + signers, msgSendV2Copy, err := cdc.GetMsgV1Signers(msgSendV1) + require.NoError(t, err) + require.Equal(t, []string{testAddrStr}, signers) + require.True(t, protov2.Equal(msgSendV2, msgSendV2Copy)) + + signers, err = cdc.GetMsgV2Signers(msgSendV2) + require.NoError(t, err) + require.Equal(t, []string{testAddrStr}, signers) + + msgSendAny, err := types.NewAnyWithValue(msgSendV1) + require.NoError(t, err) + signers, msgSendV2Copy, err = cdc.GetMsgAnySigners(msgSendAny) + require.NoError(t, err) + require.Equal(t, []string{testAddrStr}, signers) + require.True(t, protov2.Equal(msgSendV2, msgSendV2Copy)) +} diff --git a/codec/types/any.go b/codec/types/any.go index 5ecc297f8e6b..334bed746380 100644 --- a/codec/types/any.go +++ b/codec/types/any.go @@ -1,4 +1,3 @@ -// nolint package types import ( @@ -11,6 +10,7 @@ import ( sdkerrors "github.com/cosmos/cosmos-sdk/types/errors" ) +// nolint:revive // XXX is reqired for proto compatibility type Any struct { // A URL/resource name that uniquely identifies the type of the serialized // protocol buffer message. This string must contain at least diff --git a/codec/types/any_internal_test.go b/codec/types/any_internal_test.go index b2b12b123bdb..f413f95528f2 100644 --- a/codec/types/any_internal_test.go +++ b/codec/types/any_internal_test.go @@ -17,7 +17,7 @@ func (d Dog) Greet() string { return d.Name } func (d *Dog) Reset() { d.Name = "" } func (d *Dog) String() string { return d.Name } func (d *Dog) ProtoMessage() {} -func (d *Dog) XXX_MessageName() string { return "tests/dog" } //nolint:revive +func (d *Dog) XXX_MessageName() string { return "tests/dog" } //nolint:revive // XXX_ prefix is required type Animal interface { Greet() string diff --git a/codec/types/any_test.go b/codec/types/any_test.go index 656344414a7e..06c0f5b41896 100644 --- a/codec/types/any_test.go +++ b/codec/types/any_test.go @@ -19,7 +19,7 @@ var _ proto.Message = (*errOnMarshal)(nil) var errAlways = fmt.Errorf("always erroring") -func (eom *errOnMarshal) XXX_Marshal(b []byte, deterministic bool) ([]byte, error) { //nolint:revive +func (eom *errOnMarshal) XXX_Marshal(b []byte, deterministic bool) ([]byte, error) { //nolint:revive // XXX_ prefix is intentional return nil, errAlways } diff --git a/codec/types/interface_registry.go b/codec/types/interface_registry.go index b911cb6bf6e9..57a098e0cbe4 100644 --- a/codec/types/interface_registry.go +++ b/codec/types/interface_registry.go @@ -6,6 +6,9 @@ import ( "github.com/cosmos/gogoproto/jsonpb" "github.com/cosmos/gogoproto/proto" + "google.golang.org/protobuf/reflect/protodesc" + "google.golang.org/protobuf/reflect/protoreflect" + "google.golang.org/protobuf/reflect/protoregistry" ) // AnyUnpacker is an interface which allows safely unpacking types packed @@ -54,6 +57,18 @@ type InterfaceRegistry interface { // EnsureRegistered ensures there is a registered interface for the given concrete type. EnsureRegistered(iface interface{}) error + + protodesc.Resolver + + // RangeFiles iterates over all registered files and calls f on each one. This + // implements the part of protoregistry.Files that is needed for reflecting over + // the entire FileDescriptorSet. + RangeFiles(f func(protoreflect.FileDescriptor) bool) + + // mustEmbedInterfaceRegistry requires that all implementations of InterfaceRegistry embed an official implementation + // from this package. This allows new methods to be added to the InterfaceRegistry interface without breaking + // backwards compatibility. + mustEmbedInterfaceRegistry() } // UnpackInterfacesMessage is meant to extend protobuf types (which implement @@ -81,6 +96,7 @@ type UnpackInterfacesMessage interface { } type interfaceRegistry struct { + *protoregistry.Files interfaceNames map[string]reflect.Type interfaceImpls map[reflect.Type]interfaceMap implInterfaces map[reflect.Type]reflect.Type @@ -91,11 +107,21 @@ type interfaceMap = map[string]reflect.Type // NewInterfaceRegistry returns a new InterfaceRegistry func NewInterfaceRegistry() InterfaceRegistry { + protoFiles, err := proto.MergedRegistry() + if err != nil { + panic(err) + } + return NewInterfaceRegistryWithProtoFiles(protoFiles) +} + +// NewInterfaceRegistryWithProtoFiles returns a new InterfaceRegistry with the specified *protoregistry.Files instance. +func NewInterfaceRegistryWithProtoFiles(files *protoregistry.Files) InterfaceRegistry { return &interfaceRegistry{ interfaceNames: map[string]reflect.Type{}, interfaceImpls: map[reflect.Type]interfaceMap{}, implInterfaces: map[reflect.Type]reflect.Type{}, typeURLMap: map[string]reflect.Type{}, + Files: files, } } @@ -288,6 +314,8 @@ func (registry *interfaceRegistry) Resolve(typeURL string) (proto.Message, error return msg, nil } +func (registry *interfaceRegistry) mustEmbedInterfaceRegistry() {} + // UnpackInterfaces is a convenience function that calls UnpackInterfaces // on x if x implements UnpackInterfacesMessage func UnpackInterfaces(x interface{}, unpacker AnyUnpacker) error { diff --git a/codec/types/types_test.go b/codec/types/types_test.go index 2c24a87ce0c7..4bb3f7d609fa 100644 --- a/codec/types/types_test.go +++ b/codec/types/types_test.go @@ -44,7 +44,7 @@ var ( func (dog FakeDog) Reset() {} func (dog FakeDog) String() string { return "fakedog" } func (dog FakeDog) ProtoMessage() {} -func (dog FakeDog) XXX_MessageName() string { return proto.MessageName(&testdata.Dog{}) } //nolint:revive +func (dog FakeDog) XXX_MessageName() string { return proto.MessageName(&testdata.Dog{}) } //nolint:revive // XXX_ prefix is intentional func (dog FakeDog) Greet() string { return "fakedog" } func TestRegister(t *testing.T) { diff --git a/codec/unknownproto/unknown_fields_test.go b/codec/unknownproto/unknown_fields_test.go index 7e0af479adbe..1a8fd0affd7e 100644 --- a/codec/unknownproto/unknown_fields_test.go +++ b/codec/unknownproto/unknown_fields_test.go @@ -656,11 +656,11 @@ func TestRejectUnknownFieldsFlat(t *testing.T) { func TestPackedEncoding(t *testing.T) { data := testdata.TestRepeatedUints{Nums: []uint64{12, 13}} - marshalled, err := data.Marshal() + marshaled, err := data.Marshal() require.NoError(t, err) unmarshalled := &testdata.TestRepeatedUints{} - _, err = RejectUnknownFields(marshalled, unmarshalled, false, DefaultAnyResolver{}) + _, err = RejectUnknownFields(marshaled, unmarshalled, false, DefaultAnyResolver{}) require.NoError(t, err) } diff --git a/collections/CHANGELOG.md b/collections/CHANGELOG.md index 7958edea261a..c1180a049fdd 100644 --- a/collections/CHANGELOG.md +++ b/collections/CHANGELOG.md @@ -31,9 +31,6 @@ Ref: https://keepachangelog.com/en/1.0.0/ ## [Unreleased] -* [#14134](https://github.com/cosmos/cosmos-sdk/pull/14134) Initialise core (Prefix, KeyEncoder, ValueEncoder, Map). -* [#14351](https://github.com/cosmos/cosmos-sdk/pull/14351) Add keyset -* [#14364](https://github.com/cosmos/cosmos-sdk/pull/14364) Add sequence -* [#14468](https://github.com/cosmos/cosmos-sdk/pull/14468) Add Map.IterateRaw API. -* [#14310](https://github.com/cosmos/cosmos-sdk/pull/14310) Add Pair keys -* [#14397](https://github.com/cosmos/cosmos-sdk/pull/14397) Add IndexedMap \ No newline at end of file +## [v0.1.0](https://github.com/cosmos/cosmos-sdk/releases/tag/collections%2Fv0.1.0) + +Collections `v0.1.0` is released! Check out the [docs](https://docs.cosmos.network/main/packages/collections) to know how to use the APIs. \ No newline at end of file diff --git a/collections/README.md b/collections/README.md new file mode 100644 index 000000000000..19884abe94cd --- /dev/null +++ b/collections/README.md @@ -0,0 +1,1065 @@ +# Collections + +Collections is a library meant to simplify the experience with respect to module state handling. + +Cosmos SDK modules handle their state using the `KVStore` interface. The problem with working with +`KVStore` is that it forces you to think of state as a bytes KV pairings when in reality the majority of +state comes from complex concrete golang objects (strings, ints, structs, etc.). + +Collections allows you to work with state as if they were normal golang objects and removes the need +for you to think of your state as raw bytes in your code. + +It also allows you to migrate your existing state without causing any state breakage that forces you into +tedious and complex chain state migrations. + +## Installation + +To install collections in your cosmos-sdk chain project, run the following command: + +```shell +go get cosmossdk.io/collections +``` + +## Core types + +Collections offers 5 different APIs to work with state, which will be explored in the next sections, these APIs are: +- ``Map``: to work with typed arbitrary KV pairings. +- ``KeySet``: to work with just typed keys +- ``Item``: to work with just one typed value +- ``Sequence``: which is a monotonically increasing number. +- ``IndexedMap``: which combines ``Map`` and `KeySet` to provide a `Map` with indexing capabilities. + +## Preliminary components + +Before exploring the different collections types and their capability it is necessary to introduce +the three components that every collection shares. In fact when instantiating a collection type by doing, for example, +```collections.NewMap/collections.NewItem/...``` you will find yourself having to pass them some common arguments. + +For example, in code: + +```go +package collections + +import ( + "cosmossdk.io/collections" + storetypes "cosmossdk.io/store/types" + sdk "github.com/cosmos/cosmos-sdk/types" +) + +var AllowListPrefix = collections.NewPrefix(0) + +type Keeper struct { + Schema collections.Schema + AllowList collections.KeySet[string] +} + +func NewKeeper(storeKey *storetypes.KVStoreKey) Keeper { + sb := collections.NewSchemaBuilder(sdk.OpenKVStore(storeKey)) + + return Keeper{ + AllowList: collections.NewKeySet(sb, AllowListPrefix, "allow_list", collections.StringKey), + } +} + +``` + +Let's analyse the shared arguments, what they do, and why we need them. + +### SchemaBuilder + +The first argument passed is the ``SchemaBuilder`` + +`SchemaBuilder` is a structure that keeps track of all the state of a module, it is not required by the collections + to deal with state but it offers a dynamic and reflective way for clients to explore a module's state. + +We instantiate a ``SchemaBuilder`` by passing it a function that given the modules store key returns the module's specific store. + +We then need to pass the schema builder to every collection type we instantiate in our keeper, in our case the `AllowList`. + +### Prefix + +The second argument passed to our ``KeySet`` is a `collections.Prefix`, a prefix represents a partition of the module's `KVStore` +where all the state of a specific collection will be saved. + +Since a module can have multiple collections, the following is expected: +- module params will become a `collections.Item` +- the `AllowList` is a `collections.KeySet` + +We don't want a collection to write over the state of the other collection so we pass it a prefix, which defines a storage +partition owned by the collection. + +If you already built modules, the prefix translates to the items you were creating in your ``types/keys.go`` file, example: https://github.com/cosmos/cosmos-sdk/blob/main/x/feegrant/key.go#L27 + +your old: +```go +var ( + // FeeAllowanceKeyPrefix is the set of the kvstore for fee allowance data + // - 0x00: allowance + FeeAllowanceKeyPrefix = []byte{0x00} + + // FeeAllowanceQueueKeyPrefix is the set of the kvstore for fee allowance keys data + // - 0x01: + FeeAllowanceQueueKeyPrefix = []byte{0x01} +) +``` +becomes: +```go +var ( + // FeeAllowanceKeyPrefix is the set of the kvstore for fee allowance data + // - 0x00: allowance + FeeAllowanceKeyPrefix = collections.NewPrefix(0) + + // FeeAllowanceQueueKeyPrefix is the set of the kvstore for fee allowance keys data + // - 0x01: + FeeAllowanceQueueKeyPrefix = collections.NewPrefix(1) +) +``` + +#### Rules + +``collections.NewPrefix`` accepts either `uint8`, `string` or `[]bytes` it's good practice to use an always increasing `uint8`for disk space efficiency. + +A collection **MUST NOT** share the same prefix as another collection in the same module, and a collection prefix **MUST NEVER** start with the same prefix as another, examples: + +```go +prefix1 := collections.NewPrefix("prefix") +prefix2 := collections.NewPrefix("prefix") // THIS IS BAD! +``` + +```go +prefix1 := collections.NewPrefix("a") +prefix2 := collections.NewPrefix("aa") // prefix2 starts with the same as prefix1: BAD!!! +``` +### Human-Readable Name + +The third parameter we pass to a collection is a string, which is a human-readable name. +It is needed to make the role of a collection understandable by clients who have no clue about +what a module is storing in state. + +#### Rules + +Each collection in a module **MUST** have a unique humanised name. + +## Key and Value Codecs + +A collection is generic over the type you can use as keys or values. +This makes collections dumb, but also means that hypothetically we can store everything +that can be a go type into a collection. We are not bounded to any type of encoding (be it proto, json or whatever) + +So a collection needs to be given a way to understand how to convert your keys and values to bytes. +This is achieved through ``KeyCodec`` and `ValueCodec`, which are arguments that you pass to your +collections when you're instantiating them using the ```collections.NewMap/collections.NewItem/...``` +instantiation functions. + +NOTE: Generally speaking you will never be required to implement your own ``Key/ValueCodec`` as +the SDK and collections libraries already come with default, safe and fast implementation of those. +You might need to implement them only if you're migrating to collections and there are state layout incompatibilities. + +Let's explore an example: + +````go +package collections + +import ( + "cosmossdk.io/collections" + storetypes "cosmossdk.io/store/types" + sdk "github.com/cosmos/cosmos-sdk/types" +) + +var IDsPrefix = collections.NewPrefix(0) + +type Keeper struct { + Schema collections.Schema + IDs collections.Map[string, uint64] +} + +func NewKeeper(storeKey *storetypes.KVStoreKey) Keeper { + sb := collections.NewSchemaBuilder(sdk.OpenKVStore(storeKey)) + + return Keeper{ + IDs: collections.NewMap(sb, IDsPrefix, "ids", collections.StringKey, collections.Uint64Value), + } +} +```` + +We're now instantiating a map where the key is string and the value is `uint64`. +We already know the first three arguments of the ``NewMap`` function. + +The fourth parameter is our `KeyCodec`, we know that the ``Map`` has `string` as key so we pass it a `KeyCodec` that handles strings as keys. + +The fifth parameter is our `ValueCodec`, we know that the `Map` as a `uint64` as value so we pass it a `ValueCodec` that handles uint64. + +Collections already comes with all the required implementations for golang primitive types. + +Let's make another example, this falls closer to what we build using cosmos SDK, let's say we want +to create a `collections.Map` that maps account addresses to their base account. So we want to map an `sdk.AccAddress` to an `auth.BaseAccount` (which is a proto): + +```go +package collections + +import ( + "cosmossdk.io/collections" + storetypes "cosmossdk.io/store/types" + "github.com/cosmos/cosmos-sdk/codec" + sdk "github.com/cosmos/cosmos-sdk/types" + authtypes "github.com/cosmos/cosmos-sdk/x/auth/types" +) + +var AccountsPrefix = collections.NewPrefix(0) + +type Keeper struct { + Schema collections.Schema + Accounts collections.Map[sdk.AccAddress, authtypes.BaseAccount] +} + +func NewKeeper(storeKey *storetypes.KVStoreKey, cdc codec.BinaryCodec) Keeper { + sb := collections.NewSchemaBuilder(sdk.OpenKVStore(storeKey)) + return Keeper{ + Accounts: collections.NewMap(sb, AccountsPrefix, "accounts", + sdk.AccAddressKey, codec.CollValue[authtypes.BaseAccount](cdc)), + } +} +``` + +As we can see here since our `collections.Map` maps `sdk.AccAddress` to `authtypes.BaseAccount`, +we use the `sdk.AccAddressKey` which is the `KeyCodec` implementation for `AccAddress` and we use `codec.CollValue` to +encode our proto type `BaseAccount`. + +Generally speaking you will always find the respective key and value codecs for types in the `go.mod` path you're using +to import that type. If you want to encode proto values refer to the codec `codec.CollValue` function, which allows you +to encode any type implement the `proto.Message` interface. + +## Map + +We analyse the first and most important collection type, the ``collections.Map``. +This is the type that everything else builds on top of. + +### Use case + +A `collections.Map` is used to map arbitrary keys with arbitrary values. + +### Example + +It's easier to explain a `collections.Map` capabilities through an example: + +```go +package collections + +import ( + "cosmossdk.io/collections" + storetypes "cosmossdk.io/store/types" + "fmt" + "github.com/cosmos/cosmos-sdk/codec" + sdk "github.com/cosmos/cosmos-sdk/types" + authtypes "github.com/cosmos/cosmos-sdk/x/auth/types" +) + +var AccountsPrefix = collections.NewPrefix(0) + +type Keeper struct { + Schema collections.Schema + Accounts collections.Map[sdk.AccAddress, authtypes.BaseAccount] +} + +func NewKeeper(storeKey *storetypes.KVStoreKey, cdc codec.BinaryCodec) Keeper { + sb := collections.NewSchemaBuilder(sdk.OpenKVStore(storeKey)) + return Keeper{ + Accounts: collections.NewMap(sb, AccountsPrefix, "accounts", + sdk.AccAddressKey, codec.CollValue[authtypes.BaseAccount](cdc)), + } +} + +func (k Keeper) CreateAccount(ctx sdk.Context, addr sdk.AccAddress, account authtypes.BaseAccount) error { + has, err := k.Accounts.Has(ctx, addr) + if err != nil { + return err + } + if has { + return fmt.Errorf("account already exists: %s", addr) + } + + err = k.Accounts.Set(ctx, addr, account) + if err != nil { + return err + } + return nil +} + +func (k Keeper) GetAccount(ctx sdk.Context, addr sdk.AccAddress) (authtypes.BaseAccount, error) { + acc, err := k.Accounts.Get(ctx, addr) + if err != nil { + return authtypes.BaseAccount{}, err + } + + return acc, nil +} + +func (k Keeper) RemoveAccount(ctx sdk.Context, addr sdk.AccAddress) error { + err := k.Accounts.Remove(ctx, addr) + if err != nil { + return err + } + return nil +} +``` + +#### Set method + +Set maps with the provided `AccAddress` (the key) to the `auth.BaseAccount` (the value). + +Under the hood the `collections.Map` will convert the key and value to bytes using the [key and value codec](README.md#key-and-value-codecs). +It will prepend to our bytes key the [prefix](README.md#prefix) and store it in the KVStore of the module. + +#### Has method + +The has method reports if the provided key exists in the store. + +#### Get method + +The get method accepts the `AccAddress` and returns the associated `auth.BaseAccount` if it exists, otherwise it errors. + +#### Remove method + +The remove method accepts the `AccAddress` and removes it from the store. It won't report errors +if it does not exist, to check for existence before removal use the ``Has`` method. + +#### Iteration + +Iteration has a separate section. + +## KeySet + +The second type of collection is `collections.KeySet`, as the word suggests it maintains +only a set of keys without values. + +#### Implementation curiosity + +A `collections.KeySet` is just a `collections.Map` with a `key` but no value. +The value internally is always the same and is represented as an empty byte slice ```[]byte{}```. + +### Example + +As always we explore the collection type through an example: + +```go +package collections + +import ( + "cosmossdk.io/collections" + storetypes "cosmossdk.io/store/types" + "fmt" + sdk "github.com/cosmos/cosmos-sdk/types" +) + +var ValidatorsSetPrefix = collections.NewPrefix(0) + +type Keeper struct { + Schema collections.Schema + ValidatorsSet collections.KeySet[sdk.ValAddress] +} + +func NewKeeper(storeKey *storetypes.KVStoreKey) Keeper { + sb := collections.NewSchemaBuilder(sdk.OpenKVStore(storeKey)) + return Keeper{ + ValidatorsSet: collections.NewKeySet(sb, ValidatorsSetPrefix, "validators_set", sdk.ValAddressKey), + } +} + +func (k Keeper) AddValidator(ctx sdk.Context, validator sdk.ValAddress) error { + has, err := k.ValidatorsSet.Has(ctx, validator) + if err != nil { + return err + } + if has { + return fmt.Errorf("validator already in set: %s", validator) + } + + err = k.ValidatorsSet.Set(ctx, validator) + if err != nil { + return err + } + + return nil +} + +func (k Keeper) RemoveValidator(ctx sdk.Context, validator sdk.ValAddress) error { + err := k.ValidatorsSet.Remove(ctx, validator) + if err != nil { + return err + } + return nil +} +``` +The first difference we notice is that `KeySet` needs use to specify only one type parameter: the key (`sdk.ValAddress` in this case). +The second difference we notice is that `KeySet` in its `NewKeySet` function does not require +us to specify a `ValueCodec` but only a `KeyCodec`. This is because a `KeySet` only saves keys and not values. + +Let's explore the methods. + +#### Has method + +Has allows us to understand if a key is present in the `collections.KeySet` or not, functions in the same way as `collections.Map.Has +` + +#### Set method + +Set inserts the provided key in the `KeySet`. + +#### Remove method + +Remove removes the provided key from the `KeySet`, it does not error if the key does not exist, +if existence check before removal is required it needs to be coupled with the `Has` method. + +## Item + +The third type of collection is the `collections.Item`. +It stores only one single item, it's useful for example for parameters, there's only one instance +of parameters in state always. + +#### implementation curiosity + +A `collections.Item` is just a `collections.Map` with no key but just a value. +The key is the prefix of the collection! + +### Example + +```go +package collections + +import ( + "cosmossdk.io/collections" + storetypes "cosmossdk.io/store/types" + "github.com/cosmos/cosmos-sdk/codec" + sdk "github.com/cosmos/cosmos-sdk/types" + stakingtypes "github.com/cosmos/cosmos-sdk/x/staking/types" +) + +var ParamsPrefix = collections.NewPrefix(0) + +type Keeper struct { + Schema collections.Schema + Params collections.Item[stakingtypes.Params] +} + +func NewKeeper(storeKey *storetypes.KVStoreKey, cdc codec.BinaryCodec) Keeper { + sb := collections.NewSchemaBuilder(sdk.OpenKVStore(storeKey)) + return Keeper{ + Params: collections.NewItem(sb, ParamsPrefix, "params", codec.CollValue[stakingtypes.Params](cdc)), + } +} + +func (k Keeper) UpdateParams(ctx sdk.Context, params stakingtypes.Params) error { + err := k.Params.Set(ctx, params) + if err != nil { + return err + } + return nil +} + +func (k Keeper) GetParams(ctx sdk.Context) (stakingtypes.Params, error) { + return k.Params.Get(ctx) +} +``` + +The first key difference we notice is that we specify only one type parameter, which is the value we're storing. +The second key difference is that we don't specify the `KeyCodec`, since we store only one item we already know the key +and the fact that it is constant. + +## Iteration + +One of the key features of the ``KVStore`` is iterating over keys. + +Collections which deal with keys (so `Map`, `KeySet` and `IndexedMap`) allow you to iterate +over keys in a safe and typed way. They all share the same API, the only difference being +that ``KeySet`` returns a different type of `Iterator` because `KeySet` only deals with keys. + +:::note + +Every collection shares the same `Iterator` semantics. + +::: + +Let's have a look at the `Map.Iterate` method: + +```go +func (m Map[K, V]) Iterate(ctx context.Context, ranger Ranger[K]) (Iterator[K, V], error) +``` + +It accepts a `collections.Ranger[K]`, which is an API that instructs map on how to iterate over keys. +As always we don't need to implement anything here as `collections` already provides some generic `Ranger` implementers +that expose all you need to work with ranges. + +### Example + +We have a `collections.Map` that maps accounts using `uint64` IDs. + +```go +package collections + +import ( + "cosmossdk.io/collections" + storetypes "cosmossdk.io/store/types" + "github.com/cosmos/cosmos-sdk/codec" + sdk "github.com/cosmos/cosmos-sdk/types" + authtypes "github.com/cosmos/cosmos-sdk/x/auth/types" +) + +var AccountsPrefix = collections.NewPrefix(0) + +type Keeper struct { + Schema collections.Schema + Accounts collections.Map[uint64, authtypes.BaseAccount] +} + +func NewKeeper(storeKey *storetypes.KVStoreKey, cdc codec.BinaryCodec) Keeper { + sb := collections.NewSchemaBuilder(sdk.OpenKVStore(storeKey)) + return Keeper{ + Accounts: collections.NewMap(sb, AccountsPrefix, "accounts", collections.Uint64Key, codec.CollValue[authtypes.BaseAccount](cdc)), + } +} + +func (k Keeper) GetAllAccounts(ctx sdk.Context) ([]authtypes.BaseAccount, error) { + // passing a nil Ranger equals to: iterate over every possible key + iter, err := k.Accounts.Iterate(ctx, nil) + if err != nil { + return nil, err + } + accounts, err := iter.Values() + if err != nil { + return nil, err + } + + return accounts, err +} + +func (k Keeper) IterateAccountsBetween(ctx sdk.Context, start, end uint64) ([]authtypes.BaseAccount, error) { + // The collections.Range API offers a lot of capabilities + // like defining where the iteration starts or ends. + rng := new(collections.Range[uint64]). + StartInclusive(start). + EndExclusive(end). + Descending() + + iter, err := k.Accounts.Iterate(ctx, rng) + if err != nil { + return nil, err + } + accounts, err := iter.Values() + if err != nil { + return nil, err + } + + return accounts, nil +} + +func (k Keeper) IterateAccounts(ctx sdk.Context, do func(id uint64, acc authtypes.BaseAccount) (stop bool)) error { + iter, err := k.Accounts.Iterate(ctx, nil) + if err != nil { + return err + } + defer iter.Close() + + for ; iter.Valid(); iter.Next() { + kv, err := iter.KeyValue() + if err != nil { + return err + } + + if do(kv.Key, kv.Value) { + break + } + } + return nil +} +``` + +Let's analyse each method in the example and how it makes use of the `Iterate` and the returned `Iterator` API. + +#### GetAllAccounts + +In `GetAllAccounts` we pass to our `Iterate` a nil `Ranger`. This means that the returned `Iterator` will include +all the existing keys within the collection. + +Then we use some the `Values` method from the returned `Iterator` API to collect all the values into a slice. + +`Iterator` offers other methods such as `Keys()` to collect only the keys and not the values and `KeyValues` to collect +all the keys and values. + + +#### IterateAccountsBetween + +Here we make use of the `collections.Range` helper to specialise our range. +We make it start in a point through `StartInclusive` and end in the other with `EndExclusive`, then +we instruct it to report us results in reverse order through `Descending` + +Then we pass the range instruction to `Iterate` and get an `Iterator`, which will contain only the results +we specified in the range. + +Then we use again th `Values` method of the `Iterator` to collect all the results. + +`collections.Range` also offers a `Prefix` API which is not appliable to all keys types, +for example uint64 cannot be prefix because it is of constant size, but a `string` key +can be prefixed. + +#### IterateAccounts + +Here we showcase how to lazily collect values from an Iterator. + +:::note + +`Keys/Values/KeyValues` fully consume and close the `Iterator`, here we need to explicitly do a `defer iterator.Close()` call. + +::: + +`Iterator` also exposes a `Value` and `Key` method to collect only the current value or key, if collecting both is not needed. + +:::note + +For this `callback` pattern, collections expose a `Walk` API. + +::: + +## Composite keys + +So far we've worked only with simple keys, like `uint64`, the account address, etc. +There are some more complex cases in, which we need to deal with composite keys. + +A key is composite when it is composed of multiple keys, for example bank balances as stored as the composite key +`(AccAddress, string)` where the first part is the address holding the coins and the second part is the denom. + +Example, let's say address `BOB` holds `10atom,15osmo`, this is how it is stored in state: + +``` +(bob, atom) => 10 +(bob, osmos) => 15 +``` + +Now this allows to efficiently get a specific denom balance of an address, by simply `getting` `(address, denom)`, or getting all the balances +of an address by prefixing over `(address)`. + +Let's see now how we can work with composite keys using collections. + +### Example + +In our example we will show-case how we can use collections when we are dealing with balances, similar to bank, +a balance is a mapping between `(address, denom) => math.Int` the composite key in our case is `(address, denom)`. + +## Instantiation of a composite key collection + +```go +package collections + +import ( + "cosmossdk.io/collections" + "cosmossdk.io/math" + storetypes "cosmossdk.io/store/types" + sdk "github.com/cosmos/cosmos-sdk/types" +) + + +var BalancesPrefix = collections.NewPrefix(1) + +type Keeper struct { + Schema collections.Schema + Balances collections.Map[collections.Pair[sdk.AccAddress, string], math.Int] +} + +func NewKeeper(storeKey *storetypes.KVStoreKey) Keeper { + sb := collections.NewSchemaBuilder(sdk.OpenKVStore(storeKey)) + return Keeper{ + Balances: collections.NewMap( + sb, BalancesPrefix, "balances", + collections.PairKeyCodec(sdk.AccAddressKey, collections.StringKey), + math.IntValue, + ), + } +} +``` + +#### The Map Key definition + +First of all we can see that in order to define a composite key of two elements we use the `collections.Pair` type: +````go +collections.Map[collections.Pair[sdk.AccAddress, string], math.Int] +```` + +`collections.Pair` defines a key composed of two other keys, in our case the first part is `sdk.AccAddress`, the second +part is `string`. + +#### The Key Codec instantiation + +The arguments to instantiate are always the same, the only thing that changes is how we instantiate +the ``KeyCodec``, since this key is composed of two keys we use `collections.PairKeyCodec`, which generates +a `KeyCodec` composed of two key codecs. The first one will encode the first part of the key, the second one will +encode the second part of the key. + + +### Working with composite key collections + +Let's expand on the example we used before: + +````go +var BalancesPrefix = collections.NewPrefix(1) + +type Keeper struct { + Schema collections.Schema + Balances collections.Map[collections.Pair[sdk.AccAddress, string], math.Int] +} + +func NewKeeper(storeKey *storetypes.KVStoreKey) Keeper { + sb := collections.NewSchemaBuilder(sdk.OpenKVStore(storeKey)) + return Keeper{ + Balances: collections.NewMap( + sb, BalancesPrefix, "balances", + collections.PairKeyCodec(sdk.AccAddressKey, collections.StringKey), + math.IntValue, + ), + } +} + +func (k Keeper) SetBalance(ctx sdk.Context, address sdk.AccAddress, denom string, amount math.Int) error { + key := collections.Join(address, denom) + return k.Balances.Set(ctx, key, amount) +} + +func (k Keeper) GetBalance(ctx sdk.Context, address sdk.AccAddress, denom string) (math.Int, error) { + return k.Balances.Get(ctx, collections.Join(address, denom)) +} + +func (k Keeper) GetAllAddressBalances(ctx sdk.Context, address sdk.AccAddress) (sdk.Coins, error) { + balances := sdk.NewCoins() + + rng := collections.NewPrefixedPairRange[sdk.AccAddress, string](address) + + iter, err := k.Balances.Iterate(ctx, rng) + if err != nil { + return nil, err + } + + kvs, err := iter.KeyValues() + if err != nil { + return nil, err + } + + for _, kv := range kvs { + balances = balances.Add(sdk.NewCoin(kv.Key.K2(), kv.Value)) + } + return balances, nil +} + +func (k Keeper) GetAllAddressBalancesBetween(ctx sdk.Context, address sdk.AccAddress, startDenom, endDenom string) (sdk.Coins, error) { + rng := collections.NewPrefixedPairRange[sdk.AccAddress, string](address). + StartInclusive(startDenom). + EndInclusive(endDenom) + + iter, err := k.Balances.Iterate(ctx, rng) + if err != nil { + return nil, err + } + ... +} +```` + +#### SetBalance + +As we can see here we're setting the balance of an address for a specific denom. +We use the `collections.Join` function to generate the composite key. +`collections.Join` returns a `collections.Pair` (which is the key of our `collections.Map`) + +`collections.Pair` contains the two keys we have joined, it also exposes two methods: `K1` to fetch the 1st part of the +key and `K2` to fetch the second part. + +As always, we use the `collections.Map.Set` method to map the composite key to our value (`math.Int`in this case) + +#### GetBalance + +To get a value in composite key collection, we simply use `collections.Join` to compose the key. + +#### GetAllAddressBalances + +We use `collections.PrefixedPairRange` to iterate over all the keys starting with the provided address. +Concretely the iteration will report all the balances belonging to the provided address. + +The first part is that we instantiate a `PrefixedPairRange`, which is a `Ranger` implementer aimed to help +in `Pair` keys iterations. + +```go + rng := collections.NewPrefixedPairRange[sdk.AccAddress, string](address) +``` + +As we can see here we're passing the type parameters of the `collections.Pair` because golang type inference +with respect to generics is not as permissive as other languages, so we need to explitly say what are the types of the pair key. + +#### GetAllAddressesBalancesBetween + +This showcases how we can further specialise our range to limit the results further, by specifying +the range between the second part of the key (in our case the denoms, which are strings). + +## IndexedMap + +`collections.IndexedMap` is a collection that uses under the hood a `collections.Map`, and has a struct, which contains the indexes that we need to define. + +### Example + +Let's say we have an `auth.BaseAccount` struct which looks like the following: + +```go +type BaseAccount struct { + AccountNumber uint64 `protobuf:"varint,3,opt,name=account_number,json=accountNumber,proto3" json:"account_number,omitempty"` + Sequence uint64 `protobuf:"varint,4,opt,name=sequence,proto3" json:"sequence,omitempty"` +} +``` + +First of all, when we save our accounts in state we map them using a primary key `sdk.AccAddress`. +If it were to be a `collections.Map` it would be `collections.Map[sdk.AccAddres, authtypes.BaseAccount]`. + +Then we also want to be able to get an account not only by its `sdk.AccAddress`, but also by its `AccountNumber`. + +So we can say we want to create an `Index` that maps our `BaseAccount` to its `AccountNumber`. + +We also know that this `Index` is unique. Unique means that there can only be one `BaseAccount` that maps to a specific +`AccountNumber`. + +First of all, we start by defining the object that contains our index: + +```go +var AccountsNumberIndexPrefix = collections.NewPrefix(1) + +type AccountsIndexes struct { + Number *indexes.Unique[uint64, sdk.AccAddress, authtypes.BaseAccount] +} + +func (a AccountsIndexes) IndexesList() []collections.Index[sdk.AccAddress, authtypes.BaseAccount] { + return []collections.Index[sdk.AccAddress, authtypes.BaseAccount]{a.Number} +} + +func NewAccountIndexes(sb *collections.SchemaBuilder) AccountsIndexes { + return AccountsIndexes{ + Number: indexes.NewUnique( + sb, AccountsNumberIndexPrefix, "accounts_by_number", + collections.Uint64Key, sdk.AccAddressKey, + func(_ sdk.AccAddress, v authtypes.BaseAccount) (uint64, error) { + return v.AccountNumber, nil + }, + ), + } +} +``` + +We create an `AccountIndexes` struct which contains a field: `Number`. This field represents our `AccountNumber` index. +`AccountNumber` is a field of `authtypes.BaseAccount` and it's a `uint64`. + +Then we can see in our `AccountIndexes` struct the `Number` field is defined as: + +```go +*indexes.Unique[uint64, sdk.AccAddress, authtypes.BaseAccount] +``` + +Where the first type parameter is `uint64`, which is the field type of our index. +The second type parameter is the primary key `sdk.AccAddress` +And the third type parameter is the actual object we're storing `authtypes.BaseAccount`. + +Then we implement a function called `IndexesList` on our `AccountIndexes` struct, this will be used +by the `IndexedMap` to keep the underlying map in sync with the indexes, in our case `Number`. +This function just needs to return the slice of indexes contained in the struct. + +Then we create a `NewAccountIndexes` function that instantiates and returns the `AccountsIndexes` struct. + +The function takes a `SchemaBuilder`. Then we instantiate our `indexes.Unique`, let's analyse the arguments we pass to +`indexes.NewUnique`. + +#### Instantiating a `indexes.Unique` + +The first three arguments, we already know them, they are: `SchemaBuilder`, `Prefix` which is our index prefix (the partition +where index keys relationship for the `Number` index will be maintained), and the human name for the `Number` index. + +The second argument is a `collections.Uint64Key` which is a key codec to deal with `uint64` keys, we pass that because +the key we're trying to index is a `uint64` key (the account number), and then we pass as fifth argument the primary key codec, +which in our case is `sdk.AccAddress` (remember: we're mapping `sdk.AccAddress` => `BaseAccount`). + +Then as last parameter we pass a function that: given the `BaseAccount` returns its `AccountNumber`. + +After this we can proceed instantiating our `IndexedMap`. + +```go +var AccountsPrefix = collections.NewPrefix(0) + +type Keeper struct { + Schema collections.Schema + Accounts *collections.IndexedMap[sdk.AccAddress, authtypes.BaseAccount, AccountsIndexes] +} + +func NewKeeper(storeKey *storetypes.KVStoreKey, cdc codec.BinaryCodec) Keeper { + sb := collections.NewSchemaBuilder(sdk.OpenKVStore(storeKey)) + return Keeper{ + Accounts: collections.NewIndexedMap( + sb, AccountsPrefix, "accounts", + sdk.AccAddressKey, codec.CollValue[authtypes.BaseAccount](cdc), + NewAccountIndexes(sb), + ), + } +} +``` + +As we can see here what we do, for now, is the same thing as we did for `collections.Map`. +We pass it the `SchemaBuilder`, the `Prefix` where we plan to store the mapping between `sdk.AccAddress` and `authtypes.BaseAccount`, +the human name and the respective `sdk.AccAddress` key codec and `authtypes.BaseAccount` value codec. + +Then we pass the instantiation of our `AccountIndexes` through `NewAccountIndexes`. + +Full example: + +```go +package docs + +import ( + "cosmossdk.io/collections" + "cosmossdk.io/collections/indexes" + storetypes "cosmossdk.io/store/types" + "github.com/cosmos/cosmos-sdk/codec" + sdk "github.com/cosmos/cosmos-sdk/types" + authtypes "github.com/cosmos/cosmos-sdk/x/auth/types" +) + +var AccountsNumberIndexPrefix = collections.NewPrefix(1) + +type AccountsIndexes struct { + Number *indexes.Unique[uint64, sdk.AccAddress, authtypes.BaseAccount] +} + +func (a AccountsIndexes) IndexesList() []collections.Index[sdk.AccAddress, authtypes.BaseAccount] { + return []collections.Index[sdk.AccAddress, authtypes.BaseAccount]{a.Number} +} + +func NewAccountIndexes(sb *collections.SchemaBuilder) AccountsIndexes { + return AccountsIndexes{ + Number: indexes.NewUnique( + sb, AccountsNumberIndexPrefix, "accounts_by_number", + collections.Uint64Key, sdk.AccAddressKey, + func(_ sdk.AccAddress, v authtypes.BaseAccount) (uint64, error) { + return v.AccountNumber, nil + }, + ), + } +} + +var AccountsPrefix = collections.NewPrefix(0) + +type Keeper struct { + Schema collections.Schema + Accounts *collections.IndexedMap[sdk.AccAddress, authtypes.BaseAccount, AccountsIndexes] +} + +func NewKeeper(storeKey *storetypes.KVStoreKey, cdc codec.BinaryCodec) Keeper { + sb := collections.NewSchemaBuilder(sdk.OpenKVStore(storeKey)) + return Keeper{ + Accounts: collections.NewIndexedMap( + sb, AccountsPrefix, "accounts", + sdk.AccAddressKey, codec.CollValue[authtypes.BaseAccount](cdc), + NewAccountIndexes(sb), + ), + } +} +``` + +### Working with IndexedMaps + +Whilst instantiating `collections.IndexedMap` is tedious, working with them is extremely smooth. + +Let's take the full example, and expand it with some use-cases. + +```go +package docs + +import ( + "cosmossdk.io/collections" + "cosmossdk.io/collections/indexes" + storetypes "cosmossdk.io/store/types" + "github.com/cosmos/cosmos-sdk/codec" + sdk "github.com/cosmos/cosmos-sdk/types" + authtypes "github.com/cosmos/cosmos-sdk/x/auth/types" +) + +var AccountsNumberIndexPrefix = collections.NewPrefix(1) + +type AccountsIndexes struct { + Number *indexes.Unique[uint64, sdk.AccAddress, authtypes.BaseAccount] +} + +func (a AccountsIndexes) IndexesList() []collections.Index[sdk.AccAddress, authtypes.BaseAccount] { + return []collections.Index[sdk.AccAddress, authtypes.BaseAccount]{a.Number} +} + +func NewAccountIndexes(sb *collections.SchemaBuilder) AccountsIndexes { + return AccountsIndexes{ + Number: indexes.NewUnique( + sb, AccountsNumberIndexPrefix, "accounts_by_number", + collections.Uint64Key, sdk.AccAddressKey, + func(_ sdk.AccAddress, v authtypes.BaseAccount) (uint64, error) { + return v.AccountNumber, nil + }, + ), + } +} + +var AccountsPrefix = collections.NewPrefix(0) + +type Keeper struct { + Schema collections.Schema + Accounts *collections.IndexedMap[sdk.AccAddress, authtypes.BaseAccount, AccountsIndexes] +} + +func NewKeeper(storeKey *storetypes.KVStoreKey, cdc codec.BinaryCodec) Keeper { + sb := collections.NewSchemaBuilder(sdk.OpenKVStore(storeKey)) + return Keeper{ + Accounts: collections.NewIndexedMap( + sb, AccountsPrefix, "accounts", + sdk.AccAddressKey, codec.CollValue[authtypes.BaseAccount](cdc), + NewAccountIndexes(sb), + ), + } +} + +func (k Keeper) CreateAccount(ctx sdk.Context, addr sdk.AccAddress) error { + nextAccountNumber := k.getNextAccountNumber() + + newAcc := authtypes.BaseAccount{ + AccountNumber: nextAccountNumber, + Sequence: 0, + } + + return k.Accounts.Set(ctx, addr, newAcc) +} + +func (k Keeper) RemoveAccount(ctx sdk.Context, addr sdk.AccAddress) error { + return k.Accounts.Remove(ctx, addr) +} + +func (k Keeper) GetAccountByNumber(ctx sdk.Context, accNumber uint64) (sdk.AccAddress, authtypes.BaseAccount, error) { + accAddress, err := k.Accounts.Indexes.Number.MatchExact(ctx, accNumber) + if err != nil { + return nil, authtypes.BaseAccount{}, err + } + + acc, err := k.Accounts.Get(ctx, accAddress) + return accAddress, acc, nil +} + +func (k Keeper) GetAccountsByNumber(ctx sdk.Context, startAccNum, endAccNum uint64) ([]authtypes.BaseAccount, error) { + rng := new(collections.Range[uint64]). + StartInclusive(startAccNum). + EndInclusive(endAccNum) + + iter, err := k.Accounts.Indexes.Number.Iterate(ctx, rng) + if err != nil { + return nil, err + } + + return indexes.CollectValues(ctx, k.Accounts, iter) +} + + +func (k Keeper) getNextAccountNumber() uint64 { + return 0 +} +``` diff --git a/collections/codec/bool.go b/collections/codec/bool.go index b5ab8dcd9376..4016c8d68dcd 100644 --- a/collections/codec/bool.go +++ b/collections/codec/bool.go @@ -14,10 +14,9 @@ func (b boolKey[T]) Encode(buffer []byte, key T) (int, error) { if key { buffer[0] = 0x1 return 1, nil - } else { - buffer[0] = 0x0 - return 1, nil } + buffer[0] = 0x0 + return 1, nil } func (b boolKey[T]) Decode(buffer []byte) (int, T, error) { diff --git a/collections/colltest/codec.go b/collections/colltest/codec.go index 0991647971ac..dddd2df0d026 100644 --- a/collections/colltest/codec.go +++ b/collections/colltest/codec.go @@ -13,7 +13,7 @@ import ( "github.com/stretchr/testify/require" ) -// TestKeyCodec asserts the correct behaviour of a KeyCodec over the type T. +// TestKeyCodec asserts the correct behavior of a KeyCodec over the type T. func TestKeyCodec[T any](t *testing.T, keyCodec codec.KeyCodec[T], key T) { buffer := make([]byte, keyCodec.Size(key)) written, err := keyCodec.Encode(buffer, key) @@ -43,7 +43,7 @@ func TestKeyCodec[T any](t *testing.T, keyCodec codec.KeyCodec[T], key T) { require.Equal(t, key, decoded, "json encoding and decoding did not produce the same results") } -// TestValueCodec asserts the correct behaviour of a ValueCodec over the type T. +// TestValueCodec asserts the correct behavior of a ValueCodec over the type T. func TestValueCodec[T any](t *testing.T, encoder codec.ValueCodec[T], value T) { encodedValue, err := encoder.Encode(value) require.NoError(t, err) diff --git a/collections/colltest/store.go b/collections/colltest/store.go index a02b1f421f97..56231ffb199e 100644 --- a/collections/colltest/store.go +++ b/collections/colltest/store.go @@ -7,19 +7,30 @@ import ( db "github.com/cosmos/cosmos-db" ) +type contextStoreKey struct{} + // MockStore returns a mock store.KVStoreService and a mock context.Context. -// They can be used to test collections. -func MockStore() (store.KVStoreService, context.Context) { +// They can be used to test collections. The StoreService.NewStoreContext +// can be used to instantiate a new empty KVStore. +func MockStore() (*StoreService, context.Context) { kv := db.NewMemDB() - return &testStore{kv}, context.Background() + ctx := context.WithValue(context.Background(), contextStoreKey{}, &testStore{kv}) + return &StoreService{}, ctx } -type testStore struct { - db db.DB +type StoreService struct{} + +func (s StoreService) OpenKVStore(ctx context.Context) store.KVStore { + return ctx.Value(contextStoreKey{}).(store.KVStore) } -func (t testStore) OpenKVStore(ctx context.Context) store.KVStore { - return t +func (s StoreService) NewStoreContext() context.Context { + kv := db.NewMemDB() + return context.WithValue(context.Background(), contextStoreKey{}, &testStore{kv}) +} + +type testStore struct { + db db.DB } func (t testStore) Get(key []byte) ([]byte, error) { diff --git a/collections/go.mod b/collections/go.mod index ca45ebae5074..6ffb40f6e17d 100644 --- a/collections/go.mod +++ b/collections/go.mod @@ -10,7 +10,7 @@ require ( ) require ( - cosmossdk.io/api v0.3.1 // indirect + cosmossdk.io/api v0.4.0 // indirect cosmossdk.io/depinject v1.0.0-alpha.3 // indirect github.com/DataDog/zstd v1.5.2 // indirect github.com/beorn7/perks v1.0.1 // indirect @@ -35,7 +35,7 @@ require ( github.com/onsi/gomega v1.20.0 // indirect github.com/pkg/errors v0.9.1 // indirect github.com/pmezard/go-difflib v1.0.0 // indirect - github.com/prometheus/client_golang v1.14.0 // indirect + github.com/prometheus/client_golang v1.15.0 // indirect github.com/prometheus/client_model v0.3.0 // indirect github.com/prometheus/common v0.42.0 // indirect github.com/prometheus/procfs v0.9.0 // indirect diff --git a/collections/go.sum b/collections/go.sum index 9e93d1ae41a7..86031e03c031 100644 --- a/collections/go.sum +++ b/collections/go.sum @@ -1,6 +1,6 @@ cloud.google.com/go v0.26.0/go.mod h1:aQUYkXzVsufM+DwF1aE+0xfcU+56JwCaLick0ClmMTw= -cosmossdk.io/api v0.3.1 h1:NNiOclKRR0AOlO4KIqeaG6PS6kswOMhHD0ir0SscNXE= -cosmossdk.io/api v0.3.1/go.mod h1:DfHfMkiNA2Uhy8fj0JJlOCYOBp4eWUUJ1te5zBGNyIw= +cosmossdk.io/api v0.4.0 h1:x90DmdidP6EhzktAa/6/IofSHidDnPjahdlrUvyQZQw= +cosmossdk.io/api v0.4.0/go.mod h1:TWDzBhUBhI1LhSf2XSYpfIBf6D4mbLu/fvzvDfhcaYM= cosmossdk.io/core v0.6.1 h1:OBy7TI2W+/gyn2z40vVvruK3di+cAluinA6cybFbE7s= cosmossdk.io/core v0.6.1/go.mod h1:g3MMBCBXtxbDWBURDVnJE7XML4BG5qENhs0gzkcpuFA= cosmossdk.io/depinject v1.0.0-alpha.3 h1:6evFIgj//Y3w09bqOUOzEpFj5tsxBqdc5CfkO7z+zfw= @@ -218,8 +218,8 @@ github.com/pkg/errors v0.9.1 h1:FEBLx1zS214owpjy7qsBeixbURkuhQAwrK5UwLGTwt4= github.com/pkg/errors v0.9.1/go.mod h1:bwawxfHBFNV+L2hUp1rHADufV3IMtnDRdf1r5NINEl0= github.com/pmezard/go-difflib v1.0.0 h1:4DBwDE0NGyQoBHbLQYPwSUPoCMWR5BEzIk/f1lZbAQM= github.com/pmezard/go-difflib v1.0.0/go.mod h1:iKH77koFhYxTK1pcRnkKkqfTogsbg7gZNVY4sRDYZ/4= -github.com/prometheus/client_golang v1.14.0 h1:nJdhIvne2eSX/XRAFV9PcvFFRbrjbcTUj0VP62TMhnw= -github.com/prometheus/client_golang v1.14.0/go.mod h1:8vpkKitgIVNcqrRBWh1C4TIUQgYNtG/XQE4E/Zae36Y= +github.com/prometheus/client_golang v1.15.0 h1:5fCgGYogn0hFdhyhLbw7hEsWxufKtY9klyvdNfFlFhM= +github.com/prometheus/client_golang v1.15.0/go.mod h1:e9yaBhRPU2pPNsZwE+JdQl0KEt1N9XgF6zxWmaC0xOk= github.com/prometheus/client_model v0.0.0-20190812154241-14fe0d1b01d4/go.mod h1:xMI15A0UPsDsEKsMN9yxemIoYk6Tm2C1GtYGdfGttqA= github.com/prometheus/client_model v0.3.0 h1:UBgGFHqYdG/TPFD1B1ogZywDqEkwp3fBMvqdiQ7Xew4= github.com/prometheus/client_model v0.3.0/go.mod h1:LDGWKZIo7rky3hgvBe+caln+Dr3dPggB5dvjtD7w9+w= diff --git a/collections/indexed_map.go b/collections/indexed_map.go index 5c97a2ae5a1a..1625c47aec9c 100644 --- a/collections/indexed_map.go +++ b/collections/indexed_map.go @@ -2,8 +2,6 @@ package collections import ( "context" - "errors" - "fmt" "cosmossdk.io/collections/codec" ) @@ -21,12 +19,12 @@ type Indexes[PrimaryKey, Value any] interface { // Index represents an index of the Value indexed using the type PrimaryKey. type Index[PrimaryKey, Value any] interface { // Reference creates a reference between the provided primary key and value. - // If oldValue is not nil then the Index must update the references - // of the primary key associated with the new value and remove the - // old invalid references. - Reference(ctx context.Context, pk PrimaryKey, newValue Value, oldValue *Value) error + // It provides a lazyOldValue function that if called will attempt to fetch + // the previous old value, returns ErrNotFound if no value existed. + Reference(ctx context.Context, pk PrimaryKey, newValue Value, lazyOldValue func() (Value, error)) error // Unreference removes the reference between the primary key and value. - Unreference(ctx context.Context, pk PrimaryKey, value Value) error + // If error is ErrNotFound then it means that the value did not exist before. + Unreference(ctx context.Context, pk PrimaryKey, lazyOldValue func() (Value, error)) error } // IndexedMap works like a Map but creates references between fields of Value and its PrimaryKey. @@ -40,10 +38,10 @@ type IndexedMap[PrimaryKey, Value any, Idx Indexes[PrimaryKey, Value]] struct { } // NewIndexedMap instantiates a new IndexedMap. Accepts a SchemaBuilder, a Prefix, -// a humanised name that defines the name of the collection, the primary key codec +// a humanized name that defines the name of the collection, the primary key codec // which is basically what IndexedMap uses to encode the primary key to bytes, // the value codec which is what the IndexedMap uses to encode the value. -// Then it expects the initialised indexes. +// Then it expects the initialized indexes. func NewIndexedMap[PrimaryKey, Value any, Idx Indexes[PrimaryKey, Value]]( schema *SchemaBuilder, prefix Prefix, @@ -76,26 +74,10 @@ func (m *IndexedMap[PrimaryKey, Value, Idx]) Has(ctx context.Context, pk Primary // Set maps the value using the primary key. It will also iterate every index and instruct them to // add or update the indexes. func (m *IndexedMap[PrimaryKey, Value, Idx]) Set(ctx context.Context, pk PrimaryKey, value Value) error { - // we need to see if there was a previous instance of the value - oldValue, err := m.m.Get(ctx, pk) - switch { - // update indexes - case err == nil: - err = m.ref(ctx, pk, value, &oldValue) - if err != nil { - return fmt.Errorf("collections: indexing error: %w", err) - } - // create new indexes - case errors.Is(err, ErrNotFound): - err = m.ref(ctx, pk, value, nil) - if err != nil { - return fmt.Errorf("collections: indexing error: %w", err) - } - // cannot move forward error - default: + err := m.ref(ctx, pk, value) + if err != nil { return err } - return m.m.Set(ctx, pk, value) } @@ -103,13 +85,7 @@ func (m *IndexedMap[PrimaryKey, Value, Idx]) Set(ctx context.Context, pk Primary // it iterates over all the indexes and instructs them to remove all the references // associated with the removed value. func (m *IndexedMap[PrimaryKey, Value, Idx]) Remove(ctx context.Context, pk PrimaryKey) error { - oldValue, err := m.m.Get(ctx, pk) - if err != nil { - // TODO retain Map behaviour? which does not error in case we remove a non-existing object - return err - } - - err = m.unref(ctx, pk, oldValue) + err := m.unref(ctx, pk) if err != nil { return err } @@ -134,9 +110,9 @@ func (m *IndexedMap[PrimaryKey, Value, Idx]) ValueCodec() codec.ValueCodec[Value return m.m.ValueCodec() } -func (m *IndexedMap[PrimaryKey, Value, Idx]) ref(ctx context.Context, pk PrimaryKey, value Value, oldValue *Value) error { +func (m *IndexedMap[PrimaryKey, Value, Idx]) ref(ctx context.Context, pk PrimaryKey, value Value) error { for _, index := range m.Indexes.IndexesList() { - err := index.Reference(ctx, pk, value, oldValue) + err := index.Reference(ctx, pk, value, cachedGet[PrimaryKey, Value](ctx, m, pk)) if err != nil { return err } @@ -144,12 +120,34 @@ func (m *IndexedMap[PrimaryKey, Value, Idx]) ref(ctx context.Context, pk Primary return nil } -func (m *IndexedMap[PrimaryKey, Value, Idx]) unref(ctx context.Context, pk PrimaryKey, value Value) error { +func (m *IndexedMap[PrimaryKey, Value, Idx]) unref(ctx context.Context, pk PrimaryKey) error { for _, index := range m.Indexes.IndexesList() { - err := index.Unreference(ctx, pk, value) + err := index.Unreference(ctx, pk, cachedGet[PrimaryKey, Value](ctx, m, pk)) if err != nil { return err } } return nil } + +// cachedGet returns a function that gets the value V, given the key K but +// returns always the same result on multiple calls. +func cachedGet[K, V any, M interface { + Get(ctx context.Context, key K) (V, error) +}](ctx context.Context, m M, key K, +) func() (V, error) { + var ( + value V + err error + calledOnce bool + ) + + return func() (V, error) { + if calledOnce { + return value, err + } + value, err = m.Get(ctx, key) + calledOnce = true + return value, err + } +} diff --git a/collections/indexed_map_test.go b/collections/indexed_map_test.go index 707537883b05..9af4dd74b7e6 100644 --- a/collections/indexed_map_test.go +++ b/collections/indexed_map_test.go @@ -5,6 +5,7 @@ import ( "cosmossdk.io/collections" "cosmossdk.io/collections/colltest" + "cosmossdk.io/collections/indexes" "github.com/stretchr/testify/require" ) @@ -17,11 +18,11 @@ type companyIndexes struct { // City is an index of the company indexed map. It indexes a company // given its city. The index is multi, meaning that there can be multiple // companies from the same city. - City *collections.GenericMultiIndex[string, string, string, company] + City *indexes.Multi[string, string, company] // Vat is an index of the company indexed map. It indexes a company // given its VAT number. The index is unique, meaning that there can be // only one VAT number for a company. - Vat *collections.GenericUniqueIndex[uint64, string, string, company] + Vat *indexes.Unique[uint64, string, company] } func (c companyIndexes) IndexesList() []collections.Index[string, company] { @@ -31,11 +32,11 @@ func (c companyIndexes) IndexesList() []collections.Index[string, company] { func newTestIndexedMap(schema *collections.SchemaBuilder) *collections.IndexedMap[string, company, companyIndexes] { return collections.NewIndexedMap(schema, collections.NewPrefix(0), "companies", collections.StringKey, colltest.MockValueCodec[company](), companyIndexes{ - City: collections.NewGenericMultiIndex(schema, collections.NewPrefix(1), "companies_by_city", collections.StringKey, collections.StringKey, func(pk string, value company) ([]collections.IndexReference[string, string], error) { - return []collections.IndexReference[string, string]{collections.NewIndexReference(value.City, pk)}, nil + City: indexes.NewMulti(schema, collections.NewPrefix(1), "companies_by_city", collections.StringKey, collections.StringKey, func(pk string, value company) (string, error) { + return value.City, nil }), - Vat: collections.NewGenericUniqueIndex(schema, collections.NewPrefix(2), "companies_by_vat", collections.Uint64Key, collections.StringKey, func(pk string, v company) ([]collections.IndexReference[uint64, string], error) { - return []collections.IndexReference[uint64, string]{collections.NewIndexReference(v.Vat, pk)}, nil + Vat: indexes.NewUnique(schema, collections.NewPrefix(2), "companies_by_vat", collections.Uint64Key, collections.StringKey, func(pk string, value company) (uint64, error) { + return value.Vat, nil }), }, ) @@ -66,7 +67,7 @@ func TestIndexedMap(t *testing.T) { }) require.NoError(t, err) - pk, err := im.Indexes.Vat.Get(ctx, 1) + pk, err := im.Indexes.Vat.MatchExact(ctx, 1) require.NoError(t, err) require.Equal(t, "2", pk) @@ -77,17 +78,17 @@ func TestIndexedMap(t *testing.T) { }) require.NoError(t, err) - pk, err = im.Indexes.Vat.Get(ctx, 2) + pk, err = im.Indexes.Vat.MatchExact(ctx, 2) require.NoError(t, err) require.Equal(t, "2", pk) - _, err = im.Indexes.Vat.Get(ctx, 1) + _, err = im.Indexes.Vat.MatchExact(ctx, 1) require.ErrorIs(t, err, collections.ErrNotFound) // test removal err = im.Remove(ctx, "2") require.NoError(t, err) - _, err = im.Indexes.Vat.Get(ctx, 2) + _, err = im.Indexes.Vat.MatchExact(ctx, 2) require.ErrorIs(t, err, collections.ErrNotFound) // test iteration diff --git a/collections/indexes/helpers_test.go b/collections/indexes/helpers_test.go index 00052bd5e1bb..469aa38dba33 100644 --- a/collections/indexes/helpers_test.go +++ b/collections/indexes/helpers_test.go @@ -8,7 +8,7 @@ import ( ) func TestHelpers(t *testing.T) { - // uses MultiPair scenario. + // uses ReversePair scenario. // We store balances as: // Key: Pair[Address=string, Denom=string] => Value: Amount=uint64 @@ -22,7 +22,7 @@ func TestHelpers(t *testing.T) { keyCodec, collections.Uint64Value, balanceIndex{ - Denom: NewMultiPair[Amount](sb, collections.NewPrefix("denom_index"), "denom_index", keyCodec), + Denom: NewReversePair[Amount](sb, collections.NewPrefix("denom_index"), "denom_index", keyCodec), }, ) diff --git a/collections/indexes/multi.go b/collections/indexes/multi.go index 8f2452dcd809..410aae00fd3b 100644 --- a/collections/indexes/multi.go +++ b/collections/indexes/multi.go @@ -2,6 +2,7 @@ package indexes import ( "context" + "errors" "cosmossdk.io/collections" "cosmossdk.io/collections/codec" @@ -10,7 +11,10 @@ import ( // Multi defines the most common index. It can be used to create a reference between // a field of value and its primary key. Multiple primary keys can be mapped to the same // reference key as the index does not enforce uniqueness constraints. -type Multi[ReferenceKey, PrimaryKey, Value any] collections.GenericMultiIndex[ReferenceKey, PrimaryKey, PrimaryKey, Value] +type Multi[ReferenceKey, PrimaryKey, Value any] struct { + getRefKey func(pk PrimaryKey, value Value) (ReferenceKey, error) + refKeys collections.KeySet[collections.Pair[ReferenceKey, PrimaryKey]] +} // NewMulti instantiates a new Multi instance given a schema, // a Prefix, the humanized name for the index, the reference key key codec @@ -24,32 +28,54 @@ func NewMulti[ReferenceKey, PrimaryKey, Value any]( pkCodec codec.KeyCodec[PrimaryKey], getRefKeyFunc func(pk PrimaryKey, value Value) (ReferenceKey, error), ) *Multi[ReferenceKey, PrimaryKey, Value] { - i := collections.NewGenericMultiIndex( - schema, prefix, name, refCodec, pkCodec, - func(pk PrimaryKey, value Value) ([]collections.IndexReference[ReferenceKey, PrimaryKey], error) { - ref, err := getRefKeyFunc(pk, value) - if err != nil { - return nil, err - } - return []collections.IndexReference[ReferenceKey, PrimaryKey]{ - collections.NewIndexReference(ref, pk), - }, nil - }, - ) + return &Multi[ReferenceKey, PrimaryKey, Value]{ + getRefKey: getRefKeyFunc, + refKeys: collections.NewKeySet(schema, prefix, name, collections.PairKeyCodec(refCodec, pkCodec)), + } +} - return (*Multi[ReferenceKey, PrimaryKey, Value])(i) +func (m *Multi[ReferenceKey, PrimaryKey, Value]) Reference(ctx context.Context, pk PrimaryKey, newValue Value, lazyOldValue func() (Value, error)) error { + oldValue, err := lazyOldValue() + switch { + // if no error it means the value existed, and we need to remove the old indexes + case err == nil: + err = m.unreference(ctx, pk, oldValue) + if err != nil { + return err + } + // if error is ErrNotFound, it means that the object does not exist, so we're creating indexes for the first time. + // we do nothing. + case errors.Is(err, collections.ErrNotFound): + // default case means that there was some other error + default: + return err + } + // create new indexes + refKey, err := m.getRefKey(pk, newValue) + if err != nil { + return err + } + return m.refKeys.Set(ctx, collections.Join(refKey, pk)) } -func (m *Multi[ReferenceKey, PrimaryKey, Value]) Reference(ctx context.Context, pk PrimaryKey, newValue Value, oldValue *Value) error { - return (*collections.GenericMultiIndex[ReferenceKey, PrimaryKey, PrimaryKey, Value])(m).Reference(ctx, pk, newValue, oldValue) +func (m *Multi[ReferenceKey, PrimaryKey, Value]) Unreference(ctx context.Context, pk PrimaryKey, getValue func() (Value, error)) error { + value, err := getValue() + if err != nil { + return err + } + return m.unreference(ctx, pk, value) } -func (m *Multi[ReferenceKey, PrimaryKey, Value]) Unreference(ctx context.Context, pk PrimaryKey, value Value) error { - return (*collections.GenericMultiIndex[ReferenceKey, PrimaryKey, PrimaryKey, Value])(m).Unreference(ctx, pk, value) +func (m *Multi[ReferenceKey, PrimaryKey, Value]) unreference(ctx context.Context, pk PrimaryKey, value Value) error { + refKey, err := m.getRefKey(pk, value) + if err != nil { + return err + } + return m.refKeys.Remove(ctx, collections.Join(refKey, pk)) } func (m *Multi[ReferenceKey, PrimaryKey, Value]) Iterate(ctx context.Context, ranger collections.Ranger[collections.Pair[ReferenceKey, PrimaryKey]]) (MultiIterator[ReferenceKey, PrimaryKey], error) { - iter, err := (*collections.GenericMultiIndex[ReferenceKey, PrimaryKey, PrimaryKey, Value])(m).Iterate(ctx, ranger) + iter, err := m.refKeys.Iterate(ctx, ranger) return (MultiIterator[ReferenceKey, PrimaryKey])(iter), err } @@ -58,7 +84,9 @@ func (m *Multi[ReferenceKey, PrimaryKey, Value]) Walk( ranger collections.Ranger[collections.Pair[ReferenceKey, PrimaryKey]], walkFunc func(indexingKey ReferenceKey, indexedKey PrimaryKey) bool, ) error { - return (*collections.GenericMultiIndex[ReferenceKey, PrimaryKey, PrimaryKey, Value])(m).Walk(ctx, ranger, walkFunc) + return m.refKeys.Walk(ctx, ranger, func(key collections.Pair[ReferenceKey, PrimaryKey]) bool { + return walkFunc(key.K1(), key.K2()) + }) } // MatchExact returns a MultiIterator containing all the primary keys referenced by the provided reference key. @@ -66,8 +94,8 @@ func (m *Multi[ReferenceKey, PrimaryKey, Value]) MatchExact(ctx context.Context, return m.Iterate(ctx, collections.NewPrefixedPairRange[ReferenceKey, PrimaryKey](refKey)) } -func (i *MultiPair[K1, K2, Value]) KeyCodec() codec.KeyCodec[collections.Pair[K2, K1]] { - return (*collections.GenericMultiIndex[K2, K1, collections.Pair[K1, K2], Value])(i).KeyCodec() +func (m *Multi[K1, K2, Value]) KeyCodec() codec.KeyCodec[collections.Pair[K1, K2]] { + return m.refKeys.KeyCodec() } // MultiIterator is just a KeySetIterator with key as Pair[ReferenceKey, PrimaryKey]. diff --git a/collections/indexes/multi_pair.go b/collections/indexes/multi_pair.go deleted file mode 100644 index 2d53a6d65738..000000000000 --- a/collections/indexes/multi_pair.go +++ /dev/null @@ -1,132 +0,0 @@ -package indexes - -import ( - "context" - - "cosmossdk.io/collections" - "cosmossdk.io/collections/codec" -) - -// MultiPair is an index that is used with collections.Pair keys. It indexes objects by their second part of the key. -// When the value is being indexed by collections.IndexedMap then MultiPair will create a relationship between -// the second part of the primary key and the first part. -type MultiPair[K1, K2, Value any] collections.GenericMultiIndex[K2, K1, collections.Pair[K1, K2], Value] - -// TODO(tip): this is an interface to cast a collections.KeyCodec -// to a pair codec. currently we return it as a KeyCodec[Pair[K1, K2]] -// to improve dev experience with type inference, which means we cannot -// get the concrete implementation which exposes KeyCodec1 and KeyCodec2. -type pairKeyCodec[K1, K2 any] interface { - KeyCodec1() codec.KeyCodec[K1] - KeyCodec2() codec.KeyCodec[K2] -} - -// NewMultiPair instantiates a new MultiPair index. -// NOTE: when using this function you will need to type hint: doing NewMultiPair[Value]() -// Example: if the value of the indexed map is string, you need to do NewMultiPair[string](...) -func NewMultiPair[Value any, K1, K2 any]( - sb *collections.SchemaBuilder, - prefix collections.Prefix, - name string, - pairCodec codec.KeyCodec[collections.Pair[K1, K2]], -) *MultiPair[K1, K2, Value] { - pkc := pairCodec.(pairKeyCodec[K1, K2]) - mi := collections.NewGenericMultiIndex( - sb, - prefix, - name, - pkc.KeyCodec2(), - pkc.KeyCodec1(), - func(pk collections.Pair[K1, K2], _ Value) ([]collections.IndexReference[K2, K1], error) { - return []collections.IndexReference[K2, K1]{ - collections.NewIndexReference(pk.K2(), pk.K1()), - }, nil - }, - ) - - return (*MultiPair[K1, K2, Value])(mi) -} - -// Iterate exposes the raw iterator API. -func (i *MultiPair[K1, K2, Value]) Iterate(ctx context.Context, ranger collections.Ranger[collections.Pair[K2, K1]]) (iter MultiPairIterator[K2, K1], err error) { - sIter, err := (*collections.GenericMultiIndex[K2, K1, collections.Pair[K1, K2], Value])(i).Iterate(ctx, ranger) - if err != nil { - return iter, err - } - return (MultiPairIterator[K2, K1])(sIter), nil -} - -// MatchExact will return an iterator containing only the primary keys starting with the provided second part of the multipart pair key. -func (i *MultiPair[K1, K2, Value]) MatchExact(ctx context.Context, key K2) (MultiPairIterator[K2, K1], error) { - return i.Iterate(ctx, collections.NewPrefixedPairRange[K2, K1](key)) -} - -// Reference implements collections.Index -func (i *MultiPair[K1, K2, Value]) Reference(ctx context.Context, pk collections.Pair[K1, K2], value Value, oldValue *Value) error { - return (*collections.GenericMultiIndex[K2, K1, collections.Pair[K1, K2], Value])(i).Reference(ctx, pk, value, oldValue) -} - -// Unreference implements collections.Index -func (i *MultiPair[K1, K2, Value]) Unreference(ctx context.Context, pk collections.Pair[K1, K2], value Value) error { - return (*collections.GenericMultiIndex[K2, K1, collections.Pair[K1, K2], Value])(i).Unreference(ctx, pk, value) -} - -func (i *MultiPair[K1, K2, Value]) Walk( - ctx context.Context, - ranger collections.Ranger[collections.Pair[K2, K1]], - walkFunc func(indexingKey K2, indexedKey K1) bool, -) error { - return (*collections.GenericMultiIndex[K2, K1, collections.Pair[K1, K2], Value])(i).Walk(ctx, ranger, walkFunc) -} - -func (i *MultiPair[K1, K2, Value]) IterateRaw( - ctx context.Context, start, end []byte, order collections.Order, -) ( - iter collections.Iterator[collections.Pair[K2, K1], collections.NoValue], err error, -) { - return (*collections.GenericMultiIndex[K2, K1, collections.Pair[K1, K2], Value])(i).IterateRaw(ctx, start, end, order) -} - -// MultiPairIterator is a helper type around a collections.KeySetIterator when used to work -// with MultiPair indexes iterations. -type MultiPairIterator[K2, K1 any] collections.KeySetIterator[collections.Pair[K2, K1]] - -// PrimaryKey returns the primary key from the index. The index is composed like a reverse -// pair key. So we just fetch the pair key from the index and return the reverse. -func (m MultiPairIterator[K2, K1]) PrimaryKey() (pair collections.Pair[K1, K2], err error) { - reversePair, err := m.FullKey() - if err != nil { - return pair, err - } - pair = collections.Join(reversePair.K2(), reversePair.K1()) - return pair, nil -} - -// PrimaryKeys returns all the primary keys contained in the iterator. -func (m MultiPairIterator[K2, K1]) PrimaryKeys() (pairs []collections.Pair[K1, K2], err error) { - defer m.Close() - for ; m.Valid(); m.Next() { - pair, err := m.PrimaryKey() - if err != nil { - return nil, err - } - pairs = append(pairs, pair) - } - return pairs, err -} - -func (m MultiPairIterator[K2, K1]) FullKey() (p collections.Pair[K2, K1], err error) { - return (collections.KeySetIterator[collections.Pair[K2, K1]])(m).Key() -} - -func (m MultiPairIterator[K2, K1]) Next() { - (collections.KeySetIterator[collections.Pair[K2, K1]])(m).Next() -} - -func (m MultiPairIterator[K2, K1]) Valid() bool { - return (collections.KeySetIterator[collections.Pair[K2, K1]])(m).Valid() -} - -func (m MultiPairIterator[K2, K1]) Close() error { - return (collections.KeySetIterator[collections.Pair[K2, K1]])(m).Close() -} diff --git a/collections/indexes/multi_test.go b/collections/indexes/multi_test.go index 98518cd1bec8..ed11195bf0f4 100644 --- a/collections/indexes/multi_test.go +++ b/collections/indexes/multi_test.go @@ -16,8 +16,8 @@ func TestMultiIndex(t *testing.T) { }) // we crete two reference keys for primary key 1 and 2 associated with "milan" - require.NoError(t, mi.Reference(ctx, 1, company{City: "milan"}, nil)) - require.NoError(t, mi.Reference(ctx, 2, company{City: "milan"}, nil)) + require.NoError(t, mi.Reference(ctx, 1, company{City: "milan"}, func() (company, error) { return company{}, collections.ErrNotFound })) + require.NoError(t, mi.Reference(ctx, 2, company{City: "milan"}, func() (company, error) { return company{}, collections.ErrNotFound })) iter, err := mi.MatchExact(ctx, "milan") require.NoError(t, err) @@ -26,7 +26,7 @@ func TestMultiIndex(t *testing.T) { require.Equal(t, []uint64{1, 2}, pks) // replace - require.NoError(t, mi.Reference(ctx, 1, company{City: "new york"}, &company{City: "milan"})) + require.NoError(t, mi.Reference(ctx, 1, company{City: "new york"}, func() (company, error) { return company{City: "milan"}, nil })) // assert after replace only company with id 2 is referenced by milan iter, err = mi.MatchExact(ctx, "milan") diff --git a/collections/indexes/reverse_pair.go b/collections/indexes/reverse_pair.go new file mode 100644 index 000000000000..55e4007e5f19 --- /dev/null +++ b/collections/indexes/reverse_pair.go @@ -0,0 +1,131 @@ +package indexes + +import ( + "context" + + "cosmossdk.io/collections" + "cosmossdk.io/collections/codec" +) + +// ReversePair is an index that is used with collections.Pair keys. It indexes objects by their second part of the key. +// When the value is being indexed by collections.IndexedMap then ReversePair will create a relationship between +// the second part of the primary key and the first part. +type ReversePair[K1, K2, Value any] struct { + refKeys collections.KeySet[collections.Pair[K2, K1]] // refKeys has the relationships between Join(K2, K1) +} + +// TODO(tip): this is an interface to cast a collections.KeyCodec +// to a pair codec. currently we return it as a KeyCodec[Pair[K1, K2]] +// to improve dev experience with type inference, which means we cannot +// get the concrete implementation which exposes KeyCodec1 and KeyCodec2. +type pairKeyCodec[K1, K2 any] interface { + KeyCodec1() codec.KeyCodec[K1] + KeyCodec2() codec.KeyCodec[K2] +} + +// NewReversePair instantiates a new ReversePair index. +// NOTE: when using this function you will need to type hint: doing NewReversePair[Value]() +// Example: if the value of the indexed map is string, you need to do NewReversePair[string](...) +func NewReversePair[Value, K1, K2 any]( + sb *collections.SchemaBuilder, + prefix collections.Prefix, + name string, + pairCodec codec.KeyCodec[collections.Pair[K1, K2]], +) *ReversePair[K1, K2, Value] { + pkc := pairCodec.(pairKeyCodec[K1, K2]) + mi := &ReversePair[K1, K2, Value]{ + refKeys: collections.NewKeySet(sb, prefix, name, collections.PairKeyCodec(pkc.KeyCodec2(), pkc.KeyCodec1())), + } + + return mi +} + +// Iterate exposes the raw iterator API. +func (i *ReversePair[K1, K2, Value]) Iterate(ctx context.Context, ranger collections.Ranger[collections.Pair[K2, K1]]) (iter ReversePairIterator[K2, K1], err error) { + sIter, err := i.refKeys.Iterate(ctx, ranger) + if err != nil { + return + } + return (ReversePairIterator[K2, K1])(sIter), nil +} + +// MatchExact will return an iterator containing only the primary keys starting with the provided second part of the multipart pair key. +func (i *ReversePair[K1, K2, Value]) MatchExact(ctx context.Context, key K2) (ReversePairIterator[K2, K1], error) { + return i.Iterate(ctx, collections.NewPrefixedPairRange[K2, K1](key)) +} + +// Reference implements collections.Index +func (i *ReversePair[K1, K2, Value]) Reference(ctx context.Context, pk collections.Pair[K1, K2], _ Value, _ func() (Value, error)) error { + return i.refKeys.Set(ctx, collections.Join(pk.K2(), pk.K1())) +} + +// Unreference implements collections.Index +func (i *ReversePair[K1, K2, Value]) Unreference(ctx context.Context, pk collections.Pair[K1, K2], _ func() (Value, error)) error { + return i.refKeys.Remove(ctx, collections.Join(pk.K2(), pk.K1())) +} + +func (i *ReversePair[K1, K2, Value]) Walk( + ctx context.Context, + ranger collections.Ranger[collections.Pair[K2, K1]], + walkFunc func(indexingKey K2, indexedKey K1) bool, +) error { + return i.refKeys.Walk(ctx, ranger, func(key collections.Pair[K2, K1]) bool { + return walkFunc(key.K1(), key.K2()) + }) +} + +func (i *ReversePair[K1, K2, Value]) IterateRaw( + ctx context.Context, start, end []byte, order collections.Order, +) ( + iter collections.Iterator[collections.Pair[K2, K1], collections.NoValue], err error, +) { + return i.refKeys.IterateRaw(ctx, start, end, order) +} + +func (i *ReversePair[K1, K2, Value]) KeyCodec() codec.KeyCodec[collections.Pair[K2, K1]] { + return i.refKeys.KeyCodec() +} + +// ReversePairIterator is a helper type around a collections.KeySetIterator when used to work +// with ReversePair indexes iterations. +type ReversePairIterator[K2, K1 any] collections.KeySetIterator[collections.Pair[K2, K1]] + +// PrimaryKey returns the primary key from the index. The index is composed like a reverse +// pair key. So we just fetch the pair key from the index and return the reverse. +func (m ReversePairIterator[K2, K1]) PrimaryKey() (pair collections.Pair[K1, K2], err error) { + reversePair, err := m.FullKey() + if err != nil { + return pair, err + } + pair = collections.Join(reversePair.K2(), reversePair.K1()) + return pair, nil +} + +// PrimaryKeys returns all the primary keys contained in the iterator. +func (m ReversePairIterator[K2, K1]) PrimaryKeys() (pairs []collections.Pair[K1, K2], err error) { + defer m.Close() + for ; m.Valid(); m.Next() { + pair, err := m.PrimaryKey() + if err != nil { + return nil, err + } + pairs = append(pairs, pair) + } + return pairs, err +} + +func (m ReversePairIterator[K2, K1]) FullKey() (p collections.Pair[K2, K1], err error) { + return (collections.KeySetIterator[collections.Pair[K2, K1]])(m).Key() +} + +func (m ReversePairIterator[K2, K1]) Next() { + (collections.KeySetIterator[collections.Pair[K2, K1]])(m).Next() +} + +func (m ReversePairIterator[K2, K1]) Valid() bool { + return (collections.KeySetIterator[collections.Pair[K2, K1]])(m).Valid() +} + +func (m ReversePairIterator[K2, K1]) Close() error { + return (collections.KeySetIterator[collections.Pair[K2, K1]])(m).Close() +} diff --git a/collections/indexes/multi_pair_test.go b/collections/indexes/reverse_pair_test.go similarity index 89% rename from collections/indexes/multi_pair_test.go rename to collections/indexes/reverse_pair_test.go index 052a62ebeab0..55ee354f1f00 100644 --- a/collections/indexes/multi_pair_test.go +++ b/collections/indexes/reverse_pair_test.go @@ -16,14 +16,14 @@ type ( // our balance index, allows us to efficiently create an index between the key that maps // balances which is a collections.Pair[Address, Denom] and the Denom. type balanceIndex struct { - Denom *MultiPair[Address, Denom, Amount] + Denom *ReversePair[Address, Denom, Amount] } func (b balanceIndex) IndexesList() []collections.Index[collections.Pair[Address, Denom], Amount] { return []collections.Index[collections.Pair[Address, Denom], Amount]{b.Denom} } -func TestMultiPair(t *testing.T) { +func TestReversePair(t *testing.T) { sk, ctx := deps() sb := collections.NewSchemaBuilder(sk) // we create an indexed map that maps balances, which are saved as @@ -37,7 +37,7 @@ func TestMultiPair(t *testing.T) { keyCodec, collections.Uint64Value, balanceIndex{ - Denom: NewMultiPair[Amount](sb, collections.NewPrefix("denom_index"), "denom_index", keyCodec), + Denom: NewReversePair[Amount](sb, collections.NewPrefix("denom_index"), "denom_index", keyCodec), }, ) diff --git a/collections/indexes/unique.go b/collections/indexes/unique.go index 7b5c9654cb18..561ffad930fb 100644 --- a/collections/indexes/unique.go +++ b/collections/indexes/unique.go @@ -2,6 +2,8 @@ package indexes import ( "context" + "errors" + "fmt" "cosmossdk.io/collections" "cosmossdk.io/collections/codec" @@ -9,7 +11,10 @@ import ( // Unique identifies an index that imposes uniqueness constraints on the reference key. // It creates relationships between reference and primary key of the value. -type Unique[ReferenceKey, PrimaryKey, Value any] collections.GenericUniqueIndex[ReferenceKey, PrimaryKey, PrimaryKey, Value] +type Unique[ReferenceKey, PrimaryKey, Value any] struct { + getRefKey func(PrimaryKey, Value) (ReferenceKey, error) + refKeys collections.Map[ReferenceKey, PrimaryKey] +} // NewUnique instantiates a new Unique index. func NewUnique[ReferenceKey, PrimaryKey, Value any]( @@ -20,34 +25,65 @@ func NewUnique[ReferenceKey, PrimaryKey, Value any]( pkCodec codec.KeyCodec[PrimaryKey], getRefKeyFunc func(pk PrimaryKey, v Value) (ReferenceKey, error), ) *Unique[ReferenceKey, PrimaryKey, Value] { - i := collections.NewGenericUniqueIndex(schema, prefix, name, refCodec, pkCodec, func(pk PrimaryKey, value Value) ([]collections.IndexReference[ReferenceKey, PrimaryKey], error) { - ref, err := getRefKeyFunc(pk, value) + return &Unique[ReferenceKey, PrimaryKey, Value]{ + getRefKey: getRefKeyFunc, + refKeys: collections.NewMap(schema, prefix, name, refCodec, codec.KeyToValueCodec(pkCodec)), + } +} + +func (i *Unique[ReferenceKey, PrimaryKey, Value]) Reference(ctx context.Context, pk PrimaryKey, newValue Value, lazyOldValue func() (Value, error)) error { + oldValue, err := lazyOldValue() + switch { + // if no error it means the value existed, and we need to remove the old indexes + case err == nil: + err = i.unreference(ctx, pk, oldValue) if err != nil { - return nil, err + return err } - - return []collections.IndexReference[ReferenceKey, PrimaryKey]{ - collections.NewIndexReference(ref, pk), - }, nil - }) - - return (*Unique[ReferenceKey, PrimaryKey, Value])(i) + // if error is ErrNotFound, it means that the object does not exist, so we're creating indexes for the first time. + // we do nothing. + case errors.Is(err, collections.ErrNotFound): + // default case means that there was some other error + default: + return err + } + // create new indexes, asserting no uniqueness constraint violation + refKey, err := i.getRefKey(pk, newValue) + if err != nil { + return err + } + has, err := i.refKeys.Has(ctx, refKey) + if err != nil { + return err + } + if has { + return fmt.Errorf("%w: index uniqueness constrain violation: %s", collections.ErrConflict, i.refKeys.KeyCodec().Stringify(refKey)) + } + return i.refKeys.Set(ctx, refKey, pk) } -func (i *Unique[ReferenceKey, PrimaryKey, Value]) Reference(ctx context.Context, pk PrimaryKey, newValue Value, oldValue *Value) error { - return (*collections.GenericUniqueIndex[ReferenceKey, PrimaryKey, PrimaryKey, Value])(i).Reference(ctx, pk, newValue, oldValue) +func (i *Unique[ReferenceKey, PrimaryKey, Value]) Unreference(ctx context.Context, pk PrimaryKey, getValue func() (Value, error)) error { + value, err := getValue() + if err != nil { + return err + } + return i.unreference(ctx, pk, value) } -func (i *Unique[ReferenceKey, PrimaryKey, Value]) Unreference(ctx context.Context, pk PrimaryKey, value Value) error { - return (*collections.GenericUniqueIndex[ReferenceKey, PrimaryKey, PrimaryKey, Value])(i).Unreference(ctx, pk, value) +func (i *Unique[ReferenceKey, PrimaryKey, Value]) unreference(ctx context.Context, pk PrimaryKey, value Value) error { + refKey, err := i.getRefKey(pk, value) + if err != nil { + return err + } + return i.refKeys.Remove(ctx, refKey) } func (i *Unique[ReferenceKey, PrimaryKey, Value]) MatchExact(ctx context.Context, ref ReferenceKey) (PrimaryKey, error) { - return (*collections.GenericUniqueIndex[ReferenceKey, PrimaryKey, PrimaryKey, Value])(i).Get(ctx, ref) + return i.refKeys.Get(ctx, ref) } func (i *Unique[ReferenceKey, PrimaryKey, Value]) Iterate(ctx context.Context, ranger collections.Ranger[ReferenceKey]) (UniqueIterator[ReferenceKey, PrimaryKey], error) { - iter, err := (*collections.GenericUniqueIndex[ReferenceKey, PrimaryKey, PrimaryKey, Value])(i).Iterate(ctx, ranger) + iter, err := i.refKeys.Iterate(ctx, ranger) return (UniqueIterator[ReferenceKey, PrimaryKey])(iter), err } @@ -56,11 +92,11 @@ func (i *Unique[ReferenceKey, PrimaryKey, Value]) Walk( ranger collections.Ranger[ReferenceKey], walkFunc func(indexingKey ReferenceKey, indexedKey PrimaryKey) bool, ) error { - return (*collections.GenericUniqueIndex[ReferenceKey, PrimaryKey, PrimaryKey, Value])(i).Walk(ctx, ranger, walkFunc) + return i.refKeys.Walk(ctx, ranger, walkFunc) } func (i *Unique[ReferenceKey, PrimaryKey, Value]) IterateRaw(ctx context.Context, start, end []byte, order collections.Order) (u UniqueIterator[ReferenceKey, PrimaryKey], err error) { - iter, err := (*collections.GenericUniqueIndex[ReferenceKey, PrimaryKey, PrimaryKey, Value])(i).IterateRaw(ctx, start, end, order) + iter, err := i.refKeys.IterateRaw(ctx, start, end, order) if err != nil { return } diff --git a/collections/indexes/unique_test.go b/collections/indexes/unique_test.go index 6a03e94215b1..f3a174fc3981 100644 --- a/collections/indexes/unique_test.go +++ b/collections/indexes/unique_test.go @@ -15,15 +15,15 @@ func TestUniqueIndex(t *testing.T) { }) // map company with id 1 to vat 1_1 - err := ui.Reference(ctx, 1, company{Vat: 1_1}, nil) + err := ui.Reference(ctx, 1, company{Vat: 1_1}, func() (company, error) { return company{}, collections.ErrNotFound }) require.NoError(t, err) // map company with id 2 to vat 2_2 - err = ui.Reference(ctx, 2, company{Vat: 2_2}, nil) + err = ui.Reference(ctx, 2, company{Vat: 2_2}, func() (company, error) { return company{}, collections.ErrNotFound }) require.NoError(t, err) // mapping company 3 with vat 1_1 must yield to a ErrConflict - err = ui.Reference(ctx, 1, company{Vat: 1_1}, nil) + err = ui.Reference(ctx, 1, company{Vat: 1_1}, func() (company, error) { return company{}, collections.ErrNotFound }) require.ErrorIs(t, err, collections.ErrConflict) // assert references are correct @@ -36,7 +36,7 @@ func TestUniqueIndex(t *testing.T) { require.Equal(t, uint64(2), id) // on reference updates, the new referencing key is created and the old is removed - err = ui.Reference(ctx, 1, company{Vat: 1_2}, &company{Vat: 1_1}) + err = ui.Reference(ctx, 1, company{Vat: 1_2}, func() (company, error) { return company{Vat: 1_1}, nil }) require.NoError(t, err) id, err = ui.MatchExact(ctx, 1_2) // assert a new reference is created require.NoError(t, err) diff --git a/collections/indexes_generic_multi.go b/collections/indexes_generic_multi.go deleted file mode 100644 index fdb59d55af7d..000000000000 --- a/collections/indexes_generic_multi.go +++ /dev/null @@ -1,157 +0,0 @@ -package collections - -import ( - "context" - - "cosmossdk.io/collections/codec" -) - -func NewIndexReference[ReferencingKey, ReferencedKey any](referencing ReferencingKey, referenced ReferencedKey) IndexReference[ReferencingKey, ReferencedKey] { - return IndexReference[ReferencingKey, ReferencedKey]{ - Referring: referencing, - Referred: referenced, - } -} - -// IndexReference defines a generic index reference. -type IndexReference[ReferencingKey, ReferencedKey any] struct { - // Referring is the key that refers, points to the Referred key. - Referring ReferencingKey - // Referred is the key that is being pointed to by the Referring key. - Referred ReferencedKey -} - -// GenericMultiIndex defines a generic Index type that given a primary key -// and the value associated with that primary key returns one or multiple IndexReference. -// -// The referencing key can be anything, usually it is either a part of the primary -// key when we deal with multipart keys, or a field of Value. -// -// The referenced key usually is the primary key, or it can be a part -// of the primary key in the context of multipart keys. -// -// The Referencing and Referenced keys are joined and saved as a Pair in a KeySet -// where the key is Pair[ReferencingKey, ReferencedKey]. -// So if we wanted to get all the keys referenced by a generic (concrete) ReferencingKey -// we would just need to iterate over all the keys starting with bytes(ReferencingKey). -// -// Unless you're trying to build your generic multi index, you should be using the indexes package. -type GenericMultiIndex[ReferencingKey, ReferencedKey, PrimaryKey, Value any] struct { - refs KeySet[Pair[ReferencingKey, ReferencedKey]] - getRefs func(pk PrimaryKey, v Value) ([]IndexReference[ReferencingKey, ReferencedKey], error) -} - -// NewGenericMultiIndex instantiates a GenericMultiIndex, given -// schema, Prefix, humanised name, the key codec used to encode the referencing key -// to bytes, the key codec used to encode the referenced key to bytes and a function -// which given the primary key and a value of an object being saved or removed in IndexedMap -// returns all the possible IndexReference of that object. -// -// The IndexReference is usually just one. But in certain cases can be multiple, -// for example when the Value has an array field, and we want to create a relationship -// between the object and all the elements of the array contained in the object. -func NewGenericMultiIndex[ReferencingKey, ReferencedKey, PrimaryKey, Value any]( - schema *SchemaBuilder, - prefix Prefix, - name string, - referencingKeyCodec codec.KeyCodec[ReferencingKey], - referencedKeyCodec codec.KeyCodec[ReferencedKey], - getRefsFunc func(pk PrimaryKey, value Value) ([]IndexReference[ReferencingKey, ReferencedKey], error), -) *GenericMultiIndex[ReferencingKey, ReferencedKey, PrimaryKey, Value] { - return &GenericMultiIndex[ReferencingKey, ReferencedKey, PrimaryKey, Value]{ - getRefs: getRefsFunc, - refs: NewKeySet(schema, prefix, name, PairKeyCodec(referencingKeyCodec, referencedKeyCodec)), - } -} - -// Iterate allows to iterate over the index. It returns a KeySetIterator of Pair[ReferencingKey, ReferencedKey]. -// K1 of the Pair is the key (referencing) pointing to K2 (referenced). -func (i *GenericMultiIndex[ReferencingKey, ReferencedKey, PrimaryKey, Value]) Iterate( - ctx context.Context, - ranger Ranger[Pair[ReferencingKey, ReferencedKey]], -) (KeySetIterator[Pair[ReferencingKey, ReferencedKey]], error) { - return i.refs.Iterate(ctx, ranger) -} - -// Has reports if there is a relationship in the index between the referencing and the referenced key. -func (i *GenericMultiIndex[ReferencingKey, ReferencedKey, PrimaryKey, Value]) Has( - ctx context.Context, - referencing ReferencingKey, - referenced ReferencedKey, -) (bool, error) { - return i.refs.Has(ctx, Join(referencing, referenced)) -} - -// Reference implements the Index interface. -func (i *GenericMultiIndex[ReferencingKey, ReferencedKey, PrimaryKey, Value]) Reference( - ctx context.Context, - pk PrimaryKey, - value Value, - oldValue *Value, -) error { - if oldValue != nil { - err := i.Unreference(ctx, pk, *oldValue) - if err != nil { - return err - } - } - - refKeys, err := i.getRefs(pk, value) - if err != nil { - return err - } - - for _, ref := range refKeys { - err := i.refs.Set(ctx, Join(ref.Referring, ref.Referred)) - if err != nil { - return err - } - } - - return nil -} - -// Unreference implements the Index interface. -func (i *GenericMultiIndex[ReferencingKey, ReferencedKey, PrimaryKey, Value]) Unreference( - ctx context.Context, - pk PrimaryKey, - value Value, -) error { - refs, err := i.getRefs(pk, value) - if err != nil { - return err - } - - for _, ref := range refs { - err = i.refs.Remove(ctx, Join(ref.Referring, ref.Referred)) - if err != nil { - return err - } - } - - return nil -} - -func (i *GenericMultiIndex[ReferencingKey, ReferencedKey, PrimaryKey, Value]) IterateRaw( - ctx context.Context, - start, end []byte, - order Order, -) (Iterator[Pair[ReferencingKey, ReferencedKey], NoValue], error) { - return i.refs.IterateRaw(ctx, start, end, order) -} - -func (i *GenericMultiIndex[ReferencingKey, ReferencedKey, PrimaryKey, Value]) Walk( - ctx context.Context, - ranger Ranger[Pair[ReferencingKey, ReferencedKey]], - walkFunc func(referencingKey ReferencingKey, referencedKey ReferencedKey) bool, -) error { - return i.refs.Walk(ctx, ranger, func(key Pair[ReferencingKey, ReferencedKey]) bool { return walkFunc(key.K1(), key.K2()) }) -} - -func (i *GenericMultiIndex[ReferencingKey, ReferencedKey, PrimaryKey, Value]) KeyCodec() codec.KeyCodec[Pair[ReferencingKey, ReferencedKey]] { - return i.refs.KeyCodec() -} - -func (i *GenericMultiIndex[ReferencingKey, ReferencedKey, PrimaryKey, Value]) ValueCodec() codec.ValueCodec[NoValue] { - return i.refs.ValueCodec() -} diff --git a/collections/indexes_generic_multi_test.go b/collections/indexes_generic_multi_test.go deleted file mode 100644 index 6634dfcaec23..000000000000 --- a/collections/indexes_generic_multi_test.go +++ /dev/null @@ -1,83 +0,0 @@ -package collections - -import ( - "testing" - - "github.com/stretchr/testify/require" -) - -type coin struct { - denom string // this will be used as indexing field. - amount uint64 -} - -type balance struct { - coins []coin -} - -func TestGenericMultiIndex(t *testing.T) { - // we are simulating a context in which we have the following mapping: - // - // address (represented as string) => balance (slice of coins). - // - // we want to create an index that creates a relationship between the coin - // denom, which is part of the balance structure, and the address. This means - // we know given a denom who are the addresses holding that denom. - // From GenericMultiIndex point of view, the denom field of the array becomes - // the referencing key which points to the address (string), which is the key - // being referenced. - sk, ctx := deps() - sb := NewSchemaBuilder(sk) - mi := NewGenericMultiIndex( - sb, NewPrefix("denoms"), "denom_to_owner", StringKey, StringKey, - func(pk string, value balance) ([]IndexReference[string, string], error) { - // the referencing keys are all the denoms. - refs := make([]IndexReference[string, string], len(value.coins)) - // the index reference being created, generates a relationship - // between denom (the key that references) and pk (address, the key - // that is being referenced). - for i, coin := range value.coins { - refs[i] = NewIndexReference(coin.denom, pk) - } - return refs, nil - }, - ) - - // let's create the relationships - err := mi.Reference(ctx, "cosmosAddr1", balance{coins: []coin{ - {"atom", 1000}, {"osmo", 5000}, - }}, nil) - require.NoError(t, err) - - // we must find relations between cosmosaddr1 and the denom atom and osmo - iter, err := mi.Iterate(ctx, nil) - require.NoError(t, err) - - keys, err := iter.Keys() - require.NoError(t, err) - require.Len(t, keys, 2) - require.Equal(t, keys[0].K1(), "atom") // assert relationship with atom created - require.Equal(t, keys[1].K1(), "osmo") // assert relationship with osmo created - - // if we update the reference to remove osmo as balance then we must not find it anymore - err = mi.Reference(ctx, "cosmosAddr1", balance{coins: []coin{{"atom", 1000}}}, // this is the update which does not have osmo - &balance{coins: []coin{{"atom", 1000}, {"osmo", 5000}}}, // this is the previous record - ) - require.NoError(t, err) - - exists, err := mi.Has(ctx, "osmo", "cosmosAddr1") // osmo must not exist anymore - require.NoError(t, err) - require.False(t, exists) - - exists, err = mi.Has(ctx, "atom", "cosmosAddr1") // atom still exists - require.NoError(t, err) - require.True(t, exists) - - // if we unreference then no relationship is maintained anymore - err = mi.Unreference(ctx, "cosmosAddr1", balance{coins: []coin{{"atom", 1000}}}) - require.NoError(t, err) - - exists, err = mi.Has(ctx, "atom", "cosmosAddr1") // atom is not part of the index anymore because cosmosAddr1 was removed. - require.NoError(t, err) - require.False(t, exists) -} diff --git a/collections/indexes_generic_unique.go b/collections/indexes_generic_unique.go deleted file mode 100644 index 1b2d7b4c5828..000000000000 --- a/collections/indexes_generic_unique.go +++ /dev/null @@ -1,122 +0,0 @@ -package collections - -import ( - "context" - "fmt" - - "cosmossdk.io/collections/codec" -) - -// GenericUniqueIndex defines a generic index which enforces uniqueness constraints -// between ReferencingKey and ReferencedKey, meaning that one referencing key maps -// only one referenced key. The same referenced key can be mapped by multiple referencing keys. -// -// The referencing key can be anything, usually it is either a part of the primary -// key when we deal with multipart keys, or a field of Value. -// -// The referenced key usually is the primary key, or it can be a part -// of the primary key in the context of multipart keys. -// -// The referencing and referenced keys are mapped together using a Map. -// -// Unless you're trying to build your generic unique index, you should be using the indexes package. -type GenericUniqueIndex[ReferencingKey, ReferencedKey, PrimaryKey, Value any] struct { - refs Map[ReferencingKey, ReferencedKey] - getRefs func(pk PrimaryKey, value Value) ([]IndexReference[ReferencingKey, ReferencedKey], error) -} - -// NewGenericUniqueIndex instantiates a GenericUniqueIndex. Works in the same way as NewGenericMultiIndex. -func NewGenericUniqueIndex[ReferencingKey, ReferencedKey, PrimaryKey, Value any]( - schema *SchemaBuilder, - prefix Prefix, - name string, - referencingKeyCodec codec.KeyCodec[ReferencingKey], - referencedKeyCodec codec.KeyCodec[ReferencedKey], - getRefs func(pk PrimaryKey, value Value) ([]IndexReference[ReferencingKey, ReferencedKey], error), -) *GenericUniqueIndex[ReferencingKey, ReferencedKey, PrimaryKey, Value] { - return &GenericUniqueIndex[ReferencingKey, ReferencedKey, PrimaryKey, Value]{ - refs: NewMap[ReferencingKey, ReferencedKey](schema, prefix, name, referencingKeyCodec, codec.KeyToValueCodec(referencedKeyCodec)), - getRefs: getRefs, - } -} - -func (i *GenericUniqueIndex[ReferencingKey, ReferencedKey, PrimaryKey, Value]) Iterate( - ctx context.Context, - ranger Ranger[ReferencingKey], -) (Iterator[ReferencingKey, ReferencedKey], error) { - return i.refs.Iterate(ctx, ranger) -} - -func (i *GenericUniqueIndex[ReferencingKey, ReferencedKey, PrimaryKey, Value]) Get(ctx context.Context, ref ReferencingKey) (ReferencedKey, error) { - return i.refs.Get(ctx, ref) -} - -// Reference implements Index. -func (i *GenericUniqueIndex[ReferencingKey, ReferencedKey, PrimaryKey, Value]) Reference( - ctx context.Context, - pk PrimaryKey, - newValue Value, - oldValue *Value, -) error { - if oldValue != nil { - err := i.Unreference(ctx, pk, *oldValue) - if err != nil { - return err - } - } - refs, err := i.getRefs(pk, newValue) - if err != nil { - return err - } - for _, ref := range refs { - has, err := i.refs.Has(ctx, ref.Referring) - if err != nil { - return err - } - if has { - return fmt.Errorf("%w: index uniqueness constrain violation: %s", ErrConflict, i.refs.kc.Stringify(ref.Referring)) - } - err = i.refs.Set(ctx, ref.Referring, ref.Referred) - if err != nil { - return err - } - } - return nil -} - -// Unreference implements Index. -func (i *GenericUniqueIndex[ReferencingKey, ReferencedKey, PrimaryKey, Value]) Unreference( - ctx context.Context, - pk PrimaryKey, - value Value, -) error { - refs, err := i.getRefs(pk, value) - if err != nil { - return err - } - - for _, ref := range refs { - err = i.refs.Remove(ctx, ref.Referring) - if err != nil { - return err - } - } - - return nil -} - -func (i *GenericUniqueIndex[ReferencingKey, ReferencedKey, PrimaryKey, Value]) IterateRaw( - ctx context.Context, - start, end []byte, - order Order, -) (Iterator[ReferencingKey, ReferencedKey], error) { - return i.refs.IterateRaw(ctx, start, end, order) -} - -func (i *GenericUniqueIndex[ReferencingKey, ReferencedKey, PrimaryKey, Value]) Walk( - ctx context.Context, - ranger Ranger[ReferencingKey], - walkFunc func(referencingKey ReferencingKey, referencedKey ReferencedKey) bool, -) error { - return i.refs.Walk(ctx, ranger, func(k ReferencingKey, v ReferencedKey) bool { return walkFunc(k, v) }) -} diff --git a/collections/indexes_generic_unique_test.go b/collections/indexes_generic_unique_test.go deleted file mode 100644 index ae1e76ccecc7..000000000000 --- a/collections/indexes_generic_unique_test.go +++ /dev/null @@ -1,72 +0,0 @@ -package collections - -import ( - "testing" - - "github.com/stretchr/testify/require" -) - -type nftBalance struct { - nftIDs []uint64 -} - -func TestGenericUniqueIndex(t *testing.T) { - // we create the same testing context as with GenericMultiIndex. We have a mapping: - // Address => NFT balance. - // An NFT balance is represented as a slice of IDs, those IDs are unique, meaning that - // they can be held only by one address. - sk, ctx := deps() - sb := NewSchemaBuilder(sk) - ui := NewGenericUniqueIndex( - sb, NewPrefix("nft_to_owner_index"), "ntf_to_owner_index", Uint64Key, StringKey, - func(pk string, value nftBalance) ([]IndexReference[uint64, string], error) { - // the referencing keys are all the NFT unique ids. - refs := make([]IndexReference[uint64, string], len(value.nftIDs)) - // for each NFT contained in the balance we create an index reference - // between the NFT unique ID and the owner of the balance. - for i, id := range value.nftIDs { - refs[i] = NewIndexReference(id, pk) - } - return refs, nil - }, - ) - - // let's create the relationships - err := ui.Reference(ctx, "cosmosAddr1", nftBalance{nftIDs: []uint64{0, 1}}, nil) - require.NoError(t, err) - - // assert relations were created - iter, err := ui.Iterate(ctx, nil) - require.NoError(t, err) - defer iter.Close() - - kv, err := iter.KeyValues() - require.NoError(t, err) - require.Len(t, kv, 2) - require.Equal(t, kv[0].Key, uint64(0)) - require.Equal(t, kv[0].Value, "cosmosAddr1") - require.Equal(t, kv[1].Key, uint64(1)) - require.Equal(t, kv[1].Value, "cosmosAddr1") - - // assert only one address can own a unique NFT - err = ui.Reference(ctx, "cosmosAddr2", nftBalance{nftIDs: []uint64{0}}, nil) // nft with ID 0 is already owned by cosmosAddr1 - require.ErrorIs(t, err, ErrConflict) - - // during modifications references are updated, we update the index in - // such a way that cosmosAddr1 loses ownership of nft with id 0. - err = ui.Reference(ctx, "cosmosAddr1", - nftBalance{nftIDs: []uint64{1}}, // this is the update nft balance, which contains only id 1 - &nftBalance{nftIDs: []uint64{0, 1}}, // this is the old nft balance, which contains both 0 and 1 - ) - require.NoError(t, err) - - // the updated balance does not contain nft with id 0 - _, err = ui.Get(ctx, 0) - require.ErrorIs(t, err, ErrNotFound) - - // unreferencing clears all the indexes - err = ui.Unreference(ctx, "cosmosAddr1", nftBalance{nftIDs: []uint64{1}}) - require.NoError(t, err) - _, err = ui.Get(ctx, 1) - require.ErrorIs(t, err, ErrNotFound) -} diff --git a/collections/iter.go b/collections/iter.go index 6e51900986d8..976493608092 100644 --- a/collections/iter.go +++ b/collections/iter.go @@ -75,7 +75,7 @@ type Ranger[K any] interface { // iteration will yield keys from the smallest to the biggest, if order // is OrderDescending then the iteration will yield keys from the biggest to the smallest. // Ordering is defined by the keys bytes representation, which is dependent on the KeyCodec used. - RangeValues() (start *RangeKey[K], end *RangeKey[K], order Order, err error) + RangeValues() (start, end *RangeKey[K], order Order, err error) } // Range is a Ranger implementer. @@ -126,7 +126,7 @@ var ( errOrder = errors.New("collections: invalid order") ) -func (r *Range[K]) RangeValues() (start *RangeKey[K], end *RangeKey[K], order Order, err error) { +func (r *Range[K]) RangeValues() (start, end *RangeKey[K], order Order, err error) { return r.start, r.end, r.order, nil } diff --git a/collections/iter_test.go b/collections/iter_test.go index 8c1415c081e9..8569a6b93ffe 100644 --- a/collections/iter_test.go +++ b/collections/iter_test.go @@ -175,7 +175,7 @@ func TestWalk(t *testing.T) { } u := uint64(0) - err = m.Walk(ctx, nil, func(key uint64, value uint64) bool { + err = m.Walk(ctx, nil, func(key, value uint64) bool { if key == 5 { return true } diff --git a/collections/pair.go b/collections/pair.go index 7c86b5f77667..b0a789d55304 100644 --- a/collections/pair.go +++ b/collections/pair.go @@ -261,7 +261,7 @@ func (p *PairRange[K1, K2]) Descending() *PairRange[K1, K2] { return p } -func (p *PairRange[K1, K2]) RangeValues() (start *RangeKey[Pair[K1, K2]], end *RangeKey[Pair[K1, K2]], order Order, err error) { +func (p *PairRange[K1, K2]) RangeValues() (start, end *RangeKey[Pair[K1, K2]], order Order, err error) { if p.err != nil { return nil, nil, 0, err } diff --git a/collections/sequence.go b/collections/sequence.go index 4b4b86beaa96..2290d27a5d7e 100644 --- a/collections/sequence.go +++ b/collections/sequence.go @@ -6,13 +6,13 @@ import ( ) // DefaultSequenceStart defines the default starting number of a sequence. -const DefaultSequenceStart uint64 = 1 +const DefaultSequenceStart uint64 = 0 // Sequence builds on top of an Item, and represents a monotonically increasing number. type Sequence Item[uint64] // NewSequence instantiates a new sequence given -// a Schema, a Prefix and humanised name for the sequence. +// a Schema, a Prefix and humanized name for the sequence. func NewSequence(schema *SchemaBuilder, prefix Prefix, name string) Sequence { return (Sequence)(NewItem(schema, prefix, name, Uint64Value)) } diff --git a/contrib/devtools/Dockerfile b/contrib/devtools/Dockerfile index 30d61a97ec87..1fab041547c0 100644 --- a/contrib/devtools/Dockerfile +++ b/contrib/devtools/Dockerfile @@ -2,7 +2,7 @@ # docker build --pull --rm -f "contrib/devtools/Dockerfile" -t cosmossdk-proto:latest "contrib/devtools" # docker run --rm -v $(pwd):/workspace --workdir /workspace cosmossdk-proto sh ./scripts/protocgen.sh -FROM bufbuild/buf:1.15.1 as BUILDER +FROM bufbuild/buf:1.17.0 as BUILDER FROM golang:1.20-alpine RUN apk add --no-cache \ diff --git a/core/appconfig/config.go b/core/appconfig/config.go index f7b246bad46c..808c0cdc8aaa 100644 --- a/core/appconfig/config.go +++ b/core/appconfig/config.go @@ -84,7 +84,7 @@ func Compose(appConfig *appv1alpha1.Config) depinject.Config { module.Config.TypeUrl, appv1alpha1.E_Module.TypeDescriptor().FullName(), dumpRegisteredModules(modules))) } - return depinject.Error(fmt.Errorf("no module registered for type URL %s, did you forget to import %s\n\n%s", + return depinject.Error(fmt.Errorf("no module registered for type URL %s, did you forget to import %s: find more information on how to make a module ready for app wiring: https://docs.cosmos.network/main/building-modules/depinject\n\n%s", module.Config.TypeUrl, modDesc.GoImport, dumpRegisteredModules(modules))) } diff --git a/core/coins/format.go b/core/coins/format.go index 5c05ad430937..b31f18dae1de 100644 --- a/core/coins/format.go +++ b/core/coins/format.go @@ -2,6 +2,7 @@ package coins import ( "fmt" + "regexp" "sort" "strings" @@ -12,6 +13,11 @@ import ( const emptyCoins = "zero" +// Amount can be a whole number or a decimal number. Denominations can be 3 ~ 128 +// characters long and support letters, followed by either a letter, a number or +// a separator ('/', ':', '.', '_' or '-'). +var coinRegex = regexp.MustCompile(`^(\d+(\.\d+)?)([a-zA-Z][a-zA-Z0-9\/\:\._\-]{2,127})$`) + // formatCoin formats a sdk.Coin into a value-rendered string, using the // given metadata about the denom. It returns the formatted coin string, the // display denom, and an optional error. @@ -94,3 +100,24 @@ func FormatCoins(coins []*basev1beta1.Coin, metadata []*bankv1beta1.Metadata) (s return strings.Join(formatted, ", "), nil } + +// ParseCoin parses a coin from a string. The string must be in the format +// , where is a number and is a valid denom. +func ParseCoin(input string) (*basev1beta1.Coin, error) { + input = strings.TrimSpace(input) + + if input == "" { + return nil, fmt.Errorf("empty input when parsing coin") + } + + matches := coinRegex.FindStringSubmatch(input) + + if len(matches) == 0 { + return nil, fmt.Errorf("invalid input format") + } + + return &basev1beta1.Coin{ + Amount: matches[1], + Denom: matches[3], + }, nil +} diff --git a/core/coins/format_test.go b/core/coins/format_test.go index ded6a8760bbb..f17d449791f2 100644 --- a/core/coins/format_test.go +++ b/core/coins/format_test.go @@ -12,15 +12,15 @@ import ( ) // coinsJsonTest is the type of test cases in the coin.json file. -type coinJsonTest struct { +type coinJSONTest struct { Proto *basev1beta1.Coin Metadata *bankv1beta1.Metadata Text string Error bool } -// coinsJsonTest is the type of test cases in the coins.json file. -type coinsJsonTest struct { +// coinsJSONTest is the type of test cases in the coins.json file. +type coinsJSONTest struct { Proto []*basev1beta1.Coin Metadata map[string]*bankv1beta1.Metadata Text string @@ -28,7 +28,7 @@ type coinsJsonTest struct { } func TestFormatCoin(t *testing.T) { - var testcases []coinJsonTest + var testcases []coinJSONTest raw, err := os.ReadFile("../../x/tx/signing/textual/internal/testdata/coin.json") require.NoError(t, err) err = json.Unmarshal(raw, &testcases) @@ -52,7 +52,7 @@ func TestFormatCoin(t *testing.T) { } func TestFormatCoins(t *testing.T) { - var testcases []coinsJsonTest + var testcases []coinsJSONTest raw, err := os.ReadFile("../../x/tx/signing/textual/internal/testdata/coins.json") require.NoError(t, err) err = json.Unmarshal(raw, &testcases) @@ -79,3 +79,11 @@ func TestFormatCoins(t *testing.T) { }) } } + +func TestDecodeCoin(t *testing.T) { + encodedCoin := "1000000000foo" + coin, err := coins.ParseCoin(encodedCoin) + require.NoError(t, err) + require.Equal(t, "1000000000", coin.Amount) + require.Equal(t, "foo", coin.Denom) +} diff --git a/core/go.mod b/core/go.mod index 9a1350d5ae25..3da0135596ee 100644 --- a/core/go.mod +++ b/core/go.mod @@ -3,7 +3,7 @@ module cosmossdk.io/core go 1.20 require ( - cosmossdk.io/api v0.3.1 + cosmossdk.io/api v0.4.0 cosmossdk.io/depinject v1.0.0-alpha.3 cosmossdk.io/math v1.0.0 github.com/cosmos/cosmos-db v1.0.0-rc.1 @@ -23,7 +23,7 @@ require ( github.com/cockroachdb/logtags v0.0.0-20230118201751-21c54148d20b // indirect github.com/cockroachdb/pebble v0.0.0-20230226194802-02d779ffbc46 // indirect github.com/cockroachdb/redact v1.1.3 // indirect - github.com/cosmos/gogoproto v1.4.6 // indirect + github.com/cosmos/gogoproto v1.4.7 // indirect github.com/davecgh/go-spew v1.1.1 // indirect github.com/getsentry/sentry-go v0.18.0 // indirect github.com/gogo/protobuf v1.3.2 // indirect @@ -38,7 +38,7 @@ require ( github.com/matttproud/golang_protobuf_extensions v1.0.4 // indirect github.com/pkg/errors v0.9.1 // indirect github.com/pmezard/go-difflib v1.0.0 // indirect - github.com/prometheus/client_golang v1.14.0 // indirect + github.com/prometheus/client_golang v1.15.0 // indirect github.com/prometheus/client_model v0.3.0 // indirect github.com/prometheus/common v0.42.0 // indirect github.com/prometheus/procfs v0.9.0 // indirect diff --git a/core/go.sum b/core/go.sum index 3204efe39d41..84c4c6f5271c 100644 --- a/core/go.sum +++ b/core/go.sum @@ -1,6 +1,6 @@ cloud.google.com/go v0.26.0/go.mod h1:aQUYkXzVsufM+DwF1aE+0xfcU+56JwCaLick0ClmMTw= -cosmossdk.io/api v0.3.1 h1:NNiOclKRR0AOlO4KIqeaG6PS6kswOMhHD0ir0SscNXE= -cosmossdk.io/api v0.3.1/go.mod h1:DfHfMkiNA2Uhy8fj0JJlOCYOBp4eWUUJ1te5zBGNyIw= +cosmossdk.io/api v0.4.0 h1:x90DmdidP6EhzktAa/6/IofSHidDnPjahdlrUvyQZQw= +cosmossdk.io/api v0.4.0/go.mod h1:TWDzBhUBhI1LhSf2XSYpfIBf6D4mbLu/fvzvDfhcaYM= cosmossdk.io/depinject v1.0.0-alpha.3 h1:6evFIgj//Y3w09bqOUOzEpFj5tsxBqdc5CfkO7z+zfw= cosmossdk.io/depinject v1.0.0-alpha.3/go.mod h1:eRbcdQ7MRpIPEM5YUJh8k97nxHpYbc3sMUnEtt8HPWU= cosmossdk.io/math v1.0.0 h1:ro9w7eKx23om2tZz/VM2Pf+z2WAbGX1yDQQOJ6iGeJw= @@ -47,8 +47,8 @@ github.com/cosmos/cosmos-db v1.0.0-rc.1 h1:SjnT8B6WKMW9WEIX32qMhnEEKcI7ZP0+G1Sa9 github.com/cosmos/cosmos-db v1.0.0-rc.1/go.mod h1:Dnmk3flSf5lkwCqvvjNpoxjpXzhxnCAFzKHlbaForso= github.com/cosmos/cosmos-proto v1.0.0-beta.3 h1:VitvZ1lPORTVxkmF2fAp3IiA61xVwArQYKXTdEcpW6o= github.com/cosmos/cosmos-proto v1.0.0-beta.3/go.mod h1:t8IASdLaAq+bbHbjq4p960BvcTqtwuAxid3b/2rOD6I= -github.com/cosmos/gogoproto v1.4.6 h1:Ee7z15dWJaGlgM2rWrK8N2IX7PQcuccu8oG68jp5RL4= -github.com/cosmos/gogoproto v1.4.6/go.mod h1:VS/ASYmPgv6zkPKLjR9EB91lwbLHOzaGCirmKKhncfI= +github.com/cosmos/gogoproto v1.4.7 h1:RzYKVnsEC7UIkDnhTIkqEB7LnIQbsySvmNEqPCiPevk= +github.com/cosmos/gogoproto v1.4.7/go.mod h1:gxGePp9qedovvl/StQL2BIJ6qlIBn1+9YxR0IulGBKA= github.com/cpuguy83/go-md2man v1.0.10/go.mod h1:SmD6nW6nTyfqj6ABTjUi3V3JVMnlJmwcJI5acqYI6dE= github.com/creack/pty v1.1.9/go.mod h1:oKZEueFk5CKHvIhNR5MUki03XCEU+Q6VDXinZuGJ33E= github.com/cucumber/common/gherkin/go/v22 v22.0.0 h1:4K8NqptbvdOrjL9DEea6HFjSpbdT9+Q5kgLpmmsHYl0= @@ -219,8 +219,8 @@ github.com/pkg/errors v0.9.1 h1:FEBLx1zS214owpjy7qsBeixbURkuhQAwrK5UwLGTwt4= github.com/pkg/errors v0.9.1/go.mod h1:bwawxfHBFNV+L2hUp1rHADufV3IMtnDRdf1r5NINEl0= github.com/pmezard/go-difflib v1.0.0 h1:4DBwDE0NGyQoBHbLQYPwSUPoCMWR5BEzIk/f1lZbAQM= github.com/pmezard/go-difflib v1.0.0/go.mod h1:iKH77koFhYxTK1pcRnkKkqfTogsbg7gZNVY4sRDYZ/4= -github.com/prometheus/client_golang v1.14.0 h1:nJdhIvne2eSX/XRAFV9PcvFFRbrjbcTUj0VP62TMhnw= -github.com/prometheus/client_golang v1.14.0/go.mod h1:8vpkKitgIVNcqrRBWh1C4TIUQgYNtG/XQE4E/Zae36Y= +github.com/prometheus/client_golang v1.15.0 h1:5fCgGYogn0hFdhyhLbw7hEsWxufKtY9klyvdNfFlFhM= +github.com/prometheus/client_golang v1.15.0/go.mod h1:e9yaBhRPU2pPNsZwE+JdQl0KEt1N9XgF6zxWmaC0xOk= github.com/prometheus/client_model v0.0.0-20190812154241-14fe0d1b01d4/go.mod h1:xMI15A0UPsDsEKsMN9yxemIoYk6Tm2C1GtYGdfGttqA= github.com/prometheus/client_model v0.3.0 h1:UBgGFHqYdG/TPFD1B1ogZywDqEkwp3fBMvqdiQ7Xew4= github.com/prometheus/client_model v0.3.0/go.mod h1:LDGWKZIo7rky3hgvBe+caln+Dr3dPggB5dvjtD7w9+w= diff --git a/crypto/armor.go b/crypto/armor.go index b65854262387..78e723f0023a 100644 --- a/crypto/armor.go +++ b/crypto/armor.go @@ -7,7 +7,7 @@ import ( "io" "github.com/cometbft/cometbft/crypto" - "golang.org/x/crypto/openpgp/armor" //nolint:staticcheck + "golang.org/x/crypto/openpgp/armor" //nolint:staticcheck // TODO: remove this dependency errorsmod "cosmossdk.io/errors" @@ -128,7 +128,7 @@ func unarmorBytes(armorStr, blockType string) (bz []byte, header map[string]stri // encrypt/decrypt with armor // Encrypt and armor the private key. -func EncryptArmorPrivKey(privKey cryptotypes.PrivKey, passphrase string, algo string) string { +func EncryptArmorPrivKey(privKey cryptotypes.PrivKey, passphrase, algo string) string { saltBytes, encBytes := encryptPrivKey(privKey, passphrase) header := map[string]string{ "kdf": "bcrypt", @@ -147,7 +147,7 @@ func EncryptArmorPrivKey(privKey cryptotypes.PrivKey, passphrase string, algo st // encrypt the given privKey with the passphrase using a randomly // generated salt and the xsalsa20 cipher. returns the salt and the // encrypted priv key. -func encryptPrivKey(privKey cryptotypes.PrivKey, passphrase string) (saltBytes []byte, encBytes []byte) { +func encryptPrivKey(privKey cryptotypes.PrivKey, passphrase string) (saltBytes, encBytes []byte) { saltBytes = crypto.CRandBytes(16) key, err := bcrypt.GenerateFromPassword(saltBytes, []byte(passphrase), BcryptSecurityParameter) if err != nil { @@ -161,7 +161,7 @@ func encryptPrivKey(privKey cryptotypes.PrivKey, passphrase string) (saltBytes [ } // UnarmorDecryptPrivKey returns the privkey byte slice, a string of the algo type, and an error -func UnarmorDecryptPrivKey(armorStr string, passphrase string) (privKey cryptotypes.PrivKey, algo string, err error) { +func UnarmorDecryptPrivKey(armorStr, passphrase string) (privKey cryptotypes.PrivKey, algo string, err error) { blockType, header, encBytes, err := DecodeArmor(armorStr) if err != nil { return privKey, "", err @@ -193,7 +193,7 @@ func UnarmorDecryptPrivKey(armorStr string, passphrase string) (privKey cryptoty return privKey, header[headerType], err } -func decryptPrivKey(saltBytes []byte, encBytes []byte, passphrase string) (privKey cryptotypes.PrivKey, err error) { +func decryptPrivKey(saltBytes, encBytes []byte, passphrase string) (privKey cryptotypes.PrivKey, err error) { key, err := bcrypt.GenerateFromPassword(saltBytes, []byte(passphrase), BcryptSecurityParameter) if err != nil { return privKey, errorsmod.Wrap(err, "error generating bcrypt key from passphrase") diff --git a/crypto/armor_test.go b/crypto/armor_test.go index 60ed5a495aee..23c5e629cf2b 100644 --- a/crypto/armor_test.go +++ b/crypto/armor_test.go @@ -50,7 +50,7 @@ func TestArmorUnarmorPrivKey(t *testing.T) { require.Contains(t, err.Error(), "unrecognized armor type") // armor key manually - encryptPrivKeyFn := func(privKey cryptotypes.PrivKey, passphrase string) (saltBytes []byte, encBytes []byte) { + encryptPrivKeyFn := func(privKey cryptotypes.PrivKey, passphrase string) (saltBytes, encBytes []byte) { saltBytes = cmtcrypto.CRandBytes(16) key, err := bcrypt.GenerateFromPassword(saltBytes, []byte(passphrase), crypto.BcryptSecurityParameter) require.NoError(t, err) diff --git a/crypto/codec/amino.go b/crypto/codec/amino.go index 27bb10ce46b4..988c17ba1976 100644 --- a/crypto/codec/amino.go +++ b/crypto/codec/amino.go @@ -26,7 +26,7 @@ func RegisterCrypto(cdc *codec.LegacyAmino) { cdc.RegisterInterface((*cryptotypes.PrivKey)(nil), nil) cdc.RegisterConcrete(sr25519.PrivKey{}, sr25519.PrivKeyName, nil) - cdc.RegisterConcrete(&ed25519.PrivKey{}, //nolint:staticcheck + cdc.RegisterConcrete(&ed25519.PrivKey{}, ed25519.PrivKeyName, nil) cdc.RegisterConcrete(&secp256k1.PrivKey{}, secp256k1.PrivKeyName, nil) diff --git a/crypto/codec/proto.go b/crypto/codec/proto.go index 1340dab03de5..45cd5b4c35df 100644 --- a/crypto/codec/proto.go +++ b/crypto/codec/proto.go @@ -20,6 +20,6 @@ func RegisterInterfaces(registry codectypes.InterfaceRegistry) { var priv *cryptotypes.PrivKey registry.RegisterInterface("cosmos.crypto.PrivKey", priv) registry.RegisterImplementations(priv, &secp256k1.PrivKey{}) - registry.RegisterImplementations(priv, &ed25519.PrivKey{}) //nolint + registry.RegisterImplementations(priv, &ed25519.PrivKey{}) secp256r1.RegisterInterfaces(registry) } diff --git a/crypto/hd/algo.go b/crypto/hd/algo.go index 0feb4ff49b47..58a5d4534240 100644 --- a/crypto/hd/algo.go +++ b/crypto/hd/algo.go @@ -26,12 +26,12 @@ const ( var Secp256k1 = secp256k1Algo{} type ( - DeriveFn func(mnemonic string, bip39Passphrase, hdPath string) ([]byte, error) + DeriveFn func(mnemonic, bip39Passphrase, hdPath string) ([]byte, error) GenerateFn func(bz []byte) types.PrivKey ) type WalletGenerator interface { - Derive(mnemonic string, bip39Passphrase, hdPath string) ([]byte, error) + Derive(mnemonic, bip39Passphrase, hdPath string) ([]byte, error) Generate(bz []byte) types.PrivKey } @@ -43,7 +43,7 @@ func (s secp256k1Algo) Name() PubKeyType { // Derive derives and returns the secp256k1 private key for the given seed and HD path. func (s secp256k1Algo) Derive() DeriveFn { - return func(mnemonic string, bip39Passphrase, hdPath string) ([]byte, error) { + return func(mnemonic, bip39Passphrase, hdPath string) ([]byte, error) { seed, err := bip39.NewSeedWithErrorChecking(mnemonic, bip39Passphrase) if err != nil { return nil, err diff --git a/crypto/hd/hdpath.go b/crypto/hd/hdpath.go index 4813053d0f63..7873ea0a2c0b 100644 --- a/crypto/hd/hdpath.go +++ b/crypto/hd/hdpath.go @@ -156,7 +156,7 @@ func (p BIP44Params) String() string { } // ComputeMastersFromSeed returns the master secret key's, and chain code. -func ComputeMastersFromSeed(seed []byte) (secret [32]byte, chainCode [32]byte) { +func ComputeMastersFromSeed(seed []byte) (secret, chainCode [32]byte) { curveIdentifier := []byte("Bitcoin seed") secret, chainCode = i64(curveIdentifier, seed) @@ -216,7 +216,7 @@ func DerivePrivateKeyForPath(privKeyBytes, chainCode [32]byte, path string) ([]b // It returns the new private key and new chain code. // For more information on hardened keys see: // - https://github.com/bitcoin/bips/blob/master/bip-0032.mediawiki -func derivePrivateKey(privKeyBytes [32]byte, chainCode [32]byte, index uint32, harden bool) ([32]byte, [32]byte) { +func derivePrivateKey(privKeyBytes, chainCode [32]byte, index uint32, harden bool) ([32]byte, [32]byte) { var data []byte if harden { @@ -244,7 +244,7 @@ func derivePrivateKey(privKeyBytes [32]byte, chainCode [32]byte, index uint32, h } // modular big endian addition -func addScalars(a []byte, b []byte) [32]byte { +func addScalars(a, b []byte) [32]byte { aInt := new(big.Int).SetBytes(a) bInt := new(big.Int).SetBytes(b) sInt := new(big.Int).Add(aInt, bInt) @@ -263,7 +263,7 @@ func uint32ToBytes(i uint32) []byte { } // i64 returns the two halfs of the SHA512 HMAC of key and data. -func i64(key []byte, data []byte) (il [32]byte, ir [32]byte) { +func i64(key, data []byte) (il, ir [32]byte) { mac := hmac.New(sha512.New, key) // sha512 does not err _, _ = mac.Write(data) diff --git a/crypto/hd/hdpath_test.go b/crypto/hd/hdpath_test.go index 126a2a24f0ef..cce81df86f20 100644 --- a/crypto/hd/hdpath_test.go +++ b/crypto/hd/hdpath_test.go @@ -185,7 +185,7 @@ func TestDeriveHDPathRange(t *testing.T) { } } -func ExampleStringifyPathParams() { //nolint:govet +func ExampleStringifyPathParams() { //nolint:govet // ignore naming convention path := hd.NewParams(44, 0, 0, false, 0) fmt.Println(path.String()) path = hd.NewParams(44, 33, 7, true, 9) @@ -195,7 +195,7 @@ func ExampleStringifyPathParams() { //nolint:govet // m/44'/33'/7'/1/9 } -func ExampleSomeBIP32TestVecs() { //nolint:govet +func ExampleSomeBIP32TestVecs() { //nolint:govet // ignore naming convention seed := mnemonicToSeed("barrel original fuel morning among eternal " + "filter ball stove pluck matrix mechanic") master, ch := hd.ComputeMastersFromSeed(seed) diff --git a/crypto/keyring/keyring_test.go b/crypto/keyring/keyring_test.go index 451e900f0bd0..e89b0ff24652 100644 --- a/crypto/keyring/keyring_test.go +++ b/crypto/keyring/keyring_test.go @@ -1978,7 +1978,7 @@ func TestChangeBcrypt(t *testing.T) { require.NoError(t, err) } -func requireEqualRenamedKey(t *testing.T, key *Record, mnemonic *Record, nameMatch bool) { +func requireEqualRenamedKey(t *testing.T, key, mnemonic *Record, nameMatch bool) { if nameMatch { require.Equal(t, key.Name, mnemonic.Name) } diff --git a/crypto/keys/bcrypt/bcrypt.go b/crypto/keys/bcrypt/bcrypt.go index ab0ad4708eae..9badc4670cd1 100644 --- a/crypto/keys/bcrypt/bcrypt.go +++ b/crypto/keys/bcrypt/bcrypt.go @@ -85,7 +85,7 @@ type hashed struct { // cost. If the cost given is less than MinCost, the cost will be set to // DefaultCost, instead. Use CompareHashAndPassword, as defined in this package, // to compare the returned hashed password with its cleartext version. -func GenerateFromPassword(salt []byte, password []byte, cost uint32) ([]byte, error) { +func GenerateFromPassword(salt, password []byte, cost uint32) ([]byte, error) { if len(salt) != maxSaltSize { return nil, fmt.Errorf("salt len must be %v", maxSaltSize) } @@ -129,7 +129,7 @@ func Cost(hashedPassword []byte) (uint32, error) { return p.cost, nil } -func newFromPassword(salt []byte, password []byte, cost uint32) (*hashed, error) { +func newFromPassword(salt, password []byte, cost uint32) (*hashed, error) { if cost < MinCost { cost = DefaultCost } @@ -210,7 +210,7 @@ func expensiveBlowfishSetup(key []byte, cost uint32, salt []byte) (*blowfish.Cip // Bug compatibility with C bcrypt implementations. They use the trailing // NULL in the key string during expansion. // We copy the key to prevent changing the underlying array. - ckey := append(key[:len(key):len(key)], 0) //nolint:gocritic // used in original https://cs.opensource.google/go/x/crypto/+/master:bcrypt/bcrypt.go + ckey := append(key[:len(key):len(key)], 0) c, err := blowfish.NewSaltedCipher(ckey, csalt) if err != nil { diff --git a/crypto/keys/ed25519/ed25519.go b/crypto/keys/ed25519/ed25519.go index d2dc54a32d94..122be97cb254 100644 --- a/crypto/keys/ed25519/ed25519.go +++ b/crypto/keys/ed25519/ed25519.go @@ -94,12 +94,12 @@ func (privKey *PrivKey) Type() string { return keyType } -// MarshalAmino overrides Amino binary marshalling. +// MarshalAmino overrides Amino binary marshaling. func (privKey PrivKey) MarshalAmino() ([]byte, error) { return privKey.Key, nil } -// UnmarshalAmino overrides Amino binary marshalling. +// UnmarshalAmino overrides Amino binary marshaling. func (privKey *PrivKey) UnmarshalAmino(bz []byte) error { if len(bz) != PrivKeySize { return fmt.Errorf("invalid privkey size") @@ -109,14 +109,14 @@ func (privKey *PrivKey) UnmarshalAmino(bz []byte) error { return nil } -// MarshalAminoJSON overrides Amino JSON marshalling. +// MarshalAminoJSON overrides Amino JSON marshaling. func (privKey PrivKey) MarshalAminoJSON() ([]byte, error) { // When we marshal to Amino JSON, we don't marshal the "key" field itself, // just its contents (i.e. the key bytes). return privKey.MarshalAmino() } -// UnmarshalAminoJSON overrides Amino JSON marshalling. +// UnmarshalAminoJSON overrides Amino JSON marshaling. func (privKey *PrivKey) UnmarshalAminoJSON(bz []byte) error { return privKey.UnmarshalAmino(bz) } @@ -176,7 +176,7 @@ func (pubKey *PubKey) Bytes() []byte { return pubKey.Key } -func (pubKey *PubKey) VerifySignature(msg []byte, sig []byte) bool { +func (pubKey *PubKey) VerifySignature(msg, sig []byte) bool { // make sure we use the same algorithm to sign if len(sig) != SignatureSize { return false @@ -203,12 +203,12 @@ func (pubKey *PubKey) Equals(other cryptotypes.PubKey) bool { return subtle.ConstantTimeCompare(pubKey.Bytes(), other.Bytes()) == 1 } -// MarshalAmino overrides Amino binary marshalling. +// MarshalAmino overrides Amino binary marshaling. func (pubKey PubKey) MarshalAmino() ([]byte, error) { return pubKey.Key, nil } -// UnmarshalAmino overrides Amino binary marshalling. +// UnmarshalAmino overrides Amino binary marshaling. func (pubKey *PubKey) UnmarshalAmino(bz []byte) error { if len(bz) != PubKeySize { return errorsmod.Wrap(errors.ErrInvalidPubKey, "invalid pubkey size") @@ -218,14 +218,14 @@ func (pubKey *PubKey) UnmarshalAmino(bz []byte) error { return nil } -// MarshalAminoJSON overrides Amino JSON marshalling. +// MarshalAminoJSON overrides Amino JSON marshaling. func (pubKey PubKey) MarshalAminoJSON() ([]byte, error) { // When we marshal to Amino JSON, we don't marshal the "key" field itself, // just its contents (i.e. the key bytes). return pubKey.MarshalAmino() } -// UnmarshalAminoJSON overrides Amino JSON marshalling. +// UnmarshalAminoJSON overrides Amino JSON marshaling. func (pubKey *PubKey) UnmarshalAminoJSON(bz []byte) error { return pubKey.UnmarshalAmino(bz) } diff --git a/crypto/keys/ed25519/keys.pb.go b/crypto/keys/ed25519/keys.pb.go index 1280647df3ec..e24a1b3b35fb 100644 --- a/crypto/keys/ed25519/keys.pb.go +++ b/crypto/keys/ed25519/keys.pb.go @@ -73,7 +73,7 @@ func (m *PubKey) GetKey() crypto_ed25519.PublicKey { return nil } -// Deprecated: PrivKey defines a ed25519 private key. +// PrivKey defines a ed25519 private key. // NOTE: ed25519 keys must not be used in SDK apps except in a tendermint validator context. type PrivKey struct { Key crypto_ed25519.PrivateKey `protobuf:"bytes,1,opt,name=key,proto3,casttype=crypto/ed25519.PrivateKey" json:"key,omitempty"` diff --git a/crypto/keys/internal/ecdsa/privkey.go b/crypto/keys/internal/ecdsa/privkey.go index 2aeedb1c4ddc..1d642ab9a498 100644 --- a/crypto/keys/internal/ecdsa/privkey.go +++ b/crypto/keys/internal/ecdsa/privkey.go @@ -39,7 +39,7 @@ func NormalizeS(sigS *big.Int) *big.Int { // signatureRaw will serialize signature to R || S. // R, S are padded to 32 bytes respectively. // code roughly copied from secp256k1_nocgo.go -func signatureRaw(r *big.Int, s *big.Int) []byte { +func signatureRaw(r, s *big.Int) []byte { rBytes := r.Bytes() sBytes := s.Bytes() sigBytes := make([]byte, 64) diff --git a/crypto/keys/internal/ecdsa/pubkey.go b/crypto/keys/internal/ecdsa/pubkey.go index a0b5df4401c7..1141baebec02 100644 --- a/crypto/keys/internal/ecdsa/pubkey.go +++ b/crypto/keys/internal/ecdsa/pubkey.go @@ -61,7 +61,7 @@ func (pk *PubKey) Bytes() []byte { // where the s integer component of the signature is in the // lower half of the curve order // 7/21/21 - expects raw encoded signature (fixed-width 64-bytes, R || S) -func (pk *PubKey) VerifySignature(msg []byte, sig []byte) bool { +func (pk *PubKey) VerifySignature(msg, sig []byte) bool { // check length for raw signature // which is two 32-byte padded big.Ints // concatenated diff --git a/crypto/keys/multisig/amino.go b/crypto/keys/multisig/amino.go index 8c83b27021f1..1973a31a66c6 100644 --- a/crypto/keys/multisig/amino.go +++ b/crypto/keys/multisig/amino.go @@ -66,7 +66,7 @@ func tmToProto(tmPk tmMultisig) (*LegacyAminoPubKey, error) { } // MarshalAminoJSON overrides amino JSON unmarshaling. -func (m LegacyAminoPubKey) MarshalAminoJSON() (tmMultisig, error) { //nolint:golint,revive +func (m LegacyAminoPubKey) MarshalAminoJSON() (tmMultisig, error) { //nolint:golint,revive // we need to override the default amino JSON marshaling return protoToTm(&m) } diff --git a/crypto/keys/multisig/multisig.go b/crypto/keys/multisig/multisig.go index 892ae3b7b895..10f7d2e04000 100644 --- a/crypto/keys/multisig/multisig.go +++ b/crypto/keys/multisig/multisig.go @@ -100,7 +100,7 @@ func (m *LegacyAminoPubKey) VerifyMultisignature(getSignBytes multisigtypes.GetS // VerifySignature implements cryptotypes.PubKey VerifySignature method, // it panics because it can't handle MultiSignatureData // cf. https://github.com/cosmos/cosmos-sdk/issues/7109#issuecomment-686329936 -func (m *LegacyAminoPubKey) VerifySignature(msg []byte, sig []byte) bool { +func (m *LegacyAminoPubKey) VerifySignature(msg, sig []byte) bool { panic("not implemented") } diff --git a/crypto/keys/secp256k1/internal/secp256k1/secp256.go b/crypto/keys/secp256k1/internal/secp256k1/secp256.go index c9c01b3209af..d4e574da0d2b 100644 --- a/crypto/keys/secp256k1/internal/secp256k1/secp256.go +++ b/crypto/keys/secp256k1/internal/secp256k1/secp256.go @@ -67,7 +67,7 @@ var ( // The caller is responsible for ensuring that msg cannot be chosen // directly by an attacker. It is usually preferable to use a cryptographic // hash function on any input before handing it to this function. -func Sign(msg []byte, seckey []byte) ([]byte, error) { +func Sign(msg, seckey []byte) ([]byte, error) { if len(msg) != 32 { return nil, ErrInvalidMsgLen } @@ -102,7 +102,7 @@ func Sign(msg []byte, seckey []byte) ([]byte, error) { // msg must be the 32-byte hash of the message to be signed. // sig must be a 65-byte compact ECDSA signature containing the // recovery id as the last element. -func RecoverPubkey(msg []byte, sig []byte) ([]byte, error) { +func RecoverPubkey(msg, sig []byte) ([]byte, error) { if len(msg) != 32 { return nil, ErrInvalidMsgLen } diff --git a/crypto/keys/secp256k1/secp256k1.go b/crypto/keys/secp256k1/secp256k1.go index 68208f859aef..a4860fbb9240 100644 --- a/crypto/keys/secp256k1/secp256k1.go +++ b/crypto/keys/secp256k1/secp256k1.go @@ -11,7 +11,7 @@ import ( errorsmod "cosmossdk.io/errors" "github.com/cometbft/cometbft/crypto" secp256k1 "github.com/decred/dcrd/dcrec/secp256k1/v4" - "golang.org/x/crypto/ripemd160" //nolint: staticcheck + "golang.org/x/crypto/ripemd160" //nolint: staticcheck // keep around for backwards compatibility "github.com/cosmos/cosmos-sdk/codec" cryptotypes "github.com/cosmos/cosmos-sdk/crypto/types" @@ -53,12 +53,12 @@ func (privKey *PrivKey) Type() string { return keyType } -// MarshalAmino overrides Amino binary marshalling. +// MarshalAmino overrides Amino binary marshaling. func (privKey PrivKey) MarshalAmino() ([]byte, error) { return privKey.Key, nil } -// UnmarshalAmino overrides Amino binary marshalling. +// UnmarshalAmino overrides Amino binary marshaling. func (privKey *PrivKey) UnmarshalAmino(bz []byte) error { if len(bz) != PrivKeySize { return fmt.Errorf("invalid privkey size") @@ -68,14 +68,14 @@ func (privKey *PrivKey) UnmarshalAmino(bz []byte) error { return nil } -// MarshalAminoJSON overrides Amino JSON marshalling. +// MarshalAminoJSON overrides Amino JSON marshaling. func (privKey PrivKey) MarshalAminoJSON() ([]byte, error) { // When we marshal to Amino JSON, we don't marshal the "key" field itself, // just its contents (i.e. the key bytes). return privKey.MarshalAmino() } -// UnmarshalAminoJSON overrides Amino JSON marshalling. +// UnmarshalAminoJSON overrides Amino JSON marshaling. func (privKey *PrivKey) UnmarshalAminoJSON(bz []byte) error { return privKey.UnmarshalAmino(bz) } @@ -179,12 +179,12 @@ func (pubKey *PubKey) Equals(other cryptotypes.PubKey) bool { return pubKey.Type() == other.Type() && bytes.Equal(pubKey.Bytes(), other.Bytes()) } -// MarshalAmino overrides Amino binary marshalling. +// MarshalAmino overrides Amino binary marshaling. func (pubKey PubKey) MarshalAmino() ([]byte, error) { return pubKey.Key, nil } -// UnmarshalAmino overrides Amino binary marshalling. +// UnmarshalAmino overrides Amino binary marshaling. func (pubKey *PubKey) UnmarshalAmino(bz []byte) error { if len(bz) != PubKeySize { return errorsmod.Wrap(errors.ErrInvalidPubKey, "invalid pubkey size") @@ -194,14 +194,14 @@ func (pubKey *PubKey) UnmarshalAmino(bz []byte) error { return nil } -// MarshalAminoJSON overrides Amino JSON marshalling. +// MarshalAminoJSON overrides Amino JSON marshaling. func (pubKey PubKey) MarshalAminoJSON() ([]byte, error) { // When we marshal to Amino JSON, we don't marshal the "key" field itself, // just its contents (i.e. the key bytes). return pubKey.MarshalAmino() } -// UnmarshalAminoJSON overrides Amino JSON marshalling. +// UnmarshalAminoJSON overrides Amino JSON marshaling. func (pubKey *PubKey) UnmarshalAminoJSON(bz []byte) error { return pubKey.UnmarshalAmino(bz) } diff --git a/crypto/keys/secp256k1/secp256k1_cgo.go b/crypto/keys/secp256k1/secp256k1_cgo.go index 60d7a04c19e8..093a4de8eccd 100644 --- a/crypto/keys/secp256k1/secp256k1_cgo.go +++ b/crypto/keys/secp256k1/secp256k1_cgo.go @@ -22,6 +22,6 @@ func (privKey *PrivKey) Sign(msg []byte) ([]byte, error) { // VerifySignature validates the signature. // The msg will be hashed prior to signature verification. -func (pubKey *PubKey) VerifySignature(msg []byte, sigStr []byte) bool { +func (pubKey *PubKey) VerifySignature(msg, sigStr []byte) bool { return secp256k1.VerifySignature(pubKey.Bytes(), crypto.Sha256(msg), sigStr) } diff --git a/crypto/keys/secp256k1/secp256k1_internal_test.go b/crypto/keys/secp256k1/secp256k1_internal_test.go index 56bef18f6bb4..539420d00ee7 100644 --- a/crypto/keys/secp256k1/secp256k1_internal_test.go +++ b/crypto/keys/secp256k1/secp256k1_internal_test.go @@ -16,7 +16,7 @@ func Test_genPrivKey(t *testing.T) { copy(onePadded[32-len(oneB):32], oneB) t.Logf("one padded: %v, len=%v", onePadded, len(onePadded)) - validOne := append(empty, onePadded...) //nolint:gocritic // append is fine here + validOne := append(empty, onePadded...) tests := []struct { name string notSoRand []byte diff --git a/crypto/keys/secp256k1/secp256k1_nocgo.go b/crypto/keys/secp256k1/secp256k1_nocgo.go index 4d7c21280df2..db66325f0bf4 100644 --- a/crypto/keys/secp256k1/secp256k1_nocgo.go +++ b/crypto/keys/secp256k1/secp256k1_nocgo.go @@ -24,7 +24,7 @@ func (privKey *PrivKey) Sign(msg []byte) ([]byte, error) { // VerifyBytes verifies a signature of the form R || S. // It rejects signatures which are not in lower-S form. -func (pubKey *PubKey) VerifySignature(msg []byte, sigStr []byte) bool { +func (pubKey *PubKey) VerifySignature(msg, sigStr []byte) bool { if len(sigStr) != 64 { return false } diff --git a/crypto/keys/secp256r1/privkey_internal_test.go b/crypto/keys/secp256r1/privkey_internal_test.go index 771582d6a413..902ee6dafbf8 100644 --- a/crypto/keys/secp256r1/privkey_internal_test.go +++ b/crypto/keys/secp256r1/privkey_internal_test.go @@ -51,7 +51,7 @@ func (suite *SKSuite) TestBytes() { func (suite *SKSuite) TestMarshalProto() { require := suite.Require() - /**** test structure marshalling ****/ + /**** test structure marshaling ****/ var sk PrivKey bz, err := proto.Marshal(suite.sk) @@ -59,7 +59,7 @@ func (suite *SKSuite) TestMarshalProto() { require.NoError(proto.Unmarshal(bz, &sk)) require.True(sk.Equals(suite.sk)) - /**** test structure marshalling with codec ****/ + /**** test structure marshaling with codec ****/ sk = PrivKey{} registry := types.NewInterfaceRegistry() diff --git a/crypto/keys/secp256r1/pubkey.go b/crypto/keys/secp256r1/pubkey.go index 3b02e8b2e7be..cacec514c3d7 100644 --- a/crypto/keys/secp256r1/pubkey.go +++ b/crypto/keys/secp256r1/pubkey.go @@ -41,7 +41,7 @@ func (m *PubKey) Type() string { } // VerifySignature implements SDK PubKey interface. -func (m *PubKey) VerifySignature(msg []byte, sig []byte) bool { +func (m *PubKey) VerifySignature(msg, sig []byte) bool { return m.Key.VerifySignature(msg, sig) } diff --git a/crypto/keys/secp256r1/pubkey_internal_test.go b/crypto/keys/secp256r1/pubkey_internal_test.go index 2015b32cb307..d3d2ed3823eb 100644 --- a/crypto/keys/secp256r1/pubkey_internal_test.go +++ b/crypto/keys/secp256r1/pubkey_internal_test.go @@ -68,7 +68,7 @@ func (suite *PKSuite) TestEquals() { func (suite *PKSuite) TestMarshalProto() { require := suite.Require() - /**** test structure marshalling ****/ + /**** test structure marshaling ****/ var pk PubKey bz, err := proto.Marshal(suite.pk) @@ -76,7 +76,7 @@ func (suite *PKSuite) TestMarshalProto() { require.NoError(proto.Unmarshal(bz, &pk)) require.True(pk.Equals(suite.pk)) - /**** test structure marshalling with codec ****/ + /**** test structure marshaling with codec ****/ pk = PubKey{} emptyRegistry := types.NewInterfaceRegistry() @@ -104,7 +104,7 @@ func (suite *PKSuite) TestMarshalProto() { require.Len(bz2, bufSize) require.Equal(bz, bz2[(bufSize-pk.Size()):]) - /**** test interface marshalling ****/ + /**** test interface marshaling ****/ bz, err = pubkeyCodec.MarshalInterface(suite.pk) require.NoError(err) var pkI cryptotypes.PubKey diff --git a/crypto/ledger/encode_test.go b/crypto/ledger/encode_test.go index 2cc496198532..b5b06d04f37c 100644 --- a/crypto/ledger/encode_test.go +++ b/crypto/ledger/encode_test.go @@ -9,7 +9,7 @@ import ( cryptotypes "github.com/cosmos/cosmos-sdk/crypto/types" ) -func checkAminoJSON(t *testing.T, src interface{}, dst interface{}, isNil bool) { +func checkAminoJSON(t *testing.T, src, dst interface{}, isNil bool) { // Marshal to JSON bytes. js, err := cdc.MarshalJSON(src) require.Nil(t, err, "%+v", err) @@ -24,7 +24,7 @@ func checkAminoJSON(t *testing.T, src interface{}, dst interface{}, isNil bool) require.Nil(t, err, "%+v", err) } -func ExamplePrintRegisteredTypes() { //nolint:govet +func ExamplePrintRegisteredTypes() { //nolint:govet // ignore for examples _ = cdc.PrintTypes(os.Stdout) // | Type | Name | Prefix | Length | Notes | // | ---- | ---- | ------ | ----- | ------ | diff --git a/crypto/types/types.go b/crypto/types/types.go index 17d7acc94fd5..12fc6e39541f 100644 --- a/crypto/types/types.go +++ b/crypto/types/types.go @@ -11,7 +11,7 @@ type PubKey interface { Address() Address Bytes() []byte - VerifySignature(msg []byte, sig []byte) bool + VerifySignature(msg, sig []byte) bool Equals(PubKey) bool Type() string } diff --git a/crypto/xsalsa20symmetric/symmetric.go b/crypto/xsalsa20symmetric/symmetric.go index 0a2814e81737..e2ead2e2f58f 100644 --- a/crypto/xsalsa20symmetric/symmetric.go +++ b/crypto/xsalsa20symmetric/symmetric.go @@ -19,7 +19,7 @@ var ErrCiphertextDecrypt = errors.New("ciphertext decryption failed") // secret must be 32 bytes long. Use something like Sha256(Bcrypt(passphrase)) // The ciphertext is (secretbox.Overhead + 24) bytes longer than the plaintext. -func EncryptSymmetric(plaintext []byte, secret []byte) (ciphertext []byte) { +func EncryptSymmetric(plaintext, secret []byte) (ciphertext []byte) { if len(secret) != secretLen { panic(fmt.Sprintf("Secret must be 32 bytes long, got len %v", len(secret))) } @@ -36,7 +36,7 @@ func EncryptSymmetric(plaintext []byte, secret []byte) (ciphertext []byte) { // secret must be 32 bytes long. Use something like Sha256(Bcrypt(passphrase)) // The ciphertext is (secretbox.Overhead + 24) bytes longer than the plaintext. -func DecryptSymmetric(ciphertext []byte, secret []byte) (plaintext []byte, err error) { +func DecryptSymmetric(ciphertext, secret []byte) (plaintext []byte, err error) { if len(secret) != secretLen { panic(fmt.Sprintf("Secret must be 32 bytes long, got len %v", len(secret))) } diff --git a/depinject/README.md b/depinject/README.md index 17eb628726bb..258e1e0b6347 100644 --- a/depinject/README.md +++ b/depinject/README.md @@ -8,15 +8,31 @@ sidebar_position: 1 ## Overview -`depinject` is a dependency injection framework for the Cosmos SDK. This module together with `core/appconfig` are meant to simplify the definition of a blockchain by replacing most of `app.go`'s boilerplate code with a configuration file (Go, YAML or JSON). +`depinject` is a dependency injection (DI) framework for the Cosmos SDK, designed to streamline the process of building and configuring blockchain applications. It works in conjunction with the `core/appconfig` module to replace the majority of boilerplate code in `app.go` with a configuration file in Go, YAML, or JSON format. + +`depinject` is particularly useful for developing blockchain applications: + +* With multiple interdependent components, modules, or services. Helping manage their dependencies effectively. +* That require decoupling of these components, making it easier to test, modify, or replace individual parts without affecting the entire system. +* That are wanting to simplify the setup and initialisation of modules and their dependencies by reducing boilerplate code and automating dependency management. + +By using `depinject`, developers can achieve: + +* Cleaner and more organised code. +* Improved modularity and maintainability. +* A more maintainable and modular structure for their blockchain applications, ultimately enhancing development velocity and code quality. * [Go Doc](https://pkg.go.dev/cosmossdk.io/depinject) ## Usage -`depinject` includes an expressive and composable [Configuration API](https://pkg.go.dev/github.com/cosmos/cosmos-sdk/depinject#Config). -A core configuration function is `Provide`. The example below demonstrates the registration of free **provider functions** via the `Provide` API. +The `depinject` framework, based on dependency injection concepts, streamlines the management of dependencies within your blockchain application using its Configuration API. This API offers a set of functions and methods to create easy to use configurations, making it simple to define, modify, and access dependencies and their relationships. +A core component of the [Configuration API](https://pkg.go.dev/github.com/cosmos/cosmos-sdk/depinject#Config) is the `Provide` function, which allows you to register provider functions that supply dependencies. Inspired by constructor injection, these provider functions form the basis of the dependency tree, enabling the management and resolution of dependencies in a structured and maintainable manner. Additionally, `depinject` supports interface types as inputs to provider functions, offering flexibility and decoupling between components, similar to interface injection concepts. + +By leveraging `depinject` and its Configuration API, you can efficiently handle dependencies in your blockchain application, ensuring a clean, modular, and well-organised codebase. + +Example: ```go package main @@ -48,16 +64,17 @@ func main() { } ``` -Provider functions form the basis of the dependency tree, they are introspected then their inputs identified as dependencies and outputs as dependants, either for another provider function or state stored outside the DI container, as is the case of `&x` and `&y` above. +In this example, `depinject.Provide` registers two provider functions that return `int` and `AnotherInt` values. The `depinject.Inject` function is then used to inject these values into the variables `x` and `y`. + +Provider functions serve as the basis for the dependency tree. They are analysed to identify their inputs as dependencies and their outputs as dependents. These dependents can either be used by another provider function or be stored outside the DI container (e.g., `&x` and `&y` in the example above). ### Interface type resolution -`depinject` supports interface types as inputs to provider functions. In the SDK's case this pattern is used to decouple -`Keeper` dependencies between modules. For example `x/bank` expects an [AccountKeeper](https://pkg.go.dev/github.com/cosmos/cosmos-sdk/x/bank/types#AccountKeeper) interface as [input to ProvideModule](https://github.com/cosmos/cosmos-sdk/blob/v0.47.0-rc1/x/bank/module.go#L208-L260). +`depinject` supports the use of interface types as inputs to provider functions, which helps decouple dependencies between modules. This approach is particularly useful for managing complex systems with multiple modules, such as the Cosmos SDK, where dependencies need to be flexible and maintainable. -Concretely `SimApp` uses the implementation in `x/auth`, but this design allows for this loose coupling to change. +For example, `x/bank` expects an [AccountKeeper](https://pkg.go.dev/github.com/cosmos/cosmos-sdk/x/bank/types#AccountKeeper) interface as [input to ProvideModule](https://github.com/cosmos/cosmos-sdk/blob/v0.47.0-rc1/x/bank/module.go#L208-L260). `SimApp` uses the implementation in `x/auth`, but the modular design allows for easy changes to the implementation if needed. -Given the following types: +Consider the following example: ```go package duck @@ -81,7 +98,7 @@ type Pond struct { } ``` -This usage +In this example, there's a `Pond` struct that has a `Duck` field of type `AlsoDuck`. The `depinject` framework can automatically resolve the appropriate implementation when there's only one available, as shown below: ```go var pond Pond @@ -95,8 +112,9 @@ depinject.Inject( &pond) ``` -results in an *implicit* binding of `Duck` to `Mallard`. This works because there is only one implementation of `Duck` in the container. -However, adding a second provider of `Duck` will result in an error: +This code snippet results in the `Duck` field of `Pond` being implicitly bound to the `Mallard` implementation because it's the only implementation of the `Duck` interface in the container. + +However, if there are multiple implementations of the `Duck` interface, as in the following example, you'll encounter an error: ```go var pond Pond @@ -115,7 +133,7 @@ A specific binding preference for `Duck` is required. #### `BindInterface` API -In the above situation registering a binding for a given interface binding may look like +In the above situation registering a binding for a given interface binding may look like: ```go depinject.Inject( diff --git a/depinject/binding_test.go b/depinject/binding_test.go index 5cfacc628b3c..0aee332d9775 100644 --- a/depinject/binding_test.go +++ b/depinject/binding_test.go @@ -131,11 +131,11 @@ func fullTypeName(typeName string) string { return fmt.Sprintf("cosmossdk.io/depinject_test/depinject_test.%s", typeName) } -func (s *bindingSuite) ThereIsAGlobalBindingForA(preferredType string, interfaceType string) { +func (s *bindingSuite) ThereIsAGlobalBindingForA(preferredType, interfaceType string) { s.addConfig(depinject.BindInterface(fullTypeName(interfaceType), fullTypeName(preferredType))) } -func (s *bindingSuite) ThereIsABindingForAInModule(preferredType string, interfaceType string, moduleName string) { +func (s *bindingSuite) ThereIsABindingForAInModule(preferredType, interfaceType, moduleName string) { s.addConfig(depinject.BindInterfaceInModule(moduleName, fullTypeName(interfaceType), fullTypeName(preferredType))) } @@ -147,7 +147,7 @@ func (s *bindingSuite) ModuleWantsADuck(module string) { s.addConfig(depinject.ProvideInModule(module, ProvideModuleDuck)) } -func (s *bindingSuite) ModuleResolvesA(module string, duckType string) { +func (s *bindingSuite) ModuleResolvesA(module, duckType string) { pond := s.resolvePond() moduleFound := false for _, dw := range pond.Ducks { diff --git a/depinject/config.go b/depinject/config.go index 984f068f58c9..947539c4b34f 100644 --- a/depinject/config.go +++ b/depinject/config.go @@ -109,7 +109,7 @@ func invoke(ctr *container, key *moduleKey, invokers []interface{}) error { // // "cosmossdk.io/depinject_test/depinject_test.Duck", // "cosmossdk.io/depinject_test/depinject_test.Canvasback") -func BindInterface(inTypeName string, outTypeName string) Config { +func BindInterface(inTypeName, outTypeName string) Config { return containerConfig(func(ctr *container) error { return bindInterface(ctr, inTypeName, outTypeName, "") }) @@ -125,13 +125,13 @@ func BindInterface(inTypeName string, outTypeName string) Config { // "moduleFoo", // "cosmossdk.io/depinject_test/depinject_test.Duck", // "cosmossdk.io/depinject_test/depinject_test.Canvasback") -func BindInterfaceInModule(moduleName string, inTypeName string, outTypeName string) Config { +func BindInterfaceInModule(moduleName, inTypeName, outTypeName string) Config { return containerConfig(func(ctr *container) error { return bindInterface(ctr, inTypeName, outTypeName, moduleName) }) } -func bindInterface(ctr *container, inTypeName string, outTypeName string, moduleName string) error { +func bindInterface(ctr *container, inTypeName, outTypeName, moduleName string) error { var mk *moduleKey if moduleName != "" { mk = &moduleKey{name: moduleName} diff --git a/depinject/container.go b/depinject/container.go index 8b39183eda42..1ca20cc81cfa 100644 --- a/depinject/container.go +++ b/depinject/container.go @@ -295,47 +295,47 @@ func (c *container) addNode(provider *providerDescriptor, key *moduleKey) (inter } return sp, nil - } else { - if hasOwnModuleKeyParam { - return nil, errors.Errorf("%T and %T must not be declared as dependencies on the same provided", - ModuleKey{}, OwnModuleKey{}) - } - - c.logf("Registering module-scoped provider: %s", provider.Location.String()) - c.indentLogger() - defer c.dedentLogger() + } - node := &moduleDepProvider{ - provider: provider, - calledForModule: map[*moduleKey]bool{}, - valueMap: map[*moduleKey][]reflect.Value{}, - } + if hasOwnModuleKeyParam { + return nil, errors.Errorf("%T and %T must not be declared as dependencies on the same provided", + ModuleKey{}, OwnModuleKey{}) + } - for i, out := range provider.Outputs { - typ := out.Type + c.logf("Registering module-scoped provider: %s", provider.Location.String()) + c.indentLogger() + defer c.dedentLogger() - c.logf("Registering resolver for module-scoped type %v", typ) + node := &moduleDepProvider{ + provider: provider, + calledForModule: map[*moduleKey]bool{}, + valueMap: map[*moduleKey][]reflect.Value{}, + } - existing, ok := c.resolverByType(typ) - if ok { - return nil, errors.Errorf("duplicate provision of type %v by module-scoped provider %s\n\talready provided by %s", - typ, provider.Location, existing.describeLocation()) - } + for i, out := range provider.Outputs { + typ := out.Type - typeGraphNode := c.typeGraphNode(typ) - c.addResolver(typ, &moduleDepResolver{ - typ: typ, - idxInValues: i, - node: node, - valueMap: map[*moduleKey]reflect.Value{}, - graphNode: typeGraphNode, - }) + c.logf("Registering resolver for module-scoped type %v", typ) - c.addGraphEdge(providerGraphNode, typeGraphNode) + existing, ok := c.resolverByType(typ) + if ok { + return nil, errors.Errorf("duplicate provision of type %v by module-scoped provider %s\n\talready provided by %s", + typ, provider.Location, existing.describeLocation()) } - return node, nil + typeGraphNode := c.typeGraphNode(typ) + c.addResolver(typ, &moduleDepResolver{ + typ: typ, + idxInValues: i, + node: node, + valueMap: map[*moduleKey]reflect.Value{}, + graphNode: typeGraphNode, + }) + + c.addGraphEdge(providerGraphNode, typeGraphNode) } + + return node, nil } func (c *container) supply(value reflect.Value, location Location) error { diff --git a/depinject/debug.go b/depinject/debug.go index 6fb6d65bd059..957632384458 100644 --- a/depinject/debug.go +++ b/depinject/debug.go @@ -118,11 +118,11 @@ func Debug() DebugOption { ) } -func (d *debugConfig) initLogBuf() { - if d.logBuf == nil { - d.logBuf = &[]string{} - d.loggers = append(d.loggers, func(s string) { - *d.logBuf = append(*d.logBuf, s) +func (c *debugConfig) initLogBuf() { + if c.logBuf == nil { + c.logBuf = &[]string{} + c.loggers = append(c.loggers, func(s string) { + *c.logBuf = append(*c.logBuf, s) }) } } @@ -221,7 +221,7 @@ func newDebugConfig() (*debugConfig, error) { } func (c *debugConfig) indentLogger() { - c.indentStr = c.indentStr + " " + c.indentStr += " " } func (c *debugConfig) dedentLogger() { @@ -261,7 +261,7 @@ func (c *debugConfig) enableLogVisualizer() { func (c *debugConfig) addFileVisualizer(filename string) { c.visualizers = append(c.visualizers, func(_ string) { dotStr := c.graph.String() - err := os.WriteFile(filename, []byte(dotStr), 0o644) + err := os.WriteFile(filename, []byte(dotStr), 0o600) if err != nil { c.logf("Error saving graphviz file %s: %+v", filename, err) } else { @@ -323,17 +323,17 @@ func (c *debugConfig) moduleSubGraph(key *moduleKey) *graphviz.Graph { if key == nil { // return the root graph return c.graph - } else { - gname := fmt.Sprintf("cluster_%s", key.name) - graph, found := c.graph.FindOrCreateSubGraph(gname) - if !found { - graph.SetLabel(fmt.Sprintf("Module: %s", key.name)) - graph.SetPenWidth("0.5") - graph.SetFontSize("12.0") - graph.SetStyle("rounded") - } - return graph } + + gname := fmt.Sprintf("cluster_%s", key.name) + graph, found := c.graph.FindOrCreateSubGraph(gname) + if !found { + graph.SetLabel(fmt.Sprintf("Module: %s", key.name)) + graph.SetPenWidth("0.5") + graph.SetFontSize("12.0") + graph.SetStyle("rounded") + } + return graph } func (c *debugConfig) addGraphEdge(from, to *graphviz.Node) { diff --git a/depinject/errors.go b/depinject/errors.go index 737fc7daf60f..ebef77d47e38 100644 --- a/depinject/errors.go +++ b/depinject/errors.go @@ -11,7 +11,6 @@ import ( // Interface to a concrete type, but the container was unable to come to a resolution because multiple Matches // were found. type ErrMultipleImplicitInterfaceBindings struct { - error Interface reflect.Type Matches []reflect.Type } @@ -38,7 +37,6 @@ type ErrNoTypeForExplicitBindingFound struct { Implementation string Interface string ModuleName string - error } func newErrNoTypeForExplicitBindingFound(p interfaceBinding) ErrNoTypeForExplicitBindingFound { @@ -58,10 +56,10 @@ func (err ErrNoTypeForExplicitBindingFound) Error() string { if err.ModuleName != "" { return fmt.Sprintf("No type for explicit binding found. Given the explicit interface binding %s in module %s, a provider of type %s was not found.", err.Interface, err.ModuleName, err.Implementation) - } else { - return fmt.Sprintf("No type for explicit binding found. Given the explicit interface binding %s, a provider of type %s was not found.", - err.Interface, err.Implementation) } + + return fmt.Sprintf("No type for explicit binding found. Given the explicit interface binding %s, a provider of type %s was not found.", + err.Interface, err.Implementation) } func duplicateDefinitionError(typ reflect.Type, duplicateLoc Location, existingLoc string) error { diff --git a/depinject/internal/codegen/type.go b/depinject/internal/codegen/type.go index 9234206bfb88..e5a3a5cefddb 100644 --- a/depinject/internal/codegen/type.go +++ b/depinject/internal/codegen/type.go @@ -119,7 +119,7 @@ func (g *FileGen) TypeExpr(typ reflect.Type) (ast.Expr, error) { var genericTypeNameRegex = regexp.MustCompile(`(\w+)\[(.*)]`) -func (g *FileGen) importGenericTypeParams(typeName string, pkgPath string) (newTypeName string) { +func (g *FileGen) importGenericTypeParams(typeName, pkgPath string) (newTypeName string) { // a generic type parameter from the same package the generic type is defined won't have the // full package name so we need to compare it with the final package part (the default import prefix) // ex: for a/b.C in package a/b, we'll just see the type param b.C. diff --git a/depinject/internal/codegen/value.go b/depinject/internal/codegen/value.go index 27738adc5433..6174f1dca18b 100644 --- a/depinject/internal/codegen/value.go +++ b/depinject/internal/codegen/value.go @@ -111,16 +111,16 @@ func (g *FileGen) ValueExpr(value reflect.Value) (ast.Expr, error) { return ast.NewIdent("nil"), nil } - if typ.Elem().Kind() == reflect.Struct { - v, err := g.ValueExpr(value.Elem()) - if err != nil { - return nil, err - } - - return &ast.UnaryExpr{Op: token.AND, X: v}, nil - } else { + if typ.Elem().Kind() != reflect.Struct { return nil, fmt.Errorf("invalid type %s", typ) } + + v, err := g.ValueExpr(value.Elem()) + if err != nil { + return nil, err + } + + return &ast.UnaryExpr{Op: token.AND, X: v}, nil case reflect.Invalid, reflect.Uintptr, reflect.Chan, reflect.Func, reflect.Interface, reflect.UnsafePointer: return nil, fmt.Errorf("invalid type %s", typ) diff --git a/depinject/location.go b/depinject/location.go index 1a275073a4ac..7b18d5e1b16a 100644 --- a/depinject/location.go +++ b/depinject/location.go @@ -88,7 +88,7 @@ func (f *location) Format(w fmt.State, c rune) { const _vendor = "/vendor/" -func splitFuncName(function string) (pname string, fname string) { +func splitFuncName(function string) (pname, fname string) { if len(function) == 0 { return } @@ -121,5 +121,5 @@ func splitFuncName(function string) (pname string, fname string) { pname = unescaped } - return + return pname, fname } diff --git a/depinject/provider_desc_test.go b/depinject/provider_desc_test.go index b7d6d349377b..a620620d7800 100644 --- a/depinject/provider_desc_test.go +++ b/depinject/provider_desc_test.go @@ -29,7 +29,7 @@ type StructOut struct { func privateProvider(int, float64) (string, []byte) { return "", nil } -func PrivateInAndOut(containerConfig) *container { return nil } +func PrivateInAndOut(containerConfig) *container { return nil } //revive:disable:unexported-return func InternalInAndOut(graphviz.Attributes) *codegen.FileGen { return nil } @@ -45,7 +45,7 @@ func StructInAndOut(_ float32, _ StructIn, _ byte) (int16, StructOut, int32, err return int16(0), StructOut{}, int32(0), nil } -func BadErrorPosition() (error, int) { return nil, 0 } +func BadErrorPosition() (error, int) { return nil, 0 } //nolint:revive,stylecheck // Deliberately has error as first of multiple arguments. func BadOptionalFn(_ BadOptional) int { return 0 } diff --git a/docs/.gitignore b/docs/.gitignore index fc7eb7e9ba84..baff39bd9e55 100644 --- a/docs/.gitignore +++ b/docs/.gitignore @@ -15,10 +15,13 @@ docs/docs/spec docs/docs/architecture docs/docs/rfc docs/docs/tooling/01-cosmovisor.md -docs/docs/tooling/02-depinject.md -docs/docs/tooling/03-confix.md -docs/docs/tooling/04-hubl.md +docs/docs/tooling/02-confix.md +docs/docs/tooling/03-hubl.md +docs/docs/packages/01-depinject.md +docs/docs/packages/02-collections.md +docs/docs/packages/03-orm.md docs/run-node/04-rosetta.md +docs/migrations/02-upgrading.md # Misc .DS_Store diff --git a/docs/architecture/_category_.json b/docs/architecture/_category_.json index d138de900cb3..87ceb9374844 100644 --- a/docs/architecture/_category_.json +++ b/docs/architecture/_category_.json @@ -1,5 +1,5 @@ { "label": "ADRs", - "position": 10, + "position": 11, "link": null -} +} \ No newline at end of file diff --git a/docs/architecture/adr-050-sign-mode-textual-annex1.md b/docs/architecture/adr-050-sign-mode-textual-annex1.md index 48a03e806487..ff3acc8c597d 100644 --- a/docs/architecture/adr-050-sign-mode-textual-annex1.md +++ b/docs/architecture/adr-050-sign-mode-textual-annex1.md @@ -6,6 +6,7 @@ * Feb 07, 2022: Draft read and concept-ACKed by the Ledger team. * Dec 01, 2022: Remove `Object: ` prefix on Any header screen. * Dec 13, 2022: Sign over bytes hash when bytes length > 32. +* Mar 27, 2023: Update `Any` value renderer to omit message header screen. ## Status @@ -111,13 +112,12 @@ End of Allowed messages ### `message` -* Applies to Protobuf messages whose name does not start with `Msg` - * For `sdk.Msg`s, please see [ADR-050](./adr-050-sign-mode-textual.md) - * alternatively, we can decide to add a protobuf option to denote messages that are `sdk.Msg`s. +* Applies to all Protobuf messages that do not have a custom encoding. * Field names follow [sentence case](https://en.wiktionary.org/wiki/sentence_case) - * replace `_` with a spaces - * capitalize first letter of the setence + * replace each `_` with a space + * capitalize first letter of the sentence * Field names are ordered by their Protobuf field number +* Screen title is the field name, and screen content is the value. * Nesting: * if a field contains a nested message, we value-render the underlying message using the template: @@ -188,21 +188,31 @@ See example above with `message Vote{}`. > ``` +There is however one exception: when the underlying message is a Protobuf message that does not have a custom encoding, then the message header screen is omitted, and one level of indentation is removed. + +Messages that have a custom encoding, including `google.protobuf.Timestamp`, `google.protobuf.Duration`, `google.protobuf.Any`, `cosmos.base.v1beta1.Coin`, and messages that have an app-defined custom encoding, will preserve their header and indentation level. + #### Examples +Message header screen is stripped, one-level of indentation removed: +``` +/cosmos.gov.v1.Vote +> Proposal id: 4 +> Vote: cosmos1abc...def +> Options: 2 WeightedVoteOptions +> Options (1/2): WeightedVoteOption object +>> Option: Yes +>> Weight: 0.7 +> Options (2/2): WeightedVoteOption object +>> Option: No +>> Weight: 0.3 +> End of Options +``` + +Message with custom encoding: ``` -type.googleapis.com/cosmos.gov.v1.Vote -> Vote object ->> Proposal id: 4 ->> Vote: cosmos1abc...def ->> Options: 2 WeightedVoteOptions ->> Options (1/2): WeightedVoteOption object ->>> Option: Yes ->>> Weight: 0.7 ->> Options (2/2): WeightedVoteOption object ->>> Option: No ->>> Weight: 0.3 ->> End of Options +/cosmos.base.v1beta1.Coin +> 10uatom ``` ### `google.protobuf.Timestamp` @@ -310,6 +320,10 @@ TestData object > Signer: cosmos1abc ``` +### bool + +Boolean values are rendered as `True` or `False`. + ### [ABANDONED] Custom `msg_title` instead of Msg `type_url` _This paragraph is in the Annex for informational purposes only, and will be removed in a next update of the ADR._ diff --git a/docs/architecture/adr-059-test-scopes.md b/docs/architecture/adr-059-test-scopes.md index 6180df5928c0..060344593e95 100644 --- a/docs/architecture/adr-059-test-scopes.md +++ b/docs/architecture/adr-059-test-scopes.md @@ -3,6 +3,8 @@ ## Changelog * 2022-08-02: Initial Draft +* 2023-03-02: Add precision for integration tests +* 2023-03-23: Add precision for E2E tests ## Status @@ -55,13 +57,11 @@ These are almost like integration tests in that they exercise many things togeth use mocks. Example 1 journey vs illustrative tests - [depinject's BDD style tests](https://github.com/cosmos/cosmos-sdk/blob/main/depinject/features/bindings.feature), show how we can -rapidly build up many illustrative cases demonstrating behavioral rules without [very much -code](https://github.com/cosmos/cosmos-sdk/blob/main/depinject/binding_test.go) while maintaining high level readability. +rapidly build up many illustrative cases demonstrating behavioral rules without [very much code](https://github.com/cosmos/cosmos-sdk/blob/main/depinject/binding_test.go) while maintaining high level readability. Example 2 [depinject table driven tests](https://github.com/cosmos/cosmos-sdk/blob/main/depinject/provider_desc_test.go) -Example 3 [Bank keeper tests](https://github.com/cosmos/cosmos-sdk/blob/2bec9d2021918650d3938c3ab242f84289daef80/x/bank/keeper/keeper_test.go#L94-L105) - A mock implementation of `AccountKeeper` is -supplied to the keeper constructor. +Example 3 [Bank keeper tests](https://github.com/cosmos/cosmos-sdk/blob/2bec9d2021918650d3938c3ab242f84289daef80/x/bank/keeper/keeper_test.go#L94-L105) - A mock implementation of `AccountKeeper` is supplied to the keeper constructor. #### Limitations @@ -147,6 +147,9 @@ End to end tests exercise the entire system as we understand it in as close an a to a production environment as is practical. Presently these tests are located at [tests/e2e](https://github.com/cosmos/cosmos-sdk/tree/main/tests/e2e) and rely on [testutil/network](https://github.com/cosmos/cosmos-sdk/tree/main/testutil/network) to start up an in-process Tendermint node. +An application should be built as minimally as possible to exercise the desired functionality. +The SDK uses an application will only the required modules for the tests. The application developer is adviced to use its own application for e2e tests. + #### Limitations In general the limitations of end to end tests are orchestration and compute cost. @@ -162,12 +165,14 @@ The scope of e2e tests has been complected with command line interface testing. We accept these test scopes and identify the following decisions points for each. -| Scope | App Fixture | Mocks? | -| ----------- | ----------- | ------ | -| Unit | None | Yes | -| Integration | depinject | Some | -| Simulation | depinject | No | -| E2E | simapp | No | +| Scope | App Type | Mocks? | +| ----------- | ------------------- | ------ | +| Unit | None | Yes | +| Integration | integration helpers | Some | +| Simulation | minimal app | No | +| E2E | minimal app | No | + +The decision above is valid for the SDK. An application developer should test their application with their full application instead of the minimal app. ### Unit Tests @@ -175,8 +180,6 @@ All modules must have mocked unit test coverage. Illustrative tests should outnumber journeys in unit tests. -~BDD feature tests are recommended when building up illustrative and journey scenarios.~ - Unit tests should outnumber integration tests. Unit tests must not introduce additional dependencies beyond those already present in @@ -200,7 +203,7 @@ Integration tests should outnumber e2e tests. ### Simulations -Simulations shall use `depinject`. They are located under `/x/{moduleName}/simulation`. +Simulations shall use a minimal application (usually via app wiring). They are located under `/x/{moduleName}/simulation`. ### E2E Tests @@ -233,7 +236,6 @@ demonstrated in [PR#12706](https://github.com/cosmos/cosmos-sdk/pull/12706). ### Neutral -* learning curve for BDD style tests * some discovery required for e2e transition to dockertest ## Further Discussions diff --git a/docs/architecture/adr-063-core-module-api.md b/docs/architecture/adr-063-core-module-api.md index a977688ec71d..b10aca759835 100644 --- a/docs/architecture/adr-063-core-module-api.md +++ b/docs/architecture/adr-063-core-module-api.md @@ -14,33 +14,36 @@ ACCEPTED Partially Implemented A new core API is proposed as a way to develop cosmos-sdk applications that will eventually replace the existing `AppModule` and `sdk.Context` frameworks a set of core services and extension interfaces. This core API aims to: -- be simpler, -- more extensible, -- more stable than the current framework, -- enable deterministic events and queries, -- support event listeners and -- [ADR 033: Protobuf-based Inter-Module Communication](./adr-033-protobuf-inter-module-comm.md) clients. + +* be simpler +* more extensible +* more stable than the current framework +* enable deterministic events and queries, +* support event listeners +* [ADR 033: Protobuf-based Inter-Module Communication](./adr-033-protobuf-inter-module-comm.md) clients. ## Context Historically modules have exposed their functionality to the framework via the `AppModule` and `AppModuleBasic` interfaces which have the following shortcomings: + * both `AppModule` and `AppModuleBasic` need to be defined and registered which is counter-intuitive * apps need to implement the full interfaces, even parts they don't need (although there are workarounds for this), -* interface methods depend heavily on unstable third party dependencies, in particular Tendermint, +* interface methods depend heavily on unstable third party dependencies, in particular Comet, * legacy required methods have littered these interfaces for far too long In order to interact with the state machine, modules have needed to do a combination of these things: + * get store keys from the app * call methods on `sdk.Context` which contains more or less the full set of capability available to modules. By isolating all the state machine functionality into `sdk.Context`, the set of functionalities available to -modules are tightly coupled to this type. If there are changes to upstream dependencies (such as Tendermint) +modules are tightly coupled to this type. If there are changes to upstream dependencies (such as Comet) or new functionalities are desired (such as alternate store types), the changes need impact `sdk.Context` and all consumers of it (basically all modules). Also, all modules now receive `context.Context` and need to convert these to `sdk.Context`'s with a non-ergonomic unwrapping function. -Any breaking changes to these interfaces, such as ones imposed by third-party dependencies like Tendermint, have the +Any breaking changes to these interfaces, such as ones imposed by third-party dependencies like Comet, have the side effect of forcing all modules in the ecosystem to update in lock-step. This means it is almost impossible to have a version of the module which can be run with 2 or 3 different versions of the SDK or 2 or 3 different versions of another module. This lock-step coupling slows down overall development within the ecosystem and causes updates to @@ -50,11 +53,13 @@ components to be delayed longer than they would if things were more stable and l The `core` API proposes a set of core APIs that modules can rely on to interact with the state machine and expose their functionalities to it that are designed in a principled way such that: + * tight coupling of dependencies and unrelated functionalities is minimized or eliminated * APIs can have long-term stability guarantees * the SDK framework is extensible in a safe and straightforward way The design principles of the core API are as follows: + * everything that a module wants to interact with in the state machine is a service * all services coordinate state via `context.Context` and don't try to recreate the "bag of variables" approach of `sdk.Context` * all independent services are isolated in independent packages with minimal APIs and minimal dependencies @@ -63,7 +68,7 @@ The design principles of the core API are as follows: functionalities exposed by core extension interfaces * other non-core and/or non-LTS services can be exposed by specific versions of runtime modules or other modules following the same design principles, this includes functionality that interacts with specific non-stable versions of -third party dependencies such as Tendermint +third party dependencies such as Comet * the core API doesn't implement *any* functionality, it just defines types * go stable API compatibility guidelines are followed: https://go.dev/blog/module-compatibility @@ -74,7 +79,7 @@ SDK's current tightly coupled `BaseApp` design while still allowing for a high d compatibility. Modules which are built only against the core API don't need to know anything about which version of runtime, -`BaseApp` or Tendermint in order to be compatible. Modules from the core mainline SDK could be easily composed +`BaseApp` or Comet in order to be compatible. Modules from the core mainline SDK could be easily composed with a forked version of runtime with this pattern. This design is intended to enable matrices of compatible dependency versions. Ideally a given version of any module @@ -112,6 +117,7 @@ type TransientStoreService interface { ``` Modules can use these services like this: + ```go func (k msgServer) Send(ctx context.Context, msg *types.MsgSend) (*types.MsgSendResponse, error) { store := k.kvStoreSvc.OpenKVStore(ctx) @@ -166,6 +172,7 @@ by other modules. If there is a client-side need to add events in patch releases Modules will provide their core services to the runtime module via extension interfaces built on top of the `cosmossdk.io/core/appmodule.AppModule` tag interface. This tag interface requires only two empty methods which allow `depinject` to identify implementors as `depinject.OnePerModule` types and as app module implementations: + ```go type AppModule interface { depinject.OnePerModuleType @@ -226,6 +233,7 @@ streaming genesis and modules using these frameworks generally do not need to wr genesis code. To support genesis, modules should implement the `HasGenesis` extension interface: + ```go type HasGenesis interface { AppModule @@ -248,6 +256,7 @@ type HasGenesis interface { Modules that have functionality that runs before transactions (begin blockers) or after transactions (end blockers) should implement the has `HasBeginBlocker` and/or `HasEndBlocker` interfaces: + ```go type HasBeginBlocker interface { AppModule @@ -261,25 +270,34 @@ type HasEndBlocker interface { ``` The `BeginBlock` and `EndBlock` methods will take a `context.Context`, because: -* most modules don't need Tendermint information other than `BlockInfo` so we can eliminate dependencies on specific -Tendermint versions -* for the few modules that need Tendermint block headers and/or return validator updates, specific versions of the -runtime module will provide specific functionality for interacting with the specific version(s) of Tendermint + +* most modules don't need Comet information other than `BlockInfo` so we can eliminate dependencies on specific +Comet versions +* for the few modules that need Comet block headers and/or return validator updates, specific versions of the +runtime module will provide specific functionality for interacting with the specific version(s) of Comet supported -In order for `BeginBlock`, `EndBlock` and `InitGenesis` to send back validator updates and retrieve full Tendermint -block headers, the runtime module for a specific version of Tendermint could provide services like this: +In order for `BeginBlock`, `EndBlock` and `InitGenesis` to send back validator updates and retrieve full Comet +block headers, the runtime module for a specific version of Comet could provide services like this: + ```go type ValidatorUpdateService interface { SetValidatorUpdates(context.Context, []abci.ValidatorUpdate) } -type BeginBlockService interface { - GetBeginBlockRequest(context.Context) abci.RequestBeginBlock +type BlockInfoService interface { + GetHeight() int64 // GetHeight returns the height of the block + Misbehavior() []abci.Misbehavior // Misbehavior returns the misbehavior of the block + GetHeaderHash() []byte // GetHeaderHash returns the hash of the block header + // GetValidatorsHash returns the hash of the validators + // For Comet, it is the hash of the next validators + GetValidatorsHash() []byte + GetProposerAddress() []byte // GetProposerAddress returns the address of the block proposer + GetDecidedLastCommit() abci.CommitInfo // GetDecidedLastCommit returns the last commit info } ``` -We know these types will change at the Tendermint level and that also a very limited set of modules actually need this +We know these types will change at the Comet level and that also a very limited set of modules actually need this functionality, so they are intentionally kept out of core to keep core limited to the necessary, minimal set of stable APIs. @@ -287,6 +305,7 @@ APIs. The current `AppModule` framework handles a number of additional concerns which aren't addressed by this core API. These include: + * gas * block headers * upgrades @@ -307,6 +326,7 @@ gRPC gateway registration should probably be handled by the runtime module, but gateway types as 1) we are already using an older version and 2) it's possible the framework can do this registration automatically in the future. So for now, the runtime module should probably provide some sort of specific type for doing this registration ex: + ```go type GrpcGatewayInfo struct { Handlers []GrpcGatewayHandler @@ -316,6 +336,7 @@ type GrpcGatewayHandler func(ctx context.Context, mux *runtime.ServeMux, client ``` which modules can return in a provider: + ```go func ProvideGrpcGateway() GrpcGatewayInfo { return GrpcGatewayinfo { @@ -373,7 +394,7 @@ allow tests to observe service behavior or provide a non-production implementati stores can be used to mock stores. For integration testing, a mock runtime implementation should be provided that allows composing different app modules -together for testing without a dependency on runtime or Tendermint. +together for testing without a dependency on runtime or Comet. ## Consequences @@ -381,7 +402,7 @@ together for testing without a dependency on runtime or Tendermint. Early versions of runtime modules should aim to support as much as possible modules built with the existing `AppModule`/`sdk.Context` framework. As the core API is more widely adopted, later runtime versions may choose to -drop support and only support the core API plus any runtime module specific APIs (like specific versions of Tendermint). +drop support and only support the core API plus any runtime module specific APIs (like specific versions of Comet). The core module itself should strive to remain at the go semantic version `v1` as long as possible and follow design principles that allow for strong long-term support (LTS). diff --git a/docs/architecture/adr-064-abci-2.0.md b/docs/architecture/adr-064-abci-2.0.md new file mode 100644 index 000000000000..9a47180509c2 --- /dev/null +++ b/docs/architecture/adr-064-abci-2.0.md @@ -0,0 +1,461 @@ +# ADR 64: ABCI 2.0 Integration (Phase II) + +## Changelog + +* 2023-01-17: Initial Draft (@alexanderbez) +* 2023-04-06: Add upgrading section (@alexanderbez) +* 2023-04-10: Simplify vote extension state persistence (@alexanderbez) + +## Status + +ACCEPTED + +## Abstract + +This ADR outlines the continuation of the efforts to implement ABCI++ in the Cosmos +SDK outlined in [ADR 060: ABCI 1.0 (Phase I)](adr-060-abci-1.0.md). + +Specifically, this ADR outlines the design and implementation of ABCI 2.0, which +includes `ExtendVote`, `VerifyVoteExtension` and `FinalizeBlock`. + +## Context + +ABCI 2.0 continues the promised updates from ABCI++, specifically three additional +ABCI methods that the application can implement in order to gain further control, +insight and customization of the consensus process, unlocking many novel use-cases +that previously not possible. We describe these three new methods below: + +### `ExtendVote` + +This method allows each validator process to extend the pre-commit phase of the +CometBFT consensus process. Specifically, it allows the application to perform +custom business logic that extends the pre-commit vote and supply additional data +as part of the vote, although they are signed separately by the same key. + +The data, called vote extension, will be broadcast and received together with the +vote it is extending, and will be made available to the application in the next +height. Specifically, the proposer of the next block will receive the vote extensions +in `RequestPrepareProposal.local_last_commit.votes`. + +If the application does not have vote extension information to provide, it +returns a 0-length byte array as its vote extension. + +**NOTE**: + +* Although each validator process submits its own vote extension, ONLY the *proposer* + of the *next* block will receive all the vote extensions included as part of the + pre-commit phase of the previous block. This means only the proposer will + implicitly have access to all the vote extensions, via `RequestPrepareProposal`, + and that not all vote extensions may be included, since a validator does not + have to wait for all pre-commits, only 2/3. +* The pre-commit vote is signed independently from the vote extension. + +### `VerifyVoteExtension` + +This method allows validators to validate the vote extension data attached to +each pre-commit message it receives. If the validation fails, the whole pre-commit +message will be deemed invalid and ignored by CometBFT. + +CometBFT uses `VerifyVoteExtension` when validating a pre-commit vote. Specifically, +for a pre-commit, CometBFT will: + +* Reject the message if it doesn't contain a signed vote AND a signed vote extension +* Reject the message if the vote's signature OR the vote extension's signature fails to verify +* Reject the message if `VerifyVoteExtension` was rejected by the app + +Otherwise, CometBFT will accept the pre-commit message. + +Note, this has important consequences on liveness, i.e., if vote extensions repeatedly +cannot be verified by correct validators, CometBFT may not be able to finalize +a block even if sufficiently many (+2/3) validators send pre-commit votes for +that block. Thus, `VerifyVoteExtension` should be used with special care. + +CometBFT recommends that an application that detects an invalid vote extension +SHOULD accept it in `ResponseVerifyVoteExtension` and ignore it in its own logic. + +### `FinalizeBlock` + +This method delivers a decided block to the application. The application must +execute the transactions in the block deterministically and update its state +accordingly. Cryptographic commitments to the block and transaction results, +returned via the corresponding parameters in `ResponseFinalizeBlock`, are +included in the header of the next block. CometBFT calls it when a new block +is decided. + +In other words, `FinalizeBlock` encapsulates the current ABCI execution flow of +`BeginBlock`, one or more `DeliverTx`, and `EndBlock` into a single ABCI method. +CometBFT will no longer execute requests for these legacy methods and instead +will just simply call `FinalizeBlock`. + +## Decision + +We will discuss changes to the Cosmos SDK to implement ABCI 2.0 in two distinct +phases, `VoteExtensions` and `FinalizeBlock`. + +### `VoteExtensions` + +Similarly for `PrepareProposal` and `ProcessProposal`, we propose to introduce +two new handlers that an application can implement in order to provide and verify +vote extensions. + +We propose the following new handlers for applications to implement: + +```go +type ExtendVoteHandler func(sdk.Context, abci.RequestExtendVote) abci.ResponseExtendVote +type VerifyVoteExtensionHandler func(sdk.Context, abci.RequestVerifyVoteExtension) abci.ResponseVerifyVoteExtension +``` + +A new execution state, `voteExtensionState`, will be introduced and provided as +the `Context` that is supplied to both handlers. It will contain relevant metadata +such as the block height and block hash. Note, `voteExtensionState` is never +committed and will exist as ephemeral state only in the context of a single block. + +If an application decides to implement `ExtendVoteHandler`, it must return a +non-nil `ResponseExtendVote.VoteExtension`. + +Recall, an implementation of `ExtendVoteHandler` does NOT need to be deterministic, +however, given a set of vote extensions, `VerifyVoteExtensionHandler` must be +deterministic, otherwise the chain may suffer from liveness faults. In addition, +recall CometBFT proceeds in rounds for each height, so if a decision cannot be +made about about a block proposal at a given height, CometBFT will proceed to the +next round and thus will execute `ExtendVote` and `VerifyVoteExtension` again for +the new round for each validator until 2/3 valid pre-commits can be obtained. + +Given the broad scope of potential implementations and use-cases of vote extensions, +and how to verify them, most applications should choose to implement the handlers +through a single handler type, which can have any number of dependencies injected +such as keepers. In addition, this handler type could contain some notion of +volatile vote extension state management which would assist in vote extension +verification. This state management could be ephemeral or could be some form of +on-disk persistence. + +Example: + +```go +// VoteExtensionHandler implements an Oracle vote extension handler. +type VoteExtensionHandler struct { + cdc Codec + mk MyKeeper + state VoteExtState // This could be a map or a DB connection object +} + +// ExtendVoteHandler can do something with h.mk and possibly h.state to create +// a vote extension, such as fetching a series of prices for supported assets. +func (h VoteExtensionHandler) ExtendVoteHandler(ctx sdk.Context, req abci.RequestExtendVote) abci.ResponseExtendVote { + prices := GetPrices(ctx, h.mk.Assets()) + bz, err := EncodePrices(h.cdc, prices) + if err != nil { + panic(fmt.Errorf("failed to encode prices for vote extension: %w", err)) + } + + // store our vote extension at the given height + // + // NOTE: Vote extensions can be overridden since we can timeout in a round. + SetPrices(h.state, req, bz) + + return abci.ResponseExtendVote{VoteExtension: bz} +} + +// VerifyVoteExtensionHandler can do something with h.state and req to verify +// the req.VoteExtension field, such as ensuring the provided oracle prices are +// within some valid range of our prices. +func (h VoteExtensionHandler) VerifyVoteExtensionHandler(ctx sdk.Context, req abci.RequestVerifyVoteExtension) abci.ResponseVerifyVoteExtension { + prices, err := DecodePrices(h.cdc, req.VoteExtension) + if err != nil { + log("failed to decode vote extension", "err", err) + return abci.ResponseVerifyVoteExtension{Status: REJECT} + } + + if err := ValidatePrices(h.state, req, prices); err != nil { + log("failed to validate vote extension", "prices", prices, "err", err) + return abci.ResponseVerifyVoteExtension{Status: REJECT} + } + + // store updated vote extensions at the given height + // + // NOTE: Vote extensions can be overridden since we can timeout in a round. + SetPrices(h.state, req, req.VoteExtension) + + return abci.ResponseVerifyVoteExtension{Status: ACCEPT} +} +``` + +#### Vote Extension Propagation & Verification + +As mentioned previously, vote extensions for height `H` are only made available +to the proposer at height `H+1` during `PrepareProposal`. However, in order to +make vote extensions useful, all validators should have access to the agreed upon +vote extensions at height `H` during `H+1`. + +Since CometBFT includes all the vote extension signatures in `RequestPrepareProposal`, +we propose that the proposing validator manually "inject" the vote extensions +along with their respective signatures via a special transaction, `VoteExtsTx`, +into the block proposal during `PrepareProposal`. The `VoteExtsTx` will be +populated with a single `ExtendedCommitInfo` object which is received directly +from `RequestPrepareProposal`. + +For convention, the `VoteExtsTx` transaction should be the first transaction in +the block proposal, although chains can implement their own preferences. For +safety purposes, we also propose that the proposer itself verify all the vote +extension signatures it receives in `RequestPrepareProposal`. + +A validator, upon a `RequestProcessProposal`, will receive the injected `VoteExtsTx` +which includes the vote extensions along with their signatures. If no such transaction +exists, the validator MUST REJECT the proposal. + +When a validator inspects a `VoteExtsTx`, it will evaluate each `SignedVoteExtension`. +For each signed vote extension, the validator will generate the signed bytes and +verify the signature. At least 2/3 valid signatures, based on voting power, must +be received in order for the block proposal to be valid, otherwise the validator +MUST REJECT the proposal. + +In order to have the ability to validate signatures, `BaseApp` must have access +to the `x/staking` module, since this module stores an index from consensus +address to public key. However, we will avoid a direct dependency on `x/staking` +and instead rely on an interface instead. In addition, the Cosmos SDK will expose +a default signature verification method which applications can use: + +```go +type ValidatorStore interface { + GetValidatorByConsAddr(sdk.Context, cryptotypes.Address) (cryptotypes.PubKey, error) +} + +// ValidateVoteExtensions is a function that an application can execute in +// ProcessProposal to verify vote extension signatures. +func (app *BaseApp) ValidateVoteExtensions(ctx sdk.Context, currentHeight int64, extCommit abci.ExtendedCommitInfo) error { + for _, vote := range extCommit.Votes { + if !vote.SignedLastBlock || len(vote.VoteExtension) == 0 { + continue + } + + valConsAddr := cmtcrypto.Address(vote.Validator.Address) + + validator, err := app.validatorStore.GetValidatorByConsAddr(ctx, valConsAddr) + if err != nil { + return fmt.Errorf("failed to get validator %s for vote extension", valConsAddr) + } + + cmtPubKey, err := validator.CmtConsPublicKey() + if err != nil { + return fmt.Errorf("failed to convert public key: %w", err) + } + + if len(vote.ExtensionSignature) == 0 { + return fmt.Errorf("received a non-empty vote extension with empty signature for validator %s", valConsAddr) + } + + cve := cmtproto.CanonicalVoteExtension{ + Extension: vote.VoteExtension, + Height: currentHeight - 1, // the vote extension was signed in the previous height + Round: int64(extCommit.Round), + ChainId: app.GetChainID(), + } + + extSignBytes, err := cosmosio.MarshalDelimited(&cve) + if err != nil { + return fmt.Errorf("failed to encode CanonicalVoteExtension: %w", err) + } + + if !cmtPubKey.VerifySignature(extSignBytes, vote.ExtensionSignature) { + return errors.New("received vote with invalid signature") + } + + return nil + } +} +``` + +Once at least 2/3 signatures, by voting power, are received and verified, the +validator can use the vote extensions to derive additional data or come to some +decision based on the vote extensions. + +> NOTE: It is very important to state, that neither the vote propagation technique +> nor the vote extension verification mechanism described above is required for +> applications to implement. In other words, a proposer is not required to verify +> and propagate vote extensions along with their signatures nor are proposers +> required to verify those signatures. An application can implement it's own +> PKI mechanism and use that to sign and verify vote extensions. + +#### Vote Extension Persistence + +In certain contexts, it may be useful or necessary for applications to persist +data derived from vote extensions. In order to facilitate this use case, we +propose to allow application developers to manually retrieve the `finalizeState` +context (see [`FinalizeBlock`](#finalizeblock-1) below). Using this context, +state can be directly written to `finalizeState`, which will be used during +`FinalizeBlock` and eventually committed to the application state. Note, since +`ProcessProposal` can timeout and thus require another round of consensus, we +will reset `finalizeState` in the beginning of `ProcessProposal`. + +A `ProcessProposal` handler could look like the following: + +```go +func (h MyHandler) ProcessProposalHandler() sdk.ProcessProposalHandler { + return func(ctx sdk.Context, req abci.RequestProcessProposal) abci.ResponseProcessProposal { + for _, txBytes := range req.Txs { + _, err := h.app.ProcessProposalVerifyTx(txBytes) + if err != nil { + return abci.ResponseProcessProposal{Status: abci.ResponseProcessProposal_REJECT} + } + } + + fCtx := h.app.GetFinalizeState() + + // Any state changes that occur on the provided fCtx WILL be written to state! + h.myKeeper.SetVoteExtResult(fCtx, ...) + + return abci.ResponseProcessProposal{Status: abci.ResponseProcessProposal_ACCEPT} + } +} +``` + +### `FinalizeBlock` + +The existing ABCI methods `BeginBlock`, `DeliverTx`, and `EndBlock` have existed +since the dawn of ABCI-based applications. Thus, applications, tooling, and developers +have grown used to these methods and their use-cases. Specifically, `BeginBlock` +and `EndBlock` have grown to be pretty integral and powerful within ABCI-based +applications. E.g. an application might want to run distribution and inflation +related operations prior to executing transactions and then have staking related +changes to happen after executing all transactions. + +We propose to keep `BeginBlock` and `EndBlock` within the SDK's core module +interfaces only so application developers can continue to build against existing +execution flows. However, we will remove `BeginBlock`, `DeliverTx` and `EndBlock` +from the SDK's `BaseApp` implementation and thus the ABCI surface area. + +What will then exist is a single `FinalizeBlock` execution flow. Specifically, in +`FinalizeBlock` we will execute the application's `BeginBlock`, followed by +execution of all the transactions, finally followed by execution of the application's +`EndBlock`. + +Note, we will still keep the existing transaction execution mechanics within +`BaseApp`, but all notions of `DeliverTx` will be removed, i.e. `deliverState` +will be replace with `finalizeState`, which will be committed on `Commit`. + +However, there are current parameters and fields that exist in the existing +`BeginBlock` and `EndBlock` ABCI types, such as votes that are used in distribution +and byzantine validators used in evidence handling. These parameters exist in the +`FinalizeBlock` request type, and will need to be passed to the application's +implementations of `BeginBlock` and `EndBlock`. + +This means the Cosmos SDK's core module interfaces will need to be updated to +reflect these parameters. The easiest and most straightforward way to achieve +this is to just pass `RequestFinalizeBlock` to `BeginBlock` and `EndBlock`. +Alternatively, we can create dedicated proxy types in the SDK that reflect these +legacy ABCI types, e.g. `LegacyBeginBlockRequest` and `LegacyEndBlockRequest`. Or, +we can come up with new types and names altogether. + +```go +func (app *BaseApp) FinalizeBlock(req abci.RequestFinalizeBlock) abci.ResponseFinalizeBlock { + // merge any state changes from ProcessProposal into the FinalizeBlock state + app.MergeProcessProposalState() + + beginBlockResp := app.beginBlock(ctx, req) + appendBlockEventAttr(beginBlockResp.Events, "begin_block") + + txExecResults := make([]abci.ExecTxResult, 0, len(req.Txs)) + for _, tx := range req.Txs { + result := app.runTx(runTxModeFinalize, tx) + txExecResults = append(txExecResults, result) + } + + endBlockResp := app.endBlock(ctx, req) + appendBlockEventAttr(beginBlockResp.Events, "end_block") + + return abci.ResponseFinalizeBlock{ + TxResults: txExecResults, + Events: joinEvents(beginBlockResp.Events, endBlockResp.Events), + ValidatorUpdates: endBlockResp.ValidatorUpdates, + ConsensusParamUpdates: endBlockResp.ConsensusParamUpdates, + AppHash: nil, + } +} +``` + +#### Events + +Many tools, indexers and ecosystem libraries rely on the existence `BeginBlock` +and `EndBlock` events. Since CometBFT now only exposes `FinalizeBlockEvents`, we +find that it will still be useful for these clients and tools to still query for +and rely on existing events, especially since applications will still define +`BeginBlock` and `EndBlock` implementations. + +In order to facilitate existing event functionality, we propose that all `BeginBlock` +and `EndBlock` events have a dedicated `EventAttribute` with `key=block` and +`value=begin_block|end_block`. The `EventAttribute` will be appended to each event +in both `BeginBlock` and `EndBlock` events`. + + +### Upgrading + +CometBFT defines a consensus parameter, [`VoteExtensionsEnableHeight`](https://github.com/cometbft/cometbft/blob/v0.38.0-alpha.1/spec/abci/abci%2B%2B_app_requirements.md#abciparamsvoteextensionsenableheight), +which specifies the height at which vote extensions are enabled and **required**. +If the value is set to zero, which is the default, then vote extensions are +disabled and an application is not required to implement and use vote extensions. + +However, if the value `H` is positive, at all heights greater than the configured +height `H` vote extensions must be present (even if empty). When the configured +height `H` is reached, `PrepareProposal` will not include vote extensions yet, +but `ExtendVote` and `VerifyVoteExtension` will be called. Then, when reaching +height `H+1`, `PrepareProposal` will include the vote extensions from height `H`. + +It is very important to note, for all heights after H: + +* Vote extensions CANNOT be disabled +* They are mandatory, i.e. all pre-commit messages sent MUST have an extension + attached (even if empty) + +When an application updates to the Cosmos SDK version with CometBFT v0.38 support, +in the upgrade handler it must ensure to set the consensus parameter +`VoteExtensionsEnableHeight` to the correct value. E.g. if an application is set +to perform an upgrade at height `H`, then the value of `VoteExtensionsEnableHeight` +should be set to any value `>=H+1`. This means that at the upgrade height, `H`, +vote extensions will not be enabled yet, but at height `H+1` they will be enabled. + +## Consequences + +### Backwards Compatibility + +ABCI 2.0 is naturally not backwards compatible with prior versions of the Cosmos SDK +and CometBFT. For example, an application that requests `RequestFinalizeBlock` +to the same application that does not speak ABCI 2.0 will naturally fail. + +In addition, `BeginBlock`, `DeliverTx` and `EndBlock` will be removed from the +application ABCI interfaces and along with the inputs and outputs being modified +in the module interfaces. + +### Positive + +* `BeginBlock` and `EndBlock` semantics remain, so burden on application developers + should be limited. +* Less communication overhead as multiple ABCI requests are condensed into a single + request. +* Sets the groundwork for optimistic execution. +* Vote extensions allow for an entirely new set of application primitives to be + developed, such as in-process price oracles and encrypted mempools. + +### Negative + +* Some existing Cosmos SDK core APIs may need to be modified and thus broken. +* Signature verification in `ProcessProposal` of 100+ vote extension signatures + will add significant performance overhead to `ProcessProposal`. Granted, the + signature verification process can happen concurrently using an error group + with `GOMAXPROCS` goroutines. + +### Neutral + +* Having to manually "inject" vote extensions into the block proposal during + `PrepareProposal` is an awkward approach and takes up block space unnecessarily. +* The requirement of `ResetProcessProposalState` can create a footgun for + application developers if they're not careful, but this is necessary in order + for applications to be able to commit state from vote extension computation. + +## Further Discussions + +Future discussions include design and implementation of ABCI 3.0, which is a +continuation of ABCI++ and the general discussion of optimistic execution. + +## References + +* [ADR 060: ABCI 1.0 (Phase I)](adr-060-abci-1.0.md) diff --git a/docs/docs/README.md b/docs/docs/README.md index 358154e93989..451a0bc1942e 100644 --- a/docs/docs/README.md +++ b/docs/docs/README.md @@ -32,6 +32,6 @@ Check out the docs for the various parts of the Cosmos stack. ## Help & Support +* [**GitHub Discussions**](https://github.com/orgs/cosmos/discussions) - Ask questions and discuss SDK development on GitHub. * [**Discord**](https://discord.gg/cosmosnetwork) - Chat with Cosmos developers on Discord. -* [**GitHub Discussions**](https://github.com/cosmos/cosmos-sdk/discussions) - Ask questions and discuss SDK development on GitHub. * [**Found an issue?**](https://github.com/cosmos/cosmos-sdk/edit/main/docs/docs/README.md) - Help us improve this page by suggesting edits on GitHub. diff --git a/docs/docs/basics/01-tx-lifecycle.md b/docs/docs/basics/01-tx-lifecycle.md index 22a8886bffe6..29ed40370dea 100644 --- a/docs/docs/basics/01-tx-lifecycle.md +++ b/docs/docs/basics/01-tx-lifecycle.md @@ -86,24 +86,29 @@ through several steps, beginning with decoding `Tx`. When `Tx` is received by the application from the underlying consensus engine (e.g. CometBFT ), it is still in its [encoded](../core/05-encoding.md) `[]byte` form and needs to be unmarshaled in order to be processed. Then, the [`runTx`](../core/00-baseapp.md#runtx-antehandler-runmsgs-posthandler) function is called to run in `runTxModeCheck` mode, meaning the function runs all checks but exits before executing messages and writing state changes. -### ValidateBasic +### ValidateBasic (deprecated) Messages ([`sdk.Msg`](../core/01-transactions.md#messages)) are extracted from transactions (`Tx`). The `ValidateBasic` method of the `sdk.Msg` interface implemented by the module developer is run for each transaction. To discard obviously invalid messages, the `BaseApp` type calls the `ValidateBasic` method very early in the processing of the message in the [`CheckTx`](../core/00-baseapp.md#checktx) and [`DeliverTx`](../core/00-baseapp.md#delivertx) transactions. `ValidateBasic` can include only **stateless** checks (the checks that do not require access to the state). -#### Guideline +:::warning +The `ValidateBasic` method on messages has been deprecated in favor of validating messages directly in their respective [`Msg` services](../building-modules/03-msg-services.md#Validation). + +Read [RFC 001](https://docs.cosmos.network/main/rfc/rfc-001-tx-validation) for more details. +::: -Gas is not charged when `ValidateBasic` is executed, so we recommend only performing all necessary stateless checks to enable middleware operations (for example, parsing the required signer accounts to validate a signature by a middleware) and stateless sanity checks not impacting performance of the `CheckTx` phase. -Other validation operations must be performed when [handling a message](../building-modules/msg-services#Validation) in a module Msg Server. +:::note +`BaseApp` still calls `ValidateBasic` on messages that implements that method for backwards compatibility. +::: -For example, if the message is to send coins from one address to another, `ValidateBasic` likely checks for non-empty addresses and a non-negative coin amount, but does not require knowledge of state such as the account balance of an address. +#### Guideline -See also [Msg Service Validation](../building-modules/03-msg-services.md#Validation). +`ValidateBasic` should not be used anymore. Message validation should be performed in the `Msg` service when [handling a message](../building-modules/msg-services#Validation) in a module Msg Server. ### AnteHandler -After the `ValidateBasic` checks, the `AnteHandler`s are run. Technically, they are optional, but in practice, they are very often present to perform signature verification, gas calculation, fee deduction, and other core operations related to blockchain transactions. +`AnteHandler`s even though optional, are in practice very often used to perform signature verification, gas calculation, fee deduction, and other core operations related to blockchain transactions. A copy of the cached context is provided to the `AnteHandler`, which performs limited checks specified for the transaction type. Using a copy allows the `AnteHandler` to do stateful checks for `Tx` without modifying the last committed state, and revert back to the original if the execution fails. diff --git a/docs/docs/building-apps/01-app-go-v2.md b/docs/docs/building-apps/01-app-go-v2.md index 926d86dbbe4e..d22b9b040216 100644 --- a/docs/docs/building-apps/01-app-go-v2.md +++ b/docs/docs/building-apps/01-app-go-v2.md @@ -6,7 +6,7 @@ sidebar_position: 1 :::note Synopsis -The Cosmos SDK allows much easier wiring of an `app.go` thanks to App Wiring and [`depinject`](../tooling/02-depinject.md). +The Cosmos SDK allows much easier wiring of an `app.go` thanks to App Wiring and [`depinject`](../packages/01-depinject.md). Learn more about the rationale of App Wiring in [ADR-057](../architecture/adr-057-app-wiring.md). ::: @@ -16,7 +16,8 @@ Learn more about the rationale of App Wiring in [ADR-057](../architecture/adr-05 ### Pre-requisite Readings * [ADR 057: App Wiring](../architecture/adr-057-app-wiring.md) -* [Depinject Documentation](../tooling/02-depinject.md) +* [Depinject Documentation](../packages/01-depinject.md) +* [Modules depinject-ready](../building-modules/15-depinject.md) ::: diff --git a/docs/docs/migrations/01-pre-upgrade.md b/docs/docs/building-apps/03-app-upgrade.md similarity index 83% rename from docs/docs/migrations/01-pre-upgrade.md rename to docs/docs/building-apps/03-app-upgrade.md index 5b0c241ee2e3..d60e781177bc 100644 --- a/docs/docs/migrations/01-pre-upgrade.md +++ b/docs/docs/building-apps/03-app-upgrade.md @@ -2,7 +2,17 @@ sidebar_position: 1 --- -# Pre-Upgrade Handling +# Application upgrade + +:::note +This document describes how to upgrade your application. If you are looking specifically for the changes to perform between SDK versions, see the [SDK migrations documentation](https://docs.cosmos.network/main/migrations/intro). +::: + +:::warning +This section is currently incomplete. Track the progress of this document [here](https://github.com/cosmos/cosmos-sdk/issues/11504). +::: + +## Pre-Upgrade Handling Cosmovisor supports custom pre-upgrade handling. Use pre-upgrade handling when you need to implement application config changes that are required in the newer version before you perform the upgrade. diff --git a/docs/docs/building-modules/02-messages-and-queries.md b/docs/docs/building-modules/02-messages-and-queries.md index 749f7547ece9..e2cb642ee6ef 100644 --- a/docs/docs/building-modules/02-messages-and-queries.md +++ b/docs/docs/building-modules/02-messages-and-queries.md @@ -38,7 +38,7 @@ Each `Msg` service method must have exactly one argument, which must implement t rpc Send(MsgSend) returns (MsgSendResponse); ``` -`sdk.Msg` interface is a simplified version of the Amino `LegacyMsg` interface described [below](#legacy-amino-msgs) with only `ValidateBasic()` and `GetSigners()` methods. For backwards compatibility with [Amino `LegacyMsg`s](#legacy-amino-msgs), existing `LegacyMsg` types should be used as the request parameter for `service` RPC definitions. Newer `sdk.Msg` types, which only support `service` definitions, should use canonical `Msg...` name. +`sdk.Msg` interface is a simplified version of the Amino `LegacyMsg` interface described [below](#legacy-amino-msgs) with the `GetSigners()` method. For backwards compatibility with [Amino `LegacyMsg`s](#legacy-amino-msgs), existing `LegacyMsg` types should be used as the request parameter for `service` RPC definitions. Newer `sdk.Msg` types, which only support `service` definitions, should use canonical `Msg...` name. The Cosmos SDK uses Protobuf definitions to generate client and server code: @@ -63,7 +63,6 @@ https://github.com/cosmos/cosmos-sdk/blob/v0.47.0-rc1/types/tx_msg.go#L14-L26 It extends `proto.Message` and contains the following methods: -* [`ValidateBasic() error`](../basics/01-tx-lifecycle.md#ValidateBasic). * `GetSignBytes() []byte`: Return the canonical byte representation of the message. Used to generate a signature. * `GetSigners() []AccAddress`: Return the list of signers. The Cosmos SDK will make sure that each `message` contained in a transaction is signed by all the signers listed in the list returned by this method. diff --git a/docs/docs/building-modules/03-msg-services.md b/docs/docs/building-modules/03-msg-services.md index b1e9a54d336a..c1c57b3f1fef 100644 --- a/docs/docs/building-modules/03-msg-services.md +++ b/docs/docs/building-modules/03-msg-services.md @@ -43,10 +43,12 @@ https://github.com/cosmos/cosmos-sdk/blob/v0.47.0-rc1/x/bank/keeper/msg_server.g `sdk.Msg` processing usually follows these 3 steps: -### Validation +### Validation -Before a `msgServer` method is executed, the message's [`ValidateBasic()`](../basics/01-tx-lifecycle.md#ValidateBasic) method has already been called. Since `msg.ValidateBasic()` performs only the most basic checks, this stage must perform all other validation (both *stateful* and *stateless*) to make sure the `message` is valid. Checks performed in the `msgServer` method can be more expensive and the signer is charged gas for these operations. -For example, a `msgServer` method for a `transfer` message might check that the sending account has enough funds to actually perform the transfer. +The message server must perform all validation required (both *stateful* and *stateless*) to make sure the `message` is valid. +The `signer` is charged for the gas cost of this validation. + +For example, a `msgServer` method for a `transfer` message should check that the sending account has enough funds to actually perform the transfer. It is recommended to implement all validation checks in a separate function that passes state values as arguments. This implementation simplifies testing. As expected, expensive validation functions charge additional gas. Example: @@ -60,6 +62,11 @@ ValidateMsgA(msg MsgA, now Time, gm GasMeter) error { } ``` +:::warning +Previously, the `ValidateBasic` method was used to perform simple and stateless validation checks. +This way of validating is deprecated, this means the `msgServer` must perform all validation checks. +::: + ### State Transition After the validation is successful, the `msgServer` method uses the [`keeper`](./06-keeper.md) functions to access the state and perform a state transition. diff --git a/docs/docs/building-modules/05-beginblock-endblock.md b/docs/docs/building-modules/05-beginblock-endblock.md index 4cfdda370f05..3e5667ed7d97 100644 --- a/docs/docs/building-modules/05-beginblock-endblock.md +++ b/docs/docs/building-modules/05-beginblock-endblock.md @@ -43,3 +43,5 @@ and an example implementation of `EndBlocker` from the `staking` module: ```go reference https://github.com/cosmos/cosmos-sdk/blob/v0.47.0-rc1/x/staking/abci.go#L22-L27 ``` + + diff --git a/docs/docs/building-modules/06-keeper.md b/docs/docs/building-modules/06-keeper.md index 946eff6ff137..7f8f4457556f 100644 --- a/docs/docs/building-modules/06-keeper.md +++ b/docs/docs/building-modules/06-keeper.md @@ -56,7 +56,7 @@ Of course, it is possible to define different types of internal `keeper`s for th ## Implementing Methods -`Keeper`s primarily expose getter and setter methods for the store(s) managed by their module. These methods should remain as simple as possible and strictly be limited to getting or setting the requested value, as validity checks should have already been performed via the `ValidateBasic()` method of the [`message`](./02-messages-and-queries.md#messages) and the [`Msg` server](./03-msg-services.md) when `keeper`s' methods are called. +`Keeper`s primarily expose getter and setter methods for the store(s) managed by their module. These methods should remain as simple as possible and strictly be limited to getting or setting the requested value, as validity checks should have already been performed by the [`Msg` server](./03-msg-services.md) when `keeper`s' methods are called. Typically, a *getter* method will have the following signature diff --git a/docs/docs/building-modules/09-module-interfaces.md b/docs/docs/building-modules/09-module-interfaces.md index 12f290183b9f..4059e9a87753 100644 --- a/docs/docs/building-modules/09-module-interfaces.md +++ b/docs/docs/building-modules/09-module-interfaces.md @@ -43,7 +43,7 @@ In general, the getter function does the following: * **RunE:** Defines a function that can return an error. This is the function that is called when the command is executed. This function encapsulates all of the logic to create a new transaction. * The function typically starts by getting the `clientCtx`, which can be done with `client.GetClientTxContext(cmd)`. The `clientCtx` contains information relevant to transaction handling, including information about the user. In this example, the `clientCtx` is used to retrieve the address of the sender by calling `clientCtx.GetFromAddress()`. * If applicable, the command's arguments are parsed. In this example, the arguments `[to_address]` and `[amount]` are both parsed. - * A [message](./02-messages-and-queries.md) is created using the parsed arguments and information from the `clientCtx`. The constructor function of the message type is called directly. In this case, `types.NewMsgSend(fromAddr, toAddr, amount)`. Its good practice to call [`msg.ValidateBasic()`](../basics/01-tx-lifecycle.md#ValidateBasic) and other validation methods before broadcasting the message. + * A [message](./02-messages-and-queries.md) is created using the parsed arguments and information from the `clientCtx`. The constructor function of the message type is called directly. In this case, `types.NewMsgSend(fromAddr, toAddr, amount)`. Its good practice to call, if possible, the necessary [message validation methods](../building-modules/03-msg-services.md#Validation) before broadcasting the message. * Depending on what the user wants, the transaction is either generated offline or signed and broadcasted to the preconfigured node using `tx.GenerateOrBroadcastTxCLI(clientCtx, flags, msg)`. * **Adds transaction flags:** All transaction commands must add a set of transaction [flags](#flags). The transaction flags are used to collect additional information from the user (e.g. the amount of fees the user is willing to pay). The transaction flags are added to the constructed command using `AddTxFlagsToCmd(cmd)`. * **Returns the command:** Finally, the transaction command is returned. diff --git a/docs/docs/building-modules/11-structure.md b/docs/docs/building-modules/11-structure.md index 4e7b15398fed..5e31c31d944b 100644 --- a/docs/docs/building-modules/11-structure.md +++ b/docs/docs/building-modules/11-structure.md @@ -75,7 +75,7 @@ x/{module_name} └── README.md ``` -* `client/`: The module's CLI client functionality implementation and the module's integration testing suite. +* `client/`: The module's CLI client functionality implementation and the module's CLI testing suite. * `exported/`: The module's exported types - typically interface types. If a module relies on keepers from another module, it is expected to receive the keepers as interface contracts through the `expected_keepers.go` file (see below) in order to avoid a direct dependency on the module implementing the keepers. However, these interface contracts can define methods that operate on and/or return types that are specific to the module that is implementing the keepers and this is where `exported/` comes into play. The interface types that are defined in `exported/` use canonical types, allowing for the module to receive the keepers as interface contracts through the `expected_keepers.go` file. This pattern allows for code to remain DRY and also alleviates import cycle chaos. * `keeper/`: The module's `Keeper` and `MsgServer` implementation. * `module/`: The module's `AppModule` and `AppModuleBasic` implementation. diff --git a/docs/docs/building-modules/15-depinject.md b/docs/docs/building-modules/15-depinject.md index 66dafca863da..fc793f04b780 100644 --- a/docs/docs/building-modules/15-depinject.md +++ b/docs/docs/building-modules/15-depinject.md @@ -2,17 +2,17 @@ sidebar_position: 1 --- -# Dependency Injection +# Modules depinject-ready :::note ### Pre-requisite Readings -* [Cosmos SDK Dependency Injection Framework](../tooling/02-depinject.md) +* [Depinject Documentation](../packages/01-depinject.md) ::: -[`depinject`](../tooling/02-depinject.md) is used to wire any module in `app.go`. +[`depinject`](../packages/01-depinject.md) is used to wire any module in `app.go`. All core modules are already configured to support dependency injection. To work with `depinject` a module must define its configuration and requirements so that `depinject` can provide the right dependencies. @@ -79,7 +79,13 @@ All methods, structs and their fields must be public for `depinject`. https://github.com/cosmos/cosmos-sdk/blob/v0.47.0-rc1/x/group/module/module.go#L199-L204 ``` -2. Define a struct that inherits `depinject.In` and define the module inputs (i.e. module dependencies): +2. Ensure that the module implements the `appmodule.AppModule` interface: + + ```go reference + https://github.com/cosmos/cosmos-sdk/blob/v0.47.0/x/group/module/module.go#L58-L64 + ``` + +3. Define a struct that inherits `depinject.In` and define the module inputs (i.e. module dependencies): * `depinject` provides the right dependencies to the module. * `depinject` also checks that all dependencies are provided. @@ -91,14 +97,14 @@ All methods, structs and their fields must be public for `depinject`. https://github.com/cosmos/cosmos-sdk/blob/v0.47.0-rc1/x/group/module/module.go#L206-L216 ``` -3. Define the module outputs with a public struct that inherits `depinject.Out`: +4. Define the module outputs with a public struct that inherits `depinject.Out`: The module outputs are the dependencies that the module provides to other modules. It is usually the module itself and its keeper. ```go reference https://github.com/cosmos/cosmos-sdk/blob/v0.47.0-rc1/x/group/module/module.go#L218-L223 ``` -4. Create a function named `ProvideModule` (as called in 1.) and use the inputs for instantiating the module outputs. +5. Create a function named `ProvideModule` (as called in 1.) and use the inputs for instantiating the module outputs. ```go reference https://github.com/cosmos/cosmos-sdk/blob/v0.47.0-rc1/x/group/module/module.go#L225-L235 @@ -115,6 +121,6 @@ https://github.com/cosmos/cosmos-sdk/blob/v0.47.0-rc1/x/group/module/module.go#L The module is now ready to be used with `depinject` by a chain developer. -## App Wiring +## Integrate in an application The App Wiring is done in `app_config.go` / `app.yaml` and `app_v2.go` and is explained in detail in the [overview of `app_v2.go`](../building-apps/01-app-go-v2.md). diff --git a/docs/docs/building-modules/16-testing.md b/docs/docs/building-modules/16-testing.md index 7de77ec8993d..cd49fc454a30 100644 --- a/docs/docs/building-modules/16-testing.md +++ b/docs/docs/building-modules/16-testing.md @@ -57,34 +57,16 @@ https://github.com/cosmos/cosmos-sdk/blob/v0.47.0-rc1/x/gov/keeper/keeper_test.g Integration tests are at the second level of the [test pyramid](https://martinfowler.com/articles/practical-test-pyramid.html). In the SDK, we locate our integration tests under [`/tests/integrations`](https://github.com/cosmos/cosmos-sdk/tree/main/tests/integration). -The goal of these integration tests is to test a component with a minimal application (i.e. not `simapp`). The minimal application is defined with the help of [`depinject`](../tooling/02-depinject.md) – the SDK dependency injection framework, and includes all necessary modules to test the component. With the helps of the SDK testing package, we can easily create a minimal application and start the application with a set of genesis transactions: . +The goal of these integration tests is to test how a component interacts with other dependencies. Compared to unit tests, integration tests do not mock dependencies. Instead, they use the direct dependencies of the component. This differs as well from end-to-end tests, which test the component with a full application. -### Example - -Here, we will walkthrough the integration tests of the `x/distribution` module. The `x/distribution` module has, in addition to keeper unit tests, integration tests that test the `x/distribution` module with a minimal application. This is expected as you may want to test the `x/distribution` module with actual application logic, instead of only mocked dependencies. - -For creating a minimal application, we use [`simtestutil.Setup`](https://github.com/cosmos/cosmos-sdk/blob/v0.47.0-rc1/testutil/sims/app_helpers.go#L95-L99) and an [`AppConfig`](../tooling/02-depinject.md) of the `x/distribution` minimal dependencies. - -For instance, the `AppConfig` of `x/distribution` is defined as: - -* https://github.com/cosmos/cosmos-sdk/blob/v0.47.0-rc1/x/distribution/testutil/app_config.go - -This is a stripped down version of the `simapp` `AppConfig`: - -* https://github.com/cosmos/cosmos-sdk/blob/v0.47.0-rc1/simapp/app_config.go - -:::note -You can as well use the `AppConfig` `configurator` for creating an `AppConfig` [inline](https://github.com/cosmos/cosmos-sdk/blob/v0.47.0-rc1/x/slashing/app_test.go#L54-L62). There no difference between those two ways, use whichever you prefer. -::: +Integration tests interact with the tested module via the defined `Msg` and `Query` services. The result of the test can be verified by checking the state of the application, by checking the emitted events or the response. It is adviced to combine two of these methods to verify the result of the test. -```go reference -https://github.com/cosmos/cosmos-sdk/blob/v0.47.0-rc1/tests/integration/distribution/keeper/keeper_test.go#L28-L33 -``` +The SDK provides small helpers for quickly setting up an integration tests. These helpers can be found at . -Now the types are injected and we can use them for our tests: +### Example ```go reference -https://github.com/cosmos/cosmos-sdk/blob/v0.47.0-rc1/tests/integration/distribution/keeper/keeper_test.go#L21-L53 +https://github.com/cosmos/cosmos-sdk/blob/29e22b3bdb05353555c8e0b269311bbff7b8deca/testutil/integration/example_test.go#L22-L89 ``` ## Deterministic and Regression tests @@ -104,7 +86,11 @@ https://github.com/cosmos/cosmos-sdk/blob/v0.47.0-rc1/tests/integration/bank/kee ## Simulations -Simulations uses as well a minimal application, built with [`depinject`](../tooling/02-depinject.md): +Simulations uses as well a minimal application, built with [`depinject`](../packages/01-depinject.md): + +:::note +You can as well use the `AppConfig` `configurator` for creating an `AppConfig` [inline](https://github.com/cosmos/cosmos-sdk/blob/v0.47.0-rc1/x/slashing/app_test.go#L54-L62). There is no difference between those two ways, use whichever you prefer. +::: Following is an example for `x/gov/` simulations: @@ -121,6 +107,7 @@ https://github.com/cosmos/cosmos-sdk/blob/v0.47.0-rc1/x/gov/simulation/operation End-to-end tests are at the top of the [test pyramid](https://martinfowler.com/articles/practical-test-pyramid.html). They must test the whole application flow, from the user perspective (for instance, CLI tests). They are located under [`/tests/e2e`](https://github.com/cosmos/cosmos-sdk/tree/main/tests/e2e). + For that, the SDK is using `simapp` but you should use your own application (`appd`). Here are some examples: @@ -132,11 +119,6 @@ Here are some examples: The SDK is in the process of creating its E2E tests, as defined in [ADR-59](https://docs.cosmos.network/main/architecture/adr-059-test-scopes.html). This page will eventually be updated with better examples. ::: -## Summary +## Learn More -| Scope | App Fixture | Mocks? | -| ----------- | ----------- | ------ | -| Unit | None | Yes | -| Integration | `depinject` | Some | -| Simulation | `depinject` | No | -| E2E | `appd` | No | +Learn more about testing scope in [ADR-59](https://docs.cosmos.network/main/architecture/adr-059-test-scopes.html). diff --git a/docs/docs/core/00-baseapp.md b/docs/docs/core/00-baseapp.md index e18267116ce9..f54053ad8076 100644 --- a/docs/docs/core/00-baseapp.md +++ b/docs/docs/core/00-baseapp.md @@ -320,9 +320,10 @@ In the Cosmos SDK, after [decoding transactions](./05-encoding.md), `CheckTx()` to do the following checks: 1. Extract the `sdk.Msg`s from the transaction. -2. Perform _stateless_ checks by calling `ValidateBasic()` on each of the `sdk.Msg`s. This is done +2. **Optionally** perform _stateless_ checks by calling `ValidateBasic()` on each of the `sdk.Msg`s. This is done first, as _stateless_ checks are less computationally expensive than _stateful_ checks. If `ValidateBasic()` fail, `CheckTx` returns before running _stateful_ checks, which saves resources. + This check is still performed for messages that have not yet migrated to the new message validation mechanism defined in [RFC 001](https://docs.cosmos.network/main/rfc/rfc-001-tx-validation) and still have a `ValidateBasic()` method. 3. Perform non-module related _stateful_ checks on the [account](../basics/03-accounts.md). This step is mainly about checking that the `sdk.Msg` signatures are valid, that enough fees are provided and that the sending account has enough funds to pay for said fees. Note that no precise [`gas`](../basics/04-gas-fees.md) counting occurs here, @@ -408,7 +409,7 @@ At any point, if `GasConsumed > GasWanted`, the function returns with `Code != 0 The first thing `RunTx` does upon being called is to retrieve the `context`'s `CacheMultiStore` by calling the `getContextForTx()` function with the appropriate mode (either `runTxModeCheck` or `runTxModeDeliver`). This `CacheMultiStore` is a branch of the main store, with cache functionality (for query requests), instantiated during `BeginBlock` for `DeliverTx` and during the `Commit` of the previous block for `CheckTx`. After that, two `defer func()` are called for [`gas`](../basics/04-gas-fees.md) management. They are executed when `runTx` returns and make sure `gas` is actually consumed, and will throw errors, if any. -After that, `RunTx()` calls `ValidateBasic()` on each `sdk.Msg`in the `Tx`, which runs preliminary _stateless_ validity checks. If any `sdk.Msg` fails to pass `ValidateBasic()`, `RunTx()` returns with an error. +After that, `RunTx()` calls `ValidateBasic()`, when available and for backward compatibility, on each `sdk.Msg`in the `Tx`, which runs preliminary _stateless_ validity checks. If any `sdk.Msg` fails to pass `ValidateBasic()`, `RunTx()` returns with an error. Then, the [`anteHandler`](#antehandler) of the application is run (if it exists). In preparation of this step, both the `checkState`/`deliverState`'s `context` and `context`'s `CacheMultiStore` are branched using the `cacheTxContext()` function. diff --git a/docs/docs/core/01-transactions.md b/docs/docs/core/01-transactions.md index 8c1fa3f9e912..e8446646ae8c 100644 --- a/docs/docs/core/01-transactions.md +++ b/docs/docs/core/01-transactions.md @@ -33,7 +33,11 @@ https://github.com/cosmos/cosmos-sdk/blob/v0.47.0-rc1/types/tx_msg.go#L42-L50 It contains the following methods: * **GetMsgs:** unwraps the transaction and returns a list of contained `sdk.Msg`s - one transaction may have one or multiple messages, which are defined by module developers. -* **ValidateBasic:** lightweight, [_stateless_](../basics/01-tx-lifecycle.md#types-of-checks) checks used by ABCI messages [`CheckTx`](./00-baseapp.md#checktx) and [`DeliverTx`](./00-baseapp.md#delivertx) to make sure transactions are not invalid. For example, the [`auth`](https://github.com/cosmos/cosmos-sdk/tree/main/x/auth) module's `ValidateBasic` function checks that its transactions are signed by the correct number of signers and that the fees do not exceed what the user's maximum. Note that this function is to be distinct from `sdk.Msg` [`ValidateBasic`](../basics/01-tx-lifecycle.md#ValidateBasic) methods, which perform basic validity checks on messages only. When [`runTx`](./00-baseapp.md#runtx) is checking a transaction created from the [`auth`](https://github.com/cosmos/cosmos-sdk/tree/main/x/auth/spec) module, it first runs `ValidateBasic` on each message, then runs the `auth` module AnteHandler which calls `ValidateBasic` for the transaction itself. +* **ValidateBasic:** lightweight, [_stateless_](../basics/01-tx-lifecycle.md#types-of-checks) checks used by ABCI messages [`CheckTx`](./00-baseapp.md#checktx) and [`DeliverTx`](./00-baseapp.md#delivertx) to make sure transactions are not invalid. For example, the [`auth`](https://github.com/cosmos/cosmos-sdk/tree/main/x/auth) module's `ValidateBasic` function checks that its transactions are signed by the correct number of signers and that the fees do not exceed what the user's maximum. When [`runTx`](./00-baseapp.md#runtx) is checking a transaction created from the [`auth`](https://github.com/cosmos/cosmos-sdk/tree/main/x/auth/spec) module, it first runs `ValidateBasic` on each message, then runs the `auth` module AnteHandler which calls `ValidateBasic` for the transaction itself. + + :::note + This function is different from the deprecated `sdk.Msg` [`ValidateBasic`](../basics/01-tx-lifecycle.md#ValidateBasic) methods, which was performing basic validity checks on messages only. + ::: As a developer, you should rarely manipulate `Tx` directly, as `Tx` is really an intermediate type used for transaction generation. Instead, developers should prefer the `TxBuilder` interface, which you can learn more about [below](#transaction-generation). diff --git a/docs/docs/core/16-config.md b/docs/docs/core/16-config.md index ed04614d9fea..03aa55a21ec9 100644 --- a/docs/docs/core/16-config.md +++ b/docs/docs/core/16-config.md @@ -6,8 +6,8 @@ sidebar_position: 1 This documentation refers to the app.toml, if you'd like to read about the config.toml please visit [CometBFT docs](https://docs.cometbft.com/v0.37/). - -```toml reference + +```python reference https://github.com/cosmos/cosmos-sdk/blob/main/tools/confix/data/v0.47-app.toml ``` diff --git a/docs/docs/ecosystem/README.md b/docs/docs/ecosystem/README.md deleted file mode 100644 index 7dc06e65cd99..000000000000 --- a/docs/docs/ecosystem/README.md +++ /dev/null @@ -1,33 +0,0 @@ ---- -sidebar_position: 1 ---- - -# Ecosystem - -This section highlights some of the cosmos ecosystem tooling and where to find it. - -## IBC - -See the official [`ibc-go` documentation](https://ibc.cosmos.network). - -## CosmWasm smart contracts - ->CosmWasm is a smart contracting platform built for the Cosmos ecosystem. Simply put, it's the Cosmos (Cosm) way of using WebAssembly (Wasm) hence the name. - ->CosmWasm is written as a module that can plug into the Cosmos SDK. This means that anyone currently building a blockchain using the Cosmos SDK can quickly and easily add CosmWasm smart contracting support to their chain, without adjusting existing logic. - -Read more about writing smart contracts with CosmWasm at their [documentation site](https://book.cosmwasm.com/), or visit [the repository](https://github.com/CosmWasm/cosmwasm). - -## EVM - -Read more about writing smart contracts with solidity at the official [`evm` documentation page](https://docs.evmos.org/modules/evm/). - -## Explore Further - -:::tip -For non Cosmos SDK related tooling, you can have a look at the [Awesome Cosmos](https://github.com/cosmos/awesome-cosmos) GitHub repository. -::: - -:::note -If you would like to add your tooling to this section, please make a [PR to the Cosmos SDK](https://github.com/cosmos/cosmos-sdk/edit/main/docs/docs/ecosystem/README.md). -::: diff --git a/docs/docs/ecosystem/_category_.json b/docs/docs/ecosystem/_category_.json deleted file mode 100644 index 4e6d0facbb25..000000000000 --- a/docs/docs/ecosystem/_category_.json +++ /dev/null @@ -1,5 +0,0 @@ -{ - "label": "Ecosystem", - "position": 8, - "link": null -} \ No newline at end of file diff --git a/docs/docs/migrations/00-intro.md b/docs/docs/migrations/00-intro.md deleted file mode 100644 index 1d363ff41112..000000000000 --- a/docs/docs/migrations/00-intro.md +++ /dev/null @@ -1,11 +0,0 @@ ---- -sidebar_position: 1 ---- - -# Introduction to Migrations - -This document contains all the migration guides to update your app and modules to the current Cosmos SDK. - -1. Chain Upgrade Guide to v0.47: - * See [UPGRADING.md](https://github.com/cosmos/cosmos-sdk/blob/v0.47.0-rc1/UPGRADING.md) for breaking changes and deprecations upgrade instructions. - * See [Release Notes](https://github.com/cosmos/cosmos-sdk/blob/v0.47.0-rc1/RELEASE_NOTES.md) and [changelog](https://github.com/cosmos/cosmos-sdk/blob/v0.47.0-rc1/CHANGELOG.md) for the exhaustive list of API and State Machine breaking changes. diff --git a/docs/docs/migrations/01-intro.md b/docs/docs/migrations/01-intro.md new file mode 100644 index 000000000000..b27b294ea297 --- /dev/null +++ b/docs/docs/migrations/01-intro.md @@ -0,0 +1,15 @@ +--- +sidebar_position: 1 +--- + +# SDK Migrations + +To smoothen the update to the latest stable release, the SDK includes a CLI command for hard-fork migrations (under the ` genesis migrate` subcommand). +Additionally, the SDK includes in-place migrations for its core modules. These in-place migrations are useful to migrate between major releases. + +* Hard-fork migrations are supported from the last major release to the current one. +* In-place module migrations are supported from the last two major releases to the current one. + +Migration from a version older than the last two major releases is not supported. + +When migrating from a previous version, refer to the [`UPGRADING.md`](./02-upgrading.md) and the `CHANGELOG.md` of the version you are migrating to. diff --git a/docs/docs/migrations/_category_.json b/docs/docs/migrations/_category_.json index 5d4562bb6974..add3887b861b 100644 --- a/docs/docs/migrations/_category_.json +++ b/docs/docs/migrations/_category_.json @@ -1,5 +1,5 @@ { - "label": "Migrations", + "label": "SDK Migrations", "position": 6, "link": null } \ No newline at end of file diff --git a/docs/docs/packages/README.md b/docs/docs/packages/README.md new file mode 100644 index 000000000000..ad5e6699cab5 --- /dev/null +++ b/docs/docs/packages/README.md @@ -0,0 +1,39 @@ +--- +sidebar_position: 0 +--- + +# Packages + +The Cosmos SDK is a collection of Go modules. This section provides documentation on various packages that can used when developing a Cosmos SDK chain. +It lists all standalone Go modules that are part of the Cosmos SDK. + +:::tip +For more information on SDK modules, see the [SDK Modules](https://docs.cosmos.network/main/modules) section. +For more information on SDK tooling, see the [Tooling](https://docs.cosmos.network/main/tooling) section. +::: + +## Core + +* [Core](https://pkg.go.dev/cosmossdk.io/core) - Core library defining SDK interfaces ([ADR-063](https://docs.cosmos.network/main/architecture/adr-063-core-module-api)) +* [API](https://pkg.go.dev/cosmossdk.io/api) - API library containing generated SDK Pulsar API +* [Store](https://pkg.go.dev/cosmossdk.io/store) - Implementation of the Cosmos SDK store + +## State Management + +* [Collections](./02-collections.md) - State management library +* [ORM](./03-orm.md) - State management library + +## Automation + +* [Depinject](./01-depinject.md) - Dependency injection framework +* [Client/v2](https://pkg.go.dev/cosmossdk.io/client/v2) - Library powering [AutoCLI](https://docs.cosmos.network/main/building-modules/autocli) + +## Utilities + +* [Log](https://pkg.go.dev/cosmossdk.io/log) - Logging library +* [Errors](https://pkg.go.dev/cosmossdk.io/errors) - Error handling library +* [Math](https://pkg.go.dev/cosmossdk.io/math) - Math library for SDK arithmetic operations + +## Example + +* [SimApp](https://pkg.go.dev/cosmossdk.io/simapp) - SimApp is **the** sample Cosmos SDK chain. This package should not be imported in your application. diff --git a/docs/docs/packages/_category_.json b/docs/docs/packages/_category_.json new file mode 100644 index 000000000000..e91118d38435 --- /dev/null +++ b/docs/docs/packages/_category_.json @@ -0,0 +1,5 @@ +{ + "label": "Packages", + "position": 9, + "link": null +} \ No newline at end of file diff --git a/docs/docs/tooling/README.md b/docs/docs/tooling/README.md index e4f0c3f8ff05..27bc94e24f34 100644 --- a/docs/docs/tooling/README.md +++ b/docs/docs/tooling/README.md @@ -4,10 +4,16 @@ sidebar_position: 0 # Tools -This section provides documentation on various tooling used in development of a Cosmos SDK chain, operating a node and testing. +This section provides documentation on various tooling maintained by the SDK team. +This includes tools for development, operating a node, and ease of use of a Cosmos SDK chain. + +## CLI Tools -* [Protocol Buffers](./00-protobuf.md) * [Cosmovisor](./01-cosmovisor.md) -* [Depinject](./02-depinject.md) -* [Confix](./03-confix.md) -* [Hubl](./04-hubl.md) +* [Confix](./02-confix.md) +* [Hubl](./03-hubl.md) +* [Rosetta](https://docs.cosmos.network/main/run-node/rosetta) + +## Other Tools + +* [Protocol Buffers](./00-protobuf.md) diff --git a/docs/docs/tooling/_category_.json b/docs/docs/tooling/_category_.json index d91e08b5acbf..a01a4fcc48f6 100644 --- a/docs/docs/tooling/_category_.json +++ b/docs/docs/tooling/_category_.json @@ -1,5 +1,5 @@ { "label": "Tooling", - "position": 9, + "position": 10, "link": null } \ No newline at end of file diff --git a/docs/docusaurus.config.js b/docs/docusaurus.config.js index e26cd1d67b76..9d5007d122c5 100644 --- a/docs/docusaurus.config.js +++ b/docs/docusaurus.config.js @@ -385,10 +385,30 @@ const config = { ], to: "/main/modules/upgrade/", }, + { + from: ["/main/modules/capability", "/main/ecosystem"], + to: "/main/modules", + }, + { + from: ["/main/spec/circuit-breaker"], + to: "/main/modules/circuit", + }, + { + from: ["/main/spec/reserve-pool"], + to: "/main/modules/distribution", + }, { from: ["/main/run-node/cosmovisor"], to: "/main/tooling/cosmovisor", }, + { + from: ["/main/migrations/pre-upgrade"], + to: "/main/building-apps/app-upgrade", + }, + { + from: ["/main/tooling/depinject"], + to: "/main/packages/depinject", + }, ], }, ], diff --git a/docs/package-lock.json b/docs/package-lock.json index 18bbf4516828..d206175fe431 100644 --- a/docs/package-lock.json +++ b/docs/package-lock.json @@ -8,23 +8,23 @@ "name": "cosmos-sdk-docs", "version": "0.0.0", "dependencies": { - "@docusaurus/core": "2.3.1", - "@docusaurus/plugin-client-redirects": "^2.3.1", - "@docusaurus/plugin-google-analytics": "^2.3.1", - "@docusaurus/preset-classic": "2.3.1", + "@docusaurus/core": "2.4.0", + "@docusaurus/plugin-client-redirects": "^2.4.0", + "@docusaurus/plugin-google-analytics": "^2.4.0", + "@docusaurus/preset-classic": "2.4.0", "@mdx-js/react": "^1.6.22", "@you54f/theme-github-codeblock": "^0.1.1", "autoprefixer": "^10.4.14", "clsx": "^1.2.1", - "postcss": "^8.4.21", + "postcss": "^8.4.22", "postcss-import": "^15.1.0", "prism-react-renderer": "^1.3.5", "react": "^17.0.2", "react-dom": "^17.0.2", - "tailwindcss": "^3.2.7" + "tailwindcss": "^3.3.1" }, "devDependencies": { - "@docusaurus/module-type-aliases": "2.3.1" + "@docusaurus/module-type-aliases": "2.4.0" } }, "node_modules/@algolia/autocomplete-core": { @@ -53,74 +53,74 @@ "integrity": "sha512-2VGCk7I9tA9Ge73Km99+Qg87w0wzW4tgUruvWAn/gfey1ZXgmxZtyIRBebk35R1O8TbK77wujVtCnpsGpRy1kg==" }, "node_modules/@algolia/cache-browser-local-storage": { - "version": "4.14.3", - "resolved": "https://registry.npmjs.org/@algolia/cache-browser-local-storage/-/cache-browser-local-storage-4.14.3.tgz", - "integrity": "sha512-hWH1yCxgG3+R/xZIscmUrWAIBnmBFHH5j30fY/+aPkEZWt90wYILfAHIOZ1/Wxhho5SkPfwFmT7ooX2d9JeQBw==", + "version": "4.16.0", + "resolved": "https://registry.npmjs.org/@algolia/cache-browser-local-storage/-/cache-browser-local-storage-4.16.0.tgz", + "integrity": "sha512-jVrk0YB3tjOhD5/lhBtYCVCeLjZmVpf2kdi4puApofytf/R0scjWz0GdozlW4HhU+Prxmt/c9ge4QFjtv5OAzQ==", "dependencies": { - "@algolia/cache-common": "4.14.3" + "@algolia/cache-common": "4.16.0" } }, "node_modules/@algolia/cache-common": { - "version": "4.14.3", - "resolved": "https://registry.npmjs.org/@algolia/cache-common/-/cache-common-4.14.3.tgz", - "integrity": "sha512-oZJofOoD9FQOwiGTzyRnmzvh3ZP8WVTNPBLH5xU5JNF7drDbRT0ocVT0h/xB2rPHYzOeXRrLaQQBwRT/CKom0Q==" + "version": "4.16.0", + "resolved": "https://registry.npmjs.org/@algolia/cache-common/-/cache-common-4.16.0.tgz", + "integrity": "sha512-4iHjkSYQYw46pITrNQgXXhvUmcekI8INz1m+SzmqLX8jexSSy4Ky4zfGhZzhhhLHXUP3+x/PK/c0qPjxEvRwKQ==" }, "node_modules/@algolia/cache-in-memory": { - "version": "4.14.3", - "resolved": "https://registry.npmjs.org/@algolia/cache-in-memory/-/cache-in-memory-4.14.3.tgz", - "integrity": "sha512-ES0hHQnzWjeioLQf5Nq+x1AWdZJ50znNPSH3puB/Y4Xsg4Av1bvLmTJe7SY2uqONaeMTvL0OaVcoVtQgJVw0vg==", + "version": "4.16.0", + "resolved": "https://registry.npmjs.org/@algolia/cache-in-memory/-/cache-in-memory-4.16.0.tgz", + "integrity": "sha512-p7RYykvA6Ip6QENxrh99nOD77otVh1sJRivcgcVpnjoZb5sIN3t33eUY1DpB9QSBizcrW+qk19rNkdnZ43a+PQ==", "dependencies": { - "@algolia/cache-common": "4.14.3" + "@algolia/cache-common": "4.16.0" } }, "node_modules/@algolia/client-account": { - "version": "4.14.3", - "resolved": "https://registry.npmjs.org/@algolia/client-account/-/client-account-4.14.3.tgz", - "integrity": "sha512-PBcPb0+f5Xbh5UfLZNx2Ow589OdP8WYjB4CnvupfYBrl9JyC1sdH4jcq/ri8osO/mCZYjZrQsKAPIqW/gQmizQ==", + "version": "4.16.0", + "resolved": "https://registry.npmjs.org/@algolia/client-account/-/client-account-4.16.0.tgz", + "integrity": "sha512-eydcfpdIyuWoKgUSz5iZ/L0wE/Wl7958kACkvTHLDNXvK/b8Z1zypoJavh6/km1ZNQmFpeYS2jrmq0kUSFn02w==", "dependencies": { - "@algolia/client-common": "4.14.3", - "@algolia/client-search": "4.14.3", - "@algolia/transporter": "4.14.3" + "@algolia/client-common": "4.16.0", + "@algolia/client-search": "4.16.0", + "@algolia/transporter": "4.16.0" } }, "node_modules/@algolia/client-analytics": { - "version": "4.14.3", - "resolved": "https://registry.npmjs.org/@algolia/client-analytics/-/client-analytics-4.14.3.tgz", - "integrity": "sha512-eAwQq0Hb/aauv9NhCH5Dp3Nm29oFx28sayFN2fdOWemwSeJHIl7TmcsxVlRsO50fsD8CtPcDhtGeD3AIFLNvqw==", + "version": "4.16.0", + "resolved": "https://registry.npmjs.org/@algolia/client-analytics/-/client-analytics-4.16.0.tgz", + "integrity": "sha512-cONWXH3BfilgdlCofUm492bJRWtpBLVW/hsUlfoFtiX1u05xoBP7qeiDwh9RR+4pSLHLodYkHAf5U4honQ55Qg==", "dependencies": { - "@algolia/client-common": "4.14.3", - "@algolia/client-search": "4.14.3", - "@algolia/requester-common": "4.14.3", - "@algolia/transporter": "4.14.3" + "@algolia/client-common": "4.16.0", + "@algolia/client-search": "4.16.0", + "@algolia/requester-common": "4.16.0", + "@algolia/transporter": "4.16.0" } }, "node_modules/@algolia/client-common": { - "version": "4.14.3", - "resolved": "https://registry.npmjs.org/@algolia/client-common/-/client-common-4.14.3.tgz", - "integrity": "sha512-jkPPDZdi63IK64Yg4WccdCsAP4pHxSkr4usplkUZM5C1l1oEpZXsy2c579LQ0rvwCs5JFmwfNG4ahOszidfWPw==", + "version": "4.16.0", + "resolved": "https://registry.npmjs.org/@algolia/client-common/-/client-common-4.16.0.tgz", + "integrity": "sha512-QVdR4019ukBH6f5lFr27W60trRxQF1SfS1qo0IP6gjsKhXhUVJuHxOCA6ArF87jrNkeuHEoRoDU+GlvaecNo8g==", "dependencies": { - "@algolia/requester-common": "4.14.3", - "@algolia/transporter": "4.14.3" + "@algolia/requester-common": "4.16.0", + "@algolia/transporter": "4.16.0" } }, "node_modules/@algolia/client-personalization": { - "version": "4.14.3", - "resolved": "https://registry.npmjs.org/@algolia/client-personalization/-/client-personalization-4.14.3.tgz", - "integrity": "sha512-UCX1MtkVNgaOL9f0e22x6tC9e2H3unZQlSUdnVaSKpZ+hdSChXGaRjp2UIT7pxmPqNCyv51F597KEX5WT60jNg==", + "version": "4.16.0", + "resolved": "https://registry.npmjs.org/@algolia/client-personalization/-/client-personalization-4.16.0.tgz", + "integrity": "sha512-irtLafssDGPuhYqIwxqOxiWlVYvrsBD+EMA1P9VJtkKi3vSNBxiWeQ0f0Tn53cUNdSRNEssfoEH84JL97SV2SQ==", "dependencies": { - "@algolia/client-common": "4.14.3", - "@algolia/requester-common": "4.14.3", - "@algolia/transporter": "4.14.3" + "@algolia/client-common": "4.16.0", + "@algolia/requester-common": "4.16.0", + "@algolia/transporter": "4.16.0" } }, "node_modules/@algolia/client-search": { - "version": "4.14.3", - "resolved": "https://registry.npmjs.org/@algolia/client-search/-/client-search-4.14.3.tgz", - "integrity": "sha512-I2U7xBx5OPFdPLA8AXKUPPxGY3HDxZ4r7+mlZ8ZpLbI8/ri6fnu6B4z3wcL7sgHhDYMwnAE8Xr0AB0h3Hnkp4A==", + "version": "4.16.0", + "resolved": "https://registry.npmjs.org/@algolia/client-search/-/client-search-4.16.0.tgz", + "integrity": "sha512-xsfrAE1jO/JDh1wFrRz+alVyW+aA6qnkzmbWWWZWEgVF3EaFqzIf9r1l/aDtDdBtNTNhX9H3Lg31+BRtd5izQA==", "dependencies": { - "@algolia/client-common": "4.14.3", - "@algolia/requester-common": "4.14.3", - "@algolia/transporter": "4.14.3" + "@algolia/client-common": "4.16.0", + "@algolia/requester-common": "4.16.0", + "@algolia/transporter": "4.16.0" } }, "node_modules/@algolia/events": { @@ -129,47 +129,47 @@ "integrity": "sha512-FQzvOCgoFXAbf5Y6mYozw2aj5KCJoA3m4heImceldzPSMbdyS4atVjJzXKMsfX3wnZTFYwkkt8/z8UesLHlSBQ==" }, "node_modules/@algolia/logger-common": { - "version": "4.14.3", - "resolved": "https://registry.npmjs.org/@algolia/logger-common/-/logger-common-4.14.3.tgz", - "integrity": "sha512-kUEAZaBt/J3RjYi8MEBT2QEexJR2kAE2mtLmezsmqMQZTV502TkHCxYzTwY2dE7OKcUTxi4OFlMuS4GId9CWPw==" + "version": "4.16.0", + "resolved": "https://registry.npmjs.org/@algolia/logger-common/-/logger-common-4.16.0.tgz", + "integrity": "sha512-U9H8uCzSDuePJmbnjjTX21aPDRU6x74Tdq3dJmdYu2+pISx02UeBJm4kSgc9RW5jcR5j35G9gnjHY9Q3ngWbyQ==" }, "node_modules/@algolia/logger-console": { - "version": "4.14.3", - "resolved": "https://registry.npmjs.org/@algolia/logger-console/-/logger-console-4.14.3.tgz", - "integrity": "sha512-ZWqAlUITktiMN2EiFpQIFCJS10N96A++yrexqC2Z+3hgF/JcKrOxOdT4nSCQoEPvU4Ki9QKbpzbebRDemZt/hw==", + "version": "4.16.0", + "resolved": "https://registry.npmjs.org/@algolia/logger-console/-/logger-console-4.16.0.tgz", + "integrity": "sha512-+qymusiM+lPZKrkf0tDjCQA158eEJO2IU+Nr/sJ9TFyI/xkFPjNPzw/Qbc8Iy/xcOXGlc6eMgmyjtVQqAWq6UA==", "dependencies": { - "@algolia/logger-common": "4.14.3" + "@algolia/logger-common": "4.16.0" } }, "node_modules/@algolia/requester-browser-xhr": { - "version": "4.14.3", - "resolved": "https://registry.npmjs.org/@algolia/requester-browser-xhr/-/requester-browser-xhr-4.14.3.tgz", - "integrity": "sha512-AZeg2T08WLUPvDncl2XLX2O67W5wIO8MNaT7z5ii5LgBTuk/rU4CikTjCe2xsUleIZeFl++QrPAi4Bdxws6r/Q==", + "version": "4.16.0", + "resolved": "https://registry.npmjs.org/@algolia/requester-browser-xhr/-/requester-browser-xhr-4.16.0.tgz", + "integrity": "sha512-gK+kvs6LHl/PaOJfDuwjkopNbG1djzFLsVBklGBsSU6h6VjFkxIpo6Qq80IK14p9cplYZfhfaL12va6Q9p3KVQ==", "dependencies": { - "@algolia/requester-common": "4.14.3" + "@algolia/requester-common": "4.16.0" } }, "node_modules/@algolia/requester-common": { - "version": "4.14.3", - "resolved": "https://registry.npmjs.org/@algolia/requester-common/-/requester-common-4.14.3.tgz", - "integrity": "sha512-RrRzqNyKFDP7IkTuV3XvYGF9cDPn9h6qEDl595lXva3YUk9YSS8+MGZnnkOMHvjkrSCKfoLeLbm/T4tmoIeclw==" + "version": "4.16.0", + "resolved": "https://registry.npmjs.org/@algolia/requester-common/-/requester-common-4.16.0.tgz", + "integrity": "sha512-3Zmcs/iMubcm4zqZ3vZG6Zum8t+hMWxGMzo0/uY2BD8o9q5vMxIYI0c4ocdgQjkXcix189WtZNkgjSOBzSbkdw==" }, "node_modules/@algolia/requester-node-http": { - "version": "4.14.3", - "resolved": "https://registry.npmjs.org/@algolia/requester-node-http/-/requester-node-http-4.14.3.tgz", - "integrity": "sha512-O5wnPxtDRPuW2U0EaOz9rMMWdlhwP0J0eSL1Z7TtXF8xnUeeUyNJrdhV5uy2CAp6RbhM1VuC3sOJcIR6Av+vbA==", + "version": "4.16.0", + "resolved": "https://registry.npmjs.org/@algolia/requester-node-http/-/requester-node-http-4.16.0.tgz", + "integrity": "sha512-L8JxM2VwZzh8LJ1Zb8TFS6G3icYsCKZsdWW+ahcEs1rGWmyk9SybsOe1MLnjonGBaqPWJkn9NjS7mRdjEmBtKA==", "dependencies": { - "@algolia/requester-common": "4.14.3" + "@algolia/requester-common": "4.16.0" } }, "node_modules/@algolia/transporter": { - "version": "4.14.3", - "resolved": "https://registry.npmjs.org/@algolia/transporter/-/transporter-4.14.3.tgz", - "integrity": "sha512-2qlKlKsnGJ008exFRb5RTeTOqhLZj0bkMCMVskxoqWejs2Q2QtWmsiH98hDfpw0fmnyhzHEt0Z7lqxBYp8bW2w==", + "version": "4.16.0", + "resolved": "https://registry.npmjs.org/@algolia/transporter/-/transporter-4.16.0.tgz", + "integrity": "sha512-H9BVB2EAjT65w7XGBNf5drpsW39x2aSZ942j4boSAAJPPlLmjtj5IpAP7UAtsV8g9Beslonh0bLa1XGmE/P0BA==", "dependencies": { - "@algolia/cache-common": "4.14.3", - "@algolia/logger-common": "4.14.3", - "@algolia/requester-common": "4.14.3" + "@algolia/cache-common": "4.16.0", + "@algolia/logger-common": "4.16.0", + "@algolia/requester-common": "4.16.0" } }, "node_modules/@ampproject/remapping": { @@ -1889,11 +1889,11 @@ } }, "node_modules/@babel/runtime": { - "version": "7.19.4", - "resolved": "https://registry.npmjs.org/@babel/runtime/-/runtime-7.19.4.tgz", - "integrity": "sha512-EXpLCrk55f+cYqmHsSR+yD/0gAIMxxA9QK9lnQWzhMCvt+YmoBN7Zx94s++Kv0+unHk39vxNO8t+CMA2WSS3wA==", + "version": "7.21.0", + "resolved": "https://registry.npmjs.org/@babel/runtime/-/runtime-7.21.0.tgz", + "integrity": "sha512-xwII0//EObnq89Ji5AKYQaRYiW/nZ3llSv29d49IuxPhKbtJoLP+9QUUZ4nVragQVtaVGeZrpB+ZtG/Pdy/POw==", "dependencies": { - "regenerator-runtime": "^0.13.4" + "regenerator-runtime": "^0.13.11" }, "engines": { "node": ">=6.9.0" @@ -1999,9 +1999,9 @@ } }, "node_modules/@docusaurus/core": { - "version": "2.3.1", - "resolved": "https://registry.npmjs.org/@docusaurus/core/-/core-2.3.1.tgz", - "integrity": "sha512-0Jd4jtizqnRAr7svWaBbbrCCN8mzBNd2xFLoT/IM7bGfFie5y58oz97KzXliwiLY3zWjqMXjQcuP1a5VgCv2JA==", + "version": "2.4.0", + "resolved": "https://registry.npmjs.org/@docusaurus/core/-/core-2.4.0.tgz", + "integrity": "sha512-J55/WEoIpRcLf3afO5POHPguVZosKmJEQWKBL+K7TAnfuE7i+Y0NPLlkKtnWCehagGsgTqClfQEexH/UT4kELA==", "dependencies": { "@babel/core": "^7.18.6", "@babel/generator": "^7.18.7", @@ -2013,13 +2013,13 @@ "@babel/runtime": "^7.18.6", "@babel/runtime-corejs3": "^7.18.6", "@babel/traverse": "^7.18.8", - "@docusaurus/cssnano-preset": "2.3.1", - "@docusaurus/logger": "2.3.1", - "@docusaurus/mdx-loader": "2.3.1", + "@docusaurus/cssnano-preset": "2.4.0", + "@docusaurus/logger": "2.4.0", + "@docusaurus/mdx-loader": "2.4.0", "@docusaurus/react-loadable": "5.5.2", - "@docusaurus/utils": "2.3.1", - "@docusaurus/utils-common": "2.3.1", - "@docusaurus/utils-validation": "2.3.1", + "@docusaurus/utils": "2.4.0", + "@docusaurus/utils-common": "2.4.0", + "@docusaurus/utils-validation": "2.4.0", "@slorber/static-site-generator-webpack-plugin": "^4.0.7", "@svgr/webpack": "^6.2.1", "autoprefixer": "^10.4.7", @@ -2087,9 +2087,9 @@ } }, "node_modules/@docusaurus/cssnano-preset": { - "version": "2.3.1", - "resolved": "https://registry.npmjs.org/@docusaurus/cssnano-preset/-/cssnano-preset-2.3.1.tgz", - "integrity": "sha512-7mIhAROES6CY1GmCjR4CZkUfjTL6B3u6rKHK0ChQl2d1IevYXq/k/vFgvOrJfcKxiObpMnE9+X6R2Wt1KqxC6w==", + "version": "2.4.0", + "resolved": "https://registry.npmjs.org/@docusaurus/cssnano-preset/-/cssnano-preset-2.4.0.tgz", + "integrity": "sha512-RmdiA3IpsLgZGXRzqnmTbGv43W4OD44PCo+6Q/aYjEM2V57vKCVqNzuafE94jv0z/PjHoXUrjr69SaRymBKYYw==", "dependencies": { "cssnano-preset-advanced": "^5.3.8", "postcss": "^8.4.14", @@ -2101,9 +2101,9 @@ } }, "node_modules/@docusaurus/logger": { - "version": "2.3.1", - "resolved": "https://registry.npmjs.org/@docusaurus/logger/-/logger-2.3.1.tgz", - "integrity": "sha512-2lAV/olKKVr9qJhfHFCaqBIl8FgYjbUFwgUnX76+cULwQYss+42ZQ3grHGFvI0ocN2X55WcYe64ellQXz7suqg==", + "version": "2.4.0", + "resolved": "https://registry.npmjs.org/@docusaurus/logger/-/logger-2.4.0.tgz", + "integrity": "sha512-T8+qR4APN+MjcC9yL2Es+xPJ2923S9hpzDmMtdsOcUGLqpCGBbU1vp3AAqDwXtVgFkq+NsEk7sHdVsfLWR/AXw==", "dependencies": { "chalk": "^4.1.2", "tslib": "^2.4.0" @@ -2113,14 +2113,14 @@ } }, "node_modules/@docusaurus/mdx-loader": { - "version": "2.3.1", - "resolved": "https://registry.npmjs.org/@docusaurus/mdx-loader/-/mdx-loader-2.3.1.tgz", - "integrity": "sha512-Gzga7OsxQRpt3392K9lv/bW4jGppdLFJh3luKRknCKSAaZrmVkOQv2gvCn8LAOSZ3uRg5No7AgYs/vpL8K94lA==", + "version": "2.4.0", + "resolved": "https://registry.npmjs.org/@docusaurus/mdx-loader/-/mdx-loader-2.4.0.tgz", + "integrity": "sha512-GWoH4izZKOmFoC+gbI2/y8deH/xKLvzz/T5BsEexBye8EHQlwsA7FMrVa48N063bJBH4FUOiRRXxk5rq9cC36g==", "dependencies": { "@babel/parser": "^7.18.8", "@babel/traverse": "^7.18.8", - "@docusaurus/logger": "2.3.1", - "@docusaurus/utils": "2.3.1", + "@docusaurus/logger": "2.4.0", + "@docusaurus/utils": "2.4.0", "@mdx-js/mdx": "^1.6.22", "escape-html": "^1.0.3", "file-loader": "^6.2.0", @@ -2144,12 +2144,12 @@ } }, "node_modules/@docusaurus/module-type-aliases": { - "version": "2.3.1", - "resolved": "https://registry.npmjs.org/@docusaurus/module-type-aliases/-/module-type-aliases-2.3.1.tgz", - "integrity": "sha512-6KkxfAVOJqIUynTRb/tphYCl+co3cP0PlHiMDbi+SzmYxMdgIrwYqH9yAnGSDoN6Jk2ZE/JY/Azs/8LPgKP48A==", + "version": "2.4.0", + "resolved": "https://registry.npmjs.org/@docusaurus/module-type-aliases/-/module-type-aliases-2.4.0.tgz", + "integrity": "sha512-YEQO2D3UXs72qCn8Cr+RlycSQXVGN9iEUyuHwTuK4/uL/HFomB2FHSU0vSDM23oLd+X/KibQ3Ez6nGjQLqXcHg==", "dependencies": { "@docusaurus/react-loadable": "5.5.2", - "@docusaurus/types": "2.3.1", + "@docusaurus/types": "2.4.0", "@types/history": "^4.7.11", "@types/react": "*", "@types/react-router-config": "*", @@ -2163,15 +2163,15 @@ } }, "node_modules/@docusaurus/plugin-client-redirects": { - "version": "2.3.1", - "resolved": "https://registry.npmjs.org/@docusaurus/plugin-client-redirects/-/plugin-client-redirects-2.3.1.tgz", - "integrity": "sha512-Ye0z36/L8685ni0DIxHqPPaHIXFXiSF90QYiYfpODBX6NxvvveUTyylsDBU1GQhPXPn1bd39QgaOuZ+j9gfaog==", - "dependencies": { - "@docusaurus/core": "2.3.1", - "@docusaurus/logger": "2.3.1", - "@docusaurus/utils": "2.3.1", - "@docusaurus/utils-common": "2.3.1", - "@docusaurus/utils-validation": "2.3.1", + "version": "2.4.0", + "resolved": "https://registry.npmjs.org/@docusaurus/plugin-client-redirects/-/plugin-client-redirects-2.4.0.tgz", + "integrity": "sha512-HsS+Dc2ZLWhfpjYJ5LIrOB/XfXZcElcC7o1iA4yIVtiFz+LHhwP863fhqbwSJ1c6tNDOYBH3HwbskHrc/PIn7Q==", + "dependencies": { + "@docusaurus/core": "2.4.0", + "@docusaurus/logger": "2.4.0", + "@docusaurus/utils": "2.4.0", + "@docusaurus/utils-common": "2.4.0", + "@docusaurus/utils-validation": "2.4.0", "eta": "^2.0.0", "fs-extra": "^10.1.0", "lodash": "^4.17.21", @@ -2186,17 +2186,17 @@ } }, "node_modules/@docusaurus/plugin-content-blog": { - "version": "2.3.1", - "resolved": "https://registry.npmjs.org/@docusaurus/plugin-content-blog/-/plugin-content-blog-2.3.1.tgz", - "integrity": "sha512-f5LjqX+9WkiLyGiQ41x/KGSJ/9bOjSD8lsVhPvYeUYHCtYpuiDKfhZE07O4EqpHkBx4NQdtQDbp+aptgHSTuiw==", - "dependencies": { - "@docusaurus/core": "2.3.1", - "@docusaurus/logger": "2.3.1", - "@docusaurus/mdx-loader": "2.3.1", - "@docusaurus/types": "2.3.1", - "@docusaurus/utils": "2.3.1", - "@docusaurus/utils-common": "2.3.1", - "@docusaurus/utils-validation": "2.3.1", + "version": "2.4.0", + "resolved": "https://registry.npmjs.org/@docusaurus/plugin-content-blog/-/plugin-content-blog-2.4.0.tgz", + "integrity": "sha512-YwkAkVUxtxoBAIj/MCb4ohN0SCtHBs4AS75jMhPpf67qf3j+U/4n33cELq7567hwyZ6fMz2GPJcVmctzlGGThQ==", + "dependencies": { + "@docusaurus/core": "2.4.0", + "@docusaurus/logger": "2.4.0", + "@docusaurus/mdx-loader": "2.4.0", + "@docusaurus/types": "2.4.0", + "@docusaurus/utils": "2.4.0", + "@docusaurus/utils-common": "2.4.0", + "@docusaurus/utils-validation": "2.4.0", "cheerio": "^1.0.0-rc.12", "feed": "^4.2.2", "fs-extra": "^10.1.0", @@ -2216,17 +2216,17 @@ } }, "node_modules/@docusaurus/plugin-content-docs": { - "version": "2.3.1", - "resolved": "https://registry.npmjs.org/@docusaurus/plugin-content-docs/-/plugin-content-docs-2.3.1.tgz", - "integrity": "sha512-DxztTOBEruv7qFxqUtbsqXeNcHqcVEIEe+NQoI1oi2DBmKBhW/o0MIal8lt+9gvmpx3oYtlwmLOOGepxZgJGkw==", - "dependencies": { - "@docusaurus/core": "2.3.1", - "@docusaurus/logger": "2.3.1", - "@docusaurus/mdx-loader": "2.3.1", - "@docusaurus/module-type-aliases": "2.3.1", - "@docusaurus/types": "2.3.1", - "@docusaurus/utils": "2.3.1", - "@docusaurus/utils-validation": "2.3.1", + "version": "2.4.0", + "resolved": "https://registry.npmjs.org/@docusaurus/plugin-content-docs/-/plugin-content-docs-2.4.0.tgz", + "integrity": "sha512-ic/Z/ZN5Rk/RQo+Io6rUGpToOtNbtPloMR2JcGwC1xT2riMu6zzfSwmBi9tHJgdXH6CB5jG+0dOZZO8QS5tmDg==", + "dependencies": { + "@docusaurus/core": "2.4.0", + "@docusaurus/logger": "2.4.0", + "@docusaurus/mdx-loader": "2.4.0", + "@docusaurus/module-type-aliases": "2.4.0", + "@docusaurus/types": "2.4.0", + "@docusaurus/utils": "2.4.0", + "@docusaurus/utils-validation": "2.4.0", "@types/react-router-config": "^5.0.6", "combine-promises": "^1.1.0", "fs-extra": "^10.1.0", @@ -2246,15 +2246,15 @@ } }, "node_modules/@docusaurus/plugin-content-pages": { - "version": "2.3.1", - "resolved": "https://registry.npmjs.org/@docusaurus/plugin-content-pages/-/plugin-content-pages-2.3.1.tgz", - "integrity": "sha512-E80UL6hvKm5VVw8Ka8YaVDtO6kWWDVUK4fffGvkpQ/AJQDOg99LwOXKujPoICC22nUFTsZ2Hp70XvpezCsFQaA==", - "dependencies": { - "@docusaurus/core": "2.3.1", - "@docusaurus/mdx-loader": "2.3.1", - "@docusaurus/types": "2.3.1", - "@docusaurus/utils": "2.3.1", - "@docusaurus/utils-validation": "2.3.1", + "version": "2.4.0", + "resolved": "https://registry.npmjs.org/@docusaurus/plugin-content-pages/-/plugin-content-pages-2.4.0.tgz", + "integrity": "sha512-Pk2pOeOxk8MeU3mrTU0XLIgP9NZixbdcJmJ7RUFrZp1Aj42nd0RhIT14BGvXXyqb8yTQlk4DmYGAzqOfBsFyGw==", + "dependencies": { + "@docusaurus/core": "2.4.0", + "@docusaurus/mdx-loader": "2.4.0", + "@docusaurus/types": "2.4.0", + "@docusaurus/utils": "2.4.0", + "@docusaurus/utils-validation": "2.4.0", "fs-extra": "^10.1.0", "tslib": "^2.4.0", "webpack": "^5.73.0" @@ -2268,13 +2268,13 @@ } }, "node_modules/@docusaurus/plugin-debug": { - "version": "2.3.1", - "resolved": "https://registry.npmjs.org/@docusaurus/plugin-debug/-/plugin-debug-2.3.1.tgz", - "integrity": "sha512-Ujpml1Ppg4geB/2hyu2diWnO49az9U2bxM9Shen7b6qVcyFisNJTkVG2ocvLC7wM1efTJcUhBO6zAku2vKJGMw==", + "version": "2.4.0", + "resolved": "https://registry.npmjs.org/@docusaurus/plugin-debug/-/plugin-debug-2.4.0.tgz", + "integrity": "sha512-KC56DdYjYT7Txyux71vXHXGYZuP6yYtqwClvYpjKreWIHWus5Zt6VNi23rMZv3/QKhOCrN64zplUbdfQMvddBQ==", "dependencies": { - "@docusaurus/core": "2.3.1", - "@docusaurus/types": "2.3.1", - "@docusaurus/utils": "2.3.1", + "@docusaurus/core": "2.4.0", + "@docusaurus/types": "2.4.0", + "@docusaurus/utils": "2.4.0", "fs-extra": "^10.1.0", "react-json-view": "^1.21.3", "tslib": "^2.4.0" @@ -2288,13 +2288,13 @@ } }, "node_modules/@docusaurus/plugin-google-analytics": { - "version": "2.3.1", - "resolved": "https://registry.npmjs.org/@docusaurus/plugin-google-analytics/-/plugin-google-analytics-2.3.1.tgz", - "integrity": "sha512-OHip0GQxKOFU8n7gkt3TM4HOYTXPCFDjqKbMClDD3KaDnyTuMp/Zvd9HSr770lLEscgPWIvzhJByRAClqsUWiQ==", + "version": "2.4.0", + "resolved": "https://registry.npmjs.org/@docusaurus/plugin-google-analytics/-/plugin-google-analytics-2.4.0.tgz", + "integrity": "sha512-uGUzX67DOAIglygdNrmMOvEp8qG03X20jMWadeqVQktS6nADvozpSLGx4J0xbkblhJkUzN21WiilsP9iVP+zkw==", "dependencies": { - "@docusaurus/core": "2.3.1", - "@docusaurus/types": "2.3.1", - "@docusaurus/utils-validation": "2.3.1", + "@docusaurus/core": "2.4.0", + "@docusaurus/types": "2.4.0", + "@docusaurus/utils-validation": "2.4.0", "tslib": "^2.4.0" }, "engines": { @@ -2306,13 +2306,13 @@ } }, "node_modules/@docusaurus/plugin-google-gtag": { - "version": "2.3.1", - "resolved": "https://registry.npmjs.org/@docusaurus/plugin-google-gtag/-/plugin-google-gtag-2.3.1.tgz", - "integrity": "sha512-uXtDhfu4+Hm+oqWUySr3DNI5cWC/rmP6XJyAk83Heor3dFjZqDwCbkX8yWPywkRiWev3Dk/rVF8lEn0vIGVocA==", + "version": "2.4.0", + "resolved": "https://registry.npmjs.org/@docusaurus/plugin-google-gtag/-/plugin-google-gtag-2.4.0.tgz", + "integrity": "sha512-adj/70DANaQs2+TF/nRdMezDXFAV/O/pjAbUgmKBlyOTq5qoMe0Tk4muvQIwWUmiUQxFJe+sKlZGM771ownyOg==", "dependencies": { - "@docusaurus/core": "2.3.1", - "@docusaurus/types": "2.3.1", - "@docusaurus/utils-validation": "2.3.1", + "@docusaurus/core": "2.4.0", + "@docusaurus/types": "2.4.0", + "@docusaurus/utils-validation": "2.4.0", "tslib": "^2.4.0" }, "engines": { @@ -2324,13 +2324,13 @@ } }, "node_modules/@docusaurus/plugin-google-tag-manager": { - "version": "2.3.1", - "resolved": "https://registry.npmjs.org/@docusaurus/plugin-google-tag-manager/-/plugin-google-tag-manager-2.3.1.tgz", - "integrity": "sha512-Ww2BPEYSqg8q8tJdLYPFFM3FMDBCVhEM4UUqKzJaiRMx3NEoly3qqDRAoRDGdIhlC//Rf0iJV9cWAoq2m6k3sw==", + "version": "2.4.0", + "resolved": "https://registry.npmjs.org/@docusaurus/plugin-google-tag-manager/-/plugin-google-tag-manager-2.4.0.tgz", + "integrity": "sha512-E66uGcYs4l7yitmp/8kMEVQftFPwV9iC62ORh47Veqzs6ExwnhzBkJmwDnwIysHBF1vlxnzET0Fl2LfL5fRR3A==", "dependencies": { - "@docusaurus/core": "2.3.1", - "@docusaurus/types": "2.3.1", - "@docusaurus/utils-validation": "2.3.1", + "@docusaurus/core": "2.4.0", + "@docusaurus/types": "2.4.0", + "@docusaurus/utils-validation": "2.4.0", "tslib": "^2.4.0" }, "engines": { @@ -2342,16 +2342,16 @@ } }, "node_modules/@docusaurus/plugin-sitemap": { - "version": "2.3.1", - "resolved": "https://registry.npmjs.org/@docusaurus/plugin-sitemap/-/plugin-sitemap-2.3.1.tgz", - "integrity": "sha512-8Yxile/v6QGYV9vgFiYL+8d2N4z4Er3pSHsrD08c5XI8bUXxTppMwjarDUTH/TRTfgAWotRbhJ6WZLyajLpozA==", - "dependencies": { - "@docusaurus/core": "2.3.1", - "@docusaurus/logger": "2.3.1", - "@docusaurus/types": "2.3.1", - "@docusaurus/utils": "2.3.1", - "@docusaurus/utils-common": "2.3.1", - "@docusaurus/utils-validation": "2.3.1", + "version": "2.4.0", + "resolved": "https://registry.npmjs.org/@docusaurus/plugin-sitemap/-/plugin-sitemap-2.4.0.tgz", + "integrity": "sha512-pZxh+ygfnI657sN8a/FkYVIAmVv0CGk71QMKqJBOfMmDHNN1FeDeFkBjWP49ejBqpqAhjufkv5UWq3UOu2soCw==", + "dependencies": { + "@docusaurus/core": "2.4.0", + "@docusaurus/logger": "2.4.0", + "@docusaurus/types": "2.4.0", + "@docusaurus/utils": "2.4.0", + "@docusaurus/utils-common": "2.4.0", + "@docusaurus/utils-validation": "2.4.0", "fs-extra": "^10.1.0", "sitemap": "^7.1.1", "tslib": "^2.4.0" @@ -2365,23 +2365,23 @@ } }, "node_modules/@docusaurus/preset-classic": { - "version": "2.3.1", - "resolved": "https://registry.npmjs.org/@docusaurus/preset-classic/-/preset-classic-2.3.1.tgz", - "integrity": "sha512-OQ5W0AHyfdUk0IldwJ3BlnZ1EqoJuu2L2BMhqLbqwNWdkmzmSUvlFLH1Pe7CZSQgB2YUUC/DnmjbPKk/qQD0lQ==", - "dependencies": { - "@docusaurus/core": "2.3.1", - "@docusaurus/plugin-content-blog": "2.3.1", - "@docusaurus/plugin-content-docs": "2.3.1", - "@docusaurus/plugin-content-pages": "2.3.1", - "@docusaurus/plugin-debug": "2.3.1", - "@docusaurus/plugin-google-analytics": "2.3.1", - "@docusaurus/plugin-google-gtag": "2.3.1", - "@docusaurus/plugin-google-tag-manager": "2.3.1", - "@docusaurus/plugin-sitemap": "2.3.1", - "@docusaurus/theme-classic": "2.3.1", - "@docusaurus/theme-common": "2.3.1", - "@docusaurus/theme-search-algolia": "2.3.1", - "@docusaurus/types": "2.3.1" + "version": "2.4.0", + "resolved": "https://registry.npmjs.org/@docusaurus/preset-classic/-/preset-classic-2.4.0.tgz", + "integrity": "sha512-/5z5o/9bc6+P5ool2y01PbJhoGddEGsC0ej1MF6mCoazk8A+kW4feoUd68l7Bnv01rCnG3xy7kHUQP97Y0grUA==", + "dependencies": { + "@docusaurus/core": "2.4.0", + "@docusaurus/plugin-content-blog": "2.4.0", + "@docusaurus/plugin-content-docs": "2.4.0", + "@docusaurus/plugin-content-pages": "2.4.0", + "@docusaurus/plugin-debug": "2.4.0", + "@docusaurus/plugin-google-analytics": "2.4.0", + "@docusaurus/plugin-google-gtag": "2.4.0", + "@docusaurus/plugin-google-tag-manager": "2.4.0", + "@docusaurus/plugin-sitemap": "2.4.0", + "@docusaurus/theme-classic": "2.4.0", + "@docusaurus/theme-common": "2.4.0", + "@docusaurus/theme-search-algolia": "2.4.0", + "@docusaurus/types": "2.4.0" }, "engines": { "node": ">=16.14" @@ -2404,26 +2404,26 @@ } }, "node_modules/@docusaurus/theme-classic": { - "version": "2.3.1", - "resolved": "https://registry.npmjs.org/@docusaurus/theme-classic/-/theme-classic-2.3.1.tgz", - "integrity": "sha512-SelSIDvyttb7ZYHj8vEUhqykhAqfOPKk+uP0z85jH72IMC58e7O8DIlcAeBv+CWsLbNIl9/Hcg71X0jazuxJug==", - "dependencies": { - "@docusaurus/core": "2.3.1", - "@docusaurus/mdx-loader": "2.3.1", - "@docusaurus/module-type-aliases": "2.3.1", - "@docusaurus/plugin-content-blog": "2.3.1", - "@docusaurus/plugin-content-docs": "2.3.1", - "@docusaurus/plugin-content-pages": "2.3.1", - "@docusaurus/theme-common": "2.3.1", - "@docusaurus/theme-translations": "2.3.1", - "@docusaurus/types": "2.3.1", - "@docusaurus/utils": "2.3.1", - "@docusaurus/utils-common": "2.3.1", - "@docusaurus/utils-validation": "2.3.1", + "version": "2.4.0", + "resolved": "https://registry.npmjs.org/@docusaurus/theme-classic/-/theme-classic-2.4.0.tgz", + "integrity": "sha512-GMDX5WU6Z0OC65eQFgl3iNNEbI9IMJz9f6KnOyuMxNUR6q0qVLsKCNopFUDfFNJ55UU50o7P7o21yVhkwpfJ9w==", + "dependencies": { + "@docusaurus/core": "2.4.0", + "@docusaurus/mdx-loader": "2.4.0", + "@docusaurus/module-type-aliases": "2.4.0", + "@docusaurus/plugin-content-blog": "2.4.0", + "@docusaurus/plugin-content-docs": "2.4.0", + "@docusaurus/plugin-content-pages": "2.4.0", + "@docusaurus/theme-common": "2.4.0", + "@docusaurus/theme-translations": "2.4.0", + "@docusaurus/types": "2.4.0", + "@docusaurus/utils": "2.4.0", + "@docusaurus/utils-common": "2.4.0", + "@docusaurus/utils-validation": "2.4.0", "@mdx-js/react": "^1.6.22", "clsx": "^1.2.1", "copy-text-to-clipboard": "^3.0.1", - "infima": "0.2.0-alpha.42", + "infima": "0.2.0-alpha.43", "lodash": "^4.17.21", "nprogress": "^0.2.0", "postcss": "^8.4.14", @@ -2443,16 +2443,17 @@ } }, "node_modules/@docusaurus/theme-common": { - "version": "2.3.1", - "resolved": "https://registry.npmjs.org/@docusaurus/theme-common/-/theme-common-2.3.1.tgz", - "integrity": "sha512-RYmYl2OR2biO+yhmW1aS5FyEvnrItPINa+0U2dMxcHpah8reSCjQ9eJGRmAgkZFchV1+aIQzXOI1K7LCW38O0g==", - "dependencies": { - "@docusaurus/mdx-loader": "2.3.1", - "@docusaurus/module-type-aliases": "2.3.1", - "@docusaurus/plugin-content-blog": "2.3.1", - "@docusaurus/plugin-content-docs": "2.3.1", - "@docusaurus/plugin-content-pages": "2.3.1", - "@docusaurus/utils": "2.3.1", + "version": "2.4.0", + "resolved": "https://registry.npmjs.org/@docusaurus/theme-common/-/theme-common-2.4.0.tgz", + "integrity": "sha512-IkG/l5f/FLY6cBIxtPmFnxpuPzc5TupuqlOx+XDN+035MdQcAh8wHXXZJAkTeYDeZ3anIUSUIvWa7/nRKoQEfg==", + "dependencies": { + "@docusaurus/mdx-loader": "2.4.0", + "@docusaurus/module-type-aliases": "2.4.0", + "@docusaurus/plugin-content-blog": "2.4.0", + "@docusaurus/plugin-content-docs": "2.4.0", + "@docusaurus/plugin-content-pages": "2.4.0", + "@docusaurus/utils": "2.4.0", + "@docusaurus/utils-common": "2.4.0", "@types/history": "^4.7.11", "@types/react": "*", "@types/react-router-config": "*", @@ -2472,18 +2473,18 @@ } }, "node_modules/@docusaurus/theme-search-algolia": { - "version": "2.3.1", - "resolved": "https://registry.npmjs.org/@docusaurus/theme-search-algolia/-/theme-search-algolia-2.3.1.tgz", - "integrity": "sha512-JdHaRqRuH1X++g5fEMLnq7OtULSGQdrs9AbhcWRQ428ZB8/HOiaN6mj3hzHvcD3DFgu7koIVtWPQnvnN7iwzHA==", + "version": "2.4.0", + "resolved": "https://registry.npmjs.org/@docusaurus/theme-search-algolia/-/theme-search-algolia-2.4.0.tgz", + "integrity": "sha512-pPCJSCL1Qt4pu/Z0uxBAuke0yEBbxh0s4fOvimna7TEcBLPq0x06/K78AaABXrTVQM6S0vdocFl9EoNgU17hqA==", "dependencies": { "@docsearch/react": "^3.1.1", - "@docusaurus/core": "2.3.1", - "@docusaurus/logger": "2.3.1", - "@docusaurus/plugin-content-docs": "2.3.1", - "@docusaurus/theme-common": "2.3.1", - "@docusaurus/theme-translations": "2.3.1", - "@docusaurus/utils": "2.3.1", - "@docusaurus/utils-validation": "2.3.1", + "@docusaurus/core": "2.4.0", + "@docusaurus/logger": "2.4.0", + "@docusaurus/plugin-content-docs": "2.4.0", + "@docusaurus/theme-common": "2.4.0", + "@docusaurus/theme-translations": "2.4.0", + "@docusaurus/utils": "2.4.0", + "@docusaurus/utils-validation": "2.4.0", "algoliasearch": "^4.13.1", "algoliasearch-helper": "^3.10.0", "clsx": "^1.2.1", @@ -2502,9 +2503,9 @@ } }, "node_modules/@docusaurus/theme-translations": { - "version": "2.3.1", - "resolved": "https://registry.npmjs.org/@docusaurus/theme-translations/-/theme-translations-2.3.1.tgz", - "integrity": "sha512-BsBZzAewJabVhoGG1Ij2u4pMS3MPW6gZ6sS4pc+Y7czevRpzxoFNJXRtQDVGe7mOpv/MmRmqg4owDK+lcOTCVQ==", + "version": "2.4.0", + "resolved": "https://registry.npmjs.org/@docusaurus/theme-translations/-/theme-translations-2.4.0.tgz", + "integrity": "sha512-kEoITnPXzDPUMBHk3+fzEzbopxLD3fR5sDoayNH0vXkpUukA88/aDL1bqkhxWZHA3LOfJ3f0vJbOwmnXW5v85Q==", "dependencies": { "fs-extra": "^10.1.0", "tslib": "^2.4.0" @@ -2514,9 +2515,9 @@ } }, "node_modules/@docusaurus/types": { - "version": "2.3.1", - "resolved": "https://registry.npmjs.org/@docusaurus/types/-/types-2.3.1.tgz", - "integrity": "sha512-PREbIRhTaNNY042qmfSE372Jb7djZt+oVTZkoqHJ8eff8vOIc2zqqDqBVc5BhOfpZGPTrE078yy/torUEZy08A==", + "version": "2.4.0", + "resolved": "https://registry.npmjs.org/@docusaurus/types/-/types-2.4.0.tgz", + "integrity": "sha512-xaBXr+KIPDkIaef06c+i2HeTqVNixB7yFut5fBXPGI2f1rrmEV2vLMznNGsFwvZ5XmA3Quuefd4OGRkdo97Dhw==", "dependencies": { "@types/history": "^4.7.11", "@types/react": "*", @@ -2533,11 +2534,11 @@ } }, "node_modules/@docusaurus/utils": { - "version": "2.3.1", - "resolved": "https://registry.npmjs.org/@docusaurus/utils/-/utils-2.3.1.tgz", - "integrity": "sha512-9WcQROCV0MmrpOQDXDGhtGMd52DHpSFbKLfkyaYumzbTstrbA5pPOtiGtxK1nqUHkiIv8UwexS54p0Vod2I1lg==", + "version": "2.4.0", + "resolved": "https://registry.npmjs.org/@docusaurus/utils/-/utils-2.4.0.tgz", + "integrity": "sha512-89hLYkvtRX92j+C+ERYTuSUK6nF9bGM32QThcHPg2EDDHVw6FzYQXmX6/p+pU5SDyyx5nBlE4qXR92RxCAOqfg==", "dependencies": { - "@docusaurus/logger": "2.3.1", + "@docusaurus/logger": "2.4.0", "@svgr/webpack": "^6.2.1", "escape-string-regexp": "^4.0.0", "file-loader": "^6.2.0", @@ -2567,9 +2568,9 @@ } }, "node_modules/@docusaurus/utils-common": { - "version": "2.3.1", - "resolved": "https://registry.npmjs.org/@docusaurus/utils-common/-/utils-common-2.3.1.tgz", - "integrity": "sha512-pVlRpXkdNcxmKNxAaB1ya2hfCEvVsLDp2joeM6K6uv55Oc5nVIqgyYSgSNKZyMdw66NnvMfsu0RBylcwZQKo9A==", + "version": "2.4.0", + "resolved": "https://registry.npmjs.org/@docusaurus/utils-common/-/utils-common-2.4.0.tgz", + "integrity": "sha512-zIMf10xuKxddYfLg5cS19x44zud/E9I7lj3+0bv8UIs0aahpErfNrGhijEfJpAfikhQ8tL3m35nH3hJ3sOG82A==", "dependencies": { "tslib": "^2.4.0" }, @@ -2586,12 +2587,12 @@ } }, "node_modules/@docusaurus/utils-validation": { - "version": "2.3.1", - "resolved": "https://registry.npmjs.org/@docusaurus/utils-validation/-/utils-validation-2.3.1.tgz", - "integrity": "sha512-7n0208IG3k1HVTByMHlZoIDjjOFC8sbViHVXJx0r3Q+3Ezrx+VQ1RZ/zjNn6lT+QBCRCXlnlaoJ8ug4HIVgQ3w==", + "version": "2.4.0", + "resolved": "https://registry.npmjs.org/@docusaurus/utils-validation/-/utils-validation-2.4.0.tgz", + "integrity": "sha512-IrBsBbbAp6y7mZdJx4S4pIA7dUyWSA0GNosPk6ZJ0fX3uYIEQgcQSGIgTeSC+8xPEx3c16o03en1jSDpgQgz/w==", "dependencies": { - "@docusaurus/logger": "2.3.1", - "@docusaurus/utils": "2.3.1", + "@docusaurus/logger": "2.4.0", + "@docusaurus/utils": "2.4.0", "joi": "^17.6.0", "js-yaml": "^4.1.0", "tslib": "^2.4.0" @@ -3634,35 +3635,6 @@ "node": ">= 0.6" } }, - "node_modules/acorn": { - "version": "7.4.1", - "resolved": "https://registry.npmjs.org/acorn/-/acorn-7.4.1.tgz", - "integrity": "sha512-nQyp0o1/mNdbTO1PO6kHkwSrmgZ0MT/jCCpNiwbUjGoRN4dlBhqJtoQuCnEOKzgTVwg0ZWiCoQy6SxMebQVh8A==", - "bin": { - "acorn": "bin/acorn" - }, - "engines": { - "node": ">=0.4.0" - } - }, - "node_modules/acorn-node": { - "version": "1.8.2", - "resolved": "https://registry.npmjs.org/acorn-node/-/acorn-node-1.8.2.tgz", - "integrity": "sha512-8mt+fslDufLYntIoPAaIMUe/lrbrehIiwmR3t2k9LljIzoigEPF27eLk2hy8zSGzmR/ogr7zbRKINMo1u0yh5A==", - "dependencies": { - "acorn": "^7.0.0", - "acorn-walk": "^7.0.0", - "xtend": "^4.0.2" - } - }, - "node_modules/acorn-walk": { - "version": "7.2.0", - "resolved": "https://registry.npmjs.org/acorn-walk/-/acorn-walk-7.2.0.tgz", - "integrity": "sha512-OPdCF6GsMIP+Az+aWfAAOEt2/+iVDKE7oy6lJ098aoe59oAmK76qV6Gw60SbZ8jHuG2wH058GF4pLFbYamYrVA==", - "engines": { - "node": ">=0.4.0" - } - }, "node_modules/address": { "version": "1.2.1", "resolved": "https://registry.npmjs.org/address/-/address-1.2.1.tgz", @@ -3743,30 +3715,30 @@ } }, "node_modules/algoliasearch": { - "version": "4.14.3", - "resolved": "https://registry.npmjs.org/algoliasearch/-/algoliasearch-4.14.3.tgz", - "integrity": "sha512-GZTEuxzfWbP/vr7ZJfGzIl8fOsoxN916Z6FY2Egc9q2TmZ6hvq5KfAxY89pPW01oW/2HDEKA8d30f9iAH9eXYg==", - "dependencies": { - "@algolia/cache-browser-local-storage": "4.14.3", - "@algolia/cache-common": "4.14.3", - "@algolia/cache-in-memory": "4.14.3", - "@algolia/client-account": "4.14.3", - "@algolia/client-analytics": "4.14.3", - "@algolia/client-common": "4.14.3", - "@algolia/client-personalization": "4.14.3", - "@algolia/client-search": "4.14.3", - "@algolia/logger-common": "4.14.3", - "@algolia/logger-console": "4.14.3", - "@algolia/requester-browser-xhr": "4.14.3", - "@algolia/requester-common": "4.14.3", - "@algolia/requester-node-http": "4.14.3", - "@algolia/transporter": "4.14.3" + "version": "4.16.0", + "resolved": "https://registry.npmjs.org/algoliasearch/-/algoliasearch-4.16.0.tgz", + "integrity": "sha512-HAjKJ6bBblaXqO4dYygF4qx251GuJ6zCZt+qbJ+kU7sOC+yc84pawEjVpJByh+cGP2APFCsao2Giz50cDlKNPA==", + "dependencies": { + "@algolia/cache-browser-local-storage": "4.16.0", + "@algolia/cache-common": "4.16.0", + "@algolia/cache-in-memory": "4.16.0", + "@algolia/client-account": "4.16.0", + "@algolia/client-analytics": "4.16.0", + "@algolia/client-common": "4.16.0", + "@algolia/client-personalization": "4.16.0", + "@algolia/client-search": "4.16.0", + "@algolia/logger-common": "4.16.0", + "@algolia/logger-console": "4.16.0", + "@algolia/requester-browser-xhr": "4.16.0", + "@algolia/requester-common": "4.16.0", + "@algolia/requester-node-http": "4.16.0", + "@algolia/transporter": "4.16.0" } }, "node_modules/algoliasearch-helper": { - "version": "3.11.3", - "resolved": "https://registry.npmjs.org/algoliasearch-helper/-/algoliasearch-helper-3.11.3.tgz", - "integrity": "sha512-TbaEvLwiuGygHQIB8y+OsJKQQ40+JKUua5B91X66tMUHyyhbNHvqyr0lqd3wCoyKx7WybyQrC0WJvzoIeh24Aw==", + "version": "3.12.0", + "resolved": "https://registry.npmjs.org/algoliasearch-helper/-/algoliasearch-helper-3.12.0.tgz", + "integrity": "sha512-/j1U3PEwdan0n6P/QqSnSpNSLC5+cEMvyljd5CnmNmUjDlGrys+vFEOwjVEnqELIiAGMHEA/Nl3CiKVFBUYqyQ==", "dependencies": { "@algolia/events": "^4.0.1" }, @@ -3833,6 +3805,11 @@ "url": "https://github.com/chalk/ansi-styles?sponsor=1" } }, + "node_modules/any-promise": { + "version": "1.3.0", + "resolved": "https://registry.npmjs.org/any-promise/-/any-promise-1.3.0.tgz", + "integrity": "sha512-7UvmKalWRt1wgjL1RrGxoSJW/0QZFIegpeGvZG9kjp8vrRu55XTHbwnqq2GpXm9uLbcuhxm3IqX9OB4MZR1b2A==" + }, "node_modules/anymatch": { "version": "3.1.2", "resolved": "https://registry.npmjs.org/anymatch/-/anymatch-3.1.2.tgz", @@ -4737,9 +4714,9 @@ "integrity": "sha512-QADzlaHc8icV8I7vbaJXJwod9HWYp8uCqf1xa4OfNu1T7JVxQIrUgOWtHdNDtPiywmFbiS12VjotIXLrKM3orQ==" }, "node_modules/copy-text-to-clipboard": { - "version": "3.0.1", - "resolved": "https://registry.npmjs.org/copy-text-to-clipboard/-/copy-text-to-clipboard-3.0.1.tgz", - "integrity": "sha512-rvVsHrpFcL4F2P8ihsoLdFHmd404+CMg71S756oRSeQgqk51U3kicGdnvfkrxva0xXH92SjGS62B0XIJsbh+9Q==", + "version": "3.1.0", + "resolved": "https://registry.npmjs.org/copy-text-to-clipboard/-/copy-text-to-clipboard-3.1.0.tgz", + "integrity": "sha512-PFM6BnjLnOON/lB3ta/Jg7Ywsv+l9kQGD4TWDCSlRBGmqnnTM5MrDkhAFgw+8HZt0wW6Q2BBE4cmy9sq+s9Qng==", "engines": { "node": ">=12" }, @@ -5138,12 +5115,12 @@ } }, "node_modules/cssnano-preset-advanced": { - "version": "5.3.9", - "resolved": "https://registry.npmjs.org/cssnano-preset-advanced/-/cssnano-preset-advanced-5.3.9.tgz", - "integrity": "sha512-njnh4pp1xCsibJcEHnWZb4EEzni0ePMqPuPNyuWT4Z+YeXmsgqNuTPIljXFEXhxGsWs9183JkXgHxc1TcsahIg==", + "version": "5.3.10", + "resolved": "https://registry.npmjs.org/cssnano-preset-advanced/-/cssnano-preset-advanced-5.3.10.tgz", + "integrity": "sha512-fnYJyCS9jgMU+cmHO1rPSPf9axbQyD7iUhLO5Df6O4G+fKIOMps+ZbU0PdGFejFBBZ3Pftf18fn1eG7MAPUSWQ==", "dependencies": { "autoprefixer": "^10.4.12", - "cssnano-preset-default": "^5.2.13", + "cssnano-preset-default": "^5.2.14", "postcss-discard-unused": "^5.1.0", "postcss-merge-idents": "^5.1.1", "postcss-reduce-idents": "^5.2.0", @@ -5157,21 +5134,21 @@ } }, "node_modules/cssnano-preset-default": { - "version": "5.2.13", - "resolved": "https://registry.npmjs.org/cssnano-preset-default/-/cssnano-preset-default-5.2.13.tgz", - "integrity": "sha512-PX7sQ4Pb+UtOWuz8A1d+Rbi+WimBIxJTRyBdgGp1J75VU0r/HFQeLnMYgHiCAp6AR4rqrc7Y4R+1Rjk3KJz6DQ==", + "version": "5.2.14", + "resolved": "https://registry.npmjs.org/cssnano-preset-default/-/cssnano-preset-default-5.2.14.tgz", + "integrity": "sha512-t0SFesj/ZV2OTylqQVOrFgEh5uanxbO6ZAdeCrNsUQ6fVuXwYTxJPNAGvGTxHbD68ldIJNec7PyYZDBrfDQ+6A==", "dependencies": { "css-declaration-sorter": "^6.3.1", "cssnano-utils": "^3.1.0", "postcss-calc": "^8.2.3", - "postcss-colormin": "^5.3.0", + "postcss-colormin": "^5.3.1", "postcss-convert-values": "^5.1.3", "postcss-discard-comments": "^5.1.2", "postcss-discard-duplicates": "^5.1.0", "postcss-discard-empty": "^5.1.1", "postcss-discard-overridden": "^5.1.0", "postcss-merge-longhand": "^5.1.7", - "postcss-merge-rules": "^5.1.3", + "postcss-merge-rules": "^5.1.4", "postcss-minify-font-values": "^5.1.0", "postcss-minify-gradients": "^5.1.1", "postcss-minify-params": "^5.1.4", @@ -5186,7 +5163,7 @@ "postcss-normalize-url": "^5.1.0", "postcss-normalize-whitespace": "^5.1.1", "postcss-ordered-values": "^5.1.3", - "postcss-reduce-initial": "^5.1.1", + "postcss-reduce-initial": "^5.1.2", "postcss-reduce-transforms": "^5.1.0", "postcss-svgo": "^5.1.0", "postcss-unique-selectors": "^5.1.1" @@ -5307,11 +5284,6 @@ "url": "https://github.com/sponsors/ljharb" } }, - "node_modules/defined": { - "version": "1.0.0", - "resolved": "https://registry.npmjs.org/defined/-/defined-1.0.0.tgz", - "integrity": "sha512-Y2caI5+ZwS5c3RiNDJ6u53VhQHv+hHKwhkI1iHvceKUHw9Df6EK2zRLfjejRgMuCuxK7PfSWIMwWecceVvThjQ==" - }, "node_modules/del": { "version": "6.1.1", "resolved": "https://registry.npmjs.org/del/-/del-6.1.1.tgz", @@ -5409,22 +5381,6 @@ "resolved": "https://registry.npmjs.org/ms/-/ms-2.0.0.tgz", "integrity": "sha512-Tpp60P6IUJDTuOq/5Z8cdskzJujfwqfOTkrwIwj7IRISpnkJnT6SyJ4PCPnGMoFjC9ddhal5KVIYtAt97ix05A==" }, - "node_modules/detective": { - "version": "5.2.1", - "resolved": "https://registry.npmjs.org/detective/-/detective-5.2.1.tgz", - "integrity": "sha512-v9XE1zRnz1wRtgurGu0Bs8uHKFSTdteYZNbIPFVhUZ39L/S79ppMpdmVOZAnoz1jfEFodc48n6MX483Xo3t1yw==", - "dependencies": { - "acorn-node": "^1.8.2", - "defined": "^1.0.0", - "minimist": "^1.2.6" - }, - "bin": { - "detective": "bin/detective.js" - }, - "engines": { - "node": ">=0.8.0" - } - }, "node_modules/didyoumean": { "version": "1.2.2", "resolved": "https://registry.npmjs.org/didyoumean/-/didyoumean-1.2.2.tgz", @@ -6138,9 +6094,9 @@ } }, "node_modules/flux": { - "version": "4.0.3", - "resolved": "https://registry.npmjs.org/flux/-/flux-4.0.3.tgz", - "integrity": "sha512-yKAbrp7JhZhj6uiT1FTuVMlIAT1J4jqEyBpFApi1kxpGZCvacMVc/t1pMQyotqHhAgvoE3bNvAykhCo2CLjnYw==", + "version": "4.0.4", + "resolved": "https://registry.npmjs.org/flux/-/flux-4.0.4.tgz", + "integrity": "sha512-NCj3XlayA2UsapRpM7va6wU1+9rE5FIL7qoMcmxWHRzbp0yujihMBm9BBHZ1MDIk5h5o2Bl6eGiCe8rYELAmYw==", "dependencies": { "fbemitter": "^3.0.0", "fbjs": "^3.0.1" @@ -6863,9 +6819,9 @@ } }, "node_modules/htmlparser2": { - "version": "8.0.1", - "resolved": "https://registry.npmjs.org/htmlparser2/-/htmlparser2-8.0.1.tgz", - "integrity": "sha512-4lVbmc1diZC7GUJQtRQ5yBAeUCL1exyMwmForWkRLnwyzWBFxN633SALPMGYaWZvKe9j1pRZJpauvmxENSp/EA==", + "version": "8.0.2", + "resolved": "https://registry.npmjs.org/htmlparser2/-/htmlparser2-8.0.2.tgz", + "integrity": "sha512-GYdjWKDkbRLkZ5geuHs5NY1puJ+PXwP7+fHPRz06Eirsb9ugf6d8kkXav6ADhcODhFFPMIXyxkxSuMf3D6NCFA==", "funding": [ "https://github.com/fb55/htmlparser2?sponsor=1", { @@ -6875,9 +6831,9 @@ ], "dependencies": { "domelementtype": "^2.3.0", - "domhandler": "^5.0.2", + "domhandler": "^5.0.3", "domutils": "^3.0.1", - "entities": "^4.3.0" + "entities": "^4.4.0" } }, "node_modules/http-cache-semantics": { @@ -7058,9 +7014,9 @@ } }, "node_modules/infima": { - "version": "0.2.0-alpha.42", - "resolved": "https://registry.npmjs.org/infima/-/infima-0.2.0-alpha.42.tgz", - "integrity": "sha512-ift8OXNbQQwtbIt6z16KnSWP7uJ/SysSMFI4F87MNRTicypfl4Pv3E2OGVv6N3nSZFJvA8imYulCBS64iyHYww==", + "version": "0.2.0-alpha.43", + "resolved": "https://registry.npmjs.org/infima/-/infima-0.2.0-alpha.43.tgz", + "integrity": "sha512-2uw57LvUqW0rK/SWYnd/2rRfxNA5DDNOh33jxF7fy46VWoNhGxiUQyVZHbBMjQ33mQem0cjdDVwgWVAmlRfgyQ==", "engines": { "node": ">=12" } @@ -7472,6 +7428,14 @@ "url": "https://github.com/chalk/supports-color?sponsor=1" } }, + "node_modules/jiti": { + "version": "1.18.2", + "resolved": "https://registry.npmjs.org/jiti/-/jiti-1.18.2.tgz", + "integrity": "sha512-QAdOptna2NYiSSpv0O/BwoHBSmz4YhpzJHyi+fnMRTXFjp7B8i/YG5Z8IfusxB1ufjcD2Sre1F3R+nX3fvy7gg==", + "bin": { + "jiti": "bin/jiti.js" + } + }, "node_modules/joi": { "version": "17.6.2", "resolved": "https://registry.npmjs.org/joi/-/joi-17.6.2.tgz", @@ -8021,10 +7985,26 @@ "multicast-dns": "cli.js" } }, + "node_modules/mz": { + "version": "2.7.0", + "resolved": "https://registry.npmjs.org/mz/-/mz-2.7.0.tgz", + "integrity": "sha512-z81GNO7nnYMEhrGh9LeymoE4+Yr0Wn5McHIZMK5cfQCl+NDX08sCZgUc9/6MHni9IWuFLm1Z3HTCXu2z9fN62Q==", + "dependencies": { + "any-promise": "^1.0.0", + "object-assign": "^4.0.1", + "thenify-all": "^1.0.0" + } + }, "node_modules/nanoid": { - "version": "3.3.4", - "resolved": "https://registry.npmjs.org/nanoid/-/nanoid-3.3.4.tgz", - "integrity": "sha512-MqBkQh/OHTS2egovRtLk45wEyNXwF+cokD+1YPf9u5VfJiRdAiRwB2froX5Co9Rh20xs4siNPm8naNotSD6RBw==", + "version": "3.3.6", + "resolved": "https://registry.npmjs.org/nanoid/-/nanoid-3.3.6.tgz", + "integrity": "sha512-BGcqMMJuToF7i1rt+2PWSNVnWIkGCU78jBG3RxO/bZlnZPK2Cmi2QaffxGO/2RvWi9sL+FAiRiXMgsyxQ1DIDA==", + "funding": [ + { + "type": "github", + "url": "https://github.com/sponsors/ai" + } + ], "bin": { "nanoid": "bin/nanoid.cjs" }, @@ -8529,6 +8509,14 @@ "node": ">=0.10.0" } }, + "node_modules/pirates": { + "version": "4.0.5", + "resolved": "https://registry.npmjs.org/pirates/-/pirates-4.0.5.tgz", + "integrity": "sha512-8V9+HQPupnaXMA23c5hvl69zXvTwTzyAYasnkb0Tts4XvO4CliqONMOnvlq26rkhLC3nWDFBJf73LU1e1VZLaQ==", + "engines": { + "node": ">= 6" + } + }, "node_modules/pkg-dir": { "version": "4.2.0", "resolved": "https://registry.npmjs.org/pkg-dir/-/pkg-dir-4.2.0.tgz", @@ -8594,9 +8582,9 @@ } }, "node_modules/postcss": { - "version": "8.4.21", - "resolved": "https://registry.npmjs.org/postcss/-/postcss-8.4.21.tgz", - "integrity": "sha512-tP7u/Sn/dVxK2NnruI4H9BG+x+Wxz6oeZ1cJ8P6G/PZY0IKk4k/63TDsQf2kQq3+qoJeLm2kIBUNlZe3zgb4Zg==", + "version": "8.4.22", + "resolved": "https://registry.npmjs.org/postcss/-/postcss-8.4.22.tgz", + "integrity": "sha512-XseknLAfRHzVWjCEtdviapiBtfLdgyzExD50Rg2ePaucEesyh8Wv4VPdW0nbyDa1ydbrAxV19jvMT4+LFmcNUA==", "funding": [ { "type": "opencollective", @@ -8605,10 +8593,14 @@ { "type": "tidelift", "url": "https://tidelift.com/funding/github/npm/postcss" + }, + { + "type": "github", + "url": "https://github.com/sponsors/ai" } ], "dependencies": { - "nanoid": "^3.3.4", + "nanoid": "^3.3.6", "picocolors": "^1.0.0", "source-map-js": "^1.0.2" }, @@ -8629,11 +8621,11 @@ } }, "node_modules/postcss-colormin": { - "version": "5.3.0", - "resolved": "https://registry.npmjs.org/postcss-colormin/-/postcss-colormin-5.3.0.tgz", - "integrity": "sha512-WdDO4gOFG2Z8n4P8TWBpshnL3JpmNmJwdnfP2gbk2qBA8PWwOYcmjmI/t3CmMeL72a7Hkd+x/Mg9O2/0rD54Pg==", + "version": "5.3.1", + "resolved": "https://registry.npmjs.org/postcss-colormin/-/postcss-colormin-5.3.1.tgz", + "integrity": "sha512-UsWQG0AqTFQmpBegeLLc1+c3jIqBNB0zlDGRWR+dQ3pRKJL1oeMzyqmH3o2PIfn9MBdNrVPWhDbT769LxCTLJQ==", "dependencies": { - "browserslist": "^4.16.6", + "browserslist": "^4.21.4", "caniuse-api": "^3.0.0", "colord": "^2.9.1", "postcss-value-parser": "^4.2.0" @@ -8832,9 +8824,9 @@ } }, "node_modules/postcss-merge-rules": { - "version": "5.1.3", - "resolved": "https://registry.npmjs.org/postcss-merge-rules/-/postcss-merge-rules-5.1.3.tgz", - "integrity": "sha512-LbLd7uFC00vpOuMvyZop8+vvhnfRGpp2S+IMQKeuOZZapPRY4SMq5ErjQeHbHsjCUgJkRNrlU+LmxsKIqPKQlA==", + "version": "5.1.4", + "resolved": "https://registry.npmjs.org/postcss-merge-rules/-/postcss-merge-rules-5.1.4.tgz", + "integrity": "sha512-0R2IuYpgU93y9lhVbO/OylTtKMVcHb67zjWIfCiKR9rWL3GUk1677LAqD/BcHizukdZEjT8Ru3oHRoAYoJy44g==", "dependencies": { "browserslist": "^4.21.4", "caniuse-api": "^3.0.0", @@ -9136,9 +9128,9 @@ } }, "node_modules/postcss-reduce-initial": { - "version": "5.1.1", - "resolved": "https://registry.npmjs.org/postcss-reduce-initial/-/postcss-reduce-initial-5.1.1.tgz", - "integrity": "sha512-//jeDqWcHPuXGZLoolFrUXBDyuEGbr9S2rMo19bkTIjBQ4PqkaO+oI8wua5BOUxpfi97i3PCoInsiFIEBfkm9w==", + "version": "5.1.2", + "resolved": "https://registry.npmjs.org/postcss-reduce-initial/-/postcss-reduce-initial-5.1.2.tgz", + "integrity": "sha512-dE/y2XRaqAi6OvjzD22pjTUQ8eOfc6m/natGHgKFBK9DxFmIm69YmaRVQrGgFlEfc1HePIurY0TmDeROK05rIg==", "dependencies": { "browserslist": "^4.21.4", "caniuse-api": "^3.0.0" @@ -9748,11 +9740,11 @@ } }, "node_modules/react-textarea-autosize": { - "version": "8.4.0", - "resolved": "https://registry.npmjs.org/react-textarea-autosize/-/react-textarea-autosize-8.4.0.tgz", - "integrity": "sha512-YrTFaEHLgJsi8sJVYHBzYn+mkP3prGkmP2DKb/tm0t7CLJY5t1Rxix8070LAKb0wby7bl/lf2EeHkuMihMZMwQ==", + "version": "8.4.1", + "resolved": "https://registry.npmjs.org/react-textarea-autosize/-/react-textarea-autosize-8.4.1.tgz", + "integrity": "sha512-aD2C+qK6QypknC+lCMzteOdIjoMbNlgSFmJjCV+DrfTPwp59i/it9mMNf2HDzvRjQgKAyBDPyLJhcrzElf2U4Q==", "dependencies": { - "@babel/runtime": "^7.10.2", + "@babel/runtime": "^7.20.13", "use-composed-ref": "^1.3.0", "use-latest": "^1.2.1" }, @@ -9839,9 +9831,9 @@ } }, "node_modules/regenerator-runtime": { - "version": "0.13.9", - "resolved": "https://registry.npmjs.org/regenerator-runtime/-/regenerator-runtime-0.13.9.tgz", - "integrity": "sha512-p3VT+cOEgxFsRRA9X4lkI1E+k2/CtnKtU4gcxyaCUreilL/vqI6CdZ3wxVUx3UOUg+gnUOQQcRI7BmSI656MYA==" + "version": "0.13.11", + "resolved": "https://registry.npmjs.org/regenerator-runtime/-/regenerator-runtime-0.13.11.tgz", + "integrity": "sha512-kY1AZVr2Ra+t+piVaJ4gxaFaReZVH40AKNo7UCX6W+dEwBo/2oZJzqfuN1qLq1oL45o56cPaTXELwrTh8Fpggg==" }, "node_modules/regenerator-transform": { "version": "0.15.0", @@ -11037,6 +11029,53 @@ "postcss": "^8.2.15" } }, + "node_modules/sucrase": { + "version": "3.31.0", + "resolved": "https://registry.npmjs.org/sucrase/-/sucrase-3.31.0.tgz", + "integrity": "sha512-6QsHnkqyVEzYcaiHsOKkzOtOgdJcb8i54x6AV2hDwyZcY9ZyykGZVw6L/YN98xC0evwTP6utsWWrKRaa8QlfEQ==", + "dependencies": { + "commander": "^4.0.0", + "glob": "7.1.6", + "lines-and-columns": "^1.1.6", + "mz": "^2.7.0", + "pirates": "^4.0.1", + "ts-interface-checker": "^0.1.9" + }, + "bin": { + "sucrase": "bin/sucrase", + "sucrase-node": "bin/sucrase-node" + }, + "engines": { + "node": ">=8" + } + }, + "node_modules/sucrase/node_modules/commander": { + "version": "4.1.1", + "resolved": "https://registry.npmjs.org/commander/-/commander-4.1.1.tgz", + "integrity": "sha512-NOKm8xhkzAjzFx8B2v5OAHT+u5pRQc2UCa2Vq9jYL/31o2wi9mxBA7LIFs3sV5VSC49z6pEhfbMULvShKj26WA==", + "engines": { + "node": ">= 6" + } + }, + "node_modules/sucrase/node_modules/glob": { + "version": "7.1.6", + "resolved": "https://registry.npmjs.org/glob/-/glob-7.1.6.tgz", + "integrity": "sha512-LwaxwyZ72Lk7vZINtNNrywX0ZuLyStrdDtabefZKAY5ZGJhVtgdznluResxNmPitE0SAO+O26sWTHeKSI2wMBA==", + "dependencies": { + "fs.realpath": "^1.0.0", + "inflight": "^1.0.4", + "inherits": "2", + "minimatch": "^3.0.4", + "once": "^1.3.0", + "path-is-absolute": "^1.0.0" + }, + "engines": { + "node": "*" + }, + "funding": { + "url": "https://github.com/sponsors/isaacs" + } + }, "node_modules/supports-color": { "version": "7.2.0", "resolved": "https://registry.npmjs.org/supports-color/-/supports-color-7.2.0.tgz", @@ -11156,19 +11195,19 @@ } }, "node_modules/tailwindcss": { - "version": "3.2.7", - "resolved": "https://registry.npmjs.org/tailwindcss/-/tailwindcss-3.2.7.tgz", - "integrity": "sha512-B6DLqJzc21x7wntlH/GsZwEXTBttVSl1FtCzC8WP4oBc/NKef7kaax5jeihkkCEWc831/5NDJ9gRNDK6NEioQQ==", + "version": "3.3.1", + "resolved": "https://registry.npmjs.org/tailwindcss/-/tailwindcss-3.3.1.tgz", + "integrity": "sha512-Vkiouc41d4CEq0ujXl6oiGFQ7bA3WEhUZdTgXAhtKxSy49OmKs8rEfQmupsfF0IGW8fv2iQkp1EVUuapCFrZ9g==", "dependencies": { "arg": "^5.0.2", "chokidar": "^3.5.3", "color-name": "^1.1.4", - "detective": "^5.2.1", "didyoumean": "^1.2.2", "dlv": "^1.1.3", "fast-glob": "^3.2.12", "glob-parent": "^6.0.2", "is-glob": "^4.0.3", + "jiti": "^1.17.2", "lilconfig": "^2.0.6", "micromatch": "^4.0.5", "normalize-path": "^3.0.0", @@ -11182,7 +11221,8 @@ "postcss-selector-parser": "^6.0.11", "postcss-value-parser": "^4.2.0", "quick-lru": "^5.1.1", - "resolve": "^1.22.1" + "resolve": "^1.22.1", + "sucrase": "^3.29.0" }, "bin": { "tailwind": "lib/cli.js", @@ -11345,6 +11385,25 @@ "resolved": "https://registry.npmjs.org/text-table/-/text-table-0.2.0.tgz", "integrity": "sha512-N+8UisAXDGk8PFXP4HAzVR9nbfmVJ3zYLAWiTIoqC5v5isinhr+r5uaO8+7r3BMfuNIufIsA7RdpVgacC2cSpw==" }, + "node_modules/thenify": { + "version": "3.3.1", + "resolved": "https://registry.npmjs.org/thenify/-/thenify-3.3.1.tgz", + "integrity": "sha512-RVZSIV5IG10Hk3enotrhvz0T9em6cyHBLkH/YAZuKqd8hRkKhSfCGIcP2KUY0EPxndzANBmNllzWPwak+bheSw==", + "dependencies": { + "any-promise": "^1.0.0" + } + }, + "node_modules/thenify-all": { + "version": "1.6.0", + "resolved": "https://registry.npmjs.org/thenify-all/-/thenify-all-1.6.0.tgz", + "integrity": "sha512-RNxQH/qI8/t3thXJDwcstUO4zeqo64+Uy/+sNVRBx4Xn2OX+OZ9oP+iJnNFqplFra2ZUVeKCSa2oVWi3T4uVmA==", + "dependencies": { + "thenify": ">= 3.1.0 < 4" + }, + "engines": { + "node": ">=0.8" + } + }, "node_modules/thunky": { "version": "1.1.0", "resolved": "https://registry.npmjs.org/thunky/-/thunky-1.1.0.tgz", @@ -11431,6 +11490,11 @@ "url": "https://github.com/sponsors/wooorm" } }, + "node_modules/ts-interface-checker": { + "version": "0.1.13", + "resolved": "https://registry.npmjs.org/ts-interface-checker/-/ts-interface-checker-0.1.13.tgz", + "integrity": "sha512-Y/arvbn+rrz3JCKl9C4kVNfTfSm2/mEp5FSz5EsZSANGPSlQrpRI5M4PKF+mJnE52jOO90PnPSc3Ur3bTQw0gA==" + }, "node_modules/tslib": { "version": "2.4.0", "resolved": "https://registry.npmjs.org/tslib/-/tslib-2.4.0.tgz", @@ -11500,9 +11564,9 @@ } }, "node_modules/ua-parser-js": { - "version": "0.7.33", - "resolved": "https://registry.npmjs.org/ua-parser-js/-/ua-parser-js-0.7.33.tgz", - "integrity": "sha512-s8ax/CeZdK9R/56Sui0WM6y9OFREJarMRHqLB2EwkovemBxNQ+Bqu8GAsUnVcXKgphb++ghr/B2BZx4mahujPw==", + "version": "0.7.34", + "resolved": "https://registry.npmjs.org/ua-parser-js/-/ua-parser-js-0.7.34.tgz", + "integrity": "sha512-cJMeh/eOILyGu0ejgTKB95yKT3zOenSe9UGE3vj6WfiOwgGYnmATUsnDixMFvdU+rNMvWih83hrUP8VwhF9yXQ==", "funding": [ { "type": "opencollective", @@ -12762,74 +12826,74 @@ "integrity": "sha512-2VGCk7I9tA9Ge73Km99+Qg87w0wzW4tgUruvWAn/gfey1ZXgmxZtyIRBebk35R1O8TbK77wujVtCnpsGpRy1kg==" }, "@algolia/cache-browser-local-storage": { - "version": "4.14.3", - "resolved": "https://registry.npmjs.org/@algolia/cache-browser-local-storage/-/cache-browser-local-storage-4.14.3.tgz", - "integrity": "sha512-hWH1yCxgG3+R/xZIscmUrWAIBnmBFHH5j30fY/+aPkEZWt90wYILfAHIOZ1/Wxhho5SkPfwFmT7ooX2d9JeQBw==", + "version": "4.16.0", + "resolved": "https://registry.npmjs.org/@algolia/cache-browser-local-storage/-/cache-browser-local-storage-4.16.0.tgz", + "integrity": "sha512-jVrk0YB3tjOhD5/lhBtYCVCeLjZmVpf2kdi4puApofytf/R0scjWz0GdozlW4HhU+Prxmt/c9ge4QFjtv5OAzQ==", "requires": { - "@algolia/cache-common": "4.14.3" + "@algolia/cache-common": "4.16.0" } }, "@algolia/cache-common": { - "version": "4.14.3", - "resolved": "https://registry.npmjs.org/@algolia/cache-common/-/cache-common-4.14.3.tgz", - "integrity": "sha512-oZJofOoD9FQOwiGTzyRnmzvh3ZP8WVTNPBLH5xU5JNF7drDbRT0ocVT0h/xB2rPHYzOeXRrLaQQBwRT/CKom0Q==" + "version": "4.16.0", + "resolved": "https://registry.npmjs.org/@algolia/cache-common/-/cache-common-4.16.0.tgz", + "integrity": "sha512-4iHjkSYQYw46pITrNQgXXhvUmcekI8INz1m+SzmqLX8jexSSy4Ky4zfGhZzhhhLHXUP3+x/PK/c0qPjxEvRwKQ==" }, "@algolia/cache-in-memory": { - "version": "4.14.3", - "resolved": "https://registry.npmjs.org/@algolia/cache-in-memory/-/cache-in-memory-4.14.3.tgz", - "integrity": "sha512-ES0hHQnzWjeioLQf5Nq+x1AWdZJ50znNPSH3puB/Y4Xsg4Av1bvLmTJe7SY2uqONaeMTvL0OaVcoVtQgJVw0vg==", + "version": "4.16.0", + "resolved": "https://registry.npmjs.org/@algolia/cache-in-memory/-/cache-in-memory-4.16.0.tgz", + "integrity": "sha512-p7RYykvA6Ip6QENxrh99nOD77otVh1sJRivcgcVpnjoZb5sIN3t33eUY1DpB9QSBizcrW+qk19rNkdnZ43a+PQ==", "requires": { - "@algolia/cache-common": "4.14.3" + "@algolia/cache-common": "4.16.0" } }, "@algolia/client-account": { - "version": "4.14.3", - "resolved": "https://registry.npmjs.org/@algolia/client-account/-/client-account-4.14.3.tgz", - "integrity": "sha512-PBcPb0+f5Xbh5UfLZNx2Ow589OdP8WYjB4CnvupfYBrl9JyC1sdH4jcq/ri8osO/mCZYjZrQsKAPIqW/gQmizQ==", + "version": "4.16.0", + "resolved": "https://registry.npmjs.org/@algolia/client-account/-/client-account-4.16.0.tgz", + "integrity": "sha512-eydcfpdIyuWoKgUSz5iZ/L0wE/Wl7958kACkvTHLDNXvK/b8Z1zypoJavh6/km1ZNQmFpeYS2jrmq0kUSFn02w==", "requires": { - "@algolia/client-common": "4.14.3", - "@algolia/client-search": "4.14.3", - "@algolia/transporter": "4.14.3" + "@algolia/client-common": "4.16.0", + "@algolia/client-search": "4.16.0", + "@algolia/transporter": "4.16.0" } }, "@algolia/client-analytics": { - "version": "4.14.3", - "resolved": "https://registry.npmjs.org/@algolia/client-analytics/-/client-analytics-4.14.3.tgz", - "integrity": "sha512-eAwQq0Hb/aauv9NhCH5Dp3Nm29oFx28sayFN2fdOWemwSeJHIl7TmcsxVlRsO50fsD8CtPcDhtGeD3AIFLNvqw==", + "version": "4.16.0", + "resolved": "https://registry.npmjs.org/@algolia/client-analytics/-/client-analytics-4.16.0.tgz", + "integrity": "sha512-cONWXH3BfilgdlCofUm492bJRWtpBLVW/hsUlfoFtiX1u05xoBP7qeiDwh9RR+4pSLHLodYkHAf5U4honQ55Qg==", "requires": { - "@algolia/client-common": "4.14.3", - "@algolia/client-search": "4.14.3", - "@algolia/requester-common": "4.14.3", - "@algolia/transporter": "4.14.3" + "@algolia/client-common": "4.16.0", + "@algolia/client-search": "4.16.0", + "@algolia/requester-common": "4.16.0", + "@algolia/transporter": "4.16.0" } }, "@algolia/client-common": { - "version": "4.14.3", - "resolved": "https://registry.npmjs.org/@algolia/client-common/-/client-common-4.14.3.tgz", - "integrity": "sha512-jkPPDZdi63IK64Yg4WccdCsAP4pHxSkr4usplkUZM5C1l1oEpZXsy2c579LQ0rvwCs5JFmwfNG4ahOszidfWPw==", + "version": "4.16.0", + "resolved": "https://registry.npmjs.org/@algolia/client-common/-/client-common-4.16.0.tgz", + "integrity": "sha512-QVdR4019ukBH6f5lFr27W60trRxQF1SfS1qo0IP6gjsKhXhUVJuHxOCA6ArF87jrNkeuHEoRoDU+GlvaecNo8g==", "requires": { - "@algolia/requester-common": "4.14.3", - "@algolia/transporter": "4.14.3" + "@algolia/requester-common": "4.16.0", + "@algolia/transporter": "4.16.0" } }, "@algolia/client-personalization": { - "version": "4.14.3", - "resolved": "https://registry.npmjs.org/@algolia/client-personalization/-/client-personalization-4.14.3.tgz", - "integrity": "sha512-UCX1MtkVNgaOL9f0e22x6tC9e2H3unZQlSUdnVaSKpZ+hdSChXGaRjp2UIT7pxmPqNCyv51F597KEX5WT60jNg==", + "version": "4.16.0", + "resolved": "https://registry.npmjs.org/@algolia/client-personalization/-/client-personalization-4.16.0.tgz", + "integrity": "sha512-irtLafssDGPuhYqIwxqOxiWlVYvrsBD+EMA1P9VJtkKi3vSNBxiWeQ0f0Tn53cUNdSRNEssfoEH84JL97SV2SQ==", "requires": { - "@algolia/client-common": "4.14.3", - "@algolia/requester-common": "4.14.3", - "@algolia/transporter": "4.14.3" + "@algolia/client-common": "4.16.0", + "@algolia/requester-common": "4.16.0", + "@algolia/transporter": "4.16.0" } }, "@algolia/client-search": { - "version": "4.14.3", - "resolved": "https://registry.npmjs.org/@algolia/client-search/-/client-search-4.14.3.tgz", - "integrity": "sha512-I2U7xBx5OPFdPLA8AXKUPPxGY3HDxZ4r7+mlZ8ZpLbI8/ri6fnu6B4z3wcL7sgHhDYMwnAE8Xr0AB0h3Hnkp4A==", + "version": "4.16.0", + "resolved": "https://registry.npmjs.org/@algolia/client-search/-/client-search-4.16.0.tgz", + "integrity": "sha512-xsfrAE1jO/JDh1wFrRz+alVyW+aA6qnkzmbWWWZWEgVF3EaFqzIf9r1l/aDtDdBtNTNhX9H3Lg31+BRtd5izQA==", "requires": { - "@algolia/client-common": "4.14.3", - "@algolia/requester-common": "4.14.3", - "@algolia/transporter": "4.14.3" + "@algolia/client-common": "4.16.0", + "@algolia/requester-common": "4.16.0", + "@algolia/transporter": "4.16.0" } }, "@algolia/events": { @@ -12838,47 +12902,47 @@ "integrity": "sha512-FQzvOCgoFXAbf5Y6mYozw2aj5KCJoA3m4heImceldzPSMbdyS4atVjJzXKMsfX3wnZTFYwkkt8/z8UesLHlSBQ==" }, "@algolia/logger-common": { - "version": "4.14.3", - "resolved": "https://registry.npmjs.org/@algolia/logger-common/-/logger-common-4.14.3.tgz", - "integrity": "sha512-kUEAZaBt/J3RjYi8MEBT2QEexJR2kAE2mtLmezsmqMQZTV502TkHCxYzTwY2dE7OKcUTxi4OFlMuS4GId9CWPw==" + "version": "4.16.0", + "resolved": "https://registry.npmjs.org/@algolia/logger-common/-/logger-common-4.16.0.tgz", + "integrity": "sha512-U9H8uCzSDuePJmbnjjTX21aPDRU6x74Tdq3dJmdYu2+pISx02UeBJm4kSgc9RW5jcR5j35G9gnjHY9Q3ngWbyQ==" }, "@algolia/logger-console": { - "version": "4.14.3", - "resolved": "https://registry.npmjs.org/@algolia/logger-console/-/logger-console-4.14.3.tgz", - "integrity": "sha512-ZWqAlUITktiMN2EiFpQIFCJS10N96A++yrexqC2Z+3hgF/JcKrOxOdT4nSCQoEPvU4Ki9QKbpzbebRDemZt/hw==", + "version": "4.16.0", + "resolved": "https://registry.npmjs.org/@algolia/logger-console/-/logger-console-4.16.0.tgz", + "integrity": "sha512-+qymusiM+lPZKrkf0tDjCQA158eEJO2IU+Nr/sJ9TFyI/xkFPjNPzw/Qbc8Iy/xcOXGlc6eMgmyjtVQqAWq6UA==", "requires": { - "@algolia/logger-common": "4.14.3" + "@algolia/logger-common": "4.16.0" } }, "@algolia/requester-browser-xhr": { - "version": "4.14.3", - "resolved": "https://registry.npmjs.org/@algolia/requester-browser-xhr/-/requester-browser-xhr-4.14.3.tgz", - "integrity": "sha512-AZeg2T08WLUPvDncl2XLX2O67W5wIO8MNaT7z5ii5LgBTuk/rU4CikTjCe2xsUleIZeFl++QrPAi4Bdxws6r/Q==", + "version": "4.16.0", + "resolved": "https://registry.npmjs.org/@algolia/requester-browser-xhr/-/requester-browser-xhr-4.16.0.tgz", + "integrity": "sha512-gK+kvs6LHl/PaOJfDuwjkopNbG1djzFLsVBklGBsSU6h6VjFkxIpo6Qq80IK14p9cplYZfhfaL12va6Q9p3KVQ==", "requires": { - "@algolia/requester-common": "4.14.3" + "@algolia/requester-common": "4.16.0" } }, "@algolia/requester-common": { - "version": "4.14.3", - "resolved": "https://registry.npmjs.org/@algolia/requester-common/-/requester-common-4.14.3.tgz", - "integrity": "sha512-RrRzqNyKFDP7IkTuV3XvYGF9cDPn9h6qEDl595lXva3YUk9YSS8+MGZnnkOMHvjkrSCKfoLeLbm/T4tmoIeclw==" + "version": "4.16.0", + "resolved": "https://registry.npmjs.org/@algolia/requester-common/-/requester-common-4.16.0.tgz", + "integrity": "sha512-3Zmcs/iMubcm4zqZ3vZG6Zum8t+hMWxGMzo0/uY2BD8o9q5vMxIYI0c4ocdgQjkXcix189WtZNkgjSOBzSbkdw==" }, "@algolia/requester-node-http": { - "version": "4.14.3", - "resolved": "https://registry.npmjs.org/@algolia/requester-node-http/-/requester-node-http-4.14.3.tgz", - "integrity": "sha512-O5wnPxtDRPuW2U0EaOz9rMMWdlhwP0J0eSL1Z7TtXF8xnUeeUyNJrdhV5uy2CAp6RbhM1VuC3sOJcIR6Av+vbA==", + "version": "4.16.0", + "resolved": "https://registry.npmjs.org/@algolia/requester-node-http/-/requester-node-http-4.16.0.tgz", + "integrity": "sha512-L8JxM2VwZzh8LJ1Zb8TFS6G3icYsCKZsdWW+ahcEs1rGWmyk9SybsOe1MLnjonGBaqPWJkn9NjS7mRdjEmBtKA==", "requires": { - "@algolia/requester-common": "4.14.3" + "@algolia/requester-common": "4.16.0" } }, "@algolia/transporter": { - "version": "4.14.3", - "resolved": "https://registry.npmjs.org/@algolia/transporter/-/transporter-4.14.3.tgz", - "integrity": "sha512-2qlKlKsnGJ008exFRb5RTeTOqhLZj0bkMCMVskxoqWejs2Q2QtWmsiH98hDfpw0fmnyhzHEt0Z7lqxBYp8bW2w==", + "version": "4.16.0", + "resolved": "https://registry.npmjs.org/@algolia/transporter/-/transporter-4.16.0.tgz", + "integrity": "sha512-H9BVB2EAjT65w7XGBNf5drpsW39x2aSZ942j4boSAAJPPlLmjtj5IpAP7UAtsV8g9Beslonh0bLa1XGmE/P0BA==", "requires": { - "@algolia/cache-common": "4.14.3", - "@algolia/logger-common": "4.14.3", - "@algolia/requester-common": "4.14.3" + "@algolia/cache-common": "4.16.0", + "@algolia/logger-common": "4.16.0", + "@algolia/requester-common": "4.16.0" } }, "@ampproject/remapping": { @@ -14038,11 +14102,11 @@ } }, "@babel/runtime": { - "version": "7.19.4", - "resolved": "https://registry.npmjs.org/@babel/runtime/-/runtime-7.19.4.tgz", - "integrity": "sha512-EXpLCrk55f+cYqmHsSR+yD/0gAIMxxA9QK9lnQWzhMCvt+YmoBN7Zx94s++Kv0+unHk39vxNO8t+CMA2WSS3wA==", + "version": "7.21.0", + "resolved": "https://registry.npmjs.org/@babel/runtime/-/runtime-7.21.0.tgz", + "integrity": "sha512-xwII0//EObnq89Ji5AKYQaRYiW/nZ3llSv29d49IuxPhKbtJoLP+9QUUZ4nVragQVtaVGeZrpB+ZtG/Pdy/POw==", "requires": { - "regenerator-runtime": "^0.13.4" + "regenerator-runtime": "^0.13.11" } }, "@babel/runtime-corejs3": { @@ -14114,9 +14178,9 @@ } }, "@docusaurus/core": { - "version": "2.3.1", - "resolved": "https://registry.npmjs.org/@docusaurus/core/-/core-2.3.1.tgz", - "integrity": "sha512-0Jd4jtizqnRAr7svWaBbbrCCN8mzBNd2xFLoT/IM7bGfFie5y58oz97KzXliwiLY3zWjqMXjQcuP1a5VgCv2JA==", + "version": "2.4.0", + "resolved": "https://registry.npmjs.org/@docusaurus/core/-/core-2.4.0.tgz", + "integrity": "sha512-J55/WEoIpRcLf3afO5POHPguVZosKmJEQWKBL+K7TAnfuE7i+Y0NPLlkKtnWCehagGsgTqClfQEexH/UT4kELA==", "requires": { "@babel/core": "^7.18.6", "@babel/generator": "^7.18.7", @@ -14128,13 +14192,13 @@ "@babel/runtime": "^7.18.6", "@babel/runtime-corejs3": "^7.18.6", "@babel/traverse": "^7.18.8", - "@docusaurus/cssnano-preset": "2.3.1", - "@docusaurus/logger": "2.3.1", - "@docusaurus/mdx-loader": "2.3.1", + "@docusaurus/cssnano-preset": "2.4.0", + "@docusaurus/logger": "2.4.0", + "@docusaurus/mdx-loader": "2.4.0", "@docusaurus/react-loadable": "5.5.2", - "@docusaurus/utils": "2.3.1", - "@docusaurus/utils-common": "2.3.1", - "@docusaurus/utils-validation": "2.3.1", + "@docusaurus/utils": "2.4.0", + "@docusaurus/utils-common": "2.4.0", + "@docusaurus/utils-validation": "2.4.0", "@slorber/static-site-generator-webpack-plugin": "^4.0.7", "@svgr/webpack": "^6.2.1", "autoprefixer": "^10.4.7", @@ -14192,9 +14256,9 @@ } }, "@docusaurus/cssnano-preset": { - "version": "2.3.1", - "resolved": "https://registry.npmjs.org/@docusaurus/cssnano-preset/-/cssnano-preset-2.3.1.tgz", - "integrity": "sha512-7mIhAROES6CY1GmCjR4CZkUfjTL6B3u6rKHK0ChQl2d1IevYXq/k/vFgvOrJfcKxiObpMnE9+X6R2Wt1KqxC6w==", + "version": "2.4.0", + "resolved": "https://registry.npmjs.org/@docusaurus/cssnano-preset/-/cssnano-preset-2.4.0.tgz", + "integrity": "sha512-RmdiA3IpsLgZGXRzqnmTbGv43W4OD44PCo+6Q/aYjEM2V57vKCVqNzuafE94jv0z/PjHoXUrjr69SaRymBKYYw==", "requires": { "cssnano-preset-advanced": "^5.3.8", "postcss": "^8.4.14", @@ -14203,23 +14267,23 @@ } }, "@docusaurus/logger": { - "version": "2.3.1", - "resolved": "https://registry.npmjs.org/@docusaurus/logger/-/logger-2.3.1.tgz", - "integrity": "sha512-2lAV/olKKVr9qJhfHFCaqBIl8FgYjbUFwgUnX76+cULwQYss+42ZQ3grHGFvI0ocN2X55WcYe64ellQXz7suqg==", + "version": "2.4.0", + "resolved": "https://registry.npmjs.org/@docusaurus/logger/-/logger-2.4.0.tgz", + "integrity": "sha512-T8+qR4APN+MjcC9yL2Es+xPJ2923S9hpzDmMtdsOcUGLqpCGBbU1vp3AAqDwXtVgFkq+NsEk7sHdVsfLWR/AXw==", "requires": { "chalk": "^4.1.2", "tslib": "^2.4.0" } }, "@docusaurus/mdx-loader": { - "version": "2.3.1", - "resolved": "https://registry.npmjs.org/@docusaurus/mdx-loader/-/mdx-loader-2.3.1.tgz", - "integrity": "sha512-Gzga7OsxQRpt3392K9lv/bW4jGppdLFJh3luKRknCKSAaZrmVkOQv2gvCn8LAOSZ3uRg5No7AgYs/vpL8K94lA==", + "version": "2.4.0", + "resolved": "https://registry.npmjs.org/@docusaurus/mdx-loader/-/mdx-loader-2.4.0.tgz", + "integrity": "sha512-GWoH4izZKOmFoC+gbI2/y8deH/xKLvzz/T5BsEexBye8EHQlwsA7FMrVa48N063bJBH4FUOiRRXxk5rq9cC36g==", "requires": { "@babel/parser": "^7.18.8", "@babel/traverse": "^7.18.8", - "@docusaurus/logger": "2.3.1", - "@docusaurus/utils": "2.3.1", + "@docusaurus/logger": "2.4.0", + "@docusaurus/utils": "2.4.0", "@mdx-js/mdx": "^1.6.22", "escape-html": "^1.0.3", "file-loader": "^6.2.0", @@ -14236,12 +14300,12 @@ } }, "@docusaurus/module-type-aliases": { - "version": "2.3.1", - "resolved": "https://registry.npmjs.org/@docusaurus/module-type-aliases/-/module-type-aliases-2.3.1.tgz", - "integrity": "sha512-6KkxfAVOJqIUynTRb/tphYCl+co3cP0PlHiMDbi+SzmYxMdgIrwYqH9yAnGSDoN6Jk2ZE/JY/Azs/8LPgKP48A==", + "version": "2.4.0", + "resolved": "https://registry.npmjs.org/@docusaurus/module-type-aliases/-/module-type-aliases-2.4.0.tgz", + "integrity": "sha512-YEQO2D3UXs72qCn8Cr+RlycSQXVGN9iEUyuHwTuK4/uL/HFomB2FHSU0vSDM23oLd+X/KibQ3Ez6nGjQLqXcHg==", "requires": { "@docusaurus/react-loadable": "5.5.2", - "@docusaurus/types": "2.3.1", + "@docusaurus/types": "2.4.0", "@types/history": "^4.7.11", "@types/react": "*", "@types/react-router-config": "*", @@ -14251,15 +14315,15 @@ } }, "@docusaurus/plugin-client-redirects": { - "version": "2.3.1", - "resolved": "https://registry.npmjs.org/@docusaurus/plugin-client-redirects/-/plugin-client-redirects-2.3.1.tgz", - "integrity": "sha512-Ye0z36/L8685ni0DIxHqPPaHIXFXiSF90QYiYfpODBX6NxvvveUTyylsDBU1GQhPXPn1bd39QgaOuZ+j9gfaog==", - "requires": { - "@docusaurus/core": "2.3.1", - "@docusaurus/logger": "2.3.1", - "@docusaurus/utils": "2.3.1", - "@docusaurus/utils-common": "2.3.1", - "@docusaurus/utils-validation": "2.3.1", + "version": "2.4.0", + "resolved": "https://registry.npmjs.org/@docusaurus/plugin-client-redirects/-/plugin-client-redirects-2.4.0.tgz", + "integrity": "sha512-HsS+Dc2ZLWhfpjYJ5LIrOB/XfXZcElcC7o1iA4yIVtiFz+LHhwP863fhqbwSJ1c6tNDOYBH3HwbskHrc/PIn7Q==", + "requires": { + "@docusaurus/core": "2.4.0", + "@docusaurus/logger": "2.4.0", + "@docusaurus/utils": "2.4.0", + "@docusaurus/utils-common": "2.4.0", + "@docusaurus/utils-validation": "2.4.0", "eta": "^2.0.0", "fs-extra": "^10.1.0", "lodash": "^4.17.21", @@ -14267,17 +14331,17 @@ } }, "@docusaurus/plugin-content-blog": { - "version": "2.3.1", - "resolved": "https://registry.npmjs.org/@docusaurus/plugin-content-blog/-/plugin-content-blog-2.3.1.tgz", - "integrity": "sha512-f5LjqX+9WkiLyGiQ41x/KGSJ/9bOjSD8lsVhPvYeUYHCtYpuiDKfhZE07O4EqpHkBx4NQdtQDbp+aptgHSTuiw==", - "requires": { - "@docusaurus/core": "2.3.1", - "@docusaurus/logger": "2.3.1", - "@docusaurus/mdx-loader": "2.3.1", - "@docusaurus/types": "2.3.1", - "@docusaurus/utils": "2.3.1", - "@docusaurus/utils-common": "2.3.1", - "@docusaurus/utils-validation": "2.3.1", + "version": "2.4.0", + "resolved": "https://registry.npmjs.org/@docusaurus/plugin-content-blog/-/plugin-content-blog-2.4.0.tgz", + "integrity": "sha512-YwkAkVUxtxoBAIj/MCb4ohN0SCtHBs4AS75jMhPpf67qf3j+U/4n33cELq7567hwyZ6fMz2GPJcVmctzlGGThQ==", + "requires": { + "@docusaurus/core": "2.4.0", + "@docusaurus/logger": "2.4.0", + "@docusaurus/mdx-loader": "2.4.0", + "@docusaurus/types": "2.4.0", + "@docusaurus/utils": "2.4.0", + "@docusaurus/utils-common": "2.4.0", + "@docusaurus/utils-validation": "2.4.0", "cheerio": "^1.0.0-rc.12", "feed": "^4.2.2", "fs-extra": "^10.1.0", @@ -14290,17 +14354,17 @@ } }, "@docusaurus/plugin-content-docs": { - "version": "2.3.1", - "resolved": "https://registry.npmjs.org/@docusaurus/plugin-content-docs/-/plugin-content-docs-2.3.1.tgz", - "integrity": "sha512-DxztTOBEruv7qFxqUtbsqXeNcHqcVEIEe+NQoI1oi2DBmKBhW/o0MIal8lt+9gvmpx3oYtlwmLOOGepxZgJGkw==", - "requires": { - "@docusaurus/core": "2.3.1", - "@docusaurus/logger": "2.3.1", - "@docusaurus/mdx-loader": "2.3.1", - "@docusaurus/module-type-aliases": "2.3.1", - "@docusaurus/types": "2.3.1", - "@docusaurus/utils": "2.3.1", - "@docusaurus/utils-validation": "2.3.1", + "version": "2.4.0", + "resolved": "https://registry.npmjs.org/@docusaurus/plugin-content-docs/-/plugin-content-docs-2.4.0.tgz", + "integrity": "sha512-ic/Z/ZN5Rk/RQo+Io6rUGpToOtNbtPloMR2JcGwC1xT2riMu6zzfSwmBi9tHJgdXH6CB5jG+0dOZZO8QS5tmDg==", + "requires": { + "@docusaurus/core": "2.4.0", + "@docusaurus/logger": "2.4.0", + "@docusaurus/mdx-loader": "2.4.0", + "@docusaurus/module-type-aliases": "2.4.0", + "@docusaurus/types": "2.4.0", + "@docusaurus/utils": "2.4.0", + "@docusaurus/utils-validation": "2.4.0", "@types/react-router-config": "^5.0.6", "combine-promises": "^1.1.0", "fs-extra": "^10.1.0", @@ -14313,100 +14377,100 @@ } }, "@docusaurus/plugin-content-pages": { - "version": "2.3.1", - "resolved": "https://registry.npmjs.org/@docusaurus/plugin-content-pages/-/plugin-content-pages-2.3.1.tgz", - "integrity": "sha512-E80UL6hvKm5VVw8Ka8YaVDtO6kWWDVUK4fffGvkpQ/AJQDOg99LwOXKujPoICC22nUFTsZ2Hp70XvpezCsFQaA==", - "requires": { - "@docusaurus/core": "2.3.1", - "@docusaurus/mdx-loader": "2.3.1", - "@docusaurus/types": "2.3.1", - "@docusaurus/utils": "2.3.1", - "@docusaurus/utils-validation": "2.3.1", + "version": "2.4.0", + "resolved": "https://registry.npmjs.org/@docusaurus/plugin-content-pages/-/plugin-content-pages-2.4.0.tgz", + "integrity": "sha512-Pk2pOeOxk8MeU3mrTU0XLIgP9NZixbdcJmJ7RUFrZp1Aj42nd0RhIT14BGvXXyqb8yTQlk4DmYGAzqOfBsFyGw==", + "requires": { + "@docusaurus/core": "2.4.0", + "@docusaurus/mdx-loader": "2.4.0", + "@docusaurus/types": "2.4.0", + "@docusaurus/utils": "2.4.0", + "@docusaurus/utils-validation": "2.4.0", "fs-extra": "^10.1.0", "tslib": "^2.4.0", "webpack": "^5.73.0" } }, "@docusaurus/plugin-debug": { - "version": "2.3.1", - "resolved": "https://registry.npmjs.org/@docusaurus/plugin-debug/-/plugin-debug-2.3.1.tgz", - "integrity": "sha512-Ujpml1Ppg4geB/2hyu2diWnO49az9U2bxM9Shen7b6qVcyFisNJTkVG2ocvLC7wM1efTJcUhBO6zAku2vKJGMw==", + "version": "2.4.0", + "resolved": "https://registry.npmjs.org/@docusaurus/plugin-debug/-/plugin-debug-2.4.0.tgz", + "integrity": "sha512-KC56DdYjYT7Txyux71vXHXGYZuP6yYtqwClvYpjKreWIHWus5Zt6VNi23rMZv3/QKhOCrN64zplUbdfQMvddBQ==", "requires": { - "@docusaurus/core": "2.3.1", - "@docusaurus/types": "2.3.1", - "@docusaurus/utils": "2.3.1", + "@docusaurus/core": "2.4.0", + "@docusaurus/types": "2.4.0", + "@docusaurus/utils": "2.4.0", "fs-extra": "^10.1.0", "react-json-view": "^1.21.3", "tslib": "^2.4.0" } }, "@docusaurus/plugin-google-analytics": { - "version": "2.3.1", - "resolved": "https://registry.npmjs.org/@docusaurus/plugin-google-analytics/-/plugin-google-analytics-2.3.1.tgz", - "integrity": "sha512-OHip0GQxKOFU8n7gkt3TM4HOYTXPCFDjqKbMClDD3KaDnyTuMp/Zvd9HSr770lLEscgPWIvzhJByRAClqsUWiQ==", + "version": "2.4.0", + "resolved": "https://registry.npmjs.org/@docusaurus/plugin-google-analytics/-/plugin-google-analytics-2.4.0.tgz", + "integrity": "sha512-uGUzX67DOAIglygdNrmMOvEp8qG03X20jMWadeqVQktS6nADvozpSLGx4J0xbkblhJkUzN21WiilsP9iVP+zkw==", "requires": { - "@docusaurus/core": "2.3.1", - "@docusaurus/types": "2.3.1", - "@docusaurus/utils-validation": "2.3.1", + "@docusaurus/core": "2.4.0", + "@docusaurus/types": "2.4.0", + "@docusaurus/utils-validation": "2.4.0", "tslib": "^2.4.0" } }, "@docusaurus/plugin-google-gtag": { - "version": "2.3.1", - "resolved": "https://registry.npmjs.org/@docusaurus/plugin-google-gtag/-/plugin-google-gtag-2.3.1.tgz", - "integrity": "sha512-uXtDhfu4+Hm+oqWUySr3DNI5cWC/rmP6XJyAk83Heor3dFjZqDwCbkX8yWPywkRiWev3Dk/rVF8lEn0vIGVocA==", + "version": "2.4.0", + "resolved": "https://registry.npmjs.org/@docusaurus/plugin-google-gtag/-/plugin-google-gtag-2.4.0.tgz", + "integrity": "sha512-adj/70DANaQs2+TF/nRdMezDXFAV/O/pjAbUgmKBlyOTq5qoMe0Tk4muvQIwWUmiUQxFJe+sKlZGM771ownyOg==", "requires": { - "@docusaurus/core": "2.3.1", - "@docusaurus/types": "2.3.1", - "@docusaurus/utils-validation": "2.3.1", + "@docusaurus/core": "2.4.0", + "@docusaurus/types": "2.4.0", + "@docusaurus/utils-validation": "2.4.0", "tslib": "^2.4.0" } }, "@docusaurus/plugin-google-tag-manager": { - "version": "2.3.1", - "resolved": "https://registry.npmjs.org/@docusaurus/plugin-google-tag-manager/-/plugin-google-tag-manager-2.3.1.tgz", - "integrity": "sha512-Ww2BPEYSqg8q8tJdLYPFFM3FMDBCVhEM4UUqKzJaiRMx3NEoly3qqDRAoRDGdIhlC//Rf0iJV9cWAoq2m6k3sw==", + "version": "2.4.0", + "resolved": "https://registry.npmjs.org/@docusaurus/plugin-google-tag-manager/-/plugin-google-tag-manager-2.4.0.tgz", + "integrity": "sha512-E66uGcYs4l7yitmp/8kMEVQftFPwV9iC62ORh47Veqzs6ExwnhzBkJmwDnwIysHBF1vlxnzET0Fl2LfL5fRR3A==", "requires": { - "@docusaurus/core": "2.3.1", - "@docusaurus/types": "2.3.1", - "@docusaurus/utils-validation": "2.3.1", + "@docusaurus/core": "2.4.0", + "@docusaurus/types": "2.4.0", + "@docusaurus/utils-validation": "2.4.0", "tslib": "^2.4.0" } }, "@docusaurus/plugin-sitemap": { - "version": "2.3.1", - "resolved": "https://registry.npmjs.org/@docusaurus/plugin-sitemap/-/plugin-sitemap-2.3.1.tgz", - "integrity": "sha512-8Yxile/v6QGYV9vgFiYL+8d2N4z4Er3pSHsrD08c5XI8bUXxTppMwjarDUTH/TRTfgAWotRbhJ6WZLyajLpozA==", - "requires": { - "@docusaurus/core": "2.3.1", - "@docusaurus/logger": "2.3.1", - "@docusaurus/types": "2.3.1", - "@docusaurus/utils": "2.3.1", - "@docusaurus/utils-common": "2.3.1", - "@docusaurus/utils-validation": "2.3.1", + "version": "2.4.0", + "resolved": "https://registry.npmjs.org/@docusaurus/plugin-sitemap/-/plugin-sitemap-2.4.0.tgz", + "integrity": "sha512-pZxh+ygfnI657sN8a/FkYVIAmVv0CGk71QMKqJBOfMmDHNN1FeDeFkBjWP49ejBqpqAhjufkv5UWq3UOu2soCw==", + "requires": { + "@docusaurus/core": "2.4.0", + "@docusaurus/logger": "2.4.0", + "@docusaurus/types": "2.4.0", + "@docusaurus/utils": "2.4.0", + "@docusaurus/utils-common": "2.4.0", + "@docusaurus/utils-validation": "2.4.0", "fs-extra": "^10.1.0", "sitemap": "^7.1.1", "tslib": "^2.4.0" } }, "@docusaurus/preset-classic": { - "version": "2.3.1", - "resolved": "https://registry.npmjs.org/@docusaurus/preset-classic/-/preset-classic-2.3.1.tgz", - "integrity": "sha512-OQ5W0AHyfdUk0IldwJ3BlnZ1EqoJuu2L2BMhqLbqwNWdkmzmSUvlFLH1Pe7CZSQgB2YUUC/DnmjbPKk/qQD0lQ==", - "requires": { - "@docusaurus/core": "2.3.1", - "@docusaurus/plugin-content-blog": "2.3.1", - "@docusaurus/plugin-content-docs": "2.3.1", - "@docusaurus/plugin-content-pages": "2.3.1", - "@docusaurus/plugin-debug": "2.3.1", - "@docusaurus/plugin-google-analytics": "2.3.1", - "@docusaurus/plugin-google-gtag": "2.3.1", - "@docusaurus/plugin-google-tag-manager": "2.3.1", - "@docusaurus/plugin-sitemap": "2.3.1", - "@docusaurus/theme-classic": "2.3.1", - "@docusaurus/theme-common": "2.3.1", - "@docusaurus/theme-search-algolia": "2.3.1", - "@docusaurus/types": "2.3.1" + "version": "2.4.0", + "resolved": "https://registry.npmjs.org/@docusaurus/preset-classic/-/preset-classic-2.4.0.tgz", + "integrity": "sha512-/5z5o/9bc6+P5ool2y01PbJhoGddEGsC0ej1MF6mCoazk8A+kW4feoUd68l7Bnv01rCnG3xy7kHUQP97Y0grUA==", + "requires": { + "@docusaurus/core": "2.4.0", + "@docusaurus/plugin-content-blog": "2.4.0", + "@docusaurus/plugin-content-docs": "2.4.0", + "@docusaurus/plugin-content-pages": "2.4.0", + "@docusaurus/plugin-debug": "2.4.0", + "@docusaurus/plugin-google-analytics": "2.4.0", + "@docusaurus/plugin-google-gtag": "2.4.0", + "@docusaurus/plugin-google-tag-manager": "2.4.0", + "@docusaurus/plugin-sitemap": "2.4.0", + "@docusaurus/theme-classic": "2.4.0", + "@docusaurus/theme-common": "2.4.0", + "@docusaurus/theme-search-algolia": "2.4.0", + "@docusaurus/types": "2.4.0" } }, "@docusaurus/react-loadable": { @@ -14419,26 +14483,26 @@ } }, "@docusaurus/theme-classic": { - "version": "2.3.1", - "resolved": "https://registry.npmjs.org/@docusaurus/theme-classic/-/theme-classic-2.3.1.tgz", - "integrity": "sha512-SelSIDvyttb7ZYHj8vEUhqykhAqfOPKk+uP0z85jH72IMC58e7O8DIlcAeBv+CWsLbNIl9/Hcg71X0jazuxJug==", - "requires": { - "@docusaurus/core": "2.3.1", - "@docusaurus/mdx-loader": "2.3.1", - "@docusaurus/module-type-aliases": "2.3.1", - "@docusaurus/plugin-content-blog": "2.3.1", - "@docusaurus/plugin-content-docs": "2.3.1", - "@docusaurus/plugin-content-pages": "2.3.1", - "@docusaurus/theme-common": "2.3.1", - "@docusaurus/theme-translations": "2.3.1", - "@docusaurus/types": "2.3.1", - "@docusaurus/utils": "2.3.1", - "@docusaurus/utils-common": "2.3.1", - "@docusaurus/utils-validation": "2.3.1", + "version": "2.4.0", + "resolved": "https://registry.npmjs.org/@docusaurus/theme-classic/-/theme-classic-2.4.0.tgz", + "integrity": "sha512-GMDX5WU6Z0OC65eQFgl3iNNEbI9IMJz9f6KnOyuMxNUR6q0qVLsKCNopFUDfFNJ55UU50o7P7o21yVhkwpfJ9w==", + "requires": { + "@docusaurus/core": "2.4.0", + "@docusaurus/mdx-loader": "2.4.0", + "@docusaurus/module-type-aliases": "2.4.0", + "@docusaurus/plugin-content-blog": "2.4.0", + "@docusaurus/plugin-content-docs": "2.4.0", + "@docusaurus/plugin-content-pages": "2.4.0", + "@docusaurus/theme-common": "2.4.0", + "@docusaurus/theme-translations": "2.4.0", + "@docusaurus/types": "2.4.0", + "@docusaurus/utils": "2.4.0", + "@docusaurus/utils-common": "2.4.0", + "@docusaurus/utils-validation": "2.4.0", "@mdx-js/react": "^1.6.22", "clsx": "^1.2.1", "copy-text-to-clipboard": "^3.0.1", - "infima": "0.2.0-alpha.42", + "infima": "0.2.0-alpha.43", "lodash": "^4.17.21", "nprogress": "^0.2.0", "postcss": "^8.4.14", @@ -14451,16 +14515,17 @@ } }, "@docusaurus/theme-common": { - "version": "2.3.1", - "resolved": "https://registry.npmjs.org/@docusaurus/theme-common/-/theme-common-2.3.1.tgz", - "integrity": "sha512-RYmYl2OR2biO+yhmW1aS5FyEvnrItPINa+0U2dMxcHpah8reSCjQ9eJGRmAgkZFchV1+aIQzXOI1K7LCW38O0g==", - "requires": { - "@docusaurus/mdx-loader": "2.3.1", - "@docusaurus/module-type-aliases": "2.3.1", - "@docusaurus/plugin-content-blog": "2.3.1", - "@docusaurus/plugin-content-docs": "2.3.1", - "@docusaurus/plugin-content-pages": "2.3.1", - "@docusaurus/utils": "2.3.1", + "version": "2.4.0", + "resolved": "https://registry.npmjs.org/@docusaurus/theme-common/-/theme-common-2.4.0.tgz", + "integrity": "sha512-IkG/l5f/FLY6cBIxtPmFnxpuPzc5TupuqlOx+XDN+035MdQcAh8wHXXZJAkTeYDeZ3anIUSUIvWa7/nRKoQEfg==", + "requires": { + "@docusaurus/mdx-loader": "2.4.0", + "@docusaurus/module-type-aliases": "2.4.0", + "@docusaurus/plugin-content-blog": "2.4.0", + "@docusaurus/plugin-content-docs": "2.4.0", + "@docusaurus/plugin-content-pages": "2.4.0", + "@docusaurus/utils": "2.4.0", + "@docusaurus/utils-common": "2.4.0", "@types/history": "^4.7.11", "@types/react": "*", "@types/react-router-config": "*", @@ -14473,18 +14538,18 @@ } }, "@docusaurus/theme-search-algolia": { - "version": "2.3.1", - "resolved": "https://registry.npmjs.org/@docusaurus/theme-search-algolia/-/theme-search-algolia-2.3.1.tgz", - "integrity": "sha512-JdHaRqRuH1X++g5fEMLnq7OtULSGQdrs9AbhcWRQ428ZB8/HOiaN6mj3hzHvcD3DFgu7koIVtWPQnvnN7iwzHA==", + "version": "2.4.0", + "resolved": "https://registry.npmjs.org/@docusaurus/theme-search-algolia/-/theme-search-algolia-2.4.0.tgz", + "integrity": "sha512-pPCJSCL1Qt4pu/Z0uxBAuke0yEBbxh0s4fOvimna7TEcBLPq0x06/K78AaABXrTVQM6S0vdocFl9EoNgU17hqA==", "requires": { "@docsearch/react": "^3.1.1", - "@docusaurus/core": "2.3.1", - "@docusaurus/logger": "2.3.1", - "@docusaurus/plugin-content-docs": "2.3.1", - "@docusaurus/theme-common": "2.3.1", - "@docusaurus/theme-translations": "2.3.1", - "@docusaurus/utils": "2.3.1", - "@docusaurus/utils-validation": "2.3.1", + "@docusaurus/core": "2.4.0", + "@docusaurus/logger": "2.4.0", + "@docusaurus/plugin-content-docs": "2.4.0", + "@docusaurus/theme-common": "2.4.0", + "@docusaurus/theme-translations": "2.4.0", + "@docusaurus/utils": "2.4.0", + "@docusaurus/utils-validation": "2.4.0", "algoliasearch": "^4.13.1", "algoliasearch-helper": "^3.10.0", "clsx": "^1.2.1", @@ -14496,18 +14561,18 @@ } }, "@docusaurus/theme-translations": { - "version": "2.3.1", - "resolved": "https://registry.npmjs.org/@docusaurus/theme-translations/-/theme-translations-2.3.1.tgz", - "integrity": "sha512-BsBZzAewJabVhoGG1Ij2u4pMS3MPW6gZ6sS4pc+Y7czevRpzxoFNJXRtQDVGe7mOpv/MmRmqg4owDK+lcOTCVQ==", + "version": "2.4.0", + "resolved": "https://registry.npmjs.org/@docusaurus/theme-translations/-/theme-translations-2.4.0.tgz", + "integrity": "sha512-kEoITnPXzDPUMBHk3+fzEzbopxLD3fR5sDoayNH0vXkpUukA88/aDL1bqkhxWZHA3LOfJ3f0vJbOwmnXW5v85Q==", "requires": { "fs-extra": "^10.1.0", "tslib": "^2.4.0" } }, "@docusaurus/types": { - "version": "2.3.1", - "resolved": "https://registry.npmjs.org/@docusaurus/types/-/types-2.3.1.tgz", - "integrity": "sha512-PREbIRhTaNNY042qmfSE372Jb7djZt+oVTZkoqHJ8eff8vOIc2zqqDqBVc5BhOfpZGPTrE078yy/torUEZy08A==", + "version": "2.4.0", + "resolved": "https://registry.npmjs.org/@docusaurus/types/-/types-2.4.0.tgz", + "integrity": "sha512-xaBXr+KIPDkIaef06c+i2HeTqVNixB7yFut5fBXPGI2f1rrmEV2vLMznNGsFwvZ5XmA3Quuefd4OGRkdo97Dhw==", "requires": { "@types/history": "^4.7.11", "@types/react": "*", @@ -14520,11 +14585,11 @@ } }, "@docusaurus/utils": { - "version": "2.3.1", - "resolved": "https://registry.npmjs.org/@docusaurus/utils/-/utils-2.3.1.tgz", - "integrity": "sha512-9WcQROCV0MmrpOQDXDGhtGMd52DHpSFbKLfkyaYumzbTstrbA5pPOtiGtxK1nqUHkiIv8UwexS54p0Vod2I1lg==", + "version": "2.4.0", + "resolved": "https://registry.npmjs.org/@docusaurus/utils/-/utils-2.4.0.tgz", + "integrity": "sha512-89hLYkvtRX92j+C+ERYTuSUK6nF9bGM32QThcHPg2EDDHVw6FzYQXmX6/p+pU5SDyyx5nBlE4qXR92RxCAOqfg==", "requires": { - "@docusaurus/logger": "2.3.1", + "@docusaurus/logger": "2.4.0", "@svgr/webpack": "^6.2.1", "escape-string-regexp": "^4.0.0", "file-loader": "^6.2.0", @@ -14543,20 +14608,20 @@ } }, "@docusaurus/utils-common": { - "version": "2.3.1", - "resolved": "https://registry.npmjs.org/@docusaurus/utils-common/-/utils-common-2.3.1.tgz", - "integrity": "sha512-pVlRpXkdNcxmKNxAaB1ya2hfCEvVsLDp2joeM6K6uv55Oc5nVIqgyYSgSNKZyMdw66NnvMfsu0RBylcwZQKo9A==", + "version": "2.4.0", + "resolved": "https://registry.npmjs.org/@docusaurus/utils-common/-/utils-common-2.4.0.tgz", + "integrity": "sha512-zIMf10xuKxddYfLg5cS19x44zud/E9I7lj3+0bv8UIs0aahpErfNrGhijEfJpAfikhQ8tL3m35nH3hJ3sOG82A==", "requires": { "tslib": "^2.4.0" } }, "@docusaurus/utils-validation": { - "version": "2.3.1", - "resolved": "https://registry.npmjs.org/@docusaurus/utils-validation/-/utils-validation-2.3.1.tgz", - "integrity": "sha512-7n0208IG3k1HVTByMHlZoIDjjOFC8sbViHVXJx0r3Q+3Ezrx+VQ1RZ/zjNn6lT+QBCRCXlnlaoJ8ug4HIVgQ3w==", + "version": "2.4.0", + "resolved": "https://registry.npmjs.org/@docusaurus/utils-validation/-/utils-validation-2.4.0.tgz", + "integrity": "sha512-IrBsBbbAp6y7mZdJx4S4pIA7dUyWSA0GNosPk6ZJ0fX3uYIEQgcQSGIgTeSC+8xPEx3c16o03en1jSDpgQgz/w==", "requires": { - "@docusaurus/logger": "2.3.1", - "@docusaurus/utils": "2.3.1", + "@docusaurus/logger": "2.4.0", + "@docusaurus/utils": "2.4.0", "joi": "^17.6.0", "js-yaml": "^4.1.0", "tslib": "^2.4.0" @@ -15397,26 +15462,6 @@ } } }, - "acorn": { - "version": "7.4.1", - "resolved": "https://registry.npmjs.org/acorn/-/acorn-7.4.1.tgz", - "integrity": "sha512-nQyp0o1/mNdbTO1PO6kHkwSrmgZ0MT/jCCpNiwbUjGoRN4dlBhqJtoQuCnEOKzgTVwg0ZWiCoQy6SxMebQVh8A==" - }, - "acorn-node": { - "version": "1.8.2", - "resolved": "https://registry.npmjs.org/acorn-node/-/acorn-node-1.8.2.tgz", - "integrity": "sha512-8mt+fslDufLYntIoPAaIMUe/lrbrehIiwmR3t2k9LljIzoigEPF27eLk2hy8zSGzmR/ogr7zbRKINMo1u0yh5A==", - "requires": { - "acorn": "^7.0.0", - "acorn-walk": "^7.0.0", - "xtend": "^4.0.2" - } - }, - "acorn-walk": { - "version": "7.2.0", - "resolved": "https://registry.npmjs.org/acorn-walk/-/acorn-walk-7.2.0.tgz", - "integrity": "sha512-OPdCF6GsMIP+Az+aWfAAOEt2/+iVDKE7oy6lJ098aoe59oAmK76qV6Gw60SbZ8jHuG2wH058GF4pLFbYamYrVA==" - }, "address": { "version": "1.2.1", "resolved": "https://registry.npmjs.org/address/-/address-1.2.1.tgz", @@ -15475,30 +15520,30 @@ "requires": {} }, "algoliasearch": { - "version": "4.14.3", - "resolved": "https://registry.npmjs.org/algoliasearch/-/algoliasearch-4.14.3.tgz", - "integrity": "sha512-GZTEuxzfWbP/vr7ZJfGzIl8fOsoxN916Z6FY2Egc9q2TmZ6hvq5KfAxY89pPW01oW/2HDEKA8d30f9iAH9eXYg==", - "requires": { - "@algolia/cache-browser-local-storage": "4.14.3", - "@algolia/cache-common": "4.14.3", - "@algolia/cache-in-memory": "4.14.3", - "@algolia/client-account": "4.14.3", - "@algolia/client-analytics": "4.14.3", - "@algolia/client-common": "4.14.3", - "@algolia/client-personalization": "4.14.3", - "@algolia/client-search": "4.14.3", - "@algolia/logger-common": "4.14.3", - "@algolia/logger-console": "4.14.3", - "@algolia/requester-browser-xhr": "4.14.3", - "@algolia/requester-common": "4.14.3", - "@algolia/requester-node-http": "4.14.3", - "@algolia/transporter": "4.14.3" + "version": "4.16.0", + "resolved": "https://registry.npmjs.org/algoliasearch/-/algoliasearch-4.16.0.tgz", + "integrity": "sha512-HAjKJ6bBblaXqO4dYygF4qx251GuJ6zCZt+qbJ+kU7sOC+yc84pawEjVpJByh+cGP2APFCsao2Giz50cDlKNPA==", + "requires": { + "@algolia/cache-browser-local-storage": "4.16.0", + "@algolia/cache-common": "4.16.0", + "@algolia/cache-in-memory": "4.16.0", + "@algolia/client-account": "4.16.0", + "@algolia/client-analytics": "4.16.0", + "@algolia/client-common": "4.16.0", + "@algolia/client-personalization": "4.16.0", + "@algolia/client-search": "4.16.0", + "@algolia/logger-common": "4.16.0", + "@algolia/logger-console": "4.16.0", + "@algolia/requester-browser-xhr": "4.16.0", + "@algolia/requester-common": "4.16.0", + "@algolia/requester-node-http": "4.16.0", + "@algolia/transporter": "4.16.0" } }, "algoliasearch-helper": { - "version": "3.11.3", - "resolved": "https://registry.npmjs.org/algoliasearch-helper/-/algoliasearch-helper-3.11.3.tgz", - "integrity": "sha512-TbaEvLwiuGygHQIB8y+OsJKQQ40+JKUua5B91X66tMUHyyhbNHvqyr0lqd3wCoyKx7WybyQrC0WJvzoIeh24Aw==", + "version": "3.12.0", + "resolved": "https://registry.npmjs.org/algoliasearch-helper/-/algoliasearch-helper-3.12.0.tgz", + "integrity": "sha512-/j1U3PEwdan0n6P/QqSnSpNSLC5+cEMvyljd5CnmNmUjDlGrys+vFEOwjVEnqELIiAGMHEA/Nl3CiKVFBUYqyQ==", "requires": { "@algolia/events": "^4.0.1" } @@ -15546,6 +15591,11 @@ "color-convert": "^2.0.1" } }, + "any-promise": { + "version": "1.3.0", + "resolved": "https://registry.npmjs.org/any-promise/-/any-promise-1.3.0.tgz", + "integrity": "sha512-7UvmKalWRt1wgjL1RrGxoSJW/0QZFIegpeGvZG9kjp8vrRu55XTHbwnqq2GpXm9uLbcuhxm3IqX9OB4MZR1b2A==" + }, "anymatch": { "version": "3.1.2", "resolved": "https://registry.npmjs.org/anymatch/-/anymatch-3.1.2.tgz", @@ -16208,9 +16258,9 @@ "integrity": "sha512-QADzlaHc8icV8I7vbaJXJwod9HWYp8uCqf1xa4OfNu1T7JVxQIrUgOWtHdNDtPiywmFbiS12VjotIXLrKM3orQ==" }, "copy-text-to-clipboard": { - "version": "3.0.1", - "resolved": "https://registry.npmjs.org/copy-text-to-clipboard/-/copy-text-to-clipboard-3.0.1.tgz", - "integrity": "sha512-rvVsHrpFcL4F2P8ihsoLdFHmd404+CMg71S756oRSeQgqk51U3kicGdnvfkrxva0xXH92SjGS62B0XIJsbh+9Q==" + "version": "3.1.0", + "resolved": "https://registry.npmjs.org/copy-text-to-clipboard/-/copy-text-to-clipboard-3.1.0.tgz", + "integrity": "sha512-PFM6BnjLnOON/lB3ta/Jg7Ywsv+l9kQGD4TWDCSlRBGmqnnTM5MrDkhAFgw+8HZt0wW6Q2BBE4cmy9sq+s9Qng==" }, "copy-webpack-plugin": { "version": "11.0.0", @@ -16458,12 +16508,12 @@ } }, "cssnano-preset-advanced": { - "version": "5.3.9", - "resolved": "https://registry.npmjs.org/cssnano-preset-advanced/-/cssnano-preset-advanced-5.3.9.tgz", - "integrity": "sha512-njnh4pp1xCsibJcEHnWZb4EEzni0ePMqPuPNyuWT4Z+YeXmsgqNuTPIljXFEXhxGsWs9183JkXgHxc1TcsahIg==", + "version": "5.3.10", + "resolved": "https://registry.npmjs.org/cssnano-preset-advanced/-/cssnano-preset-advanced-5.3.10.tgz", + "integrity": "sha512-fnYJyCS9jgMU+cmHO1rPSPf9axbQyD7iUhLO5Df6O4G+fKIOMps+ZbU0PdGFejFBBZ3Pftf18fn1eG7MAPUSWQ==", "requires": { "autoprefixer": "^10.4.12", - "cssnano-preset-default": "^5.2.13", + "cssnano-preset-default": "^5.2.14", "postcss-discard-unused": "^5.1.0", "postcss-merge-idents": "^5.1.1", "postcss-reduce-idents": "^5.2.0", @@ -16471,21 +16521,21 @@ } }, "cssnano-preset-default": { - "version": "5.2.13", - "resolved": "https://registry.npmjs.org/cssnano-preset-default/-/cssnano-preset-default-5.2.13.tgz", - "integrity": "sha512-PX7sQ4Pb+UtOWuz8A1d+Rbi+WimBIxJTRyBdgGp1J75VU0r/HFQeLnMYgHiCAp6AR4rqrc7Y4R+1Rjk3KJz6DQ==", + "version": "5.2.14", + "resolved": "https://registry.npmjs.org/cssnano-preset-default/-/cssnano-preset-default-5.2.14.tgz", + "integrity": "sha512-t0SFesj/ZV2OTylqQVOrFgEh5uanxbO6ZAdeCrNsUQ6fVuXwYTxJPNAGvGTxHbD68ldIJNec7PyYZDBrfDQ+6A==", "requires": { "css-declaration-sorter": "^6.3.1", "cssnano-utils": "^3.1.0", "postcss-calc": "^8.2.3", - "postcss-colormin": "^5.3.0", + "postcss-colormin": "^5.3.1", "postcss-convert-values": "^5.1.3", "postcss-discard-comments": "^5.1.2", "postcss-discard-duplicates": "^5.1.0", "postcss-discard-empty": "^5.1.1", "postcss-discard-overridden": "^5.1.0", "postcss-merge-longhand": "^5.1.7", - "postcss-merge-rules": "^5.1.3", + "postcss-merge-rules": "^5.1.4", "postcss-minify-font-values": "^5.1.0", "postcss-minify-gradients": "^5.1.1", "postcss-minify-params": "^5.1.4", @@ -16500,7 +16550,7 @@ "postcss-normalize-url": "^5.1.0", "postcss-normalize-whitespace": "^5.1.1", "postcss-ordered-values": "^5.1.3", - "postcss-reduce-initial": "^5.1.1", + "postcss-reduce-initial": "^5.1.2", "postcss-reduce-transforms": "^5.1.0", "postcss-svgo": "^5.1.0", "postcss-unique-selectors": "^5.1.1" @@ -16578,11 +16628,6 @@ "object-keys": "^1.1.1" } }, - "defined": { - "version": "1.0.0", - "resolved": "https://registry.npmjs.org/defined/-/defined-1.0.0.tgz", - "integrity": "sha512-Y2caI5+ZwS5c3RiNDJ6u53VhQHv+hHKwhkI1iHvceKUHw9Df6EK2zRLfjejRgMuCuxK7PfSWIMwWecceVvThjQ==" - }, "del": { "version": "6.1.1", "resolved": "https://registry.npmjs.org/del/-/del-6.1.1.tgz", @@ -16654,16 +16699,6 @@ } } }, - "detective": { - "version": "5.2.1", - "resolved": "https://registry.npmjs.org/detective/-/detective-5.2.1.tgz", - "integrity": "sha512-v9XE1zRnz1wRtgurGu0Bs8uHKFSTdteYZNbIPFVhUZ39L/S79ppMpdmVOZAnoz1jfEFodc48n6MX483Xo3t1yw==", - "requires": { - "acorn-node": "^1.8.2", - "defined": "^1.0.0", - "minimist": "^1.2.6" - } - }, "didyoumean": { "version": "1.2.2", "resolved": "https://registry.npmjs.org/didyoumean/-/didyoumean-1.2.2.tgz", @@ -17209,9 +17244,9 @@ } }, "flux": { - "version": "4.0.3", - "resolved": "https://registry.npmjs.org/flux/-/flux-4.0.3.tgz", - "integrity": "sha512-yKAbrp7JhZhj6uiT1FTuVMlIAT1J4jqEyBpFApi1kxpGZCvacMVc/t1pMQyotqHhAgvoE3bNvAykhCo2CLjnYw==", + "version": "4.0.4", + "resolved": "https://registry.npmjs.org/flux/-/flux-4.0.4.tgz", + "integrity": "sha512-NCj3XlayA2UsapRpM7va6wU1+9rE5FIL7qoMcmxWHRzbp0yujihMBm9BBHZ1MDIk5h5o2Bl6eGiCe8rYELAmYw==", "requires": { "fbemitter": "^3.0.0", "fbjs": "^3.0.1" @@ -17740,14 +17775,14 @@ } }, "htmlparser2": { - "version": "8.0.1", - "resolved": "https://registry.npmjs.org/htmlparser2/-/htmlparser2-8.0.1.tgz", - "integrity": "sha512-4lVbmc1diZC7GUJQtRQ5yBAeUCL1exyMwmForWkRLnwyzWBFxN633SALPMGYaWZvKe9j1pRZJpauvmxENSp/EA==", + "version": "8.0.2", + "resolved": "https://registry.npmjs.org/htmlparser2/-/htmlparser2-8.0.2.tgz", + "integrity": "sha512-GYdjWKDkbRLkZ5geuHs5NY1puJ+PXwP7+fHPRz06Eirsb9ugf6d8kkXav6ADhcODhFFPMIXyxkxSuMf3D6NCFA==", "requires": { "domelementtype": "^2.3.0", - "domhandler": "^5.0.2", + "domhandler": "^5.0.3", "domutils": "^3.0.1", - "entities": "^4.3.0" + "entities": "^4.4.0" } }, "http-cache-semantics": { @@ -17868,9 +17903,9 @@ "integrity": "sha512-EdDDZu4A2OyIK7Lr/2zG+w5jmbuk1DVBnEwREQvBzspBJkCEbRa8GxU1lghYcaGJCnRWibjDXlq779X1/y5xwg==" }, "infima": { - "version": "0.2.0-alpha.42", - "resolved": "https://registry.npmjs.org/infima/-/infima-0.2.0-alpha.42.tgz", - "integrity": "sha512-ift8OXNbQQwtbIt6z16KnSWP7uJ/SysSMFI4F87MNRTicypfl4Pv3E2OGVv6N3nSZFJvA8imYulCBS64iyHYww==" + "version": "0.2.0-alpha.43", + "resolved": "https://registry.npmjs.org/infima/-/infima-0.2.0-alpha.43.tgz", + "integrity": "sha512-2uw57LvUqW0rK/SWYnd/2rRfxNA5DDNOh33jxF7fy46VWoNhGxiUQyVZHbBMjQ33mQem0cjdDVwgWVAmlRfgyQ==" }, "inflight": { "version": "1.0.6", @@ -18146,6 +18181,11 @@ } } }, + "jiti": { + "version": "1.18.2", + "resolved": "https://registry.npmjs.org/jiti/-/jiti-1.18.2.tgz", + "integrity": "sha512-QAdOptna2NYiSSpv0O/BwoHBSmz4YhpzJHyi+fnMRTXFjp7B8i/YG5Z8IfusxB1ufjcD2Sre1F3R+nX3fvy7gg==" + }, "joi": { "version": "17.6.2", "resolved": "https://registry.npmjs.org/joi/-/joi-17.6.2.tgz", @@ -18551,10 +18591,20 @@ "thunky": "^1.0.2" } }, + "mz": { + "version": "2.7.0", + "resolved": "https://registry.npmjs.org/mz/-/mz-2.7.0.tgz", + "integrity": "sha512-z81GNO7nnYMEhrGh9LeymoE4+Yr0Wn5McHIZMK5cfQCl+NDX08sCZgUc9/6MHni9IWuFLm1Z3HTCXu2z9fN62Q==", + "requires": { + "any-promise": "^1.0.0", + "object-assign": "^4.0.1", + "thenify-all": "^1.0.0" + } + }, "nanoid": { - "version": "3.3.4", - "resolved": "https://registry.npmjs.org/nanoid/-/nanoid-3.3.4.tgz", - "integrity": "sha512-MqBkQh/OHTS2egovRtLk45wEyNXwF+cokD+1YPf9u5VfJiRdAiRwB2froX5Co9Rh20xs4siNPm8naNotSD6RBw==" + "version": "3.3.6", + "resolved": "https://registry.npmjs.org/nanoid/-/nanoid-3.3.6.tgz", + "integrity": "sha512-BGcqMMJuToF7i1rt+2PWSNVnWIkGCU78jBG3RxO/bZlnZPK2Cmi2QaffxGO/2RvWi9sL+FAiRiXMgsyxQ1DIDA==" }, "negotiator": { "version": "0.6.3", @@ -18908,6 +18958,11 @@ "resolved": "https://registry.npmjs.org/pify/-/pify-2.3.0.tgz", "integrity": "sha512-udgsAY+fTnvv7kI7aaxbqwWNb0AHiB0qBO89PZKPkoTmGOgdbrHDKD+0B2X4uTfJ/FT1R09r9gTsjUjNJotuog==" }, + "pirates": { + "version": "4.0.5", + "resolved": "https://registry.npmjs.org/pirates/-/pirates-4.0.5.tgz", + "integrity": "sha512-8V9+HQPupnaXMA23c5hvl69zXvTwTzyAYasnkb0Tts4XvO4CliqONMOnvlq26rkhLC3nWDFBJf73LU1e1VZLaQ==" + }, "pkg-dir": { "version": "4.2.0", "resolved": "https://registry.npmjs.org/pkg-dir/-/pkg-dir-4.2.0.tgz", @@ -18957,11 +19012,11 @@ } }, "postcss": { - "version": "8.4.21", - "resolved": "https://registry.npmjs.org/postcss/-/postcss-8.4.21.tgz", - "integrity": "sha512-tP7u/Sn/dVxK2NnruI4H9BG+x+Wxz6oeZ1cJ8P6G/PZY0IKk4k/63TDsQf2kQq3+qoJeLm2kIBUNlZe3zgb4Zg==", + "version": "8.4.22", + "resolved": "https://registry.npmjs.org/postcss/-/postcss-8.4.22.tgz", + "integrity": "sha512-XseknLAfRHzVWjCEtdviapiBtfLdgyzExD50Rg2ePaucEesyh8Wv4VPdW0nbyDa1ydbrAxV19jvMT4+LFmcNUA==", "requires": { - "nanoid": "^3.3.4", + "nanoid": "^3.3.6", "picocolors": "^1.0.0", "source-map-js": "^1.0.2" } @@ -18976,11 +19031,11 @@ } }, "postcss-colormin": { - "version": "5.3.0", - "resolved": "https://registry.npmjs.org/postcss-colormin/-/postcss-colormin-5.3.0.tgz", - "integrity": "sha512-WdDO4gOFG2Z8n4P8TWBpshnL3JpmNmJwdnfP2gbk2qBA8PWwOYcmjmI/t3CmMeL72a7Hkd+x/Mg9O2/0rD54Pg==", + "version": "5.3.1", + "resolved": "https://registry.npmjs.org/postcss-colormin/-/postcss-colormin-5.3.1.tgz", + "integrity": "sha512-UsWQG0AqTFQmpBegeLLc1+c3jIqBNB0zlDGRWR+dQ3pRKJL1oeMzyqmH3o2PIfn9MBdNrVPWhDbT769LxCTLJQ==", "requires": { - "browserslist": "^4.16.6", + "browserslist": "^4.21.4", "caniuse-api": "^3.0.0", "colord": "^2.9.1", "postcss-value-parser": "^4.2.0" @@ -19083,9 +19138,9 @@ } }, "postcss-merge-rules": { - "version": "5.1.3", - "resolved": "https://registry.npmjs.org/postcss-merge-rules/-/postcss-merge-rules-5.1.3.tgz", - "integrity": "sha512-LbLd7uFC00vpOuMvyZop8+vvhnfRGpp2S+IMQKeuOZZapPRY4SMq5ErjQeHbHsjCUgJkRNrlU+LmxsKIqPKQlA==", + "version": "5.1.4", + "resolved": "https://registry.npmjs.org/postcss-merge-rules/-/postcss-merge-rules-5.1.4.tgz", + "integrity": "sha512-0R2IuYpgU93y9lhVbO/OylTtKMVcHb67zjWIfCiKR9rWL3GUk1677LAqD/BcHizukdZEjT8Ru3oHRoAYoJy44g==", "requires": { "browserslist": "^4.21.4", "caniuse-api": "^3.0.0", @@ -19259,9 +19314,9 @@ } }, "postcss-reduce-initial": { - "version": "5.1.1", - "resolved": "https://registry.npmjs.org/postcss-reduce-initial/-/postcss-reduce-initial-5.1.1.tgz", - "integrity": "sha512-//jeDqWcHPuXGZLoolFrUXBDyuEGbr9S2rMo19bkTIjBQ4PqkaO+oI8wua5BOUxpfi97i3PCoInsiFIEBfkm9w==", + "version": "5.1.2", + "resolved": "https://registry.npmjs.org/postcss-reduce-initial/-/postcss-reduce-initial-5.1.2.tgz", + "integrity": "sha512-dE/y2XRaqAi6OvjzD22pjTUQ8eOfc6m/natGHgKFBK9DxFmIm69YmaRVQrGgFlEfc1HePIurY0TmDeROK05rIg==", "requires": { "browserslist": "^4.21.4", "caniuse-api": "^3.0.0" @@ -19708,11 +19763,11 @@ } }, "react-textarea-autosize": { - "version": "8.4.0", - "resolved": "https://registry.npmjs.org/react-textarea-autosize/-/react-textarea-autosize-8.4.0.tgz", - "integrity": "sha512-YrTFaEHLgJsi8sJVYHBzYn+mkP3prGkmP2DKb/tm0t7CLJY5t1Rxix8070LAKb0wby7bl/lf2EeHkuMihMZMwQ==", + "version": "8.4.1", + "resolved": "https://registry.npmjs.org/react-textarea-autosize/-/react-textarea-autosize-8.4.1.tgz", + "integrity": "sha512-aD2C+qK6QypknC+lCMzteOdIjoMbNlgSFmJjCV+DrfTPwp59i/it9mMNf2HDzvRjQgKAyBDPyLJhcrzElf2U4Q==", "requires": { - "@babel/runtime": "^7.10.2", + "@babel/runtime": "^7.20.13", "use-composed-ref": "^1.3.0", "use-latest": "^1.2.1" } @@ -19778,9 +19833,9 @@ } }, "regenerator-runtime": { - "version": "0.13.9", - "resolved": "https://registry.npmjs.org/regenerator-runtime/-/regenerator-runtime-0.13.9.tgz", - "integrity": "sha512-p3VT+cOEgxFsRRA9X4lkI1E+k2/CtnKtU4gcxyaCUreilL/vqI6CdZ3wxVUx3UOUg+gnUOQQcRI7BmSI656MYA==" + "version": "0.13.11", + "resolved": "https://registry.npmjs.org/regenerator-runtime/-/regenerator-runtime-0.13.11.tgz", + "integrity": "sha512-kY1AZVr2Ra+t+piVaJ4gxaFaReZVH40AKNo7UCX6W+dEwBo/2oZJzqfuN1qLq1oL45o56cPaTXELwrTh8Fpggg==" }, "regenerator-transform": { "version": "0.15.0", @@ -20689,6 +20744,39 @@ "postcss-selector-parser": "^6.0.4" } }, + "sucrase": { + "version": "3.31.0", + "resolved": "https://registry.npmjs.org/sucrase/-/sucrase-3.31.0.tgz", + "integrity": "sha512-6QsHnkqyVEzYcaiHsOKkzOtOgdJcb8i54x6AV2hDwyZcY9ZyykGZVw6L/YN98xC0evwTP6utsWWrKRaa8QlfEQ==", + "requires": { + "commander": "^4.0.0", + "glob": "7.1.6", + "lines-and-columns": "^1.1.6", + "mz": "^2.7.0", + "pirates": "^4.0.1", + "ts-interface-checker": "^0.1.9" + }, + "dependencies": { + "commander": { + "version": "4.1.1", + "resolved": "https://registry.npmjs.org/commander/-/commander-4.1.1.tgz", + "integrity": "sha512-NOKm8xhkzAjzFx8B2v5OAHT+u5pRQc2UCa2Vq9jYL/31o2wi9mxBA7LIFs3sV5VSC49z6pEhfbMULvShKj26WA==" + }, + "glob": { + "version": "7.1.6", + "resolved": "https://registry.npmjs.org/glob/-/glob-7.1.6.tgz", + "integrity": "sha512-LwaxwyZ72Lk7vZINtNNrywX0ZuLyStrdDtabefZKAY5ZGJhVtgdznluResxNmPitE0SAO+O26sWTHeKSI2wMBA==", + "requires": { + "fs.realpath": "^1.0.0", + "inflight": "^1.0.4", + "inherits": "2", + "minimatch": "^3.0.4", + "once": "^1.3.0", + "path-is-absolute": "^1.0.0" + } + } + } + }, "supports-color": { "version": "7.2.0", "resolved": "https://registry.npmjs.org/supports-color/-/supports-color-7.2.0.tgz", @@ -20774,19 +20862,19 @@ } }, "tailwindcss": { - "version": "3.2.7", - "resolved": "https://registry.npmjs.org/tailwindcss/-/tailwindcss-3.2.7.tgz", - "integrity": "sha512-B6DLqJzc21x7wntlH/GsZwEXTBttVSl1FtCzC8WP4oBc/NKef7kaax5jeihkkCEWc831/5NDJ9gRNDK6NEioQQ==", + "version": "3.3.1", + "resolved": "https://registry.npmjs.org/tailwindcss/-/tailwindcss-3.3.1.tgz", + "integrity": "sha512-Vkiouc41d4CEq0ujXl6oiGFQ7bA3WEhUZdTgXAhtKxSy49OmKs8rEfQmupsfF0IGW8fv2iQkp1EVUuapCFrZ9g==", "requires": { "arg": "^5.0.2", "chokidar": "^3.5.3", "color-name": "^1.1.4", - "detective": "^5.2.1", "didyoumean": "^1.2.2", "dlv": "^1.1.3", "fast-glob": "^3.2.12", "glob-parent": "^6.0.2", "is-glob": "^4.0.3", + "jiti": "^1.17.2", "lilconfig": "^2.0.6", "micromatch": "^4.0.5", "normalize-path": "^3.0.0", @@ -20800,7 +20888,8 @@ "postcss-selector-parser": "^6.0.11", "postcss-value-parser": "^4.2.0", "quick-lru": "^5.1.1", - "resolve": "^1.22.1" + "resolve": "^1.22.1", + "sucrase": "^3.29.0" }, "dependencies": { "glob-parent": { @@ -20898,6 +20987,22 @@ "resolved": "https://registry.npmjs.org/text-table/-/text-table-0.2.0.tgz", "integrity": "sha512-N+8UisAXDGk8PFXP4HAzVR9nbfmVJ3zYLAWiTIoqC5v5isinhr+r5uaO8+7r3BMfuNIufIsA7RdpVgacC2cSpw==" }, + "thenify": { + "version": "3.3.1", + "resolved": "https://registry.npmjs.org/thenify/-/thenify-3.3.1.tgz", + "integrity": "sha512-RVZSIV5IG10Hk3enotrhvz0T9em6cyHBLkH/YAZuKqd8hRkKhSfCGIcP2KUY0EPxndzANBmNllzWPwak+bheSw==", + "requires": { + "any-promise": "^1.0.0" + } + }, + "thenify-all": { + "version": "1.6.0", + "resolved": "https://registry.npmjs.org/thenify-all/-/thenify-all-1.6.0.tgz", + "integrity": "sha512-RNxQH/qI8/t3thXJDwcstUO4zeqo64+Uy/+sNVRBx4Xn2OX+OZ9oP+iJnNFqplFra2ZUVeKCSa2oVWi3T4uVmA==", + "requires": { + "thenify": ">= 3.1.0 < 4" + } + }, "thunky": { "version": "1.1.0", "resolved": "https://registry.npmjs.org/thunky/-/thunky-1.1.0.tgz", @@ -20961,6 +21066,11 @@ "resolved": "https://registry.npmjs.org/trough/-/trough-1.0.5.tgz", "integrity": "sha512-rvuRbTarPXmMb79SmzEp8aqXNKcK+y0XaB298IXueQ8I2PsrATcPBCSPyK/dDNa2iWOhKlfNnOjdAOTBU/nkFA==" }, + "ts-interface-checker": { + "version": "0.1.13", + "resolved": "https://registry.npmjs.org/ts-interface-checker/-/ts-interface-checker-0.1.13.tgz", + "integrity": "sha512-Y/arvbn+rrz3JCKl9C4kVNfTfSm2/mEp5FSz5EsZSANGPSlQrpRI5M4PKF+mJnE52jOO90PnPSc3Ur3bTQw0gA==" + }, "tslib": { "version": "2.4.0", "resolved": "https://registry.npmjs.org/tslib/-/tslib-2.4.0.tgz", @@ -21010,9 +21120,9 @@ "peer": true }, "ua-parser-js": { - "version": "0.7.33", - "resolved": "https://registry.npmjs.org/ua-parser-js/-/ua-parser-js-0.7.33.tgz", - "integrity": "sha512-s8ax/CeZdK9R/56Sui0WM6y9OFREJarMRHqLB2EwkovemBxNQ+Bqu8GAsUnVcXKgphb++ghr/B2BZx4mahujPw==" + "version": "0.7.34", + "resolved": "https://registry.npmjs.org/ua-parser-js/-/ua-parser-js-0.7.34.tgz", + "integrity": "sha512-cJMeh/eOILyGu0ejgTKB95yKT3zOenSe9UGE3vj6WfiOwgGYnmATUsnDixMFvdU+rNMvWih83hrUP8VwhF9yXQ==" }, "unherit": { "version": "1.1.3", diff --git a/docs/package.json b/docs/package.json index 6a3b4d8987eb..6f16d1087619 100644 --- a/docs/package.json +++ b/docs/package.json @@ -18,23 +18,23 @@ "write-heading-ids": "docusaurus write-heading-ids" }, "dependencies": { - "@docusaurus/core": "2.3.1", - "@docusaurus/plugin-client-redirects": "^2.3.1", - "@docusaurus/plugin-google-analytics": "^2.3.1", - "@docusaurus/preset-classic": "2.3.1", + "@docusaurus/core": "2.4.0", + "@docusaurus/plugin-client-redirects": "^2.4.0", + "@docusaurus/plugin-google-analytics": "^2.4.0", + "@docusaurus/preset-classic": "2.4.0", "@mdx-js/react": "^1.6.22", "@you54f/theme-github-codeblock": "^0.1.1", "autoprefixer": "^10.4.14", "clsx": "^1.2.1", - "postcss": "^8.4.21", + "postcss": "^8.4.22", "postcss-import": "^15.1.0", "prism-react-renderer": "^1.3.5", "react": "^17.0.2", "react-dom": "^17.0.2", - "tailwindcss": "^3.2.7" + "tailwindcss": "^3.3.1" }, "devDependencies": { - "@docusaurus/module-type-aliases": "2.3.1" + "@docusaurus/module-type-aliases": "2.4.0" }, "overrides": { "trim": "0.0.3" diff --git a/docs/post.sh b/docs/post.sh index fef3afc4719b..a70eb526ad0c 100755 --- a/docs/post.sh +++ b/docs/post.sh @@ -2,11 +2,14 @@ find docs/modules ! -name '_category_.json' -type f -exec rm -rf {} + rm -rf docs/tooling/01-cosmovisor.md -rm -rf docs/tooling/02-depinject.md -rm -rf docs/tooling/03-confix.md -rm -rf docs/tooling/04-hubl.md +rm -rf docs/tooling/02-confix.md +rm -rf docs/tooling/03-hubl.md +rm -rf docs/packages/01-depinject.md +rm -rf docs/packages/02-collections.md +rm -rf docs/packages/03-orm.md rm -rf docs/run-node/04-rosetta.md rm -rf docs/architecture rm -rf docs/spec rm -rf docs/rfc +rm -rf docs/migrations/02-upgrading.md rm -rf versioned_docs versioned_sidebars versions.json \ No newline at end of file diff --git a/docs/pre.sh b/docs/pre.sh index 921a678f1d6f..cbe88f049ae8 100755 --- a/docs/pre.sh +++ b/docs/pre.sh @@ -19,9 +19,13 @@ cat ../x/README.md | sed 's/\.\.\/docs\/building-modules\/README\.md/\/building- ## Add tooling documentation cp ../tools/cosmovisor/README.md ./docs/tooling/01-cosmovisor.md -cp ../depinject/README.md ./docs/tooling/02-depinject.md -cp ../tools/confix/README.md ./docs/tooling/03-confix.md -cp ../tools/hubl/README.md ./docs/tooling/04-hubl.md +cp ../tools/confix/README.md ./docs/tooling/02-confix.md +cp ../tools/hubl/README.md ./docs/tooling/03-hubl.md + +## Add package documentation +cp ../depinject/README.md ./docs/packages/01-depinject.md +cp ../collections/README.md ./docs/packages/02-collections.md +cp ../orm/README.md ./docs/packages/03-orm.md ## Add rosetta documentation cp ../tools/rosetta/README.md ./docs/run-node/04-rosetta.md @@ -33,4 +37,7 @@ cp -r ./architecture ./docs cp -r ./spec ./docs ## Add rfc documentation -cp -r ./rfc ./docs \ No newline at end of file +cp -r ./rfc ./docs + +## Add SDK migration documentation +cp -r ../UPGRADING.md ./docs/migrations/02-upgrading.md \ No newline at end of file diff --git a/docs/sidebars.js b/docs/sidebars.js index 45531a226f33..9c832f8144d6 100644 --- a/docs/sidebars.js +++ b/docs/sidebars.js @@ -37,10 +37,15 @@ const sidebars = { label: "REST API Spec", href: "https://docs.cosmos.network/swagger/", }, + { + type: "link", + label: "Awesome Cosmos", + href: "https://github.com/cosmos/awesome-cosmos", + }, { type: "link", label: "Support", - href: "https://discord.gg/cosmosnetwork", + href: "https://github.com/orgs/cosmos/discussions", }, ], }, diff --git a/docs/spec/README.md b/docs/spec/README.md index 3aec9229775e..91f347a8e628 100644 --- a/docs/spec/README.md +++ b/docs/spec/README.md @@ -17,7 +17,7 @@ block. ## Modules specifications -Go the [module directory](https://github.com/cosmos/cosmos-sdk/blob/main/x/README.md) +Go the [module directory](https://docs.cosmos.network/main/modules) ## CometBFT diff --git a/docs/spec/_category_.json b/docs/spec/_category_.json index e77f62999bbd..1143a00a1d4a 100644 --- a/docs/spec/_category_.json +++ b/docs/spec/_category_.json @@ -1,5 +1,5 @@ { "label": "Specifications", - "position": 11, + "position": 13, "link": null -} +} \ No newline at end of file diff --git a/docs/spec/circuit-breaker/README.md b/docs/spec/circuit-breaker/README.md deleted file mode 100644 index 1956704bd592..000000000000 --- a/docs/spec/circuit-breaker/README.md +++ /dev/null @@ -1,16 +0,0 @@ -# Concepts - -The intention of the circuit breaker is to have a contingency plan for a -running network which maintains network liveness. This can be achieved through -selectively "pausing" functionality of specific modules on a running network. -The circuit breaker is intended to be enabled through either: - -* governance -* for emergencies a special subset of accounts selected by the state machine -* a transaction which proves the expected behaviour is broken - -## Pause state - -The basic pause state of any module simply disables all message routes to -that module. Beyond that, it may be a appropriate for different modules to -process begin-block/end-block in an altered "safe" way. diff --git a/docs/spec/reserve-pool/README.md b/docs/spec/reserve-pool/README.md deleted file mode 100644 index 6912ab0c482e..000000000000 --- a/docs/spec/reserve-pool/README.md +++ /dev/null @@ -1,4 +0,0 @@ -# Reserve Pool - -The reserve pool is the pool of collected funds for use by governance taken via the `CommunityTax`. -Currently with the Cosmos SDK, tokens collected by the CommunityTax are accounted for but unspendable. diff --git a/docs/spec/store/interblock-cache.md b/docs/spec/store/interblock-cache.md index e25cdc11eb15..f2153a649dc3 100644 --- a/docs/spec/store/interblock-cache.md +++ b/docs/spec/store/interblock-cache.md @@ -1,25 +1,24 @@ # Inter-block Cache -- [Inter-block cache](#inter-block-cache) - - [Synopsis](#synopsis) - - [Overview and basic concepts](#overview-and-basic-concepts) - - [Motivation](#motivation) - - [Definitions](#definitions) - - [System model and properties](#system-model-and-properties) - - [Assumptions](#assumptions) - - [Properties](#properties) - - [Thread safety](#thread-safety) - - [Crash recovery](#crash-recovery) - - [Iteration](#iteration) - - [Technical specification](#technical-specification) - - [General design](#general-design) - - [API](#api) - - [CommitKVCacheManager](#commitkvcachemanager) - - [CommitKVStoreCache](#commitkvstorecache) - - [Implementation details](#implementation-details) - - [History](#history) - - [Copyright](#copyright) - +* [Inter-block Cache](#inter-block-cache) + * [Synopsis](#synopsis) + * [Overview and basic concepts](#overview-and-basic-concepts) + * [Motivation](#motivation) + * [Definitions](#definitions) + * [System model and properties](#system-model-and-properties) + * [Assumptions](#assumptions) + * [Properties](#properties) + * [Thread safety](#thread-safety) + * [Crash recovery](#crash-recovery) + * [Iteration](#iteration) + * [Technical specification](#technical-specification) + * [General design](#general-design) + * [API](#api) + * [CommitKVCacheManager](#commitkvcachemanager) + * [CommitKVStoreCache](#commitkvstorecache) + * [Implementation details](#implementation-details) + * [History](#history) + * [Copyright](#copyright) ## Synopsis @@ -33,9 +32,9 @@ The goal of the inter-block cache is to allow SDK modules to have fast access to ### Definitions -- `Store key` uniquely identifies a store. -- `KVCache` is a `CommitKVStore` wrapped with a cache. -- `Cache manager` is a key component of the inter-block cache responsible for maintaining a map from `store keys` to `KVCaches`. +* `Store key` uniquely identifies a store. +* `KVCache` is a `CommitKVStore` wrapped with a cache. +* `Cache manager` is a key component of the inter-block cache responsible for maintaining a map from `store keys` to `KVCaches`. ## System model and properties @@ -287,4 +286,4 @@ Dec 20, 2022 - Initial draft finished and submitted as a PR ## Copyright -All content herein is licensed under [Apache 2.0](https://www.apache.org/licenses/LICENSE-2.0). \ No newline at end of file +All content herein is licensed under [Apache 2.0](https://www.apache.org/licenses/LICENSE-2.0). diff --git a/errors/abci_test.go b/errors/abci_test.go index 0982709bf7e6..333731d01518 100644 --- a/errors/abci_test.go +++ b/errors/abci_test.go @@ -66,12 +66,12 @@ func (s *abciTestSuite) TestABCInfo() { }, // This is hard to test because of attached stacktrace. This // case is tested in an another test. - //"wrapped stdlib is a full message in debug mode": { + // "wrapped stdlib is a full message in debug mode": { // err: Wrap(io.EOF, "cannot read file"), // debug: true, // wantLog: "cannot read file: EOF", // wantCode: 1, - //}, + // }, "custom error": { err: customErr{}, debug: false, diff --git a/fuzz/oss-fuzz-build.sh b/fuzz/oss-fuzz-build.sh index 1e45778ba0f3..60037271817b 100644 --- a/fuzz/oss-fuzz-build.sh +++ b/fuzz/oss-fuzz-build.sh @@ -12,8 +12,20 @@ build_go_fuzzer() { compile_native_go_fuzzer "$FUZZ_ROOT"/fuzz/tests "$function" "$fuzzer" } +( + cd math && \ + go get github.com/AdamKorcz/go-118-fuzz-build/testing && \ + compile_native_go_fuzzer cosmossdk.io/math FuzzLegacyNewDecFromStr fuzz_math_legacy_new_dec_from_str +) + go get github.com/AdamKorcz/go-118-fuzz-build/testing +# TODO: fails to build with +# main.413864645.go:12:2: found packages query (collections_pagination.go) and query_test (fuzz_test.go_fuzz.go) in /src/cosmos-sdk/types/query +# because of the separate query_test package. +# compile_native_go_fuzzer "$FUZZ_ROOT"/types/query FuzzPagination fuzz_types_query_pagination +compile_native_go_fuzzer "$FUZZ_ROOT"/types FuzzCoinUnmarshalJSON fuzz_types_coin_unmarshal_json + build_go_fuzzer FuzzCryptoHDDerivePrivateKeyForPath fuzz_crypto_hd_deriveprivatekeyforpath build_go_fuzzer FuzzCryptoHDNewParamsFromPath fuzz_crypto_hd_newparamsfrompath diff --git a/fuzz/tests/x_bank_types_addressfrombalancesstore_test.go b/fuzz/tests/x_bank_types_addressfrombalancesstore_test.go deleted file mode 100644 index 1c2235bcd69d..000000000000 --- a/fuzz/tests/x_bank_types_addressfrombalancesstore_test.go +++ /dev/null @@ -1,15 +0,0 @@ -//go:build gofuzz || go1.18 - -package tests - -import ( - "testing" - - "github.com/cosmos/cosmos-sdk/x/bank/types" -) - -func FuzzXBankTypesAddressFromBalancesStore(f *testing.F) { - f.Fuzz(func(t *testing.T, data []byte) { - types.AddressAndDenomFromBalancesStore(data) - }) -} diff --git a/go.mod b/go.mod index 7e43003f42e2..6c0a46fbe6a9 100644 --- a/go.mod +++ b/go.mod @@ -3,33 +3,35 @@ go 1.20 module github.com/cosmos/cosmos-sdk require ( - cosmossdk.io/api v0.3.2-0.20230313131911-55bf5d4efbe7 - cosmossdk.io/collections v0.0.0-20230309163709-87da587416ba + cosmossdk.io/api v0.4.0 + cosmossdk.io/collections v0.1.0 cosmossdk.io/core v0.6.1 cosmossdk.io/depinject v1.0.0-alpha.3 cosmossdk.io/errors v1.0.0-beta.7 - cosmossdk.io/log v0.1.0 + cosmossdk.io/log v1.0.0 cosmossdk.io/math v1.0.0 - cosmossdk.io/store v0.1.0-alpha.1 - cosmossdk.io/x/tx v0.3.1-0.20230321155358-6522dd1731b5 + cosmossdk.io/store v0.1.0-alpha.1.0.20230328185921-37ba88872dbc + cosmossdk.io/x/tx v0.5.5 github.com/99designs/keyring v1.2.1 github.com/armon/go-metrics v0.4.1 github.com/bgentry/speakeasy v0.1.1-0.20220910012023-760eaf8b6816 + github.com/bits-and-blooms/bitset v1.6.0 github.com/chzyer/readline v1.5.1 github.com/cockroachdb/apd/v2 v2.0.2 github.com/cockroachdb/errors v1.9.1 - github.com/cometbft/cometbft v0.37.0 + github.com/cometbft/cometbft v0.37.1-0.20230411132551-3a91d155e664 github.com/cosmos/btcutil v1.0.5 github.com/cosmos/cosmos-db v1.0.0-rc.1 github.com/cosmos/cosmos-proto v1.0.0-beta.3 github.com/cosmos/cosmos-sdk/db v1.0.0-beta.1.0.20220726092710-f848e4300a8a github.com/cosmos/go-bip39 v1.0.0 github.com/cosmos/gogogateway v1.2.0 - github.com/cosmos/gogoproto v1.4.6 + github.com/cosmos/gogoproto v1.4.8 github.com/cosmos/ledger-cosmos-go v0.13.0 - github.com/decred/dcrd/dcrec/secp256k1/v4 v4.1.0 + github.com/decred/dcrd/dcrec/secp256k1/v4 v4.2.0 github.com/golang/mock v1.6.0 github.com/golang/protobuf v1.5.3 + github.com/google/go-cmp v0.5.9 github.com/google/gofuzz v1.2.0 github.com/gorilla/handlers v1.5.1 github.com/gorilla/mux v1.8.0 @@ -43,19 +45,19 @@ require ( github.com/magiconair/properties v1.8.7 github.com/manifoldco/promptui v0.9.0 github.com/mattn/go-isatty v0.0.18 - github.com/prometheus/client_golang v1.14.0 + github.com/prometheus/client_golang v1.15.0 github.com/prometheus/common v0.42.0 - github.com/rs/zerolog v1.29.0 + github.com/rs/zerolog v1.29.1 github.com/spf13/cast v1.5.0 - github.com/spf13/cobra v1.6.1 + github.com/spf13/cobra v1.7.0 github.com/spf13/pflag v1.0.5 github.com/spf13/viper v1.15.0 github.com/stretchr/testify v1.8.2 github.com/tendermint/go-amino v0.16.0 - golang.org/x/crypto v0.7.0 + golang.org/x/crypto v0.8.0 golang.org/x/exp v0.0.0-20230321023759-10a507213a29 golang.org/x/sync v0.1.0 - google.golang.org/genproto v0.0.0-20230320184635-7606e756e683 + google.golang.org/genproto v0.0.0-20230410155749-daa745c078e1 google.golang.org/grpc v1.54.0 google.golang.org/protobuf v1.30.0 gotest.tools/v3 v3.4.0 @@ -75,7 +77,7 @@ require ( github.com/cespare/xxhash v1.1.0 // indirect github.com/cespare/xxhash/v2 v2.2.0 // indirect github.com/cockroachdb/logtags v0.0.0-20230118201751-21c54148d20b // indirect - github.com/cockroachdb/pebble v0.0.0-20230315223031-1e5ddd10389e // indirect + github.com/cockroachdb/pebble v0.0.0-20230412222916-60cfeb46143b // indirect github.com/cockroachdb/redact v1.1.3 // indirect github.com/cometbft/cometbft-db v0.7.0 // indirect github.com/confio/ics23/go v0.9.0 // indirect @@ -92,7 +94,7 @@ require ( github.com/fatih/color v1.15.0 // indirect github.com/felixge/httpsnoop v1.0.2 // indirect github.com/fsnotify/fsnotify v1.6.0 // indirect - github.com/getsentry/sentry-go v0.19.0 // indirect + github.com/getsentry/sentry-go v0.20.0 // indirect github.com/go-kit/kit v0.12.0 // indirect github.com/go-kit/log v0.2.1 // indirect github.com/go-logfmt/logfmt v0.6.0 // indirect @@ -102,7 +104,6 @@ require ( github.com/golang/glog v1.0.0 // indirect github.com/golang/snappy v0.0.4 // indirect github.com/google/btree v1.1.2 // indirect - github.com/google/go-cmp v0.5.9 // indirect github.com/google/orderedcode v0.0.1 // indirect github.com/gorilla/websocket v1.5.0 // indirect github.com/gsterjov/go-libsecret v0.0.0-20161001094733-a6f4afe4910c // indirect @@ -113,14 +114,15 @@ require ( github.com/hashicorp/go-plugin v1.4.9 // indirect github.com/hashicorp/hcl v1.0.0 // indirect github.com/hashicorp/yamux v0.1.1 // indirect + github.com/iancoleman/strcase v0.2.0 // indirect github.com/inconshreveable/mousetrap v1.1.0 // indirect github.com/jmhodges/levigo v1.0.0 // indirect - github.com/klauspost/compress v1.16.3 // indirect + github.com/klauspost/compress v1.16.5 // indirect github.com/kr/pretty v0.3.1 // indirect github.com/kr/text v0.2.0 // indirect github.com/lib/pq v1.10.7 // indirect github.com/libp2p/go-buffer-pool v0.1.0 // indirect - github.com/linxGnu/grocksdb v1.7.15 // indirect + github.com/linxGnu/grocksdb v1.7.16 // indirect github.com/mattn/go-colorable v0.1.13 // indirect github.com/matttproud/golang_protobuf_extensions v1.0.4 // indirect github.com/mimoo/StrobeGo v0.0.0-20210601165009-122bf33a46e0 // indirect @@ -136,7 +138,7 @@ require ( github.com/prometheus/client_model v0.3.0 // indirect github.com/prometheus/procfs v0.9.0 // indirect github.com/rcrowley/go-metrics v0.0.0-20201227073835-cf1acfcdf475 // indirect - github.com/rogpeppe/go-internal v1.9.0 // indirect + github.com/rogpeppe/go-internal v1.10.0 // indirect github.com/rs/cors v1.8.3 // indirect github.com/sasha-s/go-deadlock v0.3.1 // indirect github.com/spf13/afero v1.9.3 // indirect @@ -148,10 +150,10 @@ require ( github.com/zondax/hid v0.9.1 // indirect github.com/zondax/ledger-go v0.14.1 // indirect go.etcd.io/bbolt v1.3.6 // indirect - golang.org/x/net v0.8.0 // indirect - golang.org/x/sys v0.6.0 // indirect - golang.org/x/term v0.6.0 // indirect - golang.org/x/text v0.8.0 // indirect + golang.org/x/net v0.9.0 // indirect + golang.org/x/sys v0.7.0 // indirect + golang.org/x/term v0.7.0 // indirect + golang.org/x/text v0.9.0 // indirect gopkg.in/ini.v1 v1.67.0 // indirect gopkg.in/yaml.v2 v2.4.0 // indirect gopkg.in/yaml.v3 v3.0.1 // indirect diff --git a/go.sum b/go.sum index b618d036247f..07d272880725 100644 --- a/go.sum +++ b/go.sum @@ -35,24 +35,24 @@ cloud.google.com/go/storage v1.6.0/go.mod h1:N7U0C8pVQ/+NIKOBQyamJIeKQKkZ+mxpohl cloud.google.com/go/storage v1.8.0/go.mod h1:Wv1Oy7z6Yz3DshWRJFhqM/UCfaWIRTdp0RXyy7KQOVs= cloud.google.com/go/storage v1.10.0/go.mod h1:FLPqc6j+Ki4BU591ie1oL6qBQGu2Bl/tZ9ullr3+Kg0= cloud.google.com/go/storage v1.14.0/go.mod h1:GrKmX003DSIwi9o29oFT7YDnHYwZoctc3fOKtUw0Xmo= -cosmossdk.io/api v0.3.2-0.20230313131911-55bf5d4efbe7 h1:4LrWK+uGP5IxznxtHHsHD+ZBs2+oZRH2loYOGjHLzZM= -cosmossdk.io/api v0.3.2-0.20230313131911-55bf5d4efbe7/go.mod h1:yVns7mKgcsG+hZW/3C5FdJtC6QYWdFIcRlKb9+5HV5g= -cosmossdk.io/collections v0.0.0-20230309163709-87da587416ba h1:S4PYij/tX3Op/hwenVEN9D+M27JRcwSwVqE3UA0BnwM= -cosmossdk.io/collections v0.0.0-20230309163709-87da587416ba/go.mod h1:lpS+G8bGC2anqzWdndTzjnQnuMO/qAcgZUkGJp4i3rc= +cosmossdk.io/api v0.4.0 h1:x90DmdidP6EhzktAa/6/IofSHidDnPjahdlrUvyQZQw= +cosmossdk.io/api v0.4.0/go.mod h1:TWDzBhUBhI1LhSf2XSYpfIBf6D4mbLu/fvzvDfhcaYM= +cosmossdk.io/collections v0.1.0 h1:nzJGeiq32KnZroSrhB6rPifw4I85Cgmzw/YAmr4luv8= +cosmossdk.io/collections v0.1.0/go.mod h1:xbauc0YsbUF8qKMVeBZl0pFCunxBIhKN/WlxpZ3lBuo= cosmossdk.io/core v0.6.1 h1:OBy7TI2W+/gyn2z40vVvruK3di+cAluinA6cybFbE7s= cosmossdk.io/core v0.6.1/go.mod h1:g3MMBCBXtxbDWBURDVnJE7XML4BG5qENhs0gzkcpuFA= cosmossdk.io/depinject v1.0.0-alpha.3 h1:6evFIgj//Y3w09bqOUOzEpFj5tsxBqdc5CfkO7z+zfw= cosmossdk.io/depinject v1.0.0-alpha.3/go.mod h1:eRbcdQ7MRpIPEM5YUJh8k97nxHpYbc3sMUnEtt8HPWU= cosmossdk.io/errors v1.0.0-beta.7 h1:gypHW76pTQGVnHKo6QBkb4yFOJjC+sUGRc5Al3Odj1w= cosmossdk.io/errors v1.0.0-beta.7/go.mod h1:mz6FQMJRku4bY7aqS/Gwfcmr/ue91roMEKAmDUDpBfE= -cosmossdk.io/log v0.1.0 h1:Vnexi+KzUCjmqq/m93teAxjt5biWFfZ5PI1imx2IJw8= -cosmossdk.io/log v0.1.0/go.mod h1:p95Wq6mDY3SREMc4y7+QU9Uwy3nyvfpWGD1iSaFkVFs= +cosmossdk.io/log v1.0.0 h1:NGKZ/A5rd4PduDfoscgABklX557PWjQINbosZy/m3Jk= +cosmossdk.io/log v1.0.0/go.mod h1:CwX9BLiBruZb7lzLlRr3R231d/fVPUXk8gAdV4LQap0= cosmossdk.io/math v1.0.0 h1:ro9w7eKx23om2tZz/VM2Pf+z2WAbGX1yDQQOJ6iGeJw= cosmossdk.io/math v1.0.0/go.mod h1:Ygz4wBHrgc7g0N+8+MrnTfS9LLn9aaTGa9hKopuym5k= -cosmossdk.io/store v0.1.0-alpha.1 h1:NGomhLUXzAxvK4OF8+yP6eNUG5i4LwzOzx+S494pTCg= -cosmossdk.io/store v0.1.0-alpha.1/go.mod h1:kmCMbhrleCZ6rDZPY/EGNldNvPebFNyVPFYp+pv05/k= -cosmossdk.io/x/tx v0.3.1-0.20230321155358-6522dd1731b5 h1:AlvyRc7f7Py1mv254vrqjIIuykCnitHIz2T+nup3bU0= -cosmossdk.io/x/tx v0.3.1-0.20230321155358-6522dd1731b5/go.mod h1:FNkSEMbLP9NFdTfrbslNUtNS7OXf3wgZeJyXzfRPa4c= +cosmossdk.io/store v0.1.0-alpha.1.0.20230328185921-37ba88872dbc h1:9piuA+NYmhe+SyMPtMoboLw/djgDbrI3dD5TG020Tnk= +cosmossdk.io/store v0.1.0-alpha.1.0.20230328185921-37ba88872dbc/go.mod h1:UFF5rmjN7WYVfxo6ArdY/l1+yyWMURBWOmSJypGqFHQ= +cosmossdk.io/x/tx v0.5.5 h1:9XG3KOrqObt7Rw7KhT7fiqRd6EepUfmA9ERa8CHj1WM= +cosmossdk.io/x/tx v0.5.5/go.mod h1:Oh3Kh+IPOfMEILNxVd2e8SLqRrIjYHpdGBfDg4ghU/k= dmitri.shuralyov.com/gpu/mtl v0.0.0-20190408044501-666a987793e9/go.mod h1:H6x//7gZCb22OMCxBHrMx7a5I7Hp++hsVxbQ4BYO7hU= filippo.io/edwards25519 v1.0.0 h1:0wAIcmJUqRdI8IJ/3eGi5/HwXZWPujYXXlkrQogz0Ek= filippo.io/edwards25519 v1.0.0/go.mod h1:N1IkdkCkiLB6tki+MYJoSx2JTY9NUlxZE7eHn5EwJns= @@ -111,6 +111,8 @@ github.com/beorn7/perks v1.0.1/go.mod h1:G2ZrVWU2WbWT9wwq4/hrbKbnv/1ERSJQ0ibhJ6r github.com/bgentry/speakeasy v0.1.0/go.mod h1:+zsyZBPWlz7T6j88CTgSN5bM796AkVf0kBD4zp0CCIs= github.com/bgentry/speakeasy v0.1.1-0.20220910012023-760eaf8b6816 h1:41iFGWnSlI2gVpmOtVTJZNodLdLQLn/KsJqFvXwnd/s= github.com/bgentry/speakeasy v0.1.1-0.20220910012023-760eaf8b6816/go.mod h1:+zsyZBPWlz7T6j88CTgSN5bM796AkVf0kBD4zp0CCIs= +github.com/bits-and-blooms/bitset v1.6.0 h1:FVfaUsleKAUTJnaN9Fd1YFFi1S8vAX5xeXnXHFYOojM= +github.com/bits-and-blooms/bitset v1.6.0/go.mod h1:gIdJ4wp64HaoK2YrL1Q5/N7Y16edYb8uY+O0FJTyyDA= github.com/btcsuite/btcd/btcec/v2 v2.3.2 h1:5n0X6hX0Zk+6omWcihdYvdAlGf2DfasC0GMf7DClJ3U= github.com/btcsuite/btcd/btcec/v2 v2.3.2/go.mod h1:zYzJ8etWJQIv1Ogk7OzpWjowwOdXY1W/17j2MW85J04= github.com/btcsuite/btcd/btcutil v1.1.2 h1:XLMbX8JQEiwMcYft2EGi8zPUkoa0abKIU6/BJSRsjzQ= @@ -161,14 +163,14 @@ github.com/cockroachdb/errors v1.9.1/go.mod h1:2sxOtL2WIc096WSZqZ5h8fa17rdDq9HZO github.com/cockroachdb/logtags v0.0.0-20211118104740-dabe8e521a4f/go.mod h1:Vz9DsVWQQhf3vs21MhPMZpMGSht7O/2vFW2xusFUVOs= github.com/cockroachdb/logtags v0.0.0-20230118201751-21c54148d20b h1:r6VH0faHjZeQy818SGhaone5OnYfxFR/+AzdY3sf5aE= github.com/cockroachdb/logtags v0.0.0-20230118201751-21c54148d20b/go.mod h1:Vz9DsVWQQhf3vs21MhPMZpMGSht7O/2vFW2xusFUVOs= -github.com/cockroachdb/pebble v0.0.0-20230315223031-1e5ddd10389e h1:CDuLmyaZ1pD4OJHHtubKqgu/Byw5zAnm+gArJsyj96Q= -github.com/cockroachdb/pebble v0.0.0-20230315223031-1e5ddd10389e/go.mod h1:9lRMC4XN3/BLPtIp6kAKwIaHu369NOf2rMucPzipz50= +github.com/cockroachdb/pebble v0.0.0-20230412222916-60cfeb46143b h1:92ve6F1Pls/eqd+V+102lOMRJatgpqqsQvbT9Bl/fjg= +github.com/cockroachdb/pebble v0.0.0-20230412222916-60cfeb46143b/go.mod h1:9lRMC4XN3/BLPtIp6kAKwIaHu369NOf2rMucPzipz50= github.com/cockroachdb/redact v1.1.3 h1:AKZds10rFSIj7qADf0g46UixK8NNLwWTNdCIGS5wfSQ= github.com/cockroachdb/redact v1.1.3/go.mod h1:BVNblN9mBWFyMyqK1k3AAiSxhvhfK2oOZZ2lK+dpvRg= github.com/codahale/hdrhistogram v0.0.0-20161010025455-3a0bb77429bd/go.mod h1:sE/e/2PUdi/liOCUjSTXgM1o87ZssimdTWN964YiIeI= github.com/codegangsta/inject v0.0.0-20150114235600-33e0aa1cb7c0/go.mod h1:4Zcjuz89kmFXt9morQgcfYZAYZ5n8WHjt81YYWIwtTM= -github.com/cometbft/cometbft v0.37.0 h1:M005vBaSaugvYYmNZwJOopynQSjwLoDTwflnQ/I/eYk= -github.com/cometbft/cometbft v0.37.0/go.mod h1:Y2MMMN//O5K4YKd8ze4r9jmk4Y7h0ajqILXbH5JQFVs= +github.com/cometbft/cometbft v0.37.1-0.20230411132551-3a91d155e664 h1:BbCkbnaU3R603XpnbqvuDU8Kfv+hjhiFILOHhVFntsw= +github.com/cometbft/cometbft v0.37.1-0.20230411132551-3a91d155e664/go.mod h1:Y2MMMN//O5K4YKd8ze4r9jmk4Y7h0ajqILXbH5JQFVs= github.com/cometbft/cometbft-db v0.7.0 h1:uBjbrBx4QzU0zOEnU8KxoDl18dMNgDh+zZRUE0ucsbo= github.com/cometbft/cometbft-db v0.7.0/go.mod h1:yiKJIm2WKrt6x8Cyxtq9YTEcIMPcEe4XPxhgX59Fzf0= github.com/confio/ics23/go v0.9.0 h1:cWs+wdbS2KRPZezoaaj+qBleXgUk5WOQFMP3CQFGTr4= @@ -178,7 +180,7 @@ github.com/coreos/etcd v3.3.10+incompatible/go.mod h1:uF7uidLiAD3TWHmW31ZFd/JWoc github.com/coreos/go-etcd v2.0.0+incompatible/go.mod h1:Jez6KQU2B/sWsbdaef3ED8NzMklzPG4d5KIOhIy30Tk= github.com/coreos/go-semver v0.2.0/go.mod h1:nnelYz7RCh+5ahJtPPxZlU+153eP4D4r3EedlOD2RNk= github.com/coreos/go-systemd v0.0.0-20180511133405-39ca1b05acc7/go.mod h1:F5haX7vjVVG0kc13fIWeqUViNPyEJxv/OmvnBo0Yme4= -github.com/coreos/go-systemd/v22 v22.3.3-0.20220203105225-a9a7ef127534/go.mod h1:Y58oyj3AT4RCenI/lSvhwexgC+NSVTIJ3seZv2GcEnc= +github.com/coreos/go-systemd/v22 v22.5.0/go.mod h1:Y58oyj3AT4RCenI/lSvhwexgC+NSVTIJ3seZv2GcEnc= github.com/coreos/pkg v0.0.0-20160727233714-3ac0863d7acf/go.mod h1:E3G3o1h8I7cfcXa63jLwjI0eiQQMgzzUDFVpN/nH/eA= github.com/cosmos/btcutil v1.0.5 h1:t+ZFcX77LpKtDBhjucvnOH8C2l2ioGsBNEQ3jef8xFk= github.com/cosmos/btcutil v1.0.5/go.mod h1:IyB7iuqZMJlthe2tkIFL33xPyzbFYP0XVdS8P5lUPis= @@ -194,8 +196,8 @@ github.com/cosmos/go-bip39 v1.0.0/go.mod h1:RNJv0H/pOIVgxw6KS7QeX2a0Uo0aKUlfhZ4x github.com/cosmos/gogogateway v1.2.0 h1:Ae/OivNhp8DqBi/sh2A8a1D0y638GpL3tkmLQAiKxTE= github.com/cosmos/gogogateway v1.2.0/go.mod h1:iQpLkGWxYcnCdz5iAdLcRBSw3h7NXeOkZ4GUkT+tbFI= github.com/cosmos/gogoproto v1.4.2/go.mod h1:cLxOsn1ljAHSV527CHOtaIP91kK6cCrZETRBrkzItWU= -github.com/cosmos/gogoproto v1.4.6 h1:Ee7z15dWJaGlgM2rWrK8N2IX7PQcuccu8oG68jp5RL4= -github.com/cosmos/gogoproto v1.4.6/go.mod h1:VS/ASYmPgv6zkPKLjR9EB91lwbLHOzaGCirmKKhncfI= +github.com/cosmos/gogoproto v1.4.8 h1:BrHKc6WFZt8+jRV71vKSQE+JrfF+JAnzrKo2VP7wIZ4= +github.com/cosmos/gogoproto v1.4.8/go.mod h1:hnb0DIEWTv+wdNzNcqus5xCQXq5+CXauq1FJuurRfVY= github.com/cosmos/iavl v0.21.0-beta.1 h1:fBQeBc8HLZ14plJNcmGfaOXSSMLVEHvEQXiTXSD76m0= github.com/cosmos/iavl v0.21.0-beta.1/go.mod h1:25YJYzilTErJ2mKfNB3xyWL9IsCwEQdNzdIutg2mh3U= github.com/cosmos/keyring v1.2.0 h1:8C1lBP9xhImmIabyXW4c3vFjjLiBdGCmfLUfeZlV1Yo= @@ -216,9 +218,9 @@ github.com/danieljoos/wincred v1.1.2/go.mod h1:GijpziifJoIBfYh+S7BbkdUTU4LfM+QnG github.com/davecgh/go-spew v1.1.0/go.mod h1:J7Y8YcW2NihsgmVo/mv3lAwl/skON4iLHjSsI+c5H38= github.com/davecgh/go-spew v1.1.1 h1:vj9j/u1bqnvCEfJOwUhtlOARqs3+rkHYY13jYWTU97c= github.com/davecgh/go-spew v1.1.1/go.mod h1:J7Y8YcW2NihsgmVo/mv3lAwl/skON4iLHjSsI+c5H38= -github.com/decred/dcrd/crypto/blake256 v1.0.0 h1:/8DMNYp9SGi5f0w7uCm6d6M4OU2rGFK09Y2A4Xv7EE0= -github.com/decred/dcrd/dcrec/secp256k1/v4 v4.1.0 h1:HbphB4TFFXpv7MNrT52FGrrgVXF1owhMVTHFZIlnvd4= -github.com/decred/dcrd/dcrec/secp256k1/v4 v4.1.0/go.mod h1:DZGJHZMqrU4JJqFAWUS2UO1+lbSKsdiOoYi9Zzey7Fc= +github.com/decred/dcrd/crypto/blake256 v1.0.1 h1:7PltbUIQB7u/FfZ39+DGa/ShuMyJ5ilcvdfma9wOH6Y= +github.com/decred/dcrd/dcrec/secp256k1/v4 v4.2.0 h1:8UrgZ3GkP4i/CLijOJx79Yu+etlyjdBU4sfcs2WYQMs= +github.com/decred/dcrd/dcrec/secp256k1/v4 v4.2.0/go.mod h1:v57UDF4pDQJcEfFUCRop3lJL149eHGSe9Jvczhzjo/0= github.com/desertbit/timer v0.0.0-20180107155436-c41aec40b27f h1:U5y3Y5UE0w7amNe7Z5G/twsBW0KEalRQXZzf8ufSh9I= github.com/desertbit/timer v0.0.0-20180107155436-c41aec40b27f/go.mod h1:xH/i4TFMt8koVQZ6WFms69WAsDWr2XsYL3Hkl7jkoLE= github.com/dgraph-io/badger v1.6.0/go.mod h1:zwt7syl517jmP8s94KqSxTlM6IMsdhYy6psNgSztDR4= @@ -276,8 +278,8 @@ github.com/fsnotify/fsnotify v1.6.0 h1:n+5WquG0fcWoWp6xPWfHdbskMCQaFnG6PfBrh1Ky4 github.com/fsnotify/fsnotify v1.6.0/go.mod h1:sl3t1tCWJFWoRz9R8WJCbQihKKwmorjAbSClcnxKAGw= github.com/gavv/httpexpect v2.0.0+incompatible/go.mod h1:x+9tiU1YnrOvnB725RkpoLv1M62hOWzwo5OXotisrKc= github.com/getsentry/sentry-go v0.12.0/go.mod h1:NSap0JBYWzHND8oMbyi0+XZhUalc1TBdRL1M71JZW2c= -github.com/getsentry/sentry-go v0.19.0 h1:BcCH3CN5tXt5aML+gwmbFwVptLLQA+eT866fCO9wVOM= -github.com/getsentry/sentry-go v0.19.0/go.mod h1:y3+lGEFEFexZtpbG1GUE2WD/f9zGyKYwpEqryTOC/nE= +github.com/getsentry/sentry-go v0.20.0 h1:bwXW98iMRIWxn+4FgPW7vMrjmbym6HblXALmhjHmQaQ= +github.com/getsentry/sentry-go v0.20.0/go.mod h1:lc76E2QywIyW8WuBnwl8Lc4bkmQH4+w1gwTf25trprY= github.com/ghodss/yaml v1.0.0/go.mod h1:4dBDuWmgqj2HViK6kFavaiC9ZROes6MMH2rRYeMEF04= github.com/gin-contrib/sse v0.1.0 h1:Y/yl/+YNO8GZSjAhjMsSuLt29uWRFHdHYUb5lYOV9qE= github.com/gin-contrib/sse v0.1.0/go.mod h1:RHrZQHXnP2xjPF+u1gW/2HnVO7nvIa9PG3Gm+fLHvGI= @@ -492,13 +494,14 @@ github.com/huandu/skiplist v1.2.0 h1:gox56QD77HzSC0w+Ws3MH3iie755GBJU1OER3h5VsYw github.com/huandu/skiplist v1.2.0/go.mod h1:7v3iFjLcSAzO4fN5B8dvebvo/qsfumiLiDXMrPiHF9w= github.com/hudl/fargo v1.3.0/go.mod h1:y3CKSmjA+wD2gak7sUSXTAoopbhU08POFhmITJgmKTg= github.com/hydrogen18/memlistener v0.0.0-20200120041712-dcc25e7acd91/go.mod h1:qEIFzExnS6016fRpRfxrExeVn2gbClQA99gQhnIcdhE= +github.com/iancoleman/strcase v0.2.0 h1:05I4QRnGpI0m37iZQRuskXh+w77mr6Z41lwQzuHLwW0= +github.com/iancoleman/strcase v0.2.0/go.mod h1:iwCmte+B7n89clKwxIoIXy/HfoL7AsD47ZCWhYzw7ho= github.com/ianlancetaylor/demangle v0.0.0-20181102032728-5e5cf60278f6/go.mod h1:aSSvb/t6k1mPoxDqO4vJh6VOCGPwU4O0C2/Eqndh1Sc= github.com/ianlancetaylor/demangle v0.0.0-20200824232613-28f6c0f3b639/go.mod h1:aSSvb/t6k1mPoxDqO4vJh6VOCGPwU4O0C2/Eqndh1Sc= github.com/imkira/go-interpol v1.1.0/go.mod h1:z0h2/2T3XF8kyEPpRgJ3kmNv+C43p+I/CoI+jC3w2iA= github.com/improbable-eng/grpc-web v0.15.0 h1:BN+7z6uNXZ1tQGcNAuaU1YjsLTApzkjt2tzCixLaUPQ= github.com/improbable-eng/grpc-web v0.15.0/go.mod h1:1sy9HKV4Jt9aEs9JSnkWlRJPuPtwNr0l57L4f878wP8= github.com/inconshreveable/mousetrap v1.0.0/go.mod h1:PxqpIevigyE2G7u3NXJIT2ANytuPF1OarO4DADm73n8= -github.com/inconshreveable/mousetrap v1.0.1/go.mod h1:vpF70FUmC8bwa3OWnCshd2FqLfsEA9PFc4w1p2J65bw= github.com/inconshreveable/mousetrap v1.1.0 h1:wN+x4NVGpMsO7ErUn/mUI3vEoE6Jt13X2s0bqwp9tc8= github.com/inconshreveable/mousetrap v1.1.0/go.mod h1:vpF70FUmC8bwa3OWnCshd2FqLfsEA9PFc4w1p2J65bw= github.com/influxdata/influxdb1-client v0.0.0-20191209144304-8bf82d3c094d/go.mod h1:qj24IKcXYK6Iy9ceXlo3Tc+vtHo9lIhSX5JddghvEPo= @@ -541,8 +544,8 @@ github.com/klauspost/compress v1.9.7/go.mod h1:RyIbtBH6LamlWaDj8nUwkbUhJ87Yi3uG0 github.com/klauspost/compress v1.10.3/go.mod h1:aoV0uJVorq1K+umq18yTdKaF57EivdYsUV+/s2qKfXs= github.com/klauspost/compress v1.11.7/go.mod h1:aoV0uJVorq1K+umq18yTdKaF57EivdYsUV+/s2qKfXs= github.com/klauspost/compress v1.12.3/go.mod h1:8dP1Hq4DHOhN9w426knH3Rhby4rFm6D8eO+e+Dq5Gzg= -github.com/klauspost/compress v1.16.3 h1:XuJt9zzcnaz6a16/OU53ZjWp/v7/42WcR5t2a0PcNQY= -github.com/klauspost/compress v1.16.3/go.mod h1:ntbaceVETuRiXiv4DpjP66DpAtAGkEQskQzEyD//IeE= +github.com/klauspost/compress v1.16.5 h1:IFV2oUNUzZaz+XyusxpLzpzS8Pt5rh0Z16For/djlyI= +github.com/klauspost/compress v1.16.5/go.mod h1:ntbaceVETuRiXiv4DpjP66DpAtAGkEQskQzEyD//IeE= github.com/klauspost/cpuid v1.2.1/go.mod h1:Pj4uuM528wm8OyEC2QMXAi2YiTZ96dNQPGgoMS4s3ek= github.com/konsorten/go-windows-terminal-sequences v1.0.1/go.mod h1:T0+1ngSBFLxvqU3pZ+m/2kptfBszLMUkC4ZK/EgS/cQ= github.com/konsorten/go-windows-terminal-sequences v1.0.3/go.mod h1:T0+1ngSBFLxvqU3pZ+m/2kptfBszLMUkC4ZK/EgS/cQ= @@ -567,8 +570,8 @@ github.com/libp2p/go-buffer-pool v0.1.0 h1:oK4mSFcQz7cTQIfqbe4MIj9gLW+mnanjyFtc6 github.com/libp2p/go-buffer-pool v0.1.0/go.mod h1:N+vh8gMqimBzdKkSMVuydVDq+UV5QTWy5HSiZacSbPg= github.com/lightstep/lightstep-tracer-common/golang/gogo v0.0.0-20190605223551-bc2310a04743/go.mod h1:qklhhLq1aX+mtWk9cPHPzaBjWImj5ULL6C7HFJtXQMM= github.com/lightstep/lightstep-tracer-go v0.18.1/go.mod h1:jlF1pusYV4pidLvZ+XD0UBX0ZE6WURAspgAczcDHrL4= -github.com/linxGnu/grocksdb v1.7.15 h1:AEhP28lkeAybv5UYNYviYISpR6bJejEnKuYbnWAnxx0= -github.com/linxGnu/grocksdb v1.7.15/go.mod h1:pY55D0o+r8yUYLq70QmhdudxYvoDb9F+9puf4m3/W+U= +github.com/linxGnu/grocksdb v1.7.16 h1:Q2co1xrpdkr5Hx3Fp+f+f7fRGhQFQhvi/+226dtLmA8= +github.com/linxGnu/grocksdb v1.7.16/go.mod h1:JkS7pl5qWpGpuVb3bPqTz8nC12X3YtPZT+Xq7+QfQo4= github.com/lyft/protoc-gen-validate v0.0.13/go.mod h1:XbGvPuh87YZc5TdIa2/I4pLk0QoUACkjt2znoq26NVQ= github.com/magiconair/properties v1.8.0/go.mod h1:PppfXfuXeibc/6YijjN8zIbojt8czPbwD3XqdrwzmxQ= github.com/magiconair/properties v1.8.7 h1:IeQXZAiQcpL9mgcAe1Nu6cX9LLw6ExEHKjN0VQdvPDY= @@ -702,8 +705,8 @@ github.com/prometheus/client_golang v1.0.0/go.mod h1:db9x61etRT2tGnBNRi70OPL5Fsn github.com/prometheus/client_golang v1.3.0/go.mod h1:hJaj2vgQTGQmVCsAACORcieXFeDPbaTKGT+JTgUa3og= github.com/prometheus/client_golang v1.4.0/go.mod h1:e9GMxYsXl05ICDXkRhurwBS4Q3OK1iX/F2sw+iXX5zU= github.com/prometheus/client_golang v1.7.1/go.mod h1:PY5Wy2awLA44sXw4AOSfFBetzPP4j5+D6mVACh+pe2M= -github.com/prometheus/client_golang v1.14.0 h1:nJdhIvne2eSX/XRAFV9PcvFFRbrjbcTUj0VP62TMhnw= -github.com/prometheus/client_golang v1.14.0/go.mod h1:8vpkKitgIVNcqrRBWh1C4TIUQgYNtG/XQE4E/Zae36Y= +github.com/prometheus/client_golang v1.15.0 h1:5fCgGYogn0hFdhyhLbw7hEsWxufKtY9klyvdNfFlFhM= +github.com/prometheus/client_golang v1.15.0/go.mod h1:e9yaBhRPU2pPNsZwE+JdQl0KEt1N9XgF6zxWmaC0xOk= github.com/prometheus/client_model v0.0.0-20180712105110-5c3871d89910/go.mod h1:MbSGuTsp3dbXC40dX6PRTWyKYBIrTGTE9sqQNg2J8bo= github.com/prometheus/client_model v0.0.0-20190115171406-56726106282f/go.mod h1:MbSGuTsp3dbXC40dX6PRTWyKYBIrTGTE9sqQNg2J8bo= github.com/prometheus/client_model v0.0.0-20190129233127-fd36f4220a90/go.mod h1:xMI15A0UPsDsEKsMN9yxemIoYk6Tm2C1GtYGdfGttqA= @@ -738,14 +741,15 @@ github.com/rogpeppe/go-internal v1.3.0/go.mod h1:M8bDsm7K2OlrFYOpmOWEs/qY81heoFR github.com/rogpeppe/go-internal v1.6.1/go.mod h1:xXDCJY+GAPziupqXw64V24skbSoqbTEfhy4qGm1nDQc= github.com/rogpeppe/go-internal v1.8.0/go.mod h1:WmiCO8CzOY8rg0OYDC4/i/2WRWAB6poM+XZ2dLUbcbE= github.com/rogpeppe/go-internal v1.8.1/go.mod h1:JeRgkft04UBgHMgCIwADu4Pn6Mtm5d4nPKWu0nJ5d+o= -github.com/rogpeppe/go-internal v1.9.0 h1:73kH8U+JUqXU8lRuOHeVHaa/SZPifC7BkcraZVejAe8= github.com/rogpeppe/go-internal v1.9.0/go.mod h1:WtVeX8xhTBvf0smdhujwtBcq4Qrzq/fJaraNFVN+nFs= +github.com/rogpeppe/go-internal v1.10.0 h1:TMyTOH3F/DB16zRVcYyreMH6GnZZrwQVAoYjRBZyWFQ= +github.com/rogpeppe/go-internal v1.10.0/go.mod h1:UQnix2H7Ngw/k4C5ijL5+65zddjncjaFoBhdsK/akog= github.com/rs/cors v1.7.0/go.mod h1:gFx+x8UowdsKA9AchylcLynDq+nNFfI8FkUZdN/jGCU= github.com/rs/cors v1.8.3 h1:O+qNyWn7Z+F9M0ILBHgMVPuB1xTOucVd5gtaYyXBpRo= github.com/rs/cors v1.8.3/go.mod h1:XyqrcTp5zjWr1wsJ8PIRZssZ8b/WMcMf71DJnit4EMU= github.com/rs/xid v1.4.0/go.mod h1:trrq9SKmegXys3aeAKXMUTdJsYXVwGY3RLcfgqegfbg= -github.com/rs/zerolog v1.29.0 h1:Zes4hju04hjbvkVkOhdl2HpZa+0PmVwigmo8XoORE5w= -github.com/rs/zerolog v1.29.0/go.mod h1:NILgTygv/Uej1ra5XxGf82ZFSLk58MFGAUS2o6usyD0= +github.com/rs/zerolog v1.29.1 h1:cO+d60CHkknCbvzEWxP0S9K6KqyTjrCNUy1LdQLCGPc= +github.com/rs/zerolog v1.29.1/go.mod h1:Le6ESbR7hc+DP6Lt1THiV8CQSdkkNrd3R0XbEgp3ZBU= github.com/russross/blackfriday v1.5.2/go.mod h1:JO/DiYxRf+HjHt06OyowR9PTA263kcR/rfWxYHBV53g= github.com/russross/blackfriday/v2 v2.0.1/go.mod h1:+Rmxgy9KzJVeS9/2gXHxylqXiyQDYRxCVz55jmeOWTM= github.com/russross/blackfriday/v2 v2.1.0/go.mod h1:+Rmxgy9KzJVeS9/2gXHxylqXiyQDYRxCVz55jmeOWTM= @@ -778,8 +782,8 @@ github.com/spf13/cast v1.5.0 h1:rj3WzYc11XZaIZMPKmwP96zkFEnnAmV8s6XbB2aY32w= github.com/spf13/cast v1.5.0/go.mod h1:SpXXQ5YoyJw6s3/6cMTQuxvgRl3PCJiyaX9p6b155UU= github.com/spf13/cobra v0.0.3/go.mod h1:1l0Ry5zgKvJasoi3XT1TypsSe7PqH0Sj9dhYf7v3XqQ= github.com/spf13/cobra v0.0.5/go.mod h1:3K3wKZymM7VvHMDS9+Akkh4K60UwM26emMESw8tLCHU= -github.com/spf13/cobra v1.6.1 h1:o94oiPyS4KD1mPy2fmcYYHHfCxLqYjJOhGsCHFZtEzA= -github.com/spf13/cobra v1.6.1/go.mod h1:IOw/AERYS7UzyrGinqmz6HLUo219MORXGxhbaJUqzrY= +github.com/spf13/cobra v1.7.0 h1:hyqWnYt1ZQShIddO5kBpj3vu05/++x6tJ6dg8EC572I= +github.com/spf13/cobra v1.7.0/go.mod h1:uLxZILRyS/50WlhOIKD7W6V5bgeIt+4sICxh6uRMrb0= github.com/spf13/jwalterweatherman v1.0.0/go.mod h1:cQK4TGJAtQXfYWX+Ddv3mKDzgVb68N+wFjFa4jdeBTo= github.com/spf13/jwalterweatherman v1.1.0 h1:ue6voC5bR5F8YxI5S67j9i582FU4Qvo2bmqnqMYADFk= github.com/spf13/jwalterweatherman v1.1.0/go.mod h1:aNWZUN0dPAAO/Ljvb5BEdw96iTZ0EXowPYD95IqWIGo= @@ -897,8 +901,8 @@ golang.org/x/crypto v0.0.0-20210421170649-83a5a9bb288b/go.mod h1:T9bdIzuCu7OtxOm golang.org/x/crypto v0.0.0-20210711020723-a769d52b0f97/go.mod h1:GvvjBRRGRdwPK5ydBHafDWAxML/pGHZbMvKqRZ5+Abc= golang.org/x/crypto v0.0.0-20210921155107-089bfa567519/go.mod h1:GvvjBRRGRdwPK5ydBHafDWAxML/pGHZbMvKqRZ5+Abc= golang.org/x/crypto v0.0.0-20211108221036-ceb1ce70b4fa/go.mod h1:GvvjBRRGRdwPK5ydBHafDWAxML/pGHZbMvKqRZ5+Abc= -golang.org/x/crypto v0.7.0 h1:AvwMYaRytfdeVt3u6mLaxYtErKYjxA2OXjJ1HHq6t3A= -golang.org/x/crypto v0.7.0/go.mod h1:pYwdfH91IfpZVANVyUOhSIPZaFoJGxTFbZhFTx+dXZU= +golang.org/x/crypto v0.8.0 h1:pd9TJtTueMTVQXzk8E2XESSMQDj/U7OUu0PqJqPXQjQ= +golang.org/x/crypto v0.8.0/go.mod h1:mRqEX+O9/h5TFCrQhkgjo2yKi0yYA+9ecGkdQoHrywE= golang.org/x/exp v0.0.0-20190121172915-509febef88a4/go.mod h1:CJ0aWSM057203Lf6IL+f9T1iT9GByDxfZKAQTCR3kQA= golang.org/x/exp v0.0.0-20190306152737-a1d7652674e8/go.mod h1:CJ0aWSM057203Lf6IL+f9T1iT9GByDxfZKAQTCR3kQA= golang.org/x/exp v0.0.0-20190510132918-efd6b22b2522/go.mod h1:ZjyILWgesfNpC6sMxTJOJm9Kp84zZh5NQWvqDGG3Qr8= @@ -986,8 +990,8 @@ golang.org/x/net v0.0.0-20210405180319-a5a99cb37ef4/go.mod h1:p54w0d4576C0XHj96b golang.org/x/net v0.0.0-20210805182204-aaa1db679c0d/go.mod h1:9nx3DQGgdP8bBQD5qxJ1jj9UTztislL4KSBs9R2vV5Y= golang.org/x/net v0.0.0-20211008194852-3b03d305991f/go.mod h1:9nx3DQGgdP8bBQD5qxJ1jj9UTztislL4KSBs9R2vV5Y= golang.org/x/net v0.0.0-20220225172249-27dd8689420f/go.mod h1:CfG3xpIq0wQ8r1q4Su4UZFWDARRcnwPjda9FqA0JpMk= -golang.org/x/net v0.8.0 h1:Zrh2ngAOFYneWTAIAPethzeaQLuHwhuBkuV6ZiRnUaQ= -golang.org/x/net v0.8.0/go.mod h1:QVkue5JL9kW//ek3r6jTKnTFis1tRmNAW2P1shuFdJc= +golang.org/x/net v0.9.0 h1:aWJ/m6xSmxWBx+V0XRHTlrYrPG56jKsLdTFmsSsCzOM= +golang.org/x/net v0.9.0/go.mod h1:d48xBJpPfHeWQsugry2m+kC02ZBRGRgulfHnEXEuWns= golang.org/x/oauth2 v0.0.0-20180821212333-d2e6202438be/go.mod h1:N/0e6XlmueqKjAGxoOufVs8QHGRruUQn6yWY3a++T0U= golang.org/x/oauth2 v0.0.0-20190226205417-e64efc72b421/go.mod h1:gOpvHmFTYa4IltrdGE7lF6nIHvwfUNPOp7c8zoXwtLw= golang.org/x/oauth2 v0.0.0-20190604053449-0f29369cfe45/go.mod h1:gOpvHmFTYa4IltrdGE7lF6nIHvwfUNPOp7c8zoXwtLw= @@ -1090,12 +1094,13 @@ golang.org/x/sys v0.0.0-20220503163025-988cb79eb6c6/go.mod h1:oPkhp1MJrh7nUepCBc golang.org/x/sys v0.0.0-20220811171246-fbc7d0a398ab/go.mod h1:oPkhp1MJrh7nUepCBck5+mAzfO9JrbApNNgaTdGDITg= golang.org/x/sys v0.0.0-20220908164124-27713097b956/go.mod h1:oPkhp1MJrh7nUepCBck5+mAzfO9JrbApNNgaTdGDITg= golang.org/x/sys v0.0.0-20221010170243-090e33056c14/go.mod h1:oPkhp1MJrh7nUepCBck5+mAzfO9JrbApNNgaTdGDITg= -golang.org/x/sys v0.6.0 h1:MVltZSvRTcU2ljQOhs94SXPftV6DCNnZViHeQps87pQ= golang.org/x/sys v0.6.0/go.mod h1:oPkhp1MJrh7nUepCBck5+mAzfO9JrbApNNgaTdGDITg= +golang.org/x/sys v0.7.0 h1:3jlCCIQZPdOYu1h8BkNvLz8Kgwtae2cagcG/VamtZRU= +golang.org/x/sys v0.7.0/go.mod h1:oPkhp1MJrh7nUepCBck5+mAzfO9JrbApNNgaTdGDITg= golang.org/x/term v0.0.0-20201126162022-7de9c90e9dd1/go.mod h1:bj7SfCRtBDWHUb9snDiAeCFNEtKQo2Wmx5Cou7ajbmo= golang.org/x/term v0.0.0-20210927222741-03fcf44c2211/go.mod h1:jbD1KX2456YbFQfuXm/mYQcufACuNUgVhRMnK/tPxf8= -golang.org/x/term v0.6.0 h1:clScbb1cHjoCkyRbWwBEUZ5H/tIFu5TAXIqaZD0Gcjw= -golang.org/x/term v0.6.0/go.mod h1:m6U89DPEgQRMq3DNkDClhWw02AUbt2daBVO4cn4Hv9U= +golang.org/x/term v0.7.0 h1:BEvjmm5fURWqcfbSKTdpkDXYBrUS1c0m8agp14W48vQ= +golang.org/x/term v0.7.0/go.mod h1:P32HKFT3hSsZrRxla30E9HqToFYAQPCMs/zFMBUFqPY= golang.org/x/text v0.0.0-20170915032832-14c0d48ead0c/go.mod h1:NqM8EUOU14njkJ3fqMW+pc6Ldnwhi/IjpwHt7yyuwOQ= golang.org/x/text v0.3.0/go.mod h1:NqM8EUOU14njkJ3fqMW+pc6Ldnwhi/IjpwHt7yyuwOQ= golang.org/x/text v0.3.1-0.20180807135948-17ff2d5776d2/go.mod h1:NqM8EUOU14njkJ3fqMW+pc6Ldnwhi/IjpwHt7yyuwOQ= @@ -1105,8 +1110,8 @@ golang.org/x/text v0.3.4/go.mod h1:5Zoc/QRtKVWzQhOtBMvqHzDpF6irO9z98xDceosuGiQ= golang.org/x/text v0.3.5/go.mod h1:5Zoc/QRtKVWzQhOtBMvqHzDpF6irO9z98xDceosuGiQ= golang.org/x/text v0.3.6/go.mod h1:5Zoc/QRtKVWzQhOtBMvqHzDpF6irO9z98xDceosuGiQ= golang.org/x/text v0.3.7/go.mod h1:u+2+/6zg+i71rQMx5EYifcz6MCKuco9NR6JIITiCfzQ= -golang.org/x/text v0.8.0 h1:57P1ETyNKtuIjB4SRd15iJxuhj8Gc416Y78H3qgMh68= -golang.org/x/text v0.8.0/go.mod h1:e1OnstbJyHTd6l/uOt8jFFHp6TRDWZR/bV3emEE/zU8= +golang.org/x/text v0.9.0 h1:2sjJmO8cDvYveuX97RDLsxlyUxLl+GHoLxBiRdHllBE= +golang.org/x/text v0.9.0/go.mod h1:e1OnstbJyHTd6l/uOt8jFFHp6TRDWZR/bV3emEE/zU8= golang.org/x/time v0.0.0-20180412165947-fbb02b2291d2/go.mod h1:tRJNPiyCQ0inRvYxbN9jk5I+vvW/OXSQhTDSoE431IQ= golang.org/x/time v0.0.0-20181108054448-85acf8d2951c/go.mod h1:tRJNPiyCQ0inRvYxbN9jk5I+vvW/OXSQhTDSoE431IQ= golang.org/x/time v0.0.0-20190308202827-9d24e82272b4/go.mod h1:tRJNPiyCQ0inRvYxbN9jk5I+vvW/OXSQhTDSoE431IQ= @@ -1250,8 +1255,8 @@ google.golang.org/genproto v0.0.0-20210126160654-44e461bb6506/go.mod h1:FWY/as6D google.golang.org/genproto v0.0.0-20210226172003-ab064af71705/go.mod h1:FWY/as6DDZQgahTzZj3fqbO1CbirC29ZNUFHwi0/+no= google.golang.org/genproto v0.0.0-20210624195500-8bfb893ecb84/go.mod h1:SzzZ/N+nwJDaO1kznhnlzqS8ocJICar6hYhVyhi++24= google.golang.org/genproto v0.0.0-20220314164441-57ef72a4c106/go.mod h1:hAL49I2IFola2sVEjAn7MEwsja0xp51I0tlGAf9hz4E= -google.golang.org/genproto v0.0.0-20230320184635-7606e756e683 h1:khxVcsk/FhnzxMKOyD+TDGwjbEOpcPuIpmafPGFmhMA= -google.golang.org/genproto v0.0.0-20230320184635-7606e756e683/go.mod h1:NWraEVixdDnqcqQ30jipen1STv2r/n24Wb7twVTGR4s= +google.golang.org/genproto v0.0.0-20230410155749-daa745c078e1 h1:KpwkzHKEF7B9Zxg18WzOa7djJ+Ha5DzthMyZYQfEn2A= +google.golang.org/genproto v0.0.0-20230410155749-daa745c078e1/go.mod h1:nKE/iIaLqn2bQwXBg8f1g2Ylh6r5MN5CmZvuzZCgsCU= google.golang.org/grpc v1.12.0/go.mod h1:yo6s7OP7yaDglbqo1J04qKzAhqBH6lvTonzMVmEdcZw= google.golang.org/grpc v1.17.0/go.mod h1:6QZJwpn2B+Zp71q/5VxRsJ6NXXVCE5NRUHRo+f3cWCs= google.golang.org/grpc v1.19.0/go.mod h1:mqu4LbDTu4XGKhr4mRzUsmM4RtVoemTSY81AxZiDr8c= diff --git a/internal/conv/string_test.go b/internal/conv/string_test.go index 3e051d37b907..3a1451753188 100644 --- a/internal/conv/string_test.go +++ b/internal/conv/string_test.go @@ -26,7 +26,7 @@ func (s *StringSuite) TestUnsafeStrToBytes() { b := unsafeConvertStr() runtime.GC() <-time.NewTimer(2 * time.Millisecond).C - b2 := append(b, 'd') //nolint:gocritic // append is fine here + b2 := append(b, 'd') s.Equal("abc", string(b)) s.Equal("abcd", string(b2)) } diff --git a/internal/util.go b/internal/util.go index bcbcf821638d..97e3b4d1654f 100644 --- a/internal/util.go +++ b/internal/util.go @@ -4,7 +4,7 @@ import ( "fmt" ) -func CombineErrors(ret error, also error, desc string) error { +func CombineErrors(ret, also error, desc string) error { if also != nil { if ret != nil { ret = fmt.Errorf("%w; %v: %v", ret, desc, also) diff --git a/log/CHANGELOG.md b/log/CHANGELOG.md index c057371645ea..f393ecc080f9 100644 --- a/log/CHANGELOG.md +++ b/log/CHANGELOG.md @@ -31,8 +31,9 @@ Ref: https://keepachangelog.com/en/1.0.0/ ## [Unreleased] - - +## [v1.0.0](https://github.com/cosmos/cosmos-sdk/releases/tag/log/v1.0.0) - 2023-03-30 + +* [#15601](https://github.com/cosmos/cosmos-sdk/pull/15601) Introduce logger options. These options allow to configure the logger with filters, different level and output format. ## [v0.1.0](https://github.com/cosmos/cosmos-sdk/releases/tag/log/v0.1.0) - 2023-03-13 diff --git a/log/bench_test.go b/log/bench_test.go index 4c7e942fb81e..d1dd9d8e6439 100644 --- a/log/bench_test.go +++ b/log/bench_test.go @@ -134,7 +134,7 @@ func BenchmarkLoggers_StructuredVsFields(b *testing.B) { b.Run("logger structured", func(b *testing.B) { zl := zerolog.New(io.Discard) - var logger log.Logger = log.NewCustomLogger(zl) + logger := log.NewCustomLogger(zl) zerolog := logger.Impl().(*zerolog.Logger) for i := 0; i < b.N; i++ { zerolog.Info().Int64("foo", 100000).Msg(message) @@ -150,7 +150,7 @@ func BenchmarkLoggers_StructuredVsFields(b *testing.B) { b.Run("logger", func(b *testing.B) { zl := zerolog.New(io.Discard) - var logger log.Logger = log.NewCustomLogger(zl) + logger := log.NewCustomLogger(zl) for i := 0; i < b.N; i++ { logger.Info(message, "foo", 100000) logger.Info(message, "foo", "foo") diff --git a/log/go.mod b/log/go.mod index c491b7892bc9..59c98ccfb47c 100644 --- a/log/go.mod +++ b/log/go.mod @@ -3,7 +3,7 @@ module cosmossdk.io/log go 1.20 require ( - github.com/rs/zerolog v1.29.0 + github.com/rs/zerolog v1.29.1 gotest.tools/v3 v3.4.0 ) diff --git a/log/go.sum b/log/go.sum index a0cc7d74fb02..29760debc658 100644 --- a/log/go.sum +++ b/log/go.sum @@ -1,4 +1,4 @@ -github.com/coreos/go-systemd/v22 v22.3.3-0.20220203105225-a9a7ef127534/go.mod h1:Y58oyj3AT4RCenI/lSvhwexgC+NSVTIJ3seZv2GcEnc= +github.com/coreos/go-systemd/v22 v22.5.0/go.mod h1:Y58oyj3AT4RCenI/lSvhwexgC+NSVTIJ3seZv2GcEnc= github.com/godbus/dbus/v5 v5.0.4/go.mod h1:xhWf0FNVPg57R7Z0UbKHbJfkEywrmjJnf7w5xrFpKfA= github.com/google/go-cmp v0.5.5 h1:Khx7svrCpmxxtHBq5j2mp/xVjsi8hQMfNLvJFAlrGgU= github.com/google/go-cmp v0.5.5/go.mod h1:v8dTdLbMG2kIc/vJvl+f65V22dbkXbowE6jgT/gNBxE= @@ -11,8 +11,8 @@ github.com/mattn/go-isatty v0.0.18 h1:DOKFKCQ7FNG2L1rbrmstDN4QVRdS89Nkh85u68Uwp9 github.com/mattn/go-isatty v0.0.18/go.mod h1:W+V8PltTTMOvKvAeJH7IuucS94S2C6jfK/D7dTCTo3Y= github.com/pkg/errors v0.9.1/go.mod h1:bwawxfHBFNV+L2hUp1rHADufV3IMtnDRdf1r5NINEl0= github.com/rs/xid v1.4.0/go.mod h1:trrq9SKmegXys3aeAKXMUTdJsYXVwGY3RLcfgqegfbg= -github.com/rs/zerolog v1.29.0 h1:Zes4hju04hjbvkVkOhdl2HpZa+0PmVwigmo8XoORE5w= -github.com/rs/zerolog v1.29.0/go.mod h1:NILgTygv/Uej1ra5XxGf82ZFSLk58MFGAUS2o6usyD0= +github.com/rs/zerolog v1.29.1 h1:cO+d60CHkknCbvzEWxP0S9K6KqyTjrCNUy1LdQLCGPc= +github.com/rs/zerolog v1.29.1/go.mod h1:Le6ESbR7hc+DP6Lt1THiV8CQSdkkNrd3R0XbEgp3ZBU= github.com/yuin/goldmark v1.2.1/go.mod h1:3hX8gzYuyVAZsxl0MRgGTJEmQBFcNTphYh9decYSb74= golang.org/x/crypto v0.0.0-20190308221718-c2843e01d9a2/go.mod h1:djNgcEr1/C05ACkg1iLfiJU5Ep61QUkGW8qpdssI0+w= golang.org/x/crypto v0.0.0-20191011191535-87dc89f01550/go.mod h1:yigFU9vqHzYiE8UmvKecakEJjdnWj3jj499lnFckfCI= diff --git a/log/level.go b/log/level.go index f65689d85a0e..9a4f094f2c9f 100644 --- a/log/level.go +++ b/log/level.go @@ -8,12 +8,12 @@ import ( "github.com/rs/zerolog" ) +const defaultLogLevelKey = "*" + // FilterFunc is a function that returns true if the log level is filtered for the given key // When the filter returns true, the log entry is discarded. type FilterFunc func(key, level string) bool -const defaultLogLevelKey = "*" - // ParseLogLevel parses complex log level // A comma-separated list of module:level pairs with an optional *:level pair // (* means all other modules). @@ -21,7 +21,7 @@ const defaultLogLevelKey = "*" // Example: // ParseLogLevel("consensus:debug,mempool:debug,*:error") // -// This function attemps to keep the same behavior as the CometBFT ParseLogLevel +// This function attempts to keep the same behavior as the CometBFT ParseLogLevel // However the level `none` is replaced by `disabled`. func ParseLogLevel(levelStr string) (FilterFunc, error) { if levelStr == "" { diff --git a/log/logger.go b/log/logger.go index 8513fd4be2c6..da1552ef6a01 100644 --- a/log/logger.go +++ b/log/logger.go @@ -42,28 +42,36 @@ type zeroLogWrapper struct { *zerolog.Logger } -// NewNopLogger returns a new logger that does nothing. -func NewNopLogger() Logger { - // The custom nopLogger is about 3x faster than a zeroLogWrapper with zerolog.Nop(). - return nopLogger{} -} - // NewLogger returns a new logger that writes to the given destination. // // Typical usage from a main function is: -// logger := log.NewLogger(os.Stderr) +// +// logger := log.NewLogger(os.Stderr) // // Stderr is the typical destination for logs, // so that any output from your application can still be piped to other processes. -func NewLogger(dst io.Writer) Logger { - output := zerolog.ConsoleWriter{Out: dst, TimeFormat: time.Kitchen} +func NewLogger(dst io.Writer, options ...Option) Logger { + logCfg := defaultConfig + for _, opt := range options { + opt(&logCfg) + } + + output := dst + if !logCfg.OutputJSON { + output = zerolog.ConsoleWriter{Out: dst, TimeFormat: time.Kitchen} + } + + if logCfg.Filter != nil { + output = NewFilterWriter(output, logCfg.Filter) + } + logger := zerolog.New(output).With().Timestamp().Logger() - return zeroLogWrapper{&logger} -} -// NewLoggerWithKV is shorthand for NewLogger(dst).With(key, value). -func NewLoggerWithKV(dst io.Writer, key, value string) Logger { - return NewLogger(dst).With(key, value) + if logCfg.Level != zerolog.NoLevel { + logger = logger.Level(logCfg.Level) + } + + return zeroLogWrapper{&logger} } // NewCustomLogger returns a new logger with the given zerolog logger. @@ -101,33 +109,10 @@ func (l zeroLogWrapper) Impl() interface{} { return l.Logger } -// FilterKeys returns a new logger that filters out all key/value pairs that do not match the filter. -// This functions assumes that the logger is a zerolog.Logger, which is the case for the logger returned by log.NewLogger(). -// NOTE: filtering has a performance impact on the logger. -func FilterKeys(logger Logger, filter FilterFunc) Logger { - zl, ok := logger.Impl().(*zerolog.Logger) - if !ok { - panic("logger is not a zerolog.Logger") - } - - filteredLogger := zl.Hook(zerolog.HookFunc(func(e *zerolog.Event, lvl zerolog.Level, _ string) { - // TODO(@julienrbrt) wait for https://github.com/rs/zerolog/pull/527 to be merged - // keys, err := e.GetKeys() - // if err != nil { - // panic(err) - // } - - keys := []string{} - - for _, key := range keys { - if filter(key, lvl.String()) { - e.Discard() - break - } - } - })) - - return NewCustomLogger(filteredLogger) +// NewNopLogger returns a new logger that does nothing. +func NewNopLogger() Logger { + // The custom nopLogger is about 3x faster than a zeroLogWrapper with zerolog.Nop(). + return nopLogger{} } // nopLogger is a Logger that does nothing when called. diff --git a/log/options.go b/log/options.go new file mode 100644 index 000000000000..831d9e4b4f97 --- /dev/null +++ b/log/options.go @@ -0,0 +1,42 @@ +package log + +import "github.com/rs/zerolog" + +// defaultConfig has all the options disabled. +var defaultConfig = Config{ + Level: zerolog.NoLevel, + Filter: nil, + OutputJSON: false, +} + +// LoggerConfig defines configuration for the logger. +type Config struct { + Level zerolog.Level + Filter FilterFunc + OutputJSON bool +} + +type Option func(*Config) + +// FilterOption sets the filter for the Logger. +func FilterOption(filter FilterFunc) Option { + return func(cfg *Config) { + cfg.Filter = filter + } +} + +// LevelOption sets the level for the Logger. +// Messages with a lower level will be discarded. +func LevelOption(level zerolog.Level) Option { + return func(cfg *Config) { + cfg.Level = level + } +} + +// OutputJSONOption sets the output of the logger to JSON. +// By default, the logger outputs to a human-readable format. +func OutputJSONOption() Option { + return func(cfg *Config) { + cfg.OutputJSON = true + } +} diff --git a/log/testing.go b/log/testing.go index 7f231ac21318..f31f6e5182f4 100644 --- a/log/testing.go +++ b/log/testing.go @@ -8,10 +8,37 @@ type TestingT zerolog.TestingLog // NewTestLogger returns a logger that calls t.Log to write entries. // +// The returned logger emits messages at any level. +// For active debugging of a test with verbose logs, +// the [NewTestLoggerInfo] and [NewTestLoggerError] functions +// only emit messages at or above the corresponding log levels. +// // If the logs may help debug a test failure, // you may want to use NewTestLogger(t) in your test. // Otherwise, use NewNopLogger(). func NewTestLogger(t TestingT) Logger { + return newTestLogger(t, zerolog.DebugLevel) +} + +// NewTestLoggerInfo returns a test logger that filters out messages +// below info level. +// +// This is primarily helpful during active debugging of a test +// with verbose logs. +func NewTestLoggerInfo(t TestingT) Logger { + return newTestLogger(t, zerolog.InfoLevel) +} + +// NewTestLoggerError returns a test logger that filters out messages +// below Error level. +// +// This is primarily helpful during active debugging of a test +// with verbose logs. +func NewTestLoggerError(t TestingT) Logger { + return newTestLogger(t, zerolog.ErrorLevel) +} + +func newTestLogger(t TestingT, lvl zerolog.Level) Logger { cw := zerolog.NewConsoleWriter() cw.Out = zerolog.TestWriter{ T: t, @@ -22,5 +49,5 @@ func NewTestLogger(t TestingT) Logger { // but Frame=7 prints correct source locations. Frame: 7, } - return NewCustomLogger(zerolog.New(cw)) + return NewCustomLogger(zerolog.New(cw).Level(lvl)) } diff --git a/log/writer.go b/log/writer.go new file mode 100644 index 000000000000..9c6befef71fe --- /dev/null +++ b/log/writer.go @@ -0,0 +1,41 @@ +package log + +import ( + "encoding/json" + "fmt" + "io" +) + +// NewFilterWriter returns a writer that filters out all key/value pairs that do not match the filter. +// If the filter is nil, the writer will pass all events through. +// The filter function is called with the module and level of the event. +func NewFilterWriter(parent io.Writer, filter FilterFunc) io.Writer { + return &filterWriter{parent, filter} +} + +type filterWriter struct { + parent io.Writer + filter FilterFunc +} + +func (fw *filterWriter) Write(p []byte) (n int, err error) { + if fw.filter == nil { + return fw.parent.Write(p) + } + + var event struct { + Level string `json:"level"` + Module string `json:"module"` + } + + if err := json.Unmarshal(p, &event); err != nil { + return 0, fmt.Errorf("failed to unmarshal event: %w", err) + } + + // only filter module keys + if fw.filter(event.Module, event.Level) { + return len(p), nil + } + + return fw.parent.Write(p) +} diff --git a/log/writer_test.go b/log/writer_test.go new file mode 100644 index 000000000000..fc312efb679b --- /dev/null +++ b/log/writer_test.go @@ -0,0 +1,26 @@ +package log_test + +import ( + "bytes" + "strings" + "testing" + + "cosmossdk.io/log" + "gotest.tools/v3/assert" +) + +func TestFilteredWriter(t *testing.T) { + buf := new(bytes.Buffer) + + level := "consensus:debug,mempool:debug,*:error" + filter, err := log.ParseLogLevel(level) + assert.NilError(t, err) + + logger := log.NewLogger(buf, log.FilterOption(filter)) + logger.Debug("this log line should be displayed", log.ModuleKey, "consensus") + assert.Check(t, strings.Contains(buf.String(), "this log line should be displayed")) + buf.Reset() + + logger.Debug("this log line should be filtered", log.ModuleKey, "server") + assert.Check(t, buf.Len() == 0) +} diff --git a/math/CHANGELOG.md b/math/CHANGELOG.md index 9ebf9077ae62..df0d947b0f12 100644 --- a/math/CHANGELOG.md +++ b/math/CHANGELOG.md @@ -34,6 +34,16 @@ Ref: https://github.com/commitizen/conventional-commit-types/blob/v3.0.0/index.j # Changelog +## [Unreleased] + +### Bug Fixes + +* [#15714](https://github.com/cosmos/cosmos-sdk/pull/15714) `FormatInt` returns an error on empty string + +### Improvements + +* [#15768](https://github.com/cosmos/cosmos-sdk/pull/15768) Removed the second call to the `init` method for the global variable `grand`. + ## [math/v1.0.0](https://github.com/cosmos/cosmos-sdk/releases/tag/math/v1.0.0) - 2023-03-23 ### Bug Fixes diff --git a/math/dec.go b/math/dec.go index 8875dfdd7099..72d7826925f7 100644 --- a/math/dec.go +++ b/math/dec.go @@ -715,7 +715,7 @@ func (d LegacyDec) Ceil() LegacyDec { return LegacyNewDecFromBigInt(quo.Add(quo, oneInt)) } -// MaxSortableDec is the largest Dec that can be passed into SortableDecBytes() +// LegacyMaxSortableDec is the largest Dec that can be passed into SortableDecBytes() // Its negative form is the least Dec that can be passed in. var LegacyMaxSortableDec LegacyDec @@ -896,7 +896,7 @@ func LegacyDecEq(t *testing.T, exp, got LegacyDec) (*testing.T, bool, string, st return t, exp.Equal(got), "expected:\t%v\ngot:\t\t%v", exp.String(), got.String() } -func LegacyDecApproxEq(t *testing.T, d1 LegacyDec, d2 LegacyDec, tol LegacyDec) (*testing.T, bool, string, string, string) { +func LegacyDecApproxEq(t *testing.T, d1, d2, tol LegacyDec) (*testing.T, bool, string, string, string) { diff := d1.Sub(d2).Abs() return t, diff.LTE(tol), "expected |d1 - d2| <:\t%v\ngot |d1 - d2| = \t\t%v", tol.String(), diff.String() } diff --git a/math/dec_internal_test.go b/math/dec_internal_test.go index 0680cf0094e5..8b899300e3b0 100644 --- a/math/dec_internal_test.go +++ b/math/dec_internal_test.go @@ -98,7 +98,7 @@ func (s *decimalInternalTestSuite) TestDecMarshalJSON() { return } if !tt.wantErr { - s.Require().Equal(tt.want, string(got), "incorrect marshalled value") + s.Require().Equal(tt.want, string(got), "incorrect marshaled value") unmarshalledDec := LegacyNewDec(0) err := unmarshalledDec.UnmarshalJSON(got) s.Require().NoError(err) diff --git a/math/dec_test.go b/math/dec_test.go index bf7d73492088..7b565e262274 100644 --- a/math/dec_test.go +++ b/math/dec_test.go @@ -612,10 +612,8 @@ func BenchmarkMarshalTo(b *testing.B) { for _, bi := range bis { if n, err := bi.in.MarshalTo(data); err != nil { b.Fatal(err) - } else { - if !bytes.Equal(data[:n], bi.want) { - b.Fatalf("Mismatch\nGot: % x\nWant: % x\n", data[:n], bi.want) - } + } else if !bytes.Equal(data[:n], bi.want) { + b.Fatalf("Mismatch\nGot: % x\nWant: % x\n", data[:n], bi.want) } } } diff --git a/math/int.go b/math/int.go index 184a524648ca..3e6b5c257dec 100644 --- a/math/int.go +++ b/math/int.go @@ -17,31 +17,31 @@ func newIntegerFromString(s string) (*big.Int, bool) { return new(big.Int).SetString(s, 0) } -func equal(i *big.Int, i2 *big.Int) bool { return i.Cmp(i2) == 0 } +func equal(i, i2 *big.Int) bool { return i.Cmp(i2) == 0 } -func gt(i *big.Int, i2 *big.Int) bool { return i.Cmp(i2) == 1 } +func gt(i, i2 *big.Int) bool { return i.Cmp(i2) == 1 } -func gte(i *big.Int, i2 *big.Int) bool { return i.Cmp(i2) >= 0 } +func gte(i, i2 *big.Int) bool { return i.Cmp(i2) >= 0 } -func lt(i *big.Int, i2 *big.Int) bool { return i.Cmp(i2) == -1 } +func lt(i, i2 *big.Int) bool { return i.Cmp(i2) == -1 } -func lte(i *big.Int, i2 *big.Int) bool { return i.Cmp(i2) <= 0 } +func lte(i, i2 *big.Int) bool { return i.Cmp(i2) <= 0 } -func add(i *big.Int, i2 *big.Int) *big.Int { return new(big.Int).Add(i, i2) } +func add(i, i2 *big.Int) *big.Int { return new(big.Int).Add(i, i2) } -func sub(i *big.Int, i2 *big.Int) *big.Int { return new(big.Int).Sub(i, i2) } +func sub(i, i2 *big.Int) *big.Int { return new(big.Int).Sub(i, i2) } -func mul(i *big.Int, i2 *big.Int) *big.Int { return new(big.Int).Mul(i, i2) } +func mul(i, i2 *big.Int) *big.Int { return new(big.Int).Mul(i, i2) } -func div(i *big.Int, i2 *big.Int) *big.Int { return new(big.Int).Quo(i, i2) } +func div(i, i2 *big.Int) *big.Int { return new(big.Int).Quo(i, i2) } -func mod(i *big.Int, i2 *big.Int) *big.Int { return new(big.Int).Mod(i, i2) } +func mod(i, i2 *big.Int) *big.Int { return new(big.Int).Mod(i, i2) } func neg(i *big.Int) *big.Int { return new(big.Int).Neg(i) } func abs(i *big.Int) *big.Int { return new(big.Int).Abs(i) } -func min(i *big.Int, i2 *big.Int) *big.Int { +func min(i, i2 *big.Int) *big.Int { if i.Cmp(i2) == 1 { return new(big.Int).Set(i2) } @@ -49,7 +49,7 @@ func min(i *big.Int, i2 *big.Int) *big.Int { return new(big.Int).Set(i) } -func max(i *big.Int, i2 *big.Int) *big.Int { +func max(i, i2 *big.Int) *big.Int { if i.Cmp(i2) == -1 { return new(big.Int).Set(i2) } @@ -457,6 +457,10 @@ var stringsBuilderPool = &sync.Pool{ // string following ADR-050. This function operates with string manipulation // (instead of manipulating the int or sdk.Int object). func FormatInt(v string) (string, error) { + if len(v) == 0 { + return "", fmt.Errorf("cannot format empty string") + } + sign := "" if v[0] == '-' { sign = "-" diff --git a/math/int_test.go b/math/int_test.go index c86165c712ed..56b05cc69f94 100644 --- a/math/int_test.go +++ b/math/int_test.go @@ -473,6 +473,11 @@ func TestFormatIntNonDigits(t *testing.T) { } } +func TestFormatIntEmptyString(t *testing.T) { + _, err := math.FormatInt("") + require.ErrorContains(t, err, "cannot format empty string") +} + func TestFormatIntCorrectness(t *testing.T) { tests := []struct { in string diff --git a/math/uint.go b/math/uint.go index 81da2d9ef8d5..406d9418cea1 100644 --- a/math/uint.go +++ b/math/uint.go @@ -240,7 +240,7 @@ func checkNewUint(i *big.Int) (Uint, error) { // RelativePow raises x to the power of n, where x (and the result, z) are scaled by factor b // for example, RelativePow(210, 2, 100) = 441 (2.1^2 = 4.41) -func RelativePow(x Uint, n Uint, b Uint) (z Uint) { +func RelativePow(x, n, b Uint) (z Uint) { if x.IsZero() { if n.IsZero() { z = b // 0^0 = 1 diff --git a/math/unsafe/rand.go b/math/unsafe/rand.go index e7fb3c44b3c2..66d48ae4dc85 100644 --- a/math/unsafe/rand.go +++ b/math/unsafe/rand.go @@ -26,7 +26,6 @@ var grand *Rand func init() { grand = NewRand() - grand.init() } func NewRand() *Rand { diff --git a/orm/CHANGELOG.md b/orm/CHANGELOG.md index b8bb40c78dfe..6af499d5af11 100644 --- a/orm/CHANGELOG.md +++ b/orm/CHANGELOG.md @@ -42,8 +42,10 @@ Ref: https://keepachangelog.com/en/1.0.0/ ### API Breaking Changes -* [#14822](https://github.com/cosmos/cosmos-sdk/pull/14822) Migrate to cosmossdk.io/core genesis API +* [#15870](https://github.com/cosmos/cosmos-sdk/pull/15870) Rename the orm package to `cosmossdk.io/orm`. +* [#14822](https://github.com/cosmos/cosmos-sdk/pull/14822) Migrate to cosmossdk.io/core genesis API. ### State-machine Breaking Changes * [#12273](https://github.com/cosmos/cosmos-sdk/pull/12273) The timestamp key encoding was reworked to properly handle nil values. Existing users will need to manually migrate their data to the new encoding before upgrading. +* [#15138](https://github.com/cosmos/cosmos-sdk/pull/15138) The duration key encoding was reworked to properly handle nil values. Existing users will need to manually migrate their data to the new encoding before upgrading. diff --git a/orm/README.md b/orm/README.md index 7415523651e9..14bc84b8812a 100644 --- a/orm/README.md +++ b/orm/README.md @@ -2,6 +2,7 @@ The Cosmos SDK ORM is a state management library that provides a rich, but opinionated set of tools for managing a module's state. It provides support for: + * type safe management of state * multipart keys * secondary indexes @@ -56,8 +57,10 @@ of storage and not in the value leading to both a flexible data model and effici ## Defining Tables To define a table: + 1) create a .proto file to describe the module's state (naming it `state.proto` is recommended for consistency), and import "cosmos/orm/v1/orm.proto", ex: + ```protobuf syntax = "proto3"; package bank_example; @@ -66,6 +69,7 @@ import "cosmos/orm/v1/orm.proto"; ``` 2) define a `message` for the table, ex: + ```protobuf message Balance { bytes account = 1; @@ -75,6 +79,7 @@ message Balance { ``` 3) add the `cosmos.orm.v1.table` option to the table and give the table an `id` unique within this .proto file: + ```protobuf message Balance { option (cosmos.orm.v1.table) = { @@ -89,6 +94,7 @@ message Balance { 4) define the primary key field or fields, as a comma-separated list of the fields from the message which should make up the primary key: + ```protobuf message Balance { option (cosmos.orm.v1.table) = { @@ -104,6 +110,7 @@ message Balance { 5) add any desired secondary indexes by specifying an `id` unique within the table and a comma-separate list of the index fields: + ```protobuf message Balance { option (cosmos.orm.v1.table) = { @@ -123,6 +130,7 @@ message Balance { A common pattern in SDK modules and in database design is to define tables with a single integer `id` field with an automatically generated primary key. In the ORM we can do this by setting the `auto_increment` option to `true` on the primary key, ex: + ```protobuf message Account { option (cosmos.orm.v1.table) = { @@ -138,6 +146,7 @@ message Account { ### Unique Indexes A unique index can be added by setting the `unique` option to `true` on an index, ex: + ```protobuf message Account { option (cosmos.orm.v1.table) = { @@ -156,6 +165,7 @@ message Account { The ORM also supports a special type of table with only one row called a `singleton`. This can be used for storing module parameters. Singletons only need to define a unique `id` and that cannot conflict with the id of other tables or singletons in the same .proto file. Ex: + ```protobuf message Params { option (cosmos.orm.v1.singleton) = { @@ -173,13 +183,15 @@ NOTE: the ORM will only work with protobuf code that implements the [google.gola API. That means it will not work with code generated using gogo-proto. To install the ORM's code generator, run: + ```shell -go install github.com/cosmos/cosmos-sdk/orm/cmd/protoc-gen-go-cosmos-orm@latest +go install cosmossdk.io/orm/cmd/protoc-gen-go-cosmos-orm@latest ``` The recommended way to run the code generator is to use [buf build](https://docs.buf.build/build/usage). This is an example `buf.gen.yaml` that runs `protoc-gen-go`, `protoc-gen-go-grpc` and `protoc-gen-go-cosmos-orm` using buf managed mode: + ```yaml version: v1 managed: @@ -206,6 +218,7 @@ plugins: To use the ORM in a module, first create a `ModuleSchemaDescriptor`. This tells the ORM which .proto files have defined an ORM schema and assigns them all a unique non-zero id. Ex: + ```go var MyModuleSchema = &ormv1alpha1.ModuleSchemaDescriptor{ SchemaFile: []*ormv1alpha1.ModuleSchemaDescriptor_FileEntry{ @@ -220,6 +233,7 @@ var MyModuleSchema = &ormv1alpha1.ModuleSchemaDescriptor{ In the ORM generated code for a file named `state.proto`, there should be an interface `StateStore` that got generated with a constructor `NewStateStore` that takes a parameter of type `ormdb.ModuleDB`. Add a reference to `StateStore` to your module's keeper struct. Ex: + ```go type Keeper struct { db StateStore @@ -228,6 +242,7 @@ type Keeper struct { Then instantiate the `StateStore` instance via an `ormdb.ModuleDB` that is instantiated from the `SchemaDescriptor` above and one or more store services from `cosmossdk.io/core/store`. Ex: + ```go func NewKeeper(storeService store.KVStoreService) (*Keeper, error) { modDb, err := ormdb.NewModuleDB(MyModuleSchema, ormdb.ModuleDBOptions{KVStoreService: storeService}) @@ -247,6 +262,7 @@ func NewKeeper(storeService store.KVStoreService) (*Keeper, error) { The generated code for the ORM contains methods for inserting, updating, deleting and querying table entries. For each table in a .proto file, there is a type-safe table interface implemented in generated code. For instance, for a table named `Balance` there should be a `BalanceTable` interface that looks like this: + ```go type BalanceTable interface { Insert(ctx context.Context, balance *Balance) error @@ -268,6 +284,7 @@ type BalanceTable interface { This `BalanceTable` should be accessible from the `StateStore` interface (assuming our file is named `state.proto`) via a `BalanceTable()` accessor method. If all the above example tables/singletons were in the same `state.proto`, then `StateStore` would get generated like this: + ```go type BankStore interface { BalanceTable() BalanceTable @@ -279,6 +296,7 @@ type BankStore interface { ``` So to work with the `BalanceTable` in a keeper method we could use code like this: + ```go func (k keeper) AddBalance(ctx context.Context, acct []byte, denom string, amount uint64) error { balance, err := k.db.BalanceTable().Get(ctx, acct, denom) @@ -305,6 +323,7 @@ let's represent index keys for the different indexes (primary and secondary) on in the `Balance` table gets a struct `BalanceAccountDenomIndexKey` and the first index gets an index key `BalanceDenomIndexKey`. If we wanted to list all the denoms and amounts that an account holds, we would use `BalanceAccountDenomIndexKey` with a `List` query just on the account prefix. Ex: + ```go it, err := keeper.db.BalanceTable().List(ctx, BalanceAccountDenomIndexKey{}.WithAccount(acct)) ``` diff --git a/orm/cmd/protoc-gen-go-cosmos-orm-proto/main.go b/orm/cmd/protoc-gen-go-cosmos-orm-proto/main.go index 9428c514d6e5..0c3db5cf6b30 100644 --- a/orm/cmd/protoc-gen-go-cosmos-orm-proto/main.go +++ b/orm/cmd/protoc-gen-go-cosmos-orm-proto/main.go @@ -3,7 +3,7 @@ package main import ( "google.golang.org/protobuf/compiler/protogen" - "github.com/cosmos/cosmos-sdk/orm/internal/codegen" + "cosmossdk.io/orm/internal/codegen" ) func main() { diff --git a/orm/cmd/protoc-gen-go-cosmos-orm/main.go b/orm/cmd/protoc-gen-go-cosmos-orm/main.go index 9c06f9ac8b7c..bc83d887b6fe 100644 --- a/orm/cmd/protoc-gen-go-cosmos-orm/main.go +++ b/orm/cmd/protoc-gen-go-cosmos-orm/main.go @@ -3,7 +3,7 @@ package main import ( "google.golang.org/protobuf/compiler/protogen" - "github.com/cosmos/cosmos-sdk/orm/internal/codegen" + "cosmossdk.io/orm/internal/codegen" ) func main() { diff --git a/orm/encoding/encodeutil/util.go b/orm/encoding/encodeutil/util.go index d8fe8a1c2ed3..0d84093803f2 100644 --- a/orm/encoding/encodeutil/util.go +++ b/orm/encoding/encodeutil/util.go @@ -41,10 +41,9 @@ func ValuesOf(values ...interface{}) []protoreflect.Value { // this allows us to use imported messages, such as timestamppb.Timestamp // in iterators. value := values[i] - switch value.(type) { - case protoreflect.ProtoMessage: + if v, ok := value.(protoreflect.ProtoMessage); ok { if !reflect.ValueOf(value).IsNil() { - value = value.(protoreflect.ProtoMessage).ProtoReflect() + value = v.ProtoReflect() } else { value = nil } diff --git a/orm/encoding/ormfield/bool.go b/orm/encoding/ormfield/bool.go index 8fac99becb4c..454963b607ae 100644 --- a/orm/encoding/ormfield/bool.go +++ b/orm/encoding/ormfield/bool.go @@ -37,11 +37,12 @@ func (b BoolCodec) Compare(v1, v2 protoreflect.Value) int { if v2.IsValid() { b2 = v2.Bool() } - if b1 == b2 { + switch { + case b1 == b2: return 0 - } else if b1 { + case b1: return -1 - } else { + default: return 1 } } diff --git a/orm/encoding/ormfield/codec.go b/orm/encoding/ormfield/codec.go index 14a1d4804c71..ae18c5953935 100644 --- a/orm/encoding/ormfield/codec.go +++ b/orm/encoding/ormfield/codec.go @@ -3,12 +3,11 @@ package ormfield import ( "io" - "github.com/cosmos/cosmos-sdk/orm/types/ormerrors" + "cosmossdk.io/orm/types/ormerrors" + "google.golang.org/protobuf/reflect/protoreflect" "google.golang.org/protobuf/types/known/durationpb" "google.golang.org/protobuf/types/known/timestamppb" - - "google.golang.org/protobuf/reflect/protoreflect" ) // Codec defines an interface for decoding and encoding values in ORM index keys. @@ -72,15 +71,16 @@ func GetCodec(field protoreflect.FieldDescriptor, nonTerminal bool) (Codec, erro case protoreflect.BytesKind: if nonTerminal { return NonTerminalBytesCodec{}, nil - } else { - return BytesCodec{}, nil } + + return BytesCodec{}, nil case protoreflect.StringKind: if nonTerminal { return NonTerminalStringCodec{}, nil - } else { - return StringCodec{}, nil } + + return StringCodec{}, nil + case protoreflect.Uint32Kind: return CompactUint32Codec{}, nil case protoreflect.Fixed32Kind: diff --git a/orm/encoding/ormfield/codec_test.go b/orm/encoding/ormfield/codec_test.go index abab4d2d5a9b..b9e00281d466 100644 --- a/orm/encoding/ormfield/codec_test.go +++ b/orm/encoding/ormfield/codec_test.go @@ -4,19 +4,14 @@ import ( "bytes" "fmt" "testing" - "time" - - "google.golang.org/protobuf/types/known/timestamppb" - - "github.com/cosmos/cosmos-sdk/orm/encoding/ormfield" "google.golang.org/protobuf/reflect/protoreflect" "gotest.tools/v3/assert" "pgregory.net/rapid" - "github.com/cosmos/cosmos-sdk/orm/types/ormerrors" - - "github.com/cosmos/cosmos-sdk/orm/internal/testutil" + "cosmossdk.io/orm/encoding/ormfield" + "cosmossdk.io/orm/internal/testutil" + "cosmossdk.io/orm/types/ormerrors" ) func TestCodec(t *testing.T) { @@ -108,11 +103,12 @@ func TestCompactUInt32(t *testing.T) { by := ormfield.EncodeCompactUint32(y) cmp := bytes.Compare(bx, by) - if x < y { + switch { + case x < y: assert.Equal(t, -1, cmp) - } else if x == y { + case x == y: assert.Equal(t, 0, cmp) - } else { + default: assert.Equal(t, 1, cmp) } @@ -156,11 +152,12 @@ func TestCompactUInt64(t *testing.T) { by := ormfield.EncodeCompactUint64(y) cmp := bytes.Compare(bx, by) - if x < y { + switch { + case x < y: assert.Equal(t, -1, cmp) - } else if x == y { + case x == y: assert.Equal(t, 0, cmp) - } else { + default: assert.Equal(t, 1, cmp) } @@ -172,35 +169,3 @@ func TestCompactUInt64(t *testing.T) { assert.Equal(t, y, y2) }) } - -func TestTimestamp(t *testing.T) { - cdc := ormfield.TimestampCodec{} - - // nil value - buf := &bytes.Buffer{} - assert.NilError(t, cdc.Encode(protoreflect.Value{}, buf)) - assert.Equal(t, 1, len(buf.Bytes())) - val, err := cdc.Decode(buf) - assert.NilError(t, err) - assert.Assert(t, !val.IsValid()) - - // no nanos - ts := timestamppb.New(time.Date(2022, 1, 1, 12, 30, 15, 0, time.UTC)) - val = protoreflect.ValueOfMessage(ts.ProtoReflect()) - buf = &bytes.Buffer{} - assert.NilError(t, cdc.Encode(val, buf)) - assert.Equal(t, 6, len(buf.Bytes())) - val2, err := cdc.Decode(buf) - assert.NilError(t, err) - assert.Equal(t, 0, cdc.Compare(val, val2)) - - // nanos - ts = timestamppb.New(time.Date(2022, 1, 1, 12, 30, 15, 235809753, time.UTC)) - val = protoreflect.ValueOfMessage(ts.ProtoReflect()) - buf = &bytes.Buffer{} - assert.NilError(t, cdc.Encode(val, buf)) - assert.Equal(t, 9, len(buf.Bytes())) - val2, err = cdc.Decode(buf) - assert.NilError(t, err) - assert.Equal(t, 0, cdc.Compare(val, val2)) -} diff --git a/orm/encoding/ormfield/duration.go b/orm/encoding/ormfield/duration.go index f01e2a60e235..ad47173e3ff6 100644 --- a/orm/encoding/ormfield/duration.go +++ b/orm/encoding/ormfield/duration.go @@ -1,11 +1,124 @@ package ormfield import ( + "fmt" io "io" "google.golang.org/protobuf/reflect/protoreflect" ) +const ( + DurationSecondsMin = -315576000000 + DurationSecondsMax = 315576000000 + DurationNanosMin = -999999999 + DurationNanosMax = 999999999 +) + +type DurationCodec struct{} + +func (d DurationCodec) Encode(value protoreflect.Value, w io.Writer) error { + // nil case + if !value.IsValid() { + _, err := w.Write(timestampDurationNilBz) + return err + } + + seconds, nanos := getDurationSecondsAndNanos(value) + secondsInt := seconds.Int() + if secondsInt < DurationSecondsMin || secondsInt > DurationSecondsMax { + return fmt.Errorf("duration seconds is out of range %d, must be between %d and %d", secondsInt, DurationSecondsMin, DurationSecondsMax) + } + negative := secondsInt < 0 + // we subtract the min duration value to make sure secondsInt is always non-negative and starts at 0 + secondsInt -= DurationSecondsMin + err := encodeSeconds(secondsInt, w) + if err != nil { + return err + } + + nanosInt := nanos.Int() + if nanosInt == 0 { + _, err = w.Write(timestampZeroNanosBz) + return err + } + + if negative { + if nanosInt < DurationNanosMin || nanosInt > 0 { + return fmt.Errorf("negative duration nanos is out of range %d, must be between %d and %d", nanosInt, DurationNanosMin, 0) + } + nanosInt = -nanosInt + } else if nanosInt < 0 || nanosInt > DurationNanosMax { + return fmt.Errorf("duration nanos is out of range %d, must be between %d and %d", nanosInt, 0, DurationNanosMax) + } + + return encodeNanos(nanosInt, w) +} + +func (d DurationCodec) Decode(r Reader) (protoreflect.Value, error) { + isNil, seconds, err := decodeSeconds(r) + if isNil || err != nil { + return protoreflect.Value{}, err + } + + // we add the min duration value to get back the original value + seconds += DurationSecondsMin + + negative := seconds < 0 + + msg := durationMsgType.New() + msg.Set(durationSecondsField, protoreflect.ValueOfInt64(seconds)) + + nanos, err := decodeNanos(r) + if err != nil { + return protoreflect.Value{}, err + } + + if nanos == 0 { + return protoreflect.ValueOfMessage(msg), nil + } + + if negative { + nanos = -nanos + } + + msg.Set(durationNanosField, protoreflect.ValueOfInt32(nanos)) + return protoreflect.ValueOfMessage(msg), nil +} + +func (d DurationCodec) Compare(v1, v2 protoreflect.Value) int { + if !v1.IsValid() { + if !v2.IsValid() { + return 0 + } + return 1 + } + + if !v2.IsValid() { + return -1 + } + + s1, n1 := getDurationSecondsAndNanos(v1) + s2, n2 := getDurationSecondsAndNanos(v2) + c := compareInt(s1, s2) + if c != 0 { + return c + } + + return compareInt(n1, n2) +} + +func (d DurationCodec) IsOrdered() bool { + return true +} + +func (d DurationCodec) FixedBufferSize() int { + return timestampDurationBufferSize +} + +func (d DurationCodec) ComputeBufferSize(protoreflect.Value) (int, error) { + return timestampDurationBufferSize, nil +} + var ( durationSecondsField = durationMsgType.Descriptor().Fields().ByName("seconds") durationNanosField = durationMsgType.Descriptor().Fields().ByName("nanos") @@ -16,12 +129,12 @@ func getDurationSecondsAndNanos(value protoreflect.Value) (protoreflect.Value, p return msg.Get(durationSecondsField), msg.Get(durationNanosField) } -// DurationCodec encodes a google.protobuf.Duration value as 12 bytes using +// DurationV0Codec encodes a google.protobuf.Duration value as 12 bytes using // Int64Codec for seconds followed by Int32Codec for nanos. This allows for // sorted iteration. -type DurationCodec struct{} +type DurationV0Codec struct{} -func (d DurationCodec) Decode(r Reader) (protoreflect.Value, error) { +func (d DurationV0Codec) Decode(r Reader) (protoreflect.Value, error) { seconds, err := int64Codec.Decode(r) if err != nil { return protoreflect.Value{}, err @@ -36,7 +149,7 @@ func (d DurationCodec) Decode(r Reader) (protoreflect.Value, error) { return protoreflect.ValueOfMessage(msg), nil } -func (d DurationCodec) Encode(value protoreflect.Value, w io.Writer) error { +func (d DurationV0Codec) Encode(value protoreflect.Value, w io.Writer) error { seconds, nanos := getDurationSecondsAndNanos(value) err := int64Codec.Encode(seconds, w) if err != nil { @@ -45,25 +158,24 @@ func (d DurationCodec) Encode(value protoreflect.Value, w io.Writer) error { return int32Codec.Encode(nanos, w) } -func (d DurationCodec) Compare(v1, v2 protoreflect.Value) int { +func (d DurationV0Codec) Compare(v1, v2 protoreflect.Value) int { s1, n1 := getDurationSecondsAndNanos(v1) s2, n2 := getDurationSecondsAndNanos(v2) c := compareInt(s1, s2) if c != 0 { return c - } else { - return compareInt(n1, n2) } + return compareInt(n1, n2) } -func (d DurationCodec) IsOrdered() bool { +func (d DurationV0Codec) IsOrdered() bool { return true } -func (d DurationCodec) FixedBufferSize() int { +func (d DurationV0Codec) FixedBufferSize() int { return 12 } -func (d DurationCodec) ComputeBufferSize(protoreflect.Value) (int, error) { +func (d DurationV0Codec) ComputeBufferSize(protoreflect.Value) (int, error) { return d.FixedBufferSize(), nil } diff --git a/orm/encoding/ormfield/duration_test.go b/orm/encoding/ormfield/duration_test.go new file mode 100644 index 000000000000..285d86159d19 --- /dev/null +++ b/orm/encoding/ormfield/duration_test.go @@ -0,0 +1,158 @@ +package ormfield_test + +import ( + "bytes" + "testing" + "time" + + "google.golang.org/protobuf/reflect/protoreflect" + "google.golang.org/protobuf/types/known/durationpb" + "gotest.tools/v3/assert" + + "cosmossdk.io/orm/encoding/ormfield" +) + +func TestDuration(t *testing.T) { + t.Parallel() + cdc := ormfield.DurationCodec{} + + // nil value + t.Run("nil value", func(t *testing.T) { + t.Parallel() + buf := &bytes.Buffer{} + assert.NilError(t, cdc.Encode(protoreflect.Value{}, buf)) + assert.Equal(t, 1, len(buf.Bytes())) + val, err := cdc.Decode(buf) + assert.NilError(t, err) + assert.Assert(t, !val.IsValid()) + }) + + // no nanos + t.Run("no nanos", func(t *testing.T) { + t.Parallel() + dur, err := time.ParseDuration("100s") + assert.NilError(t, err) + durPb := durationpb.New(dur) + val := protoreflect.ValueOfMessage(durPb.ProtoReflect()) + buf := &bytes.Buffer{} + assert.NilError(t, cdc.Encode(val, buf)) + assert.Equal(t, 6, len(buf.Bytes())) + val2, err := cdc.Decode(buf) + assert.NilError(t, err) + assert.Equal(t, 0, cdc.Compare(val, val2)) + }) + + t.Run("nanos", func(t *testing.T) { + t.Parallel() + dur, err := time.ParseDuration("3879468295ns") + assert.NilError(t, err) + durPb := durationpb.New(dur) + val := protoreflect.ValueOfMessage(durPb.ProtoReflect()) + buf := &bytes.Buffer{} + assert.NilError(t, cdc.Encode(val, buf)) + assert.Equal(t, 9, len(buf.Bytes())) + val2, err := cdc.Decode(buf) + assert.NilError(t, err) + assert.Equal(t, 0, cdc.Compare(val, val2)) + }) + + t.Run("min value", func(t *testing.T) { + t.Parallel() + durPb := &durationpb.Duration{ + Seconds: -315576000000, + Nanos: -999999999, + } + val := protoreflect.ValueOfMessage(durPb.ProtoReflect()) + buf := &bytes.Buffer{} + assert.NilError(t, cdc.Encode(val, buf)) + assert.Equal(t, 9, len(buf.Bytes())) + val2, err := cdc.Decode(buf) + assert.NilError(t, err) + assert.Equal(t, 0, cdc.Compare(val, val2)) + }) + + t.Run("max value", func(t *testing.T) { + t.Parallel() + durPb := &durationpb.Duration{ + Seconds: 315576000000, + Nanos: 999999999, + } + val := protoreflect.ValueOfMessage(durPb.ProtoReflect()) + buf := &bytes.Buffer{} + assert.NilError(t, cdc.Encode(val, buf)) + assert.Equal(t, 9, len(buf.Bytes())) + val2, err := cdc.Decode(buf) + assert.NilError(t, err) + assert.Equal(t, 0, cdc.Compare(val, val2)) + }) +} + +func TestDurationOutOfRange(t *testing.T) { + t.Parallel() + cdc := ormfield.DurationCodec{} + + tt := []struct { + name string + dur *durationpb.Duration + expectErr string + }{ + { + name: "seconds too small", + dur: &durationpb.Duration{ + Seconds: -315576000001, + Nanos: 0, + }, + expectErr: "seconds is out of range", + }, + { + name: "seconds too big", + dur: &durationpb.Duration{ + Seconds: 315576000001, + Nanos: 0, + }, + expectErr: "seconds is out of range", + }, + { + name: "positive seconds negative nanos", + dur: &durationpb.Duration{ + Seconds: 0, + Nanos: -1, + }, + expectErr: "nanos is out of range", + }, + { + name: "positive seconds nanos too big", + dur: &durationpb.Duration{ + Seconds: 0, + Nanos: 1000000000, + }, + expectErr: "nanos is out of range", + }, + { + name: "negative seconds positive nanos", + dur: &durationpb.Duration{ + Seconds: -1, + Nanos: 1, + }, + expectErr: "negative duration nanos is out of range", + }, + { + name: "negative seconds nanos too small", + dur: &durationpb.Duration{ + Seconds: -1, + Nanos: -1000000000, + }, + expectErr: "negative duration nanos is out of range", + }, + } + for _, tc := range tt { + tc := tc + t.Run(tc.name, func(t *testing.T) { + t.Parallel() + val := protoreflect.ValueOfMessage(tc.dur.ProtoReflect()) + buf := &bytes.Buffer{} + err := cdc.Encode(val, buf) + assert.ErrorContains(t, err, tc.expectErr) + }) + } +} diff --git a/orm/encoding/ormfield/enum.go b/orm/encoding/ormfield/enum.go index 106ac311a8ff..03b95a3821bf 100644 --- a/orm/encoding/ormfield/enum.go +++ b/orm/encoding/ormfield/enum.go @@ -34,11 +34,12 @@ func (e EnumCodec) Compare(v1, v2 protoreflect.Value) int { if v2.IsValid() { y = v2.Enum() } - if x == y { + switch { + case x == y: return 0 - } else if x < y { + case x < y: return -1 - } else { + default: return 1 } } diff --git a/orm/encoding/ormfield/int64.go b/orm/encoding/ormfield/int64.go index cbe13420d7d5..1a1230ef206e 100644 --- a/orm/encoding/ormfield/int64.go +++ b/orm/encoding/ormfield/int64.go @@ -22,10 +22,10 @@ func (i Int64Codec) Decode(r Reader) (protoreflect.Value, error) { if x >= int64Max { x = x - int64Max - 1 return protoreflect.ValueOfInt64(int64(x)), err - } else { - y := int64(x) - int64Max - 1 - return protoreflect.ValueOfInt64(y), err } + + y := int64(x) - int64Max - 1 + return protoreflect.ValueOfInt64(y), err } func (i Int64Codec) Encode(value protoreflect.Value, w io.Writer) error { @@ -36,11 +36,11 @@ func (i Int64Codec) Encode(value protoreflect.Value, w io.Writer) error { if x >= -1 { y := uint64(x) + int64Max + 1 return binary.Write(w, binary.BigEndian, y) - } else { - x += int64Max - x += 1 - return binary.Write(w, binary.BigEndian, uint64(x)) } + + x += int64Max + x++ + return binary.Write(w, binary.BigEndian, uint64(x)) } func (i Int64Codec) Compare(v1, v2 protoreflect.Value) int { @@ -67,11 +67,12 @@ func compareInt(v1, v2 protoreflect.Value) int { if v2.IsValid() { y = v2.Int() } - if x == y { + switch { + case x == y: return 0 - } else if x < y { + case x < y: return -1 - } else { + default: return 1 } } diff --git a/orm/encoding/ormfield/timestamp.go b/orm/encoding/ormfield/timestamp.go index eb13c3de74b0..ab3c5049cb36 100644 --- a/orm/encoding/ormfield/timestamp.go +++ b/orm/encoding/ormfield/timestamp.go @@ -21,38 +21,33 @@ import ( type TimestampCodec struct{} const ( - timestampNilValue = 0xFF - timestampZeroNanosValue = 0x0 - timestampSecondsMin = -62135579038 - timestampSecondsMax = 253402318799 - timestampNanosMax = 999999999 + timestampDurationNilValue = 0xFF + timestampDurationZeroNanosValue = 0x0 + timestampDurationBufferSize = 9 + TimestampSecondsMin = -62135596800 + TimestampSecondsMax = 253402300799 + TimestampNanosMax = 999999999 ) var ( - timestampNilBz = []byte{timestampNilValue} - timestampZeroNanosBz = []byte{timestampZeroNanosValue} + timestampDurationNilBz = []byte{timestampDurationNilValue} + timestampZeroNanosBz = []byte{timestampDurationZeroNanosValue} ) func (t TimestampCodec) Encode(value protoreflect.Value, w io.Writer) error { // nil case if !value.IsValid() { - _, err := w.Write(timestampNilBz) + _, err := w.Write(timestampDurationNilBz) return err } seconds, nanos := getTimestampSecondsAndNanos(value) secondsInt := seconds.Int() - if secondsInt < timestampSecondsMin || secondsInt > timestampSecondsMax { - return fmt.Errorf("seconds is out of range %d, must be between %d and %d", secondsInt, timestampSecondsMin, timestampSecondsMax) + if secondsInt < TimestampSecondsMin || secondsInt > TimestampSecondsMax { + return fmt.Errorf("timestamp seconds is out of range %d, must be between %d and %d", secondsInt, TimestampSecondsMin, TimestampSecondsMax) } - secondsInt -= timestampSecondsMin - var secondsBz [5]byte - // write the seconds buffer from the end to the front - for i := 4; i >= 0; i-- { - secondsBz[i] = byte(secondsInt) - secondsInt >>= 8 - } - _, err := w.Write(secondsBz[:]) + secondsInt -= TimestampSecondsMin + err := encodeSeconds(secondsInt, w) if err != nil { return err } @@ -63,65 +58,104 @@ func (t TimestampCodec) Encode(value protoreflect.Value, w io.Writer) error { return err } - if nanosInt < 0 || nanosInt > timestampNanosMax { - return fmt.Errorf("nanos is out of range %d, must be between %d and %d", secondsInt, 0, timestampNanosMax) + if nanosInt < 0 || nanosInt > TimestampNanosMax { + return fmt.Errorf("timestamp nanos is out of range %d, must be between %d and %d", secondsInt, 0, TimestampNanosMax) } + return encodeNanos(nanosInt, w) +} + +func encodeSeconds(secondsInt int64, w io.Writer) error { + var secondsBz [5]byte + // write the seconds buffer from the end to the front + for i := 4; i >= 0; i-- { + secondsBz[i] = byte(secondsInt) + secondsInt >>= 8 + } + _, err := w.Write(secondsBz[:]) + return err +} + +func encodeNanos(nanosInt int64, w io.Writer) error { var nanosBz [4]byte for i := 3; i >= 0; i-- { nanosBz[i] = byte(nanosInt) nanosInt >>= 8 } - nanosBz[0] = nanosBz[0] | 0xC0 - _, err = w.Write(nanosBz[:]) + nanosBz[0] |= 0xC0 + _, err := w.Write(nanosBz[:]) return err } func (t TimestampCodec) Decode(r Reader) (protoreflect.Value, error) { - b0, err := r.ReadByte() + isNil, seconds, err := decodeSeconds(r) + if isNil || err != nil { + return protoreflect.Value{}, err + } + + seconds += TimestampSecondsMin + + msg := timestampMsgType.New() + msg.Set(timestampSecondsField, protoreflect.ValueOfInt64(seconds)) + + nanos, err := decodeNanos(r) if err != nil { return protoreflect.Value{}, err } - if b0 == timestampNilValue { - return protoreflect.Value{}, nil + if nanos == 0 { + return protoreflect.ValueOfMessage(msg), nil + } + + msg.Set(timestampNanosField, protoreflect.ValueOfInt32(nanos)) + return protoreflect.ValueOfMessage(msg), nil +} + +func decodeSeconds(r Reader) (isNil bool, seconds int64, err error) { + b0, err := r.ReadByte() + if err != nil { + return false, 0, err + } + + if b0 == timestampDurationNilValue { + return true, 0, nil } var secondsBz [4]byte n, err := r.Read(secondsBz[:]) if err != nil { - return protoreflect.Value{}, err + return false, 0, err } if n < 4 { - return protoreflect.Value{}, io.EOF + return false, 0, io.EOF } - seconds := int64(b0) + seconds = int64(b0) for i := 0; i < 4; i++ { seconds <<= 8 seconds |= int64(secondsBz[i]) } - seconds += timestampSecondsMin - msg := timestampMsgType.New() - msg.Set(timestampSecondsField, protoreflect.ValueOfInt64(seconds)) + return false, seconds, nil +} - b0, err = r.ReadByte() +func decodeNanos(r Reader) (int32, error) { + b0, err := r.ReadByte() if err != nil { - return protoreflect.Value{}, err + return 0, err } - if b0 == timestampZeroNanosValue { - return protoreflect.ValueOfMessage(msg), nil + if b0 == timestampDurationZeroNanosValue { + return 0, nil } var nanosBz [3]byte - n, err = r.Read(nanosBz[:]) + n, err := r.Read(nanosBz[:]) if err != nil { - return protoreflect.Value{}, err + return 0, err } if n < 3 { - return protoreflect.Value{}, io.EOF + return 0, io.EOF } nanos := int32(b0) & 0x3F // clear first two bits @@ -130,8 +164,7 @@ func (t TimestampCodec) Decode(r Reader) (protoreflect.Value, error) { nanos |= int32(nanosBz[i]) } - msg.Set(timestampNanosField, protoreflect.ValueOfInt32(nanos)) - return protoreflect.ValueOfMessage(msg), nil + return nanos, nil } func (t TimestampCodec) Compare(v1, v2 protoreflect.Value) int { @@ -151,9 +184,9 @@ func (t TimestampCodec) Compare(v1, v2 protoreflect.Value) int { c := compareInt(s1, s2) if c != 0 { return c - } else { - return compareInt(n1, n2) } + + return compareInt(n1, n2) } func (t TimestampCodec) IsOrdered() bool { @@ -161,11 +194,11 @@ func (t TimestampCodec) IsOrdered() bool { } func (t TimestampCodec) FixedBufferSize() int { - return 9 + return timestampDurationBufferSize } func (t TimestampCodec) ComputeBufferSize(protoreflect.Value) (int, error) { - return 9, nil + return timestampDurationBufferSize, nil } // TimestampV0Codec encodes a google.protobuf.Timestamp value as 12 bytes using @@ -215,9 +248,9 @@ func (t TimestampV0Codec) Compare(v1, v2 protoreflect.Value) int { c := compareInt(s1, s2) if c != 0 { return c - } else { - return compareInt(n1, n2) } + + return compareInt(n1, n2) } func (t TimestampV0Codec) IsOrdered() bool { diff --git a/orm/encoding/ormfield/timestamp_test.go b/orm/encoding/ormfield/timestamp_test.go new file mode 100644 index 000000000000..52b7caeadacd --- /dev/null +++ b/orm/encoding/ormfield/timestamp_test.go @@ -0,0 +1,126 @@ +package ormfield_test + +import ( + "bytes" + "testing" + "time" + + "google.golang.org/protobuf/reflect/protoreflect" + "google.golang.org/protobuf/types/known/timestamppb" + "gotest.tools/v3/assert" + + "cosmossdk.io/orm/encoding/ormfield" +) + +func TestTimestamp(t *testing.T) { + t.Parallel() + cdc := ormfield.TimestampCodec{} + + t.Run("nil value", func(t *testing.T) { + t.Parallel() + buf := &bytes.Buffer{} + assert.NilError(t, cdc.Encode(protoreflect.Value{}, buf)) + assert.Equal(t, 1, len(buf.Bytes())) + val, err := cdc.Decode(buf) + assert.NilError(t, err) + assert.Assert(t, !val.IsValid()) + }) + + t.Run("no nanos", func(t *testing.T) { + t.Parallel() + ts := timestamppb.New(time.Date(2022, 1, 1, 12, 30, 15, 0, time.UTC)) + val := protoreflect.ValueOfMessage(ts.ProtoReflect()) + buf := &bytes.Buffer{} + assert.NilError(t, cdc.Encode(val, buf)) + assert.Equal(t, 6, len(buf.Bytes())) + val2, err := cdc.Decode(buf) + assert.NilError(t, err) + assert.Equal(t, 0, cdc.Compare(val, val2)) + }) + + t.Run("nanos", func(t *testing.T) { + t.Parallel() + ts := timestamppb.New(time.Date(2022, 1, 1, 12, 30, 15, 235809753, time.UTC)) + val := protoreflect.ValueOfMessage(ts.ProtoReflect()) + buf := &bytes.Buffer{} + assert.NilError(t, cdc.Encode(val, buf)) + assert.Equal(t, 9, len(buf.Bytes())) + val2, err := cdc.Decode(buf) + assert.NilError(t, err) + assert.Equal(t, 0, cdc.Compare(val, val2)) + }) + + t.Run("min value", func(t *testing.T) { + t.Parallel() + ts := timestamppb.New(time.Date(1, 1, 1, 0, 0, 0, 0, time.UTC)) + val := protoreflect.ValueOfMessage(ts.ProtoReflect()) + buf := &bytes.Buffer{} + assert.NilError(t, cdc.Encode(val, buf)) + assert.Equal(t, 6, len(buf.Bytes())) + assert.Assert(t, bytes.Equal(buf.Bytes(), []byte{0, 0, 0, 0, 0, 0})) // the minimum value should be all zeros + val2, err := cdc.Decode(buf) + assert.NilError(t, err) + assert.Equal(t, 0, cdc.Compare(val, val2)) + }) + + t.Run("max value", func(t *testing.T) { + t.Parallel() + ts := timestamppb.New(time.Date(9999, 12, 31, 23, 59, 59, 999999999, time.UTC)) + val := protoreflect.ValueOfMessage(ts.ProtoReflect()) + buf := &bytes.Buffer{} + assert.NilError(t, cdc.Encode(val, buf)) + assert.Equal(t, 9, len(buf.Bytes())) + val2, err := cdc.Decode(buf) + assert.NilError(t, err) + assert.Equal(t, 0, cdc.Compare(val, val2)) + }) +} + +func TestTimestampOutOfRange(t *testing.T) { + t.Parallel() + cdc := ormfield.TimestampCodec{} + + tt := []struct { + name string + ts *timestamppb.Timestamp + expectErr string + }{ + { + name: "before min", + ts: timestamppb.New(time.Date(0, 1, 1, 0, 0, 0, 0, time.UTC)), + expectErr: "timestamp seconds is out of range", + }, + { + name: "after max", + ts: timestamppb.New(time.Date(10000, 1, 1, 0, 0, 0, 0, time.UTC)), + expectErr: "timestamp seconds is out of range", + }, + { + name: "nanos too small", + ts: ×tamppb.Timestamp{ + Seconds: 0, + Nanos: -1, + }, + expectErr: "timestamp nanos is out of range", + }, + + { + name: "nanos too big", + ts: ×tamppb.Timestamp{ + Seconds: 0, + Nanos: 1000000000, + }, + expectErr: "timestamp nanos is out of range", + }, + } + for _, tc := range tt { + tc := tc + t.Run(tc.name, func(t *testing.T) { + t.Parallel() + val := protoreflect.ValueOfMessage(tc.ts.ProtoReflect()) + buf := &bytes.Buffer{} + err := cdc.Encode(val, buf) + assert.ErrorContains(t, err, tc.expectErr) + }) + } +} diff --git a/orm/encoding/ormfield/uint64.go b/orm/encoding/ormfield/uint64.go index e4f654239905..8623e516b155 100644 --- a/orm/encoding/ormfield/uint64.go +++ b/orm/encoding/ormfield/uint64.go @@ -49,11 +49,12 @@ func compareUint(v1, v2 protoreflect.Value) int { if v2.IsValid() { y = v2.Uint() } - if x == y { + switch { + case x == y: return 0 - } else if x < y { + case x < y: return -1 - } else { + default: return 1 } } diff --git a/orm/encoding/ormkv/entry.go b/orm/encoding/ormkv/entry.go index 2098afbac6a9..fd44833994cc 100644 --- a/orm/encoding/ormkv/entry.go +++ b/orm/encoding/ormkv/entry.go @@ -4,10 +4,10 @@ import ( "fmt" "strings" - "github.com/cosmos/cosmos-sdk/orm/internal/stablejson" - "google.golang.org/protobuf/proto" "google.golang.org/protobuf/reflect/protoreflect" + + "cosmossdk.io/orm/internal/stablejson" ) // Entry defines a logical representation of a kv-store entry for ORM instances. @@ -43,14 +43,14 @@ func (p *PrimaryKeyEntry) GetTableName() protoreflect.FullName { func (p *PrimaryKeyEntry) String() string { if p.Value == nil { return fmt.Sprintf("PK %s %s -> _", p.TableName, fmtValues(p.Key)) - } else { - valBz, err := stablejson.Marshal(p.Value) - valStr := string(valBz) - if err != nil { - valStr = fmt.Sprintf("ERR %v", err) - } - return fmt.Sprintf("PK %s %s -> %s", p.TableName, fmtValues(p.Key), valStr) } + + valBz, err := stablejson.Marshal(p.Value) + valStr := string(valBz) + if err != nil { + valStr = fmt.Sprintf("ERR %v", err) + } + return fmt.Sprintf("PK %s %s -> %s", p.TableName, fmtValues(p.Key), valStr) } func fmtValues(values []protoreflect.Value) string { @@ -108,9 +108,9 @@ func fmtFields(fields []protoreflect.Name) string { func (i *IndexKeyEntry) String() string { if i.IsUnique { return fmt.Sprintf("UNIQ %s", i.string()) - } else { - return fmt.Sprintf("IDX %s", i.string()) } + + return fmt.Sprintf("IDX %s", i.string()) } // SeqEntry represents a sequence for tables with auto-incrementing primary keys. diff --git a/orm/encoding/ormkv/entry_test.go b/orm/encoding/ormkv/entry_test.go index 9a78d60825ac..91c9fd9e251e 100644 --- a/orm/encoding/ormkv/entry_test.go +++ b/orm/encoding/ormkv/entry_test.go @@ -6,9 +6,9 @@ import ( "google.golang.org/protobuf/reflect/protoreflect" "gotest.tools/v3/assert" - "github.com/cosmos/cosmos-sdk/orm/encoding/encodeutil" - "github.com/cosmos/cosmos-sdk/orm/encoding/ormkv" - "github.com/cosmos/cosmos-sdk/orm/internal/testpb" + "cosmossdk.io/orm/encoding/encodeutil" + "cosmossdk.io/orm/encoding/ormkv" + "cosmossdk.io/orm/internal/testpb" ) var aFullName = (&testpb.ExampleTable{}).ProtoReflect().Descriptor().FullName() diff --git a/orm/encoding/ormkv/index_key.go b/orm/encoding/ormkv/index_key.go index 55284f220636..bcb2341ecc6e 100644 --- a/orm/encoding/ormkv/index_key.go +++ b/orm/encoding/ormkv/index_key.go @@ -4,9 +4,9 @@ import ( "bytes" "io" - "github.com/cosmos/cosmos-sdk/orm/types/ormerrors" - "google.golang.org/protobuf/reflect/protoreflect" + + "cosmossdk.io/orm/types/ormerrors" ) // IndexKeyCodec is the codec for (non-unique) index keys. diff --git a/orm/encoding/ormkv/index_key_test.go b/orm/encoding/ormkv/index_key_test.go index 9625641bf1c6..eefcef35e205 100644 --- a/orm/encoding/ormkv/index_key_test.go +++ b/orm/encoding/ormkv/index_key_test.go @@ -8,9 +8,9 @@ import ( "gotest.tools/v3/assert" "pgregory.net/rapid" - "github.com/cosmos/cosmos-sdk/orm/encoding/ormkv" - "github.com/cosmos/cosmos-sdk/orm/internal/testpb" - "github.com/cosmos/cosmos-sdk/orm/internal/testutil" + "cosmossdk.io/orm/encoding/ormkv" + "cosmossdk.io/orm/internal/testpb" + "cosmossdk.io/orm/internal/testutil" ) func TestIndexKeyCodec(t *testing.T) { diff --git a/orm/encoding/ormkv/key_codec.go b/orm/encoding/ormkv/key_codec.go index 4d16a7bb9b8c..cc7b87b8e6a0 100644 --- a/orm/encoding/ormkv/key_codec.go +++ b/orm/encoding/ormkv/key_codec.go @@ -4,12 +4,11 @@ import ( "bytes" "io" - "github.com/cosmos/cosmos-sdk/orm/types/ormerrors" - "google.golang.org/protobuf/reflect/protoreflect" - "github.com/cosmos/cosmos-sdk/orm/encoding/encodeutil" - "github.com/cosmos/cosmos-sdk/orm/encoding/ormfield" + "cosmossdk.io/orm/encoding/encodeutil" + "cosmossdk.io/orm/encoding/ormfield" + "cosmossdk.io/orm/types/ormerrors" ) type KeyCodec struct { @@ -177,11 +176,12 @@ func (cdc *KeyCodec) CompareKeys(values1, values2 []protoreflect.Value) int { } // values are equal but arrays of different length - if j == k { + switch { + case j == k: return 0 - } else if j < k { + case j < k: return -1 - } else { + default: return 1 } } @@ -247,19 +247,20 @@ func (cdc KeyCodec) CheckValidRangeIterationKeys(start, end []protoreflect.Value y := end[i] cmp = fieldCdc.Compare(x, y) - if cmp > 0 { + switch { + case cmp > 0: return ormerrors.InvalidRangeIterationKeys.Wrapf( "start must be before end for field %s", cdc.fieldDescriptors[i].FullName(), ) - } else if !fieldCdc.IsOrdered() && cmp != 0 { + case !fieldCdc.IsOrdered() && cmp != 0: descriptor := cdc.fieldDescriptors[i] return ormerrors.InvalidRangeIterationKeys.Wrapf( "field %s of kind %s doesn't support ordered range iteration", descriptor.FullName(), descriptor.Kind(), ) - } else if cmp < 0 { + case cmp < 0: break } } diff --git a/orm/encoding/ormkv/key_codec_test.go b/orm/encoding/ormkv/key_codec_test.go index 2b5ae8e7d7d6..b2937426a7a0 100644 --- a/orm/encoding/ormkv/key_codec_test.go +++ b/orm/encoding/ormkv/key_codec_test.go @@ -9,10 +9,10 @@ import ( "gotest.tools/v3/assert" "pgregory.net/rapid" - "github.com/cosmos/cosmos-sdk/orm/encoding/encodeutil" - "github.com/cosmos/cosmos-sdk/orm/encoding/ormkv" - "github.com/cosmos/cosmos-sdk/orm/internal/testpb" - "github.com/cosmos/cosmos-sdk/orm/internal/testutil" + "cosmossdk.io/orm/encoding/encodeutil" + "cosmossdk.io/orm/encoding/ormkv" + "cosmossdk.io/orm/internal/testpb" + "cosmossdk.io/orm/internal/testutil" ) func TestKeyCodec(t *testing.T) { diff --git a/orm/encoding/ormkv/primary_key.go b/orm/encoding/ormkv/primary_key.go index ff4509cb562e..6c02d7e6b3b4 100644 --- a/orm/encoding/ormkv/primary_key.go +++ b/orm/encoding/ormkv/primary_key.go @@ -4,11 +4,10 @@ import ( "bytes" "io" - "github.com/cosmos/cosmos-sdk/orm/types/ormerrors" - "google.golang.org/protobuf/proto" - "google.golang.org/protobuf/reflect/protoreflect" + + "cosmossdk.io/orm/types/ormerrors" ) // PrimaryKeyCodec is the codec for primary keys. diff --git a/orm/encoding/ormkv/primary_key_test.go b/orm/encoding/ormkv/primary_key_test.go index ece72754a7ec..6ae43a8c0ba7 100644 --- a/orm/encoding/ormkv/primary_key_test.go +++ b/orm/encoding/ormkv/primary_key_test.go @@ -10,9 +10,9 @@ import ( "gotest.tools/v3/assert" "pgregory.net/rapid" - "github.com/cosmos/cosmos-sdk/orm/encoding/ormkv" - "github.com/cosmos/cosmos-sdk/orm/internal/testpb" - "github.com/cosmos/cosmos-sdk/orm/internal/testutil" + "cosmossdk.io/orm/encoding/ormkv" + "cosmossdk.io/orm/internal/testpb" + "cosmossdk.io/orm/internal/testutil" ) func TestPrimaryKeyCodec(t *testing.T) { diff --git a/orm/encoding/ormkv/seq.go b/orm/encoding/ormkv/seq.go index 59e38dc0e67f..ace5fe3d2eba 100644 --- a/orm/encoding/ormkv/seq.go +++ b/orm/encoding/ormkv/seq.go @@ -4,9 +4,9 @@ import ( "bytes" "encoding/binary" - "github.com/cosmos/cosmos-sdk/orm/types/ormerrors" - "google.golang.org/protobuf/reflect/protoreflect" + + "cosmossdk.io/orm/types/ormerrors" ) // SeqCodec is the codec for auto-incrementing uint64 primary key sequences. diff --git a/orm/encoding/ormkv/seq_test.go b/orm/encoding/ormkv/seq_test.go index 90a3c2b8c201..4b9742a25719 100644 --- a/orm/encoding/ormkv/seq_test.go +++ b/orm/encoding/ormkv/seq_test.go @@ -4,12 +4,11 @@ import ( "bytes" "testing" - "github.com/cosmos/cosmos-sdk/orm/encoding/ormkv" - "gotest.tools/v3/assert" "pgregory.net/rapid" - "github.com/cosmos/cosmos-sdk/orm/internal/testpb" + "cosmossdk.io/orm/encoding/ormkv" + "cosmossdk.io/orm/internal/testpb" ) func TestSeqCodec(t *testing.T) { diff --git a/orm/encoding/ormkv/unique_key.go b/orm/encoding/ormkv/unique_key.go index e9d36cb5ae6f..76ac788a50d4 100644 --- a/orm/encoding/ormkv/unique_key.go +++ b/orm/encoding/ormkv/unique_key.go @@ -4,9 +4,9 @@ import ( "bytes" "io" - "github.com/cosmos/cosmos-sdk/orm/types/ormerrors" - "google.golang.org/protobuf/reflect/protoreflect" + + "cosmossdk.io/orm/types/ormerrors" ) // UniqueKeyCodec is the codec for unique indexes. @@ -107,12 +107,12 @@ func (u UniqueKeyCodec) DecodeIndexKey(k, v []byte) (indexFields, primaryKey []p return ks, pk, nil } -func (cdc UniqueKeyCodec) extractPrimaryKey(keyValues, valueValues []protoreflect.Value) []protoreflect.Value { - numPkFields := len(cdc.pkFieldOrder) +func (u UniqueKeyCodec) extractPrimaryKey(keyValues, valueValues []protoreflect.Value) []protoreflect.Value { + numPkFields := len(u.pkFieldOrder) pkValues := make([]protoreflect.Value, numPkFields) for i := 0; i < numPkFields; i++ { - fo := cdc.pkFieldOrder[i] + fo := u.pkFieldOrder[i] if fo.inKey { pkValues[i] = keyValues[fo.i] } else { @@ -160,11 +160,10 @@ func (u UniqueKeyCodec) EncodeEntry(entry Entry) (k, v []byte, err error) { if !fieldOrder.inKey { // goes in values because it is not present in the index key otherwise values = append(values, value) - } else { - // does not go in values, but we need to verify that the value in index values matches the primary key value - if u.keyCodec.fieldCodecs[fieldOrder.i].Compare(value, indexEntry.IndexValues[fieldOrder.i]) != 0 { - return nil, nil, ormerrors.BadDecodeEntry.Wrapf("value in primary key does not match corresponding value in index key") - } + } + // does not go in values, but we need to verify that the value in index values matches the primary key value + if u.keyCodec.fieldCodecs[fieldOrder.i].Compare(value, indexEntry.IndexValues[fieldOrder.i]) != 0 { + return nil, nil, ormerrors.BadDecodeEntry.Wrapf("value in primary key does not match corresponding value in index key") } } diff --git a/orm/encoding/ormkv/unique_key_test.go b/orm/encoding/ormkv/unique_key_test.go index c015e671e397..f7448d409d58 100644 --- a/orm/encoding/ormkv/unique_key_test.go +++ b/orm/encoding/ormkv/unique_key_test.go @@ -9,10 +9,10 @@ import ( "gotest.tools/v3/assert" "pgregory.net/rapid" - "github.com/cosmos/cosmos-sdk/orm/encoding/ormkv" - "github.com/cosmos/cosmos-sdk/orm/internal/testpb" - "github.com/cosmos/cosmos-sdk/orm/internal/testutil" - "github.com/cosmos/cosmos-sdk/orm/types/ormerrors" + "cosmossdk.io/orm/encoding/ormkv" + "cosmossdk.io/orm/internal/testpb" + "cosmossdk.io/orm/internal/testutil" + "cosmossdk.io/orm/types/ormerrors" ) func TestUniqueKeyCodec(t *testing.T) { @@ -46,9 +46,8 @@ func TestUniqueKeyCodec(t *testing.T) { if isTrivialUniqueKey { assert.ErrorContains(t, err, "no new uniqueness constraint") return - } else { - assert.NilError(t, err) } + assert.NilError(t, err) for i := 0; i < 100; i++ { a := testutil.GenA.Draw(t, fmt.Sprintf("a%d", i)) diff --git a/orm/go.mod b/orm/go.mod index e7d0080a1b75..9b77809e12d3 100644 --- a/orm/go.mod +++ b/orm/go.mod @@ -1,9 +1,9 @@ -module github.com/cosmos/cosmos-sdk/orm +module cosmossdk.io/orm go 1.20 require ( - cosmossdk.io/api v0.3.2-0.20230313131911-55bf5d4efbe7 + cosmossdk.io/api v0.4.0 cosmossdk.io/core v0.6.1 cosmossdk.io/depinject v1.0.0-alpha.3 cosmossdk.io/errors v1.0.0-beta.7 @@ -14,7 +14,7 @@ require ( github.com/iancoleman/strcase v0.2.0 github.com/regen-network/gocuke v0.6.2 github.com/stretchr/testify v1.8.2 - golang.org/x/exp v0.0.0-20230315142452-642cacee5cc0 + golang.org/x/exp v0.0.0-20230321023759-10a507213a29 google.golang.org/grpc v1.54.0 google.golang.org/protobuf v1.30.0 gotest.tools/v3 v3.4.0 @@ -29,39 +29,39 @@ require ( github.com/cockroachdb/apd/v3 v3.1.0 // indirect github.com/cockroachdb/errors v1.9.1 // indirect github.com/cockroachdb/logtags v0.0.0-20230118201751-21c54148d20b // indirect - github.com/cockroachdb/pebble v0.0.0-20230315223031-1e5ddd10389e // indirect + github.com/cockroachdb/pebble v0.0.0-20230412222916-60cfeb46143b // indirect github.com/cockroachdb/redact v1.1.3 // indirect - github.com/cosmos/gogoproto v1.4.6 // indirect + github.com/cosmos/gogoproto v1.4.8 // indirect github.com/cucumber/common/gherkin/go/v22 v22.0.0 // indirect github.com/cucumber/common/messages/go/v17 v17.1.1 // indirect github.com/davecgh/go-spew v1.1.1 // indirect github.com/fsnotify/fsnotify v1.6.0 // indirect - github.com/getsentry/sentry-go v0.19.0 // indirect + github.com/getsentry/sentry-go v0.20.0 // indirect github.com/gofrs/uuid v4.2.0+incompatible // indirect github.com/gogo/protobuf v1.3.2 // indirect github.com/golang/protobuf v1.5.3 // indirect github.com/golang/snappy v0.0.4 // indirect github.com/google/btree v1.1.2 // indirect - github.com/klauspost/compress v1.16.3 // indirect + github.com/klauspost/compress v1.16.5 // indirect github.com/kr/pretty v0.3.1 // indirect github.com/kr/text v0.2.0 // indirect github.com/lib/pq v1.10.7 // indirect - github.com/linxGnu/grocksdb v1.7.15 // indirect + github.com/linxGnu/grocksdb v1.7.16 // indirect github.com/matttproud/golang_protobuf_extensions v1.0.4 // indirect github.com/onsi/gomega v1.20.0 // indirect github.com/pkg/errors v0.9.1 // indirect github.com/pmezard/go-difflib v1.0.0 // indirect - github.com/prometheus/client_golang v1.14.0 // indirect + github.com/prometheus/client_golang v1.15.0 // indirect github.com/prometheus/client_model v0.3.0 // indirect github.com/prometheus/common v0.42.0 // indirect github.com/prometheus/procfs v0.9.0 // indirect - github.com/rogpeppe/go-internal v1.9.0 // indirect + github.com/rogpeppe/go-internal v1.10.0 // indirect github.com/spf13/cast v1.5.0 // indirect github.com/syndtr/goleveldb v1.0.1-0.20220721030215-126854af5e6d // indirect - golang.org/x/net v0.8.0 // indirect - golang.org/x/sys v0.6.0 // indirect - golang.org/x/text v0.8.0 // indirect - google.golang.org/genproto v0.0.0-20230320184635-7606e756e683 // indirect + golang.org/x/net v0.9.0 // indirect + golang.org/x/sys v0.7.0 // indirect + golang.org/x/text v0.9.0 // indirect + google.golang.org/genproto v0.0.0-20230410155749-daa745c078e1 // indirect gopkg.in/yaml.v2 v2.4.0 // indirect gopkg.in/yaml.v3 v3.0.1 // indirect sigs.k8s.io/yaml v1.3.0 // indirect diff --git a/orm/go.sum b/orm/go.sum index f7aaf6d92164..51d795867fa5 100644 --- a/orm/go.sum +++ b/orm/go.sum @@ -1,6 +1,6 @@ cloud.google.com/go v0.26.0/go.mod h1:aQUYkXzVsufM+DwF1aE+0xfcU+56JwCaLick0ClmMTw= -cosmossdk.io/api v0.3.2-0.20230313131911-55bf5d4efbe7 h1:4LrWK+uGP5IxznxtHHsHD+ZBs2+oZRH2loYOGjHLzZM= -cosmossdk.io/api v0.3.2-0.20230313131911-55bf5d4efbe7/go.mod h1:yVns7mKgcsG+hZW/3C5FdJtC6QYWdFIcRlKb9+5HV5g= +cosmossdk.io/api v0.4.0 h1:x90DmdidP6EhzktAa/6/IofSHidDnPjahdlrUvyQZQw= +cosmossdk.io/api v0.4.0/go.mod h1:TWDzBhUBhI1LhSf2XSYpfIBf6D4mbLu/fvzvDfhcaYM= cosmossdk.io/core v0.6.1 h1:OBy7TI2W+/gyn2z40vVvruK3di+cAluinA6cybFbE7s= cosmossdk.io/core v0.6.1/go.mod h1:g3MMBCBXtxbDWBURDVnJE7XML4BG5qENhs0gzkcpuFA= cosmossdk.io/depinject v1.0.0-alpha.3 h1:6evFIgj//Y3w09bqOUOzEpFj5tsxBqdc5CfkO7z+zfw= @@ -41,8 +41,8 @@ github.com/cockroachdb/errors v1.9.1/go.mod h1:2sxOtL2WIc096WSZqZ5h8fa17rdDq9HZO github.com/cockroachdb/logtags v0.0.0-20211118104740-dabe8e521a4f/go.mod h1:Vz9DsVWQQhf3vs21MhPMZpMGSht7O/2vFW2xusFUVOs= github.com/cockroachdb/logtags v0.0.0-20230118201751-21c54148d20b h1:r6VH0faHjZeQy818SGhaone5OnYfxFR/+AzdY3sf5aE= github.com/cockroachdb/logtags v0.0.0-20230118201751-21c54148d20b/go.mod h1:Vz9DsVWQQhf3vs21MhPMZpMGSht7O/2vFW2xusFUVOs= -github.com/cockroachdb/pebble v0.0.0-20230315223031-1e5ddd10389e h1:CDuLmyaZ1pD4OJHHtubKqgu/Byw5zAnm+gArJsyj96Q= -github.com/cockroachdb/pebble v0.0.0-20230315223031-1e5ddd10389e/go.mod h1:9lRMC4XN3/BLPtIp6kAKwIaHu369NOf2rMucPzipz50= +github.com/cockroachdb/pebble v0.0.0-20230412222916-60cfeb46143b h1:92ve6F1Pls/eqd+V+102lOMRJatgpqqsQvbT9Bl/fjg= +github.com/cockroachdb/pebble v0.0.0-20230412222916-60cfeb46143b/go.mod h1:9lRMC4XN3/BLPtIp6kAKwIaHu369NOf2rMucPzipz50= github.com/cockroachdb/redact v1.1.3 h1:AKZds10rFSIj7qADf0g46UixK8NNLwWTNdCIGS5wfSQ= github.com/cockroachdb/redact v1.1.3/go.mod h1:BVNblN9mBWFyMyqK1k3AAiSxhvhfK2oOZZ2lK+dpvRg= github.com/codegangsta/inject v0.0.0-20150114235600-33e0aa1cb7c0/go.mod h1:4Zcjuz89kmFXt9morQgcfYZAYZ5n8WHjt81YYWIwtTM= @@ -53,8 +53,8 @@ github.com/cosmos/cosmos-db v1.0.0-rc.1 h1:SjnT8B6WKMW9WEIX32qMhnEEKcI7ZP0+G1Sa9 github.com/cosmos/cosmos-db v1.0.0-rc.1/go.mod h1:Dnmk3flSf5lkwCqvvjNpoxjpXzhxnCAFzKHlbaForso= github.com/cosmos/cosmos-proto v1.0.0-beta.3 h1:VitvZ1lPORTVxkmF2fAp3IiA61xVwArQYKXTdEcpW6o= github.com/cosmos/cosmos-proto v1.0.0-beta.3/go.mod h1:t8IASdLaAq+bbHbjq4p960BvcTqtwuAxid3b/2rOD6I= -github.com/cosmos/gogoproto v1.4.6 h1:Ee7z15dWJaGlgM2rWrK8N2IX7PQcuccu8oG68jp5RL4= -github.com/cosmos/gogoproto v1.4.6/go.mod h1:VS/ASYmPgv6zkPKLjR9EB91lwbLHOzaGCirmKKhncfI= +github.com/cosmos/gogoproto v1.4.8 h1:BrHKc6WFZt8+jRV71vKSQE+JrfF+JAnzrKo2VP7wIZ4= +github.com/cosmos/gogoproto v1.4.8/go.mod h1:hnb0DIEWTv+wdNzNcqus5xCQXq5+CXauq1FJuurRfVY= github.com/cpuguy83/go-md2man v1.0.10/go.mod h1:SmD6nW6nTyfqj6ABTjUi3V3JVMnlJmwcJI5acqYI6dE= github.com/creack/pty v1.1.9/go.mod h1:oKZEueFk5CKHvIhNR5MUki03XCEU+Q6VDXinZuGJ33E= github.com/cucumber/common/gherkin/go/v22 v22.0.0 h1:4K8NqptbvdOrjL9DEea6HFjSpbdT9+Q5kgLpmmsHYl0= @@ -83,8 +83,8 @@ github.com/fsnotify/fsnotify v1.6.0 h1:n+5WquG0fcWoWp6xPWfHdbskMCQaFnG6PfBrh1Ky4 github.com/fsnotify/fsnotify v1.6.0/go.mod h1:sl3t1tCWJFWoRz9R8WJCbQihKKwmorjAbSClcnxKAGw= github.com/gavv/httpexpect v2.0.0+incompatible/go.mod h1:x+9tiU1YnrOvnB725RkpoLv1M62hOWzwo5OXotisrKc= github.com/getsentry/sentry-go v0.12.0/go.mod h1:NSap0JBYWzHND8oMbyi0+XZhUalc1TBdRL1M71JZW2c= -github.com/getsentry/sentry-go v0.19.0 h1:BcCH3CN5tXt5aML+gwmbFwVptLLQA+eT866fCO9wVOM= -github.com/getsentry/sentry-go v0.19.0/go.mod h1:y3+lGEFEFexZtpbG1GUE2WD/f9zGyKYwpEqryTOC/nE= +github.com/getsentry/sentry-go v0.20.0 h1:bwXW98iMRIWxn+4FgPW7vMrjmbym6HblXALmhjHmQaQ= +github.com/getsentry/sentry-go v0.20.0/go.mod h1:lc76E2QywIyW8WuBnwl8Lc4bkmQH4+w1gwTf25trprY= github.com/gin-contrib/sse v0.0.0-20190301062529-5545eab6dad3/go.mod h1:VJ0WA2NBN22VlZ2dKZQPAPnyWw5XTlK1KymzLKsr59s= github.com/gin-gonic/gin v1.4.0/go.mod h1:OW2EZn3DO8Ln9oIKOvM++LBO+5UPHJJDH72/q/3rZdM= github.com/go-check/check v0.0.0-20180628173108-788fd7840127/go.mod h1:9ES+weclKsC9YodN5RgxqK/VD9HM9JsCSh7rNhMZE98= @@ -170,8 +170,8 @@ github.com/kisielk/errcheck v1.5.0/go.mod h1:pFxgyoBC7bSaBwPgfKdkLd5X25qrDl4LWUI github.com/kisielk/gotool v1.0.0/go.mod h1:XhKaO+MFFWcvkIS/tQcRk01m1F5IRFswLeQ+oQHNcck= github.com/klauspost/compress v1.8.2/go.mod h1:RyIbtBH6LamlWaDj8nUwkbUhJ87Yi3uG0guNDohfE1A= github.com/klauspost/compress v1.9.7/go.mod h1:RyIbtBH6LamlWaDj8nUwkbUhJ87Yi3uG0guNDohfE1A= -github.com/klauspost/compress v1.16.3 h1:XuJt9zzcnaz6a16/OU53ZjWp/v7/42WcR5t2a0PcNQY= -github.com/klauspost/compress v1.16.3/go.mod h1:ntbaceVETuRiXiv4DpjP66DpAtAGkEQskQzEyD//IeE= +github.com/klauspost/compress v1.16.5 h1:IFV2oUNUzZaz+XyusxpLzpzS8Pt5rh0Z16For/djlyI= +github.com/klauspost/compress v1.16.5/go.mod h1:ntbaceVETuRiXiv4DpjP66DpAtAGkEQskQzEyD//IeE= github.com/klauspost/cpuid v1.2.1/go.mod h1:Pj4uuM528wm8OyEC2QMXAi2YiTZ96dNQPGgoMS4s3ek= github.com/kr/pretty v0.1.0/go.mod h1:dAy3ld7l9f0ibDNOQOHHMYYIIbhfbHSm3C4ZsoJORNo= github.com/kr/pretty v0.3.0/go.mod h1:640gp4NfQd8pI5XOwp5fnNeVWj67G7CFk/SaSQn7NBk= @@ -185,8 +185,8 @@ github.com/labstack/echo/v4 v4.5.0/go.mod h1:czIriw4a0C1dFun+ObrXp7ok03xON0N1awS github.com/labstack/gommon v0.3.0/go.mod h1:MULnywXg0yavhxWKc+lOruYdAhDwPK9wf0OL7NoOu+k= github.com/lib/pq v1.10.7 h1:p7ZhMD+KsSRozJr34udlUrhboJwWAgCg34+/ZZNvZZw= github.com/lib/pq v1.10.7/go.mod h1:AlVN5x4E4T544tWzH6hKfbfQvm3HdbOxrmggDNAPY9o= -github.com/linxGnu/grocksdb v1.7.15 h1:AEhP28lkeAybv5UYNYviYISpR6bJejEnKuYbnWAnxx0= -github.com/linxGnu/grocksdb v1.7.15/go.mod h1:pY55D0o+r8yUYLq70QmhdudxYvoDb9F+9puf4m3/W+U= +github.com/linxGnu/grocksdb v1.7.16 h1:Q2co1xrpdkr5Hx3Fp+f+f7fRGhQFQhvi/+226dtLmA8= +github.com/linxGnu/grocksdb v1.7.16/go.mod h1:JkS7pl5qWpGpuVb3bPqTz8nC12X3YtPZT+Xq7+QfQo4= github.com/magiconair/properties v1.8.0/go.mod h1:PppfXfuXeibc/6YijjN8zIbojt8czPbwD3XqdrwzmxQ= github.com/mattn/go-colorable v0.1.2/go.mod h1:U0ppj6V5qS13XJ6of8GYAs25YV2eR4EVcfRqFIhoBtE= github.com/mattn/go-colorable v0.1.8/go.mod h1:u6P/XSegPjTcexA+o6vUJrdnUu04hMope9wVRipJSqc= @@ -238,8 +238,8 @@ github.com/pkg/errors v0.9.1 h1:FEBLx1zS214owpjy7qsBeixbURkuhQAwrK5UwLGTwt4= github.com/pkg/errors v0.9.1/go.mod h1:bwawxfHBFNV+L2hUp1rHADufV3IMtnDRdf1r5NINEl0= github.com/pmezard/go-difflib v1.0.0 h1:4DBwDE0NGyQoBHbLQYPwSUPoCMWR5BEzIk/f1lZbAQM= github.com/pmezard/go-difflib v1.0.0/go.mod h1:iKH77koFhYxTK1pcRnkKkqfTogsbg7gZNVY4sRDYZ/4= -github.com/prometheus/client_golang v1.14.0 h1:nJdhIvne2eSX/XRAFV9PcvFFRbrjbcTUj0VP62TMhnw= -github.com/prometheus/client_golang v1.14.0/go.mod h1:8vpkKitgIVNcqrRBWh1C4TIUQgYNtG/XQE4E/Zae36Y= +github.com/prometheus/client_golang v1.15.0 h1:5fCgGYogn0hFdhyhLbw7hEsWxufKtY9klyvdNfFlFhM= +github.com/prometheus/client_golang v1.15.0/go.mod h1:e9yaBhRPU2pPNsZwE+JdQl0KEt1N9XgF6zxWmaC0xOk= github.com/prometheus/client_model v0.0.0-20190812154241-14fe0d1b01d4/go.mod h1:xMI15A0UPsDsEKsMN9yxemIoYk6Tm2C1GtYGdfGttqA= github.com/prometheus/client_model v0.3.0 h1:UBgGFHqYdG/TPFD1B1ogZywDqEkwp3fBMvqdiQ7Xew4= github.com/prometheus/client_model v0.3.0/go.mod h1:LDGWKZIo7rky3hgvBe+caln+Dr3dPggB5dvjtD7w9+w= @@ -251,8 +251,9 @@ github.com/regen-network/gocuke v0.6.2 h1:pHviZ0kKAq2U2hN2q3smKNxct6hS0mGByFMHGn github.com/regen-network/gocuke v0.6.2/go.mod h1:zYaqIHZobHyd0xOrHGPQjbhGJsuZ1oElx150u2o1xuk= github.com/rogpeppe/go-internal v1.6.1/go.mod h1:xXDCJY+GAPziupqXw64V24skbSoqbTEfhy4qGm1nDQc= github.com/rogpeppe/go-internal v1.8.1/go.mod h1:JeRgkft04UBgHMgCIwADu4Pn6Mtm5d4nPKWu0nJ5d+o= -github.com/rogpeppe/go-internal v1.9.0 h1:73kH8U+JUqXU8lRuOHeVHaa/SZPifC7BkcraZVejAe8= github.com/rogpeppe/go-internal v1.9.0/go.mod h1:WtVeX8xhTBvf0smdhujwtBcq4Qrzq/fJaraNFVN+nFs= +github.com/rogpeppe/go-internal v1.10.0 h1:TMyTOH3F/DB16zRVcYyreMH6GnZZrwQVAoYjRBZyWFQ= +github.com/rogpeppe/go-internal v1.10.0/go.mod h1:UQnix2H7Ngw/k4C5ijL5+65zddjncjaFoBhdsK/akog= github.com/russross/blackfriday v1.5.2/go.mod h1:JO/DiYxRf+HjHt06OyowR9PTA263kcR/rfWxYHBV53g= github.com/ryanuber/columnize v2.1.0+incompatible/go.mod h1:sm1tb6uqfes/u+d4ooFouqFdy9/2g9QGwK3SQygK0Ts= github.com/schollz/closestmatch v2.1.0+incompatible/go.mod h1:RtP1ddjLong6gTkbtmuhtR2uUrrJOpYzYRvbcPAid+g= @@ -313,8 +314,8 @@ golang.org/x/crypto v0.0.0-20200622213623-75b288015ac9/go.mod h1:LzIPMQfyMNhhGPh golang.org/x/crypto v0.0.0-20210322153248-0c34fe9e7dc2/go.mod h1:T9bdIzuCu7OtxOm1hfPfRQxPLYneinmdGuTeoZ9dtd4= golang.org/x/crypto v0.0.0-20210921155107-089bfa567519/go.mod h1:GvvjBRRGRdwPK5ydBHafDWAxML/pGHZbMvKqRZ5+Abc= golang.org/x/exp v0.0.0-20190121172915-509febef88a4/go.mod h1:CJ0aWSM057203Lf6IL+f9T1iT9GByDxfZKAQTCR3kQA= -golang.org/x/exp v0.0.0-20230315142452-642cacee5cc0 h1:pVgRXcIictcr+lBQIFeiwuwtDIs4eL21OuM9nyAADmo= -golang.org/x/exp v0.0.0-20230315142452-642cacee5cc0/go.mod h1:CxIveKay+FTh1D0yPZemJVgC/95VzuuOLq5Qi4xnoYc= +golang.org/x/exp v0.0.0-20230321023759-10a507213a29 h1:ooxPy7fPvB4kwsA2h+iBNHkAbp/4JxTSwCmvdjEYmug= +golang.org/x/exp v0.0.0-20230321023759-10a507213a29/go.mod h1:CxIveKay+FTh1D0yPZemJVgC/95VzuuOLq5Qi4xnoYc= golang.org/x/lint v0.0.0-20181026193005-c67002cb31c3/go.mod h1:UVdnD1Gm6xHRNCYTkRU2/jEulfH38KcIWyp/GAMgvoE= golang.org/x/lint v0.0.0-20190227174305-5b3e6a55c961/go.mod h1:wehouNa3lNwaWXcvxsM5YxQ5yQlVC4a0KAMCusXpPoU= golang.org/x/lint v0.0.0-20190313153728-d0100b6bd8b3/go.mod h1:6SW0HCj/g11FgYtHlgUYUwCkIfeOF89ocIRzGO/8vkc= @@ -344,8 +345,8 @@ golang.org/x/net v0.0.0-20210428140749-89ef3d95e781/go.mod h1:OJAsFXCWl8Ukc7SiCT golang.org/x/net v0.0.0-20211008194852-3b03d305991f/go.mod h1:9nx3DQGgdP8bBQD5qxJ1jj9UTztislL4KSBs9R2vV5Y= golang.org/x/net v0.0.0-20220225172249-27dd8689420f/go.mod h1:CfG3xpIq0wQ8r1q4Su4UZFWDARRcnwPjda9FqA0JpMk= golang.org/x/net v0.0.0-20220607020251-c690dde0001d/go.mod h1:XRhObCWvk6IyKnWLug+ECip1KBveYUHfp+8e9klMJ9c= -golang.org/x/net v0.8.0 h1:Zrh2ngAOFYneWTAIAPethzeaQLuHwhuBkuV6ZiRnUaQ= -golang.org/x/net v0.8.0/go.mod h1:QVkue5JL9kW//ek3r6jTKnTFis1tRmNAW2P1shuFdJc= +golang.org/x/net v0.9.0 h1:aWJ/m6xSmxWBx+V0XRHTlrYrPG56jKsLdTFmsSsCzOM= +golang.org/x/net v0.9.0/go.mod h1:d48xBJpPfHeWQsugry2m+kC02ZBRGRgulfHnEXEuWns= golang.org/x/oauth2 v0.0.0-20180821212333-d2e6202438be/go.mod h1:N/0e6XlmueqKjAGxoOufVs8QHGRruUQn6yWY3a++T0U= golang.org/x/sync v0.0.0-20180314180146-1d60e4601c6f/go.mod h1:RxMgew5VJxzue5/jJTE5uejpjVlOe/izrB70Jof72aM= golang.org/x/sync v0.0.0-20181108010431-42b317875d0f/go.mod h1:RxMgew5VJxzue5/jJTE5uejpjVlOe/izrB70Jof72aM= @@ -388,8 +389,8 @@ golang.org/x/sys v0.0.0-20220209214540-3681064d5158/go.mod h1:oPkhp1MJrh7nUepCBc golang.org/x/sys v0.0.0-20220412211240-33da011f77ad/go.mod h1:oPkhp1MJrh7nUepCBck5+mAzfO9JrbApNNgaTdGDITg= golang.org/x/sys v0.0.0-20220520151302-bc2c85ada10a/go.mod h1:oPkhp1MJrh7nUepCBck5+mAzfO9JrbApNNgaTdGDITg= golang.org/x/sys v0.0.0-20220908164124-27713097b956/go.mod h1:oPkhp1MJrh7nUepCBck5+mAzfO9JrbApNNgaTdGDITg= -golang.org/x/sys v0.6.0 h1:MVltZSvRTcU2ljQOhs94SXPftV6DCNnZViHeQps87pQ= -golang.org/x/sys v0.6.0/go.mod h1:oPkhp1MJrh7nUepCBck5+mAzfO9JrbApNNgaTdGDITg= +golang.org/x/sys v0.7.0 h1:3jlCCIQZPdOYu1h8BkNvLz8Kgwtae2cagcG/VamtZRU= +golang.org/x/sys v0.7.0/go.mod h1:oPkhp1MJrh7nUepCBck5+mAzfO9JrbApNNgaTdGDITg= golang.org/x/term v0.0.0-20201126162022-7de9c90e9dd1/go.mod h1:bj7SfCRtBDWHUb9snDiAeCFNEtKQo2Wmx5Cou7ajbmo= golang.org/x/term v0.0.0-20210927222741-03fcf44c2211/go.mod h1:jbD1KX2456YbFQfuXm/mYQcufACuNUgVhRMnK/tPxf8= golang.org/x/text v0.3.0/go.mod h1:NqM8EUOU14njkJ3fqMW+pc6Ldnwhi/IjpwHt7yyuwOQ= @@ -398,8 +399,8 @@ golang.org/x/text v0.3.3/go.mod h1:5Zoc/QRtKVWzQhOtBMvqHzDpF6irO9z98xDceosuGiQ= golang.org/x/text v0.3.5/go.mod h1:5Zoc/QRtKVWzQhOtBMvqHzDpF6irO9z98xDceosuGiQ= golang.org/x/text v0.3.6/go.mod h1:5Zoc/QRtKVWzQhOtBMvqHzDpF6irO9z98xDceosuGiQ= golang.org/x/text v0.3.7/go.mod h1:u+2+/6zg+i71rQMx5EYifcz6MCKuco9NR6JIITiCfzQ= -golang.org/x/text v0.8.0 h1:57P1ETyNKtuIjB4SRd15iJxuhj8Gc416Y78H3qgMh68= -golang.org/x/text v0.8.0/go.mod h1:e1OnstbJyHTd6l/uOt8jFFHp6TRDWZR/bV3emEE/zU8= +golang.org/x/text v0.9.0 h1:2sjJmO8cDvYveuX97RDLsxlyUxLl+GHoLxBiRdHllBE= +golang.org/x/text v0.9.0/go.mod h1:e1OnstbJyHTd6l/uOt8jFFHp6TRDWZR/bV3emEE/zU8= golang.org/x/time v0.0.0-20201208040808-7e3f01d25324/go.mod h1:tRJNPiyCQ0inRvYxbN9jk5I+vvW/OXSQhTDSoE431IQ= golang.org/x/tools v0.0.0-20180917221912-90fa682c2a6e/go.mod h1:n7NCudcB/nEzxVGmLbDWY5pfWTLqBcC2KZ6jyYvM4mQ= golang.org/x/tools v0.0.0-20181221001348-537d06c36207/go.mod h1:n7NCudcB/nEzxVGmLbDWY5pfWTLqBcC2KZ6jyYvM4mQ= @@ -429,8 +430,8 @@ google.golang.org/genproto v0.0.0-20180817151627-c66870c02cf8/go.mod h1:JiN7NxoA google.golang.org/genproto v0.0.0-20190819201941-24fa4b261c55/go.mod h1:DMBHOl98Agz4BDEuKkezgsaosCRResVns1a3J2ZsMNc= google.golang.org/genproto v0.0.0-20200526211855-cb27e3aa2013/go.mod h1:NbSheEEYHJ7i3ixzK3sjbqSGDJWnxyFXZblF3eUsNvo= google.golang.org/genproto v0.0.0-20210624195500-8bfb893ecb84/go.mod h1:SzzZ/N+nwJDaO1kznhnlzqS8ocJICar6hYhVyhi++24= -google.golang.org/genproto v0.0.0-20230320184635-7606e756e683 h1:khxVcsk/FhnzxMKOyD+TDGwjbEOpcPuIpmafPGFmhMA= -google.golang.org/genproto v0.0.0-20230320184635-7606e756e683/go.mod h1:NWraEVixdDnqcqQ30jipen1STv2r/n24Wb7twVTGR4s= +google.golang.org/genproto v0.0.0-20230410155749-daa745c078e1 h1:KpwkzHKEF7B9Zxg18WzOa7djJ+Ha5DzthMyZYQfEn2A= +google.golang.org/genproto v0.0.0-20230410155749-daa745c078e1/go.mod h1:nKE/iIaLqn2bQwXBg8f1g2Ylh6r5MN5CmZvuzZCgsCU= google.golang.org/grpc v1.12.0/go.mod h1:yo6s7OP7yaDglbqo1J04qKzAhqBH6lvTonzMVmEdcZw= google.golang.org/grpc v1.19.0/go.mod h1:mqu4LbDTu4XGKhr4mRzUsmM4RtVoemTSY81AxZiDr8c= google.golang.org/grpc v1.23.0/go.mod h1:Y5yQAOtifL1yxbo5wqy6BxZv8vAUGQwXBOALyacEbxg= diff --git a/orm/internal/buf.gen.yaml b/orm/internal/buf.gen.yaml index 468e3cf63686..7baeb94c19a7 100644 --- a/orm/internal/buf.gen.yaml +++ b/orm/internal/buf.gen.yaml @@ -2,7 +2,7 @@ version: v1 managed: enabled: true go_package_prefix: - default: github.com/cosmos/cosmos-sdk/orm/internal + default: cosmossdk.io/orm/internal override: buf.build/cosmos/cosmos-sdk: cosmossdk.io/api plugins: diff --git a/orm/internal/buf.proto.gen.yaml b/orm/internal/buf.proto.gen.yaml index 470406018cd5..8f6ad94efa82 100644 --- a/orm/internal/buf.proto.gen.yaml +++ b/orm/internal/buf.proto.gen.yaml @@ -2,7 +2,7 @@ version: v1 managed: enabled: true go_package_prefix: - default: github.com/cosmos/cosmos-sdk/orm/internal + default: cosmossdk.io/orm/internal override: buf.build/cosmos/cosmos-sdk: cosmossdk.io/api plugins: diff --git a/orm/internal/codegen/codegen.go b/orm/internal/codegen/codegen.go index b895d9909cfc..aa2513504ed5 100644 --- a/orm/internal/codegen/codegen.go +++ b/orm/internal/codegen/codegen.go @@ -14,9 +14,9 @@ import ( const ( contextPkg = protogen.GoImportPath("context") - ormListPkg = protogen.GoImportPath("github.com/cosmos/cosmos-sdk/orm/model/ormlist") - ormErrPkg = protogen.GoImportPath("github.com/cosmos/cosmos-sdk/orm/types/ormerrors") - ormTablePkg = protogen.GoImportPath("github.com/cosmos/cosmos-sdk/orm/model/ormtable") + ormListPkg = protogen.GoImportPath("cosmossdk.io/orm/model/ormlist") + ormErrPkg = protogen.GoImportPath("cosmossdk.io/orm/types/ormerrors") + ormTablePkg = protogen.GoImportPath("cosmossdk.io/orm/model/ormtable") ) func ORMPluginRunner(p *protogen.Plugin) error { diff --git a/orm/internal/codegen/file.go b/orm/internal/codegen/file.go index 681e49cf89e2..bd494174f797 100644 --- a/orm/internal/codegen/file.go +++ b/orm/internal/codegen/file.go @@ -1,3 +1,4 @@ +// nolint:unused // ignore unused code linting package codegen import ( diff --git a/orm/internal/codegen/index.go b/orm/internal/codegen/index.go index 9b889d431e46..2a02d296148c 100644 --- a/orm/internal/codegen/index.go +++ b/orm/internal/codegen/index.go @@ -1,3 +1,4 @@ +// nolint:unused // ignore unused code linting package codegen import ( diff --git a/orm/internal/codegen/query.go b/orm/internal/codegen/query.go index 7797ef8d1e52..52551dccaee8 100644 --- a/orm/internal/codegen/query.go +++ b/orm/internal/codegen/query.go @@ -5,7 +5,6 @@ import ( "fmt" "os" - ormv1 "cosmossdk.io/api/cosmos/orm/v1" "github.com/iancoleman/strcase" "golang.org/x/exp/maps" "golang.org/x/exp/slices" @@ -13,7 +12,9 @@ import ( "google.golang.org/protobuf/proto" "google.golang.org/protobuf/reflect/protoreflect" - "github.com/cosmos/cosmos-sdk/orm/internal/fieldnames" + ormv1 "cosmossdk.io/api/cosmos/orm/v1" + + "cosmossdk.io/orm/internal/fieldnames" ) type queryProtoGen struct { @@ -231,7 +232,7 @@ func (g queryProtoGen) genTableRPCMethods(msg *protogen.Message, desc *ormv1.Tab func (g queryProtoGen) genSingletonRPCMethods(msg *protogen.Message) error { name := msg.Desc.Name() g.svc.F("// Get%s queries the %s singleton.", name, name) - g.svc.F("rpc Get%s (Get%sRequest) returns (Get%sResponse) {}", name, name, name) // TODO grpc gateway + g.svc.F("rpc Get%s(Get%sRequest) returns (Get%sResponse) {}", name, name, name) // TODO grpc gateway g.startRequestType("Get%sRequest", name) g.msgs.F("}") g.msgs.F("") @@ -252,7 +253,7 @@ func (g queryProtoGen) startResponseType(format string, args ...any) { g.startRequestResponseType("response", format, args...) } -func (g queryProtoGen) startRequestResponseType(typ string, format string, args ...any) { +func (g queryProtoGen) startRequestResponseType(typ, format string, args ...any) { msgTypeName := fmt.Sprintf(format, args...) g.msgs.F("// %s is the %s/%s %s type.", msgTypeName, g.queryServiceName(), msgTypeName, typ) g.msgs.F("message %s {", msgTypeName) @@ -302,7 +303,7 @@ func (w *writer) F(format string, args ...interface{}) { } func (w *writer) Indent() { - w.indent += 1 + w.indent++ w.updateIndent() } @@ -314,6 +315,6 @@ func (w *writer) updateIndent() { } func (w *writer) Dedent() { - w.indent -= 1 + w.indent-- w.updateIndent() } diff --git a/orm/internal/codegen/singleton.go b/orm/internal/codegen/singleton.go index 40a265235c04..851e70b73437 100644 --- a/orm/internal/codegen/singleton.go +++ b/orm/internal/codegen/singleton.go @@ -8,7 +8,7 @@ import ( ormv1 "cosmossdk.io/api/cosmos/orm/v1" - "github.com/cosmos/cosmos-sdk/orm/model/ormtable" + "cosmossdk.io/orm/model/ormtable" ) type singletonGen struct { diff --git a/orm/internal/codegen/table.go b/orm/internal/codegen/table.go index d629b0c29802..1b26e9103d2c 100644 --- a/orm/internal/codegen/table.go +++ b/orm/internal/codegen/table.go @@ -1,3 +1,4 @@ +//nolint:unused // ignore unused code linting package codegen import ( @@ -10,8 +11,8 @@ import ( ormv1 "cosmossdk.io/api/cosmos/orm/v1" - "github.com/cosmos/cosmos-sdk/orm/internal/fieldnames" - "github.com/cosmos/cosmos-sdk/orm/model/ormtable" + "cosmossdk.io/orm/internal/fieldnames" + "cosmossdk.io/orm/model/ormtable" ) type tableGen struct { diff --git a/orm/internal/stablejson/encode_test.go b/orm/internal/stablejson/encode_test.go index 85d8acd57920..c75b48f15479 100644 --- a/orm/internal/stablejson/encode_test.go +++ b/orm/internal/stablejson/encode_test.go @@ -4,14 +4,14 @@ import ( "testing" "github.com/stretchr/testify/require" - "google.golang.org/protobuf/types/known/anypb" bankv1beta1 "cosmossdk.io/api/cosmos/bank/v1beta1" basev1beta1 "cosmossdk.io/api/cosmos/base/v1beta1" txv1beta1 "cosmossdk.io/api/cosmos/tx/v1beta1" "github.com/cosmos/cosmos-proto/anyutil" - "github.com/cosmos/cosmos-sdk/orm/internal/stablejson" + + "cosmossdk.io/orm/internal/stablejson" ) func TestStableJSON(t *testing.T) { diff --git a/orm/internal/testkv/compare.go b/orm/internal/testkv/compare.go index 8b3878f4738f..35b50cbe5d16 100644 --- a/orm/internal/testkv/compare.go +++ b/orm/internal/testkv/compare.go @@ -5,8 +5,8 @@ import ( "gotest.tools/v3/assert" - "github.com/cosmos/cosmos-sdk/orm/model/ormtable" - "github.com/cosmos/cosmos-sdk/orm/types/kv" + "cosmossdk.io/orm/model/ormtable" + "cosmossdk.io/orm/types/kv" ) func AssertBackendsEqual(t assert.TestingT, b1, b2 ormtable.Backend) { diff --git a/orm/internal/testkv/debug.go b/orm/internal/testkv/debug.go index 5e2382246d46..5278409550d7 100644 --- a/orm/internal/testkv/debug.go +++ b/orm/internal/testkv/debug.go @@ -6,10 +6,10 @@ import ( "google.golang.org/protobuf/proto" - "github.com/cosmos/cosmos-sdk/orm/encoding/ormkv" - "github.com/cosmos/cosmos-sdk/orm/internal/stablejson" - "github.com/cosmos/cosmos-sdk/orm/model/ormtable" - "github.com/cosmos/cosmos-sdk/orm/types/kv" + "cosmossdk.io/orm/encoding/ormkv" + "cosmossdk.io/orm/internal/stablejson" + "cosmossdk.io/orm/model/ormtable" + "cosmossdk.io/orm/types/kv" ) // Debugger is an interface that handles debug info from the debug store wrapper. @@ -145,7 +145,7 @@ type debugIterator struct { debugger Debugger } -func (d debugIterator) Domain() (start []byte, end []byte) { +func (d debugIterator) Domain() (start, end []byte) { start, end = d.iterator.Domain() d.debugger.Log(fmt.Sprintf(" DOMAIN %x -> %x", start, end)) return start, end @@ -235,12 +235,12 @@ func (d debugHooks) ValidateInsert(context context.Context, message proto.Messag } func (d debugHooks) ValidateUpdate(ctx context.Context, existing, new proto.Message) error { - existingJson, err := stablejson.Marshal(existing) + existingJSON, err := stablejson.Marshal(existing) if err != nil { return err } - newJson, err := stablejson.Marshal(new) + newJSON, err := stablejson.Marshal(new) if err != nil { return err } @@ -248,8 +248,8 @@ func (d debugHooks) ValidateUpdate(ctx context.Context, existing, new proto.Mess d.debugger.Log(fmt.Sprintf( "ORM BEFORE UPDATE %s %s -> %s", existing.ProtoReflect().Descriptor().FullName(), - existingJson, - newJson, + existingJSON, + newJSON, )) if d.validateHooks != nil { return d.validateHooks.ValidateUpdate(ctx, existing, new) @@ -291,12 +291,12 @@ func (d debugHooks) OnInsert(ctx context.Context, message proto.Message) { } func (d debugHooks) OnUpdate(ctx context.Context, existing, new proto.Message) { - existingJson, err := stablejson.Marshal(existing) + existingJSON, err := stablejson.Marshal(existing) if err != nil { panic(err) } - newJson, err := stablejson.Marshal(new) + newJSON, err := stablejson.Marshal(new) if err != nil { panic(err) } @@ -304,8 +304,8 @@ func (d debugHooks) OnUpdate(ctx context.Context, existing, new proto.Message) { d.debugger.Log(fmt.Sprintf( "ORM AFTER UPDATE %s %s -> %s", existing.ProtoReflect().Descriptor().FullName(), - existingJson, - newJson, + existingJSON, + newJSON, )) if d.writeHooks != nil { d.writeHooks.OnUpdate(ctx, existing, new) diff --git a/orm/internal/testkv/leveldb.go b/orm/internal/testkv/leveldb.go index 4e03f3642138..c75d643bd274 100644 --- a/orm/internal/testkv/leveldb.go +++ b/orm/internal/testkv/leveldb.go @@ -6,7 +6,7 @@ import ( dbm "github.com/cosmos/cosmos-db" "gotest.tools/v3/assert" - "github.com/cosmos/cosmos-sdk/orm/model/ormtable" + "cosmossdk.io/orm/model/ormtable" ) func NewGoLevelDBBackend(t testing.TB) ormtable.Backend { diff --git a/orm/internal/testkv/mem.go b/orm/internal/testkv/mem.go index d2c89a2e8db4..e1a10a7664a1 100644 --- a/orm/internal/testkv/mem.go +++ b/orm/internal/testkv/mem.go @@ -3,7 +3,7 @@ package testkv import ( dbm "github.com/cosmos/cosmos-db" - "github.com/cosmos/cosmos-sdk/orm/model/ormtable" + "cosmossdk.io/orm/model/ormtable" ) // NewSplitMemBackend returns a Backend instance diff --git a/orm/internal/testpb/bank.cosmos_orm.go b/orm/internal/testpb/bank.cosmos_orm.go index 0635179c20e8..f7fa09cdc16b 100644 --- a/orm/internal/testpb/bank.cosmos_orm.go +++ b/orm/internal/testpb/bank.cosmos_orm.go @@ -4,9 +4,9 @@ package testpb import ( context "context" - ormlist "github.com/cosmos/cosmos-sdk/orm/model/ormlist" - ormtable "github.com/cosmos/cosmos-sdk/orm/model/ormtable" - ormerrors "github.com/cosmos/cosmos-sdk/orm/types/ormerrors" + ormlist "cosmossdk.io/orm/model/ormlist" + ormtable "cosmossdk.io/orm/model/ormtable" + ormerrors "cosmossdk.io/orm/types/ormerrors" ) type BalanceTable interface { diff --git a/orm/internal/testpb/bank.pb.go b/orm/internal/testpb/bank.pb.go index 8366c79dc574..e3320c6e8a80 100644 --- a/orm/internal/testpb/bank.pb.go +++ b/orm/internal/testpb/bank.pb.go @@ -207,16 +207,15 @@ var file_testpb_bank_proto_rawDesc = []byte{ 0x05, 0x64, 0x65, 0x6e, 0x6f, 0x6d, 0x18, 0x01, 0x20, 0x01, 0x28, 0x09, 0x52, 0x05, 0x64, 0x65, 0x6e, 0x6f, 0x6d, 0x12, 0x16, 0x0a, 0x06, 0x61, 0x6d, 0x6f, 0x75, 0x6e, 0x74, 0x18, 0x02, 0x20, 0x01, 0x28, 0x04, 0x52, 0x06, 0x61, 0x6d, 0x6f, 0x75, 0x6e, 0x74, 0x3a, 0x11, 0xf2, 0x9e, 0xd3, - 0x8e, 0x03, 0x0b, 0x0a, 0x07, 0x0a, 0x05, 0x64, 0x65, 0x6e, 0x6f, 0x6d, 0x18, 0x02, 0x42, 0x81, - 0x01, 0x0a, 0x0a, 0x63, 0x6f, 0x6d, 0x2e, 0x74, 0x65, 0x73, 0x74, 0x70, 0x62, 0x42, 0x09, 0x42, - 0x61, 0x6e, 0x6b, 0x50, 0x72, 0x6f, 0x74, 0x6f, 0x50, 0x01, 0x5a, 0x30, 0x67, 0x69, 0x74, 0x68, - 0x75, 0x62, 0x2e, 0x63, 0x6f, 0x6d, 0x2f, 0x63, 0x6f, 0x73, 0x6d, 0x6f, 0x73, 0x2f, 0x63, 0x6f, - 0x73, 0x6d, 0x6f, 0x73, 0x2d, 0x73, 0x64, 0x6b, 0x2f, 0x6f, 0x72, 0x6d, 0x2f, 0x69, 0x6e, 0x74, - 0x65, 0x72, 0x6e, 0x61, 0x6c, 0x2f, 0x74, 0x65, 0x73, 0x74, 0x70, 0x62, 0xa2, 0x02, 0x03, 0x54, - 0x58, 0x58, 0xaa, 0x02, 0x06, 0x54, 0x65, 0x73, 0x74, 0x70, 0x62, 0xca, 0x02, 0x06, 0x54, 0x65, - 0x73, 0x74, 0x70, 0x62, 0xe2, 0x02, 0x12, 0x54, 0x65, 0x73, 0x74, 0x70, 0x62, 0x5c, 0x47, 0x50, - 0x42, 0x4d, 0x65, 0x74, 0x61, 0x64, 0x61, 0x74, 0x61, 0xea, 0x02, 0x06, 0x54, 0x65, 0x73, 0x74, - 0x70, 0x62, 0x62, 0x06, 0x70, 0x72, 0x6f, 0x74, 0x6f, 0x33, + 0x8e, 0x03, 0x0b, 0x0a, 0x07, 0x0a, 0x05, 0x64, 0x65, 0x6e, 0x6f, 0x6d, 0x18, 0x02, 0x42, 0x71, + 0x0a, 0x0a, 0x63, 0x6f, 0x6d, 0x2e, 0x74, 0x65, 0x73, 0x74, 0x70, 0x62, 0x42, 0x09, 0x42, 0x61, + 0x6e, 0x6b, 0x50, 0x72, 0x6f, 0x74, 0x6f, 0x50, 0x01, 0x5a, 0x20, 0x63, 0x6f, 0x73, 0x6d, 0x6f, + 0x73, 0x73, 0x64, 0x6b, 0x2e, 0x69, 0x6f, 0x2f, 0x6f, 0x72, 0x6d, 0x2f, 0x69, 0x6e, 0x74, 0x65, + 0x72, 0x6e, 0x61, 0x6c, 0x2f, 0x74, 0x65, 0x73, 0x74, 0x70, 0x62, 0xa2, 0x02, 0x03, 0x54, 0x58, + 0x58, 0xaa, 0x02, 0x06, 0x54, 0x65, 0x73, 0x74, 0x70, 0x62, 0xca, 0x02, 0x06, 0x54, 0x65, 0x73, + 0x74, 0x70, 0x62, 0xe2, 0x02, 0x12, 0x54, 0x65, 0x73, 0x74, 0x70, 0x62, 0x5c, 0x47, 0x50, 0x42, + 0x4d, 0x65, 0x74, 0x61, 0x64, 0x61, 0x74, 0x61, 0xea, 0x02, 0x06, 0x54, 0x65, 0x73, 0x74, 0x70, + 0x62, 0x62, 0x06, 0x70, 0x72, 0x6f, 0x74, 0x6f, 0x33, } var ( diff --git a/orm/internal/testpb/bank_query.pb.go b/orm/internal/testpb/bank_query.pb.go index 487235337cf9..fc75fcfff5e8 100644 --- a/orm/internal/testpb/bank_query.pb.go +++ b/orm/internal/testpb/bank_query.pb.go @@ -1104,16 +1104,15 @@ var file_testpb_bank_query_proto_rawDesc = []byte{ 0x2e, 0x74, 0x65, 0x73, 0x74, 0x70, 0x62, 0x2e, 0x4c, 0x69, 0x73, 0x74, 0x53, 0x75, 0x70, 0x70, 0x6c, 0x79, 0x52, 0x65, 0x71, 0x75, 0x65, 0x73, 0x74, 0x1a, 0x1a, 0x2e, 0x74, 0x65, 0x73, 0x74, 0x70, 0x62, 0x2e, 0x4c, 0x69, 0x73, 0x74, 0x53, 0x75, 0x70, 0x70, 0x6c, 0x79, 0x52, 0x65, 0x73, - 0x70, 0x6f, 0x6e, 0x73, 0x65, 0x22, 0x00, 0x42, 0x86, 0x01, 0x0a, 0x0a, 0x63, 0x6f, 0x6d, 0x2e, - 0x74, 0x65, 0x73, 0x74, 0x70, 0x62, 0x42, 0x0e, 0x42, 0x61, 0x6e, 0x6b, 0x51, 0x75, 0x65, 0x72, - 0x79, 0x50, 0x72, 0x6f, 0x74, 0x6f, 0x50, 0x01, 0x5a, 0x30, 0x67, 0x69, 0x74, 0x68, 0x75, 0x62, - 0x2e, 0x63, 0x6f, 0x6d, 0x2f, 0x63, 0x6f, 0x73, 0x6d, 0x6f, 0x73, 0x2f, 0x63, 0x6f, 0x73, 0x6d, - 0x6f, 0x73, 0x2d, 0x73, 0x64, 0x6b, 0x2f, 0x6f, 0x72, 0x6d, 0x2f, 0x69, 0x6e, 0x74, 0x65, 0x72, - 0x6e, 0x61, 0x6c, 0x2f, 0x74, 0x65, 0x73, 0x74, 0x70, 0x62, 0xa2, 0x02, 0x03, 0x54, 0x58, 0x58, - 0xaa, 0x02, 0x06, 0x54, 0x65, 0x73, 0x74, 0x70, 0x62, 0xca, 0x02, 0x06, 0x54, 0x65, 0x73, 0x74, - 0x70, 0x62, 0xe2, 0x02, 0x12, 0x54, 0x65, 0x73, 0x74, 0x70, 0x62, 0x5c, 0x47, 0x50, 0x42, 0x4d, - 0x65, 0x74, 0x61, 0x64, 0x61, 0x74, 0x61, 0xea, 0x02, 0x06, 0x54, 0x65, 0x73, 0x74, 0x70, 0x62, - 0x62, 0x06, 0x70, 0x72, 0x6f, 0x74, 0x6f, 0x33, + 0x70, 0x6f, 0x6e, 0x73, 0x65, 0x22, 0x00, 0x42, 0x76, 0x0a, 0x0a, 0x63, 0x6f, 0x6d, 0x2e, 0x74, + 0x65, 0x73, 0x74, 0x70, 0x62, 0x42, 0x0e, 0x42, 0x61, 0x6e, 0x6b, 0x51, 0x75, 0x65, 0x72, 0x79, + 0x50, 0x72, 0x6f, 0x74, 0x6f, 0x50, 0x01, 0x5a, 0x20, 0x63, 0x6f, 0x73, 0x6d, 0x6f, 0x73, 0x73, + 0x64, 0x6b, 0x2e, 0x69, 0x6f, 0x2f, 0x6f, 0x72, 0x6d, 0x2f, 0x69, 0x6e, 0x74, 0x65, 0x72, 0x6e, + 0x61, 0x6c, 0x2f, 0x74, 0x65, 0x73, 0x74, 0x70, 0x62, 0xa2, 0x02, 0x03, 0x54, 0x58, 0x58, 0xaa, + 0x02, 0x06, 0x54, 0x65, 0x73, 0x74, 0x70, 0x62, 0xca, 0x02, 0x06, 0x54, 0x65, 0x73, 0x74, 0x70, + 0x62, 0xe2, 0x02, 0x12, 0x54, 0x65, 0x73, 0x74, 0x70, 0x62, 0x5c, 0x47, 0x50, 0x42, 0x4d, 0x65, + 0x74, 0x61, 0x64, 0x61, 0x74, 0x61, 0xea, 0x02, 0x06, 0x54, 0x65, 0x73, 0x74, 0x70, 0x62, 0x62, + 0x06, 0x70, 0x72, 0x6f, 0x74, 0x6f, 0x33, } var ( diff --git a/orm/internal/testpb/bank_query.proto b/orm/internal/testpb/bank_query.proto index 6335d52eaf58..a204777bd4ba 100644 --- a/orm/internal/testpb/bank_query.proto +++ b/orm/internal/testpb/bank_query.proto @@ -42,7 +42,7 @@ message ListBalanceRequest { // denom specifies the value of the Denom index key to use in the query. Denom denom = 2; } - + message AddressDenom { // address is the value of the address field in the index. // It can be omitted to query for all valid values of that field in this segment of the index. @@ -51,14 +51,14 @@ message ListBalanceRequest { // It can be omitted to query for all valid values of that field in this segment of the index. optional string denom = 2; } - + message Denom { // denom is the value of the denom field in the index. // It can be omitted to query for all valid values of that field in this segment of the index. optional string denom = 1; } } - + // query specifies the type of query - either a prefix or range query. oneof query { // prefix_query specifies the index key value to use for the prefix query. @@ -68,7 +68,7 @@ message ListBalanceRequest { } // pagination specifies optional pagination parameters. cosmos.base.query.v1beta1.PageRequest pagination = 3; - + // RangeQuery specifies the from/to index keys for a range query. message RangeQuery { // from is the index key to use for the start of the range query. @@ -110,14 +110,14 @@ message ListSupplyRequest { // denom specifies the value of the Denom index key to use in the query. Denom denom = 1; } - + message Denom { // denom is the value of the denom field in the index. // It can be omitted to query for all valid values of that field in this segment of the index. optional string denom = 1; } } - + // query specifies the type of query - either a prefix or range query. oneof query { // prefix_query specifies the index key value to use for the prefix query. @@ -127,7 +127,7 @@ message ListSupplyRequest { } // pagination specifies optional pagination parameters. cosmos.base.query.v1beta1.PageRequest pagination = 3; - + // RangeQuery specifies the from/to index keys for a range query. message RangeQuery { // from is the index key to use for the start of the range query. @@ -147,3 +147,4 @@ message ListSupplyResponse { // pagination is the pagination response. cosmos.base.query.v1beta1.PageResponse pagination = 2; } + diff --git a/orm/internal/testpb/bank_query_grpc.pb.go b/orm/internal/testpb/bank_query_grpc.pb.go index c0ca78701544..dc8eac20dbd6 100644 --- a/orm/internal/testpb/bank_query_grpc.pb.go +++ b/orm/internal/testpb/bank_query_grpc.pb.go @@ -1,6 +1,8 @@ +// Code generated by protoc-gen-go-cosmos-orm-proto. DO NOT EDIT. + // Code generated by protoc-gen-go-grpc. DO NOT EDIT. // versions: -// - protoc-gen-go-grpc v1.2.0 +// - protoc-gen-go-grpc v1.3.0 // - protoc (unknown) // source: testpb/bank_query.proto @@ -18,6 +20,13 @@ import ( // Requires gRPC-Go v1.32.0 or later. const _ = grpc.SupportPackageIsVersion7 +const ( + BankQueryService_GetBalance_FullMethodName = "/testpb.BankQueryService/GetBalance" + BankQueryService_ListBalance_FullMethodName = "/testpb.BankQueryService/ListBalance" + BankQueryService_GetSupply_FullMethodName = "/testpb.BankQueryService/GetSupply" + BankQueryService_ListSupply_FullMethodName = "/testpb.BankQueryService/ListSupply" +) + // BankQueryServiceClient is the client API for BankQueryService service. // // For semantics around ctx use and closing/ending streaming RPCs, please refer to https://pkg.go.dev/google.golang.org/grpc/?tab=doc#ClientConn.NewStream. @@ -42,7 +51,7 @@ func NewBankQueryServiceClient(cc grpc.ClientConnInterface) BankQueryServiceClie func (c *bankQueryServiceClient) GetBalance(ctx context.Context, in *GetBalanceRequest, opts ...grpc.CallOption) (*GetBalanceResponse, error) { out := new(GetBalanceResponse) - err := c.cc.Invoke(ctx, "/testpb.BankQueryService/GetBalance", in, out, opts...) + err := c.cc.Invoke(ctx, BankQueryService_GetBalance_FullMethodName, in, out, opts...) if err != nil { return nil, err } @@ -51,7 +60,7 @@ func (c *bankQueryServiceClient) GetBalance(ctx context.Context, in *GetBalanceR func (c *bankQueryServiceClient) ListBalance(ctx context.Context, in *ListBalanceRequest, opts ...grpc.CallOption) (*ListBalanceResponse, error) { out := new(ListBalanceResponse) - err := c.cc.Invoke(ctx, "/testpb.BankQueryService/ListBalance", in, out, opts...) + err := c.cc.Invoke(ctx, BankQueryService_ListBalance_FullMethodName, in, out, opts...) if err != nil { return nil, err } @@ -60,7 +69,7 @@ func (c *bankQueryServiceClient) ListBalance(ctx context.Context, in *ListBalanc func (c *bankQueryServiceClient) GetSupply(ctx context.Context, in *GetSupplyRequest, opts ...grpc.CallOption) (*GetSupplyResponse, error) { out := new(GetSupplyResponse) - err := c.cc.Invoke(ctx, "/testpb.BankQueryService/GetSupply", in, out, opts...) + err := c.cc.Invoke(ctx, BankQueryService_GetSupply_FullMethodName, in, out, opts...) if err != nil { return nil, err } @@ -69,7 +78,7 @@ func (c *bankQueryServiceClient) GetSupply(ctx context.Context, in *GetSupplyReq func (c *bankQueryServiceClient) ListSupply(ctx context.Context, in *ListSupplyRequest, opts ...grpc.CallOption) (*ListSupplyResponse, error) { out := new(ListSupplyResponse) - err := c.cc.Invoke(ctx, "/testpb.BankQueryService/ListSupply", in, out, opts...) + err := c.cc.Invoke(ctx, BankQueryService_ListSupply_FullMethodName, in, out, opts...) if err != nil { return nil, err } @@ -130,7 +139,7 @@ func _BankQueryService_GetBalance_Handler(srv interface{}, ctx context.Context, } info := &grpc.UnaryServerInfo{ Server: srv, - FullMethod: "/testpb.BankQueryService/GetBalance", + FullMethod: BankQueryService_GetBalance_FullMethodName, } handler := func(ctx context.Context, req interface{}) (interface{}, error) { return srv.(BankQueryServiceServer).GetBalance(ctx, req.(*GetBalanceRequest)) @@ -148,7 +157,7 @@ func _BankQueryService_ListBalance_Handler(srv interface{}, ctx context.Context, } info := &grpc.UnaryServerInfo{ Server: srv, - FullMethod: "/testpb.BankQueryService/ListBalance", + FullMethod: BankQueryService_ListBalance_FullMethodName, } handler := func(ctx context.Context, req interface{}) (interface{}, error) { return srv.(BankQueryServiceServer).ListBalance(ctx, req.(*ListBalanceRequest)) @@ -166,7 +175,7 @@ func _BankQueryService_GetSupply_Handler(srv interface{}, ctx context.Context, d } info := &grpc.UnaryServerInfo{ Server: srv, - FullMethod: "/testpb.BankQueryService/GetSupply", + FullMethod: BankQueryService_GetSupply_FullMethodName, } handler := func(ctx context.Context, req interface{}) (interface{}, error) { return srv.(BankQueryServiceServer).GetSupply(ctx, req.(*GetSupplyRequest)) @@ -184,7 +193,7 @@ func _BankQueryService_ListSupply_Handler(srv interface{}, ctx context.Context, } info := &grpc.UnaryServerInfo{ Server: srv, - FullMethod: "/testpb.BankQueryService/ListSupply", + FullMethod: BankQueryService_ListSupply_FullMethodName, } handler := func(ctx context.Context, req interface{}) (interface{}, error) { return srv.(BankQueryServiceServer).ListSupply(ctx, req.(*ListSupplyRequest)) diff --git a/orm/internal/testpb/test_schema.cosmos_orm.go b/orm/internal/testpb/test_schema.cosmos_orm.go index 93ce0cda021f..177886eee338 100644 --- a/orm/internal/testpb/test_schema.cosmos_orm.go +++ b/orm/internal/testpb/test_schema.cosmos_orm.go @@ -4,9 +4,10 @@ package testpb import ( context "context" - ormlist "github.com/cosmos/cosmos-sdk/orm/model/ormlist" - ormtable "github.com/cosmos/cosmos-sdk/orm/model/ormtable" - ormerrors "github.com/cosmos/cosmos-sdk/orm/types/ormerrors" + ormlist "cosmossdk.io/orm/model/ormlist" + ormtable "cosmossdk.io/orm/model/ormtable" + ormerrors "cosmossdk.io/orm/types/ormerrors" + durationpb "google.golang.org/protobuf/types/known/durationpb" timestamppb "google.golang.org/protobuf/types/known/timestamppb" ) @@ -540,6 +541,143 @@ func NewExampleTimestampTable(db ormtable.Schema) (ExampleTimestampTable, error) return exampleTimestampTable{table.(ormtable.AutoIncrementTable)}, nil } +type ExampleDurationTable interface { + Insert(ctx context.Context, exampleDuration *ExampleDuration) error + InsertReturningId(ctx context.Context, exampleDuration *ExampleDuration) (uint64, error) + LastInsertedSequence(ctx context.Context) (uint64, error) + Update(ctx context.Context, exampleDuration *ExampleDuration) error + Save(ctx context.Context, exampleDuration *ExampleDuration) error + Delete(ctx context.Context, exampleDuration *ExampleDuration) error + Has(ctx context.Context, id uint64) (found bool, err error) + // Get returns nil and an error which responds true to ormerrors.IsNotFound() if the record was not found. + Get(ctx context.Context, id uint64) (*ExampleDuration, error) + List(ctx context.Context, prefixKey ExampleDurationIndexKey, opts ...ormlist.Option) (ExampleDurationIterator, error) + ListRange(ctx context.Context, from, to ExampleDurationIndexKey, opts ...ormlist.Option) (ExampleDurationIterator, error) + DeleteBy(ctx context.Context, prefixKey ExampleDurationIndexKey) error + DeleteRange(ctx context.Context, from, to ExampleDurationIndexKey) error + + doNotImplement() +} + +type ExampleDurationIterator struct { + ormtable.Iterator +} + +func (i ExampleDurationIterator) Value() (*ExampleDuration, error) { + var exampleDuration ExampleDuration + err := i.UnmarshalMessage(&exampleDuration) + return &exampleDuration, err +} + +type ExampleDurationIndexKey interface { + id() uint32 + values() []interface{} + exampleDurationIndexKey() +} + +// primary key starting index.. +type ExampleDurationPrimaryKey = ExampleDurationIdIndexKey + +type ExampleDurationIdIndexKey struct { + vs []interface{} +} + +func (x ExampleDurationIdIndexKey) id() uint32 { return 0 } +func (x ExampleDurationIdIndexKey) values() []interface{} { return x.vs } +func (x ExampleDurationIdIndexKey) exampleDurationIndexKey() {} + +func (this ExampleDurationIdIndexKey) WithId(id uint64) ExampleDurationIdIndexKey { + this.vs = []interface{}{id} + return this +} + +type ExampleDurationDurIndexKey struct { + vs []interface{} +} + +func (x ExampleDurationDurIndexKey) id() uint32 { return 1 } +func (x ExampleDurationDurIndexKey) values() []interface{} { return x.vs } +func (x ExampleDurationDurIndexKey) exampleDurationIndexKey() {} + +func (this ExampleDurationDurIndexKey) WithDur(dur *durationpb.Duration) ExampleDurationDurIndexKey { + this.vs = []interface{}{dur} + return this +} + +type exampleDurationTable struct { + table ormtable.AutoIncrementTable +} + +func (this exampleDurationTable) Insert(ctx context.Context, exampleDuration *ExampleDuration) error { + return this.table.Insert(ctx, exampleDuration) +} + +func (this exampleDurationTable) Update(ctx context.Context, exampleDuration *ExampleDuration) error { + return this.table.Update(ctx, exampleDuration) +} + +func (this exampleDurationTable) Save(ctx context.Context, exampleDuration *ExampleDuration) error { + return this.table.Save(ctx, exampleDuration) +} + +func (this exampleDurationTable) Delete(ctx context.Context, exampleDuration *ExampleDuration) error { + return this.table.Delete(ctx, exampleDuration) +} + +func (this exampleDurationTable) InsertReturningId(ctx context.Context, exampleDuration *ExampleDuration) (uint64, error) { + return this.table.InsertReturningPKey(ctx, exampleDuration) +} + +func (this exampleDurationTable) LastInsertedSequence(ctx context.Context) (uint64, error) { + return this.table.LastInsertedSequence(ctx) +} + +func (this exampleDurationTable) Has(ctx context.Context, id uint64) (found bool, err error) { + return this.table.PrimaryKey().Has(ctx, id) +} + +func (this exampleDurationTable) Get(ctx context.Context, id uint64) (*ExampleDuration, error) { + var exampleDuration ExampleDuration + found, err := this.table.PrimaryKey().Get(ctx, &exampleDuration, id) + if err != nil { + return nil, err + } + if !found { + return nil, ormerrors.NotFound + } + return &exampleDuration, nil +} + +func (this exampleDurationTable) List(ctx context.Context, prefixKey ExampleDurationIndexKey, opts ...ormlist.Option) (ExampleDurationIterator, error) { + it, err := this.table.GetIndexByID(prefixKey.id()).List(ctx, prefixKey.values(), opts...) + return ExampleDurationIterator{it}, err +} + +func (this exampleDurationTable) ListRange(ctx context.Context, from, to ExampleDurationIndexKey, opts ...ormlist.Option) (ExampleDurationIterator, error) { + it, err := this.table.GetIndexByID(from.id()).ListRange(ctx, from.values(), to.values(), opts...) + return ExampleDurationIterator{it}, err +} + +func (this exampleDurationTable) DeleteBy(ctx context.Context, prefixKey ExampleDurationIndexKey) error { + return this.table.GetIndexByID(prefixKey.id()).DeleteBy(ctx, prefixKey.values()...) +} + +func (this exampleDurationTable) DeleteRange(ctx context.Context, from, to ExampleDurationIndexKey) error { + return this.table.GetIndexByID(from.id()).DeleteRange(ctx, from.values(), to.values()) +} + +func (this exampleDurationTable) doNotImplement() {} + +var _ ExampleDurationTable = exampleDurationTable{} + +func NewExampleDurationTable(db ormtable.Schema) (ExampleDurationTable, error) { + table := db.GetTable(&ExampleDuration{}) + if table == nil { + return nil, ormerrors.TableNotFound.Wrap(string((&ExampleDuration{}).ProtoReflect().Descriptor().FullName())) + } + return exampleDurationTable{table.(ormtable.AutoIncrementTable)}, nil +} + type SimpleExampleTable interface { Insert(ctx context.Context, simpleExample *SimpleExample) error Update(ctx context.Context, simpleExample *SimpleExample) error @@ -819,6 +957,7 @@ type TestSchemaStore interface { ExampleAutoIncrementTableTable() ExampleAutoIncrementTableTable ExampleSingletonTable() ExampleSingletonTable ExampleTimestampTable() ExampleTimestampTable + ExampleDurationTable() ExampleDurationTable SimpleExampleTable() SimpleExampleTable ExampleAutoIncFieldNameTable() ExampleAutoIncFieldNameTable @@ -830,6 +969,7 @@ type testSchemaStore struct { exampleAutoIncrementTable ExampleAutoIncrementTableTable exampleSingleton ExampleSingletonTable exampleTimestamp ExampleTimestampTable + exampleDuration ExampleDurationTable simpleExample SimpleExampleTable exampleAutoIncFieldName ExampleAutoIncFieldNameTable } @@ -850,6 +990,10 @@ func (x testSchemaStore) ExampleTimestampTable() ExampleTimestampTable { return x.exampleTimestamp } +func (x testSchemaStore) ExampleDurationTable() ExampleDurationTable { + return x.exampleDuration +} + func (x testSchemaStore) SimpleExampleTable() SimpleExampleTable { return x.simpleExample } @@ -883,6 +1027,11 @@ func NewTestSchemaStore(db ormtable.Schema) (TestSchemaStore, error) { return nil, err } + exampleDurationTable, err := NewExampleDurationTable(db) + if err != nil { + return nil, err + } + simpleExampleTable, err := NewSimpleExampleTable(db) if err != nil { return nil, err @@ -898,6 +1047,7 @@ func NewTestSchemaStore(db ormtable.Schema) (TestSchemaStore, error) { exampleAutoIncrementTableTable, exampleSingletonTable, exampleTimestampTable, + exampleDurationTable, simpleExampleTable, exampleAutoIncFieldNameTable, }, nil diff --git a/orm/internal/testpb/test_schema.pb.go b/orm/internal/testpb/test_schema.pb.go index 8dc30bfc36e4..79f8f8655356 100644 --- a/orm/internal/testpb/test_schema.pb.go +++ b/orm/internal/testpb/test_schema.pb.go @@ -480,6 +480,69 @@ func (x *ExampleTimestamp) GetTs() *timestamppb.Timestamp { return nil } +type ExampleDuration struct { + state protoimpl.MessageState + sizeCache protoimpl.SizeCache + unknownFields protoimpl.UnknownFields + + Id uint64 `protobuf:"varint,1,opt,name=id,proto3" json:"id,omitempty"` + Name string `protobuf:"bytes,2,opt,name=name,proto3" json:"name,omitempty"` + Dur *durationpb.Duration `protobuf:"bytes,3,opt,name=dur,proto3" json:"dur,omitempty"` +} + +func (x *ExampleDuration) Reset() { + *x = ExampleDuration{} + if protoimpl.UnsafeEnabled { + mi := &file_testpb_test_schema_proto_msgTypes[4] + ms := protoimpl.X.MessageStateOf(protoimpl.Pointer(x)) + ms.StoreMessageInfo(mi) + } +} + +func (x *ExampleDuration) String() string { + return protoimpl.X.MessageStringOf(x) +} + +func (*ExampleDuration) ProtoMessage() {} + +func (x *ExampleDuration) ProtoReflect() protoreflect.Message { + mi := &file_testpb_test_schema_proto_msgTypes[4] + if protoimpl.UnsafeEnabled && x != nil { + ms := protoimpl.X.MessageStateOf(protoimpl.Pointer(x)) + if ms.LoadMessageInfo() == nil { + ms.StoreMessageInfo(mi) + } + return ms + } + return mi.MessageOf(x) +} + +// Deprecated: Use ExampleDuration.ProtoReflect.Descriptor instead. +func (*ExampleDuration) Descriptor() ([]byte, []int) { + return file_testpb_test_schema_proto_rawDescGZIP(), []int{4} +} + +func (x *ExampleDuration) GetId() uint64 { + if x != nil { + return x.Id + } + return 0 +} + +func (x *ExampleDuration) GetName() string { + if x != nil { + return x.Name + } + return "" +} + +func (x *ExampleDuration) GetDur() *durationpb.Duration { + if x != nil { + return x.Dur + } + return nil +} + type SimpleExample struct { state protoimpl.MessageState sizeCache protoimpl.SizeCache @@ -493,7 +556,7 @@ type SimpleExample struct { func (x *SimpleExample) Reset() { *x = SimpleExample{} if protoimpl.UnsafeEnabled { - mi := &file_testpb_test_schema_proto_msgTypes[4] + mi := &file_testpb_test_schema_proto_msgTypes[5] ms := protoimpl.X.MessageStateOf(protoimpl.Pointer(x)) ms.StoreMessageInfo(mi) } @@ -506,7 +569,7 @@ func (x *SimpleExample) String() string { func (*SimpleExample) ProtoMessage() {} func (x *SimpleExample) ProtoReflect() protoreflect.Message { - mi := &file_testpb_test_schema_proto_msgTypes[4] + mi := &file_testpb_test_schema_proto_msgTypes[5] if protoimpl.UnsafeEnabled && x != nil { ms := protoimpl.X.MessageStateOf(protoimpl.Pointer(x)) if ms.LoadMessageInfo() == nil { @@ -519,7 +582,7 @@ func (x *SimpleExample) ProtoReflect() protoreflect.Message { // Deprecated: Use SimpleExample.ProtoReflect.Descriptor instead. func (*SimpleExample) Descriptor() ([]byte, []int) { - return file_testpb_test_schema_proto_rawDescGZIP(), []int{4} + return file_testpb_test_schema_proto_rawDescGZIP(), []int{5} } func (x *SimpleExample) GetName() string { @@ -556,7 +619,7 @@ type ExampleAutoIncFieldName struct { func (x *ExampleAutoIncFieldName) Reset() { *x = ExampleAutoIncFieldName{} if protoimpl.UnsafeEnabled { - mi := &file_testpb_test_schema_proto_msgTypes[5] + mi := &file_testpb_test_schema_proto_msgTypes[6] ms := protoimpl.X.MessageStateOf(protoimpl.Pointer(x)) ms.StoreMessageInfo(mi) } @@ -569,7 +632,7 @@ func (x *ExampleAutoIncFieldName) String() string { func (*ExampleAutoIncFieldName) ProtoMessage() {} func (x *ExampleAutoIncFieldName) ProtoReflect() protoreflect.Message { - mi := &file_testpb_test_schema_proto_msgTypes[5] + mi := &file_testpb_test_schema_proto_msgTypes[6] if protoimpl.UnsafeEnabled && x != nil { ms := protoimpl.X.MessageStateOf(protoimpl.Pointer(x)) if ms.LoadMessageInfo() == nil { @@ -582,7 +645,7 @@ func (x *ExampleAutoIncFieldName) ProtoReflect() protoreflect.Message { // Deprecated: Use ExampleAutoIncFieldName.ProtoReflect.Descriptor instead. func (*ExampleAutoIncFieldName) Descriptor() ([]byte, []int) { - return file_testpb_test_schema_proto_rawDescGZIP(), []int{5} + return file_testpb_test_schema_proto_rawDescGZIP(), []int{6} } func (x *ExampleAutoIncFieldName) GetFoo() uint64 { @@ -611,7 +674,7 @@ type ExampleTable_ExampleMessage struct { func (x *ExampleTable_ExampleMessage) Reset() { *x = ExampleTable_ExampleMessage{} if protoimpl.UnsafeEnabled { - mi := &file_testpb_test_schema_proto_msgTypes[7] + mi := &file_testpb_test_schema_proto_msgTypes[8] ms := protoimpl.X.MessageStateOf(protoimpl.Pointer(x)) ms.StoreMessageInfo(mi) } @@ -624,7 +687,7 @@ func (x *ExampleTable_ExampleMessage) String() string { func (*ExampleTable_ExampleMessage) ProtoMessage() {} func (x *ExampleTable_ExampleMessage) ProtoReflect() protoreflect.Message { - mi := &file_testpb_test_schema_proto_msgTypes[7] + mi := &file_testpb_test_schema_proto_msgTypes[8] if protoimpl.UnsafeEnabled && x != nil { ms := protoimpl.X.MessageStateOf(protoimpl.Pointer(x)) if ms.LoadMessageInfo() == nil { @@ -727,35 +790,42 @@ var file_testpb_test_schema_proto_rawDesc = []byte{ 0x70, 0x72, 0x6f, 0x74, 0x6f, 0x62, 0x75, 0x66, 0x2e, 0x54, 0x69, 0x6d, 0x65, 0x73, 0x74, 0x61, 0x6d, 0x70, 0x52, 0x02, 0x74, 0x73, 0x3a, 0x18, 0xf2, 0x9e, 0xd3, 0x8e, 0x03, 0x12, 0x0a, 0x06, 0x0a, 0x02, 0x69, 0x64, 0x10, 0x01, 0x12, 0x06, 0x0a, 0x02, 0x74, 0x73, 0x10, 0x01, 0x18, 0x04, - 0x22, 0x7a, 0x0a, 0x0d, 0x53, 0x69, 0x6d, 0x70, 0x6c, 0x65, 0x45, 0x78, 0x61, 0x6d, 0x70, 0x6c, - 0x65, 0x12, 0x12, 0x0a, 0x04, 0x6e, 0x61, 0x6d, 0x65, 0x18, 0x01, 0x20, 0x01, 0x28, 0x09, 0x52, - 0x04, 0x6e, 0x61, 0x6d, 0x65, 0x12, 0x16, 0x0a, 0x06, 0x75, 0x6e, 0x69, 0x71, 0x75, 0x65, 0x18, - 0x02, 0x20, 0x01, 0x28, 0x09, 0x52, 0x06, 0x75, 0x6e, 0x69, 0x71, 0x75, 0x65, 0x12, 0x1d, 0x0a, - 0x0a, 0x6e, 0x6f, 0x74, 0x5f, 0x75, 0x6e, 0x69, 0x71, 0x75, 0x65, 0x18, 0x03, 0x20, 0x01, 0x28, - 0x09, 0x52, 0x09, 0x6e, 0x6f, 0x74, 0x55, 0x6e, 0x69, 0x71, 0x75, 0x65, 0x3a, 0x1e, 0xf2, 0x9e, - 0xd3, 0x8e, 0x03, 0x18, 0x0a, 0x06, 0x0a, 0x04, 0x6e, 0x61, 0x6d, 0x65, 0x12, 0x0c, 0x0a, 0x06, - 0x75, 0x6e, 0x69, 0x71, 0x75, 0x65, 0x10, 0x01, 0x18, 0x01, 0x18, 0x05, 0x22, 0x50, 0x0a, 0x17, - 0x45, 0x78, 0x61, 0x6d, 0x70, 0x6c, 0x65, 0x41, 0x75, 0x74, 0x6f, 0x49, 0x6e, 0x63, 0x46, 0x69, - 0x65, 0x6c, 0x64, 0x4e, 0x61, 0x6d, 0x65, 0x12, 0x10, 0x0a, 0x03, 0x66, 0x6f, 0x6f, 0x18, 0x01, - 0x20, 0x01, 0x28, 0x04, 0x52, 0x03, 0x66, 0x6f, 0x6f, 0x12, 0x10, 0x0a, 0x03, 0x62, 0x61, 0x72, - 0x18, 0x02, 0x20, 0x01, 0x28, 0x04, 0x52, 0x03, 0x62, 0x61, 0x72, 0x3a, 0x11, 0xf2, 0x9e, 0xd3, - 0x8e, 0x03, 0x0b, 0x0a, 0x07, 0x0a, 0x03, 0x66, 0x6f, 0x6f, 0x10, 0x01, 0x18, 0x06, 0x2a, 0x64, - 0x0a, 0x04, 0x45, 0x6e, 0x75, 0x6d, 0x12, 0x14, 0x0a, 0x10, 0x45, 0x4e, 0x55, 0x4d, 0x5f, 0x55, - 0x4e, 0x53, 0x50, 0x45, 0x43, 0x49, 0x46, 0x49, 0x45, 0x44, 0x10, 0x00, 0x12, 0x0c, 0x0a, 0x08, - 0x45, 0x4e, 0x55, 0x4d, 0x5f, 0x4f, 0x4e, 0x45, 0x10, 0x01, 0x12, 0x0c, 0x0a, 0x08, 0x45, 0x4e, - 0x55, 0x4d, 0x5f, 0x54, 0x57, 0x4f, 0x10, 0x02, 0x12, 0x0d, 0x0a, 0x09, 0x45, 0x4e, 0x55, 0x4d, - 0x5f, 0x46, 0x49, 0x56, 0x45, 0x10, 0x05, 0x12, 0x1b, 0x0a, 0x0e, 0x45, 0x4e, 0x55, 0x4d, 0x5f, - 0x4e, 0x45, 0x47, 0x5f, 0x54, 0x48, 0x52, 0x45, 0x45, 0x10, 0xfd, 0xff, 0xff, 0xff, 0xff, 0xff, - 0xff, 0xff, 0xff, 0x01, 0x42, 0x87, 0x01, 0x0a, 0x0a, 0x63, 0x6f, 0x6d, 0x2e, 0x74, 0x65, 0x73, - 0x74, 0x70, 0x62, 0x42, 0x0f, 0x54, 0x65, 0x73, 0x74, 0x53, 0x63, 0x68, 0x65, 0x6d, 0x61, 0x50, - 0x72, 0x6f, 0x74, 0x6f, 0x50, 0x01, 0x5a, 0x30, 0x67, 0x69, 0x74, 0x68, 0x75, 0x62, 0x2e, 0x63, - 0x6f, 0x6d, 0x2f, 0x63, 0x6f, 0x73, 0x6d, 0x6f, 0x73, 0x2f, 0x63, 0x6f, 0x73, 0x6d, 0x6f, 0x73, - 0x2d, 0x73, 0x64, 0x6b, 0x2f, 0x6f, 0x72, 0x6d, 0x2f, 0x69, 0x6e, 0x74, 0x65, 0x72, 0x6e, 0x61, - 0x6c, 0x2f, 0x74, 0x65, 0x73, 0x74, 0x70, 0x62, 0xa2, 0x02, 0x03, 0x54, 0x58, 0x58, 0xaa, 0x02, - 0x06, 0x54, 0x65, 0x73, 0x74, 0x70, 0x62, 0xca, 0x02, 0x06, 0x54, 0x65, 0x73, 0x74, 0x70, 0x62, - 0xe2, 0x02, 0x12, 0x54, 0x65, 0x73, 0x74, 0x70, 0x62, 0x5c, 0x47, 0x50, 0x42, 0x4d, 0x65, 0x74, - 0x61, 0x64, 0x61, 0x74, 0x61, 0xea, 0x02, 0x06, 0x54, 0x65, 0x73, 0x74, 0x70, 0x62, 0x62, 0x06, - 0x70, 0x72, 0x6f, 0x74, 0x6f, 0x33, + 0x22, 0x7d, 0x0a, 0x0f, 0x45, 0x78, 0x61, 0x6d, 0x70, 0x6c, 0x65, 0x44, 0x75, 0x72, 0x61, 0x74, + 0x69, 0x6f, 0x6e, 0x12, 0x0e, 0x0a, 0x02, 0x69, 0x64, 0x18, 0x01, 0x20, 0x01, 0x28, 0x04, 0x52, + 0x02, 0x69, 0x64, 0x12, 0x12, 0x0a, 0x04, 0x6e, 0x61, 0x6d, 0x65, 0x18, 0x02, 0x20, 0x01, 0x28, + 0x09, 0x52, 0x04, 0x6e, 0x61, 0x6d, 0x65, 0x12, 0x2b, 0x0a, 0x03, 0x64, 0x75, 0x72, 0x18, 0x03, + 0x20, 0x01, 0x28, 0x0b, 0x32, 0x19, 0x2e, 0x67, 0x6f, 0x6f, 0x67, 0x6c, 0x65, 0x2e, 0x70, 0x72, + 0x6f, 0x74, 0x6f, 0x62, 0x75, 0x66, 0x2e, 0x44, 0x75, 0x72, 0x61, 0x74, 0x69, 0x6f, 0x6e, 0x52, + 0x03, 0x64, 0x75, 0x72, 0x3a, 0x19, 0xf2, 0x9e, 0xd3, 0x8e, 0x03, 0x13, 0x0a, 0x06, 0x0a, 0x02, + 0x69, 0x64, 0x10, 0x01, 0x12, 0x07, 0x0a, 0x03, 0x64, 0x75, 0x72, 0x10, 0x01, 0x18, 0x04, 0x22, + 0x7a, 0x0a, 0x0d, 0x53, 0x69, 0x6d, 0x70, 0x6c, 0x65, 0x45, 0x78, 0x61, 0x6d, 0x70, 0x6c, 0x65, + 0x12, 0x12, 0x0a, 0x04, 0x6e, 0x61, 0x6d, 0x65, 0x18, 0x01, 0x20, 0x01, 0x28, 0x09, 0x52, 0x04, + 0x6e, 0x61, 0x6d, 0x65, 0x12, 0x16, 0x0a, 0x06, 0x75, 0x6e, 0x69, 0x71, 0x75, 0x65, 0x18, 0x02, + 0x20, 0x01, 0x28, 0x09, 0x52, 0x06, 0x75, 0x6e, 0x69, 0x71, 0x75, 0x65, 0x12, 0x1d, 0x0a, 0x0a, + 0x6e, 0x6f, 0x74, 0x5f, 0x75, 0x6e, 0x69, 0x71, 0x75, 0x65, 0x18, 0x03, 0x20, 0x01, 0x28, 0x09, + 0x52, 0x09, 0x6e, 0x6f, 0x74, 0x55, 0x6e, 0x69, 0x71, 0x75, 0x65, 0x3a, 0x1e, 0xf2, 0x9e, 0xd3, + 0x8e, 0x03, 0x18, 0x0a, 0x06, 0x0a, 0x04, 0x6e, 0x61, 0x6d, 0x65, 0x12, 0x0c, 0x0a, 0x06, 0x75, + 0x6e, 0x69, 0x71, 0x75, 0x65, 0x10, 0x01, 0x18, 0x01, 0x18, 0x05, 0x22, 0x50, 0x0a, 0x17, 0x45, + 0x78, 0x61, 0x6d, 0x70, 0x6c, 0x65, 0x41, 0x75, 0x74, 0x6f, 0x49, 0x6e, 0x63, 0x46, 0x69, 0x65, + 0x6c, 0x64, 0x4e, 0x61, 0x6d, 0x65, 0x12, 0x10, 0x0a, 0x03, 0x66, 0x6f, 0x6f, 0x18, 0x01, 0x20, + 0x01, 0x28, 0x04, 0x52, 0x03, 0x66, 0x6f, 0x6f, 0x12, 0x10, 0x0a, 0x03, 0x62, 0x61, 0x72, 0x18, + 0x02, 0x20, 0x01, 0x28, 0x04, 0x52, 0x03, 0x62, 0x61, 0x72, 0x3a, 0x11, 0xf2, 0x9e, 0xd3, 0x8e, + 0x03, 0x0b, 0x0a, 0x07, 0x0a, 0x03, 0x66, 0x6f, 0x6f, 0x10, 0x01, 0x18, 0x06, 0x2a, 0x64, 0x0a, + 0x04, 0x45, 0x6e, 0x75, 0x6d, 0x12, 0x14, 0x0a, 0x10, 0x45, 0x4e, 0x55, 0x4d, 0x5f, 0x55, 0x4e, + 0x53, 0x50, 0x45, 0x43, 0x49, 0x46, 0x49, 0x45, 0x44, 0x10, 0x00, 0x12, 0x0c, 0x0a, 0x08, 0x45, + 0x4e, 0x55, 0x4d, 0x5f, 0x4f, 0x4e, 0x45, 0x10, 0x01, 0x12, 0x0c, 0x0a, 0x08, 0x45, 0x4e, 0x55, + 0x4d, 0x5f, 0x54, 0x57, 0x4f, 0x10, 0x02, 0x12, 0x0d, 0x0a, 0x09, 0x45, 0x4e, 0x55, 0x4d, 0x5f, + 0x46, 0x49, 0x56, 0x45, 0x10, 0x05, 0x12, 0x1b, 0x0a, 0x0e, 0x45, 0x4e, 0x55, 0x4d, 0x5f, 0x4e, + 0x45, 0x47, 0x5f, 0x54, 0x48, 0x52, 0x45, 0x45, 0x10, 0xfd, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, + 0xff, 0xff, 0x01, 0x42, 0x77, 0x0a, 0x0a, 0x63, 0x6f, 0x6d, 0x2e, 0x74, 0x65, 0x73, 0x74, 0x70, + 0x62, 0x42, 0x0f, 0x54, 0x65, 0x73, 0x74, 0x53, 0x63, 0x68, 0x65, 0x6d, 0x61, 0x50, 0x72, 0x6f, + 0x74, 0x6f, 0x50, 0x01, 0x5a, 0x20, 0x63, 0x6f, 0x73, 0x6d, 0x6f, 0x73, 0x73, 0x64, 0x6b, 0x2e, + 0x69, 0x6f, 0x2f, 0x6f, 0x72, 0x6d, 0x2f, 0x69, 0x6e, 0x74, 0x65, 0x72, 0x6e, 0x61, 0x6c, 0x2f, + 0x74, 0x65, 0x73, 0x74, 0x70, 0x62, 0xa2, 0x02, 0x03, 0x54, 0x58, 0x58, 0xaa, 0x02, 0x06, 0x54, + 0x65, 0x73, 0x74, 0x70, 0x62, 0xca, 0x02, 0x06, 0x54, 0x65, 0x73, 0x74, 0x70, 0x62, 0xe2, 0x02, + 0x12, 0x54, 0x65, 0x73, 0x74, 0x70, 0x62, 0x5c, 0x47, 0x50, 0x42, 0x4d, 0x65, 0x74, 0x61, 0x64, + 0x61, 0x74, 0x61, 0xea, 0x02, 0x06, 0x54, 0x65, 0x73, 0x74, 0x70, 0x62, 0x62, 0x06, 0x70, 0x72, + 0x6f, 0x74, 0x6f, 0x33, } var ( @@ -771,32 +841,34 @@ func file_testpb_test_schema_proto_rawDescGZIP() []byte { } var file_testpb_test_schema_proto_enumTypes = make([]protoimpl.EnumInfo, 1) -var file_testpb_test_schema_proto_msgTypes = make([]protoimpl.MessageInfo, 8) +var file_testpb_test_schema_proto_msgTypes = make([]protoimpl.MessageInfo, 9) var file_testpb_test_schema_proto_goTypes = []interface{}{ (Enum)(0), // 0: testpb.Enum (*ExampleTable)(nil), // 1: testpb.ExampleTable (*ExampleAutoIncrementTable)(nil), // 2: testpb.ExampleAutoIncrementTable (*ExampleSingleton)(nil), // 3: testpb.ExampleSingleton (*ExampleTimestamp)(nil), // 4: testpb.ExampleTimestamp - (*SimpleExample)(nil), // 5: testpb.SimpleExample - (*ExampleAutoIncFieldName)(nil), // 6: testpb.ExampleAutoIncFieldName - nil, // 7: testpb.ExampleTable.MapEntry - (*ExampleTable_ExampleMessage)(nil), // 8: testpb.ExampleTable.ExampleMessage - (*timestamppb.Timestamp)(nil), // 9: google.protobuf.Timestamp - (*durationpb.Duration)(nil), // 10: google.protobuf.Duration + (*ExampleDuration)(nil), // 5: testpb.ExampleDuration + (*SimpleExample)(nil), // 6: testpb.SimpleExample + (*ExampleAutoIncFieldName)(nil), // 7: testpb.ExampleAutoIncFieldName + nil, // 8: testpb.ExampleTable.MapEntry + (*ExampleTable_ExampleMessage)(nil), // 9: testpb.ExampleTable.ExampleMessage + (*timestamppb.Timestamp)(nil), // 10: google.protobuf.Timestamp + (*durationpb.Duration)(nil), // 11: google.protobuf.Duration } var file_testpb_test_schema_proto_depIdxs = []int32{ - 9, // 0: testpb.ExampleTable.ts:type_name -> google.protobuf.Timestamp - 10, // 1: testpb.ExampleTable.dur:type_name -> google.protobuf.Duration + 10, // 0: testpb.ExampleTable.ts:type_name -> google.protobuf.Timestamp + 11, // 1: testpb.ExampleTable.dur:type_name -> google.protobuf.Duration 0, // 2: testpb.ExampleTable.e:type_name -> testpb.Enum - 7, // 3: testpb.ExampleTable.map:type_name -> testpb.ExampleTable.MapEntry - 8, // 4: testpb.ExampleTable.msg:type_name -> testpb.ExampleTable.ExampleMessage - 9, // 5: testpb.ExampleTimestamp.ts:type_name -> google.protobuf.Timestamp - 6, // [6:6] is the sub-list for method output_type - 6, // [6:6] is the sub-list for method input_type - 6, // [6:6] is the sub-list for extension type_name - 6, // [6:6] is the sub-list for extension extendee - 0, // [0:6] is the sub-list for field type_name + 8, // 3: testpb.ExampleTable.map:type_name -> testpb.ExampleTable.MapEntry + 9, // 4: testpb.ExampleTable.msg:type_name -> testpb.ExampleTable.ExampleMessage + 10, // 5: testpb.ExampleTimestamp.ts:type_name -> google.protobuf.Timestamp + 11, // 6: testpb.ExampleDuration.dur:type_name -> google.protobuf.Duration + 7, // [7:7] is the sub-list for method output_type + 7, // [7:7] is the sub-list for method input_type + 7, // [7:7] is the sub-list for extension type_name + 7, // [7:7] is the sub-list for extension extendee + 0, // [0:7] is the sub-list for field type_name } func init() { file_testpb_test_schema_proto_init() } @@ -854,7 +926,7 @@ func file_testpb_test_schema_proto_init() { } } file_testpb_test_schema_proto_msgTypes[4].Exporter = func(v interface{}, i int) interface{} { - switch v := v.(*SimpleExample); i { + switch v := v.(*ExampleDuration); i { case 0: return &v.state case 1: @@ -866,6 +938,18 @@ func file_testpb_test_schema_proto_init() { } } file_testpb_test_schema_proto_msgTypes[5].Exporter = func(v interface{}, i int) interface{} { + switch v := v.(*SimpleExample); i { + case 0: + return &v.state + case 1: + return &v.sizeCache + case 2: + return &v.unknownFields + default: + return nil + } + } + file_testpb_test_schema_proto_msgTypes[6].Exporter = func(v interface{}, i int) interface{} { switch v := v.(*ExampleAutoIncFieldName); i { case 0: return &v.state @@ -877,7 +961,7 @@ func file_testpb_test_schema_proto_init() { return nil } } - file_testpb_test_schema_proto_msgTypes[7].Exporter = func(v interface{}, i int) interface{} { + file_testpb_test_schema_proto_msgTypes[8].Exporter = func(v interface{}, i int) interface{} { switch v := v.(*ExampleTable_ExampleMessage); i { case 0: return &v.state @@ -899,7 +983,7 @@ func file_testpb_test_schema_proto_init() { GoPackagePath: reflect.TypeOf(x{}).PkgPath(), RawDescriptor: file_testpb_test_schema_proto_rawDesc, NumEnums: 1, - NumMessages: 8, + NumMessages: 9, NumExtensions: 0, NumServices: 0, }, diff --git a/orm/internal/testpb/test_schema.proto b/orm/internal/testpb/test_schema.proto index 2a27f8f737a5..3aed58319e3f 100644 --- a/orm/internal/testpb/test_schema.proto +++ b/orm/internal/testpb/test_schema.proto @@ -107,6 +107,18 @@ message ExampleTimestamp { google.protobuf.Timestamp ts = 3; } +message ExampleDuration { + option (cosmos.orm.v1.table) = { + id: 4 + primary_key: {fields: "id" auto_increment: true} + index: {id: 1 fields: "dur"} + }; + + uint64 id = 1; + string name = 2; + google.protobuf.Duration dur = 3; +} + message SimpleExample { option (cosmos.orm.v1.table) = { id: 5 diff --git a/orm/internal/testpb/test_schema_query.pb.go b/orm/internal/testpb/test_schema_query.pb.go index 484624eb6492..48d7a1339a74 100644 --- a/orm/internal/testpb/test_schema_query.pb.go +++ b/orm/internal/testpb/test_schema_query.pb.go @@ -12,6 +12,7 @@ import ( v1beta1 "cosmossdk.io/api/cosmos/base/query/v1beta1" protoreflect "google.golang.org/protobuf/reflect/protoreflect" protoimpl "google.golang.org/protobuf/runtime/protoimpl" + durationpb "google.golang.org/protobuf/types/known/durationpb" timestamppb "google.golang.org/protobuf/types/known/timestamppb" reflect "reflect" sync "sync" @@ -1084,6 +1085,257 @@ func (x *ListExampleTimestampResponse) GetPagination() *v1beta1.PageResponse { return nil } +// GetExampleDurationRequest is the TestSchemaQuery/GetExampleDurationRequest request type. +type GetExampleDurationRequest struct { + state protoimpl.MessageState + sizeCache protoimpl.SizeCache + unknownFields protoimpl.UnknownFields + + // id specifies the value of the id field in the primary key. + Id uint64 `protobuf:"varint,1,opt,name=id,proto3" json:"id,omitempty"` +} + +func (x *GetExampleDurationRequest) Reset() { + *x = GetExampleDurationRequest{} + if protoimpl.UnsafeEnabled { + mi := &file_testpb_test_schema_query_proto_msgTypes[18] + ms := protoimpl.X.MessageStateOf(protoimpl.Pointer(x)) + ms.StoreMessageInfo(mi) + } +} + +func (x *GetExampleDurationRequest) String() string { + return protoimpl.X.MessageStringOf(x) +} + +func (*GetExampleDurationRequest) ProtoMessage() {} + +func (x *GetExampleDurationRequest) ProtoReflect() protoreflect.Message { + mi := &file_testpb_test_schema_query_proto_msgTypes[18] + if protoimpl.UnsafeEnabled && x != nil { + ms := protoimpl.X.MessageStateOf(protoimpl.Pointer(x)) + if ms.LoadMessageInfo() == nil { + ms.StoreMessageInfo(mi) + } + return ms + } + return mi.MessageOf(x) +} + +// Deprecated: Use GetExampleDurationRequest.ProtoReflect.Descriptor instead. +func (*GetExampleDurationRequest) Descriptor() ([]byte, []int) { + return file_testpb_test_schema_query_proto_rawDescGZIP(), []int{18} +} + +func (x *GetExampleDurationRequest) GetId() uint64 { + if x != nil { + return x.Id + } + return 0 +} + +// GetExampleDurationResponse is the TestSchemaQuery/GetExampleDurationResponse response type. +type GetExampleDurationResponse struct { + state protoimpl.MessageState + sizeCache protoimpl.SizeCache + unknownFields protoimpl.UnknownFields + + // value is the response value. + Value *ExampleDuration `protobuf:"bytes,1,opt,name=value,proto3" json:"value,omitempty"` +} + +func (x *GetExampleDurationResponse) Reset() { + *x = GetExampleDurationResponse{} + if protoimpl.UnsafeEnabled { + mi := &file_testpb_test_schema_query_proto_msgTypes[19] + ms := protoimpl.X.MessageStateOf(protoimpl.Pointer(x)) + ms.StoreMessageInfo(mi) + } +} + +func (x *GetExampleDurationResponse) String() string { + return protoimpl.X.MessageStringOf(x) +} + +func (*GetExampleDurationResponse) ProtoMessage() {} + +func (x *GetExampleDurationResponse) ProtoReflect() protoreflect.Message { + mi := &file_testpb_test_schema_query_proto_msgTypes[19] + if protoimpl.UnsafeEnabled && x != nil { + ms := protoimpl.X.MessageStateOf(protoimpl.Pointer(x)) + if ms.LoadMessageInfo() == nil { + ms.StoreMessageInfo(mi) + } + return ms + } + return mi.MessageOf(x) +} + +// Deprecated: Use GetExampleDurationResponse.ProtoReflect.Descriptor instead. +func (*GetExampleDurationResponse) Descriptor() ([]byte, []int) { + return file_testpb_test_schema_query_proto_rawDescGZIP(), []int{19} +} + +func (x *GetExampleDurationResponse) GetValue() *ExampleDuration { + if x != nil { + return x.Value + } + return nil +} + +// ListExampleDurationRequest is the TestSchemaQuery/ListExampleDurationRequest request type. +type ListExampleDurationRequest struct { + state protoimpl.MessageState + sizeCache protoimpl.SizeCache + unknownFields protoimpl.UnknownFields + + // query specifies the type of query - either a prefix or range query. + // + // Types that are assignable to Query: + // + // *ListExampleDurationRequest_PrefixQuery + // *ListExampleDurationRequest_RangeQuery_ + Query isListExampleDurationRequest_Query `protobuf_oneof:"query"` + // pagination specifies optional pagination parameters. + Pagination *v1beta1.PageRequest `protobuf:"bytes,3,opt,name=pagination,proto3" json:"pagination,omitempty"` +} + +func (x *ListExampleDurationRequest) Reset() { + *x = ListExampleDurationRequest{} + if protoimpl.UnsafeEnabled { + mi := &file_testpb_test_schema_query_proto_msgTypes[20] + ms := protoimpl.X.MessageStateOf(protoimpl.Pointer(x)) + ms.StoreMessageInfo(mi) + } +} + +func (x *ListExampleDurationRequest) String() string { + return protoimpl.X.MessageStringOf(x) +} + +func (*ListExampleDurationRequest) ProtoMessage() {} + +func (x *ListExampleDurationRequest) ProtoReflect() protoreflect.Message { + mi := &file_testpb_test_schema_query_proto_msgTypes[20] + if protoimpl.UnsafeEnabled && x != nil { + ms := protoimpl.X.MessageStateOf(protoimpl.Pointer(x)) + if ms.LoadMessageInfo() == nil { + ms.StoreMessageInfo(mi) + } + return ms + } + return mi.MessageOf(x) +} + +// Deprecated: Use ListExampleDurationRequest.ProtoReflect.Descriptor instead. +func (*ListExampleDurationRequest) Descriptor() ([]byte, []int) { + return file_testpb_test_schema_query_proto_rawDescGZIP(), []int{20} +} + +func (m *ListExampleDurationRequest) GetQuery() isListExampleDurationRequest_Query { + if m != nil { + return m.Query + } + return nil +} + +func (x *ListExampleDurationRequest) GetPrefixQuery() *ListExampleDurationRequest_IndexKey { + if x, ok := x.GetQuery().(*ListExampleDurationRequest_PrefixQuery); ok { + return x.PrefixQuery + } + return nil +} + +func (x *ListExampleDurationRequest) GetRangeQuery() *ListExampleDurationRequest_RangeQuery { + if x, ok := x.GetQuery().(*ListExampleDurationRequest_RangeQuery_); ok { + return x.RangeQuery + } + return nil +} + +func (x *ListExampleDurationRequest) GetPagination() *v1beta1.PageRequest { + if x != nil { + return x.Pagination + } + return nil +} + +type isListExampleDurationRequest_Query interface { + isListExampleDurationRequest_Query() +} + +type ListExampleDurationRequest_PrefixQuery struct { + // prefix_query specifies the index key value to use for the prefix query. + PrefixQuery *ListExampleDurationRequest_IndexKey `protobuf:"bytes,1,opt,name=prefix_query,json=prefixQuery,proto3,oneof"` +} + +type ListExampleDurationRequest_RangeQuery_ struct { + // range_query specifies the index key from/to values to use for the range query. + RangeQuery *ListExampleDurationRequest_RangeQuery `protobuf:"bytes,2,opt,name=range_query,json=rangeQuery,proto3,oneof"` +} + +func (*ListExampleDurationRequest_PrefixQuery) isListExampleDurationRequest_Query() {} + +func (*ListExampleDurationRequest_RangeQuery_) isListExampleDurationRequest_Query() {} + +// ListExampleDurationResponse is the TestSchemaQuery/ListExampleDurationResponse response type. +type ListExampleDurationResponse struct { + state protoimpl.MessageState + sizeCache protoimpl.SizeCache + unknownFields protoimpl.UnknownFields + + // values are the results of the query. + Values []*ExampleDuration `protobuf:"bytes,1,rep,name=values,proto3" json:"values,omitempty"` + // pagination is the pagination response. + Pagination *v1beta1.PageResponse `protobuf:"bytes,2,opt,name=pagination,proto3" json:"pagination,omitempty"` +} + +func (x *ListExampleDurationResponse) Reset() { + *x = ListExampleDurationResponse{} + if protoimpl.UnsafeEnabled { + mi := &file_testpb_test_schema_query_proto_msgTypes[21] + ms := protoimpl.X.MessageStateOf(protoimpl.Pointer(x)) + ms.StoreMessageInfo(mi) + } +} + +func (x *ListExampleDurationResponse) String() string { + return protoimpl.X.MessageStringOf(x) +} + +func (*ListExampleDurationResponse) ProtoMessage() {} + +func (x *ListExampleDurationResponse) ProtoReflect() protoreflect.Message { + mi := &file_testpb_test_schema_query_proto_msgTypes[21] + if protoimpl.UnsafeEnabled && x != nil { + ms := protoimpl.X.MessageStateOf(protoimpl.Pointer(x)) + if ms.LoadMessageInfo() == nil { + ms.StoreMessageInfo(mi) + } + return ms + } + return mi.MessageOf(x) +} + +// Deprecated: Use ListExampleDurationResponse.ProtoReflect.Descriptor instead. +func (*ListExampleDurationResponse) Descriptor() ([]byte, []int) { + return file_testpb_test_schema_query_proto_rawDescGZIP(), []int{21} +} + +func (x *ListExampleDurationResponse) GetValues() []*ExampleDuration { + if x != nil { + return x.Values + } + return nil +} + +func (x *ListExampleDurationResponse) GetPagination() *v1beta1.PageResponse { + if x != nil { + return x.Pagination + } + return nil +} + // GetSimpleExampleRequest is the TestSchemaQuery/GetSimpleExampleRequest request type. type GetSimpleExampleRequest struct { state protoimpl.MessageState @@ -1097,7 +1349,7 @@ type GetSimpleExampleRequest struct { func (x *GetSimpleExampleRequest) Reset() { *x = GetSimpleExampleRequest{} if protoimpl.UnsafeEnabled { - mi := &file_testpb_test_schema_query_proto_msgTypes[18] + mi := &file_testpb_test_schema_query_proto_msgTypes[22] ms := protoimpl.X.MessageStateOf(protoimpl.Pointer(x)) ms.StoreMessageInfo(mi) } @@ -1110,7 +1362,7 @@ func (x *GetSimpleExampleRequest) String() string { func (*GetSimpleExampleRequest) ProtoMessage() {} func (x *GetSimpleExampleRequest) ProtoReflect() protoreflect.Message { - mi := &file_testpb_test_schema_query_proto_msgTypes[18] + mi := &file_testpb_test_schema_query_proto_msgTypes[22] if protoimpl.UnsafeEnabled && x != nil { ms := protoimpl.X.MessageStateOf(protoimpl.Pointer(x)) if ms.LoadMessageInfo() == nil { @@ -1123,7 +1375,7 @@ func (x *GetSimpleExampleRequest) ProtoReflect() protoreflect.Message { // Deprecated: Use GetSimpleExampleRequest.ProtoReflect.Descriptor instead. func (*GetSimpleExampleRequest) Descriptor() ([]byte, []int) { - return file_testpb_test_schema_query_proto_rawDescGZIP(), []int{18} + return file_testpb_test_schema_query_proto_rawDescGZIP(), []int{22} } func (x *GetSimpleExampleRequest) GetName() string { @@ -1146,7 +1398,7 @@ type GetSimpleExampleResponse struct { func (x *GetSimpleExampleResponse) Reset() { *x = GetSimpleExampleResponse{} if protoimpl.UnsafeEnabled { - mi := &file_testpb_test_schema_query_proto_msgTypes[19] + mi := &file_testpb_test_schema_query_proto_msgTypes[23] ms := protoimpl.X.MessageStateOf(protoimpl.Pointer(x)) ms.StoreMessageInfo(mi) } @@ -1159,7 +1411,7 @@ func (x *GetSimpleExampleResponse) String() string { func (*GetSimpleExampleResponse) ProtoMessage() {} func (x *GetSimpleExampleResponse) ProtoReflect() protoreflect.Message { - mi := &file_testpb_test_schema_query_proto_msgTypes[19] + mi := &file_testpb_test_schema_query_proto_msgTypes[23] if protoimpl.UnsafeEnabled && x != nil { ms := protoimpl.X.MessageStateOf(protoimpl.Pointer(x)) if ms.LoadMessageInfo() == nil { @@ -1172,7 +1424,7 @@ func (x *GetSimpleExampleResponse) ProtoReflect() protoreflect.Message { // Deprecated: Use GetSimpleExampleResponse.ProtoReflect.Descriptor instead. func (*GetSimpleExampleResponse) Descriptor() ([]byte, []int) { - return file_testpb_test_schema_query_proto_rawDescGZIP(), []int{19} + return file_testpb_test_schema_query_proto_rawDescGZIP(), []int{23} } func (x *GetSimpleExampleResponse) GetValue() *SimpleExample { @@ -1194,7 +1446,7 @@ type GetSimpleExampleByUniqueRequest struct { func (x *GetSimpleExampleByUniqueRequest) Reset() { *x = GetSimpleExampleByUniqueRequest{} if protoimpl.UnsafeEnabled { - mi := &file_testpb_test_schema_query_proto_msgTypes[20] + mi := &file_testpb_test_schema_query_proto_msgTypes[24] ms := protoimpl.X.MessageStateOf(protoimpl.Pointer(x)) ms.StoreMessageInfo(mi) } @@ -1207,7 +1459,7 @@ func (x *GetSimpleExampleByUniqueRequest) String() string { func (*GetSimpleExampleByUniqueRequest) ProtoMessage() {} func (x *GetSimpleExampleByUniqueRequest) ProtoReflect() protoreflect.Message { - mi := &file_testpb_test_schema_query_proto_msgTypes[20] + mi := &file_testpb_test_schema_query_proto_msgTypes[24] if protoimpl.UnsafeEnabled && x != nil { ms := protoimpl.X.MessageStateOf(protoimpl.Pointer(x)) if ms.LoadMessageInfo() == nil { @@ -1220,7 +1472,7 @@ func (x *GetSimpleExampleByUniqueRequest) ProtoReflect() protoreflect.Message { // Deprecated: Use GetSimpleExampleByUniqueRequest.ProtoReflect.Descriptor instead. func (*GetSimpleExampleByUniqueRequest) Descriptor() ([]byte, []int) { - return file_testpb_test_schema_query_proto_rawDescGZIP(), []int{20} + return file_testpb_test_schema_query_proto_rawDescGZIP(), []int{24} } func (x *GetSimpleExampleByUniqueRequest) GetUnique() string { @@ -1242,7 +1494,7 @@ type GetSimpleExampleByUniqueResponse struct { func (x *GetSimpleExampleByUniqueResponse) Reset() { *x = GetSimpleExampleByUniqueResponse{} if protoimpl.UnsafeEnabled { - mi := &file_testpb_test_schema_query_proto_msgTypes[21] + mi := &file_testpb_test_schema_query_proto_msgTypes[25] ms := protoimpl.X.MessageStateOf(protoimpl.Pointer(x)) ms.StoreMessageInfo(mi) } @@ -1255,7 +1507,7 @@ func (x *GetSimpleExampleByUniqueResponse) String() string { func (*GetSimpleExampleByUniqueResponse) ProtoMessage() {} func (x *GetSimpleExampleByUniqueResponse) ProtoReflect() protoreflect.Message { - mi := &file_testpb_test_schema_query_proto_msgTypes[21] + mi := &file_testpb_test_schema_query_proto_msgTypes[25] if protoimpl.UnsafeEnabled && x != nil { ms := protoimpl.X.MessageStateOf(protoimpl.Pointer(x)) if ms.LoadMessageInfo() == nil { @@ -1268,7 +1520,7 @@ func (x *GetSimpleExampleByUniqueResponse) ProtoReflect() protoreflect.Message { // Deprecated: Use GetSimpleExampleByUniqueResponse.ProtoReflect.Descriptor instead. func (*GetSimpleExampleByUniqueResponse) Descriptor() ([]byte, []int) { - return file_testpb_test_schema_query_proto_rawDescGZIP(), []int{21} + return file_testpb_test_schema_query_proto_rawDescGZIP(), []int{25} } func (x *GetSimpleExampleByUniqueResponse) GetValue() *SimpleExample { @@ -1298,7 +1550,7 @@ type ListSimpleExampleRequest struct { func (x *ListSimpleExampleRequest) Reset() { *x = ListSimpleExampleRequest{} if protoimpl.UnsafeEnabled { - mi := &file_testpb_test_schema_query_proto_msgTypes[22] + mi := &file_testpb_test_schema_query_proto_msgTypes[26] ms := protoimpl.X.MessageStateOf(protoimpl.Pointer(x)) ms.StoreMessageInfo(mi) } @@ -1311,7 +1563,7 @@ func (x *ListSimpleExampleRequest) String() string { func (*ListSimpleExampleRequest) ProtoMessage() {} func (x *ListSimpleExampleRequest) ProtoReflect() protoreflect.Message { - mi := &file_testpb_test_schema_query_proto_msgTypes[22] + mi := &file_testpb_test_schema_query_proto_msgTypes[26] if protoimpl.UnsafeEnabled && x != nil { ms := protoimpl.X.MessageStateOf(protoimpl.Pointer(x)) if ms.LoadMessageInfo() == nil { @@ -1324,7 +1576,7 @@ func (x *ListSimpleExampleRequest) ProtoReflect() protoreflect.Message { // Deprecated: Use ListSimpleExampleRequest.ProtoReflect.Descriptor instead. func (*ListSimpleExampleRequest) Descriptor() ([]byte, []int) { - return file_testpb_test_schema_query_proto_rawDescGZIP(), []int{22} + return file_testpb_test_schema_query_proto_rawDescGZIP(), []int{26} } func (m *ListSimpleExampleRequest) GetQuery() isListSimpleExampleRequest_Query { @@ -1388,7 +1640,7 @@ type ListSimpleExampleResponse struct { func (x *ListSimpleExampleResponse) Reset() { *x = ListSimpleExampleResponse{} if protoimpl.UnsafeEnabled { - mi := &file_testpb_test_schema_query_proto_msgTypes[23] + mi := &file_testpb_test_schema_query_proto_msgTypes[27] ms := protoimpl.X.MessageStateOf(protoimpl.Pointer(x)) ms.StoreMessageInfo(mi) } @@ -1401,7 +1653,7 @@ func (x *ListSimpleExampleResponse) String() string { func (*ListSimpleExampleResponse) ProtoMessage() {} func (x *ListSimpleExampleResponse) ProtoReflect() protoreflect.Message { - mi := &file_testpb_test_schema_query_proto_msgTypes[23] + mi := &file_testpb_test_schema_query_proto_msgTypes[27] if protoimpl.UnsafeEnabled && x != nil { ms := protoimpl.X.MessageStateOf(protoimpl.Pointer(x)) if ms.LoadMessageInfo() == nil { @@ -1414,7 +1666,7 @@ func (x *ListSimpleExampleResponse) ProtoReflect() protoreflect.Message { // Deprecated: Use ListSimpleExampleResponse.ProtoReflect.Descriptor instead. func (*ListSimpleExampleResponse) Descriptor() ([]byte, []int) { - return file_testpb_test_schema_query_proto_rawDescGZIP(), []int{23} + return file_testpb_test_schema_query_proto_rawDescGZIP(), []int{27} } func (x *ListSimpleExampleResponse) GetValues() []*SimpleExample { @@ -1444,7 +1696,7 @@ type GetExampleAutoIncFieldNameRequest struct { func (x *GetExampleAutoIncFieldNameRequest) Reset() { *x = GetExampleAutoIncFieldNameRequest{} if protoimpl.UnsafeEnabled { - mi := &file_testpb_test_schema_query_proto_msgTypes[24] + mi := &file_testpb_test_schema_query_proto_msgTypes[28] ms := protoimpl.X.MessageStateOf(protoimpl.Pointer(x)) ms.StoreMessageInfo(mi) } @@ -1457,7 +1709,7 @@ func (x *GetExampleAutoIncFieldNameRequest) String() string { func (*GetExampleAutoIncFieldNameRequest) ProtoMessage() {} func (x *GetExampleAutoIncFieldNameRequest) ProtoReflect() protoreflect.Message { - mi := &file_testpb_test_schema_query_proto_msgTypes[24] + mi := &file_testpb_test_schema_query_proto_msgTypes[28] if protoimpl.UnsafeEnabled && x != nil { ms := protoimpl.X.MessageStateOf(protoimpl.Pointer(x)) if ms.LoadMessageInfo() == nil { @@ -1470,7 +1722,7 @@ func (x *GetExampleAutoIncFieldNameRequest) ProtoReflect() protoreflect.Message // Deprecated: Use GetExampleAutoIncFieldNameRequest.ProtoReflect.Descriptor instead. func (*GetExampleAutoIncFieldNameRequest) Descriptor() ([]byte, []int) { - return file_testpb_test_schema_query_proto_rawDescGZIP(), []int{24} + return file_testpb_test_schema_query_proto_rawDescGZIP(), []int{28} } func (x *GetExampleAutoIncFieldNameRequest) GetFoo() uint64 { @@ -1493,7 +1745,7 @@ type GetExampleAutoIncFieldNameResponse struct { func (x *GetExampleAutoIncFieldNameResponse) Reset() { *x = GetExampleAutoIncFieldNameResponse{} if protoimpl.UnsafeEnabled { - mi := &file_testpb_test_schema_query_proto_msgTypes[25] + mi := &file_testpb_test_schema_query_proto_msgTypes[29] ms := protoimpl.X.MessageStateOf(protoimpl.Pointer(x)) ms.StoreMessageInfo(mi) } @@ -1506,7 +1758,7 @@ func (x *GetExampleAutoIncFieldNameResponse) String() string { func (*GetExampleAutoIncFieldNameResponse) ProtoMessage() {} func (x *GetExampleAutoIncFieldNameResponse) ProtoReflect() protoreflect.Message { - mi := &file_testpb_test_schema_query_proto_msgTypes[25] + mi := &file_testpb_test_schema_query_proto_msgTypes[29] if protoimpl.UnsafeEnabled && x != nil { ms := protoimpl.X.MessageStateOf(protoimpl.Pointer(x)) if ms.LoadMessageInfo() == nil { @@ -1519,7 +1771,7 @@ func (x *GetExampleAutoIncFieldNameResponse) ProtoReflect() protoreflect.Message // Deprecated: Use GetExampleAutoIncFieldNameResponse.ProtoReflect.Descriptor instead. func (*GetExampleAutoIncFieldNameResponse) Descriptor() ([]byte, []int) { - return file_testpb_test_schema_query_proto_rawDescGZIP(), []int{25} + return file_testpb_test_schema_query_proto_rawDescGZIP(), []int{29} } func (x *GetExampleAutoIncFieldNameResponse) GetValue() *ExampleAutoIncFieldName { @@ -1549,7 +1801,7 @@ type ListExampleAutoIncFieldNameRequest struct { func (x *ListExampleAutoIncFieldNameRequest) Reset() { *x = ListExampleAutoIncFieldNameRequest{} if protoimpl.UnsafeEnabled { - mi := &file_testpb_test_schema_query_proto_msgTypes[26] + mi := &file_testpb_test_schema_query_proto_msgTypes[30] ms := protoimpl.X.MessageStateOf(protoimpl.Pointer(x)) ms.StoreMessageInfo(mi) } @@ -1562,7 +1814,7 @@ func (x *ListExampleAutoIncFieldNameRequest) String() string { func (*ListExampleAutoIncFieldNameRequest) ProtoMessage() {} func (x *ListExampleAutoIncFieldNameRequest) ProtoReflect() protoreflect.Message { - mi := &file_testpb_test_schema_query_proto_msgTypes[26] + mi := &file_testpb_test_schema_query_proto_msgTypes[30] if protoimpl.UnsafeEnabled && x != nil { ms := protoimpl.X.MessageStateOf(protoimpl.Pointer(x)) if ms.LoadMessageInfo() == nil { @@ -1575,7 +1827,7 @@ func (x *ListExampleAutoIncFieldNameRequest) ProtoReflect() protoreflect.Message // Deprecated: Use ListExampleAutoIncFieldNameRequest.ProtoReflect.Descriptor instead. func (*ListExampleAutoIncFieldNameRequest) Descriptor() ([]byte, []int) { - return file_testpb_test_schema_query_proto_rawDescGZIP(), []int{26} + return file_testpb_test_schema_query_proto_rawDescGZIP(), []int{30} } func (m *ListExampleAutoIncFieldNameRequest) GetQuery() isListExampleAutoIncFieldNameRequest_Query { @@ -1639,7 +1891,7 @@ type ListExampleAutoIncFieldNameResponse struct { func (x *ListExampleAutoIncFieldNameResponse) Reset() { *x = ListExampleAutoIncFieldNameResponse{} if protoimpl.UnsafeEnabled { - mi := &file_testpb_test_schema_query_proto_msgTypes[27] + mi := &file_testpb_test_schema_query_proto_msgTypes[31] ms := protoimpl.X.MessageStateOf(protoimpl.Pointer(x)) ms.StoreMessageInfo(mi) } @@ -1652,7 +1904,7 @@ func (x *ListExampleAutoIncFieldNameResponse) String() string { func (*ListExampleAutoIncFieldNameResponse) ProtoMessage() {} func (x *ListExampleAutoIncFieldNameResponse) ProtoReflect() protoreflect.Message { - mi := &file_testpb_test_schema_query_proto_msgTypes[27] + mi := &file_testpb_test_schema_query_proto_msgTypes[31] if protoimpl.UnsafeEnabled && x != nil { ms := protoimpl.X.MessageStateOf(protoimpl.Pointer(x)) if ms.LoadMessageInfo() == nil { @@ -1665,7 +1917,7 @@ func (x *ListExampleAutoIncFieldNameResponse) ProtoReflect() protoreflect.Messag // Deprecated: Use ListExampleAutoIncFieldNameResponse.ProtoReflect.Descriptor instead. func (*ListExampleAutoIncFieldNameResponse) Descriptor() ([]byte, []int) { - return file_testpb_test_schema_query_proto_rawDescGZIP(), []int{27} + return file_testpb_test_schema_query_proto_rawDescGZIP(), []int{31} } func (x *ListExampleAutoIncFieldNameResponse) GetValues() []*ExampleAutoIncFieldName { @@ -1702,7 +1954,7 @@ type ListExampleTableRequest_IndexKey struct { func (x *ListExampleTableRequest_IndexKey) Reset() { *x = ListExampleTableRequest_IndexKey{} if protoimpl.UnsafeEnabled { - mi := &file_testpb_test_schema_query_proto_msgTypes[28] + mi := &file_testpb_test_schema_query_proto_msgTypes[32] ms := protoimpl.X.MessageStateOf(protoimpl.Pointer(x)) ms.StoreMessageInfo(mi) } @@ -1715,7 +1967,7 @@ func (x *ListExampleTableRequest_IndexKey) String() string { func (*ListExampleTableRequest_IndexKey) ProtoMessage() {} func (x *ListExampleTableRequest_IndexKey) ProtoReflect() protoreflect.Message { - mi := &file_testpb_test_schema_query_proto_msgTypes[28] + mi := &file_testpb_test_schema_query_proto_msgTypes[32] if protoimpl.UnsafeEnabled && x != nil { ms := protoimpl.X.MessageStateOf(protoimpl.Pointer(x)) if ms.LoadMessageInfo() == nil { @@ -1816,7 +2068,7 @@ type ListExampleTableRequest_RangeQuery struct { func (x *ListExampleTableRequest_RangeQuery) Reset() { *x = ListExampleTableRequest_RangeQuery{} if protoimpl.UnsafeEnabled { - mi := &file_testpb_test_schema_query_proto_msgTypes[29] + mi := &file_testpb_test_schema_query_proto_msgTypes[33] ms := protoimpl.X.MessageStateOf(protoimpl.Pointer(x)) ms.StoreMessageInfo(mi) } @@ -1829,7 +2081,7 @@ func (x *ListExampleTableRequest_RangeQuery) String() string { func (*ListExampleTableRequest_RangeQuery) ProtoMessage() {} func (x *ListExampleTableRequest_RangeQuery) ProtoReflect() protoreflect.Message { - mi := &file_testpb_test_schema_query_proto_msgTypes[29] + mi := &file_testpb_test_schema_query_proto_msgTypes[33] if protoimpl.UnsafeEnabled && x != nil { ms := protoimpl.X.MessageStateOf(protoimpl.Pointer(x)) if ms.LoadMessageInfo() == nil { @@ -1878,7 +2130,7 @@ type ListExampleTableRequest_IndexKey_U32I64Str struct { func (x *ListExampleTableRequest_IndexKey_U32I64Str) Reset() { *x = ListExampleTableRequest_IndexKey_U32I64Str{} if protoimpl.UnsafeEnabled { - mi := &file_testpb_test_schema_query_proto_msgTypes[30] + mi := &file_testpb_test_schema_query_proto_msgTypes[34] ms := protoimpl.X.MessageStateOf(protoimpl.Pointer(x)) ms.StoreMessageInfo(mi) } @@ -1891,7 +2143,7 @@ func (x *ListExampleTableRequest_IndexKey_U32I64Str) String() string { func (*ListExampleTableRequest_IndexKey_U32I64Str) ProtoMessage() {} func (x *ListExampleTableRequest_IndexKey_U32I64Str) ProtoReflect() protoreflect.Message { - mi := &file_testpb_test_schema_query_proto_msgTypes[30] + mi := &file_testpb_test_schema_query_proto_msgTypes[34] if protoimpl.UnsafeEnabled && x != nil { ms := protoimpl.X.MessageStateOf(protoimpl.Pointer(x)) if ms.LoadMessageInfo() == nil { @@ -1944,7 +2196,7 @@ type ListExampleTableRequest_IndexKey_U64Str struct { func (x *ListExampleTableRequest_IndexKey_U64Str) Reset() { *x = ListExampleTableRequest_IndexKey_U64Str{} if protoimpl.UnsafeEnabled { - mi := &file_testpb_test_schema_query_proto_msgTypes[31] + mi := &file_testpb_test_schema_query_proto_msgTypes[35] ms := protoimpl.X.MessageStateOf(protoimpl.Pointer(x)) ms.StoreMessageInfo(mi) } @@ -1957,7 +2209,7 @@ func (x *ListExampleTableRequest_IndexKey_U64Str) String() string { func (*ListExampleTableRequest_IndexKey_U64Str) ProtoMessage() {} func (x *ListExampleTableRequest_IndexKey_U64Str) ProtoReflect() protoreflect.Message { - mi := &file_testpb_test_schema_query_proto_msgTypes[31] + mi := &file_testpb_test_schema_query_proto_msgTypes[35] if protoimpl.UnsafeEnabled && x != nil { ms := protoimpl.X.MessageStateOf(protoimpl.Pointer(x)) if ms.LoadMessageInfo() == nil { @@ -2003,7 +2255,7 @@ type ListExampleTableRequest_IndexKey_StrU32 struct { func (x *ListExampleTableRequest_IndexKey_StrU32) Reset() { *x = ListExampleTableRequest_IndexKey_StrU32{} if protoimpl.UnsafeEnabled { - mi := &file_testpb_test_schema_query_proto_msgTypes[32] + mi := &file_testpb_test_schema_query_proto_msgTypes[36] ms := protoimpl.X.MessageStateOf(protoimpl.Pointer(x)) ms.StoreMessageInfo(mi) } @@ -2016,7 +2268,7 @@ func (x *ListExampleTableRequest_IndexKey_StrU32) String() string { func (*ListExampleTableRequest_IndexKey_StrU32) ProtoMessage() {} func (x *ListExampleTableRequest_IndexKey_StrU32) ProtoReflect() protoreflect.Message { - mi := &file_testpb_test_schema_query_proto_msgTypes[32] + mi := &file_testpb_test_schema_query_proto_msgTypes[36] if protoimpl.UnsafeEnabled && x != nil { ms := protoimpl.X.MessageStateOf(protoimpl.Pointer(x)) if ms.LoadMessageInfo() == nil { @@ -2062,7 +2314,7 @@ type ListExampleTableRequest_IndexKey_BzStr struct { func (x *ListExampleTableRequest_IndexKey_BzStr) Reset() { *x = ListExampleTableRequest_IndexKey_BzStr{} if protoimpl.UnsafeEnabled { - mi := &file_testpb_test_schema_query_proto_msgTypes[33] + mi := &file_testpb_test_schema_query_proto_msgTypes[37] ms := protoimpl.X.MessageStateOf(protoimpl.Pointer(x)) ms.StoreMessageInfo(mi) } @@ -2075,7 +2327,7 @@ func (x *ListExampleTableRequest_IndexKey_BzStr) String() string { func (*ListExampleTableRequest_IndexKey_BzStr) ProtoMessage() {} func (x *ListExampleTableRequest_IndexKey_BzStr) ProtoReflect() protoreflect.Message { - mi := &file_testpb_test_schema_query_proto_msgTypes[33] + mi := &file_testpb_test_schema_query_proto_msgTypes[37] if protoimpl.UnsafeEnabled && x != nil { ms := protoimpl.X.MessageStateOf(protoimpl.Pointer(x)) if ms.LoadMessageInfo() == nil { @@ -2123,7 +2375,7 @@ type ListExampleAutoIncrementTableRequest_IndexKey struct { func (x *ListExampleAutoIncrementTableRequest_IndexKey) Reset() { *x = ListExampleAutoIncrementTableRequest_IndexKey{} if protoimpl.UnsafeEnabled { - mi := &file_testpb_test_schema_query_proto_msgTypes[34] + mi := &file_testpb_test_schema_query_proto_msgTypes[38] ms := protoimpl.X.MessageStateOf(protoimpl.Pointer(x)) ms.StoreMessageInfo(mi) } @@ -2136,7 +2388,7 @@ func (x *ListExampleAutoIncrementTableRequest_IndexKey) String() string { func (*ListExampleAutoIncrementTableRequest_IndexKey) ProtoMessage() {} func (x *ListExampleAutoIncrementTableRequest_IndexKey) ProtoReflect() protoreflect.Message { - mi := &file_testpb_test_schema_query_proto_msgTypes[34] + mi := &file_testpb_test_schema_query_proto_msgTypes[38] if protoimpl.UnsafeEnabled && x != nil { ms := protoimpl.X.MessageStateOf(protoimpl.Pointer(x)) if ms.LoadMessageInfo() == nil { @@ -2211,7 +2463,7 @@ type ListExampleAutoIncrementTableRequest_RangeQuery struct { func (x *ListExampleAutoIncrementTableRequest_RangeQuery) Reset() { *x = ListExampleAutoIncrementTableRequest_RangeQuery{} if protoimpl.UnsafeEnabled { - mi := &file_testpb_test_schema_query_proto_msgTypes[35] + mi := &file_testpb_test_schema_query_proto_msgTypes[39] ms := protoimpl.X.MessageStateOf(protoimpl.Pointer(x)) ms.StoreMessageInfo(mi) } @@ -2224,7 +2476,7 @@ func (x *ListExampleAutoIncrementTableRequest_RangeQuery) String() string { func (*ListExampleAutoIncrementTableRequest_RangeQuery) ProtoMessage() {} func (x *ListExampleAutoIncrementTableRequest_RangeQuery) ProtoReflect() protoreflect.Message { - mi := &file_testpb_test_schema_query_proto_msgTypes[35] + mi := &file_testpb_test_schema_query_proto_msgTypes[39] if protoimpl.UnsafeEnabled && x != nil { ms := protoimpl.X.MessageStateOf(protoimpl.Pointer(x)) if ms.LoadMessageInfo() == nil { @@ -2267,7 +2519,7 @@ type ListExampleAutoIncrementTableRequest_IndexKey_Id struct { func (x *ListExampleAutoIncrementTableRequest_IndexKey_Id) Reset() { *x = ListExampleAutoIncrementTableRequest_IndexKey_Id{} if protoimpl.UnsafeEnabled { - mi := &file_testpb_test_schema_query_proto_msgTypes[36] + mi := &file_testpb_test_schema_query_proto_msgTypes[40] ms := protoimpl.X.MessageStateOf(protoimpl.Pointer(x)) ms.StoreMessageInfo(mi) } @@ -2280,7 +2532,7 @@ func (x *ListExampleAutoIncrementTableRequest_IndexKey_Id) String() string { func (*ListExampleAutoIncrementTableRequest_IndexKey_Id) ProtoMessage() {} func (x *ListExampleAutoIncrementTableRequest_IndexKey_Id) ProtoReflect() protoreflect.Message { - mi := &file_testpb_test_schema_query_proto_msgTypes[36] + mi := &file_testpb_test_schema_query_proto_msgTypes[40] if protoimpl.UnsafeEnabled && x != nil { ms := protoimpl.X.MessageStateOf(protoimpl.Pointer(x)) if ms.LoadMessageInfo() == nil { @@ -2316,7 +2568,7 @@ type ListExampleAutoIncrementTableRequest_IndexKey_X struct { func (x *ListExampleAutoIncrementTableRequest_IndexKey_X) Reset() { *x = ListExampleAutoIncrementTableRequest_IndexKey_X{} if protoimpl.UnsafeEnabled { - mi := &file_testpb_test_schema_query_proto_msgTypes[37] + mi := &file_testpb_test_schema_query_proto_msgTypes[41] ms := protoimpl.X.MessageStateOf(protoimpl.Pointer(x)) ms.StoreMessageInfo(mi) } @@ -2329,7 +2581,7 @@ func (x *ListExampleAutoIncrementTableRequest_IndexKey_X) String() string { func (*ListExampleAutoIncrementTableRequest_IndexKey_X) ProtoMessage() {} func (x *ListExampleAutoIncrementTableRequest_IndexKey_X) ProtoReflect() protoreflect.Message { - mi := &file_testpb_test_schema_query_proto_msgTypes[37] + mi := &file_testpb_test_schema_query_proto_msgTypes[41] if protoimpl.UnsafeEnabled && x != nil { ms := protoimpl.X.MessageStateOf(protoimpl.Pointer(x)) if ms.LoadMessageInfo() == nil { @@ -2370,7 +2622,7 @@ type ListExampleTimestampRequest_IndexKey struct { func (x *ListExampleTimestampRequest_IndexKey) Reset() { *x = ListExampleTimestampRequest_IndexKey{} if protoimpl.UnsafeEnabled { - mi := &file_testpb_test_schema_query_proto_msgTypes[38] + mi := &file_testpb_test_schema_query_proto_msgTypes[42] ms := protoimpl.X.MessageStateOf(protoimpl.Pointer(x)) ms.StoreMessageInfo(mi) } @@ -2383,7 +2635,7 @@ func (x *ListExampleTimestampRequest_IndexKey) String() string { func (*ListExampleTimestampRequest_IndexKey) ProtoMessage() {} func (x *ListExampleTimestampRequest_IndexKey) ProtoReflect() protoreflect.Message { - mi := &file_testpb_test_schema_query_proto_msgTypes[38] + mi := &file_testpb_test_schema_query_proto_msgTypes[42] if protoimpl.UnsafeEnabled && x != nil { ms := protoimpl.X.MessageStateOf(protoimpl.Pointer(x)) if ms.LoadMessageInfo() == nil { @@ -2456,7 +2708,7 @@ type ListExampleTimestampRequest_RangeQuery struct { func (x *ListExampleTimestampRequest_RangeQuery) Reset() { *x = ListExampleTimestampRequest_RangeQuery{} if protoimpl.UnsafeEnabled { - mi := &file_testpb_test_schema_query_proto_msgTypes[39] + mi := &file_testpb_test_schema_query_proto_msgTypes[43] ms := protoimpl.X.MessageStateOf(protoimpl.Pointer(x)) ms.StoreMessageInfo(mi) } @@ -2469,7 +2721,7 @@ func (x *ListExampleTimestampRequest_RangeQuery) String() string { func (*ListExampleTimestampRequest_RangeQuery) ProtoMessage() {} func (x *ListExampleTimestampRequest_RangeQuery) ProtoReflect() protoreflect.Message { - mi := &file_testpb_test_schema_query_proto_msgTypes[39] + mi := &file_testpb_test_schema_query_proto_msgTypes[43] if protoimpl.UnsafeEnabled && x != nil { ms := protoimpl.X.MessageStateOf(protoimpl.Pointer(x)) if ms.LoadMessageInfo() == nil { @@ -2512,20 +2764,265 @@ type ListExampleTimestampRequest_IndexKey_Id struct { func (x *ListExampleTimestampRequest_IndexKey_Id) Reset() { *x = ListExampleTimestampRequest_IndexKey_Id{} if protoimpl.UnsafeEnabled { - mi := &file_testpb_test_schema_query_proto_msgTypes[40] + mi := &file_testpb_test_schema_query_proto_msgTypes[44] + ms := protoimpl.X.MessageStateOf(protoimpl.Pointer(x)) + ms.StoreMessageInfo(mi) + } +} + +func (x *ListExampleTimestampRequest_IndexKey_Id) String() string { + return protoimpl.X.MessageStringOf(x) +} + +func (*ListExampleTimestampRequest_IndexKey_Id) ProtoMessage() {} + +func (x *ListExampleTimestampRequest_IndexKey_Id) ProtoReflect() protoreflect.Message { + mi := &file_testpb_test_schema_query_proto_msgTypes[44] + if protoimpl.UnsafeEnabled && x != nil { + ms := protoimpl.X.MessageStateOf(protoimpl.Pointer(x)) + if ms.LoadMessageInfo() == nil { + ms.StoreMessageInfo(mi) + } + return ms + } + return mi.MessageOf(x) +} + +// Deprecated: Use ListExampleTimestampRequest_IndexKey_Id.ProtoReflect.Descriptor instead. +func (*ListExampleTimestampRequest_IndexKey_Id) Descriptor() ([]byte, []int) { + return file_testpb_test_schema_query_proto_rawDescGZIP(), []int{16, 0, 0} +} + +func (x *ListExampleTimestampRequest_IndexKey_Id) GetId() uint64 { + if x != nil && x.Id != nil { + return *x.Id + } + return 0 +} + +type ListExampleTimestampRequest_IndexKey_Ts struct { + state protoimpl.MessageState + sizeCache protoimpl.SizeCache + unknownFields protoimpl.UnknownFields + + // ts is the value of the ts field in the index. + // It can be omitted to query for all valid values of that field in this segment of the index. + Ts *timestamppb.Timestamp `protobuf:"bytes,1,opt,name=ts,proto3,oneof" json:"ts,omitempty"` +} + +func (x *ListExampleTimestampRequest_IndexKey_Ts) Reset() { + *x = ListExampleTimestampRequest_IndexKey_Ts{} + if protoimpl.UnsafeEnabled { + mi := &file_testpb_test_schema_query_proto_msgTypes[45] + ms := protoimpl.X.MessageStateOf(protoimpl.Pointer(x)) + ms.StoreMessageInfo(mi) + } +} + +func (x *ListExampleTimestampRequest_IndexKey_Ts) String() string { + return protoimpl.X.MessageStringOf(x) +} + +func (*ListExampleTimestampRequest_IndexKey_Ts) ProtoMessage() {} + +func (x *ListExampleTimestampRequest_IndexKey_Ts) ProtoReflect() protoreflect.Message { + mi := &file_testpb_test_schema_query_proto_msgTypes[45] + if protoimpl.UnsafeEnabled && x != nil { + ms := protoimpl.X.MessageStateOf(protoimpl.Pointer(x)) + if ms.LoadMessageInfo() == nil { + ms.StoreMessageInfo(mi) + } + return ms + } + return mi.MessageOf(x) +} + +// Deprecated: Use ListExampleTimestampRequest_IndexKey_Ts.ProtoReflect.Descriptor instead. +func (*ListExampleTimestampRequest_IndexKey_Ts) Descriptor() ([]byte, []int) { + return file_testpb_test_schema_query_proto_rawDescGZIP(), []int{16, 0, 1} +} + +func (x *ListExampleTimestampRequest_IndexKey_Ts) GetTs() *timestamppb.Timestamp { + if x != nil { + return x.Ts + } + return nil +} + +// IndexKey specifies the value of an index key to use in prefix and range queries. +type ListExampleDurationRequest_IndexKey struct { + state protoimpl.MessageState + sizeCache protoimpl.SizeCache + unknownFields protoimpl.UnknownFields + + // key specifies the index key value. + // + // Types that are assignable to Key: + // + // *ListExampleDurationRequest_IndexKey_Id_ + // *ListExampleDurationRequest_IndexKey_Dur_ + Key isListExampleDurationRequest_IndexKey_Key `protobuf_oneof:"key"` +} + +func (x *ListExampleDurationRequest_IndexKey) Reset() { + *x = ListExampleDurationRequest_IndexKey{} + if protoimpl.UnsafeEnabled { + mi := &file_testpb_test_schema_query_proto_msgTypes[46] + ms := protoimpl.X.MessageStateOf(protoimpl.Pointer(x)) + ms.StoreMessageInfo(mi) + } +} + +func (x *ListExampleDurationRequest_IndexKey) String() string { + return protoimpl.X.MessageStringOf(x) +} + +func (*ListExampleDurationRequest_IndexKey) ProtoMessage() {} + +func (x *ListExampleDurationRequest_IndexKey) ProtoReflect() protoreflect.Message { + mi := &file_testpb_test_schema_query_proto_msgTypes[46] + if protoimpl.UnsafeEnabled && x != nil { + ms := protoimpl.X.MessageStateOf(protoimpl.Pointer(x)) + if ms.LoadMessageInfo() == nil { + ms.StoreMessageInfo(mi) + } + return ms + } + return mi.MessageOf(x) +} + +// Deprecated: Use ListExampleDurationRequest_IndexKey.ProtoReflect.Descriptor instead. +func (*ListExampleDurationRequest_IndexKey) Descriptor() ([]byte, []int) { + return file_testpb_test_schema_query_proto_rawDescGZIP(), []int{20, 0} +} + +func (m *ListExampleDurationRequest_IndexKey) GetKey() isListExampleDurationRequest_IndexKey_Key { + if m != nil { + return m.Key + } + return nil +} + +func (x *ListExampleDurationRequest_IndexKey) GetId() *ListExampleDurationRequest_IndexKey_Id { + if x, ok := x.GetKey().(*ListExampleDurationRequest_IndexKey_Id_); ok { + return x.Id + } + return nil +} + +func (x *ListExampleDurationRequest_IndexKey) GetDur() *ListExampleDurationRequest_IndexKey_Dur { + if x, ok := x.GetKey().(*ListExampleDurationRequest_IndexKey_Dur_); ok { + return x.Dur + } + return nil +} + +type isListExampleDurationRequest_IndexKey_Key interface { + isListExampleDurationRequest_IndexKey_Key() +} + +type ListExampleDurationRequest_IndexKey_Id_ struct { + // id specifies the value of the Id index key to use in the query. + Id *ListExampleDurationRequest_IndexKey_Id `protobuf:"bytes,1,opt,name=id,proto3,oneof"` +} + +type ListExampleDurationRequest_IndexKey_Dur_ struct { + // dur specifies the value of the Dur index key to use in the query. + Dur *ListExampleDurationRequest_IndexKey_Dur `protobuf:"bytes,2,opt,name=dur,proto3,oneof"` +} + +func (*ListExampleDurationRequest_IndexKey_Id_) isListExampleDurationRequest_IndexKey_Key() {} + +func (*ListExampleDurationRequest_IndexKey_Dur_) isListExampleDurationRequest_IndexKey_Key() {} + +// RangeQuery specifies the from/to index keys for a range query. +type ListExampleDurationRequest_RangeQuery struct { + state protoimpl.MessageState + sizeCache protoimpl.SizeCache + unknownFields protoimpl.UnknownFields + + // from is the index key to use for the start of the range query. + // To query from the start of an index, specify an index key for that index with empty values. + From *ListExampleDurationRequest_IndexKey `protobuf:"bytes,1,opt,name=from,proto3" json:"from,omitempty"` + // to is the index key to use for the end of the range query. + // The index key type MUST be the same as the index key type used for from. + // To query from to the end of an index it can be omitted. + To *ListExampleDurationRequest_IndexKey `protobuf:"bytes,2,opt,name=to,proto3" json:"to,omitempty"` +} + +func (x *ListExampleDurationRequest_RangeQuery) Reset() { + *x = ListExampleDurationRequest_RangeQuery{} + if protoimpl.UnsafeEnabled { + mi := &file_testpb_test_schema_query_proto_msgTypes[47] + ms := protoimpl.X.MessageStateOf(protoimpl.Pointer(x)) + ms.StoreMessageInfo(mi) + } +} + +func (x *ListExampleDurationRequest_RangeQuery) String() string { + return protoimpl.X.MessageStringOf(x) +} + +func (*ListExampleDurationRequest_RangeQuery) ProtoMessage() {} + +func (x *ListExampleDurationRequest_RangeQuery) ProtoReflect() protoreflect.Message { + mi := &file_testpb_test_schema_query_proto_msgTypes[47] + if protoimpl.UnsafeEnabled && x != nil { + ms := protoimpl.X.MessageStateOf(protoimpl.Pointer(x)) + if ms.LoadMessageInfo() == nil { + ms.StoreMessageInfo(mi) + } + return ms + } + return mi.MessageOf(x) +} + +// Deprecated: Use ListExampleDurationRequest_RangeQuery.ProtoReflect.Descriptor instead. +func (*ListExampleDurationRequest_RangeQuery) Descriptor() ([]byte, []int) { + return file_testpb_test_schema_query_proto_rawDescGZIP(), []int{20, 1} +} + +func (x *ListExampleDurationRequest_RangeQuery) GetFrom() *ListExampleDurationRequest_IndexKey { + if x != nil { + return x.From + } + return nil +} + +func (x *ListExampleDurationRequest_RangeQuery) GetTo() *ListExampleDurationRequest_IndexKey { + if x != nil { + return x.To + } + return nil +} + +type ListExampleDurationRequest_IndexKey_Id struct { + state protoimpl.MessageState + sizeCache protoimpl.SizeCache + unknownFields protoimpl.UnknownFields + + // id is the value of the id field in the index. + // It can be omitted to query for all valid values of that field in this segment of the index. + Id *uint64 `protobuf:"varint,1,opt,name=id,proto3,oneof" json:"id,omitempty"` +} + +func (x *ListExampleDurationRequest_IndexKey_Id) Reset() { + *x = ListExampleDurationRequest_IndexKey_Id{} + if protoimpl.UnsafeEnabled { + mi := &file_testpb_test_schema_query_proto_msgTypes[48] ms := protoimpl.X.MessageStateOf(protoimpl.Pointer(x)) ms.StoreMessageInfo(mi) } } -func (x *ListExampleTimestampRequest_IndexKey_Id) String() string { +func (x *ListExampleDurationRequest_IndexKey_Id) String() string { return protoimpl.X.MessageStringOf(x) } -func (*ListExampleTimestampRequest_IndexKey_Id) ProtoMessage() {} +func (*ListExampleDurationRequest_IndexKey_Id) ProtoMessage() {} -func (x *ListExampleTimestampRequest_IndexKey_Id) ProtoReflect() protoreflect.Message { - mi := &file_testpb_test_schema_query_proto_msgTypes[40] +func (x *ListExampleDurationRequest_IndexKey_Id) ProtoReflect() protoreflect.Message { + mi := &file_testpb_test_schema_query_proto_msgTypes[48] if protoimpl.UnsafeEnabled && x != nil { ms := protoimpl.X.MessageStateOf(protoimpl.Pointer(x)) if ms.LoadMessageInfo() == nil { @@ -2536,45 +3033,45 @@ func (x *ListExampleTimestampRequest_IndexKey_Id) ProtoReflect() protoreflect.Me return mi.MessageOf(x) } -// Deprecated: Use ListExampleTimestampRequest_IndexKey_Id.ProtoReflect.Descriptor instead. -func (*ListExampleTimestampRequest_IndexKey_Id) Descriptor() ([]byte, []int) { - return file_testpb_test_schema_query_proto_rawDescGZIP(), []int{16, 0, 0} +// Deprecated: Use ListExampleDurationRequest_IndexKey_Id.ProtoReflect.Descriptor instead. +func (*ListExampleDurationRequest_IndexKey_Id) Descriptor() ([]byte, []int) { + return file_testpb_test_schema_query_proto_rawDescGZIP(), []int{20, 0, 0} } -func (x *ListExampleTimestampRequest_IndexKey_Id) GetId() uint64 { +func (x *ListExampleDurationRequest_IndexKey_Id) GetId() uint64 { if x != nil && x.Id != nil { return *x.Id } return 0 } -type ListExampleTimestampRequest_IndexKey_Ts struct { +type ListExampleDurationRequest_IndexKey_Dur struct { state protoimpl.MessageState sizeCache protoimpl.SizeCache unknownFields protoimpl.UnknownFields - // ts is the value of the ts field in the index. + // dur is the value of the dur field in the index. // It can be omitted to query for all valid values of that field in this segment of the index. - Ts *timestamppb.Timestamp `protobuf:"bytes,1,opt,name=ts,proto3,oneof" json:"ts,omitempty"` + Dur *durationpb.Duration `protobuf:"bytes,1,opt,name=dur,proto3,oneof" json:"dur,omitempty"` } -func (x *ListExampleTimestampRequest_IndexKey_Ts) Reset() { - *x = ListExampleTimestampRequest_IndexKey_Ts{} +func (x *ListExampleDurationRequest_IndexKey_Dur) Reset() { + *x = ListExampleDurationRequest_IndexKey_Dur{} if protoimpl.UnsafeEnabled { - mi := &file_testpb_test_schema_query_proto_msgTypes[41] + mi := &file_testpb_test_schema_query_proto_msgTypes[49] ms := protoimpl.X.MessageStateOf(protoimpl.Pointer(x)) ms.StoreMessageInfo(mi) } } -func (x *ListExampleTimestampRequest_IndexKey_Ts) String() string { +func (x *ListExampleDurationRequest_IndexKey_Dur) String() string { return protoimpl.X.MessageStringOf(x) } -func (*ListExampleTimestampRequest_IndexKey_Ts) ProtoMessage() {} +func (*ListExampleDurationRequest_IndexKey_Dur) ProtoMessage() {} -func (x *ListExampleTimestampRequest_IndexKey_Ts) ProtoReflect() protoreflect.Message { - mi := &file_testpb_test_schema_query_proto_msgTypes[41] +func (x *ListExampleDurationRequest_IndexKey_Dur) ProtoReflect() protoreflect.Message { + mi := &file_testpb_test_schema_query_proto_msgTypes[49] if protoimpl.UnsafeEnabled && x != nil { ms := protoimpl.X.MessageStateOf(protoimpl.Pointer(x)) if ms.LoadMessageInfo() == nil { @@ -2585,14 +3082,14 @@ func (x *ListExampleTimestampRequest_IndexKey_Ts) ProtoReflect() protoreflect.Me return mi.MessageOf(x) } -// Deprecated: Use ListExampleTimestampRequest_IndexKey_Ts.ProtoReflect.Descriptor instead. -func (*ListExampleTimestampRequest_IndexKey_Ts) Descriptor() ([]byte, []int) { - return file_testpb_test_schema_query_proto_rawDescGZIP(), []int{16, 0, 1} +// Deprecated: Use ListExampleDurationRequest_IndexKey_Dur.ProtoReflect.Descriptor instead. +func (*ListExampleDurationRequest_IndexKey_Dur) Descriptor() ([]byte, []int) { + return file_testpb_test_schema_query_proto_rawDescGZIP(), []int{20, 0, 1} } -func (x *ListExampleTimestampRequest_IndexKey_Ts) GetTs() *timestamppb.Timestamp { +func (x *ListExampleDurationRequest_IndexKey_Dur) GetDur() *durationpb.Duration { if x != nil { - return x.Ts + return x.Dur } return nil } @@ -2615,7 +3112,7 @@ type ListSimpleExampleRequest_IndexKey struct { func (x *ListSimpleExampleRequest_IndexKey) Reset() { *x = ListSimpleExampleRequest_IndexKey{} if protoimpl.UnsafeEnabled { - mi := &file_testpb_test_schema_query_proto_msgTypes[42] + mi := &file_testpb_test_schema_query_proto_msgTypes[50] ms := protoimpl.X.MessageStateOf(protoimpl.Pointer(x)) ms.StoreMessageInfo(mi) } @@ -2628,7 +3125,7 @@ func (x *ListSimpleExampleRequest_IndexKey) String() string { func (*ListSimpleExampleRequest_IndexKey) ProtoMessage() {} func (x *ListSimpleExampleRequest_IndexKey) ProtoReflect() protoreflect.Message { - mi := &file_testpb_test_schema_query_proto_msgTypes[42] + mi := &file_testpb_test_schema_query_proto_msgTypes[50] if protoimpl.UnsafeEnabled && x != nil { ms := protoimpl.X.MessageStateOf(protoimpl.Pointer(x)) if ms.LoadMessageInfo() == nil { @@ -2641,7 +3138,7 @@ func (x *ListSimpleExampleRequest_IndexKey) ProtoReflect() protoreflect.Message // Deprecated: Use ListSimpleExampleRequest_IndexKey.ProtoReflect.Descriptor instead. func (*ListSimpleExampleRequest_IndexKey) Descriptor() ([]byte, []int) { - return file_testpb_test_schema_query_proto_rawDescGZIP(), []int{22, 0} + return file_testpb_test_schema_query_proto_rawDescGZIP(), []int{26, 0} } func (m *ListSimpleExampleRequest_IndexKey) GetKey() isListSimpleExampleRequest_IndexKey_Key { @@ -2701,7 +3198,7 @@ type ListSimpleExampleRequest_RangeQuery struct { func (x *ListSimpleExampleRequest_RangeQuery) Reset() { *x = ListSimpleExampleRequest_RangeQuery{} if protoimpl.UnsafeEnabled { - mi := &file_testpb_test_schema_query_proto_msgTypes[43] + mi := &file_testpb_test_schema_query_proto_msgTypes[51] ms := protoimpl.X.MessageStateOf(protoimpl.Pointer(x)) ms.StoreMessageInfo(mi) } @@ -2714,7 +3211,7 @@ func (x *ListSimpleExampleRequest_RangeQuery) String() string { func (*ListSimpleExampleRequest_RangeQuery) ProtoMessage() {} func (x *ListSimpleExampleRequest_RangeQuery) ProtoReflect() protoreflect.Message { - mi := &file_testpb_test_schema_query_proto_msgTypes[43] + mi := &file_testpb_test_schema_query_proto_msgTypes[51] if protoimpl.UnsafeEnabled && x != nil { ms := protoimpl.X.MessageStateOf(protoimpl.Pointer(x)) if ms.LoadMessageInfo() == nil { @@ -2727,7 +3224,7 @@ func (x *ListSimpleExampleRequest_RangeQuery) ProtoReflect() protoreflect.Messag // Deprecated: Use ListSimpleExampleRequest_RangeQuery.ProtoReflect.Descriptor instead. func (*ListSimpleExampleRequest_RangeQuery) Descriptor() ([]byte, []int) { - return file_testpb_test_schema_query_proto_rawDescGZIP(), []int{22, 1} + return file_testpb_test_schema_query_proto_rawDescGZIP(), []int{26, 1} } func (x *ListSimpleExampleRequest_RangeQuery) GetFrom() *ListSimpleExampleRequest_IndexKey { @@ -2757,7 +3254,7 @@ type ListSimpleExampleRequest_IndexKey_Name struct { func (x *ListSimpleExampleRequest_IndexKey_Name) Reset() { *x = ListSimpleExampleRequest_IndexKey_Name{} if protoimpl.UnsafeEnabled { - mi := &file_testpb_test_schema_query_proto_msgTypes[44] + mi := &file_testpb_test_schema_query_proto_msgTypes[52] ms := protoimpl.X.MessageStateOf(protoimpl.Pointer(x)) ms.StoreMessageInfo(mi) } @@ -2770,7 +3267,7 @@ func (x *ListSimpleExampleRequest_IndexKey_Name) String() string { func (*ListSimpleExampleRequest_IndexKey_Name) ProtoMessage() {} func (x *ListSimpleExampleRequest_IndexKey_Name) ProtoReflect() protoreflect.Message { - mi := &file_testpb_test_schema_query_proto_msgTypes[44] + mi := &file_testpb_test_schema_query_proto_msgTypes[52] if protoimpl.UnsafeEnabled && x != nil { ms := protoimpl.X.MessageStateOf(protoimpl.Pointer(x)) if ms.LoadMessageInfo() == nil { @@ -2783,7 +3280,7 @@ func (x *ListSimpleExampleRequest_IndexKey_Name) ProtoReflect() protoreflect.Mes // Deprecated: Use ListSimpleExampleRequest_IndexKey_Name.ProtoReflect.Descriptor instead. func (*ListSimpleExampleRequest_IndexKey_Name) Descriptor() ([]byte, []int) { - return file_testpb_test_schema_query_proto_rawDescGZIP(), []int{22, 0, 0} + return file_testpb_test_schema_query_proto_rawDescGZIP(), []int{26, 0, 0} } func (x *ListSimpleExampleRequest_IndexKey_Name) GetName() string { @@ -2806,7 +3303,7 @@ type ListSimpleExampleRequest_IndexKey_Unique struct { func (x *ListSimpleExampleRequest_IndexKey_Unique) Reset() { *x = ListSimpleExampleRequest_IndexKey_Unique{} if protoimpl.UnsafeEnabled { - mi := &file_testpb_test_schema_query_proto_msgTypes[45] + mi := &file_testpb_test_schema_query_proto_msgTypes[53] ms := protoimpl.X.MessageStateOf(protoimpl.Pointer(x)) ms.StoreMessageInfo(mi) } @@ -2819,7 +3316,7 @@ func (x *ListSimpleExampleRequest_IndexKey_Unique) String() string { func (*ListSimpleExampleRequest_IndexKey_Unique) ProtoMessage() {} func (x *ListSimpleExampleRequest_IndexKey_Unique) ProtoReflect() protoreflect.Message { - mi := &file_testpb_test_schema_query_proto_msgTypes[45] + mi := &file_testpb_test_schema_query_proto_msgTypes[53] if protoimpl.UnsafeEnabled && x != nil { ms := protoimpl.X.MessageStateOf(protoimpl.Pointer(x)) if ms.LoadMessageInfo() == nil { @@ -2832,7 +3329,7 @@ func (x *ListSimpleExampleRequest_IndexKey_Unique) ProtoReflect() protoreflect.M // Deprecated: Use ListSimpleExampleRequest_IndexKey_Unique.ProtoReflect.Descriptor instead. func (*ListSimpleExampleRequest_IndexKey_Unique) Descriptor() ([]byte, []int) { - return file_testpb_test_schema_query_proto_rawDescGZIP(), []int{22, 0, 1} + return file_testpb_test_schema_query_proto_rawDescGZIP(), []int{26, 0, 1} } func (x *ListSimpleExampleRequest_IndexKey_Unique) GetUnique() string { @@ -2859,7 +3356,7 @@ type ListExampleAutoIncFieldNameRequest_IndexKey struct { func (x *ListExampleAutoIncFieldNameRequest_IndexKey) Reset() { *x = ListExampleAutoIncFieldNameRequest_IndexKey{} if protoimpl.UnsafeEnabled { - mi := &file_testpb_test_schema_query_proto_msgTypes[46] + mi := &file_testpb_test_schema_query_proto_msgTypes[54] ms := protoimpl.X.MessageStateOf(protoimpl.Pointer(x)) ms.StoreMessageInfo(mi) } @@ -2872,7 +3369,7 @@ func (x *ListExampleAutoIncFieldNameRequest_IndexKey) String() string { func (*ListExampleAutoIncFieldNameRequest_IndexKey) ProtoMessage() {} func (x *ListExampleAutoIncFieldNameRequest_IndexKey) ProtoReflect() protoreflect.Message { - mi := &file_testpb_test_schema_query_proto_msgTypes[46] + mi := &file_testpb_test_schema_query_proto_msgTypes[54] if protoimpl.UnsafeEnabled && x != nil { ms := protoimpl.X.MessageStateOf(protoimpl.Pointer(x)) if ms.LoadMessageInfo() == nil { @@ -2885,7 +3382,7 @@ func (x *ListExampleAutoIncFieldNameRequest_IndexKey) ProtoReflect() protoreflec // Deprecated: Use ListExampleAutoIncFieldNameRequest_IndexKey.ProtoReflect.Descriptor instead. func (*ListExampleAutoIncFieldNameRequest_IndexKey) Descriptor() ([]byte, []int) { - return file_testpb_test_schema_query_proto_rawDescGZIP(), []int{26, 0} + return file_testpb_test_schema_query_proto_rawDescGZIP(), []int{30, 0} } func (m *ListExampleAutoIncFieldNameRequest_IndexKey) GetKey() isListExampleAutoIncFieldNameRequest_IndexKey_Key { @@ -2932,7 +3429,7 @@ type ListExampleAutoIncFieldNameRequest_RangeQuery struct { func (x *ListExampleAutoIncFieldNameRequest_RangeQuery) Reset() { *x = ListExampleAutoIncFieldNameRequest_RangeQuery{} if protoimpl.UnsafeEnabled { - mi := &file_testpb_test_schema_query_proto_msgTypes[47] + mi := &file_testpb_test_schema_query_proto_msgTypes[55] ms := protoimpl.X.MessageStateOf(protoimpl.Pointer(x)) ms.StoreMessageInfo(mi) } @@ -2945,7 +3442,7 @@ func (x *ListExampleAutoIncFieldNameRequest_RangeQuery) String() string { func (*ListExampleAutoIncFieldNameRequest_RangeQuery) ProtoMessage() {} func (x *ListExampleAutoIncFieldNameRequest_RangeQuery) ProtoReflect() protoreflect.Message { - mi := &file_testpb_test_schema_query_proto_msgTypes[47] + mi := &file_testpb_test_schema_query_proto_msgTypes[55] if protoimpl.UnsafeEnabled && x != nil { ms := protoimpl.X.MessageStateOf(protoimpl.Pointer(x)) if ms.LoadMessageInfo() == nil { @@ -2958,7 +3455,7 @@ func (x *ListExampleAutoIncFieldNameRequest_RangeQuery) ProtoReflect() protorefl // Deprecated: Use ListExampleAutoIncFieldNameRequest_RangeQuery.ProtoReflect.Descriptor instead. func (*ListExampleAutoIncFieldNameRequest_RangeQuery) Descriptor() ([]byte, []int) { - return file_testpb_test_schema_query_proto_rawDescGZIP(), []int{26, 1} + return file_testpb_test_schema_query_proto_rawDescGZIP(), []int{30, 1} } func (x *ListExampleAutoIncFieldNameRequest_RangeQuery) GetFrom() *ListExampleAutoIncFieldNameRequest_IndexKey { @@ -2988,7 +3485,7 @@ type ListExampleAutoIncFieldNameRequest_IndexKey_Foo struct { func (x *ListExampleAutoIncFieldNameRequest_IndexKey_Foo) Reset() { *x = ListExampleAutoIncFieldNameRequest_IndexKey_Foo{} if protoimpl.UnsafeEnabled { - mi := &file_testpb_test_schema_query_proto_msgTypes[48] + mi := &file_testpb_test_schema_query_proto_msgTypes[56] ms := protoimpl.X.MessageStateOf(protoimpl.Pointer(x)) ms.StoreMessageInfo(mi) } @@ -3001,7 +3498,7 @@ func (x *ListExampleAutoIncFieldNameRequest_IndexKey_Foo) String() string { func (*ListExampleAutoIncFieldNameRequest_IndexKey_Foo) ProtoMessage() {} func (x *ListExampleAutoIncFieldNameRequest_IndexKey_Foo) ProtoReflect() protoreflect.Message { - mi := &file_testpb_test_schema_query_proto_msgTypes[48] + mi := &file_testpb_test_schema_query_proto_msgTypes[56] if protoimpl.UnsafeEnabled && x != nil { ms := protoimpl.X.MessageStateOf(protoimpl.Pointer(x)) if ms.LoadMessageInfo() == nil { @@ -3014,7 +3511,7 @@ func (x *ListExampleAutoIncFieldNameRequest_IndexKey_Foo) ProtoReflect() protore // Deprecated: Use ListExampleAutoIncFieldNameRequest_IndexKey_Foo.ProtoReflect.Descriptor instead. func (*ListExampleAutoIncFieldNameRequest_IndexKey_Foo) Descriptor() ([]byte, []int) { - return file_testpb_test_schema_query_proto_rawDescGZIP(), []int{26, 0, 0} + return file_testpb_test_schema_query_proto_rawDescGZIP(), []int{30, 0, 0} } func (x *ListExampleAutoIncFieldNameRequest_IndexKey_Foo) GetFoo() uint64 { @@ -3032,6 +3529,8 @@ var file_testpb_test_schema_query_proto_rawDesc = []byte{ 0x12, 0x06, 0x74, 0x65, 0x73, 0x74, 0x70, 0x62, 0x1a, 0x2a, 0x63, 0x6f, 0x73, 0x6d, 0x6f, 0x73, 0x2f, 0x62, 0x61, 0x73, 0x65, 0x2f, 0x71, 0x75, 0x65, 0x72, 0x79, 0x2f, 0x76, 0x31, 0x62, 0x65, 0x74, 0x61, 0x31, 0x2f, 0x70, 0x61, 0x67, 0x69, 0x6e, 0x61, 0x74, 0x69, 0x6f, 0x6e, 0x2e, 0x70, + 0x72, 0x6f, 0x74, 0x6f, 0x1a, 0x1e, 0x67, 0x6f, 0x6f, 0x67, 0x6c, 0x65, 0x2f, 0x70, 0x72, 0x6f, + 0x74, 0x6f, 0x62, 0x75, 0x66, 0x2f, 0x64, 0x75, 0x72, 0x61, 0x74, 0x69, 0x6f, 0x6e, 0x2e, 0x70, 0x72, 0x6f, 0x74, 0x6f, 0x1a, 0x1f, 0x67, 0x6f, 0x6f, 0x67, 0x6c, 0x65, 0x2f, 0x70, 0x72, 0x6f, 0x74, 0x6f, 0x62, 0x75, 0x66, 0x2f, 0x74, 0x69, 0x6d, 0x65, 0x73, 0x74, 0x61, 0x6d, 0x70, 0x2e, 0x70, 0x72, 0x6f, 0x74, 0x6f, 0x1a, 0x18, 0x74, 0x65, 0x73, 0x74, 0x70, 0x62, 0x2f, 0x74, 0x65, @@ -3270,236 +3769,306 @@ var file_testpb_test_schema_query_proto_rawDesc = []byte{ 0x63, 0x6f, 0x73, 0x6d, 0x6f, 0x73, 0x2e, 0x62, 0x61, 0x73, 0x65, 0x2e, 0x71, 0x75, 0x65, 0x72, 0x79, 0x2e, 0x76, 0x31, 0x62, 0x65, 0x74, 0x61, 0x31, 0x2e, 0x50, 0x61, 0x67, 0x65, 0x52, 0x65, 0x73, 0x70, 0x6f, 0x6e, 0x73, 0x65, 0x52, 0x0a, 0x70, 0x61, 0x67, 0x69, 0x6e, 0x61, 0x74, 0x69, - 0x6f, 0x6e, 0x22, 0x2d, 0x0a, 0x17, 0x47, 0x65, 0x74, 0x53, 0x69, 0x6d, 0x70, 0x6c, 0x65, 0x45, - 0x78, 0x61, 0x6d, 0x70, 0x6c, 0x65, 0x52, 0x65, 0x71, 0x75, 0x65, 0x73, 0x74, 0x12, 0x12, 0x0a, - 0x04, 0x6e, 0x61, 0x6d, 0x65, 0x18, 0x01, 0x20, 0x01, 0x28, 0x09, 0x52, 0x04, 0x6e, 0x61, 0x6d, - 0x65, 0x22, 0x47, 0x0a, 0x18, 0x47, 0x65, 0x74, 0x53, 0x69, 0x6d, 0x70, 0x6c, 0x65, 0x45, 0x78, - 0x61, 0x6d, 0x70, 0x6c, 0x65, 0x52, 0x65, 0x73, 0x70, 0x6f, 0x6e, 0x73, 0x65, 0x12, 0x2b, 0x0a, - 0x05, 0x76, 0x61, 0x6c, 0x75, 0x65, 0x18, 0x01, 0x20, 0x01, 0x28, 0x0b, 0x32, 0x15, 0x2e, 0x74, - 0x65, 0x73, 0x74, 0x70, 0x62, 0x2e, 0x53, 0x69, 0x6d, 0x70, 0x6c, 0x65, 0x45, 0x78, 0x61, 0x6d, - 0x70, 0x6c, 0x65, 0x52, 0x05, 0x76, 0x61, 0x6c, 0x75, 0x65, 0x22, 0x39, 0x0a, 0x1f, 0x47, 0x65, - 0x74, 0x53, 0x69, 0x6d, 0x70, 0x6c, 0x65, 0x45, 0x78, 0x61, 0x6d, 0x70, 0x6c, 0x65, 0x42, 0x79, - 0x55, 0x6e, 0x69, 0x71, 0x75, 0x65, 0x52, 0x65, 0x71, 0x75, 0x65, 0x73, 0x74, 0x12, 0x16, 0x0a, - 0x06, 0x75, 0x6e, 0x69, 0x71, 0x75, 0x65, 0x18, 0x01, 0x20, 0x01, 0x28, 0x09, 0x52, 0x06, 0x75, - 0x6e, 0x69, 0x71, 0x75, 0x65, 0x22, 0x4f, 0x0a, 0x20, 0x47, 0x65, 0x74, 0x53, 0x69, 0x6d, 0x70, - 0x6c, 0x65, 0x45, 0x78, 0x61, 0x6d, 0x70, 0x6c, 0x65, 0x42, 0x79, 0x55, 0x6e, 0x69, 0x71, 0x75, - 0x65, 0x52, 0x65, 0x73, 0x70, 0x6f, 0x6e, 0x73, 0x65, 0x12, 0x2b, 0x0a, 0x05, 0x76, 0x61, 0x6c, - 0x75, 0x65, 0x18, 0x01, 0x20, 0x01, 0x28, 0x0b, 0x32, 0x15, 0x2e, 0x74, 0x65, 0x73, 0x74, 0x70, - 0x62, 0x2e, 0x53, 0x69, 0x6d, 0x70, 0x6c, 0x65, 0x45, 0x78, 0x61, 0x6d, 0x70, 0x6c, 0x65, 0x52, - 0x05, 0x76, 0x61, 0x6c, 0x75, 0x65, 0x22, 0x96, 0x05, 0x0a, 0x18, 0x4c, 0x69, 0x73, 0x74, 0x53, - 0x69, 0x6d, 0x70, 0x6c, 0x65, 0x45, 0x78, 0x61, 0x6d, 0x70, 0x6c, 0x65, 0x52, 0x65, 0x71, 0x75, - 0x65, 0x73, 0x74, 0x12, 0x4e, 0x0a, 0x0c, 0x70, 0x72, 0x65, 0x66, 0x69, 0x78, 0x5f, 0x71, 0x75, - 0x65, 0x72, 0x79, 0x18, 0x01, 0x20, 0x01, 0x28, 0x0b, 0x32, 0x29, 0x2e, 0x74, 0x65, 0x73, 0x74, - 0x70, 0x62, 0x2e, 0x4c, 0x69, 0x73, 0x74, 0x53, 0x69, 0x6d, 0x70, 0x6c, 0x65, 0x45, 0x78, 0x61, - 0x6d, 0x70, 0x6c, 0x65, 0x52, 0x65, 0x71, 0x75, 0x65, 0x73, 0x74, 0x2e, 0x49, 0x6e, 0x64, 0x65, - 0x78, 0x4b, 0x65, 0x79, 0x48, 0x00, 0x52, 0x0b, 0x70, 0x72, 0x65, 0x66, 0x69, 0x78, 0x51, 0x75, - 0x65, 0x72, 0x79, 0x12, 0x4e, 0x0a, 0x0b, 0x72, 0x61, 0x6e, 0x67, 0x65, 0x5f, 0x71, 0x75, 0x65, - 0x72, 0x79, 0x18, 0x02, 0x20, 0x01, 0x28, 0x0b, 0x32, 0x2b, 0x2e, 0x74, 0x65, 0x73, 0x74, 0x70, - 0x62, 0x2e, 0x4c, 0x69, 0x73, 0x74, 0x53, 0x69, 0x6d, 0x70, 0x6c, 0x65, 0x45, 0x78, 0x61, 0x6d, - 0x70, 0x6c, 0x65, 0x52, 0x65, 0x71, 0x75, 0x65, 0x73, 0x74, 0x2e, 0x52, 0x61, 0x6e, 0x67, 0x65, - 0x51, 0x75, 0x65, 0x72, 0x79, 0x48, 0x00, 0x52, 0x0a, 0x72, 0x61, 0x6e, 0x67, 0x65, 0x51, 0x75, - 0x65, 0x72, 0x79, 0x12, 0x46, 0x0a, 0x0a, 0x70, 0x61, 0x67, 0x69, 0x6e, 0x61, 0x74, 0x69, 0x6f, - 0x6e, 0x18, 0x03, 0x20, 0x01, 0x28, 0x0b, 0x32, 0x26, 0x2e, 0x63, 0x6f, 0x73, 0x6d, 0x6f, 0x73, - 0x2e, 0x62, 0x61, 0x73, 0x65, 0x2e, 0x71, 0x75, 0x65, 0x72, 0x79, 0x2e, 0x76, 0x31, 0x62, 0x65, - 0x74, 0x61, 0x31, 0x2e, 0x50, 0x61, 0x67, 0x65, 0x52, 0x65, 0x71, 0x75, 0x65, 0x73, 0x74, 0x52, - 0x0a, 0x70, 0x61, 0x67, 0x69, 0x6e, 0x61, 0x74, 0x69, 0x6f, 0x6e, 0x1a, 0xff, 0x01, 0x0a, 0x08, - 0x49, 0x6e, 0x64, 0x65, 0x78, 0x4b, 0x65, 0x79, 0x12, 0x44, 0x0a, 0x04, 0x6e, 0x61, 0x6d, 0x65, - 0x18, 0x01, 0x20, 0x01, 0x28, 0x0b, 0x32, 0x2e, 0x2e, 0x74, 0x65, 0x73, 0x74, 0x70, 0x62, 0x2e, - 0x4c, 0x69, 0x73, 0x74, 0x53, 0x69, 0x6d, 0x70, 0x6c, 0x65, 0x45, 0x78, 0x61, 0x6d, 0x70, 0x6c, - 0x65, 0x52, 0x65, 0x71, 0x75, 0x65, 0x73, 0x74, 0x2e, 0x49, 0x6e, 0x64, 0x65, 0x78, 0x4b, 0x65, - 0x79, 0x2e, 0x4e, 0x61, 0x6d, 0x65, 0x48, 0x00, 0x52, 0x04, 0x6e, 0x61, 0x6d, 0x65, 0x12, 0x4a, - 0x0a, 0x06, 0x75, 0x6e, 0x69, 0x71, 0x75, 0x65, 0x18, 0x02, 0x20, 0x01, 0x28, 0x0b, 0x32, 0x30, - 0x2e, 0x74, 0x65, 0x73, 0x74, 0x70, 0x62, 0x2e, 0x4c, 0x69, 0x73, 0x74, 0x53, 0x69, 0x6d, 0x70, - 0x6c, 0x65, 0x45, 0x78, 0x61, 0x6d, 0x70, 0x6c, 0x65, 0x52, 0x65, 0x71, 0x75, 0x65, 0x73, 0x74, - 0x2e, 0x49, 0x6e, 0x64, 0x65, 0x78, 0x4b, 0x65, 0x79, 0x2e, 0x55, 0x6e, 0x69, 0x71, 0x75, 0x65, - 0x48, 0x00, 0x52, 0x06, 0x75, 0x6e, 0x69, 0x71, 0x75, 0x65, 0x1a, 0x28, 0x0a, 0x04, 0x4e, 0x61, - 0x6d, 0x65, 0x12, 0x17, 0x0a, 0x04, 0x6e, 0x61, 0x6d, 0x65, 0x18, 0x01, 0x20, 0x01, 0x28, 0x09, - 0x48, 0x00, 0x52, 0x04, 0x6e, 0x61, 0x6d, 0x65, 0x88, 0x01, 0x01, 0x42, 0x07, 0x0a, 0x05, 0x5f, - 0x6e, 0x61, 0x6d, 0x65, 0x1a, 0x30, 0x0a, 0x06, 0x55, 0x6e, 0x69, 0x71, 0x75, 0x65, 0x12, 0x1b, - 0x0a, 0x06, 0x75, 0x6e, 0x69, 0x71, 0x75, 0x65, 0x18, 0x01, 0x20, 0x01, 0x28, 0x09, 0x48, 0x00, - 0x52, 0x06, 0x75, 0x6e, 0x69, 0x71, 0x75, 0x65, 0x88, 0x01, 0x01, 0x42, 0x09, 0x0a, 0x07, 0x5f, - 0x75, 0x6e, 0x69, 0x71, 0x75, 0x65, 0x42, 0x05, 0x0a, 0x03, 0x6b, 0x65, 0x79, 0x1a, 0x86, 0x01, - 0x0a, 0x0a, 0x52, 0x61, 0x6e, 0x67, 0x65, 0x51, 0x75, 0x65, 0x72, 0x79, 0x12, 0x3d, 0x0a, 0x04, - 0x66, 0x72, 0x6f, 0x6d, 0x18, 0x01, 0x20, 0x01, 0x28, 0x0b, 0x32, 0x29, 0x2e, 0x74, 0x65, 0x73, - 0x74, 0x70, 0x62, 0x2e, 0x4c, 0x69, 0x73, 0x74, 0x53, 0x69, 0x6d, 0x70, 0x6c, 0x65, 0x45, 0x78, - 0x61, 0x6d, 0x70, 0x6c, 0x65, 0x52, 0x65, 0x71, 0x75, 0x65, 0x73, 0x74, 0x2e, 0x49, 0x6e, 0x64, - 0x65, 0x78, 0x4b, 0x65, 0x79, 0x52, 0x04, 0x66, 0x72, 0x6f, 0x6d, 0x12, 0x39, 0x0a, 0x02, 0x74, - 0x6f, 0x18, 0x02, 0x20, 0x01, 0x28, 0x0b, 0x32, 0x29, 0x2e, 0x74, 0x65, 0x73, 0x74, 0x70, 0x62, - 0x2e, 0x4c, 0x69, 0x73, 0x74, 0x53, 0x69, 0x6d, 0x70, 0x6c, 0x65, 0x45, 0x78, 0x61, 0x6d, 0x70, - 0x6c, 0x65, 0x52, 0x65, 0x71, 0x75, 0x65, 0x73, 0x74, 0x2e, 0x49, 0x6e, 0x64, 0x65, 0x78, 0x4b, - 0x65, 0x79, 0x52, 0x02, 0x74, 0x6f, 0x42, 0x07, 0x0a, 0x05, 0x71, 0x75, 0x65, 0x72, 0x79, 0x22, - 0x93, 0x01, 0x0a, 0x19, 0x4c, 0x69, 0x73, 0x74, 0x53, 0x69, 0x6d, 0x70, 0x6c, 0x65, 0x45, 0x78, - 0x61, 0x6d, 0x70, 0x6c, 0x65, 0x52, 0x65, 0x73, 0x70, 0x6f, 0x6e, 0x73, 0x65, 0x12, 0x2d, 0x0a, - 0x06, 0x76, 0x61, 0x6c, 0x75, 0x65, 0x73, 0x18, 0x01, 0x20, 0x03, 0x28, 0x0b, 0x32, 0x15, 0x2e, - 0x74, 0x65, 0x73, 0x74, 0x70, 0x62, 0x2e, 0x53, 0x69, 0x6d, 0x70, 0x6c, 0x65, 0x45, 0x78, 0x61, - 0x6d, 0x70, 0x6c, 0x65, 0x52, 0x06, 0x76, 0x61, 0x6c, 0x75, 0x65, 0x73, 0x12, 0x47, 0x0a, 0x0a, + 0x6f, 0x6e, 0x22, 0x2b, 0x0a, 0x19, 0x47, 0x65, 0x74, 0x45, 0x78, 0x61, 0x6d, 0x70, 0x6c, 0x65, + 0x44, 0x75, 0x72, 0x61, 0x74, 0x69, 0x6f, 0x6e, 0x52, 0x65, 0x71, 0x75, 0x65, 0x73, 0x74, 0x12, + 0x0e, 0x0a, 0x02, 0x69, 0x64, 0x18, 0x01, 0x20, 0x01, 0x28, 0x04, 0x52, 0x02, 0x69, 0x64, 0x22, + 0x4b, 0x0a, 0x1a, 0x47, 0x65, 0x74, 0x45, 0x78, 0x61, 0x6d, 0x70, 0x6c, 0x65, 0x44, 0x75, 0x72, + 0x61, 0x74, 0x69, 0x6f, 0x6e, 0x52, 0x65, 0x73, 0x70, 0x6f, 0x6e, 0x73, 0x65, 0x12, 0x2d, 0x0a, + 0x05, 0x76, 0x61, 0x6c, 0x75, 0x65, 0x18, 0x01, 0x20, 0x01, 0x28, 0x0b, 0x32, 0x17, 0x2e, 0x74, + 0x65, 0x73, 0x74, 0x70, 0x62, 0x2e, 0x45, 0x78, 0x61, 0x6d, 0x70, 0x6c, 0x65, 0x44, 0x75, 0x72, + 0x61, 0x74, 0x69, 0x6f, 0x6e, 0x52, 0x05, 0x76, 0x61, 0x6c, 0x75, 0x65, 0x22, 0x9c, 0x05, 0x0a, + 0x1a, 0x4c, 0x69, 0x73, 0x74, 0x45, 0x78, 0x61, 0x6d, 0x70, 0x6c, 0x65, 0x44, 0x75, 0x72, 0x61, + 0x74, 0x69, 0x6f, 0x6e, 0x52, 0x65, 0x71, 0x75, 0x65, 0x73, 0x74, 0x12, 0x50, 0x0a, 0x0c, 0x70, + 0x72, 0x65, 0x66, 0x69, 0x78, 0x5f, 0x71, 0x75, 0x65, 0x72, 0x79, 0x18, 0x01, 0x20, 0x01, 0x28, + 0x0b, 0x32, 0x2b, 0x2e, 0x74, 0x65, 0x73, 0x74, 0x70, 0x62, 0x2e, 0x4c, 0x69, 0x73, 0x74, 0x45, + 0x78, 0x61, 0x6d, 0x70, 0x6c, 0x65, 0x44, 0x75, 0x72, 0x61, 0x74, 0x69, 0x6f, 0x6e, 0x52, 0x65, + 0x71, 0x75, 0x65, 0x73, 0x74, 0x2e, 0x49, 0x6e, 0x64, 0x65, 0x78, 0x4b, 0x65, 0x79, 0x48, 0x00, + 0x52, 0x0b, 0x70, 0x72, 0x65, 0x66, 0x69, 0x78, 0x51, 0x75, 0x65, 0x72, 0x79, 0x12, 0x50, 0x0a, + 0x0b, 0x72, 0x61, 0x6e, 0x67, 0x65, 0x5f, 0x71, 0x75, 0x65, 0x72, 0x79, 0x18, 0x02, 0x20, 0x01, + 0x28, 0x0b, 0x32, 0x2d, 0x2e, 0x74, 0x65, 0x73, 0x74, 0x70, 0x62, 0x2e, 0x4c, 0x69, 0x73, 0x74, + 0x45, 0x78, 0x61, 0x6d, 0x70, 0x6c, 0x65, 0x44, 0x75, 0x72, 0x61, 0x74, 0x69, 0x6f, 0x6e, 0x52, + 0x65, 0x71, 0x75, 0x65, 0x73, 0x74, 0x2e, 0x52, 0x61, 0x6e, 0x67, 0x65, 0x51, 0x75, 0x65, 0x72, + 0x79, 0x48, 0x00, 0x52, 0x0a, 0x72, 0x61, 0x6e, 0x67, 0x65, 0x51, 0x75, 0x65, 0x72, 0x79, 0x12, + 0x46, 0x0a, 0x0a, 0x70, 0x61, 0x67, 0x69, 0x6e, 0x61, 0x74, 0x69, 0x6f, 0x6e, 0x18, 0x03, 0x20, + 0x01, 0x28, 0x0b, 0x32, 0x26, 0x2e, 0x63, 0x6f, 0x73, 0x6d, 0x6f, 0x73, 0x2e, 0x62, 0x61, 0x73, + 0x65, 0x2e, 0x71, 0x75, 0x65, 0x72, 0x79, 0x2e, 0x76, 0x31, 0x62, 0x65, 0x74, 0x61, 0x31, 0x2e, + 0x50, 0x61, 0x67, 0x65, 0x52, 0x65, 0x71, 0x75, 0x65, 0x73, 0x74, 0x52, 0x0a, 0x70, 0x61, 0x67, + 0x69, 0x6e, 0x61, 0x74, 0x69, 0x6f, 0x6e, 0x1a, 0xfb, 0x01, 0x0a, 0x08, 0x49, 0x6e, 0x64, 0x65, + 0x78, 0x4b, 0x65, 0x79, 0x12, 0x40, 0x0a, 0x02, 0x69, 0x64, 0x18, 0x01, 0x20, 0x01, 0x28, 0x0b, + 0x32, 0x2e, 0x2e, 0x74, 0x65, 0x73, 0x74, 0x70, 0x62, 0x2e, 0x4c, 0x69, 0x73, 0x74, 0x45, 0x78, + 0x61, 0x6d, 0x70, 0x6c, 0x65, 0x44, 0x75, 0x72, 0x61, 0x74, 0x69, 0x6f, 0x6e, 0x52, 0x65, 0x71, + 0x75, 0x65, 0x73, 0x74, 0x2e, 0x49, 0x6e, 0x64, 0x65, 0x78, 0x4b, 0x65, 0x79, 0x2e, 0x49, 0x64, + 0x48, 0x00, 0x52, 0x02, 0x69, 0x64, 0x12, 0x43, 0x0a, 0x03, 0x64, 0x75, 0x72, 0x18, 0x02, 0x20, + 0x01, 0x28, 0x0b, 0x32, 0x2f, 0x2e, 0x74, 0x65, 0x73, 0x74, 0x70, 0x62, 0x2e, 0x4c, 0x69, 0x73, + 0x74, 0x45, 0x78, 0x61, 0x6d, 0x70, 0x6c, 0x65, 0x44, 0x75, 0x72, 0x61, 0x74, 0x69, 0x6f, 0x6e, + 0x52, 0x65, 0x71, 0x75, 0x65, 0x73, 0x74, 0x2e, 0x49, 0x6e, 0x64, 0x65, 0x78, 0x4b, 0x65, 0x79, + 0x2e, 0x44, 0x75, 0x72, 0x48, 0x00, 0x52, 0x03, 0x64, 0x75, 0x72, 0x1a, 0x20, 0x0a, 0x02, 0x49, + 0x64, 0x12, 0x13, 0x0a, 0x02, 0x69, 0x64, 0x18, 0x01, 0x20, 0x01, 0x28, 0x04, 0x48, 0x00, 0x52, + 0x02, 0x69, 0x64, 0x88, 0x01, 0x01, 0x42, 0x05, 0x0a, 0x03, 0x5f, 0x69, 0x64, 0x1a, 0x3f, 0x0a, + 0x03, 0x44, 0x75, 0x72, 0x12, 0x30, 0x0a, 0x03, 0x64, 0x75, 0x72, 0x18, 0x01, 0x20, 0x01, 0x28, + 0x0b, 0x32, 0x19, 0x2e, 0x67, 0x6f, 0x6f, 0x67, 0x6c, 0x65, 0x2e, 0x70, 0x72, 0x6f, 0x74, 0x6f, + 0x62, 0x75, 0x66, 0x2e, 0x44, 0x75, 0x72, 0x61, 0x74, 0x69, 0x6f, 0x6e, 0x48, 0x00, 0x52, 0x03, + 0x64, 0x75, 0x72, 0x88, 0x01, 0x01, 0x42, 0x06, 0x0a, 0x04, 0x5f, 0x64, 0x75, 0x72, 0x42, 0x05, + 0x0a, 0x03, 0x6b, 0x65, 0x79, 0x1a, 0x8a, 0x01, 0x0a, 0x0a, 0x52, 0x61, 0x6e, 0x67, 0x65, 0x51, + 0x75, 0x65, 0x72, 0x79, 0x12, 0x3f, 0x0a, 0x04, 0x66, 0x72, 0x6f, 0x6d, 0x18, 0x01, 0x20, 0x01, + 0x28, 0x0b, 0x32, 0x2b, 0x2e, 0x74, 0x65, 0x73, 0x74, 0x70, 0x62, 0x2e, 0x4c, 0x69, 0x73, 0x74, + 0x45, 0x78, 0x61, 0x6d, 0x70, 0x6c, 0x65, 0x44, 0x75, 0x72, 0x61, 0x74, 0x69, 0x6f, 0x6e, 0x52, + 0x65, 0x71, 0x75, 0x65, 0x73, 0x74, 0x2e, 0x49, 0x6e, 0x64, 0x65, 0x78, 0x4b, 0x65, 0x79, 0x52, + 0x04, 0x66, 0x72, 0x6f, 0x6d, 0x12, 0x3b, 0x0a, 0x02, 0x74, 0x6f, 0x18, 0x02, 0x20, 0x01, 0x28, + 0x0b, 0x32, 0x2b, 0x2e, 0x74, 0x65, 0x73, 0x74, 0x70, 0x62, 0x2e, 0x4c, 0x69, 0x73, 0x74, 0x45, + 0x78, 0x61, 0x6d, 0x70, 0x6c, 0x65, 0x44, 0x75, 0x72, 0x61, 0x74, 0x69, 0x6f, 0x6e, 0x52, 0x65, + 0x71, 0x75, 0x65, 0x73, 0x74, 0x2e, 0x49, 0x6e, 0x64, 0x65, 0x78, 0x4b, 0x65, 0x79, 0x52, 0x02, + 0x74, 0x6f, 0x42, 0x07, 0x0a, 0x05, 0x71, 0x75, 0x65, 0x72, 0x79, 0x22, 0x97, 0x01, 0x0a, 0x1b, + 0x4c, 0x69, 0x73, 0x74, 0x45, 0x78, 0x61, 0x6d, 0x70, 0x6c, 0x65, 0x44, 0x75, 0x72, 0x61, 0x74, + 0x69, 0x6f, 0x6e, 0x52, 0x65, 0x73, 0x70, 0x6f, 0x6e, 0x73, 0x65, 0x12, 0x2f, 0x0a, 0x06, 0x76, + 0x61, 0x6c, 0x75, 0x65, 0x73, 0x18, 0x01, 0x20, 0x03, 0x28, 0x0b, 0x32, 0x17, 0x2e, 0x74, 0x65, + 0x73, 0x74, 0x70, 0x62, 0x2e, 0x45, 0x78, 0x61, 0x6d, 0x70, 0x6c, 0x65, 0x44, 0x75, 0x72, 0x61, + 0x74, 0x69, 0x6f, 0x6e, 0x52, 0x06, 0x76, 0x61, 0x6c, 0x75, 0x65, 0x73, 0x12, 0x47, 0x0a, 0x0a, 0x70, 0x61, 0x67, 0x69, 0x6e, 0x61, 0x74, 0x69, 0x6f, 0x6e, 0x18, 0x02, 0x20, 0x01, 0x28, 0x0b, 0x32, 0x27, 0x2e, 0x63, 0x6f, 0x73, 0x6d, 0x6f, 0x73, 0x2e, 0x62, 0x61, 0x73, 0x65, 0x2e, 0x71, 0x75, 0x65, 0x72, 0x79, 0x2e, 0x76, 0x31, 0x62, 0x65, 0x74, 0x61, 0x31, 0x2e, 0x50, 0x61, 0x67, 0x65, 0x52, 0x65, 0x73, 0x70, 0x6f, 0x6e, 0x73, 0x65, 0x52, 0x0a, 0x70, 0x61, 0x67, 0x69, 0x6e, - 0x61, 0x74, 0x69, 0x6f, 0x6e, 0x22, 0x35, 0x0a, 0x21, 0x47, 0x65, 0x74, 0x45, 0x78, 0x61, 0x6d, - 0x70, 0x6c, 0x65, 0x41, 0x75, 0x74, 0x6f, 0x49, 0x6e, 0x63, 0x46, 0x69, 0x65, 0x6c, 0x64, 0x4e, - 0x61, 0x6d, 0x65, 0x52, 0x65, 0x71, 0x75, 0x65, 0x73, 0x74, 0x12, 0x10, 0x0a, 0x03, 0x66, 0x6f, - 0x6f, 0x18, 0x01, 0x20, 0x01, 0x28, 0x04, 0x52, 0x03, 0x66, 0x6f, 0x6f, 0x22, 0x5b, 0x0a, 0x22, - 0x47, 0x65, 0x74, 0x45, 0x78, 0x61, 0x6d, 0x70, 0x6c, 0x65, 0x41, 0x75, 0x74, 0x6f, 0x49, 0x6e, - 0x63, 0x46, 0x69, 0x65, 0x6c, 0x64, 0x4e, 0x61, 0x6d, 0x65, 0x52, 0x65, 0x73, 0x70, 0x6f, 0x6e, - 0x73, 0x65, 0x12, 0x35, 0x0a, 0x05, 0x76, 0x61, 0x6c, 0x75, 0x65, 0x18, 0x01, 0x20, 0x01, 0x28, - 0x0b, 0x32, 0x1f, 0x2e, 0x74, 0x65, 0x73, 0x74, 0x70, 0x62, 0x2e, 0x45, 0x78, 0x61, 0x6d, 0x70, - 0x6c, 0x65, 0x41, 0x75, 0x74, 0x6f, 0x49, 0x6e, 0x63, 0x46, 0x69, 0x65, 0x6c, 0x64, 0x4e, 0x61, - 0x6d, 0x65, 0x52, 0x05, 0x76, 0x61, 0x6c, 0x75, 0x65, 0x22, 0xcd, 0x04, 0x0a, 0x22, 0x4c, 0x69, - 0x73, 0x74, 0x45, 0x78, 0x61, 0x6d, 0x70, 0x6c, 0x65, 0x41, 0x75, 0x74, 0x6f, 0x49, 0x6e, 0x63, - 0x46, 0x69, 0x65, 0x6c, 0x64, 0x4e, 0x61, 0x6d, 0x65, 0x52, 0x65, 0x71, 0x75, 0x65, 0x73, 0x74, - 0x12, 0x58, 0x0a, 0x0c, 0x70, 0x72, 0x65, 0x66, 0x69, 0x78, 0x5f, 0x71, 0x75, 0x65, 0x72, 0x79, - 0x18, 0x01, 0x20, 0x01, 0x28, 0x0b, 0x32, 0x33, 0x2e, 0x74, 0x65, 0x73, 0x74, 0x70, 0x62, 0x2e, - 0x4c, 0x69, 0x73, 0x74, 0x45, 0x78, 0x61, 0x6d, 0x70, 0x6c, 0x65, 0x41, 0x75, 0x74, 0x6f, 0x49, - 0x6e, 0x63, 0x46, 0x69, 0x65, 0x6c, 0x64, 0x4e, 0x61, 0x6d, 0x65, 0x52, 0x65, 0x71, 0x75, 0x65, - 0x73, 0x74, 0x2e, 0x49, 0x6e, 0x64, 0x65, 0x78, 0x4b, 0x65, 0x79, 0x48, 0x00, 0x52, 0x0b, 0x70, - 0x72, 0x65, 0x66, 0x69, 0x78, 0x51, 0x75, 0x65, 0x72, 0x79, 0x12, 0x58, 0x0a, 0x0b, 0x72, 0x61, - 0x6e, 0x67, 0x65, 0x5f, 0x71, 0x75, 0x65, 0x72, 0x79, 0x18, 0x02, 0x20, 0x01, 0x28, 0x0b, 0x32, - 0x35, 0x2e, 0x74, 0x65, 0x73, 0x74, 0x70, 0x62, 0x2e, 0x4c, 0x69, 0x73, 0x74, 0x45, 0x78, 0x61, - 0x6d, 0x70, 0x6c, 0x65, 0x41, 0x75, 0x74, 0x6f, 0x49, 0x6e, 0x63, 0x46, 0x69, 0x65, 0x6c, 0x64, - 0x4e, 0x61, 0x6d, 0x65, 0x52, 0x65, 0x71, 0x75, 0x65, 0x73, 0x74, 0x2e, 0x52, 0x61, 0x6e, 0x67, - 0x65, 0x51, 0x75, 0x65, 0x72, 0x79, 0x48, 0x00, 0x52, 0x0a, 0x72, 0x61, 0x6e, 0x67, 0x65, 0x51, - 0x75, 0x65, 0x72, 0x79, 0x12, 0x46, 0x0a, 0x0a, 0x70, 0x61, 0x67, 0x69, 0x6e, 0x61, 0x74, 0x69, - 0x6f, 0x6e, 0x18, 0x03, 0x20, 0x01, 0x28, 0x0b, 0x32, 0x26, 0x2e, 0x63, 0x6f, 0x73, 0x6d, 0x6f, - 0x73, 0x2e, 0x62, 0x61, 0x73, 0x65, 0x2e, 0x71, 0x75, 0x65, 0x72, 0x79, 0x2e, 0x76, 0x31, 0x62, - 0x65, 0x74, 0x61, 0x31, 0x2e, 0x50, 0x61, 0x67, 0x65, 0x52, 0x65, 0x71, 0x75, 0x65, 0x73, 0x74, - 0x52, 0x0a, 0x70, 0x61, 0x67, 0x69, 0x6e, 0x61, 0x74, 0x69, 0x6f, 0x6e, 0x1a, 0x84, 0x01, 0x0a, - 0x08, 0x49, 0x6e, 0x64, 0x65, 0x78, 0x4b, 0x65, 0x79, 0x12, 0x4b, 0x0a, 0x03, 0x66, 0x6f, 0x6f, - 0x18, 0x01, 0x20, 0x01, 0x28, 0x0b, 0x32, 0x37, 0x2e, 0x74, 0x65, 0x73, 0x74, 0x70, 0x62, 0x2e, - 0x4c, 0x69, 0x73, 0x74, 0x45, 0x78, 0x61, 0x6d, 0x70, 0x6c, 0x65, 0x41, 0x75, 0x74, 0x6f, 0x49, - 0x6e, 0x63, 0x46, 0x69, 0x65, 0x6c, 0x64, 0x4e, 0x61, 0x6d, 0x65, 0x52, 0x65, 0x71, 0x75, 0x65, - 0x73, 0x74, 0x2e, 0x49, 0x6e, 0x64, 0x65, 0x78, 0x4b, 0x65, 0x79, 0x2e, 0x46, 0x6f, 0x6f, 0x48, - 0x00, 0x52, 0x03, 0x66, 0x6f, 0x6f, 0x1a, 0x24, 0x0a, 0x03, 0x46, 0x6f, 0x6f, 0x12, 0x15, 0x0a, - 0x03, 0x66, 0x6f, 0x6f, 0x18, 0x01, 0x20, 0x01, 0x28, 0x04, 0x48, 0x00, 0x52, 0x03, 0x66, 0x6f, - 0x6f, 0x88, 0x01, 0x01, 0x42, 0x06, 0x0a, 0x04, 0x5f, 0x66, 0x6f, 0x6f, 0x42, 0x05, 0x0a, 0x03, - 0x6b, 0x65, 0x79, 0x1a, 0x9a, 0x01, 0x0a, 0x0a, 0x52, 0x61, 0x6e, 0x67, 0x65, 0x51, 0x75, 0x65, - 0x72, 0x79, 0x12, 0x47, 0x0a, 0x04, 0x66, 0x72, 0x6f, 0x6d, 0x18, 0x01, 0x20, 0x01, 0x28, 0x0b, - 0x32, 0x33, 0x2e, 0x74, 0x65, 0x73, 0x74, 0x70, 0x62, 0x2e, 0x4c, 0x69, 0x73, 0x74, 0x45, 0x78, + 0x61, 0x74, 0x69, 0x6f, 0x6e, 0x22, 0x2d, 0x0a, 0x17, 0x47, 0x65, 0x74, 0x53, 0x69, 0x6d, 0x70, + 0x6c, 0x65, 0x45, 0x78, 0x61, 0x6d, 0x70, 0x6c, 0x65, 0x52, 0x65, 0x71, 0x75, 0x65, 0x73, 0x74, + 0x12, 0x12, 0x0a, 0x04, 0x6e, 0x61, 0x6d, 0x65, 0x18, 0x01, 0x20, 0x01, 0x28, 0x09, 0x52, 0x04, + 0x6e, 0x61, 0x6d, 0x65, 0x22, 0x47, 0x0a, 0x18, 0x47, 0x65, 0x74, 0x53, 0x69, 0x6d, 0x70, 0x6c, + 0x65, 0x45, 0x78, 0x61, 0x6d, 0x70, 0x6c, 0x65, 0x52, 0x65, 0x73, 0x70, 0x6f, 0x6e, 0x73, 0x65, + 0x12, 0x2b, 0x0a, 0x05, 0x76, 0x61, 0x6c, 0x75, 0x65, 0x18, 0x01, 0x20, 0x01, 0x28, 0x0b, 0x32, + 0x15, 0x2e, 0x74, 0x65, 0x73, 0x74, 0x70, 0x62, 0x2e, 0x53, 0x69, 0x6d, 0x70, 0x6c, 0x65, 0x45, + 0x78, 0x61, 0x6d, 0x70, 0x6c, 0x65, 0x52, 0x05, 0x76, 0x61, 0x6c, 0x75, 0x65, 0x22, 0x39, 0x0a, + 0x1f, 0x47, 0x65, 0x74, 0x53, 0x69, 0x6d, 0x70, 0x6c, 0x65, 0x45, 0x78, 0x61, 0x6d, 0x70, 0x6c, + 0x65, 0x42, 0x79, 0x55, 0x6e, 0x69, 0x71, 0x75, 0x65, 0x52, 0x65, 0x71, 0x75, 0x65, 0x73, 0x74, + 0x12, 0x16, 0x0a, 0x06, 0x75, 0x6e, 0x69, 0x71, 0x75, 0x65, 0x18, 0x01, 0x20, 0x01, 0x28, 0x09, + 0x52, 0x06, 0x75, 0x6e, 0x69, 0x71, 0x75, 0x65, 0x22, 0x4f, 0x0a, 0x20, 0x47, 0x65, 0x74, 0x53, + 0x69, 0x6d, 0x70, 0x6c, 0x65, 0x45, 0x78, 0x61, 0x6d, 0x70, 0x6c, 0x65, 0x42, 0x79, 0x55, 0x6e, + 0x69, 0x71, 0x75, 0x65, 0x52, 0x65, 0x73, 0x70, 0x6f, 0x6e, 0x73, 0x65, 0x12, 0x2b, 0x0a, 0x05, + 0x76, 0x61, 0x6c, 0x75, 0x65, 0x18, 0x01, 0x20, 0x01, 0x28, 0x0b, 0x32, 0x15, 0x2e, 0x74, 0x65, + 0x73, 0x74, 0x70, 0x62, 0x2e, 0x53, 0x69, 0x6d, 0x70, 0x6c, 0x65, 0x45, 0x78, 0x61, 0x6d, 0x70, + 0x6c, 0x65, 0x52, 0x05, 0x76, 0x61, 0x6c, 0x75, 0x65, 0x22, 0x96, 0x05, 0x0a, 0x18, 0x4c, 0x69, + 0x73, 0x74, 0x53, 0x69, 0x6d, 0x70, 0x6c, 0x65, 0x45, 0x78, 0x61, 0x6d, 0x70, 0x6c, 0x65, 0x52, + 0x65, 0x71, 0x75, 0x65, 0x73, 0x74, 0x12, 0x4e, 0x0a, 0x0c, 0x70, 0x72, 0x65, 0x66, 0x69, 0x78, + 0x5f, 0x71, 0x75, 0x65, 0x72, 0x79, 0x18, 0x01, 0x20, 0x01, 0x28, 0x0b, 0x32, 0x29, 0x2e, 0x74, + 0x65, 0x73, 0x74, 0x70, 0x62, 0x2e, 0x4c, 0x69, 0x73, 0x74, 0x53, 0x69, 0x6d, 0x70, 0x6c, 0x65, + 0x45, 0x78, 0x61, 0x6d, 0x70, 0x6c, 0x65, 0x52, 0x65, 0x71, 0x75, 0x65, 0x73, 0x74, 0x2e, 0x49, + 0x6e, 0x64, 0x65, 0x78, 0x4b, 0x65, 0x79, 0x48, 0x00, 0x52, 0x0b, 0x70, 0x72, 0x65, 0x66, 0x69, + 0x78, 0x51, 0x75, 0x65, 0x72, 0x79, 0x12, 0x4e, 0x0a, 0x0b, 0x72, 0x61, 0x6e, 0x67, 0x65, 0x5f, + 0x71, 0x75, 0x65, 0x72, 0x79, 0x18, 0x02, 0x20, 0x01, 0x28, 0x0b, 0x32, 0x2b, 0x2e, 0x74, 0x65, + 0x73, 0x74, 0x70, 0x62, 0x2e, 0x4c, 0x69, 0x73, 0x74, 0x53, 0x69, 0x6d, 0x70, 0x6c, 0x65, 0x45, + 0x78, 0x61, 0x6d, 0x70, 0x6c, 0x65, 0x52, 0x65, 0x71, 0x75, 0x65, 0x73, 0x74, 0x2e, 0x52, 0x61, + 0x6e, 0x67, 0x65, 0x51, 0x75, 0x65, 0x72, 0x79, 0x48, 0x00, 0x52, 0x0a, 0x72, 0x61, 0x6e, 0x67, + 0x65, 0x51, 0x75, 0x65, 0x72, 0x79, 0x12, 0x46, 0x0a, 0x0a, 0x70, 0x61, 0x67, 0x69, 0x6e, 0x61, + 0x74, 0x69, 0x6f, 0x6e, 0x18, 0x03, 0x20, 0x01, 0x28, 0x0b, 0x32, 0x26, 0x2e, 0x63, 0x6f, 0x73, + 0x6d, 0x6f, 0x73, 0x2e, 0x62, 0x61, 0x73, 0x65, 0x2e, 0x71, 0x75, 0x65, 0x72, 0x79, 0x2e, 0x76, + 0x31, 0x62, 0x65, 0x74, 0x61, 0x31, 0x2e, 0x50, 0x61, 0x67, 0x65, 0x52, 0x65, 0x71, 0x75, 0x65, + 0x73, 0x74, 0x52, 0x0a, 0x70, 0x61, 0x67, 0x69, 0x6e, 0x61, 0x74, 0x69, 0x6f, 0x6e, 0x1a, 0xff, + 0x01, 0x0a, 0x08, 0x49, 0x6e, 0x64, 0x65, 0x78, 0x4b, 0x65, 0x79, 0x12, 0x44, 0x0a, 0x04, 0x6e, + 0x61, 0x6d, 0x65, 0x18, 0x01, 0x20, 0x01, 0x28, 0x0b, 0x32, 0x2e, 0x2e, 0x74, 0x65, 0x73, 0x74, + 0x70, 0x62, 0x2e, 0x4c, 0x69, 0x73, 0x74, 0x53, 0x69, 0x6d, 0x70, 0x6c, 0x65, 0x45, 0x78, 0x61, + 0x6d, 0x70, 0x6c, 0x65, 0x52, 0x65, 0x71, 0x75, 0x65, 0x73, 0x74, 0x2e, 0x49, 0x6e, 0x64, 0x65, + 0x78, 0x4b, 0x65, 0x79, 0x2e, 0x4e, 0x61, 0x6d, 0x65, 0x48, 0x00, 0x52, 0x04, 0x6e, 0x61, 0x6d, + 0x65, 0x12, 0x4a, 0x0a, 0x06, 0x75, 0x6e, 0x69, 0x71, 0x75, 0x65, 0x18, 0x02, 0x20, 0x01, 0x28, + 0x0b, 0x32, 0x30, 0x2e, 0x74, 0x65, 0x73, 0x74, 0x70, 0x62, 0x2e, 0x4c, 0x69, 0x73, 0x74, 0x53, + 0x69, 0x6d, 0x70, 0x6c, 0x65, 0x45, 0x78, 0x61, 0x6d, 0x70, 0x6c, 0x65, 0x52, 0x65, 0x71, 0x75, + 0x65, 0x73, 0x74, 0x2e, 0x49, 0x6e, 0x64, 0x65, 0x78, 0x4b, 0x65, 0x79, 0x2e, 0x55, 0x6e, 0x69, + 0x71, 0x75, 0x65, 0x48, 0x00, 0x52, 0x06, 0x75, 0x6e, 0x69, 0x71, 0x75, 0x65, 0x1a, 0x28, 0x0a, + 0x04, 0x4e, 0x61, 0x6d, 0x65, 0x12, 0x17, 0x0a, 0x04, 0x6e, 0x61, 0x6d, 0x65, 0x18, 0x01, 0x20, + 0x01, 0x28, 0x09, 0x48, 0x00, 0x52, 0x04, 0x6e, 0x61, 0x6d, 0x65, 0x88, 0x01, 0x01, 0x42, 0x07, + 0x0a, 0x05, 0x5f, 0x6e, 0x61, 0x6d, 0x65, 0x1a, 0x30, 0x0a, 0x06, 0x55, 0x6e, 0x69, 0x71, 0x75, + 0x65, 0x12, 0x1b, 0x0a, 0x06, 0x75, 0x6e, 0x69, 0x71, 0x75, 0x65, 0x18, 0x01, 0x20, 0x01, 0x28, + 0x09, 0x48, 0x00, 0x52, 0x06, 0x75, 0x6e, 0x69, 0x71, 0x75, 0x65, 0x88, 0x01, 0x01, 0x42, 0x09, + 0x0a, 0x07, 0x5f, 0x75, 0x6e, 0x69, 0x71, 0x75, 0x65, 0x42, 0x05, 0x0a, 0x03, 0x6b, 0x65, 0x79, + 0x1a, 0x86, 0x01, 0x0a, 0x0a, 0x52, 0x61, 0x6e, 0x67, 0x65, 0x51, 0x75, 0x65, 0x72, 0x79, 0x12, + 0x3d, 0x0a, 0x04, 0x66, 0x72, 0x6f, 0x6d, 0x18, 0x01, 0x20, 0x01, 0x28, 0x0b, 0x32, 0x29, 0x2e, + 0x74, 0x65, 0x73, 0x74, 0x70, 0x62, 0x2e, 0x4c, 0x69, 0x73, 0x74, 0x53, 0x69, 0x6d, 0x70, 0x6c, + 0x65, 0x45, 0x78, 0x61, 0x6d, 0x70, 0x6c, 0x65, 0x52, 0x65, 0x71, 0x75, 0x65, 0x73, 0x74, 0x2e, + 0x49, 0x6e, 0x64, 0x65, 0x78, 0x4b, 0x65, 0x79, 0x52, 0x04, 0x66, 0x72, 0x6f, 0x6d, 0x12, 0x39, + 0x0a, 0x02, 0x74, 0x6f, 0x18, 0x02, 0x20, 0x01, 0x28, 0x0b, 0x32, 0x29, 0x2e, 0x74, 0x65, 0x73, + 0x74, 0x70, 0x62, 0x2e, 0x4c, 0x69, 0x73, 0x74, 0x53, 0x69, 0x6d, 0x70, 0x6c, 0x65, 0x45, 0x78, + 0x61, 0x6d, 0x70, 0x6c, 0x65, 0x52, 0x65, 0x71, 0x75, 0x65, 0x73, 0x74, 0x2e, 0x49, 0x6e, 0x64, + 0x65, 0x78, 0x4b, 0x65, 0x79, 0x52, 0x02, 0x74, 0x6f, 0x42, 0x07, 0x0a, 0x05, 0x71, 0x75, 0x65, + 0x72, 0x79, 0x22, 0x93, 0x01, 0x0a, 0x19, 0x4c, 0x69, 0x73, 0x74, 0x53, 0x69, 0x6d, 0x70, 0x6c, + 0x65, 0x45, 0x78, 0x61, 0x6d, 0x70, 0x6c, 0x65, 0x52, 0x65, 0x73, 0x70, 0x6f, 0x6e, 0x73, 0x65, + 0x12, 0x2d, 0x0a, 0x06, 0x76, 0x61, 0x6c, 0x75, 0x65, 0x73, 0x18, 0x01, 0x20, 0x03, 0x28, 0x0b, + 0x32, 0x15, 0x2e, 0x74, 0x65, 0x73, 0x74, 0x70, 0x62, 0x2e, 0x53, 0x69, 0x6d, 0x70, 0x6c, 0x65, + 0x45, 0x78, 0x61, 0x6d, 0x70, 0x6c, 0x65, 0x52, 0x06, 0x76, 0x61, 0x6c, 0x75, 0x65, 0x73, 0x12, + 0x47, 0x0a, 0x0a, 0x70, 0x61, 0x67, 0x69, 0x6e, 0x61, 0x74, 0x69, 0x6f, 0x6e, 0x18, 0x02, 0x20, + 0x01, 0x28, 0x0b, 0x32, 0x27, 0x2e, 0x63, 0x6f, 0x73, 0x6d, 0x6f, 0x73, 0x2e, 0x62, 0x61, 0x73, + 0x65, 0x2e, 0x71, 0x75, 0x65, 0x72, 0x79, 0x2e, 0x76, 0x31, 0x62, 0x65, 0x74, 0x61, 0x31, 0x2e, + 0x50, 0x61, 0x67, 0x65, 0x52, 0x65, 0x73, 0x70, 0x6f, 0x6e, 0x73, 0x65, 0x52, 0x0a, 0x70, 0x61, + 0x67, 0x69, 0x6e, 0x61, 0x74, 0x69, 0x6f, 0x6e, 0x22, 0x35, 0x0a, 0x21, 0x47, 0x65, 0x74, 0x45, + 0x78, 0x61, 0x6d, 0x70, 0x6c, 0x65, 0x41, 0x75, 0x74, 0x6f, 0x49, 0x6e, 0x63, 0x46, 0x69, 0x65, + 0x6c, 0x64, 0x4e, 0x61, 0x6d, 0x65, 0x52, 0x65, 0x71, 0x75, 0x65, 0x73, 0x74, 0x12, 0x10, 0x0a, + 0x03, 0x66, 0x6f, 0x6f, 0x18, 0x01, 0x20, 0x01, 0x28, 0x04, 0x52, 0x03, 0x66, 0x6f, 0x6f, 0x22, + 0x5b, 0x0a, 0x22, 0x47, 0x65, 0x74, 0x45, 0x78, 0x61, 0x6d, 0x70, 0x6c, 0x65, 0x41, 0x75, 0x74, + 0x6f, 0x49, 0x6e, 0x63, 0x46, 0x69, 0x65, 0x6c, 0x64, 0x4e, 0x61, 0x6d, 0x65, 0x52, 0x65, 0x73, + 0x70, 0x6f, 0x6e, 0x73, 0x65, 0x12, 0x35, 0x0a, 0x05, 0x76, 0x61, 0x6c, 0x75, 0x65, 0x18, 0x01, + 0x20, 0x01, 0x28, 0x0b, 0x32, 0x1f, 0x2e, 0x74, 0x65, 0x73, 0x74, 0x70, 0x62, 0x2e, 0x45, 0x78, 0x61, 0x6d, 0x70, 0x6c, 0x65, 0x41, 0x75, 0x74, 0x6f, 0x49, 0x6e, 0x63, 0x46, 0x69, 0x65, 0x6c, - 0x64, 0x4e, 0x61, 0x6d, 0x65, 0x52, 0x65, 0x71, 0x75, 0x65, 0x73, 0x74, 0x2e, 0x49, 0x6e, 0x64, - 0x65, 0x78, 0x4b, 0x65, 0x79, 0x52, 0x04, 0x66, 0x72, 0x6f, 0x6d, 0x12, 0x43, 0x0a, 0x02, 0x74, - 0x6f, 0x18, 0x02, 0x20, 0x01, 0x28, 0x0b, 0x32, 0x33, 0x2e, 0x74, 0x65, 0x73, 0x74, 0x70, 0x62, - 0x2e, 0x4c, 0x69, 0x73, 0x74, 0x45, 0x78, 0x61, 0x6d, 0x70, 0x6c, 0x65, 0x41, 0x75, 0x74, 0x6f, + 0x64, 0x4e, 0x61, 0x6d, 0x65, 0x52, 0x05, 0x76, 0x61, 0x6c, 0x75, 0x65, 0x22, 0xcd, 0x04, 0x0a, + 0x22, 0x4c, 0x69, 0x73, 0x74, 0x45, 0x78, 0x61, 0x6d, 0x70, 0x6c, 0x65, 0x41, 0x75, 0x74, 0x6f, 0x49, 0x6e, 0x63, 0x46, 0x69, 0x65, 0x6c, 0x64, 0x4e, 0x61, 0x6d, 0x65, 0x52, 0x65, 0x71, 0x75, - 0x65, 0x73, 0x74, 0x2e, 0x49, 0x6e, 0x64, 0x65, 0x78, 0x4b, 0x65, 0x79, 0x52, 0x02, 0x74, 0x6f, - 0x42, 0x07, 0x0a, 0x05, 0x71, 0x75, 0x65, 0x72, 0x79, 0x22, 0xa7, 0x01, 0x0a, 0x23, 0x4c, 0x69, - 0x73, 0x74, 0x45, 0x78, 0x61, 0x6d, 0x70, 0x6c, 0x65, 0x41, 0x75, 0x74, 0x6f, 0x49, 0x6e, 0x63, - 0x46, 0x69, 0x65, 0x6c, 0x64, 0x4e, 0x61, 0x6d, 0x65, 0x52, 0x65, 0x73, 0x70, 0x6f, 0x6e, 0x73, - 0x65, 0x12, 0x37, 0x0a, 0x06, 0x76, 0x61, 0x6c, 0x75, 0x65, 0x73, 0x18, 0x01, 0x20, 0x03, 0x28, - 0x0b, 0x32, 0x1f, 0x2e, 0x74, 0x65, 0x73, 0x74, 0x70, 0x62, 0x2e, 0x45, 0x78, 0x61, 0x6d, 0x70, - 0x6c, 0x65, 0x41, 0x75, 0x74, 0x6f, 0x49, 0x6e, 0x63, 0x46, 0x69, 0x65, 0x6c, 0x64, 0x4e, 0x61, - 0x6d, 0x65, 0x52, 0x06, 0x76, 0x61, 0x6c, 0x75, 0x65, 0x73, 0x12, 0x47, 0x0a, 0x0a, 0x70, 0x61, - 0x67, 0x69, 0x6e, 0x61, 0x74, 0x69, 0x6f, 0x6e, 0x18, 0x02, 0x20, 0x01, 0x28, 0x0b, 0x32, 0x27, - 0x2e, 0x63, 0x6f, 0x73, 0x6d, 0x6f, 0x73, 0x2e, 0x62, 0x61, 0x73, 0x65, 0x2e, 0x71, 0x75, 0x65, - 0x72, 0x79, 0x2e, 0x76, 0x31, 0x62, 0x65, 0x74, 0x61, 0x31, 0x2e, 0x50, 0x61, 0x67, 0x65, 0x52, - 0x65, 0x73, 0x70, 0x6f, 0x6e, 0x73, 0x65, 0x52, 0x0a, 0x70, 0x61, 0x67, 0x69, 0x6e, 0x61, 0x74, - 0x69, 0x6f, 0x6e, 0x32, 0xf9, 0x0b, 0x0a, 0x16, 0x54, 0x65, 0x73, 0x74, 0x53, 0x63, 0x68, 0x65, - 0x6d, 0x61, 0x51, 0x75, 0x65, 0x72, 0x79, 0x53, 0x65, 0x72, 0x76, 0x69, 0x63, 0x65, 0x12, 0x54, - 0x0a, 0x0f, 0x47, 0x65, 0x74, 0x45, 0x78, 0x61, 0x6d, 0x70, 0x6c, 0x65, 0x54, 0x61, 0x62, 0x6c, - 0x65, 0x12, 0x1e, 0x2e, 0x74, 0x65, 0x73, 0x74, 0x70, 0x62, 0x2e, 0x47, 0x65, 0x74, 0x45, 0x78, - 0x61, 0x6d, 0x70, 0x6c, 0x65, 0x54, 0x61, 0x62, 0x6c, 0x65, 0x52, 0x65, 0x71, 0x75, 0x65, 0x73, - 0x74, 0x1a, 0x1f, 0x2e, 0x74, 0x65, 0x73, 0x74, 0x70, 0x62, 0x2e, 0x47, 0x65, 0x74, 0x45, 0x78, - 0x61, 0x6d, 0x70, 0x6c, 0x65, 0x54, 0x61, 0x62, 0x6c, 0x65, 0x52, 0x65, 0x73, 0x70, 0x6f, 0x6e, - 0x73, 0x65, 0x22, 0x00, 0x12, 0x6c, 0x0a, 0x17, 0x47, 0x65, 0x74, 0x45, 0x78, 0x61, 0x6d, 0x70, - 0x6c, 0x65, 0x54, 0x61, 0x62, 0x6c, 0x65, 0x42, 0x79, 0x55, 0x36, 0x34, 0x53, 0x74, 0x72, 0x12, - 0x26, 0x2e, 0x74, 0x65, 0x73, 0x74, 0x70, 0x62, 0x2e, 0x47, 0x65, 0x74, 0x45, 0x78, 0x61, 0x6d, - 0x70, 0x6c, 0x65, 0x54, 0x61, 0x62, 0x6c, 0x65, 0x42, 0x79, 0x55, 0x36, 0x34, 0x53, 0x74, 0x72, - 0x52, 0x65, 0x71, 0x75, 0x65, 0x73, 0x74, 0x1a, 0x27, 0x2e, 0x74, 0x65, 0x73, 0x74, 0x70, 0x62, - 0x2e, 0x47, 0x65, 0x74, 0x45, 0x78, 0x61, 0x6d, 0x70, 0x6c, 0x65, 0x54, 0x61, 0x62, 0x6c, 0x65, - 0x42, 0x79, 0x55, 0x36, 0x34, 0x53, 0x74, 0x72, 0x52, 0x65, 0x73, 0x70, 0x6f, 0x6e, 0x73, 0x65, - 0x22, 0x00, 0x12, 0x57, 0x0a, 0x10, 0x4c, 0x69, 0x73, 0x74, 0x45, 0x78, 0x61, 0x6d, 0x70, 0x6c, - 0x65, 0x54, 0x61, 0x62, 0x6c, 0x65, 0x12, 0x1f, 0x2e, 0x74, 0x65, 0x73, 0x74, 0x70, 0x62, 0x2e, - 0x4c, 0x69, 0x73, 0x74, 0x45, 0x78, 0x61, 0x6d, 0x70, 0x6c, 0x65, 0x54, 0x61, 0x62, 0x6c, 0x65, - 0x52, 0x65, 0x71, 0x75, 0x65, 0x73, 0x74, 0x1a, 0x20, 0x2e, 0x74, 0x65, 0x73, 0x74, 0x70, 0x62, - 0x2e, 0x4c, 0x69, 0x73, 0x74, 0x45, 0x78, 0x61, 0x6d, 0x70, 0x6c, 0x65, 0x54, 0x61, 0x62, 0x6c, - 0x65, 0x52, 0x65, 0x73, 0x70, 0x6f, 0x6e, 0x73, 0x65, 0x22, 0x00, 0x12, 0x7b, 0x0a, 0x1c, 0x47, - 0x65, 0x74, 0x45, 0x78, 0x61, 0x6d, 0x70, 0x6c, 0x65, 0x41, 0x75, 0x74, 0x6f, 0x49, 0x6e, 0x63, - 0x72, 0x65, 0x6d, 0x65, 0x6e, 0x74, 0x54, 0x61, 0x62, 0x6c, 0x65, 0x12, 0x2b, 0x2e, 0x74, 0x65, + 0x65, 0x73, 0x74, 0x12, 0x58, 0x0a, 0x0c, 0x70, 0x72, 0x65, 0x66, 0x69, 0x78, 0x5f, 0x71, 0x75, + 0x65, 0x72, 0x79, 0x18, 0x01, 0x20, 0x01, 0x28, 0x0b, 0x32, 0x33, 0x2e, 0x74, 0x65, 0x73, 0x74, + 0x70, 0x62, 0x2e, 0x4c, 0x69, 0x73, 0x74, 0x45, 0x78, 0x61, 0x6d, 0x70, 0x6c, 0x65, 0x41, 0x75, + 0x74, 0x6f, 0x49, 0x6e, 0x63, 0x46, 0x69, 0x65, 0x6c, 0x64, 0x4e, 0x61, 0x6d, 0x65, 0x52, 0x65, + 0x71, 0x75, 0x65, 0x73, 0x74, 0x2e, 0x49, 0x6e, 0x64, 0x65, 0x78, 0x4b, 0x65, 0x79, 0x48, 0x00, + 0x52, 0x0b, 0x70, 0x72, 0x65, 0x66, 0x69, 0x78, 0x51, 0x75, 0x65, 0x72, 0x79, 0x12, 0x58, 0x0a, + 0x0b, 0x72, 0x61, 0x6e, 0x67, 0x65, 0x5f, 0x71, 0x75, 0x65, 0x72, 0x79, 0x18, 0x02, 0x20, 0x01, + 0x28, 0x0b, 0x32, 0x35, 0x2e, 0x74, 0x65, 0x73, 0x74, 0x70, 0x62, 0x2e, 0x4c, 0x69, 0x73, 0x74, + 0x45, 0x78, 0x61, 0x6d, 0x70, 0x6c, 0x65, 0x41, 0x75, 0x74, 0x6f, 0x49, 0x6e, 0x63, 0x46, 0x69, + 0x65, 0x6c, 0x64, 0x4e, 0x61, 0x6d, 0x65, 0x52, 0x65, 0x71, 0x75, 0x65, 0x73, 0x74, 0x2e, 0x52, + 0x61, 0x6e, 0x67, 0x65, 0x51, 0x75, 0x65, 0x72, 0x79, 0x48, 0x00, 0x52, 0x0a, 0x72, 0x61, 0x6e, + 0x67, 0x65, 0x51, 0x75, 0x65, 0x72, 0x79, 0x12, 0x46, 0x0a, 0x0a, 0x70, 0x61, 0x67, 0x69, 0x6e, + 0x61, 0x74, 0x69, 0x6f, 0x6e, 0x18, 0x03, 0x20, 0x01, 0x28, 0x0b, 0x32, 0x26, 0x2e, 0x63, 0x6f, + 0x73, 0x6d, 0x6f, 0x73, 0x2e, 0x62, 0x61, 0x73, 0x65, 0x2e, 0x71, 0x75, 0x65, 0x72, 0x79, 0x2e, + 0x76, 0x31, 0x62, 0x65, 0x74, 0x61, 0x31, 0x2e, 0x50, 0x61, 0x67, 0x65, 0x52, 0x65, 0x71, 0x75, + 0x65, 0x73, 0x74, 0x52, 0x0a, 0x70, 0x61, 0x67, 0x69, 0x6e, 0x61, 0x74, 0x69, 0x6f, 0x6e, 0x1a, + 0x84, 0x01, 0x0a, 0x08, 0x49, 0x6e, 0x64, 0x65, 0x78, 0x4b, 0x65, 0x79, 0x12, 0x4b, 0x0a, 0x03, + 0x66, 0x6f, 0x6f, 0x18, 0x01, 0x20, 0x01, 0x28, 0x0b, 0x32, 0x37, 0x2e, 0x74, 0x65, 0x73, 0x74, + 0x70, 0x62, 0x2e, 0x4c, 0x69, 0x73, 0x74, 0x45, 0x78, 0x61, 0x6d, 0x70, 0x6c, 0x65, 0x41, 0x75, + 0x74, 0x6f, 0x49, 0x6e, 0x63, 0x46, 0x69, 0x65, 0x6c, 0x64, 0x4e, 0x61, 0x6d, 0x65, 0x52, 0x65, + 0x71, 0x75, 0x65, 0x73, 0x74, 0x2e, 0x49, 0x6e, 0x64, 0x65, 0x78, 0x4b, 0x65, 0x79, 0x2e, 0x46, + 0x6f, 0x6f, 0x48, 0x00, 0x52, 0x03, 0x66, 0x6f, 0x6f, 0x1a, 0x24, 0x0a, 0x03, 0x46, 0x6f, 0x6f, + 0x12, 0x15, 0x0a, 0x03, 0x66, 0x6f, 0x6f, 0x18, 0x01, 0x20, 0x01, 0x28, 0x04, 0x48, 0x00, 0x52, + 0x03, 0x66, 0x6f, 0x6f, 0x88, 0x01, 0x01, 0x42, 0x06, 0x0a, 0x04, 0x5f, 0x66, 0x6f, 0x6f, 0x42, + 0x05, 0x0a, 0x03, 0x6b, 0x65, 0x79, 0x1a, 0x9a, 0x01, 0x0a, 0x0a, 0x52, 0x61, 0x6e, 0x67, 0x65, + 0x51, 0x75, 0x65, 0x72, 0x79, 0x12, 0x47, 0x0a, 0x04, 0x66, 0x72, 0x6f, 0x6d, 0x18, 0x01, 0x20, + 0x01, 0x28, 0x0b, 0x32, 0x33, 0x2e, 0x74, 0x65, 0x73, 0x74, 0x70, 0x62, 0x2e, 0x4c, 0x69, 0x73, + 0x74, 0x45, 0x78, 0x61, 0x6d, 0x70, 0x6c, 0x65, 0x41, 0x75, 0x74, 0x6f, 0x49, 0x6e, 0x63, 0x46, + 0x69, 0x65, 0x6c, 0x64, 0x4e, 0x61, 0x6d, 0x65, 0x52, 0x65, 0x71, 0x75, 0x65, 0x73, 0x74, 0x2e, + 0x49, 0x6e, 0x64, 0x65, 0x78, 0x4b, 0x65, 0x79, 0x52, 0x04, 0x66, 0x72, 0x6f, 0x6d, 0x12, 0x43, + 0x0a, 0x02, 0x74, 0x6f, 0x18, 0x02, 0x20, 0x01, 0x28, 0x0b, 0x32, 0x33, 0x2e, 0x74, 0x65, 0x73, + 0x74, 0x70, 0x62, 0x2e, 0x4c, 0x69, 0x73, 0x74, 0x45, 0x78, 0x61, 0x6d, 0x70, 0x6c, 0x65, 0x41, + 0x75, 0x74, 0x6f, 0x49, 0x6e, 0x63, 0x46, 0x69, 0x65, 0x6c, 0x64, 0x4e, 0x61, 0x6d, 0x65, 0x52, + 0x65, 0x71, 0x75, 0x65, 0x73, 0x74, 0x2e, 0x49, 0x6e, 0x64, 0x65, 0x78, 0x4b, 0x65, 0x79, 0x52, + 0x02, 0x74, 0x6f, 0x42, 0x07, 0x0a, 0x05, 0x71, 0x75, 0x65, 0x72, 0x79, 0x22, 0xa7, 0x01, 0x0a, + 0x23, 0x4c, 0x69, 0x73, 0x74, 0x45, 0x78, 0x61, 0x6d, 0x70, 0x6c, 0x65, 0x41, 0x75, 0x74, 0x6f, + 0x49, 0x6e, 0x63, 0x46, 0x69, 0x65, 0x6c, 0x64, 0x4e, 0x61, 0x6d, 0x65, 0x52, 0x65, 0x73, 0x70, + 0x6f, 0x6e, 0x73, 0x65, 0x12, 0x37, 0x0a, 0x06, 0x76, 0x61, 0x6c, 0x75, 0x65, 0x73, 0x18, 0x01, + 0x20, 0x03, 0x28, 0x0b, 0x32, 0x1f, 0x2e, 0x74, 0x65, 0x73, 0x74, 0x70, 0x62, 0x2e, 0x45, 0x78, + 0x61, 0x6d, 0x70, 0x6c, 0x65, 0x41, 0x75, 0x74, 0x6f, 0x49, 0x6e, 0x63, 0x46, 0x69, 0x65, 0x6c, + 0x64, 0x4e, 0x61, 0x6d, 0x65, 0x52, 0x06, 0x76, 0x61, 0x6c, 0x75, 0x65, 0x73, 0x12, 0x47, 0x0a, + 0x0a, 0x70, 0x61, 0x67, 0x69, 0x6e, 0x61, 0x74, 0x69, 0x6f, 0x6e, 0x18, 0x02, 0x20, 0x01, 0x28, + 0x0b, 0x32, 0x27, 0x2e, 0x63, 0x6f, 0x73, 0x6d, 0x6f, 0x73, 0x2e, 0x62, 0x61, 0x73, 0x65, 0x2e, + 0x71, 0x75, 0x65, 0x72, 0x79, 0x2e, 0x76, 0x31, 0x62, 0x65, 0x74, 0x61, 0x31, 0x2e, 0x50, 0x61, + 0x67, 0x65, 0x52, 0x65, 0x73, 0x70, 0x6f, 0x6e, 0x73, 0x65, 0x52, 0x0a, 0x70, 0x61, 0x67, 0x69, + 0x6e, 0x61, 0x74, 0x69, 0x6f, 0x6e, 0x32, 0xba, 0x0d, 0x0a, 0x16, 0x54, 0x65, 0x73, 0x74, 0x53, + 0x63, 0x68, 0x65, 0x6d, 0x61, 0x51, 0x75, 0x65, 0x72, 0x79, 0x53, 0x65, 0x72, 0x76, 0x69, 0x63, + 0x65, 0x12, 0x54, 0x0a, 0x0f, 0x47, 0x65, 0x74, 0x45, 0x78, 0x61, 0x6d, 0x70, 0x6c, 0x65, 0x54, + 0x61, 0x62, 0x6c, 0x65, 0x12, 0x1e, 0x2e, 0x74, 0x65, 0x73, 0x74, 0x70, 0x62, 0x2e, 0x47, 0x65, + 0x74, 0x45, 0x78, 0x61, 0x6d, 0x70, 0x6c, 0x65, 0x54, 0x61, 0x62, 0x6c, 0x65, 0x52, 0x65, 0x71, + 0x75, 0x65, 0x73, 0x74, 0x1a, 0x1f, 0x2e, 0x74, 0x65, 0x73, 0x74, 0x70, 0x62, 0x2e, 0x47, 0x65, + 0x74, 0x45, 0x78, 0x61, 0x6d, 0x70, 0x6c, 0x65, 0x54, 0x61, 0x62, 0x6c, 0x65, 0x52, 0x65, 0x73, + 0x70, 0x6f, 0x6e, 0x73, 0x65, 0x22, 0x00, 0x12, 0x6c, 0x0a, 0x17, 0x47, 0x65, 0x74, 0x45, 0x78, + 0x61, 0x6d, 0x70, 0x6c, 0x65, 0x54, 0x61, 0x62, 0x6c, 0x65, 0x42, 0x79, 0x55, 0x36, 0x34, 0x53, + 0x74, 0x72, 0x12, 0x26, 0x2e, 0x74, 0x65, 0x73, 0x74, 0x70, 0x62, 0x2e, 0x47, 0x65, 0x74, 0x45, + 0x78, 0x61, 0x6d, 0x70, 0x6c, 0x65, 0x54, 0x61, 0x62, 0x6c, 0x65, 0x42, 0x79, 0x55, 0x36, 0x34, + 0x53, 0x74, 0x72, 0x52, 0x65, 0x71, 0x75, 0x65, 0x73, 0x74, 0x1a, 0x27, 0x2e, 0x74, 0x65, 0x73, + 0x74, 0x70, 0x62, 0x2e, 0x47, 0x65, 0x74, 0x45, 0x78, 0x61, 0x6d, 0x70, 0x6c, 0x65, 0x54, 0x61, + 0x62, 0x6c, 0x65, 0x42, 0x79, 0x55, 0x36, 0x34, 0x53, 0x74, 0x72, 0x52, 0x65, 0x73, 0x70, 0x6f, + 0x6e, 0x73, 0x65, 0x22, 0x00, 0x12, 0x57, 0x0a, 0x10, 0x4c, 0x69, 0x73, 0x74, 0x45, 0x78, 0x61, + 0x6d, 0x70, 0x6c, 0x65, 0x54, 0x61, 0x62, 0x6c, 0x65, 0x12, 0x1f, 0x2e, 0x74, 0x65, 0x73, 0x74, + 0x70, 0x62, 0x2e, 0x4c, 0x69, 0x73, 0x74, 0x45, 0x78, 0x61, 0x6d, 0x70, 0x6c, 0x65, 0x54, 0x61, + 0x62, 0x6c, 0x65, 0x52, 0x65, 0x71, 0x75, 0x65, 0x73, 0x74, 0x1a, 0x20, 0x2e, 0x74, 0x65, 0x73, + 0x74, 0x70, 0x62, 0x2e, 0x4c, 0x69, 0x73, 0x74, 0x45, 0x78, 0x61, 0x6d, 0x70, 0x6c, 0x65, 0x54, + 0x61, 0x62, 0x6c, 0x65, 0x52, 0x65, 0x73, 0x70, 0x6f, 0x6e, 0x73, 0x65, 0x22, 0x00, 0x12, 0x7b, + 0x0a, 0x1c, 0x47, 0x65, 0x74, 0x45, 0x78, 0x61, 0x6d, 0x70, 0x6c, 0x65, 0x41, 0x75, 0x74, 0x6f, + 0x49, 0x6e, 0x63, 0x72, 0x65, 0x6d, 0x65, 0x6e, 0x74, 0x54, 0x61, 0x62, 0x6c, 0x65, 0x12, 0x2b, + 0x2e, 0x74, 0x65, 0x73, 0x74, 0x70, 0x62, 0x2e, 0x47, 0x65, 0x74, 0x45, 0x78, 0x61, 0x6d, 0x70, + 0x6c, 0x65, 0x41, 0x75, 0x74, 0x6f, 0x49, 0x6e, 0x63, 0x72, 0x65, 0x6d, 0x65, 0x6e, 0x74, 0x54, + 0x61, 0x62, 0x6c, 0x65, 0x52, 0x65, 0x71, 0x75, 0x65, 0x73, 0x74, 0x1a, 0x2c, 0x2e, 0x74, 0x65, 0x73, 0x74, 0x70, 0x62, 0x2e, 0x47, 0x65, 0x74, 0x45, 0x78, 0x61, 0x6d, 0x70, 0x6c, 0x65, 0x41, 0x75, 0x74, 0x6f, 0x49, 0x6e, 0x63, 0x72, 0x65, 0x6d, 0x65, 0x6e, 0x74, 0x54, 0x61, 0x62, 0x6c, - 0x65, 0x52, 0x65, 0x71, 0x75, 0x65, 0x73, 0x74, 0x1a, 0x2c, 0x2e, 0x74, 0x65, 0x73, 0x74, 0x70, - 0x62, 0x2e, 0x47, 0x65, 0x74, 0x45, 0x78, 0x61, 0x6d, 0x70, 0x6c, 0x65, 0x41, 0x75, 0x74, 0x6f, - 0x49, 0x6e, 0x63, 0x72, 0x65, 0x6d, 0x65, 0x6e, 0x74, 0x54, 0x61, 0x62, 0x6c, 0x65, 0x52, 0x65, - 0x73, 0x70, 0x6f, 0x6e, 0x73, 0x65, 0x22, 0x00, 0x12, 0x84, 0x01, 0x0a, 0x1f, 0x47, 0x65, 0x74, - 0x45, 0x78, 0x61, 0x6d, 0x70, 0x6c, 0x65, 0x41, 0x75, 0x74, 0x6f, 0x49, 0x6e, 0x63, 0x72, 0x65, - 0x6d, 0x65, 0x6e, 0x74, 0x54, 0x61, 0x62, 0x6c, 0x65, 0x42, 0x79, 0x58, 0x12, 0x2e, 0x2e, 0x74, - 0x65, 0x73, 0x74, 0x70, 0x62, 0x2e, 0x47, 0x65, 0x74, 0x45, 0x78, 0x61, 0x6d, 0x70, 0x6c, 0x65, - 0x41, 0x75, 0x74, 0x6f, 0x49, 0x6e, 0x63, 0x72, 0x65, 0x6d, 0x65, 0x6e, 0x74, 0x54, 0x61, 0x62, - 0x6c, 0x65, 0x42, 0x79, 0x58, 0x52, 0x65, 0x71, 0x75, 0x65, 0x73, 0x74, 0x1a, 0x2f, 0x2e, 0x74, - 0x65, 0x73, 0x74, 0x70, 0x62, 0x2e, 0x47, 0x65, 0x74, 0x45, 0x78, 0x61, 0x6d, 0x70, 0x6c, 0x65, - 0x41, 0x75, 0x74, 0x6f, 0x49, 0x6e, 0x63, 0x72, 0x65, 0x6d, 0x65, 0x6e, 0x74, 0x54, 0x61, 0x62, - 0x6c, 0x65, 0x42, 0x79, 0x58, 0x52, 0x65, 0x73, 0x70, 0x6f, 0x6e, 0x73, 0x65, 0x22, 0x00, 0x12, - 0x7e, 0x0a, 0x1d, 0x4c, 0x69, 0x73, 0x74, 0x45, 0x78, 0x61, 0x6d, 0x70, 0x6c, 0x65, 0x41, 0x75, - 0x74, 0x6f, 0x49, 0x6e, 0x63, 0x72, 0x65, 0x6d, 0x65, 0x6e, 0x74, 0x54, 0x61, 0x62, 0x6c, 0x65, - 0x12, 0x2c, 0x2e, 0x74, 0x65, 0x73, 0x74, 0x70, 0x62, 0x2e, 0x4c, 0x69, 0x73, 0x74, 0x45, 0x78, - 0x61, 0x6d, 0x70, 0x6c, 0x65, 0x41, 0x75, 0x74, 0x6f, 0x49, 0x6e, 0x63, 0x72, 0x65, 0x6d, 0x65, - 0x6e, 0x74, 0x54, 0x61, 0x62, 0x6c, 0x65, 0x52, 0x65, 0x71, 0x75, 0x65, 0x73, 0x74, 0x1a, 0x2d, - 0x2e, 0x74, 0x65, 0x73, 0x74, 0x70, 0x62, 0x2e, 0x4c, 0x69, 0x73, 0x74, 0x45, 0x78, 0x61, 0x6d, + 0x65, 0x52, 0x65, 0x73, 0x70, 0x6f, 0x6e, 0x73, 0x65, 0x22, 0x00, 0x12, 0x84, 0x01, 0x0a, 0x1f, + 0x47, 0x65, 0x74, 0x45, 0x78, 0x61, 0x6d, 0x70, 0x6c, 0x65, 0x41, 0x75, 0x74, 0x6f, 0x49, 0x6e, + 0x63, 0x72, 0x65, 0x6d, 0x65, 0x6e, 0x74, 0x54, 0x61, 0x62, 0x6c, 0x65, 0x42, 0x79, 0x58, 0x12, + 0x2e, 0x2e, 0x74, 0x65, 0x73, 0x74, 0x70, 0x62, 0x2e, 0x47, 0x65, 0x74, 0x45, 0x78, 0x61, 0x6d, 0x70, 0x6c, 0x65, 0x41, 0x75, 0x74, 0x6f, 0x49, 0x6e, 0x63, 0x72, 0x65, 0x6d, 0x65, 0x6e, 0x74, - 0x54, 0x61, 0x62, 0x6c, 0x65, 0x52, 0x65, 0x73, 0x70, 0x6f, 0x6e, 0x73, 0x65, 0x22, 0x00, 0x12, - 0x60, 0x0a, 0x13, 0x47, 0x65, 0x74, 0x45, 0x78, 0x61, 0x6d, 0x70, 0x6c, 0x65, 0x53, 0x69, 0x6e, - 0x67, 0x6c, 0x65, 0x74, 0x6f, 0x6e, 0x12, 0x22, 0x2e, 0x74, 0x65, 0x73, 0x74, 0x70, 0x62, 0x2e, - 0x47, 0x65, 0x74, 0x45, 0x78, 0x61, 0x6d, 0x70, 0x6c, 0x65, 0x53, 0x69, 0x6e, 0x67, 0x6c, 0x65, - 0x74, 0x6f, 0x6e, 0x52, 0x65, 0x71, 0x75, 0x65, 0x73, 0x74, 0x1a, 0x23, 0x2e, 0x74, 0x65, 0x73, - 0x74, 0x70, 0x62, 0x2e, 0x47, 0x65, 0x74, 0x45, 0x78, 0x61, 0x6d, 0x70, 0x6c, 0x65, 0x53, 0x69, - 0x6e, 0x67, 0x6c, 0x65, 0x74, 0x6f, 0x6e, 0x52, 0x65, 0x73, 0x70, 0x6f, 0x6e, 0x73, 0x65, 0x22, - 0x00, 0x12, 0x60, 0x0a, 0x13, 0x47, 0x65, 0x74, 0x45, 0x78, 0x61, 0x6d, 0x70, 0x6c, 0x65, 0x54, - 0x69, 0x6d, 0x65, 0x73, 0x74, 0x61, 0x6d, 0x70, 0x12, 0x22, 0x2e, 0x74, 0x65, 0x73, 0x74, 0x70, - 0x62, 0x2e, 0x47, 0x65, 0x74, 0x45, 0x78, 0x61, 0x6d, 0x70, 0x6c, 0x65, 0x54, 0x69, 0x6d, 0x65, - 0x73, 0x74, 0x61, 0x6d, 0x70, 0x52, 0x65, 0x71, 0x75, 0x65, 0x73, 0x74, 0x1a, 0x23, 0x2e, 0x74, - 0x65, 0x73, 0x74, 0x70, 0x62, 0x2e, 0x47, 0x65, 0x74, 0x45, 0x78, 0x61, 0x6d, 0x70, 0x6c, 0x65, - 0x54, 0x69, 0x6d, 0x65, 0x73, 0x74, 0x61, 0x6d, 0x70, 0x52, 0x65, 0x73, 0x70, 0x6f, 0x6e, 0x73, - 0x65, 0x22, 0x00, 0x12, 0x63, 0x0a, 0x14, 0x4c, 0x69, 0x73, 0x74, 0x45, 0x78, 0x61, 0x6d, 0x70, - 0x6c, 0x65, 0x54, 0x69, 0x6d, 0x65, 0x73, 0x74, 0x61, 0x6d, 0x70, 0x12, 0x23, 0x2e, 0x74, 0x65, - 0x73, 0x74, 0x70, 0x62, 0x2e, 0x4c, 0x69, 0x73, 0x74, 0x45, 0x78, 0x61, 0x6d, 0x70, 0x6c, 0x65, - 0x54, 0x69, 0x6d, 0x65, 0x73, 0x74, 0x61, 0x6d, 0x70, 0x52, 0x65, 0x71, 0x75, 0x65, 0x73, 0x74, - 0x1a, 0x24, 0x2e, 0x74, 0x65, 0x73, 0x74, 0x70, 0x62, 0x2e, 0x4c, 0x69, 0x73, 0x74, 0x45, 0x78, - 0x61, 0x6d, 0x70, 0x6c, 0x65, 0x54, 0x69, 0x6d, 0x65, 0x73, 0x74, 0x61, 0x6d, 0x70, 0x52, 0x65, - 0x73, 0x70, 0x6f, 0x6e, 0x73, 0x65, 0x22, 0x00, 0x12, 0x57, 0x0a, 0x10, 0x47, 0x65, 0x74, 0x53, - 0x69, 0x6d, 0x70, 0x6c, 0x65, 0x45, 0x78, 0x61, 0x6d, 0x70, 0x6c, 0x65, 0x12, 0x1f, 0x2e, 0x74, - 0x65, 0x73, 0x74, 0x70, 0x62, 0x2e, 0x47, 0x65, 0x74, 0x53, 0x69, 0x6d, 0x70, 0x6c, 0x65, 0x45, - 0x78, 0x61, 0x6d, 0x70, 0x6c, 0x65, 0x52, 0x65, 0x71, 0x75, 0x65, 0x73, 0x74, 0x1a, 0x20, 0x2e, - 0x74, 0x65, 0x73, 0x74, 0x70, 0x62, 0x2e, 0x47, 0x65, 0x74, 0x53, 0x69, 0x6d, 0x70, 0x6c, 0x65, - 0x45, 0x78, 0x61, 0x6d, 0x70, 0x6c, 0x65, 0x52, 0x65, 0x73, 0x70, 0x6f, 0x6e, 0x73, 0x65, 0x22, - 0x00, 0x12, 0x6f, 0x0a, 0x18, 0x47, 0x65, 0x74, 0x53, 0x69, 0x6d, 0x70, 0x6c, 0x65, 0x45, 0x78, - 0x61, 0x6d, 0x70, 0x6c, 0x65, 0x42, 0x79, 0x55, 0x6e, 0x69, 0x71, 0x75, 0x65, 0x12, 0x27, 0x2e, - 0x74, 0x65, 0x73, 0x74, 0x70, 0x62, 0x2e, 0x47, 0x65, 0x74, 0x53, 0x69, 0x6d, 0x70, 0x6c, 0x65, - 0x45, 0x78, 0x61, 0x6d, 0x70, 0x6c, 0x65, 0x42, 0x79, 0x55, 0x6e, 0x69, 0x71, 0x75, 0x65, 0x52, - 0x65, 0x71, 0x75, 0x65, 0x73, 0x74, 0x1a, 0x28, 0x2e, 0x74, 0x65, 0x73, 0x74, 0x70, 0x62, 0x2e, + 0x54, 0x61, 0x62, 0x6c, 0x65, 0x42, 0x79, 0x58, 0x52, 0x65, 0x71, 0x75, 0x65, 0x73, 0x74, 0x1a, + 0x2f, 0x2e, 0x74, 0x65, 0x73, 0x74, 0x70, 0x62, 0x2e, 0x47, 0x65, 0x74, 0x45, 0x78, 0x61, 0x6d, + 0x70, 0x6c, 0x65, 0x41, 0x75, 0x74, 0x6f, 0x49, 0x6e, 0x63, 0x72, 0x65, 0x6d, 0x65, 0x6e, 0x74, + 0x54, 0x61, 0x62, 0x6c, 0x65, 0x42, 0x79, 0x58, 0x52, 0x65, 0x73, 0x70, 0x6f, 0x6e, 0x73, 0x65, + 0x22, 0x00, 0x12, 0x7e, 0x0a, 0x1d, 0x4c, 0x69, 0x73, 0x74, 0x45, 0x78, 0x61, 0x6d, 0x70, 0x6c, + 0x65, 0x41, 0x75, 0x74, 0x6f, 0x49, 0x6e, 0x63, 0x72, 0x65, 0x6d, 0x65, 0x6e, 0x74, 0x54, 0x61, + 0x62, 0x6c, 0x65, 0x12, 0x2c, 0x2e, 0x74, 0x65, 0x73, 0x74, 0x70, 0x62, 0x2e, 0x4c, 0x69, 0x73, + 0x74, 0x45, 0x78, 0x61, 0x6d, 0x70, 0x6c, 0x65, 0x41, 0x75, 0x74, 0x6f, 0x49, 0x6e, 0x63, 0x72, + 0x65, 0x6d, 0x65, 0x6e, 0x74, 0x54, 0x61, 0x62, 0x6c, 0x65, 0x52, 0x65, 0x71, 0x75, 0x65, 0x73, + 0x74, 0x1a, 0x2d, 0x2e, 0x74, 0x65, 0x73, 0x74, 0x70, 0x62, 0x2e, 0x4c, 0x69, 0x73, 0x74, 0x45, + 0x78, 0x61, 0x6d, 0x70, 0x6c, 0x65, 0x41, 0x75, 0x74, 0x6f, 0x49, 0x6e, 0x63, 0x72, 0x65, 0x6d, + 0x65, 0x6e, 0x74, 0x54, 0x61, 0x62, 0x6c, 0x65, 0x52, 0x65, 0x73, 0x70, 0x6f, 0x6e, 0x73, 0x65, + 0x22, 0x00, 0x12, 0x60, 0x0a, 0x13, 0x47, 0x65, 0x74, 0x45, 0x78, 0x61, 0x6d, 0x70, 0x6c, 0x65, + 0x53, 0x69, 0x6e, 0x67, 0x6c, 0x65, 0x74, 0x6f, 0x6e, 0x12, 0x22, 0x2e, 0x74, 0x65, 0x73, 0x74, + 0x70, 0x62, 0x2e, 0x47, 0x65, 0x74, 0x45, 0x78, 0x61, 0x6d, 0x70, 0x6c, 0x65, 0x53, 0x69, 0x6e, + 0x67, 0x6c, 0x65, 0x74, 0x6f, 0x6e, 0x52, 0x65, 0x71, 0x75, 0x65, 0x73, 0x74, 0x1a, 0x23, 0x2e, + 0x74, 0x65, 0x73, 0x74, 0x70, 0x62, 0x2e, 0x47, 0x65, 0x74, 0x45, 0x78, 0x61, 0x6d, 0x70, 0x6c, + 0x65, 0x53, 0x69, 0x6e, 0x67, 0x6c, 0x65, 0x74, 0x6f, 0x6e, 0x52, 0x65, 0x73, 0x70, 0x6f, 0x6e, + 0x73, 0x65, 0x22, 0x00, 0x12, 0x60, 0x0a, 0x13, 0x47, 0x65, 0x74, 0x45, 0x78, 0x61, 0x6d, 0x70, + 0x6c, 0x65, 0x54, 0x69, 0x6d, 0x65, 0x73, 0x74, 0x61, 0x6d, 0x70, 0x12, 0x22, 0x2e, 0x74, 0x65, + 0x73, 0x74, 0x70, 0x62, 0x2e, 0x47, 0x65, 0x74, 0x45, 0x78, 0x61, 0x6d, 0x70, 0x6c, 0x65, 0x54, + 0x69, 0x6d, 0x65, 0x73, 0x74, 0x61, 0x6d, 0x70, 0x52, 0x65, 0x71, 0x75, 0x65, 0x73, 0x74, 0x1a, + 0x23, 0x2e, 0x74, 0x65, 0x73, 0x74, 0x70, 0x62, 0x2e, 0x47, 0x65, 0x74, 0x45, 0x78, 0x61, 0x6d, + 0x70, 0x6c, 0x65, 0x54, 0x69, 0x6d, 0x65, 0x73, 0x74, 0x61, 0x6d, 0x70, 0x52, 0x65, 0x73, 0x70, + 0x6f, 0x6e, 0x73, 0x65, 0x22, 0x00, 0x12, 0x63, 0x0a, 0x14, 0x4c, 0x69, 0x73, 0x74, 0x45, 0x78, + 0x61, 0x6d, 0x70, 0x6c, 0x65, 0x54, 0x69, 0x6d, 0x65, 0x73, 0x74, 0x61, 0x6d, 0x70, 0x12, 0x23, + 0x2e, 0x74, 0x65, 0x73, 0x74, 0x70, 0x62, 0x2e, 0x4c, 0x69, 0x73, 0x74, 0x45, 0x78, 0x61, 0x6d, + 0x70, 0x6c, 0x65, 0x54, 0x69, 0x6d, 0x65, 0x73, 0x74, 0x61, 0x6d, 0x70, 0x52, 0x65, 0x71, 0x75, + 0x65, 0x73, 0x74, 0x1a, 0x24, 0x2e, 0x74, 0x65, 0x73, 0x74, 0x70, 0x62, 0x2e, 0x4c, 0x69, 0x73, + 0x74, 0x45, 0x78, 0x61, 0x6d, 0x70, 0x6c, 0x65, 0x54, 0x69, 0x6d, 0x65, 0x73, 0x74, 0x61, 0x6d, + 0x70, 0x52, 0x65, 0x73, 0x70, 0x6f, 0x6e, 0x73, 0x65, 0x22, 0x00, 0x12, 0x5d, 0x0a, 0x12, 0x47, + 0x65, 0x74, 0x45, 0x78, 0x61, 0x6d, 0x70, 0x6c, 0x65, 0x44, 0x75, 0x72, 0x61, 0x74, 0x69, 0x6f, + 0x6e, 0x12, 0x21, 0x2e, 0x74, 0x65, 0x73, 0x74, 0x70, 0x62, 0x2e, 0x47, 0x65, 0x74, 0x45, 0x78, + 0x61, 0x6d, 0x70, 0x6c, 0x65, 0x44, 0x75, 0x72, 0x61, 0x74, 0x69, 0x6f, 0x6e, 0x52, 0x65, 0x71, + 0x75, 0x65, 0x73, 0x74, 0x1a, 0x22, 0x2e, 0x74, 0x65, 0x73, 0x74, 0x70, 0x62, 0x2e, 0x47, 0x65, + 0x74, 0x45, 0x78, 0x61, 0x6d, 0x70, 0x6c, 0x65, 0x44, 0x75, 0x72, 0x61, 0x74, 0x69, 0x6f, 0x6e, + 0x52, 0x65, 0x73, 0x70, 0x6f, 0x6e, 0x73, 0x65, 0x22, 0x00, 0x12, 0x60, 0x0a, 0x13, 0x4c, 0x69, + 0x73, 0x74, 0x45, 0x78, 0x61, 0x6d, 0x70, 0x6c, 0x65, 0x44, 0x75, 0x72, 0x61, 0x74, 0x69, 0x6f, + 0x6e, 0x12, 0x22, 0x2e, 0x74, 0x65, 0x73, 0x74, 0x70, 0x62, 0x2e, 0x4c, 0x69, 0x73, 0x74, 0x45, + 0x78, 0x61, 0x6d, 0x70, 0x6c, 0x65, 0x44, 0x75, 0x72, 0x61, 0x74, 0x69, 0x6f, 0x6e, 0x52, 0x65, + 0x71, 0x75, 0x65, 0x73, 0x74, 0x1a, 0x23, 0x2e, 0x74, 0x65, 0x73, 0x74, 0x70, 0x62, 0x2e, 0x4c, + 0x69, 0x73, 0x74, 0x45, 0x78, 0x61, 0x6d, 0x70, 0x6c, 0x65, 0x44, 0x75, 0x72, 0x61, 0x74, 0x69, + 0x6f, 0x6e, 0x52, 0x65, 0x73, 0x70, 0x6f, 0x6e, 0x73, 0x65, 0x22, 0x00, 0x12, 0x57, 0x0a, 0x10, 0x47, 0x65, 0x74, 0x53, 0x69, 0x6d, 0x70, 0x6c, 0x65, 0x45, 0x78, 0x61, 0x6d, 0x70, 0x6c, 0x65, - 0x42, 0x79, 0x55, 0x6e, 0x69, 0x71, 0x75, 0x65, 0x52, 0x65, 0x73, 0x70, 0x6f, 0x6e, 0x73, 0x65, - 0x22, 0x00, 0x12, 0x5a, 0x0a, 0x11, 0x4c, 0x69, 0x73, 0x74, 0x53, 0x69, 0x6d, 0x70, 0x6c, 0x65, - 0x45, 0x78, 0x61, 0x6d, 0x70, 0x6c, 0x65, 0x12, 0x20, 0x2e, 0x74, 0x65, 0x73, 0x74, 0x70, 0x62, - 0x2e, 0x4c, 0x69, 0x73, 0x74, 0x53, 0x69, 0x6d, 0x70, 0x6c, 0x65, 0x45, 0x78, 0x61, 0x6d, 0x70, - 0x6c, 0x65, 0x52, 0x65, 0x71, 0x75, 0x65, 0x73, 0x74, 0x1a, 0x21, 0x2e, 0x74, 0x65, 0x73, 0x74, - 0x70, 0x62, 0x2e, 0x4c, 0x69, 0x73, 0x74, 0x53, 0x69, 0x6d, 0x70, 0x6c, 0x65, 0x45, 0x78, 0x61, - 0x6d, 0x70, 0x6c, 0x65, 0x52, 0x65, 0x73, 0x70, 0x6f, 0x6e, 0x73, 0x65, 0x22, 0x00, 0x12, 0x75, - 0x0a, 0x1a, 0x47, 0x65, 0x74, 0x45, 0x78, 0x61, 0x6d, 0x70, 0x6c, 0x65, 0x41, 0x75, 0x74, 0x6f, - 0x49, 0x6e, 0x63, 0x46, 0x69, 0x65, 0x6c, 0x64, 0x4e, 0x61, 0x6d, 0x65, 0x12, 0x29, 0x2e, 0x74, - 0x65, 0x73, 0x74, 0x70, 0x62, 0x2e, 0x47, 0x65, 0x74, 0x45, 0x78, 0x61, 0x6d, 0x70, 0x6c, 0x65, + 0x12, 0x1f, 0x2e, 0x74, 0x65, 0x73, 0x74, 0x70, 0x62, 0x2e, 0x47, 0x65, 0x74, 0x53, 0x69, 0x6d, + 0x70, 0x6c, 0x65, 0x45, 0x78, 0x61, 0x6d, 0x70, 0x6c, 0x65, 0x52, 0x65, 0x71, 0x75, 0x65, 0x73, + 0x74, 0x1a, 0x20, 0x2e, 0x74, 0x65, 0x73, 0x74, 0x70, 0x62, 0x2e, 0x47, 0x65, 0x74, 0x53, 0x69, + 0x6d, 0x70, 0x6c, 0x65, 0x45, 0x78, 0x61, 0x6d, 0x70, 0x6c, 0x65, 0x52, 0x65, 0x73, 0x70, 0x6f, + 0x6e, 0x73, 0x65, 0x22, 0x00, 0x12, 0x6f, 0x0a, 0x18, 0x47, 0x65, 0x74, 0x53, 0x69, 0x6d, 0x70, + 0x6c, 0x65, 0x45, 0x78, 0x61, 0x6d, 0x70, 0x6c, 0x65, 0x42, 0x79, 0x55, 0x6e, 0x69, 0x71, 0x75, + 0x65, 0x12, 0x27, 0x2e, 0x74, 0x65, 0x73, 0x74, 0x70, 0x62, 0x2e, 0x47, 0x65, 0x74, 0x53, 0x69, + 0x6d, 0x70, 0x6c, 0x65, 0x45, 0x78, 0x61, 0x6d, 0x70, 0x6c, 0x65, 0x42, 0x79, 0x55, 0x6e, 0x69, + 0x71, 0x75, 0x65, 0x52, 0x65, 0x71, 0x75, 0x65, 0x73, 0x74, 0x1a, 0x28, 0x2e, 0x74, 0x65, 0x73, + 0x74, 0x70, 0x62, 0x2e, 0x47, 0x65, 0x74, 0x53, 0x69, 0x6d, 0x70, 0x6c, 0x65, 0x45, 0x78, 0x61, + 0x6d, 0x70, 0x6c, 0x65, 0x42, 0x79, 0x55, 0x6e, 0x69, 0x71, 0x75, 0x65, 0x52, 0x65, 0x73, 0x70, + 0x6f, 0x6e, 0x73, 0x65, 0x22, 0x00, 0x12, 0x5a, 0x0a, 0x11, 0x4c, 0x69, 0x73, 0x74, 0x53, 0x69, + 0x6d, 0x70, 0x6c, 0x65, 0x45, 0x78, 0x61, 0x6d, 0x70, 0x6c, 0x65, 0x12, 0x20, 0x2e, 0x74, 0x65, + 0x73, 0x74, 0x70, 0x62, 0x2e, 0x4c, 0x69, 0x73, 0x74, 0x53, 0x69, 0x6d, 0x70, 0x6c, 0x65, 0x45, + 0x78, 0x61, 0x6d, 0x70, 0x6c, 0x65, 0x52, 0x65, 0x71, 0x75, 0x65, 0x73, 0x74, 0x1a, 0x21, 0x2e, + 0x74, 0x65, 0x73, 0x74, 0x70, 0x62, 0x2e, 0x4c, 0x69, 0x73, 0x74, 0x53, 0x69, 0x6d, 0x70, 0x6c, + 0x65, 0x45, 0x78, 0x61, 0x6d, 0x70, 0x6c, 0x65, 0x52, 0x65, 0x73, 0x70, 0x6f, 0x6e, 0x73, 0x65, + 0x22, 0x00, 0x12, 0x75, 0x0a, 0x1a, 0x47, 0x65, 0x74, 0x45, 0x78, 0x61, 0x6d, 0x70, 0x6c, 0x65, 0x41, 0x75, 0x74, 0x6f, 0x49, 0x6e, 0x63, 0x46, 0x69, 0x65, 0x6c, 0x64, 0x4e, 0x61, 0x6d, 0x65, - 0x52, 0x65, 0x71, 0x75, 0x65, 0x73, 0x74, 0x1a, 0x2a, 0x2e, 0x74, 0x65, 0x73, 0x74, 0x70, 0x62, - 0x2e, 0x47, 0x65, 0x74, 0x45, 0x78, 0x61, 0x6d, 0x70, 0x6c, 0x65, 0x41, 0x75, 0x74, 0x6f, 0x49, - 0x6e, 0x63, 0x46, 0x69, 0x65, 0x6c, 0x64, 0x4e, 0x61, 0x6d, 0x65, 0x52, 0x65, 0x73, 0x70, 0x6f, - 0x6e, 0x73, 0x65, 0x22, 0x00, 0x12, 0x78, 0x0a, 0x1b, 0x4c, 0x69, 0x73, 0x74, 0x45, 0x78, 0x61, + 0x12, 0x29, 0x2e, 0x74, 0x65, 0x73, 0x74, 0x70, 0x62, 0x2e, 0x47, 0x65, 0x74, 0x45, 0x78, 0x61, 0x6d, 0x70, 0x6c, 0x65, 0x41, 0x75, 0x74, 0x6f, 0x49, 0x6e, 0x63, 0x46, 0x69, 0x65, 0x6c, 0x64, - 0x4e, 0x61, 0x6d, 0x65, 0x12, 0x2a, 0x2e, 0x74, 0x65, 0x73, 0x74, 0x70, 0x62, 0x2e, 0x4c, 0x69, + 0x4e, 0x61, 0x6d, 0x65, 0x52, 0x65, 0x71, 0x75, 0x65, 0x73, 0x74, 0x1a, 0x2a, 0x2e, 0x74, 0x65, + 0x73, 0x74, 0x70, 0x62, 0x2e, 0x47, 0x65, 0x74, 0x45, 0x78, 0x61, 0x6d, 0x70, 0x6c, 0x65, 0x41, + 0x75, 0x74, 0x6f, 0x49, 0x6e, 0x63, 0x46, 0x69, 0x65, 0x6c, 0x64, 0x4e, 0x61, 0x6d, 0x65, 0x52, + 0x65, 0x73, 0x70, 0x6f, 0x6e, 0x73, 0x65, 0x22, 0x00, 0x12, 0x78, 0x0a, 0x1b, 0x4c, 0x69, 0x73, + 0x74, 0x45, 0x78, 0x61, 0x6d, 0x70, 0x6c, 0x65, 0x41, 0x75, 0x74, 0x6f, 0x49, 0x6e, 0x63, 0x46, + 0x69, 0x65, 0x6c, 0x64, 0x4e, 0x61, 0x6d, 0x65, 0x12, 0x2a, 0x2e, 0x74, 0x65, 0x73, 0x74, 0x70, + 0x62, 0x2e, 0x4c, 0x69, 0x73, 0x74, 0x45, 0x78, 0x61, 0x6d, 0x70, 0x6c, 0x65, 0x41, 0x75, 0x74, + 0x6f, 0x49, 0x6e, 0x63, 0x46, 0x69, 0x65, 0x6c, 0x64, 0x4e, 0x61, 0x6d, 0x65, 0x52, 0x65, 0x71, + 0x75, 0x65, 0x73, 0x74, 0x1a, 0x2b, 0x2e, 0x74, 0x65, 0x73, 0x74, 0x70, 0x62, 0x2e, 0x4c, 0x69, 0x73, 0x74, 0x45, 0x78, 0x61, 0x6d, 0x70, 0x6c, 0x65, 0x41, 0x75, 0x74, 0x6f, 0x49, 0x6e, 0x63, - 0x46, 0x69, 0x65, 0x6c, 0x64, 0x4e, 0x61, 0x6d, 0x65, 0x52, 0x65, 0x71, 0x75, 0x65, 0x73, 0x74, - 0x1a, 0x2b, 0x2e, 0x74, 0x65, 0x73, 0x74, 0x70, 0x62, 0x2e, 0x4c, 0x69, 0x73, 0x74, 0x45, 0x78, - 0x61, 0x6d, 0x70, 0x6c, 0x65, 0x41, 0x75, 0x74, 0x6f, 0x49, 0x6e, 0x63, 0x46, 0x69, 0x65, 0x6c, - 0x64, 0x4e, 0x61, 0x6d, 0x65, 0x52, 0x65, 0x73, 0x70, 0x6f, 0x6e, 0x73, 0x65, 0x22, 0x00, 0x42, - 0x8c, 0x01, 0x0a, 0x0a, 0x63, 0x6f, 0x6d, 0x2e, 0x74, 0x65, 0x73, 0x74, 0x70, 0x62, 0x42, 0x14, - 0x54, 0x65, 0x73, 0x74, 0x53, 0x63, 0x68, 0x65, 0x6d, 0x61, 0x51, 0x75, 0x65, 0x72, 0x79, 0x50, - 0x72, 0x6f, 0x74, 0x6f, 0x50, 0x01, 0x5a, 0x30, 0x67, 0x69, 0x74, 0x68, 0x75, 0x62, 0x2e, 0x63, - 0x6f, 0x6d, 0x2f, 0x63, 0x6f, 0x73, 0x6d, 0x6f, 0x73, 0x2f, 0x63, 0x6f, 0x73, 0x6d, 0x6f, 0x73, - 0x2d, 0x73, 0x64, 0x6b, 0x2f, 0x6f, 0x72, 0x6d, 0x2f, 0x69, 0x6e, 0x74, 0x65, 0x72, 0x6e, 0x61, - 0x6c, 0x2f, 0x74, 0x65, 0x73, 0x74, 0x70, 0x62, 0xa2, 0x02, 0x03, 0x54, 0x58, 0x58, 0xaa, 0x02, - 0x06, 0x54, 0x65, 0x73, 0x74, 0x70, 0x62, 0xca, 0x02, 0x06, 0x54, 0x65, 0x73, 0x74, 0x70, 0x62, - 0xe2, 0x02, 0x12, 0x54, 0x65, 0x73, 0x74, 0x70, 0x62, 0x5c, 0x47, 0x50, 0x42, 0x4d, 0x65, 0x74, - 0x61, 0x64, 0x61, 0x74, 0x61, 0xea, 0x02, 0x06, 0x54, 0x65, 0x73, 0x74, 0x70, 0x62, 0x62, 0x06, - 0x70, 0x72, 0x6f, 0x74, 0x6f, 0x33, + 0x46, 0x69, 0x65, 0x6c, 0x64, 0x4e, 0x61, 0x6d, 0x65, 0x52, 0x65, 0x73, 0x70, 0x6f, 0x6e, 0x73, + 0x65, 0x22, 0x00, 0x42, 0x7c, 0x0a, 0x0a, 0x63, 0x6f, 0x6d, 0x2e, 0x74, 0x65, 0x73, 0x74, 0x70, + 0x62, 0x42, 0x14, 0x54, 0x65, 0x73, 0x74, 0x53, 0x63, 0x68, 0x65, 0x6d, 0x61, 0x51, 0x75, 0x65, + 0x72, 0x79, 0x50, 0x72, 0x6f, 0x74, 0x6f, 0x50, 0x01, 0x5a, 0x20, 0x63, 0x6f, 0x73, 0x6d, 0x6f, + 0x73, 0x73, 0x64, 0x6b, 0x2e, 0x69, 0x6f, 0x2f, 0x6f, 0x72, 0x6d, 0x2f, 0x69, 0x6e, 0x74, 0x65, + 0x72, 0x6e, 0x61, 0x6c, 0x2f, 0x74, 0x65, 0x73, 0x74, 0x70, 0x62, 0xa2, 0x02, 0x03, 0x54, 0x58, + 0x58, 0xaa, 0x02, 0x06, 0x54, 0x65, 0x73, 0x74, 0x70, 0x62, 0xca, 0x02, 0x06, 0x54, 0x65, 0x73, + 0x74, 0x70, 0x62, 0xe2, 0x02, 0x12, 0x54, 0x65, 0x73, 0x74, 0x70, 0x62, 0x5c, 0x47, 0x50, 0x42, + 0x4d, 0x65, 0x74, 0x61, 0x64, 0x61, 0x74, 0x61, 0xea, 0x02, 0x06, 0x54, 0x65, 0x73, 0x74, 0x70, + 0x62, 0x62, 0x06, 0x70, 0x72, 0x6f, 0x74, 0x6f, 0x33, } var ( @@ -3514,7 +4083,7 @@ func file_testpb_test_schema_query_proto_rawDescGZIP() []byte { return file_testpb_test_schema_query_proto_rawDescData } -var file_testpb_test_schema_query_proto_msgTypes = make([]protoimpl.MessageInfo, 49) +var file_testpb_test_schema_query_proto_msgTypes = make([]protoimpl.MessageInfo, 57) var file_testpb_test_schema_query_proto_goTypes = []interface{}{ (*GetExampleTableRequest)(nil), // 0: testpb.GetExampleTableRequest (*GetExampleTableResponse)(nil), // 1: testpb.GetExampleTableResponse @@ -3534,137 +4103,162 @@ var file_testpb_test_schema_query_proto_goTypes = []interface{}{ (*GetExampleTimestampResponse)(nil), // 15: testpb.GetExampleTimestampResponse (*ListExampleTimestampRequest)(nil), // 16: testpb.ListExampleTimestampRequest (*ListExampleTimestampResponse)(nil), // 17: testpb.ListExampleTimestampResponse - (*GetSimpleExampleRequest)(nil), // 18: testpb.GetSimpleExampleRequest - (*GetSimpleExampleResponse)(nil), // 19: testpb.GetSimpleExampleResponse - (*GetSimpleExampleByUniqueRequest)(nil), // 20: testpb.GetSimpleExampleByUniqueRequest - (*GetSimpleExampleByUniqueResponse)(nil), // 21: testpb.GetSimpleExampleByUniqueResponse - (*ListSimpleExampleRequest)(nil), // 22: testpb.ListSimpleExampleRequest - (*ListSimpleExampleResponse)(nil), // 23: testpb.ListSimpleExampleResponse - (*GetExampleAutoIncFieldNameRequest)(nil), // 24: testpb.GetExampleAutoIncFieldNameRequest - (*GetExampleAutoIncFieldNameResponse)(nil), // 25: testpb.GetExampleAutoIncFieldNameResponse - (*ListExampleAutoIncFieldNameRequest)(nil), // 26: testpb.ListExampleAutoIncFieldNameRequest - (*ListExampleAutoIncFieldNameResponse)(nil), // 27: testpb.ListExampleAutoIncFieldNameResponse - (*ListExampleTableRequest_IndexKey)(nil), // 28: testpb.ListExampleTableRequest.IndexKey - (*ListExampleTableRequest_RangeQuery)(nil), // 29: testpb.ListExampleTableRequest.RangeQuery - (*ListExampleTableRequest_IndexKey_U32I64Str)(nil), // 30: testpb.ListExampleTableRequest.IndexKey.U32I64Str - (*ListExampleTableRequest_IndexKey_U64Str)(nil), // 31: testpb.ListExampleTableRequest.IndexKey.U64Str - (*ListExampleTableRequest_IndexKey_StrU32)(nil), // 32: testpb.ListExampleTableRequest.IndexKey.StrU32 - (*ListExampleTableRequest_IndexKey_BzStr)(nil), // 33: testpb.ListExampleTableRequest.IndexKey.BzStr - (*ListExampleAutoIncrementTableRequest_IndexKey)(nil), // 34: testpb.ListExampleAutoIncrementTableRequest.IndexKey - (*ListExampleAutoIncrementTableRequest_RangeQuery)(nil), // 35: testpb.ListExampleAutoIncrementTableRequest.RangeQuery - (*ListExampleAutoIncrementTableRequest_IndexKey_Id)(nil), // 36: testpb.ListExampleAutoIncrementTableRequest.IndexKey.Id - (*ListExampleAutoIncrementTableRequest_IndexKey_X)(nil), // 37: testpb.ListExampleAutoIncrementTableRequest.IndexKey.X - (*ListExampleTimestampRequest_IndexKey)(nil), // 38: testpb.ListExampleTimestampRequest.IndexKey - (*ListExampleTimestampRequest_RangeQuery)(nil), // 39: testpb.ListExampleTimestampRequest.RangeQuery - (*ListExampleTimestampRequest_IndexKey_Id)(nil), // 40: testpb.ListExampleTimestampRequest.IndexKey.Id - (*ListExampleTimestampRequest_IndexKey_Ts)(nil), // 41: testpb.ListExampleTimestampRequest.IndexKey.Ts - (*ListSimpleExampleRequest_IndexKey)(nil), // 42: testpb.ListSimpleExampleRequest.IndexKey - (*ListSimpleExampleRequest_RangeQuery)(nil), // 43: testpb.ListSimpleExampleRequest.RangeQuery - (*ListSimpleExampleRequest_IndexKey_Name)(nil), // 44: testpb.ListSimpleExampleRequest.IndexKey.Name - (*ListSimpleExampleRequest_IndexKey_Unique)(nil), // 45: testpb.ListSimpleExampleRequest.IndexKey.Unique - (*ListExampleAutoIncFieldNameRequest_IndexKey)(nil), // 46: testpb.ListExampleAutoIncFieldNameRequest.IndexKey - (*ListExampleAutoIncFieldNameRequest_RangeQuery)(nil), // 47: testpb.ListExampleAutoIncFieldNameRequest.RangeQuery - (*ListExampleAutoIncFieldNameRequest_IndexKey_Foo)(nil), // 48: testpb.ListExampleAutoIncFieldNameRequest.IndexKey.Foo - (*ExampleTable)(nil), // 49: testpb.ExampleTable - (*v1beta1.PageRequest)(nil), // 50: cosmos.base.query.v1beta1.PageRequest - (*v1beta1.PageResponse)(nil), // 51: cosmos.base.query.v1beta1.PageResponse - (*ExampleAutoIncrementTable)(nil), // 52: testpb.ExampleAutoIncrementTable - (*ExampleSingleton)(nil), // 53: testpb.ExampleSingleton - (*ExampleTimestamp)(nil), // 54: testpb.ExampleTimestamp - (*SimpleExample)(nil), // 55: testpb.SimpleExample - (*ExampleAutoIncFieldName)(nil), // 56: testpb.ExampleAutoIncFieldName - (*timestamppb.Timestamp)(nil), // 57: google.protobuf.Timestamp + (*GetExampleDurationRequest)(nil), // 18: testpb.GetExampleDurationRequest + (*GetExampleDurationResponse)(nil), // 19: testpb.GetExampleDurationResponse + (*ListExampleDurationRequest)(nil), // 20: testpb.ListExampleDurationRequest + (*ListExampleDurationResponse)(nil), // 21: testpb.ListExampleDurationResponse + (*GetSimpleExampleRequest)(nil), // 22: testpb.GetSimpleExampleRequest + (*GetSimpleExampleResponse)(nil), // 23: testpb.GetSimpleExampleResponse + (*GetSimpleExampleByUniqueRequest)(nil), // 24: testpb.GetSimpleExampleByUniqueRequest + (*GetSimpleExampleByUniqueResponse)(nil), // 25: testpb.GetSimpleExampleByUniqueResponse + (*ListSimpleExampleRequest)(nil), // 26: testpb.ListSimpleExampleRequest + (*ListSimpleExampleResponse)(nil), // 27: testpb.ListSimpleExampleResponse + (*GetExampleAutoIncFieldNameRequest)(nil), // 28: testpb.GetExampleAutoIncFieldNameRequest + (*GetExampleAutoIncFieldNameResponse)(nil), // 29: testpb.GetExampleAutoIncFieldNameResponse + (*ListExampleAutoIncFieldNameRequest)(nil), // 30: testpb.ListExampleAutoIncFieldNameRequest + (*ListExampleAutoIncFieldNameResponse)(nil), // 31: testpb.ListExampleAutoIncFieldNameResponse + (*ListExampleTableRequest_IndexKey)(nil), // 32: testpb.ListExampleTableRequest.IndexKey + (*ListExampleTableRequest_RangeQuery)(nil), // 33: testpb.ListExampleTableRequest.RangeQuery + (*ListExampleTableRequest_IndexKey_U32I64Str)(nil), // 34: testpb.ListExampleTableRequest.IndexKey.U32I64Str + (*ListExampleTableRequest_IndexKey_U64Str)(nil), // 35: testpb.ListExampleTableRequest.IndexKey.U64Str + (*ListExampleTableRequest_IndexKey_StrU32)(nil), // 36: testpb.ListExampleTableRequest.IndexKey.StrU32 + (*ListExampleTableRequest_IndexKey_BzStr)(nil), // 37: testpb.ListExampleTableRequest.IndexKey.BzStr + (*ListExampleAutoIncrementTableRequest_IndexKey)(nil), // 38: testpb.ListExampleAutoIncrementTableRequest.IndexKey + (*ListExampleAutoIncrementTableRequest_RangeQuery)(nil), // 39: testpb.ListExampleAutoIncrementTableRequest.RangeQuery + (*ListExampleAutoIncrementTableRequest_IndexKey_Id)(nil), // 40: testpb.ListExampleAutoIncrementTableRequest.IndexKey.Id + (*ListExampleAutoIncrementTableRequest_IndexKey_X)(nil), // 41: testpb.ListExampleAutoIncrementTableRequest.IndexKey.X + (*ListExampleTimestampRequest_IndexKey)(nil), // 42: testpb.ListExampleTimestampRequest.IndexKey + (*ListExampleTimestampRequest_RangeQuery)(nil), // 43: testpb.ListExampleTimestampRequest.RangeQuery + (*ListExampleTimestampRequest_IndexKey_Id)(nil), // 44: testpb.ListExampleTimestampRequest.IndexKey.Id + (*ListExampleTimestampRequest_IndexKey_Ts)(nil), // 45: testpb.ListExampleTimestampRequest.IndexKey.Ts + (*ListExampleDurationRequest_IndexKey)(nil), // 46: testpb.ListExampleDurationRequest.IndexKey + (*ListExampleDurationRequest_RangeQuery)(nil), // 47: testpb.ListExampleDurationRequest.RangeQuery + (*ListExampleDurationRequest_IndexKey_Id)(nil), // 48: testpb.ListExampleDurationRequest.IndexKey.Id + (*ListExampleDurationRequest_IndexKey_Dur)(nil), // 49: testpb.ListExampleDurationRequest.IndexKey.Dur + (*ListSimpleExampleRequest_IndexKey)(nil), // 50: testpb.ListSimpleExampleRequest.IndexKey + (*ListSimpleExampleRequest_RangeQuery)(nil), // 51: testpb.ListSimpleExampleRequest.RangeQuery + (*ListSimpleExampleRequest_IndexKey_Name)(nil), // 52: testpb.ListSimpleExampleRequest.IndexKey.Name + (*ListSimpleExampleRequest_IndexKey_Unique)(nil), // 53: testpb.ListSimpleExampleRequest.IndexKey.Unique + (*ListExampleAutoIncFieldNameRequest_IndexKey)(nil), // 54: testpb.ListExampleAutoIncFieldNameRequest.IndexKey + (*ListExampleAutoIncFieldNameRequest_RangeQuery)(nil), // 55: testpb.ListExampleAutoIncFieldNameRequest.RangeQuery + (*ListExampleAutoIncFieldNameRequest_IndexKey_Foo)(nil), // 56: testpb.ListExampleAutoIncFieldNameRequest.IndexKey.Foo + (*ExampleTable)(nil), // 57: testpb.ExampleTable + (*v1beta1.PageRequest)(nil), // 58: cosmos.base.query.v1beta1.PageRequest + (*v1beta1.PageResponse)(nil), // 59: cosmos.base.query.v1beta1.PageResponse + (*ExampleAutoIncrementTable)(nil), // 60: testpb.ExampleAutoIncrementTable + (*ExampleSingleton)(nil), // 61: testpb.ExampleSingleton + (*ExampleTimestamp)(nil), // 62: testpb.ExampleTimestamp + (*ExampleDuration)(nil), // 63: testpb.ExampleDuration + (*SimpleExample)(nil), // 64: testpb.SimpleExample + (*ExampleAutoIncFieldName)(nil), // 65: testpb.ExampleAutoIncFieldName + (*timestamppb.Timestamp)(nil), // 66: google.protobuf.Timestamp + (*durationpb.Duration)(nil), // 67: google.protobuf.Duration } var file_testpb_test_schema_query_proto_depIdxs = []int32{ - 49, // 0: testpb.GetExampleTableResponse.value:type_name -> testpb.ExampleTable - 49, // 1: testpb.GetExampleTableByU64StrResponse.value:type_name -> testpb.ExampleTable - 28, // 2: testpb.ListExampleTableRequest.prefix_query:type_name -> testpb.ListExampleTableRequest.IndexKey - 29, // 3: testpb.ListExampleTableRequest.range_query:type_name -> testpb.ListExampleTableRequest.RangeQuery - 50, // 4: testpb.ListExampleTableRequest.pagination:type_name -> cosmos.base.query.v1beta1.PageRequest - 49, // 5: testpb.ListExampleTableResponse.values:type_name -> testpb.ExampleTable - 51, // 6: testpb.ListExampleTableResponse.pagination:type_name -> cosmos.base.query.v1beta1.PageResponse - 52, // 7: testpb.GetExampleAutoIncrementTableResponse.value:type_name -> testpb.ExampleAutoIncrementTable - 52, // 8: testpb.GetExampleAutoIncrementTableByXResponse.value:type_name -> testpb.ExampleAutoIncrementTable - 34, // 9: testpb.ListExampleAutoIncrementTableRequest.prefix_query:type_name -> testpb.ListExampleAutoIncrementTableRequest.IndexKey - 35, // 10: testpb.ListExampleAutoIncrementTableRequest.range_query:type_name -> testpb.ListExampleAutoIncrementTableRequest.RangeQuery - 50, // 11: testpb.ListExampleAutoIncrementTableRequest.pagination:type_name -> cosmos.base.query.v1beta1.PageRequest - 52, // 12: testpb.ListExampleAutoIncrementTableResponse.values:type_name -> testpb.ExampleAutoIncrementTable - 51, // 13: testpb.ListExampleAutoIncrementTableResponse.pagination:type_name -> cosmos.base.query.v1beta1.PageResponse - 53, // 14: testpb.GetExampleSingletonResponse.value:type_name -> testpb.ExampleSingleton - 54, // 15: testpb.GetExampleTimestampResponse.value:type_name -> testpb.ExampleTimestamp - 38, // 16: testpb.ListExampleTimestampRequest.prefix_query:type_name -> testpb.ListExampleTimestampRequest.IndexKey - 39, // 17: testpb.ListExampleTimestampRequest.range_query:type_name -> testpb.ListExampleTimestampRequest.RangeQuery - 50, // 18: testpb.ListExampleTimestampRequest.pagination:type_name -> cosmos.base.query.v1beta1.PageRequest - 54, // 19: testpb.ListExampleTimestampResponse.values:type_name -> testpb.ExampleTimestamp - 51, // 20: testpb.ListExampleTimestampResponse.pagination:type_name -> cosmos.base.query.v1beta1.PageResponse - 55, // 21: testpb.GetSimpleExampleResponse.value:type_name -> testpb.SimpleExample - 55, // 22: testpb.GetSimpleExampleByUniqueResponse.value:type_name -> testpb.SimpleExample - 42, // 23: testpb.ListSimpleExampleRequest.prefix_query:type_name -> testpb.ListSimpleExampleRequest.IndexKey - 43, // 24: testpb.ListSimpleExampleRequest.range_query:type_name -> testpb.ListSimpleExampleRequest.RangeQuery - 50, // 25: testpb.ListSimpleExampleRequest.pagination:type_name -> cosmos.base.query.v1beta1.PageRequest - 55, // 26: testpb.ListSimpleExampleResponse.values:type_name -> testpb.SimpleExample - 51, // 27: testpb.ListSimpleExampleResponse.pagination:type_name -> cosmos.base.query.v1beta1.PageResponse - 56, // 28: testpb.GetExampleAutoIncFieldNameResponse.value:type_name -> testpb.ExampleAutoIncFieldName - 46, // 29: testpb.ListExampleAutoIncFieldNameRequest.prefix_query:type_name -> testpb.ListExampleAutoIncFieldNameRequest.IndexKey - 47, // 30: testpb.ListExampleAutoIncFieldNameRequest.range_query:type_name -> testpb.ListExampleAutoIncFieldNameRequest.RangeQuery - 50, // 31: testpb.ListExampleAutoIncFieldNameRequest.pagination:type_name -> cosmos.base.query.v1beta1.PageRequest - 56, // 32: testpb.ListExampleAutoIncFieldNameResponse.values:type_name -> testpb.ExampleAutoIncFieldName - 51, // 33: testpb.ListExampleAutoIncFieldNameResponse.pagination:type_name -> cosmos.base.query.v1beta1.PageResponse - 30, // 34: testpb.ListExampleTableRequest.IndexKey.u_32_i_64_str:type_name -> testpb.ListExampleTableRequest.IndexKey.U32I64Str - 31, // 35: testpb.ListExampleTableRequest.IndexKey.u_64_str:type_name -> testpb.ListExampleTableRequest.IndexKey.U64Str - 32, // 36: testpb.ListExampleTableRequest.IndexKey.str_u_32:type_name -> testpb.ListExampleTableRequest.IndexKey.StrU32 - 33, // 37: testpb.ListExampleTableRequest.IndexKey.bz_str:type_name -> testpb.ListExampleTableRequest.IndexKey.BzStr - 28, // 38: testpb.ListExampleTableRequest.RangeQuery.from:type_name -> testpb.ListExampleTableRequest.IndexKey - 28, // 39: testpb.ListExampleTableRequest.RangeQuery.to:type_name -> testpb.ListExampleTableRequest.IndexKey - 36, // 40: testpb.ListExampleAutoIncrementTableRequest.IndexKey.id:type_name -> testpb.ListExampleAutoIncrementTableRequest.IndexKey.Id - 37, // 41: testpb.ListExampleAutoIncrementTableRequest.IndexKey.x:type_name -> testpb.ListExampleAutoIncrementTableRequest.IndexKey.X - 34, // 42: testpb.ListExampleAutoIncrementTableRequest.RangeQuery.from:type_name -> testpb.ListExampleAutoIncrementTableRequest.IndexKey - 34, // 43: testpb.ListExampleAutoIncrementTableRequest.RangeQuery.to:type_name -> testpb.ListExampleAutoIncrementTableRequest.IndexKey - 40, // 44: testpb.ListExampleTimestampRequest.IndexKey.id:type_name -> testpb.ListExampleTimestampRequest.IndexKey.Id - 41, // 45: testpb.ListExampleTimestampRequest.IndexKey.ts:type_name -> testpb.ListExampleTimestampRequest.IndexKey.Ts - 38, // 46: testpb.ListExampleTimestampRequest.RangeQuery.from:type_name -> testpb.ListExampleTimestampRequest.IndexKey - 38, // 47: testpb.ListExampleTimestampRequest.RangeQuery.to:type_name -> testpb.ListExampleTimestampRequest.IndexKey - 57, // 48: testpb.ListExampleTimestampRequest.IndexKey.Ts.ts:type_name -> google.protobuf.Timestamp - 44, // 49: testpb.ListSimpleExampleRequest.IndexKey.name:type_name -> testpb.ListSimpleExampleRequest.IndexKey.Name - 45, // 50: testpb.ListSimpleExampleRequest.IndexKey.unique:type_name -> testpb.ListSimpleExampleRequest.IndexKey.Unique - 42, // 51: testpb.ListSimpleExampleRequest.RangeQuery.from:type_name -> testpb.ListSimpleExampleRequest.IndexKey - 42, // 52: testpb.ListSimpleExampleRequest.RangeQuery.to:type_name -> testpb.ListSimpleExampleRequest.IndexKey - 48, // 53: testpb.ListExampleAutoIncFieldNameRequest.IndexKey.foo:type_name -> testpb.ListExampleAutoIncFieldNameRequest.IndexKey.Foo - 46, // 54: testpb.ListExampleAutoIncFieldNameRequest.RangeQuery.from:type_name -> testpb.ListExampleAutoIncFieldNameRequest.IndexKey - 46, // 55: testpb.ListExampleAutoIncFieldNameRequest.RangeQuery.to:type_name -> testpb.ListExampleAutoIncFieldNameRequest.IndexKey - 0, // 56: testpb.TestSchemaQueryService.GetExampleTable:input_type -> testpb.GetExampleTableRequest - 2, // 57: testpb.TestSchemaQueryService.GetExampleTableByU64Str:input_type -> testpb.GetExampleTableByU64StrRequest - 4, // 58: testpb.TestSchemaQueryService.ListExampleTable:input_type -> testpb.ListExampleTableRequest - 6, // 59: testpb.TestSchemaQueryService.GetExampleAutoIncrementTable:input_type -> testpb.GetExampleAutoIncrementTableRequest - 8, // 60: testpb.TestSchemaQueryService.GetExampleAutoIncrementTableByX:input_type -> testpb.GetExampleAutoIncrementTableByXRequest - 10, // 61: testpb.TestSchemaQueryService.ListExampleAutoIncrementTable:input_type -> testpb.ListExampleAutoIncrementTableRequest - 12, // 62: testpb.TestSchemaQueryService.GetExampleSingleton:input_type -> testpb.GetExampleSingletonRequest - 14, // 63: testpb.TestSchemaQueryService.GetExampleTimestamp:input_type -> testpb.GetExampleTimestampRequest - 16, // 64: testpb.TestSchemaQueryService.ListExampleTimestamp:input_type -> testpb.ListExampleTimestampRequest - 18, // 65: testpb.TestSchemaQueryService.GetSimpleExample:input_type -> testpb.GetSimpleExampleRequest - 20, // 66: testpb.TestSchemaQueryService.GetSimpleExampleByUnique:input_type -> testpb.GetSimpleExampleByUniqueRequest - 22, // 67: testpb.TestSchemaQueryService.ListSimpleExample:input_type -> testpb.ListSimpleExampleRequest - 24, // 68: testpb.TestSchemaQueryService.GetExampleAutoIncFieldName:input_type -> testpb.GetExampleAutoIncFieldNameRequest - 26, // 69: testpb.TestSchemaQueryService.ListExampleAutoIncFieldName:input_type -> testpb.ListExampleAutoIncFieldNameRequest - 1, // 70: testpb.TestSchemaQueryService.GetExampleTable:output_type -> testpb.GetExampleTableResponse - 3, // 71: testpb.TestSchemaQueryService.GetExampleTableByU64Str:output_type -> testpb.GetExampleTableByU64StrResponse - 5, // 72: testpb.TestSchemaQueryService.ListExampleTable:output_type -> testpb.ListExampleTableResponse - 7, // 73: testpb.TestSchemaQueryService.GetExampleAutoIncrementTable:output_type -> testpb.GetExampleAutoIncrementTableResponse - 9, // 74: testpb.TestSchemaQueryService.GetExampleAutoIncrementTableByX:output_type -> testpb.GetExampleAutoIncrementTableByXResponse - 11, // 75: testpb.TestSchemaQueryService.ListExampleAutoIncrementTable:output_type -> testpb.ListExampleAutoIncrementTableResponse - 13, // 76: testpb.TestSchemaQueryService.GetExampleSingleton:output_type -> testpb.GetExampleSingletonResponse - 15, // 77: testpb.TestSchemaQueryService.GetExampleTimestamp:output_type -> testpb.GetExampleTimestampResponse - 17, // 78: testpb.TestSchemaQueryService.ListExampleTimestamp:output_type -> testpb.ListExampleTimestampResponse - 19, // 79: testpb.TestSchemaQueryService.GetSimpleExample:output_type -> testpb.GetSimpleExampleResponse - 21, // 80: testpb.TestSchemaQueryService.GetSimpleExampleByUnique:output_type -> testpb.GetSimpleExampleByUniqueResponse - 23, // 81: testpb.TestSchemaQueryService.ListSimpleExample:output_type -> testpb.ListSimpleExampleResponse - 25, // 82: testpb.TestSchemaQueryService.GetExampleAutoIncFieldName:output_type -> testpb.GetExampleAutoIncFieldNameResponse - 27, // 83: testpb.TestSchemaQueryService.ListExampleAutoIncFieldName:output_type -> testpb.ListExampleAutoIncFieldNameResponse - 70, // [70:84] is the sub-list for method output_type - 56, // [56:70] is the sub-list for method input_type - 56, // [56:56] is the sub-list for extension type_name - 56, // [56:56] is the sub-list for extension extendee - 0, // [0:56] is the sub-list for field type_name + 57, // 0: testpb.GetExampleTableResponse.value:type_name -> testpb.ExampleTable + 57, // 1: testpb.GetExampleTableByU64StrResponse.value:type_name -> testpb.ExampleTable + 32, // 2: testpb.ListExampleTableRequest.prefix_query:type_name -> testpb.ListExampleTableRequest.IndexKey + 33, // 3: testpb.ListExampleTableRequest.range_query:type_name -> testpb.ListExampleTableRequest.RangeQuery + 58, // 4: testpb.ListExampleTableRequest.pagination:type_name -> cosmos.base.query.v1beta1.PageRequest + 57, // 5: testpb.ListExampleTableResponse.values:type_name -> testpb.ExampleTable + 59, // 6: testpb.ListExampleTableResponse.pagination:type_name -> cosmos.base.query.v1beta1.PageResponse + 60, // 7: testpb.GetExampleAutoIncrementTableResponse.value:type_name -> testpb.ExampleAutoIncrementTable + 60, // 8: testpb.GetExampleAutoIncrementTableByXResponse.value:type_name -> testpb.ExampleAutoIncrementTable + 38, // 9: testpb.ListExampleAutoIncrementTableRequest.prefix_query:type_name -> testpb.ListExampleAutoIncrementTableRequest.IndexKey + 39, // 10: testpb.ListExampleAutoIncrementTableRequest.range_query:type_name -> testpb.ListExampleAutoIncrementTableRequest.RangeQuery + 58, // 11: testpb.ListExampleAutoIncrementTableRequest.pagination:type_name -> cosmos.base.query.v1beta1.PageRequest + 60, // 12: testpb.ListExampleAutoIncrementTableResponse.values:type_name -> testpb.ExampleAutoIncrementTable + 59, // 13: testpb.ListExampleAutoIncrementTableResponse.pagination:type_name -> cosmos.base.query.v1beta1.PageResponse + 61, // 14: testpb.GetExampleSingletonResponse.value:type_name -> testpb.ExampleSingleton + 62, // 15: testpb.GetExampleTimestampResponse.value:type_name -> testpb.ExampleTimestamp + 42, // 16: testpb.ListExampleTimestampRequest.prefix_query:type_name -> testpb.ListExampleTimestampRequest.IndexKey + 43, // 17: testpb.ListExampleTimestampRequest.range_query:type_name -> testpb.ListExampleTimestampRequest.RangeQuery + 58, // 18: testpb.ListExampleTimestampRequest.pagination:type_name -> cosmos.base.query.v1beta1.PageRequest + 62, // 19: testpb.ListExampleTimestampResponse.values:type_name -> testpb.ExampleTimestamp + 59, // 20: testpb.ListExampleTimestampResponse.pagination:type_name -> cosmos.base.query.v1beta1.PageResponse + 63, // 21: testpb.GetExampleDurationResponse.value:type_name -> testpb.ExampleDuration + 46, // 22: testpb.ListExampleDurationRequest.prefix_query:type_name -> testpb.ListExampleDurationRequest.IndexKey + 47, // 23: testpb.ListExampleDurationRequest.range_query:type_name -> testpb.ListExampleDurationRequest.RangeQuery + 58, // 24: testpb.ListExampleDurationRequest.pagination:type_name -> cosmos.base.query.v1beta1.PageRequest + 63, // 25: testpb.ListExampleDurationResponse.values:type_name -> testpb.ExampleDuration + 59, // 26: testpb.ListExampleDurationResponse.pagination:type_name -> cosmos.base.query.v1beta1.PageResponse + 64, // 27: testpb.GetSimpleExampleResponse.value:type_name -> testpb.SimpleExample + 64, // 28: testpb.GetSimpleExampleByUniqueResponse.value:type_name -> testpb.SimpleExample + 50, // 29: testpb.ListSimpleExampleRequest.prefix_query:type_name -> testpb.ListSimpleExampleRequest.IndexKey + 51, // 30: testpb.ListSimpleExampleRequest.range_query:type_name -> testpb.ListSimpleExampleRequest.RangeQuery + 58, // 31: testpb.ListSimpleExampleRequest.pagination:type_name -> cosmos.base.query.v1beta1.PageRequest + 64, // 32: testpb.ListSimpleExampleResponse.values:type_name -> testpb.SimpleExample + 59, // 33: testpb.ListSimpleExampleResponse.pagination:type_name -> cosmos.base.query.v1beta1.PageResponse + 65, // 34: testpb.GetExampleAutoIncFieldNameResponse.value:type_name -> testpb.ExampleAutoIncFieldName + 54, // 35: testpb.ListExampleAutoIncFieldNameRequest.prefix_query:type_name -> testpb.ListExampleAutoIncFieldNameRequest.IndexKey + 55, // 36: testpb.ListExampleAutoIncFieldNameRequest.range_query:type_name -> testpb.ListExampleAutoIncFieldNameRequest.RangeQuery + 58, // 37: testpb.ListExampleAutoIncFieldNameRequest.pagination:type_name -> cosmos.base.query.v1beta1.PageRequest + 65, // 38: testpb.ListExampleAutoIncFieldNameResponse.values:type_name -> testpb.ExampleAutoIncFieldName + 59, // 39: testpb.ListExampleAutoIncFieldNameResponse.pagination:type_name -> cosmos.base.query.v1beta1.PageResponse + 34, // 40: testpb.ListExampleTableRequest.IndexKey.u_32_i_64_str:type_name -> testpb.ListExampleTableRequest.IndexKey.U32I64Str + 35, // 41: testpb.ListExampleTableRequest.IndexKey.u_64_str:type_name -> testpb.ListExampleTableRequest.IndexKey.U64Str + 36, // 42: testpb.ListExampleTableRequest.IndexKey.str_u_32:type_name -> testpb.ListExampleTableRequest.IndexKey.StrU32 + 37, // 43: testpb.ListExampleTableRequest.IndexKey.bz_str:type_name -> testpb.ListExampleTableRequest.IndexKey.BzStr + 32, // 44: testpb.ListExampleTableRequest.RangeQuery.from:type_name -> testpb.ListExampleTableRequest.IndexKey + 32, // 45: testpb.ListExampleTableRequest.RangeQuery.to:type_name -> testpb.ListExampleTableRequest.IndexKey + 40, // 46: testpb.ListExampleAutoIncrementTableRequest.IndexKey.id:type_name -> testpb.ListExampleAutoIncrementTableRequest.IndexKey.Id + 41, // 47: testpb.ListExampleAutoIncrementTableRequest.IndexKey.x:type_name -> testpb.ListExampleAutoIncrementTableRequest.IndexKey.X + 38, // 48: testpb.ListExampleAutoIncrementTableRequest.RangeQuery.from:type_name -> testpb.ListExampleAutoIncrementTableRequest.IndexKey + 38, // 49: testpb.ListExampleAutoIncrementTableRequest.RangeQuery.to:type_name -> testpb.ListExampleAutoIncrementTableRequest.IndexKey + 44, // 50: testpb.ListExampleTimestampRequest.IndexKey.id:type_name -> testpb.ListExampleTimestampRequest.IndexKey.Id + 45, // 51: testpb.ListExampleTimestampRequest.IndexKey.ts:type_name -> testpb.ListExampleTimestampRequest.IndexKey.Ts + 42, // 52: testpb.ListExampleTimestampRequest.RangeQuery.from:type_name -> testpb.ListExampleTimestampRequest.IndexKey + 42, // 53: testpb.ListExampleTimestampRequest.RangeQuery.to:type_name -> testpb.ListExampleTimestampRequest.IndexKey + 66, // 54: testpb.ListExampleTimestampRequest.IndexKey.Ts.ts:type_name -> google.protobuf.Timestamp + 48, // 55: testpb.ListExampleDurationRequest.IndexKey.id:type_name -> testpb.ListExampleDurationRequest.IndexKey.Id + 49, // 56: testpb.ListExampleDurationRequest.IndexKey.dur:type_name -> testpb.ListExampleDurationRequest.IndexKey.Dur + 46, // 57: testpb.ListExampleDurationRequest.RangeQuery.from:type_name -> testpb.ListExampleDurationRequest.IndexKey + 46, // 58: testpb.ListExampleDurationRequest.RangeQuery.to:type_name -> testpb.ListExampleDurationRequest.IndexKey + 67, // 59: testpb.ListExampleDurationRequest.IndexKey.Dur.dur:type_name -> google.protobuf.Duration + 52, // 60: testpb.ListSimpleExampleRequest.IndexKey.name:type_name -> testpb.ListSimpleExampleRequest.IndexKey.Name + 53, // 61: testpb.ListSimpleExampleRequest.IndexKey.unique:type_name -> testpb.ListSimpleExampleRequest.IndexKey.Unique + 50, // 62: testpb.ListSimpleExampleRequest.RangeQuery.from:type_name -> testpb.ListSimpleExampleRequest.IndexKey + 50, // 63: testpb.ListSimpleExampleRequest.RangeQuery.to:type_name -> testpb.ListSimpleExampleRequest.IndexKey + 56, // 64: testpb.ListExampleAutoIncFieldNameRequest.IndexKey.foo:type_name -> testpb.ListExampleAutoIncFieldNameRequest.IndexKey.Foo + 54, // 65: testpb.ListExampleAutoIncFieldNameRequest.RangeQuery.from:type_name -> testpb.ListExampleAutoIncFieldNameRequest.IndexKey + 54, // 66: testpb.ListExampleAutoIncFieldNameRequest.RangeQuery.to:type_name -> testpb.ListExampleAutoIncFieldNameRequest.IndexKey + 0, // 67: testpb.TestSchemaQueryService.GetExampleTable:input_type -> testpb.GetExampleTableRequest + 2, // 68: testpb.TestSchemaQueryService.GetExampleTableByU64Str:input_type -> testpb.GetExampleTableByU64StrRequest + 4, // 69: testpb.TestSchemaQueryService.ListExampleTable:input_type -> testpb.ListExampleTableRequest + 6, // 70: testpb.TestSchemaQueryService.GetExampleAutoIncrementTable:input_type -> testpb.GetExampleAutoIncrementTableRequest + 8, // 71: testpb.TestSchemaQueryService.GetExampleAutoIncrementTableByX:input_type -> testpb.GetExampleAutoIncrementTableByXRequest + 10, // 72: testpb.TestSchemaQueryService.ListExampleAutoIncrementTable:input_type -> testpb.ListExampleAutoIncrementTableRequest + 12, // 73: testpb.TestSchemaQueryService.GetExampleSingleton:input_type -> testpb.GetExampleSingletonRequest + 14, // 74: testpb.TestSchemaQueryService.GetExampleTimestamp:input_type -> testpb.GetExampleTimestampRequest + 16, // 75: testpb.TestSchemaQueryService.ListExampleTimestamp:input_type -> testpb.ListExampleTimestampRequest + 18, // 76: testpb.TestSchemaQueryService.GetExampleDuration:input_type -> testpb.GetExampleDurationRequest + 20, // 77: testpb.TestSchemaQueryService.ListExampleDuration:input_type -> testpb.ListExampleDurationRequest + 22, // 78: testpb.TestSchemaQueryService.GetSimpleExample:input_type -> testpb.GetSimpleExampleRequest + 24, // 79: testpb.TestSchemaQueryService.GetSimpleExampleByUnique:input_type -> testpb.GetSimpleExampleByUniqueRequest + 26, // 80: testpb.TestSchemaQueryService.ListSimpleExample:input_type -> testpb.ListSimpleExampleRequest + 28, // 81: testpb.TestSchemaQueryService.GetExampleAutoIncFieldName:input_type -> testpb.GetExampleAutoIncFieldNameRequest + 30, // 82: testpb.TestSchemaQueryService.ListExampleAutoIncFieldName:input_type -> testpb.ListExampleAutoIncFieldNameRequest + 1, // 83: testpb.TestSchemaQueryService.GetExampleTable:output_type -> testpb.GetExampleTableResponse + 3, // 84: testpb.TestSchemaQueryService.GetExampleTableByU64Str:output_type -> testpb.GetExampleTableByU64StrResponse + 5, // 85: testpb.TestSchemaQueryService.ListExampleTable:output_type -> testpb.ListExampleTableResponse + 7, // 86: testpb.TestSchemaQueryService.GetExampleAutoIncrementTable:output_type -> testpb.GetExampleAutoIncrementTableResponse + 9, // 87: testpb.TestSchemaQueryService.GetExampleAutoIncrementTableByX:output_type -> testpb.GetExampleAutoIncrementTableByXResponse + 11, // 88: testpb.TestSchemaQueryService.ListExampleAutoIncrementTable:output_type -> testpb.ListExampleAutoIncrementTableResponse + 13, // 89: testpb.TestSchemaQueryService.GetExampleSingleton:output_type -> testpb.GetExampleSingletonResponse + 15, // 90: testpb.TestSchemaQueryService.GetExampleTimestamp:output_type -> testpb.GetExampleTimestampResponse + 17, // 91: testpb.TestSchemaQueryService.ListExampleTimestamp:output_type -> testpb.ListExampleTimestampResponse + 19, // 92: testpb.TestSchemaQueryService.GetExampleDuration:output_type -> testpb.GetExampleDurationResponse + 21, // 93: testpb.TestSchemaQueryService.ListExampleDuration:output_type -> testpb.ListExampleDurationResponse + 23, // 94: testpb.TestSchemaQueryService.GetSimpleExample:output_type -> testpb.GetSimpleExampleResponse + 25, // 95: testpb.TestSchemaQueryService.GetSimpleExampleByUnique:output_type -> testpb.GetSimpleExampleByUniqueResponse + 27, // 96: testpb.TestSchemaQueryService.ListSimpleExample:output_type -> testpb.ListSimpleExampleResponse + 29, // 97: testpb.TestSchemaQueryService.GetExampleAutoIncFieldName:output_type -> testpb.GetExampleAutoIncFieldNameResponse + 31, // 98: testpb.TestSchemaQueryService.ListExampleAutoIncFieldName:output_type -> testpb.ListExampleAutoIncFieldNameResponse + 83, // [83:99] is the sub-list for method output_type + 67, // [67:83] is the sub-list for method input_type + 67, // [67:67] is the sub-list for extension type_name + 67, // [67:67] is the sub-list for extension extendee + 0, // [0:67] is the sub-list for field type_name } func init() { file_testpb_test_schema_query_proto_init() } @@ -3891,7 +4485,7 @@ func file_testpb_test_schema_query_proto_init() { } } file_testpb_test_schema_query_proto_msgTypes[18].Exporter = func(v interface{}, i int) interface{} { - switch v := v.(*GetSimpleExampleRequest); i { + switch v := v.(*GetExampleDurationRequest); i { case 0: return &v.state case 1: @@ -3903,7 +4497,7 @@ func file_testpb_test_schema_query_proto_init() { } } file_testpb_test_schema_query_proto_msgTypes[19].Exporter = func(v interface{}, i int) interface{} { - switch v := v.(*GetSimpleExampleResponse); i { + switch v := v.(*GetExampleDurationResponse); i { case 0: return &v.state case 1: @@ -3915,7 +4509,7 @@ func file_testpb_test_schema_query_proto_init() { } } file_testpb_test_schema_query_proto_msgTypes[20].Exporter = func(v interface{}, i int) interface{} { - switch v := v.(*GetSimpleExampleByUniqueRequest); i { + switch v := v.(*ListExampleDurationRequest); i { case 0: return &v.state case 1: @@ -3927,7 +4521,7 @@ func file_testpb_test_schema_query_proto_init() { } } file_testpb_test_schema_query_proto_msgTypes[21].Exporter = func(v interface{}, i int) interface{} { - switch v := v.(*GetSimpleExampleByUniqueResponse); i { + switch v := v.(*ListExampleDurationResponse); i { case 0: return &v.state case 1: @@ -3939,7 +4533,7 @@ func file_testpb_test_schema_query_proto_init() { } } file_testpb_test_schema_query_proto_msgTypes[22].Exporter = func(v interface{}, i int) interface{} { - switch v := v.(*ListSimpleExampleRequest); i { + switch v := v.(*GetSimpleExampleRequest); i { case 0: return &v.state case 1: @@ -3951,7 +4545,7 @@ func file_testpb_test_schema_query_proto_init() { } } file_testpb_test_schema_query_proto_msgTypes[23].Exporter = func(v interface{}, i int) interface{} { - switch v := v.(*ListSimpleExampleResponse); i { + switch v := v.(*GetSimpleExampleResponse); i { case 0: return &v.state case 1: @@ -3963,7 +4557,7 @@ func file_testpb_test_schema_query_proto_init() { } } file_testpb_test_schema_query_proto_msgTypes[24].Exporter = func(v interface{}, i int) interface{} { - switch v := v.(*GetExampleAutoIncFieldNameRequest); i { + switch v := v.(*GetSimpleExampleByUniqueRequest); i { case 0: return &v.state case 1: @@ -3975,7 +4569,7 @@ func file_testpb_test_schema_query_proto_init() { } } file_testpb_test_schema_query_proto_msgTypes[25].Exporter = func(v interface{}, i int) interface{} { - switch v := v.(*GetExampleAutoIncFieldNameResponse); i { + switch v := v.(*GetSimpleExampleByUniqueResponse); i { case 0: return &v.state case 1: @@ -3987,7 +4581,7 @@ func file_testpb_test_schema_query_proto_init() { } } file_testpb_test_schema_query_proto_msgTypes[26].Exporter = func(v interface{}, i int) interface{} { - switch v := v.(*ListExampleAutoIncFieldNameRequest); i { + switch v := v.(*ListSimpleExampleRequest); i { case 0: return &v.state case 1: @@ -3999,7 +4593,7 @@ func file_testpb_test_schema_query_proto_init() { } } file_testpb_test_schema_query_proto_msgTypes[27].Exporter = func(v interface{}, i int) interface{} { - switch v := v.(*ListExampleAutoIncFieldNameResponse); i { + switch v := v.(*ListSimpleExampleResponse); i { case 0: return &v.state case 1: @@ -4011,7 +4605,7 @@ func file_testpb_test_schema_query_proto_init() { } } file_testpb_test_schema_query_proto_msgTypes[28].Exporter = func(v interface{}, i int) interface{} { - switch v := v.(*ListExampleTableRequest_IndexKey); i { + switch v := v.(*GetExampleAutoIncFieldNameRequest); i { case 0: return &v.state case 1: @@ -4023,7 +4617,7 @@ func file_testpb_test_schema_query_proto_init() { } } file_testpb_test_schema_query_proto_msgTypes[29].Exporter = func(v interface{}, i int) interface{} { - switch v := v.(*ListExampleTableRequest_RangeQuery); i { + switch v := v.(*GetExampleAutoIncFieldNameResponse); i { case 0: return &v.state case 1: @@ -4035,7 +4629,7 @@ func file_testpb_test_schema_query_proto_init() { } } file_testpb_test_schema_query_proto_msgTypes[30].Exporter = func(v interface{}, i int) interface{} { - switch v := v.(*ListExampleTableRequest_IndexKey_U32I64Str); i { + switch v := v.(*ListExampleAutoIncFieldNameRequest); i { case 0: return &v.state case 1: @@ -4047,7 +4641,7 @@ func file_testpb_test_schema_query_proto_init() { } } file_testpb_test_schema_query_proto_msgTypes[31].Exporter = func(v interface{}, i int) interface{} { - switch v := v.(*ListExampleTableRequest_IndexKey_U64Str); i { + switch v := v.(*ListExampleAutoIncFieldNameResponse); i { case 0: return &v.state case 1: @@ -4059,7 +4653,7 @@ func file_testpb_test_schema_query_proto_init() { } } file_testpb_test_schema_query_proto_msgTypes[32].Exporter = func(v interface{}, i int) interface{} { - switch v := v.(*ListExampleTableRequest_IndexKey_StrU32); i { + switch v := v.(*ListExampleTableRequest_IndexKey); i { case 0: return &v.state case 1: @@ -4071,7 +4665,7 @@ func file_testpb_test_schema_query_proto_init() { } } file_testpb_test_schema_query_proto_msgTypes[33].Exporter = func(v interface{}, i int) interface{} { - switch v := v.(*ListExampleTableRequest_IndexKey_BzStr); i { + switch v := v.(*ListExampleTableRequest_RangeQuery); i { case 0: return &v.state case 1: @@ -4083,7 +4677,7 @@ func file_testpb_test_schema_query_proto_init() { } } file_testpb_test_schema_query_proto_msgTypes[34].Exporter = func(v interface{}, i int) interface{} { - switch v := v.(*ListExampleAutoIncrementTableRequest_IndexKey); i { + switch v := v.(*ListExampleTableRequest_IndexKey_U32I64Str); i { case 0: return &v.state case 1: @@ -4095,7 +4689,7 @@ func file_testpb_test_schema_query_proto_init() { } } file_testpb_test_schema_query_proto_msgTypes[35].Exporter = func(v interface{}, i int) interface{} { - switch v := v.(*ListExampleAutoIncrementTableRequest_RangeQuery); i { + switch v := v.(*ListExampleTableRequest_IndexKey_U64Str); i { case 0: return &v.state case 1: @@ -4107,7 +4701,7 @@ func file_testpb_test_schema_query_proto_init() { } } file_testpb_test_schema_query_proto_msgTypes[36].Exporter = func(v interface{}, i int) interface{} { - switch v := v.(*ListExampleAutoIncrementTableRequest_IndexKey_Id); i { + switch v := v.(*ListExampleTableRequest_IndexKey_StrU32); i { case 0: return &v.state case 1: @@ -4119,7 +4713,7 @@ func file_testpb_test_schema_query_proto_init() { } } file_testpb_test_schema_query_proto_msgTypes[37].Exporter = func(v interface{}, i int) interface{} { - switch v := v.(*ListExampleAutoIncrementTableRequest_IndexKey_X); i { + switch v := v.(*ListExampleTableRequest_IndexKey_BzStr); i { case 0: return &v.state case 1: @@ -4131,7 +4725,7 @@ func file_testpb_test_schema_query_proto_init() { } } file_testpb_test_schema_query_proto_msgTypes[38].Exporter = func(v interface{}, i int) interface{} { - switch v := v.(*ListExampleTimestampRequest_IndexKey); i { + switch v := v.(*ListExampleAutoIncrementTableRequest_IndexKey); i { case 0: return &v.state case 1: @@ -4143,7 +4737,7 @@ func file_testpb_test_schema_query_proto_init() { } } file_testpb_test_schema_query_proto_msgTypes[39].Exporter = func(v interface{}, i int) interface{} { - switch v := v.(*ListExampleTimestampRequest_RangeQuery); i { + switch v := v.(*ListExampleAutoIncrementTableRequest_RangeQuery); i { case 0: return &v.state case 1: @@ -4155,7 +4749,7 @@ func file_testpb_test_schema_query_proto_init() { } } file_testpb_test_schema_query_proto_msgTypes[40].Exporter = func(v interface{}, i int) interface{} { - switch v := v.(*ListExampleTimestampRequest_IndexKey_Id); i { + switch v := v.(*ListExampleAutoIncrementTableRequest_IndexKey_Id); i { case 0: return &v.state case 1: @@ -4167,7 +4761,7 @@ func file_testpb_test_schema_query_proto_init() { } } file_testpb_test_schema_query_proto_msgTypes[41].Exporter = func(v interface{}, i int) interface{} { - switch v := v.(*ListExampleTimestampRequest_IndexKey_Ts); i { + switch v := v.(*ListExampleAutoIncrementTableRequest_IndexKey_X); i { case 0: return &v.state case 1: @@ -4179,7 +4773,7 @@ func file_testpb_test_schema_query_proto_init() { } } file_testpb_test_schema_query_proto_msgTypes[42].Exporter = func(v interface{}, i int) interface{} { - switch v := v.(*ListSimpleExampleRequest_IndexKey); i { + switch v := v.(*ListExampleTimestampRequest_IndexKey); i { case 0: return &v.state case 1: @@ -4191,7 +4785,7 @@ func file_testpb_test_schema_query_proto_init() { } } file_testpb_test_schema_query_proto_msgTypes[43].Exporter = func(v interface{}, i int) interface{} { - switch v := v.(*ListSimpleExampleRequest_RangeQuery); i { + switch v := v.(*ListExampleTimestampRequest_RangeQuery); i { case 0: return &v.state case 1: @@ -4203,7 +4797,7 @@ func file_testpb_test_schema_query_proto_init() { } } file_testpb_test_schema_query_proto_msgTypes[44].Exporter = func(v interface{}, i int) interface{} { - switch v := v.(*ListSimpleExampleRequest_IndexKey_Name); i { + switch v := v.(*ListExampleTimestampRequest_IndexKey_Id); i { case 0: return &v.state case 1: @@ -4215,7 +4809,7 @@ func file_testpb_test_schema_query_proto_init() { } } file_testpb_test_schema_query_proto_msgTypes[45].Exporter = func(v interface{}, i int) interface{} { - switch v := v.(*ListSimpleExampleRequest_IndexKey_Unique); i { + switch v := v.(*ListExampleTimestampRequest_IndexKey_Ts); i { case 0: return &v.state case 1: @@ -4227,7 +4821,7 @@ func file_testpb_test_schema_query_proto_init() { } } file_testpb_test_schema_query_proto_msgTypes[46].Exporter = func(v interface{}, i int) interface{} { - switch v := v.(*ListExampleAutoIncFieldNameRequest_IndexKey); i { + switch v := v.(*ListExampleDurationRequest_IndexKey); i { case 0: return &v.state case 1: @@ -4239,7 +4833,7 @@ func file_testpb_test_schema_query_proto_init() { } } file_testpb_test_schema_query_proto_msgTypes[47].Exporter = func(v interface{}, i int) interface{} { - switch v := v.(*ListExampleAutoIncFieldNameRequest_RangeQuery); i { + switch v := v.(*ListExampleDurationRequest_RangeQuery); i { case 0: return &v.state case 1: @@ -4251,6 +4845,102 @@ func file_testpb_test_schema_query_proto_init() { } } file_testpb_test_schema_query_proto_msgTypes[48].Exporter = func(v interface{}, i int) interface{} { + switch v := v.(*ListExampleDurationRequest_IndexKey_Id); i { + case 0: + return &v.state + case 1: + return &v.sizeCache + case 2: + return &v.unknownFields + default: + return nil + } + } + file_testpb_test_schema_query_proto_msgTypes[49].Exporter = func(v interface{}, i int) interface{} { + switch v := v.(*ListExampleDurationRequest_IndexKey_Dur); i { + case 0: + return &v.state + case 1: + return &v.sizeCache + case 2: + return &v.unknownFields + default: + return nil + } + } + file_testpb_test_schema_query_proto_msgTypes[50].Exporter = func(v interface{}, i int) interface{} { + switch v := v.(*ListSimpleExampleRequest_IndexKey); i { + case 0: + return &v.state + case 1: + return &v.sizeCache + case 2: + return &v.unknownFields + default: + return nil + } + } + file_testpb_test_schema_query_proto_msgTypes[51].Exporter = func(v interface{}, i int) interface{} { + switch v := v.(*ListSimpleExampleRequest_RangeQuery); i { + case 0: + return &v.state + case 1: + return &v.sizeCache + case 2: + return &v.unknownFields + default: + return nil + } + } + file_testpb_test_schema_query_proto_msgTypes[52].Exporter = func(v interface{}, i int) interface{} { + switch v := v.(*ListSimpleExampleRequest_IndexKey_Name); i { + case 0: + return &v.state + case 1: + return &v.sizeCache + case 2: + return &v.unknownFields + default: + return nil + } + } + file_testpb_test_schema_query_proto_msgTypes[53].Exporter = func(v interface{}, i int) interface{} { + switch v := v.(*ListSimpleExampleRequest_IndexKey_Unique); i { + case 0: + return &v.state + case 1: + return &v.sizeCache + case 2: + return &v.unknownFields + default: + return nil + } + } + file_testpb_test_schema_query_proto_msgTypes[54].Exporter = func(v interface{}, i int) interface{} { + switch v := v.(*ListExampleAutoIncFieldNameRequest_IndexKey); i { + case 0: + return &v.state + case 1: + return &v.sizeCache + case 2: + return &v.unknownFields + default: + return nil + } + } + file_testpb_test_schema_query_proto_msgTypes[55].Exporter = func(v interface{}, i int) interface{} { + switch v := v.(*ListExampleAutoIncFieldNameRequest_RangeQuery); i { + case 0: + return &v.state + case 1: + return &v.sizeCache + case 2: + return &v.unknownFields + default: + return nil + } + } + file_testpb_test_schema_query_proto_msgTypes[56].Exporter = func(v interface{}, i int) interface{} { switch v := v.(*ListExampleAutoIncFieldNameRequest_IndexKey_Foo); i { case 0: return &v.state @@ -4275,53 +4965,63 @@ func file_testpb_test_schema_query_proto_init() { (*ListExampleTimestampRequest_PrefixQuery)(nil), (*ListExampleTimestampRequest_RangeQuery_)(nil), } - file_testpb_test_schema_query_proto_msgTypes[22].OneofWrappers = []interface{}{ + file_testpb_test_schema_query_proto_msgTypes[20].OneofWrappers = []interface{}{ + (*ListExampleDurationRequest_PrefixQuery)(nil), + (*ListExampleDurationRequest_RangeQuery_)(nil), + } + file_testpb_test_schema_query_proto_msgTypes[26].OneofWrappers = []interface{}{ (*ListSimpleExampleRequest_PrefixQuery)(nil), (*ListSimpleExampleRequest_RangeQuery_)(nil), } - file_testpb_test_schema_query_proto_msgTypes[26].OneofWrappers = []interface{}{ + file_testpb_test_schema_query_proto_msgTypes[30].OneofWrappers = []interface{}{ (*ListExampleAutoIncFieldNameRequest_PrefixQuery)(nil), (*ListExampleAutoIncFieldNameRequest_RangeQuery_)(nil), } - file_testpb_test_schema_query_proto_msgTypes[28].OneofWrappers = []interface{}{ + file_testpb_test_schema_query_proto_msgTypes[32].OneofWrappers = []interface{}{ (*ListExampleTableRequest_IndexKey_U_32I_64Str)(nil), (*ListExampleTableRequest_IndexKey_U_64Str)(nil), (*ListExampleTableRequest_IndexKey_StrU_32)(nil), (*ListExampleTableRequest_IndexKey_BzStr_)(nil), } - file_testpb_test_schema_query_proto_msgTypes[30].OneofWrappers = []interface{}{} - file_testpb_test_schema_query_proto_msgTypes[31].OneofWrappers = []interface{}{} - file_testpb_test_schema_query_proto_msgTypes[32].OneofWrappers = []interface{}{} - file_testpb_test_schema_query_proto_msgTypes[33].OneofWrappers = []interface{}{} - file_testpb_test_schema_query_proto_msgTypes[34].OneofWrappers = []interface{}{ - (*ListExampleAutoIncrementTableRequest_IndexKey_Id_)(nil), - (*ListExampleAutoIncrementTableRequest_IndexKey_X_)(nil), - } + file_testpb_test_schema_query_proto_msgTypes[34].OneofWrappers = []interface{}{} + file_testpb_test_schema_query_proto_msgTypes[35].OneofWrappers = []interface{}{} file_testpb_test_schema_query_proto_msgTypes[36].OneofWrappers = []interface{}{} file_testpb_test_schema_query_proto_msgTypes[37].OneofWrappers = []interface{}{} file_testpb_test_schema_query_proto_msgTypes[38].OneofWrappers = []interface{}{ - (*ListExampleTimestampRequest_IndexKey_Id_)(nil), - (*ListExampleTimestampRequest_IndexKey_Ts_)(nil), + (*ListExampleAutoIncrementTableRequest_IndexKey_Id_)(nil), + (*ListExampleAutoIncrementTableRequest_IndexKey_X_)(nil), } file_testpb_test_schema_query_proto_msgTypes[40].OneofWrappers = []interface{}{} file_testpb_test_schema_query_proto_msgTypes[41].OneofWrappers = []interface{}{} file_testpb_test_schema_query_proto_msgTypes[42].OneofWrappers = []interface{}{ - (*ListSimpleExampleRequest_IndexKey_Name_)(nil), - (*ListSimpleExampleRequest_IndexKey_Unique_)(nil), + (*ListExampleTimestampRequest_IndexKey_Id_)(nil), + (*ListExampleTimestampRequest_IndexKey_Ts_)(nil), } file_testpb_test_schema_query_proto_msgTypes[44].OneofWrappers = []interface{}{} file_testpb_test_schema_query_proto_msgTypes[45].OneofWrappers = []interface{}{} file_testpb_test_schema_query_proto_msgTypes[46].OneofWrappers = []interface{}{ - (*ListExampleAutoIncFieldNameRequest_IndexKey_Foo_)(nil), + (*ListExampleDurationRequest_IndexKey_Id_)(nil), + (*ListExampleDurationRequest_IndexKey_Dur_)(nil), } file_testpb_test_schema_query_proto_msgTypes[48].OneofWrappers = []interface{}{} + file_testpb_test_schema_query_proto_msgTypes[49].OneofWrappers = []interface{}{} + file_testpb_test_schema_query_proto_msgTypes[50].OneofWrappers = []interface{}{ + (*ListSimpleExampleRequest_IndexKey_Name_)(nil), + (*ListSimpleExampleRequest_IndexKey_Unique_)(nil), + } + file_testpb_test_schema_query_proto_msgTypes[52].OneofWrappers = []interface{}{} + file_testpb_test_schema_query_proto_msgTypes[53].OneofWrappers = []interface{}{} + file_testpb_test_schema_query_proto_msgTypes[54].OneofWrappers = []interface{}{ + (*ListExampleAutoIncFieldNameRequest_IndexKey_Foo_)(nil), + } + file_testpb_test_schema_query_proto_msgTypes[56].OneofWrappers = []interface{}{} type x struct{} out := protoimpl.TypeBuilder{ File: protoimpl.DescBuilder{ GoPackagePath: reflect.TypeOf(x{}).PkgPath(), RawDescriptor: file_testpb_test_schema_query_proto_rawDesc, NumEnums: 0, - NumMessages: 49, + NumMessages: 57, NumExtensions: 0, NumServices: 1, }, diff --git a/orm/internal/testpb/test_schema_query.proto b/orm/internal/testpb/test_schema_query.proto index c6f79a59f717..8e07ccfcfe80 100644 --- a/orm/internal/testpb/test_schema_query.proto +++ b/orm/internal/testpb/test_schema_query.proto @@ -3,6 +3,7 @@ syntax = "proto3"; package testpb; import "cosmos/base/query/v1beta1/pagination.proto"; +import "google/protobuf/duration.proto"; import "google/protobuf/timestamp.proto"; import "testpb/test_schema.proto"; @@ -15,21 +16,21 @@ service TestSchemaQueryService { // ListExampleTable queries the ExampleTable table using prefix and range queries against defined indexes. rpc ListExampleTable(ListExampleTableRequest) returns (ListExampleTableResponse) {} // Get queries the ExampleAutoIncrementTable table by its primary key. - rpc GetExampleAutoIncrementTable(GetExampleAutoIncrementTableRequest) returns (GetExampleAutoIncrementTableResponse) { - } + rpc GetExampleAutoIncrementTable(GetExampleAutoIncrementTableRequest) returns (GetExampleAutoIncrementTableResponse) {} // GetExampleAutoIncrementTableByX queries the ExampleAutoIncrementTable table by its X index - rpc GetExampleAutoIncrementTableByX(GetExampleAutoIncrementTableByXRequest) - returns (GetExampleAutoIncrementTableByXResponse) {} - // ListExampleAutoIncrementTable queries the ExampleAutoIncrementTable table using prefix and range queries against - // defined indexes. - rpc ListExampleAutoIncrementTable(ListExampleAutoIncrementTableRequest) - returns (ListExampleAutoIncrementTableResponse) {} + rpc GetExampleAutoIncrementTableByX(GetExampleAutoIncrementTableByXRequest) returns (GetExampleAutoIncrementTableByXResponse) {} + // ListExampleAutoIncrementTable queries the ExampleAutoIncrementTable table using prefix and range queries against defined indexes. + rpc ListExampleAutoIncrementTable(ListExampleAutoIncrementTableRequest) returns (ListExampleAutoIncrementTableResponse) {} // GetExampleSingleton queries the ExampleSingleton singleton. rpc GetExampleSingleton(GetExampleSingletonRequest) returns (GetExampleSingletonResponse) {} // Get queries the ExampleTimestamp table by its primary key. rpc GetExampleTimestamp(GetExampleTimestampRequest) returns (GetExampleTimestampResponse) {} // ListExampleTimestamp queries the ExampleTimestamp table using prefix and range queries against defined indexes. rpc ListExampleTimestamp(ListExampleTimestampRequest) returns (ListExampleTimestampResponse) {} + // Get queries the ExampleDuration table by its primary key. + rpc GetExampleDuration(GetExampleDurationRequest) returns (GetExampleDurationResponse) {} + // ListExampleDuration queries the ExampleDuration table using prefix and range queries against defined indexes. + rpc ListExampleDuration(ListExampleDurationRequest) returns (ListExampleDurationResponse) {} // Get queries the SimpleExample table by its primary key. rpc GetSimpleExample(GetSimpleExampleRequest) returns (GetSimpleExampleResponse) {} // GetSimpleExampleByUnique queries the SimpleExample table by its Unique index @@ -38,8 +39,7 @@ service TestSchemaQueryService { rpc ListSimpleExample(ListSimpleExampleRequest) returns (ListSimpleExampleResponse) {} // Get queries the ExampleAutoIncFieldName table by its primary key. rpc GetExampleAutoIncFieldName(GetExampleAutoIncFieldNameRequest) returns (GetExampleAutoIncFieldNameResponse) {} - // ListExampleAutoIncFieldName queries the ExampleAutoIncFieldName table using prefix and range queries against - // defined indexes. + // ListExampleAutoIncFieldName queries the ExampleAutoIncFieldName table using prefix and range queries against defined indexes. rpc ListExampleAutoIncFieldName(ListExampleAutoIncFieldNameRequest) returns (ListExampleAutoIncFieldNameResponse) {} } @@ -85,7 +85,7 @@ message ListExampleTableRequest { // bz_str specifies the value of the BzStr index key to use in the query. BzStr bz_str = 4; } - + message U32I64Str { // u32 is the value of the u32 field in the index. // It can be omitted to query for all valid values of that field in this segment of the index. @@ -97,7 +97,7 @@ message ListExampleTableRequest { // It can be omitted to query for all valid values of that field in this segment of the index. optional string str = 3; } - + message U64Str { // u64 is the value of the u64 field in the index. // It can be omitted to query for all valid values of that field in this segment of the index. @@ -106,7 +106,7 @@ message ListExampleTableRequest { // It can be omitted to query for all valid values of that field in this segment of the index. optional string str = 2; } - + message StrU32 { // str is the value of the str field in the index. // It can be omitted to query for all valid values of that field in this segment of the index. @@ -115,7 +115,7 @@ message ListExampleTableRequest { // It can be omitted to query for all valid values of that field in this segment of the index. optional uint32 u32 = 2; } - + message BzStr { // bz is the value of the bz field in the index. // It can be omitted to query for all valid values of that field in this segment of the index. @@ -125,7 +125,7 @@ message ListExampleTableRequest { optional string str = 2; } } - + // query specifies the type of query - either a prefix or range query. oneof query { // prefix_query specifies the index key value to use for the prefix query. @@ -135,7 +135,7 @@ message ListExampleTableRequest { } // pagination specifies optional pagination parameters. cosmos.base.query.v1beta1.PageRequest pagination = 3; - + // RangeQuery specifies the from/to index keys for a range query. message RangeQuery { // from is the index key to use for the start of the range query. @@ -189,20 +189,20 @@ message ListExampleAutoIncrementTableRequest { // x specifies the value of the X index key to use in the query. X x = 2; } - + message Id { // id is the value of the id field in the index. // It can be omitted to query for all valid values of that field in this segment of the index. optional uint64 id = 1; } - + message X { // x is the value of the x field in the index. // It can be omitted to query for all valid values of that field in this segment of the index. optional string x = 1; } } - + // query specifies the type of query - either a prefix or range query. oneof query { // prefix_query specifies the index key value to use for the prefix query. @@ -212,7 +212,7 @@ message ListExampleAutoIncrementTableRequest { } // pagination specifies optional pagination parameters. cosmos.base.query.v1beta1.PageRequest pagination = 3; - + // RangeQuery specifies the from/to index keys for a range query. message RangeQuery { // from is the index key to use for the start of the range query. @@ -234,7 +234,8 @@ message ListExampleAutoIncrementTableResponse { } // GetExampleSingletonRequest is the TestSchemaQuery/GetExampleSingletonRequest request type. -message GetExampleSingletonRequest {} +message GetExampleSingletonRequest { +} // GetExampleSingletonResponse is the TestSchemaQuery/GetExampleSingletonResponse request type. message GetExampleSingletonResponse { @@ -264,20 +265,20 @@ message ListExampleTimestampRequest { // ts specifies the value of the Ts index key to use in the query. Ts ts = 2; } - + message Id { // id is the value of the id field in the index. // It can be omitted to query for all valid values of that field in this segment of the index. optional uint64 id = 1; } - + message Ts { // ts is the value of the ts field in the index. // It can be omitted to query for all valid values of that field in this segment of the index. optional google.protobuf.Timestamp ts = 1; } } - + // query specifies the type of query - either a prefix or range query. oneof query { // prefix_query specifies the index key value to use for the prefix query. @@ -287,7 +288,7 @@ message ListExampleTimestampRequest { } // pagination specifies optional pagination parameters. cosmos.base.query.v1beta1.PageRequest pagination = 3; - + // RangeQuery specifies the from/to index keys for a range query. message RangeQuery { // from is the index key to use for the start of the range query. @@ -308,6 +309,73 @@ message ListExampleTimestampResponse { cosmos.base.query.v1beta1.PageResponse pagination = 2; } +// GetExampleDurationRequest is the TestSchemaQuery/GetExampleDurationRequest request type. +message GetExampleDurationRequest { + // id specifies the value of the id field in the primary key. + uint64 id = 1; +} + +// GetExampleDurationResponse is the TestSchemaQuery/GetExampleDurationResponse response type. +message GetExampleDurationResponse { + // value is the response value. + ExampleDuration value = 1; +} + +// ListExampleDurationRequest is the TestSchemaQuery/ListExampleDurationRequest request type. +message ListExampleDurationRequest { + // IndexKey specifies the value of an index key to use in prefix and range queries. + message IndexKey { + // key specifies the index key value. + oneof key { + // id specifies the value of the Id index key to use in the query. + Id id = 1; + // dur specifies the value of the Dur index key to use in the query. + Dur dur = 2; + } + + message Id { + // id is the value of the id field in the index. + // It can be omitted to query for all valid values of that field in this segment of the index. + optional uint64 id = 1; + } + + message Dur { + // dur is the value of the dur field in the index. + // It can be omitted to query for all valid values of that field in this segment of the index. + optional google.protobuf.Duration dur = 1; + } + } + + // query specifies the type of query - either a prefix or range query. + oneof query { + // prefix_query specifies the index key value to use for the prefix query. + IndexKey prefix_query = 1; + // range_query specifies the index key from/to values to use for the range query. + RangeQuery range_query = 2; + } + // pagination specifies optional pagination parameters. + cosmos.base.query.v1beta1.PageRequest pagination = 3; + + // RangeQuery specifies the from/to index keys for a range query. + message RangeQuery { + // from is the index key to use for the start of the range query. + // To query from the start of an index, specify an index key for that index with empty values. + IndexKey from = 1; + // to is the index key to use for the end of the range query. + // The index key type MUST be the same as the index key type used for from. + // To query from to the end of an index it can be omitted. + IndexKey to = 2; + } +} + +// ListExampleDurationResponse is the TestSchemaQuery/ListExampleDurationResponse response type. +message ListExampleDurationResponse { + // values are the results of the query. + repeated ExampleDuration values = 1; + // pagination is the pagination response. + cosmos.base.query.v1beta1.PageResponse pagination = 2; +} + // GetSimpleExampleRequest is the TestSchemaQuery/GetSimpleExampleRequest request type. message GetSimpleExampleRequest { // name specifies the value of the name field in the primary key. @@ -341,20 +409,20 @@ message ListSimpleExampleRequest { // unique specifies the value of the Unique index key to use in the query. Unique unique = 2; } - + message Name { // name is the value of the name field in the index. // It can be omitted to query for all valid values of that field in this segment of the index. optional string name = 1; } - + message Unique { // unique is the value of the unique field in the index. // It can be omitted to query for all valid values of that field in this segment of the index. optional string unique = 1; } } - + // query specifies the type of query - either a prefix or range query. oneof query { // prefix_query specifies the index key value to use for the prefix query. @@ -364,7 +432,7 @@ message ListSimpleExampleRequest { } // pagination specifies optional pagination parameters. cosmos.base.query.v1beta1.PageRequest pagination = 3; - + // RangeQuery specifies the from/to index keys for a range query. message RangeQuery { // from is the index key to use for the start of the range query. @@ -406,14 +474,14 @@ message ListExampleAutoIncFieldNameRequest { // foo specifies the value of the Foo index key to use in the query. Foo foo = 1; } - + message Foo { // foo is the value of the foo field in the index. // It can be omitted to query for all valid values of that field in this segment of the index. optional uint64 foo = 1; } } - + // query specifies the type of query - either a prefix or range query. oneof query { // prefix_query specifies the index key value to use for the prefix query. @@ -423,7 +491,7 @@ message ListExampleAutoIncFieldNameRequest { } // pagination specifies optional pagination parameters. cosmos.base.query.v1beta1.PageRequest pagination = 3; - + // RangeQuery specifies the from/to index keys for a range query. message RangeQuery { // from is the index key to use for the start of the range query. @@ -443,3 +511,4 @@ message ListExampleAutoIncFieldNameResponse { // pagination is the pagination response. cosmos.base.query.v1beta1.PageResponse pagination = 2; } + diff --git a/orm/internal/testpb/test_schema_query_grpc.pb.go b/orm/internal/testpb/test_schema_query_grpc.pb.go index 61f5da6fb11c..3043f57c516d 100644 --- a/orm/internal/testpb/test_schema_query_grpc.pb.go +++ b/orm/internal/testpb/test_schema_query_grpc.pb.go @@ -1,6 +1,8 @@ +// Code generated by protoc-gen-go-cosmos-orm-proto. DO NOT EDIT. + // Code generated by protoc-gen-go-grpc. DO NOT EDIT. // versions: -// - protoc-gen-go-grpc v1.2.0 +// - protoc-gen-go-grpc v1.3.0 // - protoc (unknown) // source: testpb/test_schema_query.proto @@ -18,6 +20,25 @@ import ( // Requires gRPC-Go v1.32.0 or later. const _ = grpc.SupportPackageIsVersion7 +const ( + TestSchemaQueryService_GetExampleTable_FullMethodName = "/testpb.TestSchemaQueryService/GetExampleTable" + TestSchemaQueryService_GetExampleTableByU64Str_FullMethodName = "/testpb.TestSchemaQueryService/GetExampleTableByU64Str" + TestSchemaQueryService_ListExampleTable_FullMethodName = "/testpb.TestSchemaQueryService/ListExampleTable" + TestSchemaQueryService_GetExampleAutoIncrementTable_FullMethodName = "/testpb.TestSchemaQueryService/GetExampleAutoIncrementTable" + TestSchemaQueryService_GetExampleAutoIncrementTableByX_FullMethodName = "/testpb.TestSchemaQueryService/GetExampleAutoIncrementTableByX" + TestSchemaQueryService_ListExampleAutoIncrementTable_FullMethodName = "/testpb.TestSchemaQueryService/ListExampleAutoIncrementTable" + TestSchemaQueryService_GetExampleSingleton_FullMethodName = "/testpb.TestSchemaQueryService/GetExampleSingleton" + TestSchemaQueryService_GetExampleTimestamp_FullMethodName = "/testpb.TestSchemaQueryService/GetExampleTimestamp" + TestSchemaQueryService_ListExampleTimestamp_FullMethodName = "/testpb.TestSchemaQueryService/ListExampleTimestamp" + TestSchemaQueryService_GetExampleDuration_FullMethodName = "/testpb.TestSchemaQueryService/GetExampleDuration" + TestSchemaQueryService_ListExampleDuration_FullMethodName = "/testpb.TestSchemaQueryService/ListExampleDuration" + TestSchemaQueryService_GetSimpleExample_FullMethodName = "/testpb.TestSchemaQueryService/GetSimpleExample" + TestSchemaQueryService_GetSimpleExampleByUnique_FullMethodName = "/testpb.TestSchemaQueryService/GetSimpleExampleByUnique" + TestSchemaQueryService_ListSimpleExample_FullMethodName = "/testpb.TestSchemaQueryService/ListSimpleExample" + TestSchemaQueryService_GetExampleAutoIncFieldName_FullMethodName = "/testpb.TestSchemaQueryService/GetExampleAutoIncFieldName" + TestSchemaQueryService_ListExampleAutoIncFieldName_FullMethodName = "/testpb.TestSchemaQueryService/ListExampleAutoIncFieldName" +) + // TestSchemaQueryServiceClient is the client API for TestSchemaQueryService service. // // For semantics around ctx use and closing/ending streaming RPCs, please refer to https://pkg.go.dev/google.golang.org/grpc/?tab=doc#ClientConn.NewStream. @@ -40,6 +61,10 @@ type TestSchemaQueryServiceClient interface { GetExampleTimestamp(ctx context.Context, in *GetExampleTimestampRequest, opts ...grpc.CallOption) (*GetExampleTimestampResponse, error) // ListExampleTimestamp queries the ExampleTimestamp table using prefix and range queries against defined indexes. ListExampleTimestamp(ctx context.Context, in *ListExampleTimestampRequest, opts ...grpc.CallOption) (*ListExampleTimestampResponse, error) + // Get queries the ExampleDuration table by its primary key. + GetExampleDuration(ctx context.Context, in *GetExampleDurationRequest, opts ...grpc.CallOption) (*GetExampleDurationResponse, error) + // ListExampleDuration queries the ExampleDuration table using prefix and range queries against defined indexes. + ListExampleDuration(ctx context.Context, in *ListExampleDurationRequest, opts ...grpc.CallOption) (*ListExampleDurationResponse, error) // Get queries the SimpleExample table by its primary key. GetSimpleExample(ctx context.Context, in *GetSimpleExampleRequest, opts ...grpc.CallOption) (*GetSimpleExampleResponse, error) // GetSimpleExampleByUnique queries the SimpleExample table by its Unique index @@ -62,7 +87,7 @@ func NewTestSchemaQueryServiceClient(cc grpc.ClientConnInterface) TestSchemaQuer func (c *testSchemaQueryServiceClient) GetExampleTable(ctx context.Context, in *GetExampleTableRequest, opts ...grpc.CallOption) (*GetExampleTableResponse, error) { out := new(GetExampleTableResponse) - err := c.cc.Invoke(ctx, "/testpb.TestSchemaQueryService/GetExampleTable", in, out, opts...) + err := c.cc.Invoke(ctx, TestSchemaQueryService_GetExampleTable_FullMethodName, in, out, opts...) if err != nil { return nil, err } @@ -71,7 +96,7 @@ func (c *testSchemaQueryServiceClient) GetExampleTable(ctx context.Context, in * func (c *testSchemaQueryServiceClient) GetExampleTableByU64Str(ctx context.Context, in *GetExampleTableByU64StrRequest, opts ...grpc.CallOption) (*GetExampleTableByU64StrResponse, error) { out := new(GetExampleTableByU64StrResponse) - err := c.cc.Invoke(ctx, "/testpb.TestSchemaQueryService/GetExampleTableByU64Str", in, out, opts...) + err := c.cc.Invoke(ctx, TestSchemaQueryService_GetExampleTableByU64Str_FullMethodName, in, out, opts...) if err != nil { return nil, err } @@ -80,7 +105,7 @@ func (c *testSchemaQueryServiceClient) GetExampleTableByU64Str(ctx context.Conte func (c *testSchemaQueryServiceClient) ListExampleTable(ctx context.Context, in *ListExampleTableRequest, opts ...grpc.CallOption) (*ListExampleTableResponse, error) { out := new(ListExampleTableResponse) - err := c.cc.Invoke(ctx, "/testpb.TestSchemaQueryService/ListExampleTable", in, out, opts...) + err := c.cc.Invoke(ctx, TestSchemaQueryService_ListExampleTable_FullMethodName, in, out, opts...) if err != nil { return nil, err } @@ -89,7 +114,7 @@ func (c *testSchemaQueryServiceClient) ListExampleTable(ctx context.Context, in func (c *testSchemaQueryServiceClient) GetExampleAutoIncrementTable(ctx context.Context, in *GetExampleAutoIncrementTableRequest, opts ...grpc.CallOption) (*GetExampleAutoIncrementTableResponse, error) { out := new(GetExampleAutoIncrementTableResponse) - err := c.cc.Invoke(ctx, "/testpb.TestSchemaQueryService/GetExampleAutoIncrementTable", in, out, opts...) + err := c.cc.Invoke(ctx, TestSchemaQueryService_GetExampleAutoIncrementTable_FullMethodName, in, out, opts...) if err != nil { return nil, err } @@ -98,7 +123,7 @@ func (c *testSchemaQueryServiceClient) GetExampleAutoIncrementTable(ctx context. func (c *testSchemaQueryServiceClient) GetExampleAutoIncrementTableByX(ctx context.Context, in *GetExampleAutoIncrementTableByXRequest, opts ...grpc.CallOption) (*GetExampleAutoIncrementTableByXResponse, error) { out := new(GetExampleAutoIncrementTableByXResponse) - err := c.cc.Invoke(ctx, "/testpb.TestSchemaQueryService/GetExampleAutoIncrementTableByX", in, out, opts...) + err := c.cc.Invoke(ctx, TestSchemaQueryService_GetExampleAutoIncrementTableByX_FullMethodName, in, out, opts...) if err != nil { return nil, err } @@ -107,7 +132,7 @@ func (c *testSchemaQueryServiceClient) GetExampleAutoIncrementTableByX(ctx conte func (c *testSchemaQueryServiceClient) ListExampleAutoIncrementTable(ctx context.Context, in *ListExampleAutoIncrementTableRequest, opts ...grpc.CallOption) (*ListExampleAutoIncrementTableResponse, error) { out := new(ListExampleAutoIncrementTableResponse) - err := c.cc.Invoke(ctx, "/testpb.TestSchemaQueryService/ListExampleAutoIncrementTable", in, out, opts...) + err := c.cc.Invoke(ctx, TestSchemaQueryService_ListExampleAutoIncrementTable_FullMethodName, in, out, opts...) if err != nil { return nil, err } @@ -116,7 +141,7 @@ func (c *testSchemaQueryServiceClient) ListExampleAutoIncrementTable(ctx context func (c *testSchemaQueryServiceClient) GetExampleSingleton(ctx context.Context, in *GetExampleSingletonRequest, opts ...grpc.CallOption) (*GetExampleSingletonResponse, error) { out := new(GetExampleSingletonResponse) - err := c.cc.Invoke(ctx, "/testpb.TestSchemaQueryService/GetExampleSingleton", in, out, opts...) + err := c.cc.Invoke(ctx, TestSchemaQueryService_GetExampleSingleton_FullMethodName, in, out, opts...) if err != nil { return nil, err } @@ -125,7 +150,7 @@ func (c *testSchemaQueryServiceClient) GetExampleSingleton(ctx context.Context, func (c *testSchemaQueryServiceClient) GetExampleTimestamp(ctx context.Context, in *GetExampleTimestampRequest, opts ...grpc.CallOption) (*GetExampleTimestampResponse, error) { out := new(GetExampleTimestampResponse) - err := c.cc.Invoke(ctx, "/testpb.TestSchemaQueryService/GetExampleTimestamp", in, out, opts...) + err := c.cc.Invoke(ctx, TestSchemaQueryService_GetExampleTimestamp_FullMethodName, in, out, opts...) if err != nil { return nil, err } @@ -134,7 +159,25 @@ func (c *testSchemaQueryServiceClient) GetExampleTimestamp(ctx context.Context, func (c *testSchemaQueryServiceClient) ListExampleTimestamp(ctx context.Context, in *ListExampleTimestampRequest, opts ...grpc.CallOption) (*ListExampleTimestampResponse, error) { out := new(ListExampleTimestampResponse) - err := c.cc.Invoke(ctx, "/testpb.TestSchemaQueryService/ListExampleTimestamp", in, out, opts...) + err := c.cc.Invoke(ctx, TestSchemaQueryService_ListExampleTimestamp_FullMethodName, in, out, opts...) + if err != nil { + return nil, err + } + return out, nil +} + +func (c *testSchemaQueryServiceClient) GetExampleDuration(ctx context.Context, in *GetExampleDurationRequest, opts ...grpc.CallOption) (*GetExampleDurationResponse, error) { + out := new(GetExampleDurationResponse) + err := c.cc.Invoke(ctx, TestSchemaQueryService_GetExampleDuration_FullMethodName, in, out, opts...) + if err != nil { + return nil, err + } + return out, nil +} + +func (c *testSchemaQueryServiceClient) ListExampleDuration(ctx context.Context, in *ListExampleDurationRequest, opts ...grpc.CallOption) (*ListExampleDurationResponse, error) { + out := new(ListExampleDurationResponse) + err := c.cc.Invoke(ctx, TestSchemaQueryService_ListExampleDuration_FullMethodName, in, out, opts...) if err != nil { return nil, err } @@ -143,7 +186,7 @@ func (c *testSchemaQueryServiceClient) ListExampleTimestamp(ctx context.Context, func (c *testSchemaQueryServiceClient) GetSimpleExample(ctx context.Context, in *GetSimpleExampleRequest, opts ...grpc.CallOption) (*GetSimpleExampleResponse, error) { out := new(GetSimpleExampleResponse) - err := c.cc.Invoke(ctx, "/testpb.TestSchemaQueryService/GetSimpleExample", in, out, opts...) + err := c.cc.Invoke(ctx, TestSchemaQueryService_GetSimpleExample_FullMethodName, in, out, opts...) if err != nil { return nil, err } @@ -152,7 +195,7 @@ func (c *testSchemaQueryServiceClient) GetSimpleExample(ctx context.Context, in func (c *testSchemaQueryServiceClient) GetSimpleExampleByUnique(ctx context.Context, in *GetSimpleExampleByUniqueRequest, opts ...grpc.CallOption) (*GetSimpleExampleByUniqueResponse, error) { out := new(GetSimpleExampleByUniqueResponse) - err := c.cc.Invoke(ctx, "/testpb.TestSchemaQueryService/GetSimpleExampleByUnique", in, out, opts...) + err := c.cc.Invoke(ctx, TestSchemaQueryService_GetSimpleExampleByUnique_FullMethodName, in, out, opts...) if err != nil { return nil, err } @@ -161,7 +204,7 @@ func (c *testSchemaQueryServiceClient) GetSimpleExampleByUnique(ctx context.Cont func (c *testSchemaQueryServiceClient) ListSimpleExample(ctx context.Context, in *ListSimpleExampleRequest, opts ...grpc.CallOption) (*ListSimpleExampleResponse, error) { out := new(ListSimpleExampleResponse) - err := c.cc.Invoke(ctx, "/testpb.TestSchemaQueryService/ListSimpleExample", in, out, opts...) + err := c.cc.Invoke(ctx, TestSchemaQueryService_ListSimpleExample_FullMethodName, in, out, opts...) if err != nil { return nil, err } @@ -170,7 +213,7 @@ func (c *testSchemaQueryServiceClient) ListSimpleExample(ctx context.Context, in func (c *testSchemaQueryServiceClient) GetExampleAutoIncFieldName(ctx context.Context, in *GetExampleAutoIncFieldNameRequest, opts ...grpc.CallOption) (*GetExampleAutoIncFieldNameResponse, error) { out := new(GetExampleAutoIncFieldNameResponse) - err := c.cc.Invoke(ctx, "/testpb.TestSchemaQueryService/GetExampleAutoIncFieldName", in, out, opts...) + err := c.cc.Invoke(ctx, TestSchemaQueryService_GetExampleAutoIncFieldName_FullMethodName, in, out, opts...) if err != nil { return nil, err } @@ -179,7 +222,7 @@ func (c *testSchemaQueryServiceClient) GetExampleAutoIncFieldName(ctx context.Co func (c *testSchemaQueryServiceClient) ListExampleAutoIncFieldName(ctx context.Context, in *ListExampleAutoIncFieldNameRequest, opts ...grpc.CallOption) (*ListExampleAutoIncFieldNameResponse, error) { out := new(ListExampleAutoIncFieldNameResponse) - err := c.cc.Invoke(ctx, "/testpb.TestSchemaQueryService/ListExampleAutoIncFieldName", in, out, opts...) + err := c.cc.Invoke(ctx, TestSchemaQueryService_ListExampleAutoIncFieldName_FullMethodName, in, out, opts...) if err != nil { return nil, err } @@ -208,6 +251,10 @@ type TestSchemaQueryServiceServer interface { GetExampleTimestamp(context.Context, *GetExampleTimestampRequest) (*GetExampleTimestampResponse, error) // ListExampleTimestamp queries the ExampleTimestamp table using prefix and range queries against defined indexes. ListExampleTimestamp(context.Context, *ListExampleTimestampRequest) (*ListExampleTimestampResponse, error) + // Get queries the ExampleDuration table by its primary key. + GetExampleDuration(context.Context, *GetExampleDurationRequest) (*GetExampleDurationResponse, error) + // ListExampleDuration queries the ExampleDuration table using prefix and range queries against defined indexes. + ListExampleDuration(context.Context, *ListExampleDurationRequest) (*ListExampleDurationResponse, error) // Get queries the SimpleExample table by its primary key. GetSimpleExample(context.Context, *GetSimpleExampleRequest) (*GetSimpleExampleResponse, error) // GetSimpleExampleByUnique queries the SimpleExample table by its Unique index @@ -252,6 +299,12 @@ func (UnimplementedTestSchemaQueryServiceServer) GetExampleTimestamp(context.Con func (UnimplementedTestSchemaQueryServiceServer) ListExampleTimestamp(context.Context, *ListExampleTimestampRequest) (*ListExampleTimestampResponse, error) { return nil, status.Errorf(codes.Unimplemented, "method ListExampleTimestamp not implemented") } +func (UnimplementedTestSchemaQueryServiceServer) GetExampleDuration(context.Context, *GetExampleDurationRequest) (*GetExampleDurationResponse, error) { + return nil, status.Errorf(codes.Unimplemented, "method GetExampleDuration not implemented") +} +func (UnimplementedTestSchemaQueryServiceServer) ListExampleDuration(context.Context, *ListExampleDurationRequest) (*ListExampleDurationResponse, error) { + return nil, status.Errorf(codes.Unimplemented, "method ListExampleDuration not implemented") +} func (UnimplementedTestSchemaQueryServiceServer) GetSimpleExample(context.Context, *GetSimpleExampleRequest) (*GetSimpleExampleResponse, error) { return nil, status.Errorf(codes.Unimplemented, "method GetSimpleExample not implemented") } @@ -291,7 +344,7 @@ func _TestSchemaQueryService_GetExampleTable_Handler(srv interface{}, ctx contex } info := &grpc.UnaryServerInfo{ Server: srv, - FullMethod: "/testpb.TestSchemaQueryService/GetExampleTable", + FullMethod: TestSchemaQueryService_GetExampleTable_FullMethodName, } handler := func(ctx context.Context, req interface{}) (interface{}, error) { return srv.(TestSchemaQueryServiceServer).GetExampleTable(ctx, req.(*GetExampleTableRequest)) @@ -309,7 +362,7 @@ func _TestSchemaQueryService_GetExampleTableByU64Str_Handler(srv interface{}, ct } info := &grpc.UnaryServerInfo{ Server: srv, - FullMethod: "/testpb.TestSchemaQueryService/GetExampleTableByU64Str", + FullMethod: TestSchemaQueryService_GetExampleTableByU64Str_FullMethodName, } handler := func(ctx context.Context, req interface{}) (interface{}, error) { return srv.(TestSchemaQueryServiceServer).GetExampleTableByU64Str(ctx, req.(*GetExampleTableByU64StrRequest)) @@ -327,7 +380,7 @@ func _TestSchemaQueryService_ListExampleTable_Handler(srv interface{}, ctx conte } info := &grpc.UnaryServerInfo{ Server: srv, - FullMethod: "/testpb.TestSchemaQueryService/ListExampleTable", + FullMethod: TestSchemaQueryService_ListExampleTable_FullMethodName, } handler := func(ctx context.Context, req interface{}) (interface{}, error) { return srv.(TestSchemaQueryServiceServer).ListExampleTable(ctx, req.(*ListExampleTableRequest)) @@ -345,7 +398,7 @@ func _TestSchemaQueryService_GetExampleAutoIncrementTable_Handler(srv interface{ } info := &grpc.UnaryServerInfo{ Server: srv, - FullMethod: "/testpb.TestSchemaQueryService/GetExampleAutoIncrementTable", + FullMethod: TestSchemaQueryService_GetExampleAutoIncrementTable_FullMethodName, } handler := func(ctx context.Context, req interface{}) (interface{}, error) { return srv.(TestSchemaQueryServiceServer).GetExampleAutoIncrementTable(ctx, req.(*GetExampleAutoIncrementTableRequest)) @@ -363,7 +416,7 @@ func _TestSchemaQueryService_GetExampleAutoIncrementTableByX_Handler(srv interfa } info := &grpc.UnaryServerInfo{ Server: srv, - FullMethod: "/testpb.TestSchemaQueryService/GetExampleAutoIncrementTableByX", + FullMethod: TestSchemaQueryService_GetExampleAutoIncrementTableByX_FullMethodName, } handler := func(ctx context.Context, req interface{}) (interface{}, error) { return srv.(TestSchemaQueryServiceServer).GetExampleAutoIncrementTableByX(ctx, req.(*GetExampleAutoIncrementTableByXRequest)) @@ -381,7 +434,7 @@ func _TestSchemaQueryService_ListExampleAutoIncrementTable_Handler(srv interface } info := &grpc.UnaryServerInfo{ Server: srv, - FullMethod: "/testpb.TestSchemaQueryService/ListExampleAutoIncrementTable", + FullMethod: TestSchemaQueryService_ListExampleAutoIncrementTable_FullMethodName, } handler := func(ctx context.Context, req interface{}) (interface{}, error) { return srv.(TestSchemaQueryServiceServer).ListExampleAutoIncrementTable(ctx, req.(*ListExampleAutoIncrementTableRequest)) @@ -399,7 +452,7 @@ func _TestSchemaQueryService_GetExampleSingleton_Handler(srv interface{}, ctx co } info := &grpc.UnaryServerInfo{ Server: srv, - FullMethod: "/testpb.TestSchemaQueryService/GetExampleSingleton", + FullMethod: TestSchemaQueryService_GetExampleSingleton_FullMethodName, } handler := func(ctx context.Context, req interface{}) (interface{}, error) { return srv.(TestSchemaQueryServiceServer).GetExampleSingleton(ctx, req.(*GetExampleSingletonRequest)) @@ -417,7 +470,7 @@ func _TestSchemaQueryService_GetExampleTimestamp_Handler(srv interface{}, ctx co } info := &grpc.UnaryServerInfo{ Server: srv, - FullMethod: "/testpb.TestSchemaQueryService/GetExampleTimestamp", + FullMethod: TestSchemaQueryService_GetExampleTimestamp_FullMethodName, } handler := func(ctx context.Context, req interface{}) (interface{}, error) { return srv.(TestSchemaQueryServiceServer).GetExampleTimestamp(ctx, req.(*GetExampleTimestampRequest)) @@ -435,7 +488,7 @@ func _TestSchemaQueryService_ListExampleTimestamp_Handler(srv interface{}, ctx c } info := &grpc.UnaryServerInfo{ Server: srv, - FullMethod: "/testpb.TestSchemaQueryService/ListExampleTimestamp", + FullMethod: TestSchemaQueryService_ListExampleTimestamp_FullMethodName, } handler := func(ctx context.Context, req interface{}) (interface{}, error) { return srv.(TestSchemaQueryServiceServer).ListExampleTimestamp(ctx, req.(*ListExampleTimestampRequest)) @@ -443,6 +496,42 @@ func _TestSchemaQueryService_ListExampleTimestamp_Handler(srv interface{}, ctx c return interceptor(ctx, in, info, handler) } +func _TestSchemaQueryService_GetExampleDuration_Handler(srv interface{}, ctx context.Context, dec func(interface{}) error, interceptor grpc.UnaryServerInterceptor) (interface{}, error) { + in := new(GetExampleDurationRequest) + if err := dec(in); err != nil { + return nil, err + } + if interceptor == nil { + return srv.(TestSchemaQueryServiceServer).GetExampleDuration(ctx, in) + } + info := &grpc.UnaryServerInfo{ + Server: srv, + FullMethod: TestSchemaQueryService_GetExampleDuration_FullMethodName, + } + handler := func(ctx context.Context, req interface{}) (interface{}, error) { + return srv.(TestSchemaQueryServiceServer).GetExampleDuration(ctx, req.(*GetExampleDurationRequest)) + } + return interceptor(ctx, in, info, handler) +} + +func _TestSchemaQueryService_ListExampleDuration_Handler(srv interface{}, ctx context.Context, dec func(interface{}) error, interceptor grpc.UnaryServerInterceptor) (interface{}, error) { + in := new(ListExampleDurationRequest) + if err := dec(in); err != nil { + return nil, err + } + if interceptor == nil { + return srv.(TestSchemaQueryServiceServer).ListExampleDuration(ctx, in) + } + info := &grpc.UnaryServerInfo{ + Server: srv, + FullMethod: TestSchemaQueryService_ListExampleDuration_FullMethodName, + } + handler := func(ctx context.Context, req interface{}) (interface{}, error) { + return srv.(TestSchemaQueryServiceServer).ListExampleDuration(ctx, req.(*ListExampleDurationRequest)) + } + return interceptor(ctx, in, info, handler) +} + func _TestSchemaQueryService_GetSimpleExample_Handler(srv interface{}, ctx context.Context, dec func(interface{}) error, interceptor grpc.UnaryServerInterceptor) (interface{}, error) { in := new(GetSimpleExampleRequest) if err := dec(in); err != nil { @@ -453,7 +542,7 @@ func _TestSchemaQueryService_GetSimpleExample_Handler(srv interface{}, ctx conte } info := &grpc.UnaryServerInfo{ Server: srv, - FullMethod: "/testpb.TestSchemaQueryService/GetSimpleExample", + FullMethod: TestSchemaQueryService_GetSimpleExample_FullMethodName, } handler := func(ctx context.Context, req interface{}) (interface{}, error) { return srv.(TestSchemaQueryServiceServer).GetSimpleExample(ctx, req.(*GetSimpleExampleRequest)) @@ -471,7 +560,7 @@ func _TestSchemaQueryService_GetSimpleExampleByUnique_Handler(srv interface{}, c } info := &grpc.UnaryServerInfo{ Server: srv, - FullMethod: "/testpb.TestSchemaQueryService/GetSimpleExampleByUnique", + FullMethod: TestSchemaQueryService_GetSimpleExampleByUnique_FullMethodName, } handler := func(ctx context.Context, req interface{}) (interface{}, error) { return srv.(TestSchemaQueryServiceServer).GetSimpleExampleByUnique(ctx, req.(*GetSimpleExampleByUniqueRequest)) @@ -489,7 +578,7 @@ func _TestSchemaQueryService_ListSimpleExample_Handler(srv interface{}, ctx cont } info := &grpc.UnaryServerInfo{ Server: srv, - FullMethod: "/testpb.TestSchemaQueryService/ListSimpleExample", + FullMethod: TestSchemaQueryService_ListSimpleExample_FullMethodName, } handler := func(ctx context.Context, req interface{}) (interface{}, error) { return srv.(TestSchemaQueryServiceServer).ListSimpleExample(ctx, req.(*ListSimpleExampleRequest)) @@ -507,7 +596,7 @@ func _TestSchemaQueryService_GetExampleAutoIncFieldName_Handler(srv interface{}, } info := &grpc.UnaryServerInfo{ Server: srv, - FullMethod: "/testpb.TestSchemaQueryService/GetExampleAutoIncFieldName", + FullMethod: TestSchemaQueryService_GetExampleAutoIncFieldName_FullMethodName, } handler := func(ctx context.Context, req interface{}) (interface{}, error) { return srv.(TestSchemaQueryServiceServer).GetExampleAutoIncFieldName(ctx, req.(*GetExampleAutoIncFieldNameRequest)) @@ -525,7 +614,7 @@ func _TestSchemaQueryService_ListExampleAutoIncFieldName_Handler(srv interface{} } info := &grpc.UnaryServerInfo{ Server: srv, - FullMethod: "/testpb.TestSchemaQueryService/ListExampleAutoIncFieldName", + FullMethod: TestSchemaQueryService_ListExampleAutoIncFieldName_FullMethodName, } handler := func(ctx context.Context, req interface{}) (interface{}, error) { return srv.(TestSchemaQueryServiceServer).ListExampleAutoIncFieldName(ctx, req.(*ListExampleAutoIncFieldNameRequest)) @@ -576,6 +665,14 @@ var TestSchemaQueryService_ServiceDesc = grpc.ServiceDesc{ MethodName: "ListExampleTimestamp", Handler: _TestSchemaQueryService_ListExampleTimestamp_Handler, }, + { + MethodName: "GetExampleDuration", + Handler: _TestSchemaQueryService_GetExampleDuration_Handler, + }, + { + MethodName: "ListExampleDuration", + Handler: _TestSchemaQueryService_ListExampleDuration_Handler, + }, { MethodName: "GetSimpleExample", Handler: _TestSchemaQueryService_GetSimpleExample_Handler, diff --git a/orm/internal/testutil/testutil.go b/orm/internal/testutil/testutil.go index ce27964812f9..ea9c29f33efd 100644 --- a/orm/internal/testutil/testutil.go +++ b/orm/internal/testutil/testutil.go @@ -10,9 +10,9 @@ import ( "google.golang.org/protobuf/types/known/timestamppb" "pgregory.net/rapid" - "github.com/cosmos/cosmos-sdk/orm/encoding/ormfield" - "github.com/cosmos/cosmos-sdk/orm/encoding/ormkv" - "github.com/cosmos/cosmos-sdk/orm/internal/testpb" + "cosmossdk.io/orm/encoding/ormfield" + "cosmossdk.io/orm/encoding/ormkv" + "cosmossdk.io/orm/internal/testpb" ) // TestFieldSpec defines a test field against the testpb.ExampleTable message. @@ -84,8 +84,8 @@ var TestFieldSpecs = []TestFieldSpec{ if isNil >= 0.95 { // draw a nil 5% of the time return nil } - seconds := rapid.Int64Range(-9999999999, 9999999999).Draw(t, "seconds") - nanos := rapid.Int32Range(0, 999999999).Draw(t, "nanos") + seconds := rapid.Int64Range(ormfield.TimestampSecondsMin, ormfield.TimestampSecondsMax).Draw(t, "seconds") + nanos := rapid.Int32Range(0, ormfield.TimestampNanosMax).Draw(t, "nanos") return (×tamppb.Timestamp{ Seconds: seconds, Nanos: nanos, @@ -95,8 +95,15 @@ var TestFieldSpecs = []TestFieldSpec{ { "dur", rapid.Custom(func(t *rapid.T) protoreflect.Message { - seconds := rapid.Int64Range(0, 315576000000).Draw(t, "seconds") - nanos := rapid.Int32Range(0, 999999999).Draw(t, "nanos") + isNil := rapid.Float32().Draw(t, "isNil") + if isNil >= 0.95 { // draw a nil 5% of the time + return nil + } + seconds := rapid.Int64Range(ormfield.DurationNanosMin, ormfield.DurationNanosMax).Draw(t, "seconds") + nanos := rapid.Int32Range(0, ormfield.DurationNanosMax).Draw(t, "nanos") + if seconds < 0 { + nanos = -nanos + } return (&durationpb.Duration{ Seconds: seconds, Nanos: nanos, diff --git a/orm/model/ormdb/file.go b/orm/model/ormdb/file.go index 37c01bcb1f29..2fda9396f05c 100644 --- a/orm/model/ormdb/file.go +++ b/orm/model/ormdb/file.go @@ -6,17 +6,14 @@ import ( "errors" "math" - "google.golang.org/protobuf/reflect/protoregistry" - - "github.com/cosmos/cosmos-sdk/orm/encoding/encodeutil" - - "github.com/cosmos/cosmos-sdk/orm/encoding/ormkv" - "github.com/cosmos/cosmos-sdk/orm/types/ormerrors" - "google.golang.org/protobuf/proto" "google.golang.org/protobuf/reflect/protoreflect" + "google.golang.org/protobuf/reflect/protoregistry" - "github.com/cosmos/cosmos-sdk/orm/model/ormtable" + "cosmossdk.io/orm/encoding/encodeutil" + "cosmossdk.io/orm/encoding/ormkv" + "cosmossdk.io/orm/model/ormtable" + "cosmossdk.io/orm/types/ormerrors" ) type fileDescriptorDBOptions struct { @@ -30,7 +27,7 @@ type fileDescriptorDBOptions struct { type fileDescriptorDB struct { id uint32 prefix []byte - tablesById map[uint32]ormtable.Table + tablesByID map[uint32]ormtable.Table tablesByName map[protoreflect.FullName]ormtable.Table fileDescriptor protoreflect.FileDescriptor } @@ -41,7 +38,7 @@ func newFileDescriptorDB(fileDescriptor protoreflect.FileDescriptor, options fil schema := &fileDescriptorDB{ id: options.ID, prefix: prefix, - tablesById: map[uint32]ormtable.Table{}, + tablesByID: map[uint32]ormtable.Table{}, tablesByName: map[protoreflect.FullName]ormtable.Table{}, fileDescriptor: fileDescriptor, } @@ -76,10 +73,10 @@ func newFileDescriptorDB(fileDescriptor protoreflect.FileDescriptor, options fil } id := table.ID() - if _, ok := schema.tablesById[id]; ok { + if _, ok := schema.tablesByID[id]; ok { return nil, ormerrors.InvalidTableId.Wrapf("duplicate ID %d for %s", id, tableName) } - schema.tablesById[id] = table + schema.tablesByID[id] = table if _, ok := schema.tablesByName[tableName]; ok { return nil, ormerrors.InvalidTableDefinition.Wrapf("duplicate table %s", tableName) @@ -106,7 +103,7 @@ func (f fileDescriptorDB) DecodeEntry(k, v []byte) (ormkv.Entry, error) { return nil, ormerrors.UnexpectedDecodePrefix.Wrapf("uint32 varint id out of range %d", id) } - table, ok := f.tablesById[uint32(id)] + table, ok := f.tablesByID[uint32(id)] if !ok { return nil, ormerrors.UnexpectedDecodePrefix.Wrapf("can't find table with id %d", id) } diff --git a/orm/model/ormdb/genesis.go b/orm/model/ormdb/genesis.go index 1f983704e164..29cd0d8e65ca 100644 --- a/orm/model/ormdb/genesis.go +++ b/orm/model/ormdb/genesis.go @@ -11,7 +11,7 @@ import ( "cosmossdk.io/errors" - "github.com/cosmos/cosmos-sdk/orm/types/ormerrors" + "cosmossdk.io/orm/types/ormerrors" ) type appModuleGenesisWrapper struct { diff --git a/orm/model/ormdb/module.go b/orm/model/ormdb/module.go index ff0c0ccf1afe..72324cab02c7 100644 --- a/orm/model/ormdb/module.go +++ b/orm/model/ormdb/module.go @@ -9,21 +9,17 @@ import ( "cosmossdk.io/core/appmodule" "cosmossdk.io/core/store" + "google.golang.org/protobuf/proto" + "google.golang.org/protobuf/reflect/protodesc" + "google.golang.org/protobuf/reflect/protoreflect" "google.golang.org/protobuf/reflect/protoregistry" ormv1alpha1 "cosmossdk.io/api/cosmos/orm/v1alpha1" - "google.golang.org/protobuf/reflect/protodesc" - - "github.com/cosmos/cosmos-sdk/orm/encoding/encodeutil" - - "google.golang.org/protobuf/proto" - - "google.golang.org/protobuf/reflect/protoreflect" - - "github.com/cosmos/cosmos-sdk/orm/encoding/ormkv" - "github.com/cosmos/cosmos-sdk/orm/model/ormtable" - "github.com/cosmos/cosmos-sdk/orm/types/ormerrors" + "cosmossdk.io/orm/encoding/encodeutil" + "cosmossdk.io/orm/encoding/ormkv" + "cosmossdk.io/orm/model/ormtable" + "cosmossdk.io/orm/types/ormerrors" ) // ModuleDB defines the ORM database type to be used by modules. @@ -47,7 +43,7 @@ type ModuleDB interface { type moduleDB struct { prefix []byte - filesById map[uint32]*fileDescriptorDB + filesByID map[uint32]*fileDescriptorDB tablesByName map[protoreflect.FullName]ormtable.Table } @@ -83,7 +79,7 @@ func NewModuleDB(schema *ormv1alpha1.ModuleSchemaDescriptor, options ModuleDBOpt prefix := schema.Prefix db := &moduleDB{ prefix: prefix, - filesById: map[uint32]*fileDescriptorDB{}, + filesByID: map[uint32]*fileDescriptorDB{}, tablesByName: map[protoreflect.FullName]ormtable.Table{}, } @@ -162,7 +158,7 @@ func NewModuleDB(schema *ormv1alpha1.ModuleSchemaDescriptor, options ModuleDBOpt return nil, err } - db.filesById[id] = fdSchema + db.filesByID[id] = fdSchema for name, table := range fdSchema.tablesByName { if _, ok := db.tablesByName[name]; ok { return nil, ormerrors.UnexpectedError.Wrapf("duplicate table %s", name) @@ -191,7 +187,7 @@ func (m moduleDB) DecodeEntry(k, v []byte) (ormkv.Entry, error) { return nil, ormerrors.UnexpectedDecodePrefix.Wrapf("uint32 varint id out of range %d", id) } - fileSchema, ok := m.filesById[uint32(id)] + fileSchema, ok := m.filesByID[uint32(id)] if !ok { return nil, ormerrors.UnexpectedDecodePrefix.Wrapf("can't find FileDescriptor schema with id %d", id) } diff --git a/orm/model/ormdb/module_test.go b/orm/model/ormdb/module_test.go index 71ca0a167f49..b2e73357c8c5 100644 --- a/orm/model/ormdb/module_test.go +++ b/orm/model/ormdb/module_test.go @@ -15,24 +15,21 @@ import ( "cosmossdk.io/core/appmodule" "cosmossdk.io/core/genesis" "cosmossdk.io/core/store" - dbm "github.com/cosmos/cosmos-db" - "cosmossdk.io/depinject" + dbm "github.com/cosmos/cosmos-db" "github.com/golang/mock/gomock" - - "github.com/cosmos/cosmos-sdk/orm/testing/ormmocks" - "gotest.tools/v3/assert" "gotest.tools/v3/golden" - _ "github.com/cosmos/cosmos-sdk/orm" // required for ORM module registration - "github.com/cosmos/cosmos-sdk/orm/internal/testkv" - "github.com/cosmos/cosmos-sdk/orm/internal/testpb" - "github.com/cosmos/cosmos-sdk/orm/model/ormdb" - "github.com/cosmos/cosmos-sdk/orm/model/ormtable" - "github.com/cosmos/cosmos-sdk/orm/testing/ormtest" - "github.com/cosmos/cosmos-sdk/orm/types/ormerrors" + _ "cosmossdk.io/orm" // required for ORM module registration + "cosmossdk.io/orm/internal/testkv" + "cosmossdk.io/orm/internal/testpb" + "cosmossdk.io/orm/model/ormdb" + "cosmossdk.io/orm/model/ormtable" + "cosmossdk.io/orm/testing/ormmocks" + "cosmossdk.io/orm/testing/ormtest" + "cosmossdk.io/orm/types/ormerrors" ) // These tests use a simulated bank keeper. Addresses and balances use @@ -89,7 +86,7 @@ func (k keeper) Mint(ctx context.Context, acct, denom string, amount uint64) err if supply == nil { supply = &testpb.Supply{Denom: denom, Amount: amount} } else { - supply.Amount = supply.Amount + amount + supply.Amount += amount } err = k.store.SupplyTable().Save(ctx, supply) @@ -111,7 +108,7 @@ func (k keeper) Burn(ctx context.Context, acct, denom string, amount uint64) err return fmt.Errorf("insufficient supply") } - supply.Amount = supply.Amount - amount + supply.Amount -= amount if supply.Amount == 0 { err = supplyStore.Delete(ctx, supply) @@ -162,7 +159,7 @@ func (k keeper) addBalance(ctx context.Context, acct, denom string, amount uint6 Amount: amount, } } else { - balance.Amount = balance.Amount + amount + balance.Amount += amount } return k.store.BalanceTable().Save(ctx, balance) @@ -179,13 +176,13 @@ func (k keeper) safeSubBalance(ctx context.Context, acct, denom string, amount u return fmt.Errorf("insufficient funds") } - balance.Amount = balance.Amount - amount + balance.Amount -= amount if balance.Amount == 0 { return balanceStore.Delete(ctx, balance) - } else { - return balanceStore.Save(ctx, balance) } + + return balanceStore.Save(ctx, balance) } func TestModuleDB(t *testing.T) { @@ -227,13 +224,13 @@ func TestModuleDB(t *testing.T) { // check JSON target := genesis.RawJSONTarget{} assert.NilError(t, db.GenesisHandler().DefaultGenesis(target.Target())) - rawJson, err := target.JSON() + rawJSON, err := target.JSON() assert.NilError(t, err) - golden.Assert(t, string(rawJson), "default_json.golden") + golden.Assert(t, string(rawJSON), "default_json.golden") target = genesis.RawJSONTarget{} assert.NilError(t, db.GenesisHandler().ExportGenesis(ctx, target.Target())) - rawJson, err = target.JSON() + rawJSON, err = target.JSON() assert.NilError(t, err) goodJSON := `{ @@ -255,14 +252,14 @@ func TestModuleDB(t *testing.T) { backend2 := ormtest.NewMemoryBackend() ctx2 := ormtable.WrapContextDefault(backend2) - source, err = genesis.SourceFromRawJSON(rawJson) + source, err = genesis.SourceFromRawJSON(rawJSON) assert.NilError(t, err) assert.NilError(t, db.GenesisHandler().ValidateGenesis(source)) assert.NilError(t, db.GenesisHandler().InitGenesis(ctx2, source)) testkv.AssertBackendsEqual(t, backend, backend2) } -func runSimpleBankTests(t *testing.T, k Keeper, ctx context.Context) { +func runSimpleBankTests(t *testing.T, k Keeper, ctx context.Context) { // nolint:revive // test function // mint coins denom := "foo" acct1 := "bob" diff --git a/orm/model/ormlist/options.go b/orm/model/ormlist/options.go index 8753e3808e23..e713dfd81400 100644 --- a/orm/model/ormlist/options.go +++ b/orm/model/ormlist/options.go @@ -6,7 +6,7 @@ import ( queryv1beta1 "cosmossdk.io/api/cosmos/base/query/v1beta1" - "github.com/cosmos/cosmos-sdk/orm/internal/listinternal" + "cosmossdk.io/orm/internal/listinternal" ) // Option represents a list option. diff --git a/orm/model/ormtable/auto_increment.go b/orm/model/ormtable/auto_increment.go index 982ce7987248..e483f27286ec 100644 --- a/orm/model/ormtable/auto_increment.go +++ b/orm/model/ormtable/auto_increment.go @@ -9,9 +9,9 @@ import ( "google.golang.org/protobuf/proto" "google.golang.org/protobuf/reflect/protoreflect" - "github.com/cosmos/cosmos-sdk/orm/encoding/ormkv" - "github.com/cosmos/cosmos-sdk/orm/types/kv" - "github.com/cosmos/cosmos-sdk/orm/types/ormerrors" + "cosmossdk.io/orm/encoding/ormkv" + "cosmossdk.io/orm/types/kv" + "cosmossdk.io/orm/types/ormerrors" ) // autoIncrementTable is a Table implementation for tables with an @@ -130,7 +130,7 @@ func (t autoIncrementTable) EncodeEntry(entry ormkv.Entry) (k, v []byte, err err } func (t autoIncrementTable) ValidateJSON(reader io.Reader) error { - return t.decodeAutoIncJson(nil, reader, func(message proto.Message, maxSeq uint64) error { + return t.decodeAutoIncJSON(nil, reader, func(message proto.Message, maxSeq uint64) error { messageRef := message.ProtoReflect() pkey := messageRef.Get(t.autoIncField).Uint() if pkey > maxSeq { @@ -140,9 +140,9 @@ func (t autoIncrementTable) ValidateJSON(reader io.Reader) error { if t.customJSONValidator != nil { return t.customJSONValidator(message) - } else { - return DefaultJSONValidator(message) } + + return DefaultJSONValidator(message) }) } @@ -152,7 +152,7 @@ func (t autoIncrementTable) ImportJSON(ctx context.Context, reader io.Reader) er return err } - return t.decodeAutoIncJson(backend, reader, func(message proto.Message, maxSeq uint64) error { + return t.decodeAutoIncJSON(backend, reader, func(message proto.Message, maxSeq uint64) error { messageRef := message.ProtoReflect() pkey := messageRef.Get(t.autoIncField).Uint() if pkey == 0 { @@ -160,29 +160,29 @@ func (t autoIncrementTable) ImportJSON(ctx context.Context, reader io.Reader) er // generate one _, err = t.save(ctx, backend, message, saveModeInsert) return err - } else { - if pkey > maxSeq { - return fmt.Errorf("invalid auto increment primary key %d, expected a value <= %d, the highest "+ - "sequence number", pkey, maxSeq) - } - // we do have a primary key and calling Save will fail because it expects - // either no primary key or SAVE_MODE_UPDATE. So instead we drop one level - // down and insert using tableImpl which doesn't know about - // auto-incrementing primary keys. - return t.tableImpl.save(ctx, backend, message, saveModeInsert) } + + if pkey > maxSeq { + return fmt.Errorf("invalid auto increment primary key %d, expected a value <= %d, the highest "+ + "sequence number", pkey, maxSeq) + } + // we do have a primary key and calling Save will fail because it expects + // either no primary key or SAVE_MODE_UPDATE. So instead we drop one level + // down and insert using tableImpl which doesn't know about + // auto-incrementing primary keys. + return t.tableImpl.save(ctx, backend, message, saveModeInsert) }) } -func (t autoIncrementTable) decodeAutoIncJson(backend Backend, reader io.Reader, onMsg func(message proto.Message, maxID uint64) error) error { - decoder, err := t.startDecodeJson(reader) +func (t autoIncrementTable) decodeAutoIncJSON(backend Backend, reader io.Reader, onMsg func(message proto.Message, maxID uint64) error) error { + decoder, err := t.startDecodeJSON(reader) if err != nil { return err } var seq uint64 - return t.doDecodeJson(decoder, + return t.doDecodeJSON(decoder, func(message json.RawMessage) bool { err = json.Unmarshal(message, &seq) if err == nil { diff --git a/orm/model/ormtable/auto_increment_test.go b/orm/model/ormtable/auto_increment_test.go index 5ba1fa4ed05a..053b8a239168 100644 --- a/orm/model/ormtable/auto_increment_test.go +++ b/orm/model/ormtable/auto_increment_test.go @@ -10,9 +10,9 @@ import ( "gotest.tools/v3/assert" "gotest.tools/v3/golden" - "github.com/cosmos/cosmos-sdk/orm/internal/testkv" - "github.com/cosmos/cosmos-sdk/orm/internal/testpb" - "github.com/cosmos/cosmos-sdk/orm/model/ormtable" + "cosmossdk.io/orm/internal/testkv" + "cosmossdk.io/orm/internal/testpb" + "cosmossdk.io/orm/model/ormtable" ) func TestAutoIncrementScenario(t *testing.T) { @@ -42,7 +42,7 @@ func TestAutoIncrementScenario(t *testing.T) { checkEncodeDecodeEntries(t, table, store.IndexStoreReader()) } -func runAutoIncrementScenario(t *testing.T, table ormtable.AutoIncrementTable, ctx context.Context) { +func runAutoIncrementScenario(t *testing.T, table ormtable.AutoIncrementTable, ctx context.Context) { //nolint:revive // ignore linting on testing function signature store, err := testpb.NewExampleAutoIncrementTableTable(table) assert.NilError(t, err) @@ -57,10 +57,10 @@ func runAutoIncrementScenario(t *testing.T, table ormtable.AutoIncrementTable, c assert.Equal(t, curSeq, uint64(1)) ex2 := &testpb.ExampleAutoIncrementTable{X: "bar", Y: 10} - newId, err := table.InsertReturningPKey(ctx, ex2) + newID, err := table.InsertReturningPKey(ctx, ex2) assert.NilError(t, err) assert.Equal(t, uint64(2), ex2.Id) - assert.Equal(t, newId, ex2.Id) + assert.Equal(t, newID, ex2.Id) curSeq, err = table.LastInsertedSequence(ctx) assert.NilError(t, err) assert.Equal(t, curSeq, uint64(2)) diff --git a/orm/model/ormtable/backend.go b/orm/model/ormtable/backend.go index 66ff949ad5c0..455ca90da533 100644 --- a/orm/model/ormtable/backend.go +++ b/orm/model/ormtable/backend.go @@ -4,7 +4,7 @@ import ( "context" "fmt" - "github.com/cosmos/cosmos-sdk/orm/types/kv" + "cosmossdk.io/orm/types/kv" ) // ReadBackend defines the type used for read-only ORM operations. diff --git a/orm/model/ormtable/batch.go b/orm/model/ormtable/batch.go index 7983bee77269..75ca19422879 100644 --- a/orm/model/ormtable/batch.go +++ b/orm/model/ormtable/batch.go @@ -1,7 +1,7 @@ package ormtable import ( - "github.com/cosmos/cosmos-sdk/orm/types/kv" + "cosmossdk.io/orm/types/kv" ) type batchIndexCommitmentWriter struct { @@ -62,14 +62,15 @@ func flushWrites(store kv.Store, writer *batchStoreWriter) error { func flushBuf(store kv.Store, writes []*batchWriterEntry) error { for _, write := range writes { - if write.hookCall != nil { + switch { + case write.hookCall != nil: write.hookCall() - } else if !write.delete { + case !write.delete: err := store.Set(write.key, write.value) if err != nil { return err } - } else { + default: err := store.Delete(write.key) if err != nil { return err diff --git a/orm/model/ormtable/bench_test.go b/orm/model/ormtable/bench_test.go index 48d2621e84d6..dcd68324f342 100644 --- a/orm/model/ormtable/bench_test.go +++ b/orm/model/ormtable/bench_test.go @@ -7,15 +7,14 @@ import ( "google.golang.org/protobuf/proto" - "github.com/cosmos/cosmos-sdk/orm/internal/testkv" - "github.com/cosmos/cosmos-sdk/orm/testing/ormtest" - dbm "github.com/cosmos/cosmos-db" "gotest.tools/v3/assert" - "github.com/cosmos/cosmos-sdk/orm/internal/testpb" - "github.com/cosmos/cosmos-sdk/orm/model/ormtable" - "github.com/cosmos/cosmos-sdk/orm/types/kv" + "cosmossdk.io/orm/internal/testkv" + "cosmossdk.io/orm/internal/testpb" + "cosmossdk.io/orm/model/ormtable" + "cosmossdk.io/orm/testing/ormtest" + "cosmossdk.io/orm/types/kv" ) func initBalanceTable(t testing.TB) testpb.BalanceTable { @@ -70,7 +69,7 @@ func bench(b *testing.B, newBackend func(testing.TB) ormtable.Backend) { }) } -func benchInsert(b *testing.B, ctx context.Context) { +func benchInsert(b *testing.B, ctx context.Context) { //nolint:revive // ignore for benchmark balanceTable := initBalanceTable(b) for i := 0; i < b.N; i++ { assert.NilError(b, balanceTable.Insert(ctx, &testpb.Balance{ @@ -81,7 +80,7 @@ func benchInsert(b *testing.B, ctx context.Context) { } } -func benchUpdate(b *testing.B, ctx context.Context) { +func benchUpdate(b *testing.B, ctx context.Context) { //nolint:revive // ignore for benchmark balanceTable := initBalanceTable(b) for i := 0; i < b.N; i++ { assert.NilError(b, balanceTable.Update(ctx, &testpb.Balance{ @@ -92,7 +91,7 @@ func benchUpdate(b *testing.B, ctx context.Context) { } } -func benchGet(b *testing.B, ctx context.Context) { +func benchGet(b *testing.B, ctx context.Context) { //nolint:revive // ignore for benchmark balanceTable := initBalanceTable(b) for i := 0; i < b.N; i++ { balance, err := balanceTable.Get(ctx, fmt.Sprintf("acct%d", i), "bar") @@ -101,7 +100,7 @@ func benchGet(b *testing.B, ctx context.Context) { } } -func benchDelete(b *testing.B, ctx context.Context) { +func benchDelete(b *testing.B, ctx context.Context) { //nolint:revive // ignore for benchmark balanceTable := initBalanceTable(b) for i := 0; i < b.N; i++ { assert.NilError(b, balanceTable.Delete(ctx, &testpb.Balance{ diff --git a/orm/model/ormtable/build.go b/orm/model/ormtable/build.go index 3e9137665d0a..b946e3f59801 100644 --- a/orm/model/ormtable/build.go +++ b/orm/model/ormtable/build.go @@ -9,16 +9,16 @@ import ( ormv1 "cosmossdk.io/api/cosmos/orm/v1" - "github.com/cosmos/cosmos-sdk/orm/encoding/encodeutil" - "github.com/cosmos/cosmos-sdk/orm/encoding/ormkv" - "github.com/cosmos/cosmos-sdk/orm/internal/fieldnames" - "github.com/cosmos/cosmos-sdk/orm/types/ormerrors" + "cosmossdk.io/orm/encoding/encodeutil" + "cosmossdk.io/orm/encoding/ormkv" + "cosmossdk.io/orm/internal/fieldnames" + "cosmossdk.io/orm/types/ormerrors" ) const ( - primaryKeyId uint32 = 0 - indexIdLimit uint32 = 32768 - seqId = indexIdLimit + primaryKeyID uint32 = 0 + indexIDLimit uint32 = 32768 + seqID = indexIDLimit ) // Options are options for building a Table. @@ -84,8 +84,8 @@ func Build(options Options) (Table, error) { indexes: []Index{}, indexesByFields: map[fieldnames.FieldNames]concreteIndex{}, uniqueIndexesByFields: map[fieldnames.FieldNames]UniqueIndex{}, - entryCodecsById: map[uint32]ormkv.EntryCodec{}, - indexesById: map[uint32]Index{}, + entryCodecsByID: map[uint32]ormkv.EntryCodec{}, + indexesByID: map[uint32]Index{}, typeResolver: options.TypeResolver, customJSONValidator: options.JSONValidator, } @@ -125,22 +125,22 @@ func Build(options Options) (Table, error) { pkIndex.PrimaryKeyCodec = pkCodec table.tablePrefix = prefix - table.tableId = singletonDesc.Id + table.tableID = singletonDesc.Id return &singleton{table}, nil default: return nil, ormerrors.NoTableDescriptor.Wrapf("missing table descriptor for %s", messageDescriptor.FullName()) } - tableId := tableDesc.Id - if tableId == 0 { + tableID := tableDesc.Id + if tableID == 0 { return nil, ormerrors.InvalidTableId.Wrapf("table %s", messageDescriptor.FullName()) } prefix := options.Prefix - prefix = encodeutil.AppendVarUInt32(prefix, tableId) + prefix = encodeutil.AppendVarUInt32(prefix, tableID) table.tablePrefix = prefix - table.tableId = tableId + table.tableID = tableID if tableDesc.PrimaryKey == nil { return nil, ormerrors.MissingPrimaryKey.Wrap(string(messageDescriptor.FullName())) @@ -153,7 +153,7 @@ func Build(options Options) (Table, error) { return nil, ormerrors.InvalidTableDefinition.Wrapf("empty primary key fields for %s", messageDescriptor.FullName()) } - pkPrefix := encodeutil.AppendVarUInt32(prefix, primaryKeyId) + pkPrefix := encodeutil.AppendVarUInt32(prefix, primaryKeyID) pkCodec, err := ormkv.NewPrimaryKeyCodec( pkPrefix, options.MessageType, @@ -167,17 +167,17 @@ func Build(options Options) (Table, error) { pkIndex.PrimaryKeyCodec = pkCodec table.indexesByFields[pkFields] = pkIndex table.uniqueIndexesByFields[pkFields] = pkIndex - table.entryCodecsById[primaryKeyId] = pkIndex - table.indexesById[primaryKeyId] = pkIndex + table.entryCodecsByID[primaryKeyID] = pkIndex + table.indexesByID[primaryKeyID] = pkIndex table.indexes = append(table.indexes, pkIndex) for _, idxDesc := range tableDesc.Index { id := idxDesc.Id - if id == 0 || id >= indexIdLimit { + if id == 0 || id >= indexIDLimit { return nil, ormerrors.InvalidIndexId.Wrapf("index on table %s with fields %s, invalid id %d", messageDescriptor.FullName(), idxDesc.Fields, id) } - if _, ok := table.entryCodecsById[id]; ok { + if _, ok := table.entryCodecsByID[id]; ok { return nil, ormerrors.DuplicateIndexId.Wrapf("id %d on table %s", id, messageDescriptor.FullName()) } @@ -264,8 +264,8 @@ func Build(options Options) (Table, error) { table.indexesByFields[name] = index } - table.entryCodecsById[id] = index - table.indexesById[id] = index + table.entryCodecsByID[id] = index + table.indexesByID[id] = index table.indexes = append(table.indexes, index) table.indexers = append(table.indexers, index.(indexer)) } @@ -276,9 +276,9 @@ func Build(options Options) (Table, error) { return nil, ormerrors.InvalidAutoIncrementKey.Wrapf("field %s", autoIncField.FullName()) } - seqPrefix := encodeutil.AppendVarUInt32(prefix, seqId) + seqPrefix := encodeutil.AppendVarUInt32(prefix, seqID) seqCodec := ormkv.NewSeqCodec(options.MessageType, seqPrefix) - table.entryCodecsById[seqId] = seqCodec + table.entryCodecsByID[seqID] = seqCodec return &autoIncrementTable{ tableImpl: table, autoIncField: autoIncField, diff --git a/orm/model/ormtable/duration_test.go b/orm/model/ormtable/duration_test.go new file mode 100644 index 000000000000..7309eb4a0767 --- /dev/null +++ b/orm/model/ormtable/duration_test.go @@ -0,0 +1,103 @@ +package ormtable_test + +import ( + "testing" + "time" + + "google.golang.org/protobuf/types/known/durationpb" + "gotest.tools/v3/assert" + + "cosmossdk.io/orm/internal/testkv" + "cosmossdk.io/orm/internal/testpb" + "cosmossdk.io/orm/model/ormtable" +) + +func TestDurationIndex(t *testing.T) { + table, err := ormtable.Build(ormtable.Options{ + MessageType: (&testpb.ExampleDuration{}).ProtoReflect().Type(), + }) + assert.NilError(t, err) + backend := testkv.NewDebugBackend(testkv.NewSplitMemBackend(), &testkv.EntryCodecDebugger{ + EntryCodec: table, + }) + ctx := ormtable.WrapContextDefault(backend) + store, err := testpb.NewExampleDurationTable(table) + assert.NilError(t, err) + + neg, err := time.ParseDuration("-1h") + assert.NilError(t, err) + zero, err := time.ParseDuration("0") + assert.NilError(t, err) + pos, err := time.ParseDuration("11000ms") + assert.NilError(t, err) + + negPb, zeroPb, posPb := durationpb.New(neg), durationpb.New(zero), durationpb.New(pos) + durOrder := []*durationpb.Duration{negPb, zeroPb, posPb} + + assert.NilError(t, store.Insert(ctx, &testpb.ExampleDuration{ + Name: "foo", + Dur: negPb, + })) + assert.NilError(t, store.Insert(ctx, &testpb.ExampleDuration{ + Name: "bar", + Dur: zeroPb, + })) + assert.NilError(t, store.Insert(ctx, &testpb.ExampleDuration{ + Name: "baz", + Dur: posPb, + })) + + from, to := testpb.ExampleDurationDurIndexKey{}.WithDur(durationpb.New(neg)), + testpb.ExampleDurationDurIndexKey{}.WithDur(durationpb.New(pos)) + it, err := store.ListRange(ctx, from, to) + assert.NilError(t, err) + + i := 0 + for it.Next() { + v, err := it.Value() + assert.NilError(t, err) + assert.Equal(t, durOrder[i].String(), v.Dur.String()) + i++ + } + + // insert a nil entry + id, err := store.InsertReturningId(ctx, &testpb.ExampleDuration{ + Name: "nil", + Dur: nil, + }) + assert.NilError(t, err) + + res, err := store.Get(ctx, id) + assert.NilError(t, err) + assert.Assert(t, res.Dur == nil) + + it, err = store.List(ctx, testpb.ExampleDurationDurIndexKey{}) + assert.NilError(t, err) + + // make sure nils are ordered last + durOrder = append(durOrder, nil) + i = 0 + for it.Next() { + v, err := it.Value() + assert.NilError(t, err) + assert.Assert(t, v != nil) + x := durOrder[i] + if x == nil { + assert.Assert(t, v.Dur == nil) + } else { + assert.Equal(t, x.String(), v.Dur.String()) + } + i++ + } + it.Close() + + // try iterating over just nil timestamps + it, err = store.List(ctx, testpb.ExampleDurationDurIndexKey{}.WithDur(nil)) + assert.NilError(t, err) + assert.Assert(t, it.Next()) + res, err = it.Value() + assert.NilError(t, err) + assert.Assert(t, res.Dur == nil) + assert.Assert(t, !it.Next()) + it.Close() +} diff --git a/orm/model/ormtable/index.go b/orm/model/ormtable/index.go index 903c19348505..8b1b625734c6 100644 --- a/orm/model/ormtable/index.go +++ b/orm/model/ormtable/index.go @@ -3,13 +3,12 @@ package ormtable import ( "context" - "github.com/cosmos/cosmos-sdk/orm/types/kv" - "google.golang.org/protobuf/proto" "google.golang.org/protobuf/reflect/protoreflect" - "github.com/cosmos/cosmos-sdk/orm/encoding/ormkv" - "github.com/cosmos/cosmos-sdk/orm/model/ormlist" + "cosmossdk.io/orm/encoding/ormkv" + "cosmossdk.io/orm/model/ormlist" + "cosmossdk.io/orm/types/kv" ) // Index defines an index on a table. Index instances diff --git a/orm/model/ormtable/index_impl.go b/orm/model/ormtable/index_impl.go index 7289efc40af4..7aacd5aebac4 100644 --- a/orm/model/ormtable/index_impl.go +++ b/orm/model/ormtable/index_impl.go @@ -3,18 +3,14 @@ package ormtable import ( "context" - "github.com/cosmos/cosmos-sdk/orm/types/kv" - - "github.com/cosmos/cosmos-sdk/orm/internal/fieldnames" - - "github.com/cosmos/cosmos-sdk/orm/model/ormlist" - - "github.com/cosmos/cosmos-sdk/orm/types/ormerrors" - "google.golang.org/protobuf/proto" "google.golang.org/protobuf/reflect/protoreflect" - "github.com/cosmos/cosmos-sdk/orm/encoding/ormkv" + "cosmossdk.io/orm/encoding/ormkv" + "cosmossdk.io/orm/internal/fieldnames" + "cosmossdk.io/orm/model/ormlist" + "cosmossdk.io/orm/types/kv" + "cosmossdk.io/orm/types/ormerrors" ) // indexKeyIndex implements Index for a regular IndexKey. @@ -120,6 +116,6 @@ func (i indexKeyIndex) readValueFromIndexKey(backend ReadBackend, primaryKey []p return nil } -func (p indexKeyIndex) Fields() string { - return p.fields.String() +func (i indexKeyIndex) Fields() string { + return i.fields.String() } diff --git a/orm/model/ormtable/iterator.go b/orm/model/ormtable/iterator.go index 848396cb96c6..3d8765d2adec 100644 --- a/orm/model/ormtable/iterator.go +++ b/orm/model/ormtable/iterator.go @@ -5,11 +5,11 @@ import ( "google.golang.org/protobuf/reflect/protoreflect" queryv1beta1 "cosmossdk.io/api/cosmos/base/query/v1beta1" - "github.com/cosmos/cosmos-sdk/orm/encoding/encodeutil" - "github.com/cosmos/cosmos-sdk/orm/encoding/ormkv" - "github.com/cosmos/cosmos-sdk/orm/internal/listinternal" - "github.com/cosmos/cosmos-sdk/orm/model/ormlist" - "github.com/cosmos/cosmos-sdk/orm/types/kv" + "cosmossdk.io/orm/encoding/encodeutil" + "cosmossdk.io/orm/encoding/ormkv" + "cosmossdk.io/orm/internal/listinternal" + "cosmossdk.io/orm/model/ormlist" + "cosmossdk.io/orm/types/kv" ) // Iterator defines the interface for iterating over indexes. diff --git a/orm/model/ormtable/paginate.go b/orm/model/ormtable/paginate.go index f30d9c02583d..02ae110a83c0 100644 --- a/orm/model/ormtable/paginate.go +++ b/orm/model/ormtable/paginate.go @@ -3,7 +3,7 @@ package ormtable import ( "math" - "github.com/cosmos/cosmos-sdk/orm/internal/listinternal" + "cosmossdk.io/orm/internal/listinternal" queryv1beta1 "cosmossdk.io/api/cosmos/base/query/v1beta1" ) @@ -84,12 +84,12 @@ func (it *paginationIterator) Next() bool { if ok { it.i++ return true - } else { - it.pageRes = &queryv1beta1.PageResponse{ - Total: uint64(it.i), - } - return false } + + it.pageRes = &queryv1beta1.PageResponse{ + Total: uint64(it.i), + } + return false } func (it paginationIterator) PageResponse() *queryv1beta1.PageResponse { diff --git a/orm/model/ormtable/primary_key.go b/orm/model/ormtable/primary_key.go index 0ce62852895b..1efd1cbbf802 100644 --- a/orm/model/ormtable/primary_key.go +++ b/orm/model/ormtable/primary_key.go @@ -3,18 +3,14 @@ package ormtable import ( "context" - "github.com/cosmos/cosmos-sdk/orm/types/ormerrors" - - "github.com/cosmos/cosmos-sdk/orm/internal/fieldnames" - - "github.com/cosmos/cosmos-sdk/orm/model/ormlist" - - "github.com/cosmos/cosmos-sdk/orm/encoding/encodeutil" - "google.golang.org/protobuf/proto" "google.golang.org/protobuf/reflect/protoreflect" - "github.com/cosmos/cosmos-sdk/orm/encoding/ormkv" + "cosmossdk.io/orm/encoding/encodeutil" + "cosmossdk.io/orm/encoding/ormkv" + "cosmossdk.io/orm/internal/fieldnames" + "cosmossdk.io/orm/model/ormlist" + "cosmossdk.io/orm/types/ormerrors" ) // primaryKeyIndex defines an UniqueIndex for the primary key. diff --git a/orm/model/ormtable/save_test.go b/orm/model/ormtable/save_test.go index 564a8edb2f1d..3222ff3ad89f 100644 --- a/orm/model/ormtable/save_test.go +++ b/orm/model/ormtable/save_test.go @@ -5,7 +5,6 @@ import ( "fmt" "testing" - "github.com/cosmos/cosmos-sdk/orm/model/ormtable" "google.golang.org/grpc/codes" "google.golang.org/grpc/status" "google.golang.org/protobuf/encoding/protojson" @@ -13,8 +12,9 @@ import ( "github.com/regen-network/gocuke" "gotest.tools/v3/assert" - "github.com/cosmos/cosmos-sdk/orm/internal/testpb" - "github.com/cosmos/cosmos-sdk/orm/testing/ormtest" + "cosmossdk.io/orm/internal/testpb" + "cosmossdk.io/orm/model/ormtable" + "cosmossdk.io/orm/testing/ormtest" ) func TestSave(t *testing.T) { diff --git a/orm/model/ormtable/singleton.go b/orm/model/ormtable/singleton.go index 1a7017662579..13bf37f2afa1 100644 --- a/orm/model/ormtable/singleton.go +++ b/orm/model/ormtable/singleton.go @@ -37,9 +37,9 @@ func (t singleton) ValidateJSON(reader io.Reader) error { if t.customJSONValidator != nil { return t.customJSONValidator(msg) - } else { - return DefaultJSONValidator(msg) } + + return DefaultJSONValidator(msg) } func (t singleton) ImportJSON(ctx context.Context, reader io.Reader) error { diff --git a/orm/model/ormtable/singleton_test.go b/orm/model/ormtable/singleton_test.go index c0eaf0e90d4b..44a8c8f778f9 100644 --- a/orm/model/ormtable/singleton_test.go +++ b/orm/model/ormtable/singleton_test.go @@ -4,14 +4,13 @@ import ( "bytes" "testing" - "github.com/cosmos/cosmos-sdk/orm/model/ormtable" - "google.golang.org/protobuf/testing/protocmp" "gotest.tools/v3/assert" - "github.com/cosmos/cosmos-sdk/orm/internal/testkv" - "github.com/cosmos/cosmos-sdk/orm/internal/testpb" + "cosmossdk.io/orm/internal/testkv" + "cosmossdk.io/orm/internal/testpb" + "cosmossdk.io/orm/model/ormtable" ) func TestSingleton(t *testing.T) { diff --git a/orm/model/ormtable/table.go b/orm/model/ormtable/table.go index 221757463649..1bbdab7376ed 100644 --- a/orm/model/ormtable/table.go +++ b/orm/model/ormtable/table.go @@ -7,7 +7,7 @@ import ( "google.golang.org/protobuf/proto" - "github.com/cosmos/cosmos-sdk/orm/encoding/ormkv" + "cosmossdk.io/orm/encoding/ormkv" ) // View defines a read-only table. diff --git a/orm/model/ormtable/table_impl.go b/orm/model/ormtable/table_impl.go index bbcebb3a96ad..9321ae269664 100644 --- a/orm/model/ormtable/table_impl.go +++ b/orm/model/ormtable/table_impl.go @@ -8,14 +8,13 @@ import ( "io" "math" - "github.com/cosmos/cosmos-sdk/orm/internal/fieldnames" - "google.golang.org/protobuf/encoding/protojson" "google.golang.org/protobuf/proto" - "github.com/cosmos/cosmos-sdk/orm/encoding/encodeutil" - "github.com/cosmos/cosmos-sdk/orm/encoding/ormkv" - "github.com/cosmos/cosmos-sdk/orm/types/ormerrors" + "cosmossdk.io/orm/encoding/encodeutil" + "cosmossdk.io/orm/encoding/ormkv" + "cosmossdk.io/orm/internal/fieldnames" + "cosmossdk.io/orm/types/ormerrors" ) // tableImpl implements Table. @@ -24,10 +23,10 @@ type tableImpl struct { indexes []Index indexesByFields map[fieldnames.FieldNames]concreteIndex uniqueIndexesByFields map[fieldnames.FieldNames]UniqueIndex - indexesById map[uint32]Index - entryCodecsById map[uint32]ormkv.EntryCodec + indexesByID map[uint32]Index + entryCodecsByID map[uint32]ormkv.EntryCodec tablePrefix []byte - tableId uint32 + tableID uint32 typeResolver TypeResolver customJSONValidator func(message proto.Message) error } @@ -44,7 +43,7 @@ func (t tableImpl) PrimaryKey() UniqueIndex { } func (t tableImpl) GetIndexByID(id uint32) Index { - return t.indexesById[id] + return t.indexesByID[id] } func (t tableImpl) Save(ctx context.Context, message proto.Message) error { @@ -187,16 +186,16 @@ func (t tableImpl) DefaultJSON() json.RawMessage { return json.RawMessage("[]") } -func (t tableImpl) decodeJson(reader io.Reader, onMsg func(message proto.Message) error) error { - decoder, err := t.startDecodeJson(reader) +func (t tableImpl) decodeJSON(reader io.Reader, onMsg func(message proto.Message) error) error { + decoder, err := t.startDecodeJSON(reader) if err != nil { return err } - return t.doDecodeJson(decoder, nil, onMsg) + return t.doDecodeJSON(decoder, nil, onMsg) } -func (t tableImpl) startDecodeJson(reader io.Reader) (*json.Decoder, error) { +func (t tableImpl) startDecodeJSON(reader io.Reader) (*json.Decoder, error) { decoder := json.NewDecoder(reader) token, err := decoder.Token() if err != nil { @@ -213,13 +212,13 @@ func (t tableImpl) startDecodeJson(reader io.Reader) (*json.Decoder, error) { // onFirst is called on the first RawMessage and used for auto-increment tables // to decode the sequence in which case it should return true. // onMsg is called on every decoded message -func (t tableImpl) doDecodeJson(decoder *json.Decoder, onFirst func(message json.RawMessage) bool, onMsg func(message proto.Message) error) error { +func (t tableImpl) doDecodeJSON(decoder *json.Decoder, onFirst func(message json.RawMessage) bool, onMsg func(message proto.Message) error) error { unmarshalOptions := protojson.UnmarshalOptions{Resolver: t.typeResolver} first := true for decoder.More() { - var rawJson json.RawMessage - err := decoder.Decode(&rawJson) + var rawJSON json.RawMessage + err := decoder.Decode(&rawJSON) if err != nil { return ormerrors.JSONImportError.Wrapf("%s", err) } @@ -227,7 +226,7 @@ func (t tableImpl) doDecodeJson(decoder *json.Decoder, onFirst func(message json if first { first = false if onFirst != nil { - if onFirst(rawJson) { + if onFirst(rawJSON) { // if onFirst handled this, skip decoding into a proto message continue } @@ -235,7 +234,7 @@ func (t tableImpl) doDecodeJson(decoder *json.Decoder, onFirst func(message json } msg := t.MessageType().New().Interface() - err = unmarshalOptions.Unmarshal(rawJson, msg) + err = unmarshalOptions.Unmarshal(rawJSON, msg) if err != nil { return err } @@ -280,12 +279,12 @@ func DefaultJSONValidator(message proto.Message) error { } func (t tableImpl) ValidateJSON(reader io.Reader) error { - return t.decodeJson(reader, func(message proto.Message) error { + return t.decodeJSON(reader, func(message proto.Message) error { if t.customJSONValidator != nil { return t.customJSONValidator(message) - } else { - return DefaultJSONValidator(message) } + + return DefaultJSONValidator(message) }) } @@ -295,7 +294,7 @@ func (t tableImpl) ImportJSON(ctx context.Context, reader io.Reader) error { return err } - return t.decodeJson(reader, func(message proto.Message) error { + return t.decodeJSON(reader, func(message proto.Message) error { return t.save(ctx, backend, message, saveModeDefault) }) } @@ -366,7 +365,7 @@ func (t tableImpl) DecodeEntry(k, v []byte) (ormkv.Entry, error) { return nil, ormerrors.UnexpectedDecodePrefix.Wrapf("uint32 varint id out of range %d", id) } - idx, ok := t.entryCodecsById[uint32(id)] + idx, ok := t.entryCodecsByID[uint32(id)] if !ok { return nil, ormerrors.UnexpectedDecodePrefix.Wrapf("can't find field with id %d", id) } @@ -391,7 +390,7 @@ func (t tableImpl) EncodeEntry(entry ormkv.Entry) (k, v []byte, err error) { } func (t tableImpl) ID() uint32 { - return t.tableId + return t.tableID } func (t tableImpl) Has(ctx context.Context, message proto.Message) (found bool, err error) { diff --git a/orm/model/ormtable/table_test.go b/orm/model/ormtable/table_test.go index 8e62cf814359..766bb76592f5 100644 --- a/orm/model/ormtable/table_test.go +++ b/orm/model/ormtable/table_test.go @@ -7,9 +7,6 @@ import ( "sort" "strings" "testing" - "time" - - "google.golang.org/protobuf/types/known/timestamppb" dbm "github.com/cosmos/cosmos-db" @@ -20,18 +17,17 @@ import ( "gotest.tools/v3/golden" "pgregory.net/rapid" - "github.com/cosmos/cosmos-sdk/orm/types/kv" - queryv1beta1 "cosmossdk.io/api/cosmos/base/query/v1beta1" sdkerrors "cosmossdk.io/errors" - "github.com/cosmos/cosmos-sdk/orm/encoding/ormkv" - "github.com/cosmos/cosmos-sdk/orm/internal/testkv" - "github.com/cosmos/cosmos-sdk/orm/internal/testpb" - "github.com/cosmos/cosmos-sdk/orm/internal/testutil" - "github.com/cosmos/cosmos-sdk/orm/model/ormlist" - "github.com/cosmos/cosmos-sdk/orm/model/ormtable" - "github.com/cosmos/cosmos-sdk/orm/types/ormerrors" + "cosmossdk.io/orm/encoding/ormkv" + "cosmossdk.io/orm/internal/testkv" + "cosmossdk.io/orm/internal/testpb" + "cosmossdk.io/orm/internal/testutil" + "cosmossdk.io/orm/model/ormlist" + "cosmossdk.io/orm/model/ormtable" + "cosmossdk.io/orm/types/kv" + "cosmossdk.io/orm/types/ormerrors" ) func TestScenario(t *testing.T) { @@ -101,98 +97,6 @@ func TestPaginationLimitCountTotal(t *testing.T) { assert.Equal(t, uint64(3), pr.Total) } -func TestTimestampIndex(t *testing.T) { - table, err := ormtable.Build(ormtable.Options{ - MessageType: (&testpb.ExampleTimestamp{}).ProtoReflect().Type(), - }) - assert.NilError(t, err) - backend := testkv.NewDebugBackend(testkv.NewSplitMemBackend(), &testkv.EntryCodecDebugger{ - EntryCodec: table, - Print: func(s string) { - t.Log(s) - }, - }) - ctx := ormtable.WrapContextDefault(backend) - store, err := testpb.NewExampleTimestampTable(table) - assert.NilError(t, err) - - past, err := time.Parse("2006-01-02", "2000-01-01") - assert.NilError(t, err) - middle, err := time.Parse("2006-01-02", "2020-01-01") - assert.NilError(t, err) - future, err := time.Parse("2006-01-02", "2049-01-01") - assert.NilError(t, err) - - pastPb, middlePb, futurePb := timestamppb.New(past), timestamppb.New(middle), timestamppb.New(future) - timeOrder := []*timestamppb.Timestamp{pastPb, middlePb, futurePb} - - assert.NilError(t, store.Insert(ctx, &testpb.ExampleTimestamp{ - Name: "foo", - Ts: pastPb, - })) - assert.NilError(t, store.Insert(ctx, &testpb.ExampleTimestamp{ - Name: "bar", - Ts: middlePb, - })) - assert.NilError(t, store.Insert(ctx, &testpb.ExampleTimestamp{ - Name: "baz", - Ts: futurePb, - })) - - from, to := testpb.ExampleTimestampTsIndexKey{}.WithTs(timestamppb.New(past)), testpb.ExampleTimestampTsIndexKey{}.WithTs(timestamppb.New(future)) - it, err := store.ListRange(ctx, from, to) - assert.NilError(t, err) - - i := 0 - for it.Next() { - v, err := it.Value() - assert.NilError(t, err) - assert.Equal(t, timeOrder[i].String(), v.Ts.String()) - i++ - } - - // insert a nil entry - id, err := store.InsertReturningId(ctx, &testpb.ExampleTimestamp{ - Name: "nil", - Ts: nil, - }) - assert.NilError(t, err) - - res, err := store.Get(ctx, id) - assert.NilError(t, err) - assert.Assert(t, res.Ts == nil) - - it, err = store.List(ctx, testpb.ExampleTimestampTsIndexKey{}) - assert.NilError(t, err) - - // make sure nils are ordered last - timeOrder = append(timeOrder, nil) - i = 0 - for it.Next() { - v, err := it.Value() - assert.NilError(t, err) - assert.Assert(t, v != nil) - x := timeOrder[i] - if x == nil { - assert.Assert(t, v.Ts == nil) - } else { - assert.Equal(t, x.String(), v.Ts.String()) - } - i++ - } - it.Close() - - // try iterating over just nil timestamps - it, err = store.List(ctx, testpb.ExampleTimestampTsIndexKey{}.WithTs(nil)) - assert.NilError(t, err) - assert.Assert(t, it.Next()) - res, err = it.Value() - assert.NilError(t, err) - assert.Assert(t, res.Ts == nil) - assert.Assert(t, !it.Next()) - it.Close() -} - // check that the ormkv.Entry's decode and encode to the same bytes func checkEncodeDecodeEntries(t *testing.T, table ormtable.Table, store kv.ReadonlyStore) { it, err := store.Iterator(nil, nil) @@ -473,7 +377,7 @@ func runTestScenario(t *testing.T, table ormtable.Table, backend ormtable.Backen // now let's update some things for i := 0; i < 5; i++ { - data[i].U64 = data[i].U64 * 2 + data[i].U64 *= 2 data[i].Bz = []byte(data[i].Str) err = store.Update(ctx, data[i]) assert.NilError(t, err) @@ -763,9 +667,7 @@ func (m *IndexModel) Less(i, j int) bool { } func (m *IndexModel) Swap(i, j int) { - x := m.data[i] - m.data[i] = m.data[j] - m.data[j] = x + m.data[i], m.data[j] = m.data[j], m.data[i] } var _ sort.Interface = &IndexModel{} @@ -799,7 +701,7 @@ func TestJSONExportImport(t *testing.T) { assertTablesEqual(t, table, store, store2) } -func assertTablesEqual(t assert.TestingT, table ormtable.Table, ctx, ctx2 context.Context) { +func assertTablesEqual(t assert.TestingT, table ormtable.Table, ctx, ctx2 context.Context) { //nolint:revive // ignore long function name it, err := table.List(ctx, nil) assert.NilError(t, err) it2, err := table.List(ctx2, nil) diff --git a/orm/model/ormtable/timestamp_test.go b/orm/model/ormtable/timestamp_test.go new file mode 100644 index 000000000000..031d755f2cdb --- /dev/null +++ b/orm/model/ormtable/timestamp_test.go @@ -0,0 +1,103 @@ +package ormtable_test + +import ( + "testing" + "time" + + "google.golang.org/protobuf/types/known/timestamppb" + + "gotest.tools/v3/assert" + + "cosmossdk.io/orm/internal/testkv" + "cosmossdk.io/orm/internal/testpb" + "cosmossdk.io/orm/model/ormtable" +) + +func TestTimestampIndex(t *testing.T) { + table, err := ormtable.Build(ormtable.Options{ + MessageType: (&testpb.ExampleTimestamp{}).ProtoReflect().Type(), + }) + assert.NilError(t, err) + backend := testkv.NewDebugBackend(testkv.NewSplitMemBackend(), &testkv.EntryCodecDebugger{ + EntryCodec: table, + }) + ctx := ormtable.WrapContextDefault(backend) + store, err := testpb.NewExampleTimestampTable(table) + assert.NilError(t, err) + + past, err := time.Parse("2006-01-02", "2000-01-01") + assert.NilError(t, err) + middle, err := time.Parse("2006-01-02", "2020-01-01") + assert.NilError(t, err) + future, err := time.Parse("2006-01-02", "2049-01-01") + assert.NilError(t, err) + + pastPb, middlePb, futurePb := timestamppb.New(past), timestamppb.New(middle), timestamppb.New(future) + timeOrder := []*timestamppb.Timestamp{pastPb, middlePb, futurePb} + + assert.NilError(t, store.Insert(ctx, &testpb.ExampleTimestamp{ + Name: "foo", + Ts: pastPb, + })) + assert.NilError(t, store.Insert(ctx, &testpb.ExampleTimestamp{ + Name: "bar", + Ts: middlePb, + })) + assert.NilError(t, store.Insert(ctx, &testpb.ExampleTimestamp{ + Name: "baz", + Ts: futurePb, + })) + + from, to := testpb.ExampleTimestampTsIndexKey{}.WithTs(timestamppb.New(past)), testpb.ExampleTimestampTsIndexKey{}.WithTs(timestamppb.New(future)) + it, err := store.ListRange(ctx, from, to) + assert.NilError(t, err) + + i := 0 + for it.Next() { + v, err := it.Value() + assert.NilError(t, err) + assert.Equal(t, timeOrder[i].String(), v.Ts.String()) + i++ + } + + // insert a nil entry + id, err := store.InsertReturningId(ctx, &testpb.ExampleTimestamp{ + Name: "nil", + Ts: nil, + }) + assert.NilError(t, err) + + res, err := store.Get(ctx, id) + assert.NilError(t, err) + assert.Assert(t, res.Ts == nil) + + it, err = store.List(ctx, testpb.ExampleTimestampTsIndexKey{}) + assert.NilError(t, err) + + // make sure nils are ordered last + timeOrder = append(timeOrder, nil) + i = 0 + for it.Next() { + v, err := it.Value() + assert.NilError(t, err) + assert.Assert(t, v != nil) + x := timeOrder[i] + if x == nil { + assert.Assert(t, v.Ts == nil) + } else { + assert.Equal(t, x.String(), v.Ts.String()) + } + i++ + } + it.Close() + + // try iterating over just nil timestamps + it, err = store.List(ctx, testpb.ExampleTimestampTsIndexKey{}.WithTs(nil)) + assert.NilError(t, err) + assert.Assert(t, it.Next()) + res, err = it.Value() + assert.NilError(t, err) + assert.Assert(t, res.Ts == nil) + assert.Assert(t, !it.Next()) + it.Close() +} diff --git a/orm/model/ormtable/unique.go b/orm/model/ormtable/unique.go index 912b9db16fd8..d82df89a0805 100644 --- a/orm/model/ormtable/unique.go +++ b/orm/model/ormtable/unique.go @@ -3,19 +3,15 @@ package ormtable import ( "context" - "github.com/cosmos/cosmos-sdk/orm/types/kv" - - "github.com/cosmos/cosmos-sdk/orm/internal/fieldnames" - - "github.com/cosmos/cosmos-sdk/orm/model/ormlist" - - "github.com/cosmos/cosmos-sdk/orm/encoding/encodeutil" - "google.golang.org/protobuf/proto" "google.golang.org/protobuf/reflect/protoreflect" - "github.com/cosmos/cosmos-sdk/orm/encoding/ormkv" - "github.com/cosmos/cosmos-sdk/orm/types/ormerrors" + "cosmossdk.io/orm/encoding/encodeutil" + "cosmossdk.io/orm/encoding/ormkv" + "cosmossdk.io/orm/internal/fieldnames" + "cosmossdk.io/orm/model/ormlist" + "cosmossdk.io/orm/types/kv" + "cosmossdk.io/orm/types/ormerrors" ) type uniqueKeyIndex struct { @@ -198,7 +194,7 @@ var ( // isNonTrivialUniqueKey checks if unique key fields are non-trivial, meaning that they // don't contain the full primary key. If they contain the full primary key, then // we can just use a regular index because there is no new unique constraint. -func isNonTrivialUniqueKey(fields []protoreflect.Name, primaryKeyFields []protoreflect.Name) bool { +func isNonTrivialUniqueKey(fields, primaryKeyFields []protoreflect.Name) bool { have := map[protoreflect.Name]bool{} for _, field := range fields { have[field] = true diff --git a/orm/orm.go b/orm/orm.go index 558a061c7460..d533b2b4623d 100644 --- a/orm/orm.go +++ b/orm/orm.go @@ -14,8 +14,8 @@ import ( "cosmossdk.io/depinject" - "github.com/cosmos/cosmos-sdk/orm/model/ormdb" - "github.com/cosmos/cosmos-sdk/orm/model/ormtable" + "cosmossdk.io/orm/model/ormdb" + "cosmossdk.io/orm/model/ormtable" ) func init() { diff --git a/orm/sonar-project.properties b/orm/sonar-project.properties new file mode 100644 index 000000000000..868608220c6e --- /dev/null +++ b/orm/sonar-project.properties @@ -0,0 +1,14 @@ +sonar.projectKey=cosmos-sdk-orm +sonar.organization=cosmos + +sonar.projectName=Cosmos SDK - ORM +sonar.project.monorepo.enabled=true + +sonar.sources=. +sonar.exclusions=**/*_test.go +sonar.tests=. +sonar.test.inclusions=**/*_test.go +sonar.go.coverage.reportPaths=coverage.out + +sonar.sourceEncoding=UTF-8 +sonar.scm.provider=git \ No newline at end of file diff --git a/orm/testing/ormtest/membackend.go b/orm/testing/ormtest/membackend.go index f757daab1508..2fbeda2866d0 100644 --- a/orm/testing/ormtest/membackend.go +++ b/orm/testing/ormtest/membackend.go @@ -2,8 +2,8 @@ package ormtest import ( - "github.com/cosmos/cosmos-sdk/orm/internal/testkv" - "github.com/cosmos/cosmos-sdk/orm/model/ormtable" + "cosmossdk.io/orm/internal/testkv" + "cosmossdk.io/orm/model/ormtable" ) // NewMemoryBackend returns a new ORM memory backend which can be used for diff --git a/orm/types/ormerrors/errors.go b/orm/types/ormerrors/errors.go index ef4dac26e035..2f40da7e7eb3 100644 --- a/orm/types/ormerrors/errors.go +++ b/orm/types/ormerrors/errors.go @@ -12,6 +12,7 @@ func IsNotFound(err error) bool { return errors.IsOf(err, NotFound) } +// nolint: revive // avoid break API var ( InvalidTableId = errors.New(codespace, 1, "invalid or missing table or single id, need a non-zero value") MissingPrimaryKey = errors.New(codespace, 2, "table is missing primary key") diff --git a/proto/cosmos/base/node/v1beta1/query.proto b/proto/cosmos/base/node/v1beta1/query.proto index 8070f7b904f4..78fd9f6703a3 100644 --- a/proto/cosmos/base/node/v1beta1/query.proto +++ b/proto/cosmos/base/node/v1beta1/query.proto @@ -2,6 +2,8 @@ syntax = "proto3"; package cosmos.base.node.v1beta1; import "google/api/annotations.proto"; +import "google/protobuf/timestamp.proto"; +import "gogoproto/gogo.proto"; option go_package = "github.com/cosmos/cosmos-sdk/client/grpc/node"; @@ -11,6 +13,10 @@ service Service { rpc Config(ConfigRequest) returns (ConfigResponse) { option (google.api.http).get = "/cosmos/base/node/v1beta1/config"; } + // Status queries for the node status. + rpc Status(StatusRequest) returns (StatusResponse) { + option (google.api.http).get = "/cosmos/base/node/v1beta1/status"; + } } // ConfigRequest defines the request structure for the Config gRPC query. @@ -19,4 +25,19 @@ message ConfigRequest {} // ConfigResponse defines the response structure for the Config gRPC query. message ConfigResponse { string minimum_gas_price = 1; + // pruning settings + string pruning_keep_recent = 2; + string pruning_interval = 3; +} + +// StateRequest defines the request structure for the status of a node. +message StatusRequest {} + +// StateResponse defines the response structure for the status of a node. +message StatusResponse { + uint64 earliest_store_height = 1; // earliest block height available in the store + uint64 height = 2; // current block height + google.protobuf.Timestamp timestamp = 3 [(gogoproto.stdtime) = true]; // block height timestamp + bytes app_hash = 4; // app hash of the current block + bytes validator_hash = 5; // validator hash provided by the consensus header } diff --git a/proto/cosmos/circuit/module/v1/module.proto b/proto/cosmos/circuit/module/v1/module.proto new file mode 100644 index 000000000000..7104bad4c98f --- /dev/null +++ b/proto/cosmos/circuit/module/v1/module.proto @@ -0,0 +1,15 @@ +syntax = "proto3"; + +package cosmos.circuit.module.v1; + +import "cosmos/app/v1alpha1/module.proto"; + +// Module is the config object of the circuit module. +message Module { + option (cosmos.app.v1alpha1.module) = { + go_import: "cosmossdk.io/x/circuit" + }; + + // authority defines the custom module authority. If not set, defaults to the governance module. + string authority = 1; +} diff --git a/proto/cosmos/circuit/v1/query.proto b/proto/cosmos/circuit/v1/query.proto new file mode 100644 index 000000000000..b57aa56b108c --- /dev/null +++ b/proto/cosmos/circuit/v1/query.proto @@ -0,0 +1,64 @@ +syntax = "proto3"; +package cosmos.circuit.v1; + +option go_package = "cosmossdk.io/x/circuit/types"; + +import "cosmos/base/query/v1beta1/pagination.proto"; +import "cosmos/msg/v1/msg.proto"; +import "cosmos/circuit/v1/types.proto"; +import "google/api/annotations.proto"; +import "cosmos/query/v1/query.proto"; + +// Msg defines the crisis Msg service. +service Query { + option (cosmos.msg.v1.service) = true; + + // Account returns account permissions. + rpc Account(QueryAccountRequest) returns (AccountResponse) { + option (cosmos.query.v1.module_query_safe) = true; + option (google.api.http).get = "/cosmos/circuit/v1/accounts/{address}"; + } + + // Account returns account permissions. + rpc Accounts(QueryAccountsRequest) returns (AccountsResponse) { + option (cosmos.query.v1.module_query_safe) = true; + option (google.api.http).get = "/cosmos/circuit/v1/accounts"; + } + + // DisabledList returns a list of disabled message urls + rpc DisabledList(QueryDisabledListRequest) returns (DisabledListResponse) { + option (cosmos.query.v1.module_query_safe) = true; + option (google.api.http).get = "/cosmos/circuit/v1/disable_list"; + } +} + +// QueryAccountRequest is the request type for the Query/Account RPC method. +message QueryAccountRequest { + string address = 1; +} + +// AccountResponse is the response type for the Query/Account RPC method. +message AccountResponse { + Permissions permission = 1; +} + +// QueryAccountsRequest is the request type for the Query/Accounts RPC method. +message QueryAccountsRequest { + // pagination defines an optional pagination for the request. + cosmos.base.query.v1beta1.PageRequest pagination = 1; +} + +// AccountsResponse is the response type for the Query/Accounts RPC method. +message AccountsResponse { + repeated GenesisAccountPermissions accounts = 1; + // pagination defines the pagination in the response. + cosmos.base.query.v1beta1.PageResponse pagination = 2; +} + +// QueryDisableListRequest is the request type for the Query/DisabledList RPC method. +message QueryDisabledListRequest {} + +// DisabledListResponse is the response type for the Query/DisabledList RPC method. +message DisabledListResponse { + repeated string disabled_list = 1; +} diff --git a/proto/cosmos/circuit/v1/tx.proto b/proto/cosmos/circuit/v1/tx.proto index 4726e3d3e8c0..44e55a9f677c 100644 --- a/proto/cosmos/circuit/v1/tx.proto +++ b/proto/cosmos/circuit/v1/tx.proto @@ -1,9 +1,10 @@ syntax = "proto3"; package cosmos.circuit.v1; -option go_package = "github.com/cosmos/cosmos-sdk/x/circuit/types"; +option go_package = "cosmossdk.io/x/circuit/types"; import "cosmos/msg/v1/msg.proto"; +import "cosmos/circuit/v1/types.proto"; // Msg defines the crisis Msg service. service Msg { @@ -35,43 +36,12 @@ message MsgAuthorizeCircuitBreaker { // permissions are the circuit breaker permissions that the grantee receives. // These will overwrite any existing permissions. LEVEL_NONE_UNSPECIFIED can // be specified to revoke all permissions. - CircuitBreakerPermissions permissions = 3; + Permissions permissions = 3; } // MsgAuthorizeCircuitBreaker defines the Msg/AuthorizeCircuitBreaker response type. -message MsgAuthorizeCircuitBreakerResponse {} - -// CircuitBreakerPermissions are the permissions that an account has to trip -// or reset the circuit breaker. -message CircuitBreakerPermissions { - // level is the level of permissions granted to this account. - Level level = 1; - - // limit_msg_types is used with LEVEL_SOME_MSGS to limit the lists of Msg type - // name that the account can pause. It is an error to use limit_msg_types with - // a level other than LEVEL_SOME_MSGS. - repeated string limit_msg_types = 2; - - // Level is the permission level. - enum Level { - // LEVEL_NONE_UNSPECIFIED indicates that the account will have no circuit - // breaker permissions. - LEVEL_NONE_UNSPECIFIED = 0; - - // LEVEL_SOME_MSGS indicates that the account will have permission to - // trip or reset the circuit breaker for some Msg type URLs. If this level - // is chosen, a non-empty list of Msg type URLs must be provided in - // limit_type_urls. - LEVEL_SOME_MSGS = 1; - - // LEVEL_ALL_MSGS indicates that the account can trip or reset the circuit - // breaker for Msg's of all type URLs. - LEVEL_ALL_MSGS = 2; - - // LEVEL_SUPER_ADMIN indicates that the account can take all circuit breaker - // actions and can grant permissions to other accounts. - LEVEL_SUPER_ADMIN = 3; - } +message MsgAuthorizeCircuitBreakerResponse { + bool success = 1; } // MsgTripCircuitBreaker defines the Msg/TripCircuitBreaker request type. @@ -90,7 +60,9 @@ message MsgTripCircuitBreaker { } // MsgTripCircuitBreaker defines the Msg/TripCircuitBreaker response type. -message MsgTripCircuitBreakerResponse {} +message MsgTripCircuitBreakerResponse { + bool success = 1; +} // MsgResetCircuitBreaker defines the Msg/ResetCircuitBreaker request type. message MsgResetCircuitBreaker { @@ -106,4 +78,6 @@ message MsgResetCircuitBreaker { } // MsgResetCircuitBreakerResponse defines the Msg/ResetCircuitBreaker response type. -message MsgResetCircuitBreakerResponse {} +message MsgResetCircuitBreakerResponse { + bool success = 1; +} diff --git a/proto/cosmos/circuit/v1/types.proto b/proto/cosmos/circuit/v1/types.proto new file mode 100644 index 000000000000..1bd8d9d4484e --- /dev/null +++ b/proto/cosmos/circuit/v1/types.proto @@ -0,0 +1,49 @@ +syntax = "proto3"; +package cosmos.circuit.v1; + +option go_package = "cosmossdk.io/x/circuit/types"; + +// Permissions are the permissions that an account has to trip +// or reset the circuit breaker. +message Permissions { + // level is the level of permissions granted to this account. + Level level = 1; + + // limit_type_urls is used with LEVEL_SOME_MSGS to limit the lists of Msg type + // URLs that the account can trip. It is an error to use limit_type_urls with + // a level other than LEVEL_SOME_MSGS. + repeated string limit_type_urls = 2; + + // Level is the permission level. + enum Level { + // LEVEL_NONE_UNSPECIFIED indicates that the account will have no circuit + // breaker permissions. + LEVEL_NONE_UNSPECIFIED = 0; + + // LEVEL_SOME_MSGS indicates that the account will have permission to + // trip or reset the circuit breaker for some Msg type URLs. If this level + // is chosen, a non-empty list of Msg type URLs must be provided in + // limit_type_urls. + LEVEL_SOME_MSGS = 1; + + // LEVEL_ALL_MSGS indicates that the account can trip or reset the circuit + // breaker for Msg's of all type URLs. + LEVEL_ALL_MSGS = 2; + + // LEVEL_SUPER_ADMIN indicates that the account can take all circuit breaker + // actions and can grant permissions to other accounts. + LEVEL_SUPER_ADMIN = 3; + } +} + +// GenesisAccountPermissions is the account permissions for the circuit breaker in genesis +message GenesisAccountPermissions { + string address = 1; + Permissions permissions = 2; +} + +// GenesisState is the state that must be provided at genesis. +message GenesisState { + repeated GenesisAccountPermissions account_permissions = 1; + repeated string disabled_type_urls = 2; +} diff --git a/proto/cosmos/crypto/ed25519/keys.proto b/proto/cosmos/crypto/ed25519/keys.proto index 728b54839edf..31768075a204 100644 --- a/proto/cosmos/crypto/ed25519/keys.proto +++ b/proto/cosmos/crypto/ed25519/keys.proto @@ -29,7 +29,7 @@ message PubKey { bytes key = 1 [(gogoproto.casttype) = "crypto/ed25519.PublicKey"]; } -// Deprecated: PrivKey defines a ed25519 private key. +// PrivKey defines a ed25519 private key. // NOTE: ed25519 keys must not be used in SDK apps except in a tendermint validator context. message PrivKey { option (amino.name) = "tendermint/PrivKeyEd25519"; diff --git a/proto/cosmos/distribution/v1beta1/tx.proto b/proto/cosmos/distribution/v1beta1/tx.proto index 6a69bcca7c9c..ebc47eaab9c1 100644 --- a/proto/cosmos/distribution/v1beta1/tx.proto +++ b/proto/cosmos/distribution/v1beta1/tx.proto @@ -193,12 +193,12 @@ message MsgCommunityPoolSpendResponse {} // Since: cosmos-sdk 0.48 message MsgDepositValidatorRewardsPool { option (amino.name) = "cosmos-sdk/distr/MsgDepositValRewards"; - option (cosmos.msg.v1.signer) = "authority"; + option (cosmos.msg.v1.signer) = "depositor"; option (gogoproto.equal) = false; option (gogoproto.goproto_getters) = false; - string authority = 1 [(cosmos_proto.scalar) = "cosmos.AddressString"]; + string depositor = 1 [(cosmos_proto.scalar) = "cosmos.AddressString"]; string validator_address = 2 [(cosmos_proto.scalar) = "cosmos.AddressString"]; repeated cosmos.base.v1beta1.Coin amount = 3 [ (gogoproto.nullable) = false, diff --git a/proto/cosmos/orm/module/v1alpha1/module.proto b/proto/cosmos/orm/module/v1alpha1/module.proto index d8e7fa1f48d8..260db3699745 100644 --- a/proto/cosmos/orm/module/v1alpha1/module.proto +++ b/proto/cosmos/orm/module/v1alpha1/module.proto @@ -9,6 +9,6 @@ import "cosmos/app/v1alpha1/module.proto"; // services for modules that use the ORM. message Module { option (cosmos.app.v1alpha1.module) = { - go_import: "github.com/cosmos/cosmos-sdk/orm" + go_import: "cosmossdk.io/orm" }; } diff --git a/proto/cosmos/slashing/v1beta1/slashing.proto b/proto/cosmos/slashing/v1beta1/slashing.proto index a4d2129b1438..65bd4800e677 100644 --- a/proto/cosmos/slashing/v1beta1/slashing.proto +++ b/proto/cosmos/slashing/v1beta1/slashing.proto @@ -16,20 +16,24 @@ message ValidatorSigningInfo { option (gogoproto.equal) = true; string address = 1 [(cosmos_proto.scalar) = "cosmos.AddressString"]; - // Height at which validator was first a candidate OR was unjailed + // Height at which validator was first a candidate OR was un-jailed int64 start_height = 2; - // Index which is incremented each time the validator was a bonded - // in a block and may have signed a precommit or not. This in conjunction with the - // `SignedBlocksWindow` param determines the index in the `MissedBlocksBitArray`. + // Index which is incremented every time a validator is bonded in a block and + // _may_ have signed a pre-commit or not. This in conjunction with the + // signed_blocks_window param determines the index in the missed block bitmap. int64 index_offset = 3; // Timestamp until which the validator is jailed due to liveness downtime. - google.protobuf.Timestamp jailed_until = 4 - [(gogoproto.stdtime) = true, (gogoproto.nullable) = false, (amino.dont_omitempty) = true]; - // Whether or not a validator has been tombstoned (killed out of validator set). It is set - // once the validator commits an equivocation or for any other configured misbehiavor. + google.protobuf.Timestamp jailed_until = 4 [ + (gogoproto.stdtime) = true, + (gogoproto.nullable) = false, + (amino.dont_omitempty) = true + ]; + // Whether or not a validator has been tombstoned (killed out of validator + // set). It is set once the validator commits an equivocation or for any other + // configured misbehavior. bool tombstoned = 5; - // A counter kept to avoid unnecessary array reads. - // Note that `Sum(MissedBlocksBitArray)` always equals `MissedBlocksCounter`. + // A counter of missed (unsigned) blocks. It is used to avoid unnecessary + // reads in the missed block bitmap. int64 missed_blocks_counter = 6; } @@ -44,8 +48,11 @@ message Params { (amino.encoding) = "cosmos_dec_bytes", (amino.dont_omitempty) = true ]; - google.protobuf.Duration downtime_jail_duration = 3 - [(gogoproto.nullable) = false, (amino.dont_omitempty) = true, (gogoproto.stdduration) = true]; + google.protobuf.Duration downtime_jail_duration = 3 [ + (gogoproto.nullable) = false, + (amino.dont_omitempty) = true, + (gogoproto.stdduration) = true + ]; bytes slash_fraction_double_sign = 4 [ (gogoproto.customtype) = "github.com/cosmos/cosmos-sdk/types.Dec", (gogoproto.nullable) = false, diff --git a/proto/cosmos/store/v1beta1/commit_info.proto b/proto/cosmos/store/v1beta1/commit_info.proto index b9abea9a80bd..a931e3e7d762 100644 --- a/proto/cosmos/store/v1beta1/commit_info.proto +++ b/proto/cosmos/store/v1beta1/commit_info.proto @@ -2,14 +2,17 @@ syntax = "proto3"; package cosmos.store.v1beta1; import "gogoproto/gogo.proto"; +import "google/protobuf/timestamp.proto"; option go_package = "cosmossdk.io/store/types"; // CommitInfo defines commit information used by the multi-store when committing // a version/height. message CommitInfo { - int64 version = 1; - repeated StoreInfo store_infos = 2 [(gogoproto.nullable) = false]; + int64 version = 1; + repeated StoreInfo store_infos = 2 [(gogoproto.nullable) = false]; + google.protobuf.Timestamp timestamp = 3 + [(gogoproto.nullable) = false, (gogoproto.stdtime) = true]; } // StoreInfo defines store-specific commit information. It contains a reference diff --git a/runtime/app.go b/runtime/app.go index 7388ec9faa23..4bfd07798f20 100644 --- a/runtime/app.go +++ b/runtime/app.go @@ -4,13 +4,11 @@ import ( "encoding/json" "fmt" - abci "github.com/cometbft/cometbft/abci/types" - "golang.org/x/exp/slices" - runtimev1alpha1 "cosmossdk.io/api/cosmos/app/runtime/v1alpha1" appv1alpha1 "cosmossdk.io/api/cosmos/app/v1alpha1" - storetypes "cosmossdk.io/store/types" + abci "github.com/cometbft/cometbft/abci/types" + "golang.org/x/exp/slices" "github.com/cosmos/cosmos-sdk/baseapp" "github.com/cosmos/cosmos-sdk/client" @@ -167,8 +165,8 @@ func (a *App) RegisterTendermintService(clientCtx client.Context) { } // RegisterNodeService registers the node gRPC service on the app gRPC router. -func (a *App) RegisterNodeService(clientCtx client.Context) { - nodeservice.RegisterNodeService(clientCtx, a.GRPCQueryRouter()) +func (a *App) RegisterNodeService(clientCtx client.Context, cfg config.Config) { + nodeservice.RegisterNodeService(clientCtx, a.GRPCQueryRouter(), cfg) } // Configurator returns the app's configurator. diff --git a/runtime/events.go b/runtime/events.go new file mode 100644 index 000000000000..4139ede7b7d6 --- /dev/null +++ b/runtime/events.go @@ -0,0 +1,59 @@ +package runtime + +import ( + "context" + + "cosmossdk.io/core/event" + "google.golang.org/protobuf/runtime/protoiface" + + sdk "github.com/cosmos/cosmos-sdk/types" +) + +var _ event.Service = (*EventService)(nil) + +type EventService struct { + Events +} + +func (es EventService) EventManager(ctx context.Context) event.Manager { + sdkCtx := sdk.UnwrapSDKContext(ctx) + return &Events{sdkCtx.EventManager()} +} + +var _ event.Manager = (*Events)(nil) + +type Events struct { + sdk.EventManagerI +} + +func NewEventManager(ctx context.Context) event.Manager { + sdkCtx := sdk.UnwrapSDKContext(ctx) + return &Events{sdkCtx.EventManager()} +} + +// Emit emits an typed event that is defined in the protobuf file. +// In the future these events will be added to consensus +func (e Events) Emit(ctx context.Context, event protoiface.MessageV1) error { + return e.EventManagerI.EmitTypedEvent(event) +} + +// EmitKV emits a key value pair event +func (e Events) EmitKV(ctx context.Context, eventType string, attrs ...event.Attribute) error { + attributes := make([]sdk.Attribute, 0, len(attrs)) + + for _, attr := range attrs { + attributes = append(attributes, sdk.NewAttribute(attr.Key, attr.Value)) + } + + events := sdk.Events{ + sdk.NewEvent(eventType, attributes...), + } + e.EventManagerI.EmitEvents(events) + return nil +} + +// Emit emits an typed event that is defined in the protobuf file. +// In the future these events will be added to consensus +func (e Events) EmitNonConsensus(ctx context.Context, event protoiface.MessageV1) error { + return e.EventManagerI.EmitTypedEvent(event) +} diff --git a/runtime/module.go b/runtime/module.go index 30556ba050a6..82ee40470fba 100644 --- a/runtime/module.go +++ b/runtime/module.go @@ -5,6 +5,7 @@ import ( "os" "cosmossdk.io/core/store" + "github.com/cosmos/gogoproto/proto" "google.golang.org/protobuf/reflect/protodesc" "google.golang.org/protobuf/reflect/protoregistry" @@ -13,6 +14,7 @@ import ( runtimev1alpha1 "cosmossdk.io/api/cosmos/app/runtime/v1alpha1" appv1alpha1 "cosmossdk.io/api/cosmos/app/v1alpha1" "cosmossdk.io/core/appmodule" + "cosmossdk.io/core/event" "cosmossdk.io/depinject" storetypes "cosmossdk.io/store/types" @@ -23,7 +25,6 @@ import ( "github.com/cosmos/cosmos-sdk/std" "github.com/cosmos/cosmos-sdk/types/module" "github.com/cosmos/cosmos-sdk/types/msgservice" - "github.com/cosmos/gogoproto/proto" ) type appModule struct { @@ -63,6 +64,7 @@ func init() { ProvideKVStoreService, ProvideMemoryStoreService, ProvideTransientStoreService, + ProvideEventService, ), appmodule.Invoke(SetupAppBuilder), ) @@ -78,8 +80,23 @@ func ProvideApp() ( appmodule.AppModule, protodesc.Resolver, protoregistry.MessageTypeResolver, + error, ) { - interfaceRegistry := codectypes.NewInterfaceRegistry() + protoFiles, err := proto.MergedRegistry() + if err != nil { + return nil, nil, nil, nil, nil, nil, nil, nil, nil, err + } + protoTypes := protoregistry.GlobalTypes + + // At startup, check that all proto annotations are correct. + err = msgservice.ValidateProtoAnnotations(protoFiles) + if err != nil { + // Once we switch to using protoreflect-based antehandlers, we might + // want to panic here instead of logging a warning. + _, _ = fmt.Fprintln(os.Stderr, err.Error()) + } + + interfaceRegistry := codectypes.NewInterfaceRegistryWithProtoFiles(protoFiles) amino := codec.NewLegacyAmino() std.RegisterInterfaces(interfaceRegistry) @@ -97,21 +114,7 @@ func ProvideApp() ( } appBuilder := &AppBuilder{app} - protoFiles, err := proto.MergedRegistry() - if err != nil { - panic(err) - } - protoTypes := protoregistry.GlobalTypes - - // At startup, check that all proto annotations are correct. - err = msgservice.ValidateProtoAnnotations(protoFiles) - if err != nil { - // Once we switch to using protoreflect-based antehandlers, we might - // want to panic here instead of logging a warning. - fmt.Fprintln(os.Stderr, err.Error()) - } - - return interfaceRegistry, cdc, amino, appBuilder, cdc, msgServiceRouter, appModule{app}, protoFiles, protoTypes + return interfaceRegistry, cdc, amino, appBuilder, cdc, msgServiceRouter, appModule{app}, protoFiles, protoTypes, nil } type AppInputs struct { @@ -202,3 +205,7 @@ func ProvideTransientStoreService(key depinject.ModuleKey, app *AppBuilder) stor storeKey := ProvideTransientStoreKey(key, app) return transientStoreService{key: storeKey} } + +func ProvideEventService() event.Service { + return EventService{} +} diff --git a/runtime/services.go b/runtime/services.go index 0b9223d92a29..34f86e612d08 100644 --- a/runtime/services.go +++ b/runtime/services.go @@ -4,6 +4,7 @@ import ( appv1alpha1 "cosmossdk.io/api/cosmos/app/v1alpha1" autocliv1 "cosmossdk.io/api/cosmos/autocli/v1" reflectionv1 "cosmossdk.io/api/cosmos/reflection/v1" + abci "github.com/cometbft/cometbft/abci/types" "github.com/cosmos/cosmos-sdk/runtime/services" "github.com/cosmos/cosmos-sdk/types/module" @@ -21,3 +22,19 @@ func (a *App) registerRuntimeServices(cfg module.Configurator) error { return nil } + +// ====================================================== +// BlockInfoService +// ====================================================== + +// BlockInfoService is the service that runtime will provide to modules which need Comet block information. +type BlockInfoService interface { + GetHeight() int64 // GetHeight returns the height of the block + Misbehavior() []abci.Misbehavior // Misbehavior returns the misbehavior of the block + GetHeaderHash() []byte // GetHeaderHash returns the hash of the block header + // GetValidatorsHash returns the hash of the validators + // For Comet, it is the hash of the next validators + GetValidatorsHash() []byte + GetProposerAddress() []byte // GetProposerAddress returns the address of the block proposer + GetDecidedLastCommit() abci.CommitInfo // GetDecidedLastCommit returns the last commit info +} diff --git a/runtime/services/reflection.go b/runtime/services/reflection.go index 6140eff38655..890ff66e350e 100644 --- a/runtime/services/reflection.go +++ b/runtime/services/reflection.go @@ -15,7 +15,7 @@ type ReflectionService struct { } func NewReflectionService() (*ReflectionService, error) { - fds, err := proto.MergedFileDescriptors() + fds, err := proto.MergedGlobalFileDescriptors() if err != nil { return nil, err } diff --git a/runtime/store.go b/runtime/store.go index ed4a11dda11b..9374fb0c199f 100644 --- a/runtime/store.go +++ b/runtime/store.go @@ -2,11 +2,14 @@ package runtime import ( "context" + "io" "cosmossdk.io/core/store" storetypes "cosmossdk.io/store/types" + dbm "github.com/cosmos/cosmos-db" + sdk "github.com/cosmos/cosmos-sdk/types" ) @@ -90,3 +93,72 @@ func (store coreKVStore) Iterator(start, end []byte) (store.Iterator, error) { func (store coreKVStore) ReverseIterator(start, end []byte) (store.Iterator, error) { return store.kvStore.ReverseIterator(start, end), nil } + +// Adapter +var _ storetypes.KVStore = kvStoreAdapter{} + +type kvStoreAdapter struct { + store store.KVStore +} + +func (kvStoreAdapter) CacheWrap() storetypes.CacheWrap { + panic("unimplemented") +} + +func (kvStoreAdapter) CacheWrapWithTrace(w io.Writer, tc storetypes.TraceContext) storetypes.CacheWrap { + panic("unimplemented") +} + +func (kvStoreAdapter) GetStoreType() storetypes.StoreType { + panic("unimplemented") +} + +func (s kvStoreAdapter) Delete(key []byte) { + err := s.store.Delete(key) + if err != nil { + panic(err) + } +} + +func (s kvStoreAdapter) Get(key []byte) []byte { + bz, err := s.store.Get(key) + if err != nil { + panic(err) + } + return bz +} + +func (s kvStoreAdapter) Has(key []byte) bool { + has, err := s.store.Has(key) + if err != nil { + panic(err) + } + return has +} + +func (s kvStoreAdapter) Set(key, value []byte) { + err := s.store.Set(key, value) + if err != nil { + panic(err) + } +} + +func (s kvStoreAdapter) Iterator(start, end []byte) dbm.Iterator { + it, err := s.store.Iterator(start, end) + if err != nil { + panic(err) + } + return it +} + +func (s kvStoreAdapter) ReverseIterator(start, end []byte) dbm.Iterator { + it, err := s.store.ReverseIterator(start, end) + if err != nil { + panic(err) + } + return it +} + +func KVStoreAdapter(store store.KVStore) storetypes.KVStore { + return &kvStoreAdapter{store} +} diff --git a/runtime/types.go b/runtime/types.go index c363d083abb7..db5ab446c32e 100644 --- a/runtime/types.go +++ b/runtime/types.go @@ -34,7 +34,7 @@ type AppI interface { LoadHeight(height int64) error // Exports the state of the application for a genesis file. - ExportAppStateAndValidators(forZeroHeight bool, jailAllowedAddrs []string, modulesToExport []string) (types.ExportedApp, error) + ExportAppStateAndValidators(forZeroHeight bool, jailAllowedAddrs, modulesToExport []string) (types.ExportedApp, error) // Helper for the simulation framework. SimulationManager() *module.SimulationManager diff --git a/scripts/go-lint-all.bash b/scripts/go-lint-all.bash new file mode 100755 index 000000000000..b99606844d79 --- /dev/null +++ b/scripts/go-lint-all.bash @@ -0,0 +1,18 @@ +#!/usr/bin/env bash + +set -eu -o pipefail + +REPO_ROOT="$( cd -- "$( dirname -- "${BASH_SOURCE[0]}" )/.." &> /dev/null && pwd )" +export REPO_ROOT + +lint_module() { + local root="$1" + shift + cd "$(dirname "$root")" && + echo "linting $(grep "^module" go.mod) [$(date -Iseconds -u)]" && + golangci-lint run ./... -c "${REPO_ROOT}/.golangci.yml" "$@" +} +export -f lint_module + +find "${REPO_ROOT}" -type f -name go.mod -print0 | + xargs -0 -I{} bash -c 'lint_module "$@"' _ {} "$@" # Prepend go.mod file before command-line args. diff --git a/scripts/init-simapp.sh b/scripts/init-simapp.sh new file mode 100755 index 000000000000..5db89d2c5066 --- /dev/null +++ b/scripts/init-simapp.sh @@ -0,0 +1,16 @@ +#!/bin/bash + +SIMD_BIN=${SIMD_BIN:=$(which simd 2>/dev/null)} + +if [ -z "$SIMD_BIN" ]; then echo "SIMD_BIN is not set. Make sure to run make install before"; exit 1; fi +echo "using $SIMD_BIN" +if [ -d "$($SIMD_BIN config home)" ]; then rm -r $($SIMD_BIN config home); fi +$SIMD_BIN config set client chain-id demo +$SIMD_BIN config set client keyring-backend test +$SIMD_BIN keys add alice +$SIMD_BIN keys add bob +$SIMD_BIN init test --chain-id demo +$SIMD_BIN genesis add-genesis-account alice 5000000000stake --keyring-backend test +$SIMD_BIN genesis add-genesis-account bob 5000000000stake --keyring-backend test +$SIMD_BIN genesis gentx alice 1000000stake --chain-id demo +$SIMD_BIN genesis collect-gentxs \ No newline at end of file diff --git a/scripts/protocgen-pulsar.sh b/scripts/protocgen-pulsar.sh index 05d1e8532dc7..c859c71fc8ac 100755 --- a/scripts/protocgen-pulsar.sh +++ b/scripts/protocgen-pulsar.sh @@ -17,3 +17,6 @@ echo "Generating API module" echo "Generate Pulsar Test Data" (cd testutil/testdata; buf generate --template buf.gen.pulsar.yaml) + +echo "Generate x/tx" +(cd x/tx; make codegen) \ No newline at end of file diff --git a/server/api/server.go b/server/api/server.go index 0f5090da1bcc..d48ef7a1a19f 100644 --- a/server/api/server.go +++ b/server/api/server.go @@ -60,7 +60,7 @@ func CustomGRPCHeaderMatcher(key string) (string, bool) { func New(clientCtx client.Context, logger log.Logger, grpcSrv *grpc.Server) *Server { // The default JSON marshaller used by the gRPC-Gateway is unable to marshal non-nullable non-scalar fields. - // Using the gogo/gateway package with the gRPC-Gateway WithMarshaler option fixes the scalar field marshalling issue. + // Using the gogo/gateway package with the gRPC-Gateway WithMarshaler option fixes the scalar field marshaling issue. marshalerOption := &gateway.JSONPb{ EmitDefaults: true, Indent: " ", @@ -77,7 +77,7 @@ func New(clientCtx client.Context, logger log.Logger, grpcSrv *grpc.Server) *Ser runtime.WithMarshalerOption(runtime.MIMEWildcard, marshalerOption), // This is necessary to get error details properly - // marshalled in unary requests. + // marshaled in unary requests. runtime.WithProtoErrorHandler(runtime.DefaultHTTPProtoErrorHandler), // Custom header matcher for mapping request headers to @@ -159,7 +159,7 @@ func (s *Server) Start(ctx context.Context, cfg config.Config) error { // the server failed to start properly. select { case <-ctx.Done(): - // The calling process cancelled or closed the provided context, so we must + // The calling process canceled or closed the provided context, so we must // gracefully stop the API server. s.logger.Info("stopping API server...", "address", cfg.API.Address) return s.Close() diff --git a/server/api/server_test.go b/server/api/server_test.go index ca906dccdd48..34b51bf48990 100644 --- a/server/api/server_test.go +++ b/server/api/server_test.go @@ -126,7 +126,7 @@ func serializeProtoMessages(messages []proto.Message) [][]byte { } func (s *GRPCWebTestSuite) makeRequest( - verb string, method string, headers http.Header, body io.Reader, isText bool, + verb, method string, headers http.Header, body io.Reader, isText bool, ) (*http.Response, error) { val := s.network.Validators[0] contentType := "application/grpc-web" diff --git a/server/cmd/execute.go b/server/cmd/execute.go index c7842c690cb0..7a1a0c5ad1f3 100644 --- a/server/cmd/execute.go +++ b/server/cmd/execute.go @@ -3,7 +3,6 @@ package cmd import ( "context" - cmtcfg "github.com/cometbft/cometbft/config" cmtcli "github.com/cometbft/cometbft/libs/cli" "github.com/rs/zerolog" "github.com/spf13/cobra" @@ -17,7 +16,7 @@ import ( // server context object with the appropriate server and client objects injected // into the underlying stdlib Context. It also handles adding core CLI flags, // specifically the logging flags. It returns an error upon execution failure. -func Execute(rootCmd *cobra.Command, envPrefix string, defaultHome string) error { +func Execute(rootCmd *cobra.Command, envPrefix, defaultHome string) error { // Create and set a client.Context on the command's Context. During the pre-run // of the root command, a default initialized client.Context is provided to // seed child command execution with values such as AccountRetriever, Keyring, @@ -27,7 +26,8 @@ func Execute(rootCmd *cobra.Command, envPrefix string, defaultHome string) error ctx := CreateExecuteContext(context.Background()) rootCmd.PersistentFlags().String(flags.FlagLogLevel, zerolog.InfoLevel.String(), "The logging level (trace|debug|info|warn|error|fatal|panic)") - rootCmd.PersistentFlags().String(flags.FlagLogFormat, cmtcfg.LogFormatPlain, "The logging format (json|plain)") + // NOTE: The default logger is only checking for the "json" value, any other value will default to plain text. + rootCmd.PersistentFlags().String(flags.FlagLogFormat, "plain", "The logging format (json|plain)") executor := cmtcli.PrepareBaseCmd(rootCmd, envPrefix, defaultHome) return executor.ExecuteContext(ctx) diff --git a/server/export_test.go b/server/export_test.go index 3ec00032c1c1..6d1886469181 100644 --- a/server/export_test.go +++ b/server/export_test.go @@ -101,7 +101,7 @@ func isZeroExportedApp(a types.ExportedApp) bool { return a.AppState == nil && len(a.Validators) == 0 && a.Height == 0 && - a.ConsensusParams == nil + a.ConsensusParams == cmtproto.ConsensusParams{} } // mockExporter provides an Export method matching server/types.AppExporter, @@ -127,7 +127,7 @@ type mockExporter struct { // when e.Export is called. func (e *mockExporter) SetDefaultExportApp() { e.ExportApp = types.ExportedApp{ - ConsensusParams: &cmtproto.ConsensusParams{ + ConsensusParams: cmtproto.ConsensusParams{ Block: &cmtproto.BlockParams{ MaxBytes: 5 * 1024 * 1024, MaxGas: -1, diff --git a/server/grpc/gogoreflection/fix_registration.go b/server/grpc/gogoreflection/fix_registration.go index 7d7d3dce2b71..58cc60c4a760 100644 --- a/server/grpc/gogoreflection/fix_registration.go +++ b/server/grpc/gogoreflection/fix_registration.go @@ -7,7 +7,7 @@ import ( gogoproto "github.com/cosmos/gogoproto/proto" _ "github.com/cosmos/cosmos-proto" // look above - "github.com/golang/protobuf/proto" //nolint:staticcheck + "github.com/golang/protobuf/proto" //nolint:staticcheck // migrate in a future pr ) func getFileDescriptor(filePath string) []byte { @@ -18,7 +18,7 @@ func getFileDescriptor(filePath string) []byte { return fd } - return proto.FileDescriptor(filePath) //nolint:staticcheck + return proto.FileDescriptor(filePath) //nolint:staticcheck // keep for backward compatibility } func getMessageType(name string) reflect.Type { @@ -27,7 +27,7 @@ func getMessageType(name string) reflect.Type { return typ } - return proto.MessageType(name) //nolint:staticcheck + return proto.MessageType(name) //nolint:staticcheck // keep for backward compatibility } func getExtension(extID int32, m proto.Message) *gogoproto.ExtensionDesc { @@ -39,8 +39,7 @@ func getExtension(extID int32, m proto.Message) *gogoproto.ExtensionDesc { } // check into proto registry - //nolint:staticcheck - for id, desc := range proto.RegisteredExtensions(m) { + for id, desc := range proto.RegisteredExtensions(m) { //nolint:staticcheck // kept for backwards compatibility if id == extID { return &gogoproto.ExtensionDesc{ ExtendedType: desc.ExtendedType, @@ -67,7 +66,7 @@ func getExtensionsNumbers(m proto.Message) []int32 { return out } - protoExts := proto.RegisteredExtensions(m) //nolint:staticcheck + protoExts := proto.RegisteredExtensions(m) //nolint:staticcheck // kept for backwards compatibility out = make([]int32, 0, len(protoExts)) for id := range protoExts { out = append(out, id) diff --git a/server/grpc/gogoreflection/serverreflection.go b/server/grpc/gogoreflection/serverreflection.go index ac1e3c2d0526..55fb9ad5fe31 100644 --- a/server/grpc/gogoreflection/serverreflection.go +++ b/server/grpc/gogoreflection/serverreflection.go @@ -46,7 +46,7 @@ import ( "sort" "sync" - //nolint: staticcheck + //nolint: staticcheck // keep this import for backward compatibility "github.com/golang/protobuf/proto" dpb "github.com/golang/protobuf/protoc-gen-go/descriptor" "google.golang.org/grpc" @@ -290,8 +290,8 @@ func fileDescWithDependencies(fd *dpb.FileDescriptorProto, sentFileDescriptors m } // fileDescEncodingByFilename finds the file descriptor for given filename, -// finds all of its previously unsent transitive dependencies, does marshalling -// on them, and returns the marshalled result. +// finds all of its previously unsent transitive dependencies, does marshaling +// on them, and returns the marshaled result. func (s *serverReflectionServer) fileDescEncodingByFilename(name string, sentFileDescriptors map[string]bool) ([][]byte, error) { enc := getFileDescriptor(name) if enc == nil { @@ -324,7 +324,7 @@ func parseMetadata(meta interface{}) ([]byte, bool) { // fileDescEncodingContainingSymbol finds the file descriptor containing the // given symbol, finds all of its previously unsent transitive dependencies, -// does marshalling on them, and returns the marshalled result. The given symbol +// does marshaling on them, and returns the marshaled result. The given symbol // can be a type, a service or a method. func (s *serverReflectionServer) fileDescEncodingContainingSymbol(name string, sentFileDescriptors map[string]bool) ([][]byte, error) { _, symbols := s.getSymbols() @@ -349,7 +349,7 @@ func (s *serverReflectionServer) fileDescEncodingContainingSymbol(name string, s // fileDescEncodingContainingExtension finds the file descriptor containing // given extension, finds all of its previously unsent transitive dependencies, -// does marshalling on them, and returns the marshalled result. +// does marshaling on them, and returns the marshaled result. func (s *serverReflectionServer) fileDescEncodingContainingExtension(typeName string, extNum int32, sentFileDescriptors map[string]bool) ([][]byte, error) { st, err := typeForName(typeName) if err != nil { diff --git a/server/grpc/server.go b/server/grpc/server.go index 4c809e8655ed..51bcf3f445b9 100644 --- a/server/grpc/server.go +++ b/server/grpc/server.go @@ -5,9 +5,10 @@ import ( "fmt" "net" - "cosmossdk.io/log" "google.golang.org/grpc" + "cosmossdk.io/log" + "github.com/cosmos/cosmos-sdk/client" "github.com/cosmos/cosmos-sdk/codec" "github.com/cosmos/cosmos-sdk/server/config" @@ -44,8 +45,9 @@ func NewGRPCServer(clientCtx client.Context, app types.Application, cfg config.G // time. err := reflection.Register(grpcSrv, reflection.Config{ SigningModes: func() map[string]int32 { - modes := make(map[string]int32, len(clientCtx.TxConfig.SignModeHandler().Modes())) - for _, m := range clientCtx.TxConfig.SignModeHandler().Modes() { + supportedModes := clientCtx.TxConfig.SignModeHandler().SupportedModes() + modes := make(map[string]int32, len(supportedModes)) + for _, m := range supportedModes { modes[m.String()] = (int32)(m) } @@ -91,7 +93,7 @@ func StartGRPCServer(ctx context.Context, logger log.Logger, cfg config.GRPCConf // the server failed to start properly. select { case <-ctx.Done(): - // The calling process cancelled or closed the provided context, so we must + // The calling process canceled or closed the provided context, so we must // gracefully stop the gRPC server. logger.Info("stopping gRPC server...", "address", cfg.Address) grpcSrv.GracefulStop() diff --git a/server/mock/app.go b/server/mock/app.go index 5c977b53d21f..078bf2adf69e 100644 --- a/server/mock/app.go +++ b/server/mock/app.go @@ -47,7 +47,7 @@ func NewApp(rootDir string, logger log.Logger) (abci.Application, error) { Methods: []grpc.MethodDesc{ { MethodName: "Test", - Handler: _Msg_Test_Handler, + Handler: MsgTestHandler, }, }, } @@ -147,7 +147,7 @@ type MsgServerImpl struct { capKeyMainStore *storetypes.KVStoreKey } -func _Msg_Test_Handler(srv interface{}, ctx context.Context, dec func(interface{}) error, interceptor grpc.UnaryServerInterceptor) (interface{}, error) { //nolint:revive +func MsgTestHandler(srv interface{}, ctx context.Context, dec func(interface{}) error, interceptor grpc.UnaryServerInterceptor) (interface{}, error) { // nolint: revive // refactor this in a followup pr in := new(KVStoreTx) if err := dec(in); err != nil { return nil, err diff --git a/server/mock/app_test.go b/server/mock/app_test.go index c3fcd15b4ec7..c40dbf67b7c4 100644 --- a/server/mock/app_test.go +++ b/server/mock/app_test.go @@ -5,12 +5,11 @@ import ( "testing" "time" + "cosmossdk.io/log" abci "github.com/cometbft/cometbft/abci/types" cmtproto "github.com/cometbft/cometbft/proto/tendermint/types" "github.com/stretchr/testify/require" - "cosmossdk.io/log" - simtypes "github.com/cosmos/cosmos-sdk/types/simulation" genutiltypes "github.com/cosmos/cosmos-sdk/x/genutil/types" ) diff --git a/server/mock/store.go b/server/mock/store.go index 31b73f3fd86f..2094e2905d0a 100644 --- a/server/mock/store.go +++ b/server/mock/store.go @@ -168,6 +168,10 @@ func (ms multiStore) LatestVersion() int64 { panic("not implemented") } +func (ms multiStore) WorkingHash() []byte { + panic("not implemented") +} + var _ storetypes.KVStore = kvStore{} type kvStore struct { diff --git a/server/mock/tx.go b/server/mock/tx.go index f9f1c394dc99..e494fc470c3f 100644 --- a/server/mock/tx.go +++ b/server/mock/tx.go @@ -37,7 +37,7 @@ func (t testPubKey) Address() cryptotypes.Address { return t.address.Bytes() } func (t testPubKey) Bytes() []byte { panic("not implemented") } -func (t testPubKey) VerifySignature(msg []byte, sig []byte) bool { panic("not implemented") } +func (t testPubKey) VerifySignature(msg, sig []byte) bool { panic("not implemented") } func (t testPubKey) Equals(key cryptotypes.PubKey) bool { panic("not implemented") } @@ -53,7 +53,7 @@ func (msg *KVStoreTx) GetSignaturesV2() (res []txsigning.SignatureV2, err error) return res, nil } -func (msg *KVStoreTx) VerifySignature(msgByte []byte, sig []byte) bool { +func (msg *KVStoreTx) VerifySignature(msgByte, sig []byte) bool { panic("implement me") } @@ -121,13 +121,14 @@ func decodeTx(txBytes []byte) (sdk.Tx, error) { var tx sdk.Tx split := bytes.Split(txBytes, []byte("=")) - if len(split) == 1 { //nolint:gocritic + switch len(split) { + case 1: k := split[0] tx = &KVStoreTx{k, k, txBytes, nil} - } else if len(split) == 2 { + case 2: k, v := split[0], split[1] tx = &KVStoreTx{k, v, txBytes, nil} - } else { + default: return nil, errorsmod.Wrap(sdkerrors.ErrTxDecode, "too many '='") } diff --git a/server/start.go b/server/start.go index 5469c1923cf0..d7301f76d6c5 100644 --- a/server/start.go +++ b/server/start.go @@ -8,6 +8,7 @@ import ( "runtime/pprof" pruningtypes "cosmossdk.io/store/pruning/types" + "github.com/armon/go-metrics" "github.com/cometbft/cometbft/abci/server" cmtcmd "github.com/cometbft/cometbft/cmd/cometbft/commands" "github.com/cometbft/cometbft/node" @@ -32,6 +33,7 @@ import ( "github.com/cosmos/cosmos-sdk/server/types" "github.com/cosmos/cosmos-sdk/telemetry" "github.com/cosmos/cosmos-sdk/types/mempool" + "github.com/cosmos/cosmos-sdk/version" genutiltypes "github.com/cosmos/cosmos-sdk/x/genutil/types" ) @@ -225,6 +227,8 @@ func startStandAlone(svrCtx *Context, appCreator types.AppCreator) error { return err } + emitServerInfoMetrics() + svr, err := server.NewServer(addr, transport, app) if err != nil { return fmt.Errorf("error creating listener: %v", err) @@ -244,7 +248,7 @@ func startStandAlone(svrCtx *Context, appCreator types.AppCreator) error { return err } - // Wait for the calling process to be cancelled or close the provided context, + // Wait for the calling process to be canceled or close the provided context, // so we can gracefully stop the ABCI server. <-ctx.Done() svrCtx.Logger.Info("stopping the ABCI server...") @@ -346,7 +350,7 @@ func startInProcess(svrCtx *Context, clientCtx client.Context, appCreator types. app.RegisterTxService(clientCtx) app.RegisterTendermintService(clientCtx) - app.RegisterNodeService(clientCtx) + app.RegisterNodeService(clientCtx, config) } metrics, err := startTelemetry(config) @@ -354,6 +358,8 @@ func startInProcess(svrCtx *Context, clientCtx client.Context, appCreator types. return err } + emitServerInfoMetrics() + var ( apiSrv *api.Server grpcSrv *grpc.Server @@ -505,3 +511,22 @@ func wrapCPUProfile(svrCtx *Context, callbackFn func() error) error { return <-errCh } + +// emitServerInfoMetrics emits server info related metrics using application telemetry. +func emitServerInfoMetrics() { + var ls []metrics.Label + + versionInfo := version.NewInfo() + if len(versionInfo.GoVersion) > 0 { + ls = append(ls, telemetry.NewLabel("go", versionInfo.GoVersion)) + } + if len(versionInfo.CosmosSdkVersion) > 0 { + ls = append(ls, telemetry.NewLabel("version", versionInfo.CosmosSdkVersion)) + } + + if len(ls) == 0 { + return + } + + telemetry.SetGaugeWithLabels([]string{"server", "info"}, 1, ls) +} diff --git a/server/types/app.go b/server/types/app.go index 7f47f063e9c7..3b51fe1920ee 100644 --- a/server/types/app.go +++ b/server/types/app.go @@ -50,7 +50,7 @@ type ( RegisterTendermintService(client.Context) // RegisterNodeService registers the node gRPC Query service. - RegisterNodeService(client.Context) + RegisterNodeService(client.Context, config.Config) // CommitMultiStore return the multistore instance CommitMultiStore() storetypes.CommitMultiStore @@ -73,7 +73,7 @@ type ( // Height is the app's latest block height. Height int64 // ConsensusParams are the exported consensus params for ABCI. - ConsensusParams *cmtproto.ConsensusParams + ConsensusParams cmtproto.ConsensusParams } // AppExporter is a function that dumps all app state to diff --git a/server/util.go b/server/util.go index c655b283c322..e74110105aa4 100644 --- a/server/util.go +++ b/server/util.go @@ -16,7 +16,6 @@ import ( cmtcmd "github.com/cometbft/cometbft/cmd/cometbft/commands" cmtcfg "github.com/cometbft/cometbft/config" - cmtcli "github.com/cometbft/cometbft/libs/cli" dbm "github.com/cosmos/cosmos-db" "github.com/rs/zerolog" "github.com/spf13/cast" @@ -169,37 +168,37 @@ func InterceptConfigsAndCreateContext(cmd *cobra.Command, customAppConfigTemplat // CreateSDKLogger creates a the default SDK logger. // It reads the log level and format from the server context. func CreateSDKLogger(ctx *Context, out io.Writer) (log.Logger, error) { - var logger log.Logger - if ctx.Viper.GetString(flags.FlagLogFormat) == cmtcfg.LogFormatJSON { - zl := zerolog.New(out).With().Timestamp().Logger() - logger = log.NewCustomLogger(zl) - } else { - logger = log.NewLogger(out) + var opts []log.Option + if ctx.Viper.GetString(flags.FlagLogFormat) == flags.OutputFormatJSON { + opts = append(opts, log.OutputJSONOption()) } - // set filter level or keys for the logger if any + // check and set filter level or keys for the logger if any logLvlStr := ctx.Viper.GetString(flags.FlagLogLevel) + if logLvlStr == "" { + return log.NewLogger(out, opts...), nil + } + logLvl, err := zerolog.ParseLevel(logLvlStr) - if err != nil { + switch { + case err != nil: // If the log level is not a valid zerolog level, then we try to parse it as a key filter. filterFunc, err := log.ParseLogLevel(logLvlStr) if err != nil { - return nil, fmt.Errorf("failed to parse log level (%s): %w", logLvlStr, err) + return nil, err } - logger = log.FilterKeys(logger, filterFunc) - } else { - zl := logger.Impl().(*zerolog.Logger) + opts = append(opts, log.FilterOption(filterFunc)) + + case ctx.Viper.GetBool("trace"): // cmtcli.TraceFlag // Check if the CometBFT flag for trace logging is set if it is then setup a tracing logger in this app as well. // Note it overrides log level passed in `log_levels`. - if ctx.Viper.GetBool(cmtcli.TraceFlag) { - logger = log.NewCustomLogger(zl.Level(zerolog.TraceLevel)) - } else { - logger = log.NewCustomLogger(zl.Level(logLvl)) - } + opts = append(opts, log.LevelOption(zerolog.TraceLevel)) + default: + opts = append(opts, log.LevelOption(logLvl)) } - return logger, nil + return log.NewLogger(out, opts...), nil } // GetServerContextFromCmd returns a Context from a command or an empty Context diff --git a/server/util_test.go b/server/util_test.go index ce5dfd521a80..0f60877508ff 100644 --- a/server/util_test.go +++ b/server/util_test.go @@ -294,7 +294,7 @@ func newPrecedenceCommon(t *testing.T) precedenceCommon { return retval } -func (v precedenceCommon) setAll(t *testing.T, setFlag *string, setEnvVar *string, setConfigFile *string) { +func (v precedenceCommon) setAll(t *testing.T, setFlag, setEnvVar, setConfigFile *string) { if setFlag != nil { if err := v.cmd.Flags().Set(v.flagName, *setFlag); err != nil { t.Fatalf("Failed setting flag %q", v.flagName) diff --git a/simapp/app.go b/simapp/app.go index 61ff5568319d..e11defc2d9cf 100644 --- a/simapp/app.go +++ b/simapp/app.go @@ -285,11 +285,11 @@ func NewSimApp( app.ParamsKeeper = initParamsKeeper(appCodec, legacyAmino, keys[paramstypes.StoreKey], tkeys[paramstypes.TStoreKey]) // set the BaseApp's parameter store - app.ConsensusParamsKeeper = consensusparamkeeper.NewKeeper(appCodec, runtime.NewKVStoreService(keys[consensusparamtypes.StoreKey]), authtypes.NewModuleAddress(govtypes.ModuleName).String()) - bApp.SetParamStore(&app.ConsensusParamsKeeper) + app.ConsensusParamsKeeper = consensusparamkeeper.NewKeeper(appCodec, runtime.NewKVStoreService(keys[consensusparamtypes.StoreKey]), authtypes.NewModuleAddress(govtypes.ModuleName).String(), runtime.EventService{}) + bApp.SetParamStore(app.ConsensusParamsKeeper.ParamsStore) // add keepers - app.AccountKeeper = authkeeper.NewAccountKeeper(appCodec, keys[authtypes.StoreKey], authtypes.ProtoBaseAccount, maccPerms, sdk.Bech32MainPrefix, authtypes.NewModuleAddress(govtypes.ModuleName).String()) + app.AccountKeeper = authkeeper.NewAccountKeeper(appCodec, runtime.NewKVStoreService(keys[authtypes.StoreKey]), authtypes.ProtoBaseAccount, maccPerms, sdk.Bech32MainPrefix, authtypes.NewModuleAddress(govtypes.ModuleName).String()) app.BankKeeper = bankkeeper.NewBaseKeeper( appCodec, @@ -311,9 +311,9 @@ func NewSimApp( invCheckPeriod := cast.ToUint(appOpts.Get(server.FlagInvCheckPeriod)) app.CrisisKeeper = crisiskeeper.NewKeeper(appCodec, keys[crisistypes.StoreKey], invCheckPeriod, - app.BankKeeper, authtypes.FeeCollectorName, authtypes.NewModuleAddress(govtypes.ModuleName).String()) + app.BankKeeper, authtypes.FeeCollectorName, authtypes.NewModuleAddress(govtypes.ModuleName).String(), app.AccountKeeper.GetAddressCodec()) - app.FeeGrantKeeper = feegrantkeeper.NewKeeper(appCodec, keys[feegrant.StoreKey], app.AccountKeeper) + app.FeeGrantKeeper = feegrantkeeper.NewKeeper(appCodec, runtime.NewKVStoreService(keys[feegrant.StoreKey]), app.AccountKeeper) // register the staking hooks // NOTE: stakingKeeper above is passed by reference, so that it will contain these hooks @@ -366,11 +366,11 @@ func NewSimApp( ), ) - app.NFTKeeper = nftkeeper.NewKeeper(keys[nftkeeper.StoreKey], appCodec, app.AccountKeeper, app.BankKeeper) + app.NFTKeeper = nftkeeper.NewKeeper(runtime.NewKVStoreService(keys[nftkeeper.StoreKey]), appCodec, app.AccountKeeper, app.BankKeeper) // create evidence keeper with router evidenceKeeper := evidencekeeper.NewKeeper( - appCodec, keys[evidencetypes.StoreKey], app.StakingKeeper, app.SlashingKeeper, + appCodec, keys[evidencetypes.StoreKey], app.StakingKeeper, app.SlashingKeeper, app.AccountKeeper.GetAddressCodec(), ) // If evidence needs to be handled for the app, set routes in router here and seal app.EvidenceKeeper = *evidenceKeeper @@ -395,10 +395,10 @@ func NewSimApp( feegrantmodule.NewAppModule(appCodec, app.AccountKeeper, app.BankKeeper, app.FeeGrantKeeper, app.interfaceRegistry), gov.NewAppModule(appCodec, &app.GovKeeper, app.AccountKeeper, app.BankKeeper, app.GetSubspace(govtypes.ModuleName)), mint.NewAppModule(appCodec, app.MintKeeper, app.AccountKeeper, nil, app.GetSubspace(minttypes.ModuleName)), - slashing.NewAppModule(appCodec, app.SlashingKeeper, app.AccountKeeper, app.BankKeeper, app.StakingKeeper, app.GetSubspace(slashingtypes.ModuleName)), + slashing.NewAppModule(appCodec, app.SlashingKeeper, app.AccountKeeper, app.BankKeeper, app.StakingKeeper, app.GetSubspace(slashingtypes.ModuleName), app.interfaceRegistry), distr.NewAppModule(appCodec, app.DistrKeeper, app.AccountKeeper, app.BankKeeper, app.StakingKeeper, app.GetSubspace(distrtypes.ModuleName)), staking.NewAppModule(appCodec, app.StakingKeeper, app.AccountKeeper, app.BankKeeper, app.GetSubspace(stakingtypes.ModuleName)), - upgrade.NewAppModule(app.UpgradeKeeper), + upgrade.NewAppModule(app.UpgradeKeeper, app.AccountKeeper.GetAddressCodec()), evidence.NewAppModule(app.EvidenceKeeper), params.NewAppModule(app.ParamsKeeper), authzmodule.NewAppModule(appCodec, app.AuthzKeeper, app.AccountKeeper, app.BankKeeper, app.interfaceRegistry), @@ -709,8 +709,8 @@ func (app *SimApp) RegisterTendermintService(clientCtx client.Context) { ) } -func (app *SimApp) RegisterNodeService(clientCtx client.Context) { - nodeservice.RegisterNodeService(clientCtx, app.GRPCQueryRouter()) +func (app *SimApp) RegisterNodeService(clientCtx client.Context, cfg config.Config) { + nodeservice.RegisterNodeService(clientCtx, app.GRPCQueryRouter(), cfg) } // GetMaccPerms returns a copy of the module account permissions diff --git a/simapp/app_v2.go b/simapp/app_v2.go index 01aaaeab7313..89d77b2205ba 100644 --- a/simapp/app_v2.go +++ b/simapp/app_v2.go @@ -3,7 +3,6 @@ package simapp import ( - _ "embed" "io" "os" "path/filepath" diff --git a/simapp/export.go b/simapp/export.go index eb2e94823149..42fc8fce1a8b 100644 --- a/simapp/export.go +++ b/simapp/export.go @@ -17,7 +17,7 @@ import ( // ExportAppStateAndValidators exports the state of the application for a genesis // file. -func (app *SimApp) ExportAppStateAndValidators(forZeroHeight bool, jailAllowedAddrs []string, modulesToExport []string) (servertypes.ExportedApp, error) { +func (app *SimApp) ExportAppStateAndValidators(forZeroHeight bool, jailAllowedAddrs, modulesToExport []string) (servertypes.ExportedApp, error) { // as if they could withdraw from the start of the next block ctx := app.NewContext(true, cmtproto.Header{Height: app.LastBlockHeight()}) @@ -51,7 +51,7 @@ func (app *SimApp) ExportAppStateAndValidators(forZeroHeight bool, jailAllowedAd // prepare for fresh start at zero height // NOTE zero height genesis is a temporary feature which will be deprecated // -// in favour of export at a block height +// in favor of export at a block height func (app *SimApp) prepForZeroHeightGenesis(ctx sdk.Context, jailAllowedAddrs []string) { applyAllowedAddrs := false diff --git a/simapp/go.mod b/simapp/go.mod index 4236763ed2a9..3a3efaf31165 100644 --- a/simapp/go.mod +++ b/simapp/go.mod @@ -3,27 +3,27 @@ module cosmossdk.io/simapp go 1.20 require ( - cosmossdk.io/api v0.3.2-0.20230313131911-55bf5d4efbe7 + cosmossdk.io/api v0.4.0 cosmossdk.io/client/v2 v2.0.0-20230309163709-87da587416ba cosmossdk.io/core v0.6.1 cosmossdk.io/depinject v1.0.0-alpha.3 - cosmossdk.io/log v0.1.0 + cosmossdk.io/log v1.0.0 cosmossdk.io/math v1.0.0 - cosmossdk.io/store v0.1.0-alpha.1 + cosmossdk.io/store v0.1.0-alpha.1.0.20230328185921-37ba88872dbc cosmossdk.io/tools/confix v0.0.0-20230120150717-4f6f6c00021f cosmossdk.io/tools/rosetta v0.2.0 cosmossdk.io/x/evidence v0.1.0 cosmossdk.io/x/feegrant v0.0.0-20230117113717-50e7c4a4ceff cosmossdk.io/x/nft v0.0.0-20230113085233-fae3332d62fc cosmossdk.io/x/upgrade v0.0.0-20230127052425-54c8e1568335 - github.com/cometbft/cometbft v0.37.0 + github.com/cometbft/cometbft v0.37.1-0.20230411132551-3a91d155e664 github.com/cosmos/cosmos-db v1.0.0-rc.1 // this version is not used as it is always replaced by the latest Cosmos SDK version github.com/cosmos/cosmos-sdk v0.48.0 - github.com/cosmos/gogoproto v1.4.6 + github.com/cosmos/gogoproto v1.4.8 github.com/golang/mock v1.6.0 github.com/spf13/cast v1.5.0 - github.com/spf13/cobra v1.6.1 + github.com/spf13/cobra v1.7.0 github.com/spf13/pflag v1.0.5 github.com/spf13/viper v1.15.0 github.com/stretchr/testify v1.8.2 @@ -32,13 +32,13 @@ require ( require ( cloud.google.com/go v0.110.0 // indirect - cloud.google.com/go/compute v1.18.0 // indirect + cloud.google.com/go/compute v1.19.0 // indirect cloud.google.com/go/compute/metadata v0.2.3 // indirect cloud.google.com/go/iam v0.13.0 // indirect cloud.google.com/go/storage v1.30.0 // indirect - cosmossdk.io/collections v0.0.0-20230309163709-87da587416ba // indirect + cosmossdk.io/collections v0.1.0 // indirect cosmossdk.io/errors v1.0.0-beta.7 // indirect - cosmossdk.io/x/tx v0.3.1-0.20230321155358-6522dd1731b5 // indirect + cosmossdk.io/x/tx v0.5.5 // indirect filippo.io/edwards25519 v1.0.0 // indirect github.com/99designs/go-keychain v0.0.0-20191008050251-8e49817e8af4 // indirect github.com/99designs/keyring v1.2.1 // indirect @@ -49,6 +49,7 @@ require ( github.com/beorn7/perks v1.0.1 // indirect github.com/bgentry/go-netrc v0.0.0-20140422174119-9fd32a8b3d3d // indirect github.com/bgentry/speakeasy v0.1.1-0.20220910012023-760eaf8b6816 // indirect + github.com/bits-and-blooms/bitset v1.6.0 // indirect github.com/btcsuite/btcd/btcec/v2 v2.3.2 // indirect github.com/cenkalti/backoff/v4 v4.1.3 // indirect github.com/cespare/xxhash v1.1.0 // indirect @@ -57,7 +58,7 @@ require ( github.com/cockroachdb/apd/v2 v2.0.2 // indirect github.com/cockroachdb/errors v1.9.1 // indirect github.com/cockroachdb/logtags v0.0.0-20230118201751-21c54148d20b // indirect - github.com/cockroachdb/pebble v0.0.0-20230315223031-1e5ddd10389e // indirect + github.com/cockroachdb/pebble v0.0.0-20230412222916-60cfeb46143b // indirect github.com/cockroachdb/redact v1.1.3 // indirect github.com/coinbase/rosetta-sdk-go/types v1.0.0 // indirect github.com/cometbft/cometbft-db v0.7.0 // indirect @@ -69,12 +70,12 @@ require ( github.com/cosmos/iavl v0.21.0-beta.1 // indirect github.com/cosmos/ledger-cosmos-go v0.13.0 // indirect github.com/cosmos/rosetta-sdk-go v0.10.0 // indirect - github.com/creachadair/atomicfile v0.2.8 // indirect + github.com/creachadair/atomicfile v0.3.0 // indirect github.com/creachadair/taskgroup v0.4.2 // indirect github.com/creachadair/tomledit v0.0.24 // indirect github.com/danieljoos/wincred v1.1.2 // indirect github.com/davecgh/go-spew v1.1.1 // indirect - github.com/decred/dcrd/dcrec/secp256k1/v4 v4.1.0 // indirect + github.com/decred/dcrd/dcrec/secp256k1/v4 v4.2.0 // indirect github.com/desertbit/timer v0.0.0-20180107155436-c41aec40b27f // indirect github.com/dgraph-io/badger/v2 v2.2007.4 // indirect github.com/dgraph-io/ristretto v0.1.1 // indirect @@ -84,7 +85,7 @@ require ( github.com/fatih/color v1.15.0 // indirect github.com/felixge/httpsnoop v1.0.2 // indirect github.com/fsnotify/fsnotify v1.6.0 // indirect - github.com/getsentry/sentry-go v0.19.0 // indirect + github.com/getsentry/sentry-go v0.20.0 // indirect github.com/go-kit/kit v0.12.0 // indirect github.com/go-kit/log v0.2.1 // indirect github.com/go-logfmt/logfmt v0.6.0 // indirect @@ -121,16 +122,17 @@ require ( github.com/hashicorp/yamux v0.1.1 // indirect github.com/hdevalence/ed25519consensus v0.1.0 // indirect github.com/huandu/skiplist v1.2.0 // indirect + github.com/iancoleman/strcase v0.2.0 // indirect github.com/improbable-eng/grpc-web v0.15.0 // indirect github.com/inconshreveable/mousetrap v1.1.0 // indirect github.com/jmespath/go-jmespath v0.4.0 // indirect github.com/jmhodges/levigo v1.0.0 // indirect - github.com/klauspost/compress v1.16.3 // indirect + github.com/klauspost/compress v1.16.5 // indirect github.com/kr/pretty v0.3.1 // indirect github.com/kr/text v0.2.0 // indirect github.com/lib/pq v1.10.7 // indirect github.com/libp2p/go-buffer-pool v0.1.0 // indirect - github.com/linxGnu/grocksdb v1.7.15 // indirect + github.com/linxGnu/grocksdb v1.7.16 // indirect github.com/magiconair/properties v1.8.7 // indirect github.com/manifoldco/promptui v0.9.0 // indirect github.com/mattn/go-colorable v0.1.13 // indirect @@ -147,14 +149,14 @@ require ( github.com/petermattis/goid v0.0.0-20230317030725-371a4b8eda08 // indirect github.com/pkg/errors v0.9.1 // indirect github.com/pmezard/go-difflib v1.0.0 // indirect - github.com/prometheus/client_golang v1.14.0 // indirect + github.com/prometheus/client_golang v1.15.0 // indirect github.com/prometheus/client_model v0.3.0 // indirect github.com/prometheus/common v0.42.0 // indirect github.com/prometheus/procfs v0.9.0 // indirect github.com/rcrowley/go-metrics v0.0.0-20201227073835-cf1acfcdf475 // indirect - github.com/rogpeppe/go-internal v1.9.0 // indirect + github.com/rogpeppe/go-internal v1.10.0 // indirect github.com/rs/cors v1.8.3 // indirect - github.com/rs/zerolog v1.29.0 // indirect + github.com/rs/zerolog v1.29.1 // indirect github.com/sasha-s/go-deadlock v0.3.1 // indirect github.com/spf13/afero v1.9.3 // indirect github.com/spf13/jwalterweatherman v1.1.0 // indirect @@ -168,18 +170,18 @@ require ( github.com/zondax/ledger-go v0.14.1 // indirect go.etcd.io/bbolt v1.3.6 // indirect go.opencensus.io v0.24.0 // indirect - golang.org/x/crypto v0.7.0 // indirect + golang.org/x/crypto v0.8.0 // indirect golang.org/x/exp v0.0.0-20230321023759-10a507213a29 // indirect - golang.org/x/net v0.8.0 // indirect + golang.org/x/net v0.9.0 // indirect golang.org/x/oauth2 v0.6.0 // indirect golang.org/x/sync v0.1.0 // indirect - golang.org/x/sys v0.6.0 // indirect - golang.org/x/term v0.6.0 // indirect - golang.org/x/text v0.8.0 // indirect + golang.org/x/sys v0.7.0 // indirect + golang.org/x/term v0.7.0 // indirect + golang.org/x/text v0.9.0 // indirect golang.org/x/xerrors v0.0.0-20220907171357-04be3eba64a2 // indirect google.golang.org/api v0.114.0 // indirect google.golang.org/appengine v1.6.7 // indirect - google.golang.org/genproto v0.0.0-20230320184635-7606e756e683 // indirect + google.golang.org/genproto v0.0.0-20230410155749-daa745c078e1 // indirect google.golang.org/grpc v1.54.0 // indirect gopkg.in/ini.v1 v1.67.0 // indirect gopkg.in/yaml.v2 v2.4.0 // indirect @@ -195,6 +197,7 @@ require ( replace ( // TODO tag all extracted modules after SDK refactor cosmossdk.io/api => ../api + cosmossdk.io/store => ../store cosmossdk.io/tools/confix => ../tools/confix cosmossdk.io/tools/rosetta => ../tools/rosetta cosmossdk.io/x/evidence => ../x/evidence diff --git a/simapp/go.sum b/simapp/go.sum index 8fb99f71129e..93e2139c21c4 100644 --- a/simapp/go.sum +++ b/simapp/go.sum @@ -70,8 +70,8 @@ cloud.google.com/go/compute v1.6.0/go.mod h1:T29tfhtVbq1wvAPo0E3+7vhgmkOYeXjhFvz cloud.google.com/go/compute v1.6.1/go.mod h1:g85FgpzFvNULZ+S8AYq87axRKuf2Kh7deLqV/jJ3thU= cloud.google.com/go/compute v1.7.0/go.mod h1:435lt8av5oL9P3fv1OEzSbSUe+ybHXGMPQHHZWZxy9U= cloud.google.com/go/compute v1.10.0/go.mod h1:ER5CLbMxl90o2jtNbGSbtfOpQKR0t15FOtRsugnLrlU= -cloud.google.com/go/compute v1.18.0 h1:FEigFqoDbys2cvFkZ9Fjq4gnHBP55anJ0yQyau2f9oY= -cloud.google.com/go/compute v1.18.0/go.mod h1:1X7yHxec2Ga+Ss6jPyjxRxpu2uu7PLgsOVXvgU0yacs= +cloud.google.com/go/compute v1.19.0 h1:+9zda3WGgW1ZSTlVppLCYFIr48Pa35q1uG2N1itbCEQ= +cloud.google.com/go/compute v1.19.0/go.mod h1:rikpw2y+UMidAe9tISo04EHNOIf42RLYF/q8Bs93scU= cloud.google.com/go/compute/metadata v0.2.3 h1:mg4jlk7mCAj6xXp9UJ4fjI9VUI5rubuGBW5aJ7UnBMY= cloud.google.com/go/compute/metadata v0.2.3/go.mod h1:VAV5nSsACxMJvgaAuX6Pk2AawlZn8kiOGuCv6gTkwuA= cloud.google.com/go/containeranalysis v0.5.1/go.mod h1:1D92jd8gRR/c0fGMlymRgxWD3Qw9C1ff6/T7mLgVL8I= @@ -190,22 +190,20 @@ cloud.google.com/go/workflows v1.6.0/go.mod h1:6t9F5h/unJz41YqfBmqSASJSXccBLtD1V cloud.google.com/go/workflows v1.7.0/go.mod h1:JhSrZuVZWuiDfKEFxU0/F1PQjmpnpcoISEXH2bcHC3M= cosmossdk.io/client/v2 v2.0.0-20230309163709-87da587416ba h1:LuPHCncU2KLMNPItFECs709uo46I9wSu2fAWYVCx+/U= cosmossdk.io/client/v2 v2.0.0-20230309163709-87da587416ba/go.mod h1:SXdwqO7cN5htalh/lhXWP8V4zKtBrhhcSTU+ytuEtmM= -cosmossdk.io/collections v0.0.0-20230309163709-87da587416ba h1:S4PYij/tX3Op/hwenVEN9D+M27JRcwSwVqE3UA0BnwM= -cosmossdk.io/collections v0.0.0-20230309163709-87da587416ba/go.mod h1:lpS+G8bGC2anqzWdndTzjnQnuMO/qAcgZUkGJp4i3rc= +cosmossdk.io/collections v0.1.0 h1:nzJGeiq32KnZroSrhB6rPifw4I85Cgmzw/YAmr4luv8= +cosmossdk.io/collections v0.1.0/go.mod h1:xbauc0YsbUF8qKMVeBZl0pFCunxBIhKN/WlxpZ3lBuo= cosmossdk.io/core v0.6.1 h1:OBy7TI2W+/gyn2z40vVvruK3di+cAluinA6cybFbE7s= cosmossdk.io/core v0.6.1/go.mod h1:g3MMBCBXtxbDWBURDVnJE7XML4BG5qENhs0gzkcpuFA= cosmossdk.io/depinject v1.0.0-alpha.3 h1:6evFIgj//Y3w09bqOUOzEpFj5tsxBqdc5CfkO7z+zfw= cosmossdk.io/depinject v1.0.0-alpha.3/go.mod h1:eRbcdQ7MRpIPEM5YUJh8k97nxHpYbc3sMUnEtt8HPWU= cosmossdk.io/errors v1.0.0-beta.7 h1:gypHW76pTQGVnHKo6QBkb4yFOJjC+sUGRc5Al3Odj1w= cosmossdk.io/errors v1.0.0-beta.7/go.mod h1:mz6FQMJRku4bY7aqS/Gwfcmr/ue91roMEKAmDUDpBfE= -cosmossdk.io/log v0.1.0 h1:Vnexi+KzUCjmqq/m93teAxjt5biWFfZ5PI1imx2IJw8= -cosmossdk.io/log v0.1.0/go.mod h1:p95Wq6mDY3SREMc4y7+QU9Uwy3nyvfpWGD1iSaFkVFs= +cosmossdk.io/log v1.0.0 h1:NGKZ/A5rd4PduDfoscgABklX557PWjQINbosZy/m3Jk= +cosmossdk.io/log v1.0.0/go.mod h1:CwX9BLiBruZb7lzLlRr3R231d/fVPUXk8gAdV4LQap0= cosmossdk.io/math v1.0.0 h1:ro9w7eKx23om2tZz/VM2Pf+z2WAbGX1yDQQOJ6iGeJw= cosmossdk.io/math v1.0.0/go.mod h1:Ygz4wBHrgc7g0N+8+MrnTfS9LLn9aaTGa9hKopuym5k= -cosmossdk.io/store v0.1.0-alpha.1 h1:NGomhLUXzAxvK4OF8+yP6eNUG5i4LwzOzx+S494pTCg= -cosmossdk.io/store v0.1.0-alpha.1/go.mod h1:kmCMbhrleCZ6rDZPY/EGNldNvPebFNyVPFYp+pv05/k= -cosmossdk.io/x/tx v0.3.1-0.20230321155358-6522dd1731b5 h1:AlvyRc7f7Py1mv254vrqjIIuykCnitHIz2T+nup3bU0= -cosmossdk.io/x/tx v0.3.1-0.20230321155358-6522dd1731b5/go.mod h1:FNkSEMbLP9NFdTfrbslNUtNS7OXf3wgZeJyXzfRPa4c= +cosmossdk.io/x/tx v0.5.5 h1:9XG3KOrqObt7Rw7KhT7fiqRd6EepUfmA9ERa8CHj1WM= +cosmossdk.io/x/tx v0.5.5/go.mod h1:Oh3Kh+IPOfMEILNxVd2e8SLqRrIjYHpdGBfDg4ghU/k= dmitri.shuralyov.com/gpu/mtl v0.0.0-20190408044501-666a987793e9/go.mod h1:H6x//7gZCb22OMCxBHrMx7a5I7Hp++hsVxbQ4BYO7hU= filippo.io/edwards25519 v1.0.0 h1:0wAIcmJUqRdI8IJ/3eGi5/HwXZWPujYXXlkrQogz0Ek= filippo.io/edwards25519 v1.0.0/go.mod h1:N1IkdkCkiLB6tki+MYJoSx2JTY9NUlxZE7eHn5EwJns= @@ -269,6 +267,8 @@ github.com/bgentry/go-netrc v0.0.0-20140422174119-9fd32a8b3d3d/go.mod h1:6QX/PXZ github.com/bgentry/speakeasy v0.1.0/go.mod h1:+zsyZBPWlz7T6j88CTgSN5bM796AkVf0kBD4zp0CCIs= github.com/bgentry/speakeasy v0.1.1-0.20220910012023-760eaf8b6816 h1:41iFGWnSlI2gVpmOtVTJZNodLdLQLn/KsJqFvXwnd/s= github.com/bgentry/speakeasy v0.1.1-0.20220910012023-760eaf8b6816/go.mod h1:+zsyZBPWlz7T6j88CTgSN5bM796AkVf0kBD4zp0CCIs= +github.com/bits-and-blooms/bitset v1.6.0 h1:FVfaUsleKAUTJnaN9Fd1YFFi1S8vAX5xeXnXHFYOojM= +github.com/bits-and-blooms/bitset v1.6.0/go.mod h1:gIdJ4wp64HaoK2YrL1Q5/N7Y16edYb8uY+O0FJTyyDA= github.com/btcsuite/btcd/btcec/v2 v2.3.2 h1:5n0X6hX0Zk+6omWcihdYvdAlGf2DfasC0GMf7DClJ3U= github.com/btcsuite/btcd/btcec/v2 v2.3.2/go.mod h1:zYzJ8etWJQIv1Ogk7OzpWjowwOdXY1W/17j2MW85J04= github.com/btcsuite/btcd/btcutil v1.1.2 h1:XLMbX8JQEiwMcYft2EGi8zPUkoa0abKIU6/BJSRsjzQ= @@ -320,16 +320,16 @@ github.com/cockroachdb/errors v1.9.1/go.mod h1:2sxOtL2WIc096WSZqZ5h8fa17rdDq9HZO github.com/cockroachdb/logtags v0.0.0-20211118104740-dabe8e521a4f/go.mod h1:Vz9DsVWQQhf3vs21MhPMZpMGSht7O/2vFW2xusFUVOs= github.com/cockroachdb/logtags v0.0.0-20230118201751-21c54148d20b h1:r6VH0faHjZeQy818SGhaone5OnYfxFR/+AzdY3sf5aE= github.com/cockroachdb/logtags v0.0.0-20230118201751-21c54148d20b/go.mod h1:Vz9DsVWQQhf3vs21MhPMZpMGSht7O/2vFW2xusFUVOs= -github.com/cockroachdb/pebble v0.0.0-20230315223031-1e5ddd10389e h1:CDuLmyaZ1pD4OJHHtubKqgu/Byw5zAnm+gArJsyj96Q= -github.com/cockroachdb/pebble v0.0.0-20230315223031-1e5ddd10389e/go.mod h1:9lRMC4XN3/BLPtIp6kAKwIaHu369NOf2rMucPzipz50= +github.com/cockroachdb/pebble v0.0.0-20230412222916-60cfeb46143b h1:92ve6F1Pls/eqd+V+102lOMRJatgpqqsQvbT9Bl/fjg= +github.com/cockroachdb/pebble v0.0.0-20230412222916-60cfeb46143b/go.mod h1:9lRMC4XN3/BLPtIp6kAKwIaHu369NOf2rMucPzipz50= github.com/cockroachdb/redact v1.1.3 h1:AKZds10rFSIj7qADf0g46UixK8NNLwWTNdCIGS5wfSQ= github.com/cockroachdb/redact v1.1.3/go.mod h1:BVNblN9mBWFyMyqK1k3AAiSxhvhfK2oOZZ2lK+dpvRg= github.com/codahale/hdrhistogram v0.0.0-20161010025455-3a0bb77429bd/go.mod h1:sE/e/2PUdi/liOCUjSTXgM1o87ZssimdTWN964YiIeI= github.com/codegangsta/inject v0.0.0-20150114235600-33e0aa1cb7c0/go.mod h1:4Zcjuz89kmFXt9morQgcfYZAYZ5n8WHjt81YYWIwtTM= github.com/coinbase/rosetta-sdk-go/types v1.0.0 h1:jpVIwLcPoOeCR6o1tU+Xv7r5bMONNbHU7MuEHboiFuA= github.com/coinbase/rosetta-sdk-go/types v1.0.0/go.mod h1:eq7W2TMRH22GTW0N0beDnN931DW0/WOI1R2sdHNHG4c= -github.com/cometbft/cometbft v0.37.0 h1:M005vBaSaugvYYmNZwJOopynQSjwLoDTwflnQ/I/eYk= -github.com/cometbft/cometbft v0.37.0/go.mod h1:Y2MMMN//O5K4YKd8ze4r9jmk4Y7h0ajqILXbH5JQFVs= +github.com/cometbft/cometbft v0.37.1-0.20230411132551-3a91d155e664 h1:BbCkbnaU3R603XpnbqvuDU8Kfv+hjhiFILOHhVFntsw= +github.com/cometbft/cometbft v0.37.1-0.20230411132551-3a91d155e664/go.mod h1:Y2MMMN//O5K4YKd8ze4r9jmk4Y7h0ajqILXbH5JQFVs= github.com/cometbft/cometbft-db v0.7.0 h1:uBjbrBx4QzU0zOEnU8KxoDl18dMNgDh+zZRUE0ucsbo= github.com/cometbft/cometbft-db v0.7.0/go.mod h1:yiKJIm2WKrt6x8Cyxtq9YTEcIMPcEe4XPxhgX59Fzf0= github.com/confio/ics23/go v0.9.0 h1:cWs+wdbS2KRPZezoaaj+qBleXgUk5WOQFMP3CQFGTr4= @@ -339,7 +339,7 @@ github.com/coreos/etcd v3.3.10+incompatible/go.mod h1:uF7uidLiAD3TWHmW31ZFd/JWoc github.com/coreos/go-etcd v2.0.0+incompatible/go.mod h1:Jez6KQU2B/sWsbdaef3ED8NzMklzPG4d5KIOhIy30Tk= github.com/coreos/go-semver v0.2.0/go.mod h1:nnelYz7RCh+5ahJtPPxZlU+153eP4D4r3EedlOD2RNk= github.com/coreos/go-systemd v0.0.0-20180511133405-39ca1b05acc7/go.mod h1:F5haX7vjVVG0kc13fIWeqUViNPyEJxv/OmvnBo0Yme4= -github.com/coreos/go-systemd/v22 v22.3.3-0.20220203105225-a9a7ef127534/go.mod h1:Y58oyj3AT4RCenI/lSvhwexgC+NSVTIJ3seZv2GcEnc= +github.com/coreos/go-systemd/v22 v22.5.0/go.mod h1:Y58oyj3AT4RCenI/lSvhwexgC+NSVTIJ3seZv2GcEnc= github.com/coreos/pkg v0.0.0-20160727233714-3ac0863d7acf/go.mod h1:E3G3o1h8I7cfcXa63jLwjI0eiQQMgzzUDFVpN/nH/eA= github.com/cosmos/btcutil v1.0.5 h1:t+ZFcX77LpKtDBhjucvnOH8C2l2ioGsBNEQ3jef8xFk= github.com/cosmos/btcutil v1.0.5/go.mod h1:IyB7iuqZMJlthe2tkIFL33xPyzbFYP0XVdS8P5lUPis= @@ -353,8 +353,8 @@ github.com/cosmos/go-bip39 v1.0.0/go.mod h1:RNJv0H/pOIVgxw6KS7QeX2a0Uo0aKUlfhZ4x github.com/cosmos/gogogateway v1.2.0 h1:Ae/OivNhp8DqBi/sh2A8a1D0y638GpL3tkmLQAiKxTE= github.com/cosmos/gogogateway v1.2.0/go.mod h1:iQpLkGWxYcnCdz5iAdLcRBSw3h7NXeOkZ4GUkT+tbFI= github.com/cosmos/gogoproto v1.4.2/go.mod h1:cLxOsn1ljAHSV527CHOtaIP91kK6cCrZETRBrkzItWU= -github.com/cosmos/gogoproto v1.4.6 h1:Ee7z15dWJaGlgM2rWrK8N2IX7PQcuccu8oG68jp5RL4= -github.com/cosmos/gogoproto v1.4.6/go.mod h1:VS/ASYmPgv6zkPKLjR9EB91lwbLHOzaGCirmKKhncfI= +github.com/cosmos/gogoproto v1.4.8 h1:BrHKc6WFZt8+jRV71vKSQE+JrfF+JAnzrKo2VP7wIZ4= +github.com/cosmos/gogoproto v1.4.8/go.mod h1:hnb0DIEWTv+wdNzNcqus5xCQXq5+CXauq1FJuurRfVY= github.com/cosmos/iavl v0.21.0-beta.1 h1:fBQeBc8HLZ14plJNcmGfaOXSSMLVEHvEQXiTXSD76m0= github.com/cosmos/iavl v0.21.0-beta.1/go.mod h1:25YJYzilTErJ2mKfNB3xyWL9IsCwEQdNzdIutg2mh3U= github.com/cosmos/keyring v1.2.0 h1:8C1lBP9xhImmIabyXW4c3vFjjLiBdGCmfLUfeZlV1Yo= @@ -366,8 +366,8 @@ github.com/cosmos/rosetta-sdk-go v0.10.0/go.mod h1:SImAZkb96YbwvoRkzSMQB6noNJXFg github.com/cpuguy83/go-md2man v1.0.10/go.mod h1:SmD6nW6nTyfqj6ABTjUi3V3JVMnlJmwcJI5acqYI6dE= github.com/cpuguy83/go-md2man/v2 v2.0.0-20190314233015-f79a8a8ca69d/go.mod h1:maD7wRr/U5Z6m/iR4s+kqSMx2CaBsrgA7czyZG/E6dU= github.com/cpuguy83/go-md2man/v2 v2.0.2/go.mod h1:tgQtvFlXSQOSOSIRvRPT7W67SCa46tRHOmNcaadrF8o= -github.com/creachadair/atomicfile v0.2.8 h1:koFZzO/Byf4wRJIf1cvLmlXI7QPnR+pLushHhtTdXB8= -github.com/creachadair/atomicfile v0.2.8/go.mod h1:Tb31RroXn8ESlNsY/FzDFoKSL1mzdHemTDNL9V1Ml4M= +github.com/creachadair/atomicfile v0.3.0 h1:4HvescJCWkiLOqHkhtCeNAY4+8DVyYkQgwBDyAAvDWI= +github.com/creachadair/atomicfile v0.3.0/go.mod h1:mwfrkRxFKwpNAflYZzytbSwxvbK6fdGRRlp0KEQc0qU= github.com/creachadair/taskgroup v0.4.2 h1:jsBLdAJE42asreGss2xZGZ8fJra7WtwnHWeJFxv2Li8= github.com/creachadair/taskgroup v0.4.2/go.mod h1:qiXUOSrbwAY3u0JPGTzObbE3yf9hcXHDKBZ2ZjpCbgM= github.com/creachadair/tomledit v0.0.24 h1:5Xjr25R2esu1rKCbQEmjZYlrhFkDspoAbAKb6QKQDhQ= @@ -381,9 +381,9 @@ github.com/danieljoos/wincred v1.1.2/go.mod h1:GijpziifJoIBfYh+S7BbkdUTU4LfM+QnG github.com/davecgh/go-spew v1.1.0/go.mod h1:J7Y8YcW2NihsgmVo/mv3lAwl/skON4iLHjSsI+c5H38= github.com/davecgh/go-spew v1.1.1 h1:vj9j/u1bqnvCEfJOwUhtlOARqs3+rkHYY13jYWTU97c= github.com/davecgh/go-spew v1.1.1/go.mod h1:J7Y8YcW2NihsgmVo/mv3lAwl/skON4iLHjSsI+c5H38= -github.com/decred/dcrd/crypto/blake256 v1.0.0 h1:/8DMNYp9SGi5f0w7uCm6d6M4OU2rGFK09Y2A4Xv7EE0= -github.com/decred/dcrd/dcrec/secp256k1/v4 v4.1.0 h1:HbphB4TFFXpv7MNrT52FGrrgVXF1owhMVTHFZIlnvd4= -github.com/decred/dcrd/dcrec/secp256k1/v4 v4.1.0/go.mod h1:DZGJHZMqrU4JJqFAWUS2UO1+lbSKsdiOoYi9Zzey7Fc= +github.com/decred/dcrd/crypto/blake256 v1.0.1 h1:7PltbUIQB7u/FfZ39+DGa/ShuMyJ5ilcvdfma9wOH6Y= +github.com/decred/dcrd/dcrec/secp256k1/v4 v4.2.0 h1:8UrgZ3GkP4i/CLijOJx79Yu+etlyjdBU4sfcs2WYQMs= +github.com/decred/dcrd/dcrec/secp256k1/v4 v4.2.0/go.mod h1:v57UDF4pDQJcEfFUCRop3lJL149eHGSe9Jvczhzjo/0= github.com/desertbit/timer v0.0.0-20180107155436-c41aec40b27f h1:U5y3Y5UE0w7amNe7Z5G/twsBW0KEalRQXZzf8ufSh9I= github.com/desertbit/timer v0.0.0-20180107155436-c41aec40b27f/go.mod h1:xH/i4TFMt8koVQZ6WFms69WAsDWr2XsYL3Hkl7jkoLE= github.com/dgraph-io/badger v1.6.0/go.mod h1:zwt7syl517jmP8s94KqSxTlM6IMsdhYy6psNgSztDR4= @@ -443,8 +443,8 @@ github.com/fsnotify/fsnotify v1.6.0 h1:n+5WquG0fcWoWp6xPWfHdbskMCQaFnG6PfBrh1Ky4 github.com/fsnotify/fsnotify v1.6.0/go.mod h1:sl3t1tCWJFWoRz9R8WJCbQihKKwmorjAbSClcnxKAGw= github.com/gavv/httpexpect v2.0.0+incompatible/go.mod h1:x+9tiU1YnrOvnB725RkpoLv1M62hOWzwo5OXotisrKc= github.com/getsentry/sentry-go v0.12.0/go.mod h1:NSap0JBYWzHND8oMbyi0+XZhUalc1TBdRL1M71JZW2c= -github.com/getsentry/sentry-go v0.19.0 h1:BcCH3CN5tXt5aML+gwmbFwVptLLQA+eT866fCO9wVOM= -github.com/getsentry/sentry-go v0.19.0/go.mod h1:y3+lGEFEFexZtpbG1GUE2WD/f9zGyKYwpEqryTOC/nE= +github.com/getsentry/sentry-go v0.20.0 h1:bwXW98iMRIWxn+4FgPW7vMrjmbym6HblXALmhjHmQaQ= +github.com/getsentry/sentry-go v0.20.0/go.mod h1:lc76E2QywIyW8WuBnwl8Lc4bkmQH4+w1gwTf25trprY= github.com/ghodss/yaml v1.0.0/go.mod h1:4dBDuWmgqj2HViK6kFavaiC9ZROes6MMH2rRYeMEF04= github.com/gin-contrib/sse v0.1.0 h1:Y/yl/+YNO8GZSjAhjMsSuLt29uWRFHdHYUb5lYOV9qE= github.com/gin-contrib/sse v0.1.0/go.mod h1:RHrZQHXnP2xjPF+u1gW/2HnVO7nvIa9PG3Gm+fLHvGI= @@ -697,13 +697,14 @@ github.com/huandu/skiplist v1.2.0 h1:gox56QD77HzSC0w+Ws3MH3iie755GBJU1OER3h5VsYw github.com/huandu/skiplist v1.2.0/go.mod h1:7v3iFjLcSAzO4fN5B8dvebvo/qsfumiLiDXMrPiHF9w= github.com/hudl/fargo v1.3.0/go.mod h1:y3CKSmjA+wD2gak7sUSXTAoopbhU08POFhmITJgmKTg= github.com/hydrogen18/memlistener v0.0.0-20200120041712-dcc25e7acd91/go.mod h1:qEIFzExnS6016fRpRfxrExeVn2gbClQA99gQhnIcdhE= +github.com/iancoleman/strcase v0.2.0 h1:05I4QRnGpI0m37iZQRuskXh+w77mr6Z41lwQzuHLwW0= +github.com/iancoleman/strcase v0.2.0/go.mod h1:iwCmte+B7n89clKwxIoIXy/HfoL7AsD47ZCWhYzw7ho= github.com/ianlancetaylor/demangle v0.0.0-20181102032728-5e5cf60278f6/go.mod h1:aSSvb/t6k1mPoxDqO4vJh6VOCGPwU4O0C2/Eqndh1Sc= github.com/ianlancetaylor/demangle v0.0.0-20200824232613-28f6c0f3b639/go.mod h1:aSSvb/t6k1mPoxDqO4vJh6VOCGPwU4O0C2/Eqndh1Sc= github.com/imkira/go-interpol v1.1.0/go.mod h1:z0h2/2T3XF8kyEPpRgJ3kmNv+C43p+I/CoI+jC3w2iA= github.com/improbable-eng/grpc-web v0.15.0 h1:BN+7z6uNXZ1tQGcNAuaU1YjsLTApzkjt2tzCixLaUPQ= github.com/improbable-eng/grpc-web v0.15.0/go.mod h1:1sy9HKV4Jt9aEs9JSnkWlRJPuPtwNr0l57L4f878wP8= github.com/inconshreveable/mousetrap v1.0.0/go.mod h1:PxqpIevigyE2G7u3NXJIT2ANytuPF1OarO4DADm73n8= -github.com/inconshreveable/mousetrap v1.0.1/go.mod h1:vpF70FUmC8bwa3OWnCshd2FqLfsEA9PFc4w1p2J65bw= github.com/inconshreveable/mousetrap v1.1.0 h1:wN+x4NVGpMsO7ErUn/mUI3vEoE6Jt13X2s0bqwp9tc8= github.com/inconshreveable/mousetrap v1.1.0/go.mod h1:vpF70FUmC8bwa3OWnCshd2FqLfsEA9PFc4w1p2J65bw= github.com/influxdata/influxdb1-client v0.0.0-20191209144304-8bf82d3c094d/go.mod h1:qj24IKcXYK6Iy9ceXlo3Tc+vtHo9lIhSX5JddghvEPo= @@ -750,8 +751,8 @@ github.com/klauspost/compress v1.10.3/go.mod h1:aoV0uJVorq1K+umq18yTdKaF57EivdYs github.com/klauspost/compress v1.11.7/go.mod h1:aoV0uJVorq1K+umq18yTdKaF57EivdYsUV+/s2qKfXs= github.com/klauspost/compress v1.12.3/go.mod h1:8dP1Hq4DHOhN9w426knH3Rhby4rFm6D8eO+e+Dq5Gzg= github.com/klauspost/compress v1.15.11/go.mod h1:QPwzmACJjUTFsnSHH934V6woptycfrDDJnH7hvFVbGM= -github.com/klauspost/compress v1.16.3 h1:XuJt9zzcnaz6a16/OU53ZjWp/v7/42WcR5t2a0PcNQY= -github.com/klauspost/compress v1.16.3/go.mod h1:ntbaceVETuRiXiv4DpjP66DpAtAGkEQskQzEyD//IeE= +github.com/klauspost/compress v1.16.5 h1:IFV2oUNUzZaz+XyusxpLzpzS8Pt5rh0Z16For/djlyI= +github.com/klauspost/compress v1.16.5/go.mod h1:ntbaceVETuRiXiv4DpjP66DpAtAGkEQskQzEyD//IeE= github.com/klauspost/cpuid v1.2.1/go.mod h1:Pj4uuM528wm8OyEC2QMXAi2YiTZ96dNQPGgoMS4s3ek= github.com/konsorten/go-windows-terminal-sequences v1.0.1/go.mod h1:T0+1ngSBFLxvqU3pZ+m/2kptfBszLMUkC4ZK/EgS/cQ= github.com/konsorten/go-windows-terminal-sequences v1.0.3/go.mod h1:T0+1ngSBFLxvqU3pZ+m/2kptfBszLMUkC4ZK/EgS/cQ= @@ -776,8 +777,8 @@ github.com/libp2p/go-buffer-pool v0.1.0 h1:oK4mSFcQz7cTQIfqbe4MIj9gLW+mnanjyFtc6 github.com/libp2p/go-buffer-pool v0.1.0/go.mod h1:N+vh8gMqimBzdKkSMVuydVDq+UV5QTWy5HSiZacSbPg= github.com/lightstep/lightstep-tracer-common/golang/gogo v0.0.0-20190605223551-bc2310a04743/go.mod h1:qklhhLq1aX+mtWk9cPHPzaBjWImj5ULL6C7HFJtXQMM= github.com/lightstep/lightstep-tracer-go v0.18.1/go.mod h1:jlF1pusYV4pidLvZ+XD0UBX0ZE6WURAspgAczcDHrL4= -github.com/linxGnu/grocksdb v1.7.15 h1:AEhP28lkeAybv5UYNYviYISpR6bJejEnKuYbnWAnxx0= -github.com/linxGnu/grocksdb v1.7.15/go.mod h1:pY55D0o+r8yUYLq70QmhdudxYvoDb9F+9puf4m3/W+U= +github.com/linxGnu/grocksdb v1.7.16 h1:Q2co1xrpdkr5Hx3Fp+f+f7fRGhQFQhvi/+226dtLmA8= +github.com/linxGnu/grocksdb v1.7.16/go.mod h1:JkS7pl5qWpGpuVb3bPqTz8nC12X3YtPZT+Xq7+QfQo4= github.com/lyft/protoc-gen-validate v0.0.13/go.mod h1:XbGvPuh87YZc5TdIa2/I4pLk0QoUACkjt2znoq26NVQ= github.com/magiconair/properties v1.8.0/go.mod h1:PppfXfuXeibc/6YijjN8zIbojt8czPbwD3XqdrwzmxQ= github.com/magiconair/properties v1.8.7 h1:IeQXZAiQcpL9mgcAe1Nu6cX9LLw6ExEHKjN0VQdvPDY= @@ -913,8 +914,8 @@ github.com/prometheus/client_golang v1.0.0/go.mod h1:db9x61etRT2tGnBNRi70OPL5Fsn github.com/prometheus/client_golang v1.3.0/go.mod h1:hJaj2vgQTGQmVCsAACORcieXFeDPbaTKGT+JTgUa3og= github.com/prometheus/client_golang v1.4.0/go.mod h1:e9GMxYsXl05ICDXkRhurwBS4Q3OK1iX/F2sw+iXX5zU= github.com/prometheus/client_golang v1.7.1/go.mod h1:PY5Wy2awLA44sXw4AOSfFBetzPP4j5+D6mVACh+pe2M= -github.com/prometheus/client_golang v1.14.0 h1:nJdhIvne2eSX/XRAFV9PcvFFRbrjbcTUj0VP62TMhnw= -github.com/prometheus/client_golang v1.14.0/go.mod h1:8vpkKitgIVNcqrRBWh1C4TIUQgYNtG/XQE4E/Zae36Y= +github.com/prometheus/client_golang v1.15.0 h1:5fCgGYogn0hFdhyhLbw7hEsWxufKtY9klyvdNfFlFhM= +github.com/prometheus/client_golang v1.15.0/go.mod h1:e9yaBhRPU2pPNsZwE+JdQl0KEt1N9XgF6zxWmaC0xOk= github.com/prometheus/client_model v0.0.0-20180712105110-5c3871d89910/go.mod h1:MbSGuTsp3dbXC40dX6PRTWyKYBIrTGTE9sqQNg2J8bo= github.com/prometheus/client_model v0.0.0-20190115171406-56726106282f/go.mod h1:MbSGuTsp3dbXC40dX6PRTWyKYBIrTGTE9sqQNg2J8bo= github.com/prometheus/client_model v0.0.0-20190129233127-fd36f4220a90/go.mod h1:xMI15A0UPsDsEKsMN9yxemIoYk6Tm2C1GtYGdfGttqA= @@ -949,14 +950,15 @@ github.com/rogpeppe/go-internal v1.3.0/go.mod h1:M8bDsm7K2OlrFYOpmOWEs/qY81heoFR github.com/rogpeppe/go-internal v1.6.1/go.mod h1:xXDCJY+GAPziupqXw64V24skbSoqbTEfhy4qGm1nDQc= github.com/rogpeppe/go-internal v1.8.0/go.mod h1:WmiCO8CzOY8rg0OYDC4/i/2WRWAB6poM+XZ2dLUbcbE= github.com/rogpeppe/go-internal v1.8.1/go.mod h1:JeRgkft04UBgHMgCIwADu4Pn6Mtm5d4nPKWu0nJ5d+o= -github.com/rogpeppe/go-internal v1.9.0 h1:73kH8U+JUqXU8lRuOHeVHaa/SZPifC7BkcraZVejAe8= github.com/rogpeppe/go-internal v1.9.0/go.mod h1:WtVeX8xhTBvf0smdhujwtBcq4Qrzq/fJaraNFVN+nFs= +github.com/rogpeppe/go-internal v1.10.0 h1:TMyTOH3F/DB16zRVcYyreMH6GnZZrwQVAoYjRBZyWFQ= +github.com/rogpeppe/go-internal v1.10.0/go.mod h1:UQnix2H7Ngw/k4C5ijL5+65zddjncjaFoBhdsK/akog= github.com/rs/cors v1.7.0/go.mod h1:gFx+x8UowdsKA9AchylcLynDq+nNFfI8FkUZdN/jGCU= github.com/rs/cors v1.8.3 h1:O+qNyWn7Z+F9M0ILBHgMVPuB1xTOucVd5gtaYyXBpRo= github.com/rs/cors v1.8.3/go.mod h1:XyqrcTp5zjWr1wsJ8PIRZssZ8b/WMcMf71DJnit4EMU= github.com/rs/xid v1.4.0/go.mod h1:trrq9SKmegXys3aeAKXMUTdJsYXVwGY3RLcfgqegfbg= -github.com/rs/zerolog v1.29.0 h1:Zes4hju04hjbvkVkOhdl2HpZa+0PmVwigmo8XoORE5w= -github.com/rs/zerolog v1.29.0/go.mod h1:NILgTygv/Uej1ra5XxGf82ZFSLk58MFGAUS2o6usyD0= +github.com/rs/zerolog v1.29.1 h1:cO+d60CHkknCbvzEWxP0S9K6KqyTjrCNUy1LdQLCGPc= +github.com/rs/zerolog v1.29.1/go.mod h1:Le6ESbR7hc+DP6Lt1THiV8CQSdkkNrd3R0XbEgp3ZBU= github.com/russross/blackfriday v1.5.2/go.mod h1:JO/DiYxRf+HjHt06OyowR9PTA263kcR/rfWxYHBV53g= github.com/russross/blackfriday/v2 v2.0.1/go.mod h1:+Rmxgy9KzJVeS9/2gXHxylqXiyQDYRxCVz55jmeOWTM= github.com/russross/blackfriday/v2 v2.1.0/go.mod h1:+Rmxgy9KzJVeS9/2gXHxylqXiyQDYRxCVz55jmeOWTM= @@ -989,8 +991,8 @@ github.com/spf13/cast v1.5.0 h1:rj3WzYc11XZaIZMPKmwP96zkFEnnAmV8s6XbB2aY32w= github.com/spf13/cast v1.5.0/go.mod h1:SpXXQ5YoyJw6s3/6cMTQuxvgRl3PCJiyaX9p6b155UU= github.com/spf13/cobra v0.0.3/go.mod h1:1l0Ry5zgKvJasoi3XT1TypsSe7PqH0Sj9dhYf7v3XqQ= github.com/spf13/cobra v0.0.5/go.mod h1:3K3wKZymM7VvHMDS9+Akkh4K60UwM26emMESw8tLCHU= -github.com/spf13/cobra v1.6.1 h1:o94oiPyS4KD1mPy2fmcYYHHfCxLqYjJOhGsCHFZtEzA= -github.com/spf13/cobra v1.6.1/go.mod h1:IOw/AERYS7UzyrGinqmz6HLUo219MORXGxhbaJUqzrY= +github.com/spf13/cobra v1.7.0 h1:hyqWnYt1ZQShIddO5kBpj3vu05/++x6tJ6dg8EC572I= +github.com/spf13/cobra v1.7.0/go.mod h1:uLxZILRyS/50WlhOIKD7W6V5bgeIt+4sICxh6uRMrb0= github.com/spf13/jwalterweatherman v1.0.0/go.mod h1:cQK4TGJAtQXfYWX+Ddv3mKDzgVb68N+wFjFa4jdeBTo= github.com/spf13/jwalterweatherman v1.1.0 h1:ue6voC5bR5F8YxI5S67j9i582FU4Qvo2bmqnqMYADFk= github.com/spf13/jwalterweatherman v1.1.0/go.mod h1:aNWZUN0dPAAO/Ljvb5BEdw96iTZ0EXowPYD95IqWIGo= @@ -1115,8 +1117,8 @@ golang.org/x/crypto v0.0.0-20210421170649-83a5a9bb288b/go.mod h1:T9bdIzuCu7OtxOm golang.org/x/crypto v0.0.0-20210711020723-a769d52b0f97/go.mod h1:GvvjBRRGRdwPK5ydBHafDWAxML/pGHZbMvKqRZ5+Abc= golang.org/x/crypto v0.0.0-20210921155107-089bfa567519/go.mod h1:GvvjBRRGRdwPK5ydBHafDWAxML/pGHZbMvKqRZ5+Abc= golang.org/x/crypto v0.0.0-20211108221036-ceb1ce70b4fa/go.mod h1:GvvjBRRGRdwPK5ydBHafDWAxML/pGHZbMvKqRZ5+Abc= -golang.org/x/crypto v0.7.0 h1:AvwMYaRytfdeVt3u6mLaxYtErKYjxA2OXjJ1HHq6t3A= -golang.org/x/crypto v0.7.0/go.mod h1:pYwdfH91IfpZVANVyUOhSIPZaFoJGxTFbZhFTx+dXZU= +golang.org/x/crypto v0.8.0 h1:pd9TJtTueMTVQXzk8E2XESSMQDj/U7OUu0PqJqPXQjQ= +golang.org/x/crypto v0.8.0/go.mod h1:mRqEX+O9/h5TFCrQhkgjo2yKi0yYA+9ecGkdQoHrywE= golang.org/x/exp v0.0.0-20190121172915-509febef88a4/go.mod h1:CJ0aWSM057203Lf6IL+f9T1iT9GByDxfZKAQTCR3kQA= golang.org/x/exp v0.0.0-20190306152737-a1d7652674e8/go.mod h1:CJ0aWSM057203Lf6IL+f9T1iT9GByDxfZKAQTCR3kQA= golang.org/x/exp v0.0.0-20190510132918-efd6b22b2522/go.mod h1:ZjyILWgesfNpC6sMxTJOJm9Kp84zZh5NQWvqDGG3Qr8= @@ -1220,8 +1222,8 @@ golang.org/x/net v0.0.0-20220722155237-a158d28d115b/go.mod h1:XRhObCWvk6IyKnWLug golang.org/x/net v0.0.0-20220909164309-bea034e7d591/go.mod h1:YDH+HFinaLZZlnHAfSS6ZXJJ9M9t4Dl22yv3iI2vPwk= golang.org/x/net v0.0.0-20221014081412-f15817d10f9b/go.mod h1:YDH+HFinaLZZlnHAfSS6ZXJJ9M9t4Dl22yv3iI2vPwk= golang.org/x/net v0.1.0/go.mod h1:Cx3nUiGt4eDBEyega/BKRp+/AlGL8hYe7U9odMt2Cco= -golang.org/x/net v0.8.0 h1:Zrh2ngAOFYneWTAIAPethzeaQLuHwhuBkuV6ZiRnUaQ= -golang.org/x/net v0.8.0/go.mod h1:QVkue5JL9kW//ek3r6jTKnTFis1tRmNAW2P1shuFdJc= +golang.org/x/net v0.9.0 h1:aWJ/m6xSmxWBx+V0XRHTlrYrPG56jKsLdTFmsSsCzOM= +golang.org/x/net v0.9.0/go.mod h1:d48xBJpPfHeWQsugry2m+kC02ZBRGRgulfHnEXEuWns= golang.org/x/oauth2 v0.0.0-20180821212333-d2e6202438be/go.mod h1:N/0e6XlmueqKjAGxoOufVs8QHGRruUQn6yWY3a++T0U= golang.org/x/oauth2 v0.0.0-20190226205417-e64efc72b421/go.mod h1:gOpvHmFTYa4IltrdGE7lF6nIHvwfUNPOp7c8zoXwtLw= golang.org/x/oauth2 v0.0.0-20190604053449-0f29369cfe45/go.mod h1:gOpvHmFTYa4IltrdGE7lF6nIHvwfUNPOp7c8zoXwtLw= @@ -1368,13 +1370,14 @@ golang.org/x/sys v0.0.0-20220811171246-fbc7d0a398ab/go.mod h1:oPkhp1MJrh7nUepCBc golang.org/x/sys v0.0.0-20220908164124-27713097b956/go.mod h1:oPkhp1MJrh7nUepCBck5+mAzfO9JrbApNNgaTdGDITg= golang.org/x/sys v0.0.0-20221010170243-090e33056c14/go.mod h1:oPkhp1MJrh7nUepCBck5+mAzfO9JrbApNNgaTdGDITg= golang.org/x/sys v0.1.0/go.mod h1:oPkhp1MJrh7nUepCBck5+mAzfO9JrbApNNgaTdGDITg= -golang.org/x/sys v0.6.0 h1:MVltZSvRTcU2ljQOhs94SXPftV6DCNnZViHeQps87pQ= golang.org/x/sys v0.6.0/go.mod h1:oPkhp1MJrh7nUepCBck5+mAzfO9JrbApNNgaTdGDITg= +golang.org/x/sys v0.7.0 h1:3jlCCIQZPdOYu1h8BkNvLz8Kgwtae2cagcG/VamtZRU= +golang.org/x/sys v0.7.0/go.mod h1:oPkhp1MJrh7nUepCBck5+mAzfO9JrbApNNgaTdGDITg= golang.org/x/term v0.0.0-20201126162022-7de9c90e9dd1/go.mod h1:bj7SfCRtBDWHUb9snDiAeCFNEtKQo2Wmx5Cou7ajbmo= golang.org/x/term v0.0.0-20210927222741-03fcf44c2211/go.mod h1:jbD1KX2456YbFQfuXm/mYQcufACuNUgVhRMnK/tPxf8= golang.org/x/term v0.1.0/go.mod h1:jbD1KX2456YbFQfuXm/mYQcufACuNUgVhRMnK/tPxf8= -golang.org/x/term v0.6.0 h1:clScbb1cHjoCkyRbWwBEUZ5H/tIFu5TAXIqaZD0Gcjw= -golang.org/x/term v0.6.0/go.mod h1:m6U89DPEgQRMq3DNkDClhWw02AUbt2daBVO4cn4Hv9U= +golang.org/x/term v0.7.0 h1:BEvjmm5fURWqcfbSKTdpkDXYBrUS1c0m8agp14W48vQ= +golang.org/x/term v0.7.0/go.mod h1:P32HKFT3hSsZrRxla30E9HqToFYAQPCMs/zFMBUFqPY= golang.org/x/text v0.0.0-20170915032832-14c0d48ead0c/go.mod h1:NqM8EUOU14njkJ3fqMW+pc6Ldnwhi/IjpwHt7yyuwOQ= golang.org/x/text v0.3.0/go.mod h1:NqM8EUOU14njkJ3fqMW+pc6Ldnwhi/IjpwHt7yyuwOQ= golang.org/x/text v0.3.1-0.20180807135948-17ff2d5776d2/go.mod h1:NqM8EUOU14njkJ3fqMW+pc6Ldnwhi/IjpwHt7yyuwOQ= @@ -1385,8 +1388,8 @@ golang.org/x/text v0.3.5/go.mod h1:5Zoc/QRtKVWzQhOtBMvqHzDpF6irO9z98xDceosuGiQ= golang.org/x/text v0.3.6/go.mod h1:5Zoc/QRtKVWzQhOtBMvqHzDpF6irO9z98xDceosuGiQ= golang.org/x/text v0.3.7/go.mod h1:u+2+/6zg+i71rQMx5EYifcz6MCKuco9NR6JIITiCfzQ= golang.org/x/text v0.4.0/go.mod h1:mrYo+phRRbMaCq/xk9113O4dZlRixOauAjOtrjsXDZ8= -golang.org/x/text v0.8.0 h1:57P1ETyNKtuIjB4SRd15iJxuhj8Gc416Y78H3qgMh68= -golang.org/x/text v0.8.0/go.mod h1:e1OnstbJyHTd6l/uOt8jFFHp6TRDWZR/bV3emEE/zU8= +golang.org/x/text v0.9.0 h1:2sjJmO8cDvYveuX97RDLsxlyUxLl+GHoLxBiRdHllBE= +golang.org/x/text v0.9.0/go.mod h1:e1OnstbJyHTd6l/uOt8jFFHp6TRDWZR/bV3emEE/zU8= golang.org/x/time v0.0.0-20180412165947-fbb02b2291d2/go.mod h1:tRJNPiyCQ0inRvYxbN9jk5I+vvW/OXSQhTDSoE431IQ= golang.org/x/time v0.0.0-20181108054448-85acf8d2951c/go.mod h1:tRJNPiyCQ0inRvYxbN9jk5I+vvW/OXSQhTDSoE431IQ= golang.org/x/time v0.0.0-20190308202827-9d24e82272b4/go.mod h1:tRJNPiyCQ0inRvYxbN9jk5I+vvW/OXSQhTDSoE431IQ= @@ -1636,8 +1639,8 @@ google.golang.org/genproto v0.0.0-20221010155953-15ba04fc1c0e/go.mod h1:3526vdqw google.golang.org/genproto v0.0.0-20221014173430-6e2ab493f96b/go.mod h1:1vXfmgAz9N9Jx0QA82PqRVauvCz1SGSz739p0f183jM= google.golang.org/genproto v0.0.0-20221014213838-99cd37c6964a/go.mod h1:1vXfmgAz9N9Jx0QA82PqRVauvCz1SGSz739p0f183jM= google.golang.org/genproto v0.0.0-20221025140454-527a21cfbd71/go.mod h1:9qHF0xnpdSfF6knlcsnpzUu5y+rpwgbvsyGAZPBMg4s= -google.golang.org/genproto v0.0.0-20230320184635-7606e756e683 h1:khxVcsk/FhnzxMKOyD+TDGwjbEOpcPuIpmafPGFmhMA= -google.golang.org/genproto v0.0.0-20230320184635-7606e756e683/go.mod h1:NWraEVixdDnqcqQ30jipen1STv2r/n24Wb7twVTGR4s= +google.golang.org/genproto v0.0.0-20230410155749-daa745c078e1 h1:KpwkzHKEF7B9Zxg18WzOa7djJ+Ha5DzthMyZYQfEn2A= +google.golang.org/genproto v0.0.0-20230410155749-daa745c078e1/go.mod h1:nKE/iIaLqn2bQwXBg8f1g2Ylh6r5MN5CmZvuzZCgsCU= google.golang.org/grpc v1.12.0/go.mod h1:yo6s7OP7yaDglbqo1J04qKzAhqBH6lvTonzMVmEdcZw= google.golang.org/grpc v1.17.0/go.mod h1:6QZJwpn2B+Zp71q/5VxRsJ6NXXVCE5NRUHRo+f3cWCs= google.golang.org/grpc v1.19.0/go.mod h1:mqu4LbDTu4XGKhr4mRzUsmM4RtVoemTSY81AxZiDr8c= diff --git a/simapp/internal/testnet/cometrpc_test.go b/simapp/internal/testnet/cometrpc_test.go new file mode 100644 index 000000000000..fa463630f988 --- /dev/null +++ b/simapp/internal/testnet/cometrpc_test.go @@ -0,0 +1,167 @@ +package testnet_test + +import ( + "context" + "testing" + "time" + + "cosmossdk.io/log" + "cosmossdk.io/simapp" + cmtcfg "github.com/cometbft/cometbft/config" + "github.com/cometbft/cometbft/rpc/client/http" + dbm "github.com/cosmos/cosmos-db" + "github.com/cosmos/cosmos-sdk/baseapp" + "github.com/cosmos/cosmos-sdk/codec" + codectypes "github.com/cosmos/cosmos-sdk/codec/types" + simtestutil "github.com/cosmos/cosmos-sdk/testutil/sims" + "github.com/cosmos/cosmos-sdk/testutil/testnet" + sdk "github.com/cosmos/cosmos-sdk/types" + banktypes "github.com/cosmos/cosmos-sdk/x/bank/types" + "github.com/stretchr/testify/require" +) + +const memdb = "memdb" + +// A single comet server in a network runs an RPC server successfully. +func TestCometRPC_SingleRPCServer(t *testing.T) { + const nVals = 2 + + valPKs := testnet.NewValidatorPrivKeys(nVals) + cmtVals := valPKs.CometGenesisValidators() + stakingVals := cmtVals.StakingValidators() + + const chainID = "comet-rpc-singleton" + + b := testnet.DefaultGenesisBuilderOnlyValidators( + chainID, + stakingVals, + sdk.NewCoin(sdk.DefaultBondDenom, sdk.DefaultPowerReduction), + ) + + jGenesis := b.Encode() + + // Logs shouldn't be necessary here because we are exercising CometStarter, + // and only doing a very basic check that the RPC talks to the app. + logger := log.NewNopLogger() + + nodes, err := testnet.NewNetwork(nVals, func(idx int) *testnet.CometStarter { + rootDir := t.TempDir() + + app := simapp.NewSimApp( + logger, + dbm.NewMemDB(), + nil, + true, + simtestutil.NewAppOptionsWithFlagHome(rootDir), + baseapp.SetChainID(chainID), + ) + + cfg := cmtcfg.DefaultConfig() + cfg.BaseConfig.DBBackend = memdb + + cs := testnet.NewCometStarter( + app, + cfg, + valPKs[idx].Val, + jGenesis, + rootDir, + ) + + // Only enable the RPC on the first service. + if idx == 0 { + cs = cs.RPCListen() + } + + return cs + }) + defer nodes.StopAndWait() + require.NoError(t, err) + + // Once HTTP client to be shared across the following subtests. + c, err := http.New(nodes[0].Config().RPC.ListenAddress, "/websocket") + require.NoError(t, err) + + t.Run("status query", func(t *testing.T) { + ctx := context.Background() + st, err := c.Status(ctx) + require.NoError(t, err) + + // Simple assertion to ensure we have a functioning RPC. + require.Equal(t, chainID, st.NodeInfo.Network) + }) + + // Block until reported height is at least 1, + // otherwise we can't make transactions. + require.NoError(t, testnet.WaitForNodeHeight(nodes[0], 1, 10*time.Second)) + + t.Run("simple abci query", func(t *testing.T) { + res, err := c.ABCIQuery( + context.Background(), + "/cosmos.bank.v1beta1.Query/TotalSupply", + nil, + ) + require.NoError(t, err) + + registry := codectypes.NewInterfaceRegistry() + cdc := codec.NewProtoCodec(registry) + + var tsResp banktypes.QueryTotalSupplyResponse + require.NoError(t, cdc.Unmarshal(res.Response.Value, &tsResp)) + + // Just check that something is reported in the supply. + require.NotEmpty(t, tsResp.Supply) + }) +} + +// Starting two comet instances with an RPC server, +// fails with a predictable error. +func TestCometRPC_MultipleRPCError(t *testing.T) { + const nVals = 2 + + valPKs := testnet.NewValidatorPrivKeys(nVals) + cmtVals := valPKs.CometGenesisValidators() + stakingVals := cmtVals.StakingValidators() + + const chainID = "comet-rpc-multiple" + + b := testnet.DefaultGenesisBuilderOnlyValidators( + chainID, + stakingVals, + sdk.NewCoin(sdk.DefaultBondDenom, sdk.DefaultPowerReduction), + ) + + jGenesis := b.Encode() + + // Logs shouldn't be necessary here because we are exercising CometStarter. + logger := log.NewNopLogger() + + nodes, err := testnet.NewNetwork(nVals, func(idx int) *testnet.CometStarter { + rootDir := t.TempDir() + + app := simapp.NewSimApp( + logger, + dbm.NewMemDB(), + nil, + true, + simtestutil.NewAppOptionsWithFlagHome(rootDir), + baseapp.SetChainID(chainID), + ) + + cfg := cmtcfg.DefaultConfig() + cfg.BaseConfig.DBBackend = memdb + + return testnet.NewCometStarter( + app, + cfg, + valPKs[idx].Val, + jGenesis, + rootDir, + ).RPCListen() // Every node has RPCListen enabled, which will cause a failure. + }) + defer nodes.StopAndWait() + + // Returned error is convertible to CometRPCInUseError. + // We can't test the exact value because it includes a stack trace. + require.Error(t, err) + require.ErrorAs(t, err, new(testnet.CometRPCInUseError)) +} diff --git a/simapp/internal/testnet/cometstarter_test.go b/simapp/internal/testnet/cometstarter_test.go new file mode 100644 index 000000000000..9e9d1d53c4ac --- /dev/null +++ b/simapp/internal/testnet/cometstarter_test.go @@ -0,0 +1,134 @@ +package testnet_test + +import ( + "fmt" + "math/rand" + "net" + "testing" + "time" + + "cosmossdk.io/log" + "cosmossdk.io/simapp" + cmtcfg "github.com/cometbft/cometbft/config" + dbm "github.com/cosmos/cosmos-db" + "github.com/cosmos/cosmos-sdk/baseapp" + simtestutil "github.com/cosmos/cosmos-sdk/testutil/sims" + "github.com/cosmos/cosmos-sdk/testutil/testnet" + sdk "github.com/cosmos/cosmos-sdk/types" + "github.com/stretchr/testify/require" +) + +// Use a limited set of available ports to ensure that +// retries eventually land on a free port. +func TestCometStarter_PortContention(t *testing.T) { + if testing.Short() { + t.Skip("skipping long test in short mode") + } + + const nVals = 4 + + // Find n+1 addresses that should be free. + // Ephemeral port range should start at about 49k+ + // according to `sysctl net.inet.ip.portrange` on macOS, + // and at about 32k+ on Linux + // according to `sysctl net.ipv4.ip_local_port_range`. + // + // Because we attempt to find free addresses outside that range, + // it is unlikely that another process will claim a port + // we discover to be free, during the time this test runs. + const portSeekStart = 19000 + reuseAddrs := make([]string, 0, nVals+1) + for i := portSeekStart; i < portSeekStart+1000; i++ { + addr := fmt.Sprintf("127.0.0.1:%d", i) + ln, err := net.Listen("tcp", addr) + if err != nil { + // No need to log the failure. + continue + } + + // If the port was free, append it to our reusable addresses. + reuseAddrs = append(reuseAddrs, "tcp://"+addr) + _ = ln.Close() + + if len(reuseAddrs) == nVals+1 { + break + } + } + + if len(reuseAddrs) != nVals+1 { + t.Fatalf("needed %d free ports but only found %d", nVals+1, len(reuseAddrs)) + } + + // Now that we have one more port than the number of validators, + // there is a good chance that picking a random port will conflict with a previously chosen one. + // But since CometStarter retries several times, + // it should eventually land on a free port. + + valPKs := testnet.NewValidatorPrivKeys(nVals) + cmtVals := valPKs.CometGenesisValidators() + stakingVals := cmtVals.StakingValidators() + + const chainID = "simapp-cometstarter" + + b := testnet.DefaultGenesisBuilderOnlyValidators( + chainID, + stakingVals, + sdk.NewCoin(sdk.DefaultBondDenom, sdk.DefaultPowerReduction), + ) + + jGenesis := b.Encode() + + // Use an info-level logger, because the debug logs in comet are noisy + // and there is a data race in comet debug logs, + // due to be fixed in v0.37.1 which is not yet released: + // https://github.com/cometbft/cometbft/pull/532 + logger := log.NewTestLoggerInfo(t) + + const nRuns = 4 + for i := 0; i < nRuns; i++ { + t.Run(fmt.Sprintf("attempt %d", i), func(t *testing.T) { + nodes, err := testnet.NewNetwork(nVals, func(idx int) *testnet.CometStarter { + rootDir := t.TempDir() + + app := simapp.NewSimApp( + logger.With("instance", idx), + dbm.NewMemDB(), + nil, + true, + simtestutil.NewAppOptionsWithFlagHome(rootDir), + baseapp.SetChainID(chainID), + ) + + cfg := cmtcfg.DefaultConfig() + + // memdb is sufficient for this test. + cfg.BaseConfig.DBBackend = "memdb" + + return testnet.NewCometStarter( + app, + cfg, + valPKs[idx].Val, + jGenesis, + rootDir, + ). + Logger(logger.With("rootmodule", fmt.Sprintf("comet_node-%d", idx))). + TCPAddrChooser(func() string { + // This chooser function is the key of this test, + // where there is only one more available address than there are nodes. + // Therefore it is likely that an address will already be in use, + // thereby exercising the address-in-use retry. + return reuseAddrs[rand.Intn(len(reuseAddrs))] + }) + }) + + // Ensure nodes are stopped completely, + // so that we don't get t.Cleanup errors around directories not being empty. + defer nodes.StopAndWait() + require.NoError(t, err) + + // Ensure that the height advances. + // Looking for height 2 seems more meaningful than 1. + require.NoError(t, testnet.WaitForNodeHeight(nodes[0], 2, 10*time.Second)) + }) + } +} diff --git a/simapp/internal/testnet/doc.go b/simapp/internal/testnet/doc.go new file mode 100644 index 000000000000..19064ddd0f45 --- /dev/null +++ b/simapp/internal/testnet/doc.go @@ -0,0 +1,10 @@ +// Package testnet contains tests for +// [github.com/cosmos/cosmos-sdk/testutil/testnet]. +// +// Eventually all of these tests will move into that package, +// but that is currently blocked on having a minimal app defined +// in the root cosmos-sdk Go module. +// Once that app is available, the contents of this package +// will be moved to testutil/testnet, +// and references to SimApp will be replaced by the minimal app. +package testnet diff --git a/simapp/internal/testnet/example_basic_test.go b/simapp/internal/testnet/example_basic_test.go new file mode 100644 index 000000000000..99f7ae362cca --- /dev/null +++ b/simapp/internal/testnet/example_basic_test.go @@ -0,0 +1,112 @@ +package testnet_test + +import ( + "fmt" + "os" + "path/filepath" + + "cosmossdk.io/log" + "cosmossdk.io/simapp" + cmtcfg "github.com/cometbft/cometbft/config" + dbm "github.com/cosmos/cosmos-db" + "github.com/cosmos/cosmos-sdk/baseapp" + simtestutil "github.com/cosmos/cosmos-sdk/testutil/sims" + "github.com/cosmos/cosmos-sdk/testutil/testnet" + sdk "github.com/cosmos/cosmos-sdk/types" +) + +func Example_basicUsage() { + const nVals = 2 + + // Set up new private keys for the set of validators. + valPKs := testnet.NewValidatorPrivKeys(nVals) + + // Comet-style validators. + cmtVals := valPKs.CometGenesisValidators() + + // Cosmos SDK staking validators for genesis. + stakingVals := cmtVals.StakingValidators() + + const chainID = "example-basic" + + // Create a genesis builder that only requires validators, + // without any separate delegator accounts. + // + // If you need further customization, start with testnet.NewGenesisBuilder(). + b := testnet.DefaultGenesisBuilderOnlyValidators( + chainID, + stakingVals, + // The amount to use in each validator's account during gentx. + sdk.NewCoin(sdk.DefaultBondDenom, sdk.DefaultPowerReduction), + ) + + // JSON-formatted genesis. + jGenesis := b.Encode() + + // In this example, we have an outer root directory for the validators. + // Use t.TempDir() in tests. + rootDir, err := os.MkdirTemp("", "testnet-example-") + if err != nil { + panic(err) + } + defer os.RemoveAll(rootDir) + + // In tests, you probably want to use log.NewTestLoggerInfo(t). + logger := log.NewNopLogger() + + // The NewNetwork function creates a network of validators. + // We have to provide a callback to return CometStarter instances. + // NewNetwork will start all the comet instances concurrently + // and join the nodes together. + nodes, err := testnet.NewNetwork(nVals, func(idx int) *testnet.CometStarter { + // Make a new directory for the validator being created. + // In tests, this would be a simpler call to t.TempDir(). + dir := filepath.Join(rootDir, fmt.Sprintf("val-%d", idx)) + if err := os.Mkdir(dir, 0o755); err != nil { + panic(err) + } + + // TODO: use a different minimal app for this. + app := simapp.NewSimApp( + logger.With("instance", idx), + dbm.NewMemDB(), + nil, + true, + simtestutil.NewAppOptionsWithFlagHome(rootDir), + baseapp.SetChainID(chainID), + ) + + // Each CometStarter instance must be associated with + // a distinct comet Config object, + // as the CometStarter will automatically modify some fields, + // including P2P.ListenAddress. + cfg := cmtcfg.DefaultConfig() + + // No need to persist comet's DB to disk in this example. + cfg.BaseConfig.DBBackend = "memdb" + + return testnet.NewCometStarter( + app, + cfg, + valPKs[idx].Val, // Validator private key for this comet instance. + jGenesis, // Raw bytes of genesis file. + dir, // Where to put files on disk. + ).Logger(logger.With("root_module", fmt.Sprintf("comet_%d", idx))) + }) + // StopAndWait must be deferred before the error check, + // as the nodes value may contain some successfully started instances. + defer nodes.StopAndWait() + if err != nil { + panic(err) + } + + // Now you can begin interacting with the nodes. + // For the sake of this example, we'll just check + // a couple simple properties of one node. + fmt.Println(nodes[0].IsListening()) + fmt.Println(nodes[0].GenesisDoc().ChainID) + + // Output: + // true + // example-basic +} diff --git a/simapp/sim_test.go b/simapp/sim_test.go index b30f1771c1be..53ba1b1ece56 100644 --- a/simapp/sim_test.go +++ b/simapp/sim_test.go @@ -330,7 +330,7 @@ func TestAppStateDeterminism(t *testing.T) { config.ChainID = SimAppChainID numSeeds := 3 - numTimesToRunPerSeed := 5 + numTimesToRunPerSeed := 3 // This used to be set to 5, but we've temporarily reduced it to 3 for the sake of faster CI. appHashList := make([]json.RawMessage, numTimesToRunPerSeed) appOptions := viper.New() diff --git a/simapp/simd/cmd/root.go b/simapp/simd/cmd/root.go index 9d29ecd26e66..84c798aa1714 100644 --- a/simapp/simd/cmd/root.go +++ b/simapp/simd/cmd/root.go @@ -5,17 +5,16 @@ import ( "io" "os" - "cosmossdk.io/log" cmtcfg "github.com/cometbft/cometbft/config" dbm "github.com/cosmos/cosmos-db" "github.com/spf13/cobra" "github.com/spf13/viper" + "cosmossdk.io/log" "cosmossdk.io/simapp" "cosmossdk.io/simapp/params" confixcmd "cosmossdk.io/tools/confix/cmd" rosettaCmd "cosmossdk.io/tools/rosetta/cmd" - "github.com/cosmos/cosmos-sdk/client" "github.com/cosmos/cosmos-sdk/client/config" "github.com/cosmos/cosmos-sdk/client/debug" @@ -82,18 +81,13 @@ func NewRootCmd() *cobra.Command { // This needs to go after ReadFromClientConfig, as that function // sets the RPC client needed for SIGN_MODE_TEXTUAL. - // - // TODO Currently, the TxConfig below doesn't include Textual, so - // an error will arise when using the --textual flag. - // ref: https://github.com/cosmos/cosmos-sdk/issues/11970 - txt, err := txmodule.NewTextualWithGRPCConn(initClientCtx) + opts, err := txmodule.NewSignModeOptionsWithMetadataQueryFn(txmodule.NewGRPCCoinMetadataQueryFn(initClientCtx)) if err != nil { return err } - txConfigWithTextual := tx.NewTxConfigWithTextual( + txConfigWithTextual := tx.NewTxConfigWithOptions( codec.NewProtoCodec(encodingConfig.InterfaceRegistry), - encodingConfig.TxConfig.SignModeHandler().Modes(), - txt, + opts, ) initClientCtx = initClientCtx.WithTxConfig(txConfigWithTextual) @@ -219,10 +213,10 @@ func addModuleInitFlags(startCmd *cobra.Command) { // genesisCommand builds genesis-related `simd genesis` command. Users may provide application specific commands as a parameter func genesisCommand(encodingConfig params.EncodingConfig, cmds ...*cobra.Command) *cobra.Command { - cmd := genutilcli.GenesisCoreCommand(encodingConfig.TxConfig, simapp.ModuleBasics, simapp.DefaultNodeHome) + cmd := genutilcli.Commands(encodingConfig.TxConfig, simapp.ModuleBasics, simapp.DefaultNodeHome) - for _, sub_cmd := range cmds { - cmd.AddCommand(sub_cmd) + for _, subCmd := range cmds { + cmd.AddCommand(subCmd) } return cmd } @@ -238,7 +232,6 @@ func queryCommand() *cobra.Command { } cmd.AddCommand( - authcmd.GetAccountCmd(), rpc.ValidatorCommand(), server.QueryBlockCmd(), authcmd.QueryTxsByEventsCmd(), diff --git a/simapp/simd/cmd/testnet.go b/simapp/simd/cmd/testnet.go index 1e6fecbb6733..cd539255b189 100644 --- a/simapp/simd/cmd/testnet.go +++ b/simapp/simd/cmd/testnet.go @@ -468,14 +468,14 @@ func calculateIP(ip string, i int) (string, error) { return ipv4.String(), nil } -func writeFile(name string, dir string, contents []byte) error { +func writeFile(name, dir string, contents []byte) error { file := filepath.Join(dir, name) if err := os.MkdirAll(dir, 0o755); err != nil { return fmt.Errorf("could not create directory %q: %w", dir, err) } - if err := os.WriteFile(file, contents, 0o644); err != nil { //nolint: gosec + if err := os.WriteFile(file, contents, 0o600); err != nil { return err } diff --git a/simapp/upgrades.go b/simapp/upgrades.go index 891d72d4767a..1bce6df3f6ac 100644 --- a/simapp/upgrades.go +++ b/simapp/upgrades.go @@ -4,71 +4,22 @@ import ( storetypes "cosmossdk.io/store/types" upgradetypes "cosmossdk.io/x/upgrade/types" - "github.com/cosmos/cosmos-sdk/baseapp" sdk "github.com/cosmos/cosmos-sdk/types" "github.com/cosmos/cosmos-sdk/types/module" - authtypes "github.com/cosmos/cosmos-sdk/x/auth/types" - banktypes "github.com/cosmos/cosmos-sdk/x/bank/types" - consensustypes "github.com/cosmos/cosmos-sdk/x/consensus/types" - crisistypes "github.com/cosmos/cosmos-sdk/x/crisis/types" - distrtypes "github.com/cosmos/cosmos-sdk/x/distribution/types" - govtypes "github.com/cosmos/cosmos-sdk/x/gov/types" - govv1 "github.com/cosmos/cosmos-sdk/x/gov/types/v1" - minttypes "github.com/cosmos/cosmos-sdk/x/mint/types" - paramstypes "github.com/cosmos/cosmos-sdk/x/params/types" - slashingtypes "github.com/cosmos/cosmos-sdk/x/slashing/types" - stakingtypes "github.com/cosmos/cosmos-sdk/x/staking/types" ) // UpgradeName defines the on-chain upgrade name for the sample SimApp upgrade -// from v046 to v047. +// from v047 to v048. // // NOTE: This upgrade defines a reference implementation of what an upgrade // could look like when an application is migrating from Cosmos SDK version -// v0.46.x to v0.47.x. -const UpgradeName = "v046-to-v047" +// v0.47.x to v0.48.x. +const UpgradeName = "v047-to-v048" func (app SimApp) RegisterUpgradeHandlers() { - // Set param key table for params module migration - for _, subspace := range app.ParamsKeeper.GetSubspaces() { - subspace := subspace - - var keyTable paramstypes.KeyTable - switch subspace.Name() { - case authtypes.ModuleName: - keyTable = authtypes.ParamKeyTable() - case banktypes.ModuleName: - keyTable = banktypes.ParamKeyTable() - case stakingtypes.ModuleName: - keyTable = stakingtypes.ParamKeyTable() - case minttypes.ModuleName: - keyTable = minttypes.ParamKeyTable() - case distrtypes.ModuleName: - keyTable = distrtypes.ParamKeyTable() - case slashingtypes.ModuleName: - keyTable = slashingtypes.ParamKeyTable() - case govtypes.ModuleName: - keyTable = govv1.ParamKeyTable() //nolint:staticcheck // we still need this for upgrades - case crisistypes.ModuleName: - keyTable = crisistypes.ParamKeyTable() - } - - if !subspace.HasKeyTable() { - subspace.WithKeyTable(keyTable) - } - } - - baseAppLegacySS := app.ParamsKeeper.Subspace(baseapp.Paramspace).WithKeyTable(paramstypes.ConsensusParamsKeyTable()) - app.UpgradeKeeper.SetUpgradeHandler( UpgradeName, func(ctx sdk.Context, _ upgradetypes.Plan, fromVM module.VersionMap) (module.VersionMap, error) { - // Migrate CometBFT consensus parameters from x/params module to a dedicated x/consensus module. - baseapp.MigrateParams(ctx, baseAppLegacySS, &app.ConsensusParamsKeeper) - - // Note: this migration is optional, - // You can include x/gov proposal migration documented in [UPGRADING.md](https://github.com/cosmos/cosmos-sdk/blob/main/UPGRADING.md) - return app.ModuleManager.RunMigrations(ctx, app.Configurator(), fromVM) }, ) @@ -79,12 +30,7 @@ func (app SimApp) RegisterUpgradeHandlers() { } if upgradeInfo.Name == UpgradeName && !app.UpgradeKeeper.IsSkipHeight(upgradeInfo.Height) { - storeUpgrades := storetypes.StoreUpgrades{ - Added: []string{ - consensustypes.ModuleName, - crisistypes.ModuleName, - }, - } + storeUpgrades := storetypes.StoreUpgrades{} // configure store loader that checks if version == upgradeHeight and applies store upgrades app.SetStoreLoader(upgradetypes.UpgradeStoreLoader(upgradeInfo.Height, &storeUpgrades)) diff --git a/store/CHANGELOG.md b/store/CHANGELOG.md index c49c88668fea..4bf90b279233 100644 --- a/store/CHANGELOG.md +++ b/store/CHANGELOG.md @@ -25,13 +25,15 @@ Ref: https://keepachangelog.com/en/1.0.0/ ## [Unreleased] -## Features +### Features +- [#15712](https://github.com/cosmos/cosmos-sdk/pull/15712) Add `WorkingHash` function to the store interface to get the current app hash before commit. * [#14645](https://github.com/cosmos/cosmos-sdk/pull/14645) Add limit to the length of key and value. +* [#15683](https://github.com/cosmos/cosmos-sdk/pull/15683) `rootmulti.Store.CacheMultiStoreWithVersion` now can handle loading archival states that don't persist any of the module stores the current state has. ## [v0.1.0-alpha.1](https://github.com/cosmos/cosmos-sdk/releases/tag/store%2Fv0.1.0-alpha.1) - 2023-03-17 ### Features * [#14746](https://github.com/cosmos/cosmos-sdk/pull/14746) The `store` module is extracted to have a separate go.mod file which allows it be a standalone module. -* [#14410](https://github.com/cosmos/cosmos-sdk/pull/14410) `rootmulti.Store.loadVersion` has validation to check if all the module stores' height is correct, it will error if any module store has incorrect height. +* [#14410](https://github.com/cosmos/cosmos-sdk/pull/14410) `rootmulti.Store.loadVersion` has validation to check if all the module stores' height is correct, it will error if any module store has incorrect height. \ No newline at end of file diff --git a/store/cachekv/bench_helper_test.go b/store/cachekv/bench_helper_test.go index fe5be27fabc9..be7fec4b3a7b 100644 --- a/store/cachekv/bench_helper_test.go +++ b/store/cachekv/bench_helper_test.go @@ -34,7 +34,7 @@ func generateSequentialKeys(startKey []byte, numKeys int) [][]byte { } // Generate many random, unsorted keys -func generateRandomKeys(keySize int, numKeys int) [][]byte { +func generateRandomKeys(keySize, numKeys int) [][]byte { toReturn := make([][]byte, 0, numKeys) for i := 0; i < numKeys; i++ { newKey := randSlice(keySize) diff --git a/store/cachekv/internal/memiterator.go b/store/cachekv/internal/memiterator.go index 5ed37c1a52b5..77e7c1eea4f3 100644 --- a/store/cachekv/internal/memiterator.go +++ b/store/cachekv/internal/memiterator.go @@ -60,7 +60,7 @@ func newMemIterator(start, end []byte, items BTree, ascending bool) *memIterator return mi } -func (mi *memIterator) Domain() (start []byte, end []byte) { +func (mi *memIterator) Domain() (start, end []byte) { return mi.start, mi.end } diff --git a/store/cachekv/internal/mergeiterator.go b/store/cachekv/internal/mergeiterator.go index e4d80ab49118..58e9497b3028 100644 --- a/store/cachekv/internal/mergeiterator.go +++ b/store/cachekv/internal/mergeiterator.go @@ -24,7 +24,7 @@ type cacheMergeIterator struct { var _ types.Iterator = (*cacheMergeIterator)(nil) -func NewCacheMergeIterator(parent, cache types.Iterator, ascending bool) *cacheMergeIterator { //nolint:revive +func NewCacheMergeIterator(parent, cache types.Iterator, ascending bool) types.Iterator { iter := &cacheMergeIterator{ parent: parent, cache: cache, diff --git a/store/cachekv/store.go b/store/cachekv/store.go index 09b44ae57e4e..c2b1205243a9 100644 --- a/store/cachekv/store.go +++ b/store/cachekv/store.go @@ -68,7 +68,7 @@ func (store *Store) Get(key []byte) (value []byte) { } // Set implements types.KVStore. -func (store *Store) Set(key []byte, value []byte) { +func (store *Store) Set(key, value []byte) { types.AssertValidKey(key) types.AssertValidValue(value) diff --git a/store/gaskv/store.go b/store/gaskv/store.go index b7e2ddd70f53..e0f96af7151e 100644 --- a/store/gaskv/store.go +++ b/store/gaskv/store.go @@ -44,7 +44,7 @@ func (gs *Store) Get(key []byte) (value []byte) { } // Implements KVStore. -func (gs *Store) Set(key []byte, value []byte) { +func (gs *Store) Set(key, value []byte) { types.AssertValidKey(key) types.AssertValidValue(value) gs.gasMeter.ConsumeGas(gs.gasConfig.WriteCostFlat, types.GasWriteCostFlatDesc) @@ -121,7 +121,7 @@ func newGasIterator(gasMeter types.GasMeter, gasConfig types.GasConfig, parent t } // Implements Iterator. -func (gi *gasIterator) Domain() (start []byte, end []byte) { +func (gi *gasIterator) Domain() (start, end []byte) { return gi.parent.Domain() } diff --git a/store/go.mod b/store/go.mod index d41cae8356b9..3cc463bc8475 100644 --- a/store/go.mod +++ b/store/go.mod @@ -4,13 +4,13 @@ go 1.20 require ( cosmossdk.io/errors v1.0.0-beta.7 - cosmossdk.io/log v0.1.0 + cosmossdk.io/log v1.0.0 cosmossdk.io/math v1.0.0 github.com/armon/go-metrics v0.4.1 - github.com/cometbft/cometbft v0.37.0 + github.com/cometbft/cometbft v0.37.1-0.20230411132551-3a91d155e664 github.com/confio/ics23/go v0.9.0 github.com/cosmos/cosmos-db v1.0.0-rc.1 - github.com/cosmos/gogoproto v1.4.6 + github.com/cosmos/gogoproto v1.4.7 github.com/cosmos/iavl v0.21.0-beta.1 github.com/golang/mock v1.6.0 github.com/golang/protobuf v1.5.3 // indirect @@ -23,7 +23,7 @@ require ( golang.org/x/exp v0.0.0-20230321023759-10a507213a29 google.golang.org/genproto v0.0.0-20230320184635-7606e756e683 // indirect google.golang.org/grpc v1.54.0 - google.golang.org/protobuf v1.30.0 // indirect + google.golang.org/protobuf v1.30.0 gotest.tools/v3 v3.4.0 ) @@ -37,7 +37,7 @@ require ( github.com/cockroachdb/pebble v0.0.0-20230226194802-02d779ffbc46 // indirect github.com/cockroachdb/redact v1.1.3 // indirect github.com/davecgh/go-spew v1.1.1 // indirect - github.com/decred/dcrd/dcrec/secp256k1/v4 v4.1.0 // indirect + github.com/decred/dcrd/dcrec/secp256k1/v4 v4.2.0 // indirect github.com/fatih/color v1.15.0 // indirect github.com/fsnotify/fsnotify v1.6.0 // indirect github.com/getsentry/sentry-go v0.18.0 // indirect @@ -62,17 +62,17 @@ require ( github.com/petermattis/goid v0.0.0-20221215004737-a150e88a970d // indirect github.com/pkg/errors v0.9.1 // indirect github.com/pmezard/go-difflib v1.0.0 // indirect - github.com/prometheus/client_golang v1.14.0 // indirect + github.com/prometheus/client_golang v1.15.0 // indirect github.com/prometheus/client_model v0.3.0 // indirect github.com/prometheus/common v0.42.0 // indirect github.com/prometheus/procfs v0.9.0 // indirect github.com/rogpeppe/go-internal v1.9.0 // indirect - github.com/rs/zerolog v1.29.0 // indirect + github.com/rs/zerolog v1.29.1 // indirect github.com/sasha-s/go-deadlock v0.3.1 // indirect github.com/syndtr/goleveldb v1.0.1-0.20220721030215-126854af5e6d // indirect - golang.org/x/crypto v0.7.0 // indirect - golang.org/x/net v0.8.0 // indirect - golang.org/x/sys v0.6.0 // indirect - golang.org/x/text v0.8.0 // indirect + golang.org/x/crypto v0.8.0 // indirect + golang.org/x/net v0.9.0 // indirect + golang.org/x/sys v0.7.0 // indirect + golang.org/x/text v0.9.0 // indirect gopkg.in/yaml.v3 v3.0.1 // indirect ) diff --git a/store/go.sum b/store/go.sum index 298d75c733d2..c3bc5ae0c598 100644 --- a/store/go.sum +++ b/store/go.sum @@ -1,8 +1,8 @@ cloud.google.com/go v0.26.0/go.mod h1:aQUYkXzVsufM+DwF1aE+0xfcU+56JwCaLick0ClmMTw= cosmossdk.io/errors v1.0.0-beta.7 h1:gypHW76pTQGVnHKo6QBkb4yFOJjC+sUGRc5Al3Odj1w= cosmossdk.io/errors v1.0.0-beta.7/go.mod h1:mz6FQMJRku4bY7aqS/Gwfcmr/ue91roMEKAmDUDpBfE= -cosmossdk.io/log v0.1.0 h1:Vnexi+KzUCjmqq/m93teAxjt5biWFfZ5PI1imx2IJw8= -cosmossdk.io/log v0.1.0/go.mod h1:p95Wq6mDY3SREMc4y7+QU9Uwy3nyvfpWGD1iSaFkVFs= +cosmossdk.io/log v1.0.0 h1:NGKZ/A5rd4PduDfoscgABklX557PWjQINbosZy/m3Jk= +cosmossdk.io/log v1.0.0/go.mod h1:CwX9BLiBruZb7lzLlRr3R231d/fVPUXk8gAdV4LQap0= cosmossdk.io/math v1.0.0 h1:ro9w7eKx23om2tZz/VM2Pf+z2WAbGX1yDQQOJ6iGeJw= cosmossdk.io/math v1.0.0/go.mod h1:Ygz4wBHrgc7g0N+8+MrnTfS9LLn9aaTGa9hKopuym5k= github.com/AndreasBriese/bbloom v0.0.0-20190306092124-e2d15f34fcf9/go.mod h1:bOvUY6CB00SOBii9/FifXqc0awNKxLFCL/+pkDPuyl8= @@ -55,18 +55,18 @@ github.com/cockroachdb/pebble v0.0.0-20230226194802-02d779ffbc46/go.mod h1:9lRMC github.com/cockroachdb/redact v1.1.3 h1:AKZds10rFSIj7qADf0g46UixK8NNLwWTNdCIGS5wfSQ= github.com/cockroachdb/redact v1.1.3/go.mod h1:BVNblN9mBWFyMyqK1k3AAiSxhvhfK2oOZZ2lK+dpvRg= github.com/codegangsta/inject v0.0.0-20150114235600-33e0aa1cb7c0/go.mod h1:4Zcjuz89kmFXt9morQgcfYZAYZ5n8WHjt81YYWIwtTM= -github.com/cometbft/cometbft v0.37.0 h1:M005vBaSaugvYYmNZwJOopynQSjwLoDTwflnQ/I/eYk= -github.com/cometbft/cometbft v0.37.0/go.mod h1:Y2MMMN//O5K4YKd8ze4r9jmk4Y7h0ajqILXbH5JQFVs= +github.com/cometbft/cometbft v0.37.1-0.20230411132551-3a91d155e664 h1:BbCkbnaU3R603XpnbqvuDU8Kfv+hjhiFILOHhVFntsw= +github.com/cometbft/cometbft v0.37.1-0.20230411132551-3a91d155e664/go.mod h1:Y2MMMN//O5K4YKd8ze4r9jmk4Y7h0ajqILXbH5JQFVs= github.com/confio/ics23/go v0.9.0 h1:cWs+wdbS2KRPZezoaaj+qBleXgUk5WOQFMP3CQFGTr4= github.com/confio/ics23/go v0.9.0/go.mod h1:4LPZ2NYqnYIVRklaozjNR1FScgDJ2s5Xrp+e/mYVRak= github.com/coreos/etcd v3.3.10+incompatible/go.mod h1:uF7uidLiAD3TWHmW31ZFd/JWoc32PjwdhPthX9715RE= github.com/coreos/go-etcd v2.0.0+incompatible/go.mod h1:Jez6KQU2B/sWsbdaef3ED8NzMklzPG4d5KIOhIy30Tk= github.com/coreos/go-semver v0.2.0/go.mod h1:nnelYz7RCh+5ahJtPPxZlU+153eP4D4r3EedlOD2RNk= -github.com/coreos/go-systemd/v22 v22.3.3-0.20220203105225-a9a7ef127534/go.mod h1:Y58oyj3AT4RCenI/lSvhwexgC+NSVTIJ3seZv2GcEnc= +github.com/coreos/go-systemd/v22 v22.5.0/go.mod h1:Y58oyj3AT4RCenI/lSvhwexgC+NSVTIJ3seZv2GcEnc= github.com/cosmos/cosmos-db v1.0.0-rc.1 h1:SjnT8B6WKMW9WEIX32qMhnEEKcI7ZP0+G1Sa9HD3nmY= github.com/cosmos/cosmos-db v1.0.0-rc.1/go.mod h1:Dnmk3flSf5lkwCqvvjNpoxjpXzhxnCAFzKHlbaForso= -github.com/cosmos/gogoproto v1.4.6 h1:Ee7z15dWJaGlgM2rWrK8N2IX7PQcuccu8oG68jp5RL4= -github.com/cosmos/gogoproto v1.4.6/go.mod h1:VS/ASYmPgv6zkPKLjR9EB91lwbLHOzaGCirmKKhncfI= +github.com/cosmos/gogoproto v1.4.7 h1:RzYKVnsEC7UIkDnhTIkqEB7LnIQbsySvmNEqPCiPevk= +github.com/cosmos/gogoproto v1.4.7/go.mod h1:gxGePp9qedovvl/StQL2BIJ6qlIBn1+9YxR0IulGBKA= github.com/cosmos/iavl v0.21.0-beta.1 h1:fBQeBc8HLZ14plJNcmGfaOXSSMLVEHvEQXiTXSD76m0= github.com/cosmos/iavl v0.21.0-beta.1/go.mod h1:25YJYzilTErJ2mKfNB3xyWL9IsCwEQdNzdIutg2mh3U= github.com/cpuguy83/go-md2man v1.0.10/go.mod h1:SmD6nW6nTyfqj6ABTjUi3V3JVMnlJmwcJI5acqYI6dE= @@ -74,9 +74,9 @@ github.com/creack/pty v1.1.9/go.mod h1:oKZEueFk5CKHvIhNR5MUki03XCEU+Q6VDXinZuGJ3 github.com/davecgh/go-spew v1.1.0/go.mod h1:J7Y8YcW2NihsgmVo/mv3lAwl/skON4iLHjSsI+c5H38= github.com/davecgh/go-spew v1.1.1 h1:vj9j/u1bqnvCEfJOwUhtlOARqs3+rkHYY13jYWTU97c= github.com/davecgh/go-spew v1.1.1/go.mod h1:J7Y8YcW2NihsgmVo/mv3lAwl/skON4iLHjSsI+c5H38= -github.com/decred/dcrd/crypto/blake256 v1.0.0 h1:/8DMNYp9SGi5f0w7uCm6d6M4OU2rGFK09Y2A4Xv7EE0= -github.com/decred/dcrd/dcrec/secp256k1/v4 v4.1.0 h1:HbphB4TFFXpv7MNrT52FGrrgVXF1owhMVTHFZIlnvd4= -github.com/decred/dcrd/dcrec/secp256k1/v4 v4.1.0/go.mod h1:DZGJHZMqrU4JJqFAWUS2UO1+lbSKsdiOoYi9Zzey7Fc= +github.com/decred/dcrd/crypto/blake256 v1.0.1 h1:7PltbUIQB7u/FfZ39+DGa/ShuMyJ5ilcvdfma9wOH6Y= +github.com/decred/dcrd/dcrec/secp256k1/v4 v4.2.0 h1:8UrgZ3GkP4i/CLijOJx79Yu+etlyjdBU4sfcs2WYQMs= +github.com/decred/dcrd/dcrec/secp256k1/v4 v4.2.0/go.mod h1:v57UDF4pDQJcEfFUCRop3lJL149eHGSe9Jvczhzjo/0= github.com/dgraph-io/badger v1.6.0/go.mod h1:zwt7syl517jmP8s94KqSxTlM6IMsdhYy6psNgSztDR4= github.com/dgryski/go-farm v0.0.0-20190423205320-6a90982ecee2/go.mod h1:SqUrOPUnsFjfmXRMNPybcSiG0BgUW2AuFH8PAnS2iTw= github.com/dustin/go-humanize v1.0.0/go.mod h1:HtrtbFcZ19U5GC7JDqmcUSB87Iq5E25KnS6fMYU6eOk= @@ -297,8 +297,8 @@ github.com/pmezard/go-difflib v1.0.0/go.mod h1:iKH77koFhYxTK1pcRnkKkqfTogsbg7gZN github.com/prometheus/client_golang v0.9.1/go.mod h1:7SWBe2y4D6OKWSNQJUaRYU/AaXPKyh/dDVn+NZz0KFw= github.com/prometheus/client_golang v1.0.0/go.mod h1:db9x61etRT2tGnBNRi70OPL5FsnadC4Ky3P0J6CfImo= github.com/prometheus/client_golang v1.4.0/go.mod h1:e9GMxYsXl05ICDXkRhurwBS4Q3OK1iX/F2sw+iXX5zU= -github.com/prometheus/client_golang v1.14.0 h1:nJdhIvne2eSX/XRAFV9PcvFFRbrjbcTUj0VP62TMhnw= -github.com/prometheus/client_golang v1.14.0/go.mod h1:8vpkKitgIVNcqrRBWh1C4TIUQgYNtG/XQE4E/Zae36Y= +github.com/prometheus/client_golang v1.15.0 h1:5fCgGYogn0hFdhyhLbw7hEsWxufKtY9klyvdNfFlFhM= +github.com/prometheus/client_golang v1.15.0/go.mod h1:e9yaBhRPU2pPNsZwE+JdQl0KEt1N9XgF6zxWmaC0xOk= github.com/prometheus/client_model v0.0.0-20180712105110-5c3871d89910/go.mod h1:MbSGuTsp3dbXC40dX6PRTWyKYBIrTGTE9sqQNg2J8bo= github.com/prometheus/client_model v0.0.0-20190129233127-fd36f4220a90/go.mod h1:xMI15A0UPsDsEKsMN9yxemIoYk6Tm2C1GtYGdfGttqA= github.com/prometheus/client_model v0.0.0-20190812154241-14fe0d1b01d4/go.mod h1:xMI15A0UPsDsEKsMN9yxemIoYk6Tm2C1GtYGdfGttqA= @@ -319,8 +319,8 @@ github.com/rogpeppe/go-internal v1.8.1/go.mod h1:JeRgkft04UBgHMgCIwADu4Pn6Mtm5d4 github.com/rogpeppe/go-internal v1.9.0 h1:73kH8U+JUqXU8lRuOHeVHaa/SZPifC7BkcraZVejAe8= github.com/rogpeppe/go-internal v1.9.0/go.mod h1:WtVeX8xhTBvf0smdhujwtBcq4Qrzq/fJaraNFVN+nFs= github.com/rs/xid v1.4.0/go.mod h1:trrq9SKmegXys3aeAKXMUTdJsYXVwGY3RLcfgqegfbg= -github.com/rs/zerolog v1.29.0 h1:Zes4hju04hjbvkVkOhdl2HpZa+0PmVwigmo8XoORE5w= -github.com/rs/zerolog v1.29.0/go.mod h1:NILgTygv/Uej1ra5XxGf82ZFSLk58MFGAUS2o6usyD0= +github.com/rs/zerolog v1.29.1 h1:cO+d60CHkknCbvzEWxP0S9K6KqyTjrCNUy1LdQLCGPc= +github.com/rs/zerolog v1.29.1/go.mod h1:Le6ESbR7hc+DP6Lt1THiV8CQSdkkNrd3R0XbEgp3ZBU= github.com/russross/blackfriday v1.5.2/go.mod h1:JO/DiYxRf+HjHt06OyowR9PTA263kcR/rfWxYHBV53g= github.com/ryanuber/columnize v2.1.0+incompatible/go.mod h1:sm1tb6uqfes/u+d4ooFouqFdy9/2g9QGwK3SQygK0Ts= github.com/sasha-s/go-deadlock v0.3.1 h1:sqv7fDNShgjcaxkO0JNcOAlr8B9+cV5Ey/OB71efZx0= @@ -389,8 +389,8 @@ golang.org/x/crypto v0.0.0-20191227163750-53104e6ec876/go.mod h1:LzIPMQfyMNhhGPh golang.org/x/crypto v0.0.0-20200622213623-75b288015ac9/go.mod h1:LzIPMQfyMNhhGPhUkYOs5KpL4U8rLKemX1yGLhDgUto= golang.org/x/crypto v0.0.0-20210322153248-0c34fe9e7dc2/go.mod h1:T9bdIzuCu7OtxOm1hfPfRQxPLYneinmdGuTeoZ9dtd4= golang.org/x/crypto v0.0.0-20210921155107-089bfa567519/go.mod h1:GvvjBRRGRdwPK5ydBHafDWAxML/pGHZbMvKqRZ5+Abc= -golang.org/x/crypto v0.7.0 h1:AvwMYaRytfdeVt3u6mLaxYtErKYjxA2OXjJ1HHq6t3A= -golang.org/x/crypto v0.7.0/go.mod h1:pYwdfH91IfpZVANVyUOhSIPZaFoJGxTFbZhFTx+dXZU= +golang.org/x/crypto v0.8.0 h1:pd9TJtTueMTVQXzk8E2XESSMQDj/U7OUu0PqJqPXQjQ= +golang.org/x/crypto v0.8.0/go.mod h1:mRqEX+O9/h5TFCrQhkgjo2yKi0yYA+9ecGkdQoHrywE= golang.org/x/exp v0.0.0-20190121172915-509febef88a4/go.mod h1:CJ0aWSM057203Lf6IL+f9T1iT9GByDxfZKAQTCR3kQA= golang.org/x/exp v0.0.0-20230321023759-10a507213a29 h1:ooxPy7fPvB4kwsA2h+iBNHkAbp/4JxTSwCmvdjEYmug= golang.org/x/exp v0.0.0-20230321023759-10a507213a29/go.mod h1:CxIveKay+FTh1D0yPZemJVgC/95VzuuOLq5Qi4xnoYc= @@ -425,8 +425,8 @@ golang.org/x/net v0.0.0-20210428140749-89ef3d95e781/go.mod h1:OJAsFXCWl8Ukc7SiCT golang.org/x/net v0.0.0-20211008194852-3b03d305991f/go.mod h1:9nx3DQGgdP8bBQD5qxJ1jj9UTztislL4KSBs9R2vV5Y= golang.org/x/net v0.0.0-20220225172249-27dd8689420f/go.mod h1:CfG3xpIq0wQ8r1q4Su4UZFWDARRcnwPjda9FqA0JpMk= golang.org/x/net v0.0.0-20220607020251-c690dde0001d/go.mod h1:XRhObCWvk6IyKnWLug+ECip1KBveYUHfp+8e9klMJ9c= -golang.org/x/net v0.8.0 h1:Zrh2ngAOFYneWTAIAPethzeaQLuHwhuBkuV6ZiRnUaQ= -golang.org/x/net v0.8.0/go.mod h1:QVkue5JL9kW//ek3r6jTKnTFis1tRmNAW2P1shuFdJc= +golang.org/x/net v0.9.0 h1:aWJ/m6xSmxWBx+V0XRHTlrYrPG56jKsLdTFmsSsCzOM= +golang.org/x/net v0.9.0/go.mod h1:d48xBJpPfHeWQsugry2m+kC02ZBRGRgulfHnEXEuWns= golang.org/x/oauth2 v0.0.0-20180821212333-d2e6202438be/go.mod h1:N/0e6XlmueqKjAGxoOufVs8QHGRruUQn6yWY3a++T0U= golang.org/x/sync v0.0.0-20180314180146-1d60e4601c6f/go.mod h1:RxMgew5VJxzue5/jJTE5uejpjVlOe/izrB70Jof72aM= golang.org/x/sync v0.0.0-20181108010431-42b317875d0f/go.mod h1:RxMgew5VJxzue5/jJTE5uejpjVlOe/izrB70Jof72aM= @@ -475,8 +475,9 @@ golang.org/x/sys v0.0.0-20220503163025-988cb79eb6c6/go.mod h1:oPkhp1MJrh7nUepCBc golang.org/x/sys v0.0.0-20220520151302-bc2c85ada10a/go.mod h1:oPkhp1MJrh7nUepCBck5+mAzfO9JrbApNNgaTdGDITg= golang.org/x/sys v0.0.0-20220811171246-fbc7d0a398ab/go.mod h1:oPkhp1MJrh7nUepCBck5+mAzfO9JrbApNNgaTdGDITg= golang.org/x/sys v0.0.0-20220908164124-27713097b956/go.mod h1:oPkhp1MJrh7nUepCBck5+mAzfO9JrbApNNgaTdGDITg= -golang.org/x/sys v0.6.0 h1:MVltZSvRTcU2ljQOhs94SXPftV6DCNnZViHeQps87pQ= golang.org/x/sys v0.6.0/go.mod h1:oPkhp1MJrh7nUepCBck5+mAzfO9JrbApNNgaTdGDITg= +golang.org/x/sys v0.7.0 h1:3jlCCIQZPdOYu1h8BkNvLz8Kgwtae2cagcG/VamtZRU= +golang.org/x/sys v0.7.0/go.mod h1:oPkhp1MJrh7nUepCBck5+mAzfO9JrbApNNgaTdGDITg= golang.org/x/term v0.0.0-20201126162022-7de9c90e9dd1/go.mod h1:bj7SfCRtBDWHUb9snDiAeCFNEtKQo2Wmx5Cou7ajbmo= golang.org/x/term v0.0.0-20210927222741-03fcf44c2211/go.mod h1:jbD1KX2456YbFQfuXm/mYQcufACuNUgVhRMnK/tPxf8= golang.org/x/text v0.3.0/go.mod h1:NqM8EUOU14njkJ3fqMW+pc6Ldnwhi/IjpwHt7yyuwOQ= @@ -485,8 +486,8 @@ golang.org/x/text v0.3.3/go.mod h1:5Zoc/QRtKVWzQhOtBMvqHzDpF6irO9z98xDceosuGiQ= golang.org/x/text v0.3.5/go.mod h1:5Zoc/QRtKVWzQhOtBMvqHzDpF6irO9z98xDceosuGiQ= golang.org/x/text v0.3.6/go.mod h1:5Zoc/QRtKVWzQhOtBMvqHzDpF6irO9z98xDceosuGiQ= golang.org/x/text v0.3.7/go.mod h1:u+2+/6zg+i71rQMx5EYifcz6MCKuco9NR6JIITiCfzQ= -golang.org/x/text v0.8.0 h1:57P1ETyNKtuIjB4SRd15iJxuhj8Gc416Y78H3qgMh68= -golang.org/x/text v0.8.0/go.mod h1:e1OnstbJyHTd6l/uOt8jFFHp6TRDWZR/bV3emEE/zU8= +golang.org/x/text v0.9.0 h1:2sjJmO8cDvYveuX97RDLsxlyUxLl+GHoLxBiRdHllBE= +golang.org/x/text v0.9.0/go.mod h1:e1OnstbJyHTd6l/uOt8jFFHp6TRDWZR/bV3emEE/zU8= golang.org/x/time v0.0.0-20201208040808-7e3f01d25324/go.mod h1:tRJNPiyCQ0inRvYxbN9jk5I+vvW/OXSQhTDSoE431IQ= golang.org/x/tools v0.0.0-20180917221912-90fa682c2a6e/go.mod h1:n7NCudcB/nEzxVGmLbDWY5pfWTLqBcC2KZ6jyYvM4mQ= golang.org/x/tools v0.0.0-20181221001348-537d06c36207/go.mod h1:n7NCudcB/nEzxVGmLbDWY5pfWTLqBcC2KZ6jyYvM4mQ= diff --git a/store/iavl/store.go b/store/iavl/store.go index aae3eeaa410f..b016db51a080 100644 --- a/store/iavl/store.go +++ b/store/iavl/store.go @@ -143,6 +143,16 @@ func (st *Store) Commit() types.CommitID { } } +// WorkingHash returns the hash of the current working tree. +func (st *Store) WorkingHash() []byte { + hash, err := st.tree.WorkingHash() + if err != nil { + panic(fmt.Errorf("failed to retrieve working hash: %w", err)) + } + + return hash +} + // LastCommitID implements Committer. func (st *Store) LastCommitID() types.CommitID { hash, err := st.tree.Hash() diff --git a/store/iavl/store_test.go b/store/iavl/store_test.go index a29f6c30fb76..09461365598e 100644 --- a/store/iavl/store_test.go +++ b/store/iavl/store_test.go @@ -293,7 +293,7 @@ func TestIAVLReverseIterator(t *testing.T) { iavlStore.Set([]byte{0x00, 0x02}, []byte("0 2")) iavlStore.Set([]byte{0x01}, []byte("1")) - testReverseIterator := func(t *testing.T, start []byte, end []byte, expected []string) { + testReverseIterator := func(t *testing.T, start, end []byte, expected []string) { iter := iavlStore.ReverseIterator(start, end) var i int for i = 0; iter.Valid(); iter.Next() { diff --git a/store/iavl/tree.go b/store/iavl/tree.go index 77762e1dfbd0..e0581a856aa5 100644 --- a/store/iavl/tree.go +++ b/store/iavl/tree.go @@ -27,6 +27,7 @@ type ( DeleteVersions(versions ...int64) error Version() int64 Hash() ([]byte, error) + WorkingHash() ([]byte, error) VersionExists(version int64) bool GetVersioned(key []byte, version int64) ([]byte, error) GetImmutable(version int64) (*iavl.ImmutableTree, error) @@ -101,3 +102,7 @@ func (it *immutableTree) LoadVersionForOverwriting(targetVersion int64) (int64, func (it *immutableTree) LazyLoadVersionForOverwriting(targetVersion int64) (int64, error) { panic("cannot call 'LazyLoadVersionForOverwriting' on an immutable IAVL tree") } + +func (it *immutableTree) WorkingHash() ([]byte, error) { + panic("cannot call 'WorkingHash' on an immutable IAVL tree") +} diff --git a/store/iavl/tree_test.go b/store/iavl/tree_test.go index fa0412961656..c03e9518c74f 100644 --- a/store/iavl/tree_test.go +++ b/store/iavl/tree_test.go @@ -14,8 +14,8 @@ func TestImmutableTreePanics(t *testing.T) { it := &immutableTree{immTree} require.Panics(t, func() { it.Set([]byte{}, []byte{}) }) require.Panics(t, func() { it.Remove([]byte{}) }) - require.Panics(t, func() { it.SaveVersion() }) //nolint:errcheck - require.Panics(t, func() { it.DeleteVersion(int64(1)) }) //nolint:errcheck + require.Panics(t, func() { _, _, _ = it.SaveVersion() }) + require.Panics(t, func() { _ = it.DeleteVersion(int64(1)) }) imm, err := it.GetImmutable(1) require.Error(t, err) diff --git a/store/internal/conv/string_test.go b/store/internal/conv/string_test.go index 3e051d37b907..3a1451753188 100644 --- a/store/internal/conv/string_test.go +++ b/store/internal/conv/string_test.go @@ -26,7 +26,7 @@ func (s *StringSuite) TestUnsafeStrToBytes() { b := unsafeConvertStr() runtime.GC() <-time.NewTimer(2 * time.Millisecond).C - b2 := append(b, 'd') //nolint:gocritic // append is fine here + b2 := append(b, 'd') s.Equal("abc", string(b)) s.Equal("abcd", string(b2)) } diff --git a/store/listenkv/store.go b/store/listenkv/store.go index 27cbe1cbcdf0..b08a6e395071 100644 --- a/store/listenkv/store.go +++ b/store/listenkv/store.go @@ -32,7 +32,7 @@ func (s *Store) Get(key []byte) []byte { // Set implements the KVStore interface. It traces a write operation and // delegates the Set call to the parent KVStore. -func (s *Store) Set(key []byte, value []byte) { +func (s *Store) Set(key, value []byte) { types.AssertValidKey(key) s.parent.Set(key, value) s.listener.OnWrite(s.parentStoreKey, key, value, false) @@ -87,7 +87,7 @@ func newTraceIterator(parent types.Iterator, listener *types.MemoryListener) typ } // Domain implements the Iterator interface. -func (li *listenIterator) Domain() (start []byte, end []byte) { +func (li *listenIterator) Domain() (start, end []byte) { return li.parent.Domain() } diff --git a/store/mem/store.go b/store/mem/store.go index ce83089f7073..b819d7536302 100644 --- a/store/mem/store.go +++ b/store/mem/store.go @@ -27,7 +27,7 @@ func NewStore() *Store { return NewStoreWithDB(dbm.NewMemDB()) } -func NewStoreWithDB(db *dbm.MemDB) *Store { //nolint: interfacer +func NewStoreWithDB(db *dbm.MemDB) *Store { //nolint: interfacer // Concrete return type is fine here. return &Store{Store: dbadapter.Store{DB: db}} } @@ -58,3 +58,5 @@ func (s *Store) GetPruning() pruningtypes.PruningOptions { } func (s Store) LastCommitID() (id types.CommitID) { return } + +func (s Store) WorkingHash() (hash []byte) { return } diff --git a/store/prefix/store.go b/store/prefix/store.go index b881e71907e6..32b9e8247e2c 100644 --- a/store/prefix/store.go +++ b/store/prefix/store.go @@ -27,7 +27,7 @@ func NewStore(parent types.KVStore, prefix []byte) Store { } } -func cloneAppend(bz []byte, tail []byte) (res []byte) { +func cloneAppend(bz, tail []byte) (res []byte) { res = make([]byte, len(bz)+len(tail)) copy(res, bz) copy(res[len(bz):], tail) @@ -193,7 +193,7 @@ func (pi *prefixIterator) Error() error { } // copied from github.com/cometbft/cometbft/libs/db/prefix_db.go -func stripPrefix(key []byte, prefix []byte) []byte { +func stripPrefix(key, prefix []byte) []byte { if len(key) < len(prefix) || !bytes.Equal(key[:len(prefix)], prefix) { panic("should not happen") } diff --git a/store/prefix/store_test.go b/store/prefix/store_test.go index 127828c47dde..20df25254485 100644 --- a/store/prefix/store_test.go +++ b/store/prefix/store_test.go @@ -253,7 +253,7 @@ func mockStoreWithStuff() types.KVStore { return store } -func checkValue(t *testing.T, store types.KVStore, key []byte, expected []byte) { +func checkValue(t *testing.T, store types.KVStore, key, expected []byte) { bz := store.Get(key) require.Equal(t, expected, bz) } diff --git a/store/rootmulti/dbadapter.go b/store/rootmulti/dbadapter.go index 027359a0a578..4f32ada4e9ff 100644 --- a/store/rootmulti/dbadapter.go +++ b/store/rootmulti/dbadapter.go @@ -9,6 +9,11 @@ import ( var commithash = []byte("FAKE_HASH") +var ( + _ types.KVStore = (*commitDBStoreAdapter)(nil) + _ types.Committer = (*commitDBStoreAdapter)(nil) +) + //---------------------------------------- // commitDBStoreWrapper should only be used for simulation/debugging, // as it doesn't compute any commit hash, and it cannot load older state. @@ -32,6 +37,10 @@ func (cdsa commitDBStoreAdapter) LastCommitID() types.CommitID { } } +func (cdsa commitDBStoreAdapter) WorkingHash() []byte { + return commithash +} + func (cdsa commitDBStoreAdapter) SetPruning(_ pruningtypes.PruningOptions) {} // GetPruning is a no-op as pruning options cannot be directly set on this store. diff --git a/store/rootmulti/store.go b/store/rootmulti/store.go index f54a30dbb543..d057fcf5b23f 100644 --- a/store/rootmulti/store.go +++ b/store/rootmulti/store.go @@ -11,6 +11,7 @@ import ( "cosmossdk.io/log" abci "github.com/cometbft/cometbft/abci/types" + cmtproto "github.com/cometbft/cometbft/proto/tendermint/types" dbm "github.com/cosmos/cosmos-db" protoio "github.com/cosmos/gogoproto/io" gogotypes "github.com/cosmos/gogoproto/types" @@ -67,16 +68,13 @@ type Store struct { lazyLoading bool initialVersion int64 removalMap map[types.StoreKey]bool - - traceWriter io.Writer - traceContext types.TraceContext - traceContextMutex sync.Mutex - - interBlockCache types.MultiStorePersistentCache - - listeners map[types.StoreKey]*types.MemoryListener - - metrics metrics.StoreMetrics + traceWriter io.Writer + traceContext types.TraceContext + traceContextMutex sync.Mutex + interBlockCache types.MultiStorePersistentCache + listeners map[types.StoreKey]*types.MemoryListener + metrics metrics.StoreMetrics + commitHeader cmtproto.Header } var ( @@ -217,7 +215,7 @@ func (rs *Store) loadVersion(ver int64, upgrades *types.StoreUpgrades) error { // load old data if we are not version 0 if ver != 0 { var err error - cInfo, err = getCommitInfo(rs.db, ver) + cInfo, err = rs.GetCommitInfo(ver) if err != nil { return err } @@ -332,7 +330,7 @@ func deleteKVStore(kv types.KVStore) error { } // we simulate move by a copy and delete -func moveKVStoreData(oldDB types.KVStore, newDB types.KVStore) error { +func moveKVStoreData(oldDB, newDB types.KVStore) error { // we read from one and write to another itr := oldDB.Iterator(nil, nil) for itr.Valid() { @@ -469,7 +467,12 @@ func (rs *Store) Commit() types.CommitID { version = previousHeight + 1 } + if rs.commitHeader.Height != version { + rs.logger.Debug("commit header and version mismatch", "header_height", rs.commitHeader.Height, "version", version) + } + rs.lastCommitInfo = commitStores(version, rs.stores, rs.removalMap) + rs.lastCommitInfo.Timestamp = rs.commitHeader.Time defer rs.flushMetadata(rs.db, version, rs.lastCommitInfo) // remove remnants of removed stores @@ -480,6 +483,7 @@ func (rs *Store) Commit() types.CommitID { delete(rs.keysByName, sk.Name()) } } + // reset the removalMap rs.removalMap = make(map[types.StoreKey]bool) @@ -493,6 +497,37 @@ func (rs *Store) Commit() types.CommitID { } } +// WorkingHash returns the current hash of the store. +// it will be used to get the current app hash before commit. +func (rs *Store) WorkingHash() []byte { + storeInfos := make([]types.StoreInfo, 0, len(rs.stores)) + storeKeys := keysFromStoreKeyMap(rs.stores) + + for _, key := range storeKeys { + store := rs.stores[key] + + if store.GetStoreType() != types.StoreTypeIAVL { + continue + } + + if !rs.removalMap[key] { + si := types.StoreInfo{ + Name: key.Name(), + CommitId: types.CommitID{ + Hash: store.WorkingHash(), + }, + } + storeInfos = append(storeInfos, si) + } + } + + sort.SliceStable(storeInfos, func(i, j int) bool { + return storeInfos[i].Name < storeInfos[j].Name + }) + + return types.CommitInfo{StoreInfos: storeInfos}.Hash() +} + // CacheWrap implements CacheWrapper/Store/CommitStore. func (rs *Store) CacheWrap() types.CacheWrap { return rs.CacheMultiStore().(types.CacheWrap) @@ -525,6 +560,8 @@ func (rs *Store) CacheMultiStore() types.CacheMultiStore { // iterating at past heights. func (rs *Store) CacheMultiStoreWithVersion(version int64) (types.CacheMultiStore, error) { cachedStores := make(map[types.StoreKey]types.CacheWrapper) + var commitInfo *types.CommitInfo + storeInfos := map[string]bool{} for key, store := range rs.stores { var cacheStore types.KVStore switch store.GetStoreType() { @@ -537,9 +574,30 @@ func (rs *Store) CacheMultiStoreWithVersion(version int64) (types.CacheMultiStor // version does not exist or is pruned, an error should be returned. var err error cacheStore, err = store.(*iavl.Store).GetImmutable(version) + // if we got error from loading a module store + // we fetch commit info of this version + // we use commit info to check if the store existed at this version or not if err != nil { - return nil, err + if commitInfo == nil { + var errCommitInfo error + commitInfo, errCommitInfo = rs.GetCommitInfo(version) + + if errCommitInfo != nil { + return nil, errCommitInfo + } + + for _, storeInfo := range commitInfo.StoreInfos { + storeInfos[storeInfo.Name] = true + } + } + + // If the store existed at this version, it means there's actually an error + // getting the root store at this version. + if storeInfos[key.Name()] { + return nil, err + } } + default: cacheStore = store } @@ -705,7 +763,7 @@ func (rs *Store) Query(req abci.RequestQuery) abci.ResponseQuery { if res.Height == rs.lastCommitInfo.Version { commitInfo = rs.lastCommitInfo } else { - commitInfo, err = getCommitInfo(rs.db, res.Height) + commitInfo, err = rs.GetCommitInfo(res.Height) if err != nil { return types.QueryResult(err, false) } @@ -739,7 +797,7 @@ func (rs *Store) SetInitialVersion(version int64) error { // parsePath expects a format like /[/] // Must start with /, subpath may be empty // Returns error if it doesn't start with / -func parsePath(path string) (storeName string, subpath string, err error) { +func parsePath(path string) (storeName, subpath string, err error) { if !strings.HasPrefix(path, "/") { return storeName, subpath, errorsmod.Wrapf(types.ErrUnknownRequest, "invalid path: %s", path) } @@ -823,7 +881,6 @@ func (rs *Store) Snapshot(height uint64, protoWriter protoio.Writer) error { node, err := exporter.Next() if err == iavltree.ErrorExportDone { rs.logger.Debug("snapshot Done", "store", store.name, "nodeCount", nodeCount) - nodeCount = 0 break } else if err != nil { return err @@ -1048,6 +1105,32 @@ func (rs *Store) RollbackToVersion(target int64) error { return rs.LoadLatestVersion() } +// SetCommitHeader sets the commit block header of the store. +func (rs *Store) SetCommitHeader(h cmtproto.Header) { + rs.commitHeader = h +} + +// GetCommitInfo attempts to retrieve CommitInfo for a given version/height. It +// will return an error if no CommitInfo exists, we fail to unmarshal the record +// or if we cannot retrieve the object from the DB. +func (rs *Store) GetCommitInfo(ver int64) (*types.CommitInfo, error) { + cInfoKey := fmt.Sprintf(commitInfoKeyFmt, ver) + + bz, err := rs.db.Get([]byte(cInfoKey)) + if err != nil { + return nil, errorsmod.Wrap(err, "failed to get commit info") + } else if bz == nil { + return nil, errors.New("no commit info found") + } + + cInfo := &types.CommitInfo{} + if err = cInfo.Unmarshal(bz); err != nil { + return nil, errorsmod.Wrap(err, "failed unmarshal commit info") + } + + return cInfo, nil +} + func (rs *Store) flushMetadata(db dbm.DB, version int64, cInfo *types.CommitInfo) { rs.logger.Debug("flushing metadata", "height", version) batch := db.NewBatch() @@ -1074,7 +1157,7 @@ type storeParams struct { initialVersion uint64 } -func newStoreParams(key types.StoreKey, db dbm.DB, typ types.StoreType, initialVersion uint64) storeParams { // nolint +func newStoreParams(key types.StoreKey, db dbm.DB, typ types.StoreType, initialVersion uint64) storeParams { return storeParams{ key: key, db: db, @@ -1143,25 +1226,6 @@ func commitStores(version int64, storeMap map[types.StoreKey]types.CommitKVStore } } -// Gets commitInfo from disk. -func getCommitInfo(db dbm.DB, ver int64) (*types.CommitInfo, error) { - cInfoKey := fmt.Sprintf(commitInfoKeyFmt, ver) - - bz, err := db.Get([]byte(cInfoKey)) - if err != nil { - return nil, errorsmod.Wrap(err, "failed to get commit info") - } else if bz == nil { - return nil, errors.New("no commit info found") - } - - cInfo := &types.CommitInfo{} - if err = cInfo.Unmarshal(bz); err != nil { - return nil, errorsmod.Wrap(err, "failed unmarshal commit info") - } - - return cInfo, nil -} - func flushCommitInfo(batch dbm.Batch, version int64, cInfo *types.CommitInfo) { bz, err := cInfo.Marshal() if err != nil { diff --git a/store/rootmulti/store_test.go b/store/rootmulti/store_test.go index 4beaa73af630..e55687f363ae 100644 --- a/store/rootmulti/store_test.go +++ b/store/rootmulti/store_test.go @@ -96,6 +96,17 @@ func TestCacheMultiStoreWithVersion(t *testing.T) { require.NotNil(t, kvStore) require.Equal(t, kvStore.Get(k), v) + // add new module stores (store4 and store5) to multi stores and commit + ms.MountStoreWithDB(types.NewKVStoreKey("store4"), types.StoreTypeIAVL, nil) + ms.MountStoreWithDB(types.NewKVStoreKey("store5"), types.StoreTypeIAVL, nil) + err = ms.LoadLatestVersionAndUpgrade(&types.StoreUpgrades{Added: []string{"store4", "store5"}}) + require.NoError(t, err) + ms.Commit() + + // cache multistore of version before adding store4 should works + _, err = ms.CacheMultiStoreWithVersion(1) + require.NoError(t, err) + // require we cannot commit (write) to a cache-versioned multi-store require.Panics(t, func() { kvStore.Set(k, []byte("newValue")) @@ -117,12 +128,16 @@ func TestHashStableWithEmptyCommit(t *testing.T) { store1 := ms.GetStoreByName("store1").(types.KVStore) store1.Set(k, v) + workingHash := ms.WorkingHash() cID := ms.Commit() require.Equal(t, int64(1), cID.Version) hash := cID.Hash + require.Equal(t, workingHash, hash) // make an empty commit, it should update version, but not affect hash + workingHash = ms.WorkingHash() cID = ms.Commit() + require.Equal(t, workingHash, cID.Hash) require.Equal(t, int64(2), cID.Version) require.Equal(t, hash, cID.Hash) } @@ -148,7 +163,9 @@ func TestMultistoreCommitLoad(t *testing.T) { // Make a few commits and check them. nCommits := int64(3) for i := int64(0); i < nCommits; i++ { + workingHash := store.WorkingHash() commitID = store.Commit() + require.Equal(t, workingHash, commitID.Hash) expectedCommitID := getExpectedCommitID(store, i+1) checkStore(t, store, expectedCommitID, commitID) } @@ -161,7 +178,9 @@ func TestMultistoreCommitLoad(t *testing.T) { checkStore(t, store, commitID, commitID) // Commit and check version. + workingHash := store.WorkingHash() commitID = store.Commit() + require.Equal(t, workingHash, commitID.Hash) expectedCommitID := getExpectedCommitID(store, nCommits+1) checkStore(t, store, expectedCommitID, commitID) @@ -200,11 +219,13 @@ func TestMultistoreLoadWithUpgrade(t *testing.T) { require.Nil(t, s4) // do one commit + workingHash := store.WorkingHash() commitID := store.Commit() + require.Equal(t, workingHash, commitID.Hash) expectedCommitID := getExpectedCommitID(store, 1) checkStore(t, store, expectedCommitID, commitID) - ci, err := getCommitInfo(db, 1) + ci, err := store.GetCommitInfo(1) require.NoError(t, err) require.Equal(t, int64(1), ci.Version) require.Equal(t, 3, len(ci.StoreInfos)) @@ -294,7 +315,7 @@ func TestMultistoreLoadWithUpgrade(t *testing.T) { require.Equal(t, v4, rl4.Get(k4)) // check commitInfo in storage - ci, err = getCommitInfo(db, 2) + ci, err = reload.GetCommitInfo(2) require.NoError(t, err) require.Equal(t, int64(2), ci.Version) require.Equal(t, 3, len(ci.StoreInfos), ci.StoreInfos) @@ -349,7 +370,7 @@ func TestMultiStoreRestart(t *testing.T) { multi.Commit() - cinfo, err := getCommitInfo(multi.db, int64(i)) + cinfo, err := multi.GetCommitInfo(int64(i)) require.NoError(t, err) require.Equal(t, int64(i), cinfo.Version) } @@ -364,7 +385,7 @@ func TestMultiStoreRestart(t *testing.T) { multi.Commit() - flushedCinfo, err := getCommitInfo(multi.db, 3) + flushedCinfo, err := multi.GetCommitInfo(3) require.Nil(t, err) require.NotEqual(t, initCid, flushedCinfo, "CID is different after flush to disk") @@ -374,7 +395,7 @@ func TestMultiStoreRestart(t *testing.T) { multi.Commit() - postFlushCinfo, err := getCommitInfo(multi.db, 4) + postFlushCinfo, err := multi.GetCommitInfo(4) require.NoError(t, err) require.Equal(t, int64(4), postFlushCinfo.Version, "Commit changed after in-memory commit") @@ -757,7 +778,7 @@ func TestCommitOrdered(t *testing.T) { typeID := multi.Commit() require.Equal(t, int64(1), typeID.Version) - ci, err := getCommitInfo(db, 1) + ci, err := multi.GetCommitInfo(1) require.NoError(t, err) require.Equal(t, int64(1), ci.Version) require.Equal(t, 3, len(ci.StoreInfos)) @@ -860,7 +881,7 @@ type MockListener struct { stateCache []types.StoreKVPair } -func (tl *MockListener) OnWrite(storeKey types.StoreKey, key []byte, value []byte, delete bool) error { +func (tl *MockListener) OnWrite(storeKey types.StoreKey, key, value []byte, delete bool) error { tl.stateCache = append(tl.stateCache, types.StoreKVPair{ StoreKey: storeKey.Name(), Key: key, diff --git a/store/snapshots/helpers_test.go b/store/snapshots/helpers_test.go index 3472af60684b..0cb307642a0c 100644 --- a/store/snapshots/helpers_test.go +++ b/store/snapshots/helpers_test.go @@ -181,13 +181,24 @@ func setupBusyManager(t *testing.T) *snapshots.Manager { mgr := snapshots.NewManager(store, opts, hung, nil, log.NewNopLogger()) require.Equal(t, opts.Interval, hung.snapshotInterval) + // Channel to ensure the test doesn't finish until the goroutine is done. + // Without this, there are intermittent test failures about + // the t.TempDir() cleanup failing due to the directory not being empty. + done := make(chan struct{}) + go func() { + defer close(done) _, err := mgr.Create(1) require.NoError(t, err) _, didPruneHeight := hung.prunedHeights[1] require.True(t, didPruneHeight) }() time.Sleep(10 * time.Millisecond) + + t.Cleanup(func() { + <-done + }) + t.Cleanup(hung.Close) return mgr diff --git a/store/snapshots/manager.go b/store/snapshots/manager.go index bacffe5f6f52..90e980d4d016 100644 --- a/store/snapshots/manager.go +++ b/store/snapshots/manager.go @@ -236,7 +236,7 @@ func (m *Manager) List() ([]*types.Snapshot, error) { // LoadChunk loads a chunk into a byte slice, mirroring ABCI LoadChunk. It can be called // concurrently with other operations. If the chunk does not exist, nil is returned. -func (m *Manager) LoadChunk(height uint64, format uint32, chunk uint32) ([]byte, error) { +func (m *Manager) LoadChunk(height uint64, format, chunk uint32) ([]byte, error) { reader, err := m.store.LoadChunk(height, format, chunk) if err != nil { return nil, err diff --git a/store/snapshots/store.go b/store/snapshots/store.go index c0db328bffec..91629eaaa148 100644 --- a/store/snapshots/store.go +++ b/store/snapshots/store.go @@ -166,7 +166,7 @@ func (s *Store) Load(height uint64, format uint32) (*types.Snapshot, <-chan io.R // LoadChunk loads a chunk from disk, or returns nil if it does not exist. The caller must call // Close() on it when done. -func (s *Store) LoadChunk(height uint64, format uint32, chunk uint32) (io.ReadCloser, error) { +func (s *Store) LoadChunk(height uint64, format, chunk uint32) (io.ReadCloser, error) { path := s.pathChunk(height, format, chunk) file, err := os.Open(path) if os.IsNotExist(err) { @@ -176,7 +176,7 @@ func (s *Store) LoadChunk(height uint64, format uint32, chunk uint32) (io.ReadCl } // loadChunkFile loads a chunk from disk, and errors if it does not exist. -func (s *Store) loadChunkFile(height uint64, format uint32, chunk uint32) (io.ReadCloser, error) { +func (s *Store) loadChunkFile(height uint64, format, chunk uint32) (io.ReadCloser, error) { path := s.pathChunk(height, format, chunk) return os.Open(path) } @@ -336,7 +336,7 @@ func (s *Store) pathSnapshot(height uint64, format uint32) string { } // pathChunk generates a snapshot chunk path. -func (s *Store) pathChunk(height uint64, format uint32, chunk uint32) string { +func (s *Store) pathChunk(height uint64, format, chunk uint32) string { return filepath.Join(s.pathSnapshot(height, format), strconv.FormatUint(uint64(chunk), 10)) } diff --git a/store/streaming/streaming.go b/store/streaming/streaming.go index 212651343217..f553fd16a45e 100644 --- a/store/streaming/streaming.go +++ b/store/streaming/streaming.go @@ -28,7 +28,7 @@ func GetPluginEnvKey(name string) string { return fmt.Sprintf("%s_%s", pluginEnvKeyPrefix, strings.ToUpper(name)) } -func NewStreamingPlugin(name string, logLevel string) (interface{}, error) { +func NewStreamingPlugin(name, logLevel string) (interface{}, error) { logger := hclog.New(&hclog.LoggerOptions{ Output: hclog.DefaultOutput, Level: toHclogLevel(logLevel), diff --git a/store/tracekv/store.go b/store/tracekv/store.go index 9895d8ec410b..9ab124aa0e48 100644 --- a/store/tracekv/store.go +++ b/store/tracekv/store.go @@ -60,7 +60,7 @@ func (tkv *Store) Get(key []byte) []byte { // Set implements the KVStore interface. It traces a write operation and // delegates the Set call to the parent KVStore. -func (tkv *Store) Set(key []byte, value []byte) { +func (tkv *Store) Set(key, value []byte) { types.AssertValidKey(key) writeOperation(tkv.writer, writeOp, tkv.context, key, value) tkv.parent.Set(key, value) @@ -116,7 +116,7 @@ func newTraceIterator(w io.Writer, parent types.Iterator, tc types.TraceContext) } // Domain implements the Iterator interface. -func (ti *traceIterator) Domain() (start []byte, end []byte) { +func (ti *traceIterator) Domain() (start, end []byte) { return ti.parent.Domain() } diff --git a/store/transient/store.go b/store/transient/store.go index f0ec6cef7e1d..6f393279f571 100644 --- a/store/transient/store.go +++ b/store/transient/store.go @@ -39,8 +39,12 @@ func (ts *Store) GetPruning() pruningtypes.PruningOptions { } // Implements CommitStore -func (ts *Store) LastCommitID() (id types.CommitID) { - return +func (ts *Store) LastCommitID() types.CommitID { + return types.CommitID{} +} + +func (ts *Store) WorkingHash() []byte { + return []byte{} } // Implements Store. diff --git a/store/types/commit_info.pb.go b/store/types/commit_info.pb.go index 813a7c4fcf06..81220a79c236 100644 --- a/store/types/commit_info.pb.go +++ b/store/types/commit_info.pb.go @@ -7,15 +7,19 @@ import ( fmt "fmt" _ "github.com/cosmos/gogoproto/gogoproto" proto "github.com/cosmos/gogoproto/proto" + github_com_cosmos_gogoproto_types "github.com/cosmos/gogoproto/types" + _ "google.golang.org/protobuf/types/known/timestamppb" io "io" math "math" math_bits "math/bits" + time "time" ) // Reference imports to suppress errors if they are not otherwise used. var _ = proto.Marshal var _ = fmt.Errorf var _ = math.Inf +var _ = time.Kitchen // This is a compile-time assertion to ensure that this generated file // is compatible with the proto package it is being compiled against. @@ -28,6 +32,7 @@ const _ = proto.GoGoProtoPackageIsVersion3 // please upgrade the proto package type CommitInfo struct { Version int64 `protobuf:"varint,1,opt,name=version,proto3" json:"version,omitempty"` StoreInfos []StoreInfo `protobuf:"bytes,2,rep,name=store_infos,json=storeInfos,proto3" json:"store_infos"` + Timestamp time.Time `protobuf:"bytes,3,opt,name=timestamp,proto3,stdtime" json:"timestamp"` } func (m *CommitInfo) Reset() { *m = CommitInfo{} } @@ -77,6 +82,13 @@ func (m *CommitInfo) GetStoreInfos() []StoreInfo { return nil } +func (m *CommitInfo) GetTimestamp() time.Time { + if m != nil { + return m.Timestamp + } + return time.Time{} +} + // StoreInfo defines store-specific commit information. It contains a reference // between a store name and the commit ID. type StoreInfo struct { @@ -195,25 +207,28 @@ func init() { } var fileDescriptor_5f8c656cdef8c524 = []byte{ - // 282 bytes of a gzipped FileDescriptorProto - 0x1f, 0x8b, 0x08, 0x00, 0x00, 0x00, 0x00, 0x00, 0x02, 0xff, 0xe2, 0x52, 0x4b, 0xce, 0x2f, 0xce, - 0xcd, 0x2f, 0xd6, 0x2f, 0x2e, 0xc9, 0x2f, 0x4a, 0xd5, 0x2f, 0x33, 0x4c, 0x4a, 0x2d, 0x49, 0x34, - 0xd4, 0x4f, 0xce, 0xcf, 0xcd, 0xcd, 0x2c, 0x89, 0xcf, 0xcc, 0x4b, 0xcb, 0xd7, 0x2b, 0x28, 0xca, - 0x2f, 0xc9, 0x17, 0x12, 0x81, 0xa8, 0xd3, 0x03, 0xab, 0xd3, 0x83, 0xaa, 0x93, 0x12, 0x49, 0xcf, - 0x4f, 0xcf, 0x07, 0x2b, 0xd0, 0x07, 0xb1, 0x20, 0x6a, 0x95, 0xf2, 0xb8, 0xb8, 0x9c, 0xc1, 0x06, - 0x78, 0xe6, 0xa5, 0xe5, 0x0b, 0x49, 0x70, 0xb1, 0x97, 0xa5, 0x16, 0x15, 0x67, 0xe6, 0xe7, 0x49, - 0x30, 0x2a, 0x30, 0x6a, 0x30, 0x07, 0xc1, 0xb8, 0x42, 0x6e, 0x5c, 0xdc, 0x60, 0xe3, 0xc0, 0xf6, - 0x14, 0x4b, 0x30, 0x29, 0x30, 0x6b, 0x70, 0x1b, 0xc9, 0xeb, 0x61, 0xb3, 0x49, 0x2f, 0x18, 0xc4, - 0x03, 0x99, 0xe7, 0xc4, 0x72, 0xe2, 0x9e, 0x3c, 0x43, 0x10, 0x57, 0x31, 0x4c, 0xa0, 0x58, 0x29, - 0x89, 0x8b, 0x13, 0x2e, 0x2d, 0x24, 0xc4, 0xc5, 0x92, 0x97, 0x98, 0x9b, 0x0a, 0xb6, 0x8b, 0x33, - 0x08, 0xcc, 0x16, 0x72, 0xe4, 0xe2, 0x84, 0xf9, 0x28, 0x45, 0x82, 0x49, 0x81, 0x51, 0x83, 0xdb, - 0x48, 0x0e, 0xbb, 0x35, 0x50, 0x77, 0xbb, 0x40, 0x6d, 0xe1, 0x80, 0x68, 0xf3, 0x4c, 0x51, 0xb2, - 0xe3, 0xe2, 0x80, 0xc9, 0xe1, 0xf1, 0x91, 0x10, 0x17, 0x4b, 0x46, 0x62, 0x71, 0x06, 0xd8, 0x0e, - 0x9e, 0x20, 0x30, 0xdb, 0x8a, 0x65, 0xc6, 0x02, 0x79, 0x06, 0x27, 0xa3, 0x13, 0x8f, 0xe4, 0x18, - 0x2f, 0x3c, 0x92, 0x63, 0x7c, 0xf0, 0x48, 0x8e, 0x71, 0xc2, 0x63, 0x39, 0x86, 0x0b, 0x8f, 0xe5, - 0x18, 0x6e, 0x3c, 0x96, 0x63, 0x88, 0x92, 0x80, 0x38, 0xa4, 0x38, 0x25, 0x5b, 0x2f, 0x33, 0x1f, - 0x1a, 0x0f, 0x25, 0x95, 0x05, 0xa9, 0xc5, 0x49, 0x6c, 0xe0, 0xe0, 0x34, 0x06, 0x04, 0x00, 0x00, - 0xff, 0xff, 0x83, 0x38, 0x41, 0x6d, 0xa4, 0x01, 0x00, 0x00, + // 336 bytes of a gzipped FileDescriptorProto + 0x1f, 0x8b, 0x08, 0x00, 0x00, 0x00, 0x00, 0x00, 0x02, 0xff, 0x7c, 0x91, 0xb1, 0x4e, 0xf2, 0x50, + 0x14, 0xc7, 0x7b, 0xa1, 0xf9, 0x3e, 0x7a, 0x70, 0xba, 0x61, 0x68, 0x18, 0x6e, 0x09, 0x83, 0x61, + 0xba, 0x0d, 0xb8, 0x39, 0x98, 0x58, 0x8d, 0x09, 0x6b, 0x75, 0x72, 0x31, 0x2d, 0x5c, 0x4a, 0xa3, + 0xed, 0x21, 0xdc, 0x2b, 0x89, 0x6f, 0xc1, 0xe8, 0xe8, 0x33, 0xf8, 0x14, 0x8c, 0x8c, 0x4e, 0x6a, + 0xe0, 0x45, 0x4c, 0x4f, 0x5b, 0x5c, 0x88, 0xdb, 0x39, 0xed, 0xef, 0x9c, 0xff, 0xaf, 0xa7, 0x70, + 0x3a, 0x41, 0x9d, 0xa1, 0xf6, 0xb5, 0xc1, 0xa5, 0xf2, 0x57, 0xc3, 0x58, 0x99, 0x68, 0xe8, 0x4f, + 0x30, 0xcb, 0x52, 0xf3, 0x90, 0xe6, 0x33, 0x94, 0x8b, 0x25, 0x1a, 0xe4, 0x9d, 0x92, 0x93, 0xc4, + 0xc9, 0x8a, 0xeb, 0x76, 0x12, 0x4c, 0x90, 0x00, 0xbf, 0xa8, 0x4a, 0xb6, 0xeb, 0x25, 0x88, 0xc9, + 0x93, 0xf2, 0xa9, 0x8b, 0x9f, 0x67, 0xbe, 0x49, 0x33, 0xa5, 0x4d, 0x94, 0x2d, 0x4a, 0xa0, 0xff, + 0xce, 0x00, 0xae, 0x28, 0x62, 0x9c, 0xcf, 0x90, 0xbb, 0xf0, 0x7f, 0xa5, 0x96, 0x3a, 0xc5, 0xdc, + 0x65, 0x3d, 0x36, 0x68, 0x86, 0x75, 0xcb, 0x6f, 0xa0, 0x4d, 0x81, 0x64, 0xa2, 0xdd, 0x46, 0xaf, + 0x39, 0x68, 0x8f, 0x3c, 0x79, 0xcc, 0x45, 0xde, 0x16, 0x5d, 0xb1, 0x2f, 0xb0, 0x37, 0x9f, 0x9e, + 0x15, 0x82, 0xae, 0x1f, 0x68, 0x1e, 0x80, 0x73, 0x70, 0x70, 0x9b, 0x3d, 0x36, 0x68, 0x8f, 0xba, + 0xb2, 0xb4, 0x94, 0xb5, 0xa5, 0xbc, 0xab, 0x89, 0xa0, 0x55, 0x2c, 0x58, 0x7f, 0x79, 0x2c, 0xfc, + 0x1d, 0xeb, 0xc7, 0xe0, 0x1c, 0x22, 0x38, 0x07, 0x3b, 0x8f, 0x32, 0x45, 0xbe, 0x4e, 0x48, 0x35, + 0xbf, 0x04, 0xa7, 0xbe, 0xdb, 0xd4, 0x6d, 0x50, 0x88, 0x38, 0xae, 0x5a, 0x7d, 0xfb, 0x75, 0x65, + 0xda, 0x2a, 0xc7, 0xc6, 0xd3, 0xfe, 0x05, 0xb4, 0xea, 0x77, 0x7f, 0x5c, 0x85, 0x83, 0x3d, 0x8f, + 0xf4, 0x9c, 0x32, 0x4e, 0x42, 0xaa, 0xcf, 0xed, 0xd7, 0x37, 0xcf, 0x0a, 0x46, 0x9b, 0x9d, 0x60, + 0xdb, 0x9d, 0x60, 0xdf, 0x3b, 0xc1, 0xd6, 0x7b, 0x61, 0x6d, 0xf7, 0xc2, 0xfa, 0xd8, 0x0b, 0xeb, + 0xde, 0x2d, 0x45, 0xf4, 0xf4, 0x51, 0xa6, 0x58, 0xfd, 0x6d, 0xf3, 0xb2, 0x50, 0x3a, 0xfe, 0x47, + 0x07, 0x38, 0xfb, 0x09, 0x00, 0x00, 0xff, 0xff, 0x67, 0xb7, 0x0d, 0x59, 0x0a, 0x02, 0x00, 0x00, } func (m *CommitInfo) Marshal() (dAtA []byte, err error) { @@ -236,6 +251,14 @@ func (m *CommitInfo) MarshalToSizedBuffer(dAtA []byte) (int, error) { _ = i var l int _ = l + n1, err1 := github_com_cosmos_gogoproto_types.StdTimeMarshalTo(m.Timestamp, dAtA[i-github_com_cosmos_gogoproto_types.SizeOfStdTime(m.Timestamp):]) + if err1 != nil { + return 0, err1 + } + i -= n1 + i = encodeVarintCommitInfo(dAtA, i, uint64(n1)) + i-- + dAtA[i] = 0x1a if len(m.StoreInfos) > 0 { for iNdEx := len(m.StoreInfos) - 1; iNdEx >= 0; iNdEx-- { { @@ -359,6 +382,8 @@ func (m *CommitInfo) Size() (n int) { n += 1 + l + sovCommitInfo(uint64(l)) } } + l = github_com_cosmos_gogoproto_types.SizeOfStdTime(m.Timestamp) + n += 1 + l + sovCommitInfo(uint64(l)) return n } @@ -481,6 +506,39 @@ func (m *CommitInfo) Unmarshal(dAtA []byte) error { return err } iNdEx = postIndex + case 3: + if wireType != 2 { + return fmt.Errorf("proto: wrong wireType = %d for field Timestamp", wireType) + } + var msglen int + for shift := uint(0); ; shift += 7 { + if shift >= 64 { + return ErrIntOverflowCommitInfo + } + if iNdEx >= l { + return io.ErrUnexpectedEOF + } + b := dAtA[iNdEx] + iNdEx++ + msglen |= int(b&0x7F) << shift + if b < 0x80 { + break + } + } + if msglen < 0 { + return ErrInvalidLengthCommitInfo + } + postIndex := iNdEx + msglen + if postIndex < 0 { + return ErrInvalidLengthCommitInfo + } + if postIndex > l { + return io.ErrUnexpectedEOF + } + if err := github_com_cosmos_gogoproto_types.StdTimeUnmarshal(&m.Timestamp, dAtA[iNdEx:postIndex]); err != nil { + return err + } + iNdEx = postIndex default: iNdEx = preIndex skippy, err := skipCommitInfo(dAtA[iNdEx:]) diff --git a/store/types/gas.go b/store/types/gas.go index e0c950476b2e..baceb7ce2544 100644 --- a/store/types/gas.go +++ b/store/types/gas.go @@ -163,7 +163,7 @@ func (g *infiniteGasMeter) GasConsumed() Gas { } // GasConsumedToLimit returns the gas consumed from the GasMeter since the gas is not confined to a limit. -// NOTE: This behaviour is only called when recovering from panic when BlockGasMeter consumes gas past the limit. +// NOTE: This behavior is only called when recovering from panic when BlockGasMeter consumes gas past the limit. func (g *infiniteGasMeter) GasConsumedToLimit() Gas { return g.consumed } diff --git a/store/types/listening.go b/store/types/listening.go index dba5aa934a58..75828793ffc1 100644 --- a/store/types/listening.go +++ b/store/types/listening.go @@ -11,7 +11,7 @@ func NewMemoryListener() *MemoryListener { } // OnWrite implements MemoryListener interface -func (fl *MemoryListener) OnWrite(storeKey StoreKey, key []byte, value []byte, delete bool) { +func (fl *MemoryListener) OnWrite(storeKey StoreKey, key, value []byte, delete bool) { fl.stateCache = append(fl.stateCache, &StoreKVPair{ StoreKey: storeKey.Name(), Delete: delete, diff --git a/store/types/proof.go b/store/types/proof.go index bb3abdc8557d..acc94f387c1d 100644 --- a/store/types/proof.go +++ b/store/types/proof.go @@ -61,7 +61,7 @@ func NewSmtCommitmentOp(key []byte, proof *ics23.CommitmentProof) CommitmentOp { } // CommitmentOpDecoder takes a merkle.ProofOp and attempts to decode it into a CommitmentOp ProofOperator -// The proofOp.Data is just a marshalled CommitmentProof. The Key of the CommitmentOp is extracted +// The proofOp.Data is just a marshaled CommitmentProof. The Key of the CommitmentOp is extracted // from the unmarshalled proof. func CommitmentOpDecoder(pop cmtprotocrypto.ProofOp) (merkle.ProofOperator, error) { var spec *ics23.ProofSpec diff --git a/store/types/store.go b/store/types/store.go index 52db4a087552..e2a83bf5636d 100644 --- a/store/types/store.go +++ b/store/types/store.go @@ -22,6 +22,9 @@ type Committer interface { Commit() CommitID LastCommitID() CommitID + // WorkingHash returns the hash of the KVStore's state before commit. + WorkingHash() []byte + SetPruning(pruningtypes.PruningOptions) GetPruning() pruningtypes.PruningOptions } diff --git a/store/types/store_test.go b/store/types/store_test.go index 0a46f84fc9bd..b6304d131bc2 100644 --- a/store/types/store_test.go +++ b/store/types/store_test.go @@ -233,8 +233,6 @@ func TestNewTransientStoreKeys(t *testing.T) { func TestNewInfiniteGasMeter(t *testing.T) { gm := NewInfiniteGasMeter() require.NotNil(t, gm) - _, ok := gm.(GasMeter) //nolint:gosimple - require.True(t, ok) } func TestStoreTypes(t *testing.T) { diff --git a/tests/e2e/auth/suite.go b/tests/e2e/auth/suite.go index 7097851bad74..3887ee44291f 100644 --- a/tests/e2e/auth/suite.go +++ b/tests/e2e/auth/suite.go @@ -7,7 +7,6 @@ import ( "strings" "testing" - cmtcli "github.com/cometbft/cometbft/libs/cli" "github.com/stretchr/testify/require" "github.com/stretchr/testify/suite" @@ -16,6 +15,7 @@ import ( "github.com/cosmos/cosmos-sdk/client" "github.com/cosmos/cosmos-sdk/client/flags" + "github.com/cosmos/cosmos-sdk/codec/address" "github.com/cosmos/cosmos-sdk/crypto/hd" "github.com/cosmos/cosmos-sdk/crypto/keyring" kmultisig "github.com/cosmos/cosmos-sdk/crypto/keys/multisig" @@ -220,7 +220,7 @@ func (s *E2ETestSuite) TestCLISignGenOnly() { for _, tc := range cases { cmd := authcli.GetSignCommand() - cmtcli.PrepareBaseCmd(cmd, "", "") + cmd.PersistentFlags().String(flags.FlagHome, val.ClientCtx.HomeDir, "directory for config and data") out, err := clitestutil.ExecTestCLICmd(val.ClientCtx, cmd, append(tc.args, commonArgs...)) if tc.expErr { s.Require().Error(err) @@ -1252,7 +1252,7 @@ func (s *E2ETestSuite) TestMultisignBatch() { defer filename.Close() val.ClientCtx.HomeDir = strings.Replace(val.ClientCtx.HomeDir, "simd", "simcli", 1) - queryResJSON, err := authclitestutil.QueryAccountExec(val.ClientCtx, addr) + queryResJSON, err := authclitestutil.QueryAccountExec(val.ClientCtx, addr, address.NewBech32Codec("cosmos")) s.Require().NoError(err) var account sdk.AccountI s.Require().NoError(val.ClientCtx.Codec.UnmarshalInterfaceJSON(queryResJSON.Bytes(), &account)) @@ -1320,7 +1320,7 @@ func (s *E2ETestSuite) TestGetAccountCmd() { s.Run(tc.name, func() { clientCtx := val.ClientCtx - out, err := authclitestutil.QueryAccountExec(clientCtx, tc.address) + out, err := authclitestutil.QueryAccountExec(clientCtx, tc.address, address.NewBech32Codec("cosmos")) if tc.expectErr { s.Require().Error(err) s.Require().NotEqual("internal", err.Error()) @@ -1510,7 +1510,7 @@ func (s *E2ETestSuite) TestTxWithoutPublicKey() { sigV2 := signing.SignatureV2{ PubKey: val1.PubKey, Data: &signing.SingleSignatureData{ - SignMode: txCfg.SignModeHandler().DefaultMode(), + SignMode: signing.SignMode_SIGN_MODE_DIRECT, Signature: nil, }, } diff --git a/tests/e2e/auth/vesting/cli_test.go b/tests/e2e/auth/vesting/cli_test.go deleted file mode 100644 index 80081e2bcaf8..000000000000 --- a/tests/e2e/auth/vesting/cli_test.go +++ /dev/null @@ -1,19 +0,0 @@ -//go:build e2e -// +build e2e - -package testutil - -import ( - "testing" - - "github.com/stretchr/testify/suite" - - "cosmossdk.io/simapp" - "github.com/cosmos/cosmos-sdk/testutil/network" -) - -func TestE2ETestSuite(t *testing.T) { - cfg := network.DefaultConfig(simapp.NewTestNetworkFixture) - cfg.NumValidators = 1 - suite.Run(t, NewE2ETestSuite(cfg)) -} diff --git a/tests/e2e/auth/vesting/suite.go b/tests/e2e/auth/vesting/suite.go deleted file mode 100644 index e2bbd722ea8a..000000000000 --- a/tests/e2e/auth/vesting/suite.go +++ /dev/null @@ -1,221 +0,0 @@ -package testutil - -import ( - "fmt" - - "github.com/cosmos/gogoproto/proto" - "github.com/stretchr/testify/suite" - - "github.com/cosmos/cosmos-sdk/client/flags" - clitestutil "github.com/cosmos/cosmos-sdk/testutil/cli" - "github.com/cosmos/cosmos-sdk/testutil/network" - sdk "github.com/cosmos/cosmos-sdk/types" - "github.com/cosmos/cosmos-sdk/x/auth/vesting/client/cli" -) - -type E2ETestSuite struct { - suite.Suite - - cfg network.Config - network *network.Network -} - -func NewE2ETestSuite(cfg network.Config) *E2ETestSuite { - return &E2ETestSuite{cfg: cfg} -} - -func (s *E2ETestSuite) SetupSuite() { - s.T().Log("setting up e2e test suite") - - var err error - s.network, err = network.New(s.T(), s.T().TempDir(), s.cfg) - s.Require().NoError(err) - s.Require().NoError(s.network.WaitForNextBlock()) -} - -func (s *E2ETestSuite) TearDownSuite() { - s.T().Log("tearing down e2e test suite") - s.network.Cleanup() -} - -func (s *E2ETestSuite) TestNewMsgCreateVestingAccountCmd() { - val := s.network.Validators[0] - - testCases := map[string]struct { - args []string - expectErr bool - expectedCode uint32 - respType proto.Message - }{ - "create a continuous vesting account": { - args: []string{ - sdk.AccAddress("addr2_______________").String(), - sdk.NewCoins(sdk.NewCoin(s.cfg.BondDenom, sdk.NewInt(10))).String(), - "4070908800", - fmt.Sprintf("--%s=%s", flags.FlagFrom, val.Address), - fmt.Sprintf("--%s=true", flags.FlagSkipConfirmation), - fmt.Sprintf("--%s=%s", flags.FlagBroadcastMode, flags.BroadcastSync), - fmt.Sprintf("--%s=%s", flags.FlagFees, sdk.NewCoins(sdk.NewCoin(s.cfg.BondDenom, sdk.NewInt(10))).String()), - }, - expectErr: false, - expectedCode: 0, - respType: &sdk.TxResponse{}, - }, - "create a delayed vesting account": { - args: []string{ - sdk.AccAddress("addr3_______________").String(), - sdk.NewCoins(sdk.NewCoin(s.cfg.BondDenom, sdk.NewInt(10))).String(), - "4070908800", - fmt.Sprintf("--%s=%s", flags.FlagFrom, val.Address), - fmt.Sprintf("--%s=true", cli.FlagDelayed), - fmt.Sprintf("--%s=true", flags.FlagSkipConfirmation), - fmt.Sprintf("--%s=%s", flags.FlagBroadcastMode, flags.BroadcastSync), - fmt.Sprintf("--%s=%s", flags.FlagFees, sdk.NewCoins(sdk.NewCoin(s.cfg.BondDenom, sdk.NewInt(10))).String()), - }, - expectErr: false, - expectedCode: 0, - respType: &sdk.TxResponse{}, - }, - "invalid address": { - args: []string{ - "addr4", - sdk.NewCoins(sdk.NewCoin(s.cfg.BondDenom, sdk.NewInt(10))).String(), - "4070908800", - fmt.Sprintf("--%s=%s", flags.FlagFrom, val.Address), - }, - expectErr: true, - expectedCode: 0, - respType: &sdk.TxResponse{}, - }, - "invalid coins": { - args: []string{ - sdk.AccAddress("addr4_______________").String(), - "fooo", - "4070908800", - fmt.Sprintf("--%s=%s", flags.FlagFrom, val.Address), - }, - expectErr: true, - expectedCode: 0, - respType: &sdk.TxResponse{}, - }, - "invalid end time": { - args: []string{ - sdk.AccAddress("addr4_______________").String(), - sdk.NewCoins(sdk.NewCoin(s.cfg.BondDenom, sdk.NewInt(10))).String(), - "-4070908800", - fmt.Sprintf("--%s=%s", flags.FlagFrom, val.Address), - }, - expectErr: true, - expectedCode: 0, - respType: &sdk.TxResponse{}, - }, - } - - // Synchronize height between test runs, to ensure sequence numbers are - // properly updated. - height, err := s.network.LatestHeight() - if err != nil { - s.T().Fatalf("Getting initial latest height: %v", err) - } - s.T().Logf("Initial latest height: %d", height) - for name, tc := range testCases { - tc := tc - - s.Run(name, func() { - clientCtx := val.ClientCtx - - bw, err := clitestutil.ExecTestCLICmd(clientCtx, cli.NewMsgCreateVestingAccountCmd(), tc.args) - if tc.expectErr { - s.Require().Error(err) - } else { - s.Require().NoError(err) - s.Require().NoError(clientCtx.Codec.UnmarshalJSON(bw.Bytes(), tc.respType), bw.String()) - - txResp := tc.respType.(*sdk.TxResponse) - s.Require().NoError(clitestutil.CheckTxCode(s.network, clientCtx, txResp.TxHash, tc.expectedCode)) - } - }) - - next, err := s.network.WaitForHeight(height + 1) - if err != nil { - s.T().Fatalf("Waiting for height %d: %v", height+1, err) - } - height = next - s.T().Logf("Height now: %d", height) - } -} - -func (s *E2ETestSuite) TestNewMsgCreatePermanentLockedAccountCmd() { - val := s.network.Validators[0] - - testCases := map[string]struct { - args []string - expectErr bool - expectedCode uint32 - respType proto.Message - }{ - "create a permanent locked account": { - args: []string{ - sdk.AccAddress("addr4_______________").String(), - sdk.NewCoins(sdk.NewCoin(s.cfg.BondDenom, sdk.NewInt(100))).String(), - fmt.Sprintf("--%s=%s", flags.FlagFrom, val.Address), - fmt.Sprintf("--%s=true", flags.FlagSkipConfirmation), - fmt.Sprintf("--%s=%s", flags.FlagBroadcastMode, flags.BroadcastSync), - fmt.Sprintf("--%s=%s", flags.FlagFees, sdk.NewCoins(sdk.NewCoin(s.cfg.BondDenom, sdk.NewInt(10))).String()), - }, - expectErr: false, - expectedCode: 0, - respType: &sdk.TxResponse{}, - }, - "invalid address": { - args: []string{ - "addr4", - sdk.NewCoins(sdk.NewCoin(s.cfg.BondDenom, sdk.NewInt(10))).String(), - "4070908800", - fmt.Sprintf("--%s=%s", flags.FlagFrom, val.Address), - }, - expectErr: true, - expectedCode: 0, - respType: &sdk.TxResponse{}, - }, - "invalid coins": { - args: []string{ - sdk.AccAddress("addr4_______________").String(), - "fooo", - "4070908800", - fmt.Sprintf("--%s=%s", flags.FlagFrom, val.Address), - }, - expectErr: true, - expectedCode: 0, - respType: &sdk.TxResponse{}, - }, - } - - // Synchronize height between test runs, to ensure sequence numbers are - // properly updated. - height, err := s.network.LatestHeight() - s.Require().NoError(err, "Getting initial latest height") - s.T().Logf("Initial latest height: %d", height) - for name, tc := range testCases { - tc := tc - - s.Run(name, func() { - clientCtx := val.ClientCtx - - bw, err := clitestutil.ExecTestCLICmd(clientCtx, cli.NewMsgCreatePermanentLockedAccountCmd(), tc.args) - if tc.expectErr { - s.Require().Error(err) - } else { - s.Require().NoError(err) - s.Require().NoError(clientCtx.Codec.UnmarshalJSON(bw.Bytes(), tc.respType), bw.String()) - - txResp := tc.respType.(*sdk.TxResponse) - s.Require().NoError(clitestutil.CheckTxCode(s.network, clientCtx, txResp.TxHash, tc.expectedCode)) - } - }) - next, err := s.network.WaitForHeight(height + 1) - s.Require().NoError(err, "Waiting for height...") - height = next - s.T().Logf("Height now: %d", height) - } -} diff --git a/tests/e2e/authz/grpc.go b/tests/e2e/authz/grpc.go index 5aa21e6b68cc..72de28813cba 100644 --- a/tests/e2e/authz/grpc.go +++ b/tests/e2e/authz/grpc.go @@ -197,7 +197,7 @@ func (s *E2ETestSuite) TestQueryGranterGrantsGRPC() { fmt.Sprintf("%s/cosmos/authz/v1beta1/grants/granter/%s", val.APIAddress, val.Address.String()), false, "", - 8, + 7, }, } for _, tc := range testCases { diff --git a/tests/e2e/authz/query.go b/tests/e2e/authz/query.go index 6e930f1fe270..e4e0f94073b8 100644 --- a/tests/e2e/authz/query.go +++ b/tests/e2e/authz/query.go @@ -6,6 +6,7 @@ import ( "time" "github.com/cosmos/cosmos-sdk/client/flags" + "github.com/cosmos/cosmos-sdk/codec/address" clitestutil "github.com/cosmos/cosmos-sdk/testutil/cli" sdk "github.com/cosmos/cosmos-sdk/types" "github.com/cosmos/cosmos-sdk/x/authz" @@ -76,7 +77,7 @@ func (s *E2ETestSuite) TestQueryAuthorizations() { tc := tc s.Run(tc.name, func() { - cmd := cli.GetCmdQueryGrants() + cmd := cli.GetCmdQueryGrants(address.NewBech32Codec("cosmos")) clientCtx := val.ClientCtx resp, err := clitestutil.ExecTestCLICmd(clientCtx, cmd, tc.args) if tc.expectErr { @@ -180,7 +181,7 @@ func (s *E2ETestSuite) TestQueryAuthorization() { tc := tc s.Run(tc.name, func() { - cmd := cli.GetCmdQueryGrants() + cmd := cli.GetCmdQueryGrants(address.NewBech32Codec("cosmos")) clientCtx := val.ClientCtx out, err := clitestutil.ExecTestCLICmd(clientCtx, cmd, tc.args) if tc.expectErr { @@ -233,7 +234,7 @@ func (s *E2ETestSuite) TestQueryGranterGrants() { }, false, "", - 8, + 7, }, { "valid case with pagination", @@ -249,7 +250,7 @@ func (s *E2ETestSuite) TestQueryGranterGrants() { } for _, tc := range testCases { s.Run(tc.name, func() { - cmd := cli.GetQueryGranterGrants() + cmd := cli.GetQueryGranterGrants(address.NewBech32Codec("cosmos")) clientCtx := val.ClientCtx out, err := clitestutil.ExecTestCLICmd(clientCtx, cmd, tc.args) if tc.expectErr { diff --git a/tests/e2e/authz/tx.go b/tests/e2e/authz/tx.go index 613b959b4c75..346897801e2e 100644 --- a/tests/e2e/authz/tx.go +++ b/tests/e2e/authz/tx.go @@ -7,7 +7,10 @@ import ( "github.com/cosmos/gogoproto/proto" "github.com/stretchr/testify/suite" + // without this import amino json encoding will fail when resolving any types + _ "cosmossdk.io/api/cosmos/authz/v1beta1" "github.com/cosmos/cosmos-sdk/client/flags" + "github.com/cosmos/cosmos-sdk/codec/address" "github.com/cosmos/cosmos-sdk/crypto/hd" "github.com/cosmos/cosmos-sdk/crypto/keyring" "github.com/cosmos/cosmos-sdk/testutil" @@ -166,366 +169,6 @@ var ( typeMsgSubmitProposal = sdk.MsgTypeURL(&govv1.MsgSubmitProposal{}) ) -func (s *E2ETestSuite) TestCLITxGrantAuthorization() { - val := s.network.Validators[0] - grantee := s.grantee[0] - - twoHours := time.Now().Add(time.Minute * 120).Unix() - pastHour := time.Now().Add(-time.Minute * 60).Unix() - - testCases := []struct { - name string - args []string - expectedCode uint32 - expectErr bool - expErrMsg string - }{ - { - "Invalid granter Address", - []string{ - "grantee_addr", - "send", - fmt.Sprintf("--%s=100stake", cli.FlagSpendLimit), - fmt.Sprintf("--%s=%s", flags.FlagFrom, "granter"), - fmt.Sprintf("--%s=true", flags.FlagGenerateOnly), - fmt.Sprintf("--%s=%d", cli.FlagExpiration, twoHours), - }, - 0, - true, - "key not found", - }, - { - "Invalid grantee Address", - []string{ - "grantee_addr", - "send", - fmt.Sprintf("--%s=100stake", cli.FlagSpendLimit), - fmt.Sprintf("--%s=%s", flags.FlagFrom, val.Address.String()), - fmt.Sprintf("--%s=true", flags.FlagGenerateOnly), - fmt.Sprintf("--%s=%d", cli.FlagExpiration, twoHours), - }, - 0, - true, - "invalid separator index", - }, - { - "Invalid expiration time", - []string{ - grantee.String(), - "send", - fmt.Sprintf("--%s=100stake", cli.FlagSpendLimit), - fmt.Sprintf("--%s=%s", flags.FlagFrom, val.Address.String()), - fmt.Sprintf("--%s=true", flags.FlagBroadcastMode), - fmt.Sprintf("--%s=%d", cli.FlagExpiration, pastHour), - }, - 0, - true, - "", - }, - { - "fail with error invalid msg-type", - []string{ - grantee.String(), - "generic", - fmt.Sprintf("--%s=invalid-msg-type", cli.FlagMsgType), - fmt.Sprintf("--%s=%s", flags.FlagFrom, val.Address.String()), - fmt.Sprintf("--%s=%s", flags.FlagBroadcastMode, flags.BroadcastSync), - fmt.Sprintf("--%s=true", flags.FlagSkipConfirmation), - fmt.Sprintf("--%s=%s", flags.FlagFees, sdk.NewCoins(sdk.NewCoin(s.cfg.BondDenom, sdk.NewInt(10))).String()), - fmt.Sprintf("--%s=%d", cli.FlagExpiration, twoHours), - }, - 0x1d, - false, - "", - }, - { - "failed with error both validators not allowed", - []string{ - grantee.String(), - "delegate", - fmt.Sprintf("--%s=100stake", cli.FlagSpendLimit), - fmt.Sprintf("--%s=true", flags.FlagSkipConfirmation), - fmt.Sprintf("--%s=%s", flags.FlagFrom, val.Address.String()), - fmt.Sprintf("--%s=%s", flags.FlagBroadcastMode, flags.BroadcastSync), - fmt.Sprintf("--%s=%d", cli.FlagExpiration, twoHours), - fmt.Sprintf("--%s=%s", cli.FlagAllowedValidators, val.ValAddress.String()), - fmt.Sprintf("--%s=%s", cli.FlagDenyValidators, val.ValAddress.String()), - fmt.Sprintf("--%s=%s", flags.FlagFees, sdk.NewCoins(sdk.NewCoin(s.cfg.BondDenom, sdk.NewInt(10))).String()), - }, - 0, - true, - "cannot set both allowed & deny list", - }, - { - "invalid bond denom for tx delegate authorization allowed validators", - []string{ - grantee.String(), - "delegate", - fmt.Sprintf("--%s=100xyz", cli.FlagSpendLimit), - fmt.Sprintf("--%s=true", flags.FlagSkipConfirmation), - fmt.Sprintf("--%s=%s", flags.FlagFrom, val.Address.String()), - fmt.Sprintf("--%s=%s", flags.FlagBroadcastMode, flags.BroadcastSync), - fmt.Sprintf("--%s=%d", cli.FlagExpiration, twoHours), - fmt.Sprintf("--%s=%s", cli.FlagAllowedValidators, val.ValAddress.String()), - fmt.Sprintf("--%s=%s", flags.FlagFees, sdk.NewCoins(sdk.NewCoin(s.cfg.BondDenom, sdk.NewInt(10))).String()), - }, - 0, - true, - "invalid denom", - }, - { - "invalid bond denom for tx delegate authorization deny validators", - []string{ - grantee.String(), - "delegate", - fmt.Sprintf("--%s=100xyz", cli.FlagSpendLimit), - fmt.Sprintf("--%s=true", flags.FlagSkipConfirmation), - fmt.Sprintf("--%s=%s", flags.FlagFrom, val.Address.String()), - fmt.Sprintf("--%s=%s", flags.FlagBroadcastMode, flags.BroadcastSync), - fmt.Sprintf("--%s=%d", cli.FlagExpiration, twoHours), - fmt.Sprintf("--%s=%s", cli.FlagDenyValidators, val.ValAddress.String()), - fmt.Sprintf("--%s=%s", flags.FlagFees, sdk.NewCoins(sdk.NewCoin(s.cfg.BondDenom, sdk.NewInt(10))).String()), - }, - 0, - true, - "invalid denom", - }, - { - "invalid bond denom for tx undelegate authorization", - []string{ - grantee.String(), - "unbond", - fmt.Sprintf("--%s=100xyz", cli.FlagSpendLimit), - fmt.Sprintf("--%s=true", flags.FlagSkipConfirmation), - fmt.Sprintf("--%s=%s", flags.FlagFrom, val.Address.String()), - fmt.Sprintf("--%s=%s", flags.FlagBroadcastMode, flags.BroadcastSync), - fmt.Sprintf("--%s=%d", cli.FlagExpiration, twoHours), - fmt.Sprintf("--%s=%s", cli.FlagAllowedValidators, val.ValAddress.String()), - fmt.Sprintf("--%s=%s", flags.FlagFees, sdk.NewCoins(sdk.NewCoin(s.cfg.BondDenom, sdk.NewInt(10))).String()), - }, - 0, - true, - "invalid denom", - }, - { - "invalid bond denon for tx redelegate authorization", - []string{ - grantee.String(), - "redelegate", - fmt.Sprintf("--%s=100xyz", cli.FlagSpendLimit), - fmt.Sprintf("--%s=true", flags.FlagSkipConfirmation), - fmt.Sprintf("--%s=%s", flags.FlagFrom, val.Address.String()), - fmt.Sprintf("--%s=%s", flags.FlagBroadcastMode, flags.BroadcastSync), - fmt.Sprintf("--%s=%d", cli.FlagExpiration, twoHours), - fmt.Sprintf("--%s=%s", cli.FlagAllowedValidators, val.ValAddress.String()), - fmt.Sprintf("--%s=%s", flags.FlagFees, sdk.NewCoins(sdk.NewCoin(s.cfg.BondDenom, sdk.NewInt(10))).String()), - }, - 0, - true, - "invalid denom", - }, - { - "invalid decimal coin expression with more than single coin", - []string{ - grantee.String(), - "delegate", - fmt.Sprintf("--%s=100stake,20xyz", cli.FlagSpendLimit), - fmt.Sprintf("--%s=true", flags.FlagSkipConfirmation), - fmt.Sprintf("--%s=%s", flags.FlagFrom, val.Address.String()), - fmt.Sprintf("--%s=%s", flags.FlagBroadcastMode, flags.BroadcastSync), - fmt.Sprintf("--%s=%d", cli.FlagExpiration, twoHours), - fmt.Sprintf("--%s=%s", cli.FlagAllowedValidators, val.ValAddress.String()), - fmt.Sprintf("--%s=%s", flags.FlagFees, sdk.NewCoins(sdk.NewCoin(s.cfg.BondDenom, sdk.NewInt(10))).String()), - }, - 0, - true, - "invalid decimal coin expression", - }, - { - "valid tx delegate authorization allowed validators", - []string{ - grantee.String(), - "delegate", - fmt.Sprintf("--%s=100stake", cli.FlagSpendLimit), - fmt.Sprintf("--%s=true", flags.FlagSkipConfirmation), - fmt.Sprintf("--%s=%s", flags.FlagFrom, val.Address.String()), - fmt.Sprintf("--%s=%s", flags.FlagBroadcastMode, flags.BroadcastSync), - fmt.Sprintf("--%s=%d", cli.FlagExpiration, twoHours), - fmt.Sprintf("--%s=%s", cli.FlagAllowedValidators, val.ValAddress.String()), - fmt.Sprintf("--%s=%s", flags.FlagFees, sdk.NewCoins(sdk.NewCoin(s.cfg.BondDenom, sdk.NewInt(10))).String()), - }, - 0, - false, - "", - }, - { - "valid tx delegate authorization deny validators", - []string{ - grantee.String(), - "delegate", - fmt.Sprintf("--%s=100stake", cli.FlagSpendLimit), - fmt.Sprintf("--%s=true", flags.FlagSkipConfirmation), - fmt.Sprintf("--%s=%s", flags.FlagFrom, val.Address.String()), - fmt.Sprintf("--%s=%s", flags.FlagBroadcastMode, flags.BroadcastSync), - fmt.Sprintf("--%s=%d", cli.FlagExpiration, twoHours), - fmt.Sprintf("--%s=%s", cli.FlagDenyValidators, val.ValAddress.String()), - fmt.Sprintf("--%s=%s", flags.FlagFees, sdk.NewCoins(sdk.NewCoin(s.cfg.BondDenom, sdk.NewInt(10))).String()), - }, - 0, - false, - "", - }, - { - "valid tx undelegate authorization", - []string{ - grantee.String(), - "unbond", - fmt.Sprintf("--%s=100stake", cli.FlagSpendLimit), - fmt.Sprintf("--%s=true", flags.FlagSkipConfirmation), - fmt.Sprintf("--%s=%s", flags.FlagFrom, val.Address.String()), - fmt.Sprintf("--%s=%s", flags.FlagBroadcastMode, flags.BroadcastSync), - fmt.Sprintf("--%s=%d", cli.FlagExpiration, twoHours), - fmt.Sprintf("--%s=%s", cli.FlagAllowedValidators, val.ValAddress.String()), - fmt.Sprintf("--%s=%s", flags.FlagFees, sdk.NewCoins(sdk.NewCoin(s.cfg.BondDenom, sdk.NewInt(10))).String()), - }, - 0, - false, - "", - }, - { - "valid tx redelegate authorization", - []string{ - grantee.String(), - "redelegate", - fmt.Sprintf("--%s=100stake", cli.FlagSpendLimit), - fmt.Sprintf("--%s=true", flags.FlagSkipConfirmation), - fmt.Sprintf("--%s=%s", flags.FlagFrom, val.Address.String()), - fmt.Sprintf("--%s=%s", flags.FlagBroadcastMode, flags.BroadcastSync), - fmt.Sprintf("--%s=%d", cli.FlagExpiration, twoHours), - fmt.Sprintf("--%s=%s", cli.FlagAllowedValidators, val.ValAddress.String()), - fmt.Sprintf("--%s=%s", flags.FlagFees, sdk.NewCoins(sdk.NewCoin(s.cfg.BondDenom, sdk.NewInt(10))).String()), - }, - 0, - false, - "", - }, - { - "Valid tx send authorization", - []string{ - grantee.String(), - "send", - fmt.Sprintf("--%s=100stake", cli.FlagSpendLimit), - fmt.Sprintf("--%s=%s", flags.FlagFrom, val.Address.String()), - fmt.Sprintf("--%s=%s", flags.FlagBroadcastMode, flags.BroadcastSync), - fmt.Sprintf("--%s=%d", cli.FlagExpiration, twoHours), - fmt.Sprintf("--%s=true", flags.FlagSkipConfirmation), - fmt.Sprintf("--%s=%s", flags.FlagFees, sdk.NewCoins(sdk.NewCoin(s.cfg.BondDenom, sdk.NewInt(10))).String()), - }, - 0, - false, - "", - }, - { - "Valid tx send authorization with allow list", - []string{ - grantee.String(), - "send", - fmt.Sprintf("--%s=100stake", cli.FlagSpendLimit), - fmt.Sprintf("--%s=%s", flags.FlagFrom, val.Address.String()), - fmt.Sprintf("--%s=%s", flags.FlagBroadcastMode, flags.BroadcastSync), - fmt.Sprintf("--%s=%d", cli.FlagExpiration, twoHours), - fmt.Sprintf("--%s=true", flags.FlagSkipConfirmation), - fmt.Sprintf("--%s=%s", flags.FlagFees, sdk.NewCoins(sdk.NewCoin(s.cfg.BondDenom, sdk.NewInt(10))).String()), - fmt.Sprintf("--%s=%s", cli.FlagAllowList, s.grantee[1]), - }, - 0, - false, - "", - }, - { - "Invalid tx send authorization with duplicate allow list", - []string{ - grantee.String(), - "send", - fmt.Sprintf("--%s=100stake", cli.FlagSpendLimit), - fmt.Sprintf("--%s=%s", flags.FlagFrom, val.Address.String()), - fmt.Sprintf("--%s=%s", flags.FlagBroadcastMode, flags.BroadcastSync), - fmt.Sprintf("--%s=%d", cli.FlagExpiration, twoHours), - fmt.Sprintf("--%s=true", flags.FlagSkipConfirmation), - fmt.Sprintf("--%s=%s", flags.FlagFees, sdk.NewCoins(sdk.NewCoin(s.cfg.BondDenom, sdk.NewInt(10))).String()), - fmt.Sprintf("--%s=%s", cli.FlagAllowList, fmt.Sprintf("%s,%s", s.grantee[1], s.grantee[1])), - }, - 0, - true, - "duplicate entry", - }, - { - "Valid tx generic authorization", - []string{ - grantee.String(), - "generic", - fmt.Sprintf("--%s=%s", cli.FlagMsgType, typeMsgVote), - fmt.Sprintf("--%s=%s", flags.FlagFrom, val.Address.String()), - fmt.Sprintf("--%s=%s", flags.FlagBroadcastMode, flags.BroadcastSync), - fmt.Sprintf("--%s=%d", cli.FlagExpiration, twoHours), - fmt.Sprintf("--%s=true", flags.FlagSkipConfirmation), - fmt.Sprintf("--%s=%s", flags.FlagFees, sdk.NewCoins(sdk.NewCoin(s.cfg.BondDenom, sdk.NewInt(10))).String()), - }, - 0, - false, - "", - }, - { - "fail when granter = grantee", - []string{ - grantee.String(), - "generic", - fmt.Sprintf("--%s=%s", cli.FlagMsgType, typeMsgVote), - fmt.Sprintf("--%s=%s", flags.FlagFrom, grantee.String()), - fmt.Sprintf("--%s=%s", flags.FlagBroadcastMode, flags.BroadcastSync), - fmt.Sprintf("--%s=%d", cli.FlagExpiration, twoHours), - fmt.Sprintf("--%s=true", flags.FlagSkipConfirmation), - fmt.Sprintf("--%s=%s", flags.FlagFees, sdk.NewCoins(sdk.NewCoin(s.cfg.BondDenom, sdk.NewInt(10))).String()), - }, - 0, - true, - "grantee and granter should be different", - }, - { - "Valid tx with amino", - []string{ - grantee.String(), - "generic", - fmt.Sprintf("--%s=%s", cli.FlagMsgType, typeMsgVote), - fmt.Sprintf("--%s=%s", flags.FlagFrom, val.Address.String()), - fmt.Sprintf("--%s=%s", flags.FlagBroadcastMode, flags.BroadcastSync), - fmt.Sprintf("--%s=%d", cli.FlagExpiration, twoHours), - fmt.Sprintf("--%s=true", flags.FlagSkipConfirmation), - fmt.Sprintf("--%s=%s", flags.FlagFees, sdk.NewCoins(sdk.NewCoin(s.cfg.BondDenom, sdk.NewInt(10))).String()), - fmt.Sprintf("--%s=%s", flags.FlagSignMode, flags.SignModeLegacyAminoJSON), - }, - 0, - false, - "", - }, - } - - for _, tc := range testCases { - s.Run(tc.name, func() { - out, err := authzclitestutil.CreateGrant(val.ClientCtx, tc.args) - if tc.expectErr { - s.Require().Error(err, out) - s.Require().Contains(err.Error(), tc.expErrMsg) - } else { - var txResp sdk.TxResponse - s.Require().NoError(err) - s.Require().NoError(val.ClientCtx.Codec.UnmarshalJSON(out.Bytes(), &txResp), out.String()) - s.Require().NoError(clitestutil.CheckTxCode(s.network, val.ClientCtx, txResp.TxHash, tc.expectedCode)) - } - }) - } -} - func execDelegate(val *network.Validator, args []string) (testutil.BufferWriter, error) { cmd := stakingcli.NewDelegateCmd() clientCtx := val.ClientCtx @@ -665,7 +308,7 @@ func (s *E2ETestSuite) TestCmdRevokeAuthorizations() { for _, tc := range testCases { tc := tc s.Run(tc.name, func() { - cmd := cli.NewCmdRevokeAuthorization() + cmd := cli.NewCmdRevokeAuthorization(address.NewBech32Codec("cosmos")) clientCtx := val.ClientCtx out, err := clitestutil.ExecTestCLICmd(clientCtx, cmd, tc.args) @@ -1176,19 +819,6 @@ func (s *E2ETestSuite) TestExecDelegateAuthorization() { false, "", }, - { - "valid txn", - []string{ - execMsg.Name(), - fmt.Sprintf("--%s=%s", flags.FlagFrom, grantee.String()), - fmt.Sprintf("--%s=%s", flags.FlagBroadcastMode, flags.BroadcastSync), - fmt.Sprintf("--%s=%s", flags.FlagFees, sdk.NewCoins(sdk.NewCoin(s.cfg.BondDenom, sdk.NewInt(10))).String()), - fmt.Sprintf("--%s=true", flags.FlagSkipConfirmation), - }, - 0, - false, - "", - }, } for _, tc := range testCases { @@ -1415,20 +1045,6 @@ func (s *E2ETestSuite) TestExecUndelegateAuthorization() { false, "", }, - { - "valid txn", - []string{ - execMsg.Name(), - fmt.Sprintf("--%s=%s", flags.FlagGas, "250000"), - fmt.Sprintf("--%s=%s", flags.FlagFrom, grantee.String()), - fmt.Sprintf("--%s=%s", flags.FlagBroadcastMode, flags.BroadcastSync), - fmt.Sprintf("--%s=%s", flags.FlagFees, sdk.NewCoins(sdk.NewCoin(s.cfg.BondDenom, sdk.NewInt(10))).String()), - fmt.Sprintf("--%s=true", flags.FlagSkipConfirmation), - }, - 0, - false, - "", - }, } for _, tc := range testCases { diff --git a/tests/e2e/distribution/suite.go b/tests/e2e/distribution/suite.go index 00b7884ab879..f4d6e3dbf59b 100644 --- a/tests/e2e/distribution/suite.go +++ b/tests/e2e/distribution/suite.go @@ -1,6 +1,7 @@ package distribution import ( + "context" "encoding/hex" "fmt" "strings" @@ -11,12 +12,14 @@ import ( "github.com/cosmos/gogoproto/proto" "github.com/stretchr/testify/suite" + "github.com/cosmos/cosmos-sdk/client" "github.com/cosmos/cosmos-sdk/client/flags" + "github.com/cosmos/cosmos-sdk/codec/address" + svrcmd "github.com/cosmos/cosmos-sdk/server/cmd" clitestutil "github.com/cosmos/cosmos-sdk/testutil/cli" "github.com/cosmos/cosmos-sdk/testutil/network" sdk "github.com/cosmos/cosmos-sdk/types" "github.com/cosmos/cosmos-sdk/x/distribution/client/cli" - distrclitestutil "github.com/cosmos/cosmos-sdk/x/distribution/client/testutil" distrtypes "github.com/cosmos/cosmos-sdk/x/distribution/types" minttypes "github.com/cosmos/cosmos-sdk/x/mint/types" ) @@ -440,7 +443,7 @@ total: tc := tc s.Run(tc.name, func() { - cmd := cli.GetCmdQueryDelegatorRewards() + cmd := cli.GetCmdQueryDelegatorRewards(address.NewBech32Codec("cosmos")) clientCtx := val.ClientCtx out, err := clitestutil.ExecTestCLICmd(clientCtx, cmd, tc.args) @@ -555,13 +558,22 @@ func (s *E2ETestSuite) TestNewWithdrawRewardsCmd() { s.Run(tc.name, func() { clientCtx := val.ClientCtx + args := append([]string{tc.valAddr.String()}, tc.args...) + _, _ = s.network.WaitForHeightWithTimeout(10, time.Minute) - bz, err := distrclitestutil.MsgWithdrawDelegatorRewardExec(clientCtx, tc.valAddr, tc.args...) + + ctx := svrcmd.CreateExecuteContext(context.Background()) + cmd := cli.NewWithdrawRewardsCmd() + cmd.SetContext(ctx) + cmd.SetArgs(args) + s.Require().NoError(client.SetCmdClientContextHandler(clientCtx, cmd)) + + out, err := clitestutil.ExecTestCLICmd(clientCtx, cmd, args) if tc.expectErr { s.Require().Error(err) } else { s.Require().NoError(err) - s.Require().NoError(clientCtx.Codec.UnmarshalJSON(bz, tc.respType), string(bz)) + s.Require().NoError(clientCtx.Codec.UnmarshalJSON(out.Bytes(), tc.respType), out.String()) s.Require().NoError(s.network.WaitForNextBlock()) txResp, err := clitestutil.GetTxResponse(s.network, clientCtx, tc.respType.(*sdk.TxResponse).TxHash) @@ -724,7 +736,7 @@ func (s *E2ETestSuite) TestNewSetWithdrawAddrCmd() { tc := tc s.Run(tc.name, func() { - cmd := cli.NewSetWithdrawAddrCmd() + cmd := cli.NewSetWithdrawAddrCmd(address.NewBech32Codec("cosmos")) clientCtx := val.ClientCtx out, err := clitestutil.ExecTestCLICmd(clientCtx, cmd, tc.args) diff --git a/tests/e2e/feegrant/suite.go b/tests/e2e/feegrant/suite.go index ab9ca482a450..9797f42ed00e 100644 --- a/tests/e2e/feegrant/suite.go +++ b/tests/e2e/feegrant/suite.go @@ -9,6 +9,8 @@ import ( "github.com/cosmos/gogoproto/proto" "github.com/stretchr/testify/suite" + // without this import amino json encoding will fail when resolving any types + _ "cosmossdk.io/api/cosmos/feegrant/v1beta1" "cosmossdk.io/x/feegrant" "cosmossdk.io/x/feegrant/client/cli" "github.com/cosmos/cosmos-sdk/client" diff --git a/tests/e2e/gov/deposits.go b/tests/e2e/gov/deposits.go index a00003af4261..4b433aef26de 100644 --- a/tests/e2e/gov/deposits.go +++ b/tests/e2e/gov/deposits.go @@ -8,6 +8,7 @@ import ( "github.com/stretchr/testify/suite" "github.com/cosmos/cosmos-sdk/client/flags" + "github.com/cosmos/cosmos-sdk/codec/address" "github.com/cosmos/cosmos-sdk/testutil" clitestutil "github.com/cosmos/cosmos-sdk/testutil/cli" "github.com/cosmos/cosmos-sdk/testutil/network" @@ -56,7 +57,7 @@ func (s *DepositTestSuite) submitProposal(val *network.Validator, initialDeposit s.Require().NoError(s.network.WaitForNextBlock()) // query proposals, return the last's id - cmd := cli.GetCmdQueryProposals() + cmd := cli.GetCmdQueryProposals(address.NewBech32Codec("cosmos")) args := []string{fmt.Sprintf("--%s=json", flags.FlagOutput)} res, err := clitestutil.ExecTestCLICmd(val.ClientCtx, cmd, args) s.Require().NoError(err) @@ -130,7 +131,7 @@ func (s *DepositTestSuite) TestQueryProposalAfterVotingPeriod() { proposalID := strconv.FormatUint(id, 10) args := []string{fmt.Sprintf("--%s=json", flags.FlagOutput)} - cmd := cli.GetCmdQueryProposals() + cmd := cli.GetCmdQueryProposals(address.NewBech32Codec("cosmos")) _, err := clitestutil.ExecTestCLICmd(val.ClientCtx, cmd, args) s.Require().NoError(err) diff --git a/tests/e2e/gov/query.go b/tests/e2e/gov/query.go index 062c93fb044b..23b7c67f564a 100644 --- a/tests/e2e/gov/query.go +++ b/tests/e2e/gov/query.go @@ -5,6 +5,7 @@ import ( "strings" "github.com/cosmos/cosmos-sdk/client/flags" + "github.com/cosmos/cosmos-sdk/codec/address" clitestutil "github.com/cosmos/cosmos-sdk/testutil/cli" sdk "github.com/cosmos/cosmos-sdk/types" "github.com/cosmos/cosmos-sdk/x/gov/client/cli" @@ -305,7 +306,7 @@ func (s *E2ETestSuite) TestCmdGetProposals() { tc := tc s.Run(tc.name, func() { - cmd := cli.GetCmdQueryProposals() + cmd := cli.GetCmdQueryProposals(address.NewBech32Codec("cosmos")) clientCtx := val.ClientCtx out, err := clitestutil.ExecTestCLICmd(clientCtx, cmd, tc.args) @@ -532,7 +533,7 @@ func (s *E2ETestSuite) TestCmdQueryVote() { for _, tc := range testCases { tc := tc s.Run(tc.name, func() { - cmd := cli.GetCmdQueryVote() + cmd := cli.GetCmdQueryVote(address.NewBech32Codec("cosmos")) clientCtx := val.ClientCtx out, err := clitestutil.ExecTestCLICmd(clientCtx, cmd, tc.args) diff --git a/tests/e2e/gov/tx.go b/tests/e2e/gov/tx.go index a8e06691133a..662c593a8aff 100644 --- a/tests/e2e/gov/tx.go +++ b/tests/e2e/gov/tx.go @@ -243,7 +243,7 @@ func (s *E2ETestSuite) TestNewCmdSubmitLegacyProposal() { { "valid transaction", []string{ - fmt.Sprintf("--%s='Text Proposal'", cli.FlagTitle), //nolint:staticcheck // we are intentionally using a deprecated flag here. + fmt.Sprintf("--%s='Text Proposal'", cli.FlagTitle), fmt.Sprintf("--%s='Where is the title!?'", cli.FlagDescription), //nolint:staticcheck // we are intentionally using a deprecated flag here. fmt.Sprintf("--%s=%s", cli.FlagProposalType, v1beta1.ProposalTypeText), //nolint:staticcheck // we are intentionally using a deprecated flag here. fmt.Sprintf("--%s=%s", cli.FlagDeposit, sdk.NewCoin(s.cfg.BondDenom, sdk.NewInt(5431)).String()), diff --git a/tests/e2e/group/query.go b/tests/e2e/group/query.go index 27c7b609e692..c4cbc4fbded9 100644 --- a/tests/e2e/group/query.go +++ b/tests/e2e/group/query.go @@ -393,7 +393,7 @@ func (s *E2ETestSuite) TestQueryGroupPolicyInfo() { "group policy not found", []string{val.Address.String(), fmt.Sprintf("--%s=json", flags.FlagOutput)}, true, - "group policy: not found", + "not found", 0, }, { diff --git a/tests/e2e/group/tx.go b/tests/e2e/group/tx.go index 6b6265c6c73b..86c02e38c946 100644 --- a/tests/e2e/group/tx.go +++ b/tests/e2e/group/tx.go @@ -4,13 +4,14 @@ import ( "encoding/base64" "encoding/json" "fmt" - "strconv" "strings" "github.com/cosmos/gogoproto/proto" "github.com/google/uuid" "github.com/stretchr/testify/suite" + // without this import amino json encoding will fail when resolving any types + _ "cosmossdk.io/api/cosmos/group/v1" "github.com/cosmos/cosmos-sdk/client/flags" "github.com/cosmos/cosmos-sdk/crypto/hd" "github.com/cosmos/cosmos-sdk/crypto/keyring" @@ -18,11 +19,9 @@ import ( clitestutil "github.com/cosmos/cosmos-sdk/testutil/cli" "github.com/cosmos/cosmos-sdk/testutil/network" sdk "github.com/cosmos/cosmos-sdk/types" - sdkerrors "github.com/cosmos/cosmos-sdk/types/errors" banktypes "github.com/cosmos/cosmos-sdk/x/bank/types" "github.com/cosmos/cosmos-sdk/x/group" client "github.com/cosmos/cosmos-sdk/x/group/client/cli" - "github.com/cosmos/cosmos-sdk/x/group/errors" ) type E2ETestSuite struct { @@ -41,2107 +40,59 @@ type E2ETestSuite struct { const validMetadata = "metadata" -var tooLongMetadata = strings.Repeat("A", 256) - func NewE2ETestSuite(cfg network.Config) *E2ETestSuite { return &E2ETestSuite{cfg: cfg} } -func (s *E2ETestSuite) SetupSuite() { - s.T().Log("setting up e2e test suite") - - s.commonFlags = []string{ - fmt.Sprintf("--%s=true", flags.FlagSkipConfirmation), - fmt.Sprintf("--%s=%s", flags.FlagBroadcastMode, flags.BroadcastSync), - fmt.Sprintf("--%s=%s", flags.FlagFees, sdk.NewCoins(sdk.NewCoin(s.cfg.BondDenom, sdk.NewInt(10))).String()), - } - - var err error - s.network, err = network.New(s.T(), s.T().TempDir(), s.cfg) - s.Require().NoError(err) - s.Require().NoError(s.network.WaitForNextBlock()) - - val := s.network.Validators[0] - - // create a new account - info, _, err := val.ClientCtx.Keyring.NewMnemonic("NewValidator", keyring.English, sdk.FullFundraiserPath, keyring.DefaultBIP39Passphrase, hd.Secp256k1) - s.Require().NoError(err) - - pk, err := info.GetPubKey() - s.Require().NoError(err) - - account := sdk.AccAddress(pk.Address()) - _, err = clitestutil.MsgSendExec( - val.ClientCtx, - val.Address, - account, - sdk.NewCoins(sdk.NewCoin(s.cfg.BondDenom, sdk.NewInt(2000))), fmt.Sprintf("--%s=true", flags.FlagSkipConfirmation), - fmt.Sprintf("--%s=%s", flags.FlagBroadcastMode, flags.BroadcastSync), - fmt.Sprintf("--%s=%s", flags.FlagFees, sdk.NewCoins(sdk.NewCoin(s.cfg.BondDenom, sdk.NewInt(10))).String()), - ) - s.Require().NoError(err) - s.Require().NoError(s.network.WaitForNextBlock()) - - memberWeight := "3" - // create a group - validMembers := fmt.Sprintf(` - { - "members": [ - { - "address": "%s", - "weight": "%s", - "metadata": "%s" - } - ] - }`, val.Address.String(), memberWeight, validMetadata) - validMembersFile := testutil.WriteToNewTempFile(s.T(), validMembers) - out, err := clitestutil.ExecTestCLICmd(val.ClientCtx, client.MsgCreateGroupCmd(), - append( - []string{ - val.Address.String(), - validMetadata, - validMembersFile.Name(), - }, - s.commonFlags..., - ), - ) - s.Require().NoError(err, out.String()) - txResp := sdk.TxResponse{} - s.Require().NoError(val.ClientCtx.Codec.UnmarshalJSON(out.Bytes(), &txResp), out.String()) - s.Require().NoError(clitestutil.CheckTxCode(s.network, val.ClientCtx, txResp.TxHash, 0)) - - s.group = &group.GroupInfo{Id: 1, Admin: val.Address.String(), Metadata: validMetadata, TotalWeight: "3", Version: 1} - - // create 5 group policies - for i := 0; i < 5; i++ { - threshold := i + 1 - if threshold > 3 { - threshold = 3 - } - - s.createGroupThresholdPolicyWithBalance(val.Address.String(), "1", threshold, 1000) - out, err = clitestutil.ExecTestCLICmd(val.ClientCtx, client.QueryGroupPoliciesByGroupCmd(), []string{"1", fmt.Sprintf("--%s=json", flags.FlagOutput)}) - s.Require().NoError(err, out.String()) - s.Require().NoError(s.network.WaitForNextBlock()) - } - percentage := 0.5 - // create group policy with percentage decision policy - out, err = clitestutil.ExecTestCLICmd(val.ClientCtx, client.MsgCreateGroupPolicyCmd(), - append( - []string{ - val.Address.String(), - "1", - validMetadata, - testutil.WriteToNewTempFile(s.T(), fmt.Sprintf(`{"@type":"/cosmos.group.v1.PercentageDecisionPolicy", "percentage":"%f", "windows":{"voting_period":"30000s"}}`, percentage)).Name(), - }, - s.commonFlags..., - ), - ) - s.Require().NoError(err, out.String()) - s.Require().NoError(val.ClientCtx.Codec.UnmarshalJSON(out.Bytes(), &txResp), out.String()) - s.Require().NoError(clitestutil.CheckTxCode(s.network, val.ClientCtx, txResp.TxHash, 0)) - - out, err = clitestutil.ExecTestCLICmd(val.ClientCtx, client.QueryGroupPoliciesByGroupCmd(), []string{"1", fmt.Sprintf("--%s=json", flags.FlagOutput)}) - s.Require().NoError(err, out.String()) - - var res group.QueryGroupPoliciesByGroupResponse - s.Require().NoError(val.ClientCtx.Codec.UnmarshalJSON(out.Bytes(), &res)) - s.Require().Equal(len(res.GroupPolicies), 6) - s.groupPolicies = res.GroupPolicies - - // create a proposal - out, err = clitestutil.ExecTestCLICmd(val.ClientCtx, client.MsgSubmitProposalCmd(), - append( - []string{ - s.createCLIProposal( - s.groupPolicies[0].Address, val.Address.String(), - s.groupPolicies[0].Address, val.Address.String(), - "", "title", "summary"), - }, - s.commonFlags..., - ), - ) - s.Require().NoError(err, out.String()) - s.Require().NoError(val.ClientCtx.Codec.UnmarshalJSON(out.Bytes(), &txResp), out.String()) - s.Require().NoError(clitestutil.CheckTxCode(s.network, val.ClientCtx, txResp.TxHash, 0)) - - // vote - out, err = clitestutil.ExecTestCLICmd(val.ClientCtx, client.MsgVoteCmd(), - append( - []string{ - "1", - val.Address.String(), - "VOTE_OPTION_YES", - "", - }, - s.commonFlags..., - ), - ) - s.Require().NoError(err, out.String()) - s.Require().NoError(val.ClientCtx.Codec.UnmarshalJSON(out.Bytes(), &txResp), out.String()) - s.Require().NoError(clitestutil.CheckTxCode(s.network, val.ClientCtx, txResp.TxHash, 0)) - - out, err = clitestutil.ExecTestCLICmd(val.ClientCtx, client.QueryProposalCmd(), []string{"1", fmt.Sprintf("--%s=json", flags.FlagOutput)}) - s.Require().NoError(err, out.String()) - - var proposalRes group.QueryProposalResponse - s.Require().NoError(val.ClientCtx.Codec.UnmarshalJSON(out.Bytes(), &proposalRes)) - s.proposal = proposalRes.Proposal - - out, err = clitestutil.ExecTestCLICmd(val.ClientCtx, client.QueryVoteByProposalVoterCmd(), []string{"1", val.Address.String(), fmt.Sprintf("--%s=json", flags.FlagOutput)}) - s.Require().NoError(err, out.String()) - - var voteRes group.QueryVoteByProposalVoterResponse - s.Require().NoError(val.ClientCtx.Codec.UnmarshalJSON(out.Bytes(), &voteRes)) - s.vote = voteRes.Vote - - s.voter = &group.Member{ - Address: val.Address.String(), - Weight: memberWeight, - Metadata: validMetadata, - } -} - -func (s *E2ETestSuite) TearDownSuite() { - s.T().Log("tearing down e2e test suite") - s.network.Cleanup() -} - -func (s *E2ETestSuite) TestTxCreateGroup() { - val := s.network.Validators[0] - clientCtx := val.ClientCtx - - validMembers := fmt.Sprintf(`{"members": [{ - "address": "%s", - "weight": "1", - "metadata": "%s" - }]}`, val.Address.String(), validMetadata) - validMembersFile := testutil.WriteToNewTempFile(s.T(), validMembers) - - invalidMembersAddress := `{"members": [{ - "address": "", - "weight": "1" -}]}` - invalidMembersAddressFile := testutil.WriteToNewTempFile(s.T(), invalidMembersAddress) - - invalidMembersWeight := fmt.Sprintf(`{"members": [{ - "address": "%s", - "weight": "0" - }]}`, val.Address.String()) - invalidMembersWeightFile := testutil.WriteToNewTempFile(s.T(), invalidMembersWeight) - - invalidMembersMetadata := fmt.Sprintf(`{"members": [{ - "address": "%s", - "weight": "1", - "metadata": "%s" - }]}`, val.Address.String(), tooLongMetadata) - invalidMembersMetadataFile := testutil.WriteToNewTempFile(s.T(), invalidMembersMetadata) - - testCases := []struct { - name string - args []string - expectErr bool - expectErrMsg string - respType proto.Message - expectedCode uint32 - }{ - { - "correct data", - append( - []string{ - val.Address.String(), - "", - validMembersFile.Name(), - }, - s.commonFlags..., - ), - false, - "", - &sdk.TxResponse{}, - 0, - }, - { - "with amino-json", - append( - []string{ - val.Address.String(), - "", - validMembersFile.Name(), - fmt.Sprintf("--%s=%s", flags.FlagSignMode, flags.SignModeLegacyAminoJSON), - }, - s.commonFlags..., - ), - false, - "", - &sdk.TxResponse{}, - 0, - }, - { - "group metadata too long", - append( - []string{ - val.Address.String(), - strings.Repeat("a", 256), - "", - }, - s.commonFlags..., - ), - false, - "group metadata: limit exceeded", - &sdk.TxResponse{}, - errors.ErrMaxLimit.ABCICode(), - }, - { - "invalid members address", - append( - []string{ - val.Address.String(), - "null", - invalidMembersAddressFile.Name(), - }, - s.commonFlags..., - ), - true, - "message validation failed: address: empty address string is not allowed", - nil, - 0, - }, - { - "invalid members weight", - append( - []string{ - val.Address.String(), - "null", - invalidMembersWeightFile.Name(), - }, - s.commonFlags..., - ), - true, - "expected a positive decimal, got 0: invalid decimal string", - nil, - 0, - }, - { - "members metadata too long", - append( - []string{ - val.Address.String(), - "null", - invalidMembersMetadataFile.Name(), - }, - s.commonFlags..., - ), - false, - "member metadata: limit exceeded", - &sdk.TxResponse{}, - errors.ErrMaxLimit.ABCICode(), - }, - } - - for _, tc := range testCases { - tc := tc - - s.Run(tc.name, func() { - cmd := client.MsgCreateGroupCmd() - - out, err := clitestutil.ExecTestCLICmd(clientCtx, cmd, tc.args) - if tc.expectErr { - s.Require().Contains(out.String(), tc.expectErrMsg) - } else { - s.Require().NoError(err, out.String()) - s.Require().NoError(clientCtx.Codec.UnmarshalJSON(out.Bytes(), tc.respType), out.String()) - - txResp, err := clitestutil.GetTxResponse(s.network, clientCtx, tc.respType.(*sdk.TxResponse).TxHash) - s.Require().NoError(err) - s.Require().Equal(txResp.Code, tc.expectedCode) - if tc.expectErrMsg != "" { - s.Require().Contains(txResp.RawLog, tc.expectErrMsg) - } - } - }) - } -} - -func (s *E2ETestSuite) TestTxUpdateGroupAdmin() { - val := s.network.Validators[0] - clientCtx := val.ClientCtx - - groupIDs := make([]string, 2) - for i := 0; i < 2; i++ { - validMembers := fmt.Sprintf(`{"members": [{ - "address": "%s", - "weight": "1", - "metadata": "%s" - }]}`, val.Address.String(), validMetadata) - validMembersFile := testutil.WriteToNewTempFile(s.T(), validMembers) - out, err := clitestutil.ExecTestCLICmd(val.ClientCtx, client.MsgCreateGroupCmd(), - append( - []string{ - val.Address.String(), - validMetadata, - validMembersFile.Name(), - }, - s.commonFlags..., - ), - ) - s.Require().NoError(err, out.String()) - var txResp sdk.TxResponse - s.Require().NoError(val.ClientCtx.Codec.UnmarshalJSON(out.Bytes(), &txResp), out.String()) - txResp, err = clitestutil.GetTxResponse(s.network, val.ClientCtx, txResp.TxHash) - s.Require().NoError(err) - s.Require().Equal(txResp.Code, uint32(0), out.String()) - groupIDs[i] = s.getGroupIDFromTxResponse(txResp) - } - - testCases := []struct { - name string - args []string - expectErr bool - expectErrMsg string - respType proto.Message - expectedCode uint32 - }{ - { - "correct data", - append( - []string{ - val.Address.String(), - groupIDs[0], - s.network.Validators[1].Address.String(), - }, - s.commonFlags..., - ), - false, - "", - &sdk.TxResponse{}, - 0, - }, - { - "with amino-json", - append( - []string{ - val.Address.String(), - groupIDs[1], - s.network.Validators[1].Address.String(), - fmt.Sprintf("--%s=%s", flags.FlagSignMode, flags.SignModeLegacyAminoJSON), - }, - s.commonFlags..., - ), - false, - "", - &sdk.TxResponse{}, - 0, - }, - { - "group id invalid", - append( - []string{ - val.Address.String(), - "", - s.network.Validators[1].Address.String(), - }, - s.commonFlags..., - ), - true, - "strconv.ParseUint: parsing \"\": invalid syntax", - nil, - 0, - }, - { - "group doesn't exist", - append( - []string{ - val.Address.String(), - "12345", - s.network.Validators[1].Address.String(), - }, - s.commonFlags..., - ), - false, - "not found", - &sdk.TxResponse{}, - sdkerrors.ErrNotFound.ABCICode(), - }, - } - - for _, tc := range testCases { - tc := tc - - s.Run(tc.name, func() { - cmd := client.MsgUpdateGroupAdminCmd() - - out, err := clitestutil.ExecTestCLICmd(clientCtx, cmd, tc.args) - if tc.expectErr { - s.Require().Contains(out.String(), tc.expectErrMsg) - } else { - s.Require().NoError(err, out.String()) - s.Require().NoError(clientCtx.Codec.UnmarshalJSON(out.Bytes(), tc.respType), out.String()) - - txResp, err := clitestutil.GetTxResponse(s.network, clientCtx, tc.respType.(*sdk.TxResponse).TxHash) - s.Require().NoError(err) - s.Require().Equal(txResp.Code, tc.expectedCode) - if tc.expectErrMsg != "" { - s.Require().Contains(txResp.RawLog, tc.expectErrMsg) - } - } - }) - } -} - -func (s *E2ETestSuite) TestTxUpdateGroupMetadata() { - val := s.network.Validators[0] - clientCtx := val.ClientCtx - - testCases := []struct { - name string - args []string - expectErr bool - expectErrMsg string - respType proto.Message - expectedCode uint32 - }{ - { - "correct data", - append( - []string{ - val.Address.String(), - "1", - validMetadata, - }, - s.commonFlags..., - ), - false, - "", - &sdk.TxResponse{}, - 0, - }, - { - "with amino-json", - append( - []string{ - val.Address.String(), - "1", - validMetadata, - fmt.Sprintf("--%s=%s", flags.FlagSignMode, flags.SignModeLegacyAminoJSON), - }, - s.commonFlags..., - ), - false, - "", - &sdk.TxResponse{}, - 0, - }, - { - "group metadata too long", - append( - []string{ - val.Address.String(), - strconv.FormatUint(s.group.Id, 10), - strings.Repeat("a", 256), - }, - s.commonFlags..., - ), - false, - "group metadata: limit exceeded", - &sdk.TxResponse{}, - errors.ErrMaxLimit.ABCICode(), - }, - } - - for _, tc := range testCases { - tc := tc - - s.Run(tc.name, func() { - cmd := client.MsgUpdateGroupMetadataCmd() - - out, err := clitestutil.ExecTestCLICmd(clientCtx, cmd, tc.args) - if tc.expectErr { - s.Require().Contains(out.String(), tc.expectErrMsg) - } else { - s.Require().NoError(err, out.String()) - s.Require().NoError(clientCtx.Codec.UnmarshalJSON(out.Bytes(), tc.respType), out.String()) - - txResp, err := clitestutil.GetTxResponse(s.network, clientCtx, tc.respType.(*sdk.TxResponse).TxHash) - s.Require().NoError(err) - s.Require().Equal(txResp.Code, tc.expectedCode) - if tc.expectErrMsg != "" { - s.Require().Contains(txResp.RawLog, tc.expectErrMsg) - } - } - }) - } -} - -func (s *E2ETestSuite) TestTxUpdateGroupMembers() { - val := s.network.Validators[0] - clientCtx := val.ClientCtx - - weights := []string{"1", "1", "1"} - accounts := s.createAccounts(3) - - groupID := s.createGroupWithMembers(weights, accounts) - groupPolicyAddress := s.createGroupThresholdPolicyWithBalance(accounts[0], groupID, 3, 100) - - validUpdatedMembersFileName := testutil.WriteToNewTempFile(s.T(), fmt.Sprintf(`{"members": [{ - "address": "%s", - "weight": "0", - "metadata": "%s" - }, { - "address": "%s", - "weight": "1", - "metadata": "%s" - }]}`, accounts[0], validMetadata, groupPolicyAddress, validMetadata)).Name() - - invalidMembersMetadata := fmt.Sprintf(`{"members": [{ - "address": "%s", - "weight": "1", - "metadata": "%s" - }]}`, accounts[0], tooLongMetadata) - invalidMembersMetadataFileName := testutil.WriteToNewTempFile(s.T(), invalidMembersMetadata).Name() - - testCases := []struct { - name string - args []string - expectErr bool - expectErrMsg string - respType proto.Message - expectedCode uint32 - }{ - { - "correct data", - append( - []string{ - accounts[0], - groupID, - validUpdatedMembersFileName, - }, - s.commonFlags..., - ), - false, - "", - &sdk.TxResponse{}, - 0, - }, - { - "with amino-json", - append( - []string{ - accounts[0], - groupID, - testutil.WriteToNewTempFile(s.T(), fmt.Sprintf(`{"members": [{ - "address": "%s", - "weight": "2", - "metadata": "%s" - }]}`, s.groupPolicies[0].Address, validMetadata)).Name(), - fmt.Sprintf("--%s=%s", flags.FlagSignMode, flags.SignModeLegacyAminoJSON), - }, - s.commonFlags..., - ), - false, - "", - &sdk.TxResponse{}, - 0, - }, - { - "group member metadata too long", - append( - []string{ - accounts[0], - groupID, - invalidMembersMetadataFileName, - }, - s.commonFlags..., - ), - false, - "group member metadata: limit exceeded", - &sdk.TxResponse{}, - errors.ErrMaxLimit.ABCICode(), - }, - { - "group doesn't exist", - append( - []string{ - accounts[0], - "12345", - validUpdatedMembersFileName, - }, - s.commonFlags..., - ), - false, - "not found", - &sdk.TxResponse{}, - sdkerrors.ErrNotFound.ABCICode(), - }, - } - - for _, tc := range testCases { - tc := tc - - s.Run(tc.name, func() { - cmd := client.MsgUpdateGroupMembersCmd() - - out, err := clitestutil.ExecTestCLICmd(clientCtx, cmd, tc.args) - if tc.expectErr { - s.Require().Contains(out.String(), tc.expectErrMsg) - } else { - s.Require().NoError(err, out.String()) - s.Require().NoError(clientCtx.Codec.UnmarshalJSON(out.Bytes(), tc.respType), out.String()) - - txResp, err := clitestutil.GetTxResponse(s.network, clientCtx, tc.respType.(*sdk.TxResponse).TxHash) - s.Require().NoError(err) - s.Require().Equal(txResp.Code, tc.expectedCode) - if tc.expectErrMsg != "" { - s.Require().Contains(txResp.RawLog, tc.expectErrMsg) - } - } - }) - } -} - -func (s *E2ETestSuite) TestTxCreateGroupWithPolicy() { - val := s.network.Validators[0] - clientCtx := val.ClientCtx - - validMembers := fmt.Sprintf(`{"members": [{ - "address": "%s", - "weight": "1", - "metadata": "%s" - }]}`, val.Address.String(), validMetadata) - validMembersFile := testutil.WriteToNewTempFile(s.T(), validMembers) - - invalidMembersAddress := `{"members": [{ - "address": "", - "weight": "1" - }]}` - invalidMembersAddressFile := testutil.WriteToNewTempFile(s.T(), invalidMembersAddress) - - invalidMembersWeight := fmt.Sprintf(`{"members": [{ - "address": "%s", - "weight": "0" - }]}`, val.Address.String()) - invalidMembersWeightFile := testutil.WriteToNewTempFile(s.T(), invalidMembersWeight) - - invalidMembersMetadata := fmt.Sprintf(`{"members": [{ - "address": "%s", - "weight": "1", - "metadata": "%s" - }]}`, val.Address.String(), tooLongMetadata) - invalidMembersMetadataFile := testutil.WriteToNewTempFile(s.T(), invalidMembersMetadata) - - thresholdDecisionPolicyFile := testutil.WriteToNewTempFile(s.T(), `{"@type": "/cosmos.group.v1.ThresholdDecisionPolicy","threshold": "1","windows": {"voting_period":"1s"}}`) - - testCases := []struct { - name string - args []string - expectErr bool - expectErrMsg string - respType proto.Message - expectedCode uint32 - }{ - { - "correct data", - append( - []string{ - val.Address.String(), - validMetadata, - validMetadata, - validMembersFile.Name(), - thresholdDecisionPolicyFile.Name(), - fmt.Sprintf("--%s=%v", client.FlagGroupPolicyAsAdmin, false), - }, - s.commonFlags..., - ), - false, - "", - &sdk.TxResponse{}, - 0, - }, - { - "group-policy-as-admin is true", - append( - []string{ - val.Address.String(), - validMetadata, - validMetadata, - validMembersFile.Name(), - thresholdDecisionPolicyFile.Name(), - fmt.Sprintf("--%s=%v", client.FlagGroupPolicyAsAdmin, true), - }, - s.commonFlags..., - ), - false, - "", - &sdk.TxResponse{}, - 0, - }, - { - "with amino-json", - append( - []string{ - val.Address.String(), - validMetadata, - validMetadata, - validMembersFile.Name(), - thresholdDecisionPolicyFile.Name(), - fmt.Sprintf("--%s=%v", client.FlagGroupPolicyAsAdmin, false), - fmt.Sprintf("--%s=%s", flags.FlagSignMode, flags.SignModeLegacyAminoJSON), - }, - s.commonFlags..., - ), - false, - "", - &sdk.TxResponse{}, - 0, - }, - { - "group metadata too long", - append( - []string{ - val.Address.String(), - strings.Repeat("a", 256), - validMetadata, - validMembersFile.Name(), - thresholdDecisionPolicyFile.Name(), - fmt.Sprintf("--%s=%v", client.FlagGroupPolicyAsAdmin, false), - }, - s.commonFlags..., - ), - false, - "group metadata: limit exceeded", - &sdk.TxResponse{}, - errors.ErrMaxLimit.ABCICode(), - }, - { - "group policy metadata too long", - append( - []string{ - val.Address.String(), - validMetadata, - strings.Repeat("a", 256), - validMembersFile.Name(), - thresholdDecisionPolicyFile.Name(), - fmt.Sprintf("--%s=%v", client.FlagGroupPolicyAsAdmin, false), - }, - s.commonFlags..., - ), - false, - "group policy metadata: limit exceeded", - &sdk.TxResponse{}, - errors.ErrMaxLimit.ABCICode(), - }, - { - "invalid members address", - append( - []string{ - val.Address.String(), - validMetadata, - validMetadata, - invalidMembersAddressFile.Name(), - thresholdDecisionPolicyFile.Name(), - fmt.Sprintf("--%s=%v", client.FlagGroupPolicyAsAdmin, false), - }, - s.commonFlags..., - ), - true, - "message validation failed: address: empty address string is not allowed", - nil, - 0, - }, - { - "invalid members weight", - append( - []string{ - val.Address.String(), - validMetadata, - validMetadata, - invalidMembersWeightFile.Name(), - thresholdDecisionPolicyFile.Name(), - fmt.Sprintf("--%s=%v", client.FlagGroupPolicyAsAdmin, false), - }, - s.commonFlags..., - ), - true, - "expected a positive decimal, got 0: invalid decimal string", - nil, - 0, - }, - { - "members metadata too long", - append( - []string{ - val.Address.String(), - validMetadata, - validMetadata, - invalidMembersMetadataFile.Name(), - thresholdDecisionPolicyFile.Name(), - fmt.Sprintf("--%s=%v", client.FlagGroupPolicyAsAdmin, false), - }, - s.commonFlags..., - ), - false, - "member metadata: limit exceeded", - &sdk.TxResponse{}, - errors.ErrMaxLimit.ABCICode(), - }, - } - for _, tc := range testCases { - tc := tc - - s.Run(tc.name, func() { - cmd := client.MsgCreateGroupWithPolicyCmd() - - out, err := clitestutil.ExecTestCLICmd(clientCtx, cmd, tc.args) - if tc.expectErr { - s.Require().Contains(out.String(), tc.expectErrMsg) - } else { - s.Require().NoError(err, out.String()) - s.Require().NoError(clientCtx.Codec.UnmarshalJSON(out.Bytes(), tc.respType), out.String()) - - txResp, err := clitestutil.GetTxResponse(s.network, clientCtx, tc.respType.(*sdk.TxResponse).TxHash) - s.Require().NoError(err) - s.Require().Equal(txResp.Code, tc.expectedCode) - if tc.expectErrMsg != "" { - s.Require().Contains(txResp.RawLog, tc.expectErrMsg) - } - } - }) - } -} - -func (s *E2ETestSuite) TestTxCreateGroupPolicy() { - val := s.network.Validators[0] - wrongAdmin := s.network.Validators[1].Address - clientCtx := val.ClientCtx - - groupID := s.group.Id - - thresholdDecisionPolicyFile := testutil.WriteToNewTempFile(s.T(), `{"@type": "/cosmos.group.v1.ThresholdDecisionPolicy","threshold": "1","windows": {"voting_period":"1s"}}`) - - testCases := []struct { - name string - args []string - expectErr bool - expectErrMsg string - respType proto.Message - expectedCode uint32 - }{ - { - "correct data", - append( - []string{ - val.Address.String(), - fmt.Sprintf("%v", groupID), - validMetadata, - thresholdDecisionPolicyFile.Name(), - }, - s.commonFlags..., - ), - false, - "", - &sdk.TxResponse{}, - 0, - }, - { - "correct data with percentage decision policy", - append( - []string{ - val.Address.String(), - fmt.Sprintf("%v", groupID), - validMetadata, - testutil.WriteToNewTempFile(s.T(), `{"@type":"/cosmos.group.v1.PercentageDecisionPolicy", "percentage":"0.5", "windows":{"voting_period":"1s"}}`).Name(), - }, - s.commonFlags..., - ), - false, - "", - &sdk.TxResponse{}, - 0, - }, - { - "with amino-json", - append( - []string{ - val.Address.String(), - fmt.Sprintf("%v", groupID), - validMetadata, - thresholdDecisionPolicyFile.Name(), - fmt.Sprintf("--%s=%s", flags.FlagSignMode, flags.SignModeLegacyAminoJSON), - }, - s.commonFlags..., - ), - false, - "", - &sdk.TxResponse{}, - 0, - }, - { - "wrong admin", - append( - []string{ - wrongAdmin.String(), - fmt.Sprintf("%v", groupID), - validMetadata, - thresholdDecisionPolicyFile.Name(), - }, - s.commonFlags..., - ), - true, - "key not found", - &sdk.TxResponse{}, - 0, - }, - { - "metadata too long", - append( - []string{ - val.Address.String(), - fmt.Sprintf("%v", groupID), - strings.Repeat("a", 500), - thresholdDecisionPolicyFile.Name(), - }, - s.commonFlags..., - ), - false, - "group policy metadata: limit exceeded", - &sdk.TxResponse{}, - errors.ErrMaxLimit.ABCICode(), - }, - { - "wrong group id", - append( - []string{ - val.Address.String(), - "10", - validMetadata, - thresholdDecisionPolicyFile.Name(), - }, - s.commonFlags..., - ), - false, - "not found", - &sdk.TxResponse{}, - sdkerrors.ErrNotFound.ABCICode(), - }, - { - "invalid percentage decision policy with negative value", - append( - []string{ - val.Address.String(), - fmt.Sprintf("%v", groupID), - validMetadata, - testutil.WriteToNewTempFile(s.T(), `{"@type":"/cosmos.group.v1.PercentageDecisionPolicy", "percentage":"-0.5", "windows":{"voting_period":"1s"}}`).Name(), - }, - s.commonFlags..., - ), - true, - "expected a positive decimal", - &sdk.TxResponse{}, - 0, - }, - { - "invalid percentage decision policy with value greater than 1", - append( - []string{ - val.Address.String(), - fmt.Sprintf("%v", groupID), - validMetadata, - testutil.WriteToNewTempFile(s.T(), `{"@type":"/cosmos.group.v1.PercentageDecisionPolicy", "percentage":"2", "windows":{"voting_period":"1s"}}`).Name(), - }, - s.commonFlags..., - ), - true, - "percentage must be > 0 and <= 1", - &sdk.TxResponse{}, - 0, - }, - } - - for _, tc := range testCases { - tc := tc - - s.Run(tc.name, func() { - cmd := client.MsgCreateGroupPolicyCmd() - - out, err := clitestutil.ExecTestCLICmd(clientCtx, cmd, tc.args) - if tc.expectErr { - s.Require().Contains(out.String(), tc.expectErrMsg) - } else { - s.Require().NoError(err, out.String()) - s.Require().NoError(clientCtx.Codec.UnmarshalJSON(out.Bytes(), tc.respType), out.String()) - - txResp, err := clitestutil.GetTxResponse(s.network, clientCtx, tc.respType.(*sdk.TxResponse).TxHash) - s.Require().NoError(err) - s.Require().Equal(txResp.Code, tc.expectedCode) - if tc.expectErrMsg != "" { - s.Require().Contains(txResp.RawLog, tc.expectErrMsg) - } - } - }) - } -} - -func (s *E2ETestSuite) TestTxUpdateGroupPolicyAdmin() { - val := s.network.Validators[0] - newAdmin := s.network.Validators[1].Address - clientCtx := val.ClientCtx - groupPolicy := s.groupPolicies[3] - - commonFlags := s.commonFlags - commonFlags = append(commonFlags, fmt.Sprintf("--%s=%d", flags.FlagGas, 300000)) - - testCases := []struct { - name string - args []string - expectErr bool - expectErrMsg string - respType proto.Message - expectedCode uint32 - }{ - { - "correct data", - append( - []string{ - groupPolicy.Admin, - groupPolicy.Address, - newAdmin.String(), - }, - commonFlags..., - ), - false, - "", - &sdk.TxResponse{}, - 0, - }, - { - "with amino-json", - append( - []string{ - groupPolicy.Admin, - s.groupPolicies[4].Address, - newAdmin.String(), - fmt.Sprintf("--%s=%s", flags.FlagSignMode, flags.SignModeLegacyAminoJSON), - }, - commonFlags..., - ), - false, - "", - &sdk.TxResponse{}, - 0, - }, - { - "wrong admin", - append( - []string{ - newAdmin.String(), - groupPolicy.Address, - newAdmin.String(), - }, - commonFlags..., - ), - true, - "key not found", - &sdk.TxResponse{}, - 0, - }, - { - "wrong group policy", - append( - []string{ - groupPolicy.Admin, - newAdmin.String(), - newAdmin.String(), - }, - commonFlags..., - ), - false, - "load group policy: not found", - &sdk.TxResponse{}, - sdkerrors.ErrNotFound.ABCICode(), - }, - } - - for _, tc := range testCases { - tc := tc - - s.Run(tc.name, func() { - cmd := client.MsgUpdateGroupPolicyAdminCmd() - - out, err := clitestutil.ExecTestCLICmd(clientCtx, cmd, tc.args) - if tc.expectErr { - s.Require().Contains(out.String(), tc.expectErrMsg) - } else { - s.Require().NoError(err, out.String()) - s.Require().NoError(clientCtx.Codec.UnmarshalJSON(out.Bytes(), tc.respType), out.String()) - - txResp := tc.respType.(*sdk.TxResponse) - s.Require().NoError(clitestutil.CheckTxCode(s.network, clientCtx, txResp.TxHash, tc.expectedCode)) - } - }) - } -} - -func (s *E2ETestSuite) TestTxUpdateGroupPolicyDecisionPolicy() { - val := s.network.Validators[0] - newAdmin := s.network.Validators[1].Address - clientCtx := val.ClientCtx - groupPolicy := s.groupPolicies[2] - - commonFlags := s.commonFlags - commonFlags = append(commonFlags, fmt.Sprintf("--%s=%d", flags.FlagGas, 300000)) - - testCases := []struct { - name string - args []string - expectErr bool - expectErrMsg string - respType proto.Message - expectedCode uint32 - }{ - { - "correct data", - append( - []string{ - groupPolicy.Admin, - groupPolicy.Address, - testutil.WriteToNewTempFile(s.T(), `{"@type":"/cosmos.group.v1.ThresholdDecisionPolicy", "threshold":"1", "windows":{"voting_period":"40000s"}}`).Name(), - }, - commonFlags..., - ), - false, - "", - &sdk.TxResponse{}, - 0, - }, - { - "correct data with percentage decision policy", - append( - []string{ - groupPolicy.Admin, - groupPolicy.Address, - testutil.WriteToNewTempFile(s.T(), `{"@type":"/cosmos.group.v1.PercentageDecisionPolicy", "percentage":"0.5", "windows":{"voting_period":"40000s"}}`).Name(), - }, - commonFlags..., - ), - false, - "", - &sdk.TxResponse{}, - 0, - }, - { - "with amino-json", - append( - []string{ - groupPolicy.Admin, - groupPolicy.Address, - testutil.WriteToNewTempFile(s.T(), `{"@type":"/cosmos.group.v1.ThresholdDecisionPolicy", "threshold":"1", "windows":{"voting_period":"50000s"}}`).Name(), - fmt.Sprintf("--%s=%s", flags.FlagSignMode, flags.SignModeLegacyAminoJSON), - }, - commonFlags..., - ), - false, - "", - &sdk.TxResponse{}, - 0, - }, - { - "wrong admin", - append( - []string{ - newAdmin.String(), - groupPolicy.Address, - testutil.WriteToNewTempFile(s.T(), `{"@type":"/cosmos.group.v1.ThresholdDecisionPolicy", "threshold":"1", "windows":{"voting_period":"1s"}}`).Name(), - }, - commonFlags..., - ), - true, - "key not found", - &sdk.TxResponse{}, - 0, - }, - { - "wrong group policy", - append( - []string{ - groupPolicy.Admin, - newAdmin.String(), - testutil.WriteToNewTempFile(s.T(), `{"@type":"/cosmos.group.v1.ThresholdDecisionPolicy", "threshold":"1", "windows":{"voting_period":"1s"}}`).Name(), - }, - commonFlags..., - ), - false, - "load group policy: not found", - &sdk.TxResponse{}, - sdkerrors.ErrNotFound.ABCICode(), - }, - { - "invalid percentage decision policy with negative value", - append( - []string{ - groupPolicy.Admin, - groupPolicy.Address, - testutil.WriteToNewTempFile(s.T(), `{"@type":"/cosmos.group.v1.PercentageDecisionPolicy", "percentage":"-0.5", "windows":{"voting_period":"1s"}}`).Name(), - }, - commonFlags..., - ), - true, - "expected a positive decimal", - &sdk.TxResponse{}, - 0, - }, - { - "invalid percentage decision policy with value greater than 1", - append( - []string{ - groupPolicy.Admin, - groupPolicy.Address, - testutil.WriteToNewTempFile(s.T(), `{"@type":"/cosmos.group.v1.PercentageDecisionPolicy", "percentage":"2", "windows":{"voting_period":"40000s"}}`).Name(), - }, - commonFlags..., - ), - true, - "percentage must be > 0 and <= 1", - &sdk.TxResponse{}, - 0, - }, - } - - for _, tc := range testCases { - tc := tc - - s.Run(tc.name, func() { - cmd := client.MsgUpdateGroupPolicyDecisionPolicyCmd() - - out, err := clitestutil.ExecTestCLICmd(clientCtx, cmd, tc.args) - if tc.expectErr { - s.Require().Contains(out.String(), tc.expectErrMsg) - } else { - s.Require().NoError(err, out.String()) - s.Require().NoError(clientCtx.Codec.UnmarshalJSON(out.Bytes(), tc.respType), out.String()) - - txResp := tc.respType.(*sdk.TxResponse) - s.Require().NoError(clitestutil.CheckTxCode(s.network, clientCtx, txResp.TxHash, tc.expectedCode)) - } - }) - } -} - -func (s *E2ETestSuite) TestTxUpdateGroupPolicyMetadata() { - val := s.network.Validators[0] - newAdmin := s.network.Validators[1].Address - clientCtx := val.ClientCtx - groupPolicy := s.groupPolicies[2] - - commonFlags := s.commonFlags - commonFlags = append(commonFlags, fmt.Sprintf("--%s=%d", flags.FlagGas, 300000)) - - testCases := []struct { - name string - args []string - expectErr bool - expectErrMsg string - respType proto.Message - expectedCode uint32 - }{ - { - "correct data", - append( - []string{ - groupPolicy.Admin, - groupPolicy.Address, - validMetadata, - }, - commonFlags..., - ), - false, - "", - &sdk.TxResponse{}, - 0, - }, - { - "with amino-json", - append( - []string{ - groupPolicy.Admin, - groupPolicy.Address, - validMetadata, - fmt.Sprintf("--%s=%s", flags.FlagSignMode, flags.SignModeLegacyAminoJSON), - }, - commonFlags..., - ), - false, - "", - &sdk.TxResponse{}, - 0, - }, - { - "long metadata", - append( - []string{ - groupPolicy.Admin, - groupPolicy.Address, - strings.Repeat("a", 500), - }, - commonFlags..., - ), - false, - "group policy metadata: limit exceeded", - &sdk.TxResponse{}, - errors.ErrMaxLimit.ABCICode(), - }, - { - "wrong admin", - append( - []string{ - newAdmin.String(), - groupPolicy.Address, - validMetadata, - }, - commonFlags..., - ), - true, - "key not found", - &sdk.TxResponse{}, - 0, - }, - { - "wrong group policy", - append( - []string{ - groupPolicy.Admin, - newAdmin.String(), - validMetadata, - }, - commonFlags..., - ), - false, - "load group policy: not found", - &sdk.TxResponse{}, - sdkerrors.ErrNotFound.ABCICode(), - }, - } - - for _, tc := range testCases { - tc := tc - - s.Run(tc.name, func() { - cmd := client.MsgUpdateGroupPolicyMetadataCmd() - - out, err := clitestutil.ExecTestCLICmd(clientCtx, cmd, tc.args) - if tc.expectErr { - s.Require().Contains(out.String(), tc.expectErrMsg) - } else { - s.Require().NoError(err, out.String()) - s.Require().NoError(clientCtx.Codec.UnmarshalJSON(out.Bytes(), tc.respType), out.String()) - - txResp, err := clitestutil.GetTxResponse(s.network, clientCtx, tc.respType.(*sdk.TxResponse).TxHash) - s.Require().NoError(err) - s.Require().Equal(txResp.Code, tc.expectedCode) - if tc.expectErrMsg != "" { - s.Require().Contains(txResp.RawLog, tc.expectErrMsg) - } - } - }) - } -} - -func (s *E2ETestSuite) TestTxSubmitProposal() { - val := s.network.Validators[0] - clientCtx := val.ClientCtx - - testCases := []struct { - name string - args []string - expectErr bool - expectErrMsg string - respType proto.Message - expectedCode uint32 - }{ - { - "correct data", - append( - []string{ - s.createCLIProposal( - s.groupPolicies[0].Address, val.Address.String(), - s.groupPolicies[0].Address, val.Address.String(), - "", - "title", "summary", - ), - }, - s.commonFlags..., - ), - false, - "", - &sdk.TxResponse{}, - 0, - }, - { - "with try exec", - append( - []string{ - s.createCLIProposal( - s.groupPolicies[0].Address, val.Address.String(), - s.groupPolicies[0].Address, val.Address.String(), - "", - "title", "summary", - ), - fmt.Sprintf("--%s=try", client.FlagExec), - }, - s.commonFlags..., - ), - false, - "", - &sdk.TxResponse{}, - 0, - }, - { - "with try exec, not enough yes votes for proposal to pass", - append( - []string{ - s.createCLIProposal( - s.groupPolicies[3].Address, val.Address.String(), - s.groupPolicies[3].Address, val.Address.String(), - "", "title", "summary"), - fmt.Sprintf("--%s=try", client.FlagExec), - }, - s.commonFlags..., - ), - false, - "", - &sdk.TxResponse{}, - 0, - }, - { - "with amino-json", - append( - []string{ - s.createCLIProposal( - s.groupPolicies[0].Address, val.Address.String(), - s.groupPolicies[0].Address, val.Address.String(), - "", "title", "summary", - ), - fmt.Sprintf("--%s=%s", flags.FlagSignMode, flags.SignModeLegacyAminoJSON), - }, - s.commonFlags..., - ), - false, - "", - &sdk.TxResponse{}, - 0, - }, - { - "metadata too long", - append( - []string{ - s.createCLIProposal( - s.groupPolicies[0].Address, val.Address.String(), - s.groupPolicies[0].Address, val.Address.String(), - tooLongMetadata, "title", "summary", - ), - }, - s.commonFlags..., - ), - false, - "metadata: limit exceeded", - &sdk.TxResponse{}, - errors.ErrMaxLimit.ABCICode(), - }, - { - "unauthorized msg", - append( - []string{ - s.createCLIProposal( - s.groupPolicies[0].Address, val.Address.String(), - val.Address.String(), s.groupPolicies[0].Address, - "", "title", "summary"), - }, - s.commonFlags..., - ), - false, - "msg does not have group policy authorization", - &sdk.TxResponse{}, - sdkerrors.ErrUnauthorized.ABCICode(), - }, - { - "invalid proposers", - append( - []string{ - s.createCLIProposal( - s.groupPolicies[0].Address, "invalid", - s.groupPolicies[0].Address, val.Address.String(), - "", "title", "summary", - ), - }, - s.commonFlags..., - ), - true, - "invalid.info: key not found", - nil, - 0, - }, - { - "invalid group policy", - append( - []string{ - s.createCLIProposal( - "invalid", val.Address.String(), - s.groupPolicies[0].Address, val.Address.String(), - "", "title", "summary", - ), - }, - s.commonFlags..., - ), - true, - "group policy: decoding bech32 failed", - nil, - 0, - }, - { - "no group policy", - append( - []string{ - s.createCLIProposal( - val.Address.String(), val.Address.String(), - s.groupPolicies[0].Address, val.Address.String(), - "", "title", "summary", - ), - }, - s.commonFlags..., - ), - false, - "group policy: not found", - &sdk.TxResponse{}, - sdkerrors.ErrNotFound.ABCICode(), - }, - } - - for _, tc := range testCases { - tc := tc - - s.Run(tc.name, func() { - cmd := client.MsgSubmitProposalCmd() - - out, err := clitestutil.ExecTestCLICmd(clientCtx, cmd, tc.args) - if tc.expectErr { - s.Require().Contains(out.String(), tc.expectErrMsg) - } else { - s.Require().NoError(err, out.String()) - s.Require().NoError(clientCtx.Codec.UnmarshalJSON(out.Bytes(), tc.respType), out.String()) - - txResp, err := clitestutil.GetTxResponse(s.network, clientCtx, tc.respType.(*sdk.TxResponse).TxHash) - s.Require().NoError(err) - s.Require().Equal(txResp.Code, tc.expectedCode) - if tc.expectErrMsg != "" { - s.Require().Contains(txResp.RawLog, tc.expectErrMsg) - } - } - }) - } -} - -func (s *E2ETestSuite) TestTxVote() { - val := s.network.Validators[0] - clientCtx := val.ClientCtx - - ids := make([]string, 4) - weights := []string{"1", "1", "1"} - accounts := s.createAccounts(3) - - groupID := s.createGroupWithMembers(weights, accounts) - groupPolicyAddress := s.createGroupThresholdPolicyWithBalance(accounts[0], groupID, 3, 100) - - for i := 0; i < 4; i++ { - out, err := clitestutil.ExecTestCLICmd(val.ClientCtx, client.MsgSubmitProposalCmd(), - append( - []string{ - s.createCLIProposal( - groupPolicyAddress, accounts[0], - groupPolicyAddress, accounts[0], - "", "title", "summary", - ), - }, - s.commonFlags..., - ), - ) - s.Require().NoError(err, out.String()) - - var txResp sdk.TxResponse - s.Require().NoError(val.ClientCtx.Codec.UnmarshalJSON(out.Bytes(), &txResp), out.String()) - txResp, err = clitestutil.GetTxResponse(s.network, val.ClientCtx, txResp.TxHash) - s.Require().NoError(err) - s.Require().Equal(txResp.Code, uint32(0), out.String()) - ids[i] = s.getProposalIDFromTxResponse(txResp) - } - - testCases := []struct { - name string - args []string - expectErr bool - expectErrMsg string - respType proto.Message - expectedCode uint32 - }{ - { - "correct data", - append( - []string{ - ids[0], - accounts[0], - "VOTE_OPTION_YES", - "", - }, - s.commonFlags..., - ), - false, - "", - &sdk.TxResponse{}, - 0, - }, - { - "with try exec", - append( - []string{ - ids[1], - accounts[0], - "VOTE_OPTION_YES", - "", - fmt.Sprintf("--%s=try", client.FlagExec), - }, - s.commonFlags..., - ), - false, - "", - &sdk.TxResponse{}, - 0, - }, - { - "with try exec, not enough yes votes for proposal to pass", - append( - []string{ - ids[2], - accounts[0], - "VOTE_OPTION_NO", - "", - fmt.Sprintf("--%s=try", client.FlagExec), - }, - s.commonFlags..., - ), - false, - "", - &sdk.TxResponse{}, - 0, - }, - { - "with amino-json", - append( - []string{ - ids[3], - accounts[0], - "VOTE_OPTION_YES", - "", - fmt.Sprintf("--%s=%s", flags.FlagSignMode, flags.SignModeLegacyAminoJSON), - }, - s.commonFlags..., - ), - false, - "", - &sdk.TxResponse{}, - 0, - }, - { - "invalid proposal id", - append( - []string{ - "abcd", - accounts[0], - "VOTE_OPTION_YES", - "", - }, - s.commonFlags..., - ), - true, - "invalid syntax", - nil, - 0, - }, - { - "proposal not found", - append( - []string{ - "1234", - accounts[0], - "VOTE_OPTION_YES", - "", - }, - s.commonFlags..., - ), - false, - "proposal: not found", - &sdk.TxResponse{}, - sdkerrors.ErrNotFound.ABCICode(), - }, - { - "metadata too long", - append( - []string{ - "2", - accounts[0], - "VOTE_OPTION_YES", - tooLongMetadata, - }, - s.commonFlags..., - ), - false, - "metadata: limit exceeded", - &sdk.TxResponse{}, - errors.ErrMaxLimit.ABCICode(), - }, - { - "invalid vote option", - append( - []string{ - "2", - accounts[0], - "INVALID_VOTE_OPTION", - "", - }, - s.commonFlags..., - ), - true, - "not a valid vote option", - nil, - 0, - }, - } - - for _, tc := range testCases { - tc := tc - - s.Run(tc.name, func() { - cmd := client.MsgVoteCmd() - - out, err := clitestutil.ExecTestCLICmd(clientCtx, cmd, tc.args) - if tc.expectErr { - s.Require().Contains(out.String(), tc.expectErrMsg) - } else { - s.Require().NoError(err, out.String()) - s.Require().NoError(clientCtx.Codec.UnmarshalJSON(out.Bytes(), tc.respType), out.String()) - - txResp, err := clitestutil.GetTxResponse(s.network, clientCtx, tc.respType.(*sdk.TxResponse).TxHash) - s.Require().NoError(err) - s.Require().Equal(txResp.Code, tc.expectedCode) - if tc.expectErrMsg != "" { - s.Require().Contains(txResp.RawLog, tc.expectErrMsg) - } - } - }) - } -} - -func (s *E2ETestSuite) TestTxWithdrawProposal() { - val := s.network.Validators[0] - clientCtx := val.ClientCtx - - ids := make([]string, 2) - - for i := 0; i < 2; i++ { - out, err := clitestutil.ExecTestCLICmd(val.ClientCtx, client.MsgSubmitProposalCmd(), - append( - []string{ - s.createCLIProposal( - s.groupPolicies[1].Address, val.Address.String(), - s.groupPolicies[1].Address, val.Address.String(), - "", "title", "summary"), - }, - s.commonFlags..., - ), - ) - s.Require().NoError(err, out.String()) - - var txResp sdk.TxResponse - s.Require().NoError(val.ClientCtx.Codec.UnmarshalJSON(out.Bytes(), &txResp), out.String()) - txResp, err = clitestutil.GetTxResponse(s.network, val.ClientCtx, txResp.TxHash) - s.Require().NoError(err) - s.Require().Equal(txResp.Code, uint32(0), out.String()) - ids[i] = s.getProposalIDFromTxResponse(txResp) - } - - testCases := []struct { - name string - args []string - expectErr bool - expectErrMsg string - respType proto.Message - expectedCode uint32 - }{ - { - "correct data", - append( - []string{ - ids[0], - val.Address.String(), - }, - s.commonFlags..., - ), - false, - "", - &sdk.TxResponse{}, - 0, - }, - { - "already withdrawn proposal", - append( - []string{ - ids[0], - val.Address.String(), - }, - s.commonFlags..., - ), - false, - "cannot withdraw a proposal with the status of PROPOSAL_STATUS_WITHDRAWN", - &sdk.TxResponse{}, - errors.ErrInvalid.ABCICode(), - }, - { - "proposal not found", - append( - []string{ - "222", - "wrongAdmin", - }, - s.commonFlags..., - ), - true, - "not found", - &sdk.TxResponse{}, - 0, - }, - { - "invalid proposal", - append( - []string{ - "abc", - val.Address.String(), - }, - s.commonFlags..., - ), - true, - "invalid syntax", - &sdk.TxResponse{}, - 0, - }, - { - "wrong admin", - append( - []string{ - ids[1], - "wrongAdmin", - }, - s.commonFlags..., - ), - true, - "key not found", - &sdk.TxResponse{}, - 0, - }, - } - - for _, tc := range testCases { - tc := tc - - s.Run(tc.name, func() { - cmd := client.MsgWithdrawProposalCmd() - - out, err := clitestutil.ExecTestCLICmd(clientCtx, cmd, tc.args) - if tc.expectErr { - s.Require().Contains(out.String(), tc.expectErrMsg) - } else { - s.Require().NoError(err, out.String()) - s.Require().NoError(clientCtx.Codec.UnmarshalJSON(out.Bytes(), tc.respType), out.String()) - - txResp, err := clitestutil.GetTxResponse(s.network, clientCtx, tc.respType.(*sdk.TxResponse).TxHash) - s.Require().NoError(err) - s.Require().Equal(txResp.Code, tc.expectedCode) - if tc.expectErrMsg != "" { - s.Require().Contains(txResp.RawLog, tc.expectErrMsg) - } - } - }) - } -} - -func (s *E2ETestSuite) getProposalIDFromTxResponse(txResp sdk.TxResponse) string { - s.Require().Greater(len(txResp.Logs), 0) - s.Require().NotNil(txResp.Logs[0].Events) - events := txResp.Logs[0].Events - createProposalEvent, _ := sdk.TypedEventToEvent(&group.EventSubmitProposal{}) - - for _, e := range events { - if e.Type == createProposalEvent.Type { - return strings.ReplaceAll(e.Attributes[0].Value, "\"", "") - } - } - - return "" -} - -func (s *E2ETestSuite) TestTxExec() { - val := s.network.Validators[0] - clientCtx := val.ClientCtx - - var proposalIDs []string - // create proposals and vote - for i := 0; i < 2; i++ { - out, err := clitestutil.ExecTestCLICmd(val.ClientCtx, client.MsgSubmitProposalCmd(), - append( - []string{ - s.createCLIProposal( - s.groupPolicies[0].Address, val.Address.String(), - s.groupPolicies[0].Address, val.Address.String(), - "", "title", "summary", - ), - }, - s.commonFlags..., - ), - ) - s.Require().NoError(err, out.String()) - - var txResp sdk.TxResponse - s.Require().NoError(val.ClientCtx.Codec.UnmarshalJSON(out.Bytes(), &txResp), out.String()) - txResp, err = clitestutil.GetTxResponse(s.network, clientCtx, txResp.TxHash) - s.Require().NoError(err) - s.Require().Equal(txResp.Code, uint32(0), out.String()) - proposalID := s.getProposalIDFromTxResponse(txResp) - proposalIDs = append(proposalIDs, proposalID) - - out, err = clitestutil.ExecTestCLICmd(val.ClientCtx, client.MsgVoteCmd(), - append( - []string{ - proposalID, - val.Address.String(), - "VOTE_OPTION_YES", - "", - }, - s.commonFlags..., - ), - ) - s.Require().NoError(err, out.String()) - s.Require().NoError(s.network.WaitForNextBlock()) - } +func (s *E2ETestSuite) SetupSuite() { + s.T().Log("setting up e2e test suite") - testCases := []struct { - name string - args []string - expectErr bool - expectErrMsg string - respType proto.Message - expectedCode uint32 - }{ - { - "correct data", - append( - []string{ - proposalIDs[0], - fmt.Sprintf("--%s=%s", flags.FlagFrom, val.Address.String()), - }, - s.commonFlags..., - ), - false, - "", - &sdk.TxResponse{}, - 0, - }, - { - "with amino-json", - append( - []string{ - proposalIDs[1], - fmt.Sprintf("--%s=%s", flags.FlagFrom, val.Address.String()), - fmt.Sprintf("--%s=%s", flags.FlagSignMode, flags.SignModeLegacyAminoJSON), - }, - s.commonFlags..., - ), - false, - "", - &sdk.TxResponse{}, - 0, - }, - { - "invalid proposal id", - append( - []string{ - "abcd", - fmt.Sprintf("--%s=%s", flags.FlagFrom, val.Address.String()), - }, - s.commonFlags..., - ), - true, - "invalid syntax", - nil, - 0, - }, - { - "proposal not found", - append( - []string{ - "1234", - fmt.Sprintf("--%s=%s", flags.FlagFrom, val.Address.String()), - }, - s.commonFlags..., - ), - false, - "proposal: not found", - &sdk.TxResponse{}, - sdkerrors.ErrNotFound.ABCICode(), - }, + s.commonFlags = []string{ + fmt.Sprintf("--%s=true", flags.FlagSkipConfirmation), + fmt.Sprintf("--%s=%s", flags.FlagBroadcastMode, flags.BroadcastSync), + fmt.Sprintf("--%s=%s", flags.FlagFees, sdk.NewCoins(sdk.NewCoin(s.cfg.BondDenom, sdk.NewInt(10))).String()), } - for _, tc := range testCases { - tc := tc + var err error + s.network, err = network.New(s.T(), s.T().TempDir(), s.cfg) + s.Require().NoError(err) + s.Require().NoError(s.network.WaitForNextBlock()) - s.Run(tc.name, func() { - cmd := client.MsgExecCmd() + val := s.network.Validators[0] - out, err := clitestutil.ExecTestCLICmd(clientCtx, cmd, tc.args) - if tc.expectErr { - s.Require().Contains(out.String(), tc.expectErrMsg) - } else { - s.Require().NoError(err, out.String()) - s.Require().NoError(clientCtx.Codec.UnmarshalJSON(out.Bytes(), tc.respType), out.String()) + // create a new account + info, _, err := val.ClientCtx.Keyring.NewMnemonic("NewValidator", keyring.English, sdk.FullFundraiserPath, keyring.DefaultBIP39Passphrase, hd.Secp256k1) + s.Require().NoError(err) - txResp, err := clitestutil.GetTxResponse(s.network, clientCtx, tc.respType.(*sdk.TxResponse).TxHash) - s.Require().NoError(err) - s.Require().Equal(txResp.Code, tc.expectedCode) - if tc.expectErrMsg != "" { - s.Require().Contains(txResp.RawLog, tc.expectErrMsg) - } - } - }) - } -} + pk, err := info.GetPubKey() + s.Require().NoError(err) -func (s *E2ETestSuite) TestTxLeaveGroup() { - val := s.network.Validators[0] - clientCtx := val.ClientCtx + account := sdk.AccAddress(pk.Address()) + _, err = clitestutil.MsgSendExec( + val.ClientCtx, + val.Address, + account, + sdk.NewCoins(sdk.NewCoin(s.cfg.BondDenom, sdk.NewInt(2000))), fmt.Sprintf("--%s=true", flags.FlagSkipConfirmation), + fmt.Sprintf("--%s=%s", flags.FlagBroadcastMode, flags.BroadcastSync), + fmt.Sprintf("--%s=%s", flags.FlagFees, sdk.NewCoins(sdk.NewCoin(s.cfg.BondDenom, sdk.NewInt(10))).String()), + ) + s.Require().NoError(err) + s.Require().NoError(s.network.WaitForNextBlock()) - // create 3 accounts with some tokens - members := s.createAccounts(3) - - // create a group with three members - validMembers := fmt.Sprintf(`{"members": [{ - "address": "%s", - "weight": "1", - "metadata": "AQ==" - },{ - "address": "%s", - "weight": "2", - "metadata": "AQ==" - },{ - "address": "%s", - "weight": "2", - "metadata": "AQ==" - }]}`, members[0], members[1], members[2]) + memberWeight := "3" + // create a group + validMembers := fmt.Sprintf(` + { + "members": [ + { + "address": "%s", + "weight": "%s", + "metadata": "%s" + } + ] + }`, val.Address.String(), memberWeight, validMetadata) validMembersFile := testutil.WriteToNewTempFile(s.T(), validMembers) - out, err := clitestutil.ExecTestCLICmd(clientCtx, client.MsgCreateGroupCmd(), + out, err := clitestutil.ExecTestCLICmd(val.ClientCtx, client.MsgCreateGroupCmd(), append( []string{ val.Address.String(), @@ -2152,146 +103,107 @@ func (s *E2ETestSuite) TestTxLeaveGroup() { ), ) s.Require().NoError(err, out.String()) - s.Require().NoError(s.network.WaitForNextBlock()) - - var txResp sdk.TxResponse + txResp := sdk.TxResponse{} s.Require().NoError(val.ClientCtx.Codec.UnmarshalJSON(out.Bytes(), &txResp), out.String()) - txResp, err = clitestutil.GetTxResponse(s.network, val.ClientCtx, txResp.TxHash) - s.Require().NoError(err) - groupID := s.getGroupIDFromTxResponse(txResp) + s.Require().NoError(clitestutil.CheckTxCode(s.network, val.ClientCtx, txResp.TxHash, 0)) - // create group policy - out, err = clitestutil.ExecTestCLICmd(clientCtx, client.MsgCreateGroupPolicyCmd(), + s.group = &group.GroupInfo{Id: 1, Admin: val.Address.String(), Metadata: validMetadata, TotalWeight: "3", Version: 1} + + // create 5 group policies + for i := 0; i < 5; i++ { + threshold := i + 1 + if threshold > 3 { + threshold = 3 + } + + s.createGroupThresholdPolicyWithBalance(val.Address.String(), "1", threshold, 1000) + out, err = clitestutil.ExecTestCLICmd(val.ClientCtx, client.QueryGroupPoliciesByGroupCmd(), []string{"1", fmt.Sprintf("--%s=json", flags.FlagOutput)}) + s.Require().NoError(err, out.String()) + s.Require().NoError(s.network.WaitForNextBlock()) + } + percentage := 0.5 + // create group policy with percentage decision policy + out, err = clitestutil.ExecTestCLICmd(val.ClientCtx, client.MsgCreateGroupPolicyCmd(), append( []string{ val.Address.String(), - groupID, - "AQ==", - testutil.WriteToNewTempFile(s.T(), `{"@type":"/cosmos.group.v1.ThresholdDecisionPolicy", "threshold":"3", "windows":{"voting_period":"1s"}}`).Name(), + "1", + validMetadata, + testutil.WriteToNewTempFile(s.T(), fmt.Sprintf(`{"@type":"/cosmos.group.v1.PercentageDecisionPolicy", "percentage":"%f", "windows":{"voting_period":"30000s"}}`, percentage)).Name(), }, s.commonFlags..., ), ) s.Require().NoError(err, out.String()) + s.Require().NoError(val.ClientCtx.Codec.UnmarshalJSON(out.Bytes(), &txResp), out.String()) + s.Require().NoError(clitestutil.CheckTxCode(s.network, val.ClientCtx, txResp.TxHash, 0)) - err = s.network.RetryForBlocks(func() error { - out, err = clitestutil.ExecTestCLICmd(clientCtx, client.QueryGroupPoliciesByGroupCmd(), []string{groupID, fmt.Sprintf("--%s=json", flags.FlagOutput)}) - if err != nil { - return err - } + out, err = clitestutil.ExecTestCLICmd(val.ClientCtx, client.QueryGroupPoliciesByGroupCmd(), []string{"1", fmt.Sprintf("--%s=json", flags.FlagOutput)}) + s.Require().NoError(err, out.String()) - var resp group.QueryGroupPoliciesByGroupResponse - err = clientCtx.Codec.UnmarshalJSON(out.Bytes(), &resp) - if err != nil { - return err - } + var res group.QueryGroupPoliciesByGroupResponse + s.Require().NoError(val.ClientCtx.Codec.UnmarshalJSON(out.Bytes(), &res)) + s.Require().Equal(len(res.GroupPolicies), 6) + s.groupPolicies = res.GroupPolicies - if len(resp.GroupPolicies) != 1 { - return fmt.Errorf("expected 1 group policy, got %d", len(resp.GroupPolicies)) - } + // create a proposal + out, err = clitestutil.ExecTestCLICmd(val.ClientCtx, client.MsgSubmitProposalCmd(), + append( + []string{ + s.createCLIProposal( + s.groupPolicies[0].Address, val.Address.String(), + s.groupPolicies[0].Address, val.Address.String(), + "", "title", "summary"), + }, + s.commonFlags..., + ), + ) + s.Require().NoError(err, out.String()) + s.Require().NoError(val.ClientCtx.Codec.UnmarshalJSON(out.Bytes(), &txResp), out.String()) + s.Require().NoError(clitestutil.CheckTxCode(s.network, val.ClientCtx, txResp.TxHash, 0)) - return nil - }, 3) + // vote + out, err = clitestutil.ExecTestCLICmd(val.ClientCtx, client.MsgVoteCmd(), + append( + []string{ + "1", + val.Address.String(), + "VOTE_OPTION_YES", + "", + }, + s.commonFlags..., + ), + ) + s.Require().NoError(err, out.String()) + s.Require().NoError(val.ClientCtx.Codec.UnmarshalJSON(out.Bytes(), &txResp), out.String()) + s.Require().NoError(clitestutil.CheckTxCode(s.network, val.ClientCtx, txResp.TxHash, 0)) + out, err = clitestutil.ExecTestCLICmd(val.ClientCtx, client.QueryProposalCmd(), []string{"1", fmt.Sprintf("--%s=json", flags.FlagOutput)}) s.Require().NoError(err, out.String()) - testCases := []struct { - name string - args []string - expectErr bool - errMsg string - expectedCode uint32 - }{ - { - "invalid member address", - append( - []string{ - "address", - groupID, - fmt.Sprintf("--%s=%s", flags.FlagFrom, val.Address.String()), - }, - s.commonFlags..., - ), - true, - "key not found", - 0, - }, - { - "group not found", - append( - []string{ - members[0], - "40", - fmt.Sprintf("--%s=%s", flags.FlagFrom, members[0]), - }, - s.commonFlags..., - ), - false, - "group: not found", - sdkerrors.ErrNotFound.ABCICode(), - }, - { - "valid case", - append( - []string{ - members[2], - groupID, - fmt.Sprintf("--%s=%s", flags.FlagFrom, members[2]), - }, - s.commonFlags..., - ), - false, - "", - 0, - }, - { - "not part of group", - append( - []string{ - members[2], - groupID, - fmt.Sprintf("--%s=%s", flags.FlagFrom, members[2]), - }, - s.commonFlags..., - ), - false, - "is not part of group", - sdkerrors.ErrNotFound.ABCICode(), - }, - { - "can leave group policy threshold is more than group weight", - append( - []string{ - members[1], - groupID, - fmt.Sprintf("--%s=%s", flags.FlagFrom, members[1]), - }, - s.commonFlags..., - ), - false, - "", - 0, - }, - } + var proposalRes group.QueryProposalResponse + s.Require().NoError(val.ClientCtx.Codec.UnmarshalJSON(out.Bytes(), &proposalRes)) + s.proposal = proposalRes.Proposal - for _, tc := range testCases { - tc := tc + out, err = clitestutil.ExecTestCLICmd(val.ClientCtx, client.QueryVoteByProposalVoterCmd(), []string{"1", val.Address.String(), fmt.Sprintf("--%s=json", flags.FlagOutput)}) + s.Require().NoError(err, out.String()) - s.Run(tc.name, func() { - cmd := client.MsgLeaveGroupCmd() - out, err := clitestutil.ExecTestCLICmd(clientCtx, cmd, tc.args) - if tc.expectErr { - s.Require().Contains(out.String(), tc.errMsg) - } else { - s.Require().NoError(err, out.String()) - var resp sdk.TxResponse - s.Require().NoError(clientCtx.Codec.UnmarshalJSON(out.Bytes(), &resp), out.String()) - s.Require().NoError(clitestutil.CheckTxCode(s.network, clientCtx, resp.TxHash, tc.expectedCode)) - } - }) + var voteRes group.QueryVoteByProposalVoterResponse + s.Require().NoError(val.ClientCtx.Codec.UnmarshalJSON(out.Bytes(), &voteRes)) + s.vote = voteRes.Vote + + s.voter = &group.Member{ + Address: val.Address.String(), + Weight: memberWeight, + Metadata: validMetadata, } } +func (s *E2ETestSuite) TearDownSuite() { + s.T().Log("tearing down e2e test suite") + s.network.Cleanup() +} + func (s *E2ETestSuite) TestExecProposalsWhenMemberLeavesOrIsUpdated() { val := s.network.Validators[0] clientCtx := val.ClientCtx @@ -2498,6 +410,21 @@ func (s *E2ETestSuite) TestExecProposalsWhenMemberLeavesOrIsUpdated() { } } +func (s *E2ETestSuite) getProposalIDFromTxResponse(txResp sdk.TxResponse) string { + s.Require().Greater(len(txResp.Logs), 0) + s.Require().NotNil(txResp.Logs[0].Events) + events := txResp.Logs[0].Events + createProposalEvent, _ := sdk.TypedEventToEvent(&group.EventSubmitProposal{}) + + for _, e := range events { + if e.Type == createProposalEvent.Type { + return strings.ReplaceAll(e.Attributes[0].Value, "\"", "") + } + } + + return "" +} + func (s *E2ETestSuite) getGroupIDFromTxResponse(txResp sdk.TxResponse) string { s.Require().Greater(len(txResp.Logs), 0) s.Require().NotNil(txResp.Logs[0].Events) @@ -2644,15 +571,20 @@ func (s *E2ETestSuite) createGroupThresholdPolicyWithBalance(adminAddress, group return groupPolicyAddress } -func (s *E2ETestSuite) newValidMembers(weights, membersAddress []string) group.MemberRequests { +func (s *E2ETestSuite) newValidMembers(weights, membersAddress []string) struct{ Members []group.MemberRequest } { s.Require().Equal(len(weights), len(membersAddress)) - membersValid := group.MemberRequests{} + membersValid := []group.MemberRequest{} for i, address := range membersAddress { - membersValid.Members = append(membersValid.Members, group.MemberRequest{ + membersValid = append(membersValid, group.MemberRequest{ Address: address, Weight: weights[i], Metadata: validMetadata, }) } - return membersValid + + return struct { + Members []group.MemberRequest + }{ + Members: membersValid, + } } diff --git a/tests/e2e/nft/test_helper.go b/tests/e2e/nft/test_helper.go index 54756d5d10bc..ce34da3d6736 100644 --- a/tests/e2e/nft/test_helper.go +++ b/tests/e2e/nft/test_helper.go @@ -5,6 +5,7 @@ import ( "cosmossdk.io/x/nft/client/cli" "github.com/cosmos/cosmos-sdk/client/flags" + "github.com/cosmos/cosmos-sdk/codec/address" "github.com/cosmos/cosmos-sdk/testutil" clitestutil "github.com/cosmos/cosmos-sdk/testutil/cli" "github.com/cosmos/cosmos-sdk/testutil/network" @@ -40,7 +41,7 @@ func ExecQueryNFT(val *network.Validator, classID, nftID string) (testutil.Buffe } func ExecQueryNFTs(val *network.Validator, classID, owner string) (testutil.BufferWriter, error) { - cmd := cli.GetCmdQueryNFTs() + cmd := cli.GetCmdQueryNFTs(address.NewBech32Codec("cosmos")) var args []string args = append(args, fmt.Sprintf("--%s=%s", cli.FlagClassID, classID)) args = append(args, fmt.Sprintf("--%s=%s", cli.FlagOwner, owner)) diff --git a/tests/e2e/staking/suite.go b/tests/e2e/staking/suite.go index ee291910b81c..1814545564b3 100644 --- a/tests/e2e/staking/suite.go +++ b/tests/e2e/staking/suite.go @@ -14,6 +14,7 @@ import ( "github.com/stretchr/testify/suite" "github.com/cosmos/cosmos-sdk/client/flags" + "github.com/cosmos/cosmos-sdk/codec/address" "github.com/cosmos/cosmos-sdk/crypto/hd" "github.com/cosmos/cosmos-sdk/crypto/keyring" "github.com/cosmos/cosmos-sdk/testutil" @@ -403,7 +404,7 @@ func (s *E2ETestSuite) TestGetCmdQueryDelegation() { for _, tc := range testCases { tc := tc s.Run(tc.name, func() { - cmd := cli.GetCmdQueryDelegation() + cmd := cli.GetCmdQueryDelegation(address.NewBech32Codec("cosmos")) clientCtx := val.ClientCtx out, err := clitestutil.ExecTestCLICmd(clientCtx, cmd, tc.args) @@ -459,7 +460,7 @@ func (s *E2ETestSuite) TestGetCmdQueryDelegations() { for _, tc := range testCases { tc := tc s.Run(tc.name, func() { - cmd := cli.GetCmdQueryDelegations() + cmd := cli.GetCmdQueryDelegations(address.NewBech32Codec("cosmos")) clientCtx := val.ClientCtx out, err := clitestutil.ExecTestCLICmd(clientCtx, cmd, tc.args) @@ -515,7 +516,7 @@ func (s *E2ETestSuite) TestGetCmdQueryValidatorDelegations() { for _, tc := range testCases { tc := tc s.Run(tc.name, func() { - cmd := cli.GetCmdQueryDelegations() + cmd := cli.GetCmdQueryDelegations(address.NewBech32Codec("cosmos")) clientCtx := val.ClientCtx out, err := clitestutil.ExecTestCLICmd(clientCtx, cmd, tc.args) @@ -559,7 +560,7 @@ func (s *E2ETestSuite) TestGetCmdQueryUnbondingDelegations() { for _, tc := range testCases { tc := tc s.Run(tc.name, func() { - cmd := cli.GetCmdQueryUnbondingDelegations() + cmd := cli.GetCmdQueryUnbondingDelegations(address.NewBech32Codec("cosmos")) clientCtx := val.ClientCtx out, err := clitestutil.ExecTestCLICmd(clientCtx, cmd, tc.args) @@ -618,7 +619,7 @@ func (s *E2ETestSuite) TestGetCmdQueryUnbondingDelegation() { for _, tc := range testCases { tc := tc s.Run(tc.name, func() { - cmd := cli.GetCmdQueryUnbondingDelegation() + cmd := cli.GetCmdQueryUnbondingDelegation(address.NewBech32Codec("cosmos")) clientCtx := val.ClientCtx out, err := clitestutil.ExecTestCLICmd(clientCtx, cmd, tc.args) @@ -716,7 +717,7 @@ func (s *E2ETestSuite) TestGetCmdQueryRedelegations() { for _, tc := range testCases { tc := tc s.Run(tc.name, func() { - cmd := cli.GetCmdQueryRedelegations() + cmd := cli.GetCmdQueryRedelegations(address.NewBech32Codec("cosmos")) clientCtx := val.ClientCtx out, err := clitestutil.ExecTestCLICmd(clientCtx, cmd, tc.args) @@ -792,7 +793,7 @@ func (s *E2ETestSuite) TestGetCmdQueryRedelegation() { for _, tc := range testCases { tc := tc s.Run(tc.name, func() { - cmd := cli.GetCmdQueryRedelegation() + cmd := cli.GetCmdQueryRedelegation(address.NewBech32Codec("cosmos")) clientCtx := val.ClientCtx out, err := clitestutil.ExecTestCLICmd(clientCtx, cmd, tc.args) diff --git a/tests/e2e/staking/test_helpers.go b/tests/e2e/staking/test_helpers.go index c1358319ca7f..787080dcd897 100644 --- a/tests/e2e/staking/test_helpers.go +++ b/tests/e2e/staking/test_helpers.go @@ -33,8 +33,9 @@ func MsgRedelegateExec(clientCtx client.Context, from, src, dst, amount fmt.Stri } // MsgUnbondExec creates a unbond message. -func MsgUnbondExec(clientCtx client.Context, from fmt.Stringer, valAddress, - amount fmt.Stringer, extraArgs ...string, +func MsgUnbondExec(clientCtx client.Context, from, valAddress, + amount fmt.Stringer, + extraArgs ...string, ) (testutil.BufferWriter, error) { args := []string{ valAddress.String(), diff --git a/tests/e2e/tx/service_test.go b/tests/e2e/tx/service_test.go index 30b8142479cd..3295032363d1 100644 --- a/tests/e2e/tx/service_test.go +++ b/tests/e2e/tx/service_test.go @@ -1124,7 +1124,7 @@ type protoTxProvider interface { // txBuilderToProtoTx converts a txBuilder into a proto tx.Tx. // Deprecated: It's used for testing the deprecated Simulate gRPC endpoint // using a proto Tx field and for testing the TxEncode endpoint. -func txBuilderToProtoTx(txBuilder client.TxBuilder) (*tx.Tx, error) { // nolint +func txBuilderToProtoTx(txBuilder client.TxBuilder) (*tx.Tx, error) { protoProvider, ok := txBuilder.(protoTxProvider) if !ok { return nil, errorsmod.Wrapf(sdkerrors.ErrInvalidType, "expected proto tx builder, got %T", txBuilder) diff --git a/tests/e2e/upgrade/suite.go b/tests/e2e/upgrade/suite.go index 16cf1734b19c..8e500050b23f 100644 --- a/tests/e2e/upgrade/suite.go +++ b/tests/e2e/upgrade/suite.go @@ -93,7 +93,7 @@ func (s *E2ETestSuite) TestModuleVersionsCLI() { } jsonVM, _ := clientCtx.Codec.MarshalJSON(&pm) expectedRes := string(jsonVM) - // append new line to match behaviour of PrintProto + // append new line to match behavior of PrintProto expectedRes += "\n" // get actual module versions list response from cli diff --git a/tests/go.mod b/tests/go.mod index f1e354256a81..8419aa4f8993 100644 --- a/tests/go.mod +++ b/tests/go.mod @@ -3,27 +3,27 @@ module github.com/cosmos/cosmos-sdk/tests go 1.20 require ( - cosmossdk.io/api v0.3.2-0.20230313131911-55bf5d4efbe7 + cosmossdk.io/api v0.4.0 cosmossdk.io/depinject v1.0.0-alpha.3 cosmossdk.io/errors v1.0.0-beta.7 - cosmossdk.io/log v0.1.0 + cosmossdk.io/log v1.0.0 cosmossdk.io/math v1.0.0 cosmossdk.io/simapp v0.0.0-20230309163709-87da587416ba - cosmossdk.io/store v0.1.0-alpha.1 + cosmossdk.io/store v0.1.0-alpha.1.0.20230328185921-37ba88872dbc cosmossdk.io/x/evidence v0.1.0 cosmossdk.io/x/feegrant v0.0.0-20230117113717-50e7c4a4ceff cosmossdk.io/x/nft v0.0.0-20230113085233-fae3332d62fc - cosmossdk.io/x/tx v0.3.1-0.20230321155358-6522dd1731b5 + cosmossdk.io/x/tx v0.5.5 cosmossdk.io/x/upgrade v0.0.0-20230127052425-54c8e1568335 - github.com/cometbft/cometbft v0.37.0 + github.com/cometbft/cometbft v0.37.1-0.20230411132551-3a91d155e664 github.com/cosmos/cosmos-db v1.0.0-rc.1 github.com/cosmos/cosmos-proto v1.0.0-beta.3 // this version is not used as it is always replaced by the latest Cosmos SDK version github.com/cosmos/cosmos-sdk v0.48.0 - github.com/cosmos/gogoproto v1.4.6 + github.com/cosmos/gogoproto v1.4.8 github.com/golang/mock v1.6.0 github.com/google/uuid v1.3.0 - github.com/spf13/cobra v1.6.1 + github.com/spf13/cobra v1.7.0 github.com/stretchr/testify v1.8.2 google.golang.org/protobuf v1.30.0 gotest.tools/v3 v3.4.0 @@ -32,12 +32,12 @@ require ( require ( cloud.google.com/go v0.110.0 // indirect - cloud.google.com/go/compute v1.18.0 // indirect + cloud.google.com/go/compute v1.19.0 // indirect cloud.google.com/go/compute/metadata v0.2.3 // indirect cloud.google.com/go/iam v0.13.0 // indirect cloud.google.com/go/storage v1.30.0 // indirect cosmossdk.io/client/v2 v2.0.0-20230309163709-87da587416ba // indirect - cosmossdk.io/collections v0.0.0-20230309163709-87da587416ba // indirect + cosmossdk.io/collections v0.1.0 // indirect cosmossdk.io/core v0.6.1 // indirect filippo.io/edwards25519 v1.0.0 // indirect github.com/99designs/go-keychain v0.0.0-20191008050251-8e49817e8af4 // indirect @@ -49,6 +49,7 @@ require ( github.com/beorn7/perks v1.0.1 // indirect github.com/bgentry/go-netrc v0.0.0-20140422174119-9fd32a8b3d3d // indirect github.com/bgentry/speakeasy v0.1.1-0.20220910012023-760eaf8b6816 // indirect + github.com/bits-and-blooms/bitset v1.6.0 // indirect github.com/btcsuite/btcd/btcec/v2 v2.3.2 // indirect github.com/cenkalti/backoff/v4 v4.1.3 // indirect github.com/cespare/xxhash v1.1.0 // indirect @@ -57,7 +58,7 @@ require ( github.com/cockroachdb/apd/v2 v2.0.2 // indirect github.com/cockroachdb/errors v1.9.1 // indirect github.com/cockroachdb/logtags v0.0.0-20230118201751-21c54148d20b // indirect - github.com/cockroachdb/pebble v0.0.0-20230315223031-1e5ddd10389e // indirect + github.com/cockroachdb/pebble v0.0.0-20230412222916-60cfeb46143b // indirect github.com/cockroachdb/redact v1.1.3 // indirect github.com/cometbft/cometbft-db v0.7.0 // indirect github.com/confio/ics23/go v0.9.0 // indirect @@ -69,7 +70,7 @@ require ( github.com/creachadair/taskgroup v0.4.2 // indirect github.com/danieljoos/wincred v1.1.2 // indirect github.com/davecgh/go-spew v1.1.1 // indirect - github.com/decred/dcrd/dcrec/secp256k1/v4 v4.1.0 // indirect + github.com/decred/dcrd/dcrec/secp256k1/v4 v4.2.0 // indirect github.com/desertbit/timer v0.0.0-20180107155436-c41aec40b27f // indirect github.com/dgraph-io/badger/v2 v2.2007.4 // indirect github.com/dgraph-io/ristretto v0.1.1 // indirect @@ -79,7 +80,7 @@ require ( github.com/fatih/color v1.15.0 // indirect github.com/felixge/httpsnoop v1.0.2 // indirect github.com/fsnotify/fsnotify v1.6.0 // indirect - github.com/getsentry/sentry-go v0.19.0 // indirect + github.com/getsentry/sentry-go v0.20.0 // indirect github.com/go-kit/kit v0.12.0 // indirect github.com/go-kit/log v0.2.1 // indirect github.com/go-logfmt/logfmt v0.6.0 // indirect @@ -120,12 +121,12 @@ require ( github.com/inconshreveable/mousetrap v1.1.0 // indirect github.com/jmespath/go-jmespath v0.4.0 // indirect github.com/jmhodges/levigo v1.0.0 // indirect - github.com/klauspost/compress v1.16.3 // indirect + github.com/klauspost/compress v1.16.5 // indirect github.com/kr/pretty v0.3.1 // indirect github.com/kr/text v0.2.0 // indirect github.com/lib/pq v1.10.7 // indirect github.com/libp2p/go-buffer-pool v0.1.0 // indirect - github.com/linxGnu/grocksdb v1.7.15 // indirect + github.com/linxGnu/grocksdb v1.7.16 // indirect github.com/magiconair/properties v1.8.7 // indirect github.com/manifoldco/promptui v0.9.0 // indirect github.com/mattn/go-colorable v0.1.13 // indirect @@ -142,14 +143,14 @@ require ( github.com/petermattis/goid v0.0.0-20230317030725-371a4b8eda08 // indirect github.com/pkg/errors v0.9.1 // indirect github.com/pmezard/go-difflib v1.0.0 // indirect - github.com/prometheus/client_golang v1.14.0 // indirect + github.com/prometheus/client_golang v1.15.0 // indirect github.com/prometheus/client_model v0.3.0 // indirect github.com/prometheus/common v0.42.0 // indirect github.com/prometheus/procfs v0.9.0 // indirect github.com/rcrowley/go-metrics v0.0.0-20201227073835-cf1acfcdf475 // indirect - github.com/rogpeppe/go-internal v1.9.0 // indirect + github.com/rogpeppe/go-internal v1.10.0 // indirect github.com/rs/cors v1.8.3 // indirect - github.com/rs/zerolog v1.29.0 // indirect + github.com/rs/zerolog v1.29.1 // indirect github.com/sasha-s/go-deadlock v0.3.1 // indirect github.com/spf13/afero v1.9.3 // indirect github.com/spf13/cast v1.5.0 // indirect @@ -166,18 +167,18 @@ require ( github.com/zondax/ledger-go v0.14.1 // indirect go.etcd.io/bbolt v1.3.6 // indirect go.opencensus.io v0.24.0 // indirect - golang.org/x/crypto v0.7.0 // indirect + golang.org/x/crypto v0.8.0 // indirect golang.org/x/exp v0.0.0-20230321023759-10a507213a29 // indirect - golang.org/x/net v0.8.0 // indirect + golang.org/x/net v0.9.0 // indirect golang.org/x/oauth2 v0.6.0 // indirect golang.org/x/sync v0.1.0 // indirect - golang.org/x/sys v0.6.0 // indirect - golang.org/x/term v0.6.0 // indirect - golang.org/x/text v0.8.0 // indirect + golang.org/x/sys v0.7.0 // indirect + golang.org/x/term v0.7.0 // indirect + golang.org/x/text v0.9.0 // indirect golang.org/x/xerrors v0.0.0-20220907171357-04be3eba64a2 // indirect google.golang.org/api v0.114.0 // indirect google.golang.org/appengine v1.6.7 // indirect - google.golang.org/genproto v0.0.0-20230320184635-7606e756e683 // indirect + google.golang.org/genproto v0.0.0-20230410155749-daa745c078e1 // indirect google.golang.org/grpc v1.54.0 // indirect gopkg.in/ini.v1 v1.67.0 // indirect gopkg.in/yaml.v2 v2.4.0 // indirect @@ -190,7 +191,9 @@ require ( // Replace here are pending PRs, or version to be tagged. // It must be in sync with SimApp temporary replaces replace ( + cosmossdk.io/api => ../api // TODO tag all extracted modules after SDK refactor + cosmossdk.io/store => ../store cosmossdk.io/x/evidence => ../x/evidence cosmossdk.io/x/feegrant => ../x/feegrant cosmossdk.io/x/nft => ../x/nft diff --git a/tests/go.sum b/tests/go.sum index 67434456b8b9..ded5f08b36fe 100644 --- a/tests/go.sum +++ b/tests/go.sum @@ -70,8 +70,8 @@ cloud.google.com/go/compute v1.6.0/go.mod h1:T29tfhtVbq1wvAPo0E3+7vhgmkOYeXjhFvz cloud.google.com/go/compute v1.6.1/go.mod h1:g85FgpzFvNULZ+S8AYq87axRKuf2Kh7deLqV/jJ3thU= cloud.google.com/go/compute v1.7.0/go.mod h1:435lt8av5oL9P3fv1OEzSbSUe+ybHXGMPQHHZWZxy9U= cloud.google.com/go/compute v1.10.0/go.mod h1:ER5CLbMxl90o2jtNbGSbtfOpQKR0t15FOtRsugnLrlU= -cloud.google.com/go/compute v1.18.0 h1:FEigFqoDbys2cvFkZ9Fjq4gnHBP55anJ0yQyau2f9oY= -cloud.google.com/go/compute v1.18.0/go.mod h1:1X7yHxec2Ga+Ss6jPyjxRxpu2uu7PLgsOVXvgU0yacs= +cloud.google.com/go/compute v1.19.0 h1:+9zda3WGgW1ZSTlVppLCYFIr48Pa35q1uG2N1itbCEQ= +cloud.google.com/go/compute v1.19.0/go.mod h1:rikpw2y+UMidAe9tISo04EHNOIf42RLYF/q8Bs93scU= cloud.google.com/go/compute/metadata v0.2.3 h1:mg4jlk7mCAj6xXp9UJ4fjI9VUI5rubuGBW5aJ7UnBMY= cloud.google.com/go/compute/metadata v0.2.3/go.mod h1:VAV5nSsACxMJvgaAuX6Pk2AawlZn8kiOGuCv6gTkwuA= cloud.google.com/go/containeranalysis v0.5.1/go.mod h1:1D92jd8gRR/c0fGMlymRgxWD3Qw9C1ff6/T7mLgVL8I= @@ -188,26 +188,22 @@ cloud.google.com/go/webrisk v1.4.0/go.mod h1:Hn8X6Zr+ziE2aNd8SliSDWpEnSS1u4R9+xX cloud.google.com/go/webrisk v1.5.0/go.mod h1:iPG6fr52Tv7sGk0H6qUFzmL3HHZev1htXuWDEEsqMTg= cloud.google.com/go/workflows v1.6.0/go.mod h1:6t9F5h/unJz41YqfBmqSASJSXccBLtD1Vwf+KmJENM0= cloud.google.com/go/workflows v1.7.0/go.mod h1:JhSrZuVZWuiDfKEFxU0/F1PQjmpnpcoISEXH2bcHC3M= -cosmossdk.io/api v0.3.2-0.20230313131911-55bf5d4efbe7 h1:4LrWK+uGP5IxznxtHHsHD+ZBs2+oZRH2loYOGjHLzZM= -cosmossdk.io/api v0.3.2-0.20230313131911-55bf5d4efbe7/go.mod h1:yVns7mKgcsG+hZW/3C5FdJtC6QYWdFIcRlKb9+5HV5g= cosmossdk.io/client/v2 v2.0.0-20230309163709-87da587416ba h1:LuPHCncU2KLMNPItFECs709uo46I9wSu2fAWYVCx+/U= cosmossdk.io/client/v2 v2.0.0-20230309163709-87da587416ba/go.mod h1:SXdwqO7cN5htalh/lhXWP8V4zKtBrhhcSTU+ytuEtmM= -cosmossdk.io/collections v0.0.0-20230309163709-87da587416ba h1:S4PYij/tX3Op/hwenVEN9D+M27JRcwSwVqE3UA0BnwM= -cosmossdk.io/collections v0.0.0-20230309163709-87da587416ba/go.mod h1:lpS+G8bGC2anqzWdndTzjnQnuMO/qAcgZUkGJp4i3rc= +cosmossdk.io/collections v0.1.0 h1:nzJGeiq32KnZroSrhB6rPifw4I85Cgmzw/YAmr4luv8= +cosmossdk.io/collections v0.1.0/go.mod h1:xbauc0YsbUF8qKMVeBZl0pFCunxBIhKN/WlxpZ3lBuo= cosmossdk.io/core v0.6.1 h1:OBy7TI2W+/gyn2z40vVvruK3di+cAluinA6cybFbE7s= cosmossdk.io/core v0.6.1/go.mod h1:g3MMBCBXtxbDWBURDVnJE7XML4BG5qENhs0gzkcpuFA= cosmossdk.io/depinject v1.0.0-alpha.3 h1:6evFIgj//Y3w09bqOUOzEpFj5tsxBqdc5CfkO7z+zfw= cosmossdk.io/depinject v1.0.0-alpha.3/go.mod h1:eRbcdQ7MRpIPEM5YUJh8k97nxHpYbc3sMUnEtt8HPWU= cosmossdk.io/errors v1.0.0-beta.7 h1:gypHW76pTQGVnHKo6QBkb4yFOJjC+sUGRc5Al3Odj1w= cosmossdk.io/errors v1.0.0-beta.7/go.mod h1:mz6FQMJRku4bY7aqS/Gwfcmr/ue91roMEKAmDUDpBfE= -cosmossdk.io/log v0.1.0 h1:Vnexi+KzUCjmqq/m93teAxjt5biWFfZ5PI1imx2IJw8= -cosmossdk.io/log v0.1.0/go.mod h1:p95Wq6mDY3SREMc4y7+QU9Uwy3nyvfpWGD1iSaFkVFs= +cosmossdk.io/log v1.0.0 h1:NGKZ/A5rd4PduDfoscgABklX557PWjQINbosZy/m3Jk= +cosmossdk.io/log v1.0.0/go.mod h1:CwX9BLiBruZb7lzLlRr3R231d/fVPUXk8gAdV4LQap0= cosmossdk.io/math v1.0.0 h1:ro9w7eKx23om2tZz/VM2Pf+z2WAbGX1yDQQOJ6iGeJw= cosmossdk.io/math v1.0.0/go.mod h1:Ygz4wBHrgc7g0N+8+MrnTfS9LLn9aaTGa9hKopuym5k= -cosmossdk.io/store v0.1.0-alpha.1 h1:NGomhLUXzAxvK4OF8+yP6eNUG5i4LwzOzx+S494pTCg= -cosmossdk.io/store v0.1.0-alpha.1/go.mod h1:kmCMbhrleCZ6rDZPY/EGNldNvPebFNyVPFYp+pv05/k= -cosmossdk.io/x/tx v0.3.1-0.20230321155358-6522dd1731b5 h1:AlvyRc7f7Py1mv254vrqjIIuykCnitHIz2T+nup3bU0= -cosmossdk.io/x/tx v0.3.1-0.20230321155358-6522dd1731b5/go.mod h1:FNkSEMbLP9NFdTfrbslNUtNS7OXf3wgZeJyXzfRPa4c= +cosmossdk.io/x/tx v0.5.5 h1:9XG3KOrqObt7Rw7KhT7fiqRd6EepUfmA9ERa8CHj1WM= +cosmossdk.io/x/tx v0.5.5/go.mod h1:Oh3Kh+IPOfMEILNxVd2e8SLqRrIjYHpdGBfDg4ghU/k= dmitri.shuralyov.com/gpu/mtl v0.0.0-20190408044501-666a987793e9/go.mod h1:H6x//7gZCb22OMCxBHrMx7a5I7Hp++hsVxbQ4BYO7hU= filippo.io/edwards25519 v1.0.0 h1:0wAIcmJUqRdI8IJ/3eGi5/HwXZWPujYXXlkrQogz0Ek= filippo.io/edwards25519 v1.0.0/go.mod h1:N1IkdkCkiLB6tki+MYJoSx2JTY9NUlxZE7eHn5EwJns= @@ -271,6 +267,8 @@ github.com/bgentry/go-netrc v0.0.0-20140422174119-9fd32a8b3d3d/go.mod h1:6QX/PXZ github.com/bgentry/speakeasy v0.1.0/go.mod h1:+zsyZBPWlz7T6j88CTgSN5bM796AkVf0kBD4zp0CCIs= github.com/bgentry/speakeasy v0.1.1-0.20220910012023-760eaf8b6816 h1:41iFGWnSlI2gVpmOtVTJZNodLdLQLn/KsJqFvXwnd/s= github.com/bgentry/speakeasy v0.1.1-0.20220910012023-760eaf8b6816/go.mod h1:+zsyZBPWlz7T6j88CTgSN5bM796AkVf0kBD4zp0CCIs= +github.com/bits-and-blooms/bitset v1.6.0 h1:FVfaUsleKAUTJnaN9Fd1YFFi1S8vAX5xeXnXHFYOojM= +github.com/bits-and-blooms/bitset v1.6.0/go.mod h1:gIdJ4wp64HaoK2YrL1Q5/N7Y16edYb8uY+O0FJTyyDA= github.com/btcsuite/btcd/btcec/v2 v2.3.2 h1:5n0X6hX0Zk+6omWcihdYvdAlGf2DfasC0GMf7DClJ3U= github.com/btcsuite/btcd/btcec/v2 v2.3.2/go.mod h1:zYzJ8etWJQIv1Ogk7OzpWjowwOdXY1W/17j2MW85J04= github.com/btcsuite/btcd/btcutil v1.1.2 h1:XLMbX8JQEiwMcYft2EGi8zPUkoa0abKIU6/BJSRsjzQ= @@ -322,14 +320,14 @@ github.com/cockroachdb/errors v1.9.1/go.mod h1:2sxOtL2WIc096WSZqZ5h8fa17rdDq9HZO github.com/cockroachdb/logtags v0.0.0-20211118104740-dabe8e521a4f/go.mod h1:Vz9DsVWQQhf3vs21MhPMZpMGSht7O/2vFW2xusFUVOs= github.com/cockroachdb/logtags v0.0.0-20230118201751-21c54148d20b h1:r6VH0faHjZeQy818SGhaone5OnYfxFR/+AzdY3sf5aE= github.com/cockroachdb/logtags v0.0.0-20230118201751-21c54148d20b/go.mod h1:Vz9DsVWQQhf3vs21MhPMZpMGSht7O/2vFW2xusFUVOs= -github.com/cockroachdb/pebble v0.0.0-20230315223031-1e5ddd10389e h1:CDuLmyaZ1pD4OJHHtubKqgu/Byw5zAnm+gArJsyj96Q= -github.com/cockroachdb/pebble v0.0.0-20230315223031-1e5ddd10389e/go.mod h1:9lRMC4XN3/BLPtIp6kAKwIaHu369NOf2rMucPzipz50= +github.com/cockroachdb/pebble v0.0.0-20230412222916-60cfeb46143b h1:92ve6F1Pls/eqd+V+102lOMRJatgpqqsQvbT9Bl/fjg= +github.com/cockroachdb/pebble v0.0.0-20230412222916-60cfeb46143b/go.mod h1:9lRMC4XN3/BLPtIp6kAKwIaHu369NOf2rMucPzipz50= github.com/cockroachdb/redact v1.1.3 h1:AKZds10rFSIj7qADf0g46UixK8NNLwWTNdCIGS5wfSQ= github.com/cockroachdb/redact v1.1.3/go.mod h1:BVNblN9mBWFyMyqK1k3AAiSxhvhfK2oOZZ2lK+dpvRg= github.com/codahale/hdrhistogram v0.0.0-20161010025455-3a0bb77429bd/go.mod h1:sE/e/2PUdi/liOCUjSTXgM1o87ZssimdTWN964YiIeI= github.com/codegangsta/inject v0.0.0-20150114235600-33e0aa1cb7c0/go.mod h1:4Zcjuz89kmFXt9morQgcfYZAYZ5n8WHjt81YYWIwtTM= -github.com/cometbft/cometbft v0.37.0 h1:M005vBaSaugvYYmNZwJOopynQSjwLoDTwflnQ/I/eYk= -github.com/cometbft/cometbft v0.37.0/go.mod h1:Y2MMMN//O5K4YKd8ze4r9jmk4Y7h0ajqILXbH5JQFVs= +github.com/cometbft/cometbft v0.37.1-0.20230411132551-3a91d155e664 h1:BbCkbnaU3R603XpnbqvuDU8Kfv+hjhiFILOHhVFntsw= +github.com/cometbft/cometbft v0.37.1-0.20230411132551-3a91d155e664/go.mod h1:Y2MMMN//O5K4YKd8ze4r9jmk4Y7h0ajqILXbH5JQFVs= github.com/cometbft/cometbft-db v0.7.0 h1:uBjbrBx4QzU0zOEnU8KxoDl18dMNgDh+zZRUE0ucsbo= github.com/cometbft/cometbft-db v0.7.0/go.mod h1:yiKJIm2WKrt6x8Cyxtq9YTEcIMPcEe4XPxhgX59Fzf0= github.com/confio/ics23/go v0.9.0 h1:cWs+wdbS2KRPZezoaaj+qBleXgUk5WOQFMP3CQFGTr4= @@ -339,7 +337,7 @@ github.com/coreos/etcd v3.3.10+incompatible/go.mod h1:uF7uidLiAD3TWHmW31ZFd/JWoc github.com/coreos/go-etcd v2.0.0+incompatible/go.mod h1:Jez6KQU2B/sWsbdaef3ED8NzMklzPG4d5KIOhIy30Tk= github.com/coreos/go-semver v0.2.0/go.mod h1:nnelYz7RCh+5ahJtPPxZlU+153eP4D4r3EedlOD2RNk= github.com/coreos/go-systemd v0.0.0-20180511133405-39ca1b05acc7/go.mod h1:F5haX7vjVVG0kc13fIWeqUViNPyEJxv/OmvnBo0Yme4= -github.com/coreos/go-systemd/v22 v22.3.3-0.20220203105225-a9a7ef127534/go.mod h1:Y58oyj3AT4RCenI/lSvhwexgC+NSVTIJ3seZv2GcEnc= +github.com/coreos/go-systemd/v22 v22.5.0/go.mod h1:Y58oyj3AT4RCenI/lSvhwexgC+NSVTIJ3seZv2GcEnc= github.com/coreos/pkg v0.0.0-20160727233714-3ac0863d7acf/go.mod h1:E3G3o1h8I7cfcXa63jLwjI0eiQQMgzzUDFVpN/nH/eA= github.com/cosmos/btcutil v1.0.5 h1:t+ZFcX77LpKtDBhjucvnOH8C2l2ioGsBNEQ3jef8xFk= github.com/cosmos/btcutil v1.0.5/go.mod h1:IyB7iuqZMJlthe2tkIFL33xPyzbFYP0XVdS8P5lUPis= @@ -353,8 +351,8 @@ github.com/cosmos/go-bip39 v1.0.0/go.mod h1:RNJv0H/pOIVgxw6KS7QeX2a0Uo0aKUlfhZ4x github.com/cosmos/gogogateway v1.2.0 h1:Ae/OivNhp8DqBi/sh2A8a1D0y638GpL3tkmLQAiKxTE= github.com/cosmos/gogogateway v1.2.0/go.mod h1:iQpLkGWxYcnCdz5iAdLcRBSw3h7NXeOkZ4GUkT+tbFI= github.com/cosmos/gogoproto v1.4.2/go.mod h1:cLxOsn1ljAHSV527CHOtaIP91kK6cCrZETRBrkzItWU= -github.com/cosmos/gogoproto v1.4.6 h1:Ee7z15dWJaGlgM2rWrK8N2IX7PQcuccu8oG68jp5RL4= -github.com/cosmos/gogoproto v1.4.6/go.mod h1:VS/ASYmPgv6zkPKLjR9EB91lwbLHOzaGCirmKKhncfI= +github.com/cosmos/gogoproto v1.4.8 h1:BrHKc6WFZt8+jRV71vKSQE+JrfF+JAnzrKo2VP7wIZ4= +github.com/cosmos/gogoproto v1.4.8/go.mod h1:hnb0DIEWTv+wdNzNcqus5xCQXq5+CXauq1FJuurRfVY= github.com/cosmos/iavl v0.21.0-beta.1 h1:fBQeBc8HLZ14plJNcmGfaOXSSMLVEHvEQXiTXSD76m0= github.com/cosmos/iavl v0.21.0-beta.1/go.mod h1:25YJYzilTErJ2mKfNB3xyWL9IsCwEQdNzdIutg2mh3U= github.com/cosmos/keyring v1.2.0 h1:8C1lBP9xhImmIabyXW4c3vFjjLiBdGCmfLUfeZlV1Yo= @@ -375,9 +373,9 @@ github.com/danieljoos/wincred v1.1.2/go.mod h1:GijpziifJoIBfYh+S7BbkdUTU4LfM+QnG github.com/davecgh/go-spew v1.1.0/go.mod h1:J7Y8YcW2NihsgmVo/mv3lAwl/skON4iLHjSsI+c5H38= github.com/davecgh/go-spew v1.1.1 h1:vj9j/u1bqnvCEfJOwUhtlOARqs3+rkHYY13jYWTU97c= github.com/davecgh/go-spew v1.1.1/go.mod h1:J7Y8YcW2NihsgmVo/mv3lAwl/skON4iLHjSsI+c5H38= -github.com/decred/dcrd/crypto/blake256 v1.0.0 h1:/8DMNYp9SGi5f0w7uCm6d6M4OU2rGFK09Y2A4Xv7EE0= -github.com/decred/dcrd/dcrec/secp256k1/v4 v4.1.0 h1:HbphB4TFFXpv7MNrT52FGrrgVXF1owhMVTHFZIlnvd4= -github.com/decred/dcrd/dcrec/secp256k1/v4 v4.1.0/go.mod h1:DZGJHZMqrU4JJqFAWUS2UO1+lbSKsdiOoYi9Zzey7Fc= +github.com/decred/dcrd/crypto/blake256 v1.0.1 h1:7PltbUIQB7u/FfZ39+DGa/ShuMyJ5ilcvdfma9wOH6Y= +github.com/decred/dcrd/dcrec/secp256k1/v4 v4.2.0 h1:8UrgZ3GkP4i/CLijOJx79Yu+etlyjdBU4sfcs2WYQMs= +github.com/decred/dcrd/dcrec/secp256k1/v4 v4.2.0/go.mod h1:v57UDF4pDQJcEfFUCRop3lJL149eHGSe9Jvczhzjo/0= github.com/desertbit/timer v0.0.0-20180107155436-c41aec40b27f h1:U5y3Y5UE0w7amNe7Z5G/twsBW0KEalRQXZzf8ufSh9I= github.com/desertbit/timer v0.0.0-20180107155436-c41aec40b27f/go.mod h1:xH/i4TFMt8koVQZ6WFms69WAsDWr2XsYL3Hkl7jkoLE= github.com/dgraph-io/badger v1.6.0/go.mod h1:zwt7syl517jmP8s94KqSxTlM6IMsdhYy6psNgSztDR4= @@ -438,8 +436,8 @@ github.com/fsnotify/fsnotify v1.6.0 h1:n+5WquG0fcWoWp6xPWfHdbskMCQaFnG6PfBrh1Ky4 github.com/fsnotify/fsnotify v1.6.0/go.mod h1:sl3t1tCWJFWoRz9R8WJCbQihKKwmorjAbSClcnxKAGw= github.com/gavv/httpexpect v2.0.0+incompatible/go.mod h1:x+9tiU1YnrOvnB725RkpoLv1M62hOWzwo5OXotisrKc= github.com/getsentry/sentry-go v0.12.0/go.mod h1:NSap0JBYWzHND8oMbyi0+XZhUalc1TBdRL1M71JZW2c= -github.com/getsentry/sentry-go v0.19.0 h1:BcCH3CN5tXt5aML+gwmbFwVptLLQA+eT866fCO9wVOM= -github.com/getsentry/sentry-go v0.19.0/go.mod h1:y3+lGEFEFexZtpbG1GUE2WD/f9zGyKYwpEqryTOC/nE= +github.com/getsentry/sentry-go v0.20.0 h1:bwXW98iMRIWxn+4FgPW7vMrjmbym6HblXALmhjHmQaQ= +github.com/getsentry/sentry-go v0.20.0/go.mod h1:lc76E2QywIyW8WuBnwl8Lc4bkmQH4+w1gwTf25trprY= github.com/ghodss/yaml v1.0.0/go.mod h1:4dBDuWmgqj2HViK6kFavaiC9ZROes6MMH2rRYeMEF04= github.com/gin-contrib/sse v0.1.0 h1:Y/yl/+YNO8GZSjAhjMsSuLt29uWRFHdHYUb5lYOV9qE= github.com/gin-contrib/sse v0.1.0/go.mod h1:RHrZQHXnP2xjPF+u1gW/2HnVO7nvIa9PG3Gm+fLHvGI= @@ -702,7 +700,6 @@ github.com/imkira/go-interpol v1.1.0/go.mod h1:z0h2/2T3XF8kyEPpRgJ3kmNv+C43p+I/C github.com/improbable-eng/grpc-web v0.15.0 h1:BN+7z6uNXZ1tQGcNAuaU1YjsLTApzkjt2tzCixLaUPQ= github.com/improbable-eng/grpc-web v0.15.0/go.mod h1:1sy9HKV4Jt9aEs9JSnkWlRJPuPtwNr0l57L4f878wP8= github.com/inconshreveable/mousetrap v1.0.0/go.mod h1:PxqpIevigyE2G7u3NXJIT2ANytuPF1OarO4DADm73n8= -github.com/inconshreveable/mousetrap v1.0.1/go.mod h1:vpF70FUmC8bwa3OWnCshd2FqLfsEA9PFc4w1p2J65bw= github.com/inconshreveable/mousetrap v1.1.0 h1:wN+x4NVGpMsO7ErUn/mUI3vEoE6Jt13X2s0bqwp9tc8= github.com/inconshreveable/mousetrap v1.1.0/go.mod h1:vpF70FUmC8bwa3OWnCshd2FqLfsEA9PFc4w1p2J65bw= github.com/influxdata/influxdb1-client v0.0.0-20191209144304-8bf82d3c094d/go.mod h1:qj24IKcXYK6Iy9ceXlo3Tc+vtHo9lIhSX5JddghvEPo= @@ -749,8 +746,8 @@ github.com/klauspost/compress v1.10.3/go.mod h1:aoV0uJVorq1K+umq18yTdKaF57EivdYs github.com/klauspost/compress v1.11.7/go.mod h1:aoV0uJVorq1K+umq18yTdKaF57EivdYsUV+/s2qKfXs= github.com/klauspost/compress v1.12.3/go.mod h1:8dP1Hq4DHOhN9w426knH3Rhby4rFm6D8eO+e+Dq5Gzg= github.com/klauspost/compress v1.15.11/go.mod h1:QPwzmACJjUTFsnSHH934V6woptycfrDDJnH7hvFVbGM= -github.com/klauspost/compress v1.16.3 h1:XuJt9zzcnaz6a16/OU53ZjWp/v7/42WcR5t2a0PcNQY= -github.com/klauspost/compress v1.16.3/go.mod h1:ntbaceVETuRiXiv4DpjP66DpAtAGkEQskQzEyD//IeE= +github.com/klauspost/compress v1.16.5 h1:IFV2oUNUzZaz+XyusxpLzpzS8Pt5rh0Z16For/djlyI= +github.com/klauspost/compress v1.16.5/go.mod h1:ntbaceVETuRiXiv4DpjP66DpAtAGkEQskQzEyD//IeE= github.com/klauspost/cpuid v1.2.1/go.mod h1:Pj4uuM528wm8OyEC2QMXAi2YiTZ96dNQPGgoMS4s3ek= github.com/konsorten/go-windows-terminal-sequences v1.0.1/go.mod h1:T0+1ngSBFLxvqU3pZ+m/2kptfBszLMUkC4ZK/EgS/cQ= github.com/konsorten/go-windows-terminal-sequences v1.0.3/go.mod h1:T0+1ngSBFLxvqU3pZ+m/2kptfBszLMUkC4ZK/EgS/cQ= @@ -775,8 +772,8 @@ github.com/libp2p/go-buffer-pool v0.1.0 h1:oK4mSFcQz7cTQIfqbe4MIj9gLW+mnanjyFtc6 github.com/libp2p/go-buffer-pool v0.1.0/go.mod h1:N+vh8gMqimBzdKkSMVuydVDq+UV5QTWy5HSiZacSbPg= github.com/lightstep/lightstep-tracer-common/golang/gogo v0.0.0-20190605223551-bc2310a04743/go.mod h1:qklhhLq1aX+mtWk9cPHPzaBjWImj5ULL6C7HFJtXQMM= github.com/lightstep/lightstep-tracer-go v0.18.1/go.mod h1:jlF1pusYV4pidLvZ+XD0UBX0ZE6WURAspgAczcDHrL4= -github.com/linxGnu/grocksdb v1.7.15 h1:AEhP28lkeAybv5UYNYviYISpR6bJejEnKuYbnWAnxx0= -github.com/linxGnu/grocksdb v1.7.15/go.mod h1:pY55D0o+r8yUYLq70QmhdudxYvoDb9F+9puf4m3/W+U= +github.com/linxGnu/grocksdb v1.7.16 h1:Q2co1xrpdkr5Hx3Fp+f+f7fRGhQFQhvi/+226dtLmA8= +github.com/linxGnu/grocksdb v1.7.16/go.mod h1:JkS7pl5qWpGpuVb3bPqTz8nC12X3YtPZT+Xq7+QfQo4= github.com/lyft/protoc-gen-validate v0.0.13/go.mod h1:XbGvPuh87YZc5TdIa2/I4pLk0QoUACkjt2znoq26NVQ= github.com/magiconair/properties v1.8.0/go.mod h1:PppfXfuXeibc/6YijjN8zIbojt8czPbwD3XqdrwzmxQ= github.com/magiconair/properties v1.8.7 h1:IeQXZAiQcpL9mgcAe1Nu6cX9LLw6ExEHKjN0VQdvPDY= @@ -917,8 +914,8 @@ github.com/prometheus/client_golang v1.0.0/go.mod h1:db9x61etRT2tGnBNRi70OPL5Fsn github.com/prometheus/client_golang v1.3.0/go.mod h1:hJaj2vgQTGQmVCsAACORcieXFeDPbaTKGT+JTgUa3og= github.com/prometheus/client_golang v1.4.0/go.mod h1:e9GMxYsXl05ICDXkRhurwBS4Q3OK1iX/F2sw+iXX5zU= github.com/prometheus/client_golang v1.7.1/go.mod h1:PY5Wy2awLA44sXw4AOSfFBetzPP4j5+D6mVACh+pe2M= -github.com/prometheus/client_golang v1.14.0 h1:nJdhIvne2eSX/XRAFV9PcvFFRbrjbcTUj0VP62TMhnw= -github.com/prometheus/client_golang v1.14.0/go.mod h1:8vpkKitgIVNcqrRBWh1C4TIUQgYNtG/XQE4E/Zae36Y= +github.com/prometheus/client_golang v1.15.0 h1:5fCgGYogn0hFdhyhLbw7hEsWxufKtY9klyvdNfFlFhM= +github.com/prometheus/client_golang v1.15.0/go.mod h1:e9yaBhRPU2pPNsZwE+JdQl0KEt1N9XgF6zxWmaC0xOk= github.com/prometheus/client_model v0.0.0-20180712105110-5c3871d89910/go.mod h1:MbSGuTsp3dbXC40dX6PRTWyKYBIrTGTE9sqQNg2J8bo= github.com/prometheus/client_model v0.0.0-20190115171406-56726106282f/go.mod h1:MbSGuTsp3dbXC40dX6PRTWyKYBIrTGTE9sqQNg2J8bo= github.com/prometheus/client_model v0.0.0-20190129233127-fd36f4220a90/go.mod h1:xMI15A0UPsDsEKsMN9yxemIoYk6Tm2C1GtYGdfGttqA= @@ -953,14 +950,15 @@ github.com/rogpeppe/go-internal v1.3.0/go.mod h1:M8bDsm7K2OlrFYOpmOWEs/qY81heoFR github.com/rogpeppe/go-internal v1.6.1/go.mod h1:xXDCJY+GAPziupqXw64V24skbSoqbTEfhy4qGm1nDQc= github.com/rogpeppe/go-internal v1.8.0/go.mod h1:WmiCO8CzOY8rg0OYDC4/i/2WRWAB6poM+XZ2dLUbcbE= github.com/rogpeppe/go-internal v1.8.1/go.mod h1:JeRgkft04UBgHMgCIwADu4Pn6Mtm5d4nPKWu0nJ5d+o= -github.com/rogpeppe/go-internal v1.9.0 h1:73kH8U+JUqXU8lRuOHeVHaa/SZPifC7BkcraZVejAe8= github.com/rogpeppe/go-internal v1.9.0/go.mod h1:WtVeX8xhTBvf0smdhujwtBcq4Qrzq/fJaraNFVN+nFs= +github.com/rogpeppe/go-internal v1.10.0 h1:TMyTOH3F/DB16zRVcYyreMH6GnZZrwQVAoYjRBZyWFQ= +github.com/rogpeppe/go-internal v1.10.0/go.mod h1:UQnix2H7Ngw/k4C5ijL5+65zddjncjaFoBhdsK/akog= github.com/rs/cors v1.7.0/go.mod h1:gFx+x8UowdsKA9AchylcLynDq+nNFfI8FkUZdN/jGCU= github.com/rs/cors v1.8.3 h1:O+qNyWn7Z+F9M0ILBHgMVPuB1xTOucVd5gtaYyXBpRo= github.com/rs/cors v1.8.3/go.mod h1:XyqrcTp5zjWr1wsJ8PIRZssZ8b/WMcMf71DJnit4EMU= github.com/rs/xid v1.4.0/go.mod h1:trrq9SKmegXys3aeAKXMUTdJsYXVwGY3RLcfgqegfbg= -github.com/rs/zerolog v1.29.0 h1:Zes4hju04hjbvkVkOhdl2HpZa+0PmVwigmo8XoORE5w= -github.com/rs/zerolog v1.29.0/go.mod h1:NILgTygv/Uej1ra5XxGf82ZFSLk58MFGAUS2o6usyD0= +github.com/rs/zerolog v1.29.1 h1:cO+d60CHkknCbvzEWxP0S9K6KqyTjrCNUy1LdQLCGPc= +github.com/rs/zerolog v1.29.1/go.mod h1:Le6ESbR7hc+DP6Lt1THiV8CQSdkkNrd3R0XbEgp3ZBU= github.com/russross/blackfriday v1.5.2/go.mod h1:JO/DiYxRf+HjHt06OyowR9PTA263kcR/rfWxYHBV53g= github.com/russross/blackfriday/v2 v2.0.1/go.mod h1:+Rmxgy9KzJVeS9/2gXHxylqXiyQDYRxCVz55jmeOWTM= github.com/russross/blackfriday/v2 v2.1.0/go.mod h1:+Rmxgy9KzJVeS9/2gXHxylqXiyQDYRxCVz55jmeOWTM= @@ -993,8 +991,8 @@ github.com/spf13/cast v1.5.0 h1:rj3WzYc11XZaIZMPKmwP96zkFEnnAmV8s6XbB2aY32w= github.com/spf13/cast v1.5.0/go.mod h1:SpXXQ5YoyJw6s3/6cMTQuxvgRl3PCJiyaX9p6b155UU= github.com/spf13/cobra v0.0.3/go.mod h1:1l0Ry5zgKvJasoi3XT1TypsSe7PqH0Sj9dhYf7v3XqQ= github.com/spf13/cobra v0.0.5/go.mod h1:3K3wKZymM7VvHMDS9+Akkh4K60UwM26emMESw8tLCHU= -github.com/spf13/cobra v1.6.1 h1:o94oiPyS4KD1mPy2fmcYYHHfCxLqYjJOhGsCHFZtEzA= -github.com/spf13/cobra v1.6.1/go.mod h1:IOw/AERYS7UzyrGinqmz6HLUo219MORXGxhbaJUqzrY= +github.com/spf13/cobra v1.7.0 h1:hyqWnYt1ZQShIddO5kBpj3vu05/++x6tJ6dg8EC572I= +github.com/spf13/cobra v1.7.0/go.mod h1:uLxZILRyS/50WlhOIKD7W6V5bgeIt+4sICxh6uRMrb0= github.com/spf13/jwalterweatherman v1.0.0/go.mod h1:cQK4TGJAtQXfYWX+Ddv3mKDzgVb68N+wFjFa4jdeBTo= github.com/spf13/jwalterweatherman v1.1.0 h1:ue6voC5bR5F8YxI5S67j9i582FU4Qvo2bmqnqMYADFk= github.com/spf13/jwalterweatherman v1.1.0/go.mod h1:aNWZUN0dPAAO/Ljvb5BEdw96iTZ0EXowPYD95IqWIGo= @@ -1119,8 +1117,8 @@ golang.org/x/crypto v0.0.0-20210421170649-83a5a9bb288b/go.mod h1:T9bdIzuCu7OtxOm golang.org/x/crypto v0.0.0-20210711020723-a769d52b0f97/go.mod h1:GvvjBRRGRdwPK5ydBHafDWAxML/pGHZbMvKqRZ5+Abc= golang.org/x/crypto v0.0.0-20210921155107-089bfa567519/go.mod h1:GvvjBRRGRdwPK5ydBHafDWAxML/pGHZbMvKqRZ5+Abc= golang.org/x/crypto v0.0.0-20211108221036-ceb1ce70b4fa/go.mod h1:GvvjBRRGRdwPK5ydBHafDWAxML/pGHZbMvKqRZ5+Abc= -golang.org/x/crypto v0.7.0 h1:AvwMYaRytfdeVt3u6mLaxYtErKYjxA2OXjJ1HHq6t3A= -golang.org/x/crypto v0.7.0/go.mod h1:pYwdfH91IfpZVANVyUOhSIPZaFoJGxTFbZhFTx+dXZU= +golang.org/x/crypto v0.8.0 h1:pd9TJtTueMTVQXzk8E2XESSMQDj/U7OUu0PqJqPXQjQ= +golang.org/x/crypto v0.8.0/go.mod h1:mRqEX+O9/h5TFCrQhkgjo2yKi0yYA+9ecGkdQoHrywE= golang.org/x/exp v0.0.0-20190121172915-509febef88a4/go.mod h1:CJ0aWSM057203Lf6IL+f9T1iT9GByDxfZKAQTCR3kQA= golang.org/x/exp v0.0.0-20190306152737-a1d7652674e8/go.mod h1:CJ0aWSM057203Lf6IL+f9T1iT9GByDxfZKAQTCR3kQA= golang.org/x/exp v0.0.0-20190510132918-efd6b22b2522/go.mod h1:ZjyILWgesfNpC6sMxTJOJm9Kp84zZh5NQWvqDGG3Qr8= @@ -1224,8 +1222,8 @@ golang.org/x/net v0.0.0-20220722155237-a158d28d115b/go.mod h1:XRhObCWvk6IyKnWLug golang.org/x/net v0.0.0-20220909164309-bea034e7d591/go.mod h1:YDH+HFinaLZZlnHAfSS6ZXJJ9M9t4Dl22yv3iI2vPwk= golang.org/x/net v0.0.0-20221014081412-f15817d10f9b/go.mod h1:YDH+HFinaLZZlnHAfSS6ZXJJ9M9t4Dl22yv3iI2vPwk= golang.org/x/net v0.1.0/go.mod h1:Cx3nUiGt4eDBEyega/BKRp+/AlGL8hYe7U9odMt2Cco= -golang.org/x/net v0.8.0 h1:Zrh2ngAOFYneWTAIAPethzeaQLuHwhuBkuV6ZiRnUaQ= -golang.org/x/net v0.8.0/go.mod h1:QVkue5JL9kW//ek3r6jTKnTFis1tRmNAW2P1shuFdJc= +golang.org/x/net v0.9.0 h1:aWJ/m6xSmxWBx+V0XRHTlrYrPG56jKsLdTFmsSsCzOM= +golang.org/x/net v0.9.0/go.mod h1:d48xBJpPfHeWQsugry2m+kC02ZBRGRgulfHnEXEuWns= golang.org/x/oauth2 v0.0.0-20180821212333-d2e6202438be/go.mod h1:N/0e6XlmueqKjAGxoOufVs8QHGRruUQn6yWY3a++T0U= golang.org/x/oauth2 v0.0.0-20190226205417-e64efc72b421/go.mod h1:gOpvHmFTYa4IltrdGE7lF6nIHvwfUNPOp7c8zoXwtLw= golang.org/x/oauth2 v0.0.0-20190604053449-0f29369cfe45/go.mod h1:gOpvHmFTYa4IltrdGE7lF6nIHvwfUNPOp7c8zoXwtLw= @@ -1371,13 +1369,14 @@ golang.org/x/sys v0.0.0-20220811171246-fbc7d0a398ab/go.mod h1:oPkhp1MJrh7nUepCBc golang.org/x/sys v0.0.0-20220908164124-27713097b956/go.mod h1:oPkhp1MJrh7nUepCBck5+mAzfO9JrbApNNgaTdGDITg= golang.org/x/sys v0.0.0-20221010170243-090e33056c14/go.mod h1:oPkhp1MJrh7nUepCBck5+mAzfO9JrbApNNgaTdGDITg= golang.org/x/sys v0.1.0/go.mod h1:oPkhp1MJrh7nUepCBck5+mAzfO9JrbApNNgaTdGDITg= -golang.org/x/sys v0.6.0 h1:MVltZSvRTcU2ljQOhs94SXPftV6DCNnZViHeQps87pQ= golang.org/x/sys v0.6.0/go.mod h1:oPkhp1MJrh7nUepCBck5+mAzfO9JrbApNNgaTdGDITg= +golang.org/x/sys v0.7.0 h1:3jlCCIQZPdOYu1h8BkNvLz8Kgwtae2cagcG/VamtZRU= +golang.org/x/sys v0.7.0/go.mod h1:oPkhp1MJrh7nUepCBck5+mAzfO9JrbApNNgaTdGDITg= golang.org/x/term v0.0.0-20201126162022-7de9c90e9dd1/go.mod h1:bj7SfCRtBDWHUb9snDiAeCFNEtKQo2Wmx5Cou7ajbmo= golang.org/x/term v0.0.0-20210927222741-03fcf44c2211/go.mod h1:jbD1KX2456YbFQfuXm/mYQcufACuNUgVhRMnK/tPxf8= golang.org/x/term v0.1.0/go.mod h1:jbD1KX2456YbFQfuXm/mYQcufACuNUgVhRMnK/tPxf8= -golang.org/x/term v0.6.0 h1:clScbb1cHjoCkyRbWwBEUZ5H/tIFu5TAXIqaZD0Gcjw= -golang.org/x/term v0.6.0/go.mod h1:m6U89DPEgQRMq3DNkDClhWw02AUbt2daBVO4cn4Hv9U= +golang.org/x/term v0.7.0 h1:BEvjmm5fURWqcfbSKTdpkDXYBrUS1c0m8agp14W48vQ= +golang.org/x/term v0.7.0/go.mod h1:P32HKFT3hSsZrRxla30E9HqToFYAQPCMs/zFMBUFqPY= golang.org/x/text v0.0.0-20170915032832-14c0d48ead0c/go.mod h1:NqM8EUOU14njkJ3fqMW+pc6Ldnwhi/IjpwHt7yyuwOQ= golang.org/x/text v0.3.0/go.mod h1:NqM8EUOU14njkJ3fqMW+pc6Ldnwhi/IjpwHt7yyuwOQ= golang.org/x/text v0.3.1-0.20180807135948-17ff2d5776d2/go.mod h1:NqM8EUOU14njkJ3fqMW+pc6Ldnwhi/IjpwHt7yyuwOQ= @@ -1388,8 +1387,8 @@ golang.org/x/text v0.3.5/go.mod h1:5Zoc/QRtKVWzQhOtBMvqHzDpF6irO9z98xDceosuGiQ= golang.org/x/text v0.3.6/go.mod h1:5Zoc/QRtKVWzQhOtBMvqHzDpF6irO9z98xDceosuGiQ= golang.org/x/text v0.3.7/go.mod h1:u+2+/6zg+i71rQMx5EYifcz6MCKuco9NR6JIITiCfzQ= golang.org/x/text v0.4.0/go.mod h1:mrYo+phRRbMaCq/xk9113O4dZlRixOauAjOtrjsXDZ8= -golang.org/x/text v0.8.0 h1:57P1ETyNKtuIjB4SRd15iJxuhj8Gc416Y78H3qgMh68= -golang.org/x/text v0.8.0/go.mod h1:e1OnstbJyHTd6l/uOt8jFFHp6TRDWZR/bV3emEE/zU8= +golang.org/x/text v0.9.0 h1:2sjJmO8cDvYveuX97RDLsxlyUxLl+GHoLxBiRdHllBE= +golang.org/x/text v0.9.0/go.mod h1:e1OnstbJyHTd6l/uOt8jFFHp6TRDWZR/bV3emEE/zU8= golang.org/x/time v0.0.0-20180412165947-fbb02b2291d2/go.mod h1:tRJNPiyCQ0inRvYxbN9jk5I+vvW/OXSQhTDSoE431IQ= golang.org/x/time v0.0.0-20181108054448-85acf8d2951c/go.mod h1:tRJNPiyCQ0inRvYxbN9jk5I+vvW/OXSQhTDSoE431IQ= golang.org/x/time v0.0.0-20190308202827-9d24e82272b4/go.mod h1:tRJNPiyCQ0inRvYxbN9jk5I+vvW/OXSQhTDSoE431IQ= @@ -1640,8 +1639,8 @@ google.golang.org/genproto v0.0.0-20221010155953-15ba04fc1c0e/go.mod h1:3526vdqw google.golang.org/genproto v0.0.0-20221014173430-6e2ab493f96b/go.mod h1:1vXfmgAz9N9Jx0QA82PqRVauvCz1SGSz739p0f183jM= google.golang.org/genproto v0.0.0-20221014213838-99cd37c6964a/go.mod h1:1vXfmgAz9N9Jx0QA82PqRVauvCz1SGSz739p0f183jM= google.golang.org/genproto v0.0.0-20221025140454-527a21cfbd71/go.mod h1:9qHF0xnpdSfF6knlcsnpzUu5y+rpwgbvsyGAZPBMg4s= -google.golang.org/genproto v0.0.0-20230320184635-7606e756e683 h1:khxVcsk/FhnzxMKOyD+TDGwjbEOpcPuIpmafPGFmhMA= -google.golang.org/genproto v0.0.0-20230320184635-7606e756e683/go.mod h1:NWraEVixdDnqcqQ30jipen1STv2r/n24Wb7twVTGR4s= +google.golang.org/genproto v0.0.0-20230410155749-daa745c078e1 h1:KpwkzHKEF7B9Zxg18WzOa7djJ+Ha5DzthMyZYQfEn2A= +google.golang.org/genproto v0.0.0-20230410155749-daa745c078e1/go.mod h1:nKE/iIaLqn2bQwXBg8f1g2Ylh6r5MN5CmZvuzZCgsCU= google.golang.org/grpc v1.12.0/go.mod h1:yo6s7OP7yaDglbqo1J04qKzAhqBH6lvTonzMVmEdcZw= google.golang.org/grpc v1.17.0/go.mod h1:6QZJwpn2B+Zp71q/5VxRsJ6NXXVCE5NRUHRo+f3cWCs= google.golang.org/grpc v1.19.0/go.mod h1:mqu4LbDTu4XGKhr4mRzUsmM4RtVoemTSY81AxZiDr8c= diff --git a/tests/integration/aminojson/aminojson_test.go b/tests/integration/aminojson/aminojson_test.go index 8d80bcda5ce2..25b714b6a736 100644 --- a/tests/integration/aminojson/aminojson_test.go +++ b/tests/integration/aminojson/aminojson_test.go @@ -1,16 +1,14 @@ package aminojson import ( + "context" "fmt" "reflect" "testing" "time" - cosmos_proto "github.com/cosmos/cosmos-proto" "github.com/stretchr/testify/require" "google.golang.org/protobuf/proto" - "google.golang.org/protobuf/reflect/protoreflect" - "google.golang.org/protobuf/reflect/protoregistry" "google.golang.org/protobuf/types/known/anypb" "google.golang.org/protobuf/types/known/durationpb" "google.golang.org/protobuf/types/known/timestamppb" @@ -19,45 +17,39 @@ import ( "github.com/cosmos/cosmos-proto/rapidproto" gogoproto "github.com/cosmos/gogoproto/proto" - "cosmossdk.io/api/amino" authapi "cosmossdk.io/api/cosmos/auth/v1beta1" authzapi "cosmossdk.io/api/cosmos/authz/v1beta1" bankapi "cosmossdk.io/api/cosmos/bank/v1beta1" v1beta1 "cosmossdk.io/api/cosmos/base/v1beta1" - consensusapi "cosmossdk.io/api/cosmos/consensus/v1" "cosmossdk.io/api/cosmos/crypto/ed25519" multisigapi "cosmossdk.io/api/cosmos/crypto/multisig" "cosmossdk.io/api/cosmos/crypto/secp256k1" distapi "cosmossdk.io/api/cosmos/distribution/v1beta1" - evidenceapi "cosmossdk.io/api/cosmos/evidence/v1beta1" - feegrantapi "cosmossdk.io/api/cosmos/feegrant/v1beta1" - gov_v1_api "cosmossdk.io/api/cosmos/gov/v1" gov_v1beta1_api "cosmossdk.io/api/cosmos/gov/v1beta1" - groupapi "cosmossdk.io/api/cosmos/group/v1" - mintapi "cosmossdk.io/api/cosmos/mint/v1beta1" - paramsapi "cosmossdk.io/api/cosmos/params/v1beta1" slashingapi "cosmossdk.io/api/cosmos/slashing/v1beta1" stakingapi "cosmossdk.io/api/cosmos/staking/v1beta1" - upgradeapi "cosmossdk.io/api/cosmos/upgrade/v1beta1" + txv1beta1 "cosmossdk.io/api/cosmos/tx/v1beta1" vestingapi "cosmossdk.io/api/cosmos/vesting/v1beta1" "cosmossdk.io/x/evidence" - evidencetypes "cosmossdk.io/x/evidence/types" - feegranttypes "cosmossdk.io/x/feegrant" feegrantmodule "cosmossdk.io/x/feegrant/module" "cosmossdk.io/x/tx/signing/aminojson" + signing_testutil "cosmossdk.io/x/tx/signing/testutil" "cosmossdk.io/x/upgrade" - upgradetypes "cosmossdk.io/x/upgrade/types" codectypes "github.com/cosmos/cosmos-sdk/codec/types" ed25519types "github.com/cosmos/cosmos-sdk/crypto/keys/ed25519" "github.com/cosmos/cosmos-sdk/crypto/keys/multisig" secp256k1types "github.com/cosmos/cosmos-sdk/crypto/keys/secp256k1" gogo_testpb "github.com/cosmos/cosmos-sdk/tests/integration/aminojson/internal/gogo/testpb" pulsar_testpb "github.com/cosmos/cosmos-sdk/tests/integration/aminojson/internal/pulsar/testpb" + "github.com/cosmos/cosmos-sdk/tests/integration/rapidgen" "github.com/cosmos/cosmos-sdk/testutil/testdata" "github.com/cosmos/cosmos-sdk/types" "github.com/cosmos/cosmos-sdk/types/bech32" "github.com/cosmos/cosmos-sdk/types/module/testutil" + signingtypes "github.com/cosmos/cosmos-sdk/types/tx/signing" "github.com/cosmos/cosmos-sdk/x/auth" + "github.com/cosmos/cosmos-sdk/x/auth/signing" + "github.com/cosmos/cosmos-sdk/x/auth/tx" authtypes "github.com/cosmos/cosmos-sdk/x/auth/types" "github.com/cosmos/cosmos-sdk/x/auth/vesting" vestingtypes "github.com/cosmos/cosmos-sdk/x/auth/vesting/types" @@ -66,251 +58,19 @@ import ( "github.com/cosmos/cosmos-sdk/x/bank" banktypes "github.com/cosmos/cosmos-sdk/x/bank/types" "github.com/cosmos/cosmos-sdk/x/consensus" - consensustypes "github.com/cosmos/cosmos-sdk/x/consensus/types" "github.com/cosmos/cosmos-sdk/x/distribution" disttypes "github.com/cosmos/cosmos-sdk/x/distribution/types" "github.com/cosmos/cosmos-sdk/x/gov" - gov_v1_types "github.com/cosmos/cosmos-sdk/x/gov/types/v1" gov_v1beta1_types "github.com/cosmos/cosmos-sdk/x/gov/types/v1beta1" - grouptypes "github.com/cosmos/cosmos-sdk/x/group" groupmodule "github.com/cosmos/cosmos-sdk/x/group/module" "github.com/cosmos/cosmos-sdk/x/mint" - minttypes "github.com/cosmos/cosmos-sdk/x/mint/types" "github.com/cosmos/cosmos-sdk/x/params" - "github.com/cosmos/cosmos-sdk/x/params/types/proposal" "github.com/cosmos/cosmos-sdk/x/slashing" slashingtypes "github.com/cosmos/cosmos-sdk/x/slashing/types" "github.com/cosmos/cosmos-sdk/x/staking" stakingtypes "github.com/cosmos/cosmos-sdk/x/staking/types" ) -type generatedType struct { - pulsar proto.Message - gogo gogoproto.Message - opts rapidproto.GeneratorOptions -} - -func genType(gogo gogoproto.Message, pulsar proto.Message, opts rapidproto.GeneratorOptions) generatedType { - return generatedType{ - pulsar: pulsar, - gogo: gogo, - opts: opts, - } -} - -func withDecisionPolicy(opts rapidproto.GeneratorOptions) rapidproto.GeneratorOptions { - return opts. - WithAnyTypes( - &groupapi.ThresholdDecisionPolicy{}, - &groupapi.PercentageDecisionPolicy{}). - WithDisallowNil(). - WithInterfaceHint("cosmos.group.v1.DecisionPolicy", &groupapi.ThresholdDecisionPolicy{}). - WithInterfaceHint("cosmos.group.v1.DecisionPolicy", &groupapi.PercentageDecisionPolicy{}) -} - -func generatorFieldMapper(t *rapid.T, field protoreflect.FieldDescriptor, name string) (protoreflect.Value, bool) { - opts := field.Options() - switch { - case proto.HasExtension(opts, cosmos_proto.E_Scalar): - scalar := proto.GetExtension(opts, cosmos_proto.E_Scalar).(string) - switch scalar { - case "cosmos.Int": - i32 := rapid.Int32().Draw(t, name) - return protoreflect.ValueOfString(fmt.Sprintf("%d", i32)), true - case "cosmos.Dec": - return protoreflect.ValueOfString(""), true - } - case field.Kind() == protoreflect.BytesKind: - if proto.HasExtension(opts, amino.E_Encoding) { - encoding := proto.GetExtension(opts, amino.E_Encoding).(string) - if encoding == "cosmos_dec_bytes" { - return protoreflect.ValueOfBytes([]byte{}), true - } - } - } - - return protoreflect.Value{}, false -} - -var ( - genOpts = rapidproto.GeneratorOptions{ - Resolver: protoregistry.GlobalTypes, - FieldMaps: []rapidproto.FieldMapper{generatorFieldMapper}, - } - genTypes = []generatedType{ - // auth - genType(&authtypes.Params{}, &authapi.Params{}, genOpts), - genType(&authtypes.BaseAccount{}, &authapi.BaseAccount{}, genOpts.WithAnyTypes(&ed25519.PubKey{})), - genType(&authtypes.ModuleAccount{}, &authapi.ModuleAccount{}, genOpts.WithAnyTypes(&ed25519.PubKey{})), - genType(&authtypes.ModuleCredential{}, &authapi.ModuleCredential{}, genOpts), - genType(&authtypes.MsgUpdateParams{}, &authapi.MsgUpdateParams{}, genOpts.WithDisallowNil()), - - // authz - genType(&authztypes.GenericAuthorization{}, &authzapi.GenericAuthorization{}, genOpts), - genType(&authztypes.Grant{}, &authzapi.Grant{}, - genOpts.WithAnyTypes(&authzapi.GenericAuthorization{}). - WithDisallowNil(). - WithInterfaceHint("cosmos.authz.v1beta1.Authorization", &authzapi.GenericAuthorization{}), - ), - genType(&authztypes.MsgGrant{}, &authzapi.MsgGrant{}, - genOpts.WithAnyTypes(&authzapi.GenericAuthorization{}). - WithInterfaceHint("cosmos.authz.v1beta1.Authorization", &authzapi.GenericAuthorization{}). - WithDisallowNil(), - ), - genType(&authztypes.MsgExec{}, &authzapi.MsgExec{}, - genOpts.WithAnyTypes(&authzapi.MsgGrant{}, &authzapi.GenericAuthorization{}). - WithDisallowNil(). - WithInterfaceHint("cosmos.authz.v1beta1.Authorization", &authzapi.GenericAuthorization{}). - WithInterfaceHint("cosmos.base.v1beta1.Msg", &authzapi.MsgGrant{}), - ), - - // bank - genType(&banktypes.MsgSend{}, &bankapi.MsgSend{}, genOpts.WithDisallowNil()), - genType(&banktypes.MsgMultiSend{}, &bankapi.MsgMultiSend{}, genOpts.WithDisallowNil()), - genType(&banktypes.MsgUpdateParams{}, &bankapi.MsgUpdateParams{}, genOpts.WithDisallowNil()), - genType(&banktypes.MsgSetSendEnabled{}, &bankapi.MsgSetSendEnabled{}, genOpts), - genType(&banktypes.SendAuthorization{}, &bankapi.SendAuthorization{}, genOpts), - genType(&banktypes.Params{}, &bankapi.Params{}, genOpts), - - // consensus - genType(&consensustypes.MsgUpdateParams{}, &consensusapi.MsgUpdateParams{}, genOpts.WithDisallowNil()), - - // crypto - genType(&multisig.LegacyAminoPubKey{}, &multisigapi.LegacyAminoPubKey{}, - genOpts.WithAnyTypes(&ed25519.PubKey{}, &secp256k1.PubKey{})), - - // distribution - genType(&disttypes.MsgWithdrawDelegatorReward{}, &distapi.MsgWithdrawDelegatorReward{}, genOpts), - genType(&disttypes.MsgWithdrawValidatorCommission{}, &distapi.MsgWithdrawValidatorCommission{}, genOpts), - genType(&disttypes.MsgSetWithdrawAddress{}, &distapi.MsgSetWithdrawAddress{}, genOpts), - genType(&disttypes.MsgFundCommunityPool{}, &distapi.MsgFundCommunityPool{}, genOpts), - genType(&disttypes.MsgUpdateParams{}, &distapi.MsgUpdateParams{}, genOpts.WithDisallowNil()), - genType(&disttypes.MsgCommunityPoolSpend{}, &distapi.MsgCommunityPoolSpend{}, genOpts), - genType(&disttypes.MsgDepositValidatorRewardsPool{}, &distapi.MsgDepositValidatorRewardsPool{}, genOpts), - genType(&disttypes.Params{}, &distapi.Params{}, genOpts), - - // evidence - genType(&evidencetypes.Equivocation{}, &evidenceapi.Equivocation{}, genOpts.WithDisallowNil()), - genType(&evidencetypes.MsgSubmitEvidence{}, &evidenceapi.MsgSubmitEvidence{}, - genOpts.WithAnyTypes(&evidenceapi.Equivocation{}). - WithDisallowNil(). - WithInterfaceHint("cosmos.evidence.v1beta1.Evidence", &evidenceapi.Equivocation{})), - - // feegrant - genType(&feegranttypes.MsgGrantAllowance{}, &feegrantapi.MsgGrantAllowance{}, - genOpts.WithDisallowNil(). - WithAnyTypes( - &feegrantapi.BasicAllowance{}, - &feegrantapi.PeriodicAllowance{}). - WithInterfaceHint("cosmos.feegrant.v1beta1.FeeAllowanceI", &feegrantapi.BasicAllowance{}). - WithInterfaceHint("cosmos.feegrant.v1beta1.FeeAllowanceI", &feegrantapi.PeriodicAllowance{}), - ), - genType(&feegranttypes.MsgRevokeAllowance{}, &feegrantapi.MsgRevokeAllowance{}, genOpts), - genType(&feegranttypes.BasicAllowance{}, &feegrantapi.BasicAllowance{}, genOpts.WithDisallowNil()), - genType(&feegranttypes.PeriodicAllowance{}, &feegrantapi.PeriodicAllowance{}, genOpts.WithDisallowNil()), - genType(&feegranttypes.AllowedMsgAllowance{}, &feegrantapi.AllowedMsgAllowance{}, - genOpts.WithDisallowNil(). - WithAnyTypes( - &feegrantapi.BasicAllowance{}, - &feegrantapi.PeriodicAllowance{}). - WithInterfaceHint("cosmos.feegrant.v1beta1.FeeAllowanceI", &feegrantapi.BasicAllowance{}). - WithInterfaceHint("cosmos.feegrant.v1beta1.FeeAllowanceI", &feegrantapi.PeriodicAllowance{}), - ), - - // gov v1beta1 - genType(&gov_v1beta1_types.MsgSubmitProposal{}, &gov_v1beta1_api.MsgSubmitProposal{}, - genOpts.WithAnyTypes(&gov_v1beta1_api.TextProposal{}). - WithDisallowNil(). - WithInterfaceHint("cosmos.gov.v1beta1.Content", &gov_v1beta1_api.TextProposal{}), - ), - genType(&gov_v1beta1_types.MsgDeposit{}, &gov_v1beta1_api.MsgDeposit{}, genOpts), - genType(&gov_v1beta1_types.MsgVote{}, &gov_v1beta1_api.MsgVote{}, genOpts), - genType(&gov_v1beta1_types.MsgVoteWeighted{}, &gov_v1beta1_api.MsgVoteWeighted{}, genOpts), - genType(&gov_v1beta1_types.TextProposal{}, &gov_v1beta1_api.TextProposal{}, genOpts), - - // gov v1 - genType(&gov_v1_types.MsgSubmitProposal{}, &gov_v1_api.MsgSubmitProposal{}, - genOpts.WithAnyTypes(&gov_v1_api.MsgVote{}, &gov_v1_api.MsgVoteWeighted{}, &gov_v1_api.MsgDeposit{}, - &gov_v1_api.MsgExecLegacyContent{}, &gov_v1_api.MsgUpdateParams{}). - WithInterfaceHint("cosmos.gov.v1beta1.Content", &gov_v1beta1_api.TextProposal{}). - WithDisallowNil(), - ), - genType(&gov_v1_types.MsgDeposit{}, &gov_v1_api.MsgDeposit{}, genOpts), - genType(&gov_v1_types.MsgVote{}, &gov_v1_api.MsgVote{}, genOpts), - genType(&gov_v1_types.MsgVoteWeighted{}, &gov_v1_api.MsgVoteWeighted{}, genOpts), - genType(&gov_v1_types.MsgExecLegacyContent{}, &gov_v1_api.MsgExecLegacyContent{}, - genOpts.WithAnyTypes(&gov_v1beta1_api.TextProposal{}). - WithDisallowNil(). - WithInterfaceHint("cosmos.gov.v1beta1.Content", &gov_v1beta1_api.TextProposal{})), - genType(&gov_v1_types.MsgUpdateParams{}, &gov_v1_api.MsgUpdateParams{}, genOpts.WithDisallowNil()), - - // group - genType(&grouptypes.MsgCreateGroup{}, &groupapi.MsgCreateGroup{}, genOpts), - genType(&grouptypes.MsgUpdateGroupMembers{}, &groupapi.MsgUpdateGroupMembers{}, genOpts), - genType(&grouptypes.MsgUpdateGroupAdmin{}, &groupapi.MsgUpdateGroupAdmin{}, genOpts), - genType(&grouptypes.MsgUpdateGroupMetadata{}, &groupapi.MsgUpdateGroupMetadata{}, genOpts), - genType(&grouptypes.MsgCreateGroupWithPolicy{}, &groupapi.MsgCreateGroupWithPolicy{}, - withDecisionPolicy(genOpts)), - genType(&grouptypes.MsgCreateGroupPolicy{}, &groupapi.MsgCreateGroupPolicy{}, - withDecisionPolicy(genOpts)), - genType(&grouptypes.MsgUpdateGroupPolicyAdmin{}, &groupapi.MsgUpdateGroupPolicyAdmin{}, genOpts), - genType(&grouptypes.MsgUpdateGroupPolicyDecisionPolicy{}, &groupapi.MsgUpdateGroupPolicyDecisionPolicy{}, - withDecisionPolicy(genOpts)), - genType(&grouptypes.MsgUpdateGroupPolicyMetadata{}, &groupapi.MsgUpdateGroupPolicyMetadata{}, genOpts), - genType(&grouptypes.MsgSubmitProposal{}, &groupapi.MsgSubmitProposal{}, - genOpts.WithDisallowNil(). - WithAnyTypes(&groupapi.MsgCreateGroup{}, &groupapi.MsgUpdateGroupMembers{}). - WithInterfaceHint("cosmos.base.v1beta1.Msg", &groupapi.MsgCreateGroup{}). - WithInterfaceHint("cosmos.base.v1beta1.Msg", &groupapi.MsgUpdateGroupMembers{}), - ), - genType(&grouptypes.MsgVote{}, &groupapi.MsgVote{}, genOpts), - genType(&grouptypes.MsgExec{}, &groupapi.MsgExec{}, genOpts), - genType(&grouptypes.MsgLeaveGroup{}, &groupapi.MsgLeaveGroup{}, genOpts), - - // mint - genType(&minttypes.Params{}, &mintapi.Params{}, genOpts), - genType(&minttypes.MsgUpdateParams{}, &mintapi.MsgUpdateParams{}, genOpts.WithDisallowNil()), - - // params - genType(&proposal.ParameterChangeProposal{}, ¶msapi.ParameterChangeProposal{}, genOpts), - - // slashing - genType(&slashingtypes.Params{}, &slashingapi.Params{}, genOpts.WithDisallowNil()), - genType(&slashingtypes.MsgUnjail{}, &slashingapi.MsgUnjail{}, genOpts), - genType(&slashingtypes.MsgUpdateParams{}, &slashingapi.MsgUpdateParams{}, genOpts.WithDisallowNil()), - - // staking - genType(&stakingtypes.MsgCreateValidator{}, &stakingapi.MsgCreateValidator{}, - genOpts.WithDisallowNil(). - WithAnyTypes(&ed25519.PubKey{}). - WithInterfaceHint("cosmos.crypto.PubKey", &ed25519.PubKey{}), - ), - genType(&stakingtypes.MsgEditValidator{}, &stakingapi.MsgEditValidator{}, genOpts.WithDisallowNil()), - genType(&stakingtypes.MsgDelegate{}, &stakingapi.MsgDelegate{}, genOpts.WithDisallowNil()), - genType(&stakingtypes.MsgUndelegate{}, &stakingapi.MsgUndelegate{}, genOpts.WithDisallowNil()), - genType(&stakingtypes.MsgBeginRedelegate{}, &stakingapi.MsgBeginRedelegate{}, genOpts.WithDisallowNil()), - genType(&stakingtypes.MsgUpdateParams{}, &stakingapi.MsgUpdateParams{}, genOpts.WithDisallowNil()), - genType(&stakingtypes.StakeAuthorization{}, &stakingapi.StakeAuthorization{}, genOpts), - - // upgrade - genType(&upgradetypes.Plan{}, &upgradeapi.Plan{}, genOpts.WithDisallowNil()), - genType(&upgradetypes.SoftwareUpgradeProposal{}, &upgradeapi.SoftwareUpgradeProposal{}, genOpts.WithDisallowNil()), - genType(&upgradetypes.CancelSoftwareUpgradeProposal{}, &upgradeapi.CancelSoftwareUpgradeProposal{}, genOpts), - genType(&upgradetypes.MsgSoftwareUpgrade{}, &upgradeapi.MsgSoftwareUpgrade{}, genOpts.WithDisallowNil()), - genType(&upgradetypes.MsgCancelUpgrade{}, &upgradeapi.MsgCancelUpgrade{}, genOpts), - - // vesting - genType(&vestingtypes.BaseVestingAccount{}, &vestingapi.BaseVestingAccount{}, genOpts.WithDisallowNil()), - genType(&vestingtypes.ContinuousVestingAccount{}, &vestingapi.ContinuousVestingAccount{}, genOpts.WithDisallowNil()), - genType(&vestingtypes.DelayedVestingAccount{}, &vestingapi.DelayedVestingAccount{}, genOpts.WithDisallowNil()), - genType(&vestingtypes.PeriodicVestingAccount{}, &vestingapi.PeriodicVestingAccount{}, genOpts.WithDisallowNil()), - genType(&vestingtypes.PermanentLockedAccount{}, &vestingapi.PermanentLockedAccount{}, genOpts.WithDisallowNil()), - genType(&vestingtypes.MsgCreateVestingAccount{}, &vestingapi.MsgCreateVestingAccount{}, genOpts), - genType(&vestingtypes.MsgCreatePermanentLockedAccount{}, &vestingapi.MsgCreatePermanentLockedAccount{}, genOpts), - genType(&vestingtypes.MsgCreatePeriodicVestingAccount{}, &vestingapi.MsgCreatePeriodicVestingAccount{}, genOpts), - } -) - // TestAminoJSON_Equivalence tests that x/tx/Encoder encoding is equivalent to the legacy Encoder encoding. // A custom generator is used to generate random messages that are then encoded using both encoders. The custom // generator only supports proto.Message (which implement the protoreflect API) so in order to test legacy gogo types @@ -333,25 +93,25 @@ func TestAminoJSON_Equivalence(t *testing.T) { slashing.AppModuleBasic{}, staking.AppModuleBasic{}, upgrade.AppModuleBasic{}, vesting.AppModuleBasic{}) aj := aminojson.NewAminoJSON() - for _, tt := range genTypes { - name := string(tt.pulsar.ProtoReflect().Descriptor().FullName()) + for _, tt := range rapidgen.DefaultGeneratedTypes { + name := string(tt.Pulsar.ProtoReflect().Descriptor().FullName()) t.Run(name, func(t *testing.T) { - gen := rapidproto.MessageGenerator(tt.pulsar, tt.opts) - fmt.Printf("testing %s\n", tt.pulsar.ProtoReflect().Descriptor().FullName()) + gen := rapidproto.MessageGenerator(tt.Pulsar, tt.Opts) + fmt.Printf("testing %s\n", tt.Pulsar.ProtoReflect().Descriptor().FullName()) rapid.Check(t, func(t *rapid.T) { // uncomment to debug; catch a panic and inspect application state - //defer func() { + // defer func() { // if r := recover(); r != nil { // //fmt.Printf("Panic: %+v\n", r) // t.FailNow() // } - //}() + // }() msg := gen.Draw(t, "msg") postFixPulsarMessage(msg) - gogo := tt.gogo - sanity := tt.pulsar + gogo := tt.Gogo + sanity := tt.Pulsar protoBz, err := proto.Marshal(msg) require.NoError(t, err) @@ -362,11 +122,55 @@ func TestAminoJSON_Equivalence(t *testing.T) { err = encCfg.Codec.Unmarshal(protoBz, gogo) require.NoError(t, err) - legacyAminoJson, err := encCfg.Amino.MarshalJSON(gogo) + legacyAminoJSON, err := encCfg.Amino.MarshalJSON(gogo) + require.NoError(t, err) + aminoJSON, err := aj.Marshal(msg) + require.NoError(t, err) + require.Equal(t, string(legacyAminoJSON), string(aminoJSON)) + + // test amino json signer handler equivalence + gogoMsg, ok := gogo.(types.Msg) + if !ok { + // not signable + return + } + + handlerOptions := signing_testutil.HandlerArgumentOptions{ + ChainID: "test-chain", + Memo: "sometestmemo", + Msg: tt.Pulsar, + AccNum: 1, + AccSeq: 2, + SignerAddress: "signerAddress", + Fee: &txv1beta1.Fee{ + Amount: []*v1beta1.Coin{{Denom: "uatom", Amount: "1000"}}, + }, + } + + signerData, txData, err := signing_testutil.MakeHandlerArguments(handlerOptions) + require.NoError(t, err) + + handler := aminojson.NewSignModeHandler(aminojson.SignModeHandlerOptions{}) + signBz, err := handler.GetSignBytes(context.Background(), signerData, txData) require.NoError(t, err) - aminoJson, err := aj.Marshal(msg) + + legacyHandler := tx.NewSignModeLegacyAminoJSONHandler() + txBuilder := encCfg.TxConfig.NewTxBuilder() + require.NoError(t, txBuilder.SetMsgs([]types.Msg{gogoMsg}...)) + txBuilder.SetMemo(handlerOptions.Memo) + txBuilder.SetFeeAmount(types.Coins{types.NewInt64Coin("uatom", 1000)}) + theTx := txBuilder.GetTx() + + legacySigningData := signing.SignerData{ + ChainID: handlerOptions.ChainID, + Address: handlerOptions.SignerAddress, + AccountNumber: handlerOptions.AccNum, + Sequence: handlerOptions.AccSeq, + } + legacySignBz, err := legacyHandler.GetSignBytes(signingtypes.SignMode_SIGN_MODE_LEGACY_AMINO_JSON, + legacySigningData, theTx) require.NoError(t, err) - require.Equal(t, string(legacyAminoJson), string(aminoJson)) + require.Equal(t, string(legacySignBz), string(signBz)) }) }) } @@ -408,7 +212,7 @@ func TestAminoJSON_LegacyParity(t *testing.T) { // represent the array as nil, and a subsequent marshal to JSON represent the array as null instead of empty. roundTripUnequal bool - // pulsar does not support marshalling a math.Dec as anything except a string. Therefore, we cannot unmarshal + // pulsar does not support marshaling a math.Dec as anything except a string. Therefore, we cannot unmarshal // a pulsar encoded Math.dec (the string representation of a Decimal) into a gogo Math.dec (expecting an int64). protoUnmarshalFails bool }{ @@ -618,11 +422,56 @@ func TestAminoJSON_LegacyParity(t *testing.T) { require.NoError(t, err) newGogoBytes, err := encCfg.Amino.MarshalJSON(newGogo) + require.NoError(t, err) if tc.roundTripUnequal { require.NotEqual(t, string(gogoBytes), string(newGogoBytes)) return } require.Equal(t, string(gogoBytes), string(newGogoBytes)) + + // test amino json signer handler equivalence + msg, ok := tc.gogo.(types.Msg) + if !ok { + // not signable + return + } + + handlerOptions := signing_testutil.HandlerArgumentOptions{ + ChainID: "test-chain", + Memo: "sometestmemo", + Msg: tc.pulsar, + AccNum: 1, + AccSeq: 2, + SignerAddress: "signerAddress", + Fee: &txv1beta1.Fee{ + Amount: []*v1beta1.Coin{{Denom: "uatom", Amount: "1000"}}, + }, + } + + signerData, txData, err := signing_testutil.MakeHandlerArguments(handlerOptions) + require.NoError(t, err) + + handler := aminojson.NewSignModeHandler(aminojson.SignModeHandlerOptions{}) + signBz, err := handler.GetSignBytes(context.Background(), signerData, txData) + require.NoError(t, err) + + legacyHandler := tx.NewSignModeLegacyAminoJSONHandler() + txBuilder := encCfg.TxConfig.NewTxBuilder() + require.NoError(t, txBuilder.SetMsgs([]types.Msg{msg}...)) + txBuilder.SetMemo(handlerOptions.Memo) + txBuilder.SetFeeAmount(types.Coins{types.NewInt64Coin("uatom", 1000)}) + theTx := txBuilder.GetTx() + + legacySigningData := signing.SignerData{ + ChainID: handlerOptions.ChainID, + Address: handlerOptions.SignerAddress, + AccountNumber: handlerOptions.AccNum, + Sequence: handlerOptions.AccSeq, + } + legacySignBz, err := legacyHandler.GetSignBytes(signingtypes.SignMode_SIGN_MODE_LEGACY_AMINO_JSON, + legacySigningData, theTx) + require.NoError(t, err) + require.Equal(t, string(legacySignBz), string(signBz)) }) } } @@ -650,6 +499,7 @@ func TestSendAuthorization(t *testing.T) { require.NoError(t, err) err = proto.Unmarshal(protoBz, sanityPulsar) + require.NoError(t, err) // !!! // empty []string is not the same as nil []string. this is a bug in gogo. @@ -661,17 +511,19 @@ func TestSendAuthorization(t *testing.T) { require.NotNil(t, pulsar.SpendLimit) require.Zero(t, len(pulsar.SpendLimit)) - legacyAminoJson, err := encCfg.Amino.MarshalJSON(gogo) - aminoJson, err := aj.Marshal(sanityPulsar) + legacyAminoJSON, err := encCfg.Amino.MarshalJSON(gogo) + require.NoError(t, err) + aminoJSON, err := aj.Marshal(sanityPulsar) + require.NoError(t, err) - require.Equal(t, string(legacyAminoJson), string(aminoJson)) + require.Equal(t, string(legacyAminoJSON), string(aminoJSON)) - aminoJson, err = aj.Marshal(pulsar) + aminoJSON, err = aj.Marshal(pulsar) require.NoError(t, err) // at this point, pulsar.SpendLimit = [], and gogo.SpendLimit = nil, but they will both marshal to `[]` // this is *only* possible because of Cosmos SDK's custom MarshalJSON method for Coins - require.Equal(t, string(legacyAminoJson), string(aminoJson)) + require.Equal(t, string(legacyAminoJSON), string(aminoJSON)) } func TestDecimalMutation(t *testing.T) { @@ -683,20 +535,19 @@ func TestDecimalMutation(t *testing.T) { require.NoError(t, err) rateBz, _ = encCfg.Amino.MarshalJSON(rates) - // these assertions show behavior prior to the merge of https://github.com/cosmos/cosmos-sdk/pull/15506 - // and should be updated to reflect the new behavior once a release of math is made and updated in ./tests/go.mod + // prior to the merge of https://github.com/cosmos/cosmos-sdk/pull/15506 + // gogoproto.Marshal would mutate Decimal fields changing JSON output as shown in the assertions below // require.NotEqual(t, `{"rate":"0","max_rate":"0","max_change_rate":"0"}`, string(rateBz)) // require.Equal(t, - // `{"rate":"0.000000000000000000","max_rate":"0.000000000000000000","max_change_rate":"0.000000000000000000"}`, - // string(rateBz)) + // `{"rate":"0.000000000000000000","max_rate":"0.000000000000000000","max_change_rate":"0.000000000000000000"}`, + // string(rateBz)) - // new behavior + // This is no longer the case, new behavior: require.Equal(t, `{"rate":"0","max_rate":"0","max_change_rate":"0"}`, string(rateBz)) } func postFixPulsarMessage(msg proto.Message) { - switch m := msg.(type) { - case *authapi.ModuleAccount: + if m, ok := msg.(*authapi.ModuleAccount); ok { if m.BaseAccount == nil { m.BaseAccount = &authapi.BaseAccount{} } diff --git a/tests/integration/bank/keeper/deterministic_test.go b/tests/integration/bank/keeper/deterministic_test.go index 394727f776d6..2acef84bad15 100644 --- a/tests/integration/bank/keeper/deterministic_test.go +++ b/tests/integration/bank/keeper/deterministic_test.go @@ -478,5 +478,5 @@ func TestGRPCDenomOwners(t *testing.T) { req := &banktypes.QueryDenomOwnersRequest{ Denom: coin1.GetDenom(), } - testdata.DeterministicIterations(f.ctx, t, req, f.queryClient.DenomOwners, 2525, false) + testdata.DeterministicIterations(f.ctx, t, req, f.queryClient.DenomOwners, 2516, false) } diff --git a/tests/integration/bank/keeper/keeper_test.go b/tests/integration/bank/keeper/keeper_test.go index cfbc59072959..c4edbf85a731 100644 --- a/tests/integration/bank/keeper/keeper_test.go +++ b/tests/integration/bank/keeper/keeper_test.go @@ -12,6 +12,7 @@ import ( abci "github.com/cometbft/cometbft/abci/types" cmtproto "github.com/cometbft/cometbft/proto/tendermint/types" cmttime "github.com/cometbft/cometbft/types/time" + "github.com/stretchr/testify/require" "gotest.tools/v3/assert" storetypes "cosmossdk.io/store/types" @@ -19,7 +20,7 @@ import ( "github.com/cosmos/cosmos-sdk/baseapp" "github.com/cosmos/cosmos-sdk/codec" codectypes "github.com/cosmos/cosmos-sdk/codec/types" - "github.com/cosmos/cosmos-sdk/testutil" + "github.com/cosmos/cosmos-sdk/runtime" "github.com/cosmos/cosmos-sdk/testutil/configurator" "github.com/cosmos/cosmos-sdk/testutil/sims" sdk "github.com/cosmos/cosmos-sdk/types" @@ -88,7 +89,6 @@ func newBarCoin(amt int64) sdk.Coin { return sdk.NewInt64Coin(barDenom, amt) } -// nolint: interfacer func getCoinsByName(ctx sdk.Context, bk keeper.Keeper, ak types.AccountKeeper, moduleName string) sdk.Coins { moduleAddress := ak.GetModuleAddress(moduleName) macc := ak.GetAccount(ctx, moduleAddress) @@ -158,8 +158,10 @@ func initKeepersWithmAccPerms(f *fixture, blockedAddrs map[string]bool) (authkee maccPerms[authtypes.Minter] = []string{authtypes.Minter} maccPerms[multiPerm] = []string{authtypes.Burner, authtypes.Minter, authtypes.Staking} maccPerms[randomPerm] = []string{"random"} + + storeService := runtime.NewKVStoreService(f.fetchStoreKey(authtypes.StoreKey).(*storetypes.KVStoreKey)) authKeeper := authkeeper.NewAccountKeeper( - appCodec, f.fetchStoreKey(types.StoreKey), authtypes.ProtoBaseAccount, + appCodec, storeService, authtypes.ProtoBaseAccount, maccPerms, sdk.Bech32MainPrefix, authtypes.NewModuleAddress(govtypes.ModuleName).String(), ) bankKeeper := keeper.NewBaseKeeper( @@ -240,16 +242,16 @@ func TestSupply_SendCoins(t *testing.T) { authKeeper.SetModuleAccount(ctx, burnerAcc) authKeeper.SetAccount(ctx, baseAcc) - testutil.AssertPanics(t, func() { - _ = keeper.SendCoinsFromModuleToModule(ctx, "", holderAcc.GetName(), initCoins) // nolint:errcheck + require.Panics(t, func() { + _ = keeper.SendCoinsFromModuleToModule(ctx, "", holderAcc.GetName(), initCoins) //nolint:errcheck // no error check is needed because we are testing for a panic }) - testutil.AssertPanics(t, func() { - _ = keeper.SendCoinsFromModuleToModule(ctx, authtypes.Burner, "", initCoins) // nolint:errcheck + require.Panics(t, func() { + _ = keeper.SendCoinsFromModuleToModule(ctx, authtypes.Burner, "", initCoins) //nolint:errcheck // no error check is needed because we are testing for a panic }) - testutil.AssertPanics(t, func() { - _ = keeper.SendCoinsFromModuleToAccount(ctx, "", baseAcc.GetAddress(), initCoins) // nolint:errcheck + require.Panics(t, func() { + _ = keeper.SendCoinsFromModuleToAccount(ctx, "", baseAcc.GetAddress(), initCoins) //nolint:errcheck // no error check is needed because we are testing for a panic }) assert.Error(t, @@ -292,14 +294,14 @@ func TestSupply_MintCoins(t *testing.T) { assert.NilError(t, err) // no module account - testutil.AssertPanics(t, func() { keeper.MintCoins(ctx, "", initCoins) }) // nolint:errcheck + require.Panics(t, func() { keeper.MintCoins(ctx, "", initCoins) }) //nolint:errcheck // we're testing for a panic // invalid permission - testutil.AssertPanics(t, func() { keeper.MintCoins(ctx, authtypes.Burner, initCoins) }) // nolint:errcheck + require.Panics(t, func() { keeper.MintCoins(ctx, authtypes.Burner, initCoins) }) //nolint:errcheck // we're testing for a panic err = keeper.MintCoins(ctx, authtypes.Minter, sdk.Coins{sdk.Coin{Denom: "denom", Amount: sdk.NewInt(-10)}}) assert.Error(t, err, fmt.Sprintf("%sdenom: invalid coins", sdk.NewInt(-10))) - testutil.AssertPanics(t, func() { keeper.MintCoins(ctx, randomPerm, initCoins) }) // nolint:errcheck + require.Panics(t, func() { keeper.MintCoins(ctx, randomPerm, initCoins) }) //nolint:errcheck // we're testing for a panic err = keeper.MintCoins(ctx, authtypes.Minter, initCoins) assert.NilError(t, err) @@ -321,7 +323,7 @@ func TestSupply_MintCoins(t *testing.T) { assert.NilError(t, err) assert.DeepEqual(t, initCoins, getCoinsByName(ctx, keeper, authKeeper, multiPermAcc.GetName())) assert.DeepEqual(t, initialSupply.Add(initCoins...), totalSupply) - testutil.AssertPanics(t, func() { keeper.MintCoins(ctx, authtypes.Burner, initCoins) }) // nolint:errcheck + require.Panics(t, func() { keeper.MintCoins(ctx, authtypes.Burner, initCoins) }) //nolint:errcheck // we're testing for a panic } func TestSupply_BurnCoins(t *testing.T) { @@ -342,11 +344,11 @@ func TestSupply_BurnCoins(t *testing.T) { supplyAfterInflation, _, err := keeper.GetPaginatedTotalSupply(ctx, &query.PageRequest{}) assert.NilError(t, err) // no module account - testutil.AssertPanics(t, func() { keeper.BurnCoins(ctx, "", initCoins) }) // nolint:errcheck + require.Panics(t, func() { keeper.BurnCoins(ctx, "", initCoins) }) //nolint:errcheck // we're testing for a panic // invalid permission - testutil.AssertPanics(t, func() { keeper.BurnCoins(ctx, authtypes.Minter, initCoins) }) // nolint:errcheck + require.Panics(t, func() { keeper.BurnCoins(ctx, authtypes.Minter, initCoins) }) //nolint:errcheck // we're testing for a panic // random permission - testutil.AssertPanics(t, func() { keeper.BurnCoins(ctx, randomPerm, supplyAfterInflation) }) // nolint:errcheck + require.Panics(t, func() { keeper.BurnCoins(ctx, randomPerm, supplyAfterInflation) }) //nolint:errcheck // we're testing for a panic err = keeper.BurnCoins(ctx, authtypes.Burner, supplyAfterInflation) assert.Error(t, err, fmt.Sprintf("spendable balance %s is smaller than %s: insufficient funds", initCoins, supplyAfterInflation)) @@ -1194,8 +1196,9 @@ func TestBalanceTrackingEvents(t *testing.T) { maccPerms[multiPerm] = []string{authtypes.Burner, authtypes.Minter, authtypes.Staking} + storeService := runtime.NewKVStoreService(f.fetchStoreKey(authtypes.StoreKey).(*storetypes.KVStoreKey)) f.accountKeeper = authkeeper.NewAccountKeeper( - f.appCodec, f.fetchStoreKey(authtypes.StoreKey), + f.appCodec, storeService, authtypes.ProtoBaseAccount, maccPerms, sdk.Bech32MainPrefix, authtypes.NewModuleAddress(govtypes.ModuleName).String(), ) @@ -1241,26 +1244,26 @@ func TestBalanceTrackingEvents(t *testing.T) { for _, e := range f.ctx.EventManager().ABCIEvents() { switch e.Type { case types.EventTypeCoinBurn: - burnedCoins, err := sdk.ParseCoinsNormalized((string)(e.Attributes[1].Value)) + burnedCoins, err := sdk.ParseCoinsNormalized(e.Attributes[1].Value) assert.NilError(t, err) supply = supply.Sub(burnedCoins...) case types.EventTypeCoinMint: - mintedCoins, err := sdk.ParseCoinsNormalized((string)(e.Attributes[1].Value)) + mintedCoins, err := sdk.ParseCoinsNormalized(e.Attributes[1].Value) assert.NilError(t, err) supply = supply.Add(mintedCoins...) case types.EventTypeCoinSpent: - coinsSpent, err := sdk.ParseCoinsNormalized((string)(e.Attributes[1].Value)) + coinsSpent, err := sdk.ParseCoinsNormalized(e.Attributes[1].Value) assert.NilError(t, err) - spender, err := sdk.AccAddressFromBech32((string)(e.Attributes[0].Value)) + spender, err := sdk.AccAddressFromBech32(e.Attributes[0].Value) assert.NilError(t, err) balances[spender.String()] = balances[spender.String()].Sub(coinsSpent...) case types.EventTypeCoinReceived: - coinsRecv, err := sdk.ParseCoinsNormalized((string)(e.Attributes[1].Value)) + coinsRecv, err := sdk.ParseCoinsNormalized(e.Attributes[1].Value) assert.NilError(t, err) - receiver, err := sdk.AccAddressFromBech32((string)(e.Attributes[0].Value)) + receiver, err := sdk.AccAddressFromBech32(e.Attributes[0].Value) assert.NilError(t, err) balances[receiver.String()] = balances[receiver.String()].Add(coinsRecv...) } @@ -1324,9 +1327,10 @@ func TestMintCoinRestrictions(t *testing.T) { maccPerms := make(map[string][]string) maccPerms[multiPerm] = []string{authtypes.Burner, authtypes.Minter, authtypes.Staking} + storeService := runtime.NewKVStoreService(f.fetchStoreKey(authtypes.StoreKey).(*storetypes.KVStoreKey)) f.accountKeeper = authkeeper.NewAccountKeeper( - f.appCodec, f.fetchStoreKey(authtypes.StoreKey), + f.appCodec, storeService, authtypes.ProtoBaseAccount, maccPerms, sdk.Bech32MainPrefix, authtypes.NewModuleAddress(govtypes.ModuleName).String(), ) @@ -1794,8 +1798,8 @@ func TestMigrator_Migrate3to4(t *testing.T) { migrator := keeper.NewMigrator(bankKeeper, legacySubspace) assert.NilError(t, migrator.Migrate3to4(ctx)) newParams := bankKeeper.GetParams(ctx) - assert.Assert(t, len(newParams.SendEnabled) == 0) - for _, se := range params.SendEnabled { + assert.Assert(t, len(newParams.SendEnabled) == 0) //nolint:staticcheck // We need to test the deprecated send enabled approach + for _, se := range params.SendEnabled { //nolint:staticcheck // We need to test the deprecated send enabled approach actual := bankKeeper.IsSendEnabledDenom(ctx, se.Denom) assert.Equal(t, se.Enabled, actual, se.Denom) } @@ -1809,7 +1813,7 @@ func TestSetParams(t *testing.T) { ctx, bankKeeper := f.ctx, f.bankKeeper params := types.NewParams(true) - params.SendEnabled = []*types.SendEnabled{ + params.SendEnabled = []*types.SendEnabled{ //nolint:staticcheck // We need to test the deprecated send enabled approach {Denom: "paramscointrue", Enabled: true}, {Denom: "paramscoinfalse", Enabled: false}, } @@ -1818,7 +1822,7 @@ func TestSetParams(t *testing.T) { t.Run("stored params are as expected", func(t *testing.T) { actual := bankKeeper.GetParams(ctx) assert.Assert(t, actual.DefaultSendEnabled, "DefaultSendEnabled") - assert.Assert(t, len(actual.SendEnabled) == 0, "SendEnabled") + assert.Assert(t, len(actual.SendEnabled) == 0, "SendEnabled") //nolint:staticcheck // We need to test the deprecated send enabled approach }) t.Run("send enabled params converted to store", func(t *testing.T) { diff --git a/tests/integration/distribution/keeper/allocation_test.go b/tests/integration/distribution/keeper/allocation_test.go deleted file mode 100644 index 7ad05a0ffd6e..000000000000 --- a/tests/integration/distribution/keeper/allocation_test.go +++ /dev/null @@ -1,248 +0,0 @@ -package keeper_test - -import ( - "testing" - - "cosmossdk.io/math" - abci "github.com/cometbft/cometbft/abci/types" - cmtproto "github.com/cometbft/cometbft/proto/tendermint/types" - "gotest.tools/v3/assert" - - simtestutil "github.com/cosmos/cosmos-sdk/testutil/sims" - sdk "github.com/cosmos/cosmos-sdk/types" - authkeeper "github.com/cosmos/cosmos-sdk/x/auth/keeper" - "github.com/cosmos/cosmos-sdk/x/auth/types" - bankkeeper "github.com/cosmos/cosmos-sdk/x/bank/keeper" - banktestutil "github.com/cosmos/cosmos-sdk/x/bank/testutil" - "github.com/cosmos/cosmos-sdk/x/distribution/keeper" - "github.com/cosmos/cosmos-sdk/x/distribution/testutil" - disttypes "github.com/cosmos/cosmos-sdk/x/distribution/types" - stakingkeeper "github.com/cosmos/cosmos-sdk/x/staking/keeper" - stakingtestutil "github.com/cosmos/cosmos-sdk/x/staking/testutil" - stakingtypes "github.com/cosmos/cosmos-sdk/x/staking/types" -) - -func TestAllocateTokensToValidatorWithCommission(t *testing.T) { - var ( - bankKeeper bankkeeper.Keeper - distrKeeper keeper.Keeper - stakingKeeper *stakingkeeper.Keeper - ) - - app, err := simtestutil.Setup(testutil.AppConfig, - &bankKeeper, - &distrKeeper, - &stakingKeeper, - ) - assert.NilError(t, err) - - ctx := app.BaseApp.NewContext(false, cmtproto.Header{}) - - addrs := simtestutil.AddTestAddrs(bankKeeper, stakingKeeper, ctx, 3, sdk.NewInt(1234)) - valAddrs := simtestutil.ConvertAddrsToValAddrs(addrs) - tstaking := stakingtestutil.NewHelper(t, ctx, stakingKeeper) - - // create validator with 50% commission - tstaking.Commission = stakingtypes.NewCommissionRates(sdk.NewDecWithPrec(5, 1), sdk.NewDecWithPrec(5, 1), math.LegacyNewDec(0)) - tstaking.CreateValidator(sdk.ValAddress(addrs[0]), valConsPk0, sdk.NewInt(100), true) - val := stakingKeeper.Validator(ctx, valAddrs[0]) - - // allocate tokens - tokens := sdk.DecCoins{ - {Denom: sdk.DefaultBondDenom, Amount: math.LegacyNewDec(10)}, - } - distrKeeper.AllocateTokensToValidator(ctx, val, tokens) - - // check commission - expected := sdk.DecCoins{ - {Denom: sdk.DefaultBondDenom, Amount: math.LegacyNewDec(5)}, - } - assert.DeepEqual(t, expected, distrKeeper.GetValidatorAccumulatedCommission(ctx, val.GetOperator()).Commission) - - // check current rewards - assert.DeepEqual(t, expected, distrKeeper.GetValidatorCurrentRewards(ctx, val.GetOperator()).Rewards) -} - -func TestAllocateTokensToManyValidators(t *testing.T) { - var ( - accountKeeper authkeeper.AccountKeeper - bankKeeper bankkeeper.Keeper - distrKeeper keeper.Keeper - stakingKeeper *stakingkeeper.Keeper - ) - - app, err := simtestutil.Setup(testutil.AppConfig, - &accountKeeper, - &bankKeeper, - &distrKeeper, - &stakingKeeper, - ) - assert.NilError(t, err) - - ctx := app.BaseApp.NewContext(false, cmtproto.Header{}) - - // reset fee pool - distrKeeper.SetFeePool(ctx, disttypes.InitialFeePool()) - - addrs := simtestutil.AddTestAddrs(bankKeeper, stakingKeeper, ctx, 2, sdk.NewInt(1234)) - valAddrs := simtestutil.ConvertAddrsToValAddrs(addrs) - tstaking := stakingtestutil.NewHelper(t, ctx, stakingKeeper) - - // create validator with 50% commission - tstaking.Commission = stakingtypes.NewCommissionRates(sdk.NewDecWithPrec(5, 1), sdk.NewDecWithPrec(5, 1), math.LegacyNewDec(0)) - tstaking.CreateValidator(valAddrs[0], valConsPk0, sdk.NewInt(100), true) - - // create second validator with 0% commission - tstaking.Commission = stakingtypes.NewCommissionRates(math.LegacyNewDec(0), math.LegacyNewDec(0), math.LegacyNewDec(0)) - tstaking.CreateValidator(valAddrs[1], valConsPk1, sdk.NewInt(100), true) - - abciValA := abci.Validator{ - Address: valConsPk0.Address(), - Power: 100, - } - abciValB := abci.Validator{ - Address: valConsPk1.Address(), - Power: 100, - } - - // assert initial state: zero outstanding rewards, zero community pool, zero commission, zero current rewards - assert.Assert(t, distrKeeper.GetValidatorOutstandingRewards(ctx, valAddrs[0]).Rewards.IsZero()) - assert.Assert(t, distrKeeper.GetValidatorOutstandingRewards(ctx, valAddrs[1]).Rewards.IsZero()) - assert.Assert(t, distrKeeper.GetFeePool(ctx).CommunityPool.IsZero()) - assert.Assert(t, distrKeeper.GetValidatorAccumulatedCommission(ctx, valAddrs[0]).Commission.IsZero()) - assert.Assert(t, distrKeeper.GetValidatorAccumulatedCommission(ctx, valAddrs[1]).Commission.IsZero()) - assert.Assert(t, distrKeeper.GetValidatorCurrentRewards(ctx, valAddrs[0]).Rewards.IsZero()) - assert.Assert(t, distrKeeper.GetValidatorCurrentRewards(ctx, valAddrs[1]).Rewards.IsZero()) - - // allocate tokens as if both had voted and second was proposer - fees := sdk.NewCoins(sdk.NewCoin(sdk.DefaultBondDenom, sdk.NewInt(100))) - feeCollector := accountKeeper.GetModuleAccount(ctx, types.FeeCollectorName) - assert.Assert(t, feeCollector != nil) - - // fund fee collector - assert.NilError(t, banktestutil.FundModuleAccount(bankKeeper, ctx, feeCollector.GetName(), fees)) - - accountKeeper.SetAccount(ctx, feeCollector) - - votes := []abci.VoteInfo{ - { - Validator: abciValA, - SignedLastBlock: true, - }, - { - Validator: abciValB, - SignedLastBlock: true, - }, - } - distrKeeper.AllocateTokens(ctx, 200, votes) - - // 98 outstanding rewards (100 less 2 to community pool) - assert.DeepEqual(t, sdk.DecCoins{{Denom: sdk.DefaultBondDenom, Amount: sdk.NewDecWithPrec(490, 1)}}, distrKeeper.GetValidatorOutstandingRewards(ctx, valAddrs[0]).Rewards) - assert.DeepEqual(t, sdk.DecCoins{{Denom: sdk.DefaultBondDenom, Amount: sdk.NewDecWithPrec(490, 1)}}, distrKeeper.GetValidatorOutstandingRewards(ctx, valAddrs[1]).Rewards) - - // 2 community pool coins - assert.DeepEqual(t, sdk.DecCoins{{Denom: sdk.DefaultBondDenom, Amount: math.LegacyNewDec(2)}}, distrKeeper.GetFeePool(ctx).CommunityPool) - - // 50% commission for first proposer, (0.5 * 98%) * 100 / 2 = 23.25 - assert.DeepEqual(t, sdk.DecCoins{{Denom: sdk.DefaultBondDenom, Amount: sdk.NewDecWithPrec(2450, 2)}}, distrKeeper.GetValidatorAccumulatedCommission(ctx, valAddrs[0]).Commission) - - // zero commission for second proposer - assert.Assert(t, distrKeeper.GetValidatorAccumulatedCommission(ctx, valAddrs[1]).Commission.IsZero()) - - // just staking.proportional for first proposer less commission = (0.5 * 98%) * 100 / 2 = 24.50 - assert.DeepEqual(t, sdk.DecCoins{{Denom: sdk.DefaultBondDenom, Amount: sdk.NewDecWithPrec(2450, 2)}}, distrKeeper.GetValidatorCurrentRewards(ctx, valAddrs[0]).Rewards) - - // proposer reward + staking.proportional for second proposer = (0.5 * (98%)) * 100 = 49 - assert.DeepEqual(t, sdk.DecCoins{{Denom: sdk.DefaultBondDenom, Amount: sdk.NewDecWithPrec(490, 1)}}, distrKeeper.GetValidatorCurrentRewards(ctx, valAddrs[1]).Rewards) -} - -func TestAllocateTokensTruncation(t *testing.T) { - var ( - accountKeeper authkeeper.AccountKeeper - bankKeeper bankkeeper.Keeper - distrKeeper keeper.Keeper - stakingKeeper *stakingkeeper.Keeper - ) - - app, err := simtestutil.Setup(testutil.AppConfig, - &accountKeeper, - &bankKeeper, - &distrKeeper, - &stakingKeeper, - ) - assert.NilError(t, err) - - ctx := app.BaseApp.NewContext(false, cmtproto.Header{}) - - // reset fee pool - distrKeeper.SetFeePool(ctx, disttypes.InitialFeePool()) - - addrs := simtestutil.AddTestAddrs(bankKeeper, stakingKeeper, ctx, 3, sdk.NewInt(1234)) - valAddrs := simtestutil.ConvertAddrsToValAddrs(addrs) - tstaking := stakingtestutil.NewHelper(t, ctx, stakingKeeper) - - // create validator with 10% commission - tstaking.Commission = stakingtypes.NewCommissionRates(sdk.NewDecWithPrec(1, 1), sdk.NewDecWithPrec(1, 1), math.LegacyNewDec(0)) - tstaking.CreateValidator(valAddrs[0], valConsPk0, sdk.NewInt(110), true) - - // create second validator with 10% commission - tstaking.Commission = stakingtypes.NewCommissionRates(sdk.NewDecWithPrec(1, 1), sdk.NewDecWithPrec(1, 1), math.LegacyNewDec(0)) - tstaking.CreateValidator(valAddrs[1], valConsPk1, sdk.NewInt(100), true) - - // create third validator with 10% commission - tstaking.Commission = stakingtypes.NewCommissionRates(sdk.NewDecWithPrec(1, 1), sdk.NewDecWithPrec(1, 1), math.LegacyNewDec(0)) - tstaking.CreateValidator(valAddrs[2], valConsPk2, sdk.NewInt(100), true) - - abciValA := abci.Validator{ - Address: valConsPk0.Address(), - Power: 11, - } - abciValB := abci.Validator{ - Address: valConsPk1.Address(), - Power: 10, - } - abciValC := abci.Validator{ - Address: valConsPk2.Address(), - Power: 10, - } - - // assert initial state: zero outstanding rewards, zero community pool, zero commission, zero current rewards - assert.Assert(t, distrKeeper.GetValidatorOutstandingRewards(ctx, valAddrs[0]).Rewards.IsZero()) - assert.Assert(t, distrKeeper.GetValidatorOutstandingRewards(ctx, valAddrs[1]).Rewards.IsZero()) - assert.Assert(t, distrKeeper.GetValidatorOutstandingRewards(ctx, valAddrs[1]).Rewards.IsZero()) - assert.Assert(t, distrKeeper.GetFeePool(ctx).CommunityPool.IsZero()) - assert.Assert(t, distrKeeper.GetValidatorAccumulatedCommission(ctx, valAddrs[0]).Commission.IsZero()) - assert.Assert(t, distrKeeper.GetValidatorAccumulatedCommission(ctx, valAddrs[1]).Commission.IsZero()) - assert.Assert(t, distrKeeper.GetValidatorCurrentRewards(ctx, valAddrs[0]).Rewards.IsZero()) - assert.Assert(t, distrKeeper.GetValidatorCurrentRewards(ctx, valAddrs[1]).Rewards.IsZero()) - - // allocate tokens as if both had voted and second was proposer - fees := sdk.NewCoins(sdk.NewCoin(sdk.DefaultBondDenom, sdk.NewInt(634195840))) - - feeCollector := accountKeeper.GetModuleAccount(ctx, types.FeeCollectorName) - assert.Assert(t, feeCollector != nil) - - assert.NilError(t, banktestutil.FundModuleAccount(bankKeeper, ctx, feeCollector.GetName(), fees)) - - accountKeeper.SetAccount(ctx, feeCollector) - - votes := []abci.VoteInfo{ - { - Validator: abciValA, - SignedLastBlock: true, - }, - { - Validator: abciValB, - SignedLastBlock: true, - }, - { - Validator: abciValC, - SignedLastBlock: true, - }, - } - distrKeeper.AllocateTokens(ctx, 31, votes) - - assert.Assert(t, distrKeeper.GetValidatorOutstandingRewards(ctx, valAddrs[0]).Rewards.IsValid()) - assert.Assert(t, distrKeeper.GetValidatorOutstandingRewards(ctx, valAddrs[1]).Rewards.IsValid()) - assert.Assert(t, distrKeeper.GetValidatorOutstandingRewards(ctx, valAddrs[2]).Rewards.IsValid()) -} diff --git a/tests/integration/distribution/keeper/common_test.go b/tests/integration/distribution/keeper/common_test.go index 4ab7cead571a..783d44e2dafc 100644 --- a/tests/integration/distribution/keeper/common_test.go +++ b/tests/integration/distribution/keeper/common_test.go @@ -2,19 +2,10 @@ package keeper_test import ( simtestutil "github.com/cosmos/cosmos-sdk/testutil/sims" - sdk "github.com/cosmos/cosmos-sdk/types" - authtypes "github.com/cosmos/cosmos-sdk/x/auth/types" - "github.com/cosmos/cosmos-sdk/x/distribution/types" ) var ( - PKS = simtestutil.CreateTestPubKeys(5) + PKS = simtestutil.CreateTestPubKeys(3) valConsPk0 = PKS[0] - valConsPk1 = PKS[1] - valConsPk2 = PKS[2] - - valConsAddr0 = sdk.ConsAddress(valConsPk0.Address()) - - distrAcc = authtypes.NewEmptyModuleAccount(types.ModuleName) ) diff --git a/tests/integration/distribution/keeper/delegation_test.go b/tests/integration/distribution/keeper/delegation_test.go deleted file mode 100644 index dcb25cbf3fd8..000000000000 --- a/tests/integration/distribution/keeper/delegation_test.go +++ /dev/null @@ -1,820 +0,0 @@ -package keeper_test - -import ( - "testing" - - "cosmossdk.io/math" - cmtproto "github.com/cometbft/cometbft/proto/tendermint/types" - "gotest.tools/v3/assert" - - simtestutil "github.com/cosmos/cosmos-sdk/testutil/sims" - sdk "github.com/cosmos/cosmos-sdk/types" - authkeeper "github.com/cosmos/cosmos-sdk/x/auth/keeper" - bankkeeper "github.com/cosmos/cosmos-sdk/x/bank/keeper" - banktestutil "github.com/cosmos/cosmos-sdk/x/bank/testutil" - "github.com/cosmos/cosmos-sdk/x/distribution/keeper" - "github.com/cosmos/cosmos-sdk/x/distribution/testutil" - "github.com/cosmos/cosmos-sdk/x/staking" - stakingkeeper "github.com/cosmos/cosmos-sdk/x/staking/keeper" - stakingtestutil "github.com/cosmos/cosmos-sdk/x/staking/testutil" - stakingtypes "github.com/cosmos/cosmos-sdk/x/staking/types" -) - -func TestCalculateRewardsBasic(t *testing.T) { - var ( - bankKeeper bankkeeper.Keeper - distrKeeper keeper.Keeper - stakingKeeper *stakingkeeper.Keeper - ) - - app, err := simtestutil.Setup(testutil.AppConfig, - &bankKeeper, - &distrKeeper, - &stakingKeeper, - ) - assert.NilError(t, err) - - ctx := app.BaseApp.NewContext(false, cmtproto.Header{}) - - distrKeeper.DeleteAllValidatorHistoricalRewards(ctx) - - tstaking := stakingtestutil.NewHelper(t, ctx, stakingKeeper) - - addr := simtestutil.AddTestAddrs(bankKeeper, stakingKeeper, ctx, 2, sdk.NewInt(1000)) - valAddrs := simtestutil.ConvertAddrsToValAddrs(addr) - - // create validator with 50% commission - tstaking.Commission = stakingtypes.NewCommissionRates(sdk.NewDecWithPrec(5, 1), sdk.NewDecWithPrec(5, 1), math.LegacyNewDec(0)) - tstaking.CreateValidator(valAddrs[0], valConsPk0, sdk.NewInt(100), true) - - // end block to bond validator and start new block - staking.EndBlocker(ctx, stakingKeeper) - ctx = ctx.WithBlockHeight(ctx.BlockHeight() + 1) - tstaking.Ctx = ctx - - // fetch validator and delegation - val := stakingKeeper.Validator(ctx, valAddrs[0]) - del := stakingKeeper.Delegation(ctx, sdk.AccAddress(valAddrs[0]), valAddrs[0]) - - // historical count should be 2 (once for validator init, once for delegation init) - assert.Equal(t, uint64(2), distrKeeper.GetValidatorHistoricalReferenceCount(ctx)) - - // end period - endingPeriod := distrKeeper.IncrementValidatorPeriod(ctx, val) - - // historical count should be 2 still - assert.Equal(t, uint64(2), distrKeeper.GetValidatorHistoricalReferenceCount(ctx)) - - // calculate delegation rewards - rewards := distrKeeper.CalculateDelegationRewards(ctx, val, del, endingPeriod) - - // rewards should be zero - assert.Assert(t, rewards.IsZero()) - - // allocate some rewards - initial := int64(10) - tokens := sdk.DecCoins{{Denom: sdk.DefaultBondDenom, Amount: math.LegacyNewDec(initial)}} - distrKeeper.AllocateTokensToValidator(ctx, val, tokens) - - // end period - endingPeriod = distrKeeper.IncrementValidatorPeriod(ctx, val) - - // calculate delegation rewards - rewards = distrKeeper.CalculateDelegationRewards(ctx, val, del, endingPeriod) - - // rewards should be half the tokens - assert.DeepEqual(t, sdk.DecCoins{{Denom: sdk.DefaultBondDenom, Amount: math.LegacyNewDec(initial / 2)}}, rewards) - - // commission should be the other half - assert.DeepEqual(t, sdk.DecCoins{{Denom: sdk.DefaultBondDenom, Amount: math.LegacyNewDec(initial / 2)}}, distrKeeper.GetValidatorAccumulatedCommission(ctx, valAddrs[0]).Commission) -} - -func TestCalculateRewardsAfterSlash(t *testing.T) { - var ( - bankKeeper bankkeeper.Keeper - distrKeeper keeper.Keeper - stakingKeeper *stakingkeeper.Keeper - ) - - app, err := simtestutil.Setup(testutil.AppConfig, - &bankKeeper, - &distrKeeper, - &stakingKeeper, - ) - assert.NilError(t, err) - - ctx := app.BaseApp.NewContext(false, cmtproto.Header{}) - - addr := simtestutil.AddTestAddrs(bankKeeper, stakingKeeper, ctx, 2, sdk.NewInt(100000000)) - valAddrs := simtestutil.ConvertAddrsToValAddrs(addr) - tstaking := stakingtestutil.NewHelper(t, ctx, stakingKeeper) - - // create validator with 50% commission - tstaking.Commission = stakingtypes.NewCommissionRates(sdk.NewDecWithPrec(5, 1), sdk.NewDecWithPrec(5, 1), math.LegacyNewDec(0)) - valPower := int64(100) - tstaking.CreateValidatorWithValPower(valAddrs[0], valConsPk0, valPower, true) - - // end block to bond validator - staking.EndBlocker(ctx, stakingKeeper) - - // next block - ctx = ctx.WithBlockHeight(ctx.BlockHeight() + 1) - - // fetch validator and delegation - val := stakingKeeper.Validator(ctx, valAddrs[0]) - del := stakingKeeper.Delegation(ctx, sdk.AccAddress(valAddrs[0]), valAddrs[0]) - - // end period - endingPeriod := distrKeeper.IncrementValidatorPeriod(ctx, val) - - // calculate delegation rewards - rewards := distrKeeper.CalculateDelegationRewards(ctx, val, del, endingPeriod) - - // rewards should be zero - assert.Assert(t, rewards.IsZero()) - - // start out block height - ctx = ctx.WithBlockHeight(ctx.BlockHeight() + 3) - - // slash the validator by 50% - stakingKeeper.Slash(ctx, valConsAddr0, ctx.BlockHeight(), valPower, sdk.NewDecWithPrec(5, 1)) - - // retrieve validator - val = stakingKeeper.Validator(ctx, valAddrs[0]) - - // increase block height - ctx = ctx.WithBlockHeight(ctx.BlockHeight() + 3) - - // allocate some rewards - initial := stakingKeeper.TokensFromConsensusPower(ctx, 10) - tokens := sdk.DecCoins{{Denom: sdk.DefaultBondDenom, Amount: sdk.NewDecFromInt(initial)}} - distrKeeper.AllocateTokensToValidator(ctx, val, tokens) - - // end period - endingPeriod = distrKeeper.IncrementValidatorPeriod(ctx, val) - - // calculate delegation rewards - rewards = distrKeeper.CalculateDelegationRewards(ctx, val, del, endingPeriod) - - // rewards should be half the tokens - assert.DeepEqual(t, sdk.DecCoins{{Denom: sdk.DefaultBondDenom, Amount: sdk.NewDecFromInt(initial.QuoRaw(2))}}, rewards) - - // commission should be the other half - assert.DeepEqual(t, sdk.DecCoins{{Denom: sdk.DefaultBondDenom, Amount: sdk.NewDecFromInt(initial.QuoRaw(2))}}, - distrKeeper.GetValidatorAccumulatedCommission(ctx, valAddrs[0]).Commission) -} - -func TestCalculateRewardsAfterManySlashes(t *testing.T) { - var ( - bankKeeper bankkeeper.Keeper - distrKeeper keeper.Keeper - stakingKeeper *stakingkeeper.Keeper - ) - - app, err := simtestutil.Setup(testutil.AppConfig, - &bankKeeper, - &distrKeeper, - &stakingKeeper, - ) - assert.NilError(t, err) - - ctx := app.BaseApp.NewContext(false, cmtproto.Header{}) - - tstaking := stakingtestutil.NewHelper(t, ctx, stakingKeeper) - addr := simtestutil.AddTestAddrs(bankKeeper, stakingKeeper, ctx, 2, sdk.NewInt(100000000)) - valAddrs := simtestutil.ConvertAddrsToValAddrs(addr) - - // create validator with 50% commission - valPower := int64(100) - tstaking.Commission = stakingtypes.NewCommissionRates(sdk.NewDecWithPrec(5, 1), sdk.NewDecWithPrec(5, 1), math.LegacyNewDec(0)) - tstaking.CreateValidatorWithValPower(valAddrs[0], valConsPk0, valPower, true) - - // end block to bond validator - staking.EndBlocker(ctx, stakingKeeper) - - // next block - ctx = ctx.WithBlockHeight(ctx.BlockHeight() + 1) - - // fetch validator and delegation - val := stakingKeeper.Validator(ctx, valAddrs[0]) - del := stakingKeeper.Delegation(ctx, sdk.AccAddress(valAddrs[0]), valAddrs[0]) - - // end period - endingPeriod := distrKeeper.IncrementValidatorPeriod(ctx, val) - - // calculate delegation rewards - rewards := distrKeeper.CalculateDelegationRewards(ctx, val, del, endingPeriod) - - // rewards should be zero - assert.Assert(t, rewards.IsZero()) - - // start out block height - ctx = ctx.WithBlockHeight(ctx.BlockHeight() + 3) - - // slash the validator by 50% - stakingKeeper.Slash(ctx, valConsAddr0, ctx.BlockHeight(), valPower, sdk.NewDecWithPrec(5, 1)) - - // fetch the validator again - val = stakingKeeper.Validator(ctx, valAddrs[0]) - - // increase block height - ctx = ctx.WithBlockHeight(ctx.BlockHeight() + 3) - - // allocate some rewards - initial := stakingKeeper.TokensFromConsensusPower(ctx, 10) - tokens := sdk.DecCoins{{Denom: sdk.DefaultBondDenom, Amount: sdk.NewDecFromInt(initial)}} - distrKeeper.AllocateTokensToValidator(ctx, val, tokens) - - // slash the validator by 50% again - stakingKeeper.Slash(ctx, valConsAddr0, ctx.BlockHeight(), valPower/2, sdk.NewDecWithPrec(5, 1)) - - // fetch the validator again - val = stakingKeeper.Validator(ctx, valAddrs[0]) - - // increase block height - ctx = ctx.WithBlockHeight(ctx.BlockHeight() + 3) - - // allocate some more rewards - distrKeeper.AllocateTokensToValidator(ctx, val, tokens) - - // end period - endingPeriod = distrKeeper.IncrementValidatorPeriod(ctx, val) - - // calculate delegation rewards - rewards = distrKeeper.CalculateDelegationRewards(ctx, val, del, endingPeriod) - - // rewards should be half the tokens - assert.DeepEqual(t, sdk.DecCoins{{Denom: sdk.DefaultBondDenom, Amount: sdk.NewDecFromInt(initial)}}, rewards) - - // commission should be the other half - assert.DeepEqual(t, sdk.DecCoins{{Denom: sdk.DefaultBondDenom, Amount: sdk.NewDecFromInt(initial)}}, - distrKeeper.GetValidatorAccumulatedCommission(ctx, valAddrs[0]).Commission) -} - -func TestCalculateRewardsMultiDelegator(t *testing.T) { - var ( - bankKeeper bankkeeper.Keeper - distrKeeper keeper.Keeper - stakingKeeper *stakingkeeper.Keeper - ) - - app, err := simtestutil.Setup(testutil.AppConfig, - &bankKeeper, - &distrKeeper, - &stakingKeeper, - ) - assert.NilError(t, err) - - ctx := app.BaseApp.NewContext(false, cmtproto.Header{}) - - tstaking := stakingtestutil.NewHelper(t, ctx, stakingKeeper) - addr := simtestutil.AddTestAddrs(bankKeeper, stakingKeeper, ctx, 2, sdk.NewInt(100000000)) - valAddrs := simtestutil.ConvertAddrsToValAddrs(addr) - - // create validator with 50% commission - tstaking.Commission = stakingtypes.NewCommissionRates(sdk.NewDecWithPrec(5, 1), sdk.NewDecWithPrec(5, 1), math.LegacyNewDec(0)) - tstaking.CreateValidator(valAddrs[0], valConsPk0, sdk.NewInt(100), true) - - // end block to bond validator - staking.EndBlocker(ctx, stakingKeeper) - - // next block - ctx = ctx.WithBlockHeight(ctx.BlockHeight() + 1) - - // fetch validator and delegation - val := stakingKeeper.Validator(ctx, valAddrs[0]) - del1 := stakingKeeper.Delegation(ctx, sdk.AccAddress(valAddrs[0]), valAddrs[0]) - - // allocate some rewards - initial := int64(20) - tokens := sdk.DecCoins{{Denom: sdk.DefaultBondDenom, Amount: math.LegacyNewDec(initial)}} - distrKeeper.AllocateTokensToValidator(ctx, val, tokens) - - // second delegation - tstaking.Ctx = ctx - tstaking.Delegate(sdk.AccAddress(valAddrs[1]), valAddrs[0], sdk.NewInt(100)) - del2 := stakingKeeper.Delegation(ctx, sdk.AccAddress(valAddrs[1]), valAddrs[0]) - - // fetch updated validator - val = stakingKeeper.Validator(ctx, valAddrs[0]) - - // end block - staking.EndBlocker(ctx, stakingKeeper) - - // next block - ctx = ctx.WithBlockHeight(ctx.BlockHeight() + 1) - - // allocate some more rewards - distrKeeper.AllocateTokensToValidator(ctx, val, tokens) - - // end period - endingPeriod := distrKeeper.IncrementValidatorPeriod(ctx, val) - - // calculate delegation rewards for del1 - rewards := distrKeeper.CalculateDelegationRewards(ctx, val, del1, endingPeriod) - - // rewards for del1 should be 3/4 initial - assert.DeepEqual(t, sdk.DecCoins{{Denom: sdk.DefaultBondDenom, Amount: math.LegacyNewDec(initial * 3 / 4)}}, rewards) - - // calculate delegation rewards for del2 - rewards = distrKeeper.CalculateDelegationRewards(ctx, val, del2, endingPeriod) - - // rewards for del2 should be 1/4 initial - assert.DeepEqual(t, sdk.DecCoins{{Denom: sdk.DefaultBondDenom, Amount: math.LegacyNewDec(initial * 1 / 4)}}, rewards) - - // commission should be equal to initial (50% twice) - assert.DeepEqual(t, sdk.DecCoins{{Denom: sdk.DefaultBondDenom, Amount: math.LegacyNewDec(initial)}}, distrKeeper.GetValidatorAccumulatedCommission(ctx, valAddrs[0]).Commission) -} - -func TestWithdrawDelegationRewardsBasic(t *testing.T) { - var ( - accountKeeper authkeeper.AccountKeeper - bankKeeper bankkeeper.Keeper - distrKeeper keeper.Keeper - stakingKeeper *stakingkeeper.Keeper - ) - - app, err := simtestutil.Setup(testutil.AppConfig, - &accountKeeper, - &bankKeeper, - &distrKeeper, - &stakingKeeper, - ) - assert.NilError(t, err) - - ctx := app.BaseApp.NewContext(false, cmtproto.Header{}) - - distrKeeper.DeleteAllValidatorHistoricalRewards(ctx) - - balancePower := int64(1000) - balanceTokens := stakingKeeper.TokensFromConsensusPower(ctx, balancePower) - addr := simtestutil.AddTestAddrs(bankKeeper, stakingKeeper, ctx, 1, sdk.NewInt(1000000000)) - valAddrs := simtestutil.ConvertAddrsToValAddrs(addr) - tstaking := stakingtestutil.NewHelper(t, ctx, stakingKeeper) - - // set module account coins - distrAcc := distrKeeper.GetDistributionAccount(ctx) - assert.NilError(t, banktestutil.FundModuleAccount(bankKeeper, ctx, distrAcc.GetName(), sdk.NewCoins(sdk.NewCoin(sdk.DefaultBondDenom, balanceTokens)))) - accountKeeper.SetModuleAccount(ctx, distrAcc) - - // create validator with 50% commission - power := int64(100) - tstaking.Commission = stakingtypes.NewCommissionRates(sdk.NewDecWithPrec(5, 1), sdk.NewDecWithPrec(5, 1), math.LegacyNewDec(0)) - valTokens := tstaking.CreateValidatorWithValPower(valAddrs[0], valConsPk0, power, true) - - // assert correct initial balance - expTokens := balanceTokens.Sub(valTokens) - assert.DeepEqual(t, - sdk.Coins{sdk.NewCoin(sdk.DefaultBondDenom, expTokens)}, - bankKeeper.GetAllBalances(ctx, sdk.AccAddress(valAddrs[0])), - ) - - // end block to bond validator - staking.EndBlocker(ctx, stakingKeeper) - - // next block - ctx = ctx.WithBlockHeight(ctx.BlockHeight() + 1) - - // fetch validator and delegation - val := stakingKeeper.Validator(ctx, valAddrs[0]) - - // allocate some rewards - initial := stakingKeeper.TokensFromConsensusPower(ctx, 10) - tokens := sdk.DecCoins{sdk.NewDecCoin(sdk.DefaultBondDenom, initial)} - - distrKeeper.AllocateTokensToValidator(ctx, val, tokens) - - // historical count should be 2 (initial + latest for delegation) - assert.Equal(t, uint64(2), distrKeeper.GetValidatorHistoricalReferenceCount(ctx)) - - // withdraw rewards - _, err = distrKeeper.WithdrawDelegationRewards(ctx, sdk.AccAddress(valAddrs[0]), valAddrs[0]) - assert.Assert(t, err == nil) - - // historical count should still be 2 (added one record, cleared one) - assert.Equal(t, uint64(2), distrKeeper.GetValidatorHistoricalReferenceCount(ctx)) - - // assert correct balance - exp := balanceTokens.Sub(valTokens).Add(initial.QuoRaw(2)) - assert.DeepEqual(t, - sdk.Coins{sdk.NewCoin(sdk.DefaultBondDenom, exp)}, - bankKeeper.GetAllBalances(ctx, sdk.AccAddress(valAddrs[0])), - ) - - // withdraw commission - _, err = distrKeeper.WithdrawValidatorCommission(ctx, valAddrs[0]) - assert.Assert(t, err == nil) - - // assert correct balance - exp = balanceTokens.Sub(valTokens).Add(initial) - assert.DeepEqual(t, - sdk.Coins{sdk.NewCoin(sdk.DefaultBondDenom, exp)}, - bankKeeper.GetAllBalances(ctx, sdk.AccAddress(valAddrs[0])), - ) -} - -func TestCalculateRewardsAfterManySlashesInSameBlock(t *testing.T) { - var ( - bankKeeper bankkeeper.Keeper - distrKeeper keeper.Keeper - stakingKeeper *stakingkeeper.Keeper - ) - - app, err := simtestutil.Setup(testutil.AppConfig, - &bankKeeper, - &distrKeeper, - &stakingKeeper, - ) - assert.NilError(t, err) - - ctx := app.BaseApp.NewContext(false, cmtproto.Header{}) - - addr := simtestutil.AddTestAddrs(bankKeeper, stakingKeeper, ctx, 1, sdk.NewInt(1000000000)) - valAddrs := simtestutil.ConvertAddrsToValAddrs(addr) - tstaking := stakingtestutil.NewHelper(t, ctx, stakingKeeper) - - // create validator with 50% commission - valPower := int64(100) - tstaking.Commission = stakingtypes.NewCommissionRates(sdk.NewDecWithPrec(5, 1), sdk.NewDecWithPrec(5, 1), math.LegacyNewDec(0)) - tstaking.CreateValidatorWithValPower(valAddrs[0], valConsPk0, valPower, true) - - // end block to bond validator - staking.EndBlocker(ctx, stakingKeeper) - - // next block - ctx = ctx.WithBlockHeight(ctx.BlockHeight() + 1) - - // fetch validator and delegation - val := stakingKeeper.Validator(ctx, valAddrs[0]) - del := stakingKeeper.Delegation(ctx, sdk.AccAddress(valAddrs[0]), valAddrs[0]) - - // end period - endingPeriod := distrKeeper.IncrementValidatorPeriod(ctx, val) - - // calculate delegation rewards - rewards := distrKeeper.CalculateDelegationRewards(ctx, val, del, endingPeriod) - - // rewards should be zero - assert.Assert(t, rewards.IsZero()) - - // start out block height - ctx = ctx.WithBlockHeight(ctx.BlockHeight() + 3) - - // allocate some rewards - initial := sdk.NewDecFromInt(stakingKeeper.TokensFromConsensusPower(ctx, 10)) - tokens := sdk.DecCoins{{Denom: sdk.DefaultBondDenom, Amount: initial}} - distrKeeper.AllocateTokensToValidator(ctx, val, tokens) - - // slash the validator by 50% - stakingKeeper.Slash(ctx, valConsAddr0, ctx.BlockHeight(), valPower, sdk.NewDecWithPrec(5, 1)) - - // slash the validator by 50% again - stakingKeeper.Slash(ctx, valConsAddr0, ctx.BlockHeight(), valPower/2, sdk.NewDecWithPrec(5, 1)) - - // fetch the validator again - val = stakingKeeper.Validator(ctx, valAddrs[0]) - - // increase block height - ctx = ctx.WithBlockHeight(ctx.BlockHeight() + 3) - - // allocate some more rewards - distrKeeper.AllocateTokensToValidator(ctx, val, tokens) - - // end period - endingPeriod = distrKeeper.IncrementValidatorPeriod(ctx, val) - - // calculate delegation rewards - rewards = distrKeeper.CalculateDelegationRewards(ctx, val, del, endingPeriod) - - // rewards should be half the tokens - assert.DeepEqual(t, sdk.DecCoins{{Denom: sdk.DefaultBondDenom, Amount: initial}}, rewards) - - // commission should be the other half - assert.DeepEqual(t, sdk.DecCoins{{Denom: sdk.DefaultBondDenom, Amount: initial}}, distrKeeper.GetValidatorAccumulatedCommission(ctx, valAddrs[0]).Commission) -} - -func TestCalculateRewardsMultiDelegatorMultiSlash(t *testing.T) { - var ( - bankKeeper bankkeeper.Keeper - distrKeeper keeper.Keeper - stakingKeeper *stakingkeeper.Keeper - ) - - app, err := simtestutil.Setup(testutil.AppConfig, - &bankKeeper, - &distrKeeper, - &stakingKeeper, - ) - assert.NilError(t, err) - - ctx := app.BaseApp.NewContext(false, cmtproto.Header{}) - - tstaking := stakingtestutil.NewHelper(t, ctx, stakingKeeper) - addr := simtestutil.AddTestAddrs(bankKeeper, stakingKeeper, ctx, 2, sdk.NewInt(1000000000)) - valAddrs := simtestutil.ConvertAddrsToValAddrs(addr) - - // create validator with 50% commission - tstaking.Commission = stakingtypes.NewCommissionRates(sdk.NewDecWithPrec(5, 1), sdk.NewDecWithPrec(5, 1), math.LegacyNewDec(0)) - valPower := int64(100) - tstaking.CreateValidatorWithValPower(valAddrs[0], valConsPk0, valPower, true) - - // end block to bond validator - staking.EndBlocker(ctx, stakingKeeper) - - // next block - ctx = ctx.WithBlockHeight(ctx.BlockHeight() + 1) - - // fetch validator and delegation - val := stakingKeeper.Validator(ctx, valAddrs[0]) - del1 := stakingKeeper.Delegation(ctx, sdk.AccAddress(valAddrs[0]), valAddrs[0]) - - // allocate some rewards - initial := sdk.NewDecFromInt(stakingKeeper.TokensFromConsensusPower(ctx, 30)) - tokens := sdk.DecCoins{{Denom: sdk.DefaultBondDenom, Amount: initial}} - distrKeeper.AllocateTokensToValidator(ctx, val, tokens) - - // slash the validator - ctx = ctx.WithBlockHeight(ctx.BlockHeight() + 3) - stakingKeeper.Slash(ctx, valConsAddr0, ctx.BlockHeight(), valPower, sdk.NewDecWithPrec(5, 1)) - ctx = ctx.WithBlockHeight(ctx.BlockHeight() + 3) - - // second delegation - tstaking.DelegateWithPower(sdk.AccAddress(valAddrs[1]), valAddrs[0], 100) - - del2 := stakingKeeper.Delegation(ctx, sdk.AccAddress(valAddrs[1]), valAddrs[0]) - - // end block - staking.EndBlocker(ctx, stakingKeeper) - - // next block - ctx = ctx.WithBlockHeight(ctx.BlockHeight() + 1) - - // allocate some more rewards - distrKeeper.AllocateTokensToValidator(ctx, val, tokens) - - // slash the validator again - ctx = ctx.WithBlockHeight(ctx.BlockHeight() + 3) - stakingKeeper.Slash(ctx, valConsAddr0, ctx.BlockHeight(), valPower, sdk.NewDecWithPrec(5, 1)) - ctx = ctx.WithBlockHeight(ctx.BlockHeight() + 3) - - // fetch updated validator - val = stakingKeeper.Validator(ctx, valAddrs[0]) - - // end period - endingPeriod := distrKeeper.IncrementValidatorPeriod(ctx, val) - - // calculate delegation rewards for del1 - rewards := distrKeeper.CalculateDelegationRewards(ctx, val, del1, endingPeriod) - - // rewards for del1 should be 2/3 initial (half initial first period, 1/6 initial second period) - assert.DeepEqual(t, sdk.DecCoins{{Denom: sdk.DefaultBondDenom, Amount: initial.QuoInt64(2).Add(initial.QuoInt64(6))}}, rewards) - - // calculate delegation rewards for del2 - rewards = distrKeeper.CalculateDelegationRewards(ctx, val, del2, endingPeriod) - - // rewards for del2 should be initial / 3 - assert.DeepEqual(t, sdk.DecCoins{{Denom: sdk.DefaultBondDenom, Amount: initial.QuoInt64(3)}}, rewards) - - // commission should be equal to initial (twice 50% commission, unaffected by slashing) - assert.DeepEqual(t, sdk.DecCoins{{Denom: sdk.DefaultBondDenom, Amount: initial}}, distrKeeper.GetValidatorAccumulatedCommission(ctx, valAddrs[0]).Commission) -} - -func TestCalculateRewardsMultiDelegatorMultWithdraw(t *testing.T) { - var ( - accountKeeper authkeeper.AccountKeeper - bankKeeper bankkeeper.Keeper - distrKeeper keeper.Keeper - stakingKeeper *stakingkeeper.Keeper - ) - - app, err := simtestutil.Setup(testutil.AppConfig, - &accountKeeper, - &bankKeeper, - &distrKeeper, - &stakingKeeper, - ) - assert.NilError(t, err) - - ctx := app.BaseApp.NewContext(false, cmtproto.Header{}) - - distrKeeper.DeleteAllValidatorHistoricalRewards(ctx) - - tstaking := stakingtestutil.NewHelper(t, ctx, stakingKeeper) - addr := simtestutil.AddTestAddrs(bankKeeper, stakingKeeper, ctx, 2, sdk.NewInt(1000000000)) - valAddrs := simtestutil.ConvertAddrsToValAddrs(addr) - initial := int64(20) - - // set module account coins - distrAcc := distrKeeper.GetDistributionAccount(ctx) - assert.NilError(t, banktestutil.FundModuleAccount(bankKeeper, ctx, distrAcc.GetName(), sdk.NewCoins(sdk.NewCoin(sdk.DefaultBondDenom, sdk.NewInt(1000))))) - accountKeeper.SetModuleAccount(ctx, distrAcc) - - tokens := sdk.DecCoins{sdk.NewDecCoinFromDec(sdk.DefaultBondDenom, math.LegacyNewDec(initial))} - - // create validator with 50% commission - tstaking.Commission = stakingtypes.NewCommissionRates(sdk.NewDecWithPrec(5, 1), sdk.NewDecWithPrec(5, 1), math.LegacyNewDec(0)) - tstaking.CreateValidator(valAddrs[0], valConsPk0, sdk.NewInt(100), true) - - // end block to bond validator - staking.EndBlocker(ctx, stakingKeeper) - - // next block - ctx = ctx.WithBlockHeight(ctx.BlockHeight() + 1) - - // fetch validator and delegation - val := stakingKeeper.Validator(ctx, valAddrs[0]) - del1 := stakingKeeper.Delegation(ctx, sdk.AccAddress(valAddrs[0]), valAddrs[0]) - - // allocate some rewards - distrKeeper.AllocateTokensToValidator(ctx, val, tokens) - - // historical count should be 2 (validator init, delegation init) - assert.Equal(t, uint64(2), distrKeeper.GetValidatorHistoricalReferenceCount(ctx)) - - // second delegation - tstaking.Delegate(sdk.AccAddress(valAddrs[1]), valAddrs[0], sdk.NewInt(100)) - - // historical count should be 3 (second delegation init) - assert.Equal(t, uint64(3), distrKeeper.GetValidatorHistoricalReferenceCount(ctx)) - - // fetch updated validator - val = stakingKeeper.Validator(ctx, valAddrs[0]) - del2 := stakingKeeper.Delegation(ctx, sdk.AccAddress(valAddrs[1]), valAddrs[0]) - - // end block - staking.EndBlocker(ctx, stakingKeeper) - - // next block - ctx = ctx.WithBlockHeight(ctx.BlockHeight() + 1) - - // allocate some more rewards - distrKeeper.AllocateTokensToValidator(ctx, val, tokens) - - // first delegator withdraws - _, err = distrKeeper.WithdrawDelegationRewards(ctx, sdk.AccAddress(valAddrs[0]), valAddrs[0]) - assert.NilError(t, err) - - // second delegator withdraws - _, err = distrKeeper.WithdrawDelegationRewards(ctx, sdk.AccAddress(valAddrs[1]), valAddrs[0]) - assert.NilError(t, err) - - // historical count should be 3 (validator init + two delegations) - assert.Equal(t, uint64(3), distrKeeper.GetValidatorHistoricalReferenceCount(ctx)) - - // validator withdraws commission - _, err = distrKeeper.WithdrawValidatorCommission(ctx, valAddrs[0]) - assert.NilError(t, err) - - // end period - endingPeriod := distrKeeper.IncrementValidatorPeriod(ctx, val) - - // calculate delegation rewards for del1 - rewards := distrKeeper.CalculateDelegationRewards(ctx, val, del1, endingPeriod) - - // rewards for del1 should be zero - assert.Assert(t, rewards.IsZero()) - - // calculate delegation rewards for del2 - rewards = distrKeeper.CalculateDelegationRewards(ctx, val, del2, endingPeriod) - - // rewards for del2 should be zero - assert.Assert(t, rewards.IsZero()) - - // commission should be zero - assert.Assert(t, distrKeeper.GetValidatorAccumulatedCommission(ctx, valAddrs[0]).Commission.IsZero()) - - // next block - ctx = ctx.WithBlockHeight(ctx.BlockHeight() + 1) - - // allocate some more rewards - distrKeeper.AllocateTokensToValidator(ctx, val, tokens) - - // first delegator withdraws again - _, err = distrKeeper.WithdrawDelegationRewards(ctx, sdk.AccAddress(valAddrs[0]), valAddrs[0]) - assert.NilError(t, err) - - // end period - endingPeriod = distrKeeper.IncrementValidatorPeriod(ctx, val) - - // calculate delegation rewards for del1 - rewards = distrKeeper.CalculateDelegationRewards(ctx, val, del1, endingPeriod) - - // rewards for del1 should be zero - assert.Assert(t, rewards.IsZero()) - - // calculate delegation rewards for del2 - rewards = distrKeeper.CalculateDelegationRewards(ctx, val, del2, endingPeriod) - - // rewards for del2 should be 1/4 initial - assert.DeepEqual(t, sdk.DecCoins{{Denom: sdk.DefaultBondDenom, Amount: math.LegacyNewDec(initial / 4)}}, rewards) - - // commission should be half initial - assert.DeepEqual(t, sdk.DecCoins{{Denom: sdk.DefaultBondDenom, Amount: math.LegacyNewDec(initial / 2)}}, distrKeeper.GetValidatorAccumulatedCommission(ctx, valAddrs[0]).Commission) - - // next block - ctx = ctx.WithBlockHeight(ctx.BlockHeight() + 1) - - // allocate some more rewards - distrKeeper.AllocateTokensToValidator(ctx, val, tokens) - - // withdraw commission - _, err = distrKeeper.WithdrawValidatorCommission(ctx, valAddrs[0]) - assert.NilError(t, err) - - // end period - endingPeriod = distrKeeper.IncrementValidatorPeriod(ctx, val) - - // calculate delegation rewards for del1 - rewards = distrKeeper.CalculateDelegationRewards(ctx, val, del1, endingPeriod) - - // rewards for del1 should be 1/4 initial - assert.DeepEqual(t, sdk.DecCoins{{Denom: sdk.DefaultBondDenom, Amount: math.LegacyNewDec(initial / 4)}}, rewards) - - // calculate delegation rewards for del2 - rewards = distrKeeper.CalculateDelegationRewards(ctx, val, del2, endingPeriod) - - // rewards for del2 should be 1/2 initial - assert.DeepEqual(t, sdk.DecCoins{{Denom: sdk.DefaultBondDenom, Amount: math.LegacyNewDec(initial / 2)}}, rewards) - - // commission should be zero - assert.Assert(t, distrKeeper.GetValidatorAccumulatedCommission(ctx, valAddrs[0]).Commission.IsZero()) -} - -func Test100PercentCommissionReward(t *testing.T) { - var ( - accountKeeper authkeeper.AccountKeeper - bankKeeper bankkeeper.Keeper - distrKeeper keeper.Keeper - stakingKeeper *stakingkeeper.Keeper - ) - - app, err := simtestutil.Setup(testutil.AppConfig, - &accountKeeper, - &bankKeeper, - &distrKeeper, - &stakingKeeper, - ) - assert.NilError(t, err) - - ctx := app.BaseApp.NewContext(false, cmtproto.Header{}) - - tstaking := stakingtestutil.NewHelper(t, ctx, stakingKeeper) - addr := simtestutil.AddTestAddrs(bankKeeper, stakingKeeper, ctx, 2, sdk.NewInt(1000000000)) - valAddrs := simtestutil.ConvertAddrsToValAddrs(addr) - initial := int64(20) - - // set module account coins - distrAcc := distrKeeper.GetDistributionAccount(ctx) - assert.NilError(t, banktestutil.FundModuleAccount(bankKeeper, ctx, distrAcc.GetName(), sdk.NewCoins(sdk.NewCoin(sdk.DefaultBondDenom, sdk.NewInt(1000))))) - accountKeeper.SetModuleAccount(ctx, distrAcc) - - tokens := sdk.DecCoins{sdk.NewDecCoinFromDec(sdk.DefaultBondDenom, math.LegacyNewDec(initial))} - - // create validator with 100% commission - tstaking.Commission = stakingtypes.NewCommissionRates(sdk.NewDecWithPrec(10, 1), sdk.NewDecWithPrec(10, 1), math.LegacyNewDec(0)) - tstaking.CreateValidator(valAddrs[0], valConsPk0, sdk.NewInt(100), true) - stakingKeeper.Delegation(ctx, sdk.AccAddress(valAddrs[0]), valAddrs[0]) - - // end block to bond validator - staking.EndBlocker(ctx, stakingKeeper) - // next block - ctx = ctx.WithBlockHeight(ctx.BlockHeight() + 1) - - // fetch validator - val := stakingKeeper.Validator(ctx, valAddrs[0]) - - // allocate some rewards - distrKeeper.AllocateTokensToValidator(ctx, val, tokens) - - // end block - staking.EndBlocker(ctx, stakingKeeper) - - // next block - ctx = ctx.WithBlockHeight(ctx.BlockHeight() + 1) - - // allocate some more rewards - distrKeeper.AllocateTokensToValidator(ctx, val, tokens) - - // next block - ctx = ctx.WithBlockHeight(ctx.BlockHeight() + 1) - - // allocate some more rewards - distrKeeper.AllocateTokensToValidator(ctx, val, tokens) - - rewards, err := distrKeeper.WithdrawDelegationRewards(ctx, sdk.AccAddress(valAddrs[0]), valAddrs[0]) - assert.NilError(t, err) - - zeroRewards := sdk.Coins{sdk.NewCoin(sdk.DefaultBondDenom, math.ZeroInt())} - assert.Assert(t, rewards.Equal(zeroRewards)) - - events := ctx.EventManager().Events() - lastEvent := events[len(events)-1] - - var hasValue bool - for _, attr := range lastEvent.Attributes { - if attr.Key == "amount" && attr.Value == "0stake" { - hasValue = true - } - } - assert.Assert(t, hasValue) -} diff --git a/tests/integration/distribution/keeper/grpc_query_test.go b/tests/integration/distribution/keeper/grpc_query_test.go index 7ae9af27a451..1c949e8595fa 100644 --- a/tests/integration/distribution/keeper/grpc_query_test.go +++ b/tests/integration/distribution/keeper/grpc_query_test.go @@ -1,97 +1,49 @@ package keeper_test import ( - gocontext "context" "fmt" "testing" "cosmossdk.io/math" - cmtproto "github.com/cometbft/cometbft/proto/tendermint/types" "gotest.tools/v3/assert" - "github.com/cosmos/cosmos-sdk/baseapp" - codectypes "github.com/cosmos/cosmos-sdk/codec/types" - simtestutil "github.com/cosmos/cosmos-sdk/testutil/sims" sdk "github.com/cosmos/cosmos-sdk/types" "github.com/cosmos/cosmos-sdk/types/query" - bankkeeper "github.com/cosmos/cosmos-sdk/x/bank/keeper" - banktestutil "github.com/cosmos/cosmos-sdk/x/bank/testutil" - "github.com/cosmos/cosmos-sdk/x/distribution/keeper" - "github.com/cosmos/cosmos-sdk/x/distribution/testutil" "github.com/cosmos/cosmos-sdk/x/distribution/types" - "github.com/cosmos/cosmos-sdk/x/staking" - stakingkeeper "github.com/cosmos/cosmos-sdk/x/staking/keeper" stakingtestutil "github.com/cosmos/cosmos-sdk/x/staking/testutil" stakingtypes "github.com/cosmos/cosmos-sdk/x/staking/types" ) -type fixture struct { - ctx sdk.Context - queryClient types.QueryClient - addrs []sdk.AccAddress - valAddrs []sdk.ValAddress - - interfaceRegistry codectypes.InterfaceRegistry - bankKeeper bankkeeper.Keeper - distrKeeper keeper.Keeper - stakingKeeper *stakingkeeper.Keeper - msgServer types.MsgServer -} - -func initFixture(t assert.TestingT) *fixture { - f := &fixture{} - - app, err := simtestutil.Setup( - testutil.AppConfig, - &f.interfaceRegistry, - &f.bankKeeper, - &f.distrKeeper, - &f.stakingKeeper, - ) - assert.NilError(t, err) - - ctx := app.BaseApp.NewContext(false, cmtproto.Header{}) - - queryHelper := baseapp.NewQueryServerTestHelper(ctx, f.interfaceRegistry) - types.RegisterQueryServer(queryHelper, keeper.NewQuerier(f.distrKeeper)) - queryClient := types.NewQueryClient(queryHelper) - - f.ctx = ctx - f.queryClient = queryClient - - f.addrs = simtestutil.AddTestAddrs(f.bankKeeper, f.stakingKeeper, ctx, 2, sdk.NewInt(1000000000)) - f.valAddrs = simtestutil.ConvertAddrsToValAddrs(f.addrs) - f.msgServer = keeper.NewMsgServerImpl(f.distrKeeper) - - return f -} - func TestGRPCParams(t *testing.T) { t.Parallel() f := initFixture(t) - ctx, queryClient := f.ctx, f.queryClient + f.distrKeeper.SetParams(f.sdkCtx, types.DefaultParams()) + + qr := f.app.QueryHelper() + queryClient := types.NewQueryClient(qr) var ( params types.Params - req *types.QueryParamsRequest expParams types.Params ) testCases := []struct { - msg string - malleate func() + name string + malleate func() + msg *types.QueryParamsRequest + expErrMsg string }{ { - "empty params request", - func() { - req = &types.QueryParamsRequest{} + name: "empty params request", + malleate: func() { expParams = types.DefaultParams() }, + msg: &types.QueryParamsRequest{}, }, { - "valid request", - func() { + name: "valid request", + malleate: func() { params = types.Params{ CommunityTax: sdk.NewDecWithPrec(3, 1), BaseProposerReward: sdk.ZeroDec(), @@ -99,23 +51,23 @@ func TestGRPCParams(t *testing.T) { WithdrawAddrEnabled: true, } - assert.NilError(t, f.distrKeeper.SetParams(ctx, params)) - req = &types.QueryParamsRequest{} + assert.NilError(t, f.distrKeeper.SetParams(f.sdkCtx, params)) expParams = params }, + msg: &types.QueryParamsRequest{}, }, } - for _, testCase := range testCases { - t.Run(fmt.Sprintf("Case %s", testCase.msg), func(t *testing.T) { - testCase.malleate() - - paramsRes, err := queryClient.Params(gocontext.Background(), req) + tc := testCase + t.Run(fmt.Sprintf("Case %s", tc.name), func(t *testing.T) { + tc.malleate() + paramsRes, err := queryClient.Params(f.sdkCtx, tc.msg) assert.NilError(t, err) assert.Assert(t, paramsRes != nil) - assert.DeepEqual(t, expParams, paramsRes.Params) + assert.DeepEqual(t, paramsRes.Params, expParams) }) + } } @@ -123,54 +75,70 @@ func TestGRPCValidatorOutstandingRewards(t *testing.T) { t.Parallel() f := initFixture(t) - ctx, queryClient, valAddrs := f.ctx, f.queryClient, f.valAddrs + // set module account coins + initTokens := f.stakingKeeper.TokensFromConsensusPower(f.sdkCtx, int64(1000)) + f.bankKeeper.MintCoins(f.sdkCtx, types.ModuleName, sdk.NewCoins(sdk.NewCoin(sdk.DefaultBondDenom, initTokens))) + + // Set default staking params + f.stakingKeeper.SetParams(f.sdkCtx, stakingtypes.DefaultParams()) + + qr := f.app.QueryHelper() + queryClient := types.NewQueryClient(qr) valCommission := sdk.DecCoins{ sdk.NewDecCoinFromDec("mytoken", math.LegacyNewDec(5000)), sdk.NewDecCoinFromDec("stake", math.LegacyNewDec(300)), } - // set outstanding rewards - f.distrKeeper.SetValidatorOutstandingRewards(ctx, valAddrs[0], types.ValidatorOutstandingRewards{Rewards: valCommission}) - rewards := f.distrKeeper.GetValidatorOutstandingRewards(ctx, valAddrs[0]) + // send funds to val addr + funds := f.stakingKeeper.TokensFromConsensusPower(f.sdkCtx, int64(1000)) + f.bankKeeper.SendCoinsFromModuleToAccount(f.sdkCtx, types.ModuleName, sdk.AccAddress(f.valAddr), sdk.NewCoins(sdk.NewCoin(sdk.DefaultBondDenom, funds))) + + initialStake := int64(10) + tstaking := stakingtestutil.NewHelper(t, f.sdkCtx, f.stakingKeeper) + tstaking.Commission = stakingtypes.NewCommissionRates(sdk.NewDecWithPrec(5, 1), sdk.NewDecWithPrec(5, 1), math.LegacyNewDec(0)) + tstaking.CreateValidator(f.valAddr, valConsPk0, sdk.NewInt(initialStake), true) - var req *types.QueryValidatorOutstandingRewardsRequest + // set outstanding rewards + f.distrKeeper.SetValidatorOutstandingRewards(f.sdkCtx, f.valAddr, types.ValidatorOutstandingRewards{Rewards: valCommission}) + rewards := f.distrKeeper.GetValidatorOutstandingRewards(f.sdkCtx, f.valAddr) testCases := []struct { - msg string - malleate func() + name string + msg *types.QueryValidatorOutstandingRewardsRequest expPass bool expErrMsg string }{ { - "empty request", - func() { - req = &types.QueryValidatorOutstandingRewardsRequest{} - }, - false, - "empty validator address", - }, { - "valid request", - func() { - req = &types.QueryValidatorOutstandingRewardsRequest{ValidatorAddress: valAddrs[0].String()} - }, - true, - "", + name: "empty request", + msg: &types.QueryValidatorOutstandingRewardsRequest{}, + expPass: false, + expErrMsg: "empty validator address", + }, + { + name: "invalid address", + msg: &types.QueryValidatorOutstandingRewardsRequest{ValidatorAddress: sdk.ValAddress([]byte("addr1_______________")).String()}, + expPass: false, + expErrMsg: "validator does not exist", + }, + { + name: "valid request", + msg: &types.QueryValidatorOutstandingRewardsRequest{ValidatorAddress: f.valAddr.String()}, + expPass: true, }, } for _, testCase := range testCases { - t.Run(fmt.Sprintf("Case %s", testCase.msg), func(t *testing.T) { - testCase.malleate() + tc := testCase + t.Run(fmt.Sprintf("Case %s", tc.name), func(t *testing.T) { + validatorOutstandingRewards, err := queryClient.ValidatorOutstandingRewards(f.sdkCtx, tc.msg) - validatorOutstandingRewards, err := queryClient.ValidatorOutstandingRewards(gocontext.Background(), req) - - if testCase.expPass { + if tc.expPass { assert.NilError(t, err) assert.DeepEqual(t, rewards, validatorOutstandingRewards.Rewards) assert.DeepEqual(t, valCommission, validatorOutstandingRewards.Rewards.Rewards) } else { - assert.ErrorContains(t, err, testCase.expErrMsg) + assert.ErrorContains(t, err, tc.expErrMsg) assert.Assert(t, validatorOutstandingRewards == nil) } }) @@ -181,49 +149,64 @@ func TestGRPCValidatorCommission(t *testing.T) { t.Parallel() f := initFixture(t) - ctx, queryClient, valAddrs := f.ctx, f.queryClient, f.valAddrs + // set module account coins + initTokens := f.stakingKeeper.TokensFromConsensusPower(f.sdkCtx, int64(1000)) + f.bankKeeper.MintCoins(f.sdkCtx, types.ModuleName, sdk.NewCoins(sdk.NewCoin(sdk.DefaultBondDenom, initTokens))) - commission := sdk.DecCoins{{Denom: "token1", Amount: math.LegacyNewDec(4)}, {Denom: "token2", Amount: math.LegacyNewDec(2)}} - f.distrKeeper.SetValidatorAccumulatedCommission(ctx, valAddrs[0], types.ValidatorAccumulatedCommission{Commission: commission}) + // Set default staking params + f.stakingKeeper.SetParams(f.sdkCtx, stakingtypes.DefaultParams()) + + qr := f.app.QueryHelper() + queryClient := types.NewQueryClient(qr) - var req *types.QueryValidatorCommissionRequest + // send funds to val addr + funds := f.stakingKeeper.TokensFromConsensusPower(f.sdkCtx, int64(1000)) + f.bankKeeper.SendCoinsFromModuleToAccount(f.sdkCtx, types.ModuleName, sdk.AccAddress(f.valAddr), sdk.NewCoins(sdk.NewCoin(sdk.DefaultBondDenom, funds))) + + initialStake := int64(10) + tstaking := stakingtestutil.NewHelper(t, f.sdkCtx, f.stakingKeeper) + tstaking.Commission = stakingtypes.NewCommissionRates(sdk.NewDecWithPrec(5, 1), sdk.NewDecWithPrec(5, 1), math.LegacyNewDec(0)) + tstaking.CreateValidator(f.valAddr, valConsPk0, sdk.NewInt(initialStake), true) + + commission := sdk.DecCoins{{Denom: "token1", Amount: math.LegacyNewDec(4)}, {Denom: "token2", Amount: math.LegacyNewDec(2)}} + f.distrKeeper.SetValidatorAccumulatedCommission(f.sdkCtx, f.valAddr, types.ValidatorAccumulatedCommission{Commission: commission}) testCases := []struct { - msg string - malleate func() + name string + msg *types.QueryValidatorCommissionRequest expPass bool expErrMsg string }{ { - "empty request", - func() { - req = &types.QueryValidatorCommissionRequest{} - }, - false, - "empty validator address", + name: "empty request", + msg: &types.QueryValidatorCommissionRequest{}, + expPass: false, + expErrMsg: "empty validator address", }, { - "valid request", - func() { - req = &types.QueryValidatorCommissionRequest{ValidatorAddress: valAddrs[0].String()} - }, - true, - "", + name: "invalid validator", + msg: &types.QueryValidatorCommissionRequest{ValidatorAddress: sdk.ValAddress([]byte("addr1_______________")).String()}, + expPass: false, + expErrMsg: "validator does not exist", + }, + { + name: "valid request", + msg: &types.QueryValidatorCommissionRequest{ValidatorAddress: f.valAddr.String()}, + expPass: true, }, } for _, testCase := range testCases { - t.Run(fmt.Sprintf("Case %s", testCase.msg), func(t *testing.T) { - testCase.malleate() - - commissionRes, err := queryClient.ValidatorCommission(gocontext.Background(), req) + tc := testCase + t.Run(fmt.Sprintf("Case %s", tc.name), func(t *testing.T) { + commissionRes, err := queryClient.ValidatorCommission(f.sdkCtx, tc.msg) - if testCase.expPass { + if tc.expPass { assert.NilError(t, err) assert.Assert(t, commissionRes != nil) assert.DeepEqual(t, commissionRes.Commission.Commission, commission) } else { - assert.ErrorContains(t, err, testCase.expErrMsg) + assert.ErrorContains(t, err, tc.expErrMsg) assert.Assert(t, commissionRes == nil) } }) @@ -234,7 +217,11 @@ func TestGRPCValidatorSlashes(t *testing.T) { t.Parallel() f := initFixture(t) - ctx, queryClient, valAddrs := f.ctx, f.queryClient, f.valAddrs + qr := f.app.QueryHelper() + queryClient := types.NewQueryClient(qr) + + addr2 := sdk.AccAddress(PKS[1].Address()) + valAddr2 := sdk.ValAddress(addr2) slashes := []types.ValidatorSlashEvent{ types.NewValidatorSlashEvent(3, sdk.NewDecWithPrec(5, 1)), @@ -244,7 +231,7 @@ func TestGRPCValidatorSlashes(t *testing.T) { } for i, slash := range slashes { - f.distrKeeper.SetValidatorSlashEvent(ctx, valAddrs[0], uint64(i+2), 0, slash) + f.distrKeeper.SetValidatorSlashEvent(f.sdkCtx, f.valAddr, uint64(i+2), 0, slash) } var ( @@ -253,56 +240,55 @@ func TestGRPCValidatorSlashes(t *testing.T) { ) testCases := []struct { - msg string + name string malleate func() expPass bool expErrMsg string }{ { - "empty request", - func() { + name: "empty request", + malleate: func() { req = &types.QueryValidatorSlashesRequest{} expRes = &types.QueryValidatorSlashesResponse{} }, - false, - "empty validator address", + expPass: false, + expErrMsg: "empty validator address", }, { - "Ending height lesser than start height request", - func() { + name: "Ending height lesser than start height request", + malleate: func() { req = &types.QueryValidatorSlashesRequest{ - ValidatorAddress: valAddrs[1].String(), + ValidatorAddress: valAddr2.String(), StartingHeight: 10, EndingHeight: 1, } expRes = &types.QueryValidatorSlashesResponse{Pagination: &query.PageResponse{}} }, - false, - "starting height greater than ending height", + expPass: false, + expErrMsg: "starting height greater than ending height", }, { - "no slash event validator request", - func() { + name: "no slash event validator request", + malleate: func() { req = &types.QueryValidatorSlashesRequest{ - ValidatorAddress: valAddrs[1].String(), + ValidatorAddress: valAddr2.String(), StartingHeight: 1, EndingHeight: 10, } expRes = &types.QueryValidatorSlashesResponse{Pagination: &query.PageResponse{}} }, - true, - "", + expPass: true, }, { - "request slashes with offset 2 and limit 2", - func() { + name: "request slashes with offset 2 and limit 2", + malleate: func() { pageReq := &query.PageRequest{ Offset: 2, Limit: 2, } req = &types.QueryValidatorSlashesRequest{ - ValidatorAddress: valAddrs[0].String(), + ValidatorAddress: f.valAddr.String(), StartingHeight: 1, EndingHeight: 10, Pagination: pageReq, @@ -312,19 +298,18 @@ func TestGRPCValidatorSlashes(t *testing.T) { Slashes: slashes[2:], } }, - true, - "", + expPass: true, }, { - "request slashes with page limit 3 and count total", - func() { + name: "request slashes with page limit 3 and count total", + malleate: func() { pageReq := &query.PageRequest{ Limit: 3, CountTotal: true, } req = &types.QueryValidatorSlashesRequest{ - ValidatorAddress: valAddrs[0].String(), + ValidatorAddress: f.valAddr.String(), StartingHeight: 1, EndingHeight: 10, Pagination: pageReq, @@ -334,19 +319,18 @@ func TestGRPCValidatorSlashes(t *testing.T) { Slashes: slashes[:3], } }, - true, - "", + expPass: true, }, { - "request slashes with page limit 4 and count total", - func() { + name: "request slashes with page limit 4 and count total", + malleate: func() { pageReq := &query.PageRequest{ Limit: 4, CountTotal: true, } req = &types.QueryValidatorSlashesRequest{ - ValidatorAddress: valAddrs[0].String(), + ValidatorAddress: f.valAddr.String(), StartingHeight: 1, EndingHeight: 10, Pagination: pageReq, @@ -356,356 +340,249 @@ func TestGRPCValidatorSlashes(t *testing.T) { Slashes: slashes[:4], } }, - true, - "", + expPass: true, }, } for _, testCase := range testCases { - t.Run(fmt.Sprintf("Case %s", testCase.msg), func(t *testing.T) { - testCase.malleate() + tc := testCase + t.Run(fmt.Sprintf("Case %s", tc.name), func(t *testing.T) { + tc.malleate() - slashesRes, err := queryClient.ValidatorSlashes(gocontext.Background(), req) + slashesRes, err := queryClient.ValidatorSlashes(f.sdkCtx, req) - if testCase.expPass { + if tc.expPass { assert.NilError(t, err) assert.DeepEqual(t, expRes.GetSlashes(), slashesRes.GetSlashes()) } else { - assert.ErrorContains(t, err, testCase.expErrMsg) + assert.ErrorContains(t, err, tc.expErrMsg) assert.Assert(t, slashesRes == nil) } }) } } -func TestGRPCDelegationRewards(t *testing.T) { +func TestGRPCDelegatorWithdrawAddress(t *testing.T) { t.Parallel() f := initFixture(t) - ctx, addrs, valAddrs := f.ctx, f.addrs, f.valAddrs - - tstaking := stakingtestutil.NewHelper(t, ctx, f.stakingKeeper) - tstaking.Commission = stakingtypes.NewCommissionRates(sdk.NewDecWithPrec(5, 1), sdk.NewDecWithPrec(5, 1), math.LegacyNewDec(0)) - tstaking.CreateValidator(valAddrs[0], valConsPk0, sdk.NewInt(100), true) - - staking.EndBlocker(ctx, f.stakingKeeper) - ctx = ctx.WithBlockHeight(ctx.BlockHeight() + 1) + f.distrKeeper.SetParams(f.sdkCtx, types.DefaultParams()) - queryHelper := baseapp.NewQueryServerTestHelper(ctx, f.interfaceRegistry) - types.RegisterQueryServer(queryHelper, keeper.NewQuerier(f.distrKeeper)) - queryClient := types.NewQueryClient(queryHelper) + qr := f.app.QueryHelper() + queryClient := types.NewQueryClient(qr) - val := f.stakingKeeper.Validator(ctx, valAddrs[0]) + addr2 := sdk.AccAddress(PKS[1].Address()) - initial := int64(10) - tokens := sdk.DecCoins{{Denom: sdk.DefaultBondDenom, Amount: math.LegacyNewDec(initial)}} - f.distrKeeper.AllocateTokensToValidator(ctx, val, tokens) - - // test command delegation rewards grpc - var ( - req *types.QueryDelegationRewardsRequest - expRes *types.QueryDelegationRewardsResponse - ) + err := f.distrKeeper.SetWithdrawAddr(f.sdkCtx, f.addr, addr2) + assert.Assert(t, err == nil) testCases := []struct { - msg string - malleate func() + name string + msg *types.QueryDelegatorWithdrawAddressRequest expPass bool expErrMsg string }{ { - "empty request", - func() { - req = &types.QueryDelegationRewardsRequest{} - }, - false, - "empty delegator address", - }, - { - "empty delegator request", - func() { - req = &types.QueryDelegationRewardsRequest{ - DelegatorAddress: "", - ValidatorAddress: valAddrs[0].String(), - } - }, - false, - "empty delegator address", - }, - { - "empty validator request", - func() { - req = &types.QueryDelegationRewardsRequest{ - DelegatorAddress: addrs[1].String(), - ValidatorAddress: "", - } - }, - false, - "empty validator address", - }, - { - "request with wrong delegator and validator", - func() { - req = &types.QueryDelegationRewardsRequest{ - DelegatorAddress: addrs[1].String(), - ValidatorAddress: valAddrs[1].String(), - } - }, - false, - "validator does not exist", + name: "empty request", + msg: &types.QueryDelegatorWithdrawAddressRequest{}, + expPass: false, + expErrMsg: "empty delegator address", }, { - "valid request", - func() { - req = &types.QueryDelegationRewardsRequest{ - DelegatorAddress: addrs[0].String(), - ValidatorAddress: valAddrs[0].String(), - } - - expRes = &types.QueryDelegationRewardsResponse{ - Rewards: sdk.DecCoins{{Denom: sdk.DefaultBondDenom, Amount: math.LegacyNewDec(initial / 2)}}, - } - }, - true, - "", + name: "valid request", + msg: &types.QueryDelegatorWithdrawAddressRequest{DelegatorAddress: f.addr.String()}, + expPass: true, }, } for _, testCase := range testCases { - t.Run(fmt.Sprintf("Case %s", testCase.msg), func(t *testing.T) { - testCase.malleate() + tc := testCase + t.Run(fmt.Sprintf("Case %s", tc.name), func(t *testing.T) { + withdrawAddress, err := queryClient.DelegatorWithdrawAddress(f.sdkCtx, tc.msg) - rewards, err := queryClient.DelegationRewards(gocontext.Background(), req) - - if testCase.expPass { + if tc.expPass { assert.NilError(t, err) - assert.DeepEqual(t, expRes, rewards) + assert.Equal(t, withdrawAddress.WithdrawAddress, addr2.String()) } else { - assert.ErrorContains(t, err, testCase.expErrMsg) - assert.Assert(t, rewards == nil) + assert.ErrorContains(t, err, tc.expErrMsg) + assert.Assert(t, withdrawAddress == nil) } }) } +} - // test command delegator total rewards grpc - var ( - totalRewardsReq *types.QueryDelegationTotalRewardsRequest - expTotalRewardsRes *types.QueryDelegationTotalRewardsResponse - ) - - testCases = []struct { - msg string - malleate func() - expPass bool - expErrMsg string - }{ - { - "empty request", - func() { - totalRewardsReq = &types.QueryDelegationTotalRewardsRequest{} - }, - false, - "empty delegator address", - }, - { - "valid total delegation rewards", - func() { - totalRewardsReq = &types.QueryDelegationTotalRewardsRequest{ - DelegatorAddress: addrs[0].String(), - } - - expectedDelReward := types.NewDelegationDelegatorReward(valAddrs[0], - sdk.DecCoins{sdk.NewInt64DecCoin("stake", 5)}) - - expTotalRewardsRes = &types.QueryDelegationTotalRewardsResponse{ - Rewards: []types.DelegationDelegatorReward{expectedDelReward}, - Total: expectedDelReward.Reward, - } - }, - true, - "", - }, - } - - for _, testCase := range testCases { - t.Run(fmt.Sprintf("Case %s", testCase.msg), func(t *testing.T) { - testCase.malleate() +func TestGRPCCommunityPool(t *testing.T) { + t.Parallel() + f := initFixture(t) - totalRewardsRes, err := queryClient.DelegationTotalRewards(gocontext.Background(), totalRewardsReq) + f.distrKeeper.SetFeePool(f.sdkCtx, types.FeePool{ + CommunityPool: sdk.NewDecCoins(sdk.DecCoin{Denom: sdk.DefaultBondDenom, Amount: math.LegacyNewDec(0)}), + }) - if testCase.expPass { - assert.NilError(t, err) - assert.DeepEqual(t, totalRewardsRes, expTotalRewardsRes) - } else { - assert.ErrorContains(t, err, testCase.expErrMsg) - assert.Assert(t, totalRewardsRes == nil) - } - }) - } + qr := f.app.QueryHelper() + queryClient := types.NewQueryClient(qr) - // test command validator delegators grpc var ( - delegatorValidatorsReq *types.QueryDelegatorValidatorsRequest - expDelegatorValidatorsRes *types.QueryDelegatorValidatorsResponse + req *types.QueryCommunityPoolRequest + expPool *types.QueryCommunityPoolResponse ) - testCases = []struct { - msg string - malleate func() - expPass bool - expErrMsg string + testCases := []struct { + name string + malleate func() }{ { - "empty request", - func() { - delegatorValidatorsReq = &types.QueryDelegatorValidatorsRequest{} + name: "valid request empty community pool", + malleate: func() { + req = &types.QueryCommunityPoolRequest{} + expPool = &types.QueryCommunityPoolResponse{} }, - false, - "empty delegator address", }, { - "request no delegations address", - func() { - delegatorValidatorsReq = &types.QueryDelegatorValidatorsRequest{ - DelegatorAddress: addrs[1].String(), - } + name: "valid request", + malleate: func() { + amount := sdk.NewCoins(sdk.NewInt64Coin(sdk.DefaultBondDenom, 100)) + assert.NilError(t, f.bankKeeper.MintCoins(f.sdkCtx, types.ModuleName, amount)) + assert.NilError(t, f.bankKeeper.SendCoinsFromModuleToAccount(f.sdkCtx, types.ModuleName, f.addr, amount)) - expDelegatorValidatorsRes = &types.QueryDelegatorValidatorsResponse{} - }, - true, - "", - }, - { - "valid request", - func() { - delegatorValidatorsReq = &types.QueryDelegatorValidatorsRequest{ - DelegatorAddress: addrs[0].String(), - } - expDelegatorValidatorsRes = &types.QueryDelegatorValidatorsResponse{ - Validators: []string{valAddrs[0].String()}, - } + err := f.distrKeeper.FundCommunityPool(f.sdkCtx, amount, f.addr) + assert.Assert(t, err == nil) + req = &types.QueryCommunityPoolRequest{} + + expPool = &types.QueryCommunityPoolResponse{Pool: sdk.NewDecCoinsFromCoins(amount...)} }, - true, - "", }, } for _, testCase := range testCases { - t.Run(fmt.Sprintf("Case %s", testCase.msg), func(t *testing.T) { + tc := testCase + t.Run(fmt.Sprintf("Case %s", tc.name), func(t *testing.T) { testCase.malleate() - validators, err := queryClient.DelegatorValidators(gocontext.Background(), delegatorValidatorsReq) + pool, err := queryClient.CommunityPool(f.sdkCtx, req) - if testCase.expPass { - assert.NilError(t, err) - assert.DeepEqual(t, expDelegatorValidatorsRes, validators) - } else { - assert.ErrorContains(t, err, testCase.expErrMsg) - assert.Assert(t, validators == nil) - } + assert.NilError(t, err) + assert.DeepEqual(t, expPool, pool) }) } } -func TestGRPCDelegatorWithdrawAddress(t *testing.T) { +func TestGRPCDelegationRewards(t *testing.T) { t.Parallel() f := initFixture(t) - ctx, queryClient, addrs := f.ctx, f.queryClient, f.addrs + f.distrKeeper.SetFeePool(f.sdkCtx, types.FeePool{ + CommunityPool: sdk.NewDecCoins(sdk.DecCoin{Denom: sdk.DefaultBondDenom, Amount: math.LegacyNewDec(1000)}), + }) - err := f.distrKeeper.SetWithdrawAddr(ctx, addrs[0], addrs[1]) - assert.Assert(t, err == nil) + // set module account coins + initTokens := f.stakingKeeper.TokensFromConsensusPower(f.sdkCtx, int64(1000)) + f.bankKeeper.MintCoins(f.sdkCtx, types.ModuleName, sdk.NewCoins(sdk.NewCoin(sdk.DefaultBondDenom, initTokens))) + + // Set default staking params + f.stakingKeeper.SetParams(f.sdkCtx, stakingtypes.DefaultParams()) + + qr := f.app.QueryHelper() + queryClient := types.NewQueryClient(qr) - var req *types.QueryDelegatorWithdrawAddressRequest + addr2 := sdk.AccAddress(PKS[1].Address()) + valAddr2 := sdk.ValAddress(addr2) + delAddr := sdk.AccAddress(PKS[2].Address()) + + // send funds to val addr + funds := f.stakingKeeper.TokensFromConsensusPower(f.sdkCtx, int64(1000)) + f.bankKeeper.SendCoinsFromModuleToAccount(f.sdkCtx, types.ModuleName, sdk.AccAddress(f.valAddr), sdk.NewCoins(sdk.NewCoin(sdk.DefaultBondDenom, funds))) + + initialStake := int64(10) + tstaking := stakingtestutil.NewHelper(t, f.sdkCtx, f.stakingKeeper) + tstaking.Commission = stakingtypes.NewCommissionRates(sdk.NewDecWithPrec(5, 1), sdk.NewDecWithPrec(5, 1), math.LegacyNewDec(0)) + tstaking.CreateValidator(f.valAddr, valConsPk0, sdk.NewInt(initialStake), true) + + val, found := f.stakingKeeper.GetValidator(f.sdkCtx, f.valAddr) + assert.Assert(t, found) + + // setup delegation + delTokens := sdk.TokensFromConsensusPower(2, sdk.DefaultPowerReduction) + validator, issuedShares := val.AddTokensFromDel(delTokens) + delegation := stakingtypes.NewDelegation(delAddr, f.valAddr, issuedShares) + f.stakingKeeper.SetDelegation(f.sdkCtx, delegation) + f.distrKeeper.SetDelegatorStartingInfo(f.sdkCtx, validator.GetOperator(), delAddr, types.NewDelegatorStartingInfo(2, math.LegacyNewDec(initialStake), 20)) + + // setup validator rewards + decCoins := sdk.DecCoins{sdk.NewDecCoinFromDec(sdk.DefaultBondDenom, math.LegacyOneDec())} + historicalRewards := types.NewValidatorHistoricalRewards(decCoins, 2) + f.distrKeeper.SetValidatorHistoricalRewards(f.sdkCtx, validator.GetOperator(), 2, historicalRewards) + // setup current rewards and outstanding rewards + currentRewards := types.NewValidatorCurrentRewards(decCoins, 3) + f.distrKeeper.SetValidatorCurrentRewards(f.sdkCtx, f.valAddr, currentRewards) + f.distrKeeper.SetValidatorOutstandingRewards(f.sdkCtx, f.valAddr, types.ValidatorOutstandingRewards{Rewards: decCoins}) + + expRes := &types.QueryDelegationRewardsResponse{ + Rewards: sdk.DecCoins{{Denom: sdk.DefaultBondDenom, Amount: math.LegacyNewDec(initialStake / 10)}}, + } + // test command delegation rewards grpc testCases := []struct { - msg string - malleate func() + name string + msg *types.QueryDelegationRewardsRequest expPass bool expErrMsg string }{ { - "empty request", - func() { - req = &types.QueryDelegatorWithdrawAddressRequest{} + name: "empty request", + msg: &types.QueryDelegationRewardsRequest{}, + expPass: false, + expErrMsg: "empty delegator address", + }, + { + name: "empty delegator address", + msg: &types.QueryDelegationRewardsRequest{ + DelegatorAddress: "", + ValidatorAddress: f.valAddr.String(), }, - false, - "empty delegator address", + expPass: false, + expErrMsg: "empty delegator address", }, { - "valid request", - func() { - req = &types.QueryDelegatorWithdrawAddressRequest{DelegatorAddress: addrs[0].String()} + name: "empty validator address", + msg: &types.QueryDelegationRewardsRequest{ + DelegatorAddress: addr2.String(), + ValidatorAddress: "", }, - true, - "", + expPass: false, + expErrMsg: "empty validator address", }, - } - - for _, testCase := range testCases { - t.Run(fmt.Sprintf("Case %s", testCase.msg), func(t *testing.T) { - testCase.malleate() - - withdrawAddress, err := queryClient.DelegatorWithdrawAddress(gocontext.Background(), req) - - if testCase.expPass { - assert.NilError(t, err) - assert.Equal(t, withdrawAddress.WithdrawAddress, addrs[1].String()) - } else { - assert.ErrorContains(t, err, testCase.expErrMsg) - assert.Assert(t, withdrawAddress == nil) - } - }) - } -} - -func TestGRPCCommunityPool(t *testing.T) { - t.Parallel() - f := initFixture(t) - - ctx, queryClient, addrs := f.ctx, f.queryClient, f.addrs - // reset fee pool - f.distrKeeper.SetFeePool(ctx, types.InitialFeePool()) - - var ( - req *types.QueryCommunityPoolRequest - expPool *types.QueryCommunityPoolResponse - ) - - testCases := []struct { - msg string - malleate func() - }{ { - "valid request empty community pool", - func() { - req = &types.QueryCommunityPoolRequest{} - expPool = &types.QueryCommunityPoolResponse{} + name: "request with wrong delegator and validator", + msg: &types.QueryDelegationRewardsRequest{ + DelegatorAddress: addr2.String(), + ValidatorAddress: valAddr2.String(), }, + expPass: false, + expErrMsg: "validator does not exist", }, { - "valid request", - func() { - amount := sdk.NewCoins(sdk.NewInt64Coin("stake", 100)) - assert.NilError(t, banktestutil.FundAccount(f.bankKeeper, ctx, addrs[0], amount)) - - err := f.distrKeeper.FundCommunityPool(ctx, amount, addrs[0]) - assert.Assert(t, err == nil) - req = &types.QueryCommunityPoolRequest{} - - expPool = &types.QueryCommunityPoolResponse{Pool: sdk.NewDecCoinsFromCoins(amount...)} + name: "valid request", + msg: &types.QueryDelegationRewardsRequest{ + DelegatorAddress: delAddr.String(), + ValidatorAddress: f.valAddr.String(), }, + expPass: true, }, } for _, testCase := range testCases { - t.Run(fmt.Sprintf("Case %s", testCase.msg), func(t *testing.T) { - testCase.malleate() - - pool, err := queryClient.CommunityPool(gocontext.Background(), req) + tc := testCase + t.Run(fmt.Sprintf("Case %s", tc.name), func(t *testing.T) { + rewards, err := queryClient.DelegationRewards(f.sdkCtx, tc.msg) - assert.NilError(t, err) - assert.DeepEqual(t, expPool, pool) + if tc.expPass { + assert.NilError(t, err) + assert.DeepEqual(t, expRes, rewards) + } else { + assert.ErrorContains(t, err, tc.expErrMsg) + assert.Assert(t, rewards == nil) + } }) } } diff --git a/tests/integration/distribution/keeper/keeper_test.go b/tests/integration/distribution/keeper/keeper_test.go deleted file mode 100644 index 3db593890a30..000000000000 --- a/tests/integration/distribution/keeper/keeper_test.go +++ /dev/null @@ -1,185 +0,0 @@ -package keeper_test - -import ( - "fmt" - "testing" - - "cosmossdk.io/math" - cmtproto "github.com/cometbft/cometbft/proto/tendermint/types" - "gotest.tools/v3/assert" - - simtestutil "github.com/cosmos/cosmos-sdk/testutil/sims" - sdk "github.com/cosmos/cosmos-sdk/types" - authkeeper "github.com/cosmos/cosmos-sdk/x/auth/keeper" - bankkeeper "github.com/cosmos/cosmos-sdk/x/bank/keeper" - banktestutil "github.com/cosmos/cosmos-sdk/x/bank/testutil" - "github.com/cosmos/cosmos-sdk/x/distribution/keeper" - "github.com/cosmos/cosmos-sdk/x/distribution/testutil" - "github.com/cosmos/cosmos-sdk/x/distribution/types" - stakingkeeper "github.com/cosmos/cosmos-sdk/x/staking/keeper" -) - -func TestSetWithdrawAddr(t *testing.T) { - var ( - bankKeeper bankkeeper.Keeper - distrKeeper keeper.Keeper - stakingKeeper *stakingkeeper.Keeper - ) - - app, err := simtestutil.Setup(testutil.AppConfig, - &bankKeeper, - &distrKeeper, - &stakingKeeper, - ) - assert.NilError(t, err) - - ctx := app.BaseApp.NewContext(false, cmtproto.Header{}) - - addr := simtestutil.AddTestAddrs(bankKeeper, stakingKeeper, ctx, 2, sdk.NewInt(1000000000)) - - params := distrKeeper.GetParams(ctx) - params.WithdrawAddrEnabled = false - assert.NilError(t, distrKeeper.SetParams(ctx, params)) - - err = distrKeeper.SetWithdrawAddr(ctx, addr[0], addr[1]) - assert.Assert(t, err != nil) - - params.WithdrawAddrEnabled = true - assert.NilError(t, distrKeeper.SetParams(ctx, params)) - - err = distrKeeper.SetWithdrawAddr(ctx, addr[0], addr[1]) - assert.NilError(t, err) - - assert.ErrorContains(t, distrKeeper.SetWithdrawAddr(ctx, addr[0], distrAcc.GetAddress()), fmt.Sprintf("%s is not allowed to receive external funds: unauthorized", distrAcc.GetAddress())) -} - -func TestWithdrawValidatorCommission(t *testing.T) { - var ( - accountKeeper authkeeper.AccountKeeper - bankKeeper bankkeeper.Keeper - distrKeeper keeper.Keeper - stakingKeeper *stakingkeeper.Keeper - ) - - app, err := simtestutil.Setup(testutil.AppConfig, - &accountKeeper, - &bankKeeper, - &distrKeeper, - &stakingKeeper, - ) - assert.NilError(t, err) - - ctx := app.BaseApp.NewContext(false, cmtproto.Header{}) - - valCommission := sdk.DecCoins{ - sdk.NewDecCoinFromDec("mytoken", math.LegacyNewDec(5).Quo(math.LegacyNewDec(4))), - sdk.NewDecCoinFromDec("stake", math.LegacyNewDec(3).Quo(math.LegacyNewDec(2))), - } - - addr := simtestutil.AddTestAddrs(bankKeeper, stakingKeeper, ctx, 1, sdk.NewInt(1000000000)) - valAddrs := simtestutil.ConvertAddrsToValAddrs(addr) - - // set module account coins - distrAcc := distrKeeper.GetDistributionAccount(ctx) - coins := sdk.NewCoins(sdk.NewCoin("mytoken", sdk.NewInt(2)), sdk.NewCoin("stake", sdk.NewInt(2))) - assert.NilError(t, banktestutil.FundModuleAccount(bankKeeper, ctx, distrAcc.GetName(), coins)) - - accountKeeper.SetModuleAccount(ctx, distrAcc) - - // check initial balance - balance := bankKeeper.GetAllBalances(ctx, sdk.AccAddress(valAddrs[0])) - expTokens := stakingKeeper.TokensFromConsensusPower(ctx, 1000) - expCoins := sdk.NewCoins(sdk.NewCoin("stake", expTokens)) - assert.DeepEqual(t, expCoins, balance) - - // set outstanding rewards - distrKeeper.SetValidatorOutstandingRewards(ctx, valAddrs[0], types.ValidatorOutstandingRewards{Rewards: valCommission}) - - // set commission - distrKeeper.SetValidatorAccumulatedCommission(ctx, valAddrs[0], types.ValidatorAccumulatedCommission{Commission: valCommission}) - - // withdraw commission - _, err = distrKeeper.WithdrawValidatorCommission(ctx, valAddrs[0]) - assert.NilError(t, err) - - // check balance increase - balance = bankKeeper.GetAllBalances(ctx, sdk.AccAddress(valAddrs[0])) - assert.DeepEqual(t, sdk.NewCoins( - sdk.NewCoin("mytoken", sdk.NewInt(1)), - sdk.NewCoin("stake", expTokens.AddRaw(1)), - ), balance) - - // check remainder - remainder := distrKeeper.GetValidatorAccumulatedCommission(ctx, valAddrs[0]).Commission - assert.DeepEqual(t, sdk.DecCoins{ - sdk.NewDecCoinFromDec("mytoken", math.LegacyNewDec(1).Quo(math.LegacyNewDec(4))), - sdk.NewDecCoinFromDec("stake", math.LegacyNewDec(1).Quo(math.LegacyNewDec(2))), - }, remainder) -} - -func TestGetTotalRewards(t *testing.T) { - var ( - bankKeeper bankkeeper.Keeper - distrKeeper keeper.Keeper - stakingKeeper *stakingkeeper.Keeper - ) - - app, err := simtestutil.Setup(testutil.AppConfig, - &bankKeeper, - &distrKeeper, - &stakingKeeper, - ) - assert.NilError(t, err) - - ctx := app.BaseApp.NewContext(false, cmtproto.Header{}) - - valCommission := sdk.DecCoins{ - sdk.NewDecCoinFromDec("mytoken", math.LegacyNewDec(5).Quo(math.LegacyNewDec(4))), - sdk.NewDecCoinFromDec("stake", math.LegacyNewDec(3).Quo(math.LegacyNewDec(2))), - } - - addr := simtestutil.AddTestAddrs(bankKeeper, stakingKeeper, ctx, 2, sdk.NewInt(1000000000)) - valAddrs := simtestutil.ConvertAddrsToValAddrs(addr) - - distrKeeper.SetValidatorOutstandingRewards(ctx, valAddrs[0], types.ValidatorOutstandingRewards{Rewards: valCommission}) - distrKeeper.SetValidatorOutstandingRewards(ctx, valAddrs[1], types.ValidatorOutstandingRewards{Rewards: valCommission}) - - expectedRewards := valCommission.MulDec(math.LegacyNewDec(2)) - totalRewards := distrKeeper.GetTotalRewards(ctx) - - assert.DeepEqual(t, expectedRewards, totalRewards) -} - -func TestFundCommunityPool(t *testing.T) { - var ( - bankKeeper bankkeeper.Keeper - distrKeeper keeper.Keeper - stakingKeeper *stakingkeeper.Keeper - ) - - app, err := simtestutil.Setup(testutil.AppConfig, - &bankKeeper, - &distrKeeper, - &stakingKeeper, - ) - assert.NilError(t, err) - - ctx := app.BaseApp.NewContext(false, cmtproto.Header{}) - - // reset fee pool - distrKeeper.SetFeePool(ctx, types.InitialFeePool()) - - addr := simtestutil.AddTestAddrs(bankKeeper, stakingKeeper, ctx, 2, math.ZeroInt()) - - amount := sdk.NewCoins(sdk.NewInt64Coin("stake", 100)) - assert.NilError(t, banktestutil.FundAccount(bankKeeper, ctx, addr[0], amount)) - - initPool := distrKeeper.GetFeePool(ctx) - assert.Assert(t, initPool.CommunityPool.Empty()) - - err = distrKeeper.FundCommunityPool(ctx, amount, addr[0]) - assert.NilError(t, err) - - assert.DeepEqual(t, initPool.CommunityPool.Add(sdk.NewDecCoinsFromCoins(amount...)...), distrKeeper.GetFeePool(ctx).CommunityPool) - assert.Assert(t, bankKeeper.GetAllBalances(ctx, addr[0]).Empty()) -} diff --git a/tests/integration/distribution/keeper/msg_server_test.go b/tests/integration/distribution/keeper/msg_server_test.go index 4d0411ed00ce..65bd57837ba5 100644 --- a/tests/integration/distribution/keeper/msg_server_test.go +++ b/tests/integration/distribution/keeper/msg_server_test.go @@ -1,18 +1,635 @@ package keeper_test import ( + "fmt" "testing" + "cosmossdk.io/log" "cosmossdk.io/math" + storetypes "cosmossdk.io/store/types" + + cmtabcitypes "github.com/cometbft/cometbft/abci/types" + "github.com/cometbft/cometbft/proto/tendermint/types" + "github.com/stretchr/testify/require" "gotest.tools/v3/assert" + "github.com/cosmos/cosmos-sdk/codec" + "github.com/cosmos/cosmos-sdk/runtime" + "github.com/cosmos/cosmos-sdk/testutil/integration" sdk "github.com/cosmos/cosmos-sdk/types" - "github.com/cosmos/cosmos-sdk/x/distribution/types" - minttypes "github.com/cosmos/cosmos-sdk/x/mint/types" + moduletestutil "github.com/cosmos/cosmos-sdk/types/module/testutil" + "github.com/cosmos/cosmos-sdk/x/auth" + authkeeper "github.com/cosmos/cosmos-sdk/x/auth/keeper" + authsims "github.com/cosmos/cosmos-sdk/x/auth/simulation" + authtypes "github.com/cosmos/cosmos-sdk/x/auth/types" + "github.com/cosmos/cosmos-sdk/x/bank" + bankkeeper "github.com/cosmos/cosmos-sdk/x/bank/keeper" + banktypes "github.com/cosmos/cosmos-sdk/x/bank/types" + "github.com/cosmos/cosmos-sdk/x/distribution" + distrkeeper "github.com/cosmos/cosmos-sdk/x/distribution/keeper" + distrtypes "github.com/cosmos/cosmos-sdk/x/distribution/types" + "github.com/cosmos/cosmos-sdk/x/staking" + stakingkeeper "github.com/cosmos/cosmos-sdk/x/staking/keeper" stakingtestutil "github.com/cosmos/cosmos-sdk/x/staking/testutil" stakingtypes "github.com/cosmos/cosmos-sdk/x/staking/types" ) +var ( + emptyDelAddr sdk.AccAddress + emptyValAddr sdk.ValAddress +) + +type fixture struct { + app *integration.App + + sdkCtx sdk.Context + cdc codec.Codec + keys map[string]*storetypes.KVStoreKey + + accountKeeper authkeeper.AccountKeeper + bankKeeper bankkeeper.Keeper + distrKeeper distrkeeper.Keeper + stakingKeeper *stakingkeeper.Keeper + + addr sdk.AccAddress + valAddr sdk.ValAddress +} + +func initFixture(t testing.TB) *fixture { + keys := storetypes.NewKVStoreKeys( + authtypes.StoreKey, banktypes.StoreKey, distrtypes.StoreKey, stakingtypes.StoreKey, + ) + cdc := moduletestutil.MakeTestEncodingConfig(auth.AppModuleBasic{}, distribution.AppModuleBasic{}).Codec + + logger := log.NewTestLogger(t) + cms := integration.CreateMultiStore(keys, logger) + + newCtx := sdk.NewContext(cms, types.Header{}, true, logger) + + authority := authtypes.NewModuleAddress("gov") + + maccPerms := map[string][]string{ + distrtypes.ModuleName: {authtypes.Minter}, + stakingtypes.BondedPoolName: {authtypes.Burner, authtypes.Staking}, + stakingtypes.NotBondedPoolName: {authtypes.Burner, authtypes.Staking}, + } + + accountKeeper := authkeeper.NewAccountKeeper( + cdc, + runtime.NewKVStoreService(keys[authtypes.StoreKey]), + authtypes.ProtoBaseAccount, + maccPerms, + sdk.Bech32MainPrefix, + authority.String(), + ) + + blockedAddresses := map[string]bool{ + accountKeeper.GetAuthority(): false, + } + bankKeeper := bankkeeper.NewBaseKeeper( + cdc, + keys[banktypes.StoreKey], + accountKeeper, + blockedAddresses, + authority.String(), + ) + + stakingKeeper := stakingkeeper.NewKeeper(cdc, keys[stakingtypes.StoreKey], accountKeeper, bankKeeper, authority.String()) + + distrKeeper := distrkeeper.NewKeeper( + cdc, keys[distrtypes.StoreKey], accountKeeper, bankKeeper, stakingKeeper, distrtypes.ModuleName, authority.String(), + ) + + authModule := auth.NewAppModule(cdc, accountKeeper, authsims.RandomGenesisAccounts, nil) + bankModule := bank.NewAppModule(cdc, bankKeeper, accountKeeper, nil) + stakingModule := staking.NewAppModule(cdc, stakingKeeper, accountKeeper, bankKeeper, nil) + distrModule := distribution.NewAppModule(cdc, distrKeeper, accountKeeper, bankKeeper, stakingKeeper, nil) + + addr := sdk.AccAddress(PKS[0].Address()) + valAddr := sdk.ValAddress(addr) + valConsAddr := sdk.ConsAddress(valConsPk0.Address()) + + // set proposer and vote infos + ctx := newCtx.WithProposer(valConsAddr).WithVoteInfos([]cmtabcitypes.VoteInfo{ + { + Validator: cmtabcitypes.Validator{ + Address: valAddr, + Power: 100, + }, + SignedLastBlock: true, + }, + }) + + integrationApp := integration.NewIntegrationApp(ctx, logger, keys, cdc, authModule, bankModule, stakingModule, distrModule) + + sdkCtx := sdk.UnwrapSDKContext(integrationApp.Context()) + + // Register MsgServer and QueryServer + distrtypes.RegisterMsgServer(integrationApp.MsgServiceRouter(), distrkeeper.NewMsgServerImpl(distrKeeper)) + distrtypes.RegisterQueryServer(integrationApp.QueryHelper(), distrkeeper.NewQuerier(distrKeeper)) + + return &fixture{ + app: integrationApp, + sdkCtx: sdkCtx, + cdc: cdc, + keys: keys, + accountKeeper: accountKeeper, + bankKeeper: bankKeeper, + distrKeeper: distrKeeper, + stakingKeeper: stakingKeeper, + addr: addr, + valAddr: valAddr, + } +} + +func TestMsgWithdrawDelegatorReward(t *testing.T) { + t.Parallel() + f := initFixture(t) + + f.distrKeeper.SetFeePool(f.sdkCtx, distrtypes.FeePool{ + CommunityPool: sdk.NewDecCoins(sdk.DecCoin{Denom: "stake", Amount: math.LegacyNewDec(10000)}), + }) + f.distrKeeper.SetParams(f.sdkCtx, distrtypes.DefaultParams()) + initFeePool := f.distrKeeper.GetFeePool(f.sdkCtx) + + delAddr := sdk.AccAddress(PKS[1].Address()) + valConsAddr := sdk.ConsAddress(valConsPk0.Address()) + + valCommission := sdk.DecCoins{ + sdk.NewDecCoinFromDec("mytoken", math.LegacyNewDec(5).Quo(math.LegacyNewDec(4))), + sdk.NewDecCoinFromDec("stake", math.LegacyNewDec(3).Quo(math.LegacyNewDec(2))), + } + + // setup staking validator + validator, err := stakingtypes.NewValidator(f.valAddr, PKS[0], stakingtypes.Description{}) + assert.NilError(t, err) + commission := stakingtypes.NewCommission(math.LegacyZeroDec(), math.LegacyOneDec(), math.LegacyOneDec()) + validator, err = validator.SetInitialCommission(commission) + assert.NilError(t, err) + validator.DelegatorShares = math.LegacyNewDec(100) + validator.Tokens = sdk.NewInt(1000000) + f.stakingKeeper.SetValidator(f.sdkCtx, validator) + + // set module account coins + initTokens := f.stakingKeeper.TokensFromConsensusPower(f.sdkCtx, int64(1000)) + f.bankKeeper.MintCoins(f.sdkCtx, distrtypes.ModuleName, sdk.NewCoins(sdk.NewCoin(sdk.DefaultBondDenom, initTokens))) + + // send funds to val addr + f.bankKeeper.SendCoinsFromModuleToAccount(f.sdkCtx, distrtypes.ModuleName, sdk.AccAddress(f.valAddr), sdk.NewCoins(sdk.NewCoin(sdk.DefaultBondDenom, initTokens))) + + initBalance := f.bankKeeper.GetAllBalances(f.sdkCtx, delAddr) + + // setup delegation + delTokens := sdk.TokensFromConsensusPower(2, sdk.DefaultPowerReduction) + validator, issuedShares := validator.AddTokensFromDel(delTokens) + delegation := stakingtypes.NewDelegation(delAddr, validator.GetOperator(), issuedShares) + f.stakingKeeper.SetDelegation(f.sdkCtx, delegation) + f.distrKeeper.SetDelegatorStartingInfo(f.sdkCtx, validator.GetOperator(), delAddr, distrtypes.NewDelegatorStartingInfo(2, math.LegacyOneDec(), 20)) + + // setup validator rewards + decCoins := sdk.DecCoins{sdk.NewDecCoinFromDec(sdk.DefaultBondDenom, math.LegacyOneDec())} + historicalRewards := distrtypes.NewValidatorHistoricalRewards(decCoins, 2) + f.distrKeeper.SetValidatorHistoricalRewards(f.sdkCtx, validator.GetOperator(), 2, historicalRewards) + // setup current rewards and outstanding rewards + currentRewards := distrtypes.NewValidatorCurrentRewards(decCoins, 3) + f.distrKeeper.SetValidatorCurrentRewards(f.sdkCtx, f.valAddr, currentRewards) + f.distrKeeper.SetValidatorOutstandingRewards(f.sdkCtx, f.valAddr, distrtypes.ValidatorOutstandingRewards{Rewards: valCommission}) + initOutstandingRewards := f.distrKeeper.GetValidatorOutstandingRewardsCoins(f.sdkCtx, f.valAddr) + + testCases := []struct { + name string + msg *distrtypes.MsgWithdrawDelegatorReward + expErr bool + expErrMsg string + }{ + { + name: "empty delegator address", + msg: &distrtypes.MsgWithdrawDelegatorReward{ + DelegatorAddress: emptyDelAddr.String(), + ValidatorAddress: f.valAddr.String(), + }, + expErr: true, + expErrMsg: "invalid delegator address", + }, + { + name: "empty validator address", + msg: &distrtypes.MsgWithdrawDelegatorReward{ + DelegatorAddress: delAddr.String(), + ValidatorAddress: emptyValAddr.String(), + }, + expErr: true, + expErrMsg: "invalid validator address", + }, + { + name: "both empty addresses", + msg: &distrtypes.MsgWithdrawDelegatorReward{ + DelegatorAddress: emptyDelAddr.String(), + ValidatorAddress: emptyValAddr.String(), + }, + expErr: true, + expErrMsg: "invalid validator address", + }, + { + name: "delegator with no delegations", + msg: &distrtypes.MsgWithdrawDelegatorReward{ + DelegatorAddress: sdk.AccAddress([]byte("invalid")).String(), + ValidatorAddress: f.valAddr.String(), + }, + expErr: true, + expErrMsg: "no delegation distribution info", + }, + { + name: "validator with no delegations", + msg: &distrtypes.MsgWithdrawDelegatorReward{ + DelegatorAddress: delAddr.String(), + ValidatorAddress: sdk.ValAddress(sdk.AccAddress(PKS[2].Address())).String(), + }, + expErr: true, + expErrMsg: "no validator distribution info", + }, + { + name: "valid msg", + msg: &distrtypes.MsgWithdrawDelegatorReward{ + DelegatorAddress: delAddr.String(), + ValidatorAddress: f.valAddr.String(), + }, + expErr: false, + }, + } + height := f.app.LastBlockHeight() + require.Panics(t, func() { + f.distrKeeper.GetPreviousProposerConsAddr(f.sdkCtx) + }) + for _, tc := range testCases { + tc := tc + t.Run(tc.name, func(t *testing.T) { + res, err := f.app.RunMsg( + tc.msg, + integration.WithAutomaticBeginEndBlock(), + integration.WithAutomaticCommit(), + ) + + height++ + if f.app.LastBlockHeight() != height { + panic(fmt.Errorf("expected block height to be %d, got %d", height, f.app.LastBlockHeight())) + } + + prevProposerConsAddr := f.distrKeeper.GetPreviousProposerConsAddr(f.sdkCtx) + assert.Assert(t, prevProposerConsAddr.Empty() == false) + assert.DeepEqual(t, prevProposerConsAddr, valConsAddr) + var previousTotalPower int64 + for _, voteInfo := range f.sdkCtx.VoteInfos() { + previousTotalPower += voteInfo.Validator.Power + } + assert.Equal(t, previousTotalPower, int64(100)) + + if tc.expErr { + assert.ErrorContains(t, err, tc.expErrMsg) + } else { + assert.NilError(t, err) + assert.Assert(t, res != nil) + + // check the result + result := distrtypes.MsgWithdrawDelegatorRewardResponse{} + err := f.cdc.Unmarshal(res.Value, &result) + assert.NilError(t, err) + + // check current balance is greater than initial balance + curBalance := f.bankKeeper.GetAllBalances(f.sdkCtx, sdk.AccAddress(f.valAddr)) + assert.Assert(t, initBalance.IsAllLTE(curBalance)) + + // check rewards + curFeePool := f.distrKeeper.GetFeePool(f.sdkCtx) + rewards := curFeePool.GetCommunityPool().Sub(initFeePool.CommunityPool) + curOutstandingRewards := f.distrKeeper.GetValidatorOutstandingRewards(f.sdkCtx, f.valAddr) + assert.DeepEqual(t, rewards, initOutstandingRewards.Sub(curOutstandingRewards.Rewards)) + } + }) + } +} + +func TestMsgSetWithdrawAddress(t *testing.T) { + t.Parallel() + f := initFixture(t) + + f.distrKeeper.SetParams(f.sdkCtx, distrtypes.DefaultParams()) + + delAddr := sdk.AccAddress(PKS[0].Address()) + withdrawAddr := sdk.AccAddress(PKS[1].Address()) + + testCases := []struct { + name string + preRun func() + msg *distrtypes.MsgSetWithdrawAddress + expErr bool + expErrMsg string + }{ + { + name: "empty delegator address", + preRun: func() { + params := f.distrKeeper.GetParams(f.sdkCtx) + params.WithdrawAddrEnabled = true + assert.NilError(t, f.distrKeeper.SetParams(f.sdkCtx, params)) + }, + msg: &distrtypes.MsgSetWithdrawAddress{ + DelegatorAddress: emptyDelAddr.String(), + WithdrawAddress: withdrawAddr.String(), + }, + expErr: true, + expErrMsg: "invalid delegator address", + }, + { + name: "empty withdraw address", + preRun: func() { + params := f.distrKeeper.GetParams(f.sdkCtx) + params.WithdrawAddrEnabled = true + assert.NilError(t, f.distrKeeper.SetParams(f.sdkCtx, params)) + }, + msg: &distrtypes.MsgSetWithdrawAddress{ + DelegatorAddress: delAddr.String(), + WithdrawAddress: emptyDelAddr.String(), + }, + expErr: true, + expErrMsg: "invalid withdraw address", + }, + { + name: "both empty addresses", + preRun: func() { + params := f.distrKeeper.GetParams(f.sdkCtx) + params.WithdrawAddrEnabled = true + assert.NilError(t, f.distrKeeper.SetParams(f.sdkCtx, params)) + }, + msg: &distrtypes.MsgSetWithdrawAddress{ + DelegatorAddress: emptyDelAddr.String(), + WithdrawAddress: emptyDelAddr.String(), + }, + expErr: true, + expErrMsg: "invalid delegator address", + }, + { + name: "withdraw address disabled", + preRun: func() { + params := f.distrKeeper.GetParams(f.sdkCtx) + params.WithdrawAddrEnabled = false + assert.NilError(t, f.distrKeeper.SetParams(f.sdkCtx, params)) + }, + msg: &distrtypes.MsgSetWithdrawAddress{ + DelegatorAddress: delAddr.String(), + WithdrawAddress: withdrawAddr.String(), + }, + expErr: true, + expErrMsg: "set withdraw address disabled", + }, + { + name: "valid msg with same delegator and withdraw address", + preRun: func() { + params := f.distrKeeper.GetParams(f.sdkCtx) + params.WithdrawAddrEnabled = true + assert.NilError(t, f.distrKeeper.SetParams(f.sdkCtx, params)) + }, + msg: &distrtypes.MsgSetWithdrawAddress{ + DelegatorAddress: delAddr.String(), + WithdrawAddress: delAddr.String(), + }, + expErr: false, + }, + { + name: "valid msg", + preRun: func() { + params := f.distrKeeper.GetParams(f.sdkCtx) + params.WithdrawAddrEnabled = true + assert.NilError(t, f.distrKeeper.SetParams(f.sdkCtx, params)) + }, + msg: &distrtypes.MsgSetWithdrawAddress{ + DelegatorAddress: delAddr.String(), + WithdrawAddress: withdrawAddr.String(), + }, + expErr: false, + }, + } + for _, tc := range testCases { + tc := tc + t.Run(tc.name, func(t *testing.T) { + tc.preRun() + res, err := f.app.RunMsg( + tc.msg, + integration.WithAutomaticBeginEndBlock(), + integration.WithAutomaticCommit(), + ) + if tc.expErr { + assert.ErrorContains(t, err, tc.expErrMsg) + + // query the delegator withdraw address + addr := f.distrKeeper.GetDelegatorWithdrawAddr(f.sdkCtx, delAddr) + assert.DeepEqual(t, addr, delAddr) + } else { + assert.NilError(t, err) + assert.Assert(t, res != nil) + + // check the result + result := distrtypes.MsgSetWithdrawAddressResponse{} + err = f.cdc.Unmarshal(res.Value, &result) + assert.NilError(t, err) + + // query the delegator withdraw address + addr := f.distrKeeper.GetDelegatorWithdrawAddr(f.sdkCtx, delAddr) + assert.DeepEqual(t, addr.String(), tc.msg.WithdrawAddress) + } + }) + } +} + +func TestMsgWithdrawValidatorCommission(t *testing.T) { + t.Parallel() + f := initFixture(t) + + valCommission := sdk.DecCoins{ + sdk.NewDecCoinFromDec("mytoken", math.LegacyNewDec(5).Quo(math.LegacyNewDec(4))), + sdk.NewDecCoinFromDec("stake", math.LegacyNewDec(3).Quo(math.LegacyNewDec(2))), + } + + // set module account coins + initTokens := f.stakingKeeper.TokensFromConsensusPower(f.sdkCtx, int64(1000)) + f.bankKeeper.MintCoins(f.sdkCtx, distrtypes.ModuleName, sdk.NewCoins(sdk.NewCoin(sdk.DefaultBondDenom, initTokens))) + + // send funds to val addr + f.bankKeeper.SendCoinsFromModuleToAccount(f.sdkCtx, distrtypes.ModuleName, sdk.AccAddress(f.valAddr), sdk.NewCoins(sdk.NewCoin(sdk.DefaultBondDenom, initTokens))) + + coins := sdk.NewCoins(sdk.NewCoin("mytoken", sdk.NewInt(2)), sdk.NewCoin("stake", sdk.NewInt(2))) + f.bankKeeper.MintCoins(f.sdkCtx, distrtypes.ModuleName, coins) + + // check initial balance + balance := f.bankKeeper.GetAllBalances(f.sdkCtx, sdk.AccAddress(f.valAddr)) + expTokens := f.stakingKeeper.TokensFromConsensusPower(f.sdkCtx, 1000) + expCoins := sdk.NewCoins(sdk.NewCoin("stake", expTokens)) + assert.DeepEqual(t, expCoins, balance) + + // set outstanding rewards + f.distrKeeper.SetValidatorOutstandingRewards(f.sdkCtx, f.valAddr, distrtypes.ValidatorOutstandingRewards{Rewards: valCommission}) + + // set commission + f.distrKeeper.SetValidatorAccumulatedCommission(f.sdkCtx, f.valAddr, distrtypes.ValidatorAccumulatedCommission{Commission: valCommission}) + + testCases := []struct { + name string + msg *distrtypes.MsgWithdrawValidatorCommission + expErr bool + expErrMsg string + }{ + { + name: "empty validator address", + msg: &distrtypes.MsgWithdrawValidatorCommission{ + ValidatorAddress: emptyValAddr.String(), + }, + expErr: true, + expErrMsg: "invalid validator address", + }, + { + name: "validator with no commission", + msg: &distrtypes.MsgWithdrawValidatorCommission{ + ValidatorAddress: sdk.ValAddress([]byte("addr1_______________")).String(), + }, + expErr: true, + expErrMsg: "no validator commission to withdraw", + }, + { + name: "valid msg", + msg: &distrtypes.MsgWithdrawValidatorCommission{ + ValidatorAddress: f.valAddr.String(), + }, + expErr: false, + }, + } + + for _, tc := range testCases { + tc := tc + t.Run(tc.name, func(t *testing.T) { + res, err := f.app.RunMsg( + tc.msg, + integration.WithAutomaticBeginEndBlock(), + integration.WithAutomaticCommit(), + ) + if tc.expErr { + assert.ErrorContains(t, err, tc.expErrMsg) + } else { + assert.NilError(t, err) + assert.Assert(t, res != nil) + + // check the result + result := distrtypes.MsgWithdrawValidatorCommissionResponse{} + err = f.cdc.Unmarshal(res.Value, &result) + assert.NilError(t, err) + + // check balance increase + balance = f.bankKeeper.GetAllBalances(f.sdkCtx, sdk.AccAddress(f.valAddr)) + assert.DeepEqual(t, sdk.NewCoins( + sdk.NewCoin("mytoken", sdk.NewInt(1)), + sdk.NewCoin("stake", expTokens.AddRaw(1)), + ), balance) + + // check remainder + remainder := f.distrKeeper.GetValidatorAccumulatedCommission(f.sdkCtx, f.valAddr).Commission + assert.DeepEqual(t, sdk.DecCoins{ + sdk.NewDecCoinFromDec("mytoken", math.LegacyNewDec(1).Quo(math.LegacyNewDec(4))), + sdk.NewDecCoinFromDec("stake", math.LegacyNewDec(1).Quo(math.LegacyNewDec(2))), + }, remainder) + } + }) + + } +} + +func TestMsgFundCommunityPool(t *testing.T) { + t.Parallel() + f := initFixture(t) + + // reset fee pool + f.distrKeeper.SetFeePool(f.sdkCtx, distrtypes.InitialFeePool()) + initPool := f.distrKeeper.GetFeePool(f.sdkCtx) + assert.Assert(t, initPool.CommunityPool.Empty()) + + initTokens := f.stakingKeeper.TokensFromConsensusPower(f.sdkCtx, int64(100)) + f.bankKeeper.MintCoins(f.sdkCtx, distrtypes.ModuleName, sdk.NewCoins(sdk.NewCoin(sdk.DefaultBondDenom, initTokens))) + + addr := sdk.AccAddress(PKS[0].Address()) + addr2 := sdk.AccAddress(PKS[1].Address()) + amount := sdk.NewCoins(sdk.NewInt64Coin("stake", 100)) + + // fund the account by minting and sending amount from distribution module to addr + err := f.bankKeeper.MintCoins(f.sdkCtx, distrtypes.ModuleName, amount) + assert.NilError(t, err) + err = f.bankKeeper.SendCoinsFromModuleToAccount(f.sdkCtx, distrtypes.ModuleName, addr, amount) + assert.NilError(t, err) + + testCases := []struct { + name string + msg *distrtypes.MsgFundCommunityPool + expErr bool + expErrMsg string + }{ + { + name: "no depositor address", + msg: &distrtypes.MsgFundCommunityPool{ + Amount: sdk.NewCoins(sdk.NewCoin("stake", sdk.NewInt(100))), + Depositor: emptyDelAddr.String(), + }, + expErr: true, + expErrMsg: "invalid depositor address", + }, + { + name: "invalid coin", + msg: &distrtypes.MsgFundCommunityPool{ + Amount: sdk.Coins{sdk.NewInt64Coin("stake", 10), sdk.NewInt64Coin("stake", 10)}, + Depositor: addr.String(), + }, + expErr: true, + expErrMsg: "10stake,10stake: invalid coins", + }, + { + name: "depositor address with no funds", + msg: &distrtypes.MsgFundCommunityPool{ + Amount: sdk.NewCoins(sdk.NewCoin("stake", sdk.NewInt(100))), + Depositor: addr2.String(), + }, + expErr: true, + expErrMsg: "insufficient funds", + }, + { + name: "valid message", + msg: &distrtypes.MsgFundCommunityPool{ + Amount: sdk.NewCoins(sdk.NewCoin("stake", sdk.NewInt(100))), + Depositor: addr.String(), + }, + expErr: false, + }, + } + for _, tc := range testCases { + tc := tc + t.Run(tc.name, func(t *testing.T) { + res, err := f.app.RunMsg( + tc.msg, + integration.WithAutomaticBeginEndBlock(), + integration.WithAutomaticCommit(), + ) + if tc.expErr { + assert.ErrorContains(t, err, tc.expErrMsg) + } else { + assert.NilError(t, err) + assert.Assert(t, res != nil) + + // check the result + result := distrtypes.MsgFundCommunityPool{} + err = f.cdc.Unmarshal(res.Value, &result) + assert.NilError(t, err) + + // query the community pool funds + assert.DeepEqual(t, initPool.CommunityPool.Add(sdk.NewDecCoinsFromCoins(amount...)...), f.distrKeeper.GetFeePool(f.sdkCtx).CommunityPool) + assert.Assert(t, f.bankKeeper.GetAllBalances(f.sdkCtx, addr).Empty()) + } + }) + } +} + func TestMsgUpdateParams(t *testing.T) { t.Parallel() f := initFixture(t) @@ -23,15 +640,15 @@ func TestMsgUpdateParams(t *testing.T) { testCases := []struct { name string - input *types.MsgUpdateParams + msg *distrtypes.MsgUpdateParams expErr bool expErrMsg string }{ { name: "invalid authority", - input: &types.MsgUpdateParams{ + msg: &distrtypes.MsgUpdateParams{ Authority: "invalid", - Params: types.Params{ + Params: distrtypes.Params{ CommunityTax: sdk.NewDecWithPrec(2, 0), WithdrawAddrEnabled: withdrawAddrEnabled, BaseProposerReward: sdk.ZeroDec(), @@ -43,9 +660,9 @@ func TestMsgUpdateParams(t *testing.T) { }, { name: "community tax > 1", - input: &types.MsgUpdateParams{ + msg: &distrtypes.MsgUpdateParams{ Authority: f.distrKeeper.GetAuthority(), - Params: types.Params{ + Params: distrtypes.Params{ CommunityTax: sdk.NewDecWithPrec(2, 0), WithdrawAddrEnabled: withdrawAddrEnabled, BaseProposerReward: sdk.ZeroDec(), @@ -57,9 +674,9 @@ func TestMsgUpdateParams(t *testing.T) { }, { name: "negative community tax", - input: &types.MsgUpdateParams{ + msg: &distrtypes.MsgUpdateParams{ Authority: f.distrKeeper.GetAuthority(), - Params: types.Params{ + Params: distrtypes.Params{ CommunityTax: sdk.NewDecWithPrec(-2, 1), WithdrawAddrEnabled: withdrawAddrEnabled, BaseProposerReward: sdk.ZeroDec(), @@ -71,9 +688,9 @@ func TestMsgUpdateParams(t *testing.T) { }, { name: "base proposer reward set", - input: &types.MsgUpdateParams{ + msg: &distrtypes.MsgUpdateParams{ Authority: f.distrKeeper.GetAuthority(), - Params: types.Params{ + Params: distrtypes.Params{ CommunityTax: communityTax, BaseProposerReward: sdk.NewDecWithPrec(1, 2), BonusProposerReward: sdk.ZeroDec(), @@ -81,13 +698,13 @@ func TestMsgUpdateParams(t *testing.T) { }, }, expErr: true, - expErrMsg: "cannot update base or bonus proposer reward because these are deprecated fields: invalid request", + expErrMsg: "cannot update base or bonus proposer reward because these are deprecated fields", }, { name: "bonus proposer reward set", - input: &types.MsgUpdateParams{ + msg: &distrtypes.MsgUpdateParams{ Authority: f.distrKeeper.GetAuthority(), - Params: types.Params{ + Params: distrtypes.Params{ CommunityTax: communityTax, BaseProposerReward: sdk.ZeroDec(), BonusProposerReward: sdk.NewDecWithPrec(1, 2), @@ -95,13 +712,13 @@ func TestMsgUpdateParams(t *testing.T) { }, }, expErr: true, - expErrMsg: "cannot update base or bonus proposer reward because these are deprecated fields: invalid request", + expErrMsg: "cannot update base or bonus proposer reward because these are deprecated fields", }, { name: "all good", - input: &types.MsgUpdateParams{ + msg: &distrtypes.MsgUpdateParams{ Authority: f.distrKeeper.GetAuthority(), - Params: types.Params{ + Params: distrtypes.Params{ CommunityTax: communityTax, BaseProposerReward: sdk.ZeroDec(), BonusProposerReward: sdk.ZeroDec(), @@ -115,32 +732,54 @@ func TestMsgUpdateParams(t *testing.T) { for _, tc := range testCases { tc := tc t.Run(tc.name, func(t *testing.T) { - _, err := f.msgServer.UpdateParams(f.ctx, tc.input) - + res, err := f.app.RunMsg( + tc.msg, + integration.WithAutomaticBeginEndBlock(), + integration.WithAutomaticCommit(), + ) if tc.expErr { assert.ErrorContains(t, err, tc.expErrMsg) } else { assert.NilError(t, err) + assert.Assert(t, res != nil) + + // check the result + result := distrtypes.MsgUpdateParams{} + err = f.cdc.Unmarshal(res.Value, &result) + assert.NilError(t, err) + + // query the params and verify it has been updated + params := f.distrKeeper.GetParams(f.sdkCtx) + assert.DeepEqual(t, distrtypes.DefaultParams(), params) } }) } } -func TestCommunityPoolSpend(t *testing.T) { +func TestMsgCommunityPoolSpend(t *testing.T) { t.Parallel() f := initFixture(t) - recipient := sdk.AccAddress([]byte("addr1_______________")) + f.distrKeeper.SetParams(f.sdkCtx, distrtypes.DefaultParams()) + f.distrKeeper.SetFeePool(f.sdkCtx, distrtypes.FeePool{ + CommunityPool: sdk.NewDecCoins(sdk.DecCoin{Denom: "stake", Amount: math.LegacyNewDec(10000)}), + }) + initialFeePool := f.distrKeeper.GetFeePool(f.sdkCtx) + + initTokens := f.stakingKeeper.TokensFromConsensusPower(f.sdkCtx, int64(100)) + f.bankKeeper.MintCoins(f.sdkCtx, distrtypes.ModuleName, sdk.NewCoins(sdk.NewCoin(sdk.DefaultBondDenom, initTokens))) + + recipient := sdk.AccAddress([]byte("addr1")) testCases := []struct { name string - input *types.MsgCommunityPoolSpend + msg *distrtypes.MsgCommunityPoolSpend expErr bool expErrMsg string }{ { name: "invalid authority", - input: &types.MsgCommunityPoolSpend{ + msg: &distrtypes.MsgCommunityPoolSpend{ Authority: "invalid", Recipient: recipient.String(), Amount: sdk.NewCoins(sdk.NewCoin("stake", sdk.NewInt(100))), @@ -150,7 +789,7 @@ func TestCommunityPoolSpend(t *testing.T) { }, { name: "invalid recipient", - input: &types.MsgCommunityPoolSpend{ + msg: &distrtypes.MsgCommunityPoolSpend{ Authority: f.distrKeeper.GetAuthority(), Recipient: "invalid", Amount: sdk.NewCoins(sdk.NewCoin("stake", sdk.NewInt(100))), @@ -160,7 +799,7 @@ func TestCommunityPoolSpend(t *testing.T) { }, { name: "valid message", - input: &types.MsgCommunityPoolSpend{ + msg: &distrtypes.MsgCommunityPoolSpend{ Authority: f.distrKeeper.GetAuthority(), Recipient: recipient.String(), Amount: sdk.NewCoins(sdk.NewCoin("stake", sdk.NewInt(100))), @@ -168,22 +807,30 @@ func TestCommunityPoolSpend(t *testing.T) { expErr: false, }, } - for _, tc := range testCases { tc := tc t.Run(tc.name, func(t *testing.T) { - _, err := f.msgServer.CommunityPoolSpend(f.ctx, tc.input) - + res, err := f.app.RunMsg( + tc.msg, + integration.WithAutomaticBeginEndBlock(), + integration.WithAutomaticCommit(), + ) if tc.expErr { assert.ErrorContains(t, err, tc.expErrMsg) } else { assert.NilError(t, err) - r, err := sdk.AccAddressFromBech32(tc.input.Recipient) - assert.NilError(t, err) + assert.Assert(t, res != nil) - b := f.bankKeeper.GetAllBalances(f.ctx, r) + // check the result + result := distrtypes.MsgCommunityPoolSpend{} + err = f.cdc.Unmarshal(res.Value, &result) + assert.NilError(t, err) - assert.Assert(t, b.IsZero() == false) + // query the community pool to verify it has been updated + communityPool := f.distrKeeper.GetFeePoolCommunityCoins(f.sdkCtx) + newPool, negative := initialFeePool.CommunityPool.SafeSub(sdk.NewDecCoinsFromCoins(tc.msg.Amount...)) + assert.Assert(t, negative == false) + assert.DeepEqual(t, communityPool, newPool) } }) } @@ -193,43 +840,64 @@ func TestMsgDepositValidatorRewardsPool(t *testing.T) { t.Parallel() f := initFixture(t) - tstaking := stakingtestutil.NewHelper(t, f.ctx, f.stakingKeeper) + f.distrKeeper.SetParams(f.sdkCtx, distrtypes.DefaultParams()) + f.distrKeeper.SetFeePool(f.sdkCtx, distrtypes.FeePool{ + CommunityPool: sdk.NewDecCoins(sdk.DecCoin{Denom: "stake", Amount: math.LegacyNewDec(100)}), + }) + initTokens := f.stakingKeeper.TokensFromConsensusPower(f.sdkCtx, int64(10000)) + f.bankKeeper.MintCoins(f.sdkCtx, distrtypes.ModuleName, sdk.NewCoins(sdk.NewCoin(sdk.DefaultBondDenom, initTokens))) + + // Set default staking params + f.stakingKeeper.SetParams(f.sdkCtx, stakingtypes.DefaultParams()) + + addr := sdk.AccAddress([]byte("addr")) + addr1 := sdk.AccAddress(PKS[0].Address()) + valAddr1 := sdk.ValAddress(addr1) + + // send funds to val addr + tokens := f.stakingKeeper.TokensFromConsensusPower(f.sdkCtx, int64(1000)) + f.bankKeeper.SendCoinsFromModuleToAccount(f.sdkCtx, distrtypes.ModuleName, sdk.AccAddress(valAddr1), sdk.NewCoins(sdk.NewCoin(sdk.DefaultBondDenom, tokens))) + + // send funds from module to addr to perform DepositValidatorRewardsPool + f.bankKeeper.SendCoinsFromModuleToAccount(f.sdkCtx, distrtypes.ModuleName, addr, sdk.NewCoins(sdk.NewCoin(sdk.DefaultBondDenom, tokens))) + + tstaking := stakingtestutil.NewHelper(t, f.sdkCtx, f.stakingKeeper) tstaking.Commission = stakingtypes.NewCommissionRates(sdk.NewDecWithPrec(5, 1), sdk.NewDecWithPrec(5, 1), math.LegacyNewDec(0)) - tstaking.CreateValidator(f.valAddrs[1], valConsPk0, sdk.NewInt(100), true) + tstaking.CreateValidator(valAddr1, valConsPk0, sdk.NewInt(100), true) // mint a non-staking token and send to an account amt := sdk.NewCoins(sdk.NewInt64Coin("foo", 500)) - f.bankKeeper.MintCoins(f.ctx, minttypes.ModuleName, amt) - f.bankKeeper.SendCoinsFromModuleToAccount(f.ctx, minttypes.ModuleName, f.addrs[0], amt) + f.bankKeeper.MintCoins(f.sdkCtx, distrtypes.ModuleName, amt) + f.bankKeeper.SendCoinsFromModuleToAccount(f.sdkCtx, distrtypes.ModuleName, addr, amt) testCases := []struct { name string - input *types.MsgDepositValidatorRewardsPool + msg *distrtypes.MsgDepositValidatorRewardsPool expErr bool expErrMsg string }{ { name: "happy path (staking token)", - input: &types.MsgDepositValidatorRewardsPool{ - Authority: f.addrs[0].String(), - ValidatorAddress: f.valAddrs[1].String(), - Amount: sdk.NewCoins(sdk.NewCoin(f.stakingKeeper.BondDenom(f.ctx), sdk.NewInt(100))), + msg: &distrtypes.MsgDepositValidatorRewardsPool{ + Depositor: addr.String(), + ValidatorAddress: valAddr1.String(), + Amount: sdk.NewCoins(sdk.NewCoin(f.stakingKeeper.BondDenom(f.sdkCtx), sdk.NewInt(100))), }, }, { name: "happy path (non-staking token)", - input: &types.MsgDepositValidatorRewardsPool{ - Authority: f.addrs[0].String(), - ValidatorAddress: f.valAddrs[1].String(), + msg: &distrtypes.MsgDepositValidatorRewardsPool{ + Depositor: addr.String(), + ValidatorAddress: valAddr1.String(), Amount: amt, }, }, { name: "invalid validator", - input: &types.MsgDepositValidatorRewardsPool{ - Authority: f.addrs[0].String(), + msg: &distrtypes.MsgDepositValidatorRewardsPool{ + Depositor: addr.String(), ValidatorAddress: sdk.ValAddress([]byte("addr1_______________")).String(), - Amount: sdk.NewCoins(sdk.NewCoin(f.stakingKeeper.BondDenom(f.ctx), sdk.NewInt(100))), + Amount: sdk.NewCoins(sdk.NewCoin(f.stakingKeeper.BondDenom(f.sdkCtx), sdk.NewInt(100))), }, expErr: true, expErrMsg: "validator does not exist", @@ -239,22 +907,32 @@ func TestMsgDepositValidatorRewardsPool(t *testing.T) { for _, tc := range testCases { tc := tc t.Run(tc.name, func(t *testing.T) { - _, err := f.msgServer.DepositValidatorRewardsPool(f.ctx, tc.input) - + res, err := f.app.RunMsg( + tc.msg, + integration.WithAutomaticBeginEndBlock(), + integration.WithAutomaticCommit(), + ) if tc.expErr { assert.ErrorContains(t, err, tc.expErrMsg) } else { assert.NilError(t, err) + assert.Assert(t, res != nil) + + // check the result + result := distrtypes.MsgDepositValidatorRewardsPoolResponse{} + err = f.cdc.Unmarshal(res.Value, &result) + assert.NilError(t, err) - valAddr, err := sdk.ValAddressFromBech32(tc.input.ValidatorAddress) + val, err := sdk.ValAddressFromBech32(tc.msg.ValidatorAddress) assert.NilError(t, err) // check validator outstanding rewards - outstandingRewards := f.distrKeeper.GetValidatorOutstandingRewards(f.ctx, valAddr) - for _, c := range tc.input.Amount { + outstandingRewards := f.distrKeeper.GetValidatorOutstandingRewards(f.sdkCtx, val) + for _, c := range tc.msg.Amount { x := outstandingRewards.Rewards.AmountOf(c.Denom) assert.DeepEqual(t, x, sdk.NewDecFromInt(c.Amount)) } + } }) } diff --git a/tests/integration/evidence/keeper/infraction_test.go b/tests/integration/evidence/keeper/infraction_test.go index a53947486061..41fe09ec5e97 100644 --- a/tests/integration/evidence/keeper/infraction_test.go +++ b/tests/integration/evidence/keeper/infraction_test.go @@ -25,7 +25,6 @@ import ( minttypes "github.com/cosmos/cosmos-sdk/x/mint/types" slashingkeeper "github.com/cosmos/cosmos-sdk/x/slashing/keeper" slashingtypes "github.com/cosmos/cosmos-sdk/x/slashing/types" - "github.com/cosmos/cosmos-sdk/x/staking" stakingkeeper "github.com/cosmos/cosmos-sdk/x/staking/keeper" stakingtestutil "github.com/cosmos/cosmos-sdk/x/staking/testutil" ) @@ -100,7 +99,7 @@ func TestHandleDoubleSign(t *testing.T) { selfDelegation := tstaking.CreateValidatorWithValPower(operatorAddr, val, power, true) // execute end-blocker and verify validator attributes - staking.EndBlocker(ctx, f.stakingKeeper) + f.stakingKeeper.EndBlocker(f.ctx) assert.DeepEqual(t, f.bankKeeper.GetAllBalances(ctx, sdk.AccAddress(operatorAddr)).String(), sdk.NewCoins(sdk.NewCoin(stakingParams.BondDenom, initAmt.Sub(selfDelegation))).String(), @@ -172,7 +171,7 @@ func TestHandleDoubleSign_TooOld(t *testing.T) { amt := tstaking.CreateValidatorWithValPower(operatorAddr, val, power, true) // execute end-blocker and verify validator attributes - staking.EndBlocker(ctx, f.stakingKeeper) + f.stakingKeeper.EndBlocker(f.ctx) assert.DeepEqual(t, f.bankKeeper.GetAllBalances(ctx, sdk.AccAddress(operatorAddr)), sdk.NewCoins(sdk.NewCoin(stakingParams.BondDenom, initAmt.Sub(amt))), diff --git a/tests/integration/genutil/gentx_test.go b/tests/integration/genutil/gentx_test.go index a9bf32561c11..2b9001b68ae2 100644 --- a/tests/integration/genutil/gentx_test.go +++ b/tests/integration/genutil/gentx_test.go @@ -9,11 +9,11 @@ import ( "cosmossdk.io/math" cmtproto "github.com/cometbft/cometbft/proto/tendermint/types" + "github.com/stretchr/testify/require" "gotest.tools/v3/assert" "github.com/cosmos/cosmos-sdk/baseapp" "github.com/cosmos/cosmos-sdk/crypto/keys/secp256k1" - sdktestutil "github.com/cosmos/cosmos-sdk/testutil" "github.com/cosmos/cosmos-sdk/testutil/configurator" simtestutil "github.com/cosmos/cosmos-sdk/testutil/sims" sdk "github.com/cosmos/cosmos-sdk/types" @@ -297,7 +297,7 @@ func TestDeliverGenTxs(t *testing.T) { tc.malleate() if tc.expPass { - sdktestutil.AssertNotPanics(t, func() { + require.NotPanics(t, func() { genutil.DeliverGenTxs( f.ctx, genTxs, f.stakingKeeper, f.baseApp.DeliverTx, f.encodingConfig.TxConfig, diff --git a/tests/integration/gov/keeper/common_test.go b/tests/integration/gov/keeper/common_test.go index 8bd1518752b4..f11589e92419 100644 --- a/tests/integration/gov/keeper/common_test.go +++ b/tests/integration/gov/keeper/common_test.go @@ -15,7 +15,6 @@ import ( "github.com/cosmos/cosmos-sdk/x/gov/types" v1 "github.com/cosmos/cosmos-sdk/x/gov/types/v1" "github.com/cosmos/cosmos-sdk/x/gov/types/v1beta1" - "github.com/cosmos/cosmos-sdk/x/staking" stakingkeeper "github.com/cosmos/cosmos-sdk/x/staking/keeper" stakingtypes "github.com/cosmos/cosmos-sdk/x/staking/types" ) @@ -73,7 +72,7 @@ func createValidators(t *testing.T, ctx sdk.Context, app *simapp.SimApp, powers _, _ = app.StakingKeeper.Delegate(ctx, addrs[1], app.StakingKeeper.TokensFromConsensusPower(ctx, powers[1]), stakingtypes.Unbonded, val2, true) _, _ = app.StakingKeeper.Delegate(ctx, addrs[2], app.StakingKeeper.TokensFromConsensusPower(ctx, powers[2]), stakingtypes.Unbonded, val3, true) - _ = staking.EndBlocker(ctx, app.StakingKeeper) + app.StakingKeeper.EndBlocker(ctx) return addrs, valAddrs } diff --git a/tests/integration/gov/keeper/tally_test.go b/tests/integration/gov/keeper/tally_test.go index cda35b0d61ec..a021a3c8537a 100644 --- a/tests/integration/gov/keeper/tally_test.go +++ b/tests/integration/gov/keeper/tally_test.go @@ -8,7 +8,6 @@ import ( simtestutil "github.com/cosmos/cosmos-sdk/testutil/sims" sdk "github.com/cosmos/cosmos-sdk/types" v1 "github.com/cosmos/cosmos-sdk/x/gov/types/v1" - "github.com/cosmos/cosmos-sdk/x/staking" stakingtypes "github.com/cosmos/cosmos-sdk/x/staking/types" ) @@ -271,7 +270,7 @@ func TestTallyDelgatorOverride(t *testing.T) { _, err := app.StakingKeeper.Delegate(ctx, addrs[4], delTokens, stakingtypes.Unbonded, val1, true) assert.NilError(t, err) - _ = staking.EndBlocker(ctx, app.StakingKeeper) + app.StakingKeeper.EndBlocker(ctx) tp := TestProposal proposal, err := app.GovKeeper.SubmitProposal(ctx, tp, "", "test", "description", addrs[0], false) @@ -309,7 +308,7 @@ func TestTallyDelgatorInherit(t *testing.T) { _, err := app.StakingKeeper.Delegate(ctx, addrs[3], delTokens, stakingtypes.Unbonded, val3, true) assert.NilError(t, err) - _ = staking.EndBlocker(ctx, app.StakingKeeper) + app.StakingKeeper.EndBlocker(ctx) tp := TestProposal proposal, err := app.GovKeeper.SubmitProposal(ctx, tp, "", "test", "description", addrs[0], false) @@ -350,7 +349,7 @@ func TestTallyDelgatorMultipleOverride(t *testing.T) { _, err = app.StakingKeeper.Delegate(ctx, addrs[3], delTokens, stakingtypes.Unbonded, val2, true) assert.NilError(t, err) - _ = staking.EndBlocker(ctx, app.StakingKeeper) + app.StakingKeeper.EndBlocker(ctx) tp := TestProposal proposal, err := app.GovKeeper.SubmitProposal(ctx, tp, "", "test", "description", addrs[0], false) @@ -394,7 +393,7 @@ func TestTallyDelgatorMultipleInherit(t *testing.T) { _, err = app.StakingKeeper.Delegate(ctx, addrs[3], delTokens, stakingtypes.Unbonded, val3, true) assert.NilError(t, err) - _ = staking.EndBlocker(ctx, app.StakingKeeper) + app.StakingKeeper.EndBlocker(ctx) tp := TestProposal proposal, err := app.GovKeeper.SubmitProposal(ctx, tp, "", "test", "description", addrs[0], false) @@ -435,7 +434,7 @@ func TestTallyJailedValidator(t *testing.T) { _, err = app.StakingKeeper.Delegate(ctx, addrs[3], delTokens, stakingtypes.Unbonded, val3, true) assert.NilError(t, err) - _ = staking.EndBlocker(ctx, app.StakingKeeper) + app.StakingKeeper.EndBlocker(ctx) consAddr, err := val2.GetConsAddr() assert.NilError(t, err) diff --git a/tests/integration/rapidgen/rapidgen.go b/tests/integration/rapidgen/rapidgen.go new file mode 100644 index 000000000000..607ebaed253b --- /dev/null +++ b/tests/integration/rapidgen/rapidgen.go @@ -0,0 +1,292 @@ +package rapidgen + +import ( + "fmt" + + cosmos_proto "github.com/cosmos/cosmos-proto" + "github.com/cosmos/cosmos-proto/rapidproto" + gogoproto "github.com/cosmos/gogoproto/proto" + "google.golang.org/protobuf/proto" + "google.golang.org/protobuf/reflect/protoreflect" + "google.golang.org/protobuf/reflect/protoregistry" + "pgregory.net/rapid" + + "cosmossdk.io/api/amino" + authapi "cosmossdk.io/api/cosmos/auth/v1beta1" + authzapi "cosmossdk.io/api/cosmos/authz/v1beta1" + bankapi "cosmossdk.io/api/cosmos/bank/v1beta1" + consensusapi "cosmossdk.io/api/cosmos/consensus/v1" + "cosmossdk.io/api/cosmos/crypto/ed25519" + multisigapi "cosmossdk.io/api/cosmos/crypto/multisig" + "cosmossdk.io/api/cosmos/crypto/secp256k1" + distapi "cosmossdk.io/api/cosmos/distribution/v1beta1" + evidenceapi "cosmossdk.io/api/cosmos/evidence/v1beta1" + feegrantapi "cosmossdk.io/api/cosmos/feegrant/v1beta1" + gov_v1_api "cosmossdk.io/api/cosmos/gov/v1" + gov_v1beta1_api "cosmossdk.io/api/cosmos/gov/v1beta1" + groupapi "cosmossdk.io/api/cosmos/group/v1" + mintapi "cosmossdk.io/api/cosmos/mint/v1beta1" + paramsapi "cosmossdk.io/api/cosmos/params/v1beta1" + slashingapi "cosmossdk.io/api/cosmos/slashing/v1beta1" + stakingapi "cosmossdk.io/api/cosmos/staking/v1beta1" + upgradeapi "cosmossdk.io/api/cosmos/upgrade/v1beta1" + vestingapi "cosmossdk.io/api/cosmos/vesting/v1beta1" + evidencetypes "cosmossdk.io/x/evidence/types" + feegranttypes "cosmossdk.io/x/feegrant" + upgradetypes "cosmossdk.io/x/upgrade/types" + "github.com/cosmos/cosmos-sdk/crypto/keys/multisig" + authtypes "github.com/cosmos/cosmos-sdk/x/auth/types" + vestingtypes "github.com/cosmos/cosmos-sdk/x/auth/vesting/types" + authztypes "github.com/cosmos/cosmos-sdk/x/authz" + banktypes "github.com/cosmos/cosmos-sdk/x/bank/types" + consensustypes "github.com/cosmos/cosmos-sdk/x/consensus/types" + disttypes "github.com/cosmos/cosmos-sdk/x/distribution/types" + gov_v1_types "github.com/cosmos/cosmos-sdk/x/gov/types/v1" + gov_v1beta1_types "github.com/cosmos/cosmos-sdk/x/gov/types/v1beta1" + grouptypes "github.com/cosmos/cosmos-sdk/x/group" + minttypes "github.com/cosmos/cosmos-sdk/x/mint/types" + "github.com/cosmos/cosmos-sdk/x/params/types/proposal" + slashingtypes "github.com/cosmos/cosmos-sdk/x/slashing/types" + stakingtypes "github.com/cosmos/cosmos-sdk/x/staking/types" +) + +type GeneratedType struct { + Pulsar proto.Message + Gogo gogoproto.Message + Opts rapidproto.GeneratorOptions +} + +func GenType(gogo gogoproto.Message, pulsar proto.Message, opts rapidproto.GeneratorOptions) GeneratedType { + return GeneratedType{ + Pulsar: pulsar, + Gogo: gogo, + Opts: opts, + } +} + +func WithDecisionPolicy(opts rapidproto.GeneratorOptions) rapidproto.GeneratorOptions { + return opts. + WithAnyTypes( + &groupapi.ThresholdDecisionPolicy{}, + &groupapi.PercentageDecisionPolicy{}). + WithDisallowNil(). + WithInterfaceHint("cosmos.group.v1.DecisionPolicy", &groupapi.ThresholdDecisionPolicy{}). + WithInterfaceHint("cosmos.group.v1.DecisionPolicy", &groupapi.PercentageDecisionPolicy{}) +} + +func GeneratorFieldMapper(t *rapid.T, field protoreflect.FieldDescriptor, name string) (protoreflect.Value, bool) { + opts := field.Options() + switch { + case proto.HasExtension(opts, cosmos_proto.E_Scalar): + scalar := proto.GetExtension(opts, cosmos_proto.E_Scalar).(string) + switch scalar { + case "cosmos.Int": + i32 := rapid.Int32().Draw(t, name) + return protoreflect.ValueOfString(fmt.Sprintf("%d", i32)), true + case "cosmos.Dec": + return protoreflect.ValueOfString(""), true + } + case field.Kind() == protoreflect.BytesKind: + if proto.HasExtension(opts, amino.E_Encoding) { + encoding := proto.GetExtension(opts, amino.E_Encoding).(string) + if encoding == "cosmos_dec_bytes" { + return protoreflect.ValueOfBytes([]byte{}), true + } + } + } + + return protoreflect.Value{}, false +} + +var ( + GenOpts = rapidproto.GeneratorOptions{ + Resolver: protoregistry.GlobalTypes, + FieldMaps: []rapidproto.FieldMapper{GeneratorFieldMapper}, + } + SignableTypes = []GeneratedType{ + // auth + GenType(&authtypes.MsgUpdateParams{}, &authapi.MsgUpdateParams{}, GenOpts.WithDisallowNil()), + + // authz + GenType(&authztypes.MsgGrant{}, &authzapi.MsgGrant{}, + GenOpts.WithAnyTypes(&authzapi.GenericAuthorization{}). + WithInterfaceHint("cosmos.authz.v1beta1.Authorization", &authzapi.GenericAuthorization{}). + WithDisallowNil(), + ), + GenType(&authztypes.MsgExec{}, &authzapi.MsgExec{}, + GenOpts.WithAnyTypes(&authzapi.MsgGrant{}, &authzapi.GenericAuthorization{}). + WithDisallowNil(). + WithInterfaceHint("cosmos.authz.v1beta1.Authorization", &authzapi.GenericAuthorization{}). + WithInterfaceHint("cosmos.base.v1beta1.Msg", &authzapi.MsgGrant{}), + ), + + // bank + GenType(&banktypes.MsgSend{}, &bankapi.MsgSend{}, GenOpts.WithDisallowNil()), + GenType(&banktypes.MsgMultiSend{}, &bankapi.MsgMultiSend{}, GenOpts.WithDisallowNil()), + GenType(&banktypes.MsgUpdateParams{}, &bankapi.MsgUpdateParams{}, GenOpts.WithDisallowNil()), + GenType(&banktypes.MsgSetSendEnabled{}, &bankapi.MsgSetSendEnabled{}, GenOpts), + + // consensus + GenType(&consensustypes.MsgUpdateParams{}, &consensusapi.MsgUpdateParams{}, GenOpts.WithDisallowNil()), + + // distribution + GenType(&disttypes.MsgWithdrawDelegatorReward{}, &distapi.MsgWithdrawDelegatorReward{}, GenOpts), + GenType(&disttypes.MsgWithdrawValidatorCommission{}, &distapi.MsgWithdrawValidatorCommission{}, GenOpts), + GenType(&disttypes.MsgSetWithdrawAddress{}, &distapi.MsgSetWithdrawAddress{}, GenOpts), + GenType(&disttypes.MsgFundCommunityPool{}, &distapi.MsgFundCommunityPool{}, GenOpts), + GenType(&disttypes.MsgUpdateParams{}, &distapi.MsgUpdateParams{}, GenOpts.WithDisallowNil()), + GenType(&disttypes.MsgCommunityPoolSpend{}, &distapi.MsgCommunityPoolSpend{}, GenOpts), + GenType(&disttypes.MsgDepositValidatorRewardsPool{}, &distapi.MsgDepositValidatorRewardsPool{}, GenOpts), + + // evidence + GenType(&evidencetypes.MsgSubmitEvidence{}, &evidenceapi.MsgSubmitEvidence{}, + GenOpts.WithAnyTypes(&evidenceapi.Equivocation{}). + WithDisallowNil(). + WithInterfaceHint("cosmos.evidence.v1beta1.Evidence", &evidenceapi.Equivocation{})), + + // feegrant + GenType(&feegranttypes.MsgGrantAllowance{}, &feegrantapi.MsgGrantAllowance{}, + GenOpts.WithDisallowNil(). + WithAnyTypes( + &feegrantapi.BasicAllowance{}, + &feegrantapi.PeriodicAllowance{}). + WithInterfaceHint("cosmos.feegrant.v1beta1.FeeAllowanceI", &feegrantapi.BasicAllowance{}). + WithInterfaceHint("cosmos.feegrant.v1beta1.FeeAllowanceI", &feegrantapi.PeriodicAllowance{}), + ), + GenType(&feegranttypes.MsgRevokeAllowance{}, &feegrantapi.MsgRevokeAllowance{}, GenOpts), + + // gov v1beta1 + GenType(&gov_v1beta1_types.MsgSubmitProposal{}, &gov_v1beta1_api.MsgSubmitProposal{}, + GenOpts.WithAnyTypes(&gov_v1beta1_api.TextProposal{}). + WithDisallowNil(). + WithInterfaceHint("cosmos.gov.v1beta1.Content", &gov_v1beta1_api.TextProposal{}), + ), + GenType(&gov_v1beta1_types.MsgDeposit{}, &gov_v1beta1_api.MsgDeposit{}, GenOpts), + GenType(&gov_v1beta1_types.MsgVote{}, &gov_v1beta1_api.MsgVote{}, GenOpts), + GenType(&gov_v1beta1_types.MsgVoteWeighted{}, &gov_v1beta1_api.MsgVoteWeighted{}, GenOpts), + + // gov v1 + GenType(&gov_v1_types.MsgSubmitProposal{}, &gov_v1_api.MsgSubmitProposal{}, + GenOpts.WithAnyTypes(&gov_v1_api.MsgVote{}, &gov_v1_api.MsgVoteWeighted{}, &gov_v1_api.MsgDeposit{}, + &gov_v1_api.MsgExecLegacyContent{}, &gov_v1_api.MsgUpdateParams{}). + WithInterfaceHint("cosmos.gov.v1beta1.Content", &gov_v1beta1_api.TextProposal{}). + WithDisallowNil(), + ), + GenType(&gov_v1_types.MsgDeposit{}, &gov_v1_api.MsgDeposit{}, GenOpts), + GenType(&gov_v1_types.MsgVote{}, &gov_v1_api.MsgVote{}, GenOpts), + GenType(&gov_v1_types.MsgVoteWeighted{}, &gov_v1_api.MsgVoteWeighted{}, GenOpts), + GenType(&gov_v1_types.MsgExecLegacyContent{}, &gov_v1_api.MsgExecLegacyContent{}, + GenOpts.WithAnyTypes(&gov_v1beta1_api.TextProposal{}). + WithDisallowNil(). + WithInterfaceHint("cosmos.gov.v1beta1.Content", &gov_v1beta1_api.TextProposal{})), + GenType(&gov_v1_types.MsgUpdateParams{}, &gov_v1_api.MsgUpdateParams{}, GenOpts.WithDisallowNil()), + + // group + GenType(&grouptypes.MsgCreateGroup{}, &groupapi.MsgCreateGroup{}, GenOpts), + GenType(&grouptypes.MsgUpdateGroupMembers{}, &groupapi.MsgUpdateGroupMembers{}, GenOpts), + GenType(&grouptypes.MsgUpdateGroupAdmin{}, &groupapi.MsgUpdateGroupAdmin{}, GenOpts), + GenType(&grouptypes.MsgUpdateGroupMetadata{}, &groupapi.MsgUpdateGroupMetadata{}, GenOpts), + GenType(&grouptypes.MsgCreateGroupWithPolicy{}, &groupapi.MsgCreateGroupWithPolicy{}, + WithDecisionPolicy(GenOpts)), + GenType(&grouptypes.MsgCreateGroupPolicy{}, &groupapi.MsgCreateGroupPolicy{}, + WithDecisionPolicy(GenOpts)), + GenType(&grouptypes.MsgUpdateGroupPolicyAdmin{}, &groupapi.MsgUpdateGroupPolicyAdmin{}, GenOpts), + GenType(&grouptypes.MsgUpdateGroupPolicyDecisionPolicy{}, &groupapi.MsgUpdateGroupPolicyDecisionPolicy{}, + WithDecisionPolicy(GenOpts)), + GenType(&grouptypes.MsgUpdateGroupPolicyMetadata{}, &groupapi.MsgUpdateGroupPolicyMetadata{}, GenOpts), + GenType(&grouptypes.MsgSubmitProposal{}, &groupapi.MsgSubmitProposal{}, + GenOpts.WithDisallowNil(). + WithAnyTypes(&groupapi.MsgCreateGroup{}, &groupapi.MsgUpdateGroupMembers{}). + WithInterfaceHint("cosmos.base.v1beta1.Msg", &groupapi.MsgCreateGroup{}). + WithInterfaceHint("cosmos.base.v1beta1.Msg", &groupapi.MsgUpdateGroupMembers{}), + ), + GenType(&grouptypes.MsgVote{}, &groupapi.MsgVote{}, GenOpts), + GenType(&grouptypes.MsgExec{}, &groupapi.MsgExec{}, GenOpts), + GenType(&grouptypes.MsgLeaveGroup{}, &groupapi.MsgLeaveGroup{}, GenOpts), + + // mint + GenType(&minttypes.MsgUpdateParams{}, &mintapi.MsgUpdateParams{}, GenOpts.WithDisallowNil()), + + // slashing + GenType(&slashingtypes.MsgUnjail{}, &slashingapi.MsgUnjail{}, GenOpts), + GenType(&slashingtypes.MsgUpdateParams{}, &slashingapi.MsgUpdateParams{}, GenOpts.WithDisallowNil()), + + // staking + GenType(&stakingtypes.MsgCreateValidator{}, &stakingapi.MsgCreateValidator{}, + GenOpts.WithDisallowNil(). + WithAnyTypes(&ed25519.PubKey{}). + WithInterfaceHint("cosmos.crypto.PubKey", &ed25519.PubKey{}), + ), + GenType(&stakingtypes.MsgEditValidator{}, &stakingapi.MsgEditValidator{}, GenOpts.WithDisallowNil()), + GenType(&stakingtypes.MsgDelegate{}, &stakingapi.MsgDelegate{}, GenOpts.WithDisallowNil()), + GenType(&stakingtypes.MsgUndelegate{}, &stakingapi.MsgUndelegate{}, GenOpts.WithDisallowNil()), + GenType(&stakingtypes.MsgBeginRedelegate{}, &stakingapi.MsgBeginRedelegate{}, GenOpts.WithDisallowNil()), + GenType(&stakingtypes.MsgUpdateParams{}, &stakingapi.MsgUpdateParams{}, GenOpts.WithDisallowNil()), + + // upgrade + GenType(&upgradetypes.MsgSoftwareUpgrade{}, &upgradeapi.MsgSoftwareUpgrade{}, GenOpts.WithDisallowNil()), + GenType(&upgradetypes.MsgCancelUpgrade{}, &upgradeapi.MsgCancelUpgrade{}, GenOpts), + + // vesting + GenType(&vestingtypes.MsgCreateVestingAccount{}, &vestingapi.MsgCreateVestingAccount{}, GenOpts), + GenType(&vestingtypes.MsgCreatePermanentLockedAccount{}, &vestingapi.MsgCreatePermanentLockedAccount{}, GenOpts), + GenType(&vestingtypes.MsgCreatePeriodicVestingAccount{}, &vestingapi.MsgCreatePeriodicVestingAccount{}, GenOpts), + } + NonsignableTypes = []GeneratedType{ + GenType(&authtypes.Params{}, &authapi.Params{}, GenOpts), + GenType(&authtypes.BaseAccount{}, &authapi.BaseAccount{}, GenOpts.WithAnyTypes(&ed25519.PubKey{})), + GenType(&authtypes.ModuleAccount{}, &authapi.ModuleAccount{}, GenOpts.WithAnyTypes(&ed25519.PubKey{})), + GenType(&authtypes.ModuleCredential{}, &authapi.ModuleCredential{}, GenOpts), + + GenType(&authztypes.GenericAuthorization{}, &authzapi.GenericAuthorization{}, GenOpts), + GenType(&authztypes.Grant{}, &authzapi.Grant{}, + GenOpts.WithAnyTypes(&authzapi.GenericAuthorization{}). + WithDisallowNil(). + WithInterfaceHint("cosmos.authz.v1beta1.Authorization", &authzapi.GenericAuthorization{}), + ), + + GenType(&banktypes.SendAuthorization{}, &bankapi.SendAuthorization{}, GenOpts), + GenType(&banktypes.Params{}, &bankapi.Params{}, GenOpts), + + // crypto + GenType(&multisig.LegacyAminoPubKey{}, &multisigapi.LegacyAminoPubKey{}, + GenOpts.WithAnyTypes(&ed25519.PubKey{}, &secp256k1.PubKey{})), + + GenType(&disttypes.Params{}, &distapi.Params{}, GenOpts), + + GenType(&evidencetypes.Equivocation{}, &evidenceapi.Equivocation{}, GenOpts.WithDisallowNil()), + + GenType(&feegranttypes.BasicAllowance{}, &feegrantapi.BasicAllowance{}, GenOpts.WithDisallowNil()), + GenType(&feegranttypes.PeriodicAllowance{}, &feegrantapi.PeriodicAllowance{}, GenOpts.WithDisallowNil()), + GenType(&feegranttypes.AllowedMsgAllowance{}, &feegrantapi.AllowedMsgAllowance{}, + GenOpts.WithDisallowNil(). + WithAnyTypes( + &feegrantapi.BasicAllowance{}, + &feegrantapi.PeriodicAllowance{}). + WithInterfaceHint("cosmos.feegrant.v1beta1.FeeAllowanceI", &feegrantapi.BasicAllowance{}). + WithInterfaceHint("cosmos.feegrant.v1beta1.FeeAllowanceI", &feegrantapi.PeriodicAllowance{}), + ), + + GenType(&gov_v1beta1_types.TextProposal{}, &gov_v1beta1_api.TextProposal{}, GenOpts), + + GenType(&minttypes.Params{}, &mintapi.Params{}, GenOpts), + + // params + GenType(&proposal.ParameterChangeProposal{}, ¶msapi.ParameterChangeProposal{}, GenOpts), + + GenType(&slashingtypes.Params{}, &slashingapi.Params{}, GenOpts.WithDisallowNil()), + + 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 + GenType(&upgradetypes.Plan{}, &upgradeapi.Plan{}, GenOpts.WithDisallowNil()), + + GenType(&vestingtypes.BaseVestingAccount{}, &vestingapi.BaseVestingAccount{}, GenOpts.WithDisallowNil()), + GenType(&vestingtypes.ContinuousVestingAccount{}, &vestingapi.ContinuousVestingAccount{}, GenOpts.WithDisallowNil()), + GenType(&vestingtypes.DelayedVestingAccount{}, &vestingapi.DelayedVestingAccount{}, GenOpts.WithDisallowNil()), + GenType(&vestingtypes.PermanentLockedAccount{}, &vestingapi.PermanentLockedAccount{}, GenOpts.WithDisallowNil()), + GenType(&vestingtypes.PeriodicVestingAccount{}, &vestingapi.PeriodicVestingAccount{}, GenOpts.WithDisallowNil()), + } + DefaultGeneratedTypes = append(SignableTypes, NonsignableTypes...) +) diff --git a/tests/integration/slashing/keeper/keeper_test.go b/tests/integration/slashing/keeper/keeper_test.go index ada343cf57fb..78c1222f0781 100644 --- a/tests/integration/slashing/keeper/keeper_test.go +++ b/tests/integration/slashing/keeper/keeper_test.go @@ -5,21 +5,18 @@ import ( "time" cmtproto "github.com/cometbft/cometbft/proto/tendermint/types" + "github.com/stretchr/testify/require" "gotest.tools/v3/assert" - "github.com/cosmos/cosmos-sdk/baseapp" simtestutil "github.com/cosmos/cosmos-sdk/testutil/sims" sdk "github.com/cosmos/cosmos-sdk/types" "github.com/cosmos/cosmos-sdk/x/slashing/testutil" - "github.com/cosmos/cosmos-sdk/x/staking" - authkeeper "github.com/cosmos/cosmos-sdk/x/auth/keeper" bankkeeper "github.com/cosmos/cosmos-sdk/x/bank/keeper" slashingkeeper "github.com/cosmos/cosmos-sdk/x/slashing/keeper" stakingkeeper "github.com/cosmos/cosmos-sdk/x/staking/keeper" stakingtestutil "github.com/cosmos/cosmos-sdk/x/staking/testutil" - codectypes "github.com/cosmos/cosmos-sdk/codec/types" slashingtypes "github.com/cosmos/cosmos-sdk/x/slashing/types" stakingtypes "github.com/cosmos/cosmos-sdk/x/staking/types" ) @@ -28,15 +25,11 @@ import ( var InitTokens = sdk.TokensFromConsensusPower(200, sdk.DefaultPowerReduction) type fixture struct { - ctx sdk.Context - slashingKeeper slashingkeeper.Keeper - stakingKeeper *stakingkeeper.Keeper - bankKeeper bankkeeper.Keeper - accountKeeper authkeeper.AccountKeeper - interfaceRegistry codectypes.InterfaceRegistry - addrDels []sdk.AccAddress - queryClient slashingtypes.QueryClient - msgServer slashingtypes.MsgServer + ctx sdk.Context + slashingKeeper slashingkeeper.Keeper + stakingKeeper *stakingkeeper.Keeper + bankKeeper bankkeeper.Keeper + addrDels []sdk.AccAddress } func initFixture(t assert.TestingT) *fixture { @@ -44,10 +37,8 @@ func initFixture(t assert.TestingT) *fixture { app, err := simtestutil.Setup( testutil.AppConfig, &f.bankKeeper, - &f.accountKeeper, &f.slashingKeeper, &f.stakingKeeper, - &f.interfaceRegistry, ) assert.NilError(t, err) @@ -55,24 +46,16 @@ func initFixture(t assert.TestingT) *fixture { // TestParams set the SignedBlocksWindow to 1000 and MaxMissedBlocksPerWindow to 500 f.slashingKeeper.SetParams(ctx, testutil.TestParams()) - addrDels := simtestutil.AddTestAddrsIncremental(f.bankKeeper, f.stakingKeeper, ctx, 5, f.stakingKeeper.TokensFromConsensusPower(ctx, 200)) + addrDels := simtestutil.AddTestAddrsIncremental(f.bankKeeper, f.stakingKeeper, ctx, 5, f.stakingKeeper.TokensFromConsensusPower(f.ctx, 200)) - info1 := slashingtypes.NewValidatorSigningInfo(sdk.ConsAddress(addrDels[0]), int64(4), int64(3), - time.Unix(2, 0), false, int64(10)) - info2 := slashingtypes.NewValidatorSigningInfo(sdk.ConsAddress(addrDels[1]), int64(5), int64(4), - time.Unix(2, 0), false, int64(10)) + info1 := slashingtypes.NewValidatorSigningInfo(sdk.ConsAddress(addrDels[0]), int64(4), int64(3), time.Unix(2, 0), false, int64(10)) + info2 := slashingtypes.NewValidatorSigningInfo(sdk.ConsAddress(addrDels[1]), int64(5), int64(4), time.Unix(2, 0), false, int64(10)) f.slashingKeeper.SetValidatorSigningInfo(ctx, sdk.ConsAddress(addrDels[0]), info1) f.slashingKeeper.SetValidatorSigningInfo(ctx, sdk.ConsAddress(addrDels[1]), info2) - queryHelper := baseapp.NewQueryServerTestHelper(ctx, f.interfaceRegistry) - slashingtypes.RegisterQueryServer(queryHelper, f.slashingKeeper) - queryClient := slashingtypes.NewQueryClient(queryHelper) - f.queryClient = queryClient - f.addrDels = addrDels f.ctx = ctx - f.msgServer = slashingkeeper.NewMsgServerImpl(f.slashingKeeper) return f } @@ -81,16 +64,14 @@ func TestUnJailNotBonded(t *testing.T) { t.Parallel() f := initFixture(t) - ctx := f.ctx - - p := f.stakingKeeper.GetParams(ctx) + p := f.stakingKeeper.GetParams(f.ctx) p.MaxValidators = 5 - f.stakingKeeper.SetParams(ctx, p) + f.stakingKeeper.SetParams(f.ctx, p) - addrDels := simtestutil.AddTestAddrsIncremental(f.bankKeeper, f.stakingKeeper, ctx, 6, f.stakingKeeper.TokensFromConsensusPower(ctx, 200)) + addrDels := simtestutil.AddTestAddrsIncremental(f.bankKeeper, f.stakingKeeper, f.ctx, 6, f.stakingKeeper.TokensFromConsensusPower(f.ctx, 200)) valAddrs := simtestutil.ConvertAddrsToValAddrs(addrDels) pks := simtestutil.CreateTestPubKeys(6) - tstaking := stakingtestutil.NewHelper(t, ctx, f.stakingKeeper) + tstaking := stakingtestutil.NewHelper(t, f.ctx, f.stakingKeeper) // create max (5) validators all with the same power for i := uint32(0); i < p.MaxValidators; i++ { @@ -98,46 +79,47 @@ func TestUnJailNotBonded(t *testing.T) { tstaking.CreateValidatorWithValPower(addr, val, 100, true) } - staking.EndBlocker(ctx, f.stakingKeeper) - ctx = ctx.WithBlockHeight(ctx.BlockHeight() + 1) + f.stakingKeeper.EndBlocker(f.ctx) + f.ctx = f.ctx.WithBlockHeight(f.ctx.BlockHeight() + 1) // create a 6th validator with less power than the cliff validator (won't be bonded) addr, val := valAddrs[5], pks[5] - amt := f.stakingKeeper.TokensFromConsensusPower(ctx, 50) + amt := f.stakingKeeper.TokensFromConsensusPower(f.ctx, 50) msg := tstaking.CreateValidatorMsg(addr, val, amt) msg.MinSelfDelegation = amt - res, err := tstaking.CreateValidatorWithMsg(ctx, msg) + msg.Description = stakingtypes.Description{Moniker: "TestValidator"} + res, err := tstaking.CreateValidatorWithMsg(f.ctx, msg) assert.NilError(t, err) assert.Assert(t, res != nil) - staking.EndBlocker(ctx, f.stakingKeeper) - ctx = ctx.WithBlockHeight(ctx.BlockHeight() + 1) + f.stakingKeeper.EndBlocker(f.ctx) + f.ctx = f.ctx.WithBlockHeight(f.ctx.BlockHeight() + 1) tstaking.CheckValidator(addr, stakingtypes.Unbonded, false) // unbond below minimum self-delegation assert.Equal(t, p.BondDenom, tstaking.Denom) - tstaking.Undelegate(sdk.AccAddress(addr), addr, f.stakingKeeper.TokensFromConsensusPower(ctx, 1), true) + tstaking.Undelegate(sdk.AccAddress(addr), addr, f.stakingKeeper.TokensFromConsensusPower(f.ctx, 1), true) - staking.EndBlocker(ctx, f.stakingKeeper) - ctx = ctx.WithBlockHeight(ctx.BlockHeight() + 1) + f.stakingKeeper.EndBlocker(f.ctx) + f.ctx = f.ctx.WithBlockHeight(f.ctx.BlockHeight() + 1) // verify that validator is jailed tstaking.CheckValidator(addr, -1, true) // verify we cannot unjail (yet) - assert.ErrorContains(t, f.slashingKeeper.Unjail(ctx, addr), "cannot be unjailed") + assert.ErrorContains(t, f.slashingKeeper.Unjail(f.ctx, addr), "cannot be unjailed") - staking.EndBlocker(ctx, f.stakingKeeper) - ctx = ctx.WithBlockHeight(ctx.BlockHeight() + 1) + f.stakingKeeper.EndBlocker(f.ctx) + f.ctx = f.ctx.WithBlockHeight(f.ctx.BlockHeight() + 1) // bond to meet minimum self-delegation tstaking.DelegateWithPower(sdk.AccAddress(addr), addr, 1) - staking.EndBlocker(ctx, f.stakingKeeper) - ctx = ctx.WithBlockHeight(ctx.BlockHeight() + 1) + f.stakingKeeper.EndBlocker(f.ctx) + f.ctx = f.ctx.WithBlockHeight(f.ctx.BlockHeight() + 1) // verify we can immediately unjail - assert.NilError(t, f.slashingKeeper.Unjail(ctx, addr)) + assert.NilError(t, f.slashingKeeper.Unjail(f.ctx, addr)) tstaking.CheckValidator(addr, -1, false) } @@ -149,45 +131,43 @@ func TestHandleNewValidator(t *testing.T) { t.Parallel() f := initFixture(t) - ctx := f.ctx - - addrDels := simtestutil.AddTestAddrsIncremental(f.bankKeeper, f.stakingKeeper, ctx, 1, f.stakingKeeper.TokensFromConsensusPower(ctx, 0)) + addrDels := simtestutil.AddTestAddrsIncremental(f.bankKeeper, f.stakingKeeper, f.ctx, 1, f.stakingKeeper.TokensFromConsensusPower(f.ctx, 0)) valAddrs := simtestutil.ConvertAddrsToValAddrs(addrDels) pks := simtestutil.CreateTestPubKeys(1) addr, val := valAddrs[0], pks[0] - tstaking := stakingtestutil.NewHelper(t, ctx, f.stakingKeeper) - ctx = ctx.WithBlockHeight(f.slashingKeeper.SignedBlocksWindow(ctx) + 1) + tstaking := stakingtestutil.NewHelper(t, f.ctx, f.stakingKeeper) + f.ctx = f.ctx.WithBlockHeight(f.slashingKeeper.SignedBlocksWindow(f.ctx) + 1) // Validator created amt := tstaking.CreateValidatorWithValPower(addr, val, 100, true) - staking.EndBlocker(ctx, f.stakingKeeper) + f.stakingKeeper.EndBlocker(f.ctx) assert.DeepEqual( - t, f.bankKeeper.GetAllBalances(ctx, sdk.AccAddress(addr)), - sdk.NewCoins(sdk.NewCoin(f.stakingKeeper.GetParams(ctx).BondDenom, InitTokens.Sub(amt))), + t, f.bankKeeper.GetAllBalances(f.ctx, sdk.AccAddress(addr)), + sdk.NewCoins(sdk.NewCoin(f.stakingKeeper.GetParams(f.ctx).BondDenom, InitTokens.Sub(amt))), ) - assert.DeepEqual(t, amt, f.stakingKeeper.Validator(ctx, addr).GetBondedTokens()) + assert.DeepEqual(t, amt, f.stakingKeeper.Validator(f.ctx, addr).GetBondedTokens()) // Now a validator, for two blocks - f.slashingKeeper.HandleValidatorSignature(ctx, val.Address(), 100, true) - ctx = ctx.WithBlockHeight(f.slashingKeeper.SignedBlocksWindow(ctx) + 2) - f.slashingKeeper.HandleValidatorSignature(ctx, val.Address(), 100, false) + f.slashingKeeper.HandleValidatorSignature(f.ctx, val.Address(), 100, true) + f.ctx = f.ctx.WithBlockHeight(f.slashingKeeper.SignedBlocksWindow(f.ctx) + 2) + f.slashingKeeper.HandleValidatorSignature(f.ctx, val.Address(), 100, false) - info, found := f.slashingKeeper.GetValidatorSigningInfo(ctx, sdk.ConsAddress(val.Address())) + info, found := f.slashingKeeper.GetValidatorSigningInfo(f.ctx, sdk.ConsAddress(val.Address())) assert.Assert(t, found) - assert.Equal(t, f.slashingKeeper.SignedBlocksWindow(ctx)+1, info.StartHeight) + assert.Equal(t, f.slashingKeeper.SignedBlocksWindow(f.ctx)+1, info.StartHeight) assert.Equal(t, int64(2), info.IndexOffset) assert.Equal(t, int64(1), info.MissedBlocksCounter) assert.Equal(t, time.Unix(0, 0).UTC(), info.JailedUntil) // validator should be bonded still, should not have been jailed or slashed - validator, _ := f.stakingKeeper.GetValidatorByConsAddr(ctx, sdk.GetConsAddress(val)) + validator, _ := f.stakingKeeper.GetValidatorByConsAddr(f.ctx, sdk.GetConsAddress(val)) assert.Equal(t, stakingtypes.Bonded, validator.GetStatus()) - bondPool := f.stakingKeeper.GetBondedPool(ctx) - expTokens := f.stakingKeeper.TokensFromConsensusPower(ctx, 100) + bondPool := f.stakingKeeper.GetBondedPool(f.ctx) + expTokens := f.stakingKeeper.TokensFromConsensusPower(f.ctx, 100) // adding genesis validator tokens - expTokens = expTokens.Add(f.stakingKeeper.TokensFromConsensusPower(ctx, 1)) - assert.Assert(t, expTokens.Equal(f.bankKeeper.GetBalance(ctx, bondPool.GetAddress(), f.stakingKeeper.BondDenom(ctx)).Amount)) + expTokens = expTokens.Add(f.stakingKeeper.TokensFromConsensusPower(f.ctx, 1)) + assert.Assert(t, expTokens.Equal(f.bankKeeper.GetBalance(f.ctx, bondPool.GetAddress(), f.stakingKeeper.BondDenom(f.ctx)).Amount)) } // Test a jailed validator being "down" twice @@ -196,50 +176,47 @@ func TestHandleAlreadyJailed(t *testing.T) { t.Parallel() f := initFixture(t) - // initial setup - ctx := f.ctx - - addrDels := simtestutil.AddTestAddrsIncremental(f.bankKeeper, f.stakingKeeper, ctx, 1, f.stakingKeeper.TokensFromConsensusPower(ctx, 200)) + addrDels := simtestutil.AddTestAddrsIncremental(f.bankKeeper, f.stakingKeeper, f.ctx, 1, f.stakingKeeper.TokensFromConsensusPower(f.ctx, 200)) valAddrs := simtestutil.ConvertAddrsToValAddrs(addrDels) pks := simtestutil.CreateTestPubKeys(1) addr, val := valAddrs[0], pks[0] power := int64(100) - tstaking := stakingtestutil.NewHelper(t, ctx, f.stakingKeeper) + tstaking := stakingtestutil.NewHelper(t, f.ctx, f.stakingKeeper) amt := tstaking.CreateValidatorWithValPower(addr, val, power, true) - staking.EndBlocker(ctx, f.stakingKeeper) + f.stakingKeeper.EndBlocker(f.ctx) // 1000 first blocks OK height := int64(0) - for ; height < f.slashingKeeper.SignedBlocksWindow(ctx); height++ { - ctx = ctx.WithBlockHeight(height) - f.slashingKeeper.HandleValidatorSignature(ctx, val.Address(), power, true) + for ; height < f.slashingKeeper.SignedBlocksWindow(f.ctx); height++ { + f.ctx = f.ctx.WithBlockHeight(height) + f.slashingKeeper.HandleValidatorSignature(f.ctx, val.Address(), power, true) } // 501 blocks missed - for ; height < f.slashingKeeper.SignedBlocksWindow(ctx)+(f.slashingKeeper.SignedBlocksWindow(ctx)-f.slashingKeeper.MinSignedPerWindow(ctx))+1; height++ { - ctx = ctx.WithBlockHeight(height) - f.slashingKeeper.HandleValidatorSignature(ctx, val.Address(), power, false) + for ; height < f.slashingKeeper.SignedBlocksWindow(f.ctx)+(f.slashingKeeper.SignedBlocksWindow(f.ctx)-f.slashingKeeper.MinSignedPerWindow(f.ctx))+1; height++ { + f.ctx = f.ctx.WithBlockHeight(height) + f.slashingKeeper.HandleValidatorSignature(f.ctx, val.Address(), power, false) } // end block - staking.EndBlocker(ctx, f.stakingKeeper) + f.stakingKeeper.EndBlocker(f.ctx) // validator should have been jailed and slashed - validator, _ := f.stakingKeeper.GetValidatorByConsAddr(ctx, sdk.GetConsAddress(val)) + validator, _ := f.stakingKeeper.GetValidatorByConsAddr(f.ctx, sdk.GetConsAddress(val)) assert.Equal(t, stakingtypes.Unbonding, validator.GetStatus()) // validator should have been slashed - resultingTokens := amt.Sub(f.stakingKeeper.TokensFromConsensusPower(ctx, 1)) + resultingTokens := amt.Sub(f.stakingKeeper.TokensFromConsensusPower(f.ctx, 1)) assert.DeepEqual(t, resultingTokens, validator.GetTokens()) // another block missed - ctx = ctx.WithBlockHeight(height) - f.slashingKeeper.HandleValidatorSignature(ctx, val.Address(), power, false) + f.ctx = f.ctx.WithBlockHeight(height) + f.slashingKeeper.HandleValidatorSignature(f.ctx, val.Address(), power, false) // validator should not have been slashed twice - validator, _ = f.stakingKeeper.GetValidatorByConsAddr(ctx, sdk.GetConsAddress(val)) + validator, _ = f.stakingKeeper.GetValidatorByConsAddr(f.ctx, sdk.GetConsAddress(val)) assert.DeepEqual(t, resultingTokens, validator.GetTokens()) } @@ -250,74 +227,75 @@ func TestValidatorDippingInAndOut(t *testing.T) { t.Parallel() f := initFixture(t) - // initial setup - ctx := f.ctx - params := f.stakingKeeper.GetParams(ctx) + params := f.stakingKeeper.GetParams(f.ctx) params.MaxValidators = 1 - f.stakingKeeper.SetParams(ctx, params) + f.stakingKeeper.SetParams(f.ctx, params) power := int64(100) pks := simtestutil.CreateTestPubKeys(3) - simtestutil.AddTestAddrsFromPubKeys(f.bankKeeper, f.stakingKeeper, ctx, pks, f.stakingKeeper.TokensFromConsensusPower(ctx, 200)) + simtestutil.AddTestAddrsFromPubKeys(f.bankKeeper, f.stakingKeeper, f.ctx, pks, f.stakingKeeper.TokensFromConsensusPower(f.ctx, 200)) addr, val := pks[0].Address(), pks[0] consAddr := sdk.ConsAddress(addr) - tstaking := stakingtestutil.NewHelper(t, ctx, f.stakingKeeper) + tstaking := stakingtestutil.NewHelper(t, f.ctx, f.stakingKeeper) valAddr := sdk.ValAddress(addr) tstaking.CreateValidatorWithValPower(valAddr, val, power, true) - validatorUpdates := staking.EndBlocker(ctx, f.stakingKeeper) + validatorUpdates, err := f.stakingKeeper.EndBlocker(f.ctx) + require.NoError(t, err) assert.Equal(t, 2, len(validatorUpdates)) tstaking.CheckValidator(valAddr, stakingtypes.Bonded, false) // 100 first blocks OK height := int64(0) for ; height < int64(100); height++ { - ctx = ctx.WithBlockHeight(height) - f.slashingKeeper.HandleValidatorSignature(ctx, val.Address(), power, true) + f.ctx = f.ctx.WithBlockHeight(height) + f.slashingKeeper.HandleValidatorSignature(f.ctx, val.Address(), power, true) } // kick first validator out of validator set tstaking.CreateValidatorWithValPower(sdk.ValAddress(pks[1].Address()), pks[1], power+1, true) - validatorUpdates = staking.EndBlocker(ctx, f.stakingKeeper) + validatorUpdates, err = f.stakingKeeper.EndBlocker(f.ctx) + require.NoError(t, err) assert.Equal(t, 2, len(validatorUpdates)) tstaking.CheckValidator(sdk.ValAddress(pks[1].Address()), stakingtypes.Bonded, false) tstaking.CheckValidator(valAddr, stakingtypes.Unbonding, false) // 600 more blocks happened - height = height + 600 - ctx = ctx.WithBlockHeight(height) + height += 600 + f.ctx = f.ctx.WithBlockHeight(height) // validator added back in tstaking.DelegateWithPower(sdk.AccAddress(pks[2].Address()), valAddr, 50) - validatorUpdates = staking.EndBlocker(ctx, f.stakingKeeper) + validatorUpdates, err = f.stakingKeeper.EndBlocker(f.ctx) + require.NoError(t, err) assert.Equal(t, 2, len(validatorUpdates)) tstaking.CheckValidator(valAddr, stakingtypes.Bonded, false) newPower := power + 50 // validator misses a block - f.slashingKeeper.HandleValidatorSignature(ctx, val.Address(), newPower, false) + f.slashingKeeper.HandleValidatorSignature(f.ctx, val.Address(), newPower, false) height++ // shouldn't be jailed/kicked yet tstaking.CheckValidator(valAddr, stakingtypes.Bonded, false) // validator misses an additional 500 more blocks within the SignedBlockWindow (here 1000 blocks). - latest := f.slashingKeeper.SignedBlocksWindow(ctx) + height + latest := f.slashingKeeper.SignedBlocksWindow(f.ctx) + height // misses 500 blocks + within the signing windows i.e. 700-1700 // validators misses all 1000 block of a SignedBlockWindows for ; height < latest+1; height++ { - ctx = ctx.WithBlockHeight(height) - f.slashingKeeper.HandleValidatorSignature(ctx, val.Address(), newPower, false) + f.ctx = f.ctx.WithBlockHeight(height) + f.slashingKeeper.HandleValidatorSignature(f.ctx, val.Address(), newPower, false) } // should now be jailed & kicked - staking.EndBlocker(ctx, f.stakingKeeper) + f.stakingKeeper.EndBlocker(f.ctx) tstaking.CheckValidator(valAddr, stakingtypes.Unbonding, true) // check all the signing information - signInfo, found := f.slashingKeeper.GetValidatorSigningInfo(ctx, consAddr) + signInfo, found := f.slashingKeeper.GetValidatorSigningInfo(f.ctx, consAddr) assert.Assert(t, found) assert.Equal(t, int64(700), signInfo.StartHeight) assert.Equal(t, int64(0), signInfo.MissedBlocksCounter) @@ -325,30 +303,30 @@ func TestValidatorDippingInAndOut(t *testing.T) { // some blocks pass height = int64(5000) - ctx = ctx.WithBlockHeight(height) + f.ctx = f.ctx.WithBlockHeight(height) // validator rejoins and starts signing again - f.stakingKeeper.Unjail(ctx, consAddr) + f.stakingKeeper.Unjail(f.ctx, consAddr) - f.slashingKeeper.HandleValidatorSignature(ctx, val.Address(), newPower, true) + f.slashingKeeper.HandleValidatorSignature(f.ctx, val.Address(), newPower, true) // validator should not be kicked since we reset counter/array when it was jailed - staking.EndBlocker(ctx, f.stakingKeeper) + f.stakingKeeper.EndBlocker(f.ctx) tstaking.CheckValidator(valAddr, stakingtypes.Bonded, false) // check start height is correctly set - signInfo, found = f.slashingKeeper.GetValidatorSigningInfo(ctx, consAddr) + signInfo, found = f.slashingKeeper.GetValidatorSigningInfo(f.ctx, consAddr) assert.Assert(t, found) assert.Equal(t, height, signInfo.StartHeight) // validator misses 501 blocks after SignedBlockWindow period (1000 blocks) - latest = f.slashingKeeper.SignedBlocksWindow(ctx) + height - for ; height < latest+f.slashingKeeper.MinSignedPerWindow(ctx); height++ { - ctx = ctx.WithBlockHeight(height) - f.slashingKeeper.HandleValidatorSignature(ctx, val.Address(), newPower, false) + latest = f.slashingKeeper.SignedBlocksWindow(f.ctx) + height + for ; height < latest+f.slashingKeeper.MinSignedPerWindow(f.ctx); height++ { + f.ctx = f.ctx.WithBlockHeight(height) + f.slashingKeeper.HandleValidatorSignature(f.ctx, val.Address(), newPower, false) } // validator should now be jailed & kicked - staking.EndBlocker(ctx, f.stakingKeeper) + f.stakingKeeper.EndBlocker(f.ctx) tstaking.CheckValidator(valAddr, stakingtypes.Unbonding, true) } diff --git a/tests/integration/staking/keeper/determinstic_test.go b/tests/integration/staking/keeper/determinstic_test.go index 23fb54c81490..ded82a8be2d4 100644 --- a/tests/integration/staking/keeper/determinstic_test.go +++ b/tests/integration/staking/keeper/determinstic_test.go @@ -88,9 +88,9 @@ func pubKeyGenerator() *rapid.Generator[ed25519.PubKey] { } func bondTypeGenerator() *rapid.Generator[stakingtypes.BondStatus] { - bond_types := []stakingtypes.BondStatus{stakingtypes.Bonded, stakingtypes.Unbonded, stakingtypes.Unbonding} + bondTypes := []stakingtypes.BondStatus{stakingtypes.Bonded, stakingtypes.Unbonded, stakingtypes.Unbonding} return rapid.Custom(func(t *rapid.T) stakingtypes.BondStatus { - return bond_types[rapid.IntRange(0, 2).Draw(t, "range")] + return bondTypes[rapid.IntRange(0, 2).Draw(t, "range")] }) } @@ -605,7 +605,7 @@ func TestGRPCHistoricalInfo(t *testing.T) { Height: height, } - testdata.DeterministicIterations(f.ctx, t, req, f.queryClient.HistoricalInfo, 1930, false) + testdata.DeterministicIterations(f.ctx, t, req, f.queryClient.HistoricalInfo, 1945, false) } func TestGRPCDelegatorValidators(t *testing.T) { diff --git a/tests/integration/staking/keeper/genesis_test.go b/tests/integration/staking/keeper/genesis_test.go index 95cc4c2e1794..d1a977327d9b 100644 --- a/tests/integration/staking/keeper/genesis_test.go +++ b/tests/integration/staking/keeper/genesis_test.go @@ -8,10 +8,10 @@ import ( "cosmossdk.io/simapp" abci "github.com/cometbft/cometbft/abci/types" cmtproto "github.com/cometbft/cometbft/proto/tendermint/types" + "github.com/stretchr/testify/require" "gotest.tools/v3/assert" codectypes "github.com/cosmos/cosmos-sdk/codec/types" - sdktestutil "github.com/cosmos/cosmos-sdk/testutil" sdk "github.com/cosmos/cosmos-sdk/types" "github.com/cosmos/cosmos-sdk/x/bank/testutil" "github.com/cosmos/cosmos-sdk/x/staking" @@ -137,7 +137,7 @@ func TestInitGenesis_PoolsBalanceMismatch(t *testing.T) { BondDenom: "stake", } - sdktestutil.AssertPanics(t, func() { + require.Panics(t, func() { // setting validator status to bonded so the balance counts towards bonded pool validator.Status = types.Bonded app.StakingKeeper.InitGenesis(ctx, &types.GenesisState{ @@ -148,7 +148,7 @@ func TestInitGenesis_PoolsBalanceMismatch(t *testing.T) { // "should panic because bonded pool balance is different from bonded pool coins", ) - sdktestutil.AssertPanics(t, func() { + require.Panics(t, func() { // setting validator status to unbonded so the balance counts towards not bonded pool validator.Status = types.Unbonded app.StakingKeeper.InitGenesis(ctx, &types.GenesisState{ diff --git a/tests/integration/staking/keeper/grpc_query_test.go b/tests/integration/staking/keeper/grpc_query_test.go index 643cd8befbf1..00a53638099a 100644 --- a/tests/integration/staking/keeper/grpc_query_test.go +++ b/tests/integration/staking/keeper/grpc_query_test.go @@ -401,17 +401,18 @@ func TestGRPCQueryValidatorDelegations(t *testing.T) { t.Run(fmt.Sprintf("Case %s", tc.msg), func(t *testing.T) { tc.malleate() res, err := queryClient.ValidatorDelegations(gocontext.Background(), req) - if tc.expPass && !tc.expErr { + switch { + case tc.expPass && !tc.expErr: assert.NilError(t, err) assert.Assert(t, len(res.DelegationResponses) == 1) assert.Assert(t, res.Pagination.NextKey != nil) assert.Equal(t, uint64(2), res.Pagination.Total) assert.Equal(t, addrVal1, res.DelegationResponses[0].Delegation.ValidatorAddress) assert.DeepEqual(t, sdk.NewCoin(sdk.DefaultBondDenom, delegation.Shares.TruncateInt()), res.DelegationResponses[0].Balance) - } else if !tc.expPass && !tc.expErr { + case !tc.expPass && !tc.expErr: assert.NilError(t, err) assert.Assert(t, res.DelegationResponses == nil) - } else { + default: assert.ErrorContains(t, err, tc.expErrMsg) assert.Assert(t, res == nil) } @@ -549,16 +550,17 @@ func TestGRPCQueryDelegatorUnbondingDelegations(t *testing.T) { t.Run(fmt.Sprintf("Case %s", tc.msg), func(t *testing.T) { tc.malleate() res, err := queryClient.DelegatorUnbondingDelegations(gocontext.Background(), req) - if tc.expPass && !tc.expErr { + switch { + case tc.expPass && !tc.expErr: assert.NilError(t, err) assert.Assert(t, res.Pagination.NextKey != nil) assert.Equal(t, uint64(2), res.Pagination.Total) assert.Assert(t, len(res.UnbondingResponses) == 1) assert.DeepEqual(t, unbond, res.UnbondingResponses[0]) - } else if !tc.expPass && !tc.expErr { + case !tc.expPass && !tc.expErr: assert.NilError(t, err) assert.Assert(t, res.UnbondingResponses == nil) - } else { + default: assert.ErrorContains(t, err, tc.expErrMsg) assert.Assert(t, res == nil) } @@ -747,17 +749,18 @@ func TestGRPCQueryRedelegations(t *testing.T) { t.Run(fmt.Sprintf("Case %s", tc.msg), func(t *testing.T) { tc.malleate() res, err := queryClient.Redelegations(gocontext.Background(), req) - if tc.expPass && !tc.expErr { + switch { + case tc.expPass && !tc.expErr: assert.NilError(t, err) assert.Assert(t, len(res.RedelegationResponses) == len(redel.Entries)) assert.Equal(t, redel.DelegatorAddress, res.RedelegationResponses[0].Redelegation.DelegatorAddress) assert.Equal(t, redel.ValidatorSrcAddress, res.RedelegationResponses[0].Redelegation.ValidatorSrcAddress) assert.Equal(t, redel.ValidatorDstAddress, res.RedelegationResponses[0].Redelegation.ValidatorDstAddress) assert.Assert(t, len(redel.Entries) == len(res.RedelegationResponses[0].Entries)) - } else if !tc.expPass && !tc.expErr { + case !tc.expPass && !tc.expErr: assert.NilError(t, err) assert.Assert(t, res.RedelegationResponses == nil) - } else { + default: assert.ErrorContains(t, err, tc.expErrMsg) assert.Assert(t, res == nil) } diff --git a/tests/integration/staking/keeper/msg_server_test.go b/tests/integration/staking/keeper/msg_server_test.go index 3ccd554d5bd9..50b3e9d3c47e 100644 --- a/tests/integration/staking/keeper/msg_server_test.go +++ b/tests/integration/staking/keeper/msg_server_test.go @@ -76,47 +76,58 @@ func TestCancelUnbondingDelegation(t *testing.T) { assert.DeepEqual(t, ubd, resUnbond) testCases := []struct { - Name string - ExceptErr bool + name string + exceptErr bool req types.MsgCancelUnbondingDelegation expErrMsg string }{ { - Name: "invalid height", - ExceptErr: true, + name: "entry not found at height", + exceptErr: true, req: types.MsgCancelUnbondingDelegation{ DelegatorAddress: resUnbond.DelegatorAddress, ValidatorAddress: resUnbond.ValidatorAddress, Amount: sdk.NewCoin(stakingKeeper.BondDenom(ctx), sdk.NewInt(4)), - CreationHeight: 0, + CreationHeight: 11, }, expErrMsg: "unbonding delegation entry is not found at block height", }, { - Name: "invalid coin", - ExceptErr: true, + name: "invalid height", + exceptErr: true, req: types.MsgCancelUnbondingDelegation{ DelegatorAddress: resUnbond.DelegatorAddress, ValidatorAddress: resUnbond.ValidatorAddress, - Amount: sdk.NewCoin("dump_coin", sdk.NewInt(4)), + Amount: sdk.NewCoin(stakingKeeper.BondDenom(ctx), sdk.NewInt(4)), CreationHeight: 0, }, + expErrMsg: "invalid height", + }, + { + name: "invalid coin", + exceptErr: true, + req: types.MsgCancelUnbondingDelegation{ + DelegatorAddress: resUnbond.DelegatorAddress, + ValidatorAddress: resUnbond.ValidatorAddress, + Amount: sdk.NewCoin("dump_coin", sdk.NewInt(4)), + CreationHeight: 10, + }, expErrMsg: "invalid coin denomination", }, { - Name: "validator not exists", - ExceptErr: true, + name: "validator not exists", + exceptErr: true, req: types.MsgCancelUnbondingDelegation{ DelegatorAddress: resUnbond.DelegatorAddress, ValidatorAddress: sdk.ValAddress(sdk.AccAddress("asdsad")).String(), Amount: unbondingAmount, - CreationHeight: 0, + CreationHeight: 10, }, expErrMsg: "validator does not exist", }, { - Name: "invalid delegator address", - ExceptErr: true, + name: "invalid delegator address", + exceptErr: true, req: types.MsgCancelUnbondingDelegation{ DelegatorAddress: "invalid_delegator_addrtess", ValidatorAddress: resUnbond.ValidatorAddress, @@ -126,8 +137,8 @@ func TestCancelUnbondingDelegation(t *testing.T) { expErrMsg: "decoding bech32 failed", }, { - Name: "invalid amount", - ExceptErr: true, + name: "invalid amount", + exceptErr: true, req: types.MsgCancelUnbondingDelegation{ DelegatorAddress: resUnbond.DelegatorAddress, ValidatorAddress: resUnbond.ValidatorAddress, @@ -137,8 +148,8 @@ func TestCancelUnbondingDelegation(t *testing.T) { expErrMsg: "amount is greater than the unbonding delegation entry balance", }, { - Name: "success", - ExceptErr: false, + name: "success", + exceptErr: false, req: types.MsgCancelUnbondingDelegation{ DelegatorAddress: resUnbond.DelegatorAddress, ValidatorAddress: resUnbond.ValidatorAddress, @@ -147,8 +158,8 @@ func TestCancelUnbondingDelegation(t *testing.T) { }, }, { - Name: "success", - ExceptErr: false, + name: "success", + exceptErr: false, req: types.MsgCancelUnbondingDelegation{ DelegatorAddress: resUnbond.DelegatorAddress, ValidatorAddress: resUnbond.ValidatorAddress, @@ -159,13 +170,13 @@ func TestCancelUnbondingDelegation(t *testing.T) { } for _, testCase := range testCases { - t.Run(testCase.Name, func(t *testing.T) { + t.Run(testCase.name, func(t *testing.T) { _, err := msgServer.CancelUnbondingDelegation(ctx, &testCase.req) - if testCase.ExceptErr { + if testCase.exceptErr { assert.ErrorContains(t, err, testCase.expErrMsg) } else { assert.NilError(t, err) - balanceForNotBondedPool := bankKeeper.GetBalance(ctx, sdk.AccAddress(notBondedPool.GetAddress()), bondDenom) + balanceForNotBondedPool := bankKeeper.GetBalance(ctx, notBondedPool.GetAddress(), bondDenom) assert.DeepEqual(t, balanceForNotBondedPool, moduleBalance.Sub(testCase.req.Amount)) moduleBalance = moduleBalance.Sub(testCase.req.Amount) } diff --git a/tests/integration/staking/keeper/slash_test.go b/tests/integration/staking/keeper/slash_test.go index e2944aa58815..04a5c60df317 100644 --- a/tests/integration/staking/keeper/slash_test.go +++ b/tests/integration/staking/keeper/slash_test.go @@ -7,9 +7,9 @@ import ( "cosmossdk.io/math" "cosmossdk.io/simapp" cmtproto "github.com/cometbft/cometbft/proto/tendermint/types" + "github.com/stretchr/testify/require" "gotest.tools/v3/assert" - sdktestutil "github.com/cosmos/cosmos-sdk/testutil" sdk "github.com/cosmos/cosmos-sdk/types" banktestutil "github.com/cosmos/cosmos-sdk/x/bank/testutil" "github.com/cosmos/cosmos-sdk/x/staking/keeper" @@ -297,7 +297,7 @@ func TestSlashWithUnbondingDelegation(t *testing.T) { // slash validator again // all originally bonded stake has been slashed, so this will have no effect // on the unbonding delegation, but it will slash stake bonded since the infraction - // this may not be the desirable behaviour, ref https://github.com/cosmos/cosmos-sdk/issues/1440 + // this may not be the desirable behavior, ref https://github.com/cosmos/cosmos-sdk/issues/1440 ctx = ctx.WithBlockHeight(13) app.StakingKeeper.Slash(ctx, consAddr, 9, 10, fraction) @@ -323,7 +323,7 @@ func TestSlashWithUnbondingDelegation(t *testing.T) { // slash validator again // all originally bonded stake has been slashed, so this will have no effect // on the unbonding delegation, but it will slash stake bonded since the infraction - // this may not be the desirable behaviour, ref https://github.com/cosmos/cosmos-sdk/issues/1440 + // this may not be the desirable behavior, ref https://github.com/cosmos/cosmos-sdk/issues/1440 ctx = ctx.WithBlockHeight(13) app.StakingKeeper.Slash(ctx, consAddr, 9, 10, fraction) @@ -382,7 +382,7 @@ func TestSlashWithRedelegation(t *testing.T) { _, found := app.StakingKeeper.GetValidatorByConsAddr(ctx, consAddr) assert.Assert(t, found) - sdktestutil.AssertNotPanics(t, func() { + require.NotPanics(t, func() { app.StakingKeeper.Slash(ctx, consAddr, 10, 10, fraction) }) burnAmount := sdk.NewDecFromInt(app.StakingKeeper.TokensFromConsensusPower(ctx, 10)).Mul(fraction).TruncateInt() @@ -415,7 +415,7 @@ func TestSlashWithRedelegation(t *testing.T) { _, found = app.StakingKeeper.GetValidatorByConsAddr(ctx, consAddr) assert.Assert(t, found) - sdktestutil.AssertNotPanics(t, func() { + require.NotPanics(t, func() { app.StakingKeeper.Slash(ctx, consAddr, 10, 10, math.LegacyOneDec()) }) burnAmount = app.StakingKeeper.TokensFromConsensusPower(ctx, 7) @@ -451,7 +451,7 @@ func TestSlashWithRedelegation(t *testing.T) { _, found = app.StakingKeeper.GetValidatorByConsAddr(ctx, consAddr) assert.Assert(t, found) - sdktestutil.AssertNotPanics(t, func() { + require.NotPanics(t, func() { app.StakingKeeper.Slash(ctx, consAddr, 10, 10, math.LegacyOneDec()) }) @@ -486,7 +486,7 @@ func TestSlashWithRedelegation(t *testing.T) { validator, _ = app.StakingKeeper.GetValidatorByConsAddr(ctx, consAddr) assert.Equal(t, validator.GetStatus(), types.Unbonding) - sdktestutil.AssertNotPanics(t, func() { + require.NotPanics(t, func() { app.StakingKeeper.Slash(ctx, consAddr, 10, 10, math.LegacyOneDec()) }) diff --git a/tests/integration/staking/keeper/unbonding_test.go b/tests/integration/staking/keeper/unbonding_test.go index bc0ea18ae888..28fec367058e 100644 --- a/tests/integration/staking/keeper/unbonding_test.go +++ b/tests/integration/staking/keeper/unbonding_test.go @@ -91,7 +91,7 @@ func doUnbondingDelegation( addrDels []sdk.AccAddress, addrVals []sdk.ValAddress, hookCalled *bool, -) (completionTime time.Time, bondedAmt math.Int, notBondedAmt math.Int) { +) (completionTime time.Time, bondedAmt, notBondedAmt math.Int) { // UNDELEGATE // Save original bonded and unbonded amounts bondedAmt1 := bankKeeper.GetBalance(ctx, stakingKeeper.GetBondedPool(ctx).GetAddress(), bondDenom).Amount @@ -378,7 +378,7 @@ func TestUnbondingDelegationOnHold1(t *testing.T) { notBondedAmt5 := app.BankKeeper.GetBalance(ctx, app.StakingKeeper.GetNotBondedPool(ctx).GetAddress(), bondDenom).Amount assert.Assert(math.IntEq(t, bondedAmt1, bondedAmt5)) - // Not bonded amount back to what it was originaly + // Not bonded amount back to what it was originally assert.Assert(math.IntEq(t, notBondedAmt1.SubRaw(1), notBondedAmt5)) } @@ -414,6 +414,6 @@ func TestUnbondingDelegationOnHold2(t *testing.T) { notBondedAmt5 := app.BankKeeper.GetBalance(ctx, app.StakingKeeper.GetNotBondedPool(ctx).GetAddress(), bondDenom).Amount assert.Assert(math.IntEq(t, bondedAmt1, bondedAmt5)) - // Not bonded amount back to what it was originaly + // Not bonded amount back to what it was originally assert.Assert(math.IntEq(t, notBondedAmt1.SubRaw(1), notBondedAmt5)) } diff --git a/tests/integration/staking/keeper/validator_bench_test.go b/tests/integration/staking/keeper/validator_bench_test.go index 3667987138e2..e7eb60c51216 100644 --- a/tests/integration/staking/keeper/validator_bench_test.go +++ b/tests/integration/staking/keeper/validator_bench_test.go @@ -7,7 +7,7 @@ func BenchmarkGetValidator(b *testing.B) { // panic: encoding/hex: odd length hex string powersNumber := 900 - var totalPower int64 = 0 + var totalPower int64 powers := make([]int64, powersNumber) for i := range powers { powers[i] = int64(i) diff --git a/tests/integration/staking/keeper/validator_test.go b/tests/integration/staking/keeper/validator_test.go index 7d41655fd65d..2b462860e060 100644 --- a/tests/integration/staking/keeper/validator_test.go +++ b/tests/integration/staking/keeper/validator_test.go @@ -13,7 +13,6 @@ import ( simtestutil "github.com/cosmos/cosmos-sdk/testutil/sims" sdk "github.com/cosmos/cosmos-sdk/types" banktestutil "github.com/cosmos/cosmos-sdk/x/bank/testutil" - "github.com/cosmos/cosmos-sdk/x/staking" "github.com/cosmos/cosmos-sdk/x/staking/keeper" "github.com/cosmos/cosmos-sdk/x/staking/testutil" "github.com/cosmos/cosmos-sdk/x/staking/types" @@ -48,7 +47,7 @@ func bootstrapValidatorTest(t testing.TB, power int64, numAddrs int) (*simapp.Si assert.NilError(t, err) // end block to unbond genesis validator - staking.EndBlocker(ctx, app.StakingKeeper) + app.StakingKeeper.EndBlocker(ctx) return app, ctx, addrDels, addrVals } diff --git a/tests/integration/tx/.gitignore b/tests/integration/tx/.gitignore new file mode 100644 index 000000000000..9309455bc5b4 --- /dev/null +++ b/tests/integration/tx/.gitignore @@ -0,0 +1 @@ +testdata/rapid diff --git a/tests/integration/tx/decode_test.go b/tests/integration/tx/decode_test.go new file mode 100644 index 000000000000..d3f38376b6b8 --- /dev/null +++ b/tests/integration/tx/decode_test.go @@ -0,0 +1,141 @@ +package tx + +import ( + "testing" + + "github.com/cosmos/cosmos-proto/rapidproto" + gogoproto "github.com/cosmos/gogoproto/proto" + "github.com/stretchr/testify/require" + "google.golang.org/protobuf/proto" + "pgregory.net/rapid" + + "cosmossdk.io/x/evidence" + feegrantmodule "cosmossdk.io/x/feegrant/module" + "cosmossdk.io/x/tx/decode" + "cosmossdk.io/x/upgrade" + "github.com/cosmos/cosmos-sdk/codec/legacy" + codectypes "github.com/cosmos/cosmos-sdk/codec/types" + "github.com/cosmos/cosmos-sdk/tests/integration/rapidgen" + "github.com/cosmos/cosmos-sdk/testutil/testdata" + sdk "github.com/cosmos/cosmos-sdk/types" + "github.com/cosmos/cosmos-sdk/types/module/testutil" + txtypes "github.com/cosmos/cosmos-sdk/types/tx" + "github.com/cosmos/cosmos-sdk/types/tx/signing" + "github.com/cosmos/cosmos-sdk/x/auth" + "github.com/cosmos/cosmos-sdk/x/auth/vesting" + authzmodule "github.com/cosmos/cosmos-sdk/x/authz/module" + "github.com/cosmos/cosmos-sdk/x/bank" + "github.com/cosmos/cosmos-sdk/x/consensus" + "github.com/cosmos/cosmos-sdk/x/distribution" + "github.com/cosmos/cosmos-sdk/x/gov" + groupmodule "github.com/cosmos/cosmos-sdk/x/group/module" + "github.com/cosmos/cosmos-sdk/x/mint" + "github.com/cosmos/cosmos-sdk/x/params" + "github.com/cosmos/cosmos-sdk/x/slashing" + "github.com/cosmos/cosmos-sdk/x/staking" +) + +// TestDecode tests that the tx decoder can decode all the txs in the test suite. +func TestDecode(t *testing.T) { + encCfg := testutil.MakeTestEncodingConfig( + auth.AppModuleBasic{}, authzmodule.AppModuleBasic{}, bank.AppModuleBasic{}, consensus.AppModuleBasic{}, + distribution.AppModuleBasic{}, evidence.AppModuleBasic{}, feegrantmodule.AppModuleBasic{}, + gov.AppModuleBasic{}, groupmodule.AppModuleBasic{}, mint.AppModuleBasic{}, params.AppModuleBasic{}, + slashing.AppModuleBasic{}, staking.AppModuleBasic{}, upgrade.AppModuleBasic{}, vesting.AppModuleBasic{}) + + fee := sdk.NewCoins(sdk.NewCoin("stake", sdk.NewInt(100))) + gas := uint64(200) + memo := "memo" + accSeq := uint64(2) + + _, pubkey, _ := testdata.KeyTestPubAddr() + anyPk, _ := codectypes.NewAnyWithValue(pubkey) + var signerInfo []*txtypes.SignerInfo + signerInfo = append(signerInfo, &txtypes.SignerInfo{ + PublicKey: anyPk, + ModeInfo: &txtypes.ModeInfo{ + Sum: &txtypes.ModeInfo_Single_{ + Single: &txtypes.ModeInfo_Single{ + Mode: signing.SignMode_SIGN_MODE_DIRECT, + }, + }, + }, + Sequence: accSeq, + }) + + authInfo := &txtypes.AuthInfo{ + Fee: &txtypes.Fee{Amount: fee, GasLimit: gas}, + SignerInfos: signerInfo, + } + + authInfoBytes, err := gogoproto.Marshal(authInfo) + require.NoError(t, err) + + for _, tt := range rapidgen.SignableTypes { + name := string(tt.Pulsar.ProtoReflect().Descriptor().FullName()) + t.Run(name, func(t *testing.T) { + gen := rapidproto.MessageGenerator(tt.Pulsar, tt.Opts) + rapid.Check(t, func(t *rapid.T) { + msg := gen.Draw(t, "msg") + gogo := tt.Gogo + sanity := tt.Pulsar + + protoBz, err := proto.Marshal(msg) + require.NoError(t, err) + + err = proto.Unmarshal(protoBz, sanity) + require.NoError(t, err) + + err = encCfg.Codec.Unmarshal(protoBz, gogo) + require.NoError(t, err) + + txBuilder := encCfg.TxConfig.NewTxBuilder() + + sig := signing.SignatureV2{ + PubKey: pubkey, + Data: &signing.SingleSignatureData{ + SignMode: signing.SignMode_SIGN_MODE_DIRECT, + Signature: legacy.Cdc.MustMarshal(pubkey), + }, + Sequence: accSeq, + } + + gogoMsg, ok := gogo.(sdk.Msg) + require.True(t, ok) + + err = txBuilder.SetMsgs(gogoMsg) + require.NoError(t, err) + txBuilder.SetFeeAmount(fee) + txBuilder.SetGasLimit(gas) + txBuilder.SetMemo(memo) + err = txBuilder.SetSignatures(sig) + require.NoError(t, err) + + tx := txBuilder.GetTx() + txBytes, err := encCfg.TxConfig.TxEncoder()(tx) + require.NoError(t, err) + decodeCtx, err := decode.NewDecoder(decode.Options{}) + require.NoError(t, err) + decodedTx, err := decodeCtx.Decode(txBytes) + require.NoError(t, err) + require.NotNil(t, decodedTx) + + require.Equal(t, authInfoBytes, decodedTx.TxRaw.AuthInfoBytes) + + anyGogoMsg, err := codectypes.NewAnyWithValue(gogoMsg) + require.NoError(t, err) + + txBody := &txtypes.TxBody{ + Memo: memo, + Messages: []*codectypes.Any{ + anyGogoMsg, + }, + } + bodyBytes, err := gogoproto.Marshal(txBody) + require.NoError(t, err) + + require.Equal(t, bodyBytes, decodedTx.TxRaw.BodyBytes) + }) + }) + } +} diff --git a/testutil/assert_helpers.go b/testutil/assert_helpers.go deleted file mode 100644 index 2c11d0f50b5c..000000000000 --- a/testutil/assert_helpers.go +++ /dev/null @@ -1,25 +0,0 @@ -package testutil - -import "testing" - -func AssertPanics(t *testing.T, f func()) { - panicked := false - defer func() { - if r := recover(); r != nil { - panicked = true - } - }() - f() - if !panicked { - t.Errorf("should panic") - } -} - -func AssertNotPanics(t *testing.T, f func()) { - defer func() { - if r := recover(); r != nil { - t.Errorf("should not panic: %v", r) - } - }() - f() -} diff --git a/testutil/cli/cmd.go b/testutil/cli/cmd.go index e571ce78454b..64c25be9b7de 100644 --- a/testutil/cli/cmd.go +++ b/testutil/cli/cmd.go @@ -4,10 +4,10 @@ import ( "context" "fmt" - cli2 "github.com/cometbft/cometbft/libs/cli" "github.com/spf13/cobra" "github.com/cosmos/cosmos-sdk/client" + "github.com/cosmos/cosmos-sdk/client/flags" "github.com/cosmos/cosmos-sdk/testutil" "github.com/cosmos/cosmos-sdk/x/bank/client/cli" ) @@ -37,7 +37,7 @@ func MsgSendExec(clientCtx client.Context, from, to, amount fmt.Stringer, extraA } func QueryBalancesExec(clientCtx client.Context, address fmt.Stringer, extraArgs ...string) (testutil.BufferWriter, error) { - args := []string{address.String(), fmt.Sprintf("--%s=json", cli2.OutputFlag)} + args := []string{address.String(), fmt.Sprintf("--%s=json", flags.FlagOutput)} args = append(args, extraArgs...) return ExecTestCLICmd(clientCtx, cli.GetBalancesCmd(), args) diff --git a/testutil/compare.go b/testutil/compare.go new file mode 100644 index 000000000000..3e795e8f3f5e --- /dev/null +++ b/testutil/compare.go @@ -0,0 +1,16 @@ +package testutil + +import ( + "testing" + + "github.com/google/go-cmp/cmp" + "github.com/stretchr/testify/require" + "google.golang.org/protobuf/testing/protocmp" +) + +// RequireProtoDeepEqual fails the test t if p1 and p2 are not equivalent protobuf messages. +// Where p1 and p2 are proto.Message or slices of proto.Message. +func RequireProtoDeepEqual(t *testing.T, p1, p2 interface{}) { + t.Helper() + require.Empty(t, cmp.Diff(p1, p2, protocmp.Transform())) +} diff --git a/testutil/context.go b/testutil/context.go index 47753a773b36..f2a9bdaf922f 100644 --- a/testutil/context.go +++ b/testutil/context.go @@ -17,7 +17,7 @@ import ( ) // DefaultContext creates a sdk.Context with a fresh MemDB that can be used in tests. -func DefaultContext(key storetypes.StoreKey, tkey storetypes.StoreKey) sdk.Context { +func DefaultContext(key, tkey storetypes.StoreKey) sdk.Context { db := dbm.NewMemDB() cms := store.NewCommitMultiStore(db, log.NewNopLogger(), metrics.NewNoOpMetrics()) cms.MountStoreWithDB(key, storetypes.StoreTypeIAVL, db) @@ -37,7 +37,7 @@ type TestContext struct { CMS store.CommitMultiStore } -func DefaultContextWithDB(t *testing.T, key storetypes.StoreKey, tkey storetypes.StoreKey) TestContext { +func DefaultContextWithDB(t testing.TB, key, tkey storetypes.StoreKey) TestContext { db := dbm.NewMemDB() cms := store.NewCommitMultiStore(db, log.NewNopLogger(), metrics.NewNoOpMetrics()) cms.MountStoreWithDB(key, storetypes.StoreTypeIAVL, db) diff --git a/testutil/integration/doc.go b/testutil/integration/doc.go new file mode 100644 index 000000000000..9bb3feef40f2 --- /dev/null +++ b/testutil/integration/doc.go @@ -0,0 +1,2 @@ +// Integration contains the integration test setup used for SDK modules. +package integration diff --git a/testutil/integration/example_test.go b/testutil/integration/example_test.go new file mode 100644 index 000000000000..02c888d41566 --- /dev/null +++ b/testutil/integration/example_test.go @@ -0,0 +1,193 @@ +package integration_test + +import ( + "fmt" + "io" + + "cosmossdk.io/log" + storetypes "cosmossdk.io/store/types" + + cmtproto "github.com/cometbft/cometbft/proto/tendermint/types" + + "github.com/google/go-cmp/cmp" + + "github.com/cosmos/cosmos-sdk/runtime" + "github.com/cosmos/cosmos-sdk/testutil/integration" + sdk "github.com/cosmos/cosmos-sdk/types" + moduletestutil "github.com/cosmos/cosmos-sdk/types/module/testutil" + "github.com/cosmos/cosmos-sdk/x/auth" + authkeeper "github.com/cosmos/cosmos-sdk/x/auth/keeper" + authsims "github.com/cosmos/cosmos-sdk/x/auth/simulation" + authtypes "github.com/cosmos/cosmos-sdk/x/auth/types" + "github.com/cosmos/cosmos-sdk/x/mint" + mintkeeper "github.com/cosmos/cosmos-sdk/x/mint/keeper" + minttypes "github.com/cosmos/cosmos-sdk/x/mint/types" +) + +// Example shows how to use the integration test framework to test the integration of SDK modules. +// Panics are used in this example, but in a real test case, you should use the testing.T object and assertions. +func Example() { + // in this example we are testing the integration of the following modules: + // - mint, which directly depends on auth, bank and staking + encodingCfg := moduletestutil.MakeTestEncodingConfig(auth.AppModuleBasic{}, mint.AppModuleBasic{}) + keys := storetypes.NewKVStoreKeys(authtypes.StoreKey, minttypes.StoreKey) + authority := authtypes.NewModuleAddress("gov").String() + + // replace the logger by testing values in a real test case (e.g. log.NewTestLogger(t)) + logger := log.NewNopLogger() + + cms := integration.CreateMultiStore(keys, logger) + newCtx := sdk.NewContext(cms, cmtproto.Header{}, true, logger) + + accountKeeper := authkeeper.NewAccountKeeper( + encodingCfg.Codec, + runtime.NewKVStoreService(keys[authtypes.StoreKey]), + authtypes.ProtoBaseAccount, + map[string][]string{minttypes.ModuleName: {authtypes.Minter}}, + "cosmos", + authority, + ) + + // subspace is nil because we don't test params (which is legacy anyway) + authModule := auth.NewAppModule(encodingCfg.Codec, accountKeeper, authsims.RandomGenesisAccounts, nil) + + // here bankkeeper and staking keeper is nil because we are not testing them + // subspace is nil because we don't test params (which is legacy anyway) + mintKeeper := mintkeeper.NewKeeper(encodingCfg.Codec, keys[minttypes.StoreKey], nil, accountKeeper, nil, authtypes.FeeCollectorName, authority) + mintModule := mint.NewAppModule(encodingCfg.Codec, mintKeeper, accountKeeper, nil, nil) + + // create the application and register all the modules from the previous step + integrationApp := integration.NewIntegrationApp( + newCtx, + logger, + keys, + encodingCfg.Codec, + authModule, mintModule, + ) + + // register the message and query servers + authtypes.RegisterMsgServer(integrationApp.MsgServiceRouter(), authkeeper.NewMsgServerImpl(accountKeeper)) + minttypes.RegisterMsgServer(integrationApp.MsgServiceRouter(), mintkeeper.NewMsgServerImpl(mintKeeper)) + minttypes.RegisterQueryServer(integrationApp.QueryHelper(), mintKeeper) + + params := minttypes.DefaultParams() + params.BlocksPerYear = 10000 + + // now we can use the application to test a mint message + result, err := integrationApp.RunMsg(&minttypes.MsgUpdateParams{ + Authority: authority, + Params: params, + }) + if err != nil { + panic(err) + } + + // in this example the result is an empty response, a nil check is enough + // in other cases, it is recommended to check the result value. + if result == nil { + panic(fmt.Errorf("unexpected nil result")) + } + + // we now check the result + resp := minttypes.MsgUpdateParamsResponse{} + err = encodingCfg.Codec.Unmarshal(result.Value, &resp) + if err != nil { + panic(err) + } + + sdkCtx := sdk.UnwrapSDKContext(integrationApp.Context()) + + // we should also check the state of the application + got := mintKeeper.GetParams(sdkCtx) + if diff := cmp.Diff(got, params); diff != "" { + panic(diff) + } + fmt.Println(got.BlocksPerYear) + // Output: 10000 +} + +// ExampleOneModule shows how to use the integration test framework to test the integration of a single module. +// That module has no dependency on other modules. +func Example_oneModule() { + // in this example we are testing the integration of the auth module: + encodingCfg := moduletestutil.MakeTestEncodingConfig(auth.AppModuleBasic{}) + keys := storetypes.NewKVStoreKeys(authtypes.StoreKey) + authority := authtypes.NewModuleAddress("gov").String() + + // replace the logger by testing values in a real test case (e.g. log.NewTestLogger(t)) + logger := log.NewLogger(io.Discard) + + cms := integration.CreateMultiStore(keys, logger) + newCtx := sdk.NewContext(cms, cmtproto.Header{}, true, logger) + + accountKeeper := authkeeper.NewAccountKeeper( + encodingCfg.Codec, + runtime.NewKVStoreService(keys[authtypes.StoreKey]), + authtypes.ProtoBaseAccount, + map[string][]string{minttypes.ModuleName: {authtypes.Minter}}, + "cosmos", + authority, + ) + + // subspace is nil because we don't test params (which is legacy anyway) + authModule := auth.NewAppModule(encodingCfg.Codec, accountKeeper, authsims.RandomGenesisAccounts, nil) + + // create the application and register all the modules from the previous step + integrationApp := integration.NewIntegrationApp( + newCtx, + logger, + keys, + encodingCfg.Codec, + authModule, + ) + + // register the message and query servers + authtypes.RegisterMsgServer(integrationApp.MsgServiceRouter(), authkeeper.NewMsgServerImpl(accountKeeper)) + + params := authtypes.DefaultParams() + params.MaxMemoCharacters = 1000 + + // now we can use the application to test a mint message + result, err := integrationApp.RunMsg(&authtypes.MsgUpdateParams{ + Authority: authority, + Params: params, + }, + // this allows to the begin and end blocker of the module before and after the message + integration.WithAutomaticBeginEndBlock(), + // this allows to commit the state after the message + integration.WithAutomaticCommit(), + ) + if err != nil { + panic(err) + } + + // verify that the begin and end blocker were called + // NOTE: in this example, we are testing auth, which doesn't have any begin or end blocker + // so verifying the block height is enough + if integrationApp.LastBlockHeight() != 2 { + panic(fmt.Errorf("expected block height to be 2, got %d", integrationApp.LastBlockHeight())) + } + + // in this example the result is an empty response, a nil check is enough + // in other cases, it is recommended to check the result value. + if result == nil { + panic(fmt.Errorf("unexpected nil result")) + } + + // we now check the result + resp := authtypes.MsgUpdateParamsResponse{} + err = encodingCfg.Codec.Unmarshal(result.Value, &resp) + if err != nil { + panic(err) + } + + sdkCtx := sdk.UnwrapSDKContext(integrationApp.Context()) + + // we should also check the state of the application + got := accountKeeper.GetParams(sdkCtx) + if diff := cmp.Diff(got, params); diff != "" { + panic(diff) + } + fmt.Println(got.MaxMemoCharacters) + // Output: 1000 +} diff --git a/testutil/integration/options.go b/testutil/integration/options.go new file mode 100644 index 000000000000..a67327c01b21 --- /dev/null +++ b/testutil/integration/options.go @@ -0,0 +1,25 @@ +package integration + +// Config is the configuration for the integration app. +type Config struct { + AutomaticBeginEndBlock bool + AutomaticCommit bool +} + +// Option is a function that can be used to configure the integration app. +type Option func(*Config) + +// WithAutomaticBlockCreation enables begin/end block calls. +func WithAutomaticBeginEndBlock() Option { + return func(cfg *Config) { + cfg.AutomaticBeginEndBlock = true + } +} + +// WithAutomaticCommit enables automatic commit. +// This means that the integration app will automatically commit the state after each msgs. +func WithAutomaticCommit() Option { + return func(cfg *Config) { + cfg.AutomaticCommit = true + } +} diff --git a/testutil/integration/router.go b/testutil/integration/router.go new file mode 100644 index 000000000000..efae2d5cc9b7 --- /dev/null +++ b/testutil/integration/router.go @@ -0,0 +1,161 @@ +package integration + +import ( + "context" + "fmt" + + cmtabcitypes "github.com/cometbft/cometbft/abci/types" + cmtproto "github.com/cometbft/cometbft/proto/tendermint/types" + + "cosmossdk.io/log" + "cosmossdk.io/store" + "cosmossdk.io/store/metrics" + storetypes "cosmossdk.io/store/types" + dbm "github.com/cosmos/cosmos-db" + + "github.com/cosmos/cosmos-sdk/baseapp" + "github.com/cosmos/cosmos-sdk/codec" + codectypes "github.com/cosmos/cosmos-sdk/codec/types" + sdk "github.com/cosmos/cosmos-sdk/types" + "github.com/cosmos/cosmos-sdk/types/module" + authtx "github.com/cosmos/cosmos-sdk/x/auth/tx" +) + +const appName = "integration-app" + +// App is a test application that can be used to test the integration of modules. +type App struct { + *baseapp.BaseApp + + ctx sdk.Context + logger log.Logger + queryHelper *baseapp.QueryServiceTestHelper +} + +// NewIntegrationApp creates an application for testing purposes. This application is able to route messages to their respective handlers. +func NewIntegrationApp(sdkCtx sdk.Context, logger log.Logger, keys map[string]*storetypes.KVStoreKey, appCodec codec.Codec, modules ...module.AppModule) *App { + db := dbm.NewMemDB() + + interfaceRegistry := codectypes.NewInterfaceRegistry() + for _, module := range modules { + module.RegisterInterfaces(interfaceRegistry) + } + + txConfig := authtx.NewTxConfig(codec.NewProtoCodec(interfaceRegistry), authtx.DefaultSignModes) + bApp := baseapp.NewBaseApp(appName, logger, db, txConfig.TxDecoder(), baseapp.SetChainID(appName)) + bApp.MountKVStores(keys) + + bApp.SetInitChainer(func(ctx sdk.Context, req cmtabcitypes.RequestInitChain) (cmtabcitypes.ResponseInitChain, error) { + for _, mod := range modules { + if m, ok := mod.(module.HasGenesis); ok { + m.InitGenesis(ctx, appCodec, m.DefaultGenesis(appCodec)) + } + } + + return cmtabcitypes.ResponseInitChain{}, nil + }) + + moduleManager := module.NewManager(modules...) + bApp.SetBeginBlocker(func(_ sdk.Context, req cmtabcitypes.RequestBeginBlock) (cmtabcitypes.ResponseBeginBlock, error) { + return moduleManager.BeginBlock(sdkCtx, req) + }) + bApp.SetEndBlocker(func(_ sdk.Context, req cmtabcitypes.RequestEndBlock) (cmtabcitypes.ResponseEndBlock, error) { + return moduleManager.EndBlock(sdkCtx, req) + }) + + router := baseapp.NewMsgServiceRouter() + router.SetInterfaceRegistry(interfaceRegistry) + bApp.SetMsgServiceRouter(router) + + if err := bApp.LoadLatestVersion(); err != nil { + panic(fmt.Errorf("failed to load application version from store: %w", err)) + } + + bApp.InitChain(cmtabcitypes.RequestInitChain{ChainId: appName}) + bApp.Commit() + + ctx := sdkCtx.WithBlockHeader(cmtproto.Header{ChainID: appName}).WithIsCheckTx(true) + + return &App{ + BaseApp: bApp, + + logger: logger, + ctx: ctx, + queryHelper: baseapp.NewQueryServerTestHelper(ctx, interfaceRegistry), + } +} + +// RunMsg allows to run a message and return the response. +// In order to run a message, the application must have a handler for it. +// These handlers are registered on the application message service router. +// The result of the message execution is returned as a Any type. +// That any type can be unmarshaled to the expected response type. +// If the message execution fails, an error is returned. +func (app *App) RunMsg(msg sdk.Msg, option ...Option) (*codectypes.Any, error) { + // set options + cfg := Config{} + for _, opt := range option { + opt(&cfg) + } + + if cfg.AutomaticCommit { + defer app.Commit() + } + + if cfg.AutomaticBeginEndBlock { + height := app.LastBlockHeight() + 1 + app.logger.Info("Running beging block", "height", height) + app.BeginBlock(cmtabcitypes.RequestBeginBlock{Header: cmtproto.Header{Height: height, ChainID: appName}}) + defer func() { + app.logger.Info("Running end block", "height", height) + app.EndBlock(cmtabcitypes.RequestEndBlock{}) + }() + } + + app.logger.Info("Running msg", "msg", msg.String()) + + handler := app.MsgServiceRouter().Handler(msg) + if handler == nil { + return nil, fmt.Errorf("handler is nil, can't route message %s: %+v", sdk.MsgTypeURL(msg), msg) + } + + msgResult, err := handler(app.ctx, msg) + if err != nil { + return nil, fmt.Errorf("failed to execute message %s: %w", sdk.MsgTypeURL(msg), err) + } + + var response *codectypes.Any + if len(msgResult.MsgResponses) > 0 { + msgResponse := msgResult.MsgResponses[0] + if msgResponse == nil { + return nil, fmt.Errorf("got nil msg response %s in message result: %s", sdk.MsgTypeURL(msg), msgResult.String()) + } + + response = msgResponse + } + + return response, nil +} + +// Context returns the application context. +// It can be unwraped to a sdk.Context, with the sdk.UnwrapSDKContext function. +func (app *App) Context() context.Context { + return app.ctx +} + +// QueryHelper returns the application query helper. +// It can be used when registering query services. +func (app *App) QueryHelper() *baseapp.QueryServiceTestHelper { + return app.queryHelper +} + +// CreateMultiStore is a helper for setting up multiple stores for provided modules. +func CreateMultiStore(keys map[string]*storetypes.KVStoreKey, logger log.Logger) storetypes.CommitMultiStore { + db := dbm.NewMemDB() + cms := store.NewCommitMultiStore(db, logger, metrics.NewNoOpMetrics()) + for key := range keys { + cms.MountStoreWithDB(keys[key], storetypes.StoreTypeIAVL, db) + } + _ = cms.LoadLatestVersion() + return cms +} diff --git a/testutil/mock/types_module_module.go b/testutil/mock/types_module_module.go index 8b3a79c80fa9..c406366748c0 100644 --- a/testutil/mock/types_module_module.go +++ b/testutil/mock/types_module_module.go @@ -5,6 +5,7 @@ package mock import ( + context "context" json "encoding/json" reflect "reflect" @@ -879,3 +880,119 @@ func (mr *MockEndBlockAppModuleMockRecorder) RegisterLegacyAminoCodec(arg0 inter mr.mock.ctrl.T.Helper() return mr.mock.ctrl.RecordCallWithMethodType(mr.mock, "RegisterLegacyAminoCodec", reflect.TypeOf((*MockEndBlockAppModule)(nil).RegisterLegacyAminoCodec), arg0) } + +// MockHasABCIEndblock is a mock of HasABCIEndblock interface. +type MockHasABCIEndblock struct { + ctrl *gomock.Controller + recorder *MockHasABCIEndblockMockRecorder +} + +// MockHasABCIEndblockMockRecorder is the mock recorder for MockHasABCIEndblock. +type MockHasABCIEndblockMockRecorder struct { + mock *MockHasABCIEndblock +} + +// NewMockHasABCIEndblock creates a new mock instance. +func NewMockHasABCIEndblock(ctrl *gomock.Controller) *MockHasABCIEndblock { + mock := &MockHasABCIEndblock{ctrl: ctrl} + mock.recorder = &MockHasABCIEndblockMockRecorder{mock} + return mock +} + +// EXPECT returns an object that allows the caller to indicate expected use. +func (m *MockHasABCIEndblock) EXPECT() *MockHasABCIEndblockMockRecorder { + return m.recorder +} + +// EndBlock mocks base method. +func (m *MockHasABCIEndblock) EndBlock(arg0 context.Context) ([]types.ValidatorUpdate, error) { + m.ctrl.T.Helper() + ret := m.ctrl.Call(m, "EndBlock", arg0) + ret0, _ := ret[0].([]types.ValidatorUpdate) + ret1, _ := ret[1].(error) + return ret0, ret1 +} + +// EndBlock indicates an expected call of EndBlock. +func (mr *MockHasABCIEndblockMockRecorder) EndBlock(arg0 interface{}) *gomock.Call { + mr.mock.ctrl.T.Helper() + return mr.mock.ctrl.RecordCallWithMethodType(mr.mock, "EndBlock", reflect.TypeOf((*MockHasABCIEndblock)(nil).EndBlock), arg0) +} + +// GetQueryCmd mocks base method. +func (m *MockHasABCIEndblock) GetQueryCmd() *cobra.Command { + m.ctrl.T.Helper() + ret := m.ctrl.Call(m, "GetQueryCmd") + ret0, _ := ret[0].(*cobra.Command) + return ret0 +} + +// GetQueryCmd indicates an expected call of GetQueryCmd. +func (mr *MockHasABCIEndblockMockRecorder) GetQueryCmd() *gomock.Call { + mr.mock.ctrl.T.Helper() + return mr.mock.ctrl.RecordCallWithMethodType(mr.mock, "GetQueryCmd", reflect.TypeOf((*MockHasABCIEndblock)(nil).GetQueryCmd)) +} + +// GetTxCmd mocks base method. +func (m *MockHasABCIEndblock) GetTxCmd() *cobra.Command { + m.ctrl.T.Helper() + ret := m.ctrl.Call(m, "GetTxCmd") + ret0, _ := ret[0].(*cobra.Command) + return ret0 +} + +// GetTxCmd indicates an expected call of GetTxCmd. +func (mr *MockHasABCIEndblockMockRecorder) GetTxCmd() *gomock.Call { + mr.mock.ctrl.T.Helper() + return mr.mock.ctrl.RecordCallWithMethodType(mr.mock, "GetTxCmd", reflect.TypeOf((*MockHasABCIEndblock)(nil).GetTxCmd)) +} + +// Name mocks base method. +func (m *MockHasABCIEndblock) Name() string { + m.ctrl.T.Helper() + ret := m.ctrl.Call(m, "Name") + ret0, _ := ret[0].(string) + return ret0 +} + +// Name indicates an expected call of Name. +func (mr *MockHasABCIEndblockMockRecorder) Name() *gomock.Call { + mr.mock.ctrl.T.Helper() + return mr.mock.ctrl.RecordCallWithMethodType(mr.mock, "Name", reflect.TypeOf((*MockHasABCIEndblock)(nil).Name)) +} + +// RegisterGRPCGatewayRoutes mocks base method. +func (m *MockHasABCIEndblock) RegisterGRPCGatewayRoutes(arg0 client.Context, arg1 *runtime.ServeMux) { + m.ctrl.T.Helper() + m.ctrl.Call(m, "RegisterGRPCGatewayRoutes", arg0, arg1) +} + +// RegisterGRPCGatewayRoutes indicates an expected call of RegisterGRPCGatewayRoutes. +func (mr *MockHasABCIEndblockMockRecorder) RegisterGRPCGatewayRoutes(arg0, arg1 interface{}) *gomock.Call { + mr.mock.ctrl.T.Helper() + return mr.mock.ctrl.RecordCallWithMethodType(mr.mock, "RegisterGRPCGatewayRoutes", reflect.TypeOf((*MockHasABCIEndblock)(nil).RegisterGRPCGatewayRoutes), arg0, arg1) +} + +// RegisterInterfaces mocks base method. +func (m *MockHasABCIEndblock) RegisterInterfaces(arg0 types0.InterfaceRegistry) { + m.ctrl.T.Helper() + m.ctrl.Call(m, "RegisterInterfaces", arg0) +} + +// RegisterInterfaces indicates an expected call of RegisterInterfaces. +func (mr *MockHasABCIEndblockMockRecorder) RegisterInterfaces(arg0 interface{}) *gomock.Call { + mr.mock.ctrl.T.Helper() + return mr.mock.ctrl.RecordCallWithMethodType(mr.mock, "RegisterInterfaces", reflect.TypeOf((*MockHasABCIEndblock)(nil).RegisterInterfaces), arg0) +} + +// RegisterLegacyAminoCodec mocks base method. +func (m *MockHasABCIEndblock) RegisterLegacyAminoCodec(arg0 *codec.LegacyAmino) { + m.ctrl.T.Helper() + m.ctrl.Call(m, "RegisterLegacyAminoCodec", arg0) +} + +// RegisterLegacyAminoCodec indicates an expected call of RegisterLegacyAminoCodec. +func (mr *MockHasABCIEndblockMockRecorder) RegisterLegacyAminoCodec(arg0 interface{}) *gomock.Call { + mr.mock.ctrl.T.Helper() + return mr.mock.ctrl.RecordCallWithMethodType(mr.mock, "RegisterLegacyAminoCodec", reflect.TypeOf((*MockHasABCIEndblock)(nil).RegisterLegacyAminoCodec), arg0) +} diff --git a/testutil/network/util.go b/testutil/network/util.go index 247a7ffccf92..7c5cdc800728 100644 --- a/testutil/network/util.go +++ b/testutil/network/util.go @@ -80,7 +80,7 @@ func startInProcess(cfg Config, val *Validator) error { app.RegisterTxService(val.ClientCtx) app.RegisterTendermintService(val.ClientCtx) - app.RegisterNodeService(val.ClientCtx) + app.RegisterNodeService(val.ClientCtx, *val.AppConfig) } ctx := context.Background() @@ -196,14 +196,14 @@ func initGenFiles(cfg Config, genAccounts []authtypes.GenesisAccount, genBalance return nil } -func writeFile(name string, dir string, contents []byte) error { +func writeFile(name, dir string, contents []byte) error { file := filepath.Join(dir, name) if err := os.MkdirAll(dir, 0o755); err != nil { return fmt.Errorf("could not create directory %q: %w", dir, err) } - if err := os.WriteFile(file, contents, 0o644); err != nil { //nolint: gosec + if err := os.WriteFile(file, contents, 0o600); err != nil { return err } diff --git a/testutil/rest.go b/testutil/rest.go index b3c52e3adbc3..6b8066aafbb9 100644 --- a/testutil/rest.go +++ b/testutil/rest.go @@ -42,7 +42,7 @@ func GetRequestWithHeaders(url string, headers map[string]string) ([]byte, error // GetRequest defines a wrapper around an HTTP GET request with a provided URL. // An error is returned if the request or reading the body fails. func GetRequest(url string) ([]byte, error) { - res, err := http.Get(url) //nolint:gosec + res, err := http.Get(url) //nolint:gosec // only used for testing if err != nil { return nil, err } @@ -60,8 +60,8 @@ func GetRequest(url string) ([]byte, error) { // PostRequest defines a wrapper around an HTTP POST request with a provided URL and data. // An error is returned if the request or reading the body fails. -func PostRequest(url string, contentType string, data []byte) ([]byte, error) { - res, err := http.Post(url, contentType, bytes.NewBuffer(data)) //nolint:gosec +func PostRequest(url, contentType string, data []byte) ([]byte, error) { + res, err := http.Post(url, contentType, bytes.NewBuffer(data)) //nolint:gosec // only used for testing if err != nil { return nil, fmt.Errorf("error while sending post request: %w", err) } diff --git a/testutil/sims/address_helpers.go b/testutil/sims/address_helpers.go index 8157d30586f6..52f1db8faffe 100644 --- a/testutil/sims/address_helpers.go +++ b/testutil/sims/address_helpers.go @@ -100,7 +100,7 @@ func CreateRandomAccounts(accNum int) []sdk.AccAddress { return testAddrs } -func TestAddr(addr string, bech string) (sdk.AccAddress, error) { +func TestAddr(addr, bech string) (sdk.AccAddress, error) { res, err := sdk.AccAddressFromHexUnsafe(addr) if err != nil { return nil, err diff --git a/testutil/sims/simulation_helpers.go b/testutil/sims/simulation_helpers.go index 055ba1439642..72bbde88a905 100644 --- a/testutil/sims/simulation_helpers.go +++ b/testutil/sims/simulation_helpers.go @@ -16,6 +16,7 @@ import ( sdk "github.com/cosmos/cosmos-sdk/types" "github.com/cosmos/cosmos-sdk/types/kv" "github.com/cosmos/cosmos-sdk/types/module" + moduletestutil "github.com/cosmos/cosmos-sdk/types/module/testutil" simtypes "github.com/cosmos/cosmos-sdk/types/simulation" ) @@ -53,6 +54,7 @@ func SimulationOperations(app runtime.AppI, cdc codec.JSONCodec, config simtypes simState := module.SimulationState{ AppParams: make(simtypes.AppParams), Cdc: cdc, + TxConfig: moduletestutil.MakeTestTxConfig(), BondDenom: sdk.DefaultBondDenom, } @@ -68,7 +70,7 @@ func SimulationOperations(app runtime.AppI, cdc codec.JSONCodec, config simtypes } } - simState.LegacyProposalContents = app.SimulationManager().GetProposalContents(simState) //nolint:staticcheck + simState.LegacyProposalContents = app.SimulationManager().GetProposalContents(simState) //nolint:staticcheck // used for legacy testing simState.ProposalMsgs = app.SimulationManager().GetProposalMsgs(simState) return app.SimulationManager().WeightedOperations(simState) } @@ -131,7 +133,7 @@ func GetSimulationLog(storeName string, sdr simtypes.StoreDecoderRegistry, kvAs, // DiffKVStores compares two KVstores and returns all the key/value pairs // that differ from one another. It also skips value comparison for a set of provided prefixes. -func DiffKVStores(a storetypes.KVStore, b storetypes.KVStore, prefixesToSkip [][]byte) (kvAs, kvBs []kv.Pair) { +func DiffKVStores(a, b storetypes.KVStore, prefixesToSkip [][]byte) (kvAs, kvBs []kv.Pair) { iterA := a.Iterator(nil, nil) defer iterA.Close() diff --git a/testutil/sims/simulation_helpers_test.go b/testutil/sims/simulation_helpers_test.go index 55cc77b439aa..d60a720f2e26 100644 --- a/testutil/sims/simulation_helpers_test.go +++ b/testutil/sims/simulation_helpers_test.go @@ -85,7 +85,7 @@ func TestDiffKVStores(t *testing.T) { // Same keys, different value. Comparisons will be nil as prefixes are skipped. prefix := []byte("prefix:") - k1Prefixed := append(prefix, k1...) //nolint:gocritic // append is fine here + k1Prefixed := append(prefix, k1...) store1.Set(k1Prefixed, v1) store2.Set(k1Prefixed, v2) checkDiffResults(t, store1, store2) diff --git a/testutil/sims/tx_helpers.go b/testutil/sims/tx_helpers.go index e6daeb06cc85..415ea292be4a 100644 --- a/testutil/sims/tx_helpers.go +++ b/testutil/sims/tx_helpers.go @@ -26,7 +26,10 @@ func GenSignedMockTx(r *rand.Rand, txConfig client.TxConfig, msgs []sdk.Msg, fee // create a random length memo memo := simulation.RandStringOfLength(r, simulation.RandIntBetween(r, 0, 100)) - signMode := txConfig.SignModeHandler().DefaultMode() + signMode, err := authsign.APISignModeToInternal(txConfig.SignModeHandler().DefaultMode()) + if err != nil { + return nil, err + } // 1st round: set SignatureV2 with empty signatures, to set correct // signer infos. @@ -41,7 +44,7 @@ func GenSignedMockTx(r *rand.Rand, txConfig client.TxConfig, msgs []sdk.Msg, fee } tx := txConfig.NewTxBuilder() - err := tx.SetMsgs(msgs...) + err = tx.SetMsgs(msgs...) if err != nil { return nil, err } @@ -63,7 +66,9 @@ func GenSignedMockTx(r *rand.Rand, txConfig client.TxConfig, msgs []sdk.Msg, fee PubKey: p.PubKey(), } - signBytes, err := authsign.GetSignBytesWithContext(txConfig.SignModeHandler(), context.Background(), signMode, signerData, tx.GetTx()) + signBytes, err := authsign.GetSignBytesAdapter( + context.Background(), txConfig.TxEncoder(), txConfig.SignModeHandler(), signMode, signerData, + tx.GetTx()) if err != nil { panic(err) } diff --git a/testutil/testdata/grpc_query.go b/testutil/testdata/grpc_query.go index fade8fa7de29..522e28d59c21 100644 --- a/testutil/testdata/grpc_query.go +++ b/testutil/testdata/grpc_query.go @@ -66,7 +66,7 @@ func (m *TestAnyResponse) UnpackInterfaces(unpacker types.AnyUnpacker) error { // 2. That the gas consumption of the query is the same. When // `gasOverwrite` is set to true, we also check that this consumed // gas value is equal to the hardcoded `gasConsumed`. -func DeterministicIterations[request proto.Message, response proto.Message]( +func DeterministicIterations[request, response proto.Message]( ctx sdk.Context, t *testing.T, req request, diff --git a/testutil/testdata/testpb/tx.proto b/testutil/testdata/testpb/tx.proto index 464e3390478b..72df915b1363 100644 --- a/testutil/testdata/testpb/tx.proto +++ b/testutil/testdata/testpb/tx.proto @@ -1,6 +1,7 @@ syntax = "proto3"; package testpb; +import "amino/amino.proto"; import "gogoproto/gogo.proto"; import "testpb/testdata.proto"; import "cosmos/msg/v1/msg.proto"; @@ -30,5 +31,7 @@ message MsgCreateDogResponse { // https://github.com/cosmos/cosmos-sdk/issues/6213. message TestMsg { option (gogoproto.goproto_getters) = false; + option (cosmos.msg.v1.signer) = "signers"; + option (amino.name) = "testpb/TestMsg"; repeated string signers = 1; } diff --git a/testutil/testdata/testpb/tx.pulsar.go b/testutil/testdata/testpb/tx.pulsar.go index b0d653076627..5e4213c4802a 100644 --- a/testutil/testdata/testpb/tx.pulsar.go +++ b/testutil/testdata/testpb/tx.pulsar.go @@ -2,6 +2,7 @@ package testpb import ( + _ "cosmossdk.io/api/amino" _ "cosmossdk.io/api/cosmos/msg/v1" fmt "fmt" runtime "github.com/cosmos/cosmos-proto/runtime" @@ -1545,36 +1546,39 @@ var File_testpb_tx_proto protoreflect.FileDescriptor var file_testpb_tx_proto_rawDesc = []byte{ 0x0a, 0x0f, 0x74, 0x65, 0x73, 0x74, 0x70, 0x62, 0x2f, 0x74, 0x78, 0x2e, 0x70, 0x72, 0x6f, 0x74, - 0x6f, 0x12, 0x06, 0x74, 0x65, 0x73, 0x74, 0x70, 0x62, 0x1a, 0x14, 0x67, 0x6f, 0x67, 0x6f, 0x70, - 0x72, 0x6f, 0x74, 0x6f, 0x2f, 0x67, 0x6f, 0x67, 0x6f, 0x2e, 0x70, 0x72, 0x6f, 0x74, 0x6f, 0x1a, - 0x15, 0x74, 0x65, 0x73, 0x74, 0x70, 0x62, 0x2f, 0x74, 0x65, 0x73, 0x74, 0x64, 0x61, 0x74, 0x61, - 0x2e, 0x70, 0x72, 0x6f, 0x74, 0x6f, 0x1a, 0x17, 0x63, 0x6f, 0x73, 0x6d, 0x6f, 0x73, 0x2f, 0x6d, - 0x73, 0x67, 0x2f, 0x76, 0x31, 0x2f, 0x6d, 0x73, 0x67, 0x2e, 0x70, 0x72, 0x6f, 0x74, 0x6f, 0x22, - 0x4f, 0x0a, 0x0c, 0x4d, 0x73, 0x67, 0x43, 0x72, 0x65, 0x61, 0x74, 0x65, 0x44, 0x6f, 0x67, 0x12, - 0x1d, 0x0a, 0x03, 0x64, 0x6f, 0x67, 0x18, 0x01, 0x20, 0x01, 0x28, 0x0b, 0x32, 0x0b, 0x2e, 0x74, - 0x65, 0x73, 0x74, 0x70, 0x62, 0x2e, 0x44, 0x6f, 0x67, 0x52, 0x03, 0x64, 0x6f, 0x67, 0x12, 0x14, - 0x0a, 0x05, 0x6f, 0x77, 0x6e, 0x65, 0x72, 0x18, 0x02, 0x20, 0x01, 0x28, 0x09, 0x52, 0x05, 0x6f, - 0x77, 0x6e, 0x65, 0x72, 0x3a, 0x0a, 0x82, 0xe7, 0xb0, 0x2a, 0x05, 0x6f, 0x77, 0x6e, 0x65, 0x72, - 0x22, 0x2a, 0x0a, 0x14, 0x4d, 0x73, 0x67, 0x43, 0x72, 0x65, 0x61, 0x74, 0x65, 0x44, 0x6f, 0x67, - 0x52, 0x65, 0x73, 0x70, 0x6f, 0x6e, 0x73, 0x65, 0x12, 0x12, 0x0a, 0x04, 0x6e, 0x61, 0x6d, 0x65, - 0x18, 0x01, 0x20, 0x01, 0x28, 0x09, 0x52, 0x04, 0x6e, 0x61, 0x6d, 0x65, 0x22, 0x29, 0x0a, 0x07, - 0x54, 0x65, 0x73, 0x74, 0x4d, 0x73, 0x67, 0x12, 0x18, 0x0a, 0x07, 0x73, 0x69, 0x67, 0x6e, 0x65, - 0x72, 0x73, 0x18, 0x01, 0x20, 0x03, 0x28, 0x09, 0x52, 0x07, 0x73, 0x69, 0x67, 0x6e, 0x65, 0x72, - 0x73, 0x3a, 0x04, 0x88, 0xa0, 0x1f, 0x00, 0x32, 0x4d, 0x0a, 0x03, 0x4d, 0x73, 0x67, 0x12, 0x3f, - 0x0a, 0x09, 0x43, 0x72, 0x65, 0x61, 0x74, 0x65, 0x44, 0x6f, 0x67, 0x12, 0x14, 0x2e, 0x74, 0x65, - 0x73, 0x74, 0x70, 0x62, 0x2e, 0x4d, 0x73, 0x67, 0x43, 0x72, 0x65, 0x61, 0x74, 0x65, 0x44, 0x6f, - 0x67, 0x1a, 0x1c, 0x2e, 0x74, 0x65, 0x73, 0x74, 0x70, 0x62, 0x2e, 0x4d, 0x73, 0x67, 0x43, 0x72, - 0x65, 0x61, 0x74, 0x65, 0x44, 0x6f, 0x67, 0x52, 0x65, 0x73, 0x70, 0x6f, 0x6e, 0x73, 0x65, 0x1a, - 0x05, 0x80, 0xe7, 0xb0, 0x2a, 0x01, 0x42, 0x8b, 0x01, 0x0a, 0x0a, 0x63, 0x6f, 0x6d, 0x2e, 0x74, - 0x65, 0x73, 0x74, 0x70, 0x62, 0x42, 0x07, 0x54, 0x78, 0x50, 0x72, 0x6f, 0x74, 0x6f, 0x50, 0x01, - 0x5a, 0x3c, 0x67, 0x69, 0x74, 0x68, 0x75, 0x62, 0x2e, 0x63, 0x6f, 0x6d, 0x2f, 0x63, 0x6f, 0x73, - 0x6d, 0x6f, 0x73, 0x2f, 0x63, 0x6f, 0x73, 0x6d, 0x6f, 0x73, 0x2d, 0x73, 0x64, 0x6b, 0x2f, 0x74, - 0x65, 0x73, 0x74, 0x75, 0x74, 0x69, 0x6c, 0x2f, 0x74, 0x65, 0x73, 0x74, 0x64, 0x61, 0x74, 0x61, - 0x5f, 0x70, 0x75, 0x6c, 0x73, 0x61, 0x72, 0x2f, 0x74, 0x65, 0x73, 0x74, 0x70, 0x62, 0xa2, 0x02, - 0x03, 0x54, 0x58, 0x58, 0xaa, 0x02, 0x06, 0x54, 0x65, 0x73, 0x74, 0x70, 0x62, 0xca, 0x02, 0x06, - 0x54, 0x65, 0x73, 0x74, 0x70, 0x62, 0xe2, 0x02, 0x12, 0x54, 0x65, 0x73, 0x74, 0x70, 0x62, 0x5c, - 0x47, 0x50, 0x42, 0x4d, 0x65, 0x74, 0x61, 0x64, 0x61, 0x74, 0x61, 0xea, 0x02, 0x06, 0x54, 0x65, - 0x73, 0x74, 0x70, 0x62, 0x62, 0x06, 0x70, 0x72, 0x6f, 0x74, 0x6f, 0x33, + 0x6f, 0x12, 0x06, 0x74, 0x65, 0x73, 0x74, 0x70, 0x62, 0x1a, 0x11, 0x61, 0x6d, 0x69, 0x6e, 0x6f, + 0x2f, 0x61, 0x6d, 0x69, 0x6e, 0x6f, 0x2e, 0x70, 0x72, 0x6f, 0x74, 0x6f, 0x1a, 0x14, 0x67, 0x6f, + 0x67, 0x6f, 0x70, 0x72, 0x6f, 0x74, 0x6f, 0x2f, 0x67, 0x6f, 0x67, 0x6f, 0x2e, 0x70, 0x72, 0x6f, + 0x74, 0x6f, 0x1a, 0x15, 0x74, 0x65, 0x73, 0x74, 0x70, 0x62, 0x2f, 0x74, 0x65, 0x73, 0x74, 0x64, + 0x61, 0x74, 0x61, 0x2e, 0x70, 0x72, 0x6f, 0x74, 0x6f, 0x1a, 0x17, 0x63, 0x6f, 0x73, 0x6d, 0x6f, + 0x73, 0x2f, 0x6d, 0x73, 0x67, 0x2f, 0x76, 0x31, 0x2f, 0x6d, 0x73, 0x67, 0x2e, 0x70, 0x72, 0x6f, + 0x74, 0x6f, 0x22, 0x4f, 0x0a, 0x0c, 0x4d, 0x73, 0x67, 0x43, 0x72, 0x65, 0x61, 0x74, 0x65, 0x44, + 0x6f, 0x67, 0x12, 0x1d, 0x0a, 0x03, 0x64, 0x6f, 0x67, 0x18, 0x01, 0x20, 0x01, 0x28, 0x0b, 0x32, + 0x0b, 0x2e, 0x74, 0x65, 0x73, 0x74, 0x70, 0x62, 0x2e, 0x44, 0x6f, 0x67, 0x52, 0x03, 0x64, 0x6f, + 0x67, 0x12, 0x14, 0x0a, 0x05, 0x6f, 0x77, 0x6e, 0x65, 0x72, 0x18, 0x02, 0x20, 0x01, 0x28, 0x09, + 0x52, 0x05, 0x6f, 0x77, 0x6e, 0x65, 0x72, 0x3a, 0x0a, 0x82, 0xe7, 0xb0, 0x2a, 0x05, 0x6f, 0x77, + 0x6e, 0x65, 0x72, 0x22, 0x2a, 0x0a, 0x14, 0x4d, 0x73, 0x67, 0x43, 0x72, 0x65, 0x61, 0x74, 0x65, + 0x44, 0x6f, 0x67, 0x52, 0x65, 0x73, 0x70, 0x6f, 0x6e, 0x73, 0x65, 0x12, 0x12, 0x0a, 0x04, 0x6e, + 0x61, 0x6d, 0x65, 0x18, 0x01, 0x20, 0x01, 0x28, 0x09, 0x52, 0x04, 0x6e, 0x61, 0x6d, 0x65, 0x22, + 0x48, 0x0a, 0x07, 0x54, 0x65, 0x73, 0x74, 0x4d, 0x73, 0x67, 0x12, 0x18, 0x0a, 0x07, 0x73, 0x69, + 0x67, 0x6e, 0x65, 0x72, 0x73, 0x18, 0x01, 0x20, 0x03, 0x28, 0x09, 0x52, 0x07, 0x73, 0x69, 0x67, + 0x6e, 0x65, 0x72, 0x73, 0x3a, 0x23, 0x88, 0xa0, 0x1f, 0x00, 0x82, 0xe7, 0xb0, 0x2a, 0x07, 0x73, + 0x69, 0x67, 0x6e, 0x65, 0x72, 0x73, 0x8a, 0xe7, 0xb0, 0x2a, 0x0e, 0x74, 0x65, 0x73, 0x74, 0x70, + 0x62, 0x2f, 0x54, 0x65, 0x73, 0x74, 0x4d, 0x73, 0x67, 0x32, 0x4d, 0x0a, 0x03, 0x4d, 0x73, 0x67, + 0x12, 0x3f, 0x0a, 0x09, 0x43, 0x72, 0x65, 0x61, 0x74, 0x65, 0x44, 0x6f, 0x67, 0x12, 0x14, 0x2e, + 0x74, 0x65, 0x73, 0x74, 0x70, 0x62, 0x2e, 0x4d, 0x73, 0x67, 0x43, 0x72, 0x65, 0x61, 0x74, 0x65, + 0x44, 0x6f, 0x67, 0x1a, 0x1c, 0x2e, 0x74, 0x65, 0x73, 0x74, 0x70, 0x62, 0x2e, 0x4d, 0x73, 0x67, + 0x43, 0x72, 0x65, 0x61, 0x74, 0x65, 0x44, 0x6f, 0x67, 0x52, 0x65, 0x73, 0x70, 0x6f, 0x6e, 0x73, + 0x65, 0x1a, 0x05, 0x80, 0xe7, 0xb0, 0x2a, 0x01, 0x42, 0x8b, 0x01, 0x0a, 0x0a, 0x63, 0x6f, 0x6d, + 0x2e, 0x74, 0x65, 0x73, 0x74, 0x70, 0x62, 0x42, 0x07, 0x54, 0x78, 0x50, 0x72, 0x6f, 0x74, 0x6f, + 0x50, 0x01, 0x5a, 0x3c, 0x67, 0x69, 0x74, 0x68, 0x75, 0x62, 0x2e, 0x63, 0x6f, 0x6d, 0x2f, 0x63, + 0x6f, 0x73, 0x6d, 0x6f, 0x73, 0x2f, 0x63, 0x6f, 0x73, 0x6d, 0x6f, 0x73, 0x2d, 0x73, 0x64, 0x6b, + 0x2f, 0x74, 0x65, 0x73, 0x74, 0x75, 0x74, 0x69, 0x6c, 0x2f, 0x74, 0x65, 0x73, 0x74, 0x64, 0x61, + 0x74, 0x61, 0x5f, 0x70, 0x75, 0x6c, 0x73, 0x61, 0x72, 0x2f, 0x74, 0x65, 0x73, 0x74, 0x70, 0x62, + 0xa2, 0x02, 0x03, 0x54, 0x58, 0x58, 0xaa, 0x02, 0x06, 0x54, 0x65, 0x73, 0x74, 0x70, 0x62, 0xca, + 0x02, 0x06, 0x54, 0x65, 0x73, 0x74, 0x70, 0x62, 0xe2, 0x02, 0x12, 0x54, 0x65, 0x73, 0x74, 0x70, + 0x62, 0x5c, 0x47, 0x50, 0x42, 0x4d, 0x65, 0x74, 0x61, 0x64, 0x61, 0x74, 0x61, 0xea, 0x02, 0x06, + 0x54, 0x65, 0x73, 0x74, 0x70, 0x62, 0x62, 0x06, 0x70, 0x72, 0x6f, 0x74, 0x6f, 0x33, } var ( diff --git a/testutil/testdata/tx.pb.go b/testutil/testdata/tx.pb.go index b12e6fa2eb3c..e2d416faa41e 100644 --- a/testutil/testdata/tx.pb.go +++ b/testutil/testdata/tx.pb.go @@ -7,6 +7,7 @@ import ( context "context" fmt "fmt" _ "github.com/cosmos/cosmos-sdk/types/msgservice" + _ "github.com/cosmos/cosmos-sdk/types/tx/amino" _ "github.com/cosmos/gogoproto/gogoproto" grpc1 "github.com/cosmos/gogoproto/grpc" proto "github.com/cosmos/gogoproto/proto" @@ -173,27 +174,29 @@ func init() { func init() { proto.RegisterFile("testpb/tx.proto", fileDescriptor_1c54006dba274b2e) } var fileDescriptor_1c54006dba274b2e = []byte{ - // 313 bytes of a gzipped FileDescriptorProto - 0x1f, 0x8b, 0x08, 0x00, 0x00, 0x00, 0x00, 0x00, 0x02, 0xff, 0xe2, 0xe2, 0x2f, 0x49, 0x2d, 0x2e, - 0x29, 0x48, 0xd2, 0x2f, 0xa9, 0xd0, 0x2b, 0x28, 0xca, 0x2f, 0xc9, 0x17, 0x62, 0x83, 0x08, 0x48, - 0x89, 0xa4, 0xe7, 0xa7, 0xe7, 0x83, 0x85, 0xf4, 0x41, 0x2c, 0x88, 0xac, 0x94, 0x28, 0x4c, 0x79, - 0x6a, 0x71, 0x49, 0x4a, 0x62, 0x49, 0x22, 0x54, 0x58, 0x3c, 0x39, 0xbf, 0x38, 0x37, 0xbf, 0x58, - 0x3f, 0xb7, 0x38, 0x5d, 0xbf, 0xcc, 0x10, 0x44, 0x41, 0x24, 0x94, 0xfc, 0xb9, 0x78, 0x7c, 0x8b, - 0xd3, 0x9d, 0x8b, 0x52, 0x13, 0x4b, 0x52, 0x5d, 0xf2, 0xd3, 0x85, 0x64, 0xb9, 0x98, 0x53, 0xf2, - 0xd3, 0x25, 0x18, 0x15, 0x18, 0x35, 0xb8, 0x8d, 0xb8, 0xf5, 0x20, 0xa6, 0xe9, 0xb9, 0xe4, 0xa7, - 0x07, 0x81, 0xc4, 0x85, 0x44, 0xb8, 0x58, 0xf3, 0xcb, 0xf3, 0x52, 0x8b, 0x24, 0x98, 0x14, 0x18, - 0x35, 0x38, 0x83, 0x20, 0x1c, 0x2b, 0xae, 0xa6, 0xe7, 0x1b, 0xb4, 0x20, 0x6c, 0x25, 0x2d, 0x2e, - 0x11, 0x64, 0x03, 0x83, 0x52, 0x8b, 0x0b, 0xf2, 0xf3, 0x8a, 0x53, 0x85, 0x84, 0xb8, 0x58, 0xf2, - 0x12, 0x73, 0x53, 0xc1, 0x26, 0x73, 0x06, 0x81, 0xd9, 0x4a, 0x9a, 0x5c, 0xec, 0x21, 0xa9, 0xc5, - 0x25, 0xbe, 0xc5, 0xe9, 0x42, 0x12, 0x5c, 0xec, 0xc5, 0x99, 0xe9, 0x79, 0xa9, 0x45, 0xc5, 0x12, - 0x8c, 0x0a, 0xcc, 0x1a, 0x9c, 0x41, 0x30, 0xae, 0x15, 0x4b, 0xc7, 0x02, 0x79, 0x06, 0x23, 0x5f, - 0x2e, 0x66, 0x90, 0x32, 0x7b, 0x2e, 0x4e, 0x84, 0x5b, 0x45, 0x60, 0xce, 0x43, 0xb6, 0x50, 0x4a, - 0x06, 0x9b, 0x28, 0xcc, 0x19, 0x52, 0xac, 0x0d, 0xcf, 0x37, 0x68, 0x31, 0x3a, 0x79, 0x9c, 0x78, - 0x24, 0xc7, 0x78, 0xe1, 0x91, 0x1c, 0xe3, 0x83, 0x47, 0x72, 0x8c, 0x13, 0x1e, 0xcb, 0x31, 0x5c, - 0x78, 0x2c, 0xc7, 0x70, 0xe3, 0xb1, 0x1c, 0x43, 0x94, 0x5e, 0x7a, 0x66, 0x49, 0x46, 0x69, 0x92, - 0x5e, 0x72, 0x7e, 0xae, 0x3e, 0x34, 0xd0, 0x20, 0x94, 0x6e, 0x71, 0x4a, 0x36, 0x38, 0x58, 0x4b, - 0x4b, 0x32, 0x73, 0xe0, 0xe1, 0x9b, 0xc4, 0x06, 0x0e, 0x47, 0x63, 0x40, 0x00, 0x00, 0x00, 0xff, - 0xff, 0x0a, 0x96, 0x8c, 0x83, 0xa8, 0x01, 0x00, 0x00, + // 337 bytes of a gzipped FileDescriptorProto + 0x1f, 0x8b, 0x08, 0x00, 0x00, 0x00, 0x00, 0x00, 0x02, 0xff, 0x6c, 0x90, 0x31, 0x4b, 0xc3, 0x40, + 0x14, 0xc7, 0x73, 0xd6, 0xb6, 0xe4, 0x2a, 0x8a, 0x21, 0x62, 0x08, 0x1a, 0x4b, 0x5d, 0x4a, 0xc0, + 0x1c, 0xd6, 0xad, 0x8b, 0xa0, 0x1d, 0xba, 0x14, 0x21, 0x38, 0xb9, 0xa5, 0xed, 0x71, 0x06, 0x4d, + 0x5e, 0xc9, 0xbb, 0xaa, 0xa3, 0x38, 0x89, 0x93, 0x1f, 0xc1, 0x8f, 0xd0, 0x8f, 0xe1, 0xd8, 0xd1, + 0x51, 0xda, 0xa1, 0x5f, 0x43, 0x72, 0x97, 0x68, 0x07, 0x97, 0xbc, 0xff, 0xfb, 0x3d, 0xf2, 0xbf, + 0xf7, 0xfe, 0x74, 0x47, 0x72, 0x94, 0x93, 0x21, 0x93, 0x4f, 0xc1, 0x24, 0x03, 0x09, 0x56, 0x4d, + 0x03, 0x77, 0x37, 0x4a, 0xe2, 0x14, 0x98, 0xfa, 0xea, 0x91, 0x6b, 0x0b, 0x10, 0xa0, 0x24, 0xcb, + 0x55, 0x41, 0xf7, 0x4a, 0x07, 0x8e, 0x72, 0x1c, 0xc9, 0xa8, 0xc0, 0xfb, 0x23, 0xc0, 0x04, 0x90, + 0x25, 0x28, 0xd8, 0xc3, 0x69, 0x5e, 0xf4, 0xa0, 0x75, 0x45, 0xb7, 0x06, 0x28, 0x2e, 0x33, 0x1e, + 0x49, 0xde, 0x03, 0x61, 0x1d, 0xd2, 0xca, 0x18, 0x84, 0x43, 0x9a, 0xa4, 0xdd, 0xe8, 0x34, 0x02, + 0xed, 0x16, 0xf4, 0x40, 0x84, 0x39, 0xb7, 0x6c, 0x5a, 0x85, 0xc7, 0x94, 0x67, 0xce, 0x46, 0x93, + 0xb4, 0xcd, 0x50, 0x37, 0x5d, 0xfa, 0xb2, 0x9a, 0xf9, 0x5a, 0xb7, 0x7c, 0x6a, 0xaf, 0x1b, 0x86, + 0x1c, 0x27, 0x90, 0x22, 0xb7, 0x2c, 0xba, 0x99, 0x46, 0x09, 0x57, 0xce, 0x66, 0xa8, 0x74, 0xab, + 0x4f, 0xeb, 0xd7, 0x1c, 0xe5, 0x00, 0x85, 0xe5, 0xd0, 0x3a, 0xc6, 0x22, 0xe5, 0x19, 0x3a, 0xa4, + 0x59, 0x69, 0x9b, 0x61, 0xd9, 0x76, 0x8f, 0x5f, 0x3f, 0x8e, 0x8c, 0xfc, 0x81, 0x92, 0xbc, 0xad, + 0x66, 0xfe, 0x76, 0x71, 0x66, 0xf1, 0x7b, 0x67, 0x40, 0x2b, 0xb9, 0xcb, 0x39, 0x35, 0xff, 0x4e, + 0xb1, 0xcb, 0xed, 0xd7, 0xf7, 0x71, 0x0f, 0xfe, 0xa3, 0xe5, 0x96, 0x6e, 0xf5, 0x79, 0x35, 0xf3, + 0xc9, 0x45, 0xff, 0x73, 0xe1, 0x91, 0xf9, 0xc2, 0x23, 0xdf, 0x0b, 0x8f, 0xbc, 0x2f, 0x3d, 0x63, + 0xbe, 0xf4, 0x8c, 0xaf, 0xa5, 0x67, 0xdc, 0x04, 0x22, 0x96, 0xb7, 0xd3, 0x61, 0x30, 0x82, 0x84, + 0x15, 0x99, 0xea, 0x72, 0x82, 0xe3, 0x3b, 0x95, 0xfa, 0x54, 0xc6, 0xf7, 0xbf, 0xf1, 0x0f, 0x6b, + 0x2a, 0xe6, 0xb3, 0x9f, 0x00, 0x00, 0x00, 0xff, 0xff, 0x89, 0xf1, 0xc8, 0x3c, 0xda, 0x01, 0x00, + 0x00, } // Reference imports to suppress errors if they are not otherwise used. diff --git a/testutil/testnet/cometrpclock.go b/testutil/testnet/cometrpclock.go new file mode 100644 index 000000000000..17c05440d3e4 --- /dev/null +++ b/testutil/testnet/cometrpclock.go @@ -0,0 +1,100 @@ +package testnet + +import ( + "fmt" + "runtime/debug" + "sync" + + "github.com/cometbft/cometbft/node" +) + +// CometBFT v0.37 uses a singleton to manage the RPC "environment". +// v0.38 will not have that restriction, which was removed in commit: +// https://github.com/cometbft/cometbft/commit/3324f49fb7e7b40189726746493e83b82a61b558 +// +// We manage a corresponding global lock to ensure +// we don't attempt to use multiple active RPC servers in one process, +// which would result in unpredictable or incorrect behavior. +// Once the SDK adopts Comet v0.38+, we can remove this global lock mechanism. + +// Our singleton complementing Comet's global RPC state. +var globalCometMu = new(cometRPCMutex) + +type cometRPCMutex struct { + mu sync.Mutex + + prevLockStack []byte +} + +// CometRPCInUseError is returned on a failure to acquire +// the global comet RPC lock. +// +// This type will be removed once the Cosmos SDK adopts CometBFT v0.38 or newer. +type CometRPCInUseError struct { + prevStack []byte +} + +func (e CometRPCInUseError) Error() string { + return fmt.Sprintf(`Failed to acquire global lock for Comet RPC servers. + +If this in a test using t.Parallel(), remove the call to t.Parallel(). + +If this is in a test NOT using t.Parallel, +ensure that other callers call both Stop() and Wait() on the nodes. + +If there are multiple comet instances in one test using RPC servers, +ensure that only one instance has the RPC listener enabled. + +These restrictions will be loosened once cosmos-sdk adopts comet-bft v0.38 or newer. + +Stack where lock was previously acquired: +%s +`, e.prevStack) +} + +// Acquire attempts to acquire the underlying mutex. +// If it cannot be acquired on the first attempt, +// Acquire returns a [CometRPCInUseError] value. +func (m *cometRPCMutex) Acquire() error { + if !m.mu.TryLock() { + // If we can't acquire the lock, + // there is another active comet node using RPC. + // + // This was initially going to be a panic, + // but we can't easily write tests against that since + // the panic occurs in a separate goroutine + // when called through NewNetwork. + // + // Note, reading m.prevLockStack without holding m.mu + // is technically a data race, + // since it is possible that the previous caller was about to unlock. + // Nonetheless, the programmer is responsible for avoiding that situation, + // and a data race during a failure isn't particularly concerning. + return CometRPCInUseError{prevStack: m.prevLockStack} + } + + // Now we hold the lock, so first record the stack when the lock was taken. + m.prevLockStack = debug.Stack() + + return nil +} + +// Release unlocks m depending on n. +// If n is nil, m is unlocked immediately. +// If n is not nil, a new goroutine is created +// and n is released after the node has finished running. +func (m *cometRPCMutex) Release(n *node.Node) { + if n == nil { + m.prevLockStack = nil + m.mu.Unlock() + return + } + + go m.releaseAfterWait(n) +} + +func (m *cometRPCMutex) releaseAfterWait(n *node.Node) { + n.Wait() + m.prevLockStack = nil + m.mu.Unlock() +} diff --git a/testutil/testnet/cometstarter.go b/testutil/testnet/cometstarter.go new file mode 100644 index 000000000000..6693247f9a1d --- /dev/null +++ b/testutil/testnet/cometstarter.go @@ -0,0 +1,254 @@ +package testnet + +import ( + "errors" + "fmt" + "net" + "os" + "path/filepath" + "syscall" + + "cosmossdk.io/log" + abcitypes "github.com/cometbft/cometbft/abci/types" + cmtcfg "github.com/cometbft/cometbft/config" + cmted25519 "github.com/cometbft/cometbft/crypto/ed25519" + "github.com/cometbft/cometbft/node" + "github.com/cometbft/cometbft/p2p" + "github.com/cometbft/cometbft/privval" + "github.com/cometbft/cometbft/proxy" + cmttypes "github.com/cometbft/cometbft/types" + servercmtlog "github.com/cosmos/cosmos-sdk/server/log" + genutiltypes "github.com/cosmos/cosmos-sdk/x/genutil/types" +) + +// CometStarter offers a builder-pattern interface to +// starting a Comet instance with an ABCI application running alongside. +// +// As CometStart is more broadly used in the codebase, +// the number of available methods on CometStarter will grow. +type CometStarter struct { + logger log.Logger + + app abcitypes.Application + + cfg *cmtcfg.Config + valPrivKey cmted25519.PrivKey + genesis []byte + + rootDir string + + rpcListen bool + + tcpAddrChooser func() string + + startTries int +} + +// NewCometStarter accepts a minimal set of arguments to start comet with an ABCI app. +// For further configuration, chain other CometStarter methods before calling Start: +// +// NewCometStarter(...).Logger(...).Start() +func NewCometStarter( + app abcitypes.Application, + cfg *cmtcfg.Config, + valPrivKey cmted25519.PrivKey, + genesis []byte, + rootDir string, +) *CometStarter { + cfg.SetRoot(rootDir) + + // CometStarter won't work without these settings, + // so set them unconditionally. + cfg.P2P.AllowDuplicateIP = true + cfg.P2P.AddrBookStrict = false + + // For now, we disallow RPC listening. + // Comet v0.37 uses a global value such that multiple comet nodes in one process + // end up contending over one "rpc environment" and only the last-started validator + // will control the RPC service. + // + // The "rpc environment" was removed as a global in + // https://github.com/cometbft/cometbft/commit/3324f49fb7e7b40189726746493e83b82a61b558 + // which is due to land in v0.38. + // + // At that point, we should keep the default as RPC off, + // but we should add a RPCListen method to opt in to enabling it. + + // If RPC.ListenAddress is the default value, clear it. + const defaultRPCListenAddr = "tcp://127.0.0.1:26657" + if cfg.RPC.ListenAddress == defaultRPCListenAddr { + cfg.RPC.ListenAddress = "" + } + + // Then if it was set to anything other than empty or the default value, + // fail with a clear explanation on how to enable RPC. + // The RPCListen method must be used in order to correctly pick an available listen address. + if cfg.RPC.ListenAddress != "" { + panic(fmt.Errorf("NewCometStarter: cfg.RPC.ListenAddress must be empty (but was %q); use (*CometStarter).RPCListen() instead", cfg.RPC.ListenAddress)) + } + + // defaultStartTries is somewhat arbitrary. + // Occasionally TestCometStarter_PortContention would fail with 10 tries, + // and bumping it up to 12 makes it almost never fail. + const defaultStartTries = 12 + return &CometStarter{ + logger: log.NewNopLogger(), + + app: app, + + cfg: cfg, + genesis: genesis, + valPrivKey: valPrivKey, + + rootDir: rootDir, + + startTries: defaultStartTries, + } +} + +// Logger sets the logger for s and for the eventual started comet instance. +func (s *CometStarter) Logger(logger log.Logger) *CometStarter { + s.logger = logger + return s +} + +// RPCListen enables the RPC listener service on the underlying Comet node. +// The RPC service must be enabled this way so that s can choose a dynamic port, +// retrying if necessary. +// +// Note that there is a limitation in CometBFT v0.37 that +// prevents more than one RPC server running at a time. +// Once the Cosmos SDK has adopted CometBFT v0.38 or newer, +// that limitation will be removed. +func (s *CometStarter) RPCListen() *CometStarter { + s.rpcListen = true + return s +} + +// Start returns a started Comet node. +func (s *CometStarter) Start() (n *node.Node, err error) { + if s.rpcListen { + if err := globalCometMu.Acquire(); err != nil { + return nil, err + } + + // Wrap this defer in an anonymous function so we don't immediately evaluate n, + // which would always be nil at thi spoint. + defer func() { + globalCometMu.Release(n) + }() + } + + fpv, nodeKey, err := s.initDisk() + if err != nil { + return nil, err + } + + appGenesisProvider := func() (*cmttypes.GenesisDoc, error) { + appGenesis, err := genutiltypes.AppGenesisFromFile(s.cfg.GenesisFile()) + if err != nil { + return nil, err + } + + return appGenesis.ToGenesisDoc() + } + + for i := 0; i < s.startTries; i++ { + s.cfg.P2P.ListenAddress = s.likelyAvailableAddress() + if s.rpcListen { + s.cfg.RPC.ListenAddress = s.likelyAvailableAddress() + } + + n, err := node.NewNode( + s.cfg, + fpv, + nodeKey, + proxy.NewLocalClientCreator(s.app), + appGenesisProvider, + node.DefaultDBProvider, + node.DefaultMetricsProvider(s.cfg.Instrumentation), + servercmtlog.CometZeroLogWrapper{Logger: s.logger}, + ) + if err != nil { + return nil, fmt.Errorf("failed to create comet node: %w", err) + } + + err = n.Start() + if err == nil { + return n, nil + } + + // Error isn't nil -- if it is EADDRINUSE then we can try again. + if errors.Is(err, syscall.EADDRINUSE) { + continue + } + + // Non-nil error that isn't EADDRINUSE, just return the error. + return nil, err + } + + // If we didn't return a node from inside the loop, + // then we must have exhausted our try limit. + return nil, fmt.Errorf("failed to start a comet node within %d tries", s.startTries) +} + +// initDisk creates the config and data directories on disk, +// and other required files, so that comet and the validator work correctly. +// It also generates a node key for validators. +func (s *CometStarter) initDisk() (cmttypes.PrivValidator, *p2p.NodeKey, error) { + if err := os.MkdirAll(filepath.Join(s.rootDir, "config"), 0o750); err != nil { + return nil, nil, fmt.Errorf("failed to make config directory: %w", err) + } + if err := os.MkdirAll(filepath.Join(s.rootDir, "data"), 0o750); err != nil { + return nil, nil, fmt.Errorf("failed to make data directory: %w", err) + } + + fpv := privval.NewFilePV(s.valPrivKey, s.cfg.PrivValidatorKeyFile(), s.cfg.PrivValidatorStateFile()) + fpv.Save() + + if err := os.WriteFile(s.cfg.GenesisFile(), s.genesis, 0o600); err != nil { + return nil, nil, fmt.Errorf("failed to write genesis file: %w", err) + } + + nodeKey, err := p2p.LoadOrGenNodeKey(s.cfg.NodeKeyFile()) + if err != nil { + return nil, nil, err + } + + return fpv, nodeKey, nil +} + +// TCPAddrChooser sets the function to use when selecting a (likely to be free) +// TCP address for comet's P2P port. +// +// This should only be used when testing CometStarter. +// +// It must return a string in format "tcp://IP:PORT". +func (s *CometStarter) TCPAddrChooser(fn func() string) *CometStarter { + s.tcpAddrChooser = fn + return s +} + +// likelyAvailableAddress provides a TCP address that is likely to be available +// for comet or other processes to listen on. +// +// Generally, it is better to directly provide a net.Listener that is already bound to an address, +// but unfortunately comet does not offer that as part of its API. +// Instead, we locally bind to :0 and then report that as a "likely available" port. +// If another process steals that port before our comet instance can bind to it, +// the Start method handles retries. +func (s *CometStarter) likelyAvailableAddress() string { + // If s.TCPAddrChooser was called, use that implementation. + if s.tcpAddrChooser != nil { + return s.tcpAddrChooser() + } + + // Fall back to attempting a random port. + ln, err := net.Listen("tcp", "127.0.0.1:0") + if err != nil { + panic(fmt.Errorf("failed to bind to random port: %w", err)) + } + + defer ln.Close() + return "tcp://" + ln.Addr().String() +} diff --git a/testutil/testnet/delegator.go b/testutil/testnet/delegator.go new file mode 100644 index 000000000000..5ed8ef0ed6d5 --- /dev/null +++ b/testutil/testnet/delegator.go @@ -0,0 +1,59 @@ +package testnet + +import ( + "github.com/cosmos/cosmos-sdk/crypto/keys/secp256k1" + sdk "github.com/cosmos/cosmos-sdk/types" + authtypes "github.com/cosmos/cosmos-sdk/x/auth/types" + banktypes "github.com/cosmos/cosmos-sdk/x/bank/types" +) + +// DelegatorPrivKeys is a slice of secp256k1.PrivKey. +type DelegatorPrivKeys []*secp256k1.PrivKey + +// NewDelegatorPrivKeysreturns a DelegatorPrivKeys of length n, +// where each set of keys is dynamically generated. +func NewDelegatorPrivKeys(n int) DelegatorPrivKeys { + dpk := make(DelegatorPrivKeys, n) + + for i := range dpk { + dpk[i] = secp256k1.GenPrivKey() + } + + return dpk +} + +// BaseAccounts returns the base accounts corresponding to the delegators' public keys. +func (dpk DelegatorPrivKeys) BaseAccounts() BaseAccounts { + ba := make(BaseAccounts, len(dpk)) + + for i, pk := range dpk { + pubKey := pk.PubKey() + + const accountNumber = 0 + const sequenceNumber = 0 + + ba[i] = authtypes.NewBaseAccount( + pubKey.Address().Bytes(), pubKey, accountNumber, sequenceNumber, + ) + } + + return ba +} + +// BaseAccounts is a slice of [*authtypes.BaseAccount]. +type BaseAccounts []*authtypes.BaseAccount + +// Balances creates a slice of [banktypes.Balance] for each account in ba, +// where each balance has an identical Coins value of the singleBalance argument. +func (ba BaseAccounts) Balances(singleBalance sdk.Coins) []banktypes.Balance { + balances := make([]banktypes.Balance, len(ba)) + + for i, b := range ba { + balances[i] = banktypes.Balance{ + Address: b.GetAddress().String(), + Coins: singleBalance, + } + } + + return balances +} diff --git a/testutil/testnet/doc.go b/testutil/testnet/doc.go new file mode 100644 index 000000000000..55d4dbe441d4 --- /dev/null +++ b/testutil/testnet/doc.go @@ -0,0 +1,4 @@ +// Package testnet provides APIs for easily create and configure +// validators, genesis files, and comet instances, +// to support testing app chain instances in-process. +package testnet diff --git a/testutil/testnet/genesis.go b/testutil/testnet/genesis.go new file mode 100644 index 000000000000..bfc1755c8160 --- /dev/null +++ b/testutil/testnet/genesis.go @@ -0,0 +1,527 @@ +package testnet + +import ( + "context" + "encoding/json" + "fmt" + "strconv" + "time" + + cmttypes "github.com/cometbft/cometbft/types" + + "github.com/cosmos/cosmos-sdk/codec" + codectypes "github.com/cosmos/cosmos-sdk/codec/types" + cryptocodec "github.com/cosmos/cosmos-sdk/crypto/codec" + "github.com/cosmos/cosmos-sdk/crypto/keys/secp256k1" + sdk "github.com/cosmos/cosmos-sdk/types" + "github.com/cosmos/cosmos-sdk/types/tx/signing" + authsigning "github.com/cosmos/cosmos-sdk/x/auth/signing" + + authtx "github.com/cosmos/cosmos-sdk/x/auth/tx" + authtypes "github.com/cosmos/cosmos-sdk/x/auth/types" + banktypes "github.com/cosmos/cosmos-sdk/x/bank/types" + consensusparamtypes "github.com/cosmos/cosmos-sdk/x/consensus/types" + distributiontypes "github.com/cosmos/cosmos-sdk/x/distribution/types" + genutiltypes "github.com/cosmos/cosmos-sdk/x/genutil/types" + minttypes "github.com/cosmos/cosmos-sdk/x/mint/types" + slashingtypes "github.com/cosmos/cosmos-sdk/x/slashing/types" + stakingtypes "github.com/cosmos/cosmos-sdk/x/staking/types" +) + +// GenesisBuilder enables constructing a genesis file, +// following a builder pattern. +// +// None of the methods on GenesisBuilder return an error, +// choosing instead to panic. +// GenesisBuilder is only intended for use in tests, +// where inputs are predetermined and expected to succeed. +type GenesisBuilder struct { + amino *codec.LegacyAmino + codec *codec.ProtoCodec + + // The value used in ChainID. + // Some other require this value, + // so store it as a field instead of re-parsing it from JSON. + chainID string + + // The outer JSON object. + // Most data goes into app_state, but there are some top-level fields. + outer map[string]json.RawMessage + + // Many of GenesisBuilder's methods operate on the app_state JSON object, + // so we track that separately and nest it inside outer upon a call to JSON(). + appState map[string]json.RawMessage + + gentxs []sdk.Tx +} + +// NewGenesisBuilder returns an initialized GenesisBuilder. +// +// The returned GenesisBuilder has an initial height of 1 +// and a genesis_time of the current time when the function was called. +func NewGenesisBuilder() *GenesisBuilder { + ir := codectypes.NewInterfaceRegistry() + cryptocodec.RegisterInterfaces(ir) + stakingtypes.RegisterInterfaces(ir) + banktypes.RegisterInterfaces(ir) + authtypes.RegisterInterfaces(ir) + pCodec := codec.NewProtoCodec(ir) + + return &GenesisBuilder{ + amino: codec.NewLegacyAmino(), + codec: pCodec, + + outer: map[string]json.RawMessage{ + "initial_height": json.RawMessage(`"1"`), + "genesis_time": json.RawMessage( + strconv.AppendQuote(nil, time.Now().UTC().Format(time.RFC3339Nano)), + ), + }, + appState: map[string]json.RawMessage{}, + } +} + +// GenTx emulates the gentx CLI, creating a message to create a validator +// represented by val, with "amount" self delegation, +// and signed by privVal. +func (b *GenesisBuilder) GenTx(privVal secp256k1.PrivKey, val cmttypes.GenesisValidator, amount sdk.Coin) *GenesisBuilder { + if b.chainID == "" { + panic(fmt.Errorf("(*GenesisBuilder).GenTx must not be called before (*GenesisBuilder).ChainID")) + } + + pubKey, err := cryptocodec.FromCmtPubKeyInterface(val.PubKey) + if err != nil { + panic(err) + } + + // Produce the create validator message. + msg, err := stakingtypes.NewMsgCreateValidator( + privVal.PubKey().Address().Bytes(), + pubKey, + amount, + stakingtypes.Description{ + Moniker: "TODO", + }, + stakingtypes.CommissionRates{ + Rate: sdk.MustNewDecFromStr("0.1"), + MaxRate: sdk.MustNewDecFromStr("0.2"), + MaxChangeRate: sdk.MustNewDecFromStr("0.01"), + }, + sdk.OneInt(), + ) + if err != nil { + panic(err) + } + + if err := msg.Validate(); err != nil { + panic(err) + } + + txConf := authtx.NewTxConfig(b.codec, authtx.DefaultSignModes) + + txb := txConf.NewTxBuilder() + if err := txb.SetMsgs(msg); err != nil { + panic(err) + } + + const signMode = signing.SignMode_SIGN_MODE_DIRECT + + // Need to set the signature object on the tx builder first, + // otherwise we end up signing a different total message + // compared to what gets eventually verified. + if err := txb.SetSignatures( + signing.SignatureV2{ + PubKey: privVal.PubKey(), + Data: &signing.SingleSignatureData{ + SignMode: signMode, + }, + }, + ); err != nil { + panic(err) + } + + // Generate bytes to be signed. + bytesToSign, err := authsigning.GetSignBytesAdapter( + context.Background(), + txConf.TxEncoder(), + txConf.SignModeHandler(), + signing.SignMode_SIGN_MODE_DIRECT, + authsigning.SignerData{ + ChainID: b.chainID, + PubKey: privVal.PubKey(), + Address: sdk.MustBech32ifyAddressBytes("cosmos", privVal.PubKey().Address()), // TODO: don't hardcode cosmos1! + + // No account or sequence number for gentx. + }, + txb.GetTx(), + ) + if err != nil { + panic(err) + } + + // Produce the signature. + signed, err := privVal.Sign(bytesToSign) + if err != nil { + panic(err) + } + + // Set the signature on the builder. + if err := txb.SetSignatures( + signing.SignatureV2{ + PubKey: privVal.PubKey(), + Data: &signing.SingleSignatureData{ + SignMode: signMode, + Signature: signed, + }, + }, + ); err != nil { + panic(err) + } + + b.gentxs = append(b.gentxs, txb.GetTx()) + + return b +} + +// ChainID sets the genesis's "chain_id" field. +func (b *GenesisBuilder) ChainID(id string) *GenesisBuilder { + b.chainID = id + + var err error + b.outer["chain_id"], err = json.Marshal(id) + if err != nil { + panic(err) + } + + return b +} + +// GenesisTime sets the genesis's "genesis_time" field. +// Note that [NewGenesisBuilder] sets the genesis time to the current time by default. +func (b *GenesisBuilder) GenesisTime(t time.Time) *GenesisBuilder { + var err error + b.outer["genesis_time"], err = json.Marshal(t.Format(time.RFC3339Nano)) + if err != nil { + panic(err) + } + return b +} + +// InitialHeight sets the genesis's "initial_height" field to h. +// Note that [NewGenesisBuilder] sets the initial height to 1 by default. +func (b *GenesisBuilder) InitialHeight(h int64) *GenesisBuilder { + var err error + b.outer["initial_height"], err = json.Marshal(strconv.FormatInt(h, 10)) + if err != nil { + panic(err) + } + return b +} + +// AuthParams sets the auth params on the genesis. +func (b *GenesisBuilder) AuthParams(params authtypes.Params) *GenesisBuilder { + var err error + b.appState[authtypes.ModuleName], err = json.Marshal(map[string]any{ + "params": params, + }) + if err != nil { + panic(err) + } + + return b +} + +// DefaultAuthParams calls b.AuthParams with [authtypes.DefaultParams], +// as a convenience so that callers do not have to import the authtypes package. +func (b *GenesisBuilder) DefaultAuthParams() *GenesisBuilder { + return b.AuthParams(authtypes.DefaultParams()) +} + +// Consensus sets the consensus parameters and initial validators. +// +// If params is nil, [cmttypes.DefaultConsensusParams] is used. +func (b *GenesisBuilder) Consensus(params *cmttypes.ConsensusParams, vals CometGenesisValidators) *GenesisBuilder { + if params == nil { + params = cmttypes.DefaultConsensusParams() + } + + var err error + b.outer[consensusparamtypes.ModuleName], err = (&genutiltypes.ConsensusGenesis{ + Params: params, + Validators: vals.ToComet(), + }).MarshalJSON() + if err != nil { + panic(err) + } + + return b +} + +// Staking sets the staking parameters, validators, and delegations on the genesis. +// +// This also modifies the bank state's balances to include the bonded pool balance. +func (b *GenesisBuilder) Staking( + params stakingtypes.Params, + vals StakingValidators, + delegations []stakingtypes.Delegation, +) *GenesisBuilder { + var err error + b.appState[stakingtypes.ModuleName], err = b.codec.MarshalJSON( + stakingtypes.NewGenesisState(params, vals.ToStakingType(), delegations), + ) + if err != nil { + panic(err) + } + + // Modify bank state for bonded pool. + + var coins sdk.Coins + for _, v := range vals { + coins = coins.Add(sdk.NewCoin(sdk.DefaultBondDenom, v.V.Tokens)) + } + + bondedPoolBalance := banktypes.Balance{ + Address: authtypes.NewModuleAddress(stakingtypes.BondedPoolName).String(), + Coins: coins, + } + + // get bank types genesis, add account + + bankGenesis := banktypes.GetGenesisStateFromAppState(b.codec, b.appState) + bankGenesis.Balances = append(bankGenesis.Balances, bondedPoolBalance) + + b.appState[banktypes.ModuleName], err = b.codec.MarshalJSON(bankGenesis) + if err != nil { + panic(err) + } + + return b +} + +// StakingWithDefaultParams calls b.Staking, providing [stakingtypes.DefaultParams] +// so that callers don't necessarily have to import [stakingtypes]. +func (b *GenesisBuilder) StakingWithDefaultParams(vals StakingValidators, delegations []stakingtypes.Delegation) *GenesisBuilder { + return b.Staking(stakingtypes.DefaultParams(), vals, delegations) +} + +// DefaultStaking is shorthand for b.StakingWithDefaultParams with nil validators and delegations. +func (b *GenesisBuilder) DefaultStaking() *GenesisBuilder { + return b.StakingWithDefaultParams(nil, nil) +} + +// Banking sets the banking genesis state. +func (b *GenesisBuilder) Banking( + params banktypes.Params, + balances []banktypes.Balance, + totalSupply sdk.Coins, + denomMetadata []banktypes.Metadata, + sendEnabled []banktypes.SendEnabled, +) *GenesisBuilder { + var err error + b.appState[banktypes.ModuleName], err = b.codec.MarshalJSON( + banktypes.NewGenesisState( + params, + balances, + totalSupply, + denomMetadata, + sendEnabled, + ), + ) + if err != nil { + panic(err) + } + return b +} + +// BankingWithDefaultParams calls b.Banking with [banktypes.DefaultParams], +// so that callers don't necessarily have to import [banktypes]. +func (b *GenesisBuilder) BankingWithDefaultParams( + balances []banktypes.Balance, + totalSupply sdk.Coins, + denomMetadata []banktypes.Metadata, + sendEnabled []banktypes.SendEnabled, +) *GenesisBuilder { + return b.Banking( + banktypes.DefaultParams(), + balances, + totalSupply, + denomMetadata, + sendEnabled, + ) +} + +// Mint sets the mint genesis state. +func (b *GenesisBuilder) Mint(m minttypes.Minter, p minttypes.Params) *GenesisBuilder { + var err error + b.appState[minttypes.ModuleName], err = b.codec.MarshalJSON( + minttypes.NewGenesisState(m, p), + ) + if err != nil { + panic(err) + } + return b +} + +// DefaultMint calls b.Mint with [minttypes.DefaultInitialMinter] and [minttypes.DefaultParams]. +func (b *GenesisBuilder) DefaultMint() *GenesisBuilder { + return b.Mint(minttypes.DefaultInitialMinter(), minttypes.DefaultParams()) +} + +// Slashing sets the slashing genesis state. +func (b *GenesisBuilder) Slashing( + params slashingtypes.Params, + si []slashingtypes.SigningInfo, + mb []slashingtypes.ValidatorMissedBlocks, +) *GenesisBuilder { + var err error + b.appState[slashingtypes.ModuleName], err = b.codec.MarshalJSON( + slashingtypes.NewGenesisState(params, si, mb), + ) + if err != nil { + panic(err) + } + return b +} + +// SlashingWithDefaultParams calls b.Slashing with [slashingtypes.DefaultParams], +// so that callers don't necessarily have to import [slashingtypes]. +func (b *GenesisBuilder) SlashingWithDefaultParams( + si []slashingtypes.SigningInfo, + mb []slashingtypes.ValidatorMissedBlocks, +) *GenesisBuilder { + return b.Slashing(slashingtypes.DefaultParams(), si, mb) +} + +// DefaultSlashing is shorthand for b.SlashingWithDefaultParams +// with nil signing info and validator missed blocks. +func (b *GenesisBuilder) DefaultSlashing() *GenesisBuilder { + return b.SlashingWithDefaultParams(nil, nil) +} + +// BaseAccounts sets the initial base accounts and balances. +func (b *GenesisBuilder) BaseAccounts(ba BaseAccounts, balances []banktypes.Balance) *GenesisBuilder { + // Logic mostly copied from AddGenesisAccount. + + authGenState := authtypes.GetGenesisStateFromAppState(b.codec, b.appState) + bankGenState := banktypes.GetGenesisStateFromAppState(b.codec, b.appState) + + accs, err := authtypes.UnpackAccounts(authGenState.Accounts) + if err != nil { + panic(err) + } + + for _, a := range ba { + accs = append(accs, a) + } + accs = authtypes.SanitizeGenesisAccounts(accs) + + genAccs, err := authtypes.PackAccounts(accs) + if err != nil { + panic(err) + } + + authGenState.Accounts = genAccs + jAuthGenState, err := b.codec.MarshalJSON(&authGenState) + if err != nil { + panic(err) + } + b.appState[authtypes.ModuleName] = jAuthGenState + + bankGenState.Balances = append(bankGenState.Balances, balances...) + bankGenState.Balances = banktypes.SanitizeGenesisBalances(bankGenState.Balances) + + jBankState, err := b.codec.MarshalJSON(bankGenState) + if err != nil { + panic(err) + } + b.appState[banktypes.ModuleName] = jBankState + return b +} + +func (b *GenesisBuilder) Distribution(g *distributiontypes.GenesisState) *GenesisBuilder { + j, err := b.codec.MarshalJSON(g) + if err != nil { + panic(err) + } + + b.appState[distributiontypes.ModuleName] = j + return b +} + +func (b *GenesisBuilder) DefaultDistribution() *GenesisBuilder { + return b.Distribution(distributiontypes.DefaultGenesisState()) +} + +// JSON returns the map of the genesis after applying some final transformations. +func (b *GenesisBuilder) JSON() map[string]json.RawMessage { + gentxGenesisState := genutiltypes.NewGenesisStateFromTx( + authtx.NewTxConfig(b.codec, authtx.DefaultSignModes).TxJSONEncoder(), + b.gentxs, + ) + + if err := genutiltypes.ValidateGenesis( + gentxGenesisState, + authtx.NewTxConfig(b.codec, authtx.DefaultSignModes).TxJSONDecoder(), + genutiltypes.DefaultMessageValidator, + ); err != nil { + panic(err) + } + + b.appState = genutiltypes.SetGenesisStateInAppState( + b.codec, b.appState, gentxGenesisState, + ) + + appState, err := b.amino.MarshalJSON(b.appState) + if err != nil { + panic(err) + } + + b.outer["app_state"] = appState + + return b.outer +} + +// Encode returns the JSON-encoded, finalized genesis. +func (b *GenesisBuilder) Encode() []byte { + j, err := b.amino.MarshalJSON(b.JSON()) + if err != nil { + panic(err) + } + + return j +} + +// DefaultGenesisBuilderOnlyValidators returns a GenesisBuilder configured only with the given StakingValidators, +// with default parameters everywhere else. +// validatorAmount is the amount to give each validator during gentx. +// +// This is a convenience for the common case of nothing special in the genesis. +// For anything outside of the defaults, +// the longhand form of NewGenesisBuilder().ChainID(chainID)... should be used. +func DefaultGenesisBuilderOnlyValidators( + chainID string, + sv StakingValidators, + validatorAmount sdk.Coin, +) *GenesisBuilder { + cmtVals := make(CometGenesisValidators, len(sv)) + for i := range sv { + cmtVals[i] = sv[i].C + } + + b := NewGenesisBuilder(). + ChainID(chainID). + DefaultAuthParams(). + Consensus(nil, cmtVals). + BaseAccounts(sv.BaseAccounts(), nil). + StakingWithDefaultParams(nil, nil). + BankingWithDefaultParams(sv.Balances(), nil, nil, nil). + DefaultDistribution(). + DefaultMint(). + SlashingWithDefaultParams(nil, nil) + + for _, v := range sv { + b.GenTx(*v.PK.Del, v.C.V, sdk.NewCoin(sdk.DefaultBondDenom, sdk.DefaultPowerReduction)) + } + + return b +} diff --git a/testutil/testnet/genesis_test.go b/testutil/testnet/genesis_test.go new file mode 100644 index 000000000000..0947d86d3bd5 --- /dev/null +++ b/testutil/testnet/genesis_test.go @@ -0,0 +1,244 @@ +package testnet_test + +import ( + "encoding/base64" + "encoding/json" + "testing" + "time" + + cmted25519 "github.com/cometbft/cometbft/crypto/ed25519" + "github.com/cosmos/cosmos-sdk/crypto/keys/secp256k1" + "github.com/cosmos/cosmos-sdk/testutil/testnet" + sdk "github.com/cosmos/cosmos-sdk/types" + "github.com/cosmos/cosmos-sdk/types/bech32" + "github.com/stretchr/testify/require" +) + +func TestGenesisBuilder_GenesisTime(t *testing.T) { + t.Run("defaults to current time", func(t *testing.T) { + before := time.Now() + time.Sleep(time.Millisecond) // So that the genesis time will be strictly after "before". + gb := testnet.NewGenesisBuilder() + time.Sleep(time.Millisecond) // So that the genesis time will be strictly before "after". + after := time.Now() + + var gts string + require.NoError(t, json.Unmarshal(gb.JSON()["genesis_time"], >s)) + + gt, err := time.Parse(time.RFC3339Nano, gts) + require.NoError(t, err) + + require.True(t, gt.After(before)) + require.True(t, after.After(gt)) + }) + + t.Run("can be set to arbitrary time", func(t *testing.T) { + want := time.Date(2023, 3, 27, 9, 50, 23, 0, time.UTC) + + gb := testnet.NewGenesisBuilder().GenesisTime(want) + + var gts string + require.NoError(t, json.Unmarshal(gb.JSON()["genesis_time"], >s)) + + gt, err := time.Parse(time.RFC3339Nano, gts) + require.NoError(t, err) + + require.True(t, gt.Equal(want)) + }) +} + +func TestGenesisBuilder_InitialHeight(t *testing.T) { + t.Run("defaults to 1", func(t *testing.T) { + var ih string + require.NoError( + t, + json.Unmarshal( + testnet.NewGenesisBuilder().JSON()["initial_height"], + &ih, + ), + ) + + require.Equal(t, ih, "1") + }) + + t.Run("can be set to arbitrary value", func(t *testing.T) { + var ih string + require.NoError( + t, + json.Unmarshal( + testnet.NewGenesisBuilder().InitialHeight(12345).JSON()["initial_height"], + &ih, + ), + ) + + require.Equal(t, ih, "12345") + }) +} + +func TestGenesisBuilder_ChainID(t *testing.T) { + // No default. + gb := testnet.NewGenesisBuilder() + m := gb.JSON() + _, ok := m["chain_id"] + require.False(t, ok) + + var id string + require.NoError( + t, + json.Unmarshal( + gb.ChainID("my-chain").JSON()["chain_id"], + &id, + ), + ) + require.Equal(t, id, "my-chain") +} + +// Use known keys and addresses to assert that correct validator and delegator keys +// occur in the expected locations (i.e. we didn't mistakenly swap the keys anywhere). +func TestGenesisBuilder_GentxAddresses(t *testing.T) { + const valSecret0 = "val-secret-0" + const valAddr0 = "3F3B076353767F046477A6E0982F808C24D1870A" + const valPubKey0 = "ZhVhrOUHnUwYw/GlBSBrw/0X6A261gchCRYkAxGF2jk=" + valKey0 := cmted25519.GenPrivKeyFromSecret([]byte(valSecret0)) + if addr := valKey0.PubKey().Address().String(); addr != valAddr0 { + t.Fatalf("unexpected address %q for validator key 0 (expected %q)", addr, valAddr0) + } + if pub := base64.StdEncoding.EncodeToString(valKey0.PubKey().Bytes()); pub != valPubKey0 { + t.Fatalf("unexpected public key %q for validator key 0 (expected %q)", pub, valAddr0) + } + + const delSecret0 = "del-secret-0" + const delAddr0 = "30D7E04DA313C31B59A46408494B4272F0A9A256" + const delPubKey0 = "Aol+ZF9xBuZmYJrT1QFLpZBvSfr/zEKifWyg0Xi1tsFV" + const delAccAddr0 = "cosmos1xrt7qndrz0p3kkdyvsyyjj6zwtc2ngjky8dcpe" + delKey0 := secp256k1.GenPrivKeyFromSecret([]byte(delSecret0)) + if addr := delKey0.PubKey().Address().String(); addr != delAddr0 { + t.Fatalf("unexpected address %q for delegator key 0 (expected %q)", addr, delAddr0) + } + if pub := base64.StdEncoding.EncodeToString(delKey0.PubKey().Bytes()); pub != delPubKey0 { + t.Fatalf("unexpected public key %q for delegator key 0 (expected %q)", pub, delAddr0) + } + da, err := bech32.ConvertAndEncode("cosmos", delKey0.PubKey().Address().Bytes()) + require.NoError(t, err) + if da != delAccAddr0 { + t.Fatalf("unexpected account address %q for delegator key 0 (expected %q)", da, delAccAddr0) + } + + valPKs := testnet.ValidatorPrivKeys{ + &testnet.ValidatorPrivKey{ + Val: valKey0, + Del: delKey0, + }, + } + cmtVals := valPKs.CometGenesisValidators() + stakingVals := cmtVals.StakingValidators() + valBaseAccounts := stakingVals.BaseAccounts() + + b := testnet.NewGenesisBuilder(). + ChainID("my-test-chain"). + DefaultAuthParams(). + Consensus(nil, cmtVals). + BaseAccounts(valBaseAccounts, nil). + StakingWithDefaultParams(stakingVals, nil) + + for i, v := range valPKs { + b.GenTx(*v.Del, cmtVals[i].V, sdk.NewCoin(sdk.DefaultBondDenom, sdk.DefaultPowerReduction)) + } + + var g struct { + Consensus struct { + Validators []struct { + Address string `json:"address"` + PubKey struct { + Value string `json:"value"` + } `json:"pub_key"` + } `json:"validators"` + } `json:"consensus"` + + AppState struct { + Genutil struct { + GenTxs []struct { + Body struct { + Messages []struct { + Type string `json:"@type"` + DelegatorAddress string `json:"delegator_address"` + ValidatorAddress string `json:"validator_address"` + PubKey struct { + Key string `json:"key"` + } `json:"pubkey"` + } `json:"messages"` + } `json:"body"` + AuthInfo struct { + SignerInfos []struct { + PublicKey struct { + Key string `json:"key"` + } `json:"public_key"` + } `json:"signer_infos"` + } `json:"auth_info"` + } `json:"gen_txs"` + } `json:"genutil"` + + Auth struct { + Accounts []struct { + Address string `json:"address"` + PubKey struct { + Key string `json:"key"` + } `json:"pub_key"` + } `json:"accounts"` + } `json:"auth"` + } `json:"app_state"` + } + if err := json.Unmarshal(b.Encode(), &g); err != nil { + t.Fatal(err) + } + + // Validator encoded as expected. + vals := g.Consensus.Validators + require.Equal(t, vals[0].Address, valAddr0) + require.Equal(t, vals[0].PubKey.Value, valPubKey0) + + // Public keys on gentx message match correct keys (no ed25519/secp256k1 mismatch). + gentxs := g.AppState.Genutil.GenTxs + require.Equal(t, gentxs[0].Body.Messages[0].PubKey.Key, valPubKey0) + require.Equal(t, gentxs[0].AuthInfo.SignerInfos[0].PublicKey.Key, delPubKey0) + + // The only base account in this genesis, matches the secp256k1 key. + acct := g.AppState.Auth.Accounts[0] + require.Equal(t, acct.Address, delAccAddr0) + require.Equal(t, acct.PubKey.Key, delPubKey0) +} + +func ExampleGenesisBuilder() { + const nVals = 4 + + // Generate random private keys for validators. + valPKs := testnet.NewValidatorPrivKeys(nVals) + + // Produce the comet representation of those validators. + cmtVals := valPKs.CometGenesisValidators() + + stakingVals := cmtVals.StakingValidators() + + // Configure a new genesis builder + // with a fairly thorough set of defaults. + // + // If you only ever need defaults, you can use DefaultGenesisBuilderOnlyValidators(). + b := testnet.NewGenesisBuilder(). + ChainID("my-chain-id"). + DefaultAuthParams(). + Consensus(nil, cmtVals). + BaseAccounts(stakingVals.BaseAccounts(), nil). + DefaultStaking(). + BankingWithDefaultParams(stakingVals.Balances(), nil, nil, nil). + DefaultDistribution(). + DefaultMint(). + DefaultSlashing() + + for i := range stakingVals { + b.GenTx(*valPKs[i].Del, cmtVals[i].V, sdk.NewCoin(sdk.DefaultBondDenom, sdk.DefaultPowerReduction)) + } + + // Now, you can access b.JSON() if you need to make further modifications + // not (yet) supported by the GenesisBuilder API, + // or you can use b.Encode() for the serialzed JSON of the genesis. +} diff --git a/testutil/testnet/network.go b/testutil/testnet/network.go new file mode 100644 index 000000000000..97e7771b1135 --- /dev/null +++ b/testutil/testnet/network.go @@ -0,0 +1,116 @@ +package testnet + +import ( + "errors" + "fmt" + "sync" + + "github.com/cometbft/cometbft/p2p" +) + +// NewNetwork concurrently calls createCometStarter, nVals times; +// then it returns a slice of started comet nodes, +// in order corresponding with the number passed to createCometStarter. +// The returned nodes will all be peered together, +// by dialing each node's [github.com/cometbft/cometbft/p2p/pex.Reactor] to each other. +// +// Every node is attempted to be started, +// and any errors collected are joined together and returned. +// +// In the event of errors, a non-nil Nodes slice may still be returned +// and some elements may be nil. +// Callers should call [Nodes.Stop] and [Nodes.Wait] to perform cleanup, +// regardless of the returned error. +func NewNetwork(nVals int, createCometStarter func(int) *CometStarter) (Nodes, error) { + // The ordered slice of nodes; correct indexing is important. + // The creator goroutines will write directly into this slice. + nodes := make(Nodes, nVals) + + // Every node will be started in its own goroutine. + // We collect the switches so that each node can dial every other node. + switchCh := make(chan *p2p.Switch, nVals) + errCh := make(chan error, nVals) + + var wg sync.WaitGroup + // Start goroutines to populate nodes slice and notify as each node is available. + for i := 0; i < nVals; i++ { + wg.Add(1) + go func(i int) { + defer wg.Done() + + n, err := createCometStarter(i).Start() + if err != nil { + errCh <- fmt.Errorf("failed to start node %d: %w", i, err) + return + } + + // Notify that the new node's switch is available, + // so this node can be peered with the other nodes. + switchCh <- n.PEXReactor().Switch + + // And assign the node into its correct index in the ordered slice. + nodes[i] = n + }(i) + } + + // Once all the creation goroutines are complete, close the channels, + // to signal to the collection goroutines. + go func() { + wg.Wait() + close(errCh) + close(switchCh) + }() + + joinPeersDone := make(chan struct{}) + go joinPeers(switchCh, joinPeersDone) + + finalErrCh := make(chan error, 1) + go collectErrors(errCh, finalErrCh) + + // If there were any errors, return them. + // And return any set nodes, so that they can be cleaned up properly. + if err := <-finalErrCh; err != nil { + return nodes, err + } + + // No errors, so wait for peer joining to complete + // before returning the ordered nodes. + <-joinPeersDone + return nodes, nil +} + +// collectErrors collects all errors that arrive on the in channel, +// joins them, then sends the joined final error on the out channel. +func collectErrors(in <-chan error, out chan<- error) { + var errs []error + for err := range in { + errs = append(errs, err) + } + + var res error + if len(errs) > 0 { + res = errors.Join(errs...) + } + out <- res +} + +// joinPeers collects each switch arriving on newSwitches; +// each time a new switch arrives, it dials every previously seen switch. +// +// This allows each node to be started independently and concurrently +// without predetermined p2p ports. +func joinPeers(newSwitches <-chan *p2p.Switch, done chan<- struct{}) { + defer close(done) + + var readySwitches []*p2p.Switch + for newSwitch := range newSwitches { + newNetAddr := newSwitch.NetAddress() + for _, s := range readySwitches { + // For every new switch, connect with all the previously seen switches. + // It might not be necessary to dial in both directions, but it shouldn't hurt. + _ = s.DialPeerWithAddress(newNetAddr) + _ = newSwitch.DialPeerWithAddress(s.NetAddress()) + } + readySwitches = append(readySwitches, newSwitch) + } +} diff --git a/testutil/testnet/nodehelpers.go b/testutil/testnet/nodehelpers.go new file mode 100644 index 000000000000..686e58fec100 --- /dev/null +++ b/testutil/testnet/nodehelpers.go @@ -0,0 +1,32 @@ +package testnet + +import ( + "fmt" + "time" + + "github.com/cometbft/cometbft/node" +) + +// WaitForNodeHeight blocks until the node's consensus state reports +// a last height equal to or greater than desiredHeight. +// If totalWait has elapsed and the desired height has not been reached, +// an error is returned. +func WaitForNodeHeight(n *node.Node, desiredHeight int64, totalWait time.Duration) error { + const backoff = 100 * time.Millisecond + attempts := int64(totalWait / backoff) + + curHeight := int64(-1) + for i := int64(0); i < attempts; i++ { + curHeight = n.ConsensusState().GetLastHeight() + + if curHeight < desiredHeight { + time.Sleep(backoff) + continue + } + + // Met or exceeded target height. + return nil + } + + return fmt.Errorf("node did not reach desired height %d in %s; only reached height %d", desiredHeight, totalWait, curHeight) +} diff --git a/testutil/testnet/nodes.go b/testutil/testnet/nodes.go new file mode 100644 index 000000000000..d47699fc6fe2 --- /dev/null +++ b/testutil/testnet/nodes.go @@ -0,0 +1,70 @@ +package testnet + +import ( + "errors" + "fmt" + "time" + + "github.com/cometbft/cometbft/node" +) + +// Nodes is a slice of comet nodes, +// with some additional convenience methods. +// +// Nodes may contain nil elements, +// so that a partially failed call to NewNetwork +// can still be properly cleaned up. +type Nodes []*node.Node + +// Stop stops each node sequentially. +// All errors occurring during stop are returned as a joined error. +// +// Nil elements in ns are skipped. +func (ns Nodes) Stop() error { + var errs []error + for i, n := range ns { + if n == nil { + continue + } + if err := n.Stop(); err != nil { + errs = append(errs, fmt.Errorf("failed to stop node %d: %w", i, err)) + } + } + + if len(errs) > 0 { + return errors.Join(errs...) + } + + return nil +} + +// Wait blocks until every node in ns has completely stopped. +// +// Nil elements in ns are skipped. +func (ns Nodes) Wait() { + for _, n := range ns { + if n == nil { + continue + } + n.Wait() + } +} + +// StopAndWait is shorthand for calling both Stop() and Wait(), +// useful as a deferred call in tests. +func (ns Nodes) StopAndWait() error { + err := ns.Stop() + ns.Wait() + + // TODO(mr): remove this sleep call after we are using a version of Comet + // that includes a fix for https://github.com/cometbft/cometbft/issues/646. + // + // On my machine, this sleep appears to completely eliminate the late file write. + // It also almost always works around https://github.com/cometbft/cometbft/issues/652. + // + // Presumably the fix for those two issues will be included in a v0.37.1 release. + // If not, I assume they will be part of the first v0.38 series release. + time.Sleep(250 * time.Millisecond) + + return err +} diff --git a/testutil/testnet/nodes_test.go b/testutil/testnet/nodes_test.go new file mode 100644 index 000000000000..55fd3f4b8e98 --- /dev/null +++ b/testutil/testnet/nodes_test.go @@ -0,0 +1,29 @@ +package testnet_test + +import ( + "testing" + + "github.com/cometbft/cometbft/node" + "github.com/cosmos/cosmos-sdk/testutil/testnet" + "github.com/stretchr/testify/require" +) + +// Nil entries in a Nodes slice don't fail Stop or Wait. +func TestNodes_StopWaitNil(t *testing.T) { + for _, tc := range []struct { + Name string + Nodes []*node.Node + }{ + {Name: "nil slice", Nodes: nil}, + {Name: "slice with nil elements", Nodes: []*node.Node{nil}}, + } { + ns := testnet.Nodes(tc.Nodes) + t.Run(tc.Name, func(t *testing.T) { + require.NoError(t, ns.Stop()) + + // Nothing special to assert about Wait(). + // It should return immediately, without panicking. + ns.Wait() + }) + } +} diff --git a/testutil/testnet/validator.go b/testutil/testnet/validator.go new file mode 100644 index 000000000000..2e795393a5d3 --- /dev/null +++ b/testutil/testnet/validator.go @@ -0,0 +1,187 @@ +package testnet + +import ( + "fmt" + + sdkmath "cosmossdk.io/math" + cmted25519 "github.com/cometbft/cometbft/crypto/ed25519" + cmttypes "github.com/cometbft/cometbft/types" + codectypes "github.com/cosmos/cosmos-sdk/codec/types" + cryptocodec "github.com/cosmos/cosmos-sdk/crypto/codec" + "github.com/cosmos/cosmos-sdk/crypto/keys/secp256k1" + sdk "github.com/cosmos/cosmos-sdk/types" + "github.com/cosmos/cosmos-sdk/types/bech32" + authtypes "github.com/cosmos/cosmos-sdk/x/auth/types" + banktypes "github.com/cosmos/cosmos-sdk/x/bank/types" + stakingtypes "github.com/cosmos/cosmos-sdk/x/staking/types" +) + +// ValidatorPrivKeys is a slice of [*ValidatorPrivKey]. +type ValidatorPrivKeys []*ValidatorPrivKey + +// ValidatorPrivKey holds a validator key (a comet ed25519 key) +// and the validator's delegator or account key (a Cosmos SDK secp256k1 key). +type ValidatorPrivKey struct { + Val cmted25519.PrivKey + Del *secp256k1.PrivKey +} + +// NewValidatorPrivKeys returns a ValidatorPrivKeys of length n, +// where each set of keys is dynamically generated. +// +// If writing a test where deterministic keys are required, +// the caller should manually construct a slice and assign each key as needed. +func NewValidatorPrivKeys(n int) ValidatorPrivKeys { + vpk := make(ValidatorPrivKeys, n) + + for i := range vpk { + vpk[i] = &ValidatorPrivKey{ + Val: cmted25519.GenPrivKey(), + Del: secp256k1.GenPrivKey(), + } + } + + return vpk +} + +// CometGenesisValidators derives the CometGenesisValidators belonging to vpk. +func (vpk ValidatorPrivKeys) CometGenesisValidators() CometGenesisValidators { + cgv := make(CometGenesisValidators, len(vpk)) + + for i, pk := range vpk { + pubKey := pk.Val.PubKey() + + const votingPower = 1 + cmtVal := cmttypes.NewValidator(pubKey, votingPower) + + cgv[i] = &CometGenesisValidator{ + V: cmttypes.GenesisValidator{ + Address: cmtVal.Address, + PubKey: cmtVal.PubKey, + Power: cmtVal.VotingPower, + Name: fmt.Sprintf("val-%d", i), + }, + PK: pk, + } + } + + return cgv +} + +// CometGenesisValidators is a slice of [*CometGenesisValidator]. +type CometGenesisValidators []*CometGenesisValidator + +// CometGenesisValidator holds a comet GenesisValidator +// and a reference to the ValidatorPrivKey from which the CometGenesisValidator was derived. +type CometGenesisValidator struct { + V cmttypes.GenesisValidator + PK *ValidatorPrivKey +} + +// ToComet returns a new slice of [cmttypes.GenesisValidator], +// useful for some interactions. +func (cgv CometGenesisValidators) ToComet() []cmttypes.GenesisValidator { + vs := make([]cmttypes.GenesisValidator, len(cgv)) + for i, v := range cgv { + vs[i] = v.V + } + return vs +} + +// StakingValidators derives the StakingValidators belonging to cgv. +func (cgv CometGenesisValidators) StakingValidators() StakingValidators { + vals := make(StakingValidators, len(cgv)) + for i, v := range cgv { + pk, err := cryptocodec.FromCmtPubKeyInterface(v.V.PubKey) + if err != nil { + panic(fmt.Errorf("failed to extract comet pub key: %w", err)) + } + + pkAny, err := codectypes.NewAnyWithValue(pk) + if err != nil { + panic(fmt.Errorf("failed to wrap pub key in any type: %w", err)) + } + + vals[i] = &StakingValidator{ + V: stakingtypes.Validator{ + OperatorAddress: sdk.ValAddress(v.V.Address).String(), // TODO: this relies on global bech32 config. + ConsensusPubkey: pkAny, + Status: stakingtypes.Bonded, + Tokens: sdk.DefaultPowerReduction, + DelegatorShares: sdkmath.LegacyOneDec(), + MinSelfDelegation: sdkmath.ZeroInt(), + + // more fields uncopied from testutil/sims/app_helpers.go:220 + }, + C: v, + PK: v.PK, + } + } + + return vals +} + +// StakingValidators is a slice of [*StakingValidator]. +type StakingValidators []*StakingValidator + +// StakingValidator holds a [stakingtypes.Validator], +// and the CometGenesisValidator and ValidatorPrivKey required to derive the StakingValidator. +type StakingValidator struct { + V stakingtypes.Validator + C *CometGenesisValidator + PK *ValidatorPrivKey +} + +// ToStakingType returns a new slice of [stakingtypes.Validator], +// useful for some interactions. +func (sv StakingValidators) ToStakingType() []stakingtypes.Validator { + vs := make([]stakingtypes.Validator, len(sv)) + for i, v := range sv { + vs[i] = v.V + } + return vs +} + +// BaseAccounts returns the BaseAccounts for this set of StakingValidators. +// The base accounts are important for [*GenesisBuilder.BaseAccounts]. +func (sv StakingValidators) BaseAccounts() BaseAccounts { + ba := make(BaseAccounts, len(sv)) + + for i, v := range sv { + const accountNumber = 0 + const sequenceNumber = 0 + + pubKey := v.PK.Del.PubKey() + bech, err := bech32.ConvertAndEncode("cosmos", pubKey.Address().Bytes()) // TODO: this shouldn't be hardcoded to cosmos! + if err != nil { + panic(err) + } + accAddr, err := sdk.AccAddressFromBech32(bech) + if err != nil { + panic(err) + } + ba[i] = authtypes.NewBaseAccount( + accAddr, pubKey, accountNumber, sequenceNumber, + ) + } + + return ba +} + +// Balances returns the balances held by this set of StakingValidators. +func (sv StakingValidators) Balances() []banktypes.Balance { + bals := make([]banktypes.Balance, len(sv)) + + for i, v := range sv { + addr, err := bech32.ConvertAndEncode("cosmos", v.PK.Del.PubKey().Address().Bytes()) // TODO: this shouldn't be hardcoded to cosmos! + if err != nil { + panic(err) + } + bals[i] = banktypes.Balance{ + Address: addr, + Coins: sdk.Coins{sdk.NewCoin(sdk.DefaultBondDenom, v.V.Tokens)}, + } + } + + return bals +} diff --git a/tools/confix/cmd/diff.go b/tools/confix/cmd/diff.go index 28cd337a2f26..4dc86dbf16b1 100644 --- a/tools/confix/cmd/diff.go +++ b/tools/confix/cmd/diff.go @@ -17,11 +17,13 @@ func DiffCommand() *cobra.Command { RunE: func(cmd *cobra.Command, args []string) error { var filename string clientCtx := client.GetClientContextFromCmd(cmd) - if len(args) > 1 { + switch { + + case len(args) > 1: filename = args[1] - } else if clientCtx.HomeDir != "" { + case clientCtx.HomeDir != "": filename = fmt.Sprintf("%s/config/app.toml", clientCtx.HomeDir) - } else { + default: return fmt.Errorf("must provide a path to the app.toml file") } diff --git a/tools/confix/cmd/migrate.go b/tools/confix/cmd/migrate.go index f31425bfd3f0..18546b200f8a 100644 --- a/tools/confix/cmd/migrate.go +++ b/tools/confix/cmd/migrate.go @@ -27,11 +27,12 @@ In case of any error in updating the file, no output is written.`, RunE: func(cmd *cobra.Command, args []string) error { var filename string clientCtx := client.GetClientContextFromCmd(cmd) - if len(args) > 1 { + switch { + case len(args) > 1: filename = args[1] - } else if clientCtx.HomeDir != "" { + case clientCtx.HomeDir != "": filename = fmt.Sprintf("%s/config/app.toml", clientCtx.HomeDir) - } else { + default: return fmt.Errorf("must provide a path to the app.toml file") } diff --git a/tools/confix/cmd/mutate_test.go b/tools/confix/cmd/mutate_test.go index 294eb639105f..214af6254959 100644 --- a/tools/confix/cmd/mutate_test.go +++ b/tools/confix/cmd/mutate_test.go @@ -16,14 +16,14 @@ import ( // initClientContext initiates client Context for tests func initClientContext(t *testing.T) (client.Context, func()) { home := t.TempDir() - chainId := "test-chain" //nolint:revive + chainID := "test-chain" clientCtx := client.Context{}. WithHomeDir(home). WithViper(""). - WithChainID(chainId) + WithChainID(chainID) clientCtx, err := config.ReadFromClientConfig(clientCtx) assert.NilError(t, err) - assert.Equal(t, clientCtx.ChainID, chainId) + assert.Equal(t, clientCtx.ChainID, chainID) return clientCtx, func() { _ = os.RemoveAll(home) } } diff --git a/tools/confix/diff.go b/tools/confix/diff.go index e5d1fede4e5e..9abc4cd87aff 100644 --- a/tools/confix/diff.go +++ b/tools/confix/diff.go @@ -40,19 +40,21 @@ func DiffKeys(lhs, rhs *tomledit.Document) []Diff { i, j := 0, 0 for i < len(lsec) && j < len(rsec) { - if lsec[i].Name.Before(rsec[j].Name) { + switch { + + case lsec[i].Name.Before(rsec[j].Name): diff = append(diff, Diff{Type: Section, Deleted: true, KV: KV{Key: lsec[i].Name.String()}}) for _, kv := range allKVs(lsec[i]) { diff = append(diff, Diff{Type: Mapping, Deleted: true, KV: kv}) } i++ - } else if rsec[j].Name.Before(lsec[i].Name) { + case rsec[j].Name.Before(lsec[i].Name): diff = append(diff, Diff{Type: Section, KV: KV{Key: rsec[j].Name.String()}}) for _, kv := range allKVs(rsec[j]) { diff = append(diff, Diff{Type: Mapping, KV: kv}) } j++ - } else { + default: diff = append(diff, diffDocs(allKVs(lsec[i]), allKVs(rsec[j]), false)...) i++ j++ @@ -84,13 +86,14 @@ func DiffValues(lhs, rhs *tomledit.Document) []Diff { i, j := 0, 0 for i < len(lsec) && j < len(rsec) { - if lsec[i].Name.Before(rsec[j].Name) { + switch { + case lsec[i].Name.Before(rsec[j].Name): // skip keys present in lhs but not in rhs i++ - } else if rsec[j].Name.Before(lsec[i].Name) { + case rsec[j].Name.Before(lsec[i].Name): // skip keys present in rhs but not in lhs j++ - } else { + default: for _, d := range diffDocs(allKVs(lsec[i]), allKVs(rsec[j]), true) { if !d.Deleted { diff = append(diff, d) @@ -133,13 +136,14 @@ func diffDocs(lhs, rhs []KV, value bool) []Diff { i, j := 0, 0 for i < len(lhs) && j < len(rhs) { - if lhs[i].Key < rhs[j].Key { + switch { + case lhs[i].Key < rhs[j].Key: diff = append(diff, Diff{Type: Mapping, Deleted: true, KV: lhs[i]}) i++ - } else if lhs[i].Key > rhs[j].Key { + case lhs[i].Key > rhs[j].Key: diff = append(diff, Diff{Type: Mapping, KV: rhs[j]}) j++ - } else { + default: // key exists in both lhs and rhs // if value is true, compare the values if value && lhs[i].Value != rhs[j].Value { diff --git a/tools/confix/go.mod b/tools/confix/go.mod index 1dc9827fab71..cb7eb02e5772 100644 --- a/tools/confix/go.mod +++ b/tools/confix/go.mod @@ -3,25 +3,25 @@ module cosmossdk.io/tools/confix go 1.20 require ( - github.com/cosmos/cosmos-sdk v0.46.0-beta2.0.20230321173237-fe77d4bca302 - github.com/creachadair/atomicfile v0.2.8 + github.com/cosmos/cosmos-sdk v0.46.0-beta2.0.20230418140744-0dde947d0ab7 + github.com/creachadair/atomicfile v0.3.0 github.com/creachadair/tomledit v0.0.24 - github.com/spf13/cobra v1.6.1 + github.com/spf13/cobra v1.7.0 github.com/spf13/viper v1.15.0 golang.org/x/exp v0.0.0-20230321023759-10a507213a29 gotest.tools/v3 v3.4.0 ) require ( - cosmossdk.io/api v0.3.2-0.20230313131911-55bf5d4efbe7 // indirect - cosmossdk.io/collections v0.0.0-20230309163709-87da587416ba // indirect + cosmossdk.io/api v0.4.0 // indirect + cosmossdk.io/collections v0.1.0 // indirect cosmossdk.io/core v0.6.1 // indirect cosmossdk.io/depinject v1.0.0-alpha.3 // indirect cosmossdk.io/errors v1.0.0-beta.7 // indirect - cosmossdk.io/log v0.1.0 // indirect + cosmossdk.io/log v1.0.0 // indirect cosmossdk.io/math v1.0.0 // indirect - cosmossdk.io/store v0.1.0-alpha.1 // indirect - cosmossdk.io/x/tx v0.3.1-0.20230321155358-6522dd1731b5 // indirect + cosmossdk.io/store v0.1.0-alpha.1.0.20230328185921-37ba88872dbc // indirect + cosmossdk.io/x/tx v0.5.1-0.20230407182919-057d2e09bd63 // indirect filippo.io/edwards25519 v1.0.0 // indirect github.com/99designs/go-keychain v0.0.0-20191008050251-8e49817e8af4 // indirect github.com/99designs/keyring v1.2.1 // indirect @@ -36,9 +36,9 @@ require ( github.com/cespare/xxhash/v2 v2.2.0 // indirect github.com/cockroachdb/errors v1.9.1 // indirect github.com/cockroachdb/logtags v0.0.0-20230118201751-21c54148d20b // indirect - github.com/cockroachdb/pebble v0.0.0-20230315223031-1e5ddd10389e // indirect + github.com/cockroachdb/pebble v0.0.0-20230412222916-60cfeb46143b // indirect github.com/cockroachdb/redact v1.1.3 // indirect - github.com/cometbft/cometbft v0.37.0 // indirect + github.com/cometbft/cometbft v0.37.1-0.20230411132551-3a91d155e664 // indirect github.com/cometbft/cometbft-db v0.7.0 // indirect github.com/confio/ics23/go v0.9.0 // indirect github.com/cosmos/btcutil v1.0.5 // indirect @@ -46,13 +46,13 @@ require ( github.com/cosmos/cosmos-proto v1.0.0-beta.3 // indirect github.com/cosmos/go-bip39 v1.0.0 // indirect github.com/cosmos/gogogateway v1.2.0 // indirect - github.com/cosmos/gogoproto v1.4.6 // indirect + github.com/cosmos/gogoproto v1.4.8 // indirect github.com/cosmos/iavl v0.21.0-beta.1 // indirect github.com/cosmos/ledger-cosmos-go v0.13.0 // indirect github.com/creachadair/taskgroup v0.4.2 // indirect github.com/danieljoos/wincred v1.1.2 // indirect github.com/davecgh/go-spew v1.1.1 // indirect - github.com/decred/dcrd/dcrec/secp256k1/v4 v4.1.0 // indirect + github.com/decred/dcrd/dcrec/secp256k1/v4 v4.2.0 // indirect github.com/desertbit/timer v0.0.0-20180107155436-c41aec40b27f // indirect github.com/dgraph-io/badger/v2 v2.2007.4 // indirect github.com/dgraph-io/ristretto v0.1.1 // indirect @@ -62,7 +62,7 @@ require ( github.com/fatih/color v1.15.0 // indirect github.com/felixge/httpsnoop v1.0.2 // indirect github.com/fsnotify/fsnotify v1.6.0 // indirect - github.com/getsentry/sentry-go v0.19.0 // indirect + github.com/getsentry/sentry-go v0.20.0 // indirect github.com/go-kit/kit v0.12.0 // indirect github.com/go-kit/log v0.2.1 // indirect github.com/go-logfmt/logfmt v0.6.0 // indirect @@ -95,12 +95,12 @@ require ( github.com/improbable-eng/grpc-web v0.15.0 // indirect github.com/inconshreveable/mousetrap v1.1.0 // indirect github.com/jmhodges/levigo v1.0.0 // indirect - github.com/klauspost/compress v1.16.3 // indirect + github.com/klauspost/compress v1.16.5 // indirect github.com/kr/pretty v0.3.1 // indirect github.com/kr/text v0.2.0 // indirect github.com/lib/pq v1.10.7 // indirect github.com/libp2p/go-buffer-pool v0.1.0 // indirect - github.com/linxGnu/grocksdb v1.7.15 // indirect + github.com/linxGnu/grocksdb v1.7.16 // indirect github.com/magiconair/properties v1.8.7 // indirect github.com/mattn/go-colorable v0.1.13 // indirect github.com/mattn/go-isatty v0.0.18 // indirect @@ -115,14 +115,14 @@ require ( github.com/petermattis/goid v0.0.0-20230317030725-371a4b8eda08 // indirect github.com/pkg/errors v0.9.1 // indirect github.com/pmezard/go-difflib v1.0.0 // indirect - github.com/prometheus/client_golang v1.14.0 // indirect + github.com/prometheus/client_golang v1.15.0 // indirect github.com/prometheus/client_model v0.3.0 // indirect github.com/prometheus/common v0.42.0 // indirect github.com/prometheus/procfs v0.9.0 // indirect github.com/rcrowley/go-metrics v0.0.0-20201227073835-cf1acfcdf475 // indirect - github.com/rogpeppe/go-internal v1.9.0 // indirect + github.com/rogpeppe/go-internal v1.10.0 // indirect github.com/rs/cors v1.8.3 // indirect - github.com/rs/zerolog v1.29.0 // indirect + github.com/rs/zerolog v1.29.1 // indirect github.com/sasha-s/go-deadlock v0.3.1 // indirect github.com/spf13/afero v1.9.3 // indirect github.com/spf13/cast v1.5.0 // indirect @@ -137,13 +137,13 @@ require ( github.com/zondax/hid v0.9.1 // indirect github.com/zondax/ledger-go v0.14.1 // indirect go.etcd.io/bbolt v1.3.6 // indirect - golang.org/x/crypto v0.7.0 // indirect - golang.org/x/net v0.8.0 // indirect + golang.org/x/crypto v0.8.0 // indirect + golang.org/x/net v0.9.0 // indirect golang.org/x/sync v0.1.0 // indirect - golang.org/x/sys v0.6.0 // indirect - golang.org/x/term v0.6.0 // indirect - golang.org/x/text v0.8.0 // indirect - google.golang.org/genproto v0.0.0-20230320184635-7606e756e683 // indirect + golang.org/x/sys v0.7.0 // indirect + golang.org/x/term v0.7.0 // indirect + golang.org/x/text v0.9.0 // indirect + google.golang.org/genproto v0.0.0-20230410155749-daa745c078e1 // indirect google.golang.org/grpc v1.54.0 // indirect google.golang.org/protobuf v1.30.0 // indirect gopkg.in/ini.v1 v1.67.0 // indirect diff --git a/tools/confix/go.sum b/tools/confix/go.sum index 74af7b830697..e8bb211ff3f6 100644 --- a/tools/confix/go.sum +++ b/tools/confix/go.sum @@ -35,24 +35,24 @@ cloud.google.com/go/storage v1.6.0/go.mod h1:N7U0C8pVQ/+NIKOBQyamJIeKQKkZ+mxpohl cloud.google.com/go/storage v1.8.0/go.mod h1:Wv1Oy7z6Yz3DshWRJFhqM/UCfaWIRTdp0RXyy7KQOVs= cloud.google.com/go/storage v1.10.0/go.mod h1:FLPqc6j+Ki4BU591ie1oL6qBQGu2Bl/tZ9ullr3+Kg0= cloud.google.com/go/storage v1.14.0/go.mod h1:GrKmX003DSIwi9o29oFT7YDnHYwZoctc3fOKtUw0Xmo= -cosmossdk.io/api v0.3.2-0.20230313131911-55bf5d4efbe7 h1:4LrWK+uGP5IxznxtHHsHD+ZBs2+oZRH2loYOGjHLzZM= -cosmossdk.io/api v0.3.2-0.20230313131911-55bf5d4efbe7/go.mod h1:yVns7mKgcsG+hZW/3C5FdJtC6QYWdFIcRlKb9+5HV5g= -cosmossdk.io/collections v0.0.0-20230309163709-87da587416ba h1:S4PYij/tX3Op/hwenVEN9D+M27JRcwSwVqE3UA0BnwM= -cosmossdk.io/collections v0.0.0-20230309163709-87da587416ba/go.mod h1:lpS+G8bGC2anqzWdndTzjnQnuMO/qAcgZUkGJp4i3rc= +cosmossdk.io/api v0.4.0 h1:x90DmdidP6EhzktAa/6/IofSHidDnPjahdlrUvyQZQw= +cosmossdk.io/api v0.4.0/go.mod h1:TWDzBhUBhI1LhSf2XSYpfIBf6D4mbLu/fvzvDfhcaYM= +cosmossdk.io/collections v0.1.0 h1:nzJGeiq32KnZroSrhB6rPifw4I85Cgmzw/YAmr4luv8= +cosmossdk.io/collections v0.1.0/go.mod h1:xbauc0YsbUF8qKMVeBZl0pFCunxBIhKN/WlxpZ3lBuo= cosmossdk.io/core v0.6.1 h1:OBy7TI2W+/gyn2z40vVvruK3di+cAluinA6cybFbE7s= cosmossdk.io/core v0.6.1/go.mod h1:g3MMBCBXtxbDWBURDVnJE7XML4BG5qENhs0gzkcpuFA= cosmossdk.io/depinject v1.0.0-alpha.3 h1:6evFIgj//Y3w09bqOUOzEpFj5tsxBqdc5CfkO7z+zfw= cosmossdk.io/depinject v1.0.0-alpha.3/go.mod h1:eRbcdQ7MRpIPEM5YUJh8k97nxHpYbc3sMUnEtt8HPWU= cosmossdk.io/errors v1.0.0-beta.7 h1:gypHW76pTQGVnHKo6QBkb4yFOJjC+sUGRc5Al3Odj1w= cosmossdk.io/errors v1.0.0-beta.7/go.mod h1:mz6FQMJRku4bY7aqS/Gwfcmr/ue91roMEKAmDUDpBfE= -cosmossdk.io/log v0.1.0 h1:Vnexi+KzUCjmqq/m93teAxjt5biWFfZ5PI1imx2IJw8= -cosmossdk.io/log v0.1.0/go.mod h1:p95Wq6mDY3SREMc4y7+QU9Uwy3nyvfpWGD1iSaFkVFs= +cosmossdk.io/log v1.0.0 h1:NGKZ/A5rd4PduDfoscgABklX557PWjQINbosZy/m3Jk= +cosmossdk.io/log v1.0.0/go.mod h1:CwX9BLiBruZb7lzLlRr3R231d/fVPUXk8gAdV4LQap0= cosmossdk.io/math v1.0.0 h1:ro9w7eKx23om2tZz/VM2Pf+z2WAbGX1yDQQOJ6iGeJw= cosmossdk.io/math v1.0.0/go.mod h1:Ygz4wBHrgc7g0N+8+MrnTfS9LLn9aaTGa9hKopuym5k= -cosmossdk.io/store v0.1.0-alpha.1 h1:NGomhLUXzAxvK4OF8+yP6eNUG5i4LwzOzx+S494pTCg= -cosmossdk.io/store v0.1.0-alpha.1/go.mod h1:kmCMbhrleCZ6rDZPY/EGNldNvPebFNyVPFYp+pv05/k= -cosmossdk.io/x/tx v0.3.1-0.20230321155358-6522dd1731b5 h1:AlvyRc7f7Py1mv254vrqjIIuykCnitHIz2T+nup3bU0= -cosmossdk.io/x/tx v0.3.1-0.20230321155358-6522dd1731b5/go.mod h1:FNkSEMbLP9NFdTfrbslNUtNS7OXf3wgZeJyXzfRPa4c= +cosmossdk.io/store v0.1.0-alpha.1.0.20230328185921-37ba88872dbc h1:9piuA+NYmhe+SyMPtMoboLw/djgDbrI3dD5TG020Tnk= +cosmossdk.io/store v0.1.0-alpha.1.0.20230328185921-37ba88872dbc/go.mod h1:UFF5rmjN7WYVfxo6ArdY/l1+yyWMURBWOmSJypGqFHQ= +cosmossdk.io/x/tx v0.5.1-0.20230407182919-057d2e09bd63 h1:zHqj2VwZ/MStFmR7SUe/7gErOFhL9v2rkjmWPB/st34= +cosmossdk.io/x/tx v0.5.1-0.20230407182919-057d2e09bd63/go.mod h1:Oh3Kh+IPOfMEILNxVd2e8SLqRrIjYHpdGBfDg4ghU/k= dmitri.shuralyov.com/gpu/mtl v0.0.0-20190408044501-666a987793e9/go.mod h1:H6x//7gZCb22OMCxBHrMx7a5I7Hp++hsVxbQ4BYO7hU= filippo.io/edwards25519 v1.0.0 h1:0wAIcmJUqRdI8IJ/3eGi5/HwXZWPujYXXlkrQogz0Ek= filippo.io/edwards25519 v1.0.0/go.mod h1:N1IkdkCkiLB6tki+MYJoSx2JTY9NUlxZE7eHn5EwJns= @@ -113,6 +113,7 @@ github.com/beorn7/perks v1.0.1/go.mod h1:G2ZrVWU2WbWT9wwq4/hrbKbnv/1ERSJQ0ibhJ6r github.com/bgentry/speakeasy v0.1.0/go.mod h1:+zsyZBPWlz7T6j88CTgSN5bM796AkVf0kBD4zp0CCIs= github.com/bgentry/speakeasy v0.1.1-0.20220910012023-760eaf8b6816 h1:41iFGWnSlI2gVpmOtVTJZNodLdLQLn/KsJqFvXwnd/s= github.com/bgentry/speakeasy v0.1.1-0.20220910012023-760eaf8b6816/go.mod h1:+zsyZBPWlz7T6j88CTgSN5bM796AkVf0kBD4zp0CCIs= +github.com/bits-and-blooms/bitset v1.6.0 h1:FVfaUsleKAUTJnaN9Fd1YFFi1S8vAX5xeXnXHFYOojM= github.com/btcsuite/btcd/btcec/v2 v2.3.2 h1:5n0X6hX0Zk+6omWcihdYvdAlGf2DfasC0GMf7DClJ3U= github.com/btcsuite/btcd/btcec/v2 v2.3.2/go.mod h1:zYzJ8etWJQIv1Ogk7OzpWjowwOdXY1W/17j2MW85J04= github.com/btcsuite/btcd/btcutil v1.1.2 h1:XLMbX8JQEiwMcYft2EGi8zPUkoa0abKIU6/BJSRsjzQ= @@ -156,14 +157,14 @@ github.com/cockroachdb/errors v1.9.1/go.mod h1:2sxOtL2WIc096WSZqZ5h8fa17rdDq9HZO github.com/cockroachdb/logtags v0.0.0-20211118104740-dabe8e521a4f/go.mod h1:Vz9DsVWQQhf3vs21MhPMZpMGSht7O/2vFW2xusFUVOs= github.com/cockroachdb/logtags v0.0.0-20230118201751-21c54148d20b h1:r6VH0faHjZeQy818SGhaone5OnYfxFR/+AzdY3sf5aE= github.com/cockroachdb/logtags v0.0.0-20230118201751-21c54148d20b/go.mod h1:Vz9DsVWQQhf3vs21MhPMZpMGSht7O/2vFW2xusFUVOs= -github.com/cockroachdb/pebble v0.0.0-20230315223031-1e5ddd10389e h1:CDuLmyaZ1pD4OJHHtubKqgu/Byw5zAnm+gArJsyj96Q= -github.com/cockroachdb/pebble v0.0.0-20230315223031-1e5ddd10389e/go.mod h1:9lRMC4XN3/BLPtIp6kAKwIaHu369NOf2rMucPzipz50= +github.com/cockroachdb/pebble v0.0.0-20230412222916-60cfeb46143b h1:92ve6F1Pls/eqd+V+102lOMRJatgpqqsQvbT9Bl/fjg= +github.com/cockroachdb/pebble v0.0.0-20230412222916-60cfeb46143b/go.mod h1:9lRMC4XN3/BLPtIp6kAKwIaHu369NOf2rMucPzipz50= github.com/cockroachdb/redact v1.1.3 h1:AKZds10rFSIj7qADf0g46UixK8NNLwWTNdCIGS5wfSQ= github.com/cockroachdb/redact v1.1.3/go.mod h1:BVNblN9mBWFyMyqK1k3AAiSxhvhfK2oOZZ2lK+dpvRg= github.com/codahale/hdrhistogram v0.0.0-20161010025455-3a0bb77429bd/go.mod h1:sE/e/2PUdi/liOCUjSTXgM1o87ZssimdTWN964YiIeI= github.com/codegangsta/inject v0.0.0-20150114235600-33e0aa1cb7c0/go.mod h1:4Zcjuz89kmFXt9morQgcfYZAYZ5n8WHjt81YYWIwtTM= -github.com/cometbft/cometbft v0.37.0 h1:M005vBaSaugvYYmNZwJOopynQSjwLoDTwflnQ/I/eYk= -github.com/cometbft/cometbft v0.37.0/go.mod h1:Y2MMMN//O5K4YKd8ze4r9jmk4Y7h0ajqILXbH5JQFVs= +github.com/cometbft/cometbft v0.37.1-0.20230411132551-3a91d155e664 h1:BbCkbnaU3R603XpnbqvuDU8Kfv+hjhiFILOHhVFntsw= +github.com/cometbft/cometbft v0.37.1-0.20230411132551-3a91d155e664/go.mod h1:Y2MMMN//O5K4YKd8ze4r9jmk4Y7h0ajqILXbH5JQFVs= github.com/cometbft/cometbft-db v0.7.0 h1:uBjbrBx4QzU0zOEnU8KxoDl18dMNgDh+zZRUE0ucsbo= github.com/cometbft/cometbft-db v0.7.0/go.mod h1:yiKJIm2WKrt6x8Cyxtq9YTEcIMPcEe4XPxhgX59Fzf0= github.com/confio/ics23/go v0.9.0 h1:cWs+wdbS2KRPZezoaaj+qBleXgUk5WOQFMP3CQFGTr4= @@ -173,7 +174,7 @@ github.com/coreos/etcd v3.3.10+incompatible/go.mod h1:uF7uidLiAD3TWHmW31ZFd/JWoc github.com/coreos/go-etcd v2.0.0+incompatible/go.mod h1:Jez6KQU2B/sWsbdaef3ED8NzMklzPG4d5KIOhIy30Tk= github.com/coreos/go-semver v0.2.0/go.mod h1:nnelYz7RCh+5ahJtPPxZlU+153eP4D4r3EedlOD2RNk= github.com/coreos/go-systemd v0.0.0-20180511133405-39ca1b05acc7/go.mod h1:F5haX7vjVVG0kc13fIWeqUViNPyEJxv/OmvnBo0Yme4= -github.com/coreos/go-systemd/v22 v22.3.3-0.20220203105225-a9a7ef127534/go.mod h1:Y58oyj3AT4RCenI/lSvhwexgC+NSVTIJ3seZv2GcEnc= +github.com/coreos/go-systemd/v22 v22.5.0/go.mod h1:Y58oyj3AT4RCenI/lSvhwexgC+NSVTIJ3seZv2GcEnc= github.com/coreos/pkg v0.0.0-20160727233714-3ac0863d7acf/go.mod h1:E3G3o1h8I7cfcXa63jLwjI0eiQQMgzzUDFVpN/nH/eA= github.com/cosmos/btcutil v1.0.5 h1:t+ZFcX77LpKtDBhjucvnOH8C2l2ioGsBNEQ3jef8xFk= github.com/cosmos/btcutil v1.0.5/go.mod h1:IyB7iuqZMJlthe2tkIFL33xPyzbFYP0XVdS8P5lUPis= @@ -181,16 +182,16 @@ github.com/cosmos/cosmos-db v1.0.0-rc.1 h1:SjnT8B6WKMW9WEIX32qMhnEEKcI7ZP0+G1Sa9 github.com/cosmos/cosmos-db v1.0.0-rc.1/go.mod h1:Dnmk3flSf5lkwCqvvjNpoxjpXzhxnCAFzKHlbaForso= github.com/cosmos/cosmos-proto v1.0.0-beta.3 h1:VitvZ1lPORTVxkmF2fAp3IiA61xVwArQYKXTdEcpW6o= github.com/cosmos/cosmos-proto v1.0.0-beta.3/go.mod h1:t8IASdLaAq+bbHbjq4p960BvcTqtwuAxid3b/2rOD6I= -github.com/cosmos/cosmos-sdk v0.46.0-beta2.0.20230321173237-fe77d4bca302 h1:wffm9LPPG/FBW/tSRdJp2DCgkJQRX+Zsbdmn4I0aWeQ= -github.com/cosmos/cosmos-sdk v0.46.0-beta2.0.20230321173237-fe77d4bca302/go.mod h1:HzOsWXtPxhO8+Y8P4Ru+G3UWx6dTkpGXU9yvT35VEuI= +github.com/cosmos/cosmos-sdk v0.46.0-beta2.0.20230418140744-0dde947d0ab7 h1:+Q/K5pdQdQjp21gIxlQgGy4dOZk9gUBSQmJCYIf1bWA= +github.com/cosmos/cosmos-sdk v0.46.0-beta2.0.20230418140744-0dde947d0ab7/go.mod h1:BPvKPN63ettXrpz67uM1rHEqX/UVVkAfceFCPyp217E= github.com/cosmos/go-bip39 v0.0.0-20180819234021-555e2067c45d/go.mod h1:tSxLoYXyBmiFeKpvmq4dzayMdCjCnu8uqmCysIGBT2Y= github.com/cosmos/go-bip39 v1.0.0 h1:pcomnQdrdH22njcAatO0yWojsUnCO3y2tNoV1cb6hHY= github.com/cosmos/go-bip39 v1.0.0/go.mod h1:RNJv0H/pOIVgxw6KS7QeX2a0Uo0aKUlfhZ4xuwvCdJw= github.com/cosmos/gogogateway v1.2.0 h1:Ae/OivNhp8DqBi/sh2A8a1D0y638GpL3tkmLQAiKxTE= github.com/cosmos/gogogateway v1.2.0/go.mod h1:iQpLkGWxYcnCdz5iAdLcRBSw3h7NXeOkZ4GUkT+tbFI= github.com/cosmos/gogoproto v1.4.2/go.mod h1:cLxOsn1ljAHSV527CHOtaIP91kK6cCrZETRBrkzItWU= -github.com/cosmos/gogoproto v1.4.6 h1:Ee7z15dWJaGlgM2rWrK8N2IX7PQcuccu8oG68jp5RL4= -github.com/cosmos/gogoproto v1.4.6/go.mod h1:VS/ASYmPgv6zkPKLjR9EB91lwbLHOzaGCirmKKhncfI= +github.com/cosmos/gogoproto v1.4.8 h1:BrHKc6WFZt8+jRV71vKSQE+JrfF+JAnzrKo2VP7wIZ4= +github.com/cosmos/gogoproto v1.4.8/go.mod h1:hnb0DIEWTv+wdNzNcqus5xCQXq5+CXauq1FJuurRfVY= github.com/cosmos/iavl v0.21.0-beta.1 h1:fBQeBc8HLZ14plJNcmGfaOXSSMLVEHvEQXiTXSD76m0= github.com/cosmos/iavl v0.21.0-beta.1/go.mod h1:25YJYzilTErJ2mKfNB3xyWL9IsCwEQdNzdIutg2mh3U= github.com/cosmos/ledger-cosmos-go v0.13.0 h1:ex0CvCxToSR7j5WjrghPu2Bu9sSXKikjnVvUryNnx4s= @@ -198,8 +199,8 @@ github.com/cosmos/ledger-cosmos-go v0.13.0/go.mod h1:ZcqYgnfNJ6lAXe4HPtWgarNEY+B github.com/cpuguy83/go-md2man v1.0.10/go.mod h1:SmD6nW6nTyfqj6ABTjUi3V3JVMnlJmwcJI5acqYI6dE= github.com/cpuguy83/go-md2man/v2 v2.0.0-20190314233015-f79a8a8ca69d/go.mod h1:maD7wRr/U5Z6m/iR4s+kqSMx2CaBsrgA7czyZG/E6dU= github.com/cpuguy83/go-md2man/v2 v2.0.2/go.mod h1:tgQtvFlXSQOSOSIRvRPT7W67SCa46tRHOmNcaadrF8o= -github.com/creachadair/atomicfile v0.2.8 h1:koFZzO/Byf4wRJIf1cvLmlXI7QPnR+pLushHhtTdXB8= -github.com/creachadair/atomicfile v0.2.8/go.mod h1:Tb31RroXn8ESlNsY/FzDFoKSL1mzdHemTDNL9V1Ml4M= +github.com/creachadair/atomicfile v0.3.0 h1:4HvescJCWkiLOqHkhtCeNAY4+8DVyYkQgwBDyAAvDWI= +github.com/creachadair/atomicfile v0.3.0/go.mod h1:mwfrkRxFKwpNAflYZzytbSwxvbK6fdGRRlp0KEQc0qU= github.com/creachadair/taskgroup v0.4.2 h1:jsBLdAJE42asreGss2xZGZ8fJra7WtwnHWeJFxv2Li8= github.com/creachadair/taskgroup v0.4.2/go.mod h1:qiXUOSrbwAY3u0JPGTzObbE3yf9hcXHDKBZ2ZjpCbgM= github.com/creachadair/tomledit v0.0.24 h1:5Xjr25R2esu1rKCbQEmjZYlrhFkDspoAbAKb6QKQDhQ= @@ -213,9 +214,9 @@ github.com/danieljoos/wincred v1.1.2/go.mod h1:GijpziifJoIBfYh+S7BbkdUTU4LfM+QnG github.com/davecgh/go-spew v1.1.0/go.mod h1:J7Y8YcW2NihsgmVo/mv3lAwl/skON4iLHjSsI+c5H38= github.com/davecgh/go-spew v1.1.1 h1:vj9j/u1bqnvCEfJOwUhtlOARqs3+rkHYY13jYWTU97c= github.com/davecgh/go-spew v1.1.1/go.mod h1:J7Y8YcW2NihsgmVo/mv3lAwl/skON4iLHjSsI+c5H38= -github.com/decred/dcrd/crypto/blake256 v1.0.0 h1:/8DMNYp9SGi5f0w7uCm6d6M4OU2rGFK09Y2A4Xv7EE0= -github.com/decred/dcrd/dcrec/secp256k1/v4 v4.1.0 h1:HbphB4TFFXpv7MNrT52FGrrgVXF1owhMVTHFZIlnvd4= -github.com/decred/dcrd/dcrec/secp256k1/v4 v4.1.0/go.mod h1:DZGJHZMqrU4JJqFAWUS2UO1+lbSKsdiOoYi9Zzey7Fc= +github.com/decred/dcrd/crypto/blake256 v1.0.1 h1:7PltbUIQB7u/FfZ39+DGa/ShuMyJ5ilcvdfma9wOH6Y= +github.com/decred/dcrd/dcrec/secp256k1/v4 v4.2.0 h1:8UrgZ3GkP4i/CLijOJx79Yu+etlyjdBU4sfcs2WYQMs= +github.com/decred/dcrd/dcrec/secp256k1/v4 v4.2.0/go.mod h1:v57UDF4pDQJcEfFUCRop3lJL149eHGSe9Jvczhzjo/0= github.com/desertbit/timer v0.0.0-20180107155436-c41aec40b27f h1:U5y3Y5UE0w7amNe7Z5G/twsBW0KEalRQXZzf8ufSh9I= github.com/desertbit/timer v0.0.0-20180107155436-c41aec40b27f/go.mod h1:xH/i4TFMt8koVQZ6WFms69WAsDWr2XsYL3Hkl7jkoLE= github.com/dgraph-io/badger v1.6.0/go.mod h1:zwt7syl517jmP8s94KqSxTlM6IMsdhYy6psNgSztDR4= @@ -275,8 +276,8 @@ github.com/fsnotify/fsnotify v1.6.0 h1:n+5WquG0fcWoWp6xPWfHdbskMCQaFnG6PfBrh1Ky4 github.com/fsnotify/fsnotify v1.6.0/go.mod h1:sl3t1tCWJFWoRz9R8WJCbQihKKwmorjAbSClcnxKAGw= github.com/gavv/httpexpect v2.0.0+incompatible/go.mod h1:x+9tiU1YnrOvnB725RkpoLv1M62hOWzwo5OXotisrKc= github.com/getsentry/sentry-go v0.12.0/go.mod h1:NSap0JBYWzHND8oMbyi0+XZhUalc1TBdRL1M71JZW2c= -github.com/getsentry/sentry-go v0.19.0 h1:BcCH3CN5tXt5aML+gwmbFwVptLLQA+eT866fCO9wVOM= -github.com/getsentry/sentry-go v0.19.0/go.mod h1:y3+lGEFEFexZtpbG1GUE2WD/f9zGyKYwpEqryTOC/nE= +github.com/getsentry/sentry-go v0.20.0 h1:bwXW98iMRIWxn+4FgPW7vMrjmbym6HblXALmhjHmQaQ= +github.com/getsentry/sentry-go v0.20.0/go.mod h1:lc76E2QywIyW8WuBnwl8Lc4bkmQH4+w1gwTf25trprY= github.com/ghodss/yaml v1.0.0/go.mod h1:4dBDuWmgqj2HViK6kFavaiC9ZROes6MMH2rRYeMEF04= github.com/gin-contrib/sse v0.1.0 h1:Y/yl/+YNO8GZSjAhjMsSuLt29uWRFHdHYUb5lYOV9qE= github.com/gin-contrib/sse v0.1.0/go.mod h1:RHrZQHXnP2xjPF+u1gW/2HnVO7nvIa9PG3Gm+fLHvGI= @@ -497,7 +498,6 @@ github.com/imkira/go-interpol v1.1.0/go.mod h1:z0h2/2T3XF8kyEPpRgJ3kmNv+C43p+I/C github.com/improbable-eng/grpc-web v0.15.0 h1:BN+7z6uNXZ1tQGcNAuaU1YjsLTApzkjt2tzCixLaUPQ= github.com/improbable-eng/grpc-web v0.15.0/go.mod h1:1sy9HKV4Jt9aEs9JSnkWlRJPuPtwNr0l57L4f878wP8= github.com/inconshreveable/mousetrap v1.0.0/go.mod h1:PxqpIevigyE2G7u3NXJIT2ANytuPF1OarO4DADm73n8= -github.com/inconshreveable/mousetrap v1.0.1/go.mod h1:vpF70FUmC8bwa3OWnCshd2FqLfsEA9PFc4w1p2J65bw= github.com/inconshreveable/mousetrap v1.1.0 h1:wN+x4NVGpMsO7ErUn/mUI3vEoE6Jt13X2s0bqwp9tc8= github.com/inconshreveable/mousetrap v1.1.0/go.mod h1:vpF70FUmC8bwa3OWnCshd2FqLfsEA9PFc4w1p2J65bw= github.com/influxdata/influxdb1-client v0.0.0-20191209144304-8bf82d3c094d/go.mod h1:qj24IKcXYK6Iy9ceXlo3Tc+vtHo9lIhSX5JddghvEPo= @@ -539,8 +539,8 @@ github.com/klauspost/compress v1.9.7/go.mod h1:RyIbtBH6LamlWaDj8nUwkbUhJ87Yi3uG0 github.com/klauspost/compress v1.10.3/go.mod h1:aoV0uJVorq1K+umq18yTdKaF57EivdYsUV+/s2qKfXs= github.com/klauspost/compress v1.11.7/go.mod h1:aoV0uJVorq1K+umq18yTdKaF57EivdYsUV+/s2qKfXs= github.com/klauspost/compress v1.12.3/go.mod h1:8dP1Hq4DHOhN9w426knH3Rhby4rFm6D8eO+e+Dq5Gzg= -github.com/klauspost/compress v1.16.3 h1:XuJt9zzcnaz6a16/OU53ZjWp/v7/42WcR5t2a0PcNQY= -github.com/klauspost/compress v1.16.3/go.mod h1:ntbaceVETuRiXiv4DpjP66DpAtAGkEQskQzEyD//IeE= +github.com/klauspost/compress v1.16.5 h1:IFV2oUNUzZaz+XyusxpLzpzS8Pt5rh0Z16For/djlyI= +github.com/klauspost/compress v1.16.5/go.mod h1:ntbaceVETuRiXiv4DpjP66DpAtAGkEQskQzEyD//IeE= github.com/klauspost/cpuid v1.2.1/go.mod h1:Pj4uuM528wm8OyEC2QMXAi2YiTZ96dNQPGgoMS4s3ek= github.com/konsorten/go-windows-terminal-sequences v1.0.1/go.mod h1:T0+1ngSBFLxvqU3pZ+m/2kptfBszLMUkC4ZK/EgS/cQ= github.com/konsorten/go-windows-terminal-sequences v1.0.3/go.mod h1:T0+1ngSBFLxvqU3pZ+m/2kptfBszLMUkC4ZK/EgS/cQ= @@ -565,8 +565,8 @@ github.com/libp2p/go-buffer-pool v0.1.0 h1:oK4mSFcQz7cTQIfqbe4MIj9gLW+mnanjyFtc6 github.com/libp2p/go-buffer-pool v0.1.0/go.mod h1:N+vh8gMqimBzdKkSMVuydVDq+UV5QTWy5HSiZacSbPg= github.com/lightstep/lightstep-tracer-common/golang/gogo v0.0.0-20190605223551-bc2310a04743/go.mod h1:qklhhLq1aX+mtWk9cPHPzaBjWImj5ULL6C7HFJtXQMM= github.com/lightstep/lightstep-tracer-go v0.18.1/go.mod h1:jlF1pusYV4pidLvZ+XD0UBX0ZE6WURAspgAczcDHrL4= -github.com/linxGnu/grocksdb v1.7.15 h1:AEhP28lkeAybv5UYNYviYISpR6bJejEnKuYbnWAnxx0= -github.com/linxGnu/grocksdb v1.7.15/go.mod h1:pY55D0o+r8yUYLq70QmhdudxYvoDb9F+9puf4m3/W+U= +github.com/linxGnu/grocksdb v1.7.16 h1:Q2co1xrpdkr5Hx3Fp+f+f7fRGhQFQhvi/+226dtLmA8= +github.com/linxGnu/grocksdb v1.7.16/go.mod h1:JkS7pl5qWpGpuVb3bPqTz8nC12X3YtPZT+Xq7+QfQo4= github.com/lyft/protoc-gen-validate v0.0.13/go.mod h1:XbGvPuh87YZc5TdIa2/I4pLk0QoUACkjt2znoq26NVQ= github.com/magiconair/properties v1.8.0/go.mod h1:PppfXfuXeibc/6YijjN8zIbojt8czPbwD3XqdrwzmxQ= github.com/magiconair/properties v1.8.7 h1:IeQXZAiQcpL9mgcAe1Nu6cX9LLw6ExEHKjN0VQdvPDY= @@ -704,8 +704,8 @@ github.com/prometheus/client_golang v1.0.0/go.mod h1:db9x61etRT2tGnBNRi70OPL5Fsn github.com/prometheus/client_golang v1.3.0/go.mod h1:hJaj2vgQTGQmVCsAACORcieXFeDPbaTKGT+JTgUa3og= github.com/prometheus/client_golang v1.4.0/go.mod h1:e9GMxYsXl05ICDXkRhurwBS4Q3OK1iX/F2sw+iXX5zU= github.com/prometheus/client_golang v1.7.1/go.mod h1:PY5Wy2awLA44sXw4AOSfFBetzPP4j5+D6mVACh+pe2M= -github.com/prometheus/client_golang v1.14.0 h1:nJdhIvne2eSX/XRAFV9PcvFFRbrjbcTUj0VP62TMhnw= -github.com/prometheus/client_golang v1.14.0/go.mod h1:8vpkKitgIVNcqrRBWh1C4TIUQgYNtG/XQE4E/Zae36Y= +github.com/prometheus/client_golang v1.15.0 h1:5fCgGYogn0hFdhyhLbw7hEsWxufKtY9klyvdNfFlFhM= +github.com/prometheus/client_golang v1.15.0/go.mod h1:e9yaBhRPU2pPNsZwE+JdQl0KEt1N9XgF6zxWmaC0xOk= github.com/prometheus/client_model v0.0.0-20180712105110-5c3871d89910/go.mod h1:MbSGuTsp3dbXC40dX6PRTWyKYBIrTGTE9sqQNg2J8bo= github.com/prometheus/client_model v0.0.0-20190115171406-56726106282f/go.mod h1:MbSGuTsp3dbXC40dX6PRTWyKYBIrTGTE9sqQNg2J8bo= github.com/prometheus/client_model v0.0.0-20190129233127-fd36f4220a90/go.mod h1:xMI15A0UPsDsEKsMN9yxemIoYk6Tm2C1GtYGdfGttqA= @@ -740,14 +740,15 @@ github.com/rogpeppe/go-internal v1.3.0/go.mod h1:M8bDsm7K2OlrFYOpmOWEs/qY81heoFR github.com/rogpeppe/go-internal v1.6.1/go.mod h1:xXDCJY+GAPziupqXw64V24skbSoqbTEfhy4qGm1nDQc= github.com/rogpeppe/go-internal v1.8.0/go.mod h1:WmiCO8CzOY8rg0OYDC4/i/2WRWAB6poM+XZ2dLUbcbE= github.com/rogpeppe/go-internal v1.8.1/go.mod h1:JeRgkft04UBgHMgCIwADu4Pn6Mtm5d4nPKWu0nJ5d+o= -github.com/rogpeppe/go-internal v1.9.0 h1:73kH8U+JUqXU8lRuOHeVHaa/SZPifC7BkcraZVejAe8= github.com/rogpeppe/go-internal v1.9.0/go.mod h1:WtVeX8xhTBvf0smdhujwtBcq4Qrzq/fJaraNFVN+nFs= +github.com/rogpeppe/go-internal v1.10.0 h1:TMyTOH3F/DB16zRVcYyreMH6GnZZrwQVAoYjRBZyWFQ= +github.com/rogpeppe/go-internal v1.10.0/go.mod h1:UQnix2H7Ngw/k4C5ijL5+65zddjncjaFoBhdsK/akog= github.com/rs/cors v1.7.0/go.mod h1:gFx+x8UowdsKA9AchylcLynDq+nNFfI8FkUZdN/jGCU= github.com/rs/cors v1.8.3 h1:O+qNyWn7Z+F9M0ILBHgMVPuB1xTOucVd5gtaYyXBpRo= github.com/rs/cors v1.8.3/go.mod h1:XyqrcTp5zjWr1wsJ8PIRZssZ8b/WMcMf71DJnit4EMU= github.com/rs/xid v1.4.0/go.mod h1:trrq9SKmegXys3aeAKXMUTdJsYXVwGY3RLcfgqegfbg= -github.com/rs/zerolog v1.29.0 h1:Zes4hju04hjbvkVkOhdl2HpZa+0PmVwigmo8XoORE5w= -github.com/rs/zerolog v1.29.0/go.mod h1:NILgTygv/Uej1ra5XxGf82ZFSLk58MFGAUS2o6usyD0= +github.com/rs/zerolog v1.29.1 h1:cO+d60CHkknCbvzEWxP0S9K6KqyTjrCNUy1LdQLCGPc= +github.com/rs/zerolog v1.29.1/go.mod h1:Le6ESbR7hc+DP6Lt1THiV8CQSdkkNrd3R0XbEgp3ZBU= github.com/russross/blackfriday v1.5.2/go.mod h1:JO/DiYxRf+HjHt06OyowR9PTA263kcR/rfWxYHBV53g= github.com/russross/blackfriday/v2 v2.0.1/go.mod h1:+Rmxgy9KzJVeS9/2gXHxylqXiyQDYRxCVz55jmeOWTM= github.com/russross/blackfriday/v2 v2.1.0/go.mod h1:+Rmxgy9KzJVeS9/2gXHxylqXiyQDYRxCVz55jmeOWTM= @@ -780,8 +781,8 @@ github.com/spf13/cast v1.5.0 h1:rj3WzYc11XZaIZMPKmwP96zkFEnnAmV8s6XbB2aY32w= github.com/spf13/cast v1.5.0/go.mod h1:SpXXQ5YoyJw6s3/6cMTQuxvgRl3PCJiyaX9p6b155UU= github.com/spf13/cobra v0.0.3/go.mod h1:1l0Ry5zgKvJasoi3XT1TypsSe7PqH0Sj9dhYf7v3XqQ= github.com/spf13/cobra v0.0.5/go.mod h1:3K3wKZymM7VvHMDS9+Akkh4K60UwM26emMESw8tLCHU= -github.com/spf13/cobra v1.6.1 h1:o94oiPyS4KD1mPy2fmcYYHHfCxLqYjJOhGsCHFZtEzA= -github.com/spf13/cobra v1.6.1/go.mod h1:IOw/AERYS7UzyrGinqmz6HLUo219MORXGxhbaJUqzrY= +github.com/spf13/cobra v1.7.0 h1:hyqWnYt1ZQShIddO5kBpj3vu05/++x6tJ6dg8EC572I= +github.com/spf13/cobra v1.7.0/go.mod h1:uLxZILRyS/50WlhOIKD7W6V5bgeIt+4sICxh6uRMrb0= github.com/spf13/jwalterweatherman v1.0.0/go.mod h1:cQK4TGJAtQXfYWX+Ddv3mKDzgVb68N+wFjFa4jdeBTo= github.com/spf13/jwalterweatherman v1.1.0 h1:ue6voC5bR5F8YxI5S67j9i582FU4Qvo2bmqnqMYADFk= github.com/spf13/jwalterweatherman v1.1.0/go.mod h1:aNWZUN0dPAAO/Ljvb5BEdw96iTZ0EXowPYD95IqWIGo= @@ -899,8 +900,8 @@ golang.org/x/crypto v0.0.0-20210421170649-83a5a9bb288b/go.mod h1:T9bdIzuCu7OtxOm golang.org/x/crypto v0.0.0-20210711020723-a769d52b0f97/go.mod h1:GvvjBRRGRdwPK5ydBHafDWAxML/pGHZbMvKqRZ5+Abc= golang.org/x/crypto v0.0.0-20210921155107-089bfa567519/go.mod h1:GvvjBRRGRdwPK5ydBHafDWAxML/pGHZbMvKqRZ5+Abc= golang.org/x/crypto v0.0.0-20211108221036-ceb1ce70b4fa/go.mod h1:GvvjBRRGRdwPK5ydBHafDWAxML/pGHZbMvKqRZ5+Abc= -golang.org/x/crypto v0.7.0 h1:AvwMYaRytfdeVt3u6mLaxYtErKYjxA2OXjJ1HHq6t3A= -golang.org/x/crypto v0.7.0/go.mod h1:pYwdfH91IfpZVANVyUOhSIPZaFoJGxTFbZhFTx+dXZU= +golang.org/x/crypto v0.8.0 h1:pd9TJtTueMTVQXzk8E2XESSMQDj/U7OUu0PqJqPXQjQ= +golang.org/x/crypto v0.8.0/go.mod h1:mRqEX+O9/h5TFCrQhkgjo2yKi0yYA+9ecGkdQoHrywE= golang.org/x/exp v0.0.0-20190121172915-509febef88a4/go.mod h1:CJ0aWSM057203Lf6IL+f9T1iT9GByDxfZKAQTCR3kQA= golang.org/x/exp v0.0.0-20190306152737-a1d7652674e8/go.mod h1:CJ0aWSM057203Lf6IL+f9T1iT9GByDxfZKAQTCR3kQA= golang.org/x/exp v0.0.0-20190510132918-efd6b22b2522/go.mod h1:ZjyILWgesfNpC6sMxTJOJm9Kp84zZh5NQWvqDGG3Qr8= @@ -989,8 +990,8 @@ golang.org/x/net v0.0.0-20210805182204-aaa1db679c0d/go.mod h1:9nx3DQGgdP8bBQD5qx golang.org/x/net v0.0.0-20211008194852-3b03d305991f/go.mod h1:9nx3DQGgdP8bBQD5qxJ1jj9UTztislL4KSBs9R2vV5Y= golang.org/x/net v0.0.0-20220225172249-27dd8689420f/go.mod h1:CfG3xpIq0wQ8r1q4Su4UZFWDARRcnwPjda9FqA0JpMk= golang.org/x/net v0.0.0-20220607020251-c690dde0001d/go.mod h1:XRhObCWvk6IyKnWLug+ECip1KBveYUHfp+8e9klMJ9c= -golang.org/x/net v0.8.0 h1:Zrh2ngAOFYneWTAIAPethzeaQLuHwhuBkuV6ZiRnUaQ= -golang.org/x/net v0.8.0/go.mod h1:QVkue5JL9kW//ek3r6jTKnTFis1tRmNAW2P1shuFdJc= +golang.org/x/net v0.9.0 h1:aWJ/m6xSmxWBx+V0XRHTlrYrPG56jKsLdTFmsSsCzOM= +golang.org/x/net v0.9.0/go.mod h1:d48xBJpPfHeWQsugry2m+kC02ZBRGRgulfHnEXEuWns= golang.org/x/oauth2 v0.0.0-20180821212333-d2e6202438be/go.mod h1:N/0e6XlmueqKjAGxoOufVs8QHGRruUQn6yWY3a++T0U= golang.org/x/oauth2 v0.0.0-20190226205417-e64efc72b421/go.mod h1:gOpvHmFTYa4IltrdGE7lF6nIHvwfUNPOp7c8zoXwtLw= golang.org/x/oauth2 v0.0.0-20190604053449-0f29369cfe45/go.mod h1:gOpvHmFTYa4IltrdGE7lF6nIHvwfUNPOp7c8zoXwtLw= @@ -1093,12 +1094,13 @@ golang.org/x/sys v0.0.0-20220520151302-bc2c85ada10a/go.mod h1:oPkhp1MJrh7nUepCBc golang.org/x/sys v0.0.0-20220811171246-fbc7d0a398ab/go.mod h1:oPkhp1MJrh7nUepCBck5+mAzfO9JrbApNNgaTdGDITg= golang.org/x/sys v0.0.0-20220908164124-27713097b956/go.mod h1:oPkhp1MJrh7nUepCBck5+mAzfO9JrbApNNgaTdGDITg= golang.org/x/sys v0.0.0-20221010170243-090e33056c14/go.mod h1:oPkhp1MJrh7nUepCBck5+mAzfO9JrbApNNgaTdGDITg= -golang.org/x/sys v0.6.0 h1:MVltZSvRTcU2ljQOhs94SXPftV6DCNnZViHeQps87pQ= golang.org/x/sys v0.6.0/go.mod h1:oPkhp1MJrh7nUepCBck5+mAzfO9JrbApNNgaTdGDITg= +golang.org/x/sys v0.7.0 h1:3jlCCIQZPdOYu1h8BkNvLz8Kgwtae2cagcG/VamtZRU= +golang.org/x/sys v0.7.0/go.mod h1:oPkhp1MJrh7nUepCBck5+mAzfO9JrbApNNgaTdGDITg= golang.org/x/term v0.0.0-20201126162022-7de9c90e9dd1/go.mod h1:bj7SfCRtBDWHUb9snDiAeCFNEtKQo2Wmx5Cou7ajbmo= golang.org/x/term v0.0.0-20210927222741-03fcf44c2211/go.mod h1:jbD1KX2456YbFQfuXm/mYQcufACuNUgVhRMnK/tPxf8= -golang.org/x/term v0.6.0 h1:clScbb1cHjoCkyRbWwBEUZ5H/tIFu5TAXIqaZD0Gcjw= -golang.org/x/term v0.6.0/go.mod h1:m6U89DPEgQRMq3DNkDClhWw02AUbt2daBVO4cn4Hv9U= +golang.org/x/term v0.7.0 h1:BEvjmm5fURWqcfbSKTdpkDXYBrUS1c0m8agp14W48vQ= +golang.org/x/term v0.7.0/go.mod h1:P32HKFT3hSsZrRxla30E9HqToFYAQPCMs/zFMBUFqPY= golang.org/x/text v0.0.0-20170915032832-14c0d48ead0c/go.mod h1:NqM8EUOU14njkJ3fqMW+pc6Ldnwhi/IjpwHt7yyuwOQ= golang.org/x/text v0.3.0/go.mod h1:NqM8EUOU14njkJ3fqMW+pc6Ldnwhi/IjpwHt7yyuwOQ= golang.org/x/text v0.3.1-0.20180807135948-17ff2d5776d2/go.mod h1:NqM8EUOU14njkJ3fqMW+pc6Ldnwhi/IjpwHt7yyuwOQ= @@ -1108,8 +1110,8 @@ golang.org/x/text v0.3.4/go.mod h1:5Zoc/QRtKVWzQhOtBMvqHzDpF6irO9z98xDceosuGiQ= golang.org/x/text v0.3.5/go.mod h1:5Zoc/QRtKVWzQhOtBMvqHzDpF6irO9z98xDceosuGiQ= golang.org/x/text v0.3.6/go.mod h1:5Zoc/QRtKVWzQhOtBMvqHzDpF6irO9z98xDceosuGiQ= golang.org/x/text v0.3.7/go.mod h1:u+2+/6zg+i71rQMx5EYifcz6MCKuco9NR6JIITiCfzQ= -golang.org/x/text v0.8.0 h1:57P1ETyNKtuIjB4SRd15iJxuhj8Gc416Y78H3qgMh68= -golang.org/x/text v0.8.0/go.mod h1:e1OnstbJyHTd6l/uOt8jFFHp6TRDWZR/bV3emEE/zU8= +golang.org/x/text v0.9.0 h1:2sjJmO8cDvYveuX97RDLsxlyUxLl+GHoLxBiRdHllBE= +golang.org/x/text v0.9.0/go.mod h1:e1OnstbJyHTd6l/uOt8jFFHp6TRDWZR/bV3emEE/zU8= golang.org/x/time v0.0.0-20180412165947-fbb02b2291d2/go.mod h1:tRJNPiyCQ0inRvYxbN9jk5I+vvW/OXSQhTDSoE431IQ= golang.org/x/time v0.0.0-20181108054448-85acf8d2951c/go.mod h1:tRJNPiyCQ0inRvYxbN9jk5I+vvW/OXSQhTDSoE431IQ= golang.org/x/time v0.0.0-20190308202827-9d24e82272b4/go.mod h1:tRJNPiyCQ0inRvYxbN9jk5I+vvW/OXSQhTDSoE431IQ= @@ -1255,8 +1257,8 @@ google.golang.org/genproto v0.0.0-20210126160654-44e461bb6506/go.mod h1:FWY/as6D google.golang.org/genproto v0.0.0-20210226172003-ab064af71705/go.mod h1:FWY/as6DDZQgahTzZj3fqbO1CbirC29ZNUFHwi0/+no= google.golang.org/genproto v0.0.0-20210624195500-8bfb893ecb84/go.mod h1:SzzZ/N+nwJDaO1kznhnlzqS8ocJICar6hYhVyhi++24= google.golang.org/genproto v0.0.0-20220314164441-57ef72a4c106/go.mod h1:hAL49I2IFola2sVEjAn7MEwsja0xp51I0tlGAf9hz4E= -google.golang.org/genproto v0.0.0-20230320184635-7606e756e683 h1:khxVcsk/FhnzxMKOyD+TDGwjbEOpcPuIpmafPGFmhMA= -google.golang.org/genproto v0.0.0-20230320184635-7606e756e683/go.mod h1:NWraEVixdDnqcqQ30jipen1STv2r/n24Wb7twVTGR4s= +google.golang.org/genproto v0.0.0-20230410155749-daa745c078e1 h1:KpwkzHKEF7B9Zxg18WzOa7djJ+Ha5DzthMyZYQfEn2A= +google.golang.org/genproto v0.0.0-20230410155749-daa745c078e1/go.mod h1:nKE/iIaLqn2bQwXBg8f1g2Ylh6r5MN5CmZvuzZCgsCU= google.golang.org/grpc v1.12.0/go.mod h1:yo6s7OP7yaDglbqo1J04qKzAhqBH6lvTonzMVmEdcZw= google.golang.org/grpc v1.17.0/go.mod h1:6QZJwpn2B+Zp71q/5VxRsJ6NXXVCE5NRUHRo+f3cWCs= google.golang.org/grpc v1.19.0/go.mod h1:mqu4LbDTu4XGKhr4mRzUsmM4RtVoemTSY81AxZiDr8c= diff --git a/tools/cosmovisor/README.md b/tools/cosmovisor/README.md index 46503f29776c..6f6df095d7d0 100644 --- a/tools/cosmovisor/README.md +++ b/tools/cosmovisor/README.md @@ -6,20 +6,21 @@ sidebar_position: 1 `cosmovisor` is a small process manager for Cosmos SDK application binaries that monitors the governance module for incoming chain upgrade proposals. If it sees a proposal that gets approved, `cosmovisor` can automatically download the new binary, stop the current binary, switch from the old binary to the new one, and finally restart the node with the new binary. - * [Design](#design) - * [Contributing](#contributing) - * [Setup](#setup) - * [Installation](#installation) - * [Command Line Arguments And Environment Variables](#command-line-arguments-and-environment-variables) - * [Folder Layout](#folder-layout) - * [Usage](#usage) - * [Initialization](#initialization) - * [Detecting Upgrades](#detecting-upgrades) - * [Auto-Download](#auto-download) - * [Example: SimApp Upgrade](#example-simapp-upgrade) - * [Chain Setup](#chain-setup) - * [Prepare Cosmovisor and Start the Chain](#prepare-cosmovisor-and-start-the-chain) - * [Update App](#update-app) +* [Design](#design) +* [Contributing](#contributing) +* [Setup](#setup) + * [Installation](#installation) + * [Command Line Arguments And Environment Variables](#command-line-arguments-and-environment-variables) + * [Folder Layout](#folder-layout) +* [Usage](#usage) + * [Initialization](#initialization) + * [Detecting Upgrades](#detecting-upgrades) + * [Auto-Download](#auto-download) +* [Example: SimApp Upgrade](#example-simapp-upgrade) + * [Chain Setup](#chain-setup) + * [Prepare Cosmovisor and Start the Chain](#prepare-cosmovisor-and-start-the-chain) + * [Update App](#update-app) + ## Design Cosmovisor is designed to be used as a wrapper for a `Cosmos SDK` app: diff --git a/tools/cosmovisor/args.go b/tools/cosmovisor/args.go index 8c61c1f1c1fb..3d8c33a1e161 100644 --- a/tools/cosmovisor/args.go +++ b/tools/cosmovisor/args.go @@ -12,7 +12,6 @@ import ( "cosmossdk.io/log" cverrors "cosmossdk.io/tools/cosmovisor/errors" - upgradekeeper "cosmossdk.io/x/upgrade/keeper" "cosmossdk.io/x/upgrade/plan" upgradetypes "cosmossdk.io/x/upgrade/types" ) @@ -303,7 +302,7 @@ func (cfg *Config) SetCurrentUpgrade(u upgradetypes.Plan) (rerr error) { } cfg.currentUpgrade = u - f, err := os.Create(filepath.Join(upgrade, upgradekeeper.UpgradeInfoFileName)) + f, err := os.Create(filepath.Join(upgrade, upgradetypes.UpgradeInfoFilename)) if err != nil { return err } @@ -327,7 +326,7 @@ func (cfg *Config) UpgradeInfo() (upgradetypes.Plan, error) { return cfg.currentUpgrade, nil } - filename := filepath.Join(cfg.Root(), currentLink, upgradekeeper.UpgradeInfoFileName) + filename := filepath.Join(cfg.Root(), currentLink, upgradetypes.UpgradeInfoFilename) _, err := os.Lstat(filename) var u upgradetypes.Plan var bz []byte diff --git a/tools/cosmovisor/args_test.go b/tools/cosmovisor/args_test.go index b84e537c69d8..4651c387af34 100644 --- a/tools/cosmovisor/args_test.go +++ b/tools/cosmovisor/args_test.go @@ -371,7 +371,7 @@ func (s *argsTestSuite) TestGetConfigFromEnv() { absPath, perr := filepath.Abs(relPath) s.Require().NoError(perr) - newConfig := func(home, name string, downloadBin, restartUpgrade bool, restartDelay int, skipBackup bool, dataBackupPath string, interval int, preupgradeMaxRetries int, disableLogs bool) *Config { + newConfig := func(home, name string, downloadBin, restartUpgrade bool, restartDelay int, skipBackup bool, dataBackupPath string, interval, preupgradeMaxRetries int, disableLogs bool) *Config { return &Config{ Home: home, Name: name, @@ -609,14 +609,12 @@ func (s *argsTestSuite) TestGetConfigFromEnv() { cfg, err := GetConfigFromEnv() if tc.expectedErrCount == 0 { assert.NoError(t, err) - } else { - if assert.Error(t, err) { - errCount := 1 - if multi, isMulti := err.(*errors.MultiError); isMulti { - errCount = multi.Len() - } - assert.Equal(t, tc.expectedErrCount, errCount, "error count") + } else if assert.Error(t, err) { + errCount := 1 + if multi, isMulti := err.(*errors.MultiError); isMulti { + errCount = multi.Len() } + assert.Equal(t, tc.expectedErrCount, errCount, "error count") } assert.Equal(t, tc.expectedCfg, cfg, "config") }) diff --git a/tools/cosmovisor/buffer_test.go b/tools/cosmovisor/buffer_test.go deleted file mode 100644 index 04dd2bb4c517..000000000000 --- a/tools/cosmovisor/buffer_test.go +++ /dev/null @@ -1,34 +0,0 @@ -package cosmovisor_test - -import ( - "bytes" - "sync" -) - -// buffer is a thread safe bytes buffer -type buffer struct { - b bytes.Buffer - m sync.Mutex -} - -func NewBuffer() *buffer { - return &buffer{} -} - -func (b *buffer) Write(bz []byte) (int, error) { - b.m.Lock() - defer b.m.Unlock() - return b.b.Write(bz) -} - -func (b *buffer) String() string { - b.m.Lock() - defer b.m.Unlock() - return b.b.String() -} - -func (b *buffer) Reset() { - b.m.Lock() - defer b.m.Unlock() - b.b.Reset() -} diff --git a/tools/cosmovisor/cmd/cosmovisor/help_test.go b/tools/cosmovisor/cmd/cosmovisor/help_test.go index 3e31774fa22c..fe4e5d78c93b 100644 --- a/tools/cosmovisor/cmd/cosmovisor/help_test.go +++ b/tools/cosmovisor/cmd/cosmovisor/help_test.go @@ -1,94 +1,14 @@ package main import ( - "fmt" - "os" "testing" - "github.com/stretchr/testify/require" - "github.com/stretchr/testify/suite" + "github.com/stretchr/testify/assert" "cosmossdk.io/tools/cosmovisor" ) -type HelpTestSuite struct { - suite.Suite -} - -func TestHelpTestSuite(t *testing.T) { - suite.Run(t, new(HelpTestSuite)) -} - -// cosmovisorHelpEnv are some string values of environment variables used to configure Cosmovisor. -type cosmovisorHelpEnv struct { - Home string - Name string -} - -// ToMap creates a map of the cosmovisorHelpEnv where the keys are the env var names. -func (c cosmovisorHelpEnv) ToMap() map[string]string { - return map[string]string{ - cosmovisor.EnvHome: c.Home, - cosmovisor.EnvName: c.Name, - } -} - -// Set sets the field in this cosmovisorHelpEnv corresponding to the provided envVar to the given envVal. -func (c *cosmovisorHelpEnv) Set(envVar, envVal string) { - switch envVar { - case cosmovisor.EnvHome: - c.Home = envVal - case cosmovisor.EnvName: - c.Name = envVal - default: - panic(fmt.Errorf("Unknown environment variable [%s]. Ccannot set field to [%s]. ", envVar, envVal)) - } -} - -// clearEnv clears environment variables and returns what they were. -// Designed to be used like this: -// -// initialEnv := clearEnv() -// defer setEnv(nil, initialEnv) -func (s *HelpTestSuite) clearEnv() *cosmovisorHelpEnv { - s.T().Logf("Clearing environment variables.") - rv := cosmovisorHelpEnv{} - for envVar := range rv.ToMap() { - rv.Set(envVar, os.Getenv(envVar)) - s.Require().NoError(os.Unsetenv(envVar)) - } - return &rv -} - -// setEnv sets environment variables to the values provided. -// If t is not nil, and there's a problem, the test will fail immediately. -// If t is nil, problems will just be logged using s.T(). -func (s *HelpTestSuite) setEnv(t *testing.T, env *cosmovisorHelpEnv) { - if t == nil { - s.T().Logf("Restoring environment variables.") - } - for envVar, envVal := range env.ToMap() { - var err error - var msg string - if len(envVal) != 0 { - err = os.Setenv(envVar, envVal) - msg = fmt.Sprintf("setting %s to %s", envVar, envVal) - } else { - err = os.Unsetenv(envVar) - msg = fmt.Sprintf("unsetting %s", envVar) - } - switch { - case t != nil: - require.NoError(t, err, msg) - case err != nil: - s.T().Logf("error %s: %v", msg, err) - default: - s.T().Logf("done %s", msg) - } - } -} - -func (s *HelpTestSuite) TestGetHelpText() { +func TestGetHelpText(t *testing.T) { expectedPieces := []string{ "Cosmovisor", cosmovisor.EnvName, cosmovisor.EnvHome, @@ -97,6 +17,6 @@ func (s *HelpTestSuite) TestGetHelpText() { actual := GetHelpText() for _, piece := range expectedPieces { - s.Assert().Contains(actual, piece) + assert.Contains(t, actual, piece) } } diff --git a/tools/cosmovisor/cmd/cosmovisor/main.go b/tools/cosmovisor/cmd/cosmovisor/main.go index 44bd80fc6235..206802ac19e3 100644 --- a/tools/cosmovisor/cmd/cosmovisor/main.go +++ b/tools/cosmovisor/cmd/cosmovisor/main.go @@ -9,7 +9,7 @@ import ( ) func main() { - logger := log.NewLoggerWithKV(os.Stdout, log.ModuleKey, "cosmovisor") + logger := log.NewLogger(os.Stdout).With(log.ModuleKey, "cosmovisor") ctx := context.WithValue(context.Background(), log.ContextKey, logger) if err := NewRootCmd().ExecuteContext(ctx); err != nil { diff --git a/tools/cosmovisor/go.mod b/tools/cosmovisor/go.mod index 99abd4ac3e4d..9afac8c0e570 100644 --- a/tools/cosmovisor/go.mod +++ b/tools/cosmovisor/go.mod @@ -3,27 +3,28 @@ module cosmossdk.io/tools/cosmovisor go 1.20 require ( - cosmossdk.io/log v0.1.0 + cosmossdk.io/log v1.0.0 cosmossdk.io/x/upgrade v0.0.0-20230227110325-294ef34f396f - github.com/otiai10/copy v1.9.0 - github.com/rs/zerolog v1.29.0 - github.com/spf13/cobra v1.6.1 + github.com/otiai10/copy v1.10.0 + github.com/rs/zerolog v1.29.1 + github.com/spf13/cobra v1.7.0 github.com/stretchr/testify v1.8.2 ) require ( cloud.google.com/go v0.110.0 // indirect - cloud.google.com/go/compute v1.18.0 // indirect + cloud.google.com/go/compute v1.19.0 // indirect cloud.google.com/go/compute/metadata v0.2.3 // indirect cloud.google.com/go/iam v0.13.0 // indirect cloud.google.com/go/storage v1.30.0 // indirect - cosmossdk.io/api v0.3.2-0.20230313131911-55bf5d4efbe7 // indirect - cosmossdk.io/collections v0.0.0-20230309163709-87da587416ba // indirect + cosmossdk.io/api v0.4.0 // indirect + cosmossdk.io/collections v0.1.0 // indirect cosmossdk.io/core v0.6.1 // indirect cosmossdk.io/depinject v1.0.0-alpha.3 // indirect cosmossdk.io/errors v1.0.0-beta.7 // indirect cosmossdk.io/math v1.0.0 // indirect - cosmossdk.io/store v0.1.0-alpha.1 // indirect + cosmossdk.io/store v0.1.0-alpha.1.0.20230328185921-37ba88872dbc // indirect + cosmossdk.io/x/tx v0.5.1-0.20230407182919-057d2e09bd63 // indirect filippo.io/edwards25519 v1.0.0 // indirect github.com/99designs/go-keychain v0.0.0-20191008050251-8e49817e8af4 // indirect github.com/99designs/keyring v1.2.1 // indirect @@ -39,28 +40,28 @@ require ( github.com/cespare/xxhash/v2 v2.2.0 // indirect github.com/cockroachdb/errors v1.9.1 // indirect github.com/cockroachdb/logtags v0.0.0-20230118201751-21c54148d20b // indirect - github.com/cockroachdb/pebble v0.0.0-20230315223031-1e5ddd10389e // indirect + github.com/cockroachdb/pebble v0.0.0-20230412222916-60cfeb46143b // indirect github.com/cockroachdb/redact v1.1.3 // indirect - github.com/cometbft/cometbft v0.37.0 // indirect + github.com/cometbft/cometbft v0.37.1-0.20230411132551-3a91d155e664 // indirect github.com/confio/ics23/go v0.9.0 // indirect github.com/cosmos/btcutil v1.0.5 // indirect github.com/cosmos/cosmos-db v1.0.0-rc.1 // indirect github.com/cosmos/cosmos-proto v1.0.0-beta.3 // indirect - github.com/cosmos/cosmos-sdk v0.46.0-beta2.0.20230321173237-fe77d4bca302 // indirect + github.com/cosmos/cosmos-sdk v0.46.0-beta2.0.20230418140744-0dde947d0ab7 // indirect github.com/cosmos/go-bip39 v1.0.0 // indirect github.com/cosmos/gogogateway v1.2.0 // indirect - github.com/cosmos/gogoproto v1.4.6 // indirect + github.com/cosmos/gogoproto v1.4.8 // indirect github.com/cosmos/iavl v0.21.0-beta.1 // indirect github.com/cosmos/ledger-cosmos-go v0.13.0 // indirect github.com/danieljoos/wincred v1.1.2 // indirect github.com/davecgh/go-spew v1.1.1 // indirect - github.com/decred/dcrd/dcrec/secp256k1/v4 v4.1.0 // indirect + github.com/decred/dcrd/dcrec/secp256k1/v4 v4.2.0 // indirect github.com/desertbit/timer v0.0.0-20180107155436-c41aec40b27f // indirect github.com/dvsekhvalnov/jose2go v1.5.0 // indirect github.com/fatih/color v1.15.0 // indirect github.com/felixge/httpsnoop v1.0.2 // indirect github.com/fsnotify/fsnotify v1.6.0 // indirect - github.com/getsentry/sentry-go v0.19.0 // indirect + github.com/getsentry/sentry-go v0.20.0 // indirect github.com/go-kit/kit v0.12.0 // indirect github.com/go-kit/log v0.2.1 // indirect github.com/go-logfmt/logfmt v0.6.0 // indirect @@ -98,11 +99,11 @@ require ( github.com/improbable-eng/grpc-web v0.15.0 // indirect github.com/inconshreveable/mousetrap v1.1.0 // indirect github.com/jmespath/go-jmespath v0.4.0 // indirect - github.com/klauspost/compress v1.16.3 // indirect + github.com/klauspost/compress v1.16.5 // indirect github.com/kr/pretty v0.3.1 // indirect github.com/kr/text v0.2.0 // indirect github.com/libp2p/go-buffer-pool v0.1.0 // indirect - github.com/linxGnu/grocksdb v1.7.15 // indirect + github.com/linxGnu/grocksdb v1.7.16 // indirect github.com/magiconair/properties v1.8.7 // indirect github.com/mattn/go-colorable v0.1.13 // indirect github.com/mattn/go-isatty v0.0.18 // indirect @@ -117,12 +118,12 @@ require ( github.com/petermattis/goid v0.0.0-20230317030725-371a4b8eda08 // indirect github.com/pkg/errors v0.9.1 // indirect github.com/pmezard/go-difflib v1.0.0 // indirect - github.com/prometheus/client_golang v1.14.0 // indirect + github.com/prometheus/client_golang v1.15.0 // indirect github.com/prometheus/client_model v0.3.0 // indirect github.com/prometheus/common v0.42.0 // indirect github.com/prometheus/procfs v0.9.0 // indirect github.com/rcrowley/go-metrics v0.0.0-20201227073835-cf1acfcdf475 // indirect - github.com/rogpeppe/go-internal v1.9.0 // indirect + github.com/rogpeppe/go-internal v1.10.0 // indirect github.com/rs/cors v1.8.3 // indirect github.com/sasha-s/go-deadlock v0.3.1 // indirect github.com/spf13/afero v1.9.3 // indirect @@ -138,17 +139,17 @@ require ( github.com/zondax/hid v0.9.1 // indirect github.com/zondax/ledger-go v0.14.1 // indirect go.opencensus.io v0.24.0 // indirect - golang.org/x/crypto v0.7.0 // indirect + golang.org/x/crypto v0.8.0 // indirect golang.org/x/exp v0.0.0-20230321023759-10a507213a29 // indirect - golang.org/x/net v0.8.0 // indirect + golang.org/x/net v0.9.0 // indirect golang.org/x/oauth2 v0.6.0 // indirect - golang.org/x/sys v0.6.0 // indirect - golang.org/x/term v0.6.0 // indirect - golang.org/x/text v0.8.0 // indirect + golang.org/x/sys v0.7.0 // indirect + golang.org/x/term v0.7.0 // indirect + golang.org/x/text v0.9.0 // indirect golang.org/x/xerrors v0.0.0-20220907171357-04be3eba64a2 // indirect google.golang.org/api v0.114.0 // indirect google.golang.org/appengine v1.6.7 // indirect - google.golang.org/genproto v0.0.0-20230320184635-7606e756e683 // indirect + google.golang.org/genproto v0.0.0-20230410155749-daa745c078e1 // indirect google.golang.org/grpc v1.54.0 // indirect google.golang.org/protobuf v1.30.0 // indirect gopkg.in/ini.v1 v1.67.0 // indirect diff --git a/tools/cosmovisor/go.sum b/tools/cosmovisor/go.sum index c329e79916b2..1ddfe4592cf6 100644 --- a/tools/cosmovisor/go.sum +++ b/tools/cosmovisor/go.sum @@ -70,8 +70,8 @@ cloud.google.com/go/compute v1.6.0/go.mod h1:T29tfhtVbq1wvAPo0E3+7vhgmkOYeXjhFvz cloud.google.com/go/compute v1.6.1/go.mod h1:g85FgpzFvNULZ+S8AYq87axRKuf2Kh7deLqV/jJ3thU= cloud.google.com/go/compute v1.7.0/go.mod h1:435lt8av5oL9P3fv1OEzSbSUe+ybHXGMPQHHZWZxy9U= cloud.google.com/go/compute v1.10.0/go.mod h1:ER5CLbMxl90o2jtNbGSbtfOpQKR0t15FOtRsugnLrlU= -cloud.google.com/go/compute v1.18.0 h1:FEigFqoDbys2cvFkZ9Fjq4gnHBP55anJ0yQyau2f9oY= -cloud.google.com/go/compute v1.18.0/go.mod h1:1X7yHxec2Ga+Ss6jPyjxRxpu2uu7PLgsOVXvgU0yacs= +cloud.google.com/go/compute v1.19.0 h1:+9zda3WGgW1ZSTlVppLCYFIr48Pa35q1uG2N1itbCEQ= +cloud.google.com/go/compute v1.19.0/go.mod h1:rikpw2y+UMidAe9tISo04EHNOIf42RLYF/q8Bs93scU= cloud.google.com/go/compute/metadata v0.2.3 h1:mg4jlk7mCAj6xXp9UJ4fjI9VUI5rubuGBW5aJ7UnBMY= cloud.google.com/go/compute/metadata v0.2.3/go.mod h1:VAV5nSsACxMJvgaAuX6Pk2AawlZn8kiOGuCv6gTkwuA= cloud.google.com/go/containeranalysis v0.5.1/go.mod h1:1D92jd8gRR/c0fGMlymRgxWD3Qw9C1ff6/T7mLgVL8I= @@ -188,23 +188,24 @@ cloud.google.com/go/webrisk v1.4.0/go.mod h1:Hn8X6Zr+ziE2aNd8SliSDWpEnSS1u4R9+xX cloud.google.com/go/webrisk v1.5.0/go.mod h1:iPG6fr52Tv7sGk0H6qUFzmL3HHZev1htXuWDEEsqMTg= cloud.google.com/go/workflows v1.6.0/go.mod h1:6t9F5h/unJz41YqfBmqSASJSXccBLtD1Vwf+KmJENM0= cloud.google.com/go/workflows v1.7.0/go.mod h1:JhSrZuVZWuiDfKEFxU0/F1PQjmpnpcoISEXH2bcHC3M= -cosmossdk.io/api v0.3.2-0.20230313131911-55bf5d4efbe7 h1:4LrWK+uGP5IxznxtHHsHD+ZBs2+oZRH2loYOGjHLzZM= -cosmossdk.io/api v0.3.2-0.20230313131911-55bf5d4efbe7/go.mod h1:yVns7mKgcsG+hZW/3C5FdJtC6QYWdFIcRlKb9+5HV5g= -cosmossdk.io/collections v0.0.0-20230309163709-87da587416ba h1:S4PYij/tX3Op/hwenVEN9D+M27JRcwSwVqE3UA0BnwM= -cosmossdk.io/collections v0.0.0-20230309163709-87da587416ba/go.mod h1:lpS+G8bGC2anqzWdndTzjnQnuMO/qAcgZUkGJp4i3rc= +cosmossdk.io/api v0.4.0 h1:x90DmdidP6EhzktAa/6/IofSHidDnPjahdlrUvyQZQw= +cosmossdk.io/api v0.4.0/go.mod h1:TWDzBhUBhI1LhSf2XSYpfIBf6D4mbLu/fvzvDfhcaYM= +cosmossdk.io/collections v0.1.0 h1:nzJGeiq32KnZroSrhB6rPifw4I85Cgmzw/YAmr4luv8= +cosmossdk.io/collections v0.1.0/go.mod h1:xbauc0YsbUF8qKMVeBZl0pFCunxBIhKN/WlxpZ3lBuo= cosmossdk.io/core v0.6.1 h1:OBy7TI2W+/gyn2z40vVvruK3di+cAluinA6cybFbE7s= cosmossdk.io/core v0.6.1/go.mod h1:g3MMBCBXtxbDWBURDVnJE7XML4BG5qENhs0gzkcpuFA= cosmossdk.io/depinject v1.0.0-alpha.3 h1:6evFIgj//Y3w09bqOUOzEpFj5tsxBqdc5CfkO7z+zfw= cosmossdk.io/depinject v1.0.0-alpha.3/go.mod h1:eRbcdQ7MRpIPEM5YUJh8k97nxHpYbc3sMUnEtt8HPWU= cosmossdk.io/errors v1.0.0-beta.7 h1:gypHW76pTQGVnHKo6QBkb4yFOJjC+sUGRc5Al3Odj1w= cosmossdk.io/errors v1.0.0-beta.7/go.mod h1:mz6FQMJRku4bY7aqS/Gwfcmr/ue91roMEKAmDUDpBfE= -cosmossdk.io/log v0.1.0 h1:Vnexi+KzUCjmqq/m93teAxjt5biWFfZ5PI1imx2IJw8= -cosmossdk.io/log v0.1.0/go.mod h1:p95Wq6mDY3SREMc4y7+QU9Uwy3nyvfpWGD1iSaFkVFs= +cosmossdk.io/log v1.0.0 h1:NGKZ/A5rd4PduDfoscgABklX557PWjQINbosZy/m3Jk= +cosmossdk.io/log v1.0.0/go.mod h1:CwX9BLiBruZb7lzLlRr3R231d/fVPUXk8gAdV4LQap0= cosmossdk.io/math v1.0.0 h1:ro9w7eKx23om2tZz/VM2Pf+z2WAbGX1yDQQOJ6iGeJw= cosmossdk.io/math v1.0.0/go.mod h1:Ygz4wBHrgc7g0N+8+MrnTfS9LLn9aaTGa9hKopuym5k= -cosmossdk.io/store v0.1.0-alpha.1 h1:NGomhLUXzAxvK4OF8+yP6eNUG5i4LwzOzx+S494pTCg= -cosmossdk.io/store v0.1.0-alpha.1/go.mod h1:kmCMbhrleCZ6rDZPY/EGNldNvPebFNyVPFYp+pv05/k= -cosmossdk.io/x/tx v0.3.1-0.20230321155358-6522dd1731b5 h1:AlvyRc7f7Py1mv254vrqjIIuykCnitHIz2T+nup3bU0= +cosmossdk.io/store v0.1.0-alpha.1.0.20230328185921-37ba88872dbc h1:9piuA+NYmhe+SyMPtMoboLw/djgDbrI3dD5TG020Tnk= +cosmossdk.io/store v0.1.0-alpha.1.0.20230328185921-37ba88872dbc/go.mod h1:UFF5rmjN7WYVfxo6ArdY/l1+yyWMURBWOmSJypGqFHQ= +cosmossdk.io/x/tx v0.5.1-0.20230407182919-057d2e09bd63 h1:zHqj2VwZ/MStFmR7SUe/7gErOFhL9v2rkjmWPB/st34= +cosmossdk.io/x/tx v0.5.1-0.20230407182919-057d2e09bd63/go.mod h1:Oh3Kh+IPOfMEILNxVd2e8SLqRrIjYHpdGBfDg4ghU/k= cosmossdk.io/x/upgrade v0.0.0-20230227110325-294ef34f396f h1:K9arlZkok6I5X5+FEqQBj3vtTXSccWTfOsU9WPhsif0= cosmossdk.io/x/upgrade v0.0.0-20230227110325-294ef34f396f/go.mod h1:DgT89ckyz+u8XVfYdIoAhkFXV+o3ieva3zE+qoYu89g= dmitri.shuralyov.com/gpu/mtl v0.0.0-20190408044501-666a987793e9/go.mod h1:H6x//7gZCb22OMCxBHrMx7a5I7Hp++hsVxbQ4BYO7hU= @@ -267,6 +268,7 @@ github.com/bgentry/go-netrc v0.0.0-20140422174119-9fd32a8b3d3d/go.mod h1:6QX/PXZ github.com/bgentry/speakeasy v0.1.0/go.mod h1:+zsyZBPWlz7T6j88CTgSN5bM796AkVf0kBD4zp0CCIs= github.com/bgentry/speakeasy v0.1.1-0.20220910012023-760eaf8b6816 h1:41iFGWnSlI2gVpmOtVTJZNodLdLQLn/KsJqFvXwnd/s= github.com/bgentry/speakeasy v0.1.1-0.20220910012023-760eaf8b6816/go.mod h1:+zsyZBPWlz7T6j88CTgSN5bM796AkVf0kBD4zp0CCIs= +github.com/bits-and-blooms/bitset v1.6.0 h1:FVfaUsleKAUTJnaN9Fd1YFFi1S8vAX5xeXnXHFYOojM= github.com/btcsuite/btcd/btcec/v2 v2.3.2 h1:5n0X6hX0Zk+6omWcihdYvdAlGf2DfasC0GMf7DClJ3U= github.com/btcsuite/btcd/btcec/v2 v2.3.2/go.mod h1:zYzJ8etWJQIv1Ogk7OzpWjowwOdXY1W/17j2MW85J04= github.com/btcsuite/btcd/btcutil v1.1.2 h1:XLMbX8JQEiwMcYft2EGi8zPUkoa0abKIU6/BJSRsjzQ= @@ -310,14 +312,14 @@ github.com/cockroachdb/errors v1.9.1/go.mod h1:2sxOtL2WIc096WSZqZ5h8fa17rdDq9HZO github.com/cockroachdb/logtags v0.0.0-20211118104740-dabe8e521a4f/go.mod h1:Vz9DsVWQQhf3vs21MhPMZpMGSht7O/2vFW2xusFUVOs= github.com/cockroachdb/logtags v0.0.0-20230118201751-21c54148d20b h1:r6VH0faHjZeQy818SGhaone5OnYfxFR/+AzdY3sf5aE= github.com/cockroachdb/logtags v0.0.0-20230118201751-21c54148d20b/go.mod h1:Vz9DsVWQQhf3vs21MhPMZpMGSht7O/2vFW2xusFUVOs= -github.com/cockroachdb/pebble v0.0.0-20230315223031-1e5ddd10389e h1:CDuLmyaZ1pD4OJHHtubKqgu/Byw5zAnm+gArJsyj96Q= -github.com/cockroachdb/pebble v0.0.0-20230315223031-1e5ddd10389e/go.mod h1:9lRMC4XN3/BLPtIp6kAKwIaHu369NOf2rMucPzipz50= +github.com/cockroachdb/pebble v0.0.0-20230412222916-60cfeb46143b h1:92ve6F1Pls/eqd+V+102lOMRJatgpqqsQvbT9Bl/fjg= +github.com/cockroachdb/pebble v0.0.0-20230412222916-60cfeb46143b/go.mod h1:9lRMC4XN3/BLPtIp6kAKwIaHu369NOf2rMucPzipz50= github.com/cockroachdb/redact v1.1.3 h1:AKZds10rFSIj7qADf0g46UixK8NNLwWTNdCIGS5wfSQ= github.com/cockroachdb/redact v1.1.3/go.mod h1:BVNblN9mBWFyMyqK1k3AAiSxhvhfK2oOZZ2lK+dpvRg= github.com/codahale/hdrhistogram v0.0.0-20161010025455-3a0bb77429bd/go.mod h1:sE/e/2PUdi/liOCUjSTXgM1o87ZssimdTWN964YiIeI= github.com/codegangsta/inject v0.0.0-20150114235600-33e0aa1cb7c0/go.mod h1:4Zcjuz89kmFXt9morQgcfYZAYZ5n8WHjt81YYWIwtTM= -github.com/cometbft/cometbft v0.37.0 h1:M005vBaSaugvYYmNZwJOopynQSjwLoDTwflnQ/I/eYk= -github.com/cometbft/cometbft v0.37.0/go.mod h1:Y2MMMN//O5K4YKd8ze4r9jmk4Y7h0ajqILXbH5JQFVs= +github.com/cometbft/cometbft v0.37.1-0.20230411132551-3a91d155e664 h1:BbCkbnaU3R603XpnbqvuDU8Kfv+hjhiFILOHhVFntsw= +github.com/cometbft/cometbft v0.37.1-0.20230411132551-3a91d155e664/go.mod h1:Y2MMMN//O5K4YKd8ze4r9jmk4Y7h0ajqILXbH5JQFVs= github.com/cometbft/cometbft-db v0.7.0 h1:uBjbrBx4QzU0zOEnU8KxoDl18dMNgDh+zZRUE0ucsbo= github.com/confio/ics23/go v0.9.0 h1:cWs+wdbS2KRPZezoaaj+qBleXgUk5WOQFMP3CQFGTr4= github.com/confio/ics23/go v0.9.0/go.mod h1:4LPZ2NYqnYIVRklaozjNR1FScgDJ2s5Xrp+e/mYVRak= @@ -325,7 +327,7 @@ github.com/coreos/etcd v3.3.10+incompatible/go.mod h1:uF7uidLiAD3TWHmW31ZFd/JWoc github.com/coreos/go-etcd v2.0.0+incompatible/go.mod h1:Jez6KQU2B/sWsbdaef3ED8NzMklzPG4d5KIOhIy30Tk= github.com/coreos/go-semver v0.2.0/go.mod h1:nnelYz7RCh+5ahJtPPxZlU+153eP4D4r3EedlOD2RNk= github.com/coreos/go-systemd v0.0.0-20180511133405-39ca1b05acc7/go.mod h1:F5haX7vjVVG0kc13fIWeqUViNPyEJxv/OmvnBo0Yme4= -github.com/coreos/go-systemd/v22 v22.3.3-0.20220203105225-a9a7ef127534/go.mod h1:Y58oyj3AT4RCenI/lSvhwexgC+NSVTIJ3seZv2GcEnc= +github.com/coreos/go-systemd/v22 v22.5.0/go.mod h1:Y58oyj3AT4RCenI/lSvhwexgC+NSVTIJ3seZv2GcEnc= github.com/coreos/pkg v0.0.0-20160727233714-3ac0863d7acf/go.mod h1:E3G3o1h8I7cfcXa63jLwjI0eiQQMgzzUDFVpN/nH/eA= github.com/cosmos/btcutil v1.0.5 h1:t+ZFcX77LpKtDBhjucvnOH8C2l2ioGsBNEQ3jef8xFk= github.com/cosmos/btcutil v1.0.5/go.mod h1:IyB7iuqZMJlthe2tkIFL33xPyzbFYP0XVdS8P5lUPis= @@ -333,16 +335,16 @@ github.com/cosmos/cosmos-db v1.0.0-rc.1 h1:SjnT8B6WKMW9WEIX32qMhnEEKcI7ZP0+G1Sa9 github.com/cosmos/cosmos-db v1.0.0-rc.1/go.mod h1:Dnmk3flSf5lkwCqvvjNpoxjpXzhxnCAFzKHlbaForso= github.com/cosmos/cosmos-proto v1.0.0-beta.3 h1:VitvZ1lPORTVxkmF2fAp3IiA61xVwArQYKXTdEcpW6o= github.com/cosmos/cosmos-proto v1.0.0-beta.3/go.mod h1:t8IASdLaAq+bbHbjq4p960BvcTqtwuAxid3b/2rOD6I= -github.com/cosmos/cosmos-sdk v0.46.0-beta2.0.20230321173237-fe77d4bca302 h1:wffm9LPPG/FBW/tSRdJp2DCgkJQRX+Zsbdmn4I0aWeQ= -github.com/cosmos/cosmos-sdk v0.46.0-beta2.0.20230321173237-fe77d4bca302/go.mod h1:HzOsWXtPxhO8+Y8P4Ru+G3UWx6dTkpGXU9yvT35VEuI= +github.com/cosmos/cosmos-sdk v0.46.0-beta2.0.20230418140744-0dde947d0ab7 h1:+Q/K5pdQdQjp21gIxlQgGy4dOZk9gUBSQmJCYIf1bWA= +github.com/cosmos/cosmos-sdk v0.46.0-beta2.0.20230418140744-0dde947d0ab7/go.mod h1:BPvKPN63ettXrpz67uM1rHEqX/UVVkAfceFCPyp217E= github.com/cosmos/go-bip39 v0.0.0-20180819234021-555e2067c45d/go.mod h1:tSxLoYXyBmiFeKpvmq4dzayMdCjCnu8uqmCysIGBT2Y= github.com/cosmos/go-bip39 v1.0.0 h1:pcomnQdrdH22njcAatO0yWojsUnCO3y2tNoV1cb6hHY= github.com/cosmos/go-bip39 v1.0.0/go.mod h1:RNJv0H/pOIVgxw6KS7QeX2a0Uo0aKUlfhZ4xuwvCdJw= github.com/cosmos/gogogateway v1.2.0 h1:Ae/OivNhp8DqBi/sh2A8a1D0y638GpL3tkmLQAiKxTE= github.com/cosmos/gogogateway v1.2.0/go.mod h1:iQpLkGWxYcnCdz5iAdLcRBSw3h7NXeOkZ4GUkT+tbFI= github.com/cosmos/gogoproto v1.4.2/go.mod h1:cLxOsn1ljAHSV527CHOtaIP91kK6cCrZETRBrkzItWU= -github.com/cosmos/gogoproto v1.4.6 h1:Ee7z15dWJaGlgM2rWrK8N2IX7PQcuccu8oG68jp5RL4= -github.com/cosmos/gogoproto v1.4.6/go.mod h1:VS/ASYmPgv6zkPKLjR9EB91lwbLHOzaGCirmKKhncfI= +github.com/cosmos/gogoproto v1.4.8 h1:BrHKc6WFZt8+jRV71vKSQE+JrfF+JAnzrKo2VP7wIZ4= +github.com/cosmos/gogoproto v1.4.8/go.mod h1:hnb0DIEWTv+wdNzNcqus5xCQXq5+CXauq1FJuurRfVY= github.com/cosmos/iavl v0.21.0-beta.1 h1:fBQeBc8HLZ14plJNcmGfaOXSSMLVEHvEQXiTXSD76m0= github.com/cosmos/iavl v0.21.0-beta.1/go.mod h1:25YJYzilTErJ2mKfNB3xyWL9IsCwEQdNzdIutg2mh3U= github.com/cosmos/ledger-cosmos-go v0.13.0 h1:ex0CvCxToSR7j5WjrghPu2Bu9sSXKikjnVvUryNnx4s= @@ -360,9 +362,9 @@ github.com/danieljoos/wincred v1.1.2/go.mod h1:GijpziifJoIBfYh+S7BbkdUTU4LfM+QnG github.com/davecgh/go-spew v1.1.0/go.mod h1:J7Y8YcW2NihsgmVo/mv3lAwl/skON4iLHjSsI+c5H38= github.com/davecgh/go-spew v1.1.1 h1:vj9j/u1bqnvCEfJOwUhtlOARqs3+rkHYY13jYWTU97c= github.com/davecgh/go-spew v1.1.1/go.mod h1:J7Y8YcW2NihsgmVo/mv3lAwl/skON4iLHjSsI+c5H38= -github.com/decred/dcrd/crypto/blake256 v1.0.0 h1:/8DMNYp9SGi5f0w7uCm6d6M4OU2rGFK09Y2A4Xv7EE0= -github.com/decred/dcrd/dcrec/secp256k1/v4 v4.1.0 h1:HbphB4TFFXpv7MNrT52FGrrgVXF1owhMVTHFZIlnvd4= -github.com/decred/dcrd/dcrec/secp256k1/v4 v4.1.0/go.mod h1:DZGJHZMqrU4JJqFAWUS2UO1+lbSKsdiOoYi9Zzey7Fc= +github.com/decred/dcrd/crypto/blake256 v1.0.1 h1:7PltbUIQB7u/FfZ39+DGa/ShuMyJ5ilcvdfma9wOH6Y= +github.com/decred/dcrd/dcrec/secp256k1/v4 v4.2.0 h1:8UrgZ3GkP4i/CLijOJx79Yu+etlyjdBU4sfcs2WYQMs= +github.com/decred/dcrd/dcrec/secp256k1/v4 v4.2.0/go.mod h1:v57UDF4pDQJcEfFUCRop3lJL149eHGSe9Jvczhzjo/0= github.com/desertbit/timer v0.0.0-20180107155436-c41aec40b27f h1:U5y3Y5UE0w7amNe7Z5G/twsBW0KEalRQXZzf8ufSh9I= github.com/desertbit/timer v0.0.0-20180107155436-c41aec40b27f/go.mod h1:xH/i4TFMt8koVQZ6WFms69WAsDWr2XsYL3Hkl7jkoLE= github.com/dgraph-io/badger v1.6.0 h1:DshxFxZWXUcO0xX476VJC07Xsr6ZCBVRHKZ93Oh7Evo= @@ -414,8 +416,8 @@ github.com/fsnotify/fsnotify v1.6.0 h1:n+5WquG0fcWoWp6xPWfHdbskMCQaFnG6PfBrh1Ky4 github.com/fsnotify/fsnotify v1.6.0/go.mod h1:sl3t1tCWJFWoRz9R8WJCbQihKKwmorjAbSClcnxKAGw= github.com/gavv/httpexpect v2.0.0+incompatible/go.mod h1:x+9tiU1YnrOvnB725RkpoLv1M62hOWzwo5OXotisrKc= github.com/getsentry/sentry-go v0.12.0/go.mod h1:NSap0JBYWzHND8oMbyi0+XZhUalc1TBdRL1M71JZW2c= -github.com/getsentry/sentry-go v0.19.0 h1:BcCH3CN5tXt5aML+gwmbFwVptLLQA+eT866fCO9wVOM= -github.com/getsentry/sentry-go v0.19.0/go.mod h1:y3+lGEFEFexZtpbG1GUE2WD/f9zGyKYwpEqryTOC/nE= +github.com/getsentry/sentry-go v0.20.0 h1:bwXW98iMRIWxn+4FgPW7vMrjmbym6HblXALmhjHmQaQ= +github.com/getsentry/sentry-go v0.20.0/go.mod h1:lc76E2QywIyW8WuBnwl8Lc4bkmQH4+w1gwTf25trprY= github.com/ghodss/yaml v1.0.0/go.mod h1:4dBDuWmgqj2HViK6kFavaiC9ZROes6MMH2rRYeMEF04= github.com/gin-contrib/sse v0.0.0-20190301062529-5545eab6dad3/go.mod h1:VJ0WA2NBN22VlZ2dKZQPAPnyWw5XTlK1KymzLKsr59s= github.com/gin-contrib/sse v0.1.0 h1:Y/yl/+YNO8GZSjAhjMsSuLt29uWRFHdHYUb5lYOV9qE= @@ -675,7 +677,6 @@ github.com/imkira/go-interpol v1.1.0/go.mod h1:z0h2/2T3XF8kyEPpRgJ3kmNv+C43p+I/C github.com/improbable-eng/grpc-web v0.15.0 h1:BN+7z6uNXZ1tQGcNAuaU1YjsLTApzkjt2tzCixLaUPQ= github.com/improbable-eng/grpc-web v0.15.0/go.mod h1:1sy9HKV4Jt9aEs9JSnkWlRJPuPtwNr0l57L4f878wP8= github.com/inconshreveable/mousetrap v1.0.0/go.mod h1:PxqpIevigyE2G7u3NXJIT2ANytuPF1OarO4DADm73n8= -github.com/inconshreveable/mousetrap v1.0.1/go.mod h1:vpF70FUmC8bwa3OWnCshd2FqLfsEA9PFc4w1p2J65bw= github.com/inconshreveable/mousetrap v1.1.0 h1:wN+x4NVGpMsO7ErUn/mUI3vEoE6Jt13X2s0bqwp9tc8= github.com/inconshreveable/mousetrap v1.1.0/go.mod h1:vpF70FUmC8bwa3OWnCshd2FqLfsEA9PFc4w1p2J65bw= github.com/influxdata/influxdb1-client v0.0.0-20191209144304-8bf82d3c094d/go.mod h1:qj24IKcXYK6Iy9ceXlo3Tc+vtHo9lIhSX5JddghvEPo= @@ -719,8 +720,8 @@ github.com/klauspost/compress v1.9.7/go.mod h1:RyIbtBH6LamlWaDj8nUwkbUhJ87Yi3uG0 github.com/klauspost/compress v1.10.3/go.mod h1:aoV0uJVorq1K+umq18yTdKaF57EivdYsUV+/s2qKfXs= github.com/klauspost/compress v1.11.7/go.mod h1:aoV0uJVorq1K+umq18yTdKaF57EivdYsUV+/s2qKfXs= github.com/klauspost/compress v1.15.11/go.mod h1:QPwzmACJjUTFsnSHH934V6woptycfrDDJnH7hvFVbGM= -github.com/klauspost/compress v1.16.3 h1:XuJt9zzcnaz6a16/OU53ZjWp/v7/42WcR5t2a0PcNQY= -github.com/klauspost/compress v1.16.3/go.mod h1:ntbaceVETuRiXiv4DpjP66DpAtAGkEQskQzEyD//IeE= +github.com/klauspost/compress v1.16.5 h1:IFV2oUNUzZaz+XyusxpLzpzS8Pt5rh0Z16For/djlyI= +github.com/klauspost/compress v1.16.5/go.mod h1:ntbaceVETuRiXiv4DpjP66DpAtAGkEQskQzEyD//IeE= github.com/klauspost/cpuid v1.2.1/go.mod h1:Pj4uuM528wm8OyEC2QMXAi2YiTZ96dNQPGgoMS4s3ek= github.com/konsorten/go-windows-terminal-sequences v1.0.1/go.mod h1:T0+1ngSBFLxvqU3pZ+m/2kptfBszLMUkC4ZK/EgS/cQ= github.com/konsorten/go-windows-terminal-sequences v1.0.3/go.mod h1:T0+1ngSBFLxvqU3pZ+m/2kptfBszLMUkC4ZK/EgS/cQ= @@ -743,8 +744,8 @@ github.com/libp2p/go-buffer-pool v0.1.0 h1:oK4mSFcQz7cTQIfqbe4MIj9gLW+mnanjyFtc6 github.com/libp2p/go-buffer-pool v0.1.0/go.mod h1:N+vh8gMqimBzdKkSMVuydVDq+UV5QTWy5HSiZacSbPg= github.com/lightstep/lightstep-tracer-common/golang/gogo v0.0.0-20190605223551-bc2310a04743/go.mod h1:qklhhLq1aX+mtWk9cPHPzaBjWImj5ULL6C7HFJtXQMM= github.com/lightstep/lightstep-tracer-go v0.18.1/go.mod h1:jlF1pusYV4pidLvZ+XD0UBX0ZE6WURAspgAczcDHrL4= -github.com/linxGnu/grocksdb v1.7.15 h1:AEhP28lkeAybv5UYNYviYISpR6bJejEnKuYbnWAnxx0= -github.com/linxGnu/grocksdb v1.7.15/go.mod h1:pY55D0o+r8yUYLq70QmhdudxYvoDb9F+9puf4m3/W+U= +github.com/linxGnu/grocksdb v1.7.16 h1:Q2co1xrpdkr5Hx3Fp+f+f7fRGhQFQhvi/+226dtLmA8= +github.com/linxGnu/grocksdb v1.7.16/go.mod h1:JkS7pl5qWpGpuVb3bPqTz8nC12X3YtPZT+Xq7+QfQo4= github.com/lyft/protoc-gen-validate v0.0.13/go.mod h1:XbGvPuh87YZc5TdIa2/I4pLk0QoUACkjt2znoq26NVQ= github.com/magiconair/properties v1.8.0/go.mod h1:PppfXfuXeibc/6YijjN8zIbojt8czPbwD3XqdrwzmxQ= github.com/magiconair/properties v1.8.7 h1:IeQXZAiQcpL9mgcAe1Nu6cX9LLw6ExEHKjN0VQdvPDY= @@ -846,13 +847,9 @@ github.com/openzipkin-contrib/zipkin-go-opentracing v0.4.5/go.mod h1:/wsWhb9smxS github.com/openzipkin/zipkin-go v0.1.6/go.mod h1:QgAqvLzwWbR/WpD4A3cGpPtJrZXNIiJc5AZX7/PBEpw= github.com/openzipkin/zipkin-go v0.2.1/go.mod h1:NaW6tEwdmWMaCDZzg8sh+IBNOxHMPnhQw8ySjnjRyN4= github.com/openzipkin/zipkin-go v0.2.2/go.mod h1:NaW6tEwdmWMaCDZzg8sh+IBNOxHMPnhQw8ySjnjRyN4= -github.com/otiai10/copy v1.9.0 h1:7KFNiCgZ91Ru4qW4CWPf/7jqtxLagGRmIxWldPP9VY4= -github.com/otiai10/copy v1.9.0/go.mod h1:hsfX19wcn0UWIHUQ3/4fHuehhk2UyArQ9dVFAn3FczI= -github.com/otiai10/curr v0.0.0-20150429015615-9b4961190c95/go.mod h1:9qAhocn7zKJG+0mI8eUu6xqkFDYS2kb2saOteoSB3cE= -github.com/otiai10/curr v1.0.0/go.mod h1:LskTG5wDwr8Rs+nNQ+1LlxRjAtTZZjtJW4rMXl6j4vs= -github.com/otiai10/mint v1.3.0/go.mod h1:F5AjcsTsWUqX+Na9fpHb52P8pcRX2CI6A3ctIT91xUo= -github.com/otiai10/mint v1.4.0 h1:umwcf7gbpEwf7WFzqmWwSv0CzbeMsae2u9ZvpP8j2q4= -github.com/otiai10/mint v1.4.0/go.mod h1:gifjb2MYOoULtKLqUAEILUG/9KONW6f7YsJ6vQLTlFI= +github.com/otiai10/copy v1.10.0 h1:znyI7l134wNg/wDktoVQPxPkgvhDfGCYUasey+h0rDQ= +github.com/otiai10/copy v1.10.0/go.mod h1:rSaLseMUsZFFbsFGc7wCJnnkTAvdc5L6VWxPE4308Ww= +github.com/otiai10/mint v1.5.1 h1:XaPLeE+9vGbuyEHem1JNk3bYc7KKqyI/na0/mLd/Kks= github.com/pact-foundation/pact-go v1.0.4/go.mod h1:uExwJY4kCzNPcHRj+hCR/HBbOOIwwtUjcrb0b5/5kLM= github.com/pascaldekloe/goe v0.0.0-20180627143212-57f6aae5913c/go.mod h1:lzWF7FIEvWOWxwDKqyGYQf6ZUaNfKdP144TG7ZOy1lc= github.com/pascaldekloe/goe v0.1.0 h1:cBOtyMzM9HTpWjXfbbunk26uA6nG3a8n06Wieeh0MwY= @@ -885,8 +882,8 @@ github.com/prometheus/client_golang v1.0.0/go.mod h1:db9x61etRT2tGnBNRi70OPL5Fsn github.com/prometheus/client_golang v1.3.0/go.mod h1:hJaj2vgQTGQmVCsAACORcieXFeDPbaTKGT+JTgUa3og= github.com/prometheus/client_golang v1.4.0/go.mod h1:e9GMxYsXl05ICDXkRhurwBS4Q3OK1iX/F2sw+iXX5zU= github.com/prometheus/client_golang v1.7.1/go.mod h1:PY5Wy2awLA44sXw4AOSfFBetzPP4j5+D6mVACh+pe2M= -github.com/prometheus/client_golang v1.14.0 h1:nJdhIvne2eSX/XRAFV9PcvFFRbrjbcTUj0VP62TMhnw= -github.com/prometheus/client_golang v1.14.0/go.mod h1:8vpkKitgIVNcqrRBWh1C4TIUQgYNtG/XQE4E/Zae36Y= +github.com/prometheus/client_golang v1.15.0 h1:5fCgGYogn0hFdhyhLbw7hEsWxufKtY9klyvdNfFlFhM= +github.com/prometheus/client_golang v1.15.0/go.mod h1:e9yaBhRPU2pPNsZwE+JdQl0KEt1N9XgF6zxWmaC0xOk= github.com/prometheus/client_model v0.0.0-20180712105110-5c3871d89910/go.mod h1:MbSGuTsp3dbXC40dX6PRTWyKYBIrTGTE9sqQNg2J8bo= github.com/prometheus/client_model v0.0.0-20190115171406-56726106282f/go.mod h1:MbSGuTsp3dbXC40dX6PRTWyKYBIrTGTE9sqQNg2J8bo= github.com/prometheus/client_model v0.0.0-20190129233127-fd36f4220a90/go.mod h1:xMI15A0UPsDsEKsMN9yxemIoYk6Tm2C1GtYGdfGttqA= @@ -920,14 +917,15 @@ github.com/rogpeppe/fastuuid v1.2.0/go.mod h1:jVj6XXZzXRy/MSR5jhDC/2q6DgLz+nrA6L github.com/rogpeppe/go-internal v1.3.0/go.mod h1:M8bDsm7K2OlrFYOpmOWEs/qY81heoFRclV5y23lUDJ4= github.com/rogpeppe/go-internal v1.6.1/go.mod h1:xXDCJY+GAPziupqXw64V24skbSoqbTEfhy4qGm1nDQc= github.com/rogpeppe/go-internal v1.8.1/go.mod h1:JeRgkft04UBgHMgCIwADu4Pn6Mtm5d4nPKWu0nJ5d+o= -github.com/rogpeppe/go-internal v1.9.0 h1:73kH8U+JUqXU8lRuOHeVHaa/SZPifC7BkcraZVejAe8= github.com/rogpeppe/go-internal v1.9.0/go.mod h1:WtVeX8xhTBvf0smdhujwtBcq4Qrzq/fJaraNFVN+nFs= +github.com/rogpeppe/go-internal v1.10.0 h1:TMyTOH3F/DB16zRVcYyreMH6GnZZrwQVAoYjRBZyWFQ= +github.com/rogpeppe/go-internal v1.10.0/go.mod h1:UQnix2H7Ngw/k4C5ijL5+65zddjncjaFoBhdsK/akog= github.com/rs/cors v1.7.0/go.mod h1:gFx+x8UowdsKA9AchylcLynDq+nNFfI8FkUZdN/jGCU= github.com/rs/cors v1.8.3 h1:O+qNyWn7Z+F9M0ILBHgMVPuB1xTOucVd5gtaYyXBpRo= github.com/rs/cors v1.8.3/go.mod h1:XyqrcTp5zjWr1wsJ8PIRZssZ8b/WMcMf71DJnit4EMU= github.com/rs/xid v1.4.0/go.mod h1:trrq9SKmegXys3aeAKXMUTdJsYXVwGY3RLcfgqegfbg= -github.com/rs/zerolog v1.29.0 h1:Zes4hju04hjbvkVkOhdl2HpZa+0PmVwigmo8XoORE5w= -github.com/rs/zerolog v1.29.0/go.mod h1:NILgTygv/Uej1ra5XxGf82ZFSLk58MFGAUS2o6usyD0= +github.com/rs/zerolog v1.29.1 h1:cO+d60CHkknCbvzEWxP0S9K6KqyTjrCNUy1LdQLCGPc= +github.com/rs/zerolog v1.29.1/go.mod h1:Le6ESbR7hc+DP6Lt1THiV8CQSdkkNrd3R0XbEgp3ZBU= github.com/russross/blackfriday v1.5.2/go.mod h1:JO/DiYxRf+HjHt06OyowR9PTA263kcR/rfWxYHBV53g= github.com/russross/blackfriday/v2 v2.0.1/go.mod h1:+Rmxgy9KzJVeS9/2gXHxylqXiyQDYRxCVz55jmeOWTM= github.com/russross/blackfriday/v2 v2.1.0/go.mod h1:+Rmxgy9KzJVeS9/2gXHxylqXiyQDYRxCVz55jmeOWTM= @@ -957,8 +955,8 @@ github.com/spf13/cast v1.5.0 h1:rj3WzYc11XZaIZMPKmwP96zkFEnnAmV8s6XbB2aY32w= github.com/spf13/cast v1.5.0/go.mod h1:SpXXQ5YoyJw6s3/6cMTQuxvgRl3PCJiyaX9p6b155UU= github.com/spf13/cobra v0.0.3/go.mod h1:1l0Ry5zgKvJasoi3XT1TypsSe7PqH0Sj9dhYf7v3XqQ= github.com/spf13/cobra v0.0.5/go.mod h1:3K3wKZymM7VvHMDS9+Akkh4K60UwM26emMESw8tLCHU= -github.com/spf13/cobra v1.6.1 h1:o94oiPyS4KD1mPy2fmcYYHHfCxLqYjJOhGsCHFZtEzA= -github.com/spf13/cobra v1.6.1/go.mod h1:IOw/AERYS7UzyrGinqmz6HLUo219MORXGxhbaJUqzrY= +github.com/spf13/cobra v1.7.0 h1:hyqWnYt1ZQShIddO5kBpj3vu05/++x6tJ6dg8EC572I= +github.com/spf13/cobra v1.7.0/go.mod h1:uLxZILRyS/50WlhOIKD7W6V5bgeIt+4sICxh6uRMrb0= github.com/spf13/jwalterweatherman v1.0.0/go.mod h1:cQK4TGJAtQXfYWX+Ddv3mKDzgVb68N+wFjFa4jdeBTo= github.com/spf13/jwalterweatherman v1.1.0 h1:ue6voC5bR5F8YxI5S67j9i582FU4Qvo2bmqnqMYADFk= github.com/spf13/jwalterweatherman v1.1.0/go.mod h1:aNWZUN0dPAAO/Ljvb5BEdw96iTZ0EXowPYD95IqWIGo= @@ -1079,8 +1077,8 @@ golang.org/x/crypto v0.0.0-20210322153248-0c34fe9e7dc2/go.mod h1:T9bdIzuCu7OtxOm golang.org/x/crypto v0.0.0-20210421170649-83a5a9bb288b/go.mod h1:T9bdIzuCu7OtxOm1hfPfRQxPLYneinmdGuTeoZ9dtd4= golang.org/x/crypto v0.0.0-20210921155107-089bfa567519/go.mod h1:GvvjBRRGRdwPK5ydBHafDWAxML/pGHZbMvKqRZ5+Abc= golang.org/x/crypto v0.0.0-20211108221036-ceb1ce70b4fa/go.mod h1:GvvjBRRGRdwPK5ydBHafDWAxML/pGHZbMvKqRZ5+Abc= -golang.org/x/crypto v0.7.0 h1:AvwMYaRytfdeVt3u6mLaxYtErKYjxA2OXjJ1HHq6t3A= -golang.org/x/crypto v0.7.0/go.mod h1:pYwdfH91IfpZVANVyUOhSIPZaFoJGxTFbZhFTx+dXZU= +golang.org/x/crypto v0.8.0 h1:pd9TJtTueMTVQXzk8E2XESSMQDj/U7OUu0PqJqPXQjQ= +golang.org/x/crypto v0.8.0/go.mod h1:mRqEX+O9/h5TFCrQhkgjo2yKi0yYA+9ecGkdQoHrywE= golang.org/x/exp v0.0.0-20190121172915-509febef88a4/go.mod h1:CJ0aWSM057203Lf6IL+f9T1iT9GByDxfZKAQTCR3kQA= golang.org/x/exp v0.0.0-20190306152737-a1d7652674e8/go.mod h1:CJ0aWSM057203Lf6IL+f9T1iT9GByDxfZKAQTCR3kQA= golang.org/x/exp v0.0.0-20190510132918-efd6b22b2522/go.mod h1:ZjyILWgesfNpC6sMxTJOJm9Kp84zZh5NQWvqDGG3Qr8= @@ -1183,8 +1181,8 @@ golang.org/x/net v0.0.0-20220722155237-a158d28d115b/go.mod h1:XRhObCWvk6IyKnWLug golang.org/x/net v0.0.0-20220909164309-bea034e7d591/go.mod h1:YDH+HFinaLZZlnHAfSS6ZXJJ9M9t4Dl22yv3iI2vPwk= golang.org/x/net v0.0.0-20221014081412-f15817d10f9b/go.mod h1:YDH+HFinaLZZlnHAfSS6ZXJJ9M9t4Dl22yv3iI2vPwk= golang.org/x/net v0.1.0/go.mod h1:Cx3nUiGt4eDBEyega/BKRp+/AlGL8hYe7U9odMt2Cco= -golang.org/x/net v0.8.0 h1:Zrh2ngAOFYneWTAIAPethzeaQLuHwhuBkuV6ZiRnUaQ= -golang.org/x/net v0.8.0/go.mod h1:QVkue5JL9kW//ek3r6jTKnTFis1tRmNAW2P1shuFdJc= +golang.org/x/net v0.9.0 h1:aWJ/m6xSmxWBx+V0XRHTlrYrPG56jKsLdTFmsSsCzOM= +golang.org/x/net v0.9.0/go.mod h1:d48xBJpPfHeWQsugry2m+kC02ZBRGRgulfHnEXEuWns= golang.org/x/oauth2 v0.0.0-20180821212333-d2e6202438be/go.mod h1:N/0e6XlmueqKjAGxoOufVs8QHGRruUQn6yWY3a++T0U= golang.org/x/oauth2 v0.0.0-20190226205417-e64efc72b421/go.mod h1:gOpvHmFTYa4IltrdGE7lF6nIHvwfUNPOp7c8zoXwtLw= golang.org/x/oauth2 v0.0.0-20190604053449-0f29369cfe45/go.mod h1:gOpvHmFTYa4IltrdGE7lF6nIHvwfUNPOp7c8zoXwtLw= @@ -1320,19 +1318,19 @@ golang.org/x/sys v0.0.0-20220520151302-bc2c85ada10a/go.mod h1:oPkhp1MJrh7nUepCBc golang.org/x/sys v0.0.0-20220610221304-9f5ed59c137d/go.mod h1:oPkhp1MJrh7nUepCBck5+mAzfO9JrbApNNgaTdGDITg= golang.org/x/sys v0.0.0-20220615213510-4f61da869c0c/go.mod h1:oPkhp1MJrh7nUepCBck5+mAzfO9JrbApNNgaTdGDITg= golang.org/x/sys v0.0.0-20220624220833-87e55d714810/go.mod h1:oPkhp1MJrh7nUepCBck5+mAzfO9JrbApNNgaTdGDITg= -golang.org/x/sys v0.0.0-20220715151400-c0bba94af5f8/go.mod h1:oPkhp1MJrh7nUepCBck5+mAzfO9JrbApNNgaTdGDITg= golang.org/x/sys v0.0.0-20220722155257-8c9f86f7a55f/go.mod h1:oPkhp1MJrh7nUepCBck5+mAzfO9JrbApNNgaTdGDITg= golang.org/x/sys v0.0.0-20220728004956-3c1f35247d10/go.mod h1:oPkhp1MJrh7nUepCBck5+mAzfO9JrbApNNgaTdGDITg= golang.org/x/sys v0.0.0-20220811171246-fbc7d0a398ab/go.mod h1:oPkhp1MJrh7nUepCBck5+mAzfO9JrbApNNgaTdGDITg= golang.org/x/sys v0.0.0-20220908164124-27713097b956/go.mod h1:oPkhp1MJrh7nUepCBck5+mAzfO9JrbApNNgaTdGDITg= golang.org/x/sys v0.1.0/go.mod h1:oPkhp1MJrh7nUepCBck5+mAzfO9JrbApNNgaTdGDITg= -golang.org/x/sys v0.6.0 h1:MVltZSvRTcU2ljQOhs94SXPftV6DCNnZViHeQps87pQ= golang.org/x/sys v0.6.0/go.mod h1:oPkhp1MJrh7nUepCBck5+mAzfO9JrbApNNgaTdGDITg= +golang.org/x/sys v0.7.0 h1:3jlCCIQZPdOYu1h8BkNvLz8Kgwtae2cagcG/VamtZRU= +golang.org/x/sys v0.7.0/go.mod h1:oPkhp1MJrh7nUepCBck5+mAzfO9JrbApNNgaTdGDITg= golang.org/x/term v0.0.0-20201126162022-7de9c90e9dd1/go.mod h1:bj7SfCRtBDWHUb9snDiAeCFNEtKQo2Wmx5Cou7ajbmo= golang.org/x/term v0.0.0-20210927222741-03fcf44c2211/go.mod h1:jbD1KX2456YbFQfuXm/mYQcufACuNUgVhRMnK/tPxf8= golang.org/x/term v0.1.0/go.mod h1:jbD1KX2456YbFQfuXm/mYQcufACuNUgVhRMnK/tPxf8= -golang.org/x/term v0.6.0 h1:clScbb1cHjoCkyRbWwBEUZ5H/tIFu5TAXIqaZD0Gcjw= -golang.org/x/term v0.6.0/go.mod h1:m6U89DPEgQRMq3DNkDClhWw02AUbt2daBVO4cn4Hv9U= +golang.org/x/term v0.7.0 h1:BEvjmm5fURWqcfbSKTdpkDXYBrUS1c0m8agp14W48vQ= +golang.org/x/term v0.7.0/go.mod h1:P32HKFT3hSsZrRxla30E9HqToFYAQPCMs/zFMBUFqPY= golang.org/x/text v0.0.0-20170915032832-14c0d48ead0c/go.mod h1:NqM8EUOU14njkJ3fqMW+pc6Ldnwhi/IjpwHt7yyuwOQ= golang.org/x/text v0.3.0/go.mod h1:NqM8EUOU14njkJ3fqMW+pc6Ldnwhi/IjpwHt7yyuwOQ= golang.org/x/text v0.3.1-0.20180807135948-17ff2d5776d2/go.mod h1:NqM8EUOU14njkJ3fqMW+pc6Ldnwhi/IjpwHt7yyuwOQ= @@ -1343,8 +1341,8 @@ golang.org/x/text v0.3.5/go.mod h1:5Zoc/QRtKVWzQhOtBMvqHzDpF6irO9z98xDceosuGiQ= golang.org/x/text v0.3.6/go.mod h1:5Zoc/QRtKVWzQhOtBMvqHzDpF6irO9z98xDceosuGiQ= golang.org/x/text v0.3.7/go.mod h1:u+2+/6zg+i71rQMx5EYifcz6MCKuco9NR6JIITiCfzQ= golang.org/x/text v0.4.0/go.mod h1:mrYo+phRRbMaCq/xk9113O4dZlRixOauAjOtrjsXDZ8= -golang.org/x/text v0.8.0 h1:57P1ETyNKtuIjB4SRd15iJxuhj8Gc416Y78H3qgMh68= -golang.org/x/text v0.8.0/go.mod h1:e1OnstbJyHTd6l/uOt8jFFHp6TRDWZR/bV3emEE/zU8= +golang.org/x/text v0.9.0 h1:2sjJmO8cDvYveuX97RDLsxlyUxLl+GHoLxBiRdHllBE= +golang.org/x/text v0.9.0/go.mod h1:e1OnstbJyHTd6l/uOt8jFFHp6TRDWZR/bV3emEE/zU8= golang.org/x/time v0.0.0-20180412165947-fbb02b2291d2/go.mod h1:tRJNPiyCQ0inRvYxbN9jk5I+vvW/OXSQhTDSoE431IQ= golang.org/x/time v0.0.0-20181108054448-85acf8d2951c/go.mod h1:tRJNPiyCQ0inRvYxbN9jk5I+vvW/OXSQhTDSoE431IQ= golang.org/x/time v0.0.0-20190308202827-9d24e82272b4/go.mod h1:tRJNPiyCQ0inRvYxbN9jk5I+vvW/OXSQhTDSoE431IQ= @@ -1594,8 +1592,8 @@ google.golang.org/genproto v0.0.0-20221010155953-15ba04fc1c0e/go.mod h1:3526vdqw google.golang.org/genproto v0.0.0-20221014173430-6e2ab493f96b/go.mod h1:1vXfmgAz9N9Jx0QA82PqRVauvCz1SGSz739p0f183jM= google.golang.org/genproto v0.0.0-20221014213838-99cd37c6964a/go.mod h1:1vXfmgAz9N9Jx0QA82PqRVauvCz1SGSz739p0f183jM= google.golang.org/genproto v0.0.0-20221025140454-527a21cfbd71/go.mod h1:9qHF0xnpdSfF6knlcsnpzUu5y+rpwgbvsyGAZPBMg4s= -google.golang.org/genproto v0.0.0-20230320184635-7606e756e683 h1:khxVcsk/FhnzxMKOyD+TDGwjbEOpcPuIpmafPGFmhMA= -google.golang.org/genproto v0.0.0-20230320184635-7606e756e683/go.mod h1:NWraEVixdDnqcqQ30jipen1STv2r/n24Wb7twVTGR4s= +google.golang.org/genproto v0.0.0-20230410155749-daa745c078e1 h1:KpwkzHKEF7B9Zxg18WzOa7djJ+Ha5DzthMyZYQfEn2A= +google.golang.org/genproto v0.0.0-20230410155749-daa745c078e1/go.mod h1:nKE/iIaLqn2bQwXBg8f1g2Ylh6r5MN5CmZvuzZCgsCU= google.golang.org/grpc v1.12.0/go.mod h1:yo6s7OP7yaDglbqo1J04qKzAhqBH6lvTonzMVmEdcZw= google.golang.org/grpc v1.17.0/go.mod h1:6QZJwpn2B+Zp71q/5VxRsJ6NXXVCE5NRUHRo+f3cWCs= google.golang.org/grpc v1.19.0/go.mod h1:mqu4LbDTu4XGKhr4mRzUsmM4RtVoemTSY81AxZiDr8c= diff --git a/tools/cosmovisor/process.go b/tools/cosmovisor/process.go index bdac5c8f8e7c..dea066e041c9 100644 --- a/tools/cosmovisor/process.go +++ b/tools/cosmovisor/process.go @@ -179,7 +179,7 @@ func (l *Launcher) doPreUpgrade() error { } if err := l.executePreUpgradeCmd(); err != nil { - counter += 1 + counter++ switch err.(*exec.ExitError).ProcessState.ExitCode() { case 1: diff --git a/tools/cosmovisor/process_test.go b/tools/cosmovisor/process_test.go index 8bbd327f541a..d071c480e619 100644 --- a/tools/cosmovisor/process_test.go +++ b/tools/cosmovisor/process_test.go @@ -4,8 +4,10 @@ package cosmovisor_test import ( + "bytes" "fmt" "os" + "sync" "testing" "time" @@ -35,7 +37,7 @@ func (s *processTestSuite) TestLaunchProcess() { logger := log.NewTestLogger(s.T()).With(log.ModuleKey, "cosmosvisor") // should run the genesis binary and produce expected output - stdout, stderr := NewBuffer(), NewBuffer() + stdout, stderr := newBuffer(), newBuffer() currentBin, err := cfg.CurrentBin() require.NoError(err) require.Equal(cfg.GenesisBin(), currentBin) @@ -79,7 +81,7 @@ func (s *processTestSuite) TestLaunchProcessWithRestartDelay() { logger := log.NewTestLogger(s.T()).With(log.ModuleKey, "cosmosvisor") // should run the genesis binary and produce expected output - stdout, stderr := NewBuffer(), NewBuffer() + stdout, stderr := newBuffer(), newBuffer() currentBin, err := cfg.CurrentBin() require.NoError(err) require.Equal(cfg.GenesisBin(), currentBin) @@ -112,7 +114,7 @@ func (s *processTestSuite) TestLaunchProcessWithDownloads() { require := s.Require() home := copyTestData(s.T(), "download") cfg := &cosmovisor.Config{Home: home, Name: "autod", AllowDownloadBinaries: true, PollInterval: 100, UnsafeSkipBackup: true} - logger := log.NewLoggerWithKV(os.Stdout, log.ModuleKey, "cosmovisor") + logger := log.NewLogger(os.Stdout).With(log.ModuleKey, "cosmovisor") upgradeFilename := cfg.UpgradeInfoFilePath() // should run the genesis binary and produce expected output @@ -123,7 +125,7 @@ func (s *processTestSuite) TestLaunchProcessWithDownloads() { launcher, err := cosmovisor.NewLauncher(logger, cfg) require.NoError(err) - stdout, stderr := NewBuffer(), NewBuffer() + stdout, stderr := newBuffer(), newBuffer() args := []string{"some", "args", upgradeFilename} doUpgrade, err := launcher.Run(args, stdout, stderr) @@ -240,3 +242,31 @@ func TestUpgradeSkipHeights(t *testing.T) { require.Equal(h, tc.expectRes) } } + +// buffer is a thread safe bytes buffer +type buffer struct { + b bytes.Buffer + m sync.Mutex +} + +func newBuffer() *buffer { + return &buffer{} +} + +func (b *buffer) Write(bz []byte) (int, error) { + b.m.Lock() + defer b.m.Unlock() + return b.b.Write(bz) +} + +func (b *buffer) String() string { + b.m.Lock() + defer b.m.Unlock() + return b.b.String() +} + +func (b *buffer) Reset() { + b.m.Lock() + defer b.m.Unlock() + b.b.Reset() +} diff --git a/tools/cosmovisor/upgrade_test.go b/tools/cosmovisor/upgrade_test.go index dd6be6af4c77..028e6b0d764d 100644 --- a/tools/cosmovisor/upgrade_test.go +++ b/tools/cosmovisor/upgrade_test.go @@ -95,7 +95,7 @@ func (s *upgradeTestSuite) assertCurrentLink(cfg cosmovisor.Config, target strin func (s *upgradeTestSuite) TestUpgradeBinaryNoDownloadUrl() { home := copyTestData(s.T(), "validate") cfg := &cosmovisor.Config{Home: home, Name: "dummyd", AllowDownloadBinaries: true} - logger := log.NewLoggerWithKV(os.Stdout, log.ModuleKey, "cosmovisor").Impl().(*zerolog.Logger) + logger := log.NewLogger(os.Stdout).With(log.ModuleKey, "cosmovisor").Impl().(*zerolog.Logger) currentBin, err := cfg.CurrentBin() s.Require().NoError(err) @@ -128,7 +128,7 @@ func (s *upgradeTestSuite) TestUpgradeBinaryNoDownloadUrl() { } func (s *upgradeTestSuite) TestUpgradeBinary() { - logger := log.NewLoggerWithKV(os.Stdout, log.ModuleKey, "cosmovisor").Impl().(*zerolog.Logger) + logger := log.NewLogger(os.Stdout).With(log.ModuleKey, "cosmovisor").Impl().(*zerolog.Logger) cases := map[string]struct { url string diff --git a/tools/hubl/go.mod b/tools/hubl/go.mod index 7fa87f92731b..6ca15b3d1bf8 100644 --- a/tools/hubl/go.mod +++ b/tools/hubl/go.mod @@ -3,25 +3,26 @@ module cosmossdk.io/tools/hubl go 1.20 require ( - cosmossdk.io/api v0.3.2-0.20230313131911-55bf5d4efbe7 + cosmossdk.io/api v0.4.0 cosmossdk.io/client/v2 v2.0.0-20230320224637-dca0e7374a1d cosmossdk.io/errors v1.0.0-beta.7 github.com/cockroachdb/errors v1.9.1 github.com/hashicorp/go-multierror v1.1.1 github.com/manifoldco/promptui v0.9.0 github.com/pelletier/go-toml/v2 v2.0.7 - github.com/spf13/cobra v1.6.1 + github.com/spf13/cobra v1.7.0 google.golang.org/grpc v1.54.0 google.golang.org/protobuf v1.30.0 ) require ( - cosmossdk.io/collections v0.0.0-20230309163709-87da587416ba // indirect + cosmossdk.io/collections v0.1.0 // indirect cosmossdk.io/core v0.6.1 // indirect cosmossdk.io/depinject v1.0.0-alpha.3 // indirect - cosmossdk.io/log v0.1.0 // indirect + cosmossdk.io/log v1.0.0 // indirect cosmossdk.io/math v1.0.0 // indirect - cosmossdk.io/store v0.1.0-alpha.1 // indirect + cosmossdk.io/store v0.1.0-alpha.1.0.20230328185921-37ba88872dbc // indirect + cosmossdk.io/x/tx v0.5.1-0.20230407182919-057d2e09bd63 // indirect filippo.io/edwards25519 v1.0.0 // indirect github.com/99designs/go-keychain v0.0.0-20191008050251-8e49817e8af4 // indirect github.com/99designs/keyring v1.2.1 // indirect @@ -34,24 +35,24 @@ require ( github.com/cespare/xxhash/v2 v2.2.0 // indirect github.com/chzyer/readline v1.5.1 // indirect github.com/cockroachdb/logtags v0.0.0-20230118201751-21c54148d20b // indirect - github.com/cockroachdb/pebble v0.0.0-20230315223031-1e5ddd10389e // indirect + github.com/cockroachdb/pebble v0.0.0-20230412222916-60cfeb46143b // indirect github.com/cockroachdb/redact v1.1.3 // indirect - github.com/cometbft/cometbft v0.37.0 // indirect + github.com/cometbft/cometbft v0.37.1-0.20230411132551-3a91d155e664 // indirect github.com/confio/ics23/go v0.9.0 // indirect github.com/cosmos/btcutil v1.0.5 // indirect github.com/cosmos/cosmos-db v1.0.0-rc.1 // indirect github.com/cosmos/cosmos-proto v1.0.0-beta.3 // indirect - github.com/cosmos/cosmos-sdk v0.46.0-beta2.0.20230321173237-fe77d4bca302 // indirect + github.com/cosmos/cosmos-sdk v0.46.0-beta2.0.20230418140744-0dde947d0ab7 // indirect github.com/cosmos/go-bip39 v1.0.0 // indirect - github.com/cosmos/gogoproto v1.4.6 // indirect + github.com/cosmos/gogoproto v1.4.8 // indirect github.com/cosmos/iavl v0.21.0-beta.1 // indirect github.com/cosmos/ledger-cosmos-go v0.13.0 // indirect github.com/danieljoos/wincred v1.1.2 // indirect github.com/davecgh/go-spew v1.1.1 // indirect - github.com/decred/dcrd/dcrec/secp256k1/v4 v4.1.0 // indirect + github.com/decred/dcrd/dcrec/secp256k1/v4 v4.2.0 // indirect github.com/dvsekhvalnov/jose2go v1.5.0 // indirect github.com/fsnotify/fsnotify v1.6.0 // indirect - github.com/getsentry/sentry-go v0.19.0 // indirect + github.com/getsentry/sentry-go v0.20.0 // indirect github.com/go-kit/kit v0.12.0 // indirect github.com/go-kit/log v0.2.1 // indirect github.com/go-logfmt/logfmt v0.6.0 // indirect @@ -72,11 +73,11 @@ require ( github.com/hashicorp/hcl v1.0.0 // indirect github.com/hdevalence/ed25519consensus v0.1.0 // indirect github.com/inconshreveable/mousetrap v1.1.0 // indirect - github.com/klauspost/compress v1.16.3 // indirect + github.com/klauspost/compress v1.16.5 // indirect github.com/kr/pretty v0.3.1 // indirect github.com/kr/text v0.2.0 // indirect github.com/libp2p/go-buffer-pool v0.1.0 // indirect - github.com/linxGnu/grocksdb v1.7.15 // indirect + github.com/linxGnu/grocksdb v1.7.16 // indirect github.com/magiconair/properties v1.8.7 // indirect github.com/mattn/go-colorable v0.1.13 // indirect github.com/mattn/go-isatty v0.0.18 // indirect @@ -86,13 +87,13 @@ require ( github.com/mtibben/percent v0.2.1 // indirect github.com/petermattis/goid v0.0.0-20230317030725-371a4b8eda08 // indirect github.com/pkg/errors v0.9.1 // indirect - github.com/prometheus/client_golang v1.14.0 // indirect + github.com/prometheus/client_golang v1.15.0 // indirect github.com/prometheus/client_model v0.3.0 // indirect github.com/prometheus/common v0.42.0 // indirect github.com/prometheus/procfs v0.9.0 // indirect github.com/rcrowley/go-metrics v0.0.0-20201227073835-cf1acfcdf475 // indirect - github.com/rogpeppe/go-internal v1.9.0 // indirect - github.com/rs/zerolog v1.29.0 // indirect + github.com/rogpeppe/go-internal v1.10.0 // indirect + github.com/rs/zerolog v1.29.1 // indirect github.com/sasha-s/go-deadlock v0.3.1 // indirect github.com/spf13/afero v1.9.3 // indirect github.com/spf13/cast v1.5.0 // indirect @@ -105,13 +106,13 @@ require ( github.com/tidwall/btree v1.6.0 // indirect github.com/zondax/hid v0.9.1 // indirect github.com/zondax/ledger-go v0.14.1 // indirect - golang.org/x/crypto v0.7.0 // indirect + golang.org/x/crypto v0.8.0 // indirect golang.org/x/exp v0.0.0-20230321023759-10a507213a29 // indirect - golang.org/x/net v0.8.0 // indirect - golang.org/x/sys v0.6.0 // indirect - golang.org/x/term v0.6.0 // indirect - golang.org/x/text v0.8.0 // indirect - google.golang.org/genproto v0.0.0-20230320184635-7606e756e683 // indirect + golang.org/x/net v0.9.0 // indirect + golang.org/x/sys v0.7.0 // indirect + golang.org/x/term v0.7.0 // indirect + golang.org/x/text v0.9.0 // indirect + google.golang.org/genproto v0.0.0-20230410155749-daa745c078e1 // indirect gopkg.in/ini.v1 v1.67.0 // indirect gopkg.in/yaml.v2 v2.4.0 // indirect gopkg.in/yaml.v3 v3.0.1 // indirect diff --git a/tools/hubl/go.sum b/tools/hubl/go.sum index a3303829dee0..9e2ab66ab417 100644 --- a/tools/hubl/go.sum +++ b/tools/hubl/go.sum @@ -35,25 +35,26 @@ cloud.google.com/go/storage v1.6.0/go.mod h1:N7U0C8pVQ/+NIKOBQyamJIeKQKkZ+mxpohl cloud.google.com/go/storage v1.8.0/go.mod h1:Wv1Oy7z6Yz3DshWRJFhqM/UCfaWIRTdp0RXyy7KQOVs= cloud.google.com/go/storage v1.10.0/go.mod h1:FLPqc6j+Ki4BU591ie1oL6qBQGu2Bl/tZ9ullr3+Kg0= cloud.google.com/go/storage v1.14.0/go.mod h1:GrKmX003DSIwi9o29oFT7YDnHYwZoctc3fOKtUw0Xmo= -cosmossdk.io/api v0.3.2-0.20230313131911-55bf5d4efbe7 h1:4LrWK+uGP5IxznxtHHsHD+ZBs2+oZRH2loYOGjHLzZM= -cosmossdk.io/api v0.3.2-0.20230313131911-55bf5d4efbe7/go.mod h1:yVns7mKgcsG+hZW/3C5FdJtC6QYWdFIcRlKb9+5HV5g= +cosmossdk.io/api v0.4.0 h1:x90DmdidP6EhzktAa/6/IofSHidDnPjahdlrUvyQZQw= +cosmossdk.io/api v0.4.0/go.mod h1:TWDzBhUBhI1LhSf2XSYpfIBf6D4mbLu/fvzvDfhcaYM= cosmossdk.io/client/v2 v2.0.0-20230320224637-dca0e7374a1d h1:9mBIeO0ZhCalqS3pJiZ1fs+Nn93E7rU4+Hv7QVINbNM= cosmossdk.io/client/v2 v2.0.0-20230320224637-dca0e7374a1d/go.mod h1:qX4UABq4VI1ccJn4H4MIJx5/HvjRiaVaImovbnPXNXc= -cosmossdk.io/collections v0.0.0-20230309163709-87da587416ba h1:S4PYij/tX3Op/hwenVEN9D+M27JRcwSwVqE3UA0BnwM= -cosmossdk.io/collections v0.0.0-20230309163709-87da587416ba/go.mod h1:lpS+G8bGC2anqzWdndTzjnQnuMO/qAcgZUkGJp4i3rc= +cosmossdk.io/collections v0.1.0 h1:nzJGeiq32KnZroSrhB6rPifw4I85Cgmzw/YAmr4luv8= +cosmossdk.io/collections v0.1.0/go.mod h1:xbauc0YsbUF8qKMVeBZl0pFCunxBIhKN/WlxpZ3lBuo= cosmossdk.io/core v0.6.1 h1:OBy7TI2W+/gyn2z40vVvruK3di+cAluinA6cybFbE7s= cosmossdk.io/core v0.6.1/go.mod h1:g3MMBCBXtxbDWBURDVnJE7XML4BG5qENhs0gzkcpuFA= cosmossdk.io/depinject v1.0.0-alpha.3 h1:6evFIgj//Y3w09bqOUOzEpFj5tsxBqdc5CfkO7z+zfw= cosmossdk.io/depinject v1.0.0-alpha.3/go.mod h1:eRbcdQ7MRpIPEM5YUJh8k97nxHpYbc3sMUnEtt8HPWU= cosmossdk.io/errors v1.0.0-beta.7 h1:gypHW76pTQGVnHKo6QBkb4yFOJjC+sUGRc5Al3Odj1w= cosmossdk.io/errors v1.0.0-beta.7/go.mod h1:mz6FQMJRku4bY7aqS/Gwfcmr/ue91roMEKAmDUDpBfE= -cosmossdk.io/log v0.1.0 h1:Vnexi+KzUCjmqq/m93teAxjt5biWFfZ5PI1imx2IJw8= -cosmossdk.io/log v0.1.0/go.mod h1:p95Wq6mDY3SREMc4y7+QU9Uwy3nyvfpWGD1iSaFkVFs= +cosmossdk.io/log v1.0.0 h1:NGKZ/A5rd4PduDfoscgABklX557PWjQINbosZy/m3Jk= +cosmossdk.io/log v1.0.0/go.mod h1:CwX9BLiBruZb7lzLlRr3R231d/fVPUXk8gAdV4LQap0= cosmossdk.io/math v1.0.0 h1:ro9w7eKx23om2tZz/VM2Pf+z2WAbGX1yDQQOJ6iGeJw= cosmossdk.io/math v1.0.0/go.mod h1:Ygz4wBHrgc7g0N+8+MrnTfS9LLn9aaTGa9hKopuym5k= -cosmossdk.io/store v0.1.0-alpha.1 h1:NGomhLUXzAxvK4OF8+yP6eNUG5i4LwzOzx+S494pTCg= -cosmossdk.io/store v0.1.0-alpha.1/go.mod h1:kmCMbhrleCZ6rDZPY/EGNldNvPebFNyVPFYp+pv05/k= -cosmossdk.io/x/tx v0.3.1-0.20230321155358-6522dd1731b5 h1:AlvyRc7f7Py1mv254vrqjIIuykCnitHIz2T+nup3bU0= +cosmossdk.io/store v0.1.0-alpha.1.0.20230328185921-37ba88872dbc h1:9piuA+NYmhe+SyMPtMoboLw/djgDbrI3dD5TG020Tnk= +cosmossdk.io/store v0.1.0-alpha.1.0.20230328185921-37ba88872dbc/go.mod h1:UFF5rmjN7WYVfxo6ArdY/l1+yyWMURBWOmSJypGqFHQ= +cosmossdk.io/x/tx v0.5.1-0.20230407182919-057d2e09bd63 h1:zHqj2VwZ/MStFmR7SUe/7gErOFhL9v2rkjmWPB/st34= +cosmossdk.io/x/tx v0.5.1-0.20230407182919-057d2e09bd63/go.mod h1:Oh3Kh+IPOfMEILNxVd2e8SLqRrIjYHpdGBfDg4ghU/k= dmitri.shuralyov.com/gpu/mtl v0.0.0-20190408044501-666a987793e9/go.mod h1:H6x//7gZCb22OMCxBHrMx7a5I7Hp++hsVxbQ4BYO7hU= filippo.io/edwards25519 v1.0.0 h1:0wAIcmJUqRdI8IJ/3eGi5/HwXZWPujYXXlkrQogz0Ek= filippo.io/edwards25519 v1.0.0/go.mod h1:N1IkdkCkiLB6tki+MYJoSx2JTY9NUlxZE7eHn5EwJns= @@ -125,34 +126,34 @@ github.com/cockroachdb/errors v1.9.1/go.mod h1:2sxOtL2WIc096WSZqZ5h8fa17rdDq9HZO github.com/cockroachdb/logtags v0.0.0-20211118104740-dabe8e521a4f/go.mod h1:Vz9DsVWQQhf3vs21MhPMZpMGSht7O/2vFW2xusFUVOs= github.com/cockroachdb/logtags v0.0.0-20230118201751-21c54148d20b h1:r6VH0faHjZeQy818SGhaone5OnYfxFR/+AzdY3sf5aE= github.com/cockroachdb/logtags v0.0.0-20230118201751-21c54148d20b/go.mod h1:Vz9DsVWQQhf3vs21MhPMZpMGSht7O/2vFW2xusFUVOs= -github.com/cockroachdb/pebble v0.0.0-20230315223031-1e5ddd10389e h1:CDuLmyaZ1pD4OJHHtubKqgu/Byw5zAnm+gArJsyj96Q= -github.com/cockroachdb/pebble v0.0.0-20230315223031-1e5ddd10389e/go.mod h1:9lRMC4XN3/BLPtIp6kAKwIaHu369NOf2rMucPzipz50= +github.com/cockroachdb/pebble v0.0.0-20230412222916-60cfeb46143b h1:92ve6F1Pls/eqd+V+102lOMRJatgpqqsQvbT9Bl/fjg= +github.com/cockroachdb/pebble v0.0.0-20230412222916-60cfeb46143b/go.mod h1:9lRMC4XN3/BLPtIp6kAKwIaHu369NOf2rMucPzipz50= github.com/cockroachdb/redact v1.1.3 h1:AKZds10rFSIj7qADf0g46UixK8NNLwWTNdCIGS5wfSQ= github.com/cockroachdb/redact v1.1.3/go.mod h1:BVNblN9mBWFyMyqK1k3AAiSxhvhfK2oOZZ2lK+dpvRg= github.com/codegangsta/inject v0.0.0-20150114235600-33e0aa1cb7c0/go.mod h1:4Zcjuz89kmFXt9morQgcfYZAYZ5n8WHjt81YYWIwtTM= -github.com/cometbft/cometbft v0.37.0 h1:M005vBaSaugvYYmNZwJOopynQSjwLoDTwflnQ/I/eYk= -github.com/cometbft/cometbft v0.37.0/go.mod h1:Y2MMMN//O5K4YKd8ze4r9jmk4Y7h0ajqILXbH5JQFVs= +github.com/cometbft/cometbft v0.37.1-0.20230411132551-3a91d155e664 h1:BbCkbnaU3R603XpnbqvuDU8Kfv+hjhiFILOHhVFntsw= +github.com/cometbft/cometbft v0.37.1-0.20230411132551-3a91d155e664/go.mod h1:Y2MMMN//O5K4YKd8ze4r9jmk4Y7h0ajqILXbH5JQFVs= github.com/cometbft/cometbft-db v0.7.0 h1:uBjbrBx4QzU0zOEnU8KxoDl18dMNgDh+zZRUE0ucsbo= github.com/confio/ics23/go v0.9.0 h1:cWs+wdbS2KRPZezoaaj+qBleXgUk5WOQFMP3CQFGTr4= github.com/confio/ics23/go v0.9.0/go.mod h1:4LPZ2NYqnYIVRklaozjNR1FScgDJ2s5Xrp+e/mYVRak= github.com/coreos/etcd v3.3.10+incompatible/go.mod h1:uF7uidLiAD3TWHmW31ZFd/JWoc32PjwdhPthX9715RE= github.com/coreos/go-etcd v2.0.0+incompatible/go.mod h1:Jez6KQU2B/sWsbdaef3ED8NzMklzPG4d5KIOhIy30Tk= github.com/coreos/go-semver v0.2.0/go.mod h1:nnelYz7RCh+5ahJtPPxZlU+153eP4D4r3EedlOD2RNk= -github.com/coreos/go-systemd/v22 v22.3.3-0.20220203105225-a9a7ef127534/go.mod h1:Y58oyj3AT4RCenI/lSvhwexgC+NSVTIJ3seZv2GcEnc= +github.com/coreos/go-systemd/v22 v22.5.0/go.mod h1:Y58oyj3AT4RCenI/lSvhwexgC+NSVTIJ3seZv2GcEnc= github.com/cosmos/btcutil v1.0.5 h1:t+ZFcX77LpKtDBhjucvnOH8C2l2ioGsBNEQ3jef8xFk= github.com/cosmos/btcutil v1.0.5/go.mod h1:IyB7iuqZMJlthe2tkIFL33xPyzbFYP0XVdS8P5lUPis= github.com/cosmos/cosmos-db v1.0.0-rc.1 h1:SjnT8B6WKMW9WEIX32qMhnEEKcI7ZP0+G1Sa9HD3nmY= github.com/cosmos/cosmos-db v1.0.0-rc.1/go.mod h1:Dnmk3flSf5lkwCqvvjNpoxjpXzhxnCAFzKHlbaForso= github.com/cosmos/cosmos-proto v1.0.0-beta.3 h1:VitvZ1lPORTVxkmF2fAp3IiA61xVwArQYKXTdEcpW6o= github.com/cosmos/cosmos-proto v1.0.0-beta.3/go.mod h1:t8IASdLaAq+bbHbjq4p960BvcTqtwuAxid3b/2rOD6I= -github.com/cosmos/cosmos-sdk v0.46.0-beta2.0.20230321173237-fe77d4bca302 h1:wffm9LPPG/FBW/tSRdJp2DCgkJQRX+Zsbdmn4I0aWeQ= -github.com/cosmos/cosmos-sdk v0.46.0-beta2.0.20230321173237-fe77d4bca302/go.mod h1:HzOsWXtPxhO8+Y8P4Ru+G3UWx6dTkpGXU9yvT35VEuI= +github.com/cosmos/cosmos-sdk v0.46.0-beta2.0.20230418140744-0dde947d0ab7 h1:+Q/K5pdQdQjp21gIxlQgGy4dOZk9gUBSQmJCYIf1bWA= +github.com/cosmos/cosmos-sdk v0.46.0-beta2.0.20230418140744-0dde947d0ab7/go.mod h1:BPvKPN63ettXrpz67uM1rHEqX/UVVkAfceFCPyp217E= github.com/cosmos/go-bip39 v0.0.0-20180819234021-555e2067c45d/go.mod h1:tSxLoYXyBmiFeKpvmq4dzayMdCjCnu8uqmCysIGBT2Y= github.com/cosmos/go-bip39 v1.0.0 h1:pcomnQdrdH22njcAatO0yWojsUnCO3y2tNoV1cb6hHY= github.com/cosmos/go-bip39 v1.0.0/go.mod h1:RNJv0H/pOIVgxw6KS7QeX2a0Uo0aKUlfhZ4xuwvCdJw= github.com/cosmos/gogogateway v1.2.0 h1:Ae/OivNhp8DqBi/sh2A8a1D0y638GpL3tkmLQAiKxTE= -github.com/cosmos/gogoproto v1.4.6 h1:Ee7z15dWJaGlgM2rWrK8N2IX7PQcuccu8oG68jp5RL4= -github.com/cosmos/gogoproto v1.4.6/go.mod h1:VS/ASYmPgv6zkPKLjR9EB91lwbLHOzaGCirmKKhncfI= +github.com/cosmos/gogoproto v1.4.8 h1:BrHKc6WFZt8+jRV71vKSQE+JrfF+JAnzrKo2VP7wIZ4= +github.com/cosmos/gogoproto v1.4.8/go.mod h1:hnb0DIEWTv+wdNzNcqus5xCQXq5+CXauq1FJuurRfVY= github.com/cosmos/iavl v0.21.0-beta.1 h1:fBQeBc8HLZ14plJNcmGfaOXSSMLVEHvEQXiTXSD76m0= github.com/cosmos/iavl v0.21.0-beta.1/go.mod h1:25YJYzilTErJ2mKfNB3xyWL9IsCwEQdNzdIutg2mh3U= github.com/cosmos/ledger-cosmos-go v0.13.0 h1:ex0CvCxToSR7j5WjrghPu2Bu9sSXKikjnVvUryNnx4s= @@ -168,9 +169,9 @@ github.com/danieljoos/wincred v1.1.2/go.mod h1:GijpziifJoIBfYh+S7BbkdUTU4LfM+QnG github.com/davecgh/go-spew v1.1.0/go.mod h1:J7Y8YcW2NihsgmVo/mv3lAwl/skON4iLHjSsI+c5H38= github.com/davecgh/go-spew v1.1.1 h1:vj9j/u1bqnvCEfJOwUhtlOARqs3+rkHYY13jYWTU97c= github.com/davecgh/go-spew v1.1.1/go.mod h1:J7Y8YcW2NihsgmVo/mv3lAwl/skON4iLHjSsI+c5H38= -github.com/decred/dcrd/crypto/blake256 v1.0.0 h1:/8DMNYp9SGi5f0w7uCm6d6M4OU2rGFK09Y2A4Xv7EE0= -github.com/decred/dcrd/dcrec/secp256k1/v4 v4.1.0 h1:HbphB4TFFXpv7MNrT52FGrrgVXF1owhMVTHFZIlnvd4= -github.com/decred/dcrd/dcrec/secp256k1/v4 v4.1.0/go.mod h1:DZGJHZMqrU4JJqFAWUS2UO1+lbSKsdiOoYi9Zzey7Fc= +github.com/decred/dcrd/crypto/blake256 v1.0.1 h1:7PltbUIQB7u/FfZ39+DGa/ShuMyJ5ilcvdfma9wOH6Y= +github.com/decred/dcrd/dcrec/secp256k1/v4 v4.2.0 h1:8UrgZ3GkP4i/CLijOJx79Yu+etlyjdBU4sfcs2WYQMs= +github.com/decred/dcrd/dcrec/secp256k1/v4 v4.2.0/go.mod h1:v57UDF4pDQJcEfFUCRop3lJL149eHGSe9Jvczhzjo/0= github.com/desertbit/timer v0.0.0-20180107155436-c41aec40b27f h1:U5y3Y5UE0w7amNe7Z5G/twsBW0KEalRQXZzf8ufSh9I= github.com/dgraph-io/badger v1.6.0 h1:DshxFxZWXUcO0xX476VJC07Xsr6ZCBVRHKZ93Oh7Evo= github.com/dgraph-io/badger v1.6.0/go.mod h1:zwt7syl517jmP8s94KqSxTlM6IMsdhYy6psNgSztDR4= @@ -204,8 +205,8 @@ github.com/fsnotify/fsnotify v1.6.0 h1:n+5WquG0fcWoWp6xPWfHdbskMCQaFnG6PfBrh1Ky4 github.com/fsnotify/fsnotify v1.6.0/go.mod h1:sl3t1tCWJFWoRz9R8WJCbQihKKwmorjAbSClcnxKAGw= github.com/gavv/httpexpect v2.0.0+incompatible/go.mod h1:x+9tiU1YnrOvnB725RkpoLv1M62hOWzwo5OXotisrKc= github.com/getsentry/sentry-go v0.12.0/go.mod h1:NSap0JBYWzHND8oMbyi0+XZhUalc1TBdRL1M71JZW2c= -github.com/getsentry/sentry-go v0.19.0 h1:BcCH3CN5tXt5aML+gwmbFwVptLLQA+eT866fCO9wVOM= -github.com/getsentry/sentry-go v0.19.0/go.mod h1:y3+lGEFEFexZtpbG1GUE2WD/f9zGyKYwpEqryTOC/nE= +github.com/getsentry/sentry-go v0.20.0 h1:bwXW98iMRIWxn+4FgPW7vMrjmbym6HblXALmhjHmQaQ= +github.com/getsentry/sentry-go v0.20.0/go.mod h1:lc76E2QywIyW8WuBnwl8Lc4bkmQH4+w1gwTf25trprY= github.com/ghodss/yaml v1.0.0/go.mod h1:4dBDuWmgqj2HViK6kFavaiC9ZROes6MMH2rRYeMEF04= github.com/gin-contrib/sse v0.0.0-20190301062529-5545eab6dad3/go.mod h1:VJ0WA2NBN22VlZ2dKZQPAPnyWw5XTlK1KymzLKsr59s= github.com/gin-gonic/gin v1.4.0/go.mod h1:OW2EZn3DO8Ln9oIKOvM++LBO+5UPHJJDH72/q/3rZdM= @@ -367,7 +368,6 @@ github.com/ianlancetaylor/demangle v0.0.0-20200824232613-28f6c0f3b639/go.mod h1: github.com/imkira/go-interpol v1.1.0/go.mod h1:z0h2/2T3XF8kyEPpRgJ3kmNv+C43p+I/CoI+jC3w2iA= github.com/improbable-eng/grpc-web v0.15.0 h1:BN+7z6uNXZ1tQGcNAuaU1YjsLTApzkjt2tzCixLaUPQ= github.com/inconshreveable/mousetrap v1.0.0/go.mod h1:PxqpIevigyE2G7u3NXJIT2ANytuPF1OarO4DADm73n8= -github.com/inconshreveable/mousetrap v1.0.1/go.mod h1:vpF70FUmC8bwa3OWnCshd2FqLfsEA9PFc4w1p2J65bw= github.com/inconshreveable/mousetrap v1.1.0 h1:wN+x4NVGpMsO7ErUn/mUI3vEoE6Jt13X2s0bqwp9tc8= github.com/inconshreveable/mousetrap v1.1.0/go.mod h1:vpF70FUmC8bwa3OWnCshd2FqLfsEA9PFc4w1p2J65bw= github.com/iris-contrib/blackfriday v2.0.0+incompatible/go.mod h1:UzZ2bDEoaSGPbkg6SAB4att1aAwTmVIx/5gCVqeyUdI= @@ -392,8 +392,8 @@ github.com/kisielk/errcheck v1.5.0/go.mod h1:pFxgyoBC7bSaBwPgfKdkLd5X25qrDl4LWUI github.com/kisielk/gotool v1.0.0/go.mod h1:XhKaO+MFFWcvkIS/tQcRk01m1F5IRFswLeQ+oQHNcck= github.com/klauspost/compress v1.8.2/go.mod h1:RyIbtBH6LamlWaDj8nUwkbUhJ87Yi3uG0guNDohfE1A= github.com/klauspost/compress v1.9.7/go.mod h1:RyIbtBH6LamlWaDj8nUwkbUhJ87Yi3uG0guNDohfE1A= -github.com/klauspost/compress v1.16.3 h1:XuJt9zzcnaz6a16/OU53ZjWp/v7/42WcR5t2a0PcNQY= -github.com/klauspost/compress v1.16.3/go.mod h1:ntbaceVETuRiXiv4DpjP66DpAtAGkEQskQzEyD//IeE= +github.com/klauspost/compress v1.16.5 h1:IFV2oUNUzZaz+XyusxpLzpzS8Pt5rh0Z16For/djlyI= +github.com/klauspost/compress v1.16.5/go.mod h1:ntbaceVETuRiXiv4DpjP66DpAtAGkEQskQzEyD//IeE= github.com/klauspost/cpuid v1.2.1/go.mod h1:Pj4uuM528wm8OyEC2QMXAi2YiTZ96dNQPGgoMS4s3ek= github.com/konsorten/go-windows-terminal-sequences v1.0.1/go.mod h1:T0+1ngSBFLxvqU3pZ+m/2kptfBszLMUkC4ZK/EgS/cQ= github.com/kr/fs v0.1.0/go.mod h1:FFnZGqtBN9Gxj7eW1uZ42v5BccTP0vu6NEaFoC2HwRg= @@ -411,8 +411,8 @@ github.com/labstack/gommon v0.3.0/go.mod h1:MULnywXg0yavhxWKc+lOruYdAhDwPK9wf0OL github.com/lib/pq v1.10.7 h1:p7ZhMD+KsSRozJr34udlUrhboJwWAgCg34+/ZZNvZZw= github.com/libp2p/go-buffer-pool v0.1.0 h1:oK4mSFcQz7cTQIfqbe4MIj9gLW+mnanjyFtc6cdF0Y8= github.com/libp2p/go-buffer-pool v0.1.0/go.mod h1:N+vh8gMqimBzdKkSMVuydVDq+UV5QTWy5HSiZacSbPg= -github.com/linxGnu/grocksdb v1.7.15 h1:AEhP28lkeAybv5UYNYviYISpR6bJejEnKuYbnWAnxx0= -github.com/linxGnu/grocksdb v1.7.15/go.mod h1:pY55D0o+r8yUYLq70QmhdudxYvoDb9F+9puf4m3/W+U= +github.com/linxGnu/grocksdb v1.7.16 h1:Q2co1xrpdkr5Hx3Fp+f+f7fRGhQFQhvi/+226dtLmA8= +github.com/linxGnu/grocksdb v1.7.16/go.mod h1:JkS7pl5qWpGpuVb3bPqTz8nC12X3YtPZT+Xq7+QfQo4= github.com/magiconair/properties v1.8.0/go.mod h1:PppfXfuXeibc/6YijjN8zIbojt8czPbwD3XqdrwzmxQ= github.com/magiconair/properties v1.8.7 h1:IeQXZAiQcpL9mgcAe1Nu6cX9LLw6ExEHKjN0VQdvPDY= github.com/magiconair/properties v1.8.7/go.mod h1:Dhd985XPs7jluiymwWYZ0G4Z61jb3vdS329zhj2hYo0= @@ -497,8 +497,8 @@ github.com/pmezard/go-difflib v1.0.0/go.mod h1:iKH77koFhYxTK1pcRnkKkqfTogsbg7gZN github.com/prometheus/client_golang v0.9.1/go.mod h1:7SWBe2y4D6OKWSNQJUaRYU/AaXPKyh/dDVn+NZz0KFw= github.com/prometheus/client_golang v1.0.0/go.mod h1:db9x61etRT2tGnBNRi70OPL5FsnadC4Ky3P0J6CfImo= github.com/prometheus/client_golang v1.4.0/go.mod h1:e9GMxYsXl05ICDXkRhurwBS4Q3OK1iX/F2sw+iXX5zU= -github.com/prometheus/client_golang v1.14.0 h1:nJdhIvne2eSX/XRAFV9PcvFFRbrjbcTUj0VP62TMhnw= -github.com/prometheus/client_golang v1.14.0/go.mod h1:8vpkKitgIVNcqrRBWh1C4TIUQgYNtG/XQE4E/Zae36Y= +github.com/prometheus/client_golang v1.15.0 h1:5fCgGYogn0hFdhyhLbw7hEsWxufKtY9klyvdNfFlFhM= +github.com/prometheus/client_golang v1.15.0/go.mod h1:e9yaBhRPU2pPNsZwE+JdQl0KEt1N9XgF6zxWmaC0xOk= github.com/prometheus/client_model v0.0.0-20180712105110-5c3871d89910/go.mod h1:MbSGuTsp3dbXC40dX6PRTWyKYBIrTGTE9sqQNg2J8bo= github.com/prometheus/client_model v0.0.0-20190129233127-fd36f4220a90/go.mod h1:xMI15A0UPsDsEKsMN9yxemIoYk6Tm2C1GtYGdfGttqA= github.com/prometheus/client_model v0.0.0-20190812154241-14fe0d1b01d4/go.mod h1:xMI15A0UPsDsEKsMN9yxemIoYk6Tm2C1GtYGdfGttqA= @@ -521,12 +521,13 @@ github.com/rogpeppe/fastuuid v1.2.0/go.mod h1:jVj6XXZzXRy/MSR5jhDC/2q6DgLz+nrA6L github.com/rogpeppe/go-internal v1.3.0/go.mod h1:M8bDsm7K2OlrFYOpmOWEs/qY81heoFRclV5y23lUDJ4= github.com/rogpeppe/go-internal v1.6.1/go.mod h1:xXDCJY+GAPziupqXw64V24skbSoqbTEfhy4qGm1nDQc= github.com/rogpeppe/go-internal v1.8.1/go.mod h1:JeRgkft04UBgHMgCIwADu4Pn6Mtm5d4nPKWu0nJ5d+o= -github.com/rogpeppe/go-internal v1.9.0 h1:73kH8U+JUqXU8lRuOHeVHaa/SZPifC7BkcraZVejAe8= github.com/rogpeppe/go-internal v1.9.0/go.mod h1:WtVeX8xhTBvf0smdhujwtBcq4Qrzq/fJaraNFVN+nFs= +github.com/rogpeppe/go-internal v1.10.0 h1:TMyTOH3F/DB16zRVcYyreMH6GnZZrwQVAoYjRBZyWFQ= +github.com/rogpeppe/go-internal v1.10.0/go.mod h1:UQnix2H7Ngw/k4C5ijL5+65zddjncjaFoBhdsK/akog= github.com/rs/cors v1.8.3 h1:O+qNyWn7Z+F9M0ILBHgMVPuB1xTOucVd5gtaYyXBpRo= github.com/rs/xid v1.4.0/go.mod h1:trrq9SKmegXys3aeAKXMUTdJsYXVwGY3RLcfgqegfbg= -github.com/rs/zerolog v1.29.0 h1:Zes4hju04hjbvkVkOhdl2HpZa+0PmVwigmo8XoORE5w= -github.com/rs/zerolog v1.29.0/go.mod h1:NILgTygv/Uej1ra5XxGf82ZFSLk58MFGAUS2o6usyD0= +github.com/rs/zerolog v1.29.1 h1:cO+d60CHkknCbvzEWxP0S9K6KqyTjrCNUy1LdQLCGPc= +github.com/rs/zerolog v1.29.1/go.mod h1:Le6ESbR7hc+DP6Lt1THiV8CQSdkkNrd3R0XbEgp3ZBU= github.com/russross/blackfriday v1.5.2/go.mod h1:JO/DiYxRf+HjHt06OyowR9PTA263kcR/rfWxYHBV53g= github.com/russross/blackfriday/v2 v2.1.0/go.mod h1:+Rmxgy9KzJVeS9/2gXHxylqXiyQDYRxCVz55jmeOWTM= github.com/ryanuber/columnize v2.1.0+incompatible/go.mod h1:sm1tb6uqfes/u+d4ooFouqFdy9/2g9QGwK3SQygK0Ts= @@ -546,8 +547,8 @@ github.com/spf13/cast v1.3.0/go.mod h1:Qx5cxh0v+4UWYiBimWS+eyWzqEqokIECu5etghLkU github.com/spf13/cast v1.5.0 h1:rj3WzYc11XZaIZMPKmwP96zkFEnnAmV8s6XbB2aY32w= github.com/spf13/cast v1.5.0/go.mod h1:SpXXQ5YoyJw6s3/6cMTQuxvgRl3PCJiyaX9p6b155UU= github.com/spf13/cobra v0.0.5/go.mod h1:3K3wKZymM7VvHMDS9+Akkh4K60UwM26emMESw8tLCHU= -github.com/spf13/cobra v1.6.1 h1:o94oiPyS4KD1mPy2fmcYYHHfCxLqYjJOhGsCHFZtEzA= -github.com/spf13/cobra v1.6.1/go.mod h1:IOw/AERYS7UzyrGinqmz6HLUo219MORXGxhbaJUqzrY= +github.com/spf13/cobra v1.7.0 h1:hyqWnYt1ZQShIddO5kBpj3vu05/++x6tJ6dg8EC572I= +github.com/spf13/cobra v1.7.0/go.mod h1:uLxZILRyS/50WlhOIKD7W6V5bgeIt+4sICxh6uRMrb0= github.com/spf13/jwalterweatherman v1.0.0/go.mod h1:cQK4TGJAtQXfYWX+Ddv3mKDzgVb68N+wFjFa4jdeBTo= github.com/spf13/jwalterweatherman v1.1.0 h1:ue6voC5bR5F8YxI5S67j9i582FU4Qvo2bmqnqMYADFk= github.com/spf13/jwalterweatherman v1.1.0/go.mod h1:aNWZUN0dPAAO/Ljvb5BEdw96iTZ0EXowPYD95IqWIGo= @@ -632,8 +633,8 @@ golang.org/x/crypto v0.0.0-20210322153248-0c34fe9e7dc2/go.mod h1:T9bdIzuCu7OtxOm golang.org/x/crypto v0.0.0-20210421170649-83a5a9bb288b/go.mod h1:T9bdIzuCu7OtxOm1hfPfRQxPLYneinmdGuTeoZ9dtd4= golang.org/x/crypto v0.0.0-20210921155107-089bfa567519/go.mod h1:GvvjBRRGRdwPK5ydBHafDWAxML/pGHZbMvKqRZ5+Abc= golang.org/x/crypto v0.0.0-20211108221036-ceb1ce70b4fa/go.mod h1:GvvjBRRGRdwPK5ydBHafDWAxML/pGHZbMvKqRZ5+Abc= -golang.org/x/crypto v0.7.0 h1:AvwMYaRytfdeVt3u6mLaxYtErKYjxA2OXjJ1HHq6t3A= -golang.org/x/crypto v0.7.0/go.mod h1:pYwdfH91IfpZVANVyUOhSIPZaFoJGxTFbZhFTx+dXZU= +golang.org/x/crypto v0.8.0 h1:pd9TJtTueMTVQXzk8E2XESSMQDj/U7OUu0PqJqPXQjQ= +golang.org/x/crypto v0.8.0/go.mod h1:mRqEX+O9/h5TFCrQhkgjo2yKi0yYA+9ecGkdQoHrywE= golang.org/x/exp v0.0.0-20190121172915-509febef88a4/go.mod h1:CJ0aWSM057203Lf6IL+f9T1iT9GByDxfZKAQTCR3kQA= golang.org/x/exp v0.0.0-20190306152737-a1d7652674e8/go.mod h1:CJ0aWSM057203Lf6IL+f9T1iT9GByDxfZKAQTCR3kQA= golang.org/x/exp v0.0.0-20190510132918-efd6b22b2522/go.mod h1:ZjyILWgesfNpC6sMxTJOJm9Kp84zZh5NQWvqDGG3Qr8= @@ -714,8 +715,8 @@ golang.org/x/net v0.0.0-20210428140749-89ef3d95e781/go.mod h1:OJAsFXCWl8Ukc7SiCT golang.org/x/net v0.0.0-20211008194852-3b03d305991f/go.mod h1:9nx3DQGgdP8bBQD5qxJ1jj9UTztislL4KSBs9R2vV5Y= golang.org/x/net v0.0.0-20220225172249-27dd8689420f/go.mod h1:CfG3xpIq0wQ8r1q4Su4UZFWDARRcnwPjda9FqA0JpMk= golang.org/x/net v0.0.0-20220607020251-c690dde0001d/go.mod h1:XRhObCWvk6IyKnWLug+ECip1KBveYUHfp+8e9klMJ9c= -golang.org/x/net v0.8.0 h1:Zrh2ngAOFYneWTAIAPethzeaQLuHwhuBkuV6ZiRnUaQ= -golang.org/x/net v0.8.0/go.mod h1:QVkue5JL9kW//ek3r6jTKnTFis1tRmNAW2P1shuFdJc= +golang.org/x/net v0.9.0 h1:aWJ/m6xSmxWBx+V0XRHTlrYrPG56jKsLdTFmsSsCzOM= +golang.org/x/net v0.9.0/go.mod h1:d48xBJpPfHeWQsugry2m+kC02ZBRGRgulfHnEXEuWns= golang.org/x/oauth2 v0.0.0-20180821212333-d2e6202438be/go.mod h1:N/0e6XlmueqKjAGxoOufVs8QHGRruUQn6yWY3a++T0U= golang.org/x/oauth2 v0.0.0-20190226205417-e64efc72b421/go.mod h1:gOpvHmFTYa4IltrdGE7lF6nIHvwfUNPOp7c8zoXwtLw= golang.org/x/oauth2 v0.0.0-20190604053449-0f29369cfe45/go.mod h1:gOpvHmFTYa4IltrdGE7lF6nIHvwfUNPOp7c8zoXwtLw= @@ -800,12 +801,13 @@ golang.org/x/sys v0.0.0-20220412211240-33da011f77ad/go.mod h1:oPkhp1MJrh7nUepCBc golang.org/x/sys v0.0.0-20220520151302-bc2c85ada10a/go.mod h1:oPkhp1MJrh7nUepCBck5+mAzfO9JrbApNNgaTdGDITg= golang.org/x/sys v0.0.0-20220811171246-fbc7d0a398ab/go.mod h1:oPkhp1MJrh7nUepCBck5+mAzfO9JrbApNNgaTdGDITg= golang.org/x/sys v0.0.0-20220908164124-27713097b956/go.mod h1:oPkhp1MJrh7nUepCBck5+mAzfO9JrbApNNgaTdGDITg= -golang.org/x/sys v0.6.0 h1:MVltZSvRTcU2ljQOhs94SXPftV6DCNnZViHeQps87pQ= golang.org/x/sys v0.6.0/go.mod h1:oPkhp1MJrh7nUepCBck5+mAzfO9JrbApNNgaTdGDITg= +golang.org/x/sys v0.7.0 h1:3jlCCIQZPdOYu1h8BkNvLz8Kgwtae2cagcG/VamtZRU= +golang.org/x/sys v0.7.0/go.mod h1:oPkhp1MJrh7nUepCBck5+mAzfO9JrbApNNgaTdGDITg= golang.org/x/term v0.0.0-20201126162022-7de9c90e9dd1/go.mod h1:bj7SfCRtBDWHUb9snDiAeCFNEtKQo2Wmx5Cou7ajbmo= golang.org/x/term v0.0.0-20210927222741-03fcf44c2211/go.mod h1:jbD1KX2456YbFQfuXm/mYQcufACuNUgVhRMnK/tPxf8= -golang.org/x/term v0.6.0 h1:clScbb1cHjoCkyRbWwBEUZ5H/tIFu5TAXIqaZD0Gcjw= -golang.org/x/term v0.6.0/go.mod h1:m6U89DPEgQRMq3DNkDClhWw02AUbt2daBVO4cn4Hv9U= +golang.org/x/term v0.7.0 h1:BEvjmm5fURWqcfbSKTdpkDXYBrUS1c0m8agp14W48vQ= +golang.org/x/term v0.7.0/go.mod h1:P32HKFT3hSsZrRxla30E9HqToFYAQPCMs/zFMBUFqPY= golang.org/x/text v0.0.0-20170915032832-14c0d48ead0c/go.mod h1:NqM8EUOU14njkJ3fqMW+pc6Ldnwhi/IjpwHt7yyuwOQ= golang.org/x/text v0.3.0/go.mod h1:NqM8EUOU14njkJ3fqMW+pc6Ldnwhi/IjpwHt7yyuwOQ= golang.org/x/text v0.3.1-0.20180807135948-17ff2d5776d2/go.mod h1:NqM8EUOU14njkJ3fqMW+pc6Ldnwhi/IjpwHt7yyuwOQ= @@ -815,8 +817,8 @@ golang.org/x/text v0.3.4/go.mod h1:5Zoc/QRtKVWzQhOtBMvqHzDpF6irO9z98xDceosuGiQ= golang.org/x/text v0.3.5/go.mod h1:5Zoc/QRtKVWzQhOtBMvqHzDpF6irO9z98xDceosuGiQ= golang.org/x/text v0.3.6/go.mod h1:5Zoc/QRtKVWzQhOtBMvqHzDpF6irO9z98xDceosuGiQ= golang.org/x/text v0.3.7/go.mod h1:u+2+/6zg+i71rQMx5EYifcz6MCKuco9NR6JIITiCfzQ= -golang.org/x/text v0.8.0 h1:57P1ETyNKtuIjB4SRd15iJxuhj8Gc416Y78H3qgMh68= -golang.org/x/text v0.8.0/go.mod h1:e1OnstbJyHTd6l/uOt8jFFHp6TRDWZR/bV3emEE/zU8= +golang.org/x/text v0.9.0 h1:2sjJmO8cDvYveuX97RDLsxlyUxLl+GHoLxBiRdHllBE= +golang.org/x/text v0.9.0/go.mod h1:e1OnstbJyHTd6l/uOt8jFFHp6TRDWZR/bV3emEE/zU8= golang.org/x/time v0.0.0-20181108054448-85acf8d2951c/go.mod h1:tRJNPiyCQ0inRvYxbN9jk5I+vvW/OXSQhTDSoE431IQ= golang.org/x/time v0.0.0-20190308202827-9d24e82272b4/go.mod h1:tRJNPiyCQ0inRvYxbN9jk5I+vvW/OXSQhTDSoE431IQ= golang.org/x/time v0.0.0-20191024005414-555d28b269f0/go.mod h1:tRJNPiyCQ0inRvYxbN9jk5I+vvW/OXSQhTDSoE431IQ= @@ -946,8 +948,8 @@ google.golang.org/genproto v0.0.0-20201214200347-8c77b98c765d/go.mod h1:FWY/as6D google.golang.org/genproto v0.0.0-20210108203827-ffc7fda8c3d7/go.mod h1:FWY/as6DDZQgahTzZj3fqbO1CbirC29ZNUFHwi0/+no= google.golang.org/genproto v0.0.0-20210226172003-ab064af71705/go.mod h1:FWY/as6DDZQgahTzZj3fqbO1CbirC29ZNUFHwi0/+no= google.golang.org/genproto v0.0.0-20210624195500-8bfb893ecb84/go.mod h1:SzzZ/N+nwJDaO1kznhnlzqS8ocJICar6hYhVyhi++24= -google.golang.org/genproto v0.0.0-20230320184635-7606e756e683 h1:khxVcsk/FhnzxMKOyD+TDGwjbEOpcPuIpmafPGFmhMA= -google.golang.org/genproto v0.0.0-20230320184635-7606e756e683/go.mod h1:NWraEVixdDnqcqQ30jipen1STv2r/n24Wb7twVTGR4s= +google.golang.org/genproto v0.0.0-20230410155749-daa745c078e1 h1:KpwkzHKEF7B9Zxg18WzOa7djJ+Ha5DzthMyZYQfEn2A= +google.golang.org/genproto v0.0.0-20230410155749-daa745c078e1/go.mod h1:nKE/iIaLqn2bQwXBg8f1g2Ylh6r5MN5CmZvuzZCgsCU= google.golang.org/grpc v1.12.0/go.mod h1:yo6s7OP7yaDglbqo1J04qKzAhqBH6lvTonzMVmEdcZw= google.golang.org/grpc v1.19.0/go.mod h1:mqu4LbDTu4XGKhr4mRzUsmM4RtVoemTSY81AxZiDr8c= google.golang.org/grpc v1.20.1/go.mod h1:10oTOabMzJvdu6/UiuZezV6QK5dSlG84ov/aaiqXj38= diff --git a/tools/hubl/internal/compat.go b/tools/hubl/internal/compat.go index d3df822dac83..adfbfab216ab 100644 --- a/tools/hubl/internal/compat.go +++ b/tools/hubl/internal/compat.go @@ -176,8 +176,7 @@ func addMissingFileDescriptors(ctx context.Context, client *grpc.ClientConn, fdM panic(err) } - switch res := in.MessageResponse.(type) { - case *grpc_reflection_v1alpha.ServerReflectionResponse_FileDescriptorResponse: + if res, ok := in.MessageResponse.(*grpc_reflection_v1alpha.ServerReflectionResponse_FileDescriptorResponse); ok { processFileDescriptorsResponse(res, fdMap) } } diff --git a/tools/hubl/internal/config.go b/tools/hubl/internal/config.go index ddb44ae42ed9..75cd8483ba5e 100644 --- a/tools/hubl/internal/config.go +++ b/tools/hubl/internal/config.go @@ -54,7 +54,7 @@ func SaveConfig(configDir string, config *Config) error { } configPath := configFilename(configDir) - if err := os.WriteFile(configPath, buf.Bytes(), 0o644); err != nil { + if err := os.WriteFile(configPath, buf.Bytes(), 0o600); err != nil { return err } diff --git a/tools/hubl/internal/load.go b/tools/hubl/internal/load.go index bb389a8d4572..43270e4bc2b9 100644 --- a/tools/hubl/internal/load.go +++ b/tools/hubl/internal/load.go @@ -33,7 +33,7 @@ type ChainInfo struct { Config *ChainConfig } -func NewChainInfo(configDir string, chain string, config *ChainConfig) *ChainInfo { +func NewChainInfo(configDir, chain string, config *ChainConfig) *ChainInfo { return &ChainInfo{ ConfigDir: configDir, Chain: chain, @@ -92,7 +92,7 @@ func (c *ChainInfo) Load(reload bool) error { return err } - if err = os.WriteFile(fdsFilename, bz, 0o644); err != nil { + if err = os.WriteFile(fdsFilename, bz, 0o600); err != nil { return err } } else { @@ -133,7 +133,7 @@ func (c *ChainInfo) Load(reload bool) error { return err } - err = os.WriteFile(appOptsFilename, bz, 0o644) + err = os.WriteFile(appOptsFilename, bz, 0o600) if err != nil { return err } diff --git a/tools/hubl/internal/remote.go b/tools/hubl/internal/remote.go index 84b4f39f60f2..346ff5936453 100644 --- a/tools/hubl/internal/remote.go +++ b/tools/hubl/internal/remote.go @@ -17,9 +17,9 @@ import ( ) var ( - flagInsecure string = "insecure" - flagUpdate string = "update" - flagConfig string = "config" + flagInsecure = "insecure" + flagUpdate = "update" + flagConfig = "config" ) func RootCommand() (*cobra.Command, error) { @@ -111,12 +111,13 @@ func RemoteCommand(config *Config, configDir string) ([]*cobra.Command, error) { Use: chain, Short: fmt.Sprintf("Commands for the %s chain", chain), RunE: func(cmd *cobra.Command, args []string) error { - if reconfig { + switch { + case reconfig: return reconfigure(cmd, config, configDir, chain) - } else if update { + case update: cmd.Printf("Updating autocli data for %s\n", chain) return chainInfo.Load(true) - } else { + default: return cmd.Help() } }, @@ -135,7 +136,7 @@ func RemoteCommand(config *Config, configDir string) ([]*cobra.Command, error) { return commands, nil } -func RemoteErrorCommand(config *Config, configDir string, chain string, chainConfig *ChainConfig, err error) *cobra.Command { +func RemoteErrorCommand(config *Config, configDir, chain string, chainConfig *ChainConfig, err error) *cobra.Command { cmd := &cobra.Command{ Use: chain, Short: "Unable to load data", diff --git a/tools/rosetta/cmd/rosetta/main.go b/tools/rosetta/cmd/rosetta/main.go index 54bb88b5d161..b5454f2f5490 100644 --- a/tools/rosetta/cmd/rosetta/main.go +++ b/tools/rosetta/cmd/rosetta/main.go @@ -11,7 +11,7 @@ import ( func main() { var ( - logger = log.NewLoggerWithKV(os.Stdout, log.ModuleKey, "rosetta") + logger = log.NewLogger(os.Stdout).With(log.ModuleKey, "rosetta") interfaceRegistry = codectypes.NewInterfaceRegistry() cdc = codec.NewProtoCodec(interfaceRegistry) ) diff --git a/tools/rosetta/converter.go b/tools/rosetta/converter.go index ebc954a38b99..429add923a75 100644 --- a/tools/rosetta/converter.go +++ b/tools/rosetta/converter.go @@ -2,13 +2,11 @@ package rosetta import ( "bytes" + "context" "encoding/json" "fmt" "reflect" - sdkmath "cosmossdk.io/math" - crgerrs "cosmossdk.io/tools/rosetta/lib/errors" - crgtypes "cosmossdk.io/tools/rosetta/lib/types" rosettatypes "github.com/coinbase/rosetta-sdk-go/types" abci "github.com/cometbft/cometbft/abci/types" "github.com/cometbft/cometbft/crypto" @@ -16,6 +14,10 @@ import ( cmttypes "github.com/cometbft/cometbft/types" secp "github.com/decred/dcrd/dcrec/secp256k1/v4" + sdkmath "cosmossdk.io/math" + crgerrs "cosmossdk.io/tools/rosetta/lib/errors" + crgtypes "cosmossdk.io/tools/rosetta/lib/types" + sdkclient "github.com/cosmos/cosmos-sdk/client" "github.com/cosmos/cosmos-sdk/codec" codectypes "github.com/cosmos/cosmos-sdk/codec/types" @@ -24,7 +26,6 @@ import ( sdk "github.com/cosmos/cosmos-sdk/types" "github.com/cosmos/cosmos-sdk/types/tx/signing" authsigning "github.com/cosmos/cosmos-sdk/x/auth/signing" - auth "github.com/cosmos/cosmos-sdk/x/auth/types" banktypes "github.com/cosmos/cosmos-sdk/x/bank/types" ) @@ -114,7 +115,9 @@ func NewConverter(cdc *codec.ProtoCodec, ir codectypes.InterfaceRegistry, cfg sd txDecode: cfg.TxDecoder(), txEncode: cfg.TxEncoder(), bytesToSign: func(tx authsigning.Tx, signerData authsigning.SignerData) (b []byte, err error) { - bytesToSign, err := cfg.SignModeHandler().GetSignBytes(signing.SignMode_SIGN_MODE_LEGACY_AMINO_JSON, signerData, tx) + bytesToSign, err := authsigning.GetSignBytesAdapter( + context.Background(), cfg.TxEncoder(), cfg.SignModeHandler(), + signing.SignMode_SIGN_MODE_LEGACY_AMINO_JSON, signerData, tx) if err != nil { return nil, err } @@ -159,12 +162,15 @@ func (c converter) UnsignedTx(ops []*rosettatypes.Operation) (tx authsigning.Tx, } // verify message correctness - if err = msg.ValidateBasic(); err != nil { - return nil, crgerrs.WrapError( - crgerrs.ErrBadArgument, - fmt.Sprintf("validation of operation at index %d failed: %s", op.OperationIdentifier.Index, err), - ) + if m, ok := msg.(sdk.HasValidateBasic); ok { + if err = m.ValidateBasic(); err != nil { + return nil, crgerrs.WrapError( + crgerrs.ErrBadArgument, + fmt.Sprintf("validation of operation at index %d failed: %s", op.OperationIdentifier.Index, err), + ) + } } + signers := msg.GetSigners() // check if there are enough signers if len(signers) == 0 { @@ -338,8 +344,8 @@ func sdkEventToBalanceOperations(status string, event abci.Event) (operations [] default: return nil, false case banktypes.EventTypeCoinSpent: - spender := sdk.MustAccAddressFromBech32(string(event.Attributes[0].Value)) - coins, err := sdk.ParseCoinsNormalized(string(event.Attributes[1].Value)) + spender := sdk.MustAccAddressFromBech32(event.Attributes[0].Value) + coins, err := sdk.ParseCoinsNormalized(event.Attributes[1].Value) if err != nil { panic(err) } @@ -349,8 +355,8 @@ func sdkEventToBalanceOperations(status string, event abci.Event) (operations [] accountIdentifier = spender.String() case banktypes.EventTypeCoinReceived: - receiver := sdk.MustAccAddressFromBech32(string(event.Attributes[0].Value)) - coins, err := sdk.ParseCoinsNormalized(string(event.Attributes[1].Value)) + receiver := sdk.MustAccAddressFromBech32(event.Attributes[0].Value) + coins, err := sdk.ParseCoinsNormalized(event.Attributes[1].Value) if err != nil { panic(err) } @@ -362,7 +368,7 @@ func sdkEventToBalanceOperations(status string, event abci.Event) (operations [] // rosetta does not have the concept of burning coins, so we need to mock // the burn as a send to an address that cannot be resolved to anything case banktypes.EventTypeCoinBurn: - coins, err := sdk.ParseCoinsNormalized(string(event.Attributes[1].Value)) + coins, err := sdk.ParseCoinsNormalized(event.Attributes[1].Value) if err != nil { panic(err) } @@ -433,7 +439,7 @@ func (c converter) Amounts(ownedCoins []sdk.Coin, availableCoins sdk.Coins) []*r // AddOperationIndexes adds the indexes to operations adhering to specific rules: // operations related to messages will be always before than the balance ones -func AddOperationIndexes(msgOps []*rosettatypes.Operation, balanceOps []*rosettatypes.Operation) (finalOps []*rosettatypes.Operation) { +func AddOperationIndexes(msgOps, balanceOps []*rosettatypes.Operation) (finalOps []*rosettatypes.Operation) { lenMsgOps := len(msgOps) lenBalanceOps := len(balanceOps) finalOps = make([]*rosettatypes.Operation, 0, lenMsgOps+lenBalanceOps) @@ -755,7 +761,7 @@ func (c converter) SigningComponents(tx authsigning.Tx, metadata *ConstructionMe // SignerData converts the given any account to signer data func (c converter) SignerData(anyAccount *codectypes.Any) (*SignerData, error) { - var acc auth.AccountI + var acc sdk.AccountI err := c.ir.UnpackAny(anyAccount, &acc) if err != nil { return nil, crgerrs.WrapError(crgerrs.ErrCodec, err.Error()) diff --git a/tools/rosetta/go.mod b/tools/rosetta/go.mod index 8d84c9c2468a..5298e59c9036 100644 --- a/tools/rosetta/go.mod +++ b/tools/rosetta/go.mod @@ -3,27 +3,27 @@ module cosmossdk.io/tools/rosetta go 1.20 require ( - cosmossdk.io/log v0.1.0 + cosmossdk.io/log v1.0.0 cosmossdk.io/math v1.0.0 github.com/coinbase/rosetta-sdk-go/types v1.0.0 - github.com/cometbft/cometbft v0.37.0 - github.com/cosmos/cosmos-sdk v0.46.0-beta2.0.20230321173237-fe77d4bca302 + github.com/cometbft/cometbft v0.37.1-0.20230411132551-3a91d155e664 + github.com/cosmos/cosmos-sdk v0.46.0-beta2.0.20230418140744-0dde947d0ab7 github.com/cosmos/rosetta-sdk-go v0.10.0 - github.com/decred/dcrd/dcrec/secp256k1/v4 v4.1.0 - github.com/spf13/cobra v1.6.1 + github.com/decred/dcrd/dcrec/secp256k1/v4 v4.2.0 + github.com/spf13/cobra v1.7.0 github.com/spf13/pflag v1.0.5 github.com/stretchr/testify v1.8.2 google.golang.org/grpc v1.54.0 ) require ( - cosmossdk.io/api v0.3.2-0.20230313131911-55bf5d4efbe7 // indirect - cosmossdk.io/collections v0.0.0-20230309163709-87da587416ba // indirect + cosmossdk.io/api v0.4.0 // indirect + cosmossdk.io/collections v0.1.0 // indirect cosmossdk.io/core v0.6.1 // indirect cosmossdk.io/depinject v1.0.0-alpha.3 // indirect cosmossdk.io/errors v1.0.0-beta.7 // indirect - cosmossdk.io/store v0.1.0-alpha.1 // indirect - cosmossdk.io/x/tx v0.3.1-0.20230321155358-6522dd1731b5 // indirect + cosmossdk.io/store v0.1.0-alpha.1.0.20230328185921-37ba88872dbc // indirect + cosmossdk.io/x/tx v0.5.5 // indirect filippo.io/edwards25519 v1.0.0 // indirect github.com/99designs/go-keychain v0.0.0-20191008050251-8e49817e8af4 // indirect github.com/99designs/keyring v1.2.1 // indirect @@ -37,7 +37,7 @@ require ( github.com/cespare/xxhash/v2 v2.2.0 // indirect github.com/cockroachdb/errors v1.9.1 // indirect github.com/cockroachdb/logtags v0.0.0-20230118201751-21c54148d20b // indirect - github.com/cockroachdb/pebble v0.0.0-20230315223031-1e5ddd10389e // indirect + github.com/cockroachdb/pebble v0.0.0-20230412222916-60cfeb46143b // indirect github.com/cockroachdb/redact v1.1.3 // indirect github.com/confio/ics23/go v0.9.0 // indirect github.com/cosmos/btcutil v1.0.5 // indirect @@ -45,7 +45,7 @@ require ( github.com/cosmos/cosmos-proto v1.0.0-beta.3 // indirect github.com/cosmos/go-bip39 v1.0.0 // indirect github.com/cosmos/gogogateway v1.2.0 // indirect - github.com/cosmos/gogoproto v1.4.6 // indirect + github.com/cosmos/gogoproto v1.4.8 // indirect github.com/cosmos/iavl v0.21.0-beta.1 // indirect github.com/cosmos/ledger-cosmos-go v0.13.0 // indirect github.com/danieljoos/wincred v1.1.2 // indirect @@ -55,7 +55,7 @@ require ( github.com/fatih/color v1.15.0 // indirect github.com/felixge/httpsnoop v1.0.2 // indirect github.com/fsnotify/fsnotify v1.6.0 // indirect - github.com/getsentry/sentry-go v0.19.0 // indirect + github.com/getsentry/sentry-go v0.20.0 // indirect github.com/go-kit/kit v0.12.0 // indirect github.com/go-kit/log v0.2.1 // indirect github.com/go-logfmt/logfmt v0.6.0 // indirect @@ -82,13 +82,14 @@ require ( github.com/hashicorp/yamux v0.1.1 // indirect github.com/hdevalence/ed25519consensus v0.1.0 // indirect github.com/huandu/skiplist v1.2.0 // indirect + github.com/iancoleman/strcase v0.2.0 // indirect github.com/improbable-eng/grpc-web v0.15.0 // indirect github.com/inconshreveable/mousetrap v1.1.0 // indirect - github.com/klauspost/compress v1.16.3 // indirect + github.com/klauspost/compress v1.16.5 // indirect github.com/kr/pretty v0.3.1 // indirect github.com/kr/text v0.2.0 // indirect github.com/libp2p/go-buffer-pool v0.1.0 // indirect - github.com/linxGnu/grocksdb v1.7.15 // indirect + github.com/linxGnu/grocksdb v1.7.16 // indirect github.com/magiconair/properties v1.8.7 // indirect github.com/mattn/go-colorable v0.1.13 // indirect github.com/mattn/go-isatty v0.0.18 // indirect @@ -102,14 +103,14 @@ require ( github.com/petermattis/goid v0.0.0-20230317030725-371a4b8eda08 // indirect github.com/pkg/errors v0.9.1 // indirect github.com/pmezard/go-difflib v1.0.0 // indirect - github.com/prometheus/client_golang v1.14.0 // indirect + github.com/prometheus/client_golang v1.15.0 // indirect github.com/prometheus/client_model v0.3.0 // indirect github.com/prometheus/common v0.42.0 // indirect github.com/prometheus/procfs v0.9.0 // indirect github.com/rcrowley/go-metrics v0.0.0-20201227073835-cf1acfcdf475 // indirect - github.com/rogpeppe/go-internal v1.9.0 // indirect + github.com/rogpeppe/go-internal v1.10.0 // indirect github.com/rs/cors v1.8.3 // indirect - github.com/rs/zerolog v1.29.0 // indirect + github.com/rs/zerolog v1.29.1 // indirect github.com/sasha-s/go-deadlock v0.3.1 // indirect github.com/spf13/afero v1.9.3 // indirect github.com/spf13/cast v1.5.0 // indirect @@ -121,13 +122,13 @@ require ( github.com/tidwall/btree v1.6.0 // indirect github.com/zondax/hid v0.9.1 // indirect github.com/zondax/ledger-go v0.14.1 // indirect - golang.org/x/crypto v0.7.0 // indirect + golang.org/x/crypto v0.8.0 // indirect golang.org/x/exp v0.0.0-20230321023759-10a507213a29 // indirect - golang.org/x/net v0.8.0 // indirect - golang.org/x/sys v0.6.0 // indirect - golang.org/x/term v0.6.0 // indirect - golang.org/x/text v0.8.0 // indirect - google.golang.org/genproto v0.0.0-20230320184635-7606e756e683 // indirect + golang.org/x/net v0.9.0 // indirect + golang.org/x/sys v0.7.0 // indirect + golang.org/x/term v0.7.0 // indirect + golang.org/x/text v0.9.0 // indirect + google.golang.org/genproto v0.0.0-20230410155749-daa745c078e1 // indirect google.golang.org/protobuf v1.30.0 // indirect gopkg.in/ini.v1 v1.67.0 // indirect gopkg.in/yaml.v2 v2.4.0 // indirect @@ -137,3 +138,6 @@ require ( pgregory.net/rapid v0.5.5 // indirect sigs.k8s.io/yaml v1.3.0 // indirect ) + +// temp to use local version of cosmos-sdk while in dev +replace github.com/cosmos/cosmos-sdk => ../.. diff --git a/tools/rosetta/go.sum b/tools/rosetta/go.sum index cb891a2e2a63..742944d15ace 100644 --- a/tools/rosetta/go.sum +++ b/tools/rosetta/go.sum @@ -35,24 +35,24 @@ cloud.google.com/go/storage v1.6.0/go.mod h1:N7U0C8pVQ/+NIKOBQyamJIeKQKkZ+mxpohl cloud.google.com/go/storage v1.8.0/go.mod h1:Wv1Oy7z6Yz3DshWRJFhqM/UCfaWIRTdp0RXyy7KQOVs= cloud.google.com/go/storage v1.10.0/go.mod h1:FLPqc6j+Ki4BU591ie1oL6qBQGu2Bl/tZ9ullr3+Kg0= cloud.google.com/go/storage v1.14.0/go.mod h1:GrKmX003DSIwi9o29oFT7YDnHYwZoctc3fOKtUw0Xmo= -cosmossdk.io/api v0.3.2-0.20230313131911-55bf5d4efbe7 h1:4LrWK+uGP5IxznxtHHsHD+ZBs2+oZRH2loYOGjHLzZM= -cosmossdk.io/api v0.3.2-0.20230313131911-55bf5d4efbe7/go.mod h1:yVns7mKgcsG+hZW/3C5FdJtC6QYWdFIcRlKb9+5HV5g= -cosmossdk.io/collections v0.0.0-20230309163709-87da587416ba h1:S4PYij/tX3Op/hwenVEN9D+M27JRcwSwVqE3UA0BnwM= -cosmossdk.io/collections v0.0.0-20230309163709-87da587416ba/go.mod h1:lpS+G8bGC2anqzWdndTzjnQnuMO/qAcgZUkGJp4i3rc= +cosmossdk.io/api v0.4.0 h1:x90DmdidP6EhzktAa/6/IofSHidDnPjahdlrUvyQZQw= +cosmossdk.io/api v0.4.0/go.mod h1:TWDzBhUBhI1LhSf2XSYpfIBf6D4mbLu/fvzvDfhcaYM= +cosmossdk.io/collections v0.1.0 h1:nzJGeiq32KnZroSrhB6rPifw4I85Cgmzw/YAmr4luv8= +cosmossdk.io/collections v0.1.0/go.mod h1:xbauc0YsbUF8qKMVeBZl0pFCunxBIhKN/WlxpZ3lBuo= cosmossdk.io/core v0.6.1 h1:OBy7TI2W+/gyn2z40vVvruK3di+cAluinA6cybFbE7s= cosmossdk.io/core v0.6.1/go.mod h1:g3MMBCBXtxbDWBURDVnJE7XML4BG5qENhs0gzkcpuFA= cosmossdk.io/depinject v1.0.0-alpha.3 h1:6evFIgj//Y3w09bqOUOzEpFj5tsxBqdc5CfkO7z+zfw= cosmossdk.io/depinject v1.0.0-alpha.3/go.mod h1:eRbcdQ7MRpIPEM5YUJh8k97nxHpYbc3sMUnEtt8HPWU= cosmossdk.io/errors v1.0.0-beta.7 h1:gypHW76pTQGVnHKo6QBkb4yFOJjC+sUGRc5Al3Odj1w= cosmossdk.io/errors v1.0.0-beta.7/go.mod h1:mz6FQMJRku4bY7aqS/Gwfcmr/ue91roMEKAmDUDpBfE= -cosmossdk.io/log v0.1.0 h1:Vnexi+KzUCjmqq/m93teAxjt5biWFfZ5PI1imx2IJw8= -cosmossdk.io/log v0.1.0/go.mod h1:p95Wq6mDY3SREMc4y7+QU9Uwy3nyvfpWGD1iSaFkVFs= +cosmossdk.io/log v1.0.0 h1:NGKZ/A5rd4PduDfoscgABklX557PWjQINbosZy/m3Jk= +cosmossdk.io/log v1.0.0/go.mod h1:CwX9BLiBruZb7lzLlRr3R231d/fVPUXk8gAdV4LQap0= cosmossdk.io/math v1.0.0 h1:ro9w7eKx23om2tZz/VM2Pf+z2WAbGX1yDQQOJ6iGeJw= cosmossdk.io/math v1.0.0/go.mod h1:Ygz4wBHrgc7g0N+8+MrnTfS9LLn9aaTGa9hKopuym5k= -cosmossdk.io/store v0.1.0-alpha.1 h1:NGomhLUXzAxvK4OF8+yP6eNUG5i4LwzOzx+S494pTCg= -cosmossdk.io/store v0.1.0-alpha.1/go.mod h1:kmCMbhrleCZ6rDZPY/EGNldNvPebFNyVPFYp+pv05/k= -cosmossdk.io/x/tx v0.3.1-0.20230321155358-6522dd1731b5 h1:AlvyRc7f7Py1mv254vrqjIIuykCnitHIz2T+nup3bU0= -cosmossdk.io/x/tx v0.3.1-0.20230321155358-6522dd1731b5/go.mod h1:FNkSEMbLP9NFdTfrbslNUtNS7OXf3wgZeJyXzfRPa4c= +cosmossdk.io/store v0.1.0-alpha.1.0.20230328185921-37ba88872dbc h1:9piuA+NYmhe+SyMPtMoboLw/djgDbrI3dD5TG020Tnk= +cosmossdk.io/store v0.1.0-alpha.1.0.20230328185921-37ba88872dbc/go.mod h1:UFF5rmjN7WYVfxo6ArdY/l1+yyWMURBWOmSJypGqFHQ= +cosmossdk.io/x/tx v0.5.5 h1:9XG3KOrqObt7Rw7KhT7fiqRd6EepUfmA9ERa8CHj1WM= +cosmossdk.io/x/tx v0.5.5/go.mod h1:Oh3Kh+IPOfMEILNxVd2e8SLqRrIjYHpdGBfDg4ghU/k= dmitri.shuralyov.com/gpu/mtl v0.0.0-20190408044501-666a987793e9/go.mod h1:H6x//7gZCb22OMCxBHrMx7a5I7Hp++hsVxbQ4BYO7hU= filippo.io/edwards25519 v1.0.0 h1:0wAIcmJUqRdI8IJ/3eGi5/HwXZWPujYXXlkrQogz0Ek= filippo.io/edwards25519 v1.0.0/go.mod h1:N1IkdkCkiLB6tki+MYJoSx2JTY9NUlxZE7eHn5EwJns= @@ -147,16 +147,16 @@ github.com/cockroachdb/errors v1.9.1/go.mod h1:2sxOtL2WIc096WSZqZ5h8fa17rdDq9HZO github.com/cockroachdb/logtags v0.0.0-20211118104740-dabe8e521a4f/go.mod h1:Vz9DsVWQQhf3vs21MhPMZpMGSht7O/2vFW2xusFUVOs= github.com/cockroachdb/logtags v0.0.0-20230118201751-21c54148d20b h1:r6VH0faHjZeQy818SGhaone5OnYfxFR/+AzdY3sf5aE= github.com/cockroachdb/logtags v0.0.0-20230118201751-21c54148d20b/go.mod h1:Vz9DsVWQQhf3vs21MhPMZpMGSht7O/2vFW2xusFUVOs= -github.com/cockroachdb/pebble v0.0.0-20230315223031-1e5ddd10389e h1:CDuLmyaZ1pD4OJHHtubKqgu/Byw5zAnm+gArJsyj96Q= -github.com/cockroachdb/pebble v0.0.0-20230315223031-1e5ddd10389e/go.mod h1:9lRMC4XN3/BLPtIp6kAKwIaHu369NOf2rMucPzipz50= +github.com/cockroachdb/pebble v0.0.0-20230412222916-60cfeb46143b h1:92ve6F1Pls/eqd+V+102lOMRJatgpqqsQvbT9Bl/fjg= +github.com/cockroachdb/pebble v0.0.0-20230412222916-60cfeb46143b/go.mod h1:9lRMC4XN3/BLPtIp6kAKwIaHu369NOf2rMucPzipz50= github.com/cockroachdb/redact v1.1.3 h1:AKZds10rFSIj7qADf0g46UixK8NNLwWTNdCIGS5wfSQ= github.com/cockroachdb/redact v1.1.3/go.mod h1:BVNblN9mBWFyMyqK1k3AAiSxhvhfK2oOZZ2lK+dpvRg= github.com/codahale/hdrhistogram v0.0.0-20161010025455-3a0bb77429bd/go.mod h1:sE/e/2PUdi/liOCUjSTXgM1o87ZssimdTWN964YiIeI= github.com/codegangsta/inject v0.0.0-20150114235600-33e0aa1cb7c0/go.mod h1:4Zcjuz89kmFXt9morQgcfYZAYZ5n8WHjt81YYWIwtTM= github.com/coinbase/rosetta-sdk-go/types v1.0.0 h1:jpVIwLcPoOeCR6o1tU+Xv7r5bMONNbHU7MuEHboiFuA= github.com/coinbase/rosetta-sdk-go/types v1.0.0/go.mod h1:eq7W2TMRH22GTW0N0beDnN931DW0/WOI1R2sdHNHG4c= -github.com/cometbft/cometbft v0.37.0 h1:M005vBaSaugvYYmNZwJOopynQSjwLoDTwflnQ/I/eYk= -github.com/cometbft/cometbft v0.37.0/go.mod h1:Y2MMMN//O5K4YKd8ze4r9jmk4Y7h0ajqILXbH5JQFVs= +github.com/cometbft/cometbft v0.37.1-0.20230411132551-3a91d155e664 h1:BbCkbnaU3R603XpnbqvuDU8Kfv+hjhiFILOHhVFntsw= +github.com/cometbft/cometbft v0.37.1-0.20230411132551-3a91d155e664/go.mod h1:Y2MMMN//O5K4YKd8ze4r9jmk4Y7h0ajqILXbH5JQFVs= github.com/cometbft/cometbft-db v0.7.0 h1:uBjbrBx4QzU0zOEnU8KxoDl18dMNgDh+zZRUE0ucsbo= github.com/confio/ics23/go v0.9.0 h1:cWs+wdbS2KRPZezoaaj+qBleXgUk5WOQFMP3CQFGTr4= github.com/confio/ics23/go v0.9.0/go.mod h1:4LPZ2NYqnYIVRklaozjNR1FScgDJ2s5Xrp+e/mYVRak= @@ -164,7 +164,7 @@ github.com/coreos/etcd v3.3.10+incompatible/go.mod h1:uF7uidLiAD3TWHmW31ZFd/JWoc github.com/coreos/go-etcd v2.0.0+incompatible/go.mod h1:Jez6KQU2B/sWsbdaef3ED8NzMklzPG4d5KIOhIy30Tk= github.com/coreos/go-semver v0.2.0/go.mod h1:nnelYz7RCh+5ahJtPPxZlU+153eP4D4r3EedlOD2RNk= github.com/coreos/go-systemd v0.0.0-20180511133405-39ca1b05acc7/go.mod h1:F5haX7vjVVG0kc13fIWeqUViNPyEJxv/OmvnBo0Yme4= -github.com/coreos/go-systemd/v22 v22.3.3-0.20220203105225-a9a7ef127534/go.mod h1:Y58oyj3AT4RCenI/lSvhwexgC+NSVTIJ3seZv2GcEnc= +github.com/coreos/go-systemd/v22 v22.5.0/go.mod h1:Y58oyj3AT4RCenI/lSvhwexgC+NSVTIJ3seZv2GcEnc= github.com/coreos/pkg v0.0.0-20160727233714-3ac0863d7acf/go.mod h1:E3G3o1h8I7cfcXa63jLwjI0eiQQMgzzUDFVpN/nH/eA= github.com/cosmos/btcutil v1.0.5 h1:t+ZFcX77LpKtDBhjucvnOH8C2l2ioGsBNEQ3jef8xFk= github.com/cosmos/btcutil v1.0.5/go.mod h1:IyB7iuqZMJlthe2tkIFL33xPyzbFYP0XVdS8P5lUPis= @@ -172,16 +172,14 @@ github.com/cosmos/cosmos-db v1.0.0-rc.1 h1:SjnT8B6WKMW9WEIX32qMhnEEKcI7ZP0+G1Sa9 github.com/cosmos/cosmos-db v1.0.0-rc.1/go.mod h1:Dnmk3flSf5lkwCqvvjNpoxjpXzhxnCAFzKHlbaForso= github.com/cosmos/cosmos-proto v1.0.0-beta.3 h1:VitvZ1lPORTVxkmF2fAp3IiA61xVwArQYKXTdEcpW6o= github.com/cosmos/cosmos-proto v1.0.0-beta.3/go.mod h1:t8IASdLaAq+bbHbjq4p960BvcTqtwuAxid3b/2rOD6I= -github.com/cosmos/cosmos-sdk v0.46.0-beta2.0.20230321173237-fe77d4bca302 h1:wffm9LPPG/FBW/tSRdJp2DCgkJQRX+Zsbdmn4I0aWeQ= -github.com/cosmos/cosmos-sdk v0.46.0-beta2.0.20230321173237-fe77d4bca302/go.mod h1:HzOsWXtPxhO8+Y8P4Ru+G3UWx6dTkpGXU9yvT35VEuI= github.com/cosmos/go-bip39 v0.0.0-20180819234021-555e2067c45d/go.mod h1:tSxLoYXyBmiFeKpvmq4dzayMdCjCnu8uqmCysIGBT2Y= github.com/cosmos/go-bip39 v1.0.0 h1:pcomnQdrdH22njcAatO0yWojsUnCO3y2tNoV1cb6hHY= github.com/cosmos/go-bip39 v1.0.0/go.mod h1:RNJv0H/pOIVgxw6KS7QeX2a0Uo0aKUlfhZ4xuwvCdJw= github.com/cosmos/gogogateway v1.2.0 h1:Ae/OivNhp8DqBi/sh2A8a1D0y638GpL3tkmLQAiKxTE= github.com/cosmos/gogogateway v1.2.0/go.mod h1:iQpLkGWxYcnCdz5iAdLcRBSw3h7NXeOkZ4GUkT+tbFI= github.com/cosmos/gogoproto v1.4.2/go.mod h1:cLxOsn1ljAHSV527CHOtaIP91kK6cCrZETRBrkzItWU= -github.com/cosmos/gogoproto v1.4.6 h1:Ee7z15dWJaGlgM2rWrK8N2IX7PQcuccu8oG68jp5RL4= -github.com/cosmos/gogoproto v1.4.6/go.mod h1:VS/ASYmPgv6zkPKLjR9EB91lwbLHOzaGCirmKKhncfI= +github.com/cosmos/gogoproto v1.4.8 h1:BrHKc6WFZt8+jRV71vKSQE+JrfF+JAnzrKo2VP7wIZ4= +github.com/cosmos/gogoproto v1.4.8/go.mod h1:hnb0DIEWTv+wdNzNcqus5xCQXq5+CXauq1FJuurRfVY= github.com/cosmos/iavl v0.21.0-beta.1 h1:fBQeBc8HLZ14plJNcmGfaOXSSMLVEHvEQXiTXSD76m0= github.com/cosmos/iavl v0.21.0-beta.1/go.mod h1:25YJYzilTErJ2mKfNB3xyWL9IsCwEQdNzdIutg2mh3U= github.com/cosmos/ledger-cosmos-go v0.13.0 h1:ex0CvCxToSR7j5WjrghPu2Bu9sSXKikjnVvUryNnx4s= @@ -201,9 +199,9 @@ github.com/danieljoos/wincred v1.1.2/go.mod h1:GijpziifJoIBfYh+S7BbkdUTU4LfM+QnG github.com/davecgh/go-spew v1.1.0/go.mod h1:J7Y8YcW2NihsgmVo/mv3lAwl/skON4iLHjSsI+c5H38= github.com/davecgh/go-spew v1.1.1 h1:vj9j/u1bqnvCEfJOwUhtlOARqs3+rkHYY13jYWTU97c= github.com/davecgh/go-spew v1.1.1/go.mod h1:J7Y8YcW2NihsgmVo/mv3lAwl/skON4iLHjSsI+c5H38= -github.com/decred/dcrd/crypto/blake256 v1.0.0 h1:/8DMNYp9SGi5f0w7uCm6d6M4OU2rGFK09Y2A4Xv7EE0= -github.com/decred/dcrd/dcrec/secp256k1/v4 v4.1.0 h1:HbphB4TFFXpv7MNrT52FGrrgVXF1owhMVTHFZIlnvd4= -github.com/decred/dcrd/dcrec/secp256k1/v4 v4.1.0/go.mod h1:DZGJHZMqrU4JJqFAWUS2UO1+lbSKsdiOoYi9Zzey7Fc= +github.com/decred/dcrd/crypto/blake256 v1.0.1 h1:7PltbUIQB7u/FfZ39+DGa/ShuMyJ5ilcvdfma9wOH6Y= +github.com/decred/dcrd/dcrec/secp256k1/v4 v4.2.0 h1:8UrgZ3GkP4i/CLijOJx79Yu+etlyjdBU4sfcs2WYQMs= +github.com/decred/dcrd/dcrec/secp256k1/v4 v4.2.0/go.mod h1:v57UDF4pDQJcEfFUCRop3lJL149eHGSe9Jvczhzjo/0= github.com/desertbit/timer v0.0.0-20180107155436-c41aec40b27f h1:U5y3Y5UE0w7amNe7Z5G/twsBW0KEalRQXZzf8ufSh9I= github.com/desertbit/timer v0.0.0-20180107155436-c41aec40b27f/go.mod h1:xH/i4TFMt8koVQZ6WFms69WAsDWr2XsYL3Hkl7jkoLE= github.com/dgraph-io/badger v1.6.0 h1:DshxFxZWXUcO0xX476VJC07Xsr6ZCBVRHKZ93Oh7Evo= @@ -254,8 +252,8 @@ github.com/fsnotify/fsnotify v1.6.0 h1:n+5WquG0fcWoWp6xPWfHdbskMCQaFnG6PfBrh1Ky4 github.com/fsnotify/fsnotify v1.6.0/go.mod h1:sl3t1tCWJFWoRz9R8WJCbQihKKwmorjAbSClcnxKAGw= github.com/gavv/httpexpect v2.0.0+incompatible/go.mod h1:x+9tiU1YnrOvnB725RkpoLv1M62hOWzwo5OXotisrKc= github.com/getsentry/sentry-go v0.12.0/go.mod h1:NSap0JBYWzHND8oMbyi0+XZhUalc1TBdRL1M71JZW2c= -github.com/getsentry/sentry-go v0.19.0 h1:BcCH3CN5tXt5aML+gwmbFwVptLLQA+eT866fCO9wVOM= -github.com/getsentry/sentry-go v0.19.0/go.mod h1:y3+lGEFEFexZtpbG1GUE2WD/f9zGyKYwpEqryTOC/nE= +github.com/getsentry/sentry-go v0.20.0 h1:bwXW98iMRIWxn+4FgPW7vMrjmbym6HblXALmhjHmQaQ= +github.com/getsentry/sentry-go v0.20.0/go.mod h1:lc76E2QywIyW8WuBnwl8Lc4bkmQH4+w1gwTf25trprY= github.com/ghodss/yaml v1.0.0/go.mod h1:4dBDuWmgqj2HViK6kFavaiC9ZROes6MMH2rRYeMEF04= github.com/gin-contrib/sse v0.0.0-20190301062529-5545eab6dad3/go.mod h1:VJ0WA2NBN22VlZ2dKZQPAPnyWw5XTlK1KymzLKsr59s= github.com/gin-contrib/sse v0.1.0 h1:Y/yl/+YNO8GZSjAhjMsSuLt29uWRFHdHYUb5lYOV9qE= @@ -467,13 +465,14 @@ github.com/huandu/skiplist v1.2.0 h1:gox56QD77HzSC0w+Ws3MH3iie755GBJU1OER3h5VsYw github.com/huandu/skiplist v1.2.0/go.mod h1:7v3iFjLcSAzO4fN5B8dvebvo/qsfumiLiDXMrPiHF9w= github.com/hudl/fargo v1.3.0/go.mod h1:y3CKSmjA+wD2gak7sUSXTAoopbhU08POFhmITJgmKTg= github.com/hydrogen18/memlistener v0.0.0-20200120041712-dcc25e7acd91/go.mod h1:qEIFzExnS6016fRpRfxrExeVn2gbClQA99gQhnIcdhE= +github.com/iancoleman/strcase v0.2.0 h1:05I4QRnGpI0m37iZQRuskXh+w77mr6Z41lwQzuHLwW0= +github.com/iancoleman/strcase v0.2.0/go.mod h1:iwCmte+B7n89clKwxIoIXy/HfoL7AsD47ZCWhYzw7ho= github.com/ianlancetaylor/demangle v0.0.0-20181102032728-5e5cf60278f6/go.mod h1:aSSvb/t6k1mPoxDqO4vJh6VOCGPwU4O0C2/Eqndh1Sc= github.com/ianlancetaylor/demangle v0.0.0-20200824232613-28f6c0f3b639/go.mod h1:aSSvb/t6k1mPoxDqO4vJh6VOCGPwU4O0C2/Eqndh1Sc= github.com/imkira/go-interpol v1.1.0/go.mod h1:z0h2/2T3XF8kyEPpRgJ3kmNv+C43p+I/CoI+jC3w2iA= github.com/improbable-eng/grpc-web v0.15.0 h1:BN+7z6uNXZ1tQGcNAuaU1YjsLTApzkjt2tzCixLaUPQ= github.com/improbable-eng/grpc-web v0.15.0/go.mod h1:1sy9HKV4Jt9aEs9JSnkWlRJPuPtwNr0l57L4f878wP8= github.com/inconshreveable/mousetrap v1.0.0/go.mod h1:PxqpIevigyE2G7u3NXJIT2ANytuPF1OarO4DADm73n8= -github.com/inconshreveable/mousetrap v1.0.1/go.mod h1:vpF70FUmC8bwa3OWnCshd2FqLfsEA9PFc4w1p2J65bw= github.com/inconshreveable/mousetrap v1.1.0 h1:wN+x4NVGpMsO7ErUn/mUI3vEoE6Jt13X2s0bqwp9tc8= github.com/inconshreveable/mousetrap v1.1.0/go.mod h1:vpF70FUmC8bwa3OWnCshd2FqLfsEA9PFc4w1p2J65bw= github.com/influxdata/influxdb1-client v0.0.0-20191209144304-8bf82d3c094d/go.mod h1:qj24IKcXYK6Iy9ceXlo3Tc+vtHo9lIhSX5JddghvEPo= @@ -512,8 +511,8 @@ github.com/klauspost/compress v1.8.2/go.mod h1:RyIbtBH6LamlWaDj8nUwkbUhJ87Yi3uG0 github.com/klauspost/compress v1.9.7/go.mod h1:RyIbtBH6LamlWaDj8nUwkbUhJ87Yi3uG0guNDohfE1A= github.com/klauspost/compress v1.10.3/go.mod h1:aoV0uJVorq1K+umq18yTdKaF57EivdYsUV+/s2qKfXs= github.com/klauspost/compress v1.11.7/go.mod h1:aoV0uJVorq1K+umq18yTdKaF57EivdYsUV+/s2qKfXs= -github.com/klauspost/compress v1.16.3 h1:XuJt9zzcnaz6a16/OU53ZjWp/v7/42WcR5t2a0PcNQY= -github.com/klauspost/compress v1.16.3/go.mod h1:ntbaceVETuRiXiv4DpjP66DpAtAGkEQskQzEyD//IeE= +github.com/klauspost/compress v1.16.5 h1:IFV2oUNUzZaz+XyusxpLzpzS8Pt5rh0Z16For/djlyI= +github.com/klauspost/compress v1.16.5/go.mod h1:ntbaceVETuRiXiv4DpjP66DpAtAGkEQskQzEyD//IeE= github.com/klauspost/cpuid v1.2.1/go.mod h1:Pj4uuM528wm8OyEC2QMXAi2YiTZ96dNQPGgoMS4s3ek= github.com/konsorten/go-windows-terminal-sequences v1.0.1/go.mod h1:T0+1ngSBFLxvqU3pZ+m/2kptfBszLMUkC4ZK/EgS/cQ= github.com/konsorten/go-windows-terminal-sequences v1.0.3/go.mod h1:T0+1ngSBFLxvqU3pZ+m/2kptfBszLMUkC4ZK/EgS/cQ= @@ -536,8 +535,8 @@ github.com/libp2p/go-buffer-pool v0.1.0 h1:oK4mSFcQz7cTQIfqbe4MIj9gLW+mnanjyFtc6 github.com/libp2p/go-buffer-pool v0.1.0/go.mod h1:N+vh8gMqimBzdKkSMVuydVDq+UV5QTWy5HSiZacSbPg= github.com/lightstep/lightstep-tracer-common/golang/gogo v0.0.0-20190605223551-bc2310a04743/go.mod h1:qklhhLq1aX+mtWk9cPHPzaBjWImj5ULL6C7HFJtXQMM= github.com/lightstep/lightstep-tracer-go v0.18.1/go.mod h1:jlF1pusYV4pidLvZ+XD0UBX0ZE6WURAspgAczcDHrL4= -github.com/linxGnu/grocksdb v1.7.15 h1:AEhP28lkeAybv5UYNYviYISpR6bJejEnKuYbnWAnxx0= -github.com/linxGnu/grocksdb v1.7.15/go.mod h1:pY55D0o+r8yUYLq70QmhdudxYvoDb9F+9puf4m3/W+U= +github.com/linxGnu/grocksdb v1.7.16 h1:Q2co1xrpdkr5Hx3Fp+f+f7fRGhQFQhvi/+226dtLmA8= +github.com/linxGnu/grocksdb v1.7.16/go.mod h1:JkS7pl5qWpGpuVb3bPqTz8nC12X3YtPZT+Xq7+QfQo4= github.com/lyft/protoc-gen-validate v0.0.13/go.mod h1:XbGvPuh87YZc5TdIa2/I4pLk0QoUACkjt2znoq26NVQ= github.com/magiconair/properties v1.8.0/go.mod h1:PppfXfuXeibc/6YijjN8zIbojt8czPbwD3XqdrwzmxQ= github.com/magiconair/properties v1.8.7 h1:IeQXZAiQcpL9mgcAe1Nu6cX9LLw6ExEHKjN0VQdvPDY= @@ -669,8 +668,8 @@ github.com/prometheus/client_golang v1.0.0/go.mod h1:db9x61etRT2tGnBNRi70OPL5Fsn github.com/prometheus/client_golang v1.3.0/go.mod h1:hJaj2vgQTGQmVCsAACORcieXFeDPbaTKGT+JTgUa3og= github.com/prometheus/client_golang v1.4.0/go.mod h1:e9GMxYsXl05ICDXkRhurwBS4Q3OK1iX/F2sw+iXX5zU= github.com/prometheus/client_golang v1.7.1/go.mod h1:PY5Wy2awLA44sXw4AOSfFBetzPP4j5+D6mVACh+pe2M= -github.com/prometheus/client_golang v1.14.0 h1:nJdhIvne2eSX/XRAFV9PcvFFRbrjbcTUj0VP62TMhnw= -github.com/prometheus/client_golang v1.14.0/go.mod h1:8vpkKitgIVNcqrRBWh1C4TIUQgYNtG/XQE4E/Zae36Y= +github.com/prometheus/client_golang v1.15.0 h1:5fCgGYogn0hFdhyhLbw7hEsWxufKtY9klyvdNfFlFhM= +github.com/prometheus/client_golang v1.15.0/go.mod h1:e9yaBhRPU2pPNsZwE+JdQl0KEt1N9XgF6zxWmaC0xOk= github.com/prometheus/client_model v0.0.0-20180712105110-5c3871d89910/go.mod h1:MbSGuTsp3dbXC40dX6PRTWyKYBIrTGTE9sqQNg2J8bo= github.com/prometheus/client_model v0.0.0-20190115171406-56726106282f/go.mod h1:MbSGuTsp3dbXC40dX6PRTWyKYBIrTGTE9sqQNg2J8bo= github.com/prometheus/client_model v0.0.0-20190129233127-fd36f4220a90/go.mod h1:xMI15A0UPsDsEKsMN9yxemIoYk6Tm2C1GtYGdfGttqA= @@ -704,14 +703,15 @@ github.com/rogpeppe/fastuuid v1.2.0/go.mod h1:jVj6XXZzXRy/MSR5jhDC/2q6DgLz+nrA6L github.com/rogpeppe/go-internal v1.3.0/go.mod h1:M8bDsm7K2OlrFYOpmOWEs/qY81heoFRclV5y23lUDJ4= github.com/rogpeppe/go-internal v1.6.1/go.mod h1:xXDCJY+GAPziupqXw64V24skbSoqbTEfhy4qGm1nDQc= github.com/rogpeppe/go-internal v1.8.1/go.mod h1:JeRgkft04UBgHMgCIwADu4Pn6Mtm5d4nPKWu0nJ5d+o= -github.com/rogpeppe/go-internal v1.9.0 h1:73kH8U+JUqXU8lRuOHeVHaa/SZPifC7BkcraZVejAe8= github.com/rogpeppe/go-internal v1.9.0/go.mod h1:WtVeX8xhTBvf0smdhujwtBcq4Qrzq/fJaraNFVN+nFs= +github.com/rogpeppe/go-internal v1.10.0 h1:TMyTOH3F/DB16zRVcYyreMH6GnZZrwQVAoYjRBZyWFQ= +github.com/rogpeppe/go-internal v1.10.0/go.mod h1:UQnix2H7Ngw/k4C5ijL5+65zddjncjaFoBhdsK/akog= github.com/rs/cors v1.7.0/go.mod h1:gFx+x8UowdsKA9AchylcLynDq+nNFfI8FkUZdN/jGCU= github.com/rs/cors v1.8.3 h1:O+qNyWn7Z+F9M0ILBHgMVPuB1xTOucVd5gtaYyXBpRo= github.com/rs/cors v1.8.3/go.mod h1:XyqrcTp5zjWr1wsJ8PIRZssZ8b/WMcMf71DJnit4EMU= github.com/rs/xid v1.4.0/go.mod h1:trrq9SKmegXys3aeAKXMUTdJsYXVwGY3RLcfgqegfbg= -github.com/rs/zerolog v1.29.0 h1:Zes4hju04hjbvkVkOhdl2HpZa+0PmVwigmo8XoORE5w= -github.com/rs/zerolog v1.29.0/go.mod h1:NILgTygv/Uej1ra5XxGf82ZFSLk58MFGAUS2o6usyD0= +github.com/rs/zerolog v1.29.1 h1:cO+d60CHkknCbvzEWxP0S9K6KqyTjrCNUy1LdQLCGPc= +github.com/rs/zerolog v1.29.1/go.mod h1:Le6ESbR7hc+DP6Lt1THiV8CQSdkkNrd3R0XbEgp3ZBU= github.com/russross/blackfriday v1.5.2/go.mod h1:JO/DiYxRf+HjHt06OyowR9PTA263kcR/rfWxYHBV53g= github.com/russross/blackfriday/v2 v2.0.1/go.mod h1:+Rmxgy9KzJVeS9/2gXHxylqXiyQDYRxCVz55jmeOWTM= github.com/russross/blackfriday/v2 v2.1.0/go.mod h1:+Rmxgy9KzJVeS9/2gXHxylqXiyQDYRxCVz55jmeOWTM= @@ -740,8 +740,8 @@ github.com/spf13/cast v1.5.0 h1:rj3WzYc11XZaIZMPKmwP96zkFEnnAmV8s6XbB2aY32w= github.com/spf13/cast v1.5.0/go.mod h1:SpXXQ5YoyJw6s3/6cMTQuxvgRl3PCJiyaX9p6b155UU= github.com/spf13/cobra v0.0.3/go.mod h1:1l0Ry5zgKvJasoi3XT1TypsSe7PqH0Sj9dhYf7v3XqQ= github.com/spf13/cobra v0.0.5/go.mod h1:3K3wKZymM7VvHMDS9+Akkh4K60UwM26emMESw8tLCHU= -github.com/spf13/cobra v1.6.1 h1:o94oiPyS4KD1mPy2fmcYYHHfCxLqYjJOhGsCHFZtEzA= -github.com/spf13/cobra v1.6.1/go.mod h1:IOw/AERYS7UzyrGinqmz6HLUo219MORXGxhbaJUqzrY= +github.com/spf13/cobra v1.7.0 h1:hyqWnYt1ZQShIddO5kBpj3vu05/++x6tJ6dg8EC572I= +github.com/spf13/cobra v1.7.0/go.mod h1:uLxZILRyS/50WlhOIKD7W6V5bgeIt+4sICxh6uRMrb0= github.com/spf13/jwalterweatherman v1.0.0/go.mod h1:cQK4TGJAtQXfYWX+Ddv3mKDzgVb68N+wFjFa4jdeBTo= github.com/spf13/jwalterweatherman v1.1.0 h1:ue6voC5bR5F8YxI5S67j9i582FU4Qvo2bmqnqMYADFk= github.com/spf13/jwalterweatherman v1.1.0/go.mod h1:aNWZUN0dPAAO/Ljvb5BEdw96iTZ0EXowPYD95IqWIGo= @@ -855,8 +855,8 @@ golang.org/x/crypto v0.0.0-20210322153248-0c34fe9e7dc2/go.mod h1:T9bdIzuCu7OtxOm golang.org/x/crypto v0.0.0-20210421170649-83a5a9bb288b/go.mod h1:T9bdIzuCu7OtxOm1hfPfRQxPLYneinmdGuTeoZ9dtd4= golang.org/x/crypto v0.0.0-20210921155107-089bfa567519/go.mod h1:GvvjBRRGRdwPK5ydBHafDWAxML/pGHZbMvKqRZ5+Abc= golang.org/x/crypto v0.0.0-20211108221036-ceb1ce70b4fa/go.mod h1:GvvjBRRGRdwPK5ydBHafDWAxML/pGHZbMvKqRZ5+Abc= -golang.org/x/crypto v0.7.0 h1:AvwMYaRytfdeVt3u6mLaxYtErKYjxA2OXjJ1HHq6t3A= -golang.org/x/crypto v0.7.0/go.mod h1:pYwdfH91IfpZVANVyUOhSIPZaFoJGxTFbZhFTx+dXZU= +golang.org/x/crypto v0.8.0 h1:pd9TJtTueMTVQXzk8E2XESSMQDj/U7OUu0PqJqPXQjQ= +golang.org/x/crypto v0.8.0/go.mod h1:mRqEX+O9/h5TFCrQhkgjo2yKi0yYA+9ecGkdQoHrywE= golang.org/x/exp v0.0.0-20190121172915-509febef88a4/go.mod h1:CJ0aWSM057203Lf6IL+f9T1iT9GByDxfZKAQTCR3kQA= golang.org/x/exp v0.0.0-20190306152737-a1d7652674e8/go.mod h1:CJ0aWSM057203Lf6IL+f9T1iT9GByDxfZKAQTCR3kQA= golang.org/x/exp v0.0.0-20190510132918-efd6b22b2522/go.mod h1:ZjyILWgesfNpC6sMxTJOJm9Kp84zZh5NQWvqDGG3Qr8= @@ -944,8 +944,8 @@ golang.org/x/net v0.0.0-20210805182204-aaa1db679c0d/go.mod h1:9nx3DQGgdP8bBQD5qx golang.org/x/net v0.0.0-20211008194852-3b03d305991f/go.mod h1:9nx3DQGgdP8bBQD5qxJ1jj9UTztislL4KSBs9R2vV5Y= golang.org/x/net v0.0.0-20220225172249-27dd8689420f/go.mod h1:CfG3xpIq0wQ8r1q4Su4UZFWDARRcnwPjda9FqA0JpMk= golang.org/x/net v0.0.0-20220607020251-c690dde0001d/go.mod h1:XRhObCWvk6IyKnWLug+ECip1KBveYUHfp+8e9klMJ9c= -golang.org/x/net v0.8.0 h1:Zrh2ngAOFYneWTAIAPethzeaQLuHwhuBkuV6ZiRnUaQ= -golang.org/x/net v0.8.0/go.mod h1:QVkue5JL9kW//ek3r6jTKnTFis1tRmNAW2P1shuFdJc= +golang.org/x/net v0.9.0 h1:aWJ/m6xSmxWBx+V0XRHTlrYrPG56jKsLdTFmsSsCzOM= +golang.org/x/net v0.9.0/go.mod h1:d48xBJpPfHeWQsugry2m+kC02ZBRGRgulfHnEXEuWns= golang.org/x/oauth2 v0.0.0-20180821212333-d2e6202438be/go.mod h1:N/0e6XlmueqKjAGxoOufVs8QHGRruUQn6yWY3a++T0U= golang.org/x/oauth2 v0.0.0-20190226205417-e64efc72b421/go.mod h1:gOpvHmFTYa4IltrdGE7lF6nIHvwfUNPOp7c8zoXwtLw= golang.org/x/oauth2 v0.0.0-20190604053449-0f29369cfe45/go.mod h1:gOpvHmFTYa4IltrdGE7lF6nIHvwfUNPOp7c8zoXwtLw= @@ -1043,12 +1043,13 @@ golang.org/x/sys v0.0.0-20220503163025-988cb79eb6c6/go.mod h1:oPkhp1MJrh7nUepCBc golang.org/x/sys v0.0.0-20220520151302-bc2c85ada10a/go.mod h1:oPkhp1MJrh7nUepCBck5+mAzfO9JrbApNNgaTdGDITg= golang.org/x/sys v0.0.0-20220811171246-fbc7d0a398ab/go.mod h1:oPkhp1MJrh7nUepCBck5+mAzfO9JrbApNNgaTdGDITg= golang.org/x/sys v0.0.0-20220908164124-27713097b956/go.mod h1:oPkhp1MJrh7nUepCBck5+mAzfO9JrbApNNgaTdGDITg= -golang.org/x/sys v0.6.0 h1:MVltZSvRTcU2ljQOhs94SXPftV6DCNnZViHeQps87pQ= golang.org/x/sys v0.6.0/go.mod h1:oPkhp1MJrh7nUepCBck5+mAzfO9JrbApNNgaTdGDITg= +golang.org/x/sys v0.7.0 h1:3jlCCIQZPdOYu1h8BkNvLz8Kgwtae2cagcG/VamtZRU= +golang.org/x/sys v0.7.0/go.mod h1:oPkhp1MJrh7nUepCBck5+mAzfO9JrbApNNgaTdGDITg= golang.org/x/term v0.0.0-20201126162022-7de9c90e9dd1/go.mod h1:bj7SfCRtBDWHUb9snDiAeCFNEtKQo2Wmx5Cou7ajbmo= golang.org/x/term v0.0.0-20210927222741-03fcf44c2211/go.mod h1:jbD1KX2456YbFQfuXm/mYQcufACuNUgVhRMnK/tPxf8= -golang.org/x/term v0.6.0 h1:clScbb1cHjoCkyRbWwBEUZ5H/tIFu5TAXIqaZD0Gcjw= -golang.org/x/term v0.6.0/go.mod h1:m6U89DPEgQRMq3DNkDClhWw02AUbt2daBVO4cn4Hv9U= +golang.org/x/term v0.7.0 h1:BEvjmm5fURWqcfbSKTdpkDXYBrUS1c0m8agp14W48vQ= +golang.org/x/term v0.7.0/go.mod h1:P32HKFT3hSsZrRxla30E9HqToFYAQPCMs/zFMBUFqPY= golang.org/x/text v0.0.0-20170915032832-14c0d48ead0c/go.mod h1:NqM8EUOU14njkJ3fqMW+pc6Ldnwhi/IjpwHt7yyuwOQ= golang.org/x/text v0.3.0/go.mod h1:NqM8EUOU14njkJ3fqMW+pc6Ldnwhi/IjpwHt7yyuwOQ= golang.org/x/text v0.3.1-0.20180807135948-17ff2d5776d2/go.mod h1:NqM8EUOU14njkJ3fqMW+pc6Ldnwhi/IjpwHt7yyuwOQ= @@ -1058,8 +1059,8 @@ golang.org/x/text v0.3.4/go.mod h1:5Zoc/QRtKVWzQhOtBMvqHzDpF6irO9z98xDceosuGiQ= golang.org/x/text v0.3.5/go.mod h1:5Zoc/QRtKVWzQhOtBMvqHzDpF6irO9z98xDceosuGiQ= golang.org/x/text v0.3.6/go.mod h1:5Zoc/QRtKVWzQhOtBMvqHzDpF6irO9z98xDceosuGiQ= golang.org/x/text v0.3.7/go.mod h1:u+2+/6zg+i71rQMx5EYifcz6MCKuco9NR6JIITiCfzQ= -golang.org/x/text v0.8.0 h1:57P1ETyNKtuIjB4SRd15iJxuhj8Gc416Y78H3qgMh68= -golang.org/x/text v0.8.0/go.mod h1:e1OnstbJyHTd6l/uOt8jFFHp6TRDWZR/bV3emEE/zU8= +golang.org/x/text v0.9.0 h1:2sjJmO8cDvYveuX97RDLsxlyUxLl+GHoLxBiRdHllBE= +golang.org/x/text v0.9.0/go.mod h1:e1OnstbJyHTd6l/uOt8jFFHp6TRDWZR/bV3emEE/zU8= golang.org/x/time v0.0.0-20180412165947-fbb02b2291d2/go.mod h1:tRJNPiyCQ0inRvYxbN9jk5I+vvW/OXSQhTDSoE431IQ= golang.org/x/time v0.0.0-20181108054448-85acf8d2951c/go.mod h1:tRJNPiyCQ0inRvYxbN9jk5I+vvW/OXSQhTDSoE431IQ= golang.org/x/time v0.0.0-20190308202827-9d24e82272b4/go.mod h1:tRJNPiyCQ0inRvYxbN9jk5I+vvW/OXSQhTDSoE431IQ= @@ -1203,8 +1204,8 @@ google.golang.org/genproto v0.0.0-20210126160654-44e461bb6506/go.mod h1:FWY/as6D google.golang.org/genproto v0.0.0-20210226172003-ab064af71705/go.mod h1:FWY/as6DDZQgahTzZj3fqbO1CbirC29ZNUFHwi0/+no= google.golang.org/genproto v0.0.0-20210624195500-8bfb893ecb84/go.mod h1:SzzZ/N+nwJDaO1kznhnlzqS8ocJICar6hYhVyhi++24= google.golang.org/genproto v0.0.0-20220314164441-57ef72a4c106/go.mod h1:hAL49I2IFola2sVEjAn7MEwsja0xp51I0tlGAf9hz4E= -google.golang.org/genproto v0.0.0-20230320184635-7606e756e683 h1:khxVcsk/FhnzxMKOyD+TDGwjbEOpcPuIpmafPGFmhMA= -google.golang.org/genproto v0.0.0-20230320184635-7606e756e683/go.mod h1:NWraEVixdDnqcqQ30jipen1STv2r/n24Wb7twVTGR4s= +google.golang.org/genproto v0.0.0-20230410155749-daa745c078e1 h1:KpwkzHKEF7B9Zxg18WzOa7djJ+Ha5DzthMyZYQfEn2A= +google.golang.org/genproto v0.0.0-20230410155749-daa745c078e1/go.mod h1:nKE/iIaLqn2bQwXBg8f1g2Ylh6r5MN5CmZvuzZCgsCU= google.golang.org/grpc v1.12.0/go.mod h1:yo6s7OP7yaDglbqo1J04qKzAhqBH6lvTonzMVmEdcZw= google.golang.org/grpc v1.17.0/go.mod h1:6QZJwpn2B+Zp71q/5VxRsJ6NXXVCE5NRUHRo+f3cWCs= google.golang.org/grpc v1.19.0/go.mod h1:mqu4LbDTu4XGKhr4mRzUsmM4RtVoemTSY81AxZiDr8c= diff --git a/tools/rosetta/lib/errors/errors.go b/tools/rosetta/lib/errors/errors.go index 3f03c31aeb98..4ad034fc3d9a 100644 --- a/tools/rosetta/lib/errors/errors.go +++ b/tools/rosetta/lib/errors/errors.go @@ -133,7 +133,7 @@ var ( ErrOffline = RegisterError(1, "cannot query endpoint in offline mode", false, "returned when querying an online endpoint in offline mode") // ErrNetworkNotSupported is returned when there is an attempt to query a network which is not supported ErrNetworkNotSupported = RegisterError(2, "network is not supported", false, "returned when querying a non supported network") - // ErrCodec is returned when there's an error while marshalling or unmarshalling data + // ErrCodec is returned when there's an error while marshaling or unmarshalling data ErrCodec = RegisterError(3, "encode/decode error", true, "returned when there are errors encoding or decoding information to and from the node") // ErrInvalidOperation is returned when the operation supplied to rosetta is not a valid one ErrInvalidOperation = RegisterError(4, "invalid operation", false, "returned when the operation is not valid") diff --git a/tools/rosetta/lib/errors/errors_test.go b/tools/rosetta/lib/errors/errors_test.go index 1b35d6a20bcb..9782c654db6e 100644 --- a/tools/rosetta/lib/errors/errors_test.go +++ b/tools/rosetta/lib/errors/errors_test.go @@ -20,7 +20,7 @@ func TestRegisterError(t *testing.T) { registeredErrorsCount++ assert.Equal(t, len(ListErrors()), registeredErrorsCount) // re-register an error should not change anything - error = RegisterError(69, "nice!", false, "nice!") + RegisterError(69, "nice!", false, "nice!") assert.Equal(t, len(ListErrors()), registeredErrorsCount) // test sealing diff --git a/tools/rosetta/lib/server/server.go b/tools/rosetta/lib/server/server.go index 6b79d5fe79ea..a0809fa8fe59 100644 --- a/tools/rosetta/lib/server/server.go +++ b/tools/rosetta/lib/server/server.go @@ -45,7 +45,7 @@ type Server struct { func (h Server) Start() error { h.logger.Info(fmt.Sprintf("Rosetta server listening on add %s", h.addr)) - return http.ListenAndServe(h.addr, h.h) //nolint:gosec + return http.ListenAndServe(h.addr, h.h) //nolint:gosec // users are recommended to operate a proxy in front of this server } func NewServer(settings Settings) (Server, error) { @@ -61,7 +61,7 @@ func NewServer(settings Settings) (Server, error) { return Server{}, fmt.Errorf("cannot build asserter: %w", err) } - logger := log.NewLoggerWithKV(os.Stdout, log.ModuleKey, "rosetta") + logger := log.NewLogger(os.Stdout).With(log.ModuleKey, "rosetta") var adapter crgtypes.API switch settings.Offline { diff --git a/types/address.go b/types/address.go index 9c1a521c328d..d0cb2b04d542 100644 --- a/types/address.go +++ b/types/address.go @@ -8,6 +8,7 @@ import ( "fmt" "strings" "sync" + "sync/atomic" "github.com/hashicorp/golang-lru/simplelru" "sigs.k8s.io/yaml" @@ -85,6 +86,8 @@ var ( consAddrCache *simplelru.LRU valAddrMu sync.Mutex valAddrCache *simplelru.LRU + + isCachingEnabled atomic.Bool ) // sentinel errors @@ -94,6 +97,8 @@ var ( func init() { var err error + SetAddrCacheEnabled(true) + // in total the cache size is 61k entries. Key is 32 bytes and value is around 50-70 bytes. // That will make around 92 * 61k * 2 (LRU) bytes ~ 11 MB if accAddrCache, err = simplelru.NewLRU(60000, nil); err != nil { @@ -107,6 +112,16 @@ func init() { } } +// SetAddrCacheEnabled enables or disables accAddrCache, consAddrCache, and valAddrCache. By default, caches are enabled. +func SetAddrCacheEnabled(enabled bool) { + isCachingEnabled.Store(enabled) +} + +// IsAddrCacheEnabled returns if the address caches are enabled. +func IsAddrCacheEnabled() bool { + return isCachingEnabled.Load() +} + // Address is a common interface for different types of addresses used by the SDK type Address interface { Equals(Address) bool @@ -287,11 +302,15 @@ func (aa AccAddress) String() string { } key := conv.UnsafeBytesToStr(aa) - accAddrMu.Lock() - defer accAddrMu.Unlock() - addr, ok := accAddrCache.Get(key) - if ok { - return addr.(string) + + if IsAddrCacheEnabled() { + accAddrMu.Lock() + defer accAddrMu.Unlock() + + addr, ok := accAddrCache.Get(key) + if ok { + return addr.(string) + } } return cacheBech32Addr(GetConfig().GetBech32AccountAddrPrefix(), aa, accAddrCache, key) } @@ -437,11 +456,15 @@ func (va ValAddress) String() string { } key := conv.UnsafeBytesToStr(va) - valAddrMu.Lock() - defer valAddrMu.Unlock() - addr, ok := valAddrCache.Get(key) - if ok { - return addr.(string) + + if IsAddrCacheEnabled() { + valAddrMu.Lock() + defer valAddrMu.Unlock() + + addr, ok := valAddrCache.Get(key) + if ok { + return addr.(string) + } } return cacheBech32Addr(GetConfig().GetBech32ValidatorAddrPrefix(), va, valAddrCache, key) } @@ -592,11 +615,15 @@ func (ca ConsAddress) String() string { } key := conv.UnsafeBytesToStr(ca) - consAddrMu.Lock() - defer consAddrMu.Unlock() - addr, ok := consAddrCache.Get(key) - if ok { - return addr.(string) + + if IsAddrCacheEnabled() { + consAddrMu.Lock() + defer consAddrMu.Unlock() + + addr, ok := consAddrCache.Get(key) + if ok { + return addr.(string) + } } return cacheBech32Addr(GetConfig().GetBech32ConsensusAddrPrefix(), ca, consAddrCache, key) } @@ -676,6 +703,8 @@ func cacheBech32Addr(prefix string, addr []byte, cache *simplelru.LRU, cacheKey if err != nil { panic(err) } - cache.Add(cacheKey, bech32Addr) + if IsAddrCacheEnabled() { + cache.Add(cacheKey, bech32Addr) + } return bech32Addr } diff --git a/types/address/hash.go b/types/address/hash.go index 994bf722d6c1..ee7398518fb2 100644 --- a/types/address/hash.go +++ b/types/address/hash.go @@ -88,6 +88,6 @@ func Module(moduleName string, derivationKeys ...[]byte) []byte { // Derive derives a new address from the main `address` and a derivation `key`. // This function is used to create a sub accounts. To create a module accounts use the // `Module` function. -func Derive(address []byte, key []byte) []byte { +func Derive(address, key []byte) []byte { return Hash(conv.UnsafeBytesToStr(address), key) } diff --git a/types/address_test.go b/types/address_test.go index c463af85373a..b95d4f4148b0 100644 --- a/types/address_test.go +++ b/types/address_test.go @@ -44,7 +44,7 @@ var invalidStrs = []string{ types.Bech32PrefixConsPub + "6789", } -func (s *addressTestSuite) testMarshal(original interface{}, res interface{}, marshal func() ([]byte, error), unmarshal func([]byte) error) { +func (s *addressTestSuite) testMarshal(original, res interface{}, marshal func() ([]byte, error), unmarshal func([]byte) error) { bz, err := marshal() s.Require().Nil(err) s.Require().Nil(unmarshal(bz)) @@ -126,6 +126,77 @@ func (s *addressTestSuite) TestRandBech32AccAddrConsistency() { s.Require().Equal(types.ErrEmptyHexAddress, err) } +// Test that the account address cache ignores the bech32 prefix setting, retrieving bech32 addresses from the cache. +// This will cause the AccAddress.String() to print out unexpected prefixes if the config was changed between bech32 lookups. +// See https://github.com/cosmos/cosmos-sdk/issues/15317. +func (s *addressTestSuite) TestAddrCache() { + // Use a random key + pubBz := make([]byte, ed25519.PubKeySize) + pub := &ed25519.PubKey{Key: pubBz} + rand.Read(pub.Key) + + // Set SDK bech32 prefixes to 'osmo' + prefix := "osmo" + conf := types.GetConfig() + conf.SetBech32PrefixForAccount(prefix, prefix+"pub") + conf.SetBech32PrefixForValidator(prefix+"valoper", prefix+"valoperpub") + conf.SetBech32PrefixForConsensusNode(prefix+"valcons", prefix+"valconspub") + + acc := types.AccAddress(pub.Address()) + osmoAddrBech32 := acc.String() + + // Set SDK bech32 to 'cosmos' + prefix = "cosmos" + conf.SetBech32PrefixForAccount(prefix, prefix+"pub") + conf.SetBech32PrefixForValidator(prefix+"valoper", prefix+"valoperpub") + conf.SetBech32PrefixForConsensusNode(prefix+"valcons", prefix+"valconspub") + + // We name this 'addrCosmos' to prove a point, but the bech32 address will still begin with 'osmo' due to the cache behavior. + addrCosmos := types.AccAddress(pub.Address()) + cosmosAddrBech32 := addrCosmos.String() + + // The default behavior will retrieve the bech32 address from the cache, ignoring the bech32 prefix change. + s.Require().Equal(osmoAddrBech32, cosmosAddrBech32) + s.Require().True(strings.HasPrefix(osmoAddrBech32, "osmo")) + s.Require().True(strings.HasPrefix(cosmosAddrBech32, "osmo")) +} + +// Test that the bech32 prefix is respected when the address cache is disabled. +// This causes AccAddress.String() to print out the expected prefixes if the config is changed between bech32 lookups. +// See https://github.com/cosmos/cosmos-sdk/issues/15317. +func (s *addressTestSuite) TestAddrCacheDisabled() { + types.SetAddrCacheEnabled(false) + + // Use a random key + pubBz := make([]byte, ed25519.PubKeySize) + pub := &ed25519.PubKey{Key: pubBz} + rand.Read(pub.Key) + + // Set SDK bech32 prefixes to 'osmo' + prefix := "osmo" + conf := types.GetConfig() + conf.SetBech32PrefixForAccount(prefix, prefix+"pub") + conf.SetBech32PrefixForValidator(prefix+"valoper", prefix+"valoperpub") + conf.SetBech32PrefixForConsensusNode(prefix+"valcons", prefix+"valconspub") + + acc := types.AccAddress(pub.Address()) + osmoAddrBech32 := acc.String() + + // Set SDK bech32 to 'cosmos' + prefix = "cosmos" + conf.SetBech32PrefixForAccount(prefix, prefix+"pub") + conf.SetBech32PrefixForValidator(prefix+"valoper", prefix+"valoperpub") + conf.SetBech32PrefixForConsensusNode(prefix+"valcons", prefix+"valconspub") + + addrCosmos := types.AccAddress(pub.Address()) + cosmosAddrBech32 := addrCosmos.String() + + // retrieve the bech32 address from the cache, respecting the bech32 prefix change. + s.Require().NotEqual(osmoAddrBech32, cosmosAddrBech32) + s.Require().True(strings.HasPrefix(osmoAddrBech32, "osmo")) + s.Require().True(strings.HasPrefix(cosmosAddrBech32, "cosmos")) +} + func (s *addressTestSuite) TestValAddr() { pubBz := make([]byte, ed25519.PubKeySize) pub := &ed25519.PubKey{Key: pubBz} diff --git a/types/coin.go b/types/coin.go index e1dccdf18e82..c624f4b2bd61 100644 --- a/types/coin.go +++ b/types/coin.go @@ -2,6 +2,7 @@ package types import ( "encoding/json" + "errors" "fmt" "regexp" "sort" @@ -44,6 +45,10 @@ func (coin Coin) Validate() error { return err } + if coin.Amount.IsNil() { + return errors.New("amount is nil") + } + if coin.Amount.IsNegative() { return fmt.Errorf("negative coin amount: %v", coin.Amount) } diff --git a/types/coin_benchmark_test.go b/types/coin_benchmark_test.go index 9730284c9b3d..8d8abaf14fc3 100644 --- a/types/coin_benchmark_test.go +++ b/types/coin_benchmark_test.go @@ -11,7 +11,7 @@ func coinName(suffix int) string { func BenchmarkCoinsAdditionIntersect(b *testing.B) { b.ReportAllocs() - benchmarkingFunc := func(numCoinsA int, numCoinsB int) func(b *testing.B) { + benchmarkingFunc := func(numCoinsA, numCoinsB int) func(b *testing.B) { return func(b *testing.B) { b.ReportAllocs() coinsA := Coins(make([]Coin, numCoinsA)) @@ -42,7 +42,7 @@ func BenchmarkCoinsAdditionIntersect(b *testing.B) { func BenchmarkCoinsAdditionNoIntersect(b *testing.B) { b.ReportAllocs() - benchmarkingFunc := func(numCoinsA int, numCoinsB int) func(b *testing.B) { + benchmarkingFunc := func(numCoinsA, numCoinsB int) func(b *testing.B) { return func(b *testing.B) { b.ReportAllocs() coinsA := Coins(make([]Coin, numCoinsA)) diff --git a/types/coin_test.go b/types/coin_test.go index 13a20eee6ed0..28f20fe9b17d 100644 --- a/types/coin_test.go +++ b/types/coin_test.go @@ -1276,6 +1276,38 @@ func (s *coinTestSuite) TestMarshalJSONCoins() { } } +func (s *coinTestSuite) TestCoinValidate() { + testCases := []struct { + name string + coin sdk.Coin + wantErr string + }{ + {"nil coin: nil Amount", sdk.Coin{}, "invalid denom"}, + {"non-blank coin, nil Amount", sdk.Coin{Denom: "atom"}, "amount is nil"}, + {"valid coin", sdk.Coin{Denom: "atom", Amount: math.NewInt(100)}, ""}, + {"negative coin", sdk.Coin{Denom: "atom", Amount: math.NewInt(-999)}, "negative coin amount"}, + } + + for _, tc := range testCases { + tc := tc + t := s.T() + t.Run(tc.name, func(t *testing.T) { + err := tc.coin.Validate() + switch { + case tc.wantErr == "": + if err != nil { + t.Errorf("Unexpected error: %v", err) + } + return + case err == nil: + t.Error("Expected an error") + case !strings.Contains(err.Error(), tc.wantErr): + t.Errorf("Error mismatch\n\tGot: %q\nWant: %q", err, tc.wantErr) + } + }) + } +} + func (s *coinTestSuite) TestCoinAminoEncoding() { cdc := codec.NewLegacyAmino() c := sdk.NewInt64Coin(testDenom1, 5) diff --git a/types/collections.go b/types/collections.go index 993855ac152d..f5e3f8a3668b 100644 --- a/types/collections.go +++ b/types/collections.go @@ -8,7 +8,7 @@ import ( var ( // AccAddressKey follows the same semantics of collections.BytesKey. - // It just uses humanised format for the String() and EncodeJSON(). + // It just uses humanized format for the String() and EncodeJSON(). AccAddressKey collcodec.KeyCodec[AccAddress] = genericAddressKey[AccAddress]{ stringDecoder: AccAddressFromBech32, keyType: "sdk.AccAddress", @@ -85,6 +85,40 @@ func (a genericAddressKey[T]) SizeNonTerminal(key T) int { return collections.BytesKey.SizeNonTerminal(key) } +// Deprecated: genericAddressIndexKey is a special key codec used to retain state backwards compatibility +// when a generic address key (be: AccAddress, ValAddress, ConsAddress), is used as an index key. +// More docs can be found in the AddressKeyAsIndexKey function. +type genericAddressIndexKey[T addressUnion] struct { + collcodec.KeyCodec[T] +} + +func (g genericAddressIndexKey[T]) Encode(buffer []byte, key T) (int, error) { + return g.EncodeNonTerminal(buffer, key) +} + +func (g genericAddressIndexKey[T]) Decode(buffer []byte) (int, T, error) { + return g.DecodeNonTerminal(buffer) +} + +func (g genericAddressIndexKey[T]) Size(key T) int { return g.SizeNonTerminal(key) } + +func (g genericAddressIndexKey[T]) KeyType() string { return "index_key/" + g.KeyCodec.KeyType() } + +// Deprecated: AddressKeyAsIndexKey implements an SDK backwards compatible indexing key encoder +// for addresses. +// The status quo in the SDK is that address keys are length prefixed even when they're the +// last part of a composite key. This should never be used unless to retain state compatibility. +// For example, a composite key composed of `[string, address]` in theory would need you only to +// define a way to understand when the string part finishes, we usually do this by appending a null +// byte to the string, then when you know when the string part finishes, it's logical that the +// part which remains is the address key. In the SDK instead we prepend to the address key its +// length too. +func AddressKeyAsIndexKey[T addressUnion](keyCodec collcodec.KeyCodec[T]) collcodec.KeyCodec[T] { + return genericAddressIndexKey[T]{ + keyCodec, + } +} + // Collection Codecs type intValueCodec struct{} diff --git a/types/collections_test.go b/types/collections_test.go index fd5ea9a0244b..04e612fa2be4 100644 --- a/types/collections_test.go +++ b/types/collections_test.go @@ -18,4 +18,8 @@ func TestCollectionsCorrectness(t *testing.T) { t.Run("ConsAddress", func(t *testing.T) { colltest.TestKeyCodec(t, ConsAddressKey, ConsAddress{0x32, 0x0, 0x0, 0x3}) }) + + t.Run("AddressIndexingKey", func(t *testing.T) { + colltest.TestKeyCodec(t, AddressKeyAsIndexKey(AccAddressKey), AccAddress{0x2, 0x5, 0x8}) + }) } diff --git a/types/context.go b/types/context.go index c4e047dc7272..da17b1881fca 100644 --- a/types/context.go +++ b/types/context.go @@ -35,7 +35,7 @@ type Context struct { checkTx bool recheckTx bool // if recheckTx == true, then checkTx must also be true minGasPrice DecCoins - consParams *cmtproto.ConsensusParams + consParams cmtproto.ConsensusParams eventManager EventManagerI priority int64 // The tx priority, only relevant in CheckTx kvGasConfig storetypes.GasConfig @@ -79,8 +79,8 @@ func (c Context) HeaderHash() []byte { return hash } -func (c Context) ConsensusParams() *cmtproto.ConsensusParams { - return proto.Clone(c.consParams).(*cmtproto.ConsensusParams) +func (c Context) ConsensusParams() cmtproto.ConsensusParams { + return c.consParams } func (c Context) Deadline() (deadline time.Time, ok bool) { @@ -239,7 +239,7 @@ func (c Context) WithMinGasPrices(gasPrices DecCoins) Context { } // WithConsensusParams returns a Context with an updated consensus params -func (c Context) WithConsensusParams(params *cmtproto.ConsensusParams) Context { +func (c Context) WithConsensusParams(params cmtproto.ConsensusParams) Context { c.consParams = params return c } diff --git a/types/context_test.go b/types/context_test.go index fb51ce739f00..926f28dba193 100644 --- a/types/context_test.go +++ b/types/context_test.go @@ -134,12 +134,12 @@ func (s *contextTestSuite) TestContextWithCustom() { s.Require().True(ctx.IsReCheckTx()) // test consensus param - s.Require().Nil(ctx.ConsensusParams()) - cp := &cmtproto.ConsensusParams{} + s.Require().Equal(cmtproto.ConsensusParams{}, ctx.ConsensusParams()) + cp := cmtproto.ConsensusParams{} s.Require().Equal(cp, ctx.WithConsensusParams(cp).ConsensusParams()) // test inner context - newContext := context.WithValue(ctx.Context(), "key", "value") //nolint:golint,staticcheck,revive + newContext := context.WithValue(ctx.Context(), struct{}{}, "value") s.Require().NotEqual(ctx.Context(), ctx.WithContext(newContext).Context()) } @@ -238,7 +238,7 @@ func (s *contextTestSuite) TestUnwrapSDKContext() { s.Require().Panics(func() { types.UnwrapSDKContext(ctx) }) // test unwrapping when we've used context.WithValue - ctx = context.WithValue(sdkCtx, "foo", "bar") //nolint:golint,staticcheck,revive + ctx = context.WithValue(sdkCtx, struct{}{}, "bar") sdkCtx2 = types.UnwrapSDKContext(ctx) s.Require().Equal(sdkCtx, sdkCtx2) } diff --git a/types/errors/errors.go b/types/errors/errors.go index 15732c91f87b..5e17f2df481a 100644 --- a/types/errors/errors.go +++ b/types/errors/errors.go @@ -52,7 +52,7 @@ var ( // ErrNoSignatures to doc ErrNoSignatures = errorsmod.Register(RootCodespace, 15, "no signatures supplied") - // ErrJSONMarshal defines an ABCI typed JSON marshalling error + // ErrJSONMarshal defines an ABCI typed JSON marshaling error ErrJSONMarshal = errorsmod.Register(RootCodespace, 16, "failed to marshal JSON bytes") // ErrJSONUnmarshal defines an ABCI typed JSON unmarshalling error @@ -132,7 +132,8 @@ var ( // Examples: not DB domain error, file writing etc... ErrIO = errorsmod.Register(RootCodespace, 39, "Internal IO error") - // ErrAppConfig defines an error occurred if min-gas-prices field in BaseConfig is empty. + // ErrAppConfig defines an error occurred if application configuration is + // misconfigured. ErrAppConfig = errorsmod.Register(RootCodespace, 40, "error in app.toml") // ErrInvalidGasLimit defines an error when an invalid GasWanted value is diff --git a/types/fuzz_test.go b/types/fuzz_test.go new file mode 100644 index 000000000000..167b648ac0ce --- /dev/null +++ b/types/fuzz_test.go @@ -0,0 +1,24 @@ +package types + +import ( + "testing" + + "github.com/cosmos/cosmos-sdk/codec" +) + +func FuzzCoinUnmarshalJSON(f *testing.F) { + if testing.Short() { + f.Skip() + } + + cdc := codec.NewLegacyAmino() + f.Add(`{"denom":"atom","amount":"1000"}`) + f.Add(`{"denom":"atom","amount":"-1000"}`) + f.Add(`{"denom":"uatom","amount":"1000111111111111111111111"}`) + f.Add(`{"denom":"mu","amount":"0"}`) + + f.Fuzz(func(t *testing.T, jsonBlob string) { + var c Coin + _ = cdc.UnmarshalJSON([]byte(jsonBlob), &c) + }) +} diff --git a/types/mempool/mempool_test.go b/types/mempool/mempool_test.go index 2d544192b87c..302b9a1e57b7 100644 --- a/types/mempool/mempool_test.go +++ b/types/mempool/mempool_test.go @@ -36,7 +36,7 @@ func (t testPubKey) Address() cryptotypes.Address { return t.address.Bytes() } func (t testPubKey) Bytes() []byte { panic("not implemented") } -func (t testPubKey) VerifySignature(msg []byte, sig []byte) bool { panic("not implemented") } +func (t testPubKey) VerifySignature(msg, sig []byte) bool { panic("not implemented") } func (t testPubKey) Equals(key cryptotypes.PubKey) bool { panic("not implemented") } diff --git a/types/mempool/priority_nonce_test.go b/types/mempool/priority_nonce_test.go index 12913998aa2b..6a3a62e13d86 100644 --- a/types/mempool/priority_nonce_test.go +++ b/types/mempool/priority_nonce_test.go @@ -464,7 +464,7 @@ func (s *MempoolTestSuite) TestRandomWalkTxs() { seed, s.iterations, duration.Milliseconds()) } -func genRandomTxs(seed int64, countTx int, countAccount int) (res []testTx) { +func genRandomTxs(seed int64, countTx, countAccount int) (res []testTx) { maxPriority := 100 r := rand.New(rand.NewSource(seed)) accounts := simtypes.RandomAccounts(r, countAccount) @@ -491,7 +491,7 @@ func genRandomTxs(seed int64, countTx int, countAccount int) (res []testTx) { // since there are multiple valid ordered graph traversals for a given set of txs strict // validation against the ordered txs generated from this function is not possible as written -func genOrderedTxs(seed int64, maxTx int, numAcc int) (ordered []testTx, shuffled []testTx) { +func genOrderedTxs(seed int64, maxTx, numAcc int) (ordered, shuffled []testTx) { r := rand.New(rand.NewSource(seed)) accountNonces := make(map[string]uint64) prange := 10 diff --git a/types/module/configurator.go b/types/module/configurator.go index c756d38af981..58c9747442d4 100644 --- a/types/module/configurator.go +++ b/types/module/configurator.go @@ -85,7 +85,7 @@ func (c *configurator) Error() error { } // NewConfigurator returns a new Configurator instance -func NewConfigurator(cdc codec.Codec, msgServer grpc.Server, queryServer grpc.Server) Configurator { +func NewConfigurator(cdc codec.Codec, msgServer, queryServer grpc.Server) Configurator { return &configurator{ cdc: cdc, msgServer: msgServer, diff --git a/types/module/module.go b/types/module/module.go index ba73d3d9d7d8..e1891edda90a 100644 --- a/types/module/module.go +++ b/types/module/module.go @@ -29,6 +29,7 @@ needlessly defining many placeholder functions package module import ( + "context" "encoding/json" "errors" "fmt" @@ -212,6 +213,11 @@ type EndBlockAppModule interface { EndBlock(sdk.Context, abci.RequestEndBlock) []abci.ValidatorUpdate } +type HasABCIEndblock interface { + AppModule + EndBlock(context.Context) ([]abci.ValidatorUpdate, error) +} + // GenesisOnlyAppModule is an AppModule that only has import/export functionality type GenesisOnlyAppModule struct { AppModuleGenesis @@ -695,6 +701,22 @@ func (m *Manager) EndBlock(ctx sdk.Context, req abci.RequestEndBlock) (abci.Resp if err != nil { return abci.ResponseEndBlock{}, err } + } else if module, ok := m.Modules[moduleName].(HasABCIEndblock); ok { + moduleValUpdates, err := module.EndBlock(ctx) + if err != nil { + return abci.ResponseEndBlock{}, err + } + // use these validator updates if provided, the module manager assumes + // only one module will update the validator set + if len(moduleValUpdates) > 0 { + if len(validatorUpdates) > 0 { + return abci.ResponseEndBlock{}, errors.New("validator EndBlock updates already set by a previous module") + } + + for _, updates := range moduleValUpdates { + validatorUpdates = append(validatorUpdates, abci.ValidatorUpdate{PubKey: updates.PubKey, Power: updates.Power}) + } + } } else { continue } diff --git a/types/module/simulation.go b/types/module/simulation.go index 036ef3a9f755..79ac42c99d3a 100644 --- a/types/module/simulation.go +++ b/types/module/simulation.go @@ -7,6 +7,7 @@ import ( "time" sdkmath "cosmossdk.io/math" + "github.com/cosmos/cosmos-sdk/client" "github.com/cosmos/cosmos-sdk/codec" "github.com/cosmos/cosmos-sdk/types/simulation" ) @@ -33,7 +34,7 @@ type HasProposalMsgs interface { // HasProposalContents defines the contents that can be used to simulate legacy governance (v1beta1) proposals type HasProposalContents interface { // content functions used to simulate governance proposals - ProposalContents(simState SimulationState) []simulation.WeightedProposalContent //nolint:staticcheck + ProposalContents(simState SimulationState) []simulation.WeightedProposalContent //nolint:staticcheck // legacy v1beta1 governance } // SimulationManager defines a simulation manager that provides the high level utility @@ -142,6 +143,7 @@ func (sm *SimulationManager) WeightedOperations(simState SimulationState) []simu type SimulationState struct { AppParams simulation.AppParams Cdc codec.JSONCodec // application codec + TxConfig client.TxConfig // Shared TxConfig; this is expensive to create and stateless, so create it once up front. Rand *rand.Rand // random number GenState map[string]json.RawMessage // genesis state Accounts []simulation.Account // simulation accounts @@ -151,7 +153,7 @@ type SimulationState struct { GenTimestamp time.Time // genesis timestamp UnbondTime time.Duration // staking unbond time stored to use it as the slashing maximum evidence duration LegacyParamChange []simulation.LegacyParamChange // simulated parameter changes from modules - //nolint:staticcheck + //nolint:staticcheck // legacy used for testing LegacyProposalContents []simulation.WeightedProposalContent // proposal content generator functions with their default weight and app sim key ProposalMsgs []simulation.WeightedProposalMsg // proposal msg generator functions with their default weight and app sim key } diff --git a/types/module/testutil/codec.go b/types/module/testutil/codec.go index cbb51dc68565..8c1078b17675 100644 --- a/types/module/testutil/codec.go +++ b/types/module/testutil/codec.go @@ -41,3 +41,9 @@ func MakeTestEncodingConfig(modules ...module.AppModuleBasic) TestEncodingConfig return encCfg } + +func MakeTestTxConfig() client.TxConfig { + interfaceRegistry := types.NewInterfaceRegistry() + cdc := codec.NewProtoCodec(interfaceRegistry) + return tx.NewTxConfig(cdc, tx.DefaultSignModes) +} diff --git a/types/query/collections_pagination.go b/types/query/collections_pagination.go index 633efa8ff3fe..9e8397d9ea2f 100644 --- a/types/query/collections_pagination.go +++ b/types/query/collections_pagination.go @@ -10,6 +10,15 @@ import ( storetypes "cosmossdk.io/store/types" ) +// WithCollectionPaginationPairPrefix applies a prefix to a collection, whose key is a collection.Pair, +// being paginated that needs prefixing. +func WithCollectionPaginationPairPrefix[K1, K2 any](prefix K1) func(o *CollectionsPaginateOptions[collections.Pair[K1, K2]]) { + return func(o *CollectionsPaginateOptions[collections.Pair[K1, K2]]) { + prefix := collections.PairPrefix[K1, K2](prefix) + o.Prefix = &prefix + } +} + // CollectionsPaginateOptions provides extra options for pagination in collections. type CollectionsPaginateOptions[K any] struct { // Prefix allows to optionally set a prefix for the pagination. @@ -26,7 +35,7 @@ type Collection[K, V any] interface { KeyCodec() collcodec.KeyCodec[K] } -// CollectionPaginate follows the same behaviour as Paginate but works on a Collection. +// CollectionPaginate follows the same behavior as Paginate but works on a Collection. func CollectionPaginate[K, V any, C Collection[K, V]]( ctx context.Context, coll C, @@ -41,7 +50,7 @@ func CollectionFilteredPaginate[K, V any, C Collection[K, V]]( ctx context.Context, coll C, pageReq *PageRequest, - predicateFunc func(key K, value V) (include bool), + predicateFunc func(key K, value V) (include bool, err error), opts ...func(opt *CollectionsPaginateOptions[K]), ) ([]collections.KeyValue[K, V], *PageResponse, error) { if pageReq == nil { @@ -87,9 +96,9 @@ func CollectionFilteredPaginate[K, V any, C Collection[K, V]]( } else { results, pageRes, err = collFilteredPaginateNoKey(ctx, coll, prefix, reverse, offset, limit, countTotal, predicateFunc) } - // invalid iter error is ignored to retain Paginate behaviour + // invalid iter error is ignored to retain Paginate behavior if errors.Is(err, collections.ErrInvalidIterator) { - return results, pageRes, nil + return results, new(PageResponse), nil } // strip the prefix from next key if len(pageRes.NextKey) != 0 && prefix != nil { @@ -108,7 +117,7 @@ func collFilteredPaginateNoKey[K, V any, C Collection[K, V]]( offset uint64, limit uint64, countTotal bool, - predicateFunc func(K, V) bool, + predicateFunc func(K, V) (bool, error), ) ([]collections.KeyValue[K, V], *PageResponse, error) { iterator, err := getCollIter[K, V](ctx, coll, prefix, nil, reverse) if err != nil { @@ -137,12 +146,17 @@ func collFilteredPaginateNoKey[K, V any, C Collection[K, V]]( // if no predicate function is specified then we just include the result if predicateFunc == nil { results = append(results, kv) - count++ // if predicate function is defined we check if the result matches the filtering criteria - } else if predicateFunc(kv.Key, kv.Value) { - results = append(results, kv) - count++ + } else { + include, err := predicateFunc(kv.Key, kv.Value) + if err != nil { + return nil, nil, err + } + if include { + results = append(results, kv) + } } + count++ // second case, we found all the objects specified within the limit case count == limit: key, err := iterator.Key() @@ -200,7 +214,7 @@ func collFilteredPaginateByKey[K, V any, C Collection[K, V]]( key []byte, reverse bool, limit uint64, - predicateFunc func(K, V) bool, + predicateFunc func(K, V) (bool, error), ) ([]collections.KeyValue[K, V], *PageResponse, error) { iterator, err := getCollIter[K, V](ctx, coll, prefix, key, reverse) if err != nil { @@ -237,13 +251,18 @@ func collFilteredPaginateByKey[K, V any, C Collection[K, V]]( // if no predicate is specified then we just append the result if predicateFunc == nil { results = append(results, kv) - count++ // if predicate is applied we execute the predicate function // and append only if predicateFunc yields true. - } else if predicateFunc(kv.Key, kv.Value) { - results = append(results, kv) - count++ + } else { + include, err := predicateFunc(kv.Key, kv.Value) + if err != nil { + return nil, nil, err + } + if include { + results = append(results, kv) + } } + count++ } return results, &PageResponse{ @@ -258,14 +277,20 @@ func encodeCollKey[K, V any, C Collection[K, V]](coll C, key K) ([]byte, error) return buffer, err } -func getCollIter[K, V any, C Collection[K, V]](ctx context.Context, coll C, prefix []byte, start []byte, reverse bool) (collections.Iterator[K, V], error) { +func getCollIter[K, V any, C Collection[K, V]](ctx context.Context, coll C, prefix, start []byte, reverse bool) (collections.Iterator[K, V], error) { + // TODO: maybe can be simplified + if reverse { + var end []byte + if prefix != nil { + start = storetypes.PrefixEndBytes(append(prefix, start...)) + end = prefix + } + return coll.IterateRaw(ctx, end, start, collections.OrderDescending) + } var end []byte if prefix != nil { start = append(prefix, start...) end = storetypes.PrefixEndBytes(prefix) } - if reverse { - return coll.IterateRaw(ctx, nil, start, collections.OrderDescending) - } return coll.IterateRaw(ctx, start, end, collections.OrderAscending) } diff --git a/types/query/collections_pagination_test.go b/types/query/collections_pagination_test.go index ebb086453913..ebce41a4f22e 100644 --- a/types/query/collections_pagination_test.go +++ b/types/query/collections_pagination_test.go @@ -48,7 +48,7 @@ func TestCollectionPagination(t *testing.T) { type test struct { req *PageRequest expResp *PageResponse - filter func(key uint64, value uint64) bool + filter func(key, value uint64) (bool, error) expResults []collections.KeyValue[uint64, uint64] wantErr error } @@ -99,15 +99,14 @@ func TestCollectionPagination(t *testing.T) { Limit: 3, }, expResp: &PageResponse{ - NextKey: encodeKey(5), + NextKey: encodeKey(3), }, - filter: func(key uint64, value uint64) bool { - return key%2 == 0 + filter: func(key, value uint64) (bool, error) { + return key%2 == 0, nil }, expResults: []collections.KeyValue[uint64, uint64]{ {Key: 0, Value: 0}, {Key: 2, Value: 2}, - {Key: 4, Value: 4}, }, }, "filtered with key": { @@ -116,15 +115,14 @@ func TestCollectionPagination(t *testing.T) { Limit: 3, }, expResp: &PageResponse{ - NextKey: encodeKey(7), + NextKey: encodeKey(5), }, - filter: func(key uint64, value uint64) bool { - return key%2 == 0 + filter: func(key, value uint64) (bool, error) { + return key%2 == 0, nil }, expResults: []collections.KeyValue[uint64, uint64]{ {Key: 2, Value: 2}, {Key: 4, Value: 4}, - {Key: 6, Value: 6}, }, }, } diff --git a/types/query/filtered_pagination.go b/types/query/filtered_pagination.go index 108aab03fae8..dcb35530395c 100644 --- a/types/query/filtered_pagination.go +++ b/types/query/filtered_pagination.go @@ -20,7 +20,7 @@ import ( func FilteredPaginate( prefixStore types.KVStore, pageRequest *PageRequest, - onResult func(key []byte, value []byte, accumulate bool) (bool, error), + onResult func(key, value []byte, accumulate bool) (bool, error), ) (*PageResponse, error) { // if the PageRequest is nil, use default PageRequest if pageRequest == nil { diff --git a/types/query/filtered_pagination_test.go b/types/query/filtered_pagination_test.go index 69db71d2b169..81bc0d1f78bb 100644 --- a/types/query/filtered_pagination_test.go +++ b/types/query/filtered_pagination_test.go @@ -195,7 +195,7 @@ func (s *paginationTestSuite) TestFilteredPaginate() { accountStore := prefix.NewStore(balancesStore, address.MustLengthPrefix(addr1)) var balResult sdk.Coins - pageRes, err := query.FilteredPaginate(accountStore, pageReq, func(key []byte, value []byte, accumulate bool) (bool, error) { + pageRes, err := query.FilteredPaginate(accountStore, pageReq, func(key, value []byte, accumulate bool) (bool, error) { var amount math.Int err := amount.Unmarshal(value) if err != nil { @@ -226,7 +226,7 @@ func execFilterPaginate(store storetypes.KVStore, pageReq *query.PageRequest, ap accountStore := prefix.NewStore(balancesStore, address.MustLengthPrefix(addr1)) var balResult sdk.Coins - res, err = query.FilteredPaginate(accountStore, pageReq, func(key []byte, value []byte, accumulate bool) (bool, error) { + res, err = query.FilteredPaginate(accountStore, pageReq, func(key, value []byte, accumulate bool) (bool, error) { var amount math.Int err := amount.Unmarshal(value) if err != nil { @@ -268,7 +268,7 @@ func (s *paginationTestSuite) TestFilteredPaginationsNextKey() { accountStore := prefix.NewStore(balancesStore, address.MustLengthPrefix(addr1)) var balResult sdk.Coins - res, err = query.FilteredPaginate(accountStore, pageReq, func(key []byte, value []byte, accumulate bool) (bool, error) { + res, err = query.FilteredPaginate(accountStore, pageReq, func(key, value []byte, accumulate bool) (bool, error) { var amount math.Int err := amount.Unmarshal(value) if err != nil { diff --git a/types/query/fuzz_test.go b/types/query/fuzz_test.go index fda80367b408..e41afd1c1df3 100644 --- a/types/query/fuzz_test.go +++ b/types/query/fuzz_test.go @@ -85,7 +85,7 @@ func FuzzPagination(f *testing.F) { authStore := suite.ctx.KVStore(suite.app.UnsafeFindStoreKey(types.StoreKey)) balancesStore := prefix.NewStore(authStore, types.BalancesPrefix) accountStore := prefix.NewStore(balancesStore, address.MustLengthPrefix(addr1)) - _, _ = query.Paginate(accountStore, req.Pagination, func(key []byte, value []byte) error { + _, _ = query.Paginate(accountStore, req.Pagination, func(key, value []byte) error { var amount math.Int err := amount.Unmarshal(value) if err != nil { diff --git a/types/query/pagination.go b/types/query/pagination.go index 676f5bc2a36e..3eeb3a297aec 100644 --- a/types/query/pagination.go +++ b/types/query/pagination.go @@ -52,7 +52,7 @@ func ParsePagination(pageReq *PageRequest) (page, limit int, err error) { func Paginate( prefixStore types.KVStore, pageRequest *PageRequest, - onResult func(key []byte, value []byte) error, + onResult func(key, value []byte) error, ) (*PageResponse, error) { // if the PageRequest is nil, use default PageRequest if pageRequest == nil { diff --git a/types/query/pagination_test.go b/types/query/pagination_test.go index 025806e05b88..a31c43c0e3e9 100644 --- a/types/query/pagination_test.go +++ b/types/query/pagination_test.go @@ -231,7 +231,7 @@ func (s *paginationTestSuite) TestReversePagination() { request := types.NewQueryAllBalancesRequest(addr1, pageReq, false) res1, err := queryClient.AllBalances(gocontext.Background(), request) s.Require().NoError(err) - s.Require().Equal(res1.Balances.Len(), 2) + s.Require().Equal(2, res1.Balances.Len()) s.Require().NotNil(res1.Pagination.NextKey) s.T().Log("verify paginate with custom limit and countTotal, Reverse false") @@ -354,7 +354,7 @@ func (s *paginationTestSuite) TestPaginate() { authStore := s.ctx.KVStore(s.app.UnsafeFindStoreKey(types.StoreKey)) balancesStore := prefix.NewStore(authStore, types.BalancesPrefix) accountStore := prefix.NewStore(balancesStore, address.MustLengthPrefix(addr1)) - pageRes, err := query.Paginate(accountStore, request.Pagination, func(key []byte, value []byte) error { + pageRes, err := query.Paginate(accountStore, request.Pagination, func(key, value []byte) error { var amount math.Int err := amount.Unmarshal(value) if err != nil { diff --git a/types/registry/registry.go b/types/registry/registry.go new file mode 100644 index 000000000000..9fe5c8facc9c --- /dev/null +++ b/types/registry/registry.go @@ -0,0 +1,52 @@ +package registry + +import ( + "sync" + + "github.com/cosmos/gogoproto/proto" + "google.golang.org/protobuf/reflect/protoreflect" + "google.golang.org/protobuf/reflect/protoregistry" + + "cosmossdk.io/x/tx/signing" +) + +var ( + mergedRegistryOnce sync.Once + mergedRegistry *protoregistry.Files + _ signing.ProtoFileResolver = lazyProtoRegistry{} +) + +// lazyProtoRegistry is a lazy loading wrapper around the global protobuf registry. +type lazyProtoRegistry struct{} + +func getRegistry() *protoregistry.Files { + var err error + mergedRegistryOnce.Do(func() { + mergedRegistry, err = proto.MergedRegistry() + if err != nil { + panic(err) + } + }) + return mergedRegistry +} + +func (l lazyProtoRegistry) FindFileByPath(s string) (protoreflect.FileDescriptor, error) { + reg := getRegistry() + return reg.FindFileByPath(s) +} + +func (l lazyProtoRegistry) FindDescriptorByName(name protoreflect.FullName) (protoreflect.Descriptor, error) { + reg := getRegistry() + return reg.FindDescriptorByName(name) +} + +func (l lazyProtoRegistry) RangeFiles(f func(protoreflect.FileDescriptor) bool) { + reg := getRegistry() + reg.RangeFiles(f) +} + +// MergedProtoRegistry returns a lazy loading wrapper around the global protobuf registry, a merged registry +// containing both gogo proto and pulsar types. +func MergedProtoRegistry() signing.ProtoFileResolver { + return lazyProtoRegistry{} +} diff --git a/types/result.go b/types/result.go index 3d5e20080e4a..56e3ef7879ed 100644 --- a/types/result.go +++ b/types/result.go @@ -230,7 +230,7 @@ func WrapServiceResult(ctx Context, res proto.Message, err error) (*Result, erro } // calculate total pages in an overflow safe manner -func calcTotalPages(totalCount int64, limit int64) int64 { +func calcTotalPages(totalCount, limit int64) int64 { totalPages := int64(0) if totalCount != 0 && limit != 0 { if totalCount%limit > 0 { diff --git a/types/staking.go b/types/staking.go index 44053ca30fb5..38019d46a422 100644 --- a/types/staking.go +++ b/types/staking.go @@ -25,7 +25,7 @@ var ( ) // TokensToConsensusPower - convert input tokens to potential consensus-engine power -func TokensToConsensusPower(tokens sdkmath.Int, powerReduction sdkmath.Int) int64 { +func TokensToConsensusPower(tokens, powerReduction sdkmath.Int) int64 { return (tokens.Quo(powerReduction)).Int64() } diff --git a/types/tx_msg.go b/types/tx_msg.go index d0127a7b5b67..ba4e1238523b 100644 --- a/types/tx_msg.go +++ b/types/tx_msg.go @@ -16,10 +16,6 @@ type ( Msg interface { proto.Message - // ValidateBasic does a simple validation check that - // doesn't require access to any other information. - ValidateBasic() error - // GetSigners returns the addrs of signers that must sign. // CONTRACT: All signatures must be present to be valid. // CONTRACT: Returns addrs in some deterministic order. @@ -42,12 +38,10 @@ type ( // Tx defines the interface a transaction must fulfill. Tx interface { + HasValidateBasic + // GetMsgs gets the all the transaction's messages. GetMsgs() []Msg - - // ValidateBasic does a simple and lightweight validation check that doesn't - // require access to any other information. - ValidateBasic() error } // FeeTx defines the interface to be implemented by Tx to use the FeeDecorators @@ -72,6 +66,15 @@ type ( GetTimeoutHeight() uint64 } + + // HasValidateBasic defines a type that has a ValidateBasic method. + // ValidateBasic is deprecated and now facultative. + // Prefer validating messages directly in the msg server. + HasValidateBasic interface { + // ValidateBasic does a simple validation check that + // doesn't require access to any other information. + ValidateBasic() error + } ) // TxDecoder unmarshals transaction bytes diff --git a/types/utils.go b/types/utils.go index 340014009039..02f022d1d402 100644 --- a/types/utils.go +++ b/types/utils.go @@ -75,13 +75,13 @@ func ParseTimeBytes(bz []byte) (time.Time, error) { } // Parses an encoded type using FormatTimeKey back into a time.Time -func ParseTime(T any) (time.Time, error) { //nolint:gocritic +func ParseTime(t any) (time.Time, error) { var ( result time.Time err error ) - switch t := T.(type) { + switch t := t.(type) { case time.Time: result, err = t, nil case []byte: @@ -127,7 +127,7 @@ func AppendLengthPrefixedBytes(args ...[]byte) []byte { } // ParseLengthPrefixedBytes panics when store key length is not equal to the given length. -func ParseLengthPrefixedBytes(key []byte, startIndex int, sliceLength int) ([]byte, int) { +func ParseLengthPrefixedBytes(key []byte, startIndex, sliceLength int) ([]byte, int) { neededLength := startIndex + sliceLength endIndex := neededLength - 1 kv.AssertKeyAtLeastLength(key, neededLength) diff --git a/version/command.go b/version/command.go index 96fcfcc954c5..451173400c22 100644 --- a/version/command.go +++ b/version/command.go @@ -5,12 +5,14 @@ import ( "fmt" "strings" - "github.com/cometbft/cometbft/libs/cli" "github.com/spf13/cobra" "sigs.k8s.io/yaml" ) -const flagLong = "long" +const ( + flagLong = "long" + flagOutput = "output" +) // NewVersionCommand returns a CLI command to interactively print the application binary version information. func NewVersionCommand() *cobra.Command { @@ -31,7 +33,7 @@ func NewVersionCommand() *cobra.Command { err error ) - output, _ := cmd.Flags().GetString(cli.OutputFlag) + output, _ := cmd.Flags().GetString(flagOutput) switch strings.ToLower(output) { case "json": bz, err = json.Marshal(verInfo) @@ -50,7 +52,7 @@ func NewVersionCommand() *cobra.Command { } cmd.Flags().Bool(flagLong, false, "Print long version information") - cmd.Flags().StringP(cli.OutputFlag, "o", "text", "Output format (text|json)") + cmd.Flags().StringP(flagOutput, "o", "text", "Output format (text|json)") return cmd } diff --git a/version/version_test.go b/version/version_test.go index f14f6c03d31c..caf0a5fb6b60 100644 --- a/version/version_test.go +++ b/version/version_test.go @@ -7,10 +7,10 @@ import ( "strings" "testing" - "github.com/cometbft/cometbft/libs/cli" "github.com/stretchr/testify/assert" "github.com/stretchr/testify/require" + "github.com/cosmos/cosmos-sdk/client/flags" "github.com/cosmos/cosmos-sdk/testutil" "github.com/cosmos/cosmos-sdk/testutil/cmdtest" "github.com/cosmos/cosmos-sdk/version" @@ -144,7 +144,7 @@ func Test_runVersionCmd(t *testing.T) { _, mockOut := testutil.ApplyMockIO(cmd) cmd.SetArgs([]string{ - fmt.Sprintf("--%s=''", cli.OutputFlag), + fmt.Sprintf("--%s=''", flags.FlagOutput), "--long=false", }) @@ -153,7 +153,7 @@ func Test_runVersionCmd(t *testing.T) { mockOut.Reset() cmd.SetArgs([]string{ - fmt.Sprintf("--%s=json", cli.OutputFlag), "--long=true", + fmt.Sprintf("--%s=json", flags.FlagOutput), "--long=true", }) info := version.NewInfo() diff --git a/x/README.md b/x/README.md index 336601ff4de1..a7d3c5bc344c 100644 --- a/x/README.md +++ b/x/README.md @@ -29,8 +29,14 @@ To learn more about the process of building modules, visit the [building modules ## IBC -The IBC module for the SDK has moved to its [own repository](https://github.com/cosmos/ibc-go). +The IBC module for the SDK is maintained by the IBC Go team in its [own repository](https://github.com/cosmos/ibc-go). + +Additionally, the [capability module](https://github.com/cosmos/ibc-go/tree/fdd664698d79864f1e00e147f9879e58497b5ef1/modules/capability) is from v0.48+ maintained by the IBC Go team in its [own repository](https://github.com/cosmos/ibc-go/tree/fdd664698d79864f1e00e147f9879e58497b5ef1/modules/capability). ## CosmWasm -The CosmWasm module enables smart contracts, and has its [own repository](https://github.com/CosmWasm/cosmwasm) and [documentation site](https://docs.cosmwasm.com/docs). +The CosmWasm module enables smart contracts, learn more by going to their [documentation site](https://book.cosmwasm.com/), or visit [the repository](https://github.com/CosmWasm/cosmwasm). + +## EVM + +Read more about writing smart contracts with solidity at the official [`evm` documentation page](https://docs.evmos.org/modules/evm/). diff --git a/x/auth/ante/ante.go b/x/auth/ante/ante.go index f3b4ebb6a1bf..05c5eb102657 100644 --- a/x/auth/ante/ante.go +++ b/x/auth/ante/ante.go @@ -2,13 +2,13 @@ package ante import ( storetypes "cosmossdk.io/store/types" + txsigning "cosmossdk.io/x/tx/signing" errorsmod "cosmossdk.io/errors" sdk "github.com/cosmos/cosmos-sdk/types" sdkerrors "github.com/cosmos/cosmos-sdk/types/errors" "github.com/cosmos/cosmos-sdk/types/tx/signing" - authsigning "github.com/cosmos/cosmos-sdk/x/auth/signing" "github.com/cosmos/cosmos-sdk/x/auth/types" ) @@ -18,7 +18,7 @@ type HandlerOptions struct { BankKeeper types.BankKeeper ExtensionOptionChecker ExtensionOptionChecker FeegrantKeeper FeegrantKeeper - SignModeHandler authsigning.SignModeHandler + SignModeHandler *txsigning.HandlerMap SigGasConsumer func(meter storetypes.GasMeter, sig signing.SignatureV2, params types.Params) error TxFeeChecker TxFeeChecker } diff --git a/x/auth/ante/ante_test.go b/x/auth/ante/ante_test.go index 79d485f25eed..dd6d2dd5a149 100644 --- a/x/auth/ante/ante_test.go +++ b/x/auth/ante/ante_test.go @@ -1454,7 +1454,7 @@ func TestAnteHandlerReCheck(t *testing.T) { tx, err = suite.CreateTestTx(suite.ctx, privs, accNums, accSeqs, suite.ctx.ChainID(), signing.SignMode_SIGN_MODE_DIRECT) require.NoError(t, err) txBytes, err := json.Marshal(tx) - require.Nil(t, err, "Error marshalling tx: %v", err) + require.Nil(t, err, "Error marshaling tx: %v", err) suite.ctx = suite.ctx.WithTxBytes(txBytes) // require that state machine param-dependent checking is still run on recheck since parameters can change between check and recheck diff --git a/x/auth/ante/expected_keepers.go b/x/auth/ante/expected_keepers.go index 1db0dff716c1..99f2dd8dc6ae 100644 --- a/x/auth/ante/expected_keepers.go +++ b/x/auth/ante/expected_keepers.go @@ -1,6 +1,8 @@ package ante import ( + "context" + sdk "github.com/cosmos/cosmos-sdk/types" "github.com/cosmos/cosmos-sdk/x/auth/types" ) @@ -8,13 +10,13 @@ import ( // AccountKeeper defines the contract needed for AccountKeeper related APIs. // Interface provides support to use non-sdk AccountKeeper for AnteHandler's decorators. type AccountKeeper interface { - GetParams(ctx sdk.Context) (params types.Params) - GetAccount(ctx sdk.Context, addr sdk.AccAddress) sdk.AccountI - SetAccount(ctx sdk.Context, acc sdk.AccountI) + GetParams(ctx context.Context) (params types.Params) + GetAccount(ctx context.Context, addr sdk.AccAddress) sdk.AccountI + SetAccount(ctx context.Context, acc sdk.AccountI) GetModuleAddress(moduleName string) sdk.AccAddress } // FeegrantKeeper defines the expected feegrant keeper. type FeegrantKeeper interface { - UseGrantedFees(ctx sdk.Context, granter, grantee sdk.AccAddress, fee sdk.Coins, msgs []sdk.Msg) error + UseGrantedFees(ctx context.Context, granter, grantee sdk.AccAddress, fee sdk.Coins, msgs []sdk.Msg) error } diff --git a/x/auth/ante/feegrant_test.go b/x/auth/ante/feegrant_test.go index 3cee6394f6b6..31cebeaec981 100644 --- a/x/auth/ante/feegrant_test.go +++ b/x/auth/ante/feegrant_test.go @@ -1,6 +1,7 @@ package ante_test import ( + "context" "errors" "math/rand" "testing" @@ -168,14 +169,18 @@ func TestDeductFeesNoDelegation(t *testing.T) { var defaultGenTxGas uint64 = 10000000 tx, err := genTxWithFeeGranter(protoTxCfg, msgs, fee, defaultGenTxGas, suite.ctx.ChainID(), accNums, seqs, feeAcc, privs...) require.NoError(t, err) - _, err = feeAnteHandler(suite.ctx, tx, false) // tests only feegrant ante + txBytes, err := protoTxCfg.TxEncoder()(tx) + require.NoError(t, err) + bytesCtx := suite.ctx.WithTxBytes(txBytes) + require.NoError(t, err) + _, err = feeAnteHandler(bytesCtx, tx, false) // tests only feegrant ante if tc.valid { require.NoError(t, err) } else { testutil.AssertError(t, err, tc.err, tc.errMsg) } - _, err = anteHandlerStack(suite.ctx, tx, false) // tests while stack + _, err = anteHandlerStack(bytesCtx, tx, false) // tests whole stack if tc.valid { require.NoError(t, err) } else { @@ -200,7 +205,7 @@ func genTxWithFeeGranter(gen client.TxConfig, msgs []sdk.Msg, feeAmt sdk.Coins, memo := simulation.RandStringOfLength(r, simulation.RandIntBetween(r, 0, 100)) - signMode := gen.SignModeHandler().DefaultMode() + signMode := signing.SignMode_SIGN_MODE_DIRECT // 1st round: set SignatureV2 with empty signatures, to set correct // signer infos. @@ -234,8 +239,10 @@ func genTxWithFeeGranter(gen client.TxConfig, msgs []sdk.Msg, feeAmt sdk.Coins, ChainID: chainID, AccountNumber: accNums[i], Sequence: accSeqs[i], + PubKey: p.PubKey(), } - signBytes, err := gen.SignModeHandler().GetSignBytes(signMode, signerData, tx.GetTx()) + signBytes, err := authsign.GetSignBytesAdapter( + context.Background(), gen.TxEncoder(), gen.SignModeHandler(), signMode, signerData, tx.GetTx()) if err != nil { panic(err) } diff --git a/x/auth/ante/setup_test.go b/x/auth/ante/setup_test.go index a8644c46badc..67c408218af1 100644 --- a/x/auth/ante/setup_test.go +++ b/x/auth/ante/setup_test.go @@ -82,7 +82,7 @@ func TestRecoverPanic(t *testing.T) { require.Equal(t, gasLimit, newCtx.GasMeter().Limit()) antehandler = sdk.ChainAnteDecorators(sud, PanicDecorator{}) - require.Panics(t, func() { antehandler(suite.ctx, tx, false) }, "Recovered from non-Out-of-Gas panic") //nolint:errcheck + require.Panics(t, func() { antehandler(suite.ctx, tx, false) }, "Recovered from non-Out-of-Gas panic") } type OutOfGasDecorator struct{} diff --git a/x/auth/ante/sigverify.go b/x/auth/ante/sigverify.go index 422dde1f9978..c38ec4741d94 100644 --- a/x/auth/ante/sigverify.go +++ b/x/auth/ante/sigverify.go @@ -6,8 +6,14 @@ import ( "encoding/hex" "fmt" + "google.golang.org/protobuf/types/known/anypb" + errorsmod "cosmossdk.io/errors" storetypes "cosmossdk.io/store/types" + "cosmossdk.io/x/tx/decode" + txsigning "cosmossdk.io/x/tx/signing" + codectypes "github.com/cosmos/cosmos-sdk/codec/types" + "github.com/cosmos/cosmos-sdk/types/registry" "github.com/cosmos/cosmos-sdk/crypto/keys/ed25519" kmultisig "github.com/cosmos/cosmos-sdk/crypto/keys/multisig" @@ -194,17 +200,17 @@ func (sgcd SigGasConsumeDecorator) AnteHandle(ctx sdk.Context, tx sdk.Tx, simula return next(ctx, tx, simulate) } -// Verify all signatures for a tx and return an error if any are invalid. Note, +// SigVerificationDecorator verifies all signatures for a tx and return an error if any are invalid. Note, // the SigVerificationDecorator will not check signatures on ReCheck. // // CONTRACT: Pubkeys are set in context for all signers before this decorator runs // CONTRACT: Tx must implement SigVerifiableTx interface type SigVerificationDecorator struct { ak AccountKeeper - signModeHandler authsigning.SignModeHandler + signModeHandler *txsigning.HandlerMap } -func NewSigVerificationDecorator(ak AccountKeeper, signModeHandler authsigning.SignModeHandler) SigVerificationDecorator { +func NewSigVerificationDecorator(ak AccountKeeper, signModeHandler *txsigning.HandlerMap) SigVerificationDecorator { return SigVerificationDecorator{ ak: ak, signModeHandler: signModeHandler, @@ -279,17 +285,38 @@ func (svd SigVerificationDecorator) AnteHandle(ctx sdk.Context, tx sdk.Tx, simul if !genesis { accNum = acc.GetAccountNumber() } - signerData := authsigning.SignerData{ - Address: acc.GetAddress().String(), - ChainID: chainID, - AccountNumber: accNum, - Sequence: acc.GetSequence(), - PubKey: pubKey, - } // no need to verify signatures on recheck tx if !simulate && !ctx.IsReCheckTx() { - err := authsigning.VerifySignature(ctx, pubKey, signerData, sig.Data, svd.signModeHandler, tx) + anyPk, _ := codectypes.NewAnyWithValue(pubKey) + + signerData := txsigning.SignerData{ + Address: acc.GetAddress().String(), + ChainID: chainID, + AccountNumber: accNum, + Sequence: acc.GetSequence(), + PubKey: &anypb.Any{ + TypeUrl: anyPk.TypeUrl, + Value: anyPk.Value, + }, + } + decodeCtx, err := decode.NewDecoder(decode.Options{ProtoFiles: registry.MergedProtoRegistry()}) + if err != nil { + return ctx, err + } + // note: this is performance hit is temporary. Ultimately, the tx will be decoded once in BaseApp, + // but for now we need double decoding to support both SignModeHandlers. + decodedTx, err := decodeCtx.Decode(ctx.TxBytes()) + if err != nil { + return ctx, err + } + txData := txsigning.TxData{ + Body: decodedTx.Tx.Body, + AuthInfo: decodedTx.Tx.AuthInfo, + AuthInfoBytes: decodedTx.TxRaw.AuthInfoBytes, + BodyBytes: decodedTx.TxRaw.BodyBytes, + } + err = authsigning.VerifySignature(ctx, pubKey, signerData, sig.Data, svd.signModeHandler, txData) if err != nil { var errMsg string if OnlyLegacyAminoSigners(sig.Data) { @@ -297,7 +324,7 @@ func (svd SigVerificationDecorator) AnteHandle(ctx sdk.Context, tx sdk.Tx, simul // and therefore communicate sequence number as a potential cause of error. errMsg = fmt.Sprintf("signature verification failed; please verify account number (%d), sequence (%d) and chain-id (%s)", accNum, acc.GetSequence(), chainID) } else { - errMsg = fmt.Sprintf("signature verification failed; please verify account number (%d) and chain-id (%s)", accNum, chainID) + errMsg = fmt.Sprintf("signature verification failed; please verify account number (%d) and chain-id (%s): (%s)", accNum, chainID, err.Error()) } return ctx, errorsmod.Wrap(sdkerrors.ErrUnauthorized, errMsg) diff --git a/x/auth/ante/sigverify_test.go b/x/auth/ante/sigverify_test.go index 2af60c81a8ce..6309f72633f2 100644 --- a/x/auth/ante/sigverify_test.go +++ b/x/auth/ante/sigverify_test.go @@ -8,6 +8,7 @@ import ( "github.com/stretchr/testify/require" storetypes "cosmossdk.io/store/types" + authsign "github.com/cosmos/cosmos-sdk/x/auth/signing" "github.com/cosmos/cosmos-sdk/codec" "github.com/cosmos/cosmos-sdk/crypto/keys/ed25519" @@ -126,17 +127,16 @@ func TestConsumeSignatureVerificationGas(t *testing.T) { func TestSigVerification(t *testing.T) { suite := SetupTestSuite(t, true) - suite.txBankKeeper.EXPECT().DenomMetadata(suite.ctx, gomock.Any()).Return(&banktypes.QueryDenomMetadataResponse{}, nil).AnyTimes() + suite.txBankKeeper.EXPECT().DenomMetadata(gomock.Any(), gomock.Any()).Return(&banktypes.QueryDenomMetadataResponse{}, nil).AnyTimes() enabledSignModes := []signing.SignMode{signing.SignMode_SIGN_MODE_DIRECT, signing.SignMode_SIGN_MODE_TEXTUAL, signing.SignMode_SIGN_MODE_LEGACY_AMINO_JSON} // Since TEXTUAL is not enabled by default, we create a custom TxConfig // here which includes it. - txt, err := txmodule.NewTextualWithGRPCConn(suite.clientCtx) + opts, err := txmodule.NewSignModeOptionsWithMetadataQueryFn(txmodule.NewGRPCCoinMetadataQueryFn(suite.clientCtx)) require.NoError(t, err) - suite.clientCtx.TxConfig = authtx.NewTxConfigWithTextual( + suite.clientCtx.TxConfig = authtx.NewTxConfigWithOptions( codec.NewProtoCodec(suite.encCfg.InterfaceRegistry), - enabledSignModes, - txt, + opts, ) suite.txBuilder = suite.clientCtx.TxConfig.NewTxBuilder() @@ -163,15 +163,16 @@ func TestSigVerification(t *testing.T) { gasLimit := testdata.NewTestGasLimit() spkd := ante.NewSetPubKeyDecorator(suite.accountKeeper) - txt, err = txmodule.NewTextualWithBankKeeper(suite.txBankKeeper) + opts, err = txmodule.NewSignModeOptionsWithMetadataQueryFn(txmodule.NewBankKeeperCoinMetadataQueryFn(suite.txBankKeeper)) require.NoError(t, err) - anteTxConfig := authtx.NewTxConfigWithTextual( + anteTxConfig := authtx.NewTxConfigWithOptions( codec.NewProtoCodec(suite.encCfg.InterfaceRegistry), - enabledSignModes, - txt, + opts, ) svd := ante.NewSigVerificationDecorator(suite.accountKeeper, anteTxConfig.SignModeHandler()) antehandler := sdk.ChainAnteDecorators(spkd, svd) + defaultSignMode, err := authsign.APISignModeToInternal(anteTxConfig.SignModeHandler().DefaultMode()) + require.NoError(t, err) type testCase struct { name string @@ -211,7 +212,7 @@ func TestSigVerification(t *testing.T) { txSigs[0] = signing.SignatureV2{ PubKey: tc.privs[0].PubKey(), Data: &signing.SingleSignatureData{ - SignMode: suite.clientCtx.TxConfig.SignModeHandler().DefaultMode(), + SignMode: defaultSignMode, Signature: badSig, }, Sequence: tc.accSeqs[0], @@ -220,7 +221,10 @@ func TestSigVerification(t *testing.T) { tx = suite.txBuilder.GetTx() } - _, err = antehandler(suite.ctx, tx, false) + txBytes, err := suite.clientCtx.TxConfig.TxEncoder()(tx) + require.NoError(t, err) + byteCtx := suite.ctx.WithTxBytes(txBytes) + _, err = antehandler(byteCtx, tx, false) if tc.shouldErr { require.NotNil(t, err, "TestCase %d: %s did not error as expected", i, tc.name) } else { @@ -288,6 +292,10 @@ func runSigDecorators(t *testing.T, params types.Params, _ bool, privs ...crypto svd := ante.NewSigVerificationDecorator(suite.accountKeeper, suite.clientCtx.TxConfig.SignModeHandler()) antehandler := sdk.ChainAnteDecorators(spkd, svgc, svd) + txBytes, err := suite.clientCtx.TxConfig.TxEncoder()(tx) + require.NoError(t, err) + suite.ctx = suite.ctx.WithTxBytes(txBytes) + // Determine gas consumption of antehandler with default params before := suite.ctx.GasMeter().GasConsumed() ctx, err := antehandler(suite.ctx, tx, false) diff --git a/x/auth/ante/testutil/expected_keepers_mocks.go b/x/auth/ante/testutil/expected_keepers_mocks.go index 34c7c68e4ef8..1302bd240b83 100644 --- a/x/auth/ante/testutil/expected_keepers_mocks.go +++ b/x/auth/ante/testutil/expected_keepers_mocks.go @@ -5,6 +5,7 @@ package testutil import ( + context "context" reflect "reflect" types "github.com/cosmos/cosmos-sdk/types" @@ -36,7 +37,7 @@ func (m *MockAccountKeeper) EXPECT() *MockAccountKeeperMockRecorder { } // GetAccount mocks base method. -func (m *MockAccountKeeper) GetAccount(ctx types.Context, addr types.AccAddress) types.AccountI { +func (m *MockAccountKeeper) GetAccount(ctx context.Context, addr types.AccAddress) types.AccountI { m.ctrl.T.Helper() ret := m.ctrl.Call(m, "GetAccount", ctx, addr) ret0, _ := ret[0].(types.AccountI) @@ -64,7 +65,7 @@ func (mr *MockAccountKeeperMockRecorder) GetModuleAddress(moduleName interface{} } // GetParams mocks base method. -func (m *MockAccountKeeper) GetParams(ctx types.Context) types0.Params { +func (m *MockAccountKeeper) GetParams(ctx context.Context) types0.Params { m.ctrl.T.Helper() ret := m.ctrl.Call(m, "GetParams", ctx) ret0, _ := ret[0].(types0.Params) @@ -78,7 +79,7 @@ func (mr *MockAccountKeeperMockRecorder) GetParams(ctx interface{}) *gomock.Call } // SetAccount mocks base method. -func (m *MockAccountKeeper) SetAccount(ctx types.Context, acc types.AccountI) { +func (m *MockAccountKeeper) SetAccount(ctx context.Context, acc types.AccountI) { m.ctrl.T.Helper() m.ctrl.Call(m, "SetAccount", ctx, acc) } @@ -113,7 +114,7 @@ func (m *MockFeegrantKeeper) EXPECT() *MockFeegrantKeeperMockRecorder { } // UseGrantedFees mocks base method. -func (m *MockFeegrantKeeper) UseGrantedFees(ctx types.Context, granter, grantee types.AccAddress, fee types.Coins, msgs []types.Msg) error { +func (m *MockFeegrantKeeper) UseGrantedFees(ctx context.Context, granter, grantee types.AccAddress, fee types.Coins, msgs []types.Msg) error { m.ctrl.T.Helper() ret := m.ctrl.Call(m, "UseGrantedFees", ctx, granter, grantee, fee, msgs) ret0, _ := ret[0].(error) diff --git a/x/auth/ante/testutil_test.go b/x/auth/ante/testutil_test.go index ea539c77ed26..0680513cd4f5 100644 --- a/x/auth/ante/testutil_test.go +++ b/x/auth/ante/testutil_test.go @@ -11,6 +11,8 @@ import ( // ref: https://github.com/cosmos/cosmos-sdk/issues/14647 _ "cosmossdk.io/api/cosmos/bank/v1beta1" _ "cosmossdk.io/api/cosmos/crypto/secp256k1" + + "github.com/cosmos/cosmos-sdk/runtime" _ "github.com/cosmos/cosmos-sdk/testutil/testdata/testpb" storetypes "cosmossdk.io/store/types" @@ -77,7 +79,7 @@ func SetupTestSuite(t *testing.T, isCheckTx bool) *AnteTestSuite { } suite.accountKeeper = keeper.NewAccountKeeper( - suite.encCfg.Codec, key, types.ProtoBaseAccount, maccPerms, sdk.Bech32MainPrefix, types.NewModuleAddress("gov").String(), + suite.encCfg.Codec, runtime.NewKVStoreService(key), types.ProtoBaseAccount, maccPerms, sdk.Bech32MainPrefix, types.NewModuleAddress("gov").String(), ) suite.accountKeeper.GetModuleAccount(suite.ctx, types.FeeCollectorName) err := suite.accountKeeper.SetParams(suite.ctx, types.DefaultParams()) @@ -151,7 +153,10 @@ func (suite *AnteTestSuite) DeliverMsgs(t *testing.T, privs []cryptotypes.PrivKe tx, txErr := suite.CreateTestTx(suite.ctx, privs, accNums, accSeqs, chainID, signing.SignMode_SIGN_MODE_DIRECT) require.NoError(t, txErr) - return suite.anteHandler(suite.ctx, tx, simulate) + txBytes, err := suite.clientCtx.TxConfig.TxEncoder()(tx) + bytesCtx := suite.ctx.WithTxBytes(txBytes) + require.NoError(t, err) + return suite.anteHandler(bytesCtx, tx, simulate) } func (suite *AnteTestSuite) RunTestCase(t *testing.T, tc TestCase, args TestCaseArgs) { @@ -163,7 +168,10 @@ func (suite *AnteTestSuite) RunTestCase(t *testing.T, tc TestCase, args TestCase // ante handlers, but here we sometimes also test the tx creation // process. tx, txErr := suite.CreateTestTx(suite.ctx, args.privs, args.accNums, args.accSeqs, args.chainID, signing.SignMode_SIGN_MODE_DIRECT) - newCtx, anteErr := suite.anteHandler(suite.ctx, tx, tc.simulate) + txBytes, err := suite.clientCtx.TxConfig.TxEncoder()(tx) + require.NoError(t, err) + bytesCtx := suite.ctx.WithTxBytes(txBytes) + newCtx, anteErr := suite.anteHandler(bytesCtx, tx, tc.simulate) if tc.expPass { require.NoError(t, txErr) @@ -190,7 +198,7 @@ func (suite *AnteTestSuite) RunTestCase(t *testing.T, tc TestCase, args TestCase // CreateTestTx is a helper function to create a tx given multiple inputs. func (suite *AnteTestSuite) CreateTestTx( ctx sdk.Context, privs []cryptotypes.PrivKey, - accNums []uint64, accSeqs []uint64, + accNums, accSeqs []uint64, chainID string, signMode signing.SignMode, ) (xauthsigning.Tx, error) { // First round: we gather all the signer infos. We use the "set empty diff --git a/x/auth/client/cli/query.go b/x/auth/client/cli/query.go index 5995a4c3d37b..1cc788a711d2 100644 --- a/x/auth/client/cli/query.go +++ b/x/auth/client/cli/query.go @@ -6,6 +6,7 @@ import ( "strconv" "strings" + "cosmossdk.io/core/address" errorsmod "cosmossdk.io/errors" "github.com/spf13/cobra" @@ -34,7 +35,7 @@ const ( ) // GetQueryCmd returns the transaction commands for this module -func GetQueryCmd() *cobra.Command { +func GetQueryCmd(ac address.Codec) *cobra.Command { cmd := &cobra.Command{ Use: types.ModuleName, Short: "Querying commands for the auth module", @@ -44,7 +45,7 @@ func GetQueryCmd() *cobra.Command { } cmd.AddCommand( - GetAccountCmd(), + GetAccountCmd(ac), GetAccountAddressByIDCmd(), GetAccountsCmd(), QueryParamsCmd(), @@ -88,7 +89,7 @@ $ query auth params // GetAccountCmd returns a query account that will display the state of the // account at a given address. -func GetAccountCmd() *cobra.Command { +func GetAccountCmd(ac address.Codec) *cobra.Command { cmd := &cobra.Command{ Use: "account [address]", Short: "Query for account by address", @@ -98,13 +99,13 @@ func GetAccountCmd() *cobra.Command { if err != nil { return err } - key, err := sdk.AccAddressFromBech32(args[0]) + _, err = ac.StringToBytes(args[0]) if err != nil { return err } queryClient := types.NewQueryClient(clientCtx) - res, err := queryClient.Account(cmd.Context(), &types.QueryAccountRequest{Address: key.String()}) + res, err := queryClient.Account(cmd.Context(), &types.QueryAccountRequest{Address: args[0]}) if err != nil { node, err2 := clientCtx.GetNode() if err2 != nil { diff --git a/x/auth/client/cli/suite_test.go b/x/auth/client/cli/suite_test.go index 29bb0a2f05f5..9be3e56e163a 100644 --- a/x/auth/client/cli/suite_test.go +++ b/x/auth/client/cli/suite_test.go @@ -1,13 +1,13 @@ package cli_test import ( - "bytes" "context" "fmt" "io" "strings" "testing" + "cosmossdk.io/core/address" "cosmossdk.io/math" abci "github.com/cometbft/cometbft/abci/types" rpcclientmock "github.com/cometbft/cometbft/rpc/client/mock" @@ -15,6 +15,7 @@ import ( "github.com/cosmos/cosmos-sdk/client" "github.com/cosmos/cosmos-sdk/client/flags" + addresscodec "github.com/cosmos/cosmos-sdk/codec/address" "github.com/cosmos/cosmos-sdk/crypto/hd" "github.com/cosmos/cosmos-sdk/crypto/keyring" kmultisig "github.com/cosmos/cosmos-sdk/crypto/keys/multisig" @@ -46,6 +47,8 @@ type CLITestSuite struct { clientCtx client.Context val sdk.AccAddress val1 sdk.AccAddress + + ac address.Codec } func TestCLITestSuite(t *testing.T) { @@ -64,7 +67,6 @@ func (s *CLITestSuite) SetupSuite() { WithOutput(io.Discard). WithChainID("test-chain") - var outBuf bytes.Buffer ctxGen := func() client.Context { bz, _ := s.encCfg.Codec.Marshal(&sdk.TxResponse{}) c := clitestutil.NewMockCometRPC(abci.ResponseQuery{ @@ -72,7 +74,7 @@ func (s *CLITestSuite) SetupSuite() { }) return s.baseCtx.WithClient(c) } - s.clientCtx = ctxGen().WithOutput(&outBuf) + s.clientCtx = ctxGen() kb := s.clientCtx.Keyring valAcc, _, err := kb.NewMnemonic("newAccount", keyring.English, sdk.FullFundraiserPath, keyring.DefaultBIP39Passphrase, hd.Secp256k1) @@ -99,12 +101,14 @@ func (s *CLITestSuite) SetupSuite() { multi := kmultisig.NewLegacyAminoPubKey(2, []cryptotypes.PubKey{pub1, pub2}) _, err = kb.SaveMultisig("multi", multi) s.Require().NoError(err) + + s.ac = addresscodec.NewBech32Codec("cosmos") } func (s *CLITestSuite) TestCLIValidateSignatures() { sendTokens := sdk.NewCoins( - sdk.NewCoin("testtoken", sdk.NewInt(10)), - sdk.NewCoin("stake", sdk.NewInt(10))) + sdk.NewCoin("testtoken", math.NewInt(10)), + sdk.NewCoin("stake", math.NewInt(10))) res, err := s.createBankMsg(s.clientCtx, s.val, sendTokens, fmt.Sprintf("--%s=true", flags.FlagGenerateOnly)) @@ -139,8 +143,8 @@ func (s *CLITestSuite) TestCLIValidateSignatures() { func (s *CLITestSuite) TestCLISignBatch() { sendTokens := sdk.NewCoins( - sdk.NewCoin("testtoken", sdk.NewInt(10)), - sdk.NewCoin("stake", sdk.NewInt(10)), + sdk.NewCoin("testtoken", math.NewInt(10)), + sdk.NewCoin("stake", math.NewInt(10)), ) generatedStd, err := s.createBankMsg(s.clientCtx, s.val, @@ -294,7 +298,7 @@ func (s *CLITestSuite) TestCLIQueryTxsCmdByEvents() { []string{ fmt.Sprintf( "--query=tx.fee='%s'", - sdk.NewCoins(sdk.NewCoin("stake", sdk.NewInt(10))).String(), + sdk.NewCoins(sdk.NewCoin("stake", math.NewInt(10))).String(), ), fmt.Sprintf("--%s=json", flags.FlagOutput), }, @@ -305,7 +309,7 @@ func (s *CLITestSuite) TestCLIQueryTxsCmdByEvents() { []string{ fmt.Sprintf( "--query=tx.fee='%s'", - sdk.NewCoins(sdk.NewCoin("stake", sdk.NewInt(0))).String(), + sdk.NewCoins(sdk.NewCoin("stake", math.NewInt(0))).String(), ), fmt.Sprintf("--%s=json", flags.FlagOutput), }, @@ -458,7 +462,7 @@ func (s *CLITestSuite) TestCLIMultisignInsufficientCosigners() { ), fmt.Sprintf("--%s=true", flags.FlagSkipConfirmation), fmt.Sprintf("--%s=%s", flags.FlagBroadcastMode, flags.BroadcastSync), - fmt.Sprintf("--%s=%s", flags.FlagFees, sdk.NewCoins(sdk.NewCoin("stake", sdk.NewInt(10))).String()), + fmt.Sprintf("--%s=%s", flags.FlagFees, sdk.NewCoins(sdk.NewCoin("stake", math.NewInt(10))).String()), fmt.Sprintf("--%s=true", flags.FlagGenerateOnly), ) s.Require().NoError(err) @@ -546,7 +550,7 @@ func (s *CLITestSuite) TestCLIMultisignSortSignatures() { ), fmt.Sprintf("--%s=true", flags.FlagSkipConfirmation), fmt.Sprintf("--%s=%s", flags.FlagBroadcastMode, flags.BroadcastSync), - fmt.Sprintf("--%s=%s", flags.FlagFees, sdk.NewCoins(sdk.NewCoin("stake", sdk.NewInt(10))).String()), + fmt.Sprintf("--%s=%s", flags.FlagFees, sdk.NewCoins(sdk.NewCoin("stake", math.NewInt(10))).String()), fmt.Sprintf("--%s=true", flags.FlagGenerateOnly), ) s.Require().NoError(err) @@ -606,7 +610,7 @@ func (s *CLITestSuite) TestSignWithMultisig() { // Create an address that is not in the keyring, will be used to simulate `--multisig` multisig := "cosmos1hd6fsrvnz6qkp87s3u86ludegq97agxsdkwzyh" - multisigAddr, err := sdk.AccAddressFromBech32(multisig) + _, err = s.ac.StringToBytes(multisig) s.Require().NoError(err) // Generate a transaction for testing --multisig with an address not in the keyring. @@ -619,7 +623,7 @@ func (s *CLITestSuite) TestSignWithMultisig() { ), fmt.Sprintf("--%s=true", flags.FlagSkipConfirmation), fmt.Sprintf("--%s=%s", flags.FlagBroadcastMode, flags.BroadcastSync), - fmt.Sprintf("--%s=%s", flags.FlagFees, sdk.NewCoins(sdk.NewCoin("stake", sdk.NewInt(10))).String()), + fmt.Sprintf("--%s=%s", flags.FlagFees, sdk.NewCoins(sdk.NewCoin("stake", math.NewInt(10))).String()), fmt.Sprintf("--%s=true", flags.FlagGenerateOnly), ) s.Require().NoError(err) @@ -632,7 +636,7 @@ func (s *CLITestSuite) TestSignWithMultisig() { // even though the tx signer is NOT the multisig address. This is fine though, // as the main point of this test is to test the `--multisig` flag with an address // that is not in the keyring. - _, err = authtestutil.TxSignExec(s.clientCtx, addr1, multiGeneratedTx2File.Name(), "--multisig", multisigAddr.String()) + _, err = authtestutil.TxSignExec(s.clientCtx, addr1, multiGeneratedTx2File.Name(), "--multisig", multisig) s.Require().Contains(err.Error(), "error getting account from keybase") } @@ -660,7 +664,7 @@ func (s *CLITestSuite) TestCLIMultisign() { ), fmt.Sprintf("--%s=true", flags.FlagSkipConfirmation), fmt.Sprintf("--%s=%s", flags.FlagBroadcastMode, flags.BroadcastSync), - fmt.Sprintf("--%s=%s", flags.FlagFees, sdk.NewCoins(sdk.NewCoin("stake", sdk.NewInt(10))).String()), + fmt.Sprintf("--%s=%s", flags.FlagFees, sdk.NewCoins(sdk.NewCoin("stake", math.NewInt(10))).String()), fmt.Sprintf("--%s=true", flags.FlagGenerateOnly), ) s.Require().NoError(err) @@ -729,11 +733,11 @@ func (s *CLITestSuite) TestSignBatchMultisig() { addr, s.val, sdk.NewCoins( - sdk.NewCoin("stake", sdk.NewInt(1)), + sdk.NewCoin("stake", math.NewInt(1)), ), fmt.Sprintf("--%s=true", flags.FlagSkipConfirmation), fmt.Sprintf("--%s=%s", flags.FlagBroadcastMode, flags.BroadcastSync), - fmt.Sprintf("--%s=%s", flags.FlagFees, sdk.NewCoins(sdk.NewCoin("stake", sdk.NewInt(10))).String()), + fmt.Sprintf("--%s=%s", flags.FlagFees, sdk.NewCoins(sdk.NewCoin("stake", math.NewInt(10))).String()), fmt.Sprintf("--%s=true", flags.FlagGenerateOnly), ) s.Require().NoError(err) @@ -788,9 +792,9 @@ func (s *CLITestSuite) TestGetBroadcastCommandWithoutOfflineFlag() { // Create new file with tx builder := txCfg.NewTxBuilder() builder.SetGasLimit(200000) - from, err := sdk.AccAddressFromBech32("cosmos1cxlt8kznps92fwu3j6npahx4mjfutydyene2qw") + from, err := s.ac.StringToBytes("cosmos1cxlt8kznps92fwu3j6npahx4mjfutydyene2qw") s.Require().NoError(err) - to, err := sdk.AccAddressFromBech32("cosmos1cxlt8kznps92fwu3j6npahx4mjfutydyene2qw") + to, err := s.ac.StringToBytes("cosmos1cxlt8kznps92fwu3j6npahx4mjfutydyene2qw") s.Require().NoError(err) err = builder.SetMsgs(banktypes.NewMsgSend(from, to, sdk.Coins{sdk.NewInt64Coin("stake", 10000)})) s.Require().NoError(err) @@ -852,11 +856,11 @@ func (s *CLITestSuite) TestTxWithoutPublicKey() { // Create a txBuilder with an unsigned tx. txBuilder := txCfg.NewTxBuilder() msg := banktypes.NewMsgSend(s.val, s.val, sdk.NewCoins( - sdk.NewCoin("Stake", sdk.NewInt(10)), + sdk.NewCoin("Stake", math.NewInt(10)), )) err := txBuilder.SetMsgs(msg) s.Require().NoError(err) - txBuilder.SetFeeAmount(sdk.NewCoins(sdk.NewCoin("Stake", sdk.NewInt(150)))) + txBuilder.SetFeeAmount(sdk.NewCoins(sdk.NewCoin("Stake", math.NewInt(150)))) txBuilder.SetGasLimit(testdata.NewTestGasLimit()) // Create a file with the unsigned tx. @@ -898,8 +902,8 @@ func (s *CLITestSuite) TestTxWithoutPublicKey() { // transaction to the blockchain. func (s *CLITestSuite) TestSignWithMultiSignersAminoJSON() { val0, val1 := s.val, s.val1 - val0Coin := sdk.NewCoin("test1token", sdk.NewInt(10)) - val1Coin := sdk.NewCoin("test2token", sdk.NewInt(10)) + val0Coin := sdk.NewCoin("test1token", math.NewInt(10)) + val1Coin := sdk.NewCoin("test2token", math.NewInt(10)) _, _, addr1 := testdata.KeyTestPubAddr() // Creating a tx with 2 msgs from 2 signers: val0 and val1. @@ -911,7 +915,7 @@ func (s *CLITestSuite) TestSignWithMultiSignersAminoJSON() { banktypes.NewMsgSend(val0, addr1, sdk.NewCoins(val0Coin)), banktypes.NewMsgSend(val1, addr1, sdk.NewCoins(val1Coin)), ) - txBuilder.SetFeeAmount(sdk.NewCoins(sdk.NewCoin("stake", sdk.NewInt(10)))) + txBuilder.SetFeeAmount(sdk.NewCoins(sdk.NewCoin("stake", math.NewInt(10)))) txBuilder.SetGasLimit(testdata.NewTestGasLimit() * 2) s.Require().Equal([]sdk.AccAddress{val0, val1}, txBuilder.GetTx().GetSigners()) @@ -957,7 +961,7 @@ func (s *CLITestSuite) TestSignWithMultiSignersAminoJSON() { } func (s *CLITestSuite) TestAuxSigner() { - val0Coin := sdk.NewCoin("testtoken", sdk.NewInt(10)) + val0Coin := sdk.NewCoin("testtoken", math.NewInt(10)) testCases := []struct { name string @@ -1022,11 +1026,11 @@ func (s *CLITestSuite) TestAuxToFeeWithTips() { tipper, err := acc.GetAddress() require.NoError(err) - tipperInitialBal := sdk.NewCoin("testtoken", sdk.NewInt(10000)) + tipperInitialBal := sdk.NewCoin("testtoken", math.NewInt(10000)) feePayer := s.val - fee := sdk.NewCoin("stake", sdk.NewInt(1000)) - tip := sdk.NewCoin("testtoken", sdk.NewInt(1000)) + fee := sdk.NewCoin("stake", math.NewInt(1000)) + tip := sdk.NewCoin("testtoken", math.NewInt(1000)) _, err = s.createBankMsg(s.clientCtx, tipper, sdk.NewCoins(tipperInitialBal)) require.NoError(err) @@ -1103,7 +1107,7 @@ func (s *CLITestSuite) TestAuxToFeeWithTips() { name: "--tip flag unset: no error", tipper: tipper, feePayer: feePayer, - tip: sdk.Coin{Denom: "testtoken", Amount: sdk.NewInt(0)}, + tip: sdk.Coin{Denom: "testtoken", Amount: math.NewInt(0)}, tipperArgs: []string{ fmt.Sprintf("--%s=%s", flags.FlagSignMode, flags.SignModeDirectAux), fmt.Sprintf("--%s=true", flags.FlagAux), @@ -1174,7 +1178,7 @@ func (s *CLITestSuite) TestAuxToFeeWithTips() { name: "wrong denom in tip: error", tipper: tipper, feePayer: feePayer, - tip: sdk.Coin{Denom: "testtoken", Amount: sdk.NewInt(0)}, + tip: sdk.Coin{Denom: "testtoken", Amount: math.NewInt(0)}, tipperArgs: []string{ fmt.Sprintf("--%s=%s", flags.FlagTip, "1000wrongDenom"), fmt.Sprintf("--%s=%s", flags.FlagSignMode, flags.SignModeDirectAux), @@ -1193,7 +1197,7 @@ func (s *CLITestSuite) TestAuxToFeeWithTips() { name: "insufficient fees: error", tipper: tipper, feePayer: feePayer, - tip: sdk.Coin{Denom: "testtoken", Amount: sdk.NewInt(0)}, + tip: sdk.Coin{Denom: "testtoken", Amount: math.NewInt(0)}, tipperArgs: []string{ fmt.Sprintf("--%s=%s", flags.FlagTip, tip), fmt.Sprintf("--%s=%s", flags.FlagSignMode, flags.SignModeDirectAux), @@ -1281,7 +1285,7 @@ func (s *CLITestSuite) createBankMsg(clientCtx client.Context, toAddr sdk.AccAdd fmt.Sprintf("--%s=true", flags.FlagSkipConfirmation), fmt.Sprintf("--%s=%s", flags.FlagBroadcastMode, flags.BroadcastSync), fmt.Sprintf("--%s=%s", flags.FlagFees, - sdk.NewCoins(sdk.NewCoin("stake", sdk.NewInt(10))).String()), + sdk.NewCoins(sdk.NewCoin("stake", math.NewInt(10))).String()), } flags = append(flags, extraFlags...) diff --git a/x/auth/client/cli/tx_multisign.go b/x/auth/client/cli/tx_multisign.go index 34349ec858aa..1d1e0b2a5a74 100644 --- a/x/auth/client/cli/tx_multisign.go +++ b/x/auth/client/cli/tx_multisign.go @@ -7,8 +7,13 @@ import ( "github.com/spf13/cobra" "github.com/spf13/viper" + "google.golang.org/protobuf/types/known/anypb" errorsmod "cosmossdk.io/errors" + "cosmossdk.io/x/tx/decode" + txsigning "cosmossdk.io/x/tx/signing" + codectypes "github.com/cosmos/cosmos-sdk/codec/types" + "github.com/cosmos/cosmos-sdk/types/registry" "github.com/cosmos/cosmos-sdk/client" "github.com/cosmos/cosmos-sdk/client/flags" @@ -112,6 +117,11 @@ func makeMultiSignCmd() func(cmd *cobra.Command, args []string) (err error) { txFactory = txFactory.WithAccountNumber(accnum).WithSequence(seq) } + decoder, err := decode.NewDecoder(decode.Options{ProtoFiles: registry.MergedProtoRegistry()}) + if err != nil { + return err + } + // read each signature and add it to the multisig if valid for i := 2; i < len(args); i++ { sigs, err := unmarshalSignatureJSON(clientCtx, args[i]) @@ -124,15 +134,37 @@ func makeMultiSignCmd() func(cmd *cobra.Command, args []string) (err error) { } for _, sig := range sigs { - signingData := signing.SignerData{ - Address: sdk.AccAddress(sig.PubKey.Address()).String(), + anyPk, err := codectypes.NewAnyWithValue(sig.PubKey) + if err != nil { + return err + } + txSignerData := txsigning.SignerData{ ChainID: txFactory.ChainID(), AccountNumber: txFactory.AccountNumber(), Sequence: txFactory.Sequence(), - PubKey: sig.PubKey, + Address: sdk.AccAddress(sig.PubKey.Address()).String(), + PubKey: &anypb.Any{ + TypeUrl: anyPk.TypeUrl, + Value: anyPk.Value, + }, + } + txBytes, err := txCfg.TxEncoder()(txBuilder.GetTx()) + if err != nil { + return err + } + decodedTx, err := decoder.Decode(txBytes) + if err != nil { + return err + } + txData := txsigning.TxData{ + Body: decodedTx.Tx.Body, + AuthInfo: decodedTx.Tx.AuthInfo, + AuthInfoBytes: decodedTx.TxRaw.AuthInfoBytes, + BodyBytes: decodedTx.TxRaw.BodyBytes, } - err = signing.VerifySignature(cmd.Context(), sig.PubKey, signingData, sig.Data, txCfg.SignModeHandler(), txBuilder.GetTx()) + err = signing.VerifySignature(cmd.Context(), sig.PubKey, txSignerData, sig.Data, + txCfg.SignModeHandler(), txData) if err != nil { addr, _ := sdk.AccAddressFromHexUnsafe(sig.PubKey.Address().String()) return fmt.Errorf("couldn't verify signature for address %s", addr) @@ -295,16 +327,43 @@ func makeBatchMultisignCmd() func(cmd *cobra.Command, args []string) error { } multisigPub := pubKey.(*kmultisig.LegacyAminoPubKey) multisigSig := multisig.NewMultisig(len(multisigPub.PubKeys)) - signingData := signing.SignerData{ - Address: sdk.AccAddress(pubKey.Address()).String(), + + anyPk, err := codectypes.NewAnyWithValue(multisigPub) + if err != nil { + return err + } + txSignerData := txsigning.SignerData{ ChainID: txFactory.ChainID(), AccountNumber: txFactory.AccountNumber(), Sequence: txFactory.Sequence(), - PubKey: pubKey, + Address: sdk.AccAddress(pubKey.Address()).String(), + PubKey: &anypb.Any{ + TypeUrl: anyPk.TypeUrl, + Value: anyPk.Value, + }, } + txBytes, err := txCfg.TxEncoder()(txBldr.GetTx()) + if err != nil { + return err + } + decodeCtx, err := decode.NewDecoder(decode.Options{ProtoFiles: registry.MergedProtoRegistry()}) + if err != nil { + return err + } + decodedTx, err := decodeCtx.Decode(txBytes) + if err != nil { + return err + } + txData := txsigning.TxData{ + Body: decodedTx.Tx.Body, + AuthInfo: decodedTx.Tx.AuthInfo, + AuthInfoBytes: decodedTx.TxRaw.AuthInfoBytes, + BodyBytes: decodedTx.TxRaw.BodyBytes, + } for _, sig := range signatureBatch { - err = signing.VerifySignature(cmd.Context(), sig[i].PubKey, signingData, sig[i].Data, txCfg.SignModeHandler(), txBldr.GetTx()) + err = signing.VerifySignature(cmd.Context(), sig[i].PubKey, txSignerData, sig[i].Data, + txCfg.SignModeHandler(), txData) if err != nil { return fmt.Errorf("couldn't verify signature: %w %v", err, sig) } diff --git a/x/auth/client/cli/validate_sigs.go b/x/auth/client/cli/validate_sigs.go index 6a0b8156c7ff..a38283fd2d51 100644 --- a/x/auth/client/cli/validate_sigs.go +++ b/x/auth/client/cli/validate_sigs.go @@ -4,11 +4,16 @@ import ( "fmt" "github.com/spf13/cobra" + "google.golang.org/protobuf/types/known/anypb" + "cosmossdk.io/x/tx/decode" + txsigning "cosmossdk.io/x/tx/signing" "github.com/cosmos/cosmos-sdk/client" "github.com/cosmos/cosmos-sdk/client/flags" "github.com/cosmos/cosmos-sdk/client/tx" + codectypes "github.com/cosmos/cosmos-sdk/codec/types" sdk "github.com/cosmos/cosmos-sdk/types" + "github.com/cosmos/cosmos-sdk/types/registry" authclient "github.com/cosmos/cosmos-sdk/x/auth/client" authsigning "github.com/cosmos/cosmos-sdk/x/auth/signing" ) @@ -111,9 +116,47 @@ func printAndValidateSigs( Sequence: accSeq, PubKey: pubKey, } + anyPk, err := codectypes.NewAnyWithValue(pubKey) + if err != nil { + cmd.PrintErrf("failed to pack public key: %v", err) + return false + } + txSignerData := txsigning.SignerData{ + ChainID: signingData.ChainID, + AccountNumber: signingData.AccountNumber, + Sequence: signingData.Sequence, + Address: signingData.Address, + PubKey: &anypb.Any{ + TypeUrl: anyPk.TypeUrl, + Value: anyPk.Value, + }, + } + + txBytes, err := clientCtx.TxConfig.TxEncoder()(tx) + if err != nil { + cmd.PrintErrf("failed to encode transaction: %v", err) + return false + } + decodeCtx, err := decode.NewDecoder(decode.Options{ProtoFiles: registry.MergedProtoRegistry()}) + if err != nil { + cmd.PrintErrf("failed to create decoder: %v", err) + return false + } + decodedTx, err := decodeCtx.Decode(txBytes) + if err != nil { + cmd.PrintErrf("failed to decode transaction: %v", err) + return false + } + txData := txsigning.TxData{ + Body: decodedTx.Tx.Body, + AuthInfo: decodedTx.Tx.AuthInfo, + AuthInfoBytes: decodedTx.TxRaw.AuthInfoBytes, + BodyBytes: decodedTx.TxRaw.BodyBytes, + } - err = authsigning.VerifySignature(cmd.Context(), pubKey, signingData, sig.Data, signModeHandler, sigTx) + err = authsigning.VerifySignature(cmd.Context(), pubKey, txSignerData, sig.Data, signModeHandler, txData) if err != nil { + cmd.PrintErrf("failed to verify signature: %v", err) return false } } diff --git a/x/auth/client/testutil/helpers.go b/x/auth/client/testutil/helpers.go index cbaff7f77a0f..5d53a35c09e8 100644 --- a/x/auth/client/testutil/helpers.go +++ b/x/auth/client/testutil/helpers.go @@ -4,8 +4,7 @@ import ( "fmt" "strings" - cmtcli "github.com/cometbft/cometbft/libs/cli" - + "cosmossdk.io/core/address" "github.com/cosmos/cosmos-sdk/client" "github.com/cosmos/cosmos-sdk/client/flags" "github.com/cosmos/cosmos-sdk/crypto/keyring" @@ -23,7 +22,7 @@ func TxSignExec(clientCtx client.Context, from fmt.Stringer, filename string, ex } cmd := cli.GetSignCommand() - cmtcli.PrepareBaseCmd(cmd, "", "") + cmd.PersistentFlags().String(flags.FlagHome, clientCtx.HomeDir, "directory for config and data") return clitestutil.ExecTestCLICmd(clientCtx, cmd, append(args, extraArgs...)) } @@ -54,7 +53,7 @@ func TxValidateSignaturesExec(clientCtx client.Context, filename string) (testut return clitestutil.ExecTestCLICmd(clientCtx, cli.GetValidateSignaturesCommand(), args) } -func TxMultiSignExec(clientCtx client.Context, from string, filename string, extraArgs ...string) (testutil.BufferWriter, error) { +func TxMultiSignExec(clientCtx client.Context, from, filename string, extraArgs ...string) (testutil.BufferWriter, error) { args := []string{ fmt.Sprintf("--%s=%s", flags.FlagChainID, clientCtx.ChainID), filename, @@ -91,13 +90,13 @@ func TxAuxToFeeExec(clientCtx client.Context, filename string, extraArgs ...stri return clitestutil.ExecTestCLICmd(clientCtx, cli.GetAuxToFeeCommand(), append(args, extraArgs...)) } -func QueryAccountExec(clientCtx client.Context, address fmt.Stringer, extraArgs ...string) (testutil.BufferWriter, error) { - args := []string{address.String(), fmt.Sprintf("--%s=json", cmtcli.OutputFlag)} +func QueryAccountExec(clientCtx client.Context, address fmt.Stringer, ac address.Codec, extraArgs ...string) (testutil.BufferWriter, error) { + args := []string{address.String(), fmt.Sprintf("--%s=json", flags.FlagOutput)} - return clitestutil.ExecTestCLICmd(clientCtx, cli.GetAccountCmd(), append(args, extraArgs...)) + return clitestutil.ExecTestCLICmd(clientCtx, cli.GetAccountCmd(ac), append(args, extraArgs...)) } -func TxMultiSignBatchExec(clientCtx client.Context, filename string, from string, sigFile1 string, sigFile2 string, extraArgs ...string) (testutil.BufferWriter, error) { +func TxMultiSignBatchExec(clientCtx client.Context, filename, from, sigFile1, sigFile2 string, extraArgs ...string) (testutil.BufferWriter, error) { args := []string{ fmt.Sprintf("--%s=%s", flags.FlagKeyringBackend, keyring.BackendTest), filename, diff --git a/x/auth/keeper/account.go b/x/auth/keeper/account.go index 80d0a1f77b31..5336ecbec4e6 100644 --- a/x/auth/keeper/account.go +++ b/x/auth/keeper/account.go @@ -1,6 +1,8 @@ package keeper import ( + "context" + storetypes "cosmossdk.io/store/types" sdk "github.com/cosmos/cosmos-sdk/types" @@ -8,7 +10,7 @@ import ( ) // NewAccountWithAddress implements AccountKeeperI. -func (ak AccountKeeper) NewAccountWithAddress(ctx sdk.Context, addr sdk.AccAddress) sdk.AccountI { +func (ak AccountKeeper) NewAccountWithAddress(ctx context.Context, addr sdk.AccAddress) sdk.AccountI { acc := ak.proto() err := acc.SetAddress(addr) if err != nil { @@ -19,7 +21,7 @@ func (ak AccountKeeper) NewAccountWithAddress(ctx sdk.Context, addr sdk.AccAddre } // NewAccount sets the next account number to a given account interface -func (ak AccountKeeper) NewAccount(ctx sdk.Context, acc sdk.AccountI) sdk.AccountI { +func (ak AccountKeeper) NewAccount(ctx context.Context, acc sdk.AccountI) sdk.AccountI { if err := acc.SetAccountNumber(ak.NextAccountNumber(ctx)); err != nil { panic(err) } @@ -28,21 +30,33 @@ func (ak AccountKeeper) NewAccount(ctx sdk.Context, acc sdk.AccountI) sdk.Accoun } // HasAccount implements AccountKeeperI. -func (ak AccountKeeper) HasAccount(ctx sdk.Context, addr sdk.AccAddress) bool { - store := ctx.KVStore(ak.storeKey) - return store.Has(types.AddressStoreKey(addr)) +func (ak AccountKeeper) HasAccount(ctx context.Context, addr sdk.AccAddress) bool { + store := ak.storeService.OpenKVStore(ctx) + has, err := store.Has(types.AddressStoreKey(addr)) + if err != nil { + panic(err) + } + return has } // HasAccountAddressByID checks account address exists by id. -func (ak AccountKeeper) HasAccountAddressByID(ctx sdk.Context, id uint64) bool { - store := ctx.KVStore(ak.storeKey) - return store.Has(types.AccountNumberStoreKey(id)) +func (ak AccountKeeper) HasAccountAddressByID(ctx context.Context, id uint64) bool { + store := ak.storeService.OpenKVStore(ctx) + has, err := store.Has(types.AccountNumberStoreKey(id)) + if err != nil { + panic(err) + } + return has } // GetAccount implements AccountKeeperI. -func (ak AccountKeeper) GetAccount(ctx sdk.Context, addr sdk.AccAddress) sdk.AccountI { - store := ctx.KVStore(ak.storeKey) - bz := store.Get(types.AddressStoreKey(addr)) +func (ak AccountKeeper) GetAccount(ctx context.Context, addr sdk.AccAddress) sdk.AccountI { + store := ak.storeService.OpenKVStore(ctx) + bz, err := store.Get(types.AddressStoreKey(addr)) + if err != nil { + panic(err) + } + if bz == nil { return nil } @@ -51,9 +65,13 @@ func (ak AccountKeeper) GetAccount(ctx sdk.Context, addr sdk.AccAddress) sdk.Acc } // GetAccountAddressById returns account address by id. -func (ak AccountKeeper) GetAccountAddressByID(ctx sdk.Context, id uint64) string { - store := ctx.KVStore(ak.storeKey) - bz := store.Get(types.AccountNumberStoreKey(id)) +func (ak AccountKeeper) GetAccountAddressByID(ctx context.Context, id uint64) string { + store := ak.storeService.OpenKVStore(ctx) + bz, err := store.Get(types.AccountNumberStoreKey(id)) + if err != nil { + panic(err) + } + if bz == nil { return "" } @@ -61,7 +79,7 @@ func (ak AccountKeeper) GetAccountAddressByID(ctx sdk.Context, id uint64) string } // GetAllAccounts returns all accounts in the accountKeeper. -func (ak AccountKeeper) GetAllAccounts(ctx sdk.Context) (accounts []sdk.AccountI) { +func (ak AccountKeeper) GetAllAccounts(ctx context.Context) (accounts []sdk.AccountI) { ak.IterateAccounts(ctx, func(acc sdk.AccountI) (stop bool) { accounts = append(accounts, acc) return false @@ -71,9 +89,9 @@ func (ak AccountKeeper) GetAllAccounts(ctx sdk.Context) (accounts []sdk.AccountI } // SetAccount implements AccountKeeperI. -func (ak AccountKeeper) SetAccount(ctx sdk.Context, acc sdk.AccountI) { +func (ak AccountKeeper) SetAccount(ctx context.Context, acc sdk.AccountI) { addr := acc.GetAddress() - store := ctx.KVStore(ak.storeKey) + store := ak.storeService.OpenKVStore(ctx) bz, err := ak.MarshalAccount(acc) if err != nil { @@ -86,18 +104,28 @@ func (ak AccountKeeper) SetAccount(ctx sdk.Context, acc sdk.AccountI) { // RemoveAccount removes an account for the account mapper store. // NOTE: this will cause supply invariant violation if called -func (ak AccountKeeper) RemoveAccount(ctx sdk.Context, acc sdk.AccountI) { +func (ak AccountKeeper) RemoveAccount(ctx context.Context, acc sdk.AccountI) { addr := acc.GetAddress() - store := ctx.KVStore(ak.storeKey) - store.Delete(types.AddressStoreKey(addr)) - store.Delete(types.AccountNumberStoreKey(acc.GetAccountNumber())) + store := ak.storeService.OpenKVStore(ctx) + err := store.Delete(types.AddressStoreKey(addr)) + if err != nil { + panic(err) + } + + err = store.Delete(types.AccountNumberStoreKey(acc.GetAccountNumber())) + if err != nil { + panic(err) + } } // IterateAccounts iterates over all the stored accounts and performs a callback function. // Stops iteration when callback returns true. -func (ak AccountKeeper) IterateAccounts(ctx sdk.Context, cb func(account sdk.AccountI) (stop bool)) { - store := ctx.KVStore(ak.storeKey) - iterator := storetypes.KVStorePrefixIterator(store, types.AddressStoreKeyPrefix) +func (ak AccountKeeper) IterateAccounts(ctx context.Context, cb func(account sdk.AccountI) (stop bool)) { + store := ak.storeService.OpenKVStore(ctx) + iterator, err := store.Iterator(types.AddressStoreKeyPrefix, storetypes.PrefixEndBytes(types.AddressStoreKeyPrefix)) + if err != nil { + panic(err) + } defer iterator.Close() for ; iterator.Valid(); iterator.Next() { diff --git a/x/auth/keeper/bech32_codec.go b/x/auth/keeper/bech32_codec.go index fa0734efeba5..926dd45f6b67 100644 --- a/x/auth/keeper/bech32_codec.go +++ b/x/auth/keeper/bech32_codec.go @@ -1,6 +1,9 @@ package keeper import ( + "errors" + "strings" + "cosmossdk.io/core/address" errorsmod "cosmossdk.io/errors" @@ -21,6 +24,10 @@ func NewBech32Codec(prefix string) address.Codec { // StringToBytes encodes text to bytes func (bc bech32Codec) StringToBytes(text string) ([]byte, error) { + if len(strings.TrimSpace(text)) == 0 { + return []byte{}, errors.New("empty address string is not allowed") + } + hrp, bz, err := bech32.DecodeAndConvert(text) if err != nil { return nil, err diff --git a/x/auth/keeper/deterministic_test.go b/x/auth/keeper/deterministic_test.go index 829d28286fc7..ea7e6b64d3bb 100644 --- a/x/auth/keeper/deterministic_test.go +++ b/x/auth/keeper/deterministic_test.go @@ -5,13 +5,16 @@ import ( "sort" "testing" - storetypes "cosmossdk.io/store/types" cmtproto "github.com/cometbft/cometbft/proto/tendermint/types" "github.com/stretchr/testify/suite" "pgregory.net/rapid" + corestore "cosmossdk.io/core/store" + storetypes "cosmossdk.io/store/types" + "github.com/cosmos/cosmos-sdk/baseapp" "github.com/cosmos/cosmos-sdk/crypto/keys/secp256k1" + "github.com/cosmos/cosmos-sdk/runtime" "github.com/cosmos/cosmos-sdk/testutil" "github.com/cosmos/cosmos-sdk/testutil/testdata" sdk "github.com/cosmos/cosmos-sdk/types" @@ -25,6 +28,7 @@ type DeterministicTestSuite struct { suite.Suite key *storetypes.KVStoreKey + storeService corestore.KVStoreService ctx sdk.Context queryClient types.QueryClient accountKeeper keeper.AccountKeeper @@ -47,6 +51,7 @@ func (suite *DeterministicTestSuite) SetupTest() { suite.Require() key := storetypes.NewKVStoreKey(types.StoreKey) + storeService := runtime.NewKVStoreService(key) testCtx := testutil.DefaultContextWithDB(suite.T(), key, storetypes.NewTransientStoreKey("transient_test")) suite.ctx = testCtx.Ctx.WithBlockHeader(cmtproto.Header{}) @@ -61,7 +66,7 @@ func (suite *DeterministicTestSuite) SetupTest() { suite.accountKeeper = keeper.NewAccountKeeper( suite.encCfg.Codec, - key, + storeService, types.ProtoBaseAccount, maccPerms, "cosmos", @@ -73,6 +78,7 @@ func (suite *DeterministicTestSuite) SetupTest() { suite.queryClient = types.NewQueryClient(queryHelper) suite.key = key + suite.storeService = storeService suite.maccPerms = maccPerms } @@ -139,7 +145,7 @@ func (suite *DeterministicTestSuite) TestGRPCQueryAccounts() { }) // Regression test - addr1, err := sdk.AccAddressFromBech32("cosmos1892yr6fzlj7ud0kfkah2ctrav3a4p4n060ze8f") + addr1, err := suite.accountKeeper.GetAddressCodec().StringToBytes("cosmos1892yr6fzlj7ud0kfkah2ctrav3a4p4n060ze8f") suite.Require().NoError(err) pub1, err := hex.DecodeString("D1002E1B019000010BB7034500E71F011F1CA90D5B000E134BFB0F3603030D0303") suite.Require().NoError(err) @@ -280,7 +286,7 @@ func (suite *DeterministicTestSuite) TestGRPCQueryModuleAccounts() { ak := keeper.NewAccountKeeper( suite.encCfg.Codec, - suite.key, + suite.storeService, types.ProtoBaseAccount, maccPerms, "cosmos", @@ -326,7 +332,7 @@ func (suite *DeterministicTestSuite) TestGRPCQueryModuleAccountByName() { ak := keeper.NewAccountKeeper( suite.encCfg.Codec, - suite.key, + suite.storeService, types.ProtoBaseAccount, maccPerms, "cosmos", diff --git a/x/auth/keeper/grpc_query.go b/x/auth/keeper/grpc_query.go index f8e51411eca1..482890de7a51 100644 --- a/x/auth/keeper/grpc_query.go +++ b/x/auth/keeper/grpc_query.go @@ -8,6 +8,7 @@ import ( "cosmossdk.io/store/prefix" + "github.com/cosmos/cosmos-sdk/runtime" "github.com/cosmos/cosmos-sdk/types/query" "google.golang.org/grpc/codes" @@ -40,14 +41,13 @@ func (ak AccountKeeper) AccountAddressByID(c context.Context, req *types.QueryAc return &types.QueryAccountAddressByIDResponse{AccountAddress: address}, nil } -func (ak AccountKeeper) Accounts(c context.Context, req *types.QueryAccountsRequest) (*types.QueryAccountsResponse, error) { +func (ak AccountKeeper) Accounts(ctx context.Context, req *types.QueryAccountsRequest) (*types.QueryAccountsResponse, error) { if req == nil { return nil, status.Error(codes.InvalidArgument, "empty request") } - ctx := sdk.UnwrapSDKContext(c) - store := ctx.KVStore(ak.storeKey) - accountsStore := prefix.NewStore(store, types.AddressStoreKeyPrefix) + store := ak.storeService.OpenKVStore(ctx) + accountsStore := prefix.NewStore(runtime.KVStoreAdapter(store), types.AddressStoreKeyPrefix) var accounts []*codectypes.Any pageRes, err := query.Paginate(accountsStore, req.Pagination, func(key, value []byte) error { @@ -78,7 +78,7 @@ func (ak AccountKeeper) Account(c context.Context, req *types.QueryAccountReques } ctx := sdk.UnwrapSDKContext(c) - addr, err := sdk.AccAddressFromBech32(req.Address) + addr, err := ak.addressCdc.StringToBytes(req.Address) if err != nil { return nil, err } @@ -222,7 +222,7 @@ func (ak AccountKeeper) AccountInfo(goCtx context.Context, req *types.QueryAccou } ctx := sdk.UnwrapSDKContext(goCtx) - addr, err := sdk.AccAddressFromBech32(req.Address) + addr, err := ak.addressCdc.StringToBytes(req.Address) if err != nil { return nil, err } @@ -239,7 +239,7 @@ func (ak AccountKeeper) AccountInfo(goCtx context.Context, req *types.QueryAccou return &types.QueryAccountInfoResponse{ Info: &types.BaseAccount{ - Address: addr.String(), + Address: req.Address, PubKey: pkAny, AccountNumber: account.GetAccountNumber(), Sequence: account.GetSequence(), diff --git a/x/auth/keeper/keeper.go b/x/auth/keeper/keeper.go index d3b862e7cfee..e5db0183bb70 100644 --- a/x/auth/keeper/keeper.go +++ b/x/auth/keeper/keeper.go @@ -1,14 +1,16 @@ package keeper import ( + "context" + "errors" "fmt" - "cosmossdk.io/log" - gogotypes "github.com/cosmos/gogoproto/types" + "cosmossdk.io/collections" "cosmossdk.io/core/address" + "cosmossdk.io/core/store" errorsmod "cosmossdk.io/errors" - storetypes "cosmossdk.io/store/types" + "cosmossdk.io/log" "github.com/cosmos/cosmos-sdk/codec" cryptotypes "github.com/cosmos/cosmos-sdk/crypto/types" @@ -20,34 +22,34 @@ import ( // AccountKeeperI is the interface contract that x/auth's keeper implements. type AccountKeeperI interface { // Return a new account with the next account number and the specified address. Does not save the new account to the store. - NewAccountWithAddress(sdk.Context, sdk.AccAddress) sdk.AccountI + NewAccountWithAddress(context.Context, sdk.AccAddress) sdk.AccountI // Return a new account with the next account number. Does not save the new account to the store. - NewAccount(sdk.Context, sdk.AccountI) sdk.AccountI + NewAccount(context.Context, sdk.AccountI) sdk.AccountI // Check if an account exists in the store. - HasAccount(sdk.Context, sdk.AccAddress) bool + HasAccount(context.Context, sdk.AccAddress) bool // Retrieve an account from the store. - GetAccount(sdk.Context, sdk.AccAddress) sdk.AccountI + GetAccount(context.Context, sdk.AccAddress) sdk.AccountI // Set an account in the store. - SetAccount(sdk.Context, sdk.AccountI) + SetAccount(context.Context, sdk.AccountI) // Remove an account from the store. - RemoveAccount(sdk.Context, sdk.AccountI) + RemoveAccount(context.Context, sdk.AccountI) // Iterate over all accounts, calling the provided function. Stop iteration when it returns true. - IterateAccounts(sdk.Context, func(sdk.AccountI) bool) + IterateAccounts(context.Context, func(sdk.AccountI) bool) // Fetch the public key of an account at a specified address - GetPubKey(sdk.Context, sdk.AccAddress) (cryptotypes.PubKey, error) + GetPubKey(context.Context, sdk.AccAddress) (cryptotypes.PubKey, error) // Fetch the sequence of an account at a specified address. - GetSequence(sdk.Context, sdk.AccAddress) (uint64, error) + GetSequence(context.Context, sdk.AccAddress) (uint64, error) // Fetch the next account number, and increment the internal counter. - NextAccountNumber(sdk.Context) uint64 + NextAccountNumber(context.Context) uint64 // GetModulePermissions fetches per-module account permissions GetModulePermissions() map[string]types.PermissionsForAddress @@ -56,9 +58,9 @@ type AccountKeeperI interface { // AccountKeeper encodes/decodes accounts using the go-amino (binary) // encoding/decoding library. type AccountKeeper struct { - storeKey storetypes.StoreKey - cdc codec.BinaryCodec - permAddrs map[string]types.PermissionsForAddress + storeService store.KVStoreService + cdc codec.BinaryCodec + permAddrs map[string]types.PermissionsForAddress // The prototypical AccountI constructor. proto func() sdk.AccountI @@ -67,6 +69,11 @@ type AccountKeeper struct { // the address capable of executing a MsgUpdateParams message. Typically, this // should be the x/gov module account. authority string + + // State + + ParamsState collections.Item[types.Params] // NOTE: name is this because it conflicts with the Params gRPC method impl + AccountNumber collections.Sequence } var _ AccountKeeperI = &AccountKeeper{} @@ -78,8 +85,8 @@ var _ AccountKeeperI = &AccountKeeper{} // and don't have to fit into any predefined structure. This auth module does not use account permissions internally, though other modules // may use auth.Keeper to access the accounts permissions map. func NewAccountKeeper( - cdc codec.BinaryCodec, storeKey storetypes.StoreKey, proto func() sdk.AccountI, - maccPerms map[string][]string, bech32Prefix string, authority string, + cdc codec.BinaryCodec, storeService store.KVStoreService, proto func() sdk.AccountI, + maccPerms map[string][]string, bech32Prefix, authority string, ) AccountKeeper { permAddrs := make(map[string]types.PermissionsForAddress) for name, perms := range maccPerms { @@ -88,13 +95,17 @@ func NewAccountKeeper( bech32Codec := NewBech32Codec(bech32Prefix) + sb := collections.NewSchemaBuilder(storeService) + return AccountKeeper{ - storeKey: storeKey, - proto: proto, - cdc: cdc, - permAddrs: permAddrs, - addressCdc: bech32Codec, - authority: authority, + storeService: storeService, + proto: proto, + cdc: cdc, + permAddrs: permAddrs, + addressCdc: bech32Codec, + authority: authority, + ParamsState: collections.NewItem(sb, types.ParamsKey, "params", codec.CollValue[types.Params](cdc)), + AccountNumber: collections.NewSequence(sb, types.GlobalAccountNumberKey, "account_number"), } } @@ -110,12 +121,12 @@ func (ak AccountKeeper) GetAddressCodec() address.Codec { } // Logger returns a module-specific logger. -func (ak AccountKeeper) Logger(ctx sdk.Context) log.Logger { - return ctx.Logger().With("module", "x/"+types.ModuleName) +func (ak AccountKeeper) Logger(ctx context.Context) log.Logger { + return sdk.UnwrapSDKContext(ctx).Logger().With("module", "x/"+types.ModuleName) } // GetPubKey Returns the PubKey of the account at address -func (ak AccountKeeper) GetPubKey(ctx sdk.Context, addr sdk.AccAddress) (cryptotypes.PubKey, error) { +func (ak AccountKeeper) GetPubKey(ctx context.Context, addr sdk.AccAddress) (cryptotypes.PubKey, error) { acc := ak.GetAccount(ctx, addr) if acc == nil { return nil, errorsmod.Wrapf(sdkerrors.ErrUnknownAddress, "account %s does not exist", addr) @@ -125,7 +136,7 @@ func (ak AccountKeeper) GetPubKey(ctx sdk.Context, addr sdk.AccAddress) (cryptot } // GetSequence Returns the Sequence of the account at address -func (ak AccountKeeper) GetSequence(ctx sdk.Context, addr sdk.AccAddress) (uint64, error) { +func (ak AccountKeeper) GetSequence(ctx context.Context, addr sdk.AccAddress) (uint64, error) { acc := ak.GetAccount(ctx, addr) if acc == nil { return 0, errorsmod.Wrapf(sdkerrors.ErrUnknownAddress, "account %s does not exist", addr) @@ -136,29 +147,12 @@ func (ak AccountKeeper) GetSequence(ctx sdk.Context, addr sdk.AccAddress) (uint6 // NextAccountNumber returns and increments the global account number counter. // If the global account number is not set, it initializes it with value 0. -func (ak AccountKeeper) NextAccountNumber(ctx sdk.Context) uint64 { - var accNumber uint64 - store := ctx.KVStore(ak.storeKey) - - bz := store.Get(types.GlobalAccountNumberKey) - if bz == nil { - // initialize the account numbers - accNumber = 0 - } else { - val := gogotypes.UInt64Value{} - - err := ak.cdc.Unmarshal(bz, &val) - if err != nil { - panic(err) - } - - accNumber = val.GetValue() +func (ak AccountKeeper) NextAccountNumber(ctx context.Context) uint64 { + n, err := ak.AccountNumber.Next(ctx) + if err != nil { + panic(err) } - - bz = ak.cdc.MustMarshal(&gogotypes.UInt64Value{Value: accNumber + 1}) - store.Set(types.GlobalAccountNumberKey, bz) - - return accNumber + return n } // GetModulePermissions fetches per-module account permissions. @@ -201,7 +195,7 @@ func (ak AccountKeeper) GetModuleAddressAndPermissions(moduleName string) (addr // GetModuleAccountAndPermissions gets the module account from the auth account store and its // registered permissions -func (ak AccountKeeper) GetModuleAccountAndPermissions(ctx sdk.Context, moduleName string) (sdk.ModuleAccountI, []string) { +func (ak AccountKeeper) GetModuleAccountAndPermissions(ctx context.Context, moduleName string) (sdk.ModuleAccountI, []string) { addr, perms := ak.GetModuleAddressAndPermissions(moduleName) if addr == nil { return nil, []string{} @@ -226,13 +220,13 @@ func (ak AccountKeeper) GetModuleAccountAndPermissions(ctx sdk.Context, moduleNa // GetModuleAccount gets the module account from the auth account store, if the account does not // exist in the AccountKeeper, then it is created. -func (ak AccountKeeper) GetModuleAccount(ctx sdk.Context, moduleName string) sdk.ModuleAccountI { +func (ak AccountKeeper) GetModuleAccount(ctx context.Context, moduleName string) sdk.ModuleAccountI { acc, _ := ak.GetModuleAccountAndPermissions(ctx, moduleName) return acc } // SetModuleAccount sets the module account to the auth account store -func (ak AccountKeeper) SetModuleAccount(ctx sdk.Context, macc sdk.ModuleAccountI) { +func (ak AccountKeeper) SetModuleAccount(ctx context.Context, macc sdk.ModuleAccountI) { ak.SetAccount(ctx, macc) } @@ -246,7 +240,7 @@ func (ak AccountKeeper) decodeAccount(bz []byte) sdk.AccountI { } // MarshalAccount protobuf serializes an Account interface -func (ak AccountKeeper) MarshalAccount(accountI sdk.AccountI) ([]byte, error) { //nolint:interfacer +func (ak AccountKeeper) MarshalAccount(accountI sdk.AccountI) ([]byte, error) { return ak.cdc.MarshalInterface(accountI) } @@ -269,3 +263,18 @@ func (ak AccountKeeper) getBech32Prefix() (string, error) { return bech32Codec.bech32Prefix, nil } + +// SetParams sets the auth module's parameters. +// CONTRACT: This method performs no validation of the parameters. +func (ak AccountKeeper) SetParams(ctx context.Context, params types.Params) error { + return ak.ParamsState.Set(ctx, params) +} + +// GetParams gets the auth module's parameters. +func (ak AccountKeeper) GetParams(ctx context.Context) (params types.Params) { + params, err := ak.ParamsState.Get(ctx) + if err != nil && !errors.Is(err, collections.ErrNotFound) { + panic(err) + } + return params +} diff --git a/x/auth/keeper/keeper_test.go b/x/auth/keeper/keeper_test.go index 94a6744596ff..15be29c04b5d 100644 --- a/x/auth/keeper/keeper_test.go +++ b/x/auth/keeper/keeper_test.go @@ -3,6 +3,8 @@ package keeper_test import ( "testing" + "github.com/cosmos/cosmos-sdk/runtime" + "github.com/stretchr/testify/suite" cmtproto "github.com/cometbft/cometbft/proto/tendermint/types" @@ -46,6 +48,7 @@ func (suite *KeeperTestSuite) SetupTest() { suite.encCfg = moduletestutil.MakeTestEncodingConfig(auth.AppModuleBasic{}) key := storetypes.NewKVStoreKey(types.StoreKey) + storeService := runtime.NewKVStoreService(key) testCtx := testutil.DefaultContextWithDB(suite.T(), key, storetypes.NewTransientStoreKey("transient_test")) suite.ctx = testCtx.Ctx.WithBlockHeader(cmtproto.Header{}) @@ -60,7 +63,7 @@ func (suite *KeeperTestSuite) SetupTest() { suite.accountKeeper = keeper.NewAccountKeeper( suite.encCfg.Codec, - key, + storeService, types.ProtoBaseAccount, maccPerms, "cosmos", diff --git a/x/auth/keeper/migrations.go b/x/auth/keeper/migrations.go index ec2f49512b33..6b363dcf223b 100644 --- a/x/auth/keeper/migrations.go +++ b/x/auth/keeper/migrations.go @@ -8,6 +8,7 @@ import ( v2 "github.com/cosmos/cosmos-sdk/x/auth/migrations/v2" v3 "github.com/cosmos/cosmos-sdk/x/auth/migrations/v3" v4 "github.com/cosmos/cosmos-sdk/x/auth/migrations/v4" + v5 "github.com/cosmos/cosmos-sdk/x/auth/migrations/v5" "github.com/cosmos/cosmos-sdk/x/auth/types" ) @@ -48,7 +49,7 @@ func (m Migrator) Migrate1to2(ctx sdk.Context) error { // Migrate2to3 migrates from consensus version 2 to version 3. Specifically, for each account // we index the account's ID to their address. func (m Migrator) Migrate2to3(ctx sdk.Context) error { - return v3.MigrateStore(ctx, m.keeper.storeKey, m.keeper.cdc) + return v3.MigrateStore(ctx, m.keeper.storeService, m.keeper.cdc) } // Migrate3to4 migrates the x/auth module state from the consensus version 3 to @@ -56,22 +57,28 @@ func (m Migrator) Migrate2to3(ctx sdk.Context) error { // and managed by the x/params modules and stores them directly into the x/auth // module state. func (m Migrator) Migrate3to4(ctx sdk.Context) error { - return v4.Migrate(ctx, ctx.KVStore(m.keeper.storeKey), m.legacySubspace, m.keeper.cdc) + return v4.Migrate(ctx, m.keeper.storeService, m.legacySubspace, m.keeper.cdc) +} + +// Migrate4To5 migrates the x/auth module state from the consensus version 4 to 5. +// It migrates the GlobalAccountNumber from being a protobuf defined value to a +// big-endian encoded uint64, it also migrates it to use a more canonical prefix. +func (m Migrator) Migrate4To5(ctx sdk.Context) error { + return v5.Migrate(ctx, m.keeper.storeService, m.keeper.AccountNumber) } // V45_SetAccount implements V45_SetAccount // set the account without map to accAddr to accNumber. // // NOTE: This is used for testing purposes only. -func (m Migrator) V45_SetAccount(ctx sdk.Context, acc sdk.AccountI) error { //nolint:revive +func (m Migrator) V45SetAccount(ctx sdk.Context, acc sdk.AccountI) error { addr := acc.GetAddress() - store := ctx.KVStore(m.keeper.storeKey) + store := m.keeper.storeService.OpenKVStore(ctx) bz, err := m.keeper.MarshalAccount(acc) if err != nil { return err } - store.Set(types.AddressStoreKey(addr), bz) - return nil + return store.Set(types.AddressStoreKey(addr), bz) } diff --git a/x/auth/keeper/msg_server.go b/x/auth/keeper/msg_server.go index 8a7b324fdb21..78e92680f19c 100644 --- a/x/auth/keeper/msg_server.go +++ b/x/auth/keeper/msg_server.go @@ -23,13 +23,17 @@ func NewMsgServerImpl(ak AccountKeeper) types.MsgServer { } } -func (ms msgServer) UpdateParams(goCtx context.Context, req *types.MsgUpdateParams) (*types.MsgUpdateParamsResponse, error) { - if ms.authority != req.Authority { - return nil, errors.Wrapf(govtypes.ErrInvalidSigner, "invalid authority; expected %s, got %s", ms.authority, req.Authority) +func (ms msgServer) UpdateParams(goCtx context.Context, msg *types.MsgUpdateParams) (*types.MsgUpdateParamsResponse, error) { + if ms.authority != msg.Authority { + return nil, errors.Wrapf(govtypes.ErrInvalidSigner, "invalid authority; expected %s, got %s", ms.authority, msg.Authority) + } + + if err := msg.Params.Validate(); err != nil { + return nil, err } ctx := sdk.UnwrapSDKContext(goCtx) - if err := ms.SetParams(ctx, req.Params); err != nil { + if err := ms.SetParams(ctx, msg.Params); err != nil { return nil, err } diff --git a/x/auth/keeper/params.go b/x/auth/keeper/params.go deleted file mode 100644 index 680f7c1583e2..000000000000 --- a/x/auth/keeper/params.go +++ /dev/null @@ -1,30 +0,0 @@ -package keeper - -import ( - sdk "github.com/cosmos/cosmos-sdk/types" - "github.com/cosmos/cosmos-sdk/x/auth/types" -) - -// SetParams sets the auth module's parameters. -func (ak AccountKeeper) SetParams(ctx sdk.Context, params types.Params) error { - if err := params.Validate(); err != nil { - return err - } - - store := ctx.KVStore(ak.storeKey) - bz := ak.cdc.MustMarshal(¶ms) - store.Set(types.ParamsKey, bz) - - return nil -} - -// GetParams gets the auth module's parameters. -func (ak AccountKeeper) GetParams(ctx sdk.Context) (params types.Params) { - store := ctx.KVStore(ak.storeKey) - bz := store.Get(types.ParamsKey) - if bz == nil { - return params - } - ak.cdc.MustUnmarshal(bz, ¶ms) - return params -} diff --git a/x/auth/keeper/params_test.go b/x/auth/keeper/params_test.go deleted file mode 100644 index 4853fe563482..000000000000 --- a/x/auth/keeper/params_test.go +++ /dev/null @@ -1,92 +0,0 @@ -package keeper_test - -import ( - "github.com/cosmos/cosmos-sdk/x/auth/types" -) - -func (s *KeeperTestSuite) TestParams() { - testCases := []struct { - name string - input types.Params - expectErr bool - expErrMsg string - }{ - { - name: "set invalid max memo characters", - input: types.Params{ - MaxMemoCharacters: 0, - TxSigLimit: 9, - TxSizeCostPerByte: 5, - SigVerifyCostED25519: 694, - SigVerifyCostSecp256k1: 511, - }, - expectErr: true, - expErrMsg: "invalid max memo characters", - }, - { - name: "set invalid tx sig limit", - input: types.Params{ - MaxMemoCharacters: 140, - TxSigLimit: 0, - TxSizeCostPerByte: 5, - SigVerifyCostED25519: 694, - SigVerifyCostSecp256k1: 511, - }, - expectErr: true, - expErrMsg: "invalid tx signature limit", - }, - { - name: "set invalid tx size cost per bytes", - input: types.Params{ - MaxMemoCharacters: 140, - TxSigLimit: 9, - TxSizeCostPerByte: 0, - SigVerifyCostED25519: 694, - SigVerifyCostSecp256k1: 511, - }, - expectErr: true, - expErrMsg: "invalid tx size cost per byte", - }, - { - name: "set invalid sig verify cost ED25519", - input: types.Params{ - MaxMemoCharacters: 140, - TxSigLimit: 9, - TxSizeCostPerByte: 5, - SigVerifyCostED25519: 0, - SigVerifyCostSecp256k1: 511, - }, - expectErr: true, - expErrMsg: "invalid ED25519 signature verification cost", - }, - { - name: "set invalid sig verify cost Secp256k1", - input: types.Params{ - MaxMemoCharacters: 140, - TxSigLimit: 9, - TxSizeCostPerByte: 5, - SigVerifyCostED25519: 694, - SigVerifyCostSecp256k1: 0, - }, - expectErr: true, - expErrMsg: "invalid SECK256k1 signature verification cost", - }, - } - for _, tc := range testCases { - tc := tc - s.Run(tc.name, func() { - expected := s.accountKeeper.GetParams(s.ctx) - err := s.accountKeeper.SetParams(s.ctx, tc.input) - if tc.expectErr { - s.Require().Error(err) - s.Require().Contains(err.Error(), tc.expErrMsg) - } else { - expected = tc.input - s.Require().NoError(err) - } - - params := s.accountKeeper.GetParams(s.ctx) - s.Require().Equal(expected, params) - }) - } -} diff --git a/x/auth/migrations/v2/store_test.go b/x/auth/migrations/v2/store_test.go index eccc71fbe2e2..0663f29f1a3a 100644 --- a/x/auth/migrations/v2/store_test.go +++ b/x/auth/migrations/v2/store_test.go @@ -8,8 +8,10 @@ import ( cmtproto "github.com/cometbft/cometbft/proto/tendermint/types" "github.com/stretchr/testify/require" + sdkmath "cosmossdk.io/math" storetypes "cosmossdk.io/store/types" + "github.com/cosmos/cosmos-sdk/runtime" "github.com/cosmos/cosmos-sdk/testutil" simtestutil "github.com/cosmos/cosmos-sdk/testutil/sims" sdk "github.com/cosmos/cosmos-sdk/types" @@ -24,7 +26,6 @@ import ( "github.com/cosmos/cosmos-sdk/x/auth/vesting/exported" "github.com/cosmos/cosmos-sdk/x/auth/vesting/types" bankkeeper "github.com/cosmos/cosmos-sdk/x/bank/keeper" - "github.com/cosmos/cosmos-sdk/x/staking" stakingkeeper "github.com/cosmos/cosmos-sdk/x/staking/keeper" stakingtypes "github.com/cosmos/cosmos-sdk/x/staking/types" ) @@ -48,7 +49,7 @@ func TestMigrateVestingAccounts(t *testing.T) { storeKey := storetypes.NewKVStoreKey(v1.ModuleName) tKey := storetypes.NewTransientStoreKey("transient_test") ctx := testutil.DefaultContext(storeKey, tKey) - store := ctx.KVStore(storeKey) + storeService := runtime.NewKVStoreService(storeKey) var ( accountKeeper keeper.AccountKeeper @@ -64,7 +65,7 @@ func TestMigrateVestingAccounts(t *testing.T) { require.NoError(t, err) legacySubspace := newMockSubspace(authtypes.DefaultParams()) - require.NoError(t, v4.Migrate(ctx, store, legacySubspace, cdc)) + require.NoError(t, v4.Migrate(ctx, storeService, legacySubspace, cdc)) ctx = app.BaseApp.NewContext(false, cmtproto.Header{Time: time.Now()}) stakingKeeper.SetParams(ctx, stakingtypes.DefaultParams()) @@ -82,7 +83,7 @@ func TestMigrateVestingAccounts(t *testing.T) { "delayed vesting has vested, multiple delegations less than the total account balance", func(ctx sdk.Context, validator stakingtypes.Validator, delegatorAddr sdk.AccAddress) { baseAccount := authtypes.NewBaseAccountWithAddress(delegatorAddr) - vestedCoins := sdk.NewCoins(sdk.NewCoin(stakingKeeper.BondDenom(ctx), sdk.NewInt(200))) + vestedCoins := sdk.NewCoins(sdk.NewCoin(stakingKeeper.BondDenom(ctx), sdkmath.NewInt(200))) delayedAccount := types.NewDelayedVestingAccount(baseAccount, vestedCoins, ctx.BlockTime().Unix()) ctx = ctx.WithBlockTime(ctx.BlockTime().AddDate(1, 0, 0)) @@ -92,11 +93,11 @@ func TestMigrateVestingAccounts(t *testing.T) { accountKeeper.SetAccount(ctx, delayedAccount) - _, err = stakingKeeper.Delegate(ctx, delegatorAddr, sdk.NewInt(100), stakingtypes.Unbonded, validator, true) + _, err = stakingKeeper.Delegate(ctx, delegatorAddr, sdkmath.NewInt(100), stakingtypes.Unbonded, validator, true) require.NoError(t, err) - _, err = stakingKeeper.Delegate(ctx, delegatorAddr, sdk.NewInt(100), stakingtypes.Unbonded, validator, true) + _, err = stakingKeeper.Delegate(ctx, delegatorAddr, sdkmath.NewInt(100), stakingtypes.Unbonded, validator, true) require.NoError(t, err) - _, err = stakingKeeper.Delegate(ctx, delegatorAddr, sdk.NewInt(100), stakingtypes.Unbonded, validator, true) + _, err = stakingKeeper.Delegate(ctx, delegatorAddr, sdkmath.NewInt(100), stakingtypes.Unbonded, validator, true) require.NoError(t, err) }, cleartTrackingFields, @@ -110,14 +111,14 @@ func TestMigrateVestingAccounts(t *testing.T) { func(ctx sdk.Context, validator stakingtypes.Validator, delegatorAddr sdk.AccAddress) { require.NoError(t, err) baseAccount := authtypes.NewBaseAccountWithAddress(delegatorAddr) - vestedCoins := sdk.NewCoins(sdk.NewCoin(stakingKeeper.BondDenom(ctx), sdk.NewInt(200))) + vestedCoins := sdk.NewCoins(sdk.NewCoin(stakingKeeper.BondDenom(ctx), sdkmath.NewInt(200))) delayedAccount := types.NewDelayedVestingAccount(baseAccount, vestedCoins, ctx.BlockTime().Unix()) ctx = ctx.WithBlockTime(ctx.BlockTime().AddDate(1, 0, 0)) accountKeeper.SetAccount(ctx, delayedAccount) - _, err = stakingKeeper.Delegate(ctx, delegatorAddr, sdk.NewInt(300), stakingtypes.Unbonded, validator, true) + _, err = stakingKeeper.Delegate(ctx, delegatorAddr, sdkmath.NewInt(300), stakingtypes.Unbonded, validator, true) require.NoError(t, err) }, cleartTrackingFields, @@ -130,18 +131,18 @@ func TestMigrateVestingAccounts(t *testing.T) { "delayed vesting has vested, multiple delegations which exceed the vested amount", func(ctx sdk.Context, validator stakingtypes.Validator, delegatorAddr sdk.AccAddress) { baseAccount := authtypes.NewBaseAccountWithAddress(delegatorAddr) - vestedCoins := sdk.NewCoins(sdk.NewCoin(stakingKeeper.BondDenom(ctx), sdk.NewInt(200))) + vestedCoins := sdk.NewCoins(sdk.NewCoin(stakingKeeper.BondDenom(ctx), sdkmath.NewInt(200))) delayedAccount := types.NewDelayedVestingAccount(baseAccount, vestedCoins, ctx.BlockTime().Unix()) ctx = ctx.WithBlockTime(ctx.BlockTime().AddDate(1, 0, 0)) accountKeeper.SetAccount(ctx, delayedAccount) - _, err = stakingKeeper.Delegate(ctx, delegatorAddr, sdk.NewInt(100), stakingtypes.Unbonded, validator, true) + _, err = stakingKeeper.Delegate(ctx, delegatorAddr, sdkmath.NewInt(100), stakingtypes.Unbonded, validator, true) require.NoError(t, err) - _, err = stakingKeeper.Delegate(ctx, delegatorAddr, sdk.NewInt(100), stakingtypes.Unbonded, validator, true) + _, err = stakingKeeper.Delegate(ctx, delegatorAddr, sdkmath.NewInt(100), stakingtypes.Unbonded, validator, true) require.NoError(t, err) - _, err = stakingKeeper.Delegate(ctx, delegatorAddr, sdk.NewInt(100), stakingtypes.Unbonded, validator, true) + _, err = stakingKeeper.Delegate(ctx, delegatorAddr, sdkmath.NewInt(100), stakingtypes.Unbonded, validator, true) require.NoError(t, err) }, cleartTrackingFields, @@ -154,12 +155,12 @@ func TestMigrateVestingAccounts(t *testing.T) { "delayed vesting has not vested, single delegations which exceed the vested amount", func(ctx sdk.Context, validator stakingtypes.Validator, delegatorAddr sdk.AccAddress) { baseAccount := authtypes.NewBaseAccountWithAddress(delegatorAddr) - vestedCoins := sdk.NewCoins(sdk.NewCoin(stakingKeeper.BondDenom(ctx), sdk.NewInt(200))) + vestedCoins := sdk.NewCoins(sdk.NewCoin(stakingKeeper.BondDenom(ctx), sdkmath.NewInt(200))) delayedAccount := types.NewDelayedVestingAccount(baseAccount, vestedCoins, ctx.BlockTime().AddDate(1, 0, 0).Unix()) accountKeeper.SetAccount(ctx, delayedAccount) - _, err = stakingKeeper.Delegate(ctx, delegatorAddr, sdk.NewInt(300), stakingtypes.Unbonded, validator, true) + _, err = stakingKeeper.Delegate(ctx, delegatorAddr, sdkmath.NewInt(300), stakingtypes.Unbonded, validator, true) require.NoError(t, err) }, cleartTrackingFields, @@ -172,16 +173,16 @@ func TestMigrateVestingAccounts(t *testing.T) { "delayed vesting has not vested, multiple delegations which exceed the vested amount", func(ctx sdk.Context, validator stakingtypes.Validator, delegatorAddr sdk.AccAddress) { baseAccount := authtypes.NewBaseAccountWithAddress(delegatorAddr) - vestedCoins := sdk.NewCoins(sdk.NewCoin(stakingKeeper.BondDenom(ctx), sdk.NewInt(200))) + vestedCoins := sdk.NewCoins(sdk.NewCoin(stakingKeeper.BondDenom(ctx), sdkmath.NewInt(200))) delayedAccount := types.NewDelayedVestingAccount(baseAccount, vestedCoins, ctx.BlockTime().AddDate(1, 0, 0).Unix()) accountKeeper.SetAccount(ctx, delayedAccount) - _, err = stakingKeeper.Delegate(ctx, delegatorAddr, sdk.NewInt(100), stakingtypes.Unbonded, validator, true) + _, err = stakingKeeper.Delegate(ctx, delegatorAddr, sdkmath.NewInt(100), stakingtypes.Unbonded, validator, true) require.NoError(t, err) - _, err = stakingKeeper.Delegate(ctx, delegatorAddr, sdk.NewInt(100), stakingtypes.Unbonded, validator, true) + _, err = stakingKeeper.Delegate(ctx, delegatorAddr, sdkmath.NewInt(100), stakingtypes.Unbonded, validator, true) require.NoError(t, err) - _, err = stakingKeeper.Delegate(ctx, delegatorAddr, sdk.NewInt(100), stakingtypes.Unbonded, validator, true) + _, err = stakingKeeper.Delegate(ctx, delegatorAddr, sdkmath.NewInt(100), stakingtypes.Unbonded, validator, true) require.NoError(t, err) }, cleartTrackingFields, @@ -194,16 +195,16 @@ func TestMigrateVestingAccounts(t *testing.T) { "not end time", func(ctx sdk.Context, validator stakingtypes.Validator, delegatorAddr sdk.AccAddress) { baseAccount := authtypes.NewBaseAccountWithAddress(delegatorAddr) - vestedCoins := sdk.NewCoins(sdk.NewCoin(stakingKeeper.BondDenom(ctx), sdk.NewInt(300))) + vestedCoins := sdk.NewCoins(sdk.NewCoin(stakingKeeper.BondDenom(ctx), sdkmath.NewInt(300))) delayedAccount := types.NewDelayedVestingAccount(baseAccount, vestedCoins, ctx.BlockTime().AddDate(1, 0, 0).Unix()) accountKeeper.SetAccount(ctx, delayedAccount) - _, err = stakingKeeper.Delegate(ctx, delegatorAddr, sdk.NewInt(100), stakingtypes.Unbonded, validator, true) + _, err = stakingKeeper.Delegate(ctx, delegatorAddr, sdkmath.NewInt(100), stakingtypes.Unbonded, validator, true) require.NoError(t, err) - _, err = stakingKeeper.Delegate(ctx, delegatorAddr, sdk.NewInt(100), stakingtypes.Unbonded, validator, true) + _, err = stakingKeeper.Delegate(ctx, delegatorAddr, sdkmath.NewInt(100), stakingtypes.Unbonded, validator, true) require.NoError(t, err) - _, err = stakingKeeper.Delegate(ctx, delegatorAddr, sdk.NewInt(100), stakingtypes.Unbonded, validator, true) + _, err = stakingKeeper.Delegate(ctx, delegatorAddr, sdkmath.NewInt(100), stakingtypes.Unbonded, validator, true) require.NoError(t, err) }, cleartTrackingFields, @@ -216,12 +217,12 @@ func TestMigrateVestingAccounts(t *testing.T) { "delayed vesting has not vested, single delegation greater than the total account balance", func(ctx sdk.Context, validator stakingtypes.Validator, delegatorAddr sdk.AccAddress) { baseAccount := authtypes.NewBaseAccountWithAddress(delegatorAddr) - vestedCoins := sdk.NewCoins(sdk.NewCoin(stakingKeeper.BondDenom(ctx), sdk.NewInt(300))) + vestedCoins := sdk.NewCoins(sdk.NewCoin(stakingKeeper.BondDenom(ctx), sdkmath.NewInt(300))) delayedAccount := types.NewDelayedVestingAccount(baseAccount, vestedCoins, ctx.BlockTime().AddDate(1, 0, 0).Unix()) accountKeeper.SetAccount(ctx, delayedAccount) - _, err = stakingKeeper.Delegate(ctx, delegatorAddr, sdk.NewInt(300), stakingtypes.Unbonded, validator, true) + _, err = stakingKeeper.Delegate(ctx, delegatorAddr, sdkmath.NewInt(300), stakingtypes.Unbonded, validator, true) require.NoError(t, err) }, cleartTrackingFields, @@ -234,14 +235,14 @@ func TestMigrateVestingAccounts(t *testing.T) { "delayed vesting has vested, single delegation greater than the total account balance", func(ctx sdk.Context, validator stakingtypes.Validator, delegatorAddr sdk.AccAddress) { baseAccount := authtypes.NewBaseAccountWithAddress(delegatorAddr) - vestedCoins := sdk.NewCoins(sdk.NewCoin(stakingKeeper.BondDenom(ctx), sdk.NewInt(300))) + vestedCoins := sdk.NewCoins(sdk.NewCoin(stakingKeeper.BondDenom(ctx), sdkmath.NewInt(300))) delayedAccount := types.NewDelayedVestingAccount(baseAccount, vestedCoins, ctx.BlockTime().Unix()) ctx = ctx.WithBlockTime(ctx.BlockTime().AddDate(1, 0, 0)) accountKeeper.SetAccount(ctx, delayedAccount) - _, err = stakingKeeper.Delegate(ctx, delegatorAddr, sdk.NewInt(300), stakingtypes.Unbonded, validator, true) + _, err = stakingKeeper.Delegate(ctx, delegatorAddr, sdkmath.NewInt(300), stakingtypes.Unbonded, validator, true) require.NoError(t, err) }, cleartTrackingFields, @@ -256,14 +257,14 @@ func TestMigrateVestingAccounts(t *testing.T) { startTime := ctx.BlockTime().AddDate(1, 0, 0).Unix() endTime := ctx.BlockTime().AddDate(2, 0, 0).Unix() baseAccount := authtypes.NewBaseAccountWithAddress(delegatorAddr) - vestedCoins := sdk.NewCoins(sdk.NewCoin(stakingKeeper.BondDenom(ctx), sdk.NewInt(300))) + vestedCoins := sdk.NewCoins(sdk.NewCoin(stakingKeeper.BondDenom(ctx), sdkmath.NewInt(300))) delayedAccount := types.NewContinuousVestingAccount(baseAccount, vestedCoins, startTime, endTime) ctx = ctx.WithBlockTime(ctx.BlockTime().AddDate(1, 0, 0)) accountKeeper.SetAccount(ctx, delayedAccount) - _, err = stakingKeeper.Delegate(ctx, delegatorAddr, sdk.NewInt(300), stakingtypes.Unbonded, validator, true) + _, err = stakingKeeper.Delegate(ctx, delegatorAddr, sdkmath.NewInt(300), stakingtypes.Unbonded, validator, true) require.NoError(t, err) }, cleartTrackingFields, @@ -278,14 +279,14 @@ func TestMigrateVestingAccounts(t *testing.T) { startTime := ctx.BlockTime().AddDate(-1, 0, 0).Unix() endTime := ctx.BlockTime().AddDate(2, 0, 0).Unix() baseAccount := authtypes.NewBaseAccountWithAddress(delegatorAddr) - vestedCoins := sdk.NewCoins(sdk.NewCoin(stakingKeeper.BondDenom(ctx), sdk.NewInt(300))) + vestedCoins := sdk.NewCoins(sdk.NewCoin(stakingKeeper.BondDenom(ctx), sdkmath.NewInt(300))) delayedAccount := types.NewContinuousVestingAccount(baseAccount, vestedCoins, startTime, endTime) ctx = ctx.WithBlockTime(ctx.BlockTime().AddDate(1, 0, 0)) accountKeeper.SetAccount(ctx, delayedAccount) - _, err = stakingKeeper.Delegate(ctx, delegatorAddr, sdk.NewInt(300), stakingtypes.Unbonded, validator, true) + _, err = stakingKeeper.Delegate(ctx, delegatorAddr, sdkmath.NewInt(300), stakingtypes.Unbonded, validator, true) require.NoError(t, err) }, cleartTrackingFields, @@ -300,14 +301,14 @@ func TestMigrateVestingAccounts(t *testing.T) { startTime := ctx.BlockTime().AddDate(-2, 0, 0).Unix() endTime := ctx.BlockTime().AddDate(-1, 0, 0).Unix() baseAccount := authtypes.NewBaseAccountWithAddress(delegatorAddr) - vestedCoins := sdk.NewCoins(sdk.NewCoin(stakingKeeper.BondDenom(ctx), sdk.NewInt(300))) + vestedCoins := sdk.NewCoins(sdk.NewCoin(stakingKeeper.BondDenom(ctx), sdkmath.NewInt(300))) delayedAccount := types.NewContinuousVestingAccount(baseAccount, vestedCoins, startTime, endTime) ctx = ctx.WithBlockTime(ctx.BlockTime().AddDate(1, 0, 0)) accountKeeper.SetAccount(ctx, delayedAccount) - _, err = stakingKeeper.Delegate(ctx, delegatorAddr, sdk.NewInt(300), stakingtypes.Unbonded, validator, true) + _, err = stakingKeeper.Delegate(ctx, delegatorAddr, sdkmath.NewInt(300), stakingtypes.Unbonded, validator, true) require.NoError(t, err) }, cleartTrackingFields, @@ -320,7 +321,7 @@ func TestMigrateVestingAccounts(t *testing.T) { "periodic vesting account, yet to be vested, some rewards delegated", func(ctx sdk.Context, validator stakingtypes.Validator, delegatorAddr sdk.AccAddress) { baseAccount := authtypes.NewBaseAccountWithAddress(delegatorAddr) - vestedCoins := sdk.NewCoins(sdk.NewCoin(stakingKeeper.BondDenom(ctx), sdk.NewInt(100))) + vestedCoins := sdk.NewCoins(sdk.NewCoin(stakingKeeper.BondDenom(ctx), sdkmath.NewInt(100))) start := ctx.BlockTime().Unix() + int64(time.Hour/time.Second) @@ -640,7 +641,7 @@ func TestMigrateVestingAccounts(t *testing.T) { } } -func trackingCorrected(ctx sdk.Context, t *testing.T, ak keeper.AccountKeeper, addr sdk.AccAddress, expDelVesting sdk.Coins, expDelFree sdk.Coins) { +func trackingCorrected(ctx sdk.Context, t *testing.T, ak keeper.AccountKeeper, addr sdk.AccAddress, expDelVesting, expDelFree sdk.Coins) { t.Helper() baseAccount := ak.GetAccount(ctx, addr) vDA, ok := baseAccount.(exported.VestingAccount) @@ -712,7 +713,7 @@ func createValidator(t *testing.T, ctx sdk.Context, bankKeeper bankkeeper.Keeper _, err = stakingKeeper.Delegate(ctx, addrs[0], valTokens, stakingtypes.Unbonded, val1, true) require.NoError(t, err) - _ = staking.EndBlocker(ctx, stakingKeeper) + stakingKeeper.EndBlocker(ctx) return addrs[0], valAddrs[0] } diff --git a/x/auth/migrations/v3/store.go b/x/auth/migrations/v3/store.go index 5e188a9639bf..6aee1dc1a356 100644 --- a/x/auth/migrations/v3/store.go +++ b/x/auth/migrations/v3/store.go @@ -1,6 +1,7 @@ package v3 import ( + corestore "cosmossdk.io/core/store" storetypes "cosmossdk.io/store/types" "github.com/cosmos/cosmos-sdk/codec" @@ -8,9 +9,12 @@ import ( "github.com/cosmos/cosmos-sdk/x/auth/types" ) -func mapAccountAddressToAccountID(ctx sdk.Context, storeKey storetypes.StoreKey, cdc codec.BinaryCodec) error { - store := ctx.KVStore(storeKey) - iterator := storetypes.KVStorePrefixIterator(store, types.AddressStoreKeyPrefix) +func mapAccountAddressToAccountID(ctx sdk.Context, storeService corestore.KVStoreService, cdc codec.BinaryCodec) error { + store := storeService.OpenKVStore(ctx) + iterator, err := store.Iterator(types.AddressStoreKeyPrefix, storetypes.PrefixEndBytes(types.AddressStoreKeyPrefix)) + if err != nil { + return err + } defer iterator.Close() for ; iterator.Valid(); iterator.Next() { @@ -27,6 +31,6 @@ func mapAccountAddressToAccountID(ctx sdk.Context, storeKey storetypes.StoreKey, // MigrateStore performs in-place store migrations from v0.45 to v0.46. The // migration includes: // - Add an Account number as an index to get the account address -func MigrateStore(ctx sdk.Context, storeKey storetypes.StoreKey, cdc codec.BinaryCodec) error { - return mapAccountAddressToAccountID(ctx, storeKey, cdc) +func MigrateStore(ctx sdk.Context, storeService corestore.KVStoreService, cdc codec.BinaryCodec) error { + return mapAccountAddressToAccountID(ctx, storeService, cdc) } diff --git a/x/auth/migrations/v3/store_test.go b/x/auth/migrations/v3/store_test.go index 633735870702..df48533de972 100644 --- a/x/auth/migrations/v3/store_test.go +++ b/x/auth/migrations/v3/store_test.go @@ -11,6 +11,7 @@ import ( storetypes "cosmossdk.io/store/types" "github.com/cosmos/cosmos-sdk/crypto/keys/secp256k1" + "github.com/cosmos/cosmos-sdk/runtime" "github.com/cosmos/cosmos-sdk/testutil" simtestutil "github.com/cosmos/cosmos-sdk/testutil/sims" sdk "github.com/cosmos/cosmos-sdk/types" @@ -44,7 +45,7 @@ func TestMigrateMapAccAddressToAccNumberKey(t *testing.T) { storeKey := storetypes.NewKVStoreKey(v1.ModuleName) tKey := storetypes.NewTransientStoreKey("transient_test") ctx := testutil.DefaultContext(storeKey, tKey) - store := ctx.KVStore(storeKey) + storeService := runtime.NewKVStoreService(storeKey) var accountKeeper keeper.AccountKeeper @@ -55,7 +56,7 @@ func TestMigrateMapAccAddressToAccNumberKey(t *testing.T) { require.NoError(t, err) legacySubspace := newMockSubspace(authtypes.DefaultParams()) - require.NoError(t, v4.Migrate(ctx, store, legacySubspace, cdc)) + require.NoError(t, v4.Migrate(ctx, storeService, legacySubspace, cdc)) // new base account senderPrivKey := secp256k1.GenPrivKey() @@ -67,7 +68,7 @@ func TestMigrateMapAccAddressToAccNumberKey(t *testing.T) { // migrator m := keeper.NewMigrator(accountKeeper, app.GRPCQueryRouter(), legacySubspace) // set the account to store with map acc addr to acc number - require.NoError(t, m.V45_SetAccount(ctx, acc)) + require.NoError(t, m.V45SetAccount(ctx, acc)) testCases := []struct { name string diff --git a/x/auth/migrations/v4/migrate.go b/x/auth/migrations/v4/migrate.go index 0730f081147c..3372b248c6f6 100644 --- a/x/auth/migrations/v4/migrate.go +++ b/x/auth/migrations/v4/migrate.go @@ -1,7 +1,7 @@ package v4 import ( - storetypes "cosmossdk.io/store/types" + storetypes "cosmossdk.io/core/store" "github.com/cosmos/cosmos-sdk/codec" sdk "github.com/cosmos/cosmos-sdk/types" @@ -15,7 +15,8 @@ var ParamsKey = []byte{0x00} // version 4. Specifically, it takes the parameters that are currently stored // and managed by the x/params modules and stores them directly into the x/auth // module state. -func Migrate(ctx sdk.Context, store storetypes.KVStore, legacySubspace exported.Subspace, cdc codec.BinaryCodec) error { +func Migrate(ctx sdk.Context, storeService storetypes.KVStoreService, legacySubspace exported.Subspace, cdc codec.BinaryCodec) error { + store := storeService.OpenKVStore(ctx) var currParams types.Params legacySubspace.GetParamSet(ctx, &currParams) diff --git a/x/auth/migrations/v4/migrate_test.go b/x/auth/migrations/v4/migrate_test.go index f0b62a26c5b9..bc55fbe3985d 100644 --- a/x/auth/migrations/v4/migrate_test.go +++ b/x/auth/migrations/v4/migrate_test.go @@ -7,6 +7,7 @@ import ( storetypes "cosmossdk.io/store/types" + "github.com/cosmos/cosmos-sdk/runtime" "github.com/cosmos/cosmos-sdk/testutil" sdk "github.com/cosmos/cosmos-sdk/types" moduletestutil "github.com/cosmos/cosmos-sdk/types/module/testutil" @@ -36,13 +37,14 @@ func TestMigrate(t *testing.T) { storeKey := storetypes.NewKVStoreKey(v1.ModuleName) tKey := storetypes.NewTransientStoreKey("transient_test") ctx := testutil.DefaultContext(storeKey, tKey) - store := ctx.KVStore(storeKey) + storeService := runtime.NewKVStoreService(storeKey) legacySubspace := newMockSubspace(types.DefaultParams()) - require.NoError(t, v4.Migrate(ctx, store, legacySubspace, cdc)) + require.NoError(t, v4.Migrate(ctx, storeService, legacySubspace, cdc)) var res types.Params - bz := store.Get(v4.ParamsKey) + bz, err := storeService.OpenKVStore(ctx).Get(v4.ParamsKey) + require.NoError(t, err) require.NoError(t, cdc.Unmarshal(bz, &res)) require.Equal(t, legacySubspace.ps, res) } diff --git a/x/auth/migrations/v5/doc.go b/x/auth/migrations/v5/doc.go deleted file mode 100644 index 0e04902f80a1..000000000000 --- a/x/auth/migrations/v5/doc.go +++ /dev/null @@ -1,4 +0,0 @@ -// v5 is an empty package that exists because of the group module. -// the group module v2 migration actually migrates the auth module state (replace group policies accounts from module accounts to base accounts). -// the auth state does not migrate if the group module is not enabled. -package v5 diff --git a/x/auth/migrations/v5/migrate.go b/x/auth/migrations/v5/migrate.go new file mode 100644 index 000000000000..ba1c32c769fa --- /dev/null +++ b/x/auth/migrations/v5/migrate.go @@ -0,0 +1,45 @@ +package v5 + +import ( + "context" + + "cosmossdk.io/collections" + storetypes "cosmossdk.io/core/store" + "github.com/cosmos/gogoproto/types" +) + +var LegacyGlobalAccountNumberKey = []byte("globalAccountNumber") + +func Migrate(ctx context.Context, storeService storetypes.KVStoreService, sequence collections.Sequence) error { + store := storeService.OpenKVStore(ctx) + b, err := store.Get(LegacyGlobalAccountNumberKey) + if err != nil { + return err + } + if b == nil { + // this would mean no account was ever created in this chain which is being migrated? + // we're doing nothing as the collections.Sequence already handles the non-existing value. + return nil + } + + // get old value + v := new(types.UInt64Value) + err = v.Unmarshal(b) + if err != nil { + return err + } + + // set the old value in the collection + err = sequence.Set(ctx, v.Value) + if err != nil { + return err + } + + // remove the value from the old prefix. + err = store.Delete(LegacyGlobalAccountNumberKey) + if err != nil { + return err + } + + return nil +} diff --git a/x/auth/migrations/v5/migrate_test.go b/x/auth/migrations/v5/migrate_test.go new file mode 100644 index 000000000000..75e8b65ff042 --- /dev/null +++ b/x/auth/migrations/v5/migrate_test.go @@ -0,0 +1,44 @@ +package v5 + +import ( + "testing" + + "cosmossdk.io/collections" + "cosmossdk.io/collections/colltest" + "github.com/cosmos/gogoproto/types" + "github.com/stretchr/testify/require" +) + +func TestMigrate(t *testing.T) { + kv, ctx := colltest.MockStore() + sb := collections.NewSchemaBuilder(kv) + seq := collections.NewSequence(sb, collections.NewPrefix(0), "seq") + + wantValue := uint64(100) + + // set old sequence to wanted value + legacySeqBytes, err := (&types.UInt64Value{Value: wantValue}).Marshal() + require.NoError(t, err) + + err = kv.OpenKVStore(ctx).Set(LegacyGlobalAccountNumberKey, legacySeqBytes) + require.NoError(t, err) + + err = Migrate(ctx, kv, seq) + require.NoError(t, err) + + // check that after migration the sequence is what we want it to be + gotValue, err := seq.Peek(ctx) + require.NoError(t, err) + require.Equal(t, wantValue, gotValue) + + // case the global account number was not set + ctx = kv.NewStoreContext() // this resets the store to zero + wantValue = collections.DefaultSequenceStart + + err = Migrate(ctx, kv, seq) + require.NoError(t, err) + + gotValue, err = seq.Next(ctx) + require.NoError(t, err) + require.Equal(t, wantValue, gotValue) +} diff --git a/x/auth/module.go b/x/auth/module.go index b2fff09f8a17..684a4d8511d2 100644 --- a/x/auth/module.go +++ b/x/auth/module.go @@ -16,11 +16,10 @@ import ( modulev1 "cosmossdk.io/api/cosmos/auth/module/v1" - store "cosmossdk.io/store/types" + "cosmossdk.io/core/store" "github.com/cosmos/cosmos-sdk/client" "github.com/cosmos/cosmos-sdk/codec" - codecaddress "github.com/cosmos/cosmos-sdk/codec/address" codectypes "github.com/cosmos/cosmos-sdk/codec/types" sdk "github.com/cosmos/cosmos-sdk/types" "github.com/cosmos/cosmos-sdk/types/module" @@ -34,7 +33,7 @@ import ( ) // ConsensusVersion defines the current x/auth module consensus version. -const ConsensusVersion = 4 +const ConsensusVersion = 5 var ( _ module.AppModule = AppModule{} @@ -43,7 +42,9 @@ var ( ) // AppModuleBasic defines the basic application module used by the auth module. -type AppModuleBasic struct{} +type AppModuleBasic struct { + ac address.Codec +} // Name returns the auth module's name. func (AppModuleBasic) Name() string { @@ -84,8 +85,8 @@ func (AppModuleBasic) GetTxCmd() *cobra.Command { } // GetQueryCmd returns the root query command for the auth module. -func (AppModuleBasic) GetQueryCmd() *cobra.Command { - return cli.GetQueryCmd() +func (ab AppModuleBasic) GetQueryCmd() *cobra.Command { + return cli.GetQueryCmd(ab.ac) } // RegisterInterfaces registers interfaces and implementations of the auth module. @@ -115,7 +116,7 @@ func (am AppModule) IsAppModule() {} // NewAppModule creates a new AppModule object func NewAppModule(cdc codec.Codec, accountKeeper keeper.AccountKeeper, randGenAccountsFn types.RandomGenesisAccountsFn, ss exported.Subspace) AppModule { return AppModule{ - AppModuleBasic: AppModuleBasic{}, + AppModuleBasic: AppModuleBasic{ac: accountKeeper.GetAddressCodec()}, accountKeeper: accountKeeper, randGenAccountsFn: randGenAccountsFn, legacySubspace: ss, @@ -146,9 +147,8 @@ func (am AppModule) RegisterServices(cfg module.Configurator) { panic(fmt.Sprintf("failed to migrate x/%s from version 3 to 4: %v", types.ModuleName, err)) } - // see migrations/v5/doc.go - if err := cfg.RegisterMigration(types.ModuleName, 4, func(ctx sdk.Context) error { return nil }); err != nil { - panic(fmt.Sprintf("failed to migrate x/%s from version 4 to 5: %v", types.ModuleName, err)) + if err := cfg.RegisterMigration(types.ModuleName, 4, m.Migrate4To5); err != nil { + panic(fmt.Sprintf("failed to migrate x/%s from version 4 to 5", types.ModuleName)) } } @@ -207,16 +207,15 @@ func init() { // ProvideAddressCodec provides an address.Codec to the container for any // modules that want to do address string <> bytes conversion. func ProvideAddressCodec(config *modulev1.Module) address.Codec { - return codecaddress.NewBech32Codec(config.Bech32Prefix) + return keeper.NewBech32Codec(config.Bech32Prefix) } -//nolint:revive -type AuthInputs struct { +type ModuleInputs struct { depinject.In - Config *modulev1.Module - Key *store.KVStoreKey - Cdc codec.Codec + Config *modulev1.Module + StoreService store.KVStoreService + Cdc codec.Codec RandomGenesisAccountsFn types.RandomGenesisAccountsFn `optional:"true"` AccountI func() sdk.AccountI `optional:"true"` @@ -225,15 +224,14 @@ type AuthInputs struct { LegacySubspace exported.Subspace `optional:"true"` } -//nolint:revive -type AuthOutputs struct { +type ModuleOutputs struct { depinject.Out AccountKeeper keeper.AccountKeeper Module appmodule.AppModule } -func ProvideModule(in AuthInputs) AuthOutputs { +func ProvideModule(in ModuleInputs) ModuleOutputs { maccPerms := map[string][]string{} for _, permission := range in.Config.ModuleAccountPermissions { maccPerms[permission.Account] = permission.Permissions @@ -253,8 +251,8 @@ func ProvideModule(in AuthInputs) AuthOutputs { in.AccountI = types.ProtoBaseAccount } - k := keeper.NewAccountKeeper(in.Cdc, in.Key, in.AccountI, maccPerms, in.Config.Bech32Prefix, authority.String()) + k := keeper.NewAccountKeeper(in.Cdc, in.StoreService, in.AccountI, maccPerms, in.Config.Bech32Prefix, authority.String()) m := NewAppModule(in.Cdc, k, in.RandomGenesisAccountsFn, in.LegacySubspace) - return AuthOutputs{AccountKeeper: k, Module: m} + return ModuleOutputs{AccountKeeper: k, Module: m} } diff --git a/x/auth/signing/verify.go b/x/auth/signing/verify.go index 826df596bcaa..6455e60b782a 100644 --- a/x/auth/signing/verify.go +++ b/x/auth/signing/verify.go @@ -4,18 +4,81 @@ import ( "context" "fmt" + "google.golang.org/protobuf/types/known/anypb" + + signingv1beta1 "cosmossdk.io/api/cosmos/tx/signing/v1beta1" + "cosmossdk.io/x/tx/decode" + txsigning "cosmossdk.io/x/tx/signing" + codectypes "github.com/cosmos/cosmos-sdk/codec/types" cryptotypes "github.com/cosmos/cosmos-sdk/crypto/types" "github.com/cosmos/cosmos-sdk/crypto/types/multisig" sdk "github.com/cosmos/cosmos-sdk/types" + "github.com/cosmos/cosmos-sdk/types/registry" "github.com/cosmos/cosmos-sdk/types/tx/signing" ) -// VerifySignature verifies a transaction signature contained in SignatureData abstracting over different signing modes -// and single vs multi-signatures. -func VerifySignature(ctx context.Context, pubKey cryptotypes.PubKey, signerData SignerData, sigData signing.SignatureData, handler SignModeHandler, tx sdk.Tx) error { - switch data := sigData.(type) { +// APISignModesToInternal converts a protobuf SignMode array to a signing.SignMode array. +func APISignModesToInternal(modes []signingv1beta1.SignMode) ([]signing.SignMode, error) { + internalModes := make([]signing.SignMode, len(modes)) + for i, mode := range modes { + internalMode, err := APISignModeToInternal(mode) + if err != nil { + return nil, err + } + internalModes[i] = internalMode + } + return internalModes, nil +} + +// APISignModeToInternal converts a protobuf SignMode to a signing.SignMode. +func APISignModeToInternal(mode signingv1beta1.SignMode) (signing.SignMode, error) { + switch mode { + case signingv1beta1.SignMode_SIGN_MODE_DIRECT: + return signing.SignMode_SIGN_MODE_DIRECT, nil + case signingv1beta1.SignMode_SIGN_MODE_LEGACY_AMINO_JSON: + return signing.SignMode_SIGN_MODE_LEGACY_AMINO_JSON, nil + case signingv1beta1.SignMode_SIGN_MODE_TEXTUAL: + return signing.SignMode_SIGN_MODE_TEXTUAL, nil + case signingv1beta1.SignMode_SIGN_MODE_DIRECT_AUX: + return signing.SignMode_SIGN_MODE_DIRECT_AUX, nil + default: + return signing.SignMode_SIGN_MODE_UNSPECIFIED, fmt.Errorf("unsupported sign mode %s", mode) + } +} + +// internalSignModeToAPI converts a signing.SignMode to a protobuf SignMode. +func internalSignModeToAPI(mode signing.SignMode) (signingv1beta1.SignMode, error) { + switch mode { + case signing.SignMode_SIGN_MODE_DIRECT: + return signingv1beta1.SignMode_SIGN_MODE_DIRECT, nil + case signing.SignMode_SIGN_MODE_LEGACY_AMINO_JSON: + return signingv1beta1.SignMode_SIGN_MODE_LEGACY_AMINO_JSON, nil + case signing.SignMode_SIGN_MODE_TEXTUAL: + return signingv1beta1.SignMode_SIGN_MODE_TEXTUAL, nil + case signing.SignMode_SIGN_MODE_DIRECT_AUX: + return signingv1beta1.SignMode_SIGN_MODE_DIRECT_AUX, nil + default: + return signingv1beta1.SignMode_SIGN_MODE_UNSPECIFIED, fmt.Errorf("unsupported sign mode %s", mode) + } +} + +// VerifySignature verifies a transaction signature contained in SignatureData abstracting over different signing +// modes. It differs from VerifySignature in that it uses the new txsigning.TxData interface in x/tx. +func VerifySignature( + ctx context.Context, + pubKey cryptotypes.PubKey, + signerData txsigning.SignerData, + signatureData signing.SignatureData, + handler *txsigning.HandlerMap, + txData txsigning.TxData, +) error { + switch data := signatureData.(type) { case *signing.SingleSignatureData: - signBytes, err := GetSignBytesWithContext(handler, ctx, data.SignMode, signerData, tx) + signMode, err := internalSignModeToAPI(data.SignMode) + if err != nil { + return err + } + signBytes, err := handler.GetSignBytes(ctx, signMode, signerData, txData) if err != nil { return err } @@ -30,29 +93,72 @@ func VerifySignature(ctx context.Context, pubKey cryptotypes.PubKey, signerData return fmt.Errorf("expected %T, got %T", (multisig.PubKey)(nil), pubKey) } err := multiPK.VerifyMultisignature(func(mode signing.SignMode) ([]byte, error) { - handlerWithContext, ok := handler.(SignModeHandlerWithContext) - if ok { - return handlerWithContext.GetSignBytesWithContext(ctx, mode, signerData, tx) + signMode, err := internalSignModeToAPI(mode) + if err != nil { + return nil, err } - return handler.GetSignBytes(mode, signerData, tx) + return handler.GetSignBytes(ctx, signMode, signerData, txData) }, data) if err != nil { return err } return nil default: - return fmt.Errorf("unexpected SignatureData %T", sigData) + return fmt.Errorf("unexpected SignatureData %T", signatureData) } } -// GetSignBytesWithContext gets the sign bytes from the sign mode handler. It -// checks if the sign mode handler supports SignModeHandlerWithContext, in -// which case it passes the context.Context argument. Otherwise, it fallbacks -// to GetSignBytes. -func GetSignBytesWithContext(h SignModeHandler, ctx context.Context, mode signing.SignMode, data SignerData, tx sdk.Tx) ([]byte, error) { //nolint:revive - hWithCtx, ok := h.(SignModeHandlerWithContext) - if ok { - return hWithCtx.GetSignBytesWithContext(ctx, mode, data, tx) +// GetSignBytesAdapter returns the sign bytes for a given transaction and sign mode. It accepts the arguments expected +// for signing in x/auth/tx and converts them to the arguments expected by the txsigning.HandlerMap, then applies +// HandlerMap.GetSignBytes to get the sign bytes. +func GetSignBytesAdapter( + ctx context.Context, + encoder sdk.TxEncoder, + handlerMap *txsigning.HandlerMap, + mode signing.SignMode, + signerData SignerData, + tx sdk.Tx, +) ([]byte, error) { + // round trip performance hit. + // could be avoided if we had a way to get the bytes from the txBuilder. + txBytes, err := encoder(tx) + if err != nil { + return nil, err + } + decodeCtx, err := decode.NewDecoder(decode.Options{ProtoFiles: registry.MergedProtoRegistry()}) + if err != nil { + return nil, err + } + decodedTx, err := decodeCtx.Decode(txBytes) + if err != nil { + return nil, err + } + txData := txsigning.TxData{ + Body: decodedTx.Tx.Body, + AuthInfo: decodedTx.Tx.AuthInfo, + AuthInfoBytes: decodedTx.TxRaw.AuthInfoBytes, + BodyBytes: decodedTx.TxRaw.BodyBytes, + } + txSignMode, err := internalSignModeToAPI(mode) + if err != nil { + return nil, err + } + + anyPk, err := codectypes.NewAnyWithValue(signerData.PubKey) + if err != nil { + return nil, err + } + + txSignerData := txsigning.SignerData{ + ChainID: signerData.ChainID, + AccountNumber: signerData.AccountNumber, + Sequence: signerData.Sequence, + Address: signerData.Address, + PubKey: &anypb.Any{ + TypeUrl: anyPk.TypeUrl, + Value: anyPk.Value, + }, } - return h.GetSignBytes(mode, data, tx) + // Generate the bytes to be signed. + return handlerMap.GetSignBytes(ctx, txSignMode, txSignerData, txData) } diff --git a/x/auth/simulation/proposals.go b/x/auth/simulation/proposals.go index 87746569c22f..0e7cd95797f3 100644 --- a/x/auth/simulation/proposals.go +++ b/x/auth/simulation/proposals.go @@ -14,7 +14,7 @@ import ( const ( DefaultWeightMsgUpdateParams int = 100 - OpWeightMsgUpdateParams = "op_weight_msg_update_params" //nolint:gosec + OpWeightMsgUpdateParams = "op_weight_msg_update_params" ) // ProposalMsgs defines the module weighted proposals' contents diff --git a/x/auth/testutil/util.go b/x/auth/testutil/util.go index 93cd30355eb2..b144a7f5d80d 100644 --- a/x/auth/testutil/util.go +++ b/x/auth/testutil/util.go @@ -6,7 +6,7 @@ import ( "github.com/stretchr/testify/require" ) -func AssertError(t *testing.T, err error, expectedErr error, expectedErrMsg string) { +func AssertError(t *testing.T, err, expectedErr error, expectedErrMsg string) { switch { case expectedErr != nil: require.ErrorIs(t, err, expectedErr) diff --git a/x/auth/tx/aux_test.go b/x/auth/tx/aux_test.go index 97416a9df891..90481f5767cc 100644 --- a/x/auth/tx/aux_test.go +++ b/x/auth/tx/aux_test.go @@ -1,6 +1,7 @@ package tx_test import ( + "context" "testing" "github.com/stretchr/testify/require" @@ -130,17 +131,18 @@ func TestBuilderWithAux(t *testing.T) { PubKey: feepayerPk, Sequence: 15, }) - signBz, err = txConfig.SignModeHandler().GetSignBytes( - signing.SignMode_SIGN_MODE_DIRECT, - authsigning.SignerData{ - Address: feepayerAddr.String(), - ChainID: chainID, - AccountNumber: 11, - Sequence: 15, - PubKey: feepayerPk, - }, - w.GetTx(), - ) + signerData := authsigning.SignerData{ + Address: feepayerAddr.String(), + ChainID: chainID, + AccountNumber: 11, + Sequence: 15, + PubKey: feepayerPk, + } + + signBz, err = authsigning.GetSignBytesAdapter( + context.Background(), txConfig.TxEncoder(), txConfig.SignModeHandler(), signing.SignMode_SIGN_MODE_DIRECT, + signerData, w.GetTx()) + require.NoError(t, err) feepayerSig, err := feepayerPriv.Sign(signBz) require.NoError(t, err) diff --git a/x/auth/tx/builder_test.go b/x/auth/tx/builder_test.go index 6b4fac958682..5aa19e5e6ef5 100644 --- a/x/auth/tx/builder_test.go +++ b/x/auth/tx/builder_test.go @@ -6,6 +6,7 @@ import ( "github.com/stretchr/testify/require" errorsmod "cosmossdk.io/errors" + sdkmath "cosmossdk.io/math" "github.com/cosmos/cosmos-sdk/codec" "github.com/cosmos/cosmos-sdk/codec/legacy" @@ -23,7 +24,7 @@ func TestTxBuilder(t *testing.T) { marshaler := codec.NewProtoCodec(codectypes.NewInterfaceRegistry()) txBuilder := newBuilder(nil) - memo := "sometestmemo" //nolint:goconst + memo := "testmemo" msgs := []sdk.Msg{testdata.NewTestMsg(addr)} accSeq := uint64(2) // Arbitrary account sequence any, err := codectypes.NewAnyWithValue(pubkey) @@ -137,7 +138,7 @@ func TestBuilderValidateBasic(t *testing.T) { // require to fail validation upon invalid fee badFeeAmount := testdata.NewTestFeeAmount() - badFeeAmount[0].Amount = sdk.NewInt(-5) + badFeeAmount[0].Amount = sdkmath.NewInt(-5) txBuilder := newBuilder(nil) var sig1, sig2 signing.SignatureV2 diff --git a/x/auth/tx/config.go b/x/auth/tx/config.go index 5cb00e96907d..6d89cd41ecd8 100644 --- a/x/auth/tx/config.go +++ b/x/auth/tx/config.go @@ -3,17 +3,21 @@ package tx import ( "fmt" - "cosmossdk.io/x/tx/signing/textual" + "google.golang.org/protobuf/reflect/protoregistry" + + txsigning "cosmossdk.io/x/tx/signing" + "cosmossdk.io/x/tx/signing/aminojson" + "cosmossdk.io/x/tx/signing/direct" + "cosmossdk.io/x/tx/signing/directaux" "github.com/cosmos/cosmos-sdk/client" "github.com/cosmos/cosmos-sdk/codec" sdk "github.com/cosmos/cosmos-sdk/types" signingtypes "github.com/cosmos/cosmos-sdk/types/tx/signing" - "github.com/cosmos/cosmos-sdk/x/auth/signing" ) type config struct { - handler signing.SignModeHandler + handler *txsigning.HandlerMap decoder sdk.TxDecoder encoder sdk.TxEncoder jsonDecoder sdk.TxDecoder @@ -27,25 +31,66 @@ type config struct { // NOTE: Use NewTxConfigWithHandler to provide a custom signing handler in case the sign mode // is not supported by default (eg: SignMode_SIGN_MODE_EIP_191). Use NewTxConfigWithTextual // to enable SIGN_MODE_TEXTUAL (for testing purposes for now). -func NewTxConfig(protoCodec codec.ProtoCodecMarshaler, enabledSignModes []signingtypes.SignMode, customSignModes ...signing.SignModeHandler) client.TxConfig { +// +// We prefer to use depinject to provide client.TxConfig, but we permit this constructor usage. Within the SDK, +// this constructor is primarily used in tests, but also sees usage in app chains like: +// https://github.com/evmos/evmos/blob/719363fbb92ff3ea9649694bd088e4c6fe9c195f/encoding/config.go#L37 +// TODO: collapse enabledSignModes and customSignModes +func NewTxConfig(protoCodec codec.ProtoCodecMarshaler, enabledSignModes []signingtypes.SignMode, + customSignModes ...txsigning.SignModeHandler, +) client.TxConfig { + typeResolver := protoregistry.GlobalTypes + protoFiles := protoCodec.InterfaceRegistry() + signersContext, err := txsigning.NewGetSignersContext(txsigning.GetSignersOptions{ProtoFiles: protoFiles}) + if err != nil { + panic(err) + } + + signModeOptions := &SignModeOptions{} for _, m := range enabledSignModes { - if m == signingtypes.SignMode_SIGN_MODE_TEXTUAL { + switch m { + case signingtypes.SignMode_SIGN_MODE_DIRECT: + signModeOptions.Direct = &direct.SignModeHandler{} + case signingtypes.SignMode_SIGN_MODE_DIRECT_AUX: + signModeOptions.DirectAux = &directaux.SignModeHandlerOptions{ + FileResolver: protoFiles, + TypeResolver: typeResolver, + SignersContext: signersContext, + } + case signingtypes.SignMode_SIGN_MODE_LEGACY_AMINO_JSON: + aminoJSONEncoder := aminojson.NewAminoJSON() + signModeOptions.AminoJSON = &aminojson.SignModeHandlerOptions{ + FileResolver: protoFiles, + TypeResolver: typeResolver, + Encoder: &aminoJSONEncoder, + } + case signingtypes.SignMode_SIGN_MODE_TEXTUAL: panic("cannot use NewTxConfig with SIGN_MODE_TEXTUAL enabled; please use NewTxConfigWithTextual") } } - return NewTxConfigWithHandler(protoCodec, makeSignModeHandler(enabledSignModes, &textual.SignModeHandler{}, customSignModes...)) + return NewTxConfigWithHandler(protoCodec, makeSignModeHandler(*signModeOptions, customSignModes...)) +} + +func NewTxConfigWithOptions(protoCodec codec.ProtoCodecMarshaler, signModeOptions SignModeOptions, + customSignModes ...txsigning.SignModeHandler, +) client.TxConfig { + return NewTxConfigWithHandler(protoCodec, makeSignModeHandler(signModeOptions, customSignModes...)) } // NewTxConfigWithTextual is like NewTxConfig with the ability to add // a SIGN_MODE_TEXTUAL renderer. It is currently still EXPERIMENTAL, for should // be used for TESTING purposes only, until Textual is fully released. -func NewTxConfigWithTextual(protoCodec codec.ProtoCodecMarshaler, enabledSignModes []signingtypes.SignMode, textual *textual.SignModeHandler, customSignModes ...signing.SignModeHandler) client.TxConfig { - return NewTxConfigWithHandler(protoCodec, makeSignModeHandler(enabledSignModes, textual, customSignModes...)) +// +// Deprecated: use NewTxConfigWithOptions instead. +func NewTxConfigWithTextual(protoCodec codec.ProtoCodecMarshaler, _ []signingtypes.SignMode, + signModeOptions SignModeOptions, customSignModes ...txsigning.SignModeHandler, +) client.TxConfig { + return NewTxConfigWithOptions(protoCodec, signModeOptions, customSignModes...) } -// NewTxConfig returns a new protobuf TxConfig using the provided ProtoCodec and signing handler. -func NewTxConfigWithHandler(protoCodec codec.ProtoCodecMarshaler, handler signing.SignModeHandler) client.TxConfig { +// NewTxConfigWithHandler returns a new protobuf TxConfig using the provided ProtoCodec and signing handler. +func NewTxConfigWithHandler(protoCodec codec.ProtoCodecMarshaler, handler *txsigning.HandlerMap) client.TxConfig { return &config{ handler: handler, decoder: DefaultTxDecoder(protoCodec), @@ -70,7 +115,7 @@ func (g config) WrapTxBuilder(newTx sdk.Tx) (client.TxBuilder, error) { return newBuilder, nil } -func (g config) SignModeHandler() signing.SignModeHandler { +func (g config) SignModeHandler() *txsigning.HandlerMap { return g.handler } diff --git a/x/auth/tx/config/config.go b/x/auth/tx/config/config.go index 346c9d0eebd8..5a3ce85b32f2 100644 --- a/x/auth/tx/config/config.go +++ b/x/auth/tx/config/config.go @@ -1,65 +1,79 @@ package tx import ( + "context" "fmt" + "google.golang.org/grpc" + "google.golang.org/grpc/codes" + grpcstatus "google.golang.org/grpc/status" + "google.golang.org/protobuf/reflect/protoregistry" + + bankv1beta1 "cosmossdk.io/api/cosmos/bank/v1beta1" txconfigv1 "cosmossdk.io/api/cosmos/tx/config/v1" "cosmossdk.io/core/appmodule" "cosmossdk.io/depinject" + txsigning "cosmossdk.io/x/tx/signing" + "cosmossdk.io/x/tx/signing/aminojson" + "cosmossdk.io/x/tx/signing/direct" + "cosmossdk.io/x/tx/signing/directaux" + "cosmossdk.io/x/tx/signing/textual" + "github.com/cosmos/cosmos-sdk/baseapp" "github.com/cosmos/cosmos-sdk/client" "github.com/cosmos/cosmos-sdk/codec" "github.com/cosmos/cosmos-sdk/runtime" sdk "github.com/cosmos/cosmos-sdk/types" + "github.com/cosmos/cosmos-sdk/types/registry" "github.com/cosmos/cosmos-sdk/x/auth/ante" "github.com/cosmos/cosmos-sdk/x/auth/posthandler" - "github.com/cosmos/cosmos-sdk/x/auth/signing" "github.com/cosmos/cosmos-sdk/x/auth/tx" authtypes "github.com/cosmos/cosmos-sdk/x/auth/types" + "github.com/cosmos/cosmos-sdk/x/bank/types" ) func init() { appmodule.Register(&txconfigv1.Config{}, appmodule.Provide(ProvideModule), + appmodule.Provide(ProvideSignModeOptions), ) } -//nolint:revive -type TxInputs struct { +type ModuleInputs struct { depinject.In - Config *txconfigv1.Config ProtoCodecMarshaler codec.ProtoCodecMarshaler - - AccountKeeper ante.AccountKeeper `optional:"true"` + SignModeOptions tx.SignModeOptions // BankKeeper is the expected bank keeper to be passed to AnteHandlers - BankKeeper authtypes.BankKeeper `optional:"true"` - // TxBankKeeper is the expected bank keeper to be passed to Textual - TxBankKeeper BankKeeper - FeeGrantKeeper ante.FeegrantKeeper `optional:"true"` - - CustomSignModeHandlers func() []signing.SignModeHandler `optional:"true"` + BankKeeper authtypes.BankKeeper `optional:"true"` + AccountKeeper ante.AccountKeeper `optional:"true"` + FeeGrantKeeper ante.FeegrantKeeper `optional:"true"` + CustomSignModeHandlers func() []txsigning.SignModeHandler `optional:"true"` } -//nolint:revive -type TxOutputs struct { +type ModuleOutputs struct { depinject.Out TxConfig client.TxConfig BaseAppOption runtime.BaseAppOption } -func ProvideModule(in TxInputs) TxOutputs { - textual, err := NewTextualWithBankKeeper(in.TxBankKeeper) +// ProvideSignModeOptions provides the default x/tx SignModeOptions for the SDK. +func ProvideSignModeOptions(bk BankKeeper) tx.SignModeOptions { + opts, err := NewSignModeOptionsWithMetadataQueryFn(NewBankKeeperCoinMetadataQueryFn(bk)) if err != nil { panic(err) } + return opts +} + +func ProvideModule(in ModuleInputs) ModuleOutputs { var txConfig client.TxConfig - if in.CustomSignModeHandlers == nil { - txConfig = tx.NewTxConfigWithTextual(in.ProtoCodecMarshaler, tx.DefaultSignModes, textual) - } else { - txConfig = tx.NewTxConfigWithTextual(in.ProtoCodecMarshaler, tx.DefaultSignModes, textual, in.CustomSignModeHandlers()...) + var customSignModeHandlers []txsigning.SignModeHandler + if in.CustomSignModeHandlers != nil { + customSignModeHandlers = in.CustomSignModeHandlers() } + txConfig = tx.NewTxConfigWithOptions(in.ProtoCodecMarshaler, in.SignModeOptions, customSignModeHandlers...) baseAppOption := func(app *baseapp.BaseApp) { // AnteHandlers @@ -100,10 +114,10 @@ func ProvideModule(in TxInputs) TxOutputs { app.SetTxEncoder(txConfig.TxEncoder()) } - return TxOutputs{TxConfig: txConfig, BaseAppOption: baseAppOption} + return ModuleOutputs{TxConfig: txConfig, BaseAppOption: baseAppOption} } -func newAnteHandler(txConfig client.TxConfig, in TxInputs) (sdk.AnteHandler, error) { +func newAnteHandler(txConfig client.TxConfig, in ModuleInputs) (sdk.AnteHandler, error) { if in.BankKeeper == nil { return nil, fmt.Errorf("both AccountKeeper and BankKeeper are required") } @@ -123,3 +137,111 @@ func newAnteHandler(txConfig client.TxConfig, in TxInputs) (sdk.AnteHandler, err return anteHandler, nil } + +// NewBankKeeperCoinMetadataQueryFn creates a new Textual struct using the given +// BankKeeper to retrieve coin metadata. +// +// Note: Once we switch to ADR-033, and keepers become ADR-033 clients to each +// other, this function could probably be deprecated in favor of +// `NewTextualWithGRPCConn`. +func NewBankKeeperCoinMetadataQueryFn(bk BankKeeper) textual.CoinMetadataQueryFn { + return func(ctx context.Context, denom string) (*bankv1beta1.Metadata, error) { + res, err := bk.DenomMetadata(ctx, &types.QueryDenomMetadataRequest{Denom: denom}) + if err != nil { + return nil, metadataExists(err) + } + + m := &bankv1beta1.Metadata{ + Base: res.Metadata.Base, + Display: res.Metadata.Display, + // fields below are not strictly needed by Textual + // but added here for completeness. + Description: res.Metadata.Description, + Name: res.Metadata.Name, + Symbol: res.Metadata.Symbol, + Uri: res.Metadata.URI, + UriHash: res.Metadata.URIHash, + } + m.DenomUnits = make([]*bankv1beta1.DenomUnit, len(res.Metadata.DenomUnits)) + for i, d := range res.Metadata.DenomUnits { + m.DenomUnits[i] = &bankv1beta1.DenomUnit{ + Denom: d.Denom, + Exponent: d.Exponent, + Aliases: d.Aliases, + } + } + + return m, nil + } +} + +// NewGRPCCoinMetadataQueryFn returns a new Textual instance where the metadata +// queries are done via gRPC using the provided GRPC client connection. In the +// SDK, you can pass a client.Context as the GRPC connection. +// +// Example: +// +// clientCtx := client.GetClientContextFromCmd(cmd) +// txt := tx.NewTextualWithGRPCConn(clientCtxx) +func NewGRPCCoinMetadataQueryFn(grpcConn grpc.ClientConnInterface) textual.CoinMetadataQueryFn { + return func(ctx context.Context, denom string) (*bankv1beta1.Metadata, error) { + bankQueryClient := bankv1beta1.NewQueryClient(grpcConn) + res, err := bankQueryClient.DenomMetadata(ctx, &bankv1beta1.QueryDenomMetadataRequest{ + Denom: denom, + }) + if err != nil { + return nil, metadataExists(err) + } + + return res.Metadata, nil + } +} + +// NewSignModeOptionsWithMetadataQueryFn creates a new SignModeOptions instance +func NewSignModeOptionsWithMetadataQueryFn(fn textual.CoinMetadataQueryFn) (tx.SignModeOptions, error) { + protoFiles := registry.MergedProtoRegistry() + typeResolver := protoregistry.GlobalTypes + signersContext, err := txsigning.NewGetSignersContext(txsigning.GetSignersOptions{ProtoFiles: protoFiles}) + if err != nil { + return tx.SignModeOptions{}, err + } + + aminoJSONEncoder := aminojson.NewAminoJSON() + signModeOptions := tx.SignModeOptions{ + Direct: &direct.SignModeHandler{}, + DirectAux: &directaux.SignModeHandlerOptions{ + FileResolver: protoFiles, + TypeResolver: typeResolver, + SignersContext: signersContext, + }, + AminoJSON: &aminojson.SignModeHandlerOptions{ + FileResolver: protoFiles, + TypeResolver: typeResolver, + Encoder: &aminoJSONEncoder, + }, + Textual: &textual.SignModeOptions{ + CoinMetadataQuerier: fn, + FileResolver: protoFiles, + TypeResolver: typeResolver, + }, + } + + return signModeOptions, nil +} + +// metadataExists parses the error, and only propagates the error if it's +// different than a "not found" error. +func metadataExists(err error) error { + status, ok := grpcstatus.FromError(err) + if !ok { + return err + } + + // This means we didn't find any metadata for this denom. Returning + // empty metadata. + if status.Code() == codes.NotFound { + return nil + } + + return err +} diff --git a/x/auth/tx/config/textual.go b/x/auth/tx/config/textual.go deleted file mode 100644 index 3a93cb689d17..000000000000 --- a/x/auth/tx/config/textual.go +++ /dev/null @@ -1,107 +0,0 @@ -package tx - -import ( - "context" - - gogoproto "github.com/cosmos/gogoproto/proto" - "google.golang.org/grpc" - "google.golang.org/grpc/codes" - grpcstatus "google.golang.org/grpc/status" - - bankv1beta1 "cosmossdk.io/api/cosmos/bank/v1beta1" - "cosmossdk.io/x/tx/signing/textual" - - "github.com/cosmos/cosmos-sdk/x/bank/types" -) - -// NewTextualWithGRPCConn returns a new Textual instance where the metadata -// queries are done via gRPC using the provided GRPC client connection. In the -// SDK, you can pass a client.Context as the GRPC connection. -// -// Example: -// -// clientCtx := client.GetClientContextFromCmd(cmd) -// txt := tx.NewTextualWithGRPCConn(clientCtxx) -func NewTextualWithGRPCConn(grpcConn grpc.ClientConnInterface) (*textual.SignModeHandler, error) { - protoFiles, err := gogoproto.MergedRegistry() - if err != nil { - return nil, err - } - - return textual.NewSignModeHandler(textual.SignModeOptions{ - CoinMetadataQuerier: func(ctx context.Context, denom string) (*bankv1beta1.Metadata, error) { - bankQueryClient := bankv1beta1.NewQueryClient(grpcConn) - res, err := bankQueryClient.DenomMetadata(ctx, &bankv1beta1.QueryDenomMetadataRequest{ - Denom: denom, - }) - if err != nil { - return nil, metadataExists(err) - } - - return res.Metadata, nil - }, - FileResolver: protoFiles, - }) -} - -// NewTextualWithBankKeeper creates a new Textual struct using the given -// BankKeeper to retrieve coin metadata. -// -// Note: Once we switch to ADR-033, and keepers become ADR-033 clients to each -// other, this function could probably be deprecated in favor of -// `NewTextualWithGRPCConn`. -func NewTextualWithBankKeeper(bk BankKeeper) (*textual.SignModeHandler, error) { - protoFiles, err := gogoproto.MergedRegistry() - if err != nil { - return nil, err - } - - return textual.NewSignModeHandler(textual.SignModeOptions{ - CoinMetadataQuerier: func(ctx context.Context, denom string) (*bankv1beta1.Metadata, error) { - res, err := bk.DenomMetadata(ctx, &types.QueryDenomMetadataRequest{Denom: denom}) - if err != nil { - return nil, metadataExists(err) - } - - m := &bankv1beta1.Metadata{ - Base: res.Metadata.Base, - Display: res.Metadata.Display, - // fields below are not strictly needed by Textual - // but added here for completeness. - Description: res.Metadata.Description, - Name: res.Metadata.Name, - Symbol: res.Metadata.Symbol, - Uri: res.Metadata.URI, - UriHash: res.Metadata.URIHash, - } - m.DenomUnits = make([]*bankv1beta1.DenomUnit, len(res.Metadata.DenomUnits)) - for i, d := range res.Metadata.DenomUnits { - m.DenomUnits[i] = &bankv1beta1.DenomUnit{ - Denom: d.Denom, - Exponent: d.Exponent, - Aliases: d.Aliases, - } - } - - return m, nil - }, - FileResolver: protoFiles, - }) -} - -// metadataExists parses the error, and only propagates the error if it's -// different than a "not found" error. -func metadataExists(err error) error { - status, ok := grpcstatus.FromError(err) - if !ok { - return err - } - - // This means we didn't find any metadata for this denom. Returning - // empty metadata. - if status.Code() == codes.NotFound { - return nil - } - - return err -} diff --git a/x/auth/tx/direct_test.go b/x/auth/tx/direct_test.go index 22309639656e..09365541ee63 100644 --- a/x/auth/tx/direct_test.go +++ b/x/auth/tx/direct_test.go @@ -1,6 +1,7 @@ package tx import ( + "context" "fmt" "testing" @@ -64,9 +65,10 @@ func TestDirectModeHandler(t *testing.T) { require.NoError(t, err) t.Log("verify modes and default-mode") - modeHandler := txConfig.SignModeHandler() - require.Equal(t, modeHandler.DefaultMode(), signingtypes.SignMode_SIGN_MODE_DIRECT) - require.Len(t, modeHandler.Modes(), 1) + defaultSignMode, err := signing.APISignModeToInternal(txConfig.SignModeHandler().DefaultMode()) + require.NoError(t, err) + require.Equal(t, defaultSignMode, signingtypes.SignMode_SIGN_MODE_DIRECT) + require.Len(t, txConfig.SignModeHandler().SupportedModes(), 1) signingData := signing.SignerData{ Address: addr.String(), @@ -75,8 +77,9 @@ func TestDirectModeHandler(t *testing.T) { PubKey: pubkey, } - signBytes, err := modeHandler.GetSignBytes(signingtypes.SignMode_SIGN_MODE_DIRECT, signingData, txBuilder.GetTx()) - + signBytes, err := signing.GetSignBytesAdapter( + context.Background(), txConfig.TxEncoder(), txConfig.SignModeHandler(), defaultSignMode, signingData, + txBuilder.GetTx()) require.NoError(t, err) require.NotNil(t, signBytes) @@ -120,7 +123,9 @@ func TestDirectModeHandler(t *testing.T) { require.NoError(t, err) err = txBuilder.SetSignatures(sig) require.NoError(t, err) - signBytes, err = modeHandler.GetSignBytes(signingtypes.SignMode_SIGN_MODE_DIRECT, signingData, txBuilder.GetTx()) + signBytes, err = signing.GetSignBytesAdapter( + context.Background(), txConfig.TxEncoder(), txConfig.SignModeHandler(), defaultSignMode, signingData, + txBuilder.GetTx()) require.NoError(t, err) require.Equal(t, expectedSignBytes, signBytes) diff --git a/x/auth/tx/legacy_amino_json.go b/x/auth/tx/legacy_amino_json.go index c920c96bd767..1be6ce542f81 100644 --- a/x/auth/tx/legacy_amino_json.go +++ b/x/auth/tx/legacy_amino_json.go @@ -20,6 +20,12 @@ var _ signing.SignModeHandler = signModeLegacyAminoJSONHandler{} // SignModeHandler. type signModeLegacyAminoJSONHandler struct{} +// NewSignModeLegacyAminoJSONHandler returns a new signModeLegacyAminoJSONHandler. +// Note: The public constructor is only used for testing. +func NewSignModeLegacyAminoJSONHandler() signing.SignModeHandler { + return signModeLegacyAminoJSONHandler{} +} + func (s signModeLegacyAminoJSONHandler) DefaultMode() signingtypes.SignMode { return signingtypes.SignMode_SIGN_MODE_LEGACY_AMINO_JSON } diff --git a/x/auth/tx/mode_handler.go b/x/auth/tx/mode_handler.go index 25a2612b49b7..ff0b3440a4bc 100644 --- a/x/auth/tx/mode_handler.go +++ b/x/auth/tx/mode_handler.go @@ -1,14 +1,25 @@ package tx import ( - "fmt" - + txsigning "cosmossdk.io/x/tx/signing" + "cosmossdk.io/x/tx/signing/aminojson" + "cosmossdk.io/x/tx/signing/direct" + "cosmossdk.io/x/tx/signing/directaux" "cosmossdk.io/x/tx/signing/textual" - signingtypes "github.com/cosmos/cosmos-sdk/types/tx/signing" - "github.com/cosmos/cosmos-sdk/x/auth/signing" ) +type SignModeOptions struct { + // Textual are options for SIGN_MODE_TEXTUAL + Textual *textual.SignModeOptions + // DirectAux are options for SIGN_MODE_DIRECT_AUX + DirectAux *directaux.SignModeHandlerOptions + // AminoJSON are options for SIGN_MODE_LEGACY_AMINO_JSON + AminoJSON *aminojson.SignModeHandlerOptions + // Direct is the SignModeHandler for SIGN_MODE_DIRECT since it takes options + Direct *direct.SignModeHandler +} + // DefaultSignModes are the default sign modes enabled for protobuf transactions. var DefaultSignModes = []signingtypes.SignMode{ signingtypes.SignMode_SIGN_MODE_DIRECT, @@ -24,36 +35,31 @@ var DefaultSignModes = []signingtypes.SignMode{ // makeSignModeHandler returns the default protobuf SignModeHandler supporting // SIGN_MODE_DIRECT, SIGN_MODE_DIRECT_AUX and SIGN_MODE_LEGACY_AMINO_JSON. -func makeSignModeHandler(modes []signingtypes.SignMode, txt *textual.SignModeHandler, customSignModes ...signing.SignModeHandler) signing.SignModeHandler { - if len(modes) < 1 { - panic(fmt.Errorf("no sign modes enabled")) +func makeSignModeHandler( + opts SignModeOptions, + customSignModes ...txsigning.SignModeHandler, +) *txsigning.HandlerMap { + var handlers []txsigning.SignModeHandler + if opts.Direct != nil { + handlers = append(handlers, opts.Direct) } - - handlers := make([]signing.SignModeHandler, len(modes)+len(customSignModes)) - - // handle cosmos-sdk defined sign modes - for i, mode := range modes { - switch mode { - case signingtypes.SignMode_SIGN_MODE_DIRECT: - handlers[i] = signModeDirectHandler{} - case signingtypes.SignMode_SIGN_MODE_LEGACY_AMINO_JSON: - handlers[i] = signModeLegacyAminoJSONHandler{} - case signingtypes.SignMode_SIGN_MODE_TEXTUAL: - handlers[i] = signModeTextualHandler{t: *txt} - case signingtypes.SignMode_SIGN_MODE_DIRECT_AUX: - handlers[i] = signModeDirectAuxHandler{} - default: - panic(fmt.Errorf("unsupported sign mode %+v", mode)) + if opts.Textual != nil { + h, err := textual.NewSignModeHandler(*opts.Textual) + if err != nil { + panic(err) } + handlers = append(handlers, h) } - - // add custom sign modes - for i, handler := range customSignModes { - handlers[i+len(modes)] = handler + if opts.DirectAux != nil { + h, err := directaux.NewSignModeHandler(*opts.DirectAux) + if err != nil { + panic(err) + } + handlers = append(handlers, h) } - - return signing.NewSignModeHandlerMap( - modes[0], - handlers, - ) + if opts.AminoJSON != nil { + handlers = append(handlers, aminojson.NewSignModeHandler(*opts.AminoJSON)) + } + handlers = append(handlers, customSignModes...) + return txsigning.NewHandlerMap(handlers...) } diff --git a/x/auth/tx/service.go b/x/auth/tx/service.go index c4bfb2b66582..9f4d56a93164 100644 --- a/x/auth/tx/service.go +++ b/x/auth/tx/service.go @@ -6,7 +6,7 @@ import ( "strings" gogogrpc "github.com/cosmos/gogoproto/grpc" - "github.com/golang/protobuf/proto" //nolint:staticcheck + "github.com/golang/protobuf/proto" //nolint:staticcheck // keep legacy for now "github.com/grpc-ecosystem/grpc-gateway/runtime" "google.golang.org/grpc/codes" "google.golang.org/grpc/status" diff --git a/x/auth/tx/testutil/suite.go b/x/auth/tx/testutil/suite.go index 924f2366ca3b..ab9ab69096d6 100644 --- a/x/auth/tx/testutil/suite.go +++ b/x/auth/tx/testutil/suite.go @@ -2,9 +2,11 @@ package testutil import ( "bytes" + "context" "github.com/stretchr/testify/suite" + signingv1beta1 "cosmossdk.io/api/cosmos/tx/signing/v1beta1" "github.com/cosmos/cosmos-sdk/client" kmultisig "github.com/cosmos/cosmos-sdk/crypto/keys/multisig" cryptotypes "github.com/cosmos/cosmos-sdk/crypto/types" @@ -96,17 +98,19 @@ func (s *TxConfigTestSuite) TestTxBuilderSetSignatures() { s.Require().Error(txBuilder.GetTx().ValidateBasic()) signModeHandler := s.TxConfig.SignModeHandler() - s.Require().Contains(signModeHandler.Modes(), signModeHandler.DefaultMode()) + s.Require().Contains(signModeHandler.SupportedModes(), signingv1beta1.SignMode_SIGN_MODE_DIRECT) + defaultSignMode, err := signing.APISignModeToInternal(s.TxConfig.SignModeHandler().DefaultMode()) + s.Require().NoError(err) // set SignatureV2 without actual signature bytes seq1 := uint64(2) // Arbitrary account sequence - sigData1 := &signingtypes.SingleSignatureData{SignMode: signModeHandler.DefaultMode()} + sigData1 := &signingtypes.SingleSignatureData{SignMode: defaultSignMode} sig1 := signingtypes.SignatureV2{PubKey: pubkey, Data: sigData1, Sequence: seq1} mseq := uint64(4) // Arbitrary account sequence msigData := multisig.NewMultisig(2) - multisig.AddSignature(msigData, &signingtypes.SingleSignatureData{SignMode: signModeHandler.DefaultMode()}, 0) - multisig.AddSignature(msigData, &signingtypes.SingleSignatureData{SignMode: signModeHandler.DefaultMode()}, 1) + multisig.AddSignature(msigData, &signingtypes.SingleSignatureData{SignMode: defaultSignMode}, 0) + multisig.AddSignature(msigData, &signingtypes.SingleSignatureData{SignMode: defaultSignMode}, 1) msig := signingtypes.SignatureV2{PubKey: multisigPk, Data: msigData, Sequence: mseq} // fail validation without required signers @@ -134,7 +138,8 @@ func (s *TxConfigTestSuite) TestTxBuilderSetSignatures() { Sequence: seq1, PubKey: pubkey, } - signBytes, err := signModeHandler.GetSignBytes(signModeHandler.DefaultMode(), signerData, sigTx) + signBytes, err := signing.GetSignBytesAdapter(context.Background(), s.TxConfig.TxEncoder(), + s.TxConfig.SignModeHandler(), defaultSignMode, signerData, sigTx) s.Require().NoError(err) sigBz, err := privKey.Sign(signBytes) s.Require().NoError(err) @@ -146,7 +151,8 @@ func (s *TxConfigTestSuite) TestTxBuilderSetSignatures() { Sequence: mseq, PubKey: multisigPk, } - mSignBytes, err := signModeHandler.GetSignBytes(signModeHandler.DefaultMode(), signerData, sigTx) + mSignBytes, err := signing.GetSignBytesAdapter(context.Background(), s.TxConfig.TxEncoder(), + s.TxConfig.SignModeHandler(), defaultSignMode, signerData, sigTx) s.Require().NoError(err) mSigBz1, err := privKey.Sign(mSignBytes) s.Require().NoError(err) @@ -154,10 +160,10 @@ func (s *TxConfigTestSuite) TestTxBuilderSetSignatures() { s.Require().NoError(err) msigData = multisig.NewMultisig(2) multisig.AddSignature(msigData, &signingtypes.SingleSignatureData{ - SignMode: signModeHandler.DefaultMode(), Signature: mSigBz1, + SignMode: defaultSignMode, Signature: mSigBz1, }, 0) multisig.AddSignature(msigData, &signingtypes.SingleSignatureData{ - SignMode: signModeHandler.DefaultMode(), Signature: mSigBz2, + SignMode: defaultSignMode, Signature: mSigBz2, }, 0) // set signature diff --git a/x/auth/tx/textual.go b/x/auth/tx/textual.go index 7553f03596c7..a804280adfb5 100644 --- a/x/auth/tx/textual.go +++ b/x/auth/tx/textual.go @@ -79,7 +79,7 @@ func (h signModeTextualHandler) GetSignBytesWithContext(ctx context.Context, mod return h.t.GetSignBytes(ctx, txsigning.SignerData{ Address: data.Address, - ChainId: data.ChainID, + ChainID: data.ChainID, AccountNumber: data.AccountNumber, Sequence: data.Sequence, PubKey: &anypb.Any{ diff --git a/x/auth/types/account.go b/x/auth/types/account.go index 8026bee1c19e..9345d819d240 100644 --- a/x/auth/types/account.go +++ b/x/auth/types/account.go @@ -23,9 +23,7 @@ var ( _ sdk.ModuleAccountI = (*ModuleAccount)(nil) ) -// NewBaseAccount creates a new BaseAccount object -// -//nolint:interfacer +// NewBaseAccount creates a new BaseAccount object. func NewBaseAccount(address sdk.AccAddress, pubKey cryptotypes.PubKey, accountNumber, sequence uint64) *BaseAccount { acc := &BaseAccount{ Address: address.String(), diff --git a/x/auth/types/credentials.go b/x/auth/types/credentials.go index 6d37c98b30d2..4c63fc8d8c41 100644 --- a/x/auth/types/credentials.go +++ b/x/auth/types/credentials.go @@ -27,7 +27,6 @@ func NewBaseAccountWithPubKey(pubkey cryptotypes.PubKey) (*BaseAccount, error) { return baseAccount, nil } -//nolint:gosec // this isn't an hardcoded credential const ModuleCredentialType = "ModuleCredential" var _ cryptotypes.PubKey = &ModuleCredential{} @@ -55,7 +54,7 @@ func (m *ModuleCredential) Bytes() []byte { } // VerifySignature returns always false, making the account unclaimable -func (m *ModuleCredential) VerifySignature(_ []byte, _ []byte) bool { +func (m *ModuleCredential) VerifySignature(_, _ []byte) bool { return false } diff --git a/x/auth/types/keys.go b/x/auth/types/keys.go index 7dc4903ba34e..e8e9d70e01fd 100644 --- a/x/auth/types/keys.go +++ b/x/auth/types/keys.go @@ -1,6 +1,7 @@ package types import ( + "cosmossdk.io/collections" sdk "github.com/cosmos/cosmos-sdk/types" ) @@ -17,13 +18,14 @@ const ( var ( // ParamsKey is the prefix for params key - ParamsKey = []byte{0x00} + ParamsKey = collections.NewPrefix(0) // AddressStoreKeyPrefix prefix for account-by-address store AddressStoreKeyPrefix = []byte{0x01} - // param key for global account number - GlobalAccountNumberKey = []byte("globalAccountNumber") + // GlobalAccountNumberKey identifies the prefix where the monotonically increasing + // account number is stored. + GlobalAccountNumberKey = collections.NewPrefix(2) // AccountNumberStoreKeyPrefix prefix for account-by-id store AccountNumberStoreKeyPrefix = []byte("accountNumber") diff --git a/x/auth/types/msgs.go b/x/auth/types/msgs.go index 8774549e9ae1..df6930d5fd4b 100644 --- a/x/auth/types/msgs.go +++ b/x/auth/types/msgs.go @@ -1,8 +1,6 @@ package types import ( - "cosmossdk.io/errors" - sdk "github.com/cosmos/cosmos-sdk/types" "github.com/cosmos/cosmos-sdk/x/auth/migrations/legacytx" ) @@ -22,16 +20,3 @@ func (msg MsgUpdateParams) GetSigners() []sdk.AccAddress { addr, _ := sdk.AccAddressFromBech32(msg.Authority) return []sdk.AccAddress{addr} } - -// ValidateBasic does a sanity check on the provided data. -func (msg MsgUpdateParams) ValidateBasic() error { - if _, err := sdk.AccAddressFromBech32(msg.Authority); err != nil { - return errors.Wrap(err, "invalid authority address") - } - - if err := msg.Params.Validate(); err != nil { - return err - } - - return nil -} diff --git a/x/auth/vesting/client/cli/test.json b/x/auth/vesting/client/cli/test.json new file mode 100644 index 000000000000..1ed078e28df7 --- /dev/null +++ b/x/auth/vesting/client/cli/test.json @@ -0,0 +1,13 @@ +{ + "start_time": 1625204910, + "period": [ + { + "coins": "10test", + "length_seconds": 2592000 + }, + { + "coins": "10test", + "length_seconds": 2592000 + } + ] +} diff --git a/x/auth/vesting/client/cli/tx.go b/x/auth/vesting/client/cli/tx.go index 3c88d04500fa..0ce6708fd5e6 100644 --- a/x/auth/vesting/client/cli/tx.go +++ b/x/auth/vesting/client/cli/tx.go @@ -2,10 +2,12 @@ package cli import ( "encoding/json" + "errors" "fmt" "os" "strconv" + "cosmossdk.io/core/address" "github.com/spf13/cobra" "github.com/cosmos/cosmos-sdk/client" @@ -21,7 +23,7 @@ const ( ) // GetTxCmd returns vesting module's transaction commands. -func GetTxCmd() *cobra.Command { +func GetTxCmd(ac address.Codec) *cobra.Command { txCmd := &cobra.Command{ Use: types.ModuleName, Short: "Vesting transaction subcommands", @@ -31,9 +33,9 @@ func GetTxCmd() *cobra.Command { } txCmd.AddCommand( - NewMsgCreateVestingAccountCmd(), - NewMsgCreatePermanentLockedAccountCmd(), - NewMsgCreatePeriodicVestingAccountCmd(), + NewMsgCreateVestingAccountCmd(ac), + NewMsgCreatePermanentLockedAccountCmd(ac), + NewMsgCreatePeriodicVestingAccountCmd(ac), ) return txCmd @@ -41,7 +43,7 @@ func GetTxCmd() *cobra.Command { // NewMsgCreateVestingAccountCmd returns a CLI command handler for creating a // MsgCreateVestingAccount transaction. -func NewMsgCreateVestingAccountCmd() *cobra.Command { +func NewMsgCreateVestingAccountCmd(ac address.Codec) *cobra.Command { cmd := &cobra.Command{ Use: "create-vesting-account [to_address] [amount] [end_time]", Short: "Create a new vesting account funded with an allocation of tokens.", @@ -56,11 +58,15 @@ timestamp.`, if err != nil { return err } - toAddr, err := sdk.AccAddressFromBech32(args[0]) + toAddr, err := ac.StringToBytes(args[0]) if err != nil { return err } + if args[1] == "" { + return errors.New("amount is empty") + } + amount, err := sdk.ParseCoinsNormalized(args[1]) if err != nil { return err @@ -74,7 +80,6 @@ timestamp.`, delayed, _ := cmd.Flags().GetBool(FlagDelayed) msg := types.NewMsgCreateVestingAccount(clientCtx.GetFromAddress(), toAddr, amount, endTime, delayed) - return tx.GenerateOrBroadcastTxCLI(clientCtx, cmd.Flags(), msg) }, } @@ -87,7 +92,7 @@ timestamp.`, // NewMsgCreatePermanentLockedAccountCmd returns a CLI command handler for creating a // MsgCreatePermanentLockedAccount transaction. -func NewMsgCreatePermanentLockedAccountCmd() *cobra.Command { +func NewMsgCreatePermanentLockedAccountCmd(ac address.Codec) *cobra.Command { cmd := &cobra.Command{ Use: "create-permanent-locked-account [to_address] [amount]", Short: "Create a new permanently locked account funded with an allocation of tokens.", @@ -100,18 +105,21 @@ tokens.`, if err != nil { return err } - toAddr, err := sdk.AccAddressFromBech32(args[0]) + toAddr, err := ac.StringToBytes(args[0]) if err != nil { return err } + if args[1] == "" { + return errors.New("amount is empty") + } + amount, err := sdk.ParseCoinsNormalized(args[1]) if err != nil { return err } msg := types.NewMsgCreatePermanentLockedAccount(clientCtx.GetFromAddress(), toAddr, amount) - return tx.GenerateOrBroadcastTxCLI(clientCtx, cmd.Flags(), msg) }, } @@ -133,7 +141,7 @@ type InputPeriod struct { // NewMsgCreatePeriodicVestingAccountCmd returns a CLI command handler for creating a // MsgCreatePeriodicVestingAccountCmd transaction. -func NewMsgCreatePeriodicVestingAccountCmd() *cobra.Command { +func NewMsgCreatePeriodicVestingAccountCmd(ac address.Codec) *cobra.Command { cmd := &cobra.Command{ Use: "create-periodic-vesting-account [to_address] [periods_json_file]", Short: "Create a new vesting account funded with an allocation of tokens.", @@ -161,7 +169,7 @@ func NewMsgCreatePeriodicVestingAccountCmd() *cobra.Command { return err } - toAddr, err := sdk.AccAddressFromBech32(args[0]) + toAddr, err := ac.StringToBytes(args[0]) if err != nil { return err } @@ -190,15 +198,12 @@ func NewMsgCreatePeriodicVestingAccountCmd() *cobra.Command { if p.Length < 0 { return fmt.Errorf("invalid period length of %d in period %d, length must be greater than 0", p.Length, i) } + period := types.Period{Length: p.Length, Amount: amount} periods = append(periods, period) } msg := types.NewMsgCreatePeriodicVestingAccount(clientCtx.GetFromAddress(), toAddr, vestingData.StartTime, periods) - if err := msg.ValidateBasic(); err != nil { - return err - } - return tx.GenerateOrBroadcastTxCLI(clientCtx, cmd.Flags(), msg) }, } diff --git a/x/auth/vesting/client/cli/tx_test.go b/x/auth/vesting/client/cli/tx_test.go new file mode 100644 index 000000000000..f2591446034d --- /dev/null +++ b/x/auth/vesting/client/cli/tx_test.go @@ -0,0 +1,277 @@ +package cli_test + +import ( + "context" + "fmt" + "io" + "testing" + "time" + + sdkmath "cosmossdk.io/math" + rpcclientmock "github.com/cometbft/cometbft/rpc/client/mock" + "github.com/stretchr/testify/suite" + + "github.com/cosmos/cosmos-sdk/client" + "github.com/cosmos/cosmos-sdk/client/flags" + "github.com/cosmos/cosmos-sdk/codec/address" + "github.com/cosmos/cosmos-sdk/crypto/keyring" + svrcmd "github.com/cosmos/cosmos-sdk/server/cmd" + "github.com/cosmos/cosmos-sdk/testutil" + clitestutil "github.com/cosmos/cosmos-sdk/testutil/cli" + sdk "github.com/cosmos/cosmos-sdk/types" + testutilmod "github.com/cosmos/cosmos-sdk/types/module/testutil" + "github.com/cosmos/cosmos-sdk/x/auth/vesting" + "github.com/cosmos/cosmos-sdk/x/auth/vesting/client/cli" +) + +type CLITestSuite struct { + suite.Suite + + kr keyring.Keyring + encCfg testutilmod.TestEncodingConfig + baseCtx client.Context +} + +func TestMigrateTestSuite(t *testing.T) { + suite.Run(t, new(CLITestSuite)) +} + +func (s *CLITestSuite) SetupSuite() { + s.encCfg = testutilmod.MakeTestEncodingConfig(vesting.AppModuleBasic{}) + s.kr = keyring.NewInMemory(s.encCfg.Codec) + s.baseCtx = client.Context{}. + WithKeyring(s.kr). + WithTxConfig(s.encCfg.TxConfig). + WithCodec(s.encCfg.Codec). + WithClient(clitestutil.MockCometRPC{Client: rpcclientmock.Client{}}). + WithAccountRetriever(client.MockAccountRetriever{}). + WithOutput(io.Discard) +} + +func (s *CLITestSuite) TestNewMsgCreateVestingAccountCmd() { + accounts := testutil.CreateKeyringAccounts(s.T(), s.kr, 1) + cmd := cli.NewMsgCreateVestingAccountCmd(address.NewBech32Codec("cosmos")) + cmd.SetOutput(io.Discard) + + extraArgs := []string{ + fmt.Sprintf("--%s=%s", flags.FlagBroadcastMode, flags.BroadcastSync), + fmt.Sprintf("--%s=true", flags.FlagSkipConfirmation), + fmt.Sprintf("--%s=%s", flags.FlagFees, sdk.NewCoins(sdk.NewCoin("photon", sdkmath.NewInt(10))).String()), + fmt.Sprintf("--%s=test-chain", flags.FlagChainID), + fmt.Sprintf("--%s=%s", flags.FlagFrom, accounts[0].Address), + } + + t := time.Date(2033, time.April, 1, 12, 34, 56, 789, time.UTC).Unix() + + testCases := []struct { + name string + ctxGen func() client.Context + from, to sdk.AccAddress + amount sdk.Coins + endTime int64 + extraArgs []string + expectErr bool + }{ + { + "valid transaction", + func() client.Context { + return s.baseCtx + }, + accounts[0].Address, + accounts[0].Address, + sdk.NewCoins( + sdk.NewCoin("stake", sdkmath.NewInt(10)), + sdk.NewCoin("photon", sdkmath.NewInt(40)), + ), + t, + extraArgs, + false, + }, + { + "invalid to Address", + func() client.Context { + return s.baseCtx + }, + accounts[0].Address, + sdk.AccAddress{}, + sdk.NewCoins( + sdk.NewCoin("stake", sdkmath.NewInt(10)), + sdk.NewCoin("photon", sdkmath.NewInt(40)), + ), + t, + extraArgs, + true, + }, + { + "invalid coins", + func() client.Context { + return s.baseCtx + }, + accounts[0].Address, + accounts[0].Address, + nil, + t, + extraArgs, + true, + }, + } + + for _, tc := range testCases { + tc := tc + s.Run(tc.name, func() { + ctx := svrcmd.CreateExecuteContext(context.Background()) + + cmd.SetContext(ctx) + fmt.Println(tc.amount.String()) + cmd.SetArgs(append([]string{tc.to.String(), tc.amount.String(), fmt.Sprint(tc.endTime)}, tc.extraArgs...)) + + s.Require().NoError(client.SetCmdClientContextHandler(tc.ctxGen(), cmd)) + + err := cmd.Execute() + if tc.expectErr { + s.Require().Error(err) + } else { + s.Require().NoError(err) + } + }) + } +} + +func (s *CLITestSuite) TestNewMsgCreatePermanentLockedAccountCmd() { + accounts := testutil.CreateKeyringAccounts(s.T(), s.kr, 1) + cmd := cli.NewMsgCreatePermanentLockedAccountCmd(address.NewBech32Codec("cosmos")) + cmd.SetOutput(io.Discard) + + extraArgs := []string{ + fmt.Sprintf("--%s=%s", flags.FlagBroadcastMode, flags.BroadcastSync), + fmt.Sprintf("--%s=true", flags.FlagSkipConfirmation), + fmt.Sprintf("--%s=%s", flags.FlagFees, sdk.NewCoins(sdk.NewCoin("photon", sdkmath.NewInt(10))).String()), + fmt.Sprintf("--%s=test-chain", flags.FlagChainID), + fmt.Sprintf("--%s=%s", flags.FlagFrom, accounts[0].Address), + } + + testCases := []struct { + name string + ctxGen func() client.Context + to sdk.AccAddress + amount sdk.Coins + extraArgs []string + expectErr bool + }{ + { + "valid transaction", + func() client.Context { + return s.baseCtx + }, + accounts[0].Address, + sdk.NewCoins( + sdk.NewCoin("stake", sdkmath.NewInt(10)), + sdk.NewCoin("photon", sdkmath.NewInt(40)), + ), + extraArgs, + false, + }, + { + "invalid to Address", + func() client.Context { + return s.baseCtx + }, + sdk.AccAddress{}, + sdk.NewCoins( + sdk.NewCoin("stake", sdkmath.NewInt(10)), + sdk.NewCoin("photon", sdkmath.NewInt(40)), + ), + extraArgs, + true, + }, + { + "invalid coins", + func() client.Context { + return s.baseCtx + }, + accounts[0].Address, + nil, + extraArgs, + true, + }, + } + + for _, tc := range testCases { + tc := tc + s.Run(tc.name, func() { + ctx := svrcmd.CreateExecuteContext(context.Background()) + + cmd.SetContext(ctx) + cmd.SetArgs(append([]string{tc.to.String(), tc.amount.String()}, tc.extraArgs...)) + + s.Require().NoError(client.SetCmdClientContextHandler(tc.ctxGen(), cmd)) + + err := cmd.Execute() + if tc.expectErr { + s.Require().Error(err) + } else { + s.Require().NoError(err) + } + }) + } +} + +func (s *CLITestSuite) TestNewMsgCreatePeriodicVestingAccountCmd() { + accounts := testutil.CreateKeyringAccounts(s.T(), s.kr, 1) + cmd := cli.NewMsgCreatePeriodicVestingAccountCmd(address.NewBech32Codec("cosmos")) + cmd.SetOutput(io.Discard) + + extraArgs := []string{ + fmt.Sprintf("--%s=%s", flags.FlagBroadcastMode, flags.BroadcastSync), + fmt.Sprintf("--%s=true", flags.FlagSkipConfirmation), + fmt.Sprintf("--%s=%s", flags.FlagFees, sdk.NewCoins(sdk.NewCoin("photon", sdkmath.NewInt(10))).String()), + fmt.Sprintf("--%s=test-chain", flags.FlagChainID), + fmt.Sprintf("--%s=%s", flags.FlagFrom, accounts[0].Address), + } + + testCases := []struct { + name string + ctxGen func() client.Context + to sdk.AccAddress + extraArgs []string + expectErr bool + }{ + { + "valid transaction", + func() client.Context { + return s.baseCtx + }, + accounts[0].Address, + extraArgs, + false, + }, + { + "invalid to Address", + func() client.Context { + return s.baseCtx + }, + sdk.AccAddress{}, + extraArgs, + true, + }, + } + + for _, tc := range testCases { + tc := tc + s.Run(tc.name, func() { + ctx := svrcmd.CreateExecuteContext(context.Background()) + + cmd.SetContext(ctx) + cmd.SetArgs(append([]string{tc.to.String(), "./test.json"}, tc.extraArgs...)) + + s.Require().NoError(client.SetCmdClientContextHandler(tc.ctxGen(), cmd)) + + err := cmd.Execute() + if tc.expectErr { + s.Require().Error(err) + } else { + s.Require().NoError(err) + } + }) + } +} diff --git a/x/auth/vesting/module.go b/x/auth/vesting/module.go index 18f3ac20119d..4b16397fa2ed 100644 --- a/x/auth/vesting/module.go +++ b/x/auth/vesting/module.go @@ -17,6 +17,7 @@ import ( "github.com/cosmos/cosmos-sdk/types/module" modulev1 "cosmossdk.io/api/cosmos/vesting/module/v1" + "cosmossdk.io/core/address" "cosmossdk.io/core/appmodule" "github.com/cosmos/cosmos-sdk/x/auth/keeper" @@ -32,7 +33,9 @@ var ( // AppModuleBasic defines the basic application module used by the sub-vesting // module. The module itself contain no special logic or state other than message // handling. -type AppModuleBasic struct{} +type AppModuleBasic struct { + ac address.Codec +} // Name returns the module's name. func (AppModuleBasic) Name() string { @@ -62,11 +65,11 @@ func (AppModuleBasic) ValidateGenesis(_ codec.JSONCodec, _ client.TxEncodingConf // RegisterGRPCGatewayRoutes registers the module's gRPC Gateway routes. Currently, this // is a no-op. -func (a AppModuleBasic) RegisterGRPCGatewayRoutes(_ client.Context, _ *gwruntime.ServeMux) {} +func (AppModuleBasic) RegisterGRPCGatewayRoutes(_ client.Context, _ *gwruntime.ServeMux) {} // GetTxCmd returns the root tx command for the auth module. -func (AppModuleBasic) GetTxCmd() *cobra.Command { - return cli.GetTxCmd() +func (ab AppModuleBasic) GetTxCmd() *cobra.Command { + return cli.GetTxCmd(ab.ac) } // GetQueryCmd returns the module's root query command. Currently, this is a no-op. @@ -85,7 +88,7 @@ type AppModule struct { func NewAppModule(ak keeper.AccountKeeper, bk types.BankKeeper) AppModule { return AppModule{ - AppModuleBasic: AppModuleBasic{}, + AppModuleBasic: AppModuleBasic{ac: ak}, accountKeeper: ak, bankKeeper: bk, } @@ -131,23 +134,21 @@ func init() { ) } -//nolint:revive -type VestingInputs struct { +type ModuleInputs struct { depinject.In AccountKeeper keeper.AccountKeeper BankKeeper types.BankKeeper } -//nolint:revive -type VestingOutputs struct { +type ModuleOutputs struct { depinject.Out Module appmodule.AppModule } -func ProvideModule(in VestingInputs) VestingOutputs { +func ProvideModule(in ModuleInputs) ModuleOutputs { m := NewAppModule(in.AccountKeeper, in.BankKeeper) - return VestingOutputs{Module: m} + return ModuleOutputs{Module: m} } diff --git a/x/auth/vesting/msg_server.go b/x/auth/vesting/msg_server.go index c1f9254b3b6b..5664266dfd46 100644 --- a/x/auth/vesting/msg_server.go +++ b/x/auth/vesting/msg_server.go @@ -29,33 +29,39 @@ func NewMsgServerImpl(k keeper.AccountKeeper, bk types.BankKeeper) types.MsgServ var _ types.MsgServer = msgServer{} func (s msgServer) CreateVestingAccount(goCtx context.Context, msg *types.MsgCreateVestingAccount) (*types.MsgCreateVestingAccountResponse, error) { - ctx := sdk.UnwrapSDKContext(goCtx) - ak := s.AccountKeeper - bk := s.BankKeeper - - if err := bk.IsSendEnabledCoins(ctx, msg.Amount...); err != nil { - return nil, err + from, err := s.AccountKeeper.StringToBytes(msg.FromAddress) + if err != nil { + return nil, sdkerrors.ErrInvalidAddress.Wrapf("invalid 'from' address: %s", err) } - from, err := sdk.AccAddressFromBech32(msg.FromAddress) + to, err := s.AccountKeeper.StringToBytes(msg.ToAddress) if err != nil { + return nil, sdkerrors.ErrInvalidAddress.Wrapf("invalid 'to' address: %s", err) + } + + if err := validateAmount(msg.Amount); err != nil { return nil, err } - to, err := sdk.AccAddressFromBech32(msg.ToAddress) - if err != nil { + + if msg.EndTime <= 0 { + return nil, errorsmod.Wrap(sdkerrors.ErrInvalidRequest, "invalid end time") + } + + ctx := sdk.UnwrapSDKContext(goCtx) + if err := s.BankKeeper.IsSendEnabledCoins(ctx, msg.Amount...); err != nil { return nil, err } - if bk.BlockedAddr(to) { + if s.BankKeeper.BlockedAddr(to) { return nil, errorsmod.Wrapf(sdkerrors.ErrUnauthorized, "%s is not allowed to receive funds", msg.ToAddress) } - if acc := ak.GetAccount(ctx, to); acc != nil { + if acc := s.AccountKeeper.GetAccount(ctx, to); acc != nil { return nil, errorsmod.Wrapf(sdkerrors.ErrInvalidRequest, "account %s already exists", msg.ToAddress) } baseAccount := authtypes.NewBaseAccountWithAddress(to) - baseAccount = ak.NewAccount(ctx, baseAccount).(*authtypes.BaseAccount) + baseAccount = s.AccountKeeper.NewAccount(ctx, baseAccount).(*authtypes.BaseAccount) baseVestingAccount := types.NewBaseVestingAccount(baseAccount, msg.Amount.Sort(), msg.EndTime) var vestingAccount sdk.AccountI @@ -65,7 +71,7 @@ func (s msgServer) CreateVestingAccount(goCtx context.Context, msg *types.MsgCre vestingAccount = types.NewContinuousVestingAccountRaw(baseVestingAccount, ctx.BlockTime().Unix()) } - ak.SetAccount(ctx, vestingAccount) + s.AccountKeeper.SetAccount(ctx, vestingAccount) defer func() { telemetry.IncrCounter(1, "new", "account") @@ -81,7 +87,7 @@ func (s msgServer) CreateVestingAccount(goCtx context.Context, msg *types.MsgCre } }() - if err = bk.SendCoins(ctx, from, to, msg.Amount); err != nil { + if err = s.BankKeeper.SendCoins(ctx, from, to, msg.Amount); err != nil { return nil, err } @@ -89,36 +95,38 @@ func (s msgServer) CreateVestingAccount(goCtx context.Context, msg *types.MsgCre } func (s msgServer) CreatePermanentLockedAccount(goCtx context.Context, msg *types.MsgCreatePermanentLockedAccount) (*types.MsgCreatePermanentLockedAccountResponse, error) { - ctx := sdk.UnwrapSDKContext(goCtx) - ak := s.AccountKeeper - bk := s.BankKeeper - - if err := bk.IsSendEnabledCoins(ctx, msg.Amount...); err != nil { - return nil, err + from, err := s.AccountKeeper.StringToBytes(msg.FromAddress) + if err != nil { + return nil, sdkerrors.ErrInvalidAddress.Wrapf("invalid 'from' address: %s", err) } - from, err := sdk.AccAddressFromBech32(msg.FromAddress) + to, err := s.AccountKeeper.StringToBytes(msg.ToAddress) if err != nil { + return nil, sdkerrors.ErrInvalidAddress.Wrapf("invalid 'to' address: %s", err) + } + + if err := validateAmount(msg.Amount); err != nil { return nil, err } - to, err := sdk.AccAddressFromBech32(msg.ToAddress) - if err != nil { + + ctx := sdk.UnwrapSDKContext(goCtx) + if err := s.BankKeeper.IsSendEnabledCoins(ctx, msg.Amount...); err != nil { return nil, err } - if bk.BlockedAddr(to) { + if s.BankKeeper.BlockedAddr(to) { return nil, errorsmod.Wrapf(sdkerrors.ErrUnauthorized, "%s is not allowed to receive funds", msg.ToAddress) } - if acc := ak.GetAccount(ctx, to); acc != nil { + if acc := s.AccountKeeper.GetAccount(ctx, to); acc != nil { return nil, errorsmod.Wrapf(sdkerrors.ErrInvalidRequest, "account %s already exists", msg.ToAddress) } baseAccount := authtypes.NewBaseAccountWithAddress(to) - baseAccount = ak.NewAccount(ctx, baseAccount).(*authtypes.BaseAccount) + baseAccount = s.AccountKeeper.NewAccount(ctx, baseAccount).(*authtypes.BaseAccount) vestingAccount := types.NewPermanentLockedAccount(baseAccount, msg.Amount) - ak.SetAccount(ctx, vestingAccount) + s.AccountKeeper.SetAccount(ctx, vestingAccount) defer func() { telemetry.IncrCounter(1, "new", "account") @@ -134,7 +142,7 @@ func (s msgServer) CreatePermanentLockedAccount(goCtx context.Context, msg *type } }() - if err = bk.SendCoins(ctx, from, to, msg.Amount); err != nil { + if err = s.BankKeeper.SendCoins(ctx, from, to, msg.Amount); err != nil { return nil, err } @@ -142,38 +150,43 @@ func (s msgServer) CreatePermanentLockedAccount(goCtx context.Context, msg *type } func (s msgServer) CreatePeriodicVestingAccount(goCtx context.Context, msg *types.MsgCreatePeriodicVestingAccount) (*types.MsgCreatePeriodicVestingAccountResponse, error) { - ctx := sdk.UnwrapSDKContext(goCtx) - - ak := s.AccountKeeper - bk := s.BankKeeper - - from, err := sdk.AccAddressFromBech32(msg.FromAddress) + from, err := s.AccountKeeper.StringToBytes(msg.FromAddress) if err != nil { - return nil, err + return nil, sdkerrors.ErrInvalidAddress.Wrapf("invalid 'from' address: %s", err) } - to, err := sdk.AccAddressFromBech32(msg.ToAddress) + + to, err := s.AccountKeeper.StringToBytes(msg.ToAddress) if err != nil { - return nil, err + return nil, sdkerrors.ErrInvalidAddress.Wrapf("invalid 'to' address: %s", err) } - if acc := ak.GetAccount(ctx, to); acc != nil { - return nil, errorsmod.Wrapf(sdkerrors.ErrInvalidRequest, "account %s already exists", msg.ToAddress) + if msg.StartTime < 1 { + return nil, errorsmod.Wrapf(sdkerrors.ErrInvalidRequest, "invalid start time of %d, length must be greater than 0", msg.StartTime) } var totalCoins sdk.Coins - for _, period := range msg.VestingPeriods { + for i, period := range msg.VestingPeriods { + if period.Length < 1 { + return nil, errorsmod.Wrapf(sdkerrors.ErrInvalidRequest, "invalid period length of %d in period %d, length must be greater than 0", period.Length, i) + } + totalCoins = totalCoins.Add(period.Amount...) } - if err := bk.IsSendEnabledCoins(ctx, totalCoins...); err != nil { + ctx := sdk.UnwrapSDKContext(goCtx) + if acc := s.AccountKeeper.GetAccount(ctx, to); acc != nil { + return nil, errorsmod.Wrapf(sdkerrors.ErrInvalidRequest, "account %s already exists", msg.ToAddress) + } + + if err := s.BankKeeper.IsSendEnabledCoins(ctx, totalCoins...); err != nil { return nil, err } baseAccount := authtypes.NewBaseAccountWithAddress(to) - baseAccount = ak.NewAccount(ctx, baseAccount).(*authtypes.BaseAccount) + baseAccount = s.AccountKeeper.NewAccount(ctx, baseAccount).(*authtypes.BaseAccount) vestingAccount := types.NewPeriodicVestingAccount(baseAccount, totalCoins.Sort(), msg.StartTime, msg.VestingPeriods) - ak.SetAccount(ctx, vestingAccount) + s.AccountKeeper.SetAccount(ctx, vestingAccount) defer func() { telemetry.IncrCounter(1, "new", "account") @@ -189,9 +202,21 @@ func (s msgServer) CreatePeriodicVestingAccount(goCtx context.Context, msg *type } }() - if err = bk.SendCoins(ctx, from, to, totalCoins); err != nil { + if err = s.BankKeeper.SendCoins(ctx, from, to, totalCoins); err != nil { return nil, err } return &types.MsgCreatePeriodicVestingAccountResponse{}, nil } + +func validateAmount(amount sdk.Coins) error { + if !amount.IsValid() { + return sdkerrors.ErrInvalidCoins.Wrap(amount.String()) + } + + if !amount.IsAllPositive() { + return sdkerrors.ErrInvalidCoins.Wrap(amount.String()) + } + + return nil +} diff --git a/x/auth/vesting/msg_server_test.go b/x/auth/vesting/msg_server_test.go index f5e6fe58213a..2a121271e10a 100644 --- a/x/auth/vesting/msg_server_test.go +++ b/x/auth/vesting/msg_server_test.go @@ -11,6 +11,7 @@ import ( storetypes "cosmossdk.io/store/types" + "github.com/cosmos/cosmos-sdk/runtime" "github.com/cosmos/cosmos-sdk/testutil" sdk "github.com/cosmos/cosmos-sdk/types" moduletestutil "github.com/cosmos/cosmos-sdk/types/module/testutil" @@ -41,6 +42,7 @@ type VestingTestSuite struct { func (s *VestingTestSuite) SetupTest() { key := storetypes.NewKVStoreKey(authtypes.StoreKey) + storeService := runtime.NewKVStoreService(key) testCtx := testutil.DefaultContextWithDB(s.T(), key, storetypes.NewTransientStoreKey("transient_test")) s.ctx = testCtx.Ctx.WithBlockHeader(cmtproto.Header{Time: cmttime.Now()}) encCfg := moduletestutil.MakeTestEncodingConfig() @@ -51,7 +53,7 @@ func (s *VestingTestSuite) SetupTest() { s.bankKeeper = vestingtestutil.NewMockBankKeeper(ctrl) s.accountKeeper = authkeeper.NewAccountKeeper( encCfg.Codec, - key, + storeService, authtypes.ProtoBaseAccount, maccPerms, "cosmos", @@ -70,6 +72,39 @@ func (s *VestingTestSuite) TestCreateVestingAccount() { expErr bool expErrMsg string }{ + "empty from address": { + input: vestingtypes.NewMsgCreateVestingAccount( + []byte{}, + to1Addr, + sdk.Coins{fooCoin}, + time.Now().Unix(), + true, + ), + expErr: true, + expErrMsg: "invalid 'from' address", + }, + "empty to address": { + input: vestingtypes.NewMsgCreateVestingAccount( + fromAddr, + []byte{}, + sdk.Coins{fooCoin}, + time.Now().Unix(), + true, + ), + expErr: true, + expErrMsg: "invalid 'to' address", + }, + "": { + input: vestingtypes.NewMsgCreateVestingAccount( + fromAddr, + to1Addr, + sdk.Coins{fooCoin}, + -10, + true, + ), + expErr: true, + expErrMsg: "invalid end time", + }, "create for existing account": { preRun: func() { toAcc := s.accountKeeper.NewAccountWithAddress(s.ctx, to1Addr) @@ -123,7 +158,9 @@ func (s *VestingTestSuite) TestCreateVestingAccount() { for name, tc := range testCases { s.Run(name, func() { - tc.preRun() + if tc.preRun != nil { + tc.preRun() + } _, err := s.msgServer.CreateVestingAccount(s.ctx, tc.input) if tc.expErr { s.Require().Error(err) @@ -142,6 +179,24 @@ func (s *VestingTestSuite) TestCreatePermanentLockedAccount() { expErr bool expErrMsg string }{ + "empty from address": { + input: vestingtypes.NewMsgCreatePermanentLockedAccount( + []byte{}, + to1Addr, + sdk.Coins{fooCoin}, + ), + expErr: true, + expErrMsg: "invalid 'from' address", + }, + "empty to address": { + input: vestingtypes.NewMsgCreatePermanentLockedAccount( + fromAddr, + []byte{}, + sdk.Coins{fooCoin}, + ), + expErr: true, + expErrMsg: "invalid 'to' address", + }, "create for existing account": { preRun: func() { toAcc := s.accountKeeper.NewAccountWithAddress(s.ctx, to1Addr) @@ -175,7 +230,10 @@ func (s *VestingTestSuite) TestCreatePermanentLockedAccount() { for name, tc := range testCases { s.Run(name, func() { - tc.preRun() + if tc.preRun != nil { + tc.preRun() + } + _, err := s.msgServer.CreatePermanentLockedAccount(s.ctx, tc.input) if tc.expErr { s.Require().Error(err) @@ -195,6 +253,70 @@ func (s *VestingTestSuite) TestCreatePeriodicVestingAccount() { expErr bool expErrMsg string }{ + { + name: "empty from address", + input: vestingtypes.NewMsgCreatePeriodicVestingAccount( + []byte{}, + to1Addr, + time.Now().Unix(), + []vestingtypes.Period{ + { + Length: 10, + Amount: sdk.NewCoins(periodCoin), + }, + }, + ), + expErr: true, + expErrMsg: "invalid 'from' address", + }, + { + name: "empty to address", + input: vestingtypes.NewMsgCreatePeriodicVestingAccount( + fromAddr, + []byte{}, + time.Now().Unix(), + []vestingtypes.Period{ + { + Length: 10, + Amount: sdk.NewCoins(periodCoin), + }, + }, + ), + expErr: true, + expErrMsg: "invalid 'to' address", + }, + { + name: "invalid start time", + input: vestingtypes.NewMsgCreatePeriodicVestingAccount( + fromAddr, + to1Addr, + 0, + []vestingtypes.Period{ + { + Length: 10, + Amount: sdk.NewCoins(periodCoin), + }, + }, + ), + expErr: true, + expErrMsg: "invalid start time", + }, + { + name: "invalid period", + input: vestingtypes.NewMsgCreatePeriodicVestingAccount( + fromAddr, + to1Addr, + time.Now().Unix(), + []vestingtypes.Period{ + { + Length: 0, + Amount: sdk.NewCoins(periodCoin), + }, + }, + ), + expErr: true, + expErrMsg: "invalid period", + }, { name: "create for existing account", preRun: func() { @@ -243,7 +365,9 @@ func (s *VestingTestSuite) TestCreatePeriodicVestingAccount() { for _, tc := range testCases { s.Run(tc.name, func() { - tc.preRun() + if tc.preRun != nil { + tc.preRun() + } _, err := s.msgServer.CreatePeriodicVestingAccount(s.ctx, tc.input) if tc.expErr { s.Require().Error(err) diff --git a/x/auth/vesting/types/expected_keepers.go b/x/auth/vesting/types/expected_keepers.go index 5705eea30baf..6818f5094bb9 100644 --- a/x/auth/vesting/types/expected_keepers.go +++ b/x/auth/vesting/types/expected_keepers.go @@ -8,6 +8,6 @@ import ( // for creating vesting accounts with funds. type BankKeeper interface { IsSendEnabledCoins(ctx sdk.Context, coins ...sdk.Coin) error - SendCoins(ctx sdk.Context, fromAddr sdk.AccAddress, toAddr sdk.AccAddress, amt sdk.Coins) error + SendCoins(ctx sdk.Context, fromAddr, toAddr sdk.AccAddress, amt sdk.Coins) error BlockedAddr(addr sdk.AccAddress) bool } diff --git a/x/auth/vesting/types/msgs.go b/x/auth/vesting/types/msgs.go index 4bd31fdb9afc..34732a96891b 100644 --- a/x/auth/vesting/types/msgs.go +++ b/x/auth/vesting/types/msgs.go @@ -1,12 +1,7 @@ package types import ( - "fmt" - - errorsmod "cosmossdk.io/errors" - sdk "github.com/cosmos/cosmos-sdk/types" - sdkerrors "github.com/cosmos/cosmos-sdk/types/errors" "github.com/cosmos/cosmos-sdk/x/auth/migrations/legacytx" ) @@ -21,8 +16,6 @@ var ( ) // NewMsgCreateVestingAccount returns a reference to a new MsgCreateVestingAccount. -// -//nolint:interfacer func NewMsgCreateVestingAccount(fromAddr, toAddr sdk.AccAddress, amount sdk.Coins, endTime int64, delayed bool) *MsgCreateVestingAccount { return &MsgCreateVestingAccount{ FromAddress: fromAddr.String(), @@ -33,30 +26,6 @@ func NewMsgCreateVestingAccount(fromAddr, toAddr sdk.AccAddress, amount sdk.Coin } } -// ValidateBasic Implements Msg. -func (msg MsgCreateVestingAccount) ValidateBasic() error { - if _, err := sdk.AccAddressFromBech32(msg.FromAddress); err != nil { - return sdkerrors.ErrInvalidAddress.Wrapf("invalid 'from' address: %s", err) - } - if _, err := sdk.AccAddressFromBech32(msg.ToAddress); err != nil { - return sdkerrors.ErrInvalidAddress.Wrapf("invalid 'to' address: %s", err) - } - - if !msg.Amount.IsValid() { - return errorsmod.Wrap(sdkerrors.ErrInvalidCoins, msg.Amount.String()) - } - - if !msg.Amount.IsAllPositive() { - return errorsmod.Wrap(sdkerrors.ErrInvalidCoins, msg.Amount.String()) - } - - if msg.EndTime <= 0 { - return errorsmod.Wrap(sdkerrors.ErrInvalidRequest, "invalid end time") - } - - return nil -} - // GetSignBytes returns the bytes all expected signers must sign over for a // MsgCreateVestingAccount. func (msg MsgCreateVestingAccount) GetSignBytes() []byte { @@ -70,8 +39,6 @@ func (msg MsgCreateVestingAccount) GetSigners() []sdk.AccAddress { } // NewMsgCreatePermanentLockedAccount returns a reference to a new MsgCreatePermanentLockedAccount. -// -//nolint:interfacer func NewMsgCreatePermanentLockedAccount(fromAddr, toAddr sdk.AccAddress, amount sdk.Coins) *MsgCreatePermanentLockedAccount { return &MsgCreatePermanentLockedAccount{ FromAddress: fromAddr.String(), @@ -80,26 +47,6 @@ func NewMsgCreatePermanentLockedAccount(fromAddr, toAddr sdk.AccAddress, amount } } -// ValidateBasic Implements Msg. -func (msg MsgCreatePermanentLockedAccount) ValidateBasic() error { - if _, err := sdk.AccAddressFromBech32(msg.FromAddress); err != nil { - return sdkerrors.ErrInvalidAddress.Wrapf("invalid sender address: %s", err) - } - if _, err := sdk.AccAddressFromBech32(msg.ToAddress); err != nil { - return sdkerrors.ErrInvalidAddress.Wrapf("invalid recipient address: %s", err) - } - - if !msg.Amount.IsValid() { - return sdkerrors.ErrInvalidCoins.Wrap(msg.Amount.String()) - } - - if !msg.Amount.IsAllPositive() { - return sdkerrors.ErrInvalidCoins.Wrap(msg.Amount.String()) - } - - return nil -} - // GetSignBytes returns the bytes all expected signers must sign over for a // MsgCreatePermanentLockedAccount. func (msg MsgCreatePermanentLockedAccount) GetSignBytes() []byte { @@ -113,8 +60,6 @@ func (msg MsgCreatePermanentLockedAccount) GetSigners() []sdk.AccAddress { } // NewMsgCreatePeriodicVestingAccount returns a reference to a new MsgCreatePeriodicVestingAccount. -// -//nolint:interfacer func NewMsgCreatePeriodicVestingAccount(fromAddr, toAddr sdk.AccAddress, startTime int64, periods []Period) *MsgCreatePeriodicVestingAccount { return &MsgCreatePeriodicVestingAccount{ FromAddress: fromAddr.String(), @@ -138,34 +83,3 @@ func (msg MsgCreatePeriodicVestingAccount) GetSigners() []sdk.AccAddress { func (msg MsgCreatePeriodicVestingAccount) GetSignBytes() []byte { return sdk.MustSortJSON(ModuleCdc.MustMarshalJSON(&msg)) } - -// ValidateBasic Implements Msg. -func (msg MsgCreatePeriodicVestingAccount) ValidateBasic() error { - from, err := sdk.AccAddressFromBech32(msg.FromAddress) - if err != nil { - return err - } - to, err := sdk.AccAddressFromBech32(msg.ToAddress) - if err != nil { - return err - } - if err := sdk.VerifyAddressFormat(from); err != nil { - return errorsmod.Wrapf(sdkerrors.ErrInvalidAddress, "invalid sender address: %s", err) - } - - if err := sdk.VerifyAddressFormat(to); err != nil { - return errorsmod.Wrapf(sdkerrors.ErrInvalidAddress, "invalid recipient address: %s", err) - } - - if msg.StartTime < 1 { - return fmt.Errorf("invalid start time of %d, length must be greater than 0", msg.StartTime) - } - - for i, period := range msg.VestingPeriods { - if period.Length < 1 { - return fmt.Errorf("invalid period length of %d in period %d, length must be greater than 0", period.Length, i) - } - } - - return nil -} diff --git a/x/auth/vesting/types/vesting_account_test.go b/x/auth/vesting/types/vesting_account_test.go index 46502aff0f41..502416f6522a 100644 --- a/x/auth/vesting/types/vesting_account_test.go +++ b/x/auth/vesting/types/vesting_account_test.go @@ -12,6 +12,7 @@ import ( storetypes "cosmossdk.io/store/types" "github.com/cosmos/cosmos-sdk/crypto/keys/secp256k1" + "github.com/cosmos/cosmos-sdk/runtime" "github.com/cosmos/cosmos-sdk/testutil" "github.com/cosmos/cosmos-sdk/testutil/testdata" sdk "github.com/cosmos/cosmos-sdk/types" @@ -39,6 +40,7 @@ func (s *VestingAccountTestSuite) SetupTest() { encCfg := moduletestutil.MakeTestEncodingConfig(vesting.AppModuleBasic{}) key := storetypes.NewKVStoreKey(authtypes.StoreKey) + storeService := runtime.NewKVStoreService(key) testCtx := testutil.DefaultContextWithDB(s.T(), key, storetypes.NewTransientStoreKey("transient_test")) s.ctx = testCtx.Ctx.WithBlockHeader(cmtproto.Header{}) @@ -53,7 +55,7 @@ func (s *VestingAccountTestSuite) SetupTest() { s.accountKeeper = keeper.NewAccountKeeper( encCfg.Codec, - key, + storeService, authtypes.ProtoBaseAccount, maccPerms, "cosmos", diff --git a/x/authz/authorization_grant.go b/x/authz/authorization_grant.go index edf74f0f6c42..bc331885c930 100644 --- a/x/authz/authorization_grant.go +++ b/x/authz/authorization_grant.go @@ -53,6 +53,10 @@ func (g Grant) GetAuthorization() (Authorization, error) { } func (g Grant) ValidateBasic() error { + if g.Authorization == nil { + return sdkerrors.ErrInvalidType.Wrap("authorization is nil") + } + av := g.Authorization.GetCachedValue() a, ok := av.(Authorization) if !ok { diff --git a/x/authz/client/cli/query.go b/x/authz/client/cli/query.go index 62e40b290580..4e244c348aca 100644 --- a/x/authz/client/cli/query.go +++ b/x/authz/client/cli/query.go @@ -4,18 +4,18 @@ import ( "fmt" "strings" + "cosmossdk.io/core/address" "github.com/spf13/cobra" "github.com/cosmos/cosmos-sdk/client" "github.com/cosmos/cosmos-sdk/client/flags" - sdk "github.com/cosmos/cosmos-sdk/types" "github.com/cosmos/cosmos-sdk/version" "github.com/cosmos/cosmos-sdk/x/authz" bank "github.com/cosmos/cosmos-sdk/x/bank/types" ) // GetQueryCmd returns the cli query commands for this module -func GetQueryCmd() *cobra.Command { +func GetQueryCmd(ac address.Codec) *cobra.Command { authorizationQueryCmd := &cobra.Command{ Use: authz.ModuleName, Short: "Querying commands for the authz module", @@ -26,16 +26,16 @@ func GetQueryCmd() *cobra.Command { } authorizationQueryCmd.AddCommand( - GetCmdQueryGrants(), - GetQueryGranterGrants(), - GetQueryGranteeGrants(), + GetCmdQueryGrants(ac), + GetQueryGranterGrants(ac), + GetQueryGranteeGrants(ac), ) return authorizationQueryCmd } // GetCmdQueryGrants implements the query authorization command. -func GetCmdQueryGrants() *cobra.Command { +func GetCmdQueryGrants(ac address.Codec) *cobra.Command { cmd := &cobra.Command{ Use: "grants [granter-addr] [grantee-addr] [msg-type-url]?", Args: cobra.RangeArgs(2, 3), @@ -57,11 +57,11 @@ $ %s query %s grants cosmos1skjw.. cosmos1skjwj.. %s } queryClient := authz.NewQueryClient(clientCtx) - granter, err := sdk.AccAddressFromBech32(args[0]) + _, err = ac.StringToBytes(args[0]) if err != nil { return err } - grantee, err := sdk.AccAddressFromBech32(args[1]) + _, err = ac.StringToBytes(args[1]) if err != nil { return err } @@ -77,8 +77,8 @@ $ %s query %s grants cosmos1skjw.. cosmos1skjwj.. %s res, err := queryClient.Grants( cmd.Context(), &authz.QueryGrantsRequest{ - Granter: granter.String(), - Grantee: grantee.String(), + Granter: args[0], + Grantee: args[1], MsgTypeUrl: msgAuthorized, Pagination: pageReq, }, @@ -96,7 +96,7 @@ $ %s query %s grants cosmos1skjw.. cosmos1skjwj.. %s } // GetQueryGranterGrants returns cmd to query for all grants for a granter. -func GetQueryGranterGrants() *cobra.Command { +func GetQueryGranterGrants(ac address.Codec) *cobra.Command { cmd := &cobra.Command{ Use: "grants-by-granter [granter-addr]", Args: cobra.ExactArgs(1), @@ -114,7 +114,7 @@ $ %s q %s grants-by-granter cosmos1skj.. return err } - granter, err := sdk.AccAddressFromBech32(args[0]) + _, err = ac.StringToBytes(args[0]) if err != nil { return err } @@ -128,7 +128,7 @@ $ %s q %s grants-by-granter cosmos1skj.. res, err := queryClient.GranterGrants( cmd.Context(), &authz.QueryGranterGrantsRequest{ - Granter: granter.String(), + Granter: args[0], Pagination: pageReq, }, ) @@ -145,7 +145,7 @@ $ %s q %s grants-by-granter cosmos1skj.. } // GetQueryGranteeGrants returns cmd to query for all grants for a grantee. -func GetQueryGranteeGrants() *cobra.Command { +func GetQueryGranteeGrants(ac address.Codec) *cobra.Command { cmd := &cobra.Command{ Use: "grants-by-grantee [grantee-addr]", Args: cobra.ExactArgs(1), @@ -163,7 +163,7 @@ $ %s q %s grants-by-grantee cosmos1skj.. return err } - grantee, err := sdk.AccAddressFromBech32(args[0]) + _, err = ac.StringToBytes(args[0]) if err != nil { return err } @@ -177,7 +177,7 @@ $ %s q %s grants-by-grantee cosmos1skj.. res, err := queryClient.GranteeGrants( cmd.Context(), &authz.QueryGranteeGrantsRequest{ - Grantee: grantee.String(), + Grantee: args[0], Pagination: pageReq, }, ) diff --git a/x/authz/client/cli/query_test.go b/x/authz/client/cli/query_test.go index cc88b90a876b..8ee965101e68 100644 --- a/x/authz/client/cli/query_test.go +++ b/x/authz/client/cli/query_test.go @@ -4,7 +4,10 @@ import ( "fmt" "time" + sdkmath "cosmossdk.io/math" + "github.com/cosmos/cosmos-sdk/client/flags" + addresscodec "github.com/cosmos/cosmos-sdk/codec/address" "github.com/cosmos/cosmos-sdk/testutil" clitestutil "github.com/cosmos/cosmos-sdk/testutil/cli" sdk "github.com/cosmos/cosmos-sdk/types" @@ -29,7 +32,7 @@ func (s *CLITestSuite) TestQueryAuthorizations() { fmt.Sprintf("--%s=%s", flags.FlagFrom, val[0].Address), fmt.Sprintf("--%s=%s", flags.FlagBroadcastMode, flags.BroadcastSync), fmt.Sprintf("--%s=%d", cli.FlagExpiration, twoHours), - fmt.Sprintf("--%s=%s", flags.FlagFees, sdk.NewCoins(sdk.NewCoin("stake", sdk.NewInt(10))).String()), + fmt.Sprintf("--%s=%s", flags.FlagFees, sdk.NewCoins(sdk.NewCoin("stake", sdkmath.NewInt(10))).String()), }, ) s.Require().NoError(err) @@ -75,7 +78,7 @@ func (s *CLITestSuite) TestQueryAuthorizations() { tc := tc s.Run(tc.name, func() { - cmd := cli.GetCmdQueryGrants() + cmd := cli.GetCmdQueryGrants(addresscodec.NewBech32Codec("cosmos")) resp, err := clitestutil.ExecTestCLICmd(s.clientCtx, cmd, tc.args) if tc.expectErr { s.Require().Error(err) @@ -106,7 +109,7 @@ func (s *CLITestSuite) TestQueryAuthorization() { fmt.Sprintf("--%s=%s", flags.FlagFrom, val[0].Address), fmt.Sprintf("--%s=%s", flags.FlagBroadcastMode, flags.BroadcastSync), fmt.Sprintf("--%s=%d", cli.FlagExpiration, twoHours), - fmt.Sprintf("--%s=%s", flags.FlagFees, sdk.NewCoins(sdk.NewCoin("stake", sdk.NewInt(10))).String()), + fmt.Sprintf("--%s=%s", flags.FlagFees, sdk.NewCoins(sdk.NewCoin("stake", sdkmath.NewInt(10))).String()), }, ) s.Require().NoError(err) @@ -161,7 +164,7 @@ func (s *CLITestSuite) TestQueryAuthorization() { tc := tc s.Run(tc.name, func() { - cmd := cli.GetCmdQueryGrants() + cmd := cli.GetCmdQueryGrants(addresscodec.NewBech32Codec("cosmos")) _, err := clitestutil.ExecTestCLICmd(s.clientCtx, cmd, tc.args) if tc.expectErr { s.Require().Error(err) @@ -224,7 +227,7 @@ func (s *CLITestSuite) TestQueryGranterGrants() { } for _, tc := range testCases { s.Run(tc.name, func() { - cmd := cli.GetQueryGranterGrants() + cmd := cli.GetQueryGranterGrants(addresscodec.NewBech32Codec("cosmos")) out, err := clitestutil.ExecTestCLICmd(s.clientCtx, cmd, tc.args) if tc.expectErr { require.Error(err) diff --git a/x/authz/client/cli/tx.go b/x/authz/client/cli/tx.go index 0e35e659235d..5f3e5a491aeb 100644 --- a/x/authz/client/cli/tx.go +++ b/x/authz/client/cli/tx.go @@ -6,6 +6,7 @@ import ( "strings" "time" + "cosmossdk.io/core/address" "github.com/spf13/cobra" "github.com/cosmos/cosmos-sdk/client" @@ -33,7 +34,7 @@ const ( ) // GetTxCmd returns the transaction commands for this module -func GetTxCmd() *cobra.Command { +func GetTxCmd(ac address.Codec) *cobra.Command { AuthorizationTxCmd := &cobra.Command{ Use: authz.ModuleName, Short: "Authorization transactions subcommands", @@ -44,8 +45,8 @@ func GetTxCmd() *cobra.Command { } AuthorizationTxCmd.AddCommand( - NewCmdGrantAuthorization(), - NewCmdRevokeAuthorization(), + NewCmdGrantAuthorization(ac), + NewCmdRevokeAuthorization(ac), NewCmdExecAuthorization(), ) @@ -53,7 +54,7 @@ func GetTxCmd() *cobra.Command { } // NewCmdGrantAuthorization returns a CLI command handler for creating a MsgGrant transaction. -func NewCmdGrantAuthorization() *cobra.Command { +func NewCmdGrantAuthorization(ac address.Codec) *cobra.Command { cmd := &cobra.Command{ Use: "grant --from ", Short: "Grant authorization to an address", @@ -72,7 +73,11 @@ Examples: return err } - grantee, err := sdk.AccAddressFromBech32(args[0]) + if strings.EqualFold(args[0], clientCtx.GetFromAddress().String()) { + return errors.New("grantee and granter should be different") + } + + grantee, err := ac.StringToBytes(args[0]) if err != nil { return err } @@ -99,7 +104,16 @@ Examples: return err } - allowed, err := bech32toAccAddresses(allowList) + // check for duplicates + for i := 0; i < len(allowList); i++ { + for j := i + 1; j < len(allowList); j++ { + if allowList[i] == allowList[j] { + return fmt.Errorf("duplicate address %s in allow-list", allowList[i]) + } + } + } + + allowed, err := bech32toAccAddresses(allowList, ac) if err != nil { return err } @@ -214,7 +228,7 @@ func getExpireTime(cmd *cobra.Command) (*time.Time, error) { } // NewCmdRevokeAuthorization returns a CLI command handler for creating a MsgRevoke transaction. -func NewCmdRevokeAuthorization() *cobra.Command { +func NewCmdRevokeAuthorization(ac address.Codec) *cobra.Command { cmd := &cobra.Command{ Use: "revoke [grantee] [msg-type-url] --from=[granter]", Short: "revoke authorization", @@ -231,7 +245,7 @@ Example: return err } - grantee, err := sdk.AccAddressFromBech32(args[0]) + grantee, err := ac.StringToBytes(args[0]) if err != nil { return err } @@ -300,10 +314,10 @@ func bech32toValAddresses(validators []string) ([]sdk.ValAddress, error) { } // bech32toAccAddresses returns []AccAddress from a list of Bech32 string addresses. -func bech32toAccAddresses(accAddrs []string) ([]sdk.AccAddress, error) { +func bech32toAccAddresses(accAddrs []string, ac address.Codec) ([]sdk.AccAddress, error) { addrs := make([]sdk.AccAddress, len(accAddrs)) for i, addr := range accAddrs { - accAddr, err := sdk.AccAddressFromBech32(addr) + accAddr, err := ac.StringToBytes(addr) if err != nil { return nil, err } diff --git a/x/authz/client/cli/tx_test.go b/x/authz/client/cli/tx_test.go index 969129489fa4..b3b57706a908 100644 --- a/x/authz/client/cli/tx_test.go +++ b/x/authz/client/cli/tx_test.go @@ -1,7 +1,6 @@ package cli_test import ( - "bytes" "fmt" "io" "testing" @@ -12,8 +11,12 @@ import ( "github.com/cosmos/gogoproto/proto" "github.com/stretchr/testify/suite" + sdkmath "cosmossdk.io/math" + + _ "cosmossdk.io/api/cosmos/authz/v1beta1" "github.com/cosmos/cosmos-sdk/client" "github.com/cosmos/cosmos-sdk/client/flags" + addresscodec "github.com/cosmos/cosmos-sdk/codec/address" "github.com/cosmos/cosmos-sdk/crypto/hd" "github.com/cosmos/cosmos-sdk/crypto/keyring" "github.com/cosmos/cosmos-sdk/testutil" @@ -64,7 +67,6 @@ func (s *CLITestSuite) SetupSuite() { WithOutput(io.Discard). WithChainID("test-chain") - var outBuf bytes.Buffer ctxGen := func() client.Context { bz, _ := s.encCfg.Codec.Marshal(&sdk.TxResponse{}) c := clitestutil.NewMockCometRPC(abci.ResponseQuery{ @@ -72,7 +74,7 @@ func (s *CLITestSuite) SetupSuite() { }) return s.baseCtx.WithClient(c) } - s.clientCtx = ctxGen().WithOutput(&outBuf) + s.clientCtx = ctxGen() val := testutil.CreateKeyringAccounts(s.T(), s.kr, 1) s.grantee = make([]sdk.AccAddress, 6) @@ -104,7 +106,7 @@ func (s *CLITestSuite) SetupSuite() { fmt.Sprintf("--%s=%s", flags.FlagFrom, val[0].Address.String()), fmt.Sprintf("--%s=true", flags.FlagSkipConfirmation), fmt.Sprintf("--%s=%s", flags.FlagBroadcastMode, flags.BroadcastSync), - fmt.Sprintf("--%s=%s", flags.FlagFees, sdk.NewCoins(sdk.NewCoin(sdk.DefaultBondDenom, sdk.NewInt(10))).String()), + fmt.Sprintf("--%s=%s", flags.FlagFees, sdk.NewCoins(sdk.NewCoin(sdk.DefaultBondDenom, sdkmath.NewInt(10))).String()), fmt.Sprintf("--%s=%d", cli.FlagExpiration, time.Now().Add(time.Minute*time.Duration(120)).Unix()), }) s.Require().NoError(err) @@ -123,7 +125,7 @@ func (s *CLITestSuite) SetupSuite() { fmt.Sprintf("--%s=%s", flags.FlagFrom, val[0].Address.String()), fmt.Sprintf("--%s=true", flags.FlagSkipConfirmation), fmt.Sprintf("--%s=%s", flags.FlagBroadcastMode, flags.BroadcastSync), - fmt.Sprintf("--%s=%s", flags.FlagFees, sdk.NewCoins(sdk.NewCoin(sdk.DefaultBondDenom, sdk.NewInt(10))).String()), + fmt.Sprintf("--%s=%s", flags.FlagFees, sdk.NewCoins(sdk.NewCoin(sdk.DefaultBondDenom, sdkmath.NewInt(10))).String()), fmt.Sprintf("--%s=%d", cli.FlagExpiration, time.Now().Add(time.Minute*time.Duration(120)).Unix()), }) s.Require().NoError(err) @@ -145,12 +147,11 @@ func (s *CLITestSuite) SetupSuite() { fmt.Sprintf("--%s=%s", flags.FlagFrom, val[0].Address.String()), fmt.Sprintf("--%s=%s", flags.FlagBroadcastMode, flags.BroadcastSync), fmt.Sprintf("--%s=%d", cli.FlagExpiration, time.Now().Add(time.Minute*time.Duration(120)).Unix()), - fmt.Sprintf("--%s=%s", flags.FlagFees, sdk.NewCoins(sdk.NewCoin("stake", sdk.NewInt(10))).String()), + fmt.Sprintf("--%s=%s", flags.FlagFees, sdk.NewCoins(sdk.NewCoin("stake", sdkmath.NewInt(10))).String()), fmt.Sprintf("--%s=%s", cli.FlagAllowList, s.grantee[4]), }, ) s.Require().NoError(err) - s.Require().NoError(s.clientCtx.Codec.UnmarshalJSON(out.Bytes(), &response), out.String()) } @@ -172,9 +173,9 @@ func (s *CLITestSuite) msgSendExec(grantee sdk.AccAddress) { s.clientCtx, val[0].Address, grantee, - sdk.NewCoins(sdk.NewCoin("stake", sdk.NewInt(200))), fmt.Sprintf("--%s=true", flags.FlagSkipConfirmation), + sdk.NewCoins(sdk.NewCoin("stake", sdkmath.NewInt(200))), fmt.Sprintf("--%s=true", flags.FlagSkipConfirmation), fmt.Sprintf("--%s=%s", flags.FlagBroadcastMode, flags.BroadcastSync), - fmt.Sprintf("--%s=%s", flags.FlagFees, sdk.NewCoins(sdk.NewCoin("stake", sdk.NewInt(10))).String()), + fmt.Sprintf("--%s=%s", flags.FlagFees, sdk.NewCoins(sdk.NewCoin("stake", sdkmath.NewInt(10))).String()), ) s.Require().NoError(err) s.Require().Contains(out.String(), `"code":0`) @@ -242,7 +243,7 @@ func (s *CLITestSuite) TestCLITxGrantAuthorization() { fmt.Sprintf("--%s=%s", flags.FlagFrom, val[0].Address.String()), fmt.Sprintf("--%s=%s", flags.FlagBroadcastMode, flags.BroadcastSync), fmt.Sprintf("--%s=true", flags.FlagSkipConfirmation), - fmt.Sprintf("--%s=%s", flags.FlagFees, sdk.NewCoins(sdk.NewCoin("stake", sdk.NewInt(10))).String()), + fmt.Sprintf("--%s=%s", flags.FlagFees, sdk.NewCoins(sdk.NewCoin("stake", sdkmath.NewInt(10))).String()), fmt.Sprintf("--%s=%d", cli.FlagExpiration, twoHours), }, false, @@ -259,7 +260,7 @@ func (s *CLITestSuite) TestCLITxGrantAuthorization() { fmt.Sprintf("--%s=%s", flags.FlagBroadcastMode, flags.BroadcastSync), fmt.Sprintf("--%s=%d", cli.FlagExpiration, twoHours), fmt.Sprintf("--%s=%s", cli.FlagAllowedValidators, sdk.ValAddress(s.addrs[0]).String()), - fmt.Sprintf("--%s=%s", flags.FlagFees, sdk.NewCoins(sdk.NewCoin("stake", sdk.NewInt(10))).String()), + fmt.Sprintf("--%s=%s", flags.FlagFees, sdk.NewCoins(sdk.NewCoin("stake", sdkmath.NewInt(10))).String()), }, true, "invalid denom", @@ -275,7 +276,7 @@ func (s *CLITestSuite) TestCLITxGrantAuthorization() { fmt.Sprintf("--%s=%s", flags.FlagBroadcastMode, flags.BroadcastSync), fmt.Sprintf("--%s=%d", cli.FlagExpiration, twoHours), fmt.Sprintf("--%s=%s", cli.FlagDenyValidators, sdk.ValAddress(s.addrs[0]).String()), - fmt.Sprintf("--%s=%s", flags.FlagFees, sdk.NewCoins(sdk.NewCoin("stake", sdk.NewInt(10))).String()), + fmt.Sprintf("--%s=%s", flags.FlagFees, sdk.NewCoins(sdk.NewCoin("stake", sdkmath.NewInt(10))).String()), }, true, "invalid denom", @@ -291,7 +292,7 @@ func (s *CLITestSuite) TestCLITxGrantAuthorization() { fmt.Sprintf("--%s=%s", flags.FlagBroadcastMode, flags.BroadcastSync), fmt.Sprintf("--%s=%d", cli.FlagExpiration, twoHours), fmt.Sprintf("--%s=%s", cli.FlagAllowedValidators, sdk.ValAddress(s.addrs[0]).String()), - fmt.Sprintf("--%s=%s", flags.FlagFees, sdk.NewCoins(sdk.NewCoin("stake", sdk.NewInt(10))).String()), + fmt.Sprintf("--%s=%s", flags.FlagFees, sdk.NewCoins(sdk.NewCoin("stake", sdkmath.NewInt(10))).String()), }, true, "invalid denom", @@ -307,7 +308,7 @@ func (s *CLITestSuite) TestCLITxGrantAuthorization() { fmt.Sprintf("--%s=%s", flags.FlagBroadcastMode, flags.BroadcastSync), fmt.Sprintf("--%s=%d", cli.FlagExpiration, twoHours), fmt.Sprintf("--%s=%s", cli.FlagAllowedValidators, sdk.ValAddress(s.addrs[0]).String()), - fmt.Sprintf("--%s=%s", flags.FlagFees, sdk.NewCoins(sdk.NewCoin("stake", sdk.NewInt(10))).String()), + fmt.Sprintf("--%s=%s", flags.FlagFees, sdk.NewCoins(sdk.NewCoin("stake", sdkmath.NewInt(10))).String()), }, true, "invalid denom", @@ -323,7 +324,7 @@ func (s *CLITestSuite) TestCLITxGrantAuthorization() { fmt.Sprintf("--%s=%s", flags.FlagBroadcastMode, flags.BroadcastSync), fmt.Sprintf("--%s=%d", cli.FlagExpiration, twoHours), fmt.Sprintf("--%s=%s", cli.FlagAllowedValidators, sdk.ValAddress(s.addrs[0]).String()), - fmt.Sprintf("--%s=%s", flags.FlagFees, sdk.NewCoins(sdk.NewCoin("stake", sdk.NewInt(10))).String()), + fmt.Sprintf("--%s=%s", flags.FlagFees, sdk.NewCoins(sdk.NewCoin("stake", sdkmath.NewInt(10))).String()), }, true, "invalid decimal coin expression", @@ -338,7 +339,7 @@ func (s *CLITestSuite) TestCLITxGrantAuthorization() { fmt.Sprintf("--%s=%s", flags.FlagBroadcastMode, flags.BroadcastSync), fmt.Sprintf("--%s=%d", cli.FlagExpiration, twoHours), fmt.Sprintf("--%s=true", flags.FlagSkipConfirmation), - fmt.Sprintf("--%s=%s", flags.FlagFees, sdk.NewCoins(sdk.NewCoin("stake", sdk.NewInt(10))).String()), + fmt.Sprintf("--%s=%s", flags.FlagFees, sdk.NewCoins(sdk.NewCoin("stake", sdkmath.NewInt(10))).String()), }, false, "", @@ -353,7 +354,7 @@ func (s *CLITestSuite) TestCLITxGrantAuthorization() { fmt.Sprintf("--%s=%s", flags.FlagBroadcastMode, flags.BroadcastSync), fmt.Sprintf("--%s=%d", cli.FlagExpiration, twoHours), fmt.Sprintf("--%s=true", flags.FlagSkipConfirmation), - fmt.Sprintf("--%s=%s", flags.FlagFees, sdk.NewCoins(sdk.NewCoin("stake", sdk.NewInt(10))).String()), + fmt.Sprintf("--%s=%s", flags.FlagFees, sdk.NewCoins(sdk.NewCoin("stake", sdkmath.NewInt(10))).String()), fmt.Sprintf("--%s=%s", cli.FlagAllowList, s.grantee[1]), }, false, @@ -369,11 +370,11 @@ func (s *CLITestSuite) TestCLITxGrantAuthorization() { fmt.Sprintf("--%s=%s", flags.FlagBroadcastMode, flags.BroadcastSync), fmt.Sprintf("--%s=%d", cli.FlagExpiration, twoHours), fmt.Sprintf("--%s=true", flags.FlagSkipConfirmation), - fmt.Sprintf("--%s=%s", flags.FlagFees, sdk.NewCoins(sdk.NewCoin("stake", sdk.NewInt(10))).String()), + fmt.Sprintf("--%s=%s", flags.FlagFees, sdk.NewCoins(sdk.NewCoin("stake", sdkmath.NewInt(10))).String()), fmt.Sprintf("--%s=%s", cli.FlagAllowList, fmt.Sprintf("%s,%s", s.grantee[1], s.grantee[1])), }, true, - "duplicate entry", + "duplicate address", }, { "Valid tx generic authorization", @@ -385,7 +386,7 @@ func (s *CLITestSuite) TestCLITxGrantAuthorization() { fmt.Sprintf("--%s=%s", flags.FlagBroadcastMode, flags.BroadcastSync), fmt.Sprintf("--%s=%d", cli.FlagExpiration, twoHours), fmt.Sprintf("--%s=true", flags.FlagSkipConfirmation), - fmt.Sprintf("--%s=%s", flags.FlagFees, sdk.NewCoins(sdk.NewCoin("stake", sdk.NewInt(10))).String()), + fmt.Sprintf("--%s=%s", flags.FlagFees, sdk.NewCoins(sdk.NewCoin("stake", sdkmath.NewInt(10))).String()), }, false, "", @@ -400,7 +401,7 @@ func (s *CLITestSuite) TestCLITxGrantAuthorization() { fmt.Sprintf("--%s=%s", flags.FlagBroadcastMode, flags.BroadcastSync), fmt.Sprintf("--%s=%d", cli.FlagExpiration, twoHours), fmt.Sprintf("--%s=true", flags.FlagSkipConfirmation), - fmt.Sprintf("--%s=%s", flags.FlagFees, sdk.NewCoins(sdk.NewCoin("stake", sdk.NewInt(10))).String()), + fmt.Sprintf("--%s=%s", flags.FlagFees, sdk.NewCoins(sdk.NewCoin("stake", sdkmath.NewInt(10))).String()), }, true, "grantee and granter should be different", @@ -415,7 +416,7 @@ func (s *CLITestSuite) TestCLITxGrantAuthorization() { fmt.Sprintf("--%s=%s", flags.FlagBroadcastMode, flags.BroadcastSync), fmt.Sprintf("--%s=%d", cli.FlagExpiration, twoHours), fmt.Sprintf("--%s=true", flags.FlagSkipConfirmation), - fmt.Sprintf("--%s=%s", flags.FlagFees, sdk.NewCoins(sdk.NewCoin("stake", sdk.NewInt(10))).String()), + fmt.Sprintf("--%s=%s", flags.FlagFees, sdk.NewCoins(sdk.NewCoin("stake", sdkmath.NewInt(10))).String()), fmt.Sprintf("--%s=%s", flags.FlagSignMode, flags.SignModeLegacyAminoJSON), }, false, @@ -456,7 +457,7 @@ func (s *CLITestSuite) TestCmdRevokeAuthorizations() { fmt.Sprintf("--%s=%s", flags.FlagFrom, val[0].Address), fmt.Sprintf("--%s=%s", flags.FlagBroadcastMode, flags.BroadcastSync), fmt.Sprintf("--%s=%d", cli.FlagExpiration, twoHours), - fmt.Sprintf("--%s=%s", flags.FlagFees, sdk.NewCoins(sdk.NewCoin("stake", sdk.NewInt(10))).String()), + fmt.Sprintf("--%s=%s", flags.FlagFees, sdk.NewCoins(sdk.NewCoin("stake", sdkmath.NewInt(10))).String()), }, ) s.Require().NoError(err) @@ -471,7 +472,7 @@ func (s *CLITestSuite) TestCmdRevokeAuthorizations() { fmt.Sprintf("--%s=%s", flags.FlagFrom, val[0].Address), fmt.Sprintf("--%s=%s", flags.FlagBroadcastMode, flags.BroadcastSync), fmt.Sprintf("--%s=%d", cli.FlagExpiration, twoHours), - fmt.Sprintf("--%s=%s", flags.FlagFees, sdk.NewCoins(sdk.NewCoin("stake", sdk.NewInt(10))).String()), + fmt.Sprintf("--%s=%s", flags.FlagFees, sdk.NewCoins(sdk.NewCoin("stake", sdkmath.NewInt(10))).String()), }, ) s.Require().NoError(err) @@ -486,7 +487,7 @@ func (s *CLITestSuite) TestCmdRevokeAuthorizations() { fmt.Sprintf("--%s=%s", flags.FlagFrom, val[0].Address), fmt.Sprintf("--%s=%s", flags.FlagBroadcastMode, flags.BroadcastSync), fmt.Sprintf("--%s=%d", cli.FlagExpiration, twoHours), - fmt.Sprintf("--%s=%s", flags.FlagFees, sdk.NewCoins(sdk.NewCoin("stake", sdk.NewInt(10))).String()), + fmt.Sprintf("--%s=%s", flags.FlagFees, sdk.NewCoins(sdk.NewCoin("stake", sdkmath.NewInt(10))).String()), fmt.Sprintf("--%s=%s", flags.FlagSignMode, flags.SignModeLegacyAminoJSON), }, ) @@ -527,7 +528,7 @@ func (s *CLITestSuite) TestCmdRevokeAuthorizations() { fmt.Sprintf("--%s=%s", flags.FlagFrom, val[0].Address.String()), fmt.Sprintf("--%s=%s", flags.FlagBroadcastMode, flags.BroadcastSync), fmt.Sprintf("--%s=true", flags.FlagSkipConfirmation), - fmt.Sprintf("--%s=%s", flags.FlagFees, sdk.NewCoins(sdk.NewCoin("stake", sdk.NewInt(10))).String()), + fmt.Sprintf("--%s=%s", flags.FlagFees, sdk.NewCoins(sdk.NewCoin("stake", sdkmath.NewInt(10))).String()), }, &sdk.TxResponse{}, false, @@ -540,7 +541,7 @@ func (s *CLITestSuite) TestCmdRevokeAuthorizations() { fmt.Sprintf("--%s=%s", flags.FlagFrom, val[0].Address.String()), fmt.Sprintf("--%s=%s", flags.FlagBroadcastMode, flags.BroadcastSync), fmt.Sprintf("--%s=true", flags.FlagSkipConfirmation), - fmt.Sprintf("--%s=%s", flags.FlagFees, sdk.NewCoins(sdk.NewCoin("stake", sdk.NewInt(10))).String()), + fmt.Sprintf("--%s=%s", flags.FlagFees, sdk.NewCoins(sdk.NewCoin("stake", sdkmath.NewInt(10))).String()), }, &sdk.TxResponse{}, false, @@ -553,7 +554,7 @@ func (s *CLITestSuite) TestCmdRevokeAuthorizations() { fmt.Sprintf("--%s=%s", flags.FlagFrom, val[0].Address.String()), fmt.Sprintf("--%s=%s", flags.FlagBroadcastMode, flags.BroadcastSync), fmt.Sprintf("--%s=true", flags.FlagSkipConfirmation), - fmt.Sprintf("--%s=%s", flags.FlagFees, sdk.NewCoins(sdk.NewCoin("stake", sdk.NewInt(10))).String()), + fmt.Sprintf("--%s=%s", flags.FlagFees, sdk.NewCoins(sdk.NewCoin("stake", sdkmath.NewInt(10))).String()), fmt.Sprintf("--%s=%s", flags.FlagSignMode, flags.SignModeLegacyAminoJSON), }, &sdk.TxResponse{}, @@ -563,7 +564,7 @@ func (s *CLITestSuite) TestCmdRevokeAuthorizations() { for _, tc := range testCases { tc := tc s.Run(tc.name, func() { - cmd := cli.NewCmdRevokeAuthorization() + cmd := cli.NewCmdRevokeAuthorization(addresscodec.NewBech32Codec("cosmos")) out, err := clitestutil.ExecTestCLICmd(s.clientCtx, cmd, tc.args) if tc.expectErr { @@ -591,7 +592,7 @@ func (s *CLITestSuite) TestExecAuthorizationWithExpiration() { fmt.Sprintf("--%s=%s", flags.FlagFrom, val[0].Address.String()), fmt.Sprintf("--%s=%s", flags.FlagBroadcastMode, flags.BroadcastSync), fmt.Sprintf("--%s=%d", cli.FlagExpiration, tenSeconds), - fmt.Sprintf("--%s=%s", flags.FlagFees, sdk.NewCoins(sdk.NewCoin("stake", sdk.NewInt(10))).String()), + fmt.Sprintf("--%s=%s", flags.FlagFees, sdk.NewCoins(sdk.NewCoin("stake", sdkmath.NewInt(10))).String()), }, ) s.Require().NoError(err) @@ -609,7 +610,7 @@ func (s *CLITestSuite) TestExecAuthorizationWithExpiration() { execMsg.Name(), fmt.Sprintf("--%s=%s", flags.FlagFrom, grantee.String()), fmt.Sprintf("--%s=%s", flags.FlagBroadcastMode, flags.BroadcastSync), - fmt.Sprintf("--%s=%s", flags.FlagFees, sdk.NewCoins(sdk.NewCoin("stake", sdk.NewInt(10))).String()), + fmt.Sprintf("--%s=%s", flags.FlagFees, sdk.NewCoins(sdk.NewCoin("stake", sdkmath.NewInt(10))).String()), fmt.Sprintf("--%s=true", flags.FlagSkipConfirmation), }) s.Require().NoError(err) @@ -631,7 +632,7 @@ func (s *CLITestSuite) TestNewExecGenericAuthorized() { fmt.Sprintf("--%s=%s", flags.FlagFrom, val[0].Address.String()), fmt.Sprintf("--%s=%s", flags.FlagBroadcastMode, flags.BroadcastSync), fmt.Sprintf("--%s=%d", cli.FlagExpiration, twoHours), - fmt.Sprintf("--%s=%s", flags.FlagFees, sdk.NewCoins(sdk.NewCoin("stake", sdk.NewInt(10))).String()), + fmt.Sprintf("--%s=%s", flags.FlagFees, sdk.NewCoins(sdk.NewCoin("stake", sdkmath.NewInt(10))).String()), }, ) s.Require().NoError(err) @@ -674,7 +675,7 @@ func (s *CLITestSuite) TestNewExecGenericAuthorized() { execMsg.Name(), fmt.Sprintf("--%s=%s", flags.FlagFrom, grantee.String()), fmt.Sprintf("--%s=%s", flags.FlagBroadcastMode, flags.BroadcastSync), - fmt.Sprintf("--%s=%s", flags.FlagFees, sdk.NewCoins(sdk.NewCoin("stake", sdk.NewInt(10))).String()), + fmt.Sprintf("--%s=%s", flags.FlagFees, sdk.NewCoins(sdk.NewCoin("stake", sdkmath.NewInt(10))).String()), fmt.Sprintf("--%s=true", flags.FlagSkipConfirmation), }, &sdk.TxResponse{}, @@ -686,7 +687,7 @@ func (s *CLITestSuite) TestNewExecGenericAuthorized() { execMsg.Name(), fmt.Sprintf("--%s=%s", flags.FlagFrom, grantee.String()), fmt.Sprintf("--%s=%s", flags.FlagBroadcastMode, flags.BroadcastSync), - fmt.Sprintf("--%s=%s", flags.FlagFees, sdk.NewCoins(sdk.NewCoin("stake", sdk.NewInt(10))).String()), + fmt.Sprintf("--%s=%s", flags.FlagFees, sdk.NewCoins(sdk.NewCoin("stake", sdkmath.NewInt(10))).String()), fmt.Sprintf("--%s=true", flags.FlagSkipConfirmation), fmt.Sprintf("--%s=%s", flags.FlagSignMode, flags.SignModeLegacyAminoJSON), }, @@ -725,13 +726,13 @@ func (s *CLITestSuite) TestNewExecGrantAuthorized() { fmt.Sprintf("--%s=%s", flags.FlagFrom, val[0].Address.String()), fmt.Sprintf("--%s=%s", flags.FlagBroadcastMode, flags.BroadcastSync), fmt.Sprintf("--%s=%d", cli.FlagExpiration, twoHours), - fmt.Sprintf("--%s=%s", flags.FlagFees, sdk.NewCoins(sdk.NewCoin("stake", sdk.NewInt(10))).String()), + fmt.Sprintf("--%s=%s", flags.FlagFees, sdk.NewCoins(sdk.NewCoin("stake", sdkmath.NewInt(10))).String()), }, ) s.Require().NoError(err) tokens := sdk.NewCoins( - sdk.NewCoin("testtoken", sdk.NewInt(12)), + sdk.NewCoin("testtoken", sdkmath.NewInt(12)), ) normalGeneratedTx, err := clitestutil.MsgSendExec( s.clientCtx, @@ -740,7 +741,7 @@ func (s *CLITestSuite) TestNewExecGrantAuthorized() { tokens, fmt.Sprintf("--%s=true", flags.FlagSkipConfirmation), fmt.Sprintf("--%s=%s", flags.FlagBroadcastMode, flags.BroadcastSync), - fmt.Sprintf("--%s=%s", flags.FlagFees, sdk.NewCoins(sdk.NewCoin("stake", sdk.NewInt(10))).String()), + fmt.Sprintf("--%s=%s", flags.FlagFees, sdk.NewCoins(sdk.NewCoin("stake", sdkmath.NewInt(10))).String()), fmt.Sprintf("--%s=true", flags.FlagGenerateOnly), ) s.Require().NoError(err) @@ -759,7 +760,7 @@ func (s *CLITestSuite) TestNewExecGrantAuthorized() { execMsg.Name(), fmt.Sprintf("--%s=%s", flags.FlagFrom, grantee.String()), fmt.Sprintf("--%s=%s", flags.FlagBroadcastMode, flags.BroadcastSync), - fmt.Sprintf("--%s=%s", flags.FlagFees, sdk.NewCoins(sdk.NewCoin("stake", sdk.NewInt(10))).String()), + fmt.Sprintf("--%s=%s", flags.FlagFees, sdk.NewCoins(sdk.NewCoin("stake", sdkmath.NewInt(10))).String()), fmt.Sprintf("--%s=true", flags.FlagSkipConfirmation), }, false, @@ -771,7 +772,7 @@ func (s *CLITestSuite) TestNewExecGrantAuthorized() { execMsg.Name(), fmt.Sprintf("--%s=%s", flags.FlagFrom, grantee.String()), fmt.Sprintf("--%s=%s", flags.FlagBroadcastMode, flags.BroadcastSync), - fmt.Sprintf("--%s=%s", flags.FlagFees, sdk.NewCoins(sdk.NewCoin("stake", sdk.NewInt(10))).String()), + fmt.Sprintf("--%s=%s", flags.FlagFees, sdk.NewCoins(sdk.NewCoin("stake", sdkmath.NewInt(10))).String()), fmt.Sprintf("--%s=true", flags.FlagSkipConfirmation), }, false, @@ -820,14 +821,14 @@ func (s *CLITestSuite) TestExecSendAuthzWithAllowList() { fmt.Sprintf("--%s=%s", flags.FlagFrom, val[0].Address.String()), fmt.Sprintf("--%s=%s", flags.FlagBroadcastMode, flags.BroadcastSync), fmt.Sprintf("--%s=%d", cli.FlagExpiration, twoHours), - fmt.Sprintf("--%s=%s", flags.FlagFees, sdk.NewCoins(sdk.NewCoin("stake", sdk.NewInt(10))).String()), + fmt.Sprintf("--%s=%s", flags.FlagFees, sdk.NewCoins(sdk.NewCoin("stake", sdkmath.NewInt(10))).String()), fmt.Sprintf("--%s=%s", cli.FlagAllowList, allowedAddr), }, ) s.Require().NoError(err) tokens := sdk.NewCoins( - sdk.NewCoin("stake", sdk.NewInt(12)), + sdk.NewCoin("stake", sdkmath.NewInt(12)), ) validGeneratedTx, err := clitestutil.MsgSendExec( @@ -837,7 +838,7 @@ func (s *CLITestSuite) TestExecSendAuthzWithAllowList() { tokens, fmt.Sprintf("--%s=true", flags.FlagSkipConfirmation), fmt.Sprintf("--%s=%s", flags.FlagBroadcastMode, flags.BroadcastSync), - fmt.Sprintf("--%s=%s", flags.FlagFees, sdk.NewCoins(sdk.NewCoin("stake", sdk.NewInt(10))).String()), + fmt.Sprintf("--%s=%s", flags.FlagFees, sdk.NewCoins(sdk.NewCoin("stake", sdkmath.NewInt(10))).String()), fmt.Sprintf("--%s=true", flags.FlagGenerateOnly), ) s.Require().NoError(err) @@ -851,7 +852,7 @@ func (s *CLITestSuite) TestExecSendAuthzWithAllowList() { tokens, fmt.Sprintf("--%s=true", flags.FlagSkipConfirmation), fmt.Sprintf("--%s=%s", flags.FlagBroadcastMode, flags.BroadcastSync), - fmt.Sprintf("--%s=%s", flags.FlagFees, sdk.NewCoins(sdk.NewCoin("stake", sdk.NewInt(10))).String()), + fmt.Sprintf("--%s=%s", flags.FlagFees, sdk.NewCoins(sdk.NewCoin("stake", sdkmath.NewInt(10))).String()), fmt.Sprintf("--%s=true", flags.FlagGenerateOnly), ) s.Require().NoError(err) @@ -863,7 +864,7 @@ func (s *CLITestSuite) TestExecSendAuthzWithAllowList() { execMsg.Name(), fmt.Sprintf("--%s=%s", flags.FlagFrom, grantee.String()), fmt.Sprintf("--%s=%s", flags.FlagBroadcastMode, flags.BroadcastSync), - fmt.Sprintf("--%s=%s", flags.FlagFees, sdk.NewCoins(sdk.NewCoin("stake", sdk.NewInt(10))).String()), + fmt.Sprintf("--%s=%s", flags.FlagFees, sdk.NewCoins(sdk.NewCoin("stake", sdkmath.NewInt(10))).String()), fmt.Sprintf("--%s=true", flags.FlagSkipConfirmation), } var response sdk.TxResponse @@ -877,7 +878,7 @@ func (s *CLITestSuite) TestExecSendAuthzWithAllowList() { execMsg1.Name(), fmt.Sprintf("--%s=%s", flags.FlagFrom, grantee.String()), fmt.Sprintf("--%s=%s", flags.FlagBroadcastMode, flags.BroadcastSync), - fmt.Sprintf("--%s=%s", flags.FlagFees, sdk.NewCoins(sdk.NewCoin("stake", sdk.NewInt(10))).String()), + fmt.Sprintf("--%s=%s", flags.FlagFees, sdk.NewCoins(sdk.NewCoin("stake", sdkmath.NewInt(10))).String()), fmt.Sprintf("--%s=true", flags.FlagSkipConfirmation), } out, err = clitestutil.ExecTestCLICmd(s.clientCtx, cmd, args) diff --git a/x/authz/client/testutil/helpers.go b/x/authz/client/testutil/helpers.go index 231cf3bba033..07faa75cb3b0 100644 --- a/x/authz/client/testutil/helpers.go +++ b/x/authz/client/testutil/helpers.go @@ -2,12 +2,13 @@ package authz import ( "github.com/cosmos/cosmos-sdk/client" + addresscodec "github.com/cosmos/cosmos-sdk/codec/address" "github.com/cosmos/cosmos-sdk/testutil" clitestutil "github.com/cosmos/cosmos-sdk/testutil/cli" "github.com/cosmos/cosmos-sdk/x/authz/client/cli" ) func CreateGrant(clientCtx client.Context, args []string) (testutil.BufferWriter, error) { - cmd := cli.NewCmdGrantAuthorization() + cmd := cli.NewCmdGrantAuthorization(addresscodec.NewBech32Codec("cosmos")) return clitestutil.ExecTestCLICmd(clientCtx, cmd, args) } diff --git a/x/authz/expected_keepers.go b/x/authz/expected_keepers.go index 812daa518f52..5e0dd58a63ba 100644 --- a/x/authz/expected_keepers.go +++ b/x/authz/expected_keepers.go @@ -1,14 +1,19 @@ package authz import ( + context "context" + + "cosmossdk.io/core/address" sdk "github.com/cosmos/cosmos-sdk/types" ) // AccountKeeper defines the expected account keeper (noalias) type AccountKeeper interface { - GetAccount(ctx sdk.Context, addr sdk.AccAddress) sdk.AccountI - NewAccountWithAddress(ctx sdk.Context, addr sdk.AccAddress) sdk.AccountI - SetAccount(ctx sdk.Context, acc sdk.AccountI) + address.Codec + + GetAccount(ctx context.Context, addr sdk.AccAddress) sdk.AccountI + NewAccountWithAddress(ctx context.Context, addr sdk.AccAddress) sdk.AccountI + SetAccount(ctx context.Context, acc sdk.AccountI) } // BankKeeper defines the expected interface needed to retrieve account balances. diff --git a/x/authz/keeper/genesis.go b/x/authz/keeper/genesis.go index 6ef975a74dfe..e1dadebcd3fc 100644 --- a/x/authz/keeper/genesis.go +++ b/x/authz/keeper/genesis.go @@ -14,15 +14,21 @@ func (k Keeper) InitGenesis(ctx sdk.Context, data *authz.GenesisState) { continue } - grantee := sdk.MustAccAddressFromBech32(entry.Grantee) - granter := sdk.MustAccAddressFromBech32(entry.Granter) + grantee, err := k.authKeeper.StringToBytes(entry.Grantee) + if err != nil { + panic(err) + } + granter, err := k.authKeeper.StringToBytes(entry.Granter) + if err != nil { + panic(err) + } a, ok := entry.Authorization.GetCachedValue().(authz.Authorization) if !ok { panic("expected authorization") } - err := k.SaveGrant(ctx, grantee, granter, a, entry.Expiration) + err = k.SaveGrant(ctx, grantee, granter, a, entry.Expiration) if err != nil { panic(err) } diff --git a/x/authz/keeper/genesis_test.go b/x/authz/keeper/genesis_test.go index a0e883a1f589..52166cafbe82 100644 --- a/x/authz/keeper/genesis_test.go +++ b/x/authz/keeper/genesis_test.go @@ -8,6 +8,7 @@ import ( cmtproto "github.com/cometbft/cometbft/proto/tendermint/types" "github.com/stretchr/testify/suite" + sdkmath "cosmossdk.io/math" storetypes "cosmossdk.io/store/types" "github.com/golang/mock/gomock" @@ -22,6 +23,13 @@ import ( bank "github.com/cosmos/cosmos-sdk/x/bank/types" ) +var ( + granteePub = secp256k1.GenPrivKey().PubKey() + granterPub = secp256k1.GenPrivKey().PubKey() + granteeAddr = sdk.AccAddress(granteePub.Address()) + granterAddr = sdk.AccAddress(granterPub.Address()) +) + type GenesisTestSuite struct { suite.Suite @@ -42,6 +50,11 @@ func (suite *GenesisTestSuite) SetupTest() { ctrl := gomock.NewController(suite.T()) suite.accountKeeper = authztestutil.NewMockAccountKeeper(ctrl) + suite.accountKeeper.EXPECT().StringToBytes(granteeAddr.String()).Return(granteeAddr, nil).AnyTimes() + suite.accountKeeper.EXPECT().BytesToString(granterAddr).Return(granterAddr.String(), nil).AnyTimes() + suite.accountKeeper.EXPECT().StringToBytes(granterAddr.String()).Return(granterAddr, nil).AnyTimes() + suite.accountKeeper.EXPECT().BytesToString(granterAddr).Return(granterAddr.String(), nil).AnyTimes() + suite.baseApp = baseapp.NewBaseApp( "authz", log.NewNopLogger(), @@ -58,15 +71,8 @@ func (suite *GenesisTestSuite) SetupTest() { suite.keeper = keeper.NewKeeper(key, suite.encCfg.Codec, msr, suite.accountKeeper) } -var ( - granteePub = secp256k1.GenPrivKey().PubKey() - granterPub = secp256k1.GenPrivKey().PubKey() - granteeAddr = sdk.AccAddress(granteePub.Address()) - granterAddr = sdk.AccAddress(granterPub.Address()) -) - func (suite *GenesisTestSuite) TestImportExportGenesis() { - coins := sdk.NewCoins(sdk.NewCoin("foo", sdk.NewInt(1_000))) + coins := sdk.NewCoins(sdk.NewCoin("foo", sdkmath.NewInt(1_000))) now := suite.ctx.BlockTime() expires := now.Add(time.Hour) diff --git a/x/authz/keeper/grpc_query.go b/x/authz/keeper/grpc_query.go index a014a3a81b5b..cb19e5760e3f 100644 --- a/x/authz/keeper/grpc_query.go +++ b/x/authz/keeper/grpc_query.go @@ -1,6 +1,7 @@ package keeper import ( + "bytes" "context" "google.golang.org/grpc/codes" @@ -24,12 +25,12 @@ func (k Keeper) Grants(c context.Context, req *authz.QueryGrantsRequest) (*authz return nil, status.Errorf(codes.InvalidArgument, "empty request") } - granter, err := sdk.AccAddressFromBech32(req.Granter) + granter, err := k.authKeeper.StringToBytes(req.Granter) if err != nil { return nil, err } - grantee, err := sdk.AccAddressFromBech32(req.Grantee) + grantee, err := k.authKeeper.StringToBytes(req.Grantee) if err != nil { return nil, err } @@ -95,7 +96,7 @@ func (k Keeper) GranterGrants(c context.Context, req *authz.QueryGranterGrantsRe return nil, status.Errorf(codes.InvalidArgument, "empty request") } - granter, err := sdk.AccAddressFromBech32(req.Granter) + granter, err := k.authKeeper.StringToBytes(req.Granter) if err != nil { return nil, err } @@ -117,7 +118,7 @@ func (k Keeper) GranterGrants(c context.Context, req *authz.QueryGranterGrantsRe grantee := firstAddressFromGrantStoreKey(key) return &authz.GrantAuthorization{ - Granter: granter.String(), + Granter: req.Granter, Grantee: grantee.String(), Authorization: any, Expiration: auth.Expiration, @@ -141,7 +142,7 @@ func (k Keeper) GranteeGrants(c context.Context, req *authz.QueryGranteeGrantsRe return nil, status.Errorf(codes.InvalidArgument, "empty request") } - grantee, err := sdk.AccAddressFromBech32(req.Grantee) + grantee, err := k.authKeeper.StringToBytes(req.Grantee) if err != nil { return nil, err } @@ -156,7 +157,7 @@ func (k Keeper) GranteeGrants(c context.Context, req *authz.QueryGranteeGrantsRe } granter, g, _ := parseGrantStoreKey(append(GrantKey, key...)) - if !g.Equals(grantee) { + if !bytes.Equal(g, grantee) { return nil, nil } @@ -169,7 +170,7 @@ func (k Keeper) GranteeGrants(c context.Context, req *authz.QueryGranteeGrantsRe Authorization: authorizationAny, Expiration: auth.Expiration, Granter: granter.String(), - Grantee: grantee.String(), + Grantee: req.Grantee, }, nil }, func() *authz.Grant { return &authz.Grant{} diff --git a/x/authz/keeper/grpc_query_test.go b/x/authz/keeper/grpc_query_test.go index 041ec22f6d96..1a26e170c586 100644 --- a/x/authz/keeper/grpc_query_test.go +++ b/x/authz/keeper/grpc_query_test.go @@ -19,6 +19,7 @@ func (suite *TestSuite) TestGRPCQueryAuthorization() { req *authz.QueryGrantsRequest expAuthorization authz.Authorization ) + testCases := []struct { msg string malleate func(require *require.Assertions) diff --git a/x/authz/keeper/keeper.go b/x/authz/keeper/keeper.go index 501da89035e9..4ca846406048 100644 --- a/x/authz/keeper/keeper.go +++ b/x/authz/keeper/keeper.go @@ -58,7 +58,7 @@ func (k Keeper) getGrant(ctx sdk.Context, skey []byte) (grant authz.Grant, found return grant, true } -func (k Keeper) update(ctx sdk.Context, grantee sdk.AccAddress, granter sdk.AccAddress, updated authz.Authorization) error { +func (k Keeper) update(ctx sdk.Context, grantee, granter sdk.AccAddress, updated authz.Authorization) error { skey := grantStoreKey(grantee, granter, updated.MsgTypeURL()) grant, found := k.getGrant(ctx, skey) if !found { @@ -205,7 +205,7 @@ func (k Keeper) SaveGrant(ctx sdk.Context, grantee, granter sdk.AccAddress, auth // DeleteGrant revokes any authorization for the provided message type granted to the grantee // by the granter. -func (k Keeper) DeleteGrant(ctx sdk.Context, grantee sdk.AccAddress, granter sdk.AccAddress, msgType string) error { +func (k Keeper) DeleteGrant(ctx sdk.Context, grantee, granter sdk.AccAddress, msgType string) error { store := ctx.KVStore(k.storeKey) skey := grantStoreKey(grantee, granter, msgType) grant, found := k.getGrant(ctx, skey) @@ -230,7 +230,7 @@ func (k Keeper) DeleteGrant(ctx sdk.Context, grantee sdk.AccAddress, granter sdk } // GetAuthorizations Returns list of `Authorizations` granted to the grantee by the granter. -func (k Keeper) GetAuthorizations(ctx sdk.Context, grantee sdk.AccAddress, granter sdk.AccAddress) ([]authz.Authorization, error) { +func (k Keeper) GetAuthorizations(ctx sdk.Context, grantee, granter sdk.AccAddress) ([]authz.Authorization, error) { store := ctx.KVStore(k.storeKey) key := grantStoreKey(grantee, granter, "") iter := storetypes.KVStorePrefixIterator(store, key) @@ -259,7 +259,7 @@ func (k Keeper) GetAuthorizations(ctx sdk.Context, grantee sdk.AccAddress, grant // - No grant is found. // - A grant is found, but it is expired. // - There was an error getting the authorization from the grant. -func (k Keeper) GetAuthorization(ctx sdk.Context, grantee sdk.AccAddress, granter sdk.AccAddress, msgType string) (authz.Authorization, *time.Time) { +func (k Keeper) GetAuthorization(ctx sdk.Context, grantee, granter sdk.AccAddress, msgType string) (authz.Authorization, *time.Time) { grant, found := k.getGrant(ctx, grantStoreKey(grantee, granter, msgType)) if !found || (grant.Expiration != nil && grant.Expiration.Before(ctx.BlockHeader().Time)) { return nil, nil @@ -278,7 +278,7 @@ func (k Keeper) GetAuthorization(ctx sdk.Context, grantee sdk.AccAddress, grante // It should not be used in query or msg services without charging additional gas. // The iteration stops when the handler function returns true or the iterator exhaust. func (k Keeper) IterateGrants(ctx sdk.Context, - handler func(granterAddr sdk.AccAddress, granteeAddr sdk.AccAddress, grant authz.Grant) bool, + handler func(granterAddr, granteeAddr sdk.AccAddress, grant authz.Grant) bool, ) { store := ctx.KVStore(k.storeKey) iter := storetypes.KVStorePrefixIterator(store, GrantKey) @@ -308,7 +308,7 @@ func (k Keeper) getGrantQueueItem(ctx sdk.Context, expiration time.Time, granter } func (k Keeper) setGrantQueueItem(ctx sdk.Context, expiration time.Time, - granter sdk.AccAddress, grantee sdk.AccAddress, queueItems *authz.GrantQueueItem, + granter, grantee sdk.AccAddress, queueItems *authz.GrantQueueItem, ) error { store := ctx.KVStore(k.storeKey) bz, err := k.cdc.Marshal(queueItems) diff --git a/x/authz/keeper/keeper_test.go b/x/authz/keeper/keeper_test.go index 226b4c67a82e..b101566f8d81 100644 --- a/x/authz/keeper/keeper_test.go +++ b/x/authz/keeper/keeper_test.go @@ -1,6 +1,7 @@ package keeper_test import ( + "errors" "testing" "time" @@ -65,6 +66,13 @@ func (s *TestSuite) SetupTest() { // gomock initializations ctrl := gomock.NewController(s.T()) s.accountKeeper = authztestutil.NewMockAccountKeeper(ctrl) + for _, addr := range s.addrs { + s.accountKeeper.EXPECT().StringToBytes(addr.String()).Return(addr, nil).AnyTimes() + s.accountKeeper.EXPECT().BytesToString(addr).Return(addr.String(), nil).AnyTimes() + } + s.accountKeeper.EXPECT().StringToBytes("").Return(nil, errors.New("empty address string is not allowed")).AnyTimes() + s.accountKeeper.EXPECT().StringToBytes("invalid").Return(nil, errors.New("invalid bech32 string")).AnyTimes() + s.bankKeeper = authztestutil.NewMockBankKeeper(ctrl) banktypes.RegisterInterfaces(s.encCfg.InterfaceRegistry) banktypes.RegisterMsgServer(s.baseApp.MsgServiceRouter(), s.bankKeeper) diff --git a/x/authz/keeper/keys.go b/x/authz/keeper/keys.go index 27aec0b5e029..83eabef777e7 100644 --- a/x/authz/keeper/keys.go +++ b/x/authz/keeper/keys.go @@ -29,7 +29,7 @@ const StoreKey = authz.ModuleName // Items are stored with the following key: values // // - 0x01: Grant -func grantStoreKey(grantee sdk.AccAddress, granter sdk.AccAddress, msgType string) []byte { +func grantStoreKey(grantee, granter sdk.AccAddress, msgType string) []byte { m := conv.UnsafeStrToBytes(msgType) granter = address.MustLengthPrefix(granter) grantee = address.MustLengthPrefix(grantee) @@ -79,7 +79,7 @@ func parseGrantQueueKey(key []byte) (time.Time, sdk.AccAddress, sdk.AccAddress, // Key format is: // // 0x02: GrantQueueItem -func GrantQueueKey(expiration time.Time, granter sdk.AccAddress, grantee sdk.AccAddress) []byte { +func GrantQueueKey(expiration time.Time, granter, grantee sdk.AccAddress) []byte { exp := sdk.FormatTimeBytes(expiration) granter = address.MustLengthPrefix(granter) grantee = address.MustLengthPrefix(grantee) diff --git a/x/authz/keeper/msg_server.go b/x/authz/keeper/msg_server.go index 358146124d8f..e3800897ca86 100644 --- a/x/authz/keeper/msg_server.go +++ b/x/authz/keeper/msg_server.go @@ -2,7 +2,10 @@ package keeper import ( "context" + "errors" + "strings" + errorsmod "cosmossdk.io/errors" sdk "github.com/cosmos/cosmos-sdk/types" sdkerrors "github.com/cosmos/cosmos-sdk/types/errors" "github.com/cosmos/cosmos-sdk/x/authz" @@ -12,24 +15,32 @@ var _ authz.MsgServer = Keeper{} // Grant implements the MsgServer.Grant method to create a new grant. func (k Keeper) Grant(goCtx context.Context, msg *authz.MsgGrant) (*authz.MsgGrantResponse, error) { - ctx := sdk.UnwrapSDKContext(goCtx) - grantee, err := sdk.AccAddressFromBech32(msg.Grantee) + if strings.EqualFold(msg.Grantee, msg.Granter) { + return nil, authz.ErrGranteeIsGranter + } + + grantee, err := k.authKeeper.StringToBytes(msg.Grantee) if err != nil { + return nil, sdkerrors.ErrInvalidAddress.Wrapf("invalid grantee address: %s", err) + } + + granter, err := k.authKeeper.StringToBytes(msg.Granter) + if err != nil { + return nil, sdkerrors.ErrInvalidAddress.Wrapf("invalid grantee address: %s", err) + } + + if err := msg.Grant.ValidateBasic(); err != nil { return nil, err } // create the account if it is not in account state + ctx := sdk.UnwrapSDKContext(goCtx) granteeAcc := k.authKeeper.GetAccount(ctx, grantee) if granteeAcc == nil { granteeAcc = k.authKeeper.NewAccountWithAddress(ctx, grantee) k.authKeeper.SetAccount(ctx, granteeAcc) } - granter, err := sdk.AccAddressFromBech32(msg.Granter) - if err != nil { - return nil, err - } - authorization, err := msg.GetAuthorization() if err != nil { return nil, err @@ -50,18 +61,26 @@ func (k Keeper) Grant(goCtx context.Context, msg *authz.MsgGrant) (*authz.MsgGra // Revoke implements the MsgServer.Revoke method. func (k Keeper) Revoke(goCtx context.Context, msg *authz.MsgRevoke) (*authz.MsgRevokeResponse, error) { - ctx := sdk.UnwrapSDKContext(goCtx) - grantee, err := sdk.AccAddressFromBech32(msg.Grantee) - if err != nil { - return nil, err + if strings.EqualFold(msg.Grantee, msg.Granter) { + return nil, authz.ErrGranteeIsGranter } - granter, err := sdk.AccAddressFromBech32(msg.Granter) + + grantee, err := k.authKeeper.StringToBytes(msg.Grantee) if err != nil { - return nil, err + return nil, sdkerrors.ErrInvalidAddress.Wrapf("invalid grantee address: %s", err) } - err = k.DeleteGrant(ctx, grantee, granter, msg.MsgTypeUrl) + granter, err := k.authKeeper.StringToBytes(msg.Granter) if err != nil { + return nil, sdkerrors.ErrInvalidAddress.Wrapf("invalid granter address: %s", err) + } + + if msg.MsgTypeUrl == "" { + return nil, sdkerrors.ErrInvalidRequest.Wrap("missing msg method name") + } + + ctx := sdk.UnwrapSDKContext(goCtx) + if err = k.DeleteGrant(ctx, grantee, granter, msg.MsgTypeUrl); err != nil { return nil, err } @@ -71,9 +90,17 @@ func (k Keeper) Revoke(goCtx context.Context, msg *authz.MsgRevoke) (*authz.MsgR // Exec implements the MsgServer.Exec method. func (k Keeper) Exec(goCtx context.Context, msg *authz.MsgExec) (*authz.MsgExecResponse, error) { ctx := sdk.UnwrapSDKContext(goCtx) - grantee, err := sdk.AccAddressFromBech32(msg.Grantee) + if msg.Grantee == "" { + return nil, errors.New("empty address string is not allowed") + } + + grantee, err := k.authKeeper.StringToBytes(msg.Grantee) if err != nil { - return nil, err + return nil, sdkerrors.ErrInvalidAddress.Wrapf("invalid grantee address: %s", err) + } + + if len(msg.Msgs) == 0 { + return nil, sdkerrors.ErrInvalidRequest.Wrapf("messages cannot be empty") } msgs, err := msg.GetMessages() @@ -81,6 +108,10 @@ func (k Keeper) Exec(goCtx context.Context, msg *authz.MsgExec) (*authz.MsgExecR return nil, err } + if err := validateMsgs(msgs); err != nil { + return nil, err + } + results, err := k.DispatchActions(ctx, grantee, msgs) if err != nil { return nil, err @@ -88,3 +119,18 @@ func (k Keeper) Exec(goCtx context.Context, msg *authz.MsgExec) (*authz.MsgExecR return &authz.MsgExecResponse{Results: results}, nil } + +func validateMsgs(msgs []sdk.Msg) error { + for i, msg := range msgs { + m, ok := msg.(sdk.HasValidateBasic) + if !ok { + continue + } + + if err := m.ValidateBasic(); err != nil { + return errorsmod.Wrapf(err, "msg %d", i) + } + } + + return nil +} diff --git a/x/authz/keeper/msg_server_test.go b/x/authz/keeper/msg_server_test.go index 0a51c3f1252e..5143b8dd39aa 100644 --- a/x/authz/keeper/msg_server_test.go +++ b/x/authz/keeper/msg_server_test.go @@ -3,6 +3,8 @@ package keeper_test import ( "time" + sdkmath "cosmossdk.io/math" + simtestutil "github.com/cosmos/cosmos-sdk/testutil/sims" sdk "github.com/cosmos/cosmos-sdk/types" authtypes "github.com/cosmos/cosmos-sdk/x/auth/types" @@ -24,10 +26,12 @@ func (suite *TestSuite) TestGrant() { addrs := suite.createAccounts(2) curBlockTime := ctx.BlockTime() + suite.accountKeeper.EXPECT().StringToBytes(sdk.AccAddress("valid").String()).Return(sdk.AccAddress("valid"), nil).AnyTimes() + oneHour := curBlockTime.Add(time.Hour) oneYear := curBlockTime.AddDate(1, 0, 0) - coins := sdk.NewCoins(sdk.NewCoin("steak", sdk.NewInt(10))) + coins := sdk.NewCoins(sdk.NewCoin("steak", sdkmath.NewInt(10))) grantee, granter := addrs[0], addrs[1] @@ -37,6 +41,20 @@ func (suite *TestSuite) TestGrant() { expErr bool errMsg string }{ + { + name: "identical grantee and granter", + malleate: func() *authz.MsgGrant { + grant, err := authz.NewGrant(curBlockTime, banktypes.NewSendAuthorization(coins, nil), &oneYear) + suite.Require().NoError(err) + return &authz.MsgGrant{ + Granter: grantee.String(), + Grantee: grantee.String(), + Grant: grant, + } + }, + expErr: true, + errMsg: "grantee and granter should be different", + }, { name: "invalid granter", malleate: func() *authz.MsgGrant { @@ -65,6 +83,38 @@ func (suite *TestSuite) TestGrant() { expErr: true, errMsg: "invalid bech32 string", }, + { + name: "invalid grant", + malleate: func() *authz.MsgGrant { + return &authz.MsgGrant{ + Granter: granter.String(), + Grantee: grantee.String(), + Grant: authz.Grant{ + Expiration: &oneYear, + }, + } + }, + expErr: true, + errMsg: "authorization is nil: invalid type", + }, + { + name: "invalid grant, past time", + malleate: func() *authz.MsgGrant { + pastTime := curBlockTime.Add(-time.Hour) + grant, err := authz.NewGrant(curBlockTime, banktypes.NewSendAuthorization(coins, nil), &oneHour) // we only need the authorization + suite.Require().NoError(err) + return &authz.MsgGrant{ + Granter: granter.String(), + Grantee: grantee.String(), + Grant: authz.Grant{ + Authorization: grant.Authorization, + Expiration: &pastTime, + }, + } + }, + expErr: true, + errMsg: "expiration must be after the current block time", + }, { name: "grantee account does not exist on chain: valid grant", malleate: func() *authz.MsgGrant { @@ -128,6 +178,18 @@ func (suite *TestSuite) TestGrant() { } }, }, + { + name: "valid grant with nil expiration time", + malleate: func() *authz.MsgGrant { + grant, err := authz.NewGrant(curBlockTime, banktypes.NewSendAuthorization(coins, nil), nil) + suite.Require().NoError(err) + return &authz.MsgGrant{ + Granter: granter.String(), + Grantee: grantee.String(), + Grant: grant, + } + }, + }, } for _, tc := range testCases { @@ -154,6 +216,18 @@ func (suite *TestSuite) TestRevoke() { expErr bool errMsg string }{ + { + name: "identical grantee and granter", + malleate: func() *authz.MsgRevoke { + return &authz.MsgRevoke{ + Granter: grantee.String(), + Grantee: grantee.String(), + MsgTypeUrl: bankSendAuthMsgType, + } + }, + expErr: true, + errMsg: "grantee and granter should be different", + }, { name: "invalid granter", malleate: func() *authz.MsgRevoke { @@ -178,6 +252,18 @@ func (suite *TestSuite) TestRevoke() { expErr: true, errMsg: "invalid bech32 string", }, + { + name: "no msg given", + malleate: func() *authz.MsgRevoke { + return &authz.MsgRevoke{ + Granter: granter.String(), + Grantee: grantee.String(), + MsgTypeUrl: "", + } + }, + expErr: true, + errMsg: "missing msg method name", + }, { name: "valid grant", malleate: func() *authz.MsgRevoke { @@ -221,7 +307,7 @@ func (suite *TestSuite) TestExec() { addrs := suite.createAccounts(2) grantee, granter := addrs[0], addrs[1] - coins := sdk.NewCoins(sdk.NewCoin("steak", sdk.NewInt(10))) + coins := sdk.NewCoins(sdk.NewCoin("steak", sdkmath.NewInt(10))) msg := &banktypes.MsgSend{ FromAddress: granter.String(), @@ -236,7 +322,7 @@ func (suite *TestSuite) TestExec() { errMsg string }{ { - name: "invalid grantee", + name: "invalid grantee (empty)", malleate: func() authz.MsgExec { return authz.NewMsgExec(sdk.AccAddress{}, []sdk.Msg{msg}) }, @@ -251,6 +337,14 @@ func (suite *TestSuite) TestExec() { expErr: true, errMsg: "authorization not found", }, + { + name: "no message case", + malleate: func() authz.MsgExec { + return authz.NewMsgExec(grantee, []sdk.Msg{}) + }, + expErr: true, + errMsg: "messages cannot be empty", + }, { name: "valid case", malleate: func() authz.MsgExec { diff --git a/x/authz/migrations/v2/keys.go b/x/authz/migrations/v2/keys.go index fceced95f1c9..328edf3c88c6 100644 --- a/x/authz/migrations/v2/keys.go +++ b/x/authz/migrations/v2/keys.go @@ -23,7 +23,7 @@ var ( // Key format is // // - 0x02: GrantQueueItem -func GrantQueueKey(expiration time.Time, granter sdk.AccAddress, grantee sdk.AccAddress) []byte { +func GrantQueueKey(expiration time.Time, granter, grantee sdk.AccAddress) []byte { exp := sdk.FormatTimeBytes(expiration) granter = address.MustLengthPrefix(granter) grantee = address.MustLengthPrefix(grantee) @@ -41,7 +41,7 @@ func GrantQueueKey(expiration time.Time, granter sdk.AccAddress, grantee sdk.Acc // Items are stored with the following key: values // // - 0x01: Grant -func GrantStoreKey(grantee sdk.AccAddress, granter sdk.AccAddress, msgType string) []byte { +func GrantStoreKey(grantee, granter sdk.AccAddress, msgType string) []byte { m := conv.UnsafeStrToBytes(msgType) granter = address.MustLengthPrefix(granter) grantee = address.MustLengthPrefix(grantee) diff --git a/x/authz/module/abci_test.go b/x/authz/module/abci_test.go index fa4e91babc94..78e8402e76ca 100644 --- a/x/authz/module/abci_test.go +++ b/x/authz/module/abci_test.go @@ -59,6 +59,9 @@ func TestExpiredGrantsQueue(t *testing.T) { accountKeeper.EXPECT().GetAccount(gomock.Any(), grantee3).Return(authtypes.NewBaseAccountWithAddress(grantee3)).AnyTimes() accountKeeper.EXPECT().GetAccount(gomock.Any(), grantee4).Return(authtypes.NewBaseAccountWithAddress(grantee4)).AnyTimes() + accountKeeper.EXPECT().StringToBytes(granter.String()).Return(granter, nil).AnyTimes() + accountKeeper.EXPECT().BytesToString(granter).Return(granter.String(), nil).AnyTimes() + authzKeeper := keeper.NewKeeper(key, encCfg.Codec, baseApp.MsgServiceRouter(), accountKeeper) save := func(grantee sdk.AccAddress, exp *time.Time) { diff --git a/x/authz/module/module.go b/x/authz/module/module.go index e8c6f7d00c9f..a6cc28efb96b 100644 --- a/x/authz/module/module.go +++ b/x/authz/module/module.go @@ -10,6 +10,7 @@ import ( "github.com/spf13/cobra" modulev1 "cosmossdk.io/api/cosmos/authz/module/v1" + "cosmossdk.io/core/address" "cosmossdk.io/core/appmodule" "cosmossdk.io/depinject" @@ -38,6 +39,7 @@ var ( // AppModuleBasic defines the basic application module used by the authz module. type AppModuleBasic struct { cdc codec.Codec + ac address.Codec } // Name returns the authz module's name. @@ -84,20 +86,20 @@ func (AppModuleBasic) ValidateGenesis(cdc codec.JSONCodec, config sdkclient.TxEn } // RegisterGRPCGatewayRoutes registers the gRPC Gateway routes for the authz module. -func (a AppModuleBasic) RegisterGRPCGatewayRoutes(clientCtx sdkclient.Context, mux *gwruntime.ServeMux) { +func (AppModuleBasic) RegisterGRPCGatewayRoutes(clientCtx sdkclient.Context, mux *gwruntime.ServeMux) { if err := authz.RegisterQueryHandlerClient(context.Background(), mux, authz.NewQueryClient(clientCtx)); err != nil { panic(err) } } // GetQueryCmd returns the cli query commands for the authz module -func (AppModuleBasic) GetQueryCmd() *cobra.Command { - return cli.GetQueryCmd() +func (ab AppModuleBasic) GetQueryCmd() *cobra.Command { + return cli.GetQueryCmd(ab.ac) } // GetTxCmd returns the transaction commands for the authz module -func (AppModuleBasic) GetTxCmd() *cobra.Command { - return cli.GetTxCmd() +func (ab AppModuleBasic) GetTxCmd() *cobra.Command { + return cli.GetTxCmd(ab.ac) } // AppModule implements the sdk.AppModule interface @@ -112,7 +114,7 @@ type AppModule struct { // NewAppModule creates a new AppModule object func NewAppModule(cdc codec.Codec, keeper keeper.Keeper, ak authz.AccountKeeper, bk authz.BankKeeper, registry cdctypes.InterfaceRegistry) AppModule { return AppModule{ - AppModuleBasic: AppModuleBasic{cdc: cdc}, + AppModuleBasic: AppModuleBasic{cdc: cdc, ac: ak}, keeper: keeper, accountKeeper: ak, bankKeeper: bk, @@ -168,8 +170,7 @@ func init() { ) } -//nolint:revive -type AuthzInputs struct { +type ModuleInputs struct { depinject.In Key *store.KVStoreKey @@ -180,18 +181,17 @@ type AuthzInputs struct { MsgServiceRouter baseapp.MessageRouter } -//nolint:revive -type AuthzOutputs struct { +type ModuleOutputs struct { depinject.Out AuthzKeeper keeper.Keeper Module appmodule.AppModule } -func ProvideModule(in AuthzInputs) AuthzOutputs { +func ProvideModule(in ModuleInputs) ModuleOutputs { k := keeper.NewKeeper(in.Key, in.Cdc, in.MsgServiceRouter, in.AccountKeeper) m := NewAppModule(in.Cdc, k, in.AccountKeeper, in.BankKeeper, in.Registry) - return AuthzOutputs{AuthzKeeper: k, Module: m} + return ModuleOutputs{AuthzKeeper: k, Module: m} } // ____________________________________________________________________________ @@ -212,7 +212,7 @@ func (am AppModule) RegisterStoreDecoder(sdr simtypes.StoreDecoderRegistry) { func (am AppModule) WeightedOperations(simState module.SimulationState) []simtypes.WeightedOperation { return simulation.WeightedOperations( am.registry, - simState.AppParams, simState.Cdc, + simState.AppParams, simState.Cdc, simState.TxConfig, am.accountKeeper, am.bankKeeper, am.keeper, ) } diff --git a/x/authz/msgs.go b/x/authz/msgs.go index 792120d6de71..306a1762a04a 100644 --- a/x/authz/msgs.go +++ b/x/authz/msgs.go @@ -28,9 +28,7 @@ var ( ) // NewMsgGrant creates a new MsgGrant -// -//nolint:interfacer -func NewMsgGrant(granter sdk.AccAddress, grantee sdk.AccAddress, a Authorization, expiration *time.Time) (*MsgGrant, error) { +func NewMsgGrant(granter, grantee sdk.AccAddress, a Authorization, expiration *time.Time) (*MsgGrant, error) { m := &MsgGrant{ Granter: granter.String(), Grantee: grantee.String(), @@ -49,26 +47,9 @@ func (msg MsgGrant) GetSigners() []sdk.AccAddress { return []sdk.AccAddress{granter} } -// ValidateBasic implements Msg -func (msg MsgGrant) ValidateBasic() error { - granter, err := sdk.AccAddressFromBech32(msg.Granter) - if err != nil { - return sdkerrors.ErrInvalidAddress.Wrapf("invalid granter address: %s", err) - } - grantee, err := sdk.AccAddressFromBech32(msg.Grantee) - if err != nil { - return sdkerrors.ErrInvalidAddress.Wrapf("invalid grantee address: %s", err) - } - - if granter.Equals(grantee) { - return ErrGranteeIsGranter - } - return msg.Grant.ValidateBasic() -} - // GetSignBytes implements the LegacyMsg.GetSignBytes method. func (msg MsgGrant) GetSignBytes() []byte { - return sdk.MustSortJSON(authzcodec.ModuleCdc.MustMarshalJSON(&msg)) + return sdk.MustSortJSON(authzcodec.Amino.MustMarshalJSON(&msg)) } // GetAuthorization returns the cache value from the MsgGrant.Authorization if present. @@ -109,9 +90,7 @@ func (msg MsgGrant) UnpackInterfaces(unpacker cdctypes.AnyUnpacker) error { } // NewMsgRevoke creates a new MsgRevoke -// -//nolint:interfacer -func NewMsgRevoke(granter sdk.AccAddress, grantee sdk.AccAddress, msgTypeURL string) MsgRevoke { +func NewMsgRevoke(granter, grantee sdk.AccAddress, msgTypeURL string) MsgRevoke { return MsgRevoke{ Granter: granter.String(), Grantee: grantee.String(), @@ -125,36 +104,12 @@ func (msg MsgRevoke) GetSigners() []sdk.AccAddress { return []sdk.AccAddress{granter} } -// ValidateBasic implements MsgRequest.ValidateBasic -func (msg MsgRevoke) ValidateBasic() error { - granter, err := sdk.AccAddressFromBech32(msg.Granter) - if err != nil { - return sdkerrors.ErrInvalidAddress.Wrapf("invalid granter address: %s", err) - } - grantee, err := sdk.AccAddressFromBech32(msg.Grantee) - if err != nil { - return sdkerrors.ErrInvalidAddress.Wrapf("invalid grantee address: %s", err) - } - - if granter.Equals(grantee) { - return ErrGranteeIsGranter - } - - if msg.MsgTypeUrl == "" { - return sdkerrors.ErrInvalidRequest.Wrap("missing method name") - } - - return nil -} - // GetSignBytes implements the LegacyMsg.GetSignBytes method. func (msg MsgRevoke) GetSignBytes() []byte { - return sdk.MustSortJSON(authzcodec.ModuleCdc.MustMarshalJSON(&msg)) + return sdk.MustSortJSON(authzcodec.Amino.MustMarshalJSON(&msg)) } // NewMsgExec creates a new MsgExecAuthorized -// -//nolint:interfacer func NewMsgExec(grantee sdk.AccAddress, msgs []sdk.Msg) MsgExec { msgsAny := make([]*cdctypes.Any, len(msgs)) for i, msg := range msgs { @@ -192,30 +147,7 @@ func (msg MsgExec) GetSigners() []sdk.AccAddress { return []sdk.AccAddress{grantee} } -// ValidateBasic implements Msg -func (msg MsgExec) ValidateBasic() error { - if _, err := sdk.AccAddressFromBech32(msg.Grantee); err != nil { - return sdkerrors.ErrInvalidAddress.Wrapf("invalid grantee address: %s", err) - } - - if len(msg.Msgs) == 0 { - return sdkerrors.ErrInvalidRequest.Wrapf("messages cannot be empty") - } - - msgs, err := msg.GetMessages() - if err != nil { - return err - } - for _, msg := range msgs { - if err = msg.ValidateBasic(); err != nil { - return err - } - } - - return nil -} - // GetSignBytes implements the LegacyMsg.GetSignBytes method. func (msg MsgExec) GetSignBytes() []byte { - return sdk.MustSortJSON(authzcodec.ModuleCdc.MustMarshalJSON(&msg)) + return sdk.MustSortJSON(authzcodec.Amino.MustMarshalJSON(&msg)) } diff --git a/x/authz/msgs_test.go b/x/authz/msgs_test.go index 5d7eb3c39fb9..6514dad55d3e 100644 --- a/x/authz/msgs_test.go +++ b/x/authz/msgs_test.go @@ -6,6 +6,7 @@ import ( stakingtypes "github.com/cosmos/cosmos-sdk/x/staking/types" + sdkmath "cosmossdk.io/math" "github.com/stretchr/testify/require" cdctypes "github.com/cosmos/cosmos-sdk/codec/types" @@ -15,132 +16,6 @@ import ( banktypes "github.com/cosmos/cosmos-sdk/x/bank/types" ) -var ( - coinsPos = sdk.NewCoins(sdk.NewInt64Coin("steak", 100)) - granter = sdk.AccAddress("_______granter______") - grantee = sdk.AccAddress("_______grantee______") -) - -func TestMsgExecAuthorized(t *testing.T) { - tests := []struct { - title string - grantee sdk.AccAddress - msgs []sdk.Msg - expectPass bool - }{ - {"nil grantee address", nil, []sdk.Msg{}, false}, - {"zero-messages test: should fail", grantee, []sdk.Msg{}, false}, - {"invalid nested msg", grantee, []sdk.Msg{ - &banktypes.MsgSend{ - Amount: sdk.NewCoins(sdk.NewInt64Coin("steak", 2)), - FromAddress: "invalid_from_address", - ToAddress: grantee.String(), - }, - }, false}, - {"valid test: msg type", grantee, []sdk.Msg{ - &banktypes.MsgSend{ - Amount: sdk.NewCoins(sdk.NewInt64Coin("steak", 2)), - FromAddress: granter.String(), - ToAddress: grantee.String(), - }, - }, true}, - } - for i, tc := range tests { - msg := authz.NewMsgExec(tc.grantee, tc.msgs) - if tc.expectPass { - require.NoError(t, msg.ValidateBasic(), "test: %v", i) - } else { - require.Error(t, msg.ValidateBasic(), "test: %v", i) - } - } -} - -func TestMsgRevokeAuthorization(t *testing.T) { - tests := []struct { - title string - granter, grantee sdk.AccAddress - msgType string - expectPass bool - }{ - {"nil Granter address", nil, grantee, "hello", false}, - {"nil Grantee address", granter, nil, "hello", false}, - {"nil Granter and Grantee address", nil, nil, "hello", false}, - {"valid test case", granter, grantee, "hello", true}, - } - for i, tc := range tests { - msg := authz.NewMsgRevoke(tc.granter, tc.grantee, tc.msgType) - if tc.expectPass { - require.NoError(t, msg.ValidateBasic(), "test: %v", i) - } else { - require.Error(t, msg.ValidateBasic(), "test: %v", i) - } - } -} - -// add time interval to a time object and returns a pointer -func addDatePtr(t *time.Time, months, days int) *time.Time { - t2 := t.AddDate(0, months, days) - return &t2 -} - -func TestMsgGrantAuthorization(t *testing.T) { - now := time.Now() - tests := []struct { - name string - granter, grantee sdk.AccAddress - authorization authz.Authorization - expiration *time.Time - expectErr bool - valBasic bool - }{ - { - "nil granter address", - nil, grantee, &banktypes.SendAuthorization{SpendLimit: coinsPos}, &now, false, false, - }, - { - "nil grantee address", - granter, nil, &banktypes.SendAuthorization{SpendLimit: coinsPos}, &now, false, false, - }, - { - "nil granter and grantee address", - nil, nil, &banktypes.SendAuthorization{SpendLimit: coinsPos}, &now, false, false, - }, - { - "nil authorization should fail", - granter, grantee, nil, &now, true, false, - }, - { - "valid test case", - granter, grantee, &banktypes.SendAuthorization{SpendLimit: coinsPos}, addDatePtr(&now, 1, 0), false, true, - }, - { - "valid test case with nil expire time", - granter, grantee, &banktypes.SendAuthorization{SpendLimit: coinsPos}, nil, false, true, - }, - // we don't access the block time / nor time.Now, so we don't know if it's in the past at this level. - { - "past expire time should not fail", - granter, grantee, &banktypes.SendAuthorization{SpendLimit: coinsPos}, addDatePtr(&now, 0, -1), false, true, - }, - } - for _, tc := range tests { - msg, err := authz.NewMsgGrant( - tc.granter, tc.grantee, tc.authorization, tc.expiration, - ) - if !tc.expectErr { - require.NoError(t, err, "test: %v", tc.name) - } else { - require.Error(t, err, "test: %v", tc.name) - continue - } - if tc.valBasic { - require.NoError(t, msg.ValidateBasic(), "test: %v", tc.name) - } else { - require.Error(t, msg.ValidateBasic(), "test: %v", tc.name) - } - } -} - func TestMsgGrantGetAuthorization(t *testing.T) { require := require.New(t) @@ -174,7 +49,7 @@ func TestAminoJSON(t *testing.T) { require.NoError(t, err) grant, err := authz.NewGrant(blockTime, authz.NewGenericAuthorization(typeURL), &expiresAt) require.NoError(t, err) - sendAuthz := banktypes.NewSendAuthorization(sdk.NewCoins(sdk.NewCoin("stake", sdk.NewInt(1000))), nil) + sendAuthz := banktypes.NewSendAuthorization(sdk.NewCoins(sdk.NewCoin("stake", sdkmath.NewInt(1000))), nil) sendGrant, err := authz.NewGrant(blockTime, sendAuthz, &expiresAt) require.NoError(t, err) valAddr, err := sdk.ValAddressFromBech32("cosmosvaloper1xcy3els9ua75kdm783c3qu0rfa2eples6eavqq") diff --git a/x/authz/simulation/genesis.go b/x/authz/simulation/genesis.go index e1443683bb18..ab49f02aa674 100644 --- a/x/authz/simulation/genesis.go +++ b/x/authz/simulation/genesis.go @@ -4,6 +4,8 @@ import ( "math/rand" "time" + sdkmath "cosmossdk.io/math" + codectypes "github.com/cosmos/cosmos-sdk/codec/types" sdk "github.com/cosmos/cosmos-sdk/types" "github.com/cosmos/cosmos-sdk/types/module" @@ -37,7 +39,7 @@ func genGrant(r *rand.Rand, accounts []simtypes.Account, genT time.Time) []authz func generateRandomGrant(r *rand.Rand) *codectypes.Any { authorizations := make([]*codectypes.Any, 2) - sendAuthz := banktypes.NewSendAuthorization(sdk.NewCoins(sdk.NewCoin("stake", sdk.NewInt(1000))), nil) + sendAuthz := banktypes.NewSendAuthorization(sdk.NewCoins(sdk.NewCoin("stake", sdkmath.NewInt(1000))), nil) authorizations[0] = newAnyAuthorization(sendAuthz) authorizations[1] = newAnyAuthorization(authz.NewGenericAuthorization(sdk.MsgTypeURL(&v1.MsgSubmitProposal{}))) diff --git a/x/authz/simulation/operations.go b/x/authz/simulation/operations.go index 33fe08dea025..5375970760eb 100644 --- a/x/authz/simulation/operations.go +++ b/x/authz/simulation/operations.go @@ -5,13 +5,13 @@ import ( "time" "github.com/cosmos/cosmos-sdk/baseapp" + "github.com/cosmos/cosmos-sdk/client" "github.com/cosmos/cosmos-sdk/codec" cdctypes "github.com/cosmos/cosmos-sdk/codec/types" simtestutil "github.com/cosmos/cosmos-sdk/testutil/sims" sdk "github.com/cosmos/cosmos-sdk/types" sdkerrors "github.com/cosmos/cosmos-sdk/types/errors" simtypes "github.com/cosmos/cosmos-sdk/types/simulation" - "github.com/cosmos/cosmos-sdk/x/auth/tx" "github.com/cosmos/cosmos-sdk/x/authz" "github.com/cosmos/cosmos-sdk/x/authz/keeper" banktype "github.com/cosmos/cosmos-sdk/x/bank/types" @@ -27,9 +27,9 @@ var ( // Simulation operation weights constants const ( - OpWeightMsgGrant = "op_weight_msg_grant" //nolint:gosec - OpWeightRevoke = "op_weight_msg_revoke" //nolint:gosec - OpWeightExec = "op_weight_msg_execute" //nolint:gosec + OpWeightMsgGrant = "op_weight_msg_grant" + OpWeightRevoke = "op_weight_msg_revoke" + OpWeightExec = "op_weight_msg_execute" ) // authz operations weights @@ -44,6 +44,7 @@ func WeightedOperations( registry cdctypes.InterfaceRegistry, appParams simtypes.AppParams, cdc codec.JSONCodec, + txGen client.TxConfig, ak authz.AccountKeeper, bk authz.BankKeeper, k keeper.Keeper, @@ -72,24 +73,32 @@ func WeightedOperations( }, ) + pCdc := codec.NewProtoCodec(registry) + return simulation.WeightedOperations{ simulation.NewWeightedOperation( weightMsgGrant, - SimulateMsgGrant(codec.NewProtoCodec(registry), ak, bk, k), + SimulateMsgGrant(pCdc, txGen, ak, bk, k), ), simulation.NewWeightedOperation( weightExec, - SimulateMsgExec(codec.NewProtoCodec(registry), ak, bk, k, registry), + SimulateMsgExec(pCdc, txGen, ak, bk, k, registry), ), simulation.NewWeightedOperation( weightRevoke, - SimulateMsgRevoke(codec.NewProtoCodec(registry), ak, bk, k), + SimulateMsgRevoke(pCdc, txGen, ak, bk, k), ), } } // SimulateMsgGrant generates a MsgGrant with random values. -func SimulateMsgGrant(cdc *codec.ProtoCodec, ak authz.AccountKeeper, bk authz.BankKeeper, _ keeper.Keeper) simtypes.Operation { +func SimulateMsgGrant( + cdc *codec.ProtoCodec, + txCfg client.TxConfig, + ak authz.AccountKeeper, + bk authz.BankKeeper, + _ keeper.Keeper, +) simtypes.Operation { return func( r *rand.Rand, app *baseapp.BaseApp, ctx sdk.Context, accs []simtypes.Account, chainID string, ) (simtypes.OperationMsg, []simtypes.FutureOperation, error) { @@ -123,7 +132,6 @@ func SimulateMsgGrant(cdc *codec.ProtoCodec, ak authz.AccountKeeper, bk authz.Ba if err != nil { return simtypes.NoOpMsg(authz.ModuleName, TypeMsgGrant, err.Error()), nil, err } - txCfg := tx.NewTxConfig(cdc, tx.DefaultSignModes) tx, err := simtestutil.GenSignedMockTx( r, txCfg, @@ -157,7 +165,13 @@ func generateRandomAuthorization(r *rand.Rand, spendLimit sdk.Coins) authz.Autho } // SimulateMsgRevoke generates a MsgRevoke with random values. -func SimulateMsgRevoke(cdc *codec.ProtoCodec, ak authz.AccountKeeper, bk authz.BankKeeper, k keeper.Keeper) simtypes.Operation { +func SimulateMsgRevoke( + cdc *codec.ProtoCodec, + txCfg client.TxConfig, + ak authz.AccountKeeper, + bk authz.BankKeeper, + k keeper.Keeper, +) simtypes.Operation { return func( r *rand.Rand, app *baseapp.BaseApp, ctx sdk.Context, accs []simtypes.Account, chainID string, ) (simtypes.OperationMsg, []simtypes.FutureOperation, error) { @@ -194,7 +208,6 @@ func SimulateMsgRevoke(cdc *codec.ProtoCodec, ak authz.AccountKeeper, bk authz.B } msg := authz.NewMsgRevoke(granterAddr, granteeAddr, a.MsgTypeURL()) - txCfg := tx.NewTxConfig(cdc, tx.DefaultSignModes) account := ak.GetAccount(ctx, granterAddr) tx, err := simtestutil.GenSignedMockTx( r, @@ -221,7 +234,14 @@ func SimulateMsgRevoke(cdc *codec.ProtoCodec, ak authz.AccountKeeper, bk authz.B } // SimulateMsgExec generates a MsgExec with random values. -func SimulateMsgExec(cdc *codec.ProtoCodec, ak authz.AccountKeeper, bk authz.BankKeeper, k keeper.Keeper, unpacker cdctypes.AnyUnpacker) simtypes.Operation { +func SimulateMsgExec( + cdc *codec.ProtoCodec, + txCfg client.TxConfig, + ak authz.AccountKeeper, + bk authz.BankKeeper, + k keeper.Keeper, + unpacker cdctypes.AnyUnpacker, +) simtypes.Operation { return func( r *rand.Rand, app *baseapp.BaseApp, ctx sdk.Context, accs []simtypes.Account, chainID string, ) (simtypes.OperationMsg, []simtypes.FutureOperation, error) { @@ -288,7 +308,6 @@ func SimulateMsgExec(cdc *codec.ProtoCodec, ak authz.AccountKeeper, bk authz.Ban return simtypes.NoOpMsg(authz.ModuleName, TypeMsgExec, "fee error"), nil, err } - txCfg := tx.NewTxConfig(cdc, tx.DefaultSignModes) granteeAcc := ak.GetAccount(ctx, granteeAddr) tx, err := simtestutil.GenSignedMockTx( r, diff --git a/x/authz/simulation/operations_test.go b/x/authz/simulation/operations_test.go index 3a5ec4c9380d..7e298fb93ceb 100644 --- a/x/authz/simulation/operations_test.go +++ b/x/authz/simulation/operations_test.go @@ -9,6 +9,7 @@ import ( cmtproto "github.com/cometbft/cometbft/proto/tendermint/types" "github.com/stretchr/testify/suite" + "github.com/cosmos/cosmos-sdk/client" "github.com/cosmos/cosmos-sdk/codec" codectypes "github.com/cosmos/cosmos-sdk/codec/types" "github.com/cosmos/cosmos-sdk/runtime" @@ -34,6 +35,7 @@ type SimTestSuite struct { legacyAmino *codec.LegacyAmino codec codec.Codec interfaceRegistry codectypes.InterfaceRegistry + txConfig client.TxConfig accountKeeper authkeeper.AccountKeeper bankKeeper bankkeeper.Keeper authzKeeper authzkeeper.Keeper @@ -45,6 +47,7 @@ func (suite *SimTestSuite) SetupTest() { &suite.legacyAmino, &suite.codec, &suite.interfaceRegistry, + &suite.txConfig, &suite.accountKeeper, &suite.bankKeeper, &suite.authzKeeper, @@ -58,7 +61,7 @@ func (suite *SimTestSuite) TestWeightedOperations() { cdc := suite.codec appParams := make(simtypes.AppParams) - weightedOps := simulation.WeightedOperations(suite.interfaceRegistry, appParams, cdc, suite.accountKeeper, + weightedOps := simulation.WeightedOperations(suite.interfaceRegistry, appParams, cdc, suite.txConfig, suite.accountKeeper, suite.bankKeeper, suite.authzKeeper) s := rand.NewSource(3) @@ -125,7 +128,7 @@ func (suite *SimTestSuite) TestSimulateGrant() { grantee := accounts[1] // execute operation - op := simulation.SimulateMsgGrant(codec.NewProtoCodec(suite.interfaceRegistry), suite.accountKeeper, suite.bankKeeper, suite.authzKeeper) + op := simulation.SimulateMsgGrant(codec.NewProtoCodec(suite.interfaceRegistry), suite.txConfig, suite.accountKeeper, suite.bankKeeper, suite.authzKeeper) operationMsg, futureOperations, err := op(r, suite.app.BaseApp, ctx, accounts, "") suite.Require().NoError(err) @@ -163,7 +166,7 @@ func (suite *SimTestSuite) TestSimulateRevoke() { suite.Require().NoError(err) // execute operation - op := simulation.SimulateMsgRevoke(codec.NewProtoCodec(suite.interfaceRegistry), suite.accountKeeper, suite.bankKeeper, suite.authzKeeper) + op := simulation.SimulateMsgRevoke(codec.NewProtoCodec(suite.interfaceRegistry), suite.txConfig, suite.accountKeeper, suite.bankKeeper, suite.authzKeeper) operationMsg, futureOperations, err := op(r, suite.app.BaseApp, suite.ctx, accounts, "") suite.Require().NoError(err) @@ -198,7 +201,7 @@ func (suite *SimTestSuite) TestSimulateExec() { suite.Require().NoError(err) // execute operation - op := simulation.SimulateMsgExec(codec.NewProtoCodec(suite.interfaceRegistry), suite.accountKeeper, suite.bankKeeper, suite.authzKeeper, suite.codec) + op := simulation.SimulateMsgExec(codec.NewProtoCodec(suite.interfaceRegistry), suite.txConfig, suite.accountKeeper, suite.bankKeeper, suite.authzKeeper, suite.codec) operationMsg, futureOperations, err := op(r, suite.app.BaseApp, suite.ctx, accounts, "") suite.Require().NoError(err) diff --git a/x/authz/testutil/expected_keepers_mocks.go b/x/authz/testutil/expected_keepers_mocks.go index 82cb5c48d460..ee664fb66a12 100644 --- a/x/authz/testutil/expected_keepers_mocks.go +++ b/x/authz/testutil/expected_keepers_mocks.go @@ -5,6 +5,7 @@ package testutil import ( + context "context" reflect "reflect" types "github.com/cosmos/cosmos-sdk/types" @@ -34,8 +35,23 @@ func (m *MockAccountKeeper) EXPECT() *MockAccountKeeperMockRecorder { return m.recorder } +// BytesToString mocks base method. +func (m *MockAccountKeeper) BytesToString(bz []byte) (string, error) { + m.ctrl.T.Helper() + ret := m.ctrl.Call(m, "BytesToString", bz) + ret0, _ := ret[0].(string) + ret1, _ := ret[1].(error) + return ret0, ret1 +} + +// BytesToString indicates an expected call of BytesToString. +func (mr *MockAccountKeeperMockRecorder) BytesToString(bz interface{}) *gomock.Call { + mr.mock.ctrl.T.Helper() + return mr.mock.ctrl.RecordCallWithMethodType(mr.mock, "BytesToString", reflect.TypeOf((*MockAccountKeeper)(nil).BytesToString), bz) +} + // GetAccount mocks base method. -func (m *MockAccountKeeper) GetAccount(ctx types.Context, addr types.AccAddress) types.AccountI { +func (m *MockAccountKeeper) GetAccount(ctx context.Context, addr types.AccAddress) types.AccountI { m.ctrl.T.Helper() ret := m.ctrl.Call(m, "GetAccount", ctx, addr) ret0, _ := ret[0].(types.AccountI) @@ -49,7 +65,7 @@ func (mr *MockAccountKeeperMockRecorder) GetAccount(ctx, addr interface{}) *gomo } // NewAccountWithAddress mocks base method. -func (m *MockAccountKeeper) NewAccountWithAddress(ctx types.Context, addr types.AccAddress) types.AccountI { +func (m *MockAccountKeeper) NewAccountWithAddress(ctx context.Context, addr types.AccAddress) types.AccountI { m.ctrl.T.Helper() ret := m.ctrl.Call(m, "NewAccountWithAddress", ctx, addr) ret0, _ := ret[0].(types.AccountI) @@ -63,7 +79,7 @@ func (mr *MockAccountKeeperMockRecorder) NewAccountWithAddress(ctx, addr interfa } // SetAccount mocks base method. -func (m *MockAccountKeeper) SetAccount(ctx types.Context, acc types.AccountI) { +func (m *MockAccountKeeper) SetAccount(ctx context.Context, acc types.AccountI) { m.ctrl.T.Helper() m.ctrl.Call(m, "SetAccount", ctx, acc) } @@ -74,6 +90,21 @@ func (mr *MockAccountKeeperMockRecorder) SetAccount(ctx, acc interface{}) *gomoc return mr.mock.ctrl.RecordCallWithMethodType(mr.mock, "SetAccount", reflect.TypeOf((*MockAccountKeeper)(nil).SetAccount), ctx, acc) } +// StringToBytes mocks base method. +func (m *MockAccountKeeper) StringToBytes(text string) ([]byte, error) { + m.ctrl.T.Helper() + ret := m.ctrl.Call(m, "StringToBytes", text) + ret0, _ := ret[0].([]byte) + ret1, _ := ret[1].(error) + return ret0, ret1 +} + +// StringToBytes indicates an expected call of StringToBytes. +func (mr *MockAccountKeeperMockRecorder) StringToBytes(text interface{}) *gomock.Call { + mr.mock.ctrl.T.Helper() + return mr.mock.ctrl.RecordCallWithMethodType(mr.mock, "StringToBytes", reflect.TypeOf((*MockAccountKeeper)(nil).StringToBytes), text) +} + // MockBankKeeper is a mock of BankKeeper interface. type MockBankKeeper struct { ctrl *gomock.Controller diff --git a/x/bank/app_test.go b/x/bank/app_test.go index e6bcf28355fa..a47e060a96f5 100644 --- a/x/bank/app_test.go +++ b/x/bank/app_test.go @@ -3,6 +3,7 @@ package bank_test import ( "testing" + sdkmath "cosmossdk.io/math" cmtproto "github.com/cometbft/cometbft/proto/tendermint/types" "github.com/stretchr/testify/assert" "github.com/stretchr/testify/require" @@ -155,7 +156,7 @@ func TestSendNotEnoughBalance(t *testing.T) { sendMsg := types.NewMsgSend(addr1, addr2, sdk.Coins{sdk.NewInt64Coin("foocoin", 100)}) header := cmtproto.Header{Height: baseApp.LastBlockHeight() + 1} - txConfig := moduletestutil.MakeTestEncodingConfig().TxConfig + txConfig := moduletestutil.MakeTestTxConfig() _, _, err := simtestutil.SignCheckDeliver(t, txConfig, baseApp, header, []sdk.Msg{sendMsg}, "", []uint64{origAccNum}, []uint64{origSeq}, false, false, priv1) require.Error(t, err) @@ -232,7 +233,7 @@ func TestMsgMultiSendWithAccounts(t *testing.T) { for _, tc := range testCases { header := cmtproto.Header{Height: baseApp.LastBlockHeight() + 1} - txConfig := moduletestutil.MakeTestEncodingConfig().TxConfig + txConfig := moduletestutil.MakeTestTxConfig() _, _, err := simtestutil.SignCheckDeliver(t, txConfig, baseApp, header, tc.msgs, "", tc.accNums, tc.accSeqs, tc.expSimPass, tc.expPass, tc.privKeys...) if tc.expPass { require.NoError(t, err) @@ -283,7 +284,7 @@ func TestMsgMultiSendMultipleOut(t *testing.T) { for _, tc := range testCases { header := cmtproto.Header{Height: baseApp.LastBlockHeight() + 1} - txConfig := moduletestutil.MakeTestEncodingConfig().TxConfig + txConfig := moduletestutil.MakeTestTxConfig() _, _, err := simtestutil.SignCheckDeliver(t, txConfig, baseApp, header, tc.msgs, "", tc.accNums, tc.accSeqs, tc.expSimPass, tc.expPass, tc.privKeys...) require.NoError(t, err) @@ -336,7 +337,7 @@ func TestMsgMultiSendDependent(t *testing.T) { for _, tc := range testCases { header := cmtproto.Header{Height: baseApp.LastBlockHeight() + 1} - txConfig := moduletestutil.MakeTestEncodingConfig().TxConfig + txConfig := moduletestutil.MakeTestTxConfig() _, _, err := simtestutil.SignCheckDeliver(t, txConfig, baseApp, header, tc.msgs, "", tc.accNums, tc.accSeqs, tc.expSimPass, tc.expPass, tc.privKeys...) require.NoError(t, err) @@ -360,7 +361,7 @@ func TestMsgSetSendEnabled(t *testing.T) { []sdk.Msg{ types.NewMsgSetSendEnabled(govAddr, nil, nil), }, - sdk.Coins{{Denom: "foocoin", Amount: sdk.NewInt(5)}}, + sdk.Coins{{Denom: "foocoin", Amount: sdkmath.NewInt(5)}}, addr1Str, "set default send enabled to true", "Change send enabled", @@ -368,18 +369,6 @@ func TestMsgSetSendEnabled(t *testing.T) { false, ) require.NoError(t, err, "making goodGovProp") - badGovProp, err := govv1.NewMsgSubmitProposal( - []sdk.Msg{ - types.NewMsgSetSendEnabled(govAddr, []*types.SendEnabled{{Denom: "bad coin name!", Enabled: true}}, nil), - }, - sdk.Coins{{Denom: "foocoin", Amount: sdk.NewInt(5)}}, - addr1Str, - "set default send enabled to true", - "Change send enabled", - "Modify send enabled and set to true", - false, - ) - require.NoError(t, err, "making badGovProp") testCases := []appTestCase{ { @@ -422,25 +411,12 @@ func TestMsgSetSendEnabled(t *testing.T) { accSeqs: []uint64{1}, expInError: nil, }, - { - desc: "submitted bad as gov prop", - expSimPass: false, - expPass: false, - msgs: []sdk.Msg{ - badGovProp, - }, - accSeqs: []uint64{2}, - expInError: []string{ - "invalid denom: bad coin name!", - "invalid proposal message", - }, - }, } for _, tc := range testCases { t.Run(tc.desc, func(tt *testing.T) { header := cmtproto.Header{Height: s.App.LastBlockHeight() + 1} - txGen := moduletestutil.MakeTestEncodingConfig().TxConfig + txGen := moduletestutil.MakeTestTxConfig() _, _, err = simtestutil.SignCheckDeliver(tt, txGen, s.App.BaseApp, header, tc.msgs, "", []uint64{0}, tc.accSeqs, tc.expSimPass, tc.expPass, priv1) if len(tc.expInError) > 0 { require.Error(tt, err) diff --git a/x/bank/bench_test.go b/x/bank/bench_test.go index ce0dbb23dc9c..bbfed71d6f2e 100644 --- a/x/bank/bench_test.go +++ b/x/bank/bench_test.go @@ -76,7 +76,7 @@ func BenchmarkOneBankSendTxPerBlock(b *testing.B) { require.NoError(b, testutil.FundAccount(s.BankKeeper, ctx, addr1, sdk.NewCoins(sdk.NewInt64Coin("foocoin", 100000000000)))) baseApp.Commit() - txGen := moduletestutil.MakeTestEncodingConfig().TxConfig + txGen := moduletestutil.MakeTestTxConfig() // Precompute all txs txs, err := genSequenceOfTxs(txGen, []sdk.Msg{sendMsg1}, []uint64{0}, []uint64{uint64(0)}, b.N, priv1) @@ -121,7 +121,7 @@ func BenchmarkOneBankMultiSendTxPerBlock(b *testing.B) { require.NoError(b, testutil.FundAccount(s.BankKeeper, ctx, addr1, sdk.NewCoins(sdk.NewInt64Coin("foocoin", 100000000000)))) baseApp.Commit() - txGen := moduletestutil.MakeTestEncodingConfig().TxConfig + txGen := moduletestutil.MakeTestTxConfig() // Precompute all txs txs, err := genSequenceOfTxs(txGen, []sdk.Msg{multiSendMsg1}, []uint64{0}, []uint64{uint64(0)}, b.N, priv1) diff --git a/x/bank/client/cli/query_test.go b/x/bank/client/cli/query_test.go index 2708a9063625..52ef682fcebc 100644 --- a/x/bank/client/cli/query_test.go +++ b/x/bank/client/cli/query_test.go @@ -1,7 +1,6 @@ package cli_test import ( - "bytes" "context" "fmt" "io" @@ -99,21 +98,18 @@ func (s *CLITestSuite) TestGetBalancesCmd() { tc := tc s.Run(tc.name, func() { - var outBuf bytes.Buffer - - clientCtx := tc.ctxGen().WithOutput(&outBuf) ctx := svrcmd.CreateExecuteContext(context.Background()) cmd.SetContext(ctx) cmd.SetArgs(tc.args) - s.Require().NoError(client.SetCmdClientContextHandler(clientCtx, cmd)) + s.Require().NoError(client.SetCmdClientContextHandler(tc.ctxGen(), cmd)) - err := cmd.Execute() + out, err := clitestutil.ExecTestCLICmd(tc.ctxGen(), cmd, tc.args) if tc.expectErr { s.Require().Error(err) } else { - s.Require().NoError(s.encCfg.Codec.UnmarshalJSON(outBuf.Bytes(), tc.expectResult)) + s.Require().NoError(s.encCfg.Codec.UnmarshalJSON(out.Bytes(), tc.expectResult)) s.Require().NoError(err) } }) @@ -183,21 +179,16 @@ func (s *CLITestSuite) TestGetSpendableBalancesCmd() { tc := tc s.Run(tc.name, func() { - var outBuf bytes.Buffer - - clientCtx := tc.ctxGen().WithOutput(&outBuf) ctx := svrcmd.CreateExecuteContext(context.Background()) - cmd.SetContext(ctx) cmd.SetArgs(tc.args) + s.Require().NoError(client.SetCmdClientContextHandler(tc.ctxGen(), cmd)) - s.Require().NoError(client.SetCmdClientContextHandler(clientCtx, cmd)) - - err := cmd.Execute() + out, err := clitestutil.ExecTestCLICmd(tc.ctxGen(), cmd, tc.args) if tc.expectErr { s.Require().Error(err) } else { - s.Require().NoError(s.encCfg.Codec.UnmarshalJSON(outBuf.Bytes(), tc.expectResult)) + s.Require().NoError(s.encCfg.Codec.UnmarshalJSON(out.Bytes(), tc.expectResult)) s.Require().NoError(err) } }) @@ -266,21 +257,18 @@ func (s *CLITestSuite) TestGetCmdDenomsMetadata() { tc := tc s.Run(tc.name, func() { - var outBuf bytes.Buffer - - clientCtx := tc.ctxGen().WithOutput(&outBuf) ctx := svrcmd.CreateExecuteContext(context.Background()) cmd.SetContext(ctx) cmd.SetArgs(tc.args) - s.Require().NoError(client.SetCmdClientContextHandler(clientCtx, cmd)) + s.Require().NoError(client.SetCmdClientContextHandler(tc.ctxGen(), cmd)) - err := cmd.Execute() + out, err := clitestutil.ExecTestCLICmd(tc.ctxGen(), cmd, tc.args) if tc.expectErr { s.Require().Error(err) } else { - s.Require().NoError(s.encCfg.Codec.UnmarshalJSON(outBuf.Bytes(), tc.expectResult)) + s.Require().NoError(s.encCfg.Codec.UnmarshalJSON(out.Bytes(), tc.expectResult)) s.Require().NoError(err) } }) @@ -352,21 +340,16 @@ func (s *CLITestSuite) TestGetCmdQueryTotalSupply() { tc := tc s.Run(tc.name, func() { - var outBuf bytes.Buffer - - clientCtx := tc.ctxGen().WithOutput(&outBuf) ctx := svrcmd.CreateExecuteContext(context.Background()) - cmd.SetContext(ctx) cmd.SetArgs(tc.args) + s.Require().NoError(client.SetCmdClientContextHandler(tc.ctxGen(), cmd)) - s.Require().NoError(client.SetCmdClientContextHandler(clientCtx, cmd)) - - err := cmd.Execute() + out, err := clitestutil.ExecTestCLICmd(tc.ctxGen(), cmd, tc.args) if tc.expectErr { s.Require().Error(err) } else { - s.Require().NoError(s.encCfg.Codec.UnmarshalJSON(outBuf.Bytes(), tc.expectResult)) + s.Require().NoError(s.encCfg.Codec.UnmarshalJSON(out.Bytes(), tc.expectResult)) s.Require().NoError(err) } }) @@ -426,21 +409,18 @@ func (s *CLITestSuite) TestGetCmdQuerySendEnabled() { tc := tc s.Run(tc.name, func() { - var outBuf bytes.Buffer - - clientCtx := tc.ctxGen().WithOutput(&outBuf) ctx := svrcmd.CreateExecuteContext(context.Background()) cmd.SetContext(ctx) cmd.SetArgs(tc.args) - s.Require().NoError(client.SetCmdClientContextHandler(clientCtx, cmd)) + s.Require().NoError(client.SetCmdClientContextHandler(tc.ctxGen(), cmd)) - err := cmd.Execute() + out, err := clitestutil.ExecTestCLICmd(tc.ctxGen(), cmd, tc.args) if tc.expectErr { s.Require().Error(err) } else { - s.Require().NoError(s.encCfg.Codec.UnmarshalJSON(outBuf.Bytes(), tc.expectResult)) + s.Require().NoError(s.encCfg.Codec.UnmarshalJSON(out.Bytes(), tc.expectResult)) s.Require().NoError(err) } }) diff --git a/x/bank/client/cli/tx.go b/x/bank/client/cli/tx.go index 8161fa902118..3ccf19c36097 100644 --- a/x/bank/client/cli/tx.go +++ b/x/bank/client/cli/tx.go @@ -3,6 +3,7 @@ package cli import ( "fmt" + sdkmath "cosmossdk.io/math" "github.com/spf13/cobra" "github.com/cosmos/cosmos-sdk/client" @@ -59,6 +60,10 @@ When using '--dry-run' a key name cannot be used, only a bech32 address. return err } + if len(coins) == 0 { + return fmt.Errorf("invalid coins") + } + msg := types.NewMsgSend(clientCtx.GetFromAddress(), toAddr, coins) return tx.GenerateOrBroadcastTxCLI(clientCtx, cmd.Flags(), msg) @@ -104,7 +109,7 @@ When using '--dry-run' a key name cannot be used, only a bech32 address. return err } - totalAddrs := sdk.NewInt(int64(len(args) - 2)) + totalAddrs := sdkmath.NewInt(int64(len(args) - 2)) // coins to be received by the addresses sendCoins := coins if split { diff --git a/x/bank/client/cli/tx_test.go b/x/bank/client/cli/tx_test.go index 7f3fe4b565be..0d66d4944cb4 100644 --- a/x/bank/client/cli/tx_test.go +++ b/x/bank/client/cli/tx_test.go @@ -5,10 +5,13 @@ import ( "fmt" "io" + sdkmath "cosmossdk.io/math" + "github.com/cosmos/cosmos-sdk/client" "github.com/cosmos/cosmos-sdk/client/flags" svrcmd "github.com/cosmos/cosmos-sdk/server/cmd" "github.com/cosmos/cosmos-sdk/testutil" + clitestutil "github.com/cosmos/cosmos-sdk/testutil/cli" sdk "github.com/cosmos/cosmos-sdk/types" "github.com/cosmos/cosmos-sdk/x/bank/client/cli" ) @@ -22,17 +25,17 @@ func (s *CLITestSuite) TestSendTxCmd() { fmt.Sprintf("--%s=%s", flags.FlagBroadcastMode, flags.BroadcastSync), fmt.Sprintf("--%s=true", flags.FlagSkipConfirmation), fmt.Sprintf("--%s=%s", flags.FlagBroadcastMode, flags.BroadcastSync), - fmt.Sprintf("--%s=%s", flags.FlagFees, sdk.NewCoins(sdk.NewCoin("photon", sdk.NewInt(10))).String()), + fmt.Sprintf("--%s=%s", flags.FlagFees, sdk.NewCoins(sdk.NewCoin("photon", sdkmath.NewInt(10))).String()), fmt.Sprintf("--%s=test-chain", flags.FlagChainID), } testCases := []struct { - name string - ctxGen func() client.Context - from, to sdk.AccAddress - amount sdk.Coins - extraArgs []string - expectErr bool + name string + ctxGen func() client.Context + from, to sdk.AccAddress + amount sdk.Coins + extraArgs []string + expectErrMsg string }{ { "valid transaction", @@ -42,11 +45,11 @@ func (s *CLITestSuite) TestSendTxCmd() { accounts[0].Address, accounts[0].Address, sdk.NewCoins( - sdk.NewCoin("stake", sdk.NewInt(10)), - sdk.NewCoin("photon", sdk.NewInt(40)), + sdk.NewCoin("stake", sdkmath.NewInt(10)), + sdk.NewCoin("photon", sdkmath.NewInt(40)), ), extraArgs, - false, + "", }, { "invalid to Address", @@ -56,11 +59,11 @@ func (s *CLITestSuite) TestSendTxCmd() { accounts[0].Address, sdk.AccAddress{}, sdk.NewCoins( - sdk.NewCoin("stake", sdk.NewInt(10)), - sdk.NewCoin("photon", sdk.NewInt(40)), + sdk.NewCoin("stake", sdkmath.NewInt(10)), + sdk.NewCoin("photon", sdkmath.NewInt(40)), ), extraArgs, - true, + "empty address string is not allowed", }, { "invalid coins", @@ -71,25 +74,28 @@ func (s *CLITestSuite) TestSendTxCmd() { accounts[0].Address, nil, extraArgs, - true, + "invalid coins", }, } for _, tc := range testCases { tc := tc s.Run(tc.name, func() { - ctx := svrcmd.CreateExecuteContext(context.Background()) + args := append([]string{tc.from.String(), tc.to.String(), tc.amount.String()}, tc.extraArgs...) + ctx := svrcmd.CreateExecuteContext(context.Background()) cmd.SetContext(ctx) - cmd.SetArgs(append([]string{tc.from.String(), tc.to.String(), tc.amount.String()}, tc.extraArgs...)) - + cmd.SetArgs(args) s.Require().NoError(client.SetCmdClientContextHandler(tc.ctxGen(), cmd)) - err := cmd.Execute() - if tc.expectErr { + out, err := clitestutil.ExecTestCLICmd(tc.ctxGen(), cmd, args) + if tc.expectErrMsg != "" { s.Require().Error(err) + s.Require().Contains(out.String(), tc.expectErrMsg) } else { s.Require().NoError(err) + msg := &sdk.TxResponse{} + s.Require().NoError(tc.ctxGen().Codec.UnmarshalJSON(out.Bytes(), msg), out.String()) } }) } @@ -105,18 +111,18 @@ func (s *CLITestSuite) TestMultiSendTxCmd() { fmt.Sprintf("--%s=%s", flags.FlagBroadcastMode, flags.BroadcastSync), fmt.Sprintf("--%s=true", flags.FlagSkipConfirmation), fmt.Sprintf("--%s=%s", flags.FlagBroadcastMode, flags.BroadcastSync), - fmt.Sprintf("--%s=%s", flags.FlagFees, sdk.NewCoins(sdk.NewCoin("photon", sdk.NewInt(10))).String()), + fmt.Sprintf("--%s=%s", flags.FlagFees, sdk.NewCoins(sdk.NewCoin("photon", sdkmath.NewInt(10))).String()), fmt.Sprintf("--%s=test-chain", flags.FlagChainID), } testCases := []struct { - name string - ctxGen func() client.Context - from string - to []string - amount sdk.Coins - extraArgs []string - expectErr bool + name string + ctxGen func() client.Context + from string + to []string + amount sdk.Coins + extraArgs []string + expectErrMsg string }{ { "valid transaction", @@ -129,11 +135,11 @@ func (s *CLITestSuite) TestMultiSendTxCmd() { accounts[2].Address.String(), }, sdk.NewCoins( - sdk.NewCoin("stake", sdk.NewInt(10)), - sdk.NewCoin("photon", sdk.NewInt(40)), + sdk.NewCoin("stake", sdkmath.NewInt(10)), + sdk.NewCoin("photon", sdkmath.NewInt(40)), ), extraArgs, - false, + "", }, { "invalid from Address", @@ -146,11 +152,11 @@ func (s *CLITestSuite) TestMultiSendTxCmd() { accounts[2].Address.String(), }, sdk.NewCoins( - sdk.NewCoin("stake", sdk.NewInt(10)), - sdk.NewCoin("photon", sdk.NewInt(40)), + sdk.NewCoin("stake", sdkmath.NewInt(10)), + sdk.NewCoin("photon", sdkmath.NewInt(40)), ), extraArgs, - true, + "key not found", }, { "invalid recipients", @@ -163,11 +169,11 @@ func (s *CLITestSuite) TestMultiSendTxCmd() { "bar", }, sdk.NewCoins( - sdk.NewCoin("stake", sdk.NewInt(10)), - sdk.NewCoin("photon", sdk.NewInt(40)), + sdk.NewCoin("stake", sdkmath.NewInt(10)), + sdk.NewCoin("photon", sdkmath.NewInt(40)), ), extraArgs, - true, + "invalid bech32 string", }, { "invalid amount", @@ -181,7 +187,7 @@ func (s *CLITestSuite) TestMultiSendTxCmd() { }, nil, extraArgs, - true, + "must send positive amount", }, } @@ -201,11 +207,14 @@ func (s *CLITestSuite) TestMultiSendTxCmd() { s.Require().NoError(client.SetCmdClientContextHandler(tc.ctxGen(), cmd)) - err := cmd.Execute() - if tc.expectErr { + out, err := clitestutil.ExecTestCLICmd(tc.ctxGen(), cmd, args) + if tc.expectErrMsg != "" { s.Require().Error(err) + s.Require().Contains(out.String(), tc.expectErrMsg) } else { s.Require().NoError(err) + msg := &sdk.TxResponse{} + s.Require().NoError(tc.ctxGen().Codec.UnmarshalJSON(out.Bytes(), msg), out.String()) } }) } diff --git a/x/bank/keeper/genesis.go b/x/bank/keeper/genesis.go index e214570e5035..bbacf5035fef 100644 --- a/x/bank/keeper/genesis.go +++ b/x/bank/keeper/genesis.go @@ -3,6 +3,8 @@ package keeper import ( "fmt" + "cosmossdk.io/collections" + sdk "github.com/cosmos/cosmos-sdk/types" "github.com/cosmos/cosmos-sdk/types/query" "github.com/cosmos/cosmos-sdk/x/bank/types" @@ -24,8 +26,11 @@ func (k BaseKeeper) InitGenesis(ctx sdk.Context, genState *types.GenesisState) { for _, balance := range genState.Balances { addr := balance.GetAddress() - if err := k.initBalances(ctx, addr, balance.Coins); err != nil { - panic(fmt.Errorf("error on setting balances %w", err)) + for _, coin := range balance.Coins { + err := k.Balances.Set(ctx, collections.Join(addr, coin.Denom), coin.Amount) + if err != nil { + panic(err) + } } totalSupply = totalSupply.Add(balance.Coins...) diff --git a/x/bank/keeper/genesis_test.go b/x/bank/keeper/genesis_test.go index 7e7e9e8162a3..ac04a6232c7a 100644 --- a/x/bank/keeper/genesis_test.go +++ b/x/bank/keeper/genesis_test.go @@ -1,6 +1,8 @@ package keeper_test import ( + sdkmath "cosmossdk.io/math" + sdk "github.com/cosmos/cosmos-sdk/types" "github.com/cosmos/cosmos-sdk/types/query" "github.com/cosmos/cosmos-sdk/x/bank/types" @@ -77,11 +79,11 @@ func (suite *KeeperTestSuite) TestTotalSupply() { // Prepare some test data. defaultGenesis := types.DefaultGenesisState() balances := []types.Balance{ - {Coins: sdk.NewCoins(sdk.NewCoin("foocoin", sdk.NewInt(1))), Address: "cosmos1f9xjhxm0plzrh9cskf4qee4pc2xwp0n0556gh0"}, - {Coins: sdk.NewCoins(sdk.NewCoin("barcoin", sdk.NewInt(1))), Address: "cosmos1t5u0jfg3ljsjrh2m9e47d4ny2hea7eehxrzdgd"}, - {Coins: sdk.NewCoins(sdk.NewCoin("foocoin", sdk.NewInt(10)), sdk.NewCoin("barcoin", sdk.NewInt(20))), Address: "cosmos1m3h30wlvsf8llruxtpukdvsy0km2kum8g38c8q"}, + {Coins: sdk.NewCoins(sdk.NewCoin("foocoin", sdkmath.NewInt(1))), Address: "cosmos1f9xjhxm0plzrh9cskf4qee4pc2xwp0n0556gh0"}, + {Coins: sdk.NewCoins(sdk.NewCoin("barcoin", sdkmath.NewInt(1))), Address: "cosmos1t5u0jfg3ljsjrh2m9e47d4ny2hea7eehxrzdgd"}, + {Coins: sdk.NewCoins(sdk.NewCoin("foocoin", sdkmath.NewInt(10)), sdk.NewCoin("barcoin", sdkmath.NewInt(20))), Address: "cosmos1m3h30wlvsf8llruxtpukdvsy0km2kum8g38c8q"}, } - totalSupply := sdk.NewCoins(sdk.NewCoin("foocoin", sdk.NewInt(11)), sdk.NewCoin("barcoin", sdk.NewInt(21))) + totalSupply := sdk.NewCoins(sdk.NewCoin("foocoin", sdkmath.NewInt(11)), sdk.NewCoin("barcoin", sdkmath.NewInt(21))) genesisSupply, _, err := suite.bankKeeper.GetPaginatedTotalSupply(suite.ctx, &query.PageRequest{Limit: query.MaxLimit}) suite.Require().NoError(err) @@ -95,7 +97,7 @@ func (suite *KeeperTestSuite) TestTotalSupply() { }{ { "calculation NOT matching genesis Supply field", - types.NewGenesisState(defaultGenesis.Params, balances, sdk.NewCoins(sdk.NewCoin("wrongcoin", sdk.NewInt(1))), defaultGenesis.DenomMetadata, defaultGenesis.SendEnabled), + types.NewGenesisState(defaultGenesis.Params, balances, sdk.NewCoins(sdk.NewCoin("wrongcoin", sdkmath.NewInt(1))), defaultGenesis.DenomMetadata, defaultGenesis.SendEnabled), nil, true, "genesis supply is incorrect, expected 1wrongcoin, got 21barcoin,11foocoin", }, { diff --git a/x/bank/keeper/grpc_query.go b/x/bank/keeper/grpc_query.go index 49fa628090c7..3592ee33ef8f 100644 --- a/x/bank/keeper/grpc_query.go +++ b/x/bank/keeper/grpc_query.go @@ -3,6 +3,7 @@ package keeper import ( "context" + "cosmossdk.io/collections" "cosmossdk.io/math" "google.golang.org/grpc/codes" "google.golang.org/grpc/status" @@ -51,26 +52,17 @@ func (k BaseKeeper) AllBalances(ctx context.Context, req *types.QueryAllBalances sdkCtx := sdk.UnwrapSDKContext(ctx) balances := sdk.NewCoins() - accountStore := k.getAccountStore(sdkCtx, addr) - pageRes, err := query.Paginate(accountStore, req.Pagination, func(key, value []byte) error { - denom := string(key) - - // IBC denom metadata will be registered in ibc-go after first mint - // - // Since: ibc-go v7 + _, pageRes, err := query.CollectionFilteredPaginate(ctx, k.Balances, req.Pagination, func(key collections.Pair[sdk.AccAddress, string], value math.Int) (include bool, err error) { + denom := key.K2() if req.ResolveDenom { if metadata, ok := k.GetDenomMetaData(sdkCtx, denom); ok { denom = metadata.Display } } - balance, err := UnmarshalBalanceCompat(k.cdc, value, denom) - if err != nil { - return err - } - balances = append(balances, balance) - return nil - }) + balances = append(balances, sdk.NewCoin(denom, value)) + return false, nil // we don't include results because we're appending them here. + }, query.WithCollectionPaginationPairPrefix[sdk.AccAddress, string](addr)) if err != nil { return nil, status.Errorf(codes.InvalidArgument, "paginate: %v", err) } @@ -93,13 +85,12 @@ func (k BaseKeeper) SpendableBalances(ctx context.Context, req *types.QuerySpend sdkCtx := sdk.UnwrapSDKContext(ctx) balances := sdk.NewCoins() - accountStore := k.getAccountStore(sdkCtx, addr) zeroAmt := math.ZeroInt() - pageRes, err := query.Paginate(accountStore, req.Pagination, func(key, _ []byte) error { - balances = append(balances, sdk.NewCoin(string(key), zeroAmt)) - return nil - }) + _, pageRes, err := query.CollectionFilteredPaginate(ctx, k.Balances, req.Pagination, func(key collections.Pair[sdk.AccAddress, string], _ math.Int) (include bool, err error) { + balances = append(balances, sdk.NewCoin(key.K2(), zeroAmt)) + return false, nil // not including results as they're appended here + }, query.WithCollectionPaginationPairPrefix[sdk.AccAddress, string](addr)) if err != nil { return nil, status.Errorf(codes.InvalidArgument, "paginate: %v", err) } @@ -237,34 +228,24 @@ func (k BaseKeeper) DenomOwners( return nil, status.Error(codes.InvalidArgument, err.Error()) } - ctx := sdk.UnwrapSDKContext(goCtx) - denomPrefixStore := k.getDenomAddressPrefixStore(ctx, req.Denom) - var denomOwners []*types.DenomOwner - pageRes, err := query.FilteredPaginate( - denomPrefixStore, - req.Pagination, - func(key []byte, _ []byte, accumulate bool) (bool, error) { - if accumulate { - address, _, err := types.AddressAndDenomFromBalancesStore(key) - if err != nil { - return false, err - } - - denomOwners = append( - denomOwners, - &types.DenomOwner{ - Address: address.String(), - Balance: k.GetBalance(ctx, address, req.Denom), - }, - ) - } - return true, nil + _, pageRes, err := query.CollectionFilteredPaginate(goCtx, k.Balances.Indexes.Denom, req.Pagination, + func(key collections.Pair[string, sdk.AccAddress], value collections.NoValue) (include bool, err error) { + amt, err := k.Balances.Get(goCtx, collections.Join(key.K2(), req.Denom)) + if err != nil { + return false, err + } + denomOwners = append(denomOwners, &types.DenomOwner{ + Address: key.K2().String(), + Balance: sdk.NewCoin(req.Denom, amt), + }) + return false, nil }, + query.WithCollectionPaginationPairPrefix[string, sdk.AccAddress](req.Denom), ) if err != nil { - return nil, status.Error(codes.Internal, err.Error()) + return nil, err } return &types.QueryDenomOwnersResponse{DenomOwners: denomOwners, Pagination: pageRes}, nil diff --git a/x/bank/keeper/grpc_query_test.go b/x/bank/keeper/grpc_query_test.go index 82314501d664..c76850c41834 100644 --- a/x/bank/keeper/grpc_query_test.go +++ b/x/bank/keeper/grpc_query_test.go @@ -461,7 +461,7 @@ func (suite *KeeperTestSuite) TestGRPCDenomOwners() { suite.Require().NoError(keeper.MintCoins(ctx, minttypes.ModuleName, initCoins)) for i := 0; i < 10; i++ { - addr := sdk.AccAddress([]byte(fmt.Sprintf("account-%d", i))) + addr := sdk.AccAddress(fmt.Sprintf("account-%d", i)) bal := sdk.NewCoins(sdk.NewCoin( sdk.DefaultBondDenom, diff --git a/x/bank/keeper/keeper_test.go b/x/bank/keeper/keeper_test.go index 69e0584ed8f5..14d2b7c7f978 100644 --- a/x/bank/keeper/keeper_test.go +++ b/x/bank/keeper/keeper_test.go @@ -78,11 +78,11 @@ func newIbcCoin(amt int64) sdk.Coin { return sdk.NewInt64Coin(getIBCDenom(ibcPath, ibcBaseDenom), amt) } -func getIBCDenom(path string, baseDenom string) string { +func getIBCDenom(path, baseDenom string) string { return fmt.Sprintf("%s/%s", "ibc", hex.EncodeToString(getIBCHash(path, baseDenom))) } -func getIBCHash(path string, baseDenom string) []byte { +func getIBCHash(path, baseDenom string) []byte { hash := sha256.Sum256([]byte(path + "/" + baseDenom)) return hash[:] } @@ -173,7 +173,7 @@ func (suite *KeeperTestSuite) mockBurnCoins(moduleAcc *authtypes.ModuleAccount) suite.authKeeper.EXPECT().GetAccount(suite.ctx, moduleAcc.GetAddress()).Return(moduleAcc) } -func (suite *KeeperTestSuite) mockSendCoinsFromModuleToModule(sender *authtypes.ModuleAccount, receiver *authtypes.ModuleAccount) { +func (suite *KeeperTestSuite) mockSendCoinsFromModuleToModule(sender, receiver *authtypes.ModuleAccount) { suite.authKeeper.EXPECT().GetModuleAddress(sender.Name).Return(sender.GetAddress()) suite.authKeeper.EXPECT().GetModuleAccount(suite.ctx, receiver.Name).Return(receiver) suite.authKeeper.EXPECT().GetAccount(suite.ctx, sender.GetAddress()).Return(sender) @@ -213,7 +213,7 @@ func (suite *KeeperTestSuite) mockSpendableCoins(ctx sdk.Context, acc sdk.Accoun suite.authKeeper.EXPECT().GetAccount(ctx, acc.GetAddress()).Return(acc) } -func (suite *KeeperTestSuite) mockDelegateCoins(ctx sdk.Context, acc sdk.AccountI, mAcc sdk.AccountI) { +func (suite *KeeperTestSuite) mockDelegateCoins(ctx sdk.Context, acc, mAcc sdk.AccountI) { vacc, ok := acc.(banktypes.VestingAccount) if ok { suite.authKeeper.EXPECT().SetAccount(ctx, vacc) @@ -222,7 +222,7 @@ func (suite *KeeperTestSuite) mockDelegateCoins(ctx sdk.Context, acc sdk.Account suite.authKeeper.EXPECT().GetAccount(ctx, mAcc.GetAddress()).Return(mAcc) } -func (suite *KeeperTestSuite) mockUnDelegateCoins(ctx sdk.Context, acc sdk.AccountI, mAcc sdk.AccountI) { +func (suite *KeeperTestSuite) mockUnDelegateCoins(ctx sdk.Context, acc, mAcc sdk.AccountI) { vacc, ok := acc.(banktypes.VestingAccount) if ok { suite.authKeeper.EXPECT().SetAccount(ctx, vacc) @@ -321,18 +321,18 @@ func (suite *KeeperTestSuite) TestSupply_SendCoins() { authKeeper.EXPECT().GetModuleAddress("").Return(nil) require.Panics(func() { - _ = keeper.SendCoinsFromModuleToModule(ctx, "", holderAcc.GetName(), initCoins) //nolint:errcheck + _ = keeper.SendCoinsFromModuleToModule(ctx, "", holderAcc.GetName(), initCoins) //nolint:errcheck // we're testing for a panic, not an error }) authKeeper.EXPECT().GetModuleAddress(burnerAcc.Name).Return(burnerAcc.GetAddress()) authKeeper.EXPECT().GetModuleAccount(ctx, "").Return(nil) require.Panics(func() { - _ = keeper.SendCoinsFromModuleToModule(ctx, authtypes.Burner, "", initCoins) //nolint:errcheck + _ = keeper.SendCoinsFromModuleToModule(ctx, authtypes.Burner, "", initCoins) //nolint:errcheck // we're testing for a panic, not an error }) authKeeper.EXPECT().GetModuleAddress("").Return(nil) require.Panics(func() { - _ = keeper.SendCoinsFromModuleToAccount(ctx, "", baseAcc.GetAddress(), initCoins) //nolint:errcheck + _ = keeper.SendCoinsFromModuleToAccount(ctx, "", baseAcc.GetAddress(), initCoins) //nolint:errcheck // we're testing for a panic, not an error }) authKeeper.EXPECT().GetModuleAddress(holderAcc.Name).Return(holderAcc.GetAddress()) @@ -371,16 +371,16 @@ func (suite *KeeperTestSuite) TestSupply_MintCoins() { require.NoError(err) authKeeper.EXPECT().GetModuleAccount(ctx, "").Return(nil) - require.Panics(func() { _ = keeper.MintCoins(ctx, "", initCoins) }, "no module account") //nolint:errcheck + require.Panics(func() { _ = keeper.MintCoins(ctx, "", initCoins) }, "no module account") //nolint:errcheck // we're testing for a panic, not an error suite.mockMintCoins(burnerAcc) - require.Panics(func() { _ = keeper.MintCoins(ctx, authtypes.Burner, initCoins) }, "invalid permission") //nolint:errcheck + require.Panics(func() { _ = keeper.MintCoins(ctx, authtypes.Burner, initCoins) }, "invalid permission") //nolint:errcheck // we're testing for a panic, not an error suite.mockMintCoins(minterAcc) - require.Error(keeper.MintCoins(ctx, authtypes.Minter, sdk.Coins{sdk.Coin{Denom: "denom", Amount: sdk.NewInt(-10)}}), "insufficient coins") + require.Error(keeper.MintCoins(ctx, authtypes.Minter, sdk.Coins{sdk.Coin{Denom: "denom", Amount: math.NewInt(-10)}}), "insufficient coins") authKeeper.EXPECT().GetModuleAccount(ctx, randomPerm).Return(nil) - require.Panics(func() { _ = keeper.MintCoins(ctx, randomPerm, initCoins) }) //nolint:errcheck + require.Panics(func() { _ = keeper.MintCoins(ctx, randomPerm, initCoins) }) //nolint:errcheck // we're testing for a panic, not an error suite.mockMintCoins(minterAcc) require.NoError(keeper.MintCoins(ctx, authtypes.Minter, initCoins)) @@ -424,13 +424,13 @@ func (suite *KeeperTestSuite) TestSupply_BurnCoins() { require.NoError(err) authKeeper.EXPECT().GetModuleAccount(ctx, "").Return(nil) - require.Panics(func() { _ = keeper.BurnCoins(ctx, "", initCoins) }, "no module account") //nolint:errcheck + require.Panics(func() { _ = keeper.BurnCoins(ctx, "", initCoins) }, "no module account") //nolint:errcheck // we're testing for a panic, not an error authKeeper.EXPECT().GetModuleAccount(ctx, minterAcc.Name).Return(nil) - require.Panics(func() { _ = keeper.BurnCoins(ctx, authtypes.Minter, initCoins) }, "invalid permission") //nolint:errcheck + require.Panics(func() { _ = keeper.BurnCoins(ctx, authtypes.Minter, initCoins) }, "invalid permission") //nolint:errcheck // we're testing for a panic, not an error authKeeper.EXPECT().GetModuleAccount(ctx, randomPerm).Return(nil) - require.Panics(func() { _ = keeper.BurnCoins(ctx, randomPerm, supplyAfterInflation) }, "random permission") //nolint:errcheck + require.Panics(func() { _ = keeper.BurnCoins(ctx, randomPerm, supplyAfterInflation) }, "random permission") //nolint:errcheck // we're testing for a panic, not an error suite.mockBurnCoins(burnerAcc) require.Error(keeper.BurnCoins(ctx, authtypes.Burner, supplyAfterInflation), "insufficient coins") @@ -1051,7 +1051,7 @@ func (suite *KeeperTestSuite) TestDelegateCoins_Invalid() { require.Error(suite.bankKeeper.DelegateCoins(ctx, accAddrs[0], holderAcc.GetAddress(), delCoins)) suite.authKeeper.EXPECT().GetAccount(ctx, holderAcc.GetAddress()).Return(holderAcc) - invalidCoins := sdk.Coins{sdk.Coin{Denom: "fooDenom", Amount: sdk.NewInt(-50)}} + invalidCoins := sdk.Coins{sdk.Coin{Denom: "fooDenom", Amount: math.NewInt(-50)}} require.Error(suite.bankKeeper.DelegateCoins(ctx, accAddrs[0], holderAcc.GetAddress(), invalidCoins)) suite.authKeeper.EXPECT().GetAccount(ctx, holderAcc.GetAddress()).Return(holderAcc) @@ -1199,7 +1199,7 @@ func (suite *KeeperTestSuite) TestBalanceTrackingEvents() { suite.bankKeeper.MintCoins( suite.ctx, multiPermAcc.Name, - sdk.NewCoins(sdk.NewCoin("utxo", sdk.NewInt(100000)))), + sdk.NewCoins(sdk.NewCoin("utxo", math.NewInt(100000)))), ) // send coins to address suite.mockSendCoinsFromModuleToAccount(multiPermAcc, accAddrs[0]) @@ -1208,7 +1208,7 @@ func (suite *KeeperTestSuite) TestBalanceTrackingEvents() { suite.ctx, multiPermAcc.Name, accAddrs[0], - sdk.NewCoins(sdk.NewCoin("utxo", sdk.NewInt(50000))), + sdk.NewCoins(sdk.NewCoin("utxo", math.NewInt(50000))), ), ) diff --git a/x/bank/keeper/msg_server.go b/x/bank/keeper/msg_server.go index 77d58eefd1a5..1a4209411d88 100644 --- a/x/bank/keeper/msg_server.go +++ b/x/bank/keeper/msg_server.go @@ -27,18 +27,26 @@ func NewMsgServerImpl(keeper Keeper) types.MsgServer { } func (k msgServer) Send(goCtx context.Context, msg *types.MsgSend) (*types.MsgSendResponse, error) { - ctx := sdk.UnwrapSDKContext(goCtx) - - if err := k.IsSendEnabledCoins(ctx, msg.Amount...); err != nil { - return nil, err - } - from, err := sdk.AccAddressFromBech32(msg.FromAddress) if err != nil { - return nil, err + return nil, sdkerrors.ErrInvalidAddress.Wrapf("invalid from address: %s", err) } + to, err := sdk.AccAddressFromBech32(msg.ToAddress) if err != nil { + return nil, sdkerrors.ErrInvalidAddress.Wrapf("invalid to address: %s", err) + } + + if !msg.Amount.IsValid() { + return nil, errorsmod.Wrap(sdkerrors.ErrInvalidCoins, msg.Amount.String()) + } + + if !msg.Amount.IsAllPositive() { + return nil, errorsmod.Wrap(sdkerrors.ErrInvalidCoins, msg.Amount.String()) + } + + ctx := sdk.UnwrapSDKContext(goCtx) + if err := k.IsSendEnabledCoins(ctx, msg.Amount...); err != nil { return nil, err } @@ -67,6 +75,22 @@ func (k msgServer) Send(goCtx context.Context, msg *types.MsgSend) (*types.MsgSe } func (k msgServer) MultiSend(goCtx context.Context, msg *types.MsgMultiSend) (*types.MsgMultiSendResponse, error) { + if len(msg.Inputs) == 0 { + return nil, types.ErrNoInputs + } + + if len(msg.Inputs) != 1 { + return nil, types.ErrMultipleSenders + } + + if len(msg.Outputs) == 0 { + return nil, types.ErrNoOutputs + } + + if err := types.ValidateInputOutputs(msg.Inputs[0], msg.Outputs); err != nil { + return nil, err + } + ctx := sdk.UnwrapSDKContext(goCtx) // NOTE: totalIn == totalOut should already have been checked @@ -97,6 +121,10 @@ func (k msgServer) UpdateParams(goCtx context.Context, req *types.MsgUpdateParam return nil, errorsmod.Wrapf(govtypes.ErrInvalidSigner, "invalid authority; expected %s, got %s", k.GetAuthority(), req.Authority) } + if err := req.Params.Validate(); err != nil { + return nil, err + } + ctx := sdk.UnwrapSDKContext(goCtx) if err := k.SetParams(ctx, req.Params); err != nil { return nil, err @@ -110,6 +138,25 @@ func (k msgServer) SetSendEnabled(goCtx context.Context, msg *types.MsgSetSendEn return nil, errorsmod.Wrapf(govtypes.ErrInvalidSigner, "invalid authority; expected %s, got %s", k.GetAuthority(), msg.Authority) } + seen := map[string]bool{} + for _, se := range msg.SendEnabled { + if _, alreadySeen := seen[se.Denom]; alreadySeen { + return nil, sdkerrors.ErrInvalidRequest.Wrapf("duplicate denom entries found for %q", se.Denom) + } + + seen[se.Denom] = true + + if err := se.Validate(); err != nil { + return nil, sdkerrors.ErrInvalidRequest.Wrapf("invalid SendEnabled denom %q: %s", se.Denom, err) + } + } + + for _, denom := range msg.UseDefaultFor { + if err := sdk.ValidateDenom(denom); err != nil { + return nil, sdkerrors.ErrInvalidRequest.Wrapf("invalid UseDefaultFor denom %q: %s", denom, err) + } + } + ctx := sdk.UnwrapSDKContext(goCtx) if len(msg.SendEnabled) > 0 { k.SetAllSendEnabled(ctx, msg.SendEnabled) diff --git a/x/bank/keeper/msg_server_test.go b/x/bank/keeper/msg_server_test.go new file mode 100644 index 000000000000..0a4902688ad9 --- /dev/null +++ b/x/bank/keeper/msg_server_test.go @@ -0,0 +1,362 @@ +package keeper_test + +import ( + sdk "github.com/cosmos/cosmos-sdk/types" + authtypes "github.com/cosmos/cosmos-sdk/x/auth/types" + banktypes "github.com/cosmos/cosmos-sdk/x/bank/types" + govtypes "github.com/cosmos/cosmos-sdk/x/gov/types" +) + +var govAcc = authtypes.NewEmptyModuleAccount(govtypes.ModuleName, authtypes.Minter) + +func (suite *KeeperTestSuite) TestMsgUpdateParams() { + // default params + params := banktypes.DefaultParams() + + testCases := []struct { + name string + input *banktypes.MsgUpdateParams + expErr bool + expErrMsg string + }{ + { + name: "invalid authority", + input: &banktypes.MsgUpdateParams{ + Authority: "invalid", + Params: params, + }, + expErr: true, + expErrMsg: "invalid authority", + }, + { + name: "send enabled param", + input: &banktypes.MsgUpdateParams{ + Authority: suite.bankKeeper.GetAuthority(), + Params: banktypes.Params{ + SendEnabled: []*banktypes.SendEnabled{ + {Denom: "foo", Enabled: true}, + }, + }, + }, + expErr: true, + expErrMsg: "use of send_enabled in params is no longer supported", + }, + { + name: "all good", + input: &banktypes.MsgUpdateParams{ + Authority: suite.bankKeeper.GetAuthority(), + Params: params, + }, + expErr: false, + }, + } + + for _, tc := range testCases { + tc := tc + suite.Run(tc.name, func() { + _, err := suite.msgServer.UpdateParams(suite.ctx, tc.input) + + if tc.expErr { + suite.Require().Error(err) + suite.Require().Contains(err.Error(), tc.expErrMsg) + } else { + suite.Require().NoError(err) + } + }) + } +} + +func (suite *KeeperTestSuite) TestMsgSend() { + origCoins := sdk.NewCoins(sdk.NewInt64Coin("sendableCoin", 100)) + suite.bankKeeper.SetSendEnabled(suite.ctx, origCoins.Denoms()[0], true) + atom0 := sdk.NewCoins(sdk.NewInt64Coin("atom", 0)) + atom123eth0 := sdk.Coins{sdk.NewInt64Coin("atom", 123), sdk.NewInt64Coin("eth", 0)} + + testCases := []struct { + name string + input *banktypes.MsgSend + expErr bool + expErrMsg string + }{ + { + name: "invalid send to blocked address", + input: &banktypes.MsgSend{ + FromAddress: minterAcc.GetAddress().String(), + ToAddress: accAddrs[4].String(), + Amount: origCoins, + }, + expErr: true, + expErrMsg: "is not allowed to receive funds", + }, + { + name: "invalid coins", + input: &banktypes.MsgSend{ + FromAddress: minterAcc.GetAddress().String(), + ToAddress: baseAcc.Address, + Amount: atom0, + }, + expErr: true, + expErrMsg: "invalid coins", + }, + { + name: "123atom,0eth: invalid coins", + input: &banktypes.MsgSend{ + FromAddress: minterAcc.GetAddress().String(), + ToAddress: baseAcc.Address, + Amount: atom123eth0, + }, + expErr: true, + expErrMsg: "123atom,0eth: invalid coins", + }, + { + name: "invalid from address: empty address string is not allowed: invalid address", + input: &banktypes.MsgSend{ + FromAddress: "", + ToAddress: baseAcc.Address, + Amount: origCoins, + }, + expErr: true, + expErrMsg: "empty address string is not allowed", + }, + { + name: "invalid to address: empty address string is not allowed: invalid address", + input: &banktypes.MsgSend{ + FromAddress: minterAcc.GetAddress().String(), + ToAddress: "", + Amount: origCoins, + }, + expErr: true, + expErrMsg: "empty address string is not allowed", + }, + { + name: "all good", + input: &banktypes.MsgSend{ + FromAddress: minterAcc.GetAddress().String(), + ToAddress: baseAcc.Address, + Amount: origCoins, + }, + expErr: false, + }, + } + + for _, tc := range testCases { + tc := tc + suite.Run(tc.name, func() { + suite.mockMintCoins(minterAcc) + suite.bankKeeper.MintCoins(suite.ctx, minterAcc.Name, origCoins) + if !tc.expErr { + suite.mockSendCoins(suite.ctx, minterAcc, baseAcc.GetAddress()) + } + _, err := suite.msgServer.Send(suite.ctx, tc.input) + if tc.expErr { + suite.Require().Error(err) + suite.Require().Contains(err.Error(), tc.expErrMsg) + } else { + suite.Require().NoError(err) + } + }) + } +} + +func (suite *KeeperTestSuite) TestMsgMultiSend() { + origDenom := "sendableCoin" + origCoins := sdk.NewCoins(sdk.NewInt64Coin(origDenom, 100)) + sendCoins := sdk.NewCoins(sdk.NewInt64Coin(origDenom, 50)) + suite.bankKeeper.SetSendEnabled(suite.ctx, origDenom, true) + + testCases := []struct { + name string + input *banktypes.MsgMultiSend + expErr bool + expErrMsg string + }{ + { + name: "no inputs to send transaction", + input: &banktypes.MsgMultiSend{}, + expErr: true, + expErrMsg: "no inputs to send transaction", + }, + { + name: "no inputs to send transaction", + input: &banktypes.MsgMultiSend{ + Outputs: []banktypes.Output{ + {Address: accAddrs[4].String(), Coins: sendCoins}, + }, + }, + expErr: true, + expErrMsg: "no inputs to send transaction", + }, + { + name: "more than one inputs to send transaction", + input: &banktypes.MsgMultiSend{ + Inputs: []banktypes.Input{ + {Address: minterAcc.GetAddress().String(), Coins: origCoins}, + {Address: minterAcc.GetAddress().String(), Coins: origCoins}, + }, + }, + expErr: true, + expErrMsg: "multiple senders not allowed", + }, + { + name: "no outputs to send transaction", + input: &banktypes.MsgMultiSend{ + Inputs: []banktypes.Input{ + {Address: minterAcc.GetAddress().String(), Coins: origCoins}, + }, + }, + expErr: true, + expErrMsg: "no outputs to send transaction", + }, + { + name: "invalid send to blocked address", + input: &banktypes.MsgMultiSend{ + Inputs: []banktypes.Input{ + {Address: minterAcc.GetAddress().String(), Coins: origCoins}, + }, + Outputs: []banktypes.Output{ + {Address: accAddrs[0].String(), Coins: sendCoins}, + {Address: accAddrs[4].String(), Coins: sendCoins}, + }, + }, + expErr: true, + expErrMsg: "is not allowed to receive funds", + }, + { + name: "invalid send to blocked address", + input: &banktypes.MsgMultiSend{ + Inputs: []banktypes.Input{ + {Address: minterAcc.GetAddress().String(), Coins: origCoins}, + }, + Outputs: []banktypes.Output{ + {Address: accAddrs[0].String(), Coins: sendCoins}, + {Address: accAddrs[1].String(), Coins: sendCoins}, + }, + }, + expErr: false, + }, + } + + for _, tc := range testCases { + tc := tc + suite.Run(tc.name, func() { + suite.mockMintCoins(minterAcc) + suite.bankKeeper.MintCoins(suite.ctx, minterAcc.Name, origCoins) + if !tc.expErr { + suite.mockInputOutputCoins([]sdk.AccountI{minterAcc}, accAddrs[:2]) + } + _, err := suite.msgServer.MultiSend(suite.ctx, tc.input) + if tc.expErr { + suite.Require().Error(err) + suite.Require().Contains(err.Error(), tc.expErrMsg) + } else { + suite.Require().NoError(err) + } + }) + } +} + +func (suite *KeeperTestSuite) TestMsgSetSendEnabled() { + testCases := []struct { + name string + req *banktypes.MsgSetSendEnabled + isExpErr bool + errMsg string + }{ + { + name: "all good", + req: banktypes.NewMsgSetSendEnabled( + govAcc.GetAddress().String(), + []*banktypes.SendEnabled{ + banktypes.NewSendEnabled("atom1", true), + }, + []string{}, + ), + }, + { + name: "all good with two denoms", + req: banktypes.NewMsgSetSendEnabled( + govAcc.GetAddress().String(), + []*banktypes.SendEnabled{ + banktypes.NewSendEnabled("atom1", true), + banktypes.NewSendEnabled("atom2", true), + }, + []string{"defcoinc", "defcoind"}, + ), + }, + { + name: "duplicate denoms", + req: banktypes.NewMsgSetSendEnabled( + govAcc.GetAddress().String(), + []*banktypes.SendEnabled{ + banktypes.NewSendEnabled("atom", true), + banktypes.NewSendEnabled("atom", true), + }, + []string{}, + ), + isExpErr: true, + errMsg: `duplicate denom entries found for "atom": invalid request`, + }, + { + name: "bad first denom name, (invalid send enabled denom present in list)", + req: banktypes.NewMsgSetSendEnabled( + govAcc.GetAddress().String(), + []*banktypes.SendEnabled{ + banktypes.NewSendEnabled("not a denom", true), + banktypes.NewSendEnabled("somecoin", true), + }, + []string{}, + ), + isExpErr: true, + errMsg: `invalid SendEnabled denom "not a denom": invalid denom: not a denom: invalid request`, + }, + { + name: "bad second denom name, (invalid send enabled denom present in list)", + req: banktypes.NewMsgSetSendEnabled( + govAcc.GetAddress().String(), + []*banktypes.SendEnabled{ + banktypes.NewSendEnabled("somecoin", true), + banktypes.NewSendEnabled("not a denom", true), + }, + []string{}, + ), + isExpErr: true, + errMsg: `invalid SendEnabled denom "not a denom": invalid denom: not a denom: invalid request`, + }, + { + name: "invalid UseDefaultFor denom", + req: banktypes.NewMsgSetSendEnabled( + govAcc.GetAddress().String(), + []*banktypes.SendEnabled{ + banktypes.NewSendEnabled("atom", true), + }, + []string{"not a denom"}, + ), + isExpErr: true, + errMsg: `invalid UseDefaultFor denom "not a denom": invalid denom: not a denom: invalid request`, + }, + { + name: "invalid authority", + req: banktypes.NewMsgSetSendEnabled( + "invalid", + []*banktypes.SendEnabled{ + banktypes.NewSendEnabled("atom", true), + }, + []string{}, + ), + isExpErr: true, + }, + } + + for _, tc := range testCases { + suite.Run(tc.name, func() { + _, err := suite.msgServer.SetSendEnabled(suite.ctx, tc.req) + + if tc.isExpErr { + suite.Require().Error(err) + suite.Require().Contains(err.Error(), tc.errMsg) + } else { + suite.Require().NoError(err) + } + }) + } +} diff --git a/x/bank/keeper/msg_service_test.go b/x/bank/keeper/msg_service_test.go deleted file mode 100644 index a6454b6a8531..000000000000 --- a/x/bank/keeper/msg_service_test.go +++ /dev/null @@ -1,172 +0,0 @@ -package keeper_test - -import ( - sdk "github.com/cosmos/cosmos-sdk/types" - banktypes "github.com/cosmos/cosmos-sdk/x/bank/types" -) - -func (suite *KeeperTestSuite) TestMsgUpdateParams() { - // default params - params := banktypes.DefaultParams() - - testCases := []struct { - name string - input *banktypes.MsgUpdateParams - expErr bool - expErrMsg string - }{ - { - name: "invalid authority", - input: &banktypes.MsgUpdateParams{ - Authority: "invalid", - Params: params, - }, - expErr: true, - expErrMsg: "invalid authority", - }, - { - name: "send enabled param", - input: &banktypes.MsgUpdateParams{ - Authority: suite.bankKeeper.GetAuthority(), - Params: banktypes.Params{ - SendEnabled: []*banktypes.SendEnabled{ - {Denom: "foo", Enabled: true}, - }, - }, - }, - expErr: false, - }, - { - name: "all good", - input: &banktypes.MsgUpdateParams{ - Authority: suite.bankKeeper.GetAuthority(), - Params: params, - }, - expErr: false, - }, - } - - for _, tc := range testCases { - tc := tc - suite.Run(tc.name, func() { - _, err := suite.msgServer.UpdateParams(suite.ctx, tc.input) - - if tc.expErr { - suite.Require().Error(err) - suite.Require().Contains(err.Error(), tc.expErrMsg) - } else { - suite.Require().NoError(err) - } - }) - } -} - -func (suite *KeeperTestSuite) TestMsgSend() { - origCoins := sdk.NewCoins(sdk.NewInt64Coin("sendableCoin", 100)) - suite.bankKeeper.SetSendEnabled(suite.ctx, origCoins.Denoms()[0], true) - - testCases := []struct { - name string - input *banktypes.MsgSend - expErr bool - expErrMsg string - }{ - { - name: "invalid send to blocked address", - input: &banktypes.MsgSend{ - FromAddress: minterAcc.GetAddress().String(), - ToAddress: accAddrs[4].String(), - Amount: origCoins, - }, - expErr: true, - expErrMsg: "is not allowed to receive funds", - }, - { - name: "all good", - input: &banktypes.MsgSend{ - FromAddress: minterAcc.GetAddress().String(), - ToAddress: baseAcc.Address, - Amount: origCoins, - }, - expErr: false, - }, - } - - for _, tc := range testCases { - tc := tc - suite.Run(tc.name, func() { - suite.mockMintCoins(minterAcc) - suite.bankKeeper.MintCoins(suite.ctx, minterAcc.Name, origCoins) - if !tc.expErr { - suite.mockSendCoins(suite.ctx, minterAcc, baseAcc.GetAddress()) - } - _, err := suite.msgServer.Send(suite.ctx, tc.input) - if tc.expErr { - suite.Require().Error(err) - suite.Require().Contains(err.Error(), tc.expErrMsg) - } else { - suite.Require().NoError(err) - } - }) - } -} - -func (suite *KeeperTestSuite) TestMsgMultiSend() { - origDenom := "sendableCoin" - origCoins := sdk.NewCoins(sdk.NewInt64Coin(origDenom, 100)) - sendCoins := sdk.NewCoins(sdk.NewInt64Coin(origDenom, 50)) - suite.bankKeeper.SetSendEnabled(suite.ctx, origDenom, true) - - testCases := []struct { - name string - input *banktypes.MsgMultiSend - expErr bool - expErrMsg string - }{ - { - name: "invalid send to blocked address", - input: &banktypes.MsgMultiSend{ - Inputs: []banktypes.Input{ - {Address: minterAcc.GetAddress().String(), Coins: origCoins}, - }, - Outputs: []banktypes.Output{ - {Address: accAddrs[0].String(), Coins: sendCoins}, - {Address: accAddrs[4].String(), Coins: sendCoins}, - }, - }, - expErr: true, - expErrMsg: "is not allowed to receive funds", - }, - { - name: "invalid send to blocked address", - input: &banktypes.MsgMultiSend{ - Inputs: []banktypes.Input{ - {Address: minterAcc.GetAddress().String(), Coins: origCoins}, - }, - Outputs: []banktypes.Output{ - {Address: accAddrs[0].String(), Coins: sendCoins}, - {Address: accAddrs[1].String(), Coins: sendCoins}, - }, - }, - expErr: false, - }, - } - - for _, tc := range testCases { - tc := tc - suite.Run(tc.name, func() { - suite.mockMintCoins(minterAcc) - suite.bankKeeper.MintCoins(suite.ctx, minterAcc.Name, origCoins) - if !tc.expErr { - suite.mockInputOutputCoins([]sdk.AccountI{minterAcc}, accAddrs[:2]) - } - _, err := suite.msgServer.MultiSend(suite.ctx, tc.input) - if tc.expErr { - suite.Require().Error(err) - suite.Require().Contains(err.Error(), tc.expErrMsg) - } else { - suite.Require().NoError(err) - } - }) - } -} diff --git a/x/bank/keeper/send.go b/x/bank/keeper/send.go index 3903cf482f05..da48effc09ef 100644 --- a/x/bank/keeper/send.go +++ b/x/bank/keeper/send.go @@ -3,14 +3,14 @@ package keeper import ( "fmt" + "cosmossdk.io/collections" + errorsmod "cosmossdk.io/errors" - "cosmossdk.io/store/prefix" storetypes "cosmossdk.io/store/types" "github.com/cosmos/cosmos-sdk/codec" "github.com/cosmos/cosmos-sdk/telemetry" sdk "github.com/cosmos/cosmos-sdk/types" - "github.com/cosmos/cosmos-sdk/types/address" sdkerrors "github.com/cosmos/cosmos-sdk/types/errors" "github.com/cosmos/cosmos-sdk/x/bank/types" ) @@ -21,7 +21,7 @@ type SendKeeper interface { ViewKeeper InputOutputCoins(ctx sdk.Context, inputs types.Input, outputs []types.Output) error - SendCoins(ctx sdk.Context, fromAddr sdk.AccAddress, toAddr sdk.AccAddress, amt sdk.Coins) error + SendCoins(ctx sdk.Context, fromAddr, toAddr sdk.AccAddress, amt sdk.Coins) error GetParams(ctx sdk.Context) types.Params SetParams(ctx sdk.Context, params types.Params) error @@ -171,7 +171,7 @@ func (k BaseSendKeeper) InputOutputCoins(ctx sdk.Context, input types.Input, out // SendCoins transfers amt coins from a sending account to a receiving account. // An error is returned upon failure. -func (k BaseSendKeeper) SendCoins(ctx sdk.Context, fromAddr sdk.AccAddress, toAddr sdk.AccAddress, amt sdk.Coins) error { +func (k BaseSendKeeper) SendCoins(ctx sdk.Context, fromAddr, toAddr sdk.AccAddress, amt sdk.Coins) error { err := k.subUnlockedCoins(ctx, fromAddr, amt) if err != nil { return err @@ -277,74 +277,21 @@ func (k BaseSendKeeper) addCoins(ctx sdk.Context, addr sdk.AccAddress, amt sdk.C return nil } -// initBalances sets the balance (multiple coins) for an account by address. -// An error is returned upon failure. -func (k BaseSendKeeper) initBalances(ctx sdk.Context, addr sdk.AccAddress, balances sdk.Coins) error { - accountStore := k.getAccountStore(ctx, addr) - denomPrefixStores := make(map[string]prefix.Store) // memoize prefix stores - - for i := range balances { - balance := balances[i] - if !balance.IsValid() { - return errorsmod.Wrap(sdkerrors.ErrInvalidCoins, balance.String()) - } - - // x/bank invariants prohibit persistence of zero balances - if !balance.IsZero() { - amount, err := balance.Amount.Marshal() - if err != nil { - return err - } - accountStore.Set([]byte(balance.Denom), amount) - - denomPrefixStore, ok := denomPrefixStores[balance.Denom] - if !ok { - denomPrefixStore = k.getDenomAddressPrefixStore(ctx, balance.Denom) - denomPrefixStores[balance.Denom] = denomPrefixStore - } - - // Store a reverse index from denomination to account address with a - // sentinel value. - denomAddrKey := address.MustLengthPrefix(addr) - if !denomPrefixStore.Has(denomAddrKey) { - denomPrefixStore.Set(denomAddrKey, []byte{0}) - } - } - } - - return nil -} - // setBalance sets the coin balance for an account by address. func (k BaseSendKeeper) setBalance(ctx sdk.Context, addr sdk.AccAddress, balance sdk.Coin) error { if !balance.IsValid() { return errorsmod.Wrap(sdkerrors.ErrInvalidCoins, balance.String()) } - accountStore := k.getAccountStore(ctx, addr) - denomPrefixStore := k.getDenomAddressPrefixStore(ctx, balance.Denom) - // x/bank invariants prohibit persistence of zero balances if balance.IsZero() { - accountStore.Delete([]byte(balance.Denom)) - denomPrefixStore.Delete(address.MustLengthPrefix(addr)) - } else { - amount, err := balance.Amount.Marshal() + err := k.Balances.Remove(ctx, collections.Join(addr, balance.Denom)) if err != nil { return err } - - accountStore.Set([]byte(balance.Denom), amount) - - // Store a reverse index from denomination to account address with a - // sentinel value. - denomAddrKey := address.MustLengthPrefix(addr) - if !denomPrefixStore.Has(denomAddrKey) { - denomPrefixStore.Set(denomAddrKey, []byte{0}) - } + return nil } - - return nil + return k.Balances.Set(ctx, collections.Join(addr, balance.Denom), balance.Amount) } // IsSendEnabledCoins checks the coins provided and returns an ErrSendDisabled diff --git a/x/bank/keeper/view.go b/x/bank/keeper/view.go index 8164b4824e5d..308557889388 100644 --- a/x/bank/keeper/view.go +++ b/x/bank/keeper/view.go @@ -3,6 +3,10 @@ package keeper import ( "fmt" + "cosmossdk.io/collections/indexes" + + "github.com/cockroachdb/errors" + "cosmossdk.io/collections" "github.com/cosmos/cosmos-sdk/runtime" @@ -11,7 +15,6 @@ import ( "cosmossdk.io/math" errorsmod "cosmossdk.io/errors" - "cosmossdk.io/store/prefix" storetypes "cosmossdk.io/store/types" "github.com/cosmos/cosmos-sdk/codec" @@ -39,6 +42,23 @@ type ViewKeeper interface { IterateAllBalances(ctx sdk.Context, cb func(address sdk.AccAddress, coin sdk.Coin) (stop bool)) } +func newBalancesIndexes(sb *collections.SchemaBuilder) BalancesIndexes { + return BalancesIndexes{ + Denom: indexes.NewReversePair[math.Int]( + sb, types.DenomAddressPrefix, "address_by_denom_index", + collections.PairKeyCodec(sdk.AddressKeyAsIndexKey(sdk.AccAddressKey), collections.StringKey), // nolint:staticcheck // Note: refer to the AddressKeyAsIndexKey docs to understand why we do this. + ), + } +} + +type BalancesIndexes struct { + Denom *indexes.ReversePair[sdk.AccAddress, string, math.Int] +} + +func (b BalancesIndexes) IndexesList() []collections.Index[collections.Pair[sdk.AccAddress, string], math.Int] { + return []collections.Index[collections.Pair[sdk.AccAddress, string], math.Int]{b.Denom} +} + // BaseViewKeeper implements a read only keeper implementation of ViewKeeper. type BaseViewKeeper struct { cdc codec.BinaryCodec @@ -49,6 +69,7 @@ type BaseViewKeeper struct { Supply collections.Map[string, math.Int] DenomMetadata collections.Map[string, types.Metadata] SendEnabled collections.Map[string, bool] + Balances *collections.IndexedMap[collections.Pair[sdk.AccAddress, string], math.Int, BalancesIndexes] Params collections.Item[types.Params] } @@ -62,6 +83,7 @@ func NewBaseViewKeeper(cdc codec.BinaryCodec, storeKey storetypes.StoreKey, ak t Supply: collections.NewMap(sb, types.SupplyKey, "supply", collections.StringKey, sdk.IntValue), DenomMetadata: collections.NewMap(sb, types.DenomMetadataPrefix, "denom_metadata", collections.StringKey, codec.CollValue[types.Metadata](cdc)), SendEnabled: collections.NewMap(sb, types.SendEnabledPrefix, "send_enabled", collections.StringKey, codec.BoolValue), // NOTE: we use a bool value which uses protobuf to retain state backwards compat + Balances: collections.NewIndexedMap(sb, types.BalancesPrefix, "balances", collections.PairKeyCodec(sdk.AccAddressKey, collections.StringKey), types.NewBalanceCompatValueCodec(), newBalancesIndexes(sb)), Params: collections.NewItem(sb, types.ParamsKey, "params", codec.CollValue[types.Params](cdc)), } @@ -123,35 +145,22 @@ func (k BaseViewKeeper) GetAccountsBalances(ctx sdk.Context) []types.Balance { // GetBalance returns the balance of a specific denomination for a given account // by address. func (k BaseViewKeeper) GetBalance(ctx sdk.Context, addr sdk.AccAddress, denom string) sdk.Coin { - accountStore := k.getAccountStore(ctx, addr) - bz := accountStore.Get([]byte(denom)) - balance, err := UnmarshalBalanceCompat(k.cdc, bz, denom) + amt, err := k.Balances.Get(ctx, collections.Join(addr, denom)) if err != nil { - panic(err) + return sdk.NewCoin(denom, sdk.ZeroInt()) } - - return balance + return sdk.NewCoin(denom, amt) } // IterateAccountBalances iterates over the balances of a single account and // provides the token balance to a callback. If true is returned from the // callback, iteration is halted. func (k BaseViewKeeper) IterateAccountBalances(ctx sdk.Context, addr sdk.AccAddress, cb func(sdk.Coin) bool) { - accountStore := k.getAccountStore(ctx, addr) - - iterator := accountStore.Iterator(nil, nil) - defer sdk.LogDeferred(ctx.Logger(), func() error { return iterator.Close() }) - - for ; iterator.Valid(); iterator.Next() { - denom := string(iterator.Key()) - balance, err := UnmarshalBalanceCompat(k.cdc, iterator.Value(), denom) - if err != nil { - panic(err) - } - - if cb(balance) { - break - } + err := k.Balances.Walk(ctx, collections.NewPrefixedPairRange[sdk.AccAddress, string](addr), func(key collections.Pair[sdk.AccAddress, string], value math.Int) bool { + return cb(sdk.NewCoin(key.K2(), value)) + }) + if err != nil && !errors.Is(err, collections.ErrInvalidIterator) { // TODO(tip): is this the correct strategy + panic(err) } } @@ -159,29 +168,11 @@ func (k BaseViewKeeper) IterateAccountBalances(ctx sdk.Context, addr sdk.AccAddr // denominations that are provided to a callback. If true is returned from the // callback, iteration is halted. func (k BaseViewKeeper) IterateAllBalances(ctx sdk.Context, cb func(sdk.AccAddress, sdk.Coin) bool) { - store := ctx.KVStore(k.storeKey) - balancesStore := prefix.NewStore(store, types.BalancesPrefix) - - iterator := balancesStore.Iterator(nil, nil) - defer iterator.Close() - - for ; iterator.Valid(); iterator.Next() { - address, denom, err := types.AddressAndDenomFromBalancesStore(iterator.Key()) - if err != nil { - k.Logger(ctx).With("key", iterator.Key(), "err", err).Error("failed to get address from balances store") - // TODO: revisit, for now, panic here to keep same behavior as in 0.42 - // ref: https://github.com/cosmos/cosmos-sdk/issues/7409 - panic(err) - } - - balance, err := UnmarshalBalanceCompat(k.cdc, iterator.Value(), denom) - if err != nil { - panic(err) - } - - if cb(address, balance) { - break - } + err := k.Balances.Walk(ctx, nil, func(key collections.Pair[sdk.AccAddress, string], value math.Int) bool { + return cb(key.K1(), sdk.NewCoin(key.K2(), value)) + }) + if err != nil { + panic(err) } } @@ -261,39 +252,3 @@ func (k BaseViewKeeper) ValidateBalance(ctx sdk.Context, addr sdk.AccAddress) er return nil } - -// getAccountStore gets the account store of the given address. -func (k BaseViewKeeper) getAccountStore(ctx sdk.Context, addr sdk.AccAddress) prefix.Store { - store := ctx.KVStore(k.storeKey) - return prefix.NewStore(store, types.CreateAccountBalancesPrefix(addr)) -} - -// getDenomAddressPrefixStore returns a prefix store that acts as a reverse index -// between a denomination and account balance for that denomination. -func (k BaseViewKeeper) getDenomAddressPrefixStore(ctx sdk.Context, denom string) prefix.Store { - return prefix.NewStore(ctx.KVStore(k.storeKey), types.CreateDenomAddressPrefix(denom)) -} - -// UnmarshalBalanceCompat unmarshal balance amount from storage, it's backward-compatible with the legacy format. -func UnmarshalBalanceCompat(cdc codec.BinaryCodec, bz []byte, denom string) (sdk.Coin, error) { - if err := sdk.ValidateDenom(denom); err != nil { - return sdk.Coin{}, err - } - - amount := math.ZeroInt() - if bz == nil { - return sdk.NewCoin(denom, amount), nil - } - - if err := amount.Unmarshal(bz); err != nil { - // try to unmarshal with the legacy format. - var balance sdk.Coin - if cdc.Unmarshal(bz, &balance) != nil { - // return with the original error - return sdk.Coin{}, err - } - return balance, nil - } - - return sdk.NewCoin(denom, amount), nil -} diff --git a/x/bank/migrations/v2/json_test.go b/x/bank/migrations/v2/json_test.go index ddf908e01982..bdf20dacded0 100644 --- a/x/bank/migrations/v2/json_test.go +++ b/x/bank/migrations/v2/json_test.go @@ -4,6 +4,7 @@ import ( "encoding/json" "testing" + sdkmath "cosmossdk.io/math" "github.com/stretchr/testify/require" "github.com/cosmos/cosmos-sdk/client" @@ -27,17 +28,17 @@ func TestMigrateJSON(t *testing.T) { { Address: voter.String(), Coins: sdk.Coins{ - sdk.NewCoin("foo", sdk.NewInt(10)), - sdk.NewCoin("bar", sdk.NewInt(20)), - sdk.NewCoin("foobar", sdk.NewInt(0)), + sdk.NewCoin("foo", sdkmath.NewInt(10)), + sdk.NewCoin("bar", sdkmath.NewInt(20)), + sdk.NewCoin("foobar", sdkmath.NewInt(0)), }, }, }, Supply: sdk.Coins{ - sdk.NewCoin("foo", sdk.NewInt(10)), - sdk.NewCoin("bar", sdk.NewInt(20)), - sdk.NewCoin("foobar", sdk.NewInt(0)), - sdk.NewCoin("barfoo", sdk.NewInt(0)), + sdk.NewCoin("foo", sdkmath.NewInt(10)), + sdk.NewCoin("bar", sdkmath.NewInt(20)), + sdk.NewCoin("foobar", sdkmath.NewInt(0)), + sdk.NewCoin("barfoo", sdkmath.NewInt(0)), }, } diff --git a/x/bank/migrations/v2/store.go b/x/bank/migrations/v2/store.go index e044e6a47308..2c4186286453 100644 --- a/x/bank/migrations/v2/store.go +++ b/x/bank/migrations/v2/store.go @@ -65,7 +65,7 @@ func migrateBalanceKeys(store storetypes.KVStore, logger log.Logger) { for ; oldStoreIter.Valid(); oldStoreIter.Next() { addr := v1.AddressFromBalancesStore(oldStoreIter.Key()) denom := oldStoreIter.Key()[v1auth.AddrLen:] - newStoreKey := types.CreatePrefixedAccountStoreKey(addr, denom) + newStoreKey := CreatePrefixedAccountStoreKey(addr, denom) // Set new key on store. Values don't change. store.Set(newStoreKey, oldStoreIter.Value()) @@ -133,3 +133,9 @@ func pruneZeroSupply(store storetypes.KVStore) error { return nil } + +// CreatePrefixedAccountStoreKey returns the key for the given account and denomination. +// This method can be used when performing an ABCI query for the balance of an account. +func CreatePrefixedAccountStoreKey(addr, denom []byte) []byte { + return append(CreateAccountBalancesPrefix(addr), denom...) +} diff --git a/x/bank/migrations/v2/store_test.go b/x/bank/migrations/v2/store_test.go index ad005c5ccff6..5d98b22db48a 100644 --- a/x/bank/migrations/v2/store_test.go +++ b/x/bank/migrations/v2/store_test.go @@ -26,9 +26,9 @@ func TestSupplyMigration(t *testing.T) { v1bank.RegisterInterfaces(encCfg.InterfaceRegistry) - oldFooCoin := sdk.NewCoin("foo", sdk.NewInt(100)) - oldBarCoin := sdk.NewCoin("bar", sdk.NewInt(200)) - oldFooBarCoin := sdk.NewCoin("foobar", sdk.NewInt(0)) // to ensure the zero denom coins pruned. + oldFooCoin := sdk.NewCoin("foo", math.NewInt(100)) + oldBarCoin := sdk.NewCoin("bar", math.NewInt(200)) + oldFooBarCoin := sdk.NewCoin("foobar", math.NewInt(0)) // to ensure the zero denom coins pruned. // Old supply was stored as a single blob under the `SupplyKey`. oldSupply := &types.Supply{Total: sdk.Coins{oldFooCoin, oldBarCoin, oldFooBarCoin}} @@ -77,14 +77,14 @@ func TestBalanceKeysMigration(t *testing.T) { _, _, addr := testdata.KeyTestPubAddr() // set 10 foo coin - fooCoin := sdk.NewCoin("foo", sdk.NewInt(10)) + fooCoin := sdk.NewCoin("foo", math.NewInt(10)) oldFooKey := append(append(v1bank.BalancesPrefix, addr...), []byte(fooCoin.Denom)...) fooBz, err := encCfg.Codec.Marshal(&fooCoin) require.NoError(t, err) store.Set(oldFooKey, fooBz) // set 0 foobar coin - fooBarCoin := sdk.NewCoin("foobar", sdk.NewInt(0)) + fooBarCoin := sdk.NewCoin("foobar", math.NewInt(0)) oldKeyFooBar := append(append(v1bank.BalancesPrefix, addr...), []byte(fooBarCoin.Denom)...) fooBarBz, err := encCfg.Codec.Marshal(&fooBarCoin) require.NoError(t, err) @@ -94,13 +94,13 @@ func TestBalanceKeysMigration(t *testing.T) { err = v2bank.MigrateStore(ctx, bankKey, encCfg.Codec) require.NoError(t, err) - newKey := types.CreatePrefixedAccountStoreKey(addr, []byte(fooCoin.Denom)) + newKey := v2bank.CreatePrefixedAccountStoreKey(addr, []byte(fooCoin.Denom)) // -7 because we replaced "balances" with 0x02, // +1 because we added length-prefix to address. require.Equal(t, len(oldFooKey)-7+1, len(newKey)) require.Nil(t, store.Get(oldFooKey)) require.Equal(t, fooBz, store.Get(newKey)) - newKeyFooBar := types.CreatePrefixedAccountStoreKey(addr, []byte(fooBarCoin.Denom)) + newKeyFooBar := v2bank.CreatePrefixedAccountStoreKey(addr, []byte(fooBarCoin.Denom)) require.Nil(t, store.Get(newKeyFooBar)) // after migration zero balances pruned from store. } diff --git a/x/bank/migrations/v3/store.go b/x/bank/migrations/v3/store.go index d9c41f34617e..45e3d0994415 100644 --- a/x/bank/migrations/v3/store.go +++ b/x/bank/migrations/v3/store.go @@ -57,7 +57,7 @@ func addDenomReverseIndex(store storetypes.KVStore, cdc codec.BinaryCodec, logge return err } - newStore := prefix.NewStore(store, types.CreateAccountBalancesPrefix(addr)) + newStore := prefix.NewStore(store, CreateAccountBalancesPrefix(addr)) newStore.Set([]byte(coin.Denom), bz) denomPrefixStore, ok := denomPrefixStores[balance.Denom] @@ -94,3 +94,8 @@ func migrateDenomMetadata(store storetypes.KVStore, logger log.Logger) error { return nil } + +// CreateAccountBalancesPrefix creates the prefix for an account's balances. +func CreateAccountBalancesPrefix(addr []byte) []byte { + return append(types.BalancesPrefix.Bytes(), address.MustLengthPrefix(addr)...) +} diff --git a/x/bank/migrations/v3/store_test.go b/x/bank/migrations/v3/store_test.go index 83ba288abf80..c0e853a2aa3b 100644 --- a/x/bank/migrations/v3/store_test.go +++ b/x/bank/migrations/v3/store_test.go @@ -28,8 +28,8 @@ func TestMigrateStore(t *testing.T) { prefixAccStore := prefix.NewStore(store, v2.CreateAccountBalancesPrefix(addr)) balances := sdk.NewCoins( - sdk.NewCoin("foo", sdk.NewInt(10000)), - sdk.NewCoin("bar", sdk.NewInt(20000)), + sdk.NewCoin("foo", math.NewInt(10000)), + sdk.NewCoin("bar", math.NewInt(20000)), ) for _, b := range balances { @@ -42,7 +42,7 @@ func TestMigrateStore(t *testing.T) { require.NoError(t, v3.MigrateStore(ctx, bankKey, encCfg.Codec)) for _, b := range balances { - addrPrefixStore := prefix.NewStore(store, types.CreateAccountBalancesPrefix(addr)) + addrPrefixStore := prefix.NewStore(store, v3.CreateAccountBalancesPrefix(addr)) bz := addrPrefixStore.Get([]byte(b.Denom)) var expected math.Int require.NoError(t, expected.Unmarshal(bz)) @@ -108,7 +108,7 @@ func TestMigrateDenomMetaData(t *testing.T) { newKey := denomMetadataIter.Key() // make sure old entry is deleted - oldKey := append(newKey, newKey[0:]...) //nolint:gocritic // append is ok here + oldKey := append(newKey, newKey[0:]...) bz := denomMetadataStore.Get(oldKey) require.Nil(t, bz) diff --git a/x/bank/migrations/v4/gen_state_test.go b/x/bank/migrations/v4/gen_state_test.go index 19b15e5a137b..324216e260a5 100644 --- a/x/bank/migrations/v4/gen_state_test.go +++ b/x/bank/migrations/v4/gen_state_test.go @@ -3,6 +3,7 @@ package v4_test import ( "testing" + sdkmath "cosmossdk.io/math" "github.com/stretchr/testify/assert" sdk "github.com/cosmos/cosmos-sdk/types" @@ -22,9 +23,9 @@ func TestMigrateGenState(t *testing.T) { Params: types.Params{}, Balances: []types.Balance{{ Address: "balance1", - Coins: sdk.Coins{sdk.NewCoin("balance1coin", sdk.NewInt(8))}, + Coins: sdk.Coins{sdk.NewCoin("balance1coin", sdkmath.NewInt(8))}, }}, - Supply: sdk.Coins{sdk.NewCoin("supplycoin", sdk.NewInt(800))}, + Supply: sdk.Coins{sdk.NewCoin("supplycoin", sdkmath.NewInt(800))}, DenomMetadata: []types.Metadata{{ Description: "metadesk", DenomUnits: nil, @@ -41,9 +42,9 @@ func TestMigrateGenState(t *testing.T) { Params: types.Params{}, Balances: []types.Balance{{ Address: "balance1", - Coins: sdk.Coins{sdk.NewCoin("balance1coin", sdk.NewInt(8))}, + Coins: sdk.Coins{sdk.NewCoin("balance1coin", sdkmath.NewInt(8))}, }}, - Supply: sdk.Coins{sdk.NewCoin("supplycoin", sdk.NewInt(800))}, + Supply: sdk.Coins{sdk.NewCoin("supplycoin", sdkmath.NewInt(800))}, DenomMetadata: []types.Metadata{{ Description: "metadesk", DenomUnits: nil, diff --git a/x/bank/module.go b/x/bank/module.go index 63d6319ff479..e892e95cd819 100644 --- a/x/bank/module.go +++ b/x/bank/module.go @@ -194,7 +194,7 @@ func (am AppModule) RegisterStoreDecoder(_ simtypes.StoreDecoderRegistry) {} // WeightedOperations returns the all the gov module operations with their respective weights. func (am AppModule) WeightedOperations(simState module.SimulationState) []simtypes.WeightedOperation { return simulation.WeightedOperations( - simState.AppParams, simState.Cdc, am.accountKeeper, am.keeper, + simState.AppParams, simState.Cdc, simState.TxConfig, am.accountKeeper, am.keeper, ) } @@ -206,8 +206,7 @@ func init() { ) } -//nolint:revive -type BankInputs struct { +type ModuleInputs struct { depinject.In Config *modulev1.Module @@ -220,15 +219,14 @@ type BankInputs struct { LegacySubspace exported.Subspace `optional:"true"` } -//nolint:revive -type BankOutputs struct { +type ModuleOutputs struct { depinject.Out BankKeeper keeper.BaseKeeper Module appmodule.AppModule } -func ProvideModule(in BankInputs) BankOutputs { +func ProvideModule(in ModuleInputs) ModuleOutputs { // Configure blocked module accounts. // // Default behavior for blockedAddresses is to regard any module mentioned in @@ -259,5 +257,5 @@ func ProvideModule(in BankInputs) BankOutputs { ) m := NewAppModule(in.Cdc, bankKeeper, in.AccountKeeper, in.LegacySubspace) - return BankOutputs{BankKeeper: bankKeeper, Module: m} + return ModuleOutputs{BankKeeper: bankKeeper, Module: m} } diff --git a/x/bank/simulation/genesis.go b/x/bank/simulation/genesis.go index 11e65457a82e..4f4745db1f0b 100644 --- a/x/bank/simulation/genesis.go +++ b/x/bank/simulation/genesis.go @@ -5,6 +5,8 @@ import ( "fmt" "math/rand" + sdkmath "cosmossdk.io/math" + sdk "github.com/cosmos/cosmos-sdk/types" "github.com/cosmos/cosmos-sdk/types/module" "github.com/cosmos/cosmos-sdk/x/bank/types" @@ -78,7 +80,7 @@ func RandomizedGenState(simState *module.SimulationState) { sendEnabled := RandomGenesisSendEnabled(simState.Rand, simState.BondDenom) numAccs := int64(len(simState.Accounts)) - totalSupply := simState.InitialStake.Mul(sdk.NewInt((numAccs + simState.NumBonded))) + totalSupply := simState.InitialStake.Mul(sdkmath.NewInt((numAccs + simState.NumBonded))) supply := sdk.NewCoins(sdk.NewCoin(simState.BondDenom, totalSupply)) bankGenesis := types.GenesisState{ diff --git a/x/bank/simulation/genesis_test.go b/x/bank/simulation/genesis_test.go index 76be7256f84d..ef036617dbaf 100644 --- a/x/bank/simulation/genesis_test.go +++ b/x/bank/simulation/genesis_test.go @@ -43,7 +43,7 @@ func TestRandomizedGenState(t *testing.T) { simState.Cdc.MustUnmarshalJSON(simState.GenState[types.ModuleName], &bankGenesis) assert.Equal(t, true, bankGenesis.Params.GetDefaultSendEnabled(), "Params.GetDefaultSendEnabled") - assert.Len(t, bankGenesis.Params.GetSendEnabled(), 0, "Params.GetSendEnabled") //nolint:staticcheck + assert.Len(t, bankGenesis.Params.GetSendEnabled(), 0, "Params.GetSendEnabled") //nolint:staticcheck // we're testing deprecated code here if assert.Len(t, bankGenesis.Balances, 3) { assert.Equal(t, "cosmos1ghekyjucln7y67ntx7cf27m9dpuxxemn4c8g4r", bankGenesis.Balances[2].GetAddress().String(), "Balances[2] address") assert.Equal(t, "1000stake", bankGenesis.Balances[2].GetCoins().String(), "Balances[2] coins") diff --git a/x/bank/simulation/operations.go b/x/bank/simulation/operations.go index 3f7a1b024d91..f2c00d9170dd 100644 --- a/x/bank/simulation/operations.go +++ b/x/bank/simulation/operations.go @@ -4,11 +4,11 @@ import ( "math/rand" "github.com/cosmos/cosmos-sdk/baseapp" + "github.com/cosmos/cosmos-sdk/client" "github.com/cosmos/cosmos-sdk/codec" cryptotypes "github.com/cosmos/cosmos-sdk/crypto/types" simtestutil "github.com/cosmos/cosmos-sdk/testutil/sims" sdk "github.com/cosmos/cosmos-sdk/types" - moduletestutil "github.com/cosmos/cosmos-sdk/types/module/testutil" simtypes "github.com/cosmos/cosmos-sdk/types/simulation" "github.com/cosmos/cosmos-sdk/x/bank/keeper" "github.com/cosmos/cosmos-sdk/x/bank/types" @@ -18,15 +18,19 @@ import ( // Simulation operation weights constants const ( - OpWeightMsgSend = "op_weight_msg_send" //nolint:gosec - OpWeightMsgMultiSend = "op_weight_msg_multisend" //nolint:gosec - DefaultWeightMsgSend = 100 // from simappparams.DefaultWeightMsgSend - DefaultWeightMsgMultiSend = 10 // from simappparams.DefaultWeightMsgMultiSend + OpWeightMsgSend = "op_weight_msg_send" + OpWeightMsgMultiSend = "op_weight_msg_multisend" + DefaultWeightMsgSend = 100 // from simappparams.DefaultWeightMsgSend + DefaultWeightMsgMultiSend = 10 // from simappparams.DefaultWeightMsgMultiSend ) // WeightedOperations returns all the operations from the module with their respective weights func WeightedOperations( - appParams simtypes.AppParams, cdc codec.JSONCodec, ak types.AccountKeeper, bk keeper.Keeper, + appParams simtypes.AppParams, + cdc codec.JSONCodec, + txGen client.TxConfig, + ak types.AccountKeeper, + bk keeper.Keeper, ) simulation.WeightedOperations { var weightMsgSend, weightMsgMultiSend int appParams.GetOrGenerate(cdc, OpWeightMsgSend, &weightMsgSend, nil, @@ -44,18 +48,22 @@ func WeightedOperations( return simulation.WeightedOperations{ simulation.NewWeightedOperation( weightMsgSend, - SimulateMsgSend(ak, bk), + SimulateMsgSend(txGen, ak, bk), ), simulation.NewWeightedOperation( weightMsgMultiSend, - SimulateMsgMultiSend(ak, bk), + SimulateMsgMultiSend(txGen, ak, bk), ), } } // SimulateMsgSend tests and runs a single msg send where both // accounts already exist. -func SimulateMsgSend(ak types.AccountKeeper, bk keeper.Keeper) simtypes.Operation { +func SimulateMsgSend( + txGen client.TxConfig, + ak types.AccountKeeper, + bk keeper.Keeper, +) simtypes.Operation { return func( r *rand.Rand, app *baseapp.BaseApp, ctx sdk.Context, accs []simtypes.Account, chainID string, @@ -79,7 +87,7 @@ func SimulateMsgSend(ak types.AccountKeeper, bk keeper.Keeper) simtypes.Operatio msg := types.NewMsgSend(from.Address, to.Address, coins) - err := sendMsgSend(r, app, bk, ak, msg, ctx, chainID, []cryptotypes.PrivKey{from.PrivKey}) + err := sendMsgSend(r, app, txGen, bk, ak, msg, ctx, chainID, []cryptotypes.PrivKey{from.PrivKey}) if err != nil { return simtypes.NoOpMsg(types.ModuleName, sdk.MsgTypeURL(msg), "invalid transfers"), nil, err } @@ -90,7 +98,12 @@ func SimulateMsgSend(ak types.AccountKeeper, bk keeper.Keeper) simtypes.Operatio // SimulateMsgSendToModuleAccount tests and runs a single msg send where both // accounts already exist. -func SimulateMsgSendToModuleAccount(ak types.AccountKeeper, bk keeper.Keeper, moduleAccCount int) simtypes.Operation { +func SimulateMsgSendToModuleAccount( + txGen client.TxConfig, + ak types.AccountKeeper, + bk keeper.Keeper, + moduleAccCount int, +) simtypes.Operation { return func( r *rand.Rand, app *baseapp.BaseApp, ctx sdk.Context, accs []simtypes.Account, chainID string, @@ -113,7 +126,7 @@ func SimulateMsgSendToModuleAccount(ak types.AccountKeeper, bk keeper.Keeper, mo msg := types.NewMsgSend(from.Address, to.Address, coins) - err := sendMsgSend(r, app, bk, ak, msg, ctx, chainID, []cryptotypes.PrivKey{from.PrivKey}) + err := sendMsgSend(r, app, txGen, bk, ak, msg, ctx, chainID, []cryptotypes.PrivKey{from.PrivKey}) if err != nil { return simtypes.NoOpMsg(types.ModuleName, sdk.MsgTypeURL(msg), "invalid transfers"), nil, err } @@ -124,7 +137,9 @@ func SimulateMsgSendToModuleAccount(ak types.AccountKeeper, bk keeper.Keeper, mo // sendMsgSend sends a transaction with a MsgSend from a provided random account. func sendMsgSend( - r *rand.Rand, app *baseapp.BaseApp, bk keeper.Keeper, ak types.AccountKeeper, + r *rand.Rand, app *baseapp.BaseApp, + txGen client.TxConfig, + bk keeper.Keeper, ak types.AccountKeeper, msg *types.MsgSend, ctx sdk.Context, chainID string, privkeys []cryptotypes.PrivKey, ) error { var ( @@ -147,7 +162,6 @@ func sendMsgSend( return err } } - txGen := moduletestutil.MakeTestEncodingConfig().TxConfig tx, err := simtestutil.GenSignedMockTx( r, txGen, @@ -173,7 +187,7 @@ func sendMsgSend( // SimulateMsgMultiSend tests and runs a single msg multisend, with randomized, capped number of inputs/outputs. // all accounts in msg fields exist in state -func SimulateMsgMultiSend(ak types.AccountKeeper, bk keeper.Keeper) simtypes.Operation { +func SimulateMsgMultiSend(txGen client.TxConfig, ak types.AccountKeeper, bk keeper.Keeper) simtypes.Operation { return func( r *rand.Rand, app *baseapp.BaseApp, ctx sdk.Context, accs []simtypes.Account, chainID string, @@ -253,7 +267,7 @@ func SimulateMsgMultiSend(ak types.AccountKeeper, bk keeper.Keeper) simtypes.Ope Inputs: inputs, Outputs: outputs, } - err := sendMsgMultiSend(r, app, bk, ak, msg, ctx, chainID, privs) + err := sendMsgMultiSend(r, app, txGen, bk, ak, msg, ctx, chainID, privs) if err != nil { return simtypes.NoOpMsg(types.ModuleName, sdk.MsgTypeURL(msg), "invalid transfers"), nil, err } @@ -263,7 +277,12 @@ func SimulateMsgMultiSend(ak types.AccountKeeper, bk keeper.Keeper) simtypes.Ope } // SimulateMsgMultiSendToModuleAccount sends coins to Module Accounts -func SimulateMsgMultiSendToModuleAccount(ak types.AccountKeeper, bk keeper.Keeper, moduleAccCount int) simtypes.Operation { +func SimulateMsgMultiSendToModuleAccount( + txGen client.TxConfig, + ak types.AccountKeeper, + bk keeper.Keeper, + moduleAccCount int, +) simtypes.Operation { return func( r *rand.Rand, app *baseapp.BaseApp, ctx sdk.Context, accs []simtypes.Account, chainID string, @@ -313,7 +332,7 @@ func SimulateMsgMultiSendToModuleAccount(ak types.AccountKeeper, bk keeper.Keepe Inputs: inputs, Outputs: outputs, } - err := sendMsgMultiSend(r, app, bk, ak, msg, ctx, chainID, privs) + err := sendMsgMultiSend(r, app, txGen, bk, ak, msg, ctx, chainID, privs) if err != nil { return simtypes.NoOpMsg(types.ModuleName, sdk.MsgTypeURL(msg), "invalid transfers"), nil, err } @@ -324,7 +343,9 @@ func SimulateMsgMultiSendToModuleAccount(ak types.AccountKeeper, bk keeper.Keepe // sendMsgMultiSend sends a transaction with a MsgMultiSend from a provided random // account. func sendMsgMultiSend( - r *rand.Rand, app *baseapp.BaseApp, bk keeper.Keeper, ak types.AccountKeeper, + r *rand.Rand, app *baseapp.BaseApp, + txGen client.TxConfig, + bk keeper.Keeper, ak types.AccountKeeper, msg *types.MsgMultiSend, ctx sdk.Context, chainID string, privkeys []cryptotypes.PrivKey, ) error { accountNumbers := make([]uint64, len(msg.Inputs)) @@ -350,7 +371,6 @@ func sendMsgMultiSend( return err } } - txGen := moduletestutil.MakeTestEncodingConfig().TxConfig tx, err := simtestutil.GenSignedMockTx( r, txGen, diff --git a/x/bank/simulation/operations_test.go b/x/bank/simulation/operations_test.go index ee50ddf0cd59..8f95b4199c69 100644 --- a/x/bank/simulation/operations_test.go +++ b/x/bank/simulation/operations_test.go @@ -8,6 +8,7 @@ import ( cmtproto "github.com/cometbft/cometbft/proto/tendermint/types" "github.com/stretchr/testify/suite" + "github.com/cosmos/cosmos-sdk/client" "github.com/cosmos/cosmos-sdk/codec" "github.com/cosmos/cosmos-sdk/runtime" "github.com/cosmos/cosmos-sdk/testutil/configurator" @@ -33,6 +34,7 @@ type SimTestSuite struct { accountKeeper types.AccountKeeper bankKeeper keeper.Keeper cdc codec.Codec + txConfig client.TxConfig app *runtime.App } @@ -48,7 +50,7 @@ func (suite *SimTestSuite) SetupTest() { configurator.StakingModule(), configurator.ConsensusModule(), configurator.TxModule(), - ), &suite.accountKeeper, &suite.bankKeeper, &suite.cdc, &appBuilder) + ), &suite.accountKeeper, &suite.bankKeeper, &suite.cdc, &suite.txConfig, &appBuilder) suite.NoError(err) @@ -60,7 +62,7 @@ func (suite *SimTestSuite) TestWeightedOperations() { cdc := suite.cdc appParams := make(simtypes.AppParams) - weightesOps := simulation.WeightedOperations(appParams, cdc, suite.accountKeeper, suite.bankKeeper) + weightesOps := simulation.WeightedOperations(appParams, cdc, suite.txConfig, suite.accountKeeper, suite.bankKeeper) // setup 3 accounts s := rand.NewSource(1) @@ -101,7 +103,7 @@ func (suite *SimTestSuite) TestSimulateMsgSend() { suite.app.BeginBlock(abci.RequestBeginBlock{Header: cmtproto.Header{Height: suite.app.LastBlockHeight() + 1, AppHash: suite.app.LastCommitID().Hash}}) // execute operation - op := simulation.SimulateMsgSend(suite.accountKeeper, suite.bankKeeper) + op := simulation.SimulateMsgSend(suite.txConfig, suite.accountKeeper, suite.bankKeeper) operationMsg, futureOperations, err := op(r, suite.app.BaseApp, suite.ctx, accounts, "") suite.Require().NoError(err) @@ -128,7 +130,7 @@ func (suite *SimTestSuite) TestSimulateMsgMultiSend() { suite.app.BeginBlock(abci.RequestBeginBlock{Header: cmtproto.Header{Height: suite.app.LastBlockHeight() + 1, AppHash: suite.app.LastCommitID().Hash}}) // execute operation - op := simulation.SimulateMsgMultiSend(suite.accountKeeper, suite.bankKeeper) + op := simulation.SimulateMsgMultiSend(suite.txConfig, suite.accountKeeper, suite.bankKeeper) operationMsg, futureOperations, err := op(r, suite.app.BaseApp, suite.ctx, accounts, "") require := suite.Require() require.NoError(err) @@ -161,7 +163,7 @@ func (suite *SimTestSuite) TestSimulateModuleAccountMsgSend() { suite.app.BeginBlock(abci.RequestBeginBlock{Header: cmtproto.Header{Height: suite.app.LastBlockHeight() + 1, AppHash: suite.app.LastCommitID().Hash}}) // execute operation - op := simulation.SimulateMsgSendToModuleAccount(suite.accountKeeper, suite.bankKeeper, moduleAccCount) + op := simulation.SimulateMsgSendToModuleAccount(suite.txConfig, suite.accountKeeper, suite.bankKeeper, moduleAccCount) s = rand.NewSource(1) r = rand.New(s) @@ -192,7 +194,7 @@ func (suite *SimTestSuite) TestSimulateMsgMultiSendToModuleAccount() { suite.app.BeginBlock(abci.RequestBeginBlock{Header: cmtproto.Header{Height: suite.app.LastBlockHeight() + 1, AppHash: suite.app.LastCommitID().Hash}}) // execute operation - op := simulation.SimulateMsgMultiSendToModuleAccount(suite.accountKeeper, suite.bankKeeper, mAccCount) + op := simulation.SimulateMsgMultiSendToModuleAccount(suite.txConfig, suite.accountKeeper, suite.bankKeeper, mAccCount) operationMsg, futureOperations, err := op(r, suite.app.BaseApp, suite.ctx, accounts, "") suite.Require().Error(err) diff --git a/x/bank/simulation/proposals.go b/x/bank/simulation/proposals.go index 5a63b8632cea..3843b5f2566a 100644 --- a/x/bank/simulation/proposals.go +++ b/x/bank/simulation/proposals.go @@ -14,7 +14,7 @@ import ( const ( DefaultWeightMsgUpdateParams int = 100 - OpWeightMsgUpdateParams = "op_weight_msg_update_params" //nolint:gosec + OpWeightMsgUpdateParams = "op_weight_msg_update_params" ) // ProposalMsgs defines the module weighted proposals' contents diff --git a/x/bank/simulation/proposals_test.go b/x/bank/simulation/proposals_test.go index cc9ca7e55c08..5365a4fbf6b3 100644 --- a/x/bank/simulation/proposals_test.go +++ b/x/bank/simulation/proposals_test.go @@ -39,6 +39,6 @@ func TestProposalMsgs(t *testing.T) { fmt.Println(msgUpdateParams) assert.Equal(t, sdk.AccAddress(address.Module("gov")).String(), msgUpdateParams.Authority) - assert.Assert(t, len(msgUpdateParams.Params.SendEnabled) == 0) //nolint:staticcheck + assert.Assert(t, len(msgUpdateParams.Params.SendEnabled) == 0) //nolint:staticcheck // we're testing deprecated code here assert.Equal(t, true, msgUpdateParams.Params.DefaultSendEnabled) } diff --git a/x/bank/testutil/expected_keepers_mocks.go b/x/bank/testutil/expected_keepers_mocks.go index f39abb0b4b57..3b5668228444 100644 --- a/x/bank/testutil/expected_keepers_mocks.go +++ b/x/bank/testutil/expected_keepers_mocks.go @@ -5,6 +5,7 @@ package testutil import ( + context "context" reflect "reflect" types "github.com/cosmos/cosmos-sdk/types" @@ -36,7 +37,7 @@ func (m *MockAccountKeeper) EXPECT() *MockAccountKeeperMockRecorder { } // GetAccount mocks base method. -func (m *MockAccountKeeper) GetAccount(ctx types.Context, addr types.AccAddress) types.AccountI { +func (m *MockAccountKeeper) GetAccount(ctx context.Context, addr types.AccAddress) types.AccountI { m.ctrl.T.Helper() ret := m.ctrl.Call(m, "GetAccount", ctx, addr) ret0, _ := ret[0].(types.AccountI) @@ -50,7 +51,7 @@ func (mr *MockAccountKeeperMockRecorder) GetAccount(ctx, addr interface{}) *gomo } // GetAllAccounts mocks base method. -func (m *MockAccountKeeper) GetAllAccounts(ctx types.Context) []types.AccountI { +func (m *MockAccountKeeper) GetAllAccounts(ctx context.Context) []types.AccountI { m.ctrl.T.Helper() ret := m.ctrl.Call(m, "GetAllAccounts", ctx) ret0, _ := ret[0].([]types.AccountI) @@ -64,7 +65,7 @@ func (mr *MockAccountKeeperMockRecorder) GetAllAccounts(ctx interface{}) *gomock } // GetModuleAccount mocks base method. -func (m *MockAccountKeeper) GetModuleAccount(ctx types.Context, moduleName string) types.ModuleAccountI { +func (m *MockAccountKeeper) GetModuleAccount(ctx context.Context, moduleName string) types.ModuleAccountI { m.ctrl.T.Helper() ret := m.ctrl.Call(m, "GetModuleAccount", ctx, moduleName) ret0, _ := ret[0].(types.ModuleAccountI) @@ -78,7 +79,7 @@ func (mr *MockAccountKeeperMockRecorder) GetModuleAccount(ctx, moduleName interf } // GetModuleAccountAndPermissions mocks base method. -func (m *MockAccountKeeper) GetModuleAccountAndPermissions(ctx types.Context, moduleName string) (types.ModuleAccountI, []string) { +func (m *MockAccountKeeper) GetModuleAccountAndPermissions(ctx context.Context, moduleName string) (types.ModuleAccountI, []string) { m.ctrl.T.Helper() ret := m.ctrl.Call(m, "GetModuleAccountAndPermissions", ctx, moduleName) ret0, _ := ret[0].(types.ModuleAccountI) @@ -136,7 +137,7 @@ func (mr *MockAccountKeeperMockRecorder) GetModulePermissions() *gomock.Call { } // HasAccount mocks base method. -func (m *MockAccountKeeper) HasAccount(ctx types.Context, addr types.AccAddress) bool { +func (m *MockAccountKeeper) HasAccount(ctx context.Context, addr types.AccAddress) bool { m.ctrl.T.Helper() ret := m.ctrl.Call(m, "HasAccount", ctx, addr) ret0, _ := ret[0].(bool) @@ -150,7 +151,7 @@ func (mr *MockAccountKeeperMockRecorder) HasAccount(ctx, addr interface{}) *gomo } // IterateAccounts mocks base method. -func (m *MockAccountKeeper) IterateAccounts(ctx types.Context, process func(types.AccountI) bool) { +func (m *MockAccountKeeper) IterateAccounts(ctx context.Context, process func(types.AccountI) bool) { m.ctrl.T.Helper() m.ctrl.Call(m, "IterateAccounts", ctx, process) } @@ -162,7 +163,7 @@ func (mr *MockAccountKeeperMockRecorder) IterateAccounts(ctx, process interface{ } // NewAccount mocks base method. -func (m *MockAccountKeeper) NewAccount(arg0 types.Context, arg1 types.AccountI) types.AccountI { +func (m *MockAccountKeeper) NewAccount(arg0 context.Context, arg1 types.AccountI) types.AccountI { m.ctrl.T.Helper() ret := m.ctrl.Call(m, "NewAccount", arg0, arg1) ret0, _ := ret[0].(types.AccountI) @@ -176,7 +177,7 @@ func (mr *MockAccountKeeperMockRecorder) NewAccount(arg0, arg1 interface{}) *gom } // NewAccountWithAddress mocks base method. -func (m *MockAccountKeeper) NewAccountWithAddress(ctx types.Context, addr types.AccAddress) types.AccountI { +func (m *MockAccountKeeper) NewAccountWithAddress(ctx context.Context, addr types.AccAddress) types.AccountI { m.ctrl.T.Helper() ret := m.ctrl.Call(m, "NewAccountWithAddress", ctx, addr) ret0, _ := ret[0].(types.AccountI) @@ -190,7 +191,7 @@ func (mr *MockAccountKeeperMockRecorder) NewAccountWithAddress(ctx, addr interfa } // SetAccount mocks base method. -func (m *MockAccountKeeper) SetAccount(ctx types.Context, acc types.AccountI) { +func (m *MockAccountKeeper) SetAccount(ctx context.Context, acc types.AccountI) { m.ctrl.T.Helper() m.ctrl.Call(m, "SetAccount", ctx, acc) } @@ -202,7 +203,7 @@ func (mr *MockAccountKeeperMockRecorder) SetAccount(ctx, acc interface{}) *gomoc } // SetModuleAccount mocks base method. -func (m *MockAccountKeeper) SetModuleAccount(ctx types.Context, macc types.ModuleAccountI) { +func (m *MockAccountKeeper) SetModuleAccount(ctx context.Context, macc types.ModuleAccountI) { m.ctrl.T.Helper() m.ctrl.Call(m, "SetModuleAccount", ctx, macc) } diff --git a/x/bank/types/balance_test.go b/x/bank/types/balance_test.go index a69cf48268bf..818ce152f8f9 100644 --- a/x/bank/types/balance_test.go +++ b/x/bank/types/balance_test.go @@ -60,7 +60,7 @@ func TestBalanceValidate(t *testing.T) { bank.Balance{ Address: "cosmos1yq8lgssgxlx9smjhes6ryjasmqmd3ts2559g0t", Coins: sdk.Coins{ - sdk.Coin{Denom: "uatom", Amount: sdk.NewInt(-1)}, + sdk.Coin{Denom: "uatom", Amount: math.NewInt(-1)}, }, }, true, diff --git a/x/bank/types/expected_keepers.go b/x/bank/types/expected_keepers.go index a56aeace3b5f..c1a8911107c6 100644 --- a/x/bank/types/expected_keepers.go +++ b/x/bank/types/expected_keepers.go @@ -1,6 +1,8 @@ package types import ( + context "context" + sdk "github.com/cosmos/cosmos-sdk/types" "github.com/cosmos/cosmos-sdk/x/auth/types" ) @@ -8,22 +10,22 @@ import ( // AccountKeeper defines the account contract that must be fulfilled when // creating a x/bank keeper. type AccountKeeper interface { - NewAccount(sdk.Context, sdk.AccountI) sdk.AccountI - NewAccountWithAddress(ctx sdk.Context, addr sdk.AccAddress) sdk.AccountI + NewAccount(context.Context, sdk.AccountI) sdk.AccountI + NewAccountWithAddress(ctx context.Context, addr sdk.AccAddress) sdk.AccountI - GetAccount(ctx sdk.Context, addr sdk.AccAddress) sdk.AccountI - GetAllAccounts(ctx sdk.Context) []sdk.AccountI - HasAccount(ctx sdk.Context, addr sdk.AccAddress) bool - SetAccount(ctx sdk.Context, acc sdk.AccountI) + GetAccount(ctx context.Context, addr sdk.AccAddress) sdk.AccountI + GetAllAccounts(ctx context.Context) []sdk.AccountI + HasAccount(ctx context.Context, addr sdk.AccAddress) bool + SetAccount(ctx context.Context, acc sdk.AccountI) - IterateAccounts(ctx sdk.Context, process func(sdk.AccountI) bool) + IterateAccounts(ctx context.Context, process func(sdk.AccountI) bool) ValidatePermissions(macc sdk.ModuleAccountI) error GetModuleAddress(moduleName string) sdk.AccAddress GetModuleAddressAndPermissions(moduleName string) (addr sdk.AccAddress, permissions []string) - GetModuleAccountAndPermissions(ctx sdk.Context, moduleName string) (sdk.ModuleAccountI, []string) - GetModuleAccount(ctx sdk.Context, moduleName string) sdk.ModuleAccountI - SetModuleAccount(ctx sdk.Context, macc sdk.ModuleAccountI) + GetModuleAccountAndPermissions(ctx context.Context, moduleName string) (sdk.ModuleAccountI, []string) + GetModuleAccount(ctx context.Context, moduleName string) sdk.ModuleAccountI + SetModuleAccount(ctx context.Context, macc sdk.ModuleAccountI) GetModulePermissions() map[string]types.PermissionsForAddress } diff --git a/x/bank/types/genesis_test.go b/x/bank/types/genesis_test.go index 074825c325cb..742691b6c7b0 100644 --- a/x/bank/types/genesis_test.go +++ b/x/bank/types/genesis_test.go @@ -170,9 +170,9 @@ func TestMigrateSendEnabled(t *testing.T) { Params: Params{}, Balances: []Balance{{ Address: "balance1", - Coins: sdk.Coins{sdk.NewCoin("balance1coin", sdk.NewInt(8))}, + Coins: sdk.Coins{sdk.NewCoin("balance1coin", math.NewInt(8))}, }}, - Supply: sdk.Coins{sdk.NewCoin("supplycoin", sdk.NewInt(800))}, + Supply: sdk.Coins{sdk.NewCoin("supplycoin", math.NewInt(800))}, DenomMetadata: []Metadata{{ Description: "metadesk", DenomUnits: nil, @@ -188,9 +188,9 @@ func TestMigrateSendEnabled(t *testing.T) { Params: Params{}, Balances: []Balance{{ Address: "balance1", - Coins: sdk.Coins{sdk.NewCoin("balance1coin", sdk.NewInt(8))}, + Coins: sdk.Coins{sdk.NewCoin("balance1coin", math.NewInt(8))}, }}, - Supply: sdk.Coins{sdk.NewCoin("supplycoin", sdk.NewInt(800))}, + Supply: sdk.Coins{sdk.NewCoin("supplycoin", math.NewInt(800))}, DenomMetadata: []Metadata{{ Description: "metadesk", DenomUnits: nil, diff --git a/x/bank/types/inputs_outputs.go b/x/bank/types/inputs_outputs.go new file mode 100644 index 000000000000..cca4c039887b --- /dev/null +++ b/x/bank/types/inputs_outputs.go @@ -0,0 +1,83 @@ +package types + +import ( + errorsmod "cosmossdk.io/errors" + sdk "github.com/cosmos/cosmos-sdk/types" + sdkerrors "github.com/cosmos/cosmos-sdk/types/errors" +) + +// ValidateInputOutputs validates that each respective input and output is +// valid and that the sum of inputs is equal to the sum of outputs. +func ValidateInputOutputs(input Input, outputs []Output) error { + var totalIn, totalOut sdk.Coins + + if err := input.ValidateBasic(); err != nil { + return err + } + totalIn = input.Coins + + for _, out := range outputs { + if err := out.ValidateBasic(); err != nil { + return err + } + + totalOut = totalOut.Add(out.Coins...) + } + + // make sure inputs and outputs match + if !totalIn.Equal(totalOut) { + return ErrInputOutputMismatch + } + + return nil +} + +// ValidateBasic - validate transaction input +func (in Input) ValidateBasic() error { + if _, err := sdk.AccAddressFromBech32(in.Address); err != nil { + return sdkerrors.ErrInvalidAddress.Wrapf("invalid input address: %s", err) + } + + if !in.Coins.IsValid() { + return errorsmod.Wrap(sdkerrors.ErrInvalidCoins, in.Coins.String()) + } + + if !in.Coins.IsAllPositive() { + return errorsmod.Wrap(sdkerrors.ErrInvalidCoins, in.Coins.String()) + } + + return nil +} + +// NewInput - create a transaction input, used with MsgMultiSend +func NewInput(addr sdk.AccAddress, coins sdk.Coins) Input { + return Input{ + Address: addr.String(), + Coins: coins, + } +} + +// ValidateBasic - validate transaction output +func (out Output) ValidateBasic() error { + if _, err := sdk.AccAddressFromBech32(out.Address); err != nil { + return sdkerrors.ErrInvalidAddress.Wrapf("invalid output address: %s", err) + } + + if !out.Coins.IsValid() { + return errorsmod.Wrap(sdkerrors.ErrInvalidCoins, out.Coins.String()) + } + + if !out.Coins.IsAllPositive() { + return errorsmod.Wrap(sdkerrors.ErrInvalidCoins, out.Coins.String()) + } + + return nil +} + +// NewOutput - create a transaction output, used with MsgMultiSend +func NewOutput(addr sdk.AccAddress, coins sdk.Coins) Output { + return Output{ + Address: addr.String(), + Coins: coins, + } +} diff --git a/x/bank/types/keys.go b/x/bank/types/keys.go index fbe24f19f3df..33c14f5c3892 100644 --- a/x/bank/types/keys.go +++ b/x/bank/types/keys.go @@ -2,9 +2,9 @@ package types import ( "cosmossdk.io/collections" + collcodec "cosmossdk.io/collections/codec" + "cosmossdk.io/math" sdk "github.com/cosmos/cosmos-sdk/types" - "github.com/cosmos/cosmos-sdk/types/address" - "github.com/cosmos/cosmos-sdk/types/kv" ) const ( @@ -22,12 +22,10 @@ const ( var ( SupplyKey = collections.NewPrefix(0) DenomMetadataPrefix = collections.NewPrefix(1) - DenomAddressPrefix = []byte{0x03} - // BalancesPrefix is the prefix for the account balances store. We use a byte // (instead of `[]byte("balances")` to save some disk space). - BalancesPrefix = []byte{0x02} - + BalancesPrefix = collections.NewPrefix(2) + DenomAddressPrefix = collections.NewPrefix(3) // SendEnabledPrefix is the prefix for the SendDisabled flags for a Denom. SendEnabledPrefix = collections.NewPrefix(4) @@ -35,45 +33,27 @@ var ( ParamsKey = collections.NewPrefix(5) ) -// AddressAndDenomFromBalancesStore returns an account address and denom from a balances prefix -// store. The key must not contain the prefix BalancesPrefix as the prefix store -// iterator discards the actual prefix. -// -// If invalid key is passed, AddressAndDenomFromBalancesStore returns ErrInvalidKey. -func AddressAndDenomFromBalancesStore(key []byte) (sdk.AccAddress, string, error) { - if len(key) == 0 { - return nil, "", ErrInvalidKey - } - - kv.AssertKeyAtLeastLength(key, 1) - - addrBound := int(key[0]) - - if len(key)-1 < addrBound { - return nil, "", ErrInvalidKey +// NewBalanceCompatValueCodec is a codec for encoding Balances in a backwards compatible way +// with respect to the old format. +func NewBalanceCompatValueCodec() collcodec.ValueCodec[math.Int] { + return balanceCompatValueCodec{ + sdk.IntValue, } - - return key[1 : addrBound+1], string(key[addrBound+1:]), nil -} - -// CreatePrefixedAccountStoreKey returns the key for the given account and denomination. -// This method can be used when performing an ABCI query for the balance of an account. -func CreatePrefixedAccountStoreKey(addr []byte, denom []byte) []byte { - return append(CreateAccountBalancesPrefix(addr), denom...) } -// CreateAccountBalancesPrefix creates the prefix for an account's balances. -func CreateAccountBalancesPrefix(addr []byte) []byte { - return append(BalancesPrefix, address.MustLengthPrefix(addr)...) +type balanceCompatValueCodec struct { + collcodec.ValueCodec[math.Int] } -// CreateDenomAddressPrefix creates a prefix for a reverse index of denomination -// to account balance for that denomination. -func CreateDenomAddressPrefix(denom string) []byte { - // we add a "zero" byte at the end - null byte terminator, to allow prefix denom prefix - // scan. Setting it is not needed (key[last] = 0) - because this is the default. - key := make([]byte, len(DenomAddressPrefix)+len(denom)+1) - copy(key, DenomAddressPrefix) - copy(key[len(DenomAddressPrefix):], denom) - return key +func (v balanceCompatValueCodec) Decode(b []byte) (math.Int, error) { + i, err := v.ValueCodec.Decode(b) + if err == nil { + return i, nil + } + c := new(sdk.Coin) + err = c.Unmarshal(b) + if err != nil { + return math.Int{}, err + } + return c.Amount, nil } diff --git a/x/bank/types/keys_test.go b/x/bank/types/keys_test.go index ba0dd5c63ee4..31aa8aa13e98 100644 --- a/x/bank/types/keys_test.go +++ b/x/bank/types/keys_test.go @@ -1,70 +1,26 @@ -package types_test +package types import ( - "errors" "testing" - "github.com/stretchr/testify/assert" - "github.com/stretchr/testify/require" - + "cosmossdk.io/collections/colltest" + "cosmossdk.io/math" sdk "github.com/cosmos/cosmos-sdk/types" - "github.com/cosmos/cosmos-sdk/types/address" - "github.com/cosmos/cosmos-sdk/x/bank/types" + "github.com/stretchr/testify/require" ) -func cloneAppend(bz []byte, tail []byte) (res []byte) { - res = make([]byte, len(bz)+len(tail)) - copy(res, bz) - copy(res[len(bz):], tail) - return -} - -func TestAddressFromBalancesStore(t *testing.T) { - addr, err := sdk.AccAddressFromBech32("cosmos1n88uc38xhjgxzw9nwre4ep2c8ga4fjxcar6mn7") - require.NoError(t, err) - addrLen := len(addr) - require.Equal(t, 20, addrLen) - key := cloneAppend(address.MustLengthPrefix(addr), []byte("stake")) - - tests := []struct { - name string - key []byte - wantErr bool - expectedKey sdk.AccAddress - }{ - {"valid", key, false, addr}, - {"#9111", []byte("\xff000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000"), false, nil}, - {"empty", []byte(""), true, nil}, - {"invalid", []byte("3AA"), true, nil}, - } - - for _, tc := range tests { - tc := tc - t.Run(tc.name, func(t *testing.T) { - t.Parallel() - addr, denom, err := types.AddressAndDenomFromBalancesStore(tc.key) - if tc.wantErr { - assert.Error(t, err) - assert.True(t, errors.Is(types.ErrInvalidKey, err)) - } else { - assert.NoError(t, err) - } - if len(tc.expectedKey) > 0 { - assert.Equal(t, tc.expectedKey, addr) - assert.Equal(t, "stake", denom) - } - }) - } -} - -func TestCreateDenomAddressPrefix(t *testing.T) { - require := require.New(t) - - key := types.CreateDenomAddressPrefix("") - require.Len(key, len(types.DenomAddressPrefix)+1) - require.Equal(append(types.DenomAddressPrefix, 0), key) - - key = types.CreateDenomAddressPrefix("abc") - require.Len(key, len(types.DenomAddressPrefix)+4) - require.Equal(append(types.DenomAddressPrefix, 'a', 'b', 'c', 0), key) +func TestBalanceValueCodec(t *testing.T) { + c := NewBalanceCompatValueCodec() + t.Run("value codec implementation", func(t *testing.T) { + colltest.TestValueCodec(t, c, math.NewInt(100)) + }) + + t.Run("legacy coin", func(t *testing.T) { + coin := sdk.NewInt64Coin("coin", 1000) + b, err := coin.Marshal() + require.NoError(t, err) + amt, err := c.Decode(b) + require.NoError(t, err) + require.Equal(t, coin.Amount, amt) + }) } diff --git a/x/bank/types/msgs.go b/x/bank/types/msgs.go index 25ecdf50ceb0..f3a70d6f3e11 100644 --- a/x/bank/types/msgs.go +++ b/x/bank/types/msgs.go @@ -1,10 +1,7 @@ package types import ( - errorsmod "cosmossdk.io/errors" - sdk "github.com/cosmos/cosmos-sdk/types" - sdkerrors "github.com/cosmos/cosmos-sdk/types/errors" "github.com/cosmos/cosmos-sdk/x/auth/migrations/legacytx" ) @@ -19,33 +16,10 @@ var ( ) // NewMsgSend - construct a msg to send coins from one account to another. -// -//nolint:interfacer func NewMsgSend(fromAddr, toAddr sdk.AccAddress, amount sdk.Coins) *MsgSend { return &MsgSend{FromAddress: fromAddr.String(), ToAddress: toAddr.String(), Amount: amount} } -// ValidateBasic Implements Msg. -func (msg MsgSend) ValidateBasic() error { - if _, err := sdk.AccAddressFromBech32(msg.FromAddress); err != nil { - return sdkerrors.ErrInvalidAddress.Wrapf("invalid from address: %s", err) - } - - if _, err := sdk.AccAddressFromBech32(msg.ToAddress); err != nil { - return sdkerrors.ErrInvalidAddress.Wrapf("invalid to address: %s", err) - } - - if !msg.Amount.IsValid() { - return errorsmod.Wrap(sdkerrors.ErrInvalidCoins, msg.Amount.String()) - } - - if !msg.Amount.IsAllPositive() { - return errorsmod.Wrap(sdkerrors.ErrInvalidCoins, msg.Amount.String()) - } - - return nil -} - // GetSignBytes Implements Msg. func (msg MsgSend) GetSignBytes() []byte { return sdk.MustSortJSON(ModuleCdc.MustMarshalJSON(&msg)) @@ -62,26 +36,6 @@ func NewMsgMultiSend(in Input, out []Output) *MsgMultiSend { return &MsgMultiSend{Inputs: []Input{in}, Outputs: out} } -// ValidateBasic Implements Msg. -func (msg MsgMultiSend) ValidateBasic() error { - // this just makes sure the input and all the outputs are properly formatted, - // not that they actually have the money inside - - if len(msg.Inputs) == 0 { - return ErrNoInputs - } - - if len(msg.Inputs) != 1 { - return ErrMultipleSenders - } - - if len(msg.Outputs) == 0 { - return ErrNoOutputs - } - - return ValidateInputOutputs(msg.Inputs[0], msg.Outputs) -} - // GetSignBytes Implements Msg. func (msg MsgMultiSend) GetSignBytes() []byte { return sdk.MustSortJSON(ModuleCdc.MustMarshalJSON(&msg)) @@ -98,86 +52,6 @@ func (msg MsgMultiSend) GetSigners() []sdk.AccAddress { return []sdk.AccAddress{addrs} } -// ValidateBasic - validate transaction input -func (in Input) ValidateBasic() error { - if _, err := sdk.AccAddressFromBech32(in.Address); err != nil { - return sdkerrors.ErrInvalidAddress.Wrapf("invalid input address: %s", err) - } - - if !in.Coins.IsValid() { - return errorsmod.Wrap(sdkerrors.ErrInvalidCoins, in.Coins.String()) - } - - if !in.Coins.IsAllPositive() { - return errorsmod.Wrap(sdkerrors.ErrInvalidCoins, in.Coins.String()) - } - - return nil -} - -// NewInput - create a transaction input, used with MsgMultiSend -// -//nolint:interfacer -func NewInput(addr sdk.AccAddress, coins sdk.Coins) Input { - return Input{ - Address: addr.String(), - Coins: coins, - } -} - -// ValidateBasic - validate transaction output -func (out Output) ValidateBasic() error { - if _, err := sdk.AccAddressFromBech32(out.Address); err != nil { - return sdkerrors.ErrInvalidAddress.Wrapf("invalid output address: %s", err) - } - - if !out.Coins.IsValid() { - return errorsmod.Wrap(sdkerrors.ErrInvalidCoins, out.Coins.String()) - } - - if !out.Coins.IsAllPositive() { - return errorsmod.Wrap(sdkerrors.ErrInvalidCoins, out.Coins.String()) - } - - return nil -} - -// NewOutput - create a transaction output, used with MsgMultiSend -// -//nolint:interfacer -func NewOutput(addr sdk.AccAddress, coins sdk.Coins) Output { - return Output{ - Address: addr.String(), - Coins: coins, - } -} - -// ValidateInputOutputs validates that each respective input and output is -// valid and that the sum of inputs is equal to the sum of outputs. -func ValidateInputOutputs(input Input, outputs []Output) error { - var totalIn, totalOut sdk.Coins - - if err := input.ValidateBasic(); err != nil { - return err - } - totalIn = input.Coins - - for _, out := range outputs { - if err := out.ValidateBasic(); err != nil { - return err - } - - totalOut = totalOut.Add(out.Coins...) - } - - // make sure inputs and outputs match - if !totalIn.Equal(totalOut) { - return ErrInputOutputMismatch - } - - return nil -} - // GetSigners returns the signer addresses that are expected to sign the result // of GetSignBytes. func (msg MsgUpdateParams) GetSigners() []sdk.AccAddress { @@ -192,11 +66,6 @@ func (msg MsgUpdateParams) GetSignBytes() []byte { return sdk.MustSortJSON(bz) } -// ValidateBasic performs basic MsgUpdateParams message validation. -func (msg MsgUpdateParams) ValidateBasic() error { - return msg.Params.Validate() -} - // NewMsgSetSendEnabled Construct a message to set one or more SendEnabled entries. func NewMsgSetSendEnabled(authority string, sendEnabled []*SendEnabled, useDefaultFor []string) *MsgSetSendEnabled { return &MsgSetSendEnabled{ @@ -216,33 +85,3 @@ func (msg MsgSetSendEnabled) GetSigners() []sdk.AccAddress { addr, _ := sdk.AccAddressFromBech32(msg.Authority) return []sdk.AccAddress{addr} } - -// ValidateBasic runs basic validation on this MsgSetSendEnabled. -func (msg MsgSetSendEnabled) ValidateBasic() error { - if len(msg.Authority) > 0 { - if _, err := sdk.AccAddressFromBech32(msg.Authority); err != nil { - return sdkerrors.ErrInvalidAddress.Wrapf("invalid authority address: %s", err) - } - } - - seen := map[string]bool{} - for _, se := range msg.SendEnabled { - if _, alreadySeen := seen[se.Denom]; alreadySeen { - return sdkerrors.ErrInvalidRequest.Wrapf("duplicate denom entries found for %q", se.Denom) - } - - seen[se.Denom] = true - - if err := se.Validate(); err != nil { - return sdkerrors.ErrInvalidRequest.Wrapf("invalid SendEnabled denom %q: %s", se.Denom, err) - } - } - - for _, denom := range msg.UseDefaultFor { - if err := sdk.ValidateDenom(denom); err != nil { - return sdkerrors.ErrInvalidRequest.Wrapf("invalid UseDefaultFor denom %q: %s", denom, err) - } - } - - return nil -} diff --git a/x/bank/types/msgs_test.go b/x/bank/types/msgs_test.go index 3853d8a76ba1..4f6462da26a3 100644 --- a/x/bank/types/msgs_test.go +++ b/x/bank/types/msgs_test.go @@ -11,41 +11,6 @@ import ( govtypes "github.com/cosmos/cosmos-sdk/x/gov/types" ) -func TestMsgSendValidation(t *testing.T) { - addr1 := sdk.AccAddress([]byte("from________________")) - addr2 := sdk.AccAddress([]byte("to__________________")) - addrEmpty := sdk.AccAddress([]byte("")) - addrLong := sdk.AccAddress([]byte("Purposefully long address")) - - atom123 := sdk.NewCoins(sdk.NewInt64Coin("atom", 123)) - atom0 := sdk.NewCoins(sdk.NewInt64Coin("atom", 0)) - atom123eth123 := sdk.NewCoins(sdk.NewInt64Coin("atom", 123), sdk.NewInt64Coin("eth", 123)) - atom123eth0 := sdk.Coins{sdk.NewInt64Coin("atom", 123), sdk.NewInt64Coin("eth", 0)} - - cases := []struct { - expectedErr string // empty means no error expected - msg *MsgSend - }{ - {"", NewMsgSend(addr1, addr2, atom123)}, // valid send - {"", NewMsgSend(addr1, addr2, atom123eth123)}, // valid send with multiple coins - {"", NewMsgSend(addrLong, addr2, atom123)}, // valid send with long addr sender - {"", NewMsgSend(addr1, addrLong, atom123)}, // valid send with long addr recipient - {": invalid coins", NewMsgSend(addr1, addr2, atom0)}, // non positive coin - {"123atom,0eth: invalid coins", NewMsgSend(addr1, addr2, atom123eth0)}, // non positive coin in multicoins - {"invalid from address: empty address string is not allowed: invalid address", NewMsgSend(addrEmpty, addr2, atom123)}, - {"invalid to address: empty address string is not allowed: invalid address", NewMsgSend(addr1, addrEmpty, atom123)}, - } - - for _, tc := range cases { - err := tc.msg.ValidateBasic() - if tc.expectedErr == "" { - require.Nil(t, err) - } else { - require.EqualError(t, err, tc.expectedErr) - } - } -} - func TestMsgSendGetSignBytes(t *testing.T) { addr1 := sdk.AccAddress([]byte("input")) addr2 := sdk.AccAddress([]byte("output")) @@ -139,93 +104,6 @@ func TestOutputValidation(t *testing.T) { } } -func TestMsgMultiSendValidation(t *testing.T) { - addr1 := sdk.AccAddress([]byte("_______alice________")) - addr2 := sdk.AccAddress([]byte("________bob_________")) - addr3 := sdk.AccAddress([]byte("_______addr3________")) - atom123 := sdk.NewCoins(sdk.NewInt64Coin("atom", 123)) - atom124 := sdk.NewCoins(sdk.NewInt64Coin("atom", 124)) - atom246 := sdk.NewCoins(sdk.NewInt64Coin("atom", 246)) - - input1 := NewInput(addr1, atom123) - input2 := NewInput(addr1, atom246) - output1 := NewOutput(addr2, atom123) - output2 := NewOutput(addr2, atom124) - output3 := NewOutput(addr2, atom123) - output4 := NewOutput(addr3, atom123) - - var emptyAddr sdk.AccAddress - - cases := []struct { - valid bool - tx MsgMultiSend - expErrMsg string - }{ - {false, MsgMultiSend{}, "no inputs to send transaction"}, // no input or output - {false, MsgMultiSend{Inputs: []Input{input1}}, "no outputs to send transaction"}, // just input - {false, MsgMultiSend{Outputs: []Output{output1}}, "no inputs to send transaction"}, // just output - { - false, - MsgMultiSend{ - Inputs: []Input{NewInput(emptyAddr, atom123)}, // invalid input - Outputs: []Output{output1}, - }, - "invalid input address", - }, - { - false, - MsgMultiSend{ - Inputs: []Input{input1}, - Outputs: []Output{{emptyAddr.String(), atom123}}, // invalid output - }, - "invalid output address", - }, - { - false, - MsgMultiSend{ - Inputs: []Input{input1}, - Outputs: []Output{output2}, // amounts don't match - }, - "sum inputs != sum outputs", - }, - { - true, - MsgMultiSend{ - Inputs: []Input{input1}, - Outputs: []Output{output1}, - }, - "", - }, - { - false, - MsgMultiSend{ - Inputs: []Input{input1, input2}, - Outputs: []Output{output3, output4}, - }, - "multiple senders not allowed", - }, - { - true, - MsgMultiSend{ - Inputs: []Input{NewInput(addr2, atom123.MulInt(sdk.NewInt(2)))}, - Outputs: []Output{output1, output1}, - }, - "", - }, - } - - for i, tc := range cases { - err := tc.tx.ValidateBasic() - if tc.valid { - require.Nil(t, err, "%d: %+v", i, err) - require.Nil(t, err) - } else { - require.NotNil(t, err, "%d", i) - require.Contains(t, err.Error(), tc.expErrMsg) - } - } -} - func TestMsgMultiSendGetSignBytes(t *testing.T) { addr1 := sdk.AccAddress([]byte("input")) addr2 := sdk.AccAddress([]byte("output")) @@ -286,100 +164,3 @@ func TestMsgSetSendEnabledGetSigners(t *testing.T) { actual := msg.GetSigners() assert.Equal(t, expected, actual) } - -func TestMsgSetSendEnabledValidateBasic(t *testing.T) { - govModuleAddr := authtypes.NewModuleAddress(govtypes.ModuleName).String() - tests := []struct { - name string - msg MsgSetSendEnabled - exp string - }{ - { - name: "valid with two entries", - msg: MsgSetSendEnabled{ - Authority: govModuleAddr, - SendEnabled: []*SendEnabled{ - {"somecoina", true}, - {"somecoinb", false}, - }, - UseDefaultFor: []string{"defcoinc", "defcoind"}, - }, - exp: "", - }, - { - name: "valid with two entries but no authority", - msg: MsgSetSendEnabled{ - Authority: "", - SendEnabled: []*SendEnabled{ - {"somecoina", true}, - {"somecoinb", false}, - }, - UseDefaultFor: []string{"defcoinc", "defcoind"}, - }, - exp: "", - }, - { - name: "bad authority", - msg: MsgSetSendEnabled{ - Authority: "farva", - SendEnabled: []*SendEnabled{ - {"somecoina", true}, - {"somecoinb", false}, - }, - }, - exp: "invalid authority address: decoding bech32 failed: invalid bech32 string length 5: invalid address", - }, - { - name: "bad first denom name", - msg: MsgSetSendEnabled{ - Authority: govModuleAddr, - SendEnabled: []*SendEnabled{ - {"Not A Denom", true}, - {"somecoinb", false}, - }, - }, - exp: `invalid SendEnabled denom "Not A Denom": invalid denom: Not A Denom: invalid request`, - }, - { - name: "bad second denom", - msg: MsgSetSendEnabled{ - Authority: govModuleAddr, - SendEnabled: []*SendEnabled{ - {"somecoina", true}, - {"", false}, - }, - }, - exp: `invalid SendEnabled denom "": invalid denom: : invalid request`, - }, - { - name: "duplicate denom", - msg: MsgSetSendEnabled{ - Authority: govModuleAddr, - SendEnabled: []*SendEnabled{ - {"copycoin", true}, - {"copycoin", false}, - }, - }, - exp: `duplicate denom entries found for "copycoin": invalid request`, - }, - { - name: "bad denom to delete", - msg: MsgSetSendEnabled{ - Authority: govModuleAddr, - UseDefaultFor: []string{"very \t bad denom string~~~!"}, - }, - exp: "invalid UseDefaultFor denom \"very \\t bad denom string~~~!\": invalid denom: very \t bad denom string~~~!: invalid request", - }, - } - - for _, tc := range tests { - t.Run(tc.name, func(tt *testing.T) { - actual := tc.msg.ValidateBasic() - if len(tc.exp) > 0 { - require.EqualError(tt, actual, tc.exp) - } else { - require.NoError(tt, actual) - } - }) - } -} diff --git a/x/bank/types/querier.go b/x/bank/types/querier.go index 6a36dedcbb14..5303035c2b44 100644 --- a/x/bank/types/querier.go +++ b/x/bank/types/querier.go @@ -14,37 +14,28 @@ const ( ) // NewQueryBalanceRequest creates a new instance of QueryBalanceRequest. -// -//nolint:interfacer func NewQueryBalanceRequest(addr sdk.AccAddress, denom string) *QueryBalanceRequest { return &QueryBalanceRequest{Address: addr.String(), Denom: denom} } // NewQueryAllBalancesRequest creates a new instance of QueryAllBalancesRequest. -// -//nolint:interfacer func NewQueryAllBalancesRequest(addr sdk.AccAddress, req *query.PageRequest, resolveDenom bool) *QueryAllBalancesRequest { return &QueryAllBalancesRequest{Address: addr.String(), Pagination: req, ResolveDenom: resolveDenom} } // NewQuerySpendableBalancesRequest creates a new instance of a // QuerySpendableBalancesRequest. -// -//nolint:interfacer func NewQuerySpendableBalancesRequest(addr sdk.AccAddress, req *query.PageRequest) *QuerySpendableBalancesRequest { return &QuerySpendableBalancesRequest{Address: addr.String(), Pagination: req} } // NewQuerySpendableBalanceByDenomRequest creates a new instance of a // QuerySpendableBalanceByDenomRequest. -// -//nolint:interfacer func NewQuerySpendableBalanceByDenomRequest(addr sdk.AccAddress, denom string) *QuerySpendableBalanceByDenomRequest { return &QuerySpendableBalanceByDenomRequest{Address: addr.String(), Denom: denom} } // QueryTotalSupplyParams defines the params for the following queries: -// // - 'custom/bank/totalSupply' type QueryTotalSupplyParams struct { Page, Limit int @@ -56,7 +47,6 @@ func NewQueryTotalSupplyParams(page, limit int) QueryTotalSupplyParams { } // QuerySupplyOfParams defines the params for the following queries: -// // - 'custom/bank/totalSupplyOf' type QuerySupplyOfParams struct { Denom string diff --git a/x/bank/types/send_authorization_test.go b/x/bank/types/send_authorization_test.go index 642463c3e55d..5c50fd266dcf 100644 --- a/x/bank/types/send_authorization_test.go +++ b/x/bank/types/send_authorization_test.go @@ -7,6 +7,7 @@ import ( cmtproto "github.com/cometbft/cometbft/proto/tendermint/types" "github.com/stretchr/testify/require" + sdkmath "cosmossdk.io/math" storetypes "cosmossdk.io/store/types" "github.com/cosmos/cosmos-sdk/testutil" @@ -15,8 +16,8 @@ import ( ) var ( - coins1000 = sdk.NewCoins(sdk.NewCoin("stake", sdk.NewInt(1000))) - coins500 = sdk.NewCoins(sdk.NewCoin("stake", sdk.NewInt(500))) + coins1000 = sdk.NewCoins(sdk.NewCoin("stake", sdkmath.NewInt(1000))) + coins500 = sdk.NewCoins(sdk.NewCoin("stake", sdkmath.NewInt(500))) fromAddr = sdk.AccAddress("_____from _____") toAddr = sdk.AccAddress("_______to________") unknownAddr = sdk.AccAddress("_____unknown_____") diff --git a/x/circuit/go.mod b/x/circuit/go.mod index c675add89466..ba292506ab92 100644 --- a/x/circuit/go.mod +++ b/x/circuit/go.mod @@ -3,22 +3,26 @@ module github.com/cosmos/cosmos-sdk/x/circuit go 1.20 require ( - cosmossdk.io/store v0.1.0-alpha.1 - github.com/cosmos/cosmos-sdk v0.46.0-beta2.0.20230321173237-fe77d4bca302 - github.com/cosmos/gogoproto v1.4.6 + github.com/cosmos/cosmos-sdk v0.46.0-beta2.0.20230418140744-0dde947d0ab7 + github.com/cosmos/gogoproto v1.4.8 + github.com/golang/protobuf v1.5.3 + github.com/grpc-ecosystem/grpc-gateway v1.16.0 github.com/regen-network/gocuke v0.6.2 + google.golang.org/genproto v0.0.0-20230410155749-daa745c078e1 google.golang.org/grpc v1.54.0 gotest.tools/v3 v3.4.0 ) require ( - cosmossdk.io/api v0.3.2-0.20230313131911-55bf5d4efbe7 // indirect - cosmossdk.io/collections v0.0.0-20230309163709-87da587416ba // indirect + cosmossdk.io/api v0.4.0 // indirect + cosmossdk.io/collections v0.1.0 // indirect cosmossdk.io/core v0.6.1 // indirect cosmossdk.io/depinject v1.0.0-alpha.3 // indirect cosmossdk.io/errors v1.0.0-beta.7 // indirect - cosmossdk.io/log v0.1.0 // indirect + cosmossdk.io/log v1.0.0 // indirect cosmossdk.io/math v1.0.0 // indirect + cosmossdk.io/store v0.1.0-alpha.1.0.20230328185921-37ba88872dbc // indirect + cosmossdk.io/x/tx v0.5.1-0.20230407182919-057d2e09bd63 // indirect github.com/DataDog/zstd v1.5.2 // indirect github.com/alecthomas/participle/v2 v2.0.0-alpha7 // indirect github.com/armon/go-metrics v0.4.1 // indirect @@ -28,9 +32,9 @@ require ( github.com/cockroachdb/apd/v3 v3.1.0 // indirect github.com/cockroachdb/errors v1.9.1 // indirect github.com/cockroachdb/logtags v0.0.0-20230118201751-21c54148d20b // indirect - github.com/cockroachdb/pebble v0.0.0-20230315223031-1e5ddd10389e // indirect + github.com/cockroachdb/pebble v0.0.0-20230412222916-60cfeb46143b // indirect github.com/cockroachdb/redact v1.1.3 // indirect - github.com/cometbft/cometbft v0.37.0 // indirect + github.com/cometbft/cometbft v0.37.1-0.20230411132551-3a91d155e664 // indirect github.com/confio/ics23/go v0.9.0 // indirect github.com/cosmos/btcutil v1.0.5 // indirect github.com/cosmos/cosmos-db v1.0.0-rc.1 // indirect @@ -38,64 +42,50 @@ require ( github.com/cucumber/common/gherkin/go/v22 v22.0.0 // indirect github.com/cucumber/common/messages/go/v17 v17.1.1 // indirect github.com/davecgh/go-spew v1.1.1 // indirect - github.com/decred/dcrd/dcrec/secp256k1/v4 v4.1.0 // indirect - github.com/fsnotify/fsnotify v1.6.0 // indirect - github.com/getsentry/sentry-go v0.19.0 // indirect + github.com/decred/dcrd/dcrec/secp256k1/v4 v4.2.0 // indirect + github.com/getsentry/sentry-go v0.20.0 // indirect github.com/go-kit/kit v0.12.0 // indirect github.com/go-kit/log v0.2.1 // indirect github.com/go-logfmt/logfmt v0.6.0 // indirect github.com/gofrs/uuid v4.3.0+incompatible // indirect github.com/gogo/protobuf v1.3.2 // indirect - github.com/golang/protobuf v1.5.3 // indirect github.com/golang/snappy v0.0.4 // indirect github.com/google/btree v1.1.2 // indirect github.com/google/go-cmp v0.5.9 // indirect - github.com/grpc-ecosystem/grpc-gateway v1.16.0 // indirect github.com/gtank/merlin v0.1.1 // indirect github.com/hashicorp/go-immutable-radix v1.3.1 // indirect github.com/hashicorp/golang-lru v0.5.5-0.20210104140557-80c98217689d // indirect - github.com/hashicorp/hcl v1.0.0 // indirect github.com/inconshreveable/mousetrap v1.1.0 // indirect - github.com/klauspost/compress v1.16.3 // indirect + github.com/klauspost/compress v1.16.5 // indirect github.com/kr/pretty v0.3.1 // indirect github.com/kr/text v0.2.0 // indirect github.com/libp2p/go-buffer-pool v0.1.0 // indirect - github.com/linxGnu/grocksdb v1.7.15 // indirect - github.com/magiconair/properties v1.8.7 // indirect + github.com/linxGnu/grocksdb v1.7.16 // indirect github.com/mattn/go-colorable v0.1.13 // indirect github.com/mattn/go-isatty v0.0.18 // indirect github.com/matttproud/golang_protobuf_extensions v1.0.4 // indirect github.com/mimoo/StrobeGo v0.0.0-20210601165009-122bf33a46e0 // indirect - github.com/mitchellh/mapstructure v1.5.0 // indirect - github.com/pelletier/go-toml/v2 v2.0.7 // indirect github.com/petermattis/goid v0.0.0-20230317030725-371a4b8eda08 // indirect github.com/pkg/errors v0.9.1 // indirect - github.com/prometheus/client_golang v1.14.0 // indirect + github.com/prometheus/client_golang v1.15.0 // indirect github.com/prometheus/client_model v0.3.0 // indirect github.com/prometheus/common v0.42.0 // indirect github.com/prometheus/procfs v0.9.0 // indirect - github.com/rogpeppe/go-internal v1.9.0 // indirect - github.com/rs/zerolog v1.29.0 // indirect + github.com/rogpeppe/go-internal v1.10.0 // indirect + github.com/rs/zerolog v1.29.1 // indirect github.com/sasha-s/go-deadlock v0.3.1 // indirect - github.com/spf13/afero v1.9.3 // indirect github.com/spf13/cast v1.5.0 // indirect - github.com/spf13/cobra v1.6.1 // indirect - github.com/spf13/jwalterweatherman v1.1.0 // indirect + github.com/spf13/cobra v1.7.0 // indirect github.com/spf13/pflag v1.0.5 // indirect - github.com/spf13/viper v1.15.0 // indirect - github.com/subosito/gotenv v1.4.2 // indirect github.com/syndtr/goleveldb v1.0.1-0.20220721030215-126854af5e6d // indirect github.com/tendermint/go-amino v0.16.0 // indirect - golang.org/x/crypto v0.7.0 // indirect + golang.org/x/crypto v0.8.0 // indirect golang.org/x/exp v0.0.0-20230321023759-10a507213a29 // indirect - golang.org/x/net v0.8.0 // indirect - golang.org/x/sys v0.6.0 // indirect - golang.org/x/text v0.8.0 // indirect - google.golang.org/genproto v0.0.0-20230320184635-7606e756e683 // indirect + golang.org/x/net v0.9.0 // indirect + golang.org/x/sys v0.7.0 // indirect + golang.org/x/text v0.9.0 // indirect google.golang.org/protobuf v1.30.0 // indirect - gopkg.in/ini.v1 v1.67.0 // indirect gopkg.in/yaml.v2 v2.4.0 // indirect - gopkg.in/yaml.v3 v3.0.1 // indirect pgregory.net/rapid v0.5.5 // indirect sigs.k8s.io/yaml v1.3.0 // indirect ) diff --git a/x/circuit/go.sum b/x/circuit/go.sum index 5ea0a1e03b10..3bdb8bf35ffb 100644 --- a/x/circuit/go.sum +++ b/x/circuit/go.sum @@ -1,64 +1,28 @@ cloud.google.com/go v0.26.0/go.mod h1:aQUYkXzVsufM+DwF1aE+0xfcU+56JwCaLick0ClmMTw= cloud.google.com/go v0.34.0/go.mod h1:aQUYkXzVsufM+DwF1aE+0xfcU+56JwCaLick0ClmMTw= -cloud.google.com/go v0.38.0/go.mod h1:990N+gfupTy94rShfmMCWGDn0LpTmnzTp2qbd1dvSRU= -cloud.google.com/go v0.44.1/go.mod h1:iSa0KzasP4Uvy3f1mN/7PiObzGgflwredwwASm/v6AU= -cloud.google.com/go v0.44.2/go.mod h1:60680Gw3Yr4ikxnPRS/oxxkBccT6SA1yMk63TGekxKY= -cloud.google.com/go v0.44.3/go.mod h1:60680Gw3Yr4ikxnPRS/oxxkBccT6SA1yMk63TGekxKY= -cloud.google.com/go v0.45.1/go.mod h1:RpBamKRgapWJb87xiFSdk4g1CME7QZg3uwTez+TSTjc= -cloud.google.com/go v0.46.3/go.mod h1:a6bKKbmY7er1mI7TEI4lsAkts/mkhTSZK8w33B4RAg0= -cloud.google.com/go v0.50.0/go.mod h1:r9sluTvynVuxRIOHXQEHMFffphuXHOMZMycpNR5e6To= -cloud.google.com/go v0.52.0/go.mod h1:pXajvRH/6o3+F9jDHZWQ5PbGhn+o8w9qiu/CffaVdO4= -cloud.google.com/go v0.53.0/go.mod h1:fp/UouUEsRkN6ryDKNW/Upv/JBKnv6WDthjR6+vze6M= -cloud.google.com/go v0.54.0/go.mod h1:1rq2OEkV3YMf6n/9ZvGWI3GWw0VoqH/1x2nd8Is/bPc= -cloud.google.com/go v0.56.0/go.mod h1:jr7tqZxxKOVYizybht9+26Z/gUq7tiRzu+ACVAMbKVk= -cloud.google.com/go v0.57.0/go.mod h1:oXiQ6Rzq3RAkkY7N6t3TcE6jE+CIBBbA36lwQ1JyzZs= -cloud.google.com/go v0.62.0/go.mod h1:jmCYTdRCQuc1PHIIJ/maLInMho30T/Y0M4hTdTShOYc= -cloud.google.com/go v0.65.0/go.mod h1:O5N8zS7uWy9vkA9vayVHs65eM1ubvY4h553ofrNHObY= -cloud.google.com/go v0.72.0/go.mod h1:M+5Vjvlc2wnp6tjzE102Dw08nGShTscUx2nZMufOKPI= -cloud.google.com/go v0.74.0/go.mod h1:VV1xSbzvo+9QJOxLDaJfTjx5e+MePCpCWwvftOeQmWk= -cloud.google.com/go v0.75.0/go.mod h1:VGuuCn7PG0dwsd5XPVm2Mm3wlh3EL55/79EKB6hlPTY= -cloud.google.com/go/bigquery v1.0.1/go.mod h1:i/xbL2UlR5RvWAURpBYZTtm/cXjCha9lbfbpx4poX+o= -cloud.google.com/go/bigquery v1.3.0/go.mod h1:PjpwJnslEMmckchkHFfq+HTD2DmtT67aNFKH1/VBDHE= -cloud.google.com/go/bigquery v1.4.0/go.mod h1:S8dzgnTigyfTmLBfrtrhyYhwRxG72rYxvftPBK2Dvzc= -cloud.google.com/go/bigquery v1.5.0/go.mod h1:snEHRnqQbz117VIFhE8bmtwIDY80NLUZUMb4Nv6dBIg= -cloud.google.com/go/bigquery v1.7.0/go.mod h1://okPTzCYNXSlb24MZs83e2Do+h+VXtc4gLoIoXIAPc= -cloud.google.com/go/bigquery v1.8.0/go.mod h1:J5hqkt3O0uAFnINi6JXValWIb1v0goeZM77hZzJN/fQ= -cloud.google.com/go/datastore v1.0.0/go.mod h1:LXYbyblFSglQ5pkeyhO+Qmw7ukd3C+pD7TKLgZqpHYE= -cloud.google.com/go/datastore v1.1.0/go.mod h1:umbIZjpQpHh4hmRpGhH4tLFup+FVzqBi1b3c64qFpCk= -cloud.google.com/go/pubsub v1.0.1/go.mod h1:R0Gpsv3s54REJCy4fxDixWD93lHJMoZTyQ2kNxGRt3I= -cloud.google.com/go/pubsub v1.1.0/go.mod h1:EwwdRX2sKPjnvnqCa270oGRyludottCI76h+R3AArQw= -cloud.google.com/go/pubsub v1.2.0/go.mod h1:jhfEVHT8odbXTkndysNHCcx0awwzvfOlguIAii9o8iA= -cloud.google.com/go/pubsub v1.3.1/go.mod h1:i+ucay31+CNRpDW4Lu78I4xXG+O1r/MAHgjpRVR+TSU= -cloud.google.com/go/storage v1.0.0/go.mod h1:IhtSnM/ZTZV8YYJWCY8RULGVqBDmpoyjwiyrjsg+URw= -cloud.google.com/go/storage v1.5.0/go.mod h1:tpKbwo567HUNpVclU5sGELwQWBDZ8gh0ZeosJ0Rtdos= -cloud.google.com/go/storage v1.6.0/go.mod h1:N7U0C8pVQ/+NIKOBQyamJIeKQKkZ+mxpohlUTyfDhBk= -cloud.google.com/go/storage v1.8.0/go.mod h1:Wv1Oy7z6Yz3DshWRJFhqM/UCfaWIRTdp0RXyy7KQOVs= -cloud.google.com/go/storage v1.10.0/go.mod h1:FLPqc6j+Ki4BU591ie1oL6qBQGu2Bl/tZ9ullr3+Kg0= -cloud.google.com/go/storage v1.14.0/go.mod h1:GrKmX003DSIwi9o29oFT7YDnHYwZoctc3fOKtUw0Xmo= -cosmossdk.io/api v0.3.2-0.20230313131911-55bf5d4efbe7 h1:4LrWK+uGP5IxznxtHHsHD+ZBs2+oZRH2loYOGjHLzZM= -cosmossdk.io/api v0.3.2-0.20230313131911-55bf5d4efbe7/go.mod h1:yVns7mKgcsG+hZW/3C5FdJtC6QYWdFIcRlKb9+5HV5g= -cosmossdk.io/collections v0.0.0-20230309163709-87da587416ba h1:S4PYij/tX3Op/hwenVEN9D+M27JRcwSwVqE3UA0BnwM= -cosmossdk.io/collections v0.0.0-20230309163709-87da587416ba/go.mod h1:lpS+G8bGC2anqzWdndTzjnQnuMO/qAcgZUkGJp4i3rc= +cosmossdk.io/api v0.4.0 h1:x90DmdidP6EhzktAa/6/IofSHidDnPjahdlrUvyQZQw= +cosmossdk.io/api v0.4.0/go.mod h1:TWDzBhUBhI1LhSf2XSYpfIBf6D4mbLu/fvzvDfhcaYM= +cosmossdk.io/collections v0.1.0 h1:nzJGeiq32KnZroSrhB6rPifw4I85Cgmzw/YAmr4luv8= +cosmossdk.io/collections v0.1.0/go.mod h1:xbauc0YsbUF8qKMVeBZl0pFCunxBIhKN/WlxpZ3lBuo= cosmossdk.io/core v0.6.1 h1:OBy7TI2W+/gyn2z40vVvruK3di+cAluinA6cybFbE7s= cosmossdk.io/core v0.6.1/go.mod h1:g3MMBCBXtxbDWBURDVnJE7XML4BG5qENhs0gzkcpuFA= cosmossdk.io/depinject v1.0.0-alpha.3 h1:6evFIgj//Y3w09bqOUOzEpFj5tsxBqdc5CfkO7z+zfw= cosmossdk.io/depinject v1.0.0-alpha.3/go.mod h1:eRbcdQ7MRpIPEM5YUJh8k97nxHpYbc3sMUnEtt8HPWU= cosmossdk.io/errors v1.0.0-beta.7 h1:gypHW76pTQGVnHKo6QBkb4yFOJjC+sUGRc5Al3Odj1w= cosmossdk.io/errors v1.0.0-beta.7/go.mod h1:mz6FQMJRku4bY7aqS/Gwfcmr/ue91roMEKAmDUDpBfE= -cosmossdk.io/log v0.1.0 h1:Vnexi+KzUCjmqq/m93teAxjt5biWFfZ5PI1imx2IJw8= -cosmossdk.io/log v0.1.0/go.mod h1:p95Wq6mDY3SREMc4y7+QU9Uwy3nyvfpWGD1iSaFkVFs= +cosmossdk.io/log v1.0.0 h1:NGKZ/A5rd4PduDfoscgABklX557PWjQINbosZy/m3Jk= +cosmossdk.io/log v1.0.0/go.mod h1:CwX9BLiBruZb7lzLlRr3R231d/fVPUXk8gAdV4LQap0= cosmossdk.io/math v1.0.0 h1:ro9w7eKx23om2tZz/VM2Pf+z2WAbGX1yDQQOJ6iGeJw= cosmossdk.io/math v1.0.0/go.mod h1:Ygz4wBHrgc7g0N+8+MrnTfS9LLn9aaTGa9hKopuym5k= -cosmossdk.io/store v0.1.0-alpha.1 h1:NGomhLUXzAxvK4OF8+yP6eNUG5i4LwzOzx+S494pTCg= -cosmossdk.io/store v0.1.0-alpha.1/go.mod h1:kmCMbhrleCZ6rDZPY/EGNldNvPebFNyVPFYp+pv05/k= -cosmossdk.io/x/tx v0.3.1-0.20230321155358-6522dd1731b5 h1:AlvyRc7f7Py1mv254vrqjIIuykCnitHIz2T+nup3bU0= -dmitri.shuralyov.com/gpu/mtl v0.0.0-20190408044501-666a987793e9/go.mod h1:H6x//7gZCb22OMCxBHrMx7a5I7Hp++hsVxbQ4BYO7hU= +cosmossdk.io/store v0.1.0-alpha.1.0.20230328185921-37ba88872dbc h1:9piuA+NYmhe+SyMPtMoboLw/djgDbrI3dD5TG020Tnk= +cosmossdk.io/store v0.1.0-alpha.1.0.20230328185921-37ba88872dbc/go.mod h1:UFF5rmjN7WYVfxo6ArdY/l1+yyWMURBWOmSJypGqFHQ= +cosmossdk.io/x/tx v0.5.1-0.20230407182919-057d2e09bd63 h1:zHqj2VwZ/MStFmR7SUe/7gErOFhL9v2rkjmWPB/st34= +cosmossdk.io/x/tx v0.5.1-0.20230407182919-057d2e09bd63/go.mod h1:Oh3Kh+IPOfMEILNxVd2e8SLqRrIjYHpdGBfDg4ghU/k= filippo.io/edwards25519 v1.0.0 h1:0wAIcmJUqRdI8IJ/3eGi5/HwXZWPujYXXlkrQogz0Ek= github.com/99designs/go-keychain v0.0.0-20191008050251-8e49817e8af4 h1:/vQbFIOMbk2FiG/kXiLl8BRyzTWDw7gX/Hz7Dd5eDMs= github.com/99designs/keyring v1.2.1 h1:tYLp1ULvO7i3fI5vE21ReQuj99QFSs7lGm0xWyJo87o= github.com/AndreasBriese/bbloom v0.0.0-20190306092124-e2d15f34fcf9/go.mod h1:bOvUY6CB00SOBii9/FifXqc0awNKxLFCL/+pkDPuyl8= github.com/BurntSushi/toml v0.3.1/go.mod h1:xHWCNGjB5oqiDr8zfno3MHue2Ht5sIBksp03qcyfWMU= -github.com/BurntSushi/xgb v0.0.0-20160522181843-27f122750802/go.mod h1:IVnqGOEym/WlBOVXweHU+Q+/VP0lqqI8lqeDx9IjBqo= github.com/ChainSafe/go-schnorrkel v0.0.0-20200405005733-88cbf1b4c40d h1:nalkkPQcITbvhmL4+C4cKA87NW0tfm3Kl9VXRoPywFg= github.com/CloudyKit/fastprinter v0.0.0-20200109182630-33d98a066a53/go.mod h1:+3IMCy2vIlbG1XG/0ggNQv0SvxCAIpPM5b1nCz56Xno= github.com/CloudyKit/jet/v3 v3.0.0/go.mod h1:HKQPgSJmdK8hdoAbKUUWajkHyHo4RaU5rMdUywE7VMo= @@ -104,7 +68,6 @@ github.com/circonus-labs/circonus-gometrics v2.3.1+incompatible/go.mod h1:nmEj6D github.com/circonus-labs/circonusllhist v0.1.3/go.mod h1:kMXHVDlOchFAehlya5ePtbp5jckzBHf4XRpQvBOLI+I= github.com/client9/misspell v0.3.4/go.mod h1:qj6jICC3Q7zFZvVWo7KLAzC3yx5G7kyvSDkc90ppPyw= github.com/cncf/udpa/go v0.0.0-20191209042840-269d4d468f6f/go.mod h1:M8M6+tZqaGXZJjfX53e64911xZQV5JYwmTeXPW+k8Sc= -github.com/cncf/udpa/go v0.0.0-20200629203442-efcf912fb354/go.mod h1:WmhPx2Nbnhtbo57+VJT5O0JRkEi1Wbu0z5j0R8u5Hbk= github.com/cncf/udpa/go v0.0.0-20201120205902-5459f2c99403/go.mod h1:WmhPx2Nbnhtbo57+VJT5O0JRkEi1Wbu0z5j0R8u5Hbk= github.com/cockroachdb/apd/v3 v3.1.0 h1:MK3Ow7LH0W8zkd5GMKA1PvS9qG3bWFI95WaVNfyZJ/w= github.com/cockroachdb/apd/v3 v3.1.0/go.mod h1:6qgPBMXjATAdD/VefbRP9NoSLKjbB4LCoA7gN4LpHs4= @@ -115,31 +78,31 @@ github.com/cockroachdb/errors v1.9.1/go.mod h1:2sxOtL2WIc096WSZqZ5h8fa17rdDq9HZO github.com/cockroachdb/logtags v0.0.0-20211118104740-dabe8e521a4f/go.mod h1:Vz9DsVWQQhf3vs21MhPMZpMGSht7O/2vFW2xusFUVOs= github.com/cockroachdb/logtags v0.0.0-20230118201751-21c54148d20b h1:r6VH0faHjZeQy818SGhaone5OnYfxFR/+AzdY3sf5aE= github.com/cockroachdb/logtags v0.0.0-20230118201751-21c54148d20b/go.mod h1:Vz9DsVWQQhf3vs21MhPMZpMGSht7O/2vFW2xusFUVOs= -github.com/cockroachdb/pebble v0.0.0-20230315223031-1e5ddd10389e h1:CDuLmyaZ1pD4OJHHtubKqgu/Byw5zAnm+gArJsyj96Q= -github.com/cockroachdb/pebble v0.0.0-20230315223031-1e5ddd10389e/go.mod h1:9lRMC4XN3/BLPtIp6kAKwIaHu369NOf2rMucPzipz50= +github.com/cockroachdb/pebble v0.0.0-20230412222916-60cfeb46143b h1:92ve6F1Pls/eqd+V+102lOMRJatgpqqsQvbT9Bl/fjg= +github.com/cockroachdb/pebble v0.0.0-20230412222916-60cfeb46143b/go.mod h1:9lRMC4XN3/BLPtIp6kAKwIaHu369NOf2rMucPzipz50= github.com/cockroachdb/redact v1.1.3 h1:AKZds10rFSIj7qADf0g46UixK8NNLwWTNdCIGS5wfSQ= github.com/cockroachdb/redact v1.1.3/go.mod h1:BVNblN9mBWFyMyqK1k3AAiSxhvhfK2oOZZ2lK+dpvRg= github.com/codegangsta/inject v0.0.0-20150114235600-33e0aa1cb7c0/go.mod h1:4Zcjuz89kmFXt9morQgcfYZAYZ5n8WHjt81YYWIwtTM= -github.com/cometbft/cometbft v0.37.0 h1:M005vBaSaugvYYmNZwJOopynQSjwLoDTwflnQ/I/eYk= -github.com/cometbft/cometbft v0.37.0/go.mod h1:Y2MMMN//O5K4YKd8ze4r9jmk4Y7h0ajqILXbH5JQFVs= +github.com/cometbft/cometbft v0.37.1-0.20230411132551-3a91d155e664 h1:BbCkbnaU3R603XpnbqvuDU8Kfv+hjhiFILOHhVFntsw= +github.com/cometbft/cometbft v0.37.1-0.20230411132551-3a91d155e664/go.mod h1:Y2MMMN//O5K4YKd8ze4r9jmk4Y7h0ajqILXbH5JQFVs= github.com/confio/ics23/go v0.9.0 h1:cWs+wdbS2KRPZezoaaj+qBleXgUk5WOQFMP3CQFGTr4= github.com/confio/ics23/go v0.9.0/go.mod h1:4LPZ2NYqnYIVRklaozjNR1FScgDJ2s5Xrp+e/mYVRak= github.com/coreos/etcd v3.3.10+incompatible/go.mod h1:uF7uidLiAD3TWHmW31ZFd/JWoc32PjwdhPthX9715RE= github.com/coreos/go-etcd v2.0.0+incompatible/go.mod h1:Jez6KQU2B/sWsbdaef3ED8NzMklzPG4d5KIOhIy30Tk= github.com/coreos/go-semver v0.2.0/go.mod h1:nnelYz7RCh+5ahJtPPxZlU+153eP4D4r3EedlOD2RNk= -github.com/coreos/go-systemd/v22 v22.3.3-0.20220203105225-a9a7ef127534/go.mod h1:Y58oyj3AT4RCenI/lSvhwexgC+NSVTIJ3seZv2GcEnc= +github.com/coreos/go-systemd/v22 v22.5.0/go.mod h1:Y58oyj3AT4RCenI/lSvhwexgC+NSVTIJ3seZv2GcEnc= github.com/cosmos/btcutil v1.0.5 h1:t+ZFcX77LpKtDBhjucvnOH8C2l2ioGsBNEQ3jef8xFk= github.com/cosmos/btcutil v1.0.5/go.mod h1:IyB7iuqZMJlthe2tkIFL33xPyzbFYP0XVdS8P5lUPis= github.com/cosmos/cosmos-db v1.0.0-rc.1 h1:SjnT8B6WKMW9WEIX32qMhnEEKcI7ZP0+G1Sa9HD3nmY= github.com/cosmos/cosmos-db v1.0.0-rc.1/go.mod h1:Dnmk3flSf5lkwCqvvjNpoxjpXzhxnCAFzKHlbaForso= github.com/cosmos/cosmos-proto v1.0.0-beta.3 h1:VitvZ1lPORTVxkmF2fAp3IiA61xVwArQYKXTdEcpW6o= github.com/cosmos/cosmos-proto v1.0.0-beta.3/go.mod h1:t8IASdLaAq+bbHbjq4p960BvcTqtwuAxid3b/2rOD6I= -github.com/cosmos/cosmos-sdk v0.46.0-beta2.0.20230321173237-fe77d4bca302 h1:wffm9LPPG/FBW/tSRdJp2DCgkJQRX+Zsbdmn4I0aWeQ= -github.com/cosmos/cosmos-sdk v0.46.0-beta2.0.20230321173237-fe77d4bca302/go.mod h1:HzOsWXtPxhO8+Y8P4Ru+G3UWx6dTkpGXU9yvT35VEuI= +github.com/cosmos/cosmos-sdk v0.46.0-beta2.0.20230418140744-0dde947d0ab7 h1:+Q/K5pdQdQjp21gIxlQgGy4dOZk9gUBSQmJCYIf1bWA= +github.com/cosmos/cosmos-sdk v0.46.0-beta2.0.20230418140744-0dde947d0ab7/go.mod h1:BPvKPN63ettXrpz67uM1rHEqX/UVVkAfceFCPyp217E= github.com/cosmos/go-bip39 v1.0.0 h1:pcomnQdrdH22njcAatO0yWojsUnCO3y2tNoV1cb6hHY= github.com/cosmos/gogogateway v1.2.0 h1:Ae/OivNhp8DqBi/sh2A8a1D0y638GpL3tkmLQAiKxTE= -github.com/cosmos/gogoproto v1.4.6 h1:Ee7z15dWJaGlgM2rWrK8N2IX7PQcuccu8oG68jp5RL4= -github.com/cosmos/gogoproto v1.4.6/go.mod h1:VS/ASYmPgv6zkPKLjR9EB91lwbLHOzaGCirmKKhncfI= +github.com/cosmos/gogoproto v1.4.8 h1:BrHKc6WFZt8+jRV71vKSQE+JrfF+JAnzrKo2VP7wIZ4= +github.com/cosmos/gogoproto v1.4.8/go.mod h1:hnb0DIEWTv+wdNzNcqus5xCQXq5+CXauq1FJuurRfVY= github.com/cosmos/iavl v0.21.0-beta.1 h1:fBQeBc8HLZ14plJNcmGfaOXSSMLVEHvEQXiTXSD76m0= github.com/cosmos/ledger-cosmos-go v0.13.0 h1:ex0CvCxToSR7j5WjrghPu2Bu9sSXKikjnVvUryNnx4s= github.com/cpuguy83/go-md2man v1.0.10/go.mod h1:SmD6nW6nTyfqj6ABTjUi3V3JVMnlJmwcJI5acqYI6dE= @@ -153,9 +116,9 @@ github.com/danieljoos/wincred v1.1.2 h1:QLdCxFs1/Yl4zduvBdcHB8goaYk9RARS2SgLLRuA github.com/davecgh/go-spew v1.1.0/go.mod h1:J7Y8YcW2NihsgmVo/mv3lAwl/skON4iLHjSsI+c5H38= github.com/davecgh/go-spew v1.1.1 h1:vj9j/u1bqnvCEfJOwUhtlOARqs3+rkHYY13jYWTU97c= github.com/davecgh/go-spew v1.1.1/go.mod h1:J7Y8YcW2NihsgmVo/mv3lAwl/skON4iLHjSsI+c5H38= -github.com/decred/dcrd/crypto/blake256 v1.0.0 h1:/8DMNYp9SGi5f0w7uCm6d6M4OU2rGFK09Y2A4Xv7EE0= -github.com/decred/dcrd/dcrec/secp256k1/v4 v4.1.0 h1:HbphB4TFFXpv7MNrT52FGrrgVXF1owhMVTHFZIlnvd4= -github.com/decred/dcrd/dcrec/secp256k1/v4 v4.1.0/go.mod h1:DZGJHZMqrU4JJqFAWUS2UO1+lbSKsdiOoYi9Zzey7Fc= +github.com/decred/dcrd/crypto/blake256 v1.0.1 h1:7PltbUIQB7u/FfZ39+DGa/ShuMyJ5ilcvdfma9wOH6Y= +github.com/decred/dcrd/dcrec/secp256k1/v4 v4.2.0 h1:8UrgZ3GkP4i/CLijOJx79Yu+etlyjdBU4sfcs2WYQMs= +github.com/decred/dcrd/dcrec/secp256k1/v4 v4.2.0/go.mod h1:v57UDF4pDQJcEfFUCRop3lJL149eHGSe9Jvczhzjo/0= github.com/desertbit/timer v0.0.0-20180107155436-c41aec40b27f h1:U5y3Y5UE0w7amNe7Z5G/twsBW0KEalRQXZzf8ufSh9I= github.com/dgraph-io/badger v1.6.0/go.mod h1:zwt7syl517jmP8s94KqSxTlM6IMsdhYy6psNgSztDR4= github.com/dgryski/go-farm v0.0.0-20190423205320-6a90982ecee2/go.mod h1:SqUrOPUnsFjfmXRMNPybcSiG0BgUW2AuFH8PAnS2iTw= @@ -165,8 +128,6 @@ github.com/eknkc/amber v0.0.0-20171010120322-cdade1c07385/go.mod h1:0vRUJqYpeSZi github.com/envoyproxy/go-control-plane v0.9.0/go.mod h1:YTl/9mNaCwkRvm6d1a2C3ymFceY/DCBVvsKhRF0iEA4= github.com/envoyproxy/go-control-plane v0.9.1-0.20191026205805-5f8ba28d4473/go.mod h1:YTl/9mNaCwkRvm6d1a2C3ymFceY/DCBVvsKhRF0iEA4= github.com/envoyproxy/go-control-plane v0.9.4/go.mod h1:6rpuAdCZL397s3pYoYcLgu1mIlRU8Am5FuJP05cCM98= -github.com/envoyproxy/go-control-plane v0.9.7/go.mod h1:cwu0lG7PUMfa9snN8LXBig5ynNVH9qI8YYLbd1fK2po= -github.com/envoyproxy/go-control-plane v0.9.9-0.20201210154907-fd9021fe5dad/go.mod h1:cXg6YxExXjJnVBQHBLXeUAgxn2UodCpnH306RInaBQk= github.com/envoyproxy/go-control-plane v0.9.9-0.20210217033140-668b12f5399d/go.mod h1:cXg6YxExXjJnVBQHBLXeUAgxn2UodCpnH306RInaBQk= github.com/envoyproxy/protoc-gen-validate v0.1.0/go.mod h1:iSmxcyjqTsJpI2R4NaDN7+kN2VEUnK/pcBlmesArF7c= github.com/etcd-io/bbolt v1.3.3/go.mod h1:ZF2nL25h33cCyBtcyWeZ2/I3HQOfTP+0PIEvHjkjCrw= @@ -180,20 +141,16 @@ github.com/fsnotify/fsnotify v1.4.7/go.mod h1:jwhsz4b93w/PPRr/qN1Yymfu8t87LnFCMo github.com/fsnotify/fsnotify v1.4.9/go.mod h1:znqG4EE+3YCdAaPaxE2ZRY/06pZUdp0tY4IgpuI1SZQ= github.com/fsnotify/fsnotify v1.5.4/go.mod h1:OVB6XrOHzAwXMpEM7uPOzcehqUV2UqJxmVXmkdnm1bU= github.com/fsnotify/fsnotify v1.6.0 h1:n+5WquG0fcWoWp6xPWfHdbskMCQaFnG6PfBrh1Ky4HY= -github.com/fsnotify/fsnotify v1.6.0/go.mod h1:sl3t1tCWJFWoRz9R8WJCbQihKKwmorjAbSClcnxKAGw= github.com/gavv/httpexpect v2.0.0+incompatible/go.mod h1:x+9tiU1YnrOvnB725RkpoLv1M62hOWzwo5OXotisrKc= github.com/getsentry/sentry-go v0.12.0/go.mod h1:NSap0JBYWzHND8oMbyi0+XZhUalc1TBdRL1M71JZW2c= -github.com/getsentry/sentry-go v0.19.0 h1:BcCH3CN5tXt5aML+gwmbFwVptLLQA+eT866fCO9wVOM= -github.com/getsentry/sentry-go v0.19.0/go.mod h1:y3+lGEFEFexZtpbG1GUE2WD/f9zGyKYwpEqryTOC/nE= +github.com/getsentry/sentry-go v0.20.0 h1:bwXW98iMRIWxn+4FgPW7vMrjmbym6HblXALmhjHmQaQ= +github.com/getsentry/sentry-go v0.20.0/go.mod h1:lc76E2QywIyW8WuBnwl8Lc4bkmQH4+w1gwTf25trprY= github.com/ghodss/yaml v1.0.0/go.mod h1:4dBDuWmgqj2HViK6kFavaiC9ZROes6MMH2rRYeMEF04= github.com/gin-contrib/sse v0.0.0-20190301062529-5545eab6dad3/go.mod h1:VJ0WA2NBN22VlZ2dKZQPAPnyWw5XTlK1KymzLKsr59s= github.com/gin-gonic/gin v1.4.0/go.mod h1:OW2EZn3DO8Ln9oIKOvM++LBO+5UPHJJDH72/q/3rZdM= github.com/go-check/check v0.0.0-20180628173108-788fd7840127/go.mod h1:9ES+weclKsC9YodN5RgxqK/VD9HM9JsCSh7rNhMZE98= github.com/go-errors/errors v1.0.1/go.mod h1:f4zRHt4oKfwPJE5k8C9vpYG+aDHdBFUsgrm6/TyX73Q= github.com/go-errors/errors v1.4.2 h1:J6MZopCL4uSllY1OfXM374weqZFFItUbrImctkmUxIA= -github.com/go-gl/glfw v0.0.0-20190409004039-e6da0acd62b1/go.mod h1:vR7hzQXu2zJy9AVAgeJqvqgH9Q5CA+iKCZ2gyEVpxRU= -github.com/go-gl/glfw/v3.3/glfw v0.0.0-20191125211704-12ad95a8df72/go.mod h1:tQ2UAYgL5IevRw8kRxooKSPJfGvJ9fJQFa0TUsXzTg8= -github.com/go-gl/glfw/v3.3/glfw v0.0.0-20200222043503-6f7a984d4dc4/go.mod h1:tQ2UAYgL5IevRw8kRxooKSPJfGvJ9fJQFa0TUsXzTg8= github.com/go-kit/kit v0.8.0/go.mod h1:xBxKIO96dXMWWy0MnWVtmwkA9/13aqxPnvrjFYMA2as= github.com/go-kit/kit v0.9.0/go.mod h1:xBxKIO96dXMWWy0MnWVtmwkA9/13aqxPnvrjFYMA2as= github.com/go-kit/kit v0.12.0 h1:e4o3o3IsBfAKQh5Qbbiqyfu97Ku7jrO/JbohvztANh4= @@ -225,23 +182,13 @@ github.com/gogo/protobuf v1.3.2/go.mod h1:P1XiOD3dCwIKUDQYPy72D8LYyHL2YPYrpS2s69 github.com/gogo/status v1.1.0/go.mod h1:BFv9nrluPLmrS0EmGVvLaPNmRosr9KapBYd5/hpY1WM= github.com/golang-jwt/jwt v3.2.2+incompatible/go.mod h1:8pz2t5EyA70fFQQSrl6XZXzqecmYZeUEB8OUGHkxJ+I= github.com/golang/glog v0.0.0-20160126235308-23def4e6c14b/go.mod h1:SBH7ygxi8pfUlaOkMMuAQtPIUF8ecWP5IEl/CR7VP2Q= -github.com/golang/groupcache v0.0.0-20190702054246-869f871628b6/go.mod h1:cIg4eruTrX1D+g88fzRXU5OdNfaM+9IcxsU14FzY7Hc= -github.com/golang/groupcache v0.0.0-20191227052852-215e87163ea7/go.mod h1:cIg4eruTrX1D+g88fzRXU5OdNfaM+9IcxsU14FzY7Hc= -github.com/golang/groupcache v0.0.0-20200121045136-8c9f03a8e57e/go.mod h1:cIg4eruTrX1D+g88fzRXU5OdNfaM+9IcxsU14FzY7Hc= github.com/golang/mock v1.1.1/go.mod h1:oTYuIxOrZwtPieC+H1uAHpcLFnEyAGVDL/k47Jfbm0A= -github.com/golang/mock v1.2.0/go.mod h1:oTYuIxOrZwtPieC+H1uAHpcLFnEyAGVDL/k47Jfbm0A= -github.com/golang/mock v1.3.1/go.mod h1:sBzyDLLjw3U8JLTeZvSv8jJB+tU5PVekmnlKIyFUx0Y= -github.com/golang/mock v1.4.0/go.mod h1:UOMv5ysSaYNkG+OFQykRIcU/QvvxJf3p21QfJ2Bt3cw= -github.com/golang/mock v1.4.1/go.mod h1:UOMv5ysSaYNkG+OFQykRIcU/QvvxJf3p21QfJ2Bt3cw= -github.com/golang/mock v1.4.3/go.mod h1:UOMv5ysSaYNkG+OFQykRIcU/QvvxJf3p21QfJ2Bt3cw= -github.com/golang/mock v1.4.4/go.mod h1:l3mdAwkq5BuhzHwde/uurv3sEJeZMXNpwsxVWU71h+4= github.com/golang/mock v1.6.0 h1:ErTB+efbowRARo13NNdxyJji2egdxLGQhRaY+DUumQc= github.com/golang/protobuf v1.2.0/go.mod h1:6lQm79b+lXiMfvg/cZm0SGofjICqVBUtrP5yJMmIC1U= github.com/golang/protobuf v1.3.0/go.mod h1:Qd/q+1AKNOZr9uGQzbzCmRO6sUih6GTPZv6a1/R87v0= github.com/golang/protobuf v1.3.1/go.mod h1:6lQm79b+lXiMfvg/cZm0SGofjICqVBUtrP5yJMmIC1U= github.com/golang/protobuf v1.3.2/go.mod h1:6lQm79b+lXiMfvg/cZm0SGofjICqVBUtrP5yJMmIC1U= github.com/golang/protobuf v1.3.3/go.mod h1:vzj43D7+SQXF/4pzW/hwtAqwc6iTitCiVSaWz5lYuqw= -github.com/golang/protobuf v1.3.4/go.mod h1:vzj43D7+SQXF/4pzW/hwtAqwc6iTitCiVSaWz5lYuqw= github.com/golang/protobuf v1.3.5/go.mod h1:6O5/vntMXwX2lRkT1hjjk0nAC1IDOTvTlVgjlRvqsdk= github.com/golang/protobuf v1.4.0-rc.1/go.mod h1:ceaxUfeHdC40wWswd/P6IGgMaK3YpKi5j83Wpe3EHw8= github.com/golang/protobuf v1.4.0-rc.1.0.20200221234624-67d41d38c208/go.mod h1:xKAWHe0F5eneWXFV3EuXVDTCmh+JuBKY0li0aMyXATA= @@ -250,7 +197,6 @@ github.com/golang/protobuf v1.4.0-rc.4.0.20200313231945-b860323f09d0/go.mod h1:W github.com/golang/protobuf v1.4.0/go.mod h1:jodUvKwWbYaEsadDk5Fwe5c77LiNKVO9IDvqG2KuDX0= github.com/golang/protobuf v1.4.1/go.mod h1:U8fpvMrcmy5pZrNK1lt4xCsGvpyWQ/VVv6QDs8UjoX8= github.com/golang/protobuf v1.4.2/go.mod h1:oDoupMAO8OvCJWAcko0GGGIgR6R6ocIYbsSw735rRwI= -github.com/golang/protobuf v1.4.3/go.mod h1:oDoupMAO8OvCJWAcko0GGGIgR6R6ocIYbsSw735rRwI= github.com/golang/protobuf v1.5.0/go.mod h1:FsONVRAS9T7sI+LIUmWTfcYkHO4aIWwzhcaSAoJOfIk= github.com/golang/protobuf v1.5.2/go.mod h1:XVQd3VNwM+JqD3oG2Ue2ip4fOMUkwXdXDdiuN0vRsmY= github.com/golang/protobuf v1.5.3 h1:KhyjKVUg7Usr/dYsdSqoFveMYd5ko72D+zANwlG1mmg= @@ -258,19 +204,13 @@ github.com/golang/protobuf v1.5.3/go.mod h1:XVQd3VNwM+JqD3oG2Ue2ip4fOMUkwXdXDdiu github.com/golang/snappy v0.0.4 h1:yAGX7huGHXlcLOEtBnF4w7FQwA26wojNCwOYAEhLjQM= github.com/golang/snappy v0.0.4/go.mod h1:/XxbfmMg8lxefKM7IXC3fBNl/7bRcc72aCRzEWrmP2Q= github.com/gomodule/redigo v1.7.1-0.20190724094224-574c33c3df38/go.mod h1:B4C85qUVwatsJoIUNIfCRsp7qO0iAmpGFZ4EELWSbC4= -github.com/google/btree v0.0.0-20180813153112-4030bb1f1f0c/go.mod h1:lNA+9X1NB3Zf8V7Ke586lFgjr2dZNuvo3lPJSGZ5JPQ= -github.com/google/btree v1.0.0/go.mod h1:lNA+9X1NB3Zf8V7Ke586lFgjr2dZNuvo3lPJSGZ5JPQ= github.com/google/btree v1.1.2 h1:xf4v41cLI2Z6FxbKm+8Bu+m8ifhj15JuZ9sa0jZCMUU= github.com/google/btree v1.1.2/go.mod h1:qOPhT0dTNdNzV6Z/lhRX0YXUafgPLFUh+gZMl761Gm4= github.com/google/go-cmp v0.2.0/go.mod h1:oXzfMopK8JAjlY9xF4vHSVASa0yLyX7SntLO5aqRK0M= github.com/google/go-cmp v0.3.0/go.mod h1:8QqcDgzrUqlUb/G2PQTWiueGozuR1884gddMywk6iLU= github.com/google/go-cmp v0.3.1/go.mod h1:8QqcDgzrUqlUb/G2PQTWiueGozuR1884gddMywk6iLU= github.com/google/go-cmp v0.4.0/go.mod h1:v8dTdLbMG2kIc/vJvl+f65V22dbkXbowE6jgT/gNBxE= -github.com/google/go-cmp v0.4.1/go.mod h1:v8dTdLbMG2kIc/vJvl+f65V22dbkXbowE6jgT/gNBxE= github.com/google/go-cmp v0.5.0/go.mod h1:v8dTdLbMG2kIc/vJvl+f65V22dbkXbowE6jgT/gNBxE= -github.com/google/go-cmp v0.5.1/go.mod h1:v8dTdLbMG2kIc/vJvl+f65V22dbkXbowE6jgT/gNBxE= -github.com/google/go-cmp v0.5.2/go.mod h1:v8dTdLbMG2kIc/vJvl+f65V22dbkXbowE6jgT/gNBxE= -github.com/google/go-cmp v0.5.4/go.mod h1:v8dTdLbMG2kIc/vJvl+f65V22dbkXbowE6jgT/gNBxE= github.com/google/go-cmp v0.5.5/go.mod h1:v8dTdLbMG2kIc/vJvl+f65V22dbkXbowE6jgT/gNBxE= github.com/google/go-cmp v0.5.9 h1:O2Tfq5qg4qc4AmwVlvv0oLiVAGB7enBSJ2x2DqQFi38= github.com/google/go-cmp v0.5.9/go.mod h1:17dUlkBOakJ0+DkrSSNjCkIjxS6bF9zb3elmeNGIjoY= @@ -278,25 +218,8 @@ github.com/google/go-querystring v1.0.0/go.mod h1:odCYkC5MyYFN7vkCjXpyrEuKhc/BUO github.com/google/gofuzz v0.0.0-20170612174753-24818f796faf/go.mod h1:HP5RmnzzSNb993RKQDq4+1A4ia9nllfqcQFTQJedwGI= github.com/google/gofuzz v1.0.0/go.mod h1:dBl0BpW6vV/+mYPU4Po3pmUjxk6FQPldtuIdl/M65Eg= github.com/google/gofuzz v1.2.0 h1:xRy4A+RhZaiKjJ1bPfwQ8sedCA+YS2YcCHW6ec7JMi0= -github.com/google/martian v2.1.0+incompatible/go.mod h1:9I4somxYTbIHy5NJKHRl3wXiIaQGbYVAs8BPL6v8lEs= -github.com/google/martian/v3 v3.0.0/go.mod h1:y5Zk1BBys9G+gd6Jrk0W3cC1+ELVxBWuIGO+w/tUAp0= -github.com/google/martian/v3 v3.1.0/go.mod h1:y5Zk1BBys9G+gd6Jrk0W3cC1+ELVxBWuIGO+w/tUAp0= -github.com/google/pprof v0.0.0-20181206194817-3ea8567a2e57/go.mod h1:zfwlbNMJ+OItoe0UupaVj+oy1omPYYDuagoSzA8v9mc= -github.com/google/pprof v0.0.0-20190515194954-54271f7e092f/go.mod h1:zfwlbNMJ+OItoe0UupaVj+oy1omPYYDuagoSzA8v9mc= -github.com/google/pprof v0.0.0-20191218002539-d4f498aebedc/go.mod h1:ZgVRPoUq/hfqzAqh7sHMqb3I9Rq5C59dIz2SbBwJ4eM= -github.com/google/pprof v0.0.0-20200212024743-f11f1df84d12/go.mod h1:ZgVRPoUq/hfqzAqh7sHMqb3I9Rq5C59dIz2SbBwJ4eM= -github.com/google/pprof v0.0.0-20200229191704-1ebb73c60ed3/go.mod h1:ZgVRPoUq/hfqzAqh7sHMqb3I9Rq5C59dIz2SbBwJ4eM= -github.com/google/pprof v0.0.0-20200430221834-fc25d7d30c6d/go.mod h1:ZgVRPoUq/hfqzAqh7sHMqb3I9Rq5C59dIz2SbBwJ4eM= -github.com/google/pprof v0.0.0-20200708004538-1a94d8640e99/go.mod h1:ZgVRPoUq/hfqzAqh7sHMqb3I9Rq5C59dIz2SbBwJ4eM= -github.com/google/pprof v0.0.0-20201023163331-3e6fc7fc9c4c/go.mod h1:kpwsk12EmLew5upagYY7GY0pfYCcupk39gWOCRROcvE= -github.com/google/pprof v0.0.0-20201203190320-1bf35d6f28c2/go.mod h1:kpwsk12EmLew5upagYY7GY0pfYCcupk39gWOCRROcvE= -github.com/google/pprof v0.0.0-20201218002935-b9804c9f04c2/go.mod h1:kpwsk12EmLew5upagYY7GY0pfYCcupk39gWOCRROcvE= github.com/google/pprof v0.0.0-20210407192527-94a9f03dee38/go.mod h1:kpwsk12EmLew5upagYY7GY0pfYCcupk39gWOCRROcvE= -github.com/google/renameio v0.1.0/go.mod h1:KWCgfxg9yswjAJkECMjeO8J8rahYeXnNhOm40UhjYkI= github.com/google/uuid v1.1.2/go.mod h1:TIyPZe4MgqvfeYDBFedMoGGpEw/LqOeaOT+nhxU+yHo= -github.com/googleapis/gax-go/v2 v2.0.4/go.mod h1:0Wqv26UfaUD9n4G6kQubkQ+KchISgw+vpHVxEJEs9eg= -github.com/googleapis/gax-go/v2 v2.0.5/go.mod h1:DWXyrwAJ9X0FpwwEdw+IPEYBICEFu5mhpdKc/us6bOk= -github.com/googleapis/google-cloud-go-testing v0.0.0-20200911160855-bcd43fbb19e8/go.mod h1:dvDLG8qkwmyD9a/MJJN3XJcT3xFxOKAvTZGvuZmac9g= github.com/gopherjs/gopherjs v0.0.0-20181017120253-0766667cb4d1/go.mod h1:wJfORRmW1u3UXTncJ5qlYoELFm8eSnnEO6hX4iZ3EWY= github.com/gorilla/handlers v1.5.1 h1:9lRY6j8DEeeBT10CvO9hGW0gmky0BprnvDI5vfhUHH4= github.com/gorilla/mux v1.8.0 h1:i40aqfkR1h2SlN9hojwV5ZA91wcXFOvkdNIeFDP5koI= @@ -320,7 +243,6 @@ github.com/hashicorp/go-uuid v1.0.0/go.mod h1:6SBZvOh/SIDV7/2o3Jml5SYk/TvGqwFJ/b github.com/hashicorp/go-uuid v1.0.1 h1:fv1ep09latC32wFoVwnqcnKJGnMSdBanPczbHAYm1BE= github.com/hashicorp/go-version v1.2.0/go.mod h1:fltr4n8CU8Ke44wwGCBoEymUuxUHl09ZGVZPK5anwXA= github.com/hashicorp/golang-lru v0.5.0/go.mod h1:/m3WP610KZHVQ1SGc6re/UDhFvYD7pJ4Ao+sR/qLZy8= -github.com/hashicorp/golang-lru v0.5.1/go.mod h1:/m3WP610KZHVQ1SGc6re/UDhFvYD7pJ4Ao+sR/qLZy8= github.com/hashicorp/golang-lru v0.5.5-0.20210104140557-80c98217689d h1:dg1dEPuWpEqDnvIw251EVy4zlP8gWbsGj4BsUKCRpYs= github.com/hashicorp/golang-lru v0.5.5-0.20210104140557-80c98217689d/go.mod h1:iADmTwqILo4mZ8BN3D2Q6+9jd8WM5uGBxy+E8yxSoD4= github.com/hashicorp/hcl v1.0.0 h1:0Anlzjpi4vEasTeNFn2mLJgTSwt0+6sfsiTG8qcWGx4= @@ -330,12 +252,10 @@ github.com/hdevalence/ed25519consensus v0.1.0 h1:jtBwzzcHuTmFrQN6xQZn6CQEO/V9f7H github.com/hpcloud/tail v1.0.0/go.mod h1:ab1qPbhIpdTxEkNHXyeSf5vhxWSCs/tWer42PpOxQnU= github.com/huandu/skiplist v1.2.0 h1:gox56QD77HzSC0w+Ws3MH3iie755GBJU1OER3h5VsYw= github.com/hydrogen18/memlistener v0.0.0-20200120041712-dcc25e7acd91/go.mod h1:qEIFzExnS6016fRpRfxrExeVn2gbClQA99gQhnIcdhE= -github.com/ianlancetaylor/demangle v0.0.0-20181102032728-5e5cf60278f6/go.mod h1:aSSvb/t6k1mPoxDqO4vJh6VOCGPwU4O0C2/Eqndh1Sc= github.com/ianlancetaylor/demangle v0.0.0-20200824232613-28f6c0f3b639/go.mod h1:aSSvb/t6k1mPoxDqO4vJh6VOCGPwU4O0C2/Eqndh1Sc= github.com/imkira/go-interpol v1.1.0/go.mod h1:z0h2/2T3XF8kyEPpRgJ3kmNv+C43p+I/CoI+jC3w2iA= github.com/improbable-eng/grpc-web v0.15.0 h1:BN+7z6uNXZ1tQGcNAuaU1YjsLTApzkjt2tzCixLaUPQ= github.com/inconshreveable/mousetrap v1.0.0/go.mod h1:PxqpIevigyE2G7u3NXJIT2ANytuPF1OarO4DADm73n8= -github.com/inconshreveable/mousetrap v1.0.1/go.mod h1:vpF70FUmC8bwa3OWnCshd2FqLfsEA9PFc4w1p2J65bw= github.com/inconshreveable/mousetrap v1.1.0 h1:wN+x4NVGpMsO7ErUn/mUI3vEoE6Jt13X2s0bqwp9tc8= github.com/inconshreveable/mousetrap v1.1.0/go.mod h1:vpF70FUmC8bwa3OWnCshd2FqLfsEA9PFc4w1p2J65bw= github.com/iris-contrib/blackfriday v2.0.0+incompatible/go.mod h1:UzZ2bDEoaSGPbkg6SAB4att1aAwTmVIx/5gCVqeyUdI= @@ -345,8 +265,6 @@ github.com/iris-contrib/pongo2 v0.0.1/go.mod h1:Ssh+00+3GAZqSQb30AvBRNxBx7rf0Gqw github.com/iris-contrib/schema v0.0.1/go.mod h1:urYA3uvUNG1TIIjOSCzHr9/LmbQo8LrOcOqfqxa4hXw= github.com/json-iterator/go v1.1.6/go.mod h1:+SdeFBvtyEkXs7REEP0seUULqWtbJapLOCVDaaPEHmU= github.com/json-iterator/go v1.1.9/go.mod h1:KdQUCv79m/52Kvf8AW2vK1V8akMuk1QjK/uOdHXbAo4= -github.com/jstemmer/go-junit-report v0.0.0-20190106144839-af01ea7f8024/go.mod h1:6v2b51hI/fHJwM22ozAgKL4VKDeJcHhJFhtBdhmNjmU= -github.com/jstemmer/go-junit-report v0.9.1/go.mod h1:Brl9GWCQeLvo8nXZwPNNblvFj/XSXhF0NWZEnDohbsk= github.com/jtolds/gls v4.20.0+incompatible/go.mod h1:QJZ7F/aHp+rZTRtaJ1ow/lLfFfVYBRgL+9YlvaHOwJU= github.com/julienschmidt/httprouter v1.2.0/go.mod h1:SYymIcj16QtmaHHD7aYtjjsJG7VTCxuUUipMqKk8s4w= github.com/k0kubun/colorstring v0.0.0-20150214042306-9440f1994b88/go.mod h1:3w7q1U84EfirKl04SVQ/s7nPm1ZPhiXd34z40TNz36k= @@ -359,11 +277,10 @@ github.com/kisielk/errcheck v1.5.0/go.mod h1:pFxgyoBC7bSaBwPgfKdkLd5X25qrDl4LWUI github.com/kisielk/gotool v1.0.0/go.mod h1:XhKaO+MFFWcvkIS/tQcRk01m1F5IRFswLeQ+oQHNcck= github.com/klauspost/compress v1.8.2/go.mod h1:RyIbtBH6LamlWaDj8nUwkbUhJ87Yi3uG0guNDohfE1A= github.com/klauspost/compress v1.9.7/go.mod h1:RyIbtBH6LamlWaDj8nUwkbUhJ87Yi3uG0guNDohfE1A= -github.com/klauspost/compress v1.16.3 h1:XuJt9zzcnaz6a16/OU53ZjWp/v7/42WcR5t2a0PcNQY= -github.com/klauspost/compress v1.16.3/go.mod h1:ntbaceVETuRiXiv4DpjP66DpAtAGkEQskQzEyD//IeE= +github.com/klauspost/compress v1.16.5 h1:IFV2oUNUzZaz+XyusxpLzpzS8Pt5rh0Z16For/djlyI= +github.com/klauspost/compress v1.16.5/go.mod h1:ntbaceVETuRiXiv4DpjP66DpAtAGkEQskQzEyD//IeE= github.com/klauspost/cpuid v1.2.1/go.mod h1:Pj4uuM528wm8OyEC2QMXAi2YiTZ96dNQPGgoMS4s3ek= github.com/konsorten/go-windows-terminal-sequences v1.0.1/go.mod h1:T0+1ngSBFLxvqU3pZ+m/2kptfBszLMUkC4ZK/EgS/cQ= -github.com/kr/fs v0.1.0/go.mod h1:FFnZGqtBN9Gxj7eW1uZ42v5BccTP0vu6NEaFoC2HwRg= github.com/kr/logfmt v0.0.0-20140226030751-b84e30acd515/go.mod h1:+0opPa2QZZtGFBFZlji/RkVcI2GknAs/DXo4wKdlNEc= github.com/kr/pretty v0.1.0/go.mod h1:dAy3ld7l9f0ibDNOQOHHMYYIIbhfbHSm3C4ZsoJORNo= github.com/kr/pretty v0.3.0/go.mod h1:640gp4NfQd8pI5XOwp5fnNeVWj67G7CFk/SaSQn7NBk= @@ -378,11 +295,10 @@ github.com/labstack/gommon v0.3.0/go.mod h1:MULnywXg0yavhxWKc+lOruYdAhDwPK9wf0OL github.com/lib/pq v1.10.7 h1:p7ZhMD+KsSRozJr34udlUrhboJwWAgCg34+/ZZNvZZw= github.com/libp2p/go-buffer-pool v0.1.0 h1:oK4mSFcQz7cTQIfqbe4MIj9gLW+mnanjyFtc6cdF0Y8= github.com/libp2p/go-buffer-pool v0.1.0/go.mod h1:N+vh8gMqimBzdKkSMVuydVDq+UV5QTWy5HSiZacSbPg= -github.com/linxGnu/grocksdb v1.7.15 h1:AEhP28lkeAybv5UYNYviYISpR6bJejEnKuYbnWAnxx0= -github.com/linxGnu/grocksdb v1.7.15/go.mod h1:pY55D0o+r8yUYLq70QmhdudxYvoDb9F+9puf4m3/W+U= +github.com/linxGnu/grocksdb v1.7.16 h1:Q2co1xrpdkr5Hx3Fp+f+f7fRGhQFQhvi/+226dtLmA8= +github.com/linxGnu/grocksdb v1.7.16/go.mod h1:JkS7pl5qWpGpuVb3bPqTz8nC12X3YtPZT+Xq7+QfQo4= github.com/magiconair/properties v1.8.0/go.mod h1:PppfXfuXeibc/6YijjN8zIbojt8czPbwD3XqdrwzmxQ= github.com/magiconair/properties v1.8.7 h1:IeQXZAiQcpL9mgcAe1Nu6cX9LLw6ExEHKjN0VQdvPDY= -github.com/magiconair/properties v1.8.7/go.mod h1:Dhd985XPs7jluiymwWYZ0G4Z61jb3vdS329zhj2hYo0= github.com/mattn/go-colorable v0.1.2/go.mod h1:U0ppj6V5qS13XJ6of8GYAs25YV2eR4EVcfRqFIhoBtE= github.com/mattn/go-colorable v0.1.8/go.mod h1:u6P/XSegPjTcexA+o6vUJrdnUu04hMope9wVRipJSqc= github.com/mattn/go-colorable v0.1.11/go.mod h1:u5H1YNBxpqRaxsYJYSkiCWKzEfiAb1Gb520KVy5xxl4= @@ -410,7 +326,6 @@ github.com/mitchellh/go-homedir v1.1.0/go.mod h1:SfyaCUpYCn1Vlf4IUYiD9fPX4A5wJrk github.com/mitchellh/go-testing-interface v1.14.1 h1:jrgshOhYAUVNMAJiKbEu7EqAwgJJ2JqpQmpLJOu07cU= github.com/mitchellh/mapstructure v1.1.2/go.mod h1:FVVH3fgwuzCH5S8UJGiWEs2h04kUh9fWfEaFds41c1Y= github.com/mitchellh/mapstructure v1.5.0 h1:jeMsZIYE/09sWLaz43PL7Gy6RuMjD2eJVyuac5Z2hdY= -github.com/mitchellh/mapstructure v1.5.0/go.mod h1:bFUtVrKA4DC2yAKiSyO/QUcy7e+RRV2QTWOzhPopBRo= github.com/modern-go/concurrent v0.0.0-20180228061459-e0a39a4cb421/go.mod h1:6dJC0mAP4ikYIbvyc7fijjWJddQyLn8Ig3JB5CqoB9Q= github.com/modern-go/concurrent v0.0.0-20180306012644-bacd9c7ef1dd/go.mod h1:6dJC0mAP4ikYIbvyc7fijjWJddQyLn8Ig3JB5CqoB9Q= github.com/modern-go/reflect2 v0.0.0-20180701023420-4b7aa43c6742/go.mod h1:bx2lNnkwVCuqBIxFjflWJWanXIb3RllmbCylyMrvgv0= @@ -441,8 +356,8 @@ github.com/onsi/gomega v1.20.0 h1:8W0cWlwFkflGPLltQvLRB7ZVD5HuP6ng320w2IS245Q= github.com/pascaldekloe/goe v0.1.0 h1:cBOtyMzM9HTpWjXfbbunk26uA6nG3a8n06Wieeh0MwY= github.com/pascaldekloe/goe v0.1.0/go.mod h1:lzWF7FIEvWOWxwDKqyGYQf6ZUaNfKdP144TG7ZOy1lc= github.com/pelletier/go-toml v1.2.0/go.mod h1:5z9KED0ma1S8pY6P1sdut58dfprrGBbd/94hg7ilaic= +github.com/pelletier/go-toml v1.9.5 h1:4yBQzkHv+7BHq2PQUZF3Mx0IYxG7LsP222s7Agd3ve8= github.com/pelletier/go-toml/v2 v2.0.7 h1:muncTPStnKRos5dpVKULv2FVd4bMOhNePj9CjgDb8Us= -github.com/pelletier/go-toml/v2 v2.0.7/go.mod h1:eumQOmlWiOPt5WriQQqoM5y18pDHwha2N+QD+EUNTek= github.com/petermattis/goid v0.0.0-20180202154549-b0b1615b78e5/go.mod h1:jvVRKCrJTQWu0XVbaOlby/2lO20uSCHEMzzplHXte1o= github.com/petermattis/goid v0.0.0-20230317030725-371a4b8eda08 h1:hDSdbBuw3Lefr6R18ax0tZ2BJeNB3NehB3trOwYBsdU= github.com/petermattis/goid v0.0.0-20230317030725-371a4b8eda08/go.mod h1:pxMtw7cyUw6B2bRH0ZBANSPg+AoSud1I1iyJHI69jH4= @@ -453,14 +368,13 @@ github.com/pkg/errors v0.8.0/go.mod h1:bwawxfHBFNV+L2hUp1rHADufV3IMtnDRdf1r5NINE github.com/pkg/errors v0.8.1/go.mod h1:bwawxfHBFNV+L2hUp1rHADufV3IMtnDRdf1r5NINEl0= github.com/pkg/errors v0.9.1 h1:FEBLx1zS214owpjy7qsBeixbURkuhQAwrK5UwLGTwt4= github.com/pkg/errors v0.9.1/go.mod h1:bwawxfHBFNV+L2hUp1rHADufV3IMtnDRdf1r5NINEl0= -github.com/pkg/sftp v1.13.1/go.mod h1:3HaPG6Dq1ILlpPZRO0HVMrsydcdLt6HRDccSgb87qRg= github.com/pmezard/go-difflib v1.0.0 h1:4DBwDE0NGyQoBHbLQYPwSUPoCMWR5BEzIk/f1lZbAQM= github.com/pmezard/go-difflib v1.0.0/go.mod h1:iKH77koFhYxTK1pcRnkKkqfTogsbg7gZNVY4sRDYZ/4= github.com/prometheus/client_golang v0.9.1/go.mod h1:7SWBe2y4D6OKWSNQJUaRYU/AaXPKyh/dDVn+NZz0KFw= github.com/prometheus/client_golang v1.0.0/go.mod h1:db9x61etRT2tGnBNRi70OPL5FsnadC4Ky3P0J6CfImo= github.com/prometheus/client_golang v1.4.0/go.mod h1:e9GMxYsXl05ICDXkRhurwBS4Q3OK1iX/F2sw+iXX5zU= -github.com/prometheus/client_golang v1.14.0 h1:nJdhIvne2eSX/XRAFV9PcvFFRbrjbcTUj0VP62TMhnw= -github.com/prometheus/client_golang v1.14.0/go.mod h1:8vpkKitgIVNcqrRBWh1C4TIUQgYNtG/XQE4E/Zae36Y= +github.com/prometheus/client_golang v1.15.0 h1:5fCgGYogn0hFdhyhLbw7hEsWxufKtY9klyvdNfFlFhM= +github.com/prometheus/client_golang v1.15.0/go.mod h1:e9yaBhRPU2pPNsZwE+JdQl0KEt1N9XgF6zxWmaC0xOk= github.com/prometheus/client_model v0.0.0-20180712105110-5c3871d89910/go.mod h1:MbSGuTsp3dbXC40dX6PRTWyKYBIrTGTE9sqQNg2J8bo= github.com/prometheus/client_model v0.0.0-20190129233127-fd36f4220a90/go.mod h1:xMI15A0UPsDsEKsMN9yxemIoYk6Tm2C1GtYGdfGttqA= github.com/prometheus/client_model v0.0.0-20190812154241-14fe0d1b01d4/go.mod h1:xMI15A0UPsDsEKsMN9yxemIoYk6Tm2C1GtYGdfGttqA= @@ -480,15 +394,15 @@ github.com/rcrowley/go-metrics v0.0.0-20201227073835-cf1acfcdf475 h1:N/ElC8H3+5X github.com/regen-network/gocuke v0.6.2 h1:pHviZ0kKAq2U2hN2q3smKNxct6hS0mGByFMHGnWA97M= github.com/regen-network/gocuke v0.6.2/go.mod h1:zYaqIHZobHyd0xOrHGPQjbhGJsuZ1oElx150u2o1xuk= github.com/rogpeppe/fastuuid v1.2.0/go.mod h1:jVj6XXZzXRy/MSR5jhDC/2q6DgLz+nrA6LYCDYWNEvQ= -github.com/rogpeppe/go-internal v1.3.0/go.mod h1:M8bDsm7K2OlrFYOpmOWEs/qY81heoFRclV5y23lUDJ4= github.com/rogpeppe/go-internal v1.6.1/go.mod h1:xXDCJY+GAPziupqXw64V24skbSoqbTEfhy4qGm1nDQc= github.com/rogpeppe/go-internal v1.8.1/go.mod h1:JeRgkft04UBgHMgCIwADu4Pn6Mtm5d4nPKWu0nJ5d+o= -github.com/rogpeppe/go-internal v1.9.0 h1:73kH8U+JUqXU8lRuOHeVHaa/SZPifC7BkcraZVejAe8= github.com/rogpeppe/go-internal v1.9.0/go.mod h1:WtVeX8xhTBvf0smdhujwtBcq4Qrzq/fJaraNFVN+nFs= +github.com/rogpeppe/go-internal v1.10.0 h1:TMyTOH3F/DB16zRVcYyreMH6GnZZrwQVAoYjRBZyWFQ= +github.com/rogpeppe/go-internal v1.10.0/go.mod h1:UQnix2H7Ngw/k4C5ijL5+65zddjncjaFoBhdsK/akog= github.com/rs/cors v1.8.3 h1:O+qNyWn7Z+F9M0ILBHgMVPuB1xTOucVd5gtaYyXBpRo= github.com/rs/xid v1.4.0/go.mod h1:trrq9SKmegXys3aeAKXMUTdJsYXVwGY3RLcfgqegfbg= -github.com/rs/zerolog v1.29.0 h1:Zes4hju04hjbvkVkOhdl2HpZa+0PmVwigmo8XoORE5w= -github.com/rs/zerolog v1.29.0/go.mod h1:NILgTygv/Uej1ra5XxGf82ZFSLk58MFGAUS2o6usyD0= +github.com/rs/zerolog v1.29.1 h1:cO+d60CHkknCbvzEWxP0S9K6KqyTjrCNUy1LdQLCGPc= +github.com/rs/zerolog v1.29.1/go.mod h1:Le6ESbR7hc+DP6Lt1THiV8CQSdkkNrd3R0XbEgp3ZBU= github.com/russross/blackfriday v1.5.2/go.mod h1:JO/DiYxRf+HjHt06OyowR9PTA263kcR/rfWxYHBV53g= github.com/russross/blackfriday/v2 v2.1.0/go.mod h1:+Rmxgy9KzJVeS9/2gXHxylqXiyQDYRxCVz55jmeOWTM= github.com/ryanuber/columnize v2.1.0+incompatible/go.mod h1:sm1tb6uqfes/u+d4ooFouqFdy9/2g9QGwK3SQygK0Ts= @@ -503,38 +417,29 @@ github.com/smartystreets/assertions v0.0.0-20180927180507-b2de0cb4f26d/go.mod h1 github.com/smartystreets/goconvey v1.6.4/go.mod h1:syvi0/a8iFYH4r/RixwvyeAJjdLS9QV7WQ/tjFTllLA= github.com/spf13/afero v1.1.2/go.mod h1:j4pytiNVoe2o6bmDsKpLACNPDBIoEAkihy7loJ1B0CQ= github.com/spf13/afero v1.9.3 h1:41FoI0fD7OR7mGcKE/aOiLkGreyf8ifIOQmJANWogMk= -github.com/spf13/afero v1.9.3/go.mod h1:iUV7ddyEEZPO5gA3zD4fJt6iStLlL+Lg4m2cihcDf8Y= github.com/spf13/cast v1.3.0/go.mod h1:Qx5cxh0v+4UWYiBimWS+eyWzqEqokIECu5etghLkUJE= github.com/spf13/cast v1.5.0 h1:rj3WzYc11XZaIZMPKmwP96zkFEnnAmV8s6XbB2aY32w= github.com/spf13/cast v1.5.0/go.mod h1:SpXXQ5YoyJw6s3/6cMTQuxvgRl3PCJiyaX9p6b155UU= github.com/spf13/cobra v0.0.5/go.mod h1:3K3wKZymM7VvHMDS9+Akkh4K60UwM26emMESw8tLCHU= -github.com/spf13/cobra v1.6.1 h1:o94oiPyS4KD1mPy2fmcYYHHfCxLqYjJOhGsCHFZtEzA= -github.com/spf13/cobra v1.6.1/go.mod h1:IOw/AERYS7UzyrGinqmz6HLUo219MORXGxhbaJUqzrY= +github.com/spf13/cobra v1.7.0 h1:hyqWnYt1ZQShIddO5kBpj3vu05/++x6tJ6dg8EC572I= +github.com/spf13/cobra v1.7.0/go.mod h1:uLxZILRyS/50WlhOIKD7W6V5bgeIt+4sICxh6uRMrb0= github.com/spf13/jwalterweatherman v1.0.0/go.mod h1:cQK4TGJAtQXfYWX+Ddv3mKDzgVb68N+wFjFa4jdeBTo= github.com/spf13/jwalterweatherman v1.1.0 h1:ue6voC5bR5F8YxI5S67j9i582FU4Qvo2bmqnqMYADFk= -github.com/spf13/jwalterweatherman v1.1.0/go.mod h1:aNWZUN0dPAAO/Ljvb5BEdw96iTZ0EXowPYD95IqWIGo= github.com/spf13/pflag v1.0.3/go.mod h1:DYY7MBk1bdzusC3SYhjObp+wFpr4gzcvqqNjLnInEg4= github.com/spf13/pflag v1.0.5 h1:iy+VFUOCP1a+8yFto/drg2CJ5u0yRoB7fZw3DKv/JXA= github.com/spf13/pflag v1.0.5/go.mod h1:McXfInJRrz4CZXVZOBLb0bTZqETkiAhM9Iw0y3An2Bg= github.com/spf13/viper v1.3.2/go.mod h1:ZiWeW+zYFKm7srdB9IoDzzZXaJaI5eL9QjNiN/DMA2s= github.com/spf13/viper v1.15.0 h1:js3yy885G8xwJa6iOISGFwd+qlUo5AvyXb7CiihdtiU= -github.com/spf13/viper v1.15.0/go.mod h1:fFcTBJxvhhzSJiZy8n+PeW6t8l+KeT/uTARa0jHOQLA= github.com/stretchr/objx v0.1.0/go.mod h1:HFkY916IF+rwdDfMAkV7OtwuqBVzrE8GR6GFx+wExME= github.com/stretchr/objx v0.1.1/go.mod h1:HFkY916IF+rwdDfMAkV7OtwuqBVzrE8GR6GFx+wExME= -github.com/stretchr/objx v0.4.0/go.mod h1:YvHI0jy2hoMjB+UWwv71VJQ9isScKT/TqJzVSSt89Yw= -github.com/stretchr/objx v0.5.0/go.mod h1:Yh+to48EsGEfYuaHDzXPcE3xhTkx73EhmCGUpEOglKo= github.com/stretchr/testify v1.2.2/go.mod h1:a8OnRcib4nhh0OaRAV+Yts87kKdq0PP7pXfy6kDkUVs= github.com/stretchr/testify v1.3.0/go.mod h1:M5WIy9Dh21IEIfnGCwXGc5bZfKNJtfHm1UVUgZn+9EI= github.com/stretchr/testify v1.4.0/go.mod h1:j7eGeouHqKxXV5pUuKE4zz7dFj8WfuZ+81PSLYec5m4= github.com/stretchr/testify v1.5.1/go.mod h1:5W2xD1RspED5o8YsWQXVCued0rvSQ+mT+I5cxcmMvtA= github.com/stretchr/testify v1.7.0/go.mod h1:6Fq8oRcR53rry900zMqJjRRixrwX3KX962/h/Wwjteg= -github.com/stretchr/testify v1.7.1/go.mod h1:6Fq8oRcR53rry900zMqJjRRixrwX3KX962/h/Wwjteg= github.com/stretchr/testify v1.7.2/go.mod h1:R6va5+xMeoiuVRoj+gSkQ7d3FALtqAAGI1FQKckRals= -github.com/stretchr/testify v1.8.0/go.mod h1:yNjHg4UonilssWZ8iaSj1OCr/vHnekPRkoO+kdMU+MU= -github.com/stretchr/testify v1.8.1/go.mod h1:w2LPCIKwWwSfY2zedu0+kehJoqGctiVI29o6fzry7u4= github.com/stretchr/testify v1.8.2 h1:+h33VjcLVPDHtOdpUCuF+7gSuG3yGIftsP1YvFihtJ8= github.com/subosito/gotenv v1.4.2 h1:X1TuBLAMDFbaTAChgCBLu3DU3UPyELpnF2jjJ2cz/S8= -github.com/subosito/gotenv v1.4.2/go.mod h1:ayKnFf/c6rvx/2iiLrJUk1e6plDbT3edrFNGqEflhK0= github.com/syndtr/goleveldb v1.0.1-0.20220721030215-126854af5e6d h1:vfofYNRScrDdvS342BElfbETmL1Aiz3i2t0zfRj16Hs= github.com/syndtr/goleveldb v1.0.1-0.20220721030215-126854af5e6d/go.mod h1:RRCYJbIwD5jmqPI9XoAFR0OcDxqUctll6zUj/+B4S48= github.com/tendermint/go-amino v0.16.0 h1:GyhmgQKvqF82e2oZeuMSp9JTN0N09emoSZlb2lyGa2E= @@ -559,70 +464,32 @@ github.com/yalp/jsonpath v0.0.0-20180802001716-5cc68e5049a0/go.mod h1:/LWChgwKmv github.com/yudai/gojsondiff v1.0.0/go.mod h1:AY32+k2cwILAkW1fbgxQ5mUmMiZFgLIV+FBNExI05xg= github.com/yudai/golcs v0.0.0-20170316035057-ecda9a501e82/go.mod h1:lgjkn3NuSvDfVJdfcVVdX+jpBxNmX4rDAzaS45IcYoM= github.com/yudai/pp v2.0.1+incompatible/go.mod h1:PuxR/8QJ7cyCkFp/aUDS+JY727OFEZkTdatxwunjIkc= -github.com/yuin/goldmark v1.1.25/go.mod h1:3hX8gzYuyVAZsxl0MRgGTJEmQBFcNTphYh9decYSb74= github.com/yuin/goldmark v1.1.27/go.mod h1:3hX8gzYuyVAZsxl0MRgGTJEmQBFcNTphYh9decYSb74= -github.com/yuin/goldmark v1.1.32/go.mod h1:3hX8gzYuyVAZsxl0MRgGTJEmQBFcNTphYh9decYSb74= github.com/yuin/goldmark v1.2.1/go.mod h1:3hX8gzYuyVAZsxl0MRgGTJEmQBFcNTphYh9decYSb74= github.com/yuin/goldmark v1.3.5/go.mod h1:mwnBkeHKe2W/ZEtQ+71ViKU8L12m81fl3OWwC1Zlc8k= github.com/zondax/hid v0.9.1 h1:gQe66rtmyZ8VeGFcOpbuH3r7erYtNEAezCAYu8LdkJo= github.com/zondax/ledger-go v0.14.1 h1:Pip65OOl4iJ84WTpA4BKChvOufMhhbxED3BaihoZN4c= -go.opencensus.io v0.21.0/go.mod h1:mSImk1erAIZhrmZN+AvHh14ztQfjbGwt4TtuofqLduU= -go.opencensus.io v0.22.0/go.mod h1:+kGneAE2xo2IficOXnaByMWTGM9T73dGwxeWcUqIpI8= -go.opencensus.io v0.22.2/go.mod h1:yxeiOL68Rb0Xd1ddK5vPZ/oVn4vY4Ynel7k9FzqtOIw= -go.opencensus.io v0.22.3/go.mod h1:yxeiOL68Rb0Xd1ddK5vPZ/oVn4vY4Ynel7k9FzqtOIw= -go.opencensus.io v0.22.4/go.mod h1:yxeiOL68Rb0Xd1ddK5vPZ/oVn4vY4Ynel7k9FzqtOIw= -go.opencensus.io v0.22.5/go.mod h1:5pWMHQbX5EPX2/62yrJeAkowc+lfs/XD7Uxpq3pI6kk= golang.org/x/crypto v0.0.0-20180904163835-0709b304e793/go.mod h1:6SG95UA2DQfeDnfUPMdvaQW0Q7yPrPDi9nlGo2tz2b4= golang.org/x/crypto v0.0.0-20181203042331-505ab145d0a9/go.mod h1:6SG95UA2DQfeDnfUPMdvaQW0Q7yPrPDi9nlGo2tz2b4= golang.org/x/crypto v0.0.0-20190308221718-c2843e01d9a2/go.mod h1:djNgcEr1/C05ACkg1iLfiJU5Ep61QUkGW8qpdssI0+w= -golang.org/x/crypto v0.0.0-20190510104115-cbcb75029529/go.mod h1:yigFU9vqHzYiE8UmvKecakEJjdnWj3jj499lnFckfCI= -golang.org/x/crypto v0.0.0-20190605123033-f99c8df09eb5/go.mod h1:yigFU9vqHzYiE8UmvKecakEJjdnWj3jj499lnFckfCI= golang.org/x/crypto v0.0.0-20190701094942-4def268fd1a4/go.mod h1:yigFU9vqHzYiE8UmvKecakEJjdnWj3jj499lnFckfCI= golang.org/x/crypto v0.0.0-20191011191535-87dc89f01550/go.mod h1:yigFU9vqHzYiE8UmvKecakEJjdnWj3jj499lnFckfCI= golang.org/x/crypto v0.0.0-20191227163750-53104e6ec876/go.mod h1:LzIPMQfyMNhhGPhUkYOs5KpL4U8rLKemX1yGLhDgUto= golang.org/x/crypto v0.0.0-20200622213623-75b288015ac9/go.mod h1:LzIPMQfyMNhhGPhUkYOs5KpL4U8rLKemX1yGLhDgUto= golang.org/x/crypto v0.0.0-20210322153248-0c34fe9e7dc2/go.mod h1:T9bdIzuCu7OtxOm1hfPfRQxPLYneinmdGuTeoZ9dtd4= -golang.org/x/crypto v0.0.0-20210421170649-83a5a9bb288b/go.mod h1:T9bdIzuCu7OtxOm1hfPfRQxPLYneinmdGuTeoZ9dtd4= golang.org/x/crypto v0.0.0-20210921155107-089bfa567519/go.mod h1:GvvjBRRGRdwPK5ydBHafDWAxML/pGHZbMvKqRZ5+Abc= -golang.org/x/crypto v0.0.0-20211108221036-ceb1ce70b4fa/go.mod h1:GvvjBRRGRdwPK5ydBHafDWAxML/pGHZbMvKqRZ5+Abc= -golang.org/x/crypto v0.7.0 h1:AvwMYaRytfdeVt3u6mLaxYtErKYjxA2OXjJ1HHq6t3A= -golang.org/x/crypto v0.7.0/go.mod h1:pYwdfH91IfpZVANVyUOhSIPZaFoJGxTFbZhFTx+dXZU= +golang.org/x/crypto v0.8.0 h1:pd9TJtTueMTVQXzk8E2XESSMQDj/U7OUu0PqJqPXQjQ= +golang.org/x/crypto v0.8.0/go.mod h1:mRqEX+O9/h5TFCrQhkgjo2yKi0yYA+9ecGkdQoHrywE= golang.org/x/exp v0.0.0-20190121172915-509febef88a4/go.mod h1:CJ0aWSM057203Lf6IL+f9T1iT9GByDxfZKAQTCR3kQA= -golang.org/x/exp v0.0.0-20190306152737-a1d7652674e8/go.mod h1:CJ0aWSM057203Lf6IL+f9T1iT9GByDxfZKAQTCR3kQA= -golang.org/x/exp v0.0.0-20190510132918-efd6b22b2522/go.mod h1:ZjyILWgesfNpC6sMxTJOJm9Kp84zZh5NQWvqDGG3Qr8= -golang.org/x/exp v0.0.0-20190829153037-c13cbed26979/go.mod h1:86+5VVa7VpoJ4kLfm080zCjGlMRFzhUhsZKEZO7MGek= -golang.org/x/exp v0.0.0-20191030013958-a1ab85dbe136/go.mod h1:JXzH8nQsPlswgeRAPE3MuO9GYsAcnJvJ4vnMwN/5qkY= -golang.org/x/exp v0.0.0-20191129062945-2f5052295587/go.mod h1:2RIsYlXP63K8oxa1u096TMicItID8zy7Y6sNkU49FU4= -golang.org/x/exp v0.0.0-20191227195350-da58074b4299/go.mod h1:2RIsYlXP63K8oxa1u096TMicItID8zy7Y6sNkU49FU4= -golang.org/x/exp v0.0.0-20200119233911-0405dc783f0a/go.mod h1:2RIsYlXP63K8oxa1u096TMicItID8zy7Y6sNkU49FU4= -golang.org/x/exp v0.0.0-20200207192155-f17229e696bd/go.mod h1:J/WKrq2StrnmMY6+EHIKF9dgMWnmCNThgcyBT1FY9mM= -golang.org/x/exp v0.0.0-20200224162631-6cc2880d07d6/go.mod h1:3jZMyOhIsHpP37uCMkUooju7aAi5cS1Q23tOzKc+0MU= golang.org/x/exp v0.0.0-20230321023759-10a507213a29 h1:ooxPy7fPvB4kwsA2h+iBNHkAbp/4JxTSwCmvdjEYmug= golang.org/x/exp v0.0.0-20230321023759-10a507213a29/go.mod h1:CxIveKay+FTh1D0yPZemJVgC/95VzuuOLq5Qi4xnoYc= -golang.org/x/image v0.0.0-20190227222117-0694c2d4d067/go.mod h1:kZ7UVZpmo3dzQBMxlp+ypCbDeSB+sBbTgSJuh5dn5js= -golang.org/x/image v0.0.0-20190802002840-cff245a6509b/go.mod h1:FeLwcggjj3mMvU+oOTbSwawSJRM1uh48EjtB4UJZlP0= golang.org/x/lint v0.0.0-20181026193005-c67002cb31c3/go.mod h1:UVdnD1Gm6xHRNCYTkRU2/jEulfH38KcIWyp/GAMgvoE= golang.org/x/lint v0.0.0-20190227174305-5b3e6a55c961/go.mod h1:wehouNa3lNwaWXcvxsM5YxQ5yQlVC4a0KAMCusXpPoU= -golang.org/x/lint v0.0.0-20190301231843-5614ed5bae6f/go.mod h1:UVdnD1Gm6xHRNCYTkRU2/jEulfH38KcIWyp/GAMgvoE= golang.org/x/lint v0.0.0-20190313153728-d0100b6bd8b3/go.mod h1:6SW0HCj/g11FgYtHlgUYUwCkIfeOF89ocIRzGO/8vkc= -golang.org/x/lint v0.0.0-20190409202823-959b441ac422/go.mod h1:6SW0HCj/g11FgYtHlgUYUwCkIfeOF89ocIRzGO/8vkc= -golang.org/x/lint v0.0.0-20190909230951-414d861bb4ac/go.mod h1:6SW0HCj/g11FgYtHlgUYUwCkIfeOF89ocIRzGO/8vkc= -golang.org/x/lint v0.0.0-20190930215403-16217165b5de/go.mod h1:6SW0HCj/g11FgYtHlgUYUwCkIfeOF89ocIRzGO/8vkc= -golang.org/x/lint v0.0.0-20191125180803-fdd1cda4f05f/go.mod h1:5qLYkcX4OjUUV8bRuDixDT3tpyyb+LUpUlRWLxfhWrs= -golang.org/x/lint v0.0.0-20200130185559-910be7a94367/go.mod h1:3xt1FjdF8hUf6vQPIChWIBhFzV8gjjsPE/fR3IyQdNY= -golang.org/x/lint v0.0.0-20200302205851-738671d3881b/go.mod h1:3xt1FjdF8hUf6vQPIChWIBhFzV8gjjsPE/fR3IyQdNY= -golang.org/x/lint v0.0.0-20201208152925-83fdc39ff7b5/go.mod h1:3xt1FjdF8hUf6vQPIChWIBhFzV8gjjsPE/fR3IyQdNY= golang.org/x/lint v0.0.0-20210508222113-6edffad5e616/go.mod h1:3xt1FjdF8hUf6vQPIChWIBhFzV8gjjsPE/fR3IyQdNY= -golang.org/x/mobile v0.0.0-20190312151609-d3739f865fa6/go.mod h1:z+o9i4GpDbdi3rU15maQ/Ox0txvL9dWGYEHz965HBQE= -golang.org/x/mobile v0.0.0-20190719004257-d2bd2a29d028/go.mod h1:E/iHnbuqvinMTCcRqshq8CkpyQDoeVncDDYHnLhea+o= -golang.org/x/mod v0.0.0-20190513183733-4bf6d317e70e/go.mod h1:mXi4GBBbnImb6dmsKGUJ2LatrhH/nqhxcFungHvyanc= -golang.org/x/mod v0.1.0/go.mod h1:0QHyrYULN0/3qlju5TqG8bIK38QM8yzMo5ekMj3DlcY= golang.org/x/mod v0.1.1-0.20191105210325-c90efee705ee/go.mod h1:QqPTAvyqsEbceGzBzNggFXnrqF1CaUcvgkdR5Ot7KZg= -golang.org/x/mod v0.1.1-0.20191107180719-034126e5016b/go.mod h1:QqPTAvyqsEbceGzBzNggFXnrqF1CaUcvgkdR5Ot7KZg= golang.org/x/mod v0.2.0/go.mod h1:s0Qsj1ACt9ePp/hMypM3fl4fZqREWJwdYDEqhRiZZUA= golang.org/x/mod v0.3.0/go.mod h1:s0Qsj1ACt9ePp/hMypM3fl4fZqREWJwdYDEqhRiZZUA= -golang.org/x/mod v0.4.0/go.mod h1:s0Qsj1ACt9ePp/hMypM3fl4fZqREWJwdYDEqhRiZZUA= -golang.org/x/mod v0.4.1/go.mod h1:s0Qsj1ACt9ePp/hMypM3fl4fZqREWJwdYDEqhRiZZUA= golang.org/x/mod v0.4.2/go.mod h1:s0Qsj1ACt9ePp/hMypM3fl4fZqREWJwdYDEqhRiZZUA= golang.org/x/net v0.0.0-20180724234803-3673e40ba225/go.mod h1:mL1N/T3taQHkDXs73rZJwtUhF3w3ftmwwsq0BUmARs4= golang.org/x/net v0.0.0-20180826012351-8a410e7b638d/go.mod h1:mL1N/T3taQHkDXs73rZJwtUhF3w3ftmwwsq0BUmARs4= @@ -634,60 +501,32 @@ golang.org/x/net v0.0.0-20190213061140-3a22650c66bd/go.mod h1:mL1N/T3taQHkDXs73r golang.org/x/net v0.0.0-20190311183353-d8887717615a/go.mod h1:t9HGtf8HONx5eT2rtn7q6eTqICYqUVnKs3thJo3Qplg= golang.org/x/net v0.0.0-20190327091125-710a502c58a2/go.mod h1:t9HGtf8HONx5eT2rtn7q6eTqICYqUVnKs3thJo3Qplg= golang.org/x/net v0.0.0-20190404232315-eb5bcb51f2a3/go.mod h1:t9HGtf8HONx5eT2rtn7q6eTqICYqUVnKs3thJo3Qplg= -golang.org/x/net v0.0.0-20190501004415-9ce7a6920f09/go.mod h1:t9HGtf8HONx5eT2rtn7q6eTqICYqUVnKs3thJo3Qplg= golang.org/x/net v0.0.0-20190503192946-f4e77d36d62c/go.mod h1:t9HGtf8HONx5eT2rtn7q6eTqICYqUVnKs3thJo3Qplg= -golang.org/x/net v0.0.0-20190603091049-60506f45cf65/go.mod h1:HSz+uSET+XFnRR8LxR5pz3Of3rY3CfYBVs4xY44aLks= golang.org/x/net v0.0.0-20190613194153-d28f0bde5980/go.mod h1:z5CRVTTTmAJ677TzLLGU+0bjPO0LkuOLi4/5GtJWs/s= golang.org/x/net v0.0.0-20190620200207-3b0461eec859/go.mod h1:z5CRVTTTmAJ677TzLLGU+0bjPO0LkuOLi4/5GtJWs/s= -golang.org/x/net v0.0.0-20190628185345-da137c7871d7/go.mod h1:z5CRVTTTmAJ677TzLLGU+0bjPO0LkuOLi4/5GtJWs/s= -golang.org/x/net v0.0.0-20190724013045-ca1201d0de80/go.mod h1:z5CRVTTTmAJ677TzLLGU+0bjPO0LkuOLi4/5GtJWs/s= golang.org/x/net v0.0.0-20190827160401-ba9fcec4b297/go.mod h1:z5CRVTTTmAJ677TzLLGU+0bjPO0LkuOLi4/5GtJWs/s= golang.org/x/net v0.0.0-20191209160850-c0dbc17a3553/go.mod h1:z5CRVTTTmAJ677TzLLGU+0bjPO0LkuOLi4/5GtJWs/s= -golang.org/x/net v0.0.0-20200114155413-6afb5195e5aa/go.mod h1:z5CRVTTTmAJ677TzLLGU+0bjPO0LkuOLi4/5GtJWs/s= -golang.org/x/net v0.0.0-20200202094626-16171245cfb2/go.mod h1:z5CRVTTTmAJ677TzLLGU+0bjPO0LkuOLi4/5GtJWs/s= -golang.org/x/net v0.0.0-20200222125558-5a598a2470a0/go.mod h1:z5CRVTTTmAJ677TzLLGU+0bjPO0LkuOLi4/5GtJWs/s= golang.org/x/net v0.0.0-20200226121028-0de0cce0169b/go.mod h1:z5CRVTTTmAJ677TzLLGU+0bjPO0LkuOLi4/5GtJWs/s= -golang.org/x/net v0.0.0-20200301022130-244492dfa37a/go.mod h1:z5CRVTTTmAJ677TzLLGU+0bjPO0LkuOLi4/5GtJWs/s= -golang.org/x/net v0.0.0-20200324143707-d3edc9973b7e/go.mod h1:qpuaurCH72eLCgpAm/N6yyVIVM9cpaDIP3A8BGJEC5A= -golang.org/x/net v0.0.0-20200501053045-e0ff5e5a1de5/go.mod h1:qpuaurCH72eLCgpAm/N6yyVIVM9cpaDIP3A8BGJEC5A= -golang.org/x/net v0.0.0-20200506145744-7e3656a0809f/go.mod h1:qpuaurCH72eLCgpAm/N6yyVIVM9cpaDIP3A8BGJEC5A= -golang.org/x/net v0.0.0-20200513185701-a91f0712d120/go.mod h1:qpuaurCH72eLCgpAm/N6yyVIVM9cpaDIP3A8BGJEC5A= golang.org/x/net v0.0.0-20200520004742-59133d7f0dd7/go.mod h1:qpuaurCH72eLCgpAm/N6yyVIVM9cpaDIP3A8BGJEC5A= -golang.org/x/net v0.0.0-20200520182314-0ba52f642ac2/go.mod h1:qpuaurCH72eLCgpAm/N6yyVIVM9cpaDIP3A8BGJEC5A= -golang.org/x/net v0.0.0-20200625001655-4c5254603344/go.mod h1:/O7V0waA8r7cgGh81Ro3o1hOxt32SMVPicZroKQ2sZA= -golang.org/x/net v0.0.0-20200707034311-ab3426394381/go.mod h1:/O7V0waA8r7cgGh81Ro3o1hOxt32SMVPicZroKQ2sZA= golang.org/x/net v0.0.0-20200822124328-c89045814202/go.mod h1:/O7V0waA8r7cgGh81Ro3o1hOxt32SMVPicZroKQ2sZA= golang.org/x/net v0.0.0-20201021035429-f5854403a974/go.mod h1:sp8m0HH+o8qH0wwXwYZr8TS3Oi6o0r6Gce1SSxlDquU= -golang.org/x/net v0.0.0-20201031054903-ff519b6c9102/go.mod h1:sp8m0HH+o8qH0wwXwYZr8TS3Oi6o0r6Gce1SSxlDquU= -golang.org/x/net v0.0.0-20201209123823-ac852fbbde11/go.mod h1:m0MpNAwzfU5UDzcl9v0D8zg8gWTRqZa9RBIspLL5mdg= -golang.org/x/net v0.0.0-20201224014010-6772e930b67b/go.mod h1:m0MpNAwzfU5UDzcl9v0D8zg8gWTRqZa9RBIspLL5mdg= golang.org/x/net v0.0.0-20210226172049-e18ecbb05110/go.mod h1:m0MpNAwzfU5UDzcl9v0D8zg8gWTRqZa9RBIspLL5mdg= golang.org/x/net v0.0.0-20210405180319-a5a99cb37ef4/go.mod h1:p54w0d4576C0XHj96bSt6lcn1PtDYWL6XObtHCRCNQM= golang.org/x/net v0.0.0-20210428140749-89ef3d95e781/go.mod h1:OJAsFXCWl8Ukc7SiCT/9KSuxbyM7479/AVlXFRxuMCk= golang.org/x/net v0.0.0-20211008194852-3b03d305991f/go.mod h1:9nx3DQGgdP8bBQD5qxJ1jj9UTztislL4KSBs9R2vV5Y= golang.org/x/net v0.0.0-20220225172249-27dd8689420f/go.mod h1:CfG3xpIq0wQ8r1q4Su4UZFWDARRcnwPjda9FqA0JpMk= golang.org/x/net v0.0.0-20220607020251-c690dde0001d/go.mod h1:XRhObCWvk6IyKnWLug+ECip1KBveYUHfp+8e9klMJ9c= -golang.org/x/net v0.8.0 h1:Zrh2ngAOFYneWTAIAPethzeaQLuHwhuBkuV6ZiRnUaQ= -golang.org/x/net v0.8.0/go.mod h1:QVkue5JL9kW//ek3r6jTKnTFis1tRmNAW2P1shuFdJc= +golang.org/x/net v0.9.0 h1:aWJ/m6xSmxWBx+V0XRHTlrYrPG56jKsLdTFmsSsCzOM= +golang.org/x/net v0.9.0/go.mod h1:d48xBJpPfHeWQsugry2m+kC02ZBRGRgulfHnEXEuWns= golang.org/x/oauth2 v0.0.0-20180821212333-d2e6202438be/go.mod h1:N/0e6XlmueqKjAGxoOufVs8QHGRruUQn6yWY3a++T0U= -golang.org/x/oauth2 v0.0.0-20190226205417-e64efc72b421/go.mod h1:gOpvHmFTYa4IltrdGE7lF6nIHvwfUNPOp7c8zoXwtLw= -golang.org/x/oauth2 v0.0.0-20190604053449-0f29369cfe45/go.mod h1:gOpvHmFTYa4IltrdGE7lF6nIHvwfUNPOp7c8zoXwtLw= -golang.org/x/oauth2 v0.0.0-20191202225959-858c2ad4c8b6/go.mod h1:gOpvHmFTYa4IltrdGE7lF6nIHvwfUNPOp7c8zoXwtLw= golang.org/x/oauth2 v0.0.0-20200107190931-bf48bf16ab8d/go.mod h1:gOpvHmFTYa4IltrdGE7lF6nIHvwfUNPOp7c8zoXwtLw= -golang.org/x/oauth2 v0.0.0-20200902213428-5d25da1a8d43/go.mod h1:KelEdhl1UZF7XfJ4dDtk6s++YSgaE7mD/BuKKDLBl4A= -golang.org/x/oauth2 v0.0.0-20201109201403-9fd604954f58/go.mod h1:KelEdhl1UZF7XfJ4dDtk6s++YSgaE7mD/BuKKDLBl4A= -golang.org/x/oauth2 v0.0.0-20201208152858-08078c50e5b5/go.mod h1:KelEdhl1UZF7XfJ4dDtk6s++YSgaE7mD/BuKKDLBl4A= -golang.org/x/oauth2 v0.0.0-20210218202405-ba52d332ba99/go.mod h1:KelEdhl1UZF7XfJ4dDtk6s++YSgaE7mD/BuKKDLBl4A= golang.org/x/sync v0.0.0-20180314180146-1d60e4601c6f/go.mod h1:RxMgew5VJxzue5/jJTE5uejpjVlOe/izrB70Jof72aM= golang.org/x/sync v0.0.0-20181108010431-42b317875d0f/go.mod h1:RxMgew5VJxzue5/jJTE5uejpjVlOe/izrB70Jof72aM= golang.org/x/sync v0.0.0-20181221193216-37e7f081c4d4/go.mod h1:RxMgew5VJxzue5/jJTE5uejpjVlOe/izrB70Jof72aM= golang.org/x/sync v0.0.0-20190227155943-e225da77a7e6/go.mod h1:RxMgew5VJxzue5/jJTE5uejpjVlOe/izrB70Jof72aM= golang.org/x/sync v0.0.0-20190423024810-112230192c58/go.mod h1:RxMgew5VJxzue5/jJTE5uejpjVlOe/izrB70Jof72aM= golang.org/x/sync v0.0.0-20190911185100-cd5d95a43a6e/go.mod h1:RxMgew5VJxzue5/jJTE5uejpjVlOe/izrB70Jof72aM= -golang.org/x/sync v0.0.0-20200317015054-43a5402ce75a/go.mod h1:RxMgew5VJxzue5/jJTE5uejpjVlOe/izrB70Jof72aM= -golang.org/x/sync v0.0.0-20200625203802-6e8e738ad208/go.mod h1:RxMgew5VJxzue5/jJTE5uejpjVlOe/izrB70Jof72aM= golang.org/x/sync v0.0.0-20201020160332-67f06af15bc9/go.mod h1:RxMgew5VJxzue5/jJTE5uejpjVlOe/izrB70Jof72aM= -golang.org/x/sync v0.0.0-20201207232520-09787c993a3a/go.mod h1:RxMgew5VJxzue5/jJTE5uejpjVlOe/izrB70Jof72aM= golang.org/x/sync v0.0.0-20210220032951-036812b2e83c/go.mod h1:RxMgew5VJxzue5/jJTE5uejpjVlOe/izrB70Jof72aM= golang.org/x/sync v0.1.0 h1:wsuoTGHzEhffawBOhz5CYhcrV4IdKZbEyZjBMuTp12o= golang.org/x/sys v0.0.0-20180830151530-49385e6e1522/go.mod h1:STP8DvDyc/dI5b8T5hshtkjS+E42TnysNCUPdjciGhY= @@ -697,48 +536,25 @@ golang.org/x/sys v0.0.0-20181116152217-5ac8a444bdc5/go.mod h1:STP8DvDyc/dI5b8T5h golang.org/x/sys v0.0.0-20181205085412-a5c9d58dba9a/go.mod h1:STP8DvDyc/dI5b8T5hshtkjS+E42TnysNCUPdjciGhY= golang.org/x/sys v0.0.0-20190215142949-d0b11bdaac8a/go.mod h1:STP8DvDyc/dI5b8T5hshtkjS+E42TnysNCUPdjciGhY= golang.org/x/sys v0.0.0-20190222072716-a9d3bda3a223/go.mod h1:STP8DvDyc/dI5b8T5hshtkjS+E42TnysNCUPdjciGhY= -golang.org/x/sys v0.0.0-20190312061237-fead79001313/go.mod h1:h1NjWce9XRLGQEsW7wpKNCjG9DtNlClVuFLEZdDNbEs= golang.org/x/sys v0.0.0-20190412213103-97732733099d/go.mod h1:h1NjWce9XRLGQEsW7wpKNCjG9DtNlClVuFLEZdDNbEs= golang.org/x/sys v0.0.0-20190422165155-953cdadca894/go.mod h1:h1NjWce9XRLGQEsW7wpKNCjG9DtNlClVuFLEZdDNbEs= -golang.org/x/sys v0.0.0-20190502145724-3ef323f4f1fd/go.mod h1:h1NjWce9XRLGQEsW7wpKNCjG9DtNlClVuFLEZdDNbEs= -golang.org/x/sys v0.0.0-20190507160741-ecd444e8653b/go.mod h1:h1NjWce9XRLGQEsW7wpKNCjG9DtNlClVuFLEZdDNbEs= -golang.org/x/sys v0.0.0-20190606165138-5da285871e9c/go.mod h1:h1NjWce9XRLGQEsW7wpKNCjG9DtNlClVuFLEZdDNbEs= -golang.org/x/sys v0.0.0-20190624142023-c5567b49c5d0/go.mod h1:h1NjWce9XRLGQEsW7wpKNCjG9DtNlClVuFLEZdDNbEs= golang.org/x/sys v0.0.0-20190626221950-04f50cda93cb/go.mod h1:h1NjWce9XRLGQEsW7wpKNCjG9DtNlClVuFLEZdDNbEs= -golang.org/x/sys v0.0.0-20190726091711-fc99dfbffb4e/go.mod h1:h1NjWce9XRLGQEsW7wpKNCjG9DtNlClVuFLEZdDNbEs= golang.org/x/sys v0.0.0-20190813064441-fde4db37ae7a/go.mod h1:h1NjWce9XRLGQEsW7wpKNCjG9DtNlClVuFLEZdDNbEs= golang.org/x/sys v0.0.0-20190904154756-749cb33beabd/go.mod h1:h1NjWce9XRLGQEsW7wpKNCjG9DtNlClVuFLEZdDNbEs= -golang.org/x/sys v0.0.0-20191001151750-bb3f8db39f24/go.mod h1:h1NjWce9XRLGQEsW7wpKNCjG9DtNlClVuFLEZdDNbEs= golang.org/x/sys v0.0.0-20191005200804-aed5e4c7ecf9/go.mod h1:h1NjWce9XRLGQEsW7wpKNCjG9DtNlClVuFLEZdDNbEs= golang.org/x/sys v0.0.0-20191120155948-bd437916bb0e/go.mod h1:h1NjWce9XRLGQEsW7wpKNCjG9DtNlClVuFLEZdDNbEs= golang.org/x/sys v0.0.0-20191204072324-ce4227a45e2e/go.mod h1:h1NjWce9XRLGQEsW7wpKNCjG9DtNlClVuFLEZdDNbEs= -golang.org/x/sys v0.0.0-20191228213918-04cbcbbfeed8/go.mod h1:h1NjWce9XRLGQEsW7wpKNCjG9DtNlClVuFLEZdDNbEs= -golang.org/x/sys v0.0.0-20200113162924-86b910548bc1/go.mod h1:h1NjWce9XRLGQEsW7wpKNCjG9DtNlClVuFLEZdDNbEs= golang.org/x/sys v0.0.0-20200116001909-b77594299b42/go.mod h1:h1NjWce9XRLGQEsW7wpKNCjG9DtNlClVuFLEZdDNbEs= golang.org/x/sys v0.0.0-20200122134326-e047566fdf82/go.mod h1:h1NjWce9XRLGQEsW7wpKNCjG9DtNlClVuFLEZdDNbEs= -golang.org/x/sys v0.0.0-20200202164722-d101bd2416d5/go.mod h1:h1NjWce9XRLGQEsW7wpKNCjG9DtNlClVuFLEZdDNbEs= -golang.org/x/sys v0.0.0-20200212091648-12a6c2dcc1e4/go.mod h1:h1NjWce9XRLGQEsW7wpKNCjG9DtNlClVuFLEZdDNbEs= golang.org/x/sys v0.0.0-20200223170610-d5e6a3e2c0ae/go.mod h1:h1NjWce9XRLGQEsW7wpKNCjG9DtNlClVuFLEZdDNbEs= -golang.org/x/sys v0.0.0-20200302150141-5c8b2ff67527/go.mod h1:h1NjWce9XRLGQEsW7wpKNCjG9DtNlClVuFLEZdDNbEs= golang.org/x/sys v0.0.0-20200323222414-85ca7c5b95cd/go.mod h1:h1NjWce9XRLGQEsW7wpKNCjG9DtNlClVuFLEZdDNbEs= -golang.org/x/sys v0.0.0-20200331124033-c3d80250170d/go.mod h1:h1NjWce9XRLGQEsW7wpKNCjG9DtNlClVuFLEZdDNbEs= -golang.org/x/sys v0.0.0-20200501052902-10377860bb8e/go.mod h1:h1NjWce9XRLGQEsW7wpKNCjG9DtNlClVuFLEZdDNbEs= -golang.org/x/sys v0.0.0-20200511232937-7e40ca221e25/go.mod h1:h1NjWce9XRLGQEsW7wpKNCjG9DtNlClVuFLEZdDNbEs= -golang.org/x/sys v0.0.0-20200515095857-1151b9dac4a9/go.mod h1:h1NjWce9XRLGQEsW7wpKNCjG9DtNlClVuFLEZdDNbEs= -golang.org/x/sys v0.0.0-20200523222454-059865788121/go.mod h1:h1NjWce9XRLGQEsW7wpKNCjG9DtNlClVuFLEZdDNbEs= -golang.org/x/sys v0.0.0-20200803210538-64077c9b5642/go.mod h1:h1NjWce9XRLGQEsW7wpKNCjG9DtNlClVuFLEZdDNbEs= -golang.org/x/sys v0.0.0-20200905004654-be1d3432aa8f/go.mod h1:h1NjWce9XRLGQEsW7wpKNCjG9DtNlClVuFLEZdDNbEs= golang.org/x/sys v0.0.0-20200930185726-fdedc70b468f/go.mod h1:h1NjWce9XRLGQEsW7wpKNCjG9DtNlClVuFLEZdDNbEs= golang.org/x/sys v0.0.0-20201119102817-f84b799fce68/go.mod h1:h1NjWce9XRLGQEsW7wpKNCjG9DtNlClVuFLEZdDNbEs= -golang.org/x/sys v0.0.0-20201201145000-ef89a241ccb3/go.mod h1:h1NjWce9XRLGQEsW7wpKNCjG9DtNlClVuFLEZdDNbEs= -golang.org/x/sys v0.0.0-20210104204734-6f8348627aad/go.mod h1:h1NjWce9XRLGQEsW7wpKNCjG9DtNlClVuFLEZdDNbEs= golang.org/x/sys v0.0.0-20210112080510-489259a85091/go.mod h1:h1NjWce9XRLGQEsW7wpKNCjG9DtNlClVuFLEZdDNbEs= golang.org/x/sys v0.0.0-20210119212857-b64e53b001e4/go.mod h1:h1NjWce9XRLGQEsW7wpKNCjG9DtNlClVuFLEZdDNbEs= -golang.org/x/sys v0.0.0-20210225134936-a50acf3fe073/go.mod h1:h1NjWce9XRLGQEsW7wpKNCjG9DtNlClVuFLEZdDNbEs= golang.org/x/sys v0.0.0-20210330210617-4fbd30eecc44/go.mod h1:h1NjWce9XRLGQEsW7wpKNCjG9DtNlClVuFLEZdDNbEs= golang.org/x/sys v0.0.0-20210403161142-5e06dd20ab57/go.mod h1:h1NjWce9XRLGQEsW7wpKNCjG9DtNlClVuFLEZdDNbEs= golang.org/x/sys v0.0.0-20210423082822-04245dca01da/go.mod h1:h1NjWce9XRLGQEsW7wpKNCjG9DtNlClVuFLEZdDNbEs= -golang.org/x/sys v0.0.0-20210423185535-09eb48e85fd7/go.mod h1:h1NjWce9XRLGQEsW7wpKNCjG9DtNlClVuFLEZdDNbEs= golang.org/x/sys v0.0.0-20210510120138-977fb7262007/go.mod h1:oPkhp1MJrh7nUepCBck5+mAzfO9JrbApNNgaTdGDITg= golang.org/x/sys v0.0.0-20210615035016-665e8c7367d1/go.mod h1:oPkhp1MJrh7nUepCBck5+mAzfO9JrbApNNgaTdGDITg= golang.org/x/sys v0.0.0-20210630005230-0f9fa26af87c/go.mod h1:oPkhp1MJrh7nUepCBck5+mAzfO9JrbApNNgaTdGDITg= @@ -749,79 +565,34 @@ golang.org/x/sys v0.0.0-20220209214540-3681064d5158/go.mod h1:oPkhp1MJrh7nUepCBc golang.org/x/sys v0.0.0-20220412211240-33da011f77ad/go.mod h1:oPkhp1MJrh7nUepCBck5+mAzfO9JrbApNNgaTdGDITg= golang.org/x/sys v0.0.0-20220520151302-bc2c85ada10a/go.mod h1:oPkhp1MJrh7nUepCBck5+mAzfO9JrbApNNgaTdGDITg= golang.org/x/sys v0.0.0-20220811171246-fbc7d0a398ab/go.mod h1:oPkhp1MJrh7nUepCBck5+mAzfO9JrbApNNgaTdGDITg= -golang.org/x/sys v0.0.0-20220908164124-27713097b956/go.mod h1:oPkhp1MJrh7nUepCBck5+mAzfO9JrbApNNgaTdGDITg= -golang.org/x/sys v0.6.0 h1:MVltZSvRTcU2ljQOhs94SXPftV6DCNnZViHeQps87pQ= golang.org/x/sys v0.6.0/go.mod h1:oPkhp1MJrh7nUepCBck5+mAzfO9JrbApNNgaTdGDITg= +golang.org/x/sys v0.7.0 h1:3jlCCIQZPdOYu1h8BkNvLz8Kgwtae2cagcG/VamtZRU= +golang.org/x/sys v0.7.0/go.mod h1:oPkhp1MJrh7nUepCBck5+mAzfO9JrbApNNgaTdGDITg= golang.org/x/term v0.0.0-20201126162022-7de9c90e9dd1/go.mod h1:bj7SfCRtBDWHUb9snDiAeCFNEtKQo2Wmx5Cou7ajbmo= golang.org/x/term v0.0.0-20210927222741-03fcf44c2211/go.mod h1:jbD1KX2456YbFQfuXm/mYQcufACuNUgVhRMnK/tPxf8= -golang.org/x/term v0.6.0 h1:clScbb1cHjoCkyRbWwBEUZ5H/tIFu5TAXIqaZD0Gcjw= -golang.org/x/text v0.0.0-20170915032832-14c0d48ead0c/go.mod h1:NqM8EUOU14njkJ3fqMW+pc6Ldnwhi/IjpwHt7yyuwOQ= +golang.org/x/term v0.7.0 h1:BEvjmm5fURWqcfbSKTdpkDXYBrUS1c0m8agp14W48vQ= golang.org/x/text v0.3.0/go.mod h1:NqM8EUOU14njkJ3fqMW+pc6Ldnwhi/IjpwHt7yyuwOQ= -golang.org/x/text v0.3.1-0.20180807135948-17ff2d5776d2/go.mod h1:NqM8EUOU14njkJ3fqMW+pc6Ldnwhi/IjpwHt7yyuwOQ= golang.org/x/text v0.3.2/go.mod h1:bEr9sfX3Q8Zfm5fL9x+3itogRgK3+ptLWKqgva+5dAk= golang.org/x/text v0.3.3/go.mod h1:5Zoc/QRtKVWzQhOtBMvqHzDpF6irO9z98xDceosuGiQ= -golang.org/x/text v0.3.4/go.mod h1:5Zoc/QRtKVWzQhOtBMvqHzDpF6irO9z98xDceosuGiQ= golang.org/x/text v0.3.5/go.mod h1:5Zoc/QRtKVWzQhOtBMvqHzDpF6irO9z98xDceosuGiQ= golang.org/x/text v0.3.6/go.mod h1:5Zoc/QRtKVWzQhOtBMvqHzDpF6irO9z98xDceosuGiQ= golang.org/x/text v0.3.7/go.mod h1:u+2+/6zg+i71rQMx5EYifcz6MCKuco9NR6JIITiCfzQ= -golang.org/x/text v0.8.0 h1:57P1ETyNKtuIjB4SRd15iJxuhj8Gc416Y78H3qgMh68= -golang.org/x/text v0.8.0/go.mod h1:e1OnstbJyHTd6l/uOt8jFFHp6TRDWZR/bV3emEE/zU8= -golang.org/x/time v0.0.0-20181108054448-85acf8d2951c/go.mod h1:tRJNPiyCQ0inRvYxbN9jk5I+vvW/OXSQhTDSoE431IQ= -golang.org/x/time v0.0.0-20190308202827-9d24e82272b4/go.mod h1:tRJNPiyCQ0inRvYxbN9jk5I+vvW/OXSQhTDSoE431IQ= -golang.org/x/time v0.0.0-20191024005414-555d28b269f0/go.mod h1:tRJNPiyCQ0inRvYxbN9jk5I+vvW/OXSQhTDSoE431IQ= +golang.org/x/text v0.9.0 h1:2sjJmO8cDvYveuX97RDLsxlyUxLl+GHoLxBiRdHllBE= +golang.org/x/text v0.9.0/go.mod h1:e1OnstbJyHTd6l/uOt8jFFHp6TRDWZR/bV3emEE/zU8= golang.org/x/time v0.0.0-20201208040808-7e3f01d25324/go.mod h1:tRJNPiyCQ0inRvYxbN9jk5I+vvW/OXSQhTDSoE431IQ= golang.org/x/tools v0.0.0-20180917221912-90fa682c2a6e/go.mod h1:n7NCudcB/nEzxVGmLbDWY5pfWTLqBcC2KZ6jyYvM4mQ= golang.org/x/tools v0.0.0-20181221001348-537d06c36207/go.mod h1:n7NCudcB/nEzxVGmLbDWY5pfWTLqBcC2KZ6jyYvM4mQ= golang.org/x/tools v0.0.0-20190114222345-bf090417da8b/go.mod h1:n7NCudcB/nEzxVGmLbDWY5pfWTLqBcC2KZ6jyYvM4mQ= golang.org/x/tools v0.0.0-20190226205152-f727befe758c/go.mod h1:9Yl7xja0Znq3iFh3HoIrodX9oNMXvdceNzlUR8zjMvY= golang.org/x/tools v0.0.0-20190311212946-11955173bddd/go.mod h1:LCzVGOaR6xXOjkQ3onu1FJEFr0SW1gC7cKk1uF8kGRs= -golang.org/x/tools v0.0.0-20190312151545-0bb0c0a6e846/go.mod h1:LCzVGOaR6xXOjkQ3onu1FJEFr0SW1gC7cKk1uF8kGRs= -golang.org/x/tools v0.0.0-20190312170243-e65039ee4138/go.mod h1:LCzVGOaR6xXOjkQ3onu1FJEFr0SW1gC7cKk1uF8kGRs= golang.org/x/tools v0.0.0-20190327201419-c70d86f8b7cf/go.mod h1:LCzVGOaR6xXOjkQ3onu1FJEFr0SW1gC7cKk1uF8kGRs= golang.org/x/tools v0.0.0-20190328211700-ab21143f2384/go.mod h1:LCzVGOaR6xXOjkQ3onu1FJEFr0SW1gC7cKk1uF8kGRs= -golang.org/x/tools v0.0.0-20190425150028-36563e24a262/go.mod h1:RgjU9mgBXZiqYHBnxXauZ1Gv1EHHAz9KjViQ78xBX0Q= -golang.org/x/tools v0.0.0-20190506145303-2d16b83fe98c/go.mod h1:RgjU9mgBXZiqYHBnxXauZ1Gv1EHHAz9KjViQ78xBX0Q= golang.org/x/tools v0.0.0-20190524140312-2c0ae7006135/go.mod h1:RgjU9mgBXZiqYHBnxXauZ1Gv1EHHAz9KjViQ78xBX0Q= -golang.org/x/tools v0.0.0-20190606124116-d0a3d012864b/go.mod h1:/rFqwRUd4F7ZHNgwSSTFct+R/Kf4OFW1sUzUTQQTgfc= -golang.org/x/tools v0.0.0-20190621195816-6e04913cbbac/go.mod h1:/rFqwRUd4F7ZHNgwSSTFct+R/Kf4OFW1sUzUTQQTgfc= -golang.org/x/tools v0.0.0-20190628153133-6cdbf07be9d0/go.mod h1:/rFqwRUd4F7ZHNgwSSTFct+R/Kf4OFW1sUzUTQQTgfc= -golang.org/x/tools v0.0.0-20190816200558-6889da9d5479/go.mod h1:b+2E5dAYhXwXZwtnZ6UAqBI28+e2cm9otk0dWdXHAEo= -golang.org/x/tools v0.0.0-20190911174233-4f2ddba30aff/go.mod h1:b+2E5dAYhXwXZwtnZ6UAqBI28+e2cm9otk0dWdXHAEo= -golang.org/x/tools v0.0.0-20191012152004-8de300cfc20a/go.mod h1:b+2E5dAYhXwXZwtnZ6UAqBI28+e2cm9otk0dWdXHAEo= -golang.org/x/tools v0.0.0-20191113191852-77e3bb0ad9e7/go.mod h1:b+2E5dAYhXwXZwtnZ6UAqBI28+e2cm9otk0dWdXHAEo= -golang.org/x/tools v0.0.0-20191115202509-3a792d9c32b2/go.mod h1:b+2E5dAYhXwXZwtnZ6UAqBI28+e2cm9otk0dWdXHAEo= golang.org/x/tools v0.0.0-20191119224855-298f0cb1881e/go.mod h1:b+2E5dAYhXwXZwtnZ6UAqBI28+e2cm9otk0dWdXHAEo= -golang.org/x/tools v0.0.0-20191125144606-a911d9008d1f/go.mod h1:b+2E5dAYhXwXZwtnZ6UAqBI28+e2cm9otk0dWdXHAEo= -golang.org/x/tools v0.0.0-20191130070609-6e064ea0cf2d/go.mod h1:b+2E5dAYhXwXZwtnZ6UAqBI28+e2cm9otk0dWdXHAEo= -golang.org/x/tools v0.0.0-20191216173652-a0e659d51361/go.mod h1:TB2adYChydJhpapKDTa4BR/hXlZSLoq2Wpct/0txZ28= -golang.org/x/tools v0.0.0-20191227053925-7b8e75db28f4/go.mod h1:TB2adYChydJhpapKDTa4BR/hXlZSLoq2Wpct/0txZ28= -golang.org/x/tools v0.0.0-20200117161641-43d50277825c/go.mod h1:TB2adYChydJhpapKDTa4BR/hXlZSLoq2Wpct/0txZ28= -golang.org/x/tools v0.0.0-20200122220014-bf1340f18c4a/go.mod h1:TB2adYChydJhpapKDTa4BR/hXlZSLoq2Wpct/0txZ28= golang.org/x/tools v0.0.0-20200130002326-2f3ba24bd6e7/go.mod h1:TB2adYChydJhpapKDTa4BR/hXlZSLoq2Wpct/0txZ28= -golang.org/x/tools v0.0.0-20200204074204-1cc6d1ef6c74/go.mod h1:TB2adYChydJhpapKDTa4BR/hXlZSLoq2Wpct/0txZ28= -golang.org/x/tools v0.0.0-20200207183749-b753a1ba74fa/go.mod h1:TB2adYChydJhpapKDTa4BR/hXlZSLoq2Wpct/0txZ28= -golang.org/x/tools v0.0.0-20200212150539-ea181f53ac56/go.mod h1:TB2adYChydJhpapKDTa4BR/hXlZSLoq2Wpct/0txZ28= -golang.org/x/tools v0.0.0-20200224181240-023911ca70b2/go.mod h1:TB2adYChydJhpapKDTa4BR/hXlZSLoq2Wpct/0txZ28= -golang.org/x/tools v0.0.0-20200227222343-706bc42d1f0d/go.mod h1:TB2adYChydJhpapKDTa4BR/hXlZSLoq2Wpct/0txZ28= -golang.org/x/tools v0.0.0-20200304193943-95d2e580d8eb/go.mod h1:o4KQGtdN14AW+yjsvvwRTJJuXz8XRtIHtEnmAXLyFUw= -golang.org/x/tools v0.0.0-20200312045724-11d5b4c81c7d/go.mod h1:o4KQGtdN14AW+yjsvvwRTJJuXz8XRtIHtEnmAXLyFUw= -golang.org/x/tools v0.0.0-20200331025713-a30bf2db82d4/go.mod h1:Sl4aGygMT6LrqrWclx+PTx3U+LnKx/seiNR+3G19Ar8= -golang.org/x/tools v0.0.0-20200501065659-ab2804fb9c9d/go.mod h1:EkVYQZoAsY45+roYkvgYkIh4xh/qjgUK9TdY2XT94GE= -golang.org/x/tools v0.0.0-20200512131952-2bc93b1c0c88/go.mod h1:EkVYQZoAsY45+roYkvgYkIh4xh/qjgUK9TdY2XT94GE= -golang.org/x/tools v0.0.0-20200515010526-7d3b6ebf133d/go.mod h1:EkVYQZoAsY45+roYkvgYkIh4xh/qjgUK9TdY2XT94GE= -golang.org/x/tools v0.0.0-20200618134242-20370b0cb4b2/go.mod h1:EkVYQZoAsY45+roYkvgYkIh4xh/qjgUK9TdY2XT94GE= golang.org/x/tools v0.0.0-20200619180055-7c47624df98f/go.mod h1:EkVYQZoAsY45+roYkvgYkIh4xh/qjgUK9TdY2XT94GE= -golang.org/x/tools v0.0.0-20200729194436-6467de6f59a7/go.mod h1:njjCfa9FT2d7l9Bc6FUM5FLjQPp3cFF28FI3qnDFljA= -golang.org/x/tools v0.0.0-20200804011535-6c149bb5ef0d/go.mod h1:njjCfa9FT2d7l9Bc6FUM5FLjQPp3cFF28FI3qnDFljA= -golang.org/x/tools v0.0.0-20200825202427-b303f430e36d/go.mod h1:njjCfa9FT2d7l9Bc6FUM5FLjQPp3cFF28FI3qnDFljA= -golang.org/x/tools v0.0.0-20200904185747-39188db58858/go.mod h1:Cj7w3i3Rnn0Xh82ur9kSqwfTHTeVxaDqrfMjpcNT6bE= -golang.org/x/tools v0.0.0-20201110124207-079ba7bd75cd/go.mod h1:emZCQorbCU4vsT4fOWvOPXz4eW1wZW4PmDk9uLelYpA= -golang.org/x/tools v0.0.0-20201201161351-ac6f37ff4c2a/go.mod h1:emZCQorbCU4vsT4fOWvOPXz4eW1wZW4PmDk9uLelYpA= -golang.org/x/tools v0.0.0-20201208233053-a543418bbed2/go.mod h1:emZCQorbCU4vsT4fOWvOPXz4eW1wZW4PmDk9uLelYpA= golang.org/x/tools v0.0.0-20201224043029-2b0845dc783e/go.mod h1:emZCQorbCU4vsT4fOWvOPXz4eW1wZW4PmDk9uLelYpA= -golang.org/x/tools v0.0.0-20210105154028-b0ab187a4818/go.mod h1:emZCQorbCU4vsT4fOWvOPXz4eW1wZW4PmDk9uLelYpA= golang.org/x/tools v0.0.0-20210106214847-113979e3529a/go.mod h1:emZCQorbCU4vsT4fOWvOPXz4eW1wZW4PmDk9uLelYpA= -golang.org/x/tools v0.0.0-20210108195828-e2f9c7f1fc8e/go.mod h1:emZCQorbCU4vsT4fOWvOPXz4eW1wZW4PmDk9uLelYpA= golang.org/x/tools v0.1.0/go.mod h1:xkSsbof2nBLbhDlRMhhhyNLN/zl3eTqcnHD5viDpcZ0= golang.org/x/tools v0.1.3/go.mod h1:o0xws9oXOQQZyjljx8fwUC0k7L1pTE6eaCbjGeHmOkk= golang.org/x/xerrors v0.0.0-20190717185122-a985d3407aa7/go.mod h1:I/5z698sn9Ka8TeJc9MKroUUfqBBauWjQqLJ2OPfmY0= @@ -829,92 +600,23 @@ golang.org/x/xerrors v0.0.0-20191011141410-1b5146add898/go.mod h1:I/5z698sn9Ka8T golang.org/x/xerrors v0.0.0-20191204190536-9bdfabe68543/go.mod h1:I/5z698sn9Ka8TeJc9MKroUUfqBBauWjQqLJ2OPfmY0= golang.org/x/xerrors v0.0.0-20200804184101-5ec99f83aff1/go.mod h1:I/5z698sn9Ka8TeJc9MKroUUfqBBauWjQqLJ2OPfmY0= golang.org/x/xerrors v0.0.0-20220517211312-f3a8303e98df/go.mod h1:K8+ghG5WaK9qNqU5K3HdILfMLy1f3aNYFI/wnl100a8= -google.golang.org/api v0.4.0/go.mod h1:8k5glujaEP+g9n7WNsDg8QP6cUVNI86fCNMcbazEtwE= -google.golang.org/api v0.7.0/go.mod h1:WtwebWUNSVBH/HAw79HIFXZNqEvBhG+Ra+ax0hx3E3M= -google.golang.org/api v0.8.0/go.mod h1:o4eAsZoiT+ibD93RtjEohWalFOjRDx6CVaqeizhEnKg= -google.golang.org/api v0.9.0/go.mod h1:o4eAsZoiT+ibD93RtjEohWalFOjRDx6CVaqeizhEnKg= -google.golang.org/api v0.13.0/go.mod h1:iLdEw5Ide6rF15KTC1Kkl0iskquN2gFfn9o9XIsbkAI= -google.golang.org/api v0.14.0/go.mod h1:iLdEw5Ide6rF15KTC1Kkl0iskquN2gFfn9o9XIsbkAI= -google.golang.org/api v0.15.0/go.mod h1:iLdEw5Ide6rF15KTC1Kkl0iskquN2gFfn9o9XIsbkAI= -google.golang.org/api v0.17.0/go.mod h1:BwFmGc8tA3vsd7r/7kR8DY7iEEGSU04BFxCo5jP/sfE= -google.golang.org/api v0.18.0/go.mod h1:BwFmGc8tA3vsd7r/7kR8DY7iEEGSU04BFxCo5jP/sfE= -google.golang.org/api v0.19.0/go.mod h1:BwFmGc8tA3vsd7r/7kR8DY7iEEGSU04BFxCo5jP/sfE= -google.golang.org/api v0.20.0/go.mod h1:BwFmGc8tA3vsd7r/7kR8DY7iEEGSU04BFxCo5jP/sfE= -google.golang.org/api v0.22.0/go.mod h1:BwFmGc8tA3vsd7r/7kR8DY7iEEGSU04BFxCo5jP/sfE= -google.golang.org/api v0.24.0/go.mod h1:lIXQywCXRcnZPGlsd8NbLnOjtAoL6em04bJ9+z0MncE= -google.golang.org/api v0.28.0/go.mod h1:lIXQywCXRcnZPGlsd8NbLnOjtAoL6em04bJ9+z0MncE= -google.golang.org/api v0.29.0/go.mod h1:Lcubydp8VUV7KeIHD9z2Bys/sm/vGKnG1UHuDBSrHWM= -google.golang.org/api v0.30.0/go.mod h1:QGmEvQ87FHZNiUVJkT14jQNYJ4ZJjdRF23ZXz5138Fc= -google.golang.org/api v0.35.0/go.mod h1:/XrVsuzM0rZmrsbjJutiuftIzeuTQcEeaYcSk/mQ1dg= -google.golang.org/api v0.36.0/go.mod h1:+z5ficQTmoYpPn8LCUNVpK5I7hwkpjbcgqA7I34qYtE= -google.golang.org/api v0.40.0/go.mod h1:fYKFpnQN0DsDSKRVRcQSDQNtqWPfM9i+zNPxepjRCQ8= google.golang.org/appengine v1.1.0/go.mod h1:EbEs0AVv82hx2wNQdGPgUI5lhzA/G0D9YwlJXL52JkM= google.golang.org/appengine v1.4.0/go.mod h1:xpcJRLb0r/rnEns0DIKYYv+WjYCduHsrkT7/EB5XEv4= -google.golang.org/appengine v1.5.0/go.mod h1:xpcJRLb0r/rnEns0DIKYYv+WjYCduHsrkT7/EB5XEv4= -google.golang.org/appengine v1.6.1/go.mod h1:i06prIuMbXzDqacNJfV5OdTW448YApPu5ww/cMBSeb0= -google.golang.org/appengine v1.6.5/go.mod h1:8WjMMxjGQR8xUklV/ARdw2HLXBOI7O7uCIDZVag1xfc= -google.golang.org/appengine v1.6.6/go.mod h1:8WjMMxjGQR8xUklV/ARdw2HLXBOI7O7uCIDZVag1xfc= -google.golang.org/appengine v1.6.7/go.mod h1:8WjMMxjGQR8xUklV/ARdw2HLXBOI7O7uCIDZVag1xfc= google.golang.org/genproto v0.0.0-20180518175338-11a468237815/go.mod h1:JiN7NxoALGmiZfu7CAH4rXhgtRTLTxftemlI0sWmxmc= google.golang.org/genproto v0.0.0-20180817151627-c66870c02cf8/go.mod h1:JiN7NxoALGmiZfu7CAH4rXhgtRTLTxftemlI0sWmxmc= google.golang.org/genproto v0.0.0-20180831171423-11092d34479b/go.mod h1:JiN7NxoALGmiZfu7CAH4rXhgtRTLTxftemlI0sWmxmc= -google.golang.org/genproto v0.0.0-20190307195333-5fe7a883aa19/go.mod h1:VzzqZJRnGkLBvHegQrXjBqPurQTc5/KpmUdxsrq26oE= -google.golang.org/genproto v0.0.0-20190418145605-e7d98fc518a7/go.mod h1:VzzqZJRnGkLBvHegQrXjBqPurQTc5/KpmUdxsrq26oE= -google.golang.org/genproto v0.0.0-20190425155659-357c62f0e4bb/go.mod h1:VzzqZJRnGkLBvHegQrXjBqPurQTc5/KpmUdxsrq26oE= -google.golang.org/genproto v0.0.0-20190502173448-54afdca5d873/go.mod h1:VzzqZJRnGkLBvHegQrXjBqPurQTc5/KpmUdxsrq26oE= -google.golang.org/genproto v0.0.0-20190801165951-fa694d86fc64/go.mod h1:DMBHOl98Agz4BDEuKkezgsaosCRResVns1a3J2ZsMNc= google.golang.org/genproto v0.0.0-20190819201941-24fa4b261c55/go.mod h1:DMBHOl98Agz4BDEuKkezgsaosCRResVns1a3J2ZsMNc= -google.golang.org/genproto v0.0.0-20190911173649-1774047e7e51/go.mod h1:IbNlFCBrqXvoKpeg0TB2l7cyZUmoaFKYIwrEpbDKLA8= -google.golang.org/genproto v0.0.0-20191108220845-16a3f7862a1a/go.mod h1:n3cpQtvxv34hfy77yVDNjmbRyujviMdxYliBSkLhpCc= -google.golang.org/genproto v0.0.0-20191115194625-c23dd37a84c9/go.mod h1:n3cpQtvxv34hfy77yVDNjmbRyujviMdxYliBSkLhpCc= -google.golang.org/genproto v0.0.0-20191216164720-4f79533eabd1/go.mod h1:n3cpQtvxv34hfy77yVDNjmbRyujviMdxYliBSkLhpCc= -google.golang.org/genproto v0.0.0-20191230161307-f3c370f40bfb/go.mod h1:n3cpQtvxv34hfy77yVDNjmbRyujviMdxYliBSkLhpCc= -google.golang.org/genproto v0.0.0-20200115191322-ca5a22157cba/go.mod h1:n3cpQtvxv34hfy77yVDNjmbRyujviMdxYliBSkLhpCc= -google.golang.org/genproto v0.0.0-20200122232147-0452cf42e150/go.mod h1:n3cpQtvxv34hfy77yVDNjmbRyujviMdxYliBSkLhpCc= -google.golang.org/genproto v0.0.0-20200204135345-fa8e72b47b90/go.mod h1:GmwEX6Z4W5gMy59cAlVYjN9JhxgbQH6Gn+gFDQe2lzA= -google.golang.org/genproto v0.0.0-20200212174721-66ed5ce911ce/go.mod h1:55QSHmfGQM9UVYDPBsyGGes0y52j32PQ3BqQfXhyH3c= -google.golang.org/genproto v0.0.0-20200224152610-e50cd9704f63/go.mod h1:55QSHmfGQM9UVYDPBsyGGes0y52j32PQ3BqQfXhyH3c= -google.golang.org/genproto v0.0.0-20200228133532-8c2c7df3a383/go.mod h1:55QSHmfGQM9UVYDPBsyGGes0y52j32PQ3BqQfXhyH3c= -google.golang.org/genproto v0.0.0-20200305110556-506484158171/go.mod h1:55QSHmfGQM9UVYDPBsyGGes0y52j32PQ3BqQfXhyH3c= -google.golang.org/genproto v0.0.0-20200312145019-da6875a35672/go.mod h1:55QSHmfGQM9UVYDPBsyGGes0y52j32PQ3BqQfXhyH3c= -google.golang.org/genproto v0.0.0-20200331122359-1ee6d9798940/go.mod h1:55QSHmfGQM9UVYDPBsyGGes0y52j32PQ3BqQfXhyH3c= -google.golang.org/genproto v0.0.0-20200430143042-b979b6f78d84/go.mod h1:55QSHmfGQM9UVYDPBsyGGes0y52j32PQ3BqQfXhyH3c= -google.golang.org/genproto v0.0.0-20200511104702-f5ebc3bea380/go.mod h1:55QSHmfGQM9UVYDPBsyGGes0y52j32PQ3BqQfXhyH3c= google.golang.org/genproto v0.0.0-20200513103714-09dca8ec2884/go.mod h1:55QSHmfGQM9UVYDPBsyGGes0y52j32PQ3BqQfXhyH3c= -google.golang.org/genproto v0.0.0-20200515170657-fc4c6c6a6587/go.mod h1:YsZOwe1myG/8QRHRsmBRE1LrgQY60beZKjly0O1fX9U= google.golang.org/genproto v0.0.0-20200526211855-cb27e3aa2013/go.mod h1:NbSheEEYHJ7i3ixzK3sjbqSGDJWnxyFXZblF3eUsNvo= -google.golang.org/genproto v0.0.0-20200618031413-b414f8b61790/go.mod h1:jDfRM7FcilCzHH/e9qn6dsT145K34l5v+OpcnNgKAAA= -google.golang.org/genproto v0.0.0-20200729003335-053ba62fc06f/go.mod h1:FWY/as6DDZQgahTzZj3fqbO1CbirC29ZNUFHwi0/+no= -google.golang.org/genproto v0.0.0-20200804131852-c06518451d9c/go.mod h1:FWY/as6DDZQgahTzZj3fqbO1CbirC29ZNUFHwi0/+no= -google.golang.org/genproto v0.0.0-20200825200019-8632dd797987/go.mod h1:FWY/as6DDZQgahTzZj3fqbO1CbirC29ZNUFHwi0/+no= -google.golang.org/genproto v0.0.0-20200904004341-0bd0a958aa1d/go.mod h1:FWY/as6DDZQgahTzZj3fqbO1CbirC29ZNUFHwi0/+no= -google.golang.org/genproto v0.0.0-20201109203340-2640f1f9cdfb/go.mod h1:FWY/as6DDZQgahTzZj3fqbO1CbirC29ZNUFHwi0/+no= -google.golang.org/genproto v0.0.0-20201201144952-b05cb90ed32e/go.mod h1:FWY/as6DDZQgahTzZj3fqbO1CbirC29ZNUFHwi0/+no= -google.golang.org/genproto v0.0.0-20201210142538-e3217bee35cc/go.mod h1:FWY/as6DDZQgahTzZj3fqbO1CbirC29ZNUFHwi0/+no= -google.golang.org/genproto v0.0.0-20201214200347-8c77b98c765d/go.mod h1:FWY/as6DDZQgahTzZj3fqbO1CbirC29ZNUFHwi0/+no= -google.golang.org/genproto v0.0.0-20210108203827-ffc7fda8c3d7/go.mod h1:FWY/as6DDZQgahTzZj3fqbO1CbirC29ZNUFHwi0/+no= -google.golang.org/genproto v0.0.0-20210226172003-ab064af71705/go.mod h1:FWY/as6DDZQgahTzZj3fqbO1CbirC29ZNUFHwi0/+no= google.golang.org/genproto v0.0.0-20210624195500-8bfb893ecb84/go.mod h1:SzzZ/N+nwJDaO1kznhnlzqS8ocJICar6hYhVyhi++24= -google.golang.org/genproto v0.0.0-20230320184635-7606e756e683 h1:khxVcsk/FhnzxMKOyD+TDGwjbEOpcPuIpmafPGFmhMA= -google.golang.org/genproto v0.0.0-20230320184635-7606e756e683/go.mod h1:NWraEVixdDnqcqQ30jipen1STv2r/n24Wb7twVTGR4s= +google.golang.org/genproto v0.0.0-20230410155749-daa745c078e1 h1:KpwkzHKEF7B9Zxg18WzOa7djJ+Ha5DzthMyZYQfEn2A= +google.golang.org/genproto v0.0.0-20230410155749-daa745c078e1/go.mod h1:nKE/iIaLqn2bQwXBg8f1g2Ylh6r5MN5CmZvuzZCgsCU= google.golang.org/grpc v1.12.0/go.mod h1:yo6s7OP7yaDglbqo1J04qKzAhqBH6lvTonzMVmEdcZw= google.golang.org/grpc v1.19.0/go.mod h1:mqu4LbDTu4XGKhr4mRzUsmM4RtVoemTSY81AxZiDr8c= -google.golang.org/grpc v1.20.1/go.mod h1:10oTOabMzJvdu6/UiuZezV6QK5dSlG84ov/aaiqXj38= -google.golang.org/grpc v1.21.1/go.mod h1:oYelfM1adQP15Ek0mdvEgi9Df8B9CZIaU1084ijfRaM= google.golang.org/grpc v1.23.0/go.mod h1:Y5yQAOtifL1yxbo5wqy6BxZv8vAUGQwXBOALyacEbxg= google.golang.org/grpc v1.25.1/go.mod h1:c3i+UQWmh7LiEpx4sFZnkU36qjEYZ0imhYfXVyQciAY= -google.golang.org/grpc v1.26.0/go.mod h1:qbnxyOmOxrQa7FizSgH+ReBfzJrCY1pSN7KXBS8abTk= google.golang.org/grpc v1.27.0/go.mod h1:qbnxyOmOxrQa7FizSgH+ReBfzJrCY1pSN7KXBS8abTk= -google.golang.org/grpc v1.27.1/go.mod h1:qbnxyOmOxrQa7FizSgH+ReBfzJrCY1pSN7KXBS8abTk= -google.golang.org/grpc v1.28.0/go.mod h1:rpkK4SK4GF4Ach/+MFLZUBavHOvF2JJB5uozKKal+60= -google.golang.org/grpc v1.29.1/go.mod h1:itym6AZVZYACWQqET3MqgPpjcuV5QH3BxFS3IjizoKk= -google.golang.org/grpc v1.30.0/go.mod h1:N36X2cJ7JwdamYAgDz+s+rVMFjt3numwzf/HckM8pak= -google.golang.org/grpc v1.31.0/go.mod h1:N36X2cJ7JwdamYAgDz+s+rVMFjt3numwzf/HckM8pak= -google.golang.org/grpc v1.31.1/go.mod h1:N36X2cJ7JwdamYAgDz+s+rVMFjt3numwzf/HckM8pak= google.golang.org/grpc v1.33.1/go.mod h1:fr5YgcSWrqhRRxogOsw7RzIpsmvOZ6IcH4kBYTpR3n0= -google.golang.org/grpc v1.33.2/go.mod h1:JMHMWHQWaTccqQQlmk3MJZS+GWXOdAesneDmEnv2fbc= -google.golang.org/grpc v1.34.0/go.mod h1:WotjhfgOW/POjDeRt8vscBtXq+2VjORFy659qA51WJ8= -google.golang.org/grpc v1.35.0/go.mod h1:qjiiYl8FncCW8feJPdyg3v6XW24KsRHe+dy9BAGRRjU= google.golang.org/grpc v1.38.0/go.mod h1:NREThFqKR1f3iQ6oBuvc5LadQuXVGo9rkm5ZGrQdJfM= google.golang.org/grpc v1.54.0 h1:EhTqbhiYeixwWQtAEZAxmV9MGqcjEU2mFx52xCzNyag= google.golang.org/grpc v1.54.0/go.mod h1:PUSEXI6iWghWaB6lXM4knEgpJNu2qUcKfDtNci3EC2g= @@ -926,7 +628,6 @@ google.golang.org/protobuf v1.21.0/go.mod h1:47Nbq4nVaFHyn7ilMalzfO3qCViNmqZ2kzi google.golang.org/protobuf v1.22.0/go.mod h1:EGpADcykh3NcUnDUJcl1+ZksZNG86OlYog2l/sGQquU= google.golang.org/protobuf v1.23.0/go.mod h1:EGpADcykh3NcUnDUJcl1+ZksZNG86OlYog2l/sGQquU= google.golang.org/protobuf v1.23.1-0.20200526195155-81db48ad09cc/go.mod h1:EGpADcykh3NcUnDUJcl1+ZksZNG86OlYog2l/sGQquU= -google.golang.org/protobuf v1.24.0/go.mod h1:r/3tXBNzIEhYS9I1OUVjXDlt8tc493IdKGjtUeSXeh4= google.golang.org/protobuf v1.25.0/go.mod h1:9JNX74DMeImyA3h4bdi1ymwjUzf21/xIlbajtzgsN7c= google.golang.org/protobuf v1.26.0-rc.1/go.mod h1:jlhhOSvTdKEhbULTjvd4ARK9grFBp09yW+WbY/TyQbw= google.golang.org/protobuf v1.26.0/go.mod h1:9q0QmTI4eRPtz6boOQmLYwt+qCgq0jsYwAQnmE0givc= @@ -943,7 +644,6 @@ gopkg.in/go-playground/assert.v1 v1.2.1/go.mod h1:9RXL0bg/zibRAgZUYszZSwO/z8Y/a8 gopkg.in/go-playground/validator.v8 v8.18.2/go.mod h1:RX2a/7Ha8BgOhfk7j780h4/u/RRjR0eouCJSH80/M2Y= gopkg.in/ini.v1 v1.51.1/go.mod h1:pNLf8WUiyNEtQjuu5G5vTm06TEv9tsIgeAvK8hOrP4k= gopkg.in/ini.v1 v1.67.0 h1:Dgnx+6+nfE+IfzjUEISNeydPJh9AXNNsWbGP9KzCsOA= -gopkg.in/ini.v1 v1.67.0/go.mod h1:pNLf8WUiyNEtQjuu5G5vTm06TEv9tsIgeAvK8hOrP4k= gopkg.in/mgo.v2 v2.0.0-20180705113604-9856a29383ce/go.mod h1:yeKp02qBN3iKW1OzL3MGk2IdtZzaj7SFntXj72NppTA= gopkg.in/tomb.v1 v1.0.0-20141024135613-dd632973f1e7 h1:uRGJdciOHaEIrze2W8Q3AKkepLTh2hOroT7a+7czfdQ= gopkg.in/tomb.v1 v1.0.0-20141024135613-dd632973f1e7/go.mod h1:dt/ZhP58zS4L8KSrWDmTeBkI65Dw0HsyUHuEVlX15mw= @@ -963,17 +663,9 @@ gopkg.in/yaml.v3 v3.0.1/go.mod h1:K4uyk7z7BCEPqu6E+C64Yfv1cQ7kz7rIZviUmN+EgEM= gotest.tools/v3 v3.4.0 h1:ZazjZUfuVeZGLAmlKKuyv3IKP5orXcwtOwDQH6YVr6o= gotest.tools/v3 v3.4.0/go.mod h1:CtbdzLSsqVhDgMtKsx03ird5YTGB3ar27v0u/yKBW5g= honnef.co/go/tools v0.0.0-20190102054323-c2f93a96b099/go.mod h1:rf3lG4BRIbNafJWhAfAdb/ePZxsR/4RtNHQocxwk9r4= -honnef.co/go/tools v0.0.0-20190106161140-3f1c8253044a/go.mod h1:rf3lG4BRIbNafJWhAfAdb/ePZxsR/4RtNHQocxwk9r4= -honnef.co/go/tools v0.0.0-20190418001031-e561f6794a2a/go.mod h1:rf3lG4BRIbNafJWhAfAdb/ePZxsR/4RtNHQocxwk9r4= honnef.co/go/tools v0.0.0-20190523083050-ea95bdfd59fc/go.mod h1:rf3lG4BRIbNafJWhAfAdb/ePZxsR/4RtNHQocxwk9r4= -honnef.co/go/tools v0.0.1-2019.2.3/go.mod h1:a3bituU0lyd329TUQxRnasdCoJDkEUEAqEt0JzvZhAg= -honnef.co/go/tools v0.0.1-2020.1.3/go.mod h1:X/FiERA/W4tHapMX5mGpAtMSVEeEUOyHaw9vFzvIQ3k= -honnef.co/go/tools v0.0.1-2020.1.4/go.mod h1:X/FiERA/W4tHapMX5mGpAtMSVEeEUOyHaw9vFzvIQ3k= nhooyr.io/websocket v1.8.6 h1:s+C3xAMLwGmlI31Nyn/eAehUlZPwfYZu2JXM621Q5/k= pgregory.net/rapid v0.5.5 h1:jkgx1TjbQPD/feRoK+S/mXw9e1uj6WilpHrXJowi6oA= pgregory.net/rapid v0.5.5/go.mod h1:PY5XlDGj0+V1FCq0o192FdRhpKHGTRIWBgqjDBTrq04= -rsc.io/binaryregexp v0.2.0/go.mod h1:qTv7/COck+e2FymRvadv62gMdZztPaShugOCi3I+8D8= -rsc.io/quote/v3 v3.1.0/go.mod h1:yEA65RcK8LyAZtP9Kv3t0HmxON59tX3rD+tICJqUlj0= -rsc.io/sampler v1.3.0/go.mod h1:T1hPZKmBbMNahiBKFy5HrXp6adAjACjK9JXDnKaTXpA= sigs.k8s.io/yaml v1.3.0 h1:a2VclLzOGrwOHDiV8EfBGhvjHvP46CtW5j6POvhYGGo= sigs.k8s.io/yaml v1.3.0/go.mod h1:GeOyir5tyXNByN85N/dRIT9es5UQNerPYEKK56eTBm8= diff --git a/x/circuit/keeper/msg_authorize_test.go b/x/circuit/keeper/msg_authorize_test.go index d4a012ab1976..e69082ad7ada 100644 --- a/x/circuit/keeper/msg_authorize_test.go +++ b/x/circuit/keeper/msg_authorize_test.go @@ -20,7 +20,7 @@ func (s *authorizeSuite) Before(t *testing.T) { s.baseFixture = initFixture(t) } -func (s *authorizeSuite) HasPermission(a string, b string) { +func (s *authorizeSuite) HasPermission(a, b string) { panic("PENDING") } @@ -28,7 +28,7 @@ func (s *authorizeSuite) HasNoPermissions(a string) { panic("PENDING") } -func (s *authorizeSuite) AttemptsToGrantThePermissions(a string, b string, c gocuke.DocString) { +func (s *authorizeSuite) AttemptsToGrantThePermissions(a, b string, c gocuke.DocString) { panic("PENDING") } diff --git a/x/circuit/keeper/msg_reset_test.go b/x/circuit/keeper/msg_reset_test.go index 8b935c35b7ff..83dd989f5799 100644 --- a/x/circuit/keeper/msg_reset_test.go +++ b/x/circuit/keeper/msg_reset_test.go @@ -20,7 +20,7 @@ func (s *resetSuite) Before(t *testing.T) { s.baseFixture = initFixture(t) } -func (s *resetSuite) HasPermission(a string, b string) { +func (s *resetSuite) HasPermission(a, b string) { panic("PENDING") } @@ -28,7 +28,7 @@ func (s *resetSuite) HasNoPermissions(a string) { panic("PENDING") } -func (s *resetSuite) AttemptsToResetCircuit(a string, b string, c gocuke.DocString) { +func (s *resetSuite) AttemptsToResetCircuit(a, b string, c gocuke.DocString) { panic("PENDING") } diff --git a/x/circuit/keeper/msg_trip_test.go b/x/circuit/keeper/msg_trip_test.go index 7977eb808d48..fc9899ad265f 100644 --- a/x/circuit/keeper/msg_trip_test.go +++ b/x/circuit/keeper/msg_trip_test.go @@ -20,7 +20,7 @@ func (s *tripSuite) Before(t *testing.T) { s.baseFixture = initFixture(t) } -func (s *tripSuite) HasPermission(a string, b string) { +func (s *tripSuite) HasPermission(a, b string) { panic("PENDING") } @@ -28,7 +28,7 @@ func (s *tripSuite) HasNoPermissions(a string) { panic("PENDING") } -func (s *tripSuite) AttemptsToTripCircuit(a string, b string, c gocuke.DocString) { +func (s *tripSuite) AttemptsToTripCircuit(a, b string, c gocuke.DocString) { panic("PENDING") } diff --git a/x/circuit/keeper/test_utils.go b/x/circuit/keeper/test_utils.go index 01299e3bdc21..16e266d980e1 100644 --- a/x/circuit/keeper/test_utils.go +++ b/x/circuit/keeper/test_utils.go @@ -1,22 +1,20 @@ package keeper import ( - "context" "testing" - - storetypes "cosmossdk.io/store/types" - sdk "github.com/cosmos/cosmos-sdk/types" ) type baseFixture struct { t *testing.T err error - ctx context.Context - // k Keeper //TODO uncomment this after implementing - addrs []sdk.AccAddress - storeKey *storetypes.KVStoreKey - sdkCtx sdk.Context + // TODO: uncomment these after implementing. + // ctx context.Context + + // k Keeper + // addrs []sdk.AccAddress + // storeKey *storetypes.KVStoreKey + // sdkCtx sdk.Context } func initFixture(t *testing.T) *baseFixture { diff --git a/x/circuit/types/query.pb.go b/x/circuit/types/query.pb.go new file mode 100644 index 000000000000..adb857146619 --- /dev/null +++ b/x/circuit/types/query.pb.go @@ -0,0 +1,1404 @@ +// Code generated by protoc-gen-gogo. DO NOT EDIT. +// source: cosmos/circuit/v1/query.proto + +package types + +import ( + context "context" + fmt "fmt" + _ "github.com/cosmos/cosmos-sdk/types/msgservice" + query "github.com/cosmos/cosmos-sdk/types/query" + grpc1 "github.com/cosmos/gogoproto/grpc" + proto "github.com/cosmos/gogoproto/proto" + _ "google.golang.org/genproto/googleapis/api/annotations" + grpc "google.golang.org/grpc" + codes "google.golang.org/grpc/codes" + status "google.golang.org/grpc/status" + io "io" + math "math" + math_bits "math/bits" +) + +// Reference imports to suppress errors if they are not otherwise used. +var _ = proto.Marshal +var _ = fmt.Errorf +var _ = math.Inf + +// This is a compile-time assertion to ensure that this generated file +// is compatible with the proto package it is being compiled against. +// A compilation error at this line likely means your copy of the +// proto package needs to be updated. +const _ = proto.GoGoProtoPackageIsVersion3 // please upgrade the proto package + +// QueryAccountRequest is the request type for the Query/Account RPC method. +type QueryAccountRequest struct { + Address string `protobuf:"bytes,1,opt,name=address,proto3" json:"address,omitempty"` +} + +func (m *QueryAccountRequest) Reset() { *m = QueryAccountRequest{} } +func (m *QueryAccountRequest) String() string { return proto.CompactTextString(m) } +func (*QueryAccountRequest) ProtoMessage() {} +func (*QueryAccountRequest) Descriptor() ([]byte, []int) { + return fileDescriptor_87c65073a3d3c1e1, []int{0} +} +func (m *QueryAccountRequest) XXX_Unmarshal(b []byte) error { + return m.Unmarshal(b) +} +func (m *QueryAccountRequest) XXX_Marshal(b []byte, deterministic bool) ([]byte, error) { + if deterministic { + return xxx_messageInfo_QueryAccountRequest.Marshal(b, m, deterministic) + } else { + b = b[:cap(b)] + n, err := m.MarshalToSizedBuffer(b) + if err != nil { + return nil, err + } + return b[:n], nil + } +} +func (m *QueryAccountRequest) XXX_Merge(src proto.Message) { + xxx_messageInfo_QueryAccountRequest.Merge(m, src) +} +func (m *QueryAccountRequest) XXX_Size() int { + return m.Size() +} +func (m *QueryAccountRequest) XXX_DiscardUnknown() { + xxx_messageInfo_QueryAccountRequest.DiscardUnknown(m) +} + +var xxx_messageInfo_QueryAccountRequest proto.InternalMessageInfo + +func (m *QueryAccountRequest) GetAddress() string { + if m != nil { + return m.Address + } + return "" +} + +// AccountResponse is the response type for the Query/Account RPC method. +type AccountResponse struct { + Permission *Permissions `protobuf:"bytes,1,opt,name=permission,proto3" json:"permission,omitempty"` +} + +func (m *AccountResponse) Reset() { *m = AccountResponse{} } +func (m *AccountResponse) String() string { return proto.CompactTextString(m) } +func (*AccountResponse) ProtoMessage() {} +func (*AccountResponse) Descriptor() ([]byte, []int) { + return fileDescriptor_87c65073a3d3c1e1, []int{1} +} +func (m *AccountResponse) XXX_Unmarshal(b []byte) error { + return m.Unmarshal(b) +} +func (m *AccountResponse) XXX_Marshal(b []byte, deterministic bool) ([]byte, error) { + if deterministic { + return xxx_messageInfo_AccountResponse.Marshal(b, m, deterministic) + } else { + b = b[:cap(b)] + n, err := m.MarshalToSizedBuffer(b) + if err != nil { + return nil, err + } + return b[:n], nil + } +} +func (m *AccountResponse) XXX_Merge(src proto.Message) { + xxx_messageInfo_AccountResponse.Merge(m, src) +} +func (m *AccountResponse) XXX_Size() int { + return m.Size() +} +func (m *AccountResponse) XXX_DiscardUnknown() { + xxx_messageInfo_AccountResponse.DiscardUnknown(m) +} + +var xxx_messageInfo_AccountResponse proto.InternalMessageInfo + +func (m *AccountResponse) GetPermission() *Permissions { + if m != nil { + return m.Permission + } + return nil +} + +// QueryAccountsRequest is the request type for the Query/Accounts RPC method. +type QueryAccountsRequest struct { + // pagination defines an optional pagination for the request. + Pagination *query.PageRequest `protobuf:"bytes,1,opt,name=pagination,proto3" json:"pagination,omitempty"` +} + +func (m *QueryAccountsRequest) Reset() { *m = QueryAccountsRequest{} } +func (m *QueryAccountsRequest) String() string { return proto.CompactTextString(m) } +func (*QueryAccountsRequest) ProtoMessage() {} +func (*QueryAccountsRequest) Descriptor() ([]byte, []int) { + return fileDescriptor_87c65073a3d3c1e1, []int{2} +} +func (m *QueryAccountsRequest) XXX_Unmarshal(b []byte) error { + return m.Unmarshal(b) +} +func (m *QueryAccountsRequest) XXX_Marshal(b []byte, deterministic bool) ([]byte, error) { + if deterministic { + return xxx_messageInfo_QueryAccountsRequest.Marshal(b, m, deterministic) + } else { + b = b[:cap(b)] + n, err := m.MarshalToSizedBuffer(b) + if err != nil { + return nil, err + } + return b[:n], nil + } +} +func (m *QueryAccountsRequest) XXX_Merge(src proto.Message) { + xxx_messageInfo_QueryAccountsRequest.Merge(m, src) +} +func (m *QueryAccountsRequest) XXX_Size() int { + return m.Size() +} +func (m *QueryAccountsRequest) XXX_DiscardUnknown() { + xxx_messageInfo_QueryAccountsRequest.DiscardUnknown(m) +} + +var xxx_messageInfo_QueryAccountsRequest proto.InternalMessageInfo + +func (m *QueryAccountsRequest) GetPagination() *query.PageRequest { + if m != nil { + return m.Pagination + } + return nil +} + +// AccountsResponse is the response type for the Query/Accounts RPC method. +type AccountsResponse struct { + Accounts []*GenesisAccountPermissions `protobuf:"bytes,1,rep,name=accounts,proto3" json:"accounts,omitempty"` + // pagination defines the pagination in the response. + Pagination *query.PageResponse `protobuf:"bytes,2,opt,name=pagination,proto3" json:"pagination,omitempty"` +} + +func (m *AccountsResponse) Reset() { *m = AccountsResponse{} } +func (m *AccountsResponse) String() string { return proto.CompactTextString(m) } +func (*AccountsResponse) ProtoMessage() {} +func (*AccountsResponse) Descriptor() ([]byte, []int) { + return fileDescriptor_87c65073a3d3c1e1, []int{3} +} +func (m *AccountsResponse) XXX_Unmarshal(b []byte) error { + return m.Unmarshal(b) +} +func (m *AccountsResponse) XXX_Marshal(b []byte, deterministic bool) ([]byte, error) { + if deterministic { + return xxx_messageInfo_AccountsResponse.Marshal(b, m, deterministic) + } else { + b = b[:cap(b)] + n, err := m.MarshalToSizedBuffer(b) + if err != nil { + return nil, err + } + return b[:n], nil + } +} +func (m *AccountsResponse) XXX_Merge(src proto.Message) { + xxx_messageInfo_AccountsResponse.Merge(m, src) +} +func (m *AccountsResponse) XXX_Size() int { + return m.Size() +} +func (m *AccountsResponse) XXX_DiscardUnknown() { + xxx_messageInfo_AccountsResponse.DiscardUnknown(m) +} + +var xxx_messageInfo_AccountsResponse proto.InternalMessageInfo + +func (m *AccountsResponse) GetAccounts() []*GenesisAccountPermissions { + if m != nil { + return m.Accounts + } + return nil +} + +func (m *AccountsResponse) GetPagination() *query.PageResponse { + if m != nil { + return m.Pagination + } + return nil +} + +// QueryDisableListRequest is the request type for the Query/DisabledList RPC method. +type QueryDisabledListRequest struct { +} + +func (m *QueryDisabledListRequest) Reset() { *m = QueryDisabledListRequest{} } +func (m *QueryDisabledListRequest) String() string { return proto.CompactTextString(m) } +func (*QueryDisabledListRequest) ProtoMessage() {} +func (*QueryDisabledListRequest) Descriptor() ([]byte, []int) { + return fileDescriptor_87c65073a3d3c1e1, []int{4} +} +func (m *QueryDisabledListRequest) XXX_Unmarshal(b []byte) error { + return m.Unmarshal(b) +} +func (m *QueryDisabledListRequest) XXX_Marshal(b []byte, deterministic bool) ([]byte, error) { + if deterministic { + return xxx_messageInfo_QueryDisabledListRequest.Marshal(b, m, deterministic) + } else { + b = b[:cap(b)] + n, err := m.MarshalToSizedBuffer(b) + if err != nil { + return nil, err + } + return b[:n], nil + } +} +func (m *QueryDisabledListRequest) XXX_Merge(src proto.Message) { + xxx_messageInfo_QueryDisabledListRequest.Merge(m, src) +} +func (m *QueryDisabledListRequest) XXX_Size() int { + return m.Size() +} +func (m *QueryDisabledListRequest) XXX_DiscardUnknown() { + xxx_messageInfo_QueryDisabledListRequest.DiscardUnknown(m) +} + +var xxx_messageInfo_QueryDisabledListRequest proto.InternalMessageInfo + +// DisabledListResponse is the response type for the Query/DisabledList RPC method. +type DisabledListResponse struct { + DisabledList []string `protobuf:"bytes,1,rep,name=disabled_list,json=disabledList,proto3" json:"disabled_list,omitempty"` +} + +func (m *DisabledListResponse) Reset() { *m = DisabledListResponse{} } +func (m *DisabledListResponse) String() string { return proto.CompactTextString(m) } +func (*DisabledListResponse) ProtoMessage() {} +func (*DisabledListResponse) Descriptor() ([]byte, []int) { + return fileDescriptor_87c65073a3d3c1e1, []int{5} +} +func (m *DisabledListResponse) XXX_Unmarshal(b []byte) error { + return m.Unmarshal(b) +} +func (m *DisabledListResponse) XXX_Marshal(b []byte, deterministic bool) ([]byte, error) { + if deterministic { + return xxx_messageInfo_DisabledListResponse.Marshal(b, m, deterministic) + } else { + b = b[:cap(b)] + n, err := m.MarshalToSizedBuffer(b) + if err != nil { + return nil, err + } + return b[:n], nil + } +} +func (m *DisabledListResponse) XXX_Merge(src proto.Message) { + xxx_messageInfo_DisabledListResponse.Merge(m, src) +} +func (m *DisabledListResponse) XXX_Size() int { + return m.Size() +} +func (m *DisabledListResponse) XXX_DiscardUnknown() { + xxx_messageInfo_DisabledListResponse.DiscardUnknown(m) +} + +var xxx_messageInfo_DisabledListResponse proto.InternalMessageInfo + +func (m *DisabledListResponse) GetDisabledList() []string { + if m != nil { + return m.DisabledList + } + return nil +} + +func init() { + proto.RegisterType((*QueryAccountRequest)(nil), "cosmos.circuit.v1.QueryAccountRequest") + proto.RegisterType((*AccountResponse)(nil), "cosmos.circuit.v1.AccountResponse") + proto.RegisterType((*QueryAccountsRequest)(nil), "cosmos.circuit.v1.QueryAccountsRequest") + proto.RegisterType((*AccountsResponse)(nil), "cosmos.circuit.v1.AccountsResponse") + proto.RegisterType((*QueryDisabledListRequest)(nil), "cosmos.circuit.v1.QueryDisabledListRequest") + proto.RegisterType((*DisabledListResponse)(nil), "cosmos.circuit.v1.DisabledListResponse") +} + +func init() { proto.RegisterFile("cosmos/circuit/v1/query.proto", fileDescriptor_87c65073a3d3c1e1) } + +var fileDescriptor_87c65073a3d3c1e1 = []byte{ + // 531 bytes of a gzipped FileDescriptorProto + 0x1f, 0x8b, 0x08, 0x00, 0x00, 0x00, 0x00, 0x00, 0x02, 0xff, 0x84, 0x94, 0xcf, 0x6b, 0x13, 0x41, + 0x14, 0xc7, 0x33, 0x2d, 0xb5, 0xed, 0x6b, 0x45, 0x1d, 0x0b, 0x86, 0x6d, 0xbb, 0xd6, 0x2d, 0x36, + 0xa1, 0x96, 0x1d, 0x12, 0xc1, 0x8b, 0x20, 0x28, 0x62, 0x3d, 0x78, 0x68, 0x73, 0xf4, 0xa0, 0x4c, + 0x76, 0x87, 0x65, 0x30, 0xd9, 0xd9, 0xee, 0xdb, 0x04, 0x8b, 0x08, 0xd2, 0x93, 0xde, 0x44, 0xff, + 0x06, 0xef, 0x1e, 0xfc, 0x23, 0x3c, 0x16, 0xbc, 0x78, 0x94, 0x44, 0xf0, 0xdf, 0x90, 0xec, 0xce, + 0x6c, 0x36, 0x76, 0x6a, 0x8f, 0x33, 0xef, 0x7d, 0xbf, 0xf3, 0x79, 0x3f, 0x76, 0x61, 0x33, 0x50, + 0xd8, 0x57, 0xc8, 0x02, 0x99, 0x06, 0x03, 0x99, 0xb1, 0x61, 0x8b, 0x1d, 0x0d, 0x44, 0x7a, 0xec, + 0x27, 0xa9, 0xca, 0x14, 0xbd, 0x56, 0x84, 0x7d, 0x1d, 0xf6, 0x87, 0x2d, 0x67, 0x57, 0x2b, 0xba, + 0x1c, 0x45, 0x91, 0xcb, 0x86, 0xad, 0xae, 0xc8, 0x78, 0x8b, 0x25, 0x3c, 0x92, 0x31, 0xcf, 0xa4, + 0x8a, 0x0b, 0xb9, 0x73, 0x43, 0xe7, 0xf6, 0x31, 0x9a, 0x38, 0xf7, 0x31, 0xd2, 0x01, 0xcb, 0xb3, + 0xd9, 0x71, 0x22, 0x50, 0x87, 0x37, 0x22, 0xa5, 0xa2, 0x9e, 0x60, 0x3c, 0x91, 0x8c, 0xc7, 0xb1, + 0xca, 0x72, 0x53, 0x13, 0x5d, 0xd7, 0x62, 0xf3, 0x78, 0x95, 0xd8, 0x63, 0x70, 0xfd, 0x70, 0x72, + 0x7c, 0x18, 0x04, 0x6a, 0x10, 0x67, 0x1d, 0x71, 0x34, 0x10, 0x98, 0xd1, 0x3a, 0x2c, 0xf2, 0x30, + 0x4c, 0x05, 0x62, 0x9d, 0x6c, 0x91, 0xe6, 0x72, 0xc7, 0x1c, 0xbd, 0x43, 0xb8, 0x52, 0xe6, 0x62, + 0xa2, 0x62, 0x14, 0xf4, 0x01, 0x40, 0x22, 0xd2, 0xbe, 0x44, 0x94, 0x2a, 0xce, 0xf3, 0x57, 0xda, + 0xae, 0x7f, 0xa6, 0x15, 0xfe, 0x41, 0x99, 0x84, 0x9d, 0x8a, 0xc2, 0x7b, 0x01, 0x6b, 0x55, 0x06, + 0x34, 0x10, 0x4f, 0x00, 0xa6, 0x2d, 0xd2, 0xbe, 0x3b, 0xc6, 0x77, 0xd2, 0x4f, 0xbf, 0xa8, 0x44, + 0xf7, 0xd3, 0x3f, 0xe0, 0x91, 0xd0, 0xda, 0x4e, 0x45, 0xe9, 0x7d, 0x21, 0x70, 0x75, 0xea, 0xad, + 0xa1, 0x9f, 0xc2, 0x12, 0xd7, 0x77, 0x75, 0xb2, 0x35, 0xdf, 0x5c, 0x69, 0xef, 0x59, 0x90, 0xf7, + 0x45, 0x2c, 0x50, 0xa2, 0x56, 0x57, 0x0b, 0x28, 0xd5, 0x74, 0x7f, 0x06, 0x73, 0x2e, 0xc7, 0x6c, + 0x5c, 0x88, 0x59, 0x60, 0xcc, 0x70, 0x3a, 0x50, 0xcf, 0xfb, 0xf0, 0x58, 0x22, 0xef, 0xf6, 0x44, + 0xf8, 0x4c, 0xa2, 0x19, 0x88, 0x77, 0x1f, 0xd6, 0x66, 0xaf, 0x75, 0x19, 0xdb, 0x70, 0x39, 0xd4, + 0xf7, 0x2f, 0x7b, 0x12, 0xb3, 0xbc, 0x96, 0xe5, 0xce, 0x6a, 0x58, 0x49, 0x6e, 0x7f, 0x9b, 0x87, + 0x85, 0xdc, 0x99, 0x7e, 0x20, 0xb0, 0xa8, 0x8b, 0xa1, 0x3b, 0x96, 0x7a, 0x2d, 0xbb, 0xe0, 0x78, + 0x96, 0xbc, 0x7f, 0x56, 0xc0, 0x6b, 0xbf, 0xff, 0xf3, 0x75, 0x97, 0x9c, 0xfc, 0xf8, 0xfd, 0x79, + 0xae, 0x41, 0x6f, 0xb3, 0xb3, 0xeb, 0x6a, 0xba, 0xc5, 0xde, 0xe8, 0x45, 0x7a, 0x4b, 0x4f, 0x08, + 0x2c, 0x99, 0xb1, 0xd0, 0xc6, 0x05, 0x30, 0x66, 0x29, 0x9c, 0xed, 0xf3, 0x69, 0xca, 0xe1, 0x7a, + 0xcd, 0x29, 0xce, 0x26, 0x5d, 0xff, 0x0f, 0x0e, 0xfd, 0x44, 0x60, 0xb5, 0xda, 0x58, 0x7a, 0xe7, + 0x3c, 0x10, 0xcb, 0x54, 0x1c, 0x1b, 0xb5, 0x6d, 0x4c, 0xde, 0xde, 0x14, 0xe8, 0x16, 0xbd, 0x69, + 0x01, 0xd2, 0xf3, 0xca, 0x67, 0xe8, 0x2c, 0xbc, 0x9b, 0x64, 0x3f, 0xba, 0xf7, 0x7d, 0xe4, 0x92, + 0xd3, 0x91, 0x4b, 0x7e, 0x8d, 0x5c, 0xf2, 0x71, 0xec, 0xd6, 0x4e, 0xc7, 0x6e, 0xed, 0xe7, 0xd8, + 0xad, 0x3d, 0xdf, 0x28, 0x0c, 0x30, 0x7c, 0xe5, 0x4b, 0xc5, 0x5e, 0x97, 0x46, 0xf9, 0x4f, 0xa1, + 0x7b, 0x29, 0xff, 0xb4, 0xef, 0xfe, 0x0d, 0x00, 0x00, 0xff, 0xff, 0xab, 0xa8, 0x92, 0x5a, 0xad, + 0x04, 0x00, 0x00, +} + +// Reference imports to suppress errors if they are not otherwise used. +var _ context.Context +var _ grpc.ClientConn + +// This is a compile-time assertion to ensure that this generated file +// is compatible with the grpc package it is being compiled against. +const _ = grpc.SupportPackageIsVersion4 + +// QueryClient is the client API for Query service. +// +// For semantics around ctx use and closing/ending streaming RPCs, please refer to https://godoc.org/google.golang.org/grpc#ClientConn.NewStream. +type QueryClient interface { + // Account returns account permissions. + Account(ctx context.Context, in *QueryAccountRequest, opts ...grpc.CallOption) (*AccountResponse, error) + // Account returns account permissions. + Accounts(ctx context.Context, in *QueryAccountsRequest, opts ...grpc.CallOption) (*AccountsResponse, error) + // DisabledList returns a list of disabled message urls + DisabledList(ctx context.Context, in *QueryDisabledListRequest, opts ...grpc.CallOption) (*DisabledListResponse, error) +} + +type queryClient struct { + cc grpc1.ClientConn +} + +func NewQueryClient(cc grpc1.ClientConn) QueryClient { + return &queryClient{cc} +} + +func (c *queryClient) Account(ctx context.Context, in *QueryAccountRequest, opts ...grpc.CallOption) (*AccountResponse, error) { + out := new(AccountResponse) + err := c.cc.Invoke(ctx, "/cosmos.circuit.v1.Query/Account", in, out, opts...) + if err != nil { + return nil, err + } + return out, nil +} + +func (c *queryClient) Accounts(ctx context.Context, in *QueryAccountsRequest, opts ...grpc.CallOption) (*AccountsResponse, error) { + out := new(AccountsResponse) + err := c.cc.Invoke(ctx, "/cosmos.circuit.v1.Query/Accounts", in, out, opts...) + if err != nil { + return nil, err + } + return out, nil +} + +func (c *queryClient) DisabledList(ctx context.Context, in *QueryDisabledListRequest, opts ...grpc.CallOption) (*DisabledListResponse, error) { + out := new(DisabledListResponse) + err := c.cc.Invoke(ctx, "/cosmos.circuit.v1.Query/DisabledList", in, out, opts...) + if err != nil { + return nil, err + } + return out, nil +} + +// QueryServer is the server API for Query service. +type QueryServer interface { + // Account returns account permissions. + Account(context.Context, *QueryAccountRequest) (*AccountResponse, error) + // Account returns account permissions. + Accounts(context.Context, *QueryAccountsRequest) (*AccountsResponse, error) + // DisabledList returns a list of disabled message urls + DisabledList(context.Context, *QueryDisabledListRequest) (*DisabledListResponse, error) +} + +// UnimplementedQueryServer can be embedded to have forward compatible implementations. +type UnimplementedQueryServer struct { +} + +func (*UnimplementedQueryServer) Account(ctx context.Context, req *QueryAccountRequest) (*AccountResponse, error) { + return nil, status.Errorf(codes.Unimplemented, "method Account not implemented") +} +func (*UnimplementedQueryServer) Accounts(ctx context.Context, req *QueryAccountsRequest) (*AccountsResponse, error) { + return nil, status.Errorf(codes.Unimplemented, "method Accounts not implemented") +} +func (*UnimplementedQueryServer) DisabledList(ctx context.Context, req *QueryDisabledListRequest) (*DisabledListResponse, error) { + return nil, status.Errorf(codes.Unimplemented, "method DisabledList not implemented") +} + +func RegisterQueryServer(s grpc1.Server, srv QueryServer) { + s.RegisterService(&_Query_serviceDesc, srv) +} + +func _Query_Account_Handler(srv interface{}, ctx context.Context, dec func(interface{}) error, interceptor grpc.UnaryServerInterceptor) (interface{}, error) { + in := new(QueryAccountRequest) + if err := dec(in); err != nil { + return nil, err + } + if interceptor == nil { + return srv.(QueryServer).Account(ctx, in) + } + info := &grpc.UnaryServerInfo{ + Server: srv, + FullMethod: "/cosmos.circuit.v1.Query/Account", + } + handler := func(ctx context.Context, req interface{}) (interface{}, error) { + return srv.(QueryServer).Account(ctx, req.(*QueryAccountRequest)) + } + return interceptor(ctx, in, info, handler) +} + +func _Query_Accounts_Handler(srv interface{}, ctx context.Context, dec func(interface{}) error, interceptor grpc.UnaryServerInterceptor) (interface{}, error) { + in := new(QueryAccountsRequest) + if err := dec(in); err != nil { + return nil, err + } + if interceptor == nil { + return srv.(QueryServer).Accounts(ctx, in) + } + info := &grpc.UnaryServerInfo{ + Server: srv, + FullMethod: "/cosmos.circuit.v1.Query/Accounts", + } + handler := func(ctx context.Context, req interface{}) (interface{}, error) { + return srv.(QueryServer).Accounts(ctx, req.(*QueryAccountsRequest)) + } + return interceptor(ctx, in, info, handler) +} + +func _Query_DisabledList_Handler(srv interface{}, ctx context.Context, dec func(interface{}) error, interceptor grpc.UnaryServerInterceptor) (interface{}, error) { + in := new(QueryDisabledListRequest) + if err := dec(in); err != nil { + return nil, err + } + if interceptor == nil { + return srv.(QueryServer).DisabledList(ctx, in) + } + info := &grpc.UnaryServerInfo{ + Server: srv, + FullMethod: "/cosmos.circuit.v1.Query/DisabledList", + } + handler := func(ctx context.Context, req interface{}) (interface{}, error) { + return srv.(QueryServer).DisabledList(ctx, req.(*QueryDisabledListRequest)) + } + return interceptor(ctx, in, info, handler) +} + +var _Query_serviceDesc = grpc.ServiceDesc{ + ServiceName: "cosmos.circuit.v1.Query", + HandlerType: (*QueryServer)(nil), + Methods: []grpc.MethodDesc{ + { + MethodName: "Account", + Handler: _Query_Account_Handler, + }, + { + MethodName: "Accounts", + Handler: _Query_Accounts_Handler, + }, + { + MethodName: "DisabledList", + Handler: _Query_DisabledList_Handler, + }, + }, + Streams: []grpc.StreamDesc{}, + Metadata: "cosmos/circuit/v1/query.proto", +} + +func (m *QueryAccountRequest) Marshal() (dAtA []byte, err error) { + size := m.Size() + dAtA = make([]byte, size) + n, err := m.MarshalToSizedBuffer(dAtA[:size]) + if err != nil { + return nil, err + } + return dAtA[:n], nil +} + +func (m *QueryAccountRequest) MarshalTo(dAtA []byte) (int, error) { + size := m.Size() + return m.MarshalToSizedBuffer(dAtA[:size]) +} + +func (m *QueryAccountRequest) MarshalToSizedBuffer(dAtA []byte) (int, error) { + i := len(dAtA) + _ = i + var l int + _ = l + if len(m.Address) > 0 { + i -= len(m.Address) + copy(dAtA[i:], m.Address) + i = encodeVarintQuery(dAtA, i, uint64(len(m.Address))) + i-- + dAtA[i] = 0xa + } + return len(dAtA) - i, nil +} + +func (m *AccountResponse) Marshal() (dAtA []byte, err error) { + size := m.Size() + dAtA = make([]byte, size) + n, err := m.MarshalToSizedBuffer(dAtA[:size]) + if err != nil { + return nil, err + } + return dAtA[:n], nil +} + +func (m *AccountResponse) MarshalTo(dAtA []byte) (int, error) { + size := m.Size() + return m.MarshalToSizedBuffer(dAtA[:size]) +} + +func (m *AccountResponse) MarshalToSizedBuffer(dAtA []byte) (int, error) { + i := len(dAtA) + _ = i + var l int + _ = l + if m.Permission != nil { + { + size, err := m.Permission.MarshalToSizedBuffer(dAtA[:i]) + if err != nil { + return 0, err + } + i -= size + i = encodeVarintQuery(dAtA, i, uint64(size)) + } + i-- + dAtA[i] = 0xa + } + return len(dAtA) - i, nil +} + +func (m *QueryAccountsRequest) Marshal() (dAtA []byte, err error) { + size := m.Size() + dAtA = make([]byte, size) + n, err := m.MarshalToSizedBuffer(dAtA[:size]) + if err != nil { + return nil, err + } + return dAtA[:n], nil +} + +func (m *QueryAccountsRequest) MarshalTo(dAtA []byte) (int, error) { + size := m.Size() + return m.MarshalToSizedBuffer(dAtA[:size]) +} + +func (m *QueryAccountsRequest) MarshalToSizedBuffer(dAtA []byte) (int, error) { + i := len(dAtA) + _ = i + var l int + _ = l + if m.Pagination != nil { + { + size, err := m.Pagination.MarshalToSizedBuffer(dAtA[:i]) + if err != nil { + return 0, err + } + i -= size + i = encodeVarintQuery(dAtA, i, uint64(size)) + } + i-- + dAtA[i] = 0xa + } + return len(dAtA) - i, nil +} + +func (m *AccountsResponse) Marshal() (dAtA []byte, err error) { + size := m.Size() + dAtA = make([]byte, size) + n, err := m.MarshalToSizedBuffer(dAtA[:size]) + if err != nil { + return nil, err + } + return dAtA[:n], nil +} + +func (m *AccountsResponse) MarshalTo(dAtA []byte) (int, error) { + size := m.Size() + return m.MarshalToSizedBuffer(dAtA[:size]) +} + +func (m *AccountsResponse) MarshalToSizedBuffer(dAtA []byte) (int, error) { + i := len(dAtA) + _ = i + var l int + _ = l + if m.Pagination != nil { + { + size, err := m.Pagination.MarshalToSizedBuffer(dAtA[:i]) + if err != nil { + return 0, err + } + i -= size + i = encodeVarintQuery(dAtA, i, uint64(size)) + } + i-- + dAtA[i] = 0x12 + } + if len(m.Accounts) > 0 { + for iNdEx := len(m.Accounts) - 1; iNdEx >= 0; iNdEx-- { + { + size, err := m.Accounts[iNdEx].MarshalToSizedBuffer(dAtA[:i]) + if err != nil { + return 0, err + } + i -= size + i = encodeVarintQuery(dAtA, i, uint64(size)) + } + i-- + dAtA[i] = 0xa + } + } + return len(dAtA) - i, nil +} + +func (m *QueryDisabledListRequest) Marshal() (dAtA []byte, err error) { + size := m.Size() + dAtA = make([]byte, size) + n, err := m.MarshalToSizedBuffer(dAtA[:size]) + if err != nil { + return nil, err + } + return dAtA[:n], nil +} + +func (m *QueryDisabledListRequest) MarshalTo(dAtA []byte) (int, error) { + size := m.Size() + return m.MarshalToSizedBuffer(dAtA[:size]) +} + +func (m *QueryDisabledListRequest) MarshalToSizedBuffer(dAtA []byte) (int, error) { + i := len(dAtA) + _ = i + var l int + _ = l + return len(dAtA) - i, nil +} + +func (m *DisabledListResponse) Marshal() (dAtA []byte, err error) { + size := m.Size() + dAtA = make([]byte, size) + n, err := m.MarshalToSizedBuffer(dAtA[:size]) + if err != nil { + return nil, err + } + return dAtA[:n], nil +} + +func (m *DisabledListResponse) MarshalTo(dAtA []byte) (int, error) { + size := m.Size() + return m.MarshalToSizedBuffer(dAtA[:size]) +} + +func (m *DisabledListResponse) MarshalToSizedBuffer(dAtA []byte) (int, error) { + i := len(dAtA) + _ = i + var l int + _ = l + if len(m.DisabledList) > 0 { + for iNdEx := len(m.DisabledList) - 1; iNdEx >= 0; iNdEx-- { + i -= len(m.DisabledList[iNdEx]) + copy(dAtA[i:], m.DisabledList[iNdEx]) + i = encodeVarintQuery(dAtA, i, uint64(len(m.DisabledList[iNdEx]))) + i-- + dAtA[i] = 0xa + } + } + return len(dAtA) - i, nil +} + +func encodeVarintQuery(dAtA []byte, offset int, v uint64) int { + offset -= sovQuery(v) + base := offset + for v >= 1<<7 { + dAtA[offset] = uint8(v&0x7f | 0x80) + v >>= 7 + offset++ + } + dAtA[offset] = uint8(v) + return base +} +func (m *QueryAccountRequest) Size() (n int) { + if m == nil { + return 0 + } + var l int + _ = l + l = len(m.Address) + if l > 0 { + n += 1 + l + sovQuery(uint64(l)) + } + return n +} + +func (m *AccountResponse) Size() (n int) { + if m == nil { + return 0 + } + var l int + _ = l + if m.Permission != nil { + l = m.Permission.Size() + n += 1 + l + sovQuery(uint64(l)) + } + return n +} + +func (m *QueryAccountsRequest) Size() (n int) { + if m == nil { + return 0 + } + var l int + _ = l + if m.Pagination != nil { + l = m.Pagination.Size() + n += 1 + l + sovQuery(uint64(l)) + } + return n +} + +func (m *AccountsResponse) Size() (n int) { + if m == nil { + return 0 + } + var l int + _ = l + if len(m.Accounts) > 0 { + for _, e := range m.Accounts { + l = e.Size() + n += 1 + l + sovQuery(uint64(l)) + } + } + if m.Pagination != nil { + l = m.Pagination.Size() + n += 1 + l + sovQuery(uint64(l)) + } + return n +} + +func (m *QueryDisabledListRequest) Size() (n int) { + if m == nil { + return 0 + } + var l int + _ = l + return n +} + +func (m *DisabledListResponse) Size() (n int) { + if m == nil { + return 0 + } + var l int + _ = l + if len(m.DisabledList) > 0 { + for _, s := range m.DisabledList { + l = len(s) + n += 1 + l + sovQuery(uint64(l)) + } + } + return n +} + +func sovQuery(x uint64) (n int) { + return (math_bits.Len64(x|1) + 6) / 7 +} +func sozQuery(x uint64) (n int) { + return sovQuery(uint64((x << 1) ^ uint64((int64(x) >> 63)))) +} +func (m *QueryAccountRequest) Unmarshal(dAtA []byte) error { + l := len(dAtA) + iNdEx := 0 + for iNdEx < l { + preIndex := iNdEx + var wire uint64 + for shift := uint(0); ; shift += 7 { + if shift >= 64 { + return ErrIntOverflowQuery + } + if iNdEx >= l { + return io.ErrUnexpectedEOF + } + b := dAtA[iNdEx] + iNdEx++ + wire |= uint64(b&0x7F) << shift + if b < 0x80 { + break + } + } + fieldNum := int32(wire >> 3) + wireType := int(wire & 0x7) + if wireType == 4 { + return fmt.Errorf("proto: QueryAccountRequest: wiretype end group for non-group") + } + if fieldNum <= 0 { + return fmt.Errorf("proto: QueryAccountRequest: illegal tag %d (wire type %d)", fieldNum, wire) + } + switch fieldNum { + case 1: + if wireType != 2 { + return fmt.Errorf("proto: wrong wireType = %d for field Address", wireType) + } + var stringLen uint64 + for shift := uint(0); ; shift += 7 { + if shift >= 64 { + return ErrIntOverflowQuery + } + if iNdEx >= l { + return io.ErrUnexpectedEOF + } + b := dAtA[iNdEx] + iNdEx++ + stringLen |= uint64(b&0x7F) << shift + if b < 0x80 { + break + } + } + intStringLen := int(stringLen) + if intStringLen < 0 { + return ErrInvalidLengthQuery + } + postIndex := iNdEx + intStringLen + if postIndex < 0 { + return ErrInvalidLengthQuery + } + if postIndex > l { + return io.ErrUnexpectedEOF + } + m.Address = string(dAtA[iNdEx:postIndex]) + iNdEx = postIndex + default: + iNdEx = preIndex + skippy, err := skipQuery(dAtA[iNdEx:]) + if err != nil { + return err + } + if (skippy < 0) || (iNdEx+skippy) < 0 { + return ErrInvalidLengthQuery + } + if (iNdEx + skippy) > l { + return io.ErrUnexpectedEOF + } + iNdEx += skippy + } + } + + if iNdEx > l { + return io.ErrUnexpectedEOF + } + return nil +} +func (m *AccountResponse) Unmarshal(dAtA []byte) error { + l := len(dAtA) + iNdEx := 0 + for iNdEx < l { + preIndex := iNdEx + var wire uint64 + for shift := uint(0); ; shift += 7 { + if shift >= 64 { + return ErrIntOverflowQuery + } + if iNdEx >= l { + return io.ErrUnexpectedEOF + } + b := dAtA[iNdEx] + iNdEx++ + wire |= uint64(b&0x7F) << shift + if b < 0x80 { + break + } + } + fieldNum := int32(wire >> 3) + wireType := int(wire & 0x7) + if wireType == 4 { + return fmt.Errorf("proto: AccountResponse: wiretype end group for non-group") + } + if fieldNum <= 0 { + return fmt.Errorf("proto: AccountResponse: illegal tag %d (wire type %d)", fieldNum, wire) + } + switch fieldNum { + case 1: + if wireType != 2 { + return fmt.Errorf("proto: wrong wireType = %d for field Permission", wireType) + } + var msglen int + for shift := uint(0); ; shift += 7 { + if shift >= 64 { + return ErrIntOverflowQuery + } + if iNdEx >= l { + return io.ErrUnexpectedEOF + } + b := dAtA[iNdEx] + iNdEx++ + msglen |= int(b&0x7F) << shift + if b < 0x80 { + break + } + } + if msglen < 0 { + return ErrInvalidLengthQuery + } + postIndex := iNdEx + msglen + if postIndex < 0 { + return ErrInvalidLengthQuery + } + if postIndex > l { + return io.ErrUnexpectedEOF + } + if m.Permission == nil { + m.Permission = &Permissions{} + } + if err := m.Permission.Unmarshal(dAtA[iNdEx:postIndex]); err != nil { + return err + } + iNdEx = postIndex + default: + iNdEx = preIndex + skippy, err := skipQuery(dAtA[iNdEx:]) + if err != nil { + return err + } + if (skippy < 0) || (iNdEx+skippy) < 0 { + return ErrInvalidLengthQuery + } + if (iNdEx + skippy) > l { + return io.ErrUnexpectedEOF + } + iNdEx += skippy + } + } + + if iNdEx > l { + return io.ErrUnexpectedEOF + } + return nil +} +func (m *QueryAccountsRequest) Unmarshal(dAtA []byte) error { + l := len(dAtA) + iNdEx := 0 + for iNdEx < l { + preIndex := iNdEx + var wire uint64 + for shift := uint(0); ; shift += 7 { + if shift >= 64 { + return ErrIntOverflowQuery + } + if iNdEx >= l { + return io.ErrUnexpectedEOF + } + b := dAtA[iNdEx] + iNdEx++ + wire |= uint64(b&0x7F) << shift + if b < 0x80 { + break + } + } + fieldNum := int32(wire >> 3) + wireType := int(wire & 0x7) + if wireType == 4 { + return fmt.Errorf("proto: QueryAccountsRequest: wiretype end group for non-group") + } + if fieldNum <= 0 { + return fmt.Errorf("proto: QueryAccountsRequest: illegal tag %d (wire type %d)", fieldNum, wire) + } + switch fieldNum { + case 1: + if wireType != 2 { + return fmt.Errorf("proto: wrong wireType = %d for field Pagination", wireType) + } + var msglen int + for shift := uint(0); ; shift += 7 { + if shift >= 64 { + return ErrIntOverflowQuery + } + if iNdEx >= l { + return io.ErrUnexpectedEOF + } + b := dAtA[iNdEx] + iNdEx++ + msglen |= int(b&0x7F) << shift + if b < 0x80 { + break + } + } + if msglen < 0 { + return ErrInvalidLengthQuery + } + postIndex := iNdEx + msglen + if postIndex < 0 { + return ErrInvalidLengthQuery + } + if postIndex > l { + return io.ErrUnexpectedEOF + } + if m.Pagination == nil { + m.Pagination = &query.PageRequest{} + } + if err := m.Pagination.Unmarshal(dAtA[iNdEx:postIndex]); err != nil { + return err + } + iNdEx = postIndex + default: + iNdEx = preIndex + skippy, err := skipQuery(dAtA[iNdEx:]) + if err != nil { + return err + } + if (skippy < 0) || (iNdEx+skippy) < 0 { + return ErrInvalidLengthQuery + } + if (iNdEx + skippy) > l { + return io.ErrUnexpectedEOF + } + iNdEx += skippy + } + } + + if iNdEx > l { + return io.ErrUnexpectedEOF + } + return nil +} +func (m *AccountsResponse) Unmarshal(dAtA []byte) error { + l := len(dAtA) + iNdEx := 0 + for iNdEx < l { + preIndex := iNdEx + var wire uint64 + for shift := uint(0); ; shift += 7 { + if shift >= 64 { + return ErrIntOverflowQuery + } + if iNdEx >= l { + return io.ErrUnexpectedEOF + } + b := dAtA[iNdEx] + iNdEx++ + wire |= uint64(b&0x7F) << shift + if b < 0x80 { + break + } + } + fieldNum := int32(wire >> 3) + wireType := int(wire & 0x7) + if wireType == 4 { + return fmt.Errorf("proto: AccountsResponse: wiretype end group for non-group") + } + if fieldNum <= 0 { + return fmt.Errorf("proto: AccountsResponse: illegal tag %d (wire type %d)", fieldNum, wire) + } + switch fieldNum { + case 1: + if wireType != 2 { + return fmt.Errorf("proto: wrong wireType = %d for field Accounts", wireType) + } + var msglen int + for shift := uint(0); ; shift += 7 { + if shift >= 64 { + return ErrIntOverflowQuery + } + if iNdEx >= l { + return io.ErrUnexpectedEOF + } + b := dAtA[iNdEx] + iNdEx++ + msglen |= int(b&0x7F) << shift + if b < 0x80 { + break + } + } + if msglen < 0 { + return ErrInvalidLengthQuery + } + postIndex := iNdEx + msglen + if postIndex < 0 { + return ErrInvalidLengthQuery + } + if postIndex > l { + return io.ErrUnexpectedEOF + } + m.Accounts = append(m.Accounts, &GenesisAccountPermissions{}) + if err := m.Accounts[len(m.Accounts)-1].Unmarshal(dAtA[iNdEx:postIndex]); err != nil { + return err + } + iNdEx = postIndex + case 2: + if wireType != 2 { + return fmt.Errorf("proto: wrong wireType = %d for field Pagination", wireType) + } + var msglen int + for shift := uint(0); ; shift += 7 { + if shift >= 64 { + return ErrIntOverflowQuery + } + if iNdEx >= l { + return io.ErrUnexpectedEOF + } + b := dAtA[iNdEx] + iNdEx++ + msglen |= int(b&0x7F) << shift + if b < 0x80 { + break + } + } + if msglen < 0 { + return ErrInvalidLengthQuery + } + postIndex := iNdEx + msglen + if postIndex < 0 { + return ErrInvalidLengthQuery + } + if postIndex > l { + return io.ErrUnexpectedEOF + } + if m.Pagination == nil { + m.Pagination = &query.PageResponse{} + } + if err := m.Pagination.Unmarshal(dAtA[iNdEx:postIndex]); err != nil { + return err + } + iNdEx = postIndex + default: + iNdEx = preIndex + skippy, err := skipQuery(dAtA[iNdEx:]) + if err != nil { + return err + } + if (skippy < 0) || (iNdEx+skippy) < 0 { + return ErrInvalidLengthQuery + } + if (iNdEx + skippy) > l { + return io.ErrUnexpectedEOF + } + iNdEx += skippy + } + } + + if iNdEx > l { + return io.ErrUnexpectedEOF + } + return nil +} +func (m *QueryDisabledListRequest) Unmarshal(dAtA []byte) error { + l := len(dAtA) + iNdEx := 0 + for iNdEx < l { + preIndex := iNdEx + var wire uint64 + for shift := uint(0); ; shift += 7 { + if shift >= 64 { + return ErrIntOverflowQuery + } + if iNdEx >= l { + return io.ErrUnexpectedEOF + } + b := dAtA[iNdEx] + iNdEx++ + wire |= uint64(b&0x7F) << shift + if b < 0x80 { + break + } + } + fieldNum := int32(wire >> 3) + wireType := int(wire & 0x7) + if wireType == 4 { + return fmt.Errorf("proto: QueryDisabledListRequest: wiretype end group for non-group") + } + if fieldNum <= 0 { + return fmt.Errorf("proto: QueryDisabledListRequest: illegal tag %d (wire type %d)", fieldNum, wire) + } + switch fieldNum { + default: + iNdEx = preIndex + skippy, err := skipQuery(dAtA[iNdEx:]) + if err != nil { + return err + } + if (skippy < 0) || (iNdEx+skippy) < 0 { + return ErrInvalidLengthQuery + } + if (iNdEx + skippy) > l { + return io.ErrUnexpectedEOF + } + iNdEx += skippy + } + } + + if iNdEx > l { + return io.ErrUnexpectedEOF + } + return nil +} +func (m *DisabledListResponse) Unmarshal(dAtA []byte) error { + l := len(dAtA) + iNdEx := 0 + for iNdEx < l { + preIndex := iNdEx + var wire uint64 + for shift := uint(0); ; shift += 7 { + if shift >= 64 { + return ErrIntOverflowQuery + } + if iNdEx >= l { + return io.ErrUnexpectedEOF + } + b := dAtA[iNdEx] + iNdEx++ + wire |= uint64(b&0x7F) << shift + if b < 0x80 { + break + } + } + fieldNum := int32(wire >> 3) + wireType := int(wire & 0x7) + if wireType == 4 { + return fmt.Errorf("proto: DisabledListResponse: wiretype end group for non-group") + } + if fieldNum <= 0 { + return fmt.Errorf("proto: DisabledListResponse: illegal tag %d (wire type %d)", fieldNum, wire) + } + switch fieldNum { + case 1: + if wireType != 2 { + return fmt.Errorf("proto: wrong wireType = %d for field DisabledList", wireType) + } + var stringLen uint64 + for shift := uint(0); ; shift += 7 { + if shift >= 64 { + return ErrIntOverflowQuery + } + if iNdEx >= l { + return io.ErrUnexpectedEOF + } + b := dAtA[iNdEx] + iNdEx++ + stringLen |= uint64(b&0x7F) << shift + if b < 0x80 { + break + } + } + intStringLen := int(stringLen) + if intStringLen < 0 { + return ErrInvalidLengthQuery + } + postIndex := iNdEx + intStringLen + if postIndex < 0 { + return ErrInvalidLengthQuery + } + if postIndex > l { + return io.ErrUnexpectedEOF + } + m.DisabledList = append(m.DisabledList, string(dAtA[iNdEx:postIndex])) + iNdEx = postIndex + default: + iNdEx = preIndex + skippy, err := skipQuery(dAtA[iNdEx:]) + if err != nil { + return err + } + if (skippy < 0) || (iNdEx+skippy) < 0 { + return ErrInvalidLengthQuery + } + if (iNdEx + skippy) > l { + return io.ErrUnexpectedEOF + } + iNdEx += skippy + } + } + + if iNdEx > l { + return io.ErrUnexpectedEOF + } + return nil +} +func skipQuery(dAtA []byte) (n int, err error) { + l := len(dAtA) + iNdEx := 0 + depth := 0 + for iNdEx < l { + var wire uint64 + for shift := uint(0); ; shift += 7 { + if shift >= 64 { + return 0, ErrIntOverflowQuery + } + if iNdEx >= l { + return 0, io.ErrUnexpectedEOF + } + b := dAtA[iNdEx] + iNdEx++ + wire |= (uint64(b) & 0x7F) << shift + if b < 0x80 { + break + } + } + wireType := int(wire & 0x7) + switch wireType { + case 0: + for shift := uint(0); ; shift += 7 { + if shift >= 64 { + return 0, ErrIntOverflowQuery + } + if iNdEx >= l { + return 0, io.ErrUnexpectedEOF + } + iNdEx++ + if dAtA[iNdEx-1] < 0x80 { + break + } + } + case 1: + iNdEx += 8 + case 2: + var length int + for shift := uint(0); ; shift += 7 { + if shift >= 64 { + return 0, ErrIntOverflowQuery + } + if iNdEx >= l { + return 0, io.ErrUnexpectedEOF + } + b := dAtA[iNdEx] + iNdEx++ + length |= (int(b) & 0x7F) << shift + if b < 0x80 { + break + } + } + if length < 0 { + return 0, ErrInvalidLengthQuery + } + iNdEx += length + case 3: + depth++ + case 4: + if depth == 0 { + return 0, ErrUnexpectedEndOfGroupQuery + } + depth-- + case 5: + iNdEx += 4 + default: + return 0, fmt.Errorf("proto: illegal wireType %d", wireType) + } + if iNdEx < 0 { + return 0, ErrInvalidLengthQuery + } + if depth == 0 { + return iNdEx, nil + } + } + return 0, io.ErrUnexpectedEOF +} + +var ( + ErrInvalidLengthQuery = fmt.Errorf("proto: negative length found during unmarshaling") + ErrIntOverflowQuery = fmt.Errorf("proto: integer overflow") + ErrUnexpectedEndOfGroupQuery = fmt.Errorf("proto: unexpected end of group") +) diff --git a/x/circuit/types/query.pb.gw.go b/x/circuit/types/query.pb.gw.go new file mode 100644 index 000000000000..706b426cc1c0 --- /dev/null +++ b/x/circuit/types/query.pb.gw.go @@ -0,0 +1,337 @@ +// Code generated by protoc-gen-grpc-gateway. DO NOT EDIT. +// source: cosmos/circuit/v1/query.proto + +/* +Package types is a reverse proxy. + +It translates gRPC into RESTful JSON APIs. +*/ +package types + +import ( + "context" + "io" + "net/http" + + "github.com/golang/protobuf/descriptor" + "github.com/golang/protobuf/proto" + "github.com/grpc-ecosystem/grpc-gateway/runtime" + "github.com/grpc-ecosystem/grpc-gateway/utilities" + "google.golang.org/grpc" + "google.golang.org/grpc/codes" + "google.golang.org/grpc/grpclog" + "google.golang.org/grpc/metadata" + "google.golang.org/grpc/status" +) + +// Suppress "imported and not used" errors +var _ codes.Code +var _ io.Reader +var _ status.Status +var _ = runtime.String +var _ = utilities.NewDoubleArray +var _ = descriptor.ForMessage +var _ = metadata.Join + +func request_Query_Account_0(ctx context.Context, marshaler runtime.Marshaler, client QueryClient, req *http.Request, pathParams map[string]string) (proto.Message, runtime.ServerMetadata, error) { + var protoReq QueryAccountRequest + var metadata runtime.ServerMetadata + + var ( + val string + ok bool + err error + _ = err + ) + + val, ok = pathParams["address"] + if !ok { + return nil, metadata, status.Errorf(codes.InvalidArgument, "missing parameter %s", "address") + } + + protoReq.Address, err = runtime.String(val) + + if err != nil { + return nil, metadata, status.Errorf(codes.InvalidArgument, "type mismatch, parameter: %s, error: %v", "address", err) + } + + msg, err := client.Account(ctx, &protoReq, grpc.Header(&metadata.HeaderMD), grpc.Trailer(&metadata.TrailerMD)) + return msg, metadata, err + +} + +func local_request_Query_Account_0(ctx context.Context, marshaler runtime.Marshaler, server QueryServer, req *http.Request, pathParams map[string]string) (proto.Message, runtime.ServerMetadata, error) { + var protoReq QueryAccountRequest + var metadata runtime.ServerMetadata + + var ( + val string + ok bool + err error + _ = err + ) + + val, ok = pathParams["address"] + if !ok { + return nil, metadata, status.Errorf(codes.InvalidArgument, "missing parameter %s", "address") + } + + protoReq.Address, err = runtime.String(val) + + if err != nil { + return nil, metadata, status.Errorf(codes.InvalidArgument, "type mismatch, parameter: %s, error: %v", "address", err) + } + + msg, err := server.Account(ctx, &protoReq) + return msg, metadata, err + +} + +var ( + filter_Query_Accounts_0 = &utilities.DoubleArray{Encoding: map[string]int{}, Base: []int(nil), Check: []int(nil)} +) + +func request_Query_Accounts_0(ctx context.Context, marshaler runtime.Marshaler, client QueryClient, req *http.Request, pathParams map[string]string) (proto.Message, runtime.ServerMetadata, error) { + var protoReq QueryAccountsRequest + var metadata runtime.ServerMetadata + + if err := req.ParseForm(); err != nil { + return nil, metadata, status.Errorf(codes.InvalidArgument, "%v", err) + } + if err := runtime.PopulateQueryParameters(&protoReq, req.Form, filter_Query_Accounts_0); err != nil { + return nil, metadata, status.Errorf(codes.InvalidArgument, "%v", err) + } + + msg, err := client.Accounts(ctx, &protoReq, grpc.Header(&metadata.HeaderMD), grpc.Trailer(&metadata.TrailerMD)) + return msg, metadata, err + +} + +func local_request_Query_Accounts_0(ctx context.Context, marshaler runtime.Marshaler, server QueryServer, req *http.Request, pathParams map[string]string) (proto.Message, runtime.ServerMetadata, error) { + var protoReq QueryAccountsRequest + var metadata runtime.ServerMetadata + + if err := req.ParseForm(); err != nil { + return nil, metadata, status.Errorf(codes.InvalidArgument, "%v", err) + } + if err := runtime.PopulateQueryParameters(&protoReq, req.Form, filter_Query_Accounts_0); err != nil { + return nil, metadata, status.Errorf(codes.InvalidArgument, "%v", err) + } + + msg, err := server.Accounts(ctx, &protoReq) + return msg, metadata, err + +} + +func request_Query_DisabledList_0(ctx context.Context, marshaler runtime.Marshaler, client QueryClient, req *http.Request, pathParams map[string]string) (proto.Message, runtime.ServerMetadata, error) { + var protoReq QueryDisabledListRequest + var metadata runtime.ServerMetadata + + msg, err := client.DisabledList(ctx, &protoReq, grpc.Header(&metadata.HeaderMD), grpc.Trailer(&metadata.TrailerMD)) + return msg, metadata, err + +} + +func local_request_Query_DisabledList_0(ctx context.Context, marshaler runtime.Marshaler, server QueryServer, req *http.Request, pathParams map[string]string) (proto.Message, runtime.ServerMetadata, error) { + var protoReq QueryDisabledListRequest + var metadata runtime.ServerMetadata + + msg, err := server.DisabledList(ctx, &protoReq) + return msg, metadata, err + +} + +// RegisterQueryHandlerServer registers the http handlers for service Query to "mux". +// UnaryRPC :call QueryServer directly. +// StreamingRPC :currently unsupported pending https://github.com/grpc/grpc-go/issues/906. +// Note that using this registration option will cause many gRPC library features to stop working. Consider using RegisterQueryHandlerFromEndpoint instead. +func RegisterQueryHandlerServer(ctx context.Context, mux *runtime.ServeMux, server QueryServer) error { + + mux.Handle("GET", pattern_Query_Account_0, func(w http.ResponseWriter, req *http.Request, pathParams map[string]string) { + ctx, cancel := context.WithCancel(req.Context()) + defer cancel() + var stream runtime.ServerTransportStream + ctx = grpc.NewContextWithServerTransportStream(ctx, &stream) + inboundMarshaler, outboundMarshaler := runtime.MarshalerForRequest(mux, req) + rctx, err := runtime.AnnotateIncomingContext(ctx, mux, req) + if err != nil { + runtime.HTTPError(ctx, mux, outboundMarshaler, w, req, err) + return + } + resp, md, err := local_request_Query_Account_0(rctx, inboundMarshaler, server, req, pathParams) + md.HeaderMD, md.TrailerMD = metadata.Join(md.HeaderMD, stream.Header()), metadata.Join(md.TrailerMD, stream.Trailer()) + ctx = runtime.NewServerMetadataContext(ctx, md) + if err != nil { + runtime.HTTPError(ctx, mux, outboundMarshaler, w, req, err) + return + } + + forward_Query_Account_0(ctx, mux, outboundMarshaler, w, req, resp, mux.GetForwardResponseOptions()...) + + }) + + mux.Handle("GET", pattern_Query_Accounts_0, func(w http.ResponseWriter, req *http.Request, pathParams map[string]string) { + ctx, cancel := context.WithCancel(req.Context()) + defer cancel() + var stream runtime.ServerTransportStream + ctx = grpc.NewContextWithServerTransportStream(ctx, &stream) + inboundMarshaler, outboundMarshaler := runtime.MarshalerForRequest(mux, req) + rctx, err := runtime.AnnotateIncomingContext(ctx, mux, req) + if err != nil { + runtime.HTTPError(ctx, mux, outboundMarshaler, w, req, err) + return + } + resp, md, err := local_request_Query_Accounts_0(rctx, inboundMarshaler, server, req, pathParams) + md.HeaderMD, md.TrailerMD = metadata.Join(md.HeaderMD, stream.Header()), metadata.Join(md.TrailerMD, stream.Trailer()) + ctx = runtime.NewServerMetadataContext(ctx, md) + if err != nil { + runtime.HTTPError(ctx, mux, outboundMarshaler, w, req, err) + return + } + + forward_Query_Accounts_0(ctx, mux, outboundMarshaler, w, req, resp, mux.GetForwardResponseOptions()...) + + }) + + mux.Handle("GET", pattern_Query_DisabledList_0, func(w http.ResponseWriter, req *http.Request, pathParams map[string]string) { + ctx, cancel := context.WithCancel(req.Context()) + defer cancel() + var stream runtime.ServerTransportStream + ctx = grpc.NewContextWithServerTransportStream(ctx, &stream) + inboundMarshaler, outboundMarshaler := runtime.MarshalerForRequest(mux, req) + rctx, err := runtime.AnnotateIncomingContext(ctx, mux, req) + if err != nil { + runtime.HTTPError(ctx, mux, outboundMarshaler, w, req, err) + return + } + resp, md, err := local_request_Query_DisabledList_0(rctx, inboundMarshaler, server, req, pathParams) + md.HeaderMD, md.TrailerMD = metadata.Join(md.HeaderMD, stream.Header()), metadata.Join(md.TrailerMD, stream.Trailer()) + ctx = runtime.NewServerMetadataContext(ctx, md) + if err != nil { + runtime.HTTPError(ctx, mux, outboundMarshaler, w, req, err) + return + } + + forward_Query_DisabledList_0(ctx, mux, outboundMarshaler, w, req, resp, mux.GetForwardResponseOptions()...) + + }) + + return nil +} + +// RegisterQueryHandlerFromEndpoint is same as RegisterQueryHandler but +// automatically dials to "endpoint" and closes the connection when "ctx" gets done. +func RegisterQueryHandlerFromEndpoint(ctx context.Context, mux *runtime.ServeMux, endpoint string, opts []grpc.DialOption) (err error) { + conn, err := grpc.Dial(endpoint, opts...) + if err != nil { + return err + } + defer func() { + if err != nil { + if cerr := conn.Close(); cerr != nil { + grpclog.Infof("Failed to close conn to %s: %v", endpoint, cerr) + } + return + } + go func() { + <-ctx.Done() + if cerr := conn.Close(); cerr != nil { + grpclog.Infof("Failed to close conn to %s: %v", endpoint, cerr) + } + }() + }() + + return RegisterQueryHandler(ctx, mux, conn) +} + +// RegisterQueryHandler registers the http handlers for service Query to "mux". +// The handlers forward requests to the grpc endpoint over "conn". +func RegisterQueryHandler(ctx context.Context, mux *runtime.ServeMux, conn *grpc.ClientConn) error { + return RegisterQueryHandlerClient(ctx, mux, NewQueryClient(conn)) +} + +// RegisterQueryHandlerClient registers the http handlers for service Query +// to "mux". The handlers forward requests to the grpc endpoint over the given implementation of "QueryClient". +// Note: the gRPC framework executes interceptors within the gRPC handler. If the passed in "QueryClient" +// doesn't go through the normal gRPC flow (creating a gRPC client etc.) then it will be up to the passed in +// "QueryClient" to call the correct interceptors. +func RegisterQueryHandlerClient(ctx context.Context, mux *runtime.ServeMux, client QueryClient) error { + + mux.Handle("GET", pattern_Query_Account_0, func(w http.ResponseWriter, req *http.Request, pathParams map[string]string) { + ctx, cancel := context.WithCancel(req.Context()) + defer cancel() + inboundMarshaler, outboundMarshaler := runtime.MarshalerForRequest(mux, req) + rctx, err := runtime.AnnotateContext(ctx, mux, req) + if err != nil { + runtime.HTTPError(ctx, mux, outboundMarshaler, w, req, err) + return + } + resp, md, err := request_Query_Account_0(rctx, inboundMarshaler, client, req, pathParams) + ctx = runtime.NewServerMetadataContext(ctx, md) + if err != nil { + runtime.HTTPError(ctx, mux, outboundMarshaler, w, req, err) + return + } + + forward_Query_Account_0(ctx, mux, outboundMarshaler, w, req, resp, mux.GetForwardResponseOptions()...) + + }) + + mux.Handle("GET", pattern_Query_Accounts_0, func(w http.ResponseWriter, req *http.Request, pathParams map[string]string) { + ctx, cancel := context.WithCancel(req.Context()) + defer cancel() + inboundMarshaler, outboundMarshaler := runtime.MarshalerForRequest(mux, req) + rctx, err := runtime.AnnotateContext(ctx, mux, req) + if err != nil { + runtime.HTTPError(ctx, mux, outboundMarshaler, w, req, err) + return + } + resp, md, err := request_Query_Accounts_0(rctx, inboundMarshaler, client, req, pathParams) + ctx = runtime.NewServerMetadataContext(ctx, md) + if err != nil { + runtime.HTTPError(ctx, mux, outboundMarshaler, w, req, err) + return + } + + forward_Query_Accounts_0(ctx, mux, outboundMarshaler, w, req, resp, mux.GetForwardResponseOptions()...) + + }) + + mux.Handle("GET", pattern_Query_DisabledList_0, func(w http.ResponseWriter, req *http.Request, pathParams map[string]string) { + ctx, cancel := context.WithCancel(req.Context()) + defer cancel() + inboundMarshaler, outboundMarshaler := runtime.MarshalerForRequest(mux, req) + rctx, err := runtime.AnnotateContext(ctx, mux, req) + if err != nil { + runtime.HTTPError(ctx, mux, outboundMarshaler, w, req, err) + return + } + resp, md, err := request_Query_DisabledList_0(rctx, inboundMarshaler, client, req, pathParams) + ctx = runtime.NewServerMetadataContext(ctx, md) + if err != nil { + runtime.HTTPError(ctx, mux, outboundMarshaler, w, req, err) + return + } + + forward_Query_DisabledList_0(ctx, mux, outboundMarshaler, w, req, resp, mux.GetForwardResponseOptions()...) + + }) + + return nil +} + +var ( + pattern_Query_Account_0 = runtime.MustPattern(runtime.NewPattern(1, []int{2, 0, 2, 1, 2, 2, 2, 3, 1, 0, 4, 1, 5, 4}, []string{"cosmos", "circuit", "v1", "accounts", "address"}, "", runtime.AssumeColonVerbOpt(false))) + + pattern_Query_Accounts_0 = runtime.MustPattern(runtime.NewPattern(1, []int{2, 0, 2, 1, 2, 2, 2, 3}, []string{"cosmos", "circuit", "v1", "accounts"}, "", runtime.AssumeColonVerbOpt(false))) + + pattern_Query_DisabledList_0 = runtime.MustPattern(runtime.NewPattern(1, []int{2, 0, 2, 1, 2, 2, 2, 3}, []string{"cosmos", "circuit", "v1", "disable_list"}, "", runtime.AssumeColonVerbOpt(false))) +) + +var ( + forward_Query_Account_0 = runtime.ForwardResponseMessage + + forward_Query_Accounts_0 = runtime.ForwardResponseMessage + + forward_Query_DisabledList_0 = runtime.ForwardResponseMessage +) diff --git a/x/circuit/types/tx.pb.go b/x/circuit/types/tx.pb.go index 1356453d92db..dcd824939bb5 100644 --- a/x/circuit/types/tx.pb.go +++ b/x/circuit/types/tx.pb.go @@ -28,48 +28,6 @@ var _ = math.Inf // proto package needs to be updated. const _ = proto.GoGoProtoPackageIsVersion3 // please upgrade the proto package -// Level is the permission level. -type CircuitBreakerPermissions_Level int32 - -const ( - // LEVEL_NONE_UNSPECIFIED indicates that the account will have no circuit - // breaker permissions. - CircuitBreakerPermissions_LEVEL_NONE_UNSPECIFIED CircuitBreakerPermissions_Level = 0 - // LEVEL_SOME_MSGS indicates that the account will have permission to - // trip or reset the circuit breaker for some Msg type URLs. If this level - // is chosen, a non-empty list of Msg type URLs must be provided in - // limit_type_urls. - CircuitBreakerPermissions_LEVEL_SOME_MSGS CircuitBreakerPermissions_Level = 1 - // LEVEL_ALL_MSGS indicates that the account can trip or reset the circuit - // breaker for Msg's of all type URLs. - CircuitBreakerPermissions_LEVEL_ALL_MSGS CircuitBreakerPermissions_Level = 2 - // LEVEL_SUPER_ADMIN indicates that the account can take all circuit breaker - // actions and can grant permissions to other accounts. - CircuitBreakerPermissions_LEVEL_SUPER_ADMIN CircuitBreakerPermissions_Level = 3 -) - -var CircuitBreakerPermissions_Level_name = map[int32]string{ - 0: "LEVEL_NONE_UNSPECIFIED", - 1: "LEVEL_SOME_MSGS", - 2: "LEVEL_ALL_MSGS", - 3: "LEVEL_SUPER_ADMIN", -} - -var CircuitBreakerPermissions_Level_value = map[string]int32{ - "LEVEL_NONE_UNSPECIFIED": 0, - "LEVEL_SOME_MSGS": 1, - "LEVEL_ALL_MSGS": 2, - "LEVEL_SUPER_ADMIN": 3, -} - -func (x CircuitBreakerPermissions_Level) String() string { - return proto.EnumName(CircuitBreakerPermissions_Level_name, int32(x)) -} - -func (CircuitBreakerPermissions_Level) EnumDescriptor() ([]byte, []int) { - return fileDescriptor_a02145e57a6fbb1d, []int{2, 0} -} - // MsgAuthorizeCircuitBreaker defines the Msg/AuthorizeCircuitBreaker request type. type MsgAuthorizeCircuitBreaker struct { // granter is the granter of the circuit breaker permissions and must have @@ -80,7 +38,7 @@ type MsgAuthorizeCircuitBreaker struct { // permissions are the circuit breaker permissions that the grantee receives. // These will overwrite any existing permissions. LEVEL_NONE_UNSPECIFIED can // be specified to revoke all permissions. - Permissions *CircuitBreakerPermissions `protobuf:"bytes,3,opt,name=permissions,proto3" json:"permissions,omitempty"` + Permissions *Permissions `protobuf:"bytes,3,opt,name=permissions,proto3" json:"permissions,omitempty"` } func (m *MsgAuthorizeCircuitBreaker) Reset() { *m = MsgAuthorizeCircuitBreaker{} } @@ -130,7 +88,7 @@ func (m *MsgAuthorizeCircuitBreaker) GetGrantee() string { return "" } -func (m *MsgAuthorizeCircuitBreaker) GetPermissions() *CircuitBreakerPermissions { +func (m *MsgAuthorizeCircuitBreaker) GetPermissions() *Permissions { if m != nil { return m.Permissions } @@ -139,6 +97,7 @@ func (m *MsgAuthorizeCircuitBreaker) GetPermissions() *CircuitBreakerPermissions // MsgAuthorizeCircuitBreaker defines the Msg/AuthorizeCircuitBreaker response type. type MsgAuthorizeCircuitBreakerResponse struct { + Success bool `protobuf:"varint,1,opt,name=success,proto3" json:"success,omitempty"` } func (m *MsgAuthorizeCircuitBreakerResponse) Reset() { *m = MsgAuthorizeCircuitBreakerResponse{} } @@ -174,62 +133,11 @@ func (m *MsgAuthorizeCircuitBreakerResponse) XXX_DiscardUnknown() { var xxx_messageInfo_MsgAuthorizeCircuitBreakerResponse proto.InternalMessageInfo -// CircuitBreakerPermissions are the permissions that an account has to trip -// or reset the circuit breaker. -type CircuitBreakerPermissions struct { - // level is the level of permissions granted to this account. - Level CircuitBreakerPermissions_Level `protobuf:"varint,1,opt,name=level,proto3,enum=cosmos.circuit.v1.CircuitBreakerPermissions_Level" json:"level,omitempty"` - // limit_msg_types is used with LEVEL_SOME_MSGS to limit the lists of Msg type - // name that the account can pause. It is an error to use limit_msg_types with - // a level other than LEVEL_SOME_MSGS. - LimitMsgTypes []string `protobuf:"bytes,2,rep,name=limit_msg_types,json=limitMsgTypes,proto3" json:"limit_msg_types,omitempty"` -} - -func (m *CircuitBreakerPermissions) Reset() { *m = CircuitBreakerPermissions{} } -func (m *CircuitBreakerPermissions) String() string { return proto.CompactTextString(m) } -func (*CircuitBreakerPermissions) ProtoMessage() {} -func (*CircuitBreakerPermissions) Descriptor() ([]byte, []int) { - return fileDescriptor_a02145e57a6fbb1d, []int{2} -} -func (m *CircuitBreakerPermissions) XXX_Unmarshal(b []byte) error { - return m.Unmarshal(b) -} -func (m *CircuitBreakerPermissions) XXX_Marshal(b []byte, deterministic bool) ([]byte, error) { - if deterministic { - return xxx_messageInfo_CircuitBreakerPermissions.Marshal(b, m, deterministic) - } else { - b = b[:cap(b)] - n, err := m.MarshalToSizedBuffer(b) - if err != nil { - return nil, err - } - return b[:n], nil - } -} -func (m *CircuitBreakerPermissions) XXX_Merge(src proto.Message) { - xxx_messageInfo_CircuitBreakerPermissions.Merge(m, src) -} -func (m *CircuitBreakerPermissions) XXX_Size() int { - return m.Size() -} -func (m *CircuitBreakerPermissions) XXX_DiscardUnknown() { - xxx_messageInfo_CircuitBreakerPermissions.DiscardUnknown(m) -} - -var xxx_messageInfo_CircuitBreakerPermissions proto.InternalMessageInfo - -func (m *CircuitBreakerPermissions) GetLevel() CircuitBreakerPermissions_Level { +func (m *MsgAuthorizeCircuitBreakerResponse) GetSuccess() bool { if m != nil { - return m.Level + return m.Success } - return CircuitBreakerPermissions_LEVEL_NONE_UNSPECIFIED -} - -func (m *CircuitBreakerPermissions) GetLimitMsgTypes() []string { - if m != nil { - return m.LimitMsgTypes - } - return nil + return false } // MsgTripCircuitBreaker defines the Msg/TripCircuitBreaker request type. @@ -248,7 +156,7 @@ func (m *MsgTripCircuitBreaker) Reset() { *m = MsgTripCircuitBreaker{} } func (m *MsgTripCircuitBreaker) String() string { return proto.CompactTextString(m) } func (*MsgTripCircuitBreaker) ProtoMessage() {} func (*MsgTripCircuitBreaker) Descriptor() ([]byte, []int) { - return fileDescriptor_a02145e57a6fbb1d, []int{3} + return fileDescriptor_a02145e57a6fbb1d, []int{2} } func (m *MsgTripCircuitBreaker) XXX_Unmarshal(b []byte) error { return m.Unmarshal(b) @@ -293,13 +201,14 @@ func (m *MsgTripCircuitBreaker) GetMsgTypeUrls() []string { // MsgTripCircuitBreaker defines the Msg/TripCircuitBreaker response type. type MsgTripCircuitBreakerResponse struct { + Success bool `protobuf:"varint,1,opt,name=success,proto3" json:"success,omitempty"` } func (m *MsgTripCircuitBreakerResponse) Reset() { *m = MsgTripCircuitBreakerResponse{} } func (m *MsgTripCircuitBreakerResponse) String() string { return proto.CompactTextString(m) } func (*MsgTripCircuitBreakerResponse) ProtoMessage() {} func (*MsgTripCircuitBreakerResponse) Descriptor() ([]byte, []int) { - return fileDescriptor_a02145e57a6fbb1d, []int{4} + return fileDescriptor_a02145e57a6fbb1d, []int{3} } func (m *MsgTripCircuitBreakerResponse) XXX_Unmarshal(b []byte) error { return m.Unmarshal(b) @@ -328,6 +237,13 @@ func (m *MsgTripCircuitBreakerResponse) XXX_DiscardUnknown() { var xxx_messageInfo_MsgTripCircuitBreakerResponse proto.InternalMessageInfo +func (m *MsgTripCircuitBreakerResponse) GetSuccess() bool { + if m != nil { + return m.Success + } + return false +} + // MsgResetCircuitBreaker defines the Msg/ResetCircuitBreaker request type. type MsgResetCircuitBreaker struct { // authority is the account authorized to trip or reset the circuit breaker. @@ -342,7 +258,7 @@ func (m *MsgResetCircuitBreaker) Reset() { *m = MsgResetCircuitBreaker{} func (m *MsgResetCircuitBreaker) String() string { return proto.CompactTextString(m) } func (*MsgResetCircuitBreaker) ProtoMessage() {} func (*MsgResetCircuitBreaker) Descriptor() ([]byte, []int) { - return fileDescriptor_a02145e57a6fbb1d, []int{5} + return fileDescriptor_a02145e57a6fbb1d, []int{4} } func (m *MsgResetCircuitBreaker) XXX_Unmarshal(b []byte) error { return m.Unmarshal(b) @@ -387,13 +303,14 @@ func (m *MsgResetCircuitBreaker) GetMsgTypeUrls() []string { // MsgResetCircuitBreakerResponse defines the Msg/ResetCircuitBreaker response type. type MsgResetCircuitBreakerResponse struct { + Success bool `protobuf:"varint,1,opt,name=success,proto3" json:"success,omitempty"` } func (m *MsgResetCircuitBreakerResponse) Reset() { *m = MsgResetCircuitBreakerResponse{} } func (m *MsgResetCircuitBreakerResponse) String() string { return proto.CompactTextString(m) } func (*MsgResetCircuitBreakerResponse) ProtoMessage() {} func (*MsgResetCircuitBreakerResponse) Descriptor() ([]byte, []int) { - return fileDescriptor_a02145e57a6fbb1d, []int{6} + return fileDescriptor_a02145e57a6fbb1d, []int{5} } func (m *MsgResetCircuitBreakerResponse) XXX_Unmarshal(b []byte) error { return m.Unmarshal(b) @@ -422,11 +339,16 @@ func (m *MsgResetCircuitBreakerResponse) XXX_DiscardUnknown() { var xxx_messageInfo_MsgResetCircuitBreakerResponse proto.InternalMessageInfo +func (m *MsgResetCircuitBreakerResponse) GetSuccess() bool { + if m != nil { + return m.Success + } + return false +} + func init() { - proto.RegisterEnum("cosmos.circuit.v1.CircuitBreakerPermissions_Level", CircuitBreakerPermissions_Level_name, CircuitBreakerPermissions_Level_value) proto.RegisterType((*MsgAuthorizeCircuitBreaker)(nil), "cosmos.circuit.v1.MsgAuthorizeCircuitBreaker") proto.RegisterType((*MsgAuthorizeCircuitBreakerResponse)(nil), "cosmos.circuit.v1.MsgAuthorizeCircuitBreakerResponse") - proto.RegisterType((*CircuitBreakerPermissions)(nil), "cosmos.circuit.v1.CircuitBreakerPermissions") proto.RegisterType((*MsgTripCircuitBreaker)(nil), "cosmos.circuit.v1.MsgTripCircuitBreaker") proto.RegisterType((*MsgTripCircuitBreakerResponse)(nil), "cosmos.circuit.v1.MsgTripCircuitBreakerResponse") proto.RegisterType((*MsgResetCircuitBreaker)(nil), "cosmos.circuit.v1.MsgResetCircuitBreaker") @@ -436,41 +358,34 @@ func init() { func init() { proto.RegisterFile("cosmos/circuit/v1/tx.proto", fileDescriptor_a02145e57a6fbb1d) } var fileDescriptor_a02145e57a6fbb1d = []byte{ - // 543 bytes of a gzipped FileDescriptorProto - 0x1f, 0x8b, 0x08, 0x00, 0x00, 0x00, 0x00, 0x00, 0x02, 0xff, 0xa4, 0x54, 0xc1, 0x6e, 0xd3, 0x40, - 0x10, 0xcd, 0x26, 0x0a, 0x28, 0x13, 0x9a, 0xa6, 0x5b, 0xb5, 0x0d, 0x16, 0x98, 0xc8, 0x42, 0x28, - 0x54, 0xad, 0x43, 0x82, 0xb8, 0xf4, 0x96, 0xb6, 0x2e, 0x44, 0x8a, 0xd3, 0xc8, 0x21, 0x1c, 0xb8, - 0x58, 0xa9, 0x59, 0xb9, 0x4b, 0xed, 0xd8, 0xda, 0xdd, 0x44, 0x2d, 0x17, 0x10, 0x5f, 0xc0, 0x97, - 0xa0, 0x7e, 0x06, 0xc7, 0x1e, 0x39, 0xa2, 0xe4, 0xd0, 0x3b, 0xe2, 0x03, 0x90, 0xed, 0x38, 0x29, - 0xd4, 0x11, 0xad, 0x38, 0x59, 0x9e, 0x79, 0xf3, 0xde, 0x5b, 0xbf, 0xf5, 0x80, 0x64, 0x79, 0xdc, - 0xf5, 0x78, 0xd5, 0xa2, 0xcc, 0x1a, 0x52, 0x51, 0x1d, 0xd5, 0xaa, 0xe2, 0x54, 0xf5, 0x99, 0x27, - 0x3c, 0xbc, 0x12, 0xf5, 0xd4, 0x69, 0x4f, 0x1d, 0xd5, 0xa4, 0x8d, 0x29, 0xdc, 0xe5, 0x76, 0x00, - 0x75, 0xb9, 0x1d, 0x61, 0x95, 0xaf, 0x08, 0x24, 0x9d, 0xdb, 0x8d, 0xa1, 0x38, 0xf6, 0x18, 0xfd, - 0x40, 0xf6, 0xa2, 0x99, 0x5d, 0x46, 0xfa, 0x27, 0x84, 0xe1, 0x12, 0xdc, 0xb5, 0x59, 0x7f, 0x20, - 0x08, 0x2b, 0xa1, 0x32, 0xaa, 0xe4, 0x8c, 0xf8, 0x75, 0xde, 0x21, 0xa5, 0xf4, 0xd5, 0x0e, 0xc1, - 0x6d, 0xc8, 0xfb, 0x84, 0xb9, 0x94, 0x73, 0xea, 0x0d, 0x78, 0x29, 0x53, 0x46, 0x95, 0x7c, 0x7d, - 0x4b, 0xbd, 0x66, 0x4a, 0xfd, 0x53, 0xab, 0x33, 0x9f, 0x31, 0xae, 0x12, 0xec, 0xdc, 0xfb, 0x7c, - 0x79, 0xbe, 0x19, 0xeb, 0x2a, 0x8f, 0x41, 0x59, 0xec, 0xd7, 0x20, 0xdc, 0xf7, 0x06, 0x9c, 0x28, - 0x3f, 0x11, 0xdc, 0x5f, 0x48, 0x8f, 0x5f, 0x41, 0xd6, 0x21, 0x23, 0xe2, 0x84, 0x67, 0x2a, 0xd4, - 0xeb, 0xb7, 0xf1, 0xa6, 0xb6, 0x82, 0x49, 0x23, 0x22, 0xc0, 0x4f, 0x60, 0xd9, 0xa1, 0x2e, 0x15, - 0xa6, 0xcb, 0x6d, 0x53, 0x9c, 0xf9, 0x84, 0x97, 0xd2, 0xe5, 0x4c, 0x25, 0x67, 0x2c, 0x85, 0x65, - 0x9d, 0xdb, 0xaf, 0x83, 0xa2, 0x62, 0x41, 0x36, 0x9c, 0xc3, 0x12, 0xac, 0xb7, 0xb4, 0x37, 0x5a, - 0xcb, 0x6c, 0x1f, 0xb6, 0x35, 0xb3, 0xd7, 0xee, 0x76, 0xb4, 0xbd, 0xe6, 0x41, 0x53, 0xdb, 0x2f, - 0xa6, 0xf0, 0x2a, 0x2c, 0x47, 0xbd, 0xee, 0xa1, 0xae, 0x99, 0x7a, 0xf7, 0x65, 0xb7, 0x88, 0x30, - 0x86, 0x42, 0x54, 0x6c, 0xb4, 0x5a, 0x51, 0x2d, 0x8d, 0xd7, 0x60, 0x65, 0x0a, 0xec, 0x75, 0x34, - 0xc3, 0x6c, 0xec, 0xeb, 0xcd, 0x76, 0x31, 0xa3, 0x50, 0x58, 0x0b, 0x04, 0x19, 0xf5, 0xff, 0x4a, - 0xf1, 0x01, 0xe4, 0xfa, 0xd1, 0x07, 0x13, 0x67, 0xd3, 0x1c, 0xe7, 0x05, 0xac, 0xc0, 0x52, 0xec, - 0xde, 0x1c, 0x32, 0x27, 0x3e, 0x41, 0xde, 0x8d, 0xcc, 0xf7, 0x98, 0xc3, 0x77, 0x0a, 0x41, 0x06, - 0xf3, 0x19, 0xe5, 0x11, 0x3c, 0x4c, 0x94, 0x9a, 0x05, 0xf0, 0x1e, 0xd6, 0x75, 0x6e, 0x1b, 0x84, - 0x13, 0xf1, 0x7f, 0x66, 0x32, 0xff, 0x36, 0x53, 0x06, 0x39, 0x59, 0x2b, 0x76, 0x53, 0xff, 0x95, - 0x86, 0x8c, 0xce, 0x6d, 0xfc, 0x11, 0x36, 0x16, 0xdd, 0xf4, 0xed, 0x84, 0x4b, 0xb0, 0xf8, 0xa2, - 0x49, 0x2f, 0x6e, 0x05, 0x8f, 0x8d, 0x60, 0x1f, 0x70, 0x42, 0x3e, 0x95, 0x64, 0xb2, 0xeb, 0x48, - 0xe9, 0xd9, 0x4d, 0x91, 0x33, 0x45, 0x0e, 0xab, 0x49, 0x29, 0x3c, 0x4d, 0x26, 0x4a, 0x80, 0x4a, - 0xb5, 0x1b, 0x43, 0x63, 0x51, 0x29, 0xfb, 0xe9, 0xf2, 0x7c, 0x13, 0xed, 0x1e, 0x7c, 0x1b, 0xcb, - 0xe8, 0x62, 0x2c, 0xa3, 0x1f, 0x63, 0x19, 0x7d, 0x99, 0xc8, 0xa9, 0x8b, 0x89, 0x9c, 0xfa, 0x3e, - 0x91, 0x53, 0x6f, 0xb7, 0x6c, 0x2a, 0x8e, 0x87, 0x47, 0xaa, 0xe5, 0xb9, 0xd5, 0x78, 0x93, 0x85, - 0x8f, 0x6d, 0xfe, 0xee, 0xa4, 0x7a, 0x3a, 0x5b, 0x6b, 0xe1, 0x2f, 0x75, 0x74, 0x27, 0xdc, 0x55, - 0xcf, 0x7f, 0x07, 0x00, 0x00, 0xff, 0xff, 0xa7, 0x99, 0x58, 0xf0, 0xf5, 0x04, 0x00, 0x00, + // 429 bytes of a gzipped FileDescriptorProto + 0x1f, 0x8b, 0x08, 0x00, 0x00, 0x00, 0x00, 0x00, 0x02, 0xff, 0xa4, 0x93, 0xcf, 0xae, 0xd2, 0x40, + 0x14, 0x87, 0x19, 0x1a, 0xff, 0x30, 0xa8, 0x89, 0x35, 0x7a, 0x9b, 0xc9, 0xbd, 0x13, 0xd2, 0x55, + 0xbd, 0x89, 0xad, 0x60, 0x34, 0x91, 0x85, 0x51, 0x5c, 0x37, 0x31, 0x0d, 0x6e, 0xdc, 0x10, 0xac, + 0x93, 0x71, 0x84, 0x32, 0xcd, 0x9c, 0x96, 0x80, 0x1b, 0x8d, 0x4f, 0xe0, 0x23, 0xf8, 0x08, 0x3c, + 0x86, 0x4b, 0x96, 0x2e, 0x0d, 0x2c, 0x78, 0x01, 0x1f, 0xc0, 0x94, 0x52, 0x4a, 0x64, 0x08, 0x98, + 0xbb, 0x1c, 0xce, 0x37, 0xe7, 0xf7, 0x0d, 0xa7, 0x07, 0x93, 0x50, 0x42, 0x24, 0xc1, 0x0b, 0x85, + 0x0a, 0x53, 0x91, 0x78, 0xe3, 0xa6, 0x97, 0x4c, 0xdc, 0x58, 0xc9, 0x44, 0x9a, 0x77, 0xf3, 0x9a, + 0xbb, 0xa9, 0xb9, 0xe3, 0x26, 0x39, 0xdb, 0xe0, 0x11, 0xf0, 0x0c, 0x8d, 0x80, 0xe7, 0x2c, 0xb9, + 0xd0, 0xf4, 0x99, 0xc6, 0x0c, 0xf2, 0xb2, 0xfd, 0x03, 0x61, 0xe2, 0x03, 0x7f, 0x95, 0x26, 0x1f, + 0xa5, 0x12, 0x9f, 0xd9, 0xeb, 0x1c, 0xeb, 0x28, 0xd6, 0x1f, 0x30, 0x65, 0x5a, 0xf8, 0x06, 0x57, + 0xfd, 0x51, 0xc2, 0x94, 0x85, 0x1a, 0xc8, 0xa9, 0x05, 0xc5, 0xb1, 0xac, 0x30, 0xab, 0xba, 0x5b, + 0x61, 0xe6, 0x4b, 0x5c, 0x8f, 0x99, 0x8a, 0x04, 0x80, 0x90, 0x23, 0xb0, 0x8c, 0x06, 0x72, 0xea, + 0x2d, 0xea, 0xee, 0x39, 0xbb, 0x6f, 0x4a, 0x2a, 0xd8, 0xbd, 0xd2, 0xbe, 0xf5, 0x6d, 0x35, 0xbb, + 0x2c, 0x92, 0xec, 0x17, 0xd8, 0x3e, 0x6c, 0x18, 0x30, 0x88, 0xe5, 0x08, 0x58, 0xe6, 0x03, 0x69, + 0x18, 0x32, 0x80, 0xb5, 0xe9, 0xcd, 0xa0, 0x38, 0xda, 0x02, 0xdf, 0xf7, 0x81, 0x77, 0x95, 0x88, + 0xff, 0x79, 0xdc, 0x39, 0xae, 0xf5, 0xf3, 0xae, 0xc9, 0x74, 0xf3, 0xbc, 0xf2, 0x07, 0xd3, 0xc6, + 0xb7, 0x23, 0xe0, 0xbd, 0xec, 0xcf, 0xea, 0xa5, 0x6a, 0x08, 0x56, 0xb5, 0x61, 0x38, 0xb5, 0xa0, + 0x1e, 0x01, 0xef, 0x4e, 0x63, 0xf6, 0x56, 0x0d, 0xa1, 0x7d, 0x27, 0x13, 0x2d, 0xef, 0xd8, 0xcf, + 0xf1, 0x85, 0x36, 0xea, 0x04, 0xcb, 0x4f, 0xf8, 0x81, 0x0f, 0x3c, 0x60, 0xc0, 0x92, 0xab, 0x69, + 0x1a, 0xc7, 0x35, 0xdb, 0x98, 0xea, 0xb3, 0x8e, 0x7b, 0xb6, 0xfe, 0x54, 0xb1, 0xe1, 0x03, 0x37, + 0xbf, 0xe0, 0xb3, 0x43, 0x1f, 0xcd, 0x23, 0xcd, 0xac, 0x0f, 0x4f, 0x90, 0x3c, 0xfd, 0x2f, 0x7c, + 0xab, 0x18, 0x63, 0x53, 0x33, 0x53, 0x47, 0xdf, 0x6c, 0x9f, 0x24, 0x8f, 0x4f, 0x25, 0xb7, 0x89, + 0x80, 0xef, 0xe9, 0xe6, 0xf3, 0x50, 0xdf, 0x48, 0x83, 0x92, 0xe6, 0xc9, 0x68, 0x11, 0x4a, 0xae, + 0x7d, 0x5d, 0xcd, 0x2e, 0x51, 0xe7, 0xd9, 0xcf, 0x05, 0x45, 0xf3, 0x05, 0x45, 0xbf, 0x17, 0x14, + 0x7d, 0x5f, 0xd2, 0xca, 0x7c, 0x49, 0x2b, 0xbf, 0x96, 0xb4, 0xf2, 0xee, 0x3c, 0x6f, 0x09, 0x1f, + 0x06, 0xae, 0x90, 0xde, 0x64, 0xbb, 0xe8, 0xeb, 0x2d, 0x7f, 0x7f, 0x7d, 0xbd, 0xe6, 0x4f, 0xfe, + 0x06, 0x00, 0x00, 0xff, 0xff, 0x89, 0x07, 0x74, 0x02, 0x4f, 0x04, 0x00, 0x00, } // Reference imports to suppress errors if they are not otherwise used. @@ -704,40 +619,13 @@ func (m *MsgAuthorizeCircuitBreakerResponse) MarshalToSizedBuffer(dAtA []byte) ( _ = i var l int _ = l - return len(dAtA) - i, nil -} - -func (m *CircuitBreakerPermissions) Marshal() (dAtA []byte, err error) { - size := m.Size() - dAtA = make([]byte, size) - n, err := m.MarshalToSizedBuffer(dAtA[:size]) - if err != nil { - return nil, err - } - return dAtA[:n], nil -} - -func (m *CircuitBreakerPermissions) MarshalTo(dAtA []byte) (int, error) { - size := m.Size() - return m.MarshalToSizedBuffer(dAtA[:size]) -} - -func (m *CircuitBreakerPermissions) MarshalToSizedBuffer(dAtA []byte) (int, error) { - i := len(dAtA) - _ = i - var l int - _ = l - if len(m.LimitMsgTypes) > 0 { - for iNdEx := len(m.LimitMsgTypes) - 1; iNdEx >= 0; iNdEx-- { - i -= len(m.LimitMsgTypes[iNdEx]) - copy(dAtA[i:], m.LimitMsgTypes[iNdEx]) - i = encodeVarintTx(dAtA, i, uint64(len(m.LimitMsgTypes[iNdEx]))) - i-- - dAtA[i] = 0x12 + if m.Success { + i-- + if m.Success { + dAtA[i] = 1 + } else { + dAtA[i] = 0 } - } - if m.Level != 0 { - i = encodeVarintTx(dAtA, i, uint64(m.Level)) i-- dAtA[i] = 0x8 } @@ -803,6 +691,16 @@ func (m *MsgTripCircuitBreakerResponse) MarshalToSizedBuffer(dAtA []byte) (int, _ = i var l int _ = l + if m.Success { + i-- + if m.Success { + dAtA[i] = 1 + } else { + dAtA[i] = 0 + } + i-- + dAtA[i] = 0x8 + } return len(dAtA) - i, nil } @@ -865,6 +763,16 @@ func (m *MsgResetCircuitBreakerResponse) MarshalToSizedBuffer(dAtA []byte) (int, _ = i var l int _ = l + if m.Success { + i-- + if m.Success { + dAtA[i] = 1 + } else { + dAtA[i] = 0 + } + i-- + dAtA[i] = 0x8 + } return len(dAtA) - i, nil } @@ -906,23 +814,8 @@ func (m *MsgAuthorizeCircuitBreakerResponse) Size() (n int) { } var l int _ = l - return n -} - -func (m *CircuitBreakerPermissions) Size() (n int) { - if m == nil { - return 0 - } - var l int - _ = l - if m.Level != 0 { - n += 1 + sovTx(uint64(m.Level)) - } - if len(m.LimitMsgTypes) > 0 { - for _, s := range m.LimitMsgTypes { - l = len(s) - n += 1 + l + sovTx(uint64(l)) - } + if m.Success { + n += 2 } return n } @@ -952,6 +845,9 @@ func (m *MsgTripCircuitBreakerResponse) Size() (n int) { } var l int _ = l + if m.Success { + n += 2 + } return n } @@ -980,6 +876,9 @@ func (m *MsgResetCircuitBreakerResponse) Size() (n int) { } var l int _ = l + if m.Success { + n += 2 + } return n } @@ -1112,7 +1011,7 @@ func (m *MsgAuthorizeCircuitBreaker) Unmarshal(dAtA []byte) error { return io.ErrUnexpectedEOF } if m.Permissions == nil { - m.Permissions = &CircuitBreakerPermissions{} + m.Permissions = &Permissions{} } if err := m.Permissions.Unmarshal(dAtA[iNdEx:postIndex]); err != nil { return err @@ -1168,61 +1067,11 @@ func (m *MsgAuthorizeCircuitBreakerResponse) Unmarshal(dAtA []byte) error { return fmt.Errorf("proto: MsgAuthorizeCircuitBreakerResponse: illegal tag %d (wire type %d)", fieldNum, wire) } switch fieldNum { - default: - iNdEx = preIndex - skippy, err := skipTx(dAtA[iNdEx:]) - if err != nil { - return err - } - if (skippy < 0) || (iNdEx+skippy) < 0 { - return ErrInvalidLengthTx - } - if (iNdEx + skippy) > l { - return io.ErrUnexpectedEOF - } - iNdEx += skippy - } - } - - if iNdEx > l { - return io.ErrUnexpectedEOF - } - return nil -} -func (m *CircuitBreakerPermissions) Unmarshal(dAtA []byte) error { - l := len(dAtA) - iNdEx := 0 - for iNdEx < l { - preIndex := iNdEx - var wire uint64 - for shift := uint(0); ; shift += 7 { - if shift >= 64 { - return ErrIntOverflowTx - } - if iNdEx >= l { - return io.ErrUnexpectedEOF - } - b := dAtA[iNdEx] - iNdEx++ - wire |= uint64(b&0x7F) << shift - if b < 0x80 { - break - } - } - fieldNum := int32(wire >> 3) - wireType := int(wire & 0x7) - if wireType == 4 { - return fmt.Errorf("proto: CircuitBreakerPermissions: wiretype end group for non-group") - } - if fieldNum <= 0 { - return fmt.Errorf("proto: CircuitBreakerPermissions: illegal tag %d (wire type %d)", fieldNum, wire) - } - switch fieldNum { case 1: if wireType != 0 { - return fmt.Errorf("proto: wrong wireType = %d for field Level", wireType) + return fmt.Errorf("proto: wrong wireType = %d for field Success", wireType) } - m.Level = 0 + var v int for shift := uint(0); ; shift += 7 { if shift >= 64 { return ErrIntOverflowTx @@ -1232,43 +1081,12 @@ func (m *CircuitBreakerPermissions) Unmarshal(dAtA []byte) error { } b := dAtA[iNdEx] iNdEx++ - m.Level |= CircuitBreakerPermissions_Level(b&0x7F) << shift + v |= int(b&0x7F) << shift if b < 0x80 { break } } - case 2: - if wireType != 2 { - return fmt.Errorf("proto: wrong wireType = %d for field LimitMsgTypes", wireType) - } - var stringLen uint64 - for shift := uint(0); ; shift += 7 { - if shift >= 64 { - return ErrIntOverflowTx - } - if iNdEx >= l { - return io.ErrUnexpectedEOF - } - b := dAtA[iNdEx] - iNdEx++ - stringLen |= uint64(b&0x7F) << shift - if b < 0x80 { - break - } - } - intStringLen := int(stringLen) - if intStringLen < 0 { - return ErrInvalidLengthTx - } - postIndex := iNdEx + intStringLen - if postIndex < 0 { - return ErrInvalidLengthTx - } - if postIndex > l { - return io.ErrUnexpectedEOF - } - m.LimitMsgTypes = append(m.LimitMsgTypes, string(dAtA[iNdEx:postIndex])) - iNdEx = postIndex + m.Success = bool(v != 0) default: iNdEx = preIndex skippy, err := skipTx(dAtA[iNdEx:]) @@ -1433,6 +1251,26 @@ func (m *MsgTripCircuitBreakerResponse) Unmarshal(dAtA []byte) error { return fmt.Errorf("proto: MsgTripCircuitBreakerResponse: illegal tag %d (wire type %d)", fieldNum, wire) } switch fieldNum { + case 1: + if wireType != 0 { + return fmt.Errorf("proto: wrong wireType = %d for field Success", wireType) + } + var v int + for shift := uint(0); ; shift += 7 { + if shift >= 64 { + return ErrIntOverflowTx + } + if iNdEx >= l { + return io.ErrUnexpectedEOF + } + b := dAtA[iNdEx] + iNdEx++ + v |= int(b&0x7F) << shift + if b < 0x80 { + break + } + } + m.Success = bool(v != 0) default: iNdEx = preIndex skippy, err := skipTx(dAtA[iNdEx:]) @@ -1597,6 +1435,26 @@ func (m *MsgResetCircuitBreakerResponse) Unmarshal(dAtA []byte) error { return fmt.Errorf("proto: MsgResetCircuitBreakerResponse: illegal tag %d (wire type %d)", fieldNum, wire) } switch fieldNum { + case 1: + if wireType != 0 { + return fmt.Errorf("proto: wrong wireType = %d for field Success", wireType) + } + var v int + for shift := uint(0); ; shift += 7 { + if shift >= 64 { + return ErrIntOverflowTx + } + if iNdEx >= l { + return io.ErrUnexpectedEOF + } + b := dAtA[iNdEx] + iNdEx++ + v |= int(b&0x7F) << shift + if b < 0x80 { + break + } + } + m.Success = bool(v != 0) default: iNdEx = preIndex skippy, err := skipTx(dAtA[iNdEx:]) diff --git a/x/circuit/types/types.pb.go b/x/circuit/types/types.pb.go new file mode 100644 index 000000000000..989998af6716 --- /dev/null +++ b/x/circuit/types/types.pb.go @@ -0,0 +1,885 @@ +// Code generated by protoc-gen-gogo. DO NOT EDIT. +// source: cosmos/circuit/v1/types.proto + +package types + +import ( + fmt "fmt" + proto "github.com/cosmos/gogoproto/proto" + io "io" + math "math" + math_bits "math/bits" +) + +// Reference imports to suppress errors if they are not otherwise used. +var _ = proto.Marshal +var _ = fmt.Errorf +var _ = math.Inf + +// This is a compile-time assertion to ensure that this generated file +// is compatible with the proto package it is being compiled against. +// A compilation error at this line likely means your copy of the +// proto package needs to be updated. +const _ = proto.GoGoProtoPackageIsVersion3 // please upgrade the proto package + +// Level is the permission level. +type Permissions_Level int32 + +const ( + // LEVEL_NONE_UNSPECIFIED indicates that the account will have no circuit + // breaker permissions. + Permissions_LEVEL_NONE_UNSPECIFIED Permissions_Level = 0 + // LEVEL_SOME_MSGS indicates that the account will have permission to + // trip or reset the circuit breaker for some Msg type URLs. If this level + // is chosen, a non-empty list of Msg type URLs must be provided in + // limit_type_urls. + Permissions_LEVEL_SOME_MSGS Permissions_Level = 1 + // LEVEL_ALL_MSGS indicates that the account can trip or reset the circuit + // breaker for Msg's of all type URLs. + Permissions_LEVEL_ALL_MSGS Permissions_Level = 2 + // LEVEL_SUPER_ADMIN indicates that the account can take all circuit breaker + // actions and can grant permissions to other accounts. + Permissions_LEVEL_SUPER_ADMIN Permissions_Level = 3 +) + +var Permissions_Level_name = map[int32]string{ + 0: "LEVEL_NONE_UNSPECIFIED", + 1: "LEVEL_SOME_MSGS", + 2: "LEVEL_ALL_MSGS", + 3: "LEVEL_SUPER_ADMIN", +} + +var Permissions_Level_value = map[string]int32{ + "LEVEL_NONE_UNSPECIFIED": 0, + "LEVEL_SOME_MSGS": 1, + "LEVEL_ALL_MSGS": 2, + "LEVEL_SUPER_ADMIN": 3, +} + +func (x Permissions_Level) String() string { + return proto.EnumName(Permissions_Level_name, int32(x)) +} + +func (Permissions_Level) EnumDescriptor() ([]byte, []int) { + return fileDescriptor_1f5fe523f8a09dbc, []int{0, 0} +} + +// Permissions are the permissions that an account has to trip +// or reset the circuit breaker. +type Permissions struct { + // level is the level of permissions granted to this account. + Level Permissions_Level `protobuf:"varint,1,opt,name=level,proto3,enum=cosmos.circuit.v1.Permissions_Level" json:"level,omitempty"` + // limit_type_urls is used with LEVEL_SOME_MSGS to limit the lists of Msg type + // URLs that the account can trip. It is an error to use limit_type_urls with + // a level other than LEVEL_SOME_MSGS. + LimitTypeUrls []string `protobuf:"bytes,2,rep,name=limit_type_urls,json=limitTypeUrls,proto3" json:"limit_type_urls,omitempty"` +} + +func (m *Permissions) Reset() { *m = Permissions{} } +func (m *Permissions) String() string { return proto.CompactTextString(m) } +func (*Permissions) ProtoMessage() {} +func (*Permissions) Descriptor() ([]byte, []int) { + return fileDescriptor_1f5fe523f8a09dbc, []int{0} +} +func (m *Permissions) XXX_Unmarshal(b []byte) error { + return m.Unmarshal(b) +} +func (m *Permissions) XXX_Marshal(b []byte, deterministic bool) ([]byte, error) { + if deterministic { + return xxx_messageInfo_Permissions.Marshal(b, m, deterministic) + } else { + b = b[:cap(b)] + n, err := m.MarshalToSizedBuffer(b) + if err != nil { + return nil, err + } + return b[:n], nil + } +} +func (m *Permissions) XXX_Merge(src proto.Message) { + xxx_messageInfo_Permissions.Merge(m, src) +} +func (m *Permissions) XXX_Size() int { + return m.Size() +} +func (m *Permissions) XXX_DiscardUnknown() { + xxx_messageInfo_Permissions.DiscardUnknown(m) +} + +var xxx_messageInfo_Permissions proto.InternalMessageInfo + +func (m *Permissions) GetLevel() Permissions_Level { + if m != nil { + return m.Level + } + return Permissions_LEVEL_NONE_UNSPECIFIED +} + +func (m *Permissions) GetLimitTypeUrls() []string { + if m != nil { + return m.LimitTypeUrls + } + return nil +} + +// GenesisAccountPermissions is the account permissions for the circuit breaker in genesis +type GenesisAccountPermissions struct { + Address string `protobuf:"bytes,1,opt,name=address,proto3" json:"address,omitempty"` + Permissions *Permissions `protobuf:"bytes,2,opt,name=permissions,proto3" json:"permissions,omitempty"` +} + +func (m *GenesisAccountPermissions) Reset() { *m = GenesisAccountPermissions{} } +func (m *GenesisAccountPermissions) String() string { return proto.CompactTextString(m) } +func (*GenesisAccountPermissions) ProtoMessage() {} +func (*GenesisAccountPermissions) Descriptor() ([]byte, []int) { + return fileDescriptor_1f5fe523f8a09dbc, []int{1} +} +func (m *GenesisAccountPermissions) XXX_Unmarshal(b []byte) error { + return m.Unmarshal(b) +} +func (m *GenesisAccountPermissions) XXX_Marshal(b []byte, deterministic bool) ([]byte, error) { + if deterministic { + return xxx_messageInfo_GenesisAccountPermissions.Marshal(b, m, deterministic) + } else { + b = b[:cap(b)] + n, err := m.MarshalToSizedBuffer(b) + if err != nil { + return nil, err + } + return b[:n], nil + } +} +func (m *GenesisAccountPermissions) XXX_Merge(src proto.Message) { + xxx_messageInfo_GenesisAccountPermissions.Merge(m, src) +} +func (m *GenesisAccountPermissions) XXX_Size() int { + return m.Size() +} +func (m *GenesisAccountPermissions) XXX_DiscardUnknown() { + xxx_messageInfo_GenesisAccountPermissions.DiscardUnknown(m) +} + +var xxx_messageInfo_GenesisAccountPermissions proto.InternalMessageInfo + +func (m *GenesisAccountPermissions) GetAddress() string { + if m != nil { + return m.Address + } + return "" +} + +func (m *GenesisAccountPermissions) GetPermissions() *Permissions { + if m != nil { + return m.Permissions + } + return nil +} + +// GenesisState is the state that must be provided at genesis. +type GenesisState struct { + AccountPermissions []*GenesisAccountPermissions `protobuf:"bytes,1,rep,name=account_permissions,json=accountPermissions,proto3" json:"account_permissions,omitempty"` + DisabledTypeUrls []string `protobuf:"bytes,2,rep,name=disabled_type_urls,json=disabledTypeUrls,proto3" json:"disabled_type_urls,omitempty"` +} + +func (m *GenesisState) Reset() { *m = GenesisState{} } +func (m *GenesisState) String() string { return proto.CompactTextString(m) } +func (*GenesisState) ProtoMessage() {} +func (*GenesisState) Descriptor() ([]byte, []int) { + return fileDescriptor_1f5fe523f8a09dbc, []int{2} +} +func (m *GenesisState) XXX_Unmarshal(b []byte) error { + return m.Unmarshal(b) +} +func (m *GenesisState) XXX_Marshal(b []byte, deterministic bool) ([]byte, error) { + if deterministic { + return xxx_messageInfo_GenesisState.Marshal(b, m, deterministic) + } else { + b = b[:cap(b)] + n, err := m.MarshalToSizedBuffer(b) + if err != nil { + return nil, err + } + return b[:n], nil + } +} +func (m *GenesisState) XXX_Merge(src proto.Message) { + xxx_messageInfo_GenesisState.Merge(m, src) +} +func (m *GenesisState) XXX_Size() int { + return m.Size() +} +func (m *GenesisState) XXX_DiscardUnknown() { + xxx_messageInfo_GenesisState.DiscardUnknown(m) +} + +var xxx_messageInfo_GenesisState proto.InternalMessageInfo + +func (m *GenesisState) GetAccountPermissions() []*GenesisAccountPermissions { + if m != nil { + return m.AccountPermissions + } + return nil +} + +func (m *GenesisState) GetDisabledTypeUrls() []string { + if m != nil { + return m.DisabledTypeUrls + } + return nil +} + +func init() { + proto.RegisterEnum("cosmos.circuit.v1.Permissions_Level", Permissions_Level_name, Permissions_Level_value) + proto.RegisterType((*Permissions)(nil), "cosmos.circuit.v1.Permissions") + proto.RegisterType((*GenesisAccountPermissions)(nil), "cosmos.circuit.v1.GenesisAccountPermissions") + proto.RegisterType((*GenesisState)(nil), "cosmos.circuit.v1.GenesisState") +} + +func init() { proto.RegisterFile("cosmos/circuit/v1/types.proto", fileDescriptor_1f5fe523f8a09dbc) } + +var fileDescriptor_1f5fe523f8a09dbc = []byte{ + // 388 bytes of a gzipped FileDescriptorProto + 0x1f, 0x8b, 0x08, 0x00, 0x00, 0x00, 0x00, 0x00, 0x02, 0xff, 0x7c, 0x52, 0x41, 0x4f, 0xea, 0x40, + 0x18, 0xec, 0x42, 0x78, 0x2f, 0x6c, 0xdf, 0x83, 0xb2, 0x44, 0x53, 0x8d, 0x36, 0x4d, 0x63, 0x4c, + 0x0f, 0xa4, 0x0d, 0x98, 0x78, 0xf0, 0x24, 0x4a, 0x25, 0x24, 0xa5, 0x90, 0x56, 0x3c, 0x98, 0x98, + 0xa6, 0xb4, 0x7b, 0xd8, 0x58, 0x68, 0xd3, 0x2d, 0x28, 0xff, 0xc2, 0xbb, 0x7f, 0xc8, 0x23, 0x27, + 0xe3, 0xd1, 0xc0, 0x1f, 0x31, 0xb4, 0xa0, 0x4d, 0x50, 0x8f, 0xfb, 0xcd, 0xcc, 0x7e, 0xdf, 0x4c, + 0x06, 0x1e, 0xba, 0x01, 0x1d, 0x05, 0x54, 0x75, 0x49, 0xe4, 0x4e, 0x48, 0xac, 0x4e, 0xeb, 0x6a, + 0x3c, 0x0b, 0x31, 0x55, 0xc2, 0x28, 0x88, 0x03, 0x54, 0x49, 0x61, 0x65, 0x0d, 0x2b, 0xd3, 0xba, + 0xf4, 0x0a, 0x20, 0xdb, 0xc7, 0xd1, 0x88, 0x50, 0x4a, 0x82, 0x31, 0x45, 0x67, 0xb0, 0xe0, 0xe3, + 0x29, 0xf6, 0x79, 0x20, 0x02, 0xb9, 0xd4, 0x38, 0x52, 0xb6, 0x24, 0x4a, 0x86, 0xae, 0xe8, 0x2b, + 0xae, 0x99, 0x4a, 0xd0, 0x31, 0x2c, 0xfb, 0x64, 0x44, 0x62, 0x7b, 0xb5, 0xd3, 0x9e, 0x44, 0x3e, + 0xe5, 0x73, 0x62, 0x5e, 0x2e, 0x9a, 0xff, 0x93, 0xf1, 0xf5, 0x2c, 0xc4, 0x83, 0xc8, 0xa7, 0x92, + 0x0b, 0x0b, 0x89, 0x0e, 0xed, 0xc3, 0x5d, 0x5d, 0xbb, 0xd1, 0x74, 0xdb, 0xe8, 0x19, 0x9a, 0x3d, + 0x30, 0xac, 0xbe, 0x76, 0xd9, 0xb9, 0xea, 0x68, 0x2d, 0x8e, 0x41, 0x55, 0x58, 0x4e, 0x31, 0xab, + 0xd7, 0xd5, 0xec, 0xae, 0xd5, 0xb6, 0x38, 0x80, 0x10, 0x2c, 0xa5, 0xc3, 0xa6, 0xae, 0xa7, 0xb3, + 0x1c, 0xda, 0x81, 0x95, 0x35, 0x71, 0xd0, 0xd7, 0x4c, 0xbb, 0xd9, 0xea, 0x76, 0x0c, 0x2e, 0x2f, + 0x3d, 0xc0, 0xbd, 0x36, 0x1e, 0x63, 0x4a, 0x68, 0xd3, 0x75, 0x83, 0xc9, 0x38, 0xce, 0xba, 0xe4, + 0xe1, 0x5f, 0xc7, 0xf3, 0x22, 0x4c, 0x69, 0xe2, 0xb3, 0x68, 0x6e, 0x9e, 0xe8, 0x1c, 0xb2, 0xe1, + 0x17, 0x91, 0xcf, 0x89, 0x40, 0x66, 0x1b, 0xc2, 0xef, 0x29, 0x98, 0x59, 0x89, 0xf4, 0x0c, 0xe0, + 0xbf, 0xf5, 0x66, 0x2b, 0x76, 0x62, 0x8c, 0xee, 0x60, 0xd5, 0x49, 0x4f, 0xb0, 0xb3, 0x5f, 0x03, + 0x31, 0x2f, 0xb3, 0x8d, 0xda, 0x37, 0x5f, 0xff, 0x78, 0xb7, 0x89, 0x9c, 0x6d, 0x2f, 0x35, 0x88, + 0x3c, 0x42, 0x9d, 0xa1, 0x8f, 0xbd, 0xad, 0xe0, 0xb9, 0x0d, 0xb2, 0xc9, 0xfe, 0xe2, 0xf4, 0x65, + 0x21, 0x80, 0xf9, 0x42, 0x00, 0xef, 0x0b, 0x01, 0x3c, 0x2d, 0x05, 0x66, 0xbe, 0x14, 0x98, 0xb7, + 0xa5, 0xc0, 0xdc, 0x1e, 0xa4, 0x87, 0x50, 0xef, 0x5e, 0x21, 0x81, 0xfa, 0xf8, 0xd9, 0xa1, 0xa4, + 0x40, 0xc3, 0x3f, 0x49, 0x83, 0x4e, 0x3e, 0x02, 0x00, 0x00, 0xff, 0xff, 0x3a, 0xff, 0xdc, 0xa4, + 0x62, 0x02, 0x00, 0x00, +} + +func (m *Permissions) Marshal() (dAtA []byte, err error) { + size := m.Size() + dAtA = make([]byte, size) + n, err := m.MarshalToSizedBuffer(dAtA[:size]) + if err != nil { + return nil, err + } + return dAtA[:n], nil +} + +func (m *Permissions) MarshalTo(dAtA []byte) (int, error) { + size := m.Size() + return m.MarshalToSizedBuffer(dAtA[:size]) +} + +func (m *Permissions) MarshalToSizedBuffer(dAtA []byte) (int, error) { + i := len(dAtA) + _ = i + var l int + _ = l + if len(m.LimitTypeUrls) > 0 { + for iNdEx := len(m.LimitTypeUrls) - 1; iNdEx >= 0; iNdEx-- { + i -= len(m.LimitTypeUrls[iNdEx]) + copy(dAtA[i:], m.LimitTypeUrls[iNdEx]) + i = encodeVarintTypes(dAtA, i, uint64(len(m.LimitTypeUrls[iNdEx]))) + i-- + dAtA[i] = 0x12 + } + } + if m.Level != 0 { + i = encodeVarintTypes(dAtA, i, uint64(m.Level)) + i-- + dAtA[i] = 0x8 + } + return len(dAtA) - i, nil +} + +func (m *GenesisAccountPermissions) Marshal() (dAtA []byte, err error) { + size := m.Size() + dAtA = make([]byte, size) + n, err := m.MarshalToSizedBuffer(dAtA[:size]) + if err != nil { + return nil, err + } + return dAtA[:n], nil +} + +func (m *GenesisAccountPermissions) MarshalTo(dAtA []byte) (int, error) { + size := m.Size() + return m.MarshalToSizedBuffer(dAtA[:size]) +} + +func (m *GenesisAccountPermissions) MarshalToSizedBuffer(dAtA []byte) (int, error) { + i := len(dAtA) + _ = i + var l int + _ = l + if m.Permissions != nil { + { + size, err := m.Permissions.MarshalToSizedBuffer(dAtA[:i]) + if err != nil { + return 0, err + } + i -= size + i = encodeVarintTypes(dAtA, i, uint64(size)) + } + i-- + dAtA[i] = 0x12 + } + if len(m.Address) > 0 { + i -= len(m.Address) + copy(dAtA[i:], m.Address) + i = encodeVarintTypes(dAtA, i, uint64(len(m.Address))) + i-- + dAtA[i] = 0xa + } + return len(dAtA) - i, nil +} + +func (m *GenesisState) Marshal() (dAtA []byte, err error) { + size := m.Size() + dAtA = make([]byte, size) + n, err := m.MarshalToSizedBuffer(dAtA[:size]) + if err != nil { + return nil, err + } + return dAtA[:n], nil +} + +func (m *GenesisState) MarshalTo(dAtA []byte) (int, error) { + size := m.Size() + return m.MarshalToSizedBuffer(dAtA[:size]) +} + +func (m *GenesisState) MarshalToSizedBuffer(dAtA []byte) (int, error) { + i := len(dAtA) + _ = i + var l int + _ = l + if len(m.DisabledTypeUrls) > 0 { + for iNdEx := len(m.DisabledTypeUrls) - 1; iNdEx >= 0; iNdEx-- { + i -= len(m.DisabledTypeUrls[iNdEx]) + copy(dAtA[i:], m.DisabledTypeUrls[iNdEx]) + i = encodeVarintTypes(dAtA, i, uint64(len(m.DisabledTypeUrls[iNdEx]))) + i-- + dAtA[i] = 0x12 + } + } + if len(m.AccountPermissions) > 0 { + for iNdEx := len(m.AccountPermissions) - 1; iNdEx >= 0; iNdEx-- { + { + size, err := m.AccountPermissions[iNdEx].MarshalToSizedBuffer(dAtA[:i]) + if err != nil { + return 0, err + } + i -= size + i = encodeVarintTypes(dAtA, i, uint64(size)) + } + i-- + dAtA[i] = 0xa + } + } + return len(dAtA) - i, nil +} + +func encodeVarintTypes(dAtA []byte, offset int, v uint64) int { + offset -= sovTypes(v) + base := offset + for v >= 1<<7 { + dAtA[offset] = uint8(v&0x7f | 0x80) + v >>= 7 + offset++ + } + dAtA[offset] = uint8(v) + return base +} +func (m *Permissions) Size() (n int) { + if m == nil { + return 0 + } + var l int + _ = l + if m.Level != 0 { + n += 1 + sovTypes(uint64(m.Level)) + } + if len(m.LimitTypeUrls) > 0 { + for _, s := range m.LimitTypeUrls { + l = len(s) + n += 1 + l + sovTypes(uint64(l)) + } + } + return n +} + +func (m *GenesisAccountPermissions) Size() (n int) { + if m == nil { + return 0 + } + var l int + _ = l + l = len(m.Address) + if l > 0 { + n += 1 + l + sovTypes(uint64(l)) + } + if m.Permissions != nil { + l = m.Permissions.Size() + n += 1 + l + sovTypes(uint64(l)) + } + return n +} + +func (m *GenesisState) Size() (n int) { + if m == nil { + return 0 + } + var l int + _ = l + if len(m.AccountPermissions) > 0 { + for _, e := range m.AccountPermissions { + l = e.Size() + n += 1 + l + sovTypes(uint64(l)) + } + } + if len(m.DisabledTypeUrls) > 0 { + for _, s := range m.DisabledTypeUrls { + l = len(s) + n += 1 + l + sovTypes(uint64(l)) + } + } + return n +} + +func sovTypes(x uint64) (n int) { + return (math_bits.Len64(x|1) + 6) / 7 +} +func sozTypes(x uint64) (n int) { + return sovTypes(uint64((x << 1) ^ uint64((int64(x) >> 63)))) +} +func (m *Permissions) Unmarshal(dAtA []byte) error { + l := len(dAtA) + iNdEx := 0 + for iNdEx < l { + preIndex := iNdEx + var wire uint64 + for shift := uint(0); ; shift += 7 { + if shift >= 64 { + return ErrIntOverflowTypes + } + if iNdEx >= l { + return io.ErrUnexpectedEOF + } + b := dAtA[iNdEx] + iNdEx++ + wire |= uint64(b&0x7F) << shift + if b < 0x80 { + break + } + } + fieldNum := int32(wire >> 3) + wireType := int(wire & 0x7) + if wireType == 4 { + return fmt.Errorf("proto: Permissions: wiretype end group for non-group") + } + if fieldNum <= 0 { + return fmt.Errorf("proto: Permissions: illegal tag %d (wire type %d)", fieldNum, wire) + } + switch fieldNum { + case 1: + if wireType != 0 { + return fmt.Errorf("proto: wrong wireType = %d for field Level", wireType) + } + m.Level = 0 + for shift := uint(0); ; shift += 7 { + if shift >= 64 { + return ErrIntOverflowTypes + } + if iNdEx >= l { + return io.ErrUnexpectedEOF + } + b := dAtA[iNdEx] + iNdEx++ + m.Level |= Permissions_Level(b&0x7F) << shift + if b < 0x80 { + break + } + } + case 2: + if wireType != 2 { + return fmt.Errorf("proto: wrong wireType = %d for field LimitTypeUrls", wireType) + } + var stringLen uint64 + for shift := uint(0); ; shift += 7 { + if shift >= 64 { + return ErrIntOverflowTypes + } + if iNdEx >= l { + return io.ErrUnexpectedEOF + } + b := dAtA[iNdEx] + iNdEx++ + stringLen |= uint64(b&0x7F) << shift + if b < 0x80 { + break + } + } + intStringLen := int(stringLen) + if intStringLen < 0 { + return ErrInvalidLengthTypes + } + postIndex := iNdEx + intStringLen + if postIndex < 0 { + return ErrInvalidLengthTypes + } + if postIndex > l { + return io.ErrUnexpectedEOF + } + m.LimitTypeUrls = append(m.LimitTypeUrls, string(dAtA[iNdEx:postIndex])) + iNdEx = postIndex + default: + iNdEx = preIndex + skippy, err := skipTypes(dAtA[iNdEx:]) + if err != nil { + return err + } + if (skippy < 0) || (iNdEx+skippy) < 0 { + return ErrInvalidLengthTypes + } + if (iNdEx + skippy) > l { + return io.ErrUnexpectedEOF + } + iNdEx += skippy + } + } + + if iNdEx > l { + return io.ErrUnexpectedEOF + } + return nil +} +func (m *GenesisAccountPermissions) Unmarshal(dAtA []byte) error { + l := len(dAtA) + iNdEx := 0 + for iNdEx < l { + preIndex := iNdEx + var wire uint64 + for shift := uint(0); ; shift += 7 { + if shift >= 64 { + return ErrIntOverflowTypes + } + if iNdEx >= l { + return io.ErrUnexpectedEOF + } + b := dAtA[iNdEx] + iNdEx++ + wire |= uint64(b&0x7F) << shift + if b < 0x80 { + break + } + } + fieldNum := int32(wire >> 3) + wireType := int(wire & 0x7) + if wireType == 4 { + return fmt.Errorf("proto: GenesisAccountPermissions: wiretype end group for non-group") + } + if fieldNum <= 0 { + return fmt.Errorf("proto: GenesisAccountPermissions: illegal tag %d (wire type %d)", fieldNum, wire) + } + switch fieldNum { + case 1: + if wireType != 2 { + return fmt.Errorf("proto: wrong wireType = %d for field Address", wireType) + } + var stringLen uint64 + for shift := uint(0); ; shift += 7 { + if shift >= 64 { + return ErrIntOverflowTypes + } + if iNdEx >= l { + return io.ErrUnexpectedEOF + } + b := dAtA[iNdEx] + iNdEx++ + stringLen |= uint64(b&0x7F) << shift + if b < 0x80 { + break + } + } + intStringLen := int(stringLen) + if intStringLen < 0 { + return ErrInvalidLengthTypes + } + postIndex := iNdEx + intStringLen + if postIndex < 0 { + return ErrInvalidLengthTypes + } + if postIndex > l { + return io.ErrUnexpectedEOF + } + m.Address = string(dAtA[iNdEx:postIndex]) + iNdEx = postIndex + case 2: + if wireType != 2 { + return fmt.Errorf("proto: wrong wireType = %d for field Permissions", wireType) + } + var msglen int + for shift := uint(0); ; shift += 7 { + if shift >= 64 { + return ErrIntOverflowTypes + } + if iNdEx >= l { + return io.ErrUnexpectedEOF + } + b := dAtA[iNdEx] + iNdEx++ + msglen |= int(b&0x7F) << shift + if b < 0x80 { + break + } + } + if msglen < 0 { + return ErrInvalidLengthTypes + } + postIndex := iNdEx + msglen + if postIndex < 0 { + return ErrInvalidLengthTypes + } + if postIndex > l { + return io.ErrUnexpectedEOF + } + if m.Permissions == nil { + m.Permissions = &Permissions{} + } + if err := m.Permissions.Unmarshal(dAtA[iNdEx:postIndex]); err != nil { + return err + } + iNdEx = postIndex + default: + iNdEx = preIndex + skippy, err := skipTypes(dAtA[iNdEx:]) + if err != nil { + return err + } + if (skippy < 0) || (iNdEx+skippy) < 0 { + return ErrInvalidLengthTypes + } + if (iNdEx + skippy) > l { + return io.ErrUnexpectedEOF + } + iNdEx += skippy + } + } + + if iNdEx > l { + return io.ErrUnexpectedEOF + } + return nil +} +func (m *GenesisState) Unmarshal(dAtA []byte) error { + l := len(dAtA) + iNdEx := 0 + for iNdEx < l { + preIndex := iNdEx + var wire uint64 + for shift := uint(0); ; shift += 7 { + if shift >= 64 { + return ErrIntOverflowTypes + } + if iNdEx >= l { + return io.ErrUnexpectedEOF + } + b := dAtA[iNdEx] + iNdEx++ + wire |= uint64(b&0x7F) << shift + if b < 0x80 { + break + } + } + fieldNum := int32(wire >> 3) + wireType := int(wire & 0x7) + if wireType == 4 { + return fmt.Errorf("proto: GenesisState: wiretype end group for non-group") + } + if fieldNum <= 0 { + return fmt.Errorf("proto: GenesisState: illegal tag %d (wire type %d)", fieldNum, wire) + } + switch fieldNum { + case 1: + if wireType != 2 { + return fmt.Errorf("proto: wrong wireType = %d for field AccountPermissions", wireType) + } + var msglen int + for shift := uint(0); ; shift += 7 { + if shift >= 64 { + return ErrIntOverflowTypes + } + if iNdEx >= l { + return io.ErrUnexpectedEOF + } + b := dAtA[iNdEx] + iNdEx++ + msglen |= int(b&0x7F) << shift + if b < 0x80 { + break + } + } + if msglen < 0 { + return ErrInvalidLengthTypes + } + postIndex := iNdEx + msglen + if postIndex < 0 { + return ErrInvalidLengthTypes + } + if postIndex > l { + return io.ErrUnexpectedEOF + } + m.AccountPermissions = append(m.AccountPermissions, &GenesisAccountPermissions{}) + if err := m.AccountPermissions[len(m.AccountPermissions)-1].Unmarshal(dAtA[iNdEx:postIndex]); err != nil { + return err + } + iNdEx = postIndex + case 2: + if wireType != 2 { + return fmt.Errorf("proto: wrong wireType = %d for field DisabledTypeUrls", wireType) + } + var stringLen uint64 + for shift := uint(0); ; shift += 7 { + if shift >= 64 { + return ErrIntOverflowTypes + } + if iNdEx >= l { + return io.ErrUnexpectedEOF + } + b := dAtA[iNdEx] + iNdEx++ + stringLen |= uint64(b&0x7F) << shift + if b < 0x80 { + break + } + } + intStringLen := int(stringLen) + if intStringLen < 0 { + return ErrInvalidLengthTypes + } + postIndex := iNdEx + intStringLen + if postIndex < 0 { + return ErrInvalidLengthTypes + } + if postIndex > l { + return io.ErrUnexpectedEOF + } + m.DisabledTypeUrls = append(m.DisabledTypeUrls, string(dAtA[iNdEx:postIndex])) + iNdEx = postIndex + default: + iNdEx = preIndex + skippy, err := skipTypes(dAtA[iNdEx:]) + if err != nil { + return err + } + if (skippy < 0) || (iNdEx+skippy) < 0 { + return ErrInvalidLengthTypes + } + if (iNdEx + skippy) > l { + return io.ErrUnexpectedEOF + } + iNdEx += skippy + } + } + + if iNdEx > l { + return io.ErrUnexpectedEOF + } + return nil +} +func skipTypes(dAtA []byte) (n int, err error) { + l := len(dAtA) + iNdEx := 0 + depth := 0 + for iNdEx < l { + var wire uint64 + for shift := uint(0); ; shift += 7 { + if shift >= 64 { + return 0, ErrIntOverflowTypes + } + if iNdEx >= l { + return 0, io.ErrUnexpectedEOF + } + b := dAtA[iNdEx] + iNdEx++ + wire |= (uint64(b) & 0x7F) << shift + if b < 0x80 { + break + } + } + wireType := int(wire & 0x7) + switch wireType { + case 0: + for shift := uint(0); ; shift += 7 { + if shift >= 64 { + return 0, ErrIntOverflowTypes + } + if iNdEx >= l { + return 0, io.ErrUnexpectedEOF + } + iNdEx++ + if dAtA[iNdEx-1] < 0x80 { + break + } + } + case 1: + iNdEx += 8 + case 2: + var length int + for shift := uint(0); ; shift += 7 { + if shift >= 64 { + return 0, ErrIntOverflowTypes + } + if iNdEx >= l { + return 0, io.ErrUnexpectedEOF + } + b := dAtA[iNdEx] + iNdEx++ + length |= (int(b) & 0x7F) << shift + if b < 0x80 { + break + } + } + if length < 0 { + return 0, ErrInvalidLengthTypes + } + iNdEx += length + case 3: + depth++ + case 4: + if depth == 0 { + return 0, ErrUnexpectedEndOfGroupTypes + } + depth-- + case 5: + iNdEx += 4 + default: + return 0, fmt.Errorf("proto: illegal wireType %d", wireType) + } + if iNdEx < 0 { + return 0, ErrInvalidLengthTypes + } + if depth == 0 { + return iNdEx, nil + } + } + return 0, io.ErrUnexpectedEOF +} + +var ( + ErrInvalidLengthTypes = fmt.Errorf("proto: negative length found during unmarshaling") + ErrIntOverflowTypes = fmt.Errorf("proto: integer overflow") + ErrUnexpectedEndOfGroupTypes = fmt.Errorf("proto: unexpected end of group") +) diff --git a/x/consensus/keeper/grpc_query.go b/x/consensus/keeper/grpc_query.go deleted file mode 100644 index 9477e5951749..000000000000 --- a/x/consensus/keeper/grpc_query.go +++ /dev/null @@ -1,35 +0,0 @@ -package keeper - -import ( - "context" - - "google.golang.org/grpc/codes" - "google.golang.org/grpc/status" - - sdk "github.com/cosmos/cosmos-sdk/types" - "github.com/cosmos/cosmos-sdk/x/consensus/types" -) - -var _ types.QueryServer = Querier{} - -// Querier is used as Keeper will have duplicate methods if used directly, and gRPC names take precedence over keeper -type Querier struct { - Keeper -} - -// NewQuerier constructor for the Querier struct -func NewQuerier(keeper Keeper) Querier { - return Querier{Keeper: keeper} -} - -// Params queries params of consensus module -func (k Querier) Params(ctx context.Context, _ *types.QueryParamsRequest) (*types.QueryParamsResponse, error) { - sdkCtx := sdk.UnwrapSDKContext(ctx) - - params, err := k.Keeper.Get(sdkCtx) - if err != nil { - return nil, status.Error(codes.Internal, err.Error()) - } - - return &types.QueryParamsResponse{Params: params}, nil -} diff --git a/x/consensus/keeper/grpc_query_test.go b/x/consensus/keeper/grpc_query_test.go deleted file mode 100644 index eeee2ccf5cbc..000000000000 --- a/x/consensus/keeper/grpc_query_test.go +++ /dev/null @@ -1,61 +0,0 @@ -package keeper_test - -import ( - cmtproto "github.com/cometbft/cometbft/proto/tendermint/types" - cmttypes "github.com/cometbft/cometbft/types" - - "github.com/cosmos/cosmos-sdk/x/consensus/types" -) - -func (s *KeeperTestSuite) TestGRPCQueryConsensusParams() { - defaultConsensusParams := cmttypes.DefaultConsensusParams().ToProto() - - testCases := []struct { - msg string - req types.QueryParamsRequest - malleate func() - response types.QueryParamsResponse - expPass bool - }{ - { - "success", - types.QueryParamsRequest{}, - func() { - input := &types.MsgUpdateParams{ - Authority: s.consensusParamsKeeper.GetAuthority(), - Block: defaultConsensusParams.Block, - Validator: defaultConsensusParams.Validator, - Evidence: defaultConsensusParams.Evidence, - } - s.msgServer.UpdateParams(s.ctx, input) - }, - types.QueryParamsResponse{ - Params: &cmtproto.ConsensusParams{ - Block: defaultConsensusParams.Block, - Validator: defaultConsensusParams.Validator, - Evidence: defaultConsensusParams.Evidence, - Version: defaultConsensusParams.Version, - }, - }, - true, - }, - } - - for _, tc := range testCases { - s.Run(tc.msg, func() { - s.SetupTest() // reset - - tc.malleate() - res, err := s.queryClient.Params(s.ctx, &tc.req) - - if tc.expPass { - s.Require().NoError(err) - s.Require().NotNil(res) - s.Require().Equal(tc.response.Params, res.Params) - } else { - s.Require().Error(err) - s.Require().Nil(res) - } - }) - } -} diff --git a/x/consensus/keeper/keeper.go b/x/consensus/keeper/keeper.go index d2e9efef6fd3..837ced7e05c4 100644 --- a/x/consensus/keeper/keeper.go +++ b/x/consensus/keeper/keeper.go @@ -3,29 +3,37 @@ package keeper import ( "context" - cmtproto "github.com/cometbft/cometbft/proto/tendermint/types" - + "cosmossdk.io/collections" + "cosmossdk.io/core/event" storetypes "cosmossdk.io/core/store" + "cosmossdk.io/errors" + cmtproto "github.com/cometbft/cometbft/proto/tendermint/types" + cmttypes "github.com/cometbft/cometbft/types" + "google.golang.org/grpc/codes" + "google.golang.org/grpc/status" "github.com/cosmos/cosmos-sdk/codec" - "github.com/cosmos/cosmos-sdk/x/consensus/exported" "github.com/cosmos/cosmos-sdk/x/consensus/types" + govtypes "github.com/cosmos/cosmos-sdk/x/gov/types" ) -var _ exported.ConsensusParamSetter = (*Keeper)(nil) +var StoreKey = "Consensus" type Keeper struct { storeService storetypes.KVStoreService - cdc codec.BinaryCodec + event event.Service - authority string + authority string + ParamsStore collections.Item[cmtproto.ConsensusParams] } -func NewKeeper(cdc codec.BinaryCodec, storeService storetypes.KVStoreService, authority string) Keeper { +func NewKeeper(cdc codec.BinaryCodec, storeService storetypes.KVStoreService, authority string, em event.Service) Keeper { + sb := collections.NewSchemaBuilder(storeService) return Keeper{ storeService: storeService, - cdc: cdc, authority: authority, + event: em, + ParamsStore: collections.NewItem(sb, collections.NewPrefix("Consensus"), "params", codec.CollValue[cmtproto.ConsensusParams](cdc)), } } @@ -33,30 +41,45 @@ func (k *Keeper) GetAuthority() string { return k.authority } -// Get gets the consensus parameters -func (k *Keeper) Get(ctx context.Context) (*cmtproto.ConsensusParams, error) { - store := k.storeService.OpenKVStore(ctx) +// Querier - bz, err := store.Get(types.ParamStoreKeyConsensusParams) +var _ types.QueryServer = Keeper{} + +// Params queries params of consensus module +func (k Keeper) Params(ctx context.Context, _ *types.QueryParamsRequest) (*types.QueryParamsResponse, error) { + params, err := k.ParamsStore.Get(ctx) if err != nil { - return nil, err + return nil, status.Error(codes.Internal, err.Error()) } - cp := &cmtproto.ConsensusParams{} - if err := k.cdc.Unmarshal(bz, cp); err != nil { + return &types.QueryParamsResponse{Params: ¶ms}, nil +} + +// MsgServer + +var _ types.MsgServer = Keeper{} + +func (k Keeper) UpdateParams(ctx context.Context, msg *types.MsgUpdateParams) (*types.MsgUpdateParamsResponse, error) { + if k.GetAuthority() != msg.Authority { + return nil, errors.Wrapf(govtypes.ErrInvalidSigner, "invalid authority; expected %s, got %s", k.GetAuthority(), msg.Authority) + } + + consensusParams := msg.ToProtoConsensusParams() + if err := cmttypes.ConsensusParamsFromProto(consensusParams).ValidateBasic(); err != nil { return nil, err } - return cp, nil -} + if err := k.ParamsStore.Set(ctx, consensusParams); err != nil { + return nil, err + } -func (k *Keeper) Has(ctx context.Context) (bool, error) { - store := k.storeService.OpenKVStore(ctx) - return store.Has(types.ParamStoreKeyConsensusParams) -} + if err := k.event.EventManager(ctx).EmitKV( + ctx, + "update_consensus_params", + event.Attribute{Key: "authority", Value: msg.Authority}, + event.Attribute{Key: "parameters", Value: consensusParams.String()}); err != nil { + return nil, err + } -// Set sets the consensus parameters -func (k *Keeper) Set(ctx context.Context, cp *cmtproto.ConsensusParams) error { - store := k.storeService.OpenKVStore(ctx) - return store.Set(types.ParamStoreKeyConsensusParams, k.cdc.MustMarshal(cp)) + return &types.MsgUpdateParamsResponse{}, nil } diff --git a/x/consensus/keeper/keeper_test.go b/x/consensus/keeper/keeper_test.go index 2ac0108c3581..e1b142d319c3 100644 --- a/x/consensus/keeper/keeper_test.go +++ b/x/consensus/keeper/keeper_test.go @@ -4,6 +4,7 @@ import ( "testing" cmtproto "github.com/cometbft/cometbft/proto/tendermint/types" + cmttypes "github.com/cometbft/cometbft/types" "github.com/stretchr/testify/suite" storetypes "cosmossdk.io/store/types" @@ -15,7 +16,7 @@ import ( moduletestutil "github.com/cosmos/cosmos-sdk/types/module/testutil" authtypes "github.com/cosmos/cosmos-sdk/x/auth/types" consensusparamkeeper "github.com/cosmos/cosmos-sdk/x/consensus/keeper" - consensusparamtypes "github.com/cosmos/cosmos-sdk/x/consensus/types" + "github.com/cosmos/cosmos-sdk/x/consensus/types" govtypes "github.com/cosmos/cosmos-sdk/x/gov/types" ) @@ -24,29 +25,138 @@ type KeeperTestSuite struct { ctx sdk.Context consensusParamsKeeper *consensusparamkeeper.Keeper - queryClient consensusparamtypes.QueryClient - msgServer consensusparamtypes.MsgServer + queryClient types.QueryClient } func (s *KeeperTestSuite) SetupTest() { - key := storetypes.NewKVStoreKey(consensusparamtypes.StoreKey) + key := storetypes.NewKVStoreKey(consensusparamkeeper.StoreKey) testCtx := testutil.DefaultContextWithDB(s.T(), key, storetypes.NewTransientStoreKey("transient_test")) ctx := testCtx.Ctx.WithBlockHeader(cmtproto.Header{}) encCfg := moduletestutil.MakeTestEncodingConfig() storeService := runtime.NewKVStoreService(key) - keeper := consensusparamkeeper.NewKeeper(encCfg.Codec, storeService, authtypes.NewModuleAddress(govtypes.ModuleName).String()) + keeper := consensusparamkeeper.NewKeeper(encCfg.Codec, storeService, authtypes.NewModuleAddress(govtypes.ModuleName).String(), runtime.EventService{}) s.ctx = ctx s.consensusParamsKeeper = &keeper - consensusparamtypes.RegisterInterfaces(encCfg.InterfaceRegistry) + types.RegisterInterfaces(encCfg.InterfaceRegistry) queryHelper := baseapp.NewQueryServerTestHelper(ctx, encCfg.InterfaceRegistry) - consensusparamtypes.RegisterQueryServer(queryHelper, consensusparamkeeper.NewQuerier(keeper)) - s.queryClient = consensusparamtypes.NewQueryClient(queryHelper) - s.msgServer = consensusparamkeeper.NewMsgServerImpl(keeper) + types.RegisterQueryServer(queryHelper, keeper) + s.queryClient = types.NewQueryClient(queryHelper) } func TestKeeperTestSuite(t *testing.T) { suite.Run(t, new(KeeperTestSuite)) } + +func (s *KeeperTestSuite) TestGRPCQueryConsensusParams() { + defaultConsensusParams := cmttypes.DefaultConsensusParams().ToProto() + + testCases := []struct { + msg string + req types.QueryParamsRequest + malleate func() + response types.QueryParamsResponse + expPass bool + }{ + { + "success", + types.QueryParamsRequest{}, + func() { + input := &types.MsgUpdateParams{ + Authority: s.consensusParamsKeeper.GetAuthority(), + Block: defaultConsensusParams.Block, + Validator: defaultConsensusParams.Validator, + Evidence: defaultConsensusParams.Evidence, + } + s.consensusParamsKeeper.UpdateParams(s.ctx, input) + }, + types.QueryParamsResponse{ + Params: &cmtproto.ConsensusParams{ + Block: defaultConsensusParams.Block, + Validator: defaultConsensusParams.Validator, + Evidence: defaultConsensusParams.Evidence, + Version: defaultConsensusParams.Version, + }, + }, + true, + }, + } + + for _, tc := range testCases { + s.Run(tc.msg, func() { + s.SetupTest() // reset + + tc.malleate() + res, err := s.consensusParamsKeeper.Params(s.ctx, &tc.req) + + if tc.expPass { + s.Require().NoError(err) + s.Require().NotNil(res) + s.Require().Equal(tc.response.Params, res.Params) + } else { + s.Require().Error(err) + s.Require().Nil(res) + } + }) + } +} + +func (s *KeeperTestSuite) TestUpdateParams() { + defaultConsensusParams := cmttypes.DefaultConsensusParams().ToProto() + testCases := []struct { + name string + input *types.MsgUpdateParams + expErr bool + expErrMsg string + }{ + { + name: "valid params", + input: &types.MsgUpdateParams{ + Authority: s.consensusParamsKeeper.GetAuthority(), + Block: defaultConsensusParams.Block, + Validator: defaultConsensusParams.Validator, + Evidence: defaultConsensusParams.Evidence, + }, + expErr: false, + expErrMsg: "", + }, + { + name: "invalid params", + input: &types.MsgUpdateParams{ + Authority: s.consensusParamsKeeper.GetAuthority(), + Block: &cmtproto.BlockParams{MaxGas: -10, MaxBytes: -10}, + Validator: defaultConsensusParams.Validator, + Evidence: defaultConsensusParams.Evidence, + }, + expErr: true, + expErrMsg: "block.MaxBytes must be greater than 0. Got -10", + }, + { + name: "invalid authority", + input: &types.MsgUpdateParams{ + Authority: "invalid", + Block: defaultConsensusParams.Block, + Validator: defaultConsensusParams.Validator, + Evidence: defaultConsensusParams.Evidence, + }, + expErr: true, + expErrMsg: "invalid authority", + }, + } + + for _, tc := range testCases { + tc := tc + s.Run(tc.name, func() { + s.SetupTest() + _, err := s.consensusParamsKeeper.UpdateParams(s.ctx, tc.input) + if tc.expErr { + s.Require().Error(err) + s.Require().Contains(err.Error(), tc.expErrMsg) + } else { + s.Require().NoError(err) + } + }) + } +} diff --git a/x/consensus/keeper/msg_server.go b/x/consensus/keeper/msg_server.go deleted file mode 100644 index ed43cfdf29e5..000000000000 --- a/x/consensus/keeper/msg_server.go +++ /dev/null @@ -1,42 +0,0 @@ -package keeper - -import ( - "context" - - cmttypes "github.com/cometbft/cometbft/types" - - "cosmossdk.io/errors" - - sdk "github.com/cosmos/cosmos-sdk/types" - "github.com/cosmos/cosmos-sdk/x/consensus/types" - govtypes "github.com/cosmos/cosmos-sdk/x/gov/types" -) - -type msgServer struct { - Keeper -} - -var _ types.MsgServer = msgServer{} - -// NewMsgServerImpl returns an implementation of the bank MsgServer interface -// for the provided Keeper. -func NewMsgServerImpl(keeper Keeper) types.MsgServer { - return &msgServer{Keeper: keeper} -} - -func (k msgServer) UpdateParams(goCtx context.Context, req *types.MsgUpdateParams) (*types.MsgUpdateParamsResponse, error) { - if k.GetAuthority() != req.Authority { - return nil, errors.Wrapf(govtypes.ErrInvalidSigner, "invalid authority; expected %s, got %s", k.GetAuthority(), req.Authority) - } - - ctx := sdk.UnwrapSDKContext(goCtx) - - consensusParams := req.ToProtoConsensusParams() - if err := cmttypes.ConsensusParamsFromProto(consensusParams).ValidateBasic(); err != nil { - return nil, err - } - - k.Set(ctx, &consensusParams) - - return &types.MsgUpdateParamsResponse{}, nil -} diff --git a/x/consensus/keeper/msg_server_test.go b/x/consensus/keeper/msg_server_test.go deleted file mode 100644 index 0de099a83e82..000000000000 --- a/x/consensus/keeper/msg_server_test.go +++ /dev/null @@ -1,65 +0,0 @@ -package keeper_test - -import ( - cmtproto "github.com/cometbft/cometbft/proto/tendermint/types" - cmttypes "github.com/cometbft/cometbft/types" - "github.com/cosmos/cosmos-sdk/x/consensus/types" -) - -func (s *KeeperTestSuite) TestUpdateParams() { - defaultConsensusParams := cmttypes.DefaultConsensusParams().ToProto() - testCases := []struct { - name string - input *types.MsgUpdateParams - expErr bool - expErrMsg string - }{ - { - name: "valid params", - input: &types.MsgUpdateParams{ - Authority: s.consensusParamsKeeper.GetAuthority(), - Block: defaultConsensusParams.Block, - Validator: defaultConsensusParams.Validator, - Evidence: defaultConsensusParams.Evidence, - }, - expErr: false, - expErrMsg: "", - }, - { - name: "invalid params", - input: &types.MsgUpdateParams{ - Authority: s.consensusParamsKeeper.GetAuthority(), - Block: &cmtproto.BlockParams{MaxGas: -10, MaxBytes: -10}, - Validator: defaultConsensusParams.Validator, - Evidence: defaultConsensusParams.Evidence, - }, - expErr: true, - expErrMsg: "block.MaxBytes must be greater than 0. Got -10", - }, - { - name: "invalid authority", - input: &types.MsgUpdateParams{ - Authority: "invalid", - Block: defaultConsensusParams.Block, - Validator: defaultConsensusParams.Validator, - Evidence: defaultConsensusParams.Evidence, - }, - expErr: true, - expErrMsg: "invalid authority", - }, - } - - for _, tc := range testCases { - tc := tc - s.Run(tc.name, func() { - s.SetupTest() - _, err := s.msgServer.UpdateParams(s.ctx, tc.input) - if tc.expErr { - s.Require().Error(err) - s.Require().Contains(err.Error(), tc.expErrMsg) - } else { - s.Require().NoError(err) - } - }) - } -} diff --git a/x/consensus/module.go b/x/consensus/module.go index 8c6f87346daa..1834077305f9 100644 --- a/x/consensus/module.go +++ b/x/consensus/module.go @@ -6,6 +6,7 @@ import ( modulev1 "cosmossdk.io/api/cosmos/consensus/module/v1" "cosmossdk.io/core/appmodule" + "cosmossdk.io/core/event" "cosmossdk.io/depinject" abci "github.com/cometbft/cometbft/abci/types" gwruntime "github.com/grpc-ecosystem/grpc-gateway/runtime" @@ -102,8 +103,8 @@ func (am AppModule) IsAppModule() {} // RegisterServices registers module services. func (am AppModule) RegisterServices(registrar grpc.ServiceRegistrar) error { - types.RegisterMsgServer(registrar, keeper.NewMsgServerImpl(am.keeper)) - types.RegisterQueryServer(registrar, keeper.NewQuerier(am.keeper)) + types.RegisterMsgServer(registrar, am.keeper) + types.RegisterQueryServer(registrar, am.keeper) return nil } @@ -140,17 +141,16 @@ func init() { ) } -//nolint:revive -type ConsensusInputs struct { +type ModuleInputs struct { depinject.In Config *modulev1.Module Cdc codec.Codec StoreService storetypes.KVStoreService + EventManager event.Service } -//nolint:revive -type ConsensusOutputs struct { +type ModuleOutputs struct { depinject.Out Keeper keeper.Keeper @@ -158,20 +158,20 @@ type ConsensusOutputs struct { BaseAppOption runtime.BaseAppOption } -func ProvideModule(in ConsensusInputs) ConsensusOutputs { +func ProvideModule(in ModuleInputs) ModuleOutputs { // default to governance authority if not provided authority := authtypes.NewModuleAddress(govtypes.ModuleName) if in.Config.Authority != "" { authority = authtypes.NewModuleAddressOrBech32Address(in.Config.Authority) } - k := keeper.NewKeeper(in.Cdc, in.StoreService, authority.String()) + k := keeper.NewKeeper(in.Cdc, in.StoreService, authority.String(), in.EventManager) m := NewAppModule(in.Cdc, k) baseappOpt := func(app *baseapp.BaseApp) { - app.SetParamStore(&k) + app.SetParamStore(k.ParamsStore) } - return ConsensusOutputs{ + return ModuleOutputs{ Keeper: k, Module: m, BaseAppOption: baseappOpt, diff --git a/x/consensus/types/keys.go b/x/consensus/types/keys.go index 5ce0fc2cbe4a..2bdad4c21dd4 100644 --- a/x/consensus/types/keys.go +++ b/x/consensus/types/keys.go @@ -7,5 +7,3 @@ const ( // StoreKey defines the module's store key. StoreKey = ModuleName ) - -var ParamStoreKeyConsensusParams = []byte("Consensus") diff --git a/x/consensus/types/msgs.go b/x/consensus/types/msgs.go index 7b0ac5c94da1..c04ac71da713 100644 --- a/x/consensus/types/msgs.go +++ b/x/consensus/types/msgs.go @@ -23,13 +23,7 @@ func (msg MsgUpdateParams) GetSigners() []sdk.AccAddress { // GetSignBytes returns the raw bytes for a MsgUpdateParams message that // the expected signer needs to sign. func (msg MsgUpdateParams) GetSignBytes() []byte { - return sdk.MustSortJSON(ModuleCdc.MustMarshalJSON(&msg)) -} - -// ValidateBasic performs basic MsgUpdateParams message validation. -func (msg MsgUpdateParams) ValidateBasic() error { - params := cmttypes.ConsensusParamsFromProto(msg.ToProtoConsensusParams()) - return params.ValidateBasic() + return sdk.MustSortJSON(amino.MustMarshalJSON(&msg)) } func (msg MsgUpdateParams) ToProtoConsensusParams() cmtproto.ConsensusParams { diff --git a/x/crisis/client/cli/tx_test.go b/x/crisis/client/cli/tx_test.go index f479949bac0f..d62bc1c977ed 100644 --- a/x/crisis/client/cli/tx_test.go +++ b/x/crisis/client/cli/tx_test.go @@ -6,6 +6,7 @@ import ( "io" "testing" + sdkmath "cosmossdk.io/math" rpcclientmock "github.com/cometbft/cometbft/rpc/client/mock" clitestutil "github.com/cosmos/cosmos-sdk/testutil/cli" "github.com/stretchr/testify/require" @@ -37,9 +38,7 @@ func TestNewMsgVerifyInvariantTxCmd(t *testing.T) { testCases := []struct { name string args []string - expectErr bool - errString string - expectedCode uint32 + expectErrMsg string }{ { "missing module", @@ -48,9 +47,9 @@ func TestNewMsgVerifyInvariantTxCmd(t *testing.T) { fmt.Sprintf("--%s=%s", flags.FlagFrom, accounts[0].Address.String()), fmt.Sprintf("--%s=true", flags.FlagSkipConfirmation), fmt.Sprintf("--%s=%s", flags.FlagBroadcastMode, flags.BroadcastSync), - fmt.Sprintf("--%s=%s", flags.FlagFees, sdk.NewCoins(sdk.NewCoin(sdk.DefaultBondDenom, sdk.NewInt(10))).String()), + fmt.Sprintf("--%s=%s", flags.FlagFees, sdk.NewCoins(sdk.NewCoin(sdk.DefaultBondDenom, sdkmath.NewInt(10))).String()), }, - true, "invalid module name", 0, + "invalid module name", }, { "missing invariant route", @@ -59,9 +58,9 @@ func TestNewMsgVerifyInvariantTxCmd(t *testing.T) { fmt.Sprintf("--%s=%s", flags.FlagFrom, accounts[0].Address.String()), fmt.Sprintf("--%s=true", flags.FlagSkipConfirmation), fmt.Sprintf("--%s=%s", flags.FlagBroadcastMode, flags.BroadcastSync), - fmt.Sprintf("--%s=%s", flags.FlagFees, sdk.NewCoins(sdk.NewCoin(sdk.DefaultBondDenom, sdk.NewInt(10))).String()), + fmt.Sprintf("--%s=%s", flags.FlagFees, sdk.NewCoins(sdk.NewCoin(sdk.DefaultBondDenom, sdkmath.NewInt(10))).String()), }, - true, "invalid invariant route", 0, + "invalid invariant route", }, { "valid transaction", @@ -70,9 +69,9 @@ func TestNewMsgVerifyInvariantTxCmd(t *testing.T) { fmt.Sprintf("--%s=%s", flags.FlagFrom, accounts[0].Address.String()), fmt.Sprintf("--%s=true", flags.FlagSkipConfirmation), fmt.Sprintf("--%s=%s", flags.FlagBroadcastMode, flags.BroadcastSync), - fmt.Sprintf("--%s=%s", flags.FlagFees, sdk.NewCoins(sdk.NewCoin(sdk.DefaultBondDenom, sdk.NewInt(10))).String()), + fmt.Sprintf("--%s=%s", flags.FlagFees, sdk.NewCoins(sdk.NewCoin(sdk.DefaultBondDenom, sdkmath.NewInt(10))).String()), }, - false, "", 0, + "", }, } @@ -80,22 +79,19 @@ func TestNewMsgVerifyInvariantTxCmd(t *testing.T) { tc := tc t.Run(tc.name, func(t *testing.T) { ctx := svrcmd.CreateExecuteContext(context.Background()) - cmd := cli.NewMsgVerifyInvariantTxCmd() - cmd.SetOut(io.Discard) - require.NotNil(t, cmd) - cmd.SetContext(ctx) cmd.SetArgs(tc.args) - require.NoError(t, client.SetCmdClientContextHandler(baseCtx, cmd)) - err := cmd.Execute() - if tc.expectErr { + out, err := clitestutil.ExecTestCLICmd(baseCtx, cmd, tc.args) + if tc.expectErrMsg != "" { require.Error(t, err) - require.Contains(t, err.Error(), tc.errString) + require.Contains(t, out.String(), tc.expectErrMsg) } else { require.NoError(t, err) + msg := &sdk.TxResponse{} + require.NoError(t, baseCtx.Codec.UnmarshalJSON(out.Bytes(), msg), out.String()) } }) } diff --git a/x/crisis/keeper/genesis_test.go b/x/crisis/keeper/genesis_test.go index d31832a391fd..475e712f2629 100644 --- a/x/crisis/keeper/genesis_test.go +++ b/x/crisis/keeper/genesis_test.go @@ -6,9 +6,11 @@ import ( "github.com/golang/mock/gomock" "github.com/stretchr/testify/suite" + sdkmath "cosmossdk.io/math" storetypes "cosmossdk.io/store/types" "github.com/cosmos/cosmos-sdk/codec" + addresscodec "github.com/cosmos/cosmos-sdk/codec/address" "github.com/cosmos/cosmos-sdk/testutil" sdk "github.com/cosmos/cosmos-sdk/types" moduletestutil "github.com/cosmos/cosmos-sdk/types/module/testutil" @@ -42,18 +44,18 @@ func (s *GenesisTestSuite) SetupTest() { supplyKeeper := crisistestutil.NewMockSupplyKeeper(ctrl) - s.keeper = *keeper.NewKeeper(s.cdc, key, 5, supplyKeeper, "", "") + s.keeper = *keeper.NewKeeper(s.cdc, key, 5, supplyKeeper, "", "", addresscodec.NewBech32Codec("cosmos")) } func (s *GenesisTestSuite) TestImportExportGenesis() { // default params - constantFee := sdk.NewCoin(sdk.DefaultBondDenom, sdk.NewInt(1000)) + constantFee := sdk.NewCoin(sdk.DefaultBondDenom, sdkmath.NewInt(1000)) err := s.keeper.SetConstantFee(s.sdkCtx, constantFee) s.Require().NoError(err) genesis := s.keeper.ExportGenesis(s.sdkCtx) // set constant fee to zero - constantFee = sdk.NewCoin(sdk.DefaultBondDenom, sdk.NewInt(0)) + constantFee = sdk.NewCoin(sdk.DefaultBondDenom, sdkmath.NewInt(0)) err = s.keeper.SetConstantFee(s.sdkCtx, constantFee) s.Require().NoError(err) @@ -64,7 +66,7 @@ func (s *GenesisTestSuite) TestImportExportGenesis() { func (s *GenesisTestSuite) TestInitGenesis() { genesisState := types.DefaultGenesisState() - genesisState.ConstantFee = sdk.NewCoin(sdk.DefaultBondDenom, sdk.NewInt(1000)) + genesisState.ConstantFee = sdk.NewCoin(sdk.DefaultBondDenom, sdkmath.NewInt(1000)) s.keeper.InitGenesis(s.sdkCtx, genesisState) constantFee := s.keeper.GetConstantFee(s.sdkCtx) diff --git a/x/crisis/keeper/keeper.go b/x/crisis/keeper/keeper.go index 28f9c5d47da0..e987f813e660 100644 --- a/x/crisis/keeper/keeper.go +++ b/x/crisis/keeper/keeper.go @@ -4,6 +4,7 @@ import ( "fmt" "time" + "cosmossdk.io/core/address" "cosmossdk.io/log" storetypes "cosmossdk.io/store/types" @@ -27,12 +28,14 @@ type Keeper struct { supplyKeeper types.SupplyKeeper feeCollectorName string // name of the FeeCollector ModuleAccount + + addressCodec address.Codec } // NewKeeper creates a new Keeper object func NewKeeper( cdc codec.BinaryCodec, storeKey storetypes.StoreKey, invCheckPeriod uint, - supplyKeeper types.SupplyKeeper, feeCollectorName string, authority string, + supplyKeeper types.SupplyKeeper, feeCollectorName, authority string, ac address.Codec, ) *Keeper { return &Keeper{ storeKey: storeKey, @@ -42,6 +45,7 @@ func NewKeeper( supplyKeeper: supplyKeeper, feeCollectorName: feeCollectorName, authority: authority, + addressCodec: ac, } } diff --git a/x/crisis/keeper/keeper_test.go b/x/crisis/keeper/keeper_test.go index 1cbd6cb8422d..1a1eaa38cda6 100644 --- a/x/crisis/keeper/keeper_test.go +++ b/x/crisis/keeper/keeper_test.go @@ -8,6 +8,7 @@ import ( storetypes "cosmossdk.io/store/types" + addresscodec "github.com/cosmos/cosmos-sdk/codec/address" "github.com/cosmos/cosmos-sdk/testutil" sdk "github.com/cosmos/cosmos-sdk/types" moduletestutil "github.com/cosmos/cosmos-sdk/types/module/testutil" @@ -24,7 +25,7 @@ func TestLogger(t *testing.T) { key := storetypes.NewKVStoreKey(types.StoreKey) testCtx := testutil.DefaultContextWithDB(t, key, storetypes.NewTransientStoreKey("transient_test")) encCfg := moduletestutil.MakeTestEncodingConfig(crisis.AppModuleBasic{}) - keeper := keeper.NewKeeper(encCfg.Codec, key, 5, supplyKeeper, "", "") + keeper := keeper.NewKeeper(encCfg.Codec, key, 5, supplyKeeper, "", "", addresscodec.NewBech32Codec("cosmos")) require.Equal(t, testCtx.Ctx.Logger().With("module", "x/"+types.ModuleName), @@ -37,7 +38,7 @@ func TestInvariants(t *testing.T) { key := storetypes.NewKVStoreKey(types.StoreKey) encCfg := moduletestutil.MakeTestEncodingConfig(crisis.AppModuleBasic{}) - keeper := keeper.NewKeeper(encCfg.Codec, key, 5, supplyKeeper, "", "") + keeper := keeper.NewKeeper(encCfg.Codec, key, 5, supplyKeeper, "", "", addresscodec.NewBech32Codec("cosmos")) require.Equal(t, keeper.InvCheckPeriod(), uint(5)) orgInvRoutes := keeper.Routes() @@ -53,7 +54,7 @@ func TestAssertInvariants(t *testing.T) { key := storetypes.NewKVStoreKey(types.StoreKey) testCtx := testutil.DefaultContextWithDB(t, key, storetypes.NewTransientStoreKey("transient_test")) encCfg := moduletestutil.MakeTestEncodingConfig(crisis.AppModuleBasic{}) - keeper := keeper.NewKeeper(encCfg.Codec, key, 5, supplyKeeper, "", "") + keeper := keeper.NewKeeper(encCfg.Codec, key, 5, supplyKeeper, "", "", addresscodec.NewBech32Codec("cosmos")) keeper.RegisterRoute("testModule", "testRoute1", func(sdk.Context) (string, bool) { return "", false }) require.NotPanics(t, func() { keeper.AssertInvariants(testCtx.Ctx) }) diff --git a/x/crisis/keeper/msg_server.go b/x/crisis/keeper/msg_server.go index 729bbd570023..c0db5a46e167 100644 --- a/x/crisis/keeper/msg_server.go +++ b/x/crisis/keeper/msg_server.go @@ -6,6 +6,7 @@ import ( "cosmossdk.io/errors" sdk "github.com/cosmos/cosmos-sdk/types" + sdkerrors "github.com/cosmos/cosmos-sdk/types/errors" "github.com/cosmos/cosmos-sdk/x/crisis/types" govtypes "github.com/cosmos/cosmos-sdk/x/gov/types" ) @@ -15,13 +16,17 @@ var _ types.MsgServer = &Keeper{} // VerifyInvariant implements MsgServer.VerifyInvariant method. // It defines a method to verify a particular invariant. func (k *Keeper) VerifyInvariant(goCtx context.Context, msg *types.MsgVerifyInvariant) (*types.MsgVerifyInvariantResponse, error) { + if msg.Sender == "" { + return nil, sdkerrors.ErrInvalidAddress.Wrap("empty address string is not allowed") + } + sender, err := k.addressCodec.StringToBytes(msg.Sender) + if err != nil { + return nil, sdkerrors.ErrInvalidAddress.Wrapf("invalid sender address: %s", err) + } + ctx := sdk.UnwrapSDKContext(goCtx) constantFee := sdk.NewCoins(k.GetConstantFee(ctx)) - sender, err := sdk.AccAddressFromBech32(msg.Sender) - if err != nil { - return nil, err - } if err := k.SendCoinsFromAccountToFeeCollector(ctx, sender, constantFee); err != nil { return nil, err } @@ -67,13 +72,21 @@ func (k *Keeper) VerifyInvariant(goCtx context.Context, msg *types.MsgVerifyInva // UpdateParams implements MsgServer.UpdateParams method. // It defines a method to update the x/crisis module parameters. -func (k *Keeper) UpdateParams(goCtx context.Context, req *types.MsgUpdateParams) (*types.MsgUpdateParamsResponse, error) { - if k.authority != req.Authority { - return nil, errors.Wrapf(govtypes.ErrInvalidSigner, "invalid authority; expected %s, got %s", k.authority, req.Authority) +func (k *Keeper) UpdateParams(ctx context.Context, msg *types.MsgUpdateParams) (*types.MsgUpdateParamsResponse, error) { + if k.authority != msg.Authority { + return nil, errors.Wrapf(govtypes.ErrInvalidSigner, "invalid authority; expected %s, got %s", k.authority, msg.Authority) } - ctx := sdk.UnwrapSDKContext(goCtx) - if err := k.SetConstantFee(ctx, req.ConstantFee); err != nil { + if !msg.ConstantFee.IsValid() { + return nil, errors.Wrap(sdkerrors.ErrInvalidCoins, "invalid constant fee") + } + + if msg.ConstantFee.IsNegative() { + return nil, errors.Wrap(sdkerrors.ErrInvalidCoins, "negative constant fee") + } + + sdkCtx := sdk.UnwrapSDKContext(ctx) + if err := k.SetConstantFee(sdkCtx, msg.ConstantFee); err != nil { return nil, err } diff --git a/x/crisis/keeper/msg_server_test.go b/x/crisis/keeper/msg_server_test.go index 6652c4ecd59f..1bcedd606367 100644 --- a/x/crisis/keeper/msg_server_test.go +++ b/x/crisis/keeper/msg_server_test.go @@ -6,8 +6,11 @@ import ( "github.com/golang/mock/gomock" "github.com/stretchr/testify/suite" + sdkmath "cosmossdk.io/math" storetypes "cosmossdk.io/store/types" + addresscodec "github.com/cosmos/cosmos-sdk/codec/address" + "github.com/cosmos/cosmos-sdk/crypto/keyring" "github.com/cosmos/cosmos-sdk/testutil" sdk "github.com/cosmos/cosmos-sdk/types" moduletestutil "github.com/cosmos/cosmos-sdk/types/module/testutil" @@ -20,9 +23,9 @@ import ( type KeeperTestSuite struct { suite.Suite - ctx sdk.Context - authKeeper *crisistestutil.MockSupplyKeeper - keeper *keeper.Keeper + ctx sdk.Context + supplyKeeper *crisistestutil.MockSupplyKeeper + keeper *keeper.Keeper } func (s *KeeperTestSuite) SetupTest() { @@ -33,11 +36,11 @@ func (s *KeeperTestSuite) SetupTest() { key := storetypes.NewKVStoreKey(types.StoreKey) testCtx := testutil.DefaultContextWithDB(s.T(), key, storetypes.NewTransientStoreKey("transient_test")) encCfg := moduletestutil.MakeTestEncodingConfig(crisis.AppModuleBasic{}) - keeper := keeper.NewKeeper(encCfg.Codec, key, 5, supplyKeeper, "", "") + keeper := keeper.NewKeeper(encCfg.Codec, key, 5, supplyKeeper, "", sdk.AccAddress([]byte("addr1_______________")).String(), addresscodec.NewBech32Codec("cosmos")) s.ctx = testCtx.Ctx s.keeper = keeper - s.authKeeper = supplyKeeper + s.supplyKeeper = supplyKeeper } func (s *KeeperTestSuite) TestMsgVerifyInvariant() { @@ -46,9 +49,13 @@ func (s *KeeperTestSuite) TestMsgVerifyInvariant() { err := s.keeper.SetConstantFee(s.ctx, constantFee) s.Require().NoError(err) - sender := sdk.AccAddress([]byte("addr1_______________")) + encCfg := moduletestutil.MakeTestEncodingConfig(crisis.AppModuleBasic{}) + kr := keyring.NewInMemory(encCfg.Codec) + testutil.CreateKeyringAccounts(s.T(), kr, 1) + + sender := testutil.CreateKeyringAccounts(s.T(), kr, 1)[0] - s.authKeeper.EXPECT().SendCoinsFromAccountToModule(gomock.Any(), gomock.Any(), gomock.Any(), gomock.Any()).Return(nil).Times(2) + s.supplyKeeper.EXPECT().SendCoinsFromAccountToModule(gomock.Any(), gomock.Any(), gomock.Any(), gomock.Any()).Return(nil).Times(2) s.keeper.RegisterRoute("bank", "total-supply", func(sdk.Context) (string, bool) { return "", false }) testCases := []struct { @@ -80,7 +87,7 @@ func (s *KeeperTestSuite) TestMsgVerifyInvariant() { { name: "unregistered invariant route", input: &types.MsgVerifyInvariant{ - Sender: sender.String(), + Sender: sender.Address.String(), InvariantModuleName: "module", InvariantRoute: "invalidroute", }, @@ -90,7 +97,7 @@ func (s *KeeperTestSuite) TestMsgVerifyInvariant() { { name: "valid invariant", input: &types.MsgVerifyInvariant{ - Sender: sender.String(), + Sender: sender.Address.String(), InvariantModuleName: "bank", InvariantRoute: "total-supply", }, @@ -143,7 +150,7 @@ func (s *KeeperTestSuite) TestMsgUpdateParams() { name: "negative constant fee", input: &types.MsgUpdateParams{ Authority: s.keeper.GetAuthority(), - ConstantFee: sdk.Coin{Denom: sdk.DefaultBondDenom, Amount: sdk.NewInt(-1000)}, + ConstantFee: sdk.Coin{Denom: sdk.DefaultBondDenom, Amount: sdkmath.NewInt(-1000)}, }, expErr: true, }, diff --git a/x/crisis/keeper/params_test.go b/x/crisis/keeper/params_test.go index b5c65e5e5806..2696c7ec74d4 100644 --- a/x/crisis/keeper/params_test.go +++ b/x/crisis/keeper/params_test.go @@ -1,12 +1,14 @@ package keeper_test import ( + sdkmath "cosmossdk.io/math" + sdk "github.com/cosmos/cosmos-sdk/types" ) func (s *KeeperTestSuite) TestParams() { // default params - constantFee := sdk.NewCoin(sdk.DefaultBondDenom, sdk.NewInt(1000)) + constantFee := sdk.NewCoin(sdk.DefaultBondDenom, sdkmath.NewInt(1000)) testCases := []struct { name string @@ -21,7 +23,7 @@ func (s *KeeperTestSuite) TestParams() { }, { name: "negative constant fee", - constantFee: sdk.Coin{Denom: sdk.DefaultBondDenom, Amount: sdk.NewInt(-1000)}, + constantFee: sdk.Coin{Denom: sdk.DefaultBondDenom, Amount: sdkmath.NewInt(-1000)}, expErr: true, }, { diff --git a/x/crisis/module.go b/x/crisis/module.go index 0bf4f155e85d..a19419ee7b7e 100644 --- a/x/crisis/module.go +++ b/x/crisis/module.go @@ -12,6 +12,7 @@ import ( "github.com/spf13/cobra" modulev1 "cosmossdk.io/api/cosmos/crisis/module/v1" + "cosmossdk.io/core/address" "cosmossdk.io/core/appmodule" "cosmossdk.io/depinject" @@ -191,8 +192,7 @@ func init() { ) } -//nolint:revive -type CrisisInputs struct { +type ModuleInputs struct { depinject.In Config *modulev1.Module @@ -200,21 +200,21 @@ type CrisisInputs struct { Cdc codec.Codec AppOpts servertypes.AppOptions `optional:"true"` - BankKeeper types.SupplyKeeper + BankKeeper types.SupplyKeeper + AddressCodec address.Codec // LegacySubspace is used solely for migration of x/params managed parameters LegacySubspace exported.Subspace } -//nolint:revive -type CrisisOutputs struct { +type ModuleOutputs struct { depinject.Out Module appmodule.AppModule CrisisKeeper *keeper.Keeper } -func ProvideModule(in CrisisInputs) CrisisOutputs { +func ProvideModule(in ModuleInputs) ModuleOutputs { var invalidCheckPeriod uint if in.AppOpts != nil { invalidCheckPeriod = cast.ToUint(in.AppOpts.Get(server.FlagInvCheckPeriod)) @@ -238,6 +238,7 @@ func ProvideModule(in CrisisInputs) CrisisOutputs { in.BankKeeper, feeCollectorName, authority.String(), + in.AddressCodec, ) var skipGenesisInvariants bool @@ -247,5 +248,5 @@ func ProvideModule(in CrisisInputs) CrisisOutputs { m := NewAppModule(k, skipGenesisInvariants, in.LegacySubspace) - return CrisisOutputs{CrisisKeeper: k, Module: m} + return ModuleOutputs{CrisisKeeper: k, Module: m} } diff --git a/x/crisis/types/codec.go b/x/crisis/types/codec.go index 9e2ed19261d8..189c48a6ffb8 100644 --- a/x/crisis/types/codec.go +++ b/x/crisis/types/codec.go @@ -30,14 +30,14 @@ func RegisterInterfaces(registry codectypes.InterfaceRegistry) { } var ( - amino = codec.NewLegacyAmino() - ModuleCdc = codec.NewAminoCodec(amino) + aminoCdc = codec.NewLegacyAmino() + ModuleCdc = codec.NewAminoCodec(aminoCdc) ) func init() { - RegisterLegacyAminoCodec(amino) - cryptocodec.RegisterCrypto(amino) - sdk.RegisterLegacyAminoCodec(amino) + RegisterLegacyAminoCodec(aminoCdc) + cryptocodec.RegisterCrypto(aminoCdc) + sdk.RegisterLegacyAminoCodec(aminoCdc) // Register all Amino interfaces and concrete types on the authz and gov Amino codec so that this can later be // used to properly serialize MsgGrant, MsgExec and MsgSubmitProposal instances diff --git a/x/crisis/types/genesis.go b/x/crisis/types/genesis.go index f53099130277..4a136bb3c590 100644 --- a/x/crisis/types/genesis.go +++ b/x/crisis/types/genesis.go @@ -3,6 +3,8 @@ package types import ( "fmt" + sdkmath "cosmossdk.io/math" + sdk "github.com/cosmos/cosmos-sdk/types" ) @@ -16,7 +18,7 @@ func NewGenesisState(constantFee sdk.Coin) *GenesisState { // DefaultGenesisState creates a default GenesisState object func DefaultGenesisState() *GenesisState { return &GenesisState{ - ConstantFee: sdk.NewCoin(sdk.DefaultBondDenom, sdk.NewInt(1000)), + ConstantFee: sdk.NewCoin(sdk.DefaultBondDenom, sdkmath.NewInt(1000)), } } diff --git a/x/crisis/types/msgs.go b/x/crisis/types/msgs.go index 02ca572f45d8..39b7f9813dc2 100644 --- a/x/crisis/types/msgs.go +++ b/x/crisis/types/msgs.go @@ -1,10 +1,7 @@ package types import ( - errorsmod "cosmossdk.io/errors" - sdk "github.com/cosmos/cosmos-sdk/types" - sdkerrors "github.com/cosmos/cosmos-sdk/types/errors" "github.com/cosmos/cosmos-sdk/x/auth/migrations/legacytx" ) @@ -15,8 +12,6 @@ var ( ) // NewMsgVerifyInvariant creates a new MsgVerifyInvariant object -// -//nolint:interfacer func NewMsgVerifyInvariant(sender sdk.AccAddress, invModeName, invRoute string) *MsgVerifyInvariant { return &MsgVerifyInvariant{ Sender: sender.String(), @@ -33,18 +28,10 @@ func (msg MsgVerifyInvariant) GetSigners() []sdk.AccAddress { // GetSignBytes gets the sign bytes for the msg MsgVerifyInvariant func (msg MsgVerifyInvariant) GetSignBytes() []byte { - bz := ModuleCdc.MustMarshalJSON(&msg) + bz := aminoCdc.MustMarshalJSON(&msg) return sdk.MustSortJSON(bz) } -// quick validity check -func (msg MsgVerifyInvariant) ValidateBasic() error { - if _, err := sdk.AccAddressFromBech32(msg.Sender); err != nil { - return sdkerrors.ErrInvalidAddress.Wrapf("invalid sender address: %s", err) - } - return nil -} - // FullInvariantRoute - get the messages full invariant route func (msg MsgVerifyInvariant) FullInvariantRoute() string { return msg.InvariantModuleName + "/" + msg.InvariantRoute @@ -60,23 +47,6 @@ func (msg MsgUpdateParams) GetSigners() []sdk.AccAddress { // GetSignBytes returns the raw bytes for a MsgUpdateParams message that // the expected signer needs to sign. func (msg MsgUpdateParams) GetSignBytes() []byte { - bz := ModuleCdc.MustMarshalJSON(&msg) + bz := aminoCdc.MustMarshalJSON(&msg) return sdk.MustSortJSON(bz) } - -// ValidateBasic performs basic MsgUpdateParams message validation. -func (msg MsgUpdateParams) ValidateBasic() error { - if _, err := sdk.AccAddressFromBech32(msg.Authority); err != nil { - return errorsmod.Wrap(err, "invalid authority address") - } - - if !msg.ConstantFee.IsValid() { - return errorsmod.Wrap(sdkerrors.ErrInvalidCoins, "invalid costant fee") - } - - if msg.ConstantFee.IsNegative() { - return errorsmod.Wrap(sdkerrors.ErrInvalidCoins, "negative costant fee") - } - - return nil -} diff --git a/x/distribution/README.md b/x/distribution/README.md index 2a1414f12478..f730ed379a9b 100644 --- a/x/distribution/README.md +++ b/x/distribution/README.md @@ -145,7 +145,7 @@ When coins are distributed from the pool they are truncated back to type DecCoins []DecCoin type DecCoin struct { - Amount sdk.Dec + Amount math.LegacyDec Denom string } ``` @@ -167,7 +167,7 @@ Validator distribution information for the relevant validator is updated each ti ```go type ValidatorDistInfo struct { OperatorAddress sdk.AccAddress - SelfBondRewards sdk.DecCoins + SelfBondRewards sdkmath.DecCoins ValidatorCommission types.ValidatorAccumulatedCommission } ``` @@ -517,6 +517,11 @@ The distribution module contains the following parameters: * [0] `communitytax` must be positive and cannot exceed 1.00. * `baseproposerreward` and `bonusproposerreward` were parameters that are deprecated in v0.47 and are not used. +:::note +The reserve pool is the pool of collected funds for use by governance taken via the `CommunityTax`. +Currently with the Cosmos SDK, tokens collected by the CommunityTax are accounted for but unspendable. +::: + ## Client ## CLI diff --git a/x/distribution/client/cli/query.go b/x/distribution/client/cli/query.go index 2ffdd5f1158d..5999fee397cd 100644 --- a/x/distribution/client/cli/query.go +++ b/x/distribution/client/cli/query.go @@ -5,6 +5,7 @@ import ( "strconv" "strings" + "cosmossdk.io/core/address" "github.com/spf13/cobra" "github.com/cosmos/cosmos-sdk/client" @@ -15,7 +16,7 @@ import ( ) // GetQueryCmd returns the cli query commands for this module -func GetQueryCmd() *cobra.Command { +func GetQueryCmd(ac address.Codec) *cobra.Command { distQueryCmd := &cobra.Command{ Use: types.ModuleName, Short: "Querying commands for the distribution module", @@ -30,7 +31,7 @@ func GetQueryCmd() *cobra.Command { GetCmdQueryValidatorOutstandingRewards(), GetCmdQueryValidatorCommission(), GetCmdQueryValidatorSlashes(), - GetCmdQueryDelegatorRewards(), + GetCmdQueryDelegatorRewards(ac), GetCmdQueryCommunityPool(), ) @@ -265,7 +266,7 @@ $ %s query distribution slashes %svaloper1gghjut3ccd8ay0zduzj64hwre2fxs9ldmqhffj } // GetCmdQueryDelegatorRewards implements the query delegator rewards command. -func GetCmdQueryDelegatorRewards() *cobra.Command { +func GetCmdQueryDelegatorRewards(ac address.Codec) *cobra.Command { bech32PrefixAccAddr := sdk.GetConfig().GetBech32AccountAddrPrefix() bech32PrefixValAddr := sdk.GetConfig().GetBech32ValidatorAddrPrefix() @@ -290,7 +291,7 @@ $ %s query distribution rewards %s1gghjut3ccd8ay0zduzj64hwre2fxs9ld75ru9p %s1ggh } queryClient := types.NewQueryClient(clientCtx) - delegatorAddr, err := sdk.AccAddressFromBech32(args[0]) + _, err = ac.StringToBytes(args[0]) if err != nil { return err } @@ -305,7 +306,7 @@ $ %s query distribution rewards %s1gghjut3ccd8ay0zduzj64hwre2fxs9ld75ru9p %s1ggh res, err := queryClient.DelegationRewards( ctx, - &types.QueryDelegationRewardsRequest{DelegatorAddress: delegatorAddr.String(), ValidatorAddress: validatorAddr.String()}, + &types.QueryDelegationRewardsRequest{DelegatorAddress: args[0], ValidatorAddress: validatorAddr.String()}, ) if err != nil { return err @@ -316,7 +317,7 @@ $ %s query distribution rewards %s1gghjut3ccd8ay0zduzj64hwre2fxs9ld75ru9p %s1ggh res, err := queryClient.DelegationTotalRewards( ctx, - &types.QueryDelegationTotalRewardsRequest{DelegatorAddress: delegatorAddr.String()}, + &types.QueryDelegationTotalRewardsRequest{DelegatorAddress: args[0]}, ) if err != nil { return err diff --git a/x/distribution/client/cli/suite_test.go b/x/distribution/client/cli/query_test.go similarity index 61% rename from x/distribution/client/cli/suite_test.go rename to x/distribution/client/cli/query_test.go index 150acf8b97d2..19f62c44bb56 100644 --- a/x/distribution/client/cli/suite_test.go +++ b/x/distribution/client/cli/query_test.go @@ -1,7 +1,6 @@ package cli_test import ( - "bytes" "fmt" "io" "strings" @@ -9,11 +8,11 @@ import ( abci "github.com/cometbft/cometbft/abci/types" rpcclientmock "github.com/cometbft/cometbft/rpc/client/mock" - "github.com/cosmos/gogoproto/proto" "github.com/stretchr/testify/suite" "github.com/cosmos/cosmos-sdk/client" "github.com/cosmos/cosmos-sdk/client/flags" + "github.com/cosmos/cosmos-sdk/codec/address" "github.com/cosmos/cosmos-sdk/crypto/keyring" "github.com/cosmos/cosmos-sdk/testutil" clitestutil "github.com/cosmos/cosmos-sdk/testutil/cli" @@ -22,7 +21,6 @@ import ( testutilmod "github.com/cosmos/cosmos-sdk/types/module/testutil" "github.com/cosmos/cosmos-sdk/x/bank" "github.com/cosmos/cosmos-sdk/x/distribution/client/cli" - distrclitestutil "github.com/cosmos/cosmos-sdk/x/distribution/client/testutil" distrtestutil "github.com/cosmos/cosmos-sdk/x/distribution/testutil" "github.com/cosmos/cosmos-sdk/x/gov" minttypes "github.com/cosmos/cosmos-sdk/x/mint/types" @@ -53,7 +51,6 @@ func (s *CLITestSuite) SetupSuite() { WithOutput(io.Discard). WithChainID("test-chain") - var outBuf bytes.Buffer ctxGen := func() client.Context { bz, _ := s.encCfg.Codec.Marshal(&sdk.TxResponse{}) c := clitestutil.NewMockCometRPC(abci.ResponseQuery{ @@ -61,7 +58,7 @@ func (s *CLITestSuite) SetupSuite() { }) return s.baseCtx.WithClient(c) } - s.clientCtx = ctxGen().WithOutput(&outBuf) + s.clientCtx = ctxGen() cfg, err := network.DefaultConfigWithAppConfig(distrtestutil.AppConfig) s.Require().NoError(err) @@ -422,7 +419,7 @@ total: []`, tc := tc s.Run(tc.name, func() { - cmd := cli.GetCmdQueryDelegatorRewards() + cmd := cli.GetCmdQueryDelegatorRewards(address.NewBech32Codec("cosmos")) out, err := clitestutil.ExecTestCLICmd(s.clientCtx, cmd, tc.args) if tc.expectErr { @@ -465,216 +462,3 @@ func (s *CLITestSuite) TestGetCmdQueryCommunityPool() { }) } } - -func (s *CLITestSuite) TestNewWithdrawRewardsCmd() { - val := testutil.CreateKeyringAccounts(s.T(), s.kr, 1) - - testCases := []struct { - name string - valAddr fmt.Stringer - args []string - expectErr bool - respType proto.Message - }{ - { - "invalid validator address", - val[0].Address, - []string{ - fmt.Sprintf("--%s=%s", flags.FlagFrom, val[0].Address.String()), - fmt.Sprintf("--%s=true", flags.FlagSkipConfirmation), - fmt.Sprintf("--%s=%s", flags.FlagBroadcastMode, flags.BroadcastSync), - fmt.Sprintf("--%s=%s", flags.FlagFees, sdk.NewCoins(sdk.NewCoin("stake", sdk.NewInt(10))).String()), - }, - true, nil, - }, - { - "valid transaction", - sdk.ValAddress(val[0].Address), - []string{ - fmt.Sprintf("--%s=%s", flags.FlagFrom, val[0].Address.String()), - fmt.Sprintf("--%s=true", flags.FlagSkipConfirmation), - fmt.Sprintf("--%s=%s", flags.FlagBroadcastMode, flags.BroadcastSync), - fmt.Sprintf("--%s=%s", flags.FlagFees, sdk.NewCoins(sdk.NewCoin("stake", sdk.NewInt(10))).String()), - }, - false, &sdk.TxResponse{}, - }, - { - "valid transaction (with commission)", - sdk.ValAddress(val[0].Address), - []string{ - fmt.Sprintf("--%s=%s", flags.FlagFrom, val[0].Address.String()), - fmt.Sprintf("--%s=true", flags.FlagSkipConfirmation), - fmt.Sprintf("--%s=true", cli.FlagCommission), - fmt.Sprintf("--%s=%s", flags.FlagBroadcastMode, flags.BroadcastSync), - fmt.Sprintf("--%s=%s", flags.FlagFees, sdk.NewCoins(sdk.NewCoin("stake", sdk.NewInt(10))).String()), - }, - false, &sdk.TxResponse{}, - }, - } - - for _, tc := range testCases { - tc := tc - - s.Run(tc.name, func() { - bz, err := distrclitestutil.MsgWithdrawDelegatorRewardExec(s.clientCtx, tc.valAddr, tc.args...) - if tc.expectErr { - s.Require().Error(err) - } else { - s.Require().NoError(err) - s.Require().NoError(s.clientCtx.Codec.UnmarshalJSON(bz, tc.respType), string(bz)) - } - }) - } -} - -func (s *CLITestSuite) TestNewWithdrawAllRewardsCmd() { - val := testutil.CreateKeyringAccounts(s.T(), s.kr, 1) - - testCases := []struct { - name string - args []string - expectErr bool - expErrMsg string - respType proto.Message - }{ - { - "invalid transaction (offline)", - []string{ - fmt.Sprintf("--%s=%s", flags.FlagFrom, val[0].Address.String()), - fmt.Sprintf("--%s=true", flags.FlagOffline), - fmt.Sprintf("--%s=%s", flags.FlagBroadcastMode, flags.BroadcastSync), - fmt.Sprintf("--%s=%s", flags.FlagFees, sdk.NewCoins(sdk.NewCoin("stake", sdk.NewInt(10))).String()), - }, - true, - "cannot generate tx in offline mode", - nil, - }, - { - "valid transaction", - []string{ - fmt.Sprintf("--%s=%s", flags.FlagFrom, val[0].Address.String()), - fmt.Sprintf("--%s=true", flags.FlagSkipConfirmation), - fmt.Sprintf("--%s=%s", flags.FlagBroadcastMode, flags.BroadcastSync), - fmt.Sprintf("--%s=%s", flags.FlagFees, sdk.NewCoins(sdk.NewCoin("stake", sdk.NewInt(10))).String()), - }, - false, "", &sdk.TxResponse{}, - }, - } - - for _, tc := range testCases { - tc := tc - - s.Run(tc.name, func() { - cmd := cli.NewWithdrawAllRewardsCmd() - - out, err := clitestutil.ExecTestCLICmd(s.clientCtx, cmd, tc.args) - if tc.expectErr { - s.Require().Error(err) - s.Require().Contains(err.Error(), tc.expErrMsg) - } else { - s.Require().NoError(err) - s.Require().NoError(s.clientCtx.Codec.UnmarshalJSON(out.Bytes(), tc.respType), out.String()) - } - }) - } -} - -func (s *CLITestSuite) TestNewSetWithdrawAddrCmd() { - val := testutil.CreateKeyringAccounts(s.T(), s.kr, 1) - - testCases := []struct { - name string - args []string - expectErr bool - respType proto.Message - }{ - { - "invalid withdraw address", - []string{ - "foo", - fmt.Sprintf("--%s=%s", flags.FlagFrom, val[0].Address.String()), - fmt.Sprintf("--%s=true", flags.FlagSkipConfirmation), - fmt.Sprintf("--%s=%s", flags.FlagBroadcastMode, flags.BroadcastSync), - fmt.Sprintf("--%s=%s", flags.FlagFees, sdk.NewCoins(sdk.NewCoin("stake", sdk.NewInt(10))).String()), - }, - true, nil, - }, - { - "valid transaction", - []string{ - val[0].Address.String(), - fmt.Sprintf("--%s=%s", flags.FlagFrom, val[0].Address.String()), - fmt.Sprintf("--%s=true", flags.FlagSkipConfirmation), - fmt.Sprintf("--%s=%s", flags.FlagBroadcastMode, flags.BroadcastSync), - fmt.Sprintf("--%s=%s", flags.FlagFees, sdk.NewCoins(sdk.NewCoin("stake", sdk.NewInt(10))).String()), - }, - false, &sdk.TxResponse{}, - }, - } - - for _, tc := range testCases { - tc := tc - - s.Run(tc.name, func() { - cmd := cli.NewSetWithdrawAddrCmd() - - out, err := clitestutil.ExecTestCLICmd(s.clientCtx, cmd, tc.args) - if tc.expectErr { - s.Require().Error(err) - } else { - s.Require().NoError(err) - s.Require().NoError(s.clientCtx.Codec.UnmarshalJSON(out.Bytes(), tc.respType), out.String()) - } - }) - } -} - -func (s *CLITestSuite) TestNewFundCommunityPoolCmd() { - val := testutil.CreateKeyringAccounts(s.T(), s.kr, 1) - - testCases := []struct { - name string - args []string - expectErr bool - respType proto.Message - }{ - { - "invalid funding amount", - []string{ - "-43foocoin", - fmt.Sprintf("--%s=%s", flags.FlagFrom, val[0].Address.String()), - fmt.Sprintf("--%s=true", flags.FlagSkipConfirmation), - fmt.Sprintf("--%s=%s", flags.FlagBroadcastMode, flags.BroadcastSync), - fmt.Sprintf("--%s=%s", flags.FlagFees, sdk.NewCoins(sdk.NewCoin("stake", sdk.NewInt(10))).String()), - }, - true, nil, - }, - { - "valid transaction", - []string{ - sdk.NewCoins(sdk.NewCoin("stake", sdk.NewInt(5431))).String(), - fmt.Sprintf("--%s=%s", flags.FlagFrom, val[0].Address.String()), - fmt.Sprintf("--%s=true", flags.FlagSkipConfirmation), - fmt.Sprintf("--%s=%s", flags.FlagBroadcastMode, flags.BroadcastSync), - fmt.Sprintf("--%s=%s", flags.FlagFees, sdk.NewCoins(sdk.NewCoin("stake", sdk.NewInt(10))).String()), - }, - false, &sdk.TxResponse{}, - }, - } - - for _, tc := range testCases { - tc := tc - - s.Run(tc.name, func() { - cmd := cli.NewFundCommunityPoolCmd() - - out, err := clitestutil.ExecTestCLICmd(s.clientCtx, cmd, tc.args) - if tc.expectErr { - s.Require().Error(err) - } else { - s.Require().NoError(err) - s.Require().NoError(s.clientCtx.Codec.UnmarshalJSON(out.Bytes(), tc.respType), out.String()) - } - }) - } -} diff --git a/x/distribution/client/cli/tx.go b/x/distribution/client/cli/tx.go index 0985d3dfee48..769f9b1ce4ce 100644 --- a/x/distribution/client/cli/tx.go +++ b/x/distribution/client/cli/tx.go @@ -4,6 +4,7 @@ import ( "fmt" "strings" + "cosmossdk.io/core/address" "github.com/spf13/cobra" "github.com/spf13/pflag" @@ -26,7 +27,7 @@ const ( ) // NewTxCmd returns a root CLI command handler for all x/distribution transaction commands. -func NewTxCmd() *cobra.Command { +func NewTxCmd(ac address.Codec) *cobra.Command { distTxCmd := &cobra.Command{ Use: types.ModuleName, Short: "Distribution transactions subcommands", @@ -38,7 +39,7 @@ func NewTxCmd() *cobra.Command { distTxCmd.AddCommand( NewWithdrawRewardsCmd(), NewWithdrawAllRewardsCmd(), - NewSetWithdrawAddrCmd(), + NewSetWithdrawAddrCmd(ac), NewFundCommunityPoolCmd(), NewDepositValidatorRewardsPoolCmd(), ) @@ -181,7 +182,7 @@ $ %[1]s tx distribution withdraw-all-rewards --from mykey } // NewSetWithdrawAddrCmd returns a CLI command handler for creating a MsgSetWithdrawAddress transaction. -func NewSetWithdrawAddrCmd() *cobra.Command { +func NewSetWithdrawAddrCmd(ac address.Codec) *cobra.Command { bech32PrefixAccAddr := sdk.GetConfig().GetBech32AccountAddrPrefix() cmd := &cobra.Command{ @@ -203,7 +204,7 @@ $ %s tx distribution set-withdraw-addr %s1gghjut3ccd8ay0zduzj64hwre2fxs9ld75ru9p return err } delAddr := clientCtx.GetFromAddress() - withdrawAddr, err := sdk.AccAddressFromBech32(args[0]) + withdrawAddr, err := ac.StringToBytes(args[0]) if err != nil { return err } diff --git a/x/distribution/client/cli/tx_test.go b/x/distribution/client/cli/tx_test.go index 0c1ea11ff5f7..3522faa9b43b 100644 --- a/x/distribution/client/cli/tx_test.go +++ b/x/distribution/client/cli/tx_test.go @@ -1,59 +1,237 @@ -package cli +package cli_test import ( - "testing" + "context" + "fmt" - "github.com/spf13/pflag" - "github.com/stretchr/testify/require" + sdkmath "cosmossdk.io/math" + "github.com/cosmos/gogoproto/proto" "github.com/cosmos/cosmos-sdk/client" - "github.com/cosmos/cosmos-sdk/crypto/keys/secp256k1" - "github.com/cosmos/cosmos-sdk/testutil/testdata" + "github.com/cosmos/cosmos-sdk/client/flags" + "github.com/cosmos/cosmos-sdk/codec/address" + svrcmd "github.com/cosmos/cosmos-sdk/server/cmd" + "github.com/cosmos/cosmos-sdk/testutil" + clitestutil "github.com/cosmos/cosmos-sdk/testutil/cli" sdk "github.com/cosmos/cosmos-sdk/types" + "github.com/cosmos/cosmos-sdk/x/distribution/client/cli" ) -func Test_splitAndCall_NoMessages(t *testing.T) { - clientCtx := client.Context{} +func (s *CLITestSuite) TestTxWithdrawRewardsCmd() { + val := testutil.CreateKeyringAccounts(s.T(), s.kr, 1) - err := newSplitAndApply(nil, clientCtx, nil, nil, 10) - require.NoError(t, err, "") + testCases := []struct { + name string + valAddr fmt.Stringer + args []string + expectErrMsg string + }{ + { + "invalid validator address", + val[0].Address, + []string{ + fmt.Sprintf("--%s=%s", flags.FlagFrom, val[0].Address.String()), + fmt.Sprintf("--%s=true", flags.FlagSkipConfirmation), + fmt.Sprintf("--%s=%s", flags.FlagBroadcastMode, flags.BroadcastSync), + fmt.Sprintf("--%s=%s", flags.FlagFees, sdk.NewCoins(sdk.NewCoin("stake", sdkmath.NewInt(10))).String()), + }, + "invalid Bech32 prefix", + }, + { + "valid transaction", + sdk.ValAddress(val[0].Address), + []string{ + fmt.Sprintf("--%s=%s", flags.FlagFrom, val[0].Address.String()), + fmt.Sprintf("--%s=true", flags.FlagSkipConfirmation), + fmt.Sprintf("--%s=%s", flags.FlagBroadcastMode, flags.BroadcastSync), + fmt.Sprintf("--%s=%s", flags.FlagFees, sdk.NewCoins(sdk.NewCoin("stake", sdkmath.NewInt(10))).String()), + }, + "", + }, + { + "valid transaction (with commission)", + sdk.ValAddress(val[0].Address), + []string{ + fmt.Sprintf("--%s=%s", flags.FlagFrom, val[0].Address.String()), + fmt.Sprintf("--%s=true", flags.FlagSkipConfirmation), + fmt.Sprintf("--%s=true", cli.FlagCommission), + fmt.Sprintf("--%s=%s", flags.FlagBroadcastMode, flags.BroadcastSync), + fmt.Sprintf("--%s=%s", flags.FlagFees, sdk.NewCoins(sdk.NewCoin("stake", sdkmath.NewInt(10))).String()), + }, + "", + }, + } + + for _, tc := range testCases { + tc := tc + + s.Run(tc.name, func() { + args := append([]string{tc.valAddr.String()}, tc.args...) + + ctx := svrcmd.CreateExecuteContext(context.Background()) + cmd := cli.NewWithdrawRewardsCmd() + cmd.SetContext(ctx) + cmd.SetArgs(args) + s.Require().NoError(client.SetCmdClientContextHandler(s.clientCtx, cmd)) + + out, err := clitestutil.ExecTestCLICmd(s.clientCtx, cmd, args) + if tc.expectErrMsg != "" { + s.Require().Error(err) + s.Require().Contains(err.Error(), tc.expectErrMsg) + } else { + s.Require().NoError(err) + msg := &sdk.TxResponse{} + s.Require().NoError(s.clientCtx.Codec.UnmarshalJSON(out.Bytes(), msg), out.String()) + } + }) + } } -func Test_splitAndCall_Splitting(t *testing.T) { - clientCtx := client.Context{} +func (s *CLITestSuite) TestTxWithdrawAllRewardsCmd() { + val := testutil.CreateKeyringAccounts(s.T(), s.kr, 1) + + testCases := []struct { + name string + args []string + expectErrMsg string + }{ + { + "invalid transaction (offline)", + []string{ + fmt.Sprintf("--%s=%s", flags.FlagFrom, val[0].Address.String()), + fmt.Sprintf("--%s=true", flags.FlagOffline), + fmt.Sprintf("--%s=%s", flags.FlagBroadcastMode, flags.BroadcastSync), + fmt.Sprintf("--%s=%s", flags.FlagFees, sdk.NewCoins(sdk.NewCoin("stake", sdkmath.NewInt(10))).String()), + }, + "cannot generate tx in offline mode", + }, + { + "valid transaction", + []string{ + fmt.Sprintf("--%s=%s", flags.FlagFrom, val[0].Address.String()), + fmt.Sprintf("--%s=true", flags.FlagSkipConfirmation), + fmt.Sprintf("--%s=%s", flags.FlagBroadcastMode, flags.BroadcastSync), + fmt.Sprintf("--%s=%s", flags.FlagFees, sdk.NewCoins(sdk.NewCoin("stake", sdkmath.NewInt(10))).String()), + }, + "", + }, + } + + for _, tc := range testCases { + tc := tc - addr := sdk.AccAddress(secp256k1.GenPrivKey().PubKey().Address()) + s.Run(tc.name, func() { + cmd := cli.NewWithdrawAllRewardsCmd() - // Add five messages - msgs := []sdk.Msg{ - testdata.NewTestMsg(addr), - testdata.NewTestMsg(addr), - testdata.NewTestMsg(addr), - testdata.NewTestMsg(addr), - testdata.NewTestMsg(addr), + out, err := clitestutil.ExecTestCLICmd(s.clientCtx, cmd, tc.args) + if tc.expectErrMsg != "" { + s.Require().Error(err) + s.Require().Contains(err.Error(), tc.expectErrMsg) + } else { + s.Require().NoError(err) + msg := &sdk.TxResponse{} + s.Require().NoError(s.clientCtx.Codec.UnmarshalJSON(out.Bytes(), msg), out.String()) + } + }) } +} - // Keep track of number of calls - const chunkSize = 2 +func (s *CLITestSuite) TestTxSetWithdrawAddrCmd() { + val := testutil.CreateKeyringAccounts(s.T(), s.kr, 1) + + testCases := []struct { + name string + args []string + expectErr bool + respType proto.Message + }{ + { + "invalid withdraw address", + []string{ + "foo", + fmt.Sprintf("--%s=%s", flags.FlagFrom, val[0].Address.String()), + fmt.Sprintf("--%s=true", flags.FlagSkipConfirmation), + fmt.Sprintf("--%s=%s", flags.FlagBroadcastMode, flags.BroadcastSync), + fmt.Sprintf("--%s=%s", flags.FlagFees, sdk.NewCoins(sdk.NewCoin("stake", sdkmath.NewInt(10))).String()), + }, + true, nil, + }, + { + "valid transaction", + []string{ + val[0].Address.String(), + fmt.Sprintf("--%s=%s", flags.FlagFrom, val[0].Address.String()), + fmt.Sprintf("--%s=true", flags.FlagSkipConfirmation), + fmt.Sprintf("--%s=%s", flags.FlagBroadcastMode, flags.BroadcastSync), + fmt.Sprintf("--%s=%s", flags.FlagFees, sdk.NewCoins(sdk.NewCoin("stake", sdkmath.NewInt(10))).String()), + }, + false, &sdk.TxResponse{}, + }, + } - callCount := 0 - err := newSplitAndApply( - func(clientCtx client.Context, fs *pflag.FlagSet, msgs ...sdk.Msg) error { - callCount++ + for _, tc := range testCases { + tc := tc - require.NotNil(t, clientCtx) - require.NotNil(t, msgs) + s.Run(tc.name, func() { + cmd := cli.NewSetWithdrawAddrCmd(address.NewBech32Codec("cosmos")) - if callCount < 3 { - require.Equal(t, len(msgs), 2) + out, err := clitestutil.ExecTestCLICmd(s.clientCtx, cmd, tc.args) + if tc.expectErr { + s.Require().Error(err) } else { - require.Equal(t, len(msgs), 1) + s.Require().NoError(err) + s.Require().NoError(s.clientCtx.Codec.UnmarshalJSON(out.Bytes(), tc.respType), out.String()) } + }) + } +} - return nil +func (s *CLITestSuite) TestTxFundCommunityPoolCmd() { + val := testutil.CreateKeyringAccounts(s.T(), s.kr, 1) + + testCases := []struct { + name string + args []string + expectErr bool + respType proto.Message + }{ + { + "invalid funding amount", + []string{ + "-43foocoin", + fmt.Sprintf("--%s=%s", flags.FlagFrom, val[0].Address.String()), + fmt.Sprintf("--%s=true", flags.FlagSkipConfirmation), + fmt.Sprintf("--%s=%s", flags.FlagBroadcastMode, flags.BroadcastSync), + fmt.Sprintf("--%s=%s", flags.FlagFees, sdk.NewCoins(sdk.NewCoin("stake", sdkmath.NewInt(10))).String()), + }, + true, nil, + }, + { + "valid transaction", + []string{ + sdk.NewCoins(sdk.NewCoin("stake", sdkmath.NewInt(5431))).String(), + fmt.Sprintf("--%s=%s", flags.FlagFrom, val[0].Address.String()), + fmt.Sprintf("--%s=true", flags.FlagSkipConfirmation), + fmt.Sprintf("--%s=%s", flags.FlagBroadcastMode, flags.BroadcastSync), + fmt.Sprintf("--%s=%s", flags.FlagFees, sdk.NewCoins(sdk.NewCoin("stake", sdkmath.NewInt(10))).String()), + }, + false, &sdk.TxResponse{}, }, - clientCtx, nil, msgs, chunkSize) + } + + for _, tc := range testCases { + tc := tc - require.NoError(t, err, "") - require.Equal(t, 3, callCount) + s.Run(tc.name, func() { + cmd := cli.NewFundCommunityPoolCmd() + + out, err := clitestutil.ExecTestCLICmd(s.clientCtx, cmd, tc.args) + if tc.expectErr { + s.Require().Error(err) + } else { + s.Require().NoError(err) + s.Require().NoError(s.clientCtx.Codec.UnmarshalJSON(out.Bytes(), tc.respType), out.String()) + } + }) + } } diff --git a/x/distribution/client/cli/util_test.go b/x/distribution/client/cli/util_test.go new file mode 100644 index 000000000000..0c1ea11ff5f7 --- /dev/null +++ b/x/distribution/client/cli/util_test.go @@ -0,0 +1,59 @@ +package cli + +import ( + "testing" + + "github.com/spf13/pflag" + "github.com/stretchr/testify/require" + + "github.com/cosmos/cosmos-sdk/client" + "github.com/cosmos/cosmos-sdk/crypto/keys/secp256k1" + "github.com/cosmos/cosmos-sdk/testutil/testdata" + sdk "github.com/cosmos/cosmos-sdk/types" +) + +func Test_splitAndCall_NoMessages(t *testing.T) { + clientCtx := client.Context{} + + err := newSplitAndApply(nil, clientCtx, nil, nil, 10) + require.NoError(t, err, "") +} + +func Test_splitAndCall_Splitting(t *testing.T) { + clientCtx := client.Context{} + + addr := sdk.AccAddress(secp256k1.GenPrivKey().PubKey().Address()) + + // Add five messages + msgs := []sdk.Msg{ + testdata.NewTestMsg(addr), + testdata.NewTestMsg(addr), + testdata.NewTestMsg(addr), + testdata.NewTestMsg(addr), + testdata.NewTestMsg(addr), + } + + // Keep track of number of calls + const chunkSize = 2 + + callCount := 0 + err := newSplitAndApply( + func(clientCtx client.Context, fs *pflag.FlagSet, msgs ...sdk.Msg) error { + callCount++ + + require.NotNil(t, clientCtx) + require.NotNil(t, msgs) + + if callCount < 3 { + require.Equal(t, len(msgs), 2) + } else { + require.Equal(t, len(msgs), 1) + } + + return nil + }, + clientCtx, nil, msgs, chunkSize) + + require.NoError(t, err, "") + require.Equal(t, 3, callCount) +} diff --git a/x/distribution/client/testutil/helpers.go b/x/distribution/client/testutil/helpers.go deleted file mode 100644 index 19612c23fec0..000000000000 --- a/x/distribution/client/testutil/helpers.go +++ /dev/null @@ -1,32 +0,0 @@ -package testutil - -import ( - "bytes" - "context" - "fmt" - - "github.com/cosmos/cosmos-sdk/client" - distrcli "github.com/cosmos/cosmos-sdk/x/distribution/client/cli" -) - -func MsgWithdrawDelegatorRewardExec(clientCtx client.Context, valAddr fmt.Stringer, extraArgs ...string) ([]byte, error) { - buf := new(bytes.Buffer) - clientCtx = clientCtx.WithOutput(buf) - - ctx := context.Background() - ctx = context.WithValue(ctx, client.ClientContextKey, &clientCtx) - - args := []string{valAddr.String()} - args = append(args, extraArgs...) - - cmd := distrcli.NewWithdrawRewardsCmd() - cmd.SetErr(buf) - cmd.SetOut(buf) - cmd.SetArgs(args) - - if err := cmd.ExecuteContext(ctx); err != nil { - return nil, err - } - - return buf.Bytes(), nil -} diff --git a/x/distribution/keeper/allocation_test.go b/x/distribution/keeper/allocation_test.go index edbb2b68d881..bcecf5b47b14 100644 --- a/x/distribution/keeper/allocation_test.go +++ b/x/distribution/keeper/allocation_test.go @@ -49,7 +49,7 @@ func TestAllocateTokensToValidatorWithCommission(t *testing.T) { // create validator with 50% commission val, err := distrtestutil.CreateValidator(valConsPk0, math.NewInt(100)) require.NoError(t, err) - val.Commission = stakingtypes.NewCommission(sdk.NewDecWithPrec(5, 1), sdk.NewDecWithPrec(5, 1), math.LegacyNewDec(0)) + val.Commission = stakingtypes.NewCommission(math.LegacyNewDecWithPrec(5, 1), math.LegacyNewDecWithPrec(5, 1), math.LegacyNewDec(0)) stakingKeeper.EXPECT().ValidatorByConsAddr(gomock.Any(), sdk.GetConsAddress(valConsPk0)).Return(val).AnyTimes() // allocate tokens @@ -101,7 +101,7 @@ func TestAllocateTokensToManyValidators(t *testing.T) { valAddr0 := sdk.ValAddress(valConsAddr0) val0, err := distrtestutil.CreateValidator(valConsPk0, math.NewInt(100)) require.NoError(t, err) - val0.Commission = stakingtypes.NewCommission(sdk.NewDecWithPrec(5, 1), sdk.NewDecWithPrec(5, 1), math.LegacyNewDec(0)) + val0.Commission = stakingtypes.NewCommission(math.LegacyNewDecWithPrec(5, 1), math.LegacyNewDecWithPrec(5, 1), math.LegacyNewDec(0)) stakingKeeper.EXPECT().ValidatorByConsAddr(gomock.Any(), sdk.GetConsAddress(valConsPk0)).Return(val0).AnyTimes() // create second validator with 0% commission @@ -130,7 +130,7 @@ func TestAllocateTokensToManyValidators(t *testing.T) { require.True(t, distrKeeper.GetValidatorCurrentRewards(ctx, valAddr1).Rewards.IsZero()) // allocate tokens as if both had voted and second was proposer - fees := sdk.NewCoins(sdk.NewCoin(sdk.DefaultBondDenom, sdk.NewInt(100))) + fees := sdk.NewCoins(sdk.NewCoin(sdk.DefaultBondDenom, math.NewInt(100))) bankKeeper.EXPECT().GetAllBalances(gomock.Any(), feeCollectorAcc.GetAddress()).Return(fees) bankKeeper.EXPECT().SendCoinsFromModuleToModule(gomock.Any(), "fee_collector", disttypes.ModuleName, fees) @@ -147,23 +147,23 @@ func TestAllocateTokensToManyValidators(t *testing.T) { distrKeeper.AllocateTokens(ctx, 200, votes) // 98 outstanding rewards (100 less 2 to community pool) - require.Equal(t, sdk.DecCoins{{Denom: sdk.DefaultBondDenom, Amount: sdk.NewDecWithPrec(490, 1)}}, distrKeeper.GetValidatorOutstandingRewards(ctx, valAddr0).Rewards) - require.Equal(t, sdk.DecCoins{{Denom: sdk.DefaultBondDenom, Amount: sdk.NewDecWithPrec(490, 1)}}, distrKeeper.GetValidatorOutstandingRewards(ctx, valAddr1).Rewards) + require.Equal(t, sdk.DecCoins{{Denom: sdk.DefaultBondDenom, Amount: math.LegacyNewDecWithPrec(490, 1)}}, distrKeeper.GetValidatorOutstandingRewards(ctx, valAddr0).Rewards) + require.Equal(t, sdk.DecCoins{{Denom: sdk.DefaultBondDenom, Amount: math.LegacyNewDecWithPrec(490, 1)}}, distrKeeper.GetValidatorOutstandingRewards(ctx, valAddr1).Rewards) // 2 community pool coins require.Equal(t, sdk.DecCoins{{Denom: sdk.DefaultBondDenom, Amount: math.LegacyNewDec(2)}}, distrKeeper.GetFeePool(ctx).CommunityPool) // 50% commission for first proposer, (0.5 * 98%) * 100 / 2 = 23.25 - require.Equal(t, sdk.DecCoins{{Denom: sdk.DefaultBondDenom, Amount: sdk.NewDecWithPrec(2450, 2)}}, distrKeeper.GetValidatorAccumulatedCommission(ctx, valAddr0).Commission) + require.Equal(t, sdk.DecCoins{{Denom: sdk.DefaultBondDenom, Amount: math.LegacyNewDecWithPrec(2450, 2)}}, distrKeeper.GetValidatorAccumulatedCommission(ctx, valAddr0).Commission) // zero commission for second proposer require.True(t, distrKeeper.GetValidatorAccumulatedCommission(ctx, valAddr1).Commission.IsZero()) // just staking.proportional for first proposer less commission = (0.5 * 98%) * 100 / 2 = 24.50 - require.Equal(t, sdk.DecCoins{{Denom: sdk.DefaultBondDenom, Amount: sdk.NewDecWithPrec(2450, 2)}}, distrKeeper.GetValidatorCurrentRewards(ctx, valAddr0).Rewards) + require.Equal(t, sdk.DecCoins{{Denom: sdk.DefaultBondDenom, Amount: math.LegacyNewDecWithPrec(2450, 2)}}, distrKeeper.GetValidatorCurrentRewards(ctx, valAddr0).Rewards) // proposer reward + staking.proportional for second proposer = (0.5 * (98%)) * 100 = 49 - require.Equal(t, sdk.DecCoins{{Denom: sdk.DefaultBondDenom, Amount: sdk.NewDecWithPrec(490, 1)}}, distrKeeper.GetValidatorCurrentRewards(ctx, valAddr1).Rewards) + require.Equal(t, sdk.DecCoins{{Denom: sdk.DefaultBondDenom, Amount: math.LegacyNewDecWithPrec(490, 1)}}, distrKeeper.GetValidatorCurrentRewards(ctx, valAddr1).Rewards) } func TestAllocateTokensTruncation(t *testing.T) { @@ -199,21 +199,21 @@ func TestAllocateTokensTruncation(t *testing.T) { valAddr0 := sdk.ValAddress(valConsAddr0) val0, err := distrtestutil.CreateValidator(valConsPk0, math.NewInt(100)) require.NoError(t, err) - val0.Commission = stakingtypes.NewCommission(sdk.NewDecWithPrec(1, 1), sdk.NewDecWithPrec(1, 1), math.LegacyNewDec(0)) + val0.Commission = stakingtypes.NewCommission(math.LegacyNewDecWithPrec(1, 1), math.LegacyNewDecWithPrec(1, 1), math.LegacyNewDec(0)) stakingKeeper.EXPECT().ValidatorByConsAddr(gomock.Any(), sdk.GetConsAddress(valConsPk0)).Return(val0).AnyTimes() // create second validator with 10% commission valAddr1 := sdk.ValAddress(valConsAddr1) val1, err := distrtestutil.CreateValidator(valConsPk1, math.NewInt(100)) require.NoError(t, err) - val1.Commission = stakingtypes.NewCommission(sdk.NewDecWithPrec(1, 1), sdk.NewDecWithPrec(1, 1), math.LegacyNewDec(0)) + val1.Commission = stakingtypes.NewCommission(math.LegacyNewDecWithPrec(1, 1), math.LegacyNewDecWithPrec(1, 1), math.LegacyNewDec(0)) stakingKeeper.EXPECT().ValidatorByConsAddr(gomock.Any(), sdk.GetConsAddress(valConsPk1)).Return(val1).AnyTimes() // create third validator with 10% commission valAddr2 := sdk.ValAddress(valConsAddr2) val2, err := stakingtypes.NewValidator(sdk.ValAddress(valConsAddr2), valConsPk1, stakingtypes.Description{}) require.NoError(t, err) - val2.Commission = stakingtypes.NewCommission(sdk.NewDecWithPrec(1, 1), sdk.NewDecWithPrec(1, 1), math.LegacyNewDec(0)) + val2.Commission = stakingtypes.NewCommission(math.LegacyNewDecWithPrec(1, 1), math.LegacyNewDecWithPrec(1, 1), math.LegacyNewDec(0)) stakingKeeper.EXPECT().ValidatorByConsAddr(gomock.Any(), sdk.GetConsAddress(valConsPk2)).Return(val2).AnyTimes() abciValA := abci.Validator{ @@ -240,7 +240,7 @@ func TestAllocateTokensTruncation(t *testing.T) { require.True(t, distrKeeper.GetValidatorCurrentRewards(ctx, valAddr1).Rewards.IsZero()) // allocate tokens as if both had voted and second was proposer - fees := sdk.NewCoins(sdk.NewCoin(sdk.DefaultBondDenom, sdk.NewInt(634195840))) + fees := sdk.NewCoins(sdk.NewCoin(sdk.DefaultBondDenom, math.NewInt(634195840))) bankKeeper.EXPECT().GetAllBalances(gomock.Any(), feeCollectorAcc.GetAddress()).Return(fees) bankKeeper.EXPECT().SendCoinsFromModuleToModule(gomock.Any(), "fee_collector", disttypes.ModuleName, fees) diff --git a/x/distribution/keeper/delegation.go b/x/distribution/keeper/delegation.go index 3eb9f2b03c7d..99c6e949ad53 100644 --- a/x/distribution/keeper/delegation.go +++ b/x/distribution/keeper/delegation.go @@ -30,7 +30,7 @@ func (k Keeper) initializeDelegation(ctx sdk.Context, val sdk.ValAddress, del sd // calculate the rewards accrued by a delegation between two periods func (k Keeper) calculateDelegationRewardsBetween(ctx sdk.Context, val stakingtypes.ValidatorI, - startingPeriod, endingPeriod uint64, stake sdk.Dec, + startingPeriod, endingPeriod uint64, stake math.LegacyDec, ) (rewards sdk.DecCoins) { // sanity check if startingPeriod > endingPeriod { @@ -121,7 +121,7 @@ func (k Keeper) CalculateDelegationRewards(ctx sdk.Context, val stakingtypes.Val // // A small amount of this error is tolerated and corrected for, // however any greater amount should be considered a breach in expected - // behaviour. + // behavior. marginOfErr := sdk.SmallestDec().MulInt64(3) if stake.LTE(currentStake.Add(marginOfErr)) { stake = currentStake diff --git a/x/distribution/keeper/delegation_test.go b/x/distribution/keeper/delegation_test.go index 98225d703891..80883c204d1e 100644 --- a/x/distribution/keeper/delegation_test.go +++ b/x/distribution/keeper/delegation_test.go @@ -51,9 +51,9 @@ func TestCalculateRewardsBasic(t *testing.T) { // create validator with 50% commission valAddr := sdk.ValAddress(valConsAddr0) addr := sdk.AccAddress(valAddr) - val, err := distrtestutil.CreateValidator(valConsPk0, sdk.NewInt(1000)) + val, err := distrtestutil.CreateValidator(valConsPk0, math.NewInt(1000)) require.NoError(t, err) - val.Commission = stakingtypes.NewCommission(sdk.NewDecWithPrec(5, 1), sdk.NewDecWithPrec(5, 1), math.LegacyNewDec(0)) + val.Commission = stakingtypes.NewCommission(math.LegacyNewDecWithPrec(5, 1), math.LegacyNewDecWithPrec(5, 1), math.LegacyNewDec(0)) // delegation mock del := stakingtypes.NewDelegation(addr, valAddr, val.DelegatorShares) @@ -133,7 +133,7 @@ func TestCalculateRewardsAfterSlash(t *testing.T) { stake := sdk.TokensFromConsensusPower(100, sdk.DefaultPowerReduction) val, err := distrtestutil.CreateValidator(valConsPk0, stake) require.NoError(t, err) - val.Commission = stakingtypes.NewCommission(sdk.NewDecWithPrec(5, 1), sdk.NewDecWithPrec(5, 1), math.LegacyNewDec(0)) + val.Commission = stakingtypes.NewCommission(math.LegacyNewDecWithPrec(5, 1), math.LegacyNewDecWithPrec(5, 1), math.LegacyNewDec(0)) del := stakingtypes.NewDelegation(addr, valAddr, val.DelegatorShares) @@ -166,7 +166,7 @@ func TestCalculateRewardsAfterSlash(t *testing.T) { valConsAddr0, ctx.BlockHeight(), valPower, - sdk.NewDecWithPrec(5, 1), + math.LegacyNewDecWithPrec(5, 1), &val, &distrKeeper, ) @@ -177,7 +177,7 @@ func TestCalculateRewardsAfterSlash(t *testing.T) { // allocate some rewards initial := sdk.TokensFromConsensusPower(10, sdk.DefaultPowerReduction) - tokens := sdk.DecCoins{{Denom: sdk.DefaultBondDenom, Amount: sdk.NewDecFromInt(initial)}} + tokens := sdk.DecCoins{{Denom: sdk.DefaultBondDenom, Amount: math.LegacyNewDecFromInt(initial)}} distrKeeper.AllocateTokensToValidator(ctx, val, tokens) // end period @@ -187,10 +187,10 @@ func TestCalculateRewardsAfterSlash(t *testing.T) { rewards = distrKeeper.CalculateDelegationRewards(ctx, val, del, endingPeriod) // rewards should be half the tokens - require.Equal(t, sdk.DecCoins{{Denom: sdk.DefaultBondDenom, Amount: sdk.NewDecFromInt(initial.QuoRaw(2))}}, rewards) + require.Equal(t, sdk.DecCoins{{Denom: sdk.DefaultBondDenom, Amount: math.LegacyNewDecFromInt(initial.QuoRaw(2))}}, rewards) // commission should be the other half - require.Equal(t, sdk.DecCoins{{Denom: sdk.DefaultBondDenom, Amount: sdk.NewDecFromInt(initial.QuoRaw(2))}}, + require.Equal(t, sdk.DecCoins{{Denom: sdk.DefaultBondDenom, Amount: math.LegacyNewDecFromInt(initial.QuoRaw(2))}}, distrKeeper.GetValidatorAccumulatedCommission(ctx, valAddr).Commission) } @@ -228,7 +228,7 @@ func TestCalculateRewardsAfterManySlashes(t *testing.T) { stake := sdk.TokensFromConsensusPower(valPower, sdk.DefaultPowerReduction) val, err := distrtestutil.CreateValidator(valConsPk0, stake) require.NoError(t, err) - val.Commission = stakingtypes.NewCommission(sdk.NewDecWithPrec(5, 1), sdk.NewDecWithPrec(5, 1), math.LegacyNewDec(0)) + val.Commission = stakingtypes.NewCommission(math.LegacyNewDecWithPrec(5, 1), math.LegacyNewDecWithPrec(5, 1), math.LegacyNewDec(0)) // delegation mocks del := stakingtypes.NewDelegation(addr, valAddr, val.DelegatorShares) @@ -260,7 +260,7 @@ func TestCalculateRewardsAfterManySlashes(t *testing.T) { valConsAddr0, ctx.BlockHeight(), valPower, - sdk.NewDecWithPrec(5, 1), + math.LegacyNewDecWithPrec(5, 1), &val, &distrKeeper, ) @@ -274,7 +274,7 @@ func TestCalculateRewardsAfterManySlashes(t *testing.T) { // allocate some rewards initial := sdk.TokensFromConsensusPower(10, sdk.DefaultPowerReduction) - tokens := sdk.DecCoins{{Denom: sdk.DefaultBondDenom, Amount: sdk.NewDecFromInt(initial)}} + tokens := sdk.DecCoins{{Denom: sdk.DefaultBondDenom, Amount: math.LegacyNewDecFromInt(initial)}} distrKeeper.AllocateTokensToValidator(ctx, val, tokens) // slash the validator by 50% again @@ -283,7 +283,7 @@ func TestCalculateRewardsAfterManySlashes(t *testing.T) { valConsAddr0, ctx.BlockHeight(), valPower/2, - sdk.NewDecWithPrec(2, 1), + math.LegacyNewDecWithPrec(2, 1), &val, &distrKeeper, ) @@ -302,10 +302,10 @@ func TestCalculateRewardsAfterManySlashes(t *testing.T) { rewards = distrKeeper.CalculateDelegationRewards(ctx, val, del, endingPeriod) // rewards should be half the tokens - require.Equal(t, sdk.DecCoins{{Denom: sdk.DefaultBondDenom, Amount: sdk.NewDecFromInt(initial)}}, rewards) + require.Equal(t, sdk.DecCoins{{Denom: sdk.DefaultBondDenom, Amount: math.LegacyNewDecFromInt(initial)}}, rewards) // commission should be the other half - require.Equal(t, sdk.DecCoins{{Denom: sdk.DefaultBondDenom, Amount: sdk.NewDecFromInt(initial)}}, + require.Equal(t, sdk.DecCoins{{Denom: sdk.DefaultBondDenom, Amount: math.LegacyNewDecFromInt(initial)}}, distrKeeper.GetValidatorAccumulatedCommission(ctx, valAddr).Commission) } @@ -342,7 +342,7 @@ func TestCalculateRewardsMultiDelegator(t *testing.T) { val, err := distrtestutil.CreateValidator(valConsPk0, math.NewInt(100)) require.NoError(t, err) - val.Commission = stakingtypes.NewCommission(sdk.NewDecWithPrec(5, 1), sdk.NewDecWithPrec(5, 1), math.LegacyNewDec(0)) + val.Commission = stakingtypes.NewCommission(math.LegacyNewDecWithPrec(5, 1), math.LegacyNewDecWithPrec(5, 1), math.LegacyNewDec(0)) del0 := stakingtypes.NewDelegation(addr0, valAddr, val.DelegatorShares) @@ -364,7 +364,7 @@ func TestCalculateRewardsMultiDelegator(t *testing.T) { // second delegation addr1 := sdk.AccAddress(valConsAddr1) - _, del1, err := distrtestutil.Delegate(ctx, distrKeeper, addr1, &val, sdk.NewInt(100), nil) + _, del1, err := distrtestutil.Delegate(ctx, distrKeeper, addr1, &val, math.NewInt(100), nil) require.NoError(t, err) stakingKeeper.EXPECT().Delegation(gomock.Any(), addr1, valAddr).Return(del1) @@ -432,7 +432,7 @@ func TestWithdrawDelegationRewardsBasic(t *testing.T) { val, err := distrtestutil.CreateValidator(valConsPk0, math.NewInt(100)) require.NoError(t, err) - val.Commission = stakingtypes.NewCommission(sdk.NewDecWithPrec(5, 1), sdk.NewDecWithPrec(5, 1), math.LegacyNewDec(0)) + val.Commission = stakingtypes.NewCommission(math.LegacyNewDecWithPrec(5, 1), math.LegacyNewDecWithPrec(5, 1), math.LegacyNewDec(0)) // delegation mock del := stakingtypes.NewDelegation(addr, valAddr, val.DelegatorShares) @@ -504,7 +504,7 @@ func TestCalculateRewardsAfterManySlashesInSameBlock(t *testing.T) { val, err := distrtestutil.CreateValidator(valConsPk0, math.NewInt(100)) require.NoError(t, err) - val.Commission = stakingtypes.NewCommission(sdk.NewDecWithPrec(5, 1), sdk.NewDecWithPrec(5, 1), math.LegacyNewDec(0)) + val.Commission = stakingtypes.NewCommission(math.LegacyNewDecWithPrec(5, 1), math.LegacyNewDecWithPrec(5, 1), math.LegacyNewDec(0)) // delegation mock del := stakingtypes.NewDelegation(addr, valAddr, val.DelegatorShares) @@ -531,7 +531,7 @@ func TestCalculateRewardsAfterManySlashesInSameBlock(t *testing.T) { ctx = ctx.WithBlockHeight(ctx.BlockHeight() + 3) // allocate some rewards - initial := sdk.NewDecFromInt(sdk.TokensFromConsensusPower(10, sdk.DefaultPowerReduction)) + initial := math.LegacyNewDecFromInt(sdk.TokensFromConsensusPower(10, sdk.DefaultPowerReduction)) tokens := sdk.DecCoins{{Denom: sdk.DefaultBondDenom, Amount: initial}} distrKeeper.AllocateTokensToValidator(ctx, val, tokens) @@ -542,19 +542,19 @@ func TestCalculateRewardsAfterManySlashesInSameBlock(t *testing.T) { valConsAddr0, ctx.BlockHeight(), valPower, - sdk.NewDecWithPrec(5, 1), + math.LegacyNewDecWithPrec(5, 1), &val, &distrKeeper, ) // slash the validator by 50% again - // stakingKeeper.Slash(ctx, valConsAddr0, ctx.BlockHeight(), valPower/2, sdk.NewDecWithPrec(5, 1)) + // stakingKeeper.Slash(ctx, valConsAddr0, ctx.BlockHeight(), valPower/2, math.LegacyNewDecWithPrec(5, 1)) distrtestutil.SlashValidator( ctx, valConsAddr0, ctx.BlockHeight(), valPower/2, - sdk.NewDecWithPrec(5, 1), + math.LegacyNewDecWithPrec(5, 1), &val, &distrKeeper, ) @@ -612,7 +612,7 @@ func TestCalculateRewardsMultiDelegatorMultiSlash(t *testing.T) { addr := sdk.AccAddress(valAddr) val, err := distrtestutil.CreateValidator(valConsPk0, sdk.TokensFromConsensusPower(valPower, sdk.DefaultPowerReduction)) require.NoError(t, err) - val.Commission = stakingtypes.NewCommission(sdk.NewDecWithPrec(5, 1), sdk.NewDecWithPrec(5, 1), math.LegacyNewDec(0)) + val.Commission = stakingtypes.NewCommission(math.LegacyNewDecWithPrec(5, 1), math.LegacyNewDecWithPrec(5, 1), math.LegacyNewDec(0)) // validator and delegation mocks del := stakingtypes.NewDelegation(addr, valAddr, val.DelegatorShares) @@ -628,7 +628,7 @@ func TestCalculateRewardsMultiDelegatorMultiSlash(t *testing.T) { ctx = ctx.WithBlockHeight(ctx.BlockHeight() + 1) // allocate some rewards - initial := sdk.NewDecFromInt(sdk.TokensFromConsensusPower(30, sdk.DefaultPowerReduction)) + initial := math.LegacyNewDecFromInt(sdk.TokensFromConsensusPower(30, sdk.DefaultPowerReduction)) tokens := sdk.DecCoins{{Denom: sdk.DefaultBondDenom, Amount: initial}} distrKeeper.AllocateTokensToValidator(ctx, val, tokens) @@ -639,7 +639,7 @@ func TestCalculateRewardsMultiDelegatorMultiSlash(t *testing.T) { valConsAddr0, ctx.BlockHeight(), valPower, - sdk.NewDecWithPrec(5, 1), + math.LegacyNewDecWithPrec(5, 1), &val, &distrKeeper, ) @@ -680,7 +680,7 @@ func TestCalculateRewardsMultiDelegatorMultiSlash(t *testing.T) { valConsAddr0, ctx.BlockHeight(), valPower, - sdk.NewDecWithPrec(5, 1), + math.LegacyNewDecWithPrec(5, 1), &val, &distrKeeper, ) @@ -735,9 +735,9 @@ func TestCalculateRewardsMultiDelegatorMultWithdraw(t *testing.T) { // create validator with 50% commission valAddr := sdk.ValAddress(valConsAddr0) addr := sdk.AccAddress(valAddr) - val, err := distrtestutil.CreateValidator(valConsPk0, sdk.NewInt(100)) + val, err := distrtestutil.CreateValidator(valConsPk0, math.NewInt(100)) require.NoError(t, err) - val.Commission = stakingtypes.NewCommission(sdk.NewDecWithPrec(5, 1), sdk.NewDecWithPrec(5, 1), math.LegacyNewDec(0)) + val.Commission = stakingtypes.NewCommission(math.LegacyNewDecWithPrec(5, 1), math.LegacyNewDecWithPrec(5, 1), math.LegacyNewDec(0)) // validator and delegation mocks del := stakingtypes.NewDelegation(addr, valAddr, val.DelegatorShares) @@ -766,7 +766,7 @@ func TestCalculateRewardsMultiDelegatorMultWithdraw(t *testing.T) { distrKeeper, sdk.AccAddress(valConsAddr1), &val, - sdk.NewInt(100), + math.NewInt(100), nil, ) require.NoError(t, err) @@ -918,9 +918,9 @@ func Test100PercentCommissionReward(t *testing.T) { // create validator with 50% commission valAddr := sdk.ValAddress(valConsAddr0) addr := sdk.AccAddress(valAddr) - val, err := distrtestutil.CreateValidator(valConsPk0, sdk.NewInt(100)) + val, err := distrtestutil.CreateValidator(valConsPk0, math.NewInt(100)) require.NoError(t, err) - val.Commission = stakingtypes.NewCommission(sdk.NewDecWithPrec(10, 1), sdk.NewDecWithPrec(10, 1), math.LegacyNewDec(0)) + val.Commission = stakingtypes.NewCommission(math.LegacyNewDecWithPrec(10, 1), math.LegacyNewDecWithPrec(10, 1), math.LegacyNewDec(0)) // validator and delegation mocks del := stakingtypes.NewDelegation(addr, valAddr, val.DelegatorShares) diff --git a/x/distribution/keeper/genesis.go b/x/distribution/keeper/genesis.go index 497a732753f6..8c6ac54cf397 100644 --- a/x/distribution/keeper/genesis.go +++ b/x/distribution/keeper/genesis.go @@ -18,8 +18,14 @@ func (k Keeper) InitGenesis(ctx sdk.Context, data types.GenesisState) { } for _, dwi := range data.DelegatorWithdrawInfos { - delegatorAddress := sdk.MustAccAddressFromBech32(dwi.DelegatorAddress) - withdrawAddress := sdk.MustAccAddressFromBech32(dwi.WithdrawAddress) + delegatorAddress, err := k.authKeeper.StringToBytes(dwi.DelegatorAddress) + if err != nil { + panic(err) + } + withdrawAddress, err := k.authKeeper.StringToBytes(dwi.WithdrawAddress) + if err != nil { + panic(err) + } k.SetDelegatorWithdrawAddr(ctx, delegatorAddress, withdrawAddress) } @@ -68,7 +74,10 @@ func (k Keeper) InitGenesis(ctx sdk.Context, data types.GenesisState) { if err != nil { panic(err) } - delegatorAddress := sdk.MustAccAddressFromBech32(del.DelegatorAddress) + delegatorAddress, err := k.authKeeper.StringToBytes(del.DelegatorAddress) + if err != nil { + panic(err) + } k.SetDelegatorStartingInfo(ctx, valAddr, delegatorAddress, del.StartingInfo) } @@ -104,7 +113,7 @@ func (k Keeper) ExportGenesis(ctx sdk.Context) *types.GenesisState { params := k.GetParams(ctx) dwi := make([]types.DelegatorWithdrawInfo, 0) - k.IterateDelegatorWithdrawAddrs(ctx, func(del sdk.AccAddress, addr sdk.AccAddress) (stop bool) { + k.IterateDelegatorWithdrawAddrs(ctx, func(del, addr sdk.AccAddress) (stop bool) { dwi = append(dwi, types.DelegatorWithdrawInfo{ DelegatorAddress: del.String(), WithdrawAddress: addr.String(), diff --git a/x/distribution/keeper/grpc_query.go b/x/distribution/keeper/grpc_query.go index af2756899906..99bc45a410ae 100644 --- a/x/distribution/keeper/grpc_query.go +++ b/x/distribution/keeper/grpc_query.go @@ -6,9 +6,8 @@ import ( "google.golang.org/grpc/codes" "google.golang.org/grpc/status" - "cosmossdk.io/store/prefix" - "cosmossdk.io/errors" + "cosmossdk.io/store/prefix" sdk "github.com/cosmos/cosmos-sdk/types" "github.com/cosmos/cosmos-sdk/types/query" @@ -93,6 +92,11 @@ func (k Querier) ValidatorOutstandingRewards(c context.Context, req *types.Query if err != nil { return nil, err } + + validator := k.stakingKeeper.Validator(ctx, valAdr) + if validator == nil { + return nil, errors.Wrapf(types.ErrNoValidatorExists, valAdr.String()) + } rewards := k.GetValidatorOutstandingRewards(ctx, valAdr) return &types.QueryValidatorOutstandingRewardsResponse{Rewards: rewards}, nil @@ -114,6 +118,11 @@ func (k Querier) ValidatorCommission(c context.Context, req *types.QueryValidato if err != nil { return nil, err } + + validator := k.stakingKeeper.Validator(ctx, valAdr) + if validator == nil { + return nil, errors.Wrapf(types.ErrNoValidatorExists, valAdr.String()) + } commission := k.GetValidatorAccumulatedCommission(ctx, valAdr) return &types.QueryValidatorCommissionResponse{Commission: commission}, nil @@ -188,7 +197,7 @@ func (k Querier) DelegationRewards(c context.Context, req *types.QueryDelegation return nil, errors.Wrap(types.ErrNoValidatorExists, req.ValidatorAddress) } - delAdr, err := sdk.AccAddressFromBech32(req.DelegatorAddress) + delAdr, err := k.authKeeper.StringToBytes(req.DelegatorAddress) if err != nil { return nil, err } @@ -218,7 +227,7 @@ func (k Querier) DelegationTotalRewards(c context.Context, req *types.QueryDeleg total := sdk.DecCoins{} var delRewards []types.DelegationDelegatorReward - delAdr, err := sdk.AccAddressFromBech32(req.DelegatorAddress) + delAdr, err := k.authKeeper.StringToBytes(req.DelegatorAddress) if err != nil { return nil, err } @@ -251,7 +260,7 @@ func (k Querier) DelegatorValidators(c context.Context, req *types.QueryDelegato } ctx := sdk.UnwrapSDKContext(c) - delAdr, err := sdk.AccAddressFromBech32(req.DelegatorAddress) + delAdr, err := k.authKeeper.StringToBytes(req.DelegatorAddress) if err != nil { return nil, err } @@ -277,7 +286,7 @@ func (k Querier) DelegatorWithdrawAddress(c context.Context, req *types.QueryDel if req.DelegatorAddress == "" { return nil, status.Error(codes.InvalidArgument, "empty delegator address") } - delAdr, err := sdk.AccAddressFromBech32(req.DelegatorAddress) + delAdr, err := k.authKeeper.StringToBytes(req.DelegatorAddress) if err != nil { return nil, err } diff --git a/x/distribution/keeper/hooks.go b/x/distribution/keeper/hooks.go index cb8ca0c3f757..8179048dd514 100644 --- a/x/distribution/keeper/hooks.go +++ b/x/distribution/keeper/hooks.go @@ -1,6 +1,8 @@ package keeper import ( + sdkmath "cosmossdk.io/math" + sdk "github.com/cosmos/cosmos-sdk/types" "github.com/cosmos/cosmos-sdk/x/distribution/types" stakingtypes "github.com/cosmos/cosmos-sdk/x/staking/types" @@ -106,7 +108,7 @@ func (h Hooks) AfterDelegationModified(ctx sdk.Context, delAddr sdk.AccAddress, } // record the slash event -func (h Hooks) BeforeValidatorSlashed(ctx sdk.Context, valAddr sdk.ValAddress, fraction sdk.Dec) error { +func (h Hooks) BeforeValidatorSlashed(ctx sdk.Context, valAddr sdk.ValAddress, fraction sdkmath.LegacyDec) error { h.k.updateValidatorSlashFraction(ctx, valAddr, fraction) return nil } diff --git a/x/distribution/keeper/keeper.go b/x/distribution/keeper/keeper.go index ab80c8aeb7d7..8969d6478de0 100644 --- a/x/distribution/keeper/keeper.go +++ b/x/distribution/keeper/keeper.go @@ -31,7 +31,7 @@ type Keeper struct { func NewKeeper( cdc codec.BinaryCodec, key storetypes.StoreKey, ak types.AccountKeeper, bk types.BankKeeper, sk types.StakingKeeper, - feeCollectorName string, authority string, + feeCollectorName, authority string, ) Keeper { // ensure distribution module account is set if addr := ak.GetModuleAddress(types.ModuleName); addr == nil { @@ -60,7 +60,7 @@ func (k Keeper) Logger(ctx sdk.Context) log.Logger { } // SetWithdrawAddr sets a new address that will receive the rewards upon withdrawal -func (k Keeper) SetWithdrawAddr(ctx sdk.Context, delegatorAddr sdk.AccAddress, withdrawAddr sdk.AccAddress) error { +func (k Keeper) SetWithdrawAddr(ctx sdk.Context, delegatorAddr, withdrawAddr sdk.AccAddress) error { if k.bankKeeper.BlockedAddr(withdrawAddr) { return errorsmod.Wrapf(sdkerrors.ErrUnauthorized, "%s is not allowed to receive external funds", withdrawAddr) } diff --git a/x/distribution/keeper/keeper_test.go b/x/distribution/keeper/keeper_test.go index 754a42d35374..33d28b1c56df 100644 --- a/x/distribution/keeper/keeper_test.go +++ b/x/distribution/keeper/keeper_test.go @@ -106,7 +106,7 @@ func TestWithdrawValidatorCommission(t *testing.T) { distrKeeper.SetValidatorAccumulatedCommission(ctx, valAddr, types.ValidatorAccumulatedCommission{Commission: valCommission}) // withdraw commission - coins := sdk.NewCoins(sdk.NewCoin("mytoken", sdk.NewInt(1)), sdk.NewCoin("stake", sdk.NewInt(1))) + coins := sdk.NewCoins(sdk.NewCoin("mytoken", math.NewInt(1)), sdk.NewCoin("stake", math.NewInt(1))) // if SendCoinsFromModuleToAccount is called, we know that the withdraw was successful bankKeeper.EXPECT().SendCoinsFromModuleToAccount(gomock.Any(), "distribution", addrs[0], coins).Return(nil) diff --git a/x/distribution/keeper/msg_server.go b/x/distribution/keeper/msg_server.go index 37b66e0145b7..4e7bbb8e24d7 100644 --- a/x/distribution/keeper/msg_server.go +++ b/x/distribution/keeper/msg_server.go @@ -3,13 +3,12 @@ package keeper import ( "context" + "cosmossdk.io/errors" "github.com/armon/go-metrics" - errorsmod "cosmossdk.io/errors" - "github.com/cosmos/cosmos-sdk/telemetry" sdk "github.com/cosmos/cosmos-sdk/types" - "github.com/cosmos/cosmos-sdk/types/errors" + sdkerrors "github.com/cosmos/cosmos-sdk/types/errors" "github.com/cosmos/cosmos-sdk/x/distribution/types" govtypes "github.com/cosmos/cosmos-sdk/x/gov/types" ) @@ -27,16 +26,17 @@ func NewMsgServerImpl(keeper Keeper) types.MsgServer { } func (k msgServer) SetWithdrawAddress(goCtx context.Context, msg *types.MsgSetWithdrawAddress) (*types.MsgSetWithdrawAddressResponse, error) { - ctx := sdk.UnwrapSDKContext(goCtx) - - delegatorAddress, err := sdk.AccAddressFromBech32(msg.DelegatorAddress) + delegatorAddress, err := k.authKeeper.StringToBytes(msg.DelegatorAddress) if err != nil { - return nil, err + return nil, sdkerrors.ErrInvalidAddress.Wrapf("invalid delegator address: %s", err) } - withdrawAddress, err := sdk.AccAddressFromBech32(msg.WithdrawAddress) + + withdrawAddress, err := k.authKeeper.StringToBytes(msg.WithdrawAddress) if err != nil { - return nil, err + return nil, sdkerrors.ErrInvalidAddress.Wrapf("invalid withdraw address: %s", err) } + + ctx := sdk.UnwrapSDKContext(goCtx) err = k.SetWithdrawAddr(ctx, delegatorAddress, withdrawAddress) if err != nil { return nil, err @@ -46,16 +46,17 @@ func (k msgServer) SetWithdrawAddress(goCtx context.Context, msg *types.MsgSetWi } func (k msgServer) WithdrawDelegatorReward(goCtx context.Context, msg *types.MsgWithdrawDelegatorReward) (*types.MsgWithdrawDelegatorRewardResponse, error) { - ctx := sdk.UnwrapSDKContext(goCtx) - valAddr, err := sdk.ValAddressFromBech32(msg.ValidatorAddress) if err != nil { - return nil, err + return nil, sdkerrors.ErrInvalidAddress.Wrapf("invalid validator address: %s", err) } - delegatorAddress, err := sdk.AccAddressFromBech32(msg.DelegatorAddress) + + delegatorAddress, err := k.authKeeper.StringToBytes(msg.DelegatorAddress) if err != nil { - return nil, err + return nil, sdkerrors.ErrInvalidAddress.Wrapf("invalid delegator address: %s", err) } + + ctx := sdk.UnwrapSDKContext(goCtx) amount, err := k.WithdrawDelegationRewards(ctx, delegatorAddress, valAddr) if err != nil { return nil, err @@ -77,12 +78,12 @@ func (k msgServer) WithdrawDelegatorReward(goCtx context.Context, msg *types.Msg } func (k msgServer) WithdrawValidatorCommission(goCtx context.Context, msg *types.MsgWithdrawValidatorCommission) (*types.MsgWithdrawValidatorCommissionResponse, error) { - ctx := sdk.UnwrapSDKContext(goCtx) - valAddr, err := sdk.ValAddressFromBech32(msg.ValidatorAddress) if err != nil { - return nil, err + return nil, sdkerrors.ErrInvalidAddress.Wrapf("invalid validator address: %s", err) } + + ctx := sdk.UnwrapSDKContext(goCtx) amount, err := k.Keeper.WithdrawValidatorCommission(ctx, valAddr) if err != nil { return nil, err @@ -104,98 +105,132 @@ func (k msgServer) WithdrawValidatorCommission(goCtx context.Context, msg *types } func (k msgServer) FundCommunityPool(goCtx context.Context, msg *types.MsgFundCommunityPool) (*types.MsgFundCommunityPoolResponse, error) { - ctx := sdk.UnwrapSDKContext(goCtx) - - depositer, err := sdk.AccAddressFromBech32(msg.Depositor) + depositor, err := k.authKeeper.StringToBytes(msg.Depositor) if err != nil { + return nil, sdkerrors.ErrInvalidAddress.Wrapf("invalid depositor address: %s", err) + } + + if err := validateAmount(msg.Amount); err != nil { return nil, err } - if err := k.Keeper.FundCommunityPool(ctx, msg.Amount, depositer); err != nil { + + ctx := sdk.UnwrapSDKContext(goCtx) + if err := k.Keeper.FundCommunityPool(ctx, msg.Amount, depositor); err != nil { return nil, err } return &types.MsgFundCommunityPoolResponse{}, nil } -func (k msgServer) UpdateParams(goCtx context.Context, req *types.MsgUpdateParams) (*types.MsgUpdateParamsResponse, error) { - if k.authority != req.Authority { - return nil, errorsmod.Wrapf(govtypes.ErrInvalidSigner, "invalid authority; expected %s, got %s", k.authority, req.Authority) +func (k msgServer) UpdateParams(goCtx context.Context, msg *types.MsgUpdateParams) (*types.MsgUpdateParamsResponse, error) { + if err := k.validateAuthority(msg.Authority); err != nil { + return nil, err + } + + if (!msg.Params.BaseProposerReward.IsNil() && !msg.Params.BaseProposerReward.IsZero()) || //nolint:staticcheck // deprecated but kept for backwards compatibility + (!msg.Params.BonusProposerReward.IsNil() && !msg.Params.BonusProposerReward.IsZero()) { //nolint:staticcheck // deprecated but kept for backwards compatibility + return nil, errors.Wrapf(sdkerrors.ErrInvalidRequest, "cannot update base or bonus proposer reward because these are deprecated fields") } - if (!req.Params.BaseProposerReward.IsNil() && !req.Params.BaseProposerReward.IsZero()) || //nolint:staticcheck - (!req.Params.BonusProposerReward.IsNil() && !req.Params.BonusProposerReward.IsZero()) { //nolint:staticcheck - return nil, errorsmod.Wrapf(errors.ErrInvalidRequest, "cannot update base or bonus proposer reward because these are deprecated fields") + if err := msg.Params.ValidateBasic(); err != nil { + return nil, err } ctx := sdk.UnwrapSDKContext(goCtx) - if err := k.SetParams(ctx, req.Params); err != nil { + if err := k.SetParams(ctx, msg.Params); err != nil { return nil, err } return &types.MsgUpdateParamsResponse{}, nil } -func (k msgServer) CommunityPoolSpend(goCtx context.Context, req *types.MsgCommunityPoolSpend) (*types.MsgCommunityPoolSpendResponse, error) { - if k.authority != req.Authority { - return nil, errorsmod.Wrapf(govtypes.ErrInvalidSigner, "invalid authority; expected %s, got %s", k.authority, req.Authority) +func (k msgServer) CommunityPoolSpend(goCtx context.Context, msg *types.MsgCommunityPoolSpend) (*types.MsgCommunityPoolSpendResponse, error) { + if err := k.validateAuthority(msg.Authority); err != nil { + return nil, err } - ctx := sdk.UnwrapSDKContext(goCtx) + if err := validateAmount(msg.Amount); err != nil { + return nil, err + } - recipient, err := sdk.AccAddressFromBech32(req.Recipient) + recipient, err := k.authKeeper.StringToBytes(msg.Recipient) if err != nil { return nil, err } if k.bankKeeper.BlockedAddr(recipient) { - return nil, errorsmod.Wrapf(errors.ErrUnauthorized, "%s is not allowed to receive external funds", req.Recipient) + return nil, errors.Wrapf(sdkerrors.ErrUnauthorized, "%s is not allowed to receive external funds", msg.Recipient) } - if err := k.DistributeFromFeePool(ctx, req.Amount, recipient); err != nil { + ctx := sdk.UnwrapSDKContext(goCtx) + if err := k.DistributeFromFeePool(ctx, msg.Amount, recipient); err != nil { return nil, err } logger := k.Logger(ctx) - logger.Info("transferred from the community pool to recipient", "amount", req.Amount.String(), "recipient", req.Recipient) + logger.Info("transferred from the community pool to recipient", "amount", msg.Amount.String(), "recipient", msg.Recipient) return &types.MsgCommunityPoolSpendResponse{}, nil } -func (k msgServer) DepositValidatorRewardsPool(goCtx context.Context, req *types.MsgDepositValidatorRewardsPool) (*types.MsgDepositValidatorRewardsPoolResponse, error) { - ctx := sdk.UnwrapSDKContext(goCtx) - - authority, err := sdk.AccAddressFromBech32(req.Authority) +func (k msgServer) DepositValidatorRewardsPool(goCtx context.Context, msg *types.MsgDepositValidatorRewardsPool) (*types.MsgDepositValidatorRewardsPoolResponse, error) { + depositor, err := k.authKeeper.StringToBytes(msg.Depositor) if err != nil { return nil, err } - // deposit coins from sender's account to the distribution module - if err := k.bankKeeper.SendCoinsFromAccountToModule(ctx, authority, types.ModuleName, req.Amount); err != nil { + ctx := sdk.UnwrapSDKContext(goCtx) + // deposit coins from depositor's account to the distribution module + if err := k.bankKeeper.SendCoinsFromAccountToModule(ctx, depositor, types.ModuleName, msg.Amount); err != nil { return nil, err } - valAddr, err := sdk.ValAddressFromBech32(req.ValidatorAddress) + valAddr, err := sdk.ValAddressFromBech32(msg.ValidatorAddress) if err != nil { return nil, err } validator := k.stakingKeeper.Validator(ctx, valAddr) if validator == nil { - return nil, errorsmod.Wrapf(types.ErrNoValidatorExists, valAddr.String()) + return nil, errors.Wrapf(types.ErrNoValidatorExists, valAddr.String()) } // Allocate tokens from the distribution module to the validator, which are // then distributed to the validator's delegators. - reward := sdk.NewDecCoinsFromCoins(req.Amount...) + reward := sdk.NewDecCoinsFromCoins(msg.Amount...) k.AllocateTokensToValidator(ctx, validator, reward) logger := k.Logger(ctx) logger.Info( "transferred from rewards to validator rewards pool", - "authority", req.Authority, - "amount", req.Amount.String(), - "validator", req.ValidatorAddress, + "depositor", msg.Depositor, + "amount", msg.Amount.String(), + "validator", msg.ValidatorAddress, ) return &types.MsgDepositValidatorRewardsPoolResponse{}, nil } + +func (k *Keeper) validateAuthority(authority string) error { + if _, err := k.authKeeper.StringToBytes(authority); err != nil { + return sdkerrors.ErrInvalidAddress.Wrapf("invalid authority address: %s", err) + } + + if k.authority != authority { + return errors.Wrapf(govtypes.ErrInvalidSigner, "invalid authority; expected %s, got %s", k.authority, authority) + } + + return nil +} + +func validateAmount(amount sdk.Coins) error { + if amount == nil { + return errors.Wrap(sdkerrors.ErrInvalidCoins, "amount cannot be nil") + } + + if err := amount.Validate(); err != nil { + return errors.Wrap(sdkerrors.ErrInvalidCoins, amount.String()) + } + + return nil +} diff --git a/x/distribution/keeper/params.go b/x/distribution/keeper/params.go index 278ec4c1bd87..2ab11eb273a7 100644 --- a/x/distribution/keeper/params.go +++ b/x/distribution/keeper/params.go @@ -19,12 +19,9 @@ func (k Keeper) GetParams(ctx sdk.Context) (params types.Params) { return params } -// SetParams sets the distribution parameters to the param space. +// SetParams sets the distribution parameters. +// CONTRACT: This method performs no validation of the parameters. func (k Keeper) SetParams(ctx sdk.Context, params types.Params) error { - if err := params.ValidateBasic(); err != nil { - return err - } - store := ctx.KVStore(k.storeKey) bz, err := k.cdc.Marshal(¶ms) if err != nil { diff --git a/x/distribution/keeper/params_test.go b/x/distribution/keeper/params_test.go deleted file mode 100644 index 7a4530dd5002..000000000000 --- a/x/distribution/keeper/params_test.go +++ /dev/null @@ -1,128 +0,0 @@ -package keeper_test - -import ( - "testing" - - storetypes "cosmossdk.io/store/types" - cmtproto "github.com/cometbft/cometbft/proto/tendermint/types" - "github.com/golang/mock/gomock" - "github.com/stretchr/testify/require" - - "github.com/cosmos/cosmos-sdk/testutil" - sdk "github.com/cosmos/cosmos-sdk/types" - moduletestutil "github.com/cosmos/cosmos-sdk/types/module/testutil" - authtypes "github.com/cosmos/cosmos-sdk/x/auth/types" - "github.com/cosmos/cosmos-sdk/x/distribution" - "github.com/cosmos/cosmos-sdk/x/distribution/keeper" - distrtestutil "github.com/cosmos/cosmos-sdk/x/distribution/testutil" - "github.com/cosmos/cosmos-sdk/x/distribution/types" -) - -func TestParams(t *testing.T) { - ctrl := gomock.NewController(t) - key := storetypes.NewKVStoreKey(types.StoreKey) - testCtx := testutil.DefaultContextWithDB(t, key, storetypes.NewTransientStoreKey("transient_test")) - encCfg := moduletestutil.MakeTestEncodingConfig(distribution.AppModuleBasic{}) - ctx := testCtx.Ctx.WithBlockHeader(cmtproto.Header{Height: 1}) - - bankKeeper := distrtestutil.NewMockBankKeeper(ctrl) - stakingKeeper := distrtestutil.NewMockStakingKeeper(ctrl) - accountKeeper := distrtestutil.NewMockAccountKeeper(ctrl) - - accountKeeper.EXPECT().GetModuleAddress("distribution").Return(distrAcc.GetAddress()) - - distrKeeper := keeper.NewKeeper( - encCfg.Codec, - key, - accountKeeper, - bankKeeper, - stakingKeeper, - "fee_collector", - authtypes.NewModuleAddress("gov").String(), - ) - - // default params - communityTax := sdk.NewDecWithPrec(2, 2) // 2% - withdrawAddrEnabled := true - - testCases := []struct { - name string - input types.Params - expErr bool - expErrMsg string - }{ - { - name: "community tax > 1", - input: types.Params{ - CommunityTax: sdk.NewDecWithPrec(2, 0), - BaseProposerReward: sdk.ZeroDec(), - BonusProposerReward: sdk.ZeroDec(), - WithdrawAddrEnabled: withdrawAddrEnabled, - }, - expErr: true, - expErrMsg: "community tax should be non-negative and less than one", - }, - { - name: "negative community tax", - input: types.Params{ - CommunityTax: sdk.NewDecWithPrec(-2, 1), - BaseProposerReward: sdk.ZeroDec(), - BonusProposerReward: sdk.ZeroDec(), - WithdrawAddrEnabled: withdrawAddrEnabled, - }, - expErr: true, - expErrMsg: "community tax should be non-negative and less than one", - }, - { - name: "base proposer reward > 1", - input: types.Params{ - CommunityTax: communityTax, - BaseProposerReward: sdk.NewDecWithPrec(1, 2), - BonusProposerReward: sdk.ZeroDec(), - WithdrawAddrEnabled: withdrawAddrEnabled, - }, - expErr: false, - expErrMsg: "base proposer rewards should not be taken into account", - }, - { - name: "bonus proposer reward > 1", - input: types.Params{ - CommunityTax: communityTax, - BaseProposerReward: sdk.NewDecWithPrec(1, 2), - BonusProposerReward: sdk.ZeroDec(), - WithdrawAddrEnabled: withdrawAddrEnabled, - }, - expErr: false, - expErrMsg: "bonus proposer rewards should not be taken into account", - }, - { - name: "all good", - input: types.Params{ - CommunityTax: communityTax, - BaseProposerReward: sdk.ZeroDec(), - BonusProposerReward: sdk.ZeroDec(), - WithdrawAddrEnabled: withdrawAddrEnabled, - }, - expErr: false, - }, - } - - for _, tc := range testCases { - tc := tc - t.Run(tc.name, func(t *testing.T) { - expected := distrKeeper.GetParams(ctx) - err := distrKeeper.SetParams(ctx, tc.input) - - if tc.expErr { - require.Error(t, err) - require.Contains(t, err.Error(), tc.expErrMsg) - } else { - expected = tc.input - require.NoError(t, err) - } - - params := distrKeeper.GetParams(ctx) - require.Equal(t, expected, params) - }) - } -} diff --git a/x/distribution/keeper/store.go b/x/distribution/keeper/store.go index 636c994a2027..ae5ef44507bc 100644 --- a/x/distribution/keeper/store.go +++ b/x/distribution/keeper/store.go @@ -32,7 +32,7 @@ func (k Keeper) DeleteDelegatorWithdrawAddr(ctx sdk.Context, delAddr, withdrawAd } // iterate over delegator withdraw addrs -func (k Keeper) IterateDelegatorWithdrawAddrs(ctx sdk.Context, handler func(del sdk.AccAddress, addr sdk.AccAddress) (stop bool)) { +func (k Keeper) IterateDelegatorWithdrawAddrs(ctx sdk.Context, handler func(del, addr sdk.AccAddress) (stop bool)) { store := ctx.KVStore(k.storeKey) iter := storetypes.KVStorePrefixIterator(store, types.DelegatorWithdrawAddrPrefix) defer iter.Close() @@ -332,7 +332,7 @@ func (k Keeper) SetValidatorSlashEvent(ctx sdk.Context, val sdk.ValAddress, heig } // iterate over slash events between heights, inclusive -func (k Keeper) IterateValidatorSlashEventsBetween(ctx sdk.Context, val sdk.ValAddress, startingHeight uint64, endingHeight uint64, +func (k Keeper) IterateValidatorSlashEventsBetween(ctx sdk.Context, val sdk.ValAddress, startingHeight, endingHeight uint64, handler func(height uint64, event types.ValidatorSlashEvent) (stop bool), ) { store := ctx.KVStore(k.storeKey) diff --git a/x/distribution/keeper/validator.go b/x/distribution/keeper/validator.go index 0d6671873d2d..984ec1a54f48 100644 --- a/x/distribution/keeper/validator.go +++ b/x/distribution/keeper/validator.go @@ -46,7 +46,7 @@ func (k Keeper) IncrementValidatorPeriod(ctx sdk.Context, val stakingtypes.Valid current = sdk.DecCoins{} } else { // note: necessary to truncate so we don't allow withdrawing more rewards than owed - current = rewards.Rewards.QuoDecTruncate(sdk.NewDecFromInt(val.GetTokens())) + current = rewards.Rewards.QuoDecTruncate(math.LegacyNewDecFromInt(val.GetTokens())) } // fetch historical rewards for last period diff --git a/x/distribution/migrations/v3/json.go b/x/distribution/migrations/v3/json.go index 21f5f1f45245..b4d07b9965cc 100644 --- a/x/distribution/migrations/v3/json.go +++ b/x/distribution/migrations/v3/json.go @@ -1,7 +1,7 @@ package v3 import ( - sdk "github.com/cosmos/cosmos-sdk/types" + sdkmath "cosmossdk.io/math" "github.com/cosmos/cosmos-sdk/x/distribution/types" ) @@ -11,8 +11,8 @@ import ( // Reset of the deprecated rewards to zero. func MigrateJSON(oldState *types.GenesisState) *types.GenesisState { // reset deprecated rewards to zero - oldState.Params.BaseProposerReward = sdk.ZeroDec() - oldState.Params.BonusProposerReward = sdk.ZeroDec() + oldState.Params.BaseProposerReward = sdkmath.LegacyZeroDec() + oldState.Params.BonusProposerReward = sdkmath.LegacyZeroDec() return oldState } diff --git a/x/distribution/migrations/v3/json_test.go b/x/distribution/migrations/v3/json_test.go index 41b969330b2f..09fa98d97e3d 100644 --- a/x/distribution/migrations/v3/json_test.go +++ b/x/distribution/migrations/v3/json_test.go @@ -4,10 +4,10 @@ import ( "encoding/json" "testing" + sdkmath "cosmossdk.io/math" "github.com/stretchr/testify/require" "github.com/cosmos/cosmos-sdk/client" - sdk "github.com/cosmos/cosmos-sdk/types" moduletestutil "github.com/cosmos/cosmos-sdk/types/module/testutil" "github.com/cosmos/cosmos-sdk/x/distribution" v3 "github.com/cosmos/cosmos-sdk/x/distribution/migrations/v3" @@ -24,8 +24,8 @@ func TestMigrateJSON(t *testing.T) { distrGenState := types.DefaultGenesisState() oldDistrState := distrGenState - oldDistrState.Params.BaseProposerReward = sdk.NewDecWithPrec(1, 2) - oldDistrState.Params.BonusProposerReward = sdk.NewDecWithPrec(4, 2) + oldDistrState.Params.BaseProposerReward = sdkmath.LegacyNewDecWithPrec(1, 2) + oldDistrState.Params.BonusProposerReward = sdkmath.LegacyNewDecWithPrec(4, 2) migrated := v3.MigrateJSON(oldDistrState) require.Equal(t, migrated, distrGenState) diff --git a/x/distribution/migrations/v3/migrate.go b/x/distribution/migrations/v3/migrate.go index 9bb1a67a3756..5c6a8dd4458d 100644 --- a/x/distribution/migrations/v3/migrate.go +++ b/x/distribution/migrations/v3/migrate.go @@ -3,6 +3,8 @@ package v3 import ( storetypes "cosmossdk.io/store/types" + sdkmath "cosmossdk.io/math" + "github.com/cosmos/cosmos-sdk/codec" sdk "github.com/cosmos/cosmos-sdk/types" "github.com/cosmos/cosmos-sdk/x/distribution/exported" @@ -25,8 +27,8 @@ func MigrateStore(ctx sdk.Context, storeKey storetypes.StoreKey, legacySubspace legacySubspace.GetParamSet(ctx, &currParams) // reset unused params - currParams.BaseProposerReward = sdk.ZeroDec() - currParams.BonusProposerReward = sdk.ZeroDec() + currParams.BaseProposerReward = sdkmath.LegacyZeroDec() + currParams.BonusProposerReward = sdkmath.LegacyZeroDec() if err := currParams.ValidateBasic(); err != nil { return err diff --git a/x/distribution/module.go b/x/distribution/module.go index 11cebd12971c..45bdb93f24f9 100644 --- a/x/distribution/module.go +++ b/x/distribution/module.go @@ -10,6 +10,7 @@ import ( "github.com/spf13/cobra" modulev1 "cosmossdk.io/api/cosmos/distribution/module/v1" + "cosmossdk.io/core/address" "cosmossdk.io/core/appmodule" "cosmossdk.io/depinject" @@ -42,6 +43,7 @@ var ( // AppModuleBasic defines the basic application module used by the distribution module. type AppModuleBasic struct { cdc codec.Codec + ac address.Codec } // Name returns the distribution module's name. @@ -78,17 +80,17 @@ func (AppModuleBasic) RegisterGRPCGatewayRoutes(clientCtx sdkclient.Context, mux } // GetTxCmd returns the root tx command for the distribution module. -func (AppModuleBasic) GetTxCmd() *cobra.Command { - return cli.NewTxCmd() +func (ab AppModuleBasic) GetTxCmd() *cobra.Command { + return cli.NewTxCmd(ab.ac) } // GetQueryCmd returns the root query command for the distribution module. -func (AppModuleBasic) GetQueryCmd() *cobra.Command { - return cli.GetQueryCmd() +func (ab AppModuleBasic) GetQueryCmd() *cobra.Command { + return cli.GetQueryCmd(ab.ac) } // RegisterInterfaces implements InterfaceModule -func (b AppModuleBasic) RegisterInterfaces(registry cdctypes.InterfaceRegistry) { +func (AppModuleBasic) RegisterInterfaces(registry cdctypes.InterfaceRegistry) { types.RegisterInterfaces(registry) } @@ -111,7 +113,7 @@ func NewAppModule( bankKeeper types.BankKeeper, stakingKeeper types.StakingKeeper, ss exported.Subspace, ) AppModule { return AppModule{ - AppModuleBasic: AppModuleBasic{cdc: cdc}, + AppModuleBasic: AppModuleBasic{cdc: cdc, ac: accountKeeper}, keeper: keeper, accountKeeper: accountKeeper, bankKeeper: bankKeeper, @@ -201,7 +203,8 @@ func (am AppModule) RegisterStoreDecoder(sdr simtypes.StoreDecoderRegistry) { // WeightedOperations returns the all the gov module operations with their respective weights. func (am AppModule) WeightedOperations(simState module.SimulationState) []simtypes.WeightedOperation { return simulation.WeightedOperations( - simState.AppParams, simState.Cdc, am.accountKeeper, am.bankKeeper, am.keeper, am.stakingKeeper, + simState.AppParams, simState.Cdc, simState.TxConfig, + am.accountKeeper, am.bankKeeper, am.keeper, am.stakingKeeper, ) } @@ -215,7 +218,7 @@ func init() { ) } -type DistrInputs struct { +type ModuleInputs struct { depinject.In Config *modulev1.Module @@ -230,7 +233,7 @@ type DistrInputs struct { LegacySubspace exported.Subspace } -type DistrOutputs struct { +type ModuleOutputs struct { depinject.Out DistrKeeper keeper.Keeper @@ -238,7 +241,7 @@ type DistrOutputs struct { Hooks staking.StakingHooksWrapper } -func ProvideModule(in DistrInputs) DistrOutputs { +func ProvideModule(in ModuleInputs) ModuleOutputs { feeCollectorName := in.Config.FeeCollectorName if feeCollectorName == "" { feeCollectorName = authtypes.FeeCollectorName @@ -262,7 +265,7 @@ func ProvideModule(in DistrInputs) DistrOutputs { m := NewAppModule(in.Cdc, k, in.AccountKeeper, in.BankKeeper, in.StakingKeeper, in.LegacySubspace) - return DistrOutputs{ + return ModuleOutputs{ DistrKeeper: k, Module: m, Hooks: staking.StakingHooksWrapper{StakingHooks: k.Hooks()}, diff --git a/x/distribution/simulation/genesis.go b/x/distribution/simulation/genesis.go index 5607f133beb4..fd0be5a9047b 100644 --- a/x/distribution/simulation/genesis.go +++ b/x/distribution/simulation/genesis.go @@ -6,7 +6,6 @@ import ( "math/rand" "cosmossdk.io/math" - sdk "github.com/cosmos/cosmos-sdk/types" "github.com/cosmos/cosmos-sdk/types/module" "github.com/cosmos/cosmos-sdk/x/distribution/types" ) @@ -19,7 +18,7 @@ const ( // GenCommunityTax randomized CommunityTax func GenCommunityTax(r *rand.Rand) math.LegacyDec { - return sdk.NewDecWithPrec(1, 2).Add(sdk.NewDecWithPrec(int64(r.Intn(30)), 2)) + return math.LegacyNewDecWithPrec(1, 2).Add(math.LegacyNewDecWithPrec(int64(r.Intn(30)), 2)) } // GenWithdrawEnabled returns a randomized WithdrawEnabled parameter. @@ -29,7 +28,7 @@ func GenWithdrawEnabled(r *rand.Rand) bool { // RandomizedGenState generates a random GenesisState for distribution func RandomizedGenState(simState *module.SimulationState) { - var communityTax sdk.Dec + var communityTax math.LegacyDec simState.AppParams.GetOrGenerate( simState.Cdc, CommunityTax, &communityTax, simState.Rand, func(r *rand.Rand) { communityTax = GenCommunityTax(r) }, diff --git a/x/distribution/simulation/genesis_test.go b/x/distribution/simulation/genesis_test.go index 14d4a067807f..1531577610ba 100644 --- a/x/distribution/simulation/genesis_test.go +++ b/x/distribution/simulation/genesis_test.go @@ -10,7 +10,6 @@ import ( sdkmath "cosmossdk.io/math" "github.com/cosmos/cosmos-sdk/codec" codectypes "github.com/cosmos/cosmos-sdk/codec/types" - sdk "github.com/cosmos/cosmos-sdk/types" "github.com/cosmos/cosmos-sdk/types/module" simtypes "github.com/cosmos/cosmos-sdk/types/simulation" "github.com/cosmos/cosmos-sdk/x/distribution/simulation" @@ -40,10 +39,8 @@ func TestRandomizedGenState(t *testing.T) { var distrGenesis types.GenesisState simState.Cdc.MustUnmarshalJSON(simState.GenState[types.ModuleName], &distrGenesis) - dec1, _ := sdk.NewDecFromStr("0.210000000000000000") + dec1, _ := sdkmath.LegacyNewDecFromStr("0.210000000000000000") - require.Equal(t, sdk.ZeroDec(), distrGenesis.Params.BaseProposerReward) //nolint:staticcheck - require.Equal(t, sdk.ZeroDec(), distrGenesis.Params.BonusProposerReward) //nolint:staticcheck require.Equal(t, dec1, distrGenesis.Params.CommunityTax) require.Equal(t, true, distrGenesis.Params.WithdrawAddrEnabled) require.Len(t, distrGenesis.DelegatorStartingInfos, 0) diff --git a/x/distribution/simulation/operations.go b/x/distribution/simulation/operations.go index 40165a31798a..f39203070e87 100644 --- a/x/distribution/simulation/operations.go +++ b/x/distribution/simulation/operations.go @@ -7,11 +7,9 @@ import ( "github.com/cosmos/cosmos-sdk/baseapp" "github.com/cosmos/cosmos-sdk/client" "github.com/cosmos/cosmos-sdk/codec" - codectypes "github.com/cosmos/cosmos-sdk/codec/types" "github.com/cosmos/cosmos-sdk/testutil" sdk "github.com/cosmos/cosmos-sdk/types" simtypes "github.com/cosmos/cosmos-sdk/types/simulation" - "github.com/cosmos/cosmos-sdk/x/auth/tx" "github.com/cosmos/cosmos-sdk/x/distribution/keeper" "github.com/cosmos/cosmos-sdk/x/distribution/types" "github.com/cosmos/cosmos-sdk/x/simulation" @@ -19,10 +17,10 @@ import ( // Simulation operation weights constants const ( - OpWeightMsgSetWithdrawAddress = "op_weight_msg_set_withdraw_address" //nolint:gosec - OpWeightMsgWithdrawDelegationReward = "op_weight_msg_withdraw_delegation_reward" //nolint:gosec - OpWeightMsgWithdrawValidatorCommission = "op_weight_msg_withdraw_validator_commission" //nolint:gosec - OpWeightMsgFundCommunityPool = "op_weight_msg_fund_community_pool" //nolint:gosec + OpWeightMsgSetWithdrawAddress = "op_weight_msg_set_withdraw_address" + OpWeightMsgWithdrawDelegationReward = "op_weight_msg_withdraw_delegation_reward" + OpWeightMsgWithdrawValidatorCommission = "op_weight_msg_withdraw_validator_commission" + OpWeightMsgFundCommunityPool = "op_weight_msg_fund_community_pool" DefaultWeightMsgSetWithdrawAddress int = 50 DefaultWeightMsgWithdrawDelegationReward int = 50 @@ -31,7 +29,15 @@ const ( ) // WeightedOperations returns all the operations from the module with their respective weights -func WeightedOperations(appParams simtypes.AppParams, cdc codec.JSONCodec, ak types.AccountKeeper, bk types.BankKeeper, k keeper.Keeper, sk types.StakingKeeper) simulation.WeightedOperations { +func WeightedOperations( + appParams simtypes.AppParams, + cdc codec.JSONCodec, + txConfig client.TxConfig, + ak types.AccountKeeper, + bk types.BankKeeper, + k keeper.Keeper, + sk types.StakingKeeper, +) simulation.WeightedOperations { var weightMsgSetWithdrawAddress int appParams.GetOrGenerate(cdc, OpWeightMsgSetWithdrawAddress, &weightMsgSetWithdrawAddress, nil, func(_ *rand.Rand) { @@ -60,9 +66,6 @@ func WeightedOperations(appParams simtypes.AppParams, cdc codec.JSONCodec, ak ty }, ) - interfaceRegistry := codectypes.NewInterfaceRegistry() - txConfig := tx.NewTxConfig(codec.NewProtoCodec(interfaceRegistry), tx.DefaultSignModes) - return simulation.WeightedOperations{ simulation.NewWeightedOperation( weightMsgSetWithdrawAddress, diff --git a/x/distribution/simulation/operations_test.go b/x/distribution/simulation/operations_test.go index d416a27b817d..9a5ed8b246c3 100644 --- a/x/distribution/simulation/operations_test.go +++ b/x/distribution/simulation/operations_test.go @@ -30,7 +30,7 @@ import ( func (suite *SimTestSuite) TestWeightedOperations() { appParams := make(simtypes.AppParams) - weightesOps := simulation.WeightedOperations(appParams, suite.cdc, suite.accountKeeper, + weightedOps := simulation.WeightedOperations(appParams, suite.cdc, suite.txConfig, suite.accountKeeper, suite.bankKeeper, suite.distrKeeper, suite.stakingKeeper) // setup 3 accounts @@ -49,7 +49,7 @@ func (suite *SimTestSuite) TestWeightedOperations() { {simulation.DefaultWeightMsgFundCommunityPool, types.ModuleName, sdk.MsgTypeURL(&types.MsgFundCommunityPool{})}, } - for i, w := range weightesOps { + for i, w := range weightedOps { operationMsg, _, err := w.Op()(r, suite.app.BaseApp, suite.ctx, accs, "") suite.Require().NoError(err) @@ -149,8 +149,8 @@ func (suite *SimTestSuite) testSimulateMsgWithdrawValidatorCommission(tokenName // set module account coins distrAcc := suite.distrKeeper.GetDistributionAccount(suite.ctx) suite.Require().NoError(banktestutil.FundModuleAccount(suite.bankKeeper, suite.ctx, distrAcc.GetName(), sdk.NewCoins( - sdk.NewCoin(tokenName, sdk.NewInt(10)), - sdk.NewCoin("stake", sdk.NewInt(5)), + sdk.NewCoin(tokenName, math.NewInt(10)), + sdk.NewCoin("stake", math.NewInt(5)), ))) suite.accountKeeper.SetModuleAccount(suite.ctx, distrAcc) @@ -284,7 +284,7 @@ func (suite *SimTestSuite) getTestingValidator(accounts []simtypes.Account, comm validator, err = validator.SetInitialCommission(commission) require.NoError(err) validator.DelegatorShares = math.LegacyNewDec(100) - validator.Tokens = sdk.NewInt(1000000) + validator.Tokens = math.NewInt(1000000) suite.stakingKeeper.SetValidator(suite.ctx, validator) diff --git a/x/distribution/simulation/proposals.go b/x/distribution/simulation/proposals.go index 6330691afc26..bb5488aebd86 100644 --- a/x/distribution/simulation/proposals.go +++ b/x/distribution/simulation/proposals.go @@ -3,6 +3,8 @@ package simulation import ( "math/rand" + sdkmath "cosmossdk.io/math" + sdk "github.com/cosmos/cosmos-sdk/types" "github.com/cosmos/cosmos-sdk/types/address" simtypes "github.com/cosmos/cosmos-sdk/types/simulation" @@ -14,7 +16,7 @@ import ( const ( DefaultWeightMsgUpdateParams int = 50 - OpWeightMsgUpdateParams = "op_weight_msg_update_params" //nolint:gosec + OpWeightMsgUpdateParams = "op_weight_msg_update_params" ) // ProposalMsgs defines the module weighted proposals' contents @@ -34,7 +36,7 @@ func SimulateMsgUpdateParams(r *rand.Rand, _ sdk.Context, _ []simtypes.Account) var authority sdk.AccAddress = address.Module("gov") params := types.DefaultParams() - params.CommunityTax = simtypes.RandomDecAmount(r, sdk.NewDec(1)) + params.CommunityTax = simtypes.RandomDecAmount(r, sdkmath.LegacyNewDec(1)) params.WithdrawAddrEnabled = r.Intn(2) == 0 return &types.MsgUpdateParams{ diff --git a/x/distribution/simulation/proposals_test.go b/x/distribution/simulation/proposals_test.go index fdb59301f622..578eb66fd2b4 100644 --- a/x/distribution/simulation/proposals_test.go +++ b/x/distribution/simulation/proposals_test.go @@ -4,6 +4,7 @@ import ( "math/rand" "testing" + sdkmath "cosmossdk.io/math" cmtproto "github.com/cometbft/cometbft/proto/tendermint/types" "gotest.tools/v3/assert" @@ -37,6 +38,6 @@ func TestProposalMsgs(t *testing.T) { assert.Assert(t, ok) assert.Equal(t, sdk.AccAddress(address.Module("gov")).String(), msgUpdateParams.Authority) - assert.DeepEqual(t, sdk.NewDec(0), msgUpdateParams.Params.CommunityTax) + assert.DeepEqual(t, sdkmath.LegacyNewDec(0), msgUpdateParams.Params.CommunityTax) assert.Equal(t, true, msgUpdateParams.Params.WithdrawAddrEnabled) } diff --git a/x/distribution/testutil/expected_keepers_mocks.go b/x/distribution/testutil/expected_keepers_mocks.go index ad1e01864a56..31471ca6e769 100644 --- a/x/distribution/testutil/expected_keepers_mocks.go +++ b/x/distribution/testutil/expected_keepers_mocks.go @@ -5,6 +5,7 @@ package testutil import ( + context "context" reflect "reflect" types "github.com/cosmos/cosmos-sdk/types" @@ -35,8 +36,23 @@ func (m *MockAccountKeeper) EXPECT() *MockAccountKeeperMockRecorder { return m.recorder } +// BytesToString mocks base method. +func (m *MockAccountKeeper) BytesToString(bz []byte) (string, error) { + m.ctrl.T.Helper() + ret := m.ctrl.Call(m, "BytesToString", bz) + ret0, _ := ret[0].(string) + ret1, _ := ret[1].(error) + return ret0, ret1 +} + +// BytesToString indicates an expected call of BytesToString. +func (mr *MockAccountKeeperMockRecorder) BytesToString(bz interface{}) *gomock.Call { + mr.mock.ctrl.T.Helper() + return mr.mock.ctrl.RecordCallWithMethodType(mr.mock, "BytesToString", reflect.TypeOf((*MockAccountKeeper)(nil).BytesToString), bz) +} + // GetAccount mocks base method. -func (m *MockAccountKeeper) GetAccount(ctx types.Context, addr types.AccAddress) types.AccountI { +func (m *MockAccountKeeper) GetAccount(ctx context.Context, addr types.AccAddress) types.AccountI { m.ctrl.T.Helper() ret := m.ctrl.Call(m, "GetAccount", ctx, addr) ret0, _ := ret[0].(types.AccountI) @@ -50,7 +66,7 @@ func (mr *MockAccountKeeperMockRecorder) GetAccount(ctx, addr interface{}) *gomo } // GetModuleAccount mocks base method. -func (m *MockAccountKeeper) GetModuleAccount(ctx types.Context, name string) types.ModuleAccountI { +func (m *MockAccountKeeper) GetModuleAccount(ctx context.Context, name string) types.ModuleAccountI { m.ctrl.T.Helper() ret := m.ctrl.Call(m, "GetModuleAccount", ctx, name) ret0, _ := ret[0].(types.ModuleAccountI) @@ -78,7 +94,7 @@ func (mr *MockAccountKeeperMockRecorder) GetModuleAddress(name interface{}) *gom } // SetModuleAccount mocks base method. -func (m *MockAccountKeeper) SetModuleAccount(arg0 types.Context, arg1 types.ModuleAccountI) { +func (m *MockAccountKeeper) SetModuleAccount(arg0 context.Context, arg1 types.ModuleAccountI) { m.ctrl.T.Helper() m.ctrl.Call(m, "SetModuleAccount", arg0, arg1) } @@ -89,6 +105,21 @@ func (mr *MockAccountKeeperMockRecorder) SetModuleAccount(arg0, arg1 interface{} return mr.mock.ctrl.RecordCallWithMethodType(mr.mock, "SetModuleAccount", reflect.TypeOf((*MockAccountKeeper)(nil).SetModuleAccount), arg0, arg1) } +// StringToBytes mocks base method. +func (m *MockAccountKeeper) StringToBytes(text string) ([]byte, error) { + m.ctrl.T.Helper() + ret := m.ctrl.Call(m, "StringToBytes", text) + ret0, _ := ret[0].([]byte) + ret1, _ := ret[1].(error) + return ret0, ret1 +} + +// StringToBytes indicates an expected call of StringToBytes. +func (mr *MockAccountKeeperMockRecorder) StringToBytes(text interface{}) *gomock.Call { + mr.mock.ctrl.T.Helper() + return mr.mock.ctrl.RecordCallWithMethodType(mr.mock, "StringToBytes", reflect.TypeOf((*MockAccountKeeper)(nil).StringToBytes), text) +} + // MockBankKeeper is a mock of BankKeeper interface. type MockBankKeeper struct { ctrl *gomock.Controller diff --git a/x/distribution/testutil/staking_helper.go b/x/distribution/testutil/staking_helper.go index 925bd8bad875..a568898aabf3 100644 --- a/x/distribution/testutil/staking_helper.go +++ b/x/distribution/testutil/staking_helper.go @@ -4,6 +4,7 @@ import ( "fmt" "cosmossdk.io/math" + cryptotypes "github.com/cosmos/cosmos-sdk/crypto/types" sdk "github.com/cosmos/cosmos-sdk/types" "github.com/cosmos/cosmos-sdk/x/distribution/keeper" @@ -12,7 +13,7 @@ import ( func CreateValidator(pk cryptotypes.PubKey, stake math.Int) (stakingtypes.Validator, error) { valConsAddr := sdk.GetConsAddress(pk) - val, err := stakingtypes.NewValidator(sdk.ValAddress(valConsAddr), pk, stakingtypes.Description{}) + val, err := stakingtypes.NewValidator(sdk.ValAddress(valConsAddr), pk, stakingtypes.Description{Moniker: "TestValidator"}) val.Tokens = stake val.DelegatorShares = math.LegacyNewDecFromInt(val.Tokens) return val, err @@ -45,7 +46,7 @@ func SlashValidator( consAddr sdk.ConsAddress, infractionHeight int64, power int64, - slashFactor sdk.Dec, + slashFactor math.LegacyDec, validator *stakingtypes.Validator, distrKeeper *keeper.Keeper, ) math.Int { @@ -67,16 +68,16 @@ func SlashValidator( panic("we can't test any other case here") } - slashAmountDec := sdk.NewDecFromInt(validator.Tokens).Mul(sdk.NewDecWithPrec(5, 1)) + slashAmountDec := math.LegacyNewDecFromInt(validator.Tokens).Mul(math.LegacyNewDecWithPrec(5, 1)) slashAmount := slashAmountDec.TruncateInt() // cannot decrease balance below zero - tokensToBurn := sdk.MinInt(slashAmount, validator.Tokens) - tokensToBurn = sdk.MaxInt(tokensToBurn, math.ZeroInt()) // defensive. + tokensToBurn := math.MinInt(slashAmount, validator.Tokens) + tokensToBurn = math.MaxInt(tokensToBurn, math.ZeroInt()) // defensive. // we need to calculate the *effective* slash fraction for distribution if validator.Tokens.IsPositive() { - effectiveFraction := sdk.NewDecFromInt(tokensToBurn).QuoRoundUp(sdk.NewDecFromInt(validator.Tokens)) + effectiveFraction := math.LegacyNewDecFromInt(tokensToBurn).QuoRoundUp(math.LegacyNewDecFromInt(validator.Tokens)) // possible if power has changed if effectiveFraction.GT(math.LegacyOneDec()) { effectiveFraction = math.LegacyOneDec() @@ -102,7 +103,7 @@ func Delegate( amount math.Int, delegation *stakingtypes.Delegation, ) ( - newShares sdk.Dec, + newShares math.LegacyDec, updatedDel stakingtypes.Delegation, err error, ) { diff --git a/x/distribution/types/common_test.go b/x/distribution/types/common_test.go deleted file mode 100644 index fd74434eee98..000000000000 --- a/x/distribution/types/common_test.go +++ /dev/null @@ -1,18 +0,0 @@ -package types - -import ( - "github.com/cosmos/cosmos-sdk/crypto/keys/ed25519" - sdk "github.com/cosmos/cosmos-sdk/types" -) - -var ( - delPk1 = ed25519.GenPrivKey().PubKey() - delPk2 = ed25519.GenPrivKey().PubKey() - delAddr1 = sdk.AccAddress(delPk1.Address()) - delAddr2 = sdk.AccAddress(delPk2.Address()) - emptyDelAddr sdk.AccAddress - - valPk1 = ed25519.GenPrivKey().PubKey() - valAddr1 = sdk.ValAddress(valPk1.Address()) - emptyValAddr sdk.ValAddress -) diff --git a/x/distribution/types/delegator.go b/x/distribution/types/delegator.go index 850878660780..aa86ee8dafac 100644 --- a/x/distribution/types/delegator.go +++ b/x/distribution/types/delegator.go @@ -1,11 +1,9 @@ package types -import ( - sdk "github.com/cosmos/cosmos-sdk/types" -) +import sdkmath "cosmossdk.io/math" // create a new DelegatorStartingInfo -func NewDelegatorStartingInfo(previousPeriod uint64, stake sdk.Dec, height uint64) DelegatorStartingInfo { +func NewDelegatorStartingInfo(previousPeriod uint64, stake sdkmath.LegacyDec, height uint64) DelegatorStartingInfo { return DelegatorStartingInfo{ PreviousPeriod: previousPeriod, Stake: stake, diff --git a/x/distribution/types/expected_keepers.go b/x/distribution/types/expected_keepers.go index 3f53b4a550cf..8556d6e3ff40 100644 --- a/x/distribution/types/expected_keepers.go +++ b/x/distribution/types/expected_keepers.go @@ -1,19 +1,24 @@ package types import ( + context "context" + + "cosmossdk.io/core/address" sdk "github.com/cosmos/cosmos-sdk/types" stakingtypes "github.com/cosmos/cosmos-sdk/x/staking/types" ) // AccountKeeper defines the expected account keeper used for simulations (noalias) type AccountKeeper interface { - GetAccount(ctx sdk.Context, addr sdk.AccAddress) sdk.AccountI + address.Codec + + GetAccount(ctx context.Context, addr sdk.AccAddress) sdk.AccountI GetModuleAddress(name string) sdk.AccAddress - GetModuleAccount(ctx sdk.Context, name string) sdk.ModuleAccountI + GetModuleAccount(ctx context.Context, name string) sdk.ModuleAccountI // TODO remove with genesis 2-phases refactor https://github.com/cosmos/cosmos-sdk/issues/2862 - SetModuleAccount(sdk.Context, sdk.ModuleAccountI) + SetModuleAccount(context.Context, sdk.ModuleAccountI) } // BankKeeper defines the expected interface needed to retrieve account balances. @@ -22,7 +27,7 @@ type BankKeeper interface { SpendableCoins(ctx sdk.Context, addr sdk.AccAddress) sdk.Coins - SendCoinsFromModuleToModule(ctx sdk.Context, senderModule string, recipientModule string, amt sdk.Coins) error + SendCoinsFromModuleToModule(ctx sdk.Context, senderModule, recipientModule string, amt sdk.Coins) error SendCoinsFromModuleToAccount(ctx sdk.Context, senderModule string, recipientAddr sdk.AccAddress, amt sdk.Coins) error SendCoinsFromAccountToModule(ctx sdk.Context, senderAddr sdk.AccAddress, recipientModule string, amt sdk.Coins) error diff --git a/x/distribution/types/genesis.go b/x/distribution/types/genesis.go index 9ceb0737a13e..0affa8c34736 100644 --- a/x/distribution/types/genesis.go +++ b/x/distribution/types/genesis.go @@ -4,7 +4,6 @@ import ( sdk "github.com/cosmos/cosmos-sdk/types" ) -//nolint:interfacer func NewGenesisState( params Params, fp FeePool, dwis []DelegatorWithdrawInfo, pp sdk.ConsAddress, r []ValidatorOutstandingRewardsRecord, acc []ValidatorAccumulatedCommissionRecord, historical []ValidatorHistoricalRewardsRecord, diff --git a/x/distribution/types/msg.go b/x/distribution/types/msg.go index 9e5038664b32..0e6337769f34 100644 --- a/x/distribution/types/msg.go +++ b/x/distribution/types/msg.go @@ -1,12 +1,7 @@ package types import ( - "errors" - - errorsmod "cosmossdk.io/errors" - sdk "github.com/cosmos/cosmos-sdk/types" - sdkerrors "github.com/cosmos/cosmos-sdk/types/errors" "github.com/cosmos/cosmos-sdk/x/auth/migrations/legacytx" ) @@ -46,18 +41,6 @@ func (msg MsgSetWithdrawAddress) GetSignBytes() []byte { return sdk.MustSortJSON(bz) } -// quick validity check -func (msg MsgSetWithdrawAddress) ValidateBasic() error { - if _, err := sdk.AccAddressFromBech32(msg.DelegatorAddress); err != nil { - return sdkerrors.ErrInvalidAddress.Wrapf("invalid delegator address: %s", err) - } - if _, err := sdk.AccAddressFromBech32(msg.WithdrawAddress); err != nil { - return sdkerrors.ErrInvalidAddress.Wrapf("invalid withdraw address: %s", err) - } - - return nil -} - func NewMsgWithdrawDelegatorReward(delAddr sdk.AccAddress, valAddr sdk.ValAddress) *MsgWithdrawDelegatorReward { return &MsgWithdrawDelegatorReward{ DelegatorAddress: delAddr.String(), @@ -77,17 +60,6 @@ func (msg MsgWithdrawDelegatorReward) GetSignBytes() []byte { return sdk.MustSortJSON(bz) } -// quick validity check -func (msg MsgWithdrawDelegatorReward) ValidateBasic() error { - if _, err := sdk.AccAddressFromBech32(msg.DelegatorAddress); err != nil { - return sdkerrors.ErrInvalidAddress.Wrapf("invalid delegator address: %s", err) - } - if _, err := sdk.ValAddressFromBech32(msg.ValidatorAddress); err != nil { - return sdkerrors.ErrInvalidAddress.Wrapf("invalid validator address: %s", err) - } - return nil -} - func NewMsgWithdrawValidatorCommission(valAddr sdk.ValAddress) *MsgWithdrawValidatorCommission { return &MsgWithdrawValidatorCommission{ ValidatorAddress: valAddr.String(), @@ -106,14 +78,6 @@ func (msg MsgWithdrawValidatorCommission) GetSignBytes() []byte { return sdk.MustSortJSON(bz) } -// quick validity check -func (msg MsgWithdrawValidatorCommission) ValidateBasic() error { - if _, err := sdk.ValAddressFromBech32(msg.ValidatorAddress); err != nil { - return sdkerrors.ErrInvalidAddress.Wrapf("invalid validator address: %s", err) - } - return nil -} - // NewMsgFundCommunityPool returns a new MsgFundCommunityPool with a sender and // a funding amount. func NewMsgFundCommunityPool(amount sdk.Coins, depositor sdk.AccAddress) *MsgFundCommunityPool { @@ -137,17 +101,6 @@ func (msg MsgFundCommunityPool) GetSignBytes() []byte { return sdk.MustSortJSON(bz) } -// ValidateBasic performs basic MsgFundCommunityPool message validation. -func (msg MsgFundCommunityPool) ValidateBasic() error { - if !msg.Amount.IsValid() { - return errorsmod.Wrap(sdkerrors.ErrInvalidCoins, msg.Amount.String()) - } - if _, err := sdk.AccAddressFromBech32(msg.Depositor); err != nil { - return sdkerrors.ErrInvalidAddress.Wrapf("invalid depositor address: %s", err) - } - return nil -} - // GetSigners returns the signer addresses that are expected to sign the result // of GetSignBytes. func (msg MsgUpdateParams) GetSigners() []sdk.AccAddress { @@ -162,20 +115,6 @@ func (msg MsgUpdateParams) GetSignBytes() []byte { return sdk.MustSortJSON(bz) } -// ValidateBasic performs basic MsgUpdateParams message validation. -func (msg MsgUpdateParams) ValidateBasic() error { - if (!msg.Params.BaseProposerReward.IsNil() && !msg.Params.BaseProposerReward.IsZero()) || - (!msg.Params.BonusProposerReward.IsNil() && !msg.Params.BonusProposerReward.IsZero()) { - return errors.New("base and bonus proposer reward are deprecated fields and should not be used") - } - - if _, err := sdk.AccAddressFromBech32(msg.Authority); err != nil { - return sdkerrors.ErrInvalidAddress.Wrapf("invalid authority address: %s", err) - } - - return msg.Params.ValidateBasic() -} - // GetSigners returns the signer addresses that are expected to sign the result // of GetSignBytes, which is the authority. func (msg MsgCommunityPoolSpend) GetSigners() []sdk.AccAddress { @@ -190,30 +129,21 @@ func (msg MsgCommunityPoolSpend) GetSignBytes() []byte { return sdk.MustSortJSON(bz) } -// ValidateBasic performs basic MsgCommunityPoolSpend message validation. -func (msg MsgCommunityPoolSpend) ValidateBasic() error { - if _, err := sdk.AccAddressFromBech32(msg.Authority); err != nil { - return sdkerrors.ErrInvalidAddress.Wrapf("invalid authority address: %s", err) - } - - return msg.Amount.Validate() -} - // NewMsgDepositValidatorRewardsPool returns a new MsgDepositValidatorRewardsPool -// with a sender and a funding amount. +// with a depositor and a funding amount. func NewMsgDepositValidatorRewardsPool(depositor sdk.AccAddress, valAddr sdk.ValAddress, amount sdk.Coins) *MsgDepositValidatorRewardsPool { return &MsgDepositValidatorRewardsPool{ Amount: amount, - Authority: depositor.String(), + Depositor: depositor.String(), ValidatorAddress: valAddr.String(), } } // GetSigners returns the signer addresses that are expected to sign the result -// of GetSignBytes, which is the authority. +// of GetSignBytes, which is the depositor. func (msg MsgDepositValidatorRewardsPool) GetSigners() []sdk.AccAddress { - authority, _ := sdk.AccAddressFromBech32(msg.Authority) - return []sdk.AccAddress{authority} + depositor, _ := sdk.AccAddressFromBech32(msg.Depositor) + return []sdk.AccAddress{depositor} } // GetSignBytes returns the raw bytes for a MsgDepositValidatorRewardsPool message @@ -222,12 +152,3 @@ func (msg MsgDepositValidatorRewardsPool) GetSignBytes() []byte { bz := ModuleCdc.MustMarshalJSON(&msg) return sdk.MustSortJSON(bz) } - -// ValidateBasic performs basic MsgDepositValidatorRewardsPool message validation. -func (msg MsgDepositValidatorRewardsPool) ValidateBasic() error { - if _, err := sdk.AccAddressFromBech32(msg.Authority); err != nil { - return sdkerrors.ErrInvalidAddress.Wrapf("invalid authority address: %s", err) - } - - return msg.Amount.Validate() -} diff --git a/x/distribution/types/msg_test.go b/x/distribution/types/msg_test.go deleted file mode 100644 index 324626178d04..000000000000 --- a/x/distribution/types/msg_test.go +++ /dev/null @@ -1,95 +0,0 @@ -package types - -import ( - "testing" - - "github.com/stretchr/testify/require" - - sdk "github.com/cosmos/cosmos-sdk/types" -) - -// test ValidateBasic for MsgSetWithdrawAddress -func TestMsgSetWithdrawAddress(t *testing.T) { - tests := []struct { - delegatorAddr sdk.AccAddress - withdrawAddr sdk.AccAddress - expectPass bool - }{ - {delAddr1, delAddr2, true}, - {delAddr1, delAddr1, true}, - {emptyDelAddr, delAddr1, false}, - {delAddr1, emptyDelAddr, false}, - {emptyDelAddr, emptyDelAddr, false}, - } - - for i, tc := range tests { - msg := NewMsgSetWithdrawAddress(tc.delegatorAddr, tc.withdrawAddr) - if tc.expectPass { - require.Nil(t, msg.ValidateBasic(), "test index: %v", i) - } else { - require.NotNil(t, msg.ValidateBasic(), "test index: %v", i) - } - } -} - -// test ValidateBasic for MsgWithdrawDelegatorReward -func TestMsgWithdrawDelegatorReward(t *testing.T) { - tests := []struct { - delegatorAddr sdk.AccAddress - validatorAddr sdk.ValAddress - expectPass bool - }{ - {delAddr1, valAddr1, true}, - {emptyDelAddr, valAddr1, false}, - {delAddr1, emptyValAddr, false}, - {emptyDelAddr, emptyValAddr, false}, - } - for i, tc := range tests { - msg := NewMsgWithdrawDelegatorReward(tc.delegatorAddr, tc.validatorAddr) - if tc.expectPass { - require.Nil(t, msg.ValidateBasic(), "test index: %v", i) - } else { - require.NotNil(t, msg.ValidateBasic(), "test index: %v", i) - } - } -} - -// test ValidateBasic for MsgWithdrawValidatorCommission -func TestMsgWithdrawValidatorCommission(t *testing.T) { - tests := []struct { - validatorAddr sdk.ValAddress - expectPass bool - }{ - {valAddr1, true}, - {emptyValAddr, false}, - } - for i, tc := range tests { - msg := NewMsgWithdrawValidatorCommission(tc.validatorAddr) - if tc.expectPass { - require.Nil(t, msg.ValidateBasic(), "test index: %v", i) - } else { - require.NotNil(t, msg.ValidateBasic(), "test index: %v", i) - } - } -} - -// test ValidateBasic for MsgDepositIntoCommunityPool -func TestMsgDepositIntoCommunityPool(t *testing.T) { - tests := []struct { - amount sdk.Coins - depositor sdk.AccAddress - expectPass bool - }{ - {sdk.NewCoins(sdk.NewInt64Coin("uatom", 10000)), sdk.AccAddress{}, false}, - {sdk.Coins{sdk.NewInt64Coin("uatom", 10), sdk.NewInt64Coin("uatom", 10)}, delAddr1, false}, - {sdk.NewCoins(sdk.NewInt64Coin("uatom", 1000)), delAddr1, true}, - } - for i, tc := range tests { - msg := NewMsgFundCommunityPool(tc.amount, tc.depositor) - if tc.expectPass { - require.Nil(t, msg.ValidateBasic(), "test index: %v", i) - } else { - require.NotNil(t, msg.ValidateBasic(), "test index: %v", i) - } - } -} diff --git a/x/distribution/types/params.go b/x/distribution/types/params.go index 6d13892dccee..395be69d7ea8 100644 --- a/x/distribution/types/params.go +++ b/x/distribution/types/params.go @@ -4,16 +4,14 @@ import ( "fmt" "cosmossdk.io/math" - - sdk "github.com/cosmos/cosmos-sdk/types" ) // DefaultParams returns default distribution parameters func DefaultParams() Params { return Params{ - CommunityTax: sdk.NewDecWithPrec(2, 2), // 2% - BaseProposerReward: sdk.ZeroDec(), // deprecated - BonusProposerReward: sdk.ZeroDec(), // deprecated + CommunityTax: math.LegacyNewDecWithPrec(2, 2), // 2% + BaseProposerReward: math.LegacyZeroDec(), // deprecated + BonusProposerReward: math.LegacyZeroDec(), // deprecated WithdrawAddrEnabled: true, } } @@ -30,7 +28,7 @@ func (p Params) ValidateBasic() error { } func validateCommunityTax(i interface{}) error { - v, ok := i.(sdk.Dec) + v, ok := i.(math.LegacyDec) if !ok { return fmt.Errorf("invalid parameter type: %T", i) } diff --git a/x/distribution/types/params_internal_test.go b/x/distribution/types/params_internal_test.go index 2ea34f965e10..ebc43c37b44f 100644 --- a/x/distribution/types/params_internal_test.go +++ b/x/distribution/types/params_internal_test.go @@ -5,8 +5,6 @@ import ( "cosmossdk.io/math" "github.com/stretchr/testify/require" - - sdk "github.com/cosmos/cosmos-sdk/types" ) func Test_validateAuxFuncs(t *testing.T) { @@ -19,7 +17,7 @@ func Test_validateAuxFuncs(t *testing.T) { wantErr bool }{ {"wrong type", args{10.5}, true}, - {"empty sdk.Dec", args{sdk.Dec{}}, true}, + {"empty math.LegacyDec", args{math.LegacyDec{}}, true}, {"negative", args{math.LegacyNewDec(-1)}, true}, {"one dec", args{math.LegacyNewDec(1)}, false}, {"two dec", args{math.LegacyNewDec(2)}, true}, diff --git a/x/distribution/types/params_test.go b/x/distribution/types/params_test.go index e58e8e2065dc..c92e904b1842 100644 --- a/x/distribution/types/params_test.go +++ b/x/distribution/types/params_test.go @@ -3,6 +3,7 @@ package types_test import ( "testing" + sdkmath "cosmossdk.io/math" "github.com/stretchr/testify/require" sdk "github.com/cosmos/cosmos-sdk/types" @@ -13,9 +14,9 @@ func TestParams_ValidateBasic(t *testing.T) { toDec := sdk.MustNewDecFromStr type fields struct { - CommunityTax sdk.Dec - BaseProposerReward sdk.Dec - BonusProposerReward sdk.Dec + CommunityTax sdkmath.LegacyDec + BaseProposerReward sdkmath.LegacyDec + BonusProposerReward sdkmath.LegacyDec WithdrawAddrEnabled bool } tests := []struct { diff --git a/x/distribution/types/querier.go b/x/distribution/types/querier.go index fb9fd4677dca..46f3039c1ce7 100644 --- a/x/distribution/types/querier.go +++ b/x/distribution/types/querier.go @@ -49,7 +49,7 @@ type QueryValidatorSlashesParams struct { } // creates a new instance of QueryValidatorSlashesParams -func NewQueryValidatorSlashesParams(validatorAddr sdk.ValAddress, startingHeight uint64, endingHeight uint64) QueryValidatorSlashesParams { +func NewQueryValidatorSlashesParams(validatorAddr sdk.ValAddress, startingHeight, endingHeight uint64) QueryValidatorSlashesParams { return QueryValidatorSlashesParams{ ValidatorAddress: validatorAddr, StartingHeight: startingHeight, diff --git a/x/distribution/types/query.go b/x/distribution/types/query.go index 38f6c0a35264..e7efccd1e13d 100644 --- a/x/distribution/types/query.go +++ b/x/distribution/types/query.go @@ -32,8 +32,6 @@ func (res QueryDelegatorTotalRewardsResponse) String() string { } // NewDelegationDelegatorReward constructs a DelegationDelegatorReward. -// -//nolint:interfacer func NewDelegationDelegatorReward(valAddr sdk.ValAddress, reward sdk.DecCoins) DelegationDelegatorReward { return DelegationDelegatorReward{ValidatorAddress: valAddr.String(), Reward: reward} } diff --git a/x/distribution/types/tx.pb.go b/x/distribution/types/tx.pb.go index bc421dddc7ab..bf6a4caaf175 100644 --- a/x/distribution/types/tx.pb.go +++ b/x/distribution/types/tx.pb.go @@ -573,7 +573,7 @@ var xxx_messageInfo_MsgCommunityPoolSpendResponse proto.InternalMessageInfo // // Since: cosmos-sdk 0.48 type MsgDepositValidatorRewardsPool struct { - Authority string `protobuf:"bytes,1,opt,name=authority,proto3" json:"authority,omitempty"` + Depositor string `protobuf:"bytes,1,opt,name=depositor,proto3" json:"depositor,omitempty"` ValidatorAddress string `protobuf:"bytes,2,opt,name=validator_address,json=validatorAddress,proto3" json:"validator_address,omitempty"` Amount github_com_cosmos_cosmos_sdk_types.Coins `protobuf:"bytes,3,rep,name=amount,proto3,castrepeated=github.com/cosmos/cosmos-sdk/types.Coins" json:"amount"` } @@ -675,7 +675,7 @@ func init() { } var fileDescriptor_ed4f433d965e58ca = []byte{ - // 912 bytes of a gzipped FileDescriptorProto + // 913 bytes of a gzipped FileDescriptorProto 0x1f, 0x8b, 0x08, 0x00, 0x00, 0x00, 0x00, 0x00, 0x02, 0xff, 0xcc, 0x57, 0xb1, 0x6f, 0xf3, 0x44, 0x14, 0xcf, 0xa5, 0xa2, 0x28, 0xf7, 0x7d, 0xd2, 0xd7, 0x44, 0x45, 0x6d, 0xfd, 0x15, 0xa7, 0x72, 0xa1, 0x44, 0x11, 0xb5, 0x95, 0x80, 0x40, 0x0d, 0x03, 0x90, 0xb4, 0x91, 0x18, 0x22, 0xaa, 0x54, @@ -719,20 +719,21 @@ var fileDescriptor_ed4f433d965e58ca = []byte{ 0x05, 0xaf, 0xc3, 0x9c, 0xa5, 0x76, 0x91, 0x89, 0x54, 0x83, 0xba, 0x17, 0xda, 0x9e, 0x2c, 0x04, 0x9c, 0xb6, 0xf0, 0x1f, 0x3b, 0xad, 0xb6, 0x13, 0x55, 0x70, 0x6b, 0x5a, 0x41, 0x29, 0x56, 0x0b, 0x36, 0x4b, 0xa2, 0x1b, 0xbe, 0x8c, 0xbf, 0x64, 0x9d, 0x8e, 0xb5, 0xeb, 0xda, 0xd0, 0x7f, 0xfe, - 0x6e, 0x4b, 0x25, 0xce, 0x1b, 0xbb, 0xab, 0x9e, 0xf7, 0x33, 0x40, 0x1e, 0x52, 0xf8, 0xb7, 0x42, - 0x4f, 0x35, 0x74, 0x01, 0x2f, 0xc6, 0x5d, 0xc0, 0x44, 0x45, 0xa6, 0x9f, 0x50, 0x72, 0xba, 0x6b, - 0x82, 0xba, 0xde, 0x45, 0x54, 0xff, 0x7a, 0x16, 0x2e, 0xb4, 0x88, 0x56, 0xf8, 0x1c, 0xc0, 0x42, - 0xcc, 0x87, 0x4e, 0x35, 0xf1, 0xf5, 0xc5, 0x7e, 0x2f, 0x70, 0xb5, 0xf9, 0x31, 0x7e, 0xb3, 0xff, - 0x06, 0xc0, 0x95, 0x59, 0x1f, 0x18, 0xaf, 0xa7, 0xe5, 0x9d, 0x01, 0xe4, 0xde, 0xbc, 0x23, 0xd0, - 0x67, 0x75, 0x06, 0xe0, 0xd3, 0xa4, 0xe1, 0xfa, 0xc6, 0x6d, 0x0f, 0x88, 0x01, 0x73, 0x8d, 0x7f, - 0x01, 0xf6, 0x19, 0x7e, 0x0a, 0x60, 0x3e, 0x3a, 0xa6, 0x2a, 0x69, 0xa9, 0x23, 0x10, 0x6e, 0x67, - 0x6e, 0x88, 0xcf, 0xc1, 0x82, 0x8f, 0x43, 0x13, 0xe0, 0xe5, 0xb4, 0x54, 0xc1, 0x68, 0xee, 0xd5, - 0x79, 0xa2, 0xfd, 0x33, 0x6d, 0xdb, 0xc6, 0xf4, 0xe2, 0x54, 0xdb, 0x46, 0x31, 0xe9, 0xb6, 0x9d, - 0xdd, 0xce, 0x1c, 0x83, 0x24, 0xf5, 0xb2, 0x54, 0x83, 0x24, 0x80, 0xd3, 0x0d, 0x72, 0x8b, 0x77, - 0xce, 0x3d, 0xf3, 0x89, 0xdd, 0x62, 0xea, 0xef, 0x5e, 0x8e, 0x78, 0x70, 0x35, 0xe2, 0xc1, 0xf5, - 0x88, 0x07, 0xbf, 0x8f, 0x78, 0xf0, 0xf5, 0x0d, 0x9f, 0xb9, 0xbe, 0xe1, 0x33, 0x3f, 0xdf, 0xf0, - 0x99, 0x0f, 0x2b, 0x89, 0x0d, 0xec, 0x34, 0x3c, 0x34, 0x9d, 0x7e, 0xd6, 0x59, 0x74, 0xfe, 0x55, - 0x7a, 0xe5, 0x9f, 0x00, 0x00, 0x00, 0xff, 0xff, 0x0d, 0xb6, 0xd1, 0xb4, 0x1c, 0x0e, 0x00, 0x00, + 0x6e, 0x4b, 0x25, 0xce, 0x1b, 0x0b, 0x19, 0x1d, 0xdc, 0xda, 0xe8, 0xf7, 0x34, 0x40, 0x1e, 0x52, + 0xf8, 0xb7, 0x66, 0x3f, 0xd5, 0x17, 0xe3, 0x2e, 0x60, 0xa2, 0x22, 0xd3, 0x4f, 0x28, 0x39, 0xdd, + 0x35, 0x41, 0x5d, 0xef, 0x22, 0xaa, 0x7f, 0x3d, 0x0b, 0x17, 0x5a, 0x44, 0x2b, 0x7c, 0x0e, 0x60, + 0x21, 0xe6, 0x43, 0xa7, 0x9a, 0xf8, 0xfa, 0x62, 0xbf, 0x17, 0xb8, 0xda, 0xfc, 0x18, 0xbf, 0xd9, + 0x7f, 0x03, 0xe0, 0xca, 0xac, 0x0f, 0x8c, 0xd7, 0xd3, 0xf2, 0xce, 0x00, 0x72, 0x6f, 0xde, 0x11, + 0xe8, 0xb3, 0x3a, 0x03, 0xf0, 0x69, 0xd2, 0x70, 0x7d, 0xe3, 0xb6, 0x07, 0xc4, 0x80, 0xb9, 0xc6, + 0xbf, 0x00, 0xfb, 0x0c, 0x3f, 0x05, 0x30, 0x1f, 0x1d, 0x53, 0x95, 0xb4, 0xd4, 0x11, 0x08, 0xb7, + 0x33, 0x37, 0xc4, 0xe7, 0x60, 0xc1, 0xc7, 0xa1, 0x09, 0xf0, 0x72, 0x5a, 0xaa, 0x60, 0x34, 0xf7, + 0xea, 0x3c, 0xd1, 0xfe, 0x99, 0xb6, 0x6d, 0x63, 0x7a, 0x71, 0xaa, 0x6d, 0xa3, 0x98, 0x74, 0xdb, + 0xce, 0x6e, 0x67, 0x8e, 0x41, 0x92, 0x7a, 0x59, 0xaa, 0x41, 0x12, 0xc0, 0xe9, 0x06, 0xb9, 0xc5, + 0x3b, 0xe7, 0x9e, 0xf9, 0xc4, 0x6e, 0x31, 0xf5, 0x77, 0x2f, 0x47, 0x3c, 0xb8, 0x1a, 0xf1, 0xe0, + 0x7a, 0xc4, 0x83, 0xdf, 0x47, 0x3c, 0xf8, 0xfa, 0x86, 0xcf, 0x5c, 0xdf, 0xf0, 0x99, 0x9f, 0x6f, + 0xf8, 0xcc, 0x87, 0x95, 0xc4, 0x06, 0x76, 0x1a, 0x1e, 0x9a, 0x4e, 0x3f, 0xeb, 0x2c, 0x3a, 0xff, + 0x2a, 0xbd, 0xf2, 0x4f, 0x00, 0x00, 0x00, 0xff, 0xff, 0xd7, 0x20, 0xf3, 0xc2, 0x1c, 0x0e, 0x00, + 0x00, } func (this *MsgSetWithdrawAddressResponse) Equal(that interface{}) bool { @@ -1747,10 +1748,10 @@ func (m *MsgDepositValidatorRewardsPool) MarshalToSizedBuffer(dAtA []byte) (int, i-- dAtA[i] = 0x12 } - if len(m.Authority) > 0 { - i -= len(m.Authority) - copy(dAtA[i:], m.Authority) - i = encodeVarintTx(dAtA, i, uint64(len(m.Authority))) + if len(m.Depositor) > 0 { + i -= len(m.Depositor) + copy(dAtA[i:], m.Depositor) + i = encodeVarintTx(dAtA, i, uint64(len(m.Depositor))) i-- dAtA[i] = 0xa } @@ -1967,7 +1968,7 @@ func (m *MsgDepositValidatorRewardsPool) Size() (n int) { } var l int _ = l - l = len(m.Authority) + l = len(m.Depositor) if l > 0 { n += 1 + l + sovTx(uint64(l)) } @@ -3087,7 +3088,7 @@ func (m *MsgDepositValidatorRewardsPool) Unmarshal(dAtA []byte) error { switch fieldNum { case 1: if wireType != 2 { - return fmt.Errorf("proto: wrong wireType = %d for field Authority", wireType) + return fmt.Errorf("proto: wrong wireType = %d for field Depositor", wireType) } var stringLen uint64 for shift := uint(0); ; shift += 7 { @@ -3115,7 +3116,7 @@ func (m *MsgDepositValidatorRewardsPool) Unmarshal(dAtA []byte) error { if postIndex > l { return io.ErrUnexpectedEOF } - m.Authority = string(dAtA[iNdEx:postIndex]) + m.Depositor = string(dAtA[iNdEx:postIndex]) iNdEx = postIndex case 2: if wireType != 2 { diff --git a/x/distribution/types/validator.go b/x/distribution/types/validator.go index 56d83172913e..3910387256de 100644 --- a/x/distribution/types/validator.go +++ b/x/distribution/types/validator.go @@ -1,6 +1,8 @@ package types import ( + sdkmath "cosmossdk.io/math" + sdk "github.com/cosmos/cosmos-sdk/types" ) @@ -26,7 +28,7 @@ func InitialValidatorAccumulatedCommission() ValidatorAccumulatedCommission { } // create a new ValidatorSlashEvent -func NewValidatorSlashEvent(validatorPeriod uint64, fraction sdk.Dec) ValidatorSlashEvent { +func NewValidatorSlashEvent(validatorPeriod uint64, fraction sdkmath.LegacyDec) ValidatorSlashEvent { return ValidatorSlashEvent{ ValidatorPeriod: validatorPeriod, Fraction: fraction, diff --git a/x/evidence/CHANGELOG.md b/x/evidence/CHANGELOG.md index c54edf89ad3f..7c37c9aee7d5 100644 --- a/x/evidence/CHANGELOG.md +++ b/x/evidence/CHANGELOG.md @@ -29,3 +29,7 @@ Ref: https://keepachangelog.com/en/1.0.0/ * (x/evidence) [14724](https://github.com/cosmos/cosmos-sdk/pull/14724) The `x/evidence` module is extracted to have a separate go.mod file which allows it be a standalone module. * (keeper) [#15420](https://github.com/cosmos/cosmos-sdk/pull/15420) Move `BeginBlocker` to the keeper folder & make HandleEquivocation private + +### API Breaking Changes + +* (keeper) [#15825](https://github.com/cosmos/cosmos-sdk/pull/15825) Evidence constructor now requires an `address.Codec` (`import "cosmossdk.io/core/address"`) diff --git a/x/evidence/client/cli/query_test.go b/x/evidence/client/cli/query_test.go index 25bc3bd4bce3..5567d0427e5b 100644 --- a/x/evidence/client/cli/query_test.go +++ b/x/evidence/client/cli/query_test.go @@ -1,7 +1,6 @@ package cli_test import ( - "bytes" "context" "fmt" "io" @@ -10,7 +9,6 @@ import ( "cosmossdk.io/x/evidence" "cosmossdk.io/x/evidence/client/cli" - abci "github.com/cometbft/cometbft/abci/types" rpcclientmock "github.com/cometbft/cometbft/rpc/client/mock" "github.com/stretchr/testify/require" @@ -19,7 +17,6 @@ import ( "github.com/cosmos/cosmos-sdk/crypto/keyring" svrcmd "github.com/cosmos/cosmos-sdk/server/cmd" clitestutil "github.com/cosmos/cosmos-sdk/testutil/cli" - sdk "github.com/cosmos/cosmos-sdk/types" testutilmod "github.com/cosmos/cosmos-sdk/types/module/testutil" ) @@ -37,51 +34,25 @@ func TestGetQueryCmd(t *testing.T) { testCases := map[string]struct { args []string - ctxGen func() client.Context - expCmdOutput string expectedOutput string - expectErr bool + expectErrMsg string }{ - "non-existent evidence": { - []string{"DF0C23E8634E480F84B9D5674A7CDC9816466DEC28A3358F73260F68D28D7660"}, - func() client.Context { - bz, _ := encCfg.Codec.Marshal(&sdk.TxResponse{}) - c := clitestutil.NewMockCometRPC(abci.ResponseQuery{ - Value: bz, - }) - return baseCtx.WithClient(c) - }, - "DF0C23E8634E480F84B9D5674A7CDC9816466DEC28A3358F73260F68D28D7660", + "invalid args": { + []string{"foo", "bar"}, "", - true, + "accepts at most 1 arg(s)", }, "all evidence (default pagination)": { []string{}, - func() client.Context { - bz, _ := encCfg.Codec.Marshal(&sdk.TxResponse{}) - c := clitestutil.NewMockCometRPC(abci.ResponseQuery{ - Value: bz, - }) - return baseCtx.WithClient(c) - }, - "", "evidence: []\npagination: null", - false, + "", }, "all evidence (json output)": { []string{ fmt.Sprintf("--%s=json", flags.FlagOutput), }, - func() client.Context { - bz, _ := encCfg.Codec.Marshal(&sdk.TxResponse{}) - c := clitestutil.NewMockCometRPC(abci.ResponseQuery{ - Value: bz, - }) - return baseCtx.WithClient(c) - }, - "", `{"evidence":[],"pagination":null}`, - false, + "", }, } @@ -89,31 +60,21 @@ func TestGetQueryCmd(t *testing.T) { tc := tc t.Run(name, func(t *testing.T) { - var outBuf bytes.Buffer - - clientCtx := tc.ctxGen().WithOutput(&outBuf) ctx := svrcmd.CreateExecuteContext(context.Background()) cmd := cli.GetQueryCmd() - cmd.SetOut(io.Discard) - require.NotNil(t, cmd) - cmd.SetContext(ctx) cmd.SetArgs(tc.args) - - require.NoError(t, client.SetCmdClientContextHandler(clientCtx, cmd)) - - if len(tc.args) != 0 { - require.Contains(t, fmt.Sprint(cmd), tc.expCmdOutput) - } + require.NoError(t, client.SetCmdClientContextHandler(baseCtx, cmd)) out, err := clitestutil.ExecTestCLICmd(baseCtx, cmd, tc.args) - if tc.expectErr { + if tc.expectErrMsg != "" { require.Error(t, err) + require.Contains(t, err.Error(), tc.expectErrMsg) } else { require.NoError(t, err) } - require.Contains(t, fmt.Sprint(cmd), "evidence [] [] Query for evidence by hash or for all (paginated) submitted evidence") + require.Contains(t, strings.TrimSpace(out.String()), tc.expectedOutput) }) } diff --git a/x/evidence/go.mod b/x/evidence/go.mod index a8a20173f532..134f089e57fa 100644 --- a/x/evidence/go.mod +++ b/x/evidence/go.mod @@ -3,30 +3,30 @@ module cosmossdk.io/x/evidence go 1.20 require ( - cosmossdk.io/api v0.3.2-0.20230313131911-55bf5d4efbe7 + cosmossdk.io/api v0.4.0 cosmossdk.io/core v0.6.1 cosmossdk.io/depinject v1.0.0-alpha.3 cosmossdk.io/errors v1.0.0-beta.7 - cosmossdk.io/log v0.1.0 + cosmossdk.io/log v1.0.0 cosmossdk.io/math v1.0.0 - cosmossdk.io/store v0.1.0-alpha.1 - github.com/cometbft/cometbft v0.37.0 + cosmossdk.io/store v0.1.0-alpha.1.0.20230328185921-37ba88872dbc + github.com/cometbft/cometbft v0.37.1-0.20230411132551-3a91d155e664 github.com/cosmos/cosmos-proto v1.0.0-beta.3 - github.com/cosmos/cosmos-sdk v0.46.0-beta2.0.20230321173237-fe77d4bca302 - github.com/cosmos/gogoproto v1.4.6 + github.com/cosmos/cosmos-sdk v0.46.0-beta2.0.20230419074131-aa683247d515 + github.com/cosmos/gogoproto v1.4.8 github.com/golang/mock v1.6.0 github.com/golang/protobuf v1.5.3 github.com/grpc-ecosystem/grpc-gateway v1.16.0 - github.com/spf13/cobra v1.6.1 + github.com/spf13/cobra v1.7.0 github.com/stretchr/testify v1.8.2 - google.golang.org/genproto v0.0.0-20230320184635-7606e756e683 + google.golang.org/genproto v0.0.0-20230410155749-daa745c078e1 google.golang.org/grpc v1.54.0 google.golang.org/protobuf v1.30.0 ) require ( - cosmossdk.io/collections v0.0.0-20230309163709-87da587416ba // indirect - cosmossdk.io/x/tx v0.3.1-0.20230321155358-6522dd1731b5 // indirect + cosmossdk.io/collections v0.1.0 // indirect + cosmossdk.io/x/tx v0.5.1-0.20230407182919-057d2e09bd63 // indirect filippo.io/edwards25519 v1.0.0 // indirect github.com/99designs/go-keychain v0.0.0-20191008050251-8e49817e8af4 // indirect github.com/99designs/keyring v1.2.1 // indirect @@ -35,13 +35,14 @@ require ( github.com/armon/go-metrics v0.4.1 // indirect github.com/beorn7/perks v1.0.1 // indirect github.com/bgentry/speakeasy v0.1.1-0.20220910012023-760eaf8b6816 // indirect + github.com/bits-and-blooms/bitset v1.6.0 // indirect github.com/btcsuite/btcd/btcec/v2 v2.3.2 // indirect github.com/cenkalti/backoff/v4 v4.1.3 // indirect github.com/cespare/xxhash v1.1.0 // indirect github.com/cespare/xxhash/v2 v2.2.0 // indirect github.com/cockroachdb/errors v1.9.1 // indirect github.com/cockroachdb/logtags v0.0.0-20230118201751-21c54148d20b // indirect - github.com/cockroachdb/pebble v0.0.0-20230315223031-1e5ddd10389e // indirect + github.com/cockroachdb/pebble v0.0.0-20230412222916-60cfeb46143b // indirect github.com/cockroachdb/redact v1.1.3 // indirect github.com/cometbft/cometbft-db v0.7.0 // indirect github.com/confio/ics23/go v0.9.0 // indirect @@ -54,7 +55,7 @@ require ( github.com/creachadair/taskgroup v0.4.2 // indirect github.com/danieljoos/wincred v1.1.2 // indirect github.com/davecgh/go-spew v1.1.1 // indirect - github.com/decred/dcrd/dcrec/secp256k1/v4 v4.1.0 // indirect + github.com/decred/dcrd/dcrec/secp256k1/v4 v4.2.0 // indirect github.com/desertbit/timer v0.0.0-20180107155436-c41aec40b27f // indirect github.com/dgraph-io/badger/v2 v2.2007.4 // indirect github.com/dgraph-io/ristretto v0.1.1 // indirect @@ -64,7 +65,7 @@ require ( github.com/fatih/color v1.15.0 // indirect github.com/felixge/httpsnoop v1.0.2 // indirect github.com/fsnotify/fsnotify v1.6.0 // indirect - github.com/getsentry/sentry-go v0.19.0 // indirect + github.com/getsentry/sentry-go v0.20.0 // indirect github.com/go-kit/kit v0.12.0 // indirect github.com/go-kit/log v0.2.1 // indirect github.com/go-logfmt/logfmt v0.6.0 // indirect @@ -94,12 +95,12 @@ require ( github.com/improbable-eng/grpc-web v0.15.0 // indirect github.com/inconshreveable/mousetrap v1.1.0 // indirect github.com/jmhodges/levigo v1.0.0 // indirect - github.com/klauspost/compress v1.16.3 // indirect + github.com/klauspost/compress v1.16.5 // indirect github.com/kr/pretty v0.3.1 // indirect github.com/kr/text v0.2.0 // indirect github.com/lib/pq v1.10.7 // indirect github.com/libp2p/go-buffer-pool v0.1.0 // indirect - github.com/linxGnu/grocksdb v1.7.15 // indirect + github.com/linxGnu/grocksdb v1.7.16 // indirect github.com/magiconair/properties v1.8.7 // indirect github.com/mattn/go-colorable v0.1.13 // indirect github.com/mattn/go-isatty v0.0.18 // indirect @@ -114,14 +115,14 @@ require ( github.com/petermattis/goid v0.0.0-20230317030725-371a4b8eda08 // indirect github.com/pkg/errors v0.9.1 // indirect github.com/pmezard/go-difflib v1.0.0 // indirect - github.com/prometheus/client_golang v1.14.0 // indirect + github.com/prometheus/client_golang v1.15.0 // indirect github.com/prometheus/client_model v0.3.0 // indirect github.com/prometheus/common v0.42.0 // indirect github.com/prometheus/procfs v0.9.0 // indirect github.com/rcrowley/go-metrics v0.0.0-20201227073835-cf1acfcdf475 // indirect - github.com/rogpeppe/go-internal v1.9.0 // indirect + github.com/rogpeppe/go-internal v1.10.0 // indirect github.com/rs/cors v1.8.3 // indirect - github.com/rs/zerolog v1.29.0 // indirect + github.com/rs/zerolog v1.29.1 // indirect github.com/sasha-s/go-deadlock v0.3.1 // indirect github.com/spf13/afero v1.9.3 // indirect github.com/spf13/cast v1.5.0 // indirect @@ -136,13 +137,13 @@ require ( github.com/zondax/hid v0.9.1 // indirect github.com/zondax/ledger-go v0.14.1 // indirect go.etcd.io/bbolt v1.3.6 // indirect - golang.org/x/crypto v0.7.0 // indirect + golang.org/x/crypto v0.8.0 // indirect golang.org/x/exp v0.0.0-20230321023759-10a507213a29 // indirect - golang.org/x/net v0.8.0 // indirect + golang.org/x/net v0.9.0 // indirect golang.org/x/sync v0.1.0 // indirect - golang.org/x/sys v0.6.0 // indirect - golang.org/x/term v0.6.0 // indirect - golang.org/x/text v0.8.0 // indirect + golang.org/x/sys v0.7.0 // indirect + golang.org/x/term v0.7.0 // indirect + golang.org/x/text v0.9.0 // indirect gopkg.in/ini.v1 v1.67.0 // indirect gopkg.in/yaml.v2 v2.4.0 // indirect gopkg.in/yaml.v3 v3.0.1 // indirect diff --git a/x/evidence/go.sum b/x/evidence/go.sum index f043bbb643f9..18bde89021a6 100644 --- a/x/evidence/go.sum +++ b/x/evidence/go.sum @@ -35,24 +35,24 @@ cloud.google.com/go/storage v1.6.0/go.mod h1:N7U0C8pVQ/+NIKOBQyamJIeKQKkZ+mxpohl cloud.google.com/go/storage v1.8.0/go.mod h1:Wv1Oy7z6Yz3DshWRJFhqM/UCfaWIRTdp0RXyy7KQOVs= cloud.google.com/go/storage v1.10.0/go.mod h1:FLPqc6j+Ki4BU591ie1oL6qBQGu2Bl/tZ9ullr3+Kg0= cloud.google.com/go/storage v1.14.0/go.mod h1:GrKmX003DSIwi9o29oFT7YDnHYwZoctc3fOKtUw0Xmo= -cosmossdk.io/api v0.3.2-0.20230313131911-55bf5d4efbe7 h1:4LrWK+uGP5IxznxtHHsHD+ZBs2+oZRH2loYOGjHLzZM= -cosmossdk.io/api v0.3.2-0.20230313131911-55bf5d4efbe7/go.mod h1:yVns7mKgcsG+hZW/3C5FdJtC6QYWdFIcRlKb9+5HV5g= -cosmossdk.io/collections v0.0.0-20230309163709-87da587416ba h1:S4PYij/tX3Op/hwenVEN9D+M27JRcwSwVqE3UA0BnwM= -cosmossdk.io/collections v0.0.0-20230309163709-87da587416ba/go.mod h1:lpS+G8bGC2anqzWdndTzjnQnuMO/qAcgZUkGJp4i3rc= +cosmossdk.io/api v0.4.0 h1:x90DmdidP6EhzktAa/6/IofSHidDnPjahdlrUvyQZQw= +cosmossdk.io/api v0.4.0/go.mod h1:TWDzBhUBhI1LhSf2XSYpfIBf6D4mbLu/fvzvDfhcaYM= +cosmossdk.io/collections v0.1.0 h1:nzJGeiq32KnZroSrhB6rPifw4I85Cgmzw/YAmr4luv8= +cosmossdk.io/collections v0.1.0/go.mod h1:xbauc0YsbUF8qKMVeBZl0pFCunxBIhKN/WlxpZ3lBuo= cosmossdk.io/core v0.6.1 h1:OBy7TI2W+/gyn2z40vVvruK3di+cAluinA6cybFbE7s= cosmossdk.io/core v0.6.1/go.mod h1:g3MMBCBXtxbDWBURDVnJE7XML4BG5qENhs0gzkcpuFA= cosmossdk.io/depinject v1.0.0-alpha.3 h1:6evFIgj//Y3w09bqOUOzEpFj5tsxBqdc5CfkO7z+zfw= cosmossdk.io/depinject v1.0.0-alpha.3/go.mod h1:eRbcdQ7MRpIPEM5YUJh8k97nxHpYbc3sMUnEtt8HPWU= cosmossdk.io/errors v1.0.0-beta.7 h1:gypHW76pTQGVnHKo6QBkb4yFOJjC+sUGRc5Al3Odj1w= cosmossdk.io/errors v1.0.0-beta.7/go.mod h1:mz6FQMJRku4bY7aqS/Gwfcmr/ue91roMEKAmDUDpBfE= -cosmossdk.io/log v0.1.0 h1:Vnexi+KzUCjmqq/m93teAxjt5biWFfZ5PI1imx2IJw8= -cosmossdk.io/log v0.1.0/go.mod h1:p95Wq6mDY3SREMc4y7+QU9Uwy3nyvfpWGD1iSaFkVFs= +cosmossdk.io/log v1.0.0 h1:NGKZ/A5rd4PduDfoscgABklX557PWjQINbosZy/m3Jk= +cosmossdk.io/log v1.0.0/go.mod h1:CwX9BLiBruZb7lzLlRr3R231d/fVPUXk8gAdV4LQap0= cosmossdk.io/math v1.0.0 h1:ro9w7eKx23om2tZz/VM2Pf+z2WAbGX1yDQQOJ6iGeJw= cosmossdk.io/math v1.0.0/go.mod h1:Ygz4wBHrgc7g0N+8+MrnTfS9LLn9aaTGa9hKopuym5k= -cosmossdk.io/store v0.1.0-alpha.1 h1:NGomhLUXzAxvK4OF8+yP6eNUG5i4LwzOzx+S494pTCg= -cosmossdk.io/store v0.1.0-alpha.1/go.mod h1:kmCMbhrleCZ6rDZPY/EGNldNvPebFNyVPFYp+pv05/k= -cosmossdk.io/x/tx v0.3.1-0.20230321155358-6522dd1731b5 h1:AlvyRc7f7Py1mv254vrqjIIuykCnitHIz2T+nup3bU0= -cosmossdk.io/x/tx v0.3.1-0.20230321155358-6522dd1731b5/go.mod h1:FNkSEMbLP9NFdTfrbslNUtNS7OXf3wgZeJyXzfRPa4c= +cosmossdk.io/store v0.1.0-alpha.1.0.20230328185921-37ba88872dbc h1:9piuA+NYmhe+SyMPtMoboLw/djgDbrI3dD5TG020Tnk= +cosmossdk.io/store v0.1.0-alpha.1.0.20230328185921-37ba88872dbc/go.mod h1:UFF5rmjN7WYVfxo6ArdY/l1+yyWMURBWOmSJypGqFHQ= +cosmossdk.io/x/tx v0.5.1-0.20230407182919-057d2e09bd63 h1:zHqj2VwZ/MStFmR7SUe/7gErOFhL9v2rkjmWPB/st34= +cosmossdk.io/x/tx v0.5.1-0.20230407182919-057d2e09bd63/go.mod h1:Oh3Kh+IPOfMEILNxVd2e8SLqRrIjYHpdGBfDg4ghU/k= dmitri.shuralyov.com/gpu/mtl v0.0.0-20190408044501-666a987793e9/go.mod h1:H6x//7gZCb22OMCxBHrMx7a5I7Hp++hsVxbQ4BYO7hU= filippo.io/edwards25519 v1.0.0 h1:0wAIcmJUqRdI8IJ/3eGi5/HwXZWPujYXXlkrQogz0Ek= filippo.io/edwards25519 v1.0.0/go.mod h1:N1IkdkCkiLB6tki+MYJoSx2JTY9NUlxZE7eHn5EwJns= @@ -113,6 +113,8 @@ github.com/beorn7/perks v1.0.1/go.mod h1:G2ZrVWU2WbWT9wwq4/hrbKbnv/1ERSJQ0ibhJ6r github.com/bgentry/speakeasy v0.1.0/go.mod h1:+zsyZBPWlz7T6j88CTgSN5bM796AkVf0kBD4zp0CCIs= github.com/bgentry/speakeasy v0.1.1-0.20220910012023-760eaf8b6816 h1:41iFGWnSlI2gVpmOtVTJZNodLdLQLn/KsJqFvXwnd/s= github.com/bgentry/speakeasy v0.1.1-0.20220910012023-760eaf8b6816/go.mod h1:+zsyZBPWlz7T6j88CTgSN5bM796AkVf0kBD4zp0CCIs= +github.com/bits-and-blooms/bitset v1.6.0 h1:FVfaUsleKAUTJnaN9Fd1YFFi1S8vAX5xeXnXHFYOojM= +github.com/bits-and-blooms/bitset v1.6.0/go.mod h1:gIdJ4wp64HaoK2YrL1Q5/N7Y16edYb8uY+O0FJTyyDA= github.com/btcsuite/btcd/btcec/v2 v2.3.2 h1:5n0X6hX0Zk+6omWcihdYvdAlGf2DfasC0GMf7DClJ3U= github.com/btcsuite/btcd/btcec/v2 v2.3.2/go.mod h1:zYzJ8etWJQIv1Ogk7OzpWjowwOdXY1W/17j2MW85J04= github.com/btcsuite/btcd/btcutil v1.1.2 h1:XLMbX8JQEiwMcYft2EGi8zPUkoa0abKIU6/BJSRsjzQ= @@ -156,14 +158,14 @@ github.com/cockroachdb/errors v1.9.1/go.mod h1:2sxOtL2WIc096WSZqZ5h8fa17rdDq9HZO github.com/cockroachdb/logtags v0.0.0-20211118104740-dabe8e521a4f/go.mod h1:Vz9DsVWQQhf3vs21MhPMZpMGSht7O/2vFW2xusFUVOs= github.com/cockroachdb/logtags v0.0.0-20230118201751-21c54148d20b h1:r6VH0faHjZeQy818SGhaone5OnYfxFR/+AzdY3sf5aE= github.com/cockroachdb/logtags v0.0.0-20230118201751-21c54148d20b/go.mod h1:Vz9DsVWQQhf3vs21MhPMZpMGSht7O/2vFW2xusFUVOs= -github.com/cockroachdb/pebble v0.0.0-20230315223031-1e5ddd10389e h1:CDuLmyaZ1pD4OJHHtubKqgu/Byw5zAnm+gArJsyj96Q= -github.com/cockroachdb/pebble v0.0.0-20230315223031-1e5ddd10389e/go.mod h1:9lRMC4XN3/BLPtIp6kAKwIaHu369NOf2rMucPzipz50= +github.com/cockroachdb/pebble v0.0.0-20230412222916-60cfeb46143b h1:92ve6F1Pls/eqd+V+102lOMRJatgpqqsQvbT9Bl/fjg= +github.com/cockroachdb/pebble v0.0.0-20230412222916-60cfeb46143b/go.mod h1:9lRMC4XN3/BLPtIp6kAKwIaHu369NOf2rMucPzipz50= github.com/cockroachdb/redact v1.1.3 h1:AKZds10rFSIj7qADf0g46UixK8NNLwWTNdCIGS5wfSQ= github.com/cockroachdb/redact v1.1.3/go.mod h1:BVNblN9mBWFyMyqK1k3AAiSxhvhfK2oOZZ2lK+dpvRg= github.com/codahale/hdrhistogram v0.0.0-20161010025455-3a0bb77429bd/go.mod h1:sE/e/2PUdi/liOCUjSTXgM1o87ZssimdTWN964YiIeI= github.com/codegangsta/inject v0.0.0-20150114235600-33e0aa1cb7c0/go.mod h1:4Zcjuz89kmFXt9morQgcfYZAYZ5n8WHjt81YYWIwtTM= -github.com/cometbft/cometbft v0.37.0 h1:M005vBaSaugvYYmNZwJOopynQSjwLoDTwflnQ/I/eYk= -github.com/cometbft/cometbft v0.37.0/go.mod h1:Y2MMMN//O5K4YKd8ze4r9jmk4Y7h0ajqILXbH5JQFVs= +github.com/cometbft/cometbft v0.37.1-0.20230411132551-3a91d155e664 h1:BbCkbnaU3R603XpnbqvuDU8Kfv+hjhiFILOHhVFntsw= +github.com/cometbft/cometbft v0.37.1-0.20230411132551-3a91d155e664/go.mod h1:Y2MMMN//O5K4YKd8ze4r9jmk4Y7h0ajqILXbH5JQFVs= github.com/cometbft/cometbft-db v0.7.0 h1:uBjbrBx4QzU0zOEnU8KxoDl18dMNgDh+zZRUE0ucsbo= github.com/cometbft/cometbft-db v0.7.0/go.mod h1:yiKJIm2WKrt6x8Cyxtq9YTEcIMPcEe4XPxhgX59Fzf0= github.com/confio/ics23/go v0.9.0 h1:cWs+wdbS2KRPZezoaaj+qBleXgUk5WOQFMP3CQFGTr4= @@ -173,7 +175,7 @@ github.com/coreos/etcd v3.3.10+incompatible/go.mod h1:uF7uidLiAD3TWHmW31ZFd/JWoc github.com/coreos/go-etcd v2.0.0+incompatible/go.mod h1:Jez6KQU2B/sWsbdaef3ED8NzMklzPG4d5KIOhIy30Tk= github.com/coreos/go-semver v0.2.0/go.mod h1:nnelYz7RCh+5ahJtPPxZlU+153eP4D4r3EedlOD2RNk= github.com/coreos/go-systemd v0.0.0-20180511133405-39ca1b05acc7/go.mod h1:F5haX7vjVVG0kc13fIWeqUViNPyEJxv/OmvnBo0Yme4= -github.com/coreos/go-systemd/v22 v22.3.3-0.20220203105225-a9a7ef127534/go.mod h1:Y58oyj3AT4RCenI/lSvhwexgC+NSVTIJ3seZv2GcEnc= +github.com/coreos/go-systemd/v22 v22.5.0/go.mod h1:Y58oyj3AT4RCenI/lSvhwexgC+NSVTIJ3seZv2GcEnc= github.com/coreos/pkg v0.0.0-20160727233714-3ac0863d7acf/go.mod h1:E3G3o1h8I7cfcXa63jLwjI0eiQQMgzzUDFVpN/nH/eA= github.com/cosmos/btcutil v1.0.5 h1:t+ZFcX77LpKtDBhjucvnOH8C2l2ioGsBNEQ3jef8xFk= github.com/cosmos/btcutil v1.0.5/go.mod h1:IyB7iuqZMJlthe2tkIFL33xPyzbFYP0XVdS8P5lUPis= @@ -181,16 +183,16 @@ github.com/cosmos/cosmos-db v1.0.0-rc.1 h1:SjnT8B6WKMW9WEIX32qMhnEEKcI7ZP0+G1Sa9 github.com/cosmos/cosmos-db v1.0.0-rc.1/go.mod h1:Dnmk3flSf5lkwCqvvjNpoxjpXzhxnCAFzKHlbaForso= github.com/cosmos/cosmos-proto v1.0.0-beta.3 h1:VitvZ1lPORTVxkmF2fAp3IiA61xVwArQYKXTdEcpW6o= github.com/cosmos/cosmos-proto v1.0.0-beta.3/go.mod h1:t8IASdLaAq+bbHbjq4p960BvcTqtwuAxid3b/2rOD6I= -github.com/cosmos/cosmos-sdk v0.46.0-beta2.0.20230321173237-fe77d4bca302 h1:wffm9LPPG/FBW/tSRdJp2DCgkJQRX+Zsbdmn4I0aWeQ= -github.com/cosmos/cosmos-sdk v0.46.0-beta2.0.20230321173237-fe77d4bca302/go.mod h1:HzOsWXtPxhO8+Y8P4Ru+G3UWx6dTkpGXU9yvT35VEuI= +github.com/cosmos/cosmos-sdk v0.46.0-beta2.0.20230419074131-aa683247d515 h1:KMbJ5nAA0Xk79z0D1oL3kiw9lBYiqlV3ZqUxXVbbgBY= +github.com/cosmos/cosmos-sdk v0.46.0-beta2.0.20230419074131-aa683247d515/go.mod h1:BPvKPN63ettXrpz67uM1rHEqX/UVVkAfceFCPyp217E= github.com/cosmos/go-bip39 v0.0.0-20180819234021-555e2067c45d/go.mod h1:tSxLoYXyBmiFeKpvmq4dzayMdCjCnu8uqmCysIGBT2Y= github.com/cosmos/go-bip39 v1.0.0 h1:pcomnQdrdH22njcAatO0yWojsUnCO3y2tNoV1cb6hHY= github.com/cosmos/go-bip39 v1.0.0/go.mod h1:RNJv0H/pOIVgxw6KS7QeX2a0Uo0aKUlfhZ4xuwvCdJw= github.com/cosmos/gogogateway v1.2.0 h1:Ae/OivNhp8DqBi/sh2A8a1D0y638GpL3tkmLQAiKxTE= github.com/cosmos/gogogateway v1.2.0/go.mod h1:iQpLkGWxYcnCdz5iAdLcRBSw3h7NXeOkZ4GUkT+tbFI= github.com/cosmos/gogoproto v1.4.2/go.mod h1:cLxOsn1ljAHSV527CHOtaIP91kK6cCrZETRBrkzItWU= -github.com/cosmos/gogoproto v1.4.6 h1:Ee7z15dWJaGlgM2rWrK8N2IX7PQcuccu8oG68jp5RL4= -github.com/cosmos/gogoproto v1.4.6/go.mod h1:VS/ASYmPgv6zkPKLjR9EB91lwbLHOzaGCirmKKhncfI= +github.com/cosmos/gogoproto v1.4.8 h1:BrHKc6WFZt8+jRV71vKSQE+JrfF+JAnzrKo2VP7wIZ4= +github.com/cosmos/gogoproto v1.4.8/go.mod h1:hnb0DIEWTv+wdNzNcqus5xCQXq5+CXauq1FJuurRfVY= github.com/cosmos/iavl v0.21.0-beta.1 h1:fBQeBc8HLZ14plJNcmGfaOXSSMLVEHvEQXiTXSD76m0= github.com/cosmos/iavl v0.21.0-beta.1/go.mod h1:25YJYzilTErJ2mKfNB3xyWL9IsCwEQdNzdIutg2mh3U= github.com/cosmos/ledger-cosmos-go v0.13.0 h1:ex0CvCxToSR7j5WjrghPu2Bu9sSXKikjnVvUryNnx4s= @@ -209,9 +211,9 @@ github.com/danieljoos/wincred v1.1.2/go.mod h1:GijpziifJoIBfYh+S7BbkdUTU4LfM+QnG github.com/davecgh/go-spew v1.1.0/go.mod h1:J7Y8YcW2NihsgmVo/mv3lAwl/skON4iLHjSsI+c5H38= github.com/davecgh/go-spew v1.1.1 h1:vj9j/u1bqnvCEfJOwUhtlOARqs3+rkHYY13jYWTU97c= github.com/davecgh/go-spew v1.1.1/go.mod h1:J7Y8YcW2NihsgmVo/mv3lAwl/skON4iLHjSsI+c5H38= -github.com/decred/dcrd/crypto/blake256 v1.0.0 h1:/8DMNYp9SGi5f0w7uCm6d6M4OU2rGFK09Y2A4Xv7EE0= -github.com/decred/dcrd/dcrec/secp256k1/v4 v4.1.0 h1:HbphB4TFFXpv7MNrT52FGrrgVXF1owhMVTHFZIlnvd4= -github.com/decred/dcrd/dcrec/secp256k1/v4 v4.1.0/go.mod h1:DZGJHZMqrU4JJqFAWUS2UO1+lbSKsdiOoYi9Zzey7Fc= +github.com/decred/dcrd/crypto/blake256 v1.0.1 h1:7PltbUIQB7u/FfZ39+DGa/ShuMyJ5ilcvdfma9wOH6Y= +github.com/decred/dcrd/dcrec/secp256k1/v4 v4.2.0 h1:8UrgZ3GkP4i/CLijOJx79Yu+etlyjdBU4sfcs2WYQMs= +github.com/decred/dcrd/dcrec/secp256k1/v4 v4.2.0/go.mod h1:v57UDF4pDQJcEfFUCRop3lJL149eHGSe9Jvczhzjo/0= github.com/desertbit/timer v0.0.0-20180107155436-c41aec40b27f h1:U5y3Y5UE0w7amNe7Z5G/twsBW0KEalRQXZzf8ufSh9I= github.com/desertbit/timer v0.0.0-20180107155436-c41aec40b27f/go.mod h1:xH/i4TFMt8koVQZ6WFms69WAsDWr2XsYL3Hkl7jkoLE= github.com/dgraph-io/badger v1.6.0/go.mod h1:zwt7syl517jmP8s94KqSxTlM6IMsdhYy6psNgSztDR4= @@ -271,8 +273,8 @@ github.com/fsnotify/fsnotify v1.6.0 h1:n+5WquG0fcWoWp6xPWfHdbskMCQaFnG6PfBrh1Ky4 github.com/fsnotify/fsnotify v1.6.0/go.mod h1:sl3t1tCWJFWoRz9R8WJCbQihKKwmorjAbSClcnxKAGw= github.com/gavv/httpexpect v2.0.0+incompatible/go.mod h1:x+9tiU1YnrOvnB725RkpoLv1M62hOWzwo5OXotisrKc= github.com/getsentry/sentry-go v0.12.0/go.mod h1:NSap0JBYWzHND8oMbyi0+XZhUalc1TBdRL1M71JZW2c= -github.com/getsentry/sentry-go v0.19.0 h1:BcCH3CN5tXt5aML+gwmbFwVptLLQA+eT866fCO9wVOM= -github.com/getsentry/sentry-go v0.19.0/go.mod h1:y3+lGEFEFexZtpbG1GUE2WD/f9zGyKYwpEqryTOC/nE= +github.com/getsentry/sentry-go v0.20.0 h1:bwXW98iMRIWxn+4FgPW7vMrjmbym6HblXALmhjHmQaQ= +github.com/getsentry/sentry-go v0.20.0/go.mod h1:lc76E2QywIyW8WuBnwl8Lc4bkmQH4+w1gwTf25trprY= github.com/ghodss/yaml v1.0.0/go.mod h1:4dBDuWmgqj2HViK6kFavaiC9ZROes6MMH2rRYeMEF04= github.com/gin-contrib/sse v0.1.0 h1:Y/yl/+YNO8GZSjAhjMsSuLt29uWRFHdHYUb5lYOV9qE= github.com/gin-contrib/sse v0.1.0/go.mod h1:RHrZQHXnP2xjPF+u1gW/2HnVO7nvIa9PG3Gm+fLHvGI= @@ -493,7 +495,6 @@ github.com/imkira/go-interpol v1.1.0/go.mod h1:z0h2/2T3XF8kyEPpRgJ3kmNv+C43p+I/C github.com/improbable-eng/grpc-web v0.15.0 h1:BN+7z6uNXZ1tQGcNAuaU1YjsLTApzkjt2tzCixLaUPQ= github.com/improbable-eng/grpc-web v0.15.0/go.mod h1:1sy9HKV4Jt9aEs9JSnkWlRJPuPtwNr0l57L4f878wP8= github.com/inconshreveable/mousetrap v1.0.0/go.mod h1:PxqpIevigyE2G7u3NXJIT2ANytuPF1OarO4DADm73n8= -github.com/inconshreveable/mousetrap v1.0.1/go.mod h1:vpF70FUmC8bwa3OWnCshd2FqLfsEA9PFc4w1p2J65bw= github.com/inconshreveable/mousetrap v1.1.0 h1:wN+x4NVGpMsO7ErUn/mUI3vEoE6Jt13X2s0bqwp9tc8= github.com/inconshreveable/mousetrap v1.1.0/go.mod h1:vpF70FUmC8bwa3OWnCshd2FqLfsEA9PFc4w1p2J65bw= github.com/influxdata/influxdb1-client v0.0.0-20191209144304-8bf82d3c094d/go.mod h1:qj24IKcXYK6Iy9ceXlo3Tc+vtHo9lIhSX5JddghvEPo= @@ -535,8 +536,8 @@ github.com/klauspost/compress v1.9.7/go.mod h1:RyIbtBH6LamlWaDj8nUwkbUhJ87Yi3uG0 github.com/klauspost/compress v1.10.3/go.mod h1:aoV0uJVorq1K+umq18yTdKaF57EivdYsUV+/s2qKfXs= github.com/klauspost/compress v1.11.7/go.mod h1:aoV0uJVorq1K+umq18yTdKaF57EivdYsUV+/s2qKfXs= github.com/klauspost/compress v1.12.3/go.mod h1:8dP1Hq4DHOhN9w426knH3Rhby4rFm6D8eO+e+Dq5Gzg= -github.com/klauspost/compress v1.16.3 h1:XuJt9zzcnaz6a16/OU53ZjWp/v7/42WcR5t2a0PcNQY= -github.com/klauspost/compress v1.16.3/go.mod h1:ntbaceVETuRiXiv4DpjP66DpAtAGkEQskQzEyD//IeE= +github.com/klauspost/compress v1.16.5 h1:IFV2oUNUzZaz+XyusxpLzpzS8Pt5rh0Z16For/djlyI= +github.com/klauspost/compress v1.16.5/go.mod h1:ntbaceVETuRiXiv4DpjP66DpAtAGkEQskQzEyD//IeE= github.com/klauspost/cpuid v1.2.1/go.mod h1:Pj4uuM528wm8OyEC2QMXAi2YiTZ96dNQPGgoMS4s3ek= github.com/konsorten/go-windows-terminal-sequences v1.0.1/go.mod h1:T0+1ngSBFLxvqU3pZ+m/2kptfBszLMUkC4ZK/EgS/cQ= github.com/konsorten/go-windows-terminal-sequences v1.0.3/go.mod h1:T0+1ngSBFLxvqU3pZ+m/2kptfBszLMUkC4ZK/EgS/cQ= @@ -561,8 +562,8 @@ github.com/libp2p/go-buffer-pool v0.1.0 h1:oK4mSFcQz7cTQIfqbe4MIj9gLW+mnanjyFtc6 github.com/libp2p/go-buffer-pool v0.1.0/go.mod h1:N+vh8gMqimBzdKkSMVuydVDq+UV5QTWy5HSiZacSbPg= github.com/lightstep/lightstep-tracer-common/golang/gogo v0.0.0-20190605223551-bc2310a04743/go.mod h1:qklhhLq1aX+mtWk9cPHPzaBjWImj5ULL6C7HFJtXQMM= github.com/lightstep/lightstep-tracer-go v0.18.1/go.mod h1:jlF1pusYV4pidLvZ+XD0UBX0ZE6WURAspgAczcDHrL4= -github.com/linxGnu/grocksdb v1.7.15 h1:AEhP28lkeAybv5UYNYviYISpR6bJejEnKuYbnWAnxx0= -github.com/linxGnu/grocksdb v1.7.15/go.mod h1:pY55D0o+r8yUYLq70QmhdudxYvoDb9F+9puf4m3/W+U= +github.com/linxGnu/grocksdb v1.7.16 h1:Q2co1xrpdkr5Hx3Fp+f+f7fRGhQFQhvi/+226dtLmA8= +github.com/linxGnu/grocksdb v1.7.16/go.mod h1:JkS7pl5qWpGpuVb3bPqTz8nC12X3YtPZT+Xq7+QfQo4= github.com/lyft/protoc-gen-validate v0.0.13/go.mod h1:XbGvPuh87YZc5TdIa2/I4pLk0QoUACkjt2znoq26NVQ= github.com/magiconair/properties v1.8.0/go.mod h1:PppfXfuXeibc/6YijjN8zIbojt8czPbwD3XqdrwzmxQ= github.com/magiconair/properties v1.8.7 h1:IeQXZAiQcpL9mgcAe1Nu6cX9LLw6ExEHKjN0VQdvPDY= @@ -700,8 +701,8 @@ github.com/prometheus/client_golang v1.0.0/go.mod h1:db9x61etRT2tGnBNRi70OPL5Fsn github.com/prometheus/client_golang v1.3.0/go.mod h1:hJaj2vgQTGQmVCsAACORcieXFeDPbaTKGT+JTgUa3og= github.com/prometheus/client_golang v1.4.0/go.mod h1:e9GMxYsXl05ICDXkRhurwBS4Q3OK1iX/F2sw+iXX5zU= github.com/prometheus/client_golang v1.7.1/go.mod h1:PY5Wy2awLA44sXw4AOSfFBetzPP4j5+D6mVACh+pe2M= -github.com/prometheus/client_golang v1.14.0 h1:nJdhIvne2eSX/XRAFV9PcvFFRbrjbcTUj0VP62TMhnw= -github.com/prometheus/client_golang v1.14.0/go.mod h1:8vpkKitgIVNcqrRBWh1C4TIUQgYNtG/XQE4E/Zae36Y= +github.com/prometheus/client_golang v1.15.0 h1:5fCgGYogn0hFdhyhLbw7hEsWxufKtY9klyvdNfFlFhM= +github.com/prometheus/client_golang v1.15.0/go.mod h1:e9yaBhRPU2pPNsZwE+JdQl0KEt1N9XgF6zxWmaC0xOk= github.com/prometheus/client_model v0.0.0-20180712105110-5c3871d89910/go.mod h1:MbSGuTsp3dbXC40dX6PRTWyKYBIrTGTE9sqQNg2J8bo= github.com/prometheus/client_model v0.0.0-20190115171406-56726106282f/go.mod h1:MbSGuTsp3dbXC40dX6PRTWyKYBIrTGTE9sqQNg2J8bo= github.com/prometheus/client_model v0.0.0-20190129233127-fd36f4220a90/go.mod h1:xMI15A0UPsDsEKsMN9yxemIoYk6Tm2C1GtYGdfGttqA= @@ -736,14 +737,15 @@ github.com/rogpeppe/go-internal v1.3.0/go.mod h1:M8bDsm7K2OlrFYOpmOWEs/qY81heoFR github.com/rogpeppe/go-internal v1.6.1/go.mod h1:xXDCJY+GAPziupqXw64V24skbSoqbTEfhy4qGm1nDQc= github.com/rogpeppe/go-internal v1.8.0/go.mod h1:WmiCO8CzOY8rg0OYDC4/i/2WRWAB6poM+XZ2dLUbcbE= github.com/rogpeppe/go-internal v1.8.1/go.mod h1:JeRgkft04UBgHMgCIwADu4Pn6Mtm5d4nPKWu0nJ5d+o= -github.com/rogpeppe/go-internal v1.9.0 h1:73kH8U+JUqXU8lRuOHeVHaa/SZPifC7BkcraZVejAe8= github.com/rogpeppe/go-internal v1.9.0/go.mod h1:WtVeX8xhTBvf0smdhujwtBcq4Qrzq/fJaraNFVN+nFs= +github.com/rogpeppe/go-internal v1.10.0 h1:TMyTOH3F/DB16zRVcYyreMH6GnZZrwQVAoYjRBZyWFQ= +github.com/rogpeppe/go-internal v1.10.0/go.mod h1:UQnix2H7Ngw/k4C5ijL5+65zddjncjaFoBhdsK/akog= github.com/rs/cors v1.7.0/go.mod h1:gFx+x8UowdsKA9AchylcLynDq+nNFfI8FkUZdN/jGCU= github.com/rs/cors v1.8.3 h1:O+qNyWn7Z+F9M0ILBHgMVPuB1xTOucVd5gtaYyXBpRo= github.com/rs/cors v1.8.3/go.mod h1:XyqrcTp5zjWr1wsJ8PIRZssZ8b/WMcMf71DJnit4EMU= github.com/rs/xid v1.4.0/go.mod h1:trrq9SKmegXys3aeAKXMUTdJsYXVwGY3RLcfgqegfbg= -github.com/rs/zerolog v1.29.0 h1:Zes4hju04hjbvkVkOhdl2HpZa+0PmVwigmo8XoORE5w= -github.com/rs/zerolog v1.29.0/go.mod h1:NILgTygv/Uej1ra5XxGf82ZFSLk58MFGAUS2o6usyD0= +github.com/rs/zerolog v1.29.1 h1:cO+d60CHkknCbvzEWxP0S9K6KqyTjrCNUy1LdQLCGPc= +github.com/rs/zerolog v1.29.1/go.mod h1:Le6ESbR7hc+DP6Lt1THiV8CQSdkkNrd3R0XbEgp3ZBU= github.com/russross/blackfriday v1.5.2/go.mod h1:JO/DiYxRf+HjHt06OyowR9PTA263kcR/rfWxYHBV53g= github.com/russross/blackfriday/v2 v2.0.1/go.mod h1:+Rmxgy9KzJVeS9/2gXHxylqXiyQDYRxCVz55jmeOWTM= github.com/russross/blackfriday/v2 v2.1.0/go.mod h1:+Rmxgy9KzJVeS9/2gXHxylqXiyQDYRxCVz55jmeOWTM= @@ -776,8 +778,8 @@ github.com/spf13/cast v1.5.0 h1:rj3WzYc11XZaIZMPKmwP96zkFEnnAmV8s6XbB2aY32w= github.com/spf13/cast v1.5.0/go.mod h1:SpXXQ5YoyJw6s3/6cMTQuxvgRl3PCJiyaX9p6b155UU= github.com/spf13/cobra v0.0.3/go.mod h1:1l0Ry5zgKvJasoi3XT1TypsSe7PqH0Sj9dhYf7v3XqQ= github.com/spf13/cobra v0.0.5/go.mod h1:3K3wKZymM7VvHMDS9+Akkh4K60UwM26emMESw8tLCHU= -github.com/spf13/cobra v1.6.1 h1:o94oiPyS4KD1mPy2fmcYYHHfCxLqYjJOhGsCHFZtEzA= -github.com/spf13/cobra v1.6.1/go.mod h1:IOw/AERYS7UzyrGinqmz6HLUo219MORXGxhbaJUqzrY= +github.com/spf13/cobra v1.7.0 h1:hyqWnYt1ZQShIddO5kBpj3vu05/++x6tJ6dg8EC572I= +github.com/spf13/cobra v1.7.0/go.mod h1:uLxZILRyS/50WlhOIKD7W6V5bgeIt+4sICxh6uRMrb0= github.com/spf13/jwalterweatherman v1.0.0/go.mod h1:cQK4TGJAtQXfYWX+Ddv3mKDzgVb68N+wFjFa4jdeBTo= github.com/spf13/jwalterweatherman v1.1.0 h1:ue6voC5bR5F8YxI5S67j9i582FU4Qvo2bmqnqMYADFk= github.com/spf13/jwalterweatherman v1.1.0/go.mod h1:aNWZUN0dPAAO/Ljvb5BEdw96iTZ0EXowPYD95IqWIGo= @@ -895,8 +897,8 @@ golang.org/x/crypto v0.0.0-20210421170649-83a5a9bb288b/go.mod h1:T9bdIzuCu7OtxOm golang.org/x/crypto v0.0.0-20210711020723-a769d52b0f97/go.mod h1:GvvjBRRGRdwPK5ydBHafDWAxML/pGHZbMvKqRZ5+Abc= golang.org/x/crypto v0.0.0-20210921155107-089bfa567519/go.mod h1:GvvjBRRGRdwPK5ydBHafDWAxML/pGHZbMvKqRZ5+Abc= golang.org/x/crypto v0.0.0-20211108221036-ceb1ce70b4fa/go.mod h1:GvvjBRRGRdwPK5ydBHafDWAxML/pGHZbMvKqRZ5+Abc= -golang.org/x/crypto v0.7.0 h1:AvwMYaRytfdeVt3u6mLaxYtErKYjxA2OXjJ1HHq6t3A= -golang.org/x/crypto v0.7.0/go.mod h1:pYwdfH91IfpZVANVyUOhSIPZaFoJGxTFbZhFTx+dXZU= +golang.org/x/crypto v0.8.0 h1:pd9TJtTueMTVQXzk8E2XESSMQDj/U7OUu0PqJqPXQjQ= +golang.org/x/crypto v0.8.0/go.mod h1:mRqEX+O9/h5TFCrQhkgjo2yKi0yYA+9ecGkdQoHrywE= golang.org/x/exp v0.0.0-20190121172915-509febef88a4/go.mod h1:CJ0aWSM057203Lf6IL+f9T1iT9GByDxfZKAQTCR3kQA= golang.org/x/exp v0.0.0-20190306152737-a1d7652674e8/go.mod h1:CJ0aWSM057203Lf6IL+f9T1iT9GByDxfZKAQTCR3kQA= golang.org/x/exp v0.0.0-20190510132918-efd6b22b2522/go.mod h1:ZjyILWgesfNpC6sMxTJOJm9Kp84zZh5NQWvqDGG3Qr8= @@ -985,8 +987,8 @@ golang.org/x/net v0.0.0-20210805182204-aaa1db679c0d/go.mod h1:9nx3DQGgdP8bBQD5qx golang.org/x/net v0.0.0-20211008194852-3b03d305991f/go.mod h1:9nx3DQGgdP8bBQD5qxJ1jj9UTztislL4KSBs9R2vV5Y= golang.org/x/net v0.0.0-20220225172249-27dd8689420f/go.mod h1:CfG3xpIq0wQ8r1q4Su4UZFWDARRcnwPjda9FqA0JpMk= golang.org/x/net v0.0.0-20220607020251-c690dde0001d/go.mod h1:XRhObCWvk6IyKnWLug+ECip1KBveYUHfp+8e9klMJ9c= -golang.org/x/net v0.8.0 h1:Zrh2ngAOFYneWTAIAPethzeaQLuHwhuBkuV6ZiRnUaQ= -golang.org/x/net v0.8.0/go.mod h1:QVkue5JL9kW//ek3r6jTKnTFis1tRmNAW2P1shuFdJc= +golang.org/x/net v0.9.0 h1:aWJ/m6xSmxWBx+V0XRHTlrYrPG56jKsLdTFmsSsCzOM= +golang.org/x/net v0.9.0/go.mod h1:d48xBJpPfHeWQsugry2m+kC02ZBRGRgulfHnEXEuWns= golang.org/x/oauth2 v0.0.0-20180821212333-d2e6202438be/go.mod h1:N/0e6XlmueqKjAGxoOufVs8QHGRruUQn6yWY3a++T0U= golang.org/x/oauth2 v0.0.0-20190226205417-e64efc72b421/go.mod h1:gOpvHmFTYa4IltrdGE7lF6nIHvwfUNPOp7c8zoXwtLw= golang.org/x/oauth2 v0.0.0-20190604053449-0f29369cfe45/go.mod h1:gOpvHmFTYa4IltrdGE7lF6nIHvwfUNPOp7c8zoXwtLw= @@ -1089,12 +1091,13 @@ golang.org/x/sys v0.0.0-20220520151302-bc2c85ada10a/go.mod h1:oPkhp1MJrh7nUepCBc golang.org/x/sys v0.0.0-20220811171246-fbc7d0a398ab/go.mod h1:oPkhp1MJrh7nUepCBck5+mAzfO9JrbApNNgaTdGDITg= golang.org/x/sys v0.0.0-20220908164124-27713097b956/go.mod h1:oPkhp1MJrh7nUepCBck5+mAzfO9JrbApNNgaTdGDITg= golang.org/x/sys v0.0.0-20221010170243-090e33056c14/go.mod h1:oPkhp1MJrh7nUepCBck5+mAzfO9JrbApNNgaTdGDITg= -golang.org/x/sys v0.6.0 h1:MVltZSvRTcU2ljQOhs94SXPftV6DCNnZViHeQps87pQ= golang.org/x/sys v0.6.0/go.mod h1:oPkhp1MJrh7nUepCBck5+mAzfO9JrbApNNgaTdGDITg= +golang.org/x/sys v0.7.0 h1:3jlCCIQZPdOYu1h8BkNvLz8Kgwtae2cagcG/VamtZRU= +golang.org/x/sys v0.7.0/go.mod h1:oPkhp1MJrh7nUepCBck5+mAzfO9JrbApNNgaTdGDITg= golang.org/x/term v0.0.0-20201126162022-7de9c90e9dd1/go.mod h1:bj7SfCRtBDWHUb9snDiAeCFNEtKQo2Wmx5Cou7ajbmo= golang.org/x/term v0.0.0-20210927222741-03fcf44c2211/go.mod h1:jbD1KX2456YbFQfuXm/mYQcufACuNUgVhRMnK/tPxf8= -golang.org/x/term v0.6.0 h1:clScbb1cHjoCkyRbWwBEUZ5H/tIFu5TAXIqaZD0Gcjw= -golang.org/x/term v0.6.0/go.mod h1:m6U89DPEgQRMq3DNkDClhWw02AUbt2daBVO4cn4Hv9U= +golang.org/x/term v0.7.0 h1:BEvjmm5fURWqcfbSKTdpkDXYBrUS1c0m8agp14W48vQ= +golang.org/x/term v0.7.0/go.mod h1:P32HKFT3hSsZrRxla30E9HqToFYAQPCMs/zFMBUFqPY= golang.org/x/text v0.0.0-20170915032832-14c0d48ead0c/go.mod h1:NqM8EUOU14njkJ3fqMW+pc6Ldnwhi/IjpwHt7yyuwOQ= golang.org/x/text v0.3.0/go.mod h1:NqM8EUOU14njkJ3fqMW+pc6Ldnwhi/IjpwHt7yyuwOQ= golang.org/x/text v0.3.1-0.20180807135948-17ff2d5776d2/go.mod h1:NqM8EUOU14njkJ3fqMW+pc6Ldnwhi/IjpwHt7yyuwOQ= @@ -1104,8 +1107,8 @@ golang.org/x/text v0.3.4/go.mod h1:5Zoc/QRtKVWzQhOtBMvqHzDpF6irO9z98xDceosuGiQ= golang.org/x/text v0.3.5/go.mod h1:5Zoc/QRtKVWzQhOtBMvqHzDpF6irO9z98xDceosuGiQ= golang.org/x/text v0.3.6/go.mod h1:5Zoc/QRtKVWzQhOtBMvqHzDpF6irO9z98xDceosuGiQ= golang.org/x/text v0.3.7/go.mod h1:u+2+/6zg+i71rQMx5EYifcz6MCKuco9NR6JIITiCfzQ= -golang.org/x/text v0.8.0 h1:57P1ETyNKtuIjB4SRd15iJxuhj8Gc416Y78H3qgMh68= -golang.org/x/text v0.8.0/go.mod h1:e1OnstbJyHTd6l/uOt8jFFHp6TRDWZR/bV3emEE/zU8= +golang.org/x/text v0.9.0 h1:2sjJmO8cDvYveuX97RDLsxlyUxLl+GHoLxBiRdHllBE= +golang.org/x/text v0.9.0/go.mod h1:e1OnstbJyHTd6l/uOt8jFFHp6TRDWZR/bV3emEE/zU8= golang.org/x/time v0.0.0-20180412165947-fbb02b2291d2/go.mod h1:tRJNPiyCQ0inRvYxbN9jk5I+vvW/OXSQhTDSoE431IQ= golang.org/x/time v0.0.0-20181108054448-85acf8d2951c/go.mod h1:tRJNPiyCQ0inRvYxbN9jk5I+vvW/OXSQhTDSoE431IQ= golang.org/x/time v0.0.0-20190308202827-9d24e82272b4/go.mod h1:tRJNPiyCQ0inRvYxbN9jk5I+vvW/OXSQhTDSoE431IQ= @@ -1251,8 +1254,8 @@ google.golang.org/genproto v0.0.0-20210126160654-44e461bb6506/go.mod h1:FWY/as6D google.golang.org/genproto v0.0.0-20210226172003-ab064af71705/go.mod h1:FWY/as6DDZQgahTzZj3fqbO1CbirC29ZNUFHwi0/+no= google.golang.org/genproto v0.0.0-20210624195500-8bfb893ecb84/go.mod h1:SzzZ/N+nwJDaO1kznhnlzqS8ocJICar6hYhVyhi++24= google.golang.org/genproto v0.0.0-20220314164441-57ef72a4c106/go.mod h1:hAL49I2IFola2sVEjAn7MEwsja0xp51I0tlGAf9hz4E= -google.golang.org/genproto v0.0.0-20230320184635-7606e756e683 h1:khxVcsk/FhnzxMKOyD+TDGwjbEOpcPuIpmafPGFmhMA= -google.golang.org/genproto v0.0.0-20230320184635-7606e756e683/go.mod h1:NWraEVixdDnqcqQ30jipen1STv2r/n24Wb7twVTGR4s= +google.golang.org/genproto v0.0.0-20230410155749-daa745c078e1 h1:KpwkzHKEF7B9Zxg18WzOa7djJ+Ha5DzthMyZYQfEn2A= +google.golang.org/genproto v0.0.0-20230410155749-daa745c078e1/go.mod h1:nKE/iIaLqn2bQwXBg8f1g2Ylh6r5MN5CmZvuzZCgsCU= google.golang.org/grpc v1.12.0/go.mod h1:yo6s7OP7yaDglbqo1J04qKzAhqBH6lvTonzMVmEdcZw= google.golang.org/grpc v1.17.0/go.mod h1:6QZJwpn2B+Zp71q/5VxRsJ6NXXVCE5NRUHRo+f3cWCs= google.golang.org/grpc v1.19.0/go.mod h1:mqu4LbDTu4XGKhr4mRzUsmM4RtVoemTSY81AxZiDr8c= diff --git a/x/evidence/keeper/grpc_query.go b/x/evidence/keeper/grpc_query.go index 654f3710c253..309d927b3702 100644 --- a/x/evidence/keeper/grpc_query.go +++ b/x/evidence/keeper/grpc_query.go @@ -66,7 +66,7 @@ func (k Keeper) AllEvidence(c context.Context, req *types.QueryAllEvidenceReques store := ctx.KVStore(k.storeKey) evidenceStore := prefix.NewStore(store, types.KeyPrefixEvidence) - pageRes, err := query.Paginate(evidenceStore, req.Pagination, func(key []byte, value []byte) error { + pageRes, err := query.Paginate(evidenceStore, req.Pagination, func(key, value []byte) error { result, err := k.UnmarshalEvidence(value) if err != nil { return err diff --git a/x/evidence/keeper/infraction.go b/x/evidence/keeper/infraction.go index b9713c01fc30..9526c0a29ffe 100644 --- a/x/evidence/keeper/infraction.go +++ b/x/evidence/keeper/infraction.go @@ -50,7 +50,7 @@ func (k Keeper) handleEquivocationEvidence(ctx sdk.Context, evidence *types.Equi // if the difference in time and number of blocks is greater than the allowed // parameters defined. cp := ctx.ConsensusParams() - if cp != nil && cp.Evidence != nil { + if cp.Evidence != nil { if ageDuration > cp.Evidence.MaxAgeDuration && ageBlocks > cp.Evidence.MaxAgeNumBlocks { logger.Info( "ignored equivocation; evidence too old", diff --git a/x/evidence/keeper/keeper.go b/x/evidence/keeper/keeper.go index dc0d091a5c25..bd992e7ff56f 100644 --- a/x/evidence/keeper/keeper.go +++ b/x/evidence/keeper/keeper.go @@ -5,6 +5,7 @@ import ( "fmt" "strings" + "cosmossdk.io/core/address" "cosmossdk.io/log" "cosmossdk.io/x/evidence/exported" "cosmossdk.io/x/evidence/types" @@ -26,18 +27,20 @@ type Keeper struct { router types.Router stakingKeeper types.StakingKeeper slashingKeeper types.SlashingKeeper + addressCodec address.Codec } // NewKeeper creates a new Keeper object. func NewKeeper( cdc codec.BinaryCodec, storeKey storetypes.StoreKey, stakingKeeper types.StakingKeeper, - slashingKeeper types.SlashingKeeper, + slashingKeeper types.SlashingKeeper, ac address.Codec, ) *Keeper { return &Keeper{ cdc: cdc, storeKey: storeKey, stakingKeeper: stakingKeeper, slashingKeeper: slashingKeeper, + addressCodec: ac, } } diff --git a/x/evidence/keeper/keeper_test.go b/x/evidence/keeper/keeper_test.go index ff8de64f5bc7..b155d659deee 100644 --- a/x/evidence/keeper/keeper_test.go +++ b/x/evidence/keeper/keeper_test.go @@ -17,6 +17,7 @@ import ( storetypes "cosmossdk.io/store/types" "github.com/cosmos/cosmos-sdk/baseapp" + "github.com/cosmos/cosmos-sdk/codec/address" "github.com/cosmos/cosmos-sdk/crypto/keys/ed25519" cryptotypes "github.com/cosmos/cosmos-sdk/crypto/types" "github.com/cosmos/cosmos-sdk/testutil" @@ -101,6 +102,7 @@ func (suite *KeeperTestSuite) SetupTest() { key, stakingKeeper, slashingKeeper, + address.NewBech32Codec("cosmos"), ) suite.stakingKeeper = stakingKeeper diff --git a/x/evidence/keeper/msg_server.go b/x/evidence/keeper/msg_server.go index adb4fb94b659..9862bbf6b953 100644 --- a/x/evidence/keeper/msg_server.go +++ b/x/evidence/keeper/msg_server.go @@ -3,9 +3,11 @@ package keeper import ( "context" - "cosmossdk.io/x/evidence/types" - + "cosmossdk.io/errors" sdk "github.com/cosmos/cosmos-sdk/types" + sdkerrors "github.com/cosmos/cosmos-sdk/types/errors" + + "cosmossdk.io/x/evidence/types" ) type msgServer struct { @@ -22,9 +24,20 @@ var _ types.MsgServer = msgServer{} // SubmitEvidence implements the MsgServer.SubmitEvidence method. func (ms msgServer) SubmitEvidence(goCtx context.Context, msg *types.MsgSubmitEvidence) (*types.MsgSubmitEvidenceResponse, error) { - ctx := sdk.UnwrapSDKContext(goCtx) + if _, err := ms.addressCodec.StringToBytes(msg.Submitter); err != nil { + return nil, sdkerrors.ErrInvalidAddress.Wrapf("invalid submitter address: %s", err) + } evidence := msg.GetEvidence() + if evidence == nil { + return nil, errors.Wrap(types.ErrInvalidEvidence, "missing evidence") + } + + if err := evidence.ValidateBasic(); err != nil { + return nil, errors.Wrapf(types.ErrInvalidEvidence, "failed basic validation: %s", err) + } + + ctx := sdk.UnwrapSDKContext(goCtx) if err := ms.Keeper.SubmitEvidence(ctx, evidence); err != nil { return nil, err } diff --git a/x/evidence/keeper/msg_server_test.go b/x/evidence/keeper/msg_server_test.go index 210377e11f51..055d1b863976 100644 --- a/x/evidence/keeper/msg_server_test.go +++ b/x/evidence/keeper/msg_server_test.go @@ -38,6 +38,20 @@ func (s *KeeperTestSuite) TestSubmitEvidence() { expErr bool expErrMsg string }{ + { + name: "invalid address", + req: &types.MsgSubmitEvidence{}, + expErr: true, + expErrMsg: "invalid submitter address: decoding bech32 failed: invalid bech32 string length 0", + }, + { + name: "missing evidence", + req: &types.MsgSubmitEvidence{ + Submitter: sdk.AccAddress(valAddresses[0]).String(), + }, + expErr: true, + expErrMsg: "missing evidence: invalid evidence", + }, { name: "invalid evidence with height 0", req: invalidEvidence, diff --git a/x/evidence/module.go b/x/evidence/module.go index 255ee7fcc215..a0c4c6fbbf59 100644 --- a/x/evidence/module.go +++ b/x/evidence/module.go @@ -11,6 +11,7 @@ import ( "google.golang.org/grpc" modulev1 "cosmossdk.io/api/cosmos/evidence/module/v1" + "cosmossdk.io/core/address" "cosmossdk.io/core/appmodule" "cosmossdk.io/depinject" @@ -199,8 +200,7 @@ func init() { ) } -//nolint:revive -type EvidenceInputs struct { +type ModuleInputs struct { depinject.In Key *store.KVStoreKey @@ -208,19 +208,19 @@ type EvidenceInputs struct { StakingKeeper types.StakingKeeper SlashingKeeper types.SlashingKeeper + AddressCodec address.Codec } -//nolint:revive -type EvidenceOutputs struct { +type ModuleOutputs struct { depinject.Out EvidenceKeeper keeper.Keeper Module appmodule.AppModule } -func ProvideModule(in EvidenceInputs) EvidenceOutputs { - k := keeper.NewKeeper(in.Cdc, in.Key, in.StakingKeeper, in.SlashingKeeper) +func ProvideModule(in ModuleInputs) ModuleOutputs { + k := keeper.NewKeeper(in.Cdc, in.Key, in.StakingKeeper, in.SlashingKeeper, in.AddressCodec) m := NewAppModule(*k) - return EvidenceOutputs{EvidenceKeeper: *k, Module: m} + return ModuleOutputs{EvidenceKeeper: *k, Module: m} } diff --git a/x/evidence/testutil/expected_keepers_mocks.go b/x/evidence/testutil/expected_keepers_mocks.go index f9021ea468ae..e6b93cdf7f43 100644 --- a/x/evidence/testutil/expected_keepers_mocks.go +++ b/x/evidence/testutil/expected_keepers_mocks.go @@ -5,9 +5,11 @@ package testutil import ( + context "context" reflect "reflect" time "time" + math "cosmossdk.io/math" types "github.com/cosmos/cosmos-sdk/crypto/types" types0 "github.com/cosmos/cosmos-sdk/types" types1 "github.com/cosmos/cosmos-sdk/x/staking/types" @@ -156,7 +158,7 @@ func (mr *MockSlashingKeeperMockRecorder) JailUntil(arg0, arg1, arg2 interface{} } // Slash mocks base method. -func (m *MockSlashingKeeper) Slash(arg0 types0.Context, arg1 types0.ConsAddress, arg2 types0.Dec, arg3, arg4 int64) { +func (m *MockSlashingKeeper) Slash(arg0 types0.Context, arg1 types0.ConsAddress, arg2 math.LegacyDec, arg3, arg4 int64) { m.ctrl.T.Helper() m.ctrl.Call(m, "Slash", arg0, arg1, arg2, arg3, arg4) } @@ -168,10 +170,10 @@ func (mr *MockSlashingKeeperMockRecorder) Slash(arg0, arg1, arg2, arg3, arg4 int } // SlashFractionDoubleSign mocks base method. -func (m *MockSlashingKeeper) SlashFractionDoubleSign(arg0 types0.Context) types0.Dec { +func (m *MockSlashingKeeper) SlashFractionDoubleSign(arg0 types0.Context) math.LegacyDec { m.ctrl.T.Helper() ret := m.ctrl.Call(m, "SlashFractionDoubleSign", arg0) - ret0, _ := ret[0].(types0.Dec) + ret0, _ := ret[0].(math.LegacyDec) return ret0 } @@ -182,7 +184,7 @@ func (mr *MockSlashingKeeperMockRecorder) SlashFractionDoubleSign(arg0 interface } // SlashWithInfractionReason mocks base method. -func (m *MockSlashingKeeper) SlashWithInfractionReason(arg0 types0.Context, arg1 types0.ConsAddress, arg2 types0.Dec, arg3, arg4 int64, arg5 types1.Infraction) { +func (m *MockSlashingKeeper) SlashWithInfractionReason(arg0 types0.Context, arg1 types0.ConsAddress, arg2 math.LegacyDec, arg3, arg4 int64, arg5 types1.Infraction) { m.ctrl.T.Helper() m.ctrl.Call(m, "SlashWithInfractionReason", arg0, arg1, arg2, arg3, arg4, arg5) } @@ -229,7 +231,7 @@ func (m *MockAccountKeeper) EXPECT() *MockAccountKeeperMockRecorder { } // SetAccount mocks base method. -func (m *MockAccountKeeper) SetAccount(ctx types0.Context, acc types0.AccountI) { +func (m *MockAccountKeeper) SetAccount(ctx context.Context, acc types0.AccountI) { m.ctrl.T.Helper() m.ctrl.Call(m, "SetAccount", ctx, acc) } diff --git a/x/evidence/types/expected_keepers.go b/x/evidence/types/expected_keepers.go index f7355ee3a3a8..e21ca0530122 100644 --- a/x/evidence/types/expected_keepers.go +++ b/x/evidence/types/expected_keepers.go @@ -1,8 +1,11 @@ package types import ( + "context" "time" + sdkmath "cosmossdk.io/math" + cryptotypes "github.com/cosmos/cosmos-sdk/crypto/types" sdk "github.com/cosmos/cosmos-sdk/types" stakingtypes "github.com/cosmos/cosmos-sdk/x/staking/types" @@ -23,16 +26,16 @@ type ( IsTombstoned(sdk.Context, sdk.ConsAddress) bool HasValidatorSigningInfo(sdk.Context, sdk.ConsAddress) bool Tombstone(sdk.Context, sdk.ConsAddress) - Slash(sdk.Context, sdk.ConsAddress, sdk.Dec, int64, int64) - SlashWithInfractionReason(sdk.Context, sdk.ConsAddress, sdk.Dec, int64, int64, stakingtypes.Infraction) - SlashFractionDoubleSign(sdk.Context) sdk.Dec + Slash(sdk.Context, sdk.ConsAddress, sdkmath.LegacyDec, int64, int64) + SlashWithInfractionReason(sdk.Context, sdk.ConsAddress, sdkmath.LegacyDec, int64, int64, stakingtypes.Infraction) + SlashFractionDoubleSign(sdk.Context) sdkmath.LegacyDec Jail(sdk.Context, sdk.ConsAddress) JailUntil(sdk.Context, sdk.ConsAddress, time.Time) } // AccountKeeper define the account keeper interface contracted needed by the evidence module AccountKeeper interface { - SetAccount(ctx sdk.Context, acc sdk.AccountI) + SetAccount(ctx context.Context, acc sdk.AccountI) } // BankKeeper define the account keeper interface contracted needed by the evidence module diff --git a/x/evidence/types/msgs.go b/x/evidence/types/msgs.go index f70dd01ae727..10c747174d6c 100644 --- a/x/evidence/types/msgs.go +++ b/x/evidence/types/msgs.go @@ -3,13 +3,11 @@ package types import ( "fmt" - errorsmod "cosmossdk.io/errors" "cosmossdk.io/x/evidence/exported" "github.com/cosmos/gogoproto/proto" "github.com/cosmos/cosmos-sdk/codec/types" sdk "github.com/cosmos/cosmos-sdk/types" - sdkerrors "github.com/cosmos/cosmos-sdk/types/errors" "github.com/cosmos/cosmos-sdk/x/auth/migrations/legacytx" ) @@ -21,8 +19,6 @@ var ( ) // NewMsgSubmitEvidence returns a new MsgSubmitEvidence with a signer/submitter. -// -//nolint:interfacer func NewMsgSubmitEvidence(s sdk.AccAddress, evi exported.Evidence) (*MsgSubmitEvidence, error) { msg, ok := evi.(proto.Message) if !ok { @@ -35,23 +31,6 @@ func NewMsgSubmitEvidence(s sdk.AccAddress, evi exported.Evidence) (*MsgSubmitEv return &MsgSubmitEvidence{Submitter: s.String(), Evidence: any}, nil } -// ValidateBasic performs basic (non-state-dependant) validation on a MsgSubmitEvidence. -func (m MsgSubmitEvidence) ValidateBasic() error { - if _, err := sdk.AccAddressFromBech32(m.Submitter); err != nil { - return sdkerrors.ErrInvalidAddress.Wrapf("invalid submitter address: %s", err) - } - - evi := m.GetEvidence() - if evi == nil { - return errorsmod.Wrap(ErrInvalidEvidence, "missing evidence") - } - if err := evi.ValidateBasic(); err != nil { - return err - } - - return nil -} - // GetSignBytes returns the raw bytes a signer is expected to sign when submitting // a MsgSubmitEvidence message. func (m MsgSubmitEvidence) GetSignBytes() []byte { @@ -65,10 +44,15 @@ func (m MsgSubmitEvidence) GetSigners() []sdk.AccAddress { } func (m MsgSubmitEvidence) GetEvidence() exported.Evidence { + if m.Evidence == nil { + return nil + } + evi, ok := m.Evidence.GetCachedValue().(exported.Evidence) if !ok { return nil } + return evi } diff --git a/x/evidence/types/msgs_test.go b/x/evidence/types/msgs_test.go deleted file mode 100644 index c0c209c5d25a..000000000000 --- a/x/evidence/types/msgs_test.go +++ /dev/null @@ -1,60 +0,0 @@ -package types_test - -import ( - "testing" - "time" - - "cosmossdk.io/x/evidence/exported" - "cosmossdk.io/x/evidence/types" - "github.com/stretchr/testify/require" - - "github.com/cosmos/cosmos-sdk/crypto/keys/ed25519" - sdk "github.com/cosmos/cosmos-sdk/types" -) - -func testMsgSubmitEvidence(t *testing.T, e exported.Evidence, s sdk.AccAddress) exported.MsgSubmitEvidenceI { - msg, err := types.NewMsgSubmitEvidence(s, e) - require.NoError(t, err) - return msg -} - -func TestMsgSubmitEvidence(t *testing.T) { - pk := ed25519.GenPrivKey() - submitter := sdk.AccAddress("test________________") - - testCases := []struct { - msg sdk.Msg - submitter sdk.AccAddress - expectErr bool - }{ - { - testMsgSubmitEvidence(t, &types.Equivocation{ - Height: 0, - Power: 100, - Time: time.Now().UTC(), - ConsensusAddress: pk.PubKey().Address().String(), - }, submitter), - submitter, - true, - }, - { - testMsgSubmitEvidence(t, &types.Equivocation{ - Height: 10, - Power: 100, - Time: time.Now().UTC(), - ConsensusAddress: pk.PubKey().Address().String(), - }, submitter), - submitter, - false, - }, - } - - for i, tc := range testCases { - require.Equal(t, sdk.MsgTypeURL(&types.MsgSubmitEvidence{}), sdk.MsgTypeURL(tc.msg), "unexpected result for tc #%d", i) - require.Equal(t, tc.expectErr, tc.msg.ValidateBasic() != nil, "unexpected result for tc #%d", i) - - if !tc.expectErr { - require.Equal(t, tc.msg.GetSigners(), []sdk.AccAddress{tc.submitter}, "unexpected result for tc #%d", i) - } - } -} diff --git a/x/feegrant/CHANGELOG.md b/x/feegrant/CHANGELOG.md index 8202db4de60e..9dabfb6fa994 100644 --- a/x/feegrant/CHANGELOG.md +++ b/x/feegrant/CHANGELOG.md @@ -31,5 +31,6 @@ Ref: https://keepachangelog.com/en/1.0.0/ ### API Breaking Changes +* [#15606](https://github.com/cosmos/cosmos-sdk/pull/15606) `NewKeeper` now takes a `KVStoreService` instead of a `StoreKey` and methods in the `Keeper` now take a `context.Context` instead of a `sdk.Context`. * [#15347](https://github.com/cosmos/cosmos-sdk/pull/15347) Remove global bech32 usage in keeper. * [#15347](https://github.com/cosmos/cosmos-sdk/pull/15347) `ValidateBasic` is treated as a no op now with with acceptance of RFC001 diff --git a/x/feegrant/basic_fee.go b/x/feegrant/basic_fee.go index 5425afb35dc5..e1eb829f5221 100644 --- a/x/feegrant/basic_fee.go +++ b/x/feegrant/basic_fee.go @@ -1,6 +1,7 @@ package feegrant import ( + "context" time "time" errorsmod "cosmossdk.io/errors" @@ -21,8 +22,8 @@ var _ FeeAllowanceI = (*BasicAllowance)(nil) // // If remove is true (regardless of the error), the FeeAllowance will be deleted from storage // (eg. when it is used up). (See call to RevokeAllowance in Keeper.UseGrantedFees) -func (a *BasicAllowance) Accept(ctx sdk.Context, fee sdk.Coins, _ []sdk.Msg) (bool, error) { - if a.Expiration != nil && a.Expiration.Before(ctx.BlockTime()) { +func (a *BasicAllowance) Accept(ctx context.Context, fee sdk.Coins, _ []sdk.Msg) (bool, error) { + if a.Expiration != nil && a.Expiration.Before(sdk.UnwrapSDKContext(ctx).BlockTime()) { return true, errorsmod.Wrap(ErrFeeLimitExpired, "basic allowance") } diff --git a/x/feegrant/client/cli/tx_test.go b/x/feegrant/client/cli/tx_test.go index c62febd7a3a7..b0e7ffc8d283 100644 --- a/x/feegrant/client/cli/tx_test.go +++ b/x/feegrant/client/cli/tx_test.go @@ -1,13 +1,13 @@ package cli_test import ( - "bytes" "fmt" "io" "strings" "testing" "time" + sdkmath "cosmossdk.io/math" abci "github.com/cometbft/cometbft/abci/types" rpcclientmock "github.com/cometbft/cometbft/rpc/client/mock" "github.com/cosmos/gogoproto/proto" @@ -69,7 +69,6 @@ func (s *CLITestSuite) SetupSuite() { WithOutput(io.Discard). WithChainID("test-chain") - var outBuf bytes.Buffer ctxGen := func() client.Context { bz, _ := s.encCfg.Codec.Marshal(&sdk.TxResponse{}) c := clitestutil.NewMockCometRPC(abci.ResponseQuery{ @@ -78,7 +77,7 @@ func (s *CLITestSuite) SetupSuite() { return s.baseCtx.WithClient(c) } - s.clientCtx = ctxGen().WithOutput(&outBuf) + s.clientCtx = ctxGen() if testing.Short() { s.T().Skip("skipping test in unit-tests mode.") @@ -92,7 +91,7 @@ func (s *CLITestSuite) SetupSuite() { s.createGrant(granter, grantee) grant, err := feegrant.NewGrant(granter, grantee, &feegrant.BasicAllowance{ - SpendLimit: sdk.NewCoins(sdk.NewCoin("stake", sdk.NewInt(100))), + SpendLimit: sdk.NewCoins(sdk.NewCoin("stake", sdkmath.NewInt(100))), }) s.Require().NoError(err) @@ -110,10 +109,10 @@ func (s *CLITestSuite) createGrant(granter, grantee sdk.Address) { commonFlags := []string{ fmt.Sprintf("--%s=%s", flags.FlagBroadcastMode, flags.BroadcastSync), fmt.Sprintf("--%s=true", flags.FlagSkipConfirmation), - fmt.Sprintf("--%s=%s", flags.FlagFees, sdk.NewCoins(sdk.NewCoin("stake", sdk.NewInt(100))).String()), + fmt.Sprintf("--%s=%s", flags.FlagFees, sdk.NewCoins(sdk.NewCoin("stake", sdkmath.NewInt(100))).String()), } - fee := sdk.NewCoin("stake", sdk.NewInt(100)) + fee := sdk.NewCoin("stake", sdkmath.NewInt(100)) args := append( []string{ @@ -147,7 +146,7 @@ func (s *CLITestSuite) TestNewCmdFeeGrant() { commonFlags := []string{ fmt.Sprintf("--%s=%s", flags.FlagBroadcastMode, flags.BroadcastSync), fmt.Sprintf("--%s=true", flags.FlagSkipConfirmation), - fmt.Sprintf("--%s=%s", flags.FlagFees, sdk.NewCoins(sdk.NewCoin("stake", sdk.NewInt(10))).String()), + fmt.Sprintf("--%s=%s", flags.FlagFees, sdk.NewCoins(sdk.NewCoin("stake", sdkmath.NewInt(10))).String()), } testCases := []struct { @@ -434,7 +433,7 @@ func (s *CLITestSuite) TestNewCmdRevokeFeegrant() { commonFlags := []string{ fmt.Sprintf("--%s=%s", flags.FlagBroadcastMode, flags.BroadcastSync), fmt.Sprintf("--%s=true", flags.FlagSkipConfirmation), - fmt.Sprintf("--%s=%s", flags.FlagFees, sdk.NewCoins(sdk.NewCoin("stake", sdk.NewInt(10))).String()), + fmt.Sprintf("--%s=%s", flags.FlagFees, sdk.NewCoins(sdk.NewCoin("stake", sdkmath.NewInt(10))).String()), } addressCodec := codecaddress.NewBech32Codec("cosmos") @@ -533,10 +532,10 @@ func (s *CLITestSuite) TestTxWithFeeGrant() { commonFlags := []string{ fmt.Sprintf("--%s=%s", flags.FlagBroadcastMode, flags.BroadcastSync), fmt.Sprintf("--%s=true", flags.FlagSkipConfirmation), - fmt.Sprintf("--%s=%s", flags.FlagFees, sdk.NewCoins(sdk.NewCoin("stake", sdk.NewInt(10))).String()), + fmt.Sprintf("--%s=%s", flags.FlagFees, sdk.NewCoins(sdk.NewCoin("stake", sdkmath.NewInt(10))).String()), } - fee := sdk.NewCoin("stake", sdk.NewInt(100)) + fee := sdk.NewCoin("stake", sdkmath.NewInt(100)) args := append( []string{ @@ -610,7 +609,7 @@ func (s *CLITestSuite) msgSubmitLegacyProposal(clientCtx client.Context, from, t commonArgs := []string{ fmt.Sprintf("--%s=true", flags.FlagSkipConfirmation), fmt.Sprintf("--%s=%s", flags.FlagBroadcastMode, flags.BroadcastSync), - fmt.Sprintf("--%s=%s", flags.FlagFees, sdk.NewCoins(sdk.NewCoin(sdk.DefaultBondDenom, sdk.NewInt(10))).String()), + fmt.Sprintf("--%s=%s", flags.FlagFees, sdk.NewCoins(sdk.NewCoin(sdk.DefaultBondDenom, sdkmath.NewInt(10))).String()), } args := append([]string{ @@ -639,24 +638,20 @@ func (s *CLITestSuite) TestFilteredFeeAllowance() { pub, err := k.GetPubKey() s.Require().NoError(err) grantee := sdk.AccAddress(pub.Address()) - clientCtx := s.clientCtx commonFlags := []string{ fmt.Sprintf("--%s=%s", flags.FlagBroadcastMode, flags.BroadcastSync), fmt.Sprintf("--%s=true", flags.FlagSkipConfirmation), - fmt.Sprintf("--%s=%s", flags.FlagFees, sdk.NewCoins(sdk.NewCoin(sdk.DefaultBondDenom, sdk.NewInt(100))).String()), + fmt.Sprintf("--%s=%s", flags.FlagFees, sdk.NewCoins(sdk.NewCoin(sdk.DefaultBondDenom, sdkmath.NewInt(100))).String()), } - spendLimit := sdk.NewCoin("stake", sdk.NewInt(1000)) - + spendLimit := sdk.NewCoin("stake", sdkmath.NewInt(1000)) allowMsgs := strings.Join([]string{sdk.MsgTypeURL(&govv1beta1.MsgSubmitProposal{}), sdk.MsgTypeURL(&govv1.MsgVoteWeighted{})}, ",") testCases := []struct { name string args []string - expectErr bool - respType proto.Message - expectedCode uint32 + expectErrMsg string }{ { "invalid granter address", @@ -670,7 +665,7 @@ func (s *CLITestSuite) TestFilteredFeeAllowance() { }, commonFlags..., ), - true, &sdk.TxResponse{}, 0, + "key not found", }, { "invalid grantee address", @@ -684,7 +679,7 @@ func (s *CLITestSuite) TestFilteredFeeAllowance() { }, commonFlags..., ), - true, &sdk.TxResponse{}, 0, + "decoding bech32 failed", }, { "valid filter fee grant", @@ -698,7 +693,7 @@ func (s *CLITestSuite) TestFilteredFeeAllowance() { }, commonFlags..., ), - false, &sdk.TxResponse{}, 0, + "", }, } @@ -708,22 +703,21 @@ func (s *CLITestSuite) TestFilteredFeeAllowance() { s.Run(tc.name, func() { cmd := cli.NewCmdFeeGrant(codecaddress.NewBech32Codec("cosmos")) out, err := clitestutil.ExecTestCLICmd(clientCtx, cmd, tc.args) - - if tc.expectErr { + if tc.expectErrMsg != "" { s.Require().Error(err) + s.Require().Contains(err.Error(), tc.expectErrMsg) } else { s.Require().NoError(err) - s.Require().NoError(clientCtx.Codec.UnmarshalJSON(out.Bytes(), tc.respType), out.String()) + msg := &sdk.TxResponse{} + s.Require().NoError(clientCtx.Codec.UnmarshalJSON(out.Bytes(), msg), out.String()) } }) } // exec filtered fee allowance cases := []struct { - name string - malleate func() error - respType proto.Message - expectedCode uint32 + name string + malleate func() error }{ { "valid proposal tx", @@ -731,22 +725,18 @@ func (s *CLITestSuite) TestFilteredFeeAllowance() { return s.msgSubmitLegacyProposal(s.baseCtx, grantee.String(), "Text Proposal", "No desc", govv1beta1.ProposalTypeText, fmt.Sprintf("--%s=%s", flags.FlagFeeGranter, granter.String()), - fmt.Sprintf("--%s=%s", flags.FlagFees, sdk.NewCoins(sdk.NewCoin(sdk.DefaultBondDenom, sdk.NewInt(100))).String()), + fmt.Sprintf("--%s=%s", flags.FlagFees, sdk.NewCoins(sdk.NewCoin(sdk.DefaultBondDenom, sdkmath.NewInt(100))).String()), ) }, - &sdk.TxResponse{}, - 0, }, { "valid weighted_vote tx", func() error { return s.msgVote(s.baseCtx, grantee.String(), "0", "yes", fmt.Sprintf("--%s=%s", flags.FlagFeeGranter, granter.String()), - fmt.Sprintf("--%s=%s", flags.FlagFees, sdk.NewCoins(sdk.NewCoin(sdk.DefaultBondDenom, sdk.NewInt(100))).String()), + fmt.Sprintf("--%s=%s", flags.FlagFees, sdk.NewCoins(sdk.NewCoin(sdk.DefaultBondDenom, sdkmath.NewInt(100))).String()), ) }, - &sdk.TxResponse{}, - 2, }, { "should fail with unauthorized msgs", @@ -767,8 +757,6 @@ func (s *CLITestSuite) TestFilteredFeeAllowance() { return err }, - &sdk.TxResponse{}, - 7, }, } @@ -787,7 +775,7 @@ func (s *CLITestSuite) msgVote(clientCtx client.Context, from, id, vote string, commonArgs := []string{ fmt.Sprintf("--%s=true", flags.FlagSkipConfirmation), fmt.Sprintf("--%s=%s", flags.FlagBroadcastMode, flags.BroadcastSync), - fmt.Sprintf("--%s=%s", flags.FlagFees, sdk.NewCoins(sdk.NewCoin(sdk.DefaultBondDenom, sdk.NewInt(10))).String()), + fmt.Sprintf("--%s=%s", flags.FlagFees, sdk.NewCoins(sdk.NewCoin(sdk.DefaultBondDenom, sdkmath.NewInt(10))).String()), } args := append([]string{ id, diff --git a/x/feegrant/expected_keepers.go b/x/feegrant/expected_keepers.go index 1ec0ddeff2eb..d796675db59f 100644 --- a/x/feegrant/expected_keepers.go +++ b/x/feegrant/expected_keepers.go @@ -1,22 +1,23 @@ package feegrant import ( + "context" + + "cosmossdk.io/core/address" + sdk "github.com/cosmos/cosmos-sdk/types" ) // AccountKeeper defines the expected auth Account Keeper (noalias) type AccountKeeper interface { - GetModuleAddress(moduleName string) sdk.AccAddress - GetModuleAccount(ctx sdk.Context, moduleName string) sdk.ModuleAccountI + address.Codec - NewAccountWithAddress(ctx sdk.Context, addr sdk.AccAddress) sdk.AccountI - GetAccount(ctx sdk.Context, addr sdk.AccAddress) sdk.AccountI - SetAccount(ctx sdk.Context, acc sdk.AccountI) + GetModuleAddress(moduleName string) sdk.AccAddress + GetModuleAccount(ctx context.Context, moduleName string) sdk.ModuleAccountI - // StringToBytes decodes text to bytes - StringToBytes(text string) ([]byte, error) - // BytesToString encodes bytes to text - BytesToString(bz []byte) (string, error) + NewAccountWithAddress(ctx context.Context, addr sdk.AccAddress) sdk.AccountI + GetAccount(ctx context.Context, addr sdk.AccAddress) sdk.AccountI + SetAccount(ctx context.Context, acc sdk.AccountI) } // BankKeeper defines the expected supply Keeper (noalias) diff --git a/x/feegrant/fees.go b/x/feegrant/fees.go index 9b2c03338685..b6191204d5dd 100644 --- a/x/feegrant/fees.go +++ b/x/feegrant/fees.go @@ -1,6 +1,7 @@ package feegrant import ( + "context" "time" sdk "github.com/cosmos/cosmos-sdk/types" @@ -19,7 +20,7 @@ type FeeAllowanceI interface { // // If remove is true (regardless of the error), the FeeAllowance will be deleted from storage // (eg. when it is used up). (See call to RevokeAllowance in Keeper.UseGrantedFees) - Accept(ctx sdk.Context, fee sdk.Coins, msgs []sdk.Msg) (remove bool, err error) + Accept(ctx context.Context, fee sdk.Coins, msgs []sdk.Msg) (remove bool, err error) // ValidateBasic should evaluate this FeeAllowance for internal consistency. // Don't allow negative amounts, or negative periods for example. diff --git a/x/feegrant/filtered_fee.go b/x/feegrant/filtered_fee.go index fea737177476..4af34e95eea2 100644 --- a/x/feegrant/filtered_fee.go +++ b/x/feegrant/filtered_fee.go @@ -1,6 +1,7 @@ package feegrant import ( + "context" "time" errorsmod "cosmossdk.io/errors" @@ -67,8 +68,8 @@ func (a *AllowedMsgAllowance) SetAllowance(allowance FeeAllowanceI) error { } // Accept method checks for the filtered messages has valid expiry -func (a *AllowedMsgAllowance) Accept(ctx sdk.Context, fee sdk.Coins, msgs []sdk.Msg) (bool, error) { - if !a.allMsgTypesAllowed(ctx, msgs) { +func (a *AllowedMsgAllowance) Accept(ctx context.Context, fee sdk.Coins, msgs []sdk.Msg) (bool, error) { + if !a.allMsgTypesAllowed(sdk.UnwrapSDKContext(ctx), msgs) { return false, errorsmod.Wrap(ErrMessageNotAllowed, "message does not exist in allowed messages") } diff --git a/x/feegrant/go.mod b/x/feegrant/go.mod index 6cf8f6b20be6..d8d0380eb6e2 100644 --- a/x/feegrant/go.mod +++ b/x/feegrant/go.mod @@ -3,31 +3,31 @@ module cosmossdk.io/x/feegrant go 1.20 require ( - cosmossdk.io/api v0.3.2-0.20230313131911-55bf5d4efbe7 + cosmossdk.io/api v0.4.0 cosmossdk.io/core v0.6.1 cosmossdk.io/depinject v1.0.0-alpha.3 cosmossdk.io/errors v1.0.0-beta.7 - cosmossdk.io/log v0.1.0 + cosmossdk.io/log v1.0.0 cosmossdk.io/math v1.0.0 - cosmossdk.io/store v0.1.0-alpha.1 - github.com/cometbft/cometbft v0.37.0 + cosmossdk.io/store v0.1.0-alpha.1.0.20230328185921-37ba88872dbc + github.com/cometbft/cometbft v0.37.1-0.20230411132551-3a91d155e664 github.com/cosmos/cosmos-proto v1.0.0-beta.3 - github.com/cosmos/cosmos-sdk v0.46.0-beta2.0.20230324171029-0176e313261d - github.com/cosmos/gogoproto v1.4.6 + github.com/cosmos/cosmos-sdk v0.46.0-beta2.0.20230419124727-7b10ada768f4 + github.com/cosmos/gogoproto v1.4.8 github.com/golang/mock v1.6.0 github.com/golang/protobuf v1.5.3 github.com/grpc-ecosystem/grpc-gateway v1.16.0 - github.com/spf13/cobra v1.6.1 + github.com/spf13/cobra v1.7.0 github.com/stretchr/testify v1.8.2 - google.golang.org/genproto v0.0.0-20230320184635-7606e756e683 + google.golang.org/genproto v0.0.0-20230410155749-daa745c078e1 google.golang.org/grpc v1.54.0 google.golang.org/protobuf v1.30.0 gotest.tools/v3 v3.4.0 ) require ( - cosmossdk.io/collections v0.0.0-20230309163709-87da587416ba // indirect - cosmossdk.io/x/tx v0.3.1-0.20230321155358-6522dd1731b5 // indirect + cosmossdk.io/collections v0.1.0 // indirect + cosmossdk.io/x/tx v0.5.1-0.20230407182919-057d2e09bd63 // indirect filippo.io/edwards25519 v1.0.0 // indirect github.com/99designs/go-keychain v0.0.0-20191008050251-8e49817e8af4 // indirect github.com/99designs/keyring v1.2.1 // indirect @@ -43,7 +43,7 @@ require ( github.com/chzyer/readline v1.5.1 // indirect github.com/cockroachdb/errors v1.9.1 // indirect github.com/cockroachdb/logtags v0.0.0-20230118201751-21c54148d20b // indirect - github.com/cockroachdb/pebble v0.0.0-20230315223031-1e5ddd10389e // indirect + github.com/cockroachdb/pebble v0.0.0-20230412222916-60cfeb46143b // indirect github.com/cockroachdb/redact v1.1.3 // indirect github.com/cometbft/cometbft-db v0.7.0 // indirect github.com/confio/ics23/go v0.9.0 // indirect @@ -56,7 +56,7 @@ require ( github.com/creachadair/taskgroup v0.4.2 // indirect github.com/danieljoos/wincred v1.1.2 // indirect github.com/davecgh/go-spew v1.1.1 // indirect - github.com/decred/dcrd/dcrec/secp256k1/v4 v4.1.0 // indirect + github.com/decred/dcrd/dcrec/secp256k1/v4 v4.2.0 // indirect github.com/desertbit/timer v0.0.0-20180107155436-c41aec40b27f // indirect github.com/dgraph-io/badger/v2 v2.2007.4 // indirect github.com/dgraph-io/ristretto v0.1.1 // indirect @@ -66,7 +66,7 @@ require ( github.com/fatih/color v1.15.0 // indirect github.com/felixge/httpsnoop v1.0.2 // indirect github.com/fsnotify/fsnotify v1.6.0 // indirect - github.com/getsentry/sentry-go v0.19.0 // indirect + github.com/getsentry/sentry-go v0.20.0 // indirect github.com/go-kit/kit v0.12.0 // indirect github.com/go-kit/log v0.2.1 // indirect github.com/go-logfmt/logfmt v0.6.0 // indirect @@ -96,12 +96,12 @@ require ( github.com/improbable-eng/grpc-web v0.15.0 // indirect github.com/inconshreveable/mousetrap v1.1.0 // indirect github.com/jmhodges/levigo v1.0.0 // indirect - github.com/klauspost/compress v1.16.3 // indirect + github.com/klauspost/compress v1.16.5 // indirect github.com/kr/pretty v0.3.1 // indirect github.com/kr/text v0.2.0 // indirect github.com/lib/pq v1.10.7 // indirect github.com/libp2p/go-buffer-pool v0.1.0 // indirect - github.com/linxGnu/grocksdb v1.7.15 // indirect + github.com/linxGnu/grocksdb v1.7.16 // indirect github.com/magiconair/properties v1.8.7 // indirect github.com/manifoldco/promptui v0.9.0 // indirect github.com/mattn/go-colorable v0.1.13 // indirect @@ -117,14 +117,14 @@ require ( github.com/petermattis/goid v0.0.0-20230317030725-371a4b8eda08 // indirect github.com/pkg/errors v0.9.1 // indirect github.com/pmezard/go-difflib v1.0.0 // indirect - github.com/prometheus/client_golang v1.14.0 // indirect + github.com/prometheus/client_golang v1.15.0 // indirect github.com/prometheus/client_model v0.3.0 // indirect github.com/prometheus/common v0.42.0 // indirect github.com/prometheus/procfs v0.9.0 // indirect github.com/rcrowley/go-metrics v0.0.0-20201227073835-cf1acfcdf475 // indirect - github.com/rogpeppe/go-internal v1.9.0 // indirect + github.com/rogpeppe/go-internal v1.10.0 // indirect github.com/rs/cors v1.8.3 // indirect - github.com/rs/zerolog v1.29.0 // indirect + github.com/rs/zerolog v1.29.1 // indirect github.com/sasha-s/go-deadlock v0.3.1 // indirect github.com/spf13/afero v1.9.3 // indirect github.com/spf13/cast v1.5.0 // indirect @@ -139,13 +139,13 @@ require ( github.com/zondax/hid v0.9.1 // indirect github.com/zondax/ledger-go v0.14.1 // indirect go.etcd.io/bbolt v1.3.6 // indirect - golang.org/x/crypto v0.7.0 // indirect + golang.org/x/crypto v0.8.0 // indirect golang.org/x/exp v0.0.0-20230321023759-10a507213a29 // indirect - golang.org/x/net v0.8.0 // indirect + golang.org/x/net v0.9.0 // indirect golang.org/x/sync v0.1.0 // indirect - golang.org/x/sys v0.6.0 // indirect - golang.org/x/term v0.6.0 // indirect - golang.org/x/text v0.8.0 // indirect + golang.org/x/sys v0.7.0 // indirect + golang.org/x/term v0.7.0 // indirect + golang.org/x/text v0.9.0 // indirect gopkg.in/ini.v1 v1.67.0 // indirect gopkg.in/yaml.v2 v2.4.0 // indirect gopkg.in/yaml.v3 v3.0.1 // indirect diff --git a/x/feegrant/go.sum b/x/feegrant/go.sum index 67eed43ad41d..a6d5922f9a3c 100644 --- a/x/feegrant/go.sum +++ b/x/feegrant/go.sum @@ -35,24 +35,24 @@ cloud.google.com/go/storage v1.6.0/go.mod h1:N7U0C8pVQ/+NIKOBQyamJIeKQKkZ+mxpohl cloud.google.com/go/storage v1.8.0/go.mod h1:Wv1Oy7z6Yz3DshWRJFhqM/UCfaWIRTdp0RXyy7KQOVs= cloud.google.com/go/storage v1.10.0/go.mod h1:FLPqc6j+Ki4BU591ie1oL6qBQGu2Bl/tZ9ullr3+Kg0= cloud.google.com/go/storage v1.14.0/go.mod h1:GrKmX003DSIwi9o29oFT7YDnHYwZoctc3fOKtUw0Xmo= -cosmossdk.io/api v0.3.2-0.20230313131911-55bf5d4efbe7 h1:4LrWK+uGP5IxznxtHHsHD+ZBs2+oZRH2loYOGjHLzZM= -cosmossdk.io/api v0.3.2-0.20230313131911-55bf5d4efbe7/go.mod h1:yVns7mKgcsG+hZW/3C5FdJtC6QYWdFIcRlKb9+5HV5g= -cosmossdk.io/collections v0.0.0-20230309163709-87da587416ba h1:S4PYij/tX3Op/hwenVEN9D+M27JRcwSwVqE3UA0BnwM= -cosmossdk.io/collections v0.0.0-20230309163709-87da587416ba/go.mod h1:lpS+G8bGC2anqzWdndTzjnQnuMO/qAcgZUkGJp4i3rc= +cosmossdk.io/api v0.4.0 h1:x90DmdidP6EhzktAa/6/IofSHidDnPjahdlrUvyQZQw= +cosmossdk.io/api v0.4.0/go.mod h1:TWDzBhUBhI1LhSf2XSYpfIBf6D4mbLu/fvzvDfhcaYM= +cosmossdk.io/collections v0.1.0 h1:nzJGeiq32KnZroSrhB6rPifw4I85Cgmzw/YAmr4luv8= +cosmossdk.io/collections v0.1.0/go.mod h1:xbauc0YsbUF8qKMVeBZl0pFCunxBIhKN/WlxpZ3lBuo= cosmossdk.io/core v0.6.1 h1:OBy7TI2W+/gyn2z40vVvruK3di+cAluinA6cybFbE7s= cosmossdk.io/core v0.6.1/go.mod h1:g3MMBCBXtxbDWBURDVnJE7XML4BG5qENhs0gzkcpuFA= cosmossdk.io/depinject v1.0.0-alpha.3 h1:6evFIgj//Y3w09bqOUOzEpFj5tsxBqdc5CfkO7z+zfw= cosmossdk.io/depinject v1.0.0-alpha.3/go.mod h1:eRbcdQ7MRpIPEM5YUJh8k97nxHpYbc3sMUnEtt8HPWU= cosmossdk.io/errors v1.0.0-beta.7 h1:gypHW76pTQGVnHKo6QBkb4yFOJjC+sUGRc5Al3Odj1w= cosmossdk.io/errors v1.0.0-beta.7/go.mod h1:mz6FQMJRku4bY7aqS/Gwfcmr/ue91roMEKAmDUDpBfE= -cosmossdk.io/log v0.1.0 h1:Vnexi+KzUCjmqq/m93teAxjt5biWFfZ5PI1imx2IJw8= -cosmossdk.io/log v0.1.0/go.mod h1:p95Wq6mDY3SREMc4y7+QU9Uwy3nyvfpWGD1iSaFkVFs= +cosmossdk.io/log v1.0.0 h1:NGKZ/A5rd4PduDfoscgABklX557PWjQINbosZy/m3Jk= +cosmossdk.io/log v1.0.0/go.mod h1:CwX9BLiBruZb7lzLlRr3R231d/fVPUXk8gAdV4LQap0= cosmossdk.io/math v1.0.0 h1:ro9w7eKx23om2tZz/VM2Pf+z2WAbGX1yDQQOJ6iGeJw= cosmossdk.io/math v1.0.0/go.mod h1:Ygz4wBHrgc7g0N+8+MrnTfS9LLn9aaTGa9hKopuym5k= -cosmossdk.io/store v0.1.0-alpha.1 h1:NGomhLUXzAxvK4OF8+yP6eNUG5i4LwzOzx+S494pTCg= -cosmossdk.io/store v0.1.0-alpha.1/go.mod h1:kmCMbhrleCZ6rDZPY/EGNldNvPebFNyVPFYp+pv05/k= -cosmossdk.io/x/tx v0.3.1-0.20230321155358-6522dd1731b5 h1:AlvyRc7f7Py1mv254vrqjIIuykCnitHIz2T+nup3bU0= -cosmossdk.io/x/tx v0.3.1-0.20230321155358-6522dd1731b5/go.mod h1:FNkSEMbLP9NFdTfrbslNUtNS7OXf3wgZeJyXzfRPa4c= +cosmossdk.io/store v0.1.0-alpha.1.0.20230328185921-37ba88872dbc h1:9piuA+NYmhe+SyMPtMoboLw/djgDbrI3dD5TG020Tnk= +cosmossdk.io/store v0.1.0-alpha.1.0.20230328185921-37ba88872dbc/go.mod h1:UFF5rmjN7WYVfxo6ArdY/l1+yyWMURBWOmSJypGqFHQ= +cosmossdk.io/x/tx v0.5.1-0.20230407182919-057d2e09bd63 h1:zHqj2VwZ/MStFmR7SUe/7gErOFhL9v2rkjmWPB/st34= +cosmossdk.io/x/tx v0.5.1-0.20230407182919-057d2e09bd63/go.mod h1:Oh3Kh+IPOfMEILNxVd2e8SLqRrIjYHpdGBfDg4ghU/k= dmitri.shuralyov.com/gpu/mtl v0.0.0-20190408044501-666a987793e9/go.mod h1:H6x//7gZCb22OMCxBHrMx7a5I7Hp++hsVxbQ4BYO7hU= filippo.io/edwards25519 v1.0.0 h1:0wAIcmJUqRdI8IJ/3eGi5/HwXZWPujYXXlkrQogz0Ek= filippo.io/edwards25519 v1.0.0/go.mod h1:N1IkdkCkiLB6tki+MYJoSx2JTY9NUlxZE7eHn5EwJns= @@ -113,6 +113,7 @@ github.com/beorn7/perks v1.0.1/go.mod h1:G2ZrVWU2WbWT9wwq4/hrbKbnv/1ERSJQ0ibhJ6r github.com/bgentry/speakeasy v0.1.0/go.mod h1:+zsyZBPWlz7T6j88CTgSN5bM796AkVf0kBD4zp0CCIs= github.com/bgentry/speakeasy v0.1.1-0.20220910012023-760eaf8b6816 h1:41iFGWnSlI2gVpmOtVTJZNodLdLQLn/KsJqFvXwnd/s= github.com/bgentry/speakeasy v0.1.1-0.20220910012023-760eaf8b6816/go.mod h1:+zsyZBPWlz7T6j88CTgSN5bM796AkVf0kBD4zp0CCIs= +github.com/bits-and-blooms/bitset v1.6.0 h1:FVfaUsleKAUTJnaN9Fd1YFFi1S8vAX5xeXnXHFYOojM= github.com/btcsuite/btcd/btcec/v2 v2.3.2 h1:5n0X6hX0Zk+6omWcihdYvdAlGf2DfasC0GMf7DClJ3U= github.com/btcsuite/btcd/btcec/v2 v2.3.2/go.mod h1:zYzJ8etWJQIv1Ogk7OzpWjowwOdXY1W/17j2MW85J04= github.com/btcsuite/btcd/btcutil v1.1.2 h1:XLMbX8JQEiwMcYft2EGi8zPUkoa0abKIU6/BJSRsjzQ= @@ -161,14 +162,14 @@ github.com/cockroachdb/errors v1.9.1/go.mod h1:2sxOtL2WIc096WSZqZ5h8fa17rdDq9HZO github.com/cockroachdb/logtags v0.0.0-20211118104740-dabe8e521a4f/go.mod h1:Vz9DsVWQQhf3vs21MhPMZpMGSht7O/2vFW2xusFUVOs= github.com/cockroachdb/logtags v0.0.0-20230118201751-21c54148d20b h1:r6VH0faHjZeQy818SGhaone5OnYfxFR/+AzdY3sf5aE= github.com/cockroachdb/logtags v0.0.0-20230118201751-21c54148d20b/go.mod h1:Vz9DsVWQQhf3vs21MhPMZpMGSht7O/2vFW2xusFUVOs= -github.com/cockroachdb/pebble v0.0.0-20230315223031-1e5ddd10389e h1:CDuLmyaZ1pD4OJHHtubKqgu/Byw5zAnm+gArJsyj96Q= -github.com/cockroachdb/pebble v0.0.0-20230315223031-1e5ddd10389e/go.mod h1:9lRMC4XN3/BLPtIp6kAKwIaHu369NOf2rMucPzipz50= +github.com/cockroachdb/pebble v0.0.0-20230412222916-60cfeb46143b h1:92ve6F1Pls/eqd+V+102lOMRJatgpqqsQvbT9Bl/fjg= +github.com/cockroachdb/pebble v0.0.0-20230412222916-60cfeb46143b/go.mod h1:9lRMC4XN3/BLPtIp6kAKwIaHu369NOf2rMucPzipz50= github.com/cockroachdb/redact v1.1.3 h1:AKZds10rFSIj7qADf0g46UixK8NNLwWTNdCIGS5wfSQ= github.com/cockroachdb/redact v1.1.3/go.mod h1:BVNblN9mBWFyMyqK1k3AAiSxhvhfK2oOZZ2lK+dpvRg= github.com/codahale/hdrhistogram v0.0.0-20161010025455-3a0bb77429bd/go.mod h1:sE/e/2PUdi/liOCUjSTXgM1o87ZssimdTWN964YiIeI= github.com/codegangsta/inject v0.0.0-20150114235600-33e0aa1cb7c0/go.mod h1:4Zcjuz89kmFXt9morQgcfYZAYZ5n8WHjt81YYWIwtTM= -github.com/cometbft/cometbft v0.37.0 h1:M005vBaSaugvYYmNZwJOopynQSjwLoDTwflnQ/I/eYk= -github.com/cometbft/cometbft v0.37.0/go.mod h1:Y2MMMN//O5K4YKd8ze4r9jmk4Y7h0ajqILXbH5JQFVs= +github.com/cometbft/cometbft v0.37.1-0.20230411132551-3a91d155e664 h1:BbCkbnaU3R603XpnbqvuDU8Kfv+hjhiFILOHhVFntsw= +github.com/cometbft/cometbft v0.37.1-0.20230411132551-3a91d155e664/go.mod h1:Y2MMMN//O5K4YKd8ze4r9jmk4Y7h0ajqILXbH5JQFVs= github.com/cometbft/cometbft-db v0.7.0 h1:uBjbrBx4QzU0zOEnU8KxoDl18dMNgDh+zZRUE0ucsbo= github.com/cometbft/cometbft-db v0.7.0/go.mod h1:yiKJIm2WKrt6x8Cyxtq9YTEcIMPcEe4XPxhgX59Fzf0= github.com/confio/ics23/go v0.9.0 h1:cWs+wdbS2KRPZezoaaj+qBleXgUk5WOQFMP3CQFGTr4= @@ -178,7 +179,7 @@ github.com/coreos/etcd v3.3.10+incompatible/go.mod h1:uF7uidLiAD3TWHmW31ZFd/JWoc github.com/coreos/go-etcd v2.0.0+incompatible/go.mod h1:Jez6KQU2B/sWsbdaef3ED8NzMklzPG4d5KIOhIy30Tk= github.com/coreos/go-semver v0.2.0/go.mod h1:nnelYz7RCh+5ahJtPPxZlU+153eP4D4r3EedlOD2RNk= github.com/coreos/go-systemd v0.0.0-20180511133405-39ca1b05acc7/go.mod h1:F5haX7vjVVG0kc13fIWeqUViNPyEJxv/OmvnBo0Yme4= -github.com/coreos/go-systemd/v22 v22.3.3-0.20220203105225-a9a7ef127534/go.mod h1:Y58oyj3AT4RCenI/lSvhwexgC+NSVTIJ3seZv2GcEnc= +github.com/coreos/go-systemd/v22 v22.5.0/go.mod h1:Y58oyj3AT4RCenI/lSvhwexgC+NSVTIJ3seZv2GcEnc= github.com/coreos/pkg v0.0.0-20160727233714-3ac0863d7acf/go.mod h1:E3G3o1h8I7cfcXa63jLwjI0eiQQMgzzUDFVpN/nH/eA= github.com/cosmos/btcutil v1.0.5 h1:t+ZFcX77LpKtDBhjucvnOH8C2l2ioGsBNEQ3jef8xFk= github.com/cosmos/btcutil v1.0.5/go.mod h1:IyB7iuqZMJlthe2tkIFL33xPyzbFYP0XVdS8P5lUPis= @@ -186,16 +187,16 @@ github.com/cosmos/cosmos-db v1.0.0-rc.1 h1:SjnT8B6WKMW9WEIX32qMhnEEKcI7ZP0+G1Sa9 github.com/cosmos/cosmos-db v1.0.0-rc.1/go.mod h1:Dnmk3flSf5lkwCqvvjNpoxjpXzhxnCAFzKHlbaForso= github.com/cosmos/cosmos-proto v1.0.0-beta.3 h1:VitvZ1lPORTVxkmF2fAp3IiA61xVwArQYKXTdEcpW6o= github.com/cosmos/cosmos-proto v1.0.0-beta.3/go.mod h1:t8IASdLaAq+bbHbjq4p960BvcTqtwuAxid3b/2rOD6I= -github.com/cosmos/cosmos-sdk v0.46.0-beta2.0.20230324171029-0176e313261d h1:FmHvrGoLwiF/4UviweBbWtpEXcNo6IOjnZMgNHcP4mU= -github.com/cosmos/cosmos-sdk v0.46.0-beta2.0.20230324171029-0176e313261d/go.mod h1:X5eCGsQaPQWvFwRzAbneZZaLjnZcral+yoLqAN2QTRI= +github.com/cosmos/cosmos-sdk v0.46.0-beta2.0.20230419124727-7b10ada768f4 h1:tZ2vcNWznBxIIK37nlgrh4n/n5aQv0KY6VzIb86xTNs= +github.com/cosmos/cosmos-sdk v0.46.0-beta2.0.20230419124727-7b10ada768f4/go.mod h1:BPvKPN63ettXrpz67uM1rHEqX/UVVkAfceFCPyp217E= github.com/cosmos/go-bip39 v0.0.0-20180819234021-555e2067c45d/go.mod h1:tSxLoYXyBmiFeKpvmq4dzayMdCjCnu8uqmCysIGBT2Y= github.com/cosmos/go-bip39 v1.0.0 h1:pcomnQdrdH22njcAatO0yWojsUnCO3y2tNoV1cb6hHY= github.com/cosmos/go-bip39 v1.0.0/go.mod h1:RNJv0H/pOIVgxw6KS7QeX2a0Uo0aKUlfhZ4xuwvCdJw= github.com/cosmos/gogogateway v1.2.0 h1:Ae/OivNhp8DqBi/sh2A8a1D0y638GpL3tkmLQAiKxTE= github.com/cosmos/gogogateway v1.2.0/go.mod h1:iQpLkGWxYcnCdz5iAdLcRBSw3h7NXeOkZ4GUkT+tbFI= github.com/cosmos/gogoproto v1.4.2/go.mod h1:cLxOsn1ljAHSV527CHOtaIP91kK6cCrZETRBrkzItWU= -github.com/cosmos/gogoproto v1.4.6 h1:Ee7z15dWJaGlgM2rWrK8N2IX7PQcuccu8oG68jp5RL4= -github.com/cosmos/gogoproto v1.4.6/go.mod h1:VS/ASYmPgv6zkPKLjR9EB91lwbLHOzaGCirmKKhncfI= +github.com/cosmos/gogoproto v1.4.8 h1:BrHKc6WFZt8+jRV71vKSQE+JrfF+JAnzrKo2VP7wIZ4= +github.com/cosmos/gogoproto v1.4.8/go.mod h1:hnb0DIEWTv+wdNzNcqus5xCQXq5+CXauq1FJuurRfVY= github.com/cosmos/iavl v0.21.0-beta.1 h1:fBQeBc8HLZ14plJNcmGfaOXSSMLVEHvEQXiTXSD76m0= github.com/cosmos/iavl v0.21.0-beta.1/go.mod h1:25YJYzilTErJ2mKfNB3xyWL9IsCwEQdNzdIutg2mh3U= github.com/cosmos/ledger-cosmos-go v0.13.0 h1:ex0CvCxToSR7j5WjrghPu2Bu9sSXKikjnVvUryNnx4s= @@ -214,9 +215,9 @@ github.com/danieljoos/wincred v1.1.2/go.mod h1:GijpziifJoIBfYh+S7BbkdUTU4LfM+QnG github.com/davecgh/go-spew v1.1.0/go.mod h1:J7Y8YcW2NihsgmVo/mv3lAwl/skON4iLHjSsI+c5H38= github.com/davecgh/go-spew v1.1.1 h1:vj9j/u1bqnvCEfJOwUhtlOARqs3+rkHYY13jYWTU97c= github.com/davecgh/go-spew v1.1.1/go.mod h1:J7Y8YcW2NihsgmVo/mv3lAwl/skON4iLHjSsI+c5H38= -github.com/decred/dcrd/crypto/blake256 v1.0.0 h1:/8DMNYp9SGi5f0w7uCm6d6M4OU2rGFK09Y2A4Xv7EE0= -github.com/decred/dcrd/dcrec/secp256k1/v4 v4.1.0 h1:HbphB4TFFXpv7MNrT52FGrrgVXF1owhMVTHFZIlnvd4= -github.com/decred/dcrd/dcrec/secp256k1/v4 v4.1.0/go.mod h1:DZGJHZMqrU4JJqFAWUS2UO1+lbSKsdiOoYi9Zzey7Fc= +github.com/decred/dcrd/crypto/blake256 v1.0.1 h1:7PltbUIQB7u/FfZ39+DGa/ShuMyJ5ilcvdfma9wOH6Y= +github.com/decred/dcrd/dcrec/secp256k1/v4 v4.2.0 h1:8UrgZ3GkP4i/CLijOJx79Yu+etlyjdBU4sfcs2WYQMs= +github.com/decred/dcrd/dcrec/secp256k1/v4 v4.2.0/go.mod h1:v57UDF4pDQJcEfFUCRop3lJL149eHGSe9Jvczhzjo/0= github.com/desertbit/timer v0.0.0-20180107155436-c41aec40b27f h1:U5y3Y5UE0w7amNe7Z5G/twsBW0KEalRQXZzf8ufSh9I= github.com/desertbit/timer v0.0.0-20180107155436-c41aec40b27f/go.mod h1:xH/i4TFMt8koVQZ6WFms69WAsDWr2XsYL3Hkl7jkoLE= github.com/dgraph-io/badger v1.6.0/go.mod h1:zwt7syl517jmP8s94KqSxTlM6IMsdhYy6psNgSztDR4= @@ -276,8 +277,8 @@ github.com/fsnotify/fsnotify v1.6.0 h1:n+5WquG0fcWoWp6xPWfHdbskMCQaFnG6PfBrh1Ky4 github.com/fsnotify/fsnotify v1.6.0/go.mod h1:sl3t1tCWJFWoRz9R8WJCbQihKKwmorjAbSClcnxKAGw= github.com/gavv/httpexpect v2.0.0+incompatible/go.mod h1:x+9tiU1YnrOvnB725RkpoLv1M62hOWzwo5OXotisrKc= github.com/getsentry/sentry-go v0.12.0/go.mod h1:NSap0JBYWzHND8oMbyi0+XZhUalc1TBdRL1M71JZW2c= -github.com/getsentry/sentry-go v0.19.0 h1:BcCH3CN5tXt5aML+gwmbFwVptLLQA+eT866fCO9wVOM= -github.com/getsentry/sentry-go v0.19.0/go.mod h1:y3+lGEFEFexZtpbG1GUE2WD/f9zGyKYwpEqryTOC/nE= +github.com/getsentry/sentry-go v0.20.0 h1:bwXW98iMRIWxn+4FgPW7vMrjmbym6HblXALmhjHmQaQ= +github.com/getsentry/sentry-go v0.20.0/go.mod h1:lc76E2QywIyW8WuBnwl8Lc4bkmQH4+w1gwTf25trprY= github.com/ghodss/yaml v1.0.0/go.mod h1:4dBDuWmgqj2HViK6kFavaiC9ZROes6MMH2rRYeMEF04= github.com/gin-contrib/sse v0.0.0-20190301062529-5545eab6dad3/go.mod h1:VJ0WA2NBN22VlZ2dKZQPAPnyWw5XTlK1KymzLKsr59s= github.com/gin-contrib/sse v0.1.0 h1:Y/yl/+YNO8GZSjAhjMsSuLt29uWRFHdHYUb5lYOV9qE= @@ -499,7 +500,6 @@ github.com/imkira/go-interpol v1.1.0/go.mod h1:z0h2/2T3XF8kyEPpRgJ3kmNv+C43p+I/C github.com/improbable-eng/grpc-web v0.15.0 h1:BN+7z6uNXZ1tQGcNAuaU1YjsLTApzkjt2tzCixLaUPQ= github.com/improbable-eng/grpc-web v0.15.0/go.mod h1:1sy9HKV4Jt9aEs9JSnkWlRJPuPtwNr0l57L4f878wP8= github.com/inconshreveable/mousetrap v1.0.0/go.mod h1:PxqpIevigyE2G7u3NXJIT2ANytuPF1OarO4DADm73n8= -github.com/inconshreveable/mousetrap v1.0.1/go.mod h1:vpF70FUmC8bwa3OWnCshd2FqLfsEA9PFc4w1p2J65bw= github.com/inconshreveable/mousetrap v1.1.0 h1:wN+x4NVGpMsO7ErUn/mUI3vEoE6Jt13X2s0bqwp9tc8= github.com/inconshreveable/mousetrap v1.1.0/go.mod h1:vpF70FUmC8bwa3OWnCshd2FqLfsEA9PFc4w1p2J65bw= github.com/influxdata/influxdb1-client v0.0.0-20191209144304-8bf82d3c094d/go.mod h1:qj24IKcXYK6Iy9ceXlo3Tc+vtHo9lIhSX5JddghvEPo= @@ -540,8 +540,8 @@ github.com/klauspost/compress v1.9.7/go.mod h1:RyIbtBH6LamlWaDj8nUwkbUhJ87Yi3uG0 github.com/klauspost/compress v1.10.3/go.mod h1:aoV0uJVorq1K+umq18yTdKaF57EivdYsUV+/s2qKfXs= github.com/klauspost/compress v1.11.7/go.mod h1:aoV0uJVorq1K+umq18yTdKaF57EivdYsUV+/s2qKfXs= github.com/klauspost/compress v1.12.3/go.mod h1:8dP1Hq4DHOhN9w426knH3Rhby4rFm6D8eO+e+Dq5Gzg= -github.com/klauspost/compress v1.16.3 h1:XuJt9zzcnaz6a16/OU53ZjWp/v7/42WcR5t2a0PcNQY= -github.com/klauspost/compress v1.16.3/go.mod h1:ntbaceVETuRiXiv4DpjP66DpAtAGkEQskQzEyD//IeE= +github.com/klauspost/compress v1.16.5 h1:IFV2oUNUzZaz+XyusxpLzpzS8Pt5rh0Z16For/djlyI= +github.com/klauspost/compress v1.16.5/go.mod h1:ntbaceVETuRiXiv4DpjP66DpAtAGkEQskQzEyD//IeE= github.com/klauspost/cpuid v1.2.1/go.mod h1:Pj4uuM528wm8OyEC2QMXAi2YiTZ96dNQPGgoMS4s3ek= github.com/konsorten/go-windows-terminal-sequences v1.0.1/go.mod h1:T0+1ngSBFLxvqU3pZ+m/2kptfBszLMUkC4ZK/EgS/cQ= github.com/konsorten/go-windows-terminal-sequences v1.0.3/go.mod h1:T0+1ngSBFLxvqU3pZ+m/2kptfBszLMUkC4ZK/EgS/cQ= @@ -565,8 +565,8 @@ github.com/libp2p/go-buffer-pool v0.1.0 h1:oK4mSFcQz7cTQIfqbe4MIj9gLW+mnanjyFtc6 github.com/libp2p/go-buffer-pool v0.1.0/go.mod h1:N+vh8gMqimBzdKkSMVuydVDq+UV5QTWy5HSiZacSbPg= github.com/lightstep/lightstep-tracer-common/golang/gogo v0.0.0-20190605223551-bc2310a04743/go.mod h1:qklhhLq1aX+mtWk9cPHPzaBjWImj5ULL6C7HFJtXQMM= github.com/lightstep/lightstep-tracer-go v0.18.1/go.mod h1:jlF1pusYV4pidLvZ+XD0UBX0ZE6WURAspgAczcDHrL4= -github.com/linxGnu/grocksdb v1.7.15 h1:AEhP28lkeAybv5UYNYviYISpR6bJejEnKuYbnWAnxx0= -github.com/linxGnu/grocksdb v1.7.15/go.mod h1:pY55D0o+r8yUYLq70QmhdudxYvoDb9F+9puf4m3/W+U= +github.com/linxGnu/grocksdb v1.7.16 h1:Q2co1xrpdkr5Hx3Fp+f+f7fRGhQFQhvi/+226dtLmA8= +github.com/linxGnu/grocksdb v1.7.16/go.mod h1:JkS7pl5qWpGpuVb3bPqTz8nC12X3YtPZT+Xq7+QfQo4= github.com/lyft/protoc-gen-validate v0.0.13/go.mod h1:XbGvPuh87YZc5TdIa2/I4pLk0QoUACkjt2znoq26NVQ= github.com/magiconair/properties v1.8.0/go.mod h1:PppfXfuXeibc/6YijjN8zIbojt8czPbwD3XqdrwzmxQ= github.com/magiconair/properties v1.8.7 h1:IeQXZAiQcpL9mgcAe1Nu6cX9LLw6ExEHKjN0VQdvPDY= @@ -704,8 +704,8 @@ github.com/prometheus/client_golang v1.0.0/go.mod h1:db9x61etRT2tGnBNRi70OPL5Fsn github.com/prometheus/client_golang v1.3.0/go.mod h1:hJaj2vgQTGQmVCsAACORcieXFeDPbaTKGT+JTgUa3og= github.com/prometheus/client_golang v1.4.0/go.mod h1:e9GMxYsXl05ICDXkRhurwBS4Q3OK1iX/F2sw+iXX5zU= github.com/prometheus/client_golang v1.7.1/go.mod h1:PY5Wy2awLA44sXw4AOSfFBetzPP4j5+D6mVACh+pe2M= -github.com/prometheus/client_golang v1.14.0 h1:nJdhIvne2eSX/XRAFV9PcvFFRbrjbcTUj0VP62TMhnw= -github.com/prometheus/client_golang v1.14.0/go.mod h1:8vpkKitgIVNcqrRBWh1C4TIUQgYNtG/XQE4E/Zae36Y= +github.com/prometheus/client_golang v1.15.0 h1:5fCgGYogn0hFdhyhLbw7hEsWxufKtY9klyvdNfFlFhM= +github.com/prometheus/client_golang v1.15.0/go.mod h1:e9yaBhRPU2pPNsZwE+JdQl0KEt1N9XgF6zxWmaC0xOk= github.com/prometheus/client_model v0.0.0-20180712105110-5c3871d89910/go.mod h1:MbSGuTsp3dbXC40dX6PRTWyKYBIrTGTE9sqQNg2J8bo= github.com/prometheus/client_model v0.0.0-20190115171406-56726106282f/go.mod h1:MbSGuTsp3dbXC40dX6PRTWyKYBIrTGTE9sqQNg2J8bo= github.com/prometheus/client_model v0.0.0-20190129233127-fd36f4220a90/go.mod h1:xMI15A0UPsDsEKsMN9yxemIoYk6Tm2C1GtYGdfGttqA= @@ -739,14 +739,15 @@ github.com/rogpeppe/fastuuid v1.2.0/go.mod h1:jVj6XXZzXRy/MSR5jhDC/2q6DgLz+nrA6L github.com/rogpeppe/go-internal v1.3.0/go.mod h1:M8bDsm7K2OlrFYOpmOWEs/qY81heoFRclV5y23lUDJ4= github.com/rogpeppe/go-internal v1.6.1/go.mod h1:xXDCJY+GAPziupqXw64V24skbSoqbTEfhy4qGm1nDQc= github.com/rogpeppe/go-internal v1.8.1/go.mod h1:JeRgkft04UBgHMgCIwADu4Pn6Mtm5d4nPKWu0nJ5d+o= -github.com/rogpeppe/go-internal v1.9.0 h1:73kH8U+JUqXU8lRuOHeVHaa/SZPifC7BkcraZVejAe8= github.com/rogpeppe/go-internal v1.9.0/go.mod h1:WtVeX8xhTBvf0smdhujwtBcq4Qrzq/fJaraNFVN+nFs= +github.com/rogpeppe/go-internal v1.10.0 h1:TMyTOH3F/DB16zRVcYyreMH6GnZZrwQVAoYjRBZyWFQ= +github.com/rogpeppe/go-internal v1.10.0/go.mod h1:UQnix2H7Ngw/k4C5ijL5+65zddjncjaFoBhdsK/akog= github.com/rs/cors v1.7.0/go.mod h1:gFx+x8UowdsKA9AchylcLynDq+nNFfI8FkUZdN/jGCU= github.com/rs/cors v1.8.3 h1:O+qNyWn7Z+F9M0ILBHgMVPuB1xTOucVd5gtaYyXBpRo= github.com/rs/cors v1.8.3/go.mod h1:XyqrcTp5zjWr1wsJ8PIRZssZ8b/WMcMf71DJnit4EMU= github.com/rs/xid v1.4.0/go.mod h1:trrq9SKmegXys3aeAKXMUTdJsYXVwGY3RLcfgqegfbg= -github.com/rs/zerolog v1.29.0 h1:Zes4hju04hjbvkVkOhdl2HpZa+0PmVwigmo8XoORE5w= -github.com/rs/zerolog v1.29.0/go.mod h1:NILgTygv/Uej1ra5XxGf82ZFSLk58MFGAUS2o6usyD0= +github.com/rs/zerolog v1.29.1 h1:cO+d60CHkknCbvzEWxP0S9K6KqyTjrCNUy1LdQLCGPc= +github.com/rs/zerolog v1.29.1/go.mod h1:Le6ESbR7hc+DP6Lt1THiV8CQSdkkNrd3R0XbEgp3ZBU= github.com/russross/blackfriday v1.5.2/go.mod h1:JO/DiYxRf+HjHt06OyowR9PTA263kcR/rfWxYHBV53g= github.com/russross/blackfriday/v2 v2.0.1/go.mod h1:+Rmxgy9KzJVeS9/2gXHxylqXiyQDYRxCVz55jmeOWTM= github.com/russross/blackfriday/v2 v2.1.0/go.mod h1:+Rmxgy9KzJVeS9/2gXHxylqXiyQDYRxCVz55jmeOWTM= @@ -779,8 +780,8 @@ github.com/spf13/cast v1.5.0 h1:rj3WzYc11XZaIZMPKmwP96zkFEnnAmV8s6XbB2aY32w= github.com/spf13/cast v1.5.0/go.mod h1:SpXXQ5YoyJw6s3/6cMTQuxvgRl3PCJiyaX9p6b155UU= github.com/spf13/cobra v0.0.3/go.mod h1:1l0Ry5zgKvJasoi3XT1TypsSe7PqH0Sj9dhYf7v3XqQ= github.com/spf13/cobra v0.0.5/go.mod h1:3K3wKZymM7VvHMDS9+Akkh4K60UwM26emMESw8tLCHU= -github.com/spf13/cobra v1.6.1 h1:o94oiPyS4KD1mPy2fmcYYHHfCxLqYjJOhGsCHFZtEzA= -github.com/spf13/cobra v1.6.1/go.mod h1:IOw/AERYS7UzyrGinqmz6HLUo219MORXGxhbaJUqzrY= +github.com/spf13/cobra v1.7.0 h1:hyqWnYt1ZQShIddO5kBpj3vu05/++x6tJ6dg8EC572I= +github.com/spf13/cobra v1.7.0/go.mod h1:uLxZILRyS/50WlhOIKD7W6V5bgeIt+4sICxh6uRMrb0= github.com/spf13/jwalterweatherman v1.0.0/go.mod h1:cQK4TGJAtQXfYWX+Ddv3mKDzgVb68N+wFjFa4jdeBTo= github.com/spf13/jwalterweatherman v1.1.0 h1:ue6voC5bR5F8YxI5S67j9i582FU4Qvo2bmqnqMYADFk= github.com/spf13/jwalterweatherman v1.1.0/go.mod h1:aNWZUN0dPAAO/Ljvb5BEdw96iTZ0EXowPYD95IqWIGo= @@ -896,8 +897,8 @@ golang.org/x/crypto v0.0.0-20210322153248-0c34fe9e7dc2/go.mod h1:T9bdIzuCu7OtxOm golang.org/x/crypto v0.0.0-20210421170649-83a5a9bb288b/go.mod h1:T9bdIzuCu7OtxOm1hfPfRQxPLYneinmdGuTeoZ9dtd4= golang.org/x/crypto v0.0.0-20210921155107-089bfa567519/go.mod h1:GvvjBRRGRdwPK5ydBHafDWAxML/pGHZbMvKqRZ5+Abc= golang.org/x/crypto v0.0.0-20211108221036-ceb1ce70b4fa/go.mod h1:GvvjBRRGRdwPK5ydBHafDWAxML/pGHZbMvKqRZ5+Abc= -golang.org/x/crypto v0.7.0 h1:AvwMYaRytfdeVt3u6mLaxYtErKYjxA2OXjJ1HHq6t3A= -golang.org/x/crypto v0.7.0/go.mod h1:pYwdfH91IfpZVANVyUOhSIPZaFoJGxTFbZhFTx+dXZU= +golang.org/x/crypto v0.8.0 h1:pd9TJtTueMTVQXzk8E2XESSMQDj/U7OUu0PqJqPXQjQ= +golang.org/x/crypto v0.8.0/go.mod h1:mRqEX+O9/h5TFCrQhkgjo2yKi0yYA+9ecGkdQoHrywE= golang.org/x/exp v0.0.0-20190121172915-509febef88a4/go.mod h1:CJ0aWSM057203Lf6IL+f9T1iT9GByDxfZKAQTCR3kQA= golang.org/x/exp v0.0.0-20190306152737-a1d7652674e8/go.mod h1:CJ0aWSM057203Lf6IL+f9T1iT9GByDxfZKAQTCR3kQA= golang.org/x/exp v0.0.0-20190510132918-efd6b22b2522/go.mod h1:ZjyILWgesfNpC6sMxTJOJm9Kp84zZh5NQWvqDGG3Qr8= @@ -986,8 +987,8 @@ golang.org/x/net v0.0.0-20210805182204-aaa1db679c0d/go.mod h1:9nx3DQGgdP8bBQD5qx golang.org/x/net v0.0.0-20211008194852-3b03d305991f/go.mod h1:9nx3DQGgdP8bBQD5qxJ1jj9UTztislL4KSBs9R2vV5Y= golang.org/x/net v0.0.0-20220225172249-27dd8689420f/go.mod h1:CfG3xpIq0wQ8r1q4Su4UZFWDARRcnwPjda9FqA0JpMk= golang.org/x/net v0.0.0-20220607020251-c690dde0001d/go.mod h1:XRhObCWvk6IyKnWLug+ECip1KBveYUHfp+8e9klMJ9c= -golang.org/x/net v0.8.0 h1:Zrh2ngAOFYneWTAIAPethzeaQLuHwhuBkuV6ZiRnUaQ= -golang.org/x/net v0.8.0/go.mod h1:QVkue5JL9kW//ek3r6jTKnTFis1tRmNAW2P1shuFdJc= +golang.org/x/net v0.9.0 h1:aWJ/m6xSmxWBx+V0XRHTlrYrPG56jKsLdTFmsSsCzOM= +golang.org/x/net v0.9.0/go.mod h1:d48xBJpPfHeWQsugry2m+kC02ZBRGRgulfHnEXEuWns= golang.org/x/oauth2 v0.0.0-20180821212333-d2e6202438be/go.mod h1:N/0e6XlmueqKjAGxoOufVs8QHGRruUQn6yWY3a++T0U= golang.org/x/oauth2 v0.0.0-20190226205417-e64efc72b421/go.mod h1:gOpvHmFTYa4IltrdGE7lF6nIHvwfUNPOp7c8zoXwtLw= golang.org/x/oauth2 v0.0.0-20190604053449-0f29369cfe45/go.mod h1:gOpvHmFTYa4IltrdGE7lF6nIHvwfUNPOp7c8zoXwtLw= @@ -1090,12 +1091,13 @@ golang.org/x/sys v0.0.0-20220520151302-bc2c85ada10a/go.mod h1:oPkhp1MJrh7nUepCBc golang.org/x/sys v0.0.0-20220811171246-fbc7d0a398ab/go.mod h1:oPkhp1MJrh7nUepCBck5+mAzfO9JrbApNNgaTdGDITg= golang.org/x/sys v0.0.0-20220908164124-27713097b956/go.mod h1:oPkhp1MJrh7nUepCBck5+mAzfO9JrbApNNgaTdGDITg= golang.org/x/sys v0.0.0-20221010170243-090e33056c14/go.mod h1:oPkhp1MJrh7nUepCBck5+mAzfO9JrbApNNgaTdGDITg= -golang.org/x/sys v0.6.0 h1:MVltZSvRTcU2ljQOhs94SXPftV6DCNnZViHeQps87pQ= golang.org/x/sys v0.6.0/go.mod h1:oPkhp1MJrh7nUepCBck5+mAzfO9JrbApNNgaTdGDITg= +golang.org/x/sys v0.7.0 h1:3jlCCIQZPdOYu1h8BkNvLz8Kgwtae2cagcG/VamtZRU= +golang.org/x/sys v0.7.0/go.mod h1:oPkhp1MJrh7nUepCBck5+mAzfO9JrbApNNgaTdGDITg= golang.org/x/term v0.0.0-20201126162022-7de9c90e9dd1/go.mod h1:bj7SfCRtBDWHUb9snDiAeCFNEtKQo2Wmx5Cou7ajbmo= golang.org/x/term v0.0.0-20210927222741-03fcf44c2211/go.mod h1:jbD1KX2456YbFQfuXm/mYQcufACuNUgVhRMnK/tPxf8= -golang.org/x/term v0.6.0 h1:clScbb1cHjoCkyRbWwBEUZ5H/tIFu5TAXIqaZD0Gcjw= -golang.org/x/term v0.6.0/go.mod h1:m6U89DPEgQRMq3DNkDClhWw02AUbt2daBVO4cn4Hv9U= +golang.org/x/term v0.7.0 h1:BEvjmm5fURWqcfbSKTdpkDXYBrUS1c0m8agp14W48vQ= +golang.org/x/term v0.7.0/go.mod h1:P32HKFT3hSsZrRxla30E9HqToFYAQPCMs/zFMBUFqPY= golang.org/x/text v0.0.0-20170915032832-14c0d48ead0c/go.mod h1:NqM8EUOU14njkJ3fqMW+pc6Ldnwhi/IjpwHt7yyuwOQ= golang.org/x/text v0.3.0/go.mod h1:NqM8EUOU14njkJ3fqMW+pc6Ldnwhi/IjpwHt7yyuwOQ= golang.org/x/text v0.3.1-0.20180807135948-17ff2d5776d2/go.mod h1:NqM8EUOU14njkJ3fqMW+pc6Ldnwhi/IjpwHt7yyuwOQ= @@ -1105,8 +1107,8 @@ golang.org/x/text v0.3.4/go.mod h1:5Zoc/QRtKVWzQhOtBMvqHzDpF6irO9z98xDceosuGiQ= golang.org/x/text v0.3.5/go.mod h1:5Zoc/QRtKVWzQhOtBMvqHzDpF6irO9z98xDceosuGiQ= golang.org/x/text v0.3.6/go.mod h1:5Zoc/QRtKVWzQhOtBMvqHzDpF6irO9z98xDceosuGiQ= golang.org/x/text v0.3.7/go.mod h1:u+2+/6zg+i71rQMx5EYifcz6MCKuco9NR6JIITiCfzQ= -golang.org/x/text v0.8.0 h1:57P1ETyNKtuIjB4SRd15iJxuhj8Gc416Y78H3qgMh68= -golang.org/x/text v0.8.0/go.mod h1:e1OnstbJyHTd6l/uOt8jFFHp6TRDWZR/bV3emEE/zU8= +golang.org/x/text v0.9.0 h1:2sjJmO8cDvYveuX97RDLsxlyUxLl+GHoLxBiRdHllBE= +golang.org/x/text v0.9.0/go.mod h1:e1OnstbJyHTd6l/uOt8jFFHp6TRDWZR/bV3emEE/zU8= golang.org/x/time v0.0.0-20180412165947-fbb02b2291d2/go.mod h1:tRJNPiyCQ0inRvYxbN9jk5I+vvW/OXSQhTDSoE431IQ= golang.org/x/time v0.0.0-20181108054448-85acf8d2951c/go.mod h1:tRJNPiyCQ0inRvYxbN9jk5I+vvW/OXSQhTDSoE431IQ= golang.org/x/time v0.0.0-20190308202827-9d24e82272b4/go.mod h1:tRJNPiyCQ0inRvYxbN9jk5I+vvW/OXSQhTDSoE431IQ= @@ -1252,8 +1254,8 @@ google.golang.org/genproto v0.0.0-20210126160654-44e461bb6506/go.mod h1:FWY/as6D google.golang.org/genproto v0.0.0-20210226172003-ab064af71705/go.mod h1:FWY/as6DDZQgahTzZj3fqbO1CbirC29ZNUFHwi0/+no= google.golang.org/genproto v0.0.0-20210624195500-8bfb893ecb84/go.mod h1:SzzZ/N+nwJDaO1kznhnlzqS8ocJICar6hYhVyhi++24= google.golang.org/genproto v0.0.0-20220314164441-57ef72a4c106/go.mod h1:hAL49I2IFola2sVEjAn7MEwsja0xp51I0tlGAf9hz4E= -google.golang.org/genproto v0.0.0-20230320184635-7606e756e683 h1:khxVcsk/FhnzxMKOyD+TDGwjbEOpcPuIpmafPGFmhMA= -google.golang.org/genproto v0.0.0-20230320184635-7606e756e683/go.mod h1:NWraEVixdDnqcqQ30jipen1STv2r/n24Wb7twVTGR4s= +google.golang.org/genproto v0.0.0-20230410155749-daa745c078e1 h1:KpwkzHKEF7B9Zxg18WzOa7djJ+Ha5DzthMyZYQfEn2A= +google.golang.org/genproto v0.0.0-20230410155749-daa745c078e1/go.mod h1:nKE/iIaLqn2bQwXBg8f1g2Ylh6r5MN5CmZvuzZCgsCU= google.golang.org/grpc v1.12.0/go.mod h1:yo6s7OP7yaDglbqo1J04qKzAhqBH6lvTonzMVmEdcZw= google.golang.org/grpc v1.17.0/go.mod h1:6QZJwpn2B+Zp71q/5VxRsJ6NXXVCE5NRUHRo+f3cWCs= google.golang.org/grpc v1.19.0/go.mod h1:mqu4LbDTu4XGKhr4mRzUsmM4RtVoemTSY81AxZiDr8c= diff --git a/x/feegrant/grant.go b/x/feegrant/grant.go index 8ea74bbce6b2..56029b9ae21c 100644 --- a/x/feegrant/grant.go +++ b/x/feegrant/grant.go @@ -13,8 +13,6 @@ import ( var _ types.UnpackInterfacesMessage = &Grant{} // NewGrant creates a new FeeAllowanceGrant. -// -//nolint:interfacer func NewGrant(granter, grantee sdk.AccAddress, feeAllowance FeeAllowanceI) (Grant, error) { msg, ok := feeAllowance.(proto.Message) if !ok { diff --git a/x/feegrant/keeper/genesis_test.go b/x/feegrant/keeper/genesis_test.go index 374c859632f0..6f24f2b4fa43 100644 --- a/x/feegrant/keeper/genesis_test.go +++ b/x/feegrant/keeper/genesis_test.go @@ -15,6 +15,7 @@ import ( codectypes "github.com/cosmos/cosmos-sdk/codec/types" "github.com/cosmos/cosmos-sdk/crypto/keys/secp256k1" + "github.com/cosmos/cosmos-sdk/runtime" "github.com/cosmos/cosmos-sdk/testutil" "github.com/cosmos/cosmos-sdk/testutil/testdata" sdk "github.com/cosmos/cosmos-sdk/types" @@ -45,7 +46,7 @@ func initFixture(t *testing.T) *genesisFixture { return &genesisFixture{ ctx: testCtx.Ctx, - feegrantKeeper: keeper.NewKeeper(encCfg.Codec, key, accountKeeper), + feegrantKeeper: keeper.NewKeeper(encCfg.Codec, runtime.NewKVStoreService(key), accountKeeper), accountKeeper: accountKeeper, } } diff --git a/x/feegrant/keeper/grpc_query.go b/x/feegrant/keeper/grpc_query.go index ffa061e7ce53..bb3e281651cf 100644 --- a/x/feegrant/keeper/grpc_query.go +++ b/x/feegrant/keeper/grpc_query.go @@ -12,6 +12,7 @@ import ( "cosmossdk.io/x/feegrant" codectypes "github.com/cosmos/cosmos-sdk/codec/types" + "github.com/cosmos/cosmos-sdk/runtime" sdk "github.com/cosmos/cosmos-sdk/types" "github.com/cosmos/cosmos-sdk/types/query" ) @@ -75,10 +76,10 @@ func (q Keeper) Allowances(c context.Context, req *feegrant.QueryAllowancesReque var grants []*feegrant.Grant - store := ctx.KVStore(q.storeKey) - grantsStore := prefix.NewStore(store, feegrant.FeeAllowancePrefixByGrantee(granteeAddr)) + store := q.storeService.OpenKVStore(ctx) + grantsStore := prefix.NewStore(runtime.KVStoreAdapter(store), feegrant.FeeAllowancePrefixByGrantee(granteeAddr)) - pageRes, err := query.Paginate(grantsStore, req.Pagination, func(key []byte, value []byte) error { + pageRes, err := query.Paginate(grantsStore, req.Pagination, func(key, value []byte) error { var grant feegrant.Grant if err := q.cdc.Unmarshal(value, &grant); err != nil { @@ -108,8 +109,8 @@ func (q Keeper) AllowancesByGranter(c context.Context, req *feegrant.QueryAllowa ctx := sdk.UnwrapSDKContext(c) - store := ctx.KVStore(q.storeKey) - prefixStore := prefix.NewStore(store, feegrant.FeeAllowanceKeyPrefix) + store := q.storeService.OpenKVStore(ctx) + prefixStore := prefix.NewStore(runtime.KVStoreAdapter(store), feegrant.FeeAllowanceKeyPrefix) grants, pageRes, err := query.GenericFilteredPaginate(q.cdc, prefixStore, req.Pagination, func(key []byte, grant *feegrant.Grant) (*feegrant.Grant, error) { // ParseAddressesFromFeeAllowanceKey expects the full key including the prefix. granter, _ := feegrant.ParseAddressesFromFeeAllowanceKey(append(feegrant.FeeAllowanceKeyPrefix, key...)) diff --git a/x/feegrant/keeper/keeper.go b/x/feegrant/keeper/keeper.go index b2f1ede2776a..77905a4b1a50 100644 --- a/x/feegrant/keeper/keeper.go +++ b/x/feegrant/keeper/keeper.go @@ -1,15 +1,19 @@ package keeper import ( + "context" "fmt" "time" + "cosmossdk.io/core/store" errorsmod "cosmossdk.io/errors" "cosmossdk.io/log" storetypes "cosmossdk.io/store/types" + "cosmossdk.io/x/feegrant" "github.com/cosmos/cosmos-sdk/codec" + "github.com/cosmos/cosmos-sdk/runtime" sdk "github.com/cosmos/cosmos-sdk/types" sdkerrors "github.com/cosmos/cosmos-sdk/types/errors" "github.com/cosmos/cosmos-sdk/x/auth/ante" @@ -18,19 +22,19 @@ import ( // Keeper manages state of all fee grants, as well as calculating approval. // It must have a codec with all available allowances registered. type Keeper struct { - cdc codec.BinaryCodec - storeKey storetypes.StoreKey - authKeeper feegrant.AccountKeeper + cdc codec.BinaryCodec + storeService store.KVStoreService + authKeeper feegrant.AccountKeeper } var _ ante.FeegrantKeeper = &Keeper{} // NewKeeper creates a fee grant Keeper -func NewKeeper(cdc codec.BinaryCodec, storeKey storetypes.StoreKey, ak feegrant.AccountKeeper) Keeper { +func NewKeeper(cdc codec.BinaryCodec, storeService store.KVStoreService, ak feegrant.AccountKeeper) Keeper { return Keeper{ - cdc: cdc, - storeKey: storeKey, - authKeeper: ak, + cdc: cdc, + storeService: storeService, + authKeeper: ak, } } @@ -40,7 +44,7 @@ func (k Keeper) Logger(ctx sdk.Context) log.Logger { } // GrantAllowance creates a new grant -func (k Keeper) GrantAllowance(ctx sdk.Context, granter, grantee sdk.AccAddress, feeAllowance feegrant.FeeAllowanceI) error { +func (k Keeper) GrantAllowance(ctx context.Context, granter, grantee sdk.AccAddress, feeAllowance feegrant.FeeAllowanceI) error { // Checking for duplicate entry if f, _ := k.GetAllowance(ctx, granter, grantee); f != nil { return errorsmod.Wrap(sdkerrors.ErrInvalidRequest, "fee allowance already exists") @@ -53,7 +57,7 @@ func (k Keeper) GrantAllowance(ctx sdk.Context, granter, grantee sdk.AccAddress, k.authKeeper.SetAccount(ctx, granteeAcc) } - store := ctx.KVStore(k.storeKey) + store := k.storeService.OpenKVStore(ctx) key := feegrant.FeeAllowanceKey(granter, grantee) exp, err := feeAllowance.ExpiresAt() @@ -62,7 +66,8 @@ func (k Keeper) GrantAllowance(ctx sdk.Context, granter, grantee sdk.AccAddress, } // expiration shouldn't be in the past. - if exp != nil && exp.Before(ctx.BlockTime()) { + sdkCtx := sdk.UnwrapSDKContext(ctx) + if exp != nil && exp.Before(sdkCtx.BlockTime()) { return errorsmod.Wrap(sdkerrors.ErrInvalidRequest, "expiration is before current block time") } @@ -70,7 +75,10 @@ func (k Keeper) GrantAllowance(ctx sdk.Context, granter, grantee sdk.AccAddress, if exp != nil { // `key` formed here with the prefix of `FeeAllowanceKeyPrefix` (which is `0x00`) // remove the 1st byte and reuse the remaining key as it is - k.addToFeeAllowanceQueue(ctx, key[1:], exp) + err = k.addToFeeAllowanceQueue(ctx, key[1:], exp) + if err != nil { + return err + } } grant, err := feegrant.NewGrant(granter, grantee, feeAllowance) @@ -83,8 +91,12 @@ func (k Keeper) GrantAllowance(ctx sdk.Context, granter, grantee sdk.AccAddress, return err } - store.Set(key, bz) - ctx.EventManager().EmitEvent( + err = store.Set(key, bz) + if err != nil { + return err + } + + sdkCtx.EventManager().EmitEvent( sdk.NewEvent( feegrant.EventTypeSetFeeGrant, sdk.NewAttribute(feegrant.AttributeKeyGranter, grant.Granter), @@ -96,8 +108,8 @@ func (k Keeper) GrantAllowance(ctx sdk.Context, granter, grantee sdk.AccAddress, } // UpdateAllowance updates the existing grant. -func (k Keeper) UpdateAllowance(ctx sdk.Context, granter, grantee sdk.AccAddress, feeAllowance feegrant.FeeAllowanceI) error { - store := ctx.KVStore(k.storeKey) +func (k Keeper) UpdateAllowance(ctx context.Context, granter, grantee sdk.AccAddress, feeAllowance feegrant.FeeAllowanceI) error { + store := k.storeService.OpenKVStore(ctx) key := feegrant.FeeAllowanceKey(granter, grantee) _, err := k.getGrant(ctx, granter, grantee) @@ -115,9 +127,12 @@ func (k Keeper) UpdateAllowance(ctx sdk.Context, granter, grantee sdk.AccAddress return err } - store.Set(key, bz) + err = store.Set(key, bz) + if err != nil { + return err + } - ctx.EventManager().EmitEvent( + sdk.UnwrapSDKContext(ctx).EventManager().EmitEvent( sdk.NewEvent( feegrant.EventTypeUpdateFeeGrant, sdk.NewAttribute(feegrant.AttributeKeyGranter, grant.Granter), @@ -129,17 +144,20 @@ func (k Keeper) UpdateAllowance(ctx sdk.Context, granter, grantee sdk.AccAddress } // revokeAllowance removes an existing grant -func (k Keeper) revokeAllowance(ctx sdk.Context, granter, grantee sdk.AccAddress) error { +func (k Keeper) revokeAllowance(ctx context.Context, granter, grantee sdk.AccAddress) error { _, err := k.getGrant(ctx, granter, grantee) if err != nil { return err } - store := ctx.KVStore(k.storeKey) + store := k.storeService.OpenKVStore(ctx) key := feegrant.FeeAllowanceKey(granter, grantee) - store.Delete(key) + err = store.Delete(key) + if err != nil { + return err + } - ctx.EventManager().EmitEvent( + sdk.UnwrapSDKContext(ctx).EventManager().EmitEvent( sdk.NewEvent( feegrant.EventTypeRevokeFeeGrant, sdk.NewAttribute(feegrant.AttributeKeyGranter, granter.String()), @@ -152,7 +170,7 @@ func (k Keeper) revokeAllowance(ctx sdk.Context, granter, grantee sdk.AccAddress // GetAllowance returns the allowance between the granter and grantee. // If there is none, it returns nil, nil. // Returns an error on parsing issues -func (k Keeper) GetAllowance(ctx sdk.Context, granter, grantee sdk.AccAddress) (feegrant.FeeAllowanceI, error) { +func (k Keeper) GetAllowance(ctx context.Context, granter, grantee sdk.AccAddress) (feegrant.FeeAllowanceI, error) { grant, err := k.getGrant(ctx, granter, grantee) if err != nil { return nil, err @@ -162,10 +180,14 @@ func (k Keeper) GetAllowance(ctx sdk.Context, granter, grantee sdk.AccAddress) ( } // getGrant returns entire grant between both accounts -func (k Keeper) getGrant(ctx sdk.Context, granter sdk.AccAddress, grantee sdk.AccAddress) (*feegrant.Grant, error) { - store := ctx.KVStore(k.storeKey) +func (k Keeper) getGrant(ctx context.Context, granter, grantee sdk.AccAddress) (*feegrant.Grant, error) { + store := k.storeService.OpenKVStore(ctx) key := feegrant.FeeAllowanceKey(granter, grantee) - bz := store.Get(key) + bz, err := store.Get(key) + if err != nil { + return nil, err + } + if len(bz) == 0 { return nil, sdkerrors.ErrNotFound.Wrap("fee-grant not found") } @@ -181,9 +203,9 @@ func (k Keeper) getGrant(ctx sdk.Context, granter sdk.AccAddress, grantee sdk.Ac // IterateAllFeeAllowances iterates over all the grants in the store. // Callback to get all data, returns true to stop, false to keep reading // Calling this without pagination is very expensive and only designed for export genesis -func (k Keeper) IterateAllFeeAllowances(ctx sdk.Context, cb func(grant feegrant.Grant) bool) error { - store := ctx.KVStore(k.storeKey) - iter := storetypes.KVStorePrefixIterator(store, feegrant.FeeAllowanceKeyPrefix) +func (k Keeper) IterateAllFeeAllowances(ctx context.Context, cb func(grant feegrant.Grant) bool) error { + store := k.storeService.OpenKVStore(ctx) + iter := storetypes.KVStorePrefixIterator(runtime.KVStoreAdapter(store), feegrant.FeeAllowanceKeyPrefix) defer iter.Close() stop := false @@ -200,7 +222,7 @@ func (k Keeper) IterateAllFeeAllowances(ctx sdk.Context, cb func(grant feegrant. } // UseGrantedFees will try to pay the given fee from the granter's account as requested by the grantee -func (k Keeper) UseGrantedFees(ctx sdk.Context, granter, grantee sdk.AccAddress, fee sdk.Coins, msgs []sdk.Msg) error { +func (k Keeper) UseGrantedFees(ctx context.Context, granter, grantee sdk.AccAddress, fee sdk.Coins, msgs []sdk.Msg) error { f, err := k.getGrant(ctx, granter, grantee) if err != nil { return err @@ -235,8 +257,8 @@ func (k Keeper) UseGrantedFees(ctx sdk.Context, granter, grantee sdk.AccAddress, return k.UpdateAllowance(ctx, granter, grantee, grant) } -func emitUseGrantEvent(ctx sdk.Context, granter, grantee string) { - ctx.EventManager().EmitEvent( +func emitUseGrantEvent(ctx context.Context, granter, grantee string) { + sdk.UnwrapSDKContext(ctx).EventManager().EmitEvent( sdk.NewEvent( feegrant.EventTypeUseFeeGrant, sdk.NewAttribute(feegrant.AttributeKeyGranter, granter), @@ -246,7 +268,7 @@ func emitUseGrantEvent(ctx sdk.Context, granter, grantee string) { } // InitGenesis will initialize the keeper from a *previously validated* GenesisState -func (k Keeper) InitGenesis(ctx sdk.Context, data *feegrant.GenesisState) error { +func (k Keeper) InitGenesis(ctx context.Context, data *feegrant.GenesisState) error { for _, f := range data.Allowances { granter, err := k.authKeeper.StringToBytes(f.Granter) if err != nil { @@ -271,7 +293,7 @@ func (k Keeper) InitGenesis(ctx sdk.Context, data *feegrant.GenesisState) error } // ExportGenesis will dump the contents of the keeper into a serializable GenesisState. -func (k Keeper) ExportGenesis(ctx sdk.Context) (*feegrant.GenesisState, error) { +func (k Keeper) ExportGenesis(ctx context.Context) (*feegrant.GenesisState, error) { var grants []feegrant.Grant err := k.IterateAllFeeAllowances(ctx, func(grant feegrant.Grant) bool { @@ -284,22 +306,32 @@ func (k Keeper) ExportGenesis(ctx sdk.Context) (*feegrant.GenesisState, error) { }, err } -func (k Keeper) addToFeeAllowanceQueue(ctx sdk.Context, grantKey []byte, exp *time.Time) { - store := ctx.KVStore(k.storeKey) - store.Set(feegrant.FeeAllowancePrefixQueue(exp, grantKey), []byte{}) +func (k Keeper) addToFeeAllowanceQueue(ctx context.Context, grantKey []byte, exp *time.Time) error { + store := k.storeService.OpenKVStore(ctx) + return store.Set(feegrant.FeeAllowancePrefixQueue(exp, grantKey), []byte{}) } // RemoveExpiredAllowances iterates grantsByExpiryQueue and deletes the expired grants. -func (k Keeper) RemoveExpiredAllowances(ctx sdk.Context) { - exp := ctx.BlockTime() - store := ctx.KVStore(k.storeKey) - iterator := store.Iterator(feegrant.FeeAllowanceQueueKeyPrefix, storetypes.InclusiveEndBytes(feegrant.AllowanceByExpTimeKey(&exp))) +func (k Keeper) RemoveExpiredAllowances(ctx context.Context) error { + exp := sdk.UnwrapSDKContext(ctx).BlockTime() + store := k.storeService.OpenKVStore(ctx) + iterator, err := store.Iterator(feegrant.FeeAllowanceQueueKeyPrefix, storetypes.InclusiveEndBytes(feegrant.AllowanceByExpTimeKey(&exp))) + if err != nil { + return err + } defer iterator.Close() for ; iterator.Valid(); iterator.Next() { - store.Delete(iterator.Key()) + err = store.Delete(iterator.Key()) + if err != nil { + return err + } granter, grantee := feegrant.ParseAddressesFromFeeAllowanceQueueKey(iterator.Key()) - store.Delete(feegrant.FeeAllowanceKey(granter, grantee)) + err = store.Delete(feegrant.FeeAllowanceKey(granter, grantee)) + if err != nil { + return err + } } + return nil } diff --git a/x/feegrant/keeper/keeper_test.go b/x/feegrant/keeper/keeper_test.go index c9e033a446e8..919f47d71180 100644 --- a/x/feegrant/keeper/keeper_test.go +++ b/x/feegrant/keeper/keeper_test.go @@ -6,6 +6,7 @@ import ( "github.com/golang/mock/gomock" "github.com/stretchr/testify/suite" + sdkmath "cosmossdk.io/math" storetypes "cosmossdk.io/store/types" "cosmossdk.io/x/feegrant" "cosmossdk.io/x/feegrant/keeper" @@ -13,6 +14,7 @@ import ( feegranttestutil "cosmossdk.io/x/feegrant/testutil" codecaddress "github.com/cosmos/cosmos-sdk/codec/address" + "github.com/cosmos/cosmos-sdk/runtime" "github.com/cosmos/cosmos-sdk/testutil" simtestutil "github.com/cosmos/cosmos-sdk/testutil/sims" sdk "github.com/cosmos/cosmos-sdk/types" @@ -59,10 +61,10 @@ func (suite *KeeperTestSuite) SetupTest() { suite.accountKeeper.EXPECT().BytesToString(suite.addrs[2]).Return(suite.addrs[2].String(), nil).AnyTimes() suite.accountKeeper.EXPECT().BytesToString(suite.addrs[3]).Return(suite.addrs[3].String(), nil).AnyTimes() - suite.feegrantKeeper = keeper.NewKeeper(encCfg.Codec, key, suite.accountKeeper) + suite.feegrantKeeper = keeper.NewKeeper(encCfg.Codec, runtime.NewKVStoreService(key), suite.accountKeeper) suite.ctx = testCtx.Ctx suite.msgSrvr = keeper.NewMsgServerImpl(suite.feegrantKeeper) - suite.atom = sdk.NewCoins(sdk.NewCoin("atom", sdk.NewInt(555))) + suite.atom = sdk.NewCoins(sdk.NewCoin("atom", sdkmath.NewInt(555))) } func (suite *KeeperTestSuite) TestKeeperCrud() { diff --git a/x/feegrant/keeper/migrations.go b/x/feegrant/keeper/migrations.go index 3523d0079063..ccb583197179 100644 --- a/x/feegrant/keeper/migrations.go +++ b/x/feegrant/keeper/migrations.go @@ -2,6 +2,7 @@ package keeper import ( v2 "cosmossdk.io/x/feegrant/migrations/v2" + sdk "github.com/cosmos/cosmos-sdk/types" ) @@ -17,5 +18,5 @@ func NewMigrator(keeper Keeper) Migrator { // Migrate1to2 migrates from version 1 to 2. func (m Migrator) Migrate1to2(ctx sdk.Context) error { - return v2.MigrateStore(ctx, m.keeper.storeKey, m.keeper.cdc) + return v2.MigrateStore(ctx, m.keeper.storeService, m.keeper.cdc) } diff --git a/x/feegrant/keeper/msg_server.go b/x/feegrant/keeper/msg_server.go index e6d735602e11..0c6023a1b303 100644 --- a/x/feegrant/keeper/msg_server.go +++ b/x/feegrant/keeper/msg_server.go @@ -2,6 +2,7 @@ package keeper import ( "context" + "strings" errorsmod "cosmossdk.io/errors" sdk "github.com/cosmos/cosmos-sdk/types" @@ -26,7 +27,7 @@ var _ feegrant.MsgServer = msgServer{} // GrantAllowance grants an allowance from the granter's funds to be used by the grantee. func (k msgServer) GrantAllowance(goCtx context.Context, msg *feegrant.MsgGrantAllowance) (*feegrant.MsgGrantAllowanceResponse, error) { - if msg.Grantee == msg.Granter { + if strings.EqualFold(msg.Grantee, msg.Granter) { return nil, errorsmod.Wrap(sdkerrors.ErrInvalidAddress, "cannot self-grant fee authorization") } diff --git a/x/feegrant/key.go b/x/feegrant/key.go index 8b519053a0fc..066ddf5c8997 100644 --- a/x/feegrant/key.go +++ b/x/feegrant/key.go @@ -36,7 +36,7 @@ var ( // // Key format: // - <0x00> -func FeeAllowanceKey(granter sdk.AccAddress, grantee sdk.AccAddress) []byte { +func FeeAllowanceKey(granter, grantee sdk.AccAddress) []byte { return append(FeeAllowancePrefixByGrantee(grantee), address.MustLengthPrefix(granter.Bytes())...) } diff --git a/x/feegrant/migrations/v2/keys.go b/x/feegrant/migrations/v2/keys.go index ae748c6491cf..b7aee7300da0 100644 --- a/x/feegrant/migrations/v2/keys.go +++ b/x/feegrant/migrations/v2/keys.go @@ -36,7 +36,7 @@ func FeeAllowancePrefixQueue(exp *time.Time, granterAddrBz []byte) []byte { // // Key format: // - <0x00> -func FeeAllowanceKey(granter sdk.AccAddress, grantee sdk.AccAddress) []byte { +func FeeAllowanceKey(granter, grantee sdk.AccAddress) []byte { return append(FeeAllowancePrefixByGrantee(grantee), address.MustLengthPrefix(granter.Bytes())...) } diff --git a/x/feegrant/migrations/v2/store.go b/x/feegrant/migrations/v2/store.go index c484c206cd02..48a8d3e3398b 100644 --- a/x/feegrant/migrations/v2/store.go +++ b/x/feegrant/migrations/v2/store.go @@ -1,16 +1,19 @@ package v2 import ( + "context" + + "cosmossdk.io/core/store" "cosmossdk.io/store/prefix" - storetypes "cosmossdk.io/store/types" "cosmossdk.io/x/feegrant" "github.com/cosmos/cosmos-sdk/codec" + "github.com/cosmos/cosmos-sdk/runtime" "github.com/cosmos/cosmos-sdk/types" ) -func addAllowancesByExpTimeQueue(ctx types.Context, store storetypes.KVStore, cdc codec.BinaryCodec) error { - prefixStore := prefix.NewStore(store, FeeAllowanceKeyPrefix) +func addAllowancesByExpTimeQueue(ctx context.Context, store store.KVStore, cdc codec.BinaryCodec) error { + prefixStore := prefix.NewStore(runtime.KVStoreAdapter(store), FeeAllowanceKeyPrefix) iterator := prefixStore.Iterator(nil, nil) defer iterator.Close() @@ -34,7 +37,7 @@ func addAllowancesByExpTimeQueue(ctx types.Context, store storetypes.KVStore, cd if exp != nil { // store key is not changed in 0.46 key := iterator.Key() - if exp.Before(ctx.BlockTime()) { + if exp.Before(types.UnwrapSDKContext(ctx).BlockTime()) { prefixStore.Delete(key) } else { grantByExpTimeQueueKey := FeeAllowancePrefixQueue(exp, key) @@ -46,7 +49,7 @@ func addAllowancesByExpTimeQueue(ctx types.Context, store storetypes.KVStore, cd return nil } -func MigrateStore(ctx types.Context, storeKey storetypes.StoreKey, cdc codec.BinaryCodec) error { - store := ctx.KVStore(storeKey) +func MigrateStore(ctx context.Context, storeService store.KVStoreService, cdc codec.BinaryCodec) error { + store := storeService.OpenKVStore(ctx) return addAllowancesByExpTimeQueue(ctx, store, cdc) } diff --git a/x/feegrant/migrations/v2/store_test.go b/x/feegrant/migrations/v2/store_test.go index c762a45750b4..26173dea4f10 100644 --- a/x/feegrant/migrations/v2/store_test.go +++ b/x/feegrant/migrations/v2/store_test.go @@ -4,13 +4,16 @@ import ( "testing" "time" + sdkmath "cosmossdk.io/math" "github.com/stretchr/testify/require" storetypes "cosmossdk.io/store/types" "cosmossdk.io/x/feegrant" v2 "cosmossdk.io/x/feegrant/migrations/v2" "cosmossdk.io/x/feegrant/module" + "github.com/cosmos/cosmos-sdk/crypto/keys/ed25519" + "github.com/cosmos/cosmos-sdk/runtime" "github.com/cosmos/cosmos-sdk/testutil" sdk "github.com/cosmos/cosmos-sdk/types" moduletestutil "github.com/cosmos/cosmos-sdk/types/module/testutil" @@ -27,7 +30,7 @@ func TestMigration(t *testing.T) { granter2 := sdk.AccAddress(ed25519.GenPrivKey().PubKey().Address()) grantee2 := sdk.AccAddress(ed25519.GenPrivKey().PubKey().Address()) - spendLimit := sdk.NewCoins(sdk.NewCoin("stake", sdk.NewInt(1000))) + spendLimit := sdk.NewCoins(sdk.NewCoin("stake", sdkmath.NewInt(1000))) now := ctx.BlockTime() oneDay := now.AddDate(0, 0, 1) twoDays := now.AddDate(0, 0, 2) @@ -77,7 +80,7 @@ func TestMigration(t *testing.T) { } ctx = ctx.WithBlockTime(now.Add(30 * time.Hour)) - require.NoError(t, v2.MigrateStore(ctx, feegrantKey, cdc)) + require.NoError(t, v2.MigrateStore(ctx, runtime.NewKVStoreService(feegrantKey), cdc)) store = ctx.KVStore(feegrantKey) require.NotNil(t, store.Get(v2.FeeAllowanceKey(granter1, grantee1))) diff --git a/x/feegrant/module/abci.go b/x/feegrant/module/abci.go index 84decfbc9981..4dbab056a9a3 100644 --- a/x/feegrant/module/abci.go +++ b/x/feegrant/module/abci.go @@ -2,9 +2,13 @@ package module import ( "cosmossdk.io/x/feegrant/keeper" + sdk "github.com/cosmos/cosmos-sdk/types" ) func EndBlocker(ctx sdk.Context, k keeper.Keeper) { - k.RemoveExpiredAllowances(ctx) + err := k.RemoveExpiredAllowances(ctx) + if err != nil { + panic(err) + } } diff --git a/x/feegrant/module/abci_test.go b/x/feegrant/module/abci_test.go index b0def7d5ff16..7ce3fc48fdf0 100644 --- a/x/feegrant/module/abci_test.go +++ b/x/feegrant/module/abci_test.go @@ -3,6 +3,7 @@ package module_test import ( "testing" + sdkmath "cosmossdk.io/math" storetypes "cosmossdk.io/store/types" "cosmossdk.io/x/feegrant" "cosmossdk.io/x/feegrant/keeper" @@ -12,6 +13,7 @@ import ( "github.com/stretchr/testify/require" "github.com/cosmos/cosmos-sdk/baseapp" + "github.com/cosmos/cosmos-sdk/runtime" "github.com/cosmos/cosmos-sdk/testutil" simtestutil "github.com/cosmos/cosmos-sdk/testutil/sims" sdk "github.com/cosmos/cosmos-sdk/types" @@ -29,7 +31,7 @@ func TestFeegrantPruning(t *testing.T) { granter2 := addrs[1] granter3 := addrs[2] grantee := addrs[3] - spendLimit := sdk.NewCoins(sdk.NewCoin("stake", sdk.NewInt(1000))) + spendLimit := sdk.NewCoins(sdk.NewCoin("stake", sdkmath.NewInt(1000))) now := testCtx.Ctx.BlockTime() oneDay := now.AddDate(0, 0, 1) @@ -50,7 +52,7 @@ func TestFeegrantPruning(t *testing.T) { accountKeeper.EXPECT().BytesToString(granter2.Bytes()).Return(granter2.String(), nil).AnyTimes() accountKeeper.EXPECT().BytesToString(granter3.Bytes()).Return(granter3.String(), nil).AnyTimes() - feegrantKeeper := keeper.NewKeeper(encCfg.Codec, key, accountKeeper) + feegrantKeeper := keeper.NewKeeper(encCfg.Codec, runtime.NewKVStoreService(key), accountKeeper) feegrantKeeper.GrantAllowance( testCtx.Ctx, diff --git a/x/feegrant/module/module.go b/x/feegrant/module/module.go index 37b99faea2d5..559c5cec0b49 100644 --- a/x/feegrant/module/module.go +++ b/x/feegrant/module/module.go @@ -17,7 +17,7 @@ import ( "cosmossdk.io/depinject" - store "cosmossdk.io/store/types" + "cosmossdk.io/core/store" "cosmossdk.io/x/feegrant" "cosmossdk.io/x/feegrant/client/cli" "cosmossdk.io/x/feegrant/keeper" @@ -190,7 +190,7 @@ func init() { type FeegrantInputs struct { depinject.In - Key *store.KVStoreKey + StoreService store.KVStoreService Cdc codec.Codec AccountKeeper feegrant.AccountKeeper BankKeeper feegrant.BankKeeper @@ -198,7 +198,7 @@ type FeegrantInputs struct { } func ProvideModule(in FeegrantInputs) (keeper.Keeper, appmodule.AppModule) { - k := keeper.NewKeeper(in.Cdc, in.Key, in.AccountKeeper) + k := keeper.NewKeeper(in.Cdc, in.StoreService, in.AccountKeeper) m := NewAppModule(in.Cdc, in.AccountKeeper, in.BankKeeper, k, in.Registry) return k, m } @@ -218,6 +218,7 @@ func (am AppModule) RegisterStoreDecoder(sdr simtypes.StoreDecoderRegistry) { // WeightedOperations returns all the feegrant module operations with their respective weights. func (am AppModule) WeightedOperations(simState module.SimulationState) []simtypes.WeightedOperation { return simulation.WeightedOperations( - am.registry, simState.AppParams, simState.Cdc, am.accountKeeper, am.bankKeeper, am.keeper, am.ac, + am.registry, simState.AppParams, simState.Cdc, simState.TxConfig, + am.accountKeeper, am.bankKeeper, am.keeper, am.ac, ) } diff --git a/x/feegrant/msgs.go b/x/feegrant/msgs.go index c3120b587a99..1ff00590eb35 100644 --- a/x/feegrant/msgs.go +++ b/x/feegrant/msgs.go @@ -20,8 +20,6 @@ var ( ) // NewMsgGrantAllowance creates a new MsgGrantAllowance. -// -//nolint:interfacer func NewMsgGrantAllowance(feeAllowance FeeAllowanceI, granter, grantee sdk.AccAddress) (*MsgGrantAllowance, error) { msg, ok := feeAllowance.(proto.Message) if !ok { @@ -39,11 +37,6 @@ func NewMsgGrantAllowance(feeAllowance FeeAllowanceI, granter, grantee sdk.AccAd }, nil } -// ValidateBasic implements the sdk.Msg interface. -func (msg MsgGrantAllowance) ValidateBasic() error { - return nil -} - // GetSigners gets the granter account associated with an allowance func (msg MsgGrantAllowance) GetSigners() []sdk.AccAddress { granter, _ := sdk.AccAddressFromBech32(msg.Granter) @@ -74,15 +67,9 @@ func (msg MsgGrantAllowance) UnpackInterfaces(unpacker types.AnyUnpacker) error // NewMsgRevokeAllowance returns a message to revoke a fee allowance for a given // granter and grantee // -//nolint:interfacer -func NewMsgRevokeAllowance(granter sdk.AccAddress, grantee sdk.AccAddress) MsgRevokeAllowance { - return MsgRevokeAllowance{Granter: granter.String(), Grantee: grantee.String()} -} - -// ValidateBasic implements the sdk.Msg interface. -func (msg MsgRevokeAllowance) ValidateBasic() error { - return nil +func NewMsgRevokeAllowance(granter, grantee sdk.AccAddress) MsgRevokeAllowance { + return MsgRevokeAllowance{Granter: granter.String(), Grantee: grantee.String()} } // GetSigners gets the granter address associated with an Allowance diff --git a/x/feegrant/periodic_fee.go b/x/feegrant/periodic_fee.go index 800e9e84f57a..5439d66fb17a 100644 --- a/x/feegrant/periodic_fee.go +++ b/x/feegrant/periodic_fee.go @@ -1,6 +1,7 @@ package feegrant import ( + "context" "time" errorsmod "cosmossdk.io/errors" @@ -21,8 +22,8 @@ var _ FeeAllowanceI = (*PeriodicAllowance)(nil) // // If remove is true (regardless of the error), the FeeAllowance will be deleted from storage // (eg. when it is used up). (See call to RevokeAllowance in Keeper.UseGrantedFees) -func (a *PeriodicAllowance) Accept(ctx sdk.Context, fee sdk.Coins, _ []sdk.Msg) (bool, error) { - blockTime := ctx.BlockTime() +func (a *PeriodicAllowance) Accept(ctx context.Context, fee sdk.Coins, _ []sdk.Msg) (bool, error) { + blockTime := sdk.UnwrapSDKContext(ctx).BlockTime() if a.Basic.Expiration != nil && blockTime.After(*a.Basic.Expiration) { return true, errorsmod.Wrap(ErrFeeLimitExpired, "absolute limit") diff --git a/x/feegrant/simulation/decoder_test.go b/x/feegrant/simulation/decoder_test.go index 621f85939f24..2c7d288d1ab7 100644 --- a/x/feegrant/simulation/decoder_test.go +++ b/x/feegrant/simulation/decoder_test.go @@ -6,6 +6,7 @@ import ( "github.com/stretchr/testify/require" + sdkmath "cosmossdk.io/math" "cosmossdk.io/x/feegrant" "cosmossdk.io/x/feegrant/module" "cosmossdk.io/x/feegrant/simulation" @@ -27,7 +28,7 @@ func TestDecodeStore(t *testing.T) { dec := simulation.NewDecodeStore(cdc) grant, err := feegrant.NewGrant(granterAddr, granteeAddr, &feegrant.BasicAllowance{ - SpendLimit: sdk.NewCoins(sdk.NewCoin("foo", sdk.NewInt(100))), + SpendLimit: sdk.NewCoins(sdk.NewCoin("foo", sdkmath.NewInt(100))), }) require.NoError(t, err) diff --git a/x/feegrant/simulation/genesis.go b/x/feegrant/simulation/genesis.go index 1dc5903740a7..ef995a979a89 100644 --- a/x/feegrant/simulation/genesis.go +++ b/x/feegrant/simulation/genesis.go @@ -4,6 +4,7 @@ import ( "math/rand" "time" + sdkmath "cosmossdk.io/math" "cosmossdk.io/x/feegrant" sdk "github.com/cosmos/cosmos-sdk/types" "github.com/cosmos/cosmos-sdk/types/module" @@ -23,8 +24,8 @@ func genFeeGrants(r *rand.Rand, accounts []simtypes.Account) []feegrant.Grant { func generateRandomAllowances(granter, grantee sdk.AccAddress, r *rand.Rand) feegrant.Grant { allowances := make([]feegrant.Grant, 3) - spendLimit := sdk.NewCoins(sdk.NewCoin("stake", sdk.NewInt(100))) - periodSpendLimit := sdk.NewCoins(sdk.NewCoin("stake", sdk.NewInt(10))) + spendLimit := sdk.NewCoins(sdk.NewCoin("stake", sdkmath.NewInt(100))) + periodSpendLimit := sdk.NewCoins(sdk.NewCoin("stake", sdkmath.NewInt(10))) basic := feegrant.BasicAllowance{ SpendLimit: spendLimit, diff --git a/x/feegrant/simulation/operations.go b/x/feegrant/simulation/operations.go index 173a6478f9e7..8dbcf1f7f90d 100644 --- a/x/feegrant/simulation/operations.go +++ b/x/feegrant/simulation/operations.go @@ -7,17 +7,15 @@ import ( "cosmossdk.io/x/feegrant" "cosmossdk.io/x/feegrant/keeper" "github.com/cosmos/cosmos-sdk/baseapp" + "github.com/cosmos/cosmos-sdk/client" "github.com/cosmos/cosmos-sdk/codec" codectypes "github.com/cosmos/cosmos-sdk/codec/types" sdk "github.com/cosmos/cosmos-sdk/types" simtypes "github.com/cosmos/cosmos-sdk/types/simulation" - "github.com/cosmos/cosmos-sdk/x/auth/tx" "github.com/cosmos/cosmos-sdk/x/simulation" ) // Simulation operation weights constants -// -//nolint:gosec // These aren't harcoded credentials. const ( OpWeightMsgGrantAllowance = "op_weight_msg_grant_fee_allowance" OpWeightMsgRevokeAllowance = "op_weight_msg_grant_revoke_allowance" @@ -34,6 +32,7 @@ func WeightedOperations( registry codectypes.InterfaceRegistry, appParams simtypes.AppParams, cdc codec.JSONCodec, + txConfig client.TxConfig, ak feegrant.AccountKeeper, bk feegrant.BankKeeper, k keeper.Keeper, @@ -56,20 +55,28 @@ func WeightedOperations( }, ) + pCdc := codec.NewProtoCodec(registry) + return simulation.WeightedOperations{ simulation.NewWeightedOperation( weightMsgGrantAllowance, - SimulateMsgGrantAllowance(codec.NewProtoCodec(registry), ak, bk, k), + SimulateMsgGrantAllowance(pCdc, txConfig, ak, bk, k), ), simulation.NewWeightedOperation( weightMsgRevokeAllowance, - SimulateMsgRevokeAllowance(codec.NewProtoCodec(registry), ak, bk, k, ac), + SimulateMsgRevokeAllowance(pCdc, txConfig, ak, bk, k, ac), ), } } // SimulateMsgGrantAllowance generates MsgGrantAllowance with random values. -func SimulateMsgGrantAllowance(cdc *codec.ProtoCodec, ak feegrant.AccountKeeper, bk feegrant.BankKeeper, k keeper.Keeper) simtypes.Operation { +func SimulateMsgGrantAllowance( + cdc *codec.ProtoCodec, + txConfig client.TxConfig, + ak feegrant.AccountKeeper, + bk feegrant.BankKeeper, + k keeper.Keeper, +) simtypes.Operation { return func( r *rand.Rand, app *baseapp.BaseApp, ctx sdk.Context, accs []simtypes.Account, chainID string, ) (simtypes.OperationMsg, []simtypes.FutureOperation, error) { @@ -102,7 +109,7 @@ func SimulateMsgGrantAllowance(cdc *codec.ProtoCodec, ak feegrant.AccountKeeper, txCtx := simulation.OperationInput{ R: r, App: app, - TxGen: tx.NewTxConfig(cdc, tx.DefaultSignModes), + TxGen: txConfig, Cdc: nil, Msg: msg, Context: ctx, @@ -118,7 +125,14 @@ func SimulateMsgGrantAllowance(cdc *codec.ProtoCodec, ak feegrant.AccountKeeper, } // SimulateMsgRevokeAllowance generates a MsgRevokeAllowance with random values. -func SimulateMsgRevokeAllowance(cdc *codec.ProtoCodec, ak feegrant.AccountKeeper, bk feegrant.BankKeeper, k keeper.Keeper, ac address.Codec) simtypes.Operation { +func SimulateMsgRevokeAllowance( + cdc *codec.ProtoCodec, + txConfig client.TxConfig, + ak feegrant.AccountKeeper, + bk feegrant.BankKeeper, + k keeper.Keeper, + ac address.Codec, +) simtypes.Operation { return func( r *rand.Rand, app *baseapp.BaseApp, ctx sdk.Context, accs []simtypes.Account, chainID string, ) (simtypes.OperationMsg, []simtypes.FutureOperation, error) { @@ -157,7 +171,7 @@ func SimulateMsgRevokeAllowance(cdc *codec.ProtoCodec, ak feegrant.AccountKeeper txCtx := simulation.OperationInput{ R: r, App: app, - TxGen: tx.NewTxConfig(cdc, tx.DefaultSignModes), + TxGen: txConfig, Cdc: nil, Msg: &msg, Context: ctx, diff --git a/x/feegrant/simulation/operations_test.go b/x/feegrant/simulation/operations_test.go index edb098747160..065f2a19351e 100644 --- a/x/feegrant/simulation/operations_test.go +++ b/x/feegrant/simulation/operations_test.go @@ -6,6 +6,7 @@ import ( "time" _ "cosmossdk.io/x/feegrant/module" + "github.com/cosmos/cosmos-sdk/client" _ "github.com/cosmos/cosmos-sdk/x/auth" _ "github.com/cosmos/cosmos-sdk/x/auth/tx/config" _ "github.com/cosmos/cosmos-sdk/x/bank" @@ -41,6 +42,7 @@ type SimTestSuite struct { ctx sdk.Context feegrantKeeper keeper.Keeper interfaceRegistry codectypes.InterfaceRegistry + txConfig client.TxConfig accountKeeper authkeeper.AccountKeeper bankKeeper bankkeeper.Keeper cdc codec.Codec @@ -63,6 +65,7 @@ func (suite *SimTestSuite) SetupTest() { &suite.bankKeeper, &suite.accountKeeper, &suite.interfaceRegistry, + &suite.txConfig, &suite.cdc, &suite.legacyAmino, ) @@ -94,7 +97,7 @@ func (suite *SimTestSuite) TestWeightedOperations() { weightedOps := simulation.WeightedOperations( suite.interfaceRegistry, - appParams, suite.cdc, suite.accountKeeper, + appParams, suite.cdc, suite.txConfig, suite.accountKeeper, suite.bankKeeper, suite.feegrantKeeper, codecaddress.NewBech32Codec("cosmos"), ) @@ -144,7 +147,7 @@ func (suite *SimTestSuite) TestSimulateMsgGrantAllowance() { app.BeginBlock(abci.RequestBeginBlock{Header: cmtproto.Header{Height: app.LastBlockHeight() + 1, AppHash: app.LastCommitID().Hash}}) // execute operation - op := simulation.SimulateMsgGrantAllowance(codec.NewProtoCodec(suite.interfaceRegistry), suite.accountKeeper, suite.bankKeeper, suite.feegrantKeeper) + op := simulation.SimulateMsgGrantAllowance(codec.NewProtoCodec(suite.interfaceRegistry), suite.txConfig, suite.accountKeeper, suite.bankKeeper, suite.feegrantKeeper) operationMsg, futureOperations, err := op(r, app.BaseApp, ctx, accounts, "") require.NoError(err) @@ -186,7 +189,7 @@ func (suite *SimTestSuite) TestSimulateMsgRevokeAllowance() { require.NoError(err) // execute operation - op := simulation.SimulateMsgRevokeAllowance(codec.NewProtoCodec(suite.interfaceRegistry), suite.accountKeeper, suite.bankKeeper, suite.feegrantKeeper, codecaddress.NewBech32Codec("cosmos")) + op := simulation.SimulateMsgRevokeAllowance(codec.NewProtoCodec(suite.interfaceRegistry), suite.txConfig, suite.accountKeeper, suite.bankKeeper, suite.feegrantKeeper, codecaddress.NewBech32Codec("cosmos")) operationMsg, futureOperations, err := op(r, app.BaseApp, ctx, accounts, "") require.NoError(err) diff --git a/x/feegrant/testutil/expected_keepers_mocks.go b/x/feegrant/testutil/expected_keepers_mocks.go index 5145192c17fa..b73d1735322d 100644 --- a/x/feegrant/testutil/expected_keepers_mocks.go +++ b/x/feegrant/testutil/expected_keepers_mocks.go @@ -5,6 +5,7 @@ package testutil import ( + context "context" reflect "reflect" types "github.com/cosmos/cosmos-sdk/types" @@ -50,7 +51,7 @@ func (mr *MockAccountKeeperMockRecorder) BytesToString(bz interface{}) *gomock.C } // GetAccount mocks base method. -func (m *MockAccountKeeper) GetAccount(ctx types.Context, addr types.AccAddress) types.AccountI { +func (m *MockAccountKeeper) GetAccount(ctx context.Context, addr types.AccAddress) types.AccountI { m.ctrl.T.Helper() ret := m.ctrl.Call(m, "GetAccount", ctx, addr) ret0, _ := ret[0].(types.AccountI) @@ -64,7 +65,7 @@ func (mr *MockAccountKeeperMockRecorder) GetAccount(ctx, addr interface{}) *gomo } // GetModuleAccount mocks base method. -func (m *MockAccountKeeper) GetModuleAccount(ctx types.Context, moduleName string) types.ModuleAccountI { +func (m *MockAccountKeeper) GetModuleAccount(ctx context.Context, moduleName string) types.ModuleAccountI { m.ctrl.T.Helper() ret := m.ctrl.Call(m, "GetModuleAccount", ctx, moduleName) ret0, _ := ret[0].(types.ModuleAccountI) @@ -92,7 +93,7 @@ func (mr *MockAccountKeeperMockRecorder) GetModuleAddress(moduleName interface{} } // NewAccountWithAddress mocks base method. -func (m *MockAccountKeeper) NewAccountWithAddress(ctx types.Context, addr types.AccAddress) types.AccountI { +func (m *MockAccountKeeper) NewAccountWithAddress(ctx context.Context, addr types.AccAddress) types.AccountI { m.ctrl.T.Helper() ret := m.ctrl.Call(m, "NewAccountWithAddress", ctx, addr) ret0, _ := ret[0].(types.AccountI) @@ -106,7 +107,7 @@ func (mr *MockAccountKeeperMockRecorder) NewAccountWithAddress(ctx, addr interfa } // SetAccount mocks base method. -func (m *MockAccountKeeper) SetAccount(ctx types.Context, acc types.AccountI) { +func (m *MockAccountKeeper) SetAccount(ctx context.Context, acc types.AccountI) { m.ctrl.T.Helper() m.ctrl.Call(m, "SetAccount", ctx, acc) } diff --git a/x/genutil/README.md b/x/genutil/README.md index 90db9f494212..c534b8b0d7ac 100644 --- a/x/genutil/README.md +++ b/x/genutil/README.md @@ -51,6 +51,11 @@ Migrate genesis to a specified target (SDK) version. simd genesis migrate [target-version] ``` +:::tip +The `migrate` command is extensible and takes a `MigrationMap`. This map is a mapping of target versions to genesis migrations functions. +When not using the default `MigrationMap`, it is recommended to still call the default `MigrationMap` corresponding the SDK version of the chain and prepend/append your own genesis migrations. +::: + #### validate-genesis Validates the genesis file at the default location or at the location passed as an argument. @@ -58,3 +63,7 @@ Validates the genesis file at the default location or at the location passed as ```shell simd genesis validate-genesis ``` + +:::warning +Validate genesis only validates if the genesis is valid at the **current application binary**. For validating a genesis from a previous version of the application, use the `migrate` command to migrate the genesis to the current version. +::: diff --git a/x/genutil/client/cli/core_genesis_cmd.go b/x/genutil/client/cli/commands.go similarity index 52% rename from x/genutil/client/cli/core_genesis_cmd.go rename to x/genutil/client/cli/commands.go index 384ddc9c782c..22d69dc6d17b 100644 --- a/x/genutil/client/cli/core_genesis_cmd.go +++ b/x/genutil/client/cli/commands.go @@ -10,9 +10,20 @@ import ( "github.com/spf13/cobra" ) -// GenesisCoreCommand adds core sdk's sub-commands into genesis command: -// -> gentx, migrate, collect-gentxs, validate-genesis, add-genesis-account +// GenesisCoreCommand adds core sdk's sub-commands into genesis command. +// Deprecated: use Commands instead. func GenesisCoreCommand(txConfig client.TxConfig, moduleBasics module.BasicManager, defaultNodeHome string) *cobra.Command { + return Commands(txConfig, moduleBasics, defaultNodeHome) +} + +// Commands adds core sdk's sub-commands into genesis command. +func Commands(txConfig client.TxConfig, moduleBasics module.BasicManager, defaultNodeHome string) *cobra.Command { + return CommandsWithCustomMigrationMap(txConfig, moduleBasics, defaultNodeHome, MigrationMap) +} + +// CommandsWithCustomMigrationMap adds core sdk's sub-commands into genesis command with custom migration map. +// This custom migration map can be used by the application to add its own migration map. +func CommandsWithCustomMigrationMap(txConfig client.TxConfig, moduleBasics module.BasicManager, defaultNodeHome string, migrationMap genutiltypes.MigrationMap) *cobra.Command { cmd := &cobra.Command{ Use: "genesis", Short: "Application's genesis-related subcommands", @@ -23,11 +34,9 @@ func GenesisCoreCommand(txConfig client.TxConfig, moduleBasics module.BasicManag gentxModule := moduleBasics[genutiltypes.ModuleName].(genutil.AppModuleBasic) cmd.AddCommand( - GenTxCmd(moduleBasics, txConfig, - banktypes.GenesisBalancesIterator{}, defaultNodeHome), - MigrateGenesisCmd(), - CollectGenTxsCmd(banktypes.GenesisBalancesIterator{}, defaultNodeHome, - gentxModule.GenTxValidator), + GenTxCmd(moduleBasics, txConfig, banktypes.GenesisBalancesIterator{}, defaultNodeHome), + MigrateGenesisCmd(migrationMap), + CollectGenTxsCmd(banktypes.GenesisBalancesIterator{}, defaultNodeHome, gentxModule.GenTxValidator), ValidateGenesisCmd(moduleBasics), AddGenesisAccountCmd(defaultNodeHome), ) diff --git a/x/genutil/client/cli/gentx.go b/x/genutil/client/cli/gentx.go index e73fce8a125d..ed7c659ad1c4 100644 --- a/x/genutil/client/cli/gentx.go +++ b/x/genutil/client/cli/gentx.go @@ -166,8 +166,10 @@ $ %s gentx my-key-name 1000000stake --home=/path/to/home/dir --keyring-backend=o w := bytes.NewBuffer([]byte{}) clientCtx = clientCtx.WithOutput(w) - if err = msg.ValidateBasic(); err != nil { - return err + if m, ok := msg.(sdk.HasValidateBasic); ok { + if err := m.ValidateBasic(); err != nil { + return err + } } if err = txBldr.PrintUnsignedTx(clientCtx, msg); err != nil { diff --git a/x/genutil/client/cli/gentx_test.go b/x/genutil/client/cli/gentx_test.go index ee4d9cf30085..c3fa2e63d68f 100644 --- a/x/genutil/client/cli/gentx_test.go +++ b/x/genutil/client/cli/gentx_test.go @@ -1,13 +1,13 @@ package cli_test import ( - "bytes" "context" "fmt" "io" "path/filepath" "testing" + sdkmath "cosmossdk.io/math" abci "github.com/cometbft/cometbft/abci/types" rpcclientmock "github.com/cometbft/cometbft/rpc/client/mock" "github.com/stretchr/testify/suite" @@ -51,7 +51,6 @@ func (s *CLITestSuite) SetupSuite() { WithOutput(io.Discard). WithChainID("test-chain") - var outBuf bytes.Buffer ctxGen := func() client.Context { bz, _ := s.encCfg.Codec.Marshal(&sdk.TxResponse{}) c := clitestutil.NewMockCometRPC(abci.ResponseQuery{ @@ -59,11 +58,11 @@ func (s *CLITestSuite) SetupSuite() { }) return s.baseCtx.WithClient(c) } - s.clientCtx = ctxGen().WithOutput(&outBuf) + s.clientCtx = ctxGen() } func (s *CLITestSuite) TestGenTxCmd() { - amount := sdk.NewCoin("stake", sdk.NewInt(12)) + amount := sdk.NewCoin("stake", sdkmath.NewInt(12)) tests := []struct { name string diff --git a/x/genutil/client/cli/init.go b/x/genutil/client/cli/init.go index e09e84067e51..37eda3cc719d 100644 --- a/x/genutil/client/cli/init.go +++ b/x/genutil/client/cli/init.go @@ -11,7 +11,6 @@ import ( errorsmod "cosmossdk.io/errors" "cosmossdk.io/math/unsafe" cfg "github.com/cometbft/cometbft/config" - "github.com/cometbft/cometbft/libs/cli" "github.com/cosmos/go-bip39" "github.com/spf13/cobra" @@ -173,7 +172,7 @@ func InitCmd(mbm module.BasicManager, defaultNodeHome string) *cobra.Command { }, } - cmd.Flags().String(cli.HomeFlag, defaultNodeHome, "node's home directory") + cmd.Flags().String(flags.FlagHome, defaultNodeHome, "node's home directory") cmd.Flags().BoolP(FlagOverwrite, "o", false, "overwrite the genesis.json file") cmd.Flags().Bool(FlagRecover, false, "provide seed phrase to recover existing key instead of creating") cmd.Flags().String(flags.FlagChainID, "", "genesis file chain-id, if left blank will be randomly created") diff --git a/x/genutil/client/cli/init_test.go b/x/genutil/client/cli/init_test.go index 01cbc5f97669..a53e5037c185 100644 --- a/x/genutil/client/cli/init_test.go +++ b/x/genutil/client/cli/init_test.go @@ -10,7 +10,6 @@ import ( "time" abci_server "github.com/cometbft/cometbft/abci/server" - "github.com/cometbft/cometbft/libs/cli" "github.com/spf13/viper" "github.com/stretchr/testify/require" @@ -146,7 +145,7 @@ func TestInitDefaultBondDenom(t *testing.T) { cmd.SetArgs([]string{ "appnode-test", - fmt.Sprintf("--%s=%s", cli.HomeFlag, home), + fmt.Sprintf("--%s=%s", flags.FlagHome, home), fmt.Sprintf("--%s=testtoken", genutilcli.FlagDefaultBondDenom), }) require.NoError(t, cmd.ExecuteContext(ctx)) @@ -171,7 +170,7 @@ func TestEmptyState(t *testing.T) { ctx = context.WithValue(ctx, server.ServerContextKey, serverCtx) cmd := genutilcli.InitCmd(testMbm, home) - cmd.SetArgs([]string{"appnode-test", fmt.Sprintf("--%s=%s", cli.HomeFlag, home)}) + cmd.SetArgs([]string{"appnode-test", fmt.Sprintf("--%s=%s", flags.FlagHome, home)}) require.NoError(t, cmd.ExecuteContext(ctx)) @@ -180,7 +179,7 @@ func TestEmptyState(t *testing.T) { os.Stdout = w cmd = server.ExportCmd(nil, home) - cmd.SetArgs([]string{fmt.Sprintf("--%s=%s", cli.HomeFlag, home)}) + cmd.SetArgs([]string{fmt.Sprintf("--%s=%s", flags.FlagHome, home)}) require.NoError(t, cmd.ExecuteContext(ctx)) outC := make(chan string) diff --git a/x/genutil/client/cli/migrate.go b/x/genutil/client/cli/migrate.go index 6ab54b8e9689..56c8d3638335 100644 --- a/x/genutil/client/cli/migrate.go +++ b/x/genutil/client/cli/migrate.go @@ -4,6 +4,7 @@ import ( "encoding/json" "fmt" "sort" + "strings" "time" "github.com/spf13/cobra" @@ -20,47 +21,35 @@ import ( const flagGenesisTime = "genesis-time" -// Allow applications to extend and modify the migration process. -// -// Ref: https://github.com/cosmos/cosmos-sdk/issues/5041 -var migrationMap = types.MigrationMap{ +// MigrationMap is a map of SDK versions to their respective genesis migration functions. +var MigrationMap = types.MigrationMap{ "v0.43": v043.Migrate, // NOTE: v0.43, v0.44 and v0.45 are genesis compatible. "v0.46": v046.Migrate, "v0.47": v047.Migrate, } -// GetMigrationCallback returns a MigrationCallback for a given version. -func GetMigrationCallback(version string) types.MigrationCallback { - return migrationMap[version] -} - -// GetMigrationVersions get all migration version in a sorted slice. -func GetMigrationVersions() []string { - versions := maps.Keys(migrationMap) - sort.Strings(versions) - - return versions -} - // MigrateGenesisCmd returns a command to execute genesis state migration. -func MigrateGenesisCmd() *cobra.Command { +// Applications should pass their own migration map to this function. +// When the application migration includes a SDK migration, the Cosmos SDK migration function should as well be called. +func MigrateGenesisCmd(migrations types.MigrationMap) *cobra.Command { cmd := &cobra.Command{ - Use: "migrate [target-version] [genesis-file]", - Short: "Migrate genesis to a specified target version", - Long: fmt.Sprintf(`Migrate the source genesis into the target version and print to STDOUT. - -Example: -$ %s migrate v0.36 /path/to/genesis.json --chain-id=cosmoshub-3 --genesis-time=2019-04-22T17:00:00Z -`, version.AppName), - Args: cobra.ExactArgs(2), + Use: "migrate [target-version] [genesis-file]", + Short: "Migrate genesis to a specified target version", + Long: "Migrate the source genesis into the target version and print to STDOUT", + Example: fmt.Sprintf("%s migrate v0.47 /path/to/genesis.json --chain-id=cosmoshub-3 --genesis-time=2019-04-22T17:00:00Z", version.AppName), + Args: cobra.ExactArgs(2), RunE: func(cmd *cobra.Command, args []string) error { clientCtx := client.GetClientContextFromCmd(cmd) - var err error - target := args[0] - importGenesis := args[1] + migrationFunc, ok := migrations[target] + if !ok || migrationFunc == nil { + versions := maps.Keys(migrations) + sort.Strings(versions) + return fmt.Errorf("unknown migration function for version: %s (supported versions %s)", target, strings.Join(versions, ", ")) + } + importGenesis := args[1] appGenesis, err := types.AppGenesisFromFile(importGenesis) if err != nil { return err @@ -83,14 +72,11 @@ $ %s migrate v0.36 /path/to/genesis.json --chain-id=cosmoshub-3 --genesis-time=2 return fmt.Errorf("failed to JSON unmarshal initial genesis state: %w", err) } - migrationFunc := GetMigrationCallback(target) - if migrationFunc == nil { - return fmt.Errorf("unknown migration function for version: %s", target) + newGenState, err := migrationFunc(initialState, clientCtx) + if err != nil { + return fmt.Errorf("failed to migrate genesis state: %w", err) } - // TODO: handler error from migrationFunc call - newGenState := migrationFunc(initialState, clientCtx) - appGenesis.AppState, err = json.Marshal(newGenState) if err != nil { return fmt.Errorf("failed to JSON marshal migrated genesis state: %w", err) diff --git a/x/genutil/client/cli/migrate_test.go b/x/genutil/client/cli/migrate_test.go index 9a569a8b6ede..ab89ed5429fc 100644 --- a/x/genutil/client/cli/migrate_test.go +++ b/x/genutil/client/cli/migrate_test.go @@ -9,15 +9,10 @@ import ( "github.com/cosmos/cosmos-sdk/client" "github.com/cosmos/cosmos-sdk/testutil" clitestutil "github.com/cosmos/cosmos-sdk/testutil/cli" + moduletestutil "github.com/cosmos/cosmos-sdk/types/module/testutil" "github.com/cosmos/cosmos-sdk/x/genutil/client/cli" ) -func TestGetMigrationCallback(t *testing.T) { - for _, version := range cli.GetMigrationVersions() { - require.NotNil(t, cli.GetMigrationCallback(version)) - } -} - func TestMigrateGenesis(t *testing.T) { testCases := []struct { name string @@ -28,9 +23,9 @@ func TestMigrateGenesis(t *testing.T) { check func(jsonOut string) }{ { - "migrate 0.37 to 0.42", + "migrate 0.37 to 0.43", v037Exported, - "v0.42", + "v0.43", true, "make sure that you have correctly migrated all CometBFT consensus params", func(_ string) {}, }, { @@ -42,7 +37,7 @@ func TestMigrateGenesis(t *testing.T) { return string(bz) }(), "v0.10", - true, "unknown migration function for version: v0.10", func(_ string) {}, + true, "unknown migration function for version: v0.10 (supported versions v0.43, v0.46, v0.47)", func(_ string) {}, }, { "invalid target version", @@ -53,7 +48,7 @@ func TestMigrateGenesis(t *testing.T) { return string(bz) }(), "v0.10", - true, "unknown migration function for version: v0.10", func(_ string) {}, + true, "unknown migration function for version: v0.10 (supported versions v0.43, v0.46, v0.47)", func(_ string) {}, }, } @@ -61,7 +56,12 @@ func TestMigrateGenesis(t *testing.T) { tc := tc t.Run(tc.name, func(t *testing.T) { genesisFile := testutil.WriteToNewTempFile(t, tc.genesis) - jsonOutput, err := clitestutil.ExecTestCLICmd(client.Context{}, cli.MigrateGenesisCmd(), []string{tc.target, genesisFile.Name()}) + jsonOutput, err := clitestutil.ExecTestCLICmd( + // the codec does not contain any modules so that genutil does not bring unnecessary dependencies in the test + client.Context{Codec: moduletestutil.MakeTestEncodingConfig().Codec}, + cli.MigrateGenesisCmd(cli.MigrationMap), + []string{tc.target, genesisFile.Name()}, + ) if tc.expErr { require.Contains(t, err.Error(), tc.expErrMsg) } else { diff --git a/x/genutil/client/cli/validate_genesis.go b/x/genutil/client/cli/validate_genesis.go index a565a37f368b..f3a57320ac16 100644 --- a/x/genutil/client/cli/validate_genesis.go +++ b/x/genutil/client/cli/validate_genesis.go @@ -53,7 +53,7 @@ func ValidateGenesisCmd(mbm module.BasicManager) *cobra.Command { return fmt.Errorf("error validating genesis file %s: %s", genesis, err.Error()) } - fmt.Printf("File at %s is a valid genesis file\n", genesis) + fmt.Fprintf(cmd.OutOrStdout(), "File at %s is a valid genesis file\n", genesis) return nil }, } diff --git a/x/genutil/client/testutil/helpers.go b/x/genutil/client/testutil/helpers.go index c570b9a6d080..7060f6ab243c 100644 --- a/x/genutil/client/testutil/helpers.go +++ b/x/genutil/client/testutil/helpers.go @@ -5,12 +5,12 @@ import ( "fmt" cmtcfg "github.com/cometbft/cometbft/config" - "github.com/cometbft/cometbft/libs/cli" "github.com/spf13/viper" "cosmossdk.io/log" "github.com/cosmos/cosmos-sdk/client" + "github.com/cosmos/cosmos-sdk/client/flags" "github.com/cosmos/cosmos-sdk/codec" "github.com/cosmos/cosmos-sdk/server" "github.com/cosmos/cosmos-sdk/testutil" @@ -36,7 +36,7 @@ func ExecInitCmd(testMbm module.BasicManager, home string, cdc codec.Codec) erro ctx = context.WithValue(ctx, client.ClientContextKey, &clientCtx) ctx = context.WithValue(ctx, server.ServerContextKey, serverCtx) - cmd.SetArgs([]string{"appnode-test", fmt.Sprintf("--%s=%s", cli.HomeFlag, home)}) + cmd.SetArgs([]string{"appnode-test", fmt.Sprintf("--%s=%s", flags.FlagHome, home)}) return cmd.ExecuteContext(ctx) } diff --git a/x/genutil/migrations/v043/migrate.go b/x/genutil/migrations/v043/migrate.go index bbb78e5f0769..93ed56989472 100644 --- a/x/genutil/migrations/v043/migrate.go +++ b/x/genutil/migrations/v043/migrate.go @@ -12,7 +12,7 @@ import ( ) // Migrate migrates exported state from v0.40 to a v0.43 genesis state. -func Migrate(appState types.AppMap, clientCtx client.Context) types.AppMap { +func Migrate(appState types.AppMap, clientCtx client.Context) (types.AppMap, error) { // Migrate x/gov. if appState[v1gov.ModuleName] != nil { // unmarshal relative source genesis application state @@ -40,5 +40,5 @@ func Migrate(appState types.AppMap, clientCtx client.Context) types.AppMap { appState[v2bank.ModuleName] = clientCtx.Codec.MustMarshalJSON(v2bank.MigrateJSON(&oldBankState)) } - return appState + return appState, nil } diff --git a/x/genutil/migrations/v046/migrate.go b/x/genutil/migrations/v046/migrate.go index c13a24746627..b6d6774feb41 100644 --- a/x/genutil/migrations/v046/migrate.go +++ b/x/genutil/migrations/v046/migrate.go @@ -12,7 +12,7 @@ import ( ) // Migrate migrates exported state from v0.43 to a v0.46 genesis state. -func Migrate(appState types.AppMap, clientCtx client.Context) types.AppMap { +func Migrate(appState types.AppMap, clientCtx client.Context) (types.AppMap, error) { // Migrate x/gov. if appState[v2gov.ModuleName] != nil { // unmarshal relative source genesis application state @@ -26,7 +26,7 @@ func Migrate(appState types.AppMap, clientCtx client.Context) types.AppMap { // the respective key. new, err := v3gov.MigrateJSON(&old) if err != nil { - panic(err) + return nil, err } appState[v3gov.ModuleName] = clientCtx.Codec.MustMarshalJSON(new) } @@ -44,10 +44,10 @@ func Migrate(appState types.AppMap, clientCtx client.Context) types.AppMap { // the respective key. new, err := stakingv3.MigrateJSON(old) if err != nil { - panic(err) + return nil, err } appState[stakingv3.ModuleName] = clientCtx.Codec.MustMarshalJSON(&new) } - return appState + return appState, nil } diff --git a/x/genutil/migrations/v047/migrate.go b/x/genutil/migrations/v047/migrate.go index 0e3512257aae..359bb1e0439d 100644 --- a/x/genutil/migrations/v047/migrate.go +++ b/x/genutil/migrations/v047/migrate.go @@ -16,7 +16,7 @@ import ( ) // Migrate migrates exported state from v0.46 to a v0.47 genesis state. -func Migrate(appState types.AppMap, clientCtx client.Context) types.AppMap { +func Migrate(appState types.AppMap, clientCtx client.Context) (types.AppMap, error) { // Migrate x/bank. bankState := appState[banktypes.ModuleName] if len(bankState) > 0 { @@ -37,7 +37,7 @@ func Migrate(appState types.AppMap, clientCtx client.Context) types.AppMap { // set the x/gov genesis state with new state. new, err := v4gov.MigrateJSON(&old) if err != nil { - panic(err) + return nil, err } appState[v4gov.ModuleName] = clientCtx.Codec.MustMarshalJSON(new) } @@ -58,5 +58,5 @@ func Migrate(appState types.AppMap, clientCtx client.Context) types.AppMap { appState[v1distr.ModuleName] = clientCtx.Codec.MustMarshalJSON(newDistState) } - return appState + return appState, nil } diff --git a/x/genutil/module.go b/x/genutil/module.go index 735d4390bcdf..85d70d39eb71 100644 --- a/x/genutil/module.go +++ b/x/genutil/module.go @@ -132,10 +132,8 @@ func init() { ) } -// GenutilInputs defines the inputs needed for the genutil module. -// -//nolint:revive -type GenutilInputs struct { +// ModuleInputs defines the inputs needed for the genutil module. +type ModuleInputs struct { depinject.In AccountKeeper types.AccountKeeper @@ -144,7 +142,7 @@ type GenutilInputs struct { Config client.TxConfig } -func ProvideModule(in GenutilInputs) appmodule.AppModule { +func ProvideModule(in ModuleInputs) appmodule.AppModule { m := NewAppModule(in.AccountKeeper, in.StakingKeeper, in.DeliverTx, in.Config) return m } diff --git a/x/genutil/testutil/expected_keepers_mocks.go b/x/genutil/testutil/expected_keepers_mocks.go index 51d75e6e8962..1b33fb0d3092 100644 --- a/x/genutil/testutil/expected_keepers_mocks.go +++ b/x/genutil/testutil/expected_keepers_mocks.go @@ -5,6 +5,7 @@ package testutil import ( + context "context" json "encoding/json" reflect "reflect" @@ -77,7 +78,7 @@ func (m *MockAccountKeeper) EXPECT() *MockAccountKeeperMockRecorder { } // IterateAccounts mocks base method. -func (m *MockAccountKeeper) IterateAccounts(ctx types0.Context, process func(types0.AccountI) bool) { +func (m *MockAccountKeeper) IterateAccounts(ctx context.Context, process func(types0.AccountI) bool) { m.ctrl.T.Helper() m.ctrl.Call(m, "IterateAccounts", ctx, process) } @@ -89,7 +90,7 @@ func (mr *MockAccountKeeperMockRecorder) IterateAccounts(ctx, process interface{ } // NewAccount mocks base method. -func (m *MockAccountKeeper) NewAccount(arg0 types0.Context, arg1 types0.AccountI) types0.AccountI { +func (m *MockAccountKeeper) NewAccount(arg0 context.Context, arg1 types0.AccountI) types0.AccountI { m.ctrl.T.Helper() ret := m.ctrl.Call(m, "NewAccount", arg0, arg1) ret0, _ := ret[0].(types0.AccountI) @@ -103,7 +104,7 @@ func (mr *MockAccountKeeperMockRecorder) NewAccount(arg0, arg1 interface{}) *gom } // SetAccount mocks base method. -func (m *MockAccountKeeper) SetAccount(arg0 types0.Context, arg1 types0.AccountI) { +func (m *MockAccountKeeper) SetAccount(arg0 context.Context, arg1 types0.AccountI) { m.ctrl.T.Helper() m.ctrl.Call(m, "SetAccount", arg0, arg1) } diff --git a/x/genutil/types/expected_keepers.go b/x/genutil/types/expected_keepers.go index ed62ea3ab4e3..634109a7e1e5 100644 --- a/x/genutil/types/expected_keepers.go +++ b/x/genutil/types/expected_keepers.go @@ -1,6 +1,7 @@ package types import ( + "context" "encoding/json" abci "github.com/cometbft/cometbft/abci/types" @@ -17,9 +18,9 @@ type StakingKeeper interface { // AccountKeeper defines the expected account keeper (noalias) type AccountKeeper interface { - NewAccount(sdk.Context, sdk.AccountI) sdk.AccountI - SetAccount(sdk.Context, sdk.AccountI) - IterateAccounts(ctx sdk.Context, process func(sdk.AccountI) (stop bool)) + NewAccount(context.Context, sdk.AccountI) sdk.AccountI + SetAccount(context.Context, sdk.AccountI) + IterateAccounts(ctx context.Context, process func(sdk.AccountI) (stop bool)) } // GenesisAccountsIterator defines the expected iterating genesis accounts object (noalias) diff --git a/x/genutil/types/genesis.go b/x/genutil/types/genesis.go index ffd601d2b703..8b9d55a72b2f 100644 --- a/x/genutil/types/genesis.go +++ b/x/genutil/types/genesis.go @@ -142,7 +142,7 @@ type ConsensusGenesis struct { // NewConsensusGenesis returns a ConsensusGenesis with given values. // It takes a proto consensus params so it can called from server export command. -func NewConsensusGenesis(params *cmtproto.ConsensusParams, validators []cmttypes.GenesisValidator) *ConsensusGenesis { +func NewConsensusGenesis(params cmtproto.ConsensusParams, validators []cmttypes.GenesisValidator) *ConsensusGenesis { return &ConsensusGenesis{ Params: &cmttypes.ConsensusParams{ Block: cmttypes.BlockParams{ diff --git a/x/genutil/types/genesis_state.go b/x/genutil/types/genesis_state.go index 421319adc3a3..7e09237becc1 100644 --- a/x/genutil/types/genesis_state.go +++ b/x/genutil/types/genesis_state.go @@ -109,8 +109,11 @@ func DefaultMessageValidator(msgs []sdk.Msg) error { if _, ok := msgs[0].(*stakingtypes.MsgCreateValidator); !ok { return fmt.Errorf("unexpected GenTx message type; expected: MsgCreateValidator, got: %T", msgs[0]) } - if err := msgs[0].ValidateBasic(); err != nil { - return fmt.Errorf("invalid GenTx '%s': %w", msgs[0], err) + + if m, ok := msgs[0].(sdk.HasValidateBasic); ok { + if err := m.ValidateBasic(); err != nil { + return fmt.Errorf("invalid GenTx '%s': %w", msgs[0], err) + } } return nil diff --git a/x/genutil/types/genesis_state_test.go b/x/genutil/types/genesis_state_test.go index a589f5a4f953..1c0ae70de730 100644 --- a/x/genutil/types/genesis_state_test.go +++ b/x/genutil/types/genesis_state_test.go @@ -40,8 +40,7 @@ func TestValidateGenesisMultipleMessages(t *testing.T) { desc := stakingtypes.NewDescription("testname", "", "", "", "") comm := stakingtypes.CommissionRates{} - msg1, err := stakingtypes.NewMsgCreateValidator(sdk.ValAddress(pk1.Address()), pk1, - sdk.NewInt64Coin(sdk.DefaultBondDenom, 50), desc, comm, math.OneInt()) + msg1, err := stakingtypes.NewMsgCreateValidator(sdk.ValAddress(pk1.Address()), pk1, sdk.NewInt64Coin(sdk.DefaultBondDenom, 50), desc, comm, math.OneInt()) require.NoError(t, err) msg2, err := stakingtypes.NewMsgCreateValidator(sdk.ValAddress(pk2.Address()), pk2, diff --git a/x/genutil/types/genesis_test.go b/x/genutil/types/genesis_test.go index 811c285cee4a..245568855717 100644 --- a/x/genutil/types/genesis_test.go +++ b/x/genutil/types/genesis_test.go @@ -62,7 +62,7 @@ func TestAppGenesis_ValidGenesis(t *testing.T) { assert.NilError(t, err) assert.DeepEqual(t, appGenesis.Consensus.Params, genesis.Consensus.Params) - // validate marshalling of app genesis + // validate marshaling of app genesis rawAppGenesis, err = json.Marshal(&appGenesis) assert.NilError(t, err) golden.Assert(t, string(rawAppGenesis), "app_genesis.json") diff --git a/x/genutil/types/types.go b/x/genutil/types/types.go index 89f63554869a..e0995f978377 100644 --- a/x/genutil/types/types.go +++ b/x/genutil/types/types.go @@ -13,9 +13,7 @@ type ( // MigrationCallback converts a genesis map from the previous version to the // targeted one. - // - // TODO: MigrationCallback should also return an error upon failure. - MigrationCallback func(AppMap, client.Context) AppMap + MigrationCallback func(AppMap, client.Context) (AppMap, error) // MigrationMap defines a mapping from a version to a MigrationCallback. MigrationMap map[string]MigrationCallback diff --git a/x/gov/README.md b/x/gov/README.md index 6d1a8fe2d8d0..3861c76a27b6 100644 --- a/x/gov/README.md +++ b/x/gov/README.md @@ -231,34 +231,6 @@ At present, validators are not punished for failing to vote. Later, we may add permissioned keys that could only sign txs from certain modules. For the MVP, the `Governance address` will be the main validator address generated at account creation. This address corresponds to a different PrivKey than the CometBFT PrivKey which is responsible for signing consensus messages. Validators thus do not have to sign governance transactions with the sensitive CometBFT PrivKey. -### Software Upgrade - -If proposals are of type `SoftwareUpgradeProposal`, then nodes need to upgrade -their software to the new version that was voted. This process is divided into -two steps: - -#### Signal - -After a `SoftwareUpgradeProposal` is accepted, validators are expected to -download and install the new version of the software while continuing to run -the previous version. Once a validator has downloaded and installed the -upgrade, it will start signaling to the network that it is ready to switch by -including the proposal's `proposalID` in its *precommits*. (*Note: Confirmation that we want it in the precommit?*) - -Note: There is only one signal slot per *precommit*. If several -`SoftwareUpgradeProposals` are accepted in a short timeframe, a pipeline will -form and they will be implemented one after the other in the order that they -were accepted. - -#### Switch - -Once a block contains more than 2/3rd *precommits* where a common -`SoftwareUpgradeProposal` is signaled, all the nodes (including validator -nodes, non-validating full nodes and light-nodes) are expected to switch to the -new version of the software. - -Validators and full nodes can use an automation tool, such as [Cosmovisor](https://docs.cosmos.network/main/tooling/cosmovisor), for automatically switching version of the chain. - #### Burnable Params There are three parameters that define if the deposit of a proposal should be burned or returned to the depositors. diff --git a/x/gov/abci.go b/x/gov/abci.go index 7ea7a748feee..934e770545a0 100644 --- a/x/gov/abci.go +++ b/x/gov/abci.go @@ -85,18 +85,25 @@ func EndBlocker(ctx sdk.Context, keeper *keeper.Keeper) { // message is logged. cacheCtx, writeCache := ctx.CacheContext() messages, err := proposal.GetMsgs() - if err == nil { - for idx, msg = range messages { - handler := keeper.Router().Handler(msg) + if err != nil { + proposal.Status = v1.StatusFailed + tagValue = types.AttributeValueProposalFailed + logMsg = fmt.Sprintf("passed proposal (%v) failed to execute; msgs: %s", proposal, err) - var res *sdk.Result - res, err = handler(cacheCtx, msg) - if err != nil { - break - } + break + } - events = append(events, res.GetEvents()...) + // execute all messages + for idx, msg = range messages { + handler := keeper.Router().Handler(msg) + + var res *sdk.Result + res, err = handler(cacheCtx, msg) + if err != nil { + break } + + events = append(events, res.GetEvents()...) } // `err == nil` when all handlers passed. @@ -146,6 +153,7 @@ func EndBlocker(ctx sdk.Context, keeper *keeper.Keeper) { logger.Info( "proposal tallied", "proposal", proposal.Id, + "status", proposal.Status.String(), "expedited", proposal.Expedited, "title", proposal.Title, "results", logMsg, @@ -156,8 +164,10 @@ func EndBlocker(ctx sdk.Context, keeper *keeper.Keeper) { types.EventTypeActiveProposal, sdk.NewAttribute(types.AttributeKeyProposalID, fmt.Sprintf("%d", proposal.Id)), sdk.NewAttribute(types.AttributeKeyProposalResult, tagValue), + sdk.NewAttribute(types.AttributeKeyProposalLog, logMsg), ), ) + return false }) } diff --git a/x/gov/abci_test.go b/x/gov/abci_test.go index 93df9fc4809d..2423c488d498 100644 --- a/x/gov/abci_test.go +++ b/x/gov/abci_test.go @@ -17,7 +17,6 @@ import ( "github.com/cosmos/cosmos-sdk/x/gov/keeper" "github.com/cosmos/cosmos-sdk/x/gov/types" v1 "github.com/cosmos/cosmos-sdk/x/gov/types/v1" - "github.com/cosmos/cosmos-sdk/x/staking" stakingkeeper "github.com/cosmos/cosmos-sdk/x/staking/keeper" stakingtypes "github.com/cosmos/cosmos-sdk/x/staking/types" ) @@ -361,7 +360,7 @@ func TestProposalPassedEndblocker(t *testing.T) { proposer := addrs[0] createValidators(t, stakingMsgSvr, ctx, []sdk.ValAddress{valAddr}, []int64{10}) - staking.EndBlocker(ctx, suite.StakingKeeper) + suite.StakingKeeper.EndBlocker(ctx) macc := suite.GovKeeper.GetGovernanceAccount(ctx) require.NotNil(t, macc) @@ -416,7 +415,7 @@ func TestEndBlockerProposalHandlerFailed(t *testing.T) { proposer := addrs[0] createValidators(t, stakingMsgSvr, ctx, []sdk.ValAddress{valAddr}, []int64{10}) - staking.EndBlocker(ctx, suite.StakingKeeper) + suite.StakingKeeper.EndBlocker(ctx) msg := banktypes.NewMsgSend(authtypes.NewModuleAddress(types.ModuleName), addrs[0], sdk.NewCoins(sdk.NewCoin(sdk.DefaultBondDenom, sdk.NewInt(100000)))) proposal, err := suite.GovKeeper.SubmitProposal(ctx, []sdk.Msg{msg}, "", "title", "summary", proposer, false) @@ -440,6 +439,12 @@ func TestEndBlockerProposalHandlerFailed(t *testing.T) { // validate that the proposal fails/has been rejected gov.EndBlocker(ctx, suite.GovKeeper) + // check proposal events + events := ctx.EventManager().Events() + attr, eventOk := events.GetAttributes(types.AttributeKeyProposalLog) + require.True(t, eventOk) + require.Contains(t, attr[0].Value, "failed on execution") + proposal, ok := suite.GovKeeper.GetProposal(ctx, proposal.Id) require.True(t, ok) require.Equal(t, v1.StatusFailed, proposal.Status) @@ -491,7 +496,7 @@ func TestExpeditedProposal_PassAndConversionToRegular(t *testing.T) { // Create a validator so that able to vote on proposal. createValidators(t, stakingMsgSvr, ctx, []sdk.ValAddress{valAddr}, []int64{10}) - staking.EndBlocker(ctx, suite.StakingKeeper) + suite.StakingKeeper.EndBlocker(ctx) inactiveQueue := suite.GovKeeper.InactiveProposalQueueIterator(ctx, ctx.BlockHeader().Time) require.False(t, inactiveQueue.Valid()) diff --git a/x/gov/client/cli/query.go b/x/gov/client/cli/query.go index f93bf8b1fd32..9907f05d89de 100644 --- a/x/gov/client/cli/query.go +++ b/x/gov/client/cli/query.go @@ -5,11 +5,11 @@ import ( "strconv" "strings" + "cosmossdk.io/core/address" "github.com/spf13/cobra" "github.com/cosmos/cosmos-sdk/client" "github.com/cosmos/cosmos-sdk/client/flags" - sdk "github.com/cosmos/cosmos-sdk/types" "github.com/cosmos/cosmos-sdk/version" gcutils "github.com/cosmos/cosmos-sdk/x/gov/client/utils" "github.com/cosmos/cosmos-sdk/x/gov/types" @@ -17,7 +17,7 @@ import ( ) // GetQueryCmd returns the cli query commands for this module -func GetQueryCmd() *cobra.Command { +func GetQueryCmd(ac address.Codec) *cobra.Command { // Group gov queries under a subcommand govQueryCmd := &cobra.Command{ Use: types.ModuleName, @@ -29,8 +29,8 @@ func GetQueryCmd() *cobra.Command { govQueryCmd.AddCommand( GetCmdQueryProposal(), - GetCmdQueryProposals(), - GetCmdQueryVote(), + GetCmdQueryProposals(ac), + GetCmdQueryVote(ac), GetCmdQueryVotes(), GetCmdQueryParams(), GetCmdQueryParam(), @@ -93,7 +93,7 @@ $ %s query gov proposal 1 // GetCmdQueryProposals implements a query proposals command. Command to Get // Proposals Information. -func GetCmdQueryProposals() *cobra.Command { +func GetCmdQueryProposals(ac address.Codec) *cobra.Command { cmd := &cobra.Command{ Use: "proposals", Short: "Query proposals with optional filters", @@ -117,14 +117,14 @@ $ %s query gov proposals --page=2 --limit=100 var proposalStatus v1.ProposalStatus if len(bechDepositorAddr) != 0 { - _, err := sdk.AccAddressFromBech32(bechDepositorAddr) + _, err := ac.StringToBytes(bechDepositorAddr) if err != nil { return err } } if len(bechVoterAddr) != 0 { - _, err := sdk.AccAddressFromBech32(bechVoterAddr) + _, err := ac.StringToBytes(bechVoterAddr) if err != nil { return err } @@ -181,7 +181,7 @@ $ %s query gov proposals --page=2 --limit=100 // GetCmdQueryVote implements the query proposal vote command. Command to Get a // Vote Information. -func GetCmdQueryVote() *cobra.Command { +func GetCmdQueryVote(ac address.Codec) *cobra.Command { cmd := &cobra.Command{ Use: "vote [proposal-id] [voter-addr]", Args: cobra.ExactArgs(2), @@ -218,7 +218,7 @@ $ %s query gov vote 1 cosmos1skjwj5whet0lpe65qaq4rpq03hjxlwd9nf39lk return fmt.Errorf("failed to fetch proposal-id %d: %s", proposalID, err) } - voterAddr, err := sdk.AccAddressFromBech32(args[1]) + voterAddr, err := ac.StringToBytes(args[1]) if err != nil { return err } diff --git a/x/gov/client/cli/query_test.go b/x/gov/client/cli/query_test.go index c5f756b25bf7..baa74d6d2de3 100644 --- a/x/gov/client/cli/query_test.go +++ b/x/gov/client/cli/query_test.go @@ -4,6 +4,7 @@ import ( "fmt" "strings" + "github.com/cosmos/cosmos-sdk/codec/address" clitestutil "github.com/cosmos/cosmos-sdk/testutil/cli" "github.com/cosmos/cosmos-sdk/client/flags" @@ -214,7 +215,7 @@ func (s *CLITestSuite) TestCmdGetProposals() { tc := tc s.Run(tc.name, func() { - cmd := cli.GetCmdQueryProposals() + cmd := cli.GetCmdQueryProposals(address.NewBech32Codec("cosmos")) cmd.SetArgs(tc.args) s.Require().Contains(fmt.Sprint(cmd), strings.TrimSpace(tc.expCmdOutput)) }) @@ -374,7 +375,7 @@ func (s *CLITestSuite) TestCmdQueryVote() { for _, tc := range testCases { tc := tc s.Run(tc.name, func() { - cmd := cli.GetCmdQueryVote() + cmd := cli.GetCmdQueryVote(address.NewBech32Codec("cosmos")) cmd.SetArgs(tc.args) if len(tc.args) != 0 { diff --git a/x/gov/client/cli/tx_test.go b/x/gov/client/cli/tx_test.go index d052aa779e54..3ae1b515c4a8 100644 --- a/x/gov/client/cli/tx_test.go +++ b/x/gov/client/cli/tx_test.go @@ -1,15 +1,14 @@ package cli_test import ( - "bytes" "encoding/base64" "fmt" "io" "testing" + sdkmath "cosmossdk.io/math" abci "github.com/cometbft/cometbft/abci/types" rpcclientmock "github.com/cometbft/cometbft/rpc/client/mock" - "github.com/cosmos/gogoproto/proto" "github.com/stretchr/testify/suite" "github.com/cosmos/cosmos-sdk/client" @@ -53,7 +52,6 @@ func (s *CLITestSuite) SetupSuite() { WithOutput(io.Discard). WithChainID("test-chain") - var outBuf bytes.Buffer ctxGen := func() client.Context { bz, _ := s.encCfg.Codec.Marshal(&sdk.TxResponse{}) c := clitestutil.NewMockCometRPC(abci.ResponseQuery{ @@ -61,7 +59,7 @@ func (s *CLITestSuite) SetupSuite() { }) return s.baseCtx.WithClient(c) } - s.clientCtx = ctxGen().WithOutput(&outBuf) + s.clientCtx = ctxGen() val := testutil.CreateKeyringAccounts(s.T(), s.kr, 1) @@ -124,24 +122,23 @@ func (s *CLITestSuite) TestNewCmdSubmitProposal() { "summary": "My awesome description", "metadata": "%s", "deposit": "%s" - }`, authtypes.NewModuleAddress(types.ModuleName), base64.StdEncoding.EncodeToString(propMetadata), sdk.NewCoin("stake", sdk.NewInt(5431))) + }`, authtypes.NewModuleAddress(types.ModuleName), base64.StdEncoding.EncodeToString(propMetadata), sdk.NewCoin("stake", sdkmath.NewInt(5431))) validPropFile := testutil.WriteToNewTempFile(s.T(), validProp) defer validPropFile.Close() testCases := []struct { - name string - args []string - expectErr bool - respType proto.Message + name string + args []string + expectErrMsg string }{ { "invalid proposal", []string{ invalidPropFile.Name(), fmt.Sprintf("--%s=true", flags.FlagSkipConfirmation), - fmt.Sprintf("--%s=%s", flags.FlagFees, sdk.NewCoins(sdk.NewCoin("stake", sdk.NewInt(10))).String()), + fmt.Sprintf("--%s=%s", flags.FlagFees, sdk.NewCoins(sdk.NewCoin("stake", sdkmath.NewInt(10))).String()), }, - true, nil, + "invalid decimal coin expression", }, { "valid proposal", @@ -150,9 +147,9 @@ func (s *CLITestSuite) TestNewCmdSubmitProposal() { fmt.Sprintf("--%s=%s", flags.FlagFrom, val[0].Address.String()), fmt.Sprintf("--%s=true", flags.FlagSkipConfirmation), fmt.Sprintf("--%s=%s", flags.FlagBroadcastMode, flags.BroadcastSync), - fmt.Sprintf("--%s=%s", flags.FlagFees, sdk.NewCoins(sdk.NewCoin("stake", sdk.NewInt(10))).String()), + fmt.Sprintf("--%s=%s", flags.FlagFees, sdk.NewCoins(sdk.NewCoin("stake", sdkmath.NewInt(10))).String()), }, - false, &sdk.TxResponse{}, + "", }, } @@ -163,11 +160,13 @@ func (s *CLITestSuite) TestNewCmdSubmitProposal() { cmd := cli.NewCmdSubmitProposal() out, err := clitestutil.ExecTestCLICmd(s.clientCtx, cmd, tc.args) - if tc.expectErr { + if tc.expectErrMsg != "" { s.Require().Error(err) + s.Require().Contains(err.Error(), tc.expectErrMsg) } else { s.Require().NoError(err) - s.Require().NoError(s.clientCtx.Codec.UnmarshalJSON(out.Bytes(), tc.respType), out.String()) + msg := &sdk.TxResponse{} + s.Require().NoError(s.clientCtx.Codec.UnmarshalJSON(out.Bytes(), msg), out.String()) } }) } @@ -189,15 +188,14 @@ func (s *CLITestSuite) TestNewCmdSubmitLegacyProposal() { "description": "Hello, World!", "type": "Text", "deposit": "%s" - }`, sdk.NewCoin("stake", sdk.NewInt(5431))) + }`, sdk.NewCoin("stake", sdkmath.NewInt(5431))) validPropFile := testutil.WriteToNewTempFile(s.T(), validProp) defer validPropFile.Close() testCases := []struct { - name string - args []string - expectErr bool - respType proto.Message + name string + args []string + expectErrMsg string }{ { "invalid proposal (file)", @@ -205,21 +203,21 @@ func (s *CLITestSuite) TestNewCmdSubmitLegacyProposal() { fmt.Sprintf("--%s=%s", cli.FlagProposal, invalidPropFile.Name()), fmt.Sprintf("--%s=%s", flags.FlagFrom, val[0].Address.String()), fmt.Sprintf("--%s=true", flags.FlagSkipConfirmation), - fmt.Sprintf("--%s=%s", flags.FlagFees, sdk.NewCoins(sdk.NewCoin("stake", sdk.NewInt(10))).String()), + fmt.Sprintf("--%s=%s", flags.FlagFees, sdk.NewCoins(sdk.NewCoin("stake", sdkmath.NewInt(10))).String()), }, - true, nil, + "failed to parse proposal: proposal title is required", }, { "invalid proposal", []string{ fmt.Sprintf("--%s='Where is the title!?'", cli.FlagDescription), fmt.Sprintf("--%s=%s", cli.FlagProposalType, v1beta1.ProposalTypeText), - fmt.Sprintf("--%s=%s", cli.FlagDeposit, sdk.NewCoin("stake", sdk.NewInt(5431)).String()), + fmt.Sprintf("--%s=%s", cli.FlagDeposit, sdk.NewCoin("stake", sdkmath.NewInt(5431)).String()), fmt.Sprintf("--%s=%s", flags.FlagFrom, val[0].Address.String()), fmt.Sprintf("--%s=true", flags.FlagSkipConfirmation), - fmt.Sprintf("--%s=%s", flags.FlagFees, sdk.NewCoins(sdk.NewCoin("stake", sdk.NewInt(10))).String()), + fmt.Sprintf("--%s=%s", flags.FlagFees, sdk.NewCoins(sdk.NewCoin("stake", sdkmath.NewInt(10))).String()), }, - true, nil, + "failed to parse proposal: proposal title is required", }, { "valid transaction (file)", @@ -229,9 +227,9 @@ func (s *CLITestSuite) TestNewCmdSubmitLegacyProposal() { fmt.Sprintf("--%s=%s", flags.FlagFrom, val[0].Address.String()), fmt.Sprintf("--%s=true", flags.FlagSkipConfirmation), fmt.Sprintf("--%s=%s", flags.FlagBroadcastMode, flags.BroadcastSync), - fmt.Sprintf("--%s=%s", flags.FlagFees, sdk.NewCoins(sdk.NewCoin("stake", sdk.NewInt(10))).String()), + fmt.Sprintf("--%s=%s", flags.FlagFees, sdk.NewCoins(sdk.NewCoin("stake", sdkmath.NewInt(10))).String()), }, - false, &sdk.TxResponse{}, + "", }, { "valid transaction", @@ -239,13 +237,13 @@ func (s *CLITestSuite) TestNewCmdSubmitLegacyProposal() { fmt.Sprintf("--%s='Text Proposal'", cli.FlagTitle), fmt.Sprintf("--%s='Where is the title!?'", cli.FlagDescription), fmt.Sprintf("--%s=%s", cli.FlagProposalType, v1beta1.ProposalTypeText), - fmt.Sprintf("--%s=%s", cli.FlagDeposit, sdk.NewCoin("stake", sdk.NewInt(5431)).String()), + fmt.Sprintf("--%s=%s", cli.FlagDeposit, sdk.NewCoin("stake", sdkmath.NewInt(5431)).String()), fmt.Sprintf("--%s=%s", flags.FlagFrom, val[0].Address.String()), fmt.Sprintf("--%s=true", flags.FlagSkipConfirmation), fmt.Sprintf("--%s=%s", flags.FlagBroadcastMode, flags.BroadcastSync), - fmt.Sprintf("--%s=%s", flags.FlagFees, sdk.NewCoins(sdk.NewCoin("stake", sdk.NewInt(10))).String()), + fmt.Sprintf("--%s=%s", flags.FlagFees, sdk.NewCoins(sdk.NewCoin("stake", sdkmath.NewInt(10))).String()), }, - false, &sdk.TxResponse{}, + "", }, } @@ -256,11 +254,13 @@ func (s *CLITestSuite) TestNewCmdSubmitLegacyProposal() { cmd := cli.NewCmdSubmitLegacyProposal() out, err := clitestutil.ExecTestCLICmd(s.clientCtx, cmd, tc.args) - if tc.expectErr { + if tc.expectErrMsg != "" { s.Require().Error(err) + s.Require().Contains(err.Error(), tc.expectErrMsg) } else { s.Require().NoError(err) - s.Require().NoError(s.clientCtx.Codec.UnmarshalJSON(out.Bytes(), tc.respType), out.String()) + msg := &sdk.TxResponse{} + s.Require().NoError(s.clientCtx.Codec.UnmarshalJSON(out.Bytes(), msg), out.String()) } }) } @@ -270,59 +270,62 @@ func (s *CLITestSuite) TestNewCmdDeposit() { val := testutil.CreateKeyringAccounts(s.T(), s.kr, 1) testCases := []struct { - name string - args []string - expectErr bool + name string + args []string + expectErrMsg string }{ { - "without proposal id", + "invalid proposal id", []string{ - sdk.NewCoin("stake", sdk.NewInt(10)).String(), // 10stake + "abc", + sdk.NewCoin("stake", sdkmath.NewInt(10)).String(), // 10stake fmt.Sprintf("--%s=%s", flags.FlagFrom, val[0].Address.String()), fmt.Sprintf("--%s=true", flags.FlagSkipConfirmation), fmt.Sprintf("--%s=%s", flags.FlagBroadcastMode, flags.BroadcastSync), - fmt.Sprintf("--%s=%s", flags.FlagFees, sdk.NewCoins(sdk.NewCoin("stake", sdk.NewInt(10))).String()), + fmt.Sprintf("--%s=%s", flags.FlagFees, sdk.NewCoins(sdk.NewCoin("stake", sdkmath.NewInt(10))).String()), }, - true, + "proposal-id abc not a valid uint, please input a valid proposal-id", }, { "without deposit amount", []string{ "1", + "invalidCoin", fmt.Sprintf("--%s=%s", flags.FlagFrom, val[0].Address.String()), fmt.Sprintf("--%s=true", flags.FlagSkipConfirmation), fmt.Sprintf("--%s=%s", flags.FlagBroadcastMode, flags.BroadcastSync), - fmt.Sprintf("--%s=%s", flags.FlagFees, sdk.NewCoins(sdk.NewCoin("stake", sdk.NewInt(10))).String()), + fmt.Sprintf("--%s=%s", flags.FlagFees, sdk.NewCoins(sdk.NewCoin("stake", sdkmath.NewInt(10))).String()), }, - true, + "invalid decimal coin expression: invalidCoin", }, { "deposit on a proposal", []string{ "10", - sdk.NewCoin("stake", sdk.NewInt(10)).String(), // 10stake + sdk.NewCoin("stake", sdkmath.NewInt(10)).String(), // 10stake fmt.Sprintf("--%s=%s", flags.FlagFrom, val[0].Address.String()), fmt.Sprintf("--%s=true", flags.FlagSkipConfirmation), fmt.Sprintf("--%s=%s", flags.FlagBroadcastMode, flags.BroadcastSync), - fmt.Sprintf("--%s=%s", flags.FlagFees, sdk.NewCoins(sdk.NewCoin("stake", sdk.NewInt(10))).String()), + fmt.Sprintf("--%s=%s", flags.FlagFees, sdk.NewCoins(sdk.NewCoin("stake", sdkmath.NewInt(10))).String()), }, - false, + "", }, } for _, tc := range testCases { tc := tc - var resp sdk.TxResponse s.Run(tc.name, func() { cmd := cli.NewCmdDeposit() out, err := clitestutil.ExecTestCLICmd(s.clientCtx, cmd, tc.args) - if tc.expectErr { + if tc.expectErrMsg != "" { s.Require().Error(err) + s.Require().Contains(err.Error(), tc.expectErrMsg) } else { s.Require().NoError(err) - s.Require().NoError(s.clientCtx.Codec.UnmarshalJSON(out.Bytes(), &resp), out.String()) + resp := &sdk.TxResponse{} + s.Require().NoError(s.clientCtx.Codec.UnmarshalJSON(out.Bytes(), resp), out.String()) } }) } @@ -334,26 +337,32 @@ func (s *CLITestSuite) TestNewCmdVote() { testCases := []struct { name string args []string - expectErr bool - expectedCode uint32 + expectErrMsg string }{ - { - "invalid vote", - []string{}, - true, 0, - }, { "vote for invalid proposal", []string{ - "10", + "abc", "yes", fmt.Sprintf("--%s=%s", flags.FlagFrom, val[0].Address.String()), fmt.Sprintf("--%s=true", flags.FlagSkipConfirmation), fmt.Sprintf("--%s=%s", flags.FlagBroadcastMode, flags.BroadcastSync), fmt.Sprintf("--metadata=%s", "AQ=="), - fmt.Sprintf("--%s=%s", flags.FlagFees, sdk.NewCoins(sdk.NewCoin("stake", sdk.NewInt(10))).String()), + fmt.Sprintf("--%s=%s", flags.FlagFees, sdk.NewCoins(sdk.NewCoin("stake", sdkmath.NewInt(10))).String()), }, - false, 3, + "proposal-id abc not a valid int, please input a valid proposal-id", + }, + { + "invalid vote", + []string{ + "1", + "AYE", + fmt.Sprintf("--%s=%s", flags.FlagFrom, val[0].Address.String()), + fmt.Sprintf("--%s=true", flags.FlagSkipConfirmation), + fmt.Sprintf("--%s=%s", flags.FlagBroadcastMode, flags.BroadcastSync), + fmt.Sprintf("--%s=%s", flags.FlagFees, sdk.NewCoins(sdk.NewCoin("stake", sdkmath.NewInt(10))).String()), + }, + "'AYE' is not a valid vote option", }, { "valid vote", @@ -363,9 +372,9 @@ func (s *CLITestSuite) TestNewCmdVote() { fmt.Sprintf("--%s=%s", flags.FlagFrom, val[0].Address.String()), fmt.Sprintf("--%s=true", flags.FlagSkipConfirmation), fmt.Sprintf("--%s=%s", flags.FlagBroadcastMode, flags.BroadcastSync), - fmt.Sprintf("--%s=%s", flags.FlagFees, sdk.NewCoins(sdk.NewCoin("stake", sdk.NewInt(10))).String()), + fmt.Sprintf("--%s=%s", flags.FlagFees, sdk.NewCoins(sdk.NewCoin("stake", sdkmath.NewInt(10))).String()), }, - false, 0, + "", }, { "valid vote with metadata", @@ -376,9 +385,9 @@ func (s *CLITestSuite) TestNewCmdVote() { fmt.Sprintf("--%s=true", flags.FlagSkipConfirmation), fmt.Sprintf("--%s=%s", flags.FlagBroadcastMode, flags.BroadcastSync), fmt.Sprintf("--metadata=%s", "AQ=="), - fmt.Sprintf("--%s=%s", flags.FlagFees, sdk.NewCoins(sdk.NewCoin("stake", sdk.NewInt(10))).String()), + fmt.Sprintf("--%s=%s", flags.FlagFees, sdk.NewCoins(sdk.NewCoin("stake", sdkmath.NewInt(10))).String()), }, - false, 0, + "", }, } @@ -386,15 +395,15 @@ func (s *CLITestSuite) TestNewCmdVote() { tc := tc s.Run(tc.name, func() { cmd := cli.NewCmdVote() - var txResp sdk.TxResponse - out, err := clitestutil.ExecTestCLICmd(s.clientCtx, cmd, tc.args) - if tc.expectErr { + if tc.expectErrMsg != "" { s.Require().Error(err) + s.Require().Contains(err.Error(), tc.expectErrMsg) } else { s.Require().NoError(err) - s.Require().NoError(s.clientCtx.Codec.UnmarshalJSON(out.Bytes(), &txResp), out.String()) + resp := &sdk.TxResponse{} + s.Require().NoError(s.clientCtx.Codec.UnmarshalJSON(out.Bytes(), resp), out.String()) } }) } @@ -406,25 +415,31 @@ func (s *CLITestSuite) TestNewCmdWeightedVote() { testCases := []struct { name string args []string - expectErr bool - expectedCode uint32 + expectErrMsg string }{ - { - "invalid vote", - []string{}, - true, 0, - }, { "vote for invalid proposal", []string{ - "10", + "abc", "yes", fmt.Sprintf("--%s=%s", flags.FlagFrom, val[0].Address.String()), fmt.Sprintf("--%s=true", flags.FlagSkipConfirmation), fmt.Sprintf("--%s=%s", flags.FlagBroadcastMode, flags.BroadcastSync), - fmt.Sprintf("--%s=%s", flags.FlagFees, sdk.NewCoins(sdk.NewCoin("stake", sdk.NewInt(10))).String()), + fmt.Sprintf("--%s=%s", flags.FlagFees, sdk.NewCoins(sdk.NewCoin("stake", sdkmath.NewInt(10))).String()), }, - false, 3, + "proposal-id abc not a valid int, please input a valid proposal-id", + }, + { + "invalid vote", + []string{ + "1", + "AYE", + fmt.Sprintf("--%s=%s", flags.FlagFrom, val[0].Address.String()), + fmt.Sprintf("--%s=true", flags.FlagSkipConfirmation), + fmt.Sprintf("--%s=%s", flags.FlagBroadcastMode, flags.BroadcastSync), + fmt.Sprintf("--%s=%s", flags.FlagFees, sdk.NewCoins(sdk.NewCoin("stake", sdkmath.NewInt(10))).String()), + }, + "'AYE' is not a valid vote option", }, { "valid vote", @@ -434,9 +449,9 @@ func (s *CLITestSuite) TestNewCmdWeightedVote() { fmt.Sprintf("--%s=%s", flags.FlagFrom, val[0].Address.String()), fmt.Sprintf("--%s=true", flags.FlagSkipConfirmation), fmt.Sprintf("--%s=%s", flags.FlagBroadcastMode, flags.BroadcastSync), - fmt.Sprintf("--%s=%s", flags.FlagFees, sdk.NewCoins(sdk.NewCoin("stake", sdk.NewInt(10))).String()), + fmt.Sprintf("--%s=%s", flags.FlagFees, sdk.NewCoins(sdk.NewCoin("stake", sdkmath.NewInt(10))).String()), }, - false, 0, + "", }, { "valid vote with metadata", @@ -447,9 +462,9 @@ func (s *CLITestSuite) TestNewCmdWeightedVote() { fmt.Sprintf("--%s=true", flags.FlagSkipConfirmation), fmt.Sprintf("--%s=%s", flags.FlagBroadcastMode, flags.BroadcastSync), fmt.Sprintf("--metadata=%s", "AQ=="), - fmt.Sprintf("--%s=%s", flags.FlagFees, sdk.NewCoins(sdk.NewCoin("stake", sdk.NewInt(10))).String()), + fmt.Sprintf("--%s=%s", flags.FlagFees, sdk.NewCoins(sdk.NewCoin("stake", sdkmath.NewInt(10))).String()), }, - false, 0, + "", }, { "invalid valid split vote string", @@ -459,9 +474,9 @@ func (s *CLITestSuite) TestNewCmdWeightedVote() { fmt.Sprintf("--%s=%s", flags.FlagFrom, val[0].Address.String()), fmt.Sprintf("--%s=true", flags.FlagSkipConfirmation), fmt.Sprintf("--%s=%s", flags.FlagBroadcastMode, flags.BroadcastSync), - fmt.Sprintf("--%s=%s", flags.FlagFees, sdk.NewCoins(sdk.NewCoin("stake", sdk.NewInt(10))).String()), + fmt.Sprintf("--%s=%s", flags.FlagFees, sdk.NewCoins(sdk.NewCoin("stake", sdkmath.NewInt(10))).String()), }, - true, 0, + "'yes/0.6' is not a valid vote option", }, { "valid split vote", @@ -471,9 +486,9 @@ func (s *CLITestSuite) TestNewCmdWeightedVote() { fmt.Sprintf("--%s=%s", flags.FlagFrom, val[0].Address.String()), fmt.Sprintf("--%s=true", flags.FlagSkipConfirmation), fmt.Sprintf("--%s=%s", flags.FlagBroadcastMode, flags.BroadcastSync), - fmt.Sprintf("--%s=%s", flags.FlagFees, sdk.NewCoins(sdk.NewCoin("stake", sdk.NewInt(10))).String()), + fmt.Sprintf("--%s=%s", flags.FlagFees, sdk.NewCoins(sdk.NewCoin("stake", sdkmath.NewInt(10))).String()), }, - false, 0, + "", }, } @@ -481,15 +496,14 @@ func (s *CLITestSuite) TestNewCmdWeightedVote() { tc := tc s.Run(tc.name, func() { cmd := cli.NewCmdWeightedVote() - var txResp sdk.TxResponse - out, err := clitestutil.ExecTestCLICmd(s.clientCtx, cmd, tc.args) - - if tc.expectErr { + if tc.expectErrMsg != "" { s.Require().Error(err) + s.Require().Contains(err.Error(), tc.expectErrMsg) } else { s.Require().NoError(err) - s.Require().NoError(s.clientCtx.Codec.UnmarshalJSON(out.Bytes(), &txResp), out.String()) + resp := &sdk.TxResponse{} + s.Require().NoError(s.clientCtx.Codec.UnmarshalJSON(out.Bytes(), resp), out.String()) } }) } diff --git a/x/gov/client/cli/util_test.go b/x/gov/client/cli/util_test.go index 53b40293e376..06aa1e5f4fac 100644 --- a/x/gov/client/cli/util_test.go +++ b/x/gov/client/cli/util_test.go @@ -9,6 +9,7 @@ import ( "strings" "testing" + sdkmath "cosmossdk.io/math" "github.com/spf13/cobra" "github.com/stretchr/testify/assert" "github.com/stretchr/testify/require" @@ -181,19 +182,19 @@ func TestParseSubmitProposal(t *testing.T) { // ok json proposal, msgs, deposit, err := parseSubmitProposal(cdc, okJSON.Name()) require.NoError(t, err, "unexpected error") - require.Equal(t, sdk.NewCoins(sdk.NewCoin("test", sdk.NewInt(1000))), deposit) + require.Equal(t, sdk.NewCoins(sdk.NewCoin("test", sdkmath.NewInt(1000))), deposit) require.Equal(t, base64.StdEncoding.EncodeToString(expectedMetadata), proposal.Metadata) require.Len(t, msgs, 3) msg1, ok := msgs[0].(*banktypes.MsgSend) require.True(t, ok) require.Equal(t, addr.String(), msg1.FromAddress) require.Equal(t, addr.String(), msg1.ToAddress) - require.Equal(t, sdk.NewCoins(sdk.NewCoin("stake", sdk.NewInt(10))), msg1.Amount) + require.Equal(t, sdk.NewCoins(sdk.NewCoin("stake", sdkmath.NewInt(10))), msg1.Amount) msg2, ok := msgs[1].(*stakingtypes.MsgDelegate) require.True(t, ok) require.Equal(t, addr.String(), msg2.DelegatorAddress) require.Equal(t, addr.String(), msg2.ValidatorAddress) - require.Equal(t, sdk.NewCoin("stake", sdk.NewInt(10)), msg2.Amount) + require.Equal(t, sdk.NewCoin("stake", sdkmath.NewInt(10)), msg2.Amount) msg3, ok := msgs[2].(*v1.MsgExecLegacyContent) require.True(t, ok) require.Equal(t, addr.String(), msg3.Authority) diff --git a/x/gov/client/testutil/helpers.go b/x/gov/client/testutil/helpers.go index 2e9baf92db73..c772126c4bcd 100644 --- a/x/gov/client/testutil/helpers.go +++ b/x/gov/client/testutil/helpers.go @@ -3,6 +3,8 @@ package testutil import ( "fmt" + sdkmath "cosmossdk.io/math" + "github.com/cosmos/cosmos-sdk/client" "github.com/cosmos/cosmos-sdk/client/flags" "github.com/cosmos/cosmos-sdk/testutil" @@ -14,7 +16,7 @@ import ( var commonArgs = []string{ fmt.Sprintf("--%s=true", flags.FlagSkipConfirmation), fmt.Sprintf("--%s=%s", flags.FlagBroadcastMode, flags.BroadcastSync), - fmt.Sprintf("--%s=%s", flags.FlagFees, sdk.NewCoins(sdk.NewCoin(sdk.DefaultBondDenom, sdk.NewInt(10))).String()), + fmt.Sprintf("--%s=%s", flags.FlagFees, sdk.NewCoins(sdk.NewCoin(sdk.DefaultBondDenom, sdkmath.NewInt(10))).String()), } // MsgSubmitLegacyProposal creates a tx for submit legacy proposal diff --git a/x/gov/client/utils/query.go b/x/gov/client/utils/query.go index 8bbd30220e18..6ee7ca4a6541 100644 --- a/x/gov/client/utils/query.go +++ b/x/gov/client/utils/query.go @@ -35,7 +35,7 @@ func (p Proposer) String() string { // QueryVotesByTxQuery will query for votes via a direct txs tags query. It // will fetch and build votes directly from the returned txs and returns a JSON -// marshalled result or any error that occurred. +// marshaled result or any error that occurred. func QueryVotesByTxQuery(clientCtx client.Context, params v1.QueryProposalVotesParams) ([]byte, error) { var ( votes []*v1.Vote diff --git a/x/gov/client/utils/query_test.go b/x/gov/client/utils/query_test.go index 458836cd8bb1..3210396c9d3a 100644 --- a/x/gov/client/utils/query_test.go +++ b/x/gov/client/utils/query_test.go @@ -4,6 +4,7 @@ import ( "context" "testing" + sdkmath "cosmossdk.io/math" "github.com/cometbft/cometbft/rpc/client/mock" coretypes "github.com/cometbft/cometbft/rpc/core/types" cmttypes "github.com/cometbft/cometbft/types" @@ -67,7 +68,7 @@ func TestGetPaginatedVotes(t *testing.T) { acc1Msgs := []sdk.Msg{ v1.NewMsgVote(acc1, 0, v1.OptionYes, ""), v1.NewMsgVote(acc1, 0, v1.OptionYes, ""), - v1.NewMsgDeposit(acc1, 0, sdk.NewCoins(sdk.NewCoin("stake", sdk.NewInt(10)))), // should be ignored + v1.NewMsgDeposit(acc1, 0, sdk.NewCoins(sdk.NewCoin("stake", sdkmath.NewInt(10)))), // should be ignored } acc2Msgs := []sdk.Msg{ v1.NewMsgVote(acc2, 0, v1.OptionYes, ""), @@ -141,8 +142,8 @@ func TestGetPaginatedVotes(t *testing.T) { tc := tc t.Run(tc.description, func(t *testing.T) { - marshalled := make([]cmttypes.Tx, len(tc.msgs)) - cli := TxSearchMock{txs: marshalled, txConfig: encCfg.TxConfig} + marshaled := make([]cmttypes.Tx, len(tc.msgs)) + cli := TxSearchMock{txs: marshaled, txConfig: encCfg.TxConfig} clientCtx := client.Context{}. WithLegacyAmino(encCfg.Amino). WithClient(cli). @@ -155,7 +156,7 @@ func TestGetPaginatedVotes(t *testing.T) { tx, err := clientCtx.TxConfig.TxEncoder()(txBuilder.GetTx()) require.NoError(t, err) - marshalled[i] = tx + marshaled[i] = tx } params := v1.NewQueryProposalVotesParams(0, tc.page, tc.limit) diff --git a/x/gov/genesis_test.go b/x/gov/genesis_test.go index 909a5d0ca992..5b8b0d32c6f4 100644 --- a/x/gov/genesis_test.go +++ b/x/gov/genesis_test.go @@ -3,6 +3,7 @@ package gov_test import ( "testing" + sdkmath "cosmossdk.io/math" cmtproto "github.com/cometbft/cometbft/proto/tendermint/types" "github.com/stretchr/testify/require" @@ -24,7 +25,7 @@ func TestImportExportQueues_ErrorUnconsistentState(t *testing.T) { Amount: sdk.Coins{ sdk.NewCoin( "stake", - sdk.NewInt(1234), + sdkmath.NewInt(1234), ), }, }, diff --git a/x/gov/keeper/common_test.go b/x/gov/keeper/common_test.go index 3c1af49a2aeb..fe17762e0b54 100644 --- a/x/gov/keeper/common_test.go +++ b/x/gov/keeper/common_test.go @@ -42,7 +42,7 @@ func getTestProposal() []sdk.Msg { } return []sdk.Msg{ - banktypes.NewMsgSend(govAcct, addr, sdk.NewCoins(sdk.NewCoin("stake", sdk.NewInt(1000)))), + banktypes.NewMsgSend(govAcct, addr, sdk.NewCoins(sdk.NewCoin("stake", math.NewInt(1000)))), legacyProposalMsg, } } @@ -79,10 +79,14 @@ func setupGovKeeper(t *testing.T) ( acctKeeper.EXPECT().GetModuleAddress(types.ModuleName).Return(govAcct).AnyTimes() acctKeeper.EXPECT().GetModuleAddress(disttypes.ModuleName).Return(distAcct).AnyTimes() acctKeeper.EXPECT().GetModuleAccount(gomock.Any(), types.ModuleName).Return(authtypes.NewEmptyModuleAccount(types.ModuleName)).AnyTimes() + acctKeeper.EXPECT().StringToBytes(govAcct.String()).Return(govAcct, nil).AnyTimes() + acctKeeper.EXPECT().BytesToString(govAcct).Return(govAcct.String(), nil).AnyTimes() + trackMockBalances(bankKeeper, distributionKeeper) stakingKeeper.EXPECT().TokensFromConsensusPower(ctx, gomock.Any()).DoAndReturn(func(ctx sdk.Context, power int64) math.Int { return sdk.TokensFromConsensusPower(power, math.NewIntFromUint64(1000000)) }).AnyTimes() + stakingKeeper.EXPECT().BondDenom(ctx).Return("stake").AnyTimes() stakingKeeper.EXPECT().IterateBondedValidatorsByPower(gomock.Any(), gomock.Any()).AnyTimes() stakingKeeper.EXPECT().IterateDelegations(gomock.Any(), gomock.Any(), gomock.Any()).AnyTimes() @@ -109,7 +113,7 @@ func setupGovKeeper(t *testing.T) ( // locally tracks accounts balances (not modules balances). func trackMockBalances(bankKeeper *govtestutil.MockBankKeeper, distributionKeeper *govtestutil.MockDistributionKeeper) { balances := make(map[string]sdk.Coins) - balances[distAcct.String()] = sdk.NewCoins(sdk.NewCoin(sdk.DefaultBondDenom, sdk.NewInt(0))) + balances[distAcct.String()] = sdk.NewCoins(sdk.NewCoin(sdk.DefaultBondDenom, math.NewInt(0))) // We don't track module account balances. bankKeeper.EXPECT().MintCoins(gomock.Any(), minttypes.ModuleName, gomock.Any()).AnyTimes() @@ -139,7 +143,7 @@ func trackMockBalances(bankKeeper *govtestutil.MockBankKeeper, distributionKeepe return balance } } - return sdk.NewCoin(sdk.DefaultBondDenom, sdk.NewInt(0)) + return sdk.NewCoin(sdk.DefaultBondDenom, math.NewInt(0)) }).AnyTimes() distributionKeeper.EXPECT().FundCommunityPool(gomock.Any(), gomock.Any(), gomock.Any()).DoAndReturn(func(_ sdk.Context, coins sdk.Coins, sender sdk.AccAddress) error { diff --git a/x/gov/keeper/deposit.go b/x/gov/keeper/deposit.go index e7901e11d400..e83cc493848d 100644 --- a/x/gov/keeper/deposit.go +++ b/x/gov/keeper/deposit.go @@ -4,6 +4,7 @@ import ( "fmt" "cosmossdk.io/errors" + sdkmath "cosmossdk.io/math" storetypes "cosmossdk.io/store/types" sdk "github.com/cosmos/cosmos-sdk/types" @@ -29,7 +30,10 @@ func (keeper Keeper) GetDeposit(ctx sdk.Context, proposalID uint64, depositorAdd func (keeper Keeper) SetDeposit(ctx sdk.Context, deposit v1.Deposit) { store := ctx.KVStore(keeper.storeKey) bz := keeper.cdc.MustMarshal(&deposit) - depositor := sdk.MustAccAddressFromBech32(deposit.Depositor) + depositor, err := keeper.authKeeper.StringToBytes(deposit.Depositor) + if err != nil { + panic(err) + } store.Set(types.DepositKey(deposit.ProposalId, depositor), bz) } @@ -64,7 +68,10 @@ func (keeper Keeper) DeleteAndBurnDeposits(ctx sdk.Context, proposalID uint64) { panic(err) } - depositor := sdk.MustAccAddressFromBech32(deposit.Depositor) + depositor, err := keeper.authKeeper.StringToBytes(deposit.Depositor) + if err != nil { + panic(err) + } store.Delete(types.DepositKey(proposalID, depositor)) return false @@ -171,11 +178,15 @@ func (keeper Keeper) AddDeposit(ctx sdk.Context, proposalID uint64, depositorAdd // Remaining funds are send back to the depositor. func (keeper Keeper) ChargeDeposit(ctx sdk.Context, proposalID uint64, destAddress, proposalCancelRate string) error { store := ctx.KVStore(keeper.storeKey) - rate := sdk.MustNewDecFromStr(proposalCancelRate) + rate := sdkmath.LegacyMustNewDecFromStr(proposalCancelRate) var cancellationCharges sdk.Coins for _, deposit := range keeper.GetDeposits(ctx, proposalID) { - depositerAddress := sdk.MustAccAddressFromBech32(deposit.Depositor) + depositerAddress, err := keeper.authKeeper.StringToBytes(deposit.Depositor) + if err != nil { + return err + } + var remainingAmount sdk.Coins for _, coins := range deposit.Amount { @@ -224,8 +235,11 @@ func (keeper Keeper) ChargeDeposit(ctx sdk.Context, proposalID uint64, destAddre return err } default: - destAccAddress := sdk.MustAccAddressFromBech32(destAddress) - err := keeper.bankKeeper.SendCoinsFromModuleToAccount( + destAccAddress, err := keeper.authKeeper.StringToBytes(destAddress) + if err != nil { + return err + } + err = keeper.bankKeeper.SendCoinsFromModuleToAccount( ctx, types.ModuleName, destAccAddress, cancellationCharges, ) if err != nil { @@ -242,9 +256,12 @@ func (keeper Keeper) RefundAndDeleteDeposits(ctx sdk.Context, proposalID uint64) store := ctx.KVStore(keeper.storeKey) keeper.IterateDeposits(ctx, proposalID, func(deposit v1.Deposit) bool { - depositor := sdk.MustAccAddressFromBech32(deposit.Depositor) + depositor, err := keeper.authKeeper.StringToBytes(deposit.Depositor) + if err != nil { + panic(err) + } - err := keeper.bankKeeper.SendCoinsFromModuleToAccount(ctx, types.ModuleName, depositor, deposit.Amount) + err = keeper.bankKeeper.SendCoinsFromModuleToAccount(ctx, types.ModuleName, depositor, deposit.Amount) if err != nil { panic(err) } diff --git a/x/gov/keeper/deposit_test.go b/x/gov/keeper/deposit_test.go index 9eb9c8478577..90eb68069cde 100644 --- a/x/gov/keeper/deposit_test.go +++ b/x/gov/keeper/deposit_test.go @@ -4,9 +4,10 @@ import ( "fmt" "testing" - "cosmossdk.io/math" + sdkmath "cosmossdk.io/math" "github.com/stretchr/testify/require" + "github.com/cosmos/cosmos-sdk/codec/address" simtestutil "github.com/cosmos/cosmos-sdk/testutil/sims" sdk "github.com/cosmos/cosmos-sdk/types" authtypes "github.com/cosmos/cosmos-sdk/x/auth/types" @@ -35,7 +36,7 @@ func TestDeposits(t *testing.T) { for _, tc := range testcases { t.Run(tc.name, func(t *testing.T) { - govKeeper, _, bankKeeper, stakingKeeper, distKeeper, _, ctx := setupGovKeeper(t) + govKeeper, authKeeper, bankKeeper, stakingKeeper, distKeeper, _, ctx := setupGovKeeper(t) trackMockBalances(bankKeeper, distKeeper) // With expedited proposals the minimum deposit is higher, so we must @@ -46,7 +47,11 @@ func TestDeposits(t *testing.T) { depositMultiplier = v1.DefaultMinExpeditedDepositTokensRatio } - TestAddrs := simtestutil.AddTestAddrsIncremental(bankKeeper, stakingKeeper, ctx, 2, sdk.NewInt(10000000*depositMultiplier)) + TestAddrs := simtestutil.AddTestAddrsIncremental(bankKeeper, stakingKeeper, ctx, 2, sdkmath.NewInt(10000000*depositMultiplier)) + for _, addr := range TestAddrs { + authKeeper.EXPECT().BytesToString(addr).Return(addr.String(), nil).AnyTimes() + authKeeper.EXPECT().StringToBytes(addr.String()).Return(addr, nil).AnyTimes() + } tp := TestProposal proposal, err := govKeeper.SubmitProposal(ctx, tp, "", "title", "summary", TestAddrs[0], tc.expedited) @@ -156,79 +161,79 @@ func TestValidateInitialDeposit(t *testing.T) { expectError bool }{ "min deposit * initial percent == initial deposit: success": { - minDeposit: sdk.NewCoins(sdk.NewCoin(sdk.DefaultBondDenom, sdk.NewInt(baseDepositTestAmount))), + minDeposit: sdk.NewCoins(sdk.NewCoin(sdk.DefaultBondDenom, sdkmath.NewInt(baseDepositTestAmount))), minInitialDepositPercent: baseDepositTestPercent, - initialDeposit: sdk.NewCoins(sdk.NewCoin(sdk.DefaultBondDenom, sdk.NewInt(baseDepositTestAmount*baseDepositTestPercent/100))), + initialDeposit: sdk.NewCoins(sdk.NewCoin(sdk.DefaultBondDenom, sdkmath.NewInt(baseDepositTestAmount*baseDepositTestPercent/100))), }, "min deposit * initial percent < initial deposit: success": { - minDeposit: sdk.NewCoins(sdk.NewCoin(sdk.DefaultBondDenom, sdk.NewInt(baseDepositTestAmount))), + minDeposit: sdk.NewCoins(sdk.NewCoin(sdk.DefaultBondDenom, sdkmath.NewInt(baseDepositTestAmount))), minInitialDepositPercent: baseDepositTestPercent, - initialDeposit: sdk.NewCoins(sdk.NewCoin(sdk.DefaultBondDenom, sdk.NewInt(baseDepositTestAmount*baseDepositTestPercent/100+1))), + initialDeposit: sdk.NewCoins(sdk.NewCoin(sdk.DefaultBondDenom, sdkmath.NewInt(baseDepositTestAmount*baseDepositTestPercent/100+1))), }, "min deposit * initial percent > initial deposit: error": { - minDeposit: sdk.NewCoins(sdk.NewCoin(sdk.DefaultBondDenom, sdk.NewInt(baseDepositTestAmount))), + minDeposit: sdk.NewCoins(sdk.NewCoin(sdk.DefaultBondDenom, sdkmath.NewInt(baseDepositTestAmount))), minInitialDepositPercent: baseDepositTestPercent, - initialDeposit: sdk.NewCoins(sdk.NewCoin(sdk.DefaultBondDenom, sdk.NewInt(baseDepositTestAmount*baseDepositTestPercent/100-1))), + initialDeposit: sdk.NewCoins(sdk.NewCoin(sdk.DefaultBondDenom, sdkmath.NewInt(baseDepositTestAmount*baseDepositTestPercent/100-1))), expectError: true, }, "min deposit * initial percent == initial deposit (non-base values and denom): success": { - minDeposit: sdk.NewCoins(sdk.NewCoin("uosmo", sdk.NewInt(56912))), + minDeposit: sdk.NewCoins(sdk.NewCoin("uosmo", sdkmath.NewInt(56912))), minInitialDepositPercent: 50, - initialDeposit: sdk.NewCoins(sdk.NewCoin("uosmo", sdk.NewInt(56912/2+10))), + initialDeposit: sdk.NewCoins(sdk.NewCoin("uosmo", sdkmath.NewInt(56912/2+10))), }, "min deposit * initial percent == initial deposit but different denoms: error": { - minDeposit: sdk.NewCoins(sdk.NewCoin(sdk.DefaultBondDenom, sdk.NewInt(baseDepositTestAmount))), + minDeposit: sdk.NewCoins(sdk.NewCoin(sdk.DefaultBondDenom, sdkmath.NewInt(baseDepositTestAmount))), minInitialDepositPercent: baseDepositTestPercent, - initialDeposit: sdk.NewCoins(sdk.NewCoin("uosmo", sdk.NewInt(baseDepositTestAmount*baseDepositTestPercent/100))), + initialDeposit: sdk.NewCoins(sdk.NewCoin("uosmo", sdkmath.NewInt(baseDepositTestAmount*baseDepositTestPercent/100))), expectError: true, }, "min deposit * initial percent == initial deposit (multiple coins): success": { minDeposit: sdk.NewCoins( - sdk.NewCoin(sdk.DefaultBondDenom, sdk.NewInt(baseDepositTestAmount)), - sdk.NewCoin("uosmo", sdk.NewInt(baseDepositTestAmount*2))), + sdk.NewCoin(sdk.DefaultBondDenom, sdkmath.NewInt(baseDepositTestAmount)), + sdk.NewCoin("uosmo", sdkmath.NewInt(baseDepositTestAmount*2))), minInitialDepositPercent: baseDepositTestPercent, initialDeposit: sdk.NewCoins( - sdk.NewCoin(sdk.DefaultBondDenom, sdk.NewInt(baseDepositTestAmount*baseDepositTestPercent/100)), - sdk.NewCoin("uosmo", sdk.NewInt(baseDepositTestAmount*2*baseDepositTestPercent/100)), + sdk.NewCoin(sdk.DefaultBondDenom, sdkmath.NewInt(baseDepositTestAmount*baseDepositTestPercent/100)), + sdk.NewCoin("uosmo", sdkmath.NewInt(baseDepositTestAmount*2*baseDepositTestPercent/100)), ), }, "min deposit * initial percent > initial deposit (multiple coins): error": { minDeposit: sdk.NewCoins( - sdk.NewCoin(sdk.DefaultBondDenom, sdk.NewInt(baseDepositTestAmount)), - sdk.NewCoin("uosmo", sdk.NewInt(baseDepositTestAmount*2))), + sdk.NewCoin(sdk.DefaultBondDenom, sdkmath.NewInt(baseDepositTestAmount)), + sdk.NewCoin("uosmo", sdkmath.NewInt(baseDepositTestAmount*2))), minInitialDepositPercent: baseDepositTestPercent, initialDeposit: sdk.NewCoins( - sdk.NewCoin(sdk.DefaultBondDenom, sdk.NewInt(baseDepositTestAmount*baseDepositTestPercent/100)), - sdk.NewCoin("uosmo", sdk.NewInt(baseDepositTestAmount*2*baseDepositTestPercent/100-1)), + sdk.NewCoin(sdk.DefaultBondDenom, sdkmath.NewInt(baseDepositTestAmount*baseDepositTestPercent/100)), + sdk.NewCoin("uosmo", sdkmath.NewInt(baseDepositTestAmount*2*baseDepositTestPercent/100-1)), ), expectError: true, }, "min deposit * initial percent < initial deposit (multiple coins - coin not required by min deposit): success": { - minDeposit: sdk.NewCoins(sdk.NewCoin(sdk.DefaultBondDenom, sdk.NewInt(baseDepositTestAmount))), + minDeposit: sdk.NewCoins(sdk.NewCoin(sdk.DefaultBondDenom, sdkmath.NewInt(baseDepositTestAmount))), minInitialDepositPercent: baseDepositTestPercent, initialDeposit: sdk.NewCoins( - sdk.NewCoin(sdk.DefaultBondDenom, sdk.NewInt(baseDepositTestAmount*baseDepositTestPercent/100)), - sdk.NewCoin("uosmo", sdk.NewInt(baseDepositTestAmount*baseDepositTestPercent/100-1)), + sdk.NewCoin(sdk.DefaultBondDenom, sdkmath.NewInt(baseDepositTestAmount*baseDepositTestPercent/100)), + sdk.NewCoin("uosmo", sdkmath.NewInt(baseDepositTestAmount*baseDepositTestPercent/100-1)), ), }, "0 initial percent: success": { - minDeposit: sdk.NewCoins(sdk.NewCoin(sdk.DefaultBondDenom, sdk.NewInt(baseDepositTestAmount))), + minDeposit: sdk.NewCoins(sdk.NewCoin(sdk.DefaultBondDenom, sdkmath.NewInt(baseDepositTestAmount))), minInitialDepositPercent: 0, - initialDeposit: sdk.NewCoins(sdk.NewCoin(sdk.DefaultBondDenom, sdk.NewInt(baseDepositTestAmount*baseDepositTestPercent/100))), + initialDeposit: sdk.NewCoins(sdk.NewCoin(sdk.DefaultBondDenom, sdkmath.NewInt(baseDepositTestAmount*baseDepositTestPercent/100))), }, "expedited min deposit * initial percent == initial deposit: success": { - minDeposit: sdk.NewCoins(sdk.NewCoin(sdk.DefaultBondDenom, sdk.NewInt(baseDepositTestAmount))), + minDeposit: sdk.NewCoins(sdk.NewCoin(sdk.DefaultBondDenom, sdkmath.NewInt(baseDepositTestAmount))), minInitialDepositPercent: baseDepositTestPercent, - initialDeposit: sdk.NewCoins(sdk.NewCoin(sdk.DefaultBondDenom, sdk.NewInt(baseDepositTestAmount*baseDepositTestPercent/100))), + initialDeposit: sdk.NewCoins(sdk.NewCoin(sdk.DefaultBondDenom, sdkmath.NewInt(baseDepositTestAmount*baseDepositTestPercent/100))), expedited: true, }, "expedited - 0 initial percent: success": { - minDeposit: sdk.NewCoins(sdk.NewCoin(sdk.DefaultBondDenom, sdk.NewInt(baseDepositTestAmount))), + minDeposit: sdk.NewCoins(sdk.NewCoin(sdk.DefaultBondDenom, sdkmath.NewInt(baseDepositTestAmount))), minInitialDepositPercent: 0, - initialDeposit: sdk.NewCoins(sdk.NewCoin(sdk.DefaultBondDenom, sdk.NewInt(baseDepositTestAmount*baseDepositTestPercent/100))), + initialDeposit: sdk.NewCoins(sdk.NewCoin(sdk.DefaultBondDenom, sdkmath.NewInt(baseDepositTestAmount*baseDepositTestPercent/100))), expedited: true, }, } @@ -243,7 +248,7 @@ func TestValidateInitialDeposit(t *testing.T) { } else { params.MinDeposit = tc.minDeposit } - params.MinInitialDepositRatio = sdk.NewDec(tc.minInitialDepositPercent).Quo(sdk.NewDec(100)).String() + params.MinInitialDepositRatio = sdkmath.LegacyNewDec(tc.minInitialDepositPercent).Quo(sdkmath.LegacyNewDec(100)).String() govKeeper.SetParams(ctx, params) @@ -297,10 +302,14 @@ func TestChargeDeposit(t *testing.T) { } t.Run(testName(i), func(t *testing.T) { - govKeeper, _, bankKeeper, stakingKeeper, _, _, ctx := setupGovKeeper(t) + govKeeper, authKeeper, bankKeeper, stakingKeeper, _, _, ctx := setupGovKeeper(t) params := v1.DefaultParams() params.ProposalCancelRatio = tc.proposalCancelRatio TestAddrs := simtestutil.AddTestAddrsIncremental(bankKeeper, stakingKeeper, ctx, 2, sdk.NewInt(10000000000)) + for _, addr := range TestAddrs { + authKeeper.EXPECT().BytesToString(addr).Return(addr.String(), nil).AnyTimes() + authKeeper.EXPECT().StringToBytes(addr.String()).Return(addr, nil).AnyTimes() + } switch i { case 0: @@ -326,10 +335,12 @@ func TestChargeDeposit(t *testing.T) { _, err = govKeeper.AddDeposit(ctx, proposalID, TestAddrs[0], fiveStake) require.NoError(t, err) + codec := address.NewBech32Codec("cosmos") // get balances of dest address var prevBalance sdk.Coin if len(params.ProposalCancelDest) != 0 { - accAddr := sdk.MustAccAddressFromBech32(params.ProposalCancelDest) + accAddr, err := codec.StringToBytes(params.ProposalCancelDest) + require.NoError(t, err) prevBalance = bankKeeper.GetBalance(ctx, accAddr, sdk.DefaultBondDenom) } @@ -345,12 +356,13 @@ func TestChargeDeposit(t *testing.T) { require.NoError(t, err) if len(params.ProposalCancelDest) != 0 { - accAddr := sdk.MustAccAddressFromBech32(params.ProposalCancelDest) + accAddr, err := codec.StringToBytes(params.ProposalCancelDest) + require.NoError(t, err) newBalanceAfterCancelProposal := bankKeeper.GetBalance(ctx, accAddr, sdk.DefaultBondDenom) - cancellationCharges := math.NewInt(0) + cancellationCharges := sdkmath.NewInt(0) for _, deposits := range allDeposits { for _, deposit := range deposits.Amount { - burnAmount := sdk.NewDecFromInt(deposit.Amount).Mul(sdk.MustNewDecFromStr(params.MinInitialDepositRatio)).TruncateInt() + burnAmount := sdkmath.LegacyNewDecFromInt(deposit.Amount).Mul(sdkmath.LegacyMustNewDecFromStr(params.MinInitialDepositRatio)).TruncateInt() cancellationCharges = cancellationCharges.Add(burnAmount) } } diff --git a/x/gov/keeper/grpc_query.go b/x/gov/keeper/grpc_query.go index a3dfc4da87b3..54733e649dca 100644 --- a/x/gov/keeper/grpc_query.go +++ b/x/gov/keeper/grpc_query.go @@ -6,6 +6,7 @@ import ( "google.golang.org/grpc/codes" "google.golang.org/grpc/status" + sdkmath "cosmossdk.io/math" "cosmossdk.io/store/prefix" sdk "github.com/cosmos/cosmos-sdk/types" @@ -66,7 +67,7 @@ func (q Keeper) Proposals(c context.Context, req *v1.QueryProposalsRequest) (*v1 // match voter address (if supplied) if len(req.Voter) > 0 { - voter, err := sdk.AccAddressFromBech32(req.Voter) + voter, err := q.authKeeper.StringToBytes(req.Voter) if err != nil { return nil, err } @@ -76,7 +77,7 @@ func (q Keeper) Proposals(c context.Context, req *v1.QueryProposalsRequest) (*v1 // match depositor (if supplied) if len(req.Depositor) > 0 { - depositor, err := sdk.AccAddressFromBech32(req.Depositor) + depositor, err := q.authKeeper.StringToBytes(req.Depositor) if err != nil { return nil, err } @@ -114,7 +115,7 @@ func (q Keeper) Vote(c context.Context, req *v1.QueryVoteRequest) (*v1.QueryVote ctx := sdk.UnwrapSDKContext(c) - voter, err := sdk.AccAddressFromBech32(req.Voter) + voter, err := q.authKeeper.StringToBytes(req.Voter) if err != nil { return nil, err } @@ -143,7 +144,7 @@ func (q Keeper) Votes(c context.Context, req *v1.QueryVotesRequest) (*v1.QueryVo store := ctx.KVStore(q.storeKey) votesStore := prefix.NewStore(store, types.VotesKey(req.ProposalId)) - pageRes, err := query.Paginate(votesStore, req.Pagination, func(key []byte, value []byte) error { + pageRes, err := query.Paginate(votesStore, req.Pagination, func(key, value []byte) error { var vote v1.Vote if err := q.cdc.Unmarshal(value, &vote); err != nil { return err @@ -170,7 +171,7 @@ func (q Keeper) Params(c context.Context, req *v1.QueryParamsRequest) (*v1.Query response := &v1.QueryParamsResponse{} - //nolint:staticcheck + //nolint:staticcheck // needed for legacy parameters switch req.ParamsType { case v1.ParamDeposit: depositParams := v1.NewDepositParams(params.MinDeposit, params.MaxDepositPeriod) @@ -210,7 +211,7 @@ func (q Keeper) Deposit(c context.Context, req *v1.QueryDepositRequest) (*v1.Que ctx := sdk.UnwrapSDKContext(c) - depositor, err := sdk.AccAddressFromBech32(req.Depositor) + depositor, err := q.authKeeper.StringToBytes(req.Depositor) if err != nil { return nil, err } @@ -239,7 +240,7 @@ func (q Keeper) Deposits(c context.Context, req *v1.QueryDepositsRequest) (*v1.Q store := ctx.KVStore(q.storeKey) depositStore := prefix.NewStore(store, types.DepositsKey(req.ProposalId)) - pageRes, err := query.Paginate(depositStore, req.Pagination, func(key []byte, value []byte) error { + pageRes, err := query.Paginate(depositStore, req.Pagination, func(key, value []byte) error { var deposit v1.Deposit if err := q.cdc.Unmarshal(value, &deposit); err != nil { return err @@ -381,7 +382,7 @@ func (q legacyQueryServer) Votes(c context.Context, req *v1beta1.QueryVotesReque }, nil } -//nolint:staticcheck +//nolint:staticcheck // this is needed for legacy param support func (q legacyQueryServer) Params(c context.Context, req *v1beta1.QueryParamsRequest) (*v1beta1.QueryParamsResponse, error) { resp, err := q.keeper.Params(c, &v1.QueryParamsRequest{ ParamsType: req.ParamsType, @@ -402,15 +403,15 @@ func (q legacyQueryServer) Params(c context.Context, req *v1beta1.QueryParamsReq } if resp.TallyParams != nil { - quorum, err := sdk.NewDecFromStr(resp.TallyParams.Quorum) + quorum, err := sdkmath.LegacyNewDecFromStr(resp.TallyParams.Quorum) if err != nil { return nil, err } - threshold, err := sdk.NewDecFromStr(resp.TallyParams.Threshold) + threshold, err := sdkmath.LegacyNewDecFromStr(resp.TallyParams.Threshold) if err != nil { return nil, err } - vetoThreshold, err := sdk.NewDecFromStr(resp.TallyParams.VetoThreshold) + vetoThreshold, err := sdkmath.LegacyNewDecFromStr(resp.TallyParams.VetoThreshold) if err != nil { return nil, err } diff --git a/x/gov/keeper/grpc_query_test.go b/x/gov/keeper/grpc_query_test.go index 56543c142711..7c63d36417fc 100644 --- a/x/gov/keeper/grpc_query_test.go +++ b/x/gov/keeper/grpc_query_test.go @@ -9,6 +9,8 @@ import ( simtestutil "github.com/cosmos/cosmos-sdk/testutil/sims" sdk "github.com/cosmos/cosmos-sdk/types" + + "github.com/cosmos/cosmos-sdk/codec/address" "github.com/cosmos/cosmos-sdk/types/query" v3 "github.com/cosmos/cosmos-sdk/x/gov/migrations/v3" v1 "github.com/cosmos/cosmos-sdk/x/gov/types/v1" @@ -556,7 +558,7 @@ func (suite *KeeperTestSuite) TestLegacyGRPCQueryVote() { Voter: addrs[0].String(), } - expRes = &v1beta1.QueryVoteResponse{Vote: v1beta1.Vote{ProposalId: proposal.Id, Voter: addrs[0].String(), Options: []v1beta1.WeightedVoteOption{{Option: v1beta1.OptionAbstain, Weight: sdk.MustNewDecFromStr("1.0")}}}} + expRes = &v1beta1.QueryVoteResponse{Vote: v1beta1.Vote{ProposalId: proposal.Id, Voter: addrs[0].String(), Options: []v1beta1.WeightedVoteOption{{Option: v1beta1.OptionAbstain, Weight: math.LegacyMustNewDecFromStr("1.0")}}}} }, true, }, @@ -595,7 +597,7 @@ func (suite *KeeperTestSuite) TestGRPCQueryVotes() { suite.reset() ctx, queryClient := suite.ctx, suite.queryClient - addrs := simtestutil.AddTestAddrsIncremental(suite.bankKeeper, suite.stakingKeeper, ctx, 2, sdk.NewInt(30000000)) + addrs := simtestutil.AddTestAddrsIncremental(suite.bankKeeper, suite.stakingKeeper, ctx, 2, math.NewInt(30000000)) var ( req *v1.QueryVotesRequest @@ -657,8 +659,10 @@ func (suite *KeeperTestSuite) TestGRPCQueryVotes() { {ProposalId: proposal.Id, Voter: addrs[0].String(), Options: v1.NewNonSplitVoteOption(v1.OptionAbstain)}, {ProposalId: proposal.Id, Voter: addrs[1].String(), Options: v1.NewNonSplitVoteOption(v1.OptionYes)}, } - accAddr1, err1 := sdk.AccAddressFromBech32(votes[0].Voter) - accAddr2, err2 := sdk.AccAddressFromBech32(votes[1].Voter) + + codec := address.NewBech32Codec("cosmos") + accAddr1, err1 := codec.StringToBytes(votes[0].Voter) + accAddr2, err2 := codec.StringToBytes(votes[1].Voter) suite.Require().NoError(err1) suite.Require().NoError(err2) suite.Require().NoError(suite.govKeeper.AddVote(ctx, proposal.Id, accAddr1, votes[0].Options, "")) @@ -697,7 +701,7 @@ func (suite *KeeperTestSuite) TestLegacyGRPCQueryVotes() { suite.reset() ctx, queryClient := suite.ctx, suite.legacyQueryClient - addrs := simtestutil.AddTestAddrsIncremental(suite.bankKeeper, suite.stakingKeeper, ctx, 2, sdk.NewInt(30000000)) + addrs := simtestutil.AddTestAddrsIncremental(suite.bankKeeper, suite.stakingKeeper, ctx, 2, math.NewInt(30000000)) var ( req *v1beta1.QueryVotesRequest @@ -759,8 +763,10 @@ func (suite *KeeperTestSuite) TestLegacyGRPCQueryVotes() { {ProposalId: proposal.Id, Voter: addrs[0].String(), Options: v1beta1.NewNonSplitVoteOption(v1beta1.OptionAbstain)}, {ProposalId: proposal.Id, Voter: addrs[1].String(), Options: v1beta1.NewNonSplitVoteOption(v1beta1.OptionYes)}, } - accAddr1, err1 := sdk.AccAddressFromBech32(votes[0].Voter) - accAddr2, err2 := sdk.AccAddressFromBech32(votes[1].Voter) + codec := address.NewBech32Codec("cosmos") + + accAddr1, err1 := codec.StringToBytes(votes[0].Voter) + accAddr2, err2 := codec.StringToBytes(votes[1].Voter) suite.Require().NoError(err1) suite.Require().NoError(err2) suite.Require().NoError(suite.govKeeper.AddVote(ctx, proposal.Id, accAddr1, v1.NewNonSplitVoteOption(v1.OptionAbstain), "")) diff --git a/x/gov/keeper/hooks_test.go b/x/gov/keeper/hooks_test.go index 0711d8fd48bd..430f6487bc20 100644 --- a/x/gov/keeper/hooks_test.go +++ b/x/gov/keeper/hooks_test.go @@ -47,9 +47,14 @@ func (h *MockGovHooksReceiver) AfterProposalVotingPeriodEnded(ctx sdk.Context, p func TestHooks(t *testing.T) { minDeposit := v1.DefaultParams().MinDeposit - govKeeper, _, bankKeeper, stakingKeeper, _, _, ctx := setupGovKeeper(t) + govKeeper, authKeeper, bankKeeper, stakingKeeper, _, _, ctx := setupGovKeeper(t) addrs := simtestutil.AddTestAddrs(bankKeeper, stakingKeeper, ctx, 1, minDeposit[0].Amount) + for _, addr := range addrs { + authKeeper.EXPECT().BytesToString(addr).Return(addr.String(), nil).AnyTimes() + authKeeper.EXPECT().StringToBytes(addr.String()).Return(addr, nil).AnyTimes() + } + govHooksReceiver := MockGovHooksReceiver{} keeper.UnsafeSetHooks( diff --git a/x/gov/keeper/keeper.go b/x/gov/keeper/keeper.go index 399a4179fc8f..c1ccf6f049dc 100644 --- a/x/gov/keeper/keeper.go +++ b/x/gov/keeper/keeper.go @@ -68,7 +68,7 @@ func NewKeeper( panic(fmt.Sprintf("%s module account has not been set", types.ModuleName)) } - if _, err := sdk.AccAddressFromBech32(authority); err != nil { + if _, err := authKeeper.StringToBytes(authority); err != nil { panic(fmt.Sprintf("invalid authority address: %s", authority)) } diff --git a/x/gov/keeper/keeper_test.go b/x/gov/keeper/keeper_test.go index 028b071a65ff..ab7ba18d64a8 100644 --- a/x/gov/keeper/keeper_test.go +++ b/x/gov/keeper/keeper_test.go @@ -6,8 +6,11 @@ import ( "github.com/stretchr/testify/require" "github.com/stretchr/testify/suite" + sdkmath "cosmossdk.io/math" + "github.com/cosmos/cosmos-sdk/baseapp" "github.com/cosmos/cosmos-sdk/codec" + "github.com/cosmos/cosmos-sdk/codec/address" simtestutil "github.com/cosmos/cosmos-sdk/testutil/sims" sdk "github.com/cosmos/cosmos-sdk/types" "github.com/cosmos/cosmos-sdk/x/gov/keeper" @@ -18,6 +21,8 @@ import ( minttypes "github.com/cosmos/cosmos-sdk/x/mint/types" ) +var address1 = "cosmos1ghekyjucln7y67ntx7cf27m9dpuxxemn4c8g4r" + type KeeperTestSuite struct { suite.Suite @@ -44,7 +49,7 @@ func (suite *KeeperTestSuite) reset() { // Populate the gov account with some coins, as the TestProposal we have // is a MsgSend from the gov account. - coins := sdk.NewCoins(sdk.NewCoin("stake", sdk.NewInt(100000))) + coins := sdk.NewCoins(sdk.NewCoin("stake", sdkmath.NewInt(100000))) err := bankKeeper.MintCoins(suite.ctx, minttypes.ModuleName, coins) suite.NoError(err) err = bankKeeper.SendCoinsFromModuleToModule(ctx, minttypes.ModuleName, types.ModuleName, coins) @@ -69,35 +74,52 @@ func (suite *KeeperTestSuite) reset() { suite.msgSrvr = keeper.NewMsgServerImpl(suite.govKeeper) suite.legacyMsgSrvr = keeper.NewLegacyMsgServerImpl(govAcct.String(), suite.msgSrvr) - suite.addrs = simtestutil.AddTestAddrsIncremental(bankKeeper, stakingKeeper, ctx, 3, sdk.NewInt(30000000)) + suite.addrs = simtestutil.AddTestAddrsIncremental(bankKeeper, stakingKeeper, ctx, 3, sdkmath.NewInt(30000000)) + + for _, addr := range suite.addrs { + suite.acctKeeper.EXPECT().BytesToString(addr).Return(addr.String(), nil).AnyTimes() + suite.acctKeeper.EXPECT().StringToBytes(addr.String()).Return(addr, nil).AnyTimes() + } } func TestIncrementProposalNumber(t *testing.T) { - govKeeper, _, _, _, _, _, ctx := setupGovKeeper(t) //nolint:dogsled + govKeeper, authKeeper, _, _, _, _, ctx := setupGovKeeper(t) + + ac := address.NewBech32Codec("cosmos") + addrBz, err := ac.StringToBytes(address1) + require.NoError(t, err) + authKeeper.EXPECT().StringToBytes(address1).Return(addrBz, nil).AnyTimes() + authKeeper.EXPECT().BytesToString(addrBz).Return(address1, nil).AnyTimes() tp := TestProposal - _, err := govKeeper.SubmitProposal(ctx, tp, "", "test", "summary", sdk.AccAddress("cosmos1ghekyjucln7y67ntx7cf27m9dpuxxemn4c8g4r"), false) + _, err = govKeeper.SubmitProposal(ctx, tp, "", "test", "summary", addrBz, false) require.NoError(t, err) - _, err = govKeeper.SubmitProposal(ctx, tp, "", "test", "summary", sdk.AccAddress("cosmos1ghekyjucln7y67ntx7cf27m9dpuxxemn4c8g4r"), false) + _, err = govKeeper.SubmitProposal(ctx, tp, "", "test", "summary", addrBz, false) require.NoError(t, err) - _, err = govKeeper.SubmitProposal(ctx, tp, "", "test", "summary", sdk.AccAddress("cosmos1ghekyjucln7y67ntx7cf27m9dpuxxemn4c8g4r"), true) + _, err = govKeeper.SubmitProposal(ctx, tp, "", "test", "summary", addrBz, true) require.NoError(t, err) - _, err = govKeeper.SubmitProposal(ctx, tp, "", "test", "summary", sdk.AccAddress("cosmos1ghekyjucln7y67ntx7cf27m9dpuxxemn4c8g4r"), true) + _, err = govKeeper.SubmitProposal(ctx, tp, "", "test", "summary", addrBz, true) require.NoError(t, err) - _, err = govKeeper.SubmitProposal(ctx, tp, "", "test", "summary", sdk.AccAddress("cosmos1ghekyjucln7y67ntx7cf27m9dpuxxemn4c8g4r"), false) + _, err = govKeeper.SubmitProposal(ctx, tp, "", "test", "summary", addrBz, false) require.NoError(t, err) - proposal6, err := govKeeper.SubmitProposal(ctx, tp, "", "test", "summary", sdk.AccAddress("cosmos1ghekyjucln7y67ntx7cf27m9dpuxxemn4c8g4r"), false) + proposal6, err := govKeeper.SubmitProposal(ctx, tp, "", "test", "summary", addrBz, false) require.NoError(t, err) require.Equal(t, uint64(6), proposal6.Id) } func TestProposalQueues(t *testing.T) { - govKeeper, _, _, _, _, _, ctx := setupGovKeeper(t) //nolint:dogsled + govKeeper, authKeeper, _, _, _, _, ctx := setupGovKeeper(t) + + ac := address.NewBech32Codec("cosmos") + addrBz, err := ac.StringToBytes(address1) + require.NoError(t, err) + authKeeper.EXPECT().StringToBytes(address1).Return(addrBz, nil).AnyTimes() + authKeeper.EXPECT().BytesToString(addrBz).Return(address1, nil).AnyTimes() // create test proposals tp := TestProposal - proposal, err := govKeeper.SubmitProposal(ctx, tp, "", "test", "summary", sdk.AccAddress("cosmos1ghekyjucln7y67ntx7cf27m9dpuxxemn4c8g4r"), false) + proposal, err := govKeeper.SubmitProposal(ctx, tp, "", "test", "summary", addrBz, false) require.NoError(t, err) inactiveIterator := govKeeper.InactiveProposalQueueIterator(ctx, *proposal.DepositEndTime) diff --git a/x/gov/keeper/msg_server.go b/x/gov/keeper/msg_server.go index 8e83178246d1..274c881b82b2 100644 --- a/x/gov/keeper/msg_server.go +++ b/x/gov/keeper/msg_server.go @@ -6,10 +6,12 @@ import ( "strconv" "cosmossdk.io/errors" + "cosmossdk.io/math" "github.com/armon/go-metrics" "github.com/cosmos/cosmos-sdk/telemetry" sdk "github.com/cosmos/cosmos-sdk/types" + sdkerrors "github.com/cosmos/cosmos-sdk/types/errors" govtypes "github.com/cosmos/cosmos-sdk/x/gov/types" v1 "github.com/cosmos/cosmos-sdk/x/gov/types/v1" "github.com/cosmos/cosmos-sdk/x/gov/types/v1beta1" @@ -29,17 +31,25 @@ var _ v1.MsgServer = msgServer{} // SubmitProposal implements the MsgServer.SubmitProposal method. func (k msgServer) SubmitProposal(goCtx context.Context, msg *v1.MsgSubmitProposal) (*v1.MsgSubmitProposalResponse, error) { - ctx := sdk.UnwrapSDKContext(goCtx) + if msg.Title == "" { + return nil, errors.Wrap(sdkerrors.ErrInvalidRequest, "proposal title cannot be empty") + } + if msg.Summary == "" { + return nil, errors.Wrap(sdkerrors.ErrInvalidRequest, "proposal summary cannot be empty") + } - initialDeposit := msg.GetInitialDeposit() + proposer, err := k.authKeeper.StringToBytes(msg.GetProposer()) + if err != nil { + return nil, sdkerrors.ErrInvalidAddress.Wrapf("invalid proposer address: %s", err) + } - if err := k.validateInitialDeposit(ctx, initialDeposit, msg.Expedited); err != nil { + if err := validateDeposit(sdk.NewCoins(msg.InitialDeposit...)); err != nil { return nil, err } - proposer, err := sdk.AccAddressFromBech32(msg.GetProposer()) - if err != nil { - return nil, err + // Check that either metadata or Msgs length is non nil. + if len(msg.Messages) == 0 && len(msg.Metadata) == 0 { + return nil, errors.Wrap(govtypes.ErrNoProposalMsgs, "either metadata or Msgs length must be non-nil") } proposalMsgs, err := msg.GetMsgs() @@ -47,6 +57,17 @@ func (k msgServer) SubmitProposal(goCtx context.Context, msg *v1.MsgSubmitPropos return nil, err } + if err := validateMsgs(proposalMsgs); err != nil { + return nil, err + } + + ctx := sdk.UnwrapSDKContext(goCtx) + initialDeposit := msg.GetInitialDeposit() + + if err := k.validateInitialDeposit(ctx, initialDeposit, msg.Expedited); err != nil { + return nil, err + } + proposal, err := k.Keeper.SubmitProposal(ctx, proposalMsgs, msg.Metadata, msg.Title, msg.Summary, proposer, msg.Expedited) if err != nil { return nil, err @@ -85,12 +106,12 @@ func (k msgServer) SubmitProposal(goCtx context.Context, msg *v1.MsgSubmitPropos // CancelProposals implements the MsgServer.CancelProposal method. func (k msgServer) CancelProposal(goCtx context.Context, msg *v1.MsgCancelProposal) (*v1.MsgCancelProposalResponse, error) { - ctx := sdk.UnwrapSDKContext(goCtx) - _, err := sdk.AccAddressFromBech32(msg.Proposer) + _, err := k.authKeeper.StringToBytes(msg.Proposer) if err != nil { - return nil, err + return nil, sdkerrors.ErrInvalidAddress.Wrapf("invalid proposer address: %s", err) } + ctx := sdk.UnwrapSDKContext(goCtx) if err := k.Keeper.CancelProposal(ctx, msg.ProposalId, msg.Proposer); err != nil { return nil, err } @@ -139,11 +160,16 @@ func (k msgServer) ExecLegacyContent(goCtx context.Context, msg *v1.MsgExecLegac // Vote implements the MsgServer.Vote method. func (k msgServer) Vote(goCtx context.Context, msg *v1.MsgVote) (*v1.MsgVoteResponse, error) { - ctx := sdk.UnwrapSDKContext(goCtx) - accAddr, err := sdk.AccAddressFromBech32(msg.Voter) + accAddr, err := k.authKeeper.StringToBytes(msg.Voter) if err != nil { - return nil, err + return nil, sdkerrors.ErrInvalidAddress.Wrapf("invalid voter address: %s", err) } + + if !v1.ValidVoteOption(msg.Option) { + return nil, errors.Wrap(govtypes.ErrInvalidVote, msg.Option.String()) + } + + ctx := sdk.UnwrapSDKContext(goCtx) err = k.Keeper.AddVote(ctx, msg.ProposalId, accAddr, v1.NewNonSplitVoteOption(msg.Option), msg.Metadata) if err != nil { return nil, err @@ -162,11 +188,41 @@ func (k msgServer) Vote(goCtx context.Context, msg *v1.MsgVote) (*v1.MsgVoteResp // VoteWeighted implements the MsgServer.VoteWeighted method. func (k msgServer) VoteWeighted(goCtx context.Context, msg *v1.MsgVoteWeighted) (*v1.MsgVoteWeightedResponse, error) { - ctx := sdk.UnwrapSDKContext(goCtx) - accAddr, accErr := sdk.AccAddressFromBech32(msg.Voter) + accAddr, accErr := k.authKeeper.StringToBytes(msg.Voter) if accErr != nil { - return nil, accErr + return nil, sdkerrors.ErrInvalidAddress.Wrapf("invalid voter address: %s", accErr) + } + + if len(msg.Options) == 0 { + return nil, errors.Wrap(sdkerrors.ErrInvalidRequest, v1.WeightedVoteOptions(msg.Options).String()) + } + + totalWeight := math.LegacyNewDec(0) + usedOptions := make(map[v1.VoteOption]bool) + for _, option := range msg.Options { + if !option.IsValid() { + return nil, errors.Wrap(govtypes.ErrInvalidVote, option.String()) + } + weight, err := sdk.NewDecFromStr(option.Weight) + if err != nil { + return nil, errors.Wrapf(govtypes.ErrInvalidVote, "invalid weight: %s", err) + } + totalWeight = totalWeight.Add(weight) + if usedOptions[option.Option] { + return nil, errors.Wrap(govtypes.ErrInvalidVote, "duplicated vote option") + } + usedOptions[option.Option] = true + } + + if totalWeight.GT(math.LegacyNewDec(1)) { + return nil, errors.Wrap(govtypes.ErrInvalidVote, "total weight overflow 1.00") + } + + if totalWeight.LT(math.LegacyNewDec(1)) { + return nil, errors.Wrap(govtypes.ErrInvalidVote, "total weight lower than 1.00") } + + ctx := sdk.UnwrapSDKContext(goCtx) err := k.Keeper.AddVote(ctx, msg.ProposalId, accAddr, msg.Options, msg.Metadata) if err != nil { return nil, err @@ -185,11 +241,16 @@ func (k msgServer) VoteWeighted(goCtx context.Context, msg *v1.MsgVoteWeighted) // Deposit implements the MsgServer.Deposit method. func (k msgServer) Deposit(goCtx context.Context, msg *v1.MsgDeposit) (*v1.MsgDepositResponse, error) { - ctx := sdk.UnwrapSDKContext(goCtx) - accAddr, err := sdk.AccAddressFromBech32(msg.Depositor) + accAddr, err := k.authKeeper.StringToBytes(msg.Depositor) if err != nil { + return nil, sdkerrors.ErrInvalidAddress.Wrapf("invalid depositor address: %s", err) + } + + if err := validateAmount(sdk.NewCoins(msg.Amount...)); err != nil { return nil, err } + + ctx := sdk.UnwrapSDKContext(goCtx) votingStarted, err := k.Keeper.AddDeposit(ctx, msg.ProposalId, accAddr, msg.Amount) if err != nil { return nil, err @@ -221,6 +282,10 @@ func (k msgServer) UpdateParams(goCtx context.Context, msg *v1.MsgUpdateParams) return nil, errors.Wrapf(govtypes.ErrInvalidSigner, "invalid authority; expected %s, got %s", k.authority, msg.Authority) } + if err := msg.Params.ValidateBasic(); err != nil { + return nil, err + } + ctx := sdk.UnwrapSDKContext(goCtx) if err := k.SetParams(ctx, msg.Params); err != nil { return nil, err @@ -243,6 +308,17 @@ func NewLegacyMsgServerImpl(govAcct string, v1Server v1.MsgServer) v1beta1.MsgSe var _ v1beta1.MsgServer = legacyMsgServer{} func (k legacyMsgServer) SubmitProposal(goCtx context.Context, msg *v1beta1.MsgSubmitProposal) (*v1beta1.MsgSubmitProposalResponse, error) { + content := msg.GetContent() + if content == nil { + return nil, errors.Wrap(govtypes.ErrInvalidProposalContent, "missing content") + } + if !v1beta1.IsValidProposalType(content.ProposalType()) { + return nil, errors.Wrap(govtypes.ErrInvalidProposalType, content.ProposalType()) + } + if err := content.ValidateBasic(); err != nil { + return nil, err + } + contentMsg, err := v1.NewLegacyContent(msg.GetContent(), k.govAcct) if err != nil { return nil, fmt.Errorf("error converting legacy content into proposal message: %w", err) @@ -312,3 +388,43 @@ func (k legacyMsgServer) Deposit(goCtx context.Context, msg *v1beta1.MsgDeposit) } return &v1beta1.MsgDepositResponse{}, nil } + +func validateAmount(amount sdk.Coins) error { + if !amount.IsValid() { + return sdkerrors.ErrInvalidCoins.Wrap(amount.String()) + } + + if !amount.IsAllPositive() { + return sdkerrors.ErrInvalidCoins.Wrap(amount.String()) + } + + return nil +} + +func validateDeposit(deposit sdk.Coins) error { + if !deposit.IsValid() { + return errors.Wrap(sdkerrors.ErrInvalidCoins, deposit.String()) + } + + if deposit.IsAnyNegative() { + return errors.Wrap(sdkerrors.ErrInvalidCoins, deposit.String()) + } + + return nil +} + +func validateMsgs(msgs []sdk.Msg) error { + for idx, msg := range msgs { + m, ok := msg.(sdk.HasValidateBasic) + if !ok { + continue + } + + if err := m.ValidateBasic(); err != nil { + return errors.Wrap(govtypes.ErrInvalidProposalMsg, + fmt.Sprintf("msg: %d, err: %s", idx, err.Error())) + } + } + + return nil +} diff --git a/x/gov/keeper/msg_server_test.go b/x/gov/keeper/msg_server_test.go index 8dfe414def81..cc45f577ca02 100644 --- a/x/gov/keeper/msg_server_test.go +++ b/x/gov/keeper/msg_server_test.go @@ -1,9 +1,11 @@ package keeper_test import ( + "errors" "strings" "time" + sdkmath "cosmossdk.io/math" simtestutil "github.com/cosmos/cosmos-sdk/testutil/sims" "github.com/cosmos/cosmos-sdk/testutil/testdata" sdk "github.com/cosmos/cosmos-sdk/types" @@ -12,13 +14,24 @@ import ( "github.com/cosmos/cosmos-sdk/x/gov/types/v1beta1" ) +const ( + abc = "abc" + o1 = "-0.1" +) + +var ( + longAddress = "cosmos1v9skzctpv9skzctpv9skzctpv9skzctpv9skzctpv9skzctpv9skzctpv9skzctpv9skzctpv9skzctpv9skzctpv9skzctpv9skzctpv9skzctpv9skzctpv9skzctpv9skzctpv9skzctpv9skzctpv9skzctpv9skzctpv9skzctpv9skzctpv9skzctpv9skzctpv9skzctpv9skzctpv9skzctpv9skzctpv9skzctpv9skzctpv9skzctpv9skzctpv9skzctpv9skzctpv9skzctpv9skzctpv9skzctpv9skzctpv9skzctpv9skzctpv9skzctpv9skzctpv9skzctpv9skzctpv9skzctpv9skzctpv9skzctpv9skzctpv9skzctpv9skzctpv9skzctpv9skzctpv9skzctpv9skzctpv9skzctpv9skzctpv9skzctpv9skzctpv9skzctpg0s5ed" + longAddressError = "address max length is 255" + emptyAddressError = "empty address string is not allowed" +) + func (suite *KeeperTestSuite) TestSubmitProposalReq() { suite.reset() govAcct := suite.govKeeper.GetGovernanceAccount(suite.ctx).GetAddress() addrs := suite.addrs proposer := addrs[0] - coins := sdk.NewCoins(sdk.NewCoin("stake", sdk.NewInt(100))) + coins := sdk.NewCoins(sdk.NewCoin("stake", sdkmath.NewInt(100))) initialDeposit := coins minDeposit := suite.govKeeper.GetParams(suite.ctx).MinDeposit bankMsg := &banktypes.MsgSend{ @@ -27,11 +40,73 @@ func (suite *KeeperTestSuite) TestSubmitProposalReq() { Amount: coins, } + suite.acctKeeper.EXPECT().StringToBytes("").Return(nil, errors.New(emptyAddressError)) + cases := map[string]struct { preRun func() (*v1.MsgSubmitProposal, error) expErr bool expErrMsg string }{ + "invalid addr": { + preRun: func() (*v1.MsgSubmitProposal, error) { + return v1.NewMsgSubmitProposal( + []sdk.Msg{bankMsg}, + initialDeposit, + "", + strings.Repeat("1", 300), + "Proposal", + "description of proposal", + false, + ) + }, + expErr: true, + expErrMsg: "invalid proposer address", + }, + "empty msgs and metadata": { + preRun: func() (*v1.MsgSubmitProposal, error) { + return v1.NewMsgSubmitProposal( + nil, + initialDeposit, + proposer.String(), + "", + "Proposal", + "description of proposal", + false, + ) + }, + expErr: true, + expErrMsg: "no messages proposed", + }, + "empty title": { + preRun: func() (*v1.MsgSubmitProposal, error) { + return v1.NewMsgSubmitProposal( + []sdk.Msg{bankMsg}, + initialDeposit, + proposer.String(), + "", + "", + "description of proposal", + false, + ) + }, + expErr: true, + expErrMsg: "proposal title cannot be empty", + }, + "empty description": { + preRun: func() (*v1.MsgSubmitProposal, error) { + return v1.NewMsgSubmitProposal( + []sdk.Msg{bankMsg}, + initialDeposit, + proposer.String(), + "", + "Proposal", + "", + false, + ) + }, + expErr: true, + expErrMsg: "proposal summary cannot be empty", + }, "metadata too long": { preRun: func() (*v1.MsgSubmitProposal, error) { return v1.NewMsgSubmitProposal( @@ -143,7 +218,7 @@ func (suite *KeeperTestSuite) TestCancelProposalReq() { addrs := suite.addrs proposer := addrs[0] - coins := sdk.NewCoins(sdk.NewCoin("stake", sdk.NewInt(100))) + coins := sdk.NewCoins(sdk.NewCoin("stake", sdkmath.NewInt(100))) bankMsg := &banktypes.MsgSend{ FromAddress: govAcct.String(), ToAddress: proposer.String(), @@ -164,9 +239,12 @@ func (suite *KeeperTestSuite) TestCancelProposalReq() { suite.Require().NotNil(res.ProposalId) proposalID := res.ProposalId + suite.acctKeeper.EXPECT().StringToBytes("").Return(nil, errors.New(emptyAddressError)) + cases := map[string]struct { preRun func() uint64 expErr bool + expErrMsg string proposalID uint64 depositor sdk.AccAddress }{ @@ -176,6 +254,7 @@ func (suite *KeeperTestSuite) TestCancelProposalReq() { }, depositor: proposer, expErr: true, + expErrMsg: "proposal is not found", }, "valid proposal but invalid proposer": { preRun: func() uint64 { @@ -183,11 +262,34 @@ func (suite *KeeperTestSuite) TestCancelProposalReq() { }, depositor: addrs[1], expErr: true, + expErrMsg: "invalid proposer", }, - "all good": { + "empty proposer": { preRun: func() uint64 { return proposalID }, + depositor: sdk.AccAddress{}, + expErr: true, + expErrMsg: "invalid proposer address: empty address string is not allowed", + }, + "all good": { + preRun: func() uint64 { + msg, err := v1.NewMsgSubmitProposal( + []sdk.Msg{bankMsg}, + coins, + proposer.String(), + "", + "Proposal", + "description of proposal", + false, + ) + suite.Require().NoError(err) + + res, err := suite.msgSrvr.SubmitProposal(suite.ctx, msg) + suite.Require().NoError(err) + suite.Require().NotNil(res.ProposalId) + return res.ProposalId + }, depositor: proposer, expErr: false, }, @@ -200,6 +302,7 @@ func (suite *KeeperTestSuite) TestCancelProposalReq() { _, err := suite.msgSrvr.CancelProposal(suite.ctx, cancelProposalReq) if tc.expErr { suite.Require().Error(err) + suite.Require().Contains(err.Error(), tc.expErrMsg) } else { suite.Require().NoError(err) } @@ -213,7 +316,7 @@ func (suite *KeeperTestSuite) TestVoteReq() { addrs := suite.addrs proposer := addrs[0] - coins := sdk.NewCoins(sdk.NewCoin("stake", sdk.NewInt(100))) + coins := sdk.NewCoins(sdk.NewCoin("stake", sdkmath.NewInt(100))) minDeposit := suite.govKeeper.GetParams(suite.ctx).MinDeposit bankMsg := &banktypes.MsgSend{ FromAddress: govAcct.String(), @@ -232,6 +335,9 @@ func (suite *KeeperTestSuite) TestVoteReq() { ) suite.Require().NoError(err) + suite.acctKeeper.EXPECT().StringToBytes(longAddress).Return(nil, errors.New(longAddressError)).AnyTimes() + suite.acctKeeper.EXPECT().StringToBytes("").Return(nil, errors.New(emptyAddressError)) + res, err := suite.msgSrvr.SubmitProposal(suite.ctx, msg) suite.Require().NoError(err) suite.Require().NotNil(res.ProposalId) @@ -245,6 +351,26 @@ func (suite *KeeperTestSuite) TestVoteReq() { metadata string voter sdk.AccAddress }{ + "empty voter": { + preRun: func() uint64 { + return proposalID + }, + option: v1.VoteOption_VOTE_OPTION_YES, + voter: sdk.AccAddress{}, + metadata: "", + expErr: true, + expErrMsg: "invalid voter address", + }, + "wrong vote option": { + preRun: func() uint64 { + return proposalID + }, + option: v1.VoteOption(0x13), + voter: proposer, + metadata: "", + expErr: true, + expErrMsg: "invalid vote option", + }, "vote on inactive proposal": { preRun: func() uint64 { msg, err := v1.NewMsgSubmitProposal( @@ -287,7 +413,7 @@ func (suite *KeeperTestSuite) TestVoteReq() { voter: sdk.AccAddress(strings.Repeat("a", 300)), metadata: "", expErr: true, - expErrMsg: "address max length is 255", + expErrMsg: longAddressError, }, "all good": { preRun: func() uint64 { @@ -332,10 +458,10 @@ func (suite *KeeperTestSuite) TestVoteReq() { func (suite *KeeperTestSuite) TestVoteWeightedReq() { suite.reset() govAcct := suite.govKeeper.GetGovernanceAccount(suite.ctx).GetAddress() - addrs := suite.addrs - proposer := addrs[0] - coins := sdk.NewCoins(sdk.NewCoin("stake", sdk.NewInt(100))) + proposer := simtestutil.AddTestAddrsIncremental(suite.bankKeeper, suite.stakingKeeper, suite.ctx, 1, sdkmath.NewInt(50000000))[0] + + coins := sdk.NewCoins(sdk.NewCoin("stake", sdkmath.NewInt(100))) minDeposit := suite.govKeeper.GetParams(suite.ctx).MinDeposit bankMsg := &banktypes.MsgSend{ FromAddress: govAcct.String(), @@ -359,15 +485,112 @@ func (suite *KeeperTestSuite) TestVoteWeightedReq() { suite.Require().NotNil(res.ProposalId) proposalID := res.ProposalId + suite.acctKeeper.EXPECT().StringToBytes(longAddress).Return(nil, errors.New(longAddressError)).AnyTimes() + suite.acctKeeper.EXPECT().StringToBytes("").Return(nil, errors.New(emptyAddressError)) + cases := map[string]struct { preRun func() uint64 vote *v1.MsgVote expErr bool expErrMsg string - option v1.VoteOption + option v1.WeightedVoteOptions metadata string voter sdk.AccAddress }{ + "empty voter": { + preRun: func() uint64 { + return proposalID + }, + option: v1.WeightedVoteOptions{ + v1.NewWeightedVoteOption(v1.OptionYes, sdkmath.LegacyNewDec(1)), + }, + voter: sdk.AccAddress{}, + metadata: "", + expErr: true, + expErrMsg: "invalid voter address", + }, + "weights sum > 1": { + preRun: func() uint64 { + return proposalID + }, + option: v1.WeightedVoteOptions{ + v1.NewWeightedVoteOption(v1.OptionYes, sdkmath.LegacyNewDec(1)), + v1.NewWeightedVoteOption(v1.OptionAbstain, sdkmath.LegacyNewDec(1)), + }, + voter: proposer, + metadata: "", + expErr: true, + expErrMsg: "total weight overflow 1.00: invalid vote option", + }, + "duplicate vote options": { + preRun: func() uint64 { + return proposalID + }, + option: v1.WeightedVoteOptions{ + v1.NewWeightedVoteOption(v1.OptionYes, sdk.NewDecWithPrec(5, 1)), + v1.NewWeightedVoteOption(v1.OptionYes, sdk.NewDecWithPrec(5, 1)), + }, + voter: proposer, + metadata: "", + expErr: true, + expErrMsg: "duplicated vote option", + }, + "zero weight": { + preRun: func() uint64 { + return proposalID + }, + option: v1.WeightedVoteOptions{ + v1.NewWeightedVoteOption(v1.OptionYes, sdkmath.LegacyNewDec(0)), + }, + voter: proposer, + metadata: "", + expErr: true, + expErrMsg: `option:VOTE_OPTION_YES weight:"0.000000000000000000" : invalid vote option`, + }, + "negative weight": { + preRun: func() uint64 { + return proposalID + }, + option: v1.WeightedVoteOptions{ + v1.NewWeightedVoteOption(v1.OptionYes, sdkmath.LegacyNewDec(-1)), + }, + voter: proposer, + metadata: "", + expErr: true, + expErrMsg: `option:VOTE_OPTION_YES weight:"-1.000000000000000000" : invalid vote option`, + }, + "empty options": { + preRun: func() uint64 { + return proposalID + }, + option: v1.WeightedVoteOptions{}, + voter: proposer, + metadata: "", + expErr: true, + expErrMsg: "invalid request", + }, + "invalid vote option": { + preRun: func() uint64 { + return proposalID + }, + option: v1.NewNonSplitVoteOption(v1.VoteOption(0x13)), + voter: proposer, + metadata: "", + expErr: true, + expErrMsg: "invalid vote option", + }, + "weight sum < 1": { + preRun: func() uint64 { + return proposalID + }, + option: v1.WeightedVoteOptions{ // weight sum <1 + v1.NewWeightedVoteOption(v1.OptionYes, sdk.NewDecWithPrec(5, 1)), + }, + voter: proposer, + metadata: "", + expErr: true, + expErrMsg: "total weight lower than 1.00: invalid vote option", + }, "vote on inactive proposal": { preRun: func() uint64 { msg, err := v1.NewMsgSubmitProposal( @@ -386,7 +609,7 @@ func (suite *KeeperTestSuite) TestVoteWeightedReq() { suite.Require().NotNil(res.ProposalId) return res.ProposalId }, - option: v1.VoteOption_VOTE_OPTION_YES, + option: v1.NewNonSplitVoteOption(v1.VoteOption_VOTE_OPTION_YES), voter: proposer, metadata: "", expErr: true, @@ -396,7 +619,7 @@ func (suite *KeeperTestSuite) TestVoteWeightedReq() { preRun: func() uint64 { return proposalID }, - option: v1.VoteOption_VOTE_OPTION_YES, + option: v1.NewNonSplitVoteOption(v1.VoteOption_VOTE_OPTION_YES), voter: proposer, metadata: strings.Repeat("a", 300), expErr: true, @@ -406,11 +629,11 @@ func (suite *KeeperTestSuite) TestVoteWeightedReq() { preRun: func() uint64 { return proposalID }, - option: v1.VoteOption_VOTE_OPTION_YES, + option: v1.NewNonSplitVoteOption(v1.VoteOption_VOTE_OPTION_YES), voter: sdk.AccAddress(strings.Repeat("a", 300)), metadata: "", expErr: true, - expErrMsg: "address max length is 255", + expErrMsg: longAddressError, }, "all good": { preRun: func() uint64 { @@ -430,7 +653,33 @@ func (suite *KeeperTestSuite) TestVoteWeightedReq() { suite.Require().NotNil(res.ProposalId) return res.ProposalId }, - option: v1.VoteOption_VOTE_OPTION_YES, + option: v1.NewNonSplitVoteOption(v1.VoteOption_VOTE_OPTION_YES), + voter: proposer, + metadata: "", + expErr: false, + }, + "all good with split votes": { + preRun: func() uint64 { + msg, err := v1.NewMsgSubmitProposal( + []sdk.Msg{bankMsg}, + minDeposit, + proposer.String(), + "", + "Proposal", + "description of proposal", + false, + ) + suite.Require().NoError(err) + + res, err := suite.msgSrvr.SubmitProposal(suite.ctx, msg) + suite.Require().NoError(err) + suite.Require().NotNil(res.ProposalId) + return res.ProposalId + }, + option: v1.WeightedVoteOptions{ + v1.NewWeightedVoteOption(v1.OptionYes, sdk.NewDecWithPrec(5, 1)), + v1.NewWeightedVoteOption(v1.OptionAbstain, sdk.NewDecWithPrec(5, 1)), + }, voter: proposer, metadata: "", expErr: false, @@ -440,7 +689,7 @@ func (suite *KeeperTestSuite) TestVoteWeightedReq() { for name, tc := range cases { suite.Run(name, func() { pID := tc.preRun() - voteReq := v1.NewMsgVoteWeighted(tc.voter, pID, v1.NewNonSplitVoteOption(tc.option), tc.metadata) + voteReq := v1.NewMsgVoteWeighted(tc.voter, pID, tc.option, tc.metadata) _, err := suite.msgSrvr.VoteWeighted(suite.ctx, voteReq) if tc.expErr { suite.Require().Error(err) @@ -457,7 +706,7 @@ func (suite *KeeperTestSuite) TestDepositReq() { addrs := suite.addrs proposer := addrs[0] - coins := sdk.NewCoins(sdk.NewCoin("stake", sdk.NewInt(100))) + coins := sdk.NewCoins(sdk.NewCoin("stake", sdkmath.NewInt(100))) minDeposit := suite.govKeeper.GetParams(suite.ctx).MinDeposit bankMsg := &banktypes.MsgSend{ FromAddress: govAcct.String(), @@ -481,13 +730,15 @@ func (suite *KeeperTestSuite) TestDepositReq() { suite.Require().NotNil(res.ProposalId) pID := res.ProposalId + suite.acctKeeper.EXPECT().StringToBytes("").Return(nil, errors.New(emptyAddressError)) + cases := map[string]struct { preRun func() uint64 expErr bool proposalID uint64 depositor sdk.AccAddress deposit sdk.Coins - options v1.WeightedVoteOptions + expErrMsg string }{ "wrong proposal id": { preRun: func() uint64 { @@ -496,7 +747,16 @@ func (suite *KeeperTestSuite) TestDepositReq() { depositor: proposer, deposit: coins, expErr: true, - options: v1.NewNonSplitVoteOption(v1.OptionYes), + expErrMsg: "0: unknown proposal", + }, + "empty depositor": { + preRun: func() uint64 { + return pID + }, + depositor: sdk.AccAddress{}, + deposit: minDeposit, + expErr: true, + expErrMsg: "invalid depositor address", }, "all good": { preRun: func() uint64 { @@ -505,7 +765,6 @@ func (suite *KeeperTestSuite) TestDepositReq() { depositor: proposer, deposit: minDeposit, expErr: false, - options: v1.NewNonSplitVoteOption(v1.OptionYes), }, } @@ -516,6 +775,7 @@ func (suite *KeeperTestSuite) TestDepositReq() { _, err := suite.msgSrvr.Deposit(suite.ctx, depositReq) if tc.expErr { suite.Require().Error(err) + suite.Require().Contains(err.Error(), tc.expErrMsg) } else { suite.Require().NoError(err) } @@ -525,17 +785,78 @@ func (suite *KeeperTestSuite) TestDepositReq() { // legacy msg server tests func (suite *KeeperTestSuite) TestLegacyMsgSubmitProposal() { - addrs := suite.addrs - proposer := addrs[0] - - coins := sdk.NewCoins(sdk.NewCoin("stake", sdk.NewInt(100))) + proposer := simtestutil.AddTestAddrsIncremental(suite.bankKeeper, suite.stakingKeeper, suite.ctx, 1, sdkmath.NewInt(50000000))[0] + coins := sdk.NewCoins(sdk.NewCoin("stake", sdkmath.NewInt(100))) initialDeposit := coins minDeposit := suite.govKeeper.GetParams(suite.ctx).MinDeposit + suite.acctKeeper.EXPECT().StringToBytes("").Return(nil, errors.New(emptyAddressError)) + cases := map[string]struct { - preRun func() (*v1beta1.MsgSubmitProposal, error) - expErr bool + preRun func() (*v1beta1.MsgSubmitProposal, error) + expErr bool + expErrMsg string }{ + "empty title": { + preRun: func() (*v1beta1.MsgSubmitProposal, error) { + content := v1beta1.NewTextProposal("", "I am test") + return v1beta1.NewMsgSubmitProposal( + content, + initialDeposit, + proposer, + ) + }, + expErr: true, + expErrMsg: "proposal title cannot be blank", + }, + "empty description": { + preRun: func() (*v1beta1.MsgSubmitProposal, error) { + content := v1beta1.NewTextProposal("test", "") + return v1beta1.NewMsgSubmitProposal( + content, + initialDeposit, + proposer, + ) + }, + expErr: true, + expErrMsg: "proposal description cannot be blank", + }, + "empty proposer": { + preRun: func() (*v1beta1.MsgSubmitProposal, error) { + content := v1beta1.NewTextProposal("test", "I am test") + return v1beta1.NewMsgSubmitProposal( + content, + initialDeposit, + sdk.AccAddress{}, + ) + }, + expErr: true, + expErrMsg: "invalid proposer address: empty address string is not allowed", + }, + "title text length > max limit allowed": { + preRun: func() (*v1beta1.MsgSubmitProposal, error) { + content := v1beta1.NewTextProposal(strings.Repeat("#", v1beta1.MaxTitleLength*2), "I am test") + return v1beta1.NewMsgSubmitProposal( + content, + initialDeposit, + proposer, + ) + }, + expErr: true, + expErrMsg: "proposal title is longer than max length of 140: invalid proposal content", + }, + "description text length > max limit allowed": { + preRun: func() (*v1beta1.MsgSubmitProposal, error) { + content := v1beta1.NewTextProposal("test", strings.Repeat("#", v1beta1.MaxDescriptionLength*2)) + return v1beta1.NewMsgSubmitProposal( + content, + initialDeposit, + proposer, + ) + }, + expErr: true, + expErrMsg: "proposal description is longer than max length of 10000: invalid proposal content", + }, "all good": { preRun: func() (*v1beta1.MsgSubmitProposal, error) { return v1beta1.NewMsgSubmitProposal( @@ -565,6 +886,7 @@ func (suite *KeeperTestSuite) TestLegacyMsgSubmitProposal() { res, err := suite.legacyMsgSrvr.SubmitProposal(suite.ctx, msg) if c.expErr { suite.Require().Error(err) + suite.Require().Contains(err.Error(), c.expErrMsg) } else { suite.Require().NoError(err) suite.Require().NotNil(res.ProposalId) @@ -578,7 +900,7 @@ func (suite *KeeperTestSuite) TestLegacyMsgVote() { addrs := suite.addrs proposer := addrs[0] - coins := sdk.NewCoins(sdk.NewCoin("stake", sdk.NewInt(100))) + coins := sdk.NewCoins(sdk.NewCoin("stake", sdkmath.NewInt(100))) minDeposit := suite.govKeeper.GetParams(suite.ctx).MinDeposit bankMsg := &banktypes.MsgSend{ FromAddress: govAcct.String(), @@ -602,6 +924,9 @@ func (suite *KeeperTestSuite) TestLegacyMsgVote() { suite.Require().NotNil(res.ProposalId) proposalID := res.ProposalId + suite.acctKeeper.EXPECT().StringToBytes(longAddress).Return(nil, errors.New(longAddressError)).AnyTimes() + suite.acctKeeper.EXPECT().StringToBytes("").Return(nil, errors.New(emptyAddressError)) + cases := map[string]struct { preRun func() uint64 expErr bool @@ -610,6 +935,26 @@ func (suite *KeeperTestSuite) TestLegacyMsgVote() { metadata string voter sdk.AccAddress }{ + "empty voter": { + preRun: func() uint64 { + return proposalID + }, + option: v1beta1.OptionYes, + voter: sdk.AccAddress{}, + metadata: "", + expErr: true, + expErrMsg: "invalid voter address", + }, + "wrong vote option": { + preRun: func() uint64 { + return proposalID + }, + option: v1beta1.VoteOption(0x13), + voter: proposer, + metadata: "", + expErr: true, + expErrMsg: "invalid vote option", + }, "vote on inactive proposal": { preRun: func() uint64 { msg, err := v1.NewMsgSubmitProposal( @@ -642,7 +987,7 @@ func (suite *KeeperTestSuite) TestLegacyMsgVote() { voter: sdk.AccAddress(strings.Repeat("a", 300)), metadata: "", expErr: true, - expErrMsg: "address max length is 255", + expErrMsg: longAddressError, }, "all good": { preRun: func() uint64 { @@ -690,7 +1035,7 @@ func (suite *KeeperTestSuite) TestLegacyVoteWeighted() { addrs := suite.addrs proposer := addrs[0] - coins := sdk.NewCoins(sdk.NewCoin("stake", sdk.NewInt(100))) + coins := sdk.NewCoins(sdk.NewCoin("stake", sdkmath.NewInt(100))) minDeposit := suite.govKeeper.GetParams(suite.ctx).MinDeposit bankMsg := &banktypes.MsgSend{ FromAddress: govAcct.String(), @@ -714,15 +1059,141 @@ func (suite *KeeperTestSuite) TestLegacyVoteWeighted() { suite.Require().NotNil(res.ProposalId) proposalID := res.ProposalId + suite.acctKeeper.EXPECT().StringToBytes(longAddress).Return(nil, errors.New(longAddressError)).AnyTimes() + suite.acctKeeper.EXPECT().StringToBytes("").Return(nil, errors.New(emptyAddressError)) + cases := map[string]struct { preRun func() uint64 vote *v1beta1.MsgVote expErr bool expErrMsg string - option v1beta1.VoteOption + option v1beta1.WeightedVoteOptions metadata string voter sdk.AccAddress }{ + "empty voter": { + preRun: func() uint64 { + return proposalID + }, + option: v1beta1.WeightedVoteOptions{ + v1beta1.WeightedVoteOption{ + Option: v1beta1.OptionYes, + Weight: sdkmath.LegacyNewDec(1), + }, + }, + voter: sdk.AccAddress{}, + metadata: "", + expErr: true, + expErrMsg: "invalid voter address", + }, + "weights sum > 1": { + preRun: func() uint64 { + return proposalID + }, + option: v1beta1.WeightedVoteOptions{ + v1beta1.WeightedVoteOption{ + Option: v1beta1.OptionYes, + Weight: sdkmath.LegacyNewDec(1), + }, + v1beta1.WeightedVoteOption{ + Option: v1beta1.OptionAbstain, + Weight: sdkmath.LegacyNewDec(1), + }, + }, + voter: proposer, + metadata: "", + expErr: true, + expErrMsg: "total weight overflow 1.00: invalid vote option", + }, + "duplicate vote options": { + preRun: func() uint64 { + return proposalID + }, + option: v1beta1.WeightedVoteOptions{ + v1beta1.WeightedVoteOption{ + Option: v1beta1.OptionYes, + Weight: sdk.NewDecWithPrec(5, 1), + }, + v1beta1.WeightedVoteOption{ + Option: v1beta1.OptionYes, + Weight: sdk.NewDecWithPrec(5, 1), + }, + }, + voter: proposer, + metadata: "", + expErr: true, + expErrMsg: "duplicated vote option", + }, + "zero weight": { + preRun: func() uint64 { + return proposalID + }, + option: v1beta1.WeightedVoteOptions{ + v1beta1.WeightedVoteOption{ + Option: v1beta1.OptionYes, + Weight: sdkmath.LegacyNewDec(0), + }, + }, + voter: proposer, + metadata: "", + expErr: true, + expErrMsg: `option:VOTE_OPTION_YES weight:"0.000000000000000000" : invalid vote option`, + }, + "negative weight": { + preRun: func() uint64 { + return proposalID + }, + option: v1beta1.WeightedVoteOptions{ + v1beta1.WeightedVoteOption{ + Option: v1beta1.OptionYes, + Weight: sdkmath.LegacyNewDec(-1), + }, + }, + voter: proposer, + metadata: "", + expErr: true, + expErrMsg: `option:VOTE_OPTION_YES weight:"-1.000000000000000000" : invalid vote option`, + }, + "empty options": { + preRun: func() uint64 { + return proposalID + }, + option: v1beta1.WeightedVoteOptions{}, + voter: proposer, + metadata: "", + expErr: true, + expErrMsg: "invalid request", + }, + "invalid vote option": { + preRun: func() uint64 { + return proposalID + }, + option: v1beta1.WeightedVoteOptions{ + v1beta1.WeightedVoteOption{ + Option: v1beta1.VoteOption(0x13), + Weight: sdk.NewDecWithPrec(5, 1), + }, + }, + voter: proposer, + metadata: "", + expErr: true, + expErrMsg: "invalid vote option", + }, + "weight sum < 1": { + preRun: func() uint64 { + return proposalID + }, + option: v1beta1.WeightedVoteOptions{ + v1beta1.WeightedVoteOption{ + Option: v1beta1.OptionYes, + Weight: sdk.NewDecWithPrec(5, 1), + }, + }, + voter: proposer, + metadata: "", + expErr: true, + expErrMsg: "total weight lower than 1.00: invalid vote option", + }, "vote on inactive proposal": { preRun: func() uint64 { msg, err := v1.NewMsgSubmitProposal( @@ -741,7 +1212,12 @@ func (suite *KeeperTestSuite) TestLegacyVoteWeighted() { suite.Require().NotNil(res.ProposalId) return res.ProposalId }, - option: v1beta1.OptionYes, + option: v1beta1.WeightedVoteOptions{ + v1beta1.WeightedVoteOption{ + Option: v1beta1.OptionYes, + Weight: sdkmath.LegacyNewDec(1), + }, + }, voter: proposer, metadata: "", expErr: true, @@ -751,11 +1227,16 @@ func (suite *KeeperTestSuite) TestLegacyVoteWeighted() { preRun: func() uint64 { return proposalID }, - option: v1beta1.OptionYes, + option: v1beta1.WeightedVoteOptions{ + v1beta1.WeightedVoteOption{ + Option: v1beta1.OptionYes, + Weight: sdkmath.LegacyNewDec(1), + }, + }, voter: sdk.AccAddress(strings.Repeat("a", 300)), metadata: "", expErr: true, - expErrMsg: "address max length is 255", + expErrMsg: longAddressError, }, "all good": { preRun: func() uint64 { @@ -775,7 +1256,12 @@ func (suite *KeeperTestSuite) TestLegacyVoteWeighted() { suite.Require().NotNil(res.ProposalId) return res.ProposalId }, - option: v1beta1.OptionYes, + option: v1beta1.WeightedVoteOptions{ + v1beta1.WeightedVoteOption{ + Option: v1beta1.OptionYes, + Weight: sdkmath.LegacyNewDec(1), + }, + }, voter: proposer, metadata: "", expErr: false, @@ -785,7 +1271,7 @@ func (suite *KeeperTestSuite) TestLegacyVoteWeighted() { for name, tc := range cases { suite.Run(name, func() { pID := tc.preRun() - voteReq := v1beta1.NewMsgVoteWeighted(tc.voter, pID, v1beta1.NewNonSplitVoteOption(tc.option)) + voteReq := v1beta1.NewMsgVoteWeighted(tc.voter, pID, tc.option) _, err := suite.legacyMsgSrvr.VoteWeighted(suite.ctx, voteReq) if tc.expErr { suite.Require().Error(err) @@ -802,7 +1288,7 @@ func (suite *KeeperTestSuite) TestLegacyMsgDeposit() { addrs := suite.addrs proposer := addrs[0] - coins := sdk.NewCoins(sdk.NewCoin("stake", sdk.NewInt(100))) + coins := sdk.NewCoins(sdk.NewCoin("stake", sdkmath.NewInt(100))) minDeposit := suite.govKeeper.GetParams(suite.ctx).MinDeposit bankMsg := &banktypes.MsgSend{ FromAddress: govAcct.String(), @@ -826,13 +1312,15 @@ func (suite *KeeperTestSuite) TestLegacyMsgDeposit() { suite.Require().NotNil(res.ProposalId) pID := res.ProposalId + suite.acctKeeper.EXPECT().StringToBytes("").Return(nil, errors.New(emptyAddressError)) + cases := map[string]struct { preRun func() uint64 expErr bool + expErrMsg string proposalID uint64 depositor sdk.AccAddress deposit sdk.Coins - options v1beta1.WeightedVoteOptions }{ "wrong proposal id": { preRun: func() uint64 { @@ -841,7 +1329,16 @@ func (suite *KeeperTestSuite) TestLegacyMsgDeposit() { depositor: proposer, deposit: coins, expErr: true, - options: v1beta1.NewNonSplitVoteOption(v1beta1.OptionYes), + expErrMsg: "unknown proposal", + }, + "empty depositer": { + preRun: func() uint64 { + return pID + }, + depositor: sdk.AccAddress{}, + deposit: coins, + expErr: true, + expErrMsg: "invalid depositor address: empty address string is not allowed", }, "all good": { preRun: func() uint64 { @@ -850,7 +1347,6 @@ func (suite *KeeperTestSuite) TestLegacyMsgDeposit() { depositor: proposer, deposit: minDeposit, expErr: false, - options: v1beta1.NewNonSplitVoteOption(v1beta1.OptionYes), }, } @@ -861,6 +1357,7 @@ func (suite *KeeperTestSuite) TestLegacyMsgDeposit() { _, err := suite.legacyMsgSrvr.Deposit(suite.ctx, depositReq) if tc.expErr { suite.Require().Error(err) + suite.Require().Contains(err.Error(), tc.expErrMsg) } else { suite.Require().NoError(err) } @@ -896,7 +1393,7 @@ func (suite *KeeperTestSuite) TestMsgUpdateParams() { } }, expErr: true, - expErrMsg: "invalid authority address", + expErrMsg: "invalid authority", }, { name: "invalid min deposit", @@ -918,7 +1415,7 @@ func (suite *KeeperTestSuite) TestMsgUpdateParams() { params1 := params params1.MinDeposit = sdk.Coins{{ Denom: sdk.DefaultBondDenom, - Amount: sdk.NewInt(-100), + Amount: sdkmath.NewInt(-100), }} return &v1.MsgUpdateParams{ @@ -962,7 +1459,7 @@ func (suite *KeeperTestSuite) TestMsgUpdateParams() { name: "invalid quorum", input: func() *v1.MsgUpdateParams { params1 := params - params1.Quorum = "abc" //nolint:goconst + params1.Quorum = abc return &v1.MsgUpdateParams{ Authority: authority, @@ -976,7 +1473,7 @@ func (suite *KeeperTestSuite) TestMsgUpdateParams() { name: "negative quorum", input: func() *v1.MsgUpdateParams { params1 := params - params1.Quorum = "-0.1" //nolint:goconst + params1.Quorum = o1 return &v1.MsgUpdateParams{ Authority: authority, @@ -1004,7 +1501,7 @@ func (suite *KeeperTestSuite) TestMsgUpdateParams() { name: "invalid threshold", input: func() *v1.MsgUpdateParams { params1 := params - params1.Threshold = "abc" + params1.Threshold = abc return &v1.MsgUpdateParams{ Authority: authority, @@ -1018,7 +1515,7 @@ func (suite *KeeperTestSuite) TestMsgUpdateParams() { name: "negative threshold", input: func() *v1.MsgUpdateParams { params1 := params - params1.Threshold = "-0.1" + params1.Threshold = o1 return &v1.MsgUpdateParams{ Authority: authority, @@ -1046,7 +1543,7 @@ func (suite *KeeperTestSuite) TestMsgUpdateParams() { name: "invalid veto threshold", input: func() *v1.MsgUpdateParams { params1 := params - params1.VetoThreshold = "abc" + params1.VetoThreshold = abc return &v1.MsgUpdateParams{ Authority: authority, @@ -1060,7 +1557,7 @@ func (suite *KeeperTestSuite) TestMsgUpdateParams() { name: "negative veto threshold", input: func() *v1.MsgUpdateParams { params1 := params - params1.VetoThreshold = "-0.1" + params1.VetoThreshold = o1 return &v1.MsgUpdateParams{ Authority: authority, @@ -1120,10 +1617,6 @@ func (suite *KeeperTestSuite) TestMsgUpdateParams() { suite.Run(tc.name, func() { msg := tc.input() exec := func(updateParams *v1.MsgUpdateParams) error { - if err := msg.ValidateBasic(); err != nil { - return err - } - if _, err := suite.msgSrvr.UpdateParams(suite.ctx, updateParams); err != nil { return err } @@ -1154,32 +1647,32 @@ func (suite *KeeperTestSuite) TestSubmitProposal_InitialDeposit() { expectError bool }{ "meets initial deposit, enough balance - success": { - minDeposit: sdk.NewCoins(sdk.NewCoin(sdk.DefaultBondDenom, sdk.NewInt(baseDepositTestAmount))), + minDeposit: sdk.NewCoins(sdk.NewCoin(sdk.DefaultBondDenom, sdkmath.NewInt(baseDepositTestAmount))), minInitialDepositRatio: baseDepositRatioDec, - initialDeposit: sdk.NewCoins(sdk.NewCoin(sdk.DefaultBondDenom, sdk.NewInt(meetsDepositValue))), - accountBalance: sdk.NewCoins(sdk.NewCoin(sdk.DefaultBondDenom, sdk.NewInt(meetsDepositValue))), + initialDeposit: sdk.NewCoins(sdk.NewCoin(sdk.DefaultBondDenom, sdkmath.NewInt(meetsDepositValue))), + accountBalance: sdk.NewCoins(sdk.NewCoin(sdk.DefaultBondDenom, sdkmath.NewInt(meetsDepositValue))), }, "does not meet initial deposit, enough balance - error": { - minDeposit: sdk.NewCoins(sdk.NewCoin(sdk.DefaultBondDenom, sdk.NewInt(baseDepositTestAmount))), + minDeposit: sdk.NewCoins(sdk.NewCoin(sdk.DefaultBondDenom, sdkmath.NewInt(baseDepositTestAmount))), minInitialDepositRatio: baseDepositRatioDec, - initialDeposit: sdk.NewCoins(sdk.NewCoin(sdk.DefaultBondDenom, sdk.NewInt(meetsDepositValue-1))), - accountBalance: sdk.NewCoins(sdk.NewCoin(sdk.DefaultBondDenom, sdk.NewInt(meetsDepositValue))), + initialDeposit: sdk.NewCoins(sdk.NewCoin(sdk.DefaultBondDenom, sdkmath.NewInt(meetsDepositValue-1))), + accountBalance: sdk.NewCoins(sdk.NewCoin(sdk.DefaultBondDenom, sdkmath.NewInt(meetsDepositValue))), expectError: true, }, "meets initial deposit, not enough balance - error": { - minDeposit: sdk.NewCoins(sdk.NewCoin(sdk.DefaultBondDenom, sdk.NewInt(baseDepositTestAmount))), + minDeposit: sdk.NewCoins(sdk.NewCoin(sdk.DefaultBondDenom, sdkmath.NewInt(baseDepositTestAmount))), minInitialDepositRatio: baseDepositRatioDec, - initialDeposit: sdk.NewCoins(sdk.NewCoin(sdk.DefaultBondDenom, sdk.NewInt(meetsDepositValue))), - accountBalance: sdk.NewCoins(sdk.NewCoin(sdk.DefaultBondDenom, sdk.NewInt(meetsDepositValue-1))), + initialDeposit: sdk.NewCoins(sdk.NewCoin(sdk.DefaultBondDenom, sdkmath.NewInt(meetsDepositValue))), + accountBalance: sdk.NewCoins(sdk.NewCoin(sdk.DefaultBondDenom, sdkmath.NewInt(meetsDepositValue-1))), expectError: true, }, "does not meet initial deposit and not enough balance - error": { - minDeposit: sdk.NewCoins(sdk.NewCoin(sdk.DefaultBondDenom, sdk.NewInt(baseDepositTestAmount))), + minDeposit: sdk.NewCoins(sdk.NewCoin(sdk.DefaultBondDenom, sdkmath.NewInt(baseDepositTestAmount))), minInitialDepositRatio: baseDepositRatioDec, - initialDeposit: sdk.NewCoins(sdk.NewCoin(sdk.DefaultBondDenom, sdk.NewInt(meetsDepositValue-1))), - accountBalance: sdk.NewCoins(sdk.NewCoin(sdk.DefaultBondDenom, sdk.NewInt(meetsDepositValue-1))), + initialDeposit: sdk.NewCoins(sdk.NewCoin(sdk.DefaultBondDenom, sdkmath.NewInt(meetsDepositValue-1))), + accountBalance: sdk.NewCoins(sdk.NewCoin(sdk.DefaultBondDenom, sdkmath.NewInt(meetsDepositValue-1))), expectError: true, }, @@ -1191,6 +1684,9 @@ func (suite *KeeperTestSuite) TestSubmitProposal_InitialDeposit() { govKeeper, ctx := suite.govKeeper, suite.ctx address := simtestutil.AddTestAddrs(suite.bankKeeper, suite.stakingKeeper, ctx, 1, tc.accountBalance[0].Amount)[0] + suite.acctKeeper.EXPECT().StringToBytes(address.String()).Return(address, nil).AnyTimes() + suite.acctKeeper.EXPECT().BytesToString(address).Return(address.String(), nil).AnyTimes() + params := v1.DefaultParams() params.MinDeposit = tc.minDeposit params.MinInitialDepositRatio = tc.minInitialDepositRatio.String() diff --git a/x/gov/keeper/params.go b/x/gov/keeper/params.go index 9e4aef9dd059..dc8e93212076 100644 --- a/x/gov/keeper/params.go +++ b/x/gov/keeper/params.go @@ -7,6 +7,7 @@ import ( ) // SetParams sets the gov module's parameters. +// CONTRACT: This method performs no validation of the parameters. func (k Keeper) SetParams(ctx sdk.Context, params v1.Params) error { store := ctx.KVStore(k.storeKey) bz, err := k.cdc.Marshal(¶ms) diff --git a/x/gov/keeper/proposal.go b/x/gov/keeper/proposal.go index 3777ab12bb46..3979a2047c64 100644 --- a/x/gov/keeper/proposal.go +++ b/x/gov/keeper/proposal.go @@ -42,8 +42,10 @@ func (keeper Keeper) SubmitProposal(ctx sdk.Context, messages []sdk.Msg, metadat msgsStr += fmt.Sprintf(",%s", sdk.MsgTypeURL(msg)) // perform a basic validation of the message - if err := msg.ValidateBasic(); err != nil { - return v1.Proposal{}, errorsmod.Wrap(types.ErrInvalidProposalMsg, err.Error()) + if m, ok := msg.(sdk.HasValidateBasic); ok { + if err := m.ValidateBasic(); err != nil { + return v1.Proposal{}, errorsmod.Wrap(types.ErrInvalidProposalMsg, err.Error()) + } } signers := msg.GetSigners() diff --git a/x/gov/keeper/proposal_test.go b/x/gov/keeper/proposal_test.go index c9acd6c898f4..2a888cf14816 100644 --- a/x/gov/keeper/proposal_test.go +++ b/x/gov/keeper/proposal_test.go @@ -28,7 +28,7 @@ func (suite *KeeperTestSuite) TestGetSetProposal() { for _, tc := range testCases { tp := TestProposal - proposal, err := suite.govKeeper.SubmitProposal(suite.ctx, tp, "", "test", "summary", sdk.AccAddress("cosmos1ghekyjucln7y67ntx7cf27m9dpuxxemn4c8g4r"), tc.expedited) + proposal, err := suite.govKeeper.SubmitProposal(suite.ctx, tp, "", "test", "summary", suite.addrs[0], tc.expedited) suite.Require().NoError(err) proposalID := proposal.Id suite.govKeeper.SetProposal(suite.ctx, proposal) @@ -57,7 +57,7 @@ func (suite *KeeperTestSuite) TestDeleteProposal() { }, ) tp := TestProposal - proposal, err := suite.govKeeper.SubmitProposal(suite.ctx, tp, "", "test", "summary", sdk.AccAddress("cosmos1ghekyjucln7y67ntx7cf27m9dpuxxemn4c8g4r"), tc.expedited) + proposal, err := suite.govKeeper.SubmitProposal(suite.ctx, tp, "", "test", "summary", suite.addrs[0], tc.expedited) suite.Require().NoError(err) proposalID := proposal.Id suite.govKeeper.SetProposal(suite.ctx, proposal) @@ -78,7 +78,7 @@ func (suite *KeeperTestSuite) TestActivateVotingPeriod() { for _, tc := range testCases { tp := TestProposal - proposal, err := suite.govKeeper.SubmitProposal(suite.ctx, tp, "", "test", "summary", sdk.AccAddress("cosmos1ghekyjucln7y67ntx7cf27m9dpuxxemn4c8g4r"), tc.expedited) + proposal, err := suite.govKeeper.SubmitProposal(suite.ctx, tp, "", "test", "summary", suite.addrs[0], tc.expedited) suite.Require().NoError(err) suite.Require().Nil(proposal.VotingStartTime) @@ -115,7 +115,7 @@ func (suite *KeeperTestSuite) TestDeleteProposalInVotingPeriod() { for _, tc := range testCases { suite.reset() tp := TestProposal - proposal, err := suite.govKeeper.SubmitProposal(suite.ctx, tp, "", "test", "summary", sdk.AccAddress("cosmos1ghekyjucln7y67ntx7cf27m9dpuxxemn4c8g4r"), tc.expedited) + proposal, err := suite.govKeeper.SubmitProposal(suite.ctx, tp, "", "test", "summary", suite.addrs[0], tc.expedited) suite.Require().NoError(err) suite.Require().Nil(proposal.VotingStartTime) @@ -134,7 +134,7 @@ func (suite *KeeperTestSuite) TestDeleteProposalInVotingPeriod() { // add vote voteOptions := []*v1.WeightedVoteOption{{Option: v1.OptionYes, Weight: "1.0"}} - err = suite.govKeeper.AddVote(suite.ctx, proposal.Id, sdk.AccAddress("cosmos1ghekyjucln7y67ntx7cf27m9dpuxxemn4c8g4r"), voteOptions, "") + err = suite.govKeeper.AddVote(suite.ctx, proposal.Id, suite.addrs[0], voteOptions, "") suite.Require().NoError(err) suite.Require().NotPanics(func() { @@ -142,7 +142,7 @@ func (suite *KeeperTestSuite) TestDeleteProposalInVotingPeriod() { }, "") // add vote but proposal is deleted along with its VotingPeriodProposalKey - err = suite.govKeeper.AddVote(suite.ctx, proposal.Id, sdk.AccAddress("cosmos1ghekyjucln7y67ntx7cf27m9dpuxxemn4c8g4r"), voteOptions, "") + err = suite.govKeeper.AddVote(suite.ctx, proposal.Id, suite.addrs[0], voteOptions, "") suite.Require().ErrorContains(err, ": inactive proposal") } } @@ -181,7 +181,7 @@ func (suite *KeeperTestSuite) TestSubmitProposal() { for i, tc := range testCases { prop, err := v1.NewLegacyContent(tc.content, tc.authority) suite.Require().NoError(err) - _, err = suite.govKeeper.SubmitProposal(suite.ctx, []sdk.Msg{prop}, tc.metadata, "title", "", sdk.AccAddress("cosmos1ghekyjucln7y67ntx7cf27m9dpuxxemn4c8g4r"), tc.expedited) + _, err = suite.govKeeper.SubmitProposal(suite.ctx, []sdk.Msg{prop}, tc.metadata, "title", "", suite.addrs[0], tc.expedited) suite.Require().True(errors.Is(tc.expectedErr, err), "tc #%d; got: %v, expected: %v", i, err, tc.expectedErr) } } @@ -190,11 +190,11 @@ func (suite *KeeperTestSuite) TestGetProposalsFiltered() { proposalID := uint64(1) status := []v1.ProposalStatus{v1.StatusDepositPeriod, v1.StatusVotingPeriod} - addr1 := sdk.AccAddress("foo_________________") + addr1 := suite.addrs[1] for _, s := range status { for i := 0; i < 50; i++ { - p, err := v1.NewProposal(TestProposal, proposalID, time.Now(), time.Now(), "metadata", "title", "summary", sdk.AccAddress("cosmos1ghekyjucln7y67ntx7cf27m9dpuxxemn4c8g4r"), false) + p, err := v1.NewProposal(TestProposal, proposalID, time.Now(), time.Now(), "metadata", "title", "summary", suite.addrs[0], false) suite.Require().NoError(err) p.Status = s diff --git a/x/gov/keeper/tally.go b/x/gov/keeper/tally.go index 37c1b2af1a9f..d40778d8038c 100644 --- a/x/gov/keeper/tally.go +++ b/x/gov/keeper/tally.go @@ -11,7 +11,7 @@ import ( // Tally iterates over the votes and updates the tally of a proposal based on the voting power of the // voters -func (keeper Keeper) Tally(ctx sdk.Context, proposal v1.Proposal) (passes bool, burnDeposits bool, tallyResults v1.TallyResult) { +func (keeper Keeper) Tally(ctx sdk.Context, proposal v1.Proposal) (passes, burnDeposits bool, tallyResults v1.TallyResult) { results := make(map[v1.VoteOption]sdk.Dec) results[v1.OptionYes] = math.LegacyZeroDec() results[v1.OptionAbstain] = math.LegacyZeroDec() @@ -36,9 +36,12 @@ func (keeper Keeper) Tally(ctx sdk.Context, proposal v1.Proposal) (passes bool, keeper.IterateVotes(ctx, proposal.Id, func(vote v1.Vote) bool { // if validator, just record it in the map - voter := sdk.MustAccAddressFromBech32(vote.Voter) + voter, err := keeper.authKeeper.StringToBytes(vote.Voter) + if err != nil { + panic(err) + } - valAddrStr := sdk.ValAddress(voter.Bytes()).String() + valAddrStr := sdk.ValAddress(voter).String() if val, ok := currValidators[valAddrStr]; ok { val.Vote = vote.Options currValidators[valAddrStr] = val @@ -58,7 +61,7 @@ func (keeper Keeper) Tally(ctx sdk.Context, proposal v1.Proposal) (passes bool, votingPower := delegation.GetShares().MulInt(val.BondedTokens).Quo(val.DelegatorShares) for _, option := range vote.Options { - weight, _ := sdk.NewDecFromStr(option.Weight) + weight, _ := math.LegacyNewDecFromStr(option.Weight) subPower := votingPower.Mul(weight) results[option.Option] = results[option.Option].Add(subPower) } @@ -82,7 +85,7 @@ func (keeper Keeper) Tally(ctx sdk.Context, proposal v1.Proposal) (passes bool, votingPower := sharesAfterDeductions.MulInt(val.BondedTokens).Quo(val.DelegatorShares) for _, option := range val.Vote { - weight, _ := sdk.NewDecFromStr(option.Weight) + weight, _ := math.LegacyNewDecFromStr(option.Weight) subPower := votingPower.Mul(weight) results[option.Option] = results[option.Option].Add(subPower) } @@ -99,8 +102,8 @@ func (keeper Keeper) Tally(ctx sdk.Context, proposal v1.Proposal) (passes bool, } // If there is not enough quorum of votes, the proposal fails - percentVoting := totalVotingPower.Quo(sdk.NewDecFromInt(keeper.sk.TotalBondedTokens(ctx))) - quorum, _ := sdk.NewDecFromStr(params.Quorum) + percentVoting := totalVotingPower.Quo(math.LegacyNewDecFromInt(keeper.sk.TotalBondedTokens(ctx))) + quorum, _ := math.LegacyNewDecFromStr(params.Quorum) if percentVoting.LT(quorum) { return false, params.BurnVoteQuorum, tallyResults } @@ -111,7 +114,7 @@ func (keeper Keeper) Tally(ctx sdk.Context, proposal v1.Proposal) (passes bool, } // If more than 1/3 of voters veto, proposal fails - vetoThreshold, _ := sdk.NewDecFromStr(params.VetoThreshold) + vetoThreshold, _ := math.LegacyNewDecFromStr(params.VetoThreshold) if results[v1.OptionNoWithVeto].Quo(totalVotingPower).GT(vetoThreshold) { return false, params.BurnVoteVeto, tallyResults } @@ -125,7 +128,7 @@ func (keeper Keeper) Tally(ctx sdk.Context, proposal v1.Proposal) (passes bool, thresholdStr = params.GetThreshold() } - threshold, _ := sdk.NewDecFromStr(thresholdStr) + threshold, _ := math.LegacyNewDecFromStr(thresholdStr) if results[v1.OptionYes].Quo(totalVotingPower.Sub(results[v1.OptionAbstain])).GT(threshold) { return true, false, tallyResults } diff --git a/x/gov/keeper/vote.go b/x/gov/keeper/vote.go index 79295b9ed006..0a1e2b6f6cf5 100644 --- a/x/gov/keeper/vote.go +++ b/x/gov/keeper/vote.go @@ -82,7 +82,10 @@ func (keeper Keeper) GetVote(ctx sdk.Context, proposalID uint64, voterAddr sdk.A func (keeper Keeper) SetVote(ctx sdk.Context, vote v1.Vote) { store := ctx.KVStore(keeper.storeKey) bz := keeper.cdc.MustMarshal(&vote) - addr := sdk.MustAccAddressFromBech32(vote.Voter) + addr, err := keeper.authKeeper.StringToBytes(vote.Voter) + if err != nil { + panic(err) + } store.Set(types.VoteKey(vote.ProposalId, addr), bz) } diff --git a/x/gov/keeper/vote_test.go b/x/gov/keeper/vote_test.go index e3bae155f54f..29e1e89722f4 100644 --- a/x/gov/keeper/vote_test.go +++ b/x/gov/keeper/vote_test.go @@ -3,6 +3,7 @@ package keeper_test import ( "testing" + sdkmath "cosmossdk.io/math" "github.com/stretchr/testify/require" simtestutil "github.com/cosmos/cosmos-sdk/testutil/sims" @@ -11,8 +12,12 @@ import ( ) func TestVotes(t *testing.T) { - govKeeper, _, bankKeeper, stakingKeeper, _, _, ctx := setupGovKeeper(t) - addrs := simtestutil.AddTestAddrsIncremental(bankKeeper, stakingKeeper, ctx, 2, sdk.NewInt(10000000)) + govKeeper, authKeeper, bankKeeper, stakingKeeper, _, _, ctx := setupGovKeeper(t) + addrs := simtestutil.AddTestAddrsIncremental(bankKeeper, stakingKeeper, ctx, 2, sdkmath.NewInt(10000000)) + for _, addr := range addrs { + authKeeper.EXPECT().BytesToString(addr).Return(addr.String(), nil).AnyTimes() + authKeeper.EXPECT().StringToBytes(addr.String()).Return(addr, nil).AnyTimes() + } tp := TestProposal proposal, err := govKeeper.SubmitProposal(ctx, tp, "", "title", "description", sdk.AccAddress("cosmos1ghekyjucln7y67ntx7cf27m9dpuxxemn4c8g4r"), false) @@ -50,10 +55,10 @@ func TestVotes(t *testing.T) { // Test second vote require.NoError(t, govKeeper.AddVote(ctx, proposalID, addrs[1], v1.WeightedVoteOptions{ - v1.NewWeightedVoteOption(v1.OptionYes, sdk.NewDecWithPrec(60, 2)), - v1.NewWeightedVoteOption(v1.OptionNo, sdk.NewDecWithPrec(30, 2)), - v1.NewWeightedVoteOption(v1.OptionAbstain, sdk.NewDecWithPrec(5, 2)), - v1.NewWeightedVoteOption(v1.OptionNoWithVeto, sdk.NewDecWithPrec(5, 2)), + v1.NewWeightedVoteOption(v1.OptionYes, sdkmath.LegacyNewDecWithPrec(60, 2)), + v1.NewWeightedVoteOption(v1.OptionNo, sdkmath.LegacyNewDecWithPrec(30, 2)), + v1.NewWeightedVoteOption(v1.OptionAbstain, sdkmath.LegacyNewDecWithPrec(5, 2)), + v1.NewWeightedVoteOption(v1.OptionNoWithVeto, sdkmath.LegacyNewDecWithPrec(5, 2)), }, "")) vote, found = govKeeper.GetVote(ctx, proposalID, addrs[1]) require.True(t, found) @@ -64,10 +69,10 @@ func TestVotes(t *testing.T) { require.Equal(t, v1.OptionNo, vote.Options[1].Option) require.Equal(t, v1.OptionAbstain, vote.Options[2].Option) require.Equal(t, v1.OptionNoWithVeto, vote.Options[3].Option) - require.Equal(t, vote.Options[0].Weight, sdk.NewDecWithPrec(60, 2).String()) - require.Equal(t, vote.Options[1].Weight, sdk.NewDecWithPrec(30, 2).String()) - require.Equal(t, vote.Options[2].Weight, sdk.NewDecWithPrec(5, 2).String()) - require.Equal(t, vote.Options[3].Weight, sdk.NewDecWithPrec(5, 2).String()) + require.Equal(t, vote.Options[0].Weight, sdkmath.LegacyNewDecWithPrec(60, 2).String()) + require.Equal(t, vote.Options[1].Weight, sdkmath.LegacyNewDecWithPrec(30, 2).String()) + require.Equal(t, vote.Options[2].Weight, sdkmath.LegacyNewDecWithPrec(5, 2).String()) + require.Equal(t, vote.Options[3].Weight, sdkmath.LegacyNewDecWithPrec(5, 2).String()) // Test vote iterator // NOTE order of deposits is determined by the addresses @@ -81,8 +86,8 @@ func TestVotes(t *testing.T) { require.Equal(t, addrs[1].String(), votes[1].Voter) require.Equal(t, proposalID, votes[1].ProposalId) require.True(t, len(votes[1].Options) == 4) - require.Equal(t, votes[1].Options[0].Weight, sdk.NewDecWithPrec(60, 2).String()) - require.Equal(t, votes[1].Options[1].Weight, sdk.NewDecWithPrec(30, 2).String()) - require.Equal(t, votes[1].Options[2].Weight, sdk.NewDecWithPrec(5, 2).String()) - require.Equal(t, votes[1].Options[3].Weight, sdk.NewDecWithPrec(5, 2).String()) + require.Equal(t, votes[1].Options[0].Weight, sdkmath.LegacyNewDecWithPrec(60, 2).String()) + require.Equal(t, votes[1].Options[1].Weight, sdkmath.LegacyNewDecWithPrec(30, 2).String()) + require.Equal(t, votes[1].Options[2].Weight, sdkmath.LegacyNewDecWithPrec(5, 2).String()) + require.Equal(t, votes[1].Options[3].Weight, sdkmath.LegacyNewDecWithPrec(5, 2).String()) } diff --git a/x/gov/migrations/v3/convert_test.go b/x/gov/migrations/v3/convert_test.go index b6ad2633f73d..719d1040fe86 100644 --- a/x/gov/migrations/v3/convert_test.go +++ b/x/gov/migrations/v3/convert_test.go @@ -60,10 +60,10 @@ func TestConvertToLegacyProposal(t *testing.T) { require.Equal(t, v1beta1Proposal.VotingEndTime, *proposal.VotingEndTime) require.Equal(t, v1beta1Proposal.SubmitTime, *proposal.SubmitTime) require.Equal(t, v1beta1Proposal.DepositEndTime, *proposal.DepositEndTime) - require.Equal(t, v1beta1Proposal.FinalTallyResult.Yes, sdk.NewInt(0)) - require.Equal(t, v1beta1Proposal.FinalTallyResult.No, sdk.NewInt(0)) - require.Equal(t, v1beta1Proposal.FinalTallyResult.NoWithVeto, sdk.NewInt(0)) - require.Equal(t, v1beta1Proposal.FinalTallyResult.Abstain, sdk.NewInt(0)) + require.Equal(t, v1beta1Proposal.FinalTallyResult.Yes, math.NewInt(0)) + require.Equal(t, v1beta1Proposal.FinalTallyResult.No, math.NewInt(0)) + require.Equal(t, v1beta1Proposal.FinalTallyResult.NoWithVeto, math.NewInt(0)) + require.Equal(t, v1beta1Proposal.FinalTallyResult.Abstain, math.NewInt(0)) tp, ok := v1beta1Proposal.Content.GetCachedValue().(*v1beta1.TextProposal) require.Truef(t, ok, "expected *TextProposal, got %T", v1beta1Proposal.Content.GetCachedValue()) require.Equal(t, tp.Title, "title") @@ -203,7 +203,7 @@ func TestConvertToLegacyDeposit(t *testing.T) { deposit := v1.Deposit{ ProposalId: 1, Depositor: "cosmos1fl48vsnmsdzcv85q5d2q4z5ajdha8yu34mf0eh", - Amount: sdk.NewCoins(sdk.NewCoin(sdk.DefaultBondDenom, sdk.NewInt(1))), + Amount: sdk.NewCoins(sdk.NewCoin(sdk.DefaultBondDenom, math.NewInt(1))), } v1beta1Deposit := v3.ConvertToLegacyDeposit(&deposit) diff --git a/x/gov/migrations/v3/json_test.go b/x/gov/migrations/v3/json_test.go index fdfad8941ae4..17a36689d387 100644 --- a/x/gov/migrations/v3/json_test.go +++ b/x/gov/migrations/v3/json_test.go @@ -5,6 +5,7 @@ import ( "testing" "time" + sdkmath "cosmossdk.io/math" "github.com/cosmos/gogoproto/proto" "github.com/stretchr/testify/require" @@ -43,7 +44,7 @@ func TestMigrateJSON(t *testing.T) { VotingEndTime: propTime, Status: v1beta1.StatusDepositPeriod, FinalTallyResult: v1beta1.EmptyTallyResult(), - TotalDeposit: sdk.NewCoins(sdk.NewCoin("stake", sdk.NewInt(123))), + TotalDeposit: sdk.NewCoins(sdk.NewCoin("stake", sdkmath.NewInt(123))), }, } govGenState.Votes = v1beta1.Votes{ diff --git a/x/gov/migrations/v4/store_test.go b/x/gov/migrations/v4/store_test.go index 64dbff538b2e..cadc1d14308d 100644 --- a/x/gov/migrations/v4/store_test.go +++ b/x/gov/migrations/v4/store_test.go @@ -6,6 +6,7 @@ import ( "github.com/stretchr/testify/require" + sdkmath "cosmossdk.io/math" storetypes "cosmossdk.io/store/types" "github.com/cosmos/cosmos-sdk/testutil" @@ -129,7 +130,7 @@ func getTestProposal() []sdk.Msg { } return []sdk.Msg{ - banktypes.NewMsgSend(govAcct, addr, sdk.NewCoins(sdk.NewCoin("stake", sdk.NewInt(1000)))), + banktypes.NewMsgSend(govAcct, addr, sdk.NewCoins(sdk.NewCoin("stake", sdkmath.NewInt(1000)))), legacyProposalMsg, } } diff --git a/x/gov/module.go b/x/gov/module.go index 00acf507cd2c..1f46cab77d4e 100644 --- a/x/gov/module.go +++ b/x/gov/module.go @@ -13,6 +13,7 @@ import ( "golang.org/x/exp/slices" modulev1 "cosmossdk.io/api/cosmos/gov/module/v1" + "cosmossdk.io/core/address" "cosmossdk.io/core/appmodule" "cosmossdk.io/depinject" @@ -47,6 +48,7 @@ var ( type AppModuleBasic struct { cdc codec.Codec legacyProposalHandlers []govclient.ProposalHandler // legacy proposal handlers which live in governance cli and rest + ac address.Codec } // NewAppModuleBasic creates a new AppModuleBasic object @@ -84,7 +86,7 @@ func (AppModuleBasic) ValidateGenesis(cdc codec.JSONCodec, config client.TxEncod } // RegisterGRPCGatewayRoutes registers the gRPC Gateway routes for the gov module. -func (a AppModuleBasic) RegisterGRPCGatewayRoutes(clientCtx client.Context, mux *gwruntime.ServeMux) { +func (AppModuleBasic) RegisterGRPCGatewayRoutes(clientCtx client.Context, mux *gwruntime.ServeMux) { if err := v1.RegisterQueryHandlerClient(context.Background(), mux, v1.NewQueryClient(clientCtx)); err != nil { panic(err) } @@ -94,8 +96,8 @@ func (a AppModuleBasic) RegisterGRPCGatewayRoutes(clientCtx client.Context, mux } // GetTxCmd returns the root tx command for the gov module. -func (a AppModuleBasic) GetTxCmd() *cobra.Command { - legacyProposalCLIHandlers := getProposalCLIHandlers(a.legacyProposalHandlers) +func (ab AppModuleBasic) GetTxCmd() *cobra.Command { + legacyProposalCLIHandlers := getProposalCLIHandlers(ab.legacyProposalHandlers) return cli.NewTxCmd(legacyProposalCLIHandlers) } @@ -109,12 +111,12 @@ func getProposalCLIHandlers(handlers []govclient.ProposalHandler) []*cobra.Comma } // GetQueryCmd returns the root query command for the gov module. -func (AppModuleBasic) GetQueryCmd() *cobra.Command { - return cli.GetQueryCmd() +func (ab AppModuleBasic) GetQueryCmd() *cobra.Command { + return cli.GetQueryCmd(ab.ac) } // RegisterInterfaces implements InterfaceModule.RegisterInterfaces -func (a AppModuleBasic) RegisterInterfaces(registry codectypes.InterfaceRegistry) { +func (AppModuleBasic) RegisterInterfaces(registry codectypes.InterfaceRegistry) { v1.RegisterInterfaces(registry) v1beta1.RegisterInterfaces(registry) } @@ -137,7 +139,7 @@ func NewAppModule( ak govtypes.AccountKeeper, bk govtypes.BankKeeper, ss govtypes.ParamSubspace, ) AppModule { return AppModule{ - AppModuleBasic: AppModuleBasic{cdc: cdc}, + AppModuleBasic: AppModuleBasic{cdc: cdc, ac: ak}, keeper: keeper, accountKeeper: ak, bankKeeper: bk, @@ -163,8 +165,7 @@ func init() { appmodule.Invoke(InvokeAddRoutes, InvokeSetHooks)) } -//nolint:revive -type GovInputs struct { +type ModuleInputs struct { depinject.In Config *modulev1.Module @@ -182,8 +183,7 @@ type GovInputs struct { LegacySubspace govtypes.ParamSubspace } -//nolint:revive -type GovOutputs struct { +type ModuleOutputs struct { depinject.Out Module appmodule.AppModule @@ -191,7 +191,7 @@ type GovOutputs struct { HandlerRoute v1beta1.HandlerRoute } -func ProvideModule(in GovInputs) GovOutputs { +func ProvideModule(in ModuleInputs) ModuleOutputs { defaultConfig := govtypes.DefaultConfig() if in.Config.MaxMetadataLen != 0 { defaultConfig.MaxMetadataLen = in.Config.MaxMetadataLen @@ -217,7 +217,7 @@ func ProvideModule(in GovInputs) GovOutputs { m := NewAppModule(in.Cdc, k, in.AccountKeeper, in.BankKeeper, in.LegacySubspace) hr := v1beta1.HandlerRoute{Handler: v1beta1.ProposalHandler, RouteKey: govtypes.RouterKey} - return GovOutputs{Module: m, Keeper: k, HandlerRoute: hr} + return ModuleOutputs{Module: m, Keeper: k, HandlerRoute: hr} } func ProvideKeyTable() paramtypes.KeyTable { @@ -340,7 +340,7 @@ func (AppModule) GenerateGenesisState(simState *module.SimulationState) { // ProposalContents returns all the gov content functions used to // simulate governance proposals. -func (AppModule) ProposalContents(simState module.SimulationState) []simtypes.WeightedProposalContent { //nolint:staticcheck +func (AppModule) ProposalContents(simState module.SimulationState) []simtypes.WeightedProposalContent { //nolint:staticcheck // used for legacy testing return simulation.ProposalContents() } @@ -357,7 +357,7 @@ func (am AppModule) RegisterStoreDecoder(sdr simtypes.StoreDecoderRegistry) { // WeightedOperations returns the all the gov module operations with their respective weights. func (am AppModule) WeightedOperations(simState module.SimulationState) []simtypes.WeightedOperation { return simulation.WeightedOperations( - simState.AppParams, simState.Cdc, + simState.AppParams, simState.Cdc, simState.TxConfig, am.accountKeeper, am.bankKeeper, am.keeper, simState.ProposalMsgs, simState.LegacyProposalContents, ) diff --git a/x/gov/simulation/genesis.go b/x/gov/simulation/genesis.go index bd80f4927aab..f6a3a9fd9bc5 100644 --- a/x/gov/simulation/genesis.go +++ b/x/gov/simulation/genesis.go @@ -6,7 +6,7 @@ import ( "math/rand" "time" - "cosmossdk.io/math" + sdkmath "cosmossdk.io/math" sdk "github.com/cosmos/cosmos-sdk/types" "github.com/cosmos/cosmos-sdk/types/module" @@ -75,23 +75,23 @@ func GenExpeditedVotingPeriod(r *rand.Rand) time.Duration { } // GenQuorum returns randomized Quorum -func GenQuorum(r *rand.Rand) math.LegacyDec { - return sdk.NewDecWithPrec(int64(simulation.RandIntBetween(r, 334, 500)), 3) +func GenQuorum(r *rand.Rand) sdkmath.LegacyDec { + return sdkmath.LegacyNewDecWithPrec(int64(simulation.RandIntBetween(r, 334, 500)), 3) } // GenThreshold returns randomized Threshold -func GenThreshold(r *rand.Rand) math.LegacyDec { - return sdk.NewDecWithPrec(int64(simulation.RandIntBetween(r, 450, tallyNonExpeditedMax+1)), 3) +func GenThreshold(r *rand.Rand) sdkmath.LegacyDec { + return sdkmath.LegacyNewDecWithPrec(int64(simulation.RandIntBetween(r, 450, tallyNonExpeditedMax+1)), 3) } // GenExpeditedThreshold randomized ExpeditedThreshold func GenExpeditedThreshold(r *rand.Rand) sdk.Dec { - return sdk.NewDecWithPrec(int64(simulation.RandIntBetween(r, tallyNonExpeditedMax, 550)), 3) + return sdkmath.LegacyNewDecWithPrec(int64(simulation.RandIntBetween(r, tallyNonExpeditedMax, 550)), 3) } // GenVeto returns randomized Veto -func GenVeto(r *rand.Rand) math.LegacyDec { - return sdk.NewDecWithPrec(int64(simulation.RandIntBetween(r, 250, 334)), 3) +func GenVeto(r *rand.Rand) sdkmath.LegacyDec { + return sdkmath.LegacyNewDecWithPrec(int64(simulation.RandIntBetween(r, 250, 334)), 3) } // RandomizedGenState generates a random GenesisState for gov diff --git a/x/gov/simulation/operations.go b/x/gov/simulation/operations.go index 4ea36900e787..97a0e7734337 100644 --- a/x/gov/simulation/operations.go +++ b/x/gov/simulation/operations.go @@ -5,11 +5,13 @@ import ( "math/rand" "time" + sdkmath "cosmossdk.io/math" + "github.com/cosmos/cosmos-sdk/baseapp" + "github.com/cosmos/cosmos-sdk/client" "github.com/cosmos/cosmos-sdk/codec" simtestutil "github.com/cosmos/cosmos-sdk/testutil/sims" sdk "github.com/cosmos/cosmos-sdk/types" - moduletestutil "github.com/cosmos/cosmos-sdk/types/module/testutil" simtypes "github.com/cosmos/cosmos-sdk/types/simulation" "github.com/cosmos/cosmos-sdk/x/gov/keeper" "github.com/cosmos/cosmos-sdk/x/gov/types" @@ -29,8 +31,6 @@ var ( ) // Simulation operation weights constants -// -//nolint:gosec // these are not hard-coded credentials. const ( OpWeightMsgDeposit = "op_weight_msg_deposit" OpWeightMsgVote = "op_weight_msg_vote" @@ -45,7 +45,16 @@ const ( ) // WeightedOperations returns all the operations from the module with their respective weights -func WeightedOperations(appParams simtypes.AppParams, cdc codec.JSONCodec, ak types.AccountKeeper, bk types.BankKeeper, k *keeper.Keeper, wMsgs []simtypes.WeightedProposalMsg, wContents []simtypes.WeightedProposalContent) simulation.WeightedOperations { //nolint:staticcheck +func WeightedOperations( + appParams simtypes.AppParams, + cdc codec.JSONCodec, + txGen client.TxConfig, + ak types.AccountKeeper, + bk types.BankKeeper, + k *keeper.Keeper, + wMsgs []simtypes.WeightedProposalMsg, + wContents []simtypes.WeightedProposalContent, //nolint:staticcheck // used for legacy testing +) simulation.WeightedOperations { var ( weightMsgDeposit int weightMsgVote int @@ -90,7 +99,7 @@ func WeightedOperations(appParams simtypes.AppParams, cdc codec.JSONCodec, ak ty wProposalOps, simulation.NewWeightedOperation( weight, - SimulateMsgSubmitProposal(ak, bk, k, wMsg.MsgSimulatorFn()), + SimulateMsgSubmitProposal(txGen, ak, bk, k, wMsg.MsgSimulatorFn()), ), ) } @@ -108,7 +117,7 @@ func WeightedOperations(appParams simtypes.AppParams, cdc codec.JSONCodec, ak ty wLegacyProposalOps, simulation.NewWeightedOperation( weight, - SimulateMsgSubmitLegacyProposal(ak, bk, k, wContent.ContentSimulatorFn()), + SimulateMsgSubmitLegacyProposal(txGen, ak, bk, k, wContent.ContentSimulatorFn()), ), ) } @@ -116,19 +125,19 @@ func WeightedOperations(appParams simtypes.AppParams, cdc codec.JSONCodec, ak ty wGovOps := simulation.WeightedOperations{ simulation.NewWeightedOperation( weightMsgDeposit, - SimulateMsgDeposit(ak, bk, k), + SimulateMsgDeposit(txGen, ak, bk, k), ), simulation.NewWeightedOperation( weightMsgVote, - SimulateMsgVote(ak, bk, k), + SimulateMsgVote(txGen, ak, bk, k), ), simulation.NewWeightedOperation( weightMsgVoteWeighted, - SimulateMsgVoteWeighted(ak, bk, k), + SimulateMsgVoteWeighted(txGen, ak, bk, k), ), simulation.NewWeightedOperation( weightMsgCancelProposal, - SimulateMsgCancelProposal(ak, bk, k), + SimulateMsgCancelProposal(txGen, ak, bk, k), ), } @@ -138,7 +147,13 @@ func WeightedOperations(appParams simtypes.AppParams, cdc codec.JSONCodec, ak ty // SimulateMsgSubmitProposal simulates creating a msg Submit Proposal // voting on the proposal, and subsequently slashing the proposal. It is implemented using // future operations. -func SimulateMsgSubmitProposal(ak types.AccountKeeper, bk types.BankKeeper, k *keeper.Keeper, msgSim simtypes.MsgSimulatorFn) simtypes.Operation { +func SimulateMsgSubmitProposal( + txGen client.TxConfig, + ak types.AccountKeeper, + bk types.BankKeeper, + k *keeper.Keeper, + msgSim simtypes.MsgSimulatorFn, +) simtypes.Operation { return func(r *rand.Rand, app *baseapp.BaseApp, ctx sdk.Context, accs []simtypes.Account, chainID string, ) (simtypes.OperationMsg, []simtypes.FutureOperation, error) { msgs := []sdk.Msg{} @@ -147,14 +162,20 @@ func SimulateMsgSubmitProposal(ak types.AccountKeeper, bk types.BankKeeper, k *k msgs = append(msgs, proposalMsg) } - return simulateMsgSubmitProposal(ak, bk, k, msgs)(r, app, ctx, accs, chainID) + return simulateMsgSubmitProposal(txGen, ak, bk, k, msgs)(r, app, ctx, accs, chainID) } } // SimulateMsgSubmitLegacyProposal simulates creating a msg Submit Proposal // voting on the proposal, and subsequently slashing the proposal. It is implemented using // future operations. -func SimulateMsgSubmitLegacyProposal(ak types.AccountKeeper, bk types.BankKeeper, k *keeper.Keeper, contentSim simtypes.ContentSimulatorFn) simtypes.Operation { //nolint:staticcheck +func SimulateMsgSubmitLegacyProposal( + txGen client.TxConfig, + ak types.AccountKeeper, + bk types.BankKeeper, + k *keeper.Keeper, + contentSim simtypes.ContentSimulatorFn, //nolint:staticcheck // used for legacy testing +) simtypes.Operation { return func(r *rand.Rand, app *baseapp.BaseApp, ctx sdk.Context, accs []simtypes.Account, chainID string, ) (simtypes.OperationMsg, []simtypes.FutureOperation, error) { // 1) submit proposal now @@ -169,11 +190,17 @@ func SimulateMsgSubmitLegacyProposal(ak types.AccountKeeper, bk types.BankKeeper return simtypes.NoOpMsg(types.ModuleName, TypeMsgSubmitProposal, "error converting legacy content into proposal message"), nil, err } - return simulateMsgSubmitProposal(ak, bk, k, []sdk.Msg{contentMsg})(r, app, ctx, accs, chainID) + return simulateMsgSubmitProposal(txGen, ak, bk, k, []sdk.Msg{contentMsg})(r, app, ctx, accs, chainID) } } -func simulateMsgSubmitProposal(ak types.AccountKeeper, bk types.BankKeeper, k *keeper.Keeper, proposalMsgs []sdk.Msg) simtypes.Operation { +func simulateMsgSubmitProposal( + txGen client.TxConfig, + ak types.AccountKeeper, + bk types.BankKeeper, + k *keeper.Keeper, + proposalMsgs []sdk.Msg, +) simtypes.Operation { // The states are: // column 1: All validators vote // column 2: 90% vote @@ -226,7 +253,6 @@ func simulateMsgSubmitProposal(ak types.AccountKeeper, bk types.BankKeeper, k *k } account := ak.GetAccount(ctx, simAccount.Address) - txGen := moduletestutil.MakeTestEncodingConfig().TxConfig tx, err := simtestutil.GenSignedMockTx( r, txGen, @@ -272,7 +298,7 @@ func simulateMsgSubmitProposal(ak types.AccountKeeper, bk types.BankKeeper, k *k whenVote := ctx.BlockHeader().Time.Add(time.Duration(r.Int63n(int64(votingPeriod.Seconds()))) * time.Second) fops[i] = simtypes.FutureOperation{ BlockTime: whenVote, - Op: operationSimulateMsgVote(ak, bk, k, accs[whoVotes[i]], int64(proposalID)), + Op: operationSimulateMsgVote(txGen, ak, bk, k, accs[whoVotes[i]], int64(proposalID)), } } @@ -281,7 +307,12 @@ func simulateMsgSubmitProposal(ak types.AccountKeeper, bk types.BankKeeper, k *k } // SimulateMsgDeposit generates a MsgDeposit with random values. -func SimulateMsgDeposit(ak types.AccountKeeper, bk types.BankKeeper, k *keeper.Keeper) simtypes.Operation { +func SimulateMsgDeposit( + txGen client.TxConfig, + ak types.AccountKeeper, + bk types.BankKeeper, + k *keeper.Keeper, +) simtypes.Operation { return func( r *rand.Rand, app *baseapp.BaseApp, ctx sdk.Context, accs []simtypes.Account, chainID string, @@ -317,7 +348,7 @@ func SimulateMsgDeposit(ak types.AccountKeeper, bk types.BankKeeper, k *keeper.K txCtx := simulation.OperationInput{ R: r, App: app, - TxGen: moduletestutil.MakeTestEncodingConfig().TxConfig, + TxGen: txGen, Cdc: nil, Msg: msg, Context: ctx, @@ -331,11 +362,23 @@ func SimulateMsgDeposit(ak types.AccountKeeper, bk types.BankKeeper, k *keeper.K } // SimulateMsgVote generates a MsgVote with random values. -func SimulateMsgVote(ak types.AccountKeeper, bk types.BankKeeper, k *keeper.Keeper) simtypes.Operation { - return operationSimulateMsgVote(ak, bk, k, simtypes.Account{}, -1) +func SimulateMsgVote( + txGen client.TxConfig, + ak types.AccountKeeper, + bk types.BankKeeper, + k *keeper.Keeper, +) simtypes.Operation { + return operationSimulateMsgVote(txGen, ak, bk, k, simtypes.Account{}, -1) } -func operationSimulateMsgVote(ak types.AccountKeeper, bk types.BankKeeper, k *keeper.Keeper, simAccount simtypes.Account, proposalIDInt int64) simtypes.Operation { +func operationSimulateMsgVote( + txGen client.TxConfig, + ak types.AccountKeeper, + bk types.BankKeeper, + k *keeper.Keeper, + simAccount simtypes.Account, + proposalIDInt int64, +) simtypes.Operation { return func( r *rand.Rand, app *baseapp.BaseApp, ctx sdk.Context, accs []simtypes.Account, chainID string, @@ -366,7 +409,7 @@ func operationSimulateMsgVote(ak types.AccountKeeper, bk types.BankKeeper, k *ke txCtx := simulation.OperationInput{ R: r, App: app, - TxGen: moduletestutil.MakeTestEncodingConfig().TxConfig, + TxGen: txGen, Cdc: nil, Msg: msg, Context: ctx, @@ -382,11 +425,23 @@ func operationSimulateMsgVote(ak types.AccountKeeper, bk types.BankKeeper, k *ke } // SimulateMsgVoteWeighted generates a MsgVoteWeighted with random values. -func SimulateMsgVoteWeighted(ak types.AccountKeeper, bk types.BankKeeper, k *keeper.Keeper) simtypes.Operation { - return operationSimulateMsgVoteWeighted(ak, bk, k, simtypes.Account{}, -1) +func SimulateMsgVoteWeighted( + txGen client.TxConfig, + ak types.AccountKeeper, + bk types.BankKeeper, + k *keeper.Keeper, +) simtypes.Operation { + return operationSimulateMsgVoteWeighted(txGen, ak, bk, k, simtypes.Account{}, -1) } -func operationSimulateMsgVoteWeighted(ak types.AccountKeeper, bk types.BankKeeper, k *keeper.Keeper, simAccount simtypes.Account, proposalIDInt int64) simtypes.Operation { +func operationSimulateMsgVoteWeighted( + txGen client.TxConfig, + ak types.AccountKeeper, + bk types.BankKeeper, + k *keeper.Keeper, + simAccount simtypes.Account, + proposalIDInt int64, +) simtypes.Operation { return func( r *rand.Rand, app *baseapp.BaseApp, ctx sdk.Context, accs []simtypes.Account, chainID string, @@ -417,7 +472,7 @@ func operationSimulateMsgVoteWeighted(ak types.AccountKeeper, bk types.BankKeepe txCtx := simulation.OperationInput{ R: r, App: app, - TxGen: moduletestutil.MakeTestEncodingConfig().TxConfig, + TxGen: txGen, Cdc: nil, Msg: msg, Context: ctx, @@ -433,7 +488,12 @@ func operationSimulateMsgVoteWeighted(ak types.AccountKeeper, bk types.BankKeepe } // SimulateMsgCancelProposal generates a MsgCancelProposal. -func SimulateMsgCancelProposal(ak types.AccountKeeper, bk types.BankKeeper, k *keeper.Keeper) simtypes.Operation { +func SimulateMsgCancelProposal( + txGen client.TxConfig, + ak types.AccountKeeper, + bk types.BankKeeper, + k *keeper.Keeper, +) simtypes.Operation { return func( r *rand.Rand, app *baseapp.BaseApp, ctx sdk.Context, accs []simtypes.Account, chainID string, @@ -460,7 +520,7 @@ func SimulateMsgCancelProposal(ak types.AccountKeeper, bk types.BankKeeper, k *k txCtx := simulation.OperationInput{ R: r, App: app, - TxGen: moduletestutil.MakeTestEncodingConfig().TxConfig, + TxGen: txGen, Cdc: nil, Msg: msg, Context: ctx, @@ -511,14 +571,14 @@ func randomDeposit( minDepositAmount := minDeposit[denomIndex].Amount - minAmount := sdk.ZeroInt() + minAmount := sdkmath.ZeroInt() if useMinAmount { - minDepositPercent, err := sdk.NewDecFromStr(params.MinInitialDepositRatio) + minDepositPercent, err := sdkmath.LegacyNewDecFromStr(params.MinInitialDepositRatio) if err != nil { return nil, false, err } - minAmount = sdk.NewDecFromInt(minDepositAmount).Mul(minDepositPercent).TruncateInt() + minAmount = sdkmath.LegacyNewDecFromInt(minDepositAmount).Mul(minDepositPercent).TruncateInt() } amount, err := simtypes.RandPositiveInt(r, minDepositAmount.Sub(minAmount)) @@ -602,19 +662,19 @@ func randomWeightedVotingOptions(r *rand.Rand) v1.WeightedVoteOptions { if w2 > 0 { weightedVoteOptions = append(weightedVoteOptions, &v1.WeightedVoteOption{ Option: v1.OptionAbstain, - Weight: sdk.NewDecWithPrec(int64(w2), 2).String(), + Weight: sdkmath.LegacyNewDecWithPrec(int64(w2), 2).String(), }) } if w3 > 0 { weightedVoteOptions = append(weightedVoteOptions, &v1.WeightedVoteOption{ Option: v1.OptionNo, - Weight: sdk.NewDecWithPrec(int64(w3), 2).String(), + Weight: sdkmath.LegacyNewDecWithPrec(int64(w3), 2).String(), }) } if w4 > 0 { weightedVoteOptions = append(weightedVoteOptions, &v1.WeightedVoteOption{ Option: v1.OptionNoWithVeto, - Weight: sdk.NewDecWithPrec(int64(w4), 2).String(), + Weight: sdkmath.LegacyNewDecWithPrec(int64(w4), 2).String(), }) } return weightedVoteOptions diff --git a/x/gov/simulation/operations_test.go b/x/gov/simulation/operations_test.go index 6293d9815e87..aa661f639b94 100644 --- a/x/gov/simulation/operations_test.go +++ b/x/gov/simulation/operations_test.go @@ -10,6 +10,7 @@ import ( cmtproto "github.com/cometbft/cometbft/proto/tendermint/types" "github.com/stretchr/testify/require" + "github.com/cosmos/cosmos-sdk/client" "github.com/cosmos/cosmos-sdk/runtime" "github.com/cosmos/cosmos-sdk/testutil/configurator" simtestutil "github.com/cosmos/cosmos-sdk/testutil/sims" @@ -37,7 +38,7 @@ import ( var ( _ simtypes.WeightedProposalMsg = MockWeightedProposals{} - _ simtypes.WeightedProposalContent = MockWeightedProposals{} //nolint:staticcheck + _ simtypes.WeightedProposalContent = MockWeightedProposals{} //nolint:staticcheck // testing legacy code path ) type MockWeightedProposals struct { @@ -58,8 +59,8 @@ func (m MockWeightedProposals) MsgSimulatorFn() simtypes.MsgSimulatorFn { } } -func (m MockWeightedProposals) ContentSimulatorFn() simtypes.ContentSimulatorFn { //nolint:staticcheck - return func(r *rand.Rand, _ sdk.Context, _ []simtypes.Account) simtypes.Content { //nolint:staticcheck +func (m MockWeightedProposals) ContentSimulatorFn() simtypes.ContentSimulatorFn { //nolint:staticcheck // testing legacy code path + return func(r *rand.Rand, _ sdk.Context, _ []simtypes.Account) simtypes.Content { //nolint:staticcheck // testing legacy code path return v1beta1.NewTextProposal( fmt.Sprintf("title-%d: %s", m.n, simtypes.RandStringOfLength(r, 100)), fmt.Sprintf("description-%d: %s", m.n, simtypes.RandStringOfLength(r, 4000)), @@ -75,8 +76,8 @@ func mockWeightedProposalMsg(n int) []simtypes.WeightedProposalMsg { return wpc } -func mockWeightedLegacyProposalContent(n int) []simtypes.WeightedProposalContent { //nolint:staticcheck - wpc := make([]simtypes.WeightedProposalContent, n) //nolint:staticcheck +func mockWeightedLegacyProposalContent(n int) []simtypes.WeightedProposalContent { //nolint:staticcheck // testing legacy code path + wpc := make([]simtypes.WeightedProposalContent, n) //nolint:staticcheck // testing legacy code path for i := 0; i < n; i++ { wpc[i] = MockWeightedProposals{i} } @@ -90,7 +91,7 @@ func TestWeightedOperations(t *testing.T) { ctx.WithChainID("test-chain") appParams := make(simtypes.AppParams) - weightesOps := simulation.WeightedOperations(appParams, govcodec.ModuleCdc, suite.AccountKeeper, + weightesOps := simulation.WeightedOperations(appParams, govcodec.ModuleCdc, suite.TxConfig, suite.AccountKeeper, suite.BankKeeper, suite.GovKeeper, mockWeightedProposalMsg(3), mockWeightedLegacyProposalContent(1), ) @@ -143,7 +144,7 @@ func TestSimulateMsgSubmitProposal(t *testing.T) { app.BeginBlock(abci.RequestBeginBlock{Header: cmtproto.Header{Height: app.LastBlockHeight() + 1, AppHash: app.LastCommitID().Hash}}) // execute operation - op := simulation.SimulateMsgSubmitProposal(suite.AccountKeeper, suite.BankKeeper, suite.GovKeeper, MockWeightedProposals{3}.MsgSimulatorFn()) + op := simulation.SimulateMsgSubmitProposal(suite.TxConfig, suite.AccountKeeper, suite.BankKeeper, suite.GovKeeper, MockWeightedProposals{3}.MsgSimulatorFn()) operationMsg, _, err := op(r, app.BaseApp, ctx, accounts, "") require.NoError(t, err) @@ -173,7 +174,7 @@ func TestSimulateMsgSubmitLegacyProposal(t *testing.T) { app.BeginBlock(abci.RequestBeginBlock{Header: cmtproto.Header{Height: app.LastBlockHeight() + 1, AppHash: app.LastCommitID().Hash}}) // execute operation - op := simulation.SimulateMsgSubmitLegacyProposal(suite.AccountKeeper, suite.BankKeeper, suite.GovKeeper, MockWeightedProposals{3}.ContentSimulatorFn()) + op := simulation.SimulateMsgSubmitLegacyProposal(suite.TxConfig, suite.AccountKeeper, suite.BankKeeper, suite.GovKeeper, MockWeightedProposals{3}.ContentSimulatorFn()) operationMsg, _, err := op(r, app.BaseApp, ctx, accounts, "") require.NoError(t, err) @@ -220,7 +221,7 @@ func TestSimulateMsgCancelProposal(t *testing.T) { app.BeginBlock(abci.RequestBeginBlock{Header: cmtproto.Header{Height: app.LastBlockHeight() + 1, AppHash: app.LastCommitID().Hash, Time: blockTime}}) // execute operation - op := simulation.SimulateMsgCancelProposal(suite.AccountKeeper, suite.BankKeeper, suite.GovKeeper) + op := simulation.SimulateMsgCancelProposal(suite.TxConfig, suite.AccountKeeper, suite.BankKeeper, suite.GovKeeper) operationMsg, _, err := op(r, app.BaseApp, ctx, accounts, "") require.NoError(t, err) @@ -264,7 +265,7 @@ func TestSimulateMsgDeposit(t *testing.T) { app.BeginBlock(abci.RequestBeginBlock{Header: cmtproto.Header{Height: app.LastBlockHeight() + 1, AppHash: app.LastCommitID().Hash, Time: blockTime}}) // execute operation - op := simulation.SimulateMsgDeposit(suite.AccountKeeper, suite.BankKeeper, suite.GovKeeper) + op := simulation.SimulateMsgDeposit(suite.TxConfig, suite.AccountKeeper, suite.BankKeeper, suite.GovKeeper) operationMsg, _, err := op(r, app.BaseApp, ctx, accounts, "") require.NoError(t, err) @@ -310,7 +311,7 @@ func TestSimulateMsgVote(t *testing.T) { app.BeginBlock(abci.RequestBeginBlock{Header: cmtproto.Header{Height: app.LastBlockHeight() + 1, AppHash: app.LastCommitID().Hash, Time: blockTime}}) // execute operation - op := simulation.SimulateMsgVote(suite.AccountKeeper, suite.BankKeeper, suite.GovKeeper) + op := simulation.SimulateMsgVote(suite.TxConfig, suite.AccountKeeper, suite.BankKeeper, suite.GovKeeper) operationMsg, _, err := op(r, app.BaseApp, ctx, accounts, "") require.NoError(t, err) @@ -353,7 +354,7 @@ func TestSimulateMsgVoteWeighted(t *testing.T) { app.BeginBlock(abci.RequestBeginBlock{Header: cmtproto.Header{Height: app.LastBlockHeight() + 1, AppHash: app.LastCommitID().Hash, Time: blockTime}}) // execute operation - op := simulation.SimulateMsgVoteWeighted(suite.AccountKeeper, suite.BankKeeper, suite.GovKeeper) + op := simulation.SimulateMsgVoteWeighted(suite.TxConfig, suite.AccountKeeper, suite.BankKeeper, suite.GovKeeper) operationMsg, _, err := op(r, app.BaseApp, ctx, accounts, "") require.NoError(t, err) @@ -368,6 +369,7 @@ func TestSimulateMsgVoteWeighted(t *testing.T) { } type suite struct { + TxConfig client.TxConfig AccountKeeper authkeeper.AccountKeeper BankKeeper bankkeeper.Keeper GovKeeper *keeper.Keeper @@ -389,7 +391,7 @@ func createTestSuite(t *testing.T, isCheckTx bool) (suite, sdk.Context) { configurator.ConsensusModule(), configurator.DistributionModule(), configurator.GovModule(), - ), &res.AccountKeeper, &res.BankKeeper, &res.GovKeeper, &res.StakingKeeper, &res.DistributionKeeper) + ), &res.TxConfig, &res.AccountKeeper, &res.BankKeeper, &res.GovKeeper, &res.StakingKeeper, &res.DistributionKeeper) require.NoError(t, err) ctx := app.BaseApp.NewContext(isCheckTx, cmtproto.Header{}) diff --git a/x/gov/simulation/proposals.go b/x/gov/simulation/proposals.go index 4afda5b0e498..06c6a1d785e2 100644 --- a/x/gov/simulation/proposals.go +++ b/x/gov/simulation/proposals.go @@ -31,7 +31,7 @@ func SimulateTextProposal(r *rand.Rand, _ sdk.Context, _ []simtypes.Account) sdk // ProposalContents defines the module weighted proposals' contents // -//nolint:staticcheck +//nolint:staticcheck // used for legacy testing func ProposalContents() []simtypes.WeightedProposalContent { return []simtypes.WeightedProposalContent{ simulation.NewWeightedProposalContent( @@ -44,7 +44,7 @@ func ProposalContents() []simtypes.WeightedProposalContent { // SimulateTextProposalContent returns a random text proposal content. // -//nolint:staticcheck +//nolint:staticcheck // used for legacy testing func SimulateLegacyTextProposalContent(r *rand.Rand, _ sdk.Context, _ []simtypes.Account) simtypes.Content { return v1beta1.NewTextProposal( simtypes.RandStringOfLength(r, 140), diff --git a/x/gov/testutil/expected_keepers.go b/x/gov/testutil/expected_keepers.go index 312c8292c434..c18a77a010b2 100644 --- a/x/gov/testutil/expected_keepers.go +++ b/x/gov/testutil/expected_keepers.go @@ -3,7 +3,9 @@ package testutil import ( - math "cosmossdk.io/math" + context "context" + + "cosmossdk.io/math" sdk "github.com/cosmos/cosmos-sdk/types" bankkeeper "github.com/cosmos/cosmos-sdk/x/bank/keeper" @@ -15,7 +17,7 @@ import ( type AccountKeeper interface { types.AccountKeeper - IterateAccounts(ctx sdk.Context, cb func(account sdk.AccountI) (stop bool)) + IterateAccounts(ctx context.Context, cb func(account sdk.AccountI) (stop bool)) } // BankKeeper extends gov's actual expected BankKeeper with additional diff --git a/x/gov/testutil/expected_keepers_mocks.go b/x/gov/testutil/expected_keepers_mocks.go index 62bdf8b03715..58027e55ea89 100644 --- a/x/gov/testutil/expected_keepers_mocks.go +++ b/x/gov/testutil/expected_keepers_mocks.go @@ -40,8 +40,23 @@ func (m *MockAccountKeeper) EXPECT() *MockAccountKeeperMockRecorder { return m.recorder } +// BytesToString mocks base method. +func (m *MockAccountKeeper) BytesToString(bz []byte) (string, error) { + m.ctrl.T.Helper() + ret := m.ctrl.Call(m, "BytesToString", bz) + ret0, _ := ret[0].(string) + ret1, _ := ret[1].(error) + return ret0, ret1 +} + +// BytesToString indicates an expected call of BytesToString. +func (mr *MockAccountKeeperMockRecorder) BytesToString(bz interface{}) *gomock.Call { + mr.mock.ctrl.T.Helper() + return mr.mock.ctrl.RecordCallWithMethodType(mr.mock, "BytesToString", reflect.TypeOf((*MockAccountKeeper)(nil).BytesToString), bz) +} + // GetAccount mocks base method. -func (m *MockAccountKeeper) GetAccount(ctx types.Context, addr types.AccAddress) types.AccountI { +func (m *MockAccountKeeper) GetAccount(ctx context.Context, addr types.AccAddress) types.AccountI { m.ctrl.T.Helper() ret := m.ctrl.Call(m, "GetAccount", ctx, addr) ret0, _ := ret[0].(types.AccountI) @@ -55,7 +70,7 @@ func (mr *MockAccountKeeperMockRecorder) GetAccount(ctx, addr interface{}) *gomo } // GetModuleAccount mocks base method. -func (m *MockAccountKeeper) GetModuleAccount(ctx types.Context, name string) types.ModuleAccountI { +func (m *MockAccountKeeper) GetModuleAccount(ctx context.Context, name string) types.ModuleAccountI { m.ctrl.T.Helper() ret := m.ctrl.Call(m, "GetModuleAccount", ctx, name) ret0, _ := ret[0].(types.ModuleAccountI) @@ -83,7 +98,7 @@ func (mr *MockAccountKeeperMockRecorder) GetModuleAddress(name interface{}) *gom } // IterateAccounts mocks base method. -func (m *MockAccountKeeper) IterateAccounts(ctx types.Context, cb func(types.AccountI) bool) { +func (m *MockAccountKeeper) IterateAccounts(ctx context.Context, cb func(types.AccountI) bool) { m.ctrl.T.Helper() m.ctrl.Call(m, "IterateAccounts", ctx, cb) } @@ -95,7 +110,7 @@ func (mr *MockAccountKeeperMockRecorder) IterateAccounts(ctx, cb interface{}) *g } // SetModuleAccount mocks base method. -func (m *MockAccountKeeper) SetModuleAccount(arg0 types.Context, arg1 types.ModuleAccountI) { +func (m *MockAccountKeeper) SetModuleAccount(arg0 context.Context, arg1 types.ModuleAccountI) { m.ctrl.T.Helper() m.ctrl.Call(m, "SetModuleAccount", arg0, arg1) } @@ -106,6 +121,21 @@ func (mr *MockAccountKeeperMockRecorder) SetModuleAccount(arg0, arg1 interface{} return mr.mock.ctrl.RecordCallWithMethodType(mr.mock, "SetModuleAccount", reflect.TypeOf((*MockAccountKeeper)(nil).SetModuleAccount), arg0, arg1) } +// StringToBytes mocks base method. +func (m *MockAccountKeeper) StringToBytes(text string) ([]byte, error) { + m.ctrl.T.Helper() + ret := m.ctrl.Call(m, "StringToBytes", text) + ret0, _ := ret[0].([]byte) + ret1, _ := ret[1].(error) + return ret0, ret1 +} + +// StringToBytes indicates an expected call of StringToBytes. +func (mr *MockAccountKeeperMockRecorder) StringToBytes(text interface{}) *gomock.Call { + mr.mock.ctrl.T.Helper() + return mr.mock.ctrl.RecordCallWithMethodType(mr.mock, "StringToBytes", reflect.TypeOf((*MockAccountKeeper)(nil).StringToBytes), text) +} + // MockBankKeeper is a mock of BankKeeper interface. type MockBankKeeper struct { ctrl *gomock.Controller diff --git a/x/gov/types/events.go b/x/gov/types/events.go index 179f51e33a83..c7f895234f0b 100644 --- a/x/gov/types/events.go +++ b/x/gov/types/events.go @@ -7,7 +7,6 @@ const ( EventTypeProposalVote = "proposal_vote" EventTypeInactiveProposal = "inactive_proposal" EventTypeActiveProposal = "active_proposal" - EventTypeSignalProposal = "signal_proposal" EventTypeCancelProposal = "cancel_proposal" AttributeKeyProposalResult = "proposal_result" @@ -15,6 +14,7 @@ const ( AttributeKeyProposalID = "proposal_id" AttributeKeyProposalMessages = "proposal_messages" // Msg type_urls in the proposal AttributeKeyVotingPeriodStart = "voting_period_start" + AttributeKeyProposalLog = "proposal_log" // log of proposal execution AttributeValueProposalDropped = "proposal_dropped" // didn't meet min deposit AttributeValueProposalPassed = "proposal_passed" // met vote quorum AttributeValueProposalRejected = "proposal_rejected" // didn't meet vote quorum diff --git a/x/gov/types/expected_keepers.go b/x/gov/types/expected_keepers.go index 94b35219da7e..2ffc4a135ffa 100644 --- a/x/gov/types/expected_keepers.go +++ b/x/gov/types/expected_keepers.go @@ -1,6 +1,9 @@ package types import ( + "context" + + addresscodec "cosmossdk.io/core/address" "cosmossdk.io/math" sdk "github.com/cosmos/cosmos-sdk/types" @@ -34,13 +37,15 @@ type DistributionKeeper interface { // AccountKeeper defines the expected account keeper (noalias) type AccountKeeper interface { - GetAccount(ctx sdk.Context, addr sdk.AccAddress) sdk.AccountI + addresscodec.Codec + + GetAccount(ctx context.Context, addr sdk.AccAddress) sdk.AccountI GetModuleAddress(name string) sdk.AccAddress - GetModuleAccount(ctx sdk.Context, name string) sdk.ModuleAccountI + GetModuleAccount(ctx context.Context, name string) sdk.ModuleAccountI // TODO remove with genesis 2-phases refactor https://github.com/cosmos/cosmos-sdk/issues/2862 - SetModuleAccount(sdk.Context, sdk.ModuleAccountI) + SetModuleAccount(context.Context, sdk.ModuleAccountI) } // BankKeeper defines the expected interface needed to retrieve account balances. diff --git a/x/gov/types/v1/deposit.go b/x/gov/types/v1/deposit.go index 03c02ba47176..2ddbd8c221ac 100644 --- a/x/gov/types/v1/deposit.go +++ b/x/gov/types/v1/deposit.go @@ -7,8 +7,6 @@ import ( ) // NewDeposit creates a new Deposit instance -// -//nolint:interfacer func NewDeposit(proposalID uint64, depositor sdk.AccAddress, amount sdk.Coins) Deposit { return Deposit{proposalID, depositor.String(), amount} } diff --git a/x/gov/types/v1/genesis_test.go b/x/gov/types/v1/genesis_test.go index 1d74e2ded392..682131769a58 100644 --- a/x/gov/types/v1/genesis_test.go +++ b/x/gov/types/v1/genesis_test.go @@ -3,6 +3,8 @@ package v1_test import ( "testing" + sdkmath "cosmossdk.io/math" + sdk "github.com/cosmos/cosmos-sdk/types" v1 "github.com/cosmos/cosmos-sdk/x/gov/types/v1" "github.com/stretchr/testify/require" @@ -43,7 +45,7 @@ func TestValidateGenesis(t *testing.T) { params1 := params params1.MinDeposit = sdk.Coins{{ Denom: sdk.DefaultBondDenom, - Amount: sdk.NewInt(-100), + Amount: sdkmath.NewInt(-100), }} return v1.NewGenesisState(0, params1) diff --git a/x/gov/types/v1/msgs.go b/x/gov/types/v1/msgs.go index ac10428e23b2..7ba8e69a97e6 100644 --- a/x/gov/types/v1/msgs.go +++ b/x/gov/types/v1/msgs.go @@ -1,18 +1,11 @@ package v1 import ( - "fmt" - - errorsmod "cosmossdk.io/errors" - "cosmossdk.io/math" - codectypes "github.com/cosmos/cosmos-sdk/codec/types" sdk "github.com/cosmos/cosmos-sdk/types" - sdkerrors "github.com/cosmos/cosmos-sdk/types/errors" sdktx "github.com/cosmos/cosmos-sdk/types/tx" "github.com/cosmos/cosmos-sdk/x/auth/migrations/legacytx" "github.com/cosmos/cosmos-sdk/x/gov/codec" - "github.com/cosmos/cosmos-sdk/x/gov/types" "github.com/cosmos/cosmos-sdk/x/gov/types/v1beta1" ) @@ -23,8 +16,6 @@ var ( ) // NewMsgSubmitProposal creates a new MsgSubmitProposal. -// -//nolint:interfacer func NewMsgSubmitProposal( messages []sdk.Msg, initialDeposit sdk.Coins, @@ -67,51 +58,9 @@ func (m *MsgSubmitProposal) SetMsgs(msgs []sdk.Msg) error { return nil } -// ValidateBasic implements the sdk.Msg interface. -func (m MsgSubmitProposal) ValidateBasic() error { - if m.Title == "" { - return errorsmod.Wrap(sdkerrors.ErrInvalidRequest, "proposal title cannot be empty") - } - if m.Summary == "" { - return errorsmod.Wrap(sdkerrors.ErrInvalidRequest, "proposal summary cannot be empty") - } - - if _, err := sdk.AccAddressFromBech32(m.Proposer); err != nil { - return sdkerrors.ErrInvalidAddress.Wrapf("invalid proposer address: %s", err) - } - - deposit := sdk.NewCoins(m.InitialDeposit...) - if !deposit.IsValid() { - return errorsmod.Wrap(sdkerrors.ErrInvalidCoins, deposit.String()) - } - - if deposit.IsAnyNegative() { - return errorsmod.Wrap(sdkerrors.ErrInvalidCoins, deposit.String()) - } - - // Check that either metadata or Msgs length is non nil. - if len(m.Messages) == 0 && len(m.Metadata) == 0 { - return errorsmod.Wrap(types.ErrNoProposalMsgs, "either metadata or Msgs length must be non-nil") - } - - msgs, err := m.GetMsgs() - if err != nil { - return err - } - - for idx, msg := range msgs { - if err := msg.ValidateBasic(); err != nil { - return errorsmod.Wrap(types.ErrInvalidProposalMsg, - fmt.Sprintf("msg: %d, err: %s", idx, err.Error())) - } - } - - return nil -} - // GetSignBytes returns the message bytes to sign over. func (m MsgSubmitProposal) GetSignBytes() []byte { - bz := codec.ModuleCdc.MustMarshalJSON(&m) + bz := codec.Amino.MustMarshalJSON(&m) return sdk.MustSortJSON(bz) } @@ -127,31 +76,13 @@ func (m MsgSubmitProposal) UnpackInterfaces(unpacker codectypes.AnyUnpacker) err } // NewMsgDeposit creates a new MsgDeposit instance -// -//nolint:interfacer func NewMsgDeposit(depositor sdk.AccAddress, proposalID uint64, amount sdk.Coins) *MsgDeposit { return &MsgDeposit{proposalID, depositor.String(), amount} } -// ValidateBasic implements the sdk.Msg interface. -func (msg MsgDeposit) ValidateBasic() error { - if _, err := sdk.AccAddressFromBech32(msg.Depositor); err != nil { - return sdkerrors.ErrInvalidAddress.Wrapf("invalid depositor address: %s", err) - } - amount := sdk.NewCoins(msg.Amount...) - if !amount.IsValid() { - return errorsmod.Wrap(sdkerrors.ErrInvalidCoins, amount.String()) - } - if amount.IsAnyNegative() { - return errorsmod.Wrap(sdkerrors.ErrInvalidCoins, amount.String()) - } - - return nil -} - // GetSignBytes returns the message bytes to sign over. func (msg MsgDeposit) GetSignBytes() []byte { - bz := codec.ModuleCdc.MustMarshalJSON(&msg) + bz := codec.Amino.MustMarshalJSON(&msg) return sdk.MustSortJSON(bz) } @@ -162,27 +93,13 @@ func (msg MsgDeposit) GetSigners() []sdk.AccAddress { } // NewMsgVote creates a message to cast a vote on an active proposal -// -//nolint:interfacer func NewMsgVote(voter sdk.AccAddress, proposalID uint64, option VoteOption, metadata string) *MsgVote { return &MsgVote{proposalID, voter.String(), option, metadata} } -// ValidateBasic implements the sdk.Msg interface. -func (msg MsgVote) ValidateBasic() error { - if _, err := sdk.AccAddressFromBech32(msg.Voter); err != nil { - return sdkerrors.ErrInvalidAddress.Wrapf("invalid voter address: %s", err) - } - if !ValidVoteOption(msg.Option) { - return errorsmod.Wrap(types.ErrInvalidVote, msg.Option.String()) - } - - return nil -} - // GetSignBytes returns the message bytes to sign over. func (msg MsgVote) GetSignBytes() []byte { - bz := codec.ModuleCdc.MustMarshalJSON(&msg) + bz := codec.Amino.MustMarshalJSON(&msg) return sdk.MustSortJSON(bz) } @@ -193,52 +110,13 @@ func (msg MsgVote) GetSigners() []sdk.AccAddress { } // NewMsgVoteWeighted creates a message to cast a vote on an active proposal -// -//nolint:interfacer func NewMsgVoteWeighted(voter sdk.AccAddress, proposalID uint64, options WeightedVoteOptions, metadata string) *MsgVoteWeighted { return &MsgVoteWeighted{proposalID, voter.String(), options, metadata} } -// ValidateBasic implements the sdk.Msg interface. -func (msg MsgVoteWeighted) ValidateBasic() error { - if _, err := sdk.AccAddressFromBech32(msg.Voter); err != nil { - return sdkerrors.ErrInvalidAddress.Wrapf("invalid voter address: %s", err) - } - if len(msg.Options) == 0 { - return errorsmod.Wrap(sdkerrors.ErrInvalidRequest, WeightedVoteOptions(msg.Options).String()) - } - - totalWeight := math.LegacyNewDec(0) - usedOptions := make(map[VoteOption]bool) - for _, option := range msg.Options { - if !option.IsValid() { - return errorsmod.Wrap(types.ErrInvalidVote, option.String()) - } - weight, err := sdk.NewDecFromStr(option.Weight) - if err != nil { - return errorsmod.Wrapf(types.ErrInvalidVote, "Invalid weight: %s", err) - } - totalWeight = totalWeight.Add(weight) - if usedOptions[option.Option] { - return errorsmod.Wrap(types.ErrInvalidVote, "Duplicated vote option") - } - usedOptions[option.Option] = true - } - - if totalWeight.GT(math.LegacyNewDec(1)) { - return errorsmod.Wrap(types.ErrInvalidVote, "Total weight overflow 1.00") - } - - if totalWeight.LT(math.LegacyNewDec(1)) { - return errorsmod.Wrap(types.ErrInvalidVote, "Total weight lower than 1.00") - } - - return nil -} - // GetSignBytes returns the message bytes to sign over. func (msg MsgVoteWeighted) GetSignBytes() []byte { - bz := codec.ModuleCdc.MustMarshalJSON(&msg) + bz := codec.Amino.MustMarshalJSON(&msg) return sdk.MustSortJSON(bz) } @@ -248,9 +126,7 @@ func (msg MsgVoteWeighted) GetSigners() []sdk.AccAddress { return []sdk.AccAddress{voter} } -// NewMsgExecLegacyContent creates a new MsgExecLegacyContent instance -// -//nolint:interfacer +// NewMsgExecLegacyContent creates a new MsgExecLegacyContent instance. func NewMsgExecLegacyContent(content *codectypes.Any, authority string) *MsgExecLegacyContent { return &MsgExecLegacyContent{ Content: content, @@ -260,7 +136,7 @@ func NewMsgExecLegacyContent(content *codectypes.Any, authority string) *MsgExec // GetSignBytes returns the message bytes to sign over. func (c MsgExecLegacyContent) GetSignBytes() []byte { - bz := codec.ModuleCdc.MustMarshalJSON(&c) + bz := codec.Amino.MustMarshalJSON(&c) return sdk.MustSortJSON(bz) } @@ -286,18 +162,9 @@ func (c MsgExecLegacyContent) UnpackInterfaces(unpacker codectypes.AnyUnpacker) return unpacker.UnpackAny(c.Content, &content) } -// ValidateBasic implements the sdk.Msg interface. -func (msg MsgUpdateParams) ValidateBasic() error { - if _, err := sdk.AccAddressFromBech32(msg.Authority); err != nil { - return sdkerrors.ErrInvalidAddress.Wrapf("invalid authority address: %s", err) - } - - return msg.Params.ValidateBasic() -} - // GetSignBytes returns the message bytes to sign over. func (msg MsgUpdateParams) GetSignBytes() []byte { - bz := codec.ModuleCdc.MustMarshalJSON(&msg) + bz := codec.Amino.MustMarshalJSON(&msg) return sdk.MustSortJSON(bz) } @@ -307,9 +174,7 @@ func (msg MsgUpdateParams) GetSigners() []sdk.AccAddress { return []sdk.AccAddress{authority} } -// NewMsgCancelProposal creates a new MsgCancelProposal instance -// -//nolint:interfacer +// NewMsgCancelProposal creates a new MsgCancelProposal instance. func NewMsgCancelProposal(proposalID uint64, proposer string) *MsgCancelProposal { return &MsgCancelProposal{ ProposalId: proposalID, @@ -317,18 +182,9 @@ func NewMsgCancelProposal(proposalID uint64, proposer string) *MsgCancelProposal } } -// ValidateBasic implements Msg -func (msg MsgCancelProposal) ValidateBasic() error { - if _, err := sdk.AccAddressFromBech32(msg.Proposer); err != nil { - return sdkerrors.ErrInvalidAddress.Wrapf("invalid proposer address: %s", err) - } - - return nil -} - // GetSignBytes implements Msg func (msg MsgCancelProposal) GetSignBytes() []byte { - bz := codec.ModuleCdc.MustMarshalJSON(&msg) + bz := codec.Amino.MustMarshalJSON(&msg) return sdk.MustSortJSON(bz) } diff --git a/x/gov/types/v1/msgs_test.go b/x/gov/types/v1/msgs_test.go index 2c721ad6404a..456e7429a573 100644 --- a/x/gov/types/v1/msgs_test.go +++ b/x/gov/types/v1/msgs_test.go @@ -4,18 +4,15 @@ import ( "fmt" "testing" - "cosmossdk.io/math" "github.com/stretchr/testify/require" sdk "github.com/cosmos/cosmos-sdk/types" banktypes "github.com/cosmos/cosmos-sdk/x/bank/types" v1 "github.com/cosmos/cosmos-sdk/x/gov/types/v1" - "github.com/cosmos/cosmos-sdk/x/gov/types/v1beta1" ) var ( coinsPos = sdk.NewCoins(sdk.NewInt64Coin(sdk.DefaultBondDenom, 1000)) - coinsZero = sdk.NewCoins() coinsMulti = sdk.NewCoins(sdk.NewInt64Coin(sdk.DefaultBondDenom, 1000), sdk.NewInt64Coin("foo", 10000)) addrs = []sdk.AccAddress{ sdk.AccAddress("test1"), @@ -36,142 +33,6 @@ func TestMsgDepositGetSignBytes(t *testing.T) { require.Equal(t, expected, string(res)) } -// test ValidateBasic for MsgDeposit -func TestMsgDeposit(t *testing.T) { - tests := []struct { - proposalID uint64 - depositorAddr sdk.AccAddress - depositAmount sdk.Coins - expectPass bool - }{ - {0, addrs[0], coinsPos, true}, - {1, sdk.AccAddress{}, coinsPos, false}, - {1, addrs[0], coinsZero, true}, - {1, addrs[0], coinsMulti, true}, - } - - for i, tc := range tests { - msg := v1.NewMsgDeposit(tc.depositorAddr, tc.proposalID, tc.depositAmount) - if tc.expectPass { - require.NoError(t, msg.ValidateBasic(), "test: %v", i) - } else { - require.Error(t, msg.ValidateBasic(), "test: %v", i) - } - } -} - -// test ValidateBasic for MsgVote -func TestMsgVote(t *testing.T) { - metadata := "metadata" //nolint:goconst - tests := []struct { - proposalID uint64 - voterAddr sdk.AccAddress - option v1.VoteOption - metadata string - expectPass bool - }{ - {0, addrs[0], v1.OptionYes, metadata, true}, - {0, sdk.AccAddress{}, v1.OptionYes, "", false}, - {0, addrs[0], v1.OptionNo, metadata, true}, - {0, addrs[0], v1.OptionNoWithVeto, "", true}, - {0, addrs[0], v1.OptionAbstain, "", true}, - {0, addrs[0], v1.VoteOption(0x13), "", false}, - } - - for i, tc := range tests { - msg := v1.NewMsgVote(tc.voterAddr, tc.proposalID, tc.option, tc.metadata) - if tc.expectPass { - require.Nil(t, msg.ValidateBasic(), "test: %v", i) - } else { - require.NotNil(t, msg.ValidateBasic(), "test: %v", i) - } - } -} - -// test ValidateBasic for MsgVoteWeighted -func TestMsgVoteWeighted(t *testing.T) { - metadata := "metadata" - tests := []struct { - proposalID uint64 - voterAddr sdk.AccAddress - options v1.WeightedVoteOptions - metadata string - expectPass bool - }{ - {0, addrs[0], v1.NewNonSplitVoteOption(v1.OptionYes), metadata, true}, - {0, sdk.AccAddress{}, v1.NewNonSplitVoteOption(v1.OptionYes), "", false}, - {0, addrs[0], v1.NewNonSplitVoteOption(v1.OptionNo), "", true}, - {0, addrs[0], v1.NewNonSplitVoteOption(v1.OptionNoWithVeto), "", true}, - {0, addrs[0], v1.NewNonSplitVoteOption(v1.OptionAbstain), "", true}, - {0, addrs[0], v1.WeightedVoteOptions{ // weight sum > 1 - v1.NewWeightedVoteOption(v1.OptionYes, math.LegacyNewDec(1)), - v1.NewWeightedVoteOption(v1.OptionAbstain, math.LegacyNewDec(1)), - }, "", false}, - {0, addrs[0], v1.WeightedVoteOptions{ // duplicate option - v1.NewWeightedVoteOption(v1.OptionYes, sdk.NewDecWithPrec(5, 1)), - v1.NewWeightedVoteOption(v1.OptionYes, sdk.NewDecWithPrec(5, 1)), - }, "", false}, - {0, addrs[0], v1.WeightedVoteOptions{ // zero weight - v1.NewWeightedVoteOption(v1.OptionYes, math.LegacyNewDec(0)), - }, "", false}, - {0, addrs[0], v1.WeightedVoteOptions{ // negative weight - v1.NewWeightedVoteOption(v1.OptionYes, math.LegacyNewDec(-1)), - }, "", false}, - {0, addrs[0], v1.WeightedVoteOptions{}, "", false}, - {0, addrs[0], v1.NewNonSplitVoteOption(v1.VoteOption(0x13)), "", false}, - {0, addrs[0], v1.WeightedVoteOptions{ // weight sum <1 - v1.NewWeightedVoteOption(v1.OptionYes, sdk.NewDecWithPrec(5, 1)), - }, "", false}, - } - - for i, tc := range tests { - msg := v1.NewMsgVoteWeighted(tc.voterAddr, tc.proposalID, tc.options, tc.metadata) - if tc.expectPass { - require.Nil(t, msg.ValidateBasic(), "test: %v", i) - } else { - require.NotNil(t, msg.ValidateBasic(), "test: %v", i) - } - } -} - -func TestMsgSubmitProposal_ValidateBasic(t *testing.T) { - metadata := "metadata" - // Valid msg - msg1, err := v1.NewLegacyContent(v1beta1.NewTextProposal("Title", "description"), addrs[0].String()) - require.NoError(t, err) - // Invalid msg - msg2, err := v1.NewLegacyContent(v1beta1.NewTextProposal("Title", "description"), "foo") - require.NoError(t, err) - - tests := []struct { - name string - proposer string - initialDeposit sdk.Coins - messages []sdk.Msg - metadata, title, summary string - expedited bool - expErr bool - }{ - {"invalid addr", "", coinsPos, []sdk.Msg{msg1}, metadata, "Title", "Summary", false, true}, - {"empty msgs and metadata", addrs[0].String(), coinsPos, nil, "", "Title", "Summary", false, true}, - {"empty title and summary", addrs[0].String(), coinsPos, nil, "", "", "", false, true}, - {"invalid msg", addrs[0].String(), coinsPos, []sdk.Msg{msg1, msg2}, metadata, "Title", "Summary", false, true}, - {"valid with no Msg", addrs[0].String(), coinsPos, nil, metadata, "Title", "Summary", false, false}, - {"valid with no metadata", addrs[0].String(), coinsPos, []sdk.Msg{msg1}, "", "Title", "Summary", false, false}, - {"valid with everything", addrs[0].String(), coinsPos, []sdk.Msg{msg1}, metadata, "Title", "Summary", true, false}, - } - - for _, tc := range tests { - msg, err := v1.NewMsgSubmitProposal(tc.messages, tc.initialDeposit, tc.proposer, tc.metadata, tc.title, tc.summary, tc.expedited) - require.NoError(t, err) - if tc.expErr { - require.Error(t, msg.ValidateBasic(), "test: %s", tc.name) - } else { - require.NoError(t, msg.ValidateBasic(), "test: %s", tc.name) - } - } -} - // this tests that Amino JSON MsgSubmitProposal.GetSignBytes() still works with Content as Any using the ModuleCdc func TestMsgSubmitProposal_GetSignBytes(t *testing.T) { testcases := []struct { diff --git a/x/gov/types/v1/params.go b/x/gov/types/v1/params.go index fbf2faef16d5..5633ebb4c59c 100644 --- a/x/gov/types/v1/params.go +++ b/x/gov/types/v1/params.go @@ -4,7 +4,7 @@ import ( "fmt" "time" - "cosmossdk.io/math" + sdkmath "cosmossdk.io/math" sdk "github.com/cosmos/cosmos-sdk/types" ) @@ -18,14 +18,14 @@ const ( // Default governance params var ( - DefaultMinDepositTokens = sdk.NewInt(10000000) - DefaultMinExpeditedDepositTokens = DefaultMinDepositTokens.Mul(math.NewInt(DefaultMinExpeditedDepositTokensRatio)) - DefaultQuorum = sdk.NewDecWithPrec(334, 3) - DefaultThreshold = sdk.NewDecWithPrec(5, 1) - DefaultExpeditedThreshold = sdk.NewDecWithPrec(667, 3) - DefaultVetoThreshold = sdk.NewDecWithPrec(334, 3) - DefaultMinInitialDepositRatio = sdk.ZeroDec() - DefaultProposalCancelRatio = sdk.MustNewDecFromStr("0.5") + DefaultMinDepositTokens = sdkmath.NewInt(10000000) + DefaultMinExpeditedDepositTokens = DefaultMinDepositTokens.Mul(sdkmath.NewInt(DefaultMinExpeditedDepositTokensRatio)) + DefaultQuorum = sdkmath.LegacyNewDecWithPrec(334, 3) + DefaultThreshold = sdkmath.LegacyNewDecWithPrec(5, 1) + DefaultExpeditedThreshold = sdkmath.LegacyNewDecWithPrec(667, 3) + DefaultVetoThreshold = sdkmath.LegacyNewDecWithPrec(334, 3) + DefaultMinInitialDepositRatio = sdkmath.LegacyZeroDec() + DefaultProposalCancelRatio = sdkmath.LegacyMustNewDecFromStr("0.5") DefaultProposalCancelDestAddress = "" DefaultBurnProposalPrevote = false // set to false to replicate behavior of when this change was made (0.47) DefaultBurnVoteQuorom = false // set to false to replicate behavior of when this change was made (0.47) @@ -122,50 +122,50 @@ func (p Params) ValidateBasic() error { return fmt.Errorf("maximum deposit period must be positive: %d", p.MaxDepositPeriod) } - quorum, err := sdk.NewDecFromStr(p.Quorum) + quorum, err := sdkmath.LegacyNewDecFromStr(p.Quorum) if err != nil { return fmt.Errorf("invalid quorum string: %w", err) } if quorum.IsNegative() { return fmt.Errorf("quorom cannot be negative: %s", quorum) } - if quorum.GT(math.LegacyOneDec()) { + if quorum.GT(sdkmath.LegacyOneDec()) { return fmt.Errorf("quorom too large: %s", p.Quorum) } - threshold, err := sdk.NewDecFromStr(p.Threshold) + threshold, err := sdkmath.LegacyNewDecFromStr(p.Threshold) if err != nil { return fmt.Errorf("invalid threshold string: %w", err) } if !threshold.IsPositive() { return fmt.Errorf("vote threshold must be positive: %s", threshold) } - if threshold.GT(math.LegacyOneDec()) { + if threshold.GT(sdkmath.LegacyOneDec()) { return fmt.Errorf("vote threshold too large: %s", threshold) } - expeditedThreshold, err := sdk.NewDecFromStr(p.ExpeditedThreshold) + expeditedThreshold, err := sdkmath.LegacyNewDecFromStr(p.ExpeditedThreshold) if err != nil { return fmt.Errorf("invalid expedited threshold string: %w", err) } if !threshold.IsPositive() { return fmt.Errorf("expedited vote threshold must be positive: %s", threshold) } - if threshold.GT(math.LegacyOneDec()) { + if threshold.GT(sdkmath.LegacyOneDec()) { return fmt.Errorf("expedited vote threshold too large: %s", threshold) } if expeditedThreshold.LTE(threshold) { return fmt.Errorf("expedited vote threshold %s, must be greater than the regular threshold %s", expeditedThreshold, threshold) } - vetoThreshold, err := sdk.NewDecFromStr(p.VetoThreshold) + vetoThreshold, err := sdkmath.LegacyNewDecFromStr(p.VetoThreshold) if err != nil { return fmt.Errorf("invalid vetoThreshold string: %w", err) } if !vetoThreshold.IsPositive() { return fmt.Errorf("veto threshold must be positive: %s", vetoThreshold) } - if vetoThreshold.GT(math.LegacyOneDec()) { + if vetoThreshold.GT(sdkmath.LegacyOneDec()) { return fmt.Errorf("veto threshold too large: %s", vetoThreshold) } @@ -186,25 +186,25 @@ func (p Params) ValidateBasic() error { return fmt.Errorf("expedited voting period %s must be strictly less that the regular voting period %s", p.ExpeditedVotingPeriod, p.VotingPeriod) } - minInitialDepositRatio, err := sdk.NewDecFromStr(p.MinInitialDepositRatio) + minInitialDepositRatio, err := sdkmath.LegacyNewDecFromStr(p.MinInitialDepositRatio) if err != nil { return fmt.Errorf("invalid mininum initial deposit ratio of proposal: %w", err) } if minInitialDepositRatio.IsNegative() { return fmt.Errorf("mininum initial deposit ratio of proposal must be positive: %s", minInitialDepositRatio) } - if minInitialDepositRatio.GT(math.LegacyOneDec()) { + if minInitialDepositRatio.GT(sdkmath.LegacyOneDec()) { return fmt.Errorf("mininum initial deposit ratio of proposal is too large: %s", minInitialDepositRatio) } - proposalCancelRate, err := sdk.NewDecFromStr(p.ProposalCancelRatio) + proposalCancelRate, err := sdkmath.LegacyNewDecFromStr(p.ProposalCancelRatio) if err != nil { return fmt.Errorf("invalid burn rate of cancel proposal: %w", err) } if proposalCancelRate.IsNegative() { return fmt.Errorf("burn rate of cancel proposal must be positive: %s", proposalCancelRate) } - if proposalCancelRate.GT(math.LegacyOneDec()) { + if proposalCancelRate.GT(sdkmath.LegacyOneDec()) { return fmt.Errorf("burn rate of cancel proposal is too large: %s", proposalCancelRate) } diff --git a/x/gov/types/v1/params_legacy.go b/x/gov/types/v1/params_legacy.go index 38fb6b84ff10..7fbea6917a1e 100644 --- a/x/gov/types/v1/params_legacy.go +++ b/x/gov/types/v1/params_legacy.go @@ -47,7 +47,7 @@ func validateTallyParams(i interface{}) error { return fmt.Errorf("invalid parameter type: %T", i) } - quorum, err := sdk.NewDecFromStr(v.Quorum) + quorum, err := math.LegacyNewDecFromStr(v.Quorum) if err != nil { return fmt.Errorf("invalid quorum string: %w", err) } @@ -58,7 +58,7 @@ func validateTallyParams(i interface{}) error { return fmt.Errorf("quorom too large: %s", v) } - threshold, err := sdk.NewDecFromStr(v.Threshold) + threshold, err := math.LegacyNewDecFromStr(v.Threshold) if err != nil { return fmt.Errorf("invalid threshold string: %w", err) } @@ -69,7 +69,7 @@ func validateTallyParams(i interface{}) error { return fmt.Errorf("vote threshold too large: %s", v) } - vetoThreshold, err := sdk.NewDecFromStr(v.VetoThreshold) + vetoThreshold, err := math.LegacyNewDecFromStr(v.VetoThreshold) if err != nil { return fmt.Errorf("invalid vetoThreshold string: %w", err) } diff --git a/x/gov/types/v1/vote.go b/x/gov/types/v1/vote.go index cb1f9066fc4a..fe481eba9294 100644 --- a/x/gov/types/v1/vote.go +++ b/x/gov/types/v1/vote.go @@ -18,8 +18,6 @@ const ( ) // NewVote creates a new Vote instance -// -//nolint:interfacer func NewVote(proposalID uint64, voter sdk.AccAddress, options WeightedVoteOptions, metadata string) Vote { return Vote{ProposalId: proposalID, Voter: voter.String(), Options: options, Metadata: metadata} } @@ -65,7 +63,7 @@ func NewWeightedVoteOption(option VoteOption, weight sdk.Dec) *WeightedVoteOptio // IsValid returns true if the sub vote is valid and false otherwise. func (w *WeightedVoteOption) IsValid() bool { - weight, err := sdk.NewDecFromStr(w.Weight) + weight, err := math.LegacyNewDecFromStr(w.Weight) if err != nil { return false } @@ -125,7 +123,7 @@ func WeightedVoteOptionsFromString(str string) (WeightedVoteOptions, error) { if len(fields) < 2 { return options, fmt.Errorf("weight field does not exist for %s option", fields[0]) } - weight, err := sdk.NewDecFromStr(fields[1]) + weight, err := math.LegacyNewDecFromStr(fields[1]) if err != nil { return options, err } diff --git a/x/gov/types/v1beta1/deposit.go b/x/gov/types/v1beta1/deposit.go index ee05ae7a09b3..c9945b420990 100644 --- a/x/gov/types/v1beta1/deposit.go +++ b/x/gov/types/v1beta1/deposit.go @@ -7,8 +7,6 @@ import ( ) // NewDeposit creates a new Deposit instance -// -//nolint:interfacer func NewDeposit(proposalID uint64, depositor sdk.AccAddress, amount sdk.Coins) Deposit { return Deposit{proposalID, depositor.String(), amount} } diff --git a/x/gov/types/v1beta1/msgs.go b/x/gov/types/v1beta1/msgs.go index c02b93fd9bd7..0cc741fd3bc5 100644 --- a/x/gov/types/v1beta1/msgs.go +++ b/x/gov/types/v1beta1/msgs.go @@ -3,17 +3,12 @@ package v1beta1 import ( "fmt" - "cosmossdk.io/math" "github.com/cosmos/gogoproto/proto" - errorsmod "cosmossdk.io/errors" - codectypes "github.com/cosmos/cosmos-sdk/codec/types" sdk "github.com/cosmos/cosmos-sdk/types" - sdkerrors "github.com/cosmos/cosmos-sdk/types/errors" "github.com/cosmos/cosmos-sdk/x/auth/migrations/legacytx" "github.com/cosmos/cosmos-sdk/x/gov/codec" - "github.com/cosmos/cosmos-sdk/x/gov/types" ) // Governance message types and routes @@ -32,8 +27,6 @@ var ( ) // NewMsgSubmitProposal creates a new MsgSubmitProposal. -// -//nolint:interfacer func NewMsgSubmitProposal(content Content, initialDeposit sdk.Coins, proposer sdk.AccAddress) (*MsgSubmitProposal, error) { m := &MsgSubmitProposal{ InitialDeposit: initialDeposit, @@ -88,35 +81,9 @@ func (m *MsgSubmitProposal) SetContent(content Content) error { return nil } -// ValidateBasic implements the sdk.Msg interface. -func (m MsgSubmitProposal) ValidateBasic() error { - if _, err := sdk.AccAddressFromBech32(m.Proposer); err != nil { - return sdkerrors.ErrInvalidAddress.Wrapf("invalid proposer address: %s", err) - } - if !m.InitialDeposit.IsValid() { - return errorsmod.Wrap(sdkerrors.ErrInvalidCoins, m.InitialDeposit.String()) - } - if m.InitialDeposit.IsAnyNegative() { - return errorsmod.Wrap(sdkerrors.ErrInvalidCoins, m.InitialDeposit.String()) - } - - content := m.GetContent() - if content == nil { - return errorsmod.Wrap(types.ErrInvalidProposalContent, "missing content") - } - if !IsValidProposalType(content.ProposalType()) { - return errorsmod.Wrap(types.ErrInvalidProposalType, content.ProposalType()) - } - if err := content.ValidateBasic(); err != nil { - return err - } - - return nil -} - // GetSignBytes returns the message bytes to sign over. func (m MsgSubmitProposal) GetSignBytes() []byte { - bz := codec.ModuleCdc.MustMarshalJSON(&m) + bz := codec.Amino.MustMarshalJSON(&m) return sdk.MustSortJSON(bz) } @@ -133,30 +100,13 @@ func (m MsgSubmitProposal) UnpackInterfaces(unpacker codectypes.AnyUnpacker) err } // NewMsgDeposit creates a new MsgDeposit instance -// -//nolint:interfacer func NewMsgDeposit(depositor sdk.AccAddress, proposalID uint64, amount sdk.Coins) *MsgDeposit { return &MsgDeposit{proposalID, depositor.String(), amount} } -// ValidateBasic implements the sdk.Msg interface. -func (msg MsgDeposit) ValidateBasic() error { - if _, err := sdk.AccAddressFromBech32(msg.Depositor); err != nil { - return sdkerrors.ErrInvalidAddress.Wrapf("invalid depositor address: %s", err) - } - if !msg.Amount.IsValid() { - return errorsmod.Wrap(sdkerrors.ErrInvalidCoins, msg.Amount.String()) - } - if msg.Amount.IsAnyNegative() { - return errorsmod.Wrap(sdkerrors.ErrInvalidCoins, msg.Amount.String()) - } - - return nil -} - // GetSignBytes returns the message bytes to sign over. func (msg MsgDeposit) GetSignBytes() []byte { - bz := codec.ModuleCdc.MustMarshalJSON(&msg) + bz := codec.Amino.MustMarshalJSON(&msg) return sdk.MustSortJSON(bz) } @@ -167,27 +117,13 @@ func (msg MsgDeposit) GetSigners() []sdk.AccAddress { } // NewMsgVote creates a message to cast a vote on an active proposal -// -//nolint:interfacer func NewMsgVote(voter sdk.AccAddress, proposalID uint64, option VoteOption) *MsgVote { return &MsgVote{proposalID, voter.String(), option} } -// ValidateBasic implements the sdk.Msg interface. -func (msg MsgVote) ValidateBasic() error { - if _, err := sdk.AccAddressFromBech32(msg.Voter); err != nil { - return sdkerrors.ErrInvalidAddress.Wrapf("invalid voter address: %s", err) - } - if !ValidVoteOption(msg.Option) { - return errorsmod.Wrap(types.ErrInvalidVote, msg.Option.String()) - } - - return nil -} - // GetSignBytes returns the message bytes to sign over. func (msg MsgVote) GetSignBytes() []byte { - bz := codec.ModuleCdc.MustMarshalJSON(&msg) + bz := codec.Amino.MustMarshalJSON(&msg) return sdk.MustSortJSON(bz) } @@ -197,49 +133,14 @@ func (msg MsgVote) GetSigners() []sdk.AccAddress { return []sdk.AccAddress{voter} } -// NewMsgVoteWeighted creates a message to cast a vote on an active proposal -// -//nolint:interfacer +// NewMsgVoteWeighted creates a message to cast a vote on an active proposal. func NewMsgVoteWeighted(voter sdk.AccAddress, proposalID uint64, options WeightedVoteOptions) *MsgVoteWeighted { return &MsgVoteWeighted{proposalID, voter.String(), options} } -// ValidateBasic implements the sdk.Msg interface. -func (msg MsgVoteWeighted) ValidateBasic() error { - if _, err := sdk.AccAddressFromBech32(msg.Voter); err != nil { - return sdkerrors.ErrInvalidAddress.Wrapf("invalid voter address: %s", err) - } - if len(msg.Options) == 0 { - return errorsmod.Wrap(sdkerrors.ErrInvalidRequest, WeightedVoteOptions(msg.Options).String()) - } - - totalWeight := math.LegacyNewDec(0) - usedOptions := make(map[VoteOption]bool) - for _, option := range msg.Options { - if !ValidWeightedVoteOption(option) { - return errorsmod.Wrap(types.ErrInvalidVote, option.String()) - } - totalWeight = totalWeight.Add(option.Weight) - if usedOptions[option.Option] { - return errorsmod.Wrap(types.ErrInvalidVote, "Duplicated vote option") - } - usedOptions[option.Option] = true - } - - if totalWeight.GT(math.LegacyNewDec(1)) { - return errorsmod.Wrap(types.ErrInvalidVote, "Total weight overflow 1.00") - } - - if totalWeight.LT(math.LegacyNewDec(1)) { - return errorsmod.Wrap(types.ErrInvalidVote, "Total weight lower than 1.00") - } - - return nil -} - // GetSignBytes returns the message bytes to sign over. func (msg MsgVoteWeighted) GetSignBytes() []byte { - bz := codec.ModuleCdc.MustMarshalJSON(&msg) + bz := codec.Amino.MustMarshalJSON(&msg) return sdk.MustSortJSON(bz) } diff --git a/x/gov/types/v1beta1/msgs_test.go b/x/gov/types/v1beta1/msgs_test.go index 8dbdbc8c470e..d041ccb834cc 100644 --- a/x/gov/types/v1beta1/msgs_test.go +++ b/x/gov/types/v1beta1/msgs_test.go @@ -1,10 +1,8 @@ package v1beta1 import ( - "strings" "testing" - "cosmossdk.io/math" "github.com/stretchr/testify/require" sdk "github.com/cosmos/cosmos-sdk/types" @@ -12,57 +10,13 @@ import ( var ( coinsPos = sdk.NewCoins(sdk.NewInt64Coin(sdk.DefaultBondDenom, 1000)) - coinsZero = sdk.NewCoins() coinsMulti = sdk.NewCoins(sdk.NewInt64Coin(sdk.DefaultBondDenom, 1000), sdk.NewInt64Coin("foo", 10000)) - addrs = []sdk.AccAddress{ - sdk.AccAddress("test1"), - sdk.AccAddress("test2"), - } ) func init() { coinsMulti.Sort() } -// test ValidateBasic for MsgCreateValidator -func TestMsgSubmitProposal(t *testing.T) { - tests := []struct { - title, description string - proposalType string - proposerAddr sdk.AccAddress - initialDeposit sdk.Coins - expectPass bool - }{ - {"Test Proposal", "the purpose of this proposal is to test", ProposalTypeText, addrs[0], coinsPos, true}, - {"", "the purpose of this proposal is to test", ProposalTypeText, addrs[0], coinsPos, false}, - {"Test Proposal", "", ProposalTypeText, addrs[0], coinsPos, false}, - {"Test Proposal", "the purpose of this proposal is to test", ProposalTypeText, sdk.AccAddress{}, coinsPos, false}, - {"Test Proposal", "the purpose of this proposal is to test", ProposalTypeText, addrs[0], coinsZero, true}, - {"Test Proposal", "the purpose of this proposal is to test", ProposalTypeText, addrs[0], coinsMulti, true}, - {strings.Repeat("#", MaxTitleLength*2), "the purpose of this proposal is to test", ProposalTypeText, addrs[0], coinsMulti, false}, - {"Test Proposal", strings.Repeat("#", MaxDescriptionLength*2), ProposalTypeText, addrs[0], coinsMulti, false}, - } - - for i, tc := range tests { - content, ok := ContentFromProposalType(tc.title, tc.description, tc.proposalType) - require.True(t, ok) - - msg, err := NewMsgSubmitProposal( - content, - tc.initialDeposit, - tc.proposerAddr, - ) - - require.NoError(t, err) - - if tc.expectPass { - require.NoError(t, msg.ValidateBasic(), "test: %v", i) - } else { - require.Error(t, msg.ValidateBasic(), "test: %v", i) - } - } -} - func TestMsgDepositGetSignBytes(t *testing.T) { addr := sdk.AccAddress("addr1") msg := NewMsgDeposit(addr, 0, coinsPos) @@ -72,100 +26,6 @@ func TestMsgDepositGetSignBytes(t *testing.T) { require.Equal(t, expected, string(res)) } -// test ValidateBasic for MsgDeposit -func TestMsgDeposit(t *testing.T) { - tests := []struct { - proposalID uint64 - depositorAddr sdk.AccAddress - depositAmount sdk.Coins - expectPass bool - }{ - {0, addrs[0], coinsPos, true}, - {1, sdk.AccAddress{}, coinsPos, false}, - {1, addrs[0], coinsZero, true}, - {1, addrs[0], coinsMulti, true}, - } - - for i, tc := range tests { - msg := NewMsgDeposit(tc.depositorAddr, tc.proposalID, tc.depositAmount) - if tc.expectPass { - require.NoError(t, msg.ValidateBasic(), "test: %v", i) - } else { - require.Error(t, msg.ValidateBasic(), "test: %v", i) - } - } -} - -// test ValidateBasic for MsgVote -func TestMsgVote(t *testing.T) { - tests := []struct { - proposalID uint64 - voterAddr sdk.AccAddress - option VoteOption - expectPass bool - }{ - {0, addrs[0], OptionYes, true}, - {0, sdk.AccAddress{}, OptionYes, false}, - {0, addrs[0], OptionNo, true}, - {0, addrs[0], OptionNoWithVeto, true}, - {0, addrs[0], OptionAbstain, true}, - {0, addrs[0], VoteOption(0x13), false}, - } - - for i, tc := range tests { - msg := NewMsgVote(tc.voterAddr, tc.proposalID, tc.option) - if tc.expectPass { - require.Nil(t, msg.ValidateBasic(), "test: %v", i) - } else { - require.NotNil(t, msg.ValidateBasic(), "test: %v", i) - } - } -} - -// test ValidateBasic for MsgVoteWeighted -func TestMsgVoteWeighted(t *testing.T) { - tests := []struct { - proposalID uint64 - voterAddr sdk.AccAddress - options WeightedVoteOptions - expectPass bool - }{ - {0, addrs[0], NewNonSplitVoteOption(OptionYes), true}, - {0, sdk.AccAddress{}, NewNonSplitVoteOption(OptionYes), false}, - {0, addrs[0], NewNonSplitVoteOption(OptionNo), true}, - {0, addrs[0], NewNonSplitVoteOption(OptionNoWithVeto), true}, - {0, addrs[0], NewNonSplitVoteOption(OptionAbstain), true}, - {0, addrs[0], WeightedVoteOptions{ // weight sum > 1 - WeightedVoteOption{Option: OptionYes, Weight: math.LegacyNewDec(1)}, - WeightedVoteOption{Option: OptionAbstain, Weight: math.LegacyNewDec(1)}, - }, false}, - {0, addrs[0], WeightedVoteOptions{ // duplicate option - WeightedVoteOption{Option: OptionYes, Weight: sdk.NewDecWithPrec(5, 1)}, - WeightedVoteOption{Option: OptionYes, Weight: sdk.NewDecWithPrec(5, 1)}, - }, false}, - {0, addrs[0], WeightedVoteOptions{ // zero weight - WeightedVoteOption{Option: OptionYes, Weight: math.LegacyNewDec(0)}, - }, false}, - {0, addrs[0], WeightedVoteOptions{ // negative weight - WeightedVoteOption{Option: OptionYes, Weight: math.LegacyNewDec(-1)}, - }, false}, - {0, addrs[0], WeightedVoteOptions{}, false}, - {0, addrs[0], NewNonSplitVoteOption(VoteOption(0x13)), false}, - {0, addrs[0], WeightedVoteOptions{ // weight sum <1 - WeightedVoteOption{Option: OptionYes, Weight: sdk.NewDecWithPrec(5, 1)}, - }, false}, - } - - for i, tc := range tests { - msg := NewMsgVoteWeighted(tc.voterAddr, tc.proposalID, tc.options) - if tc.expectPass { - require.Nil(t, msg.ValidateBasic(), "test: %v", i) - } else { - require.NotNil(t, msg.ValidateBasic(), "test: %v", i) - } - } -} - // this tests that Amino JSON MsgSubmitProposal.GetSignBytes() still works with Content as Any using the ModuleCdc func TestMsgSubmitProposal_GetSignBytes(t *testing.T) { msg, err := NewMsgSubmitProposal(NewTextProposal("test", "abcd"), sdk.NewCoins(), sdk.AccAddress{}) diff --git a/x/gov/types/v1beta1/params.go b/x/gov/types/v1beta1/params.go index b7eb24349095..11033a012237 100644 --- a/x/gov/types/v1beta1/params.go +++ b/x/gov/types/v1beta1/params.go @@ -3,6 +3,8 @@ package v1beta1 import ( "time" + sdkmath "cosmossdk.io/math" + sdk "github.com/cosmos/cosmos-sdk/types" ) @@ -13,10 +15,10 @@ const ( // Default governance params var ( - DefaultMinDepositTokens = sdk.NewInt(10000000) - DefaultQuorum = sdk.NewDecWithPrec(334, 3) - DefaultThreshold = sdk.NewDecWithPrec(5, 1) - DefaultVetoThreshold = sdk.NewDecWithPrec(334, 3) + DefaultMinDepositTokens = sdkmath.NewInt(10000000) + DefaultQuorum = sdkmath.LegacyNewDecWithPrec(334, 3) + DefaultThreshold = sdkmath.LegacyNewDecWithPrec(5, 1) + DefaultVetoThreshold = sdkmath.LegacyNewDecWithPrec(334, 3) ) // NewDepositParams creates a new DepositParams object diff --git a/x/gov/types/v1beta1/vote.go b/x/gov/types/v1beta1/vote.go index 25c959894b25..b3d47be3100a 100644 --- a/x/gov/types/v1beta1/vote.go +++ b/x/gov/types/v1beta1/vote.go @@ -4,14 +4,12 @@ import ( "fmt" "strings" - "cosmossdk.io/math" + sdkmath "cosmossdk.io/math" sdk "github.com/cosmos/cosmos-sdk/types" ) -// NewVote creates a new Vote instance -// -//nolint:interfacer +// NewVote creates a new Vote instance. func NewVote(proposalID uint64, voter sdk.AccAddress, options WeightedVoteOptions) Vote { return Vote{ProposalId: proposalID, Voter: voter.String(), Options: options} } @@ -53,7 +51,7 @@ func (v Votes) String() string { // NewNonSplitVoteOption creates a single option vote with weight 1 func NewNonSplitVoteOption(option VoteOption) WeightedVoteOptions { - return WeightedVoteOptions{{option, math.LegacyNewDec(1)}} + return WeightedVoteOptions{{option, sdkmath.LegacyNewDec(1)}} } // WeightedVoteOptions describes array of WeightedVoteOptions @@ -69,7 +67,7 @@ func (v WeightedVoteOptions) String() (out string) { // ValidWeightedVoteOption returns true if the sub vote is valid and false otherwise. func ValidWeightedVoteOption(option WeightedVoteOption) bool { - if !option.Weight.IsPositive() || option.Weight.GT(math.LegacyNewDec(1)) { + if !option.Weight.IsPositive() || option.Weight.GT(sdkmath.LegacyNewDec(1)) { return false } return ValidVoteOption(option.Option) @@ -98,7 +96,7 @@ func WeightedVoteOptionsFromString(str string) (WeightedVoteOptions, error) { if len(fields) < 2 { return options, fmt.Errorf("weight field does not exist for %s option", fields[0]) } - weight, err := sdk.NewDecFromStr(fields[1]) + weight, err := sdkmath.LegacyNewDecFromStr(fields[1]) if err != nil { return options, err } diff --git a/x/group/client/cli/tx.go b/x/group/client/cli/tx.go index 93dc5627d16b..172f64564b05 100644 --- a/x/group/client/cli/tx.go +++ b/x/group/client/cli/tx.go @@ -4,15 +4,17 @@ import ( "errors" "fmt" "strconv" + "strings" + "cosmossdk.io/core/address" "github.com/spf13/cobra" "github.com/cosmos/cosmos-sdk/client" "github.com/cosmos/cosmos-sdk/client/flags" "github.com/cosmos/cosmos-sdk/client/tx" - sdk "github.com/cosmos/cosmos-sdk/types" "github.com/cosmos/cosmos-sdk/version" "github.com/cosmos/cosmos-sdk/x/group" + "github.com/cosmos/cosmos-sdk/x/group/internal/math" ) const ( @@ -21,8 +23,10 @@ const ( FlagGroupPolicyAsAdmin = "group-policy-as-admin" ) +var errZeroGroupID = errors.New("group id cannot be 0") + // TxCmd returns a root CLI command handler for all x/group transaction commands. -func TxCmd(name string) *cobra.Command { +func TxCmd(name string, ac address.Codec) *cobra.Command { txCmd := &cobra.Command{ Use: name, Short: "Group transaction subcommands", @@ -39,7 +43,7 @@ func TxCmd(name string) *cobra.Command { MsgCreateGroupWithPolicyCmd(), MsgCreateGroupPolicyCmd(), MsgUpdateGroupPolicyAdminCmd(), - MsgUpdateGroupPolicyDecisionPolicyCmd(), + MsgUpdateGroupPolicyDecisionPolicyCmd(ac), MsgUpdateGroupPolicyMetadataCmd(), MsgWithdrawProposalCmd(), MsgSubmitProposalCmd(), @@ -95,14 +99,17 @@ Where members.json contains: return err } + for _, member := range members { + if _, err := math.NewPositiveDecFromString(member.Weight); err != nil { + return fmt.Errorf("invalid weight %s for %s: weight must be positive", member.Weight, member.Address) + } + } + msg := &group.MsgCreateGroup{ Admin: clientCtx.GetFromAddress().String(), Members: members, Metadata: args[1], } - if err = msg.ValidateBasic(); err != nil { - return fmt.Errorf("message validation failed: %w", err) - } return tx.GenerateOrBroadcastTxCLI(clientCtx, cmd.Flags(), msg) }, @@ -157,19 +164,26 @@ Set a member's weight to "0" to delete it. return err } + for _, member := range members { + if _, err := math.NewNonNegativeDecFromString(member.Weight); err != nil { + return fmt.Errorf("invalid weight %s for %s: weight must not be negative", member.Weight, member.Address) + } + } + groupID, err := strconv.ParseUint(args[1], 10, 64) if err != nil { return err } + if groupID == 0 { + return errZeroGroupID + } + msg := &group.MsgUpdateGroupMembers{ Admin: clientCtx.GetFromAddress().String(), MemberUpdates: members, GroupId: groupID, } - if err = msg.ValidateBasic(); err != nil { - return fmt.Errorf("message validation failed: %w", err) - } return tx.GenerateOrBroadcastTxCLI(clientCtx, cmd.Flags(), msg) }, @@ -187,8 +201,7 @@ func MsgUpdateGroupAdminCmd() *cobra.Command { Short: "Update a group's admin", Args: cobra.ExactArgs(3), RunE: func(cmd *cobra.Command, args []string) error { - err := cmd.Flags().Set(flags.FlagFrom, args[0]) - if err != nil { + if err := cmd.Flags().Set(flags.FlagFrom, args[0]); err != nil { return err } @@ -202,14 +215,19 @@ func MsgUpdateGroupAdminCmd() *cobra.Command { return err } + if groupID == 0 { + return errZeroGroupID + } + + if strings.EqualFold(args[0], args[2]) { + return errors.New("new admin cannot be the same as the current admin") + } + msg := &group.MsgUpdateGroupAdmin{ Admin: clientCtx.GetFromAddress().String(), NewAdmin: args[2], GroupId: groupID, } - if err = msg.ValidateBasic(); err != nil { - return fmt.Errorf("message validation failed: %w", err) - } return tx.GenerateOrBroadcastTxCLI(clientCtx, cmd.Flags(), msg) }, @@ -242,14 +260,15 @@ func MsgUpdateGroupMetadataCmd() *cobra.Command { return err } + if groupID == 0 { + return errZeroGroupID + } + msg := &group.MsgUpdateGroupMetadata{ Admin: clientCtx.GetFromAddress().String(), Metadata: args[2], GroupId: groupID, } - if err = msg.ValidateBasic(); err != nil { - return fmt.Errorf("message validation failed: %w", err) - } return tx.GenerateOrBroadcastTxCLI(clientCtx, cmd.Flags(), msg) }, @@ -322,11 +341,21 @@ and policy.json contains: return err } + for _, member := range members { + if _, err := math.NewPositiveDecFromString(member.Weight); err != nil { + return fmt.Errorf("invalid weight %s for %s: weight must be positive", member.Weight, member.Address) + } + } + policy, err := parseDecisionPolicy(clientCtx.Codec, args[4]) if err != nil { return err } + if err := policy.ValidateBasic(); err != nil { + return err + } + msg, err := group.NewMsgCreateGroupWithPolicy( clientCtx.GetFromAddress().String(), members, @@ -339,10 +368,6 @@ and policy.json contains: return err } - if err = msg.ValidateBasic(); err != nil { - return fmt.Errorf("message validation failed: %w", err) - } - return tx.GenerateOrBroadcastTxCLI(clientCtx, cmd.Flags(), msg) }, } @@ -398,11 +423,19 @@ Here, we can use percentage decision policy when needed, where 0 < percentage <= return err } + if groupID == 0 { + return errZeroGroupID + } + policy, err := parseDecisionPolicy(clientCtx.Codec, args[3]) if err != nil { return err } + if err := policy.ValidateBasic(); err != nil { + return err + } + msg, err := group.NewMsgCreateGroupPolicy( clientCtx.GetFromAddress(), groupID, @@ -412,9 +445,6 @@ Here, we can use percentage decision policy when needed, where 0 < percentage <= if err != nil { return err } - if err = msg.ValidateBasic(); err != nil { - return fmt.Errorf("message validation failed: %w", err) - } return tx.GenerateOrBroadcastTxCLI(clientCtx, cmd.Flags(), msg) }, @@ -432,11 +462,14 @@ func MsgUpdateGroupPolicyAdminCmd() *cobra.Command { Short: "Update a group policy admin", Args: cobra.ExactArgs(3), RunE: func(cmd *cobra.Command, args []string) error { - err := cmd.Flags().Set(flags.FlagFrom, args[0]) - if err != nil { + if err := cmd.Flags().Set(flags.FlagFrom, args[0]); err != nil { return err } + if strings.EqualFold(args[0], args[2]) { + return errors.New("new admin cannot be the same as the current admin") + } + clientCtx, err := client.GetClientTxContext(cmd) if err != nil { return err @@ -447,9 +480,6 @@ func MsgUpdateGroupPolicyAdminCmd() *cobra.Command { GroupPolicyAddress: args[1], NewAdmin: args[2], } - if err = msg.ValidateBasic(); err != nil { - return fmt.Errorf("message validation failed: %w", err) - } return tx.GenerateOrBroadcastTxCLI(clientCtx, cmd.Flags(), msg) }, @@ -461,7 +491,7 @@ func MsgUpdateGroupPolicyAdminCmd() *cobra.Command { } // MsgUpdateGroupPolicyDecisionPolicyCmd creates a CLI command for Msg/UpdateGroupPolicyDecisionPolicy. -func MsgUpdateGroupPolicyDecisionPolicyCmd() *cobra.Command { +func MsgUpdateGroupPolicyDecisionPolicyCmd(ac address.Codec) *cobra.Command { cmd := &cobra.Command{ Use: "update-group-policy-decision-policy [admin] [group-policy-account] [decision-policy-json-file]", Short: "Update a group policy's decision policy", @@ -482,7 +512,7 @@ func MsgUpdateGroupPolicyDecisionPolicyCmd() *cobra.Command { return err } - accountAddress, err := sdk.AccAddressFromBech32(args[1]) + accountAddress, err := ac.StringToBytes(args[1]) if err != nil { return err } @@ -496,10 +526,6 @@ func MsgUpdateGroupPolicyDecisionPolicyCmd() *cobra.Command { return err } - if err = msg.ValidateBasic(); err != nil { - return fmt.Errorf("message validation failed: %w", err) - } - return tx.GenerateOrBroadcastTxCLI(clientCtx, cmd.Flags(), msg) }, } @@ -516,8 +542,7 @@ func MsgUpdateGroupPolicyMetadataCmd() *cobra.Command { Short: "Update a group policy metadata", Args: cobra.ExactArgs(3), RunE: func(cmd *cobra.Command, args []string) error { - err := cmd.Flags().Set(flags.FlagFrom, args[0]) - if err != nil { + if err := cmd.Flags().Set(flags.FlagFrom, args[0]); err != nil { return err } @@ -531,9 +556,6 @@ func MsgUpdateGroupPolicyMetadataCmd() *cobra.Command { GroupPolicyAddress: args[1], Metadata: args[2], } - if err = msg.ValidateBasic(); err != nil { - return fmt.Errorf("message validation failed: %w", err) - } return tx.GenerateOrBroadcastTxCLI(clientCtx, cmd.Flags(), msg) }, @@ -611,7 +633,6 @@ metadata example: } execStr, _ := cmd.Flags().GetString(FlagExec) - msg, err := group.NewMsgSubmitProposal( prop.GroupPolicyAddress, prop.Proposers, @@ -625,10 +646,6 @@ metadata example: return err } - if err = msg.ValidateBasic(); err != nil { - return fmt.Errorf("message validation failed: %w", err) - } - return tx.GenerateOrBroadcastTxCLI(clientCtx, cmd.Flags(), msg) }, } @@ -653,8 +670,7 @@ Parameters: `, Args: cobra.ExactArgs(2), RunE: func(cmd *cobra.Command, args []string) error { - err := cmd.Flags().Set(flags.FlagFrom, args[1]) - if err != nil { + if err := cmd.Flags().Set(flags.FlagFrom, args[1]); err != nil { return err } @@ -668,19 +684,15 @@ Parameters: return err } + if proposalID == 0 { + return fmt.Errorf("invalid proposal id: %d", proposalID) + } + msg := &group.MsgWithdrawProposal{ ProposalId: proposalID, Address: clientCtx.GetFromAddress().String(), } - if err != nil { - return err - } - - if err = msg.ValidateBasic(); err != nil { - return fmt.Errorf("message validation failed: %w", err) - } - return tx.GenerateOrBroadcastTxCLI(clientCtx, cmd.Flags(), msg) }, } @@ -739,13 +751,6 @@ Parameters: Metadata: args[3], Exec: execFromString(execStr), } - if err != nil { - return err - } - - if err = msg.ValidateBasic(); err != nil { - return fmt.Errorf("message validation failed: %w", err) - } return tx.GenerateOrBroadcastTxCLI(clientCtx, cmd.Flags(), msg) }, @@ -778,13 +783,6 @@ func MsgExecCmd() *cobra.Command { ProposalId: proposalID, Executor: clientCtx.GetFromAddress().String(), } - if err != nil { - return err - } - - if err = msg.ValidateBasic(); err != nil { - return fmt.Errorf("message validation failed: %w", err) - } return tx.GenerateOrBroadcastTxCLI(clientCtx, cmd.Flags(), msg) }, @@ -820,13 +818,14 @@ Parameters: return err } + if groupID == 0 { + return errZeroGroupID + } + msg := &group.MsgLeaveGroup{ Address: clientCtx.GetFromAddress().String(), GroupId: groupID, } - if err = msg.ValidateBasic(); err != nil { - return fmt.Errorf("message validation failed: %w", err) - } return tx.GenerateOrBroadcastTxCLI(clientCtx, cmd.Flags(), msg) }, diff --git a/x/group/client/cli/tx_test.go b/x/group/client/cli/tx_test.go index 46f35b137c80..20f0fe2024b7 100644 --- a/x/group/client/cli/tx_test.go +++ b/x/group/client/cli/tx_test.go @@ -1,22 +1,23 @@ package cli_test import ( - "bytes" "context" "encoding/json" "fmt" "io" - "strconv" - "strings" "testing" abci "github.com/cometbft/cometbft/abci/types" rpcclientmock "github.com/cometbft/cometbft/rpc/client/mock" - "github.com/cosmos/gogoproto/proto" "github.com/stretchr/testify/suite" + // without this import amino json encoding will fail when resolving any types + _ "cosmossdk.io/api/cosmos/group/v1" + sdkmath "cosmossdk.io/math" + "github.com/cosmos/cosmos-sdk/client" "github.com/cosmos/cosmos-sdk/client/flags" + "github.com/cosmos/cosmos-sdk/codec/address" "github.com/cosmos/cosmos-sdk/crypto/hd" "github.com/cosmos/cosmos-sdk/crypto/keyring" svrcmd "github.com/cosmos/cosmos-sdk/server/cmd" @@ -29,9 +30,7 @@ import ( groupmodule "github.com/cosmos/cosmos-sdk/x/group/module" ) -const validMetadata = "metadata" - -var tooLongMetadata = strings.Repeat("A", 256) +var validMetadata = "metadata" type CLITestSuite struct { suite.Suite @@ -63,13 +62,12 @@ func (s *CLITestSuite) SetupSuite() { s.commonFlags = []string{ fmt.Sprintf("--%s=true", flags.FlagSkipConfirmation), fmt.Sprintf("--%s=%s", flags.FlagBroadcastMode, flags.BroadcastSync), - fmt.Sprintf("--%s=%s", flags.FlagFees, sdk.NewCoins(sdk.NewCoin("stake", sdk.NewInt(10))).String()), + fmt.Sprintf("--%s=%s", flags.FlagFees, sdk.NewCoins(sdk.NewCoin("stake", sdkmath.NewInt(10))).String()), } accounts := testutil.CreateKeyringAccounts(s.T(), s.kr, 1) val := accounts[0] - var outBuf bytes.Buffer ctxGen := func() client.Context { bz, _ := s.encCfg.Codec.Marshal(&sdk.TxResponse{}) c := clitestutil.NewMockCometRPC(abci.ResponseQuery{ @@ -77,7 +75,7 @@ func (s *CLITestSuite) SetupSuite() { }) return s.baseCtx.WithClient(c) } - s.clientCtx = ctxGen().WithOutput(&outBuf) + s.clientCtx = ctxGen() // create a new account info, _, err := s.clientCtx.Keyring.NewMnemonic("NewValidator", keyring.English, sdk.FullFundraiserPath, keyring.DefaultBIP39Passphrase, hd.Secp256k1) @@ -91,24 +89,23 @@ func (s *CLITestSuite) SetupSuite() { s.clientCtx, val.Address, account, - sdk.NewCoins(sdk.NewCoin("stake", sdk.NewInt(2000))), fmt.Sprintf("--%s=true", flags.FlagSkipConfirmation), + sdk.NewCoins(sdk.NewCoin("stake", sdkmath.NewInt(2000))), fmt.Sprintf("--%s=true", flags.FlagSkipConfirmation), fmt.Sprintf("--%s=%s", flags.FlagBroadcastMode, flags.BroadcastSync), - fmt.Sprintf("--%s=%s", flags.FlagFees, sdk.NewCoins(sdk.NewCoin("stake", sdk.NewInt(10))).String()), + fmt.Sprintf("--%s=%s", flags.FlagFees, sdk.NewCoins(sdk.NewCoin("stake", sdkmath.NewInt(10))).String()), ) s.Require().NoError(err) - memberWeight := "3" // create a group validMembers := fmt.Sprintf(` { "members": [ { "address": "%s", - "weight": "%s", + "weight": "3", "metadata": "%s" } ] - }`, val.Address.String(), memberWeight, validMetadata) + }`, val.Address.String(), validMetadata) validMembersFile := testutil.WriteToNewTempFile(s.T(), validMembers) out, err := clitestutil.ExecTestCLICmd(s.clientCtx, groupcli.MsgCreateGroupCmd(), append( @@ -142,12 +139,6 @@ func (s *CLITestSuite) TestTxCreateGroup() { }]}`, accounts[0].Address.String(), validMetadata) validMembersFile := testutil.WriteToNewTempFile(s.T(), validMembers) - invalidMembersAddress := `{"members": [{ - "address": "", - "weight": "1" - }]}` - invalidMembersAddressFile := testutil.WriteToNewTempFile(s.T(), invalidMembersAddress) - invalidMembersWeight := fmt.Sprintf(`{"members": [{ "address": "%s", "weight": "0" @@ -156,23 +147,13 @@ func (s *CLITestSuite) TestTxCreateGroup() { testCases := []struct { name string - ctxGen func() client.Context args []string - respType proto.Message expCmdOutput string - expectErr bool expectErrMsg string }{ { - "correct data", - func() client.Context { - bz, _ := s.encCfg.Codec.Marshal(&sdk.TxResponse{}) - c := clitestutil.NewMockCometRPC(abci.ResponseQuery{ - Value: bz, - }) - return s.baseCtx.WithClient(c) - }, - append( + name: "correct data", + args: append( []string{ accounts[0].Address.String(), "", @@ -180,20 +161,11 @@ func (s *CLITestSuite) TestTxCreateGroup() { }, s.commonFlags..., ), - &sdk.TxResponse{}, - fmt.Sprintf("%s %s %s", accounts[0].Address.String(), "", validMembersFile.Name()), - false, - "", + expCmdOutput: fmt.Sprintf("%s %s %s", accounts[0].Address.String(), "", validMembersFile.Name()), + expectErrMsg: "", }, { "with amino-json", - func() client.Context { - bz, _ := s.encCfg.Codec.Marshal(&sdk.TxResponse{}) - c := clitestutil.NewMockCometRPC(abci.ResponseQuery{ - Value: bz, - }) - return s.baseCtx.WithClient(c) - }, append( []string{ accounts[0].Address.String(), @@ -203,54 +175,34 @@ func (s *CLITestSuite) TestTxCreateGroup() { }, s.commonFlags..., ), - &sdk.TxResponse{}, fmt.Sprintf("%s %s %s", accounts[0].Address.String(), "", validMembersFile.Name()), - false, "", }, { - "invalid members address", - func() client.Context { - bz, _ := s.encCfg.Codec.Marshal(&sdk.TxResponse{}) - c := clitestutil.NewMockCometRPC(abci.ResponseQuery{ - Value: bz, - }) - return s.baseCtx.WithClient(c) - }, + "invalid members weight", append( []string{ accounts[0].Address.String(), "null", - invalidMembersAddressFile.Name(), + invalidMembersWeightFile.Name(), }, s.commonFlags..., ), - &sdk.TxResponse{}, - fmt.Sprintf("%s %s %s", accounts[0].Address.String(), "null", invalidMembersAddressFile.Name()), - true, - "message validation failed: address: empty address string is not allowed", + "", + "weight must be positive", }, { - "invalid members weight", - func() client.Context { - bz, _ := s.encCfg.Codec.Marshal(&sdk.TxResponse{}) - c := clitestutil.NewMockCometRPC(abci.ResponseQuery{ - Value: bz, - }) - return s.baseCtx.WithClient(c) - }, + "no member provided", append( []string{ accounts[0].Address.String(), "null", - invalidMembersWeightFile.Name(), + "doesnotexist.json", }, s.commonFlags..., ), - &sdk.TxResponse{}, - fmt.Sprintf("%s %s %s", accounts[0].Address.String(), "null", invalidMembersWeightFile.Name()), - true, - "expected a positive decimal, got 0: invalid decimal string", + "", + "no such file or directory", }, } @@ -258,27 +210,23 @@ func (s *CLITestSuite) TestTxCreateGroup() { tc := tc s.Run(tc.name, func() { - var outBuf bytes.Buffer - - clientCtx := tc.ctxGen().WithOutput(&outBuf) ctx := svrcmd.CreateExecuteContext(context.Background()) - cmd.SetContext(ctx) cmd.SetArgs(tc.args) - - s.Require().NoError(client.SetCmdClientContextHandler(clientCtx, cmd)) + s.Require().NoError(client.SetCmdClientContextHandler(s.baseCtx, cmd)) if len(tc.args) != 0 { s.Require().Contains(fmt.Sprint(cmd), tc.expCmdOutput) } - out, err := clitestutil.ExecTestCLICmd(clientCtx, cmd, tc.args) - if tc.expectErr { + out, err := clitestutil.ExecTestCLICmd(s.baseCtx, cmd, tc.args) + if tc.expectErrMsg != "" { s.Require().Error(err) s.Require().Contains(out.String(), tc.expectErrMsg) } else { s.Require().NoError(err) - s.Require().NoError(clientCtx.Codec.UnmarshalJSON(out.Bytes(), tc.respType), out.String()) + msg := &sdk.TxResponse{} + s.Require().NoError(s.baseCtx.Codec.UnmarshalJSON(out.Bytes(), msg), out.String()) } }) } @@ -290,21 +238,9 @@ func (s *CLITestSuite) TestTxUpdateGroupAdmin() { cmd := groupcli.MsgUpdateGroupAdminCmd() cmd.SetOutput(io.Discard) - var outBuf bytes.Buffer - - ctxGen := func() client.Context { - bz, _ := s.encCfg.Codec.Marshal(&sdk.TxResponse{}) - c := clitestutil.NewMockCometRPC(abci.ResponseQuery{ - Value: bz, - }) - return s.baseCtx.WithClient(c) - } - clientCtx := ctxGen().WithOutput(&outBuf) ctx := svrcmd.CreateExecuteContext(context.Background()) - cmd.SetContext(ctx) - - s.Require().NoError(client.SetCmdClientContextHandler(clientCtx, cmd)) + s.Require().NoError(client.SetCmdClientContextHandler(s.baseCtx, cmd)) groupIDs := make([]string, 2) for i := 0; i < 2; i++ { @@ -314,7 +250,7 @@ func (s *CLITestSuite) TestTxUpdateGroupAdmin() { "metadata": "%s" }]}`, accounts[0].Address.String(), validMetadata) validMembersFile := testutil.WriteToNewTempFile(s.T(), validMembers) - out, err := clitestutil.ExecTestCLICmd(clientCtx, groupcli.MsgCreateGroupCmd(), + out, err := clitestutil.ExecTestCLICmd(s.baseCtx, groupcli.MsgCreateGroupCmd(), append( []string{ accounts[0].Address.String(), @@ -332,9 +268,7 @@ func (s *CLITestSuite) TestTxUpdateGroupAdmin() { name string ctxGen func() client.Context args []string - respType proto.Message expCmdOutput string - expectErr bool expectErrMsg string }{ { @@ -354,9 +288,7 @@ func (s *CLITestSuite) TestTxUpdateGroupAdmin() { }, s.commonFlags..., ), - &sdk.TxResponse{}, fmt.Sprintf("%s %s %s", accounts[0].Address.String(), groupIDs[0], accounts[1].Address.String()), - false, "", }, { @@ -377,9 +309,7 @@ func (s *CLITestSuite) TestTxUpdateGroupAdmin() { }, s.commonFlags..., ), - &sdk.TxResponse{}, fmt.Sprintf("%s %s %s --%s=%s", accounts[0].Address.String(), groupIDs[1], accounts[1].Address.String(), flags.FlagSignMode, flags.SignModeLegacyAminoJSON), - false, "", }, { @@ -399,9 +329,7 @@ func (s *CLITestSuite) TestTxUpdateGroupAdmin() { }, s.commonFlags..., ), - &sdk.TxResponse{}, fmt.Sprintf("%s %s %s", accounts[0].Address.String(), "", accounts[1].Address.String()), - true, "strconv.ParseUint: parsing \"\": invalid syntax", }, } @@ -410,27 +338,25 @@ func (s *CLITestSuite) TestTxUpdateGroupAdmin() { tc := tc s.Run(tc.name, func() { - var outBuf bytes.Buffer - - clientCtx := tc.ctxGen().WithOutput(&outBuf) ctx := svrcmd.CreateExecuteContext(context.Background()) cmd.SetContext(ctx) cmd.SetArgs(tc.args) - s.Require().NoError(client.SetCmdClientContextHandler(clientCtx, cmd)) + s.Require().NoError(client.SetCmdClientContextHandler(s.baseCtx, cmd)) if len(tc.args) != 0 { s.Require().Contains(fmt.Sprint(cmd), tc.expCmdOutput) } - out, err := clitestutil.ExecTestCLICmd(clientCtx, cmd, tc.args) - if tc.expectErr { + out, err := clitestutil.ExecTestCLICmd(s.baseCtx, cmd, tc.args) + if tc.expectErrMsg != "" { s.Require().Error(err) s.Require().Contains(out.String(), tc.expectErrMsg) } else { s.Require().NoError(err) - s.Require().NoError(clientCtx.Codec.UnmarshalJSON(out.Bytes(), tc.respType), out.String()) + msg := &sdk.TxResponse{} + s.Require().NoError(s.baseCtx.Codec.UnmarshalJSON(out.Bytes(), msg), out.String()) } }) } @@ -444,19 +370,12 @@ func (s *CLITestSuite) TestTxUpdateGroupMetadata() { testCases := []struct { name string - ctxGen func() client.Context args []string expCmdOutput string + expectErrMsg string }{ { "correct data", - func() client.Context { - bz, _ := s.encCfg.Codec.Marshal(&sdk.TxResponse{}) - c := clitestutil.NewMockCometRPC(abci.ResponseQuery{ - Value: bz, - }) - return s.baseCtx.WithClient(c) - }, append( []string{ accounts[0].Address.String(), @@ -466,16 +385,10 @@ func (s *CLITestSuite) TestTxUpdateGroupMetadata() { s.commonFlags..., ), fmt.Sprintf("%s %s %s", accounts[0].Address.String(), "1", validMetadata), + "", }, { "with amino-json", - func() client.Context { - bz, _ := s.encCfg.Codec.Marshal(&sdk.TxResponse{}) - c := clitestutil.NewMockCometRPC(abci.ResponseQuery{ - Value: bz, - }) - return s.baseCtx.WithClient(c) - }, append( []string{ accounts[0].Address.String(), @@ -486,25 +399,33 @@ func (s *CLITestSuite) TestTxUpdateGroupMetadata() { s.commonFlags..., ), fmt.Sprintf("%s %s %s --%s=%s", accounts[0].Address.String(), "1", validMetadata, flags.FlagSignMode, flags.SignModeLegacyAminoJSON), + "", }, { - "group metadata too long", - func() client.Context { - bz, _ := s.encCfg.Codec.Marshal(&sdk.TxResponse{}) - c := clitestutil.NewMockCometRPC(abci.ResponseQuery{ - Value: bz, - }) - return s.baseCtx.WithClient(c) - }, + "invalid group id", + append( + []string{ + accounts[0].Address.String(), + "abc", + validMetadata, + }, + s.commonFlags..., + ), + fmt.Sprintf("%s %s %s", accounts[0].Address.String(), "abc", validMetadata), + "Error: strconv.ParseUint: parsing \"abc\"", + }, + { + "empty group id", append( []string{ accounts[0].Address.String(), - strconv.FormatUint(s.group.Id, 10), - strings.Repeat("a", 256), + "0", + validMetadata, }, s.commonFlags..., ), - fmt.Sprintf("%s %s %s", accounts[0].Address.String(), strconv.FormatUint(s.group.Id, 10), strings.Repeat("a", 256)), + fmt.Sprintf("%s %s %s", accounts[0].Address.String(), "0", validMetadata), + "group id cannot be 0", }, } @@ -512,19 +433,26 @@ func (s *CLITestSuite) TestTxUpdateGroupMetadata() { tc := tc s.Run(tc.name, func() { - var outBuf bytes.Buffer - - clientCtx := tc.ctxGen().WithOutput(&outBuf) ctx := svrcmd.CreateExecuteContext(context.Background()) cmd.SetContext(ctx) cmd.SetArgs(tc.args) - s.Require().NoError(client.SetCmdClientContextHandler(clientCtx, cmd)) + s.Require().NoError(client.SetCmdClientContextHandler(s.baseCtx, cmd)) if len(tc.args) != 0 { s.Require().Contains(fmt.Sprint(cmd), tc.expCmdOutput) } + + out, err := clitestutil.ExecTestCLICmd(s.baseCtx, cmd, tc.args) + if tc.expectErrMsg != "" { + s.Require().Error(err) + s.Require().Contains(out.String(), tc.expectErrMsg) + } else { + s.Require().NoError(err) + msg := &sdk.TxResponse{} + s.Require().NoError(s.baseCtx.Codec.UnmarshalJSON(out.Bytes(), msg), out.String()) + } }) } } @@ -550,26 +478,19 @@ func (s *CLITestSuite) TestTxUpdateGroupMembers() { invalidMembersMetadata := fmt.Sprintf(`{"members": [{ "address": "%s", - "weight": "1", - "metadata": "%s" - }]}`, accounts[1], tooLongMetadata) + "weight": "-1", + "metadata": "foo" + }]}`, accounts[1]) invalidMembersMetadataFileName := testutil.WriteToNewTempFile(s.T(), invalidMembersMetadata).Name() testCases := []struct { name string - ctxGen func() client.Context args []string expCmdOutput string + expectErrMsg string }{ { "correct data", - func() client.Context { - bz, _ := s.encCfg.Codec.Marshal(&sdk.TxResponse{}) - c := clitestutil.NewMockCometRPC(abci.ResponseQuery{ - Value: bz, - }) - return s.baseCtx.WithClient(c) - }, append( []string{ accounts[0].Address.String(), @@ -579,16 +500,10 @@ func (s *CLITestSuite) TestTxUpdateGroupMembers() { s.commonFlags..., ), fmt.Sprintf("%s %s %s", accounts[0].Address.String(), groupID, validUpdatedMembersFileName), + "", }, { "with amino-json", - func() client.Context { - bz, _ := s.encCfg.Codec.Marshal(&sdk.TxResponse{}) - c := clitestutil.NewMockCometRPC(abci.ResponseQuery{ - Value: bz, - }) - return s.baseCtx.WithClient(c) - }, append( []string{ accounts[0].Address.String(), @@ -599,44 +514,33 @@ func (s *CLITestSuite) TestTxUpdateGroupMembers() { s.commonFlags..., ), fmt.Sprintf("%s %s %s --%s=%s", accounts[0].Address.String(), groupID, validUpdatedMembersFileName, flags.FlagSignMode, flags.SignModeLegacyAminoJSON), + "", }, { - "group member metadata too long", - func() client.Context { - bz, _ := s.encCfg.Codec.Marshal(&sdk.TxResponse{}) - c := clitestutil.NewMockCometRPC(abci.ResponseQuery{ - Value: bz, - }) - return s.baseCtx.WithClient(c) - }, + "group id invalid", append( []string{ accounts[0].Address.String(), - groupID, - invalidMembersMetadataFileName, + "0", + validUpdatedMembersFileName, }, s.commonFlags..., ), - fmt.Sprintf("%s %s %s", accounts[0].Address.String(), groupID, invalidMembersMetadataFileName), + fmt.Sprintf("%s %s %s", accounts[0].Address.String(), "0", validUpdatedMembersFileName), + "group id cannot be 0", }, { - "group doesn't exist", - func() client.Context { - bz, _ := s.encCfg.Codec.Marshal(&sdk.TxResponse{}) - c := clitestutil.NewMockCometRPC(abci.ResponseQuery{ - Value: bz, - }) - return s.baseCtx.WithClient(c) - }, + "group member weight invalid", append( []string{ accounts[0].Address.String(), - "12345", - validUpdatedMembersFileName, + groupID, + invalidMembersMetadataFileName, }, s.commonFlags..., ), - fmt.Sprintf("%s %s %s", accounts[0].Address.String(), "12345", validUpdatedMembersFileName), + fmt.Sprintf("%s %s %s", accounts[0].Address.String(), groupID, invalidMembersMetadataFileName), + "invalid weight -1", }, } @@ -644,19 +548,26 @@ func (s *CLITestSuite) TestTxUpdateGroupMembers() { tc := tc s.Run(tc.name, func() { - var outBuf bytes.Buffer - - clientCtx := tc.ctxGen().WithOutput(&outBuf) ctx := svrcmd.CreateExecuteContext(context.Background()) cmd.SetContext(ctx) cmd.SetArgs(tc.args) - s.Require().NoError(client.SetCmdClientContextHandler(clientCtx, cmd)) + s.Require().NoError(client.SetCmdClientContextHandler(s.baseCtx, cmd)) if len(tc.args) != 0 { s.Require().Contains(fmt.Sprint(cmd), tc.expCmdOutput) } + + out, err := clitestutil.ExecTestCLICmd(s.baseCtx, cmd, tc.args) + if tc.expectErrMsg != "" { + s.Require().Error(err) + s.Require().Contains(out.String(), tc.expectErrMsg) + } else { + s.Require().NoError(err) + msg := &sdk.TxResponse{} + s.Require().NoError(s.baseCtx.Codec.UnmarshalJSON(out.Bytes(), msg), out.String()) + } }) } } @@ -674,12 +585,6 @@ func (s *CLITestSuite) TestTxCreateGroupWithPolicy() { }]}`, accounts[0].Address.String(), validMetadata) validMembersFile := testutil.WriteToNewTempFile(s.T(), validMembers) - invalidMembersAddress := `{"members": [{ - "address": "", - "weight": "1" - }]}` - invalidMembersAddressFile := testutil.WriteToNewTempFile(s.T(), invalidMembersAddress) - invalidMembersWeight := fmt.Sprintf(`{"members": [{ "address": "%s", "weight": "0" @@ -690,22 +595,12 @@ func (s *CLITestSuite) TestTxCreateGroupWithPolicy() { testCases := []struct { name string - ctxGen func() client.Context args []string - expectErr bool expectErrMsg string - respType proto.Message expCmdOutput string }{ { "correct data", - func() client.Context { - bz, _ := s.encCfg.Codec.Marshal(&sdk.TxResponse{}) - c := clitestutil.NewMockCometRPC(abci.ResponseQuery{ - Value: bz, - }) - return s.baseCtx.WithClient(c) - }, append( []string{ accounts[0].Address.String(), @@ -717,20 +612,11 @@ func (s *CLITestSuite) TestTxCreateGroupWithPolicy() { }, s.commonFlags..., ), - false, "", - &sdk.TxResponse{}, fmt.Sprintf("%s %s %s %s %s --%s=%v", accounts[0].Address.String(), validMetadata, validMetadata, validMembersFile.Name(), thresholdDecisionPolicyFile.Name(), groupcli.FlagGroupPolicyAsAdmin, false), }, { "group-policy-as-admin is true", - func() client.Context { - bz, _ := s.encCfg.Codec.Marshal(&sdk.TxResponse{}) - c := clitestutil.NewMockCometRPC(abci.ResponseQuery{ - Value: bz, - }) - return s.baseCtx.WithClient(c) - }, append( []string{ accounts[0].Address.String(), @@ -742,20 +628,11 @@ func (s *CLITestSuite) TestTxCreateGroupWithPolicy() { }, s.commonFlags..., ), - false, "", - &sdk.TxResponse{}, fmt.Sprintf("%s %s %s %s %s --%s=%v", accounts[0].Address.String(), validMetadata, validMetadata, validMembersFile.Name(), thresholdDecisionPolicyFile.Name(), groupcli.FlagGroupPolicyAsAdmin, true), }, { "with amino-json", - func() client.Context { - bz, _ := s.encCfg.Codec.Marshal(&sdk.TxResponse{}) - c := clitestutil.NewMockCometRPC(abci.ResponseQuery{ - Value: bz, - }) - return s.baseCtx.WithClient(c) - }, append( []string{ accounts[0].Address.String(), @@ -768,45 +645,11 @@ func (s *CLITestSuite) TestTxCreateGroupWithPolicy() { }, s.commonFlags..., ), - false, "", - &sdk.TxResponse{}, fmt.Sprintf("%s %s %s %s %s --%s=%v --%s=%s", accounts[0].Address.String(), validMetadata, validMetadata, validMembersFile.Name(), thresholdDecisionPolicyFile.Name(), groupcli.FlagGroupPolicyAsAdmin, false, flags.FlagSignMode, flags.SignModeLegacyAminoJSON), }, - { - "invalid members address", - func() client.Context { - bz, _ := s.encCfg.Codec.Marshal(&sdk.TxResponse{}) - c := clitestutil.NewMockCometRPC(abci.ResponseQuery{ - Value: bz, - }) - return s.baseCtx.WithClient(c) - }, - append( - []string{ - accounts[0].Address.String(), - validMetadata, - validMetadata, - invalidMembersAddressFile.Name(), - thresholdDecisionPolicyFile.Name(), - fmt.Sprintf("--%s=%v", groupcli.FlagGroupPolicyAsAdmin, false), - }, - s.commonFlags..., - ), - true, - "message validation failed: address: empty address string is not allowed", - nil, - fmt.Sprintf("%s %s %s %s %s --%s=%v", accounts[0].Address.String(), validMetadata, validMetadata, invalidMembersAddressFile.Name(), thresholdDecisionPolicyFile.Name(), groupcli.FlagGroupPolicyAsAdmin, false), - }, { "invalid members weight", - func() client.Context { - bz, _ := s.encCfg.Codec.Marshal(&sdk.TxResponse{}) - c := clitestutil.NewMockCometRPC(abci.ResponseQuery{ - Value: bz, - }) - return s.baseCtx.WithClient(c) - }, append( []string{ accounts[0].Address.String(), @@ -818,9 +661,7 @@ func (s *CLITestSuite) TestTxCreateGroupWithPolicy() { }, s.commonFlags..., ), - true, - "expected a positive decimal, got 0: invalid decimal string", - nil, + "weight must be positive", fmt.Sprintf("%s %s %s %s %s --%s=%v", accounts[0].Address.String(), validMetadata, validMetadata, invalidMembersWeightFile.Name(), thresholdDecisionPolicyFile.Name(), groupcli.FlagGroupPolicyAsAdmin, false), }, } @@ -828,27 +669,25 @@ func (s *CLITestSuite) TestTxCreateGroupWithPolicy() { tc := tc s.Run(tc.name, func() { - var outBuf bytes.Buffer - - clientCtx := tc.ctxGen().WithOutput(&outBuf) ctx := svrcmd.CreateExecuteContext(context.Background()) cmd.SetContext(ctx) cmd.SetArgs(tc.args) - s.Require().NoError(client.SetCmdClientContextHandler(clientCtx, cmd)) + s.Require().NoError(client.SetCmdClientContextHandler(s.baseCtx, cmd)) if len(tc.args) != 0 { s.Require().Contains(fmt.Sprint(cmd), tc.expCmdOutput) } - out, err := clitestutil.ExecTestCLICmd(clientCtx, cmd, tc.args) - if tc.expectErr { + out, err := clitestutil.ExecTestCLICmd(s.baseCtx, cmd, tc.args) + if tc.expectErrMsg != "" { s.Require().Error(err) s.Require().Contains(out.String(), tc.expectErrMsg) } else { s.Require().NoError(err, out.String()) - s.Require().NoError(clientCtx.Codec.UnmarshalJSON(out.Bytes(), tc.respType), out.String()) + msg := &sdk.TxResponse{} + s.Require().NoError(s.baseCtx.Codec.UnmarshalJSON(out.Bytes(), msg), out.String()) } }) } @@ -871,22 +710,12 @@ func (s *CLITestSuite) TestTxCreateGroupPolicy() { testCases := []struct { name string - ctxGen func() client.Context args []string - expectErr bool expectErrMsg string - respType proto.Message expCmdOutput string }{ { "correct data", - func() client.Context { - bz, _ := s.encCfg.Codec.Marshal(&sdk.TxResponse{}) - c := clitestutil.NewMockCometRPC(abci.ResponseQuery{ - Value: bz, - }) - return s.baseCtx.WithClient(c) - }, append( []string{ val.Address.String(), @@ -896,20 +725,11 @@ func (s *CLITestSuite) TestTxCreateGroupPolicy() { }, s.commonFlags..., ), - false, "", - &sdk.TxResponse{}, fmt.Sprintf("%s %s %s %s", val.Address.String(), fmt.Sprintf("%v", groupID), validMetadata, thresholdDecisionPolicyFile.Name()), }, { "correct data with percentage decision policy", - func() client.Context { - bz, _ := s.encCfg.Codec.Marshal(&sdk.TxResponse{}) - c := clitestutil.NewMockCometRPC(abci.ResponseQuery{ - Value: bz, - }) - return s.baseCtx.WithClient(c) - }, append( []string{ val.Address.String(), @@ -919,20 +739,11 @@ func (s *CLITestSuite) TestTxCreateGroupPolicy() { }, s.commonFlags..., ), - false, "", - &sdk.TxResponse{}, fmt.Sprintf("%s %s %s %s", val.Address.String(), fmt.Sprintf("%v", groupID), validMetadata, percentageDecisionPolicyFile.Name()), }, { "with amino-json", - func() client.Context { - bz, _ := s.encCfg.Codec.Marshal(&sdk.TxResponse{}) - c := clitestutil.NewMockCometRPC(abci.ResponseQuery{ - Value: bz, - }) - return s.baseCtx.WithClient(c) - }, append( []string{ val.Address.String(), @@ -943,20 +754,11 @@ func (s *CLITestSuite) TestTxCreateGroupPolicy() { }, s.commonFlags..., ), - false, "", - &sdk.TxResponse{}, fmt.Sprintf("%s %s %s %s --%s=%s", val.Address.String(), fmt.Sprintf("%v", groupID), validMetadata, thresholdDecisionPolicyFile.Name(), flags.FlagSignMode, flags.SignModeLegacyAminoJSON), }, { "wrong admin", - func() client.Context { - bz, _ := s.encCfg.Codec.Marshal(&sdk.TxResponse{}) - c := clitestutil.NewMockCometRPC(abci.ResponseQuery{ - Value: bz, - }) - return s.baseCtx.WithClient(c) - }, append( []string{ "wrongAdmin", @@ -966,20 +768,11 @@ func (s *CLITestSuite) TestTxCreateGroupPolicy() { }, s.commonFlags..., ), - true, "key not found", - &sdk.TxResponse{}, fmt.Sprintf("%s %s %s %s", "wrongAdmin", fmt.Sprintf("%v", groupID), validMetadata, thresholdDecisionPolicyFile.Name()), }, { "invalid percentage decision policy with negative value", - func() client.Context { - bz, _ := s.encCfg.Codec.Marshal(&sdk.TxResponse{}) - c := clitestutil.NewMockCometRPC(abci.ResponseQuery{ - Value: bz, - }) - return s.baseCtx.WithClient(c) - }, append( []string{ val.Address.String(), @@ -989,20 +782,11 @@ func (s *CLITestSuite) TestTxCreateGroupPolicy() { }, s.commonFlags..., ), - true, "expected a positive decimal", - &sdk.TxResponse{}, fmt.Sprintf("%s %s %s %s", val.Address.String(), fmt.Sprintf("%v", groupID), validMetadata, invalidNegativePercentageDecisionPolicyFile.Name()), }, { "invalid percentage decision policy with value greater than 1", - func() client.Context { - bz, _ := s.encCfg.Codec.Marshal(&sdk.TxResponse{}) - c := clitestutil.NewMockCometRPC(abci.ResponseQuery{ - Value: bz, - }) - return s.baseCtx.WithClient(c) - }, append( []string{ val.Address.String(), @@ -1012,9 +796,7 @@ func (s *CLITestSuite) TestTxCreateGroupPolicy() { }, s.commonFlags..., ), - true, "percentage must be > 0 and <= 1", - &sdk.TxResponse{}, fmt.Sprintf("%s %s %s %s", val.Address.String(), fmt.Sprintf("%v", groupID), validMetadata, invalidPercentageDecisionPolicyFile.Name()), }, } @@ -1023,27 +805,25 @@ func (s *CLITestSuite) TestTxCreateGroupPolicy() { tc := tc s.Run(tc.name, func() { - var outBuf bytes.Buffer - - clientCtx := tc.ctxGen().WithOutput(&outBuf) ctx := svrcmd.CreateExecuteContext(context.Background()) cmd.SetContext(ctx) cmd.SetArgs(tc.args) - s.Require().NoError(client.SetCmdClientContextHandler(clientCtx, cmd)) + s.Require().NoError(client.SetCmdClientContextHandler(s.baseCtx, cmd)) if len(tc.args) != 0 { s.Require().Contains(fmt.Sprint(cmd), tc.expCmdOutput) } - out, err := clitestutil.ExecTestCLICmd(clientCtx, cmd, tc.args) - if tc.expectErr { + out, err := clitestutil.ExecTestCLICmd(s.baseCtx, cmd, tc.args) + if tc.expectErrMsg != "" { s.Require().Error(err) s.Require().Contains(out.String(), tc.expectErrMsg) } else { s.Require().NoError(err, out.String()) - s.Require().NoError(clientCtx.Codec.UnmarshalJSON(out.Bytes(), tc.respType), out.String()) + msg := &sdk.TxResponse{} + s.Require().NoError(s.baseCtx.Codec.UnmarshalJSON(out.Bytes(), msg), out.String()) } }) } @@ -1063,19 +843,12 @@ func (s *CLITestSuite) TestTxUpdateGroupPolicyAdmin() { testCases := []struct { name string - ctxGen func() client.Context args []string expCmdOutput string + expectErrMsg string }{ { "correct data", - func() client.Context { - bz, _ := s.encCfg.Codec.Marshal(&sdk.TxResponse{}) - c := clitestutil.NewMockCometRPC(abci.ResponseQuery{ - Value: bz, - }) - return s.baseCtx.WithClient(c) - }, append( []string{ groupPolicyAdmin.Address.String(), @@ -1085,16 +858,10 @@ func (s *CLITestSuite) TestTxUpdateGroupPolicyAdmin() { commonFlags..., ), fmt.Sprintf("%s %s %s", groupPolicyAdmin.Address.String(), groupPolicyAddress.Address.String(), newAdmin.Address.String()), + "", }, { "with amino-json", - func() client.Context { - bz, _ := s.encCfg.Codec.Marshal(&sdk.TxResponse{}) - c := clitestutil.NewMockCometRPC(abci.ResponseQuery{ - Value: bz, - }) - return s.baseCtx.WithClient(c) - }, append( []string{ groupPolicyAdmin.Address.String(), @@ -1105,16 +872,10 @@ func (s *CLITestSuite) TestTxUpdateGroupPolicyAdmin() { commonFlags..., ), fmt.Sprintf("%s %s %s --%s=%s", groupPolicyAdmin.Address.String(), groupPolicyAddress.Address.String(), newAdmin.Address.String(), flags.FlagSignMode, flags.SignModeLegacyAminoJSON), + "", }, { "wrong admin", - func() client.Context { - bz, _ := s.encCfg.Codec.Marshal(&sdk.TxResponse{}) - c := clitestutil.NewMockCometRPC(abci.ResponseQuery{ - Value: bz, - }) - return s.baseCtx.WithClient(c) - }, append( []string{ "wrong admin", @@ -1124,25 +885,20 @@ func (s *CLITestSuite) TestTxUpdateGroupPolicyAdmin() { commonFlags..., ), fmt.Sprintf("%s %s %s", "wrong admin", groupPolicyAddress.Address.String(), newAdmin.Address.String()), + "key not found", }, { - "wrong group policy", - func() client.Context { - bz, _ := s.encCfg.Codec.Marshal(&sdk.TxResponse{}) - c := clitestutil.NewMockCometRPC(abci.ResponseQuery{ - Value: bz, - }) - return s.baseCtx.WithClient(c) - }, + "identical admin and new admin", append( []string{ groupPolicyAdmin.Address.String(), - "wrong group policy", - newAdmin.Address.String(), + groupPolicyAddress.Address.String(), + groupPolicyAdmin.Address.String(), }, commonFlags..., ), - fmt.Sprintf("%s %s %s", groupPolicyAdmin.Address.String(), "wrong group policy", newAdmin.Address.String()), + fmt.Sprintf("%s %s %s", groupPolicyAdmin.Address.String(), groupPolicyAddress.Address.String(), groupPolicyAdmin.Address.String()), + "new admin cannot be the same as the current admin", }, } @@ -1150,19 +906,26 @@ func (s *CLITestSuite) TestTxUpdateGroupPolicyAdmin() { tc := tc s.Run(tc.name, func() { - var outBuf bytes.Buffer - - clientCtx := tc.ctxGen().WithOutput(&outBuf) ctx := svrcmd.CreateExecuteContext(context.Background()) cmd.SetContext(ctx) cmd.SetArgs(tc.args) - s.Require().NoError(client.SetCmdClientContextHandler(clientCtx, cmd)) + s.Require().NoError(client.SetCmdClientContextHandler(s.baseCtx, cmd)) if len(tc.args) != 0 { s.Require().Contains(fmt.Sprint(cmd), tc.expCmdOutput) } + + out, err := clitestutil.ExecTestCLICmd(s.baseCtx, cmd, tc.args) + if tc.expectErrMsg != "" { + s.Require().Error(err) + s.Require().Contains(out.String(), tc.expectErrMsg) + } else { + s.Require().NoError(err) + msg := &sdk.TxResponse{} + s.Require().NoError(s.baseCtx.Codec.UnmarshalJSON(out.Bytes(), msg), out.String()) + } }) } } @@ -1178,27 +941,18 @@ func (s *CLITestSuite) TestTxUpdateGroupPolicyDecisionPolicy() { thresholdDecisionPolicy := testutil.WriteToNewTempFile(s.T(), `{"@type":"/cosmos.group.v1.ThresholdDecisionPolicy", "threshold":"1", "windows":{"voting_period":"40000s"}}`) percentageDecisionPolicy := testutil.WriteToNewTempFile(s.T(), `{"@type":"/cosmos.group.v1.PercentageDecisionPolicy", "percentage":"0.5", "windows":{"voting_period":"40000s"}}`) - invalidNegativePercentageDecisionPolicy := testutil.WriteToNewTempFile(s.T(), `{"@type":"/cosmos.group.v1.PercentageDecisionPolicy", "percentage":"-0.5", "windows":{"voting_period":"1s"}}`) - invalidPercentageDecisionPolicy := testutil.WriteToNewTempFile(s.T(), `{"@type":"/cosmos.group.v1.PercentageDecisionPolicy", "percentage":"2", "windows":{"voting_period":"40000s"}}`) - cmd := groupcli.MsgUpdateGroupPolicyDecisionPolicyCmd() + cmd := groupcli.MsgUpdateGroupPolicyDecisionPolicyCmd(address.NewBech32Codec("cosmos")) cmd.SetOutput(io.Discard) testCases := []struct { name string - ctxGen func() client.Context args []string expCmdOutput string + expectErrMsg string }{ { "correct data", - func() client.Context { - bz, _ := s.encCfg.Codec.Marshal(&sdk.TxResponse{}) - c := clitestutil.NewMockCometRPC(abci.ResponseQuery{ - Value: bz, - }) - return s.baseCtx.WithClient(c) - }, append( []string{ groupPolicyAdmin.Address.String(), @@ -1208,16 +962,10 @@ func (s *CLITestSuite) TestTxUpdateGroupPolicyDecisionPolicy() { commonFlags..., ), fmt.Sprintf("%s %s %s", groupPolicyAdmin.Address.String(), groupPolicyAddress.Address.String(), thresholdDecisionPolicy.Name()), + "", }, { "correct data with percentage decision policy", - func() client.Context { - bz, _ := s.encCfg.Codec.Marshal(&sdk.TxResponse{}) - c := clitestutil.NewMockCometRPC(abci.ResponseQuery{ - Value: bz, - }) - return s.baseCtx.WithClient(c) - }, append( []string{ groupPolicyAdmin.Address.String(), @@ -1227,16 +975,10 @@ func (s *CLITestSuite) TestTxUpdateGroupPolicyDecisionPolicy() { commonFlags..., ), fmt.Sprintf("%s %s %s", groupPolicyAdmin.Address.String(), groupPolicyAddress.Address.String(), percentageDecisionPolicy.Name()), + "", }, { "with amino-json", - func() client.Context { - bz, _ := s.encCfg.Codec.Marshal(&sdk.TxResponse{}) - c := clitestutil.NewMockCometRPC(abci.ResponseQuery{ - Value: bz, - }) - return s.baseCtx.WithClient(c) - }, append( []string{ groupPolicyAdmin.Address.String(), @@ -1247,82 +989,20 @@ func (s *CLITestSuite) TestTxUpdateGroupPolicyDecisionPolicy() { commonFlags..., ), fmt.Sprintf("%s %s %s --%s=%s", groupPolicyAdmin.Address.String(), groupPolicyAddress.Address.String(), thresholdDecisionPolicy.Name(), flags.FlagSignMode, flags.SignModeLegacyAminoJSON), + "", }, { "wrong admin", - func() client.Context { - bz, _ := s.encCfg.Codec.Marshal(&sdk.TxResponse{}) - c := clitestutil.NewMockCometRPC(abci.ResponseQuery{ - Value: bz, - }) - return s.baseCtx.WithClient(c) - }, append( []string{ newAdmin.Address.String(), - groupPolicyAddress.Address.String(), - thresholdDecisionPolicy.Name(), - }, - commonFlags..., - ), - fmt.Sprintf("%s %s %s", newAdmin.Address.String(), groupPolicyAddress.Address.String(), thresholdDecisionPolicy.Name()), - }, - { - "wrong group policy", - func() client.Context { - bz, _ := s.encCfg.Codec.Marshal(&sdk.TxResponse{}) - c := clitestutil.NewMockCometRPC(abci.ResponseQuery{ - Value: bz, - }) - return s.baseCtx.WithClient(c) - }, - append( - []string{ - groupPolicyAdmin.Address.String(), - "wrong group policy", + "invalid", thresholdDecisionPolicy.Name(), }, commonFlags..., ), - fmt.Sprintf("%s %s %s", groupPolicyAdmin.Address.String(), "wrong group policy", thresholdDecisionPolicy.Name()), - }, - { - "invalid percentage decision policy with negative value", - func() client.Context { - bz, _ := s.encCfg.Codec.Marshal(&sdk.TxResponse{}) - c := clitestutil.NewMockCometRPC(abci.ResponseQuery{ - Value: bz, - }) - return s.baseCtx.WithClient(c) - }, - append( - []string{ - groupPolicyAdmin.Address.String(), - groupPolicyAddress.Address.String(), - invalidNegativePercentageDecisionPolicy.Name(), - }, - commonFlags..., - ), - fmt.Sprintf("%s %s %s", groupPolicyAdmin.Address.String(), groupPolicyAddress.Address.String(), invalidNegativePercentageDecisionPolicy.Name()), - }, - { - "invalid percentage decision policy with value greater than 1", - func() client.Context { - bz, _ := s.encCfg.Codec.Marshal(&sdk.TxResponse{}) - c := clitestutil.NewMockCometRPC(abci.ResponseQuery{ - Value: bz, - }) - return s.baseCtx.WithClient(c) - }, - append( - []string{ - groupPolicyAdmin.Address.String(), - groupPolicyAddress.Address.String(), - invalidPercentageDecisionPolicy.Name(), - }, - commonFlags..., - ), - fmt.Sprintf("%s %s %s", groupPolicyAdmin.Address.String(), groupPolicyAddress.Address.String(), invalidPercentageDecisionPolicy.Name()), + fmt.Sprintf("%s %s %s", newAdmin.Address.String(), "invalid", thresholdDecisionPolicy.Name()), + "decoding bech32 failed", }, } @@ -1330,19 +1010,26 @@ func (s *CLITestSuite) TestTxUpdateGroupPolicyDecisionPolicy() { tc := tc s.Run(tc.name, func() { - var outBuf bytes.Buffer - - clientCtx := tc.ctxGen().WithOutput(&outBuf) ctx := svrcmd.CreateExecuteContext(context.Background()) cmd.SetContext(ctx) cmd.SetArgs(tc.args) - s.Require().NoError(client.SetCmdClientContextHandler(clientCtx, cmd)) + s.Require().NoError(client.SetCmdClientContextHandler(s.baseCtx, cmd)) if len(tc.args) != 0 { s.Require().Contains(fmt.Sprint(cmd), tc.expCmdOutput) } + + out, err := clitestutil.ExecTestCLICmd(s.baseCtx, cmd, tc.args) + if tc.expectErrMsg != "" { + s.Require().Error(err) + s.Require().Contains(out.String(), tc.expectErrMsg) + } else { + s.Require().NoError(err) + msg := &sdk.TxResponse{} + s.Require().NoError(s.baseCtx.Codec.UnmarshalJSON(out.Bytes(), msg), out.String()) + } }) } } @@ -1360,19 +1047,12 @@ func (s *CLITestSuite) TestTxUpdateGroupPolicyMetadata() { testCases := []struct { name string - ctxGen func() client.Context args []string expCmdOutput string + expectErrMsg string }{ { "correct data", - func() client.Context { - bz, _ := s.encCfg.Codec.Marshal(&sdk.TxResponse{}) - c := clitestutil.NewMockCometRPC(abci.ResponseQuery{ - Value: bz, - }) - return s.baseCtx.WithClient(c) - }, append( []string{ groupPolicyAdmin.String(), @@ -1382,16 +1062,10 @@ func (s *CLITestSuite) TestTxUpdateGroupPolicyMetadata() { commonFlags..., ), fmt.Sprintf("%s %s %s", groupPolicyAdmin.String(), groupPolicyAddress.String(), validMetadata), + "", }, { "with amino-json", - func() client.Context { - bz, _ := s.encCfg.Codec.Marshal(&sdk.TxResponse{}) - c := clitestutil.NewMockCometRPC(abci.ResponseQuery{ - Value: bz, - }) - return s.baseCtx.WithClient(c) - }, append( []string{ groupPolicyAdmin.String(), @@ -1402,35 +1076,10 @@ func (s *CLITestSuite) TestTxUpdateGroupPolicyMetadata() { commonFlags..., ), fmt.Sprintf("%s %s %s --%s=%s", groupPolicyAdmin.String(), groupPolicyAddress.String(), validMetadata, flags.FlagSignMode, flags.SignModeLegacyAminoJSON), - }, - { - "long metadata", - func() client.Context { - bz, _ := s.encCfg.Codec.Marshal(&sdk.TxResponse{}) - c := clitestutil.NewMockCometRPC(abci.ResponseQuery{ - Value: bz, - }) - return s.baseCtx.WithClient(c) - }, - append( - []string{ - groupPolicyAdmin.String(), - groupPolicyAddress.String(), - strings.Repeat("a", 500), - }, - commonFlags..., - ), - fmt.Sprintf("%s %s %s", groupPolicyAdmin.String(), groupPolicyAddress.String(), strings.Repeat("a", 500)), + "", }, { "wrong admin", - func() client.Context { - bz, _ := s.encCfg.Codec.Marshal(&sdk.TxResponse{}) - c := clitestutil.NewMockCometRPC(abci.ResponseQuery{ - Value: bz, - }) - return s.baseCtx.WithClient(c) - }, append( []string{ "wrong admin", @@ -1440,25 +1089,7 @@ func (s *CLITestSuite) TestTxUpdateGroupPolicyMetadata() { commonFlags..., ), fmt.Sprintf("%s %s %s", "wrong admin", groupPolicyAddress.String(), validMetadata), - }, - { - "wrong group policy", - func() client.Context { - bz, _ := s.encCfg.Codec.Marshal(&sdk.TxResponse{}) - c := clitestutil.NewMockCometRPC(abci.ResponseQuery{ - Value: bz, - }) - return s.baseCtx.WithClient(c) - }, - append( - []string{ - groupPolicyAdmin.String(), - "wrong group policy", - validMetadata, - }, - commonFlags..., - ), - fmt.Sprintf("%s %s %s", groupPolicyAdmin.String(), "wrong group policy", validMetadata), + "key not found", }, } @@ -1466,19 +1097,26 @@ func (s *CLITestSuite) TestTxUpdateGroupPolicyMetadata() { tc := tc s.Run(tc.name, func() { - var outBuf bytes.Buffer - - clientCtx := tc.ctxGen().WithOutput(&outBuf) ctx := svrcmd.CreateExecuteContext(context.Background()) cmd.SetContext(ctx) cmd.SetArgs(tc.args) - s.Require().NoError(client.SetCmdClientContextHandler(clientCtx, cmd)) + s.Require().NoError(client.SetCmdClientContextHandler(s.baseCtx, cmd)) if len(tc.args) != 0 { s.Require().Contains(fmt.Sprint(cmd), tc.expCmdOutput) } + + out, err := clitestutil.ExecTestCLICmd(s.baseCtx, cmd, tc.args) + if tc.expectErrMsg != "" { + s.Require().Error(err) + s.Require().Contains(out.String(), tc.expectErrMsg) + } else { + s.Require().NoError(err) + msg := &sdk.TxResponse{} + s.Require().NoError(s.baseCtx.Codec.UnmarshalJSON(out.Bytes(), msg), out.String()) + } }) } } @@ -1502,19 +1140,12 @@ func (s *CLITestSuite) TestTxSubmitProposal() { testCases := []struct { name string - ctxGen func() client.Context args []string expCmdOutput string + expectErrMsg string }{ { "correct data", - func() client.Context { - bz, _ := s.encCfg.Codec.Marshal(&sdk.TxResponse{}) - c := clitestutil.NewMockCometRPC(abci.ResponseQuery{ - Value: bz, - }) - return s.baseCtx.WithClient(c) - }, append( []string{ proposalFile.Name(), @@ -1522,16 +1153,10 @@ func (s *CLITestSuite) TestTxSubmitProposal() { s.commonFlags..., ), proposalFile.Name(), + "", }, { "with try exec", - func() client.Context { - bz, _ := s.encCfg.Codec.Marshal(&sdk.TxResponse{}) - c := clitestutil.NewMockCometRPC(abci.ResponseQuery{ - Value: bz, - }) - return s.baseCtx.WithClient(c) - }, append( []string{ proposalFile.Name(), @@ -1540,16 +1165,10 @@ func (s *CLITestSuite) TestTxSubmitProposal() { s.commonFlags..., ), fmt.Sprintf("%s --%s=try", proposalFile.Name(), groupcli.FlagExec), + "", }, { "with try exec, not enough yes votes for proposal to pass", - func() client.Context { - bz, _ := s.encCfg.Codec.Marshal(&sdk.TxResponse{}) - c := clitestutil.NewMockCometRPC(abci.ResponseQuery{ - Value: bz, - }) - return s.baseCtx.WithClient(c) - }, append( []string{ proposalFile.Name(), @@ -1558,16 +1177,10 @@ func (s *CLITestSuite) TestTxSubmitProposal() { s.commonFlags..., ), fmt.Sprintf("%s --%s=try", proposalFile.Name(), groupcli.FlagExec), + "", }, { "with amino-json", - func() client.Context { - bz, _ := s.encCfg.Codec.Marshal(&sdk.TxResponse{}) - c := clitestutil.NewMockCometRPC(abci.ResponseQuery{ - Value: bz, - }) - return s.baseCtx.WithClient(c) - }, append( []string{ proposalFile.Name(), @@ -1576,6 +1189,7 @@ func (s *CLITestSuite) TestTxSubmitProposal() { s.commonFlags..., ), fmt.Sprintf("%s --%s=%s", proposalFile.Name(), flags.FlagSignMode, flags.SignModeLegacyAminoJSON), + "", }, } @@ -1583,19 +1197,26 @@ func (s *CLITestSuite) TestTxSubmitProposal() { tc := tc s.Run(tc.name, func() { - var outBuf bytes.Buffer - - clientCtx := tc.ctxGen().WithOutput(&outBuf) ctx := svrcmd.CreateExecuteContext(context.Background()) cmd.SetContext(ctx) cmd.SetArgs(tc.args) - s.Require().NoError(client.SetCmdClientContextHandler(clientCtx, cmd)) + s.Require().NoError(client.SetCmdClientContextHandler(s.baseCtx, cmd)) if len(tc.args) != 0 { s.Require().Contains(fmt.Sprint(cmd), tc.expCmdOutput) } + + out, err := clitestutil.ExecTestCLICmd(s.baseCtx, cmd, tc.args) + if tc.expectErrMsg != "" { + s.Require().Error(err) + s.Require().Contains(out.String(), tc.expectErrMsg) + } else { + s.Require().NoError(err) + msg := &sdk.TxResponse{} + s.Require().NoError(s.baseCtx.Codec.UnmarshalJSON(out.Bytes(), msg), out.String()) + } }) } } @@ -1613,19 +1234,26 @@ func (s *CLITestSuite) TestTxVote() { testCases := []struct { name string - ctxGen func() client.Context args []string expCmdOutput string + expectErrMsg string }{ + { + "invalid vote", + append( + []string{ + ids[0], + accounts[0].Address.String(), + "AYE", + "", + }, + s.commonFlags..., + ), + fmt.Sprintf("%s %s %s", ids[0], accounts[0].Address.String(), "AYE"), + "Error: 'AYE' is not a valid vote option", + }, { "correct data", - func() client.Context { - bz, _ := s.encCfg.Codec.Marshal(&sdk.TxResponse{}) - c := clitestutil.NewMockCometRPC(abci.ResponseQuery{ - Value: bz, - }) - return s.baseCtx.WithClient(c) - }, append( []string{ ids[0], @@ -1636,16 +1264,10 @@ func (s *CLITestSuite) TestTxVote() { s.commonFlags..., ), fmt.Sprintf("%s %s %s", ids[0], accounts[0].Address.String(), "VOTE_OPTION_YES"), + "", }, { "with try exec", - func() client.Context { - bz, _ := s.encCfg.Codec.Marshal(&sdk.TxResponse{}) - c := clitestutil.NewMockCometRPC(abci.ResponseQuery{ - Value: bz, - }) - return s.baseCtx.WithClient(c) - }, append( []string{ ids[1], @@ -1657,16 +1279,10 @@ func (s *CLITestSuite) TestTxVote() { s.commonFlags..., ), fmt.Sprintf("%s %s %s %s --%s=try", ids[1], accounts[0].Address.String(), "VOTE_OPTION_YES", "", groupcli.FlagExec), + "", }, { "with amino-json", - func() client.Context { - bz, _ := s.encCfg.Codec.Marshal(&sdk.TxResponse{}) - c := clitestutil.NewMockCometRPC(abci.ResponseQuery{ - Value: bz, - }) - return s.baseCtx.WithClient(c) - }, append( []string{ ids[3], @@ -1678,26 +1294,7 @@ func (s *CLITestSuite) TestTxVote() { s.commonFlags..., ), fmt.Sprintf("%s %s %s %s --%s=%s", ids[3], accounts[0].Address.String(), "VOTE_OPTION_YES", "", flags.FlagSignMode, flags.SignModeLegacyAminoJSON), - }, - { - "metadata too long", - func() client.Context { - bz, _ := s.encCfg.Codec.Marshal(&sdk.TxResponse{}) - c := clitestutil.NewMockCometRPC(abci.ResponseQuery{ - Value: bz, - }) - return s.baseCtx.WithClient(c) - }, - append( - []string{ - ids[2], - accounts[0].Address.String(), - "VOTE_OPTION_YES", - tooLongMetadata, - }, - s.commonFlags..., - ), - fmt.Sprintf("%s %s %s %s", ids[2], accounts[0].Address.String(), "VOTE_OPTION_YES", tooLongMetadata), + "", }, } @@ -1705,19 +1302,26 @@ func (s *CLITestSuite) TestTxVote() { tc := tc s.Run(tc.name, func() { - var outBuf bytes.Buffer - - clientCtx := tc.ctxGen().WithOutput(&outBuf) ctx := svrcmd.CreateExecuteContext(context.Background()) cmd.SetContext(ctx) cmd.SetArgs(tc.args) - s.Require().NoError(client.SetCmdClientContextHandler(clientCtx, cmd)) + s.Require().NoError(client.SetCmdClientContextHandler(s.baseCtx, cmd)) if len(tc.args) != 0 { s.Require().Contains(fmt.Sprint(cmd), tc.expCmdOutput) } + + out, err := clitestutil.ExecTestCLICmd(s.baseCtx, cmd, tc.args) + if tc.expectErrMsg != "" { + s.Require().Error(err) + s.Require().Contains(out.String(), tc.expectErrMsg) + } else { + s.Require().NoError(err) + msg := &sdk.TxResponse{} + s.Require().NoError(s.baseCtx.Codec.UnmarshalJSON(out.Bytes(), msg), out.String()) + } }) } } @@ -1734,19 +1338,12 @@ func (s *CLITestSuite) TestTxWithdrawProposal() { testCases := []struct { name string - ctxGen func() client.Context args []string expCmdOutput string + expectErrMsg string }{ { "correct data", - func() client.Context { - bz, _ := s.encCfg.Codec.Marshal(&sdk.TxResponse{}) - c := clitestutil.NewMockCometRPC(abci.ResponseQuery{ - Value: bz, - }) - return s.baseCtx.WithClient(c) - }, append( []string{ ids[0], @@ -1755,16 +1352,10 @@ func (s *CLITestSuite) TestTxWithdrawProposal() { s.commonFlags..., ), fmt.Sprintf("%s %s", ids[0], accounts[0].Address.String()), + "", }, { "wrong admin", - func() client.Context { - bz, _ := s.encCfg.Codec.Marshal(&sdk.TxResponse{}) - c := clitestutil.NewMockCometRPC(abci.ResponseQuery{ - Value: bz, - }) - return s.baseCtx.WithClient(c) - }, append( []string{ ids[1], @@ -1773,6 +1364,19 @@ func (s *CLITestSuite) TestTxWithdrawProposal() { s.commonFlags..., ), fmt.Sprintf("%s %s", ids[1], "wrongAdmin"), + "key not found", + }, + { + "wrong proposal id", + append( + []string{ + "abc", + accounts[0].Address.String(), + }, + s.commonFlags..., + ), + fmt.Sprintf("%s %s", "abc", accounts[0].Address.String()), + "Error: strconv.ParseUint: parsing \"abc\"", }, } @@ -1780,19 +1384,26 @@ func (s *CLITestSuite) TestTxWithdrawProposal() { tc := tc s.Run(tc.name, func() { - var outBuf bytes.Buffer - - clientCtx := tc.ctxGen().WithOutput(&outBuf) ctx := svrcmd.CreateExecuteContext(context.Background()) cmd.SetContext(ctx) cmd.SetArgs(tc.args) - s.Require().NoError(client.SetCmdClientContextHandler(clientCtx, cmd)) + s.Require().NoError(client.SetCmdClientContextHandler(s.baseCtx, cmd)) if len(tc.args) != 0 { s.Require().Contains(fmt.Sprint(cmd), tc.expCmdOutput) } + + out, err := clitestutil.ExecTestCLICmd(s.baseCtx, cmd, tc.args) + if tc.expectErrMsg != "" { + s.Require().Error(err) + s.Require().Contains(out.String(), tc.expectErrMsg) + } else { + s.Require().NoError(err) + msg := &sdk.TxResponse{} + s.Require().NoError(s.baseCtx.Codec.UnmarshalJSON(out.Bytes(), msg), out.String()) + } }) } } diff --git a/x/group/client/cli/util.go b/x/group/client/cli/util.go index 7bd2bdb3b55f..65ad49425a54 100644 --- a/x/group/client/cli/util.go +++ b/x/group/client/cli/util.go @@ -31,7 +31,9 @@ func parseDecisionPolicy(cdc codec.Codec, decisionPolicyFile string) (group.Deci // parseMembers reads and parses the members. func parseMembers(membersFile string) ([]group.MemberRequest, error) { - members := group.MemberRequests{} + members := struct { + Members []group.MemberRequest `json:"members"` + }{} if membersFile == "" { return members.Members, nil @@ -42,8 +44,7 @@ func parseMembers(membersFile string) ([]group.MemberRequest, error) { return nil, err } - err = json.Unmarshal(contents, &members) - if err != nil { + if err := json.Unmarshal(contents, &members); err != nil { return nil, err } diff --git a/x/group/expected_keepers.go b/x/group/expected_keepers.go index 31334a3413b7..e346fd513652 100644 --- a/x/group/expected_keepers.go +++ b/x/group/expected_keepers.go @@ -1,21 +1,26 @@ package group import ( + context "context" + + "cosmossdk.io/core/address" sdk "github.com/cosmos/cosmos-sdk/types" ) type AccountKeeper interface { + address.Codec + // NewAccount returns a new account with the next account number. Does not save the new account to the store. - NewAccount(sdk.Context, sdk.AccountI) sdk.AccountI + NewAccount(context.Context, sdk.AccountI) sdk.AccountI // GetAccount retrieves an account from the store. - GetAccount(sdk.Context, sdk.AccAddress) sdk.AccountI + GetAccount(context.Context, sdk.AccAddress) sdk.AccountI // SetAccount sets an account in the store. - SetAccount(sdk.Context, sdk.AccountI) + SetAccount(context.Context, sdk.AccountI) // RemoveAccount Remove an account in the store. - RemoveAccount(ctx sdk.Context, acc sdk.AccountI) + RemoveAccount(ctx context.Context, acc sdk.AccountI) } // BankKeeper defines the expected interface needed to retrieve account balances. diff --git a/x/group/internal/math/dec.go b/x/group/internal/math/dec.go index bdf19691c2bc..650acf337880 100644 --- a/x/group/internal/math/dec.go +++ b/x/group/internal/math/dec.go @@ -105,7 +105,7 @@ func (x Dec) IsNegative() bool { } // Add adds x and y -func Add(x Dec, y Dec) (Dec, error) { +func Add(x, y Dec) (Dec, error) { return x.Add(y) } @@ -130,7 +130,7 @@ func (x Dec) IsZero() bool { // SubNonNegative subtracts the value of y from x and returns the result with // arbitrary precision. Returns an error if the result is negative. -func SubNonNegative(x Dec, y Dec) (Dec, error) { +func SubNonNegative(x, y Dec) (Dec, error) { z, err := x.Sub(y) if err != nil { return Dec{}, err diff --git a/x/group/internal/math/dec_test.go b/x/group/internal/math/dec_test.go index 27757b01e992..c52f2219f8d9 100644 --- a/x/group/internal/math/dec_test.go +++ b/x/group/internal/math/dec_test.go @@ -2,8 +2,6 @@ package math import ( "fmt" - "regexp" - "strconv" "testing" "github.com/stretchr/testify/require" @@ -257,41 +255,3 @@ func testIsNegative(t *rapid.T) { require.Equal(t, f < 0, dec.IsNegative()) } - -func floatDecimalPlaces(t *rapid.T, f float64) uint32 { //nolint:unused - reScientific := regexp.MustCompile(`^\-?(?:[[:digit:]]+(?:\.([[:digit:]]+))?|\.([[:digit:]]+))(?:e?(?:\+?([[:digit:]]+)|(-[[:digit:]]+)))?$`) - fStr := fmt.Sprintf("%g", f) - matches := reScientific.FindAllStringSubmatch(fStr, 1) - if len(matches) != 1 { - t.Fatalf("Didn't match float: %g", f) - } - - // basePlaces is the number of decimal places in the decimal part of the - // string - basePlaces := 0 - if matches[0][1] != "" { - basePlaces = len(matches[0][1]) - } else if matches[0][2] != "" { - basePlaces = len(matches[0][2]) - } - t.Logf("Base places: %d", basePlaces) - - // exp is the exponent - exp := 0 - if matches[0][3] != "" { - var err error - exp, err = strconv.Atoi(matches[0][3]) - require.NoError(t, err) - } else if matches[0][4] != "" { - var err error - exp, err = strconv.Atoi(matches[0][4]) - require.NoError(t, err) - } - - // Subtract exponent from base and check if negative - if res := basePlaces - exp; res <= 0 { - return 0 - } else { //nolint:revive - return uint32(res) - } -} diff --git a/x/group/internal/orm/auto_uint64.go b/x/group/internal/orm/auto_uint64.go index bb081f0a3dd0..98b924f5533a 100644 --- a/x/group/internal/orm/auto_uint64.go +++ b/x/group/internal/orm/auto_uint64.go @@ -112,7 +112,7 @@ func (a AutoUInt64Table) PrefixScan(store storetypes.KVStore, start, end uint64) // this as an endpoint to the public without further limits. See `LimitIterator` // // CONTRACT: No writes may happen within a domain while an iterator exists over it. -func (a AutoUInt64Table) ReversePrefixScan(store storetypes.KVStore, start uint64, end uint64) (Iterator, error) { +func (a AutoUInt64Table) ReversePrefixScan(store storetypes.KVStore, start, end uint64) (Iterator, error) { return a.table.ReversePrefixScan(store, EncodeSequence(start), EncodeSequence(end)) } diff --git a/x/group/internal/orm/auto_uint64_test.go b/x/group/internal/orm/auto_uint64_test.go index 2296c86d021f..079b137c46c1 100644 --- a/x/group/internal/orm/auto_uint64_test.go +++ b/x/group/internal/orm/auto_uint64_test.go @@ -52,7 +52,7 @@ func TestAutoUInt64PrefixScan(t *testing.T) { expResult []testdata.TableModel expRowIDs []RowID expError *errorsmod.Error - method func(store storetypes.KVStore, start uint64, end uint64) (Iterator, error) + method func(store storetypes.KVStore, start, end uint64) (Iterator, error) }{ "first element": { start: 1, diff --git a/x/group/internal/orm/index.go b/x/group/internal/orm/index.go index b5ab7d95898a..7564f4705bec 100644 --- a/x/group/internal/orm/index.go +++ b/x/group/internal/orm/index.go @@ -134,7 +134,7 @@ func (i MultiKeyIndex) GetPaginated(store types.KVStore, searchKey interface{}, // it = LimitIterator(it, defaultLimit) // // CONTRACT: No writes may happen within a domain while an iterator exists over it. -func (i MultiKeyIndex) PrefixScan(store types.KVStore, startI interface{}, endI interface{}) (Iterator, error) { +func (i MultiKeyIndex) PrefixScan(store types.KVStore, startI, endI interface{}) (Iterator, error) { start, end, err := getStartEndBz(startI, endI) if err != nil { return nil, err @@ -154,7 +154,7 @@ func (i MultiKeyIndex) PrefixScan(store types.KVStore, startI interface{}, endI // this as an endpoint to the public without further limits. See `LimitIterator` // // CONTRACT: No writes may happen within a domain while an iterator exists over it. -func (i MultiKeyIndex) ReversePrefixScan(store types.KVStore, startI interface{}, endI interface{}) (Iterator, error) { +func (i MultiKeyIndex) ReversePrefixScan(store types.KVStore, startI, endI interface{}) (Iterator, error) { start, end, err := getStartEndBz(startI, endI) if err != nil { return nil, err @@ -167,7 +167,7 @@ func (i MultiKeyIndex) ReversePrefixScan(store types.KVStore, startI interface{} // getStartEndBz gets the start and end bytes to be passed into the SDK store // iterator. -func getStartEndBz(startI interface{}, endI interface{}) ([]byte, []byte, error) { +func getStartEndBz(startI, endI interface{}) ([]byte, []byte, error) { start, err := getPrefixScanKeyBytes(startI) if err != nil { return nil, nil, err diff --git a/x/group/internal/orm/indexer.go b/x/group/internal/orm/indexer.go index 6dcdf4e519e4..a3600c6c8b4d 100644 --- a/x/group/internal/orm/indexer.go +++ b/x/group/internal/orm/indexer.go @@ -177,7 +177,7 @@ func multiKeyAddFunc(store storetypes.KVStore, secondaryIndexKey interface{}, ro } // difference returns the list of elements that are in a but not in b. -func difference(a []interface{}, b []interface{}) ([]interface{}, error) { +func difference(a, b []interface{}) ([]interface{}, error) { set := make(map[interface{}]struct{}, len(b)) for _, v := range b { bt, err := keyPartBytes(v, true) diff --git a/x/group/internal/orm/iterator.go b/x/group/internal/orm/iterator.go index c83d588064a1..7f96b6a4b907 100644 --- a/x/group/internal/orm/iterator.go +++ b/x/group/internal/orm/iterator.go @@ -273,7 +273,7 @@ func ReadAll(it Iterator, dest ModelSlicePtr) ([]RowID, error) { // assertDest checks that the provided dest is not nil and a pointer to a slice. // It also verifies that the slice elements implement *codec.ProtoMarshaler. // It overwrites destRef and tmpSlice using reflection. -func assertDest(dest ModelSlicePtr, destRef *reflect.Value, tmpSlice *reflect.Value) (reflect.Type, error) { +func assertDest(dest ModelSlicePtr, destRef, tmpSlice *reflect.Value) (reflect.Type, error) { if dest == nil { return nil, errorsmod.Wrap(errors.ErrORMInvalidArgument, "destination must not be nil") } diff --git a/x/group/internal/orm/primary_key_property_test.go b/x/group/internal/orm/primary_key_property_test.go index 7a40cf8c2dc5..0149531af301 100644 --- a/x/group/internal/orm/primary_key_property_test.go +++ b/x/group/internal/orm/primary_key_property_test.go @@ -18,7 +18,7 @@ func TestPrimaryKeyTable(t *testing.T) { } // primaryKeyMachine is a state machine model of the PrimaryKeyTable. The state -// is modelled as a map of strings to TableModels. +// is modeled as a map of strings to TableModels. type primaryKeyMachine struct { store storetypes.KVStore table *PrimaryKeyTable diff --git a/x/group/internal/orm/types.go b/x/group/internal/orm/types.go index c3f357a6a3d7..da6f2c6a1ba9 100644 --- a/x/group/internal/orm/types.go +++ b/x/group/internal/orm/types.go @@ -64,7 +64,7 @@ type Index interface { // it = LimitIterator(it, defaultLimit) // // CONTRACT: No writes may happen within a domain while an iterator exists over it. - PrefixScan(store storetypes.KVStore, startI interface{}, endI interface{}) (Iterator, error) + PrefixScan(store storetypes.KVStore, startI, endI interface{}) (Iterator, error) // ReversePrefixScan returns an Iterator over a domain of keys in descending order. End is exclusive. // Start is an MultiKeyIndex key or prefix. It must be less than end, or the Iterator is invalid and error is returned. @@ -75,7 +75,7 @@ type Index interface { // this as an endpoint to the public without further limits. See `LimitIterator` // // CONTRACT: No writes may happen within a domain while an iterator exists over it. - ReversePrefixScan(store storetypes.KVStore, startI interface{}, endI interface{}) (Iterator, error) + ReversePrefixScan(store storetypes.KVStore, startI, endI interface{}) (Iterator, error) } // Iterator allows iteration through a sequence of key value pairs diff --git a/x/group/keeper/genesis_test.go b/x/group/keeper/genesis_test.go index 33a59cb52312..109cc1c2cf68 100644 --- a/x/group/keeper/genesis_test.go +++ b/x/group/keeper/genesis_test.go @@ -55,6 +55,10 @@ func (s *GenesisTestSuite) SetupTest() { accountKeeper := grouptestutil.NewMockAccountKeeper(ctrl) accountKeeper.EXPECT().GetAccount(gomock.Any(), accAddr).Return(authtypes.NewBaseAccountWithAddress(accAddr)).AnyTimes() accountKeeper.EXPECT().GetAccount(gomock.Any(), memberAddr).Return(authtypes.NewBaseAccountWithAddress(memberAddr)).AnyTimes() + accountKeeper.EXPECT().BytesToString(accAddr).Return(accAddr.String(), nil).AnyTimes() + accountKeeper.EXPECT().StringToBytes(accAddr.String()).Return(accAddr, nil).AnyTimes() + accountKeeper.EXPECT().BytesToString(memberAddr).Return(memberAddr.String(), nil).AnyTimes() + accountKeeper.EXPECT().StringToBytes(memberAddr.String()).Return(memberAddr, nil).AnyTimes() bApp := baseapp.NewBaseApp( "group", @@ -210,7 +214,7 @@ func (s *GenesisTestSuite) TestInitExportGenesis() { s.Require().Equal(genesisState.ProposalSeq, exportedGenesisState.ProposalSeq) } -func (s *GenesisTestSuite) assertGroupPoliciesEqual(g *group.GroupPolicyInfo, other *group.GroupPolicyInfo) { +func (s *GenesisTestSuite) assertGroupPoliciesEqual(g, other *group.GroupPolicyInfo) { require := s.Require() require.Equal(g.Address, other.Address) require.Equal(g.GroupId, other.GroupId) @@ -224,7 +228,7 @@ func (s *GenesisTestSuite) assertGroupPoliciesEqual(g *group.GroupPolicyInfo, ot require.Equal(dp1, dp2) } -func (s *GenesisTestSuite) assertProposalsEqual(g *group.Proposal, other *group.Proposal) { +func (s *GenesisTestSuite) assertProposalsEqual(g, other *group.Proposal) { require := s.Require() require.Equal(g.Id, other.Id) require.Equal(g.GroupPolicyAddress, other.GroupPolicyAddress) diff --git a/x/group/keeper/grpc_query.go b/x/group/keeper/grpc_query.go index a54e3bedf293..aeabe5ca4700 100644 --- a/x/group/keeper/grpc_query.go +++ b/x/group/keeper/grpc_query.go @@ -83,7 +83,7 @@ func (k Keeper) getGroupMembers(ctx sdk.Context, id uint64, pageRequest *query.P // GroupsByAdmin queries all groups where a given address is admin. func (k Keeper) GroupsByAdmin(goCtx context.Context, request *group.QueryGroupsByAdminRequest) (*group.QueryGroupsByAdminResponse, error) { ctx := sdk.UnwrapSDKContext(goCtx) - addr, err := sdk.AccAddressFromBech32(request.Admin) + addr, err := k.accKeeper.StringToBytes(request.Admin) if err != nil { return nil, err } @@ -139,7 +139,7 @@ func (k Keeper) getGroupPoliciesByGroup(ctx sdk.Context, id uint64, pageRequest // admin. func (k Keeper) GroupPoliciesByAdmin(goCtx context.Context, request *group.QueryGroupPoliciesByAdminRequest) (*group.QueryGroupPoliciesByAdminResponse, error) { ctx := sdk.UnwrapSDKContext(goCtx) - addr, err := sdk.AccAddressFromBech32(request.Admin) + addr, err := k.accKeeper.StringToBytes(request.Admin) if err != nil { return nil, err } @@ -180,7 +180,7 @@ func (k Keeper) Proposal(goCtx context.Context, request *group.QueryProposalRequ // ProposalsByGroupPolicy queries all proposals of a group policy. func (k Keeper) ProposalsByGroupPolicy(goCtx context.Context, request *group.QueryProposalsByGroupPolicyRequest) (*group.QueryProposalsByGroupPolicyResponse, error) { ctx := sdk.UnwrapSDKContext(goCtx) - addr, err := sdk.AccAddressFromBech32(request.Address) + addr, err := k.accKeeper.StringToBytes(request.Address) if err != nil { return nil, err } @@ -218,7 +218,7 @@ func (k Keeper) getProposal(ctx sdk.Context, proposalID uint64) (group.Proposal, // VoteByProposalVoter queries a vote given a voter and a proposal ID. func (k Keeper) VoteByProposalVoter(goCtx context.Context, request *group.QueryVoteByProposalVoterRequest) (*group.QueryVoteByProposalVoterResponse, error) { ctx := sdk.UnwrapSDKContext(goCtx) - addr, err := sdk.AccAddressFromBech32(request.Voter) + addr, err := k.accKeeper.StringToBytes(request.Voter) if err != nil { return nil, err } @@ -256,7 +256,7 @@ func (k Keeper) VotesByProposal(goCtx context.Context, request *group.QueryVotes // VotesByVoter queries all votes of a voter. func (k Keeper) VotesByVoter(goCtx context.Context, request *group.QueryVotesByVoterRequest) (*group.QueryVotesByVoterResponse, error) { ctx := sdk.UnwrapSDKContext(goCtx) - addr, err := sdk.AccAddressFromBech32(request.Voter) + addr, err := k.accKeeper.StringToBytes(request.Voter) if err != nil { return nil, err } @@ -284,12 +284,12 @@ func (k Keeper) GroupsByMember(goCtx context.Context, request *group.QueryGroups } ctx := sdk.UnwrapSDKContext(goCtx) - member, err := sdk.AccAddressFromBech32(request.Address) + member, err := k.accKeeper.StringToBytes(request.Address) if err != nil { return nil, err } - iter, err := k.groupMemberByMemberIndex.GetPaginated(ctx.KVStore(k.key), member.Bytes(), request.Pagination) + iter, err := k.groupMemberByMemberIndex.GetPaginated(ctx.KVStore(k.key), member, request.Pagination) if err != nil { return nil, err } diff --git a/x/group/keeper/grpc_query_test.go b/x/group/keeper/grpc_query_test.go index a57165751511..ed37c6928a16 100644 --- a/x/group/keeper/grpc_query_test.go +++ b/x/group/keeper/grpc_query_test.go @@ -46,12 +46,11 @@ func initKeeper(t *testing.T) (types.Context, groupkeeper.Keeper, []types.AccAdd addrs := simtestutil.CreateIncrementalAccounts(6) ctrl := gomock.NewController(t) accountKeeper := grouptestutil.NewMockAccountKeeper(ctrl) - accountKeeper.EXPECT().GetAccount(gomock.Any(), addrs[0]).Return(authtypes.NewBaseAccountWithAddress(addrs[0])).AnyTimes() - accountKeeper.EXPECT().GetAccount(gomock.Any(), addrs[1]).Return(authtypes.NewBaseAccountWithAddress(addrs[1])).AnyTimes() - accountKeeper.EXPECT().GetAccount(gomock.Any(), addrs[2]).Return(authtypes.NewBaseAccountWithAddress(addrs[2])).AnyTimes() - accountKeeper.EXPECT().GetAccount(gomock.Any(), addrs[3]).Return(authtypes.NewBaseAccountWithAddress(addrs[3])).AnyTimes() - accountKeeper.EXPECT().GetAccount(gomock.Any(), addrs[4]).Return(authtypes.NewBaseAccountWithAddress(addrs[4])).AnyTimes() - accountKeeper.EXPECT().GetAccount(gomock.Any(), addrs[5]).Return(authtypes.NewBaseAccountWithAddress(addrs[5])).AnyTimes() + for _, addr := range addrs { + accountKeeper.EXPECT().GetAccount(gomock.Any(), addr).Return(authtypes.NewBaseAccountWithAddress(addr)).AnyTimes() + accountKeeper.EXPECT().BytesToString(addr).Return(addr.String(), nil).AnyTimes() + accountKeeper.EXPECT().StringToBytes(addr.String()).Return(addr, nil).AnyTimes() + } groupKeeper = groupkeeper.NewKeeper(key, encCfg.Codec, bApp.MsgServiceRouter(), accountKeeper, group.DefaultConfig()) diff --git a/x/group/keeper/keeper.go b/x/group/keeper/keeper.go index 73df21e9372f..c3b705b2c369 100644 --- a/x/group/keeper/keeper.go +++ b/x/group/keeper/keeper.go @@ -94,11 +94,11 @@ func NewKeeper(storeKey storetypes.StoreKey, cdc codec.Codec, router baseapp.Mes panic(err.Error()) } k.groupByAdminIndex, err = orm.NewIndex(groupTable, GroupByAdminIndexPrefix, func(val interface{}) ([]interface{}, error) { - addr, err := sdk.AccAddressFromBech32(val.(*group.GroupInfo).Admin) + addr, err := accKeeper.StringToBytes(val.(*group.GroupInfo).Admin) if err != nil { return nil, err } - return []interface{}{addr.Bytes()}, nil + return []interface{}{addr}, nil }, []byte{}) if err != nil { panic(err.Error()) @@ -119,11 +119,11 @@ func NewKeeper(storeKey storetypes.StoreKey, cdc codec.Codec, router baseapp.Mes } k.groupMemberByMemberIndex, err = orm.NewIndex(groupMemberTable, GroupMemberByMemberIndexPrefix, func(val interface{}) ([]interface{}, error) { memberAddr := val.(*group.GroupMember).Member.Address - addr, err := sdk.AccAddressFromBech32(memberAddr) + addr, err := accKeeper.StringToBytes(memberAddr) if err != nil { return nil, err } - return []interface{}{addr.Bytes()}, nil + return []interface{}{addr}, nil }, []byte{}) if err != nil { panic(err.Error()) @@ -144,11 +144,11 @@ func NewKeeper(storeKey storetypes.StoreKey, cdc codec.Codec, router baseapp.Mes } k.groupPolicyByAdminIndex, err = orm.NewIndex(groupPolicyTable, GroupPolicyByAdminIndexPrefix, func(value interface{}) ([]interface{}, error) { admin := value.(*group.GroupPolicyInfo).Admin - addr, err := sdk.AccAddressFromBech32(admin) + addr, err := accKeeper.StringToBytes(admin) if err != nil { return nil, err } - return []interface{}{addr.Bytes()}, nil + return []interface{}{addr}, nil }, []byte{}) if err != nil { panic(err.Error()) @@ -162,11 +162,11 @@ func NewKeeper(storeKey storetypes.StoreKey, cdc codec.Codec, router baseapp.Mes } k.proposalByGroupPolicyIndex, err = orm.NewIndex(proposalTable, ProposalByGroupPolicyIndexPrefix, func(value interface{}) ([]interface{}, error) { account := value.(*group.Proposal).GroupPolicyAddress - addr, err := sdk.AccAddressFromBech32(account) + addr, err := accKeeper.StringToBytes(account) if err != nil { return nil, err } - return []interface{}{addr.Bytes()}, nil + return []interface{}{addr}, nil }, []byte{}) if err != nil { panic(err.Error()) @@ -192,11 +192,11 @@ func NewKeeper(storeKey storetypes.StoreKey, cdc codec.Codec, router baseapp.Mes panic(err.Error()) } k.voteByVoterIndex, err = orm.NewIndex(voteTable, VoteByVoterIndexPrefix, func(value interface{}) ([]interface{}, error) { - addr, err := sdk.AccAddressFromBech32(value.(*group.Vote).Voter) + addr, err := accKeeper.StringToBytes(value.(*group.Vote).Voter) if err != nil { return nil, err } - return []interface{}{addr.Bytes()}, nil + return []interface{}{addr}, nil }, []byte{}) if err != nil { panic(err.Error()) diff --git a/x/group/keeper/keeper_test.go b/x/group/keeper/keeper_test.go index 40a25f591eba..e57089e2cb67 100644 --- a/x/group/keeper/keeper_test.go +++ b/x/group/keeper/keeper_test.go @@ -1,12 +1,9 @@ package keeper_test import ( - "bytes" "context" "encoding/binary" - "fmt" - "sort" - "strings" + "errors" "testing" "time" @@ -18,16 +15,15 @@ import ( storetypes "cosmossdk.io/store/types" "github.com/cosmos/cosmos-sdk/baseapp" + "github.com/cosmos/cosmos-sdk/codec/address" "github.com/cosmos/cosmos-sdk/testutil" simtestutil "github.com/cosmos/cosmos-sdk/testutil/sims" - "github.com/cosmos/cosmos-sdk/testutil/testdata" sdk "github.com/cosmos/cosmos-sdk/types" moduletestutil "github.com/cosmos/cosmos-sdk/types/module/testutil" authtypes "github.com/cosmos/cosmos-sdk/x/auth/types" "github.com/cosmos/cosmos-sdk/x/bank" banktypes "github.com/cosmos/cosmos-sdk/x/bank/types" "github.com/cosmos/cosmos-sdk/x/group" - "github.com/cosmos/cosmos-sdk/x/group/internal/math" "github.com/cosmos/cosmos-sdk/x/group/keeper" "github.com/cosmos/cosmos-sdk/x/group/module" grouptestutil "github.com/cosmos/cosmos-sdk/x/group/testutil" @@ -64,2746 +60,102 @@ func (s *TestSuite) SetupTest() { s.accountKeeper = grouptestutil.NewMockAccountKeeper(ctrl) for i := range s.addrs { s.accountKeeper.EXPECT().GetAccount(gomock.Any(), s.addrs[i]).Return(authtypes.NewBaseAccountWithAddress(s.addrs[i])).AnyTimes() + s.accountKeeper.EXPECT().BytesToString(s.addrs[i]).Return(s.addrs[i].String(), nil).AnyTimes() + s.accountKeeper.EXPECT().StringToBytes(s.addrs[i].String()).Return(s.addrs[i], nil).AnyTimes() } - s.bankKeeper = grouptestutil.NewMockBankKeeper(ctrl) - - bApp := baseapp.NewBaseApp( - "group", - log.NewNopLogger(), - testCtx.DB, - encCfg.TxConfig.TxDecoder(), - ) - bApp.SetInterfaceRegistry(encCfg.InterfaceRegistry) - banktypes.RegisterMsgServer(bApp.MsgServiceRouter(), s.bankKeeper) - - config := group.DefaultConfig() - s.groupKeeper = keeper.NewKeeper(key, encCfg.Codec, bApp.MsgServiceRouter(), s.accountKeeper, config) - s.ctx = testCtx.Ctx.WithBlockTime(s.blockTime) - s.sdkCtx = sdk.UnwrapSDKContext(s.ctx) - - // Initial group, group policy and balance setup - members := []group.MemberRequest{ - {Address: s.addrs[4].String(), Weight: "1"}, {Address: s.addrs[1].String(), Weight: "2"}, - } - - s.setNextAccount() - - groupRes, err := s.groupKeeper.CreateGroup(s.ctx, &group.MsgCreateGroup{ - Admin: s.addrs[0].String(), - Members: members, - }) - s.Require().NoError(err) - s.groupID = groupRes.GroupId - - policy := group.NewThresholdDecisionPolicy( - "2", - time.Second, - minExecutionPeriod, // Must wait 5 seconds before executing proposal - ) - policyReq := &group.MsgCreateGroupPolicy{ - Admin: s.addrs[0].String(), - GroupId: s.groupID, - } - err = policyReq.SetDecisionPolicy(policy) - s.Require().NoError(err) - s.setNextAccount() - - groupSeq := s.groupKeeper.GetGroupSequence(s.sdkCtx) - s.Require().Equal(groupSeq, uint64(1)) - - policyRes, err := s.groupKeeper.CreateGroupPolicy(s.ctx, policyReq) - s.Require().NoError(err) - s.policy = policy - addr, err := sdk.AccAddressFromBech32(policyRes.Address) - s.Require().NoError(err) - s.groupPolicyAddr = addr - - s.bankKeeper.EXPECT().MintCoins(s.sdkCtx, minttypes.ModuleName, sdk.Coins{sdk.NewInt64Coin("test", 100000)}).Return(nil).AnyTimes() - s.bankKeeper.MintCoins(s.sdkCtx, minttypes.ModuleName, sdk.Coins{sdk.NewInt64Coin("test", 100000)}) - s.bankKeeper.EXPECT().SendCoinsFromModuleToAccount(s.sdkCtx, minttypes.ModuleName, s.groupPolicyAddr, sdk.Coins{sdk.NewInt64Coin("test", 10000)}).Return(nil).AnyTimes() - s.bankKeeper.SendCoinsFromModuleToAccount(s.sdkCtx, minttypes.ModuleName, s.groupPolicyAddr, sdk.Coins{sdk.NewInt64Coin("test", 10000)}) -} - -func (s *TestSuite) setNextAccount() { - nextAccVal := s.groupKeeper.GetGroupPolicySeq(s.sdkCtx) + 1 - derivationKey := make([]byte, 8) - binary.BigEndian.PutUint64(derivationKey, nextAccVal) - - ac, err := authtypes.NewModuleCredential(group.ModuleName, []byte{keeper.GroupPolicyTablePrefix}, derivationKey) - s.Require().NoError(err) - - groupPolicyAcc, err := authtypes.NewBaseAccountWithPubKey(ac) - s.Require().NoError(err) - - groupPolicyAccBumpAccountNumber, err := authtypes.NewBaseAccountWithPubKey(ac) - s.Require().NoError(err) - groupPolicyAccBumpAccountNumber.SetAccountNumber(nextAccVal) - - s.accountKeeper.EXPECT().GetAccount(gomock.Any(), sdk.AccAddress(ac.Address())).Return(nil).AnyTimes() - s.accountKeeper.EXPECT().NewAccount(gomock.Any(), groupPolicyAcc).Return(groupPolicyAccBumpAccountNumber).AnyTimes() - s.accountKeeper.EXPECT().SetAccount(gomock.Any(), sdk.AccountI(groupPolicyAccBumpAccountNumber)).Return().AnyTimes() -} - -func TestKeeperTestSuite(t *testing.T) { - suite.Run(t, new(TestSuite)) -} - -func (s *TestSuite) TestCreateGroupWithLotsOfMembers() { - for i := 50; i < 70; i++ { - membersResp := s.createGroupAndGetMembers(i) - s.Require().Equal(len(membersResp), i) - } -} - -func (s *TestSuite) createGroupAndGetMembers(numMembers int) []*group.GroupMember { - addressPool := simtestutil.CreateIncrementalAccounts(numMembers) - members := make([]group.MemberRequest, numMembers) - for i := 0; i < len(members); i++ { - members[i] = group.MemberRequest{ - Address: addressPool[i].String(), - Weight: "1", - } - } - - g, err := s.groupKeeper.CreateGroup(s.ctx, &group.MsgCreateGroup{ - Admin: members[0].Address, - Members: members, - }) - s.Require().NoErrorf(err, "failed to create group with %d members", len(members)) - s.T().Logf("group %d created with %d members", g.GroupId, len(members)) - - groupMemberResp, err := s.groupKeeper.GroupMembers(s.ctx, &group.QueryGroupMembersRequest{GroupId: g.GroupId}) - s.Require().NoError(err) - - s.T().Logf("got %d members from group %d", len(groupMemberResp.Members), g.GroupId) - - return groupMemberResp.Members -} - -func (s *TestSuite) TestCreateGroup() { - addrs := s.addrs - addr1 := addrs[0] - addr3 := addrs[2] - addr5 := addrs[4] - addr6 := addrs[5] - - members := []group.MemberRequest{{ - Address: addr5.String(), - Weight: "1", - }, { - Address: addr6.String(), - Weight: "2", - }} - - expGroups := []*group.GroupInfo{ - { - Id: s.groupID, - Version: 1, - Admin: addr1.String(), - TotalWeight: "3", - CreatedAt: s.blockTime, - }, - { - Id: 2, - Version: 1, - Admin: addr1.String(), - TotalWeight: "3", - CreatedAt: s.blockTime, - }, - } - - specs := map[string]struct { - req *group.MsgCreateGroup - expErr bool - expGroups []*group.GroupInfo - }{ - "all good": { - req: &group.MsgCreateGroup{ - Admin: addr1.String(), - Members: members, - }, - expGroups: expGroups, - }, - "group metadata too long": { - req: &group.MsgCreateGroup{ - Admin: addr1.String(), - Members: members, - Metadata: strings.Repeat("a", 256), - }, - expErr: true, - }, - "member metadata too long": { - req: &group.MsgCreateGroup{ - Admin: addr1.String(), - Members: []group.MemberRequest{{ - Address: addr3.String(), - Weight: "1", - Metadata: strings.Repeat("a", 256), - }}, - }, - expErr: true, - }, - "zero member weight": { - req: &group.MsgCreateGroup{ - Admin: addr1.String(), - Members: []group.MemberRequest{{ - Address: addr3.String(), - Weight: "0", - }}, - }, - expErr: true, - }, - "invalid member weight - Inf": { - req: &group.MsgCreateGroup{ - Admin: addr1.String(), - Members: []group.MemberRequest{{ - Address: addr3.String(), - Weight: "inf", - }}, - }, - expErr: true, - }, - "invalid member weight - NaN": { - req: &group.MsgCreateGroup{ - Admin: addr1.String(), - Members: []group.MemberRequest{{ - Address: addr3.String(), - Weight: "NaN", - }}, - }, - expErr: true, - }, - } - - var seq uint32 = 1 - for msg, spec := range specs { - spec := spec - s.Run(msg, func() { - blockTime := sdk.UnwrapSDKContext(s.ctx).BlockTime() - res, err := s.groupKeeper.CreateGroup(s.ctx, spec.req) - if spec.expErr { - s.Require().Error(err) - _, err := s.groupKeeper.GroupInfo(s.ctx, &group.QueryGroupInfoRequest{GroupId: uint64(seq + 1)}) - s.Require().Error(err) - return - } - s.Require().NoError(err) - id := res.GroupId - - seq++ - s.Assert().Equal(uint64(seq), id) - - // then all data persisted - loadedGroupRes, err := s.groupKeeper.GroupInfo(s.ctx, &group.QueryGroupInfoRequest{GroupId: id}) - s.Require().NoError(err) - s.Assert().Equal(spec.req.Admin, loadedGroupRes.Info.Admin) - s.Assert().Equal(spec.req.Metadata, loadedGroupRes.Info.Metadata) - s.Assert().Equal(id, loadedGroupRes.Info.Id) - s.Assert().Equal(uint64(1), loadedGroupRes.Info.Version) - - // and members are stored as well - membersRes, err := s.groupKeeper.GroupMembers(s.ctx, &group.QueryGroupMembersRequest{GroupId: id}) - s.Require().NoError(err) - loadedMembers := membersRes.Members - s.Require().Equal(len(members), len(loadedMembers)) - // we reorder members by address to be able to compare them - sort.Slice(members, func(i, j int) bool { - addri, err := sdk.AccAddressFromBech32(members[i].Address) - s.Require().NoError(err) - addrj, err := sdk.AccAddressFromBech32(members[j].Address) - s.Require().NoError(err) - return bytes.Compare(addri, addrj) < 0 - }) - for i := range loadedMembers { - s.Assert().Equal(members[i].Metadata, loadedMembers[i].Member.Metadata) - s.Assert().Equal(members[i].Address, loadedMembers[i].Member.Address) - s.Assert().Equal(members[i].Weight, loadedMembers[i].Member.Weight) - s.Assert().Equal(blockTime, loadedMembers[i].Member.AddedAt) - s.Assert().Equal(id, loadedMembers[i].GroupId) - } - - // query groups by admin - groupsRes, err := s.groupKeeper.GroupsByAdmin(s.ctx, &group.QueryGroupsByAdminRequest{Admin: addr1.String()}) - s.Require().NoError(err) - loadedGroups := groupsRes.Groups - s.Require().Equal(len(spec.expGroups), len(loadedGroups)) - for i := range loadedGroups { - s.Assert().Equal(spec.expGroups[i].Metadata, loadedGroups[i].Metadata) - s.Assert().Equal(spec.expGroups[i].Admin, loadedGroups[i].Admin) - s.Assert().Equal(spec.expGroups[i].TotalWeight, loadedGroups[i].TotalWeight) - s.Assert().Equal(spec.expGroups[i].Id, loadedGroups[i].Id) - s.Assert().Equal(spec.expGroups[i].Version, loadedGroups[i].Version) - s.Assert().Equal(spec.expGroups[i].CreatedAt, loadedGroups[i].CreatedAt) - } - }) - } -} - -func (s *TestSuite) TestUpdateGroupAdmin() { - addrs := s.addrs - addr1 := addrs[0] - addr2 := addrs[1] - addr3 := addrs[2] - addr4 := addrs[3] - - members := []group.MemberRequest{{ - Address: addr1.String(), - Weight: "1", - }} - oldAdmin := addr2.String() - newAdmin := addr3.String() - groupRes, err := s.groupKeeper.CreateGroup(s.ctx, &group.MsgCreateGroup{ - Admin: oldAdmin, - Members: members, - }) - s.Require().NoError(err) - groupID := groupRes.GroupId - specs := map[string]struct { - req *group.MsgUpdateGroupAdmin - expStored *group.GroupInfo - expErr bool - }{ - "with correct admin": { - req: &group.MsgUpdateGroupAdmin{ - GroupId: groupID, - Admin: oldAdmin, - NewAdmin: newAdmin, - }, - expStored: &group.GroupInfo{ - Id: groupID, - Admin: newAdmin, - TotalWeight: "1", - Version: 2, - CreatedAt: s.blockTime, - }, - }, - "with wrong admin": { - req: &group.MsgUpdateGroupAdmin{ - GroupId: groupID, - Admin: addr4.String(), - NewAdmin: newAdmin, - }, - expErr: true, - expStored: &group.GroupInfo{ - Id: groupID, - Admin: oldAdmin, - TotalWeight: "1", - Version: 1, - CreatedAt: s.blockTime, - }, - }, - "with unknown groupID": { - req: &group.MsgUpdateGroupAdmin{ - GroupId: 999, - Admin: oldAdmin, - NewAdmin: newAdmin, - }, - expErr: true, - expStored: &group.GroupInfo{ - Id: groupID, - Admin: oldAdmin, - TotalWeight: "1", - Version: 1, - CreatedAt: s.blockTime, - }, - }, - } - for msg, spec := range specs { - spec := spec - s.Run(msg, func() { - _, err := s.groupKeeper.UpdateGroupAdmin(s.ctx, spec.req) - if spec.expErr { - s.Require().Error(err) - return - } - s.Require().NoError(err) - - // then - res, err := s.groupKeeper.GroupInfo(s.ctx, &group.QueryGroupInfoRequest{GroupId: groupID}) - s.Require().NoError(err) - s.Assert().Equal(spec.expStored, res.Info) - }) - } -} - -func (s *TestSuite) TestUpdateGroupMetadata() { - addrs := s.addrs - addr1 := addrs[0] - addr3 := addrs[2] - - oldAdmin := addr1.String() - groupID := s.groupID - - specs := map[string]struct { - req *group.MsgUpdateGroupMetadata - expErr bool - expStored *group.GroupInfo - }{ - "with correct admin": { - req: &group.MsgUpdateGroupMetadata{ - GroupId: groupID, - Admin: oldAdmin, - }, - expStored: &group.GroupInfo{ - Id: groupID, - Admin: oldAdmin, - TotalWeight: "3", - Version: 2, - CreatedAt: s.blockTime, - }, - }, - "with wrong admin": { - req: &group.MsgUpdateGroupMetadata{ - GroupId: groupID, - Admin: addr3.String(), - }, - expErr: true, - expStored: &group.GroupInfo{ - Id: groupID, - Admin: oldAdmin, - TotalWeight: "1", - Version: 1, - CreatedAt: s.blockTime, - }, - }, - "with unknown groupid": { - req: &group.MsgUpdateGroupMetadata{ - GroupId: 999, - Admin: oldAdmin, - }, - expErr: true, - expStored: &group.GroupInfo{ - Id: groupID, - Admin: oldAdmin, - TotalWeight: "1", - Version: 1, - CreatedAt: s.blockTime, - }, - }, - } - for msg, spec := range specs { - spec := spec - s.Run(msg, func() { - sdkCtx, _ := s.sdkCtx.CacheContext() - _, err := s.groupKeeper.UpdateGroupMetadata(sdkCtx, spec.req) - if spec.expErr { - s.Require().Error(err) - return - } - s.Require().NoError(err) - - // then - res, err := s.groupKeeper.GroupInfo(sdkCtx, &group.QueryGroupInfoRequest{GroupId: groupID}) - s.Require().NoError(err) - s.Assert().Equal(spec.expStored, res.Info) - - events := sdkCtx.EventManager().ABCIEvents() - s.Require().Len(events, 1) // EventUpdateGroup - }) - } -} - -func (s *TestSuite) TestUpdateGroupMembers() { - addrs := s.addrs - addr3 := addrs[2] - addr4 := addrs[3] - addr5 := addrs[4] - addr6 := addrs[5] - - member1 := addr5.String() - member2 := addr6.String() - members := []group.MemberRequest{{ - Address: member1, - Weight: "1", - }} - - myAdmin := addr4.String() - groupRes, err := s.groupKeeper.CreateGroup(s.ctx, &group.MsgCreateGroup{ - Admin: myAdmin, - Members: members, - }) - s.Require().NoError(err) - groupID := groupRes.GroupId - - specs := map[string]struct { - req *group.MsgUpdateGroupMembers - expErr bool - expGroup *group.GroupInfo - expMembers []*group.GroupMember - }{ - "add new member": { - req: &group.MsgUpdateGroupMembers{ - GroupId: groupID, - Admin: myAdmin, - MemberUpdates: []group.MemberRequest{{ - Address: member2, - Weight: "2", - }}, - }, - expGroup: &group.GroupInfo{ - Id: groupID, - Admin: myAdmin, - TotalWeight: "3", - Version: 2, - CreatedAt: s.blockTime, - }, - expMembers: []*group.GroupMember{ - { - Member: &group.Member{ - Address: member2, - Weight: "2", - AddedAt: s.sdkCtx.BlockTime(), - }, - GroupId: groupID, - }, - { - Member: &group.Member{ - Address: member1, - Weight: "1", - AddedAt: s.blockTime, - }, - GroupId: groupID, - }, - }, - }, - "update member": { - req: &group.MsgUpdateGroupMembers{ - GroupId: groupID, - Admin: myAdmin, - MemberUpdates: []group.MemberRequest{{ - Address: member1, - Weight: "2", - }}, - }, - expGroup: &group.GroupInfo{ - Id: groupID, - Admin: myAdmin, - TotalWeight: "2", - Version: 2, - CreatedAt: s.blockTime, - }, - expMembers: []*group.GroupMember{ - { - GroupId: groupID, - Member: &group.Member{ - Address: member1, - Weight: "2", - AddedAt: s.blockTime, - }, - }, - }, - }, - "update member with same data": { - req: &group.MsgUpdateGroupMembers{ - GroupId: groupID, - Admin: myAdmin, - MemberUpdates: []group.MemberRequest{{ - Address: member1, - Weight: "1", - }}, - }, - expGroup: &group.GroupInfo{ - Id: groupID, - Admin: myAdmin, - TotalWeight: "1", - Version: 2, - CreatedAt: s.blockTime, - }, - expMembers: []*group.GroupMember{ - { - GroupId: groupID, - Member: &group.Member{ - Address: member1, - Weight: "1", - AddedAt: s.blockTime, - }, - }, - }, - }, - "replace member": { - req: &group.MsgUpdateGroupMembers{ - GroupId: groupID, - Admin: myAdmin, - MemberUpdates: []group.MemberRequest{ - { - Address: member1, - Weight: "0", - }, - { - Address: member2, - Weight: "1", - }, - }, - }, - expGroup: &group.GroupInfo{ - Id: groupID, - Admin: myAdmin, - TotalWeight: "1", - Version: 2, - CreatedAt: s.blockTime, - }, - expMembers: []*group.GroupMember{{ - GroupId: groupID, - Member: &group.Member{ - Address: member2, - Weight: "1", - AddedAt: s.sdkCtx.BlockTime(), - }, - }}, - }, - "remove existing member": { - req: &group.MsgUpdateGroupMembers{ - GroupId: groupID, - Admin: myAdmin, - MemberUpdates: []group.MemberRequest{{ - Address: member1, - Weight: "0", - }}, - }, - expGroup: &group.GroupInfo{ - Id: groupID, - Admin: myAdmin, - TotalWeight: "0", - Version: 2, - CreatedAt: s.blockTime, - }, - expMembers: []*group.GroupMember{}, - }, - "remove unknown member": { - req: &group.MsgUpdateGroupMembers{ - GroupId: groupID, - Admin: myAdmin, - MemberUpdates: []group.MemberRequest{{ - Address: addr4.String(), - Weight: "0", - }}, - }, - expErr: true, - expGroup: &group.GroupInfo{ - Id: groupID, - Admin: myAdmin, - TotalWeight: "1", - Version: 1, - CreatedAt: s.blockTime, - }, - expMembers: []*group.GroupMember{{ - GroupId: groupID, - Member: &group.Member{ - Address: member1, - Weight: "1", - }, - }}, - }, - "with wrong admin": { - req: &group.MsgUpdateGroupMembers{ - GroupId: groupID, - Admin: addr3.String(), - MemberUpdates: []group.MemberRequest{{ - Address: member1, - Weight: "2", - }}, - }, - expErr: true, - expGroup: &group.GroupInfo{ - Id: groupID, - Admin: myAdmin, - TotalWeight: "1", - Version: 1, - CreatedAt: s.blockTime, - }, - expMembers: []*group.GroupMember{{ - GroupId: groupID, - Member: &group.Member{ - Address: member1, - Weight: "1", - }, - }}, - }, - "with unknown groupID": { - req: &group.MsgUpdateGroupMembers{ - GroupId: 999, - Admin: myAdmin, - MemberUpdates: []group.MemberRequest{{ - Address: member1, - Weight: "2", - }}, - }, - expErr: true, - expGroup: &group.GroupInfo{ - Id: groupID, - Admin: myAdmin, - TotalWeight: "1", - Version: 1, - CreatedAt: s.blockTime, - }, - expMembers: []*group.GroupMember{{ - GroupId: groupID, - Member: &group.Member{ - Address: member1, - Weight: "1", - }, - }}, - }, - } - for msg, spec := range specs { - spec := spec - s.Run(msg, func() { - sdkCtx, _ := s.sdkCtx.CacheContext() - _, err := s.groupKeeper.UpdateGroupMembers(sdkCtx, spec.req) - if spec.expErr { - s.Require().Error(err) - return - } - s.Require().NoError(err) - - // then - res, err := s.groupKeeper.GroupInfo(sdkCtx, &group.QueryGroupInfoRequest{GroupId: groupID}) - s.Require().NoError(err) - s.Assert().Equal(spec.expGroup, res.Info) - - // and members persisted - membersRes, err := s.groupKeeper.GroupMembers(sdkCtx, &group.QueryGroupMembersRequest{GroupId: groupID}) - s.Require().NoError(err) - loadedMembers := membersRes.Members - s.Require().Equal(len(spec.expMembers), len(loadedMembers)) - // we reorder group members by address to be able to compare them - sort.Slice(spec.expMembers, func(i, j int) bool { - addri, err := sdk.AccAddressFromBech32(spec.expMembers[i].Member.Address) - s.Require().NoError(err) - addrj, err := sdk.AccAddressFromBech32(spec.expMembers[j].Member.Address) - s.Require().NoError(err) - return bytes.Compare(addri, addrj) < 0 - }) - for i := range loadedMembers { - s.Assert().Equal(spec.expMembers[i].Member.Metadata, loadedMembers[i].Member.Metadata) - s.Assert().Equal(spec.expMembers[i].Member.Address, loadedMembers[i].Member.Address) - s.Assert().Equal(spec.expMembers[i].Member.Weight, loadedMembers[i].Member.Weight) - s.Assert().Equal(spec.expMembers[i].Member.AddedAt, loadedMembers[i].Member.AddedAt) - s.Assert().Equal(spec.expMembers[i].GroupId, loadedMembers[i].GroupId) - } - - events := sdkCtx.EventManager().ABCIEvents() - s.Require().Len(events, 1) // EventUpdateGroup - }) - } -} - -func (s *TestSuite) TestCreateGroupWithPolicy() { - addrs := s.addrs - addr1 := addrs[0] - addr3 := addrs[2] - addr5 := addrs[4] - addr6 := addrs[5] - - s.setNextAccount() - - members := []group.MemberRequest{{ - Address: addr5.String(), - Weight: "1", - }, { - Address: addr6.String(), - Weight: "2", - }} - - specs := map[string]struct { - req *group.MsgCreateGroupWithPolicy - policy group.DecisionPolicy - malleate func() - expErr bool - expErrMsg string - }{ - "all good": { - req: &group.MsgCreateGroupWithPolicy{ - Admin: addr1.String(), - Members: members, - GroupPolicyAsAdmin: false, - }, - malleate: func() { - s.setNextAccount() - }, - policy: group.NewThresholdDecisionPolicy( - "1", - time.Second, - 0, - ), - }, - "group policy as admin is true": { - req: &group.MsgCreateGroupWithPolicy{ - Admin: addr1.String(), - Members: members, - GroupPolicyAsAdmin: true, - }, - malleate: func() { - s.setNextAccount() - }, - policy: group.NewThresholdDecisionPolicy( - "1", - time.Second, - 0, - ), - }, - "group metadata too long": { - req: &group.MsgCreateGroupWithPolicy{ - Admin: addr1.String(), - Members: members, - GroupPolicyAsAdmin: false, - GroupMetadata: strings.Repeat("a", 256), - }, - policy: group.NewThresholdDecisionPolicy( - "1", - time.Second, - 0, - ), - expErr: true, - expErrMsg: "limit exceeded", - }, - "group policy metadata too long": { - req: &group.MsgCreateGroupWithPolicy{ - Admin: addr1.String(), - Members: members, - GroupPolicyAsAdmin: false, - GroupPolicyMetadata: strings.Repeat("a", 256), - }, - policy: group.NewThresholdDecisionPolicy( - "1", - time.Second, - 0, - ), - expErr: true, - expErrMsg: "limit exceeded", - }, - "member metadata too long": { - req: &group.MsgCreateGroupWithPolicy{ - Admin: addr1.String(), - Members: []group.MemberRequest{{ - Address: addr3.String(), - Weight: "1", - Metadata: strings.Repeat("a", 256), - }}, - GroupPolicyAsAdmin: false, - }, - policy: group.NewThresholdDecisionPolicy( - "1", - time.Second, - 0, - ), - expErr: true, - expErrMsg: "limit exceeded", - }, - "zero member weight": { - req: &group.MsgCreateGroupWithPolicy{ - Admin: addr1.String(), - Members: []group.MemberRequest{{ - Address: addr3.String(), - Weight: "0", - }}, - GroupPolicyAsAdmin: false, - }, - policy: group.NewThresholdDecisionPolicy( - "1", - time.Second, - 0, - ), - expErr: true, - expErrMsg: "expected a positive decimal", - }, - "decision policy threshold > total group weight": { - req: &group.MsgCreateGroupWithPolicy{ - Admin: addr1.String(), - Members: members, - GroupPolicyAsAdmin: false, - }, - malleate: func() { - s.setNextAccount() - }, - policy: group.NewThresholdDecisionPolicy( - "10", - time.Second, - 0, - ), - expErr: false, - }, - } - - for msg, spec := range specs { - spec := spec - s.Run(msg, func() { - s.setNextAccount() - err := spec.req.SetDecisionPolicy(spec.policy) - s.Require().NoError(err) - - blockTime := sdk.UnwrapSDKContext(s.ctx).BlockTime() - res, err := s.groupKeeper.CreateGroupWithPolicy(s.ctx, spec.req) - if spec.expErr { - s.Require().Error(err) - s.Require().Contains(err.Error(), spec.expErrMsg) - return - } - s.Require().NoError(err) - id := res.GroupId - groupPolicyAddr := res.GroupPolicyAddress - - // then all data persisted in group - loadedGroupRes, err := s.groupKeeper.GroupInfo(s.ctx, &group.QueryGroupInfoRequest{GroupId: id}) - s.Require().NoError(err) - s.Assert().Equal(spec.req.GroupMetadata, loadedGroupRes.Info.Metadata) - s.Assert().Equal(id, loadedGroupRes.Info.Id) - if spec.req.GroupPolicyAsAdmin { - s.Assert().NotEqual(spec.req.Admin, loadedGroupRes.Info.Admin) - s.Assert().Equal(groupPolicyAddr, loadedGroupRes.Info.Admin) - } else { - s.Assert().Equal(spec.req.Admin, loadedGroupRes.Info.Admin) - } - - // and members are stored as well - membersRes, err := s.groupKeeper.GroupMembers(s.ctx, &group.QueryGroupMembersRequest{GroupId: id}) - s.Require().NoError(err) - loadedMembers := membersRes.Members - s.Require().Equal(len(members), len(loadedMembers)) - // we reorder members by address to be able to compare them - sort.Slice(members, func(i, j int) bool { - addri, err := sdk.AccAddressFromBech32(members[i].Address) - s.Require().NoError(err) - addrj, err := sdk.AccAddressFromBech32(members[j].Address) - s.Require().NoError(err) - return bytes.Compare(addri, addrj) < 0 - }) - for i := range loadedMembers { - s.Assert().Equal(members[i].Metadata, loadedMembers[i].Member.Metadata) - s.Assert().Equal(members[i].Address, loadedMembers[i].Member.Address) - s.Assert().Equal(members[i].Weight, loadedMembers[i].Member.Weight) - s.Assert().Equal(blockTime, loadedMembers[i].Member.AddedAt) - s.Assert().Equal(id, loadedMembers[i].GroupId) - } - - // then all data persisted in group policy - groupPolicyRes, err := s.groupKeeper.GroupPolicyInfo(s.ctx, &group.QueryGroupPolicyInfoRequest{Address: groupPolicyAddr}) - s.Require().NoError(err) - - groupPolicy := groupPolicyRes.Info - s.Assert().Equal(groupPolicyAddr, groupPolicy.Address) - s.Assert().Equal(id, groupPolicy.GroupId) - s.Assert().Equal(spec.req.GroupPolicyMetadata, groupPolicy.Metadata) - dp, err := groupPolicy.GetDecisionPolicy() - s.Assert().NoError(err) - s.Assert().Equal(spec.policy.(*group.ThresholdDecisionPolicy), dp) - if spec.req.GroupPolicyAsAdmin { - s.Assert().NotEqual(spec.req.Admin, groupPolicy.Admin) - s.Assert().Equal(groupPolicyAddr, groupPolicy.Admin) - } else { - s.Assert().Equal(spec.req.Admin, groupPolicy.Admin) - } - }) - } -} - -func (s *TestSuite) TestCreateGroupPolicy() { - addrs := s.addrs - addr1 := addrs[0] - addr4 := addrs[3] - - s.setNextAccount() - groupRes, err := s.groupKeeper.CreateGroup(s.ctx, &group.MsgCreateGroup{ - Admin: addr1.String(), - Members: nil, - }) - s.Require().NoError(err) - myGroupID := groupRes.GroupId - - specs := map[string]struct { - req *group.MsgCreateGroupPolicy - policy group.DecisionPolicy - expErr bool - expErrMsg string - }{ - "all good": { - req: &group.MsgCreateGroupPolicy{ - Admin: addr1.String(), - GroupId: myGroupID, - }, - policy: group.NewThresholdDecisionPolicy( - "1", - time.Second, - 0, - ), - }, - "all good with percentage decision policy": { - req: &group.MsgCreateGroupPolicy{ - Admin: addr1.String(), - GroupId: myGroupID, - }, - policy: group.NewPercentageDecisionPolicy( - "0.5", - time.Second, - 0, - ), - }, - "decision policy threshold > total group weight": { - req: &group.MsgCreateGroupPolicy{ - Admin: addr1.String(), - GroupId: myGroupID, - }, - policy: group.NewThresholdDecisionPolicy( - "10", - time.Second, - 0, - ), - }, - "group id does not exists": { - req: &group.MsgCreateGroupPolicy{ - Admin: addr1.String(), - GroupId: 9999, - }, - policy: group.NewThresholdDecisionPolicy( - "1", - time.Second, - 0, - ), - expErr: true, - expErrMsg: "not found", - }, - "admin not group admin": { - req: &group.MsgCreateGroupPolicy{ - Admin: addr4.String(), - GroupId: myGroupID, - }, - policy: group.NewThresholdDecisionPolicy( - "1", - time.Second, - 0, - ), - expErr: true, - expErrMsg: "not group admin", - }, - "metadata too long": { - req: &group.MsgCreateGroupPolicy{ - Admin: addr1.String(), - GroupId: myGroupID, - Metadata: strings.Repeat("a", 256), - }, - policy: group.NewThresholdDecisionPolicy( - "1", - time.Second, - 0, - ), - expErr: true, - expErrMsg: "limit exceeded", - }, - "percentage decision policy with negative value": { - req: &group.MsgCreateGroupPolicy{ - Admin: addr1.String(), - GroupId: myGroupID, - }, - policy: group.NewPercentageDecisionPolicy( - "-0.5", - time.Second, - 0, - ), - expErr: true, - expErrMsg: "expected a positive decimal", - }, - "percentage decision policy with value greater than 1": { - req: &group.MsgCreateGroupPolicy{ - Admin: addr1.String(), - GroupId: myGroupID, - }, - policy: group.NewPercentageDecisionPolicy( - "2", - time.Second, - 0, - ), - expErr: true, - expErrMsg: "percentage must be > 0 and <= 1", - }, - } - for msg, spec := range specs { - spec := spec - s.Run(msg, func() { - err := spec.req.SetDecisionPolicy(spec.policy) - s.Require().NoError(err) - - s.setNextAccount() - - res, err := s.groupKeeper.CreateGroupPolicy(s.ctx, spec.req) - if spec.expErr { - s.Require().Error(err) - s.Require().Contains(err.Error(), spec.expErrMsg) - return - } - s.Require().NoError(err) - addr := res.Address - - // then all data persisted - groupPolicyRes, err := s.groupKeeper.GroupPolicyInfo(s.ctx, &group.QueryGroupPolicyInfoRequest{Address: addr}) - s.Require().NoError(err) - - groupPolicy := groupPolicyRes.Info - s.Assert().Equal(addr, groupPolicy.Address) - s.Assert().Equal(myGroupID, groupPolicy.GroupId) - s.Assert().Equal(spec.req.Admin, groupPolicy.Admin) - s.Assert().Equal(spec.req.Metadata, groupPolicy.Metadata) - s.Assert().Equal(uint64(1), groupPolicy.Version) - percentageDecisionPolicy, ok := spec.policy.(*group.PercentageDecisionPolicy) - if ok { - dp, err := groupPolicy.GetDecisionPolicy() - s.Assert().NoError(err) - s.Assert().Equal(percentageDecisionPolicy, dp) - } else { - dp, err := groupPolicy.GetDecisionPolicy() - s.Assert().NoError(err) - s.Assert().Equal(spec.policy.(*group.ThresholdDecisionPolicy), dp) - } - }) - } -} - -func (s *TestSuite) TestUpdateGroupPolicyAdmin() { - addrs := s.addrs - addr1 := addrs[0] - addr2 := addrs[1] - addr5 := addrs[4] - - admin, newAdmin := addr1, addr2 - policy := group.NewThresholdDecisionPolicy( - "1", - time.Second, - 0, - ) - s.setNextAccount() - groupPolicyAddr, myGroupID := s.createGroupAndGroupPolicy(admin, nil, policy) - - specs := map[string]struct { - req *group.MsgUpdateGroupPolicyAdmin - expGroupPolicy *group.GroupPolicyInfo - expErr bool - }{ - "with wrong admin": { - req: &group.MsgUpdateGroupPolicyAdmin{ - Admin: addr5.String(), - GroupPolicyAddress: groupPolicyAddr, - NewAdmin: newAdmin.String(), - }, - expGroupPolicy: &group.GroupPolicyInfo{ - Admin: admin.String(), - Address: groupPolicyAddr, - GroupId: myGroupID, - Version: 2, - DecisionPolicy: nil, - CreatedAt: s.blockTime, - }, - expErr: true, - }, - "with wrong group policy": { - req: &group.MsgUpdateGroupPolicyAdmin{ - Admin: admin.String(), - GroupPolicyAddress: addr5.String(), - NewAdmin: newAdmin.String(), - }, - expGroupPolicy: &group.GroupPolicyInfo{ - Admin: admin.String(), - Address: groupPolicyAddr, - GroupId: myGroupID, - Version: 2, - DecisionPolicy: nil, - CreatedAt: s.blockTime, - }, - expErr: true, - }, - "correct data": { - req: &group.MsgUpdateGroupPolicyAdmin{ - Admin: admin.String(), - GroupPolicyAddress: groupPolicyAddr, - NewAdmin: newAdmin.String(), - }, - expGroupPolicy: &group.GroupPolicyInfo{ - Admin: newAdmin.String(), - Address: groupPolicyAddr, - GroupId: myGroupID, - Version: 2, - DecisionPolicy: nil, - CreatedAt: s.blockTime, - }, - expErr: false, - }, - } - for msg, spec := range specs { - spec := spec - err := spec.expGroupPolicy.SetDecisionPolicy(policy) - s.Require().NoError(err) - - s.Run(msg, func() { - _, err := s.groupKeeper.UpdateGroupPolicyAdmin(s.ctx, spec.req) - if spec.expErr { - s.Require().Error(err) - return - } - s.Require().NoError(err) - res, err := s.groupKeeper.GroupPolicyInfo(s.ctx, &group.QueryGroupPolicyInfoRequest{ - Address: groupPolicyAddr, - }) - s.Require().NoError(err) - s.Assert().Equal(spec.expGroupPolicy, res.Info) - }) - } -} - -func (s *TestSuite) TestUpdateGroupPolicyMetadata() { - addrs := s.addrs - addr1 := addrs[0] - addr5 := addrs[4] - - admin := addr1 - policy := group.NewThresholdDecisionPolicy( - "1", - time.Second, - 0, - ) - - s.setNextAccount() - groupPolicyAddr, myGroupID := s.createGroupAndGroupPolicy(admin, nil, policy) - - specs := map[string]struct { - req *group.MsgUpdateGroupPolicyMetadata - expGroupPolicy *group.GroupPolicyInfo - expErr bool - }{ - "with wrong admin": { - req: &group.MsgUpdateGroupPolicyMetadata{ - Admin: addr5.String(), - GroupPolicyAddress: groupPolicyAddr, - }, - expGroupPolicy: &group.GroupPolicyInfo{}, - expErr: true, - }, - "with wrong group policy": { - req: &group.MsgUpdateGroupPolicyMetadata{ - Admin: admin.String(), - GroupPolicyAddress: addr5.String(), - }, - expGroupPolicy: &group.GroupPolicyInfo{}, - expErr: true, - }, - "with comment too long": { - req: &group.MsgUpdateGroupPolicyMetadata{ - Admin: admin.String(), - GroupPolicyAddress: addr5.String(), - }, - expGroupPolicy: &group.GroupPolicyInfo{}, - expErr: true, - }, - "correct data": { - req: &group.MsgUpdateGroupPolicyMetadata{ - Admin: admin.String(), - GroupPolicyAddress: groupPolicyAddr, - }, - expGroupPolicy: &group.GroupPolicyInfo{ - Admin: admin.String(), - Address: groupPolicyAddr, - GroupId: myGroupID, - Version: 2, - DecisionPolicy: nil, - CreatedAt: s.blockTime, - }, - expErr: false, - }, - } - for msg, spec := range specs { - spec := spec - err := spec.expGroupPolicy.SetDecisionPolicy(policy) - s.Require().NoError(err) - - s.Run(msg, func() { - _, err := s.groupKeeper.UpdateGroupPolicyMetadata(s.ctx, spec.req) - if spec.expErr { - s.Require().Error(err) - return - } - s.Require().NoError(err) - - res, err := s.groupKeeper.GroupPolicyInfo(s.ctx, &group.QueryGroupPolicyInfoRequest{ - Address: groupPolicyAddr, - }) - s.Require().NoError(err) - s.Assert().Equal(spec.expGroupPolicy, res.Info) - - // check events - var hasUpdateGroupPolicyEvent bool - events := s.ctx.(sdk.Context).EventManager().ABCIEvents() - for _, event := range events { - event, err := sdk.ParseTypedEvent(event) - s.Require().NoError(err) - - if e, ok := event.(*group.EventUpdateGroupPolicy); ok { - s.Require().Equal(e.Address, groupPolicyAddr) - hasUpdateGroupPolicyEvent = true - break - } - } - - s.Require().True(hasUpdateGroupPolicyEvent) - }) - } -} - -func (s *TestSuite) TestUpdateGroupPolicyDecisionPolicy() { - addrs := s.addrs - addr1 := addrs[0] - addr5 := addrs[4] - - admin := addr1 - policy := group.NewThresholdDecisionPolicy( - "1", - time.Second, - 0, - ) - - s.setNextAccount() - groupPolicyAddr, myGroupID := s.createGroupAndGroupPolicy(admin, nil, policy) - - specs := map[string]struct { - preRun func(admin sdk.AccAddress) (policyAddr string, groupId uint64) - req *group.MsgUpdateGroupPolicyDecisionPolicy - policy group.DecisionPolicy - expGroupPolicy *group.GroupPolicyInfo - expErr bool - }{ - "with wrong admin": { - req: &group.MsgUpdateGroupPolicyDecisionPolicy{ - Admin: addr5.String(), - GroupPolicyAddress: groupPolicyAddr, - }, - policy: policy, - expGroupPolicy: &group.GroupPolicyInfo{}, - expErr: true, - }, - "with wrong group policy": { - req: &group.MsgUpdateGroupPolicyDecisionPolicy{ - Admin: admin.String(), - GroupPolicyAddress: addr5.String(), - }, - policy: policy, - expGroupPolicy: &group.GroupPolicyInfo{}, - expErr: true, - }, - "correct data": { - req: &group.MsgUpdateGroupPolicyDecisionPolicy{ - Admin: admin.String(), - GroupPolicyAddress: groupPolicyAddr, - }, - policy: group.NewThresholdDecisionPolicy( - "2", - time.Duration(2)*time.Second, - 0, - ), - expGroupPolicy: &group.GroupPolicyInfo{ - Admin: admin.String(), - Address: groupPolicyAddr, - GroupId: myGroupID, - Version: 2, - DecisionPolicy: nil, - CreatedAt: s.blockTime, - }, - expErr: false, - }, - "correct data with percentage decision policy": { - preRun: func(admin sdk.AccAddress) (string, uint64) { - s.setNextAccount() - return s.createGroupAndGroupPolicy(admin, nil, policy) - }, - req: &group.MsgUpdateGroupPolicyDecisionPolicy{ - Admin: admin.String(), - GroupPolicyAddress: groupPolicyAddr, - }, - policy: group.NewPercentageDecisionPolicy( - "0.5", - time.Duration(2)*time.Second, - 0, - ), - expGroupPolicy: &group.GroupPolicyInfo{ - Admin: admin.String(), - DecisionPolicy: nil, - Version: 2, - CreatedAt: s.blockTime, - }, - expErr: false, - }, - } - for msg, spec := range specs { - spec := spec - policyAddr := groupPolicyAddr - err := spec.expGroupPolicy.SetDecisionPolicy(spec.policy) - s.Require().NoError(err) - if spec.preRun != nil { - policyAddr1, groupID := spec.preRun(admin) - policyAddr = policyAddr1 - - // update the expected info with new group policy details - spec.expGroupPolicy.Address = policyAddr1 - spec.expGroupPolicy.GroupId = groupID - - // update req with new group policy addr - spec.req.GroupPolicyAddress = policyAddr1 - } - - err = spec.req.SetDecisionPolicy(spec.policy) - s.Require().NoError(err) - - s.Run(msg, func() { - _, err := s.groupKeeper.UpdateGroupPolicyDecisionPolicy(s.ctx, spec.req) - if spec.expErr { - s.Require().Error(err) - return - } - s.Require().NoError(err) - res, err := s.groupKeeper.GroupPolicyInfo(s.ctx, &group.QueryGroupPolicyInfoRequest{ - Address: policyAddr, - }) - s.Require().NoError(err) - s.Assert().Equal(spec.expGroupPolicy, res.Info) - }) - } -} - -func (s *TestSuite) TestGroupPoliciesByAdminOrGroup() { - addrs := s.addrs - addr2 := addrs[1] - - admin := addr2 - - groupRes, err := s.groupKeeper.CreateGroup(s.ctx, &group.MsgCreateGroup{ - Admin: admin.String(), - Members: nil, - }) - s.Require().NoError(err) - myGroupID := groupRes.GroupId - - policies := []group.DecisionPolicy{ - group.NewThresholdDecisionPolicy( - "1", - time.Second, - 0, - ), - group.NewThresholdDecisionPolicy( - "10", - time.Second, - 0, - ), - group.NewPercentageDecisionPolicy( - "0.5", - time.Second, - 0, - ), - } - - count := 3 - expectAccs := make([]*group.GroupPolicyInfo, count) - for i := range expectAccs { - req := &group.MsgCreateGroupPolicy{ - Admin: admin.String(), - GroupId: myGroupID, - } - err := req.SetDecisionPolicy(policies[i]) - s.Require().NoError(err) - - s.setNextAccount() - res, err := s.groupKeeper.CreateGroupPolicy(s.ctx, req) - s.Require().NoError(err) - - expectAcc := &group.GroupPolicyInfo{ - Address: res.Address, - Admin: admin.String(), - GroupId: myGroupID, - Version: uint64(1), - CreatedAt: s.blockTime, - } - err = expectAcc.SetDecisionPolicy(policies[i]) - s.Require().NoError(err) - expectAccs[i] = expectAcc - } - sort.Slice(expectAccs, func(i, j int) bool { return expectAccs[i].Address < expectAccs[j].Address }) - - // query group policy by group - policiesByGroupRes, err := s.groupKeeper.GroupPoliciesByGroup(s.ctx, &group.QueryGroupPoliciesByGroupRequest{ - GroupId: myGroupID, - }) - s.Require().NoError(err) - policyAccs := policiesByGroupRes.GroupPolicies - s.Require().Equal(len(policyAccs), count) - // we reorder policyAccs by address to be able to compare them - sort.Slice(policyAccs, func(i, j int) bool { return policyAccs[i].Address < policyAccs[j].Address }) - for i := range policyAccs { - s.Assert().Equal(policyAccs[i].Address, expectAccs[i].Address) - s.Assert().Equal(policyAccs[i].GroupId, expectAccs[i].GroupId) - s.Assert().Equal(policyAccs[i].Admin, expectAccs[i].Admin) - s.Assert().Equal(policyAccs[i].Metadata, expectAccs[i].Metadata) - s.Assert().Equal(policyAccs[i].Version, expectAccs[i].Version) - s.Assert().Equal(policyAccs[i].CreatedAt, expectAccs[i].CreatedAt) - dp1, err := policyAccs[i].GetDecisionPolicy() - s.Assert().NoError(err) - dp2, err := expectAccs[i].GetDecisionPolicy() - s.Assert().NoError(err) - s.Assert().Equal(dp1, dp2) - } - - // query group policy by admin - policiesByAdminRes, err := s.groupKeeper.GroupPoliciesByAdmin(s.ctx, &group.QueryGroupPoliciesByAdminRequest{ - Admin: admin.String(), - }) - s.Require().NoError(err) - policyAccs = policiesByAdminRes.GroupPolicies - s.Require().Equal(len(policyAccs), count) - // we reorder policyAccs by address to be able to compare them - sort.Slice(policyAccs, func(i, j int) bool { return policyAccs[i].Address < policyAccs[j].Address }) - for i := range policyAccs { - s.Assert().Equal(policyAccs[i].Address, expectAccs[i].Address) - s.Assert().Equal(policyAccs[i].GroupId, expectAccs[i].GroupId) - s.Assert().Equal(policyAccs[i].Admin, expectAccs[i].Admin) - s.Assert().Equal(policyAccs[i].Metadata, expectAccs[i].Metadata) - s.Assert().Equal(policyAccs[i].Version, expectAccs[i].Version) - s.Assert().Equal(policyAccs[i].CreatedAt, expectAccs[i].CreatedAt) - dp1, err := policyAccs[i].GetDecisionPolicy() - s.Assert().NoError(err) - dp2, err := expectAccs[i].GetDecisionPolicy() - s.Assert().NoError(err) - s.Assert().Equal(dp1, dp2) - } -} - -func (s *TestSuite) TestSubmitProposal() { - addrs := s.addrs - addr1 := addrs[0] - addr2 := addrs[1] // Has weight 2 - addr4 := addrs[3] - addr5 := addrs[4] // Has weight 1 - - myGroupID := s.groupID - accountAddr := s.groupPolicyAddr - - // Create a new group policy to test TRY_EXEC - policyReq := &group.MsgCreateGroupPolicy{ - Admin: addr1.String(), - GroupId: myGroupID, - } - noMinExecPeriodPolicy := group.NewThresholdDecisionPolicy( - "2", - time.Second, - 0, // no MinExecutionPeriod to test TRY_EXEC - ) - err := policyReq.SetDecisionPolicy(noMinExecPeriodPolicy) - s.Require().NoError(err) - s.setNextAccount() - res, err := s.groupKeeper.CreateGroupPolicy(s.ctx, policyReq) - s.Require().NoError(err) - noMinExecPeriodPolicyAddr := sdk.MustAccAddressFromBech32(res.Address) - - // Create a new group policy with super high threshold - bigThresholdPolicy := group.NewThresholdDecisionPolicy( - "100", - time.Second, - minExecutionPeriod, - ) - s.setNextAccount() - err = policyReq.SetDecisionPolicy(bigThresholdPolicy) - s.Require().NoError(err) - bigThresholdRes, err := s.groupKeeper.CreateGroupPolicy(s.ctx, policyReq) - s.Require().NoError(err) - bigThresholdAddr := bigThresholdRes.Address - - msgSend := &banktypes.MsgSend{ - FromAddress: noMinExecPeriodPolicyAddr.String(), - ToAddress: addr2.String(), - Amount: sdk.Coins{sdk.NewInt64Coin("test", 100)}, - } - defaultProposal := group.Proposal{ - GroupPolicyAddress: accountAddr.String(), - Status: group.PROPOSAL_STATUS_SUBMITTED, - FinalTallyResult: group.TallyResult{ - YesCount: "0", - NoCount: "0", - AbstainCount: "0", - NoWithVetoCount: "0", - }, - ExecutorResult: group.PROPOSAL_EXECUTOR_RESULT_NOT_RUN, - } - specs := map[string]struct { - req *group.MsgSubmitProposal - msgs []sdk.Msg - expProposal group.Proposal - expErr bool - postRun func(sdkCtx sdk.Context) - preRun func(msg []sdk.Msg) - }{ - "all good with minimal fields set": { - req: &group.MsgSubmitProposal{ - GroupPolicyAddress: accountAddr.String(), - Proposers: []string{addr2.String()}, - }, - expProposal: defaultProposal, - postRun: func(sdkCtx sdk.Context) {}, - }, - "all good with good msg payload": { - req: &group.MsgSubmitProposal{ - GroupPolicyAddress: accountAddr.String(), - Proposers: []string{addr2.String()}, - }, - msgs: []sdk.Msg{&banktypes.MsgSend{ - FromAddress: accountAddr.String(), - ToAddress: addr2.String(), - Amount: sdk.Coins{sdk.NewInt64Coin("token", 100)}, - }}, - expProposal: defaultProposal, - postRun: func(sdkCtx sdk.Context) {}, - }, - "metadata too long": { - req: &group.MsgSubmitProposal{ - GroupPolicyAddress: accountAddr.String(), - Proposers: []string{addr2.String()}, - Metadata: strings.Repeat("a", 256), - }, - expErr: true, - postRun: func(sdkCtx sdk.Context) {}, - }, - "group policy required": { - req: &group.MsgSubmitProposal{ - Proposers: []string{addr2.String()}, - }, - expErr: true, - postRun: func(sdkCtx sdk.Context) {}, - }, - "existing group policy required": { - req: &group.MsgSubmitProposal{ - GroupPolicyAddress: addr1.String(), - Proposers: []string{addr2.String()}, - }, - expErr: true, - postRun: func(sdkCtx sdk.Context) {}, - }, - "decision policy threshold > total group weight": { - req: &group.MsgSubmitProposal{ - GroupPolicyAddress: bigThresholdAddr, - Proposers: []string{addr2.String()}, - }, - expErr: false, - expProposal: group.Proposal{ - GroupPolicyAddress: bigThresholdAddr, - Status: group.PROPOSAL_STATUS_SUBMITTED, - FinalTallyResult: group.DefaultTallyResult(), - ExecutorResult: group.PROPOSAL_EXECUTOR_RESULT_NOT_RUN, - }, - postRun: func(sdkCtx sdk.Context) {}, - }, - "only group members can create a proposal": { - req: &group.MsgSubmitProposal{ - GroupPolicyAddress: accountAddr.String(), - Proposers: []string{addr4.String()}, - }, - expErr: true, - postRun: func(sdkCtx sdk.Context) {}, - }, - "all proposers must be in group": { - req: &group.MsgSubmitProposal{ - GroupPolicyAddress: accountAddr.String(), - Proposers: []string{addr2.String(), addr4.String()}, - }, - expErr: true, - postRun: func(sdkCtx sdk.Context) {}, - }, - "admin that is not a group member can not create proposal": { - req: &group.MsgSubmitProposal{ - GroupPolicyAddress: accountAddr.String(), - Proposers: []string{addr1.String()}, - }, - expErr: true, - postRun: func(sdkCtx sdk.Context) {}, - }, - "reject msgs that are not authz by group policy": { - req: &group.MsgSubmitProposal{ - GroupPolicyAddress: accountAddr.String(), - Proposers: []string{addr2.String()}, - }, - msgs: []sdk.Msg{&testdata.TestMsg{Signers: []string{addr1.String()}}}, - expErr: true, - postRun: func(sdkCtx sdk.Context) {}, - }, - "with try exec": { - preRun: func(msgs []sdk.Msg) { - for i := 0; i < len(msgs); i++ { - s.bankKeeper.EXPECT().Send(gomock.Any(), msgs[i]).Return(nil, nil) - } - }, - req: &group.MsgSubmitProposal{ - GroupPolicyAddress: noMinExecPeriodPolicyAddr.String(), - Proposers: []string{addr2.String()}, - Exec: group.Exec_EXEC_TRY, - }, - msgs: []sdk.Msg{msgSend}, - expProposal: group.Proposal{ - GroupPolicyAddress: noMinExecPeriodPolicyAddr.String(), - Status: group.PROPOSAL_STATUS_ACCEPTED, - FinalTallyResult: group.TallyResult{ - YesCount: "2", - NoCount: "0", - AbstainCount: "0", - NoWithVetoCount: "0", - }, - ExecutorResult: group.PROPOSAL_EXECUTOR_RESULT_SUCCESS, - }, - postRun: func(sdkCtx sdk.Context) { - s.bankKeeper.EXPECT().GetAllBalances(sdkCtx, noMinExecPeriodPolicyAddr).Return(sdk.NewCoins(sdk.NewInt64Coin("test", 9900))) - s.bankKeeper.EXPECT().GetAllBalances(sdkCtx, addr2).Return(sdk.NewCoins(sdk.NewInt64Coin("test", 100))) - - fromBalances := s.bankKeeper.GetAllBalances(sdkCtx, noMinExecPeriodPolicyAddr) - s.Require().Contains(fromBalances, sdk.NewInt64Coin("test", 9900)) - toBalances := s.bankKeeper.GetAllBalances(sdkCtx, addr2) - s.Require().Contains(toBalances, sdk.NewInt64Coin("test", 100)) - }, - }, - "with try exec, not enough yes votes for proposal to pass": { - req: &group.MsgSubmitProposal{ - GroupPolicyAddress: noMinExecPeriodPolicyAddr.String(), - Proposers: []string{addr5.String()}, - Exec: group.Exec_EXEC_TRY, - }, - msgs: []sdk.Msg{msgSend}, - expProposal: group.Proposal{ - GroupPolicyAddress: noMinExecPeriodPolicyAddr.String(), - Status: group.PROPOSAL_STATUS_SUBMITTED, - FinalTallyResult: group.TallyResult{ - YesCount: "0", // Since tally doesn't pass Allow(), we consider the proposal not final - NoCount: "0", - AbstainCount: "0", - NoWithVetoCount: "0", - }, - ExecutorResult: group.PROPOSAL_EXECUTOR_RESULT_NOT_RUN, - }, - postRun: func(sdkCtx sdk.Context) {}, - }, - } - for msg, spec := range specs { - spec := spec - s.Run(msg, func() { - err := spec.req.SetMsgs(spec.msgs) - s.Require().NoError(err) - - if spec.preRun != nil { - spec.preRun(spec.msgs) - } - - res, err := s.groupKeeper.SubmitProposal(s.ctx, spec.req) - if spec.expErr { - s.Require().Error(err) - return - } - s.Require().NoError(err) - id := res.ProposalId - - if !(spec.expProposal.ExecutorResult == group.PROPOSAL_EXECUTOR_RESULT_SUCCESS) { - // then all data persisted - proposalRes, err := s.groupKeeper.Proposal(s.ctx, &group.QueryProposalRequest{ProposalId: id}) - s.Require().NoError(err) - proposal := proposalRes.Proposal - - s.Assert().Equal(spec.expProposal.GroupPolicyAddress, proposal.GroupPolicyAddress) - s.Assert().Equal(spec.req.Metadata, proposal.Metadata) - s.Assert().Equal(spec.req.Proposers, proposal.Proposers) - s.Assert().Equal(s.blockTime, proposal.SubmitTime) - s.Assert().Equal(uint64(1), proposal.GroupVersion) - s.Assert().Equal(uint64(1), proposal.GroupPolicyVersion) - s.Assert().Equal(spec.expProposal.Status, proposal.Status) - s.Assert().Equal(spec.expProposal.FinalTallyResult, proposal.FinalTallyResult) - s.Assert().Equal(spec.expProposal.ExecutorResult, proposal.ExecutorResult) - s.Assert().Equal(s.blockTime.Add(time.Second), proposal.VotingPeriodEnd) - - msgs, err := proposal.GetMsgs() - s.Assert().NoError(err) - if spec.msgs == nil { // then empty list is ok - s.Assert().Len(msgs, 0) - } else { - s.Assert().Equal(spec.msgs, msgs) - } - } - - spec.postRun(s.sdkCtx) - }) - } -} - -func (s *TestSuite) TestWithdrawProposal() { - addrs := s.addrs - addr2 := addrs[1] - addr5 := addrs[4] - - msgSend := &banktypes.MsgSend{ - FromAddress: s.groupPolicyAddr.String(), - ToAddress: addr2.String(), - Amount: sdk.Coins{sdk.NewInt64Coin("test", 100)}, - } - - proposers := []string{addr2.String()} - proposalID := submitProposal(s.ctx, s, []sdk.Msg{msgSend}, proposers) - - specs := map[string]struct { - preRun func(sdkCtx sdk.Context) uint64 - proposalID uint64 - admin string - expErrMsg string - }{ - "wrong admin": { - preRun: func(sdkCtx sdk.Context) uint64 { - return submitProposal(s.ctx, s, []sdk.Msg{msgSend}, proposers) - }, - admin: addr5.String(), - expErrMsg: "unauthorized", - }, - "wrong proposalId": { - preRun: func(sdkCtx sdk.Context) uint64 { - return 1111 - }, - admin: proposers[0], - expErrMsg: "not found", - }, - "happy case with proposer": { - preRun: func(sdkCtx sdk.Context) uint64 { - return submitProposal(s.ctx, s, []sdk.Msg{msgSend}, proposers) - }, - proposalID: proposalID, - admin: proposers[0], - }, - "already closed proposal": { - preRun: func(sdkCtx sdk.Context) uint64 { - pID := submitProposal(s.ctx, s, []sdk.Msg{msgSend}, proposers) - _, err := s.groupKeeper.WithdrawProposal(s.ctx, &group.MsgWithdrawProposal{ - ProposalId: pID, - Address: proposers[0], - }) - s.Require().NoError(err) - return pID - }, - proposalID: proposalID, - admin: proposers[0], - expErrMsg: "cannot withdraw a proposal with the status of PROPOSAL_STATUS_WITHDRAWN", - }, - "happy case with group admin address": { - preRun: func(sdkCtx sdk.Context) uint64 { - return submitProposal(s.ctx, s, []sdk.Msg{msgSend}, proposers) - }, - proposalID: proposalID, - admin: proposers[0], - }, - } - for msg, spec := range specs { - spec := spec - s.Run(msg, func() { - pID := spec.preRun(s.sdkCtx) - - _, err := s.groupKeeper.WithdrawProposal(s.ctx, &group.MsgWithdrawProposal{ - ProposalId: pID, - Address: spec.admin, - }) - - if spec.expErrMsg != "" { - s.Require().Error(err) - s.Require().Contains(err.Error(), spec.expErrMsg) - return - } - - s.Require().NoError(err) - resp, err := s.groupKeeper.Proposal(s.ctx, &group.QueryProposalRequest{ProposalId: pID}) - s.Require().NoError(err) - s.Require().Equal(resp.GetProposal().Status, group.PROPOSAL_STATUS_WITHDRAWN) - }) - } -} - -func (s *TestSuite) TestVote() { - addrs := s.addrs - addr1 := addrs[0] - addr2 := addrs[1] - addr3 := addrs[2] - addr4 := addrs[3] - addr5 := addrs[4] - members := []group.MemberRequest{ - {Address: addr4.String(), Weight: "1"}, - {Address: addr3.String(), Weight: "2"}, - } - - groupRes, err := s.groupKeeper.CreateGroup(s.ctx, &group.MsgCreateGroup{ - Admin: addr1.String(), - Members: members, - }) - s.Require().NoError(err) - myGroupID := groupRes.GroupId - - policy := group.NewThresholdDecisionPolicy( - "2", - time.Duration(2), - 0, - ) - policyReq := &group.MsgCreateGroupPolicy{ - Admin: addr1.String(), - GroupId: myGroupID, - } - err = policyReq.SetDecisionPolicy(policy) - s.Require().NoError(err) - - s.setNextAccount() - policyRes, err := s.groupKeeper.CreateGroupPolicy(s.ctx, policyReq) - s.Require().NoError(err) - accountAddr := policyRes.Address - groupPolicy, err := sdk.AccAddressFromBech32(accountAddr) - s.Require().NoError(err) - s.Require().NotNil(groupPolicy) - - s.bankKeeper.EXPECT().SendCoinsFromModuleToAccount(s.sdkCtx, minttypes.ModuleName, groupPolicy, sdk.Coins{sdk.NewInt64Coin("test", 10000)}).Return(nil).AnyTimes() - s.Require().NoError(s.bankKeeper.SendCoinsFromModuleToAccount(s.sdkCtx, minttypes.ModuleName, groupPolicy, sdk.Coins{sdk.NewInt64Coin("test", 10000)})) - - req := &group.MsgSubmitProposal{ - GroupPolicyAddress: accountAddr, - Proposers: []string{addr4.String()}, - Messages: nil, - } - msg := &banktypes.MsgSend{ - FromAddress: accountAddr, - ToAddress: addr5.String(), - Amount: sdk.Coins{sdk.NewInt64Coin("test", 100)}, - } - err = req.SetMsgs([]sdk.Msg{msg}) - s.Require().NoError(err) - - proposalRes, err := s.groupKeeper.SubmitProposal(s.ctx, req) - s.Require().NoError(err) - myProposalID := proposalRes.ProposalId - - // proposals by group policy - proposalsRes, err := s.groupKeeper.ProposalsByGroupPolicy(s.ctx, &group.QueryProposalsByGroupPolicyRequest{ - Address: accountAddr, - }) - s.Require().NoError(err) - proposals := proposalsRes.Proposals - s.Require().Equal(len(proposals), 1) - s.Assert().Equal(req.GroupPolicyAddress, proposals[0].GroupPolicyAddress) - s.Assert().Equal(req.Metadata, proposals[0].Metadata) - s.Assert().Equal(req.Proposers, proposals[0].Proposers) - s.Assert().Equal(s.blockTime, proposals[0].SubmitTime) - s.Assert().Equal(uint64(1), proposals[0].GroupVersion) - s.Assert().Equal(uint64(1), proposals[0].GroupPolicyVersion) - s.Assert().Equal(group.PROPOSAL_STATUS_SUBMITTED, proposals[0].Status) - s.Assert().Equal(group.DefaultTallyResult(), proposals[0].FinalTallyResult) - - specs := map[string]struct { - srcCtx sdk.Context - expTallyResult group.TallyResult // expected after tallying - isFinal bool // is the tally result final? - req *group.MsgVote - doBefore func(ctx context.Context) - postRun func(sdkCtx sdk.Context) - expProposalStatus group.ProposalStatus // expected after tallying - expExecutorResult group.ProposalExecutorResult // expected after tallying - expErr bool - }{ - "vote yes": { - req: &group.MsgVote{ - ProposalId: myProposalID, - Voter: addr4.String(), - Option: group.VOTE_OPTION_YES, - }, - expTallyResult: group.TallyResult{ - YesCount: "1", - NoCount: "0", - AbstainCount: "0", - NoWithVetoCount: "0", - }, - expProposalStatus: group.PROPOSAL_STATUS_SUBMITTED, - expExecutorResult: group.PROPOSAL_EXECUTOR_RESULT_NOT_RUN, - postRun: func(sdkCtx sdk.Context) {}, - }, - "with try exec": { - req: &group.MsgVote{ - ProposalId: myProposalID, - Voter: addr3.String(), - Option: group.VOTE_OPTION_YES, - Exec: group.Exec_EXEC_TRY, - }, - expTallyResult: group.TallyResult{ - YesCount: "2", - NoCount: "0", - AbstainCount: "0", - NoWithVetoCount: "0", - }, - isFinal: true, - expProposalStatus: group.PROPOSAL_STATUS_ACCEPTED, - expExecutorResult: group.PROPOSAL_EXECUTOR_RESULT_SUCCESS, - doBefore: func(ctx context.Context) { - s.bankKeeper.EXPECT().Send(gomock.Any(), msg).Return(nil, nil) - }, - postRun: func(sdkCtx sdk.Context) { - s.bankKeeper.EXPECT().GetAllBalances(gomock.Any(), groupPolicy).Return(sdk.NewCoins(sdk.NewInt64Coin("test", 9900))) - s.bankKeeper.EXPECT().GetAllBalances(gomock.Any(), addr5).Return(sdk.NewCoins(sdk.NewInt64Coin("test", 100))) - - fromBalances := s.bankKeeper.GetAllBalances(sdkCtx, groupPolicy) - s.Require().Contains(fromBalances, sdk.NewInt64Coin("test", 9900)) - toBalances := s.bankKeeper.GetAllBalances(sdkCtx, addr5) - s.Require().Contains(toBalances, sdk.NewInt64Coin("test", 100)) - }, - }, - "with try exec, not enough yes votes for proposal to pass": { - req: &group.MsgVote{ - ProposalId: myProposalID, - Voter: addr4.String(), - Option: group.VOTE_OPTION_YES, - Exec: group.Exec_EXEC_TRY, - }, - expTallyResult: group.TallyResult{ - YesCount: "1", - NoCount: "0", - AbstainCount: "0", - NoWithVetoCount: "0", - }, - expProposalStatus: group.PROPOSAL_STATUS_SUBMITTED, - expExecutorResult: group.PROPOSAL_EXECUTOR_RESULT_NOT_RUN, - postRun: func(sdkCtx sdk.Context) {}, - }, - "vote no": { - req: &group.MsgVote{ - ProposalId: myProposalID, - Voter: addr4.String(), - Option: group.VOTE_OPTION_NO, - }, - expTallyResult: group.TallyResult{ - YesCount: "0", - NoCount: "1", - AbstainCount: "0", - NoWithVetoCount: "0", - }, - expProposalStatus: group.PROPOSAL_STATUS_SUBMITTED, - expExecutorResult: group.PROPOSAL_EXECUTOR_RESULT_NOT_RUN, - postRun: func(sdkCtx sdk.Context) {}, - }, - "vote abstain": { - req: &group.MsgVote{ - ProposalId: myProposalID, - Voter: addr4.String(), - Option: group.VOTE_OPTION_ABSTAIN, - }, - expTallyResult: group.TallyResult{ - YesCount: "0", - NoCount: "0", - AbstainCount: "1", - NoWithVetoCount: "0", - }, - expProposalStatus: group.PROPOSAL_STATUS_SUBMITTED, - expExecutorResult: group.PROPOSAL_EXECUTOR_RESULT_NOT_RUN, - postRun: func(sdkCtx sdk.Context) {}, - }, - "vote veto": { - req: &group.MsgVote{ - ProposalId: myProposalID, - Voter: addr4.String(), - Option: group.VOTE_OPTION_NO_WITH_VETO, - }, - expTallyResult: group.TallyResult{ - YesCount: "0", - NoCount: "0", - AbstainCount: "0", - NoWithVetoCount: "1", - }, - expProposalStatus: group.PROPOSAL_STATUS_SUBMITTED, - expExecutorResult: group.PROPOSAL_EXECUTOR_RESULT_NOT_RUN, - postRun: func(sdkCtx sdk.Context) {}, - }, - "apply decision policy early": { - req: &group.MsgVote{ - ProposalId: myProposalID, - Voter: addr3.String(), - Option: group.VOTE_OPTION_YES, - }, - expTallyResult: group.TallyResult{ - YesCount: "2", - NoCount: "0", - AbstainCount: "0", - NoWithVetoCount: "0", - }, - expProposalStatus: group.PROPOSAL_STATUS_ACCEPTED, - expExecutorResult: group.PROPOSAL_EXECUTOR_RESULT_NOT_RUN, - postRun: func(sdkCtx sdk.Context) {}, - }, - "reject new votes when final decision is made already": { - req: &group.MsgVote{ - ProposalId: myProposalID, - Voter: addr4.String(), - Option: group.VOTE_OPTION_YES, - }, - doBefore: func(ctx context.Context) { - _, err := s.groupKeeper.Vote(ctx, &group.MsgVote{ - ProposalId: myProposalID, - Voter: addr3.String(), - Option: group.VOTE_OPTION_NO_WITH_VETO, - Exec: 1, // Execute the proposal so that its status is final - }) - s.Require().NoError(err) - }, - expErr: true, - postRun: func(sdkCtx sdk.Context) {}, - }, - "metadata too long": { - req: &group.MsgVote{ - ProposalId: myProposalID, - Voter: addr4.String(), - Option: group.VOTE_OPTION_NO, - Metadata: strings.Repeat("a", 256), - }, - expErr: true, - postRun: func(sdkCtx sdk.Context) {}, - }, - "existing proposal required": { - req: &group.MsgVote{ - ProposalId: 999, - Voter: addr4.String(), - Option: group.VOTE_OPTION_NO, - }, - expErr: true, - postRun: func(sdkCtx sdk.Context) {}, - }, - "empty vote option": { - req: &group.MsgVote{ - ProposalId: myProposalID, - Voter: addr4.String(), - }, - expErr: true, - postRun: func(sdkCtx sdk.Context) {}, - }, - "invalid vote option": { - req: &group.MsgVote{ - ProposalId: myProposalID, - Voter: addr4.String(), - Option: 5, - }, - expErr: true, - postRun: func(sdkCtx sdk.Context) {}, - }, - "voter must be in group": { - req: &group.MsgVote{ - ProposalId: myProposalID, - Voter: addr2.String(), - Option: group.VOTE_OPTION_NO, - }, - expErr: true, - postRun: func(sdkCtx sdk.Context) {}, - }, - "admin that is not a group member can not vote": { - req: &group.MsgVote{ - ProposalId: myProposalID, - Voter: addr1.String(), - Option: group.VOTE_OPTION_NO, - }, - expErr: true, - postRun: func(sdkCtx sdk.Context) {}, - }, - "on voting period end": { - req: &group.MsgVote{ - ProposalId: myProposalID, - Voter: addr4.String(), - Option: group.VOTE_OPTION_NO, - }, - srcCtx: s.sdkCtx.WithBlockTime(s.blockTime.Add(time.Second)), - expErr: true, - postRun: func(sdkCtx sdk.Context) {}, - }, - "closed already": { - req: &group.MsgVote{ - ProposalId: myProposalID, - Voter: addr4.String(), - Option: group.VOTE_OPTION_NO, - }, - doBefore: func(ctx context.Context) { - s.bankKeeper.EXPECT().Send(gomock.Any(), msg).Return(nil, nil) - - _, err := s.groupKeeper.Vote(ctx, &group.MsgVote{ - ProposalId: myProposalID, - Voter: addr3.String(), - Option: group.VOTE_OPTION_YES, - Exec: 1, // Execute to close the proposal. - }) - s.Require().NoError(err) - }, - expErr: true, - postRun: func(sdkCtx sdk.Context) {}, - }, - "voted already": { - req: &group.MsgVote{ - ProposalId: myProposalID, - Voter: addr4.String(), - Option: group.VOTE_OPTION_NO, - }, - doBefore: func(ctx context.Context) { - _, err := s.groupKeeper.Vote(ctx, &group.MsgVote{ - ProposalId: myProposalID, - Voter: addr4.String(), - Option: group.VOTE_OPTION_YES, - }) - s.Require().NoError(err) - }, - expErr: true, - postRun: func(sdkCtx sdk.Context) {}, - }, - } - for msg, spec := range specs { - spec := spec - s.Run(msg, func() { - sdkCtx := s.sdkCtx - if !spec.srcCtx.IsZero() { - sdkCtx = spec.srcCtx - } - sdkCtx, _ = sdkCtx.CacheContext() - if spec.doBefore != nil { - spec.doBefore(sdkCtx) - } - _, err := s.groupKeeper.Vote(sdkCtx, spec.req) - if spec.expErr { - s.Require().Error(err) - return - } - s.Require().NoError(err) - - if !(spec.expExecutorResult == group.PROPOSAL_EXECUTOR_RESULT_SUCCESS) { - // vote is stored and all data persisted - res, err := s.groupKeeper.VoteByProposalVoter(sdkCtx, &group.QueryVoteByProposalVoterRequest{ - ProposalId: spec.req.ProposalId, - Voter: spec.req.Voter, - }) - s.Require().NoError(err) - loaded := res.Vote - s.Assert().Equal(spec.req.ProposalId, loaded.ProposalId) - s.Assert().Equal(spec.req.Voter, loaded.Voter) - s.Assert().Equal(spec.req.Option, loaded.Option) - s.Assert().Equal(spec.req.Metadata, loaded.Metadata) - s.Assert().Equal(s.blockTime, loaded.SubmitTime) - - // query votes by proposal - votesByProposalRes, err := s.groupKeeper.VotesByProposal(sdkCtx, &group.QueryVotesByProposalRequest{ - ProposalId: spec.req.ProposalId, - }) - s.Require().NoError(err) - votesByProposal := votesByProposalRes.Votes - s.Require().Equal(1, len(votesByProposal)) - vote := votesByProposal[0] - s.Assert().Equal(spec.req.ProposalId, vote.ProposalId) - s.Assert().Equal(spec.req.Voter, vote.Voter) - s.Assert().Equal(spec.req.Option, vote.Option) - s.Assert().Equal(spec.req.Metadata, vote.Metadata) - s.Assert().Equal(s.blockTime, vote.SubmitTime) - - // query votes by voter - voter := spec.req.Voter - votesByVoterRes, err := s.groupKeeper.VotesByVoter(sdkCtx, &group.QueryVotesByVoterRequest{ - Voter: voter, - }) - s.Require().NoError(err) - votesByVoter := votesByVoterRes.Votes - s.Require().Equal(1, len(votesByVoter)) - s.Assert().Equal(spec.req.ProposalId, votesByVoter[0].ProposalId) - s.Assert().Equal(voter, votesByVoter[0].Voter) - s.Assert().Equal(spec.req.Option, votesByVoter[0].Option) - s.Assert().Equal(spec.req.Metadata, votesByVoter[0].Metadata) - s.Assert().Equal(s.blockTime, votesByVoter[0].SubmitTime) - - proposalRes, err := s.groupKeeper.Proposal(sdkCtx, &group.QueryProposalRequest{ - ProposalId: spec.req.ProposalId, - }) - s.Require().NoError(err) - proposal := proposalRes.Proposal - if spec.isFinal { - s.Assert().Equal(spec.expTallyResult, proposal.FinalTallyResult) - s.Assert().Equal(spec.expProposalStatus, proposal.Status) - s.Assert().Equal(spec.expExecutorResult, proposal.ExecutorResult) - } else { - s.Assert().Equal(group.DefaultTallyResult(), proposal.FinalTallyResult) // Make sure proposal isn't mutated. + // add empty string to the list of expected calls + s.accountKeeper.EXPECT().StringToBytes("").Return(nil, errors.New("unable to decode")).AnyTimes() + s.accountKeeper.EXPECT().StringToBytes("invalid").Return(nil, errors.New("unable to decode")).AnyTimes() - // do a round of tallying - tallyResult, err := s.groupKeeper.Tally(sdkCtx, *proposal, myGroupID) - s.Require().NoError(err) + s.bankKeeper = grouptestutil.NewMockBankKeeper(ctrl) - s.Assert().Equal(spec.expTallyResult, tallyResult) - } - } + bApp := baseapp.NewBaseApp( + "group", + log.NewNopLogger(), + testCtx.DB, + encCfg.TxConfig.TxDecoder(), + ) + bApp.SetInterfaceRegistry(encCfg.InterfaceRegistry) + banktypes.RegisterMsgServer(bApp.MsgServiceRouter(), s.bankKeeper) - spec.postRun(sdkCtx) - }) - } + config := group.DefaultConfig() + s.groupKeeper = keeper.NewKeeper(key, encCfg.Codec, bApp.MsgServiceRouter(), s.accountKeeper, config) + s.ctx = testCtx.Ctx.WithBlockTime(s.blockTime) + s.sdkCtx = sdk.UnwrapSDKContext(s.ctx) - s.T().Log("test tally result should not take into account the member who left the group") - require := s.Require() - members = []group.MemberRequest{ - {Address: addr2.String(), Weight: "3"}, - {Address: addr3.String(), Weight: "2"}, - {Address: addr4.String(), Weight: "1"}, - } - reqCreate := &group.MsgCreateGroupWithPolicy{ - Admin: addr1.String(), - Members: members, - GroupMetadata: "metadata", + // Initial group, group policy and balance setup + members := []group.MemberRequest{ + {Address: s.addrs[4].String(), Weight: "1"}, {Address: s.addrs[1].String(), Weight: "2"}, } - policy = group.NewThresholdDecisionPolicy( - "4", - time.Duration(10), - 0, - ) - require.NoError(reqCreate.SetDecisionPolicy(policy)) s.setNextAccount() - result, err := s.groupKeeper.CreateGroupWithPolicy(s.ctx, reqCreate) - require.NoError(err) - require.NotNil(result) - - policyAddr := result.GroupPolicyAddress - groupID := result.GroupId - reqProposal := &group.MsgSubmitProposal{ - GroupPolicyAddress: policyAddr, - Proposers: []string{addr4.String()}, - } - require.NoError(reqProposal.SetMsgs([]sdk.Msg{&banktypes.MsgSend{ - FromAddress: policyAddr, - ToAddress: addr5.String(), - Amount: sdk.Coins{sdk.NewInt64Coin("test", 100)}, - }})) - - resSubmitProposal, err := s.groupKeeper.SubmitProposal(s.ctx, reqProposal) - require.NoError(err) - require.NotNil(resSubmitProposal) - proposalID := resSubmitProposal.ProposalId - - for _, voter := range []string{addr4.String(), addr3.String(), addr2.String()} { - _, err := s.groupKeeper.Vote(s.ctx, - &group.MsgVote{ProposalId: proposalID, Voter: voter, Option: group.VOTE_OPTION_YES}, - ) - require.NoError(err) - } - - qProposals, err := s.groupKeeper.Proposal(s.ctx, &group.QueryProposalRequest{ - ProposalId: proposalID, + groupRes, err := s.groupKeeper.CreateGroup(s.ctx, &group.MsgCreateGroup{ + Admin: s.addrs[0].String(), + Members: members, }) - require.NoError(err) - - tallyResult, err := s.groupKeeper.Tally(s.sdkCtx, *qProposals.Proposal, groupID) - require.NoError(err) - - _, err = s.groupKeeper.LeaveGroup(s.ctx, &group.MsgLeaveGroup{Address: addr4.String(), GroupId: groupID}) - require.NoError(err) - - tallyResult1, err := s.groupKeeper.Tally(s.sdkCtx, *qProposals.Proposal, groupID) - require.NoError(err) - require.NotEqual(tallyResult.String(), tallyResult1.String()) -} - -func (s *TestSuite) TestExecProposal() { - addrs := s.addrs - addr1 := addrs[0] - addr2 := addrs[1] - - msgSend1 := &banktypes.MsgSend{ - FromAddress: s.groupPolicyAddr.String(), - ToAddress: addr2.String(), - Amount: sdk.Coins{sdk.NewInt64Coin("test", 100)}, - } - msgSend2 := &banktypes.MsgSend{ - FromAddress: s.groupPolicyAddr.String(), - ToAddress: addr2.String(), - Amount: sdk.Coins{sdk.NewInt64Coin("test", 10001)}, - } - proposers := []string{addr2.String()} - - specs := map[string]struct { - srcBlockTime time.Time - setupProposal func(ctx context.Context) uint64 - expErr bool - expProposalStatus group.ProposalStatus - expExecutorResult group.ProposalExecutorResult - expBalance bool - expFromBalances sdk.Coin - expToBalances sdk.Coin - }{ - "proposal executed when accepted": { - setupProposal: func(ctx context.Context) uint64 { - s.bankKeeper.EXPECT().Send(gomock.Any(), msgSend1).Return(nil, nil) - msgs := []sdk.Msg{msgSend1} - return submitProposalAndVote(ctx, s, msgs, proposers, group.VOTE_OPTION_YES) - }, - srcBlockTime: s.blockTime.Add(minExecutionPeriod), // After min execution period end - expProposalStatus: group.PROPOSAL_STATUS_ACCEPTED, - expExecutorResult: group.PROPOSAL_EXECUTOR_RESULT_SUCCESS, - expBalance: true, - expFromBalances: sdk.NewInt64Coin("test", 9900), - expToBalances: sdk.NewInt64Coin("test", 100), - }, - "proposal with multiple messages executed when accepted": { - setupProposal: func(ctx context.Context) uint64 { - msgs := []sdk.Msg{msgSend1, msgSend1} - s.bankKeeper.EXPECT().Send(gomock.Any(), msgSend1).Return(nil, nil).MaxTimes(2) - - return submitProposalAndVote(ctx, s, msgs, proposers, group.VOTE_OPTION_YES) - }, - srcBlockTime: s.blockTime.Add(minExecutionPeriod), // After min execution period end - expProposalStatus: group.PROPOSAL_STATUS_ACCEPTED, - expExecutorResult: group.PROPOSAL_EXECUTOR_RESULT_SUCCESS, - expBalance: true, - expFromBalances: sdk.NewInt64Coin("test", 9800), - expToBalances: sdk.NewInt64Coin("test", 200), - }, - "proposal not executed when rejected": { - setupProposal: func(ctx context.Context) uint64 { - msgs := []sdk.Msg{msgSend1} - return submitProposalAndVote(ctx, s, msgs, proposers, group.VOTE_OPTION_NO) - }, - srcBlockTime: s.blockTime.Add(minExecutionPeriod), // After min execution period end - expProposalStatus: group.PROPOSAL_STATUS_REJECTED, - expExecutorResult: group.PROPOSAL_EXECUTOR_RESULT_NOT_RUN, - }, - "open proposal must not fail": { - setupProposal: func(ctx context.Context) uint64 { - return submitProposal(ctx, s, []sdk.Msg{msgSend1}, proposers) - }, - expProposalStatus: group.PROPOSAL_STATUS_SUBMITTED, - expExecutorResult: group.PROPOSAL_EXECUTOR_RESULT_NOT_RUN, - }, - "existing proposal required": { - setupProposal: func(ctx context.Context) uint64 { - return 9999 - }, - expErr: true, - }, - "Decision policy also applied on exactly voting period end": { - setupProposal: func(ctx context.Context) uint64 { - msgs := []sdk.Msg{msgSend1} - return submitProposalAndVote(ctx, s, msgs, proposers, group.VOTE_OPTION_NO) - }, - srcBlockTime: s.blockTime.Add(time.Second), // Voting period is 1s - expProposalStatus: group.PROPOSAL_STATUS_REJECTED, - expExecutorResult: group.PROPOSAL_EXECUTOR_RESULT_NOT_RUN, - }, - "Decision policy also applied after voting period end": { - setupProposal: func(ctx context.Context) uint64 { - msgs := []sdk.Msg{msgSend1} - return submitProposalAndVote(ctx, s, msgs, proposers, group.VOTE_OPTION_NO) - }, - srcBlockTime: s.blockTime.Add(time.Second).Add(time.Millisecond), // Voting period is 1s - expProposalStatus: group.PROPOSAL_STATUS_REJECTED, - expExecutorResult: group.PROPOSAL_EXECUTOR_RESULT_NOT_RUN, - }, - "exec proposal before MinExecutionPeriod should fail": { - setupProposal: func(ctx context.Context) uint64 { - msgs := []sdk.Msg{msgSend1} - return submitProposalAndVote(ctx, s, msgs, proposers, group.VOTE_OPTION_YES) - }, - srcBlockTime: s.blockTime.Add(4 * time.Second), // min execution date is 5s later after s.blockTime - expProposalStatus: group.PROPOSAL_STATUS_ACCEPTED, - expExecutorResult: group.PROPOSAL_EXECUTOR_RESULT_FAILURE, // Because MinExecutionPeriod has not passed - }, - "exec proposal at exactly MinExecutionPeriod should pass": { - setupProposal: func(ctx context.Context) uint64 { - msgs := []sdk.Msg{msgSend1} - s.bankKeeper.EXPECT().Send(gomock.Any(), msgSend1).Return(nil, nil) - return submitProposalAndVote(ctx, s, msgs, proposers, group.VOTE_OPTION_YES) - }, - srcBlockTime: s.blockTime.Add(5 * time.Second), // min execution date is 5s later after s.blockTime - expProposalStatus: group.PROPOSAL_STATUS_ACCEPTED, - expExecutorResult: group.PROPOSAL_EXECUTOR_RESULT_SUCCESS, - }, - "prevent double execution when successful": { - setupProposal: func(ctx context.Context) uint64 { - myProposalID := submitProposalAndVote(ctx, s, []sdk.Msg{msgSend1}, proposers, group.VOTE_OPTION_YES) - s.bankKeeper.EXPECT().Send(gomock.Any(), msgSend1).Return(nil, nil) - - // Wait after min execution period end before Exec - sdkCtx := sdk.UnwrapSDKContext(ctx) - sdkCtx = sdkCtx.WithBlockTime(sdkCtx.BlockTime().Add(minExecutionPeriod)) // MinExecutionPeriod is 5s - _, err := s.groupKeeper.Exec(sdkCtx, &group.MsgExec{Executor: addr1.String(), ProposalId: myProposalID}) - s.Require().NoError(err) - return myProposalID - }, - srcBlockTime: s.blockTime.Add(minExecutionPeriod), // After min execution period end - expErr: true, // since proposal is pruned after a successful MsgExec - expProposalStatus: group.PROPOSAL_STATUS_ACCEPTED, - expExecutorResult: group.PROPOSAL_EXECUTOR_RESULT_SUCCESS, - expBalance: true, - expFromBalances: sdk.NewInt64Coin("test", 9900), - expToBalances: sdk.NewInt64Coin("test", 100), - }, - "rollback all msg updates on failure": { - setupProposal: func(ctx context.Context) uint64 { - msgs := []sdk.Msg{msgSend1, msgSend2} - s.bankKeeper.EXPECT().Send(gomock.Any(), msgSend1).Return(nil, nil) - s.bankKeeper.EXPECT().Send(gomock.Any(), msgSend2).Return(nil, fmt.Errorf("error")) - - return submitProposalAndVote(ctx, s, msgs, proposers, group.VOTE_OPTION_YES) - }, - srcBlockTime: s.blockTime.Add(minExecutionPeriod), // After min execution period end - expProposalStatus: group.PROPOSAL_STATUS_ACCEPTED, - expExecutorResult: group.PROPOSAL_EXECUTOR_RESULT_FAILURE, - }, - "executable when failed before": { - setupProposal: func(ctx context.Context) uint64 { - msgs := []sdk.Msg{msgSend2} - myProposalID := submitProposalAndVote(ctx, s, msgs, proposers, group.VOTE_OPTION_YES) - - // Wait after min execution period end before Exec - sdkCtx := sdk.UnwrapSDKContext(ctx) - sdkCtx = sdkCtx.WithBlockTime(sdkCtx.BlockTime().Add(minExecutionPeriod)) // MinExecutionPeriod is 5s - s.bankKeeper.EXPECT().Send(gomock.Any(), msgSend2).Return(nil, fmt.Errorf("error")) - _, err := s.groupKeeper.Exec(sdkCtx, &group.MsgExec{Executor: addr1.String(), ProposalId: myProposalID}) - s.bankKeeper.EXPECT().Send(gomock.Any(), msgSend2).Return(nil, nil) - - s.Require().NoError(err) - s.Require().NoError(s.bankKeeper.SendCoinsFromModuleToAccount(s.sdkCtx, minttypes.ModuleName, s.groupPolicyAddr, sdk.Coins{sdk.NewInt64Coin("test", 10000)})) + s.Require().NoError(err) + s.groupID = groupRes.GroupId - return myProposalID - }, - srcBlockTime: s.blockTime.Add(minExecutionPeriod), // After min execution period end - expProposalStatus: group.PROPOSAL_STATUS_ACCEPTED, - expExecutorResult: group.PROPOSAL_EXECUTOR_RESULT_SUCCESS, - }, + policy := group.NewThresholdDecisionPolicy( + "2", + time.Second, + minExecutionPeriod, // Must wait 5 seconds before executing proposal + ) + policyReq := &group.MsgCreateGroupPolicy{ + Admin: s.addrs[0].String(), + GroupId: s.groupID, } - for msg, spec := range specs { - spec := spec - s.Run(msg, func() { - sdkCtx, _ := s.sdkCtx.CacheContext() - proposalID := spec.setupProposal(sdkCtx) - - if !spec.srcBlockTime.IsZero() { - sdkCtx = sdkCtx.WithBlockTime(spec.srcBlockTime) - } - - _, err := s.groupKeeper.Exec(sdkCtx, &group.MsgExec{Executor: addr1.String(), ProposalId: proposalID}) - if spec.expErr { - s.Require().Error(err) - return - } - s.Require().NoError(err) - - if !(spec.expExecutorResult == group.PROPOSAL_EXECUTOR_RESULT_SUCCESS) { - - // and proposal is updated - res, err := s.groupKeeper.Proposal(sdkCtx, &group.QueryProposalRequest{ProposalId: proposalID}) - s.Require().NoError(err) - proposal := res.Proposal + err = policyReq.SetDecisionPolicy(policy) + s.Require().NoError(err) + s.setNextAccount() - exp := group.ProposalStatus_name[int32(spec.expProposalStatus)] - got := group.ProposalStatus_name[int32(proposal.Status)] - s.Assert().Equal(exp, got) + groupSeq := s.groupKeeper.GetGroupSequence(s.sdkCtx) + s.Require().Equal(groupSeq, uint64(1)) - exp = group.ProposalExecutorResult_name[int32(spec.expExecutorResult)] - got = group.ProposalExecutorResult_name[int32(proposal.ExecutorResult)] - s.Assert().Equal(exp, got) - } + policyRes, err := s.groupKeeper.CreateGroupPolicy(s.ctx, policyReq) + s.Require().NoError(err) - if spec.expBalance { - s.bankKeeper.EXPECT().GetAllBalances(sdkCtx, s.groupPolicyAddr).Return(sdk.Coins{spec.expFromBalances}) - s.bankKeeper.EXPECT().GetAllBalances(sdkCtx, addr2).Return(sdk.Coins{spec.expToBalances}) + addrbz, err := address.NewBech32Codec("cosmos").StringToBytes(policyRes.Address) + s.Require().NoError(err) + s.policy = policy + s.groupPolicyAddr = addrbz - fromBalances := s.bankKeeper.GetAllBalances(sdkCtx, s.groupPolicyAddr) - s.Require().Contains(fromBalances, spec.expFromBalances) - toBalances := s.bankKeeper.GetAllBalances(sdkCtx, addr2) - s.Require().Contains(toBalances, spec.expToBalances) - } - }) - } + s.bankKeeper.EXPECT().MintCoins(s.sdkCtx, minttypes.ModuleName, sdk.Coins{sdk.NewInt64Coin("test", 100000)}).Return(nil).AnyTimes() + s.bankKeeper.MintCoins(s.sdkCtx, minttypes.ModuleName, sdk.Coins{sdk.NewInt64Coin("test", 100000)}) + s.bankKeeper.EXPECT().SendCoinsFromModuleToAccount(s.sdkCtx, minttypes.ModuleName, s.groupPolicyAddr, sdk.Coins{sdk.NewInt64Coin("test", 10000)}).Return(nil).AnyTimes() + s.bankKeeper.SendCoinsFromModuleToAccount(s.sdkCtx, minttypes.ModuleName, s.groupPolicyAddr, sdk.Coins{sdk.NewInt64Coin("test", 10000)}) } -func (s *TestSuite) TestExecPrunedProposalsAndVotes() { - addrs := s.addrs - addr1 := addrs[0] - addr2 := addrs[1] - - proposers := []string{addr2.String()} - specs := map[string]struct { - srcBlockTime time.Time - setupProposal func(ctx context.Context) uint64 - expErr bool - expErrMsg string - expExecutorResult group.ProposalExecutorResult - }{ - "proposal pruned after executor result success": { - setupProposal: func(ctx context.Context) uint64 { - msgSend1 := &banktypes.MsgSend{ - FromAddress: s.groupPolicyAddr.String(), - ToAddress: addr2.String(), - Amount: sdk.Coins{sdk.NewInt64Coin("test", 101)}, - } - msgs := []sdk.Msg{msgSend1} - s.bankKeeper.EXPECT().Send(gomock.Any(), msgSend1).Return(nil, nil) - return submitProposalAndVote(ctx, s, msgs, proposers, group.VOTE_OPTION_YES) - }, - expErrMsg: "load proposal: not found", - expExecutorResult: group.PROPOSAL_EXECUTOR_RESULT_SUCCESS, - }, - "proposal with multiple messages pruned when executed with result success": { - setupProposal: func(ctx context.Context) uint64 { - msgSend1 := &banktypes.MsgSend{ - FromAddress: s.groupPolicyAddr.String(), - ToAddress: addr2.String(), - Amount: sdk.Coins{sdk.NewInt64Coin("test", 102)}, - } - s.bankKeeper.EXPECT().Send(gomock.Any(), msgSend1).Return(nil, nil).MaxTimes(2) - - msgs := []sdk.Msg{msgSend1, msgSend1} - return submitProposalAndVote(ctx, s, msgs, proposers, group.VOTE_OPTION_YES) - }, - expErrMsg: "load proposal: not found", - expExecutorResult: group.PROPOSAL_EXECUTOR_RESULT_SUCCESS, - }, - "proposal not pruned when not executed and rejected": { - setupProposal: func(ctx context.Context) uint64 { - msgSend1 := &banktypes.MsgSend{ - FromAddress: s.groupPolicyAddr.String(), - ToAddress: addr2.String(), - Amount: sdk.Coins{sdk.NewInt64Coin("test", 103)}, - } - msgs := []sdk.Msg{msgSend1} - return submitProposalAndVote(ctx, s, msgs, proposers, group.VOTE_OPTION_NO) - }, - expExecutorResult: group.PROPOSAL_EXECUTOR_RESULT_NOT_RUN, - }, - "open proposal is not pruned which must not fail ": { - setupProposal: func(ctx context.Context) uint64 { - msgSend1 := &banktypes.MsgSend{ - FromAddress: s.groupPolicyAddr.String(), - ToAddress: addr2.String(), - Amount: sdk.Coins{sdk.NewInt64Coin("test", 104)}, - } - return submitProposal(ctx, s, []sdk.Msg{msgSend1}, proposers) - }, - expExecutorResult: group.PROPOSAL_EXECUTOR_RESULT_NOT_RUN, - }, - "proposal not pruned with group modified before tally": { - setupProposal: func(ctx context.Context) uint64 { - msgSend1 := &banktypes.MsgSend{ - FromAddress: s.groupPolicyAddr.String(), - ToAddress: addr2.String(), - Amount: sdk.Coins{sdk.NewInt64Coin("test", 105)}, - } - myProposalID := submitProposal(ctx, s, []sdk.Msg{msgSend1}, proposers) - - // then modify group - _, err := s.groupKeeper.UpdateGroupMetadata(ctx, &group.MsgUpdateGroupMetadata{ - Admin: addr1.String(), - GroupId: s.groupID, - }) - s.Require().NoError(err) - return myProposalID - }, - expExecutorResult: group.PROPOSAL_EXECUTOR_RESULT_NOT_RUN, - }, - "proposal not pruned with group policy modified before tally": { - setupProposal: func(ctx context.Context) uint64 { - msgSend1 := &banktypes.MsgSend{ - FromAddress: s.groupPolicyAddr.String(), - ToAddress: addr2.String(), - Amount: sdk.Coins{sdk.NewInt64Coin("test", 106)}, - } - - myProposalID := submitProposal(ctx, s, []sdk.Msg{msgSend1}, proposers) - _, err := s.groupKeeper.UpdateGroupPolicyMetadata(ctx, &group.MsgUpdateGroupPolicyMetadata{ - Admin: addr1.String(), - GroupPolicyAddress: s.groupPolicyAddr.String(), - }) - s.Require().NoError(err) - return myProposalID - }, - expErr: true, // since proposal status will be `aborted` when group policy is modified - expErrMsg: "not possible to exec with proposal status", - expExecutorResult: group.PROPOSAL_EXECUTOR_RESULT_NOT_RUN, - }, - "proposal exists when rollback all msg updates on failure": { - setupProposal: func(ctx context.Context) uint64 { - msgSend1 := &banktypes.MsgSend{ - FromAddress: s.groupPolicyAddr.String(), - ToAddress: addr2.String(), - Amount: sdk.Coins{sdk.NewInt64Coin("test", 107)}, - } - - msgSend2 := &banktypes.MsgSend{ - FromAddress: s.groupPolicyAddr.String(), - ToAddress: addr2.String(), - Amount: sdk.Coins{sdk.NewInt64Coin("test", 10002)}, - } - - msgs := []sdk.Msg{msgSend1, msgSend2} - s.bankKeeper.EXPECT().Send(gomock.Any(), msgSend1).Return(nil, fmt.Errorf("error")) - - return submitProposalAndVote(ctx, s, msgs, proposers, group.VOTE_OPTION_YES) - }, - expExecutorResult: group.PROPOSAL_EXECUTOR_RESULT_FAILURE, - }, - "pruned when proposal is executable when failed before": { - setupProposal: func(ctx context.Context) uint64 { - msgSend2 := &banktypes.MsgSend{ - FromAddress: s.groupPolicyAddr.String(), - ToAddress: addr2.String(), - Amount: sdk.Coins{sdk.NewInt64Coin("test", 10003)}, - } - - msgs := []sdk.Msg{msgSend2} - - myProposalID := submitProposalAndVote(ctx, s, msgs, proposers, group.VOTE_OPTION_YES) - - s.bankKeeper.EXPECT().Send(gomock.Any(), msgSend2).Return(nil, fmt.Errorf("error")) - - // Wait for min execution period end - sdkCtx := sdk.UnwrapSDKContext(ctx) - sdkCtx = sdkCtx.WithBlockTime(sdkCtx.BlockTime().Add(minExecutionPeriod)) - _, err := s.groupKeeper.Exec(sdkCtx, &group.MsgExec{Executor: addr1.String(), ProposalId: myProposalID}) - s.bankKeeper.EXPECT().Send(gomock.Any(), msgSend2).Return(nil, nil) +func (s *TestSuite) setNextAccount() { + nextAccVal := s.groupKeeper.GetGroupPolicySeq(s.sdkCtx) + 1 + derivationKey := make([]byte, 8) + binary.BigEndian.PutUint64(derivationKey, nextAccVal) - s.Require().NoError(err) - return myProposalID - }, - expErrMsg: "load proposal: not found", - expExecutorResult: group.PROPOSAL_EXECUTOR_RESULT_SUCCESS, - }, - } - for msg, spec := range specs { - spec := spec - s.Run(msg, func() { - sdkCtx, _ := s.sdkCtx.CacheContext() - proposalID := spec.setupProposal(sdkCtx) + ac, err := authtypes.NewModuleCredential(group.ModuleName, []byte{keeper.GroupPolicyTablePrefix}, derivationKey) + s.Require().NoError(err) - if !spec.srcBlockTime.IsZero() { - sdkCtx = sdkCtx.WithBlockTime(spec.srcBlockTime) - } + groupPolicyAcc, err := authtypes.NewBaseAccountWithPubKey(ac) + s.Require().NoError(err) - // Wait for min execution period end - sdkCtx = sdkCtx.WithBlockTime(sdkCtx.BlockTime().Add(minExecutionPeriod)) - _, err := s.groupKeeper.Exec(sdkCtx, &group.MsgExec{Executor: addr1.String(), ProposalId: proposalID}) - if spec.expErr { - s.Require().Error(err) - s.Require().Contains(err.Error(), spec.expErrMsg) - return - } - s.Require().NoError(err) + groupPolicyAccBumpAccountNumber, err := authtypes.NewBaseAccountWithPubKey(ac) + s.Require().NoError(err) + groupPolicyAccBumpAccountNumber.SetAccountNumber(nextAccVal) - if spec.expExecutorResult == group.PROPOSAL_EXECUTOR_RESULT_SUCCESS { - // Make sure proposal is deleted from state - _, err := s.groupKeeper.Proposal(sdkCtx, &group.QueryProposalRequest{ProposalId: proposalID}) - s.Require().Contains(err.Error(), spec.expErrMsg) - res, err := s.groupKeeper.VotesByProposal(sdkCtx, &group.QueryVotesByProposalRequest{ProposalId: proposalID}) - s.Require().NoError(err) - s.Require().Empty(res.GetVotes()) + addrcdc := address.NewBech32Codec("cosmos") + addrst, err := addrcdc.BytesToString(ac.Address()) + s.Require().NoError(err) - } else { - // Check that proposal and votes exists - res, err := s.groupKeeper.Proposal(sdkCtx, &group.QueryProposalRequest{ProposalId: proposalID}) - s.Require().NoError(err) - _, err = s.groupKeeper.VotesByProposal(sdkCtx, &group.QueryVotesByProposalRequest{ProposalId: res.Proposal.Id}) - s.Require().NoError(err) - s.Require().Equal("", spec.expErrMsg) + s.accountKeeper.EXPECT().GetAccount(gomock.Any(), sdk.AccAddress(ac.Address())).Return(nil).AnyTimes() + s.accountKeeper.EXPECT().NewAccount(gomock.Any(), groupPolicyAcc).Return(groupPolicyAccBumpAccountNumber).AnyTimes() + s.accountKeeper.EXPECT().SetAccount(gomock.Any(), sdk.AccountI(groupPolicyAccBumpAccountNumber)).Return().AnyTimes() + s.accountKeeper.EXPECT().StringToBytes(addrst).Return(ac.Address().Bytes(), nil).AnyTimes() + s.accountKeeper.EXPECT().BytesToString(ac.Address().Bytes()).Return(addrst, nil).AnyTimes() +} - exp := group.ProposalExecutorResult_name[int32(spec.expExecutorResult)] - got := group.ProposalExecutorResult_name[int32(res.Proposal.ExecutorResult)] - s.Assert().Equal(exp, got) - } - }) - } +func TestKeeperTestSuite(t *testing.T) { + suite.Run(t, new(TestSuite)) } func (s *TestSuite) TestProposalsByVPEnd() { @@ -2944,186 +296,6 @@ func (s *TestSuite) TestProposalsByVPEnd() { } } -func (s *TestSuite) TestLeaveGroup() { - addrs := simtestutil.CreateIncrementalAccounts(7) - - admin1 := addrs[0] - member1 := addrs[1] - member2 := addrs[2] - member3 := addrs[3] - member4 := addrs[4] - admin2 := addrs[5] - admin3 := addrs[6] - require := s.Require() - - members := []group.MemberRequest{ - { - Address: member1.String(), - Weight: "1", - Metadata: "metadata", - }, - { - Address: member2.String(), - Weight: "2", - Metadata: "metadata", - }, - { - Address: member3.String(), - Weight: "3", - Metadata: "metadata", - }, - } - policy := group.NewThresholdDecisionPolicy( - "3", - time.Hour, - time.Hour, - ) - s.setNextAccount() - _, groupID1 := s.createGroupAndGroupPolicy(admin1, members, policy) - - members = []group.MemberRequest{ - { - Address: member1.String(), - Weight: "1", - Metadata: "metadata", - }, - } - - s.setNextAccount() - _, groupID2 := s.createGroupAndGroupPolicy(admin2, members, nil) - - members = []group.MemberRequest{ - { - Address: member1.String(), - Weight: "1", - Metadata: "metadata", - }, - { - Address: member2.String(), - Weight: "2", - Metadata: "metadata", - }, - } - policy = &group.PercentageDecisionPolicy{ - Percentage: "0.5", - Windows: &group.DecisionPolicyWindows{VotingPeriod: time.Hour}, - } - - s.setNextAccount() - - _, groupID3 := s.createGroupAndGroupPolicy(admin3, members, policy) - testCases := []struct { - name string - req *group.MsgLeaveGroup - expErr bool - errMsg string - expMembersSize int - memberWeight math.Dec - }{ - { - "expect error: group not found", - &group.MsgLeaveGroup{ - GroupId: 100000, - Address: member1.String(), - }, - true, - "group: not found", - 0, - math.NewDecFromInt64(0), - }, - { - "expect error: member not part of group", - &group.MsgLeaveGroup{ - GroupId: groupID1, - Address: member4.String(), - }, - true, - "not part of group", - 0, - math.NewDecFromInt64(0), - }, - { - "valid testcase: decision policy is not present (and group total weight can be 0)", - &group.MsgLeaveGroup{ - GroupId: groupID2, - Address: member1.String(), - }, - false, - "", - 0, - math.NewDecFromInt64(1), - }, - { - "valid testcase: threshold decision policy", - &group.MsgLeaveGroup{ - GroupId: groupID1, - Address: member3.String(), - }, - false, - "", - 2, - math.NewDecFromInt64(3), - }, - { - "valid request: can leave group policy threshold more than group weight", - &group.MsgLeaveGroup{ - GroupId: groupID1, - Address: member2.String(), - }, - false, - "", - 1, - math.NewDecFromInt64(2), - }, - { - "valid request: can leave group (percentage decision policy)", - &group.MsgLeaveGroup{ - GroupId: groupID3, - Address: member2.String(), - }, - false, - "", - 1, - math.NewDecFromInt64(2), - }, - } - - for _, tc := range testCases { - s.Run(tc.name, func() { - var groupWeight1 math.Dec - if !tc.expErr { - groupRes, err := s.groupKeeper.GroupInfo(s.ctx, &group.QueryGroupInfoRequest{GroupId: tc.req.GroupId}) - require.NoError(err) - groupWeight1, err = math.NewNonNegativeDecFromString(groupRes.Info.TotalWeight) - require.NoError(err) - } - - res, err := s.groupKeeper.LeaveGroup(s.ctx, tc.req) - if tc.expErr { - require.Error(err) - require.Contains(err.Error(), tc.errMsg) - } else { - require.NoError(err) - require.NotNil(res) - res, err := s.groupKeeper.GroupMembers(s.ctx, &group.QueryGroupMembersRequest{ - GroupId: tc.req.GroupId, - }) - require.NoError(err) - require.Len(res.Members, tc.expMembersSize) - - groupRes, err := s.groupKeeper.GroupInfo(s.ctx, &group.QueryGroupInfoRequest{GroupId: tc.req.GroupId}) - require.NoError(err) - groupWeight2, err := math.NewNonNegativeDecFromString(groupRes.Info.TotalWeight) - require.NoError(err) - - rWeight, err := groupWeight1.Sub(tc.memberWeight) - require.NoError(err) - require.Equal(rWeight.Cmp(groupWeight2), 0) - } - }) - } -} - func (s *TestSuite) TestPruneProposals() { addrs := s.addrs expirationTime := time.Hour * 24 * 15 // 15 days @@ -3262,7 +434,7 @@ func (s *TestSuite) TestTallyProposalsAtVPEnd() { groupRes, err := s.groupKeeper.CreateGroupWithPolicy(s.ctx, groupMsg) s.Require().NoError(err) accountAddr := groupRes.GetGroupPolicyAddress() - groupPolicy, err := sdk.AccAddressFromBech32(accountAddr) + groupPolicy, err := s.accountKeeper.StringToBytes(accountAddr) s.Require().NoError(err) s.Require().NotNil(groupPolicy) diff --git a/x/group/keeper/msg_server.go b/x/group/keeper/msg_server.go index 94feeaed3ee8..0619e0e7098b 100644 --- a/x/group/keeper/msg_server.go +++ b/x/group/keeper/msg_server.go @@ -1,9 +1,11 @@ package keeper import ( + "bytes" "context" "encoding/binary" "fmt" + "strings" errorsmod "cosmossdk.io/errors" @@ -22,28 +24,28 @@ var _ group.MsgServer = Keeper{} // Tracking issues https://github.com/cosmos/cosmos-sdk/issues/9054, https://github.com/cosmos/cosmos-sdk/discussions/9072 const gasCostPerIteration = uint64(20) -func (k Keeper) CreateGroup(goCtx context.Context, req *group.MsgCreateGroup) (*group.MsgCreateGroupResponse, error) { - ctx := sdk.UnwrapSDKContext(goCtx) - metadata := req.Metadata - members := group.MemberRequests{Members: req.Members} - admin := req.Admin +func (k Keeper) CreateGroup(goCtx context.Context, msg *group.MsgCreateGroup) (*group.MsgCreateGroupResponse, error) { + if _, err := k.accKeeper.StringToBytes(msg.Admin); err != nil { + return nil, errorsmod.Wrapf(sdkerrors.ErrInvalidAddress, "invalid admin address: %s", msg.Admin) + } - if err := members.ValidateBasic(); err != nil { - return nil, err + if err := k.validateMembers(msg.Members); err != nil { + return nil, errorsmod.Wrap(err, "members") } - if err := k.assertMetadataLength(metadata, "group metadata"); err != nil { + if err := k.assertMetadataLength(msg.Metadata, "group metadata"); err != nil { return nil, err } totalWeight := math.NewDecFromInt64(0) - for i := range members.Members { - m := members.Members[i] + for _, m := range msg.Members { if err := k.assertMetadataLength(m.Metadata, "member metadata"); err != nil { return nil, err } // Members of a group must have a positive weight. + // NOTE: group member with zero weight are only allowed when updating group members. + // If the member has a zero weight, it will be removed from the group. weight, err := math.NewPositiveDecFromString(m.Weight) if err != nil { return nil, err @@ -57,10 +59,11 @@ func (k Keeper) CreateGroup(goCtx context.Context, req *group.MsgCreateGroup) (* } // Create a new group in the groupTable. + ctx := sdk.UnwrapSDKContext(goCtx) groupInfo := &group.GroupInfo{ Id: k.groupTable.Sequence().PeekNextVal(ctx.KVStore(k.key)), - Admin: admin, - Metadata: metadata, + Admin: msg.Admin, + Metadata: msg.Metadata, Version: 1, TotalWeight: totalWeight.String(), CreatedAt: ctx.BlockTime(), @@ -71,8 +74,7 @@ func (k Keeper) CreateGroup(goCtx context.Context, req *group.MsgCreateGroup) (* } // Create new group members in the groupMemberTable. - for i := range members.Members { - m := members.Members[i] + for i, m := range msg.Members { err := k.groupMemberTable.Create(ctx.KVStore(k.key), &group.GroupMember{ GroupId: groupID, Member: &group.Member{ @@ -87,31 +89,43 @@ func (k Keeper) CreateGroup(goCtx context.Context, req *group.MsgCreateGroup) (* } } - err = ctx.EventManager().EmitTypedEvent(&group.EventCreateGroup{GroupId: groupID}) - if err != nil { + if err := ctx.EventManager().EmitTypedEvent(&group.EventCreateGroup{GroupId: groupID}); err != nil { return nil, err } return &group.MsgCreateGroupResponse{GroupId: groupID}, nil } -func (k Keeper) UpdateGroupMembers(goCtx context.Context, req *group.MsgUpdateGroupMembers) (*group.MsgUpdateGroupMembersResponse, error) { +func (k Keeper) UpdateGroupMembers(goCtx context.Context, msg *group.MsgUpdateGroupMembers) (*group.MsgUpdateGroupMembersResponse, error) { + if msg.GroupId == 0 { + return nil, errorsmod.Wrap(errors.ErrEmpty, "group id") + } + + if len(msg.MemberUpdates) == 0 { + return nil, errorsmod.Wrap(errors.ErrEmpty, "member updates") + } + + if err := k.validateMembers(msg.MemberUpdates); err != nil { + return nil, errorsmod.Wrap(err, "members") + } + ctx := sdk.UnwrapSDKContext(goCtx) action := func(g *group.GroupInfo) error { totalWeight, err := math.NewNonNegativeDecFromString(g.TotalWeight) if err != nil { return errorsmod.Wrap(err, "group total weight") } - for i := range req.MemberUpdates { - if err := k.assertMetadataLength(req.MemberUpdates[i].Metadata, "group member metadata"); err != nil { + + for _, member := range msg.MemberUpdates { + if err := k.assertMetadataLength(member.Metadata, "group member metadata"); err != nil { return err } groupMember := group.GroupMember{ - GroupId: req.GroupId, + GroupId: msg.GroupId, Member: &group.Member{ - Address: req.MemberUpdates[i].Address, - Weight: req.MemberUpdates[i].Weight, - Metadata: req.MemberUpdates[i].Metadata, + Address: member.Address, + Weight: member.Weight, + Metadata: member.Metadata, }, } @@ -195,137 +209,160 @@ func (k Keeper) UpdateGroupMembers(goCtx context.Context, req *group.MsgUpdateGr return k.groupTable.Update(ctx.KVStore(k.key), g.Id, g) } - err := k.doUpdateGroup(ctx, req, action, "members updated") - if err != nil { + if err := k.doUpdateGroup(ctx, msg.GetGroupID(), msg.GetAdmin(), action, "members updated"); err != nil { return nil, err } return &group.MsgUpdateGroupMembersResponse{}, nil } -func (k Keeper) UpdateGroupAdmin(goCtx context.Context, req *group.MsgUpdateGroupAdmin) (*group.MsgUpdateGroupAdminResponse, error) { +func (k Keeper) UpdateGroupAdmin(goCtx context.Context, msg *group.MsgUpdateGroupAdmin) (*group.MsgUpdateGroupAdminResponse, error) { + if msg.GroupId == 0 { + return nil, errorsmod.Wrap(errors.ErrEmpty, "group id") + } + + if strings.EqualFold(msg.Admin, msg.NewAdmin) { + return nil, errorsmod.Wrap(errors.ErrInvalid, "new and old admin are the same") + } + + if _, err := k.accKeeper.StringToBytes(msg.Admin); err != nil { + return nil, errorsmod.Wrap(sdkerrors.ErrInvalidAddress, "admin address") + } + + if _, err := k.accKeeper.StringToBytes(msg.NewAdmin); err != nil { + return nil, errorsmod.Wrap(sdkerrors.ErrInvalidAddress, "new admin address") + } + ctx := sdk.UnwrapSDKContext(goCtx) action := func(g *group.GroupInfo) error { - g.Admin = req.NewAdmin + g.Admin = msg.NewAdmin g.Version++ return k.groupTable.Update(ctx.KVStore(k.key), g.Id, g) } - err := k.doUpdateGroup(ctx, req, action, "admin updated") - if err != nil { + if err := k.doUpdateGroup(ctx, msg.GetGroupID(), msg.GetAdmin(), action, "admin updated"); err != nil { return nil, err } return &group.MsgUpdateGroupAdminResponse{}, nil } -func (k Keeper) UpdateGroupMetadata(goCtx context.Context, req *group.MsgUpdateGroupMetadata) (*group.MsgUpdateGroupMetadataResponse, error) { +func (k Keeper) UpdateGroupMetadata(goCtx context.Context, msg *group.MsgUpdateGroupMetadata) (*group.MsgUpdateGroupMetadataResponse, error) { + if msg.GroupId == 0 { + return nil, errorsmod.Wrap(errors.ErrEmpty, "group id") + } + + if err := k.assertMetadataLength(msg.Metadata, "group metadata"); err != nil { + return nil, err + } + + if _, err := k.accKeeper.StringToBytes(msg.Admin); err != nil { + return nil, errorsmod.Wrap(sdkerrors.ErrInvalidAddress, "admin address") + } + ctx := sdk.UnwrapSDKContext(goCtx) action := func(g *group.GroupInfo) error { - g.Metadata = req.Metadata + g.Metadata = msg.Metadata g.Version++ return k.groupTable.Update(ctx.KVStore(k.key), g.Id, g) } - if err := k.assertMetadataLength(req.Metadata, "group metadata"); err != nil { - return nil, err - } - - err := k.doUpdateGroup(ctx, req, action, "metadata updated") - if err != nil { + if err := k.doUpdateGroup(ctx, msg.GetGroupID(), msg.GetAdmin(), action, "metadata updated"); err != nil { return nil, err } return &group.MsgUpdateGroupMetadataResponse{}, nil } -func (k Keeper) CreateGroupWithPolicy(goCtx context.Context, req *group.MsgCreateGroupWithPolicy) (*group.MsgCreateGroupWithPolicyResponse, error) { - groupRes, err := k.CreateGroup(goCtx, &group.MsgCreateGroup{ - Admin: req.Admin, - Members: req.Members, - Metadata: req.GroupMetadata, +func (k Keeper) CreateGroupWithPolicy(ctx context.Context, msg *group.MsgCreateGroupWithPolicy) (*group.MsgCreateGroupWithPolicyResponse, error) { + // NOTE: admin, and group message validation is performed in the CreateGroup method + groupRes, err := k.CreateGroup(ctx, &group.MsgCreateGroup{ + Admin: msg.Admin, + Members: msg.Members, + Metadata: msg.GroupMetadata, }) if err != nil { return nil, errorsmod.Wrap(err, "group response") } groupID := groupRes.GroupId - var groupPolicyAddr sdk.AccAddress - groupPolicyRes, err := k.CreateGroupPolicy(goCtx, &group.MsgCreateGroupPolicy{ - Admin: req.Admin, + // NOTE: group policy message validation is performed in the CreateGroupPolicy method + groupPolicyRes, err := k.CreateGroupPolicy(ctx, &group.MsgCreateGroupPolicy{ + Admin: msg.Admin, GroupId: groupID, - Metadata: req.GroupPolicyMetadata, - DecisionPolicy: req.DecisionPolicy, + Metadata: msg.GroupPolicyMetadata, + DecisionPolicy: msg.DecisionPolicy, }) if err != nil { return nil, errorsmod.Wrap(err, "group policy response") } - policyAddr := groupPolicyRes.Address - groupPolicyAddr, err = sdk.AccAddressFromBech32(policyAddr) - if err != nil { - return nil, errorsmod.Wrap(err, "group policy address") - } - groupPolicyAddress := groupPolicyAddr.String() - - if req.GroupPolicyAsAdmin { + if msg.GroupPolicyAsAdmin { updateAdminReq := &group.MsgUpdateGroupAdmin{ GroupId: groupID, - Admin: req.Admin, - NewAdmin: groupPolicyAddress, + Admin: msg.Admin, + NewAdmin: groupPolicyRes.Address, } - _, err = k.UpdateGroupAdmin(goCtx, updateAdminReq) + _, err = k.UpdateGroupAdmin(ctx, updateAdminReq) if err != nil { return nil, err } updatePolicyAddressReq := &group.MsgUpdateGroupPolicyAdmin{ - Admin: req.Admin, - GroupPolicyAddress: groupPolicyAddress, - NewAdmin: groupPolicyAddress, + Admin: msg.Admin, + GroupPolicyAddress: groupPolicyRes.Address, + NewAdmin: groupPolicyRes.Address, } - _, err = k.UpdateGroupPolicyAdmin(goCtx, updatePolicyAddressReq) + _, err = k.UpdateGroupPolicyAdmin(ctx, updatePolicyAddressReq) if err != nil { return nil, err } } - return &group.MsgCreateGroupWithPolicyResponse{GroupId: groupID, GroupPolicyAddress: groupPolicyAddress}, nil + return &group.MsgCreateGroupWithPolicyResponse{GroupId: groupID, GroupPolicyAddress: groupPolicyRes.Address}, nil } -func (k Keeper) CreateGroupPolicy(goCtx context.Context, req *group.MsgCreateGroupPolicy) (*group.MsgCreateGroupPolicyResponse, error) { - ctx := sdk.UnwrapSDKContext(goCtx) - admin, err := sdk.AccAddressFromBech32(req.GetAdmin()) - if err != nil { - return nil, errorsmod.Wrap(err, "request admin") +func (k Keeper) CreateGroupPolicy(goCtx context.Context, msg *group.MsgCreateGroupPolicy) (*group.MsgCreateGroupPolicyResponse, error) { + if msg.GroupId == 0 { + return nil, errorsmod.Wrap(errors.ErrEmpty, "group id") } - policy, err := req.GetDecisionPolicy() + + if err := k.assertMetadataLength(msg.GetMetadata(), "group policy metadata"); err != nil { + return nil, err + } + + policy, err := msg.GetDecisionPolicy() if err != nil { return nil, errorsmod.Wrap(err, "request decision policy") } - groupID := req.GetGroupID() - metadata := req.GetMetadata() - if err := k.assertMetadataLength(metadata, "group policy metadata"); err != nil { - return nil, err + if err := policy.ValidateBasic(); err != nil { + return nil, errorsmod.Wrap(err, "decision policy") } - g, err := k.getGroupInfo(ctx, groupID) + reqGroupAdmin, err := k.accKeeper.StringToBytes(msg.GetAdmin()) + if err != nil { + return nil, errorsmod.Wrap(err, "request admin") + } + + ctx := sdk.UnwrapSDKContext(goCtx) + groupInfo, err := k.getGroupInfo(ctx, msg.GetGroupID()) if err != nil { return nil, err } - groupAdmin, err := sdk.AccAddressFromBech32(g.Admin) + + groupAdmin, err := k.accKeeper.StringToBytes(groupInfo.Admin) if err != nil { return nil, errorsmod.Wrap(err, "group admin") } + // Only current group admin is authorized to create a group policy for this - if !groupAdmin.Equals(admin) { + if !bytes.Equal(groupAdmin, reqGroupAdmin) { return nil, errorsmod.Wrap(sdkerrors.ErrUnauthorized, "not group admin") } - err = policy.Validate(g, k.config) - if err != nil { + if err := policy.Validate(groupInfo, k.config); err != nil { return nil, err } @@ -363,9 +400,9 @@ func (k Keeper) CreateGroupPolicy(goCtx context.Context, req *group.MsgCreateGro groupPolicy, err := group.NewGroupPolicyInfo( accountAddr, - groupID, - admin, - metadata, + msg.GetGroupID(), + reqGroupAdmin, + msg.GetMetadata(), 1, policy, ctx.BlockTime(), @@ -378,44 +415,50 @@ func (k Keeper) CreateGroupPolicy(goCtx context.Context, req *group.MsgCreateGro return nil, errorsmod.Wrap(err, "could not create group policy") } - err = ctx.EventManager().EmitTypedEvent(&group.EventCreateGroupPolicy{Address: accountAddr.String()}) - if err != nil { + if err := ctx.EventManager().EmitTypedEvent(&group.EventCreateGroupPolicy{Address: accountAddr.String()}); err != nil { return nil, err } return &group.MsgCreateGroupPolicyResponse{Address: accountAddr.String()}, nil } -func (k Keeper) UpdateGroupPolicyAdmin(goCtx context.Context, req *group.MsgUpdateGroupPolicyAdmin) (*group.MsgUpdateGroupPolicyAdminResponse, error) { +func (k Keeper) UpdateGroupPolicyAdmin(goCtx context.Context, msg *group.MsgUpdateGroupPolicyAdmin) (*group.MsgUpdateGroupPolicyAdminResponse, error) { + if strings.EqualFold(msg.Admin, msg.NewAdmin) { + return nil, errorsmod.Wrap(errors.ErrInvalid, "new and old admin are same") + } + ctx := sdk.UnwrapSDKContext(goCtx) action := func(groupPolicy *group.GroupPolicyInfo) error { - groupPolicy.Admin = req.NewAdmin + groupPolicy.Admin = msg.NewAdmin groupPolicy.Version++ return k.groupPolicyTable.Update(ctx.KVStore(k.key), groupPolicy) } - err := k.doUpdateGroupPolicy(ctx, req.GroupPolicyAddress, req.Admin, action, "group policy admin updated") - if err != nil { + if err := k.doUpdateGroupPolicy(ctx, msg.GroupPolicyAddress, msg.Admin, action, "group policy admin updated"); err != nil { return nil, err } return &group.MsgUpdateGroupPolicyAdminResponse{}, nil } -func (k Keeper) UpdateGroupPolicyDecisionPolicy(goCtx context.Context, req *group.MsgUpdateGroupPolicyDecisionPolicy) (*group.MsgUpdateGroupPolicyDecisionPolicyResponse, error) { - ctx := sdk.UnwrapSDKContext(goCtx) - policy, err := req.GetDecisionPolicy() +func (k Keeper) UpdateGroupPolicyDecisionPolicy(goCtx context.Context, msg *group.MsgUpdateGroupPolicyDecisionPolicy) (*group.MsgUpdateGroupPolicyDecisionPolicyResponse, error) { + policy, err := msg.GetDecisionPolicy() if err != nil { - return nil, err + return nil, errorsmod.Wrap(err, "decision policy") } + if err := policy.ValidateBasic(); err != nil { + return nil, errorsmod.Wrap(err, "decision policy") + } + + ctx := sdk.UnwrapSDKContext(goCtx) action := func(groupPolicy *group.GroupPolicyInfo) error { - g, err := k.getGroupInfo(ctx, groupPolicy.GroupId) + groupInfo, err := k.getGroupInfo(ctx, groupPolicy.GroupId) if err != nil { return err } - err = policy.Validate(g, k.config) + err = policy.Validate(groupInfo, k.config) if err != nil { return err } @@ -429,17 +472,16 @@ func (k Keeper) UpdateGroupPolicyDecisionPolicy(goCtx context.Context, req *grou return k.groupPolicyTable.Update(ctx.KVStore(k.key), groupPolicy) } - err = k.doUpdateGroupPolicy(ctx, req.GroupPolicyAddress, req.Admin, action, "group policy's decision policy updated") - if err != nil { + if err = k.doUpdateGroupPolicy(ctx, msg.GroupPolicyAddress, msg.Admin, action, "group policy's decision policy updated"); err != nil { return nil, err } return &group.MsgUpdateGroupPolicyDecisionPolicyResponse{}, nil } -func (k Keeper) UpdateGroupPolicyMetadata(goCtx context.Context, req *group.MsgUpdateGroupPolicyMetadata) (*group.MsgUpdateGroupPolicyMetadataResponse, error) { +func (k Keeper) UpdateGroupPolicyMetadata(goCtx context.Context, msg *group.MsgUpdateGroupPolicyMetadata) (*group.MsgUpdateGroupPolicyMetadataResponse, error) { ctx := sdk.UnwrapSDKContext(goCtx) - metadata := req.GetMetadata() + metadata := msg.GetMetadata() action := func(groupPolicy *group.GroupPolicyInfo) error { groupPolicy.Metadata = metadata @@ -451,7 +493,7 @@ func (k Keeper) UpdateGroupPolicyMetadata(goCtx context.Context, req *group.MsgU return nil, err } - err := k.doUpdateGroupPolicy(ctx, req.GroupPolicyAddress, req.Admin, action, "group policy metadata updated") + err := k.doUpdateGroupPolicy(ctx, msg.GroupPolicyAddress, msg.Admin, action, "group policy metadata updated") if err != nil { return nil, err } @@ -459,45 +501,56 @@ func (k Keeper) UpdateGroupPolicyMetadata(goCtx context.Context, req *group.MsgU return &group.MsgUpdateGroupPolicyMetadataResponse{}, nil } -func (k Keeper) SubmitProposal(goCtx context.Context, req *group.MsgSubmitProposal) (*group.MsgSubmitProposalResponse, error) { - ctx := sdk.UnwrapSDKContext(goCtx) - groupPolicyAddr, err := sdk.AccAddressFromBech32(req.GroupPolicyAddress) +func (k Keeper) SubmitProposal(goCtx context.Context, msg *group.MsgSubmitProposal) (*group.MsgSubmitProposalResponse, error) { + if len(msg.Proposers) == 0 { + return nil, errorsmod.Wrap(errors.ErrEmpty, "proposers") + } + + if err := k.validateProposers(msg.Proposers); err != nil { + return nil, err + } + + groupPolicyAddr, err := k.accKeeper.StringToBytes(msg.GroupPolicyAddress) if err != nil { return nil, errorsmod.Wrap(err, "request account address of group policy") } - metadata := req.Metadata - proposers := req.Proposers - msgs, err := req.GetMsgs() - if err != nil { - return nil, errorsmod.Wrap(err, "request msgs") + + if err := k.assertMetadataLength(msg.Title, "proposal Title"); err != nil { + return nil, err } - if err := k.assertMetadataLength(metadata, "metadata"); err != nil { + if err := k.assertMetadataLength(msg.Summary, "proposal summary"); err != nil { return nil, err } - if err := k.assertMetadataLength(req.Summary, "proposal summary"); err != nil { + if err := k.assertMetadataLength(msg.Metadata, "metadata"); err != nil { return nil, err } - if err := k.assertMetadataLength(req.Title, "proposal Title"); err != nil { + msgs, err := msg.GetMsgs() + if err != nil { + return nil, errorsmod.Wrap(err, "request msgs") + } + + if err := validateMsgs(msgs); err != nil { return nil, err } - policyAcc, err := k.getGroupPolicyInfo(ctx, req.GroupPolicyAddress) + ctx := sdk.UnwrapSDKContext(goCtx) + policyAcc, err := k.getGroupPolicyInfo(ctx, msg.GroupPolicyAddress) if err != nil { - return nil, errorsmod.Wrap(err, "load group policy") + return nil, errorsmod.Wrapf(err, "load group policy: %s", msg.GroupPolicyAddress) } - g, err := k.getGroupInfo(ctx, policyAcc.GroupId) + groupInfo, err := k.getGroupInfo(ctx, policyAcc.GroupId) if err != nil { return nil, errorsmod.Wrap(err, "get group by groupId of group policy") } // Only members of the group can submit a new proposal. - for i := range proposers { - if !k.groupMemberTable.Has(ctx.KVStore(k.key), orm.PrimaryKey(&group.GroupMember{GroupId: g.Id, Member: &group.Member{Address: proposers[i]}})) { - return nil, errorsmod.Wrapf(errors.ErrUnauthorized, "not in group: %s", proposers[i]) + for _, proposer := range msg.Proposers { + if !k.groupMemberTable.Has(ctx.KVStore(k.key), orm.PrimaryKey(&group.GroupMember{GroupId: groupInfo.Id, Member: &group.Member{Address: proposer}})) { + return nil, errorsmod.Wrapf(errors.ErrUnauthorized, "not in group: %s", proposer) } } @@ -511,26 +564,25 @@ func (k Keeper) SubmitProposal(goCtx context.Context, req *group.MsgSubmitPropos return nil, errorsmod.Wrap(err, "proposal group policy decision policy") } - // Prevent proposal that can not succeed. - err = policy.Validate(g, k.config) - if err != nil { + // Prevent proposal that cannot succeed. + if err = policy.Validate(groupInfo, k.config); err != nil { return nil, err } m := &group.Proposal{ Id: k.proposalTable.Sequence().PeekNextVal(ctx.KVStore(k.key)), - GroupPolicyAddress: req.GroupPolicyAddress, - Metadata: metadata, - Proposers: proposers, + GroupPolicyAddress: msg.GroupPolicyAddress, + Metadata: msg.Metadata, + Proposers: msg.Proposers, SubmitTime: ctx.BlockTime(), - GroupVersion: g.Version, + GroupVersion: groupInfo.Version, GroupPolicyVersion: policyAcc.Version, Status: group.PROPOSAL_STATUS_SUBMITTED, ExecutorResult: group.PROPOSAL_EXECUTOR_RESULT_NOT_RUN, VotingPeriodEnd: ctx.BlockTime().Add(policy.GetVotingPeriod()), // The voting window begins as soon as the proposal is submitted. FinalTallyResult: group.DefaultTallyResult(), - Title: req.Title, - Summary: req.Summary, + Title: msg.Title, + Summary: msg.Summary, } if err := m.SetMsgs(msgs); err != nil { @@ -542,23 +594,22 @@ func (k Keeper) SubmitProposal(goCtx context.Context, req *group.MsgSubmitPropos return nil, errorsmod.Wrap(err, "create proposal") } - err = ctx.EventManager().EmitTypedEvent(&group.EventSubmitProposal{ProposalId: id}) - if err != nil { + if err := ctx.EventManager().EmitTypedEvent(&group.EventSubmitProposal{ProposalId: id}); err != nil { return nil, err } // Try to execute proposal immediately - if req.Exec == group.Exec_EXEC_TRY { + if msg.Exec == group.Exec_EXEC_TRY { // Consider proposers as Yes votes - for i := range proposers { + for _, proposer := range msg.Proposers { ctx.GasMeter().ConsumeGas(gasCostPerIteration, "vote on proposal") _, err = k.Vote(ctx, &group.MsgVote{ ProposalId: id, - Voter: proposers[i], + Voter: proposer, Option: group.VOTE_OPTION_YES, }) if err != nil { - return &group.MsgSubmitProposalResponse{ProposalId: id}, errorsmod.Wrapf(err, "the proposal was created but failed on vote for voter %s", proposers[i]) + return &group.MsgSubmitProposalResponse{ProposalId: id}, errorsmod.Wrapf(err, "the proposal was created but failed on vote for voter %s", proposer) } } @@ -567,7 +618,7 @@ func (k Keeper) SubmitProposal(goCtx context.Context, req *group.MsgSubmitPropos ProposalId: id, // We consider the first proposer as the MsgExecRequest signer // but that could be revisited (eg using the group policy) - Executor: proposers[0], + Executor: msg.Proposers[0], }) if err != nil { return &group.MsgSubmitProposalResponse{ProposalId: id}, errorsmod.Wrap(err, "the proposal was created but failed on exec") @@ -577,12 +628,17 @@ func (k Keeper) SubmitProposal(goCtx context.Context, req *group.MsgSubmitPropos return &group.MsgSubmitProposalResponse{ProposalId: id}, nil } -func (k Keeper) WithdrawProposal(goCtx context.Context, req *group.MsgWithdrawProposal) (*group.MsgWithdrawProposalResponse, error) { - ctx := sdk.UnwrapSDKContext(goCtx) - id := req.ProposalId - address := req.Address +func (k Keeper) WithdrawProposal(goCtx context.Context, msg *group.MsgWithdrawProposal) (*group.MsgWithdrawProposalResponse, error) { + if msg.ProposalId == 0 { + return nil, errorsmod.Wrap(errors.ErrEmpty, "proposal id") + } + + if _, err := k.accKeeper.StringToBytes(msg.Address); err != nil { + return nil, errorsmod.Wrapf(sdkerrors.ErrInvalidAddress, "invalid group policy admin / proposer address: %s", msg.Address) + } - proposal, err := k.getProposal(ctx, id) + ctx := sdk.UnwrapSDKContext(goCtx) + proposal, err := k.getProposal(ctx, msg.ProposalId) if err != nil { return nil, err } @@ -598,41 +654,55 @@ func (k Keeper) WithdrawProposal(goCtx context.Context, req *group.MsgWithdrawPr } // check address is the group policy admin he is in proposers list.. - if address != policyInfo.Admin && !isProposer(proposal, address) { - return nil, errorsmod.Wrapf(errors.ErrUnauthorized, "given address is neither group policy admin nor in proposers: %s", address) + if msg.Address != policyInfo.Admin && !isProposer(proposal, msg.Address) { + return nil, errorsmod.Wrapf(errors.ErrUnauthorized, "given address is neither group policy admin nor in proposers: %s", msg.Address) } proposal.Status = group.PROPOSAL_STATUS_WITHDRAWN - if err := k.proposalTable.Update(ctx.KVStore(k.key), id, &proposal); err != nil { + if err := k.proposalTable.Update(ctx.KVStore(k.key), msg.ProposalId, &proposal); err != nil { return nil, err } - err = ctx.EventManager().EmitTypedEvent(&group.EventWithdrawProposal{ProposalId: id}) - if err != nil { + if err := ctx.EventManager().EmitTypedEvent(&group.EventWithdrawProposal{ProposalId: msg.ProposalId}); err != nil { return nil, err } return &group.MsgWithdrawProposalResponse{}, nil } -func (k Keeper) Vote(goCtx context.Context, req *group.MsgVote) (*group.MsgVoteResponse, error) { - ctx := sdk.UnwrapSDKContext(goCtx) - id := req.ProposalId - voteOption := req.Option - metadata := req.Metadata +func (k Keeper) Vote(goCtx context.Context, msg *group.MsgVote) (*group.MsgVoteResponse, error) { + if msg.ProposalId == 0 { + return nil, errorsmod.Wrap(errors.ErrEmpty, "proposal id") + } + + // verify vote options + if msg.Option == group.VOTE_OPTION_UNSPECIFIED { + return nil, errorsmod.Wrap(errors.ErrEmpty, "vote option") + } - if err := k.assertMetadataLength(metadata, "metadata"); err != nil { + if _, ok := group.VoteOption_name[int32(msg.Option)]; !ok { + return nil, errorsmod.Wrap(errors.ErrInvalid, "vote option") + } + + if err := k.assertMetadataLength(msg.Metadata, "metadata"); err != nil { return nil, err } - proposal, err := k.getProposal(ctx, id) + if _, err := k.accKeeper.StringToBytes(msg.Voter); err != nil { + return nil, errorsmod.Wrapf(sdkerrors.ErrInvalidAddress, "invalid voter address: %s", msg.Voter) + } + + ctx := sdk.UnwrapSDKContext(goCtx) + proposal, err := k.getProposal(ctx, msg.ProposalId) if err != nil { return nil, err } + // Ensure that we can still accept votes for this proposal. if proposal.Status != group.PROPOSAL_STATUS_SUBMITTED { return nil, errorsmod.Wrap(errors.ErrInvalid, "proposal not open for voting") } + if ctx.BlockTime().After(proposal.VotingPeriodEnd) { return nil, errorsmod.Wrap(errors.ErrExpired, "voting period has ended already") } @@ -642,22 +712,21 @@ func (k Keeper) Vote(goCtx context.Context, req *group.MsgVote) (*group.MsgVoteR return nil, errorsmod.Wrap(err, "load group policy") } - electorate, err := k.getGroupInfo(ctx, policyInfo.GroupId) + groupInfo, err := k.getGroupInfo(ctx, policyInfo.GroupId) if err != nil { return nil, err } // Count and store votes. - voterAddr := req.Voter - voter := group.GroupMember{GroupId: electorate.Id, Member: &group.Member{Address: voterAddr}} + voter := group.GroupMember{GroupId: groupInfo.Id, Member: &group.Member{Address: msg.Voter}} if err := k.groupMemberTable.GetOne(ctx.KVStore(k.key), orm.PrimaryKey(&voter), &voter); err != nil { - return nil, errorsmod.Wrapf(err, "voter address: %s", voterAddr) + return nil, errorsmod.Wrapf(err, "voter address: %s", msg.Voter) } newVote := group.Vote{ - ProposalId: id, - Voter: voterAddr, - Option: voteOption, - Metadata: metadata, + ProposalId: msg.ProposalId, + Voter: msg.Voter, + Option: msg.Option, + Metadata: msg.Metadata, SubmitTime: ctx.BlockTime(), } @@ -667,17 +736,13 @@ func (k Keeper) Vote(goCtx context.Context, req *group.MsgVote) (*group.MsgVoteR return nil, errorsmod.Wrap(err, "store vote") } - err = ctx.EventManager().EmitTypedEvent(&group.EventVote{ProposalId: id}) - if err != nil { + if err := ctx.EventManager().EmitTypedEvent(&group.EventVote{ProposalId: msg.ProposalId}); err != nil { return nil, err } // Try to execute proposal immediately - if req.Exec == group.Exec_EXEC_TRY { - _, err = k.Exec(ctx, &group.MsgExec{ - ProposalId: id, - Executor: voterAddr, - }) + if msg.Exec == group.Exec_EXEC_TRY { + _, err = k.Exec(ctx, &group.MsgExec{ProposalId: msg.ProposalId, Executor: msg.Voter}) if err != nil { return nil, err } @@ -689,7 +754,7 @@ func (k Keeper) Vote(goCtx context.Context, req *group.MsgVote) (*group.MsgVoteR // doTallyAndUpdate performs a tally, and, if the tally result is final, then: // - updates the proposal's `Status` and `FinalTallyResult` fields, // - prune all the votes. -func (k Keeper) doTallyAndUpdate(ctx sdk.Context, p *group.Proposal, electorate group.GroupInfo, policyInfo group.GroupPolicyInfo) error { +func (k Keeper) doTallyAndUpdate(ctx sdk.Context, p *group.Proposal, groupInfo group.GroupInfo, policyInfo group.GroupPolicyInfo) error { policy, err := policyInfo.GetDecisionPolicy() if err != nil { return err @@ -700,7 +765,7 @@ func (k Keeper) doTallyAndUpdate(ctx sdk.Context, p *group.Proposal, electorate return err } - result, err := policy.Allow(tallyResult, electorate.TotalWeight) + result, err := policy.Allow(tallyResult, groupInfo.TotalWeight) if err != nil { return errorsmod.Wrap(err, "policy allow") } @@ -723,11 +788,13 @@ func (k Keeper) doTallyAndUpdate(ctx sdk.Context, p *group.Proposal, electorate } // Exec executes the messages from a proposal. -func (k Keeper) Exec(goCtx context.Context, req *group.MsgExec) (*group.MsgExecResponse, error) { - ctx := sdk.UnwrapSDKContext(goCtx) - id := req.ProposalId +func (k Keeper) Exec(goCtx context.Context, msg *group.MsgExec) (*group.MsgExecResponse, error) { + if msg.ProposalId == 0 { + return nil, errorsmod.Wrap(errors.ErrEmpty, "proposal id") + } - proposal, err := k.getProposal(ctx, id) + ctx := sdk.UnwrapSDKContext(goCtx) + proposal, err := k.getProposal(ctx, msg.ProposalId) if err != nil { return nil, err } @@ -745,12 +812,12 @@ func (k Keeper) Exec(goCtx context.Context, req *group.MsgExec) (*group.MsgExecR // didn't end yet, and tallying hasn't been done. In this case, we need to // tally first. if proposal.Status == group.PROPOSAL_STATUS_SUBMITTED { - electorate, err := k.getGroupInfo(ctx, policyInfo.GroupId) + groupInfo, err := k.getGroupInfo(ctx, policyInfo.GroupId) if err != nil { return nil, errorsmod.Wrap(err, "load group") } - if err := k.doTallyAndUpdate(ctx, &proposal, electorate, policyInfo); err != nil { + if err := k.doTallyAndUpdate(ctx, &proposal, groupInfo, policyInfo); err != nil { return nil, err } } @@ -761,7 +828,7 @@ func (k Keeper) Exec(goCtx context.Context, req *group.MsgExec) (*group.MsgExecR // Caching context so that we don't update the store in case of failure. cacheCtx, flush := ctx.CacheContext() - addr, err := sdk.AccAddressFromBech32(policyInfo.Address) + addr, err := k.accKeeper.StringToBytes(policyInfo.Address) if err != nil { return nil, err } @@ -769,8 +836,8 @@ func (k Keeper) Exec(goCtx context.Context, req *group.MsgExec) (*group.MsgExecR decisionPolicy := policyInfo.DecisionPolicy.GetCachedValue().(group.DecisionPolicy) if results, err := k.doExecuteMsgs(cacheCtx, k.router, proposal, addr, decisionPolicy); err != nil { proposal.ExecutorResult = group.PROPOSAL_EXECUTOR_RESULT_FAILURE - logs = fmt.Sprintf("proposal execution failed on proposal %d, because of error %s", id, err.Error()) - k.Logger(ctx).Info("proposal execution failed", "cause", err, "proposalID", id) + logs = fmt.Sprintf("proposal execution failed on proposal %d, because of error %s", proposal.Id, err.Error()) + k.Logger(ctx).Info("proposal execution failed", "cause", err, "proposalID", proposal.Id) } else { proposal.ExecutorResult = group.PROPOSAL_EXECUTOR_RESULT_SUCCESS flush() @@ -790,17 +857,16 @@ func (k Keeper) Exec(goCtx context.Context, req *group.MsgExec) (*group.MsgExecR } } else { store := ctx.KVStore(k.key) - if err := k.proposalTable.Update(store, id, &proposal); err != nil { + if err := k.proposalTable.Update(store, proposal.Id, &proposal); err != nil { return nil, err } } - err = ctx.EventManager().EmitTypedEvent(&group.EventExec{ - ProposalId: id, + if err := ctx.EventManager().EmitTypedEvent(&group.EventExec{ + ProposalId: proposal.Id, Logs: logs, Result: proposal.ExecutorResult, - }) - if err != nil { + }); err != nil { return nil, err } @@ -810,14 +876,18 @@ func (k Keeper) Exec(goCtx context.Context, req *group.MsgExec) (*group.MsgExecR } // LeaveGroup implements the MsgServer/LeaveGroup method. -func (k Keeper) LeaveGroup(goCtx context.Context, req *group.MsgLeaveGroup) (*group.MsgLeaveGroupResponse, error) { - ctx := sdk.UnwrapSDKContext(goCtx) - _, err := sdk.AccAddressFromBech32(req.Address) +func (k Keeper) LeaveGroup(goCtx context.Context, msg *group.MsgLeaveGroup) (*group.MsgLeaveGroupResponse, error) { + if msg.GroupId == 0 { + return nil, errorsmod.Wrap(errors.ErrEmpty, "group-id") + } + + _, err := k.accKeeper.StringToBytes(msg.Address) if err != nil { - return nil, err + return nil, errorsmod.Wrap(err, "group member") } - groupInfo, err := k.getGroupInfo(ctx, req.GroupId) + ctx := sdk.UnwrapSDKContext(goCtx) + groupInfo, err := k.getGroupInfo(ctx, msg.GroupId) if err != nil { return nil, errorsmod.Wrap(err, "group") } @@ -828,8 +898,8 @@ func (k Keeper) LeaveGroup(goCtx context.Context, req *group.MsgLeaveGroup) (*gr } gm, err := k.getGroupMember(ctx, &group.GroupMember{ - GroupId: req.GroupId, - Member: &group.Member{Address: req.Address}, + GroupId: msg.GroupId, + Member: &group.Member{Address: msg.Address}, }) if err != nil { return nil, err @@ -862,10 +932,12 @@ func (k Keeper) LeaveGroup(goCtx context.Context, req *group.MsgLeaveGroup) (*gr return nil, err } - ctx.EventManager().EmitTypedEvent(&group.EventLeaveGroup{ - GroupId: req.GroupId, - Address: req.Address, - }) + if err := ctx.EventManager().EmitTypedEvent(&group.EventLeaveGroup{ + GroupId: msg.GroupId, + Address: msg.Address, + }); err != nil { + return nil, err + } return &group.MsgLeaveGroupResponse{}, nil } @@ -885,11 +957,6 @@ func (k Keeper) getGroupMember(ctx sdk.Context, member *group.GroupMember) (*gro return &groupMember, nil } -type authNGroupReq interface { - GetGroupID() uint64 - GetAdmin() string -} - type ( actionFn func(m *group.GroupInfo) error groupPolicyActionFn func(m *group.GroupPolicyInfo) error @@ -897,24 +964,24 @@ type ( // doUpdateGroupPolicy first makes sure that the group policy admin initiated the group policy update, // before performing the group policy update and emitting an event. -func (k Keeper) doUpdateGroupPolicy(ctx sdk.Context, groupPolicy string, admin string, action groupPolicyActionFn, note string) error { - groupPolicyInfo, err := k.getGroupPolicyInfo(ctx, groupPolicy) +func (k Keeper) doUpdateGroupPolicy(ctx sdk.Context, reqGroupPolicy, reqAdmin string, action groupPolicyActionFn, note string) error { + groupPolicyAddr, err := k.accKeeper.StringToBytes(reqGroupPolicy) if err != nil { - return errorsmod.Wrap(err, "load group policy") + return errorsmod.Wrap(err, "group policy address") } - groupPolicyAddr, err := sdk.AccAddressFromBech32(groupPolicy) + _, err = k.accKeeper.StringToBytes(reqAdmin) if err != nil { - return errorsmod.Wrap(err, "group policy address") + return errorsmod.Wrap(err, "group policy admin") } - groupPolicyAdmin, err := sdk.AccAddressFromBech32(admin) + groupPolicyInfo, err := k.getGroupPolicyInfo(ctx, reqGroupPolicy) if err != nil { - return errorsmod.Wrap(err, "group policy admin") + return errorsmod.Wrap(err, "load group policy") } // Only current group policy admin is authorized to update a group policy. - if groupPolicyAdmin.String() != groupPolicyInfo.Admin { + if reqAdmin != groupPolicyInfo.Admin { return errorsmod.Wrap(sdkerrors.ErrUnauthorized, "not group policy admin") } @@ -935,47 +1002,30 @@ func (k Keeper) doUpdateGroupPolicy(ctx sdk.Context, groupPolicy string, admin s // doUpdateGroup first makes sure that the group admin initiated the group update, // before performing the group update and emitting an event. -func (k Keeper) doUpdateGroup(ctx sdk.Context, req authNGroupReq, action actionFn, note string) error { - err := k.doAuthenticated(ctx, req, action, note) +func (k Keeper) doUpdateGroup(ctx sdk.Context, groupID uint64, reqGroupAdmin string, action actionFn, errNote string) error { + groupInfo, err := k.getGroupInfo(ctx, groupID) if err != nil { return err } - err = ctx.EventManager().EmitTypedEvent(&group.EventUpdateGroup{GroupId: req.GetGroupID()}) - if err != nil { - return err + if !strings.EqualFold(groupInfo.Admin, reqGroupAdmin) { + return errorsmod.Wrapf(sdkerrors.ErrUnauthorized, "not group admin; got %s, expected %s", reqGroupAdmin, groupInfo.Admin) } - return nil -} + if err := action(&groupInfo); err != nil { + return errorsmod.Wrap(err, errNote) + } -// doAuthenticated makes sure that the group admin initiated the request, -// and perform the provided action on the group. -func (k Keeper) doAuthenticated(ctx sdk.Context, req authNGroupReq, action actionFn, errNote string) error { - group, err := k.getGroupInfo(ctx, req.GetGroupID()) - if err != nil { + if err := ctx.EventManager().EmitTypedEvent(&group.EventUpdateGroup{GroupId: groupID}); err != nil { return err } - admin, err := sdk.AccAddressFromBech32(group.Admin) - if err != nil { - return errorsmod.Wrap(err, "group admin") - } - reqAdmin, err := sdk.AccAddressFromBech32(req.GetAdmin()) - if err != nil { - return errorsmod.Wrap(err, "request admin") - } - if !admin.Equals(reqAdmin) { - return errorsmod.Wrapf(sdkerrors.ErrUnauthorized, "not group admin; got %s, expected %s", req.GetAdmin(), group.Admin) - } - if err := action(&group); err != nil { - return errorsmod.Wrap(err, errNote) - } + return nil } // assertMetadataLength returns an error if given metadata length // is greater than a pre-defined maxMetadataLen. -func (k Keeper) assertMetadataLength(metadata string, description string) error { +func (k Keeper) assertMetadataLength(metadata, description string) error { if metadata != "" && uint64(len(metadata)) > k.config.MaxMetadataLen { return errorsmod.Wrapf(errors.ErrMaxLimit, description) } @@ -1010,6 +1060,55 @@ func (k Keeper) validateDecisionPolicies(ctx sdk.Context, g group.GroupInfo) err return nil } +// validateProposers checks that all proposers addresses are valid. +// It as well verifies that there is no duplicate address. +func (k Keeper) validateProposers(proposers []string) error { + index := make(map[string]struct{}, len(proposers)) + for _, proposer := range proposers { + if _, exists := index[proposer]; exists { + return errorsmod.Wrapf(errors.ErrDuplicate, "address: %s", proposer) + } + + _, err := k.accKeeper.StringToBytes(proposer) + if err != nil { + return errorsmod.Wrapf(err, "proposer address %s", proposer) + } + + index[proposer] = struct{}{} + } + + return nil +} + +// validateMembers checks that all members addresses are valid. +// additionally it verifies that there is no duplicate address +// and the member weight is non-negative. +// Note: in state, a member's weight MUST be positive. However, in some Msgs, +// it's possible to set a zero member weight, for example in +// MsgUpdateGroupMembers to denote that we're removing a member. +// It returns an error if any of the above conditions is not met. +func (k Keeper) validateMembers(members []group.MemberRequest) error { + index := make(map[string]struct{}, len(members)) + for _, member := range members { + if _, exists := index[member.Address]; exists { + return errorsmod.Wrapf(errors.ErrDuplicate, "address: %s", member.Address) + } + + _, err := k.accKeeper.StringToBytes(member.Address) + if err != nil { + return errorsmod.Wrapf(err, "member address %s", member.Address) + } + + if _, err := math.NewNonNegativeDecFromString(member.Weight); err != nil { + return errorsmod.Wrap(err, "weight must be non negative") + } + + index[member.Address] = struct{}{} + } + + return nil +} + // isProposer checks that an address is a proposer of a given proposal. func isProposer(proposal group.Proposal, address string) bool { for _, proposer := range proposal.Proposers { @@ -1020,3 +1119,18 @@ func isProposer(proposal group.Proposal, address string) bool { return false } + +func validateMsgs(msgs []sdk.Msg) error { + for i, msg := range msgs { + m, ok := msg.(sdk.HasValidateBasic) + if !ok { + continue + } + + if err := m.ValidateBasic(); err != nil { + return errorsmod.Wrapf(err, "msg %d", i) + } + } + + return nil +} diff --git a/x/group/keeper/msg_server_test.go b/x/group/keeper/msg_server_test.go new file mode 100644 index 000000000000..4f80159f982d --- /dev/null +++ b/x/group/keeper/msg_server_test.go @@ -0,0 +1,3078 @@ +package keeper_test + +import ( + "bytes" + "context" + "fmt" + "sort" + "strings" + "time" + + "github.com/cosmos/cosmos-sdk/codec/address" + simtestutil "github.com/cosmos/cosmos-sdk/testutil/sims" + "github.com/cosmos/cosmos-sdk/testutil/testdata" + sdk "github.com/cosmos/cosmos-sdk/types" + banktypes "github.com/cosmos/cosmos-sdk/x/bank/types" + "github.com/cosmos/cosmos-sdk/x/group" + "github.com/cosmos/cosmos-sdk/x/group/internal/math" + minttypes "github.com/cosmos/cosmos-sdk/x/mint/types" + "github.com/golang/mock/gomock" +) + +func (s *TestSuite) TestCreateGroupWithLotsOfMembers() { + for i := 50; i < 70; i++ { + membersResp := s.createGroupAndGetMembers(i) + s.Require().Equal(len(membersResp), i) + } +} + +func (s *TestSuite) createGroupAndGetMembers(numMembers int) []*group.GroupMember { + addressPool := simtestutil.CreateIncrementalAccounts(numMembers) + members := make([]group.MemberRequest, numMembers) + for i := 0; i < len(members); i++ { + members[i] = group.MemberRequest{ + Address: addressPool[i].String(), + Weight: "1", + } + s.accountKeeper.EXPECT().StringToBytes(addressPool[i].String()).Return(addressPool[i].Bytes(), nil).AnyTimes() + s.accountKeeper.EXPECT().BytesToString(addressPool[i].Bytes()).Return(addressPool[i].String(), nil).AnyTimes() + } + + g, err := s.groupKeeper.CreateGroup(s.ctx, &group.MsgCreateGroup{ + Admin: members[0].Address, + Members: members, + }) + s.Require().NoErrorf(err, "failed to create group with %d members", len(members)) + s.T().Logf("group %d created with %d members", g.GroupId, len(members)) + + groupMemberResp, err := s.groupKeeper.GroupMembers(s.ctx, &group.QueryGroupMembersRequest{GroupId: g.GroupId}) + s.Require().NoError(err) + + s.T().Logf("got %d members from group %d", len(groupMemberResp.Members), g.GroupId) + + return groupMemberResp.Members +} + +func (s *TestSuite) TestCreateGroup() { + addrs := s.addrs + addr1 := addrs[0] + addr3 := addrs[2] + addr5 := addrs[4] + addr6 := addrs[5] + + members := []group.MemberRequest{{ + Address: addr5.String(), + Weight: "1", + }, { + Address: addr6.String(), + Weight: "2", + }} + + expGroups := []*group.GroupInfo{ + { + Id: s.groupID, + Version: 1, + Admin: addr1.String(), + TotalWeight: "3", + CreatedAt: s.blockTime, + }, + { + Id: 2, + Version: 1, + Admin: addr1.String(), + TotalWeight: "3", + CreatedAt: s.blockTime, + }, + } + + specs := map[string]struct { + req *group.MsgCreateGroup + expErr bool + expErrMsg string + expGroups []*group.GroupInfo + }{ + "all good": { + req: &group.MsgCreateGroup{ + Admin: addr1.String(), + Members: members, + }, + expGroups: expGroups, + }, + "group metadata too long": { + req: &group.MsgCreateGroup{ + Admin: addr1.String(), + Members: members, + Metadata: strings.Repeat("a", 256), + }, + expErr: true, + expErrMsg: "group metadata: limit exceeded", + }, + "invalid member address": { + req: &group.MsgCreateGroup{ + Admin: addr1.String(), + Members: []group.MemberRequest{{ + Address: "invalid", + Weight: "1", + }}, + }, + expErr: true, + expErrMsg: "member address invalid", + }, + "member metadata too long": { + req: &group.MsgCreateGroup{ + Admin: addr1.String(), + Members: []group.MemberRequest{{ + Address: addr3.String(), + Weight: "1", + Metadata: strings.Repeat("a", 256), + }}, + }, + expErr: true, + expErrMsg: "metadata: limit exceeded", + }, + "zero member weight": { + req: &group.MsgCreateGroup{ + Admin: addr1.String(), + Members: []group.MemberRequest{{ + Address: addr3.String(), + Weight: "0", + }}, + }, + expErr: true, + expErrMsg: "expected a positive decimal", + }, + "invalid member weight - Inf": { + req: &group.MsgCreateGroup{ + Admin: addr1.String(), + Members: []group.MemberRequest{{ + Address: addr3.String(), + Weight: "inf", + }}, + }, + expErr: true, + expErrMsg: "expected a finite decimal", + }, + "invalid member weight - NaN": { + req: &group.MsgCreateGroup{ + Admin: addr1.String(), + Members: []group.MemberRequest{{ + Address: addr3.String(), + Weight: "NaN", + }}, + }, + expErr: true, + expErrMsg: "expected a finite decimal", + }, + } + + var seq uint32 = 1 + for msg, spec := range specs { + spec := spec + s.Run(msg, func() { + blockTime := sdk.UnwrapSDKContext(s.ctx).BlockTime() + res, err := s.groupKeeper.CreateGroup(s.ctx, spec.req) + if spec.expErr { + s.Require().Error(err) + s.Require().Contains(err.Error(), spec.expErrMsg) + _, err := s.groupKeeper.GroupInfo(s.ctx, &group.QueryGroupInfoRequest{GroupId: uint64(seq + 1)}) + s.Require().Error(err) + return + } + + s.Require().NoError(err) + id := res.GroupId + + seq++ + s.Assert().Equal(uint64(seq), id) + + // then all data persisted + loadedGroupRes, err := s.groupKeeper.GroupInfo(s.ctx, &group.QueryGroupInfoRequest{GroupId: id}) + s.Require().NoError(err) + s.Assert().Equal(spec.req.Admin, loadedGroupRes.Info.Admin) + s.Assert().Equal(spec.req.Metadata, loadedGroupRes.Info.Metadata) + s.Assert().Equal(id, loadedGroupRes.Info.Id) + s.Assert().Equal(uint64(1), loadedGroupRes.Info.Version) + + // and members are stored as well + membersRes, err := s.groupKeeper.GroupMembers(s.ctx, &group.QueryGroupMembersRequest{GroupId: id}) + s.Require().NoError(err) + loadedMembers := membersRes.Members + s.Require().Equal(len(members), len(loadedMembers)) + // we reorder members by address to be able to compare them + sort.Slice(members, func(i, j int) bool { + addri, err := sdk.AccAddressFromBech32(members[i].Address) + s.Require().NoError(err) + addrj, err := sdk.AccAddressFromBech32(members[j].Address) + s.Require().NoError(err) + return bytes.Compare(addri, addrj) < 0 + }) + for i := range loadedMembers { + s.Assert().Equal(members[i].Metadata, loadedMembers[i].Member.Metadata) + s.Assert().Equal(members[i].Address, loadedMembers[i].Member.Address) + s.Assert().Equal(members[i].Weight, loadedMembers[i].Member.Weight) + s.Assert().Equal(blockTime, loadedMembers[i].Member.AddedAt) + s.Assert().Equal(id, loadedMembers[i].GroupId) + } + + // query groups by admin + groupsRes, err := s.groupKeeper.GroupsByAdmin(s.ctx, &group.QueryGroupsByAdminRequest{Admin: addr1.String()}) + s.Require().NoError(err) + loadedGroups := groupsRes.Groups + s.Require().Equal(len(spec.expGroups), len(loadedGroups)) + for i := range loadedGroups { + s.Assert().Equal(spec.expGroups[i].Metadata, loadedGroups[i].Metadata) + s.Assert().Equal(spec.expGroups[i].Admin, loadedGroups[i].Admin) + s.Assert().Equal(spec.expGroups[i].TotalWeight, loadedGroups[i].TotalWeight) + s.Assert().Equal(spec.expGroups[i].Id, loadedGroups[i].Id) + s.Assert().Equal(spec.expGroups[i].Version, loadedGroups[i].Version) + s.Assert().Equal(spec.expGroups[i].CreatedAt, loadedGroups[i].CreatedAt) + } + }) + } +} + +func (s *TestSuite) TestUpdateGroupMembers() { + addrs := s.addrs + addr3 := addrs[2] + addr4 := addrs[3] + addr5 := addrs[4] + addr6 := addrs[5] + + member1 := addr5.String() + member2 := addr6.String() + members := []group.MemberRequest{{ + Address: member1, + Weight: "1", + }} + + myAdmin := addr4.String() + groupRes, err := s.groupKeeper.CreateGroup(s.ctx, &group.MsgCreateGroup{ + Admin: myAdmin, + Members: members, + }) + s.Require().NoError(err) + groupID := groupRes.GroupId + + specs := map[string]struct { + req *group.MsgUpdateGroupMembers + expErr bool + expErrMsg string + expGroup *group.GroupInfo + expMembers []*group.GroupMember + }{ + "empty group id": { + req: &group.MsgUpdateGroupMembers{ + GroupId: 0, + Admin: myAdmin, + MemberUpdates: []group.MemberRequest{{ + Address: member2, + Weight: "2", + }}, + }, + expErr: true, + expErrMsg: "value is empty", + }, + "no new members": { + req: &group.MsgUpdateGroupMembers{ + GroupId: groupID, + Admin: myAdmin, + MemberUpdates: []group.MemberRequest{}, + }, + expErr: true, + expErrMsg: "value is empty", + }, + "invalid member": { + req: &group.MsgUpdateGroupMembers{ + GroupId: groupID, + Admin: myAdmin, + MemberUpdates: []group.MemberRequest{ + {}, + }, + }, + expErr: true, + expErrMsg: "unable to decode", + }, + "invalid member metadata too long": { + req: &group.MsgUpdateGroupMembers{ + GroupId: groupID, + Admin: myAdmin, + MemberUpdates: []group.MemberRequest{ + { + Address: member2, + Weight: "2", + Metadata: strings.Repeat("a", 256), + }, + }, + }, + expErr: true, + expErrMsg: "group member metadata: limit exceeded", + }, + "add new member": { + req: &group.MsgUpdateGroupMembers{ + GroupId: groupID, + Admin: myAdmin, + MemberUpdates: []group.MemberRequest{{ + Address: member2, + Weight: "2", + }}, + }, + expGroup: &group.GroupInfo{ + Id: groupID, + Admin: myAdmin, + TotalWeight: "3", + Version: 2, + CreatedAt: s.blockTime, + }, + expMembers: []*group.GroupMember{ + { + Member: &group.Member{ + Address: member2, + Weight: "2", + AddedAt: s.sdkCtx.BlockTime(), + }, + GroupId: groupID, + }, + { + Member: &group.Member{ + Address: member1, + Weight: "1", + AddedAt: s.blockTime, + }, + GroupId: groupID, + }, + }, + }, + "update member": { + req: &group.MsgUpdateGroupMembers{ + GroupId: groupID, + Admin: myAdmin, + MemberUpdates: []group.MemberRequest{{ + Address: member1, + Weight: "2", + }}, + }, + expGroup: &group.GroupInfo{ + Id: groupID, + Admin: myAdmin, + TotalWeight: "2", + Version: 2, + CreatedAt: s.blockTime, + }, + expMembers: []*group.GroupMember{ + { + GroupId: groupID, + Member: &group.Member{ + Address: member1, + Weight: "2", + AddedAt: s.blockTime, + }, + }, + }, + }, + "update member with same data": { + req: &group.MsgUpdateGroupMembers{ + GroupId: groupID, + Admin: myAdmin, + MemberUpdates: []group.MemberRequest{{ + Address: member1, + Weight: "1", + }}, + }, + expGroup: &group.GroupInfo{ + Id: groupID, + Admin: myAdmin, + TotalWeight: "1", + Version: 2, + CreatedAt: s.blockTime, + }, + expMembers: []*group.GroupMember{ + { + GroupId: groupID, + Member: &group.Member{ + Address: member1, + Weight: "1", + AddedAt: s.blockTime, + }, + }, + }, + }, + "replace member": { + req: &group.MsgUpdateGroupMembers{ + GroupId: groupID, + Admin: myAdmin, + MemberUpdates: []group.MemberRequest{ + { + Address: member1, + Weight: "0", + }, + { + Address: member2, + Weight: "1", + }, + }, + }, + expGroup: &group.GroupInfo{ + Id: groupID, + Admin: myAdmin, + TotalWeight: "1", + Version: 2, + CreatedAt: s.blockTime, + }, + expMembers: []*group.GroupMember{{ + GroupId: groupID, + Member: &group.Member{ + Address: member2, + Weight: "1", + AddedAt: s.sdkCtx.BlockTime(), + }, + }}, + }, + "remove existing member": { + req: &group.MsgUpdateGroupMembers{ + GroupId: groupID, + Admin: myAdmin, + MemberUpdates: []group.MemberRequest{{ + Address: member1, + Weight: "0", + }}, + }, + expGroup: &group.GroupInfo{ + Id: groupID, + Admin: myAdmin, + TotalWeight: "0", + Version: 2, + CreatedAt: s.blockTime, + }, + expMembers: []*group.GroupMember{}, + }, + "remove unknown member": { + req: &group.MsgUpdateGroupMembers{ + GroupId: groupID, + Admin: myAdmin, + MemberUpdates: []group.MemberRequest{{ + Address: addr4.String(), + Weight: "0", + }}, + }, + expErr: true, + expGroup: &group.GroupInfo{ + Id: groupID, + Admin: myAdmin, + TotalWeight: "1", + Version: 1, + CreatedAt: s.blockTime, + }, + expMembers: []*group.GroupMember{{ + GroupId: groupID, + Member: &group.Member{ + Address: member1, + Weight: "1", + }, + }}, + }, + "with wrong admin": { + req: &group.MsgUpdateGroupMembers{ + GroupId: groupID, + Admin: addr3.String(), + MemberUpdates: []group.MemberRequest{{ + Address: member1, + Weight: "2", + }}, + }, + expErr: true, + expErrMsg: "not group admin", + expGroup: &group.GroupInfo{ + Id: groupID, + Admin: myAdmin, + TotalWeight: "1", + Version: 1, + CreatedAt: s.blockTime, + }, + expMembers: []*group.GroupMember{{ + GroupId: groupID, + Member: &group.Member{ + Address: member1, + Weight: "1", + }, + }}, + }, + "with unknown groupID": { + req: &group.MsgUpdateGroupMembers{ + GroupId: 999, + Admin: myAdmin, + MemberUpdates: []group.MemberRequest{{ + Address: member1, + Weight: "2", + }}, + }, + expErr: true, + expErrMsg: "not found", + expGroup: &group.GroupInfo{ + Id: groupID, + Admin: myAdmin, + TotalWeight: "1", + Version: 1, + CreatedAt: s.blockTime, + }, + expMembers: []*group.GroupMember{{ + GroupId: groupID, + Member: &group.Member{ + Address: member1, + Weight: "1", + }, + }}, + }, + } + for msg, spec := range specs { + spec := spec + s.Run(msg, func() { + sdkCtx, _ := s.sdkCtx.CacheContext() + _, err := s.groupKeeper.UpdateGroupMembers(sdkCtx, spec.req) + if spec.expErr { + s.Require().Error(err) + s.Require().Contains(err.Error(), spec.expErrMsg) + return + } + s.Require().NoError(err) + + // then + res, err := s.groupKeeper.GroupInfo(sdkCtx, &group.QueryGroupInfoRequest{GroupId: groupID}) + s.Require().NoError(err) + s.Assert().Equal(spec.expGroup, res.Info) + + // and members persisted + membersRes, err := s.groupKeeper.GroupMembers(sdkCtx, &group.QueryGroupMembersRequest{GroupId: groupID}) + s.Require().NoError(err) + loadedMembers := membersRes.Members + s.Require().Equal(len(spec.expMembers), len(loadedMembers)) + // we reorder group members by address to be able to compare them + sort.Slice(spec.expMembers, func(i, j int) bool { + addri, err := sdk.AccAddressFromBech32(spec.expMembers[i].Member.Address) + s.Require().NoError(err) + addrj, err := sdk.AccAddressFromBech32(spec.expMembers[j].Member.Address) + s.Require().NoError(err) + return bytes.Compare(addri, addrj) < 0 + }) + for i := range loadedMembers { + s.Assert().Equal(spec.expMembers[i].Member.Metadata, loadedMembers[i].Member.Metadata) + s.Assert().Equal(spec.expMembers[i].Member.Address, loadedMembers[i].Member.Address) + s.Assert().Equal(spec.expMembers[i].Member.Weight, loadedMembers[i].Member.Weight) + s.Assert().Equal(spec.expMembers[i].Member.AddedAt, loadedMembers[i].Member.AddedAt) + s.Assert().Equal(spec.expMembers[i].GroupId, loadedMembers[i].GroupId) + } + + events := sdkCtx.EventManager().ABCIEvents() + s.Require().Len(events, 1) // EventUpdateGroup + }) + } +} + +func (s *TestSuite) TestUpdateGroupAdmin() { + addrs := s.addrs + addr1 := addrs[0] + addr2 := addrs[1] + addr3 := addrs[2] + addr4 := addrs[3] + + members := []group.MemberRequest{{ + Address: addr1.String(), + Weight: "1", + }} + oldAdmin := addr2.String() + newAdmin := addr3.String() + groupRes, err := s.groupKeeper.CreateGroup(s.ctx, &group.MsgCreateGroup{ + Admin: oldAdmin, + Members: members, + }) + s.Require().NoError(err) + groupID := groupRes.GroupId + specs := map[string]struct { + req *group.MsgUpdateGroupAdmin + expStored *group.GroupInfo + expErr bool + expErrMsg string + }{ + "with no groupID": { + req: &group.MsgUpdateGroupAdmin{ + GroupId: 0, + Admin: oldAdmin, + NewAdmin: newAdmin, + }, + expErr: true, + expErrMsg: "value is empty", + }, + "with identical admin and new admin": { + req: &group.MsgUpdateGroupAdmin{ + GroupId: groupID, + Admin: oldAdmin, + NewAdmin: oldAdmin, + }, + expErr: true, + expErrMsg: "new and old admin are the same", + }, + "with correct admin": { + req: &group.MsgUpdateGroupAdmin{ + GroupId: groupID, + Admin: oldAdmin, + NewAdmin: newAdmin, + }, + expStored: &group.GroupInfo{ + Id: groupID, + Admin: newAdmin, + TotalWeight: "1", + Version: 2, + CreatedAt: s.blockTime, + }, + }, + "with wrong admin": { + req: &group.MsgUpdateGroupAdmin{ + GroupId: groupID, + Admin: addr4.String(), + NewAdmin: newAdmin, + }, + expErr: true, + expErrMsg: "not group admin", + expStored: &group.GroupInfo{ + Id: groupID, + Admin: oldAdmin, + TotalWeight: "1", + Version: 1, + CreatedAt: s.blockTime, + }, + }, + "with unknown groupID": { + req: &group.MsgUpdateGroupAdmin{ + GroupId: 999, + Admin: oldAdmin, + NewAdmin: newAdmin, + }, + expErr: true, + expErrMsg: "not found", + expStored: &group.GroupInfo{ + Id: groupID, + Admin: oldAdmin, + TotalWeight: "1", + Version: 1, + CreatedAt: s.blockTime, + }, + }, + } + for msg, spec := range specs { + spec := spec + s.Run(msg, func() { + _, err := s.groupKeeper.UpdateGroupAdmin(s.ctx, spec.req) + if spec.expErr { + s.Require().Error(err) + s.Require().Contains(err.Error(), spec.expErrMsg) + return + } + s.Require().NoError(err) + + // then + res, err := s.groupKeeper.GroupInfo(s.ctx, &group.QueryGroupInfoRequest{GroupId: groupID}) + s.Require().NoError(err) + s.Assert().Equal(spec.expStored, res.Info) + }) + } +} + +func (s *TestSuite) TestUpdateGroupMetadata() { + addrs := s.addrs + addr1 := addrs[0] + addr3 := addrs[2] + + oldAdmin := addr1.String() + groupID := s.groupID + + specs := map[string]struct { + req *group.MsgUpdateGroupMetadata + expErr bool + expStored *group.GroupInfo + }{ + "with correct admin": { + req: &group.MsgUpdateGroupMetadata{ + GroupId: groupID, + Admin: oldAdmin, + }, + expStored: &group.GroupInfo{ + Id: groupID, + Admin: oldAdmin, + TotalWeight: "3", + Version: 2, + CreatedAt: s.blockTime, + }, + }, + "with wrong admin": { + req: &group.MsgUpdateGroupMetadata{ + GroupId: groupID, + Admin: addr3.String(), + }, + expErr: true, + expStored: &group.GroupInfo{ + Id: groupID, + Admin: oldAdmin, + TotalWeight: "1", + Version: 1, + CreatedAt: s.blockTime, + }, + }, + "with unknown groupid": { + req: &group.MsgUpdateGroupMetadata{ + GroupId: 999, + Admin: oldAdmin, + }, + expErr: true, + expStored: &group.GroupInfo{ + Id: groupID, + Admin: oldAdmin, + TotalWeight: "1", + Version: 1, + CreatedAt: s.blockTime, + }, + }, + } + for msg, spec := range specs { + spec := spec + s.Run(msg, func() { + sdkCtx, _ := s.sdkCtx.CacheContext() + _, err := s.groupKeeper.UpdateGroupMetadata(sdkCtx, spec.req) + if spec.expErr { + s.Require().Error(err) + return + } + s.Require().NoError(err) + + // then + res, err := s.groupKeeper.GroupInfo(sdkCtx, &group.QueryGroupInfoRequest{GroupId: groupID}) + s.Require().NoError(err) + s.Assert().Equal(spec.expStored, res.Info) + + events := sdkCtx.EventManager().ABCIEvents() + s.Require().Len(events, 1) // EventUpdateGroup + }) + } +} + +func (s *TestSuite) TestCreateGroupWithPolicy() { + addrs := s.addrs + addr1 := addrs[0] + addr3 := addrs[2] + addr5 := addrs[4] + addr6 := addrs[5] + + s.setNextAccount() + + members := []group.MemberRequest{{ + Address: addr5.String(), + Weight: "1", + }, { + Address: addr6.String(), + Weight: "2", + }} + + specs := map[string]struct { + req *group.MsgCreateGroupWithPolicy + policy group.DecisionPolicy + malleate func() + expErr bool + expErrMsg string + }{ + "all good": { + req: &group.MsgCreateGroupWithPolicy{ + Admin: addr1.String(), + Members: members, + GroupPolicyAsAdmin: false, + }, + malleate: func() { + s.setNextAccount() + }, + policy: group.NewThresholdDecisionPolicy( + "1", + time.Second, + 0, + ), + }, + "group policy as admin is true": { + req: &group.MsgCreateGroupWithPolicy{ + Admin: addr1.String(), + Members: members, + GroupPolicyAsAdmin: true, + }, + malleate: func() { + s.setNextAccount() + }, + policy: group.NewThresholdDecisionPolicy( + "1", + time.Second, + 0, + ), + }, + "group metadata too long": { + req: &group.MsgCreateGroupWithPolicy{ + Admin: addr1.String(), + Members: members, + GroupPolicyAsAdmin: false, + GroupMetadata: strings.Repeat("a", 256), + }, + policy: group.NewThresholdDecisionPolicy( + "1", + time.Second, + 0, + ), + expErr: true, + expErrMsg: "group metadata: limit exceeded", + }, + "group policy metadata too long": { + req: &group.MsgCreateGroupWithPolicy{ + Admin: addr1.String(), + Members: members, + GroupPolicyAsAdmin: false, + GroupPolicyMetadata: strings.Repeat("a", 256), + }, + policy: group.NewThresholdDecisionPolicy( + "1", + time.Second, + 0, + ), + expErr: true, + expErrMsg: "group policy metadata: limit exceeded", + }, + "member metadata too long": { + req: &group.MsgCreateGroupWithPolicy{ + Admin: addr1.String(), + Members: []group.MemberRequest{{ + Address: addr3.String(), + Weight: "1", + Metadata: strings.Repeat("a", 256), + }}, + GroupPolicyAsAdmin: false, + }, + policy: group.NewThresholdDecisionPolicy( + "1", + time.Second, + 0, + ), + expErr: true, + expErrMsg: "member metadata: limit exceeded", + }, + "zero member weight": { + req: &group.MsgCreateGroupWithPolicy{ + Admin: addr1.String(), + Members: []group.MemberRequest{{ + Address: addr3.String(), + Weight: "0", + }}, + GroupPolicyAsAdmin: false, + }, + policy: group.NewThresholdDecisionPolicy( + "1", + time.Second, + 0, + ), + expErr: true, + expErrMsg: "expected a positive decimal", + }, + "invalid member address": { + req: &group.MsgCreateGroupWithPolicy{ + Admin: addr1.String(), + Members: []group.MemberRequest{{ + Address: "invalid", + Weight: "1", + }}, + GroupPolicyAsAdmin: false, + }, + policy: group.NewThresholdDecisionPolicy( + "1", + time.Second, + 0, + ), + expErr: true, + expErrMsg: "unable to decode", + }, + "decision policy threshold > total group weight": { + req: &group.MsgCreateGroupWithPolicy{ + Admin: addr1.String(), + Members: members, + GroupPolicyAsAdmin: false, + }, + malleate: func() { + s.setNextAccount() + }, + policy: group.NewThresholdDecisionPolicy( + "10", + time.Second, + 0, + ), + expErr: false, + }, + } + + for msg, spec := range specs { + spec := spec + s.Run(msg, func() { + s.setNextAccount() + err := spec.req.SetDecisionPolicy(spec.policy) + s.Require().NoError(err) + + blockTime := sdk.UnwrapSDKContext(s.ctx).BlockTime() + res, err := s.groupKeeper.CreateGroupWithPolicy(s.ctx, spec.req) + if spec.expErr { + s.Require().Error(err) + s.Require().Contains(err.Error(), spec.expErrMsg) + return + } + s.Require().NoError(err) + id := res.GroupId + groupPolicyAddr := res.GroupPolicyAddress + + // then all data persisted in group + loadedGroupRes, err := s.groupKeeper.GroupInfo(s.ctx, &group.QueryGroupInfoRequest{GroupId: id}) + s.Require().NoError(err) + s.Assert().Equal(spec.req.GroupMetadata, loadedGroupRes.Info.Metadata) + s.Assert().Equal(id, loadedGroupRes.Info.Id) + if spec.req.GroupPolicyAsAdmin { + s.Assert().NotEqual(spec.req.Admin, loadedGroupRes.Info.Admin) + s.Assert().Equal(groupPolicyAddr, loadedGroupRes.Info.Admin) + } else { + s.Assert().Equal(spec.req.Admin, loadedGroupRes.Info.Admin) + } + + // and members are stored as well + membersRes, err := s.groupKeeper.GroupMembers(s.ctx, &group.QueryGroupMembersRequest{GroupId: id}) + s.Require().NoError(err) + loadedMembers := membersRes.Members + s.Require().Equal(len(members), len(loadedMembers)) + // we reorder members by address to be able to compare them + sort.Slice(members, func(i, j int) bool { + addri, err := sdk.AccAddressFromBech32(members[i].Address) + s.Require().NoError(err) + addrj, err := sdk.AccAddressFromBech32(members[j].Address) + s.Require().NoError(err) + return bytes.Compare(addri, addrj) < 0 + }) + for i := range loadedMembers { + s.Assert().Equal(members[i].Metadata, loadedMembers[i].Member.Metadata) + s.Assert().Equal(members[i].Address, loadedMembers[i].Member.Address) + s.Assert().Equal(members[i].Weight, loadedMembers[i].Member.Weight) + s.Assert().Equal(blockTime, loadedMembers[i].Member.AddedAt) + s.Assert().Equal(id, loadedMembers[i].GroupId) + } + + // then all data persisted in group policy + groupPolicyRes, err := s.groupKeeper.GroupPolicyInfo(s.ctx, &group.QueryGroupPolicyInfoRequest{Address: groupPolicyAddr}) + s.Require().NoError(err) + + groupPolicy := groupPolicyRes.Info + s.Assert().Equal(groupPolicyAddr, groupPolicy.Address) + s.Assert().Equal(id, groupPolicy.GroupId) + s.Assert().Equal(spec.req.GroupPolicyMetadata, groupPolicy.Metadata) + dp, err := groupPolicy.GetDecisionPolicy() + s.Assert().NoError(err) + s.Assert().Equal(spec.policy.(*group.ThresholdDecisionPolicy), dp) + if spec.req.GroupPolicyAsAdmin { + s.Assert().NotEqual(spec.req.Admin, groupPolicy.Admin) + s.Assert().Equal(groupPolicyAddr, groupPolicy.Admin) + } else { + s.Assert().Equal(spec.req.Admin, groupPolicy.Admin) + } + }) + } +} + +func (s *TestSuite) TestCreateGroupPolicy() { + addrs := s.addrs + addr1 := addrs[0] + addr4 := addrs[3] + + s.setNextAccount() + groupRes, err := s.groupKeeper.CreateGroup(s.ctx, &group.MsgCreateGroup{ + Admin: addr1.String(), + Members: nil, + }) + s.Require().NoError(err) + myGroupID := groupRes.GroupId + + specs := map[string]struct { + req *group.MsgCreateGroupPolicy + policy group.DecisionPolicy + expErr bool + expErrMsg string + }{ + "all good": { + req: &group.MsgCreateGroupPolicy{ + Admin: addr1.String(), + GroupId: myGroupID, + }, + policy: group.NewThresholdDecisionPolicy( + "1", + time.Second, + 0, + ), + }, + "all good with percentage decision policy": { + req: &group.MsgCreateGroupPolicy{ + Admin: addr1.String(), + GroupId: myGroupID, + }, + policy: group.NewPercentageDecisionPolicy( + "0.5", + time.Second, + 0, + ), + }, + "decision policy threshold > total group weight": { + req: &group.MsgCreateGroupPolicy{ + Admin: addr1.String(), + GroupId: myGroupID, + }, + policy: group.NewThresholdDecisionPolicy( + "10", + time.Second, + 0, + ), + }, + "group id does not exists": { + req: &group.MsgCreateGroupPolicy{ + Admin: addr1.String(), + GroupId: 9999, + }, + policy: group.NewThresholdDecisionPolicy( + "1", + time.Second, + 0, + ), + expErr: true, + expErrMsg: "not found", + }, + "admin not group admin": { + req: &group.MsgCreateGroupPolicy{ + Admin: addr4.String(), + GroupId: myGroupID, + }, + policy: group.NewThresholdDecisionPolicy( + "1", + time.Second, + 0, + ), + expErr: true, + expErrMsg: "not group admin", + }, + "metadata too long": { + req: &group.MsgCreateGroupPolicy{ + Admin: addr1.String(), + GroupId: myGroupID, + Metadata: strings.Repeat("a", 256), + }, + policy: group.NewThresholdDecisionPolicy( + "1", + time.Second, + 0, + ), + expErr: true, + expErrMsg: "limit exceeded", + }, + "percentage decision policy with negative value": { + req: &group.MsgCreateGroupPolicy{ + Admin: addr1.String(), + GroupId: myGroupID, + }, + policy: group.NewPercentageDecisionPolicy( + "-0.5", + time.Second, + 0, + ), + expErr: true, + expErrMsg: "expected a positive decimal", + }, + "percentage decision policy with value greater than 1": { + req: &group.MsgCreateGroupPolicy{ + Admin: addr1.String(), + GroupId: myGroupID, + }, + policy: group.NewPercentageDecisionPolicy( + "2", + time.Second, + 0, + ), + expErr: true, + expErrMsg: "percentage must be > 0 and <= 1", + }, + } + for msg, spec := range specs { + spec := spec + s.Run(msg, func() { + err := spec.req.SetDecisionPolicy(spec.policy) + s.Require().NoError(err) + + s.setNextAccount() + + res, err := s.groupKeeper.CreateGroupPolicy(s.ctx, spec.req) + if spec.expErr { + s.Require().Error(err) + s.Require().Contains(err.Error(), spec.expErrMsg) + return + } + s.Require().NoError(err) + addr := res.Address + + // then all data persisted + groupPolicyRes, err := s.groupKeeper.GroupPolicyInfo(s.ctx, &group.QueryGroupPolicyInfoRequest{Address: addr}) + s.Require().NoError(err) + + groupPolicy := groupPolicyRes.Info + s.Assert().Equal(addr, groupPolicy.Address) + s.Assert().Equal(myGroupID, groupPolicy.GroupId) + s.Assert().Equal(spec.req.Admin, groupPolicy.Admin) + s.Assert().Equal(spec.req.Metadata, groupPolicy.Metadata) + s.Assert().Equal(uint64(1), groupPolicy.Version) + percentageDecisionPolicy, ok := spec.policy.(*group.PercentageDecisionPolicy) + if ok { + dp, err := groupPolicy.GetDecisionPolicy() + s.Assert().NoError(err) + s.Assert().Equal(percentageDecisionPolicy, dp) + } else { + dp, err := groupPolicy.GetDecisionPolicy() + s.Assert().NoError(err) + s.Assert().Equal(spec.policy.(*group.ThresholdDecisionPolicy), dp) + } + }) + } +} + +func (s *TestSuite) TestUpdateGroupPolicyAdmin() { + addrs := s.addrs + addr1 := addrs[0] + addr2 := addrs[1] + addr5 := addrs[4] + + admin, newAdmin := addr1, addr2 + policy := group.NewThresholdDecisionPolicy( + "1", + time.Second, + 0, + ) + s.setNextAccount() + groupPolicyAddr, myGroupID := s.createGroupAndGroupPolicy(admin, nil, policy) + + specs := map[string]struct { + req *group.MsgUpdateGroupPolicyAdmin + expGroupPolicy *group.GroupPolicyInfo + expErr bool + expErrMsg string + }{ + "with wrong admin": { + req: &group.MsgUpdateGroupPolicyAdmin{ + Admin: addr5.String(), + GroupPolicyAddress: groupPolicyAddr, + NewAdmin: newAdmin.String(), + }, + expGroupPolicy: &group.GroupPolicyInfo{ + Admin: admin.String(), + Address: groupPolicyAddr, + GroupId: myGroupID, + Version: 2, + DecisionPolicy: nil, + CreatedAt: s.blockTime, + }, + expErr: true, + expErrMsg: "not group policy admin: unauthorized", + }, + "with wrong group policy": { + req: &group.MsgUpdateGroupPolicyAdmin{ + Admin: admin.String(), + GroupPolicyAddress: addr5.String(), + NewAdmin: newAdmin.String(), + }, + expGroupPolicy: &group.GroupPolicyInfo{ + Admin: admin.String(), + Address: groupPolicyAddr, + GroupId: myGroupID, + Version: 2, + DecisionPolicy: nil, + CreatedAt: s.blockTime, + }, + expErr: true, + expErrMsg: "load group policy: not found", + }, + "correct data": { + req: &group.MsgUpdateGroupPolicyAdmin{ + Admin: admin.String(), + GroupPolicyAddress: groupPolicyAddr, + NewAdmin: newAdmin.String(), + }, + expGroupPolicy: &group.GroupPolicyInfo{ + Admin: newAdmin.String(), + Address: groupPolicyAddr, + GroupId: myGroupID, + Version: 2, + DecisionPolicy: nil, + CreatedAt: s.blockTime, + }, + expErr: false, + }, + } + for msg, spec := range specs { + spec := spec + err := spec.expGroupPolicy.SetDecisionPolicy(policy) + s.Require().NoError(err) + + s.Run(msg, func() { + _, err := s.groupKeeper.UpdateGroupPolicyAdmin(s.ctx, spec.req) + if spec.expErr { + s.Require().Error(err) + s.Require().Contains(err.Error(), spec.expErrMsg) + return + } + s.Require().NoError(err) + res, err := s.groupKeeper.GroupPolicyInfo(s.ctx, &group.QueryGroupPolicyInfoRequest{ + Address: groupPolicyAddr, + }) + s.Require().NoError(err) + s.Assert().Equal(spec.expGroupPolicy, res.Info) + }) + } +} + +func (s *TestSuite) TestUpdateGroupPolicyDecisionPolicy() { + addrs := s.addrs + addr1 := addrs[0] + addr5 := addrs[4] + + admin := addr1 + policy := group.NewThresholdDecisionPolicy( + "1", + time.Second, + 0, + ) + + s.setNextAccount() + groupPolicyAddr, myGroupID := s.createGroupAndGroupPolicy(admin, nil, policy) + + specs := map[string]struct { + preRun func(admin sdk.AccAddress) (policyAddr string, groupId uint64) + req *group.MsgUpdateGroupPolicyDecisionPolicy + policy group.DecisionPolicy + expGroupPolicy *group.GroupPolicyInfo + expErr bool + expErrMsg string + }{ + "with wrong admin": { + req: &group.MsgUpdateGroupPolicyDecisionPolicy{ + Admin: addr5.String(), + GroupPolicyAddress: groupPolicyAddr, + }, + policy: policy, + expGroupPolicy: &group.GroupPolicyInfo{}, + expErr: true, + expErrMsg: "not group policy admin: unauthorized", + }, + "with wrong group policy": { + req: &group.MsgUpdateGroupPolicyDecisionPolicy{ + Admin: admin.String(), + GroupPolicyAddress: addr5.String(), + }, + policy: policy, + expGroupPolicy: &group.GroupPolicyInfo{}, + expErr: true, + expErrMsg: "load group policy: not found", + }, + "invalid percentage decision policy with negative value": { + req: &group.MsgUpdateGroupPolicyDecisionPolicy{ + Admin: admin.String(), + GroupPolicyAddress: groupPolicyAddr, + }, + policy: group.NewPercentageDecisionPolicy( + "-0.5", + time.Duration(1)*time.Second, + 0, + ), + expGroupPolicy: &group.GroupPolicyInfo{ + Admin: admin.String(), + Address: groupPolicyAddr, + GroupId: myGroupID, + Version: 2, + DecisionPolicy: nil, + CreatedAt: s.blockTime, + }, + expErr: true, + expErrMsg: "expected a positive decimal", + }, + "invalid percentage decision policy with value greater than 1": { + req: &group.MsgUpdateGroupPolicyDecisionPolicy{ + Admin: admin.String(), + GroupPolicyAddress: groupPolicyAddr, + }, + policy: group.NewPercentageDecisionPolicy( + "2", + time.Duration(1)*time.Second, + 0, + ), + expGroupPolicy: &group.GroupPolicyInfo{ + Admin: admin.String(), + Address: groupPolicyAddr, + GroupId: myGroupID, + Version: 2, + DecisionPolicy: nil, + CreatedAt: s.blockTime, + }, + expErr: true, + expErrMsg: "percentage must be > 0 and <= 1", + }, + "correct data": { + req: &group.MsgUpdateGroupPolicyDecisionPolicy{ + Admin: admin.String(), + GroupPolicyAddress: groupPolicyAddr, + }, + policy: group.NewThresholdDecisionPolicy( + "2", + time.Duration(2)*time.Second, + 0, + ), + expGroupPolicy: &group.GroupPolicyInfo{ + Admin: admin.String(), + Address: groupPolicyAddr, + GroupId: myGroupID, + Version: 2, + DecisionPolicy: nil, + CreatedAt: s.blockTime, + }, + expErr: false, + }, + "correct data with percentage decision policy": { + preRun: func(admin sdk.AccAddress) (string, uint64) { + s.setNextAccount() + return s.createGroupAndGroupPolicy(admin, nil, policy) + }, + req: &group.MsgUpdateGroupPolicyDecisionPolicy{ + Admin: admin.String(), + GroupPolicyAddress: groupPolicyAddr, + }, + policy: group.NewPercentageDecisionPolicy( + "0.5", + time.Duration(2)*time.Second, + 0, + ), + expGroupPolicy: &group.GroupPolicyInfo{ + Admin: admin.String(), + DecisionPolicy: nil, + Version: 2, + CreatedAt: s.blockTime, + }, + expErr: false, + }, + } + for msg, spec := range specs { + spec := spec + policyAddr := groupPolicyAddr + err := spec.expGroupPolicy.SetDecisionPolicy(spec.policy) + s.Require().NoError(err) + if spec.preRun != nil { + policyAddr1, groupID := spec.preRun(admin) + policyAddr = policyAddr1 + + // update the expected info with new group policy details + spec.expGroupPolicy.Address = policyAddr1 + spec.expGroupPolicy.GroupId = groupID + + // update req with new group policy addr + spec.req.GroupPolicyAddress = policyAddr1 + } + + err = spec.req.SetDecisionPolicy(spec.policy) + s.Require().NoError(err) + + s.Run(msg, func() { + _, err := s.groupKeeper.UpdateGroupPolicyDecisionPolicy(s.ctx, spec.req) + if spec.expErr { + s.Require().Error(err) + s.Require().Contains(err.Error(), spec.expErrMsg) + return + } + s.Require().NoError(err) + res, err := s.groupKeeper.GroupPolicyInfo(s.ctx, &group.QueryGroupPolicyInfoRequest{ + Address: policyAddr, + }) + s.Require().NoError(err) + s.Assert().Equal(spec.expGroupPolicy, res.Info) + }) + } +} + +func (s *TestSuite) TestUpdateGroupPolicyMetadata() { + addrs := s.addrs + addr1 := addrs[0] + addr5 := addrs[4] + + admin := addr1 + policy := group.NewThresholdDecisionPolicy( + "1", + time.Second, + 0, + ) + + s.setNextAccount() + groupPolicyAddr, myGroupID := s.createGroupAndGroupPolicy(admin, nil, policy) + + specs := map[string]struct { + req *group.MsgUpdateGroupPolicyMetadata + expGroupPolicy *group.GroupPolicyInfo + expErr bool + expErrMsg string + }{ + "with wrong admin": { + req: &group.MsgUpdateGroupPolicyMetadata{ + Admin: addr5.String(), + GroupPolicyAddress: groupPolicyAddr, + }, + expGroupPolicy: &group.GroupPolicyInfo{}, + expErr: true, + expErrMsg: "not group policy admin: unauthorized", + }, + "with wrong group policy": { + req: &group.MsgUpdateGroupPolicyMetadata{ + Admin: admin.String(), + GroupPolicyAddress: addr5.String(), + }, + expGroupPolicy: &group.GroupPolicyInfo{}, + expErr: true, + expErrMsg: "load group policy: not found", + }, + "with metadata too long": { + req: &group.MsgUpdateGroupPolicyMetadata{ + Admin: admin.String(), + GroupPolicyAddress: groupPolicyAddr, + Metadata: strings.Repeat("a", 1001), + }, + expGroupPolicy: &group.GroupPolicyInfo{}, + expErr: true, + expErrMsg: "group policy metadata: limit exceeded", + }, + "correct data": { + req: &group.MsgUpdateGroupPolicyMetadata{ + Admin: admin.String(), + GroupPolicyAddress: groupPolicyAddr, + }, + expGroupPolicy: &group.GroupPolicyInfo{ + Admin: admin.String(), + Address: groupPolicyAddr, + GroupId: myGroupID, + Version: 2, + DecisionPolicy: nil, + CreatedAt: s.blockTime, + }, + expErr: false, + }, + } + for msg, spec := range specs { + spec := spec + err := spec.expGroupPolicy.SetDecisionPolicy(policy) + s.Require().NoError(err) + + s.Run(msg, func() { + _, err := s.groupKeeper.UpdateGroupPolicyMetadata(s.ctx, spec.req) + if spec.expErr { + s.Require().Error(err) + s.Require().Contains(err.Error(), spec.expErrMsg) + return + } + s.Require().NoError(err) + + res, err := s.groupKeeper.GroupPolicyInfo(s.ctx, &group.QueryGroupPolicyInfoRequest{ + Address: groupPolicyAddr, + }) + s.Require().NoError(err) + s.Assert().Equal(spec.expGroupPolicy, res.Info) + + // check events + var hasUpdateGroupPolicyEvent bool + events := s.ctx.(sdk.Context).EventManager().ABCIEvents() + for _, event := range events { + event, err := sdk.ParseTypedEvent(event) + s.Require().NoError(err) + + if e, ok := event.(*group.EventUpdateGroupPolicy); ok { + s.Require().Equal(e.Address, groupPolicyAddr) + hasUpdateGroupPolicyEvent = true + break + } + } + + s.Require().True(hasUpdateGroupPolicyEvent) + }) + } +} + +func (s *TestSuite) TestGroupPoliciesByAdminOrGroup() { + addrs := s.addrs + addr2 := addrs[1] + + admin := addr2 + + groupRes, err := s.groupKeeper.CreateGroup(s.ctx, &group.MsgCreateGroup{ + Admin: admin.String(), + Members: nil, + }) + s.Require().NoError(err) + myGroupID := groupRes.GroupId + + policies := []group.DecisionPolicy{ + group.NewThresholdDecisionPolicy( + "1", + time.Second, + 0, + ), + group.NewThresholdDecisionPolicy( + "10", + time.Second, + 0, + ), + group.NewPercentageDecisionPolicy( + "0.5", + time.Second, + 0, + ), + } + + count := 3 + expectAccs := make([]*group.GroupPolicyInfo, count) + for i := range expectAccs { + req := &group.MsgCreateGroupPolicy{ + Admin: admin.String(), + GroupId: myGroupID, + } + err := req.SetDecisionPolicy(policies[i]) + s.Require().NoError(err) + + s.setNextAccount() + res, err := s.groupKeeper.CreateGroupPolicy(s.ctx, req) + s.Require().NoError(err) + + expectAcc := &group.GroupPolicyInfo{ + Address: res.Address, + Admin: admin.String(), + GroupId: myGroupID, + Version: uint64(1), + CreatedAt: s.blockTime, + } + err = expectAcc.SetDecisionPolicy(policies[i]) + s.Require().NoError(err) + expectAccs[i] = expectAcc + } + sort.Slice(expectAccs, func(i, j int) bool { return expectAccs[i].Address < expectAccs[j].Address }) + + // query group policy by group + policiesByGroupRes, err := s.groupKeeper.GroupPoliciesByGroup(s.ctx, &group.QueryGroupPoliciesByGroupRequest{ + GroupId: myGroupID, + }) + s.Require().NoError(err) + policyAccs := policiesByGroupRes.GroupPolicies + s.Require().Equal(len(policyAccs), count) + // we reorder policyAccs by address to be able to compare them + sort.Slice(policyAccs, func(i, j int) bool { return policyAccs[i].Address < policyAccs[j].Address }) + for i := range policyAccs { + s.Assert().Equal(policyAccs[i].Address, expectAccs[i].Address) + s.Assert().Equal(policyAccs[i].GroupId, expectAccs[i].GroupId) + s.Assert().Equal(policyAccs[i].Admin, expectAccs[i].Admin) + s.Assert().Equal(policyAccs[i].Metadata, expectAccs[i].Metadata) + s.Assert().Equal(policyAccs[i].Version, expectAccs[i].Version) + s.Assert().Equal(policyAccs[i].CreatedAt, expectAccs[i].CreatedAt) + dp1, err := policyAccs[i].GetDecisionPolicy() + s.Assert().NoError(err) + dp2, err := expectAccs[i].GetDecisionPolicy() + s.Assert().NoError(err) + s.Assert().Equal(dp1, dp2) + } + + // query group policy by admin + policiesByAdminRes, err := s.groupKeeper.GroupPoliciesByAdmin(s.ctx, &group.QueryGroupPoliciesByAdminRequest{ + Admin: admin.String(), + }) + s.Require().NoError(err) + policyAccs = policiesByAdminRes.GroupPolicies + s.Require().Equal(len(policyAccs), count) + // we reorder policyAccs by address to be able to compare them + sort.Slice(policyAccs, func(i, j int) bool { return policyAccs[i].Address < policyAccs[j].Address }) + for i := range policyAccs { + s.Assert().Equal(policyAccs[i].Address, expectAccs[i].Address) + s.Assert().Equal(policyAccs[i].GroupId, expectAccs[i].GroupId) + s.Assert().Equal(policyAccs[i].Admin, expectAccs[i].Admin) + s.Assert().Equal(policyAccs[i].Metadata, expectAccs[i].Metadata) + s.Assert().Equal(policyAccs[i].Version, expectAccs[i].Version) + s.Assert().Equal(policyAccs[i].CreatedAt, expectAccs[i].CreatedAt) + dp1, err := policyAccs[i].GetDecisionPolicy() + s.Assert().NoError(err) + dp2, err := expectAccs[i].GetDecisionPolicy() + s.Assert().NoError(err) + s.Assert().Equal(dp1, dp2) + } +} + +func (s *TestSuite) TestSubmitProposal() { + addrs := s.addrs + addr1 := addrs[0] + addr2 := addrs[1] // Has weight 2 + addr4 := addrs[3] + addr5 := addrs[4] // Has weight 1 + + myGroupID := s.groupID + accountAddr := s.groupPolicyAddr + + // Create a new group policy to test TRY_EXEC + policyReq := &group.MsgCreateGroupPolicy{ + Admin: addr1.String(), + GroupId: myGroupID, + } + noMinExecPeriodPolicy := group.NewThresholdDecisionPolicy( + "2", + time.Second, + 0, // no MinExecutionPeriod to test TRY_EXEC + ) + err := policyReq.SetDecisionPolicy(noMinExecPeriodPolicy) + s.Require().NoError(err) + s.setNextAccount() + res, err := s.groupKeeper.CreateGroupPolicy(s.ctx, policyReq) + s.Require().NoError(err) + + s.accountKeeper.EXPECT().StringToBytes(res.Address).Return(sdk.MustAccAddressFromBech32(res.Address).Bytes(), nil).AnyTimes() + noMinExecPeriodPolicyAddr, err := s.accountKeeper.StringToBytes(res.Address) + s.Require().NoError(err) + + // Create a new group policy with super high threshold + bigThresholdPolicy := group.NewThresholdDecisionPolicy( + "100", + time.Second, + minExecutionPeriod, + ) + s.setNextAccount() + err = policyReq.SetDecisionPolicy(bigThresholdPolicy) + s.Require().NoError(err) + bigThresholdRes, err := s.groupKeeper.CreateGroupPolicy(s.ctx, policyReq) + s.Require().NoError(err) + bigThresholdAddr := bigThresholdRes.Address + + msgSend := &banktypes.MsgSend{ + FromAddress: res.Address, + ToAddress: addr2.String(), + Amount: sdk.Coins{sdk.NewInt64Coin("test", 100)}, + } + defaultProposal := group.Proposal{ + GroupPolicyAddress: accountAddr.String(), + Status: group.PROPOSAL_STATUS_SUBMITTED, + FinalTallyResult: group.TallyResult{ + YesCount: "0", + NoCount: "0", + AbstainCount: "0", + NoWithVetoCount: "0", + }, + ExecutorResult: group.PROPOSAL_EXECUTOR_RESULT_NOT_RUN, + } + specs := map[string]struct { + req *group.MsgSubmitProposal + msgs []sdk.Msg + expProposal group.Proposal + expErr bool + expErrMsg string + postRun func(sdkCtx sdk.Context) + preRun func(msg []sdk.Msg) + }{ + "all good with minimal fields set": { + req: &group.MsgSubmitProposal{ + GroupPolicyAddress: accountAddr.String(), + Proposers: []string{addr2.String()}, + }, + expProposal: defaultProposal, + postRun: func(sdkCtx sdk.Context) {}, + }, + "all good with good msg payload": { + req: &group.MsgSubmitProposal{ + GroupPolicyAddress: accountAddr.String(), + Proposers: []string{addr2.String()}, + }, + msgs: []sdk.Msg{&banktypes.MsgSend{ + FromAddress: accountAddr.String(), + ToAddress: addr2.String(), + Amount: sdk.Coins{sdk.NewInt64Coin("token", 100)}, + }}, + expProposal: defaultProposal, + postRun: func(sdkCtx sdk.Context) {}, + }, + "metadata too long": { + req: &group.MsgSubmitProposal{ + GroupPolicyAddress: accountAddr.String(), + Proposers: []string{addr2.String()}, + Metadata: strings.Repeat("a", 256), + }, + expErr: true, + expErrMsg: "limit exceeded", + postRun: func(sdkCtx sdk.Context) {}, + }, + "group policy required": { + req: &group.MsgSubmitProposal{ + Proposers: []string{addr2.String()}, + }, + expErr: true, + expErrMsg: "unable to decode", + postRun: func(sdkCtx sdk.Context) {}, + }, + "existing group policy required": { + req: &group.MsgSubmitProposal{ + GroupPolicyAddress: addr1.String(), + Proposers: []string{addr2.String()}, + }, + expErr: true, + expErrMsg: "not found", + postRun: func(sdkCtx sdk.Context) {}, + }, + "decision policy threshold > total group weight": { + req: &group.MsgSubmitProposal{ + GroupPolicyAddress: bigThresholdAddr, + Proposers: []string{addr2.String()}, + }, + expErr: false, + expProposal: group.Proposal{ + GroupPolicyAddress: bigThresholdAddr, + Status: group.PROPOSAL_STATUS_SUBMITTED, + FinalTallyResult: group.DefaultTallyResult(), + ExecutorResult: group.PROPOSAL_EXECUTOR_RESULT_NOT_RUN, + }, + postRun: func(sdkCtx sdk.Context) {}, + }, + "only group members can create a proposal": { + req: &group.MsgSubmitProposal{ + GroupPolicyAddress: accountAddr.String(), + Proposers: []string{addr4.String()}, + }, + expErr: true, + expErrMsg: "not in group", + postRun: func(sdkCtx sdk.Context) {}, + }, + "all proposers must be in group": { + req: &group.MsgSubmitProposal{ + GroupPolicyAddress: accountAddr.String(), + Proposers: []string{addr2.String(), addr4.String()}, + }, + expErr: true, + expErrMsg: "not in group", + postRun: func(sdkCtx sdk.Context) {}, + }, + "admin that is not a group member can not create proposal": { + req: &group.MsgSubmitProposal{ + GroupPolicyAddress: accountAddr.String(), + Proposers: []string{addr1.String()}, + }, + expErr: true, + expErrMsg: "not in group", + postRun: func(sdkCtx sdk.Context) {}, + }, + "reject msgs that are not authz by group policy": { + req: &group.MsgSubmitProposal{ + GroupPolicyAddress: accountAddr.String(), + Proposers: []string{addr2.String()}, + }, + msgs: []sdk.Msg{&testdata.TestMsg{Signers: []string{addr1.String()}}}, + expErr: true, + expErrMsg: "msg does not have group policy authorization", + postRun: func(sdkCtx sdk.Context) {}, + }, + "with try exec": { + preRun: func(msgs []sdk.Msg) { + for i := 0; i < len(msgs); i++ { + s.bankKeeper.EXPECT().Send(gomock.Any(), msgs[i]).Return(nil, nil) + } + }, + req: &group.MsgSubmitProposal{ + GroupPolicyAddress: res.Address, + Proposers: []string{addr2.String()}, + Exec: group.Exec_EXEC_TRY, + }, + msgs: []sdk.Msg{msgSend}, + expProposal: group.Proposal{ + GroupPolicyAddress: res.Address, + Status: group.PROPOSAL_STATUS_ACCEPTED, + FinalTallyResult: group.TallyResult{ + YesCount: "2", + NoCount: "0", + AbstainCount: "0", + NoWithVetoCount: "0", + }, + ExecutorResult: group.PROPOSAL_EXECUTOR_RESULT_SUCCESS, + }, + postRun: func(sdkCtx sdk.Context) { + s.bankKeeper.EXPECT().GetAllBalances(sdkCtx, noMinExecPeriodPolicyAddr).Return(sdk.NewCoins(sdk.NewInt64Coin("test", 9900))) + s.bankKeeper.EXPECT().GetAllBalances(sdkCtx, addr2).Return(sdk.NewCoins(sdk.NewInt64Coin("test", 100))) + + fromBalances := s.bankKeeper.GetAllBalances(sdkCtx, noMinExecPeriodPolicyAddr) + s.Require().Contains(fromBalances, sdk.NewInt64Coin("test", 9900)) + toBalances := s.bankKeeper.GetAllBalances(sdkCtx, addr2) + s.Require().Contains(toBalances, sdk.NewInt64Coin("test", 100)) + }, + }, + "with try exec, not enough yes votes for proposal to pass": { + req: &group.MsgSubmitProposal{ + GroupPolicyAddress: res.Address, + Proposers: []string{addr5.String()}, + Exec: group.Exec_EXEC_TRY, + }, + msgs: []sdk.Msg{msgSend}, + expProposal: group.Proposal{ + GroupPolicyAddress: res.Address, + Status: group.PROPOSAL_STATUS_SUBMITTED, + FinalTallyResult: group.TallyResult{ + YesCount: "0", // Since tally doesn't pass Allow(), we consider the proposal not final + NoCount: "0", + AbstainCount: "0", + NoWithVetoCount: "0", + }, + ExecutorResult: group.PROPOSAL_EXECUTOR_RESULT_NOT_RUN, + }, + postRun: func(sdkCtx sdk.Context) {}, + }, + } + for msg, spec := range specs { + spec := spec + s.Run(msg, func() { + err := spec.req.SetMsgs(spec.msgs) + s.Require().NoError(err) + + if spec.preRun != nil { + spec.preRun(spec.msgs) + } + + res, err := s.groupKeeper.SubmitProposal(s.ctx, spec.req) + if spec.expErr { + s.Require().Error(err) + s.Require().Contains(err.Error(), spec.expErrMsg) + return + } + s.Require().NoError(err) + id := res.ProposalId + + if !(spec.expProposal.ExecutorResult == group.PROPOSAL_EXECUTOR_RESULT_SUCCESS) { + // then all data persisted + proposalRes, err := s.groupKeeper.Proposal(s.ctx, &group.QueryProposalRequest{ProposalId: id}) + s.Require().NoError(err) + proposal := proposalRes.Proposal + + s.Assert().Equal(spec.expProposal.GroupPolicyAddress, proposal.GroupPolicyAddress) + s.Assert().Equal(spec.req.Metadata, proposal.Metadata) + s.Assert().Equal(spec.req.Proposers, proposal.Proposers) + s.Assert().Equal(s.blockTime, proposal.SubmitTime) + s.Assert().Equal(uint64(1), proposal.GroupVersion) + s.Assert().Equal(uint64(1), proposal.GroupPolicyVersion) + s.Assert().Equal(spec.expProposal.Status, proposal.Status) + s.Assert().Equal(spec.expProposal.FinalTallyResult, proposal.FinalTallyResult) + s.Assert().Equal(spec.expProposal.ExecutorResult, proposal.ExecutorResult) + s.Assert().Equal(s.blockTime.Add(time.Second), proposal.VotingPeriodEnd) + + msgs, err := proposal.GetMsgs() + s.Assert().NoError(err) + if spec.msgs == nil { // then empty list is ok + s.Assert().Len(msgs, 0) + } else { + s.Assert().Equal(spec.msgs, msgs) + } + } + + spec.postRun(s.sdkCtx) + }) + } +} + +func (s *TestSuite) TestWithdrawProposal() { + addrs := s.addrs + addr2 := addrs[1] + addr5 := addrs[4] + + msgSend := &banktypes.MsgSend{ + FromAddress: s.groupPolicyAddr.String(), + ToAddress: addr2.String(), + Amount: sdk.Coins{sdk.NewInt64Coin("test", 100)}, + } + + proposers := []string{addr2.String()} + proposalID := submitProposal(s.ctx, s, []sdk.Msg{msgSend}, proposers) + + specs := map[string]struct { + preRun func(sdkCtx sdk.Context) uint64 + proposalID uint64 + admin string + expErrMsg string + }{ + "wrong admin": { + preRun: func(sdkCtx sdk.Context) uint64 { + return submitProposal(s.ctx, s, []sdk.Msg{msgSend}, proposers) + }, + admin: addr5.String(), + expErrMsg: "unauthorized", + }, + "wrong proposal id": { + preRun: func(sdkCtx sdk.Context) uint64 { + return 1111 + }, + admin: proposers[0], + expErrMsg: "not found", + }, + "happy case with proposer": { + preRun: func(sdkCtx sdk.Context) uint64 { + return submitProposal(s.ctx, s, []sdk.Msg{msgSend}, proposers) + }, + proposalID: proposalID, + admin: proposers[0], + }, + "already closed proposal": { + preRun: func(sdkCtx sdk.Context) uint64 { + pID := submitProposal(s.ctx, s, []sdk.Msg{msgSend}, proposers) + _, err := s.groupKeeper.WithdrawProposal(s.ctx, &group.MsgWithdrawProposal{ + ProposalId: pID, + Address: proposers[0], + }) + s.Require().NoError(err) + return pID + }, + proposalID: proposalID, + admin: proposers[0], + expErrMsg: "cannot withdraw a proposal with the status of PROPOSAL_STATUS_WITHDRAWN", + }, + "happy case with group admin address": { + preRun: func(sdkCtx sdk.Context) uint64 { + return submitProposal(s.ctx, s, []sdk.Msg{msgSend}, proposers) + }, + proposalID: proposalID, + admin: proposers[0], + }, + } + for msg, spec := range specs { + spec := spec + s.Run(msg, func() { + pID := spec.preRun(s.sdkCtx) + + _, err := s.groupKeeper.WithdrawProposal(s.ctx, &group.MsgWithdrawProposal{ + ProposalId: pID, + Address: spec.admin, + }) + + if spec.expErrMsg != "" { + s.Require().Error(err) + s.Require().Contains(err.Error(), spec.expErrMsg) + return + } + + s.Require().NoError(err) + resp, err := s.groupKeeper.Proposal(s.ctx, &group.QueryProposalRequest{ProposalId: pID}) + s.Require().NoError(err) + s.Require().Equal(resp.GetProposal().Status, group.PROPOSAL_STATUS_WITHDRAWN) + }) + } +} + +func (s *TestSuite) TestVote() { + addrs := s.addrs + addr1 := addrs[0] + addr2 := addrs[1] + addr3 := addrs[2] + addr4 := addrs[3] + addr5 := addrs[4] + members := []group.MemberRequest{ + {Address: addr4.String(), Weight: "1"}, + {Address: addr3.String(), Weight: "2"}, + } + + groupRes, err := s.groupKeeper.CreateGroup(s.ctx, &group.MsgCreateGroup{ + Admin: addr1.String(), + Members: members, + }) + s.Require().NoError(err) + myGroupID := groupRes.GroupId + + policy := group.NewThresholdDecisionPolicy( + "2", + time.Duration(2), + 0, + ) + policyReq := &group.MsgCreateGroupPolicy{ + Admin: addr1.String(), + GroupId: myGroupID, + } + err = policyReq.SetDecisionPolicy(policy) + s.Require().NoError(err) + + s.setNextAccount() + policyRes, err := s.groupKeeper.CreateGroupPolicy(s.ctx, policyReq) + s.Require().NoError(err) + accountAddr := policyRes.Address + // module account will be created and returned + addrbz, err := address.NewBech32Codec("cosmos").StringToBytes(accountAddr) + s.Require().NoError(err) + s.accountKeeper.EXPECT().StringToBytes(accountAddr).Return(addrbz, nil).AnyTimes() + groupPolicy, err := s.accountKeeper.StringToBytes(accountAddr) + s.Require().NoError(err) + s.Require().NotNil(groupPolicy) + + s.bankKeeper.EXPECT().SendCoinsFromModuleToAccount(s.sdkCtx, minttypes.ModuleName, groupPolicy, sdk.Coins{sdk.NewInt64Coin("test", 10000)}).Return(nil).AnyTimes() + s.Require().NoError(s.bankKeeper.SendCoinsFromModuleToAccount(s.sdkCtx, minttypes.ModuleName, groupPolicy, sdk.Coins{sdk.NewInt64Coin("test", 10000)})) + + req := &group.MsgSubmitProposal{ + GroupPolicyAddress: accountAddr, + Proposers: []string{addr4.String()}, + Messages: nil, + } + msg := &banktypes.MsgSend{ + FromAddress: accountAddr, + ToAddress: addr5.String(), + Amount: sdk.Coins{sdk.NewInt64Coin("test", 100)}, + } + err = req.SetMsgs([]sdk.Msg{msg}) + s.Require().NoError(err) + + proposalRes, err := s.groupKeeper.SubmitProposal(s.ctx, req) + s.Require().NoError(err) + myProposalID := proposalRes.ProposalId + + // proposals by group policy + proposalsRes, err := s.groupKeeper.ProposalsByGroupPolicy(s.ctx, &group.QueryProposalsByGroupPolicyRequest{ + Address: accountAddr, + }) + s.Require().NoError(err) + proposals := proposalsRes.Proposals + s.Require().Equal(len(proposals), 1) + s.Assert().Equal(req.GroupPolicyAddress, proposals[0].GroupPolicyAddress) + s.Assert().Equal(req.Metadata, proposals[0].Metadata) + s.Assert().Equal(req.Proposers, proposals[0].Proposers) + s.Assert().Equal(s.blockTime, proposals[0].SubmitTime) + s.Assert().Equal(uint64(1), proposals[0].GroupVersion) + s.Assert().Equal(uint64(1), proposals[0].GroupPolicyVersion) + s.Assert().Equal(group.PROPOSAL_STATUS_SUBMITTED, proposals[0].Status) + s.Assert().Equal(group.DefaultTallyResult(), proposals[0].FinalTallyResult) + + specs := map[string]struct { + srcCtx sdk.Context + expTallyResult group.TallyResult // expected after tallying + isFinal bool // is the tally result final? + req *group.MsgVote + doBefore func(ctx context.Context) + postRun func(sdkCtx sdk.Context) + expProposalStatus group.ProposalStatus // expected after tallying + expExecutorResult group.ProposalExecutorResult // expected after tallying + expErr bool + expErrMsg string + }{ + "vote yes": { + req: &group.MsgVote{ + ProposalId: myProposalID, + Voter: addr4.String(), + Option: group.VOTE_OPTION_YES, + }, + expTallyResult: group.TallyResult{ + YesCount: "1", + NoCount: "0", + AbstainCount: "0", + NoWithVetoCount: "0", + }, + expProposalStatus: group.PROPOSAL_STATUS_SUBMITTED, + expExecutorResult: group.PROPOSAL_EXECUTOR_RESULT_NOT_RUN, + postRun: func(sdkCtx sdk.Context) {}, + }, + "with try exec": { + req: &group.MsgVote{ + ProposalId: myProposalID, + Voter: addr3.String(), + Option: group.VOTE_OPTION_YES, + Exec: group.Exec_EXEC_TRY, + }, + expTallyResult: group.TallyResult{ + YesCount: "2", + NoCount: "0", + AbstainCount: "0", + NoWithVetoCount: "0", + }, + isFinal: true, + expProposalStatus: group.PROPOSAL_STATUS_ACCEPTED, + expExecutorResult: group.PROPOSAL_EXECUTOR_RESULT_SUCCESS, + doBefore: func(ctx context.Context) { + s.bankKeeper.EXPECT().Send(gomock.Any(), msg).Return(nil, nil) + }, + postRun: func(sdkCtx sdk.Context) { + s.bankKeeper.EXPECT().GetAllBalances(gomock.Any(), groupPolicy).Return(sdk.NewCoins(sdk.NewInt64Coin("test", 9900))) + s.bankKeeper.EXPECT().GetAllBalances(gomock.Any(), addr5).Return(sdk.NewCoins(sdk.NewInt64Coin("test", 100))) + + fromBalances := s.bankKeeper.GetAllBalances(sdkCtx, groupPolicy) + s.Require().Contains(fromBalances, sdk.NewInt64Coin("test", 9900)) + toBalances := s.bankKeeper.GetAllBalances(sdkCtx, addr5) + s.Require().Contains(toBalances, sdk.NewInt64Coin("test", 100)) + }, + }, + "with try exec, not enough yes votes for proposal to pass": { + req: &group.MsgVote{ + ProposalId: myProposalID, + Voter: addr4.String(), + Option: group.VOTE_OPTION_YES, + Exec: group.Exec_EXEC_TRY, + }, + expTallyResult: group.TallyResult{ + YesCount: "1", + NoCount: "0", + AbstainCount: "0", + NoWithVetoCount: "0", + }, + expProposalStatus: group.PROPOSAL_STATUS_SUBMITTED, + expExecutorResult: group.PROPOSAL_EXECUTOR_RESULT_NOT_RUN, + postRun: func(sdkCtx sdk.Context) {}, + }, + "vote no": { + req: &group.MsgVote{ + ProposalId: myProposalID, + Voter: addr4.String(), + Option: group.VOTE_OPTION_NO, + }, + expTallyResult: group.TallyResult{ + YesCount: "0", + NoCount: "1", + AbstainCount: "0", + NoWithVetoCount: "0", + }, + expProposalStatus: group.PROPOSAL_STATUS_SUBMITTED, + expExecutorResult: group.PROPOSAL_EXECUTOR_RESULT_NOT_RUN, + postRun: func(sdkCtx sdk.Context) {}, + }, + "vote abstain": { + req: &group.MsgVote{ + ProposalId: myProposalID, + Voter: addr4.String(), + Option: group.VOTE_OPTION_ABSTAIN, + }, + expTallyResult: group.TallyResult{ + YesCount: "0", + NoCount: "0", + AbstainCount: "1", + NoWithVetoCount: "0", + }, + expProposalStatus: group.PROPOSAL_STATUS_SUBMITTED, + expExecutorResult: group.PROPOSAL_EXECUTOR_RESULT_NOT_RUN, + postRun: func(sdkCtx sdk.Context) {}, + }, + "vote veto": { + req: &group.MsgVote{ + ProposalId: myProposalID, + Voter: addr4.String(), + Option: group.VOTE_OPTION_NO_WITH_VETO, + }, + expTallyResult: group.TallyResult{ + YesCount: "0", + NoCount: "0", + AbstainCount: "0", + NoWithVetoCount: "1", + }, + expProposalStatus: group.PROPOSAL_STATUS_SUBMITTED, + expExecutorResult: group.PROPOSAL_EXECUTOR_RESULT_NOT_RUN, + postRun: func(sdkCtx sdk.Context) {}, + }, + "apply decision policy early": { + req: &group.MsgVote{ + ProposalId: myProposalID, + Voter: addr3.String(), + Option: group.VOTE_OPTION_YES, + }, + expTallyResult: group.TallyResult{ + YesCount: "2", + NoCount: "0", + AbstainCount: "0", + NoWithVetoCount: "0", + }, + expProposalStatus: group.PROPOSAL_STATUS_ACCEPTED, + expExecutorResult: group.PROPOSAL_EXECUTOR_RESULT_NOT_RUN, + postRun: func(sdkCtx sdk.Context) {}, + }, + "reject new votes when final decision is made already": { + req: &group.MsgVote{ + ProposalId: myProposalID, + Voter: addr4.String(), + Option: group.VOTE_OPTION_YES, + }, + doBefore: func(ctx context.Context) { + _, err := s.groupKeeper.Vote(ctx, &group.MsgVote{ + ProposalId: myProposalID, + Voter: addr3.String(), + Option: group.VOTE_OPTION_NO_WITH_VETO, + Exec: 1, // Execute the proposal so that its status is final + }) + s.Require().NoError(err) + }, + expErr: true, + expErrMsg: "proposal not open for voting", + postRun: func(sdkCtx sdk.Context) {}, + }, + "metadata too long": { + req: &group.MsgVote{ + ProposalId: myProposalID, + Voter: addr4.String(), + Option: group.VOTE_OPTION_NO, + Metadata: strings.Repeat("a", 256), + }, + expErr: true, + expErrMsg: "metadata: limit exceeded", + postRun: func(sdkCtx sdk.Context) {}, + }, + "existing proposal required": { + req: &group.MsgVote{ + ProposalId: 999, + Voter: addr4.String(), + Option: group.VOTE_OPTION_NO, + }, + expErr: true, + expErrMsg: "load proposal: not found", + postRun: func(sdkCtx sdk.Context) {}, + }, + "empty vote option": { + req: &group.MsgVote{ + ProposalId: myProposalID, + Voter: addr4.String(), + }, + expErr: true, + expErrMsg: "vote option: value is empty", + postRun: func(sdkCtx sdk.Context) {}, + }, + "invalid vote option": { + req: &group.MsgVote{ + ProposalId: myProposalID, + Voter: addr4.String(), + Option: 5, + }, + expErr: true, + expErrMsg: "ote option: invalid value", + postRun: func(sdkCtx sdk.Context) {}, + }, + "voter must be in group": { + req: &group.MsgVote{ + ProposalId: myProposalID, + Voter: addr2.String(), + Option: group.VOTE_OPTION_NO, + }, + expErr: true, + expErrMsg: "not found", + postRun: func(sdkCtx sdk.Context) {}, + }, + "admin that is not a group member can not vote": { + req: &group.MsgVote{ + ProposalId: myProposalID, + Voter: addr1.String(), + Option: group.VOTE_OPTION_NO, + }, + expErr: true, + expErrMsg: "not found", + postRun: func(sdkCtx sdk.Context) {}, + }, + "on voting period end": { + req: &group.MsgVote{ + ProposalId: myProposalID, + Voter: addr4.String(), + Option: group.VOTE_OPTION_NO, + }, + srcCtx: s.sdkCtx.WithBlockTime(s.blockTime.Add(time.Second)), + expErr: true, + expErrMsg: "voting period has ended already: expired", + postRun: func(sdkCtx sdk.Context) {}, + }, + "vote closed already": { + req: &group.MsgVote{ + ProposalId: myProposalID, + Voter: addr4.String(), + Option: group.VOTE_OPTION_NO, + }, + doBefore: func(ctx context.Context) { + s.bankKeeper.EXPECT().Send(gomock.Any(), msg).Return(nil, nil) + + _, err := s.groupKeeper.Vote(ctx, &group.MsgVote{ + ProposalId: myProposalID, + Voter: addr3.String(), + Option: group.VOTE_OPTION_YES, + Exec: 1, // Execute to close the proposal. + }) + s.Require().NoError(err) + }, + expErr: true, + expErrMsg: "load proposal: not found", + postRun: func(sdkCtx sdk.Context) {}, + }, + "voted already": { + req: &group.MsgVote{ + ProposalId: myProposalID, + Voter: addr4.String(), + Option: group.VOTE_OPTION_NO, + }, + doBefore: func(ctx context.Context) { + _, err := s.groupKeeper.Vote(ctx, &group.MsgVote{ + ProposalId: myProposalID, + Voter: addr4.String(), + Option: group.VOTE_OPTION_YES, + }) + s.Require().NoError(err) + }, + expErr: true, + expErrMsg: "store vote: unique constraint violation", + postRun: func(sdkCtx sdk.Context) {}, + }, + } + for msg, spec := range specs { + spec := spec + s.Run(msg, func() { + sdkCtx := s.sdkCtx + if !spec.srcCtx.IsZero() { + sdkCtx = spec.srcCtx + } + sdkCtx, _ = sdkCtx.CacheContext() + if spec.doBefore != nil { + spec.doBefore(sdkCtx) + } + _, err := s.groupKeeper.Vote(sdkCtx, spec.req) + if spec.expErr { + s.Require().Error(err) + s.Require().Contains(err.Error(), spec.expErrMsg) + return + } + s.Require().NoError(err) + + if !(spec.expExecutorResult == group.PROPOSAL_EXECUTOR_RESULT_SUCCESS) { + // vote is stored and all data persisted + res, err := s.groupKeeper.VoteByProposalVoter(sdkCtx, &group.QueryVoteByProposalVoterRequest{ + ProposalId: spec.req.ProposalId, + Voter: spec.req.Voter, + }) + s.Require().NoError(err) + loaded := res.Vote + s.Assert().Equal(spec.req.ProposalId, loaded.ProposalId) + s.Assert().Equal(spec.req.Voter, loaded.Voter) + s.Assert().Equal(spec.req.Option, loaded.Option) + s.Assert().Equal(spec.req.Metadata, loaded.Metadata) + s.Assert().Equal(s.blockTime, loaded.SubmitTime) + + // query votes by proposal + votesByProposalRes, err := s.groupKeeper.VotesByProposal(sdkCtx, &group.QueryVotesByProposalRequest{ + ProposalId: spec.req.ProposalId, + }) + s.Require().NoError(err) + votesByProposal := votesByProposalRes.Votes + s.Require().Equal(1, len(votesByProposal)) + vote := votesByProposal[0] + s.Assert().Equal(spec.req.ProposalId, vote.ProposalId) + s.Assert().Equal(spec.req.Voter, vote.Voter) + s.Assert().Equal(spec.req.Option, vote.Option) + s.Assert().Equal(spec.req.Metadata, vote.Metadata) + s.Assert().Equal(s.blockTime, vote.SubmitTime) + + // query votes by voter + voter := spec.req.Voter + votesByVoterRes, err := s.groupKeeper.VotesByVoter(sdkCtx, &group.QueryVotesByVoterRequest{ + Voter: voter, + }) + s.Require().NoError(err) + votesByVoter := votesByVoterRes.Votes + s.Require().Equal(1, len(votesByVoter)) + s.Assert().Equal(spec.req.ProposalId, votesByVoter[0].ProposalId) + s.Assert().Equal(voter, votesByVoter[0].Voter) + s.Assert().Equal(spec.req.Option, votesByVoter[0].Option) + s.Assert().Equal(spec.req.Metadata, votesByVoter[0].Metadata) + s.Assert().Equal(s.blockTime, votesByVoter[0].SubmitTime) + + proposalRes, err := s.groupKeeper.Proposal(sdkCtx, &group.QueryProposalRequest{ + ProposalId: spec.req.ProposalId, + }) + s.Require().NoError(err) + + proposal := proposalRes.Proposal + if spec.isFinal { + s.Assert().Equal(spec.expTallyResult, proposal.FinalTallyResult) + s.Assert().Equal(spec.expProposalStatus, proposal.Status) + s.Assert().Equal(spec.expExecutorResult, proposal.ExecutorResult) + } else { + s.Assert().Equal(group.DefaultTallyResult(), proposal.FinalTallyResult) // Make sure proposal isn't mutated. + + // do a round of tallying + tallyResult, err := s.groupKeeper.Tally(sdkCtx, *proposal, myGroupID) + s.Require().NoError(err) + + s.Assert().Equal(spec.expTallyResult, tallyResult) + } + } + + spec.postRun(sdkCtx) + }) + } + + s.T().Log("test tally result should not take into account the member who left the group") + members = []group.MemberRequest{ + {Address: addr2.String(), Weight: "3"}, + {Address: addr3.String(), Weight: "2"}, + {Address: addr4.String(), Weight: "1"}, + } + reqCreate := &group.MsgCreateGroupWithPolicy{ + Admin: addr1.String(), + Members: members, + GroupMetadata: "metadata", + } + + policy = group.NewThresholdDecisionPolicy( + "4", + time.Duration(10), + 0, + ) + s.Require().NoError(reqCreate.SetDecisionPolicy(policy)) + s.setNextAccount() + + result, err := s.groupKeeper.CreateGroupWithPolicy(s.ctx, reqCreate) + s.Require().NoError(err) + s.Require().NotNil(result) + + policyAddr := result.GroupPolicyAddress + groupID := result.GroupId + reqProposal := &group.MsgSubmitProposal{ + GroupPolicyAddress: policyAddr, + Proposers: []string{addr4.String()}, + } + s.Require().NoError(reqProposal.SetMsgs([]sdk.Msg{&banktypes.MsgSend{ + FromAddress: policyAddr, + ToAddress: addr5.String(), + Amount: sdk.Coins{sdk.NewInt64Coin("test", 100)}, + }})) + + resSubmitProposal, err := s.groupKeeper.SubmitProposal(s.ctx, reqProposal) + s.Require().NoError(err) + s.Require().NotNil(resSubmitProposal) + proposalID := resSubmitProposal.ProposalId + + for _, voter := range []string{addr4.String(), addr3.String(), addr2.String()} { + _, err := s.groupKeeper.Vote(s.ctx, + &group.MsgVote{ProposalId: proposalID, Voter: voter, Option: group.VOTE_OPTION_YES}, + ) + s.Require().NoError(err) + } + + qProposals, err := s.groupKeeper.Proposal(s.ctx, &group.QueryProposalRequest{ + ProposalId: proposalID, + }) + s.Require().NoError(err) + + tallyResult, err := s.groupKeeper.Tally(s.sdkCtx, *qProposals.Proposal, groupID) + s.Require().NoError(err) + + _, err = s.groupKeeper.LeaveGroup(s.ctx, &group.MsgLeaveGroup{Address: addr4.String(), GroupId: groupID}) + s.Require().NoError(err) + + tallyResult1, err := s.groupKeeper.Tally(s.sdkCtx, *qProposals.Proposal, groupID) + s.Require().NoError(err) + s.Require().NotEqual(tallyResult.String(), tallyResult1.String()) +} + +func (s *TestSuite) TestExecProposal() { + addrs := s.addrs + addr1 := addrs[0] + addr2 := addrs[1] + + msgSend1 := &banktypes.MsgSend{ + FromAddress: s.groupPolicyAddr.String(), + ToAddress: addr2.String(), + Amount: sdk.Coins{sdk.NewInt64Coin("test", 100)}, + } + msgSend2 := &banktypes.MsgSend{ + FromAddress: s.groupPolicyAddr.String(), + ToAddress: addr2.String(), + Amount: sdk.Coins{sdk.NewInt64Coin("test", 10001)}, + } + proposers := []string{addr2.String()} + + specs := map[string]struct { + srcBlockTime time.Time + setupProposal func(ctx context.Context) uint64 + expErr bool + expErrMsg string + expProposalStatus group.ProposalStatus + expExecutorResult group.ProposalExecutorResult + expBalance bool + expFromBalances sdk.Coin + expToBalances sdk.Coin + }{ + "proposal executed when accepted": { + setupProposal: func(ctx context.Context) uint64 { + s.bankKeeper.EXPECT().Send(gomock.Any(), msgSend1).Return(nil, nil) + msgs := []sdk.Msg{msgSend1} + return submitProposalAndVote(ctx, s, msgs, proposers, group.VOTE_OPTION_YES) + }, + srcBlockTime: s.blockTime.Add(minExecutionPeriod), // After min execution period end + expProposalStatus: group.PROPOSAL_STATUS_ACCEPTED, + expExecutorResult: group.PROPOSAL_EXECUTOR_RESULT_SUCCESS, + expBalance: true, + expFromBalances: sdk.NewInt64Coin("test", 9900), + expToBalances: sdk.NewInt64Coin("test", 100), + }, + "proposal with multiple messages executed when accepted": { + setupProposal: func(ctx context.Context) uint64 { + msgs := []sdk.Msg{msgSend1, msgSend1} + s.bankKeeper.EXPECT().Send(gomock.Any(), msgSend1).Return(nil, nil).MaxTimes(2) + + return submitProposalAndVote(ctx, s, msgs, proposers, group.VOTE_OPTION_YES) + }, + srcBlockTime: s.blockTime.Add(minExecutionPeriod), // After min execution period end + expProposalStatus: group.PROPOSAL_STATUS_ACCEPTED, + expExecutorResult: group.PROPOSAL_EXECUTOR_RESULT_SUCCESS, + expBalance: true, + expFromBalances: sdk.NewInt64Coin("test", 9800), + expToBalances: sdk.NewInt64Coin("test", 200), + }, + "proposal not executed when rejected": { + setupProposal: func(ctx context.Context) uint64 { + msgs := []sdk.Msg{msgSend1} + return submitProposalAndVote(ctx, s, msgs, proposers, group.VOTE_OPTION_NO) + }, + srcBlockTime: s.blockTime.Add(minExecutionPeriod), // After min execution period end + expProposalStatus: group.PROPOSAL_STATUS_REJECTED, + expExecutorResult: group.PROPOSAL_EXECUTOR_RESULT_NOT_RUN, + }, + "open proposal must not fail": { + setupProposal: func(ctx context.Context) uint64 { + return submitProposal(ctx, s, []sdk.Msg{msgSend1}, proposers) + }, + expProposalStatus: group.PROPOSAL_STATUS_SUBMITTED, + expExecutorResult: group.PROPOSAL_EXECUTOR_RESULT_NOT_RUN, + }, + "invalid proposal id": { + setupProposal: func(ctx context.Context) uint64 { + return 0 + }, + expErr: true, + expErrMsg: "proposal id: value is empty", + }, + "existing proposal required": { + setupProposal: func(ctx context.Context) uint64 { + return 9999 + }, + expErr: true, + expErrMsg: "load proposal: not found", + }, + "Decision policy also applied on exactly voting period end": { + setupProposal: func(ctx context.Context) uint64 { + msgs := []sdk.Msg{msgSend1} + return submitProposalAndVote(ctx, s, msgs, proposers, group.VOTE_OPTION_NO) + }, + srcBlockTime: s.blockTime.Add(time.Second), // Voting period is 1s + expProposalStatus: group.PROPOSAL_STATUS_REJECTED, + expExecutorResult: group.PROPOSAL_EXECUTOR_RESULT_NOT_RUN, + }, + "Decision policy also applied after voting period end": { + setupProposal: func(ctx context.Context) uint64 { + msgs := []sdk.Msg{msgSend1} + return submitProposalAndVote(ctx, s, msgs, proposers, group.VOTE_OPTION_NO) + }, + srcBlockTime: s.blockTime.Add(time.Second).Add(time.Millisecond), // Voting period is 1s + expProposalStatus: group.PROPOSAL_STATUS_REJECTED, + expExecutorResult: group.PROPOSAL_EXECUTOR_RESULT_NOT_RUN, + }, + "exec proposal before MinExecutionPeriod should fail": { + setupProposal: func(ctx context.Context) uint64 { + msgs := []sdk.Msg{msgSend1} + return submitProposalAndVote(ctx, s, msgs, proposers, group.VOTE_OPTION_YES) + }, + srcBlockTime: s.blockTime.Add(4 * time.Second), // min execution date is 5s later after s.blockTime + expProposalStatus: group.PROPOSAL_STATUS_ACCEPTED, + expExecutorResult: group.PROPOSAL_EXECUTOR_RESULT_FAILURE, // Because MinExecutionPeriod has not passed + }, + "exec proposal at exactly MinExecutionPeriod should pass": { + setupProposal: func(ctx context.Context) uint64 { + msgs := []sdk.Msg{msgSend1} + s.bankKeeper.EXPECT().Send(gomock.Any(), msgSend1).Return(nil, nil) + return submitProposalAndVote(ctx, s, msgs, proposers, group.VOTE_OPTION_YES) + }, + srcBlockTime: s.blockTime.Add(5 * time.Second), // min execution date is 5s later after s.blockTime + expProposalStatus: group.PROPOSAL_STATUS_ACCEPTED, + expExecutorResult: group.PROPOSAL_EXECUTOR_RESULT_SUCCESS, + }, + "prevent double execution when successful": { + setupProposal: func(ctx context.Context) uint64 { + myProposalID := submitProposalAndVote(ctx, s, []sdk.Msg{msgSend1}, proposers, group.VOTE_OPTION_YES) + s.bankKeeper.EXPECT().Send(gomock.Any(), msgSend1).Return(nil, nil) + + // Wait after min execution period end before Exec + sdkCtx := sdk.UnwrapSDKContext(ctx) + sdkCtx = sdkCtx.WithBlockTime(sdkCtx.BlockTime().Add(minExecutionPeriod)) // MinExecutionPeriod is 5s + _, err := s.groupKeeper.Exec(sdkCtx, &group.MsgExec{Executor: addr1.String(), ProposalId: myProposalID}) + s.Require().NoError(err) + return myProposalID + }, + srcBlockTime: s.blockTime.Add(minExecutionPeriod), // After min execution period end + expErr: true, // since proposal is pruned after a successful MsgExec + expErrMsg: "load proposal: not found", + expProposalStatus: group.PROPOSAL_STATUS_ACCEPTED, + expExecutorResult: group.PROPOSAL_EXECUTOR_RESULT_SUCCESS, + expBalance: true, + expFromBalances: sdk.NewInt64Coin("test", 9900), + expToBalances: sdk.NewInt64Coin("test", 100), + }, + "rollback all msg updates on failure": { + setupProposal: func(ctx context.Context) uint64 { + msgs := []sdk.Msg{msgSend1, msgSend2} + s.bankKeeper.EXPECT().Send(gomock.Any(), msgSend1).Return(nil, nil) + s.bankKeeper.EXPECT().Send(gomock.Any(), msgSend2).Return(nil, fmt.Errorf("error")) + + return submitProposalAndVote(ctx, s, msgs, proposers, group.VOTE_OPTION_YES) + }, + srcBlockTime: s.blockTime.Add(minExecutionPeriod), // After min execution period end + expProposalStatus: group.PROPOSAL_STATUS_ACCEPTED, + expExecutorResult: group.PROPOSAL_EXECUTOR_RESULT_FAILURE, + }, + "executable when failed before": { + setupProposal: func(ctx context.Context) uint64 { + msgs := []sdk.Msg{msgSend2} + myProposalID := submitProposalAndVote(ctx, s, msgs, proposers, group.VOTE_OPTION_YES) + + // Wait after min execution period end before Exec + sdkCtx := sdk.UnwrapSDKContext(ctx) + sdkCtx = sdkCtx.WithBlockTime(sdkCtx.BlockTime().Add(minExecutionPeriod)) // MinExecutionPeriod is 5s + s.bankKeeper.EXPECT().Send(gomock.Any(), msgSend2).Return(nil, fmt.Errorf("error")) + _, err := s.groupKeeper.Exec(sdkCtx, &group.MsgExec{Executor: addr1.String(), ProposalId: myProposalID}) + s.bankKeeper.EXPECT().Send(gomock.Any(), msgSend2).Return(nil, nil) + + s.Require().NoError(err) + s.Require().NoError(s.bankKeeper.SendCoinsFromModuleToAccount(s.sdkCtx, minttypes.ModuleName, s.groupPolicyAddr, sdk.Coins{sdk.NewInt64Coin("test", 10000)})) + + return myProposalID + }, + srcBlockTime: s.blockTime.Add(minExecutionPeriod), // After min execution period end + expProposalStatus: group.PROPOSAL_STATUS_ACCEPTED, + expExecutorResult: group.PROPOSAL_EXECUTOR_RESULT_SUCCESS, + }, + } + for msg, spec := range specs { + spec := spec + s.Run(msg, func() { + sdkCtx, _ := s.sdkCtx.CacheContext() + proposalID := spec.setupProposal(sdkCtx) + + if !spec.srcBlockTime.IsZero() { + sdkCtx = sdkCtx.WithBlockTime(spec.srcBlockTime) + } + + _, err := s.groupKeeper.Exec(sdkCtx, &group.MsgExec{Executor: addr1.String(), ProposalId: proposalID}) + if spec.expErr { + s.Require().Error(err) + s.Require().Contains(err.Error(), spec.expErrMsg) + return + } + s.Require().NoError(err) + + if !(spec.expExecutorResult == group.PROPOSAL_EXECUTOR_RESULT_SUCCESS) { + + // and proposal is updated + res, err := s.groupKeeper.Proposal(sdkCtx, &group.QueryProposalRequest{ProposalId: proposalID}) + s.Require().NoError(err) + proposal := res.Proposal + + exp := group.ProposalStatus_name[int32(spec.expProposalStatus)] + got := group.ProposalStatus_name[int32(proposal.Status)] + s.Assert().Equal(exp, got) + + exp = group.ProposalExecutorResult_name[int32(spec.expExecutorResult)] + got = group.ProposalExecutorResult_name[int32(proposal.ExecutorResult)] + s.Assert().Equal(exp, got) + } + + if spec.expBalance { + s.bankKeeper.EXPECT().GetAllBalances(sdkCtx, s.groupPolicyAddr).Return(sdk.Coins{spec.expFromBalances}) + s.bankKeeper.EXPECT().GetAllBalances(sdkCtx, addr2).Return(sdk.Coins{spec.expToBalances}) + + fromBalances := s.bankKeeper.GetAllBalances(sdkCtx, s.groupPolicyAddr) + s.Require().Contains(fromBalances, spec.expFromBalances) + toBalances := s.bankKeeper.GetAllBalances(sdkCtx, addr2) + s.Require().Contains(toBalances, spec.expToBalances) + } + }) + } +} + +func (s *TestSuite) TestExecPrunedProposalsAndVotes() { + addrs := s.addrs + addr1 := addrs[0] + addr2 := addrs[1] + + proposers := []string{addr2.String()} + specs := map[string]struct { + srcBlockTime time.Time + setupProposal func(ctx context.Context) uint64 + expErr bool + expErrMsg string + expExecutorResult group.ProposalExecutorResult + }{ + "proposal pruned after executor result success": { + setupProposal: func(ctx context.Context) uint64 { + msgSend1 := &banktypes.MsgSend{ + FromAddress: s.groupPolicyAddr.String(), + ToAddress: addr2.String(), + Amount: sdk.Coins{sdk.NewInt64Coin("test", 101)}, + } + msgs := []sdk.Msg{msgSend1} + s.bankKeeper.EXPECT().Send(gomock.Any(), msgSend1).Return(nil, nil) + return submitProposalAndVote(ctx, s, msgs, proposers, group.VOTE_OPTION_YES) + }, + expErrMsg: "load proposal: not found", + expExecutorResult: group.PROPOSAL_EXECUTOR_RESULT_SUCCESS, + }, + "proposal with multiple messages pruned when executed with result success": { + setupProposal: func(ctx context.Context) uint64 { + msgSend1 := &banktypes.MsgSend{ + FromAddress: s.groupPolicyAddr.String(), + ToAddress: addr2.String(), + Amount: sdk.Coins{sdk.NewInt64Coin("test", 102)}, + } + s.bankKeeper.EXPECT().Send(gomock.Any(), msgSend1).Return(nil, nil).MaxTimes(2) + + msgs := []sdk.Msg{msgSend1, msgSend1} + return submitProposalAndVote(ctx, s, msgs, proposers, group.VOTE_OPTION_YES) + }, + expErrMsg: "load proposal: not found", + expExecutorResult: group.PROPOSAL_EXECUTOR_RESULT_SUCCESS, + }, + "proposal not pruned when not executed and rejected": { + setupProposal: func(ctx context.Context) uint64 { + msgSend1 := &banktypes.MsgSend{ + FromAddress: s.groupPolicyAddr.String(), + ToAddress: addr2.String(), + Amount: sdk.Coins{sdk.NewInt64Coin("test", 103)}, + } + msgs := []sdk.Msg{msgSend1} + return submitProposalAndVote(ctx, s, msgs, proposers, group.VOTE_OPTION_NO) + }, + expExecutorResult: group.PROPOSAL_EXECUTOR_RESULT_NOT_RUN, + }, + "open proposal is not pruned which must not fail ": { + setupProposal: func(ctx context.Context) uint64 { + msgSend1 := &banktypes.MsgSend{ + FromAddress: s.groupPolicyAddr.String(), + ToAddress: addr2.String(), + Amount: sdk.Coins{sdk.NewInt64Coin("test", 104)}, + } + return submitProposal(ctx, s, []sdk.Msg{msgSend1}, proposers) + }, + expExecutorResult: group.PROPOSAL_EXECUTOR_RESULT_NOT_RUN, + }, + "proposal not pruned with group modified before tally": { + setupProposal: func(ctx context.Context) uint64 { + msgSend1 := &banktypes.MsgSend{ + FromAddress: s.groupPolicyAddr.String(), + ToAddress: addr2.String(), + Amount: sdk.Coins{sdk.NewInt64Coin("test", 105)}, + } + myProposalID := submitProposal(ctx, s, []sdk.Msg{msgSend1}, proposers) + + // then modify group + _, err := s.groupKeeper.UpdateGroupMetadata(ctx, &group.MsgUpdateGroupMetadata{ + Admin: addr1.String(), + GroupId: s.groupID, + }) + s.Require().NoError(err) + return myProposalID + }, + expExecutorResult: group.PROPOSAL_EXECUTOR_RESULT_NOT_RUN, + }, + "proposal not pruned with group policy modified before tally": { + setupProposal: func(ctx context.Context) uint64 { + msgSend1 := &banktypes.MsgSend{ + FromAddress: s.groupPolicyAddr.String(), + ToAddress: addr2.String(), + Amount: sdk.Coins{sdk.NewInt64Coin("test", 106)}, + } + + myProposalID := submitProposal(ctx, s, []sdk.Msg{msgSend1}, proposers) + _, err := s.groupKeeper.UpdateGroupPolicyMetadata(ctx, &group.MsgUpdateGroupPolicyMetadata{ + Admin: addr1.String(), + GroupPolicyAddress: s.groupPolicyAddr.String(), + }) + s.Require().NoError(err) + return myProposalID + }, + expErr: true, // since proposal status will be `aborted` when group policy is modified + expErrMsg: "not possible to exec with proposal status", + expExecutorResult: group.PROPOSAL_EXECUTOR_RESULT_NOT_RUN, + }, + "proposal exists when rollback all msg updates on failure": { + setupProposal: func(ctx context.Context) uint64 { + msgSend1 := &banktypes.MsgSend{ + FromAddress: s.groupPolicyAddr.String(), + ToAddress: addr2.String(), + Amount: sdk.Coins{sdk.NewInt64Coin("test", 107)}, + } + + msgSend2 := &banktypes.MsgSend{ + FromAddress: s.groupPolicyAddr.String(), + ToAddress: addr2.String(), + Amount: sdk.Coins{sdk.NewInt64Coin("test", 10002)}, + } + + msgs := []sdk.Msg{msgSend1, msgSend2} + s.bankKeeper.EXPECT().Send(gomock.Any(), msgSend1).Return(nil, fmt.Errorf("error")) + + return submitProposalAndVote(ctx, s, msgs, proposers, group.VOTE_OPTION_YES) + }, + expExecutorResult: group.PROPOSAL_EXECUTOR_RESULT_FAILURE, + }, + "pruned when proposal is executable when failed before": { + setupProposal: func(ctx context.Context) uint64 { + msgSend2 := &banktypes.MsgSend{ + FromAddress: s.groupPolicyAddr.String(), + ToAddress: addr2.String(), + Amount: sdk.Coins{sdk.NewInt64Coin("test", 10003)}, + } + + msgs := []sdk.Msg{msgSend2} + + myProposalID := submitProposalAndVote(ctx, s, msgs, proposers, group.VOTE_OPTION_YES) + + s.bankKeeper.EXPECT().Send(gomock.Any(), msgSend2).Return(nil, fmt.Errorf("error")) + + // Wait for min execution period end + sdkCtx := sdk.UnwrapSDKContext(ctx) + sdkCtx = sdkCtx.WithBlockTime(sdkCtx.BlockTime().Add(minExecutionPeriod)) + _, err := s.groupKeeper.Exec(sdkCtx, &group.MsgExec{Executor: addr1.String(), ProposalId: myProposalID}) + s.bankKeeper.EXPECT().Send(gomock.Any(), msgSend2).Return(nil, nil) + + s.Require().NoError(err) + return myProposalID + }, + expErrMsg: "load proposal: not found", + expExecutorResult: group.PROPOSAL_EXECUTOR_RESULT_SUCCESS, + }, + } + for msg, spec := range specs { + spec := spec + s.Run(msg, func() { + sdkCtx, _ := s.sdkCtx.CacheContext() + proposalID := spec.setupProposal(sdkCtx) + + if !spec.srcBlockTime.IsZero() { + sdkCtx = sdkCtx.WithBlockTime(spec.srcBlockTime) + } + + // Wait for min execution period end + sdkCtx = sdkCtx.WithBlockTime(sdkCtx.BlockTime().Add(minExecutionPeriod)) + _, err := s.groupKeeper.Exec(sdkCtx, &group.MsgExec{Executor: addr1.String(), ProposalId: proposalID}) + if spec.expErr { + s.Require().Error(err) + s.Require().Contains(err.Error(), spec.expErrMsg) + return + } + s.Require().NoError(err) + + if spec.expExecutorResult == group.PROPOSAL_EXECUTOR_RESULT_SUCCESS { + // Make sure proposal is deleted from state + _, err := s.groupKeeper.Proposal(sdkCtx, &group.QueryProposalRequest{ProposalId: proposalID}) + s.Require().Contains(err.Error(), spec.expErrMsg) + res, err := s.groupKeeper.VotesByProposal(sdkCtx, &group.QueryVotesByProposalRequest{ProposalId: proposalID}) + s.Require().NoError(err) + s.Require().Empty(res.GetVotes()) + + } else { + // Check that proposal and votes exists + res, err := s.groupKeeper.Proposal(sdkCtx, &group.QueryProposalRequest{ProposalId: proposalID}) + s.Require().NoError(err) + _, err = s.groupKeeper.VotesByProposal(sdkCtx, &group.QueryVotesByProposalRequest{ProposalId: res.Proposal.Id}) + s.Require().NoError(err) + s.Require().Equal("", spec.expErrMsg) + + exp := group.ProposalExecutorResult_name[int32(spec.expExecutorResult)] + got := group.ProposalExecutorResult_name[int32(res.Proposal.ExecutorResult)] + s.Assert().Equal(exp, got) + } + }) + } +} + +func (s *TestSuite) TestLeaveGroup() { + addrs := simtestutil.CreateIncrementalAccounts(7) + + admin1 := addrs[0] + member1 := addrs[1] + member2 := addrs[2] + member3 := addrs[3] + member4 := addrs[4] + admin2 := addrs[5] + admin3 := addrs[6] + + for _, addr := range addrs { + s.accountKeeper.EXPECT().StringToBytes(addr.String()).Return(addr.Bytes(), nil).AnyTimes() + s.accountKeeper.EXPECT().BytesToString(addr).Return(addr.String(), nil).AnyTimes() + } + + members := []group.MemberRequest{ + { + Address: member1.String(), + Weight: "1", + Metadata: "metadata", + }, + { + Address: member2.String(), + Weight: "2", + Metadata: "metadata", + }, + { + Address: member3.String(), + Weight: "3", + Metadata: "metadata", + }, + } + policy := group.NewThresholdDecisionPolicy( + "3", + time.Hour, + time.Hour, + ) + s.setNextAccount() + _, groupID1 := s.createGroupAndGroupPolicy(admin1, members, policy) + + members = []group.MemberRequest{ + { + Address: member1.String(), + Weight: "1", + Metadata: "metadata", + }, + } + + s.setNextAccount() + _, groupID2 := s.createGroupAndGroupPolicy(admin2, members, nil) + + members = []group.MemberRequest{ + { + Address: member1.String(), + Weight: "1", + Metadata: "metadata", + }, + { + Address: member2.String(), + Weight: "2", + Metadata: "metadata", + }, + } + policy = &group.PercentageDecisionPolicy{ + Percentage: "0.5", + Windows: &group.DecisionPolicyWindows{VotingPeriod: time.Hour}, + } + + s.setNextAccount() + + _, groupID3 := s.createGroupAndGroupPolicy(admin3, members, policy) + testCases := []struct { + name string + req *group.MsgLeaveGroup + expErr bool + expErrMsg string + expMembersSize int + memberWeight math.Dec + }{ + { + "group not found", + &group.MsgLeaveGroup{ + GroupId: 100000, + Address: member1.String(), + }, + true, + "group: not found", + 0, + math.NewDecFromInt64(0), + }, + { + "member address invalid", + &group.MsgLeaveGroup{ + GroupId: groupID1, + Address: "invalid", + }, + true, + "unable to decode", + 0, + math.NewDecFromInt64(0), + }, + { + "member not part of group", + &group.MsgLeaveGroup{ + GroupId: groupID1, + Address: member4.String(), + }, + true, + "not part of group", + 0, + math.NewDecFromInt64(0), + }, + { + "valid testcase: decision policy is not present (and group total weight can be 0)", + &group.MsgLeaveGroup{ + GroupId: groupID2, + Address: member1.String(), + }, + false, + "", + 0, + math.NewDecFromInt64(1), + }, + { + "valid testcase: threshold decision policy", + &group.MsgLeaveGroup{ + GroupId: groupID1, + Address: member3.String(), + }, + false, + "", + 2, + math.NewDecFromInt64(3), + }, + { + "valid request: can leave group policy threshold more than group weight", + &group.MsgLeaveGroup{ + GroupId: groupID1, + Address: member2.String(), + }, + false, + "", + 1, + math.NewDecFromInt64(2), + }, + { + "valid request: can leave group (percentage decision policy)", + &group.MsgLeaveGroup{ + GroupId: groupID3, + Address: member2.String(), + }, + false, + "", + 1, + math.NewDecFromInt64(2), + }, + } + + for _, tc := range testCases { + s.Run(tc.name, func() { + var groupWeight1 math.Dec + if !tc.expErr { + groupRes, err := s.groupKeeper.GroupInfo(s.ctx, &group.QueryGroupInfoRequest{GroupId: tc.req.GroupId}) + s.Require().NoError(err) + groupWeight1, err = math.NewNonNegativeDecFromString(groupRes.Info.TotalWeight) + s.Require().NoError(err) + } + + res, err := s.groupKeeper.LeaveGroup(s.ctx, tc.req) + if tc.expErr { + s.Require().Error(err) + s.Require().Contains(err.Error(), tc.expErrMsg) + } else { + s.Require().NoError(err) + s.Require().NotNil(res) + res, err := s.groupKeeper.GroupMembers(s.ctx, &group.QueryGroupMembersRequest{ + GroupId: tc.req.GroupId, + }) + s.Require().NoError(err) + s.Require().Len(res.Members, tc.expMembersSize) + + groupRes, err := s.groupKeeper.GroupInfo(s.ctx, &group.QueryGroupInfoRequest{GroupId: tc.req.GroupId}) + s.Require().NoError(err) + groupWeight2, err := math.NewNonNegativeDecFromString(groupRes.Info.TotalWeight) + s.Require().NoError(err) + + rWeight, err := groupWeight1.Sub(tc.memberWeight) + s.Require().NoError(err) + s.Require().Equal(rWeight.Cmp(groupWeight2), 0) + } + }) + } +} diff --git a/x/group/migrations/v2/migrate_test.go b/x/group/migrations/v2/migrate_test.go index 20902ebdde7f..be7243eaa24a 100644 --- a/x/group/migrations/v2/migrate_test.go +++ b/x/group/migrations/v2/migrate_test.go @@ -8,6 +8,7 @@ import ( storetypes "cosmossdk.io/store/types" "github.com/cosmos/cosmos-sdk/codec" + "github.com/cosmos/cosmos-sdk/runtime" "github.com/cosmos/cosmos-sdk/testutil" sdk "github.com/cosmos/cosmos-sdk/types" moduletestutil "github.com/cosmos/cosmos-sdk/types/module/testutil" @@ -78,7 +79,7 @@ func createGroupPolicies(ctx sdk.Context, storeKey storetypes.StoreKey, cdc code // createOldPolicyAccount re-creates the group policy account using a module account func createOldPolicyAccount(ctx sdk.Context, storeKey storetypes.StoreKey, cdc codec.Codec) group.AccountKeeper { - accountKeeper := authkeeper.NewAccountKeeper(cdc, storeKey, authtypes.ProtoBaseAccount, nil, sdk.Bech32MainPrefix, accountAddr.String()) + accountKeeper := authkeeper.NewAccountKeeper(cdc, runtime.NewKVStoreService(storeKey.(*storetypes.KVStoreKey)), authtypes.ProtoBaseAccount, nil, sdk.Bech32MainPrefix, accountAddr.String()) for _, policyAddr := range policies { acc := accountKeeper.NewAccount(ctx, &authtypes.ModuleAccount{ BaseAccount: &authtypes.BaseAccount{ diff --git a/x/group/module/abci_test.go b/x/group/module/abci_test.go index f4d006f375c4..c669fb3b4654 100644 --- a/x/group/module/abci_test.go +++ b/x/group/module/abci_test.go @@ -5,8 +5,11 @@ import ( "testing" "time" + "cosmossdk.io/core/address" + cmtproto "github.com/cometbft/cometbft/proto/tendermint/types" cmttime "github.com/cometbft/cometbft/types/time" + codecaddress "github.com/cosmos/cosmos-sdk/codec/address" codectypes "github.com/cosmos/cosmos-sdk/codec/types" "github.com/cosmos/cosmos-sdk/runtime" simtestutil "github.com/cosmos/cosmos-sdk/testutil/sims" @@ -32,6 +35,8 @@ type IntegrationTestSuite struct { bankKeeper bankkeeper.Keeper stakingKeeper *stakingkeeper.Keeper interfaceRegistry codectypes.InterfaceRegistry + + addressCodec address.Codec } func TestIntegrationTestSuite(t *testing.T) { @@ -53,7 +58,10 @@ func (s *IntegrationTestSuite) SetupTest() { ctx = ctx.WithBlockHeader(cmtproto.Header{Time: cmttime.Now()}) s.ctx = ctx + s.addrs = simtestutil.AddTestAddrsIncremental(s.bankKeeper, s.stakingKeeper, ctx, 4, sdk.NewInt(30000000)) + + s.addressCodec = codecaddress.NewBech32Codec("cosmos") } func (s *IntegrationTestSuite) TestEndBlockerPruning() { @@ -62,13 +70,16 @@ func (s *IntegrationTestSuite) TestEndBlockerPruning() { addr2 := s.addrs[1] addr3 := s.addrs[2] + addr1st, err := s.addressCodec.BytesToString(addr1) + s.Require().NoError(err) + // Initial group, group policy and balance setup members := []group.MemberRequest{ - {Address: addr1.String(), Weight: "1"}, {Address: addr2.String(), Weight: "2"}, + {Address: addr1st, Weight: "1"}, {Address: addr2.String(), Weight: "2"}, } groupRes, err := s.groupKeeper.CreateGroup(ctx, &group.MsgCreateGroup{ - Admin: addr1.String(), + Admin: addr1st, Members: members, }) s.Require().NoError(err) @@ -114,23 +125,23 @@ func (s *IntegrationTestSuite) TestEndBlockerPruning() { policyRes2, err := s.groupKeeper.CreateGroupPolicy(ctx, policyReq2) s.Require().NoError(err) - groupPolicyAddr, err := sdk.AccAddressFromBech32(policyRes.Address) + groupPolicyAddr, err := s.addressCodec.StringToBytes(policyRes.Address) s.Require().NoError(err) s.Require().NoError(testutil.FundAccount(s.bankKeeper, ctx, groupPolicyAddr, sdk.Coins{sdk.NewInt64Coin("test", 10000)})) - groupPolicyAddr2, err := sdk.AccAddressFromBech32(policyRes2.Address) + groupPolicyAddr2, err := s.addressCodec.StringToBytes(policyRes2.Address) s.Require().NoError(err) s.Require().NoError(testutil.FundAccount(s.bankKeeper, ctx, groupPolicyAddr2, sdk.Coins{sdk.NewInt64Coin("test", 10000)})) votingPeriod := policy.GetVotingPeriod() msgSend1 := &banktypes.MsgSend{ - FromAddress: groupPolicyAddr.String(), + FromAddress: policyRes.Address, ToAddress: addr2.String(), Amount: sdk.Coins{sdk.NewInt64Coin("test", 100)}, } msgSend2 := &banktypes.MsgSend{ - FromAddress: groupPolicyAddr2.String(), + FromAddress: policyRes2.Address, ToAddress: addr2.String(), Amount: sdk.Coins{sdk.NewInt64Coin("test", 100)}, } @@ -213,7 +224,7 @@ func (s *IntegrationTestSuite) TestEndBlockerPruning() { s.Require().NoError(err) _, err = s.groupKeeper.UpdateGroupPolicyMetadata(ctx, &group.MsgUpdateGroupPolicyMetadata{ Admin: addr1.String(), - GroupPolicyAddress: groupPolicyAddr.String(), + GroupPolicyAddress: policyRes.Address, }) s.Require().NoError(err) _, err = s.groupKeeper.Exec(ctx, &group.MsgExec{Executor: addr3.String(), ProposalId: pID}) @@ -279,7 +290,7 @@ func (s *IntegrationTestSuite) TestEndBlockerPruning() { policy := group.NewThresholdDecisionPolicy("3", time.Second, 0) msg := &group.MsgUpdateGroupPolicyDecisionPolicy{ Admin: s.addrs[1].String(), - GroupPolicyAddress: groupPolicyAddr2.String(), + GroupPolicyAddress: policyRes2.Address, } err = msg.SetDecisionPolicy(policy) s.Require().NoError(err) @@ -301,7 +312,7 @@ func (s *IntegrationTestSuite) TestEndBlockerPruning() { policy := group.NewThresholdDecisionPolicy("3", time.Second, 0) msg := &group.MsgUpdateGroupPolicyDecisionPolicy{ Admin: s.addrs[1].String(), - GroupPolicyAddress: groupPolicyAddr2.String(), + GroupPolicyAddress: policyRes2.Address, } err = msg.SetDecisionPolicy(policy) s.Require().NoError(err) @@ -389,13 +400,13 @@ func (s *IntegrationTestSuite) TestEndBlockerTallying() { policyRes, err := s.groupKeeper.CreateGroupPolicy(ctx, policyReq) s.Require().NoError(err) - groupPolicyAddr, err := sdk.AccAddressFromBech32(policyRes.Address) + groupPolicyAddr, err := s.addressCodec.StringToBytes(policyRes.Address) s.Require().NoError(err) votingPeriod := policy.GetVotingPeriod() msgSend := &banktypes.MsgSend{ - FromAddress: groupPolicyAddr.String(), + FromAddress: policyRes.Address, ToAddress: addrs[3].String(), Amount: sdk.Coins{sdk.NewInt64Coin("test", 100)}, } diff --git a/x/group/module/module.go b/x/group/module/module.go index e95536e70e8d..f86389b53b9b 100644 --- a/x/group/module/module.go +++ b/x/group/module/module.go @@ -10,6 +10,7 @@ import ( "github.com/spf13/cobra" modulev1 "cosmossdk.io/api/cosmos/group/module/v1" + "cosmossdk.io/core/address" "cosmossdk.io/core/appmodule" "cosmossdk.io/depinject" @@ -47,7 +48,7 @@ type AppModule struct { // NewAppModule creates a new AppModule object func NewAppModule(cdc codec.Codec, keeper keeper.Keeper, ak group.AccountKeeper, bk group.BankKeeper, registry cdctypes.InterfaceRegistry) AppModule { return AppModule{ - AppModuleBasic: AppModuleBasic{cdc: cdc}, + AppModuleBasic: AppModuleBasic{cdc: cdc, ac: ak}, keeper: keeper, bankKeeper: bk, accKeeper: ak, @@ -68,6 +69,7 @@ func (am AppModule) IsAppModule() {} type AppModuleBasic struct { cdc codec.Codec + ac address.Codec } // Name returns the group module's name. @@ -97,7 +99,7 @@ func (a AppModuleBasic) GetQueryCmd() *cobra.Command { // GetTxCmd returns the transaction commands for the group module func (a AppModuleBasic) GetTxCmd() *cobra.Command { - return cli.TxCmd(a.Name()) + return cli.TxCmd(a.Name(), a.ac) } // RegisterGRPCGatewayRoutes registers the gRPC Gateway routes for the group module. @@ -180,7 +182,7 @@ func (am AppModule) RegisterStoreDecoder(sdr simtypes.StoreDecoderRegistry) { func (am AppModule) WeightedOperations(simState module.SimulationState) []simtypes.WeightedOperation { return simulation.WeightedOperations( am.registry, - simState.AppParams, simState.Cdc, + simState.AppParams, simState.Cdc, simState.TxConfig, am.accKeeper, am.bankKeeper, am.keeper, am.cdc, ) } diff --git a/x/group/msgs.go b/x/group/msgs.go index 426105c11393..ed00d5cc471b 100644 --- a/x/group/msgs.go +++ b/x/group/msgs.go @@ -11,8 +11,6 @@ import ( "github.com/cosmos/cosmos-sdk/types/tx" "github.com/cosmos/cosmos-sdk/x/auth/migrations/legacytx" "github.com/cosmos/cosmos-sdk/x/group/codec" - errors "github.com/cosmos/cosmos-sdk/x/group/errors" - "github.com/cosmos/cosmos-sdk/x/group/internal/math" ) var ( @@ -32,34 +30,6 @@ func (m MsgCreateGroup) GetSigners() []sdk.AccAddress { return []sdk.AccAddress{admin} } -// ValidateBasic does a sanity check on the provided data -func (m MsgCreateGroup) ValidateBasic() error { - _, err := sdk.AccAddressFromBech32(m.Admin) - if err != nil { - return errorsmod.Wrap(err, "admin") - } - - return strictValidateMembers(m.Members) -} - -// ValidateBasic performs stateless validation on a group member, such as -// making sure the address is well-formed, and the weight is non-negative. -// Note: in state, a member's weight MUST be positive. However, in some Msgs, -// it's possible to set a zero member weight, for example in -// MsgUpdateGroupMembers to denote that we're removing a member. -func (m MemberRequest) ValidateBasic() error { - _, err := sdk.AccAddressFromBech32(m.Address) - if err != nil { - return errorsmod.Wrap(err, "address") - } - - if _, err := math.NewNonNegativeDecFromString(m.Weight); err != nil { - return errorsmod.Wrap(err, "weight") - } - - return nil -} - var ( _ sdk.Msg = &MsgUpdateGroupAdmin{} _ legacytx.LegacyMsg = &MsgUpdateGroupAdmin{} @@ -77,28 +47,6 @@ func (m MsgUpdateGroupAdmin) GetSigners() []sdk.AccAddress { return []sdk.AccAddress{admin} } -// ValidateBasic does a sanity check on the provided data. -func (m MsgUpdateGroupAdmin) ValidateBasic() error { - if m.GroupId == 0 { - return errorsmod.Wrap(errors.ErrEmpty, "group id") - } - - admin, err := sdk.AccAddressFromBech32(m.Admin) - if err != nil { - return errorsmod.Wrap(err, "admin") - } - - newAdmin, err := sdk.AccAddressFromBech32(m.NewAdmin) - if err != nil { - return errorsmod.Wrap(err, "new admin") - } - - if admin.Equals(newAdmin) { - return errorsmod.Wrap(errors.ErrInvalid, "new and old admin are the same") - } - return nil -} - // GetGroupID gets the group id of the MsgUpdateGroupAdmin. func (m *MsgUpdateGroupAdmin) GetGroupID() uint64 { return m.GroupId @@ -121,19 +69,6 @@ func (m MsgUpdateGroupMetadata) GetSigners() []sdk.AccAddress { return []sdk.AccAddress{admin} } -// ValidateBasic does a sanity check on the provided data -func (m MsgUpdateGroupMetadata) ValidateBasic() error { - if m.GroupId == 0 { - return errorsmod.Wrap(errors.ErrEmpty, "group id") - } - _, err := sdk.AccAddressFromBech32(m.Admin) - if err != nil { - return errorsmod.Wrap(err, "admin") - } - - return nil -} - // GetGroupID gets the group id of the MsgUpdateGroupMetadata. func (m *MsgUpdateGroupMetadata) GetGroupID() uint64 { return m.GroupId @@ -158,26 +93,6 @@ func (m MsgUpdateGroupMembers) GetSigners() []sdk.AccAddress { return []sdk.AccAddress{admin} } -// ValidateBasic does a sanity check on the provided data -func (m MsgUpdateGroupMembers) ValidateBasic() error { - if m.GroupId == 0 { - return errorsmod.Wrap(errors.ErrEmpty, "group id") - } - _, err := sdk.AccAddressFromBech32(m.Admin) - if err != nil { - return errorsmod.Wrap(err, "admin") - } - - if len(m.MemberUpdates) == 0 { - return errorsmod.Wrap(errors.ErrEmpty, "member updates") - } - members := MemberRequests{Members: m.MemberUpdates} - if err := members.ValidateBasic(); err != nil { - return errorsmod.Wrap(err, "members") - } - return nil -} - // GetGroupID gets the group id of the MsgUpdateGroupMembers. func (m *MsgUpdateGroupMembers) GetGroupID() uint64 { return m.GroupId @@ -191,7 +106,7 @@ var ( ) // NewMsgCreateGroupWithPolicy creates a new MsgCreateGroupWithPolicy. -func NewMsgCreateGroupWithPolicy(admin string, members []MemberRequest, groupMetadata string, groupPolicyMetadata string, groupPolicyAsAdmin bool, decisionPolicy DecisionPolicy) (*MsgCreateGroupWithPolicy, error) { +func NewMsgCreateGroupWithPolicy(admin string, members []MemberRequest, groupMetadata, groupPolicyMetadata string, groupPolicyAsAdmin bool, decisionPolicy DecisionPolicy) (*MsgCreateGroupWithPolicy, error) { m := &MsgCreateGroupWithPolicy{ Admin: admin, Members: members, @@ -242,23 +157,6 @@ func (m MsgCreateGroupWithPolicy) GetSigners() []sdk.AccAddress { return []sdk.AccAddress{admin} } -// ValidateBasic does a sanity check on the provided data -func (m MsgCreateGroupWithPolicy) ValidateBasic() error { - _, err := sdk.AccAddressFromBech32(m.Admin) - if err != nil { - return errorsmod.Wrap(err, "admin") - } - policy, err := m.GetDecisionPolicy() - if err != nil { - return errorsmod.Wrap(err, "decision policy") - } - if err := policy.ValidateBasic(); err != nil { - return errorsmod.Wrap(err, "decision policy") - } - - return strictValidateMembers(m.Members) -} - var ( _ sdk.Msg = &MsgCreateGroupPolicy{} _ legacytx.LegacyMsg = &MsgCreateGroupPolicy{} @@ -275,27 +173,6 @@ func (m MsgCreateGroupPolicy) GetSigners() []sdk.AccAddress { return []sdk.AccAddress{admin} } -// ValidateBasic does a sanity check on the provided data -func (m MsgCreateGroupPolicy) ValidateBasic() error { - _, err := sdk.AccAddressFromBech32(m.Admin) - if err != nil { - return errorsmod.Wrap(err, "admin") - } - if m.GroupId == 0 { - return errorsmod.Wrap(errors.ErrEmpty, "group id") - } - - policy, err := m.GetDecisionPolicy() - if err != nil { - return errorsmod.Wrap(err, "decision policy") - } - - if err := policy.ValidateBasic(); err != nil { - return errorsmod.Wrap(err, "decision policy") - } - return nil -} - var ( _ sdk.Msg = &MsgUpdateGroupPolicyAdmin{} _ legacytx.LegacyMsg = &MsgUpdateGroupPolicyAdmin{} @@ -313,29 +190,6 @@ func (m MsgUpdateGroupPolicyAdmin) GetSigners() []sdk.AccAddress { return []sdk.AccAddress{admin} } -// ValidateBasic does a sanity check on the provided data -func (m MsgUpdateGroupPolicyAdmin) ValidateBasic() error { - admin, err := sdk.AccAddressFromBech32(m.Admin) - if err != nil { - return errorsmod.Wrap(err, "admin") - } - - newAdmin, err := sdk.AccAddressFromBech32(m.NewAdmin) - if err != nil { - return errorsmod.Wrap(err, "new admin") - } - - _, err = sdk.AccAddressFromBech32(m.GroupPolicyAddress) - if err != nil { - return errorsmod.Wrap(err, "group policy") - } - - if admin.Equals(newAdmin) { - return errorsmod.Wrap(errors.ErrInvalid, "new and old admin are same") - } - return nil -} - var ( _ sdk.Msg = &MsgUpdateGroupPolicyDecisionPolicy{} _ legacytx.LegacyMsg = &MsgUpdateGroupPolicyDecisionPolicy{} @@ -344,7 +198,7 @@ var ( ) // NewMsgUpdateGroupPolicyDecisionPolicy creates a new MsgUpdateGroupPolicyDecisionPolicy. -func NewMsgUpdateGroupPolicyDecisionPolicy(admin sdk.AccAddress, address sdk.AccAddress, decisionPolicy DecisionPolicy) (*MsgUpdateGroupPolicyDecisionPolicy, error) { +func NewMsgUpdateGroupPolicyDecisionPolicy(admin, address sdk.AccAddress, decisionPolicy DecisionPolicy) (*MsgUpdateGroupPolicyDecisionPolicy, error) { m := &MsgUpdateGroupPolicyDecisionPolicy{ Admin: admin.String(), GroupPolicyAddress: address.String(), @@ -382,30 +236,6 @@ func (m MsgUpdateGroupPolicyDecisionPolicy) GetSigners() []sdk.AccAddress { return []sdk.AccAddress{admin} } -// ValidateBasic does a sanity check on the provided data -func (m MsgUpdateGroupPolicyDecisionPolicy) ValidateBasic() error { - _, err := sdk.AccAddressFromBech32(m.Admin) - if err != nil { - return errorsmod.Wrap(err, "admin") - } - - _, err = sdk.AccAddressFromBech32(m.GroupPolicyAddress) - if err != nil { - return errorsmod.Wrap(err, "group policy") - } - - policy, err := m.GetDecisionPolicy() - if err != nil { - return errorsmod.Wrap(err, "decision policy") - } - - if err := policy.ValidateBasic(); err != nil { - return errorsmod.Wrap(err, "decision policy") - } - - return nil -} - // GetDecisionPolicy gets the decision policy of MsgUpdateGroupPolicyDecisionPolicy. func (m *MsgUpdateGroupPolicyDecisionPolicy) GetDecisionPolicy() (DecisionPolicy, error) { decisionPolicy, ok := m.DecisionPolicy.GetCachedValue().(DecisionPolicy) @@ -439,21 +269,6 @@ func (m MsgUpdateGroupPolicyMetadata) GetSigners() []sdk.AccAddress { return []sdk.AccAddress{admin} } -// ValidateBasic does a sanity check on the provided data -func (m MsgUpdateGroupPolicyMetadata) ValidateBasic() error { - _, err := sdk.AccAddressFromBech32(m.Admin) - if err != nil { - return errorsmod.Wrap(err, "admin") - } - - _, err = sdk.AccAddressFromBech32(m.GroupPolicyAddress) - if err != nil { - return errorsmod.Wrap(err, "group policy") - } - - return nil -} - var ( _ sdk.Msg = &MsgCreateGroupPolicy{} _ legacytx.LegacyMsg = &MsgCreateGroupPolicy{} @@ -552,49 +367,6 @@ func (m MsgSubmitProposal) GetSigners() []sdk.AccAddress { return addrs } -// ValidateBasic does a sanity check on the provided proposal, such as -// verifying proposer addresses, and performing ValidateBasic on each -// individual `sdk.Msg`. -func (m MsgSubmitProposal) ValidateBasic() error { - _, err := sdk.AccAddressFromBech32(m.GroupPolicyAddress) - if err != nil { - return errorsmod.Wrap(err, "group policy") - } - - if m.Title == "" { - return errorsmod.Wrap(errors.ErrEmpty, "title") - } - - if m.Summary == "" { - return errorsmod.Wrap(errors.ErrEmpty, "summary") - } - - if len(m.Proposers) == 0 { - return errorsmod.Wrap(errors.ErrEmpty, "proposers") - } - - addrs, err := m.getProposerAccAddresses() - if err != nil { - return errorsmod.Wrap(err, "group proposers") - } - - if err := accAddresses(addrs).ValidateBasic(); err != nil { - return errorsmod.Wrap(err, "proposers") - } - - msgs, err := m.GetMsgs() - if err != nil { - return err - } - - for i, msg := range msgs { - if err := msg.ValidateBasic(); err != nil { - return errorsmod.Wrapf(err, "msg %d", i) - } - } - return nil -} - // getProposerAccAddresses returns the proposers as `[]sdk.AccAddress`. func (m *MsgSubmitProposal) getProposerAccAddresses() ([]sdk.AccAddress, error) { addrs := make([]sdk.AccAddress, len(m.Proposers)) @@ -646,20 +418,6 @@ func (m MsgWithdrawProposal) GetSigners() []sdk.AccAddress { return []sdk.AccAddress{admin} } -// ValidateBasic does a sanity check on the provided data -func (m MsgWithdrawProposal) ValidateBasic() error { - _, err := sdk.AccAddressFromBech32(m.Address) - if err != nil { - return errorsmod.Wrap(err, "admin") - } - - if m.ProposalId == 0 { - return errorsmod.Wrap(errors.ErrEmpty, "proposal id") - } - - return nil -} - var ( _ sdk.Msg = &MsgVote{} _ legacytx.LegacyMsg = &MsgVote{} @@ -677,24 +435,6 @@ func (m MsgVote) GetSigners() []sdk.AccAddress { return []sdk.AccAddress{addr} } -// ValidateBasic does a sanity check on the provided data -func (m MsgVote) ValidateBasic() error { - _, err := sdk.AccAddressFromBech32(m.Voter) - if err != nil { - return errorsmod.Wrap(err, "voter") - } - if m.ProposalId == 0 { - return errorsmod.Wrap(errors.ErrEmpty, "proposal id") - } - if m.Option == VOTE_OPTION_UNSPECIFIED { - return errorsmod.Wrap(errors.ErrEmpty, "vote option") - } - if _, ok := VoteOption_name[int32(m.Option)]; !ok { - return errorsmod.Wrap(errors.ErrInvalid, "vote option") - } - return nil -} - var ( _ sdk.Msg = &MsgExec{} _ legacytx.LegacyMsg = &MsgExec{} @@ -712,18 +452,6 @@ func (m MsgExec) GetSigners() []sdk.AccAddress { return []sdk.AccAddress{signer} } -// ValidateBasic does a sanity check on the provided data -func (m MsgExec) ValidateBasic() error { - _, err := sdk.AccAddressFromBech32(m.Executor) - if err != nil { - return errorsmod.Wrap(err, "signer") - } - if m.ProposalId == 0 { - return errorsmod.Wrap(errors.ErrEmpty, "proposal id") - } - return nil -} - var ( _ sdk.Msg = &MsgLeaveGroup{} _ legacytx.LegacyMsg = &MsgLeaveGroup{} @@ -740,34 +468,3 @@ func (m MsgLeaveGroup) GetSigners() []sdk.AccAddress { return []sdk.AccAddress{signer} } - -// ValidateBasic does a sanity check on the provided data -func (m MsgLeaveGroup) ValidateBasic() error { - _, err := sdk.AccAddressFromBech32(m.Address) - if err != nil { - return errorsmod.Wrap(err, "group member") - } - - if m.GroupId == 0 { - return errorsmod.Wrap(errors.ErrEmpty, "group-id") - } - return nil -} - -// strictValidateMembers performs ValidateBasic on Members, but also checks -// that all members weights are positive (whereas `Members{members}.ValidateBasic()` -// only checks that they are non-negative. -func strictValidateMembers(members []MemberRequest) error { - err := MemberRequests{members}.ValidateBasic() - if err != nil { - return err - } - - for _, m := range members { - if _, err := math.NewPositiveDecFromString(m.Weight); err != nil { - return errorsmod.Wrap(err, "weight") - } - } - - return nil -} diff --git a/x/group/msgs_test.go b/x/group/msgs_test.go deleted file mode 100644 index acfdeb5b6f9f..000000000000 --- a/x/group/msgs_test.go +++ /dev/null @@ -1,1232 +0,0 @@ -package group_test - -import ( - "fmt" - "testing" - "time" - - "github.com/stretchr/testify/require" - - sdk "github.com/cosmos/cosmos-sdk/types" - "github.com/cosmos/cosmos-sdk/types/module/testutil" - banktypes "github.com/cosmos/cosmos-sdk/x/bank/types" - "github.com/cosmos/cosmos-sdk/x/group" - "github.com/cosmos/cosmos-sdk/x/group/module" -) - -var ( - admin = sdk.AccAddress("admin") - member1 = sdk.AccAddress("member1") - member2 = sdk.AccAddress("member2") - member3 = sdk.AccAddress("member3") - member4 = sdk.AccAddress("member4") - member5 = sdk.AccAddress("member5") -) - -func TestMsgCreateGroup(t *testing.T) { - testCases := []struct { - name string - msg *group.MsgCreateGroup - expErr bool - errMsg string - }{ - { - "invalid admin address", - &group.MsgCreateGroup{ - Admin: "admin", - }, - true, - "admin: decoding bech32 failed", - }, - { - "invalid member address", - &group.MsgCreateGroup{ - Admin: admin.String(), - Members: []group.MemberRequest{ - { - Address: "invalid address", - }, - }, - }, - true, - "address: decoding bech32 failed", - }, - { - "negitive member's weight not allowed", - &group.MsgCreateGroup{ - Admin: admin.String(), - Members: []group.MemberRequest{ - { - Address: member1.String(), - Weight: "-1", - }, - }, - }, - true, - "expected a non-negative decimal", - }, - { - "zero member's weight not allowed", - &group.MsgCreateGroup{ - Admin: admin.String(), - Members: []group.MemberRequest{ - { - Address: member1.String(), - Weight: "0", - }, - }, - }, - true, - "expected a positive decimal", - }, - { - "duplicate member not allowed", - &group.MsgCreateGroup{ - Admin: admin.String(), - Members: []group.MemberRequest{ - { - Address: member1.String(), - Weight: "1", - Metadata: "metadata", - }, - { - Address: member1.String(), - Weight: "1", - Metadata: "metadata", - }, - }, - }, - true, - "duplicate value", - }, - { - "valid test case with single member", - &group.MsgCreateGroup{ - Admin: admin.String(), - Members: []group.MemberRequest{ - { - Address: member1.String(), - Weight: "1", - Metadata: "metadata", - }, - }, - }, - false, - "", - }, - { - "minimum fields", - &group.MsgCreateGroup{ - Admin: admin.String(), - Members: []group.MemberRequest{}, - }, - false, - "", - }, - { - "valid test case with multiple members", - &group.MsgCreateGroup{ - Admin: admin.String(), - Members: []group.MemberRequest{ - { - Address: member1.String(), - Weight: "1", - Metadata: "metadata", - }, - { - Address: member2.String(), - Weight: "1", - Metadata: "metadata", - }, - }, - }, - false, - "", - }, - } - - for _, tc := range testCases { - t.Run(tc.name, func(t *testing.T) { - err := tc.msg.ValidateBasic() - if tc.expErr { - require.Error(t, err) - require.Contains(t, err.Error(), tc.errMsg) - } else { - require.NoError(t, err) - require.Equal(t, sdk.MsgTypeURL(tc.msg), sdk.MsgTypeURL(&group.MsgCreateGroup{})) - } - }) - } -} - -func TestMsgUpdateGroupAdmin(t *testing.T) { - testCases := []struct { - name string - msg *group.MsgUpdateGroupAdmin - expErr bool - errMsg string - }{ - { - "empty group id", - &group.MsgUpdateGroupAdmin{ - Admin: admin.String(), - NewAdmin: member1.String(), - }, - true, - "group id: value is empty", - }, - { - "admin: invalid bech32 address", - &group.MsgUpdateGroupAdmin{ - GroupId: 1, - Admin: "admin", - }, - true, - "admin: decoding bech32 failed", - }, - { - "new admin: invalid bech32 address", - &group.MsgUpdateGroupAdmin{ - GroupId: 1, - Admin: admin.String(), - NewAdmin: "new-admin", - }, - true, - "new admin: decoding bech32 failed", - }, - { - "admin & new admin is same", - &group.MsgUpdateGroupAdmin{ - GroupId: 1, - Admin: admin.String(), - NewAdmin: admin.String(), - }, - true, - "new and old admin are the same", - }, - { - "valid case", - &group.MsgUpdateGroupAdmin{ - GroupId: 1, - Admin: admin.String(), - NewAdmin: member1.String(), - }, - false, - "", - }, - } - - for _, tc := range testCases { - t.Run(tc.name, func(t *testing.T) { - err := tc.msg.ValidateBasic() - if tc.expErr { - require.Error(t, err) - require.Contains(t, err.Error(), tc.errMsg) - } else { - require.NoError(t, err) - require.Equal(t, sdk.MsgTypeURL(tc.msg), sdk.MsgTypeURL(&group.MsgUpdateGroupAdmin{})) - } - }) - } -} - -func TestMsgUpdateGroupMetadata(t *testing.T) { - testCases := []struct { - name string - msg *group.MsgUpdateGroupMetadata - expErr bool - errMsg string - }{ - { - "empty group id", - &group.MsgUpdateGroupMetadata{ - Admin: admin.String(), - }, - true, - "group id: value is empty", - }, - { - "admin: invalid bech32 address", - &group.MsgUpdateGroupMetadata{ - GroupId: 1, - Admin: "admin", - }, - true, - "admin: decoding bech32 failed", - }, - { - "valid test", - &group.MsgUpdateGroupMetadata{ - GroupId: 1, - Admin: admin.String(), - Metadata: "metadata", - }, - false, - "", - }, - } - - for _, tc := range testCases { - t.Run(tc.name, func(t *testing.T) { - err := tc.msg.ValidateBasic() - if tc.expErr { - require.Error(t, err) - require.Contains(t, err.Error(), tc.errMsg) - } else { - require.NoError(t, err) - require.Equal(t, sdk.MsgTypeURL(tc.msg), sdk.MsgTypeURL(&group.MsgUpdateGroupMetadata{})) - } - }) - } -} - -func TestMsgUpdateGroupMembers(t *testing.T) { - testCases := []struct { - name string - msg *group.MsgUpdateGroupMembers - expErr bool - errMsg string - }{ - { - "empty group id", - &group.MsgUpdateGroupMembers{}, - true, - "group id: value is empty", - }, - { - "admin: invalid bech32 address", - &group.MsgUpdateGroupMembers{ - GroupId: 1, - Admin: "admin", - }, - true, - "admin: decoding bech32 failed", - }, - { - "empty member list", - &group.MsgUpdateGroupMembers{ - GroupId: 1, - Admin: admin.String(), - MemberUpdates: []group.MemberRequest{}, - }, - true, - "member updates: value is empty", - }, - { - "valid test", - &group.MsgUpdateGroupMembers{ - GroupId: 1, - Admin: admin.String(), - MemberUpdates: []group.MemberRequest{ - { - Address: member1.String(), - Weight: "1", - Metadata: "metadata", - }, - }, - }, - false, - "", - }, - { - "valid test with zero weight", - &group.MsgUpdateGroupMembers{ - GroupId: 1, - Admin: admin.String(), - MemberUpdates: []group.MemberRequest{ - { - Address: member1.String(), - Weight: "0", - Metadata: "metadata", - }, - }, - }, - false, - "", - }, - } - - for _, tc := range testCases { - t.Run(tc.name, func(t *testing.T) { - err := tc.msg.ValidateBasic() - if tc.expErr { - require.Error(t, err) - require.Contains(t, err.Error(), tc.errMsg) - } else { - require.NoError(t, err) - require.Equal(t, sdk.MsgTypeURL(tc.msg), sdk.MsgTypeURL(&group.MsgUpdateGroupMembers{})) - } - }) - } -} - -func TestMsgCreateGroupWithPolicy(t *testing.T) { - testCases := []struct { - name string - msg func() *group.MsgCreateGroupWithPolicy - expErr bool - errMsg string - }{ - { - "invalid admin address", - func() *group.MsgCreateGroupWithPolicy { - admin := "admin" - policy := group.NewThresholdDecisionPolicy("1", time.Second, 0) - members := []group.MemberRequest{ - { - Address: member1.String(), - Weight: "1", - Metadata: "metadata", - }, - } - req, err := group.NewMsgCreateGroupWithPolicy(admin, members, "group_metadata", "group_policy_metadata", false, policy) - require.NoError(t, err) - return req - }, - true, - "admin: decoding bech32 failed", - }, - { - "invalid member address", - func() *group.MsgCreateGroupWithPolicy { - policy := group.NewThresholdDecisionPolicy("1", time.Second, 0) - members := []group.MemberRequest{ - { - Address: "invalid_address", - Weight: "1", - Metadata: "metadata", - }, - } - req, err := group.NewMsgCreateGroupWithPolicy(admin.String(), members, "group_metadata", "group_policy_metadata", false, policy) - require.NoError(t, err) - return req - }, - true, - "address: decoding bech32 failed", - }, - { - "negative member's weight not allowed", - func() *group.MsgCreateGroupWithPolicy { - policy := group.NewThresholdDecisionPolicy("1", time.Second, 0) - members := []group.MemberRequest{ - { - Address: member1.String(), - Weight: "-1", - Metadata: "metadata", - }, - } - req, err := group.NewMsgCreateGroupWithPolicy(admin.String(), members, "group_metadata", "group_policy_metadata", false, policy) - require.NoError(t, err) - return req - }, - true, - "expected a non-negative decimal", - }, - { - "zero member's weight not allowed", - func() *group.MsgCreateGroupWithPolicy { - policy := group.NewThresholdDecisionPolicy("1", time.Second, 0) - members := []group.MemberRequest{ - { - Address: member1.String(), - Weight: "0", - Metadata: "metadata", - }, - } - req, err := group.NewMsgCreateGroupWithPolicy(admin.String(), members, "group_metadata", "group_policy_metadata", false, policy) - require.NoError(t, err) - return req - }, - true, - "expected a positive decimal", - }, - { - "duplicate member not allowed", - func() *group.MsgCreateGroupWithPolicy { - policy := group.NewThresholdDecisionPolicy("1", time.Second, 0) - members := []group.MemberRequest{ - { - Address: member1.String(), - Weight: "1", - Metadata: "metadata", - }, - { - Address: member1.String(), - Weight: "1", - Metadata: "metadata", - }, - } - req, err := group.NewMsgCreateGroupWithPolicy(admin.String(), members, "group_metadata", "group_policy_metadata", false, policy) - require.NoError(t, err) - return req - }, - true, - "duplicate value", - }, - { - "invalid threshold policy", - func() *group.MsgCreateGroupWithPolicy { - policy := group.NewThresholdDecisionPolicy("-1", time.Second, 0) - members := []group.MemberRequest{ - { - Address: member1.String(), - Weight: "1", - Metadata: "metadata", - }, - } - req, err := group.NewMsgCreateGroupWithPolicy(admin.String(), members, "group_metadata", "group_policy_metadata", false, policy) - require.NoError(t, err) - return req - }, - true, - "expected a positive decimal", - }, - { - "valid test case with single member", - func() *group.MsgCreateGroupWithPolicy { - policy := group.NewThresholdDecisionPolicy("1", time.Second, 0) - members := []group.MemberRequest{ - { - Address: member1.String(), - Weight: "1", - Metadata: "metadata", - }, - } - req, err := group.NewMsgCreateGroupWithPolicy(admin.String(), members, "group_metadata", "group_policy_metadata", false, policy) - require.NoError(t, err) - return req - }, - false, - "", - }, - { - "valid test case with multiple members", - func() *group.MsgCreateGroupWithPolicy { - policy := group.NewThresholdDecisionPolicy("1", time.Second, 0) - members := []group.MemberRequest{ - { - Address: member1.String(), - Weight: "1", - Metadata: "metadata", - }, - { - Address: member2.String(), - Weight: "1", - Metadata: "metadata", - }, - } - req, err := group.NewMsgCreateGroupWithPolicy(admin.String(), members, "group_metadata", "group_policy_metadata", false, policy) - require.NoError(t, err) - return req - }, - false, - "", - }, - } - - for _, tc := range testCases { - t.Run(tc.name, func(t *testing.T) { - msg := tc.msg() - err := msg.ValidateBasic() - if tc.expErr { - require.Error(t, err) - require.Contains(t, err.Error(), tc.errMsg) - } else { - require.NoError(t, err) - require.Equal(t, sdk.MsgTypeURL(msg), sdk.MsgTypeURL(&group.MsgCreateGroupWithPolicy{})) - } - }) - } -} - -func TestMsgCreateGroupPolicy(t *testing.T) { - testCases := []struct { - name string - msg func() *group.MsgCreateGroupPolicy - expErr bool - errMsg string - }{ - { - "empty group id", - func() *group.MsgCreateGroupPolicy { - return &group.MsgCreateGroupPolicy{ - Admin: admin.String(), - } - }, - true, - "group id: value is empty", - }, - { - "admin: invalid bech32 address", - func() *group.MsgCreateGroupPolicy { - return &group.MsgCreateGroupPolicy{ - Admin: "admin", - GroupId: 1, - } - }, - true, - "admin: decoding bech32 failed", - }, - { - "invalid threshold policy", - func() *group.MsgCreateGroupPolicy { - policy := group.NewThresholdDecisionPolicy("-1", time.Second, 0) - req, err := group.NewMsgCreateGroupPolicy(admin, 1, "metadata", policy) - require.NoError(t, err) - return req - }, - true, - "expected a positive decimal", - }, - { - "invalid voting period", - func() *group.MsgCreateGroupPolicy { - policy := group.NewThresholdDecisionPolicy("-1", time.Duration(0), 0) - req, err := group.NewMsgCreateGroupPolicy(admin, 1, "metadata", policy) - require.NoError(t, err) - return req - }, - true, - "expected a positive decimal", - }, - { - "invalid execution period", - func() *group.MsgCreateGroupPolicy { - policy := group.NewThresholdDecisionPolicy("-1", time.Minute, 0) - req, err := group.NewMsgCreateGroupPolicy(admin, 1, "metadata", policy) - require.NoError(t, err) - return req - }, - true, - "expected a positive decimal", - }, - { - "valid test case, only voting period", - func() *group.MsgCreateGroupPolicy { - policy := group.NewThresholdDecisionPolicy("1", time.Second, 0) - req, err := group.NewMsgCreateGroupPolicy(admin, 1, "metadata", policy) - require.NoError(t, err) - return req - }, - false, - "", - }, - { - "valid test case, voting and execution, empty min exec period", - func() *group.MsgCreateGroupPolicy { - policy := group.NewThresholdDecisionPolicy("1", time.Second, 0) - req, err := group.NewMsgCreateGroupPolicy(admin, 1, "metadata", policy) - require.NoError(t, err) - return req - }, - false, - "", - }, - { - "valid test case, voting and execution, non-empty min exec period", - func() *group.MsgCreateGroupPolicy { - policy := group.NewThresholdDecisionPolicy("1", time.Second, time.Minute) - req, err := group.NewMsgCreateGroupPolicy(admin, 1, "metadata", policy) - require.NoError(t, err) - return req - }, - false, - "", - }, - { - "invalid percentage decision policy with zero value", - func() *group.MsgCreateGroupPolicy { - percentagePolicy := group.NewPercentageDecisionPolicy("0", time.Second, 0) - req, err := group.NewMsgCreateGroupPolicy(admin, 1, "metadata", percentagePolicy) - require.NoError(t, err) - return req - }, - true, - "expected a positive decimal", - }, - { - "invalid percentage decision policy with negative value", - func() *group.MsgCreateGroupPolicy { - percentagePolicy := group.NewPercentageDecisionPolicy("-0.2", time.Second, 0) - req, err := group.NewMsgCreateGroupPolicy(admin, 1, "metadata", percentagePolicy) - require.NoError(t, err) - return req - }, - true, - "expected a positive decimal", - }, - { - "invalid percentage decision policy with value greater than 1", - func() *group.MsgCreateGroupPolicy { - percentagePolicy := group.NewPercentageDecisionPolicy("2", time.Second, 0) - req, err := group.NewMsgCreateGroupPolicy(admin, 1, "metadata", percentagePolicy) - require.NoError(t, err) - return req - }, - true, - "percentage must be > 0 and <= 1", - }, - { - "valid test case with percentage decision policy", - func() *group.MsgCreateGroupPolicy { - percentagePolicy := group.NewPercentageDecisionPolicy("0.5", time.Second, 0) - req, err := group.NewMsgCreateGroupPolicy(admin, 1, "metadata", percentagePolicy) - require.NoError(t, err) - return req - }, - false, - "", - }, - } - - for _, tc := range testCases { - t.Run(tc.name, func(t *testing.T) { - msg := tc.msg() - err := msg.ValidateBasic() - if tc.expErr { - require.Error(t, err) - require.Contains(t, err.Error(), tc.errMsg) - } else { - require.NoError(t, err) - require.Equal(t, sdk.MsgTypeURL(msg), sdk.MsgTypeURL(&group.MsgCreateGroupPolicy{})) - } - }) - } -} - -func TestMsgUpdateGroupPolicyDecisionPolicy(t *testing.T) { - validPolicy := group.NewThresholdDecisionPolicy("1", time.Second, 0) - msg1, err := group.NewMsgUpdateGroupPolicyDecisionPolicy(admin, member1, validPolicy) - require.NoError(t, err) - - invalidPolicy := group.NewThresholdDecisionPolicy("-1", time.Second, 0) - msg2, err := group.NewMsgUpdateGroupPolicyDecisionPolicy(admin, member2, invalidPolicy) - require.NoError(t, err) - - validPercentagePolicy := group.NewPercentageDecisionPolicy("0.7", time.Second, 0) - msg3, err := group.NewMsgUpdateGroupPolicyDecisionPolicy(admin, member3, validPercentagePolicy) - require.NoError(t, err) - - invalidPercentagePolicy := group.NewPercentageDecisionPolicy("-0.1", time.Second, 0) - msg4, err := group.NewMsgUpdateGroupPolicyDecisionPolicy(admin, member4, invalidPercentagePolicy) - require.NoError(t, err) - - invalidPercentagePolicy2 := group.NewPercentageDecisionPolicy("2", time.Second, 0) - msg5, err := group.NewMsgUpdateGroupPolicyDecisionPolicy(admin, member5, invalidPercentagePolicy2) - require.NoError(t, err) - - testCases := []struct { - name string - msg *group.MsgUpdateGroupPolicyDecisionPolicy - expErr bool - errMsg string - }{ - { - "admin: invalid bech32 address", - &group.MsgUpdateGroupPolicyDecisionPolicy{ - Admin: "admin", - }, - true, - "admin: decoding bech32 failed", - }, - { - "group policy: invalid bech32 address", - &group.MsgUpdateGroupPolicyDecisionPolicy{ - Admin: admin.String(), - GroupPolicyAddress: "address", - }, - true, - "group policy: decoding bech32 failed", - }, - { - "group policy: invalid bech32 address", - &group.MsgUpdateGroupPolicyDecisionPolicy{ - Admin: admin.String(), - GroupPolicyAddress: "address", - }, - true, - "group policy: decoding bech32 failed", - }, - { - "invalid decision policy", - msg2, - true, - "decision policy: threshold: expected a positive decimal", - }, - { - "valid decision policy", - msg1, - false, - "", - }, - { - "valid percentage decision policy", - msg3, - false, - "", - }, - { - "invalid percentage decision policy with negative value", - msg4, - true, - "decision policy: percentage threshold: expected a positive decimal", - }, - { - "invalid percentage decision policy with value greater than 1", - msg5, - true, - "decision policy: percentage must be > 0 and <= 1", - }, - } - - for _, tc := range testCases { - t.Run(tc.name, func(t *testing.T) { - msg := tc.msg - err := msg.ValidateBasic() - if tc.expErr { - require.Error(t, err) - require.Contains(t, err.Error(), tc.errMsg) - } else { - require.NoError(t, err) - require.Equal(t, sdk.MsgTypeURL(msg), sdk.MsgTypeURL(&group.MsgUpdateGroupPolicyDecisionPolicy{})) - } - }) - } -} - -func TestMsgUpdateGroupPolicyAdmin(t *testing.T) { - testCases := []struct { - name string - msg *group.MsgUpdateGroupPolicyAdmin - expErr bool - errMsg string - }{ - { - "admin: invalid bech32 address", - &group.MsgUpdateGroupPolicyAdmin{ - Admin: "admin", - }, - true, - "admin: decoding bech32 failed", - }, - { - "policy address: invalid bech32 address", - &group.MsgUpdateGroupPolicyAdmin{ - Admin: admin.String(), - NewAdmin: member1.String(), - GroupPolicyAddress: "address", - }, - true, - "group policy: decoding bech32 failed", - }, - { - "new admin: invalid bech32 address", - &group.MsgUpdateGroupPolicyAdmin{ - Admin: admin.String(), - GroupPolicyAddress: admin.String(), - NewAdmin: "new-admin", - }, - true, - "new admin: decoding bech32 failed", - }, - { - "same old and new admin", - &group.MsgUpdateGroupPolicyAdmin{ - Admin: admin.String(), - GroupPolicyAddress: admin.String(), - NewAdmin: admin.String(), - }, - true, - "new and old admin are same", - }, - { - "valid test", - &group.MsgUpdateGroupPolicyAdmin{ - Admin: admin.String(), - GroupPolicyAddress: admin.String(), - NewAdmin: member1.String(), - }, - false, - "", - }, - } - - for _, tc := range testCases { - t.Run(tc.name, func(t *testing.T) { - msg := tc.msg - err := msg.ValidateBasic() - if tc.expErr { - require.Error(t, err) - require.Contains(t, err.Error(), tc.errMsg) - } else { - require.NoError(t, err) - require.Equal(t, sdk.MsgTypeURL(msg), sdk.MsgTypeURL(&group.MsgUpdateGroupPolicyAdmin{})) - } - }) - } -} - -func TestMsgUpdateGroupPolicyMetadata(t *testing.T) { - testCases := []struct { - name string - msg *group.MsgUpdateGroupPolicyMetadata - expErr bool - errMsg string - }{ - { - "admin: invalid bech32 address", - &group.MsgUpdateGroupPolicyMetadata{ - Admin: "admin", - }, - true, - "admin: decoding bech32 failed", - }, - { - "group policy address: invalid bech32 address", - &group.MsgUpdateGroupPolicyMetadata{ - Admin: admin.String(), - GroupPolicyAddress: "address", - }, - true, - "group policy: decoding bech32 failed", - }, - { - "valid testcase", - &group.MsgUpdateGroupPolicyMetadata{ - Admin: admin.String(), - GroupPolicyAddress: member1.String(), - Metadata: "metadata", - }, - false, - "", - }, - } - - for _, tc := range testCases { - t.Run(tc.name, func(t *testing.T) { - msg := tc.msg - err := msg.ValidateBasic() - if tc.expErr { - require.Error(t, err) - require.Contains(t, err.Error(), tc.errMsg) - } else { - require.NoError(t, err) - require.Equal(t, sdk.MsgTypeURL(msg), sdk.MsgTypeURL(&group.MsgUpdateGroupPolicyMetadata{})) - } - }) - } -} - -func TestMsgSubmitProposal(t *testing.T) { - testCases := []struct { - name string - msg *group.MsgSubmitProposal - expErr bool - errMsg string - }{ - { - "invalid group policy address", - &group.MsgSubmitProposal{ - GroupPolicyAddress: "address", - }, - true, - "group policy: decoding bech32 failed", - }, - { - "proposers required", - &group.MsgSubmitProposal{ - GroupPolicyAddress: admin.String(), - Title: "Title", - Summary: "Summary", - }, - true, - "proposers: value is empty", - }, - { - "valid testcase", - &group.MsgSubmitProposal{ - GroupPolicyAddress: admin.String(), - Proposers: []string{member1.String(), member2.String()}, - Title: "Title", - Summary: "Summary", - }, - false, - "", - }, - { - "missing title", - &group.MsgSubmitProposal{ - GroupPolicyAddress: admin.String(), - Proposers: []string{member1.String(), member2.String()}, - Summary: "Summary", - }, - true, - "title: value is empty", - }, - { - "missing summary", - &group.MsgSubmitProposal{ - GroupPolicyAddress: admin.String(), - Proposers: []string{member1.String(), member2.String()}, - Title: "title", - }, - true, - "summary: value is empty", - }, - } - - for _, tc := range testCases { - t.Run(tc.name, func(t *testing.T) { - msg := tc.msg - err := msg.ValidateBasic() - if tc.expErr { - require.Error(t, err) - require.Contains(t, err.Error(), tc.errMsg) - } else { - require.NoError(t, err) - require.Equal(t, sdk.MsgTypeURL(msg), sdk.MsgTypeURL(&group.MsgSubmitProposal{})) - } - }) - } -} - -func TestMsgSubmitProposalGetSignBytes(t *testing.T) { - testcases := []struct { - name string - proposal []sdk.Msg - expSignBz string - }{ - { - "MsgSend", - []sdk.Msg{banktypes.NewMsgSend(member1, member1, sdk.NewCoins())}, - fmt.Sprintf(`{"type":"cosmos-sdk/group/MsgSubmitProposal","value":{"messages":[{"type":"cosmos-sdk/MsgSend","value":{"amount":[],"from_address":"%s","to_address":"%s"}}],"proposers":[""],"summary":"This is a test","title":"MsgSend"}}`, member1, member1), - }, - } - - for _, tc := range testcases { - t.Run(tc.name, func(t *testing.T) { - msg, err := group.NewMsgSubmitProposal(sdk.AccAddress{}.String(), []string{sdk.AccAddress{}.String()}, tc.proposal, "", group.Exec_EXEC_UNSPECIFIED, "MsgSend", "This is a test") - require.NoError(t, err) - var bz []byte - require.NotPanics(t, func() { - bz = msg.GetSignBytes() - }) - require.Equal(t, tc.expSignBz, string(bz)) - }) - } -} - -func TestMsgVote(t *testing.T) { - testCases := []struct { - name string - msg *group.MsgVote - expErr bool - errMsg string - }{ - { - "invalid voter address", - &group.MsgVote{ - Voter: "voter", - }, - true, - "voter: decoding bech32 failed", - }, - { - "proposal id is required", - &group.MsgVote{ - Voter: member1.String(), - }, - true, - "proposal id: value is empty", - }, - { - "unspecified vote option", - &group.MsgVote{ - Voter: member1.String(), - ProposalId: 1, - }, - true, - "vote option: value is empty", - }, - { - "valid test case", - &group.MsgVote{ - Voter: member1.String(), - ProposalId: 1, - Option: group.VOTE_OPTION_YES, - }, - false, - "", - }, - } - - for _, tc := range testCases { - t.Run(tc.name, func(t *testing.T) { - msg := tc.msg - err := msg.ValidateBasic() - if tc.expErr { - require.Error(t, err) - require.Contains(t, err.Error(), tc.errMsg) - } else { - require.NoError(t, err) - require.Equal(t, sdk.MsgTypeURL(msg), sdk.MsgTypeURL(&group.MsgVote{})) - } - }) - } -} - -func TestMsgWithdrawProposal(t *testing.T) { - testCases := []struct { - name string - msg *group.MsgWithdrawProposal - expErr bool - errMsg string - }{ - { - "invalid address", - &group.MsgWithdrawProposal{ - Address: "address", - }, - true, - "decoding bech32 failed", - }, - { - "proposal id is required", - &group.MsgWithdrawProposal{ - Address: member1.String(), - }, - true, - "proposal id: value is empty", - }, - { - "valid msg", - &group.MsgWithdrawProposal{ - Address: member1.String(), - ProposalId: 1, - }, - false, - "", - }, - } - - for _, tc := range testCases { - t.Run(tc.name, func(t *testing.T) { - msg := tc.msg - err := msg.ValidateBasic() - if tc.expErr { - require.Error(t, err) - require.Contains(t, err.Error(), tc.errMsg) - } else { - require.NoError(t, err) - require.Equal(t, sdk.MsgTypeURL(msg), sdk.MsgTypeURL(&group.MsgWithdrawProposal{})) - } - }) - } -} - -func TestMsgExec(t *testing.T) { - testCases := []struct { - name string - msg *group.MsgExec - expErr bool - errMsg string - }{ - { - "invalid signer address", - &group.MsgExec{ - Executor: "signer", - }, - true, - "signer: decoding bech32 failed", - }, - { - "proposal is required", - &group.MsgExec{ - Executor: admin.String(), - }, - true, - "proposal id: value is empty", - }, - { - "valid testcase", - &group.MsgExec{ - Executor: admin.String(), - ProposalId: 1, - }, - false, - "", - }, - } - for _, tc := range testCases { - t.Run(tc.name, func(t *testing.T) { - msg := tc.msg - err := msg.ValidateBasic() - if tc.expErr { - require.Error(t, err) - require.Contains(t, err.Error(), tc.errMsg) - } else { - require.NoError(t, err) - require.Equal(t, sdk.MsgTypeURL(msg), sdk.MsgTypeURL(&group.MsgExec{})) - } - }) - } -} - -func TestMsgLeaveGroup(t *testing.T) { - testCases := []struct { - name string - msg *group.MsgLeaveGroup - expErr bool - errMsg string - }{ - { - "invalid group member address", - &group.MsgLeaveGroup{ - Address: "member", - }, - true, - "group member: decoding bech32 failed", - }, - { - "group id is required", - &group.MsgLeaveGroup{ - Address: admin.String(), - }, - true, - "group-id: value is empty", - }, - { - "valid testcase", - &group.MsgLeaveGroup{ - Address: admin.String(), - GroupId: 1, - }, - false, - "", - }, - } - for _, tc := range testCases { - t.Run(tc.name, func(t *testing.T) { - msg := tc.msg - err := msg.ValidateBasic() - if tc.expErr { - require.Error(t, err) - require.Contains(t, err.Error(), tc.errMsg) - } else { - require.NoError(t, err) - require.Equal(t, sdk.MsgTypeURL(msg), sdk.MsgTypeURL(&group.MsgLeaveGroup{})) - } - }) - } -} - -func TestAmino(t *testing.T) { - cdc := testutil.MakeTestEncodingConfig(module.AppModuleBasic{}) - - out, err := cdc.Amino.MarshalJSON(group.MsgSubmitProposal{Proposers: []string{member1.String()}}) - require.NoError(t, err) - require.Equal(t, - `{"type":"cosmos-sdk/group/MsgSubmitProposal","value":{"proposers":["cosmos1d4jk6cn9wgcsj540xq"]}}`, - string(out), - ) -} diff --git a/x/group/simulation/operations.go b/x/group/simulation/operations.go index 9b19fd692f46..7a17ebba89d0 100644 --- a/x/group/simulation/operations.go +++ b/x/group/simulation/operations.go @@ -8,12 +8,12 @@ import ( "time" "github.com/cosmos/cosmos-sdk/baseapp" + "github.com/cosmos/cosmos-sdk/client" "github.com/cosmos/cosmos-sdk/codec" cdctypes "github.com/cosmos/cosmos-sdk/codec/types" simtestutil "github.com/cosmos/cosmos-sdk/testutil/sims" sdk "github.com/cosmos/cosmos-sdk/types" simtypes "github.com/cosmos/cosmos-sdk/types/simulation" - "github.com/cosmos/cosmos-sdk/x/auth/tx" "github.com/cosmos/cosmos-sdk/x/group/keeper" "github.com/cosmos/cosmos-sdk/x/simulation" @@ -41,8 +41,6 @@ var ( ) // Simulation operation weights constants -// -//nolint:gosec // these are not hardcoded credentials. const ( OpMsgCreateGroup = "op_weight_msg_create_group" OpMsgUpdateGroupAdmin = "op_weight_msg_update_group_admin" @@ -82,8 +80,9 @@ const ( // WeightedOperations returns all the operations from the module with their respective weights func WeightedOperations( registry cdctypes.InterfaceRegistry, - appParams simtypes.AppParams, cdc codec.JSONCodec, ak group.AccountKeeper, - bk group.BankKeeper, k keeper.Keeper, appCdc cdctypes.AnyUnpacker, + appParams simtypes.AppParams, cdc codec.JSONCodec, txGen client.TxConfig, + ak group.AccountKeeper, bk group.BankKeeper, k keeper.Keeper, + appCdc cdctypes.AnyUnpacker, ) simulation.WeightedOperations { var ( weightMsgCreateGroup int @@ -173,70 +172,72 @@ func WeightedOperations( }, ) + pCdc := codec.NewProtoCodec(registry) + // create two proposals for weightedOperations var createProposalOps simulation.WeightedOperations for i := 0; i < 2; i++ { createProposalOps = append(createProposalOps, simulation.NewWeightedOperation( weightMsgSubmitProposal, - SimulateMsgSubmitProposal(codec.NewProtoCodec(registry), ak, bk, k), + SimulateMsgSubmitProposal(pCdc, txGen, ak, bk, k), )) } wPreCreateProposalOps := simulation.WeightedOperations{ simulation.NewWeightedOperation( weightMsgCreateGroup, - SimulateMsgCreateGroup(codec.NewProtoCodec(registry), ak, bk), + SimulateMsgCreateGroup(pCdc, txGen, ak, bk), ), simulation.NewWeightedOperation( weightMsgCreateGroupPolicy, - SimulateMsgCreateGroupPolicy(codec.NewProtoCodec(registry), ak, bk, k), + SimulateMsgCreateGroupPolicy(pCdc, txGen, ak, bk, k), ), simulation.NewWeightedOperation( weightMsgCreateGroupWithPolicy, - SimulateMsgCreateGroupWithPolicy(codec.NewProtoCodec(registry), ak, bk), + SimulateMsgCreateGroupWithPolicy(pCdc, txGen, ak, bk), ), } wPostCreateProposalOps := simulation.WeightedOperations{ simulation.NewWeightedOperation( WeightMsgWithdrawProposal, - SimulateMsgWithdrawProposal(codec.NewProtoCodec(registry), ak, bk, k), + SimulateMsgWithdrawProposal(pCdc, txGen, ak, bk, k), ), simulation.NewWeightedOperation( weightMsgVote, - SimulateMsgVote(codec.NewProtoCodec(registry), ak, bk, k), + SimulateMsgVote(pCdc, txGen, ak, bk, k), ), simulation.NewWeightedOperation( weightMsgExec, - SimulateMsgExec(codec.NewProtoCodec(registry), ak, bk, k), + SimulateMsgExec(pCdc, txGen, ak, bk, k), ), simulation.NewWeightedOperation( weightMsgUpdateGroupMetadata, - SimulateMsgUpdateGroupMetadata(codec.NewProtoCodec(registry), ak, bk, k), + SimulateMsgUpdateGroupMetadata(pCdc, txGen, ak, bk, k), ), simulation.NewWeightedOperation( weightMsgUpdateGroupAdmin, - SimulateMsgUpdateGroupAdmin(codec.NewProtoCodec(registry), ak, bk, k), + SimulateMsgUpdateGroupAdmin(pCdc, txGen, ak, bk, k), ), simulation.NewWeightedOperation( weightMsgUpdateGroupMembers, - SimulateMsgUpdateGroupMembers(codec.NewProtoCodec(registry), ak, bk, k), + SimulateMsgUpdateGroupMembers(pCdc, txGen, ak, bk, k), ), simulation.NewWeightedOperation( weightMsgUpdateGroupPolicyAdmin, - SimulateMsgUpdateGroupPolicyAdmin(codec.NewProtoCodec(registry), ak, bk, k), + SimulateMsgUpdateGroupPolicyAdmin(pCdc, txGen, ak, bk, k), ), simulation.NewWeightedOperation( weightMsgUpdateGroupPolicyDecisionPolicy, - SimulateMsgUpdateGroupPolicyDecisionPolicy(codec.NewProtoCodec(registry), ak, bk, k), + SimulateMsgUpdateGroupPolicyDecisionPolicy(pCdc, txGen, ak, bk, k), ), simulation.NewWeightedOperation( weightMsgUpdateGroupPolicyMetadata, - SimulateMsgUpdateGroupPolicyMetadata(codec.NewProtoCodec(registry), ak, bk, k), + SimulateMsgUpdateGroupPolicyMetadata(pCdc, txGen, ak, bk, k), ), simulation.NewWeightedOperation( weightMsgLeaveGroup, - SimulateMsgLeaveGroup(codec.NewProtoCodec(registry), k, ak, bk), + SimulateMsgLeaveGroup(pCdc, txGen, k, ak, bk), ), } @@ -244,7 +245,12 @@ func WeightedOperations( } // SimulateMsgCreateGroup generates a MsgCreateGroup with random values -func SimulateMsgCreateGroup(cdc *codec.ProtoCodec, ak group.AccountKeeper, bk group.BankKeeper) simtypes.Operation { +func SimulateMsgCreateGroup( + cdc *codec.ProtoCodec, + txGen client.TxConfig, + ak group.AccountKeeper, + bk group.BankKeeper, +) simtypes.Operation { return func( r *rand.Rand, app *baseapp.BaseApp, ctx sdk.Context, accounts []simtypes.Account, chainID string, ) (simtypes.OperationMsg, []simtypes.FutureOperation, error) { @@ -261,7 +267,6 @@ func SimulateMsgCreateGroup(cdc *codec.ProtoCodec, ak group.AccountKeeper, bk gr members := genGroupMembers(r, accounts) msg := &group.MsgCreateGroup{Admin: accAddr, Members: members, Metadata: simtypes.RandStringOfLength(r, 10)} - txGen := tx.NewTxConfig(cdc, tx.DefaultSignModes) tx, err := simtestutil.GenSignedMockTx( r, txGen, @@ -287,7 +292,12 @@ func SimulateMsgCreateGroup(cdc *codec.ProtoCodec, ak group.AccountKeeper, bk gr } // SimulateMsgCreateGroupWithPolicy generates a MsgCreateGroupWithPolicy with random values -func SimulateMsgCreateGroupWithPolicy(cdc *codec.ProtoCodec, ak group.AccountKeeper, bk group.BankKeeper) simtypes.Operation { +func SimulateMsgCreateGroupWithPolicy( + cdc *codec.ProtoCodec, + txGen client.TxConfig, + ak group.AccountKeeper, + bk group.BankKeeper, +) simtypes.Operation { return func( r *rand.Rand, app *baseapp.BaseApp, ctx sdk.Context, accounts []simtypes.Account, chainID string, ) (simtypes.OperationMsg, []simtypes.FutureOperation, error) { @@ -321,7 +331,6 @@ func SimulateMsgCreateGroupWithPolicy(cdc *codec.ProtoCodec, ak group.AccountKee return simtypes.NoOpMsg(group.ModuleName, sdk.MsgTypeURL(msg), "unable to set decision policy"), nil, err } - txGen := tx.NewTxConfig(cdc, tx.DefaultSignModes) tx, err := simtestutil.GenSignedMockTx( r, txGen, @@ -347,7 +356,13 @@ func SimulateMsgCreateGroupWithPolicy(cdc *codec.ProtoCodec, ak group.AccountKee } // SimulateMsgCreateGroupPolicy generates a NewMsgCreateGroupPolicy with random values -func SimulateMsgCreateGroupPolicy(cdc *codec.ProtoCodec, ak group.AccountKeeper, bk group.BankKeeper, k keeper.Keeper) simtypes.Operation { +func SimulateMsgCreateGroupPolicy( + cdc *codec.ProtoCodec, + txGen client.TxConfig, + ak group.AccountKeeper, + bk group.BankKeeper, + k keeper.Keeper, +) simtypes.Operation { return func( r *rand.Rand, app *baseapp.BaseApp, sdkCtx sdk.Context, accounts []simtypes.Account, chainID string, ) (simtypes.OperationMsg, []simtypes.FutureOperation, error) { @@ -381,7 +396,6 @@ func SimulateMsgCreateGroupPolicy(cdc *codec.ProtoCodec, ak group.AccountKeeper, return simtypes.NoOpMsg(group.ModuleName, TypeMsgCreateGroupPolicy, err.Error()), nil, err } - txGen := tx.NewTxConfig(cdc, tx.DefaultSignModes) tx, err := simtestutil.GenSignedMockTx( r, txGen, @@ -408,7 +422,13 @@ func SimulateMsgCreateGroupPolicy(cdc *codec.ProtoCodec, ak group.AccountKeeper, } // SimulateMsgSubmitProposal generates a NewMsgSubmitProposal with random values -func SimulateMsgSubmitProposal(cdc *codec.ProtoCodec, ak group.AccountKeeper, bk group.BankKeeper, k keeper.Keeper) simtypes.Operation { +func SimulateMsgSubmitProposal( + cdc *codec.ProtoCodec, + txGen client.TxConfig, + ak group.AccountKeeper, + bk group.BankKeeper, + k keeper.Keeper, +) simtypes.Operation { return func( r *rand.Rand, app *baseapp.BaseApp, sdkCtx sdk.Context, accounts []simtypes.Account, chainID string, ) (simtypes.OperationMsg, []simtypes.FutureOperation, error) { @@ -458,7 +478,6 @@ func SimulateMsgSubmitProposal(cdc *codec.ProtoCodec, ak group.AccountKeeper, bk Summary: "Summary of the proposal", } - txGen := tx.NewTxConfig(cdc, tx.DefaultSignModes) tx, err := simtestutil.GenSignedMockTx( r, txGen, @@ -484,7 +503,13 @@ func SimulateMsgSubmitProposal(cdc *codec.ProtoCodec, ak group.AccountKeeper, bk } // SimulateMsgUpdateGroupAdmin generates a MsgUpdateGroupAdmin with random values -func SimulateMsgUpdateGroupAdmin(cdc *codec.ProtoCodec, ak group.AccountKeeper, bk group.BankKeeper, k keeper.Keeper) simtypes.Operation { +func SimulateMsgUpdateGroupAdmin( + cdc *codec.ProtoCodec, + txGen client.TxConfig, + ak group.AccountKeeper, + bk group.BankKeeper, + k keeper.Keeper, +) simtypes.Operation { return func( r *rand.Rand, app *baseapp.BaseApp, sdkCtx sdk.Context, accounts []simtypes.Account, chainID string, ) (simtypes.OperationMsg, []simtypes.FutureOperation, error) { @@ -518,7 +543,6 @@ func SimulateMsgUpdateGroupAdmin(cdc *codec.ProtoCodec, ak group.AccountKeeper, NewAdmin: newAdmin.Address.String(), } - txGen := tx.NewTxConfig(cdc, tx.DefaultSignModes) tx, err := simtestutil.GenSignedMockTx( r, txGen, @@ -544,7 +568,13 @@ func SimulateMsgUpdateGroupAdmin(cdc *codec.ProtoCodec, ak group.AccountKeeper, } // SimulateMsgUpdateGroupMetadata generates a MsgUpdateGroupMetadata with random values -func SimulateMsgUpdateGroupMetadata(cdc *codec.ProtoCodec, ak group.AccountKeeper, bk group.BankKeeper, k keeper.Keeper) simtypes.Operation { +func SimulateMsgUpdateGroupMetadata( + cdc *codec.ProtoCodec, + txGen client.TxConfig, + ak group.AccountKeeper, + bk group.BankKeeper, + k keeper.Keeper, +) simtypes.Operation { return func( r *rand.Rand, app *baseapp.BaseApp, sdkCtx sdk.Context, accounts []simtypes.Account, chainID string, ) (simtypes.OperationMsg, []simtypes.FutureOperation, error) { @@ -569,7 +599,6 @@ func SimulateMsgUpdateGroupMetadata(cdc *codec.ProtoCodec, ak group.AccountKeepe Metadata: simtypes.RandStringOfLength(r, 10), } - txGen := tx.NewTxConfig(cdc, tx.DefaultSignModes) tx, err := simtestutil.GenSignedMockTx( r, txGen, @@ -595,8 +624,12 @@ func SimulateMsgUpdateGroupMetadata(cdc *codec.ProtoCodec, ak group.AccountKeepe } // SimulateMsgUpdateGroupMembers generates a MsgUpdateGroupMembers with random values -func SimulateMsgUpdateGroupMembers(cdc *codec.ProtoCodec, ak group.AccountKeeper, - bk group.BankKeeper, k keeper.Keeper, +func SimulateMsgUpdateGroupMembers( + cdc *codec.ProtoCodec, + txGen client.TxConfig, + ak group.AccountKeeper, + bk group.BankKeeper, + k keeper.Keeper, ) simtypes.Operation { return func( r *rand.Rand, app *baseapp.BaseApp, sdkCtx sdk.Context, accounts []simtypes.Account, chainID string, @@ -649,7 +682,6 @@ func SimulateMsgUpdateGroupMembers(cdc *codec.ProtoCodec, ak group.AccountKeeper MemberUpdates: members, } - txGen := tx.NewTxConfig(cdc, tx.DefaultSignModes) tx, err := simtestutil.GenSignedMockTx( r, txGen, @@ -675,7 +707,13 @@ func SimulateMsgUpdateGroupMembers(cdc *codec.ProtoCodec, ak group.AccountKeeper } // SimulateMsgUpdateGroupPolicyAdmin generates a MsgUpdateGroupPolicyAdmin with random values -func SimulateMsgUpdateGroupPolicyAdmin(cdc *codec.ProtoCodec, ak group.AccountKeeper, bk group.BankKeeper, k keeper.Keeper) simtypes.Operation { +func SimulateMsgUpdateGroupPolicyAdmin( + cdc *codec.ProtoCodec, + txGen client.TxConfig, + ak group.AccountKeeper, + bk group.BankKeeper, + k keeper.Keeper, +) simtypes.Operation { return func( r *rand.Rand, app *baseapp.BaseApp, sdkCtx sdk.Context, accounts []simtypes.Account, chainID string, ) (simtypes.OperationMsg, []simtypes.FutureOperation, error) { @@ -709,7 +747,6 @@ func SimulateMsgUpdateGroupPolicyAdmin(cdc *codec.ProtoCodec, ak group.AccountKe NewAdmin: newAdmin.Address.String(), } - txGen := tx.NewTxConfig(cdc, tx.DefaultSignModes) tx, err := simtestutil.GenSignedMockTx( r, txGen, @@ -735,8 +772,12 @@ func SimulateMsgUpdateGroupPolicyAdmin(cdc *codec.ProtoCodec, ak group.AccountKe } // // SimulateMsgUpdateGroupPolicyDecisionPolicy generates a NewMsgUpdateGroupPolicyDecisionPolicy with random values -func SimulateMsgUpdateGroupPolicyDecisionPolicy(cdc *codec.ProtoCodec, ak group.AccountKeeper, - bk group.BankKeeper, k keeper.Keeper, +func SimulateMsgUpdateGroupPolicyDecisionPolicy( + cdc *codec.ProtoCodec, + txGen client.TxConfig, + ak group.AccountKeeper, + bk group.BankKeeper, + k keeper.Keeper, ) simtypes.Operation { return func( r *rand.Rand, app *baseapp.BaseApp, sdkCtx sdk.Context, accounts []simtypes.Account, chainID string, @@ -771,7 +812,6 @@ func SimulateMsgUpdateGroupPolicyDecisionPolicy(cdc *codec.ProtoCodec, ak group. return simtypes.NoOpMsg(group.ModuleName, TypeMsgUpdateGroupPolicyDecisionPolicy, err.Error()), nil, err } - txGen := tx.NewTxConfig(cdc, tx.DefaultSignModes) tx, err := simtestutil.GenSignedMockTx( r, txGen, @@ -796,8 +836,12 @@ func SimulateMsgUpdateGroupPolicyDecisionPolicy(cdc *codec.ProtoCodec, ak group. } // // SimulateMsgUpdateGroupPolicyMetadata generates a MsgUpdateGroupPolicyMetadata with random values -func SimulateMsgUpdateGroupPolicyMetadata(cdc *codec.ProtoCodec, ak group.AccountKeeper, - bk group.BankKeeper, k keeper.Keeper, +func SimulateMsgUpdateGroupPolicyMetadata( + cdc *codec.ProtoCodec, + txGen client.TxConfig, + ak group.AccountKeeper, + bk group.BankKeeper, + k keeper.Keeper, ) simtypes.Operation { return func( r *rand.Rand, app *baseapp.BaseApp, sdkCtx sdk.Context, accounts []simtypes.Account, chainID string, @@ -823,7 +867,6 @@ func SimulateMsgUpdateGroupPolicyMetadata(cdc *codec.ProtoCodec, ak group.Accoun Metadata: simtypes.RandStringOfLength(r, 10), } - txGen := tx.NewTxConfig(cdc, tx.DefaultSignModes) tx, err := simtestutil.GenSignedMockTx( r, txGen, @@ -849,8 +892,12 @@ func SimulateMsgUpdateGroupPolicyMetadata(cdc *codec.ProtoCodec, ak group.Accoun } // SimulateMsgWithdrawProposal generates a MsgWithdrawProposal with random values -func SimulateMsgWithdrawProposal(cdc *codec.ProtoCodec, ak group.AccountKeeper, - bk group.BankKeeper, k keeper.Keeper, +func SimulateMsgWithdrawProposal( + cdc *codec.ProtoCodec, + txGen client.TxConfig, + ak group.AccountKeeper, + bk group.BankKeeper, + k keeper.Keeper, ) simtypes.Operation { return func( r *rand.Rand, app *baseapp.BaseApp, sdkCtx sdk.Context, accounts []simtypes.Account, chainID string, @@ -924,7 +971,6 @@ func SimulateMsgWithdrawProposal(cdc *codec.ProtoCodec, ak group.AccountKeeper, Address: proposer.Address.String(), } - txGen := tx.NewTxConfig(cdc, tx.DefaultSignModes) tx, err := simtestutil.GenSignedMockTx( r, txGen, @@ -954,8 +1000,12 @@ func SimulateMsgWithdrawProposal(cdc *codec.ProtoCodec, ak group.AccountKeeper, } // SimulateMsgVote generates a MsgVote with random values -func SimulateMsgVote(cdc *codec.ProtoCodec, ak group.AccountKeeper, - bk group.BankKeeper, k keeper.Keeper, +func SimulateMsgVote( + cdc *codec.ProtoCodec, + txGen client.TxConfig, + ak group.AccountKeeper, + bk group.BankKeeper, + k keeper.Keeper, ) simtypes.Operation { return func( r *rand.Rand, app *baseapp.BaseApp, sdkCtx sdk.Context, accounts []simtypes.Account, chainID string, @@ -1029,7 +1079,6 @@ func SimulateMsgVote(cdc *codec.ProtoCodec, ak group.AccountKeeper, Option: group.VOTE_OPTION_YES, Metadata: simtypes.RandStringOfLength(r, 10), } - txGen := tx.NewTxConfig(cdc, tx.DefaultSignModes) tx, err := simtestutil.GenSignedMockTx( r, txGen, @@ -1059,8 +1108,12 @@ func SimulateMsgVote(cdc *codec.ProtoCodec, ak group.AccountKeeper, } // // SimulateMsgExec generates a MsgExec with random values -func SimulateMsgExec(cdc *codec.ProtoCodec, ak group.AccountKeeper, - bk group.BankKeeper, k keeper.Keeper, +func SimulateMsgExec( + cdc *codec.ProtoCodec, + txGen client.TxConfig, + ak group.AccountKeeper, + bk group.BankKeeper, + k keeper.Keeper, ) simtypes.Operation { return func( r *rand.Rand, app *baseapp.BaseApp, sdkCtx sdk.Context, accounts []simtypes.Account, chainID string, @@ -1107,7 +1160,6 @@ func SimulateMsgExec(cdc *codec.ProtoCodec, ak group.AccountKeeper, ProposalId: uint64(proposalID), Executor: acc.Address.String(), } - txGen := tx.NewTxConfig(cdc, tx.DefaultSignModes) tx, err := simtestutil.GenSignedMockTx( r, txGen, @@ -1136,7 +1188,13 @@ func SimulateMsgExec(cdc *codec.ProtoCodec, ak group.AccountKeeper, } // SimulateMsgLeaveGroup generates a MsgLeaveGroup with random values -func SimulateMsgLeaveGroup(cdc *codec.ProtoCodec, k keeper.Keeper, ak group.AccountKeeper, bk group.BankKeeper) simtypes.Operation { +func SimulateMsgLeaveGroup( + cdc *codec.ProtoCodec, + txGen client.TxConfig, + k keeper.Keeper, + ak group.AccountKeeper, + bk group.BankKeeper, +) simtypes.Operation { return func( r *rand.Rand, app *baseapp.BaseApp, sdkCtx sdk.Context, accounts []simtypes.Account, chainID string, ) (simtypes.OperationMsg, []simtypes.FutureOperation, error) { @@ -1169,7 +1227,6 @@ func SimulateMsgLeaveGroup(cdc *codec.ProtoCodec, k keeper.Keeper, ak group.Acco GroupId: groupInfo.Id, } - txGen := tx.NewTxConfig(cdc, tx.DefaultSignModes) tx, err := simtestutil.GenSignedMockTx( r, txGen, diff --git a/x/group/simulation/operations_test.go b/x/group/simulation/operations_test.go index b3f4ccc539c2..315b5280ad0f 100644 --- a/x/group/simulation/operations_test.go +++ b/x/group/simulation/operations_test.go @@ -9,6 +9,7 @@ import ( cmtproto "github.com/cometbft/cometbft/proto/tendermint/types" "github.com/stretchr/testify/suite" + "github.com/cosmos/cosmos-sdk/client" "github.com/cosmos/cosmos-sdk/codec" codectypes "github.com/cosmos/cosmos-sdk/codec/types" "github.com/cosmos/cosmos-sdk/runtime" @@ -33,6 +34,7 @@ type SimTestSuite struct { app *runtime.App codec codec.Codec interfaceRegistry codectypes.InterfaceRegistry + txConfig client.TxConfig accountKeeper authkeeper.AccountKeeper bankKeeper bankkeeper.Keeper groupKeeper groupkeeper.Keeper @@ -43,6 +45,7 @@ func (suite *SimTestSuite) SetupTest() { grouptestutil.AppConfig, &suite.codec, &suite.interfaceRegistry, + &suite.txConfig, &suite.accountKeeper, &suite.bankKeeper, &suite.groupKeeper, @@ -57,7 +60,7 @@ func (suite *SimTestSuite) TestWeightedOperations() { cdc := suite.codec appParams := make(simtypes.AppParams) - weightedOps := simulation.WeightedOperations(suite.interfaceRegistry, appParams, cdc, suite.accountKeeper, + weightedOps := simulation.WeightedOperations(suite.interfaceRegistry, appParams, cdc, suite.txConfig, suite.accountKeeper, suite.bankKeeper, suite.groupKeeper, cdc, ) @@ -133,7 +136,7 @@ func (suite *SimTestSuite) TestSimulateCreateGroup() { acc := accounts[0] // execute operation - op := simulation.SimulateMsgCreateGroup(codec.NewProtoCodec(suite.interfaceRegistry), suite.accountKeeper, suite.bankKeeper) + op := simulation.SimulateMsgCreateGroup(codec.NewProtoCodec(suite.interfaceRegistry), suite.txConfig, suite.accountKeeper, suite.bankKeeper) operationMsg, futureOperations, err := op(r, suite.app.BaseApp, suite.ctx, accounts, "") suite.Require().NoError(err) @@ -162,7 +165,7 @@ func (suite *SimTestSuite) TestSimulateCreateGroupWithPolicy() { acc := accounts[0] // execute operation - op := simulation.SimulateMsgCreateGroupWithPolicy(codec.NewProtoCodec(suite.interfaceRegistry), suite.accountKeeper, suite.bankKeeper) + op := simulation.SimulateMsgCreateGroupWithPolicy(codec.NewProtoCodec(suite.interfaceRegistry), suite.txConfig, suite.accountKeeper, suite.bankKeeper) operationMsg, futureOperations, err := op(r, suite.app.BaseApp, suite.ctx, accounts, "") suite.Require().NoError(err) @@ -204,7 +207,7 @@ func (suite *SimTestSuite) TestSimulateCreateGroupPolicy() { }) // execute operation - op := simulation.SimulateMsgCreateGroupPolicy(codec.NewProtoCodec(suite.interfaceRegistry), suite.accountKeeper, suite.bankKeeper, suite.groupKeeper) + op := simulation.SimulateMsgCreateGroupPolicy(codec.NewProtoCodec(suite.interfaceRegistry), suite.txConfig, suite.accountKeeper, suite.bankKeeper, suite.groupKeeper) operationMsg, futureOperations, err := op(r, suite.app.BaseApp, suite.ctx, accounts, "") suite.Require().NoError(err) @@ -257,7 +260,7 @@ func (suite *SimTestSuite) TestSimulateSubmitProposal() { }) // execute operation - op := simulation.SimulateMsgSubmitProposal(codec.NewProtoCodec(suite.interfaceRegistry), suite.accountKeeper, suite.bankKeeper, suite.groupKeeper) + op := simulation.SimulateMsgSubmitProposal(codec.NewProtoCodec(suite.interfaceRegistry), suite.txConfig, suite.accountKeeper, suite.bankKeeper, suite.groupKeeper) operationMsg, futureOperations, err := op(r, suite.app.BaseApp, suite.ctx, accounts, "") suite.Require().NoError(err) @@ -323,7 +326,7 @@ func (suite *SimTestSuite) TestWithdrawProposal() { }) // execute operation - op := simulation.SimulateMsgWithdrawProposal(codec.NewProtoCodec(suite.interfaceRegistry), suite.accountKeeper, suite.bankKeeper, suite.groupKeeper) + op := simulation.SimulateMsgWithdrawProposal(codec.NewProtoCodec(suite.interfaceRegistry), suite.txConfig, suite.accountKeeper, suite.bankKeeper, suite.groupKeeper) operationMsg, futureOperations, err := op(r, suite.app.BaseApp, suite.ctx, accounts, "") suite.Require().NoError(err) @@ -390,7 +393,7 @@ func (suite *SimTestSuite) TestSimulateVote() { }) // execute operation - op := simulation.SimulateMsgVote(codec.NewProtoCodec(suite.interfaceRegistry), suite.accountKeeper, suite.bankKeeper, suite.groupKeeper) + op := simulation.SimulateMsgVote(codec.NewProtoCodec(suite.interfaceRegistry), suite.txConfig, suite.accountKeeper, suite.bankKeeper, suite.groupKeeper) operationMsg, futureOperations, err := op(r, suite.app.BaseApp, suite.ctx, accounts, "") suite.Require().NoError(err) @@ -465,7 +468,7 @@ func (suite *SimTestSuite) TestSimulateExec() { }) // execute operation - op := simulation.SimulateMsgExec(codec.NewProtoCodec(suite.interfaceRegistry), suite.accountKeeper, suite.bankKeeper, suite.groupKeeper) + op := simulation.SimulateMsgExec(codec.NewProtoCodec(suite.interfaceRegistry), suite.txConfig, suite.accountKeeper, suite.bankKeeper, suite.groupKeeper) operationMsg, futureOperations, err := op(r, suite.app.BaseApp, suite.ctx, accounts, "") suite.Require().NoError(err) @@ -507,7 +510,7 @@ func (suite *SimTestSuite) TestSimulateUpdateGroupAdmin() { }) // execute operation - op := simulation.SimulateMsgUpdateGroupAdmin(codec.NewProtoCodec(suite.interfaceRegistry), suite.accountKeeper, suite.bankKeeper, suite.groupKeeper) + op := simulation.SimulateMsgUpdateGroupAdmin(codec.NewProtoCodec(suite.interfaceRegistry), suite.txConfig, suite.accountKeeper, suite.bankKeeper, suite.groupKeeper) operationMsg, futureOperations, err := op(r, suite.app.BaseApp, suite.ctx, accounts, "") suite.Require().NoError(err) @@ -549,7 +552,7 @@ func (suite *SimTestSuite) TestSimulateUpdateGroupMetadata() { }) // execute operation - op := simulation.SimulateMsgUpdateGroupMetadata(codec.NewProtoCodec(suite.interfaceRegistry), suite.accountKeeper, suite.bankKeeper, suite.groupKeeper) + op := simulation.SimulateMsgUpdateGroupMetadata(codec.NewProtoCodec(suite.interfaceRegistry), suite.txConfig, suite.accountKeeper, suite.bankKeeper, suite.groupKeeper) operationMsg, futureOperations, err := op(r, suite.app.BaseApp, suite.ctx, accounts, "") suite.Require().NoError(err) @@ -591,7 +594,7 @@ func (suite *SimTestSuite) TestSimulateUpdateGroupMembers() { }) // execute operation - op := simulation.SimulateMsgUpdateGroupMembers(codec.NewProtoCodec(suite.interfaceRegistry), suite.accountKeeper, suite.bankKeeper, suite.groupKeeper) + op := simulation.SimulateMsgUpdateGroupMembers(codec.NewProtoCodec(suite.interfaceRegistry), suite.txConfig, suite.accountKeeper, suite.bankKeeper, suite.groupKeeper) operationMsg, futureOperations, err := op(r, suite.app.BaseApp, suite.ctx, accounts, "") suite.Require().NoError(err) @@ -644,7 +647,7 @@ func (suite *SimTestSuite) TestSimulateUpdateGroupPolicyAdmin() { }) // execute operation - op := simulation.SimulateMsgUpdateGroupPolicyAdmin(codec.NewProtoCodec(suite.interfaceRegistry), suite.accountKeeper, suite.bankKeeper, suite.groupKeeper) + op := simulation.SimulateMsgUpdateGroupPolicyAdmin(codec.NewProtoCodec(suite.interfaceRegistry), suite.txConfig, suite.accountKeeper, suite.bankKeeper, suite.groupKeeper) operationMsg, futureOperations, err := op(r, suite.app.BaseApp, suite.ctx, accounts, "") suite.Require().NoError(err) @@ -697,7 +700,7 @@ func (suite *SimTestSuite) TestSimulateUpdateGroupPolicyDecisionPolicy() { }) // execute operation - op := simulation.SimulateMsgUpdateGroupPolicyDecisionPolicy(codec.NewProtoCodec(suite.interfaceRegistry), suite.accountKeeper, suite.bankKeeper, suite.groupKeeper) + op := simulation.SimulateMsgUpdateGroupPolicyDecisionPolicy(codec.NewProtoCodec(suite.interfaceRegistry), suite.txConfig, suite.accountKeeper, suite.bankKeeper, suite.groupKeeper) operationMsg, futureOperations, err := op(r, suite.app.BaseApp, suite.ctx, accounts, "") suite.Require().NoError(err) @@ -750,7 +753,7 @@ func (suite *SimTestSuite) TestSimulateUpdateGroupPolicyMetadata() { }) // execute operation - op := simulation.SimulateMsgUpdateGroupPolicyMetadata(codec.NewProtoCodec(suite.interfaceRegistry), suite.accountKeeper, suite.bankKeeper, suite.groupKeeper) + op := simulation.SimulateMsgUpdateGroupPolicyMetadata(codec.NewProtoCodec(suite.interfaceRegistry), suite.txConfig, suite.accountKeeper, suite.bankKeeper, suite.groupKeeper) operationMsg, futureOperations, err := op(r, suite.app.BaseApp, suite.ctx, accounts, "") suite.Require().NoError(err) @@ -816,7 +819,7 @@ func (suite *SimTestSuite) TestSimulateLeaveGroup() { }) // execute operation - op := simulation.SimulateMsgLeaveGroup(codec.NewProtoCodec(suite.interfaceRegistry), suite.groupKeeper, suite.accountKeeper, suite.bankKeeper) + op := simulation.SimulateMsgLeaveGroup(codec.NewProtoCodec(suite.interfaceRegistry), suite.txConfig, suite.groupKeeper, suite.accountKeeper, suite.bankKeeper) operationMsg, futureOperations, err := op(r, suite.app.BaseApp, suite.ctx, accounts, "") suite.Require().NoError(err) diff --git a/x/group/testutil/expected_keepers_mocks.go b/x/group/testutil/expected_keepers_mocks.go index 8f614b6be1e2..ae05d4e8e1ff 100644 --- a/x/group/testutil/expected_keepers_mocks.go +++ b/x/group/testutil/expected_keepers_mocks.go @@ -36,8 +36,23 @@ func (m *MockAccountKeeper) EXPECT() *MockAccountKeeperMockRecorder { return m.recorder } +// BytesToString mocks base method. +func (m *MockAccountKeeper) BytesToString(bz []byte) (string, error) { + m.ctrl.T.Helper() + ret := m.ctrl.Call(m, "BytesToString", bz) + ret0, _ := ret[0].(string) + ret1, _ := ret[1].(error) + return ret0, ret1 +} + +// BytesToString indicates an expected call of BytesToString. +func (mr *MockAccountKeeperMockRecorder) BytesToString(bz interface{}) *gomock.Call { + mr.mock.ctrl.T.Helper() + return mr.mock.ctrl.RecordCallWithMethodType(mr.mock, "BytesToString", reflect.TypeOf((*MockAccountKeeper)(nil).BytesToString), bz) +} + // GetAccount mocks base method. -func (m *MockAccountKeeper) GetAccount(arg0 types.Context, arg1 types.AccAddress) types.AccountI { +func (m *MockAccountKeeper) GetAccount(arg0 context.Context, arg1 types.AccAddress) types.AccountI { m.ctrl.T.Helper() ret := m.ctrl.Call(m, "GetAccount", arg0, arg1) ret0, _ := ret[0].(types.AccountI) @@ -51,7 +66,7 @@ func (mr *MockAccountKeeperMockRecorder) GetAccount(arg0, arg1 interface{}) *gom } // NewAccount mocks base method. -func (m *MockAccountKeeper) NewAccount(arg0 types.Context, arg1 types.AccountI) types.AccountI { +func (m *MockAccountKeeper) NewAccount(arg0 context.Context, arg1 types.AccountI) types.AccountI { m.ctrl.T.Helper() ret := m.ctrl.Call(m, "NewAccount", arg0, arg1) ret0, _ := ret[0].(types.AccountI) @@ -65,7 +80,7 @@ func (mr *MockAccountKeeperMockRecorder) NewAccount(arg0, arg1 interface{}) *gom } // RemoveAccount mocks base method. -func (m *MockAccountKeeper) RemoveAccount(ctx types.Context, acc types.AccountI) { +func (m *MockAccountKeeper) RemoveAccount(ctx context.Context, acc types.AccountI) { m.ctrl.T.Helper() m.ctrl.Call(m, "RemoveAccount", ctx, acc) } @@ -77,7 +92,7 @@ func (mr *MockAccountKeeperMockRecorder) RemoveAccount(ctx, acc interface{}) *go } // SetAccount mocks base method. -func (m *MockAccountKeeper) SetAccount(arg0 types.Context, arg1 types.AccountI) { +func (m *MockAccountKeeper) SetAccount(arg0 context.Context, arg1 types.AccountI) { m.ctrl.T.Helper() m.ctrl.Call(m, "SetAccount", arg0, arg1) } @@ -88,6 +103,21 @@ func (mr *MockAccountKeeperMockRecorder) SetAccount(arg0, arg1 interface{}) *gom return mr.mock.ctrl.RecordCallWithMethodType(mr.mock, "SetAccount", reflect.TypeOf((*MockAccountKeeper)(nil).SetAccount), arg0, arg1) } +// StringToBytes mocks base method. +func (m *MockAccountKeeper) StringToBytes(text string) ([]byte, error) { + m.ctrl.T.Helper() + ret := m.ctrl.Call(m, "StringToBytes", text) + ret0, _ := ret[0].([]byte) + ret1, _ := ret[1].(error) + return ret0, ret1 +} + +// StringToBytes indicates an expected call of StringToBytes. +func (mr *MockAccountKeeperMockRecorder) StringToBytes(text interface{}) *gomock.Call { + mr.mock.ctrl.T.Helper() + return mr.mock.ctrl.RecordCallWithMethodType(mr.mock, "StringToBytes", reflect.TypeOf((*MockAccountKeeper)(nil).StringToBytes), text) +} + // MockBankKeeper is a mock of BankKeeper interface. type MockBankKeeper struct { ctrl *gomock.Controller diff --git a/x/group/types.go b/x/group/types.go index 9b0a84f35982..529b5be66d24 100644 --- a/x/group/types.go +++ b/x/group/types.go @@ -51,7 +51,7 @@ type DecisionPolicy interface { var _ DecisionPolicy = &ThresholdDecisionPolicy{} // NewThresholdDecisionPolicy creates a threshold DecisionPolicy -func NewThresholdDecisionPolicy(threshold string, votingPeriod time.Duration, minExecutionPeriod time.Duration) DecisionPolicy { +func NewThresholdDecisionPolicy(threshold string, votingPeriod, minExecutionPeriod time.Duration) DecisionPolicy { return &ThresholdDecisionPolicy{threshold, &DecisionPolicyWindows{votingPeriod, minExecutionPeriod}} } @@ -156,7 +156,7 @@ func (p *ThresholdDecisionPolicy) Validate(g GroupInfo, config Config) error { var _ DecisionPolicy = &PercentageDecisionPolicy{} // NewPercentageDecisionPolicy creates a new percentage DecisionPolicy -func NewPercentageDecisionPolicy(percentage string, votingPeriod time.Duration, executionPeriod time.Duration) DecisionPolicy { +func NewPercentageDecisionPolicy(percentage string, votingPeriod, executionPeriod time.Duration) DecisionPolicy { return &PercentageDecisionPolicy{percentage, &DecisionPolicyWindows{votingPeriod, executionPeriod}} } @@ -364,10 +364,14 @@ func (g GroupMember) ValidateBasic() error { return errorsmod.Wrap(errors.ErrEmpty, "group member's group id") } - err := MemberToMemberRequest(g.Member).ValidateBasic() - if err != nil { - return errorsmod.Wrap(err, "group member") + if _, err := sdk.AccAddressFromBech32(g.Member.Address); err != nil { + return errorsmod.Wrap(err, "group member's address") + } + + if _, err := math.NewNonNegativeDecFromString(g.Member.Weight); err != nil { + return errorsmod.Wrap(err, "weight must be non negative") } + return nil } diff --git a/x/group/typesupport.go b/x/group/typesupport.go deleted file mode 100644 index c1108606c9e4..000000000000 --- a/x/group/typesupport.go +++ /dev/null @@ -1,49 +0,0 @@ -package group - -import ( - errorsmod "cosmossdk.io/errors" - - sdk "github.com/cosmos/cosmos-sdk/types" - "github.com/cosmos/cosmos-sdk/x/group/errors" -) - -// MemberRequests defines a repeated slice of MemberRequest objects. -type MemberRequests struct { - Members []MemberRequest -} - -// ValidateBasic performs stateless validation on an array of members. On top -// of validating each member individually, it also makes sure there are no -// duplicate addresses. -func (ms MemberRequests) ValidateBasic() error { - index := make(map[string]struct{}, len(ms.Members)) - for i := range ms.Members { - member := ms.Members[i] - if err := member.ValidateBasic(); err != nil { - return err - } - addr := member.Address - if _, exists := index[addr]; exists { - return errorsmod.Wrapf(errors.ErrDuplicate, "address: %s", addr) - } - index[addr] = struct{}{} - } - return nil -} - -type accAddresses []sdk.AccAddress - -// ValidateBasic verifies that there's no duplicate address. -// Individual account address validation has to be done separately. -func (a accAddresses) ValidateBasic() error { - index := make(map[string]struct{}, len(a)) - for i := range a { - accAddr := a[i] - addr := string(accAddr) - if _, exists := index[addr]; exists { - return errorsmod.Wrapf(errors.ErrDuplicate, "address: %s", accAddr.String()) - } - index[addr] = struct{}{} - } - return nil -} diff --git a/x/mint/README.md b/x/mint/README.md index 3b4966c2d04b..900615bbabb3 100644 --- a/x/mint/README.md +++ b/x/mint/README.md @@ -83,7 +83,7 @@ inflation calculation logic is needed, this can be achieved by defining and passing a function that matches `InflationCalculationFn`'s signature. ```go -type InflationCalculationFn func(ctx sdk.Context, minter Minter, params Params, bondedRatio sdk.Dec) sdk.Dec +type InflationCalculationFn func(ctx sdk.Context, minter Minter, params Params, bondedRatio math.LegacyDec) math.LegacyDec ``` #### NextInflationRate @@ -95,7 +95,7 @@ possible is defined to be 13% per year, however the annual inflation is capped as between 7% and 20%. ```go -NextInflationRate(params Params, bondedRatio sdk.Dec) (inflation sdk.Dec) { +NextInflationRate(params Params, bondedRatio math.LegacyDec) (inflation math.LegacyDec) { inflationRateChangePerYear = (1 - bondedRatio/params.GoalBonded) * params.InflationRateChange inflationRateChange = inflationRateChangePerYear/blocksPerYr @@ -118,7 +118,7 @@ Calculate the annual provisions based on current total supply and inflation rate. This parameter is calculated once per block. ```go -NextAnnualProvisions(params Params, totalSupply sdk.Dec) (provisions sdk.Dec) { +NextAnnualProvisions(params Params, totalSupply math.LegacyDec) (provisions math.LegacyDec) { return Inflation * totalSupply ``` diff --git a/x/mint/keeper/genesis_test.go b/x/mint/keeper/genesis_test.go index 362de7f404cb..af777b7d96cc 100644 --- a/x/mint/keeper/genesis_test.go +++ b/x/mint/keeper/genesis_test.go @@ -59,13 +59,13 @@ func (s *GenesisTestSuite) SetupTest() { func (s *GenesisTestSuite) TestImportExportGenesis() { genesisState := types.DefaultGenesisState() - genesisState.Minter = types.NewMinter(sdk.NewDecWithPrec(20, 2), math.LegacyNewDec(1)) + genesisState.Minter = types.NewMinter(math.LegacyNewDecWithPrec(20, 2), math.LegacyNewDec(1)) genesisState.Params = types.NewParams( "testDenom", - sdk.NewDecWithPrec(15, 2), - sdk.NewDecWithPrec(22, 2), - sdk.NewDecWithPrec(9, 2), - sdk.NewDecWithPrec(69, 2), + math.LegacyNewDecWithPrec(15, 2), + math.LegacyNewDecWithPrec(22, 2), + math.LegacyNewDecWithPrec(9, 2), + math.LegacyNewDecWithPrec(69, 2), uint64(60*60*8766/5), ) diff --git a/x/mint/keeper/keeper.go b/x/mint/keeper/keeper.go index b21b6be19e0e..56c0664dd90a 100644 --- a/x/mint/keeper/keeper.go +++ b/x/mint/keeper/keeper.go @@ -81,13 +81,9 @@ func (k Keeper) SetMinter(ctx sdk.Context, minter types.Minter) { } // SetParams sets the x/mint module parameters. -func (k Keeper) SetParams(ctx sdk.Context, p types.Params) error { - if err := p.Validate(); err != nil { - return err - } - +func (k Keeper) SetParams(ctx sdk.Context, params types.Params) error { store := ctx.KVStore(k.storeKey) - bz := k.cdc.MustMarshal(&p) + bz := k.cdc.MustMarshal(¶ms) store.Set(types.ParamsKey, bz) return nil diff --git a/x/mint/keeper/keeper_test.go b/x/mint/keeper/keeper_test.go index 137dbbc5d23c..2dcd5e7506a0 100644 --- a/x/mint/keeper/keeper_test.go +++ b/x/mint/keeper/keeper_test.go @@ -6,6 +6,7 @@ import ( "github.com/golang/mock/gomock" "github.com/stretchr/testify/suite" + sdkmath "cosmossdk.io/math" storetypes "cosmossdk.io/store/types" "github.com/cosmos/cosmos-sdk/testutil" @@ -76,25 +77,25 @@ func (s *IntegrationTestSuite) TestParams() { expectErr bool }{ { - name: "set invalid params", + name: "set invalid params (⚠️ not validated in keeper)", input: types.Params{ MintDenom: sdk.DefaultBondDenom, - InflationRateChange: sdk.NewDecWithPrec(-13, 2), - InflationMax: sdk.NewDecWithPrec(20, 2), - InflationMin: sdk.NewDecWithPrec(7, 2), - GoalBonded: sdk.NewDecWithPrec(67, 2), + InflationRateChange: sdkmath.LegacyNewDecWithPrec(-13, 2), + InflationMax: sdkmath.LegacyNewDecWithPrec(20, 2), + InflationMin: sdkmath.LegacyNewDecWithPrec(7, 2), + GoalBonded: sdkmath.LegacyNewDecWithPrec(67, 2), BlocksPerYear: uint64(60 * 60 * 8766 / 5), }, - expectErr: true, + expectErr: false, }, { name: "set full valid params", input: types.Params{ MintDenom: sdk.DefaultBondDenom, - InflationRateChange: sdk.NewDecWithPrec(8, 2), - InflationMax: sdk.NewDecWithPrec(20, 2), - InflationMin: sdk.NewDecWithPrec(2, 2), - GoalBonded: sdk.NewDecWithPrec(37, 2), + InflationRateChange: sdkmath.LegacyNewDecWithPrec(8, 2), + InflationMax: sdkmath.LegacyNewDecWithPrec(20, 2), + InflationMin: sdkmath.LegacyNewDecWithPrec(2, 2), + GoalBonded: sdkmath.LegacyNewDecWithPrec(37, 2), BlocksPerYear: uint64(60 * 60 * 8766 / 5), }, expectErr: false, @@ -125,16 +126,16 @@ func (s *IntegrationTestSuite) TestAliasFunctions() { s.stakingKeeper.EXPECT().StakingTokenSupply(s.ctx).Return(stakingTokenSupply) s.Require().Equal(s.mintKeeper.StakingTokenSupply(s.ctx), stakingTokenSupply) - bondedRatio := sdk.NewDecWithPrec(15, 2) + bondedRatio := sdkmath.LegacyNewDecWithPrec(15, 2) s.stakingKeeper.EXPECT().BondedRatio(s.ctx).Return(bondedRatio) s.Require().Equal(s.mintKeeper.BondedRatio(s.ctx), bondedRatio) - coins := sdk.NewCoins(sdk.NewCoin("stake", sdk.NewInt(1000000))) + coins := sdk.NewCoins(sdk.NewCoin("stake", sdkmath.NewInt(1000000))) s.bankKeeper.EXPECT().MintCoins(s.ctx, types.ModuleName, coins).Return(nil) s.Require().Equal(s.mintKeeper.MintCoins(s.ctx, sdk.NewCoins()), nil) s.Require().Nil(s.mintKeeper.MintCoins(s.ctx, coins)) - fees := sdk.NewCoins(sdk.NewCoin("stake", sdk.NewInt(1000))) + fees := sdk.NewCoins(sdk.NewCoin("stake", sdkmath.NewInt(1000))) s.bankKeeper.EXPECT().SendCoinsFromModuleToModule(s.ctx, types.ModuleName, authtypes.FeeCollectorName, fees).Return(nil) s.Require().Nil(s.mintKeeper.AddCollectedFees(s.ctx, fees)) } diff --git a/x/mint/keeper/msg_server.go b/x/mint/keeper/msg_server.go index f65e21c5191b..20f9848f6416 100644 --- a/x/mint/keeper/msg_server.go +++ b/x/mint/keeper/msg_server.go @@ -25,13 +25,17 @@ func NewMsgServerImpl(k Keeper) types.MsgServer { } // UpdateParams updates the params. -func (ms msgServer) UpdateParams(goCtx context.Context, req *types.MsgUpdateParams) (*types.MsgUpdateParamsResponse, error) { - if ms.authority != req.Authority { - return nil, errors.Wrapf(govtypes.ErrInvalidSigner, "invalid authority; expected %s, got %s", ms.authority, req.Authority) +func (ms msgServer) UpdateParams(goCtx context.Context, msg *types.MsgUpdateParams) (*types.MsgUpdateParamsResponse, error) { + if ms.authority != msg.Authority { + return nil, errors.Wrapf(govtypes.ErrInvalidSigner, "invalid authority; expected %s, got %s", ms.authority, msg.Authority) + } + + if err := msg.Params.Validate(); err != nil { + return nil, err } ctx := sdk.UnwrapSDKContext(goCtx) - if err := ms.SetParams(ctx, req.Params); err != nil { + if err := ms.SetParams(ctx, msg.Params); err != nil { return nil, err } diff --git a/x/mint/keeper/msg_server_test.go b/x/mint/keeper/msg_server_test.go index f709a030c121..ecdf76dc6131 100644 --- a/x/mint/keeper/msg_server_test.go +++ b/x/mint/keeper/msg_server_test.go @@ -1,6 +1,8 @@ package keeper_test import ( + sdkmath "cosmossdk.io/math" + sdk "github.com/cosmos/cosmos-sdk/types" "github.com/cosmos/cosmos-sdk/x/mint/types" ) @@ -12,22 +14,29 @@ func (s *IntegrationTestSuite) TestUpdateParams() { expectErr bool }{ { - name: "set invalid authority", + name: "set invalid authority (not an address)", request: &types.MsgUpdateParams{ Authority: "foo", }, expectErr: true, }, + { + name: "set invalid authority (not defined authority)", + request: &types.MsgUpdateParams{ + Authority: "cosmos139f7kncmglres2nf3h4hc4tade85ekfr8sulz5", + }, + expectErr: true, + }, { name: "set invalid params", request: &types.MsgUpdateParams{ Authority: s.mintKeeper.GetAuthority(), Params: types.Params{ MintDenom: sdk.DefaultBondDenom, - InflationRateChange: sdk.NewDecWithPrec(-13, 2), - InflationMax: sdk.NewDecWithPrec(20, 2), - InflationMin: sdk.NewDecWithPrec(7, 2), - GoalBonded: sdk.NewDecWithPrec(67, 2), + InflationRateChange: sdkmath.LegacyNewDecWithPrec(-13, 2), + InflationMax: sdkmath.LegacyNewDecWithPrec(20, 2), + InflationMin: sdkmath.LegacyNewDecWithPrec(7, 2), + GoalBonded: sdkmath.LegacyNewDecWithPrec(67, 2), BlocksPerYear: uint64(60 * 60 * 8766 / 5), }, }, @@ -39,10 +48,10 @@ func (s *IntegrationTestSuite) TestUpdateParams() { Authority: s.mintKeeper.GetAuthority(), Params: types.Params{ MintDenom: sdk.DefaultBondDenom, - InflationRateChange: sdk.NewDecWithPrec(8, 2), - InflationMax: sdk.NewDecWithPrec(20, 2), - InflationMin: sdk.NewDecWithPrec(2, 2), - GoalBonded: sdk.NewDecWithPrec(37, 2), + InflationRateChange: sdkmath.LegacyNewDecWithPrec(8, 2), + InflationMax: sdkmath.LegacyNewDecWithPrec(20, 2), + InflationMin: sdkmath.LegacyNewDecWithPrec(2, 2), + GoalBonded: sdkmath.LegacyNewDecWithPrec(37, 2), BlocksPerYear: uint64(60 * 60 * 8766 / 5), }, }, diff --git a/x/mint/module.go b/x/mint/module.go index 614367acff1f..ae5bda3dd2cd 100644 --- a/x/mint/module.go +++ b/x/mint/module.go @@ -216,8 +216,7 @@ func init() { ) } -//nolint:revive -type MintInputs struct { +type ModuleInputs struct { depinject.In ModuleKey depinject.OwnModuleKey @@ -234,15 +233,14 @@ type MintInputs struct { StakingKeeper types.StakingKeeper } -//nolint:revive -type MintOutputs struct { +type ModuleOutputs struct { depinject.Out MintKeeper keeper.Keeper Module appmodule.AppModule } -func ProvideModule(in MintInputs) MintOutputs { +func ProvideModule(in ModuleInputs) ModuleOutputs { feeCollectorName := in.Config.FeeCollectorName if feeCollectorName == "" { feeCollectorName = authtypes.FeeCollectorName @@ -267,5 +265,5 @@ func ProvideModule(in MintInputs) MintOutputs { // when no inflation calculation function is provided it will use the default types.DefaultInflationCalculationFn m := NewAppModule(in.Cdc, k, in.AccountKeeper, in.InflationCalculationFn, in.LegacySubspace) - return MintOutputs{MintKeeper: k, Module: m} + return ModuleOutputs{MintKeeper: k, Module: m} } diff --git a/x/mint/simulation/genesis.go b/x/mint/simulation/genesis.go index 5de00c5c89fd..f543ffc27626 100644 --- a/x/mint/simulation/genesis.go +++ b/x/mint/simulation/genesis.go @@ -6,7 +6,6 @@ import ( "math/rand" "cosmossdk.io/math" - sdk "github.com/cosmos/cosmos-sdk/types" "github.com/cosmos/cosmos-sdk/types/module" "github.com/cosmos/cosmos-sdk/x/mint/types" ) @@ -22,58 +21,58 @@ const ( // GenInflation randomized Inflation func GenInflation(r *rand.Rand) math.LegacyDec { - return sdk.NewDecWithPrec(int64(r.Intn(99)), 2) + return math.LegacyNewDecWithPrec(int64(r.Intn(99)), 2) } // GenInflationRateChange randomized InflationRateChange func GenInflationRateChange(r *rand.Rand) math.LegacyDec { - return sdk.NewDecWithPrec(int64(r.Intn(99)), 2) + return math.LegacyNewDecWithPrec(int64(r.Intn(99)), 2) } // GenInflationMax randomized InflationMax func GenInflationMax(r *rand.Rand) math.LegacyDec { - return sdk.NewDecWithPrec(20, 2) + return math.LegacyNewDecWithPrec(20, 2) } // GenInflationMin randomized InflationMin func GenInflationMin(r *rand.Rand) math.LegacyDec { - return sdk.NewDecWithPrec(7, 2) + return math.LegacyNewDecWithPrec(7, 2) } // GenGoalBonded randomized GoalBonded func GenGoalBonded(r *rand.Rand) math.LegacyDec { - return sdk.NewDecWithPrec(67, 2) + return math.LegacyNewDecWithPrec(67, 2) } // RandomizedGenState generates a random GenesisState for mint func RandomizedGenState(simState *module.SimulationState) { // minter - var inflation sdk.Dec + var inflation math.LegacyDec simState.AppParams.GetOrGenerate( simState.Cdc, Inflation, &inflation, simState.Rand, func(r *rand.Rand) { inflation = GenInflation(r) }, ) // params - var inflationRateChange sdk.Dec + var inflationRateChange math.LegacyDec simState.AppParams.GetOrGenerate( simState.Cdc, InflationRateChange, &inflationRateChange, simState.Rand, func(r *rand.Rand) { inflationRateChange = GenInflationRateChange(r) }, ) - var inflationMax sdk.Dec + var inflationMax math.LegacyDec simState.AppParams.GetOrGenerate( simState.Cdc, InflationMax, &inflationMax, simState.Rand, func(r *rand.Rand) { inflationMax = GenInflationMax(r) }, ) - var inflationMin sdk.Dec + var inflationMin math.LegacyDec simState.AppParams.GetOrGenerate( simState.Cdc, InflationMin, &inflationMin, simState.Rand, func(r *rand.Rand) { inflationMin = GenInflationMin(r) }, ) - var goalBonded sdk.Dec + var goalBonded math.LegacyDec simState.AppParams.GetOrGenerate( simState.Cdc, GoalBonded, &goalBonded, simState.Rand, func(r *rand.Rand) { goalBonded = GenGoalBonded(r) }, diff --git a/x/mint/simulation/genesis_test.go b/x/mint/simulation/genesis_test.go index c1bd6141adec..c1938012bbe2 100644 --- a/x/mint/simulation/genesis_test.go +++ b/x/mint/simulation/genesis_test.go @@ -41,9 +41,9 @@ func TestRandomizedGenState(t *testing.T) { var mintGenesis types.GenesisState simState.Cdc.MustUnmarshalJSON(simState.GenState[types.ModuleName], &mintGenesis) - dec1, _ := sdk.NewDecFromStr("0.670000000000000000") - dec2, _ := sdk.NewDecFromStr("0.200000000000000000") - dec3, _ := sdk.NewDecFromStr("0.070000000000000000") + dec1, _ := math.LegacyNewDecFromStr("0.670000000000000000") + dec2, _ := math.LegacyNewDecFromStr("0.200000000000000000") + dec3, _ := math.LegacyNewDecFromStr("0.070000000000000000") require.Equal(t, uint64(6311520), mintGenesis.Params.BlocksPerYear) require.Equal(t, dec1, mintGenesis.Params.GoalBonded) diff --git a/x/mint/simulation/proposals.go b/x/mint/simulation/proposals.go index 129658adcf22..f39a150585a7 100644 --- a/x/mint/simulation/proposals.go +++ b/x/mint/simulation/proposals.go @@ -3,6 +3,8 @@ package simulation import ( "math/rand" + sdkmath "cosmossdk.io/math" + sdk "github.com/cosmos/cosmos-sdk/types" "github.com/cosmos/cosmos-sdk/types/address" simtypes "github.com/cosmos/cosmos-sdk/types/simulation" @@ -14,7 +16,7 @@ import ( const ( DefaultWeightMsgUpdateParams int = 100 - OpWeightMsgUpdateParams = "op_weight_msg_update_params" //nolint:gosec + OpWeightMsgUpdateParams = "op_weight_msg_update_params" ) // ProposalMsgs defines the module weighted proposals' contents @@ -35,10 +37,10 @@ func SimulateMsgUpdateParams(r *rand.Rand, _ sdk.Context, _ []simtypes.Account) params := types.DefaultParams() params.BlocksPerYear = uint64(simtypes.RandIntBetween(r, 1, 1000000)) - params.GoalBonded = sdk.NewDecWithPrec(int64(simtypes.RandIntBetween(r, 1, 100)), 2) - params.InflationMin = sdk.NewDecWithPrec(int64(simtypes.RandIntBetween(r, 1, 50)), 2) - params.InflationMax = sdk.NewDecWithPrec(int64(simtypes.RandIntBetween(r, 50, 100)), 2) - params.InflationRateChange = sdk.NewDecWithPrec(int64(simtypes.RandIntBetween(r, 1, 100)), 2) + params.GoalBonded = sdkmath.LegacyNewDecWithPrec(int64(simtypes.RandIntBetween(r, 1, 100)), 2) + params.InflationMin = sdkmath.LegacyNewDecWithPrec(int64(simtypes.RandIntBetween(r, 1, 50)), 2) + params.InflationMax = sdkmath.LegacyNewDecWithPrec(int64(simtypes.RandIntBetween(r, 50, 100)), 2) + params.InflationRateChange = sdkmath.LegacyNewDecWithPrec(int64(simtypes.RandIntBetween(r, 1, 100)), 2) params.MintDenom = simtypes.RandStringOfLength(r, 10) return &types.MsgUpdateParams{ diff --git a/x/mint/simulation/proposals_test.go b/x/mint/simulation/proposals_test.go index 9b3aef1660c8..0dc21ac2b3c6 100644 --- a/x/mint/simulation/proposals_test.go +++ b/x/mint/simulation/proposals_test.go @@ -4,6 +4,7 @@ import ( "math/rand" "testing" + sdkmath "cosmossdk.io/math" cmtproto "github.com/cometbft/cometbft/proto/tendermint/types" "gotest.tools/v3/assert" @@ -38,9 +39,9 @@ func TestProposalMsgs(t *testing.T) { assert.Equal(t, sdk.AccAddress(address.Module("gov")).String(), msgUpdateParams.Authority) assert.Equal(t, uint64(122877), msgUpdateParams.Params.BlocksPerYear) - assert.DeepEqual(t, sdk.NewDecWithPrec(95, 2), msgUpdateParams.Params.GoalBonded) - assert.DeepEqual(t, sdk.NewDecWithPrec(94, 2), msgUpdateParams.Params.InflationMax) - assert.DeepEqual(t, sdk.NewDecWithPrec(23, 2), msgUpdateParams.Params.InflationMin) - assert.DeepEqual(t, sdk.NewDecWithPrec(89, 2), msgUpdateParams.Params.InflationRateChange) + assert.DeepEqual(t, sdkmath.LegacyNewDecWithPrec(95, 2), msgUpdateParams.Params.GoalBonded) + assert.DeepEqual(t, sdkmath.LegacyNewDecWithPrec(94, 2), msgUpdateParams.Params.InflationMax) + assert.DeepEqual(t, sdkmath.LegacyNewDecWithPrec(23, 2), msgUpdateParams.Params.InflationMin) + assert.DeepEqual(t, sdkmath.LegacyNewDecWithPrec(89, 2), msgUpdateParams.Params.InflationRateChange) assert.Equal(t, "XhhuTSkuxK", msgUpdateParams.Params.MintDenom) } diff --git a/x/mint/testutil/expected_keepers_mocks.go b/x/mint/testutil/expected_keepers_mocks.go index 47af766c6b9b..6504d5122930 100644 --- a/x/mint/testutil/expected_keepers_mocks.go +++ b/x/mint/testutil/expected_keepers_mocks.go @@ -5,6 +5,7 @@ package testutil import ( + context "context" reflect "reflect" math "cosmossdk.io/math" @@ -36,10 +37,10 @@ func (m *MockStakingKeeper) EXPECT() *MockStakingKeeperMockRecorder { } // BondedRatio mocks base method. -func (m *MockStakingKeeper) BondedRatio(ctx types.Context) types.Dec { +func (m *MockStakingKeeper) BondedRatio(ctx types.Context) math.LegacyDec { m.ctrl.T.Helper() ret := m.ctrl.Call(m, "BondedRatio", ctx) - ret0, _ := ret[0].(types.Dec) + ret0, _ := ret[0].(math.LegacyDec) return ret0 } @@ -87,7 +88,7 @@ func (m *MockAccountKeeper) EXPECT() *MockAccountKeeperMockRecorder { } // GetModuleAccount mocks base method. -func (m *MockAccountKeeper) GetModuleAccount(ctx types.Context, moduleName string) types.ModuleAccountI { +func (m *MockAccountKeeper) GetModuleAccount(ctx context.Context, moduleName string) types.ModuleAccountI { m.ctrl.T.Helper() ret := m.ctrl.Call(m, "GetModuleAccount", ctx, moduleName) ret0, _ := ret[0].(types.ModuleAccountI) @@ -115,7 +116,7 @@ func (mr *MockAccountKeeperMockRecorder) GetModuleAddress(name interface{}) *gom } // SetModuleAccount mocks base method. -func (m *MockAccountKeeper) SetModuleAccount(arg0 types.Context, arg1 types.ModuleAccountI) { +func (m *MockAccountKeeper) SetModuleAccount(arg0 context.Context, arg1 types.ModuleAccountI) { m.ctrl.T.Helper() m.ctrl.Call(m, "SetModuleAccount", arg0, arg1) } diff --git a/x/mint/types/expected_keepers.go b/x/mint/types/expected_keepers.go index 46c2f4ed93a0..af4bd54d05f4 100644 --- a/x/mint/types/expected_keepers.go +++ b/x/mint/types/expected_keepers.go @@ -1,6 +1,8 @@ package types // noalias import ( + context "context" + "cosmossdk.io/math" sdk "github.com/cosmos/cosmos-sdk/types" @@ -9,7 +11,7 @@ import ( // StakingKeeper defines the expected staking keeper type StakingKeeper interface { StakingTokenSupply(ctx sdk.Context) math.Int - BondedRatio(ctx sdk.Context) sdk.Dec + BondedRatio(ctx sdk.Context) math.LegacyDec } // AccountKeeper defines the contract required for account APIs. @@ -17,8 +19,8 @@ type AccountKeeper interface { GetModuleAddress(name string) sdk.AccAddress // TODO remove with genesis 2-phases refactor https://github.com/cosmos/cosmos-sdk/issues/2862 - SetModuleAccount(sdk.Context, sdk.ModuleAccountI) - GetModuleAccount(ctx sdk.Context, moduleName string) sdk.ModuleAccountI + SetModuleAccount(context.Context, sdk.ModuleAccountI) + GetModuleAccount(ctx context.Context, moduleName string) sdk.ModuleAccountI } // BankKeeper defines the contract needed to be fulfilled for banking and supply diff --git a/x/mint/types/genesis.go b/x/mint/types/genesis.go index d32c573484b7..dd710b61bc79 100644 --- a/x/mint/types/genesis.go +++ b/x/mint/types/genesis.go @@ -10,10 +10,10 @@ import ( // bondedRatio and returns the newly calculated inflation rate. // It can be used to specify a custom inflation calculation logic, instead of relying on the // default logic provided by the sdk. -type InflationCalculationFn func(ctx sdk.Context, minter Minter, params Params, bondedRatio sdk.Dec) sdk.Dec +type InflationCalculationFn func(ctx sdk.Context, minter Minter, params Params, bondedRatio math.LegacyDec) math.LegacyDec // DefaultInflationCalculationFn is the default function used to calculate inflation. -func DefaultInflationCalculationFn(_ sdk.Context, minter Minter, params Params, bondedRatio sdk.Dec) math.LegacyDec { +func DefaultInflationCalculationFn(_ sdk.Context, minter Minter, params Params, bondedRatio math.LegacyDec) math.LegacyDec { return minter.NextInflationRate(params, bondedRatio) } diff --git a/x/mint/types/minter.go b/x/mint/types/minter.go index 1f5db5400bf9..349198a43462 100644 --- a/x/mint/types/minter.go +++ b/x/mint/types/minter.go @@ -10,7 +10,7 @@ import ( // NewMinter returns a new Minter object with the given inflation and annual // provisions values. -func NewMinter(inflation, annualProvisions sdk.Dec) Minter { +func NewMinter(inflation, annualProvisions math.LegacyDec) Minter { return Minter{ Inflation: inflation, AnnualProvisions: annualProvisions, @@ -18,7 +18,7 @@ func NewMinter(inflation, annualProvisions sdk.Dec) Minter { } // InitialMinter returns an initial Minter object with a given inflation value. -func InitialMinter(inflation sdk.Dec) Minter { +func InitialMinter(inflation math.LegacyDec) Minter { return NewMinter( inflation, math.LegacyNewDec(0), @@ -29,7 +29,7 @@ func InitialMinter(inflation sdk.Dec) Minter { // which uses an inflation rate of 13%. func DefaultInitialMinter() Minter { return InitialMinter( - sdk.NewDecWithPrec(13, 2), + math.LegacyNewDecWithPrec(13, 2), ) } @@ -43,7 +43,7 @@ func ValidateMinter(minter Minter) error { } // NextInflationRate returns the new inflation rate for the next block. -func (m Minter) NextInflationRate(params Params, bondedRatio sdk.Dec) math.LegacyDec { +func (m Minter) NextInflationRate(params Params, bondedRatio math.LegacyDec) math.LegacyDec { // The target annual inflation rate is recalculated for each block. The inflation // is also subject to a rate change (positive or negative) depending on the // distance from the desired ratio (67%). The maximum rate change possible is @@ -77,6 +77,6 @@ func (m Minter) NextAnnualProvisions(_ Params, totalSupply math.Int) math.Legacy // BlockProvision returns the provisions for a block based on the annual // provisions rate. func (m Minter) BlockProvision(params Params) sdk.Coin { - provisionAmt := m.AnnualProvisions.QuoInt(sdk.NewInt(int64(params.BlocksPerYear))) + provisionAmt := m.AnnualProvisions.QuoInt(math.NewInt(int64(params.BlocksPerYear))) return sdk.NewCoin(params.MintDenom, provisionAmt.TruncateInt()) } diff --git a/x/mint/types/minter_test.go b/x/mint/types/minter_test.go index cd0c9f6da00e..d1f2a444dd14 100644 --- a/x/mint/types/minter_test.go +++ b/x/mint/types/minter_test.go @@ -19,34 +19,34 @@ func TestNextInflation(t *testing.T) { // inflationRateChangePerYear = (1- BondedRatio/ GoalBonded) * MaxInflationRateChange tests := []struct { - bondedRatio, setInflation, expChange sdk.Dec + bondedRatio, setInflation, expChange math.LegacyDec }{ // with 0% bonded atom supply the inflation should increase by InflationRateChange - {math.LegacyZeroDec(), sdk.NewDecWithPrec(7, 2), params.InflationRateChange.Quo(blocksPerYr)}, + {math.LegacyZeroDec(), math.LegacyNewDecWithPrec(7, 2), params.InflationRateChange.Quo(blocksPerYr)}, // 100% bonded, starting at 20% inflation and being reduced // (1 - (1/0.67))*(0.13/8667) { - math.LegacyOneDec(), sdk.NewDecWithPrec(20, 2), + math.LegacyOneDec(), math.LegacyNewDecWithPrec(20, 2), math.LegacyOneDec().Sub(math.LegacyOneDec().Quo(params.GoalBonded)).Mul(params.InflationRateChange).Quo(blocksPerYr), }, // 50% bonded, starting at 10% inflation and being increased { - sdk.NewDecWithPrec(5, 1), sdk.NewDecWithPrec(10, 2), - math.LegacyOneDec().Sub(sdk.NewDecWithPrec(5, 1).Quo(params.GoalBonded)).Mul(params.InflationRateChange).Quo(blocksPerYr), + math.LegacyNewDecWithPrec(5, 1), math.LegacyNewDecWithPrec(10, 2), + math.LegacyOneDec().Sub(math.LegacyNewDecWithPrec(5, 1).Quo(params.GoalBonded)).Mul(params.InflationRateChange).Quo(blocksPerYr), }, // test 7% minimum stop (testing with 100% bonded) - {math.LegacyOneDec(), sdk.NewDecWithPrec(7, 2), math.LegacyZeroDec()}, - {math.LegacyOneDec(), sdk.NewDecWithPrec(700000001, 10), sdk.NewDecWithPrec(-1, 10)}, + {math.LegacyOneDec(), math.LegacyNewDecWithPrec(7, 2), math.LegacyZeroDec()}, + {math.LegacyOneDec(), math.LegacyNewDecWithPrec(700000001, 10), math.LegacyNewDecWithPrec(-1, 10)}, // test 20% maximum stop (testing with 0% bonded) - {math.LegacyZeroDec(), sdk.NewDecWithPrec(20, 2), math.LegacyZeroDec()}, - {math.LegacyZeroDec(), sdk.NewDecWithPrec(1999999999, 10), sdk.NewDecWithPrec(1, 10)}, + {math.LegacyZeroDec(), math.LegacyNewDecWithPrec(20, 2), math.LegacyZeroDec()}, + {math.LegacyZeroDec(), math.LegacyNewDecWithPrec(1999999999, 10), math.LegacyNewDecWithPrec(1, 10)}, // perfect balance shouldn't change inflation - {sdk.NewDecWithPrec(67, 2), sdk.NewDecWithPrec(15, 2), math.LegacyZeroDec()}, + {math.LegacyNewDecWithPrec(67, 2), math.LegacyNewDecWithPrec(15, 2), math.LegacyZeroDec()}, } for i, tc := range tests { minter.Inflation = tc.setInflation @@ -60,7 +60,7 @@ func TestNextInflation(t *testing.T) { } func TestBlockProvision(t *testing.T) { - minter := InitialMinter(sdk.NewDecWithPrec(1, 1)) + minter := InitialMinter(math.LegacyNewDecWithPrec(1, 1)) params := DefaultParams() secondsPerYear := int64(60 * 60 * 8766) @@ -79,7 +79,7 @@ func TestBlockProvision(t *testing.T) { provisions := minter.BlockProvision(params) expProvisions := sdk.NewCoin(params.MintDenom, - sdk.NewInt(tc.expProvisions)) + math.NewInt(tc.expProvisions)) require.True(t, expProvisions.IsEqual(provisions), "test: %v\n\tExp: %v\n\tGot: %v\n", @@ -95,7 +95,7 @@ func TestBlockProvision(t *testing.T) { // BenchmarkBlockProvision-4 3000000 429 ns/op func BenchmarkBlockProvision(b *testing.B) { b.ReportAllocs() - minter := InitialMinter(sdk.NewDecWithPrec(1, 1)) + minter := InitialMinter(math.LegacyNewDecWithPrec(1, 1)) params := DefaultParams() s1 := rand.NewSource(100) @@ -112,9 +112,9 @@ func BenchmarkBlockProvision(b *testing.B) { // BenchmarkNextInflation-4 1000000 1828 ns/op func BenchmarkNextInflation(b *testing.B) { b.ReportAllocs() - minter := InitialMinter(sdk.NewDecWithPrec(1, 1)) + minter := InitialMinter(math.LegacyNewDecWithPrec(1, 1)) params := DefaultParams() - bondedRatio := sdk.NewDecWithPrec(1, 1) + bondedRatio := math.LegacyNewDecWithPrec(1, 1) // run the NextInflationRate function b.N times for n := 0; n < b.N; n++ { @@ -126,9 +126,9 @@ func BenchmarkNextInflation(b *testing.B) { // BenchmarkNextAnnualProvisions-4 5000000 251 ns/op func BenchmarkNextAnnualProvisions(b *testing.B) { b.ReportAllocs() - minter := InitialMinter(sdk.NewDecWithPrec(1, 1)) + minter := InitialMinter(math.LegacyNewDecWithPrec(1, 1)) params := DefaultParams() - totalSupply := sdk.NewInt(100000000000000) + totalSupply := math.NewInt(100000000000000) // run the NextAnnualProvisions function b.N times for n := 0; n < b.N; n++ { diff --git a/x/mint/types/msgs.go b/x/mint/types/msgs.go index 8ee7ee78cbde..5c9ba09663e9 100644 --- a/x/mint/types/msgs.go +++ b/x/mint/types/msgs.go @@ -1,8 +1,6 @@ package types import ( - "cosmossdk.io/errors" - sdk "github.com/cosmos/cosmos-sdk/types" "github.com/cosmos/cosmos-sdk/x/auth/migrations/legacytx" ) @@ -22,16 +20,3 @@ func (m MsgUpdateParams) GetSigners() []sdk.AccAddress { addr, _ := sdk.AccAddressFromBech32(m.Authority) return []sdk.AccAddress{addr} } - -// ValidateBasic does a sanity check on the provided data. -func (m MsgUpdateParams) ValidateBasic() error { - if _, err := sdk.AccAddressFromBech32(m.Authority); err != nil { - return errors.Wrap(err, "invalid authority address") - } - - if err := m.Params.Validate(); err != nil { - return err - } - - return nil -} diff --git a/x/mint/types/params.go b/x/mint/types/params.go index 375762b19762..4c31610d6f2a 100644 --- a/x/mint/types/params.go +++ b/x/mint/types/params.go @@ -11,7 +11,7 @@ import ( ) // NewParams returns Params instance with the given values. -func NewParams(mintDenom string, inflationRateChange, inflationMax, inflationMin, goalBonded sdk.Dec, blocksPerYear uint64) Params { +func NewParams(mintDenom string, inflationRateChange, inflationMax, inflationMin, goalBonded math.LegacyDec, blocksPerYear uint64) Params { return Params{ MintDenom: mintDenom, InflationRateChange: inflationRateChange, @@ -26,10 +26,10 @@ func NewParams(mintDenom string, inflationRateChange, inflationMax, inflationMin func DefaultParams() Params { return Params{ MintDenom: sdk.DefaultBondDenom, - InflationRateChange: sdk.NewDecWithPrec(13, 2), - InflationMax: sdk.NewDecWithPrec(20, 2), - InflationMin: sdk.NewDecWithPrec(7, 2), - GoalBonded: sdk.NewDecWithPrec(67, 2), + InflationRateChange: math.LegacyNewDecWithPrec(13, 2), + InflationMax: math.LegacyNewDecWithPrec(20, 2), + InflationMin: math.LegacyNewDecWithPrec(7, 2), + GoalBonded: math.LegacyNewDecWithPrec(67, 2), BlocksPerYear: uint64(60 * 60 * 8766 / 5), // assuming 5 second block times } } @@ -81,7 +81,7 @@ func validateMintDenom(i interface{}) error { } func validateInflationRateChange(i interface{}) error { - v, ok := i.(sdk.Dec) + v, ok := i.(math.LegacyDec) if !ok { return fmt.Errorf("invalid parameter type: %T", i) } @@ -100,7 +100,7 @@ func validateInflationRateChange(i interface{}) error { } func validateInflationMax(i interface{}) error { - v, ok := i.(sdk.Dec) + v, ok := i.(math.LegacyDec) if !ok { return fmt.Errorf("invalid parameter type: %T", i) } @@ -119,7 +119,7 @@ func validateInflationMax(i interface{}) error { } func validateInflationMin(i interface{}) error { - v, ok := i.(sdk.Dec) + v, ok := i.(math.LegacyDec) if !ok { return fmt.Errorf("invalid parameter type: %T", i) } @@ -138,7 +138,7 @@ func validateInflationMin(i interface{}) error { } func validateGoalBonded(i interface{}) error { - v, ok := i.(sdk.Dec) + v, ok := i.(math.LegacyDec) if !ok { return fmt.Errorf("invalid parameter type: %T", i) } diff --git a/x/nft/client/cli/query.go b/x/nft/client/cli/query.go index 63f567e761b0..a32489a76e3e 100644 --- a/x/nft/client/cli/query.go +++ b/x/nft/client/cli/query.go @@ -6,10 +6,10 @@ import ( "github.com/spf13/cobra" + "cosmossdk.io/core/address" "cosmossdk.io/x/nft" "github.com/cosmos/cosmos-sdk/client" "github.com/cosmos/cosmos-sdk/client/flags" - sdk "github.com/cosmos/cosmos-sdk/types" "github.com/cosmos/cosmos-sdk/types/errors" "github.com/cosmos/cosmos-sdk/version" ) @@ -21,7 +21,7 @@ const ( ) // GetQueryCmd returns the cli query commands for this module -func GetQueryCmd() *cobra.Command { +func GetQueryCmd(ac address.Codec) *cobra.Command { nftQueryCmd := &cobra.Command{ Use: nft.ModuleName, Short: "Querying commands for the nft module", @@ -35,7 +35,7 @@ func GetQueryCmd() *cobra.Command { GetCmdQueryClass(), GetCmdQueryClasses(), GetCmdQueryNFT(), - GetCmdQueryNFTs(), + GetCmdQueryNFTs(ac), GetCmdQueryOwner(), GetCmdQueryBalance(), GetCmdQuerySupply(), @@ -127,7 +127,7 @@ func GetCmdQueryNFT() *cobra.Command { } // GetCmdQueryNFTs implements the query nft command. -func GetCmdQueryNFTs() *cobra.Command { +func GetCmdQueryNFTs(ac address.Codec) *cobra.Command { cmd := &cobra.Command{ Use: "nfts", Short: "query all NFTs of a given class or owner address.", @@ -156,7 +156,7 @@ $ %s query %s nfts --owner= } if len(owner) > 0 { - if _, err := sdk.AccAddressFromBech32(owner); err != nil { + if _, err := ac.StringToBytes(owner); err != nil { return err } } diff --git a/x/nft/client/cli/query_test.go b/x/nft/client/cli/query_test.go index 8e7411982a51..d2e019df2d7a 100644 --- a/x/nft/client/cli/query_test.go +++ b/x/nft/client/cli/query_test.go @@ -9,6 +9,7 @@ import ( "cosmossdk.io/x/nft/client/cli" "github.com/cosmos/cosmos-sdk/client" "github.com/cosmos/cosmos-sdk/client/flags" + "github.com/cosmos/cosmos-sdk/codec/address" svrcmd "github.com/cosmos/cosmos-sdk/server/cmd" "github.com/cosmos/cosmos-sdk/testutil" clitestutil "github.com/cosmos/cosmos-sdk/testutil/cli" @@ -169,7 +170,7 @@ func (s *CLITestSuite) TestQueryNFTs() { for _, tc := range testCases { s.Run(tc.name, func() { - cmd := cli.GetCmdQueryNFTs() + cmd := cli.GetCmdQueryNFTs(address.NewBech32Codec("cosmos")) var args []string args = append(args, fmt.Sprintf("--%s=%s", cli.FlagClassID, tc.args.ClassID)) args = append(args, fmt.Sprintf("--%s=%s", cli.FlagOwner, tc.args.Owner)) diff --git a/x/nft/client/cli/tx.go b/x/nft/client/cli/tx.go index 2a314fe9797f..e6cdd2b7716e 100644 --- a/x/nft/client/cli/tx.go +++ b/x/nft/client/cli/tx.go @@ -46,6 +46,10 @@ func NewCmdSend() *cobra.Command { return err } + if args[0] == "" || args[1] == "" || args[2] == "" { + return fmt.Errorf("class-id, nft-id and receiver cannot be empty") + } + msg := nft.MsgSend{ ClassId: args[0], Id: args[1], diff --git a/x/nft/client/cli/tx_test.go b/x/nft/client/cli/tx_test.go index 5d78c89d699f..6fd09133f330 100644 --- a/x/nft/client/cli/tx_test.go +++ b/x/nft/client/cli/tx_test.go @@ -1,7 +1,6 @@ package cli_test import ( - "bytes" "context" "fmt" "io" @@ -94,7 +93,6 @@ func (s *CLITestSuite) SetupSuite() { WithChainID("test-chain") s.ctx = svrcmd.CreateExecuteContext(context.Background()) - var outBuf bytes.Buffer ctxGen := func() client.Context { bz, _ := s.encCfg.Codec.Marshal(&sdk.TxResponse{}) c := clitestutil.NewMockCometRPC(abci.ResponseQuery{ @@ -102,7 +100,7 @@ func (s *CLITestSuite) SetupSuite() { }) return s.baseCtx.WithClient(c) } - s.clientCtx = ctxGen().WithOutput(&outBuf) + s.clientCtx = ctxGen() cfg, err := network.DefaultConfigWithAppConfig(nfttestutil.AppConfig) s.Require().NoError(err) @@ -149,7 +147,7 @@ func (s *CLITestSuite) TestCLITxSend() { }, 0, true, - "empty class id", + "class-id, nft-id and receiver cannot be empty", }, { "nft id is empty", @@ -160,18 +158,18 @@ func (s *CLITestSuite) TestCLITxSend() { }, 0, true, - "empty nft id", + "class-id, nft-id and receiver cannot be empty", }, { - "invalid receiver address", + "empty receiver address", []string{ testClassID, testID, - "invalid receiver", + "", }, 0, true, - "Invalid receiver address", + "class-id, nft-id and receiver cannot be empty", }, { "valid transaction", @@ -189,7 +187,7 @@ func (s *CLITestSuite) TestCLITxSend() { for _, tc := range testCases { tc := tc s.Run(tc.name, func() { - args := append(tc.args, extraArgs...) //nolint:gocritic // false positive + args := append(tc.args, extraArgs...) cmd := cli.NewCmdSend() cmd.SetContext(s.ctx) cmd.SetArgs(args) diff --git a/x/nft/expected_keepers.go b/x/nft/expected_keepers.go index ec7976e294b9..98fd9890b7b8 100644 --- a/x/nft/expected_keepers.go +++ b/x/nft/expected_keepers.go @@ -1,6 +1,9 @@ package nft import ( + context "context" + + "cosmossdk.io/core/address" sdk "github.com/cosmos/cosmos-sdk/types" ) @@ -13,5 +16,7 @@ type BankKeeper interface { // AccountKeeper defines the contract required for account APIs. type AccountKeeper interface { GetModuleAddress(name string) sdk.AccAddress - GetAccount(ctx sdk.Context, addr sdk.AccAddress) sdk.AccountI + GetAccount(ctx context.Context, addr sdk.AccAddress) sdk.AccountI + + address.Codec } diff --git a/x/nft/genesis.go b/x/nft/genesis.go index 30b743a68696..14a71f7dbb3b 100644 --- a/x/nft/genesis.go +++ b/x/nft/genesis.go @@ -1,11 +1,11 @@ package nft import ( - sdk "github.com/cosmos/cosmos-sdk/types" + "cosmossdk.io/core/address" ) // ValidateGenesis checks that the given genesis state has no integrity issues -func ValidateGenesis(data GenesisState) error { +func ValidateGenesis(data GenesisState, ac address.Codec) error { for _, class := range data.Classes { if len(class.Id) == 0 { return ErrEmptyClassID @@ -16,7 +16,7 @@ func ValidateGenesis(data GenesisState) error { if len(nft.Id) == 0 { return ErrEmptyNFTID } - if _, err := sdk.AccAddressFromBech32(entry.Owner); err != nil { + if _, err := ac.StringToBytes(entry.Owner); err != nil { return err } } diff --git a/x/nft/go.mod b/x/nft/go.mod index bb1710e45ee2..c814319777c3 100644 --- a/x/nft/go.mod +++ b/x/nft/go.mod @@ -3,29 +3,29 @@ module cosmossdk.io/x/nft go 1.20 require ( - cosmossdk.io/api v0.3.2-0.20230313131911-55bf5d4efbe7 + cosmossdk.io/api v0.4.0 cosmossdk.io/core v0.6.1 cosmossdk.io/depinject v1.0.0-alpha.3 cosmossdk.io/errors v1.0.0-beta.7 cosmossdk.io/math v1.0.0 - cosmossdk.io/store v0.1.0-alpha.1 - github.com/cometbft/cometbft v0.37.0 + cosmossdk.io/store v0.1.0-alpha.1.0.20230328185921-37ba88872dbc + github.com/cometbft/cometbft v0.37.1-0.20230411132551-3a91d155e664 github.com/cosmos/cosmos-proto v1.0.0-beta.3 - github.com/cosmos/cosmos-sdk v0.46.0-beta2.0.20230321173237-fe77d4bca302 - github.com/cosmos/gogoproto v1.4.6 + github.com/cosmos/cosmos-sdk v0.46.0-beta2.0.20230419124727-7b10ada768f4 + github.com/cosmos/gogoproto v1.4.8 github.com/golang/mock v1.6.0 github.com/golang/protobuf v1.5.3 github.com/grpc-ecosystem/grpc-gateway v1.16.0 - github.com/spf13/cobra v1.6.1 + github.com/spf13/cobra v1.7.0 github.com/stretchr/testify v1.8.2 - google.golang.org/genproto v0.0.0-20230320184635-7606e756e683 + google.golang.org/genproto v0.0.0-20230410155749-daa745c078e1 google.golang.org/grpc v1.54.0 ) require ( - cosmossdk.io/collections v0.0.0-20230309163709-87da587416ba // indirect - cosmossdk.io/log v0.1.0 // indirect - cosmossdk.io/x/tx v0.3.1-0.20230321155358-6522dd1731b5 // indirect + cosmossdk.io/collections v0.1.0 // indirect + cosmossdk.io/log v1.0.0 // indirect + cosmossdk.io/x/tx v0.5.1-0.20230407182919-057d2e09bd63 // indirect filippo.io/edwards25519 v1.0.0 // indirect github.com/99designs/go-keychain v0.0.0-20191008050251-8e49817e8af4 // indirect github.com/99designs/keyring v1.2.1 // indirect @@ -40,7 +40,7 @@ require ( github.com/cespare/xxhash/v2 v2.2.0 // indirect github.com/cockroachdb/errors v1.9.1 // indirect github.com/cockroachdb/logtags v0.0.0-20230118201751-21c54148d20b // indirect - github.com/cockroachdb/pebble v0.0.0-20230315223031-1e5ddd10389e // indirect + github.com/cockroachdb/pebble v0.0.0-20230412222916-60cfeb46143b // indirect github.com/cockroachdb/redact v1.1.3 // indirect github.com/cometbft/cometbft-db v0.7.0 // indirect github.com/confio/ics23/go v0.9.0 // indirect @@ -53,7 +53,7 @@ require ( github.com/creachadair/taskgroup v0.4.2 // indirect github.com/danieljoos/wincred v1.1.2 // indirect github.com/davecgh/go-spew v1.1.1 // indirect - github.com/decred/dcrd/dcrec/secp256k1/v4 v4.1.0 // indirect + github.com/decred/dcrd/dcrec/secp256k1/v4 v4.2.0 // indirect github.com/desertbit/timer v0.0.0-20180107155436-c41aec40b27f // indirect github.com/dgraph-io/badger/v2 v2.2007.4 // indirect github.com/dgraph-io/ristretto v0.1.1 // indirect @@ -63,7 +63,7 @@ require ( github.com/fatih/color v1.15.0 // indirect github.com/felixge/httpsnoop v1.0.2 // indirect github.com/fsnotify/fsnotify v1.6.0 // indirect - github.com/getsentry/sentry-go v0.19.0 // indirect + github.com/getsentry/sentry-go v0.20.0 // indirect github.com/go-kit/kit v0.12.0 // indirect github.com/go-kit/log v0.2.1 // indirect github.com/go-logfmt/logfmt v0.6.0 // indirect @@ -93,12 +93,12 @@ require ( github.com/improbable-eng/grpc-web v0.15.0 // indirect github.com/inconshreveable/mousetrap v1.1.0 // indirect github.com/jmhodges/levigo v1.0.0 // indirect - github.com/klauspost/compress v1.16.3 // indirect + github.com/klauspost/compress v1.16.5 // indirect github.com/kr/pretty v0.3.1 // indirect github.com/kr/text v0.2.0 // indirect github.com/lib/pq v1.10.7 // indirect github.com/libp2p/go-buffer-pool v0.1.0 // indirect - github.com/linxGnu/grocksdb v1.7.15 // indirect + github.com/linxGnu/grocksdb v1.7.16 // indirect github.com/magiconair/properties v1.8.7 // indirect github.com/mattn/go-colorable v0.1.13 // indirect github.com/mattn/go-isatty v0.0.18 // indirect @@ -113,14 +113,14 @@ require ( github.com/petermattis/goid v0.0.0-20230317030725-371a4b8eda08 // indirect github.com/pkg/errors v0.9.1 // indirect github.com/pmezard/go-difflib v1.0.0 // indirect - github.com/prometheus/client_golang v1.14.0 // indirect + github.com/prometheus/client_golang v1.15.0 // indirect github.com/prometheus/client_model v0.3.0 // indirect github.com/prometheus/common v0.42.0 // indirect github.com/prometheus/procfs v0.9.0 // indirect github.com/rcrowley/go-metrics v0.0.0-20201227073835-cf1acfcdf475 // indirect - github.com/rogpeppe/go-internal v1.9.0 // indirect + github.com/rogpeppe/go-internal v1.10.0 // indirect github.com/rs/cors v1.8.3 // indirect - github.com/rs/zerolog v1.29.0 // indirect + github.com/rs/zerolog v1.29.1 // indirect github.com/sasha-s/go-deadlock v0.3.1 // indirect github.com/spf13/afero v1.9.3 // indirect github.com/spf13/cast v1.5.0 // indirect @@ -135,13 +135,13 @@ require ( github.com/zondax/hid v0.9.1 // indirect github.com/zondax/ledger-go v0.14.1 // indirect go.etcd.io/bbolt v1.3.6 // indirect - golang.org/x/crypto v0.7.0 // indirect + golang.org/x/crypto v0.8.0 // indirect golang.org/x/exp v0.0.0-20230321023759-10a507213a29 // indirect - golang.org/x/net v0.8.0 // indirect + golang.org/x/net v0.9.0 // indirect golang.org/x/sync v0.1.0 // indirect - golang.org/x/sys v0.6.0 // indirect - golang.org/x/term v0.6.0 // indirect - golang.org/x/text v0.8.0 // indirect + golang.org/x/sys v0.7.0 // indirect + golang.org/x/term v0.7.0 // indirect + golang.org/x/text v0.9.0 // indirect google.golang.org/protobuf v1.30.0 // indirect gopkg.in/ini.v1 v1.67.0 // indirect gopkg.in/yaml.v2 v2.4.0 // indirect diff --git a/x/nft/go.sum b/x/nft/go.sum index f043bbb643f9..ea4c8d4af259 100644 --- a/x/nft/go.sum +++ b/x/nft/go.sum @@ -35,24 +35,24 @@ cloud.google.com/go/storage v1.6.0/go.mod h1:N7U0C8pVQ/+NIKOBQyamJIeKQKkZ+mxpohl cloud.google.com/go/storage v1.8.0/go.mod h1:Wv1Oy7z6Yz3DshWRJFhqM/UCfaWIRTdp0RXyy7KQOVs= cloud.google.com/go/storage v1.10.0/go.mod h1:FLPqc6j+Ki4BU591ie1oL6qBQGu2Bl/tZ9ullr3+Kg0= cloud.google.com/go/storage v1.14.0/go.mod h1:GrKmX003DSIwi9o29oFT7YDnHYwZoctc3fOKtUw0Xmo= -cosmossdk.io/api v0.3.2-0.20230313131911-55bf5d4efbe7 h1:4LrWK+uGP5IxznxtHHsHD+ZBs2+oZRH2loYOGjHLzZM= -cosmossdk.io/api v0.3.2-0.20230313131911-55bf5d4efbe7/go.mod h1:yVns7mKgcsG+hZW/3C5FdJtC6QYWdFIcRlKb9+5HV5g= -cosmossdk.io/collections v0.0.0-20230309163709-87da587416ba h1:S4PYij/tX3Op/hwenVEN9D+M27JRcwSwVqE3UA0BnwM= -cosmossdk.io/collections v0.0.0-20230309163709-87da587416ba/go.mod h1:lpS+G8bGC2anqzWdndTzjnQnuMO/qAcgZUkGJp4i3rc= +cosmossdk.io/api v0.4.0 h1:x90DmdidP6EhzktAa/6/IofSHidDnPjahdlrUvyQZQw= +cosmossdk.io/api v0.4.0/go.mod h1:TWDzBhUBhI1LhSf2XSYpfIBf6D4mbLu/fvzvDfhcaYM= +cosmossdk.io/collections v0.1.0 h1:nzJGeiq32KnZroSrhB6rPifw4I85Cgmzw/YAmr4luv8= +cosmossdk.io/collections v0.1.0/go.mod h1:xbauc0YsbUF8qKMVeBZl0pFCunxBIhKN/WlxpZ3lBuo= cosmossdk.io/core v0.6.1 h1:OBy7TI2W+/gyn2z40vVvruK3di+cAluinA6cybFbE7s= cosmossdk.io/core v0.6.1/go.mod h1:g3MMBCBXtxbDWBURDVnJE7XML4BG5qENhs0gzkcpuFA= cosmossdk.io/depinject v1.0.0-alpha.3 h1:6evFIgj//Y3w09bqOUOzEpFj5tsxBqdc5CfkO7z+zfw= cosmossdk.io/depinject v1.0.0-alpha.3/go.mod h1:eRbcdQ7MRpIPEM5YUJh8k97nxHpYbc3sMUnEtt8HPWU= cosmossdk.io/errors v1.0.0-beta.7 h1:gypHW76pTQGVnHKo6QBkb4yFOJjC+sUGRc5Al3Odj1w= cosmossdk.io/errors v1.0.0-beta.7/go.mod h1:mz6FQMJRku4bY7aqS/Gwfcmr/ue91roMEKAmDUDpBfE= -cosmossdk.io/log v0.1.0 h1:Vnexi+KzUCjmqq/m93teAxjt5biWFfZ5PI1imx2IJw8= -cosmossdk.io/log v0.1.0/go.mod h1:p95Wq6mDY3SREMc4y7+QU9Uwy3nyvfpWGD1iSaFkVFs= +cosmossdk.io/log v1.0.0 h1:NGKZ/A5rd4PduDfoscgABklX557PWjQINbosZy/m3Jk= +cosmossdk.io/log v1.0.0/go.mod h1:CwX9BLiBruZb7lzLlRr3R231d/fVPUXk8gAdV4LQap0= cosmossdk.io/math v1.0.0 h1:ro9w7eKx23om2tZz/VM2Pf+z2WAbGX1yDQQOJ6iGeJw= cosmossdk.io/math v1.0.0/go.mod h1:Ygz4wBHrgc7g0N+8+MrnTfS9LLn9aaTGa9hKopuym5k= -cosmossdk.io/store v0.1.0-alpha.1 h1:NGomhLUXzAxvK4OF8+yP6eNUG5i4LwzOzx+S494pTCg= -cosmossdk.io/store v0.1.0-alpha.1/go.mod h1:kmCMbhrleCZ6rDZPY/EGNldNvPebFNyVPFYp+pv05/k= -cosmossdk.io/x/tx v0.3.1-0.20230321155358-6522dd1731b5 h1:AlvyRc7f7Py1mv254vrqjIIuykCnitHIz2T+nup3bU0= -cosmossdk.io/x/tx v0.3.1-0.20230321155358-6522dd1731b5/go.mod h1:FNkSEMbLP9NFdTfrbslNUtNS7OXf3wgZeJyXzfRPa4c= +cosmossdk.io/store v0.1.0-alpha.1.0.20230328185921-37ba88872dbc h1:9piuA+NYmhe+SyMPtMoboLw/djgDbrI3dD5TG020Tnk= +cosmossdk.io/store v0.1.0-alpha.1.0.20230328185921-37ba88872dbc/go.mod h1:UFF5rmjN7WYVfxo6ArdY/l1+yyWMURBWOmSJypGqFHQ= +cosmossdk.io/x/tx v0.5.1-0.20230407182919-057d2e09bd63 h1:zHqj2VwZ/MStFmR7SUe/7gErOFhL9v2rkjmWPB/st34= +cosmossdk.io/x/tx v0.5.1-0.20230407182919-057d2e09bd63/go.mod h1:Oh3Kh+IPOfMEILNxVd2e8SLqRrIjYHpdGBfDg4ghU/k= dmitri.shuralyov.com/gpu/mtl v0.0.0-20190408044501-666a987793e9/go.mod h1:H6x//7gZCb22OMCxBHrMx7a5I7Hp++hsVxbQ4BYO7hU= filippo.io/edwards25519 v1.0.0 h1:0wAIcmJUqRdI8IJ/3eGi5/HwXZWPujYXXlkrQogz0Ek= filippo.io/edwards25519 v1.0.0/go.mod h1:N1IkdkCkiLB6tki+MYJoSx2JTY9NUlxZE7eHn5EwJns= @@ -113,6 +113,7 @@ github.com/beorn7/perks v1.0.1/go.mod h1:G2ZrVWU2WbWT9wwq4/hrbKbnv/1ERSJQ0ibhJ6r github.com/bgentry/speakeasy v0.1.0/go.mod h1:+zsyZBPWlz7T6j88CTgSN5bM796AkVf0kBD4zp0CCIs= github.com/bgentry/speakeasy v0.1.1-0.20220910012023-760eaf8b6816 h1:41iFGWnSlI2gVpmOtVTJZNodLdLQLn/KsJqFvXwnd/s= github.com/bgentry/speakeasy v0.1.1-0.20220910012023-760eaf8b6816/go.mod h1:+zsyZBPWlz7T6j88CTgSN5bM796AkVf0kBD4zp0CCIs= +github.com/bits-and-blooms/bitset v1.6.0 h1:FVfaUsleKAUTJnaN9Fd1YFFi1S8vAX5xeXnXHFYOojM= github.com/btcsuite/btcd/btcec/v2 v2.3.2 h1:5n0X6hX0Zk+6omWcihdYvdAlGf2DfasC0GMf7DClJ3U= github.com/btcsuite/btcd/btcec/v2 v2.3.2/go.mod h1:zYzJ8etWJQIv1Ogk7OzpWjowwOdXY1W/17j2MW85J04= github.com/btcsuite/btcd/btcutil v1.1.2 h1:XLMbX8JQEiwMcYft2EGi8zPUkoa0abKIU6/BJSRsjzQ= @@ -156,14 +157,14 @@ github.com/cockroachdb/errors v1.9.1/go.mod h1:2sxOtL2WIc096WSZqZ5h8fa17rdDq9HZO github.com/cockroachdb/logtags v0.0.0-20211118104740-dabe8e521a4f/go.mod h1:Vz9DsVWQQhf3vs21MhPMZpMGSht7O/2vFW2xusFUVOs= github.com/cockroachdb/logtags v0.0.0-20230118201751-21c54148d20b h1:r6VH0faHjZeQy818SGhaone5OnYfxFR/+AzdY3sf5aE= github.com/cockroachdb/logtags v0.0.0-20230118201751-21c54148d20b/go.mod h1:Vz9DsVWQQhf3vs21MhPMZpMGSht7O/2vFW2xusFUVOs= -github.com/cockroachdb/pebble v0.0.0-20230315223031-1e5ddd10389e h1:CDuLmyaZ1pD4OJHHtubKqgu/Byw5zAnm+gArJsyj96Q= -github.com/cockroachdb/pebble v0.0.0-20230315223031-1e5ddd10389e/go.mod h1:9lRMC4XN3/BLPtIp6kAKwIaHu369NOf2rMucPzipz50= +github.com/cockroachdb/pebble v0.0.0-20230412222916-60cfeb46143b h1:92ve6F1Pls/eqd+V+102lOMRJatgpqqsQvbT9Bl/fjg= +github.com/cockroachdb/pebble v0.0.0-20230412222916-60cfeb46143b/go.mod h1:9lRMC4XN3/BLPtIp6kAKwIaHu369NOf2rMucPzipz50= github.com/cockroachdb/redact v1.1.3 h1:AKZds10rFSIj7qADf0g46UixK8NNLwWTNdCIGS5wfSQ= github.com/cockroachdb/redact v1.1.3/go.mod h1:BVNblN9mBWFyMyqK1k3AAiSxhvhfK2oOZZ2lK+dpvRg= github.com/codahale/hdrhistogram v0.0.0-20161010025455-3a0bb77429bd/go.mod h1:sE/e/2PUdi/liOCUjSTXgM1o87ZssimdTWN964YiIeI= github.com/codegangsta/inject v0.0.0-20150114235600-33e0aa1cb7c0/go.mod h1:4Zcjuz89kmFXt9morQgcfYZAYZ5n8WHjt81YYWIwtTM= -github.com/cometbft/cometbft v0.37.0 h1:M005vBaSaugvYYmNZwJOopynQSjwLoDTwflnQ/I/eYk= -github.com/cometbft/cometbft v0.37.0/go.mod h1:Y2MMMN//O5K4YKd8ze4r9jmk4Y7h0ajqILXbH5JQFVs= +github.com/cometbft/cometbft v0.37.1-0.20230411132551-3a91d155e664 h1:BbCkbnaU3R603XpnbqvuDU8Kfv+hjhiFILOHhVFntsw= +github.com/cometbft/cometbft v0.37.1-0.20230411132551-3a91d155e664/go.mod h1:Y2MMMN//O5K4YKd8ze4r9jmk4Y7h0ajqILXbH5JQFVs= github.com/cometbft/cometbft-db v0.7.0 h1:uBjbrBx4QzU0zOEnU8KxoDl18dMNgDh+zZRUE0ucsbo= github.com/cometbft/cometbft-db v0.7.0/go.mod h1:yiKJIm2WKrt6x8Cyxtq9YTEcIMPcEe4XPxhgX59Fzf0= github.com/confio/ics23/go v0.9.0 h1:cWs+wdbS2KRPZezoaaj+qBleXgUk5WOQFMP3CQFGTr4= @@ -173,7 +174,7 @@ github.com/coreos/etcd v3.3.10+incompatible/go.mod h1:uF7uidLiAD3TWHmW31ZFd/JWoc github.com/coreos/go-etcd v2.0.0+incompatible/go.mod h1:Jez6KQU2B/sWsbdaef3ED8NzMklzPG4d5KIOhIy30Tk= github.com/coreos/go-semver v0.2.0/go.mod h1:nnelYz7RCh+5ahJtPPxZlU+153eP4D4r3EedlOD2RNk= github.com/coreos/go-systemd v0.0.0-20180511133405-39ca1b05acc7/go.mod h1:F5haX7vjVVG0kc13fIWeqUViNPyEJxv/OmvnBo0Yme4= -github.com/coreos/go-systemd/v22 v22.3.3-0.20220203105225-a9a7ef127534/go.mod h1:Y58oyj3AT4RCenI/lSvhwexgC+NSVTIJ3seZv2GcEnc= +github.com/coreos/go-systemd/v22 v22.5.0/go.mod h1:Y58oyj3AT4RCenI/lSvhwexgC+NSVTIJ3seZv2GcEnc= github.com/coreos/pkg v0.0.0-20160727233714-3ac0863d7acf/go.mod h1:E3G3o1h8I7cfcXa63jLwjI0eiQQMgzzUDFVpN/nH/eA= github.com/cosmos/btcutil v1.0.5 h1:t+ZFcX77LpKtDBhjucvnOH8C2l2ioGsBNEQ3jef8xFk= github.com/cosmos/btcutil v1.0.5/go.mod h1:IyB7iuqZMJlthe2tkIFL33xPyzbFYP0XVdS8P5lUPis= @@ -181,16 +182,16 @@ github.com/cosmos/cosmos-db v1.0.0-rc.1 h1:SjnT8B6WKMW9WEIX32qMhnEEKcI7ZP0+G1Sa9 github.com/cosmos/cosmos-db v1.0.0-rc.1/go.mod h1:Dnmk3flSf5lkwCqvvjNpoxjpXzhxnCAFzKHlbaForso= github.com/cosmos/cosmos-proto v1.0.0-beta.3 h1:VitvZ1lPORTVxkmF2fAp3IiA61xVwArQYKXTdEcpW6o= github.com/cosmos/cosmos-proto v1.0.0-beta.3/go.mod h1:t8IASdLaAq+bbHbjq4p960BvcTqtwuAxid3b/2rOD6I= -github.com/cosmos/cosmos-sdk v0.46.0-beta2.0.20230321173237-fe77d4bca302 h1:wffm9LPPG/FBW/tSRdJp2DCgkJQRX+Zsbdmn4I0aWeQ= -github.com/cosmos/cosmos-sdk v0.46.0-beta2.0.20230321173237-fe77d4bca302/go.mod h1:HzOsWXtPxhO8+Y8P4Ru+G3UWx6dTkpGXU9yvT35VEuI= +github.com/cosmos/cosmos-sdk v0.46.0-beta2.0.20230419124727-7b10ada768f4 h1:tZ2vcNWznBxIIK37nlgrh4n/n5aQv0KY6VzIb86xTNs= +github.com/cosmos/cosmos-sdk v0.46.0-beta2.0.20230419124727-7b10ada768f4/go.mod h1:BPvKPN63ettXrpz67uM1rHEqX/UVVkAfceFCPyp217E= github.com/cosmos/go-bip39 v0.0.0-20180819234021-555e2067c45d/go.mod h1:tSxLoYXyBmiFeKpvmq4dzayMdCjCnu8uqmCysIGBT2Y= github.com/cosmos/go-bip39 v1.0.0 h1:pcomnQdrdH22njcAatO0yWojsUnCO3y2tNoV1cb6hHY= github.com/cosmos/go-bip39 v1.0.0/go.mod h1:RNJv0H/pOIVgxw6KS7QeX2a0Uo0aKUlfhZ4xuwvCdJw= github.com/cosmos/gogogateway v1.2.0 h1:Ae/OivNhp8DqBi/sh2A8a1D0y638GpL3tkmLQAiKxTE= github.com/cosmos/gogogateway v1.2.0/go.mod h1:iQpLkGWxYcnCdz5iAdLcRBSw3h7NXeOkZ4GUkT+tbFI= github.com/cosmos/gogoproto v1.4.2/go.mod h1:cLxOsn1ljAHSV527CHOtaIP91kK6cCrZETRBrkzItWU= -github.com/cosmos/gogoproto v1.4.6 h1:Ee7z15dWJaGlgM2rWrK8N2IX7PQcuccu8oG68jp5RL4= -github.com/cosmos/gogoproto v1.4.6/go.mod h1:VS/ASYmPgv6zkPKLjR9EB91lwbLHOzaGCirmKKhncfI= +github.com/cosmos/gogoproto v1.4.8 h1:BrHKc6WFZt8+jRV71vKSQE+JrfF+JAnzrKo2VP7wIZ4= +github.com/cosmos/gogoproto v1.4.8/go.mod h1:hnb0DIEWTv+wdNzNcqus5xCQXq5+CXauq1FJuurRfVY= github.com/cosmos/iavl v0.21.0-beta.1 h1:fBQeBc8HLZ14plJNcmGfaOXSSMLVEHvEQXiTXSD76m0= github.com/cosmos/iavl v0.21.0-beta.1/go.mod h1:25YJYzilTErJ2mKfNB3xyWL9IsCwEQdNzdIutg2mh3U= github.com/cosmos/ledger-cosmos-go v0.13.0 h1:ex0CvCxToSR7j5WjrghPu2Bu9sSXKikjnVvUryNnx4s= @@ -209,9 +210,9 @@ github.com/danieljoos/wincred v1.1.2/go.mod h1:GijpziifJoIBfYh+S7BbkdUTU4LfM+QnG github.com/davecgh/go-spew v1.1.0/go.mod h1:J7Y8YcW2NihsgmVo/mv3lAwl/skON4iLHjSsI+c5H38= github.com/davecgh/go-spew v1.1.1 h1:vj9j/u1bqnvCEfJOwUhtlOARqs3+rkHYY13jYWTU97c= github.com/davecgh/go-spew v1.1.1/go.mod h1:J7Y8YcW2NihsgmVo/mv3lAwl/skON4iLHjSsI+c5H38= -github.com/decred/dcrd/crypto/blake256 v1.0.0 h1:/8DMNYp9SGi5f0w7uCm6d6M4OU2rGFK09Y2A4Xv7EE0= -github.com/decred/dcrd/dcrec/secp256k1/v4 v4.1.0 h1:HbphB4TFFXpv7MNrT52FGrrgVXF1owhMVTHFZIlnvd4= -github.com/decred/dcrd/dcrec/secp256k1/v4 v4.1.0/go.mod h1:DZGJHZMqrU4JJqFAWUS2UO1+lbSKsdiOoYi9Zzey7Fc= +github.com/decred/dcrd/crypto/blake256 v1.0.1 h1:7PltbUIQB7u/FfZ39+DGa/ShuMyJ5ilcvdfma9wOH6Y= +github.com/decred/dcrd/dcrec/secp256k1/v4 v4.2.0 h1:8UrgZ3GkP4i/CLijOJx79Yu+etlyjdBU4sfcs2WYQMs= +github.com/decred/dcrd/dcrec/secp256k1/v4 v4.2.0/go.mod h1:v57UDF4pDQJcEfFUCRop3lJL149eHGSe9Jvczhzjo/0= github.com/desertbit/timer v0.0.0-20180107155436-c41aec40b27f h1:U5y3Y5UE0w7amNe7Z5G/twsBW0KEalRQXZzf8ufSh9I= github.com/desertbit/timer v0.0.0-20180107155436-c41aec40b27f/go.mod h1:xH/i4TFMt8koVQZ6WFms69WAsDWr2XsYL3Hkl7jkoLE= github.com/dgraph-io/badger v1.6.0/go.mod h1:zwt7syl517jmP8s94KqSxTlM6IMsdhYy6psNgSztDR4= @@ -271,8 +272,8 @@ github.com/fsnotify/fsnotify v1.6.0 h1:n+5WquG0fcWoWp6xPWfHdbskMCQaFnG6PfBrh1Ky4 github.com/fsnotify/fsnotify v1.6.0/go.mod h1:sl3t1tCWJFWoRz9R8WJCbQihKKwmorjAbSClcnxKAGw= github.com/gavv/httpexpect v2.0.0+incompatible/go.mod h1:x+9tiU1YnrOvnB725RkpoLv1M62hOWzwo5OXotisrKc= github.com/getsentry/sentry-go v0.12.0/go.mod h1:NSap0JBYWzHND8oMbyi0+XZhUalc1TBdRL1M71JZW2c= -github.com/getsentry/sentry-go v0.19.0 h1:BcCH3CN5tXt5aML+gwmbFwVptLLQA+eT866fCO9wVOM= -github.com/getsentry/sentry-go v0.19.0/go.mod h1:y3+lGEFEFexZtpbG1GUE2WD/f9zGyKYwpEqryTOC/nE= +github.com/getsentry/sentry-go v0.20.0 h1:bwXW98iMRIWxn+4FgPW7vMrjmbym6HblXALmhjHmQaQ= +github.com/getsentry/sentry-go v0.20.0/go.mod h1:lc76E2QywIyW8WuBnwl8Lc4bkmQH4+w1gwTf25trprY= github.com/ghodss/yaml v1.0.0/go.mod h1:4dBDuWmgqj2HViK6kFavaiC9ZROes6MMH2rRYeMEF04= github.com/gin-contrib/sse v0.1.0 h1:Y/yl/+YNO8GZSjAhjMsSuLt29uWRFHdHYUb5lYOV9qE= github.com/gin-contrib/sse v0.1.0/go.mod h1:RHrZQHXnP2xjPF+u1gW/2HnVO7nvIa9PG3Gm+fLHvGI= @@ -493,7 +494,6 @@ github.com/imkira/go-interpol v1.1.0/go.mod h1:z0h2/2T3XF8kyEPpRgJ3kmNv+C43p+I/C github.com/improbable-eng/grpc-web v0.15.0 h1:BN+7z6uNXZ1tQGcNAuaU1YjsLTApzkjt2tzCixLaUPQ= github.com/improbable-eng/grpc-web v0.15.0/go.mod h1:1sy9HKV4Jt9aEs9JSnkWlRJPuPtwNr0l57L4f878wP8= github.com/inconshreveable/mousetrap v1.0.0/go.mod h1:PxqpIevigyE2G7u3NXJIT2ANytuPF1OarO4DADm73n8= -github.com/inconshreveable/mousetrap v1.0.1/go.mod h1:vpF70FUmC8bwa3OWnCshd2FqLfsEA9PFc4w1p2J65bw= github.com/inconshreveable/mousetrap v1.1.0 h1:wN+x4NVGpMsO7ErUn/mUI3vEoE6Jt13X2s0bqwp9tc8= github.com/inconshreveable/mousetrap v1.1.0/go.mod h1:vpF70FUmC8bwa3OWnCshd2FqLfsEA9PFc4w1p2J65bw= github.com/influxdata/influxdb1-client v0.0.0-20191209144304-8bf82d3c094d/go.mod h1:qj24IKcXYK6Iy9ceXlo3Tc+vtHo9lIhSX5JddghvEPo= @@ -535,8 +535,8 @@ github.com/klauspost/compress v1.9.7/go.mod h1:RyIbtBH6LamlWaDj8nUwkbUhJ87Yi3uG0 github.com/klauspost/compress v1.10.3/go.mod h1:aoV0uJVorq1K+umq18yTdKaF57EivdYsUV+/s2qKfXs= github.com/klauspost/compress v1.11.7/go.mod h1:aoV0uJVorq1K+umq18yTdKaF57EivdYsUV+/s2qKfXs= github.com/klauspost/compress v1.12.3/go.mod h1:8dP1Hq4DHOhN9w426knH3Rhby4rFm6D8eO+e+Dq5Gzg= -github.com/klauspost/compress v1.16.3 h1:XuJt9zzcnaz6a16/OU53ZjWp/v7/42WcR5t2a0PcNQY= -github.com/klauspost/compress v1.16.3/go.mod h1:ntbaceVETuRiXiv4DpjP66DpAtAGkEQskQzEyD//IeE= +github.com/klauspost/compress v1.16.5 h1:IFV2oUNUzZaz+XyusxpLzpzS8Pt5rh0Z16For/djlyI= +github.com/klauspost/compress v1.16.5/go.mod h1:ntbaceVETuRiXiv4DpjP66DpAtAGkEQskQzEyD//IeE= github.com/klauspost/cpuid v1.2.1/go.mod h1:Pj4uuM528wm8OyEC2QMXAi2YiTZ96dNQPGgoMS4s3ek= github.com/konsorten/go-windows-terminal-sequences v1.0.1/go.mod h1:T0+1ngSBFLxvqU3pZ+m/2kptfBszLMUkC4ZK/EgS/cQ= github.com/konsorten/go-windows-terminal-sequences v1.0.3/go.mod h1:T0+1ngSBFLxvqU3pZ+m/2kptfBszLMUkC4ZK/EgS/cQ= @@ -561,8 +561,8 @@ github.com/libp2p/go-buffer-pool v0.1.0 h1:oK4mSFcQz7cTQIfqbe4MIj9gLW+mnanjyFtc6 github.com/libp2p/go-buffer-pool v0.1.0/go.mod h1:N+vh8gMqimBzdKkSMVuydVDq+UV5QTWy5HSiZacSbPg= github.com/lightstep/lightstep-tracer-common/golang/gogo v0.0.0-20190605223551-bc2310a04743/go.mod h1:qklhhLq1aX+mtWk9cPHPzaBjWImj5ULL6C7HFJtXQMM= github.com/lightstep/lightstep-tracer-go v0.18.1/go.mod h1:jlF1pusYV4pidLvZ+XD0UBX0ZE6WURAspgAczcDHrL4= -github.com/linxGnu/grocksdb v1.7.15 h1:AEhP28lkeAybv5UYNYviYISpR6bJejEnKuYbnWAnxx0= -github.com/linxGnu/grocksdb v1.7.15/go.mod h1:pY55D0o+r8yUYLq70QmhdudxYvoDb9F+9puf4m3/W+U= +github.com/linxGnu/grocksdb v1.7.16 h1:Q2co1xrpdkr5Hx3Fp+f+f7fRGhQFQhvi/+226dtLmA8= +github.com/linxGnu/grocksdb v1.7.16/go.mod h1:JkS7pl5qWpGpuVb3bPqTz8nC12X3YtPZT+Xq7+QfQo4= github.com/lyft/protoc-gen-validate v0.0.13/go.mod h1:XbGvPuh87YZc5TdIa2/I4pLk0QoUACkjt2znoq26NVQ= github.com/magiconair/properties v1.8.0/go.mod h1:PppfXfuXeibc/6YijjN8zIbojt8czPbwD3XqdrwzmxQ= github.com/magiconair/properties v1.8.7 h1:IeQXZAiQcpL9mgcAe1Nu6cX9LLw6ExEHKjN0VQdvPDY= @@ -700,8 +700,8 @@ github.com/prometheus/client_golang v1.0.0/go.mod h1:db9x61etRT2tGnBNRi70OPL5Fsn github.com/prometheus/client_golang v1.3.0/go.mod h1:hJaj2vgQTGQmVCsAACORcieXFeDPbaTKGT+JTgUa3og= github.com/prometheus/client_golang v1.4.0/go.mod h1:e9GMxYsXl05ICDXkRhurwBS4Q3OK1iX/F2sw+iXX5zU= github.com/prometheus/client_golang v1.7.1/go.mod h1:PY5Wy2awLA44sXw4AOSfFBetzPP4j5+D6mVACh+pe2M= -github.com/prometheus/client_golang v1.14.0 h1:nJdhIvne2eSX/XRAFV9PcvFFRbrjbcTUj0VP62TMhnw= -github.com/prometheus/client_golang v1.14.0/go.mod h1:8vpkKitgIVNcqrRBWh1C4TIUQgYNtG/XQE4E/Zae36Y= +github.com/prometheus/client_golang v1.15.0 h1:5fCgGYogn0hFdhyhLbw7hEsWxufKtY9klyvdNfFlFhM= +github.com/prometheus/client_golang v1.15.0/go.mod h1:e9yaBhRPU2pPNsZwE+JdQl0KEt1N9XgF6zxWmaC0xOk= github.com/prometheus/client_model v0.0.0-20180712105110-5c3871d89910/go.mod h1:MbSGuTsp3dbXC40dX6PRTWyKYBIrTGTE9sqQNg2J8bo= github.com/prometheus/client_model v0.0.0-20190115171406-56726106282f/go.mod h1:MbSGuTsp3dbXC40dX6PRTWyKYBIrTGTE9sqQNg2J8bo= github.com/prometheus/client_model v0.0.0-20190129233127-fd36f4220a90/go.mod h1:xMI15A0UPsDsEKsMN9yxemIoYk6Tm2C1GtYGdfGttqA= @@ -736,14 +736,15 @@ github.com/rogpeppe/go-internal v1.3.0/go.mod h1:M8bDsm7K2OlrFYOpmOWEs/qY81heoFR github.com/rogpeppe/go-internal v1.6.1/go.mod h1:xXDCJY+GAPziupqXw64V24skbSoqbTEfhy4qGm1nDQc= github.com/rogpeppe/go-internal v1.8.0/go.mod h1:WmiCO8CzOY8rg0OYDC4/i/2WRWAB6poM+XZ2dLUbcbE= github.com/rogpeppe/go-internal v1.8.1/go.mod h1:JeRgkft04UBgHMgCIwADu4Pn6Mtm5d4nPKWu0nJ5d+o= -github.com/rogpeppe/go-internal v1.9.0 h1:73kH8U+JUqXU8lRuOHeVHaa/SZPifC7BkcraZVejAe8= github.com/rogpeppe/go-internal v1.9.0/go.mod h1:WtVeX8xhTBvf0smdhujwtBcq4Qrzq/fJaraNFVN+nFs= +github.com/rogpeppe/go-internal v1.10.0 h1:TMyTOH3F/DB16zRVcYyreMH6GnZZrwQVAoYjRBZyWFQ= +github.com/rogpeppe/go-internal v1.10.0/go.mod h1:UQnix2H7Ngw/k4C5ijL5+65zddjncjaFoBhdsK/akog= github.com/rs/cors v1.7.0/go.mod h1:gFx+x8UowdsKA9AchylcLynDq+nNFfI8FkUZdN/jGCU= github.com/rs/cors v1.8.3 h1:O+qNyWn7Z+F9M0ILBHgMVPuB1xTOucVd5gtaYyXBpRo= github.com/rs/cors v1.8.3/go.mod h1:XyqrcTp5zjWr1wsJ8PIRZssZ8b/WMcMf71DJnit4EMU= github.com/rs/xid v1.4.0/go.mod h1:trrq9SKmegXys3aeAKXMUTdJsYXVwGY3RLcfgqegfbg= -github.com/rs/zerolog v1.29.0 h1:Zes4hju04hjbvkVkOhdl2HpZa+0PmVwigmo8XoORE5w= -github.com/rs/zerolog v1.29.0/go.mod h1:NILgTygv/Uej1ra5XxGf82ZFSLk58MFGAUS2o6usyD0= +github.com/rs/zerolog v1.29.1 h1:cO+d60CHkknCbvzEWxP0S9K6KqyTjrCNUy1LdQLCGPc= +github.com/rs/zerolog v1.29.1/go.mod h1:Le6ESbR7hc+DP6Lt1THiV8CQSdkkNrd3R0XbEgp3ZBU= github.com/russross/blackfriday v1.5.2/go.mod h1:JO/DiYxRf+HjHt06OyowR9PTA263kcR/rfWxYHBV53g= github.com/russross/blackfriday/v2 v2.0.1/go.mod h1:+Rmxgy9KzJVeS9/2gXHxylqXiyQDYRxCVz55jmeOWTM= github.com/russross/blackfriday/v2 v2.1.0/go.mod h1:+Rmxgy9KzJVeS9/2gXHxylqXiyQDYRxCVz55jmeOWTM= @@ -776,8 +777,8 @@ github.com/spf13/cast v1.5.0 h1:rj3WzYc11XZaIZMPKmwP96zkFEnnAmV8s6XbB2aY32w= github.com/spf13/cast v1.5.0/go.mod h1:SpXXQ5YoyJw6s3/6cMTQuxvgRl3PCJiyaX9p6b155UU= github.com/spf13/cobra v0.0.3/go.mod h1:1l0Ry5zgKvJasoi3XT1TypsSe7PqH0Sj9dhYf7v3XqQ= github.com/spf13/cobra v0.0.5/go.mod h1:3K3wKZymM7VvHMDS9+Akkh4K60UwM26emMESw8tLCHU= -github.com/spf13/cobra v1.6.1 h1:o94oiPyS4KD1mPy2fmcYYHHfCxLqYjJOhGsCHFZtEzA= -github.com/spf13/cobra v1.6.1/go.mod h1:IOw/AERYS7UzyrGinqmz6HLUo219MORXGxhbaJUqzrY= +github.com/spf13/cobra v1.7.0 h1:hyqWnYt1ZQShIddO5kBpj3vu05/++x6tJ6dg8EC572I= +github.com/spf13/cobra v1.7.0/go.mod h1:uLxZILRyS/50WlhOIKD7W6V5bgeIt+4sICxh6uRMrb0= github.com/spf13/jwalterweatherman v1.0.0/go.mod h1:cQK4TGJAtQXfYWX+Ddv3mKDzgVb68N+wFjFa4jdeBTo= github.com/spf13/jwalterweatherman v1.1.0 h1:ue6voC5bR5F8YxI5S67j9i582FU4Qvo2bmqnqMYADFk= github.com/spf13/jwalterweatherman v1.1.0/go.mod h1:aNWZUN0dPAAO/Ljvb5BEdw96iTZ0EXowPYD95IqWIGo= @@ -895,8 +896,8 @@ golang.org/x/crypto v0.0.0-20210421170649-83a5a9bb288b/go.mod h1:T9bdIzuCu7OtxOm golang.org/x/crypto v0.0.0-20210711020723-a769d52b0f97/go.mod h1:GvvjBRRGRdwPK5ydBHafDWAxML/pGHZbMvKqRZ5+Abc= golang.org/x/crypto v0.0.0-20210921155107-089bfa567519/go.mod h1:GvvjBRRGRdwPK5ydBHafDWAxML/pGHZbMvKqRZ5+Abc= golang.org/x/crypto v0.0.0-20211108221036-ceb1ce70b4fa/go.mod h1:GvvjBRRGRdwPK5ydBHafDWAxML/pGHZbMvKqRZ5+Abc= -golang.org/x/crypto v0.7.0 h1:AvwMYaRytfdeVt3u6mLaxYtErKYjxA2OXjJ1HHq6t3A= -golang.org/x/crypto v0.7.0/go.mod h1:pYwdfH91IfpZVANVyUOhSIPZaFoJGxTFbZhFTx+dXZU= +golang.org/x/crypto v0.8.0 h1:pd9TJtTueMTVQXzk8E2XESSMQDj/U7OUu0PqJqPXQjQ= +golang.org/x/crypto v0.8.0/go.mod h1:mRqEX+O9/h5TFCrQhkgjo2yKi0yYA+9ecGkdQoHrywE= golang.org/x/exp v0.0.0-20190121172915-509febef88a4/go.mod h1:CJ0aWSM057203Lf6IL+f9T1iT9GByDxfZKAQTCR3kQA= golang.org/x/exp v0.0.0-20190306152737-a1d7652674e8/go.mod h1:CJ0aWSM057203Lf6IL+f9T1iT9GByDxfZKAQTCR3kQA= golang.org/x/exp v0.0.0-20190510132918-efd6b22b2522/go.mod h1:ZjyILWgesfNpC6sMxTJOJm9Kp84zZh5NQWvqDGG3Qr8= @@ -985,8 +986,8 @@ golang.org/x/net v0.0.0-20210805182204-aaa1db679c0d/go.mod h1:9nx3DQGgdP8bBQD5qx golang.org/x/net v0.0.0-20211008194852-3b03d305991f/go.mod h1:9nx3DQGgdP8bBQD5qxJ1jj9UTztislL4KSBs9R2vV5Y= golang.org/x/net v0.0.0-20220225172249-27dd8689420f/go.mod h1:CfG3xpIq0wQ8r1q4Su4UZFWDARRcnwPjda9FqA0JpMk= golang.org/x/net v0.0.0-20220607020251-c690dde0001d/go.mod h1:XRhObCWvk6IyKnWLug+ECip1KBveYUHfp+8e9klMJ9c= -golang.org/x/net v0.8.0 h1:Zrh2ngAOFYneWTAIAPethzeaQLuHwhuBkuV6ZiRnUaQ= -golang.org/x/net v0.8.0/go.mod h1:QVkue5JL9kW//ek3r6jTKnTFis1tRmNAW2P1shuFdJc= +golang.org/x/net v0.9.0 h1:aWJ/m6xSmxWBx+V0XRHTlrYrPG56jKsLdTFmsSsCzOM= +golang.org/x/net v0.9.0/go.mod h1:d48xBJpPfHeWQsugry2m+kC02ZBRGRgulfHnEXEuWns= golang.org/x/oauth2 v0.0.0-20180821212333-d2e6202438be/go.mod h1:N/0e6XlmueqKjAGxoOufVs8QHGRruUQn6yWY3a++T0U= golang.org/x/oauth2 v0.0.0-20190226205417-e64efc72b421/go.mod h1:gOpvHmFTYa4IltrdGE7lF6nIHvwfUNPOp7c8zoXwtLw= golang.org/x/oauth2 v0.0.0-20190604053449-0f29369cfe45/go.mod h1:gOpvHmFTYa4IltrdGE7lF6nIHvwfUNPOp7c8zoXwtLw= @@ -1089,12 +1090,13 @@ golang.org/x/sys v0.0.0-20220520151302-bc2c85ada10a/go.mod h1:oPkhp1MJrh7nUepCBc golang.org/x/sys v0.0.0-20220811171246-fbc7d0a398ab/go.mod h1:oPkhp1MJrh7nUepCBck5+mAzfO9JrbApNNgaTdGDITg= golang.org/x/sys v0.0.0-20220908164124-27713097b956/go.mod h1:oPkhp1MJrh7nUepCBck5+mAzfO9JrbApNNgaTdGDITg= golang.org/x/sys v0.0.0-20221010170243-090e33056c14/go.mod h1:oPkhp1MJrh7nUepCBck5+mAzfO9JrbApNNgaTdGDITg= -golang.org/x/sys v0.6.0 h1:MVltZSvRTcU2ljQOhs94SXPftV6DCNnZViHeQps87pQ= golang.org/x/sys v0.6.0/go.mod h1:oPkhp1MJrh7nUepCBck5+mAzfO9JrbApNNgaTdGDITg= +golang.org/x/sys v0.7.0 h1:3jlCCIQZPdOYu1h8BkNvLz8Kgwtae2cagcG/VamtZRU= +golang.org/x/sys v0.7.0/go.mod h1:oPkhp1MJrh7nUepCBck5+mAzfO9JrbApNNgaTdGDITg= golang.org/x/term v0.0.0-20201126162022-7de9c90e9dd1/go.mod h1:bj7SfCRtBDWHUb9snDiAeCFNEtKQo2Wmx5Cou7ajbmo= golang.org/x/term v0.0.0-20210927222741-03fcf44c2211/go.mod h1:jbD1KX2456YbFQfuXm/mYQcufACuNUgVhRMnK/tPxf8= -golang.org/x/term v0.6.0 h1:clScbb1cHjoCkyRbWwBEUZ5H/tIFu5TAXIqaZD0Gcjw= -golang.org/x/term v0.6.0/go.mod h1:m6U89DPEgQRMq3DNkDClhWw02AUbt2daBVO4cn4Hv9U= +golang.org/x/term v0.7.0 h1:BEvjmm5fURWqcfbSKTdpkDXYBrUS1c0m8agp14W48vQ= +golang.org/x/term v0.7.0/go.mod h1:P32HKFT3hSsZrRxla30E9HqToFYAQPCMs/zFMBUFqPY= golang.org/x/text v0.0.0-20170915032832-14c0d48ead0c/go.mod h1:NqM8EUOU14njkJ3fqMW+pc6Ldnwhi/IjpwHt7yyuwOQ= golang.org/x/text v0.3.0/go.mod h1:NqM8EUOU14njkJ3fqMW+pc6Ldnwhi/IjpwHt7yyuwOQ= golang.org/x/text v0.3.1-0.20180807135948-17ff2d5776d2/go.mod h1:NqM8EUOU14njkJ3fqMW+pc6Ldnwhi/IjpwHt7yyuwOQ= @@ -1104,8 +1106,8 @@ golang.org/x/text v0.3.4/go.mod h1:5Zoc/QRtKVWzQhOtBMvqHzDpF6irO9z98xDceosuGiQ= golang.org/x/text v0.3.5/go.mod h1:5Zoc/QRtKVWzQhOtBMvqHzDpF6irO9z98xDceosuGiQ= golang.org/x/text v0.3.6/go.mod h1:5Zoc/QRtKVWzQhOtBMvqHzDpF6irO9z98xDceosuGiQ= golang.org/x/text v0.3.7/go.mod h1:u+2+/6zg+i71rQMx5EYifcz6MCKuco9NR6JIITiCfzQ= -golang.org/x/text v0.8.0 h1:57P1ETyNKtuIjB4SRd15iJxuhj8Gc416Y78H3qgMh68= -golang.org/x/text v0.8.0/go.mod h1:e1OnstbJyHTd6l/uOt8jFFHp6TRDWZR/bV3emEE/zU8= +golang.org/x/text v0.9.0 h1:2sjJmO8cDvYveuX97RDLsxlyUxLl+GHoLxBiRdHllBE= +golang.org/x/text v0.9.0/go.mod h1:e1OnstbJyHTd6l/uOt8jFFHp6TRDWZR/bV3emEE/zU8= golang.org/x/time v0.0.0-20180412165947-fbb02b2291d2/go.mod h1:tRJNPiyCQ0inRvYxbN9jk5I+vvW/OXSQhTDSoE431IQ= golang.org/x/time v0.0.0-20181108054448-85acf8d2951c/go.mod h1:tRJNPiyCQ0inRvYxbN9jk5I+vvW/OXSQhTDSoE431IQ= golang.org/x/time v0.0.0-20190308202827-9d24e82272b4/go.mod h1:tRJNPiyCQ0inRvYxbN9jk5I+vvW/OXSQhTDSoE431IQ= @@ -1251,8 +1253,8 @@ google.golang.org/genproto v0.0.0-20210126160654-44e461bb6506/go.mod h1:FWY/as6D google.golang.org/genproto v0.0.0-20210226172003-ab064af71705/go.mod h1:FWY/as6DDZQgahTzZj3fqbO1CbirC29ZNUFHwi0/+no= google.golang.org/genproto v0.0.0-20210624195500-8bfb893ecb84/go.mod h1:SzzZ/N+nwJDaO1kznhnlzqS8ocJICar6hYhVyhi++24= google.golang.org/genproto v0.0.0-20220314164441-57ef72a4c106/go.mod h1:hAL49I2IFola2sVEjAn7MEwsja0xp51I0tlGAf9hz4E= -google.golang.org/genproto v0.0.0-20230320184635-7606e756e683 h1:khxVcsk/FhnzxMKOyD+TDGwjbEOpcPuIpmafPGFmhMA= -google.golang.org/genproto v0.0.0-20230320184635-7606e756e683/go.mod h1:NWraEVixdDnqcqQ30jipen1STv2r/n24Wb7twVTGR4s= +google.golang.org/genproto v0.0.0-20230410155749-daa745c078e1 h1:KpwkzHKEF7B9Zxg18WzOa7djJ+Ha5DzthMyZYQfEn2A= +google.golang.org/genproto v0.0.0-20230410155749-daa745c078e1/go.mod h1:nKE/iIaLqn2bQwXBg8f1g2Ylh6r5MN5CmZvuzZCgsCU= google.golang.org/grpc v1.12.0/go.mod h1:yo6s7OP7yaDglbqo1J04qKzAhqBH6lvTonzMVmEdcZw= google.golang.org/grpc v1.17.0/go.mod h1:6QZJwpn2B+Zp71q/5VxRsJ6NXXVCE5NRUHRo+f3cWCs= google.golang.org/grpc v1.19.0/go.mod h1:mqu4LbDTu4XGKhr4mRzUsmM4RtVoemTSY81AxZiDr8c= diff --git a/x/nft/internal/conv/string_test.go b/x/nft/internal/conv/string_test.go index 3e051d37b907..3a1451753188 100644 --- a/x/nft/internal/conv/string_test.go +++ b/x/nft/internal/conv/string_test.go @@ -26,7 +26,7 @@ func (s *StringSuite) TestUnsafeStrToBytes() { b := unsafeConvertStr() runtime.GC() <-time.NewTimer(2 * time.Millisecond).C - b2 := append(b, 'd') //nolint:gocritic // append is fine here + b2 := append(b, 'd') s.Equal("abc", string(b)) s.Equal("abcd", string(b2)) } diff --git a/x/nft/keeper/class.go b/x/nft/keeper/class.go index 1517961df02b..1e73a27beec6 100644 --- a/x/nft/keeper/class.go +++ b/x/nft/keeper/class.go @@ -1,15 +1,17 @@ package keeper import ( + "context" + "cosmossdk.io/errors" storetypes "cosmossdk.io/store/types" "cosmossdk.io/x/nft" - sdk "github.com/cosmos/cosmos-sdk/types" + "github.com/cosmos/cosmos-sdk/runtime" ) // SaveClass defines a method for creating a new nft class -func (k Keeper) SaveClass(ctx sdk.Context, class nft.Class) error { +func (k Keeper) SaveClass(ctx context.Context, class nft.Class) error { if k.HasClass(ctx, class.Id) { return errors.Wrap(nft.ErrClassExists, class.Id) } @@ -17,13 +19,12 @@ func (k Keeper) SaveClass(ctx sdk.Context, class nft.Class) error { if err != nil { return errors.Wrap(err, "Marshal nft.Class failed") } - store := ctx.KVStore(k.storeKey) - store.Set(classStoreKey(class.Id), bz) - return nil + store := k.storeService.OpenKVStore(ctx) + return store.Set(classStoreKey(class.Id), bz) } // UpdateClass defines a method for updating an exist nft class -func (k Keeper) UpdateClass(ctx sdk.Context, class nft.Class) error { +func (k Keeper) UpdateClass(ctx context.Context, class nft.Class) error { if !k.HasClass(ctx, class.Id) { return errors.Wrap(nft.ErrClassNotExists, class.Id) } @@ -31,17 +32,20 @@ func (k Keeper) UpdateClass(ctx sdk.Context, class nft.Class) error { if err != nil { return errors.Wrap(err, "Marshal nft.Class failed") } - store := ctx.KVStore(k.storeKey) - store.Set(classStoreKey(class.Id), bz) - return nil + store := k.storeService.OpenKVStore(ctx) + return store.Set(classStoreKey(class.Id), bz) } // GetClass defines a method for returning the class information of the specified id -func (k Keeper) GetClass(ctx sdk.Context, classID string) (nft.Class, bool) { - store := ctx.KVStore(k.storeKey) - bz := store.Get(classStoreKey(classID)) - +func (k Keeper) GetClass(ctx context.Context, classID string) (nft.Class, bool) { + store := k.storeService.OpenKVStore(ctx) var class nft.Class + + bz, err := store.Get(classStoreKey(classID)) + if err != nil { + return class, false + } + if len(bz) == 0 { return class, false } @@ -50,9 +54,9 @@ func (k Keeper) GetClass(ctx sdk.Context, classID string) (nft.Class, bool) { } // GetClasses defines a method for returning all classes information -func (k Keeper) GetClasses(ctx sdk.Context) (classes []*nft.Class) { - store := ctx.KVStore(k.storeKey) - iterator := storetypes.KVStorePrefixIterator(store, ClassKey) +func (k Keeper) GetClasses(ctx context.Context) (classes []*nft.Class) { + store := k.storeService.OpenKVStore(ctx) + iterator := storetypes.KVStorePrefixIterator(runtime.KVStoreAdapter(store), ClassKey) defer iterator.Close() for ; iterator.Valid(); iterator.Next() { var class nft.Class @@ -63,7 +67,11 @@ func (k Keeper) GetClasses(ctx sdk.Context) (classes []*nft.Class) { } // HasClass determines whether the specified classID exist -func (k Keeper) HasClass(ctx sdk.Context, classID string) bool { - store := ctx.KVStore(k.storeKey) - return store.Has(classStoreKey(classID)) +func (k Keeper) HasClass(ctx context.Context, classID string) bool { + store := k.storeService.OpenKVStore(ctx) + has, err := store.Has(classStoreKey(classID)) + if err != nil { + panic(err) + } + return has } diff --git a/x/nft/keeper/genesis.go b/x/nft/keeper/genesis.go index 37b9acd402c7..9b57cd8b65e1 100644 --- a/x/nft/keeper/genesis.go +++ b/x/nft/keeper/genesis.go @@ -17,7 +17,10 @@ func (k Keeper) InitGenesis(ctx sdk.Context, data *nft.GenesisState) { } for _, entry := range data.Entries { for _, nft := range entry.Nfts { - owner := sdk.MustAccAddressFromBech32(entry.Owner) + owner, err := k.ac.StringToBytes(entry.Owner) + if err != nil { + panic(err) + } if err := k.Mint(ctx, *nft, owner); err != nil { panic(err) diff --git a/x/nft/keeper/grpc_query.go b/x/nft/keeper/grpc_query.go index 0280394c8951..274238288185 100644 --- a/x/nft/keeper/grpc_query.go +++ b/x/nft/keeper/grpc_query.go @@ -6,6 +6,7 @@ import ( "cosmossdk.io/store/prefix" "cosmossdk.io/x/nft" + "github.com/cosmos/cosmos-sdk/runtime" sdk "github.com/cosmos/cosmos-sdk/types" sdkerrors "github.com/cosmos/cosmos-sdk/types/errors" "github.com/cosmos/cosmos-sdk/types/query" @@ -23,7 +24,7 @@ func (k Keeper) Balance(goCtx context.Context, r *nft.QueryBalanceRequest) (*nft return nil, nft.ErrEmptyClassID } - owner, err := sdk.AccAddressFromBech32(r.Owner) + owner, err := k.ac.StringToBytes(r.Owner) if err != nil { return nil, err } @@ -76,7 +77,7 @@ func (k Keeper) NFTs(goCtx context.Context, r *nft.QueryNFTsRequest) (*nft.Query var owner sdk.AccAddress if len(r.Owner) > 0 { - owner, err = sdk.AccAddressFromBech32(r.Owner) + owner, err = k.ac.StringToBytes(r.Owner) if err != nil { return nil, err } @@ -88,7 +89,7 @@ func (k Keeper) NFTs(goCtx context.Context, r *nft.QueryNFTsRequest) (*nft.Query switch { case len(r.ClassId) > 0 && len(r.Owner) > 0: - if pageRes, err = query.Paginate(k.getClassStoreByOwner(ctx, owner, r.ClassId), r.Pagination, func(key []byte, _ []byte) error { + if pageRes, err = query.Paginate(k.getClassStoreByOwner(ctx, owner, r.ClassId), r.Pagination, func(key, _ []byte) error { nft, has := k.GetNFT(ctx, r.ClassId, string(key)) if has { nfts = append(nfts, &nft) @@ -99,7 +100,7 @@ func (k Keeper) NFTs(goCtx context.Context, r *nft.QueryNFTsRequest) (*nft.Query } case len(r.ClassId) > 0 && len(r.Owner) == 0: nftStore := k.getNFTStore(ctx, r.ClassId) - if pageRes, err = query.Paginate(nftStore, r.Pagination, func(_ []byte, value []byte) error { + if pageRes, err = query.Paginate(nftStore, r.Pagination, func(_, value []byte) error { var nft nft.NFT if err := k.cdc.Unmarshal(value, &nft); err != nil { return err @@ -110,7 +111,7 @@ func (k Keeper) NFTs(goCtx context.Context, r *nft.QueryNFTsRequest) (*nft.Query return nil, err } case len(r.ClassId) == 0 && len(r.Owner) > 0: - if pageRes, err = query.Paginate(k.prefixStoreNftOfClassByOwner(ctx, owner), r.Pagination, func(key []byte, value []byte) error { + if pageRes, err = query.Paginate(k.prefixStoreNftOfClassByOwner(ctx, owner), r.Pagination, func(key, value []byte) error { classID, nftID := parseNftOfClassByOwnerStoreKey(key) if n, has := k.GetNFT(ctx, classID, nftID); has { nfts = append(nfts, &n) @@ -174,11 +175,11 @@ func (k Keeper) Classes(goCtx context.Context, r *nft.QueryClassesRequest) (*nft } ctx := sdk.UnwrapSDKContext(goCtx) - store := ctx.KVStore(k.storeKey) - classStore := prefix.NewStore(store, ClassKey) + store := k.storeService.OpenKVStore(ctx) + classStore := prefix.NewStore(runtime.KVStoreAdapter(store), ClassKey) var classes []*nft.Class - pageRes, err := query.Paginate(classStore, r.Pagination, func(_ []byte, value []byte) error { + pageRes, err := query.Paginate(classStore, r.Pagination, func(_, value []byte) error { var class nft.Class if err := k.cdc.Unmarshal(value, &class); err != nil { return err diff --git a/x/nft/keeper/grpc_query_test.go b/x/nft/keeper/grpc_query_test.go index 13f9db530c86..3320a09c61c0 100644 --- a/x/nft/keeper/grpc_query_test.go +++ b/x/nft/keeper/grpc_query_test.go @@ -16,6 +16,7 @@ func TestGRPCQuery(t *testing.T) { } func (s *TestSuite) TestBalance() { + s.accountKeeper.EXPECT().StringToBytes("owner").Return(nil, fmt.Errorf("decoding bech32 failed")).AnyTimes() var req *nft.QueryBalanceRequest testCases := []struct { msg string diff --git a/x/nft/keeper/keeper.go b/x/nft/keeper/keeper.go index 3bfa5696d2a4..218230e05f38 100644 --- a/x/nft/keeper/keeper.go +++ b/x/nft/keeper/keeper.go @@ -1,7 +1,8 @@ package keeper import ( - storetypes "cosmossdk.io/store/types" + "cosmossdk.io/core/address" + store "cosmossdk.io/core/store" "cosmossdk.io/x/nft" "github.com/cosmos/cosmos-sdk/codec" @@ -9,13 +10,14 @@ import ( // Keeper of the nft store type Keeper struct { - cdc codec.BinaryCodec - storeKey storetypes.StoreKey - bk nft.BankKeeper + cdc codec.BinaryCodec + storeService store.KVStoreService + bk nft.BankKeeper + ac address.Codec } // NewKeeper creates a new nft Keeper instance -func NewKeeper(key storetypes.StoreKey, +func NewKeeper(storeService store.KVStoreService, cdc codec.BinaryCodec, ak nft.AccountKeeper, bk nft.BankKeeper, ) Keeper { // ensure nft module account is set @@ -24,8 +26,9 @@ func NewKeeper(key storetypes.StoreKey, } return Keeper{ - cdc: cdc, - storeKey: key, - bk: bk, + cdc: cdc, + storeService: storeService, + bk: bk, + ac: ak, } } diff --git a/x/nft/keeper/keeper_test.go b/x/nft/keeper/keeper_test.go index 36abc07a6c09..6d7fda36dde4 100644 --- a/x/nft/keeper/keeper_test.go +++ b/x/nft/keeper/keeper_test.go @@ -15,6 +15,7 @@ import ( nfttestutil "cosmossdk.io/x/nft/testutil" "github.com/cosmos/cosmos-sdk/baseapp" + "github.com/cosmos/cosmos-sdk/runtime" "github.com/cosmos/cosmos-sdk/testutil" simtestutil "github.com/cosmos/cosmos-sdk/testutil/sims" sdk "github.com/cosmos/cosmos-sdk/types" @@ -36,10 +37,11 @@ const ( type TestSuite struct { suite.Suite - ctx sdk.Context - addrs []sdk.AccAddress - queryClient nft.QueryClient - nftKeeper keeper.Keeper + ctx sdk.Context + addrs []sdk.AccAddress + queryClient nft.QueryClient + nftKeeper keeper.Keeper + accountKeeper *nfttestutil.MockAccountKeeper encCfg moduletestutil.TestEncodingConfig } @@ -50,6 +52,7 @@ func (s *TestSuite) SetupTest() { s.encCfg = moduletestutil.MakeTestEncodingConfig(module.AppModuleBasic{}) key := storetypes.NewKVStoreKey(nft.StoreKey) + storeService := runtime.NewKVStoreService(key) testCtx := testutil.DefaultContextWithDB(s.T(), key, storetypes.NewTransientStoreKey("transient_test")) ctx := testCtx.Ctx.WithBlockHeader(cmtproto.Header{Time: cmttime.Now()}) @@ -58,8 +61,13 @@ func (s *TestSuite) SetupTest() { accountKeeper := nfttestutil.NewMockAccountKeeper(ctrl) bankKeeper := nfttestutil.NewMockBankKeeper(ctrl) accountKeeper.EXPECT().GetModuleAddress("nft").Return(s.addrs[0]).AnyTimes() + for _, addr := range s.addrs { + accountKeeper.EXPECT().StringToBytes(addr.String()).Return(addr, nil).AnyTimes() + } + + s.accountKeeper = accountKeeper - nftKeeper := keeper.NewKeeper(key, s.encCfg.Codec, accountKeeper, bankKeeper) + nftKeeper := keeper.NewKeeper(storeService, s.encCfg.Codec, accountKeeper, bankKeeper) queryHelper := baseapp.NewQueryServerTestHelper(ctx, s.encCfg.InterfaceRegistry) nft.RegisterQueryServer(queryHelper, nftKeeper) diff --git a/x/nft/keeper/msg_server.go b/x/nft/keeper/msg_server.go index 87e8dc270c90..2f48298714f4 100644 --- a/x/nft/keeper/msg_server.go +++ b/x/nft/keeper/msg_server.go @@ -1,6 +1,7 @@ package keeper import ( + "bytes" "context" errorsmod "cosmossdk.io/errors" @@ -14,20 +15,28 @@ var _ nft.MsgServer = Keeper{} // Send implements Send method of the types.MsgServer. func (k Keeper) Send(goCtx context.Context, msg *nft.MsgSend) (*nft.MsgSendResponse, error) { - ctx := sdk.UnwrapSDKContext(goCtx) - sender, err := sdk.AccAddressFromBech32(msg.Sender) - if err != nil { - return nil, err + if len(msg.ClassId) == 0 { + return nil, nft.ErrEmptyClassID } - owner := k.GetOwner(ctx, msg.ClassId, msg.Id) - if !owner.Equals(sender) { - return nil, errorsmod.Wrapf(sdkerrors.ErrUnauthorized, "%s is not the owner of nft %s", sender, msg.Id) + if len(msg.Id) == 0 { + return nil, nft.ErrEmptyNFTID } - receiver, err := sdk.AccAddressFromBech32(msg.Receiver) + sender, err := k.ac.StringToBytes(msg.Sender) if err != nil { - return nil, err + return nil, errorsmod.Wrapf(sdkerrors.ErrInvalidAddress, "Invalid sender address (%s)", msg.Sender) + } + + receiver, err := k.ac.StringToBytes(msg.Receiver) + if err != nil { + return nil, errorsmod.Wrapf(sdkerrors.ErrInvalidAddress, "Invalid receiver address (%s)", msg.Receiver) + } + + ctx := sdk.UnwrapSDKContext(goCtx) + owner := k.GetOwner(ctx, msg.ClassId, msg.Id) + if !bytes.Equal(owner, sender) { + return nil, errorsmod.Wrapf(sdkerrors.ErrUnauthorized, "%s is not the owner of nft %s", msg.Sender, msg.Id) } if err := k.Transfer(ctx, msg.ClassId, msg.Id, receiver); err != nil { diff --git a/x/nft/keeper/msg_server_test.go b/x/nft/keeper/msg_server_test.go index 14f90f7c0664..fc044a5f995c 100644 --- a/x/nft/keeper/msg_server_test.go +++ b/x/nft/keeper/msg_server_test.go @@ -50,6 +50,28 @@ func (s *TestSuite) TestSend() { expErr bool errMsg string }{ + { + name: "empty nft id", + req: &nft.MsgSend{ + ClassId: testClassID, + Id: "", + Sender: s.addrs[0].String(), + Receiver: s.addrs[1].String(), + }, + expErr: true, + errMsg: "empty nft id", + }, + { + name: "empty class id", + req: &nft.MsgSend{ + ClassId: "", + Id: testID, + Sender: s.addrs[0].String(), + Receiver: s.addrs[1].String(), + }, + expErr: true, + errMsg: "empty class id", + }, { name: "invalid class id", req: &nft.MsgSend{ diff --git a/x/nft/keeper/nft.go b/x/nft/keeper/nft.go index 2db46f54eff0..a2f1426891b9 100644 --- a/x/nft/keeper/nft.go +++ b/x/nft/keeper/nft.go @@ -1,15 +1,18 @@ package keeper import ( + "context" + "cosmossdk.io/errors" "cosmossdk.io/store/prefix" "cosmossdk.io/x/nft" + "github.com/cosmos/cosmos-sdk/runtime" sdk "github.com/cosmos/cosmos-sdk/types" ) // Mint defines a method for minting a new nft -func (k Keeper) Mint(ctx sdk.Context, token nft.NFT, receiver sdk.AccAddress) error { +func (k Keeper) Mint(ctx context.Context, token nft.NFT, receiver sdk.AccAddress) error { if !k.HasClass(ctx, token.ClassId) { return errors.Wrap(nft.ErrClassNotExists, token.ClassId) } @@ -25,12 +28,12 @@ func (k Keeper) Mint(ctx sdk.Context, token nft.NFT, receiver sdk.AccAddress) er // mintWithNoCheck defines a method for minting a new nft // Note: this method does not check whether the class already exists in nft. // The upper-layer application needs to check it when it needs to use it. -func (k Keeper) mintWithNoCheck(ctx sdk.Context, token nft.NFT, receiver sdk.AccAddress) { +func (k Keeper) mintWithNoCheck(ctx context.Context, token nft.NFT, receiver sdk.AccAddress) { k.setNFT(ctx, token) k.setOwner(ctx, token.ClassId, token.Id, receiver) k.incrTotalSupply(ctx, token.ClassId) - ctx.EventManager().EmitTypedEvent(&nft.EventMint{ + sdk.UnwrapSDKContext(ctx).EventManager().EmitTypedEvent(&nft.EventMint{ ClassId: token.ClassId, Id: token.Id, Owner: receiver.String(), @@ -39,7 +42,7 @@ func (k Keeper) mintWithNoCheck(ctx sdk.Context, token nft.NFT, receiver sdk.Acc // Burn defines a method for burning a nft from a specific account. // Note: When the upper module uses this method, it needs to authenticate nft -func (k Keeper) Burn(ctx sdk.Context, classID string, nftID string) error { +func (k Keeper) Burn(ctx context.Context, classID, nftID string) error { if !k.HasClass(ctx, classID) { return errors.Wrap(nft.ErrClassNotExists, classID) } @@ -55,14 +58,14 @@ func (k Keeper) Burn(ctx sdk.Context, classID string, nftID string) error { // burnWithNoCheck defines a method for burning a nft from a specific account. // Note: this method does not check whether the class already exists in nft. // The upper-layer application needs to check it when it needs to use it -func (k Keeper) burnWithNoCheck(ctx sdk.Context, classID string, nftID string) error { +func (k Keeper) burnWithNoCheck(ctx context.Context, classID, nftID string) error { owner := k.GetOwner(ctx, classID, nftID) nftStore := k.getNFTStore(ctx, classID) nftStore.Delete([]byte(nftID)) k.deleteOwner(ctx, classID, nftID, owner) k.decrTotalSupply(ctx, classID) - ctx.EventManager().EmitTypedEvent(&nft.EventBurn{ + sdk.UnwrapSDKContext(ctx).EventManager().EmitTypedEvent(&nft.EventBurn{ ClassId: classID, Id: nftID, Owner: owner.String(), @@ -72,7 +75,7 @@ func (k Keeper) burnWithNoCheck(ctx sdk.Context, classID string, nftID string) e // Update defines a method for updating an exist nft // Note: When the upper module uses this method, it needs to authenticate nft -func (k Keeper) Update(ctx sdk.Context, token nft.NFT) error { +func (k Keeper) Update(ctx context.Context, token nft.NFT) error { if !k.HasClass(ctx, token.ClassId) { return errors.Wrap(nft.ErrClassNotExists, token.ClassId) } @@ -87,13 +90,13 @@ func (k Keeper) Update(ctx sdk.Context, token nft.NFT) error { // Update defines a method for updating an exist nft // Note: this method does not check whether the class already exists in nft. // The upper-layer application needs to check it when it needs to use it -func (k Keeper) updateWithNoCheck(ctx sdk.Context, token nft.NFT) { +func (k Keeper) updateWithNoCheck(ctx context.Context, token nft.NFT) { k.setNFT(ctx, token) } // Transfer defines a method for sending a nft from one account to another account. // Note: When the upper module uses this method, it needs to authenticate nft -func (k Keeper) Transfer(ctx sdk.Context, +func (k Keeper) Transfer(ctx context.Context, classID string, nftID string, receiver sdk.AccAddress, @@ -113,7 +116,7 @@ func (k Keeper) Transfer(ctx sdk.Context, // Transfer defines a method for sending a nft from one account to another account. // Note: this method does not check whether the class already exists in nft. // The upper-layer application needs to check it when it needs to use it -func (k Keeper) transferWithNoCheck(ctx sdk.Context, +func (k Keeper) transferWithNoCheck(ctx context.Context, classID string, nftID string, receiver sdk.AccAddress, @@ -125,7 +128,7 @@ func (k Keeper) transferWithNoCheck(ctx sdk.Context, } // GetNFT returns the nft information of the specified classID and nftID -func (k Keeper) GetNFT(ctx sdk.Context, classID, nftID string) (nft.NFT, bool) { +func (k Keeper) GetNFT(ctx context.Context, classID, nftID string) (nft.NFT, bool) { store := k.getNFTStore(ctx, classID) bz := store.Get([]byte(nftID)) if len(bz) == 0 { @@ -137,7 +140,7 @@ func (k Keeper) GetNFT(ctx sdk.Context, classID, nftID string) (nft.NFT, bool) { } // GetNFTsOfClassByOwner returns all nft information of the specified classID under the specified owner -func (k Keeper) GetNFTsOfClassByOwner(ctx sdk.Context, classID string, owner sdk.AccAddress) (nfts []nft.NFT) { +func (k Keeper) GetNFTsOfClassByOwner(ctx context.Context, classID string, owner sdk.AccAddress) (nfts []nft.NFT) { ownerStore := k.getClassStoreByOwner(ctx, owner, classID) iterator := ownerStore.Iterator(nil, nil) defer iterator.Close() @@ -151,7 +154,7 @@ func (k Keeper) GetNFTsOfClassByOwner(ctx sdk.Context, classID string, owner sdk } // GetNFTsOfClass returns all nft information under the specified classID -func (k Keeper) GetNFTsOfClass(ctx sdk.Context, classID string) (nfts []nft.NFT) { +func (k Keeper) GetNFTsOfClass(ctx context.Context, classID string) (nfts []nft.NFT) { nftStore := k.getNFTStore(ctx, classID) iterator := nftStore.Iterator(nil, nil) defer iterator.Close() @@ -164,82 +167,91 @@ func (k Keeper) GetNFTsOfClass(ctx sdk.Context, classID string) (nfts []nft.NFT) } // GetOwner returns the owner information of the specified nft -func (k Keeper) GetOwner(ctx sdk.Context, classID string, nftID string) sdk.AccAddress { - store := ctx.KVStore(k.storeKey) - bz := store.Get(ownerStoreKey(classID, nftID)) +func (k Keeper) GetOwner(ctx context.Context, classID, nftID string) sdk.AccAddress { + store := k.storeService.OpenKVStore(ctx) + bz, err := store.Get(ownerStoreKey(classID, nftID)) + if err != nil { + panic(err) + } return sdk.AccAddress(bz) } // GetBalance returns the specified account, the number of all nfts under the specified classID -func (k Keeper) GetBalance(ctx sdk.Context, classID string, owner sdk.AccAddress) uint64 { +func (k Keeper) GetBalance(ctx context.Context, classID string, owner sdk.AccAddress) uint64 { nfts := k.GetNFTsOfClassByOwner(ctx, classID, owner) return uint64(len(nfts)) } // GetTotalSupply returns the number of all nfts under the specified classID -func (k Keeper) GetTotalSupply(ctx sdk.Context, classID string) uint64 { - store := ctx.KVStore(k.storeKey) - bz := store.Get(classTotalSupply(classID)) +func (k Keeper) GetTotalSupply(ctx context.Context, classID string) uint64 { + store := k.storeService.OpenKVStore(ctx) + bz, err := store.Get(classTotalSupply(classID)) + if err != nil { + panic(err) + } return sdk.BigEndianToUint64(bz) } // HasNFT determines whether the specified classID and nftID exist -func (k Keeper) HasNFT(ctx sdk.Context, classID, id string) bool { +func (k Keeper) HasNFT(ctx context.Context, classID, id string) bool { store := k.getNFTStore(ctx, classID) return store.Has([]byte(id)) } -func (k Keeper) setNFT(ctx sdk.Context, token nft.NFT) { +func (k Keeper) setNFT(ctx context.Context, token nft.NFT) { nftStore := k.getNFTStore(ctx, token.ClassId) bz := k.cdc.MustMarshal(&token) nftStore.Set([]byte(token.Id), bz) } -func (k Keeper) setOwner(ctx sdk.Context, classID, nftID string, owner sdk.AccAddress) { - store := ctx.KVStore(k.storeKey) +func (k Keeper) setOwner(ctx context.Context, classID, nftID string, owner sdk.AccAddress) { + store := k.storeService.OpenKVStore(ctx) store.Set(ownerStoreKey(classID, nftID), owner.Bytes()) ownerStore := k.getClassStoreByOwner(ctx, owner, classID) ownerStore.Set([]byte(nftID), Placeholder) } -func (k Keeper) deleteOwner(ctx sdk.Context, classID, nftID string, owner sdk.AccAddress) { - store := ctx.KVStore(k.storeKey) +func (k Keeper) deleteOwner(ctx context.Context, classID, nftID string, owner sdk.AccAddress) { + store := k.storeService.OpenKVStore(ctx) store.Delete(ownerStoreKey(classID, nftID)) ownerStore := k.getClassStoreByOwner(ctx, owner, classID) ownerStore.Delete([]byte(nftID)) } -func (k Keeper) getNFTStore(ctx sdk.Context, classID string) prefix.Store { - store := ctx.KVStore(k.storeKey) - return prefix.NewStore(store, nftStoreKey(classID)) +func (k Keeper) getNFTStore(ctx context.Context, classID string) prefix.Store { + store := k.storeService.OpenKVStore(ctx) + return prefix.NewStore(runtime.KVStoreAdapter(store), nftStoreKey(classID)) } -func (k Keeper) getClassStoreByOwner(ctx sdk.Context, owner sdk.AccAddress, classID string) prefix.Store { - store := ctx.KVStore(k.storeKey) +func (k Keeper) getClassStoreByOwner(ctx context.Context, owner sdk.AccAddress, classID string) prefix.Store { + store := k.storeService.OpenKVStore(ctx) key := nftOfClassByOwnerStoreKey(owner, classID) - return prefix.NewStore(store, key) + return prefix.NewStore(runtime.KVStoreAdapter(store), key) } -func (k Keeper) prefixStoreNftOfClassByOwner(ctx sdk.Context, owner sdk.AccAddress) prefix.Store { - store := ctx.KVStore(k.storeKey) +func (k Keeper) prefixStoreNftOfClassByOwner(ctx context.Context, owner sdk.AccAddress) prefix.Store { + store := k.storeService.OpenKVStore(ctx) key := prefixNftOfClassByOwnerStoreKey(owner) - return prefix.NewStore(store, key) + return prefix.NewStore(runtime.KVStoreAdapter(store), key) } -func (k Keeper) incrTotalSupply(ctx sdk.Context, classID string) { +func (k Keeper) incrTotalSupply(ctx context.Context, classID string) { supply := k.GetTotalSupply(ctx, classID) + 1 k.updateTotalSupply(ctx, classID, supply) } -func (k Keeper) decrTotalSupply(ctx sdk.Context, classID string) { +func (k Keeper) decrTotalSupply(ctx context.Context, classID string) { supply := k.GetTotalSupply(ctx, classID) - 1 k.updateTotalSupply(ctx, classID, supply) } -func (k Keeper) updateTotalSupply(ctx sdk.Context, classID string, supply uint64) { - store := ctx.KVStore(k.storeKey) +func (k Keeper) updateTotalSupply(ctx context.Context, classID string, supply uint64) { + store := k.storeService.OpenKVStore(ctx) supplyKey := classTotalSupply(classID) - store.Set(supplyKey, sdk.Uint64ToBigEndian(supply)) + err := store.Set(supplyKey, sdk.Uint64ToBigEndian(supply)) + if err != nil { + panic(err) + } } diff --git a/x/nft/keeper/nft_batch.go b/x/nft/keeper/nft_batch.go index 345897d6b060..474842869f66 100644 --- a/x/nft/keeper/nft_batch.go +++ b/x/nft/keeper/nft_batch.go @@ -1,6 +1,8 @@ package keeper import ( + "context" + "cosmossdk.io/errors" "cosmossdk.io/x/nft" @@ -8,7 +10,7 @@ import ( ) // BatchMint defines a method for minting a batch of nfts -func (k Keeper) BatchMint(ctx sdk.Context, +func (k Keeper) BatchMint(ctx context.Context, tokens []nft.NFT, receiver sdk.AccAddress, ) error { @@ -30,7 +32,7 @@ func (k Keeper) BatchMint(ctx sdk.Context, // BatchBurn defines a method for burning a batch of nfts from a specific classID. // Note: When the upper module uses this method, it needs to authenticate nft -func (k Keeper) BatchBurn(ctx sdk.Context, classID string, nftIDs []string) error { +func (k Keeper) BatchBurn(ctx context.Context, classID string, nftIDs []string) error { if !k.HasClass(ctx, classID) { return errors.Wrap(nft.ErrClassNotExists, classID) } @@ -47,7 +49,7 @@ func (k Keeper) BatchBurn(ctx sdk.Context, classID string, nftIDs []string) erro // BatchUpdate defines a method for updating a batch of exist nfts // Note: When the upper module uses this method, it needs to authenticate nft -func (k Keeper) BatchUpdate(ctx sdk.Context, tokens []nft.NFT) error { +func (k Keeper) BatchUpdate(ctx context.Context, tokens []nft.NFT) error { checked := make(map[string]bool, len(tokens)) for _, token := range tokens { if !checked[token.ClassId] && !k.HasClass(ctx, token.ClassId) { @@ -65,7 +67,7 @@ func (k Keeper) BatchUpdate(ctx sdk.Context, tokens []nft.NFT) error { // BatchTransfer defines a method for sending a batch of nfts from one account to another account from a specific classID. // Note: When the upper module uses this method, it needs to authenticate nft -func (k Keeper) BatchTransfer(ctx sdk.Context, +func (k Keeper) BatchTransfer(ctx context.Context, classID string, nftIDs []string, receiver sdk.AccAddress, diff --git a/x/nft/module/module.go b/x/nft/module/module.go index 5ff580568504..94db19427c17 100644 --- a/x/nft/module/module.go +++ b/x/nft/module/module.go @@ -9,10 +9,11 @@ import ( "github.com/spf13/cobra" "google.golang.org/grpc" + "cosmossdk.io/core/address" "cosmossdk.io/core/appmodule" + "cosmossdk.io/core/store" "cosmossdk.io/depinject" "cosmossdk.io/errors" - store "cosmossdk.io/store/types" sdkclient "github.com/cosmos/cosmos-sdk/client" "github.com/cosmos/cosmos-sdk/codec" @@ -38,6 +39,7 @@ var ( // AppModuleBasic defines the basic application module used by the nft module. type AppModuleBasic struct { cdc codec.Codec + ac address.Codec } // Name returns the nft module's name. @@ -68,25 +70,25 @@ func (AppModuleBasic) DefaultGenesis(cdc codec.JSONCodec) json.RawMessage { } // ValidateGenesis performs genesis state validation for the nft module. -func (AppModuleBasic) ValidateGenesis(cdc codec.JSONCodec, config sdkclient.TxEncodingConfig, bz json.RawMessage) error { +func (ab AppModuleBasic) ValidateGenesis(cdc codec.JSONCodec, config sdkclient.TxEncodingConfig, bz json.RawMessage) error { var data nft.GenesisState if err := cdc.UnmarshalJSON(bz, &data); err != nil { return errors.Wrapf(err, "failed to unmarshal %s genesis state", nft.ModuleName) } - return nft.ValidateGenesis(data) + return nft.ValidateGenesis(data, ab.ac) } // RegisterGRPCGatewayRoutes registers the gRPC Gateway routes for the nft module. -func (a AppModuleBasic) RegisterGRPCGatewayRoutes(clientCtx sdkclient.Context, mux *gwruntime.ServeMux) { +func (AppModuleBasic) RegisterGRPCGatewayRoutes(clientCtx sdkclient.Context, mux *gwruntime.ServeMux) { if err := nft.RegisterQueryHandlerClient(context.Background(), mux, nft.NewQueryClient(clientCtx)); err != nil { panic(err) } } // GetQueryCmd returns the cli query commands for the nft module -func (AppModuleBasic) GetQueryCmd() *cobra.Command { - return cli.GetQueryCmd() +func (ab AppModuleBasic) GetQueryCmd() *cobra.Command { + return cli.GetQueryCmd(ab.ac) } // GetTxCmd returns the transaction commands for the nft module @@ -107,7 +109,7 @@ type AppModule struct { // NewAppModule creates a new AppModule object func NewAppModule(cdc codec.Codec, keeper keeper.Keeper, ak nft.AccountKeeper, bk nft.BankKeeper, registry cdctypes.InterfaceRegistry) AppModule { return AppModule{ - AppModuleBasic: AppModuleBasic{cdc: cdc}, + AppModuleBasic: AppModuleBasic{cdc: cdc, ac: ak}, keeper: keeper, accountKeeper: ak, bankKeeper: bk, @@ -168,7 +170,7 @@ func (am AppModule) RegisterStoreDecoder(sdr simtypes.StoreDecoderRegistry) { func (am AppModule) WeightedOperations(simState module.SimulationState) []simtypes.WeightedOperation { return simulation.WeightedOperations( am.registry, - simState.AppParams, simState.Cdc, + simState.AppParams, simState.Cdc, simState.TxConfig, am.accountKeeper, am.bankKeeper, am.keeper, ) } @@ -186,9 +188,9 @@ func init() { type NftInputs struct { depinject.In - Key *store.KVStoreKey - Cdc codec.Codec - Registry cdctypes.InterfaceRegistry + StoreService store.KVStoreService + Cdc codec.Codec + Registry cdctypes.InterfaceRegistry AccountKeeper nft.AccountKeeper BankKeeper nft.BankKeeper @@ -202,7 +204,7 @@ type NftOutputs struct { } func ProvideModule(in NftInputs) NftOutputs { - k := keeper.NewKeeper(in.Key, in.Cdc, in.AccountKeeper, in.BankKeeper) + k := keeper.NewKeeper(in.StoreService, in.Cdc, in.AccountKeeper, in.BankKeeper) m := NewAppModule(in.Cdc, k, in.AccountKeeper, in.BankKeeper, in.Registry) return NftOutputs{NFTKeeper: k, Module: m} diff --git a/x/nft/msgs.go b/x/nft/msgs.go index c15b99cd8e5e..081737eb973d 100644 --- a/x/nft/msgs.go +++ b/x/nft/msgs.go @@ -1,10 +1,7 @@ package nft import ( - errorsmod "cosmossdk.io/errors" - sdk "github.com/cosmos/cosmos-sdk/types" - sdkerrors "github.com/cosmos/cosmos-sdk/types/errors" ) const ( @@ -14,28 +11,6 @@ const ( var _ sdk.Msg = &MsgSend{} -// ValidateBasic implements the Msg.ValidateBasic method. -func (m MsgSend) ValidateBasic() error { - if len(m.ClassId) == 0 { - return ErrEmptyClassID - } - - if len(m.Id) == 0 { - return ErrEmptyNFTID - } - - _, err := sdk.AccAddressFromBech32(m.Sender) - if err != nil { - return errorsmod.Wrapf(sdkerrors.ErrInvalidAddress, "Invalid sender address (%s)", m.Sender) - } - - _, err = sdk.AccAddressFromBech32(m.Receiver) - if err != nil { - return errorsmod.Wrapf(sdkerrors.ErrInvalidAddress, "Invalid receiver address (%s)", m.Receiver) - } - return nil -} - // GetSigners returns the expected signers for MsgSend. func (m MsgSend) GetSigners() []sdk.AccAddress { signer, _ := sdk.AccAddressFromBech32(m.Sender) diff --git a/x/nft/simulation/operations.go b/x/nft/simulation/operations.go index 7667d7067388..b3bccf2b84f1 100644 --- a/x/nft/simulation/operations.go +++ b/x/nft/simulation/operations.go @@ -4,12 +4,12 @@ import ( "math/rand" "github.com/cosmos/cosmos-sdk/baseapp" + "github.com/cosmos/cosmos-sdk/client" "github.com/cosmos/cosmos-sdk/codec" cdctypes "github.com/cosmos/cosmos-sdk/codec/types" simtestutil "github.com/cosmos/cosmos-sdk/testutil/sims" sdk "github.com/cosmos/cosmos-sdk/types" simtypes "github.com/cosmos/cosmos-sdk/types/simulation" - "github.com/cosmos/cosmos-sdk/x/auth/tx" "github.com/cosmos/cosmos-sdk/x/simulation" "cosmossdk.io/x/nft" @@ -18,7 +18,7 @@ import ( const ( // OpWeightMsgSend Simulation operation weights constants - OpWeightMsgSend = "op_weight_msg_send" //nolint:gosec + OpWeightMsgSend = "op_weight_msg_send" // WeightSend nft operations weights WeightSend = 100 @@ -31,6 +31,7 @@ func WeightedOperations( registry cdctypes.InterfaceRegistry, appParams simtypes.AppParams, cdc codec.JSONCodec, + txCfg client.TxConfig, ak nft.AccountKeeper, bk nft.BankKeeper, k keeper.Keeper, @@ -46,7 +47,7 @@ func WeightedOperations( return simulation.WeightedOperations{ simulation.NewWeightedOperation( weightMsgSend, - SimulateMsgSend(codec.NewProtoCodec(registry), ak, bk, k), + SimulateMsgSend(codec.NewProtoCodec(registry), txCfg, ak, bk, k), ), } } @@ -54,6 +55,7 @@ func WeightedOperations( // SimulateMsgSend generates a MsgSend with random values. func SimulateMsgSend( cdc *codec.ProtoCodec, + txCfg client.TxConfig, ak nft.AccountKeeper, bk nft.BankKeeper, k keeper.Keeper, @@ -92,7 +94,6 @@ func SimulateMsgSend( Receiver: receiver.Address.String(), } - txCfg := tx.NewTxConfig(cdc, tx.DefaultSignModes) tx, err := simtestutil.GenSignedMockTx( r, txCfg, diff --git a/x/nft/simulation/operations_test.go b/x/nft/simulation/operations_test.go index f32daf2dec87..8274fdbae916 100644 --- a/x/nft/simulation/operations_test.go +++ b/x/nft/simulation/operations_test.go @@ -14,6 +14,7 @@ import ( nftkeeper "cosmossdk.io/x/nft/keeper" "cosmossdk.io/x/nft/simulation" "cosmossdk.io/x/nft/testutil" + "github.com/cosmos/cosmos-sdk/client" "github.com/cosmos/cosmos-sdk/codec" codectypes "github.com/cosmos/cosmos-sdk/codec/types" "github.com/cosmos/cosmos-sdk/runtime" @@ -34,6 +35,7 @@ type SimTestSuite struct { app *runtime.App codec codec.Codec interfaceRegistry codectypes.InterfaceRegistry + txConfig client.TxConfig accountKeeper authkeeper.AccountKeeper bankKeeper bankkeeper.Keeper stakingKeeper *stakingkeeper.Keeper @@ -45,6 +47,7 @@ func (suite *SimTestSuite) SetupTest() { testutil.AppConfig, &suite.codec, &suite.interfaceRegistry, + &suite.txConfig, &suite.accountKeeper, &suite.bankKeeper, &suite.stakingKeeper, @@ -61,6 +64,7 @@ func (suite *SimTestSuite) TestWeightedOperations() { suite.interfaceRegistry, make(simtypes.AppParams), suite.codec, + suite.txConfig, suite.accountKeeper, suite.bankKeeper, suite.nftKeeper, @@ -125,7 +129,7 @@ func (suite *SimTestSuite) TestSimulateMsgSend() { // execute operation registry := suite.interfaceRegistry - op := simulation.SimulateMsgSend(codec.NewProtoCodec(registry), suite.accountKeeper, suite.bankKeeper, suite.nftKeeper) + op := simulation.SimulateMsgSend(codec.NewProtoCodec(registry), suite.txConfig, suite.accountKeeper, suite.bankKeeper, suite.nftKeeper) operationMsg, futureOperations, err := op(r, suite.app.BaseApp, ctx, accounts, "") suite.Require().NoError(err) diff --git a/x/nft/testutil/expected_keepers_mocks.go b/x/nft/testutil/expected_keepers_mocks.go index cf85857c6717..a54ef8207077 100644 --- a/x/nft/testutil/expected_keepers_mocks.go +++ b/x/nft/testutil/expected_keepers_mocks.go @@ -5,6 +5,7 @@ package testutil import ( + context "context" reflect "reflect" types "github.com/cosmos/cosmos-sdk/types" @@ -71,8 +72,23 @@ func (m *MockAccountKeeper) EXPECT() *MockAccountKeeperMockRecorder { return m.recorder } +// BytesToString mocks base method. +func (m *MockAccountKeeper) BytesToString(bz []byte) (string, error) { + m.ctrl.T.Helper() + ret := m.ctrl.Call(m, "BytesToString", bz) + ret0, _ := ret[0].(string) + ret1, _ := ret[1].(error) + return ret0, ret1 +} + +// BytesToString indicates an expected call of BytesToString. +func (mr *MockAccountKeeperMockRecorder) BytesToString(bz interface{}) *gomock.Call { + mr.mock.ctrl.T.Helper() + return mr.mock.ctrl.RecordCallWithMethodType(mr.mock, "BytesToString", reflect.TypeOf((*MockAccountKeeper)(nil).BytesToString), bz) +} + // GetAccount mocks base method. -func (m *MockAccountKeeper) GetAccount(ctx types.Context, addr types.AccAddress) types.AccountI { +func (m *MockAccountKeeper) GetAccount(ctx context.Context, addr types.AccAddress) types.AccountI { m.ctrl.T.Helper() ret := m.ctrl.Call(m, "GetAccount", ctx, addr) ret0, _ := ret[0].(types.AccountI) @@ -98,3 +114,18 @@ func (mr *MockAccountKeeperMockRecorder) GetModuleAddress(name interface{}) *gom mr.mock.ctrl.T.Helper() return mr.mock.ctrl.RecordCallWithMethodType(mr.mock, "GetModuleAddress", reflect.TypeOf((*MockAccountKeeper)(nil).GetModuleAddress), name) } + +// StringToBytes mocks base method. +func (m *MockAccountKeeper) StringToBytes(text string) ([]byte, error) { + m.ctrl.T.Helper() + ret := m.ctrl.Call(m, "StringToBytes", text) + ret0, _ := ret[0].([]byte) + ret1, _ := ret[1].(error) + return ret0, ret1 +} + +// StringToBytes indicates an expected call of StringToBytes. +func (mr *MockAccountKeeperMockRecorder) StringToBytes(text interface{}) *gomock.Call { + mr.mock.ctrl.T.Helper() + return mr.mock.ctrl.RecordCallWithMethodType(mr.mock, "StringToBytes", reflect.TypeOf((*MockAccountKeeper)(nil).StringToBytes), text) +} diff --git a/x/params/keeper/keeper_test.go b/x/params/keeper/keeper_test.go index e9863c7c5e2d..4abc039932e1 100644 --- a/x/params/keeper/keeper_test.go +++ b/x/params/keeper/keeper_test.go @@ -153,7 +153,7 @@ func indirect(ptr interface{}) interface{} { } func TestGetSubspaces(t *testing.T) { - _, _, _, _, keeper := testComponents() //nolint:dogsled + _, _, _, _, keeper := testComponents() table := types.NewKeyTable( types.NewParamSetPair([]byte("string"), "", validateNoOp), diff --git a/x/params/module.go b/x/params/module.go index 867a8735aa33..5f312dd5cc6b 100644 --- a/x/params/module.go +++ b/x/params/module.go @@ -120,8 +120,7 @@ func init() { )) } -//nolint:revive -type ParamsInputs struct { +type ModuleInputs struct { depinject.In KvStoreKey *store.KVStoreKey @@ -130,8 +129,7 @@ type ParamsInputs struct { LegacyAmino *codec.LegacyAmino } -//nolint:revive -type ParamsOutputs struct { +type ModuleOutputs struct { depinject.Out ParamsKeeper keeper.Keeper @@ -139,13 +137,13 @@ type ParamsOutputs struct { GovHandler govv1beta1.HandlerRoute } -func ProvideModule(in ParamsInputs) ParamsOutputs { +func ProvideModule(in ModuleInputs) ModuleOutputs { k := keeper.NewKeeper(in.Cdc, in.LegacyAmino, in.KvStoreKey, in.TransientStoreKey) m := NewAppModule(k) govHandler := govv1beta1.HandlerRoute{RouteKey: proposal.RouterKey, Handler: NewParamChangeProposalHandler(k)} - return ParamsOutputs{ParamsKeeper: k, Module: m, GovHandler: govHandler} + return ModuleOutputs{ParamsKeeper: k, Module: m, GovHandler: govHandler} } type SubspaceInputs struct { diff --git a/x/params/proposal_handler_test.go b/x/params/proposal_handler_test.go index aa06e18725a1..5b36ea9f067e 100644 --- a/x/params/proposal_handler_test.go +++ b/x/params/proposal_handler_test.go @@ -40,7 +40,7 @@ func (suite *HandlerTestSuite) SetupTest() { ctx := testutil.DefaultContext(key, tkey) paramsKeeper := keeper.NewKeeper(encodingCfg.Codec, encodingCfg.Amino, key, tkey) - paramsKeeper.Subspace("staking").WithKeyTable(stakingtypes.ParamKeyTable()) + paramsKeeper.Subspace("staking").WithKeyTable(stakingtypes.ParamKeyTable()) //nolint:staticcheck // TODO: depreacte this test case ctrl := gomock.NewController(suite.T()) stakingKeeper := paramstestutil.NewMockStakingKeeper(ctrl) stakingKeeper.EXPECT().MaxValidators(ctx).Return(uint32(1)) diff --git a/x/params/simulation/operations.go b/x/params/simulation/operations.go index fe6a5069e6b7..2d9a862dc449 100644 --- a/x/params/simulation/operations.go +++ b/x/params/simulation/operations.go @@ -9,7 +9,7 @@ import ( "github.com/cosmos/cosmos-sdk/x/params/types/proposal" ) -func min(a int, b int) int { +func min(a, b int) int { if a <= b { return a } @@ -19,7 +19,7 @@ func min(a int, b int) int { // SimulateParamChangeProposalContent returns random parameter change content. // It will generate a ParameterChangeProposal object with anywhere between 1 and // the total amount of defined parameters changes, all of which have random valid values. -func SimulateParamChangeProposalContent(paramChangePool []simulation.LegacyParamChange) simulation.ContentSimulatorFn { //nolint:staticcheck +func SimulateParamChangeProposalContent(paramChangePool []simulation.LegacyParamChange) simulation.ContentSimulatorFn { //nolint:staticcheck // used for legacy testing numProposals := 0 // Bound the maximum number of simultaneous parameter changes maxSimultaneousParamChanges := min(len(paramChangePool), 1000) @@ -27,7 +27,7 @@ func SimulateParamChangeProposalContent(paramChangePool []simulation.LegacyParam panic("param changes array is empty") } - return func(r *rand.Rand, _ sdk.Context, _ []simulation.Account) simulation.Content { //nolint:staticcheck + return func(r *rand.Rand, _ sdk.Context, _ []simulation.Account) simulation.Content { //nolint:staticcheck // used for legacy testing numChanges := simulation.RandIntBetween(r, 1, maxSimultaneousParamChanges) paramChanges := make([]proposal.ParamChange, numChanges) diff --git a/x/params/simulation/proposals.go b/x/params/simulation/proposals.go index 30b8f8434794..8dc636fa05c2 100644 --- a/x/params/simulation/proposals.go +++ b/x/params/simulation/proposals.go @@ -13,7 +13,7 @@ const ( // ProposalContents defines the module weighted proposals' contents // -//nolint:staticcheck +//nolint:staticcheck // used for legacy testing func ProposalContents(paramChanges []simtypes.LegacyParamChange) []simtypes.WeightedProposalContent { return []simtypes.WeightedProposalContent{ simulation.NewWeightedProposalContent( diff --git a/x/params/types/subspace.go b/x/params/types/subspace.go index b53bff85b757..bc577480107b 100644 --- a/x/params/types/subspace.go +++ b/x/params/types/subspace.go @@ -32,7 +32,7 @@ type Subspace struct { } // NewSubspace constructs a store with namestore -func NewSubspace(cdc codec.BinaryCodec, legacyAmino *codec.LegacyAmino, key storetypes.StoreKey, tkey storetypes.StoreKey, name string) Subspace { +func NewSubspace(cdc codec.BinaryCodec, legacyAmino *codec.LegacyAmino, key, tkey storetypes.StoreKey, name string) Subspace { return Subspace{ cdc: cdc, legacyAmino: legacyAmino, diff --git a/x/params/types/subspace_test.go b/x/params/types/subspace_test.go index ac2b4951f456..bb8c84477cb4 100644 --- a/x/params/types/subspace_test.go +++ b/x/params/types/subspace_test.go @@ -154,7 +154,7 @@ func (suite *SubspaceTestSuite) TestModified() { func (suite *SubspaceTestSuite) TestUpdate() { suite.Require().Panics(func() { - suite.ss.Update(suite.ctx, []byte("invalid_key"), nil) //nolint:errcheck + suite.ss.Update(suite.ctx, []byte("invalid_key"), nil) }) t := time.Hour * 48 diff --git a/x/simulation/expected_keepers.go b/x/simulation/expected_keepers.go index 346d695f66dc..345205996eb0 100644 --- a/x/simulation/expected_keepers.go +++ b/x/simulation/expected_keepers.go @@ -1,12 +1,14 @@ package simulation import ( + "context" + sdk "github.com/cosmos/cosmos-sdk/types" ) // AccountKeeper defines the expected account keeper used for simulations (noalias) type AccountKeeper interface { - GetAccount(ctx sdk.Context, addr sdk.AccAddress) sdk.AccountI + GetAccount(ctx context.Context, addr sdk.AccAddress) sdk.AccountI } // BankKeeper defines the expected interface needed to retrieve account balances. diff --git a/x/simulation/mock_cometbft.go b/x/simulation/mock_cometbft.go index 166cf40a87d7..7e72a1ae8d91 100644 --- a/x/simulation/mock_cometbft.go +++ b/x/simulation/mock_cometbft.go @@ -69,7 +69,7 @@ func (vals mockValidators) randomProposer(r *rand.Rand) []byte { proposer := vals[key].val pk, err := cryptoenc.PubKeyFromProto(proposer.PubKey) - if err != nil { //nolint:wsl + if err != nil { panic(err) } diff --git a/x/simulation/operation.go b/x/simulation/operation.go index 7aab48e9fbec..5594fd3f5822 100644 --- a/x/simulation/operation.go +++ b/x/simulation/operation.go @@ -73,7 +73,7 @@ func NewOperationQueue() OperationQueue { } // queueOperations adds all future operations into the operation queue. -func queueOperations(queuedOps OperationQueue, queuedTimeOps []simulation.FutureOperation, futureOps []simulation.FutureOperation) { +func queueOperations(queuedOps OperationQueue, queuedTimeOps, futureOps []simulation.FutureOperation) { if futureOps == nil { return } diff --git a/x/simulation/params.go b/x/simulation/params.go index 4ac7fac95099..73b520a0fd74 100644 --- a/x/simulation/params.go +++ b/x/simulation/params.go @@ -150,14 +150,14 @@ func (w WeightedProposalMsg) MsgSimulatorFn() simulation.MsgSimulatorFn { // WeightedProposalContent defines a common struct for proposal content defined by external modules (i.e outside gov) // -//nolint:staticcheck +//nolint:staticcheck // used for legacy testing type WeightedProposalContent struct { appParamsKey string // key used to retrieve the value of the weight from the simulation application params defaultWeight int // default weight contentSimulatorFn simulation.ContentSimulatorFn // content simulator function } -func NewWeightedProposalContent(appParamsKey string, defaultWeight int, contentSimulatorFn simulation.ContentSimulatorFn) simulation.WeightedProposalContent { //nolint:staticcheck +func NewWeightedProposalContent(appParamsKey string, defaultWeight int, contentSimulatorFn simulation.ContentSimulatorFn) simulation.WeightedProposalContent { //nolint:staticcheck // used for legacy testing return &WeightedProposalContent{appParamsKey: appParamsKey, defaultWeight: defaultWeight, contentSimulatorFn: contentSimulatorFn} } @@ -169,7 +169,7 @@ func (w WeightedProposalContent) DefaultWeight() int { return w.defaultWeight } -func (w WeightedProposalContent) ContentSimulatorFn() simulation.ContentSimulatorFn { //nolint:staticcheck +func (w WeightedProposalContent) ContentSimulatorFn() simulation.ContentSimulatorFn { //nolint:staticcheck // used for legacy testing return w.contentSimulatorFn } diff --git a/x/simulation/params_test.go b/x/simulation/params_test.go index 496454142c45..c3ea94896fa5 100644 --- a/x/simulation/params_test.go +++ b/x/simulation/params_test.go @@ -30,7 +30,7 @@ func TestNewWeightedProposalContent(t *testing.T) { key := "theKey" weight := 1 content := &testContent{} - f := func(r *rand.Rand, ctx sdk.Context, accs []simtypes.Account) simtypes.Content { //nolint:staticcheck + f := func(r *rand.Rand, ctx sdk.Context, accs []simtypes.Account) simtypes.Content { //nolint:staticcheck // used for legacy testing return content } diff --git a/x/slashing/abci_test.go b/x/slashing/abci_test.go index 367486040340..a87cf4bf827f 100644 --- a/x/slashing/abci_test.go +++ b/x/slashing/abci_test.go @@ -15,7 +15,6 @@ import ( "github.com/cosmos/cosmos-sdk/x/slashing" slashingkeeper "github.com/cosmos/cosmos-sdk/x/slashing/keeper" "github.com/cosmos/cosmos-sdk/x/slashing/testutil" - "github.com/cosmos/cosmos-sdk/x/staking" stakingkeeper "github.com/cosmos/cosmos-sdk/x/staking/keeper" stakingtestutil "github.com/cosmos/cosmos-sdk/x/staking/testutil" stakingtypes "github.com/cosmos/cosmos-sdk/x/staking/types" @@ -46,7 +45,7 @@ func TestBeginBlocker(t *testing.T) { // bond the validator power := int64(100) amt := tstaking.CreateValidatorWithValPower(addr, pk, power, true) - staking.EndBlocker(ctx, stakingKeeper) + stakingKeeper.EndBlocker(ctx) require.Equal( t, bankKeeper.GetAllBalances(ctx, sdk.AccAddress(addr)), sdk.NewCoins(sdk.NewCoin(stakingKeeper.GetParams(ctx).BondDenom, InitTokens.Sub(amt))), @@ -97,7 +96,7 @@ func TestBeginBlocker(t *testing.T) { } // end block - staking.EndBlocker(ctx, stakingKeeper) + stakingKeeper.EndBlocker(ctx) // validator should be jailed validator, found := stakingKeeper.GetValidatorByConsAddr(ctx, sdk.GetConsAddress(pk)) diff --git a/x/slashing/app_test.go b/x/slashing/app_test.go index d95c8c5692ac..aa5ac935f197 100644 --- a/x/slashing/app_test.go +++ b/x/slashing/app_test.go @@ -77,7 +77,7 @@ func TestSlashingMsgs(t *testing.T) { require.NoError(t, err) header := cmtproto.Header{Height: app.LastBlockHeight() + 1} - txConfig := moduletestutil.MakeTestEncodingConfig().TxConfig + txConfig := moduletestutil.MakeTestTxConfig() _, _, err = sims.SignCheckDeliver(t, txConfig, app.BaseApp, header, []sdk.Msg{createValidatorMsg}, "", []uint64{0}, []uint64{0}, true, true, priv1) require.NoError(t, err) require.True(t, sdk.Coins{genCoin.Sub(bondCoin)}.Equal(bankKeeper.GetAllBalances(ctxCheck, addr1))) diff --git a/x/slashing/client/cli/query_test.go b/x/slashing/client/cli/query_test.go index a86a30a1e7e7..0779025cfc99 100644 --- a/x/slashing/client/cli/query_test.go +++ b/x/slashing/client/cli/query_test.go @@ -1,7 +1,6 @@ package cli_test import ( - "bytes" "fmt" "io" "testing" @@ -52,7 +51,6 @@ func (s *CLITestSuite) SetupSuite() { WithOutput(io.Discard). WithChainID("test-chain") - var outBuf bytes.Buffer ctxGen := func() client.Context { bz, _ := s.encCfg.Codec.Marshal(&sdk.TxResponse{}) c := clitestutil.NewMockCometRPC(abci.ResponseQuery{ @@ -61,7 +59,7 @@ func (s *CLITestSuite) SetupSuite() { return s.baseCtx.WithClient(c) } - s.clientCtx = ctxGen().WithOutput(&outBuf) + s.clientCtx = ctxGen() k, _, err := s.clientCtx.Keyring.NewMnemonic("NewValidator", keyring.English, sdk.FullFundraiserPath, keyring.DefaultBIP39Passphrase, hd.Secp256k1) s.Require().NoError(err) diff --git a/x/slashing/client/cli/tx_test.go b/x/slashing/client/cli/tx_test.go index 8ffc9b9e473c..b7dff299e14c 100644 --- a/x/slashing/client/cli/tx_test.go +++ b/x/slashing/client/cli/tx_test.go @@ -3,8 +3,6 @@ package cli_test import ( "fmt" - "github.com/cosmos/gogoproto/proto" - "github.com/cosmos/cosmos-sdk/client/flags" clitestutil "github.com/cosmos/cosmos-sdk/testutil/cli" sdk "github.com/cosmos/cosmos-sdk/types" @@ -16,9 +14,7 @@ func (s *CLITestSuite) TestNewUnjailTxCmd() { testCases := []struct { name string args []string - expectErr bool - expectedCode uint32 - respType proto.Message + expectErrMsg string }{ { "valid transaction", @@ -28,7 +24,7 @@ func (s *CLITestSuite) TestNewUnjailTxCmd() { fmt.Sprintf("--%s=%s", flags.FlagBroadcastMode, flags.BroadcastSync), // sync mode as there are no funds yet fmt.Sprintf("--%s=%s", flags.FlagFees, sdk.NewCoins(sdk.NewCoin(sdk.DefaultBondDenom, sdk.NewInt(10))).String()), }, - false, 0, &sdk.TxResponse{}, + "", }, } @@ -40,14 +36,12 @@ func (s *CLITestSuite) TestNewUnjailTxCmd() { clientCtx := s.clientCtx out, err := clitestutil.ExecTestCLICmd(clientCtx, cmd, tc.args) - if tc.expectErr { + if tc.expectErrMsg != "" { s.Require().Error(err) } else { s.Require().NoError(err) - s.Require().NoError(clientCtx.Codec.UnmarshalJSON(out.Bytes(), tc.respType), out.String()) - - txResp := tc.respType.(*sdk.TxResponse) - s.Require().Equal(tc.expectedCode, txResp.Code, out.String()) + txResp := &sdk.TxResponse{} + s.Require().NoError(clientCtx.Codec.UnmarshalJSON(out.Bytes(), txResp), out.String()) } }) } diff --git a/x/slashing/keeper/genesis.go b/x/slashing/keeper/genesis.go index e53ef3730c06..dda2da2431d6 100644 --- a/x/slashing/keeper/genesis.go +++ b/x/slashing/keeper/genesis.go @@ -6,8 +6,8 @@ import ( stakingtypes "github.com/cosmos/cosmos-sdk/x/staking/types" ) -// InitGenesis initialize default parameters -// and the keeper's address to pubkey map +// InitGenesis initializes default parameters and the keeper's address to +// pubkey map. func (keeper Keeper) InitGenesis(ctx sdk.Context, stakingKeeper types.StakingKeeper, data *types.GenesisState) { stakingKeeper.IterateValidators(ctx, func(index int64, validator stakingtypes.ValidatorI) bool { @@ -15,6 +15,7 @@ func (keeper Keeper) InitGenesis(ctx sdk.Context, stakingKeeper types.StakingKee if err != nil { panic(err) } + keeper.AddPubkey(ctx, consPk) return false }, @@ -33,8 +34,11 @@ func (keeper Keeper) InitGenesis(ctx sdk.Context, stakingKeeper types.StakingKee if err != nil { panic(err) } + for _, missed := range array.MissedBlocks { - keeper.SetValidatorMissedBlockBitArray(ctx, address, missed.Index, missed.Missed) + if err := keeper.SetMissedBlockBitmapValue(ctx, address, missed.Index, missed.Missed); err != nil { + panic(err) + } } } diff --git a/x/slashing/keeper/genesis_test.go b/x/slashing/keeper/genesis_test.go index 5aea8f4204e5..3db4d79b580d 100644 --- a/x/slashing/keeper/genesis_test.go +++ b/x/slashing/keeper/genesis_test.go @@ -42,11 +42,11 @@ func (s *KeeperTestSuite) TestExportAndInitGenesis() { newInfo1, _ := keeper.GetValidatorSigningInfo(ctx, consAddr1) require.NotEqual(info1, newInfo1) - // Initialise genesis with genesis state before tombstone + // Initialize genesis with genesis state before tombstone s.stakingKeeper.EXPECT().IterateValidators(ctx, gomock.Any()).Return() keeper.InitGenesis(ctx, s.stakingKeeper, genesisState) - // Validator isTombstoned should return false as GenesisState is initialised + // Validator isTombstoned should return false as GenesisState is initialized ok = keeper.IsTombstoned(ctx, consAddr1) require.False(ok) diff --git a/x/slashing/keeper/grpc_query.go b/x/slashing/keeper/grpc_query.go index 986fac8159e1..f39fd9f71fc4 100644 --- a/x/slashing/keeper/grpc_query.go +++ b/x/slashing/keeper/grpc_query.go @@ -62,7 +62,7 @@ func (k Keeper) SigningInfos(c context.Context, req *types.QuerySigningInfosRequ var signInfos []types.ValidatorSigningInfo sigInfoStore := prefix.NewStore(store, types.ValidatorSigningInfoKeyPrefix) - pageRes, err := query.Paginate(sigInfoStore, req.Pagination, func(key []byte, value []byte) error { + pageRes, err := query.Paginate(sigInfoStore, req.Pagination, func(key, value []byte) error { var info types.ValidatorSigningInfo err := k.cdc.Unmarshal(value, &info) if err != nil { diff --git a/x/slashing/keeper/infractions.go b/x/slashing/keeper/infractions.go index 17f56d04c6cc..557a48a639cf 100644 --- a/x/slashing/keeper/infractions.go +++ b/x/slashing/keeper/infractions.go @@ -3,6 +3,8 @@ package keeper import ( "fmt" + "github.com/cockroachdb/errors" + cryptotypes "github.com/cosmos/cosmos-sdk/crypto/types" sdk "github.com/cosmos/cosmos-sdk/types" "github.com/cosmos/cosmos-sdk/x/slashing/types" @@ -31,27 +33,42 @@ func (k Keeper) HandleValidatorSignature(ctx sdk.Context, addr cryptotypes.Addre panic(fmt.Sprintf("Expected signing info for validator %s but not found", consAddr)) } - // this is a relative index, so it counts blocks the validator *should* have signed - // will use the 0-value default signing info if not present, except for start height + // Compute the relative index, so we count the blocks the validator *should* + // have signed. We will use the 0-value default signing info if not present, + // except for start height. The index is in the range [0, SignedBlocksWindow) + // and is used to see if a validator signed a block at the given height, which + // is represented by a bit in the bitmap. index := signInfo.IndexOffset % k.SignedBlocksWindow(ctx) signInfo.IndexOffset++ - // Update signed block bit array & counter - // This counter just tracks the sum of the bit array - // That way we avoid needing to read/write the whole array each time - previous := k.GetValidatorMissedBlockBitArray(ctx, consAddr, index) + // determine if the validator signed the previous block + previous, err := k.GetMissedBlockBitmapValue(ctx, consAddr, index) + if err != nil { + panic(errors.Wrap(err, "failed to get the validator's bitmap value")) + } + missed := !signed switch { case !previous && missed: - // Array value has changed from not missed to missed, increment counter - k.SetValidatorMissedBlockBitArray(ctx, consAddr, index, true) + // Bitmap value has changed from not missed to missed, so we flip the bit + // and increment the counter. + if err := k.SetMissedBlockBitmapValue(ctx, consAddr, index, true); err != nil { + panic(err) + } + signInfo.MissedBlocksCounter++ + case previous && !missed: - // Array value has changed from missed to not missed, decrement counter - k.SetValidatorMissedBlockBitArray(ctx, consAddr, index, false) + // Bitmap value has changed from missed to not missed, so we flip the bit + // and decrement the counter. + if err := k.SetMissedBlockBitmapValue(ctx, consAddr, index, false); err != nil { + panic(err) + } + signInfo.MissedBlocksCounter-- + default: - // Array value at this index has not changed, no need to update counter + // bitmap value at this index has not changed, no need to update counter } minSignedPerWindow := k.MinSignedPerWindow(ctx) @@ -105,10 +122,11 @@ func (k Keeper) HandleValidatorSignature(ctx sdk.Context, addr cryptotypes.Addre signInfo.JailedUntil = ctx.BlockHeader().Time.Add(k.DowntimeJailDuration(ctx)) - // We need to reset the counter & array so that the validator won't be immediately slashed for downtime upon rebonding. + // We need to reset the counter & bitmap so that the validator won't be + // immediately slashed for downtime upon re-bonding. signInfo.MissedBlocksCounter = 0 signInfo.IndexOffset = 0 - k.clearValidatorMissedBlockBitArray(ctx, consAddr) + k.DeleteMissedBlockBitmap(ctx, consAddr) logger.Info( "slashing and jailing validator due to liveness fault", diff --git a/x/slashing/keeper/migrations.go b/x/slashing/keeper/migrations.go index fca5255e6f68..5fb281ccc6c0 100644 --- a/x/slashing/keeper/migrations.go +++ b/x/slashing/keeper/migrations.go @@ -5,6 +5,7 @@ import ( "github.com/cosmos/cosmos-sdk/x/slashing/exported" v2 "github.com/cosmos/cosmos-sdk/x/slashing/migrations/v2" v3 "github.com/cosmos/cosmos-sdk/x/slashing/migrations/v3" + v4 "github.com/cosmos/cosmos-sdk/x/slashing/migrations/v4" ) // Migrator is a struct for handling in-place store migrations. @@ -30,3 +31,10 @@ func (m Migrator) Migrate1to2(ctx sdk.Context) error { func (m Migrator) Migrate2to3(ctx sdk.Context) error { return v3.Migrate(ctx, ctx.KVStore(m.keeper.storeKey), m.legacySubspace, m.keeper.cdc) } + +// Migrate3to4 migrates the x/slashing module state from the consensus +// version 3 to version 4. Specifically, it migrates the validator missed block +// bitmap. +func (m Migrator) Migrate3to4(ctx sdk.Context) error { + return v4.Migrate(ctx, m.keeper.cdc, ctx.KVStore(m.keeper.storeKey), m.keeper.GetParams(ctx)) +} diff --git a/x/slashing/keeper/msg_server.go b/x/slashing/keeper/msg_server.go index d671e578fbcb..b5663393342f 100644 --- a/x/slashing/keeper/msg_server.go +++ b/x/slashing/keeper/msg_server.go @@ -6,6 +6,7 @@ import ( "cosmossdk.io/errors" sdk "github.com/cosmos/cosmos-sdk/types" + sdkerrors "github.com/cosmos/cosmos-sdk/types/errors" govtypes "github.com/cosmos/cosmos-sdk/x/gov/types" "github.com/cosmos/cosmos-sdk/x/slashing/types" ) @@ -24,12 +25,17 @@ func NewMsgServerImpl(keeper Keeper) types.MsgServer { // UpdateParams implements MsgServer.UpdateParams method. // It defines a method to update the x/slashing module parameters. -func (k msgServer) UpdateParams(goCtx context.Context, req *types.MsgUpdateParams) (*types.MsgUpdateParamsResponse, error) { - if k.authority != req.Authority { - return nil, errors.Wrapf(govtypes.ErrInvalidSigner, "invalid authority; expected %s, got %s", k.authority, req.Authority) +func (k msgServer) UpdateParams(goCtx context.Context, msg *types.MsgUpdateParams) (*types.MsgUpdateParamsResponse, error) { + if k.authority != msg.Authority { + return nil, errors.Wrapf(govtypes.ErrInvalidSigner, "invalid authority; expected %s, got %s", k.authority, msg.Authority) } + + if err := msg.Params.Validate(); err != nil { + return nil, err + } + ctx := sdk.UnwrapSDKContext(goCtx) - if err := k.SetParams(ctx, req.Params); err != nil { + if err := k.SetParams(ctx, msg.Params); err != nil { return nil, err } @@ -40,14 +46,13 @@ func (k msgServer) UpdateParams(goCtx context.Context, req *types.MsgUpdateParam // Validators must submit a transaction to unjail itself after // having been jailed (and thus unbonded) for downtime func (k msgServer) Unjail(goCtx context.Context, msg *types.MsgUnjail) (*types.MsgUnjailResponse, error) { - ctx := sdk.UnwrapSDKContext(goCtx) - - valAddr, valErr := sdk.ValAddressFromBech32(msg.ValidatorAddr) - if valErr != nil { - return nil, valErr - } - err := k.Keeper.Unjail(ctx, valAddr) + valAddr, err := sdk.ValAddressFromBech32(msg.ValidatorAddr) if err != nil { + return nil, sdkerrors.ErrInvalidAddress.Wrapf("validator input address: %s", err) + } + + ctx := sdk.UnwrapSDKContext(goCtx) + if err := k.Keeper.Unjail(ctx, valAddr); err != nil { return nil, err } diff --git a/x/slashing/keeper/msg_server_test.go b/x/slashing/keeper/msg_server_test.go index 5db479c20976..2fa9bc681638 100644 --- a/x/slashing/keeper/msg_server_test.go +++ b/x/slashing/keeper/msg_server_test.go @@ -150,6 +150,16 @@ func (s *KeeperTestSuite) TestUnjail() { expErr bool expErrMsg string }{ + { + name: "invalid validator address: invalid request", + malleate: func() *slashingtypes.MsgUnjail { + return &slashingtypes.MsgUnjail{ + ValidatorAddr: "invalid", + } + }, + expErr: true, + expErrMsg: "decoding bech32 failed", + }, { name: "no self delegation: invalid request", malleate: func() *slashingtypes.MsgUnjail { diff --git a/x/slashing/keeper/params.go b/x/slashing/keeper/params.go index 4c7fc1824694..787b108be6e6 100644 --- a/x/slashing/keeper/params.go +++ b/x/slashing/keeper/params.go @@ -49,11 +49,8 @@ func (k Keeper) GetParams(ctx sdk.Context) (params types.Params) { } // SetParams sets the x/slashing module parameters. +// CONTRACT: This method performs no validation of the parameters. func (k Keeper) SetParams(ctx sdk.Context, params types.Params) error { - if err := params.Validate(); err != nil { - return err - } - store := ctx.KVStore(k.storeKey) bz := k.cdc.MustMarshal(¶ms) store.Set(types.ParamsKey, bz) diff --git a/x/slashing/keeper/params_test.go b/x/slashing/keeper/params_test.go deleted file mode 100644 index bcf96ef136c0..000000000000 --- a/x/slashing/keeper/params_test.go +++ /dev/null @@ -1,127 +0,0 @@ -package keeper_test - -import ( - "time" - - sdk "github.com/cosmos/cosmos-sdk/types" - "github.com/cosmos/cosmos-sdk/x/slashing/types" -) - -func (s *KeeperTestSuite) TestParams() { - ctx, keeper := s.ctx, s.slashingKeeper - require := s.Require() - - minSignedPerWindow, err := sdk.NewDecFromStr("0.60") - require.NoError(err) - - slashFractionDoubleSign, err := sdk.NewDecFromStr("0.022") - require.NoError(err) - - slashFractionDowntime, err := sdk.NewDecFromStr("0.0089") - require.NoError(err) - - invalidVal, err := sdk.NewDecFromStr("-1") - require.NoError(err) - - testCases := []struct { - name string - input types.Params - expectErr bool - expErrMsg string - }{ - { - name: "set invalid signed blocks window", - input: types.Params{ - SignedBlocksWindow: 0, - MinSignedPerWindow: minSignedPerWindow, - DowntimeJailDuration: time.Duration(34800000000000), - SlashFractionDoubleSign: slashFractionDoubleSign, - SlashFractionDowntime: slashFractionDowntime, - }, - expectErr: true, - expErrMsg: "signed blocks window must be positive", - }, - { - name: "set invalid min signed per window", - input: types.Params{ - SignedBlocksWindow: int64(750), - MinSignedPerWindow: invalidVal, - DowntimeJailDuration: time.Duration(34800000000000), - SlashFractionDoubleSign: slashFractionDoubleSign, - SlashFractionDowntime: slashFractionDowntime, - }, - expectErr: true, - expErrMsg: "min signed per window cannot be negative", - }, - { - name: "set invalid downtime jail duration", - input: types.Params{ - SignedBlocksWindow: int64(750), - MinSignedPerWindow: minSignedPerWindow, - DowntimeJailDuration: time.Duration(0), - SlashFractionDoubleSign: slashFractionDoubleSign, - SlashFractionDowntime: slashFractionDowntime, - }, - expectErr: true, - expErrMsg: "downtime jail duration must be positive", - }, - { - name: "set invalid slash fraction double sign", - input: types.Params{ - SignedBlocksWindow: int64(750), - MinSignedPerWindow: minSignedPerWindow, - DowntimeJailDuration: time.Duration(10), - SlashFractionDoubleSign: invalidVal, - SlashFractionDowntime: slashFractionDowntime, - }, - expectErr: true, - expErrMsg: "double sign slash fraction cannot be negative", - }, - { - name: "set invalid slash fraction downtime", - input: types.Params{ - SignedBlocksWindow: int64(750), - MinSignedPerWindow: minSignedPerWindow, - DowntimeJailDuration: time.Duration(10), - SlashFractionDoubleSign: slashFractionDoubleSign, - SlashFractionDowntime: invalidVal, - }, - expectErr: true, - expErrMsg: "downtime slash fraction cannot be negative", - }, - { - name: "set all valid params", - input: types.Params{ - SignedBlocksWindow: int64(750), - MinSignedPerWindow: minSignedPerWindow, - DowntimeJailDuration: time.Duration(34800000000000), - SlashFractionDoubleSign: slashFractionDoubleSign, - SlashFractionDowntime: slashFractionDowntime, - }, - expectErr: false, - }, - } - for _, tc := range testCases { - tc := tc - s.Run(tc.name, func() { - expected := keeper.GetParams(ctx) - err := keeper.SetParams(ctx, tc.input) - - if tc.expectErr { - require.Error(err) - require.Contains(err.Error(), tc.expErrMsg) - } else { - expected = tc.input - require.NoError(err) - } - - params := keeper.GetParams(ctx) - require.Equal(params, expected) - require.Equal(keeper.SignedBlocksWindow(ctx), expected.SignedBlocksWindow) - require.Equal(keeper.MinSignedPerWindow(ctx), expected.MinSignedPerWindow.MulInt64(expected.SignedBlocksWindow).RoundInt64()) - require.Equal(keeper.DowntimeJailDuration(ctx), expected.DowntimeJailDuration) - require.Equal(keeper.SlashFractionDoubleSign(ctx), expected.SlashFractionDoubleSign) - require.Equal(keeper.SlashFractionDowntime(ctx), expected.SlashFractionDowntime) - }) - } -} diff --git a/x/slashing/keeper/signing_info.go b/x/slashing/keeper/signing_info.go index df72366e306f..628b262369ea 100644 --- a/x/slashing/keeper/signing_info.go +++ b/x/slashing/keeper/signing_info.go @@ -3,9 +3,9 @@ package keeper import ( "time" - gogotypes "github.com/cosmos/gogoproto/types" - storetypes "cosmossdk.io/store/types" + "github.com/bits-and-blooms/bitset" + "github.com/cockroachdb/errors" sdk "github.com/cosmos/cosmos-sdk/types" "github.com/cosmos/cosmos-sdk/x/slashing/types" @@ -13,20 +13,21 @@ import ( // GetValidatorSigningInfo retruns the ValidatorSigningInfo for a specific validator // ConsAddress -func (k Keeper) GetValidatorSigningInfo(ctx sdk.Context, address sdk.ConsAddress) (info types.ValidatorSigningInfo, found bool) { +func (k Keeper) GetValidatorSigningInfo(ctx sdk.Context, address sdk.ConsAddress) (types.ValidatorSigningInfo, bool) { store := ctx.KVStore(k.storeKey) + + var info types.ValidatorSigningInfo bz := store.Get(types.ValidatorSigningInfoKey(address)) if bz == nil { - found = false - return + return info, false } + k.cdc.MustUnmarshal(bz, &info) - found = true - return + return info, true } // HasValidatorSigningInfo returns if a given validator has signing information -// persited. +// persisted. func (k Keeper) HasValidatorSigningInfo(ctx sdk.Context, consAddr sdk.ConsAddress) bool { _, ok := k.GetValidatorSigningInfo(ctx, consAddr) return ok @@ -56,53 +57,6 @@ func (k Keeper) IterateValidatorSigningInfos(ctx sdk.Context, } } -// GetValidatorMissedBlockBitArray gets the bit for the missed blocks array -func (k Keeper) GetValidatorMissedBlockBitArray(ctx sdk.Context, address sdk.ConsAddress, index int64) bool { - store := ctx.KVStore(k.storeKey) - bz := store.Get(types.ValidatorMissedBlockBitArrayKey(address, index)) - var missed gogotypes.BoolValue - if bz == nil { - // lazy: treat empty key as not missed - return false - } - k.cdc.MustUnmarshal(bz, &missed) - - return missed.Value -} - -// IterateValidatorMissedBlockBitArray iterates over the signed blocks window -// and performs a callback function -func (k Keeper) IterateValidatorMissedBlockBitArray(ctx sdk.Context, - address sdk.ConsAddress, handler func(index int64, missed bool) (stop bool), -) { - store := ctx.KVStore(k.storeKey) - index := int64(0) - // Array may be sparse - for ; index < k.SignedBlocksWindow(ctx); index++ { - var missed gogotypes.BoolValue - bz := store.Get(types.ValidatorMissedBlockBitArrayKey(address, index)) - if bz == nil { - continue - } - - k.cdc.MustUnmarshal(bz, &missed) - if handler(index, missed.Value) { - break - } - } -} - -// GetValidatorMissedBlocks returns array of missed blocks for given validator Cons address -func (k Keeper) GetValidatorMissedBlocks(ctx sdk.Context, address sdk.ConsAddress) []types.MissedBlock { - missedBlocks := []types.MissedBlock{} - k.IterateValidatorMissedBlockBitArray(ctx, address, func(index int64, missed bool) (stop bool) { - missedBlocks = append(missedBlocks, types.NewMissedBlock(index, missed)) - return false - }) - - return missedBlocks -} - // JailUntil attempts to set a validator's JailedUntil attribute in its signing // info. It will panic if the signing info does not exist for the validator. func (k Keeper) JailUntil(ctx sdk.Context, consAddr sdk.ConsAddress, jailTime time.Time) { @@ -141,20 +95,135 @@ func (k Keeper) IsTombstoned(ctx sdk.Context, consAddr sdk.ConsAddress) bool { return signInfo.Tombstoned } -// SetValidatorMissedBlockBitArray sets the bit that checks if the validator has -// missed a block in the current window -func (k Keeper) SetValidatorMissedBlockBitArray(ctx sdk.Context, address sdk.ConsAddress, index int64, missed bool) { +// getMissedBlockBitmapChunk gets the bitmap chunk at the given chunk index for +// a validator's missed block signing window. +func (k Keeper) getMissedBlockBitmapChunk(ctx sdk.Context, addr sdk.ConsAddress, chunkIndex int64) []byte { store := ctx.KVStore(k.storeKey) - bz := k.cdc.MustMarshal(&gogotypes.BoolValue{Value: missed}) - store.Set(types.ValidatorMissedBlockBitArrayKey(address, index), bz) + chunk := store.Get(types.ValidatorMissedBlockBitmapKey(addr, chunkIndex)) + return chunk } -// clearValidatorMissedBlockBitArray deletes every instance of ValidatorMissedBlockBitArray in the store -func (k Keeper) clearValidatorMissedBlockBitArray(ctx sdk.Context, address sdk.ConsAddress) { +// setMissedBlockBitmapChunk sets the bitmap chunk at the given chunk index for +// a validator's missed block signing window. +func (k Keeper) setMissedBlockBitmapChunk(ctx sdk.Context, addr sdk.ConsAddress, chunkIndex int64, chunk []byte) { store := ctx.KVStore(k.storeKey) - iter := storetypes.KVStorePrefixIterator(store, types.ValidatorMissedBlockBitArrayPrefixKey(address)) + key := types.ValidatorMissedBlockBitmapKey(addr, chunkIndex) + store.Set(key, chunk) +} + +// GetMissedBlockBitmapValue returns true if a validator missed signing a block +// at the given index and false otherwise. The index provided is assumed to be +// the index in the range [0, SignedBlocksWindow), which represents the bitmap +// where each bit represents a height, and is determined by the validator's +// IndexOffset modulo SignedBlocksWindow. This index is used to fetch the chunk +// in the bitmap and the relative bit in that chunk. +func (k Keeper) GetMissedBlockBitmapValue(ctx sdk.Context, addr sdk.ConsAddress, index int64) (bool, error) { + // get the chunk or "word" in the logical bitmap + chunkIndex := index / types.MissedBlockBitmapChunkSize + + bs := bitset.New(uint(types.MissedBlockBitmapChunkSize)) + chunk := k.getMissedBlockBitmapChunk(ctx, addr, chunkIndex) + if chunk != nil { + if err := bs.UnmarshalBinary(chunk); err != nil { + return false, errors.Wrapf(err, "failed to decode bitmap chunk; index: %d", index) + } + } + + // get the bit position in the chunk of the logical bitmap, where Test() + // checks if the bit is set. + bitIndex := index % types.MissedBlockBitmapChunkSize + return bs.Test(uint(bitIndex)), nil +} + +// SetMissedBlockBitmapValue sets, i.e. flips, a bit in the validator's missed +// block bitmap. When missed=true, the bit is set, otherwise it set to zero. The +// index provided is assumed to be the index in the range [0, SignedBlocksWindow), +// which represents the bitmap where each bit represents a height, and is +// determined by the validator's IndexOffset modulo SignedBlocksWindow. This +// index is used to fetch the chunk in the bitmap and the relative bit in that +// chunk. +func (k Keeper) SetMissedBlockBitmapValue(ctx sdk.Context, addr sdk.ConsAddress, index int64, missed bool) error { + // get the chunk or "word" in the logical bitmap + chunkIndex := index / types.MissedBlockBitmapChunkSize + + bs := bitset.New(uint(types.MissedBlockBitmapChunkSize)) + chunk := k.getMissedBlockBitmapChunk(ctx, addr, chunkIndex) + if chunk != nil { + if err := bs.UnmarshalBinary(chunk); err != nil { + return errors.Wrapf(err, "failed to decode bitmap chunk; index: %d", index) + } + } + + // get the bit position in the chunk of the logical bitmap + bitIndex := uint(index % types.MissedBlockBitmapChunkSize) + if missed { + bs.Set(bitIndex) + } else { + bs.Clear(bitIndex) + } + + updatedChunk, err := bs.MarshalBinary() + if err != nil { + return errors.Wrapf(err, "failed to encode bitmap chunk; index: %d", index) + } + + k.setMissedBlockBitmapChunk(ctx, addr, chunkIndex, updatedChunk) + return nil +} + +// DeleteMissedBlockBitmap removes a validator's missed block bitmap from state. +func (k Keeper) DeleteMissedBlockBitmap(ctx sdk.Context, addr sdk.ConsAddress) { + store := ctx.KVStore(k.storeKey) + + iter := storetypes.KVStorePrefixIterator(store, types.ValidatorMissedBlockBitmapPrefixKey(addr)) defer iter.Close() + for ; iter.Valid(); iter.Next() { store.Delete(iter.Key()) } } + +// IterateMissedBlockBitmap iterates over a validator's signed blocks window +// bitmap and performs a callback function on each index, i.e. block height, in +// the range [0, SignedBlocksWindow). +// +// Note: A callback will only be executed over all bitmap chunks that exist in +// state. +func (k Keeper) IterateMissedBlockBitmap(ctx sdk.Context, addr sdk.ConsAddress, cb func(index int64, missed bool) (stop bool)) { + store := ctx.KVStore(k.storeKey) + + iter := storetypes.KVStorePrefixIterator(store, types.ValidatorMissedBlockBitmapPrefixKey(addr)) + defer iter.Close() + + var index int64 + for ; iter.Valid(); iter.Next() { + bs := bitset.New(uint(types.MissedBlockBitmapChunkSize)) + + if err := bs.UnmarshalBinary(iter.Value()); err != nil { + panic(errors.Wrapf(err, "failed to decode bitmap chunk; index: %v", string(iter.Key()))) + } + + for i := uint(0); i < types.MissedBlockBitmapChunkSize; i++ { + // execute the callback, where Test() returns true if the bit is set + if cb(index, bs.Test(i)) { + break + } + + index++ + } + } +} + +// GetValidatorMissedBlocks returns array of missed blocks for given validator. +func (k Keeper) GetValidatorMissedBlocks(ctx sdk.Context, addr sdk.ConsAddress) []types.MissedBlock { + missedBlocks := make([]types.MissedBlock, 0, k.SignedBlocksWindow(ctx)) + k.IterateMissedBlockBitmap(ctx, addr, func(index int64, missed bool) (stop bool) { + if missed { + missedBlocks = append(missedBlocks, types.NewMissedBlock(index, missed)) + } + + return false + }) + + return missedBlocks +} diff --git a/x/slashing/keeper/signing_info_test.go b/x/slashing/keeper/signing_info_test.go index f33fbf34b53d..c08e59f26520 100644 --- a/x/slashing/keeper/signing_info_test.go +++ b/x/slashing/keeper/signing_info_test.go @@ -53,41 +53,44 @@ func (s *KeeperTestSuite) TestValidatorSigningInfo() { require.Equal(sInfo.JailedUntil, jailTime) } -func (s *KeeperTestSuite) TestValidatorMissedBlockBitArray() { +func (s *KeeperTestSuite) TestValidatorMissedBlockBitmap_SmallWindow() { ctx, keeper := s.ctx, s.slashingKeeper require := s.Require() - params := testutil.TestParams() - params.SignedBlocksWindow = 100 - require.NoError(keeper.SetParams(ctx, params)) - - testCases := []struct { - name string - index int64 - missed bool - }{ - { - name: "missed block with false", - index: 50, - missed: false, - }, - { - name: "missed block with true", - index: 51, - missed: true, - }, - } - for ind, tc := range testCases { - tc := tc - s.Run(tc.name, func() { - keeper.SetValidatorMissedBlockBitArray(ctx, consAddr, tc.index, tc.missed) - missed := keeper.GetValidatorMissedBlockBitArray(ctx, consAddr, tc.index) - - require.Equal(missed, tc.missed) - missedBlocks := keeper.GetValidatorMissedBlocks(ctx, consAddr) - require.Equal(len(missedBlocks), ind+1) - require.Equal(missedBlocks[ind].Index, tc.index) - require.Equal(missedBlocks[ind].Missed, tc.missed) - }) + for _, window := range []int64{100, 32_000} { + params := testutil.TestParams() + params.SignedBlocksWindow = window + require.NoError(keeper.SetParams(ctx, params)) + + // validator misses all blocks in the window + var valIdxOffset int64 + for valIdxOffset < params.SignedBlocksWindow { + idx := valIdxOffset % params.SignedBlocksWindow + err := keeper.SetMissedBlockBitmapValue(ctx, consAddr, idx, true) + require.NoError(err) + + missed, err := keeper.GetMissedBlockBitmapValue(ctx, consAddr, idx) + require.NoError(err) + require.True(missed) + + valIdxOffset++ + } + + // validator should have missed all blocks + missedBlocks := keeper.GetValidatorMissedBlocks(ctx, consAddr) + require.Len(missedBlocks, int(params.SignedBlocksWindow)) + + // sign next block, which rolls the missed block bitmap + idx := valIdxOffset % params.SignedBlocksWindow + err := keeper.SetMissedBlockBitmapValue(ctx, consAddr, idx, false) + require.NoError(err) + + missed, err := keeper.GetMissedBlockBitmapValue(ctx, consAddr, idx) + require.NoError(err) + require.False(missed) + + // validator should have missed all blocks except the last one + missedBlocks = keeper.GetValidatorMissedBlocks(ctx, consAddr) + require.Len(missedBlocks, int(params.SignedBlocksWindow)-1) } } diff --git a/x/slashing/migrations/v2/keys.go b/x/slashing/migrations/v2/keys.go new file mode 100644 index 000000000000..26f3f97544f3 --- /dev/null +++ b/x/slashing/migrations/v2/keys.go @@ -0,0 +1,21 @@ +package v2 + +import ( + "encoding/binary" + + sdk "github.com/cosmos/cosmos-sdk/types" + "github.com/cosmos/cosmos-sdk/types/address" +) + +var ValidatorMissedBlockBitArrayKeyPrefix = []byte{0x02} + +func ValidatorMissedBlockBitArrayPrefixKey(v sdk.ConsAddress) []byte { + return append(ValidatorMissedBlockBitArrayKeyPrefix, address.MustLengthPrefix(v.Bytes())...) +} + +func ValidatorMissedBlockBitArrayKey(v sdk.ConsAddress, i int64) []byte { + b := make([]byte, 8) + binary.LittleEndian.PutUint64(b, uint64(i)) + + return append(ValidatorMissedBlockBitArrayPrefixKey(v), b...) +} diff --git a/x/slashing/migrations/v2/store_test.go b/x/slashing/migrations/v2/store_test.go index b824981cb465..da583b79e6d4 100644 --- a/x/slashing/migrations/v2/store_test.go +++ b/x/slashing/migrations/v2/store_test.go @@ -4,9 +4,8 @@ import ( "bytes" "testing" - "github.com/stretchr/testify/require" - storetypes "cosmossdk.io/store/types" + "github.com/stretchr/testify/require" "github.com/cosmos/cosmos-sdk/testutil" "github.com/cosmos/cosmos-sdk/testutil/testdata" @@ -39,7 +38,7 @@ func TestStoreMigration(t *testing.T) { { "ValidatorMissedBlockBitArrayKey", v1.ValidatorMissedBlockBitArrayKey(consAddr, 2), - types.ValidatorMissedBlockBitArrayKey(consAddr, 2), + v2.ValidatorMissedBlockBitArrayKey(consAddr, 2), }, { "AddrPubkeyRelationKey", diff --git a/x/slashing/migrations/v4/keys.go b/x/slashing/migrations/v4/keys.go new file mode 100644 index 000000000000..1ac42b6c1aff --- /dev/null +++ b/x/slashing/migrations/v4/keys.go @@ -0,0 +1,49 @@ +package v4 + +import ( + "encoding/binary" + + sdk "github.com/cosmos/cosmos-sdk/types" + "github.com/cosmos/cosmos-sdk/types/address" + "github.com/cosmos/cosmos-sdk/types/kv" +) + +const MissedBlockBitmapChunkSize = 1024 // 2^10 bits + +var ( + ValidatorSigningInfoKeyPrefix = []byte{0x01} + validatorMissedBlockBitArrayKeyPrefix = []byte{0x02} +) + +func ValidatorSigningInfoKey(v sdk.ConsAddress) []byte { + return append(ValidatorSigningInfoKeyPrefix, address.MustLengthPrefix(v.Bytes())...) +} + +func ValidatorSigningInfoAddress(key []byte) (v sdk.ConsAddress) { + // Remove prefix and address length. + kv.AssertKeyAtLeastLength(key, 3) + addr := key[2:] + + return sdk.ConsAddress(addr) +} + +func validatorMissedBlockBitArrayPrefixKey(v sdk.ConsAddress) []byte { + return append(validatorMissedBlockBitArrayKeyPrefix, v.Bytes()...) +} + +func ValidatorMissedBlockBitArrayKey(v sdk.ConsAddress, i int64) []byte { + b := make([]byte, 8) + binary.LittleEndian.PutUint64(b, uint64(i)) + return append(validatorMissedBlockBitArrayPrefixKey(v), b...) +} + +func validatorMissedBlockBitmapPrefixKey(v sdk.ConsAddress) []byte { + return append(validatorMissedBlockBitArrayKeyPrefix, address.MustLengthPrefix(v.Bytes())...) +} + +func ValidatorMissedBlockBitmapKey(v sdk.ConsAddress, chunkIndex int64) []byte { + bz := make([]byte, 8) + binary.LittleEndian.PutUint64(bz, uint64(chunkIndex)) + + return append(validatorMissedBlockBitmapPrefixKey(v), bz...) +} diff --git a/x/slashing/migrations/v4/migrate.go b/x/slashing/migrations/v4/migrate.go new file mode 100644 index 000000000000..01480c05e185 --- /dev/null +++ b/x/slashing/migrations/v4/migrate.go @@ -0,0 +1,153 @@ +package v4 + +import ( + "cosmossdk.io/errors" + storetypes "cosmossdk.io/store/types" + "github.com/bits-and-blooms/bitset" + gogotypes "github.com/cosmos/gogoproto/types" + + "github.com/cosmos/cosmos-sdk/codec" + sdk "github.com/cosmos/cosmos-sdk/types" + "github.com/cosmos/cosmos-sdk/x/slashing/types" +) + +// Migrate migrates state to consensus version 4. Specifically, the migration +// deletes all existing validator bitmap entries and replaces them with a real +// "chunked" bitmap. +func Migrate(ctx sdk.Context, cdc codec.BinaryCodec, store storetypes.KVStore, params types.Params) error { + // Get all the missed blocks for each validator, based on the existing signing + // info. + var missedBlocks []types.ValidatorMissedBlocks + iterateValidatorSigningInfos(ctx, cdc, store, func(addr sdk.ConsAddress, info types.ValidatorSigningInfo) (stop bool) { + bechAddr := addr.String() + localMissedBlocks := GetValidatorMissedBlocks(ctx, cdc, store, addr, params) + + missedBlocks = append(missedBlocks, types.ValidatorMissedBlocks{ + Address: bechAddr, + MissedBlocks: localMissedBlocks, + }) + + return false + }) + + // For each missed blocks entry, of which there should only be one per validator, + // we clear all the old entries and insert the new chunked entry. + for _, mb := range missedBlocks { + addr, err := sdk.ConsAddressFromBech32(mb.Address) + if err != nil { + return err + } + + deleteValidatorMissedBlockBitArray(ctx, store, addr) + + for _, b := range mb.MissedBlocks { + // Note: It is not necessary to store entries with missed=false, i.e. where + // the bit is zero, since when the bitmap is initialized, all non-set bits + // are already zero. + if b.Missed { + if err := setMissedBlockBitmapValue(ctx, store, addr, b.Index, true); err != nil { + return err + } + } + } + } + + return nil +} + +func iterateValidatorSigningInfos( + ctx sdk.Context, + cdc codec.BinaryCodec, + store storetypes.KVStore, + cb func(address sdk.ConsAddress, info types.ValidatorSigningInfo) (stop bool), +) { + iter := storetypes.KVStorePrefixIterator(store, ValidatorSigningInfoKeyPrefix) + defer iter.Close() + + for ; iter.Valid(); iter.Next() { + address := ValidatorSigningInfoAddress(iter.Key()) + var info types.ValidatorSigningInfo + cdc.MustUnmarshal(iter.Value(), &info) + + if cb(address, info) { + break + } + } +} + +func iterateValidatorMissedBlockBitArray( + ctx sdk.Context, + cdc codec.BinaryCodec, + store storetypes.KVStore, + addr sdk.ConsAddress, + params types.Params, + cb func(index int64, missed bool) (stop bool), +) { + for i := int64(0); i < params.SignedBlocksWindow; i++ { + var missed gogotypes.BoolValue + bz := store.Get(ValidatorMissedBlockBitArrayKey(addr, i)) + if bz == nil { + continue + } + + cdc.MustUnmarshal(bz, &missed) + if cb(i, missed.Value) { + break + } + } +} + +func GetValidatorMissedBlocks( + ctx sdk.Context, + cdc codec.BinaryCodec, + store storetypes.KVStore, + addr sdk.ConsAddress, + params types.Params, +) []types.MissedBlock { + var missedBlocks []types.MissedBlock + iterateValidatorMissedBlockBitArray(ctx, cdc, store, addr, params, func(index int64, missed bool) (stop bool) { + missedBlocks = append(missedBlocks, types.NewMissedBlock(index, missed)) + return false + }) + + return missedBlocks +} + +func deleteValidatorMissedBlockBitArray(ctx sdk.Context, store storetypes.KVStore, addr sdk.ConsAddress) { + iter := storetypes.KVStorePrefixIterator(store, validatorMissedBlockBitArrayPrefixKey(addr)) + defer iter.Close() + + for ; iter.Valid(); iter.Next() { + store.Delete(iter.Key()) + } +} + +func setMissedBlockBitmapValue(ctx sdk.Context, store storetypes.KVStore, addr sdk.ConsAddress, index int64, missed bool) error { + // get the chunk or "word" in the logical bitmap + chunkIndex := index / MissedBlockBitmapChunkSize + key := ValidatorMissedBlockBitmapKey(addr, chunkIndex) + + bs := bitset.New(uint(MissedBlockBitmapChunkSize)) + chunk := store.Get(key) + if chunk != nil { + if err := bs.UnmarshalBinary(chunk); err != nil { + return errors.Wrapf(err, "failed to decode bitmap chunk; index: %d", index) + } + } + + // get the bit position in the chunk of the logical bitmap + bitIndex := uint(index % MissedBlockBitmapChunkSize) + if missed { + bs.Set(bitIndex) + } else { + bs.Clear(bitIndex) + } + + updatedChunk, err := bs.MarshalBinary() + if err != nil { + return errors.Wrapf(err, "failed to encode bitmap chunk; index: %d", index) + } + + store.Set(key, updatedChunk) + return nil +} diff --git a/x/slashing/migrations/v4/migrate_test.go b/x/slashing/migrations/v4/migrate_test.go new file mode 100644 index 000000000000..a49ae658166f --- /dev/null +++ b/x/slashing/migrations/v4/migrate_test.go @@ -0,0 +1,64 @@ +package v4_test + +import ( + "testing" + + storetypes "cosmossdk.io/store/types" + "github.com/bits-and-blooms/bitset" + gogotypes "github.com/cosmos/gogoproto/types" + "github.com/stretchr/testify/require" + + "github.com/cosmos/cosmos-sdk/testutil" + sdk "github.com/cosmos/cosmos-sdk/types" + moduletestutil "github.com/cosmos/cosmos-sdk/types/module/testutil" + "github.com/cosmos/cosmos-sdk/x/slashing" + v4 "github.com/cosmos/cosmos-sdk/x/slashing/migrations/v4" + slashingtypes "github.com/cosmos/cosmos-sdk/x/slashing/types" +) + +var consAddr = sdk.ConsAddress(sdk.AccAddress([]byte("addr1_______________"))) + +func TestMigrate(t *testing.T) { + cdc := moduletestutil.MakeTestEncodingConfig(slashing.AppModuleBasic{}).Codec + storeKey := storetypes.NewKVStoreKey(slashingtypes.ModuleName) + tKey := storetypes.NewTransientStoreKey("transient_test") + ctx := testutil.DefaultContext(storeKey, tKey) + store := ctx.KVStore(storeKey) + params := slashingtypes.Params{SignedBlocksWindow: 100} + + // store old signing info and bitmap entries + bz := cdc.MustMarshal(&slashingtypes.ValidatorSigningInfo{Address: consAddr.String()}) + store.Set(v4.ValidatorSigningInfoKey(consAddr), bz) + + for i := int64(0); i < params.SignedBlocksWindow; i++ { + // all even blocks are missed + missed := &gogotypes.BoolValue{Value: i%2 == 0} + bz := cdc.MustMarshal(missed) + store.Set(v4.ValidatorMissedBlockBitArrayKey(consAddr, i), bz) + } + + err := v4.Migrate(ctx, cdc, store, params) + require.NoError(t, err) + + // ensure old entries no longer exist and new bitmap chunk entries exist + entries := v4.GetValidatorMissedBlocks(ctx, cdc, store, consAddr, params) + require.Empty(t, entries) + + for i := int64(0); i < params.SignedBlocksWindow; i++ { + chunkIndex := i / v4.MissedBlockBitmapChunkSize + chunk := store.Get(v4.ValidatorMissedBlockBitmapKey(consAddr, chunkIndex)) + require.NotNil(t, chunk) + + bs := bitset.New(uint(v4.MissedBlockBitmapChunkSize)) + require.NoError(t, bs.UnmarshalBinary(chunk)) + + // ensure all even blocks are missed + bitIndex := uint(i % v4.MissedBlockBitmapChunkSize) + require.Equal(t, i%2 == 0, bs.Test(bitIndex)) + require.Equal(t, i%2 == 1, !bs.Test(bitIndex)) + } + + // ensure there's only one chunk for a window of size 100 + chunk := store.Get(v4.ValidatorMissedBlockBitmapKey(consAddr, 1)) + require.Nil(t, chunk) +} diff --git a/x/slashing/module.go b/x/slashing/module.go index 7374e27ab075..e92ad1b47a3f 100644 --- a/x/slashing/module.go +++ b/x/slashing/module.go @@ -5,15 +5,13 @@ import ( "encoding/json" "fmt" - abci "github.com/cometbft/cometbft/abci/types" - gwruntime "github.com/grpc-ecosystem/grpc-gateway/runtime" - "github.com/spf13/cobra" - modulev1 "cosmossdk.io/api/cosmos/slashing/module/v1" "cosmossdk.io/core/appmodule" "cosmossdk.io/depinject" - store "cosmossdk.io/store/types" + abci "github.com/cometbft/cometbft/abci/types" + gwruntime "github.com/grpc-ecosystem/grpc-gateway/runtime" + "github.com/spf13/cobra" "github.com/cosmos/cosmos-sdk/client" "github.com/cosmos/cosmos-sdk/codec" @@ -32,7 +30,7 @@ import ( ) // ConsensusVersion defines the current x/slashing module consensus version. -const ConsensusVersion = 3 +const ConsensusVersion = 4 var ( _ module.AppModuleBasic = AppModuleBasic{} @@ -98,6 +96,8 @@ func (AppModuleBasic) GetQueryCmd() *cobra.Command { type AppModule struct { AppModuleBasic + registry cdctypes.InterfaceRegistry + keeper keeper.Keeper accountKeeper types.AccountKeeper bankKeeper types.BankKeeper @@ -108,7 +108,15 @@ type AppModule struct { } // NewAppModule creates a new AppModule object -func NewAppModule(cdc codec.Codec, keeper keeper.Keeper, ak types.AccountKeeper, bk types.BankKeeper, sk types.StakingKeeper, ss exported.Subspace) AppModule { +func NewAppModule( + cdc codec.Codec, + keeper keeper.Keeper, + ak types.AccountKeeper, + bk types.BankKeeper, + sk types.StakingKeeper, + ss exported.Subspace, + registry cdctypes.InterfaceRegistry, +) AppModule { return AppModule{ AppModuleBasic: AppModuleBasic{cdc: cdc}, keeper: keeper, @@ -148,6 +156,10 @@ func (am AppModule) RegisterServices(cfg module.Configurator) { if err := cfg.RegisterMigration(types.ModuleName, 2, m.Migrate2to3); err != nil { panic(fmt.Sprintf("failed to migrate x/%s from version 2 to 3: %v", types.ModuleName, err)) } + + if err := cfg.RegisterMigration(types.ModuleName, 3, m.Migrate3to4); err != nil { + panic(fmt.Sprintf("failed to migrate x/%s from version 3 to 4: %v", types.ModuleName, err)) + } } // InitGenesis performs genesis initialization for the slashing module. It returns @@ -196,7 +208,7 @@ func (am AppModule) RegisterStoreDecoder(sdr simtypes.StoreDecoderRegistry) { // WeightedOperations returns the all the slashing module operations with their respective weights. func (am AppModule) WeightedOperations(simState module.SimulationState) []simtypes.WeightedOperation { return simulation.WeightedOperations( - simState.AppParams, simState.Cdc, + am.registry, simState.AppParams, simState.Cdc, simState.TxConfig, am.accountKeeper, am.bankKeeper, am.keeper, am.stakingKeeper, ) } @@ -212,14 +224,14 @@ func init() { ) } -//nolint:revive -type SlashingInputs struct { +type ModuleInputs struct { depinject.In Config *modulev1.Module Key *store.KVStoreKey Cdc codec.Codec LegacyAmino *codec.LegacyAmino + Registry cdctypes.InterfaceRegistry AccountKeeper types.AccountKeeper BankKeeper types.BankKeeper @@ -229,8 +241,7 @@ type SlashingInputs struct { LegacySubspace exported.Subspace } -//nolint:revive -type SlashingOutputs struct { +type ModuleOutputs struct { depinject.Out Keeper keeper.Keeper @@ -238,7 +249,7 @@ type SlashingOutputs struct { Hooks staking.StakingHooksWrapper } -func ProvideModule(in SlashingInputs) SlashingOutputs { +func ProvideModule(in ModuleInputs) ModuleOutputs { // default to governance authority if not provided authority := authtypes.NewModuleAddress(govtypes.ModuleName) if in.Config.Authority != "" { @@ -246,8 +257,8 @@ func ProvideModule(in SlashingInputs) SlashingOutputs { } k := keeper.NewKeeper(in.Cdc, in.LegacyAmino, in.Key, in.StakingKeeper, authority.String()) - m := NewAppModule(in.Cdc, k, in.AccountKeeper, in.BankKeeper, in.StakingKeeper, in.LegacySubspace) - return SlashingOutputs{ + m := NewAppModule(in.Cdc, k, in.AccountKeeper, in.BankKeeper, in.StakingKeeper, in.LegacySubspace, in.Registry) + return ModuleOutputs{ Keeper: k, Module: m, Hooks: staking.StakingHooksWrapper{StakingHooks: k.Hooks()}, diff --git a/x/slashing/simulation/decoder.go b/x/slashing/simulation/decoder.go index d295a284ac18..1e96739d6680 100644 --- a/x/slashing/simulation/decoder.go +++ b/x/slashing/simulation/decoder.go @@ -23,7 +23,7 @@ func NewDecodeStore(cdc codec.BinaryCodec) func(kvA, kvB kv.Pair) string { cdc.MustUnmarshal(kvB.Value, &infoB) return fmt.Sprintf("%v\n%v", infoA, infoB) - case bytes.Equal(kvA.Key[:1], types.ValidatorMissedBlockBitArrayKeyPrefix): + case bytes.Equal(kvA.Key[:1], types.ValidatorMissedBlockBitmapKeyPrefix): var missedA, missedB gogotypes.BoolValue cdc.MustUnmarshal(kvA.Value, &missedA) cdc.MustUnmarshal(kvB.Value, &missedB) diff --git a/x/slashing/simulation/decoder_test.go b/x/slashing/simulation/decoder_test.go index 974defe4a258..85aa4fa460bc 100644 --- a/x/slashing/simulation/decoder_test.go +++ b/x/slashing/simulation/decoder_test.go @@ -17,7 +17,6 @@ import ( "github.com/cosmos/cosmos-sdk/x/slashing/types" ) -//nolint:deadcode,varcheck var ( delPk1 = ed25519.GenPrivKey().PubKey() delAddr1 = sdk.AccAddress(delPk1.Address()) @@ -37,7 +36,7 @@ func TestDecodeStore(t *testing.T) { kvPairs := kv.Pairs{ Pairs: []kv.Pair{ {Key: types.ValidatorSigningInfoKey(consAddr1), Value: cdc.MustMarshal(&info)}, - {Key: types.ValidatorMissedBlockBitArrayKey(consAddr1, 6), Value: cdc.MustMarshal(&missed)}, + {Key: types.ValidatorMissedBlockBitmapKey(consAddr1, 6), Value: cdc.MustMarshal(&missed)}, {Key: types.AddrPubkeyRelationKey(delAddr1), Value: bz}, {Key: []byte{0x99}, Value: []byte{0x99}}, // This test should panic }, diff --git a/x/slashing/simulation/operations.go b/x/slashing/simulation/operations.go index 41649e2793d1..cbdeb2b102eb 100644 --- a/x/slashing/simulation/operations.go +++ b/x/slashing/simulation/operations.go @@ -5,13 +5,13 @@ import ( "math/rand" "github.com/cosmos/cosmos-sdk/baseapp" + "github.com/cosmos/cosmos-sdk/client" "github.com/cosmos/cosmos-sdk/codec" codectypes "github.com/cosmos/cosmos-sdk/codec/types" "github.com/cosmos/cosmos-sdk/testutil" simtestutil "github.com/cosmos/cosmos-sdk/testutil/sims" sdk "github.com/cosmos/cosmos-sdk/types" simtypes "github.com/cosmos/cosmos-sdk/types/simulation" - "github.com/cosmos/cosmos-sdk/x/auth/tx" "github.com/cosmos/cosmos-sdk/x/simulation" "github.com/cosmos/cosmos-sdk/x/slashing/keeper" "github.com/cosmos/cosmos-sdk/x/slashing/types" @@ -19,18 +19,22 @@ import ( // Simulation operation weights constants const ( - OpWeightMsgUnjail = "op_weight_msg_unjail" //nolint:gosec + OpWeightMsgUnjail = "op_weight_msg_unjail" DefaultWeightMsgUnjail = 100 ) // WeightedOperations returns all the operations from the module with their respective weights func WeightedOperations( - appParams simtypes.AppParams, cdc codec.JSONCodec, ak types.AccountKeeper, - bk types.BankKeeper, k keeper.Keeper, sk types.StakingKeeper, + registry codectypes.InterfaceRegistry, + appParams simtypes.AppParams, + cdc codec.JSONCodec, + txGen client.TxConfig, + ak types.AccountKeeper, + bk types.BankKeeper, + k keeper.Keeper, + sk types.StakingKeeper, ) simulation.WeightedOperations { - interfaceRegistry := codectypes.NewInterfaceRegistry() - var weightMsgUnjail int appParams.GetOrGenerate(cdc, OpWeightMsgUnjail, &weightMsgUnjail, nil, func(_ *rand.Rand) { @@ -41,13 +45,20 @@ func WeightedOperations( return simulation.WeightedOperations{ simulation.NewWeightedOperation( weightMsgUnjail, - SimulateMsgUnjail(codec.NewProtoCodec(interfaceRegistry), ak, bk, k, sk), + SimulateMsgUnjail(codec.NewProtoCodec(registry), txGen, ak, bk, k, sk), ), } } // SimulateMsgUnjail generates a MsgUnjail with random values -func SimulateMsgUnjail(cdc *codec.ProtoCodec, ak types.AccountKeeper, bk types.BankKeeper, k keeper.Keeper, sk types.StakingKeeper) simtypes.Operation { +func SimulateMsgUnjail( + cdc *codec.ProtoCodec, + txGen client.TxConfig, + ak types.AccountKeeper, + bk types.BankKeeper, + k keeper.Keeper, + sk types.StakingKeeper, +) simtypes.Operation { return func( r *rand.Rand, app *baseapp.BaseApp, ctx sdk.Context, accs []simtypes.Account, chainID string, @@ -93,7 +104,6 @@ func SimulateMsgUnjail(cdc *codec.ProtoCodec, ak types.AccountKeeper, bk types.B msg := types.NewMsgUnjail(validator.GetOperator()) - txGen := tx.NewTxConfig(cdc, tx.DefaultSignModes) tx, err := simtestutil.GenSignedMockTx( r, txGen, diff --git a/x/slashing/simulation/operations_test.go b/x/slashing/simulation/operations_test.go index de71e3153e95..0990f5f9e891 100644 --- a/x/slashing/simulation/operations_test.go +++ b/x/slashing/simulation/operations_test.go @@ -13,6 +13,7 @@ import ( "cosmossdk.io/math" + "github.com/cosmos/cosmos-sdk/client" "github.com/cosmos/cosmos-sdk/codec" codectypes "github.com/cosmos/cosmos-sdk/codec/types" cryptocodec "github.com/cosmos/cosmos-sdk/crypto/codec" @@ -46,6 +47,7 @@ type SimTestSuite struct { legacyAmino *codec.LegacyAmino codec codec.Codec interfaceRegistry codectypes.InterfaceRegistry + txConfig client.TxConfig accountKeeper authkeeper.AccountKeeper bankKeeper bankkeeper.Keeper stakingKeeper *stakingkeeper.Keeper @@ -81,6 +83,7 @@ func (suite *SimTestSuite) SetupTest() { &suite.legacyAmino, &suite.codec, &suite.interfaceRegistry, + &suite.txConfig, &suite.accountKeeper, &suite.bankKeeper, &suite.stakingKeeper, @@ -127,8 +130,8 @@ func (suite *SimTestSuite) TestWeightedOperations() { {simulation.DefaultWeightMsgUnjail, types.ModuleName, sdk.MsgTypeURL(&types.MsgUnjail{})}, } - weightesOps := simulation.WeightedOperations(appParams, suite.codec, suite.accountKeeper, suite.bankKeeper, suite.slashingKeeper, suite.stakingKeeper) - for i, w := range weightesOps { + weightedOps := simulation.WeightedOperations(suite.interfaceRegistry, appParams, suite.codec, suite.txConfig, suite.accountKeeper, suite.bankKeeper, suite.slashingKeeper, suite.stakingKeeper) + for i, w := range weightedOps { operationMsg, _, err := w.Op()(suite.r, suite.app.BaseApp, ctx, suite.accounts, ctx.ChainID()) suite.Require().NoError(err) @@ -175,7 +178,7 @@ func (suite *SimTestSuite) TestSimulateMsgUnjail() { suite.app.BeginBlock(abci.RequestBeginBlock{Header: cmtproto.Header{Height: suite.app.LastBlockHeight() + 1, AppHash: suite.app.LastCommitID().Hash, Time: blockTime}}) // execute operation - op := simulation.SimulateMsgUnjail(codec.NewProtoCodec(suite.interfaceRegistry), suite.accountKeeper, suite.bankKeeper, suite.slashingKeeper, suite.stakingKeeper) + op := simulation.SimulateMsgUnjail(codec.NewProtoCodec(suite.interfaceRegistry), suite.txConfig, suite.accountKeeper, suite.bankKeeper, suite.slashingKeeper, suite.stakingKeeper) operationMsg, futureOperations, err := op(suite.r, suite.app.BaseApp, ctx, suite.accounts, "") suite.Require().NoError(err) diff --git a/x/slashing/simulation/proposals.go b/x/slashing/simulation/proposals.go index 6c17b9c44a0a..86b5d5a532d8 100644 --- a/x/slashing/simulation/proposals.go +++ b/x/slashing/simulation/proposals.go @@ -15,7 +15,7 @@ import ( const ( DefaultWeightMsgUpdateParams int = 100 - OpWeightMsgUpdateParams = "op_weight_msg_update_params" //nolint:gosec + OpWeightMsgUpdateParams = "op_weight_msg_update_params" ) // ProposalMsgs defines the module weighted proposals' contents diff --git a/x/slashing/testutil/expected_keepers_mocks.go b/x/slashing/testutil/expected_keepers_mocks.go index 1de66b89e99a..2cc775c7fbf7 100644 --- a/x/slashing/testutil/expected_keepers_mocks.go +++ b/x/slashing/testutil/expected_keepers_mocks.go @@ -5,6 +5,7 @@ package testutil import ( + context "context" reflect "reflect" math "cosmossdk.io/math" @@ -38,7 +39,7 @@ func (m *MockAccountKeeper) EXPECT() *MockAccountKeeperMockRecorder { } // GetAccount mocks base method. -func (m *MockAccountKeeper) GetAccount(ctx types.Context, addr types.AccAddress) types.AccountI { +func (m *MockAccountKeeper) GetAccount(ctx context.Context, addr types.AccAddress) types.AccountI { m.ctrl.T.Helper() ret := m.ctrl.Call(m, "GetAccount", ctx, addr) ret0, _ := ret[0].(types.AccountI) @@ -52,7 +53,7 @@ func (mr *MockAccountKeeperMockRecorder) GetAccount(ctx, addr interface{}) *gomo } // IterateAccounts mocks base method. -func (m *MockAccountKeeper) IterateAccounts(ctx types.Context, process func(types.AccountI) bool) { +func (m *MockAccountKeeper) IterateAccounts(ctx context.Context, process func(types.AccountI) bool) { m.ctrl.T.Helper() m.ctrl.Call(m, "IterateAccounts", ctx, process) } diff --git a/x/slashing/types/expected_keepers.go b/x/slashing/types/expected_keepers.go index 3306be791a27..ba7a34c58ac5 100644 --- a/x/slashing/types/expected_keepers.go +++ b/x/slashing/types/expected_keepers.go @@ -1,6 +1,8 @@ package types import ( + context "context" + "cosmossdk.io/math" sdk "github.com/cosmos/cosmos-sdk/types" @@ -10,8 +12,8 @@ import ( // AccountKeeper expected account keeper type AccountKeeper interface { - GetAccount(ctx sdk.Context, addr sdk.AccAddress) sdk.AccountI - IterateAccounts(ctx sdk.Context, process func(sdk.AccountI) (stop bool)) + GetAccount(ctx context.Context, addr sdk.AccAddress) sdk.AccountI + IterateAccounts(ctx context.Context, process func(sdk.AccountI) (stop bool)) } // BankKeeper defines the expected interface needed to retrieve account balances. @@ -40,7 +42,7 @@ type StakingKeeper interface { Validator(sdk.Context, sdk.ValAddress) stakingtypes.ValidatorI // get a particular validator by operator address ValidatorByConsAddr(sdk.Context, sdk.ConsAddress) stakingtypes.ValidatorI // get a particular validator by consensus address - // slash the validator and delegators of the validator, specifying offence height, offence power, and slash fraction + // slash the validator and delegators of the validator, specifying offense height, offense power, and slash fraction Slash(sdk.Context, sdk.ConsAddress, int64, int64, sdk.Dec) math.Int SlashWithInfractionReason(sdk.Context, sdk.ConsAddress, int64, int64, sdk.Dec, stakingtypes.Infraction) math.Int Jail(sdk.Context, sdk.ConsAddress) // jail a validator diff --git a/x/slashing/types/keys.go b/x/slashing/types/keys.go index 02a86e167e28..856780f86c48 100644 --- a/x/slashing/types/keys.go +++ b/x/slashing/types/keys.go @@ -17,6 +17,25 @@ const ( // RouterKey is the message route for slashing RouterKey = ModuleName + + // MissedBlockBitmapChunkSize defines the chunk size, in number of bits, of a + // validator missed block bitmap. Chunks are used to reduce the storage and + // write overhead of IAVL nodes. The total size of the bitmap is roughly in + // the range [0, SignedBlocksWindow) where each bit represents a block. A + // validator's IndexOffset modulo the SignedBlocksWindow is used to retrieve + // the chunk in that bitmap range. Once the chunk is retrieved, the same index + // is used to check or flip a bit, where if a bit is set, it indicates the + // validator missed that block. + // + // For a bitmap of N items, i.e. a validator's signed block window, the amount + // of write complexity per write with a factor of f being the overhead of + // IAVL being un-optimized, i.e. 2-4, is as follows: + // + // ChunkSize + (f * 256 ) + 256 * log_2(N / ChunkSize) + // + // As for the storage overhead, with the same factor f, it is as follows: + // (N - 256) + (N / ChunkSize) * (512 * f) + MissedBlockBitmapChunkSize = 1024 // 2^10 bits ) // Keys for slashing store @@ -24,15 +43,15 @@ const ( // // - 0x01: ValidatorSigningInfo // -// - 0x02: bool +// - 0x02: bitmap_chunk // // - 0x03: cryptotypes.PubKey var ( - ParamsKey = []byte{0x00} // Prefix for params key - ValidatorSigningInfoKeyPrefix = []byte{0x01} // Prefix for signing info - ValidatorMissedBlockBitArrayKeyPrefix = []byte{0x02} // Prefix for missed block bit array - AddrPubkeyRelationKeyPrefix = []byte{0x03} // Prefix for address-pubkey relation + ParamsKey = []byte{0x00} // Prefix for params key + ValidatorSigningInfoKeyPrefix = []byte{0x01} // Prefix for signing info + ValidatorMissedBlockBitmapKeyPrefix = []byte{0x02} // Prefix for missed block bitmap + AddrPubkeyRelationKeyPrefix = []byte{0x03} // Prefix for address-pubkey relation ) // ValidatorSigningInfoKey - stored by *Consensus* address (not operator address) @@ -49,17 +68,19 @@ func ValidatorSigningInfoAddress(key []byte) (v sdk.ConsAddress) { return sdk.ConsAddress(addr) } -// ValidatorMissedBlockBitArrayPrefixKey - stored by *Consensus* address (not operator address) -func ValidatorMissedBlockBitArrayPrefixKey(v sdk.ConsAddress) []byte { - return append(ValidatorMissedBlockBitArrayKeyPrefix, address.MustLengthPrefix(v.Bytes())...) +// ValidatorMissedBlockBitmapPrefixKey returns the key prefix for a validator's +// missed block bitmap. +func ValidatorMissedBlockBitmapPrefixKey(v sdk.ConsAddress) []byte { + return append(ValidatorMissedBlockBitmapKeyPrefix, address.MustLengthPrefix(v.Bytes())...) } -// ValidatorMissedBlockBitArrayKey - stored by *Consensus* address (not operator address) -func ValidatorMissedBlockBitArrayKey(v sdk.ConsAddress, i int64) []byte { - b := make([]byte, 8) - binary.LittleEndian.PutUint64(b, uint64(i)) +// ValidatorMissedBlockBitmapKey returns the key for a validator's missed block +// bitmap chunk. +func ValidatorMissedBlockBitmapKey(v sdk.ConsAddress, chunkIndex int64) []byte { + bz := make([]byte, 8) + binary.LittleEndian.PutUint64(bz, uint64(chunkIndex)) - return append(ValidatorMissedBlockBitArrayPrefixKey(v), b...) + return append(ValidatorMissedBlockBitmapPrefixKey(v), bz...) } // AddrPubkeyRelationKey gets pubkey relation key used to get the pubkey from the address diff --git a/x/slashing/types/msg.go b/x/slashing/types/msg.go index 416e9b3077f9..a4aa2925a9e1 100644 --- a/x/slashing/types/msg.go +++ b/x/slashing/types/msg.go @@ -1,10 +1,7 @@ package types import ( - errorsmod "cosmossdk.io/errors" - sdk "github.com/cosmos/cosmos-sdk/types" - sdkerrors "github.com/cosmos/cosmos-sdk/types/errors" "github.com/cosmos/cosmos-sdk/x/auth/migrations/legacytx" ) @@ -18,8 +15,6 @@ var ( ) // NewMsgUnjail creates a new MsgUnjail instance -// -//nolint:interfacer func NewMsgUnjail(validatorAddr sdk.ValAddress) *MsgUnjail { return &MsgUnjail{ ValidatorAddr: validatorAddr.String(), @@ -38,14 +33,6 @@ func (msg MsgUnjail) GetSignBytes() []byte { return sdk.MustSortJSON(bz) } -// ValidateBasic does a sanity check on the provided message. -func (msg MsgUnjail) ValidateBasic() error { - if _, err := sdk.ValAddressFromBech32(msg.ValidatorAddr); err != nil { - return sdkerrors.ErrInvalidAddress.Wrapf("validator input address: %s", err) - } - return nil -} - // GetSignBytes implements the LegacyMsg interface. func (msg MsgUpdateParams) GetSignBytes() []byte { return sdk.MustSortJSON(ModuleCdc.MustMarshalJSON(&msg)) @@ -56,16 +43,3 @@ func (msg MsgUpdateParams) GetSigners() []sdk.AccAddress { addr, _ := sdk.AccAddressFromBech32(msg.Authority) return []sdk.AccAddress{addr} } - -// ValidateBasic does a sanity check on the provided data. -func (msg MsgUpdateParams) ValidateBasic() error { - if _, err := sdk.AccAddressFromBech32(msg.Authority); err != nil { - return errorsmod.Wrap(err, "invalid authority address") - } - - if err := msg.Params.Validate(); err != nil { - return err - } - - return nil -} diff --git a/x/slashing/types/signing_info.go b/x/slashing/types/signing_info.go index 27ed54e0b819..8e9519d51dec 100644 --- a/x/slashing/types/signing_info.go +++ b/x/slashing/types/signing_info.go @@ -8,8 +8,6 @@ import ( ) // NewValidatorSigningInfo creates a new ValidatorSigningInfo instance -// -//nolint:interfacer func NewValidatorSigningInfo( consAddr sdk.ConsAddress, startHeight, indexOffset int64, jailedUntil time.Time, tombstoned bool, missedBlocksCounter int64, diff --git a/x/slashing/types/slashing.pb.go b/x/slashing/types/slashing.pb.go index ce901400b720..2673f6a77f58 100644 --- a/x/slashing/types/slashing.pb.go +++ b/x/slashing/types/slashing.pb.go @@ -35,19 +35,20 @@ const _ = proto.GoGoProtoPackageIsVersion3 // please upgrade the proto package // liveness activity. type ValidatorSigningInfo struct { Address string `protobuf:"bytes,1,opt,name=address,proto3" json:"address,omitempty"` - // Height at which validator was first a candidate OR was unjailed + // Height at which validator was first a candidate OR was un-jailed StartHeight int64 `protobuf:"varint,2,opt,name=start_height,json=startHeight,proto3" json:"start_height,omitempty"` - // Index which is incremented each time the validator was a bonded - // in a block and may have signed a precommit or not. This in conjunction with the - // `SignedBlocksWindow` param determines the index in the `MissedBlocksBitArray`. + // Index which is incremented every time a validator is bonded in a block and + // _may_ have signed a pre-commit or not. This in conjunction with the + // signed_blocks_window param determines the index in the missed block bitmap. IndexOffset int64 `protobuf:"varint,3,opt,name=index_offset,json=indexOffset,proto3" json:"index_offset,omitempty"` // Timestamp until which the validator is jailed due to liveness downtime. JailedUntil time.Time `protobuf:"bytes,4,opt,name=jailed_until,json=jailedUntil,proto3,stdtime" json:"jailed_until"` - // Whether or not a validator has been tombstoned (killed out of validator set). It is set - // once the validator commits an equivocation or for any other configured misbehiavor. + // Whether or not a validator has been tombstoned (killed out of validator + // set). It is set once the validator commits an equivocation or for any other + // configured misbehavior. Tombstoned bool `protobuf:"varint,5,opt,name=tombstoned,proto3" json:"tombstoned,omitempty"` - // A counter kept to avoid unnecessary array reads. - // Note that `Sum(MissedBlocksBitArray)` always equals `MissedBlocksCounter`. + // A counter of missed (unsigned) blocks. It is used to avoid unnecessary + // reads in the missed block bitmap. MissedBlocksCounter int64 `protobuf:"varint,6,opt,name=missed_blocks_counter,json=missedBlocksCounter,proto3" json:"missed_blocks_counter,omitempty"` } diff --git a/x/staking/app_test.go b/x/staking/app_test.go index b0f3d0cb1dbf..4a81bac5eb83 100644 --- a/x/staking/app_test.go +++ b/x/staking/app_test.go @@ -68,7 +68,7 @@ func TestStakingMsgs(t *testing.T) { require.NoError(t, err) header := cmtproto.Header{Height: app.LastBlockHeight() + 1} - txConfig := moduletestutil.MakeTestEncodingConfig().TxConfig + txConfig := moduletestutil.MakeTestTxConfig() _, _, err = simtestutil.SignCheckDeliver(t, txConfig, app.BaseApp, header, []sdk.Msg{createValidatorMsg}, "", []uint64{0}, []uint64{0}, true, true, priv1) require.NoError(t, err) require.True(t, sdk.Coins{genCoin.Sub(bondCoin)}.Equal(bankKeeper.GetAllBalances(ctxCheck, addr1))) diff --git a/x/staking/client/cli/query.go b/x/staking/client/cli/query.go index 0982296161e4..d896b54ef7a0 100644 --- a/x/staking/client/cli/query.go +++ b/x/staking/client/cli/query.go @@ -5,6 +5,7 @@ import ( "strconv" "strings" + "cosmossdk.io/core/address" "github.com/spf13/cobra" "github.com/cosmos/cosmos-sdk/client" @@ -15,7 +16,7 @@ import ( ) // GetQueryCmd returns the cli query commands for this module -func GetQueryCmd() *cobra.Command { +func GetQueryCmd(ac address.Codec) *cobra.Command { stakingQueryCmd := &cobra.Command{ Use: types.ModuleName, Short: "Querying commands for the staking module", @@ -25,12 +26,12 @@ func GetQueryCmd() *cobra.Command { } stakingQueryCmd.AddCommand( - GetCmdQueryDelegation(), - GetCmdQueryDelegations(), - GetCmdQueryUnbondingDelegation(), - GetCmdQueryUnbondingDelegations(), - GetCmdQueryRedelegation(), - GetCmdQueryRedelegations(), + GetCmdQueryDelegation(ac), + GetCmdQueryDelegations(ac), + GetCmdQueryUnbondingDelegation(ac), + GetCmdQueryUnbondingDelegations(ac), + GetCmdQueryRedelegation(ac), + GetCmdQueryRedelegations(ac), GetCmdQueryValidator(), GetCmdQueryValidators(), GetCmdQueryValidatorDelegations(), @@ -242,22 +243,13 @@ $ %s query staking redelegations-from %s1gghjut3ccd8ay0zduzj64hwre2fxs9ldmqhffj } // GetCmdQueryDelegation the query delegation command. -func GetCmdQueryDelegation() *cobra.Command { - bech32PrefixAccAddr := sdk.GetConfig().GetBech32AccountAddrPrefix() - bech32PrefixValAddr := sdk.GetConfig().GetBech32ValidatorAddrPrefix() - +func GetCmdQueryDelegation(ac address.Codec) *cobra.Command { cmd := &cobra.Command{ Use: "delegation [delegator-addr] [validator-addr]", Short: "Query a delegation based on address and validator address", - Long: strings.TrimSpace( - fmt.Sprintf(`Query delegations for an individual delegator on an individual validator. - -Example: -$ %s query staking delegation %s1gghjut3ccd8ay0zduzj64hwre2fxs9ld75ru9p %s1gghjut3ccd8ay0zduzj64hwre2fxs9ldmqhffj -`, - version.AppName, bech32PrefixAccAddr, bech32PrefixValAddr, - ), - ), + Example: fmt.Sprintf(`%s query staking delegation [delegator-address] [validator-address]`, + version.AppName), + Long: "Query delegations for an individual delegator on an individual validator", Args: cobra.ExactArgs(2), RunE: func(cmd *cobra.Command, args []string) error { clientCtx, err := client.GetClientQueryContext(cmd) @@ -266,7 +258,7 @@ $ %s query staking delegation %s1gghjut3ccd8ay0zduzj64hwre2fxs9ld75ru9p %s1gghju } queryClient := types.NewQueryClient(clientCtx) - delAddr, err := sdk.AccAddressFromBech32(args[0]) + _, err = ac.StringToBytes(args[0]) if err != nil { return err } @@ -277,7 +269,7 @@ $ %s query staking delegation %s1gghjut3ccd8ay0zduzj64hwre2fxs9ld75ru9p %s1gghju } params := &types.QueryDelegationRequest{ - DelegatorAddr: delAddr.String(), + DelegatorAddr: args[0], ValidatorAddr: valAddr.String(), } @@ -297,7 +289,7 @@ $ %s query staking delegation %s1gghjut3ccd8ay0zduzj64hwre2fxs9ld75ru9p %s1gghju // GetCmdQueryDelegations implements the command to query all the delegations // made from one delegator. -func GetCmdQueryDelegations() *cobra.Command { +func GetCmdQueryDelegations(ac address.Codec) *cobra.Command { bech32PrefixAccAddr := sdk.GetConfig().GetBech32AccountAddrPrefix() cmd := &cobra.Command{ @@ -320,7 +312,7 @@ $ %s query staking delegations %s1gghjut3ccd8ay0zduzj64hwre2fxs9ld75ru9p } queryClient := types.NewQueryClient(clientCtx) - delAddr, err := sdk.AccAddressFromBech32(args[0]) + _, err = ac.StringToBytes(args[0]) if err != nil { return err } @@ -331,7 +323,7 @@ $ %s query staking delegations %s1gghjut3ccd8ay0zduzj64hwre2fxs9ld75ru9p } params := &types.QueryDelegatorDelegationsRequest{ - DelegatorAddr: delAddr.String(), + DelegatorAddr: args[0], Pagination: pageReq, } @@ -407,7 +399,7 @@ $ %s query staking delegations-to %s1gghjut3ccd8ay0zduzj64hwre2fxs9ldmqhffj // GetCmdQueryUnbondingDelegation implements the command to query a single // unbonding-delegation record. -func GetCmdQueryUnbondingDelegation() *cobra.Command { +func GetCmdQueryUnbondingDelegation(ac address.Codec) *cobra.Command { bech32PrefixAccAddr := sdk.GetConfig().GetBech32AccountAddrPrefix() bech32PrefixValAddr := sdk.GetConfig().GetBech32ValidatorAddrPrefix() @@ -436,13 +428,13 @@ $ %s query staking unbonding-delegation %s1gghjut3ccd8ay0zduzj64hwre2fxs9ld75ru9 return err } - delAddr, err := sdk.AccAddressFromBech32(args[0]) + _, err = ac.StringToBytes(args[0]) if err != nil { return err } params := &types.QueryUnbondingDelegationRequest{ - DelegatorAddr: delAddr.String(), + DelegatorAddr: args[0], ValidatorAddr: valAddr.String(), } @@ -462,7 +454,7 @@ $ %s query staking unbonding-delegation %s1gghjut3ccd8ay0zduzj64hwre2fxs9ld75ru9 // GetCmdQueryUnbondingDelegations implements the command to query all the // unbonding-delegation records for a delegator. -func GetCmdQueryUnbondingDelegations() *cobra.Command { +func GetCmdQueryUnbondingDelegations(ac address.Codec) *cobra.Command { bech32PrefixAccAddr := sdk.GetConfig().GetBech32AccountAddrPrefix() cmd := &cobra.Command{ @@ -485,7 +477,7 @@ $ %s query staking unbonding-delegations %s1gghjut3ccd8ay0zduzj64hwre2fxs9ld75ru } queryClient := types.NewQueryClient(clientCtx) - delegatorAddr, err := sdk.AccAddressFromBech32(args[0]) + _, err = ac.StringToBytes(args[0]) if err != nil { return err } @@ -496,7 +488,7 @@ $ %s query staking unbonding-delegations %s1gghjut3ccd8ay0zduzj64hwre2fxs9ld75ru } params := &types.QueryDelegatorUnbondingDelegationsRequest{ - DelegatorAddr: delegatorAddr.String(), + DelegatorAddr: args[0], Pagination: pageReq, } @@ -517,7 +509,7 @@ $ %s query staking unbonding-delegations %s1gghjut3ccd8ay0zduzj64hwre2fxs9ld75ru // GetCmdQueryRedelegation implements the command to query a single // redelegation record. -func GetCmdQueryRedelegation() *cobra.Command { +func GetCmdQueryRedelegation(ac address.Codec) *cobra.Command { bech32PrefixAccAddr := sdk.GetConfig().GetBech32AccountAddrPrefix() bech32PrefixValAddr := sdk.GetConfig().GetBech32ValidatorAddrPrefix() @@ -541,7 +533,7 @@ $ %s query staking redelegation %s1gghjut3ccd8ay0zduzj64hwre2fxs9ld75ru9p %s1l2r } queryClient := types.NewQueryClient(clientCtx) - delAddr, err := sdk.AccAddressFromBech32(args[0]) + _, err = ac.StringToBytes(args[0]) if err != nil { return err } @@ -557,7 +549,7 @@ $ %s query staking redelegation %s1gghjut3ccd8ay0zduzj64hwre2fxs9ld75ru9p %s1l2r } params := &types.QueryRedelegationsRequest{ - DelegatorAddr: delAddr.String(), + DelegatorAddr: args[0], DstValidatorAddr: valDstAddr.String(), SrcValidatorAddr: valSrcAddr.String(), } @@ -578,7 +570,7 @@ $ %s query staking redelegation %s1gghjut3ccd8ay0zduzj64hwre2fxs9ld75ru9p %s1l2r // GetCmdQueryRedelegations implements the command to query all the // redelegation records for a delegator. -func GetCmdQueryRedelegations() *cobra.Command { +func GetCmdQueryRedelegations(ac address.Codec) *cobra.Command { bech32PrefixAccAddr := sdk.GetConfig().GetBech32AccountAddrPrefix() cmd := &cobra.Command{ @@ -601,7 +593,7 @@ $ %s query staking redelegation %s1gghjut3ccd8ay0zduzj64hwre2fxs9ld75ru9p } queryClient := types.NewQueryClient(clientCtx) - delAddr, err := sdk.AccAddressFromBech32(args[0]) + _, err = ac.StringToBytes(args[0]) if err != nil { return err } @@ -612,7 +604,7 @@ $ %s query staking redelegation %s1gghjut3ccd8ay0zduzj64hwre2fxs9ld75ru9p } params := &types.QueryRedelegationsRequest{ - DelegatorAddr: delAddr.String(), + DelegatorAddr: args[0], Pagination: pageReq, } diff --git a/x/staking/client/cli/query_test.go b/x/staking/client/cli/query_test.go index fca40e92d9d5..febffe77da3a 100644 --- a/x/staking/client/cli/query_test.go +++ b/x/staking/client/cli/query_test.go @@ -7,6 +7,7 @@ import ( "github.com/cosmos/gogoproto/proto" "github.com/cosmos/cosmos-sdk/client/flags" + "github.com/cosmos/cosmos-sdk/codec/address" clitestutil "github.com/cosmos/cosmos-sdk/testutil/cli" sdk "github.com/cosmos/cosmos-sdk/types" "github.com/cosmos/cosmos-sdk/x/staking/client/cli" @@ -124,7 +125,7 @@ func (s *CLITestSuite) TestGetCmdQueryDelegation() { for _, tc := range testCases { tc := tc s.Run(tc.name, func() { - cmd := cli.GetCmdQueryDelegation() + cmd := cli.GetCmdQueryDelegation(address.NewBech32Codec("cosmos")) clientCtx := s.clientCtx _, err := clitestutil.ExecTestCLICmd(clientCtx, cmd, tc.args) @@ -169,7 +170,7 @@ func (s *CLITestSuite) TestGetCmdQueryDelegations() { for _, tc := range testCases { tc := tc s.Run(tc.name, func() { - cmd := cli.GetCmdQueryDelegations() + cmd := cli.GetCmdQueryDelegations(address.NewBech32Codec("cosmos")) clientCtx := s.clientCtx out, err := clitestutil.ExecTestCLICmd(clientCtx, cmd, tc.args) @@ -215,7 +216,7 @@ func (s *CLITestSuite) TestGetCmdQueryValidatorDelegations() { for _, tc := range testCases { tc := tc s.Run(tc.name, func() { - cmd := cli.GetCmdQueryDelegations() + cmd := cli.GetCmdQueryDelegations(address.NewBech32Codec("cosmos")) clientCtx := s.clientCtx out, err := clitestutil.ExecTestCLICmd(clientCtx, cmd, tc.args) @@ -256,7 +257,7 @@ func (s *CLITestSuite) TestGetCmdQueryUnbondingDelegations() { for _, tc := range testCases { tc := tc s.Run(tc.name, func() { - cmd := cli.GetCmdQueryUnbondingDelegations() + cmd := cli.GetCmdQueryUnbondingDelegations(address.NewBech32Codec("cosmos")) clientCtx := s.clientCtx out, err := clitestutil.ExecTestCLICmd(clientCtx, cmd, tc.args) @@ -311,7 +312,7 @@ func (s *CLITestSuite) TestGetCmdQueryUnbondingDelegation() { for _, tc := range testCases { tc := tc s.Run(tc.name, func() { - cmd := cli.GetCmdQueryUnbondingDelegation() + cmd := cli.GetCmdQueryUnbondingDelegation(address.NewBech32Codec("cosmos")) clientCtx := s.clientCtx out, err := clitestutil.ExecTestCLICmd(clientCtx, cmd, tc.args) @@ -398,7 +399,7 @@ func (s *CLITestSuite) TestGetCmdQueryRedelegations() { for _, tc := range testCases { tc := tc s.Run(tc.name, func() { - cmd := cli.GetCmdQueryRedelegations() + cmd := cli.GetCmdQueryRedelegations(address.NewBech32Codec("cosmos")) clientCtx := s.clientCtx out, err := clitestutil.ExecTestCLICmd(clientCtx, cmd, tc.args) @@ -465,7 +466,7 @@ func (s *CLITestSuite) TestGetCmdQueryRedelegation() { for _, tc := range testCases { tc := tc s.Run(tc.name, func() { - cmd := cli.GetCmdQueryRedelegation() + cmd := cli.GetCmdQueryRedelegation(address.NewBech32Codec("cosmos")) clientCtx := s.clientCtx out, err := clitestutil.ExecTestCLICmd(clientCtx, cmd, tc.args) diff --git a/x/staking/client/cli/tx.go b/x/staking/client/cli/tx.go index 9453c10aef1a..35599b0b6089 100644 --- a/x/staking/client/cli/tx.go +++ b/x/staking/client/cli/tx.go @@ -289,6 +289,7 @@ $ %s tx staking unbond %s1gghjut3ccd8ay0zduzj64hwre2fxs9ldmqhffj 100stake --from if err != nil { return err } + delAddr := clientCtx.GetFromAddress() valAddr, err := sdk.ValAddressFromBech32(args[0]) if err != nil { @@ -379,7 +380,7 @@ func newBuildCreateValidatorMsg(clientCtx client.Context, txf tx.Factory, fs *fl if err != nil { return txf, nil, err } - if err := msg.ValidateBasic(); err != nil { + if err := msg.Validate(); err != nil { return txf, nil, err } diff --git a/x/staking/client/cli/tx_test.go b/x/staking/client/cli/tx_test.go index c595e00d512d..2ad8db094a21 100644 --- a/x/staking/client/cli/tx_test.go +++ b/x/staking/client/cli/tx_test.go @@ -1,14 +1,12 @@ package cli_test import ( - "bytes" "fmt" "io" "testing" abci "github.com/cometbft/cometbft/abci/types" rpcclientmock "github.com/cometbft/cometbft/rpc/client/mock" - "github.com/cosmos/gogoproto/proto" "github.com/spf13/pflag" "github.com/stretchr/testify/require" "github.com/stretchr/testify/suite" @@ -51,7 +49,6 @@ func (s *CLITestSuite) SetupSuite() { WithOutput(io.Discard). WithChainID("test-chain") - var outBuf bytes.Buffer ctxGen := func() client.Context { bz, _ := s.encCfg.Codec.Marshal(&sdk.TxResponse{}) c := clitestutil.NewMockCometRPC(abci.ResponseQuery{ @@ -59,7 +56,7 @@ func (s *CLITestSuite) SetupSuite() { }) return s.baseCtx.WithClient(c) } - s.clientCtx = ctxGen().WithOutput(&outBuf) + s.clientCtx = ctxGen() s.addrs = make([]sdk.AccAddress, 0) for i := 0; i < 3; i++ { @@ -231,11 +228,9 @@ func (s *CLITestSuite) TestNewCreateValidatorCmd() { defer noMonikerJSONFile.Close() testCases := []struct { - name string - args []string - expectErr bool - expErrMsg string - respType proto.Message + name string + args []string + expectErrMsg string }{ { "invalid transaction (missing amount)", @@ -246,9 +241,7 @@ func (s *CLITestSuite) TestNewCreateValidatorCmd() { fmt.Sprintf("--%s=%s", flags.FlagBroadcastMode, flags.BroadcastSync), fmt.Sprintf("--%s=%s", flags.FlagFees, sdk.NewCoins(sdk.NewCoin(sdk.DefaultBondDenom, sdk.NewInt(10))).String()), }, - true, "must specify amount of coins to bond", - nil, }, { "invalid transaction (missing pubkey)", @@ -259,9 +252,7 @@ func (s *CLITestSuite) TestNewCreateValidatorCmd() { fmt.Sprintf("--%s=%s", flags.FlagBroadcastMode, flags.BroadcastSync), fmt.Sprintf("--%s=%s", flags.FlagFees, sdk.NewCoins(sdk.NewCoin(sdk.DefaultBondDenom, sdk.NewInt(10))).String()), }, - true, "must specify the JSON encoded pubkey", - nil, }, { "invalid transaction (missing moniker)", @@ -272,9 +263,7 @@ func (s *CLITestSuite) TestNewCreateValidatorCmd() { fmt.Sprintf("--%s=%s", flags.FlagBroadcastMode, flags.BroadcastSync), fmt.Sprintf("--%s=%s", flags.FlagFees, sdk.NewCoins(sdk.NewCoin(sdk.DefaultBondDenom, sdk.NewInt(10))).String()), }, - true, "must specify the moniker name", - nil, }, { "valid transaction with all fields", @@ -285,7 +274,7 @@ func (s *CLITestSuite) TestNewCreateValidatorCmd() { fmt.Sprintf("--%s=%s", flags.FlagBroadcastMode, flags.BroadcastSync), fmt.Sprintf("--%s=%s", flags.FlagFees, sdk.NewCoins(sdk.NewCoin(sdk.DefaultBondDenom, sdk.NewInt(10))).String()), }, - false, "", &sdk.TxResponse{}, + "", }, { "valid transaction without optional fields", @@ -296,19 +285,20 @@ func (s *CLITestSuite) TestNewCreateValidatorCmd() { fmt.Sprintf("--%s=%s", flags.FlagBroadcastMode, flags.BroadcastSync), fmt.Sprintf("--%s=%s", flags.FlagFees, sdk.NewCoins(sdk.NewCoin(sdk.DefaultBondDenom, sdk.NewInt(10))).String()), }, - false, "", &sdk.TxResponse{}, + "", }, } for _, tc := range testCases { tc := tc s.Run(tc.name, func() { out, err := clitestutil.ExecTestCLICmd(s.clientCtx, cmd, tc.args) - if tc.expectErr { + if tc.expectErrMsg != "" { require.Error(err) - require.Contains(err.Error(), tc.expErrMsg) + require.Contains(err.Error(), tc.expectErrMsg) } else { require.NoError(err, "test: %s\noutput: %s", tc.name, out.String()) - err = s.clientCtx.Codec.UnmarshalJSON(out.Bytes(), tc.respType) + resp := &sdk.TxResponse{} + err = s.clientCtx.Codec.UnmarshalJSON(out.Bytes(), resp) require.NoError(err, out.String(), "test: %s, output\n:", tc.name, out.String()) } }) @@ -326,32 +316,30 @@ func (s *CLITestSuite) TestNewEditValidatorCmd() { testCases := []struct { name string args []string - expectErr bool - expectedCode uint32 - respType proto.Message + expectErrMsg string }{ { - "with no edit flag (since all are optional)", + "wrong from address", []string{ fmt.Sprintf("--%s=%s", flags.FlagFrom, "with wrong from address"), fmt.Sprintf("--%s=true", flags.FlagSkipConfirmation), fmt.Sprintf("--%s=%s", flags.FlagBroadcastMode, flags.BroadcastSync), fmt.Sprintf("--%s=%s", flags.FlagFees, sdk.NewCoins(sdk.NewCoin(sdk.DefaultBondDenom, sdk.NewInt(10))).String()), }, - true, 0, nil, + "key not found", }, { - "with no edit flag (since all are optional)", + "valid with no edit flag (since all are optional)", []string{ fmt.Sprintf("--%s=%s", flags.FlagFrom, s.addrs[0]), fmt.Sprintf("--%s=true", flags.FlagSkipConfirmation), fmt.Sprintf("--%s=%s", flags.FlagBroadcastMode, flags.BroadcastSync), fmt.Sprintf("--%s=%s", flags.FlagFees, sdk.NewCoins(sdk.NewCoin(sdk.DefaultBondDenom, sdk.NewInt(10))).String()), }, - false, 0, &sdk.TxResponse{}, + "", }, { - "edit validator details", + "valid with edit validator details", []string{ fmt.Sprintf("--details=%s", details), fmt.Sprintf("--%s=%s", flags.FlagFrom, s.addrs[0]), @@ -359,7 +347,7 @@ func (s *CLITestSuite) TestNewEditValidatorCmd() { fmt.Sprintf("--%s=%s", flags.FlagBroadcastMode, flags.BroadcastSync), fmt.Sprintf("--%s=%s", flags.FlagFees, sdk.NewCoins(sdk.NewCoin(sdk.DefaultBondDenom, sdk.NewInt(10))).String()), }, - false, 0, &sdk.TxResponse{}, + "", }, { "edit validator identity", @@ -370,7 +358,7 @@ func (s *CLITestSuite) TestNewEditValidatorCmd() { fmt.Sprintf("--%s=%s", flags.FlagBroadcastMode, flags.BroadcastSync), fmt.Sprintf("--%s=%s", flags.FlagFees, sdk.NewCoins(sdk.NewCoin(sdk.DefaultBondDenom, sdk.NewInt(10))).String()), }, - false, 0, &sdk.TxResponse{}, + "", }, { "edit validator security-contact", @@ -381,7 +369,7 @@ func (s *CLITestSuite) TestNewEditValidatorCmd() { fmt.Sprintf("--%s=%s", flags.FlagBroadcastMode, flags.BroadcastSync), fmt.Sprintf("--%s=%s", flags.FlagFees, sdk.NewCoins(sdk.NewCoin(sdk.DefaultBondDenom, sdk.NewInt(10))).String()), }, - false, 0, &sdk.TxResponse{}, + "", }, { "edit validator website", @@ -392,7 +380,7 @@ func (s *CLITestSuite) TestNewEditValidatorCmd() { fmt.Sprintf("--%s=%s", flags.FlagBroadcastMode, flags.BroadcastSync), fmt.Sprintf("--%s=%s", flags.FlagFees, sdk.NewCoins(sdk.NewCoin(sdk.DefaultBondDenom, sdk.NewInt(10))).String()), }, - false, 0, &sdk.TxResponse{}, + "", }, { "with all edit flags", @@ -406,7 +394,7 @@ func (s *CLITestSuite) TestNewEditValidatorCmd() { fmt.Sprintf("--%s=%s", flags.FlagBroadcastMode, flags.BroadcastSync), fmt.Sprintf("--%s=%s", flags.FlagFees, sdk.NewCoins(sdk.NewCoin(sdk.DefaultBondDenom, sdk.NewInt(10))).String()), }, - false, 0, &sdk.TxResponse{}, + "", }, } @@ -415,14 +403,13 @@ func (s *CLITestSuite) TestNewEditValidatorCmd() { s.Run(tc.name, func() { out, err := clitestutil.ExecTestCLICmd(s.clientCtx, cmd, tc.args) - if tc.expectErr { + if tc.expectErrMsg != "" { s.Require().Error(err) + s.Require().Contains(err.Error(), tc.expectErrMsg) } else { s.Require().NoError(err, out.String()) - s.Require().NoError(s.clientCtx.Codec.UnmarshalJSON(out.Bytes(), tc.respType), out.String()) - - txResp := tc.respType.(*sdk.TxResponse) - s.Require().Equal(tc.expectedCode, txResp.Code, out.String()) + resp := &sdk.TxResponse{} + s.Require().NoError(s.clientCtx.Codec.UnmarshalJSON(out.Bytes(), resp)) } }) } @@ -434,31 +421,31 @@ func (s *CLITestSuite) TestNewDelegateCmd() { testCases := []struct { name string args []string - expectErr bool - expectedCode uint32 - respType proto.Message + expectErrMsg string }{ { - "without delegate amount", + "invalid delegate amount", []string{ sdk.ValAddress(s.addrs[0]).String(), + "fooCoin", fmt.Sprintf("--%s=%s", flags.FlagFrom, s.addrs[0]), fmt.Sprintf("--%s=true", flags.FlagSkipConfirmation), fmt.Sprintf("--%s=%s", flags.FlagBroadcastMode, flags.BroadcastSync), fmt.Sprintf("--%s=%s", flags.FlagFees, sdk.NewCoins(sdk.NewCoin(sdk.DefaultBondDenom, sdk.NewInt(10))).String()), }, - true, 0, nil, + "invalid decimal coin expression: fooCoin", }, { - "without validator address", + "invalid validator address", []string{ + "abc", sdk.NewCoin(sdk.DefaultBondDenom, sdk.NewInt(150)).String(), fmt.Sprintf("--%s=%s", flags.FlagFrom, s.addrs[0]), fmt.Sprintf("--%s=true", flags.FlagSkipConfirmation), fmt.Sprintf("--%s=%s", flags.FlagBroadcastMode, flags.BroadcastSync), fmt.Sprintf("--%s=%s", flags.FlagFees, sdk.NewCoins(sdk.NewCoin(sdk.DefaultBondDenom, sdk.NewInt(10))).String()), }, - true, 0, nil, + "decoding bech32 failed", }, { "valid transaction of delegate", @@ -470,7 +457,7 @@ func (s *CLITestSuite) TestNewDelegateCmd() { fmt.Sprintf("--%s=%s", flags.FlagBroadcastMode, flags.BroadcastSync), fmt.Sprintf("--%s=%s", flags.FlagFees, sdk.NewCoins(sdk.NewCoin(sdk.DefaultBondDenom, sdk.NewInt(10))).String()), }, - false, 0, &sdk.TxResponse{}, + "", }, } @@ -479,14 +466,13 @@ func (s *CLITestSuite) TestNewDelegateCmd() { s.Run(tc.name, func() { out, err := clitestutil.ExecTestCLICmd(s.clientCtx, cmd, tc.args) - if tc.expectErr { + if tc.expectErrMsg != "" { s.Require().Error(err) + s.Require().Contains(err.Error(), tc.expectErrMsg) } else { s.Require().NoError(err, out.String()) - s.Require().NoError(s.clientCtx.Codec.UnmarshalJSON(out.Bytes(), tc.respType), out.String()) - - txResp := tc.respType.(*sdk.TxResponse) - s.Require().Equal(tc.expectedCode, txResp.Code, out.String()) + resp := &sdk.TxResponse{} + s.Require().NoError(s.clientCtx.Codec.UnmarshalJSON(out.Bytes(), resp)) } }) } @@ -498,21 +484,20 @@ func (s *CLITestSuite) TestNewRedelegateCmd() { testCases := []struct { name string args []string - expectErr bool - expectedCode uint32 - respType proto.Message + expectErrMsg string }{ { - "without amount", + "invalid amount", []string{ sdk.ValAddress(s.addrs[0]).String(), // src-validator-addr sdk.ValAddress(s.addrs[1]).String(), // dst-validator-addr + "fooCoin", fmt.Sprintf("--%s=%s", flags.FlagFrom, s.addrs[0]), fmt.Sprintf("--%s=true", flags.FlagSkipConfirmation), fmt.Sprintf("--%s=%s", flags.FlagBroadcastMode, flags.BroadcastSync), fmt.Sprintf("--%s=%s", flags.FlagFees, sdk.NewCoins(sdk.NewCoin(sdk.DefaultBondDenom, sdk.NewInt(10))).String()), }, - true, 0, nil, + "invalid decimal coin expression: fooCoin", }, { "valid transaction of delegate", @@ -526,7 +511,7 @@ func (s *CLITestSuite) TestNewRedelegateCmd() { fmt.Sprintf("--%s=%s", flags.FlagBroadcastMode, flags.BroadcastSync), fmt.Sprintf("--%s=%s", flags.FlagFees, sdk.NewCoins(sdk.NewCoin(sdk.DefaultBondDenom, sdk.NewInt(10))).String()), }, - false, 0, &sdk.TxResponse{}, + "", }, } @@ -535,14 +520,13 @@ func (s *CLITestSuite) TestNewRedelegateCmd() { s.Run(tc.name, func() { out, err := clitestutil.ExecTestCLICmd(s.clientCtx, cmd, tc.args) - if tc.expectErr { + if tc.expectErrMsg != "" { s.Require().Error(err) + s.Require().Contains(err.Error(), tc.expectErrMsg) } else { s.Require().NoError(err, out.String()) - s.Require().NoError(s.clientCtx.Codec.UnmarshalJSON(out.Bytes(), tc.respType), out.String()) - - txResp := tc.respType.(*sdk.TxResponse) - s.Require().Equal(tc.expectedCode, txResp.Code, out.String()) + resp := &sdk.TxResponse{} + s.Require().NoError(s.clientCtx.Codec.UnmarshalJSON(out.Bytes(), resp)) } }) } @@ -554,31 +538,31 @@ func (s *CLITestSuite) TestNewUnbondCmd() { testCases := []struct { name string args []string - expectErr bool - expectedCode uint32 - respType proto.Message + expectErrMsg string }{ { - "Without unbond amount", + "invalid unbond amount", []string{ sdk.ValAddress(s.addrs[0]).String(), + "foo", fmt.Sprintf("--%s=%s", flags.FlagFrom, s.addrs[0]), fmt.Sprintf("--%s=true", flags.FlagSkipConfirmation), fmt.Sprintf("--%s=%s", flags.FlagBroadcastMode, flags.BroadcastSync), fmt.Sprintf("--%s=%s", flags.FlagFees, sdk.NewCoins(sdk.NewCoin(sdk.DefaultBondDenom, sdk.NewInt(10))).String()), }, - true, 0, nil, + "invalid decimal coin expression: foo", }, { - "Without validator address", + "invalid validator address", []string{ + "foo", sdk.NewCoin(sdk.DefaultBondDenom, sdk.NewInt(150)).String(), fmt.Sprintf("--%s=%s", flags.FlagFrom, s.addrs[0]), fmt.Sprintf("--%s=true", flags.FlagSkipConfirmation), fmt.Sprintf("--%s=%s", flags.FlagBroadcastMode, flags.BroadcastSync), fmt.Sprintf("--%s=%s", flags.FlagFees, sdk.NewCoins(sdk.NewCoin(sdk.DefaultBondDenom, sdk.NewInt(10))).String()), }, - true, 0, nil, + "decoding bech32 failed", }, { "valid transaction of unbond", @@ -590,7 +574,7 @@ func (s *CLITestSuite) TestNewUnbondCmd() { fmt.Sprintf("--%s=%s", flags.FlagBroadcastMode, flags.BroadcastSync), fmt.Sprintf("--%s=%s", flags.FlagFees, sdk.NewCoins(sdk.NewCoin(sdk.DefaultBondDenom, sdk.NewInt(10))).String()), }, - false, 0, &sdk.TxResponse{}, + "", }, } @@ -599,14 +583,13 @@ func (s *CLITestSuite) TestNewUnbondCmd() { s.Run(tc.name, func() { out, err := clitestutil.ExecTestCLICmd(s.clientCtx, cmd, tc.args) - if tc.expectErr { + if tc.expectErrMsg != "" { s.Require().Error(err) + s.Require().Contains(err.Error(), tc.expectErrMsg) } else { s.Require().NoError(err, out.String()) - s.Require().NoError(s.clientCtx.Codec.UnmarshalJSON(out.Bytes(), tc.respType), out.String()) - - txResp := tc.respType.(*sdk.TxResponse) - s.Require().Equal(tc.expectedCode, txResp.Code, out.String()) + resp := &sdk.TxResponse{} + s.Require().NoError(s.clientCtx.Codec.UnmarshalJSON(out.Bytes(), resp)) } }) } @@ -618,42 +601,46 @@ func (s *CLITestSuite) TestNewCancelUnbondingDelegationCmd() { testCases := []struct { name string args []string - expectErr bool - expectedCode uint32 - respType proto.Message + expectErrMsg string }{ { - "Without validator address", + "invalid validator address", []string{ + "foo", + sdk.NewCoin(sdk.DefaultBondDenom, sdk.NewInt(150)).String(), + sdk.NewInt(10000).String(), fmt.Sprintf("--%s=%s", flags.FlagFrom, s.addrs[0]), fmt.Sprintf("--%s=true", flags.FlagSkipConfirmation), fmt.Sprintf("--%s=%s", flags.FlagBroadcastMode, flags.BroadcastSync), fmt.Sprintf("--%s=%s", flags.FlagFees, sdk.NewCoins(sdk.NewCoin(sdk.DefaultBondDenom, sdk.NewInt(10))).String()), }, - true, 0, nil, + "decoding bech32 failed", }, { - "Without canceling unbond delegation amount", + "invalid canceling unbond delegation amount", []string{ sdk.ValAddress(s.addrs[0]).String(), + "fooCoin", + sdk.NewInt(10000).String(), fmt.Sprintf("--%s=%s", flags.FlagFrom, s.addrs[0]), fmt.Sprintf("--%s=true", flags.FlagSkipConfirmation), fmt.Sprintf("--%s=%s", flags.FlagBroadcastMode, flags.BroadcastSync), fmt.Sprintf("--%s=%s", flags.FlagFees, sdk.NewCoins(sdk.NewCoin(sdk.DefaultBondDenom, sdk.NewInt(10))).String()), }, - true, 0, nil, + "invalid decimal coin expression", }, { - "Without unbond creation height", + "without unbond creation height", []string{ sdk.ValAddress(s.addrs[0]).String(), sdk.NewCoin(sdk.DefaultBondDenom, sdk.NewInt(150)).String(), + "abc", fmt.Sprintf("--%s=%s", flags.FlagFrom, s.addrs[0]), fmt.Sprintf("--%s=true", flags.FlagSkipConfirmation), fmt.Sprintf("--%s=%s", flags.FlagBroadcastMode, flags.BroadcastSync), fmt.Sprintf("--%s=%s", flags.FlagFees, sdk.NewCoins(sdk.NewCoin(sdk.DefaultBondDenom, sdk.NewInt(10))).String()), }, - true, 0, nil, + "invalid height: invalid height: 0", }, { "valid transaction of canceling unbonding delegation", @@ -666,7 +653,7 @@ func (s *CLITestSuite) TestNewCancelUnbondingDelegationCmd() { fmt.Sprintf("--%s=%s", flags.FlagBroadcastMode, flags.BroadcastSync), fmt.Sprintf("--%s=%s", flags.FlagFees, sdk.NewCoins(sdk.NewCoin(sdk.DefaultBondDenom, sdk.NewInt(10))).String()), }, - false, 0, &sdk.TxResponse{}, + "", }, } @@ -675,14 +662,13 @@ func (s *CLITestSuite) TestNewCancelUnbondingDelegationCmd() { s.Run(tc.name, func() { out, err := clitestutil.ExecTestCLICmd(s.clientCtx, cmd, tc.args) - if tc.expectErr { + if tc.expectErrMsg != "" { s.Require().Error(err) + s.Require().Contains(err.Error(), tc.expectErrMsg) } else { s.Require().NoError(err, out.String()) - s.Require().NoError(s.clientCtx.Codec.UnmarshalJSON(out.Bytes(), tc.respType), out.String()) - - txResp := tc.respType.(*sdk.TxResponse) - s.Require().Equal(tc.expectedCode, txResp.Code, out.String()) + resp := &sdk.TxResponse{} + s.Require().NoError(s.clientCtx.Codec.UnmarshalJSON(out.Bytes(), resp)) } }) } diff --git a/x/staking/abci.go b/x/staking/keeper/abci.go similarity index 73% rename from x/staking/abci.go rename to x/staking/keeper/abci.go index 1912beb99747..fcb65377eba8 100644 --- a/x/staking/abci.go +++ b/x/staking/keeper/abci.go @@ -1,27 +1,26 @@ -package staking +package keeper import ( + "context" "time" abci "github.com/cometbft/cometbft/abci/types" - "github.com/cosmos/cosmos-sdk/telemetry" sdk "github.com/cosmos/cosmos-sdk/types" - "github.com/cosmos/cosmos-sdk/x/staking/keeper" "github.com/cosmos/cosmos-sdk/x/staking/types" ) // BeginBlocker will persist the current header and validator set as a historical entry // and prune the oldest entry based on the HistoricalEntries parameter -func BeginBlocker(ctx sdk.Context, k *keeper.Keeper) { +func (k *Keeper) BeginBlocker(ctx sdk.Context) { defer telemetry.ModuleMeasureSince(types.ModuleName, time.Now(), telemetry.MetricKeyBeginBlocker) k.TrackHistoricalInfo(ctx) } // Called every block, update validator set -func EndBlocker(ctx sdk.Context, k *keeper.Keeper) []abci.ValidatorUpdate { +func (k *Keeper) EndBlocker(ctx context.Context) ([]abci.ValidatorUpdate, error) { defer telemetry.ModuleMeasureSince(types.ModuleName, time.Now(), telemetry.MetricKeyEndBlocker) - return k.BlockValidatorUpdates(ctx) + return k.BlockValidatorUpdates(sdk.UnwrapSDKContext(ctx)), nil } diff --git a/x/staking/keeper/delegation.go b/x/staking/keeper/delegation.go index 5093688b5bb9..3ad718aaffad 100644 --- a/x/staking/keeper/delegation.go +++ b/x/staking/keeper/delegation.go @@ -57,7 +57,7 @@ func (k Keeper) GetAllDelegations(ctx sdk.Context) (delegations []types.Delegati // GetValidatorDelegations returns all delegations to a specific validator. // Useful for querier. -func (k Keeper) GetValidatorDelegations(ctx sdk.Context, valAddr sdk.ValAddress) (delegations []types.Delegation) { //nolint:interfacer +func (k Keeper) GetValidatorDelegations(ctx sdk.Context, valAddr sdk.ValAddress) (delegations []types.Delegation) { store := ctx.KVStore(k.storeKey) iterator := storetypes.KVStorePrefixIterator(store, types.DelegationKey) @@ -95,7 +95,10 @@ func (k Keeper) GetDelegatorDelegations(ctx sdk.Context, delegator sdk.AccAddres // SetDelegation sets a delegation. func (k Keeper) SetDelegation(ctx sdk.Context, delegation types.Delegation) { - delegatorAddress := sdk.MustAccAddressFromBech32(delegation.DelegatorAddress) + delegatorAddress, err := k.authKeeper.StringToBytes(delegation.DelegatorAddress) + if err != nil { + panic(err) + } store := ctx.KVStore(k.storeKey) b := types.MustMarshalDelegation(k.cdc, delegation) @@ -104,7 +107,10 @@ func (k Keeper) SetDelegation(ctx sdk.Context, delegation types.Delegation) { // RemoveDelegation removes a delegation func (k Keeper) RemoveDelegation(ctx sdk.Context, delegation types.Delegation) error { - delegatorAddress := sdk.MustAccAddressFromBech32(delegation.DelegatorAddress) + delegatorAddress, err := k.authKeeper.StringToBytes(delegation.DelegatorAddress) + if err != nil { + panic(err) + } // TODO: Consider calling hooks outside of the store wrapper functions, it's unobvious. if err := k.Hooks().BeforeDelegationRemoved(ctx, delegatorAddress, delegation.GetValidatorAddr()); err != nil { @@ -275,7 +281,10 @@ func (k Keeper) HasMaxUnbondingDelegationEntries(ctx sdk.Context, delegatorAddr // SetUnbondingDelegation sets the unbonding delegation and associated index. func (k Keeper) SetUnbondingDelegation(ctx sdk.Context, ubd types.UnbondingDelegation) { - delAddr := sdk.MustAccAddressFromBech32(ubd.DelegatorAddress) + delAddr, err := k.authKeeper.StringToBytes(ubd.DelegatorAddress) + if err != nil { + panic(err) + } store := ctx.KVStore(k.storeKey) bz := types.MustMarshalUBD(k.cdc, ubd) @@ -290,7 +299,10 @@ func (k Keeper) SetUnbondingDelegation(ctx sdk.Context, ubd types.UnbondingDeleg // RemoveUnbondingDelegation removes the unbonding delegation object and associated index. func (k Keeper) RemoveUnbondingDelegation(ctx sdk.Context, ubd types.UnbondingDelegation) { - delegatorAddress := sdk.MustAccAddressFromBech32(ubd.DelegatorAddress) + delegatorAddress, err := k.authKeeper.StringToBytes(ubd.DelegatorAddress) + if err != nil { + panic(err) + } store := ctx.KVStore(k.storeKey) addr, err := sdk.ValAddressFromBech32(ubd.ValidatorAddress) @@ -473,7 +485,10 @@ func (k Keeper) HasMaxRedelegationEntries(ctx sdk.Context, delegatorAddr sdk.Acc // SetRedelegation set a redelegation and associated index. func (k Keeper) SetRedelegation(ctx sdk.Context, red types.Redelegation) { - delegatorAddress := sdk.MustAccAddressFromBech32(red.DelegatorAddress) + delegatorAddress, err := k.authKeeper.StringToBytes(red.DelegatorAddress) + if err != nil { + panic(err) + } store := ctx.KVStore(k.storeKey) bz := types.MustMarshalRED(k.cdc, red) @@ -538,7 +553,10 @@ func (k Keeper) IterateRedelegations(ctx sdk.Context, fn func(index int64, red t // RemoveRedelegation removes a redelegation object and associated index. func (k Keeper) RemoveRedelegation(ctx sdk.Context, red types.Redelegation) { - delegatorAddress := sdk.MustAccAddressFromBech32(red.DelegatorAddress) + delegatorAddress, err := k.authKeeper.StringToBytes(red.DelegatorAddress) + if err != nil { + panic(err) + } store := ctx.KVStore(k.storeKey) valSrcAddr, err := sdk.ValAddressFromBech32(red.ValidatorSrcAddress) @@ -659,7 +677,10 @@ func (k Keeper) Delegate( return math.LegacyZeroDec(), err } - delegatorAddress := sdk.MustAccAddressFromBech32(delegation.DelegatorAddress) + delegatorAddress, err := k.authKeeper.StringToBytes(delegation.DelegatorAddress) + if err != nil { + panic(err) + } // if subtractAccount is true then we are // performing a delegation and not a redelegation, thus the source tokens are @@ -745,12 +766,12 @@ func (k Keeper) Unbond( // subtract shares from delegation delegation.Shares = delegation.Shares.Sub(shares) - delegatorAddress, err := sdk.AccAddressFromBech32(delegation.DelegatorAddress) + delegatorAddress, err := k.authKeeper.StringToBytes(delegation.DelegatorAddress) if err != nil { return amount, err } - isValidatorOperator := delegatorAddress.Equals(validator.GetOperator()) + isValidatorOperator := bytes.Equal(delegatorAddress, validator.GetOperator()) // If the delegation is the operator of the validator and undelegating will decrease the validator's // self-delegation below their minimum, we jail the validator. @@ -858,7 +879,7 @@ func (k Keeper) CompleteUnbonding(ctx sdk.Context, delAddr sdk.AccAddress, valAd balances := sdk.NewCoins() ctxTime := ctx.BlockHeader().Time - delegatorAddress, err := sdk.AccAddressFromBech32(ubd.DelegatorAddress) + delegatorAddress, err := k.authKeeper.StringToBytes(ubd.DelegatorAddress) if err != nil { return nil, err } diff --git a/x/staking/keeper/delegation_test.go b/x/staking/keeper/delegation_test.go index 7a747aceaf7b..fa2cd3351eb5 100644 --- a/x/staking/keeper/delegation_test.go +++ b/x/staking/keeper/delegation_test.go @@ -27,6 +27,11 @@ func (s *KeeperTestSuite) TestDelegation() { addrDels, valAddrs := createValAddrs(3) + for _, addr := range addrDels { + s.accountKeeper.EXPECT().StringToBytes(addr.String()).Return(addr, nil).AnyTimes() + s.accountKeeper.EXPECT().BytesToString(addr).Return(addr.String(), nil).AnyTimes() + } + // construct the validators amts := []math.Int{sdk.NewInt(9), sdk.NewInt(8), sdk.NewInt(7)} var validators [3]stakingtypes.Validator @@ -146,6 +151,11 @@ func (s *KeeperTestSuite) TestUnbondingDelegation() { delAddrs, valAddrs := createValAddrs(2) + for _, addr := range delAddrs { + s.accountKeeper.EXPECT().StringToBytes(addr.String()).Return(addr, nil).AnyTimes() + s.accountKeeper.EXPECT().BytesToString(addr).Return(addr.String(), nil).AnyTimes() + } + ubd := stakingtypes.NewUnbondingDelegation( delAddrs[0], valAddrs[0], @@ -196,6 +206,11 @@ func (s *KeeperTestSuite) TestUnbondDelegation() { require := s.Require() delAddrs, valAddrs := createValAddrs(1) + + for _, addr := range delAddrs { + s.accountKeeper.EXPECT().StringToBytes(addr.String()).Return(addr, nil).AnyTimes() + s.accountKeeper.EXPECT().BytesToString(addr).Return(addr.String(), nil).AnyTimes() + } startTokens := keeper.TokensFromConsensusPower(ctx, 10) validator := testutil.NewValidator(s.T(), valAddrs[0], PKs[0]) @@ -231,6 +246,10 @@ func (s *KeeperTestSuite) TestUndelegateSelfDelegationBelowMinSelfDelegation() { require := s.Require() addrDels, addrVals := createValAddrs(1) + for _, addr := range addrDels { + s.accountKeeper.EXPECT().StringToBytes(addr.String()).Return(addr, nil).AnyTimes() + s.accountKeeper.EXPECT().BytesToString(addr).Return(addr.String(), nil).AnyTimes() + } delTokens := keeper.TokensFromConsensusPower(ctx, 10) // create a validator with a self-delegation @@ -280,6 +299,10 @@ func (s *KeeperTestSuite) TestUndelegateFromUnbondingValidator() { delTokens := keeper.TokensFromConsensusPower(ctx, 10) addrDels, addrVals := createValAddrs(2) + for _, addr := range addrDels { + s.accountKeeper.EXPECT().StringToBytes(addr.String()).Return(addr, nil).AnyTimes() + s.accountKeeper.EXPECT().BytesToString(addr).Return(addr.String(), nil).AnyTimes() + } // create a validator with a self-delegation validator := testutil.NewValidator(s.T(), addrVals[0], PKs[0]) @@ -355,6 +378,10 @@ func (s *KeeperTestSuite) TestUndelegateFromUnbondedValidator() { delTokens := keeper.TokensFromConsensusPower(ctx, 10) addrDels, addrVals := createValAddrs(2) + for _, addr := range addrDels { + s.accountKeeper.EXPECT().StringToBytes(addr.String()).Return(addr, nil).AnyTimes() + s.accountKeeper.EXPECT().BytesToString(addr).Return(addr.String(), nil).AnyTimes() + } // create a validator with a self-delegation validator := testutil.NewValidator(s.T(), addrVals[0], PKs[0]) @@ -431,6 +458,10 @@ func (s *KeeperTestSuite) TestUnbondingAllDelegationFromValidator() { delTokens := keeper.TokensFromConsensusPower(ctx, 10) addrDels, addrVals := createValAddrs(2) + for _, addr := range addrDels { + s.accountKeeper.EXPECT().StringToBytes(addr.String()).Return(addr, nil).AnyTimes() + s.accountKeeper.EXPECT().BytesToString(addr).Return(addr.String(), nil).AnyTimes() + } // create a validator with a self-delegation validator := testutil.NewValidator(s.T(), addrVals[0], PKs[0]) @@ -498,6 +529,11 @@ func (s *KeeperTestSuite) TestGetRedelegationsFromSrcValidator() { addrDels, addrVals := createValAddrs(2) + for _, addr := range addrDels { + s.accountKeeper.EXPECT().StringToBytes(addr.String()).Return(addr, nil).AnyTimes() + s.accountKeeper.EXPECT().BytesToString(addr).Return(addr.String(), nil).AnyTimes() + } + rd := stakingtypes.NewRedelegation(addrDels[0], addrVals[0], addrVals[1], 0, time.Unix(0, 0), sdk.NewInt(5), math.LegacyNewDec(5), 0) @@ -524,6 +560,10 @@ func (s *KeeperTestSuite) TestRedelegation() { require := s.Require() addrDels, addrVals := createValAddrs(2) + for _, addr := range addrDels { + s.accountKeeper.EXPECT().StringToBytes(addr.String()).Return(addr, nil).AnyTimes() + s.accountKeeper.EXPECT().BytesToString(addr).Return(addr.String(), nil).AnyTimes() + } rd := stakingtypes.NewRedelegation(addrDels[0], addrVals[0], addrVals[1], 0, time.Unix(0, 0).UTC(), sdk.NewInt(5), @@ -599,6 +639,10 @@ func (s *KeeperTestSuite) TestRedelegateToSameValidator() { require.True(validator.IsBonded()) val0AccAddr := sdk.AccAddress(addrVals[0].Bytes()) + + s.accountKeeper.EXPECT().StringToBytes(val0AccAddr.String()).Return(val0AccAddr, nil).AnyTimes() + s.accountKeeper.EXPECT().BytesToString(val0AccAddr).Return(val0AccAddr.String(), nil).AnyTimes() + selfDelegation := stakingtypes.NewDelegation(val0AccAddr, addrVals[0], issuedShares) keeper.SetDelegation(ctx, selfDelegation) @@ -621,6 +665,8 @@ func (s *KeeperTestSuite) TestRedelegationMaxEntries() { s.bankKeeper.EXPECT().SendCoinsFromModuleToModule(gomock.Any(), stakingtypes.NotBondedPoolName, stakingtypes.BondedPoolName, gomock.Any()) _ = stakingkeeper.TestingUpdateValidator(keeper, ctx, validator, true) val0AccAddr := sdk.AccAddress(addrVals[0].Bytes()) + s.accountKeeper.EXPECT().StringToBytes(val0AccAddr.String()).Return(val0AccAddr, nil).AnyTimes() + s.accountKeeper.EXPECT().BytesToString(val0AccAddr).Return(val0AccAddr.String(), nil).AnyTimes() selfDelegation := stakingtypes.NewDelegation(val0AccAddr, addrVals[0], issuedShares) keeper.SetDelegation(ctx, selfDelegation) @@ -662,6 +708,15 @@ func (s *KeeperTestSuite) TestRedelegateSelfDelegation() { require := s.Require() addrDels, addrVals := createValAddrs(2) + for _, addr := range addrDels { + s.accountKeeper.EXPECT().StringToBytes(addr.String()).Return(addr, nil).AnyTimes() + s.accountKeeper.EXPECT().BytesToString(addr).Return(addr.String(), nil).AnyTimes() + } + + for _, addr := range addrDels { + s.accountKeeper.EXPECT().StringToBytes(addr.String()).Return(addr, nil).AnyTimes() + s.accountKeeper.EXPECT().BytesToString(addr).Return(addr.String(), nil).AnyTimes() + } // create a validator with a self-delegation validator := testutil.NewValidator(s.T(), addrVals[0], PKs[0]) @@ -713,6 +768,10 @@ func (s *KeeperTestSuite) TestRedelegateFromUnbondingValidator() { require := s.Require() addrDels, addrVals := createValAddrs(2) + for _, addr := range addrDels { + s.accountKeeper.EXPECT().StringToBytes(addr.String()).Return(addr, nil).AnyTimes() + s.accountKeeper.EXPECT().BytesToString(addr).Return(addr.String(), nil).AnyTimes() + } // create a validator with a self-delegation validator := testutil.NewValidator(s.T(), addrVals[0], PKs[0]) @@ -793,6 +852,15 @@ func (s *KeeperTestSuite) TestRedelegateFromUnbondedValidator() { require := s.Require() addrDels, addrVals := createValAddrs(2) + for _, addr := range addrDels { + s.accountKeeper.EXPECT().StringToBytes(addr.String()).Return(addr, nil).AnyTimes() + s.accountKeeper.EXPECT().BytesToString(addr).Return(addr.String(), nil).AnyTimes() + } + + for _, addr := range addrDels { + s.accountKeeper.EXPECT().StringToBytes(addr.String()).Return(addr, nil).AnyTimes() + s.accountKeeper.EXPECT().BytesToString(addr).Return(addr.String(), nil).AnyTimes() + } // create a validator with a self-delegation validator := testutil.NewValidator(s.T(), addrVals[0], PKs[0]) diff --git a/x/staking/keeper/genesis.go b/x/staking/keeper/genesis.go index d8af3355f91c..37e68cc699e8 100644 --- a/x/staking/keeper/genesis.go +++ b/x/staking/keeper/genesis.go @@ -64,7 +64,10 @@ func (k Keeper) InitGenesis(ctx sdk.Context, data *types.GenesisState) (res []ab } for _, delegation := range data.Delegations { - delegatorAddress := sdk.MustAccAddressFromBech32(delegation.DelegatorAddress) + delegatorAddress, err := k.authKeeper.StringToBytes(delegation.DelegatorAddress) + if err != nil { + panic(fmt.Errorf("invalid delegator address: %s", err)) + } // Call the before-creation hook if not exported if !data.Exported { diff --git a/x/staking/keeper/grpc_query.go b/x/staking/keeper/grpc_query.go index 135242001706..ea9f29810223 100644 --- a/x/staking/keeper/grpc_query.go +++ b/x/staking/keeper/grpc_query.go @@ -150,7 +150,7 @@ func (k Querier) ValidatorUnbondingDelegations(c context.Context, req *types.Que srcValPrefix := types.GetUBDsByValIndexKey(valAddr) ubdStore := prefix.NewStore(store, srcValPrefix) - pageRes, err := query.Paginate(ubdStore, req.Pagination, func(key []byte, value []byte) error { + pageRes, err := query.Paginate(ubdStore, req.Pagination, func(key, value []byte) error { storeKey := types.GetUBDKeyFromValIndexKey(append(srcValPrefix, key...)) storeValue := store.Get(storeKey) @@ -185,7 +185,7 @@ func (k Querier) Delegation(c context.Context, req *types.QueryDelegationRequest } ctx := sdk.UnwrapSDKContext(c) - delAddr, err := sdk.AccAddressFromBech32(req.DelegatorAddr) + delAddr, err := k.authKeeper.StringToBytes(req.DelegatorAddr) if err != nil { return nil, err } @@ -226,7 +226,7 @@ func (k Querier) UnbondingDelegation(c context.Context, req *types.QueryUnbondin ctx := sdk.UnwrapSDKContext(c) - delAddr, err := sdk.AccAddressFromBech32(req.DelegatorAddr) + delAddr, err := k.authKeeper.StringToBytes(req.DelegatorAddr) if err != nil { return nil, err } @@ -259,14 +259,14 @@ func (k Querier) DelegatorDelegations(c context.Context, req *types.QueryDelegat var delegations types.Delegations ctx := sdk.UnwrapSDKContext(c) - delAddr, err := sdk.AccAddressFromBech32(req.DelegatorAddr) + delAddr, err := k.authKeeper.StringToBytes(req.DelegatorAddr) if err != nil { return nil, err } store := ctx.KVStore(k.storeKey) delStore := prefix.NewStore(store, types.GetDelegationsKey(delAddr)) - pageRes, err := query.Paginate(delStore, req.Pagination, func(key []byte, value []byte) error { + pageRes, err := query.Paginate(delStore, req.Pagination, func(key, value []byte) error { delegation, err := types.UnmarshalDelegation(k.cdc, value) if err != nil { return err @@ -300,7 +300,7 @@ func (k Querier) DelegatorValidator(c context.Context, req *types.QueryDelegator } ctx := sdk.UnwrapSDKContext(c) - delAddr, err := sdk.AccAddressFromBech32(req.DelegatorAddr) + delAddr, err := k.authKeeper.StringToBytes(req.DelegatorAddr) if err != nil { return nil, err } @@ -331,13 +331,13 @@ func (k Querier) DelegatorUnbondingDelegations(c context.Context, req *types.Que ctx := sdk.UnwrapSDKContext(c) store := ctx.KVStore(k.storeKey) - delAddr, err := sdk.AccAddressFromBech32(req.DelegatorAddr) + delAddr, err := k.authKeeper.StringToBytes(req.DelegatorAddr) if err != nil { return nil, err } unbStore := prefix.NewStore(store, types.GetUBDsKey(delAddr)) - pageRes, err := query.Paginate(unbStore, req.Pagination, func(key []byte, value []byte) error { + pageRes, err := query.Paginate(unbStore, req.Pagination, func(key, value []byte) error { unbond, err := types.UnmarshalUBD(k.cdc, value) if err != nil { return err @@ -416,13 +416,13 @@ func (k Querier) DelegatorValidators(c context.Context, req *types.QueryDelegato ctx := sdk.UnwrapSDKContext(c) store := ctx.KVStore(k.storeKey) - delAddr, err := sdk.AccAddressFromBech32(req.DelegatorAddr) + delAddr, err := k.authKeeper.StringToBytes(req.DelegatorAddr) if err != nil { return nil, err } delStore := prefix.NewStore(store, types.GetDelegationsKey(delAddr)) - pageRes, err := query.Paginate(delStore, req.Pagination, func(key []byte, value []byte) error { + pageRes, err := query.Paginate(delStore, req.Pagination, func(key, value []byte) error { delegation, err := types.UnmarshalDelegation(k.cdc, value) if err != nil { return err @@ -467,7 +467,7 @@ func (k Querier) Params(c context.Context, _ *types.QueryParamsRequest) (*types. } func queryRedelegation(ctx sdk.Context, k Querier, req *types.QueryRedelegationsRequest) (redels types.Redelegations, err error) { - delAddr, err := sdk.AccAddressFromBech32(req.DelegatorAddr) + delAddr, err := k.authKeeper.StringToBytes(req.DelegatorAddr) if err != nil { return nil, err } @@ -502,7 +502,7 @@ func queryRedelegationsFromSrcValidator(store storetypes.KVStore, k Querier, req srcValPrefix := types.GetREDsFromValSrcIndexKey(valAddr) redStore := prefix.NewStore(store, srcValPrefix) - res, err = query.Paginate(redStore, req.Pagination, func(key []byte, value []byte) error { + res, err = query.Paginate(redStore, req.Pagination, func(key, value []byte) error { storeKey := types.GetREDKeyFromValSrcIndexKey(append(srcValPrefix, key...)) storeValue := store.Get(storeKey) red, err := types.UnmarshalRED(k.cdc, storeValue) @@ -517,13 +517,13 @@ func queryRedelegationsFromSrcValidator(store storetypes.KVStore, k Querier, req } func queryAllRedelegations(store storetypes.KVStore, k Querier, req *types.QueryRedelegationsRequest) (redels types.Redelegations, res *query.PageResponse, err error) { - delAddr, err := sdk.AccAddressFromBech32(req.DelegatorAddr) + delAddr, err := k.authKeeper.StringToBytes(req.DelegatorAddr) if err != nil { return nil, nil, err } redStore := prefix.NewStore(store, types.GetREDsKey(delAddr)) - res, err = query.Paginate(redStore, req.Pagination, func(key []byte, value []byte) error { + res, err = query.Paginate(redStore, req.Pagination, func(key, value []byte) error { redelegation, err := types.UnmarshalRED(k.cdc, value) if err != nil { return err @@ -543,7 +543,7 @@ func DelegationToDelegationResponse(ctx sdk.Context, k *Keeper, del types.Delega return types.DelegationResponse{}, types.ErrNoValidatorFound } - delegatorAddress, err := sdk.AccAddressFromBech32(del.DelegatorAddress) + delegatorAddress, err := k.authKeeper.StringToBytes(del.DelegatorAddress) if err != nil { return types.DelegationResponse{}, err } @@ -584,7 +584,10 @@ func RedelegationsToRedelegationResponses(ctx sdk.Context, k *Keeper, redels typ panic(err) } - delegatorAddress := sdk.MustAccAddressFromBech32(redel.DelegatorAddress) + delegatorAddress, err := k.authKeeper.StringToBytes(redel.DelegatorAddress) + if err != nil { + return nil, err + } val, found := k.GetValidator(ctx, valDstAddr) if !found { diff --git a/x/staking/keeper/historical_info_test.go b/x/staking/keeper/historical_info_test.go index 9709c5440b52..f3b68ceec48a 100644 --- a/x/staking/keeper/historical_info_test.go +++ b/x/staking/keeper/historical_info_test.go @@ -136,9 +136,9 @@ func (s *KeeperTestSuite) TestGetAllHistoricalInfo() { testutil.NewValidator(s.T(), addrVals[1], PKs[1]), } - header1 := cmtproto.Header{ChainID: "HelloChain", Height: 10} - header2 := cmtproto.Header{ChainID: "HelloChain", Height: 11} - header3 := cmtproto.Header{ChainID: "HelloChain", Height: 12} + header1 := cmtproto.Header{ChainID: "HelloChain", Height: 9} + header2 := cmtproto.Header{ChainID: "HelloChain", Height: 10} + header3 := cmtproto.Header{ChainID: "HelloChain", Height: 11} hist1 := stakingtypes.HistoricalInfo{Header: header1, Valset: valSet} hist2 := stakingtypes.HistoricalInfo{Header: header2, Valset: valSet} @@ -147,7 +147,7 @@ func (s *KeeperTestSuite) TestGetAllHistoricalInfo() { expHistInfos := []stakingtypes.HistoricalInfo{hist1, hist2, hist3} for i, hi := range expHistInfos { - keeper.SetHistoricalInfo(ctx, int64(10+i), &hi) //nolint:gosec // G601: Implicit memory aliasing in for loop. + keeper.SetHistoricalInfo(ctx, int64(9+i), &hi) //nolint:gosec // G601: Implicit memory aliasing in for loop. } infos := keeper.GetAllHistoricalInfo(ctx) diff --git a/x/staking/keeper/keeper.go b/x/staking/keeper/keeper.go index 93902cf3d885..39513647b1c3 100644 --- a/x/staking/keeper/keeper.go +++ b/x/staking/keeper/keeper.go @@ -8,7 +8,6 @@ import ( abci "github.com/cometbft/cometbft/abci/types" storetypes "cosmossdk.io/store/types" - "github.com/cosmos/cosmos-sdk/codec" sdk "github.com/cosmos/cosmos-sdk/types" "github.com/cosmos/cosmos-sdk/x/staking/types" @@ -48,7 +47,7 @@ func NewKeeper( } // ensure that authority is a valid AccAddress - if _, err := sdk.AccAddressFromBech32(authority); err != nil { + if _, err := ak.StringToBytes(authority); err != nil { panic("authority is not a valid acc address") } diff --git a/x/staking/keeper/keeper_test.go b/x/staking/keeper/keeper_test.go index fb74f5525d78..4379a7e3448c 100644 --- a/x/staking/keeper/keeper_test.go +++ b/x/staking/keeper/keeper_test.go @@ -1,6 +1,7 @@ package keeper_test import ( + "errors" "testing" "cosmossdk.io/math" @@ -50,6 +51,11 @@ func (s *KeeperTestSuite) SetupTest() { accountKeeper := stakingtestutil.NewMockAccountKeeper(ctrl) accountKeeper.EXPECT().GetModuleAddress(stakingtypes.BondedPoolName).Return(bondedAcc.GetAddress()) accountKeeper.EXPECT().GetModuleAddress(stakingtypes.NotBondedPoolName).Return(notBondedAcc.GetAddress()) + accountKeeper.EXPECT().StringToBytes(authtypes.NewModuleAddress(govtypes.ModuleName).String()).Return(authtypes.NewModuleAddress(govtypes.ModuleName), nil).AnyTimes() + accountKeeper.EXPECT().BytesToString(authtypes.NewModuleAddress(govtypes.ModuleName)).Return(authtypes.NewModuleAddress(govtypes.ModuleName).String(), nil).AnyTimes() + accountKeeper.EXPECT().StringToBytes("").Return(nil, errors.New("empty address string is not allowed")).AnyTimes() + accountKeeper.EXPECT().StringToBytes("invalid").Return(nil, errors.New("invalid bech32 string")).AnyTimes() + bankKeeper := stakingtestutil.NewMockBankKeeper(ctrl) keeper := stakingkeeper.NewKeeper( diff --git a/x/staking/keeper/migrations.go b/x/staking/keeper/migrations.go index b34a7993bfc7..26dd511e2195 100644 --- a/x/staking/keeper/migrations.go +++ b/x/staking/keeper/migrations.go @@ -6,6 +6,7 @@ import ( v2 "github.com/cosmos/cosmos-sdk/x/staking/migrations/v2" v3 "github.com/cosmos/cosmos-sdk/x/staking/migrations/v3" v4 "github.com/cosmos/cosmos-sdk/x/staking/migrations/v4" + v5 "github.com/cosmos/cosmos-sdk/x/staking/migrations/v5" ) // Migrator is a struct for handling in-place store migrations. @@ -36,3 +37,8 @@ func (m Migrator) Migrate2to3(ctx sdk.Context) error { func (m Migrator) Migrate3to4(ctx sdk.Context) error { return v4.MigrateStore(ctx, m.keeper.storeKey, m.keeper.cdc, m.legacySubspace) } + +// Migrate4to5 migrates x/staking state from consensus version 4 to 5. +func (m Migrator) Migrate4to5(ctx sdk.Context) error { + return v5.MigrateStore(ctx, m.keeper.storeKey) +} diff --git a/x/staking/keeper/msg_server.go b/x/staking/keeper/msg_server.go index 9d7113113f1b..83bdd0149edd 100644 --- a/x/staking/keeper/msg_server.go +++ b/x/staking/keeper/msg_server.go @@ -5,12 +5,13 @@ import ( "strconv" "time" + errorsmod "cosmossdk.io/errors" + "cosmossdk.io/math" + "github.com/armon/go-metrics" "google.golang.org/grpc/codes" "google.golang.org/grpc/status" - errorsmod "cosmossdk.io/errors" - cryptotypes "github.com/cosmos/cosmos-sdk/crypto/types" "github.com/cosmos/cosmos-sdk/telemetry" sdk "github.com/cosmos/cosmos-sdk/types" @@ -33,13 +34,17 @@ var _ types.MsgServer = msgServer{} // CreateValidator defines a method for creating a new validator func (k msgServer) CreateValidator(goCtx context.Context, msg *types.MsgCreateValidator) (*types.MsgCreateValidatorResponse, error) { - ctx := sdk.UnwrapSDKContext(goCtx) - valAddr, err := sdk.ValAddressFromBech32(msg.ValidatorAddress) if err != nil { + return nil, sdkerrors.ErrInvalidAddress.Wrapf("invalid validator address: %s", err) + } + + if err := msg.Validate(); err != nil { return nil, err } + ctx := sdk.UnwrapSDKContext(goCtx) + if msg.Commission.Rate.LT(k.MinCommissionRate(ctx)) { return nil, errorsmod.Wrapf(types.ErrCommissionLTMinRate, "cannot set validator commission to less than minimum rate of %s", k.MinCommissionRate(ctx)) } @@ -70,7 +75,7 @@ func (k msgServer) CreateValidator(goCtx context.Context, msg *types.MsgCreateVa } cp := ctx.ConsensusParams() - if cp != nil && cp.Validator != nil { + if cp.Validator != nil { pkType := pk.Type() hasKeyType := false for _, keyType := range cp.Validator.PubKeyTypes { @@ -134,11 +139,30 @@ func (k msgServer) CreateValidator(goCtx context.Context, msg *types.MsgCreateVa // EditValidator defines a method for editing an existing validator func (k msgServer) EditValidator(goCtx context.Context, msg *types.MsgEditValidator) (*types.MsgEditValidatorResponse, error) { - ctx := sdk.UnwrapSDKContext(goCtx) valAddr, err := sdk.ValAddressFromBech32(msg.ValidatorAddress) if err != nil { - return nil, err + return nil, sdkerrors.ErrInvalidAddress.Wrapf("invalid validator address: %s", err) + } + + if msg.Description == (types.Description{}) { + return nil, errorsmod.Wrap(sdkerrors.ErrInvalidRequest, "empty description") + } + + if msg.MinSelfDelegation != nil && !msg.MinSelfDelegation.IsPositive() { + return nil, errorsmod.Wrap( + sdkerrors.ErrInvalidRequest, + "minimum self delegation must be a positive integer", + ) } + + if msg.CommissionRate != nil { + if msg.CommissionRate.GT(math.LegacyOneDec()) || msg.CommissionRate.IsNegative() { + return nil, errorsmod.Wrap(sdkerrors.ErrInvalidRequest, "commission rate must be between 0 and 1 (inclusive)") + } + } + + ctx := sdk.UnwrapSDKContext(goCtx) + // validator must already be registered validator, found := k.GetValidator(ctx, valAddr) if !found { @@ -194,22 +218,30 @@ func (k msgServer) EditValidator(goCtx context.Context, msg *types.MsgEditValida // Delegate defines a method for performing a delegation of coins from a delegator to a validator func (k msgServer) Delegate(goCtx context.Context, msg *types.MsgDelegate) (*types.MsgDelegateResponse, error) { - ctx := sdk.UnwrapSDKContext(goCtx) valAddr, valErr := sdk.ValAddressFromBech32(msg.ValidatorAddress) if valErr != nil { - return nil, valErr + return nil, sdkerrors.ErrInvalidAddress.Wrapf("invalid validator address: %s", valErr) + } + + delegatorAddress, err := k.authKeeper.StringToBytes(msg.DelegatorAddress) + if err != nil { + return nil, sdkerrors.ErrInvalidAddress.Wrapf("invalid delegator address: %s", err) } + if !msg.Amount.IsValid() || !msg.Amount.Amount.IsPositive() { + return nil, errorsmod.Wrap( + sdkerrors.ErrInvalidRequest, + "invalid delegation amount", + ) + } + + ctx := sdk.UnwrapSDKContext(goCtx) + validator, found := k.GetValidator(ctx, valAddr) if !found { return nil, types.ErrNoValidatorFound } - delegatorAddress, err := sdk.AccAddressFromBech32(msg.DelegatorAddress) - if err != nil { - return nil, err - } - bondDenom := k.BondDenom(ctx) if msg.Amount.Denom != bondDenom { return nil, errorsmod.Wrapf( @@ -248,15 +280,30 @@ func (k msgServer) Delegate(goCtx context.Context, msg *types.MsgDelegate) (*typ // BeginRedelegate defines a method for performing a redelegation of coins from a delegator and source validator to a destination validator func (k msgServer) BeginRedelegate(goCtx context.Context, msg *types.MsgBeginRedelegate) (*types.MsgBeginRedelegateResponse, error) { - ctx := sdk.UnwrapSDKContext(goCtx) valSrcAddr, err := sdk.ValAddressFromBech32(msg.ValidatorSrcAddress) if err != nil { - return nil, err + return nil, sdkerrors.ErrInvalidAddress.Wrapf("invalid source validator address: %s", err) } - delegatorAddress, err := sdk.AccAddressFromBech32(msg.DelegatorAddress) + + valDstAddr, err := sdk.ValAddressFromBech32(msg.ValidatorDstAddress) if err != nil { - return nil, err + return nil, sdkerrors.ErrInvalidAddress.Wrapf("invalid destination validator address: %s", err) + } + + delegatorAddress, err := k.authKeeper.StringToBytes(msg.DelegatorAddress) + if err != nil { + return nil, sdkerrors.ErrInvalidAddress.Wrapf("invalid delegator address: %s", err) + } + + if !msg.Amount.IsValid() || !msg.Amount.Amount.IsPositive() { + return nil, errorsmod.Wrap( + sdkerrors.ErrInvalidRequest, + "invalid shares amount", + ) } + + ctx := sdk.UnwrapSDKContext(goCtx) + shares, err := k.ValidateUnbondAmount( ctx, delegatorAddress, valSrcAddr, msg.Amount.Amount, ) @@ -271,11 +318,6 @@ func (k msgServer) BeginRedelegate(goCtx context.Context, msg *types.MsgBeginRed ) } - valDstAddr, err := sdk.ValAddressFromBech32(msg.ValidatorDstAddress) - if err != nil { - return nil, err - } - completionTime, err := k.BeginRedelegation( ctx, delegatorAddress, valSrcAddr, valDstAddr, shares, ) @@ -311,16 +353,25 @@ func (k msgServer) BeginRedelegate(goCtx context.Context, msg *types.MsgBeginRed // Undelegate defines a method for performing an undelegation from a delegate and a validator func (k msgServer) Undelegate(goCtx context.Context, msg *types.MsgUndelegate) (*types.MsgUndelegateResponse, error) { - ctx := sdk.UnwrapSDKContext(goCtx) - addr, err := sdk.ValAddressFromBech32(msg.ValidatorAddress) if err != nil { - return nil, err + return nil, sdkerrors.ErrInvalidAddress.Wrapf("invalid validator address: %s", err) } - delegatorAddress, err := sdk.AccAddressFromBech32(msg.DelegatorAddress) + + delegatorAddress, err := k.authKeeper.StringToBytes(msg.DelegatorAddress) if err != nil { - return nil, err + return nil, sdkerrors.ErrInvalidAddress.Wrapf("invalid delegator address: %s", err) } + + if !msg.Amount.IsValid() || !msg.Amount.Amount.IsPositive() { + return nil, errorsmod.Wrap( + sdkerrors.ErrInvalidRequest, + "invalid shares amount", + ) + } + + ctx := sdk.UnwrapSDKContext(goCtx) + shares, err := k.ValidateUnbondAmount( ctx, delegatorAddress, addr, msg.Amount.Amount, ) @@ -371,18 +422,32 @@ func (k msgServer) Undelegate(goCtx context.Context, msg *types.MsgUndelegate) ( // CancelUnbondingDelegation defines a method for canceling the unbonding delegation // and delegate back to the validator. func (k msgServer) CancelUnbondingDelegation(goCtx context.Context, msg *types.MsgCancelUnbondingDelegation) (*types.MsgCancelUnbondingDelegationResponse, error) { - ctx := sdk.UnwrapSDKContext(goCtx) - valAddr, err := sdk.ValAddressFromBech32(msg.ValidatorAddress) if err != nil { - return nil, err + return nil, sdkerrors.ErrInvalidAddress.Wrapf("invalid validator address: %s", err) } - delegatorAddress, err := sdk.AccAddressFromBech32(msg.DelegatorAddress) + delegatorAddress, err := k.authKeeper.StringToBytes(msg.DelegatorAddress) if err != nil { - return nil, err + return nil, sdkerrors.ErrInvalidAddress.Wrapf("invalid delegator address: %s", err) } + if !msg.Amount.IsValid() || !msg.Amount.Amount.IsPositive() { + return nil, errorsmod.Wrap( + sdkerrors.ErrInvalidRequest, + "invalid amount", + ) + } + + if msg.CreationHeight <= 0 { + return nil, errorsmod.Wrap( + sdkerrors.ErrInvalidRequest, + "invalid height", + ) + } + + ctx := sdk.UnwrapSDKContext(goCtx) + bondDenom := k.BondDenom(ctx) if msg.Amount.Denom != bondDenom { return nil, errorsmod.Wrapf( @@ -476,12 +541,16 @@ func (k msgServer) CancelUnbondingDelegation(goCtx context.Context, msg *types.M } func (k msgServer) UpdateParams(goCtx context.Context, msg *types.MsgUpdateParams) (*types.MsgUpdateParamsResponse, error) { - ctx := sdk.UnwrapSDKContext(goCtx) - if k.authority != msg.Authority { return nil, errorsmod.Wrapf(govtypes.ErrInvalidSigner, "invalid authority; expected %s, got %s", k.authority, msg.Authority) } + if err := msg.Params.Validate(); err != nil { + return nil, err + } + + ctx := sdk.UnwrapSDKContext(goCtx) + // store params if err := k.SetParams(ctx, msg.Params); err != nil { return nil, err diff --git a/x/staking/keeper/msg_server_test.go b/x/staking/keeper/msg_server_test.go index 87a7dff90936..30cf6e6b963c 100644 --- a/x/staking/keeper/msg_server_test.go +++ b/x/staking/keeper/msg_server_test.go @@ -2,11 +2,998 @@ package keeper_test import ( "testing" + "time" "cosmossdk.io/math" + + "github.com/golang/mock/gomock" + + codectypes "github.com/cosmos/cosmos-sdk/codec/types" + "github.com/cosmos/cosmos-sdk/crypto/keys/ed25519" + simtestutil "github.com/cosmos/cosmos-sdk/testutil/sims" + sdk "github.com/cosmos/cosmos-sdk/types" stakingtypes "github.com/cosmos/cosmos-sdk/x/staking/types" ) +var ( + PKS = simtestutil.CreateTestPubKeys(3) + Addr = sdk.AccAddress(PKS[0].Address()) + ValAddr = sdk.ValAddress(Addr) +) + +func (s *KeeperTestSuite) execExpectCalls() { + s.accountKeeper.EXPECT().StringToBytes(Addr.String()).Return(Addr, nil).AnyTimes() + s.accountKeeper.EXPECT().BytesToString(Addr).Return(Addr.String(), nil).AnyTimes() + s.bankKeeper.EXPECT().DelegateCoinsFromAccountToModule(gomock.Any(), Addr, stakingtypes.NotBondedPoolName, gomock.Any()).AnyTimes() +} + +func (s *KeeperTestSuite) TestMsgCreateValidator() { + ctx, msgServer := s.ctx, s.msgServer + require := s.Require() + s.execExpectCalls() + + pk1 := ed25519.GenPrivKey().PubKey() + require.NotNil(pk1) + + pubkey, err := codectypes.NewAnyWithValue(pk1) + require.NoError(err) + + testCases := []struct { + name string + input *stakingtypes.MsgCreateValidator + expErr bool + expErrMsg string + }{ + { + name: "empty description", + input: &stakingtypes.MsgCreateValidator{ + Description: stakingtypes.Description{}, + Commission: stakingtypes.CommissionRates{ + Rate: sdk.NewDecWithPrec(5, 1), + MaxRate: sdk.NewDecWithPrec(5, 1), + MaxChangeRate: math.LegacyNewDec(0), + }, + MinSelfDelegation: math.NewInt(1), + DelegatorAddress: Addr.String(), + ValidatorAddress: ValAddr.String(), + Pubkey: pubkey, + Value: sdk.NewInt64Coin("stake", 10000), + }, + expErr: true, + expErrMsg: "empty description", + }, + { + name: "invalid validator address", + input: &stakingtypes.MsgCreateValidator{ + Description: stakingtypes.Description{ + Moniker: "NewValidator", + }, + Commission: stakingtypes.CommissionRates{ + Rate: sdk.NewDecWithPrec(5, 1), + MaxRate: sdk.NewDecWithPrec(5, 1), + MaxChangeRate: math.LegacyNewDec(0), + }, + MinSelfDelegation: math.NewInt(1), + DelegatorAddress: Addr.String(), + ValidatorAddress: sdk.AccAddress([]byte("invalid")).String(), + Pubkey: pubkey, + Value: sdk.NewInt64Coin("stake", 10000), + }, + expErr: true, + expErrMsg: "invalid validator address", + }, + { + name: "empty validator pubkey", + input: &stakingtypes.MsgCreateValidator{ + Description: stakingtypes.Description{ + Moniker: "NewValidator", + }, + Commission: stakingtypes.CommissionRates{ + Rate: sdk.NewDecWithPrec(5, 1), + MaxRate: sdk.NewDecWithPrec(5, 1), + MaxChangeRate: math.LegacyNewDec(0), + }, + MinSelfDelegation: math.NewInt(1), + DelegatorAddress: Addr.String(), + ValidatorAddress: ValAddr.String(), + Pubkey: nil, + Value: sdk.NewInt64Coin("stake", 10000), + }, + expErr: true, + expErrMsg: "empty validator public key", + }, + { + name: "empty delegation amount", + input: &stakingtypes.MsgCreateValidator{ + Description: stakingtypes.Description{ + Moniker: "NewValidator", + }, + Commission: stakingtypes.CommissionRates{ + Rate: sdk.NewDecWithPrec(5, 1), + MaxRate: sdk.NewDecWithPrec(5, 1), + MaxChangeRate: math.LegacyNewDec(0), + }, + MinSelfDelegation: math.NewInt(1), + DelegatorAddress: Addr.String(), + ValidatorAddress: ValAddr.String(), + Pubkey: pubkey, + Value: sdk.NewInt64Coin("stake", 0), + }, + expErr: true, + expErrMsg: "invalid delegation amount", + }, + { + name: "nil delegation amount", + input: &stakingtypes.MsgCreateValidator{ + Description: stakingtypes.Description{ + Moniker: "NewValidator", + }, + Commission: stakingtypes.CommissionRates{ + Rate: sdk.NewDecWithPrec(5, 1), + MaxRate: sdk.NewDecWithPrec(5, 1), + MaxChangeRate: math.LegacyNewDec(0), + }, + MinSelfDelegation: math.NewInt(1), + DelegatorAddress: Addr.String(), + ValidatorAddress: ValAddr.String(), + Pubkey: pubkey, + Value: sdk.Coin{}, + }, + expErr: true, + expErrMsg: "invalid delegation amount", + }, + { + name: "zero minimum self delegation", + input: &stakingtypes.MsgCreateValidator{ + Description: stakingtypes.Description{ + Moniker: "NewValidator", + }, + Commission: stakingtypes.CommissionRates{ + Rate: sdk.NewDecWithPrec(5, 1), + MaxRate: sdk.NewDecWithPrec(5, 1), + MaxChangeRate: math.LegacyNewDec(0), + }, + MinSelfDelegation: math.NewInt(0), + DelegatorAddress: Addr.String(), + ValidatorAddress: ValAddr.String(), + Pubkey: pubkey, + Value: sdk.NewInt64Coin("stake", 10000), + }, + expErr: true, + expErrMsg: "minimum self delegation must be a positive integer", + }, + { + name: "negative minimum self delegation", + input: &stakingtypes.MsgCreateValidator{ + Description: stakingtypes.Description{ + Moniker: "NewValidator", + }, + Commission: stakingtypes.CommissionRates{ + Rate: sdk.NewDecWithPrec(5, 1), + MaxRate: sdk.NewDecWithPrec(5, 1), + MaxChangeRate: math.LegacyNewDec(0), + }, + MinSelfDelegation: math.NewInt(-1), + DelegatorAddress: Addr.String(), + ValidatorAddress: ValAddr.String(), + Pubkey: pubkey, + Value: sdk.NewInt64Coin("stake", 10000), + }, + expErr: true, + expErrMsg: "minimum self delegation must be a positive integer", + }, + { + name: "delegation less than minimum self delegation", + input: &stakingtypes.MsgCreateValidator{ + Description: stakingtypes.Description{ + Moniker: "NewValidator", + }, + Commission: stakingtypes.CommissionRates{ + Rate: sdk.NewDecWithPrec(5, 1), + MaxRate: sdk.NewDecWithPrec(5, 1), + MaxChangeRate: math.LegacyNewDec(0), + }, + MinSelfDelegation: math.NewInt(100), + DelegatorAddress: Addr.String(), + ValidatorAddress: ValAddr.String(), + Pubkey: pubkey, + Value: sdk.NewInt64Coin("stake", 10), + }, + expErr: true, + expErrMsg: "validator's self delegation must be greater than their minimum self delegation", + }, + { + name: "valid msg", + input: &stakingtypes.MsgCreateValidator{ + Description: stakingtypes.Description{ + Moniker: "NewValidator", + Identity: "xyz", + Website: "xyz.com", + SecurityContact: "xyz@gmail.com", + Details: "details", + }, + Commission: stakingtypes.CommissionRates{ + Rate: sdk.NewDecWithPrec(5, 1), + MaxRate: sdk.NewDecWithPrec(5, 1), + MaxChangeRate: math.LegacyNewDec(0), + }, + MinSelfDelegation: math.NewInt(1), + DelegatorAddress: Addr.String(), + ValidatorAddress: ValAddr.String(), + Pubkey: pubkey, + Value: sdk.NewInt64Coin("stake", 10000), + }, + expErr: false, + }, + } + for _, tc := range testCases { + tc := tc + s.T().Run(tc.name, func(t *testing.T) { + _, err := msgServer.CreateValidator(ctx, tc.input) + if tc.expErr { + require.Error(err) + require.Contains(err.Error(), tc.expErrMsg) + } else { + require.NoError(err) + } + }) + } +} + +func (s *KeeperTestSuite) TestMsgEditValidator() { + ctx, msgServer := s.ctx, s.msgServer + require := s.Require() + s.execExpectCalls() + + // create new context with updated block time + newCtx := ctx.WithBlockTime(ctx.BlockTime().AddDate(0, 0, 1)) + + pk := ed25519.GenPrivKey().PubKey() + require.NotNil(pk) + + comm := stakingtypes.NewCommissionRates(math.LegacyNewDec(0), math.LegacyNewDec(0), math.LegacyNewDec(0)) + msg, err := stakingtypes.NewMsgCreateValidator(ValAddr, pk, sdk.NewCoin("stake", sdk.NewInt(10)), stakingtypes.Description{Moniker: "NewVal"}, comm, sdk.OneInt()) + require.NoError(err) + + res, err := msgServer.CreateValidator(ctx, msg) + require.NoError(err) + require.NotNil(res) + + newRate := math.LegacyZeroDec() + invalidRate := sdk.NewDec(2) + + lowSelfDel := math.OneInt() + highSelfDel := math.NewInt(100) + negSelfDel := math.NewInt(-1) + newSelfDel := math.NewInt(3) + + testCases := []struct { + name string + ctx sdk.Context + input *stakingtypes.MsgEditValidator + expErr bool + expErrMsg string + }{ + { + name: "invalid validator", + ctx: newCtx, + input: &stakingtypes.MsgEditValidator{ + Description: stakingtypes.Description{ + Moniker: "TestValidator", + }, + ValidatorAddress: sdk.AccAddress([]byte("invalid")).String(), + CommissionRate: &newRate, + MinSelfDelegation: &newSelfDel, + }, + expErr: true, + expErrMsg: "invalid validator address", + }, + { + name: "empty description", + ctx: newCtx, + input: &stakingtypes.MsgEditValidator{ + Description: stakingtypes.Description{}, + ValidatorAddress: ValAddr.String(), + CommissionRate: &newRate, + MinSelfDelegation: &newSelfDel, + }, + expErr: true, + expErrMsg: "empty description", + }, + { + name: "negative self delegation", + ctx: newCtx, + input: &stakingtypes.MsgEditValidator{ + Description: stakingtypes.Description{ + Moniker: "TestValidator", + }, + ValidatorAddress: ValAddr.String(), + CommissionRate: &newRate, + MinSelfDelegation: &negSelfDel, + }, + expErr: true, + expErrMsg: "minimum self delegation must be a positive integer", + }, + { + name: "invalid commission rate", + ctx: newCtx, + input: &stakingtypes.MsgEditValidator{ + Description: stakingtypes.Description{ + Moniker: "TestValidator", + }, + ValidatorAddress: ValAddr.String(), + CommissionRate: &invalidRate, + MinSelfDelegation: &newSelfDel, + }, + expErr: true, + expErrMsg: "commission rate must be between 0 and 1 (inclusive)", + }, + { + name: "validator does not exist", + ctx: newCtx, + input: &stakingtypes.MsgEditValidator{ + Description: stakingtypes.Description{ + Moniker: "TestValidator", + }, + ValidatorAddress: sdk.ValAddress([]byte("val")).String(), + CommissionRate: &newRate, + MinSelfDelegation: &newSelfDel, + }, + expErr: true, + expErrMsg: "validator does not exist", + }, + { + name: "change commmission rate in <24hrs", + ctx: ctx, + input: &stakingtypes.MsgEditValidator{ + Description: stakingtypes.Description{ + Moniker: "TestValidator", + }, + ValidatorAddress: ValAddr.String(), + CommissionRate: &newRate, + MinSelfDelegation: &newSelfDel, + }, + expErr: true, + expErrMsg: "commission cannot be changed more than once in 24h", + }, + { + name: "minimum self delegation cannot decrease", + ctx: newCtx, + input: &stakingtypes.MsgEditValidator{ + Description: stakingtypes.Description{ + Moniker: "TestValidator", + }, + ValidatorAddress: ValAddr.String(), + CommissionRate: &newRate, + MinSelfDelegation: &lowSelfDel, + }, + expErr: true, + expErrMsg: "minimum self delegation cannot be decrease", + }, + { + name: "validator self-delegation must be greater than min self delegation", + ctx: newCtx, + input: &stakingtypes.MsgEditValidator{ + Description: stakingtypes.Description{ + Moniker: "TestValidator", + }, + ValidatorAddress: ValAddr.String(), + CommissionRate: &newRate, + MinSelfDelegation: &highSelfDel, + }, + expErr: true, + expErrMsg: "validator's self delegation must be greater than their minimum self delegation", + }, + { + name: "valid msg", + ctx: newCtx, + input: &stakingtypes.MsgEditValidator{ + Description: stakingtypes.Description{ + Moniker: "TestValidator", + Identity: "abc", + Website: "abc.com", + SecurityContact: "abc@gmail.com", + Details: "newDetails", + }, + ValidatorAddress: ValAddr.String(), + CommissionRate: &newRate, + MinSelfDelegation: &newSelfDel, + }, + expErr: false, + }, + } + for _, tc := range testCases { + tc := tc + s.T().Run(tc.name, func(t *testing.T) { + _, err := msgServer.EditValidator(tc.ctx, tc.input) + if tc.expErr { + require.Error(err) + require.Contains(err.Error(), tc.expErrMsg) + } else { + require.NoError(err) + } + }) + } +} + +func (s *KeeperTestSuite) TestMsgDelegate() { + ctx, keeper, msgServer := s.ctx, s.stakingKeeper, s.msgServer + require := s.Require() + s.execExpectCalls() + + pk := ed25519.GenPrivKey().PubKey() + require.NotNil(pk) + + comm := stakingtypes.NewCommissionRates(math.LegacyNewDec(0), math.LegacyNewDec(0), math.LegacyNewDec(0)) + + msg, err := stakingtypes.NewMsgCreateValidator(ValAddr, pk, sdk.NewCoin("stake", sdk.NewInt(10)), stakingtypes.Description{Moniker: "NewVal"}, comm, sdk.OneInt()) + require.NoError(err) + + res, err := msgServer.CreateValidator(ctx, msg) + require.NoError(err) + require.NotNil(res) + + testCases := []struct { + name string + input *stakingtypes.MsgDelegate + expErr bool + expErrMsg string + }{ + { + name: "invalid validator", + input: &stakingtypes.MsgDelegate{ + DelegatorAddress: Addr.String(), + ValidatorAddress: sdk.AccAddress([]byte("invalid")).String(), + Amount: sdk.Coin{Denom: sdk.DefaultBondDenom, Amount: keeper.TokensFromConsensusPower(s.ctx, int64(100))}, + }, + expErr: true, + expErrMsg: "invalid validator address", + }, + { + name: "empty delegator", + input: &stakingtypes.MsgDelegate{ + DelegatorAddress: "", + ValidatorAddress: ValAddr.String(), + Amount: sdk.Coin{Denom: sdk.DefaultBondDenom, Amount: keeper.TokensFromConsensusPower(s.ctx, int64(100))}, + }, + expErr: true, + expErrMsg: "invalid delegator address: empty address string is not allowed", + }, + { + name: "invalid delegator", + input: &stakingtypes.MsgDelegate{ + DelegatorAddress: "invalid", + ValidatorAddress: ValAddr.String(), + Amount: sdk.Coin{Denom: sdk.DefaultBondDenom, Amount: keeper.TokensFromConsensusPower(s.ctx, int64(100))}, + }, + expErr: true, + expErrMsg: "invalid delegator address: invalid bech32 string", + }, + { + name: "validator does not exist", + input: &stakingtypes.MsgDelegate{ + DelegatorAddress: Addr.String(), + ValidatorAddress: sdk.ValAddress([]byte("val")).String(), + Amount: sdk.Coin{Denom: sdk.DefaultBondDenom, Amount: keeper.TokensFromConsensusPower(s.ctx, int64(100))}, + }, + expErr: true, + expErrMsg: "validator does not exist", + }, + { + name: "zero amount", + input: &stakingtypes.MsgDelegate{ + DelegatorAddress: Addr.String(), + ValidatorAddress: ValAddr.String(), + Amount: sdk.Coin{Denom: sdk.DefaultBondDenom, Amount: keeper.TokensFromConsensusPower(s.ctx, int64(0))}, + }, + expErr: true, + expErrMsg: "invalid delegation amount", + }, + { + name: "negative amount", + input: &stakingtypes.MsgDelegate{ + DelegatorAddress: Addr.String(), + ValidatorAddress: ValAddr.String(), + Amount: sdk.Coin{Denom: sdk.DefaultBondDenom, Amount: keeper.TokensFromConsensusPower(s.ctx, int64(-1))}, + }, + expErr: true, + expErrMsg: "invalid delegation amount", + }, + { + name: "invalid BondDenom", + input: &stakingtypes.MsgDelegate{ + DelegatorAddress: Addr.String(), + ValidatorAddress: ValAddr.String(), + Amount: sdk.Coin{Denom: "test", Amount: keeper.TokensFromConsensusPower(s.ctx, int64(100))}, + }, + expErr: true, + expErrMsg: "invalid coin denomination", + }, + { + name: "valid msg", + input: &stakingtypes.MsgDelegate{ + DelegatorAddress: Addr.String(), + ValidatorAddress: ValAddr.String(), + Amount: sdk.Coin{Denom: sdk.DefaultBondDenom, Amount: keeper.TokensFromConsensusPower(s.ctx, int64(100))}, + }, + expErr: false, + }, + } + + for _, tc := range testCases { + tc := tc + s.T().Run(tc.name, func(t *testing.T) { + _, err := msgServer.Delegate(ctx, tc.input) + if tc.expErr { + require.Error(err) + require.Contains(err.Error(), tc.expErrMsg) + } else { + require.NoError(err) + } + }) + } +} + +func (s *KeeperTestSuite) TestMsgBeginRedelegate() { + ctx, keeper, msgServer := s.ctx, s.stakingKeeper, s.msgServer + require := s.Require() + s.execExpectCalls() + + srcValAddr := ValAddr + addr2 := sdk.AccAddress(PKS[1].Address()) + dstValAddr := sdk.ValAddress(addr2) + + pk := ed25519.GenPrivKey().PubKey() + require.NotNil(pk) + dstPk := ed25519.GenPrivKey().PubKey() + require.NotNil(dstPk) + + comm := stakingtypes.NewCommissionRates(math.LegacyNewDec(0), math.LegacyNewDec(0), math.LegacyNewDec(0)) + amt := sdk.Coin{Denom: sdk.DefaultBondDenom, Amount: keeper.TokensFromConsensusPower(s.ctx, int64(100))} + + msg, err := stakingtypes.NewMsgCreateValidator(srcValAddr, pk, amt, stakingtypes.Description{Moniker: "NewVal"}, comm, sdk.OneInt()) + require.NoError(err) + res, err := msgServer.CreateValidator(ctx, msg) + require.NoError(err) + require.NotNil(res) + + s.accountKeeper.EXPECT().StringToBytes(addr2.String()).Return(addr2, nil).AnyTimes() + s.accountKeeper.EXPECT().BytesToString(addr2).Return(addr2.String(), nil).AnyTimes() + s.bankKeeper.EXPECT().DelegateCoinsFromAccountToModule(gomock.Any(), addr2, stakingtypes.NotBondedPoolName, gomock.Any()).AnyTimes() + + msg, err = stakingtypes.NewMsgCreateValidator(dstValAddr, dstPk, amt, stakingtypes.Description{Moniker: "NewVal"}, comm, sdk.OneInt()) + require.NoError(err) + + res, err = msgServer.CreateValidator(ctx, msg) + require.NoError(err) + require.NotNil(res) + + shares := math.LegacyNewDec(100) + del := stakingtypes.NewDelegation(Addr, srcValAddr, shares) + keeper.SetDelegation(ctx, del) + _, found := keeper.GetDelegation(ctx, Addr, srcValAddr) + require.True(found) + + testCases := []struct { + name string + input *stakingtypes.MsgBeginRedelegate + expErr bool + expErrMsg string + }{ + { + name: "invalid source validator", + input: &stakingtypes.MsgBeginRedelegate{ + DelegatorAddress: Addr.String(), + ValidatorSrcAddress: sdk.AccAddress([]byte("invalid")).String(), + ValidatorDstAddress: dstValAddr.String(), + Amount: sdk.NewCoin(sdk.DefaultBondDenom, shares.RoundInt()), + }, + expErr: true, + expErrMsg: "invalid source validator address", + }, + { + name: "empty delegator", + input: &stakingtypes.MsgBeginRedelegate{ + DelegatorAddress: "", + ValidatorSrcAddress: srcValAddr.String(), + ValidatorDstAddress: dstValAddr.String(), + Amount: sdk.Coin{Denom: sdk.DefaultBondDenom, Amount: keeper.TokensFromConsensusPower(s.ctx, int64(100))}, + }, + expErr: true, + expErrMsg: "invalid delegator address: empty address string is not allowed", + }, + { + name: "invalid delegator", + input: &stakingtypes.MsgBeginRedelegate{ + DelegatorAddress: "invalid", + ValidatorSrcAddress: srcValAddr.String(), + ValidatorDstAddress: dstValAddr.String(), + Amount: sdk.Coin{Denom: sdk.DefaultBondDenom, Amount: keeper.TokensFromConsensusPower(s.ctx, int64(100))}, + }, + expErr: true, + expErrMsg: "invalid delegator address: invalid bech32 string", + }, + { + name: "invalid destination validator", + input: &stakingtypes.MsgBeginRedelegate{ + DelegatorAddress: Addr.String(), + ValidatorSrcAddress: srcValAddr.String(), + ValidatorDstAddress: sdk.AccAddress([]byte("invalid")).String(), + Amount: sdk.NewCoin(sdk.DefaultBondDenom, shares.RoundInt()), + }, + expErr: true, + expErrMsg: "invalid destination validator address", + }, + { + name: "validator does not exist", + input: &stakingtypes.MsgBeginRedelegate{ + DelegatorAddress: Addr.String(), + ValidatorSrcAddress: sdk.ValAddress([]byte("invalid")).String(), + ValidatorDstAddress: dstValAddr.String(), + Amount: sdk.NewCoin(sdk.DefaultBondDenom, shares.RoundInt()), + }, + expErr: true, + expErrMsg: "validator does not exist", + }, + { + name: "self redelegation", + input: &stakingtypes.MsgBeginRedelegate{ + DelegatorAddress: Addr.String(), + ValidatorSrcAddress: srcValAddr.String(), + ValidatorDstAddress: srcValAddr.String(), + Amount: sdk.NewCoin(sdk.DefaultBondDenom, shares.RoundInt()), + }, + expErr: true, + expErrMsg: "cannot redelegate to the same validator", + }, + { + name: "amount greater than delegated shares amount", + input: &stakingtypes.MsgBeginRedelegate{ + DelegatorAddress: Addr.String(), + ValidatorSrcAddress: srcValAddr.String(), + ValidatorDstAddress: dstValAddr.String(), + Amount: sdk.NewCoin(sdk.DefaultBondDenom, math.NewInt(101)), + }, + expErr: true, + expErrMsg: "invalid shares amount", + }, + { + name: "zero amount", + input: &stakingtypes.MsgBeginRedelegate{ + DelegatorAddress: Addr.String(), + ValidatorSrcAddress: srcValAddr.String(), + ValidatorDstAddress: dstValAddr.String(), + Amount: sdk.NewCoin(sdk.DefaultBondDenom, math.NewInt(0)), + }, + expErr: true, + expErrMsg: "invalid shares amount", + }, + { + name: "invalid coin denom", + input: &stakingtypes.MsgBeginRedelegate{ + DelegatorAddress: Addr.String(), + ValidatorSrcAddress: srcValAddr.String(), + ValidatorDstAddress: dstValAddr.String(), + Amount: sdk.NewCoin("test", shares.RoundInt()), + }, + expErr: true, + expErrMsg: "invalid coin denomination", + }, + { + name: "valid msg", + input: &stakingtypes.MsgBeginRedelegate{ + DelegatorAddress: Addr.String(), + ValidatorSrcAddress: srcValAddr.String(), + ValidatorDstAddress: dstValAddr.String(), + Amount: sdk.NewCoin(sdk.DefaultBondDenom, shares.RoundInt()), + }, + expErr: false, + }, + } + + for _, tc := range testCases { + tc := tc + s.T().Run(tc.name, func(t *testing.T) { + _, err := msgServer.BeginRedelegate(ctx, tc.input) + if tc.expErr { + require.Error(err) + require.Contains(err.Error(), tc.expErrMsg) + } else { + require.NoError(err) + } + }) + } +} + +func (s *KeeperTestSuite) TestMsgUndelegate() { + ctx, keeper, msgServer := s.ctx, s.stakingKeeper, s.msgServer + require := s.Require() + s.execExpectCalls() + + pk := ed25519.GenPrivKey().PubKey() + require.NotNil(pk) + + comm := stakingtypes.NewCommissionRates(math.LegacyNewDec(0), math.LegacyNewDec(0), math.LegacyNewDec(0)) + amt := sdk.Coin{Denom: sdk.DefaultBondDenom, Amount: keeper.TokensFromConsensusPower(s.ctx, int64(100))} + + msg, err := stakingtypes.NewMsgCreateValidator(ValAddr, pk, amt, stakingtypes.Description{Moniker: "NewVal"}, comm, sdk.OneInt()) + require.NoError(err) + res, err := msgServer.CreateValidator(ctx, msg) + require.NoError(err) + require.NotNil(res) + + shares := math.LegacyNewDec(100) + del := stakingtypes.NewDelegation(Addr, ValAddr, shares) + keeper.SetDelegation(ctx, del) + _, found := keeper.GetDelegation(ctx, Addr, ValAddr) + require.True(found) + + testCases := []struct { + name string + input *stakingtypes.MsgUndelegate + expErr bool + expErrMsg string + }{ + { + name: "invalid validator", + input: &stakingtypes.MsgUndelegate{ + DelegatorAddress: Addr.String(), + ValidatorAddress: sdk.AccAddress([]byte("invalid")).String(), + Amount: sdk.NewCoin(sdk.DefaultBondDenom, shares.RoundInt()), + }, + expErr: true, + expErrMsg: "invalid validator address", + }, + { + name: "empty delegator", + input: &stakingtypes.MsgUndelegate{ + DelegatorAddress: "", + ValidatorAddress: ValAddr.String(), + Amount: sdk.Coin{Denom: sdk.DefaultBondDenom, Amount: shares.RoundInt()}, + }, + expErr: true, + expErrMsg: "invalid delegator address: empty address string is not allowed", + }, + { + name: "invalid delegator", + input: &stakingtypes.MsgUndelegate{ + DelegatorAddress: "invalid", + ValidatorAddress: ValAddr.String(), + Amount: sdk.Coin{Denom: sdk.DefaultBondDenom, Amount: shares.RoundInt()}, + }, + expErr: true, + expErrMsg: "invalid delegator address: invalid bech32 string", + }, + { + name: "validator does not exist", + input: &stakingtypes.MsgUndelegate{ + DelegatorAddress: Addr.String(), + ValidatorAddress: sdk.ValAddress([]byte("invalid")).String(), + Amount: sdk.NewCoin(sdk.DefaultBondDenom, shares.RoundInt()), + }, + expErr: true, + expErrMsg: "validator does not exist", + }, + { + name: "amount greater than delegated shares amount", + input: &stakingtypes.MsgUndelegate{ + DelegatorAddress: Addr.String(), + ValidatorAddress: ValAddr.String(), + Amount: sdk.NewCoin(sdk.DefaultBondDenom, math.NewInt(101)), + }, + expErr: true, + expErrMsg: "invalid shares amount", + }, + { + name: "zero amount", + input: &stakingtypes.MsgUndelegate{ + DelegatorAddress: Addr.String(), + ValidatorAddress: ValAddr.String(), + Amount: sdk.NewCoin(sdk.DefaultBondDenom, math.NewInt(0)), + }, + expErr: true, + expErrMsg: "invalid shares amount", + }, + { + name: "invalid coin denom", + input: &stakingtypes.MsgUndelegate{ + DelegatorAddress: Addr.String(), + ValidatorAddress: ValAddr.String(), + Amount: sdk.NewCoin("test", shares.RoundInt()), + }, + expErr: true, + expErrMsg: "invalid coin denomination", + }, + { + name: "valid msg", + input: &stakingtypes.MsgUndelegate{ + DelegatorAddress: Addr.String(), + ValidatorAddress: ValAddr.String(), + Amount: sdk.NewCoin(sdk.DefaultBondDenom, shares.RoundInt()), + }, + expErr: false, + }, + } + + for _, tc := range testCases { + tc := tc + s.T().Run(tc.name, func(t *testing.T) { + _, err := msgServer.Undelegate(ctx, tc.input) + if tc.expErr { + require.Error(err) + require.Contains(err.Error(), tc.expErrMsg) + } else { + require.NoError(err) + } + }) + } +} + +func (s *KeeperTestSuite) TestMsgCancelUnbondingDelegation() { + ctx, keeper, msgServer := s.ctx, s.stakingKeeper, s.msgServer + require := s.Require() + + pk := ed25519.GenPrivKey().PubKey() + require.NotNil(pk) + + comm := stakingtypes.NewCommissionRates(math.LegacyNewDec(0), math.LegacyNewDec(0), math.LegacyNewDec(0)) + amt := sdk.Coin{Denom: sdk.DefaultBondDenom, Amount: keeper.TokensFromConsensusPower(s.ctx, int64(100))} + + s.accountKeeper.EXPECT().StringToBytes(Addr.String()).Return(Addr, nil).AnyTimes() + s.accountKeeper.EXPECT().BytesToString(Addr).Return(Addr.String(), nil).AnyTimes() + + s.bankKeeper.EXPECT().DelegateCoinsFromAccountToModule(gomock.Any(), Addr, stakingtypes.NotBondedPoolName, gomock.Any()).AnyTimes() + + msg, err := stakingtypes.NewMsgCreateValidator(ValAddr, pk, amt, stakingtypes.Description{Moniker: "NewVal"}, comm, sdk.OneInt()) + require.NoError(err) + res, err := msgServer.CreateValidator(ctx, msg) + require.NoError(err) + require.NotNil(res) + + shares := math.LegacyNewDec(100) + del := stakingtypes.NewDelegation(Addr, ValAddr, shares) + keeper.SetDelegation(ctx, del) + resDel, found := keeper.GetDelegation(ctx, Addr, ValAddr) + require.True(found) + require.Equal(del, resDel) + + ubd := stakingtypes.NewUnbondingDelegation(Addr, ValAddr, 10, ctx.BlockTime().Add(time.Minute*10), shares.RoundInt(), 0) + keeper.SetUnbondingDelegation(ctx, ubd) + resUnbond, found := keeper.GetUnbondingDelegation(ctx, Addr, ValAddr) + require.True(found) + require.Equal(ubd, resUnbond) + + testCases := []struct { + name string + input *stakingtypes.MsgCancelUnbondingDelegation + expErr bool + expErrMsg string + }{ + { + name: "invalid validator", + input: &stakingtypes.MsgCancelUnbondingDelegation{ + DelegatorAddress: Addr.String(), + ValidatorAddress: sdk.AccAddress([]byte("invalid")).String(), + Amount: sdk.NewCoin(sdk.DefaultBondDenom, shares.RoundInt()), + CreationHeight: 10, + }, + expErr: true, + expErrMsg: "invalid validator address", + }, + { + name: "empty delegator", + input: &stakingtypes.MsgCancelUnbondingDelegation{ + DelegatorAddress: "", + ValidatorAddress: ValAddr.String(), + Amount: sdk.NewCoin(sdk.DefaultBondDenom, shares.RoundInt()), + CreationHeight: 10, + }, + expErr: true, + expErrMsg: "invalid delegator address: empty address string is not allowed", + }, + { + name: "invalid delegator", + input: &stakingtypes.MsgCancelUnbondingDelegation{ + DelegatorAddress: "invalid", + ValidatorAddress: ValAddr.String(), + Amount: sdk.NewCoin(sdk.DefaultBondDenom, shares.RoundInt()), + CreationHeight: 10, + }, + expErr: true, + expErrMsg: "invalid delegator address: invalid bech32 string", + }, + { + name: "entry not found at height", + input: &stakingtypes.MsgCancelUnbondingDelegation{ + DelegatorAddress: Addr.String(), + ValidatorAddress: ValAddr.String(), + Amount: sdk.NewCoin(sdk.DefaultBondDenom, shares.RoundInt()), + CreationHeight: 11, + }, + expErr: true, + expErrMsg: "unbonding delegation entry is not found at block height", + }, + { + name: "invalid height", + input: &stakingtypes.MsgCancelUnbondingDelegation{ + DelegatorAddress: Addr.String(), + ValidatorAddress: ValAddr.String(), + Amount: sdk.NewCoin(sdk.DefaultBondDenom, shares.RoundInt()), + CreationHeight: -1, + }, + expErr: true, + expErrMsg: "invalid height", + }, + { + name: "invalid coin", + input: &stakingtypes.MsgCancelUnbondingDelegation{ + DelegatorAddress: Addr.String(), + ValidatorAddress: ValAddr.String(), + Amount: sdk.NewCoin("test", shares.RoundInt()), + CreationHeight: 10, + }, + expErr: true, + expErrMsg: "invalid coin denomination", + }, + { + name: "validator does not exist", + input: &stakingtypes.MsgCancelUnbondingDelegation{ + DelegatorAddress: Addr.String(), + ValidatorAddress: sdk.ValAddress([]byte("invalid")).String(), + Amount: sdk.NewCoin(sdk.DefaultBondDenom, shares.RoundInt()), + CreationHeight: 10, + }, + expErr: true, + expErrMsg: "validator does not exist", + }, + { + name: "amount is greater than balance", + input: &stakingtypes.MsgCancelUnbondingDelegation{ + DelegatorAddress: Addr.String(), + ValidatorAddress: ValAddr.String(), + Amount: sdk.NewCoin(sdk.DefaultBondDenom, sdk.NewInt(101)), + CreationHeight: 10, + }, + expErr: true, + expErrMsg: "amount is greater than the unbonding delegation entry balance", + }, + { + name: "zero amount", + input: &stakingtypes.MsgCancelUnbondingDelegation{ + DelegatorAddress: Addr.String(), + ValidatorAddress: ValAddr.String(), + Amount: sdk.NewCoin(sdk.DefaultBondDenom, sdk.NewInt(0)), + CreationHeight: 10, + }, + expErr: true, + expErrMsg: "invalid amount", + }, + { + name: "valid msg", + input: &stakingtypes.MsgCancelUnbondingDelegation{ + DelegatorAddress: Addr.String(), + ValidatorAddress: ValAddr.String(), + Amount: sdk.NewCoin(sdk.DefaultBondDenom, shares.RoundInt()), + CreationHeight: 10, + }, + expErr: false, + }, + } + + for _, tc := range testCases { + tc := tc + s.T().Run(tc.name, func(t *testing.T) { + _, err := msgServer.CancelUnbondingDelegation(ctx, tc.input) + if tc.expErr { + require.Error(err) + require.Contains(err.Error(), tc.expErrMsg) + } else { + require.NoError(err) + } + }) + } +} + func (s *KeeperTestSuite) TestMsgUpdateParams() { ctx, keeper, msgServer := s.ctx, s.stakingKeeper, s.msgServer require := s.Require() @@ -83,7 +1070,7 @@ func (s *KeeperTestSuite) TestMsgUpdateParams() { expErrMsg: "bond denom cannot be blank", }, { - name: "max validators most be positive", + name: "max validators must be positive", input: &stakingtypes.MsgUpdateParams{ Authority: keeper.GetAuthority(), Params: stakingtypes.Params{ @@ -114,6 +1101,22 @@ func (s *KeeperTestSuite) TestMsgUpdateParams() { expErr: true, expErrMsg: "max entries must be positive", }, + { + name: "negative unbounding time", + input: &stakingtypes.MsgUpdateParams{ + Authority: keeper.GetAuthority(), + Params: stakingtypes.Params{ + UnbondingTime: time.Hour * 24 * 7 * 3 * -1, + MaxEntries: stakingtypes.DefaultMaxEntries, + MaxValidators: stakingtypes.DefaultMaxValidators, + HistoricalEntries: stakingtypes.DefaultHistoricalEntries, + MinCommissionRate: stakingtypes.DefaultMinCommissionRate, + BondDenom: "denom", + }, + }, + expErr: true, + expErrMsg: "unbonding time must be positive", + }, } for _, tc := range testCases { diff --git a/x/staking/keeper/params.go b/x/staking/keeper/params.go index 3e1bb083916e..74316694d9bf 100644 --- a/x/staking/keeper/params.go +++ b/x/staking/keeper/params.go @@ -50,11 +50,8 @@ func (k Keeper) MinCommissionRate(ctx sdk.Context) math.LegacyDec { } // SetParams sets the x/staking module parameters. +// CONTRACT: This method performs no validation of the parameters. func (k Keeper) SetParams(ctx sdk.Context, params types.Params) error { - if err := params.Validate(); err != nil { - return err - } - store := ctx.KVStore(k.storeKey) bz, err := k.cdc.Marshal(¶ms) if err != nil { diff --git a/x/staking/keeper/slash.go b/x/staking/keeper/slash.go index e5b4e1f87e61..3d9dc3e00d08 100644 --- a/x/staking/keeper/slash.go +++ b/x/staking/keeper/slash.go @@ -30,7 +30,7 @@ import ( // // Infraction was committed at the current height or at a past height, // not at a height in the future -func (k Keeper) Slash(ctx sdk.Context, consAddr sdk.ConsAddress, infractionHeight int64, power int64, slashFactor sdk.Dec) math.Int { +func (k Keeper) Slash(ctx sdk.Context, consAddr sdk.ConsAddress, infractionHeight, power int64, slashFactor sdk.Dec) math.Int { logger := k.Logger(ctx) if slashFactor.IsNegative() { @@ -157,7 +157,7 @@ func (k Keeper) Slash(ctx sdk.Context, consAddr sdk.ConsAddress, infractionHeigh } // SlashWithInfractionReason implementation doesn't require the infraction (types.Infraction) to work but is required by Interchain Security. -func (k Keeper) SlashWithInfractionReason(ctx sdk.Context, consAddr sdk.ConsAddress, infractionHeight int64, power int64, slashFactor sdk.Dec, _ types.Infraction) math.Int { +func (k Keeper) SlashWithInfractionReason(ctx sdk.Context, consAddr sdk.ConsAddress, infractionHeight, power int64, slashFactor sdk.Dec, _ types.Infraction) math.Int { return k.Slash(ctx, consAddr, infractionHeight, power, slashFactor) } @@ -271,7 +271,10 @@ func (k Keeper) SlashRedelegation(ctx sdk.Context, srcValidator types.Validator, panic(err) } - delegatorAddress := sdk.MustAccAddressFromBech32(redelegation.DelegatorAddress) + delegatorAddress, err := k.authKeeper.StringToBytes(redelegation.DelegatorAddress) + if err != nil { + panic(err) + } delegation, found := k.GetDelegation(ctx, delegatorAddress, valDstAddr) if !found { diff --git a/x/staking/keeper/unbonding.go b/x/staking/keeper/unbonding.go index c1e8a9443f94..bccbe3e14fdd 100644 --- a/x/staking/keeper/unbonding.go +++ b/x/staking/keeper/unbonding.go @@ -128,7 +128,10 @@ func (k Keeper) GetValidatorByUnbondingID(ctx sdk.Context, id uint64) (val types // Note, it does not set the unbonding delegation itself, use SetUnbondingDelegation(ctx, ubd) for that func (k Keeper) SetUnbondingDelegationByUnbondingID(ctx sdk.Context, ubd types.UnbondingDelegation, id uint64) { store := ctx.KVStore(k.storeKey) - delAddr := sdk.MustAccAddressFromBech32(ubd.DelegatorAddress) + delAddr, err := k.authKeeper.StringToBytes(ubd.DelegatorAddress) + if err != nil { + panic(err) + } valAddr, err := sdk.ValAddressFromBech32(ubd.ValidatorAddress) if err != nil { panic(err) @@ -146,7 +149,10 @@ func (k Keeper) SetUnbondingDelegationByUnbondingID(ctx sdk.Context, ubd types.U func (k Keeper) SetRedelegationByUnbondingID(ctx sdk.Context, red types.Redelegation, id uint64) { store := ctx.KVStore(k.storeKey) - delAddr := sdk.MustAccAddressFromBech32(red.DelegatorAddress) + delAddr, err := k.authKeeper.StringToBytes(red.DelegatorAddress) + if err != nil { + panic(err) + } valSrcAddr, err := sdk.ValAddressFromBech32(red.ValidatorSrcAddress) if err != nil { @@ -260,7 +266,7 @@ func (k Keeper) unbondingDelegationEntryCanComplete(ctx sdk.Context, id uint64) // Check if entry is matured. if !ubd.Entries[i].OnHold() && ubd.Entries[i].IsMature(ctx.BlockHeader().Time) { // If matured, complete it. - delegatorAddress, err := sdk.AccAddressFromBech32(ubd.DelegatorAddress) + delegatorAddress, err := k.authKeeper.StringToBytes(ubd.DelegatorAddress) if err != nil { return err } diff --git a/x/staking/keeper/unbonding_test.go b/x/staking/keeper/unbonding_test.go index 0f2b396a3ab3..aad30a2fd9aa 100644 --- a/x/staking/keeper/unbonding_test.go +++ b/x/staking/keeper/unbonding_test.go @@ -56,6 +56,10 @@ func (s *KeeperTestSuite) TestUnbondingTypeAccessors() { func (s *KeeperTestSuite) TestUnbondingDelegationByUnbondingIDAccessors() { delAddrs, valAddrs := createValAddrs(2) + for _, addr := range delAddrs { + s.accountKeeper.EXPECT().StringToBytes(addr.String()).Return(addr, nil).AnyTimes() + s.accountKeeper.EXPECT().BytesToString(addr).Return(addr.String(), nil).AnyTimes() + } type exists struct { setUnbondingDelegation bool @@ -129,6 +133,11 @@ func (s *KeeperTestSuite) TestUnbondingDelegationByUnbondingIDAccessors() { func (s *KeeperTestSuite) TestRedelegationByUnbondingIDAccessors() { delAddrs, valAddrs := createValAddrs(2) + for _, addr := range delAddrs { + s.accountKeeper.EXPECT().StringToBytes(addr.String()).Return(addr, nil).AnyTimes() + s.accountKeeper.EXPECT().BytesToString(addr).Return(addr.String(), nil).AnyTimes() + } + type exists struct { setRedelegation bool setRedelegationByUnbondingID bool @@ -257,6 +266,10 @@ func (s *KeeperTestSuite) TestValidatorByUnbondingIDAccessors() { func (s *KeeperTestSuite) TestUnbondingCanComplete() { delAddrs, valAddrs := createValAddrs(3) + for _, addr := range delAddrs { + s.accountKeeper.EXPECT().StringToBytes(addr.String()).Return(addr, nil).AnyTimes() + s.accountKeeper.EXPECT().BytesToString(addr).Return(addr.String(), nil).AnyTimes() + } unbondingID := uint64(1) // no unbondingID set diff --git a/x/staking/keeper/val_state_change.go b/x/staking/keeper/val_state_change.go index e37db543d0ea..da6d1a520833 100644 --- a/x/staking/keeper/val_state_change.go +++ b/x/staking/keeper/val_state_change.go @@ -41,7 +41,10 @@ func (k Keeper) BlockValidatorUpdates(ctx sdk.Context) []abci.ValidatorUpdate { if err != nil { panic(err) } - delegatorAddress := sdk.MustAccAddressFromBech32(dvPair.DelegatorAddress) + delegatorAddress, err := k.authKeeper.StringToBytes(dvPair.DelegatorAddress) + if err != nil { + panic(err) + } balances, err := k.CompleteUnbonding(ctx, delegatorAddress, addr) if err != nil { @@ -69,7 +72,10 @@ func (k Keeper) BlockValidatorUpdates(ctx sdk.Context) []abci.ValidatorUpdate { if err != nil { panic(err) } - delegatorAddress := sdk.MustAccAddressFromBech32(dvvTriplet.DelegatorAddress) + delegatorAddress, err := k.authKeeper.StringToBytes(dvvTriplet.DelegatorAddress) + if err != nil { + panic(err) + } balances, err := k.CompleteRedelegation( ctx, diff --git a/x/staking/migrations/v2/keys.go b/x/staking/migrations/v2/keys.go index 439a823206a1..57ccb0aebeea 100644 --- a/x/staking/migrations/v2/keys.go +++ b/x/staking/migrations/v2/keys.go @@ -1,6 +1,15 @@ package v2 +import "strconv" + const ( // ModuleName is the name of the module ModuleName = "staking" ) + +var HistoricalInfoKey = []byte{0x50} // prefix for the historical info + +// GetHistoricalInfoKey returns a key prefix for indexing HistoricalInfo objects. +func GetHistoricalInfoKey(height int64) []byte { + return append(HistoricalInfoKey, []byte(strconv.FormatInt(height, 10))...) +} diff --git a/x/staking/migrations/v2/store_test.go b/x/staking/migrations/v2/store_test.go index 31c8016b1bba..b9416ad4f80e 100644 --- a/x/staking/migrations/v2/store_test.go +++ b/x/staking/migrations/v2/store_test.go @@ -114,7 +114,7 @@ func TestStoreMigration(t *testing.T) { { "HistoricalInfoKey", v1.GetHistoricalInfoKey(4), - types.GetHistoricalInfoKey(4), + v2.GetHistoricalInfoKey(4), }, } diff --git a/x/staking/migrations/v5/keys.go b/x/staking/migrations/v5/keys.go new file mode 100644 index 000000000000..3725301f77d2 --- /dev/null +++ b/x/staking/migrations/v5/keys.go @@ -0,0 +1,12 @@ +package v5 + +import "encoding/binary" + +var HistoricalInfoKey = []byte{0x50} // prefix for the historical info + +// GetHistoricalInfoKey returns a key prefix for indexing HistoricalInfo objects. +func GetHistoricalInfoKey(height int64) []byte { + heightBytes := make([]byte, 8) + binary.BigEndian.PutUint64(heightBytes, uint64(height)) + return append(HistoricalInfoKey, heightBytes...) +} diff --git a/x/staking/migrations/v5/migrations_test.go b/x/staking/migrations/v5/migrations_test.go new file mode 100644 index 000000000000..67607ffa4e88 --- /dev/null +++ b/x/staking/migrations/v5/migrations_test.go @@ -0,0 +1,71 @@ +package v5_test + +import ( + "math" + "math/rand" + "testing" + "time" + + storetypes "cosmossdk.io/store/types" + cmtproto "github.com/cometbft/cometbft/proto/tendermint/types" + "github.com/cosmos/cosmos-sdk/testutil" + moduletestutil "github.com/cosmos/cosmos-sdk/types/module/testutil" + v2 "github.com/cosmos/cosmos-sdk/x/staking/migrations/v2" + v5 "github.com/cosmos/cosmos-sdk/x/staking/migrations/v5" + stackingtypes "github.com/cosmos/cosmos-sdk/x/staking/types" + "github.com/stretchr/testify/require" +) + +func TestHistoricalKeysMigration(t *testing.T) { + storeKey := storetypes.NewKVStoreKey("staking") + tKey := storetypes.NewTransientStoreKey("transient_test") + ctx := testutil.DefaultContext(storeKey, tKey) + store := ctx.KVStore(storeKey) + + type testCase struct { + oldKey, newKey []byte + historicalInfo []byte + } + + testCases := make(map[int64]testCase) + + // edge cases + testCases[0], testCases[1], testCases[math.MaxInt32] = testCase{}, testCase{}, testCase{} + + // random cases + seed := time.Now().UnixNano() + r := rand.New(rand.NewSource(seed)) + for i := 0; i < 10; i++ { + height := r.Intn(math.MaxInt32-2) + 2 + + testCases[int64(height)] = testCase{} + } + + cdc := moduletestutil.MakeTestEncodingConfig().Codec + for height := range testCases { + testCases[height] = testCase{ + oldKey: v2.GetHistoricalInfoKey(height), + newKey: v5.GetHistoricalInfoKey(height), + historicalInfo: cdc.MustMarshal(createHistoricalInfo(height, "testChainID")), + } + } + + // populate store using old key format + for _, tc := range testCases { + store.Set(tc.oldKey, tc.historicalInfo) + } + + // migrate store to new key format + require.NoErrorf(t, v5.MigrateStore(ctx, storeKey), "v5.MigrateStore failed, seed: %d", seed) + + // check results + for _, tc := range testCases { + require.Nilf(t, store.Get(tc.oldKey), "old key should be deleted, seed: %d", seed) + require.NotNilf(t, store.Get(tc.newKey), "new key should be created, seed: %d", seed) + require.Equalf(t, tc.historicalInfo, store.Get(tc.newKey), "seed: %d", seed) + } +} + +func createHistoricalInfo(height int64, chainID string) *stackingtypes.HistoricalInfo { + return &stackingtypes.HistoricalInfo{Header: cmtproto.Header{ChainID: chainID, Height: height}} +} diff --git a/x/staking/migrations/v5/store.go b/x/staking/migrations/v5/store.go new file mode 100644 index 000000000000..4ab2eadece26 --- /dev/null +++ b/x/staking/migrations/v5/store.go @@ -0,0 +1,46 @@ +package v5 + +import ( + "fmt" + "strconv" + + "cosmossdk.io/log" + "cosmossdk.io/store/prefix" + storetypes "cosmossdk.io/store/types" + sdk "github.com/cosmos/cosmos-sdk/types" +) + +// MigrateStore performs in-place store migrations from v4 to v5. +func MigrateStore(ctx sdk.Context, storeKey storetypes.StoreKey) error { + store := ctx.KVStore(storeKey) + return migrateHistoricalInfoKeys(store, ctx.Logger()) +} + +// migrateHistoricalInfoKeys migrate HistoricalInfo keys to binary format +func migrateHistoricalInfoKeys(store storetypes.KVStore, logger log.Logger) error { + // old key is of format: + // prefix (0x50) || heightBytes (string representation of height in 10 base) + // new key is of format: + // prefix (0x50) || heightBytes (byte array representation using big-endian byte order) + oldStore := prefix.NewStore(store, HistoricalInfoKey) + + oldStoreIter := oldStore.Iterator(nil, nil) + defer sdk.LogDeferred(logger, func() error { return oldStoreIter.Close() }) + + for ; oldStoreIter.Valid(); oldStoreIter.Next() { + strHeight := oldStoreIter.Key() + + intHeight, err := strconv.ParseInt(string(strHeight), 10, 64) + if err != nil { + return fmt.Errorf("can't parse height from key %q to int64: %v", strHeight, err) + } + + newStoreKey := GetHistoricalInfoKey(intHeight) + + // Set new key on store. Values don't change. + store.Set(newStoreKey, oldStoreIter.Value()) + oldStore.Delete(oldStoreIter.Key()) + } + + return nil +} diff --git a/x/staking/module.go b/x/staking/module.go index 9674998406dd..d7d421f738a4 100644 --- a/x/staking/module.go +++ b/x/staking/module.go @@ -6,20 +6,14 @@ import ( "fmt" "sort" - authtypes "github.com/cosmos/cosmos-sdk/x/auth/types" - govtypes "github.com/cosmos/cosmos-sdk/x/gov/types" - "github.com/cosmos/cosmos-sdk/x/staking/exported" - - abci "github.com/cometbft/cometbft/abci/types" - gwruntime "github.com/grpc-ecosystem/grpc-gateway/runtime" - "github.com/spf13/cobra" - "golang.org/x/exp/maps" - modulev1 "cosmossdk.io/api/cosmos/staking/module/v1" "cosmossdk.io/core/appmodule" "cosmossdk.io/depinject" - store "cosmossdk.io/store/types" + abci "github.com/cometbft/cometbft/abci/types" + gwruntime "github.com/grpc-ecosystem/grpc-gateway/runtime" + "github.com/spf13/cobra" + "golang.org/x/exp/maps" "github.com/cosmos/cosmos-sdk/client" "github.com/cosmos/cosmos-sdk/codec" @@ -27,18 +21,23 @@ import ( sdk "github.com/cosmos/cosmos-sdk/types" "github.com/cosmos/cosmos-sdk/types/module" simtypes "github.com/cosmos/cosmos-sdk/types/simulation" + authtypes "github.com/cosmos/cosmos-sdk/x/auth/types" + govtypes "github.com/cosmos/cosmos-sdk/x/gov/types" "github.com/cosmos/cosmos-sdk/x/staking/client/cli" + "github.com/cosmos/cosmos-sdk/x/staking/exported" "github.com/cosmos/cosmos-sdk/x/staking/keeper" "github.com/cosmos/cosmos-sdk/x/staking/simulation" "github.com/cosmos/cosmos-sdk/x/staking/types" ) const ( - consensusVersion uint64 = 4 + consensusVersion uint64 = 5 ) var ( - _ module.EndBlockAppModule = AppModule{} + _ appmodule.AppModule = AppModule{} + _ appmodule.HasBeginBlocker = AppModule{} + _ module.HasABCIEndblock = AppModule{} _ module.AppModuleBasic = AppModuleBasic{} _ module.AppModuleSimulation = AppModule{} ) @@ -46,6 +45,7 @@ var ( // AppModuleBasic defines the basic application module used by the staking module. type AppModuleBasic struct { cdc codec.Codec + ak types.AccountKeeper } var _ module.AppModuleBasic = AppModuleBasic{} @@ -61,7 +61,7 @@ func (AppModuleBasic) RegisterLegacyAminoCodec(cdc *codec.LegacyAmino) { } // RegisterInterfaces registers the module's interface types -func (b AppModuleBasic) RegisterInterfaces(registry cdctypes.InterfaceRegistry) { +func (AppModuleBasic) RegisterInterfaces(registry cdctypes.InterfaceRegistry) { types.RegisterInterfaces(registry) } @@ -94,8 +94,8 @@ func (AppModuleBasic) GetTxCmd() *cobra.Command { } // GetQueryCmd returns no root query command for the staking module. -func (AppModuleBasic) GetQueryCmd() *cobra.Command { - return cli.GetQueryCmd() +func (ab AppModuleBasic) GetQueryCmd() *cobra.Command { + return cli.GetQueryCmd(ab.ak) } // AppModule implements an application module for the staking module. @@ -119,7 +119,7 @@ func NewAppModule( ls exported.Subspace, ) AppModule { return AppModule{ - AppModuleBasic: AppModuleBasic{cdc: cdc}, + AppModuleBasic: AppModuleBasic{cdc: cdc, ak: ak}, keeper: keeper, accountKeeper: ak, bankKeeper: bk, @@ -164,6 +164,9 @@ func (am AppModule) RegisterServices(cfg module.Configurator) { if err := cfg.RegisterMigration(types.ModuleName, 3, m.Migrate3to4); err != nil { panic(fmt.Sprintf("failed to migrate x/%s from version 3 to 4: %v", types.ModuleName, err)) } + if err := cfg.RegisterMigration(types.ModuleName, 4, m.Migrate4to5); err != nil { + panic(fmt.Sprintf("failed to migrate x/%s from version 4 to 5: %v", types.ModuleName, err)) + } } // InitGenesis performs genesis initialization for the staking module. @@ -187,14 +190,15 @@ func (AppModule) ConsensusVersion() uint64 { return consensusVersion } // BeginBlock returns the begin blocker for the staking module. func (am AppModule) BeginBlock(ctx context.Context) error { c := sdk.UnwrapSDKContext(ctx) - BeginBlocker(c, am.keeper) + + am.keeper.BeginBlocker(c) return nil } // EndBlock returns the end blocker for the staking module. It returns no validator // updates. -func (am AppModule) EndBlock(ctx sdk.Context, _ abci.RequestEndBlock) []abci.ValidatorUpdate { - return EndBlocker(ctx, am.keeper) +func (am AppModule) EndBlock(ctx context.Context) ([]abci.ValidatorUpdate, error) { + return am.keeper.EndBlocker(ctx) } func init() { @@ -205,8 +209,7 @@ func init() { ) } -//nolint:revive -type StakingInputs struct { +type ModuleInputs struct { depinject.In Config *modulev1.Module @@ -220,16 +223,14 @@ type StakingInputs struct { } // Dependency Injection Outputs -// -//nolint:revive -type StakingOutputs struct { +type ModuleOutputs struct { depinject.Out StakingKeeper *keeper.Keeper Module appmodule.AppModule } -func ProvideModule(in StakingInputs) StakingOutputs { +func ProvideModule(in ModuleInputs) ModuleOutputs { // default to governance authority if not provided authority := authtypes.NewModuleAddress(govtypes.ModuleName) if in.Config.Authority != "" { @@ -244,7 +245,7 @@ func ProvideModule(in StakingInputs) StakingOutputs { authority.String(), ) m := NewAppModule(in.Cdc, k, in.AccountKeeper, in.BankKeeper, in.LegacySubspace) - return StakingOutputs{StakingKeeper: k, Module: m} + return ModuleOutputs{StakingKeeper: k, Module: m} } func InvokeSetStakingHooks( @@ -306,6 +307,7 @@ func (am AppModule) RegisterStoreDecoder(sdr simtypes.StoreDecoderRegistry) { // WeightedOperations returns the all the staking module operations with their respective weights. func (am AppModule) WeightedOperations(simState module.SimulationState) []simtypes.WeightedOperation { return simulation.WeightedOperations( - simState.AppParams, simState.Cdc, am.accountKeeper, am.bankKeeper, am.keeper, + simState.AppParams, simState.Cdc, simState.TxConfig, + am.accountKeeper, am.bankKeeper, am.keeper, ) } diff --git a/x/staking/simulation/operations.go b/x/staking/simulation/operations.go index 18794553b037..adfda8fccfd5 100644 --- a/x/staking/simulation/operations.go +++ b/x/staking/simulation/operations.go @@ -6,10 +6,10 @@ import ( "cosmossdk.io/math" "github.com/cosmos/cosmos-sdk/baseapp" + "github.com/cosmos/cosmos-sdk/client" "github.com/cosmos/cosmos-sdk/codec" "github.com/cosmos/cosmos-sdk/testutil" sdk "github.com/cosmos/cosmos-sdk/types" - moduletestutil "github.com/cosmos/cosmos-sdk/types/module/testutil" simtypes "github.com/cosmos/cosmos-sdk/types/simulation" "github.com/cosmos/cosmos-sdk/x/simulation" "github.com/cosmos/cosmos-sdk/x/staking/keeper" @@ -17,8 +17,6 @@ import ( ) // Simulation operation weights constants -// -//nolint:gosec // these are not hardcoded credentials const ( DefaultWeightMsgCreateValidator int = 100 DefaultWeightMsgEditValidator int = 5 @@ -37,8 +35,12 @@ const ( // WeightedOperations returns all the operations from the module with their respective weights func WeightedOperations( - appParams simtypes.AppParams, cdc codec.JSONCodec, ak types.AccountKeeper, - bk types.BankKeeper, k *keeper.Keeper, + appParams simtypes.AppParams, + cdc codec.JSONCodec, + txGen client.TxConfig, + ak types.AccountKeeper, + bk types.BankKeeper, + k *keeper.Keeper, ) simulation.WeightedOperations { var ( weightMsgCreateValidator int @@ -88,33 +90,38 @@ func WeightedOperations( return simulation.WeightedOperations{ simulation.NewWeightedOperation( weightMsgCreateValidator, - SimulateMsgCreateValidator(ak, bk, k), + SimulateMsgCreateValidator(txGen, ak, bk, k), ), simulation.NewWeightedOperation( weightMsgEditValidator, - SimulateMsgEditValidator(ak, bk, k), + SimulateMsgEditValidator(txGen, ak, bk, k), ), simulation.NewWeightedOperation( weightMsgDelegate, - SimulateMsgDelegate(ak, bk, k), + SimulateMsgDelegate(txGen, ak, bk, k), ), simulation.NewWeightedOperation( weightMsgUndelegate, - SimulateMsgUndelegate(ak, bk, k), + SimulateMsgUndelegate(txGen, ak, bk, k), ), simulation.NewWeightedOperation( weightMsgBeginRedelegate, - SimulateMsgBeginRedelegate(ak, bk, k), + SimulateMsgBeginRedelegate(txGen, ak, bk, k), ), simulation.NewWeightedOperation( weightMsgCancelUnbondingDelegation, - SimulateMsgCancelUnbondingDelegate(ak, bk, k), + SimulateMsgCancelUnbondingDelegate(txGen, ak, bk, k), ), } } // SimulateMsgCreateValidator generates a MsgCreateValidator with random values -func SimulateMsgCreateValidator(ak types.AccountKeeper, bk types.BankKeeper, k *keeper.Keeper) simtypes.Operation { +func SimulateMsgCreateValidator( + txGen client.TxConfig, + ak types.AccountKeeper, + bk types.BankKeeper, + k *keeper.Keeper, +) simtypes.Operation { return func( r *rand.Rand, app *baseapp.BaseApp, ctx sdk.Context, accs []simtypes.Account, chainID string, ) (simtypes.OperationMsg, []simtypes.FutureOperation, error) { @@ -179,7 +186,7 @@ func SimulateMsgCreateValidator(ak types.AccountKeeper, bk types.BankKeeper, k * txCtx := simulation.OperationInput{ R: r, App: app, - TxGen: moduletestutil.MakeTestEncodingConfig().TxConfig, + TxGen: txGen, Cdc: nil, Msg: msg, Context: ctx, @@ -193,7 +200,12 @@ func SimulateMsgCreateValidator(ak types.AccountKeeper, bk types.BankKeeper, k * } // SimulateMsgEditValidator generates a MsgEditValidator with random values -func SimulateMsgEditValidator(ak types.AccountKeeper, bk types.BankKeeper, k *keeper.Keeper) simtypes.Operation { +func SimulateMsgEditValidator( + txGen client.TxConfig, + ak types.AccountKeeper, + bk types.BankKeeper, + k *keeper.Keeper, +) simtypes.Operation { return func( r *rand.Rand, app *baseapp.BaseApp, ctx sdk.Context, accs []simtypes.Account, chainID string, ) (simtypes.OperationMsg, []simtypes.FutureOperation, error) { @@ -237,7 +249,7 @@ func SimulateMsgEditValidator(ak types.AccountKeeper, bk types.BankKeeper, k *ke txCtx := simulation.OperationInput{ R: r, App: app, - TxGen: moduletestutil.MakeTestEncodingConfig().TxConfig, + TxGen: txGen, Cdc: nil, Msg: msg, Context: ctx, @@ -253,7 +265,12 @@ func SimulateMsgEditValidator(ak types.AccountKeeper, bk types.BankKeeper, k *ke } // SimulateMsgDelegate generates a MsgDelegate with random values -func SimulateMsgDelegate(ak types.AccountKeeper, bk types.BankKeeper, k *keeper.Keeper) simtypes.Operation { +func SimulateMsgDelegate( + txGen client.TxConfig, + ak types.AccountKeeper, + bk types.BankKeeper, + k *keeper.Keeper, +) simtypes.Operation { return func( r *rand.Rand, app *baseapp.BaseApp, ctx sdk.Context, accs []simtypes.Account, chainID string, ) (simtypes.OperationMsg, []simtypes.FutureOperation, error) { @@ -304,7 +321,7 @@ func SimulateMsgDelegate(ak types.AccountKeeper, bk types.BankKeeper, k *keeper. txCtx := simulation.OperationInput{ R: r, App: app, - TxGen: moduletestutil.MakeTestEncodingConfig().TxConfig, + TxGen: txGen, Cdc: nil, Msg: msg, Context: ctx, @@ -318,7 +335,12 @@ func SimulateMsgDelegate(ak types.AccountKeeper, bk types.BankKeeper, k *keeper. } // SimulateMsgUndelegate generates a MsgUndelegate with random values -func SimulateMsgUndelegate(ak types.AccountKeeper, bk types.BankKeeper, k *keeper.Keeper) simtypes.Operation { +func SimulateMsgUndelegate( + txGen client.TxConfig, + ak types.AccountKeeper, + bk types.BankKeeper, + k *keeper.Keeper, +) simtypes.Operation { return func( r *rand.Rand, app *baseapp.BaseApp, ctx sdk.Context, accs []simtypes.Account, chainID string, ) (simtypes.OperationMsg, []simtypes.FutureOperation, error) { @@ -381,7 +403,7 @@ func SimulateMsgUndelegate(ak types.AccountKeeper, bk types.BankKeeper, k *keepe txCtx := simulation.OperationInput{ R: r, App: app, - TxGen: moduletestutil.MakeTestEncodingConfig().TxConfig, + TxGen: txGen, Cdc: nil, Msg: msg, Context: ctx, @@ -397,7 +419,12 @@ func SimulateMsgUndelegate(ak types.AccountKeeper, bk types.BankKeeper, k *keepe } // SimulateMsgCancelUnbondingDelegate generates a MsgCancelUnbondingDelegate with random values -func SimulateMsgCancelUnbondingDelegate(ak types.AccountKeeper, bk types.BankKeeper, k *keeper.Keeper) simtypes.Operation { +func SimulateMsgCancelUnbondingDelegate( + txGen client.TxConfig, + ak types.AccountKeeper, + bk types.BankKeeper, + k *keeper.Keeper, +) simtypes.Operation { return func( r *rand.Rand, app *baseapp.BaseApp, ctx sdk.Context, accs []simtypes.Account, chainID string, ) (simtypes.OperationMsg, []simtypes.FutureOperation, error) { @@ -462,7 +489,7 @@ func SimulateMsgCancelUnbondingDelegate(ak types.AccountKeeper, bk types.BankKee txCtx := simulation.OperationInput{ R: r, App: app, - TxGen: moduletestutil.MakeTestEncodingConfig().TxConfig, + TxGen: txGen, Cdc: nil, Msg: msg, Context: ctx, @@ -478,7 +505,12 @@ func SimulateMsgCancelUnbondingDelegate(ak types.AccountKeeper, bk types.BankKee } // SimulateMsgBeginRedelegate generates a MsgBeginRedelegate with random values -func SimulateMsgBeginRedelegate(ak types.AccountKeeper, bk types.BankKeeper, k *keeper.Keeper) simtypes.Operation { +func SimulateMsgBeginRedelegate( + txGen client.TxConfig, + ak types.AccountKeeper, + bk types.BankKeeper, + k *keeper.Keeper, +) simtypes.Operation { return func( r *rand.Rand, app *baseapp.BaseApp, ctx sdk.Context, accs []simtypes.Account, chainID string, ) (simtypes.OperationMsg, []simtypes.FutureOperation, error) { @@ -565,7 +597,7 @@ func SimulateMsgBeginRedelegate(ak types.AccountKeeper, bk types.BankKeeper, k * txCtx := simulation.OperationInput{ R: r, App: app, - TxGen: moduletestutil.MakeTestEncodingConfig().TxConfig, + TxGen: txGen, Cdc: nil, Msg: msg, Context: ctx, diff --git a/x/staking/simulation/operations_test.go b/x/staking/simulation/operations_test.go index 2ccfe937d738..6d1484a6991f 100644 --- a/x/staking/simulation/operations_test.go +++ b/x/staking/simulation/operations_test.go @@ -13,6 +13,7 @@ import ( abci "github.com/cometbft/cometbft/abci/types" cmtproto "github.com/cometbft/cometbft/proto/tendermint/types" cmttypes "github.com/cometbft/cometbft/types" + "github.com/cosmos/cosmos-sdk/client" cryptocodec "github.com/cosmos/cosmos-sdk/crypto/codec" "github.com/cosmos/cosmos-sdk/crypto/keys/secp256k1" "github.com/cosmos/cosmos-sdk/runtime" @@ -42,6 +43,7 @@ type SimTestSuite struct { suite.Suite r *rand.Rand + txConfig client.TxConfig accounts []simtypes.Account ctx sdk.Context app *runtime.App @@ -86,7 +88,7 @@ func (s *SimTestSuite) SetupTest() { stakingKeeper *stakingkeeper.Keeper ) - app, err := simtestutil.SetupWithConfiguration(testutil.AppConfig, startupCfg, &bankKeeper, &accountKeeper, &mintKeeper, &distrKeeper, &stakingKeeper) + app, err := simtestutil.SetupWithConfiguration(testutil.AppConfig, startupCfg, &s.txConfig, &bankKeeper, &accountKeeper, &mintKeeper, &distrKeeper, &stakingKeeper) require.NoError(s.T(), err) ctx := app.BaseApp.NewContext(false, cmtproto.Header{}) @@ -122,7 +124,7 @@ func (s *SimTestSuite) TestWeightedOperations() { cdc := s.encCfg.Codec appParams := make(simtypes.AppParams) - weightesOps := simulation.WeightedOperations(appParams, cdc, s.accountKeeper, + weightedOps := simulation.WeightedOperations(appParams, cdc, s.txConfig, s.accountKeeper, s.bankKeeper, s.stakingKeeper, ) @@ -139,7 +141,7 @@ func (s *SimTestSuite) TestWeightedOperations() { {simulation.DefaultWeightMsgCancelUnbondingDelegation, types.ModuleName, sdk.MsgTypeURL(&types.MsgCancelUnbondingDelegation{})}, } - for i, w := range weightesOps { + for i, w := range weightedOps { operationMsg, _, _ := w.Op()(s.r, s.app.BaseApp, s.ctx, s.accounts, s.ctx.ChainID()) // require.NoError(t, err) // TODO check if it should be NoError @@ -160,7 +162,7 @@ func (s *SimTestSuite) TestSimulateMsgCreateValidator() { s.app.BeginBlock(abci.RequestBeginBlock{Header: cmtproto.Header{Height: s.app.LastBlockHeight() + 1, AppHash: s.app.LastCommitID().Hash}}) // execute operation - op := simulation.SimulateMsgCreateValidator(s.accountKeeper, s.bankKeeper, s.stakingKeeper) + op := simulation.SimulateMsgCreateValidator(s.txConfig, s.accountKeeper, s.bankKeeper, s.stakingKeeper) operationMsg, futureOperations, err := op(s.r, s.app.BaseApp, s.ctx, s.accounts[1:], "") require.NoError(err) @@ -205,7 +207,7 @@ func (s *SimTestSuite) TestSimulateMsgCancelUnbondingDelegation() { s.app.BeginBlock(abci.RequestBeginBlock{Header: cmtproto.Header{Height: s.app.LastBlockHeight() + 1, AppHash: s.app.LastCommitID().Hash, Time: blockTime}}) // execute operation - op := simulation.SimulateMsgCancelUnbondingDelegate(s.accountKeeper, s.bankKeeper, s.stakingKeeper) + op := simulation.SimulateMsgCancelUnbondingDelegate(s.txConfig, s.accountKeeper, s.bankKeeper, s.stakingKeeper) accounts := []simtypes.Account{delegator} operationMsg, futureOperations, err := op(s.r, s.app.BaseApp, ctx, accounts, "") require.NoError(err) @@ -234,7 +236,7 @@ func (s *SimTestSuite) TestSimulateMsgEditValidator() { s.app.BeginBlock(abci.RequestBeginBlock{Header: cmtproto.Header{Height: s.app.LastBlockHeight() + 1, AppHash: s.app.LastCommitID().Hash, Time: blockTime}}) // execute operation - op := simulation.SimulateMsgEditValidator(s.accountKeeper, s.bankKeeper, s.stakingKeeper) + op := simulation.SimulateMsgEditValidator(s.txConfig, s.accountKeeper, s.bankKeeper, s.stakingKeeper) operationMsg, futureOperations, err := op(s.r, s.app.BaseApp, ctx, s.accounts, "") require.NoError(err) @@ -255,7 +257,7 @@ func (s *SimTestSuite) TestSimulateMsgDelegate() { ctx := s.ctx.WithBlockTime(blockTime) // execute operation - op := simulation.SimulateMsgDelegate(s.accountKeeper, s.bankKeeper, s.stakingKeeper) + op := simulation.SimulateMsgDelegate(s.txConfig, s.accountKeeper, s.bankKeeper, s.stakingKeeper) operationMsg, futureOperations, err := op(s.r, s.app.BaseApp, ctx, s.accounts[1:], "") require.NoError(err) @@ -294,7 +296,7 @@ func (s *SimTestSuite) TestSimulateMsgUndelegate() { s.app.BeginBlock(abci.RequestBeginBlock{Header: cmtproto.Header{Height: s.app.LastBlockHeight() + 1, AppHash: s.app.LastCommitID().Hash, Time: blockTime}}) // execute operation - op := simulation.SimulateMsgUndelegate(s.accountKeeper, s.bankKeeper, s.stakingKeeper) + op := simulation.SimulateMsgUndelegate(s.txConfig, s.accountKeeper, s.bankKeeper, s.stakingKeeper) operationMsg, futureOperations, err := op(s.r, s.app.BaseApp, ctx, s.accounts, "") require.NoError(err) @@ -337,7 +339,7 @@ func (s *SimTestSuite) TestSimulateMsgBeginRedelegate() { s.app.BeginBlock(abci.RequestBeginBlock{Header: cmtproto.Header{Height: s.app.LastBlockHeight() + 1, AppHash: s.app.LastCommitID().Hash, Time: blockTime}}) // execute operation - op := simulation.SimulateMsgBeginRedelegate(s.accountKeeper, s.bankKeeper, s.stakingKeeper) + op := simulation.SimulateMsgBeginRedelegate(s.txConfig, s.accountKeeper, s.bankKeeper, s.stakingKeeper) operationMsg, futureOperations, err := op(s.r, s.app.BaseApp, ctx, s.accounts, "") s.T().Logf("operation message: %v", operationMsg) require.NoError(err) diff --git a/x/staking/simulation/proposals.go b/x/staking/simulation/proposals.go index 6b1f43128247..5ef5fc7a13bc 100644 --- a/x/staking/simulation/proposals.go +++ b/x/staking/simulation/proposals.go @@ -15,7 +15,7 @@ import ( const ( DefaultWeightMsgUpdateParams int = 100 - OpWeightMsgUpdateParams = "op_weight_msg_update_params" //nolint:gosec + OpWeightMsgUpdateParams = "op_weight_msg_update_params" ) // ProposalMsgs defines the module weighted proposals' contents diff --git a/x/staking/testutil/expected_keepers_mocks.go b/x/staking/testutil/expected_keepers_mocks.go index 3c69110153cc..ba3036da7561 100644 --- a/x/staking/testutil/expected_keepers_mocks.go +++ b/x/staking/testutil/expected_keepers_mocks.go @@ -5,6 +5,7 @@ package testutil import ( + context "context" reflect "reflect" math "cosmossdk.io/math" @@ -87,8 +88,23 @@ func (m *MockAccountKeeper) EXPECT() *MockAccountKeeperMockRecorder { return m.recorder } +// BytesToString mocks base method. +func (m *MockAccountKeeper) BytesToString(bz []byte) (string, error) { + m.ctrl.T.Helper() + ret := m.ctrl.Call(m, "BytesToString", bz) + ret0, _ := ret[0].(string) + ret1, _ := ret[1].(error) + return ret0, ret1 +} + +// BytesToString indicates an expected call of BytesToString. +func (mr *MockAccountKeeperMockRecorder) BytesToString(bz interface{}) *gomock.Call { + mr.mock.ctrl.T.Helper() + return mr.mock.ctrl.RecordCallWithMethodType(mr.mock, "BytesToString", reflect.TypeOf((*MockAccountKeeper)(nil).BytesToString), bz) +} + // GetAccount mocks base method. -func (m *MockAccountKeeper) GetAccount(ctx types.Context, addr types.AccAddress) types.AccountI { +func (m *MockAccountKeeper) GetAccount(ctx context.Context, addr types.AccAddress) types.AccountI { m.ctrl.T.Helper() ret := m.ctrl.Call(m, "GetAccount", ctx, addr) ret0, _ := ret[0].(types.AccountI) @@ -102,7 +118,7 @@ func (mr *MockAccountKeeperMockRecorder) GetAccount(ctx, addr interface{}) *gomo } // GetModuleAccount mocks base method. -func (m *MockAccountKeeper) GetModuleAccount(ctx types.Context, moduleName string) types.ModuleAccountI { +func (m *MockAccountKeeper) GetModuleAccount(ctx context.Context, moduleName string) types.ModuleAccountI { m.ctrl.T.Helper() ret := m.ctrl.Call(m, "GetModuleAccount", ctx, moduleName) ret0, _ := ret[0].(types.ModuleAccountI) @@ -130,7 +146,7 @@ func (mr *MockAccountKeeperMockRecorder) GetModuleAddress(name interface{}) *gom } // IterateAccounts mocks base method. -func (m *MockAccountKeeper) IterateAccounts(ctx types.Context, process func(types.AccountI) bool) { +func (m *MockAccountKeeper) IterateAccounts(ctx context.Context, process func(types.AccountI) bool) { m.ctrl.T.Helper() m.ctrl.Call(m, "IterateAccounts", ctx, process) } @@ -142,7 +158,7 @@ func (mr *MockAccountKeeperMockRecorder) IterateAccounts(ctx, process interface{ } // SetModuleAccount mocks base method. -func (m *MockAccountKeeper) SetModuleAccount(arg0 types.Context, arg1 types.ModuleAccountI) { +func (m *MockAccountKeeper) SetModuleAccount(arg0 context.Context, arg1 types.ModuleAccountI) { m.ctrl.T.Helper() m.ctrl.Call(m, "SetModuleAccount", arg0, arg1) } @@ -153,6 +169,21 @@ func (mr *MockAccountKeeperMockRecorder) SetModuleAccount(arg0, arg1 interface{} return mr.mock.ctrl.RecordCallWithMethodType(mr.mock, "SetModuleAccount", reflect.TypeOf((*MockAccountKeeper)(nil).SetModuleAccount), arg0, arg1) } +// StringToBytes mocks base method. +func (m *MockAccountKeeper) StringToBytes(text string) ([]byte, error) { + m.ctrl.T.Helper() + ret := m.ctrl.Call(m, "StringToBytes", text) + ret0, _ := ret[0].([]byte) + ret1, _ := ret[1].(error) + return ret0, ret1 +} + +// StringToBytes indicates an expected call of StringToBytes. +func (mr *MockAccountKeeperMockRecorder) StringToBytes(text interface{}) *gomock.Call { + mr.mock.ctrl.T.Helper() + return mr.mock.ctrl.RecordCallWithMethodType(mr.mock, "StringToBytes", reflect.TypeOf((*MockAccountKeeper)(nil).StringToBytes), text) +} + // MockBankKeeper is a mock of BankKeeper interface. type MockBankKeeper struct { ctrl *gomock.Controller diff --git a/x/staking/testutil/helpers.go b/x/staking/testutil/helpers.go index 3dae28b09a06..a7a2298d039b 100644 --- a/x/staking/testutil/helpers.go +++ b/x/staking/testutil/helpers.go @@ -10,7 +10,6 @@ import ( cryptotypes "github.com/cosmos/cosmos-sdk/crypto/types" sdk "github.com/cosmos/cosmos-sdk/types" - "github.com/cosmos/cosmos-sdk/x/staking" "github.com/cosmos/cosmos-sdk/x/staking/keeper" stakingtypes "github.com/cosmos/cosmos-sdk/x/staking/types" ) @@ -62,7 +61,7 @@ func (sh *Helper) CreateValidatorWithMsg(ctx context.Context, msg *stakingtypes. } func (sh *Helper) createValidator(addr sdk.ValAddress, pk cryptotypes.PubKey, coin sdk.Coin, ok bool) { - msg, err := stakingtypes.NewMsgCreateValidator(addr, pk, coin, stakingtypes.Description{}, sh.Commission, math.OneInt()) + msg, err := stakingtypes.NewMsgCreateValidator(addr, pk, coin, stakingtypes.Description{Moniker: "TestValidator"}, sh.Commission, math.OneInt()) require.NoError(sh.t, err) res, err := sh.msgSrvr.CreateValidator(sh.Ctx, msg) if ok { @@ -127,7 +126,7 @@ func (sh *Helper) CheckDelegator(delegator sdk.AccAddress, val sdk.ValAddress, f // TurnBlock calls EndBlocker and updates the block time func (sh *Helper) TurnBlock(newTime time.Time) sdk.Context { sh.Ctx = sh.Ctx.WithBlockTime(newTime) - staking.EndBlocker(sh.Ctx, sh.k) + sh.k.EndBlocker(sh.Ctx) return sh.Ctx } @@ -135,7 +134,7 @@ func (sh *Helper) TurnBlock(newTime time.Time) sdk.Context { // duration to the current block time func (sh *Helper) TurnBlockTimeDiff(diff time.Duration) sdk.Context { sh.Ctx = sh.Ctx.WithBlockTime(sh.Ctx.BlockHeader().Time.Add(diff)) - staking.EndBlocker(sh.Ctx, sh.k) + sh.k.EndBlocker(sh.Ctx) return sh.Ctx } diff --git a/x/staking/types/authz.go b/x/staking/types/authz.go index f30dfe018bc2..911974c1e376 100644 --- a/x/staking/types/authz.go +++ b/x/staking/types/authz.go @@ -15,7 +15,7 @@ const gasCostPerIteration = uint64(10) var _ authz.Authorization = &StakeAuthorization{} // NewStakeAuthorization creates a new StakeAuthorization object. -func NewStakeAuthorization(allowed []sdk.ValAddress, denied []sdk.ValAddress, authzType AuthorizationType, amount *sdk.Coin) (*StakeAuthorization, error) { +func NewStakeAuthorization(allowed, denied []sdk.ValAddress, authzType AuthorizationType, amount *sdk.Coin) (*StakeAuthorization, error) { allowedValidators, deniedValidators, err := validateAllowAndDenyValidators(allowed, denied) if err != nil { return nil, err @@ -150,7 +150,7 @@ func (a StakeAuthorization) Accept(ctx sdk.Context, msg sdk.Msg) (authz.AcceptRe }, nil } -func validateAllowAndDenyValidators(allowed []sdk.ValAddress, denied []sdk.ValAddress) ([]string, []string, error) { +func validateAllowAndDenyValidators(allowed, denied []sdk.ValAddress) ([]string, []string, error) { if len(allowed) == 0 && len(denied) == 0 { return nil, nil, sdkerrors.ErrInvalidRequest.Wrap("both allowed & deny list cannot be empty") } diff --git a/x/staking/types/data_test.go b/x/staking/types/data_test.go index d875b088fdbb..f8b927ef1e6f 100644 --- a/x/staking/types/data_test.go +++ b/x/staking/types/data_test.go @@ -5,7 +5,6 @@ import ( codectypes "github.com/cosmos/cosmos-sdk/codec/types" "github.com/cosmos/cosmos-sdk/crypto/keys/ed25519" - cryptotypes "github.com/cosmos/cosmos-sdk/crypto/types" sdk "github.com/cosmos/cosmos-sdk/types" ) @@ -17,9 +16,6 @@ var ( valAddr1 = sdk.ValAddress(pk1.Address()) valAddr2 = sdk.ValAddress(pk2.Address()) valAddr3 = sdk.ValAddress(pk3.Address()) - - emptyAddr sdk.ValAddress - emptyPubkey cryptotypes.PubKey ) func init() { diff --git a/x/staking/types/delegation.go b/x/staking/types/delegation.go index f993d9dc28e8..3fd63b261648 100644 --- a/x/staking/types/delegation.go +++ b/x/staking/types/delegation.go @@ -14,8 +14,6 @@ import ( var _ DelegationI = Delegation{} // NewDelegation creates a new delegation object -// -//nolint:interfacer func NewDelegation(delegatorAddr sdk.AccAddress, validatorAddr sdk.ValAddress, shares sdk.Dec) Delegation { return Delegation{ DelegatorAddress: delegatorAddr.String(), @@ -115,8 +113,6 @@ func UnmarshalUBDE(cdc codec.BinaryCodec, value []byte) (ubd UnbondingDelegation } // NewUnbondingDelegation - create a new unbonding delegation object -// -//nolint:interfacer func NewUnbondingDelegation( delegatorAddr sdk.AccAddress, validatorAddr sdk.ValAddress, creationHeight int64, minTime time.Time, balance math.Int, id uint64, @@ -213,7 +209,6 @@ func (e RedelegationEntry) OnHold() bool { return e.UnbondingOnHoldRefCount > 0 } -//nolint:interfacer func NewRedelegation( delegatorAddr sdk.AccAddress, validatorSrcAddr, validatorDstAddr sdk.ValAddress, creationHeight int64, minTime time.Time, balance math.Int, sharesDst sdk.Dec, id uint64, @@ -311,8 +306,6 @@ func (d DelegationResponses) String() (out string) { } // NewRedelegationResponse crates a new RedelegationEntryResponse instance. -// -//nolint:interfacer func NewRedelegationResponse( delegatorAddr sdk.AccAddress, validatorSrc, validatorDst sdk.ValAddress, entries []RedelegationEntryResponse, ) RedelegationResponse { diff --git a/x/staking/types/expected_keepers.go b/x/staking/types/expected_keepers.go index 5a9e22344c49..b70505d0ec30 100644 --- a/x/staking/types/expected_keepers.go +++ b/x/staking/types/expected_keepers.go @@ -1,6 +1,9 @@ package types import ( + context "context" + + "cosmossdk.io/core/address" "cosmossdk.io/math" sdk "github.com/cosmos/cosmos-sdk/types" @@ -14,14 +17,16 @@ type DistributionKeeper interface { // AccountKeeper defines the expected account keeper (noalias) type AccountKeeper interface { - IterateAccounts(ctx sdk.Context, process func(sdk.AccountI) (stop bool)) - GetAccount(ctx sdk.Context, addr sdk.AccAddress) sdk.AccountI // only used for simulation + address.Codec + + IterateAccounts(ctx context.Context, process func(sdk.AccountI) (stop bool)) + GetAccount(ctx context.Context, addr sdk.AccAddress) sdk.AccountI // only used for simulation GetModuleAddress(name string) sdk.AccAddress - GetModuleAccount(ctx sdk.Context, moduleName string) sdk.ModuleAccountI + GetModuleAccount(ctx context.Context, moduleName string) sdk.ModuleAccountI // TODO remove with genesis 2-phases refactor https://github.com/cosmos/cosmos-sdk/issues/2862 - SetModuleAccount(sdk.Context, sdk.ModuleAccountI) + SetModuleAccount(context.Context, sdk.ModuleAccountI) } // BankKeeper defines the expected interface needed to retrieve account balances. @@ -59,7 +64,7 @@ type ValidatorSet interface { TotalBondedTokens(sdk.Context) math.Int // total bonded tokens within the validator set StakingTokenSupply(sdk.Context) math.Int // total staking token supply - // slash the validator and delegators of the validator, specifying offence height, offence power, and slash fraction + // slash the validator and delegators of the validator, specifying offense height, offense power, and slash fraction Slash(sdk.Context, sdk.ConsAddress, int64, int64, sdk.Dec) math.Int SlashWithInfractionReason(sdk.Context, sdk.ConsAddress, int64, int64, sdk.Dec, Infraction) math.Int Jail(sdk.Context, sdk.ConsAddress) // jail a validator diff --git a/x/staking/types/historical_info_test.go b/x/staking/types/historical_info_test.go index f463111d777e..90b4872733a8 100644 --- a/x/staking/types/historical_info_test.go +++ b/x/staking/types/historical_info_test.go @@ -37,7 +37,7 @@ func TestHistoricalInfo(t *testing.T) { require.NotPanics(t, func() { value = legacy.Cdc.MustMarshal(&hi) }) - require.NotNil(t, value, "Marshalled HistoricalInfo is nil") + require.NotNil(t, value, "Marshaled HistoricalInfo is nil") recv, err := types.UnmarshalHistoricalInfo(codec.NewAminoCodec(legacy.Cdc), value) require.Nil(t, err, "Unmarshalling HistoricalInfo failed") @@ -59,9 +59,7 @@ func TestValidateBasic(t *testing.T) { // Ensure validators are not sorted for sort.IsSorted(types.Validators(validators)) { rand.Shuffle(len(validators), func(i, j int) { - it := validators[i] //nolint:gocritic - validators[i] = validators[j] - validators[j] = it + validators[i], validators[j] = validators[j], validators[i] }) } hi = types.HistoricalInfo{ diff --git a/x/staking/types/keys.go b/x/staking/types/keys.go index f8f642af5c9b..d197d58d1d32 100644 --- a/x/staking/types/keys.go +++ b/x/staking/types/keys.go @@ -4,7 +4,6 @@ import ( "bytes" "encoding/binary" "fmt" - "strconv" "time" "cosmossdk.io/math" @@ -376,5 +375,7 @@ func GetREDsByDelToValDstIndexKey(delAddr sdk.AccAddress, valDstAddr sdk.ValAddr // GetHistoricalInfoKey returns a key prefix for indexing HistoricalInfo objects. func GetHistoricalInfoKey(height int64) []byte { - return append(HistoricalInfoKey, []byte(strconv.FormatInt(height, 10))...) + heightBytes := make([]byte, 8) + binary.BigEndian.PutUint64(heightBytes, uint64(height)) + return append(HistoricalInfoKey, heightBytes...) } diff --git a/x/staking/types/keys_test.go b/x/staking/types/keys_test.go index e5b96e484442..ce3c55e45409 100644 --- a/x/staking/types/keys_test.go +++ b/x/staking/types/keys_test.go @@ -3,7 +3,9 @@ package types_test import ( "bytes" "encoding/hex" + math2 "math" "math/big" + "strconv" "testing" "time" @@ -129,3 +131,21 @@ func TestTestGetValidatorQueueKeyOrder(t *testing.T) { require.Equal(t, -1, bytes.Compare(keyB, endKey)) // keyB <= endKey require.Equal(t, 1, bytes.Compare(keyC, endKey)) // keyB >= endKey } + +func TestGetHistoricalInfoKey(t *testing.T) { + tests := []struct { + height int64 + want []byte + }{ + {0, append(types.HistoricalInfoKey, []byte{0, 0, 0, 0, 0, 0, 0, 0}...)}, + {1, append(types.HistoricalInfoKey, []byte{0, 0, 0, 0, 0, 0, 0, 1}...)}, + {2, append(types.HistoricalInfoKey, []byte{0, 0, 0, 0, 0, 0, 0, 2}...)}, + {514, append(types.HistoricalInfoKey, []byte{0, 0, 0, 0, 0, 0, 2, 2}...)}, + {math2.MaxInt64, append(types.HistoricalInfoKey, []byte{127, 255, 255, 255, 255, 255, 255, 255}...)}, + } + for _, tt := range tests { + t.Run(strconv.FormatInt(tt.height, 10), func(t *testing.T) { + require.Equal(t, tt.want, types.GetHistoricalInfoKey(tt.height)) + }) + } +} diff --git a/x/staking/types/msg.go b/x/staking/types/msg.go index 1cd7767266aa..6899e5e35f95 100644 --- a/x/staking/types/msg.go +++ b/x/staking/types/msg.go @@ -33,7 +33,7 @@ var ( // NewMsgCreateValidator creates a new MsgCreateValidator instance. // Delegator address and validator address are the same. func NewMsgCreateValidator( - valAddr sdk.ValAddress, pubKey cryptotypes.PubKey, //nolint:interfacer + valAddr sdk.ValAddress, pubKey cryptotypes.PubKey, selfDelegation sdk.Coin, description Description, commission CommissionRates, minSelfDelegation math.Int, ) (*MsgCreateValidator, error) { var pkAny *codectypes.Any @@ -71,8 +71,8 @@ func (msg MsgCreateValidator) GetSignBytes() []byte { return sdk.MustSortJSON(bz) } -// ValidateBasic implements the sdk.Msg interface. -func (msg MsgCreateValidator) ValidateBasic() error { +// Validate validates the MsgCreateValidator sdk msg. +func (msg MsgCreateValidator) Validate() error { // note that unmarshaling from bech32 ensures both non-empty and valid _, err := sdk.ValAddressFromBech32(msg.ValidatorAddress) if err != nil { @@ -120,8 +120,6 @@ func (msg MsgCreateValidator) UnpackInterfaces(unpacker codectypes.AnyUnpacker) } // NewMsgEditValidator creates a new MsgEditValidator instance -// -//nolint:interfacer func NewMsgEditValidator(valAddr sdk.ValAddress, description Description, newRate *sdk.Dec, newMinSelfDelegation *math.Int) *MsgEditValidator { return &MsgEditValidator{ Description: description, @@ -143,35 +141,7 @@ func (msg MsgEditValidator) GetSignBytes() []byte { return sdk.MustSortJSON(bz) } -// ValidateBasic implements the sdk.Msg interface. -func (msg MsgEditValidator) ValidateBasic() error { - if _, err := sdk.ValAddressFromBech32(msg.ValidatorAddress); err != nil { - return sdkerrors.ErrInvalidAddress.Wrapf("invalid validator address: %s", err) - } - - if msg.Description == (Description{}) { - return errorsmod.Wrap(sdkerrors.ErrInvalidRequest, "empty description") - } - - if msg.MinSelfDelegation != nil && !msg.MinSelfDelegation.IsPositive() { - return errorsmod.Wrap( - sdkerrors.ErrInvalidRequest, - "minimum self delegation must be a positive integer", - ) - } - - if msg.CommissionRate != nil { - if msg.CommissionRate.GT(math.LegacyOneDec()) || msg.CommissionRate.IsNegative() { - return errorsmod.Wrap(sdkerrors.ErrInvalidRequest, "commission rate must be between 0 and 1 (inclusive)") - } - } - - return nil -} - // NewMsgDelegate creates a new MsgDelegate instance. -// -//nolint:interfacer func NewMsgDelegate(delAddr sdk.AccAddress, valAddr sdk.ValAddress, amount sdk.Coin) *MsgDelegate { return &MsgDelegate{ DelegatorAddress: delAddr.String(), @@ -192,28 +162,7 @@ func (msg MsgDelegate) GetSignBytes() []byte { return sdk.MustSortJSON(bz) } -// ValidateBasic implements the sdk.Msg interface. -func (msg MsgDelegate) ValidateBasic() error { - if _, err := sdk.AccAddressFromBech32(msg.DelegatorAddress); err != nil { - return sdkerrors.ErrInvalidAddress.Wrapf("invalid delegator address: %s", err) - } - if _, err := sdk.ValAddressFromBech32(msg.ValidatorAddress); err != nil { - return sdkerrors.ErrInvalidAddress.Wrapf("invalid validator address: %s", err) - } - - if !msg.Amount.IsValid() || !msg.Amount.Amount.IsPositive() { - return errorsmod.Wrap( - sdkerrors.ErrInvalidRequest, - "invalid delegation amount", - ) - } - - return nil -} - // NewMsgBeginRedelegate creates a new MsgBeginRedelegate instance. -// -//nolint:interfacer func NewMsgBeginRedelegate( delAddr sdk.AccAddress, valSrcAddr, valDstAddr sdk.ValAddress, amount sdk.Coin, ) *MsgBeginRedelegate { @@ -237,31 +186,7 @@ func (msg MsgBeginRedelegate) GetSignBytes() []byte { return sdk.MustSortJSON(bz) } -// ValidateBasic implements the sdk.Msg interface. -func (msg MsgBeginRedelegate) ValidateBasic() error { - if _, err := sdk.AccAddressFromBech32(msg.DelegatorAddress); err != nil { - return sdkerrors.ErrInvalidAddress.Wrapf("invalid delegator address: %s", err) - } - if _, err := sdk.ValAddressFromBech32(msg.ValidatorSrcAddress); err != nil { - return sdkerrors.ErrInvalidAddress.Wrapf("invalid source validator address: %s", err) - } - if _, err := sdk.ValAddressFromBech32(msg.ValidatorDstAddress); err != nil { - return sdkerrors.ErrInvalidAddress.Wrapf("invalid destination validator address: %s", err) - } - - if !msg.Amount.IsValid() || !msg.Amount.Amount.IsPositive() { - return errorsmod.Wrap( - sdkerrors.ErrInvalidRequest, - "invalid shares amount", - ) - } - - return nil -} - // NewMsgUndelegate creates a new MsgUndelegate instance. -// -//nolint:interfacer func NewMsgUndelegate(delAddr sdk.AccAddress, valAddr sdk.ValAddress, amount sdk.Coin) *MsgUndelegate { return &MsgUndelegate{ DelegatorAddress: delAddr.String(), @@ -282,28 +207,7 @@ func (msg MsgUndelegate) GetSignBytes() []byte { return sdk.MustSortJSON(bz) } -// ValidateBasic implements the sdk.Msg interface. -func (msg MsgUndelegate) ValidateBasic() error { - if _, err := sdk.AccAddressFromBech32(msg.DelegatorAddress); err != nil { - return sdkerrors.ErrInvalidAddress.Wrapf("invalid delegator address: %s", err) - } - if _, err := sdk.ValAddressFromBech32(msg.ValidatorAddress); err != nil { - return sdkerrors.ErrInvalidAddress.Wrapf("invalid validator address: %s", err) - } - - if !msg.Amount.IsValid() || !msg.Amount.Amount.IsPositive() { - return errorsmod.Wrap( - sdkerrors.ErrInvalidRequest, - "invalid shares amount", - ) - } - - return nil -} - // NewMsgCancelUnbondingDelegation creates a new MsgCancelUnbondingDelegation instance. -// -//nolint:interfacer func NewMsgCancelUnbondingDelegation(delAddr sdk.AccAddress, valAddr sdk.ValAddress, creationHeight int64, amount sdk.Coin) *MsgCancelUnbondingDelegation { return &MsgCancelUnbondingDelegation{ DelegatorAddress: delAddr.String(), @@ -324,32 +228,6 @@ func (msg MsgCancelUnbondingDelegation) GetSignBytes() []byte { return sdk.MustSortJSON(ModuleCdc.MustMarshalJSON(&msg)) } -// ValidateBasic implements the sdk.Msg interface. -func (msg MsgCancelUnbondingDelegation) ValidateBasic() error { - if _, err := sdk.AccAddressFromBech32(msg.DelegatorAddress); err != nil { - return sdkerrors.ErrInvalidAddress.Wrapf("invalid delegator address: %s", err) - } - if _, err := sdk.ValAddressFromBech32(msg.ValidatorAddress); err != nil { - return sdkerrors.ErrInvalidAddress.Wrapf("invalid validator address: %s", err) - } - - if !msg.Amount.IsValid() || !msg.Amount.Amount.IsPositive() { - return errorsmod.Wrap( - sdkerrors.ErrInvalidRequest, - "invalid amount", - ) - } - - if msg.CreationHeight <= 0 { - return errorsmod.Wrap( - sdkerrors.ErrInvalidRequest, - "invalid height", - ) - } - - return nil -} - // GetSignBytes returns the raw bytes for a MsgUpdateParams message that // the expected signer needs to sign. func (m MsgUpdateParams) GetSignBytes() []byte { @@ -357,14 +235,6 @@ func (m MsgUpdateParams) GetSignBytes() []byte { return sdk.MustSortJSON(bz) } -// ValidateBasic executes sanity validation on the provided data -func (m MsgUpdateParams) ValidateBasic() error { - if _, err := sdk.AccAddressFromBech32(m.Authority); err != nil { - return errorsmod.Wrap(err, "invalid authority address") - } - return m.Params.Validate() -} - // GetSigners returns the expected signers for a MsgUpdateParams message func (m MsgUpdateParams) GetSigners() []sdk.AccAddress { addr, _ := sdk.AccAddressFromBech32(m.Authority) diff --git a/x/staking/types/msg_test.go b/x/staking/types/msg_test.go index 428e25c95594..a59a897bc42a 100644 --- a/x/staking/types/msg_test.go +++ b/x/staking/types/msg_test.go @@ -2,11 +2,8 @@ package types_test import ( "testing" - "time" "cosmossdk.io/math" - authtypes "github.com/cosmos/cosmos-sdk/x/auth/types" - govtypes "github.com/cosmos/cosmos-sdk/x/gov/types" "github.com/stretchr/testify/require" @@ -19,10 +16,7 @@ import ( "github.com/cosmos/cosmos-sdk/x/staking/types" ) -var ( - coinPos = sdk.NewInt64Coin(sdk.DefaultBondDenom, 1000) - coinZero = sdk.NewInt64Coin(sdk.DefaultBondDenom, 0) -) +var coinPos = sdk.NewInt64Coin(sdk.DefaultBondDenom, 1000) func TestMsgDecode(t *testing.T) { registry := codectypes.NewInterfaceRegistry() @@ -55,300 +49,3 @@ func TestMsgDecode(t *testing.T) { require.True(t, msg.Value.IsEqual(msg2.Value)) require.True(t, msg.Pubkey.Equal(msg2.Pubkey)) } - -// test ValidateBasic for MsgCreateValidator -func TestMsgCreateValidator(t *testing.T) { - commission1 := types.NewCommissionRates(math.LegacyZeroDec(), math.LegacyZeroDec(), math.LegacyZeroDec()) - commission2 := types.NewCommissionRates(math.LegacyNewDec(5), math.LegacyNewDec(5), math.LegacyNewDec(5)) - - tests := []struct { - name, moniker, identity, website, securityContact, details string - CommissionRates types.CommissionRates - minSelfDelegation math.Int - validatorAddr sdk.ValAddress - pubkey cryptotypes.PubKey - bond sdk.Coin - expectPass bool - }{ - {"basic good", "a", "b", "c", "d", "e", commission1, math.OneInt(), valAddr1, pk1, coinPos, true}, - {"partial description", "", "", "c", "", "", commission1, math.OneInt(), valAddr1, pk1, coinPos, true}, - {"empty description", "", "", "", "", "", commission2, math.OneInt(), valAddr1, pk1, coinPos, false}, - {"empty address", "a", "b", "c", "d", "e", commission2, math.OneInt(), emptyAddr, pk1, coinPos, false}, - {"empty pubkey", "a", "b", "c", "d", "e", commission1, math.OneInt(), valAddr1, emptyPubkey, coinPos, false}, - {"empty bond", "a", "b", "c", "d", "e", commission2, math.OneInt(), valAddr1, pk1, coinZero, false}, - {"nil bond", "a", "b", "c", "d", "e", commission2, math.OneInt(), valAddr1, pk1, sdk.Coin{}, false}, - {"zero min self delegation", "a", "b", "c", "d", "e", commission1, math.ZeroInt(), valAddr1, pk1, coinPos, false}, - {"negative min self delegation", "a", "b", "c", "d", "e", commission1, sdk.NewInt(-1), valAddr1, pk1, coinPos, false}, - {"delegation less than min self delegation", "a", "b", "c", "d", "e", commission1, coinPos.Amount.Add(math.OneInt()), valAddr1, pk1, coinPos, false}, - } - - for _, tc := range tests { - description := types.NewDescription(tc.moniker, tc.identity, tc.website, tc.securityContact, tc.details) - msg, err := types.NewMsgCreateValidator(tc.validatorAddr, tc.pubkey, tc.bond, description, tc.CommissionRates, tc.minSelfDelegation) - require.NoError(t, err) - if tc.expectPass { - require.Nil(t, msg.ValidateBasic(), "test: %v", tc.name) - } else { - require.NotNil(t, msg.ValidateBasic(), "test: %v", tc.name) - } - } -} - -// test ValidateBasic for MsgEditValidator -func TestMsgEditValidator(t *testing.T) { - tests := []struct { - name, moniker, identity, website, securityContact, details string - validatorAddr sdk.ValAddress - expectPass bool - minSelfDelegation math.Int - }{ - {"basic good", "a", "b", "c", "d", "e", valAddr1, true, math.OneInt()}, - {"partial description", "", "", "c", "", "", valAddr1, true, math.OneInt()}, - {"empty description", "", "", "", "", "", valAddr1, false, math.OneInt()}, - {"empty address", "a", "b", "c", "d", "e", emptyAddr, false, math.OneInt()}, - {"nil int", "a", "b", "c", "d", "e", emptyAddr, false, math.Int{}}, - } - - for _, tc := range tests { - description := types.NewDescription(tc.moniker, tc.identity, tc.website, tc.securityContact, tc.details) - newRate := math.LegacyZeroDec() - - msg := types.NewMsgEditValidator(tc.validatorAddr, description, &newRate, &tc.minSelfDelegation) - if tc.expectPass { - require.Nil(t, msg.ValidateBasic(), "test: %v", tc.name) - } else { - require.NotNil(t, msg.ValidateBasic(), "test: %v", tc.name) - } - } -} - -// test ValidateBasic for MsgDelegate -func TestMsgDelegate(t *testing.T) { - tests := []struct { - name string - delegatorAddr sdk.AccAddress - validatorAddr sdk.ValAddress - bond sdk.Coin - expectPass bool - }{ - {"basic good", sdk.AccAddress(valAddr1), valAddr2, coinPos, true}, - {"self bond", sdk.AccAddress(valAddr1), valAddr1, coinPos, true}, - {"empty delegator", sdk.AccAddress(emptyAddr), valAddr1, coinPos, false}, - {"empty validator", sdk.AccAddress(valAddr1), emptyAddr, coinPos, false}, - {"empty bond", sdk.AccAddress(valAddr1), valAddr2, coinZero, false}, - {"nil bold", sdk.AccAddress(valAddr1), valAddr2, sdk.Coin{}, false}, - } - - for _, tc := range tests { - msg := types.NewMsgDelegate(tc.delegatorAddr, tc.validatorAddr, tc.bond) - if tc.expectPass { - require.Nil(t, msg.ValidateBasic(), "test: %v", tc.name) - } else { - require.NotNil(t, msg.ValidateBasic(), "test: %v", tc.name) - } - } -} - -// test ValidateBasic for MsgUnbond -func TestMsgBeginRedelegate(t *testing.T) { - tests := []struct { - name string - delegatorAddr sdk.AccAddress - validatorSrcAddr sdk.ValAddress - validatorDstAddr sdk.ValAddress - amount sdk.Coin - expectPass bool - }{ - {"regular", sdk.AccAddress(valAddr1), valAddr2, valAddr3, sdk.NewInt64Coin(sdk.DefaultBondDenom, 1), true}, - {"zero amount", sdk.AccAddress(valAddr1), valAddr2, valAddr3, sdk.NewInt64Coin(sdk.DefaultBondDenom, 0), false}, - {"nil amount", sdk.AccAddress(valAddr1), valAddr2, valAddr3, sdk.Coin{}, false}, - {"empty delegator", sdk.AccAddress(emptyAddr), valAddr1, valAddr3, sdk.NewInt64Coin(sdk.DefaultBondDenom, 1), false}, - {"empty source validator", sdk.AccAddress(valAddr1), emptyAddr, valAddr3, sdk.NewInt64Coin(sdk.DefaultBondDenom, 1), false}, - {"empty destination validator", sdk.AccAddress(valAddr1), valAddr2, emptyAddr, sdk.NewInt64Coin(sdk.DefaultBondDenom, 1), false}, - } - - for _, tc := range tests { - msg := types.NewMsgBeginRedelegate(tc.delegatorAddr, tc.validatorSrcAddr, tc.validatorDstAddr, tc.amount) - if tc.expectPass { - require.Nil(t, msg.ValidateBasic(), "test: %v", tc.name) - } else { - require.NotNil(t, msg.ValidateBasic(), "test: %v", tc.name) - } - } -} - -// test ValidateBasic for MsgUnbond -func TestMsgUndelegate(t *testing.T) { - tests := []struct { - name string - delegatorAddr sdk.AccAddress - validatorAddr sdk.ValAddress - amount sdk.Coin - expectPass bool - }{ - {"regular", sdk.AccAddress(valAddr1), valAddr2, sdk.NewInt64Coin(sdk.DefaultBondDenom, 1), true}, - {"zero amount", sdk.AccAddress(valAddr1), valAddr2, sdk.NewInt64Coin(sdk.DefaultBondDenom, 0), false}, - {"nil amount", sdk.AccAddress(valAddr1), valAddr2, sdk.Coin{}, false}, - {"empty delegator", sdk.AccAddress(emptyAddr), valAddr1, sdk.NewInt64Coin(sdk.DefaultBondDenom, 1), false}, - {"empty validator", sdk.AccAddress(valAddr1), emptyAddr, sdk.NewInt64Coin(sdk.DefaultBondDenom, 1), false}, - } - - for _, tc := range tests { - msg := types.NewMsgUndelegate(tc.delegatorAddr, tc.validatorAddr, tc.amount) - if tc.expectPass { - require.Nil(t, msg.ValidateBasic(), "test: %v", tc.name) - } else { - require.NotNil(t, msg.ValidateBasic(), "test: %v", tc.name) - } - } -} - -func TestMsgUpdateParams(t *testing.T) { - msg := types.MsgUpdateParams{ - Authority: authtypes.NewModuleAddress(govtypes.ModuleName).String(), - Params: types.DefaultParams(), - } - - require.Equal(t, []sdk.AccAddress{authtypes.NewModuleAddress(govtypes.ModuleName)}, msg.GetSigners()) -} - -func TestMsgUpdateParamsValidateBasic(t *testing.T) { - tests := []struct { - name string - msgUpdateParams types.MsgUpdateParams - expFail bool - expError string - }{ - { - "valid msg", - types.MsgUpdateParams{ - Authority: authtypes.NewModuleAddress(govtypes.ModuleName).String(), - Params: types.DefaultParams(), - }, - false, - "", - }, - { - "negative unbounding time", - types.MsgUpdateParams{ - Authority: authtypes.NewModuleAddress(govtypes.ModuleName).String(), - Params: types.Params{ - UnbondingTime: time.Hour * 24 * 7 * 3 * -1, - MaxEntries: types.DefaultMaxEntries, - MaxValidators: types.DefaultMaxValidators, - HistoricalEntries: types.DefaultHistoricalEntries, - MinCommissionRate: types.DefaultMinCommissionRate, - BondDenom: "denom", - }, - }, - true, - "unbonding time must be positive:", - }, - { - "cero value max validator", - types.MsgUpdateParams{ - Authority: authtypes.NewModuleAddress(govtypes.ModuleName).String(), - Params: types.Params{ - UnbondingTime: time.Hour * 24 * 7 * 3, - MaxEntries: types.DefaultMaxEntries, - MaxValidators: 0, - HistoricalEntries: types.DefaultHistoricalEntries, - MinCommissionRate: types.DefaultMinCommissionRate, - BondDenom: "denom", - }, - }, - true, - "max validators must be positive:", - }, - { - "cero value max validator", - types.MsgUpdateParams{ - Authority: authtypes.NewModuleAddress(govtypes.ModuleName).String(), - Params: types.Params{ - UnbondingTime: time.Hour * 24 * 7 * 3, - MaxEntries: 0, - MaxValidators: types.DefaultMaxValidators, - HistoricalEntries: types.DefaultHistoricalEntries, - MinCommissionRate: types.DefaultMinCommissionRate, - BondDenom: "denom", - }, - }, - true, - "max entries must be positive:", - }, - { - "negative commission rate", - types.MsgUpdateParams{ - Authority: authtypes.NewModuleAddress(govtypes.ModuleName).String(), - Params: types.Params{ - UnbondingTime: time.Hour * 24 * 7 * 3, - MaxEntries: types.DefaultMaxEntries, - MaxValidators: types.DefaultMaxValidators, - HistoricalEntries: types.DefaultHistoricalEntries, - MinCommissionRate: math.LegacyNewDec(-1), - BondDenom: "denom", - }, - }, - true, - "minimum commission rate cannot be negative:", - }, - { - "negative commission rate", - types.MsgUpdateParams{ - Authority: authtypes.NewModuleAddress(govtypes.ModuleName).String(), - Params: types.Params{ - UnbondingTime: time.Hour * 24 * 7 * 3, - MaxEntries: types.DefaultMaxEntries, - MaxValidators: types.DefaultMaxValidators, - HistoricalEntries: types.DefaultHistoricalEntries, - MinCommissionRate: math.LegacyNewDec(2), - BondDenom: "denom", - }, - }, - true, - "minimum commission rate cannot be greater than 100", - }, - { - "blank bonddenom", - types.MsgUpdateParams{ - Authority: authtypes.NewModuleAddress(govtypes.ModuleName).String(), - Params: types.Params{ - UnbondingTime: time.Hour * 24 * 7 * 3, - MaxEntries: types.DefaultMaxEntries, - MaxValidators: types.DefaultMaxValidators, - HistoricalEntries: types.DefaultHistoricalEntries, - MinCommissionRate: types.DefaultMinCommissionRate, - BondDenom: "", - }, - }, - true, - "bond denom cannot be blank", - }, - { - "Invalid authority", - types.MsgUpdateParams{ - Authority: "invalid", - Params: types.Params{ - UnbondingTime: time.Hour * 24 * 7 * 3, - MaxEntries: types.DefaultMaxEntries, - MaxValidators: types.DefaultMaxValidators, - HistoricalEntries: types.DefaultHistoricalEntries, - MinCommissionRate: types.DefaultMinCommissionRate, - BondDenom: "denom", - }, - }, - true, - "invalid authority address", - }, - } - - for _, tc := range tests { - err := tc.msgUpdateParams.ValidateBasic() - if tc.expFail { - require.Error(t, err) - require.Contains(t, err.Error(), tc.expError) - } else { - require.NoError(t, err) - } - } -} diff --git a/x/staking/types/params_legacy.go b/x/staking/types/params_legacy.go index df474c02ffa1..f2ab55624976 100644 --- a/x/staking/types/params_legacy.go +++ b/x/staking/types/params_legacy.go @@ -13,14 +13,13 @@ var ( var _ paramtypes.ParamSet = (*Params)(nil) -// ParamTable for staking module // Deprecated: now params can be accessed on key `0x51` on the staking store. +// ParamTable for staking module func ParamKeyTable() paramtypes.KeyTable { return paramtypes.NewKeyTable().RegisterParamSet(&Params{}) } -// Implements params.ParamSet -// Deprecated. +// Deprecated: Implements params.ParamSet func (p *Params) ParamSetPairs() paramtypes.ParamSetPairs { return paramtypes.ParamSetPairs{ paramtypes.NewParamSetPair(KeyUnbondingTime, &p.UnbondingTime, validateUnbondingTime), diff --git a/x/staking/types/validator.go b/x/staking/types/validator.go index c763998dc7d1..1b55f7120cf2 100644 --- a/x/staking/types/validator.go +++ b/x/staking/types/validator.go @@ -39,8 +39,6 @@ var ( var _ ValidatorI = Validator{} // NewValidator constructs a new Validator -// -//nolint:interfacer func NewValidator(operator sdk.ValAddress, pubKey cryptotypes.PubKey, description Description) (Validator, error) { pkAny, err := codectypes.NewAnyWithValue(pubKey) if err != nil { diff --git a/x/staking/types/validator_test.go b/x/staking/types/validator_test.go index 6a005cce7622..1150fbed6146 100644 --- a/x/staking/types/validator_test.go +++ b/x/staking/types/validator_test.go @@ -261,9 +261,7 @@ func TestValidatorsSortDeterminism(t *testing.T) { // Randomly shuffle validators, sort, and check it is equal to original sort for i := 0; i < 10; i++ { rand.Shuffle(10, func(i, j int) { - it := vals[i] //nolint:gocritic - vals[i] = vals[j] - vals[j] = it + vals[i], vals[j] = vals[j], vals[i] }) types.Validators(vals).Sort() diff --git a/x/tx/CHANGELOG.md b/x/tx/CHANGELOG.md index baf46b9f622c..5a8fafb2a10c 100644 --- a/x/tx/CHANGELOG.md +++ b/x/tx/CHANGELOG.md @@ -29,15 +29,48 @@ Ref: https://keepachangelog.com/en/1.0.0/ # Changelog -## [Unreleased] +## Unreleased -## API Breaking +### API Breaking + +* [#15709](https://github.com/cosmos/cosmos-sdk/pull/15709): + * `GetSignersContext` has been renamed to `signing.Context` + * `GetSigners` now returns `[][]byte` instead of `[]string` + * `GetSignersOptions` has been renamed to `signing.Options` and requires `address.Codec`s for account and validator addresses + * `GetSignersOptions.ProtoFiles` has been renamed to `signing.Options.FileResolver` + +### Bug Fixes +* [#15849](https://github.com/cosmos/cosmos-sdk/pull/15849) Fix int64 usage for 32 bit platforms. + +## v0.5.1 + +### Features + +* [#15414](https://github.com/cosmos/cosmos-sdk/pull/15414) Add basic transaction decoding support. + +## v0.5.0 + +### API Breaking + +* [#15581](https://github.com/cosmos/cosmos-sdk/pull/15581) `GetSignersOptions` and `directaux.SignModeHandlerOptions` now +require a `signing.ProtoFileResolver` interface instead of `protodesc.Resolver`. +* [#15742](https://github.com/cosmos/cosmos-sdk/pull/15742) The `direct_aux` package has been renamed to `directaux` in line with Go conventions. No other types were changed during the package rename. +* [#15748](https://github.com/cosmos/cosmos-sdk/pull/15748) Rename signing.SignerData.ChainId to .ChainID, in line with Go conventions. + +### Bug Fixes + +* (signing/textual) [#15730](https://github.com/cosmos/cosmos-sdk/pull/15730) make IntValueRenderer.Parse: gracefully handle "" + fuzz + +## v0.4.0 + +### API Breaking * [#13793](https://github.com/cosmos/cosmos-sdk/pull/13793) `direct_aux.NewSignModeHandler` constructor function now returns an additional error argument. * [#15278](https://github.com/cosmos/cosmos-sdk/pull/15278) Move `x/tx/{textual,aminojson}` into `x/tx/signing`. * [#15302](https://github.com/cosmos/cosmos-sdk/pull/15302) `textual.NewSignModeHandler` now takes an options struct instead of a simple coin querier argument. It also returns an error. -## Improvements +### Improvements * [#15302](https://github.com/cosmos/cosmos-sdk/pull/15302) Add support for a custom registry (e.g. gogo's MergedRegistry) to be plugged into SIGN_MODE_TEXTUAL. - +* [#15557](https://github.com/cosmos/cosmos-sdk/pull/15557) Implement unknown field filtering. +* [#15515](https://github.com/cosmos/cosmos-sdk/pull/15515) Implement SIGN_MODE_LEGACY_AMINO_JSON handler. diff --git a/x/tx/Makefile b/x/tx/Makefile index 9ca0b828981d..7fd7077787f8 100644 --- a/x/tx/Makefile +++ b/x/tx/Makefile @@ -1,2 +1,3 @@ codegen: @(cd internal/testpb; buf generate) + @(cd signing/aminojson/internal; make codegen) \ No newline at end of file diff --git a/x/tx/decode/adr027.go b/x/tx/decode/adr027.go new file mode 100644 index 000000000000..0588acbaa9fd --- /dev/null +++ b/x/tx/decode/adr027.go @@ -0,0 +1,88 @@ +package decode + +import ( + "fmt" + + "google.golang.org/protobuf/encoding/protowire" +) + +// rejectNonADR027TxRaw rejects txBytes that do not follow ADR-027. This is NOT +// a generic ADR-027 checker, it only applies decoding TxRaw. Specifically, it +// only checks that: +// +// - Field numbers are in ascending order (1, 2, and potentially multiple 3s) +// - Varints are as short as possible +// +// All other ADR-027 edge cases (e.g. default values) are not applicable with +// TxRaw. +func rejectNonADR027TxRaw(txBytes []byte) error { + // Make sure all fields are ordered in ascending order with this variable. + prevTagNum := protowire.Number(0) + + for len(txBytes) > 0 { + tagNum, wireType, m := protowire.ConsumeTag(txBytes) + if m < 0 { + return fmt.Errorf("invalid length; %w", protowire.ParseError(m)) + } + // TxRaw only has bytes fields. + if wireType != protowire.BytesType { + return fmt.Errorf("expected %d wire type, got %d", protowire.BytesType, wireType) + } + // Make sure fields are ordered in ascending order. + if tagNum < prevTagNum { + return fmt.Errorf("txRaw must follow ADR-027, got tagNum %d after tagNum %d", tagNum, prevTagNum) + } + prevTagNum = tagNum + + // All 3 fields of TxRaw have wireType == 2, so their next component + // is a varint, so we can safely call ConsumeVarint here. + // Byte structure: + // Inner fields are verified in `DefaultTxDecoder` + lengthPrefix, m := protowire.ConsumeVarint(txBytes[m:]) + if m < 0 { + return fmt.Errorf("invalid length; %w", protowire.ParseError(m)) + } + // We make sure that this varint is as short as possible. + n := varintMinLength(lengthPrefix) + if n != m { + return fmt.Errorf("length prefix varint for tagNum %d is not as short as possible, read %d, only need %d", tagNum, m, n) + } + + // Skip over the bytes that store fieldNumber and wireType bytes. + _, _, m = protowire.ConsumeField(txBytes) + if m < 0 { + return fmt.Errorf("invalid length; %w", protowire.ParseError(m)) + } + txBytes = txBytes[m:] + } + + return nil +} + +// varintMinLength returns the minimum number of bytes necessary to encode an +// uint using varint encoding. +func varintMinLength(n uint64) int { + switch { + // Note: 1< 0 { + tagNum, wireType, m := protowire.ConsumeTag(bz) + if m < 0 { + return hasUnknownNonCriticals, errors.New("invalid length") + } + + fieldDesc := fields.ByNumber(tagNum) + if fieldDesc == nil { + isCriticalField := tagNum&bit11NonCritical == 0 + + if !isCriticalField { + hasUnknownNonCriticals = true + } + + if isCriticalField || !allowUnknownNonCriticals { + // The tag is critical, so report it. + return hasUnknownNonCriticals, ErrUnknownField.Wrapf( + "%s: {TagNum: %d, WireType:%q}", + desc.FullName(), tagNum, WireTypeToString(wireType)) + } + } + + // Skip over the bytes that store fieldNumber and wireType bytes. + bz = bz[m:] + n := protowire.ConsumeFieldValue(tagNum, wireType, bz) + if n < 0 { + err = fmt.Errorf("could not consume field value for tagNum: %d, wireType: %q; %w", + tagNum, WireTypeToString(wireType), protowire.ParseError(n)) + return hasUnknownNonCriticals, err + } + fieldBytes := bz[:n] + bz = bz[n:] + + // An unknown but non-critical field + if fieldDesc == nil { + continue + } + + fieldMessage := fieldDesc.Message() + // not message or group kind + if fieldMessage == nil { + continue + } + + // consume length prefix of nested message + _, o := protowire.ConsumeVarint(fieldBytes) + fieldBytes = fieldBytes[o:] + + var err error + + if fieldMessage.FullName() == anyFullName { + // Firstly typecheck types.Any to ensure nothing snuck in. + hasUnknownNonCriticalsChild, err := RejectUnknownFields(fieldBytes, anyDesc, allowUnknownNonCriticals, resolver) + hasUnknownNonCriticals = hasUnknownNonCriticals || hasUnknownNonCriticalsChild + if err != nil { + return hasUnknownNonCriticals, err + } + var a anypb.Any + if err = proto.Unmarshal(fieldBytes, &a); err != nil { + return hasUnknownNonCriticals, err + } + + msgName := protoreflect.FullName(strings.TrimPrefix(a.TypeUrl, "/")) + msgDesc, err := resolver.FindDescriptorByName(msgName) + if err != nil { + return hasUnknownNonCriticals, err + } + + fieldMessage = msgDesc.(protoreflect.MessageDescriptor) + fieldBytes = a.Value + } + + hasUnknownNonCriticalsChild, err := RejectUnknownFields(fieldBytes, fieldMessage, allowUnknownNonCriticals, resolver) + hasUnknownNonCriticals = hasUnknownNonCriticals || hasUnknownNonCriticalsChild + if err != nil { + return hasUnknownNonCriticals, err + } + } + + return hasUnknownNonCriticals, nil +} + +// errUnknownField represents an error indicating that we encountered +// a field that isn't available in the target proto.Message. +type errUnknownField struct { + Desc protoreflect.MessageDescriptor + TagNum protowire.Number + WireType protowire.Type +} + +// String implements fmt.Stringer. +func (twt *errUnknownField) String() string { + return fmt.Sprintf("errUnknownField %q: {TagNum: %d, WireType:%q}", + twt.Desc.FullName(), twt.TagNum, WireTypeToString(twt.WireType)) +} + +// Error implements the error interface. +func (twt *errUnknownField) Error() string { + return twt.String() +} + +var _ error = (*errUnknownField)(nil) + +// WireTypeToString returns a string representation of the given protowire.Type. +func WireTypeToString(wt protowire.Type) string { + switch wt { + case 0: + return "varint" + case 1: + return "fixed64" + case 2: + return "bytes" + case 3: + return "start_group" + case 4: + return "end_group" + case 5: + return "fixed32" + default: + return fmt.Sprintf("unknown type: %d", wt) + } +} diff --git a/x/tx/decode/unknown_test.go b/x/tx/decode/unknown_test.go new file mode 100644 index 000000000000..dddabbb40267 --- /dev/null +++ b/x/tx/decode/unknown_test.go @@ -0,0 +1,668 @@ +package decode_test + +import ( + "errors" + "testing" + + "github.com/stretchr/testify/require" + "google.golang.org/protobuf/encoding/protowire" + "google.golang.org/protobuf/proto" + "google.golang.org/protobuf/reflect/protoregistry" + "google.golang.org/protobuf/types/known/anypb" + + "cosmossdk.io/x/tx/decode" + "cosmossdk.io/x/tx/internal/testpb" +) + +func errUnknownField(typ string, tagNum int, wireType protowire.Type) error { + var wt string + if wireType >= 0 && wireType < 6 { + wt = decode.WireTypeToString(wireType) + } + return decode.ErrUnknownField.Wrapf("%s: {TagNum: %d, WireType:%q}", typ, tagNum, wt) +} + +var ProtoResolver = protoregistry.GlobalFiles + +func TestRejectUnknownFieldsRepeated(t *testing.T) { + tests := []struct { + name string + in proto.Message + recv proto.Message + wantErr error + allowUnknownNonCriticals bool + hasUnknownNonCriticals bool + }{ + { + name: "Unknown field in midst of repeated values", + in: &testpb.TestVersion2{ + C: []*testpb.TestVersion2{ + { + C: []*testpb.TestVersion2{ + { + Sum: &testpb.TestVersion2_F{ + F: &testpb.TestVersion2{ + A: &testpb.TestVersion2{ + B: &testpb.TestVersion2{ + H: []*testpb.TestVersion1{ + { + X: 0x01, + }, + }, + }, + }, + }, + }, + }, + { + Sum: &testpb.TestVersion2_F{ + F: &testpb.TestVersion2{ + A: &testpb.TestVersion2{ + B: &testpb.TestVersion2{ + H: []*testpb.TestVersion1{ + { + X: 0x02, + }, + }, + }, + }, + }, + }, + }, + { + Sum: &testpb.TestVersion2_F{ + F: &testpb.TestVersion2{ + NewField_: 411, + }, + }, + }, + }, + }, + }, + }, + recv: new(testpb.TestVersion1), + wantErr: errUnknownField( + "testpb.TestVersion1", + 25, + 0), + }, + { + name: "Unknown field in midst of repeated values, allowUnknownNonCriticals set", + allowUnknownNonCriticals: true, + in: &testpb.TestVersion2{ + C: []*testpb.TestVersion2{ + { + C: []*testpb.TestVersion2{ + { + Sum: &testpb.TestVersion2_F{ + F: &testpb.TestVersion2{ + A: &testpb.TestVersion2{ + B: &testpb.TestVersion2{ + H: []*testpb.TestVersion1{ + { + X: 0x01, + }, + }, + }, + }, + }, + }, + }, + { + Sum: &testpb.TestVersion2_F{ + F: &testpb.TestVersion2{ + A: &testpb.TestVersion2{ + B: &testpb.TestVersion2{ + H: []*testpb.TestVersion1{ + { + X: 0x02, + }, + }, + }, + }, + }, + }, + }, + { + Sum: &testpb.TestVersion2_F{ + F: &testpb.TestVersion2{ + NewField_: 411, + }, + }, + }, + }, + }, + }, + }, + recv: new(testpb.TestVersion1), + wantErr: errUnknownField( + "testpb.TestVersion1", + 25, + 0), + }, + { + name: "Unknown field in midst of repeated values, non-critical field to be rejected", + in: &testpb.TestVersion3{ + C: []*testpb.TestVersion3{ + { + C: []*testpb.TestVersion3{ + { + Sum: &testpb.TestVersion3_F{ + F: &testpb.TestVersion3{ + A: &testpb.TestVersion3{ + B: &testpb.TestVersion3{ + X: 0x01, + }, + }, + }, + }, + }, + { + Sum: &testpb.TestVersion3_F{ + F: &testpb.TestVersion3{ + A: &testpb.TestVersion3{ + B: &testpb.TestVersion3{ + X: 0x02, + }, + }, + }, + }, + }, + { + Sum: &testpb.TestVersion3_F{ + F: &testpb.TestVersion3{ + NonCriticalField: "non-critical", + }, + }, + }, + }, + }, + }, + }, + recv: new(testpb.TestVersion1), + wantErr: errUnknownField( + "testpb.TestVersion1", + 1031, + 2), + hasUnknownNonCriticals: true, + }, + { + name: "Unknown field in midst of repeated values, non-critical field ignored", + allowUnknownNonCriticals: true, + in: &testpb.TestVersion3{ + C: []*testpb.TestVersion3{ + { + C: []*testpb.TestVersion3{ + { + Sum: &testpb.TestVersion3_F{ + F: &testpb.TestVersion3{ + A: &testpb.TestVersion3{ + B: &testpb.TestVersion3{ + X: 0x01, + }, + }, + }, + }, + }, + { + Sum: &testpb.TestVersion3_F{ + F: &testpb.TestVersion3{ + A: &testpb.TestVersion3{ + B: &testpb.TestVersion3{ + X: 0x02, + }, + }, + }, + }, + }, + { + Sum: &testpb.TestVersion3_F{ + F: &testpb.TestVersion3{ + NonCriticalField: "non-critical", + }, + }, + }, + }, + }, + }, + }, + recv: new(testpb.TestVersion1), + wantErr: nil, + hasUnknownNonCriticals: true, + }, + } + + for _, tt := range tests { + tt := tt + t.Run(tt.name, func(t *testing.T) { + protoBlob, err := proto.Marshal(tt.in) + if err != nil { + t.Fatal(err) + } + desc := tt.recv.ProtoReflect().Descriptor() + hasUnknownNonCriticals, gotErr := decode.RejectUnknownFields( + protoBlob, desc, tt.allowUnknownNonCriticals, ProtoResolver) + if tt.wantErr != nil { + require.EqualError(t, gotErr, tt.wantErr.Error()) + } else { + require.NoError(t, gotErr) + } + require.Equal(t, tt.hasUnknownNonCriticals, hasUnknownNonCriticals) + }) + } +} + +func TestRejectUnknownFields_allowUnknownNonCriticals(t *testing.T) { + tests := []struct { + name string + in proto.Message + allowUnknownNonCriticals bool + wantErr error + }{ + { + name: "Field that's in the reserved range, should fail by default", + in: &testpb.Customer2{ + Id: 289, + Reserved: 99, + }, + wantErr: errUnknownField( + "testpb.Customer1", + 1047, + 0), + }, + { + name: "Field that's in the reserved range, toggle allowUnknownNonCriticals", + allowUnknownNonCriticals: true, + in: &testpb.Customer2{ + Id: 289, + Reserved: 99, + }, + wantErr: nil, + }, + { + name: "Unknown fields that are critical, but with allowUnknownNonCriticals set", + allowUnknownNonCriticals: true, + in: &testpb.Customer2{ + Id: 289, + City: testpb.Customer2_PaloAlto, + }, + wantErr: errUnknownField( + "testpb.Customer1", + 6, + 0), + }, + } + + for _, tt := range tests { + tt := tt + t.Run(tt.name, func(t *testing.T) { + blob, err := proto.Marshal(tt.in) + if err != nil { + t.Fatalf("Failed to marshal input: %v", err) + } + + c1 := new(testpb.Customer1).ProtoReflect().Descriptor() + _, gotErr := decode.RejectUnknownFields(blob, c1, tt.allowUnknownNonCriticals, ProtoResolver) + if tt.wantErr != nil { + require.EqualError(t, gotErr, tt.wantErr.Error()) + } else { + require.NoError(t, gotErr) + } + }) + } +} + +func TestRejectUnknownFieldsNested(t *testing.T) { + tests := []struct { + name string + in proto.Message + recv proto.Message + wantErr error + }{ + { + name: "TestVersion3 from TestVersionFD1", + in: &testpb.TestVersion2{ + X: 5, + Sum: &testpb.TestVersion2_E{ + E: 100, + }, + H: []*testpb.TestVersion1{ + {X: 999}, + {X: -55}, + { + X: 102, + Sum: &testpb.TestVersion1_F{ + F: &testpb.TestVersion1{ + X: 4, + }, + }, + }, + }, + K: &testpb.Customer1{ + Id: 45, + Name: "customer1", + SubscriptionFee: 99, + }, + }, + recv: new(testpb.TestVersionFD1), + wantErr: errUnknownField( + "testpb.TestVersionFD1", + 12, + 2), + }, + { + name: "Alternating oneofs", + in: &testpb.TestVersion3{ + Sum: &testpb.TestVersion3_E{ + E: 99, + }, + }, + recv: new(testpb.TestVersion3LoneOneOfValue), + wantErr: nil, + }, + { + name: "Alternating oneofs mismatched field", + in: &testpb.TestVersion3{ + Sum: &testpb.TestVersion3_F{ + F: &testpb.TestVersion3{ + X: 99, + }, + }, + }, + recv: new(testpb.TestVersion3LoneOneOfValue), + wantErr: errUnknownField( + "testpb.TestVersion3LoneOneOfValue", + 7, + 2), + }, + { + name: "Discrepancy in a deeply nested one of field", + in: &testpb.TestVersion3{ + Sum: &testpb.TestVersion3_F{ + F: &testpb.TestVersion3{ + Sum: &testpb.TestVersion3_F{ + F: &testpb.TestVersion3{ + X: 19, + Sum: &testpb.TestVersion3_E{ + E: 99, + }, + }, + }, + }, + }, + }, + recv: new(testpb.TestVersion3LoneNesting), + wantErr: errUnknownField( + "testpb.TestVersion3LoneNesting", + 6, + 0), + }, + { + name: "unknown field types.Any in G", + in: &testpb.TestVersion3{ + G: &anypb.Any{ + TypeUrl: "/testpb.TestVersion1", + Value: mustMarshal(&testpb.TestVersion2{ + Sum: &testpb.TestVersion2_F{ + F: &testpb.TestVersion2{ + NewField_: 999, + }, + }, + }), + }, + }, + recv: new(testpb.TestVersion3), + wantErr: errUnknownField( + "testpb.TestVersion1", + 25, 0), + }, + { + name: "types.Any with extra fields", + in: &testpb.TestVersionFD1WithExtraAny{ + G: &testpb.AnyWithExtra{ + A: &anypb.Any{ + TypeUrl: "/testpb.TestVersion1", + Value: mustMarshal(&testpb.TestVersion2{ + Sum: &testpb.TestVersion2_F{ + F: &testpb.TestVersion2{ + NewField_: 999, + }, + }, + }), + }, + B: 3, + C: 2, + }, + }, + recv: new(testpb.TestVersion3), + wantErr: errUnknownField( + "google.protobuf.Any", + 3, + 0), + }, + { + name: "mismatched types.Any in G", + in: &testpb.TestVersion1{ + G: &anypb.Any{ + TypeUrl: "/testpb.TestVersion4LoneNesting", + Value: mustMarshal(&testpb.TestVersion3LoneNesting_Inner1{ + Inner: &testpb.TestVersion3LoneNesting_Inner1_InnerInner{ + Id: "ID", + City: "Gotham", + }, + }), + }, + }, + recv: new(testpb.TestVersion1), + // behavior change from previous implementation: we allow mismatched wire -> proto types, + // but this will still error on ConsumeFieldValue + wantErr: errors.New("cannot parse reserved wire type"), + }, + { + name: "From nested proto message, message index 0", + in: &testpb.TestVersion3LoneNesting{ + Inner1: &testpb.TestVersion3LoneNesting_Inner1{ + Id: 10, + Name: "foo", + Inner: &testpb.TestVersion3LoneNesting_Inner1_InnerInner{ + Id: "ID", + City: "Palo Alto", + }, + }, + }, + recv: new(testpb.TestVersion4LoneNesting), + wantErr: nil, + }, + { + name: "From nested proto message, message index 1", + in: &testpb.TestVersion3LoneNesting{ + Inner2: &testpb.TestVersion3LoneNesting_Inner2{ + Id: "ID", + Country: "Maldives", + Inner: &testpb.TestVersion3LoneNesting_Inner2_InnerInner{ + Id: "ID", + City: "Unknown", + }, + }, + }, + recv: new(testpb.TestVersion4LoneNesting), + wantErr: nil, + }, + } + + for _, tt := range tests { + tt := tt + t.Run(tt.name, func(t *testing.T) { + protoBlob, err := proto.Marshal(tt.in) + if err != nil { + t.Fatal(err) + } + + desc := tt.recv.ProtoReflect().Descriptor() + gotErr := decode.RejectUnknownFieldsStrict(protoBlob, desc, ProtoResolver) + if tt.wantErr != nil { + require.ErrorContains(t, gotErr, tt.wantErr.Error()) + } else { + require.NoError(t, gotErr) + } + }) + } +} + +func TestRejectUnknownFieldsFlat(t *testing.T) { + tests := []struct { + name string + in proto.Message + wantErr error + }{ + { + name: "Oneof with same field number, shouldn't complain", + in: &testpb.Customer3{ + Id: 68, + Name: "ACME3", + Payment: &testpb.Customer3_CreditCardNo{ + CreditCardNo: "123-XXXX-XXX881", + }, + }, + wantErr: nil, + }, + { + name: "Oneof with different field number, should fail", + in: &testpb.Customer3{ + Id: 68, + Name: "ACME3", + Payment: &testpb.Customer3_ChequeNo{ + ChequeNo: "123XXXXXXX881", + }, + }, + wantErr: errUnknownField( + "testpb.Customer1", + 8, 2), + }, + { + name: "Any in a field, the extra field will be serialized so should fail", + in: &testpb.Customer2{ + Miscellaneous: &anypb.Any{}, + }, + wantErr: errUnknownField( + "testpb.Customer1", + 10, + 2), + }, + { + name: "With a nested struct as a field", + in: &testpb.Customer3{ + Id: 289, + Original: &testpb.Customer1{ + Id: 991, + }, + }, + wantErr: errUnknownField( + "testpb.Customer1", + 9, + 2), + }, + { + name: "An extra field that's non-existent in Customer1", + in: &testpb.Customer2{ + Id: 289, + Name: "Customer1", + Industry: 5299, + Fewer: 199.9, + }, + wantErr: errUnknownField("testpb.Customer1", 4, 5), + }, + { + name: "Using a field that's in the reserved range, should fail by default", + in: &testpb.Customer2{ + Id: 289, + Reserved: 99, + }, + wantErr: errUnknownField( + "testpb.Customer1", + 1047, + 0), + }, + { + name: "Only fields matching", + in: &testpb.Customer2{ + Id: 289, + Name: "CustomerCustomerCustomerCustomerCustomer11111Customer1", + }, + // behavior change from previous implementation: we allow mismatched wire -> proto types. + // wantErr: errMismatchedField("testpb.Customer1", 4, 5), + }, + { + name: "Extra field that's non-existent in Customer1, along with Reserved set", + in: &testpb.Customer2{ + Id: 289, + Name: "Customer1", + Industry: 5299, + Fewer: 199.9, + Reserved: 819, + }, + wantErr: errUnknownField("testpb.Customer1", 4, 5), + }, + { + name: "Using enumerated field", + in: &testpb.Customer2{ + Id: 289, + Name: "Customer1", + Industry: 5299, + City: testpb.Customer2_PaloAlto, + }, + wantErr: errUnknownField("testpb.Customer1", 6, 0), + }, + { + name: "multiple extraneous fields", + in: &testpb.Customer2{ + Id: 289, + Name: "Customer1", + Industry: 5299, + City: testpb.Customer2_PaloAlto, + Fewer: 45, + }, + wantErr: errUnknownField("testpb.Customer1", 4, 5), + }, + } + + for _, tt := range tests { + tt := tt + t.Run(tt.name, func(t *testing.T) { + blob, err := proto.Marshal(tt.in) + if err != nil { + t.Fatalf("Failed to marshal input: %v", err) + } + + c1 := new(testpb.Customer1) + c1Desc := c1.ProtoReflect().Descriptor() + gotErr := decode.RejectUnknownFieldsStrict(blob, c1Desc, ProtoResolver) + if tt.wantErr != nil { + require.EqualError(t, gotErr, tt.wantErr.Error()) + } else { + require.NoError(t, gotErr) + } + }) + } +} + +// Issue https://github.com/cosmos/cosmos-sdk/issues/7222, we need to ensure that repeated +// uint64 are recognized as packed. +func TestPackedEncoding(t *testing.T) { + data := &testpb.TestRepeatedUints{Nums: []uint64{12, 13}} + + marshaled, err := proto.Marshal(data) + require.NoError(t, err) + + unmarshalled := data.ProtoReflect().Descriptor() + _, err = decode.RejectUnknownFields(marshaled, unmarshalled, false, ProtoResolver) + require.NoError(t, err) +} + +func mustMarshal(msg proto.Message) []byte { + blob, err := proto.Marshal(msg) + if err != nil { + panic(err) + } + return blob +} diff --git a/x/tx/go.mod b/x/tx/go.mod index c7efe6ba02c7..b205b176c7f1 100644 --- a/x/tx/go.mod +++ b/x/tx/go.mod @@ -3,8 +3,9 @@ module cosmossdk.io/x/tx go 1.20 require ( - cosmossdk.io/api v0.3.2-0.20230313131911-55bf5d4efbe7 + cosmossdk.io/api v0.4.0 cosmossdk.io/core v0.6.1 + cosmossdk.io/errors v1.0.0-beta.7 cosmossdk.io/math v1.0.0 github.com/cosmos/cosmos-proto v1.0.0-beta.3 github.com/google/go-cmp v0.5.9 @@ -18,7 +19,7 @@ require ( ) require ( - github.com/cosmos/gogoproto v1.4.6 // indirect + github.com/cosmos/gogoproto v1.4.7 // indirect github.com/davecgh/go-spew v1.1.1 // indirect github.com/golang/protobuf v1.5.3 // indirect github.com/pmezard/go-difflib v1.0.0 // indirect diff --git a/x/tx/go.sum b/x/tx/go.sum index f935d69ec6fa..5009d6018ef3 100644 --- a/x/tx/go.sum +++ b/x/tx/go.sum @@ -1,13 +1,15 @@ -cosmossdk.io/api v0.3.2-0.20230313131911-55bf5d4efbe7 h1:4LrWK+uGP5IxznxtHHsHD+ZBs2+oZRH2loYOGjHLzZM= -cosmossdk.io/api v0.3.2-0.20230313131911-55bf5d4efbe7/go.mod h1:yVns7mKgcsG+hZW/3C5FdJtC6QYWdFIcRlKb9+5HV5g= +cosmossdk.io/api v0.4.0 h1:x90DmdidP6EhzktAa/6/IofSHidDnPjahdlrUvyQZQw= +cosmossdk.io/api v0.4.0/go.mod h1:TWDzBhUBhI1LhSf2XSYpfIBf6D4mbLu/fvzvDfhcaYM= cosmossdk.io/core v0.6.1 h1:OBy7TI2W+/gyn2z40vVvruK3di+cAluinA6cybFbE7s= cosmossdk.io/core v0.6.1/go.mod h1:g3MMBCBXtxbDWBURDVnJE7XML4BG5qENhs0gzkcpuFA= +cosmossdk.io/errors v1.0.0-beta.7 h1:gypHW76pTQGVnHKo6QBkb4yFOJjC+sUGRc5Al3Odj1w= +cosmossdk.io/errors v1.0.0-beta.7/go.mod h1:mz6FQMJRku4bY7aqS/Gwfcmr/ue91roMEKAmDUDpBfE= cosmossdk.io/math v1.0.0 h1:ro9w7eKx23om2tZz/VM2Pf+z2WAbGX1yDQQOJ6iGeJw= cosmossdk.io/math v1.0.0/go.mod h1:Ygz4wBHrgc7g0N+8+MrnTfS9LLn9aaTGa9hKopuym5k= github.com/cosmos/cosmos-proto v1.0.0-beta.3 h1:VitvZ1lPORTVxkmF2fAp3IiA61xVwArQYKXTdEcpW6o= github.com/cosmos/cosmos-proto v1.0.0-beta.3/go.mod h1:t8IASdLaAq+bbHbjq4p960BvcTqtwuAxid3b/2rOD6I= -github.com/cosmos/gogoproto v1.4.6 h1:Ee7z15dWJaGlgM2rWrK8N2IX7PQcuccu8oG68jp5RL4= -github.com/cosmos/gogoproto v1.4.6/go.mod h1:VS/ASYmPgv6zkPKLjR9EB91lwbLHOzaGCirmKKhncfI= +github.com/cosmos/gogoproto v1.4.7 h1:RzYKVnsEC7UIkDnhTIkqEB7LnIQbsySvmNEqPCiPevk= +github.com/cosmos/gogoproto v1.4.7/go.mod h1:gxGePp9qedovvl/StQL2BIJ6qlIBn1+9YxR0IulGBKA= github.com/davecgh/go-spew v1.1.0/go.mod h1:J7Y8YcW2NihsgmVo/mv3lAwl/skON4iLHjSsI+c5H38= github.com/davecgh/go-spew v1.1.1 h1:vj9j/u1bqnvCEfJOwUhtlOARqs3+rkHYY13jYWTU97c= github.com/davecgh/go-spew v1.1.1/go.mod h1:J7Y8YcW2NihsgmVo/mv3lAwl/skON4iLHjSsI+c5H38= diff --git a/x/tx/internal/testpb/signers.proto b/x/tx/internal/testpb/signers.proto index 26b9867b2ad6..dfd6db078646 100644 --- a/x/tx/internal/testpb/signers.proto +++ b/x/tx/internal/testpb/signers.proto @@ -1,6 +1,7 @@ syntax = "proto3"; import "cosmos/msg/v1/msg.proto"; +import "cosmos_proto/cosmos.proto"; option go_package = "cosmossdk.io/x/tx/internal/testpb"; @@ -58,6 +59,12 @@ message BadSigner { option (cosmos.msg.v1.signer) = "signer"; bytes signer = 1; } + message NoSignerOption { bytes signer = 1; } + +message ValidatorSigner { + option (cosmos.msg.v1.signer) = "signer"; + string signer = 1 [(cosmos_proto.scalar) = "cosmos.ValidatorAddressString"]; +} \ No newline at end of file diff --git a/x/tx/internal/testpb/signers.pulsar.go b/x/tx/internal/testpb/signers.pulsar.go index b554e807f002..f7ce5db88e20 100644 --- a/x/tx/internal/testpb/signers.pulsar.go +++ b/x/tx/internal/testpb/signers.pulsar.go @@ -4,6 +4,7 @@ package testpb import ( _ "cosmossdk.io/api/cosmos/msg/v1" fmt "fmt" + _ "github.com/cosmos/cosmos-proto" runtime "github.com/cosmos/cosmos-proto/runtime" protoreflect "google.golang.org/protobuf/reflect/protoreflect" protoiface "google.golang.org/protobuf/runtime/protoiface" @@ -1368,7 +1369,7 @@ func (x *NestedSigner_Inner) ProtoReflect() protoreflect.Message { } func (x *NestedSigner_Inner) slowProtoReflect() protoreflect.Message { - mi := &file_signers_proto_msgTypes[8] + mi := &file_signers_proto_msgTypes[9] if protoimpl.UnsafeEnabled && x != nil { ms := protoimpl.X.MessageStateOf(protoimpl.Pointer(x)) if ms.LoadMessageInfo() == nil { @@ -2282,7 +2283,7 @@ func (x *RepeatedNestedSigner_Inner) ProtoReflect() protoreflect.Message { } func (x *RepeatedNestedSigner_Inner) slowProtoReflect() protoreflect.Message { - mi := &file_signers_proto_msgTypes[9] + mi := &file_signers_proto_msgTypes[10] if protoimpl.UnsafeEnabled && x != nil { ms := protoimpl.X.MessageStateOf(protoimpl.Pointer(x)) if ms.LoadMessageInfo() == nil { @@ -3183,7 +3184,7 @@ func (x *NestedRepeatedSigner_Inner) ProtoReflect() protoreflect.Message { } func (x *NestedRepeatedSigner_Inner) slowProtoReflect() protoreflect.Message { - mi := &file_signers_proto_msgTypes[10] + mi := &file_signers_proto_msgTypes[11] if protoimpl.UnsafeEnabled && x != nil { ms := protoimpl.X.MessageStateOf(protoimpl.Pointer(x)) if ms.LoadMessageInfo() == nil { @@ -4157,7 +4158,7 @@ func (x *RepeatedNestedRepeatedSigner_Inner) ProtoReflect() protoreflect.Message } func (x *RepeatedNestedRepeatedSigner_Inner) slowProtoReflect() protoreflect.Message { - mi := &file_signers_proto_msgTypes[11] + mi := &file_signers_proto_msgTypes[12] if protoimpl.UnsafeEnabled && x != nil { ms := protoimpl.X.MessageStateOf(protoimpl.Pointer(x)) if ms.LoadMessageInfo() == nil { @@ -5415,6 +5416,426 @@ func (x *fastReflection_NoSignerOption) ProtoMethods() *protoiface.Methods { } } +var ( + md_ValidatorSigner protoreflect.MessageDescriptor + fd_ValidatorSigner_signer protoreflect.FieldDescriptor +) + +func init() { + file_signers_proto_init() + md_ValidatorSigner = File_signers_proto.Messages().ByName("ValidatorSigner") + fd_ValidatorSigner_signer = md_ValidatorSigner.Fields().ByName("signer") +} + +var _ protoreflect.Message = (*fastReflection_ValidatorSigner)(nil) + +type fastReflection_ValidatorSigner ValidatorSigner + +func (x *ValidatorSigner) ProtoReflect() protoreflect.Message { + return (*fastReflection_ValidatorSigner)(x) +} + +func (x *ValidatorSigner) slowProtoReflect() protoreflect.Message { + mi := &file_signers_proto_msgTypes[8] + if protoimpl.UnsafeEnabled && x != nil { + ms := protoimpl.X.MessageStateOf(protoimpl.Pointer(x)) + if ms.LoadMessageInfo() == nil { + ms.StoreMessageInfo(mi) + } + return ms + } + return mi.MessageOf(x) +} + +var _fastReflection_ValidatorSigner_messageType fastReflection_ValidatorSigner_messageType +var _ protoreflect.MessageType = fastReflection_ValidatorSigner_messageType{} + +type fastReflection_ValidatorSigner_messageType struct{} + +func (x fastReflection_ValidatorSigner_messageType) Zero() protoreflect.Message { + return (*fastReflection_ValidatorSigner)(nil) +} +func (x fastReflection_ValidatorSigner_messageType) New() protoreflect.Message { + return new(fastReflection_ValidatorSigner) +} +func (x fastReflection_ValidatorSigner_messageType) Descriptor() protoreflect.MessageDescriptor { + return md_ValidatorSigner +} + +// Descriptor returns message descriptor, which contains only the protobuf +// type information for the message. +func (x *fastReflection_ValidatorSigner) Descriptor() protoreflect.MessageDescriptor { + return md_ValidatorSigner +} + +// Type returns the message type, which encapsulates both Go and protobuf +// type information. If the Go type information is not needed, +// it is recommended that the message descriptor be used instead. +func (x *fastReflection_ValidatorSigner) Type() protoreflect.MessageType { + return _fastReflection_ValidatorSigner_messageType +} + +// New returns a newly allocated and mutable empty message. +func (x *fastReflection_ValidatorSigner) New() protoreflect.Message { + return new(fastReflection_ValidatorSigner) +} + +// Interface unwraps the message reflection interface and +// returns the underlying ProtoMessage interface. +func (x *fastReflection_ValidatorSigner) Interface() protoreflect.ProtoMessage { + return (*ValidatorSigner)(x) +} + +// Range iterates over every populated field in an undefined order, +// calling f for each field descriptor and value encountered. +// Range returns immediately if f returns false. +// While iterating, mutating operations may only be performed +// on the current field descriptor. +func (x *fastReflection_ValidatorSigner) Range(f func(protoreflect.FieldDescriptor, protoreflect.Value) bool) { + if x.Signer != "" { + value := protoreflect.ValueOfString(x.Signer) + if !f(fd_ValidatorSigner_signer, value) { + return + } + } +} + +// Has reports whether a field is populated. +// +// Some fields have the property of nullability where it is possible to +// distinguish between the default value of a field and whether the field +// was explicitly populated with the default value. Singular message fields, +// member fields of a oneof, and proto2 scalar fields are nullable. Such +// fields are populated only if explicitly set. +// +// In other cases (aside from the nullable cases above), +// a proto3 scalar field is populated if it contains a non-zero value, and +// a repeated field is populated if it is non-empty. +func (x *fastReflection_ValidatorSigner) Has(fd protoreflect.FieldDescriptor) bool { + switch fd.FullName() { + case "ValidatorSigner.signer": + return x.Signer != "" + default: + if fd.IsExtension() { + panic(fmt.Errorf("proto3 declared messages do not support extensions: ValidatorSigner")) + } + panic(fmt.Errorf("message ValidatorSigner does not contain field %s", fd.FullName())) + } +} + +// Clear clears the field such that a subsequent Has call reports false. +// +// Clearing an extension field clears both the extension type and value +// associated with the given field number. +// +// Clear is a mutating operation and unsafe for concurrent use. +func (x *fastReflection_ValidatorSigner) Clear(fd protoreflect.FieldDescriptor) { + switch fd.FullName() { + case "ValidatorSigner.signer": + x.Signer = "" + default: + if fd.IsExtension() { + panic(fmt.Errorf("proto3 declared messages do not support extensions: ValidatorSigner")) + } + panic(fmt.Errorf("message ValidatorSigner does not contain field %s", fd.FullName())) + } +} + +// Get retrieves the value for a field. +// +// For unpopulated scalars, it returns the default value, where +// the default value of a bytes scalar is guaranteed to be a copy. +// For unpopulated composite types, it returns an empty, read-only view +// of the value; to obtain a mutable reference, use Mutable. +func (x *fastReflection_ValidatorSigner) Get(descriptor protoreflect.FieldDescriptor) protoreflect.Value { + switch descriptor.FullName() { + case "ValidatorSigner.signer": + value := x.Signer + return protoreflect.ValueOfString(value) + default: + if descriptor.IsExtension() { + panic(fmt.Errorf("proto3 declared messages do not support extensions: ValidatorSigner")) + } + panic(fmt.Errorf("message ValidatorSigner does not contain field %s", descriptor.FullName())) + } +} + +// Set stores the value for a field. +// +// For a field belonging to a oneof, it implicitly clears any other field +// that may be currently set within the same oneof. +// For extension fields, it implicitly stores the provided ExtensionType. +// When setting a composite type, it is unspecified whether the stored value +// aliases the source's memory in any way. If the composite value is an +// empty, read-only value, then it panics. +// +// Set is a mutating operation and unsafe for concurrent use. +func (x *fastReflection_ValidatorSigner) Set(fd protoreflect.FieldDescriptor, value protoreflect.Value) { + switch fd.FullName() { + case "ValidatorSigner.signer": + x.Signer = value.Interface().(string) + default: + if fd.IsExtension() { + panic(fmt.Errorf("proto3 declared messages do not support extensions: ValidatorSigner")) + } + panic(fmt.Errorf("message ValidatorSigner does not contain field %s", fd.FullName())) + } +} + +// Mutable returns a mutable reference to a composite type. +// +// If the field is unpopulated, it may allocate a composite value. +// For a field belonging to a oneof, it implicitly clears any other field +// that may be currently set within the same oneof. +// For extension fields, it implicitly stores the provided ExtensionType +// if not already stored. +// It panics if the field does not contain a composite type. +// +// Mutable is a mutating operation and unsafe for concurrent use. +func (x *fastReflection_ValidatorSigner) Mutable(fd protoreflect.FieldDescriptor) protoreflect.Value { + switch fd.FullName() { + case "ValidatorSigner.signer": + panic(fmt.Errorf("field signer of message ValidatorSigner is not mutable")) + default: + if fd.IsExtension() { + panic(fmt.Errorf("proto3 declared messages do not support extensions: ValidatorSigner")) + } + panic(fmt.Errorf("message ValidatorSigner does not contain field %s", fd.FullName())) + } +} + +// NewField returns a new value that is assignable to the field +// for the given descriptor. For scalars, this returns the default value. +// For lists, maps, and messages, this returns a new, empty, mutable value. +func (x *fastReflection_ValidatorSigner) NewField(fd protoreflect.FieldDescriptor) protoreflect.Value { + switch fd.FullName() { + case "ValidatorSigner.signer": + return protoreflect.ValueOfString("") + default: + if fd.IsExtension() { + panic(fmt.Errorf("proto3 declared messages do not support extensions: ValidatorSigner")) + } + panic(fmt.Errorf("message ValidatorSigner does not contain field %s", fd.FullName())) + } +} + +// WhichOneof reports which field within the oneof is populated, +// returning nil if none are populated. +// It panics if the oneof descriptor does not belong to this message. +func (x *fastReflection_ValidatorSigner) WhichOneof(d protoreflect.OneofDescriptor) protoreflect.FieldDescriptor { + switch d.FullName() { + default: + panic(fmt.Errorf("%s is not a oneof field in ValidatorSigner", d.FullName())) + } + panic("unreachable") +} + +// GetUnknown retrieves the entire list of unknown fields. +// The caller may only mutate the contents of the RawFields +// if the mutated bytes are stored back into the message with SetUnknown. +func (x *fastReflection_ValidatorSigner) GetUnknown() protoreflect.RawFields { + return x.unknownFields +} + +// SetUnknown stores an entire list of unknown fields. +// The raw fields must be syntactically valid according to the wire format. +// An implementation may panic if this is not the case. +// Once stored, the caller must not mutate the content of the RawFields. +// An empty RawFields may be passed to clear the fields. +// +// SetUnknown is a mutating operation and unsafe for concurrent use. +func (x *fastReflection_ValidatorSigner) SetUnknown(fields protoreflect.RawFields) { + x.unknownFields = fields +} + +// IsValid reports whether the message is valid. +// +// An invalid message is an empty, read-only value. +// +// An invalid message often corresponds to a nil pointer of the concrete +// message type, but the details are implementation dependent. +// Validity is not part of the protobuf data model, and may not +// be preserved in marshaling or other operations. +func (x *fastReflection_ValidatorSigner) IsValid() bool { + return x != nil +} + +// ProtoMethods returns optional fastReflectionFeature-path implementations of various operations. +// This method may return nil. +// +// The returned methods type is identical to +// "google.golang.org/protobuf/runtime/protoiface".Methods. +// Consult the protoiface package documentation for details. +func (x *fastReflection_ValidatorSigner) ProtoMethods() *protoiface.Methods { + size := func(input protoiface.SizeInput) protoiface.SizeOutput { + x := input.Message.Interface().(*ValidatorSigner) + if x == nil { + return protoiface.SizeOutput{ + NoUnkeyedLiterals: input.NoUnkeyedLiterals, + Size: 0, + } + } + options := runtime.SizeInputToOptions(input) + _ = options + var n int + var l int + _ = l + l = len(x.Signer) + if l > 0 { + n += 1 + l + runtime.Sov(uint64(l)) + } + if x.unknownFields != nil { + n += len(x.unknownFields) + } + return protoiface.SizeOutput{ + NoUnkeyedLiterals: input.NoUnkeyedLiterals, + Size: n, + } + } + + marshal := func(input protoiface.MarshalInput) (protoiface.MarshalOutput, error) { + x := input.Message.Interface().(*ValidatorSigner) + if x == nil { + return protoiface.MarshalOutput{ + NoUnkeyedLiterals: input.NoUnkeyedLiterals, + Buf: input.Buf, + }, nil + } + options := runtime.MarshalInputToOptions(input) + _ = options + size := options.Size(x) + dAtA := make([]byte, size) + i := len(dAtA) + _ = i + var l int + _ = l + if x.unknownFields != nil { + i -= len(x.unknownFields) + copy(dAtA[i:], x.unknownFields) + } + if len(x.Signer) > 0 { + i -= len(x.Signer) + copy(dAtA[i:], x.Signer) + i = runtime.EncodeVarint(dAtA, i, uint64(len(x.Signer))) + i-- + dAtA[i] = 0xa + } + if input.Buf != nil { + input.Buf = append(input.Buf, dAtA...) + } else { + input.Buf = dAtA + } + return protoiface.MarshalOutput{ + NoUnkeyedLiterals: input.NoUnkeyedLiterals, + Buf: input.Buf, + }, nil + } + unmarshal := func(input protoiface.UnmarshalInput) (protoiface.UnmarshalOutput, error) { + x := input.Message.Interface().(*ValidatorSigner) + if x == nil { + return protoiface.UnmarshalOutput{ + NoUnkeyedLiterals: input.NoUnkeyedLiterals, + Flags: input.Flags, + }, nil + } + options := runtime.UnmarshalInputToOptions(input) + _ = options + dAtA := input.Buf + l := len(dAtA) + iNdEx := 0 + for iNdEx < l { + preIndex := iNdEx + var wire uint64 + for shift := uint(0); ; shift += 7 { + if shift >= 64 { + return protoiface.UnmarshalOutput{NoUnkeyedLiterals: input.NoUnkeyedLiterals, Flags: input.Flags}, runtime.ErrIntOverflow + } + if iNdEx >= l { + return protoiface.UnmarshalOutput{NoUnkeyedLiterals: input.NoUnkeyedLiterals, Flags: input.Flags}, io.ErrUnexpectedEOF + } + b := dAtA[iNdEx] + iNdEx++ + wire |= uint64(b&0x7F) << shift + if b < 0x80 { + break + } + } + fieldNum := int32(wire >> 3) + wireType := int(wire & 0x7) + if wireType == 4 { + return protoiface.UnmarshalOutput{NoUnkeyedLiterals: input.NoUnkeyedLiterals, Flags: input.Flags}, fmt.Errorf("proto: ValidatorSigner: wiretype end group for non-group") + } + if fieldNum <= 0 { + return protoiface.UnmarshalOutput{NoUnkeyedLiterals: input.NoUnkeyedLiterals, Flags: input.Flags}, fmt.Errorf("proto: ValidatorSigner: illegal tag %d (wire type %d)", fieldNum, wire) + } + switch fieldNum { + case 1: + if wireType != 2 { + return protoiface.UnmarshalOutput{NoUnkeyedLiterals: input.NoUnkeyedLiterals, Flags: input.Flags}, fmt.Errorf("proto: wrong wireType = %d for field Signer", wireType) + } + var stringLen uint64 + for shift := uint(0); ; shift += 7 { + if shift >= 64 { + return protoiface.UnmarshalOutput{NoUnkeyedLiterals: input.NoUnkeyedLiterals, Flags: input.Flags}, runtime.ErrIntOverflow + } + if iNdEx >= l { + return protoiface.UnmarshalOutput{NoUnkeyedLiterals: input.NoUnkeyedLiterals, Flags: input.Flags}, io.ErrUnexpectedEOF + } + b := dAtA[iNdEx] + iNdEx++ + stringLen |= uint64(b&0x7F) << shift + if b < 0x80 { + break + } + } + intStringLen := int(stringLen) + if intStringLen < 0 { + return protoiface.UnmarshalOutput{NoUnkeyedLiterals: input.NoUnkeyedLiterals, Flags: input.Flags}, runtime.ErrInvalidLength + } + postIndex := iNdEx + intStringLen + if postIndex < 0 { + return protoiface.UnmarshalOutput{NoUnkeyedLiterals: input.NoUnkeyedLiterals, Flags: input.Flags}, runtime.ErrInvalidLength + } + if postIndex > l { + return protoiface.UnmarshalOutput{NoUnkeyedLiterals: input.NoUnkeyedLiterals, Flags: input.Flags}, io.ErrUnexpectedEOF + } + x.Signer = string(dAtA[iNdEx:postIndex]) + iNdEx = postIndex + default: + iNdEx = preIndex + skippy, err := runtime.Skip(dAtA[iNdEx:]) + if err != nil { + return protoiface.UnmarshalOutput{NoUnkeyedLiterals: input.NoUnkeyedLiterals, Flags: input.Flags}, err + } + if (skippy < 0) || (iNdEx+skippy) < 0 { + return protoiface.UnmarshalOutput{NoUnkeyedLiterals: input.NoUnkeyedLiterals, Flags: input.Flags}, runtime.ErrInvalidLength + } + if (iNdEx + skippy) > l { + return protoiface.UnmarshalOutput{NoUnkeyedLiterals: input.NoUnkeyedLiterals, Flags: input.Flags}, io.ErrUnexpectedEOF + } + if !options.DiscardUnknown { + x.unknownFields = append(x.unknownFields, dAtA[iNdEx:iNdEx+skippy]...) + } + iNdEx += skippy + } + } + + if iNdEx > l { + return protoiface.UnmarshalOutput{NoUnkeyedLiterals: input.NoUnkeyedLiterals, Flags: input.Flags}, io.ErrUnexpectedEOF + } + return protoiface.UnmarshalOutput{NoUnkeyedLiterals: input.NoUnkeyedLiterals, Flags: input.Flags}, nil + } + return &protoiface.Methods{ + NoUnkeyedLiterals: struct{}{}, + Flags: protoiface.SupportMarshalDeterministic | protoiface.SupportUnmarshalDiscardUnknown, + Size: size, + Marshal: marshal, + Unmarshal: unmarshal, + Merge: nil, + CheckInitialized: nil, + } +} + // Code generated by protoc-gen-go. DO NOT EDIT. // versions: // protoc-gen-go v1.27.0 @@ -5708,6 +6129,41 @@ func (x *NoSignerOption) GetSigner() []byte { return nil } +type ValidatorSigner struct { + state protoimpl.MessageState + sizeCache protoimpl.SizeCache + unknownFields protoimpl.UnknownFields + + Signer string `protobuf:"bytes,1,opt,name=signer,proto3" json:"signer,omitempty"` +} + +func (x *ValidatorSigner) Reset() { + *x = ValidatorSigner{} + if protoimpl.UnsafeEnabled { + mi := &file_signers_proto_msgTypes[8] + ms := protoimpl.X.MessageStateOf(protoimpl.Pointer(x)) + ms.StoreMessageInfo(mi) + } +} + +func (x *ValidatorSigner) String() string { + return protoimpl.X.MessageStringOf(x) +} + +func (*ValidatorSigner) ProtoMessage() {} + +// Deprecated: Use ValidatorSigner.ProtoReflect.Descriptor instead. +func (*ValidatorSigner) Descriptor() ([]byte, []int) { + return file_signers_proto_rawDescGZIP(), []int{8} +} + +func (x *ValidatorSigner) GetSigner() string { + if x != nil { + return x.Signer + } + return "" +} + type NestedSigner_Inner struct { state protoimpl.MessageState sizeCache protoimpl.SizeCache @@ -5719,7 +6175,7 @@ type NestedSigner_Inner struct { func (x *NestedSigner_Inner) Reset() { *x = NestedSigner_Inner{} if protoimpl.UnsafeEnabled { - mi := &file_signers_proto_msgTypes[8] + mi := &file_signers_proto_msgTypes[9] ms := protoimpl.X.MessageStateOf(protoimpl.Pointer(x)) ms.StoreMessageInfo(mi) } @@ -5754,7 +6210,7 @@ type RepeatedNestedSigner_Inner struct { func (x *RepeatedNestedSigner_Inner) Reset() { *x = RepeatedNestedSigner_Inner{} if protoimpl.UnsafeEnabled { - mi := &file_signers_proto_msgTypes[9] + mi := &file_signers_proto_msgTypes[10] ms := protoimpl.X.MessageStateOf(protoimpl.Pointer(x)) ms.StoreMessageInfo(mi) } @@ -5789,7 +6245,7 @@ type NestedRepeatedSigner_Inner struct { func (x *NestedRepeatedSigner_Inner) Reset() { *x = NestedRepeatedSigner_Inner{} if protoimpl.UnsafeEnabled { - mi := &file_signers_proto_msgTypes[10] + mi := &file_signers_proto_msgTypes[11] ms := protoimpl.X.MessageStateOf(protoimpl.Pointer(x)) ms.StoreMessageInfo(mi) } @@ -5824,7 +6280,7 @@ type RepeatedNestedRepeatedSigner_Inner struct { func (x *RepeatedNestedRepeatedSigner_Inner) Reset() { *x = RepeatedNestedRepeatedSigner_Inner{} if protoimpl.UnsafeEnabled { - mi := &file_signers_proto_msgTypes[11] + mi := &file_signers_proto_msgTypes[12] ms := protoimpl.X.MessageStateOf(protoimpl.Pointer(x)) ms.StoreMessageInfo(mi) } @@ -5853,57 +6309,65 @@ var File_signers_proto protoreflect.FileDescriptor var file_signers_proto_rawDesc = []byte{ 0x0a, 0x0d, 0x73, 0x69, 0x67, 0x6e, 0x65, 0x72, 0x73, 0x2e, 0x70, 0x72, 0x6f, 0x74, 0x6f, 0x1a, 0x17, 0x63, 0x6f, 0x73, 0x6d, 0x6f, 0x73, 0x2f, 0x6d, 0x73, 0x67, 0x2f, 0x76, 0x31, 0x2f, 0x6d, - 0x73, 0x67, 0x2e, 0x70, 0x72, 0x6f, 0x74, 0x6f, 0x22, 0x33, 0x0a, 0x0c, 0x53, 0x69, 0x6d, 0x70, - 0x6c, 0x65, 0x53, 0x69, 0x67, 0x6e, 0x65, 0x72, 0x12, 0x16, 0x0a, 0x06, 0x73, 0x69, 0x67, 0x6e, - 0x65, 0x72, 0x18, 0x01, 0x20, 0x01, 0x28, 0x09, 0x52, 0x06, 0x73, 0x69, 0x67, 0x6e, 0x65, 0x72, - 0x3a, 0x0b, 0x82, 0xe7, 0xb0, 0x2a, 0x06, 0x73, 0x69, 0x67, 0x6e, 0x65, 0x72, 0x22, 0x35, 0x0a, - 0x0e, 0x52, 0x65, 0x70, 0x65, 0x61, 0x74, 0x65, 0x64, 0x53, 0x69, 0x67, 0x6e, 0x65, 0x72, 0x12, + 0x73, 0x67, 0x2e, 0x70, 0x72, 0x6f, 0x74, 0x6f, 0x1a, 0x19, 0x63, 0x6f, 0x73, 0x6d, 0x6f, 0x73, + 0x5f, 0x70, 0x72, 0x6f, 0x74, 0x6f, 0x2f, 0x63, 0x6f, 0x73, 0x6d, 0x6f, 0x73, 0x2e, 0x70, 0x72, + 0x6f, 0x74, 0x6f, 0x22, 0x33, 0x0a, 0x0c, 0x53, 0x69, 0x6d, 0x70, 0x6c, 0x65, 0x53, 0x69, 0x67, + 0x6e, 0x65, 0x72, 0x12, 0x16, 0x0a, 0x06, 0x73, 0x69, 0x67, 0x6e, 0x65, 0x72, 0x18, 0x01, 0x20, + 0x01, 0x28, 0x09, 0x52, 0x06, 0x73, 0x69, 0x67, 0x6e, 0x65, 0x72, 0x3a, 0x0b, 0x82, 0xe7, 0xb0, + 0x2a, 0x06, 0x73, 0x69, 0x67, 0x6e, 0x65, 0x72, 0x22, 0x35, 0x0a, 0x0e, 0x52, 0x65, 0x70, 0x65, + 0x61, 0x74, 0x65, 0x64, 0x53, 0x69, 0x67, 0x6e, 0x65, 0x72, 0x12, 0x16, 0x0a, 0x06, 0x73, 0x69, + 0x67, 0x6e, 0x65, 0x72, 0x18, 0x01, 0x20, 0x03, 0x28, 0x09, 0x52, 0x06, 0x73, 0x69, 0x67, 0x6e, + 0x65, 0x72, 0x3a, 0x0b, 0x82, 0xe7, 0xb0, 0x2a, 0x06, 0x73, 0x69, 0x67, 0x6e, 0x65, 0x72, 0x22, + 0x73, 0x0a, 0x0c, 0x4e, 0x65, 0x73, 0x74, 0x65, 0x64, 0x53, 0x69, 0x67, 0x6e, 0x65, 0x72, 0x12, + 0x29, 0x0a, 0x05, 0x69, 0x6e, 0x6e, 0x65, 0x72, 0x18, 0x01, 0x20, 0x01, 0x28, 0x0b, 0x32, 0x13, + 0x2e, 0x4e, 0x65, 0x73, 0x74, 0x65, 0x64, 0x53, 0x69, 0x67, 0x6e, 0x65, 0x72, 0x2e, 0x49, 0x6e, + 0x6e, 0x65, 0x72, 0x52, 0x05, 0x69, 0x6e, 0x6e, 0x65, 0x72, 0x1a, 0x2c, 0x0a, 0x05, 0x49, 0x6e, + 0x6e, 0x65, 0x72, 0x12, 0x16, 0x0a, 0x06, 0x73, 0x69, 0x67, 0x6e, 0x65, 0x72, 0x18, 0x01, 0x20, + 0x01, 0x28, 0x09, 0x52, 0x06, 0x73, 0x69, 0x67, 0x6e, 0x65, 0x72, 0x3a, 0x0b, 0x82, 0xe7, 0xb0, + 0x2a, 0x06, 0x73, 0x69, 0x67, 0x6e, 0x65, 0x72, 0x3a, 0x0a, 0x82, 0xe7, 0xb0, 0x2a, 0x05, 0x69, + 0x6e, 0x6e, 0x65, 0x72, 0x22, 0x83, 0x01, 0x0a, 0x14, 0x52, 0x65, 0x70, 0x65, 0x61, 0x74, 0x65, + 0x64, 0x4e, 0x65, 0x73, 0x74, 0x65, 0x64, 0x53, 0x69, 0x67, 0x6e, 0x65, 0x72, 0x12, 0x31, 0x0a, + 0x05, 0x69, 0x6e, 0x6e, 0x65, 0x72, 0x18, 0x01, 0x20, 0x03, 0x28, 0x0b, 0x32, 0x1b, 0x2e, 0x52, + 0x65, 0x70, 0x65, 0x61, 0x74, 0x65, 0x64, 0x4e, 0x65, 0x73, 0x74, 0x65, 0x64, 0x53, 0x69, 0x67, + 0x6e, 0x65, 0x72, 0x2e, 0x49, 0x6e, 0x6e, 0x65, 0x72, 0x52, 0x05, 0x69, 0x6e, 0x6e, 0x65, 0x72, + 0x1a, 0x2c, 0x0a, 0x05, 0x49, 0x6e, 0x6e, 0x65, 0x72, 0x12, 0x16, 0x0a, 0x06, 0x73, 0x69, 0x67, + 0x6e, 0x65, 0x72, 0x18, 0x01, 0x20, 0x01, 0x28, 0x09, 0x52, 0x06, 0x73, 0x69, 0x67, 0x6e, 0x65, + 0x72, 0x3a, 0x0b, 0x82, 0xe7, 0xb0, 0x2a, 0x06, 0x73, 0x69, 0x67, 0x6e, 0x65, 0x72, 0x3a, 0x0a, + 0x82, 0xe7, 0xb0, 0x2a, 0x05, 0x69, 0x6e, 0x6e, 0x65, 0x72, 0x22, 0x83, 0x01, 0x0a, 0x14, 0x4e, + 0x65, 0x73, 0x74, 0x65, 0x64, 0x52, 0x65, 0x70, 0x65, 0x61, 0x74, 0x65, 0x64, 0x53, 0x69, 0x67, + 0x6e, 0x65, 0x72, 0x12, 0x31, 0x0a, 0x05, 0x69, 0x6e, 0x6e, 0x65, 0x72, 0x18, 0x01, 0x20, 0x01, + 0x28, 0x0b, 0x32, 0x1b, 0x2e, 0x4e, 0x65, 0x73, 0x74, 0x65, 0x64, 0x52, 0x65, 0x70, 0x65, 0x61, + 0x74, 0x65, 0x64, 0x53, 0x69, 0x67, 0x6e, 0x65, 0x72, 0x2e, 0x49, 0x6e, 0x6e, 0x65, 0x72, 0x52, + 0x05, 0x69, 0x6e, 0x6e, 0x65, 0x72, 0x1a, 0x2c, 0x0a, 0x05, 0x49, 0x6e, 0x6e, 0x65, 0x72, 0x12, 0x16, 0x0a, 0x06, 0x73, 0x69, 0x67, 0x6e, 0x65, 0x72, 0x18, 0x01, 0x20, 0x03, 0x28, 0x09, 0x52, 0x06, 0x73, 0x69, 0x67, 0x6e, 0x65, 0x72, 0x3a, 0x0b, 0x82, 0xe7, 0xb0, 0x2a, 0x06, 0x73, 0x69, - 0x67, 0x6e, 0x65, 0x72, 0x22, 0x73, 0x0a, 0x0c, 0x4e, 0x65, 0x73, 0x74, 0x65, 0x64, 0x53, 0x69, - 0x67, 0x6e, 0x65, 0x72, 0x12, 0x29, 0x0a, 0x05, 0x69, 0x6e, 0x6e, 0x65, 0x72, 0x18, 0x01, 0x20, - 0x01, 0x28, 0x0b, 0x32, 0x13, 0x2e, 0x4e, 0x65, 0x73, 0x74, 0x65, 0x64, 0x53, 0x69, 0x67, 0x6e, - 0x65, 0x72, 0x2e, 0x49, 0x6e, 0x6e, 0x65, 0x72, 0x52, 0x05, 0x69, 0x6e, 0x6e, 0x65, 0x72, 0x1a, - 0x2c, 0x0a, 0x05, 0x49, 0x6e, 0x6e, 0x65, 0x72, 0x12, 0x16, 0x0a, 0x06, 0x73, 0x69, 0x67, 0x6e, - 0x65, 0x72, 0x18, 0x01, 0x20, 0x01, 0x28, 0x09, 0x52, 0x06, 0x73, 0x69, 0x67, 0x6e, 0x65, 0x72, - 0x3a, 0x0b, 0x82, 0xe7, 0xb0, 0x2a, 0x06, 0x73, 0x69, 0x67, 0x6e, 0x65, 0x72, 0x3a, 0x0a, 0x82, - 0xe7, 0xb0, 0x2a, 0x05, 0x69, 0x6e, 0x6e, 0x65, 0x72, 0x22, 0x83, 0x01, 0x0a, 0x14, 0x52, 0x65, - 0x70, 0x65, 0x61, 0x74, 0x65, 0x64, 0x4e, 0x65, 0x73, 0x74, 0x65, 0x64, 0x53, 0x69, 0x67, 0x6e, - 0x65, 0x72, 0x12, 0x31, 0x0a, 0x05, 0x69, 0x6e, 0x6e, 0x65, 0x72, 0x18, 0x01, 0x20, 0x03, 0x28, - 0x0b, 0x32, 0x1b, 0x2e, 0x52, 0x65, 0x70, 0x65, 0x61, 0x74, 0x65, 0x64, 0x4e, 0x65, 0x73, 0x74, - 0x65, 0x64, 0x53, 0x69, 0x67, 0x6e, 0x65, 0x72, 0x2e, 0x49, 0x6e, 0x6e, 0x65, 0x72, 0x52, 0x05, - 0x69, 0x6e, 0x6e, 0x65, 0x72, 0x1a, 0x2c, 0x0a, 0x05, 0x49, 0x6e, 0x6e, 0x65, 0x72, 0x12, 0x16, - 0x0a, 0x06, 0x73, 0x69, 0x67, 0x6e, 0x65, 0x72, 0x18, 0x01, 0x20, 0x01, 0x28, 0x09, 0x52, 0x06, - 0x73, 0x69, 0x67, 0x6e, 0x65, 0x72, 0x3a, 0x0b, 0x82, 0xe7, 0xb0, 0x2a, 0x06, 0x73, 0x69, 0x67, - 0x6e, 0x65, 0x72, 0x3a, 0x0a, 0x82, 0xe7, 0xb0, 0x2a, 0x05, 0x69, 0x6e, 0x6e, 0x65, 0x72, 0x22, - 0x83, 0x01, 0x0a, 0x14, 0x4e, 0x65, 0x73, 0x74, 0x65, 0x64, 0x52, 0x65, 0x70, 0x65, 0x61, 0x74, - 0x65, 0x64, 0x53, 0x69, 0x67, 0x6e, 0x65, 0x72, 0x12, 0x31, 0x0a, 0x05, 0x69, 0x6e, 0x6e, 0x65, - 0x72, 0x18, 0x01, 0x20, 0x01, 0x28, 0x0b, 0x32, 0x1b, 0x2e, 0x4e, 0x65, 0x73, 0x74, 0x65, 0x64, - 0x52, 0x65, 0x70, 0x65, 0x61, 0x74, 0x65, 0x64, 0x53, 0x69, 0x67, 0x6e, 0x65, 0x72, 0x2e, 0x49, - 0x6e, 0x6e, 0x65, 0x72, 0x52, 0x05, 0x69, 0x6e, 0x6e, 0x65, 0x72, 0x1a, 0x2c, 0x0a, 0x05, 0x49, - 0x6e, 0x6e, 0x65, 0x72, 0x12, 0x16, 0x0a, 0x06, 0x73, 0x69, 0x67, 0x6e, 0x65, 0x72, 0x18, 0x01, - 0x20, 0x03, 0x28, 0x09, 0x52, 0x06, 0x73, 0x69, 0x67, 0x6e, 0x65, 0x72, 0x3a, 0x0b, 0x82, 0xe7, - 0xb0, 0x2a, 0x06, 0x73, 0x69, 0x67, 0x6e, 0x65, 0x72, 0x3a, 0x0a, 0x82, 0xe7, 0xb0, 0x2a, 0x05, - 0x69, 0x6e, 0x6e, 0x65, 0x72, 0x22, 0x93, 0x01, 0x0a, 0x1c, 0x52, 0x65, 0x70, 0x65, 0x61, 0x74, - 0x65, 0x64, 0x4e, 0x65, 0x73, 0x74, 0x65, 0x64, 0x52, 0x65, 0x70, 0x65, 0x61, 0x74, 0x65, 0x64, - 0x53, 0x69, 0x67, 0x6e, 0x65, 0x72, 0x12, 0x39, 0x0a, 0x05, 0x69, 0x6e, 0x6e, 0x65, 0x72, 0x18, - 0x01, 0x20, 0x03, 0x28, 0x0b, 0x32, 0x23, 0x2e, 0x52, 0x65, 0x70, 0x65, 0x61, 0x74, 0x65, 0x64, - 0x4e, 0x65, 0x73, 0x74, 0x65, 0x64, 0x52, 0x65, 0x70, 0x65, 0x61, 0x74, 0x65, 0x64, 0x53, 0x69, - 0x67, 0x6e, 0x65, 0x72, 0x2e, 0x49, 0x6e, 0x6e, 0x65, 0x72, 0x52, 0x05, 0x69, 0x6e, 0x6e, 0x65, - 0x72, 0x1a, 0x2c, 0x0a, 0x05, 0x49, 0x6e, 0x6e, 0x65, 0x72, 0x12, 0x16, 0x0a, 0x06, 0x73, 0x69, - 0x67, 0x6e, 0x65, 0x72, 0x18, 0x01, 0x20, 0x03, 0x28, 0x09, 0x52, 0x06, 0x73, 0x69, 0x67, 0x6e, - 0x65, 0x72, 0x3a, 0x0b, 0x82, 0xe7, 0xb0, 0x2a, 0x06, 0x73, 0x69, 0x67, 0x6e, 0x65, 0x72, 0x3a, - 0x0a, 0x82, 0xe7, 0xb0, 0x2a, 0x05, 0x69, 0x6e, 0x6e, 0x65, 0x72, 0x22, 0x30, 0x0a, 0x09, 0x42, - 0x61, 0x64, 0x53, 0x69, 0x67, 0x6e, 0x65, 0x72, 0x12, 0x16, 0x0a, 0x06, 0x73, 0x69, 0x67, 0x6e, - 0x65, 0x72, 0x18, 0x01, 0x20, 0x01, 0x28, 0x0c, 0x52, 0x06, 0x73, 0x69, 0x67, 0x6e, 0x65, 0x72, - 0x3a, 0x0b, 0x82, 0xe7, 0xb0, 0x2a, 0x06, 0x73, 0x69, 0x67, 0x6e, 0x65, 0x72, 0x22, 0x28, 0x0a, - 0x0e, 0x4e, 0x6f, 0x53, 0x69, 0x67, 0x6e, 0x65, 0x72, 0x4f, 0x70, 0x74, 0x69, 0x6f, 0x6e, 0x12, - 0x16, 0x0a, 0x06, 0x73, 0x69, 0x67, 0x6e, 0x65, 0x72, 0x18, 0x01, 0x20, 0x01, 0x28, 0x0c, 0x52, - 0x06, 0x73, 0x69, 0x67, 0x6e, 0x65, 0x72, 0x42, 0x3b, 0x42, 0x0c, 0x53, 0x69, 0x67, 0x6e, 0x65, - 0x72, 0x73, 0x50, 0x72, 0x6f, 0x74, 0x6f, 0x50, 0x01, 0x5a, 0x29, 0x63, 0x6f, 0x73, 0x6d, 0x6f, - 0x73, 0x73, 0x64, 0x6b, 0x2e, 0x69, 0x6f, 0x2f, 0x78, 0x2f, 0x74, 0x78, 0x2f, 0x74, 0x65, 0x78, - 0x74, 0x75, 0x61, 0x6c, 0x2f, 0x69, 0x6e, 0x74, 0x65, 0x72, 0x6e, 0x61, 0x6c, 0x2f, 0x74, 0x65, - 0x73, 0x74, 0x70, 0x62, 0x62, 0x06, 0x70, 0x72, 0x6f, 0x74, 0x6f, 0x33, + 0x67, 0x6e, 0x65, 0x72, 0x3a, 0x0a, 0x82, 0xe7, 0xb0, 0x2a, 0x05, 0x69, 0x6e, 0x6e, 0x65, 0x72, + 0x22, 0x93, 0x01, 0x0a, 0x1c, 0x52, 0x65, 0x70, 0x65, 0x61, 0x74, 0x65, 0x64, 0x4e, 0x65, 0x73, + 0x74, 0x65, 0x64, 0x52, 0x65, 0x70, 0x65, 0x61, 0x74, 0x65, 0x64, 0x53, 0x69, 0x67, 0x6e, 0x65, + 0x72, 0x12, 0x39, 0x0a, 0x05, 0x69, 0x6e, 0x6e, 0x65, 0x72, 0x18, 0x01, 0x20, 0x03, 0x28, 0x0b, + 0x32, 0x23, 0x2e, 0x52, 0x65, 0x70, 0x65, 0x61, 0x74, 0x65, 0x64, 0x4e, 0x65, 0x73, 0x74, 0x65, + 0x64, 0x52, 0x65, 0x70, 0x65, 0x61, 0x74, 0x65, 0x64, 0x53, 0x69, 0x67, 0x6e, 0x65, 0x72, 0x2e, + 0x49, 0x6e, 0x6e, 0x65, 0x72, 0x52, 0x05, 0x69, 0x6e, 0x6e, 0x65, 0x72, 0x1a, 0x2c, 0x0a, 0x05, + 0x49, 0x6e, 0x6e, 0x65, 0x72, 0x12, 0x16, 0x0a, 0x06, 0x73, 0x69, 0x67, 0x6e, 0x65, 0x72, 0x18, + 0x01, 0x20, 0x03, 0x28, 0x09, 0x52, 0x06, 0x73, 0x69, 0x67, 0x6e, 0x65, 0x72, 0x3a, 0x0b, 0x82, + 0xe7, 0xb0, 0x2a, 0x06, 0x73, 0x69, 0x67, 0x6e, 0x65, 0x72, 0x3a, 0x0a, 0x82, 0xe7, 0xb0, 0x2a, + 0x05, 0x69, 0x6e, 0x6e, 0x65, 0x72, 0x22, 0x30, 0x0a, 0x09, 0x42, 0x61, 0x64, 0x53, 0x69, 0x67, + 0x6e, 0x65, 0x72, 0x12, 0x16, 0x0a, 0x06, 0x73, 0x69, 0x67, 0x6e, 0x65, 0x72, 0x18, 0x01, 0x20, + 0x01, 0x28, 0x0c, 0x52, 0x06, 0x73, 0x69, 0x67, 0x6e, 0x65, 0x72, 0x3a, 0x0b, 0x82, 0xe7, 0xb0, + 0x2a, 0x06, 0x73, 0x69, 0x67, 0x6e, 0x65, 0x72, 0x22, 0x28, 0x0a, 0x0e, 0x4e, 0x6f, 0x53, 0x69, + 0x67, 0x6e, 0x65, 0x72, 0x4f, 0x70, 0x74, 0x69, 0x6f, 0x6e, 0x12, 0x16, 0x0a, 0x06, 0x73, 0x69, + 0x67, 0x6e, 0x65, 0x72, 0x18, 0x01, 0x20, 0x01, 0x28, 0x0c, 0x52, 0x06, 0x73, 0x69, 0x67, 0x6e, + 0x65, 0x72, 0x22, 0x59, 0x0a, 0x0f, 0x56, 0x61, 0x6c, 0x69, 0x64, 0x61, 0x74, 0x6f, 0x72, 0x53, + 0x69, 0x67, 0x6e, 0x65, 0x72, 0x12, 0x39, 0x0a, 0x06, 0x73, 0x69, 0x67, 0x6e, 0x65, 0x72, 0x18, + 0x01, 0x20, 0x01, 0x28, 0x09, 0x42, 0x21, 0xd2, 0xb4, 0x2d, 0x1d, 0x63, 0x6f, 0x73, 0x6d, 0x6f, + 0x73, 0x2e, 0x56, 0x61, 0x6c, 0x69, 0x64, 0x61, 0x74, 0x6f, 0x72, 0x41, 0x64, 0x64, 0x72, 0x65, + 0x73, 0x73, 0x53, 0x74, 0x72, 0x69, 0x6e, 0x67, 0x52, 0x06, 0x73, 0x69, 0x67, 0x6e, 0x65, 0x72, + 0x3a, 0x0b, 0x82, 0xe7, 0xb0, 0x2a, 0x06, 0x73, 0x69, 0x67, 0x6e, 0x65, 0x72, 0x42, 0x3b, 0x42, + 0x0c, 0x53, 0x69, 0x67, 0x6e, 0x65, 0x72, 0x73, 0x50, 0x72, 0x6f, 0x74, 0x6f, 0x50, 0x01, 0x5a, + 0x29, 0x63, 0x6f, 0x73, 0x6d, 0x6f, 0x73, 0x73, 0x64, 0x6b, 0x2e, 0x69, 0x6f, 0x2f, 0x78, 0x2f, + 0x74, 0x78, 0x2f, 0x74, 0x65, 0x78, 0x74, 0x75, 0x61, 0x6c, 0x2f, 0x69, 0x6e, 0x74, 0x65, 0x72, + 0x6e, 0x61, 0x6c, 0x2f, 0x74, 0x65, 0x73, 0x74, 0x70, 0x62, 0x62, 0x06, 0x70, 0x72, 0x6f, 0x74, + 0x6f, 0x33, } var ( @@ -5918,7 +6382,7 @@ func file_signers_proto_rawDescGZIP() []byte { return file_signers_proto_rawDescData } -var file_signers_proto_msgTypes = make([]protoimpl.MessageInfo, 12) +var file_signers_proto_msgTypes = make([]protoimpl.MessageInfo, 13) var file_signers_proto_goTypes = []interface{}{ (*SimpleSigner)(nil), // 0: SimpleSigner (*RepeatedSigner)(nil), // 1: RepeatedSigner @@ -5928,16 +6392,17 @@ var file_signers_proto_goTypes = []interface{}{ (*RepeatedNestedRepeatedSigner)(nil), // 5: RepeatedNestedRepeatedSigner (*BadSigner)(nil), // 6: BadSigner (*NoSignerOption)(nil), // 7: NoSignerOption - (*NestedSigner_Inner)(nil), // 8: NestedSigner.Inner - (*RepeatedNestedSigner_Inner)(nil), // 9: RepeatedNestedSigner.Inner - (*NestedRepeatedSigner_Inner)(nil), // 10: NestedRepeatedSigner.Inner - (*RepeatedNestedRepeatedSigner_Inner)(nil), // 11: RepeatedNestedRepeatedSigner.Inner + (*ValidatorSigner)(nil), // 8: ValidatorSigner + (*NestedSigner_Inner)(nil), // 9: NestedSigner.Inner + (*RepeatedNestedSigner_Inner)(nil), // 10: RepeatedNestedSigner.Inner + (*NestedRepeatedSigner_Inner)(nil), // 11: NestedRepeatedSigner.Inner + (*RepeatedNestedRepeatedSigner_Inner)(nil), // 12: RepeatedNestedRepeatedSigner.Inner } var file_signers_proto_depIdxs = []int32{ - 8, // 0: NestedSigner.inner:type_name -> NestedSigner.Inner - 9, // 1: RepeatedNestedSigner.inner:type_name -> RepeatedNestedSigner.Inner - 10, // 2: NestedRepeatedSigner.inner:type_name -> NestedRepeatedSigner.Inner - 11, // 3: RepeatedNestedRepeatedSigner.inner:type_name -> RepeatedNestedRepeatedSigner.Inner + 9, // 0: NestedSigner.inner:type_name -> NestedSigner.Inner + 10, // 1: RepeatedNestedSigner.inner:type_name -> RepeatedNestedSigner.Inner + 11, // 2: NestedRepeatedSigner.inner:type_name -> NestedRepeatedSigner.Inner + 12, // 3: RepeatedNestedRepeatedSigner.inner:type_name -> RepeatedNestedRepeatedSigner.Inner 4, // [4:4] is the sub-list for method output_type 4, // [4:4] is the sub-list for method input_type 4, // [4:4] is the sub-list for extension type_name @@ -6048,7 +6513,7 @@ func file_signers_proto_init() { } } file_signers_proto_msgTypes[8].Exporter = func(v interface{}, i int) interface{} { - switch v := v.(*NestedSigner_Inner); i { + switch v := v.(*ValidatorSigner); i { case 0: return &v.state case 1: @@ -6060,7 +6525,7 @@ func file_signers_proto_init() { } } file_signers_proto_msgTypes[9].Exporter = func(v interface{}, i int) interface{} { - switch v := v.(*RepeatedNestedSigner_Inner); i { + switch v := v.(*NestedSigner_Inner); i { case 0: return &v.state case 1: @@ -6072,7 +6537,7 @@ func file_signers_proto_init() { } } file_signers_proto_msgTypes[10].Exporter = func(v interface{}, i int) interface{} { - switch v := v.(*NestedRepeatedSigner_Inner); i { + switch v := v.(*RepeatedNestedSigner_Inner); i { case 0: return &v.state case 1: @@ -6084,6 +6549,18 @@ func file_signers_proto_init() { } } file_signers_proto_msgTypes[11].Exporter = func(v interface{}, i int) interface{} { + switch v := v.(*NestedRepeatedSigner_Inner); i { + case 0: + return &v.state + case 1: + return &v.sizeCache + case 2: + return &v.unknownFields + default: + return nil + } + } + file_signers_proto_msgTypes[12].Exporter = func(v interface{}, i int) interface{} { switch v := v.(*RepeatedNestedRepeatedSigner_Inner); i { case 0: return &v.state @@ -6102,7 +6579,7 @@ func file_signers_proto_init() { GoPackagePath: reflect.TypeOf(x{}).PkgPath(), RawDescriptor: file_signers_proto_rawDesc, NumEnums: 0, - NumMessages: 12, + NumMessages: 13, NumExtensions: 0, NumServices: 0, }, diff --git a/x/tx/internal/testpb/unknownproto.proto b/x/tx/internal/testpb/unknownproto.proto new file mode 100644 index 000000000000..5b8fadcb5fd7 --- /dev/null +++ b/x/tx/internal/testpb/unknownproto.proto @@ -0,0 +1,305 @@ +syntax = "proto3"; +package testpb; + +import "google/protobuf/any.proto"; +import "cosmos/tx/v1beta1/tx.proto"; + +message Customer1 { + int32 id = 1; + string name = 2; + float subscription_fee = 3; + + string payment = 7; +} + +message Customer2 { + int32 id = 1; + int32 industry = 2; + string name = 3; + float fewer = 4; + + int64 reserved = 1047; + + enum City { + Laos = 0; + LosAngeles = 1; + PaloAlto = 2; + Moscow = 3; + Nairobi = 4; + } + + City city = 6; + + google.protobuf.Any miscellaneous = 10; +} + +message Nested4A { + int32 id = 1; + string name = 2; +} + +message Nested3A { + int32 id = 1; + string name = 2; + repeated Nested4A a4 = 4; + map index = 5; +} + +message Nested2A { + int32 id = 1; + string name = 2; + Nested3A nested = 3; +} + +message Nested1A { + int32 id = 1; + Nested2A nested = 2; +} + +message Nested4B { + int32 id = 1; + int32 age = 2; + string name = 3; +} + +message Nested3B { + int32 id = 1; + int32 age = 2; + string name = 3; + repeated Nested4B b4 = 4; +} + +message Nested2B { + int32 id = 1; + double fee = 2; + Nested3B nested = 3; + string route = 4; +} + +message Nested1B { + int32 id = 1; + Nested2B nested = 2; + int32 age = 3; +} + +message Customer3 { + int32 id = 1; + string name = 2; + float sf = 3; + float surcharge = 4; + string destination = 5; + + oneof payment { + string credit_card_no = 7; + string cheque_no = 8; + } + + Customer1 original = 9; +} + +message TestVersion1 { + int64 x = 1; + TestVersion1 a = 2; + TestVersion1 b = 3; // [(gogoproto.nullable) = false] generates invalid recursive structs; + repeated TestVersion1 c = 4; + repeated TestVersion1 d = 5; + oneof sum { + int32 e = 6; + TestVersion1 f = 7; + } + google.protobuf.Any g = 8; + repeated TestVersion1 h = 9; // [(gogoproto.castrepeated) = "TestVersion1"]; + // google.protobuf.Timestamp i = 10; + // google.protobuf.Timestamp j = 11; // [(gogoproto.stdtime) = true]; + Customer1 k = 12; +} +message TestVersion2 { + int64 x = 1; + TestVersion2 a = 2; + TestVersion2 b = 3; // [(gogoproto.nullable) = false]; + repeated TestVersion2 c = 4; + repeated TestVersion2 d = 5; // [(gogoproto.nullable) = false]; + oneof sum { + int32 e = 6; + TestVersion2 f = 7; + } + google.protobuf.Any g = 8; + repeated TestVersion1 h = 9; // [(gogoproto.castrepeated) = "TestVersion1"]; + // google.protobuf.Timestamp i = 10; + // google.protobuf.Timestamp j = 11; // [(gogoproto.stdtime) = true]; + Customer1 k = 12; + uint64 new_field = 25; +} +message TestVersion3 { + int64 x = 1; + TestVersion3 a = 2; + TestVersion3 b = 3; // [(gogoproto.nullable) = false]; + repeated TestVersion3 c = 4; + repeated TestVersion3 d = 5; // [(gogoproto.nullable) = false]; + oneof sum { + int32 e = 6; + TestVersion3 f = 7; + } + google.protobuf.Any g = 8; + repeated TestVersion1 h = 9; //[(gogoproto.castrepeated) = "TestVersion1"]; + // google.protobuf.Timestamp i = 10; + // google.protobuf.Timestamp j = 11; // [(gogoproto.stdtime) = true]; + Customer1 k = 12; + string non_critical_field = 1031; +} + +message TestVersion3LoneOneOfValue { + int64 x = 1; + TestVersion3 a = 2; + TestVersion3 b = 3; // [(gogoproto.nullable) = false]; + repeated TestVersion3 c = 4; + repeated TestVersion3 d = 5; // [(gogoproto.nullable) = false]; + oneof sum { + int32 e = 6; + } + google.protobuf.Any g = 8; + repeated TestVersion1 h = 9; //[(gogoproto.castrepeated) = "TestVersion1"]; + // google.protobuf.Timestamp i = 10; + // google.protobuf.Timestamp j = 11; // [(gogoproto.stdtime) = true]; + Customer1 k = 12; + string non_critical_field = 1031; +} + +message TestVersion3LoneNesting { + int64 x = 1; + TestVersion3 a = 2; + TestVersion3 b = 3; // [(gogoproto.nullable) = false]; + repeated TestVersion3 c = 4; + repeated TestVersion3 d = 5; // [(gogoproto.nullable) = false]; + oneof sum { + TestVersion3LoneNesting f = 7; + } + google.protobuf.Any g = 8; + repeated TestVersion1 h = 9; //[(gogoproto.castrepeated) = "TestVersion1"]; + // google.protobuf.Timestamp i = 10; + // google.protobuf.Timestamp j = 11; // [(gogoproto.stdtime) = true]; + Customer1 k = 12; + string non_critical_field = 1031; + + message Inner1 { + int64 id = 1; + string name = 2; + message InnerInner { + string id = 1; + string city = 2; + } + InnerInner inner = 3; + } + + Inner1 inner1 = 14; + + message Inner2 { + string id = 1; + string country = 2; + message InnerInner { + string id = 1; + string city = 2; + } + InnerInner inner = 3; + } + + Inner2 inner2 = 15; +} + +message TestVersion4LoneNesting { + int64 x = 1; + TestVersion3 a = 2; + TestVersion3 b = 3; // [(gogoproto.nullable) = false]; + repeated TestVersion3 c = 4; + repeated TestVersion3 d = 5; // [(gogoproto.nullable) = false]; + oneof sum { + TestVersion3LoneNesting f = 7; + } + google.protobuf.Any g = 8; + repeated TestVersion1 h = 9; //[(gogoproto.castrepeated) = "TestVersion1"]; + // google.protobuf.Timestamp i = 10; + // google.protobuf.Timestamp j = 11; // [(gogoproto.stdtime) = true]; + Customer1 k = 12; + string non_critical_field = 1031; + + message Inner1 { + int64 id = 1; + string name = 2; + message InnerInner { + int64 id = 1; + string city = 2; + } + InnerInner inner = 3; + } + + Inner1 inner1 = 14; + + message Inner2 { + string id = 1; + string country = 2; + message InnerInner { + string id = 1; + int64 value = 2; + } + InnerInner inner = 3; + } + + Inner2 inner2 = 15; +} + +message TestVersionFD1 { + int64 x = 1; + TestVersion1 a = 2; + oneof sum { + int32 e = 6; + TestVersion1 f = 7; + } + google.protobuf.Any g = 8; + repeated TestVersion1 h = 9; // [(gogoproto.castrepeated) = "TestVersion1"]; +} + +message TestVersionFD1WithExtraAny { + int64 x = 1; + TestVersion1 a = 2; + oneof sum { + int32 e = 6; + TestVersion1 f = 7; + } + AnyWithExtra g = 8; + repeated TestVersion1 h = 9; // [(gogoproto.castrepeated) = "TestVersion1"]; +} + +message AnyWithExtra { + google.protobuf.Any a = 1; + int64 b = 3; + int64 c = 4; +} + +message TestUpdatedTxRaw { + bytes body_bytes = 1; + bytes auth_info_bytes = 2; + repeated bytes signatures = 3; + bytes new_field_5 = 5; + bytes new_field_1024 = 1024; +} + +message TestUpdatedTxBody { + repeated google.protobuf.Any messages = 1; + string memo = 2; + int64 timeout_height = 3; + uint64 some_new_field = 4; + string some_new_field_non_critical_field = 1050; + repeated google.protobuf.Any extension_options = 1023; + repeated google.protobuf.Any non_critical_extension_options = 2047; +} + +message TestUpdatedAuthInfo { + repeated cosmos.tx.v1beta1.SignerInfo signer_infos = 1; + cosmos.tx.v1beta1.Fee fee = 2; + bytes new_field_3 = 3; + bytes new_field_1024 = 1024; +} + +message TestRepeatedUints { + repeated uint64 nums = 1; +} diff --git a/x/tx/internal/testpb/unknownproto.pulsar.go b/x/tx/internal/testpb/unknownproto.pulsar.go new file mode 100644 index 000000000000..cb0c8aa88365 --- /dev/null +++ b/x/tx/internal/testpb/unknownproto.pulsar.go @@ -0,0 +1,28034 @@ +// Code generated by protoc-gen-go-pulsar. DO NOT EDIT. +package testpb + +import ( + v1beta1 "cosmossdk.io/api/cosmos/tx/v1beta1" + binary "encoding/binary" + fmt "fmt" + runtime "github.com/cosmos/cosmos-proto/runtime" + protoreflect "google.golang.org/protobuf/reflect/protoreflect" + protoiface "google.golang.org/protobuf/runtime/protoiface" + protoimpl "google.golang.org/protobuf/runtime/protoimpl" + anypb "google.golang.org/protobuf/types/known/anypb" + io "io" + math "math" + reflect "reflect" + sort "sort" + sync "sync" +) + +var ( + md_Customer1 protoreflect.MessageDescriptor + fd_Customer1_id protoreflect.FieldDescriptor + fd_Customer1_name protoreflect.FieldDescriptor + fd_Customer1_subscription_fee protoreflect.FieldDescriptor + fd_Customer1_payment protoreflect.FieldDescriptor +) + +func init() { + file_unknownproto_proto_init() + md_Customer1 = File_unknownproto_proto.Messages().ByName("Customer1") + fd_Customer1_id = md_Customer1.Fields().ByName("id") + fd_Customer1_name = md_Customer1.Fields().ByName("name") + fd_Customer1_subscription_fee = md_Customer1.Fields().ByName("subscription_fee") + fd_Customer1_payment = md_Customer1.Fields().ByName("payment") +} + +var _ protoreflect.Message = (*fastReflection_Customer1)(nil) + +type fastReflection_Customer1 Customer1 + +func (x *Customer1) ProtoReflect() protoreflect.Message { + return (*fastReflection_Customer1)(x) +} + +func (x *Customer1) slowProtoReflect() protoreflect.Message { + mi := &file_unknownproto_proto_msgTypes[0] + if protoimpl.UnsafeEnabled && x != nil { + ms := protoimpl.X.MessageStateOf(protoimpl.Pointer(x)) + if ms.LoadMessageInfo() == nil { + ms.StoreMessageInfo(mi) + } + return ms + } + return mi.MessageOf(x) +} + +var _fastReflection_Customer1_messageType fastReflection_Customer1_messageType +var _ protoreflect.MessageType = fastReflection_Customer1_messageType{} + +type fastReflection_Customer1_messageType struct{} + +func (x fastReflection_Customer1_messageType) Zero() protoreflect.Message { + return (*fastReflection_Customer1)(nil) +} +func (x fastReflection_Customer1_messageType) New() protoreflect.Message { + return new(fastReflection_Customer1) +} +func (x fastReflection_Customer1_messageType) Descriptor() protoreflect.MessageDescriptor { + return md_Customer1 +} + +// Descriptor returns message descriptor, which contains only the protobuf +// type information for the message. +func (x *fastReflection_Customer1) Descriptor() protoreflect.MessageDescriptor { + return md_Customer1 +} + +// Type returns the message type, which encapsulates both Go and protobuf +// type information. If the Go type information is not needed, +// it is recommended that the message descriptor be used instead. +func (x *fastReflection_Customer1) Type() protoreflect.MessageType { + return _fastReflection_Customer1_messageType +} + +// New returns a newly allocated and mutable empty message. +func (x *fastReflection_Customer1) New() protoreflect.Message { + return new(fastReflection_Customer1) +} + +// Interface unwraps the message reflection interface and +// returns the underlying ProtoMessage interface. +func (x *fastReflection_Customer1) Interface() protoreflect.ProtoMessage { + return (*Customer1)(x) +} + +// Range iterates over every populated field in an undefined order, +// calling f for each field descriptor and value encountered. +// Range returns immediately if f returns false. +// While iterating, mutating operations may only be performed +// on the current field descriptor. +func (x *fastReflection_Customer1) Range(f func(protoreflect.FieldDescriptor, protoreflect.Value) bool) { + if x.Id != int32(0) { + value := protoreflect.ValueOfInt32(x.Id) + if !f(fd_Customer1_id, value) { + return + } + } + if x.Name != "" { + value := protoreflect.ValueOfString(x.Name) + if !f(fd_Customer1_name, value) { + return + } + } + if x.SubscriptionFee != float32(0) || math.Signbit(float64(x.SubscriptionFee)) { + value := protoreflect.ValueOfFloat32(x.SubscriptionFee) + if !f(fd_Customer1_subscription_fee, value) { + return + } + } + if x.Payment != "" { + value := protoreflect.ValueOfString(x.Payment) + if !f(fd_Customer1_payment, value) { + return + } + } +} + +// Has reports whether a field is populated. +// +// Some fields have the property of nullability where it is possible to +// distinguish between the default value of a field and whether the field +// was explicitly populated with the default value. Singular message fields, +// member fields of a oneof, and proto2 scalar fields are nullable. Such +// fields are populated only if explicitly set. +// +// In other cases (aside from the nullable cases above), +// a proto3 scalar field is populated if it contains a non-zero value, and +// a repeated field is populated if it is non-empty. +func (x *fastReflection_Customer1) Has(fd protoreflect.FieldDescriptor) bool { + switch fd.FullName() { + case "testpb.Customer1.id": + return x.Id != int32(0) + case "testpb.Customer1.name": + return x.Name != "" + case "testpb.Customer1.subscription_fee": + return x.SubscriptionFee != float32(0) || math.Signbit(float64(x.SubscriptionFee)) + case "testpb.Customer1.payment": + return x.Payment != "" + default: + if fd.IsExtension() { + panic(fmt.Errorf("proto3 declared messages do not support extensions: testpb.Customer1")) + } + panic(fmt.Errorf("message testpb.Customer1 does not contain field %s", fd.FullName())) + } +} + +// Clear clears the field such that a subsequent Has call reports false. +// +// Clearing an extension field clears both the extension type and value +// associated with the given field number. +// +// Clear is a mutating operation and unsafe for concurrent use. +func (x *fastReflection_Customer1) Clear(fd protoreflect.FieldDescriptor) { + switch fd.FullName() { + case "testpb.Customer1.id": + x.Id = int32(0) + case "testpb.Customer1.name": + x.Name = "" + case "testpb.Customer1.subscription_fee": + x.SubscriptionFee = float32(0) + case "testpb.Customer1.payment": + x.Payment = "" + default: + if fd.IsExtension() { + panic(fmt.Errorf("proto3 declared messages do not support extensions: testpb.Customer1")) + } + panic(fmt.Errorf("message testpb.Customer1 does not contain field %s", fd.FullName())) + } +} + +// Get retrieves the value for a field. +// +// For unpopulated scalars, it returns the default value, where +// the default value of a bytes scalar is guaranteed to be a copy. +// For unpopulated composite types, it returns an empty, read-only view +// of the value; to obtain a mutable reference, use Mutable. +func (x *fastReflection_Customer1) Get(descriptor protoreflect.FieldDescriptor) protoreflect.Value { + switch descriptor.FullName() { + case "testpb.Customer1.id": + value := x.Id + return protoreflect.ValueOfInt32(value) + case "testpb.Customer1.name": + value := x.Name + return protoreflect.ValueOfString(value) + case "testpb.Customer1.subscription_fee": + value := x.SubscriptionFee + return protoreflect.ValueOfFloat32(value) + case "testpb.Customer1.payment": + value := x.Payment + return protoreflect.ValueOfString(value) + default: + if descriptor.IsExtension() { + panic(fmt.Errorf("proto3 declared messages do not support extensions: testpb.Customer1")) + } + panic(fmt.Errorf("message testpb.Customer1 does not contain field %s", descriptor.FullName())) + } +} + +// Set stores the value for a field. +// +// For a field belonging to a oneof, it implicitly clears any other field +// that may be currently set within the same oneof. +// For extension fields, it implicitly stores the provided ExtensionType. +// When setting a composite type, it is unspecified whether the stored value +// aliases the source's memory in any way. If the composite value is an +// empty, read-only value, then it panics. +// +// Set is a mutating operation and unsafe for concurrent use. +func (x *fastReflection_Customer1) Set(fd protoreflect.FieldDescriptor, value protoreflect.Value) { + switch fd.FullName() { + case "testpb.Customer1.id": + x.Id = int32(value.Int()) + case "testpb.Customer1.name": + x.Name = value.Interface().(string) + case "testpb.Customer1.subscription_fee": + x.SubscriptionFee = float32(value.Float()) + case "testpb.Customer1.payment": + x.Payment = value.Interface().(string) + default: + if fd.IsExtension() { + panic(fmt.Errorf("proto3 declared messages do not support extensions: testpb.Customer1")) + } + panic(fmt.Errorf("message testpb.Customer1 does not contain field %s", fd.FullName())) + } +} + +// Mutable returns a mutable reference to a composite type. +// +// If the field is unpopulated, it may allocate a composite value. +// For a field belonging to a oneof, it implicitly clears any other field +// that may be currently set within the same oneof. +// For extension fields, it implicitly stores the provided ExtensionType +// if not already stored. +// It panics if the field does not contain a composite type. +// +// Mutable is a mutating operation and unsafe for concurrent use. +func (x *fastReflection_Customer1) Mutable(fd protoreflect.FieldDescriptor) protoreflect.Value { + switch fd.FullName() { + case "testpb.Customer1.id": + panic(fmt.Errorf("field id of message testpb.Customer1 is not mutable")) + case "testpb.Customer1.name": + panic(fmt.Errorf("field name of message testpb.Customer1 is not mutable")) + case "testpb.Customer1.subscription_fee": + panic(fmt.Errorf("field subscription_fee of message testpb.Customer1 is not mutable")) + case "testpb.Customer1.payment": + panic(fmt.Errorf("field payment of message testpb.Customer1 is not mutable")) + default: + if fd.IsExtension() { + panic(fmt.Errorf("proto3 declared messages do not support extensions: testpb.Customer1")) + } + panic(fmt.Errorf("message testpb.Customer1 does not contain field %s", fd.FullName())) + } +} + +// NewField returns a new value that is assignable to the field +// for the given descriptor. For scalars, this returns the default value. +// For lists, maps, and messages, this returns a new, empty, mutable value. +func (x *fastReflection_Customer1) NewField(fd protoreflect.FieldDescriptor) protoreflect.Value { + switch fd.FullName() { + case "testpb.Customer1.id": + return protoreflect.ValueOfInt32(int32(0)) + case "testpb.Customer1.name": + return protoreflect.ValueOfString("") + case "testpb.Customer1.subscription_fee": + return protoreflect.ValueOfFloat32(float32(0)) + case "testpb.Customer1.payment": + return protoreflect.ValueOfString("") + default: + if fd.IsExtension() { + panic(fmt.Errorf("proto3 declared messages do not support extensions: testpb.Customer1")) + } + panic(fmt.Errorf("message testpb.Customer1 does not contain field %s", fd.FullName())) + } +} + +// WhichOneof reports which field within the oneof is populated, +// returning nil if none are populated. +// It panics if the oneof descriptor does not belong to this message. +func (x *fastReflection_Customer1) WhichOneof(d protoreflect.OneofDescriptor) protoreflect.FieldDescriptor { + switch d.FullName() { + default: + panic(fmt.Errorf("%s is not a oneof field in testpb.Customer1", d.FullName())) + } + panic("unreachable") +} + +// GetUnknown retrieves the entire list of unknown fields. +// The caller may only mutate the contents of the RawFields +// if the mutated bytes are stored back into the message with SetUnknown. +func (x *fastReflection_Customer1) GetUnknown() protoreflect.RawFields { + return x.unknownFields +} + +// SetUnknown stores an entire list of unknown fields. +// The raw fields must be syntactically valid according to the wire format. +// An implementation may panic if this is not the case. +// Once stored, the caller must not mutate the content of the RawFields. +// An empty RawFields may be passed to clear the fields. +// +// SetUnknown is a mutating operation and unsafe for concurrent use. +func (x *fastReflection_Customer1) SetUnknown(fields protoreflect.RawFields) { + x.unknownFields = fields +} + +// IsValid reports whether the message is valid. +// +// An invalid message is an empty, read-only value. +// +// An invalid message often corresponds to a nil pointer of the concrete +// message type, but the details are implementation dependent. +// Validity is not part of the protobuf data model, and may not +// be preserved in marshaling or other operations. +func (x *fastReflection_Customer1) IsValid() bool { + return x != nil +} + +// ProtoMethods returns optional fastReflectionFeature-path implementations of various operations. +// This method may return nil. +// +// The returned methods type is identical to +// "google.golang.org/protobuf/runtime/protoiface".Methods. +// Consult the protoiface package documentation for details. +func (x *fastReflection_Customer1) ProtoMethods() *protoiface.Methods { + size := func(input protoiface.SizeInput) protoiface.SizeOutput { + x := input.Message.Interface().(*Customer1) + if x == nil { + return protoiface.SizeOutput{ + NoUnkeyedLiterals: input.NoUnkeyedLiterals, + Size: 0, + } + } + options := runtime.SizeInputToOptions(input) + _ = options + var n int + var l int + _ = l + if x.Id != 0 { + n += 1 + runtime.Sov(uint64(x.Id)) + } + l = len(x.Name) + if l > 0 { + n += 1 + l + runtime.Sov(uint64(l)) + } + if x.SubscriptionFee != 0 || math.Signbit(float64(x.SubscriptionFee)) { + n += 5 + } + l = len(x.Payment) + if l > 0 { + n += 1 + l + runtime.Sov(uint64(l)) + } + if x.unknownFields != nil { + n += len(x.unknownFields) + } + return protoiface.SizeOutput{ + NoUnkeyedLiterals: input.NoUnkeyedLiterals, + Size: n, + } + } + + marshal := func(input protoiface.MarshalInput) (protoiface.MarshalOutput, error) { + x := input.Message.Interface().(*Customer1) + if x == nil { + return protoiface.MarshalOutput{ + NoUnkeyedLiterals: input.NoUnkeyedLiterals, + Buf: input.Buf, + }, nil + } + options := runtime.MarshalInputToOptions(input) + _ = options + size := options.Size(x) + dAtA := make([]byte, size) + i := len(dAtA) + _ = i + var l int + _ = l + if x.unknownFields != nil { + i -= len(x.unknownFields) + copy(dAtA[i:], x.unknownFields) + } + if len(x.Payment) > 0 { + i -= len(x.Payment) + copy(dAtA[i:], x.Payment) + i = runtime.EncodeVarint(dAtA, i, uint64(len(x.Payment))) + i-- + dAtA[i] = 0x3a + } + if x.SubscriptionFee != 0 || math.Signbit(float64(x.SubscriptionFee)) { + i -= 4 + binary.LittleEndian.PutUint32(dAtA[i:], uint32(math.Float32bits(float32(x.SubscriptionFee)))) + i-- + dAtA[i] = 0x1d + } + if len(x.Name) > 0 { + i -= len(x.Name) + copy(dAtA[i:], x.Name) + i = runtime.EncodeVarint(dAtA, i, uint64(len(x.Name))) + i-- + dAtA[i] = 0x12 + } + if x.Id != 0 { + i = runtime.EncodeVarint(dAtA, i, uint64(x.Id)) + i-- + dAtA[i] = 0x8 + } + if input.Buf != nil { + input.Buf = append(input.Buf, dAtA...) + } else { + input.Buf = dAtA + } + return protoiface.MarshalOutput{ + NoUnkeyedLiterals: input.NoUnkeyedLiterals, + Buf: input.Buf, + }, nil + } + unmarshal := func(input protoiface.UnmarshalInput) (protoiface.UnmarshalOutput, error) { + x := input.Message.Interface().(*Customer1) + if x == nil { + return protoiface.UnmarshalOutput{ + NoUnkeyedLiterals: input.NoUnkeyedLiterals, + Flags: input.Flags, + }, nil + } + options := runtime.UnmarshalInputToOptions(input) + _ = options + dAtA := input.Buf + l := len(dAtA) + iNdEx := 0 + for iNdEx < l { + preIndex := iNdEx + var wire uint64 + for shift := uint(0); ; shift += 7 { + if shift >= 64 { + return protoiface.UnmarshalOutput{NoUnkeyedLiterals: input.NoUnkeyedLiterals, Flags: input.Flags}, runtime.ErrIntOverflow + } + if iNdEx >= l { + return protoiface.UnmarshalOutput{NoUnkeyedLiterals: input.NoUnkeyedLiterals, Flags: input.Flags}, io.ErrUnexpectedEOF + } + b := dAtA[iNdEx] + iNdEx++ + wire |= uint64(b&0x7F) << shift + if b < 0x80 { + break + } + } + fieldNum := int32(wire >> 3) + wireType := int(wire & 0x7) + if wireType == 4 { + return protoiface.UnmarshalOutput{NoUnkeyedLiterals: input.NoUnkeyedLiterals, Flags: input.Flags}, fmt.Errorf("proto: Customer1: wiretype end group for non-group") + } + if fieldNum <= 0 { + return protoiface.UnmarshalOutput{NoUnkeyedLiterals: input.NoUnkeyedLiterals, Flags: input.Flags}, fmt.Errorf("proto: Customer1: illegal tag %d (wire type %d)", fieldNum, wire) + } + switch fieldNum { + case 1: + if wireType != 0 { + return protoiface.UnmarshalOutput{NoUnkeyedLiterals: input.NoUnkeyedLiterals, Flags: input.Flags}, fmt.Errorf("proto: wrong wireType = %d for field Id", wireType) + } + x.Id = 0 + for shift := uint(0); ; shift += 7 { + if shift >= 64 { + return protoiface.UnmarshalOutput{NoUnkeyedLiterals: input.NoUnkeyedLiterals, Flags: input.Flags}, runtime.ErrIntOverflow + } + if iNdEx >= l { + return protoiface.UnmarshalOutput{NoUnkeyedLiterals: input.NoUnkeyedLiterals, Flags: input.Flags}, io.ErrUnexpectedEOF + } + b := dAtA[iNdEx] + iNdEx++ + x.Id |= int32(b&0x7F) << shift + if b < 0x80 { + break + } + } + case 2: + if wireType != 2 { + return protoiface.UnmarshalOutput{NoUnkeyedLiterals: input.NoUnkeyedLiterals, Flags: input.Flags}, fmt.Errorf("proto: wrong wireType = %d for field Name", wireType) + } + var stringLen uint64 + for shift := uint(0); ; shift += 7 { + if shift >= 64 { + return protoiface.UnmarshalOutput{NoUnkeyedLiterals: input.NoUnkeyedLiterals, Flags: input.Flags}, runtime.ErrIntOverflow + } + if iNdEx >= l { + return protoiface.UnmarshalOutput{NoUnkeyedLiterals: input.NoUnkeyedLiterals, Flags: input.Flags}, io.ErrUnexpectedEOF + } + b := dAtA[iNdEx] + iNdEx++ + stringLen |= uint64(b&0x7F) << shift + if b < 0x80 { + break + } + } + intStringLen := int(stringLen) + if intStringLen < 0 { + return protoiface.UnmarshalOutput{NoUnkeyedLiterals: input.NoUnkeyedLiterals, Flags: input.Flags}, runtime.ErrInvalidLength + } + postIndex := iNdEx + intStringLen + if postIndex < 0 { + return protoiface.UnmarshalOutput{NoUnkeyedLiterals: input.NoUnkeyedLiterals, Flags: input.Flags}, runtime.ErrInvalidLength + } + if postIndex > l { + return protoiface.UnmarshalOutput{NoUnkeyedLiterals: input.NoUnkeyedLiterals, Flags: input.Flags}, io.ErrUnexpectedEOF + } + x.Name = string(dAtA[iNdEx:postIndex]) + iNdEx = postIndex + case 3: + if wireType != 5 { + return protoiface.UnmarshalOutput{NoUnkeyedLiterals: input.NoUnkeyedLiterals, Flags: input.Flags}, fmt.Errorf("proto: wrong wireType = %d for field SubscriptionFee", wireType) + } + var v uint32 + if (iNdEx + 4) > l { + return protoiface.UnmarshalOutput{NoUnkeyedLiterals: input.NoUnkeyedLiterals, Flags: input.Flags}, io.ErrUnexpectedEOF + } + v = uint32(binary.LittleEndian.Uint32(dAtA[iNdEx:])) + iNdEx += 4 + x.SubscriptionFee = float32(math.Float32frombits(v)) + case 7: + if wireType != 2 { + return protoiface.UnmarshalOutput{NoUnkeyedLiterals: input.NoUnkeyedLiterals, Flags: input.Flags}, fmt.Errorf("proto: wrong wireType = %d for field Payment", wireType) + } + var stringLen uint64 + for shift := uint(0); ; shift += 7 { + if shift >= 64 { + return protoiface.UnmarshalOutput{NoUnkeyedLiterals: input.NoUnkeyedLiterals, Flags: input.Flags}, runtime.ErrIntOverflow + } + if iNdEx >= l { + return protoiface.UnmarshalOutput{NoUnkeyedLiterals: input.NoUnkeyedLiterals, Flags: input.Flags}, io.ErrUnexpectedEOF + } + b := dAtA[iNdEx] + iNdEx++ + stringLen |= uint64(b&0x7F) << shift + if b < 0x80 { + break + } + } + intStringLen := int(stringLen) + if intStringLen < 0 { + return protoiface.UnmarshalOutput{NoUnkeyedLiterals: input.NoUnkeyedLiterals, Flags: input.Flags}, runtime.ErrInvalidLength + } + postIndex := iNdEx + intStringLen + if postIndex < 0 { + return protoiface.UnmarshalOutput{NoUnkeyedLiterals: input.NoUnkeyedLiterals, Flags: input.Flags}, runtime.ErrInvalidLength + } + if postIndex > l { + return protoiface.UnmarshalOutput{NoUnkeyedLiterals: input.NoUnkeyedLiterals, Flags: input.Flags}, io.ErrUnexpectedEOF + } + x.Payment = string(dAtA[iNdEx:postIndex]) + iNdEx = postIndex + default: + iNdEx = preIndex + skippy, err := runtime.Skip(dAtA[iNdEx:]) + if err != nil { + return protoiface.UnmarshalOutput{NoUnkeyedLiterals: input.NoUnkeyedLiterals, Flags: input.Flags}, err + } + if (skippy < 0) || (iNdEx+skippy) < 0 { + return protoiface.UnmarshalOutput{NoUnkeyedLiterals: input.NoUnkeyedLiterals, Flags: input.Flags}, runtime.ErrInvalidLength + } + if (iNdEx + skippy) > l { + return protoiface.UnmarshalOutput{NoUnkeyedLiterals: input.NoUnkeyedLiterals, Flags: input.Flags}, io.ErrUnexpectedEOF + } + if !options.DiscardUnknown { + x.unknownFields = append(x.unknownFields, dAtA[iNdEx:iNdEx+skippy]...) + } + iNdEx += skippy + } + } + + if iNdEx > l { + return protoiface.UnmarshalOutput{NoUnkeyedLiterals: input.NoUnkeyedLiterals, Flags: input.Flags}, io.ErrUnexpectedEOF + } + return protoiface.UnmarshalOutput{NoUnkeyedLiterals: input.NoUnkeyedLiterals, Flags: input.Flags}, nil + } + return &protoiface.Methods{ + NoUnkeyedLiterals: struct{}{}, + Flags: protoiface.SupportMarshalDeterministic | protoiface.SupportUnmarshalDiscardUnknown, + Size: size, + Marshal: marshal, + Unmarshal: unmarshal, + Merge: nil, + CheckInitialized: nil, + } +} + +var ( + md_Customer2 protoreflect.MessageDescriptor + fd_Customer2_id protoreflect.FieldDescriptor + fd_Customer2_industry protoreflect.FieldDescriptor + fd_Customer2_name protoreflect.FieldDescriptor + fd_Customer2_fewer protoreflect.FieldDescriptor + fd_Customer2_reserved protoreflect.FieldDescriptor + fd_Customer2_city protoreflect.FieldDescriptor + fd_Customer2_miscellaneous protoreflect.FieldDescriptor +) + +func init() { + file_unknownproto_proto_init() + md_Customer2 = File_unknownproto_proto.Messages().ByName("Customer2") + fd_Customer2_id = md_Customer2.Fields().ByName("id") + fd_Customer2_industry = md_Customer2.Fields().ByName("industry") + fd_Customer2_name = md_Customer2.Fields().ByName("name") + fd_Customer2_fewer = md_Customer2.Fields().ByName("fewer") + fd_Customer2_reserved = md_Customer2.Fields().ByName("reserved") + fd_Customer2_city = md_Customer2.Fields().ByName("city") + fd_Customer2_miscellaneous = md_Customer2.Fields().ByName("miscellaneous") +} + +var _ protoreflect.Message = (*fastReflection_Customer2)(nil) + +type fastReflection_Customer2 Customer2 + +func (x *Customer2) ProtoReflect() protoreflect.Message { + return (*fastReflection_Customer2)(x) +} + +func (x *Customer2) slowProtoReflect() protoreflect.Message { + mi := &file_unknownproto_proto_msgTypes[1] + if protoimpl.UnsafeEnabled && x != nil { + ms := protoimpl.X.MessageStateOf(protoimpl.Pointer(x)) + if ms.LoadMessageInfo() == nil { + ms.StoreMessageInfo(mi) + } + return ms + } + return mi.MessageOf(x) +} + +var _fastReflection_Customer2_messageType fastReflection_Customer2_messageType +var _ protoreflect.MessageType = fastReflection_Customer2_messageType{} + +type fastReflection_Customer2_messageType struct{} + +func (x fastReflection_Customer2_messageType) Zero() protoreflect.Message { + return (*fastReflection_Customer2)(nil) +} +func (x fastReflection_Customer2_messageType) New() protoreflect.Message { + return new(fastReflection_Customer2) +} +func (x fastReflection_Customer2_messageType) Descriptor() protoreflect.MessageDescriptor { + return md_Customer2 +} + +// Descriptor returns message descriptor, which contains only the protobuf +// type information for the message. +func (x *fastReflection_Customer2) Descriptor() protoreflect.MessageDescriptor { + return md_Customer2 +} + +// Type returns the message type, which encapsulates both Go and protobuf +// type information. If the Go type information is not needed, +// it is recommended that the message descriptor be used instead. +func (x *fastReflection_Customer2) Type() protoreflect.MessageType { + return _fastReflection_Customer2_messageType +} + +// New returns a newly allocated and mutable empty message. +func (x *fastReflection_Customer2) New() protoreflect.Message { + return new(fastReflection_Customer2) +} + +// Interface unwraps the message reflection interface and +// returns the underlying ProtoMessage interface. +func (x *fastReflection_Customer2) Interface() protoreflect.ProtoMessage { + return (*Customer2)(x) +} + +// Range iterates over every populated field in an undefined order, +// calling f for each field descriptor and value encountered. +// Range returns immediately if f returns false. +// While iterating, mutating operations may only be performed +// on the current field descriptor. +func (x *fastReflection_Customer2) Range(f func(protoreflect.FieldDescriptor, protoreflect.Value) bool) { + if x.Id != int32(0) { + value := protoreflect.ValueOfInt32(x.Id) + if !f(fd_Customer2_id, value) { + return + } + } + if x.Industry != int32(0) { + value := protoreflect.ValueOfInt32(x.Industry) + if !f(fd_Customer2_industry, value) { + return + } + } + if x.Name != "" { + value := protoreflect.ValueOfString(x.Name) + if !f(fd_Customer2_name, value) { + return + } + } + if x.Fewer != float32(0) || math.Signbit(float64(x.Fewer)) { + value := protoreflect.ValueOfFloat32(x.Fewer) + if !f(fd_Customer2_fewer, value) { + return + } + } + if x.Reserved != int64(0) { + value := protoreflect.ValueOfInt64(x.Reserved) + if !f(fd_Customer2_reserved, value) { + return + } + } + if x.City != 0 { + value := protoreflect.ValueOfEnum((protoreflect.EnumNumber)(x.City)) + if !f(fd_Customer2_city, value) { + return + } + } + if x.Miscellaneous != nil { + value := protoreflect.ValueOfMessage(x.Miscellaneous.ProtoReflect()) + if !f(fd_Customer2_miscellaneous, value) { + return + } + } +} + +// Has reports whether a field is populated. +// +// Some fields have the property of nullability where it is possible to +// distinguish between the default value of a field and whether the field +// was explicitly populated with the default value. Singular message fields, +// member fields of a oneof, and proto2 scalar fields are nullable. Such +// fields are populated only if explicitly set. +// +// In other cases (aside from the nullable cases above), +// a proto3 scalar field is populated if it contains a non-zero value, and +// a repeated field is populated if it is non-empty. +func (x *fastReflection_Customer2) Has(fd protoreflect.FieldDescriptor) bool { + switch fd.FullName() { + case "testpb.Customer2.id": + return x.Id != int32(0) + case "testpb.Customer2.industry": + return x.Industry != int32(0) + case "testpb.Customer2.name": + return x.Name != "" + case "testpb.Customer2.fewer": + return x.Fewer != float32(0) || math.Signbit(float64(x.Fewer)) + case "testpb.Customer2.reserved": + return x.Reserved != int64(0) + case "testpb.Customer2.city": + return x.City != 0 + case "testpb.Customer2.miscellaneous": + return x.Miscellaneous != nil + default: + if fd.IsExtension() { + panic(fmt.Errorf("proto3 declared messages do not support extensions: testpb.Customer2")) + } + panic(fmt.Errorf("message testpb.Customer2 does not contain field %s", fd.FullName())) + } +} + +// Clear clears the field such that a subsequent Has call reports false. +// +// Clearing an extension field clears both the extension type and value +// associated with the given field number. +// +// Clear is a mutating operation and unsafe for concurrent use. +func (x *fastReflection_Customer2) Clear(fd protoreflect.FieldDescriptor) { + switch fd.FullName() { + case "testpb.Customer2.id": + x.Id = int32(0) + case "testpb.Customer2.industry": + x.Industry = int32(0) + case "testpb.Customer2.name": + x.Name = "" + case "testpb.Customer2.fewer": + x.Fewer = float32(0) + case "testpb.Customer2.reserved": + x.Reserved = int64(0) + case "testpb.Customer2.city": + x.City = 0 + case "testpb.Customer2.miscellaneous": + x.Miscellaneous = nil + default: + if fd.IsExtension() { + panic(fmt.Errorf("proto3 declared messages do not support extensions: testpb.Customer2")) + } + panic(fmt.Errorf("message testpb.Customer2 does not contain field %s", fd.FullName())) + } +} + +// Get retrieves the value for a field. +// +// For unpopulated scalars, it returns the default value, where +// the default value of a bytes scalar is guaranteed to be a copy. +// For unpopulated composite types, it returns an empty, read-only view +// of the value; to obtain a mutable reference, use Mutable. +func (x *fastReflection_Customer2) Get(descriptor protoreflect.FieldDescriptor) protoreflect.Value { + switch descriptor.FullName() { + case "testpb.Customer2.id": + value := x.Id + return protoreflect.ValueOfInt32(value) + case "testpb.Customer2.industry": + value := x.Industry + return protoreflect.ValueOfInt32(value) + case "testpb.Customer2.name": + value := x.Name + return protoreflect.ValueOfString(value) + case "testpb.Customer2.fewer": + value := x.Fewer + return protoreflect.ValueOfFloat32(value) + case "testpb.Customer2.reserved": + value := x.Reserved + return protoreflect.ValueOfInt64(value) + case "testpb.Customer2.city": + value := x.City + return protoreflect.ValueOfEnum((protoreflect.EnumNumber)(value)) + case "testpb.Customer2.miscellaneous": + value := x.Miscellaneous + return protoreflect.ValueOfMessage(value.ProtoReflect()) + default: + if descriptor.IsExtension() { + panic(fmt.Errorf("proto3 declared messages do not support extensions: testpb.Customer2")) + } + panic(fmt.Errorf("message testpb.Customer2 does not contain field %s", descriptor.FullName())) + } +} + +// Set stores the value for a field. +// +// For a field belonging to a oneof, it implicitly clears any other field +// that may be currently set within the same oneof. +// For extension fields, it implicitly stores the provided ExtensionType. +// When setting a composite type, it is unspecified whether the stored value +// aliases the source's memory in any way. If the composite value is an +// empty, read-only value, then it panics. +// +// Set is a mutating operation and unsafe for concurrent use. +func (x *fastReflection_Customer2) Set(fd protoreflect.FieldDescriptor, value protoreflect.Value) { + switch fd.FullName() { + case "testpb.Customer2.id": + x.Id = int32(value.Int()) + case "testpb.Customer2.industry": + x.Industry = int32(value.Int()) + case "testpb.Customer2.name": + x.Name = value.Interface().(string) + case "testpb.Customer2.fewer": + x.Fewer = float32(value.Float()) + case "testpb.Customer2.reserved": + x.Reserved = value.Int() + case "testpb.Customer2.city": + x.City = (Customer2_City)(value.Enum()) + case "testpb.Customer2.miscellaneous": + x.Miscellaneous = value.Message().Interface().(*anypb.Any) + default: + if fd.IsExtension() { + panic(fmt.Errorf("proto3 declared messages do not support extensions: testpb.Customer2")) + } + panic(fmt.Errorf("message testpb.Customer2 does not contain field %s", fd.FullName())) + } +} + +// Mutable returns a mutable reference to a composite type. +// +// If the field is unpopulated, it may allocate a composite value. +// For a field belonging to a oneof, it implicitly clears any other field +// that may be currently set within the same oneof. +// For extension fields, it implicitly stores the provided ExtensionType +// if not already stored. +// It panics if the field does not contain a composite type. +// +// Mutable is a mutating operation and unsafe for concurrent use. +func (x *fastReflection_Customer2) Mutable(fd protoreflect.FieldDescriptor) protoreflect.Value { + switch fd.FullName() { + case "testpb.Customer2.miscellaneous": + if x.Miscellaneous == nil { + x.Miscellaneous = new(anypb.Any) + } + return protoreflect.ValueOfMessage(x.Miscellaneous.ProtoReflect()) + case "testpb.Customer2.id": + panic(fmt.Errorf("field id of message testpb.Customer2 is not mutable")) + case "testpb.Customer2.industry": + panic(fmt.Errorf("field industry of message testpb.Customer2 is not mutable")) + case "testpb.Customer2.name": + panic(fmt.Errorf("field name of message testpb.Customer2 is not mutable")) + case "testpb.Customer2.fewer": + panic(fmt.Errorf("field fewer of message testpb.Customer2 is not mutable")) + case "testpb.Customer2.reserved": + panic(fmt.Errorf("field reserved of message testpb.Customer2 is not mutable")) + case "testpb.Customer2.city": + panic(fmt.Errorf("field city of message testpb.Customer2 is not mutable")) + default: + if fd.IsExtension() { + panic(fmt.Errorf("proto3 declared messages do not support extensions: testpb.Customer2")) + } + panic(fmt.Errorf("message testpb.Customer2 does not contain field %s", fd.FullName())) + } +} + +// NewField returns a new value that is assignable to the field +// for the given descriptor. For scalars, this returns the default value. +// For lists, maps, and messages, this returns a new, empty, mutable value. +func (x *fastReflection_Customer2) NewField(fd protoreflect.FieldDescriptor) protoreflect.Value { + switch fd.FullName() { + case "testpb.Customer2.id": + return protoreflect.ValueOfInt32(int32(0)) + case "testpb.Customer2.industry": + return protoreflect.ValueOfInt32(int32(0)) + case "testpb.Customer2.name": + return protoreflect.ValueOfString("") + case "testpb.Customer2.fewer": + return protoreflect.ValueOfFloat32(float32(0)) + case "testpb.Customer2.reserved": + return protoreflect.ValueOfInt64(int64(0)) + case "testpb.Customer2.city": + return protoreflect.ValueOfEnum(0) + case "testpb.Customer2.miscellaneous": + m := new(anypb.Any) + return protoreflect.ValueOfMessage(m.ProtoReflect()) + default: + if fd.IsExtension() { + panic(fmt.Errorf("proto3 declared messages do not support extensions: testpb.Customer2")) + } + panic(fmt.Errorf("message testpb.Customer2 does not contain field %s", fd.FullName())) + } +} + +// WhichOneof reports which field within the oneof is populated, +// returning nil if none are populated. +// It panics if the oneof descriptor does not belong to this message. +func (x *fastReflection_Customer2) WhichOneof(d protoreflect.OneofDescriptor) protoreflect.FieldDescriptor { + switch d.FullName() { + default: + panic(fmt.Errorf("%s is not a oneof field in testpb.Customer2", d.FullName())) + } + panic("unreachable") +} + +// GetUnknown retrieves the entire list of unknown fields. +// The caller may only mutate the contents of the RawFields +// if the mutated bytes are stored back into the message with SetUnknown. +func (x *fastReflection_Customer2) GetUnknown() protoreflect.RawFields { + return x.unknownFields +} + +// SetUnknown stores an entire list of unknown fields. +// The raw fields must be syntactically valid according to the wire format. +// An implementation may panic if this is not the case. +// Once stored, the caller must not mutate the content of the RawFields. +// An empty RawFields may be passed to clear the fields. +// +// SetUnknown is a mutating operation and unsafe for concurrent use. +func (x *fastReflection_Customer2) SetUnknown(fields protoreflect.RawFields) { + x.unknownFields = fields +} + +// IsValid reports whether the message is valid. +// +// An invalid message is an empty, read-only value. +// +// An invalid message often corresponds to a nil pointer of the concrete +// message type, but the details are implementation dependent. +// Validity is not part of the protobuf data model, and may not +// be preserved in marshaling or other operations. +func (x *fastReflection_Customer2) IsValid() bool { + return x != nil +} + +// ProtoMethods returns optional fastReflectionFeature-path implementations of various operations. +// This method may return nil. +// +// The returned methods type is identical to +// "google.golang.org/protobuf/runtime/protoiface".Methods. +// Consult the protoiface package documentation for details. +func (x *fastReflection_Customer2) ProtoMethods() *protoiface.Methods { + size := func(input protoiface.SizeInput) protoiface.SizeOutput { + x := input.Message.Interface().(*Customer2) + if x == nil { + return protoiface.SizeOutput{ + NoUnkeyedLiterals: input.NoUnkeyedLiterals, + Size: 0, + } + } + options := runtime.SizeInputToOptions(input) + _ = options + var n int + var l int + _ = l + if x.Id != 0 { + n += 1 + runtime.Sov(uint64(x.Id)) + } + if x.Industry != 0 { + n += 1 + runtime.Sov(uint64(x.Industry)) + } + l = len(x.Name) + if l > 0 { + n += 1 + l + runtime.Sov(uint64(l)) + } + if x.Fewer != 0 || math.Signbit(float64(x.Fewer)) { + n += 5 + } + if x.Reserved != 0 { + n += 2 + runtime.Sov(uint64(x.Reserved)) + } + if x.City != 0 { + n += 1 + runtime.Sov(uint64(x.City)) + } + if x.Miscellaneous != nil { + l = options.Size(x.Miscellaneous) + n += 1 + l + runtime.Sov(uint64(l)) + } + if x.unknownFields != nil { + n += len(x.unknownFields) + } + return protoiface.SizeOutput{ + NoUnkeyedLiterals: input.NoUnkeyedLiterals, + Size: n, + } + } + + marshal := func(input protoiface.MarshalInput) (protoiface.MarshalOutput, error) { + x := input.Message.Interface().(*Customer2) + if x == nil { + return protoiface.MarshalOutput{ + NoUnkeyedLiterals: input.NoUnkeyedLiterals, + Buf: input.Buf, + }, nil + } + options := runtime.MarshalInputToOptions(input) + _ = options + size := options.Size(x) + dAtA := make([]byte, size) + i := len(dAtA) + _ = i + var l int + _ = l + if x.unknownFields != nil { + i -= len(x.unknownFields) + copy(dAtA[i:], x.unknownFields) + } + if x.Reserved != 0 { + i = runtime.EncodeVarint(dAtA, i, uint64(x.Reserved)) + i-- + dAtA[i] = 0x41 + i-- + dAtA[i] = 0xb8 + } + if x.Miscellaneous != nil { + encoded, err := options.Marshal(x.Miscellaneous) + if err != nil { + return protoiface.MarshalOutput{ + NoUnkeyedLiterals: input.NoUnkeyedLiterals, + Buf: input.Buf, + }, err + } + i -= len(encoded) + copy(dAtA[i:], encoded) + i = runtime.EncodeVarint(dAtA, i, uint64(len(encoded))) + i-- + dAtA[i] = 0x52 + } + if x.City != 0 { + i = runtime.EncodeVarint(dAtA, i, uint64(x.City)) + i-- + dAtA[i] = 0x30 + } + if x.Fewer != 0 || math.Signbit(float64(x.Fewer)) { + i -= 4 + binary.LittleEndian.PutUint32(dAtA[i:], uint32(math.Float32bits(float32(x.Fewer)))) + i-- + dAtA[i] = 0x25 + } + if len(x.Name) > 0 { + i -= len(x.Name) + copy(dAtA[i:], x.Name) + i = runtime.EncodeVarint(dAtA, i, uint64(len(x.Name))) + i-- + dAtA[i] = 0x1a + } + if x.Industry != 0 { + i = runtime.EncodeVarint(dAtA, i, uint64(x.Industry)) + i-- + dAtA[i] = 0x10 + } + if x.Id != 0 { + i = runtime.EncodeVarint(dAtA, i, uint64(x.Id)) + i-- + dAtA[i] = 0x8 + } + if input.Buf != nil { + input.Buf = append(input.Buf, dAtA...) + } else { + input.Buf = dAtA + } + return protoiface.MarshalOutput{ + NoUnkeyedLiterals: input.NoUnkeyedLiterals, + Buf: input.Buf, + }, nil + } + unmarshal := func(input protoiface.UnmarshalInput) (protoiface.UnmarshalOutput, error) { + x := input.Message.Interface().(*Customer2) + if x == nil { + return protoiface.UnmarshalOutput{ + NoUnkeyedLiterals: input.NoUnkeyedLiterals, + Flags: input.Flags, + }, nil + } + options := runtime.UnmarshalInputToOptions(input) + _ = options + dAtA := input.Buf + l := len(dAtA) + iNdEx := 0 + for iNdEx < l { + preIndex := iNdEx + var wire uint64 + for shift := uint(0); ; shift += 7 { + if shift >= 64 { + return protoiface.UnmarshalOutput{NoUnkeyedLiterals: input.NoUnkeyedLiterals, Flags: input.Flags}, runtime.ErrIntOverflow + } + if iNdEx >= l { + return protoiface.UnmarshalOutput{NoUnkeyedLiterals: input.NoUnkeyedLiterals, Flags: input.Flags}, io.ErrUnexpectedEOF + } + b := dAtA[iNdEx] + iNdEx++ + wire |= uint64(b&0x7F) << shift + if b < 0x80 { + break + } + } + fieldNum := int32(wire >> 3) + wireType := int(wire & 0x7) + if wireType == 4 { + return protoiface.UnmarshalOutput{NoUnkeyedLiterals: input.NoUnkeyedLiterals, Flags: input.Flags}, fmt.Errorf("proto: Customer2: wiretype end group for non-group") + } + if fieldNum <= 0 { + return protoiface.UnmarshalOutput{NoUnkeyedLiterals: input.NoUnkeyedLiterals, Flags: input.Flags}, fmt.Errorf("proto: Customer2: illegal tag %d (wire type %d)", fieldNum, wire) + } + switch fieldNum { + case 1: + if wireType != 0 { + return protoiface.UnmarshalOutput{NoUnkeyedLiterals: input.NoUnkeyedLiterals, Flags: input.Flags}, fmt.Errorf("proto: wrong wireType = %d for field Id", wireType) + } + x.Id = 0 + for shift := uint(0); ; shift += 7 { + if shift >= 64 { + return protoiface.UnmarshalOutput{NoUnkeyedLiterals: input.NoUnkeyedLiterals, Flags: input.Flags}, runtime.ErrIntOverflow + } + if iNdEx >= l { + return protoiface.UnmarshalOutput{NoUnkeyedLiterals: input.NoUnkeyedLiterals, Flags: input.Flags}, io.ErrUnexpectedEOF + } + b := dAtA[iNdEx] + iNdEx++ + x.Id |= int32(b&0x7F) << shift + if b < 0x80 { + break + } + } + case 2: + if wireType != 0 { + return protoiface.UnmarshalOutput{NoUnkeyedLiterals: input.NoUnkeyedLiterals, Flags: input.Flags}, fmt.Errorf("proto: wrong wireType = %d for field Industry", wireType) + } + x.Industry = 0 + for shift := uint(0); ; shift += 7 { + if shift >= 64 { + return protoiface.UnmarshalOutput{NoUnkeyedLiterals: input.NoUnkeyedLiterals, Flags: input.Flags}, runtime.ErrIntOverflow + } + if iNdEx >= l { + return protoiface.UnmarshalOutput{NoUnkeyedLiterals: input.NoUnkeyedLiterals, Flags: input.Flags}, io.ErrUnexpectedEOF + } + b := dAtA[iNdEx] + iNdEx++ + x.Industry |= int32(b&0x7F) << shift + if b < 0x80 { + break + } + } + case 3: + if wireType != 2 { + return protoiface.UnmarshalOutput{NoUnkeyedLiterals: input.NoUnkeyedLiterals, Flags: input.Flags}, fmt.Errorf("proto: wrong wireType = %d for field Name", wireType) + } + var stringLen uint64 + for shift := uint(0); ; shift += 7 { + if shift >= 64 { + return protoiface.UnmarshalOutput{NoUnkeyedLiterals: input.NoUnkeyedLiterals, Flags: input.Flags}, runtime.ErrIntOverflow + } + if iNdEx >= l { + return protoiface.UnmarshalOutput{NoUnkeyedLiterals: input.NoUnkeyedLiterals, Flags: input.Flags}, io.ErrUnexpectedEOF + } + b := dAtA[iNdEx] + iNdEx++ + stringLen |= uint64(b&0x7F) << shift + if b < 0x80 { + break + } + } + intStringLen := int(stringLen) + if intStringLen < 0 { + return protoiface.UnmarshalOutput{NoUnkeyedLiterals: input.NoUnkeyedLiterals, Flags: input.Flags}, runtime.ErrInvalidLength + } + postIndex := iNdEx + intStringLen + if postIndex < 0 { + return protoiface.UnmarshalOutput{NoUnkeyedLiterals: input.NoUnkeyedLiterals, Flags: input.Flags}, runtime.ErrInvalidLength + } + if postIndex > l { + return protoiface.UnmarshalOutput{NoUnkeyedLiterals: input.NoUnkeyedLiterals, Flags: input.Flags}, io.ErrUnexpectedEOF + } + x.Name = string(dAtA[iNdEx:postIndex]) + iNdEx = postIndex + case 4: + if wireType != 5 { + return protoiface.UnmarshalOutput{NoUnkeyedLiterals: input.NoUnkeyedLiterals, Flags: input.Flags}, fmt.Errorf("proto: wrong wireType = %d for field Fewer", wireType) + } + var v uint32 + if (iNdEx + 4) > l { + return protoiface.UnmarshalOutput{NoUnkeyedLiterals: input.NoUnkeyedLiterals, Flags: input.Flags}, io.ErrUnexpectedEOF + } + v = uint32(binary.LittleEndian.Uint32(dAtA[iNdEx:])) + iNdEx += 4 + x.Fewer = float32(math.Float32frombits(v)) + case 1047: + if wireType != 0 { + return protoiface.UnmarshalOutput{NoUnkeyedLiterals: input.NoUnkeyedLiterals, Flags: input.Flags}, fmt.Errorf("proto: wrong wireType = %d for field Reserved", wireType) + } + x.Reserved = 0 + for shift := uint(0); ; shift += 7 { + if shift >= 64 { + return protoiface.UnmarshalOutput{NoUnkeyedLiterals: input.NoUnkeyedLiterals, Flags: input.Flags}, runtime.ErrIntOverflow + } + if iNdEx >= l { + return protoiface.UnmarshalOutput{NoUnkeyedLiterals: input.NoUnkeyedLiterals, Flags: input.Flags}, io.ErrUnexpectedEOF + } + b := dAtA[iNdEx] + iNdEx++ + x.Reserved |= int64(b&0x7F) << shift + if b < 0x80 { + break + } + } + case 6: + if wireType != 0 { + return protoiface.UnmarshalOutput{NoUnkeyedLiterals: input.NoUnkeyedLiterals, Flags: input.Flags}, fmt.Errorf("proto: wrong wireType = %d for field City", wireType) + } + x.City = 0 + for shift := uint(0); ; shift += 7 { + if shift >= 64 { + return protoiface.UnmarshalOutput{NoUnkeyedLiterals: input.NoUnkeyedLiterals, Flags: input.Flags}, runtime.ErrIntOverflow + } + if iNdEx >= l { + return protoiface.UnmarshalOutput{NoUnkeyedLiterals: input.NoUnkeyedLiterals, Flags: input.Flags}, io.ErrUnexpectedEOF + } + b := dAtA[iNdEx] + iNdEx++ + x.City |= Customer2_City(b&0x7F) << shift + if b < 0x80 { + break + } + } + case 10: + if wireType != 2 { + return protoiface.UnmarshalOutput{NoUnkeyedLiterals: input.NoUnkeyedLiterals, Flags: input.Flags}, fmt.Errorf("proto: wrong wireType = %d for field Miscellaneous", wireType) + } + var msglen int + for shift := uint(0); ; shift += 7 { + if shift >= 64 { + return protoiface.UnmarshalOutput{NoUnkeyedLiterals: input.NoUnkeyedLiterals, Flags: input.Flags}, runtime.ErrIntOverflow + } + if iNdEx >= l { + return protoiface.UnmarshalOutput{NoUnkeyedLiterals: input.NoUnkeyedLiterals, Flags: input.Flags}, io.ErrUnexpectedEOF + } + b := dAtA[iNdEx] + iNdEx++ + msglen |= int(b&0x7F) << shift + if b < 0x80 { + break + } + } + if msglen < 0 { + return protoiface.UnmarshalOutput{NoUnkeyedLiterals: input.NoUnkeyedLiterals, Flags: input.Flags}, runtime.ErrInvalidLength + } + postIndex := iNdEx + msglen + if postIndex < 0 { + return protoiface.UnmarshalOutput{NoUnkeyedLiterals: input.NoUnkeyedLiterals, Flags: input.Flags}, runtime.ErrInvalidLength + } + if postIndex > l { + return protoiface.UnmarshalOutput{NoUnkeyedLiterals: input.NoUnkeyedLiterals, Flags: input.Flags}, io.ErrUnexpectedEOF + } + if x.Miscellaneous == nil { + x.Miscellaneous = &anypb.Any{} + } + if err := options.Unmarshal(dAtA[iNdEx:postIndex], x.Miscellaneous); err != nil { + return protoiface.UnmarshalOutput{NoUnkeyedLiterals: input.NoUnkeyedLiterals, Flags: input.Flags}, err + } + iNdEx = postIndex + default: + iNdEx = preIndex + skippy, err := runtime.Skip(dAtA[iNdEx:]) + if err != nil { + return protoiface.UnmarshalOutput{NoUnkeyedLiterals: input.NoUnkeyedLiterals, Flags: input.Flags}, err + } + if (skippy < 0) || (iNdEx+skippy) < 0 { + return protoiface.UnmarshalOutput{NoUnkeyedLiterals: input.NoUnkeyedLiterals, Flags: input.Flags}, runtime.ErrInvalidLength + } + if (iNdEx + skippy) > l { + return protoiface.UnmarshalOutput{NoUnkeyedLiterals: input.NoUnkeyedLiterals, Flags: input.Flags}, io.ErrUnexpectedEOF + } + if !options.DiscardUnknown { + x.unknownFields = append(x.unknownFields, dAtA[iNdEx:iNdEx+skippy]...) + } + iNdEx += skippy + } + } + + if iNdEx > l { + return protoiface.UnmarshalOutput{NoUnkeyedLiterals: input.NoUnkeyedLiterals, Flags: input.Flags}, io.ErrUnexpectedEOF + } + return protoiface.UnmarshalOutput{NoUnkeyedLiterals: input.NoUnkeyedLiterals, Flags: input.Flags}, nil + } + return &protoiface.Methods{ + NoUnkeyedLiterals: struct{}{}, + Flags: protoiface.SupportMarshalDeterministic | protoiface.SupportUnmarshalDiscardUnknown, + Size: size, + Marshal: marshal, + Unmarshal: unmarshal, + Merge: nil, + CheckInitialized: nil, + } +} + +var ( + md_Nested4A protoreflect.MessageDescriptor + fd_Nested4A_id protoreflect.FieldDescriptor + fd_Nested4A_name protoreflect.FieldDescriptor +) + +func init() { + file_unknownproto_proto_init() + md_Nested4A = File_unknownproto_proto.Messages().ByName("Nested4A") + fd_Nested4A_id = md_Nested4A.Fields().ByName("id") + fd_Nested4A_name = md_Nested4A.Fields().ByName("name") +} + +var _ protoreflect.Message = (*fastReflection_Nested4A)(nil) + +type fastReflection_Nested4A Nested4A + +func (x *Nested4A) ProtoReflect() protoreflect.Message { + return (*fastReflection_Nested4A)(x) +} + +func (x *Nested4A) slowProtoReflect() protoreflect.Message { + mi := &file_unknownproto_proto_msgTypes[2] + if protoimpl.UnsafeEnabled && x != nil { + ms := protoimpl.X.MessageStateOf(protoimpl.Pointer(x)) + if ms.LoadMessageInfo() == nil { + ms.StoreMessageInfo(mi) + } + return ms + } + return mi.MessageOf(x) +} + +var _fastReflection_Nested4A_messageType fastReflection_Nested4A_messageType +var _ protoreflect.MessageType = fastReflection_Nested4A_messageType{} + +type fastReflection_Nested4A_messageType struct{} + +func (x fastReflection_Nested4A_messageType) Zero() protoreflect.Message { + return (*fastReflection_Nested4A)(nil) +} +func (x fastReflection_Nested4A_messageType) New() protoreflect.Message { + return new(fastReflection_Nested4A) +} +func (x fastReflection_Nested4A_messageType) Descriptor() protoreflect.MessageDescriptor { + return md_Nested4A +} + +// Descriptor returns message descriptor, which contains only the protobuf +// type information for the message. +func (x *fastReflection_Nested4A) Descriptor() protoreflect.MessageDescriptor { + return md_Nested4A +} + +// Type returns the message type, which encapsulates both Go and protobuf +// type information. If the Go type information is not needed, +// it is recommended that the message descriptor be used instead. +func (x *fastReflection_Nested4A) Type() protoreflect.MessageType { + return _fastReflection_Nested4A_messageType +} + +// New returns a newly allocated and mutable empty message. +func (x *fastReflection_Nested4A) New() protoreflect.Message { + return new(fastReflection_Nested4A) +} + +// Interface unwraps the message reflection interface and +// returns the underlying ProtoMessage interface. +func (x *fastReflection_Nested4A) Interface() protoreflect.ProtoMessage { + return (*Nested4A)(x) +} + +// Range iterates over every populated field in an undefined order, +// calling f for each field descriptor and value encountered. +// Range returns immediately if f returns false. +// While iterating, mutating operations may only be performed +// on the current field descriptor. +func (x *fastReflection_Nested4A) Range(f func(protoreflect.FieldDescriptor, protoreflect.Value) bool) { + if x.Id != int32(0) { + value := protoreflect.ValueOfInt32(x.Id) + if !f(fd_Nested4A_id, value) { + return + } + } + if x.Name != "" { + value := protoreflect.ValueOfString(x.Name) + if !f(fd_Nested4A_name, value) { + return + } + } +} + +// Has reports whether a field is populated. +// +// Some fields have the property of nullability where it is possible to +// distinguish between the default value of a field and whether the field +// was explicitly populated with the default value. Singular message fields, +// member fields of a oneof, and proto2 scalar fields are nullable. Such +// fields are populated only if explicitly set. +// +// In other cases (aside from the nullable cases above), +// a proto3 scalar field is populated if it contains a non-zero value, and +// a repeated field is populated if it is non-empty. +func (x *fastReflection_Nested4A) Has(fd protoreflect.FieldDescriptor) bool { + switch fd.FullName() { + case "testpb.Nested4A.id": + return x.Id != int32(0) + case "testpb.Nested4A.name": + return x.Name != "" + default: + if fd.IsExtension() { + panic(fmt.Errorf("proto3 declared messages do not support extensions: testpb.Nested4A")) + } + panic(fmt.Errorf("message testpb.Nested4A does not contain field %s", fd.FullName())) + } +} + +// Clear clears the field such that a subsequent Has call reports false. +// +// Clearing an extension field clears both the extension type and value +// associated with the given field number. +// +// Clear is a mutating operation and unsafe for concurrent use. +func (x *fastReflection_Nested4A) Clear(fd protoreflect.FieldDescriptor) { + switch fd.FullName() { + case "testpb.Nested4A.id": + x.Id = int32(0) + case "testpb.Nested4A.name": + x.Name = "" + default: + if fd.IsExtension() { + panic(fmt.Errorf("proto3 declared messages do not support extensions: testpb.Nested4A")) + } + panic(fmt.Errorf("message testpb.Nested4A does not contain field %s", fd.FullName())) + } +} + +// Get retrieves the value for a field. +// +// For unpopulated scalars, it returns the default value, where +// the default value of a bytes scalar is guaranteed to be a copy. +// For unpopulated composite types, it returns an empty, read-only view +// of the value; to obtain a mutable reference, use Mutable. +func (x *fastReflection_Nested4A) Get(descriptor protoreflect.FieldDescriptor) protoreflect.Value { + switch descriptor.FullName() { + case "testpb.Nested4A.id": + value := x.Id + return protoreflect.ValueOfInt32(value) + case "testpb.Nested4A.name": + value := x.Name + return protoreflect.ValueOfString(value) + default: + if descriptor.IsExtension() { + panic(fmt.Errorf("proto3 declared messages do not support extensions: testpb.Nested4A")) + } + panic(fmt.Errorf("message testpb.Nested4A does not contain field %s", descriptor.FullName())) + } +} + +// Set stores the value for a field. +// +// For a field belonging to a oneof, it implicitly clears any other field +// that may be currently set within the same oneof. +// For extension fields, it implicitly stores the provided ExtensionType. +// When setting a composite type, it is unspecified whether the stored value +// aliases the source's memory in any way. If the composite value is an +// empty, read-only value, then it panics. +// +// Set is a mutating operation and unsafe for concurrent use. +func (x *fastReflection_Nested4A) Set(fd protoreflect.FieldDescriptor, value protoreflect.Value) { + switch fd.FullName() { + case "testpb.Nested4A.id": + x.Id = int32(value.Int()) + case "testpb.Nested4A.name": + x.Name = value.Interface().(string) + default: + if fd.IsExtension() { + panic(fmt.Errorf("proto3 declared messages do not support extensions: testpb.Nested4A")) + } + panic(fmt.Errorf("message testpb.Nested4A does not contain field %s", fd.FullName())) + } +} + +// Mutable returns a mutable reference to a composite type. +// +// If the field is unpopulated, it may allocate a composite value. +// For a field belonging to a oneof, it implicitly clears any other field +// that may be currently set within the same oneof. +// For extension fields, it implicitly stores the provided ExtensionType +// if not already stored. +// It panics if the field does not contain a composite type. +// +// Mutable is a mutating operation and unsafe for concurrent use. +func (x *fastReflection_Nested4A) Mutable(fd protoreflect.FieldDescriptor) protoreflect.Value { + switch fd.FullName() { + case "testpb.Nested4A.id": + panic(fmt.Errorf("field id of message testpb.Nested4A is not mutable")) + case "testpb.Nested4A.name": + panic(fmt.Errorf("field name of message testpb.Nested4A is not mutable")) + default: + if fd.IsExtension() { + panic(fmt.Errorf("proto3 declared messages do not support extensions: testpb.Nested4A")) + } + panic(fmt.Errorf("message testpb.Nested4A does not contain field %s", fd.FullName())) + } +} + +// NewField returns a new value that is assignable to the field +// for the given descriptor. For scalars, this returns the default value. +// For lists, maps, and messages, this returns a new, empty, mutable value. +func (x *fastReflection_Nested4A) NewField(fd protoreflect.FieldDescriptor) protoreflect.Value { + switch fd.FullName() { + case "testpb.Nested4A.id": + return protoreflect.ValueOfInt32(int32(0)) + case "testpb.Nested4A.name": + return protoreflect.ValueOfString("") + default: + if fd.IsExtension() { + panic(fmt.Errorf("proto3 declared messages do not support extensions: testpb.Nested4A")) + } + panic(fmt.Errorf("message testpb.Nested4A does not contain field %s", fd.FullName())) + } +} + +// WhichOneof reports which field within the oneof is populated, +// returning nil if none are populated. +// It panics if the oneof descriptor does not belong to this message. +func (x *fastReflection_Nested4A) WhichOneof(d protoreflect.OneofDescriptor) protoreflect.FieldDescriptor { + switch d.FullName() { + default: + panic(fmt.Errorf("%s is not a oneof field in testpb.Nested4A", d.FullName())) + } + panic("unreachable") +} + +// GetUnknown retrieves the entire list of unknown fields. +// The caller may only mutate the contents of the RawFields +// if the mutated bytes are stored back into the message with SetUnknown. +func (x *fastReflection_Nested4A) GetUnknown() protoreflect.RawFields { + return x.unknownFields +} + +// SetUnknown stores an entire list of unknown fields. +// The raw fields must be syntactically valid according to the wire format. +// An implementation may panic if this is not the case. +// Once stored, the caller must not mutate the content of the RawFields. +// An empty RawFields may be passed to clear the fields. +// +// SetUnknown is a mutating operation and unsafe for concurrent use. +func (x *fastReflection_Nested4A) SetUnknown(fields protoreflect.RawFields) { + x.unknownFields = fields +} + +// IsValid reports whether the message is valid. +// +// An invalid message is an empty, read-only value. +// +// An invalid message often corresponds to a nil pointer of the concrete +// message type, but the details are implementation dependent. +// Validity is not part of the protobuf data model, and may not +// be preserved in marshaling or other operations. +func (x *fastReflection_Nested4A) IsValid() bool { + return x != nil +} + +// ProtoMethods returns optional fastReflectionFeature-path implementations of various operations. +// This method may return nil. +// +// The returned methods type is identical to +// "google.golang.org/protobuf/runtime/protoiface".Methods. +// Consult the protoiface package documentation for details. +func (x *fastReflection_Nested4A) ProtoMethods() *protoiface.Methods { + size := func(input protoiface.SizeInput) protoiface.SizeOutput { + x := input.Message.Interface().(*Nested4A) + if x == nil { + return protoiface.SizeOutput{ + NoUnkeyedLiterals: input.NoUnkeyedLiterals, + Size: 0, + } + } + options := runtime.SizeInputToOptions(input) + _ = options + var n int + var l int + _ = l + if x.Id != 0 { + n += 1 + runtime.Sov(uint64(x.Id)) + } + l = len(x.Name) + if l > 0 { + n += 1 + l + runtime.Sov(uint64(l)) + } + if x.unknownFields != nil { + n += len(x.unknownFields) + } + return protoiface.SizeOutput{ + NoUnkeyedLiterals: input.NoUnkeyedLiterals, + Size: n, + } + } + + marshal := func(input protoiface.MarshalInput) (protoiface.MarshalOutput, error) { + x := input.Message.Interface().(*Nested4A) + if x == nil { + return protoiface.MarshalOutput{ + NoUnkeyedLiterals: input.NoUnkeyedLiterals, + Buf: input.Buf, + }, nil + } + options := runtime.MarshalInputToOptions(input) + _ = options + size := options.Size(x) + dAtA := make([]byte, size) + i := len(dAtA) + _ = i + var l int + _ = l + if x.unknownFields != nil { + i -= len(x.unknownFields) + copy(dAtA[i:], x.unknownFields) + } + if len(x.Name) > 0 { + i -= len(x.Name) + copy(dAtA[i:], x.Name) + i = runtime.EncodeVarint(dAtA, i, uint64(len(x.Name))) + i-- + dAtA[i] = 0x12 + } + if x.Id != 0 { + i = runtime.EncodeVarint(dAtA, i, uint64(x.Id)) + i-- + dAtA[i] = 0x8 + } + if input.Buf != nil { + input.Buf = append(input.Buf, dAtA...) + } else { + input.Buf = dAtA + } + return protoiface.MarshalOutput{ + NoUnkeyedLiterals: input.NoUnkeyedLiterals, + Buf: input.Buf, + }, nil + } + unmarshal := func(input protoiface.UnmarshalInput) (protoiface.UnmarshalOutput, error) { + x := input.Message.Interface().(*Nested4A) + if x == nil { + return protoiface.UnmarshalOutput{ + NoUnkeyedLiterals: input.NoUnkeyedLiterals, + Flags: input.Flags, + }, nil + } + options := runtime.UnmarshalInputToOptions(input) + _ = options + dAtA := input.Buf + l := len(dAtA) + iNdEx := 0 + for iNdEx < l { + preIndex := iNdEx + var wire uint64 + for shift := uint(0); ; shift += 7 { + if shift >= 64 { + return protoiface.UnmarshalOutput{NoUnkeyedLiterals: input.NoUnkeyedLiterals, Flags: input.Flags}, runtime.ErrIntOverflow + } + if iNdEx >= l { + return protoiface.UnmarshalOutput{NoUnkeyedLiterals: input.NoUnkeyedLiterals, Flags: input.Flags}, io.ErrUnexpectedEOF + } + b := dAtA[iNdEx] + iNdEx++ + wire |= uint64(b&0x7F) << shift + if b < 0x80 { + break + } + } + fieldNum := int32(wire >> 3) + wireType := int(wire & 0x7) + if wireType == 4 { + return protoiface.UnmarshalOutput{NoUnkeyedLiterals: input.NoUnkeyedLiterals, Flags: input.Flags}, fmt.Errorf("proto: Nested4A: wiretype end group for non-group") + } + if fieldNum <= 0 { + return protoiface.UnmarshalOutput{NoUnkeyedLiterals: input.NoUnkeyedLiterals, Flags: input.Flags}, fmt.Errorf("proto: Nested4A: illegal tag %d (wire type %d)", fieldNum, wire) + } + switch fieldNum { + case 1: + if wireType != 0 { + return protoiface.UnmarshalOutput{NoUnkeyedLiterals: input.NoUnkeyedLiterals, Flags: input.Flags}, fmt.Errorf("proto: wrong wireType = %d for field Id", wireType) + } + x.Id = 0 + for shift := uint(0); ; shift += 7 { + if shift >= 64 { + return protoiface.UnmarshalOutput{NoUnkeyedLiterals: input.NoUnkeyedLiterals, Flags: input.Flags}, runtime.ErrIntOverflow + } + if iNdEx >= l { + return protoiface.UnmarshalOutput{NoUnkeyedLiterals: input.NoUnkeyedLiterals, Flags: input.Flags}, io.ErrUnexpectedEOF + } + b := dAtA[iNdEx] + iNdEx++ + x.Id |= int32(b&0x7F) << shift + if b < 0x80 { + break + } + } + case 2: + if wireType != 2 { + return protoiface.UnmarshalOutput{NoUnkeyedLiterals: input.NoUnkeyedLiterals, Flags: input.Flags}, fmt.Errorf("proto: wrong wireType = %d for field Name", wireType) + } + var stringLen uint64 + for shift := uint(0); ; shift += 7 { + if shift >= 64 { + return protoiface.UnmarshalOutput{NoUnkeyedLiterals: input.NoUnkeyedLiterals, Flags: input.Flags}, runtime.ErrIntOverflow + } + if iNdEx >= l { + return protoiface.UnmarshalOutput{NoUnkeyedLiterals: input.NoUnkeyedLiterals, Flags: input.Flags}, io.ErrUnexpectedEOF + } + b := dAtA[iNdEx] + iNdEx++ + stringLen |= uint64(b&0x7F) << shift + if b < 0x80 { + break + } + } + intStringLen := int(stringLen) + if intStringLen < 0 { + return protoiface.UnmarshalOutput{NoUnkeyedLiterals: input.NoUnkeyedLiterals, Flags: input.Flags}, runtime.ErrInvalidLength + } + postIndex := iNdEx + intStringLen + if postIndex < 0 { + return protoiface.UnmarshalOutput{NoUnkeyedLiterals: input.NoUnkeyedLiterals, Flags: input.Flags}, runtime.ErrInvalidLength + } + if postIndex > l { + return protoiface.UnmarshalOutput{NoUnkeyedLiterals: input.NoUnkeyedLiterals, Flags: input.Flags}, io.ErrUnexpectedEOF + } + x.Name = string(dAtA[iNdEx:postIndex]) + iNdEx = postIndex + default: + iNdEx = preIndex + skippy, err := runtime.Skip(dAtA[iNdEx:]) + if err != nil { + return protoiface.UnmarshalOutput{NoUnkeyedLiterals: input.NoUnkeyedLiterals, Flags: input.Flags}, err + } + if (skippy < 0) || (iNdEx+skippy) < 0 { + return protoiface.UnmarshalOutput{NoUnkeyedLiterals: input.NoUnkeyedLiterals, Flags: input.Flags}, runtime.ErrInvalidLength + } + if (iNdEx + skippy) > l { + return protoiface.UnmarshalOutput{NoUnkeyedLiterals: input.NoUnkeyedLiterals, Flags: input.Flags}, io.ErrUnexpectedEOF + } + if !options.DiscardUnknown { + x.unknownFields = append(x.unknownFields, dAtA[iNdEx:iNdEx+skippy]...) + } + iNdEx += skippy + } + } + + if iNdEx > l { + return protoiface.UnmarshalOutput{NoUnkeyedLiterals: input.NoUnkeyedLiterals, Flags: input.Flags}, io.ErrUnexpectedEOF + } + return protoiface.UnmarshalOutput{NoUnkeyedLiterals: input.NoUnkeyedLiterals, Flags: input.Flags}, nil + } + return &protoiface.Methods{ + NoUnkeyedLiterals: struct{}{}, + Flags: protoiface.SupportMarshalDeterministic | protoiface.SupportUnmarshalDiscardUnknown, + Size: size, + Marshal: marshal, + Unmarshal: unmarshal, + Merge: nil, + CheckInitialized: nil, + } +} + +var _ protoreflect.List = (*_Nested3A_4_list)(nil) + +type _Nested3A_4_list struct { + list *[]*Nested4A +} + +func (x *_Nested3A_4_list) Len() int { + if x.list == nil { + return 0 + } + return len(*x.list) +} + +func (x *_Nested3A_4_list) Get(i int) protoreflect.Value { + return protoreflect.ValueOfMessage((*x.list)[i].ProtoReflect()) +} + +func (x *_Nested3A_4_list) Set(i int, value protoreflect.Value) { + valueUnwrapped := value.Message() + concreteValue := valueUnwrapped.Interface().(*Nested4A) + (*x.list)[i] = concreteValue +} + +func (x *_Nested3A_4_list) Append(value protoreflect.Value) { + valueUnwrapped := value.Message() + concreteValue := valueUnwrapped.Interface().(*Nested4A) + *x.list = append(*x.list, concreteValue) +} + +func (x *_Nested3A_4_list) AppendMutable() protoreflect.Value { + v := new(Nested4A) + *x.list = append(*x.list, v) + return protoreflect.ValueOfMessage(v.ProtoReflect()) +} + +func (x *_Nested3A_4_list) Truncate(n int) { + for i := n; i < len(*x.list); i++ { + (*x.list)[i] = nil + } + *x.list = (*x.list)[:n] +} + +func (x *_Nested3A_4_list) NewElement() protoreflect.Value { + v := new(Nested4A) + return protoreflect.ValueOfMessage(v.ProtoReflect()) +} + +func (x *_Nested3A_4_list) IsValid() bool { + return x.list != nil +} + +var _ protoreflect.Map = (*_Nested3A_5_map)(nil) + +type _Nested3A_5_map struct { + m *map[int64]*Nested4A +} + +func (x *_Nested3A_5_map) Len() int { + if x.m == nil { + return 0 + } + return len(*x.m) +} + +func (x *_Nested3A_5_map) Range(f func(protoreflect.MapKey, protoreflect.Value) bool) { + if x.m == nil { + return + } + for k, v := range *x.m { + mapKey := (protoreflect.MapKey)(protoreflect.ValueOfInt64(k)) + mapValue := protoreflect.ValueOfMessage(v.ProtoReflect()) + if !f(mapKey, mapValue) { + break + } + } +} + +func (x *_Nested3A_5_map) Has(key protoreflect.MapKey) bool { + if x.m == nil { + return false + } + keyUnwrapped := key.Int() + concreteValue := keyUnwrapped + _, ok := (*x.m)[concreteValue] + return ok +} + +func (x *_Nested3A_5_map) Clear(key protoreflect.MapKey) { + if x.m == nil { + return + } + keyUnwrapped := key.Int() + concreteKey := keyUnwrapped + delete(*x.m, concreteKey) +} + +func (x *_Nested3A_5_map) Get(key protoreflect.MapKey) protoreflect.Value { + if x.m == nil { + return protoreflect.Value{} + } + keyUnwrapped := key.Int() + concreteKey := keyUnwrapped + v, ok := (*x.m)[concreteKey] + if !ok { + return protoreflect.Value{} + } + return protoreflect.ValueOfMessage(v.ProtoReflect()) +} + +func (x *_Nested3A_5_map) Set(key protoreflect.MapKey, value protoreflect.Value) { + if !key.IsValid() || !value.IsValid() { + panic("invalid key or value provided") + } + keyUnwrapped := key.Int() + concreteKey := keyUnwrapped + valueUnwrapped := value.Message() + concreteValue := valueUnwrapped.Interface().(*Nested4A) + (*x.m)[concreteKey] = concreteValue +} + +func (x *_Nested3A_5_map) Mutable(key protoreflect.MapKey) protoreflect.Value { + keyUnwrapped := key.Int() + concreteKey := keyUnwrapped + v, ok := (*x.m)[concreteKey] + if ok { + return protoreflect.ValueOfMessage(v.ProtoReflect()) + } + newValue := new(Nested4A) + (*x.m)[concreteKey] = newValue + return protoreflect.ValueOfMessage(newValue.ProtoReflect()) +} + +func (x *_Nested3A_5_map) NewValue() protoreflect.Value { + v := new(Nested4A) + return protoreflect.ValueOfMessage(v.ProtoReflect()) +} + +func (x *_Nested3A_5_map) IsValid() bool { + return x.m != nil +} + +var ( + md_Nested3A protoreflect.MessageDescriptor + fd_Nested3A_id protoreflect.FieldDescriptor + fd_Nested3A_name protoreflect.FieldDescriptor + fd_Nested3A_a4 protoreflect.FieldDescriptor + fd_Nested3A_index protoreflect.FieldDescriptor +) + +func init() { + file_unknownproto_proto_init() + md_Nested3A = File_unknownproto_proto.Messages().ByName("Nested3A") + fd_Nested3A_id = md_Nested3A.Fields().ByName("id") + fd_Nested3A_name = md_Nested3A.Fields().ByName("name") + fd_Nested3A_a4 = md_Nested3A.Fields().ByName("a4") + fd_Nested3A_index = md_Nested3A.Fields().ByName("index") +} + +var _ protoreflect.Message = (*fastReflection_Nested3A)(nil) + +type fastReflection_Nested3A Nested3A + +func (x *Nested3A) ProtoReflect() protoreflect.Message { + return (*fastReflection_Nested3A)(x) +} + +func (x *Nested3A) slowProtoReflect() protoreflect.Message { + mi := &file_unknownproto_proto_msgTypes[3] + if protoimpl.UnsafeEnabled && x != nil { + ms := protoimpl.X.MessageStateOf(protoimpl.Pointer(x)) + if ms.LoadMessageInfo() == nil { + ms.StoreMessageInfo(mi) + } + return ms + } + return mi.MessageOf(x) +} + +var _fastReflection_Nested3A_messageType fastReflection_Nested3A_messageType +var _ protoreflect.MessageType = fastReflection_Nested3A_messageType{} + +type fastReflection_Nested3A_messageType struct{} + +func (x fastReflection_Nested3A_messageType) Zero() protoreflect.Message { + return (*fastReflection_Nested3A)(nil) +} +func (x fastReflection_Nested3A_messageType) New() protoreflect.Message { + return new(fastReflection_Nested3A) +} +func (x fastReflection_Nested3A_messageType) Descriptor() protoreflect.MessageDescriptor { + return md_Nested3A +} + +// Descriptor returns message descriptor, which contains only the protobuf +// type information for the message. +func (x *fastReflection_Nested3A) Descriptor() protoreflect.MessageDescriptor { + return md_Nested3A +} + +// Type returns the message type, which encapsulates both Go and protobuf +// type information. If the Go type information is not needed, +// it is recommended that the message descriptor be used instead. +func (x *fastReflection_Nested3A) Type() protoreflect.MessageType { + return _fastReflection_Nested3A_messageType +} + +// New returns a newly allocated and mutable empty message. +func (x *fastReflection_Nested3A) New() protoreflect.Message { + return new(fastReflection_Nested3A) +} + +// Interface unwraps the message reflection interface and +// returns the underlying ProtoMessage interface. +func (x *fastReflection_Nested3A) Interface() protoreflect.ProtoMessage { + return (*Nested3A)(x) +} + +// Range iterates over every populated field in an undefined order, +// calling f for each field descriptor and value encountered. +// Range returns immediately if f returns false. +// While iterating, mutating operations may only be performed +// on the current field descriptor. +func (x *fastReflection_Nested3A) Range(f func(protoreflect.FieldDescriptor, protoreflect.Value) bool) { + if x.Id != int32(0) { + value := protoreflect.ValueOfInt32(x.Id) + if !f(fd_Nested3A_id, value) { + return + } + } + if x.Name != "" { + value := protoreflect.ValueOfString(x.Name) + if !f(fd_Nested3A_name, value) { + return + } + } + if len(x.A4) != 0 { + value := protoreflect.ValueOfList(&_Nested3A_4_list{list: &x.A4}) + if !f(fd_Nested3A_a4, value) { + return + } + } + if len(x.Index) != 0 { + value := protoreflect.ValueOfMap(&_Nested3A_5_map{m: &x.Index}) + if !f(fd_Nested3A_index, value) { + return + } + } +} + +// Has reports whether a field is populated. +// +// Some fields have the property of nullability where it is possible to +// distinguish between the default value of a field and whether the field +// was explicitly populated with the default value. Singular message fields, +// member fields of a oneof, and proto2 scalar fields are nullable. Such +// fields are populated only if explicitly set. +// +// In other cases (aside from the nullable cases above), +// a proto3 scalar field is populated if it contains a non-zero value, and +// a repeated field is populated if it is non-empty. +func (x *fastReflection_Nested3A) Has(fd protoreflect.FieldDescriptor) bool { + switch fd.FullName() { + case "testpb.Nested3A.id": + return x.Id != int32(0) + case "testpb.Nested3A.name": + return x.Name != "" + case "testpb.Nested3A.a4": + return len(x.A4) != 0 + case "testpb.Nested3A.index": + return len(x.Index) != 0 + default: + if fd.IsExtension() { + panic(fmt.Errorf("proto3 declared messages do not support extensions: testpb.Nested3A")) + } + panic(fmt.Errorf("message testpb.Nested3A does not contain field %s", fd.FullName())) + } +} + +// Clear clears the field such that a subsequent Has call reports false. +// +// Clearing an extension field clears both the extension type and value +// associated with the given field number. +// +// Clear is a mutating operation and unsafe for concurrent use. +func (x *fastReflection_Nested3A) Clear(fd protoreflect.FieldDescriptor) { + switch fd.FullName() { + case "testpb.Nested3A.id": + x.Id = int32(0) + case "testpb.Nested3A.name": + x.Name = "" + case "testpb.Nested3A.a4": + x.A4 = nil + case "testpb.Nested3A.index": + x.Index = nil + default: + if fd.IsExtension() { + panic(fmt.Errorf("proto3 declared messages do not support extensions: testpb.Nested3A")) + } + panic(fmt.Errorf("message testpb.Nested3A does not contain field %s", fd.FullName())) + } +} + +// Get retrieves the value for a field. +// +// For unpopulated scalars, it returns the default value, where +// the default value of a bytes scalar is guaranteed to be a copy. +// For unpopulated composite types, it returns an empty, read-only view +// of the value; to obtain a mutable reference, use Mutable. +func (x *fastReflection_Nested3A) Get(descriptor protoreflect.FieldDescriptor) protoreflect.Value { + switch descriptor.FullName() { + case "testpb.Nested3A.id": + value := x.Id + return protoreflect.ValueOfInt32(value) + case "testpb.Nested3A.name": + value := x.Name + return protoreflect.ValueOfString(value) + case "testpb.Nested3A.a4": + if len(x.A4) == 0 { + return protoreflect.ValueOfList(&_Nested3A_4_list{}) + } + listValue := &_Nested3A_4_list{list: &x.A4} + return protoreflect.ValueOfList(listValue) + case "testpb.Nested3A.index": + if len(x.Index) == 0 { + return protoreflect.ValueOfMap(&_Nested3A_5_map{}) + } + mapValue := &_Nested3A_5_map{m: &x.Index} + return protoreflect.ValueOfMap(mapValue) + default: + if descriptor.IsExtension() { + panic(fmt.Errorf("proto3 declared messages do not support extensions: testpb.Nested3A")) + } + panic(fmt.Errorf("message testpb.Nested3A does not contain field %s", descriptor.FullName())) + } +} + +// Set stores the value for a field. +// +// For a field belonging to a oneof, it implicitly clears any other field +// that may be currently set within the same oneof. +// For extension fields, it implicitly stores the provided ExtensionType. +// When setting a composite type, it is unspecified whether the stored value +// aliases the source's memory in any way. If the composite value is an +// empty, read-only value, then it panics. +// +// Set is a mutating operation and unsafe for concurrent use. +func (x *fastReflection_Nested3A) Set(fd protoreflect.FieldDescriptor, value protoreflect.Value) { + switch fd.FullName() { + case "testpb.Nested3A.id": + x.Id = int32(value.Int()) + case "testpb.Nested3A.name": + x.Name = value.Interface().(string) + case "testpb.Nested3A.a4": + lv := value.List() + clv := lv.(*_Nested3A_4_list) + x.A4 = *clv.list + case "testpb.Nested3A.index": + mv := value.Map() + cmv := mv.(*_Nested3A_5_map) + x.Index = *cmv.m + default: + if fd.IsExtension() { + panic(fmt.Errorf("proto3 declared messages do not support extensions: testpb.Nested3A")) + } + panic(fmt.Errorf("message testpb.Nested3A does not contain field %s", fd.FullName())) + } +} + +// Mutable returns a mutable reference to a composite type. +// +// If the field is unpopulated, it may allocate a composite value. +// For a field belonging to a oneof, it implicitly clears any other field +// that may be currently set within the same oneof. +// For extension fields, it implicitly stores the provided ExtensionType +// if not already stored. +// It panics if the field does not contain a composite type. +// +// Mutable is a mutating operation and unsafe for concurrent use. +func (x *fastReflection_Nested3A) Mutable(fd protoreflect.FieldDescriptor) protoreflect.Value { + switch fd.FullName() { + case "testpb.Nested3A.a4": + if x.A4 == nil { + x.A4 = []*Nested4A{} + } + value := &_Nested3A_4_list{list: &x.A4} + return protoreflect.ValueOfList(value) + case "testpb.Nested3A.index": + if x.Index == nil { + x.Index = make(map[int64]*Nested4A) + } + value := &_Nested3A_5_map{m: &x.Index} + return protoreflect.ValueOfMap(value) + case "testpb.Nested3A.id": + panic(fmt.Errorf("field id of message testpb.Nested3A is not mutable")) + case "testpb.Nested3A.name": + panic(fmt.Errorf("field name of message testpb.Nested3A is not mutable")) + default: + if fd.IsExtension() { + panic(fmt.Errorf("proto3 declared messages do not support extensions: testpb.Nested3A")) + } + panic(fmt.Errorf("message testpb.Nested3A does not contain field %s", fd.FullName())) + } +} + +// NewField returns a new value that is assignable to the field +// for the given descriptor. For scalars, this returns the default value. +// For lists, maps, and messages, this returns a new, empty, mutable value. +func (x *fastReflection_Nested3A) NewField(fd protoreflect.FieldDescriptor) protoreflect.Value { + switch fd.FullName() { + case "testpb.Nested3A.id": + return protoreflect.ValueOfInt32(int32(0)) + case "testpb.Nested3A.name": + return protoreflect.ValueOfString("") + case "testpb.Nested3A.a4": + list := []*Nested4A{} + return protoreflect.ValueOfList(&_Nested3A_4_list{list: &list}) + case "testpb.Nested3A.index": + m := make(map[int64]*Nested4A) + return protoreflect.ValueOfMap(&_Nested3A_5_map{m: &m}) + default: + if fd.IsExtension() { + panic(fmt.Errorf("proto3 declared messages do not support extensions: testpb.Nested3A")) + } + panic(fmt.Errorf("message testpb.Nested3A does not contain field %s", fd.FullName())) + } +} + +// WhichOneof reports which field within the oneof is populated, +// returning nil if none are populated. +// It panics if the oneof descriptor does not belong to this message. +func (x *fastReflection_Nested3A) WhichOneof(d protoreflect.OneofDescriptor) protoreflect.FieldDescriptor { + switch d.FullName() { + default: + panic(fmt.Errorf("%s is not a oneof field in testpb.Nested3A", d.FullName())) + } + panic("unreachable") +} + +// GetUnknown retrieves the entire list of unknown fields. +// The caller may only mutate the contents of the RawFields +// if the mutated bytes are stored back into the message with SetUnknown. +func (x *fastReflection_Nested3A) GetUnknown() protoreflect.RawFields { + return x.unknownFields +} + +// SetUnknown stores an entire list of unknown fields. +// The raw fields must be syntactically valid according to the wire format. +// An implementation may panic if this is not the case. +// Once stored, the caller must not mutate the content of the RawFields. +// An empty RawFields may be passed to clear the fields. +// +// SetUnknown is a mutating operation and unsafe for concurrent use. +func (x *fastReflection_Nested3A) SetUnknown(fields protoreflect.RawFields) { + x.unknownFields = fields +} + +// IsValid reports whether the message is valid. +// +// An invalid message is an empty, read-only value. +// +// An invalid message often corresponds to a nil pointer of the concrete +// message type, but the details are implementation dependent. +// Validity is not part of the protobuf data model, and may not +// be preserved in marshaling or other operations. +func (x *fastReflection_Nested3A) IsValid() bool { + return x != nil +} + +// ProtoMethods returns optional fastReflectionFeature-path implementations of various operations. +// This method may return nil. +// +// The returned methods type is identical to +// "google.golang.org/protobuf/runtime/protoiface".Methods. +// Consult the protoiface package documentation for details. +func (x *fastReflection_Nested3A) ProtoMethods() *protoiface.Methods { + size := func(input protoiface.SizeInput) protoiface.SizeOutput { + x := input.Message.Interface().(*Nested3A) + if x == nil { + return protoiface.SizeOutput{ + NoUnkeyedLiterals: input.NoUnkeyedLiterals, + Size: 0, + } + } + options := runtime.SizeInputToOptions(input) + _ = options + var n int + var l int + _ = l + if x.Id != 0 { + n += 1 + runtime.Sov(uint64(x.Id)) + } + l = len(x.Name) + if l > 0 { + n += 1 + l + runtime.Sov(uint64(l)) + } + if len(x.A4) > 0 { + for _, e := range x.A4 { + l = options.Size(e) + n += 1 + l + runtime.Sov(uint64(l)) + } + } + if len(x.Index) > 0 { + SiZeMaP := func(k int64, v *Nested4A) { + l := 0 + if v != nil { + l = options.Size(v) + } + l += 1 + runtime.Sov(uint64(l)) + mapEntrySize := 1 + runtime.Sov(uint64(k)) + l + n += mapEntrySize + 1 + runtime.Sov(uint64(mapEntrySize)) + } + if options.Deterministic { + sortme := make([]int64, 0, len(x.Index)) + for k := range x.Index { + sortme = append(sortme, k) + } + sort.Slice(sortme, func(i, j int) bool { + return sortme[i] < sortme[j] + }) + for _, k := range sortme { + v := x.Index[k] + SiZeMaP(k, v) + } + } else { + for k, v := range x.Index { + SiZeMaP(k, v) + } + } + } + if x.unknownFields != nil { + n += len(x.unknownFields) + } + return protoiface.SizeOutput{ + NoUnkeyedLiterals: input.NoUnkeyedLiterals, + Size: n, + } + } + + marshal := func(input protoiface.MarshalInput) (protoiface.MarshalOutput, error) { + x := input.Message.Interface().(*Nested3A) + if x == nil { + return protoiface.MarshalOutput{ + NoUnkeyedLiterals: input.NoUnkeyedLiterals, + Buf: input.Buf, + }, nil + } + options := runtime.MarshalInputToOptions(input) + _ = options + size := options.Size(x) + dAtA := make([]byte, size) + i := len(dAtA) + _ = i + var l int + _ = l + if x.unknownFields != nil { + i -= len(x.unknownFields) + copy(dAtA[i:], x.unknownFields) + } + if len(x.Index) > 0 { + MaRsHaLmAp := func(k int64, v *Nested4A) (protoiface.MarshalOutput, error) { + baseI := i + encoded, err := options.Marshal(v) + if err != nil { + return protoiface.MarshalOutput{ + NoUnkeyedLiterals: input.NoUnkeyedLiterals, + Buf: input.Buf, + }, err + } + i -= len(encoded) + copy(dAtA[i:], encoded) + i = runtime.EncodeVarint(dAtA, i, uint64(len(encoded))) + i-- + dAtA[i] = 0x12 + i = runtime.EncodeVarint(dAtA, i, uint64(k)) + i-- + dAtA[i] = 0x8 + i = runtime.EncodeVarint(dAtA, i, uint64(baseI-i)) + i-- + dAtA[i] = 0x2a + return protoiface.MarshalOutput{}, nil + } + if options.Deterministic { + keysForIndex := make([]int64, 0, len(x.Index)) + for k := range x.Index { + keysForIndex = append(keysForIndex, int64(k)) + } + sort.Slice(keysForIndex, func(i, j int) bool { + return keysForIndex[i] < keysForIndex[j] + }) + for iNdEx := len(keysForIndex) - 1; iNdEx >= 0; iNdEx-- { + v := x.Index[int64(keysForIndex[iNdEx])] + out, err := MaRsHaLmAp(keysForIndex[iNdEx], v) + if err != nil { + return out, err + } + } + } else { + for k := range x.Index { + v := x.Index[k] + out, err := MaRsHaLmAp(k, v) + if err != nil { + return out, err + } + } + } + } + if len(x.A4) > 0 { + for iNdEx := len(x.A4) - 1; iNdEx >= 0; iNdEx-- { + encoded, err := options.Marshal(x.A4[iNdEx]) + if err != nil { + return protoiface.MarshalOutput{ + NoUnkeyedLiterals: input.NoUnkeyedLiterals, + Buf: input.Buf, + }, err + } + i -= len(encoded) + copy(dAtA[i:], encoded) + i = runtime.EncodeVarint(dAtA, i, uint64(len(encoded))) + i-- + dAtA[i] = 0x22 + } + } + if len(x.Name) > 0 { + i -= len(x.Name) + copy(dAtA[i:], x.Name) + i = runtime.EncodeVarint(dAtA, i, uint64(len(x.Name))) + i-- + dAtA[i] = 0x12 + } + if x.Id != 0 { + i = runtime.EncodeVarint(dAtA, i, uint64(x.Id)) + i-- + dAtA[i] = 0x8 + } + if input.Buf != nil { + input.Buf = append(input.Buf, dAtA...) + } else { + input.Buf = dAtA + } + return protoiface.MarshalOutput{ + NoUnkeyedLiterals: input.NoUnkeyedLiterals, + Buf: input.Buf, + }, nil + } + unmarshal := func(input protoiface.UnmarshalInput) (protoiface.UnmarshalOutput, error) { + x := input.Message.Interface().(*Nested3A) + if x == nil { + return protoiface.UnmarshalOutput{ + NoUnkeyedLiterals: input.NoUnkeyedLiterals, + Flags: input.Flags, + }, nil + } + options := runtime.UnmarshalInputToOptions(input) + _ = options + dAtA := input.Buf + l := len(dAtA) + iNdEx := 0 + for iNdEx < l { + preIndex := iNdEx + var wire uint64 + for shift := uint(0); ; shift += 7 { + if shift >= 64 { + return protoiface.UnmarshalOutput{NoUnkeyedLiterals: input.NoUnkeyedLiterals, Flags: input.Flags}, runtime.ErrIntOverflow + } + if iNdEx >= l { + return protoiface.UnmarshalOutput{NoUnkeyedLiterals: input.NoUnkeyedLiterals, Flags: input.Flags}, io.ErrUnexpectedEOF + } + b := dAtA[iNdEx] + iNdEx++ + wire |= uint64(b&0x7F) << shift + if b < 0x80 { + break + } + } + fieldNum := int32(wire >> 3) + wireType := int(wire & 0x7) + if wireType == 4 { + return protoiface.UnmarshalOutput{NoUnkeyedLiterals: input.NoUnkeyedLiterals, Flags: input.Flags}, fmt.Errorf("proto: Nested3A: wiretype end group for non-group") + } + if fieldNum <= 0 { + return protoiface.UnmarshalOutput{NoUnkeyedLiterals: input.NoUnkeyedLiterals, Flags: input.Flags}, fmt.Errorf("proto: Nested3A: illegal tag %d (wire type %d)", fieldNum, wire) + } + switch fieldNum { + case 1: + if wireType != 0 { + return protoiface.UnmarshalOutput{NoUnkeyedLiterals: input.NoUnkeyedLiterals, Flags: input.Flags}, fmt.Errorf("proto: wrong wireType = %d for field Id", wireType) + } + x.Id = 0 + for shift := uint(0); ; shift += 7 { + if shift >= 64 { + return protoiface.UnmarshalOutput{NoUnkeyedLiterals: input.NoUnkeyedLiterals, Flags: input.Flags}, runtime.ErrIntOverflow + } + if iNdEx >= l { + return protoiface.UnmarshalOutput{NoUnkeyedLiterals: input.NoUnkeyedLiterals, Flags: input.Flags}, io.ErrUnexpectedEOF + } + b := dAtA[iNdEx] + iNdEx++ + x.Id |= int32(b&0x7F) << shift + if b < 0x80 { + break + } + } + case 2: + if wireType != 2 { + return protoiface.UnmarshalOutput{NoUnkeyedLiterals: input.NoUnkeyedLiterals, Flags: input.Flags}, fmt.Errorf("proto: wrong wireType = %d for field Name", wireType) + } + var stringLen uint64 + for shift := uint(0); ; shift += 7 { + if shift >= 64 { + return protoiface.UnmarshalOutput{NoUnkeyedLiterals: input.NoUnkeyedLiterals, Flags: input.Flags}, runtime.ErrIntOverflow + } + if iNdEx >= l { + return protoiface.UnmarshalOutput{NoUnkeyedLiterals: input.NoUnkeyedLiterals, Flags: input.Flags}, io.ErrUnexpectedEOF + } + b := dAtA[iNdEx] + iNdEx++ + stringLen |= uint64(b&0x7F) << shift + if b < 0x80 { + break + } + } + intStringLen := int(stringLen) + if intStringLen < 0 { + return protoiface.UnmarshalOutput{NoUnkeyedLiterals: input.NoUnkeyedLiterals, Flags: input.Flags}, runtime.ErrInvalidLength + } + postIndex := iNdEx + intStringLen + if postIndex < 0 { + return protoiface.UnmarshalOutput{NoUnkeyedLiterals: input.NoUnkeyedLiterals, Flags: input.Flags}, runtime.ErrInvalidLength + } + if postIndex > l { + return protoiface.UnmarshalOutput{NoUnkeyedLiterals: input.NoUnkeyedLiterals, Flags: input.Flags}, io.ErrUnexpectedEOF + } + x.Name = string(dAtA[iNdEx:postIndex]) + iNdEx = postIndex + case 4: + if wireType != 2 { + return protoiface.UnmarshalOutput{NoUnkeyedLiterals: input.NoUnkeyedLiterals, Flags: input.Flags}, fmt.Errorf("proto: wrong wireType = %d for field A4", wireType) + } + var msglen int + for shift := uint(0); ; shift += 7 { + if shift >= 64 { + return protoiface.UnmarshalOutput{NoUnkeyedLiterals: input.NoUnkeyedLiterals, Flags: input.Flags}, runtime.ErrIntOverflow + } + if iNdEx >= l { + return protoiface.UnmarshalOutput{NoUnkeyedLiterals: input.NoUnkeyedLiterals, Flags: input.Flags}, io.ErrUnexpectedEOF + } + b := dAtA[iNdEx] + iNdEx++ + msglen |= int(b&0x7F) << shift + if b < 0x80 { + break + } + } + if msglen < 0 { + return protoiface.UnmarshalOutput{NoUnkeyedLiterals: input.NoUnkeyedLiterals, Flags: input.Flags}, runtime.ErrInvalidLength + } + postIndex := iNdEx + msglen + if postIndex < 0 { + return protoiface.UnmarshalOutput{NoUnkeyedLiterals: input.NoUnkeyedLiterals, Flags: input.Flags}, runtime.ErrInvalidLength + } + if postIndex > l { + return protoiface.UnmarshalOutput{NoUnkeyedLiterals: input.NoUnkeyedLiterals, Flags: input.Flags}, io.ErrUnexpectedEOF + } + x.A4 = append(x.A4, &Nested4A{}) + if err := options.Unmarshal(dAtA[iNdEx:postIndex], x.A4[len(x.A4)-1]); err != nil { + return protoiface.UnmarshalOutput{NoUnkeyedLiterals: input.NoUnkeyedLiterals, Flags: input.Flags}, err + } + iNdEx = postIndex + case 5: + if wireType != 2 { + return protoiface.UnmarshalOutput{NoUnkeyedLiterals: input.NoUnkeyedLiterals, Flags: input.Flags}, fmt.Errorf("proto: wrong wireType = %d for field Index", wireType) + } + var msglen int + for shift := uint(0); ; shift += 7 { + if shift >= 64 { + return protoiface.UnmarshalOutput{NoUnkeyedLiterals: input.NoUnkeyedLiterals, Flags: input.Flags}, runtime.ErrIntOverflow + } + if iNdEx >= l { + return protoiface.UnmarshalOutput{NoUnkeyedLiterals: input.NoUnkeyedLiterals, Flags: input.Flags}, io.ErrUnexpectedEOF + } + b := dAtA[iNdEx] + iNdEx++ + msglen |= int(b&0x7F) << shift + if b < 0x80 { + break + } + } + if msglen < 0 { + return protoiface.UnmarshalOutput{NoUnkeyedLiterals: input.NoUnkeyedLiterals, Flags: input.Flags}, runtime.ErrInvalidLength + } + postIndex := iNdEx + msglen + if postIndex < 0 { + return protoiface.UnmarshalOutput{NoUnkeyedLiterals: input.NoUnkeyedLiterals, Flags: input.Flags}, runtime.ErrInvalidLength + } + if postIndex > l { + return protoiface.UnmarshalOutput{NoUnkeyedLiterals: input.NoUnkeyedLiterals, Flags: input.Flags}, io.ErrUnexpectedEOF + } + if x.Index == nil { + x.Index = make(map[int64]*Nested4A) + } + var mapkey int64 + var mapvalue *Nested4A + for iNdEx < postIndex { + entryPreIndex := iNdEx + var wire uint64 + for shift := uint(0); ; shift += 7 { + if shift >= 64 { + return protoiface.UnmarshalOutput{NoUnkeyedLiterals: input.NoUnkeyedLiterals, Flags: input.Flags}, runtime.ErrIntOverflow + } + if iNdEx >= l { + return protoiface.UnmarshalOutput{NoUnkeyedLiterals: input.NoUnkeyedLiterals, Flags: input.Flags}, io.ErrUnexpectedEOF + } + b := dAtA[iNdEx] + iNdEx++ + wire |= uint64(b&0x7F) << shift + if b < 0x80 { + break + } + } + fieldNum := int32(wire >> 3) + if fieldNum == 1 { + for shift := uint(0); ; shift += 7 { + if shift >= 64 { + return protoiface.UnmarshalOutput{NoUnkeyedLiterals: input.NoUnkeyedLiterals, Flags: input.Flags}, runtime.ErrIntOverflow + } + if iNdEx >= l { + return protoiface.UnmarshalOutput{NoUnkeyedLiterals: input.NoUnkeyedLiterals, Flags: input.Flags}, io.ErrUnexpectedEOF + } + b := dAtA[iNdEx] + iNdEx++ + mapkey |= int64(b&0x7F) << shift + if b < 0x80 { + break + } + } + } else if fieldNum == 2 { + var mapmsglen int + for shift := uint(0); ; shift += 7 { + if shift >= 64 { + return protoiface.UnmarshalOutput{NoUnkeyedLiterals: input.NoUnkeyedLiterals, Flags: input.Flags}, runtime.ErrIntOverflow + } + if iNdEx >= l { + return protoiface.UnmarshalOutput{NoUnkeyedLiterals: input.NoUnkeyedLiterals, Flags: input.Flags}, io.ErrUnexpectedEOF + } + b := dAtA[iNdEx] + iNdEx++ + mapmsglen |= int(b&0x7F) << shift + if b < 0x80 { + break + } + } + if mapmsglen < 0 { + return protoiface.UnmarshalOutput{NoUnkeyedLiterals: input.NoUnkeyedLiterals, Flags: input.Flags}, runtime.ErrInvalidLength + } + postmsgIndex := iNdEx + mapmsglen + if postmsgIndex < 0 { + return protoiface.UnmarshalOutput{NoUnkeyedLiterals: input.NoUnkeyedLiterals, Flags: input.Flags}, runtime.ErrInvalidLength + } + if postmsgIndex > l { + return protoiface.UnmarshalOutput{NoUnkeyedLiterals: input.NoUnkeyedLiterals, Flags: input.Flags}, io.ErrUnexpectedEOF + } + mapvalue = &Nested4A{} + if err := options.Unmarshal(dAtA[iNdEx:postmsgIndex], mapvalue); err != nil { + return protoiface.UnmarshalOutput{NoUnkeyedLiterals: input.NoUnkeyedLiterals, Flags: input.Flags}, err + } + iNdEx = postmsgIndex + } else { + iNdEx = entryPreIndex + skippy, err := runtime.Skip(dAtA[iNdEx:]) + if err != nil { + return protoiface.UnmarshalOutput{NoUnkeyedLiterals: input.NoUnkeyedLiterals, Flags: input.Flags}, err + } + if (skippy < 0) || (iNdEx+skippy) < 0 { + return protoiface.UnmarshalOutput{NoUnkeyedLiterals: input.NoUnkeyedLiterals, Flags: input.Flags}, runtime.ErrInvalidLength + } + if (iNdEx + skippy) > postIndex { + return protoiface.UnmarshalOutput{NoUnkeyedLiterals: input.NoUnkeyedLiterals, Flags: input.Flags}, io.ErrUnexpectedEOF + } + iNdEx += skippy + } + } + x.Index[mapkey] = mapvalue + iNdEx = postIndex + default: + iNdEx = preIndex + skippy, err := runtime.Skip(dAtA[iNdEx:]) + if err != nil { + return protoiface.UnmarshalOutput{NoUnkeyedLiterals: input.NoUnkeyedLiterals, Flags: input.Flags}, err + } + if (skippy < 0) || (iNdEx+skippy) < 0 { + return protoiface.UnmarshalOutput{NoUnkeyedLiterals: input.NoUnkeyedLiterals, Flags: input.Flags}, runtime.ErrInvalidLength + } + if (iNdEx + skippy) > l { + return protoiface.UnmarshalOutput{NoUnkeyedLiterals: input.NoUnkeyedLiterals, Flags: input.Flags}, io.ErrUnexpectedEOF + } + if !options.DiscardUnknown { + x.unknownFields = append(x.unknownFields, dAtA[iNdEx:iNdEx+skippy]...) + } + iNdEx += skippy + } + } + + if iNdEx > l { + return protoiface.UnmarshalOutput{NoUnkeyedLiterals: input.NoUnkeyedLiterals, Flags: input.Flags}, io.ErrUnexpectedEOF + } + return protoiface.UnmarshalOutput{NoUnkeyedLiterals: input.NoUnkeyedLiterals, Flags: input.Flags}, nil + } + return &protoiface.Methods{ + NoUnkeyedLiterals: struct{}{}, + Flags: protoiface.SupportMarshalDeterministic | protoiface.SupportUnmarshalDiscardUnknown, + Size: size, + Marshal: marshal, + Unmarshal: unmarshal, + Merge: nil, + CheckInitialized: nil, + } +} + +var ( + md_Nested2A protoreflect.MessageDescriptor + fd_Nested2A_id protoreflect.FieldDescriptor + fd_Nested2A_name protoreflect.FieldDescriptor + fd_Nested2A_nested protoreflect.FieldDescriptor +) + +func init() { + file_unknownproto_proto_init() + md_Nested2A = File_unknownproto_proto.Messages().ByName("Nested2A") + fd_Nested2A_id = md_Nested2A.Fields().ByName("id") + fd_Nested2A_name = md_Nested2A.Fields().ByName("name") + fd_Nested2A_nested = md_Nested2A.Fields().ByName("nested") +} + +var _ protoreflect.Message = (*fastReflection_Nested2A)(nil) + +type fastReflection_Nested2A Nested2A + +func (x *Nested2A) ProtoReflect() protoreflect.Message { + return (*fastReflection_Nested2A)(x) +} + +func (x *Nested2A) slowProtoReflect() protoreflect.Message { + mi := &file_unknownproto_proto_msgTypes[4] + if protoimpl.UnsafeEnabled && x != nil { + ms := protoimpl.X.MessageStateOf(protoimpl.Pointer(x)) + if ms.LoadMessageInfo() == nil { + ms.StoreMessageInfo(mi) + } + return ms + } + return mi.MessageOf(x) +} + +var _fastReflection_Nested2A_messageType fastReflection_Nested2A_messageType +var _ protoreflect.MessageType = fastReflection_Nested2A_messageType{} + +type fastReflection_Nested2A_messageType struct{} + +func (x fastReflection_Nested2A_messageType) Zero() protoreflect.Message { + return (*fastReflection_Nested2A)(nil) +} +func (x fastReflection_Nested2A_messageType) New() protoreflect.Message { + return new(fastReflection_Nested2A) +} +func (x fastReflection_Nested2A_messageType) Descriptor() protoreflect.MessageDescriptor { + return md_Nested2A +} + +// Descriptor returns message descriptor, which contains only the protobuf +// type information for the message. +func (x *fastReflection_Nested2A) Descriptor() protoreflect.MessageDescriptor { + return md_Nested2A +} + +// Type returns the message type, which encapsulates both Go and protobuf +// type information. If the Go type information is not needed, +// it is recommended that the message descriptor be used instead. +func (x *fastReflection_Nested2A) Type() protoreflect.MessageType { + return _fastReflection_Nested2A_messageType +} + +// New returns a newly allocated and mutable empty message. +func (x *fastReflection_Nested2A) New() protoreflect.Message { + return new(fastReflection_Nested2A) +} + +// Interface unwraps the message reflection interface and +// returns the underlying ProtoMessage interface. +func (x *fastReflection_Nested2A) Interface() protoreflect.ProtoMessage { + return (*Nested2A)(x) +} + +// Range iterates over every populated field in an undefined order, +// calling f for each field descriptor and value encountered. +// Range returns immediately if f returns false. +// While iterating, mutating operations may only be performed +// on the current field descriptor. +func (x *fastReflection_Nested2A) Range(f func(protoreflect.FieldDescriptor, protoreflect.Value) bool) { + if x.Id != int32(0) { + value := protoreflect.ValueOfInt32(x.Id) + if !f(fd_Nested2A_id, value) { + return + } + } + if x.Name != "" { + value := protoreflect.ValueOfString(x.Name) + if !f(fd_Nested2A_name, value) { + return + } + } + if x.Nested != nil { + value := protoreflect.ValueOfMessage(x.Nested.ProtoReflect()) + if !f(fd_Nested2A_nested, value) { + return + } + } +} + +// Has reports whether a field is populated. +// +// Some fields have the property of nullability where it is possible to +// distinguish between the default value of a field and whether the field +// was explicitly populated with the default value. Singular message fields, +// member fields of a oneof, and proto2 scalar fields are nullable. Such +// fields are populated only if explicitly set. +// +// In other cases (aside from the nullable cases above), +// a proto3 scalar field is populated if it contains a non-zero value, and +// a repeated field is populated if it is non-empty. +func (x *fastReflection_Nested2A) Has(fd protoreflect.FieldDescriptor) bool { + switch fd.FullName() { + case "testpb.Nested2A.id": + return x.Id != int32(0) + case "testpb.Nested2A.name": + return x.Name != "" + case "testpb.Nested2A.nested": + return x.Nested != nil + default: + if fd.IsExtension() { + panic(fmt.Errorf("proto3 declared messages do not support extensions: testpb.Nested2A")) + } + panic(fmt.Errorf("message testpb.Nested2A does not contain field %s", fd.FullName())) + } +} + +// Clear clears the field such that a subsequent Has call reports false. +// +// Clearing an extension field clears both the extension type and value +// associated with the given field number. +// +// Clear is a mutating operation and unsafe for concurrent use. +func (x *fastReflection_Nested2A) Clear(fd protoreflect.FieldDescriptor) { + switch fd.FullName() { + case "testpb.Nested2A.id": + x.Id = int32(0) + case "testpb.Nested2A.name": + x.Name = "" + case "testpb.Nested2A.nested": + x.Nested = nil + default: + if fd.IsExtension() { + panic(fmt.Errorf("proto3 declared messages do not support extensions: testpb.Nested2A")) + } + panic(fmt.Errorf("message testpb.Nested2A does not contain field %s", fd.FullName())) + } +} + +// Get retrieves the value for a field. +// +// For unpopulated scalars, it returns the default value, where +// the default value of a bytes scalar is guaranteed to be a copy. +// For unpopulated composite types, it returns an empty, read-only view +// of the value; to obtain a mutable reference, use Mutable. +func (x *fastReflection_Nested2A) Get(descriptor protoreflect.FieldDescriptor) protoreflect.Value { + switch descriptor.FullName() { + case "testpb.Nested2A.id": + value := x.Id + return protoreflect.ValueOfInt32(value) + case "testpb.Nested2A.name": + value := x.Name + return protoreflect.ValueOfString(value) + case "testpb.Nested2A.nested": + value := x.Nested + return protoreflect.ValueOfMessage(value.ProtoReflect()) + default: + if descriptor.IsExtension() { + panic(fmt.Errorf("proto3 declared messages do not support extensions: testpb.Nested2A")) + } + panic(fmt.Errorf("message testpb.Nested2A does not contain field %s", descriptor.FullName())) + } +} + +// Set stores the value for a field. +// +// For a field belonging to a oneof, it implicitly clears any other field +// that may be currently set within the same oneof. +// For extension fields, it implicitly stores the provided ExtensionType. +// When setting a composite type, it is unspecified whether the stored value +// aliases the source's memory in any way. If the composite value is an +// empty, read-only value, then it panics. +// +// Set is a mutating operation and unsafe for concurrent use. +func (x *fastReflection_Nested2A) Set(fd protoreflect.FieldDescriptor, value protoreflect.Value) { + switch fd.FullName() { + case "testpb.Nested2A.id": + x.Id = int32(value.Int()) + case "testpb.Nested2A.name": + x.Name = value.Interface().(string) + case "testpb.Nested2A.nested": + x.Nested = value.Message().Interface().(*Nested3A) + default: + if fd.IsExtension() { + panic(fmt.Errorf("proto3 declared messages do not support extensions: testpb.Nested2A")) + } + panic(fmt.Errorf("message testpb.Nested2A does not contain field %s", fd.FullName())) + } +} + +// Mutable returns a mutable reference to a composite type. +// +// If the field is unpopulated, it may allocate a composite value. +// For a field belonging to a oneof, it implicitly clears any other field +// that may be currently set within the same oneof. +// For extension fields, it implicitly stores the provided ExtensionType +// if not already stored. +// It panics if the field does not contain a composite type. +// +// Mutable is a mutating operation and unsafe for concurrent use. +func (x *fastReflection_Nested2A) Mutable(fd protoreflect.FieldDescriptor) protoreflect.Value { + switch fd.FullName() { + case "testpb.Nested2A.nested": + if x.Nested == nil { + x.Nested = new(Nested3A) + } + return protoreflect.ValueOfMessage(x.Nested.ProtoReflect()) + case "testpb.Nested2A.id": + panic(fmt.Errorf("field id of message testpb.Nested2A is not mutable")) + case "testpb.Nested2A.name": + panic(fmt.Errorf("field name of message testpb.Nested2A is not mutable")) + default: + if fd.IsExtension() { + panic(fmt.Errorf("proto3 declared messages do not support extensions: testpb.Nested2A")) + } + panic(fmt.Errorf("message testpb.Nested2A does not contain field %s", fd.FullName())) + } +} + +// NewField returns a new value that is assignable to the field +// for the given descriptor. For scalars, this returns the default value. +// For lists, maps, and messages, this returns a new, empty, mutable value. +func (x *fastReflection_Nested2A) NewField(fd protoreflect.FieldDescriptor) protoreflect.Value { + switch fd.FullName() { + case "testpb.Nested2A.id": + return protoreflect.ValueOfInt32(int32(0)) + case "testpb.Nested2A.name": + return protoreflect.ValueOfString("") + case "testpb.Nested2A.nested": + m := new(Nested3A) + return protoreflect.ValueOfMessage(m.ProtoReflect()) + default: + if fd.IsExtension() { + panic(fmt.Errorf("proto3 declared messages do not support extensions: testpb.Nested2A")) + } + panic(fmt.Errorf("message testpb.Nested2A does not contain field %s", fd.FullName())) + } +} + +// WhichOneof reports which field within the oneof is populated, +// returning nil if none are populated. +// It panics if the oneof descriptor does not belong to this message. +func (x *fastReflection_Nested2A) WhichOneof(d protoreflect.OneofDescriptor) protoreflect.FieldDescriptor { + switch d.FullName() { + default: + panic(fmt.Errorf("%s is not a oneof field in testpb.Nested2A", d.FullName())) + } + panic("unreachable") +} + +// GetUnknown retrieves the entire list of unknown fields. +// The caller may only mutate the contents of the RawFields +// if the mutated bytes are stored back into the message with SetUnknown. +func (x *fastReflection_Nested2A) GetUnknown() protoreflect.RawFields { + return x.unknownFields +} + +// SetUnknown stores an entire list of unknown fields. +// The raw fields must be syntactically valid according to the wire format. +// An implementation may panic if this is not the case. +// Once stored, the caller must not mutate the content of the RawFields. +// An empty RawFields may be passed to clear the fields. +// +// SetUnknown is a mutating operation and unsafe for concurrent use. +func (x *fastReflection_Nested2A) SetUnknown(fields protoreflect.RawFields) { + x.unknownFields = fields +} + +// IsValid reports whether the message is valid. +// +// An invalid message is an empty, read-only value. +// +// An invalid message often corresponds to a nil pointer of the concrete +// message type, but the details are implementation dependent. +// Validity is not part of the protobuf data model, and may not +// be preserved in marshaling or other operations. +func (x *fastReflection_Nested2A) IsValid() bool { + return x != nil +} + +// ProtoMethods returns optional fastReflectionFeature-path implementations of various operations. +// This method may return nil. +// +// The returned methods type is identical to +// "google.golang.org/protobuf/runtime/protoiface".Methods. +// Consult the protoiface package documentation for details. +func (x *fastReflection_Nested2A) ProtoMethods() *protoiface.Methods { + size := func(input protoiface.SizeInput) protoiface.SizeOutput { + x := input.Message.Interface().(*Nested2A) + if x == nil { + return protoiface.SizeOutput{ + NoUnkeyedLiterals: input.NoUnkeyedLiterals, + Size: 0, + } + } + options := runtime.SizeInputToOptions(input) + _ = options + var n int + var l int + _ = l + if x.Id != 0 { + n += 1 + runtime.Sov(uint64(x.Id)) + } + l = len(x.Name) + if l > 0 { + n += 1 + l + runtime.Sov(uint64(l)) + } + if x.Nested != nil { + l = options.Size(x.Nested) + n += 1 + l + runtime.Sov(uint64(l)) + } + if x.unknownFields != nil { + n += len(x.unknownFields) + } + return protoiface.SizeOutput{ + NoUnkeyedLiterals: input.NoUnkeyedLiterals, + Size: n, + } + } + + marshal := func(input protoiface.MarshalInput) (protoiface.MarshalOutput, error) { + x := input.Message.Interface().(*Nested2A) + if x == nil { + return protoiface.MarshalOutput{ + NoUnkeyedLiterals: input.NoUnkeyedLiterals, + Buf: input.Buf, + }, nil + } + options := runtime.MarshalInputToOptions(input) + _ = options + size := options.Size(x) + dAtA := make([]byte, size) + i := len(dAtA) + _ = i + var l int + _ = l + if x.unknownFields != nil { + i -= len(x.unknownFields) + copy(dAtA[i:], x.unknownFields) + } + if x.Nested != nil { + encoded, err := options.Marshal(x.Nested) + if err != nil { + return protoiface.MarshalOutput{ + NoUnkeyedLiterals: input.NoUnkeyedLiterals, + Buf: input.Buf, + }, err + } + i -= len(encoded) + copy(dAtA[i:], encoded) + i = runtime.EncodeVarint(dAtA, i, uint64(len(encoded))) + i-- + dAtA[i] = 0x1a + } + if len(x.Name) > 0 { + i -= len(x.Name) + copy(dAtA[i:], x.Name) + i = runtime.EncodeVarint(dAtA, i, uint64(len(x.Name))) + i-- + dAtA[i] = 0x12 + } + if x.Id != 0 { + i = runtime.EncodeVarint(dAtA, i, uint64(x.Id)) + i-- + dAtA[i] = 0x8 + } + if input.Buf != nil { + input.Buf = append(input.Buf, dAtA...) + } else { + input.Buf = dAtA + } + return protoiface.MarshalOutput{ + NoUnkeyedLiterals: input.NoUnkeyedLiterals, + Buf: input.Buf, + }, nil + } + unmarshal := func(input protoiface.UnmarshalInput) (protoiface.UnmarshalOutput, error) { + x := input.Message.Interface().(*Nested2A) + if x == nil { + return protoiface.UnmarshalOutput{ + NoUnkeyedLiterals: input.NoUnkeyedLiterals, + Flags: input.Flags, + }, nil + } + options := runtime.UnmarshalInputToOptions(input) + _ = options + dAtA := input.Buf + l := len(dAtA) + iNdEx := 0 + for iNdEx < l { + preIndex := iNdEx + var wire uint64 + for shift := uint(0); ; shift += 7 { + if shift >= 64 { + return protoiface.UnmarshalOutput{NoUnkeyedLiterals: input.NoUnkeyedLiterals, Flags: input.Flags}, runtime.ErrIntOverflow + } + if iNdEx >= l { + return protoiface.UnmarshalOutput{NoUnkeyedLiterals: input.NoUnkeyedLiterals, Flags: input.Flags}, io.ErrUnexpectedEOF + } + b := dAtA[iNdEx] + iNdEx++ + wire |= uint64(b&0x7F) << shift + if b < 0x80 { + break + } + } + fieldNum := int32(wire >> 3) + wireType := int(wire & 0x7) + if wireType == 4 { + return protoiface.UnmarshalOutput{NoUnkeyedLiterals: input.NoUnkeyedLiterals, Flags: input.Flags}, fmt.Errorf("proto: Nested2A: wiretype end group for non-group") + } + if fieldNum <= 0 { + return protoiface.UnmarshalOutput{NoUnkeyedLiterals: input.NoUnkeyedLiterals, Flags: input.Flags}, fmt.Errorf("proto: Nested2A: illegal tag %d (wire type %d)", fieldNum, wire) + } + switch fieldNum { + case 1: + if wireType != 0 { + return protoiface.UnmarshalOutput{NoUnkeyedLiterals: input.NoUnkeyedLiterals, Flags: input.Flags}, fmt.Errorf("proto: wrong wireType = %d for field Id", wireType) + } + x.Id = 0 + for shift := uint(0); ; shift += 7 { + if shift >= 64 { + return protoiface.UnmarshalOutput{NoUnkeyedLiterals: input.NoUnkeyedLiterals, Flags: input.Flags}, runtime.ErrIntOverflow + } + if iNdEx >= l { + return protoiface.UnmarshalOutput{NoUnkeyedLiterals: input.NoUnkeyedLiterals, Flags: input.Flags}, io.ErrUnexpectedEOF + } + b := dAtA[iNdEx] + iNdEx++ + x.Id |= int32(b&0x7F) << shift + if b < 0x80 { + break + } + } + case 2: + if wireType != 2 { + return protoiface.UnmarshalOutput{NoUnkeyedLiterals: input.NoUnkeyedLiterals, Flags: input.Flags}, fmt.Errorf("proto: wrong wireType = %d for field Name", wireType) + } + var stringLen uint64 + for shift := uint(0); ; shift += 7 { + if shift >= 64 { + return protoiface.UnmarshalOutput{NoUnkeyedLiterals: input.NoUnkeyedLiterals, Flags: input.Flags}, runtime.ErrIntOverflow + } + if iNdEx >= l { + return protoiface.UnmarshalOutput{NoUnkeyedLiterals: input.NoUnkeyedLiterals, Flags: input.Flags}, io.ErrUnexpectedEOF + } + b := dAtA[iNdEx] + iNdEx++ + stringLen |= uint64(b&0x7F) << shift + if b < 0x80 { + break + } + } + intStringLen := int(stringLen) + if intStringLen < 0 { + return protoiface.UnmarshalOutput{NoUnkeyedLiterals: input.NoUnkeyedLiterals, Flags: input.Flags}, runtime.ErrInvalidLength + } + postIndex := iNdEx + intStringLen + if postIndex < 0 { + return protoiface.UnmarshalOutput{NoUnkeyedLiterals: input.NoUnkeyedLiterals, Flags: input.Flags}, runtime.ErrInvalidLength + } + if postIndex > l { + return protoiface.UnmarshalOutput{NoUnkeyedLiterals: input.NoUnkeyedLiterals, Flags: input.Flags}, io.ErrUnexpectedEOF + } + x.Name = string(dAtA[iNdEx:postIndex]) + iNdEx = postIndex + case 3: + if wireType != 2 { + return protoiface.UnmarshalOutput{NoUnkeyedLiterals: input.NoUnkeyedLiterals, Flags: input.Flags}, fmt.Errorf("proto: wrong wireType = %d for field Nested", wireType) + } + var msglen int + for shift := uint(0); ; shift += 7 { + if shift >= 64 { + return protoiface.UnmarshalOutput{NoUnkeyedLiterals: input.NoUnkeyedLiterals, Flags: input.Flags}, runtime.ErrIntOverflow + } + if iNdEx >= l { + return protoiface.UnmarshalOutput{NoUnkeyedLiterals: input.NoUnkeyedLiterals, Flags: input.Flags}, io.ErrUnexpectedEOF + } + b := dAtA[iNdEx] + iNdEx++ + msglen |= int(b&0x7F) << shift + if b < 0x80 { + break + } + } + if msglen < 0 { + return protoiface.UnmarshalOutput{NoUnkeyedLiterals: input.NoUnkeyedLiterals, Flags: input.Flags}, runtime.ErrInvalidLength + } + postIndex := iNdEx + msglen + if postIndex < 0 { + return protoiface.UnmarshalOutput{NoUnkeyedLiterals: input.NoUnkeyedLiterals, Flags: input.Flags}, runtime.ErrInvalidLength + } + if postIndex > l { + return protoiface.UnmarshalOutput{NoUnkeyedLiterals: input.NoUnkeyedLiterals, Flags: input.Flags}, io.ErrUnexpectedEOF + } + if x.Nested == nil { + x.Nested = &Nested3A{} + } + if err := options.Unmarshal(dAtA[iNdEx:postIndex], x.Nested); err != nil { + return protoiface.UnmarshalOutput{NoUnkeyedLiterals: input.NoUnkeyedLiterals, Flags: input.Flags}, err + } + iNdEx = postIndex + default: + iNdEx = preIndex + skippy, err := runtime.Skip(dAtA[iNdEx:]) + if err != nil { + return protoiface.UnmarshalOutput{NoUnkeyedLiterals: input.NoUnkeyedLiterals, Flags: input.Flags}, err + } + if (skippy < 0) || (iNdEx+skippy) < 0 { + return protoiface.UnmarshalOutput{NoUnkeyedLiterals: input.NoUnkeyedLiterals, Flags: input.Flags}, runtime.ErrInvalidLength + } + if (iNdEx + skippy) > l { + return protoiface.UnmarshalOutput{NoUnkeyedLiterals: input.NoUnkeyedLiterals, Flags: input.Flags}, io.ErrUnexpectedEOF + } + if !options.DiscardUnknown { + x.unknownFields = append(x.unknownFields, dAtA[iNdEx:iNdEx+skippy]...) + } + iNdEx += skippy + } + } + + if iNdEx > l { + return protoiface.UnmarshalOutput{NoUnkeyedLiterals: input.NoUnkeyedLiterals, Flags: input.Flags}, io.ErrUnexpectedEOF + } + return protoiface.UnmarshalOutput{NoUnkeyedLiterals: input.NoUnkeyedLiterals, Flags: input.Flags}, nil + } + return &protoiface.Methods{ + NoUnkeyedLiterals: struct{}{}, + Flags: protoiface.SupportMarshalDeterministic | protoiface.SupportUnmarshalDiscardUnknown, + Size: size, + Marshal: marshal, + Unmarshal: unmarshal, + Merge: nil, + CheckInitialized: nil, + } +} + +var ( + md_Nested1A protoreflect.MessageDescriptor + fd_Nested1A_id protoreflect.FieldDescriptor + fd_Nested1A_nested protoreflect.FieldDescriptor +) + +func init() { + file_unknownproto_proto_init() + md_Nested1A = File_unknownproto_proto.Messages().ByName("Nested1A") + fd_Nested1A_id = md_Nested1A.Fields().ByName("id") + fd_Nested1A_nested = md_Nested1A.Fields().ByName("nested") +} + +var _ protoreflect.Message = (*fastReflection_Nested1A)(nil) + +type fastReflection_Nested1A Nested1A + +func (x *Nested1A) ProtoReflect() protoreflect.Message { + return (*fastReflection_Nested1A)(x) +} + +func (x *Nested1A) slowProtoReflect() protoreflect.Message { + mi := &file_unknownproto_proto_msgTypes[5] + if protoimpl.UnsafeEnabled && x != nil { + ms := protoimpl.X.MessageStateOf(protoimpl.Pointer(x)) + if ms.LoadMessageInfo() == nil { + ms.StoreMessageInfo(mi) + } + return ms + } + return mi.MessageOf(x) +} + +var _fastReflection_Nested1A_messageType fastReflection_Nested1A_messageType +var _ protoreflect.MessageType = fastReflection_Nested1A_messageType{} + +type fastReflection_Nested1A_messageType struct{} + +func (x fastReflection_Nested1A_messageType) Zero() protoreflect.Message { + return (*fastReflection_Nested1A)(nil) +} +func (x fastReflection_Nested1A_messageType) New() protoreflect.Message { + return new(fastReflection_Nested1A) +} +func (x fastReflection_Nested1A_messageType) Descriptor() protoreflect.MessageDescriptor { + return md_Nested1A +} + +// Descriptor returns message descriptor, which contains only the protobuf +// type information for the message. +func (x *fastReflection_Nested1A) Descriptor() protoreflect.MessageDescriptor { + return md_Nested1A +} + +// Type returns the message type, which encapsulates both Go and protobuf +// type information. If the Go type information is not needed, +// it is recommended that the message descriptor be used instead. +func (x *fastReflection_Nested1A) Type() protoreflect.MessageType { + return _fastReflection_Nested1A_messageType +} + +// New returns a newly allocated and mutable empty message. +func (x *fastReflection_Nested1A) New() protoreflect.Message { + return new(fastReflection_Nested1A) +} + +// Interface unwraps the message reflection interface and +// returns the underlying ProtoMessage interface. +func (x *fastReflection_Nested1A) Interface() protoreflect.ProtoMessage { + return (*Nested1A)(x) +} + +// Range iterates over every populated field in an undefined order, +// calling f for each field descriptor and value encountered. +// Range returns immediately if f returns false. +// While iterating, mutating operations may only be performed +// on the current field descriptor. +func (x *fastReflection_Nested1A) Range(f func(protoreflect.FieldDescriptor, protoreflect.Value) bool) { + if x.Id != int32(0) { + value := protoreflect.ValueOfInt32(x.Id) + if !f(fd_Nested1A_id, value) { + return + } + } + if x.Nested != nil { + value := protoreflect.ValueOfMessage(x.Nested.ProtoReflect()) + if !f(fd_Nested1A_nested, value) { + return + } + } +} + +// Has reports whether a field is populated. +// +// Some fields have the property of nullability where it is possible to +// distinguish between the default value of a field and whether the field +// was explicitly populated with the default value. Singular message fields, +// member fields of a oneof, and proto2 scalar fields are nullable. Such +// fields are populated only if explicitly set. +// +// In other cases (aside from the nullable cases above), +// a proto3 scalar field is populated if it contains a non-zero value, and +// a repeated field is populated if it is non-empty. +func (x *fastReflection_Nested1A) Has(fd protoreflect.FieldDescriptor) bool { + switch fd.FullName() { + case "testpb.Nested1A.id": + return x.Id != int32(0) + case "testpb.Nested1A.nested": + return x.Nested != nil + default: + if fd.IsExtension() { + panic(fmt.Errorf("proto3 declared messages do not support extensions: testpb.Nested1A")) + } + panic(fmt.Errorf("message testpb.Nested1A does not contain field %s", fd.FullName())) + } +} + +// Clear clears the field such that a subsequent Has call reports false. +// +// Clearing an extension field clears both the extension type and value +// associated with the given field number. +// +// Clear is a mutating operation and unsafe for concurrent use. +func (x *fastReflection_Nested1A) Clear(fd protoreflect.FieldDescriptor) { + switch fd.FullName() { + case "testpb.Nested1A.id": + x.Id = int32(0) + case "testpb.Nested1A.nested": + x.Nested = nil + default: + if fd.IsExtension() { + panic(fmt.Errorf("proto3 declared messages do not support extensions: testpb.Nested1A")) + } + panic(fmt.Errorf("message testpb.Nested1A does not contain field %s", fd.FullName())) + } +} + +// Get retrieves the value for a field. +// +// For unpopulated scalars, it returns the default value, where +// the default value of a bytes scalar is guaranteed to be a copy. +// For unpopulated composite types, it returns an empty, read-only view +// of the value; to obtain a mutable reference, use Mutable. +func (x *fastReflection_Nested1A) Get(descriptor protoreflect.FieldDescriptor) protoreflect.Value { + switch descriptor.FullName() { + case "testpb.Nested1A.id": + value := x.Id + return protoreflect.ValueOfInt32(value) + case "testpb.Nested1A.nested": + value := x.Nested + return protoreflect.ValueOfMessage(value.ProtoReflect()) + default: + if descriptor.IsExtension() { + panic(fmt.Errorf("proto3 declared messages do not support extensions: testpb.Nested1A")) + } + panic(fmt.Errorf("message testpb.Nested1A does not contain field %s", descriptor.FullName())) + } +} + +// Set stores the value for a field. +// +// For a field belonging to a oneof, it implicitly clears any other field +// that may be currently set within the same oneof. +// For extension fields, it implicitly stores the provided ExtensionType. +// When setting a composite type, it is unspecified whether the stored value +// aliases the source's memory in any way. If the composite value is an +// empty, read-only value, then it panics. +// +// Set is a mutating operation and unsafe for concurrent use. +func (x *fastReflection_Nested1A) Set(fd protoreflect.FieldDescriptor, value protoreflect.Value) { + switch fd.FullName() { + case "testpb.Nested1A.id": + x.Id = int32(value.Int()) + case "testpb.Nested1A.nested": + x.Nested = value.Message().Interface().(*Nested2A) + default: + if fd.IsExtension() { + panic(fmt.Errorf("proto3 declared messages do not support extensions: testpb.Nested1A")) + } + panic(fmt.Errorf("message testpb.Nested1A does not contain field %s", fd.FullName())) + } +} + +// Mutable returns a mutable reference to a composite type. +// +// If the field is unpopulated, it may allocate a composite value. +// For a field belonging to a oneof, it implicitly clears any other field +// that may be currently set within the same oneof. +// For extension fields, it implicitly stores the provided ExtensionType +// if not already stored. +// It panics if the field does not contain a composite type. +// +// Mutable is a mutating operation and unsafe for concurrent use. +func (x *fastReflection_Nested1A) Mutable(fd protoreflect.FieldDescriptor) protoreflect.Value { + switch fd.FullName() { + case "testpb.Nested1A.nested": + if x.Nested == nil { + x.Nested = new(Nested2A) + } + return protoreflect.ValueOfMessage(x.Nested.ProtoReflect()) + case "testpb.Nested1A.id": + panic(fmt.Errorf("field id of message testpb.Nested1A is not mutable")) + default: + if fd.IsExtension() { + panic(fmt.Errorf("proto3 declared messages do not support extensions: testpb.Nested1A")) + } + panic(fmt.Errorf("message testpb.Nested1A does not contain field %s", fd.FullName())) + } +} + +// NewField returns a new value that is assignable to the field +// for the given descriptor. For scalars, this returns the default value. +// For lists, maps, and messages, this returns a new, empty, mutable value. +func (x *fastReflection_Nested1A) NewField(fd protoreflect.FieldDescriptor) protoreflect.Value { + switch fd.FullName() { + case "testpb.Nested1A.id": + return protoreflect.ValueOfInt32(int32(0)) + case "testpb.Nested1A.nested": + m := new(Nested2A) + return protoreflect.ValueOfMessage(m.ProtoReflect()) + default: + if fd.IsExtension() { + panic(fmt.Errorf("proto3 declared messages do not support extensions: testpb.Nested1A")) + } + panic(fmt.Errorf("message testpb.Nested1A does not contain field %s", fd.FullName())) + } +} + +// WhichOneof reports which field within the oneof is populated, +// returning nil if none are populated. +// It panics if the oneof descriptor does not belong to this message. +func (x *fastReflection_Nested1A) WhichOneof(d protoreflect.OneofDescriptor) protoreflect.FieldDescriptor { + switch d.FullName() { + default: + panic(fmt.Errorf("%s is not a oneof field in testpb.Nested1A", d.FullName())) + } + panic("unreachable") +} + +// GetUnknown retrieves the entire list of unknown fields. +// The caller may only mutate the contents of the RawFields +// if the mutated bytes are stored back into the message with SetUnknown. +func (x *fastReflection_Nested1A) GetUnknown() protoreflect.RawFields { + return x.unknownFields +} + +// SetUnknown stores an entire list of unknown fields. +// The raw fields must be syntactically valid according to the wire format. +// An implementation may panic if this is not the case. +// Once stored, the caller must not mutate the content of the RawFields. +// An empty RawFields may be passed to clear the fields. +// +// SetUnknown is a mutating operation and unsafe for concurrent use. +func (x *fastReflection_Nested1A) SetUnknown(fields protoreflect.RawFields) { + x.unknownFields = fields +} + +// IsValid reports whether the message is valid. +// +// An invalid message is an empty, read-only value. +// +// An invalid message often corresponds to a nil pointer of the concrete +// message type, but the details are implementation dependent. +// Validity is not part of the protobuf data model, and may not +// be preserved in marshaling or other operations. +func (x *fastReflection_Nested1A) IsValid() bool { + return x != nil +} + +// ProtoMethods returns optional fastReflectionFeature-path implementations of various operations. +// This method may return nil. +// +// The returned methods type is identical to +// "google.golang.org/protobuf/runtime/protoiface".Methods. +// Consult the protoiface package documentation for details. +func (x *fastReflection_Nested1A) ProtoMethods() *protoiface.Methods { + size := func(input protoiface.SizeInput) protoiface.SizeOutput { + x := input.Message.Interface().(*Nested1A) + if x == nil { + return protoiface.SizeOutput{ + NoUnkeyedLiterals: input.NoUnkeyedLiterals, + Size: 0, + } + } + options := runtime.SizeInputToOptions(input) + _ = options + var n int + var l int + _ = l + if x.Id != 0 { + n += 1 + runtime.Sov(uint64(x.Id)) + } + if x.Nested != nil { + l = options.Size(x.Nested) + n += 1 + l + runtime.Sov(uint64(l)) + } + if x.unknownFields != nil { + n += len(x.unknownFields) + } + return protoiface.SizeOutput{ + NoUnkeyedLiterals: input.NoUnkeyedLiterals, + Size: n, + } + } + + marshal := func(input protoiface.MarshalInput) (protoiface.MarshalOutput, error) { + x := input.Message.Interface().(*Nested1A) + if x == nil { + return protoiface.MarshalOutput{ + NoUnkeyedLiterals: input.NoUnkeyedLiterals, + Buf: input.Buf, + }, nil + } + options := runtime.MarshalInputToOptions(input) + _ = options + size := options.Size(x) + dAtA := make([]byte, size) + i := len(dAtA) + _ = i + var l int + _ = l + if x.unknownFields != nil { + i -= len(x.unknownFields) + copy(dAtA[i:], x.unknownFields) + } + if x.Nested != nil { + encoded, err := options.Marshal(x.Nested) + if err != nil { + return protoiface.MarshalOutput{ + NoUnkeyedLiterals: input.NoUnkeyedLiterals, + Buf: input.Buf, + }, err + } + i -= len(encoded) + copy(dAtA[i:], encoded) + i = runtime.EncodeVarint(dAtA, i, uint64(len(encoded))) + i-- + dAtA[i] = 0x12 + } + if x.Id != 0 { + i = runtime.EncodeVarint(dAtA, i, uint64(x.Id)) + i-- + dAtA[i] = 0x8 + } + if input.Buf != nil { + input.Buf = append(input.Buf, dAtA...) + } else { + input.Buf = dAtA + } + return protoiface.MarshalOutput{ + NoUnkeyedLiterals: input.NoUnkeyedLiterals, + Buf: input.Buf, + }, nil + } + unmarshal := func(input protoiface.UnmarshalInput) (protoiface.UnmarshalOutput, error) { + x := input.Message.Interface().(*Nested1A) + if x == nil { + return protoiface.UnmarshalOutput{ + NoUnkeyedLiterals: input.NoUnkeyedLiterals, + Flags: input.Flags, + }, nil + } + options := runtime.UnmarshalInputToOptions(input) + _ = options + dAtA := input.Buf + l := len(dAtA) + iNdEx := 0 + for iNdEx < l { + preIndex := iNdEx + var wire uint64 + for shift := uint(0); ; shift += 7 { + if shift >= 64 { + return protoiface.UnmarshalOutput{NoUnkeyedLiterals: input.NoUnkeyedLiterals, Flags: input.Flags}, runtime.ErrIntOverflow + } + if iNdEx >= l { + return protoiface.UnmarshalOutput{NoUnkeyedLiterals: input.NoUnkeyedLiterals, Flags: input.Flags}, io.ErrUnexpectedEOF + } + b := dAtA[iNdEx] + iNdEx++ + wire |= uint64(b&0x7F) << shift + if b < 0x80 { + break + } + } + fieldNum := int32(wire >> 3) + wireType := int(wire & 0x7) + if wireType == 4 { + return protoiface.UnmarshalOutput{NoUnkeyedLiterals: input.NoUnkeyedLiterals, Flags: input.Flags}, fmt.Errorf("proto: Nested1A: wiretype end group for non-group") + } + if fieldNum <= 0 { + return protoiface.UnmarshalOutput{NoUnkeyedLiterals: input.NoUnkeyedLiterals, Flags: input.Flags}, fmt.Errorf("proto: Nested1A: illegal tag %d (wire type %d)", fieldNum, wire) + } + switch fieldNum { + case 1: + if wireType != 0 { + return protoiface.UnmarshalOutput{NoUnkeyedLiterals: input.NoUnkeyedLiterals, Flags: input.Flags}, fmt.Errorf("proto: wrong wireType = %d for field Id", wireType) + } + x.Id = 0 + for shift := uint(0); ; shift += 7 { + if shift >= 64 { + return protoiface.UnmarshalOutput{NoUnkeyedLiterals: input.NoUnkeyedLiterals, Flags: input.Flags}, runtime.ErrIntOverflow + } + if iNdEx >= l { + return protoiface.UnmarshalOutput{NoUnkeyedLiterals: input.NoUnkeyedLiterals, Flags: input.Flags}, io.ErrUnexpectedEOF + } + b := dAtA[iNdEx] + iNdEx++ + x.Id |= int32(b&0x7F) << shift + if b < 0x80 { + break + } + } + case 2: + if wireType != 2 { + return protoiface.UnmarshalOutput{NoUnkeyedLiterals: input.NoUnkeyedLiterals, Flags: input.Flags}, fmt.Errorf("proto: wrong wireType = %d for field Nested", wireType) + } + var msglen int + for shift := uint(0); ; shift += 7 { + if shift >= 64 { + return protoiface.UnmarshalOutput{NoUnkeyedLiterals: input.NoUnkeyedLiterals, Flags: input.Flags}, runtime.ErrIntOverflow + } + if iNdEx >= l { + return protoiface.UnmarshalOutput{NoUnkeyedLiterals: input.NoUnkeyedLiterals, Flags: input.Flags}, io.ErrUnexpectedEOF + } + b := dAtA[iNdEx] + iNdEx++ + msglen |= int(b&0x7F) << shift + if b < 0x80 { + break + } + } + if msglen < 0 { + return protoiface.UnmarshalOutput{NoUnkeyedLiterals: input.NoUnkeyedLiterals, Flags: input.Flags}, runtime.ErrInvalidLength + } + postIndex := iNdEx + msglen + if postIndex < 0 { + return protoiface.UnmarshalOutput{NoUnkeyedLiterals: input.NoUnkeyedLiterals, Flags: input.Flags}, runtime.ErrInvalidLength + } + if postIndex > l { + return protoiface.UnmarshalOutput{NoUnkeyedLiterals: input.NoUnkeyedLiterals, Flags: input.Flags}, io.ErrUnexpectedEOF + } + if x.Nested == nil { + x.Nested = &Nested2A{} + } + if err := options.Unmarshal(dAtA[iNdEx:postIndex], x.Nested); err != nil { + return protoiface.UnmarshalOutput{NoUnkeyedLiterals: input.NoUnkeyedLiterals, Flags: input.Flags}, err + } + iNdEx = postIndex + default: + iNdEx = preIndex + skippy, err := runtime.Skip(dAtA[iNdEx:]) + if err != nil { + return protoiface.UnmarshalOutput{NoUnkeyedLiterals: input.NoUnkeyedLiterals, Flags: input.Flags}, err + } + if (skippy < 0) || (iNdEx+skippy) < 0 { + return protoiface.UnmarshalOutput{NoUnkeyedLiterals: input.NoUnkeyedLiterals, Flags: input.Flags}, runtime.ErrInvalidLength + } + if (iNdEx + skippy) > l { + return protoiface.UnmarshalOutput{NoUnkeyedLiterals: input.NoUnkeyedLiterals, Flags: input.Flags}, io.ErrUnexpectedEOF + } + if !options.DiscardUnknown { + x.unknownFields = append(x.unknownFields, dAtA[iNdEx:iNdEx+skippy]...) + } + iNdEx += skippy + } + } + + if iNdEx > l { + return protoiface.UnmarshalOutput{NoUnkeyedLiterals: input.NoUnkeyedLiterals, Flags: input.Flags}, io.ErrUnexpectedEOF + } + return protoiface.UnmarshalOutput{NoUnkeyedLiterals: input.NoUnkeyedLiterals, Flags: input.Flags}, nil + } + return &protoiface.Methods{ + NoUnkeyedLiterals: struct{}{}, + Flags: protoiface.SupportMarshalDeterministic | protoiface.SupportUnmarshalDiscardUnknown, + Size: size, + Marshal: marshal, + Unmarshal: unmarshal, + Merge: nil, + CheckInitialized: nil, + } +} + +var ( + md_Nested4B protoreflect.MessageDescriptor + fd_Nested4B_id protoreflect.FieldDescriptor + fd_Nested4B_age protoreflect.FieldDescriptor + fd_Nested4B_name protoreflect.FieldDescriptor +) + +func init() { + file_unknownproto_proto_init() + md_Nested4B = File_unknownproto_proto.Messages().ByName("Nested4B") + fd_Nested4B_id = md_Nested4B.Fields().ByName("id") + fd_Nested4B_age = md_Nested4B.Fields().ByName("age") + fd_Nested4B_name = md_Nested4B.Fields().ByName("name") +} + +var _ protoreflect.Message = (*fastReflection_Nested4B)(nil) + +type fastReflection_Nested4B Nested4B + +func (x *Nested4B) ProtoReflect() protoreflect.Message { + return (*fastReflection_Nested4B)(x) +} + +func (x *Nested4B) slowProtoReflect() protoreflect.Message { + mi := &file_unknownproto_proto_msgTypes[6] + if protoimpl.UnsafeEnabled && x != nil { + ms := protoimpl.X.MessageStateOf(protoimpl.Pointer(x)) + if ms.LoadMessageInfo() == nil { + ms.StoreMessageInfo(mi) + } + return ms + } + return mi.MessageOf(x) +} + +var _fastReflection_Nested4B_messageType fastReflection_Nested4B_messageType +var _ protoreflect.MessageType = fastReflection_Nested4B_messageType{} + +type fastReflection_Nested4B_messageType struct{} + +func (x fastReflection_Nested4B_messageType) Zero() protoreflect.Message { + return (*fastReflection_Nested4B)(nil) +} +func (x fastReflection_Nested4B_messageType) New() protoreflect.Message { + return new(fastReflection_Nested4B) +} +func (x fastReflection_Nested4B_messageType) Descriptor() protoreflect.MessageDescriptor { + return md_Nested4B +} + +// Descriptor returns message descriptor, which contains only the protobuf +// type information for the message. +func (x *fastReflection_Nested4B) Descriptor() protoreflect.MessageDescriptor { + return md_Nested4B +} + +// Type returns the message type, which encapsulates both Go and protobuf +// type information. If the Go type information is not needed, +// it is recommended that the message descriptor be used instead. +func (x *fastReflection_Nested4B) Type() protoreflect.MessageType { + return _fastReflection_Nested4B_messageType +} + +// New returns a newly allocated and mutable empty message. +func (x *fastReflection_Nested4B) New() protoreflect.Message { + return new(fastReflection_Nested4B) +} + +// Interface unwraps the message reflection interface and +// returns the underlying ProtoMessage interface. +func (x *fastReflection_Nested4B) Interface() protoreflect.ProtoMessage { + return (*Nested4B)(x) +} + +// Range iterates over every populated field in an undefined order, +// calling f for each field descriptor and value encountered. +// Range returns immediately if f returns false. +// While iterating, mutating operations may only be performed +// on the current field descriptor. +func (x *fastReflection_Nested4B) Range(f func(protoreflect.FieldDescriptor, protoreflect.Value) bool) { + if x.Id != int32(0) { + value := protoreflect.ValueOfInt32(x.Id) + if !f(fd_Nested4B_id, value) { + return + } + } + if x.Age != int32(0) { + value := protoreflect.ValueOfInt32(x.Age) + if !f(fd_Nested4B_age, value) { + return + } + } + if x.Name != "" { + value := protoreflect.ValueOfString(x.Name) + if !f(fd_Nested4B_name, value) { + return + } + } +} + +// Has reports whether a field is populated. +// +// Some fields have the property of nullability where it is possible to +// distinguish between the default value of a field and whether the field +// was explicitly populated with the default value. Singular message fields, +// member fields of a oneof, and proto2 scalar fields are nullable. Such +// fields are populated only if explicitly set. +// +// In other cases (aside from the nullable cases above), +// a proto3 scalar field is populated if it contains a non-zero value, and +// a repeated field is populated if it is non-empty. +func (x *fastReflection_Nested4B) Has(fd protoreflect.FieldDescriptor) bool { + switch fd.FullName() { + case "testpb.Nested4B.id": + return x.Id != int32(0) + case "testpb.Nested4B.age": + return x.Age != int32(0) + case "testpb.Nested4B.name": + return x.Name != "" + default: + if fd.IsExtension() { + panic(fmt.Errorf("proto3 declared messages do not support extensions: testpb.Nested4B")) + } + panic(fmt.Errorf("message testpb.Nested4B does not contain field %s", fd.FullName())) + } +} + +// Clear clears the field such that a subsequent Has call reports false. +// +// Clearing an extension field clears both the extension type and value +// associated with the given field number. +// +// Clear is a mutating operation and unsafe for concurrent use. +func (x *fastReflection_Nested4B) Clear(fd protoreflect.FieldDescriptor) { + switch fd.FullName() { + case "testpb.Nested4B.id": + x.Id = int32(0) + case "testpb.Nested4B.age": + x.Age = int32(0) + case "testpb.Nested4B.name": + x.Name = "" + default: + if fd.IsExtension() { + panic(fmt.Errorf("proto3 declared messages do not support extensions: testpb.Nested4B")) + } + panic(fmt.Errorf("message testpb.Nested4B does not contain field %s", fd.FullName())) + } +} + +// Get retrieves the value for a field. +// +// For unpopulated scalars, it returns the default value, where +// the default value of a bytes scalar is guaranteed to be a copy. +// For unpopulated composite types, it returns an empty, read-only view +// of the value; to obtain a mutable reference, use Mutable. +func (x *fastReflection_Nested4B) Get(descriptor protoreflect.FieldDescriptor) protoreflect.Value { + switch descriptor.FullName() { + case "testpb.Nested4B.id": + value := x.Id + return protoreflect.ValueOfInt32(value) + case "testpb.Nested4B.age": + value := x.Age + return protoreflect.ValueOfInt32(value) + case "testpb.Nested4B.name": + value := x.Name + return protoreflect.ValueOfString(value) + default: + if descriptor.IsExtension() { + panic(fmt.Errorf("proto3 declared messages do not support extensions: testpb.Nested4B")) + } + panic(fmt.Errorf("message testpb.Nested4B does not contain field %s", descriptor.FullName())) + } +} + +// Set stores the value for a field. +// +// For a field belonging to a oneof, it implicitly clears any other field +// that may be currently set within the same oneof. +// For extension fields, it implicitly stores the provided ExtensionType. +// When setting a composite type, it is unspecified whether the stored value +// aliases the source's memory in any way. If the composite value is an +// empty, read-only value, then it panics. +// +// Set is a mutating operation and unsafe for concurrent use. +func (x *fastReflection_Nested4B) Set(fd protoreflect.FieldDescriptor, value protoreflect.Value) { + switch fd.FullName() { + case "testpb.Nested4B.id": + x.Id = int32(value.Int()) + case "testpb.Nested4B.age": + x.Age = int32(value.Int()) + case "testpb.Nested4B.name": + x.Name = value.Interface().(string) + default: + if fd.IsExtension() { + panic(fmt.Errorf("proto3 declared messages do not support extensions: testpb.Nested4B")) + } + panic(fmt.Errorf("message testpb.Nested4B does not contain field %s", fd.FullName())) + } +} + +// Mutable returns a mutable reference to a composite type. +// +// If the field is unpopulated, it may allocate a composite value. +// For a field belonging to a oneof, it implicitly clears any other field +// that may be currently set within the same oneof. +// For extension fields, it implicitly stores the provided ExtensionType +// if not already stored. +// It panics if the field does not contain a composite type. +// +// Mutable is a mutating operation and unsafe for concurrent use. +func (x *fastReflection_Nested4B) Mutable(fd protoreflect.FieldDescriptor) protoreflect.Value { + switch fd.FullName() { + case "testpb.Nested4B.id": + panic(fmt.Errorf("field id of message testpb.Nested4B is not mutable")) + case "testpb.Nested4B.age": + panic(fmt.Errorf("field age of message testpb.Nested4B is not mutable")) + case "testpb.Nested4B.name": + panic(fmt.Errorf("field name of message testpb.Nested4B is not mutable")) + default: + if fd.IsExtension() { + panic(fmt.Errorf("proto3 declared messages do not support extensions: testpb.Nested4B")) + } + panic(fmt.Errorf("message testpb.Nested4B does not contain field %s", fd.FullName())) + } +} + +// NewField returns a new value that is assignable to the field +// for the given descriptor. For scalars, this returns the default value. +// For lists, maps, and messages, this returns a new, empty, mutable value. +func (x *fastReflection_Nested4B) NewField(fd protoreflect.FieldDescriptor) protoreflect.Value { + switch fd.FullName() { + case "testpb.Nested4B.id": + return protoreflect.ValueOfInt32(int32(0)) + case "testpb.Nested4B.age": + return protoreflect.ValueOfInt32(int32(0)) + case "testpb.Nested4B.name": + return protoreflect.ValueOfString("") + default: + if fd.IsExtension() { + panic(fmt.Errorf("proto3 declared messages do not support extensions: testpb.Nested4B")) + } + panic(fmt.Errorf("message testpb.Nested4B does not contain field %s", fd.FullName())) + } +} + +// WhichOneof reports which field within the oneof is populated, +// returning nil if none are populated. +// It panics if the oneof descriptor does not belong to this message. +func (x *fastReflection_Nested4B) WhichOneof(d protoreflect.OneofDescriptor) protoreflect.FieldDescriptor { + switch d.FullName() { + default: + panic(fmt.Errorf("%s is not a oneof field in testpb.Nested4B", d.FullName())) + } + panic("unreachable") +} + +// GetUnknown retrieves the entire list of unknown fields. +// The caller may only mutate the contents of the RawFields +// if the mutated bytes are stored back into the message with SetUnknown. +func (x *fastReflection_Nested4B) GetUnknown() protoreflect.RawFields { + return x.unknownFields +} + +// SetUnknown stores an entire list of unknown fields. +// The raw fields must be syntactically valid according to the wire format. +// An implementation may panic if this is not the case. +// Once stored, the caller must not mutate the content of the RawFields. +// An empty RawFields may be passed to clear the fields. +// +// SetUnknown is a mutating operation and unsafe for concurrent use. +func (x *fastReflection_Nested4B) SetUnknown(fields protoreflect.RawFields) { + x.unknownFields = fields +} + +// IsValid reports whether the message is valid. +// +// An invalid message is an empty, read-only value. +// +// An invalid message often corresponds to a nil pointer of the concrete +// message type, but the details are implementation dependent. +// Validity is not part of the protobuf data model, and may not +// be preserved in marshaling or other operations. +func (x *fastReflection_Nested4B) IsValid() bool { + return x != nil +} + +// ProtoMethods returns optional fastReflectionFeature-path implementations of various operations. +// This method may return nil. +// +// The returned methods type is identical to +// "google.golang.org/protobuf/runtime/protoiface".Methods. +// Consult the protoiface package documentation for details. +func (x *fastReflection_Nested4B) ProtoMethods() *protoiface.Methods { + size := func(input protoiface.SizeInput) protoiface.SizeOutput { + x := input.Message.Interface().(*Nested4B) + if x == nil { + return protoiface.SizeOutput{ + NoUnkeyedLiterals: input.NoUnkeyedLiterals, + Size: 0, + } + } + options := runtime.SizeInputToOptions(input) + _ = options + var n int + var l int + _ = l + if x.Id != 0 { + n += 1 + runtime.Sov(uint64(x.Id)) + } + if x.Age != 0 { + n += 1 + runtime.Sov(uint64(x.Age)) + } + l = len(x.Name) + if l > 0 { + n += 1 + l + runtime.Sov(uint64(l)) + } + if x.unknownFields != nil { + n += len(x.unknownFields) + } + return protoiface.SizeOutput{ + NoUnkeyedLiterals: input.NoUnkeyedLiterals, + Size: n, + } + } + + marshal := func(input protoiface.MarshalInput) (protoiface.MarshalOutput, error) { + x := input.Message.Interface().(*Nested4B) + if x == nil { + return protoiface.MarshalOutput{ + NoUnkeyedLiterals: input.NoUnkeyedLiterals, + Buf: input.Buf, + }, nil + } + options := runtime.MarshalInputToOptions(input) + _ = options + size := options.Size(x) + dAtA := make([]byte, size) + i := len(dAtA) + _ = i + var l int + _ = l + if x.unknownFields != nil { + i -= len(x.unknownFields) + copy(dAtA[i:], x.unknownFields) + } + if len(x.Name) > 0 { + i -= len(x.Name) + copy(dAtA[i:], x.Name) + i = runtime.EncodeVarint(dAtA, i, uint64(len(x.Name))) + i-- + dAtA[i] = 0x1a + } + if x.Age != 0 { + i = runtime.EncodeVarint(dAtA, i, uint64(x.Age)) + i-- + dAtA[i] = 0x10 + } + if x.Id != 0 { + i = runtime.EncodeVarint(dAtA, i, uint64(x.Id)) + i-- + dAtA[i] = 0x8 + } + if input.Buf != nil { + input.Buf = append(input.Buf, dAtA...) + } else { + input.Buf = dAtA + } + return protoiface.MarshalOutput{ + NoUnkeyedLiterals: input.NoUnkeyedLiterals, + Buf: input.Buf, + }, nil + } + unmarshal := func(input protoiface.UnmarshalInput) (protoiface.UnmarshalOutput, error) { + x := input.Message.Interface().(*Nested4B) + if x == nil { + return protoiface.UnmarshalOutput{ + NoUnkeyedLiterals: input.NoUnkeyedLiterals, + Flags: input.Flags, + }, nil + } + options := runtime.UnmarshalInputToOptions(input) + _ = options + dAtA := input.Buf + l := len(dAtA) + iNdEx := 0 + for iNdEx < l { + preIndex := iNdEx + var wire uint64 + for shift := uint(0); ; shift += 7 { + if shift >= 64 { + return protoiface.UnmarshalOutput{NoUnkeyedLiterals: input.NoUnkeyedLiterals, Flags: input.Flags}, runtime.ErrIntOverflow + } + if iNdEx >= l { + return protoiface.UnmarshalOutput{NoUnkeyedLiterals: input.NoUnkeyedLiterals, Flags: input.Flags}, io.ErrUnexpectedEOF + } + b := dAtA[iNdEx] + iNdEx++ + wire |= uint64(b&0x7F) << shift + if b < 0x80 { + break + } + } + fieldNum := int32(wire >> 3) + wireType := int(wire & 0x7) + if wireType == 4 { + return protoiface.UnmarshalOutput{NoUnkeyedLiterals: input.NoUnkeyedLiterals, Flags: input.Flags}, fmt.Errorf("proto: Nested4B: wiretype end group for non-group") + } + if fieldNum <= 0 { + return protoiface.UnmarshalOutput{NoUnkeyedLiterals: input.NoUnkeyedLiterals, Flags: input.Flags}, fmt.Errorf("proto: Nested4B: illegal tag %d (wire type %d)", fieldNum, wire) + } + switch fieldNum { + case 1: + if wireType != 0 { + return protoiface.UnmarshalOutput{NoUnkeyedLiterals: input.NoUnkeyedLiterals, Flags: input.Flags}, fmt.Errorf("proto: wrong wireType = %d for field Id", wireType) + } + x.Id = 0 + for shift := uint(0); ; shift += 7 { + if shift >= 64 { + return protoiface.UnmarshalOutput{NoUnkeyedLiterals: input.NoUnkeyedLiterals, Flags: input.Flags}, runtime.ErrIntOverflow + } + if iNdEx >= l { + return protoiface.UnmarshalOutput{NoUnkeyedLiterals: input.NoUnkeyedLiterals, Flags: input.Flags}, io.ErrUnexpectedEOF + } + b := dAtA[iNdEx] + iNdEx++ + x.Id |= int32(b&0x7F) << shift + if b < 0x80 { + break + } + } + case 2: + if wireType != 0 { + return protoiface.UnmarshalOutput{NoUnkeyedLiterals: input.NoUnkeyedLiterals, Flags: input.Flags}, fmt.Errorf("proto: wrong wireType = %d for field Age", wireType) + } + x.Age = 0 + for shift := uint(0); ; shift += 7 { + if shift >= 64 { + return protoiface.UnmarshalOutput{NoUnkeyedLiterals: input.NoUnkeyedLiterals, Flags: input.Flags}, runtime.ErrIntOverflow + } + if iNdEx >= l { + return protoiface.UnmarshalOutput{NoUnkeyedLiterals: input.NoUnkeyedLiterals, Flags: input.Flags}, io.ErrUnexpectedEOF + } + b := dAtA[iNdEx] + iNdEx++ + x.Age |= int32(b&0x7F) << shift + if b < 0x80 { + break + } + } + case 3: + if wireType != 2 { + return protoiface.UnmarshalOutput{NoUnkeyedLiterals: input.NoUnkeyedLiterals, Flags: input.Flags}, fmt.Errorf("proto: wrong wireType = %d for field Name", wireType) + } + var stringLen uint64 + for shift := uint(0); ; shift += 7 { + if shift >= 64 { + return protoiface.UnmarshalOutput{NoUnkeyedLiterals: input.NoUnkeyedLiterals, Flags: input.Flags}, runtime.ErrIntOverflow + } + if iNdEx >= l { + return protoiface.UnmarshalOutput{NoUnkeyedLiterals: input.NoUnkeyedLiterals, Flags: input.Flags}, io.ErrUnexpectedEOF + } + b := dAtA[iNdEx] + iNdEx++ + stringLen |= uint64(b&0x7F) << shift + if b < 0x80 { + break + } + } + intStringLen := int(stringLen) + if intStringLen < 0 { + return protoiface.UnmarshalOutput{NoUnkeyedLiterals: input.NoUnkeyedLiterals, Flags: input.Flags}, runtime.ErrInvalidLength + } + postIndex := iNdEx + intStringLen + if postIndex < 0 { + return protoiface.UnmarshalOutput{NoUnkeyedLiterals: input.NoUnkeyedLiterals, Flags: input.Flags}, runtime.ErrInvalidLength + } + if postIndex > l { + return protoiface.UnmarshalOutput{NoUnkeyedLiterals: input.NoUnkeyedLiterals, Flags: input.Flags}, io.ErrUnexpectedEOF + } + x.Name = string(dAtA[iNdEx:postIndex]) + iNdEx = postIndex + default: + iNdEx = preIndex + skippy, err := runtime.Skip(dAtA[iNdEx:]) + if err != nil { + return protoiface.UnmarshalOutput{NoUnkeyedLiterals: input.NoUnkeyedLiterals, Flags: input.Flags}, err + } + if (skippy < 0) || (iNdEx+skippy) < 0 { + return protoiface.UnmarshalOutput{NoUnkeyedLiterals: input.NoUnkeyedLiterals, Flags: input.Flags}, runtime.ErrInvalidLength + } + if (iNdEx + skippy) > l { + return protoiface.UnmarshalOutput{NoUnkeyedLiterals: input.NoUnkeyedLiterals, Flags: input.Flags}, io.ErrUnexpectedEOF + } + if !options.DiscardUnknown { + x.unknownFields = append(x.unknownFields, dAtA[iNdEx:iNdEx+skippy]...) + } + iNdEx += skippy + } + } + + if iNdEx > l { + return protoiface.UnmarshalOutput{NoUnkeyedLiterals: input.NoUnkeyedLiterals, Flags: input.Flags}, io.ErrUnexpectedEOF + } + return protoiface.UnmarshalOutput{NoUnkeyedLiterals: input.NoUnkeyedLiterals, Flags: input.Flags}, nil + } + return &protoiface.Methods{ + NoUnkeyedLiterals: struct{}{}, + Flags: protoiface.SupportMarshalDeterministic | protoiface.SupportUnmarshalDiscardUnknown, + Size: size, + Marshal: marshal, + Unmarshal: unmarshal, + Merge: nil, + CheckInitialized: nil, + } +} + +var _ protoreflect.List = (*_Nested3B_4_list)(nil) + +type _Nested3B_4_list struct { + list *[]*Nested4B +} + +func (x *_Nested3B_4_list) Len() int { + if x.list == nil { + return 0 + } + return len(*x.list) +} + +func (x *_Nested3B_4_list) Get(i int) protoreflect.Value { + return protoreflect.ValueOfMessage((*x.list)[i].ProtoReflect()) +} + +func (x *_Nested3B_4_list) Set(i int, value protoreflect.Value) { + valueUnwrapped := value.Message() + concreteValue := valueUnwrapped.Interface().(*Nested4B) + (*x.list)[i] = concreteValue +} + +func (x *_Nested3B_4_list) Append(value protoreflect.Value) { + valueUnwrapped := value.Message() + concreteValue := valueUnwrapped.Interface().(*Nested4B) + *x.list = append(*x.list, concreteValue) +} + +func (x *_Nested3B_4_list) AppendMutable() protoreflect.Value { + v := new(Nested4B) + *x.list = append(*x.list, v) + return protoreflect.ValueOfMessage(v.ProtoReflect()) +} + +func (x *_Nested3B_4_list) Truncate(n int) { + for i := n; i < len(*x.list); i++ { + (*x.list)[i] = nil + } + *x.list = (*x.list)[:n] +} + +func (x *_Nested3B_4_list) NewElement() protoreflect.Value { + v := new(Nested4B) + return protoreflect.ValueOfMessage(v.ProtoReflect()) +} + +func (x *_Nested3B_4_list) IsValid() bool { + return x.list != nil +} + +var ( + md_Nested3B protoreflect.MessageDescriptor + fd_Nested3B_id protoreflect.FieldDescriptor + fd_Nested3B_age protoreflect.FieldDescriptor + fd_Nested3B_name protoreflect.FieldDescriptor + fd_Nested3B_b4 protoreflect.FieldDescriptor +) + +func init() { + file_unknownproto_proto_init() + md_Nested3B = File_unknownproto_proto.Messages().ByName("Nested3B") + fd_Nested3B_id = md_Nested3B.Fields().ByName("id") + fd_Nested3B_age = md_Nested3B.Fields().ByName("age") + fd_Nested3B_name = md_Nested3B.Fields().ByName("name") + fd_Nested3B_b4 = md_Nested3B.Fields().ByName("b4") +} + +var _ protoreflect.Message = (*fastReflection_Nested3B)(nil) + +type fastReflection_Nested3B Nested3B + +func (x *Nested3B) ProtoReflect() protoreflect.Message { + return (*fastReflection_Nested3B)(x) +} + +func (x *Nested3B) slowProtoReflect() protoreflect.Message { + mi := &file_unknownproto_proto_msgTypes[7] + if protoimpl.UnsafeEnabled && x != nil { + ms := protoimpl.X.MessageStateOf(protoimpl.Pointer(x)) + if ms.LoadMessageInfo() == nil { + ms.StoreMessageInfo(mi) + } + return ms + } + return mi.MessageOf(x) +} + +var _fastReflection_Nested3B_messageType fastReflection_Nested3B_messageType +var _ protoreflect.MessageType = fastReflection_Nested3B_messageType{} + +type fastReflection_Nested3B_messageType struct{} + +func (x fastReflection_Nested3B_messageType) Zero() protoreflect.Message { + return (*fastReflection_Nested3B)(nil) +} +func (x fastReflection_Nested3B_messageType) New() protoreflect.Message { + return new(fastReflection_Nested3B) +} +func (x fastReflection_Nested3B_messageType) Descriptor() protoreflect.MessageDescriptor { + return md_Nested3B +} + +// Descriptor returns message descriptor, which contains only the protobuf +// type information for the message. +func (x *fastReflection_Nested3B) Descriptor() protoreflect.MessageDescriptor { + return md_Nested3B +} + +// Type returns the message type, which encapsulates both Go and protobuf +// type information. If the Go type information is not needed, +// it is recommended that the message descriptor be used instead. +func (x *fastReflection_Nested3B) Type() protoreflect.MessageType { + return _fastReflection_Nested3B_messageType +} + +// New returns a newly allocated and mutable empty message. +func (x *fastReflection_Nested3B) New() protoreflect.Message { + return new(fastReflection_Nested3B) +} + +// Interface unwraps the message reflection interface and +// returns the underlying ProtoMessage interface. +func (x *fastReflection_Nested3B) Interface() protoreflect.ProtoMessage { + return (*Nested3B)(x) +} + +// Range iterates over every populated field in an undefined order, +// calling f for each field descriptor and value encountered. +// Range returns immediately if f returns false. +// While iterating, mutating operations may only be performed +// on the current field descriptor. +func (x *fastReflection_Nested3B) Range(f func(protoreflect.FieldDescriptor, protoreflect.Value) bool) { + if x.Id != int32(0) { + value := protoreflect.ValueOfInt32(x.Id) + if !f(fd_Nested3B_id, value) { + return + } + } + if x.Age != int32(0) { + value := protoreflect.ValueOfInt32(x.Age) + if !f(fd_Nested3B_age, value) { + return + } + } + if x.Name != "" { + value := protoreflect.ValueOfString(x.Name) + if !f(fd_Nested3B_name, value) { + return + } + } + if len(x.B4) != 0 { + value := protoreflect.ValueOfList(&_Nested3B_4_list{list: &x.B4}) + if !f(fd_Nested3B_b4, value) { + return + } + } +} + +// Has reports whether a field is populated. +// +// Some fields have the property of nullability where it is possible to +// distinguish between the default value of a field and whether the field +// was explicitly populated with the default value. Singular message fields, +// member fields of a oneof, and proto2 scalar fields are nullable. Such +// fields are populated only if explicitly set. +// +// In other cases (aside from the nullable cases above), +// a proto3 scalar field is populated if it contains a non-zero value, and +// a repeated field is populated if it is non-empty. +func (x *fastReflection_Nested3B) Has(fd protoreflect.FieldDescriptor) bool { + switch fd.FullName() { + case "testpb.Nested3B.id": + return x.Id != int32(0) + case "testpb.Nested3B.age": + return x.Age != int32(0) + case "testpb.Nested3B.name": + return x.Name != "" + case "testpb.Nested3B.b4": + return len(x.B4) != 0 + default: + if fd.IsExtension() { + panic(fmt.Errorf("proto3 declared messages do not support extensions: testpb.Nested3B")) + } + panic(fmt.Errorf("message testpb.Nested3B does not contain field %s", fd.FullName())) + } +} + +// Clear clears the field such that a subsequent Has call reports false. +// +// Clearing an extension field clears both the extension type and value +// associated with the given field number. +// +// Clear is a mutating operation and unsafe for concurrent use. +func (x *fastReflection_Nested3B) Clear(fd protoreflect.FieldDescriptor) { + switch fd.FullName() { + case "testpb.Nested3B.id": + x.Id = int32(0) + case "testpb.Nested3B.age": + x.Age = int32(0) + case "testpb.Nested3B.name": + x.Name = "" + case "testpb.Nested3B.b4": + x.B4 = nil + default: + if fd.IsExtension() { + panic(fmt.Errorf("proto3 declared messages do not support extensions: testpb.Nested3B")) + } + panic(fmt.Errorf("message testpb.Nested3B does not contain field %s", fd.FullName())) + } +} + +// Get retrieves the value for a field. +// +// For unpopulated scalars, it returns the default value, where +// the default value of a bytes scalar is guaranteed to be a copy. +// For unpopulated composite types, it returns an empty, read-only view +// of the value; to obtain a mutable reference, use Mutable. +func (x *fastReflection_Nested3B) Get(descriptor protoreflect.FieldDescriptor) protoreflect.Value { + switch descriptor.FullName() { + case "testpb.Nested3B.id": + value := x.Id + return protoreflect.ValueOfInt32(value) + case "testpb.Nested3B.age": + value := x.Age + return protoreflect.ValueOfInt32(value) + case "testpb.Nested3B.name": + value := x.Name + return protoreflect.ValueOfString(value) + case "testpb.Nested3B.b4": + if len(x.B4) == 0 { + return protoreflect.ValueOfList(&_Nested3B_4_list{}) + } + listValue := &_Nested3B_4_list{list: &x.B4} + return protoreflect.ValueOfList(listValue) + default: + if descriptor.IsExtension() { + panic(fmt.Errorf("proto3 declared messages do not support extensions: testpb.Nested3B")) + } + panic(fmt.Errorf("message testpb.Nested3B does not contain field %s", descriptor.FullName())) + } +} + +// Set stores the value for a field. +// +// For a field belonging to a oneof, it implicitly clears any other field +// that may be currently set within the same oneof. +// For extension fields, it implicitly stores the provided ExtensionType. +// When setting a composite type, it is unspecified whether the stored value +// aliases the source's memory in any way. If the composite value is an +// empty, read-only value, then it panics. +// +// Set is a mutating operation and unsafe for concurrent use. +func (x *fastReflection_Nested3B) Set(fd protoreflect.FieldDescriptor, value protoreflect.Value) { + switch fd.FullName() { + case "testpb.Nested3B.id": + x.Id = int32(value.Int()) + case "testpb.Nested3B.age": + x.Age = int32(value.Int()) + case "testpb.Nested3B.name": + x.Name = value.Interface().(string) + case "testpb.Nested3B.b4": + lv := value.List() + clv := lv.(*_Nested3B_4_list) + x.B4 = *clv.list + default: + if fd.IsExtension() { + panic(fmt.Errorf("proto3 declared messages do not support extensions: testpb.Nested3B")) + } + panic(fmt.Errorf("message testpb.Nested3B does not contain field %s", fd.FullName())) + } +} + +// Mutable returns a mutable reference to a composite type. +// +// If the field is unpopulated, it may allocate a composite value. +// For a field belonging to a oneof, it implicitly clears any other field +// that may be currently set within the same oneof. +// For extension fields, it implicitly stores the provided ExtensionType +// if not already stored. +// It panics if the field does not contain a composite type. +// +// Mutable is a mutating operation and unsafe for concurrent use. +func (x *fastReflection_Nested3B) Mutable(fd protoreflect.FieldDescriptor) protoreflect.Value { + switch fd.FullName() { + case "testpb.Nested3B.b4": + if x.B4 == nil { + x.B4 = []*Nested4B{} + } + value := &_Nested3B_4_list{list: &x.B4} + return protoreflect.ValueOfList(value) + case "testpb.Nested3B.id": + panic(fmt.Errorf("field id of message testpb.Nested3B is not mutable")) + case "testpb.Nested3B.age": + panic(fmt.Errorf("field age of message testpb.Nested3B is not mutable")) + case "testpb.Nested3B.name": + panic(fmt.Errorf("field name of message testpb.Nested3B is not mutable")) + default: + if fd.IsExtension() { + panic(fmt.Errorf("proto3 declared messages do not support extensions: testpb.Nested3B")) + } + panic(fmt.Errorf("message testpb.Nested3B does not contain field %s", fd.FullName())) + } +} + +// NewField returns a new value that is assignable to the field +// for the given descriptor. For scalars, this returns the default value. +// For lists, maps, and messages, this returns a new, empty, mutable value. +func (x *fastReflection_Nested3B) NewField(fd protoreflect.FieldDescriptor) protoreflect.Value { + switch fd.FullName() { + case "testpb.Nested3B.id": + return protoreflect.ValueOfInt32(int32(0)) + case "testpb.Nested3B.age": + return protoreflect.ValueOfInt32(int32(0)) + case "testpb.Nested3B.name": + return protoreflect.ValueOfString("") + case "testpb.Nested3B.b4": + list := []*Nested4B{} + return protoreflect.ValueOfList(&_Nested3B_4_list{list: &list}) + default: + if fd.IsExtension() { + panic(fmt.Errorf("proto3 declared messages do not support extensions: testpb.Nested3B")) + } + panic(fmt.Errorf("message testpb.Nested3B does not contain field %s", fd.FullName())) + } +} + +// WhichOneof reports which field within the oneof is populated, +// returning nil if none are populated. +// It panics if the oneof descriptor does not belong to this message. +func (x *fastReflection_Nested3B) WhichOneof(d protoreflect.OneofDescriptor) protoreflect.FieldDescriptor { + switch d.FullName() { + default: + panic(fmt.Errorf("%s is not a oneof field in testpb.Nested3B", d.FullName())) + } + panic("unreachable") +} + +// GetUnknown retrieves the entire list of unknown fields. +// The caller may only mutate the contents of the RawFields +// if the mutated bytes are stored back into the message with SetUnknown. +func (x *fastReflection_Nested3B) GetUnknown() protoreflect.RawFields { + return x.unknownFields +} + +// SetUnknown stores an entire list of unknown fields. +// The raw fields must be syntactically valid according to the wire format. +// An implementation may panic if this is not the case. +// Once stored, the caller must not mutate the content of the RawFields. +// An empty RawFields may be passed to clear the fields. +// +// SetUnknown is a mutating operation and unsafe for concurrent use. +func (x *fastReflection_Nested3B) SetUnknown(fields protoreflect.RawFields) { + x.unknownFields = fields +} + +// IsValid reports whether the message is valid. +// +// An invalid message is an empty, read-only value. +// +// An invalid message often corresponds to a nil pointer of the concrete +// message type, but the details are implementation dependent. +// Validity is not part of the protobuf data model, and may not +// be preserved in marshaling or other operations. +func (x *fastReflection_Nested3B) IsValid() bool { + return x != nil +} + +// ProtoMethods returns optional fastReflectionFeature-path implementations of various operations. +// This method may return nil. +// +// The returned methods type is identical to +// "google.golang.org/protobuf/runtime/protoiface".Methods. +// Consult the protoiface package documentation for details. +func (x *fastReflection_Nested3B) ProtoMethods() *protoiface.Methods { + size := func(input protoiface.SizeInput) protoiface.SizeOutput { + x := input.Message.Interface().(*Nested3B) + if x == nil { + return protoiface.SizeOutput{ + NoUnkeyedLiterals: input.NoUnkeyedLiterals, + Size: 0, + } + } + options := runtime.SizeInputToOptions(input) + _ = options + var n int + var l int + _ = l + if x.Id != 0 { + n += 1 + runtime.Sov(uint64(x.Id)) + } + if x.Age != 0 { + n += 1 + runtime.Sov(uint64(x.Age)) + } + l = len(x.Name) + if l > 0 { + n += 1 + l + runtime.Sov(uint64(l)) + } + if len(x.B4) > 0 { + for _, e := range x.B4 { + l = options.Size(e) + n += 1 + l + runtime.Sov(uint64(l)) + } + } + if x.unknownFields != nil { + n += len(x.unknownFields) + } + return protoiface.SizeOutput{ + NoUnkeyedLiterals: input.NoUnkeyedLiterals, + Size: n, + } + } + + marshal := func(input protoiface.MarshalInput) (protoiface.MarshalOutput, error) { + x := input.Message.Interface().(*Nested3B) + if x == nil { + return protoiface.MarshalOutput{ + NoUnkeyedLiterals: input.NoUnkeyedLiterals, + Buf: input.Buf, + }, nil + } + options := runtime.MarshalInputToOptions(input) + _ = options + size := options.Size(x) + dAtA := make([]byte, size) + i := len(dAtA) + _ = i + var l int + _ = l + if x.unknownFields != nil { + i -= len(x.unknownFields) + copy(dAtA[i:], x.unknownFields) + } + if len(x.B4) > 0 { + for iNdEx := len(x.B4) - 1; iNdEx >= 0; iNdEx-- { + encoded, err := options.Marshal(x.B4[iNdEx]) + if err != nil { + return protoiface.MarshalOutput{ + NoUnkeyedLiterals: input.NoUnkeyedLiterals, + Buf: input.Buf, + }, err + } + i -= len(encoded) + copy(dAtA[i:], encoded) + i = runtime.EncodeVarint(dAtA, i, uint64(len(encoded))) + i-- + dAtA[i] = 0x22 + } + } + if len(x.Name) > 0 { + i -= len(x.Name) + copy(dAtA[i:], x.Name) + i = runtime.EncodeVarint(dAtA, i, uint64(len(x.Name))) + i-- + dAtA[i] = 0x1a + } + if x.Age != 0 { + i = runtime.EncodeVarint(dAtA, i, uint64(x.Age)) + i-- + dAtA[i] = 0x10 + } + if x.Id != 0 { + i = runtime.EncodeVarint(dAtA, i, uint64(x.Id)) + i-- + dAtA[i] = 0x8 + } + if input.Buf != nil { + input.Buf = append(input.Buf, dAtA...) + } else { + input.Buf = dAtA + } + return protoiface.MarshalOutput{ + NoUnkeyedLiterals: input.NoUnkeyedLiterals, + Buf: input.Buf, + }, nil + } + unmarshal := func(input protoiface.UnmarshalInput) (protoiface.UnmarshalOutput, error) { + x := input.Message.Interface().(*Nested3B) + if x == nil { + return protoiface.UnmarshalOutput{ + NoUnkeyedLiterals: input.NoUnkeyedLiterals, + Flags: input.Flags, + }, nil + } + options := runtime.UnmarshalInputToOptions(input) + _ = options + dAtA := input.Buf + l := len(dAtA) + iNdEx := 0 + for iNdEx < l { + preIndex := iNdEx + var wire uint64 + for shift := uint(0); ; shift += 7 { + if shift >= 64 { + return protoiface.UnmarshalOutput{NoUnkeyedLiterals: input.NoUnkeyedLiterals, Flags: input.Flags}, runtime.ErrIntOverflow + } + if iNdEx >= l { + return protoiface.UnmarshalOutput{NoUnkeyedLiterals: input.NoUnkeyedLiterals, Flags: input.Flags}, io.ErrUnexpectedEOF + } + b := dAtA[iNdEx] + iNdEx++ + wire |= uint64(b&0x7F) << shift + if b < 0x80 { + break + } + } + fieldNum := int32(wire >> 3) + wireType := int(wire & 0x7) + if wireType == 4 { + return protoiface.UnmarshalOutput{NoUnkeyedLiterals: input.NoUnkeyedLiterals, Flags: input.Flags}, fmt.Errorf("proto: Nested3B: wiretype end group for non-group") + } + if fieldNum <= 0 { + return protoiface.UnmarshalOutput{NoUnkeyedLiterals: input.NoUnkeyedLiterals, Flags: input.Flags}, fmt.Errorf("proto: Nested3B: illegal tag %d (wire type %d)", fieldNum, wire) + } + switch fieldNum { + case 1: + if wireType != 0 { + return protoiface.UnmarshalOutput{NoUnkeyedLiterals: input.NoUnkeyedLiterals, Flags: input.Flags}, fmt.Errorf("proto: wrong wireType = %d for field Id", wireType) + } + x.Id = 0 + for shift := uint(0); ; shift += 7 { + if shift >= 64 { + return protoiface.UnmarshalOutput{NoUnkeyedLiterals: input.NoUnkeyedLiterals, Flags: input.Flags}, runtime.ErrIntOverflow + } + if iNdEx >= l { + return protoiface.UnmarshalOutput{NoUnkeyedLiterals: input.NoUnkeyedLiterals, Flags: input.Flags}, io.ErrUnexpectedEOF + } + b := dAtA[iNdEx] + iNdEx++ + x.Id |= int32(b&0x7F) << shift + if b < 0x80 { + break + } + } + case 2: + if wireType != 0 { + return protoiface.UnmarshalOutput{NoUnkeyedLiterals: input.NoUnkeyedLiterals, Flags: input.Flags}, fmt.Errorf("proto: wrong wireType = %d for field Age", wireType) + } + x.Age = 0 + for shift := uint(0); ; shift += 7 { + if shift >= 64 { + return protoiface.UnmarshalOutput{NoUnkeyedLiterals: input.NoUnkeyedLiterals, Flags: input.Flags}, runtime.ErrIntOverflow + } + if iNdEx >= l { + return protoiface.UnmarshalOutput{NoUnkeyedLiterals: input.NoUnkeyedLiterals, Flags: input.Flags}, io.ErrUnexpectedEOF + } + b := dAtA[iNdEx] + iNdEx++ + x.Age |= int32(b&0x7F) << shift + if b < 0x80 { + break + } + } + case 3: + if wireType != 2 { + return protoiface.UnmarshalOutput{NoUnkeyedLiterals: input.NoUnkeyedLiterals, Flags: input.Flags}, fmt.Errorf("proto: wrong wireType = %d for field Name", wireType) + } + var stringLen uint64 + for shift := uint(0); ; shift += 7 { + if shift >= 64 { + return protoiface.UnmarshalOutput{NoUnkeyedLiterals: input.NoUnkeyedLiterals, Flags: input.Flags}, runtime.ErrIntOverflow + } + if iNdEx >= l { + return protoiface.UnmarshalOutput{NoUnkeyedLiterals: input.NoUnkeyedLiterals, Flags: input.Flags}, io.ErrUnexpectedEOF + } + b := dAtA[iNdEx] + iNdEx++ + stringLen |= uint64(b&0x7F) << shift + if b < 0x80 { + break + } + } + intStringLen := int(stringLen) + if intStringLen < 0 { + return protoiface.UnmarshalOutput{NoUnkeyedLiterals: input.NoUnkeyedLiterals, Flags: input.Flags}, runtime.ErrInvalidLength + } + postIndex := iNdEx + intStringLen + if postIndex < 0 { + return protoiface.UnmarshalOutput{NoUnkeyedLiterals: input.NoUnkeyedLiterals, Flags: input.Flags}, runtime.ErrInvalidLength + } + if postIndex > l { + return protoiface.UnmarshalOutput{NoUnkeyedLiterals: input.NoUnkeyedLiterals, Flags: input.Flags}, io.ErrUnexpectedEOF + } + x.Name = string(dAtA[iNdEx:postIndex]) + iNdEx = postIndex + case 4: + if wireType != 2 { + return protoiface.UnmarshalOutput{NoUnkeyedLiterals: input.NoUnkeyedLiterals, Flags: input.Flags}, fmt.Errorf("proto: wrong wireType = %d for field B4", wireType) + } + var msglen int + for shift := uint(0); ; shift += 7 { + if shift >= 64 { + return protoiface.UnmarshalOutput{NoUnkeyedLiterals: input.NoUnkeyedLiterals, Flags: input.Flags}, runtime.ErrIntOverflow + } + if iNdEx >= l { + return protoiface.UnmarshalOutput{NoUnkeyedLiterals: input.NoUnkeyedLiterals, Flags: input.Flags}, io.ErrUnexpectedEOF + } + b := dAtA[iNdEx] + iNdEx++ + msglen |= int(b&0x7F) << shift + if b < 0x80 { + break + } + } + if msglen < 0 { + return protoiface.UnmarshalOutput{NoUnkeyedLiterals: input.NoUnkeyedLiterals, Flags: input.Flags}, runtime.ErrInvalidLength + } + postIndex := iNdEx + msglen + if postIndex < 0 { + return protoiface.UnmarshalOutput{NoUnkeyedLiterals: input.NoUnkeyedLiterals, Flags: input.Flags}, runtime.ErrInvalidLength + } + if postIndex > l { + return protoiface.UnmarshalOutput{NoUnkeyedLiterals: input.NoUnkeyedLiterals, Flags: input.Flags}, io.ErrUnexpectedEOF + } + x.B4 = append(x.B4, &Nested4B{}) + if err := options.Unmarshal(dAtA[iNdEx:postIndex], x.B4[len(x.B4)-1]); err != nil { + return protoiface.UnmarshalOutput{NoUnkeyedLiterals: input.NoUnkeyedLiterals, Flags: input.Flags}, err + } + iNdEx = postIndex + default: + iNdEx = preIndex + skippy, err := runtime.Skip(dAtA[iNdEx:]) + if err != nil { + return protoiface.UnmarshalOutput{NoUnkeyedLiterals: input.NoUnkeyedLiterals, Flags: input.Flags}, err + } + if (skippy < 0) || (iNdEx+skippy) < 0 { + return protoiface.UnmarshalOutput{NoUnkeyedLiterals: input.NoUnkeyedLiterals, Flags: input.Flags}, runtime.ErrInvalidLength + } + if (iNdEx + skippy) > l { + return protoiface.UnmarshalOutput{NoUnkeyedLiterals: input.NoUnkeyedLiterals, Flags: input.Flags}, io.ErrUnexpectedEOF + } + if !options.DiscardUnknown { + x.unknownFields = append(x.unknownFields, dAtA[iNdEx:iNdEx+skippy]...) + } + iNdEx += skippy + } + } + + if iNdEx > l { + return protoiface.UnmarshalOutput{NoUnkeyedLiterals: input.NoUnkeyedLiterals, Flags: input.Flags}, io.ErrUnexpectedEOF + } + return protoiface.UnmarshalOutput{NoUnkeyedLiterals: input.NoUnkeyedLiterals, Flags: input.Flags}, nil + } + return &protoiface.Methods{ + NoUnkeyedLiterals: struct{}{}, + Flags: protoiface.SupportMarshalDeterministic | protoiface.SupportUnmarshalDiscardUnknown, + Size: size, + Marshal: marshal, + Unmarshal: unmarshal, + Merge: nil, + CheckInitialized: nil, + } +} + +var ( + md_Nested2B protoreflect.MessageDescriptor + fd_Nested2B_id protoreflect.FieldDescriptor + fd_Nested2B_fee protoreflect.FieldDescriptor + fd_Nested2B_nested protoreflect.FieldDescriptor + fd_Nested2B_route protoreflect.FieldDescriptor +) + +func init() { + file_unknownproto_proto_init() + md_Nested2B = File_unknownproto_proto.Messages().ByName("Nested2B") + fd_Nested2B_id = md_Nested2B.Fields().ByName("id") + fd_Nested2B_fee = md_Nested2B.Fields().ByName("fee") + fd_Nested2B_nested = md_Nested2B.Fields().ByName("nested") + fd_Nested2B_route = md_Nested2B.Fields().ByName("route") +} + +var _ protoreflect.Message = (*fastReflection_Nested2B)(nil) + +type fastReflection_Nested2B Nested2B + +func (x *Nested2B) ProtoReflect() protoreflect.Message { + return (*fastReflection_Nested2B)(x) +} + +func (x *Nested2B) slowProtoReflect() protoreflect.Message { + mi := &file_unknownproto_proto_msgTypes[8] + if protoimpl.UnsafeEnabled && x != nil { + ms := protoimpl.X.MessageStateOf(protoimpl.Pointer(x)) + if ms.LoadMessageInfo() == nil { + ms.StoreMessageInfo(mi) + } + return ms + } + return mi.MessageOf(x) +} + +var _fastReflection_Nested2B_messageType fastReflection_Nested2B_messageType +var _ protoreflect.MessageType = fastReflection_Nested2B_messageType{} + +type fastReflection_Nested2B_messageType struct{} + +func (x fastReflection_Nested2B_messageType) Zero() protoreflect.Message { + return (*fastReflection_Nested2B)(nil) +} +func (x fastReflection_Nested2B_messageType) New() protoreflect.Message { + return new(fastReflection_Nested2B) +} +func (x fastReflection_Nested2B_messageType) Descriptor() protoreflect.MessageDescriptor { + return md_Nested2B +} + +// Descriptor returns message descriptor, which contains only the protobuf +// type information for the message. +func (x *fastReflection_Nested2B) Descriptor() protoreflect.MessageDescriptor { + return md_Nested2B +} + +// Type returns the message type, which encapsulates both Go and protobuf +// type information. If the Go type information is not needed, +// it is recommended that the message descriptor be used instead. +func (x *fastReflection_Nested2B) Type() protoreflect.MessageType { + return _fastReflection_Nested2B_messageType +} + +// New returns a newly allocated and mutable empty message. +func (x *fastReflection_Nested2B) New() protoreflect.Message { + return new(fastReflection_Nested2B) +} + +// Interface unwraps the message reflection interface and +// returns the underlying ProtoMessage interface. +func (x *fastReflection_Nested2B) Interface() protoreflect.ProtoMessage { + return (*Nested2B)(x) +} + +// Range iterates over every populated field in an undefined order, +// calling f for each field descriptor and value encountered. +// Range returns immediately if f returns false. +// While iterating, mutating operations may only be performed +// on the current field descriptor. +func (x *fastReflection_Nested2B) Range(f func(protoreflect.FieldDescriptor, protoreflect.Value) bool) { + if x.Id != int32(0) { + value := protoreflect.ValueOfInt32(x.Id) + if !f(fd_Nested2B_id, value) { + return + } + } + if x.Fee != float64(0) || math.Signbit(x.Fee) { + value := protoreflect.ValueOfFloat64(x.Fee) + if !f(fd_Nested2B_fee, value) { + return + } + } + if x.Nested != nil { + value := protoreflect.ValueOfMessage(x.Nested.ProtoReflect()) + if !f(fd_Nested2B_nested, value) { + return + } + } + if x.Route != "" { + value := protoreflect.ValueOfString(x.Route) + if !f(fd_Nested2B_route, value) { + return + } + } +} + +// Has reports whether a field is populated. +// +// Some fields have the property of nullability where it is possible to +// distinguish between the default value of a field and whether the field +// was explicitly populated with the default value. Singular message fields, +// member fields of a oneof, and proto2 scalar fields are nullable. Such +// fields are populated only if explicitly set. +// +// In other cases (aside from the nullable cases above), +// a proto3 scalar field is populated if it contains a non-zero value, and +// a repeated field is populated if it is non-empty. +func (x *fastReflection_Nested2B) Has(fd protoreflect.FieldDescriptor) bool { + switch fd.FullName() { + case "testpb.Nested2B.id": + return x.Id != int32(0) + case "testpb.Nested2B.fee": + return x.Fee != float64(0) || math.Signbit(x.Fee) + case "testpb.Nested2B.nested": + return x.Nested != nil + case "testpb.Nested2B.route": + return x.Route != "" + default: + if fd.IsExtension() { + panic(fmt.Errorf("proto3 declared messages do not support extensions: testpb.Nested2B")) + } + panic(fmt.Errorf("message testpb.Nested2B does not contain field %s", fd.FullName())) + } +} + +// Clear clears the field such that a subsequent Has call reports false. +// +// Clearing an extension field clears both the extension type and value +// associated with the given field number. +// +// Clear is a mutating operation and unsafe for concurrent use. +func (x *fastReflection_Nested2B) Clear(fd protoreflect.FieldDescriptor) { + switch fd.FullName() { + case "testpb.Nested2B.id": + x.Id = int32(0) + case "testpb.Nested2B.fee": + x.Fee = float64(0) + case "testpb.Nested2B.nested": + x.Nested = nil + case "testpb.Nested2B.route": + x.Route = "" + default: + if fd.IsExtension() { + panic(fmt.Errorf("proto3 declared messages do not support extensions: testpb.Nested2B")) + } + panic(fmt.Errorf("message testpb.Nested2B does not contain field %s", fd.FullName())) + } +} + +// Get retrieves the value for a field. +// +// For unpopulated scalars, it returns the default value, where +// the default value of a bytes scalar is guaranteed to be a copy. +// For unpopulated composite types, it returns an empty, read-only view +// of the value; to obtain a mutable reference, use Mutable. +func (x *fastReflection_Nested2B) Get(descriptor protoreflect.FieldDescriptor) protoreflect.Value { + switch descriptor.FullName() { + case "testpb.Nested2B.id": + value := x.Id + return protoreflect.ValueOfInt32(value) + case "testpb.Nested2B.fee": + value := x.Fee + return protoreflect.ValueOfFloat64(value) + case "testpb.Nested2B.nested": + value := x.Nested + return protoreflect.ValueOfMessage(value.ProtoReflect()) + case "testpb.Nested2B.route": + value := x.Route + return protoreflect.ValueOfString(value) + default: + if descriptor.IsExtension() { + panic(fmt.Errorf("proto3 declared messages do not support extensions: testpb.Nested2B")) + } + panic(fmt.Errorf("message testpb.Nested2B does not contain field %s", descriptor.FullName())) + } +} + +// Set stores the value for a field. +// +// For a field belonging to a oneof, it implicitly clears any other field +// that may be currently set within the same oneof. +// For extension fields, it implicitly stores the provided ExtensionType. +// When setting a composite type, it is unspecified whether the stored value +// aliases the source's memory in any way. If the composite value is an +// empty, read-only value, then it panics. +// +// Set is a mutating operation and unsafe for concurrent use. +func (x *fastReflection_Nested2B) Set(fd protoreflect.FieldDescriptor, value protoreflect.Value) { + switch fd.FullName() { + case "testpb.Nested2B.id": + x.Id = int32(value.Int()) + case "testpb.Nested2B.fee": + x.Fee = value.Float() + case "testpb.Nested2B.nested": + x.Nested = value.Message().Interface().(*Nested3B) + case "testpb.Nested2B.route": + x.Route = value.Interface().(string) + default: + if fd.IsExtension() { + panic(fmt.Errorf("proto3 declared messages do not support extensions: testpb.Nested2B")) + } + panic(fmt.Errorf("message testpb.Nested2B does not contain field %s", fd.FullName())) + } +} + +// Mutable returns a mutable reference to a composite type. +// +// If the field is unpopulated, it may allocate a composite value. +// For a field belonging to a oneof, it implicitly clears any other field +// that may be currently set within the same oneof. +// For extension fields, it implicitly stores the provided ExtensionType +// if not already stored. +// It panics if the field does not contain a composite type. +// +// Mutable is a mutating operation and unsafe for concurrent use. +func (x *fastReflection_Nested2B) Mutable(fd protoreflect.FieldDescriptor) protoreflect.Value { + switch fd.FullName() { + case "testpb.Nested2B.nested": + if x.Nested == nil { + x.Nested = new(Nested3B) + } + return protoreflect.ValueOfMessage(x.Nested.ProtoReflect()) + case "testpb.Nested2B.id": + panic(fmt.Errorf("field id of message testpb.Nested2B is not mutable")) + case "testpb.Nested2B.fee": + panic(fmt.Errorf("field fee of message testpb.Nested2B is not mutable")) + case "testpb.Nested2B.route": + panic(fmt.Errorf("field route of message testpb.Nested2B is not mutable")) + default: + if fd.IsExtension() { + panic(fmt.Errorf("proto3 declared messages do not support extensions: testpb.Nested2B")) + } + panic(fmt.Errorf("message testpb.Nested2B does not contain field %s", fd.FullName())) + } +} + +// NewField returns a new value that is assignable to the field +// for the given descriptor. For scalars, this returns the default value. +// For lists, maps, and messages, this returns a new, empty, mutable value. +func (x *fastReflection_Nested2B) NewField(fd protoreflect.FieldDescriptor) protoreflect.Value { + switch fd.FullName() { + case "testpb.Nested2B.id": + return protoreflect.ValueOfInt32(int32(0)) + case "testpb.Nested2B.fee": + return protoreflect.ValueOfFloat64(float64(0)) + case "testpb.Nested2B.nested": + m := new(Nested3B) + return protoreflect.ValueOfMessage(m.ProtoReflect()) + case "testpb.Nested2B.route": + return protoreflect.ValueOfString("") + default: + if fd.IsExtension() { + panic(fmt.Errorf("proto3 declared messages do not support extensions: testpb.Nested2B")) + } + panic(fmt.Errorf("message testpb.Nested2B does not contain field %s", fd.FullName())) + } +} + +// WhichOneof reports which field within the oneof is populated, +// returning nil if none are populated. +// It panics if the oneof descriptor does not belong to this message. +func (x *fastReflection_Nested2B) WhichOneof(d protoreflect.OneofDescriptor) protoreflect.FieldDescriptor { + switch d.FullName() { + default: + panic(fmt.Errorf("%s is not a oneof field in testpb.Nested2B", d.FullName())) + } + panic("unreachable") +} + +// GetUnknown retrieves the entire list of unknown fields. +// The caller may only mutate the contents of the RawFields +// if the mutated bytes are stored back into the message with SetUnknown. +func (x *fastReflection_Nested2B) GetUnknown() protoreflect.RawFields { + return x.unknownFields +} + +// SetUnknown stores an entire list of unknown fields. +// The raw fields must be syntactically valid according to the wire format. +// An implementation may panic if this is not the case. +// Once stored, the caller must not mutate the content of the RawFields. +// An empty RawFields may be passed to clear the fields. +// +// SetUnknown is a mutating operation and unsafe for concurrent use. +func (x *fastReflection_Nested2B) SetUnknown(fields protoreflect.RawFields) { + x.unknownFields = fields +} + +// IsValid reports whether the message is valid. +// +// An invalid message is an empty, read-only value. +// +// An invalid message often corresponds to a nil pointer of the concrete +// message type, but the details are implementation dependent. +// Validity is not part of the protobuf data model, and may not +// be preserved in marshaling or other operations. +func (x *fastReflection_Nested2B) IsValid() bool { + return x != nil +} + +// ProtoMethods returns optional fastReflectionFeature-path implementations of various operations. +// This method may return nil. +// +// The returned methods type is identical to +// "google.golang.org/protobuf/runtime/protoiface".Methods. +// Consult the protoiface package documentation for details. +func (x *fastReflection_Nested2B) ProtoMethods() *protoiface.Methods { + size := func(input protoiface.SizeInput) protoiface.SizeOutput { + x := input.Message.Interface().(*Nested2B) + if x == nil { + return protoiface.SizeOutput{ + NoUnkeyedLiterals: input.NoUnkeyedLiterals, + Size: 0, + } + } + options := runtime.SizeInputToOptions(input) + _ = options + var n int + var l int + _ = l + if x.Id != 0 { + n += 1 + runtime.Sov(uint64(x.Id)) + } + if x.Fee != 0 || math.Signbit(x.Fee) { + n += 9 + } + if x.Nested != nil { + l = options.Size(x.Nested) + n += 1 + l + runtime.Sov(uint64(l)) + } + l = len(x.Route) + if l > 0 { + n += 1 + l + runtime.Sov(uint64(l)) + } + if x.unknownFields != nil { + n += len(x.unknownFields) + } + return protoiface.SizeOutput{ + NoUnkeyedLiterals: input.NoUnkeyedLiterals, + Size: n, + } + } + + marshal := func(input protoiface.MarshalInput) (protoiface.MarshalOutput, error) { + x := input.Message.Interface().(*Nested2B) + if x == nil { + return protoiface.MarshalOutput{ + NoUnkeyedLiterals: input.NoUnkeyedLiterals, + Buf: input.Buf, + }, nil + } + options := runtime.MarshalInputToOptions(input) + _ = options + size := options.Size(x) + dAtA := make([]byte, size) + i := len(dAtA) + _ = i + var l int + _ = l + if x.unknownFields != nil { + i -= len(x.unknownFields) + copy(dAtA[i:], x.unknownFields) + } + if len(x.Route) > 0 { + i -= len(x.Route) + copy(dAtA[i:], x.Route) + i = runtime.EncodeVarint(dAtA, i, uint64(len(x.Route))) + i-- + dAtA[i] = 0x22 + } + if x.Nested != nil { + encoded, err := options.Marshal(x.Nested) + if err != nil { + return protoiface.MarshalOutput{ + NoUnkeyedLiterals: input.NoUnkeyedLiterals, + Buf: input.Buf, + }, err + } + i -= len(encoded) + copy(dAtA[i:], encoded) + i = runtime.EncodeVarint(dAtA, i, uint64(len(encoded))) + i-- + dAtA[i] = 0x1a + } + if x.Fee != 0 || math.Signbit(x.Fee) { + i -= 8 + binary.LittleEndian.PutUint64(dAtA[i:], uint64(math.Float64bits(float64(x.Fee)))) + i-- + dAtA[i] = 0x11 + } + if x.Id != 0 { + i = runtime.EncodeVarint(dAtA, i, uint64(x.Id)) + i-- + dAtA[i] = 0x8 + } + if input.Buf != nil { + input.Buf = append(input.Buf, dAtA...) + } else { + input.Buf = dAtA + } + return protoiface.MarshalOutput{ + NoUnkeyedLiterals: input.NoUnkeyedLiterals, + Buf: input.Buf, + }, nil + } + unmarshal := func(input protoiface.UnmarshalInput) (protoiface.UnmarshalOutput, error) { + x := input.Message.Interface().(*Nested2B) + if x == nil { + return protoiface.UnmarshalOutput{ + NoUnkeyedLiterals: input.NoUnkeyedLiterals, + Flags: input.Flags, + }, nil + } + options := runtime.UnmarshalInputToOptions(input) + _ = options + dAtA := input.Buf + l := len(dAtA) + iNdEx := 0 + for iNdEx < l { + preIndex := iNdEx + var wire uint64 + for shift := uint(0); ; shift += 7 { + if shift >= 64 { + return protoiface.UnmarshalOutput{NoUnkeyedLiterals: input.NoUnkeyedLiterals, Flags: input.Flags}, runtime.ErrIntOverflow + } + if iNdEx >= l { + return protoiface.UnmarshalOutput{NoUnkeyedLiterals: input.NoUnkeyedLiterals, Flags: input.Flags}, io.ErrUnexpectedEOF + } + b := dAtA[iNdEx] + iNdEx++ + wire |= uint64(b&0x7F) << shift + if b < 0x80 { + break + } + } + fieldNum := int32(wire >> 3) + wireType := int(wire & 0x7) + if wireType == 4 { + return protoiface.UnmarshalOutput{NoUnkeyedLiterals: input.NoUnkeyedLiterals, Flags: input.Flags}, fmt.Errorf("proto: Nested2B: wiretype end group for non-group") + } + if fieldNum <= 0 { + return protoiface.UnmarshalOutput{NoUnkeyedLiterals: input.NoUnkeyedLiterals, Flags: input.Flags}, fmt.Errorf("proto: Nested2B: illegal tag %d (wire type %d)", fieldNum, wire) + } + switch fieldNum { + case 1: + if wireType != 0 { + return protoiface.UnmarshalOutput{NoUnkeyedLiterals: input.NoUnkeyedLiterals, Flags: input.Flags}, fmt.Errorf("proto: wrong wireType = %d for field Id", wireType) + } + x.Id = 0 + for shift := uint(0); ; shift += 7 { + if shift >= 64 { + return protoiface.UnmarshalOutput{NoUnkeyedLiterals: input.NoUnkeyedLiterals, Flags: input.Flags}, runtime.ErrIntOverflow + } + if iNdEx >= l { + return protoiface.UnmarshalOutput{NoUnkeyedLiterals: input.NoUnkeyedLiterals, Flags: input.Flags}, io.ErrUnexpectedEOF + } + b := dAtA[iNdEx] + iNdEx++ + x.Id |= int32(b&0x7F) << shift + if b < 0x80 { + break + } + } + case 2: + if wireType != 1 { + return protoiface.UnmarshalOutput{NoUnkeyedLiterals: input.NoUnkeyedLiterals, Flags: input.Flags}, fmt.Errorf("proto: wrong wireType = %d for field Fee", wireType) + } + var v uint64 + if (iNdEx + 8) > l { + return protoiface.UnmarshalOutput{NoUnkeyedLiterals: input.NoUnkeyedLiterals, Flags: input.Flags}, io.ErrUnexpectedEOF + } + v = uint64(binary.LittleEndian.Uint64(dAtA[iNdEx:])) + iNdEx += 8 + x.Fee = float64(math.Float64frombits(v)) + case 3: + if wireType != 2 { + return protoiface.UnmarshalOutput{NoUnkeyedLiterals: input.NoUnkeyedLiterals, Flags: input.Flags}, fmt.Errorf("proto: wrong wireType = %d for field Nested", wireType) + } + var msglen int + for shift := uint(0); ; shift += 7 { + if shift >= 64 { + return protoiface.UnmarshalOutput{NoUnkeyedLiterals: input.NoUnkeyedLiterals, Flags: input.Flags}, runtime.ErrIntOverflow + } + if iNdEx >= l { + return protoiface.UnmarshalOutput{NoUnkeyedLiterals: input.NoUnkeyedLiterals, Flags: input.Flags}, io.ErrUnexpectedEOF + } + b := dAtA[iNdEx] + iNdEx++ + msglen |= int(b&0x7F) << shift + if b < 0x80 { + break + } + } + if msglen < 0 { + return protoiface.UnmarshalOutput{NoUnkeyedLiterals: input.NoUnkeyedLiterals, Flags: input.Flags}, runtime.ErrInvalidLength + } + postIndex := iNdEx + msglen + if postIndex < 0 { + return protoiface.UnmarshalOutput{NoUnkeyedLiterals: input.NoUnkeyedLiterals, Flags: input.Flags}, runtime.ErrInvalidLength + } + if postIndex > l { + return protoiface.UnmarshalOutput{NoUnkeyedLiterals: input.NoUnkeyedLiterals, Flags: input.Flags}, io.ErrUnexpectedEOF + } + if x.Nested == nil { + x.Nested = &Nested3B{} + } + if err := options.Unmarshal(dAtA[iNdEx:postIndex], x.Nested); err != nil { + return protoiface.UnmarshalOutput{NoUnkeyedLiterals: input.NoUnkeyedLiterals, Flags: input.Flags}, err + } + iNdEx = postIndex + case 4: + if wireType != 2 { + return protoiface.UnmarshalOutput{NoUnkeyedLiterals: input.NoUnkeyedLiterals, Flags: input.Flags}, fmt.Errorf("proto: wrong wireType = %d for field Route", wireType) + } + var stringLen uint64 + for shift := uint(0); ; shift += 7 { + if shift >= 64 { + return protoiface.UnmarshalOutput{NoUnkeyedLiterals: input.NoUnkeyedLiterals, Flags: input.Flags}, runtime.ErrIntOverflow + } + if iNdEx >= l { + return protoiface.UnmarshalOutput{NoUnkeyedLiterals: input.NoUnkeyedLiterals, Flags: input.Flags}, io.ErrUnexpectedEOF + } + b := dAtA[iNdEx] + iNdEx++ + stringLen |= uint64(b&0x7F) << shift + if b < 0x80 { + break + } + } + intStringLen := int(stringLen) + if intStringLen < 0 { + return protoiface.UnmarshalOutput{NoUnkeyedLiterals: input.NoUnkeyedLiterals, Flags: input.Flags}, runtime.ErrInvalidLength + } + postIndex := iNdEx + intStringLen + if postIndex < 0 { + return protoiface.UnmarshalOutput{NoUnkeyedLiterals: input.NoUnkeyedLiterals, Flags: input.Flags}, runtime.ErrInvalidLength + } + if postIndex > l { + return protoiface.UnmarshalOutput{NoUnkeyedLiterals: input.NoUnkeyedLiterals, Flags: input.Flags}, io.ErrUnexpectedEOF + } + x.Route = string(dAtA[iNdEx:postIndex]) + iNdEx = postIndex + default: + iNdEx = preIndex + skippy, err := runtime.Skip(dAtA[iNdEx:]) + if err != nil { + return protoiface.UnmarshalOutput{NoUnkeyedLiterals: input.NoUnkeyedLiterals, Flags: input.Flags}, err + } + if (skippy < 0) || (iNdEx+skippy) < 0 { + return protoiface.UnmarshalOutput{NoUnkeyedLiterals: input.NoUnkeyedLiterals, Flags: input.Flags}, runtime.ErrInvalidLength + } + if (iNdEx + skippy) > l { + return protoiface.UnmarshalOutput{NoUnkeyedLiterals: input.NoUnkeyedLiterals, Flags: input.Flags}, io.ErrUnexpectedEOF + } + if !options.DiscardUnknown { + x.unknownFields = append(x.unknownFields, dAtA[iNdEx:iNdEx+skippy]...) + } + iNdEx += skippy + } + } + + if iNdEx > l { + return protoiface.UnmarshalOutput{NoUnkeyedLiterals: input.NoUnkeyedLiterals, Flags: input.Flags}, io.ErrUnexpectedEOF + } + return protoiface.UnmarshalOutput{NoUnkeyedLiterals: input.NoUnkeyedLiterals, Flags: input.Flags}, nil + } + return &protoiface.Methods{ + NoUnkeyedLiterals: struct{}{}, + Flags: protoiface.SupportMarshalDeterministic | protoiface.SupportUnmarshalDiscardUnknown, + Size: size, + Marshal: marshal, + Unmarshal: unmarshal, + Merge: nil, + CheckInitialized: nil, + } +} + +var ( + md_Nested1B protoreflect.MessageDescriptor + fd_Nested1B_id protoreflect.FieldDescriptor + fd_Nested1B_nested protoreflect.FieldDescriptor + fd_Nested1B_age protoreflect.FieldDescriptor +) + +func init() { + file_unknownproto_proto_init() + md_Nested1B = File_unknownproto_proto.Messages().ByName("Nested1B") + fd_Nested1B_id = md_Nested1B.Fields().ByName("id") + fd_Nested1B_nested = md_Nested1B.Fields().ByName("nested") + fd_Nested1B_age = md_Nested1B.Fields().ByName("age") +} + +var _ protoreflect.Message = (*fastReflection_Nested1B)(nil) + +type fastReflection_Nested1B Nested1B + +func (x *Nested1B) ProtoReflect() protoreflect.Message { + return (*fastReflection_Nested1B)(x) +} + +func (x *Nested1B) slowProtoReflect() protoreflect.Message { + mi := &file_unknownproto_proto_msgTypes[9] + if protoimpl.UnsafeEnabled && x != nil { + ms := protoimpl.X.MessageStateOf(protoimpl.Pointer(x)) + if ms.LoadMessageInfo() == nil { + ms.StoreMessageInfo(mi) + } + return ms + } + return mi.MessageOf(x) +} + +var _fastReflection_Nested1B_messageType fastReflection_Nested1B_messageType +var _ protoreflect.MessageType = fastReflection_Nested1B_messageType{} + +type fastReflection_Nested1B_messageType struct{} + +func (x fastReflection_Nested1B_messageType) Zero() protoreflect.Message { + return (*fastReflection_Nested1B)(nil) +} +func (x fastReflection_Nested1B_messageType) New() protoreflect.Message { + return new(fastReflection_Nested1B) +} +func (x fastReflection_Nested1B_messageType) Descriptor() protoreflect.MessageDescriptor { + return md_Nested1B +} + +// Descriptor returns message descriptor, which contains only the protobuf +// type information for the message. +func (x *fastReflection_Nested1B) Descriptor() protoreflect.MessageDescriptor { + return md_Nested1B +} + +// Type returns the message type, which encapsulates both Go and protobuf +// type information. If the Go type information is not needed, +// it is recommended that the message descriptor be used instead. +func (x *fastReflection_Nested1B) Type() protoreflect.MessageType { + return _fastReflection_Nested1B_messageType +} + +// New returns a newly allocated and mutable empty message. +func (x *fastReflection_Nested1B) New() protoreflect.Message { + return new(fastReflection_Nested1B) +} + +// Interface unwraps the message reflection interface and +// returns the underlying ProtoMessage interface. +func (x *fastReflection_Nested1B) Interface() protoreflect.ProtoMessage { + return (*Nested1B)(x) +} + +// Range iterates over every populated field in an undefined order, +// calling f for each field descriptor and value encountered. +// Range returns immediately if f returns false. +// While iterating, mutating operations may only be performed +// on the current field descriptor. +func (x *fastReflection_Nested1B) Range(f func(protoreflect.FieldDescriptor, protoreflect.Value) bool) { + if x.Id != int32(0) { + value := protoreflect.ValueOfInt32(x.Id) + if !f(fd_Nested1B_id, value) { + return + } + } + if x.Nested != nil { + value := protoreflect.ValueOfMessage(x.Nested.ProtoReflect()) + if !f(fd_Nested1B_nested, value) { + return + } + } + if x.Age != int32(0) { + value := protoreflect.ValueOfInt32(x.Age) + if !f(fd_Nested1B_age, value) { + return + } + } +} + +// Has reports whether a field is populated. +// +// Some fields have the property of nullability where it is possible to +// distinguish between the default value of a field and whether the field +// was explicitly populated with the default value. Singular message fields, +// member fields of a oneof, and proto2 scalar fields are nullable. Such +// fields are populated only if explicitly set. +// +// In other cases (aside from the nullable cases above), +// a proto3 scalar field is populated if it contains a non-zero value, and +// a repeated field is populated if it is non-empty. +func (x *fastReflection_Nested1B) Has(fd protoreflect.FieldDescriptor) bool { + switch fd.FullName() { + case "testpb.Nested1B.id": + return x.Id != int32(0) + case "testpb.Nested1B.nested": + return x.Nested != nil + case "testpb.Nested1B.age": + return x.Age != int32(0) + default: + if fd.IsExtension() { + panic(fmt.Errorf("proto3 declared messages do not support extensions: testpb.Nested1B")) + } + panic(fmt.Errorf("message testpb.Nested1B does not contain field %s", fd.FullName())) + } +} + +// Clear clears the field such that a subsequent Has call reports false. +// +// Clearing an extension field clears both the extension type and value +// associated with the given field number. +// +// Clear is a mutating operation and unsafe for concurrent use. +func (x *fastReflection_Nested1B) Clear(fd protoreflect.FieldDescriptor) { + switch fd.FullName() { + case "testpb.Nested1B.id": + x.Id = int32(0) + case "testpb.Nested1B.nested": + x.Nested = nil + case "testpb.Nested1B.age": + x.Age = int32(0) + default: + if fd.IsExtension() { + panic(fmt.Errorf("proto3 declared messages do not support extensions: testpb.Nested1B")) + } + panic(fmt.Errorf("message testpb.Nested1B does not contain field %s", fd.FullName())) + } +} + +// Get retrieves the value for a field. +// +// For unpopulated scalars, it returns the default value, where +// the default value of a bytes scalar is guaranteed to be a copy. +// For unpopulated composite types, it returns an empty, read-only view +// of the value; to obtain a mutable reference, use Mutable. +func (x *fastReflection_Nested1B) Get(descriptor protoreflect.FieldDescriptor) protoreflect.Value { + switch descriptor.FullName() { + case "testpb.Nested1B.id": + value := x.Id + return protoreflect.ValueOfInt32(value) + case "testpb.Nested1B.nested": + value := x.Nested + return protoreflect.ValueOfMessage(value.ProtoReflect()) + case "testpb.Nested1B.age": + value := x.Age + return protoreflect.ValueOfInt32(value) + default: + if descriptor.IsExtension() { + panic(fmt.Errorf("proto3 declared messages do not support extensions: testpb.Nested1B")) + } + panic(fmt.Errorf("message testpb.Nested1B does not contain field %s", descriptor.FullName())) + } +} + +// Set stores the value for a field. +// +// For a field belonging to a oneof, it implicitly clears any other field +// that may be currently set within the same oneof. +// For extension fields, it implicitly stores the provided ExtensionType. +// When setting a composite type, it is unspecified whether the stored value +// aliases the source's memory in any way. If the composite value is an +// empty, read-only value, then it panics. +// +// Set is a mutating operation and unsafe for concurrent use. +func (x *fastReflection_Nested1B) Set(fd protoreflect.FieldDescriptor, value protoreflect.Value) { + switch fd.FullName() { + case "testpb.Nested1B.id": + x.Id = int32(value.Int()) + case "testpb.Nested1B.nested": + x.Nested = value.Message().Interface().(*Nested2B) + case "testpb.Nested1B.age": + x.Age = int32(value.Int()) + default: + if fd.IsExtension() { + panic(fmt.Errorf("proto3 declared messages do not support extensions: testpb.Nested1B")) + } + panic(fmt.Errorf("message testpb.Nested1B does not contain field %s", fd.FullName())) + } +} + +// Mutable returns a mutable reference to a composite type. +// +// If the field is unpopulated, it may allocate a composite value. +// For a field belonging to a oneof, it implicitly clears any other field +// that may be currently set within the same oneof. +// For extension fields, it implicitly stores the provided ExtensionType +// if not already stored. +// It panics if the field does not contain a composite type. +// +// Mutable is a mutating operation and unsafe for concurrent use. +func (x *fastReflection_Nested1B) Mutable(fd protoreflect.FieldDescriptor) protoreflect.Value { + switch fd.FullName() { + case "testpb.Nested1B.nested": + if x.Nested == nil { + x.Nested = new(Nested2B) + } + return protoreflect.ValueOfMessage(x.Nested.ProtoReflect()) + case "testpb.Nested1B.id": + panic(fmt.Errorf("field id of message testpb.Nested1B is not mutable")) + case "testpb.Nested1B.age": + panic(fmt.Errorf("field age of message testpb.Nested1B is not mutable")) + default: + if fd.IsExtension() { + panic(fmt.Errorf("proto3 declared messages do not support extensions: testpb.Nested1B")) + } + panic(fmt.Errorf("message testpb.Nested1B does not contain field %s", fd.FullName())) + } +} + +// NewField returns a new value that is assignable to the field +// for the given descriptor. For scalars, this returns the default value. +// For lists, maps, and messages, this returns a new, empty, mutable value. +func (x *fastReflection_Nested1B) NewField(fd protoreflect.FieldDescriptor) protoreflect.Value { + switch fd.FullName() { + case "testpb.Nested1B.id": + return protoreflect.ValueOfInt32(int32(0)) + case "testpb.Nested1B.nested": + m := new(Nested2B) + return protoreflect.ValueOfMessage(m.ProtoReflect()) + case "testpb.Nested1B.age": + return protoreflect.ValueOfInt32(int32(0)) + default: + if fd.IsExtension() { + panic(fmt.Errorf("proto3 declared messages do not support extensions: testpb.Nested1B")) + } + panic(fmt.Errorf("message testpb.Nested1B does not contain field %s", fd.FullName())) + } +} + +// WhichOneof reports which field within the oneof is populated, +// returning nil if none are populated. +// It panics if the oneof descriptor does not belong to this message. +func (x *fastReflection_Nested1B) WhichOneof(d protoreflect.OneofDescriptor) protoreflect.FieldDescriptor { + switch d.FullName() { + default: + panic(fmt.Errorf("%s is not a oneof field in testpb.Nested1B", d.FullName())) + } + panic("unreachable") +} + +// GetUnknown retrieves the entire list of unknown fields. +// The caller may only mutate the contents of the RawFields +// if the mutated bytes are stored back into the message with SetUnknown. +func (x *fastReflection_Nested1B) GetUnknown() protoreflect.RawFields { + return x.unknownFields +} + +// SetUnknown stores an entire list of unknown fields. +// The raw fields must be syntactically valid according to the wire format. +// An implementation may panic if this is not the case. +// Once stored, the caller must not mutate the content of the RawFields. +// An empty RawFields may be passed to clear the fields. +// +// SetUnknown is a mutating operation and unsafe for concurrent use. +func (x *fastReflection_Nested1B) SetUnknown(fields protoreflect.RawFields) { + x.unknownFields = fields +} + +// IsValid reports whether the message is valid. +// +// An invalid message is an empty, read-only value. +// +// An invalid message often corresponds to a nil pointer of the concrete +// message type, but the details are implementation dependent. +// Validity is not part of the protobuf data model, and may not +// be preserved in marshaling or other operations. +func (x *fastReflection_Nested1B) IsValid() bool { + return x != nil +} + +// ProtoMethods returns optional fastReflectionFeature-path implementations of various operations. +// This method may return nil. +// +// The returned methods type is identical to +// "google.golang.org/protobuf/runtime/protoiface".Methods. +// Consult the protoiface package documentation for details. +func (x *fastReflection_Nested1B) ProtoMethods() *protoiface.Methods { + size := func(input protoiface.SizeInput) protoiface.SizeOutput { + x := input.Message.Interface().(*Nested1B) + if x == nil { + return protoiface.SizeOutput{ + NoUnkeyedLiterals: input.NoUnkeyedLiterals, + Size: 0, + } + } + options := runtime.SizeInputToOptions(input) + _ = options + var n int + var l int + _ = l + if x.Id != 0 { + n += 1 + runtime.Sov(uint64(x.Id)) + } + if x.Nested != nil { + l = options.Size(x.Nested) + n += 1 + l + runtime.Sov(uint64(l)) + } + if x.Age != 0 { + n += 1 + runtime.Sov(uint64(x.Age)) + } + if x.unknownFields != nil { + n += len(x.unknownFields) + } + return protoiface.SizeOutput{ + NoUnkeyedLiterals: input.NoUnkeyedLiterals, + Size: n, + } + } + + marshal := func(input protoiface.MarshalInput) (protoiface.MarshalOutput, error) { + x := input.Message.Interface().(*Nested1B) + if x == nil { + return protoiface.MarshalOutput{ + NoUnkeyedLiterals: input.NoUnkeyedLiterals, + Buf: input.Buf, + }, nil + } + options := runtime.MarshalInputToOptions(input) + _ = options + size := options.Size(x) + dAtA := make([]byte, size) + i := len(dAtA) + _ = i + var l int + _ = l + if x.unknownFields != nil { + i -= len(x.unknownFields) + copy(dAtA[i:], x.unknownFields) + } + if x.Age != 0 { + i = runtime.EncodeVarint(dAtA, i, uint64(x.Age)) + i-- + dAtA[i] = 0x18 + } + if x.Nested != nil { + encoded, err := options.Marshal(x.Nested) + if err != nil { + return protoiface.MarshalOutput{ + NoUnkeyedLiterals: input.NoUnkeyedLiterals, + Buf: input.Buf, + }, err + } + i -= len(encoded) + copy(dAtA[i:], encoded) + i = runtime.EncodeVarint(dAtA, i, uint64(len(encoded))) + i-- + dAtA[i] = 0x12 + } + if x.Id != 0 { + i = runtime.EncodeVarint(dAtA, i, uint64(x.Id)) + i-- + dAtA[i] = 0x8 + } + if input.Buf != nil { + input.Buf = append(input.Buf, dAtA...) + } else { + input.Buf = dAtA + } + return protoiface.MarshalOutput{ + NoUnkeyedLiterals: input.NoUnkeyedLiterals, + Buf: input.Buf, + }, nil + } + unmarshal := func(input protoiface.UnmarshalInput) (protoiface.UnmarshalOutput, error) { + x := input.Message.Interface().(*Nested1B) + if x == nil { + return protoiface.UnmarshalOutput{ + NoUnkeyedLiterals: input.NoUnkeyedLiterals, + Flags: input.Flags, + }, nil + } + options := runtime.UnmarshalInputToOptions(input) + _ = options + dAtA := input.Buf + l := len(dAtA) + iNdEx := 0 + for iNdEx < l { + preIndex := iNdEx + var wire uint64 + for shift := uint(0); ; shift += 7 { + if shift >= 64 { + return protoiface.UnmarshalOutput{NoUnkeyedLiterals: input.NoUnkeyedLiterals, Flags: input.Flags}, runtime.ErrIntOverflow + } + if iNdEx >= l { + return protoiface.UnmarshalOutput{NoUnkeyedLiterals: input.NoUnkeyedLiterals, Flags: input.Flags}, io.ErrUnexpectedEOF + } + b := dAtA[iNdEx] + iNdEx++ + wire |= uint64(b&0x7F) << shift + if b < 0x80 { + break + } + } + fieldNum := int32(wire >> 3) + wireType := int(wire & 0x7) + if wireType == 4 { + return protoiface.UnmarshalOutput{NoUnkeyedLiterals: input.NoUnkeyedLiterals, Flags: input.Flags}, fmt.Errorf("proto: Nested1B: wiretype end group for non-group") + } + if fieldNum <= 0 { + return protoiface.UnmarshalOutput{NoUnkeyedLiterals: input.NoUnkeyedLiterals, Flags: input.Flags}, fmt.Errorf("proto: Nested1B: illegal tag %d (wire type %d)", fieldNum, wire) + } + switch fieldNum { + case 1: + if wireType != 0 { + return protoiface.UnmarshalOutput{NoUnkeyedLiterals: input.NoUnkeyedLiterals, Flags: input.Flags}, fmt.Errorf("proto: wrong wireType = %d for field Id", wireType) + } + x.Id = 0 + for shift := uint(0); ; shift += 7 { + if shift >= 64 { + return protoiface.UnmarshalOutput{NoUnkeyedLiterals: input.NoUnkeyedLiterals, Flags: input.Flags}, runtime.ErrIntOverflow + } + if iNdEx >= l { + return protoiface.UnmarshalOutput{NoUnkeyedLiterals: input.NoUnkeyedLiterals, Flags: input.Flags}, io.ErrUnexpectedEOF + } + b := dAtA[iNdEx] + iNdEx++ + x.Id |= int32(b&0x7F) << shift + if b < 0x80 { + break + } + } + case 2: + if wireType != 2 { + return protoiface.UnmarshalOutput{NoUnkeyedLiterals: input.NoUnkeyedLiterals, Flags: input.Flags}, fmt.Errorf("proto: wrong wireType = %d for field Nested", wireType) + } + var msglen int + for shift := uint(0); ; shift += 7 { + if shift >= 64 { + return protoiface.UnmarshalOutput{NoUnkeyedLiterals: input.NoUnkeyedLiterals, Flags: input.Flags}, runtime.ErrIntOverflow + } + if iNdEx >= l { + return protoiface.UnmarshalOutput{NoUnkeyedLiterals: input.NoUnkeyedLiterals, Flags: input.Flags}, io.ErrUnexpectedEOF + } + b := dAtA[iNdEx] + iNdEx++ + msglen |= int(b&0x7F) << shift + if b < 0x80 { + break + } + } + if msglen < 0 { + return protoiface.UnmarshalOutput{NoUnkeyedLiterals: input.NoUnkeyedLiterals, Flags: input.Flags}, runtime.ErrInvalidLength + } + postIndex := iNdEx + msglen + if postIndex < 0 { + return protoiface.UnmarshalOutput{NoUnkeyedLiterals: input.NoUnkeyedLiterals, Flags: input.Flags}, runtime.ErrInvalidLength + } + if postIndex > l { + return protoiface.UnmarshalOutput{NoUnkeyedLiterals: input.NoUnkeyedLiterals, Flags: input.Flags}, io.ErrUnexpectedEOF + } + if x.Nested == nil { + x.Nested = &Nested2B{} + } + if err := options.Unmarshal(dAtA[iNdEx:postIndex], x.Nested); err != nil { + return protoiface.UnmarshalOutput{NoUnkeyedLiterals: input.NoUnkeyedLiterals, Flags: input.Flags}, err + } + iNdEx = postIndex + case 3: + if wireType != 0 { + return protoiface.UnmarshalOutput{NoUnkeyedLiterals: input.NoUnkeyedLiterals, Flags: input.Flags}, fmt.Errorf("proto: wrong wireType = %d for field Age", wireType) + } + x.Age = 0 + for shift := uint(0); ; shift += 7 { + if shift >= 64 { + return protoiface.UnmarshalOutput{NoUnkeyedLiterals: input.NoUnkeyedLiterals, Flags: input.Flags}, runtime.ErrIntOverflow + } + if iNdEx >= l { + return protoiface.UnmarshalOutput{NoUnkeyedLiterals: input.NoUnkeyedLiterals, Flags: input.Flags}, io.ErrUnexpectedEOF + } + b := dAtA[iNdEx] + iNdEx++ + x.Age |= int32(b&0x7F) << shift + if b < 0x80 { + break + } + } + default: + iNdEx = preIndex + skippy, err := runtime.Skip(dAtA[iNdEx:]) + if err != nil { + return protoiface.UnmarshalOutput{NoUnkeyedLiterals: input.NoUnkeyedLiterals, Flags: input.Flags}, err + } + if (skippy < 0) || (iNdEx+skippy) < 0 { + return protoiface.UnmarshalOutput{NoUnkeyedLiterals: input.NoUnkeyedLiterals, Flags: input.Flags}, runtime.ErrInvalidLength + } + if (iNdEx + skippy) > l { + return protoiface.UnmarshalOutput{NoUnkeyedLiterals: input.NoUnkeyedLiterals, Flags: input.Flags}, io.ErrUnexpectedEOF + } + if !options.DiscardUnknown { + x.unknownFields = append(x.unknownFields, dAtA[iNdEx:iNdEx+skippy]...) + } + iNdEx += skippy + } + } + + if iNdEx > l { + return protoiface.UnmarshalOutput{NoUnkeyedLiterals: input.NoUnkeyedLiterals, Flags: input.Flags}, io.ErrUnexpectedEOF + } + return protoiface.UnmarshalOutput{NoUnkeyedLiterals: input.NoUnkeyedLiterals, Flags: input.Flags}, nil + } + return &protoiface.Methods{ + NoUnkeyedLiterals: struct{}{}, + Flags: protoiface.SupportMarshalDeterministic | protoiface.SupportUnmarshalDiscardUnknown, + Size: size, + Marshal: marshal, + Unmarshal: unmarshal, + Merge: nil, + CheckInitialized: nil, + } +} + +var ( + md_Customer3 protoreflect.MessageDescriptor + fd_Customer3_id protoreflect.FieldDescriptor + fd_Customer3_name protoreflect.FieldDescriptor + fd_Customer3_sf protoreflect.FieldDescriptor + fd_Customer3_surcharge protoreflect.FieldDescriptor + fd_Customer3_destination protoreflect.FieldDescriptor + fd_Customer3_credit_card_no protoreflect.FieldDescriptor + fd_Customer3_cheque_no protoreflect.FieldDescriptor + fd_Customer3_original protoreflect.FieldDescriptor +) + +func init() { + file_unknownproto_proto_init() + md_Customer3 = File_unknownproto_proto.Messages().ByName("Customer3") + fd_Customer3_id = md_Customer3.Fields().ByName("id") + fd_Customer3_name = md_Customer3.Fields().ByName("name") + fd_Customer3_sf = md_Customer3.Fields().ByName("sf") + fd_Customer3_surcharge = md_Customer3.Fields().ByName("surcharge") + fd_Customer3_destination = md_Customer3.Fields().ByName("destination") + fd_Customer3_credit_card_no = md_Customer3.Fields().ByName("credit_card_no") + fd_Customer3_cheque_no = md_Customer3.Fields().ByName("cheque_no") + fd_Customer3_original = md_Customer3.Fields().ByName("original") +} + +var _ protoreflect.Message = (*fastReflection_Customer3)(nil) + +type fastReflection_Customer3 Customer3 + +func (x *Customer3) ProtoReflect() protoreflect.Message { + return (*fastReflection_Customer3)(x) +} + +func (x *Customer3) slowProtoReflect() protoreflect.Message { + mi := &file_unknownproto_proto_msgTypes[10] + if protoimpl.UnsafeEnabled && x != nil { + ms := protoimpl.X.MessageStateOf(protoimpl.Pointer(x)) + if ms.LoadMessageInfo() == nil { + ms.StoreMessageInfo(mi) + } + return ms + } + return mi.MessageOf(x) +} + +var _fastReflection_Customer3_messageType fastReflection_Customer3_messageType +var _ protoreflect.MessageType = fastReflection_Customer3_messageType{} + +type fastReflection_Customer3_messageType struct{} + +func (x fastReflection_Customer3_messageType) Zero() protoreflect.Message { + return (*fastReflection_Customer3)(nil) +} +func (x fastReflection_Customer3_messageType) New() protoreflect.Message { + return new(fastReflection_Customer3) +} +func (x fastReflection_Customer3_messageType) Descriptor() protoreflect.MessageDescriptor { + return md_Customer3 +} + +// Descriptor returns message descriptor, which contains only the protobuf +// type information for the message. +func (x *fastReflection_Customer3) Descriptor() protoreflect.MessageDescriptor { + return md_Customer3 +} + +// Type returns the message type, which encapsulates both Go and protobuf +// type information. If the Go type information is not needed, +// it is recommended that the message descriptor be used instead. +func (x *fastReflection_Customer3) Type() protoreflect.MessageType { + return _fastReflection_Customer3_messageType +} + +// New returns a newly allocated and mutable empty message. +func (x *fastReflection_Customer3) New() protoreflect.Message { + return new(fastReflection_Customer3) +} + +// Interface unwraps the message reflection interface and +// returns the underlying ProtoMessage interface. +func (x *fastReflection_Customer3) Interface() protoreflect.ProtoMessage { + return (*Customer3)(x) +} + +// Range iterates over every populated field in an undefined order, +// calling f for each field descriptor and value encountered. +// Range returns immediately if f returns false. +// While iterating, mutating operations may only be performed +// on the current field descriptor. +func (x *fastReflection_Customer3) Range(f func(protoreflect.FieldDescriptor, protoreflect.Value) bool) { + if x.Id != int32(0) { + value := protoreflect.ValueOfInt32(x.Id) + if !f(fd_Customer3_id, value) { + return + } + } + if x.Name != "" { + value := protoreflect.ValueOfString(x.Name) + if !f(fd_Customer3_name, value) { + return + } + } + if x.Sf != float32(0) || math.Signbit(float64(x.Sf)) { + value := protoreflect.ValueOfFloat32(x.Sf) + if !f(fd_Customer3_sf, value) { + return + } + } + if x.Surcharge != float32(0) || math.Signbit(float64(x.Surcharge)) { + value := protoreflect.ValueOfFloat32(x.Surcharge) + if !f(fd_Customer3_surcharge, value) { + return + } + } + if x.Destination != "" { + value := protoreflect.ValueOfString(x.Destination) + if !f(fd_Customer3_destination, value) { + return + } + } + if x.Payment != nil { + switch o := x.Payment.(type) { + case *Customer3_CreditCardNo: + v := o.CreditCardNo + value := protoreflect.ValueOfString(v) + if !f(fd_Customer3_credit_card_no, value) { + return + } + case *Customer3_ChequeNo: + v := o.ChequeNo + value := protoreflect.ValueOfString(v) + if !f(fd_Customer3_cheque_no, value) { + return + } + } + } + if x.Original != nil { + value := protoreflect.ValueOfMessage(x.Original.ProtoReflect()) + if !f(fd_Customer3_original, value) { + return + } + } +} + +// Has reports whether a field is populated. +// +// Some fields have the property of nullability where it is possible to +// distinguish between the default value of a field and whether the field +// was explicitly populated with the default value. Singular message fields, +// member fields of a oneof, and proto2 scalar fields are nullable. Such +// fields are populated only if explicitly set. +// +// In other cases (aside from the nullable cases above), +// a proto3 scalar field is populated if it contains a non-zero value, and +// a repeated field is populated if it is non-empty. +func (x *fastReflection_Customer3) Has(fd protoreflect.FieldDescriptor) bool { + switch fd.FullName() { + case "testpb.Customer3.id": + return x.Id != int32(0) + case "testpb.Customer3.name": + return x.Name != "" + case "testpb.Customer3.sf": + return x.Sf != float32(0) || math.Signbit(float64(x.Sf)) + case "testpb.Customer3.surcharge": + return x.Surcharge != float32(0) || math.Signbit(float64(x.Surcharge)) + case "testpb.Customer3.destination": + return x.Destination != "" + case "testpb.Customer3.credit_card_no": + if x.Payment == nil { + return false + } else if _, ok := x.Payment.(*Customer3_CreditCardNo); ok { + return true + } else { + return false + } + case "testpb.Customer3.cheque_no": + if x.Payment == nil { + return false + } else if _, ok := x.Payment.(*Customer3_ChequeNo); ok { + return true + } else { + return false + } + case "testpb.Customer3.original": + return x.Original != nil + default: + if fd.IsExtension() { + panic(fmt.Errorf("proto3 declared messages do not support extensions: testpb.Customer3")) + } + panic(fmt.Errorf("message testpb.Customer3 does not contain field %s", fd.FullName())) + } +} + +// Clear clears the field such that a subsequent Has call reports false. +// +// Clearing an extension field clears both the extension type and value +// associated with the given field number. +// +// Clear is a mutating operation and unsafe for concurrent use. +func (x *fastReflection_Customer3) Clear(fd protoreflect.FieldDescriptor) { + switch fd.FullName() { + case "testpb.Customer3.id": + x.Id = int32(0) + case "testpb.Customer3.name": + x.Name = "" + case "testpb.Customer3.sf": + x.Sf = float32(0) + case "testpb.Customer3.surcharge": + x.Surcharge = float32(0) + case "testpb.Customer3.destination": + x.Destination = "" + case "testpb.Customer3.credit_card_no": + x.Payment = nil + case "testpb.Customer3.cheque_no": + x.Payment = nil + case "testpb.Customer3.original": + x.Original = nil + default: + if fd.IsExtension() { + panic(fmt.Errorf("proto3 declared messages do not support extensions: testpb.Customer3")) + } + panic(fmt.Errorf("message testpb.Customer3 does not contain field %s", fd.FullName())) + } +} + +// Get retrieves the value for a field. +// +// For unpopulated scalars, it returns the default value, where +// the default value of a bytes scalar is guaranteed to be a copy. +// For unpopulated composite types, it returns an empty, read-only view +// of the value; to obtain a mutable reference, use Mutable. +func (x *fastReflection_Customer3) Get(descriptor protoreflect.FieldDescriptor) protoreflect.Value { + switch descriptor.FullName() { + case "testpb.Customer3.id": + value := x.Id + return protoreflect.ValueOfInt32(value) + case "testpb.Customer3.name": + value := x.Name + return protoreflect.ValueOfString(value) + case "testpb.Customer3.sf": + value := x.Sf + return protoreflect.ValueOfFloat32(value) + case "testpb.Customer3.surcharge": + value := x.Surcharge + return protoreflect.ValueOfFloat32(value) + case "testpb.Customer3.destination": + value := x.Destination + return protoreflect.ValueOfString(value) + case "testpb.Customer3.credit_card_no": + if x.Payment == nil { + return protoreflect.ValueOfString("") + } else if v, ok := x.Payment.(*Customer3_CreditCardNo); ok { + return protoreflect.ValueOfString(v.CreditCardNo) + } else { + return protoreflect.ValueOfString("") + } + case "testpb.Customer3.cheque_no": + if x.Payment == nil { + return protoreflect.ValueOfString("") + } else if v, ok := x.Payment.(*Customer3_ChequeNo); ok { + return protoreflect.ValueOfString(v.ChequeNo) + } else { + return protoreflect.ValueOfString("") + } + case "testpb.Customer3.original": + value := x.Original + return protoreflect.ValueOfMessage(value.ProtoReflect()) + default: + if descriptor.IsExtension() { + panic(fmt.Errorf("proto3 declared messages do not support extensions: testpb.Customer3")) + } + panic(fmt.Errorf("message testpb.Customer3 does not contain field %s", descriptor.FullName())) + } +} + +// Set stores the value for a field. +// +// For a field belonging to a oneof, it implicitly clears any other field +// that may be currently set within the same oneof. +// For extension fields, it implicitly stores the provided ExtensionType. +// When setting a composite type, it is unspecified whether the stored value +// aliases the source's memory in any way. If the composite value is an +// empty, read-only value, then it panics. +// +// Set is a mutating operation and unsafe for concurrent use. +func (x *fastReflection_Customer3) Set(fd protoreflect.FieldDescriptor, value protoreflect.Value) { + switch fd.FullName() { + case "testpb.Customer3.id": + x.Id = int32(value.Int()) + case "testpb.Customer3.name": + x.Name = value.Interface().(string) + case "testpb.Customer3.sf": + x.Sf = float32(value.Float()) + case "testpb.Customer3.surcharge": + x.Surcharge = float32(value.Float()) + case "testpb.Customer3.destination": + x.Destination = value.Interface().(string) + case "testpb.Customer3.credit_card_no": + cv := value.Interface().(string) + x.Payment = &Customer3_CreditCardNo{CreditCardNo: cv} + case "testpb.Customer3.cheque_no": + cv := value.Interface().(string) + x.Payment = &Customer3_ChequeNo{ChequeNo: cv} + case "testpb.Customer3.original": + x.Original = value.Message().Interface().(*Customer1) + default: + if fd.IsExtension() { + panic(fmt.Errorf("proto3 declared messages do not support extensions: testpb.Customer3")) + } + panic(fmt.Errorf("message testpb.Customer3 does not contain field %s", fd.FullName())) + } +} + +// Mutable returns a mutable reference to a composite type. +// +// If the field is unpopulated, it may allocate a composite value. +// For a field belonging to a oneof, it implicitly clears any other field +// that may be currently set within the same oneof. +// For extension fields, it implicitly stores the provided ExtensionType +// if not already stored. +// It panics if the field does not contain a composite type. +// +// Mutable is a mutating operation and unsafe for concurrent use. +func (x *fastReflection_Customer3) Mutable(fd protoreflect.FieldDescriptor) protoreflect.Value { + switch fd.FullName() { + case "testpb.Customer3.original": + if x.Original == nil { + x.Original = new(Customer1) + } + return protoreflect.ValueOfMessage(x.Original.ProtoReflect()) + case "testpb.Customer3.id": + panic(fmt.Errorf("field id of message testpb.Customer3 is not mutable")) + case "testpb.Customer3.name": + panic(fmt.Errorf("field name of message testpb.Customer3 is not mutable")) + case "testpb.Customer3.sf": + panic(fmt.Errorf("field sf of message testpb.Customer3 is not mutable")) + case "testpb.Customer3.surcharge": + panic(fmt.Errorf("field surcharge of message testpb.Customer3 is not mutable")) + case "testpb.Customer3.destination": + panic(fmt.Errorf("field destination of message testpb.Customer3 is not mutable")) + case "testpb.Customer3.credit_card_no": + panic(fmt.Errorf("field credit_card_no of message testpb.Customer3 is not mutable")) + case "testpb.Customer3.cheque_no": + panic(fmt.Errorf("field cheque_no of message testpb.Customer3 is not mutable")) + default: + if fd.IsExtension() { + panic(fmt.Errorf("proto3 declared messages do not support extensions: testpb.Customer3")) + } + panic(fmt.Errorf("message testpb.Customer3 does not contain field %s", fd.FullName())) + } +} + +// NewField returns a new value that is assignable to the field +// for the given descriptor. For scalars, this returns the default value. +// For lists, maps, and messages, this returns a new, empty, mutable value. +func (x *fastReflection_Customer3) NewField(fd protoreflect.FieldDescriptor) protoreflect.Value { + switch fd.FullName() { + case "testpb.Customer3.id": + return protoreflect.ValueOfInt32(int32(0)) + case "testpb.Customer3.name": + return protoreflect.ValueOfString("") + case "testpb.Customer3.sf": + return protoreflect.ValueOfFloat32(float32(0)) + case "testpb.Customer3.surcharge": + return protoreflect.ValueOfFloat32(float32(0)) + case "testpb.Customer3.destination": + return protoreflect.ValueOfString("") + case "testpb.Customer3.credit_card_no": + return protoreflect.ValueOfString("") + case "testpb.Customer3.cheque_no": + return protoreflect.ValueOfString("") + case "testpb.Customer3.original": + m := new(Customer1) + return protoreflect.ValueOfMessage(m.ProtoReflect()) + default: + if fd.IsExtension() { + panic(fmt.Errorf("proto3 declared messages do not support extensions: testpb.Customer3")) + } + panic(fmt.Errorf("message testpb.Customer3 does not contain field %s", fd.FullName())) + } +} + +// WhichOneof reports which field within the oneof is populated, +// returning nil if none are populated. +// It panics if the oneof descriptor does not belong to this message. +func (x *fastReflection_Customer3) WhichOneof(d protoreflect.OneofDescriptor) protoreflect.FieldDescriptor { + switch d.FullName() { + case "testpb.Customer3.payment": + if x.Payment == nil { + return nil + } + switch x.Payment.(type) { + case *Customer3_CreditCardNo: + return x.Descriptor().Fields().ByName("credit_card_no") + case *Customer3_ChequeNo: + return x.Descriptor().Fields().ByName("cheque_no") + } + default: + panic(fmt.Errorf("%s is not a oneof field in testpb.Customer3", d.FullName())) + } + panic("unreachable") +} + +// GetUnknown retrieves the entire list of unknown fields. +// The caller may only mutate the contents of the RawFields +// if the mutated bytes are stored back into the message with SetUnknown. +func (x *fastReflection_Customer3) GetUnknown() protoreflect.RawFields { + return x.unknownFields +} + +// SetUnknown stores an entire list of unknown fields. +// The raw fields must be syntactically valid according to the wire format. +// An implementation may panic if this is not the case. +// Once stored, the caller must not mutate the content of the RawFields. +// An empty RawFields may be passed to clear the fields. +// +// SetUnknown is a mutating operation and unsafe for concurrent use. +func (x *fastReflection_Customer3) SetUnknown(fields protoreflect.RawFields) { + x.unknownFields = fields +} + +// IsValid reports whether the message is valid. +// +// An invalid message is an empty, read-only value. +// +// An invalid message often corresponds to a nil pointer of the concrete +// message type, but the details are implementation dependent. +// Validity is not part of the protobuf data model, and may not +// be preserved in marshaling or other operations. +func (x *fastReflection_Customer3) IsValid() bool { + return x != nil +} + +// ProtoMethods returns optional fastReflectionFeature-path implementations of various operations. +// This method may return nil. +// +// The returned methods type is identical to +// "google.golang.org/protobuf/runtime/protoiface".Methods. +// Consult the protoiface package documentation for details. +func (x *fastReflection_Customer3) ProtoMethods() *protoiface.Methods { + size := func(input protoiface.SizeInput) protoiface.SizeOutput { + x := input.Message.Interface().(*Customer3) + if x == nil { + return protoiface.SizeOutput{ + NoUnkeyedLiterals: input.NoUnkeyedLiterals, + Size: 0, + } + } + options := runtime.SizeInputToOptions(input) + _ = options + var n int + var l int + _ = l + if x.Id != 0 { + n += 1 + runtime.Sov(uint64(x.Id)) + } + l = len(x.Name) + if l > 0 { + n += 1 + l + runtime.Sov(uint64(l)) + } + if x.Sf != 0 || math.Signbit(float64(x.Sf)) { + n += 5 + } + if x.Surcharge != 0 || math.Signbit(float64(x.Surcharge)) { + n += 5 + } + l = len(x.Destination) + if l > 0 { + n += 1 + l + runtime.Sov(uint64(l)) + } + switch x := x.Payment.(type) { + case *Customer3_CreditCardNo: + if x == nil { + break + } + l = len(x.CreditCardNo) + n += 1 + l + runtime.Sov(uint64(l)) + case *Customer3_ChequeNo: + if x == nil { + break + } + l = len(x.ChequeNo) + n += 1 + l + runtime.Sov(uint64(l)) + } + if x.Original != nil { + l = options.Size(x.Original) + n += 1 + l + runtime.Sov(uint64(l)) + } + if x.unknownFields != nil { + n += len(x.unknownFields) + } + return protoiface.SizeOutput{ + NoUnkeyedLiterals: input.NoUnkeyedLiterals, + Size: n, + } + } + + marshal := func(input protoiface.MarshalInput) (protoiface.MarshalOutput, error) { + x := input.Message.Interface().(*Customer3) + if x == nil { + return protoiface.MarshalOutput{ + NoUnkeyedLiterals: input.NoUnkeyedLiterals, + Buf: input.Buf, + }, nil + } + options := runtime.MarshalInputToOptions(input) + _ = options + size := options.Size(x) + dAtA := make([]byte, size) + i := len(dAtA) + _ = i + var l int + _ = l + if x.unknownFields != nil { + i -= len(x.unknownFields) + copy(dAtA[i:], x.unknownFields) + } + switch x := x.Payment.(type) { + case *Customer3_CreditCardNo: + i -= len(x.CreditCardNo) + copy(dAtA[i:], x.CreditCardNo) + i = runtime.EncodeVarint(dAtA, i, uint64(len(x.CreditCardNo))) + i-- + dAtA[i] = 0x3a + case *Customer3_ChequeNo: + i -= len(x.ChequeNo) + copy(dAtA[i:], x.ChequeNo) + i = runtime.EncodeVarint(dAtA, i, uint64(len(x.ChequeNo))) + i-- + dAtA[i] = 0x42 + } + if x.Original != nil { + encoded, err := options.Marshal(x.Original) + if err != nil { + return protoiface.MarshalOutput{ + NoUnkeyedLiterals: input.NoUnkeyedLiterals, + Buf: input.Buf, + }, err + } + i -= len(encoded) + copy(dAtA[i:], encoded) + i = runtime.EncodeVarint(dAtA, i, uint64(len(encoded))) + i-- + dAtA[i] = 0x4a + } + if len(x.Destination) > 0 { + i -= len(x.Destination) + copy(dAtA[i:], x.Destination) + i = runtime.EncodeVarint(dAtA, i, uint64(len(x.Destination))) + i-- + dAtA[i] = 0x2a + } + if x.Surcharge != 0 || math.Signbit(float64(x.Surcharge)) { + i -= 4 + binary.LittleEndian.PutUint32(dAtA[i:], uint32(math.Float32bits(float32(x.Surcharge)))) + i-- + dAtA[i] = 0x25 + } + if x.Sf != 0 || math.Signbit(float64(x.Sf)) { + i -= 4 + binary.LittleEndian.PutUint32(dAtA[i:], uint32(math.Float32bits(float32(x.Sf)))) + i-- + dAtA[i] = 0x1d + } + if len(x.Name) > 0 { + i -= len(x.Name) + copy(dAtA[i:], x.Name) + i = runtime.EncodeVarint(dAtA, i, uint64(len(x.Name))) + i-- + dAtA[i] = 0x12 + } + if x.Id != 0 { + i = runtime.EncodeVarint(dAtA, i, uint64(x.Id)) + i-- + dAtA[i] = 0x8 + } + if input.Buf != nil { + input.Buf = append(input.Buf, dAtA...) + } else { + input.Buf = dAtA + } + return protoiface.MarshalOutput{ + NoUnkeyedLiterals: input.NoUnkeyedLiterals, + Buf: input.Buf, + }, nil + } + unmarshal := func(input protoiface.UnmarshalInput) (protoiface.UnmarshalOutput, error) { + x := input.Message.Interface().(*Customer3) + if x == nil { + return protoiface.UnmarshalOutput{ + NoUnkeyedLiterals: input.NoUnkeyedLiterals, + Flags: input.Flags, + }, nil + } + options := runtime.UnmarshalInputToOptions(input) + _ = options + dAtA := input.Buf + l := len(dAtA) + iNdEx := 0 + for iNdEx < l { + preIndex := iNdEx + var wire uint64 + for shift := uint(0); ; shift += 7 { + if shift >= 64 { + return protoiface.UnmarshalOutput{NoUnkeyedLiterals: input.NoUnkeyedLiterals, Flags: input.Flags}, runtime.ErrIntOverflow + } + if iNdEx >= l { + return protoiface.UnmarshalOutput{NoUnkeyedLiterals: input.NoUnkeyedLiterals, Flags: input.Flags}, io.ErrUnexpectedEOF + } + b := dAtA[iNdEx] + iNdEx++ + wire |= uint64(b&0x7F) << shift + if b < 0x80 { + break + } + } + fieldNum := int32(wire >> 3) + wireType := int(wire & 0x7) + if wireType == 4 { + return protoiface.UnmarshalOutput{NoUnkeyedLiterals: input.NoUnkeyedLiterals, Flags: input.Flags}, fmt.Errorf("proto: Customer3: wiretype end group for non-group") + } + if fieldNum <= 0 { + return protoiface.UnmarshalOutput{NoUnkeyedLiterals: input.NoUnkeyedLiterals, Flags: input.Flags}, fmt.Errorf("proto: Customer3: illegal tag %d (wire type %d)", fieldNum, wire) + } + switch fieldNum { + case 1: + if wireType != 0 { + return protoiface.UnmarshalOutput{NoUnkeyedLiterals: input.NoUnkeyedLiterals, Flags: input.Flags}, fmt.Errorf("proto: wrong wireType = %d for field Id", wireType) + } + x.Id = 0 + for shift := uint(0); ; shift += 7 { + if shift >= 64 { + return protoiface.UnmarshalOutput{NoUnkeyedLiterals: input.NoUnkeyedLiterals, Flags: input.Flags}, runtime.ErrIntOverflow + } + if iNdEx >= l { + return protoiface.UnmarshalOutput{NoUnkeyedLiterals: input.NoUnkeyedLiterals, Flags: input.Flags}, io.ErrUnexpectedEOF + } + b := dAtA[iNdEx] + iNdEx++ + x.Id |= int32(b&0x7F) << shift + if b < 0x80 { + break + } + } + case 2: + if wireType != 2 { + return protoiface.UnmarshalOutput{NoUnkeyedLiterals: input.NoUnkeyedLiterals, Flags: input.Flags}, fmt.Errorf("proto: wrong wireType = %d for field Name", wireType) + } + var stringLen uint64 + for shift := uint(0); ; shift += 7 { + if shift >= 64 { + return protoiface.UnmarshalOutput{NoUnkeyedLiterals: input.NoUnkeyedLiterals, Flags: input.Flags}, runtime.ErrIntOverflow + } + if iNdEx >= l { + return protoiface.UnmarshalOutput{NoUnkeyedLiterals: input.NoUnkeyedLiterals, Flags: input.Flags}, io.ErrUnexpectedEOF + } + b := dAtA[iNdEx] + iNdEx++ + stringLen |= uint64(b&0x7F) << shift + if b < 0x80 { + break + } + } + intStringLen := int(stringLen) + if intStringLen < 0 { + return protoiface.UnmarshalOutput{NoUnkeyedLiterals: input.NoUnkeyedLiterals, Flags: input.Flags}, runtime.ErrInvalidLength + } + postIndex := iNdEx + intStringLen + if postIndex < 0 { + return protoiface.UnmarshalOutput{NoUnkeyedLiterals: input.NoUnkeyedLiterals, Flags: input.Flags}, runtime.ErrInvalidLength + } + if postIndex > l { + return protoiface.UnmarshalOutput{NoUnkeyedLiterals: input.NoUnkeyedLiterals, Flags: input.Flags}, io.ErrUnexpectedEOF + } + x.Name = string(dAtA[iNdEx:postIndex]) + iNdEx = postIndex + case 3: + if wireType != 5 { + return protoiface.UnmarshalOutput{NoUnkeyedLiterals: input.NoUnkeyedLiterals, Flags: input.Flags}, fmt.Errorf("proto: wrong wireType = %d for field Sf", wireType) + } + var v uint32 + if (iNdEx + 4) > l { + return protoiface.UnmarshalOutput{NoUnkeyedLiterals: input.NoUnkeyedLiterals, Flags: input.Flags}, io.ErrUnexpectedEOF + } + v = uint32(binary.LittleEndian.Uint32(dAtA[iNdEx:])) + iNdEx += 4 + x.Sf = float32(math.Float32frombits(v)) + case 4: + if wireType != 5 { + return protoiface.UnmarshalOutput{NoUnkeyedLiterals: input.NoUnkeyedLiterals, Flags: input.Flags}, fmt.Errorf("proto: wrong wireType = %d for field Surcharge", wireType) + } + var v uint32 + if (iNdEx + 4) > l { + return protoiface.UnmarshalOutput{NoUnkeyedLiterals: input.NoUnkeyedLiterals, Flags: input.Flags}, io.ErrUnexpectedEOF + } + v = uint32(binary.LittleEndian.Uint32(dAtA[iNdEx:])) + iNdEx += 4 + x.Surcharge = float32(math.Float32frombits(v)) + case 5: + if wireType != 2 { + return protoiface.UnmarshalOutput{NoUnkeyedLiterals: input.NoUnkeyedLiterals, Flags: input.Flags}, fmt.Errorf("proto: wrong wireType = %d for field Destination", wireType) + } + var stringLen uint64 + for shift := uint(0); ; shift += 7 { + if shift >= 64 { + return protoiface.UnmarshalOutput{NoUnkeyedLiterals: input.NoUnkeyedLiterals, Flags: input.Flags}, runtime.ErrIntOverflow + } + if iNdEx >= l { + return protoiface.UnmarshalOutput{NoUnkeyedLiterals: input.NoUnkeyedLiterals, Flags: input.Flags}, io.ErrUnexpectedEOF + } + b := dAtA[iNdEx] + iNdEx++ + stringLen |= uint64(b&0x7F) << shift + if b < 0x80 { + break + } + } + intStringLen := int(stringLen) + if intStringLen < 0 { + return protoiface.UnmarshalOutput{NoUnkeyedLiterals: input.NoUnkeyedLiterals, Flags: input.Flags}, runtime.ErrInvalidLength + } + postIndex := iNdEx + intStringLen + if postIndex < 0 { + return protoiface.UnmarshalOutput{NoUnkeyedLiterals: input.NoUnkeyedLiterals, Flags: input.Flags}, runtime.ErrInvalidLength + } + if postIndex > l { + return protoiface.UnmarshalOutput{NoUnkeyedLiterals: input.NoUnkeyedLiterals, Flags: input.Flags}, io.ErrUnexpectedEOF + } + x.Destination = string(dAtA[iNdEx:postIndex]) + iNdEx = postIndex + case 7: + if wireType != 2 { + return protoiface.UnmarshalOutput{NoUnkeyedLiterals: input.NoUnkeyedLiterals, Flags: input.Flags}, fmt.Errorf("proto: wrong wireType = %d for field CreditCardNo", wireType) + } + var stringLen uint64 + for shift := uint(0); ; shift += 7 { + if shift >= 64 { + return protoiface.UnmarshalOutput{NoUnkeyedLiterals: input.NoUnkeyedLiterals, Flags: input.Flags}, runtime.ErrIntOverflow + } + if iNdEx >= l { + return protoiface.UnmarshalOutput{NoUnkeyedLiterals: input.NoUnkeyedLiterals, Flags: input.Flags}, io.ErrUnexpectedEOF + } + b := dAtA[iNdEx] + iNdEx++ + stringLen |= uint64(b&0x7F) << shift + if b < 0x80 { + break + } + } + intStringLen := int(stringLen) + if intStringLen < 0 { + return protoiface.UnmarshalOutput{NoUnkeyedLiterals: input.NoUnkeyedLiterals, Flags: input.Flags}, runtime.ErrInvalidLength + } + postIndex := iNdEx + intStringLen + if postIndex < 0 { + return protoiface.UnmarshalOutput{NoUnkeyedLiterals: input.NoUnkeyedLiterals, Flags: input.Flags}, runtime.ErrInvalidLength + } + if postIndex > l { + return protoiface.UnmarshalOutput{NoUnkeyedLiterals: input.NoUnkeyedLiterals, Flags: input.Flags}, io.ErrUnexpectedEOF + } + x.Payment = &Customer3_CreditCardNo{string(dAtA[iNdEx:postIndex])} + iNdEx = postIndex + case 8: + if wireType != 2 { + return protoiface.UnmarshalOutput{NoUnkeyedLiterals: input.NoUnkeyedLiterals, Flags: input.Flags}, fmt.Errorf("proto: wrong wireType = %d for field ChequeNo", wireType) + } + var stringLen uint64 + for shift := uint(0); ; shift += 7 { + if shift >= 64 { + return protoiface.UnmarshalOutput{NoUnkeyedLiterals: input.NoUnkeyedLiterals, Flags: input.Flags}, runtime.ErrIntOverflow + } + if iNdEx >= l { + return protoiface.UnmarshalOutput{NoUnkeyedLiterals: input.NoUnkeyedLiterals, Flags: input.Flags}, io.ErrUnexpectedEOF + } + b := dAtA[iNdEx] + iNdEx++ + stringLen |= uint64(b&0x7F) << shift + if b < 0x80 { + break + } + } + intStringLen := int(stringLen) + if intStringLen < 0 { + return protoiface.UnmarshalOutput{NoUnkeyedLiterals: input.NoUnkeyedLiterals, Flags: input.Flags}, runtime.ErrInvalidLength + } + postIndex := iNdEx + intStringLen + if postIndex < 0 { + return protoiface.UnmarshalOutput{NoUnkeyedLiterals: input.NoUnkeyedLiterals, Flags: input.Flags}, runtime.ErrInvalidLength + } + if postIndex > l { + return protoiface.UnmarshalOutput{NoUnkeyedLiterals: input.NoUnkeyedLiterals, Flags: input.Flags}, io.ErrUnexpectedEOF + } + x.Payment = &Customer3_ChequeNo{string(dAtA[iNdEx:postIndex])} + iNdEx = postIndex + case 9: + if wireType != 2 { + return protoiface.UnmarshalOutput{NoUnkeyedLiterals: input.NoUnkeyedLiterals, Flags: input.Flags}, fmt.Errorf("proto: wrong wireType = %d for field Original", wireType) + } + var msglen int + for shift := uint(0); ; shift += 7 { + if shift >= 64 { + return protoiface.UnmarshalOutput{NoUnkeyedLiterals: input.NoUnkeyedLiterals, Flags: input.Flags}, runtime.ErrIntOverflow + } + if iNdEx >= l { + return protoiface.UnmarshalOutput{NoUnkeyedLiterals: input.NoUnkeyedLiterals, Flags: input.Flags}, io.ErrUnexpectedEOF + } + b := dAtA[iNdEx] + iNdEx++ + msglen |= int(b&0x7F) << shift + if b < 0x80 { + break + } + } + if msglen < 0 { + return protoiface.UnmarshalOutput{NoUnkeyedLiterals: input.NoUnkeyedLiterals, Flags: input.Flags}, runtime.ErrInvalidLength + } + postIndex := iNdEx + msglen + if postIndex < 0 { + return protoiface.UnmarshalOutput{NoUnkeyedLiterals: input.NoUnkeyedLiterals, Flags: input.Flags}, runtime.ErrInvalidLength + } + if postIndex > l { + return protoiface.UnmarshalOutput{NoUnkeyedLiterals: input.NoUnkeyedLiterals, Flags: input.Flags}, io.ErrUnexpectedEOF + } + if x.Original == nil { + x.Original = &Customer1{} + } + if err := options.Unmarshal(dAtA[iNdEx:postIndex], x.Original); err != nil { + return protoiface.UnmarshalOutput{NoUnkeyedLiterals: input.NoUnkeyedLiterals, Flags: input.Flags}, err + } + iNdEx = postIndex + default: + iNdEx = preIndex + skippy, err := runtime.Skip(dAtA[iNdEx:]) + if err != nil { + return protoiface.UnmarshalOutput{NoUnkeyedLiterals: input.NoUnkeyedLiterals, Flags: input.Flags}, err + } + if (skippy < 0) || (iNdEx+skippy) < 0 { + return protoiface.UnmarshalOutput{NoUnkeyedLiterals: input.NoUnkeyedLiterals, Flags: input.Flags}, runtime.ErrInvalidLength + } + if (iNdEx + skippy) > l { + return protoiface.UnmarshalOutput{NoUnkeyedLiterals: input.NoUnkeyedLiterals, Flags: input.Flags}, io.ErrUnexpectedEOF + } + if !options.DiscardUnknown { + x.unknownFields = append(x.unknownFields, dAtA[iNdEx:iNdEx+skippy]...) + } + iNdEx += skippy + } + } + + if iNdEx > l { + return protoiface.UnmarshalOutput{NoUnkeyedLiterals: input.NoUnkeyedLiterals, Flags: input.Flags}, io.ErrUnexpectedEOF + } + return protoiface.UnmarshalOutput{NoUnkeyedLiterals: input.NoUnkeyedLiterals, Flags: input.Flags}, nil + } + return &protoiface.Methods{ + NoUnkeyedLiterals: struct{}{}, + Flags: protoiface.SupportMarshalDeterministic | protoiface.SupportUnmarshalDiscardUnknown, + Size: size, + Marshal: marshal, + Unmarshal: unmarshal, + Merge: nil, + CheckInitialized: nil, + } +} + +var _ protoreflect.List = (*_TestVersion1_4_list)(nil) + +type _TestVersion1_4_list struct { + list *[]*TestVersion1 +} + +func (x *_TestVersion1_4_list) Len() int { + if x.list == nil { + return 0 + } + return len(*x.list) +} + +func (x *_TestVersion1_4_list) Get(i int) protoreflect.Value { + return protoreflect.ValueOfMessage((*x.list)[i].ProtoReflect()) +} + +func (x *_TestVersion1_4_list) Set(i int, value protoreflect.Value) { + valueUnwrapped := value.Message() + concreteValue := valueUnwrapped.Interface().(*TestVersion1) + (*x.list)[i] = concreteValue +} + +func (x *_TestVersion1_4_list) Append(value protoreflect.Value) { + valueUnwrapped := value.Message() + concreteValue := valueUnwrapped.Interface().(*TestVersion1) + *x.list = append(*x.list, concreteValue) +} + +func (x *_TestVersion1_4_list) AppendMutable() protoreflect.Value { + v := new(TestVersion1) + *x.list = append(*x.list, v) + return protoreflect.ValueOfMessage(v.ProtoReflect()) +} + +func (x *_TestVersion1_4_list) Truncate(n int) { + for i := n; i < len(*x.list); i++ { + (*x.list)[i] = nil + } + *x.list = (*x.list)[:n] +} + +func (x *_TestVersion1_4_list) NewElement() protoreflect.Value { + v := new(TestVersion1) + return protoreflect.ValueOfMessage(v.ProtoReflect()) +} + +func (x *_TestVersion1_4_list) IsValid() bool { + return x.list != nil +} + +var _ protoreflect.List = (*_TestVersion1_5_list)(nil) + +type _TestVersion1_5_list struct { + list *[]*TestVersion1 +} + +func (x *_TestVersion1_5_list) Len() int { + if x.list == nil { + return 0 + } + return len(*x.list) +} + +func (x *_TestVersion1_5_list) Get(i int) protoreflect.Value { + return protoreflect.ValueOfMessage((*x.list)[i].ProtoReflect()) +} + +func (x *_TestVersion1_5_list) Set(i int, value protoreflect.Value) { + valueUnwrapped := value.Message() + concreteValue := valueUnwrapped.Interface().(*TestVersion1) + (*x.list)[i] = concreteValue +} + +func (x *_TestVersion1_5_list) Append(value protoreflect.Value) { + valueUnwrapped := value.Message() + concreteValue := valueUnwrapped.Interface().(*TestVersion1) + *x.list = append(*x.list, concreteValue) +} + +func (x *_TestVersion1_5_list) AppendMutable() protoreflect.Value { + v := new(TestVersion1) + *x.list = append(*x.list, v) + return protoreflect.ValueOfMessage(v.ProtoReflect()) +} + +func (x *_TestVersion1_5_list) Truncate(n int) { + for i := n; i < len(*x.list); i++ { + (*x.list)[i] = nil + } + *x.list = (*x.list)[:n] +} + +func (x *_TestVersion1_5_list) NewElement() protoreflect.Value { + v := new(TestVersion1) + return protoreflect.ValueOfMessage(v.ProtoReflect()) +} + +func (x *_TestVersion1_5_list) IsValid() bool { + return x.list != nil +} + +var _ protoreflect.List = (*_TestVersion1_9_list)(nil) + +type _TestVersion1_9_list struct { + list *[]*TestVersion1 +} + +func (x *_TestVersion1_9_list) Len() int { + if x.list == nil { + return 0 + } + return len(*x.list) +} + +func (x *_TestVersion1_9_list) Get(i int) protoreflect.Value { + return protoreflect.ValueOfMessage((*x.list)[i].ProtoReflect()) +} + +func (x *_TestVersion1_9_list) Set(i int, value protoreflect.Value) { + valueUnwrapped := value.Message() + concreteValue := valueUnwrapped.Interface().(*TestVersion1) + (*x.list)[i] = concreteValue +} + +func (x *_TestVersion1_9_list) Append(value protoreflect.Value) { + valueUnwrapped := value.Message() + concreteValue := valueUnwrapped.Interface().(*TestVersion1) + *x.list = append(*x.list, concreteValue) +} + +func (x *_TestVersion1_9_list) AppendMutable() protoreflect.Value { + v := new(TestVersion1) + *x.list = append(*x.list, v) + return protoreflect.ValueOfMessage(v.ProtoReflect()) +} + +func (x *_TestVersion1_9_list) Truncate(n int) { + for i := n; i < len(*x.list); i++ { + (*x.list)[i] = nil + } + *x.list = (*x.list)[:n] +} + +func (x *_TestVersion1_9_list) NewElement() protoreflect.Value { + v := new(TestVersion1) + return protoreflect.ValueOfMessage(v.ProtoReflect()) +} + +func (x *_TestVersion1_9_list) IsValid() bool { + return x.list != nil +} + +var ( + md_TestVersion1 protoreflect.MessageDescriptor + fd_TestVersion1_x protoreflect.FieldDescriptor + fd_TestVersion1_a protoreflect.FieldDescriptor + fd_TestVersion1_b protoreflect.FieldDescriptor + fd_TestVersion1_c protoreflect.FieldDescriptor + fd_TestVersion1_d protoreflect.FieldDescriptor + fd_TestVersion1_e protoreflect.FieldDescriptor + fd_TestVersion1_f protoreflect.FieldDescriptor + fd_TestVersion1_g protoreflect.FieldDescriptor + fd_TestVersion1_h protoreflect.FieldDescriptor + fd_TestVersion1_k protoreflect.FieldDescriptor +) + +func init() { + file_unknownproto_proto_init() + md_TestVersion1 = File_unknownproto_proto.Messages().ByName("TestVersion1") + fd_TestVersion1_x = md_TestVersion1.Fields().ByName("x") + fd_TestVersion1_a = md_TestVersion1.Fields().ByName("a") + fd_TestVersion1_b = md_TestVersion1.Fields().ByName("b") + fd_TestVersion1_c = md_TestVersion1.Fields().ByName("c") + fd_TestVersion1_d = md_TestVersion1.Fields().ByName("d") + fd_TestVersion1_e = md_TestVersion1.Fields().ByName("e") + fd_TestVersion1_f = md_TestVersion1.Fields().ByName("f") + fd_TestVersion1_g = md_TestVersion1.Fields().ByName("g") + fd_TestVersion1_h = md_TestVersion1.Fields().ByName("h") + fd_TestVersion1_k = md_TestVersion1.Fields().ByName("k") +} + +var _ protoreflect.Message = (*fastReflection_TestVersion1)(nil) + +type fastReflection_TestVersion1 TestVersion1 + +func (x *TestVersion1) ProtoReflect() protoreflect.Message { + return (*fastReflection_TestVersion1)(x) +} + +func (x *TestVersion1) slowProtoReflect() protoreflect.Message { + mi := &file_unknownproto_proto_msgTypes[11] + if protoimpl.UnsafeEnabled && x != nil { + ms := protoimpl.X.MessageStateOf(protoimpl.Pointer(x)) + if ms.LoadMessageInfo() == nil { + ms.StoreMessageInfo(mi) + } + return ms + } + return mi.MessageOf(x) +} + +var _fastReflection_TestVersion1_messageType fastReflection_TestVersion1_messageType +var _ protoreflect.MessageType = fastReflection_TestVersion1_messageType{} + +type fastReflection_TestVersion1_messageType struct{} + +func (x fastReflection_TestVersion1_messageType) Zero() protoreflect.Message { + return (*fastReflection_TestVersion1)(nil) +} +func (x fastReflection_TestVersion1_messageType) New() protoreflect.Message { + return new(fastReflection_TestVersion1) +} +func (x fastReflection_TestVersion1_messageType) Descriptor() protoreflect.MessageDescriptor { + return md_TestVersion1 +} + +// Descriptor returns message descriptor, which contains only the protobuf +// type information for the message. +func (x *fastReflection_TestVersion1) Descriptor() protoreflect.MessageDescriptor { + return md_TestVersion1 +} + +// Type returns the message type, which encapsulates both Go and protobuf +// type information. If the Go type information is not needed, +// it is recommended that the message descriptor be used instead. +func (x *fastReflection_TestVersion1) Type() protoreflect.MessageType { + return _fastReflection_TestVersion1_messageType +} + +// New returns a newly allocated and mutable empty message. +func (x *fastReflection_TestVersion1) New() protoreflect.Message { + return new(fastReflection_TestVersion1) +} + +// Interface unwraps the message reflection interface and +// returns the underlying ProtoMessage interface. +func (x *fastReflection_TestVersion1) Interface() protoreflect.ProtoMessage { + return (*TestVersion1)(x) +} + +// Range iterates over every populated field in an undefined order, +// calling f for each field descriptor and value encountered. +// Range returns immediately if f returns false. +// While iterating, mutating operations may only be performed +// on the current field descriptor. +func (x *fastReflection_TestVersion1) Range(f func(protoreflect.FieldDescriptor, protoreflect.Value) bool) { + if x.X != int64(0) { + value := protoreflect.ValueOfInt64(x.X) + if !f(fd_TestVersion1_x, value) { + return + } + } + if x.A != nil { + value := protoreflect.ValueOfMessage(x.A.ProtoReflect()) + if !f(fd_TestVersion1_a, value) { + return + } + } + if x.B != nil { + value := protoreflect.ValueOfMessage(x.B.ProtoReflect()) + if !f(fd_TestVersion1_b, value) { + return + } + } + if len(x.C) != 0 { + value := protoreflect.ValueOfList(&_TestVersion1_4_list{list: &x.C}) + if !f(fd_TestVersion1_c, value) { + return + } + } + if len(x.D) != 0 { + value := protoreflect.ValueOfList(&_TestVersion1_5_list{list: &x.D}) + if !f(fd_TestVersion1_d, value) { + return + } + } + if x.Sum != nil { + switch o := x.Sum.(type) { + case *TestVersion1_E: + v := o.E + value := protoreflect.ValueOfInt32(v) + if !f(fd_TestVersion1_e, value) { + return + } + case *TestVersion1_F: + v := o.F + value := protoreflect.ValueOfMessage(v.ProtoReflect()) + if !f(fd_TestVersion1_f, value) { + return + } + } + } + if x.G != nil { + value := protoreflect.ValueOfMessage(x.G.ProtoReflect()) + if !f(fd_TestVersion1_g, value) { + return + } + } + if len(x.H) != 0 { + value := protoreflect.ValueOfList(&_TestVersion1_9_list{list: &x.H}) + if !f(fd_TestVersion1_h, value) { + return + } + } + if x.K != nil { + value := protoreflect.ValueOfMessage(x.K.ProtoReflect()) + if !f(fd_TestVersion1_k, value) { + return + } + } +} + +// Has reports whether a field is populated. +// +// Some fields have the property of nullability where it is possible to +// distinguish between the default value of a field and whether the field +// was explicitly populated with the default value. Singular message fields, +// member fields of a oneof, and proto2 scalar fields are nullable. Such +// fields are populated only if explicitly set. +// +// In other cases (aside from the nullable cases above), +// a proto3 scalar field is populated if it contains a non-zero value, and +// a repeated field is populated if it is non-empty. +func (x *fastReflection_TestVersion1) Has(fd protoreflect.FieldDescriptor) bool { + switch fd.FullName() { + case "testpb.TestVersion1.x": + return x.X != int64(0) + case "testpb.TestVersion1.a": + return x.A != nil + case "testpb.TestVersion1.b": + return x.B != nil + case "testpb.TestVersion1.c": + return len(x.C) != 0 + case "testpb.TestVersion1.d": + return len(x.D) != 0 + case "testpb.TestVersion1.e": + if x.Sum == nil { + return false + } else if _, ok := x.Sum.(*TestVersion1_E); ok { + return true + } else { + return false + } + case "testpb.TestVersion1.f": + if x.Sum == nil { + return false + } else if _, ok := x.Sum.(*TestVersion1_F); ok { + return true + } else { + return false + } + case "testpb.TestVersion1.g": + return x.G != nil + case "testpb.TestVersion1.h": + return len(x.H) != 0 + case "testpb.TestVersion1.k": + return x.K != nil + default: + if fd.IsExtension() { + panic(fmt.Errorf("proto3 declared messages do not support extensions: testpb.TestVersion1")) + } + panic(fmt.Errorf("message testpb.TestVersion1 does not contain field %s", fd.FullName())) + } +} + +// Clear clears the field such that a subsequent Has call reports false. +// +// Clearing an extension field clears both the extension type and value +// associated with the given field number. +// +// Clear is a mutating operation and unsafe for concurrent use. +func (x *fastReflection_TestVersion1) Clear(fd protoreflect.FieldDescriptor) { + switch fd.FullName() { + case "testpb.TestVersion1.x": + x.X = int64(0) + case "testpb.TestVersion1.a": + x.A = nil + case "testpb.TestVersion1.b": + x.B = nil + case "testpb.TestVersion1.c": + x.C = nil + case "testpb.TestVersion1.d": + x.D = nil + case "testpb.TestVersion1.e": + x.Sum = nil + case "testpb.TestVersion1.f": + x.Sum = nil + case "testpb.TestVersion1.g": + x.G = nil + case "testpb.TestVersion1.h": + x.H = nil + case "testpb.TestVersion1.k": + x.K = nil + default: + if fd.IsExtension() { + panic(fmt.Errorf("proto3 declared messages do not support extensions: testpb.TestVersion1")) + } + panic(fmt.Errorf("message testpb.TestVersion1 does not contain field %s", fd.FullName())) + } +} + +// Get retrieves the value for a field. +// +// For unpopulated scalars, it returns the default value, where +// the default value of a bytes scalar is guaranteed to be a copy. +// For unpopulated composite types, it returns an empty, read-only view +// of the value; to obtain a mutable reference, use Mutable. +func (x *fastReflection_TestVersion1) Get(descriptor protoreflect.FieldDescriptor) protoreflect.Value { + switch descriptor.FullName() { + case "testpb.TestVersion1.x": + value := x.X + return protoreflect.ValueOfInt64(value) + case "testpb.TestVersion1.a": + value := x.A + return protoreflect.ValueOfMessage(value.ProtoReflect()) + case "testpb.TestVersion1.b": + value := x.B + return protoreflect.ValueOfMessage(value.ProtoReflect()) + case "testpb.TestVersion1.c": + if len(x.C) == 0 { + return protoreflect.ValueOfList(&_TestVersion1_4_list{}) + } + listValue := &_TestVersion1_4_list{list: &x.C} + return protoreflect.ValueOfList(listValue) + case "testpb.TestVersion1.d": + if len(x.D) == 0 { + return protoreflect.ValueOfList(&_TestVersion1_5_list{}) + } + listValue := &_TestVersion1_5_list{list: &x.D} + return protoreflect.ValueOfList(listValue) + case "testpb.TestVersion1.e": + if x.Sum == nil { + return protoreflect.ValueOfInt32(int32(0)) + } else if v, ok := x.Sum.(*TestVersion1_E); ok { + return protoreflect.ValueOfInt32(v.E) + } else { + return protoreflect.ValueOfInt32(int32(0)) + } + case "testpb.TestVersion1.f": + if x.Sum == nil { + return protoreflect.ValueOfMessage((*TestVersion1)(nil).ProtoReflect()) + } else if v, ok := x.Sum.(*TestVersion1_F); ok { + return protoreflect.ValueOfMessage(v.F.ProtoReflect()) + } else { + return protoreflect.ValueOfMessage((*TestVersion1)(nil).ProtoReflect()) + } + case "testpb.TestVersion1.g": + value := x.G + return protoreflect.ValueOfMessage(value.ProtoReflect()) + case "testpb.TestVersion1.h": + if len(x.H) == 0 { + return protoreflect.ValueOfList(&_TestVersion1_9_list{}) + } + listValue := &_TestVersion1_9_list{list: &x.H} + return protoreflect.ValueOfList(listValue) + case "testpb.TestVersion1.k": + value := x.K + return protoreflect.ValueOfMessage(value.ProtoReflect()) + default: + if descriptor.IsExtension() { + panic(fmt.Errorf("proto3 declared messages do not support extensions: testpb.TestVersion1")) + } + panic(fmt.Errorf("message testpb.TestVersion1 does not contain field %s", descriptor.FullName())) + } +} + +// Set stores the value for a field. +// +// For a field belonging to a oneof, it implicitly clears any other field +// that may be currently set within the same oneof. +// For extension fields, it implicitly stores the provided ExtensionType. +// When setting a composite type, it is unspecified whether the stored value +// aliases the source's memory in any way. If the composite value is an +// empty, read-only value, then it panics. +// +// Set is a mutating operation and unsafe for concurrent use. +func (x *fastReflection_TestVersion1) Set(fd protoreflect.FieldDescriptor, value protoreflect.Value) { + switch fd.FullName() { + case "testpb.TestVersion1.x": + x.X = value.Int() + case "testpb.TestVersion1.a": + x.A = value.Message().Interface().(*TestVersion1) + case "testpb.TestVersion1.b": + x.B = value.Message().Interface().(*TestVersion1) + case "testpb.TestVersion1.c": + lv := value.List() + clv := lv.(*_TestVersion1_4_list) + x.C = *clv.list + case "testpb.TestVersion1.d": + lv := value.List() + clv := lv.(*_TestVersion1_5_list) + x.D = *clv.list + case "testpb.TestVersion1.e": + cv := int32(value.Int()) + x.Sum = &TestVersion1_E{E: cv} + case "testpb.TestVersion1.f": + cv := value.Message().Interface().(*TestVersion1) + x.Sum = &TestVersion1_F{F: cv} + case "testpb.TestVersion1.g": + x.G = value.Message().Interface().(*anypb.Any) + case "testpb.TestVersion1.h": + lv := value.List() + clv := lv.(*_TestVersion1_9_list) + x.H = *clv.list + case "testpb.TestVersion1.k": + x.K = value.Message().Interface().(*Customer1) + default: + if fd.IsExtension() { + panic(fmt.Errorf("proto3 declared messages do not support extensions: testpb.TestVersion1")) + } + panic(fmt.Errorf("message testpb.TestVersion1 does not contain field %s", fd.FullName())) + } +} + +// Mutable returns a mutable reference to a composite type. +// +// If the field is unpopulated, it may allocate a composite value. +// For a field belonging to a oneof, it implicitly clears any other field +// that may be currently set within the same oneof. +// For extension fields, it implicitly stores the provided ExtensionType +// if not already stored. +// It panics if the field does not contain a composite type. +// +// Mutable is a mutating operation and unsafe for concurrent use. +func (x *fastReflection_TestVersion1) Mutable(fd protoreflect.FieldDescriptor) protoreflect.Value { + switch fd.FullName() { + case "testpb.TestVersion1.a": + if x.A == nil { + x.A = new(TestVersion1) + } + return protoreflect.ValueOfMessage(x.A.ProtoReflect()) + case "testpb.TestVersion1.b": + if x.B == nil { + x.B = new(TestVersion1) + } + return protoreflect.ValueOfMessage(x.B.ProtoReflect()) + case "testpb.TestVersion1.c": + if x.C == nil { + x.C = []*TestVersion1{} + } + value := &_TestVersion1_4_list{list: &x.C} + return protoreflect.ValueOfList(value) + case "testpb.TestVersion1.d": + if x.D == nil { + x.D = []*TestVersion1{} + } + value := &_TestVersion1_5_list{list: &x.D} + return protoreflect.ValueOfList(value) + case "testpb.TestVersion1.f": + if x.Sum == nil { + value := &TestVersion1{} + oneofValue := &TestVersion1_F{F: value} + x.Sum = oneofValue + return protoreflect.ValueOfMessage(value.ProtoReflect()) + } + switch m := x.Sum.(type) { + case *TestVersion1_F: + return protoreflect.ValueOfMessage(m.F.ProtoReflect()) + default: + value := &TestVersion1{} + oneofValue := &TestVersion1_F{F: value} + x.Sum = oneofValue + return protoreflect.ValueOfMessage(value.ProtoReflect()) + } + case "testpb.TestVersion1.g": + if x.G == nil { + x.G = new(anypb.Any) + } + return protoreflect.ValueOfMessage(x.G.ProtoReflect()) + case "testpb.TestVersion1.h": + if x.H == nil { + x.H = []*TestVersion1{} + } + value := &_TestVersion1_9_list{list: &x.H} + return protoreflect.ValueOfList(value) + case "testpb.TestVersion1.k": + if x.K == nil { + x.K = new(Customer1) + } + return protoreflect.ValueOfMessage(x.K.ProtoReflect()) + case "testpb.TestVersion1.x": + panic(fmt.Errorf("field x of message testpb.TestVersion1 is not mutable")) + case "testpb.TestVersion1.e": + panic(fmt.Errorf("field e of message testpb.TestVersion1 is not mutable")) + default: + if fd.IsExtension() { + panic(fmt.Errorf("proto3 declared messages do not support extensions: testpb.TestVersion1")) + } + panic(fmt.Errorf("message testpb.TestVersion1 does not contain field %s", fd.FullName())) + } +} + +// NewField returns a new value that is assignable to the field +// for the given descriptor. For scalars, this returns the default value. +// For lists, maps, and messages, this returns a new, empty, mutable value. +func (x *fastReflection_TestVersion1) NewField(fd protoreflect.FieldDescriptor) protoreflect.Value { + switch fd.FullName() { + case "testpb.TestVersion1.x": + return protoreflect.ValueOfInt64(int64(0)) + case "testpb.TestVersion1.a": + m := new(TestVersion1) + return protoreflect.ValueOfMessage(m.ProtoReflect()) + case "testpb.TestVersion1.b": + m := new(TestVersion1) + return protoreflect.ValueOfMessage(m.ProtoReflect()) + case "testpb.TestVersion1.c": + list := []*TestVersion1{} + return protoreflect.ValueOfList(&_TestVersion1_4_list{list: &list}) + case "testpb.TestVersion1.d": + list := []*TestVersion1{} + return protoreflect.ValueOfList(&_TestVersion1_5_list{list: &list}) + case "testpb.TestVersion1.e": + return protoreflect.ValueOfInt32(int32(0)) + case "testpb.TestVersion1.f": + value := &TestVersion1{} + return protoreflect.ValueOfMessage(value.ProtoReflect()) + case "testpb.TestVersion1.g": + m := new(anypb.Any) + return protoreflect.ValueOfMessage(m.ProtoReflect()) + case "testpb.TestVersion1.h": + list := []*TestVersion1{} + return protoreflect.ValueOfList(&_TestVersion1_9_list{list: &list}) + case "testpb.TestVersion1.k": + m := new(Customer1) + return protoreflect.ValueOfMessage(m.ProtoReflect()) + default: + if fd.IsExtension() { + panic(fmt.Errorf("proto3 declared messages do not support extensions: testpb.TestVersion1")) + } + panic(fmt.Errorf("message testpb.TestVersion1 does not contain field %s", fd.FullName())) + } +} + +// WhichOneof reports which field within the oneof is populated, +// returning nil if none are populated. +// It panics if the oneof descriptor does not belong to this message. +func (x *fastReflection_TestVersion1) WhichOneof(d protoreflect.OneofDescriptor) protoreflect.FieldDescriptor { + switch d.FullName() { + case "testpb.TestVersion1.sum": + if x.Sum == nil { + return nil + } + switch x.Sum.(type) { + case *TestVersion1_E: + return x.Descriptor().Fields().ByName("e") + case *TestVersion1_F: + return x.Descriptor().Fields().ByName("f") + } + default: + panic(fmt.Errorf("%s is not a oneof field in testpb.TestVersion1", d.FullName())) + } + panic("unreachable") +} + +// GetUnknown retrieves the entire list of unknown fields. +// The caller may only mutate the contents of the RawFields +// if the mutated bytes are stored back into the message with SetUnknown. +func (x *fastReflection_TestVersion1) GetUnknown() protoreflect.RawFields { + return x.unknownFields +} + +// SetUnknown stores an entire list of unknown fields. +// The raw fields must be syntactically valid according to the wire format. +// An implementation may panic if this is not the case. +// Once stored, the caller must not mutate the content of the RawFields. +// An empty RawFields may be passed to clear the fields. +// +// SetUnknown is a mutating operation and unsafe for concurrent use. +func (x *fastReflection_TestVersion1) SetUnknown(fields protoreflect.RawFields) { + x.unknownFields = fields +} + +// IsValid reports whether the message is valid. +// +// An invalid message is an empty, read-only value. +// +// An invalid message often corresponds to a nil pointer of the concrete +// message type, but the details are implementation dependent. +// Validity is not part of the protobuf data model, and may not +// be preserved in marshaling or other operations. +func (x *fastReflection_TestVersion1) IsValid() bool { + return x != nil +} + +// ProtoMethods returns optional fastReflectionFeature-path implementations of various operations. +// This method may return nil. +// +// The returned methods type is identical to +// "google.golang.org/protobuf/runtime/protoiface".Methods. +// Consult the protoiface package documentation for details. +func (x *fastReflection_TestVersion1) ProtoMethods() *protoiface.Methods { + size := func(input protoiface.SizeInput) protoiface.SizeOutput { + x := input.Message.Interface().(*TestVersion1) + if x == nil { + return protoiface.SizeOutput{ + NoUnkeyedLiterals: input.NoUnkeyedLiterals, + Size: 0, + } + } + options := runtime.SizeInputToOptions(input) + _ = options + var n int + var l int + _ = l + if x.X != 0 { + n += 1 + runtime.Sov(uint64(x.X)) + } + if x.A != nil { + l = options.Size(x.A) + n += 1 + l + runtime.Sov(uint64(l)) + } + if x.B != nil { + l = options.Size(x.B) + n += 1 + l + runtime.Sov(uint64(l)) + } + if len(x.C) > 0 { + for _, e := range x.C { + l = options.Size(e) + n += 1 + l + runtime.Sov(uint64(l)) + } + } + if len(x.D) > 0 { + for _, e := range x.D { + l = options.Size(e) + n += 1 + l + runtime.Sov(uint64(l)) + } + } + switch x := x.Sum.(type) { + case *TestVersion1_E: + if x == nil { + break + } + n += 1 + runtime.Sov(uint64(x.E)) + case *TestVersion1_F: + if x == nil { + break + } + l = options.Size(x.F) + n += 1 + l + runtime.Sov(uint64(l)) + } + if x.G != nil { + l = options.Size(x.G) + n += 1 + l + runtime.Sov(uint64(l)) + } + if len(x.H) > 0 { + for _, e := range x.H { + l = options.Size(e) + n += 1 + l + runtime.Sov(uint64(l)) + } + } + if x.K != nil { + l = options.Size(x.K) + n += 1 + l + runtime.Sov(uint64(l)) + } + if x.unknownFields != nil { + n += len(x.unknownFields) + } + return protoiface.SizeOutput{ + NoUnkeyedLiterals: input.NoUnkeyedLiterals, + Size: n, + } + } + + marshal := func(input protoiface.MarshalInput) (protoiface.MarshalOutput, error) { + x := input.Message.Interface().(*TestVersion1) + if x == nil { + return protoiface.MarshalOutput{ + NoUnkeyedLiterals: input.NoUnkeyedLiterals, + Buf: input.Buf, + }, nil + } + options := runtime.MarshalInputToOptions(input) + _ = options + size := options.Size(x) + dAtA := make([]byte, size) + i := len(dAtA) + _ = i + var l int + _ = l + if x.unknownFields != nil { + i -= len(x.unknownFields) + copy(dAtA[i:], x.unknownFields) + } + switch x := x.Sum.(type) { + case *TestVersion1_E: + i = runtime.EncodeVarint(dAtA, i, uint64(x.E)) + i-- + dAtA[i] = 0x30 + case *TestVersion1_F: + encoded, err := options.Marshal(x.F) + if err != nil { + return protoiface.MarshalOutput{ + NoUnkeyedLiterals: input.NoUnkeyedLiterals, + Buf: input.Buf, + }, err + } + i -= len(encoded) + copy(dAtA[i:], encoded) + i = runtime.EncodeVarint(dAtA, i, uint64(len(encoded))) + i-- + dAtA[i] = 0x3a + } + if x.K != nil { + encoded, err := options.Marshal(x.K) + if err != nil { + return protoiface.MarshalOutput{ + NoUnkeyedLiterals: input.NoUnkeyedLiterals, + Buf: input.Buf, + }, err + } + i -= len(encoded) + copy(dAtA[i:], encoded) + i = runtime.EncodeVarint(dAtA, i, uint64(len(encoded))) + i-- + dAtA[i] = 0x62 + } + if len(x.H) > 0 { + for iNdEx := len(x.H) - 1; iNdEx >= 0; iNdEx-- { + encoded, err := options.Marshal(x.H[iNdEx]) + if err != nil { + return protoiface.MarshalOutput{ + NoUnkeyedLiterals: input.NoUnkeyedLiterals, + Buf: input.Buf, + }, err + } + i -= len(encoded) + copy(dAtA[i:], encoded) + i = runtime.EncodeVarint(dAtA, i, uint64(len(encoded))) + i-- + dAtA[i] = 0x4a + } + } + if x.G != nil { + encoded, err := options.Marshal(x.G) + if err != nil { + return protoiface.MarshalOutput{ + NoUnkeyedLiterals: input.NoUnkeyedLiterals, + Buf: input.Buf, + }, err + } + i -= len(encoded) + copy(dAtA[i:], encoded) + i = runtime.EncodeVarint(dAtA, i, uint64(len(encoded))) + i-- + dAtA[i] = 0x42 + } + if len(x.D) > 0 { + for iNdEx := len(x.D) - 1; iNdEx >= 0; iNdEx-- { + encoded, err := options.Marshal(x.D[iNdEx]) + if err != nil { + return protoiface.MarshalOutput{ + NoUnkeyedLiterals: input.NoUnkeyedLiterals, + Buf: input.Buf, + }, err + } + i -= len(encoded) + copy(dAtA[i:], encoded) + i = runtime.EncodeVarint(dAtA, i, uint64(len(encoded))) + i-- + dAtA[i] = 0x2a + } + } + if len(x.C) > 0 { + for iNdEx := len(x.C) - 1; iNdEx >= 0; iNdEx-- { + encoded, err := options.Marshal(x.C[iNdEx]) + if err != nil { + return protoiface.MarshalOutput{ + NoUnkeyedLiterals: input.NoUnkeyedLiterals, + Buf: input.Buf, + }, err + } + i -= len(encoded) + copy(dAtA[i:], encoded) + i = runtime.EncodeVarint(dAtA, i, uint64(len(encoded))) + i-- + dAtA[i] = 0x22 + } + } + if x.B != nil { + encoded, err := options.Marshal(x.B) + if err != nil { + return protoiface.MarshalOutput{ + NoUnkeyedLiterals: input.NoUnkeyedLiterals, + Buf: input.Buf, + }, err + } + i -= len(encoded) + copy(dAtA[i:], encoded) + i = runtime.EncodeVarint(dAtA, i, uint64(len(encoded))) + i-- + dAtA[i] = 0x1a + } + if x.A != nil { + encoded, err := options.Marshal(x.A) + if err != nil { + return protoiface.MarshalOutput{ + NoUnkeyedLiterals: input.NoUnkeyedLiterals, + Buf: input.Buf, + }, err + } + i -= len(encoded) + copy(dAtA[i:], encoded) + i = runtime.EncodeVarint(dAtA, i, uint64(len(encoded))) + i-- + dAtA[i] = 0x12 + } + if x.X != 0 { + i = runtime.EncodeVarint(dAtA, i, uint64(x.X)) + i-- + dAtA[i] = 0x8 + } + if input.Buf != nil { + input.Buf = append(input.Buf, dAtA...) + } else { + input.Buf = dAtA + } + return protoiface.MarshalOutput{ + NoUnkeyedLiterals: input.NoUnkeyedLiterals, + Buf: input.Buf, + }, nil + } + unmarshal := func(input protoiface.UnmarshalInput) (protoiface.UnmarshalOutput, error) { + x := input.Message.Interface().(*TestVersion1) + if x == nil { + return protoiface.UnmarshalOutput{ + NoUnkeyedLiterals: input.NoUnkeyedLiterals, + Flags: input.Flags, + }, nil + } + options := runtime.UnmarshalInputToOptions(input) + _ = options + dAtA := input.Buf + l := len(dAtA) + iNdEx := 0 + for iNdEx < l { + preIndex := iNdEx + var wire uint64 + for shift := uint(0); ; shift += 7 { + if shift >= 64 { + return protoiface.UnmarshalOutput{NoUnkeyedLiterals: input.NoUnkeyedLiterals, Flags: input.Flags}, runtime.ErrIntOverflow + } + if iNdEx >= l { + return protoiface.UnmarshalOutput{NoUnkeyedLiterals: input.NoUnkeyedLiterals, Flags: input.Flags}, io.ErrUnexpectedEOF + } + b := dAtA[iNdEx] + iNdEx++ + wire |= uint64(b&0x7F) << shift + if b < 0x80 { + break + } + } + fieldNum := int32(wire >> 3) + wireType := int(wire & 0x7) + if wireType == 4 { + return protoiface.UnmarshalOutput{NoUnkeyedLiterals: input.NoUnkeyedLiterals, Flags: input.Flags}, fmt.Errorf("proto: TestVersion1: wiretype end group for non-group") + } + if fieldNum <= 0 { + return protoiface.UnmarshalOutput{NoUnkeyedLiterals: input.NoUnkeyedLiterals, Flags: input.Flags}, fmt.Errorf("proto: TestVersion1: illegal tag %d (wire type %d)", fieldNum, wire) + } + switch fieldNum { + case 1: + if wireType != 0 { + return protoiface.UnmarshalOutput{NoUnkeyedLiterals: input.NoUnkeyedLiterals, Flags: input.Flags}, fmt.Errorf("proto: wrong wireType = %d for field X", wireType) + } + x.X = 0 + for shift := uint(0); ; shift += 7 { + if shift >= 64 { + return protoiface.UnmarshalOutput{NoUnkeyedLiterals: input.NoUnkeyedLiterals, Flags: input.Flags}, runtime.ErrIntOverflow + } + if iNdEx >= l { + return protoiface.UnmarshalOutput{NoUnkeyedLiterals: input.NoUnkeyedLiterals, Flags: input.Flags}, io.ErrUnexpectedEOF + } + b := dAtA[iNdEx] + iNdEx++ + x.X |= int64(b&0x7F) << shift + if b < 0x80 { + break + } + } + case 2: + if wireType != 2 { + return protoiface.UnmarshalOutput{NoUnkeyedLiterals: input.NoUnkeyedLiterals, Flags: input.Flags}, fmt.Errorf("proto: wrong wireType = %d for field A", wireType) + } + var msglen int + for shift := uint(0); ; shift += 7 { + if shift >= 64 { + return protoiface.UnmarshalOutput{NoUnkeyedLiterals: input.NoUnkeyedLiterals, Flags: input.Flags}, runtime.ErrIntOverflow + } + if iNdEx >= l { + return protoiface.UnmarshalOutput{NoUnkeyedLiterals: input.NoUnkeyedLiterals, Flags: input.Flags}, io.ErrUnexpectedEOF + } + b := dAtA[iNdEx] + iNdEx++ + msglen |= int(b&0x7F) << shift + if b < 0x80 { + break + } + } + if msglen < 0 { + return protoiface.UnmarshalOutput{NoUnkeyedLiterals: input.NoUnkeyedLiterals, Flags: input.Flags}, runtime.ErrInvalidLength + } + postIndex := iNdEx + msglen + if postIndex < 0 { + return protoiface.UnmarshalOutput{NoUnkeyedLiterals: input.NoUnkeyedLiterals, Flags: input.Flags}, runtime.ErrInvalidLength + } + if postIndex > l { + return protoiface.UnmarshalOutput{NoUnkeyedLiterals: input.NoUnkeyedLiterals, Flags: input.Flags}, io.ErrUnexpectedEOF + } + if x.A == nil { + x.A = &TestVersion1{} + } + if err := options.Unmarshal(dAtA[iNdEx:postIndex], x.A); err != nil { + return protoiface.UnmarshalOutput{NoUnkeyedLiterals: input.NoUnkeyedLiterals, Flags: input.Flags}, err + } + iNdEx = postIndex + case 3: + if wireType != 2 { + return protoiface.UnmarshalOutput{NoUnkeyedLiterals: input.NoUnkeyedLiterals, Flags: input.Flags}, fmt.Errorf("proto: wrong wireType = %d for field B", wireType) + } + var msglen int + for shift := uint(0); ; shift += 7 { + if shift >= 64 { + return protoiface.UnmarshalOutput{NoUnkeyedLiterals: input.NoUnkeyedLiterals, Flags: input.Flags}, runtime.ErrIntOverflow + } + if iNdEx >= l { + return protoiface.UnmarshalOutput{NoUnkeyedLiterals: input.NoUnkeyedLiterals, Flags: input.Flags}, io.ErrUnexpectedEOF + } + b := dAtA[iNdEx] + iNdEx++ + msglen |= int(b&0x7F) << shift + if b < 0x80 { + break + } + } + if msglen < 0 { + return protoiface.UnmarshalOutput{NoUnkeyedLiterals: input.NoUnkeyedLiterals, Flags: input.Flags}, runtime.ErrInvalidLength + } + postIndex := iNdEx + msglen + if postIndex < 0 { + return protoiface.UnmarshalOutput{NoUnkeyedLiterals: input.NoUnkeyedLiterals, Flags: input.Flags}, runtime.ErrInvalidLength + } + if postIndex > l { + return protoiface.UnmarshalOutput{NoUnkeyedLiterals: input.NoUnkeyedLiterals, Flags: input.Flags}, io.ErrUnexpectedEOF + } + if x.B == nil { + x.B = &TestVersion1{} + } + if err := options.Unmarshal(dAtA[iNdEx:postIndex], x.B); err != nil { + return protoiface.UnmarshalOutput{NoUnkeyedLiterals: input.NoUnkeyedLiterals, Flags: input.Flags}, err + } + iNdEx = postIndex + case 4: + if wireType != 2 { + return protoiface.UnmarshalOutput{NoUnkeyedLiterals: input.NoUnkeyedLiterals, Flags: input.Flags}, fmt.Errorf("proto: wrong wireType = %d for field C", wireType) + } + var msglen int + for shift := uint(0); ; shift += 7 { + if shift >= 64 { + return protoiface.UnmarshalOutput{NoUnkeyedLiterals: input.NoUnkeyedLiterals, Flags: input.Flags}, runtime.ErrIntOverflow + } + if iNdEx >= l { + return protoiface.UnmarshalOutput{NoUnkeyedLiterals: input.NoUnkeyedLiterals, Flags: input.Flags}, io.ErrUnexpectedEOF + } + b := dAtA[iNdEx] + iNdEx++ + msglen |= int(b&0x7F) << shift + if b < 0x80 { + break + } + } + if msglen < 0 { + return protoiface.UnmarshalOutput{NoUnkeyedLiterals: input.NoUnkeyedLiterals, Flags: input.Flags}, runtime.ErrInvalidLength + } + postIndex := iNdEx + msglen + if postIndex < 0 { + return protoiface.UnmarshalOutput{NoUnkeyedLiterals: input.NoUnkeyedLiterals, Flags: input.Flags}, runtime.ErrInvalidLength + } + if postIndex > l { + return protoiface.UnmarshalOutput{NoUnkeyedLiterals: input.NoUnkeyedLiterals, Flags: input.Flags}, io.ErrUnexpectedEOF + } + x.C = append(x.C, &TestVersion1{}) + if err := options.Unmarshal(dAtA[iNdEx:postIndex], x.C[len(x.C)-1]); err != nil { + return protoiface.UnmarshalOutput{NoUnkeyedLiterals: input.NoUnkeyedLiterals, Flags: input.Flags}, err + } + iNdEx = postIndex + case 5: + if wireType != 2 { + return protoiface.UnmarshalOutput{NoUnkeyedLiterals: input.NoUnkeyedLiterals, Flags: input.Flags}, fmt.Errorf("proto: wrong wireType = %d for field D", wireType) + } + var msglen int + for shift := uint(0); ; shift += 7 { + if shift >= 64 { + return protoiface.UnmarshalOutput{NoUnkeyedLiterals: input.NoUnkeyedLiterals, Flags: input.Flags}, runtime.ErrIntOverflow + } + if iNdEx >= l { + return protoiface.UnmarshalOutput{NoUnkeyedLiterals: input.NoUnkeyedLiterals, Flags: input.Flags}, io.ErrUnexpectedEOF + } + b := dAtA[iNdEx] + iNdEx++ + msglen |= int(b&0x7F) << shift + if b < 0x80 { + break + } + } + if msglen < 0 { + return protoiface.UnmarshalOutput{NoUnkeyedLiterals: input.NoUnkeyedLiterals, Flags: input.Flags}, runtime.ErrInvalidLength + } + postIndex := iNdEx + msglen + if postIndex < 0 { + return protoiface.UnmarshalOutput{NoUnkeyedLiterals: input.NoUnkeyedLiterals, Flags: input.Flags}, runtime.ErrInvalidLength + } + if postIndex > l { + return protoiface.UnmarshalOutput{NoUnkeyedLiterals: input.NoUnkeyedLiterals, Flags: input.Flags}, io.ErrUnexpectedEOF + } + x.D = append(x.D, &TestVersion1{}) + if err := options.Unmarshal(dAtA[iNdEx:postIndex], x.D[len(x.D)-1]); err != nil { + return protoiface.UnmarshalOutput{NoUnkeyedLiterals: input.NoUnkeyedLiterals, Flags: input.Flags}, err + } + iNdEx = postIndex + case 6: + if wireType != 0 { + return protoiface.UnmarshalOutput{NoUnkeyedLiterals: input.NoUnkeyedLiterals, Flags: input.Flags}, fmt.Errorf("proto: wrong wireType = %d for field E", wireType) + } + var v int32 + for shift := uint(0); ; shift += 7 { + if shift >= 64 { + return protoiface.UnmarshalOutput{NoUnkeyedLiterals: input.NoUnkeyedLiterals, Flags: input.Flags}, runtime.ErrIntOverflow + } + if iNdEx >= l { + return protoiface.UnmarshalOutput{NoUnkeyedLiterals: input.NoUnkeyedLiterals, Flags: input.Flags}, io.ErrUnexpectedEOF + } + b := dAtA[iNdEx] + iNdEx++ + v |= int32(b&0x7F) << shift + if b < 0x80 { + break + } + } + x.Sum = &TestVersion1_E{v} + case 7: + if wireType != 2 { + return protoiface.UnmarshalOutput{NoUnkeyedLiterals: input.NoUnkeyedLiterals, Flags: input.Flags}, fmt.Errorf("proto: wrong wireType = %d for field F", wireType) + } + var msglen int + for shift := uint(0); ; shift += 7 { + if shift >= 64 { + return protoiface.UnmarshalOutput{NoUnkeyedLiterals: input.NoUnkeyedLiterals, Flags: input.Flags}, runtime.ErrIntOverflow + } + if iNdEx >= l { + return protoiface.UnmarshalOutput{NoUnkeyedLiterals: input.NoUnkeyedLiterals, Flags: input.Flags}, io.ErrUnexpectedEOF + } + b := dAtA[iNdEx] + iNdEx++ + msglen |= int(b&0x7F) << shift + if b < 0x80 { + break + } + } + if msglen < 0 { + return protoiface.UnmarshalOutput{NoUnkeyedLiterals: input.NoUnkeyedLiterals, Flags: input.Flags}, runtime.ErrInvalidLength + } + postIndex := iNdEx + msglen + if postIndex < 0 { + return protoiface.UnmarshalOutput{NoUnkeyedLiterals: input.NoUnkeyedLiterals, Flags: input.Flags}, runtime.ErrInvalidLength + } + if postIndex > l { + return protoiface.UnmarshalOutput{NoUnkeyedLiterals: input.NoUnkeyedLiterals, Flags: input.Flags}, io.ErrUnexpectedEOF + } + v := &TestVersion1{} + if err := options.Unmarshal(dAtA[iNdEx:postIndex], v); err != nil { + return protoiface.UnmarshalOutput{NoUnkeyedLiterals: input.NoUnkeyedLiterals, Flags: input.Flags}, err + } + x.Sum = &TestVersion1_F{v} + iNdEx = postIndex + case 8: + if wireType != 2 { + return protoiface.UnmarshalOutput{NoUnkeyedLiterals: input.NoUnkeyedLiterals, Flags: input.Flags}, fmt.Errorf("proto: wrong wireType = %d for field G", wireType) + } + var msglen int + for shift := uint(0); ; shift += 7 { + if shift >= 64 { + return protoiface.UnmarshalOutput{NoUnkeyedLiterals: input.NoUnkeyedLiterals, Flags: input.Flags}, runtime.ErrIntOverflow + } + if iNdEx >= l { + return protoiface.UnmarshalOutput{NoUnkeyedLiterals: input.NoUnkeyedLiterals, Flags: input.Flags}, io.ErrUnexpectedEOF + } + b := dAtA[iNdEx] + iNdEx++ + msglen |= int(b&0x7F) << shift + if b < 0x80 { + break + } + } + if msglen < 0 { + return protoiface.UnmarshalOutput{NoUnkeyedLiterals: input.NoUnkeyedLiterals, Flags: input.Flags}, runtime.ErrInvalidLength + } + postIndex := iNdEx + msglen + if postIndex < 0 { + return protoiface.UnmarshalOutput{NoUnkeyedLiterals: input.NoUnkeyedLiterals, Flags: input.Flags}, runtime.ErrInvalidLength + } + if postIndex > l { + return protoiface.UnmarshalOutput{NoUnkeyedLiterals: input.NoUnkeyedLiterals, Flags: input.Flags}, io.ErrUnexpectedEOF + } + if x.G == nil { + x.G = &anypb.Any{} + } + if err := options.Unmarshal(dAtA[iNdEx:postIndex], x.G); err != nil { + return protoiface.UnmarshalOutput{NoUnkeyedLiterals: input.NoUnkeyedLiterals, Flags: input.Flags}, err + } + iNdEx = postIndex + case 9: + if wireType != 2 { + return protoiface.UnmarshalOutput{NoUnkeyedLiterals: input.NoUnkeyedLiterals, Flags: input.Flags}, fmt.Errorf("proto: wrong wireType = %d for field H", wireType) + } + var msglen int + for shift := uint(0); ; shift += 7 { + if shift >= 64 { + return protoiface.UnmarshalOutput{NoUnkeyedLiterals: input.NoUnkeyedLiterals, Flags: input.Flags}, runtime.ErrIntOverflow + } + if iNdEx >= l { + return protoiface.UnmarshalOutput{NoUnkeyedLiterals: input.NoUnkeyedLiterals, Flags: input.Flags}, io.ErrUnexpectedEOF + } + b := dAtA[iNdEx] + iNdEx++ + msglen |= int(b&0x7F) << shift + if b < 0x80 { + break + } + } + if msglen < 0 { + return protoiface.UnmarshalOutput{NoUnkeyedLiterals: input.NoUnkeyedLiterals, Flags: input.Flags}, runtime.ErrInvalidLength + } + postIndex := iNdEx + msglen + if postIndex < 0 { + return protoiface.UnmarshalOutput{NoUnkeyedLiterals: input.NoUnkeyedLiterals, Flags: input.Flags}, runtime.ErrInvalidLength + } + if postIndex > l { + return protoiface.UnmarshalOutput{NoUnkeyedLiterals: input.NoUnkeyedLiterals, Flags: input.Flags}, io.ErrUnexpectedEOF + } + x.H = append(x.H, &TestVersion1{}) + if err := options.Unmarshal(dAtA[iNdEx:postIndex], x.H[len(x.H)-1]); err != nil { + return protoiface.UnmarshalOutput{NoUnkeyedLiterals: input.NoUnkeyedLiterals, Flags: input.Flags}, err + } + iNdEx = postIndex + case 12: + if wireType != 2 { + return protoiface.UnmarshalOutput{NoUnkeyedLiterals: input.NoUnkeyedLiterals, Flags: input.Flags}, fmt.Errorf("proto: wrong wireType = %d for field K", wireType) + } + var msglen int + for shift := uint(0); ; shift += 7 { + if shift >= 64 { + return protoiface.UnmarshalOutput{NoUnkeyedLiterals: input.NoUnkeyedLiterals, Flags: input.Flags}, runtime.ErrIntOverflow + } + if iNdEx >= l { + return protoiface.UnmarshalOutput{NoUnkeyedLiterals: input.NoUnkeyedLiterals, Flags: input.Flags}, io.ErrUnexpectedEOF + } + b := dAtA[iNdEx] + iNdEx++ + msglen |= int(b&0x7F) << shift + if b < 0x80 { + break + } + } + if msglen < 0 { + return protoiface.UnmarshalOutput{NoUnkeyedLiterals: input.NoUnkeyedLiterals, Flags: input.Flags}, runtime.ErrInvalidLength + } + postIndex := iNdEx + msglen + if postIndex < 0 { + return protoiface.UnmarshalOutput{NoUnkeyedLiterals: input.NoUnkeyedLiterals, Flags: input.Flags}, runtime.ErrInvalidLength + } + if postIndex > l { + return protoiface.UnmarshalOutput{NoUnkeyedLiterals: input.NoUnkeyedLiterals, Flags: input.Flags}, io.ErrUnexpectedEOF + } + if x.K == nil { + x.K = &Customer1{} + } + if err := options.Unmarshal(dAtA[iNdEx:postIndex], x.K); err != nil { + return protoiface.UnmarshalOutput{NoUnkeyedLiterals: input.NoUnkeyedLiterals, Flags: input.Flags}, err + } + iNdEx = postIndex + default: + iNdEx = preIndex + skippy, err := runtime.Skip(dAtA[iNdEx:]) + if err != nil { + return protoiface.UnmarshalOutput{NoUnkeyedLiterals: input.NoUnkeyedLiterals, Flags: input.Flags}, err + } + if (skippy < 0) || (iNdEx+skippy) < 0 { + return protoiface.UnmarshalOutput{NoUnkeyedLiterals: input.NoUnkeyedLiterals, Flags: input.Flags}, runtime.ErrInvalidLength + } + if (iNdEx + skippy) > l { + return protoiface.UnmarshalOutput{NoUnkeyedLiterals: input.NoUnkeyedLiterals, Flags: input.Flags}, io.ErrUnexpectedEOF + } + if !options.DiscardUnknown { + x.unknownFields = append(x.unknownFields, dAtA[iNdEx:iNdEx+skippy]...) + } + iNdEx += skippy + } + } + + if iNdEx > l { + return protoiface.UnmarshalOutput{NoUnkeyedLiterals: input.NoUnkeyedLiterals, Flags: input.Flags}, io.ErrUnexpectedEOF + } + return protoiface.UnmarshalOutput{NoUnkeyedLiterals: input.NoUnkeyedLiterals, Flags: input.Flags}, nil + } + return &protoiface.Methods{ + NoUnkeyedLiterals: struct{}{}, + Flags: protoiface.SupportMarshalDeterministic | protoiface.SupportUnmarshalDiscardUnknown, + Size: size, + Marshal: marshal, + Unmarshal: unmarshal, + Merge: nil, + CheckInitialized: nil, + } +} + +var _ protoreflect.List = (*_TestVersion2_4_list)(nil) + +type _TestVersion2_4_list struct { + list *[]*TestVersion2 +} + +func (x *_TestVersion2_4_list) Len() int { + if x.list == nil { + return 0 + } + return len(*x.list) +} + +func (x *_TestVersion2_4_list) Get(i int) protoreflect.Value { + return protoreflect.ValueOfMessage((*x.list)[i].ProtoReflect()) +} + +func (x *_TestVersion2_4_list) Set(i int, value protoreflect.Value) { + valueUnwrapped := value.Message() + concreteValue := valueUnwrapped.Interface().(*TestVersion2) + (*x.list)[i] = concreteValue +} + +func (x *_TestVersion2_4_list) Append(value protoreflect.Value) { + valueUnwrapped := value.Message() + concreteValue := valueUnwrapped.Interface().(*TestVersion2) + *x.list = append(*x.list, concreteValue) +} + +func (x *_TestVersion2_4_list) AppendMutable() protoreflect.Value { + v := new(TestVersion2) + *x.list = append(*x.list, v) + return protoreflect.ValueOfMessage(v.ProtoReflect()) +} + +func (x *_TestVersion2_4_list) Truncate(n int) { + for i := n; i < len(*x.list); i++ { + (*x.list)[i] = nil + } + *x.list = (*x.list)[:n] +} + +func (x *_TestVersion2_4_list) NewElement() protoreflect.Value { + v := new(TestVersion2) + return protoreflect.ValueOfMessage(v.ProtoReflect()) +} + +func (x *_TestVersion2_4_list) IsValid() bool { + return x.list != nil +} + +var _ protoreflect.List = (*_TestVersion2_5_list)(nil) + +type _TestVersion2_5_list struct { + list *[]*TestVersion2 +} + +func (x *_TestVersion2_5_list) Len() int { + if x.list == nil { + return 0 + } + return len(*x.list) +} + +func (x *_TestVersion2_5_list) Get(i int) protoreflect.Value { + return protoreflect.ValueOfMessage((*x.list)[i].ProtoReflect()) +} + +func (x *_TestVersion2_5_list) Set(i int, value protoreflect.Value) { + valueUnwrapped := value.Message() + concreteValue := valueUnwrapped.Interface().(*TestVersion2) + (*x.list)[i] = concreteValue +} + +func (x *_TestVersion2_5_list) Append(value protoreflect.Value) { + valueUnwrapped := value.Message() + concreteValue := valueUnwrapped.Interface().(*TestVersion2) + *x.list = append(*x.list, concreteValue) +} + +func (x *_TestVersion2_5_list) AppendMutable() protoreflect.Value { + v := new(TestVersion2) + *x.list = append(*x.list, v) + return protoreflect.ValueOfMessage(v.ProtoReflect()) +} + +func (x *_TestVersion2_5_list) Truncate(n int) { + for i := n; i < len(*x.list); i++ { + (*x.list)[i] = nil + } + *x.list = (*x.list)[:n] +} + +func (x *_TestVersion2_5_list) NewElement() protoreflect.Value { + v := new(TestVersion2) + return protoreflect.ValueOfMessage(v.ProtoReflect()) +} + +func (x *_TestVersion2_5_list) IsValid() bool { + return x.list != nil +} + +var _ protoreflect.List = (*_TestVersion2_9_list)(nil) + +type _TestVersion2_9_list struct { + list *[]*TestVersion1 +} + +func (x *_TestVersion2_9_list) Len() int { + if x.list == nil { + return 0 + } + return len(*x.list) +} + +func (x *_TestVersion2_9_list) Get(i int) protoreflect.Value { + return protoreflect.ValueOfMessage((*x.list)[i].ProtoReflect()) +} + +func (x *_TestVersion2_9_list) Set(i int, value protoreflect.Value) { + valueUnwrapped := value.Message() + concreteValue := valueUnwrapped.Interface().(*TestVersion1) + (*x.list)[i] = concreteValue +} + +func (x *_TestVersion2_9_list) Append(value protoreflect.Value) { + valueUnwrapped := value.Message() + concreteValue := valueUnwrapped.Interface().(*TestVersion1) + *x.list = append(*x.list, concreteValue) +} + +func (x *_TestVersion2_9_list) AppendMutable() protoreflect.Value { + v := new(TestVersion1) + *x.list = append(*x.list, v) + return protoreflect.ValueOfMessage(v.ProtoReflect()) +} + +func (x *_TestVersion2_9_list) Truncate(n int) { + for i := n; i < len(*x.list); i++ { + (*x.list)[i] = nil + } + *x.list = (*x.list)[:n] +} + +func (x *_TestVersion2_9_list) NewElement() protoreflect.Value { + v := new(TestVersion1) + return protoreflect.ValueOfMessage(v.ProtoReflect()) +} + +func (x *_TestVersion2_9_list) IsValid() bool { + return x.list != nil +} + +var ( + md_TestVersion2 protoreflect.MessageDescriptor + fd_TestVersion2_x protoreflect.FieldDescriptor + fd_TestVersion2_a protoreflect.FieldDescriptor + fd_TestVersion2_b protoreflect.FieldDescriptor + fd_TestVersion2_c protoreflect.FieldDescriptor + fd_TestVersion2_d protoreflect.FieldDescriptor + fd_TestVersion2_e protoreflect.FieldDescriptor + fd_TestVersion2_f protoreflect.FieldDescriptor + fd_TestVersion2_g protoreflect.FieldDescriptor + fd_TestVersion2_h protoreflect.FieldDescriptor + fd_TestVersion2_k protoreflect.FieldDescriptor + fd_TestVersion2_new_field protoreflect.FieldDescriptor +) + +func init() { + file_unknownproto_proto_init() + md_TestVersion2 = File_unknownproto_proto.Messages().ByName("TestVersion2") + fd_TestVersion2_x = md_TestVersion2.Fields().ByName("x") + fd_TestVersion2_a = md_TestVersion2.Fields().ByName("a") + fd_TestVersion2_b = md_TestVersion2.Fields().ByName("b") + fd_TestVersion2_c = md_TestVersion2.Fields().ByName("c") + fd_TestVersion2_d = md_TestVersion2.Fields().ByName("d") + fd_TestVersion2_e = md_TestVersion2.Fields().ByName("e") + fd_TestVersion2_f = md_TestVersion2.Fields().ByName("f") + fd_TestVersion2_g = md_TestVersion2.Fields().ByName("g") + fd_TestVersion2_h = md_TestVersion2.Fields().ByName("h") + fd_TestVersion2_k = md_TestVersion2.Fields().ByName("k") + fd_TestVersion2_new_field = md_TestVersion2.Fields().ByName("new_field") +} + +var _ protoreflect.Message = (*fastReflection_TestVersion2)(nil) + +type fastReflection_TestVersion2 TestVersion2 + +func (x *TestVersion2) ProtoReflect() protoreflect.Message { + return (*fastReflection_TestVersion2)(x) +} + +func (x *TestVersion2) slowProtoReflect() protoreflect.Message { + mi := &file_unknownproto_proto_msgTypes[12] + if protoimpl.UnsafeEnabled && x != nil { + ms := protoimpl.X.MessageStateOf(protoimpl.Pointer(x)) + if ms.LoadMessageInfo() == nil { + ms.StoreMessageInfo(mi) + } + return ms + } + return mi.MessageOf(x) +} + +var _fastReflection_TestVersion2_messageType fastReflection_TestVersion2_messageType +var _ protoreflect.MessageType = fastReflection_TestVersion2_messageType{} + +type fastReflection_TestVersion2_messageType struct{} + +func (x fastReflection_TestVersion2_messageType) Zero() protoreflect.Message { + return (*fastReflection_TestVersion2)(nil) +} +func (x fastReflection_TestVersion2_messageType) New() protoreflect.Message { + return new(fastReflection_TestVersion2) +} +func (x fastReflection_TestVersion2_messageType) Descriptor() protoreflect.MessageDescriptor { + return md_TestVersion2 +} + +// Descriptor returns message descriptor, which contains only the protobuf +// type information for the message. +func (x *fastReflection_TestVersion2) Descriptor() protoreflect.MessageDescriptor { + return md_TestVersion2 +} + +// Type returns the message type, which encapsulates both Go and protobuf +// type information. If the Go type information is not needed, +// it is recommended that the message descriptor be used instead. +func (x *fastReflection_TestVersion2) Type() protoreflect.MessageType { + return _fastReflection_TestVersion2_messageType +} + +// New returns a newly allocated and mutable empty message. +func (x *fastReflection_TestVersion2) New() protoreflect.Message { + return new(fastReflection_TestVersion2) +} + +// Interface unwraps the message reflection interface and +// returns the underlying ProtoMessage interface. +func (x *fastReflection_TestVersion2) Interface() protoreflect.ProtoMessage { + return (*TestVersion2)(x) +} + +// Range iterates over every populated field in an undefined order, +// calling f for each field descriptor and value encountered. +// Range returns immediately if f returns false. +// While iterating, mutating operations may only be performed +// on the current field descriptor. +func (x *fastReflection_TestVersion2) Range(f func(protoreflect.FieldDescriptor, protoreflect.Value) bool) { + if x.X != int64(0) { + value := protoreflect.ValueOfInt64(x.X) + if !f(fd_TestVersion2_x, value) { + return + } + } + if x.A != nil { + value := protoreflect.ValueOfMessage(x.A.ProtoReflect()) + if !f(fd_TestVersion2_a, value) { + return + } + } + if x.B != nil { + value := protoreflect.ValueOfMessage(x.B.ProtoReflect()) + if !f(fd_TestVersion2_b, value) { + return + } + } + if len(x.C) != 0 { + value := protoreflect.ValueOfList(&_TestVersion2_4_list{list: &x.C}) + if !f(fd_TestVersion2_c, value) { + return + } + } + if len(x.D) != 0 { + value := protoreflect.ValueOfList(&_TestVersion2_5_list{list: &x.D}) + if !f(fd_TestVersion2_d, value) { + return + } + } + if x.Sum != nil { + switch o := x.Sum.(type) { + case *TestVersion2_E: + v := o.E + value := protoreflect.ValueOfInt32(v) + if !f(fd_TestVersion2_e, value) { + return + } + case *TestVersion2_F: + v := o.F + value := protoreflect.ValueOfMessage(v.ProtoReflect()) + if !f(fd_TestVersion2_f, value) { + return + } + } + } + if x.G != nil { + value := protoreflect.ValueOfMessage(x.G.ProtoReflect()) + if !f(fd_TestVersion2_g, value) { + return + } + } + if len(x.H) != 0 { + value := protoreflect.ValueOfList(&_TestVersion2_9_list{list: &x.H}) + if !f(fd_TestVersion2_h, value) { + return + } + } + if x.K != nil { + value := protoreflect.ValueOfMessage(x.K.ProtoReflect()) + if !f(fd_TestVersion2_k, value) { + return + } + } + if x.NewField_ != uint64(0) { + value := protoreflect.ValueOfUint64(x.NewField_) + if !f(fd_TestVersion2_new_field, value) { + return + } + } +} + +// Has reports whether a field is populated. +// +// Some fields have the property of nullability where it is possible to +// distinguish between the default value of a field and whether the field +// was explicitly populated with the default value. Singular message fields, +// member fields of a oneof, and proto2 scalar fields are nullable. Such +// fields are populated only if explicitly set. +// +// In other cases (aside from the nullable cases above), +// a proto3 scalar field is populated if it contains a non-zero value, and +// a repeated field is populated if it is non-empty. +func (x *fastReflection_TestVersion2) Has(fd protoreflect.FieldDescriptor) bool { + switch fd.FullName() { + case "testpb.TestVersion2.x": + return x.X != int64(0) + case "testpb.TestVersion2.a": + return x.A != nil + case "testpb.TestVersion2.b": + return x.B != nil + case "testpb.TestVersion2.c": + return len(x.C) != 0 + case "testpb.TestVersion2.d": + return len(x.D) != 0 + case "testpb.TestVersion2.e": + if x.Sum == nil { + return false + } else if _, ok := x.Sum.(*TestVersion2_E); ok { + return true + } else { + return false + } + case "testpb.TestVersion2.f": + if x.Sum == nil { + return false + } else if _, ok := x.Sum.(*TestVersion2_F); ok { + return true + } else { + return false + } + case "testpb.TestVersion2.g": + return x.G != nil + case "testpb.TestVersion2.h": + return len(x.H) != 0 + case "testpb.TestVersion2.k": + return x.K != nil + case "testpb.TestVersion2.new_field": + return x.NewField_ != uint64(0) + default: + if fd.IsExtension() { + panic(fmt.Errorf("proto3 declared messages do not support extensions: testpb.TestVersion2")) + } + panic(fmt.Errorf("message testpb.TestVersion2 does not contain field %s", fd.FullName())) + } +} + +// Clear clears the field such that a subsequent Has call reports false. +// +// Clearing an extension field clears both the extension type and value +// associated with the given field number. +// +// Clear is a mutating operation and unsafe for concurrent use. +func (x *fastReflection_TestVersion2) Clear(fd protoreflect.FieldDescriptor) { + switch fd.FullName() { + case "testpb.TestVersion2.x": + x.X = int64(0) + case "testpb.TestVersion2.a": + x.A = nil + case "testpb.TestVersion2.b": + x.B = nil + case "testpb.TestVersion2.c": + x.C = nil + case "testpb.TestVersion2.d": + x.D = nil + case "testpb.TestVersion2.e": + x.Sum = nil + case "testpb.TestVersion2.f": + x.Sum = nil + case "testpb.TestVersion2.g": + x.G = nil + case "testpb.TestVersion2.h": + x.H = nil + case "testpb.TestVersion2.k": + x.K = nil + case "testpb.TestVersion2.new_field": + x.NewField_ = uint64(0) + default: + if fd.IsExtension() { + panic(fmt.Errorf("proto3 declared messages do not support extensions: testpb.TestVersion2")) + } + panic(fmt.Errorf("message testpb.TestVersion2 does not contain field %s", fd.FullName())) + } +} + +// Get retrieves the value for a field. +// +// For unpopulated scalars, it returns the default value, where +// the default value of a bytes scalar is guaranteed to be a copy. +// For unpopulated composite types, it returns an empty, read-only view +// of the value; to obtain a mutable reference, use Mutable. +func (x *fastReflection_TestVersion2) Get(descriptor protoreflect.FieldDescriptor) protoreflect.Value { + switch descriptor.FullName() { + case "testpb.TestVersion2.x": + value := x.X + return protoreflect.ValueOfInt64(value) + case "testpb.TestVersion2.a": + value := x.A + return protoreflect.ValueOfMessage(value.ProtoReflect()) + case "testpb.TestVersion2.b": + value := x.B + return protoreflect.ValueOfMessage(value.ProtoReflect()) + case "testpb.TestVersion2.c": + if len(x.C) == 0 { + return protoreflect.ValueOfList(&_TestVersion2_4_list{}) + } + listValue := &_TestVersion2_4_list{list: &x.C} + return protoreflect.ValueOfList(listValue) + case "testpb.TestVersion2.d": + if len(x.D) == 0 { + return protoreflect.ValueOfList(&_TestVersion2_5_list{}) + } + listValue := &_TestVersion2_5_list{list: &x.D} + return protoreflect.ValueOfList(listValue) + case "testpb.TestVersion2.e": + if x.Sum == nil { + return protoreflect.ValueOfInt32(int32(0)) + } else if v, ok := x.Sum.(*TestVersion2_E); ok { + return protoreflect.ValueOfInt32(v.E) + } else { + return protoreflect.ValueOfInt32(int32(0)) + } + case "testpb.TestVersion2.f": + if x.Sum == nil { + return protoreflect.ValueOfMessage((*TestVersion2)(nil).ProtoReflect()) + } else if v, ok := x.Sum.(*TestVersion2_F); ok { + return protoreflect.ValueOfMessage(v.F.ProtoReflect()) + } else { + return protoreflect.ValueOfMessage((*TestVersion2)(nil).ProtoReflect()) + } + case "testpb.TestVersion2.g": + value := x.G + return protoreflect.ValueOfMessage(value.ProtoReflect()) + case "testpb.TestVersion2.h": + if len(x.H) == 0 { + return protoreflect.ValueOfList(&_TestVersion2_9_list{}) + } + listValue := &_TestVersion2_9_list{list: &x.H} + return protoreflect.ValueOfList(listValue) + case "testpb.TestVersion2.k": + value := x.K + return protoreflect.ValueOfMessage(value.ProtoReflect()) + case "testpb.TestVersion2.new_field": + value := x.NewField_ + return protoreflect.ValueOfUint64(value) + default: + if descriptor.IsExtension() { + panic(fmt.Errorf("proto3 declared messages do not support extensions: testpb.TestVersion2")) + } + panic(fmt.Errorf("message testpb.TestVersion2 does not contain field %s", descriptor.FullName())) + } +} + +// Set stores the value for a field. +// +// For a field belonging to a oneof, it implicitly clears any other field +// that may be currently set within the same oneof. +// For extension fields, it implicitly stores the provided ExtensionType. +// When setting a composite type, it is unspecified whether the stored value +// aliases the source's memory in any way. If the composite value is an +// empty, read-only value, then it panics. +// +// Set is a mutating operation and unsafe for concurrent use. +func (x *fastReflection_TestVersion2) Set(fd protoreflect.FieldDescriptor, value protoreflect.Value) { + switch fd.FullName() { + case "testpb.TestVersion2.x": + x.X = value.Int() + case "testpb.TestVersion2.a": + x.A = value.Message().Interface().(*TestVersion2) + case "testpb.TestVersion2.b": + x.B = value.Message().Interface().(*TestVersion2) + case "testpb.TestVersion2.c": + lv := value.List() + clv := lv.(*_TestVersion2_4_list) + x.C = *clv.list + case "testpb.TestVersion2.d": + lv := value.List() + clv := lv.(*_TestVersion2_5_list) + x.D = *clv.list + case "testpb.TestVersion2.e": + cv := int32(value.Int()) + x.Sum = &TestVersion2_E{E: cv} + case "testpb.TestVersion2.f": + cv := value.Message().Interface().(*TestVersion2) + x.Sum = &TestVersion2_F{F: cv} + case "testpb.TestVersion2.g": + x.G = value.Message().Interface().(*anypb.Any) + case "testpb.TestVersion2.h": + lv := value.List() + clv := lv.(*_TestVersion2_9_list) + x.H = *clv.list + case "testpb.TestVersion2.k": + x.K = value.Message().Interface().(*Customer1) + case "testpb.TestVersion2.new_field": + x.NewField_ = value.Uint() + default: + if fd.IsExtension() { + panic(fmt.Errorf("proto3 declared messages do not support extensions: testpb.TestVersion2")) + } + panic(fmt.Errorf("message testpb.TestVersion2 does not contain field %s", fd.FullName())) + } +} + +// Mutable returns a mutable reference to a composite type. +// +// If the field is unpopulated, it may allocate a composite value. +// For a field belonging to a oneof, it implicitly clears any other field +// that may be currently set within the same oneof. +// For extension fields, it implicitly stores the provided ExtensionType +// if not already stored. +// It panics if the field does not contain a composite type. +// +// Mutable is a mutating operation and unsafe for concurrent use. +func (x *fastReflection_TestVersion2) Mutable(fd protoreflect.FieldDescriptor) protoreflect.Value { + switch fd.FullName() { + case "testpb.TestVersion2.a": + if x.A == nil { + x.A = new(TestVersion2) + } + return protoreflect.ValueOfMessage(x.A.ProtoReflect()) + case "testpb.TestVersion2.b": + if x.B == nil { + x.B = new(TestVersion2) + } + return protoreflect.ValueOfMessage(x.B.ProtoReflect()) + case "testpb.TestVersion2.c": + if x.C == nil { + x.C = []*TestVersion2{} + } + value := &_TestVersion2_4_list{list: &x.C} + return protoreflect.ValueOfList(value) + case "testpb.TestVersion2.d": + if x.D == nil { + x.D = []*TestVersion2{} + } + value := &_TestVersion2_5_list{list: &x.D} + return protoreflect.ValueOfList(value) + case "testpb.TestVersion2.f": + if x.Sum == nil { + value := &TestVersion2{} + oneofValue := &TestVersion2_F{F: value} + x.Sum = oneofValue + return protoreflect.ValueOfMessage(value.ProtoReflect()) + } + switch m := x.Sum.(type) { + case *TestVersion2_F: + return protoreflect.ValueOfMessage(m.F.ProtoReflect()) + default: + value := &TestVersion2{} + oneofValue := &TestVersion2_F{F: value} + x.Sum = oneofValue + return protoreflect.ValueOfMessage(value.ProtoReflect()) + } + case "testpb.TestVersion2.g": + if x.G == nil { + x.G = new(anypb.Any) + } + return protoreflect.ValueOfMessage(x.G.ProtoReflect()) + case "testpb.TestVersion2.h": + if x.H == nil { + x.H = []*TestVersion1{} + } + value := &_TestVersion2_9_list{list: &x.H} + return protoreflect.ValueOfList(value) + case "testpb.TestVersion2.k": + if x.K == nil { + x.K = new(Customer1) + } + return protoreflect.ValueOfMessage(x.K.ProtoReflect()) + case "testpb.TestVersion2.x": + panic(fmt.Errorf("field x of message testpb.TestVersion2 is not mutable")) + case "testpb.TestVersion2.e": + panic(fmt.Errorf("field e of message testpb.TestVersion2 is not mutable")) + case "testpb.TestVersion2.new_field": + panic(fmt.Errorf("field new_field of message testpb.TestVersion2 is not mutable")) + default: + if fd.IsExtension() { + panic(fmt.Errorf("proto3 declared messages do not support extensions: testpb.TestVersion2")) + } + panic(fmt.Errorf("message testpb.TestVersion2 does not contain field %s", fd.FullName())) + } +} + +// NewField returns a new value that is assignable to the field +// for the given descriptor. For scalars, this returns the default value. +// For lists, maps, and messages, this returns a new, empty, mutable value. +func (x *fastReflection_TestVersion2) NewField(fd protoreflect.FieldDescriptor) protoreflect.Value { + switch fd.FullName() { + case "testpb.TestVersion2.x": + return protoreflect.ValueOfInt64(int64(0)) + case "testpb.TestVersion2.a": + m := new(TestVersion2) + return protoreflect.ValueOfMessage(m.ProtoReflect()) + case "testpb.TestVersion2.b": + m := new(TestVersion2) + return protoreflect.ValueOfMessage(m.ProtoReflect()) + case "testpb.TestVersion2.c": + list := []*TestVersion2{} + return protoreflect.ValueOfList(&_TestVersion2_4_list{list: &list}) + case "testpb.TestVersion2.d": + list := []*TestVersion2{} + return protoreflect.ValueOfList(&_TestVersion2_5_list{list: &list}) + case "testpb.TestVersion2.e": + return protoreflect.ValueOfInt32(int32(0)) + case "testpb.TestVersion2.f": + value := &TestVersion2{} + return protoreflect.ValueOfMessage(value.ProtoReflect()) + case "testpb.TestVersion2.g": + m := new(anypb.Any) + return protoreflect.ValueOfMessage(m.ProtoReflect()) + case "testpb.TestVersion2.h": + list := []*TestVersion1{} + return protoreflect.ValueOfList(&_TestVersion2_9_list{list: &list}) + case "testpb.TestVersion2.k": + m := new(Customer1) + return protoreflect.ValueOfMessage(m.ProtoReflect()) + case "testpb.TestVersion2.new_field": + return protoreflect.ValueOfUint64(uint64(0)) + default: + if fd.IsExtension() { + panic(fmt.Errorf("proto3 declared messages do not support extensions: testpb.TestVersion2")) + } + panic(fmt.Errorf("message testpb.TestVersion2 does not contain field %s", fd.FullName())) + } +} + +// WhichOneof reports which field within the oneof is populated, +// returning nil if none are populated. +// It panics if the oneof descriptor does not belong to this message. +func (x *fastReflection_TestVersion2) WhichOneof(d protoreflect.OneofDescriptor) protoreflect.FieldDescriptor { + switch d.FullName() { + case "testpb.TestVersion2.sum": + if x.Sum == nil { + return nil + } + switch x.Sum.(type) { + case *TestVersion2_E: + return x.Descriptor().Fields().ByName("e") + case *TestVersion2_F: + return x.Descriptor().Fields().ByName("f") + } + default: + panic(fmt.Errorf("%s is not a oneof field in testpb.TestVersion2", d.FullName())) + } + panic("unreachable") +} + +// GetUnknown retrieves the entire list of unknown fields. +// The caller may only mutate the contents of the RawFields +// if the mutated bytes are stored back into the message with SetUnknown. +func (x *fastReflection_TestVersion2) GetUnknown() protoreflect.RawFields { + return x.unknownFields +} + +// SetUnknown stores an entire list of unknown fields. +// The raw fields must be syntactically valid according to the wire format. +// An implementation may panic if this is not the case. +// Once stored, the caller must not mutate the content of the RawFields. +// An empty RawFields may be passed to clear the fields. +// +// SetUnknown is a mutating operation and unsafe for concurrent use. +func (x *fastReflection_TestVersion2) SetUnknown(fields protoreflect.RawFields) { + x.unknownFields = fields +} + +// IsValid reports whether the message is valid. +// +// An invalid message is an empty, read-only value. +// +// An invalid message often corresponds to a nil pointer of the concrete +// message type, but the details are implementation dependent. +// Validity is not part of the protobuf data model, and may not +// be preserved in marshaling or other operations. +func (x *fastReflection_TestVersion2) IsValid() bool { + return x != nil +} + +// ProtoMethods returns optional fastReflectionFeature-path implementations of various operations. +// This method may return nil. +// +// The returned methods type is identical to +// "google.golang.org/protobuf/runtime/protoiface".Methods. +// Consult the protoiface package documentation for details. +func (x *fastReflection_TestVersion2) ProtoMethods() *protoiface.Methods { + size := func(input protoiface.SizeInput) protoiface.SizeOutput { + x := input.Message.Interface().(*TestVersion2) + if x == nil { + return protoiface.SizeOutput{ + NoUnkeyedLiterals: input.NoUnkeyedLiterals, + Size: 0, + } + } + options := runtime.SizeInputToOptions(input) + _ = options + var n int + var l int + _ = l + if x.X != 0 { + n += 1 + runtime.Sov(uint64(x.X)) + } + if x.A != nil { + l = options.Size(x.A) + n += 1 + l + runtime.Sov(uint64(l)) + } + if x.B != nil { + l = options.Size(x.B) + n += 1 + l + runtime.Sov(uint64(l)) + } + if len(x.C) > 0 { + for _, e := range x.C { + l = options.Size(e) + n += 1 + l + runtime.Sov(uint64(l)) + } + } + if len(x.D) > 0 { + for _, e := range x.D { + l = options.Size(e) + n += 1 + l + runtime.Sov(uint64(l)) + } + } + switch x := x.Sum.(type) { + case *TestVersion2_E: + if x == nil { + break + } + n += 1 + runtime.Sov(uint64(x.E)) + case *TestVersion2_F: + if x == nil { + break + } + l = options.Size(x.F) + n += 1 + l + runtime.Sov(uint64(l)) + } + if x.G != nil { + l = options.Size(x.G) + n += 1 + l + runtime.Sov(uint64(l)) + } + if len(x.H) > 0 { + for _, e := range x.H { + l = options.Size(e) + n += 1 + l + runtime.Sov(uint64(l)) + } + } + if x.K != nil { + l = options.Size(x.K) + n += 1 + l + runtime.Sov(uint64(l)) + } + if x.NewField_ != 0 { + n += 2 + runtime.Sov(uint64(x.NewField_)) + } + if x.unknownFields != nil { + n += len(x.unknownFields) + } + return protoiface.SizeOutput{ + NoUnkeyedLiterals: input.NoUnkeyedLiterals, + Size: n, + } + } + + marshal := func(input protoiface.MarshalInput) (protoiface.MarshalOutput, error) { + x := input.Message.Interface().(*TestVersion2) + if x == nil { + return protoiface.MarshalOutput{ + NoUnkeyedLiterals: input.NoUnkeyedLiterals, + Buf: input.Buf, + }, nil + } + options := runtime.MarshalInputToOptions(input) + _ = options + size := options.Size(x) + dAtA := make([]byte, size) + i := len(dAtA) + _ = i + var l int + _ = l + if x.unknownFields != nil { + i -= len(x.unknownFields) + copy(dAtA[i:], x.unknownFields) + } + switch x := x.Sum.(type) { + case *TestVersion2_E: + i = runtime.EncodeVarint(dAtA, i, uint64(x.E)) + i-- + dAtA[i] = 0x30 + case *TestVersion2_F: + encoded, err := options.Marshal(x.F) + if err != nil { + return protoiface.MarshalOutput{ + NoUnkeyedLiterals: input.NoUnkeyedLiterals, + Buf: input.Buf, + }, err + } + i -= len(encoded) + copy(dAtA[i:], encoded) + i = runtime.EncodeVarint(dAtA, i, uint64(len(encoded))) + i-- + dAtA[i] = 0x3a + } + if x.NewField_ != 0 { + i = runtime.EncodeVarint(dAtA, i, uint64(x.NewField_)) + i-- + dAtA[i] = 0x1 + i-- + dAtA[i] = 0xc8 + } + if x.K != nil { + encoded, err := options.Marshal(x.K) + if err != nil { + return protoiface.MarshalOutput{ + NoUnkeyedLiterals: input.NoUnkeyedLiterals, + Buf: input.Buf, + }, err + } + i -= len(encoded) + copy(dAtA[i:], encoded) + i = runtime.EncodeVarint(dAtA, i, uint64(len(encoded))) + i-- + dAtA[i] = 0x62 + } + if len(x.H) > 0 { + for iNdEx := len(x.H) - 1; iNdEx >= 0; iNdEx-- { + encoded, err := options.Marshal(x.H[iNdEx]) + if err != nil { + return protoiface.MarshalOutput{ + NoUnkeyedLiterals: input.NoUnkeyedLiterals, + Buf: input.Buf, + }, err + } + i -= len(encoded) + copy(dAtA[i:], encoded) + i = runtime.EncodeVarint(dAtA, i, uint64(len(encoded))) + i-- + dAtA[i] = 0x4a + } + } + if x.G != nil { + encoded, err := options.Marshal(x.G) + if err != nil { + return protoiface.MarshalOutput{ + NoUnkeyedLiterals: input.NoUnkeyedLiterals, + Buf: input.Buf, + }, err + } + i -= len(encoded) + copy(dAtA[i:], encoded) + i = runtime.EncodeVarint(dAtA, i, uint64(len(encoded))) + i-- + dAtA[i] = 0x42 + } + if len(x.D) > 0 { + for iNdEx := len(x.D) - 1; iNdEx >= 0; iNdEx-- { + encoded, err := options.Marshal(x.D[iNdEx]) + if err != nil { + return protoiface.MarshalOutput{ + NoUnkeyedLiterals: input.NoUnkeyedLiterals, + Buf: input.Buf, + }, err + } + i -= len(encoded) + copy(dAtA[i:], encoded) + i = runtime.EncodeVarint(dAtA, i, uint64(len(encoded))) + i-- + dAtA[i] = 0x2a + } + } + if len(x.C) > 0 { + for iNdEx := len(x.C) - 1; iNdEx >= 0; iNdEx-- { + encoded, err := options.Marshal(x.C[iNdEx]) + if err != nil { + return protoiface.MarshalOutput{ + NoUnkeyedLiterals: input.NoUnkeyedLiterals, + Buf: input.Buf, + }, err + } + i -= len(encoded) + copy(dAtA[i:], encoded) + i = runtime.EncodeVarint(dAtA, i, uint64(len(encoded))) + i-- + dAtA[i] = 0x22 + } + } + if x.B != nil { + encoded, err := options.Marshal(x.B) + if err != nil { + return protoiface.MarshalOutput{ + NoUnkeyedLiterals: input.NoUnkeyedLiterals, + Buf: input.Buf, + }, err + } + i -= len(encoded) + copy(dAtA[i:], encoded) + i = runtime.EncodeVarint(dAtA, i, uint64(len(encoded))) + i-- + dAtA[i] = 0x1a + } + if x.A != nil { + encoded, err := options.Marshal(x.A) + if err != nil { + return protoiface.MarshalOutput{ + NoUnkeyedLiterals: input.NoUnkeyedLiterals, + Buf: input.Buf, + }, err + } + i -= len(encoded) + copy(dAtA[i:], encoded) + i = runtime.EncodeVarint(dAtA, i, uint64(len(encoded))) + i-- + dAtA[i] = 0x12 + } + if x.X != 0 { + i = runtime.EncodeVarint(dAtA, i, uint64(x.X)) + i-- + dAtA[i] = 0x8 + } + if input.Buf != nil { + input.Buf = append(input.Buf, dAtA...) + } else { + input.Buf = dAtA + } + return protoiface.MarshalOutput{ + NoUnkeyedLiterals: input.NoUnkeyedLiterals, + Buf: input.Buf, + }, nil + } + unmarshal := func(input protoiface.UnmarshalInput) (protoiface.UnmarshalOutput, error) { + x := input.Message.Interface().(*TestVersion2) + if x == nil { + return protoiface.UnmarshalOutput{ + NoUnkeyedLiterals: input.NoUnkeyedLiterals, + Flags: input.Flags, + }, nil + } + options := runtime.UnmarshalInputToOptions(input) + _ = options + dAtA := input.Buf + l := len(dAtA) + iNdEx := 0 + for iNdEx < l { + preIndex := iNdEx + var wire uint64 + for shift := uint(0); ; shift += 7 { + if shift >= 64 { + return protoiface.UnmarshalOutput{NoUnkeyedLiterals: input.NoUnkeyedLiterals, Flags: input.Flags}, runtime.ErrIntOverflow + } + if iNdEx >= l { + return protoiface.UnmarshalOutput{NoUnkeyedLiterals: input.NoUnkeyedLiterals, Flags: input.Flags}, io.ErrUnexpectedEOF + } + b := dAtA[iNdEx] + iNdEx++ + wire |= uint64(b&0x7F) << shift + if b < 0x80 { + break + } + } + fieldNum := int32(wire >> 3) + wireType := int(wire & 0x7) + if wireType == 4 { + return protoiface.UnmarshalOutput{NoUnkeyedLiterals: input.NoUnkeyedLiterals, Flags: input.Flags}, fmt.Errorf("proto: TestVersion2: wiretype end group for non-group") + } + if fieldNum <= 0 { + return protoiface.UnmarshalOutput{NoUnkeyedLiterals: input.NoUnkeyedLiterals, Flags: input.Flags}, fmt.Errorf("proto: TestVersion2: illegal tag %d (wire type %d)", fieldNum, wire) + } + switch fieldNum { + case 1: + if wireType != 0 { + return protoiface.UnmarshalOutput{NoUnkeyedLiterals: input.NoUnkeyedLiterals, Flags: input.Flags}, fmt.Errorf("proto: wrong wireType = %d for field X", wireType) + } + x.X = 0 + for shift := uint(0); ; shift += 7 { + if shift >= 64 { + return protoiface.UnmarshalOutput{NoUnkeyedLiterals: input.NoUnkeyedLiterals, Flags: input.Flags}, runtime.ErrIntOverflow + } + if iNdEx >= l { + return protoiface.UnmarshalOutput{NoUnkeyedLiterals: input.NoUnkeyedLiterals, Flags: input.Flags}, io.ErrUnexpectedEOF + } + b := dAtA[iNdEx] + iNdEx++ + x.X |= int64(b&0x7F) << shift + if b < 0x80 { + break + } + } + case 2: + if wireType != 2 { + return protoiface.UnmarshalOutput{NoUnkeyedLiterals: input.NoUnkeyedLiterals, Flags: input.Flags}, fmt.Errorf("proto: wrong wireType = %d for field A", wireType) + } + var msglen int + for shift := uint(0); ; shift += 7 { + if shift >= 64 { + return protoiface.UnmarshalOutput{NoUnkeyedLiterals: input.NoUnkeyedLiterals, Flags: input.Flags}, runtime.ErrIntOverflow + } + if iNdEx >= l { + return protoiface.UnmarshalOutput{NoUnkeyedLiterals: input.NoUnkeyedLiterals, Flags: input.Flags}, io.ErrUnexpectedEOF + } + b := dAtA[iNdEx] + iNdEx++ + msglen |= int(b&0x7F) << shift + if b < 0x80 { + break + } + } + if msglen < 0 { + return protoiface.UnmarshalOutput{NoUnkeyedLiterals: input.NoUnkeyedLiterals, Flags: input.Flags}, runtime.ErrInvalidLength + } + postIndex := iNdEx + msglen + if postIndex < 0 { + return protoiface.UnmarshalOutput{NoUnkeyedLiterals: input.NoUnkeyedLiterals, Flags: input.Flags}, runtime.ErrInvalidLength + } + if postIndex > l { + return protoiface.UnmarshalOutput{NoUnkeyedLiterals: input.NoUnkeyedLiterals, Flags: input.Flags}, io.ErrUnexpectedEOF + } + if x.A == nil { + x.A = &TestVersion2{} + } + if err := options.Unmarshal(dAtA[iNdEx:postIndex], x.A); err != nil { + return protoiface.UnmarshalOutput{NoUnkeyedLiterals: input.NoUnkeyedLiterals, Flags: input.Flags}, err + } + iNdEx = postIndex + case 3: + if wireType != 2 { + return protoiface.UnmarshalOutput{NoUnkeyedLiterals: input.NoUnkeyedLiterals, Flags: input.Flags}, fmt.Errorf("proto: wrong wireType = %d for field B", wireType) + } + var msglen int + for shift := uint(0); ; shift += 7 { + if shift >= 64 { + return protoiface.UnmarshalOutput{NoUnkeyedLiterals: input.NoUnkeyedLiterals, Flags: input.Flags}, runtime.ErrIntOverflow + } + if iNdEx >= l { + return protoiface.UnmarshalOutput{NoUnkeyedLiterals: input.NoUnkeyedLiterals, Flags: input.Flags}, io.ErrUnexpectedEOF + } + b := dAtA[iNdEx] + iNdEx++ + msglen |= int(b&0x7F) << shift + if b < 0x80 { + break + } + } + if msglen < 0 { + return protoiface.UnmarshalOutput{NoUnkeyedLiterals: input.NoUnkeyedLiterals, Flags: input.Flags}, runtime.ErrInvalidLength + } + postIndex := iNdEx + msglen + if postIndex < 0 { + return protoiface.UnmarshalOutput{NoUnkeyedLiterals: input.NoUnkeyedLiterals, Flags: input.Flags}, runtime.ErrInvalidLength + } + if postIndex > l { + return protoiface.UnmarshalOutput{NoUnkeyedLiterals: input.NoUnkeyedLiterals, Flags: input.Flags}, io.ErrUnexpectedEOF + } + if x.B == nil { + x.B = &TestVersion2{} + } + if err := options.Unmarshal(dAtA[iNdEx:postIndex], x.B); err != nil { + return protoiface.UnmarshalOutput{NoUnkeyedLiterals: input.NoUnkeyedLiterals, Flags: input.Flags}, err + } + iNdEx = postIndex + case 4: + if wireType != 2 { + return protoiface.UnmarshalOutput{NoUnkeyedLiterals: input.NoUnkeyedLiterals, Flags: input.Flags}, fmt.Errorf("proto: wrong wireType = %d for field C", wireType) + } + var msglen int + for shift := uint(0); ; shift += 7 { + if shift >= 64 { + return protoiface.UnmarshalOutput{NoUnkeyedLiterals: input.NoUnkeyedLiterals, Flags: input.Flags}, runtime.ErrIntOverflow + } + if iNdEx >= l { + return protoiface.UnmarshalOutput{NoUnkeyedLiterals: input.NoUnkeyedLiterals, Flags: input.Flags}, io.ErrUnexpectedEOF + } + b := dAtA[iNdEx] + iNdEx++ + msglen |= int(b&0x7F) << shift + if b < 0x80 { + break + } + } + if msglen < 0 { + return protoiface.UnmarshalOutput{NoUnkeyedLiterals: input.NoUnkeyedLiterals, Flags: input.Flags}, runtime.ErrInvalidLength + } + postIndex := iNdEx + msglen + if postIndex < 0 { + return protoiface.UnmarshalOutput{NoUnkeyedLiterals: input.NoUnkeyedLiterals, Flags: input.Flags}, runtime.ErrInvalidLength + } + if postIndex > l { + return protoiface.UnmarshalOutput{NoUnkeyedLiterals: input.NoUnkeyedLiterals, Flags: input.Flags}, io.ErrUnexpectedEOF + } + x.C = append(x.C, &TestVersion2{}) + if err := options.Unmarshal(dAtA[iNdEx:postIndex], x.C[len(x.C)-1]); err != nil { + return protoiface.UnmarshalOutput{NoUnkeyedLiterals: input.NoUnkeyedLiterals, Flags: input.Flags}, err + } + iNdEx = postIndex + case 5: + if wireType != 2 { + return protoiface.UnmarshalOutput{NoUnkeyedLiterals: input.NoUnkeyedLiterals, Flags: input.Flags}, fmt.Errorf("proto: wrong wireType = %d for field D", wireType) + } + var msglen int + for shift := uint(0); ; shift += 7 { + if shift >= 64 { + return protoiface.UnmarshalOutput{NoUnkeyedLiterals: input.NoUnkeyedLiterals, Flags: input.Flags}, runtime.ErrIntOverflow + } + if iNdEx >= l { + return protoiface.UnmarshalOutput{NoUnkeyedLiterals: input.NoUnkeyedLiterals, Flags: input.Flags}, io.ErrUnexpectedEOF + } + b := dAtA[iNdEx] + iNdEx++ + msglen |= int(b&0x7F) << shift + if b < 0x80 { + break + } + } + if msglen < 0 { + return protoiface.UnmarshalOutput{NoUnkeyedLiterals: input.NoUnkeyedLiterals, Flags: input.Flags}, runtime.ErrInvalidLength + } + postIndex := iNdEx + msglen + if postIndex < 0 { + return protoiface.UnmarshalOutput{NoUnkeyedLiterals: input.NoUnkeyedLiterals, Flags: input.Flags}, runtime.ErrInvalidLength + } + if postIndex > l { + return protoiface.UnmarshalOutput{NoUnkeyedLiterals: input.NoUnkeyedLiterals, Flags: input.Flags}, io.ErrUnexpectedEOF + } + x.D = append(x.D, &TestVersion2{}) + if err := options.Unmarshal(dAtA[iNdEx:postIndex], x.D[len(x.D)-1]); err != nil { + return protoiface.UnmarshalOutput{NoUnkeyedLiterals: input.NoUnkeyedLiterals, Flags: input.Flags}, err + } + iNdEx = postIndex + case 6: + if wireType != 0 { + return protoiface.UnmarshalOutput{NoUnkeyedLiterals: input.NoUnkeyedLiterals, Flags: input.Flags}, fmt.Errorf("proto: wrong wireType = %d for field E", wireType) + } + var v int32 + for shift := uint(0); ; shift += 7 { + if shift >= 64 { + return protoiface.UnmarshalOutput{NoUnkeyedLiterals: input.NoUnkeyedLiterals, Flags: input.Flags}, runtime.ErrIntOverflow + } + if iNdEx >= l { + return protoiface.UnmarshalOutput{NoUnkeyedLiterals: input.NoUnkeyedLiterals, Flags: input.Flags}, io.ErrUnexpectedEOF + } + b := dAtA[iNdEx] + iNdEx++ + v |= int32(b&0x7F) << shift + if b < 0x80 { + break + } + } + x.Sum = &TestVersion2_E{v} + case 7: + if wireType != 2 { + return protoiface.UnmarshalOutput{NoUnkeyedLiterals: input.NoUnkeyedLiterals, Flags: input.Flags}, fmt.Errorf("proto: wrong wireType = %d for field F", wireType) + } + var msglen int + for shift := uint(0); ; shift += 7 { + if shift >= 64 { + return protoiface.UnmarshalOutput{NoUnkeyedLiterals: input.NoUnkeyedLiterals, Flags: input.Flags}, runtime.ErrIntOverflow + } + if iNdEx >= l { + return protoiface.UnmarshalOutput{NoUnkeyedLiterals: input.NoUnkeyedLiterals, Flags: input.Flags}, io.ErrUnexpectedEOF + } + b := dAtA[iNdEx] + iNdEx++ + msglen |= int(b&0x7F) << shift + if b < 0x80 { + break + } + } + if msglen < 0 { + return protoiface.UnmarshalOutput{NoUnkeyedLiterals: input.NoUnkeyedLiterals, Flags: input.Flags}, runtime.ErrInvalidLength + } + postIndex := iNdEx + msglen + if postIndex < 0 { + return protoiface.UnmarshalOutput{NoUnkeyedLiterals: input.NoUnkeyedLiterals, Flags: input.Flags}, runtime.ErrInvalidLength + } + if postIndex > l { + return protoiface.UnmarshalOutput{NoUnkeyedLiterals: input.NoUnkeyedLiterals, Flags: input.Flags}, io.ErrUnexpectedEOF + } + v := &TestVersion2{} + if err := options.Unmarshal(dAtA[iNdEx:postIndex], v); err != nil { + return protoiface.UnmarshalOutput{NoUnkeyedLiterals: input.NoUnkeyedLiterals, Flags: input.Flags}, err + } + x.Sum = &TestVersion2_F{v} + iNdEx = postIndex + case 8: + if wireType != 2 { + return protoiface.UnmarshalOutput{NoUnkeyedLiterals: input.NoUnkeyedLiterals, Flags: input.Flags}, fmt.Errorf("proto: wrong wireType = %d for field G", wireType) + } + var msglen int + for shift := uint(0); ; shift += 7 { + if shift >= 64 { + return protoiface.UnmarshalOutput{NoUnkeyedLiterals: input.NoUnkeyedLiterals, Flags: input.Flags}, runtime.ErrIntOverflow + } + if iNdEx >= l { + return protoiface.UnmarshalOutput{NoUnkeyedLiterals: input.NoUnkeyedLiterals, Flags: input.Flags}, io.ErrUnexpectedEOF + } + b := dAtA[iNdEx] + iNdEx++ + msglen |= int(b&0x7F) << shift + if b < 0x80 { + break + } + } + if msglen < 0 { + return protoiface.UnmarshalOutput{NoUnkeyedLiterals: input.NoUnkeyedLiterals, Flags: input.Flags}, runtime.ErrInvalidLength + } + postIndex := iNdEx + msglen + if postIndex < 0 { + return protoiface.UnmarshalOutput{NoUnkeyedLiterals: input.NoUnkeyedLiterals, Flags: input.Flags}, runtime.ErrInvalidLength + } + if postIndex > l { + return protoiface.UnmarshalOutput{NoUnkeyedLiterals: input.NoUnkeyedLiterals, Flags: input.Flags}, io.ErrUnexpectedEOF + } + if x.G == nil { + x.G = &anypb.Any{} + } + if err := options.Unmarshal(dAtA[iNdEx:postIndex], x.G); err != nil { + return protoiface.UnmarshalOutput{NoUnkeyedLiterals: input.NoUnkeyedLiterals, Flags: input.Flags}, err + } + iNdEx = postIndex + case 9: + if wireType != 2 { + return protoiface.UnmarshalOutput{NoUnkeyedLiterals: input.NoUnkeyedLiterals, Flags: input.Flags}, fmt.Errorf("proto: wrong wireType = %d for field H", wireType) + } + var msglen int + for shift := uint(0); ; shift += 7 { + if shift >= 64 { + return protoiface.UnmarshalOutput{NoUnkeyedLiterals: input.NoUnkeyedLiterals, Flags: input.Flags}, runtime.ErrIntOverflow + } + if iNdEx >= l { + return protoiface.UnmarshalOutput{NoUnkeyedLiterals: input.NoUnkeyedLiterals, Flags: input.Flags}, io.ErrUnexpectedEOF + } + b := dAtA[iNdEx] + iNdEx++ + msglen |= int(b&0x7F) << shift + if b < 0x80 { + break + } + } + if msglen < 0 { + return protoiface.UnmarshalOutput{NoUnkeyedLiterals: input.NoUnkeyedLiterals, Flags: input.Flags}, runtime.ErrInvalidLength + } + postIndex := iNdEx + msglen + if postIndex < 0 { + return protoiface.UnmarshalOutput{NoUnkeyedLiterals: input.NoUnkeyedLiterals, Flags: input.Flags}, runtime.ErrInvalidLength + } + if postIndex > l { + return protoiface.UnmarshalOutput{NoUnkeyedLiterals: input.NoUnkeyedLiterals, Flags: input.Flags}, io.ErrUnexpectedEOF + } + x.H = append(x.H, &TestVersion1{}) + if err := options.Unmarshal(dAtA[iNdEx:postIndex], x.H[len(x.H)-1]); err != nil { + return protoiface.UnmarshalOutput{NoUnkeyedLiterals: input.NoUnkeyedLiterals, Flags: input.Flags}, err + } + iNdEx = postIndex + case 12: + if wireType != 2 { + return protoiface.UnmarshalOutput{NoUnkeyedLiterals: input.NoUnkeyedLiterals, Flags: input.Flags}, fmt.Errorf("proto: wrong wireType = %d for field K", wireType) + } + var msglen int + for shift := uint(0); ; shift += 7 { + if shift >= 64 { + return protoiface.UnmarshalOutput{NoUnkeyedLiterals: input.NoUnkeyedLiterals, Flags: input.Flags}, runtime.ErrIntOverflow + } + if iNdEx >= l { + return protoiface.UnmarshalOutput{NoUnkeyedLiterals: input.NoUnkeyedLiterals, Flags: input.Flags}, io.ErrUnexpectedEOF + } + b := dAtA[iNdEx] + iNdEx++ + msglen |= int(b&0x7F) << shift + if b < 0x80 { + break + } + } + if msglen < 0 { + return protoiface.UnmarshalOutput{NoUnkeyedLiterals: input.NoUnkeyedLiterals, Flags: input.Flags}, runtime.ErrInvalidLength + } + postIndex := iNdEx + msglen + if postIndex < 0 { + return protoiface.UnmarshalOutput{NoUnkeyedLiterals: input.NoUnkeyedLiterals, Flags: input.Flags}, runtime.ErrInvalidLength + } + if postIndex > l { + return protoiface.UnmarshalOutput{NoUnkeyedLiterals: input.NoUnkeyedLiterals, Flags: input.Flags}, io.ErrUnexpectedEOF + } + if x.K == nil { + x.K = &Customer1{} + } + if err := options.Unmarshal(dAtA[iNdEx:postIndex], x.K); err != nil { + return protoiface.UnmarshalOutput{NoUnkeyedLiterals: input.NoUnkeyedLiterals, Flags: input.Flags}, err + } + iNdEx = postIndex + case 25: + if wireType != 0 { + return protoiface.UnmarshalOutput{NoUnkeyedLiterals: input.NoUnkeyedLiterals, Flags: input.Flags}, fmt.Errorf("proto: wrong wireType = %d for field NewField_", wireType) + } + x.NewField_ = 0 + for shift := uint(0); ; shift += 7 { + if shift >= 64 { + return protoiface.UnmarshalOutput{NoUnkeyedLiterals: input.NoUnkeyedLiterals, Flags: input.Flags}, runtime.ErrIntOverflow + } + if iNdEx >= l { + return protoiface.UnmarshalOutput{NoUnkeyedLiterals: input.NoUnkeyedLiterals, Flags: input.Flags}, io.ErrUnexpectedEOF + } + b := dAtA[iNdEx] + iNdEx++ + x.NewField_ |= uint64(b&0x7F) << shift + if b < 0x80 { + break + } + } + default: + iNdEx = preIndex + skippy, err := runtime.Skip(dAtA[iNdEx:]) + if err != nil { + return protoiface.UnmarshalOutput{NoUnkeyedLiterals: input.NoUnkeyedLiterals, Flags: input.Flags}, err + } + if (skippy < 0) || (iNdEx+skippy) < 0 { + return protoiface.UnmarshalOutput{NoUnkeyedLiterals: input.NoUnkeyedLiterals, Flags: input.Flags}, runtime.ErrInvalidLength + } + if (iNdEx + skippy) > l { + return protoiface.UnmarshalOutput{NoUnkeyedLiterals: input.NoUnkeyedLiterals, Flags: input.Flags}, io.ErrUnexpectedEOF + } + if !options.DiscardUnknown { + x.unknownFields = append(x.unknownFields, dAtA[iNdEx:iNdEx+skippy]...) + } + iNdEx += skippy + } + } + + if iNdEx > l { + return protoiface.UnmarshalOutput{NoUnkeyedLiterals: input.NoUnkeyedLiterals, Flags: input.Flags}, io.ErrUnexpectedEOF + } + return protoiface.UnmarshalOutput{NoUnkeyedLiterals: input.NoUnkeyedLiterals, Flags: input.Flags}, nil + } + return &protoiface.Methods{ + NoUnkeyedLiterals: struct{}{}, + Flags: protoiface.SupportMarshalDeterministic | protoiface.SupportUnmarshalDiscardUnknown, + Size: size, + Marshal: marshal, + Unmarshal: unmarshal, + Merge: nil, + CheckInitialized: nil, + } +} + +var _ protoreflect.List = (*_TestVersion3_4_list)(nil) + +type _TestVersion3_4_list struct { + list *[]*TestVersion3 +} + +func (x *_TestVersion3_4_list) Len() int { + if x.list == nil { + return 0 + } + return len(*x.list) +} + +func (x *_TestVersion3_4_list) Get(i int) protoreflect.Value { + return protoreflect.ValueOfMessage((*x.list)[i].ProtoReflect()) +} + +func (x *_TestVersion3_4_list) Set(i int, value protoreflect.Value) { + valueUnwrapped := value.Message() + concreteValue := valueUnwrapped.Interface().(*TestVersion3) + (*x.list)[i] = concreteValue +} + +func (x *_TestVersion3_4_list) Append(value protoreflect.Value) { + valueUnwrapped := value.Message() + concreteValue := valueUnwrapped.Interface().(*TestVersion3) + *x.list = append(*x.list, concreteValue) +} + +func (x *_TestVersion3_4_list) AppendMutable() protoreflect.Value { + v := new(TestVersion3) + *x.list = append(*x.list, v) + return protoreflect.ValueOfMessage(v.ProtoReflect()) +} + +func (x *_TestVersion3_4_list) Truncate(n int) { + for i := n; i < len(*x.list); i++ { + (*x.list)[i] = nil + } + *x.list = (*x.list)[:n] +} + +func (x *_TestVersion3_4_list) NewElement() protoreflect.Value { + v := new(TestVersion3) + return protoreflect.ValueOfMessage(v.ProtoReflect()) +} + +func (x *_TestVersion3_4_list) IsValid() bool { + return x.list != nil +} + +var _ protoreflect.List = (*_TestVersion3_5_list)(nil) + +type _TestVersion3_5_list struct { + list *[]*TestVersion3 +} + +func (x *_TestVersion3_5_list) Len() int { + if x.list == nil { + return 0 + } + return len(*x.list) +} + +func (x *_TestVersion3_5_list) Get(i int) protoreflect.Value { + return protoreflect.ValueOfMessage((*x.list)[i].ProtoReflect()) +} + +func (x *_TestVersion3_5_list) Set(i int, value protoreflect.Value) { + valueUnwrapped := value.Message() + concreteValue := valueUnwrapped.Interface().(*TestVersion3) + (*x.list)[i] = concreteValue +} + +func (x *_TestVersion3_5_list) Append(value protoreflect.Value) { + valueUnwrapped := value.Message() + concreteValue := valueUnwrapped.Interface().(*TestVersion3) + *x.list = append(*x.list, concreteValue) +} + +func (x *_TestVersion3_5_list) AppendMutable() protoreflect.Value { + v := new(TestVersion3) + *x.list = append(*x.list, v) + return protoreflect.ValueOfMessage(v.ProtoReflect()) +} + +func (x *_TestVersion3_5_list) Truncate(n int) { + for i := n; i < len(*x.list); i++ { + (*x.list)[i] = nil + } + *x.list = (*x.list)[:n] +} + +func (x *_TestVersion3_5_list) NewElement() protoreflect.Value { + v := new(TestVersion3) + return protoreflect.ValueOfMessage(v.ProtoReflect()) +} + +func (x *_TestVersion3_5_list) IsValid() bool { + return x.list != nil +} + +var _ protoreflect.List = (*_TestVersion3_9_list)(nil) + +type _TestVersion3_9_list struct { + list *[]*TestVersion1 +} + +func (x *_TestVersion3_9_list) Len() int { + if x.list == nil { + return 0 + } + return len(*x.list) +} + +func (x *_TestVersion3_9_list) Get(i int) protoreflect.Value { + return protoreflect.ValueOfMessage((*x.list)[i].ProtoReflect()) +} + +func (x *_TestVersion3_9_list) Set(i int, value protoreflect.Value) { + valueUnwrapped := value.Message() + concreteValue := valueUnwrapped.Interface().(*TestVersion1) + (*x.list)[i] = concreteValue +} + +func (x *_TestVersion3_9_list) Append(value protoreflect.Value) { + valueUnwrapped := value.Message() + concreteValue := valueUnwrapped.Interface().(*TestVersion1) + *x.list = append(*x.list, concreteValue) +} + +func (x *_TestVersion3_9_list) AppendMutable() protoreflect.Value { + v := new(TestVersion1) + *x.list = append(*x.list, v) + return protoreflect.ValueOfMessage(v.ProtoReflect()) +} + +func (x *_TestVersion3_9_list) Truncate(n int) { + for i := n; i < len(*x.list); i++ { + (*x.list)[i] = nil + } + *x.list = (*x.list)[:n] +} + +func (x *_TestVersion3_9_list) NewElement() protoreflect.Value { + v := new(TestVersion1) + return protoreflect.ValueOfMessage(v.ProtoReflect()) +} + +func (x *_TestVersion3_9_list) IsValid() bool { + return x.list != nil +} + +var ( + md_TestVersion3 protoreflect.MessageDescriptor + fd_TestVersion3_x protoreflect.FieldDescriptor + fd_TestVersion3_a protoreflect.FieldDescriptor + fd_TestVersion3_b protoreflect.FieldDescriptor + fd_TestVersion3_c protoreflect.FieldDescriptor + fd_TestVersion3_d protoreflect.FieldDescriptor + fd_TestVersion3_e protoreflect.FieldDescriptor + fd_TestVersion3_f protoreflect.FieldDescriptor + fd_TestVersion3_g protoreflect.FieldDescriptor + fd_TestVersion3_h protoreflect.FieldDescriptor + fd_TestVersion3_k protoreflect.FieldDescriptor + fd_TestVersion3_non_critical_field protoreflect.FieldDescriptor +) + +func init() { + file_unknownproto_proto_init() + md_TestVersion3 = File_unknownproto_proto.Messages().ByName("TestVersion3") + fd_TestVersion3_x = md_TestVersion3.Fields().ByName("x") + fd_TestVersion3_a = md_TestVersion3.Fields().ByName("a") + fd_TestVersion3_b = md_TestVersion3.Fields().ByName("b") + fd_TestVersion3_c = md_TestVersion3.Fields().ByName("c") + fd_TestVersion3_d = md_TestVersion3.Fields().ByName("d") + fd_TestVersion3_e = md_TestVersion3.Fields().ByName("e") + fd_TestVersion3_f = md_TestVersion3.Fields().ByName("f") + fd_TestVersion3_g = md_TestVersion3.Fields().ByName("g") + fd_TestVersion3_h = md_TestVersion3.Fields().ByName("h") + fd_TestVersion3_k = md_TestVersion3.Fields().ByName("k") + fd_TestVersion3_non_critical_field = md_TestVersion3.Fields().ByName("non_critical_field") +} + +var _ protoreflect.Message = (*fastReflection_TestVersion3)(nil) + +type fastReflection_TestVersion3 TestVersion3 + +func (x *TestVersion3) ProtoReflect() protoreflect.Message { + return (*fastReflection_TestVersion3)(x) +} + +func (x *TestVersion3) slowProtoReflect() protoreflect.Message { + mi := &file_unknownproto_proto_msgTypes[13] + if protoimpl.UnsafeEnabled && x != nil { + ms := protoimpl.X.MessageStateOf(protoimpl.Pointer(x)) + if ms.LoadMessageInfo() == nil { + ms.StoreMessageInfo(mi) + } + return ms + } + return mi.MessageOf(x) +} + +var _fastReflection_TestVersion3_messageType fastReflection_TestVersion3_messageType +var _ protoreflect.MessageType = fastReflection_TestVersion3_messageType{} + +type fastReflection_TestVersion3_messageType struct{} + +func (x fastReflection_TestVersion3_messageType) Zero() protoreflect.Message { + return (*fastReflection_TestVersion3)(nil) +} +func (x fastReflection_TestVersion3_messageType) New() protoreflect.Message { + return new(fastReflection_TestVersion3) +} +func (x fastReflection_TestVersion3_messageType) Descriptor() protoreflect.MessageDescriptor { + return md_TestVersion3 +} + +// Descriptor returns message descriptor, which contains only the protobuf +// type information for the message. +func (x *fastReflection_TestVersion3) Descriptor() protoreflect.MessageDescriptor { + return md_TestVersion3 +} + +// Type returns the message type, which encapsulates both Go and protobuf +// type information. If the Go type information is not needed, +// it is recommended that the message descriptor be used instead. +func (x *fastReflection_TestVersion3) Type() protoreflect.MessageType { + return _fastReflection_TestVersion3_messageType +} + +// New returns a newly allocated and mutable empty message. +func (x *fastReflection_TestVersion3) New() protoreflect.Message { + return new(fastReflection_TestVersion3) +} + +// Interface unwraps the message reflection interface and +// returns the underlying ProtoMessage interface. +func (x *fastReflection_TestVersion3) Interface() protoreflect.ProtoMessage { + return (*TestVersion3)(x) +} + +// Range iterates over every populated field in an undefined order, +// calling f for each field descriptor and value encountered. +// Range returns immediately if f returns false. +// While iterating, mutating operations may only be performed +// on the current field descriptor. +func (x *fastReflection_TestVersion3) Range(f func(protoreflect.FieldDescriptor, protoreflect.Value) bool) { + if x.X != int64(0) { + value := protoreflect.ValueOfInt64(x.X) + if !f(fd_TestVersion3_x, value) { + return + } + } + if x.A != nil { + value := protoreflect.ValueOfMessage(x.A.ProtoReflect()) + if !f(fd_TestVersion3_a, value) { + return + } + } + if x.B != nil { + value := protoreflect.ValueOfMessage(x.B.ProtoReflect()) + if !f(fd_TestVersion3_b, value) { + return + } + } + if len(x.C) != 0 { + value := protoreflect.ValueOfList(&_TestVersion3_4_list{list: &x.C}) + if !f(fd_TestVersion3_c, value) { + return + } + } + if len(x.D) != 0 { + value := protoreflect.ValueOfList(&_TestVersion3_5_list{list: &x.D}) + if !f(fd_TestVersion3_d, value) { + return + } + } + if x.Sum != nil { + switch o := x.Sum.(type) { + case *TestVersion3_E: + v := o.E + value := protoreflect.ValueOfInt32(v) + if !f(fd_TestVersion3_e, value) { + return + } + case *TestVersion3_F: + v := o.F + value := protoreflect.ValueOfMessage(v.ProtoReflect()) + if !f(fd_TestVersion3_f, value) { + return + } + } + } + if x.G != nil { + value := protoreflect.ValueOfMessage(x.G.ProtoReflect()) + if !f(fd_TestVersion3_g, value) { + return + } + } + if len(x.H) != 0 { + value := protoreflect.ValueOfList(&_TestVersion3_9_list{list: &x.H}) + if !f(fd_TestVersion3_h, value) { + return + } + } + if x.K != nil { + value := protoreflect.ValueOfMessage(x.K.ProtoReflect()) + if !f(fd_TestVersion3_k, value) { + return + } + } + if x.NonCriticalField != "" { + value := protoreflect.ValueOfString(x.NonCriticalField) + if !f(fd_TestVersion3_non_critical_field, value) { + return + } + } +} + +// Has reports whether a field is populated. +// +// Some fields have the property of nullability where it is possible to +// distinguish between the default value of a field and whether the field +// was explicitly populated with the default value. Singular message fields, +// member fields of a oneof, and proto2 scalar fields are nullable. Such +// fields are populated only if explicitly set. +// +// In other cases (aside from the nullable cases above), +// a proto3 scalar field is populated if it contains a non-zero value, and +// a repeated field is populated if it is non-empty. +func (x *fastReflection_TestVersion3) Has(fd protoreflect.FieldDescriptor) bool { + switch fd.FullName() { + case "testpb.TestVersion3.x": + return x.X != int64(0) + case "testpb.TestVersion3.a": + return x.A != nil + case "testpb.TestVersion3.b": + return x.B != nil + case "testpb.TestVersion3.c": + return len(x.C) != 0 + case "testpb.TestVersion3.d": + return len(x.D) != 0 + case "testpb.TestVersion3.e": + if x.Sum == nil { + return false + } else if _, ok := x.Sum.(*TestVersion3_E); ok { + return true + } else { + return false + } + case "testpb.TestVersion3.f": + if x.Sum == nil { + return false + } else if _, ok := x.Sum.(*TestVersion3_F); ok { + return true + } else { + return false + } + case "testpb.TestVersion3.g": + return x.G != nil + case "testpb.TestVersion3.h": + return len(x.H) != 0 + case "testpb.TestVersion3.k": + return x.K != nil + case "testpb.TestVersion3.non_critical_field": + return x.NonCriticalField != "" + default: + if fd.IsExtension() { + panic(fmt.Errorf("proto3 declared messages do not support extensions: testpb.TestVersion3")) + } + panic(fmt.Errorf("message testpb.TestVersion3 does not contain field %s", fd.FullName())) + } +} + +// Clear clears the field such that a subsequent Has call reports false. +// +// Clearing an extension field clears both the extension type and value +// associated with the given field number. +// +// Clear is a mutating operation and unsafe for concurrent use. +func (x *fastReflection_TestVersion3) Clear(fd protoreflect.FieldDescriptor) { + switch fd.FullName() { + case "testpb.TestVersion3.x": + x.X = int64(0) + case "testpb.TestVersion3.a": + x.A = nil + case "testpb.TestVersion3.b": + x.B = nil + case "testpb.TestVersion3.c": + x.C = nil + case "testpb.TestVersion3.d": + x.D = nil + case "testpb.TestVersion3.e": + x.Sum = nil + case "testpb.TestVersion3.f": + x.Sum = nil + case "testpb.TestVersion3.g": + x.G = nil + case "testpb.TestVersion3.h": + x.H = nil + case "testpb.TestVersion3.k": + x.K = nil + case "testpb.TestVersion3.non_critical_field": + x.NonCriticalField = "" + default: + if fd.IsExtension() { + panic(fmt.Errorf("proto3 declared messages do not support extensions: testpb.TestVersion3")) + } + panic(fmt.Errorf("message testpb.TestVersion3 does not contain field %s", fd.FullName())) + } +} + +// Get retrieves the value for a field. +// +// For unpopulated scalars, it returns the default value, where +// the default value of a bytes scalar is guaranteed to be a copy. +// For unpopulated composite types, it returns an empty, read-only view +// of the value; to obtain a mutable reference, use Mutable. +func (x *fastReflection_TestVersion3) Get(descriptor protoreflect.FieldDescriptor) protoreflect.Value { + switch descriptor.FullName() { + case "testpb.TestVersion3.x": + value := x.X + return protoreflect.ValueOfInt64(value) + case "testpb.TestVersion3.a": + value := x.A + return protoreflect.ValueOfMessage(value.ProtoReflect()) + case "testpb.TestVersion3.b": + value := x.B + return protoreflect.ValueOfMessage(value.ProtoReflect()) + case "testpb.TestVersion3.c": + if len(x.C) == 0 { + return protoreflect.ValueOfList(&_TestVersion3_4_list{}) + } + listValue := &_TestVersion3_4_list{list: &x.C} + return protoreflect.ValueOfList(listValue) + case "testpb.TestVersion3.d": + if len(x.D) == 0 { + return protoreflect.ValueOfList(&_TestVersion3_5_list{}) + } + listValue := &_TestVersion3_5_list{list: &x.D} + return protoreflect.ValueOfList(listValue) + case "testpb.TestVersion3.e": + if x.Sum == nil { + return protoreflect.ValueOfInt32(int32(0)) + } else if v, ok := x.Sum.(*TestVersion3_E); ok { + return protoreflect.ValueOfInt32(v.E) + } else { + return protoreflect.ValueOfInt32(int32(0)) + } + case "testpb.TestVersion3.f": + if x.Sum == nil { + return protoreflect.ValueOfMessage((*TestVersion3)(nil).ProtoReflect()) + } else if v, ok := x.Sum.(*TestVersion3_F); ok { + return protoreflect.ValueOfMessage(v.F.ProtoReflect()) + } else { + return protoreflect.ValueOfMessage((*TestVersion3)(nil).ProtoReflect()) + } + case "testpb.TestVersion3.g": + value := x.G + return protoreflect.ValueOfMessage(value.ProtoReflect()) + case "testpb.TestVersion3.h": + if len(x.H) == 0 { + return protoreflect.ValueOfList(&_TestVersion3_9_list{}) + } + listValue := &_TestVersion3_9_list{list: &x.H} + return protoreflect.ValueOfList(listValue) + case "testpb.TestVersion3.k": + value := x.K + return protoreflect.ValueOfMessage(value.ProtoReflect()) + case "testpb.TestVersion3.non_critical_field": + value := x.NonCriticalField + return protoreflect.ValueOfString(value) + default: + if descriptor.IsExtension() { + panic(fmt.Errorf("proto3 declared messages do not support extensions: testpb.TestVersion3")) + } + panic(fmt.Errorf("message testpb.TestVersion3 does not contain field %s", descriptor.FullName())) + } +} + +// Set stores the value for a field. +// +// For a field belonging to a oneof, it implicitly clears any other field +// that may be currently set within the same oneof. +// For extension fields, it implicitly stores the provided ExtensionType. +// When setting a composite type, it is unspecified whether the stored value +// aliases the source's memory in any way. If the composite value is an +// empty, read-only value, then it panics. +// +// Set is a mutating operation and unsafe for concurrent use. +func (x *fastReflection_TestVersion3) Set(fd protoreflect.FieldDescriptor, value protoreflect.Value) { + switch fd.FullName() { + case "testpb.TestVersion3.x": + x.X = value.Int() + case "testpb.TestVersion3.a": + x.A = value.Message().Interface().(*TestVersion3) + case "testpb.TestVersion3.b": + x.B = value.Message().Interface().(*TestVersion3) + case "testpb.TestVersion3.c": + lv := value.List() + clv := lv.(*_TestVersion3_4_list) + x.C = *clv.list + case "testpb.TestVersion3.d": + lv := value.List() + clv := lv.(*_TestVersion3_5_list) + x.D = *clv.list + case "testpb.TestVersion3.e": + cv := int32(value.Int()) + x.Sum = &TestVersion3_E{E: cv} + case "testpb.TestVersion3.f": + cv := value.Message().Interface().(*TestVersion3) + x.Sum = &TestVersion3_F{F: cv} + case "testpb.TestVersion3.g": + x.G = value.Message().Interface().(*anypb.Any) + case "testpb.TestVersion3.h": + lv := value.List() + clv := lv.(*_TestVersion3_9_list) + x.H = *clv.list + case "testpb.TestVersion3.k": + x.K = value.Message().Interface().(*Customer1) + case "testpb.TestVersion3.non_critical_field": + x.NonCriticalField = value.Interface().(string) + default: + if fd.IsExtension() { + panic(fmt.Errorf("proto3 declared messages do not support extensions: testpb.TestVersion3")) + } + panic(fmt.Errorf("message testpb.TestVersion3 does not contain field %s", fd.FullName())) + } +} + +// Mutable returns a mutable reference to a composite type. +// +// If the field is unpopulated, it may allocate a composite value. +// For a field belonging to a oneof, it implicitly clears any other field +// that may be currently set within the same oneof. +// For extension fields, it implicitly stores the provided ExtensionType +// if not already stored. +// It panics if the field does not contain a composite type. +// +// Mutable is a mutating operation and unsafe for concurrent use. +func (x *fastReflection_TestVersion3) Mutable(fd protoreflect.FieldDescriptor) protoreflect.Value { + switch fd.FullName() { + case "testpb.TestVersion3.a": + if x.A == nil { + x.A = new(TestVersion3) + } + return protoreflect.ValueOfMessage(x.A.ProtoReflect()) + case "testpb.TestVersion3.b": + if x.B == nil { + x.B = new(TestVersion3) + } + return protoreflect.ValueOfMessage(x.B.ProtoReflect()) + case "testpb.TestVersion3.c": + if x.C == nil { + x.C = []*TestVersion3{} + } + value := &_TestVersion3_4_list{list: &x.C} + return protoreflect.ValueOfList(value) + case "testpb.TestVersion3.d": + if x.D == nil { + x.D = []*TestVersion3{} + } + value := &_TestVersion3_5_list{list: &x.D} + return protoreflect.ValueOfList(value) + case "testpb.TestVersion3.f": + if x.Sum == nil { + value := &TestVersion3{} + oneofValue := &TestVersion3_F{F: value} + x.Sum = oneofValue + return protoreflect.ValueOfMessage(value.ProtoReflect()) + } + switch m := x.Sum.(type) { + case *TestVersion3_F: + return protoreflect.ValueOfMessage(m.F.ProtoReflect()) + default: + value := &TestVersion3{} + oneofValue := &TestVersion3_F{F: value} + x.Sum = oneofValue + return protoreflect.ValueOfMessage(value.ProtoReflect()) + } + case "testpb.TestVersion3.g": + if x.G == nil { + x.G = new(anypb.Any) + } + return protoreflect.ValueOfMessage(x.G.ProtoReflect()) + case "testpb.TestVersion3.h": + if x.H == nil { + x.H = []*TestVersion1{} + } + value := &_TestVersion3_9_list{list: &x.H} + return protoreflect.ValueOfList(value) + case "testpb.TestVersion3.k": + if x.K == nil { + x.K = new(Customer1) + } + return protoreflect.ValueOfMessage(x.K.ProtoReflect()) + case "testpb.TestVersion3.x": + panic(fmt.Errorf("field x of message testpb.TestVersion3 is not mutable")) + case "testpb.TestVersion3.e": + panic(fmt.Errorf("field e of message testpb.TestVersion3 is not mutable")) + case "testpb.TestVersion3.non_critical_field": + panic(fmt.Errorf("field non_critical_field of message testpb.TestVersion3 is not mutable")) + default: + if fd.IsExtension() { + panic(fmt.Errorf("proto3 declared messages do not support extensions: testpb.TestVersion3")) + } + panic(fmt.Errorf("message testpb.TestVersion3 does not contain field %s", fd.FullName())) + } +} + +// NewField returns a new value that is assignable to the field +// for the given descriptor. For scalars, this returns the default value. +// For lists, maps, and messages, this returns a new, empty, mutable value. +func (x *fastReflection_TestVersion3) NewField(fd protoreflect.FieldDescriptor) protoreflect.Value { + switch fd.FullName() { + case "testpb.TestVersion3.x": + return protoreflect.ValueOfInt64(int64(0)) + case "testpb.TestVersion3.a": + m := new(TestVersion3) + return protoreflect.ValueOfMessage(m.ProtoReflect()) + case "testpb.TestVersion3.b": + m := new(TestVersion3) + return protoreflect.ValueOfMessage(m.ProtoReflect()) + case "testpb.TestVersion3.c": + list := []*TestVersion3{} + return protoreflect.ValueOfList(&_TestVersion3_4_list{list: &list}) + case "testpb.TestVersion3.d": + list := []*TestVersion3{} + return protoreflect.ValueOfList(&_TestVersion3_5_list{list: &list}) + case "testpb.TestVersion3.e": + return protoreflect.ValueOfInt32(int32(0)) + case "testpb.TestVersion3.f": + value := &TestVersion3{} + return protoreflect.ValueOfMessage(value.ProtoReflect()) + case "testpb.TestVersion3.g": + m := new(anypb.Any) + return protoreflect.ValueOfMessage(m.ProtoReflect()) + case "testpb.TestVersion3.h": + list := []*TestVersion1{} + return protoreflect.ValueOfList(&_TestVersion3_9_list{list: &list}) + case "testpb.TestVersion3.k": + m := new(Customer1) + return protoreflect.ValueOfMessage(m.ProtoReflect()) + case "testpb.TestVersion3.non_critical_field": + return protoreflect.ValueOfString("") + default: + if fd.IsExtension() { + panic(fmt.Errorf("proto3 declared messages do not support extensions: testpb.TestVersion3")) + } + panic(fmt.Errorf("message testpb.TestVersion3 does not contain field %s", fd.FullName())) + } +} + +// WhichOneof reports which field within the oneof is populated, +// returning nil if none are populated. +// It panics if the oneof descriptor does not belong to this message. +func (x *fastReflection_TestVersion3) WhichOneof(d protoreflect.OneofDescriptor) protoreflect.FieldDescriptor { + switch d.FullName() { + case "testpb.TestVersion3.sum": + if x.Sum == nil { + return nil + } + switch x.Sum.(type) { + case *TestVersion3_E: + return x.Descriptor().Fields().ByName("e") + case *TestVersion3_F: + return x.Descriptor().Fields().ByName("f") + } + default: + panic(fmt.Errorf("%s is not a oneof field in testpb.TestVersion3", d.FullName())) + } + panic("unreachable") +} + +// GetUnknown retrieves the entire list of unknown fields. +// The caller may only mutate the contents of the RawFields +// if the mutated bytes are stored back into the message with SetUnknown. +func (x *fastReflection_TestVersion3) GetUnknown() protoreflect.RawFields { + return x.unknownFields +} + +// SetUnknown stores an entire list of unknown fields. +// The raw fields must be syntactically valid according to the wire format. +// An implementation may panic if this is not the case. +// Once stored, the caller must not mutate the content of the RawFields. +// An empty RawFields may be passed to clear the fields. +// +// SetUnknown is a mutating operation and unsafe for concurrent use. +func (x *fastReflection_TestVersion3) SetUnknown(fields protoreflect.RawFields) { + x.unknownFields = fields +} + +// IsValid reports whether the message is valid. +// +// An invalid message is an empty, read-only value. +// +// An invalid message often corresponds to a nil pointer of the concrete +// message type, but the details are implementation dependent. +// Validity is not part of the protobuf data model, and may not +// be preserved in marshaling or other operations. +func (x *fastReflection_TestVersion3) IsValid() bool { + return x != nil +} + +// ProtoMethods returns optional fastReflectionFeature-path implementations of various operations. +// This method may return nil. +// +// The returned methods type is identical to +// "google.golang.org/protobuf/runtime/protoiface".Methods. +// Consult the protoiface package documentation for details. +func (x *fastReflection_TestVersion3) ProtoMethods() *protoiface.Methods { + size := func(input protoiface.SizeInput) protoiface.SizeOutput { + x := input.Message.Interface().(*TestVersion3) + if x == nil { + return protoiface.SizeOutput{ + NoUnkeyedLiterals: input.NoUnkeyedLiterals, + Size: 0, + } + } + options := runtime.SizeInputToOptions(input) + _ = options + var n int + var l int + _ = l + if x.X != 0 { + n += 1 + runtime.Sov(uint64(x.X)) + } + if x.A != nil { + l = options.Size(x.A) + n += 1 + l + runtime.Sov(uint64(l)) + } + if x.B != nil { + l = options.Size(x.B) + n += 1 + l + runtime.Sov(uint64(l)) + } + if len(x.C) > 0 { + for _, e := range x.C { + l = options.Size(e) + n += 1 + l + runtime.Sov(uint64(l)) + } + } + if len(x.D) > 0 { + for _, e := range x.D { + l = options.Size(e) + n += 1 + l + runtime.Sov(uint64(l)) + } + } + switch x := x.Sum.(type) { + case *TestVersion3_E: + if x == nil { + break + } + n += 1 + runtime.Sov(uint64(x.E)) + case *TestVersion3_F: + if x == nil { + break + } + l = options.Size(x.F) + n += 1 + l + runtime.Sov(uint64(l)) + } + if x.G != nil { + l = options.Size(x.G) + n += 1 + l + runtime.Sov(uint64(l)) + } + if len(x.H) > 0 { + for _, e := range x.H { + l = options.Size(e) + n += 1 + l + runtime.Sov(uint64(l)) + } + } + if x.K != nil { + l = options.Size(x.K) + n += 1 + l + runtime.Sov(uint64(l)) + } + l = len(x.NonCriticalField) + if l > 0 { + n += 2 + l + runtime.Sov(uint64(l)) + } + if x.unknownFields != nil { + n += len(x.unknownFields) + } + return protoiface.SizeOutput{ + NoUnkeyedLiterals: input.NoUnkeyedLiterals, + Size: n, + } + } + + marshal := func(input protoiface.MarshalInput) (protoiface.MarshalOutput, error) { + x := input.Message.Interface().(*TestVersion3) + if x == nil { + return protoiface.MarshalOutput{ + NoUnkeyedLiterals: input.NoUnkeyedLiterals, + Buf: input.Buf, + }, nil + } + options := runtime.MarshalInputToOptions(input) + _ = options + size := options.Size(x) + dAtA := make([]byte, size) + i := len(dAtA) + _ = i + var l int + _ = l + if x.unknownFields != nil { + i -= len(x.unknownFields) + copy(dAtA[i:], x.unknownFields) + } + switch x := x.Sum.(type) { + case *TestVersion3_E: + i = runtime.EncodeVarint(dAtA, i, uint64(x.E)) + i-- + dAtA[i] = 0x30 + case *TestVersion3_F: + encoded, err := options.Marshal(x.F) + if err != nil { + return protoiface.MarshalOutput{ + NoUnkeyedLiterals: input.NoUnkeyedLiterals, + Buf: input.Buf, + }, err + } + i -= len(encoded) + copy(dAtA[i:], encoded) + i = runtime.EncodeVarint(dAtA, i, uint64(len(encoded))) + i-- + dAtA[i] = 0x3a + } + if len(x.NonCriticalField) > 0 { + i -= len(x.NonCriticalField) + copy(dAtA[i:], x.NonCriticalField) + i = runtime.EncodeVarint(dAtA, i, uint64(len(x.NonCriticalField))) + i-- + dAtA[i] = 0x40 + i-- + dAtA[i] = 0xba + } + if x.K != nil { + encoded, err := options.Marshal(x.K) + if err != nil { + return protoiface.MarshalOutput{ + NoUnkeyedLiterals: input.NoUnkeyedLiterals, + Buf: input.Buf, + }, err + } + i -= len(encoded) + copy(dAtA[i:], encoded) + i = runtime.EncodeVarint(dAtA, i, uint64(len(encoded))) + i-- + dAtA[i] = 0x62 + } + if len(x.H) > 0 { + for iNdEx := len(x.H) - 1; iNdEx >= 0; iNdEx-- { + encoded, err := options.Marshal(x.H[iNdEx]) + if err != nil { + return protoiface.MarshalOutput{ + NoUnkeyedLiterals: input.NoUnkeyedLiterals, + Buf: input.Buf, + }, err + } + i -= len(encoded) + copy(dAtA[i:], encoded) + i = runtime.EncodeVarint(dAtA, i, uint64(len(encoded))) + i-- + dAtA[i] = 0x4a + } + } + if x.G != nil { + encoded, err := options.Marshal(x.G) + if err != nil { + return protoiface.MarshalOutput{ + NoUnkeyedLiterals: input.NoUnkeyedLiterals, + Buf: input.Buf, + }, err + } + i -= len(encoded) + copy(dAtA[i:], encoded) + i = runtime.EncodeVarint(dAtA, i, uint64(len(encoded))) + i-- + dAtA[i] = 0x42 + } + if len(x.D) > 0 { + for iNdEx := len(x.D) - 1; iNdEx >= 0; iNdEx-- { + encoded, err := options.Marshal(x.D[iNdEx]) + if err != nil { + return protoiface.MarshalOutput{ + NoUnkeyedLiterals: input.NoUnkeyedLiterals, + Buf: input.Buf, + }, err + } + i -= len(encoded) + copy(dAtA[i:], encoded) + i = runtime.EncodeVarint(dAtA, i, uint64(len(encoded))) + i-- + dAtA[i] = 0x2a + } + } + if len(x.C) > 0 { + for iNdEx := len(x.C) - 1; iNdEx >= 0; iNdEx-- { + encoded, err := options.Marshal(x.C[iNdEx]) + if err != nil { + return protoiface.MarshalOutput{ + NoUnkeyedLiterals: input.NoUnkeyedLiterals, + Buf: input.Buf, + }, err + } + i -= len(encoded) + copy(dAtA[i:], encoded) + i = runtime.EncodeVarint(dAtA, i, uint64(len(encoded))) + i-- + dAtA[i] = 0x22 + } + } + if x.B != nil { + encoded, err := options.Marshal(x.B) + if err != nil { + return protoiface.MarshalOutput{ + NoUnkeyedLiterals: input.NoUnkeyedLiterals, + Buf: input.Buf, + }, err + } + i -= len(encoded) + copy(dAtA[i:], encoded) + i = runtime.EncodeVarint(dAtA, i, uint64(len(encoded))) + i-- + dAtA[i] = 0x1a + } + if x.A != nil { + encoded, err := options.Marshal(x.A) + if err != nil { + return protoiface.MarshalOutput{ + NoUnkeyedLiterals: input.NoUnkeyedLiterals, + Buf: input.Buf, + }, err + } + i -= len(encoded) + copy(dAtA[i:], encoded) + i = runtime.EncodeVarint(dAtA, i, uint64(len(encoded))) + i-- + dAtA[i] = 0x12 + } + if x.X != 0 { + i = runtime.EncodeVarint(dAtA, i, uint64(x.X)) + i-- + dAtA[i] = 0x8 + } + if input.Buf != nil { + input.Buf = append(input.Buf, dAtA...) + } else { + input.Buf = dAtA + } + return protoiface.MarshalOutput{ + NoUnkeyedLiterals: input.NoUnkeyedLiterals, + Buf: input.Buf, + }, nil + } + unmarshal := func(input protoiface.UnmarshalInput) (protoiface.UnmarshalOutput, error) { + x := input.Message.Interface().(*TestVersion3) + if x == nil { + return protoiface.UnmarshalOutput{ + NoUnkeyedLiterals: input.NoUnkeyedLiterals, + Flags: input.Flags, + }, nil + } + options := runtime.UnmarshalInputToOptions(input) + _ = options + dAtA := input.Buf + l := len(dAtA) + iNdEx := 0 + for iNdEx < l { + preIndex := iNdEx + var wire uint64 + for shift := uint(0); ; shift += 7 { + if shift >= 64 { + return protoiface.UnmarshalOutput{NoUnkeyedLiterals: input.NoUnkeyedLiterals, Flags: input.Flags}, runtime.ErrIntOverflow + } + if iNdEx >= l { + return protoiface.UnmarshalOutput{NoUnkeyedLiterals: input.NoUnkeyedLiterals, Flags: input.Flags}, io.ErrUnexpectedEOF + } + b := dAtA[iNdEx] + iNdEx++ + wire |= uint64(b&0x7F) << shift + if b < 0x80 { + break + } + } + fieldNum := int32(wire >> 3) + wireType := int(wire & 0x7) + if wireType == 4 { + return protoiface.UnmarshalOutput{NoUnkeyedLiterals: input.NoUnkeyedLiterals, Flags: input.Flags}, fmt.Errorf("proto: TestVersion3: wiretype end group for non-group") + } + if fieldNum <= 0 { + return protoiface.UnmarshalOutput{NoUnkeyedLiterals: input.NoUnkeyedLiterals, Flags: input.Flags}, fmt.Errorf("proto: TestVersion3: illegal tag %d (wire type %d)", fieldNum, wire) + } + switch fieldNum { + case 1: + if wireType != 0 { + return protoiface.UnmarshalOutput{NoUnkeyedLiterals: input.NoUnkeyedLiterals, Flags: input.Flags}, fmt.Errorf("proto: wrong wireType = %d for field X", wireType) + } + x.X = 0 + for shift := uint(0); ; shift += 7 { + if shift >= 64 { + return protoiface.UnmarshalOutput{NoUnkeyedLiterals: input.NoUnkeyedLiterals, Flags: input.Flags}, runtime.ErrIntOverflow + } + if iNdEx >= l { + return protoiface.UnmarshalOutput{NoUnkeyedLiterals: input.NoUnkeyedLiterals, Flags: input.Flags}, io.ErrUnexpectedEOF + } + b := dAtA[iNdEx] + iNdEx++ + x.X |= int64(b&0x7F) << shift + if b < 0x80 { + break + } + } + case 2: + if wireType != 2 { + return protoiface.UnmarshalOutput{NoUnkeyedLiterals: input.NoUnkeyedLiterals, Flags: input.Flags}, fmt.Errorf("proto: wrong wireType = %d for field A", wireType) + } + var msglen int + for shift := uint(0); ; shift += 7 { + if shift >= 64 { + return protoiface.UnmarshalOutput{NoUnkeyedLiterals: input.NoUnkeyedLiterals, Flags: input.Flags}, runtime.ErrIntOverflow + } + if iNdEx >= l { + return protoiface.UnmarshalOutput{NoUnkeyedLiterals: input.NoUnkeyedLiterals, Flags: input.Flags}, io.ErrUnexpectedEOF + } + b := dAtA[iNdEx] + iNdEx++ + msglen |= int(b&0x7F) << shift + if b < 0x80 { + break + } + } + if msglen < 0 { + return protoiface.UnmarshalOutput{NoUnkeyedLiterals: input.NoUnkeyedLiterals, Flags: input.Flags}, runtime.ErrInvalidLength + } + postIndex := iNdEx + msglen + if postIndex < 0 { + return protoiface.UnmarshalOutput{NoUnkeyedLiterals: input.NoUnkeyedLiterals, Flags: input.Flags}, runtime.ErrInvalidLength + } + if postIndex > l { + return protoiface.UnmarshalOutput{NoUnkeyedLiterals: input.NoUnkeyedLiterals, Flags: input.Flags}, io.ErrUnexpectedEOF + } + if x.A == nil { + x.A = &TestVersion3{} + } + if err := options.Unmarshal(dAtA[iNdEx:postIndex], x.A); err != nil { + return protoiface.UnmarshalOutput{NoUnkeyedLiterals: input.NoUnkeyedLiterals, Flags: input.Flags}, err + } + iNdEx = postIndex + case 3: + if wireType != 2 { + return protoiface.UnmarshalOutput{NoUnkeyedLiterals: input.NoUnkeyedLiterals, Flags: input.Flags}, fmt.Errorf("proto: wrong wireType = %d for field B", wireType) + } + var msglen int + for shift := uint(0); ; shift += 7 { + if shift >= 64 { + return protoiface.UnmarshalOutput{NoUnkeyedLiterals: input.NoUnkeyedLiterals, Flags: input.Flags}, runtime.ErrIntOverflow + } + if iNdEx >= l { + return protoiface.UnmarshalOutput{NoUnkeyedLiterals: input.NoUnkeyedLiterals, Flags: input.Flags}, io.ErrUnexpectedEOF + } + b := dAtA[iNdEx] + iNdEx++ + msglen |= int(b&0x7F) << shift + if b < 0x80 { + break + } + } + if msglen < 0 { + return protoiface.UnmarshalOutput{NoUnkeyedLiterals: input.NoUnkeyedLiterals, Flags: input.Flags}, runtime.ErrInvalidLength + } + postIndex := iNdEx + msglen + if postIndex < 0 { + return protoiface.UnmarshalOutput{NoUnkeyedLiterals: input.NoUnkeyedLiterals, Flags: input.Flags}, runtime.ErrInvalidLength + } + if postIndex > l { + return protoiface.UnmarshalOutput{NoUnkeyedLiterals: input.NoUnkeyedLiterals, Flags: input.Flags}, io.ErrUnexpectedEOF + } + if x.B == nil { + x.B = &TestVersion3{} + } + if err := options.Unmarshal(dAtA[iNdEx:postIndex], x.B); err != nil { + return protoiface.UnmarshalOutput{NoUnkeyedLiterals: input.NoUnkeyedLiterals, Flags: input.Flags}, err + } + iNdEx = postIndex + case 4: + if wireType != 2 { + return protoiface.UnmarshalOutput{NoUnkeyedLiterals: input.NoUnkeyedLiterals, Flags: input.Flags}, fmt.Errorf("proto: wrong wireType = %d for field C", wireType) + } + var msglen int + for shift := uint(0); ; shift += 7 { + if shift >= 64 { + return protoiface.UnmarshalOutput{NoUnkeyedLiterals: input.NoUnkeyedLiterals, Flags: input.Flags}, runtime.ErrIntOverflow + } + if iNdEx >= l { + return protoiface.UnmarshalOutput{NoUnkeyedLiterals: input.NoUnkeyedLiterals, Flags: input.Flags}, io.ErrUnexpectedEOF + } + b := dAtA[iNdEx] + iNdEx++ + msglen |= int(b&0x7F) << shift + if b < 0x80 { + break + } + } + if msglen < 0 { + return protoiface.UnmarshalOutput{NoUnkeyedLiterals: input.NoUnkeyedLiterals, Flags: input.Flags}, runtime.ErrInvalidLength + } + postIndex := iNdEx + msglen + if postIndex < 0 { + return protoiface.UnmarshalOutput{NoUnkeyedLiterals: input.NoUnkeyedLiterals, Flags: input.Flags}, runtime.ErrInvalidLength + } + if postIndex > l { + return protoiface.UnmarshalOutput{NoUnkeyedLiterals: input.NoUnkeyedLiterals, Flags: input.Flags}, io.ErrUnexpectedEOF + } + x.C = append(x.C, &TestVersion3{}) + if err := options.Unmarshal(dAtA[iNdEx:postIndex], x.C[len(x.C)-1]); err != nil { + return protoiface.UnmarshalOutput{NoUnkeyedLiterals: input.NoUnkeyedLiterals, Flags: input.Flags}, err + } + iNdEx = postIndex + case 5: + if wireType != 2 { + return protoiface.UnmarshalOutput{NoUnkeyedLiterals: input.NoUnkeyedLiterals, Flags: input.Flags}, fmt.Errorf("proto: wrong wireType = %d for field D", wireType) + } + var msglen int + for shift := uint(0); ; shift += 7 { + if shift >= 64 { + return protoiface.UnmarshalOutput{NoUnkeyedLiterals: input.NoUnkeyedLiterals, Flags: input.Flags}, runtime.ErrIntOverflow + } + if iNdEx >= l { + return protoiface.UnmarshalOutput{NoUnkeyedLiterals: input.NoUnkeyedLiterals, Flags: input.Flags}, io.ErrUnexpectedEOF + } + b := dAtA[iNdEx] + iNdEx++ + msglen |= int(b&0x7F) << shift + if b < 0x80 { + break + } + } + if msglen < 0 { + return protoiface.UnmarshalOutput{NoUnkeyedLiterals: input.NoUnkeyedLiterals, Flags: input.Flags}, runtime.ErrInvalidLength + } + postIndex := iNdEx + msglen + if postIndex < 0 { + return protoiface.UnmarshalOutput{NoUnkeyedLiterals: input.NoUnkeyedLiterals, Flags: input.Flags}, runtime.ErrInvalidLength + } + if postIndex > l { + return protoiface.UnmarshalOutput{NoUnkeyedLiterals: input.NoUnkeyedLiterals, Flags: input.Flags}, io.ErrUnexpectedEOF + } + x.D = append(x.D, &TestVersion3{}) + if err := options.Unmarshal(dAtA[iNdEx:postIndex], x.D[len(x.D)-1]); err != nil { + return protoiface.UnmarshalOutput{NoUnkeyedLiterals: input.NoUnkeyedLiterals, Flags: input.Flags}, err + } + iNdEx = postIndex + case 6: + if wireType != 0 { + return protoiface.UnmarshalOutput{NoUnkeyedLiterals: input.NoUnkeyedLiterals, Flags: input.Flags}, fmt.Errorf("proto: wrong wireType = %d for field E", wireType) + } + var v int32 + for shift := uint(0); ; shift += 7 { + if shift >= 64 { + return protoiface.UnmarshalOutput{NoUnkeyedLiterals: input.NoUnkeyedLiterals, Flags: input.Flags}, runtime.ErrIntOverflow + } + if iNdEx >= l { + return protoiface.UnmarshalOutput{NoUnkeyedLiterals: input.NoUnkeyedLiterals, Flags: input.Flags}, io.ErrUnexpectedEOF + } + b := dAtA[iNdEx] + iNdEx++ + v |= int32(b&0x7F) << shift + if b < 0x80 { + break + } + } + x.Sum = &TestVersion3_E{v} + case 7: + if wireType != 2 { + return protoiface.UnmarshalOutput{NoUnkeyedLiterals: input.NoUnkeyedLiterals, Flags: input.Flags}, fmt.Errorf("proto: wrong wireType = %d for field F", wireType) + } + var msglen int + for shift := uint(0); ; shift += 7 { + if shift >= 64 { + return protoiface.UnmarshalOutput{NoUnkeyedLiterals: input.NoUnkeyedLiterals, Flags: input.Flags}, runtime.ErrIntOverflow + } + if iNdEx >= l { + return protoiface.UnmarshalOutput{NoUnkeyedLiterals: input.NoUnkeyedLiterals, Flags: input.Flags}, io.ErrUnexpectedEOF + } + b := dAtA[iNdEx] + iNdEx++ + msglen |= int(b&0x7F) << shift + if b < 0x80 { + break + } + } + if msglen < 0 { + return protoiface.UnmarshalOutput{NoUnkeyedLiterals: input.NoUnkeyedLiterals, Flags: input.Flags}, runtime.ErrInvalidLength + } + postIndex := iNdEx + msglen + if postIndex < 0 { + return protoiface.UnmarshalOutput{NoUnkeyedLiterals: input.NoUnkeyedLiterals, Flags: input.Flags}, runtime.ErrInvalidLength + } + if postIndex > l { + return protoiface.UnmarshalOutput{NoUnkeyedLiterals: input.NoUnkeyedLiterals, Flags: input.Flags}, io.ErrUnexpectedEOF + } + v := &TestVersion3{} + if err := options.Unmarshal(dAtA[iNdEx:postIndex], v); err != nil { + return protoiface.UnmarshalOutput{NoUnkeyedLiterals: input.NoUnkeyedLiterals, Flags: input.Flags}, err + } + x.Sum = &TestVersion3_F{v} + iNdEx = postIndex + case 8: + if wireType != 2 { + return protoiface.UnmarshalOutput{NoUnkeyedLiterals: input.NoUnkeyedLiterals, Flags: input.Flags}, fmt.Errorf("proto: wrong wireType = %d for field G", wireType) + } + var msglen int + for shift := uint(0); ; shift += 7 { + if shift >= 64 { + return protoiface.UnmarshalOutput{NoUnkeyedLiterals: input.NoUnkeyedLiterals, Flags: input.Flags}, runtime.ErrIntOverflow + } + if iNdEx >= l { + return protoiface.UnmarshalOutput{NoUnkeyedLiterals: input.NoUnkeyedLiterals, Flags: input.Flags}, io.ErrUnexpectedEOF + } + b := dAtA[iNdEx] + iNdEx++ + msglen |= int(b&0x7F) << shift + if b < 0x80 { + break + } + } + if msglen < 0 { + return protoiface.UnmarshalOutput{NoUnkeyedLiterals: input.NoUnkeyedLiterals, Flags: input.Flags}, runtime.ErrInvalidLength + } + postIndex := iNdEx + msglen + if postIndex < 0 { + return protoiface.UnmarshalOutput{NoUnkeyedLiterals: input.NoUnkeyedLiterals, Flags: input.Flags}, runtime.ErrInvalidLength + } + if postIndex > l { + return protoiface.UnmarshalOutput{NoUnkeyedLiterals: input.NoUnkeyedLiterals, Flags: input.Flags}, io.ErrUnexpectedEOF + } + if x.G == nil { + x.G = &anypb.Any{} + } + if err := options.Unmarshal(dAtA[iNdEx:postIndex], x.G); err != nil { + return protoiface.UnmarshalOutput{NoUnkeyedLiterals: input.NoUnkeyedLiterals, Flags: input.Flags}, err + } + iNdEx = postIndex + case 9: + if wireType != 2 { + return protoiface.UnmarshalOutput{NoUnkeyedLiterals: input.NoUnkeyedLiterals, Flags: input.Flags}, fmt.Errorf("proto: wrong wireType = %d for field H", wireType) + } + var msglen int + for shift := uint(0); ; shift += 7 { + if shift >= 64 { + return protoiface.UnmarshalOutput{NoUnkeyedLiterals: input.NoUnkeyedLiterals, Flags: input.Flags}, runtime.ErrIntOverflow + } + if iNdEx >= l { + return protoiface.UnmarshalOutput{NoUnkeyedLiterals: input.NoUnkeyedLiterals, Flags: input.Flags}, io.ErrUnexpectedEOF + } + b := dAtA[iNdEx] + iNdEx++ + msglen |= int(b&0x7F) << shift + if b < 0x80 { + break + } + } + if msglen < 0 { + return protoiface.UnmarshalOutput{NoUnkeyedLiterals: input.NoUnkeyedLiterals, Flags: input.Flags}, runtime.ErrInvalidLength + } + postIndex := iNdEx + msglen + if postIndex < 0 { + return protoiface.UnmarshalOutput{NoUnkeyedLiterals: input.NoUnkeyedLiterals, Flags: input.Flags}, runtime.ErrInvalidLength + } + if postIndex > l { + return protoiface.UnmarshalOutput{NoUnkeyedLiterals: input.NoUnkeyedLiterals, Flags: input.Flags}, io.ErrUnexpectedEOF + } + x.H = append(x.H, &TestVersion1{}) + if err := options.Unmarshal(dAtA[iNdEx:postIndex], x.H[len(x.H)-1]); err != nil { + return protoiface.UnmarshalOutput{NoUnkeyedLiterals: input.NoUnkeyedLiterals, Flags: input.Flags}, err + } + iNdEx = postIndex + case 12: + if wireType != 2 { + return protoiface.UnmarshalOutput{NoUnkeyedLiterals: input.NoUnkeyedLiterals, Flags: input.Flags}, fmt.Errorf("proto: wrong wireType = %d for field K", wireType) + } + var msglen int + for shift := uint(0); ; shift += 7 { + if shift >= 64 { + return protoiface.UnmarshalOutput{NoUnkeyedLiterals: input.NoUnkeyedLiterals, Flags: input.Flags}, runtime.ErrIntOverflow + } + if iNdEx >= l { + return protoiface.UnmarshalOutput{NoUnkeyedLiterals: input.NoUnkeyedLiterals, Flags: input.Flags}, io.ErrUnexpectedEOF + } + b := dAtA[iNdEx] + iNdEx++ + msglen |= int(b&0x7F) << shift + if b < 0x80 { + break + } + } + if msglen < 0 { + return protoiface.UnmarshalOutput{NoUnkeyedLiterals: input.NoUnkeyedLiterals, Flags: input.Flags}, runtime.ErrInvalidLength + } + postIndex := iNdEx + msglen + if postIndex < 0 { + return protoiface.UnmarshalOutput{NoUnkeyedLiterals: input.NoUnkeyedLiterals, Flags: input.Flags}, runtime.ErrInvalidLength + } + if postIndex > l { + return protoiface.UnmarshalOutput{NoUnkeyedLiterals: input.NoUnkeyedLiterals, Flags: input.Flags}, io.ErrUnexpectedEOF + } + if x.K == nil { + x.K = &Customer1{} + } + if err := options.Unmarshal(dAtA[iNdEx:postIndex], x.K); err != nil { + return protoiface.UnmarshalOutput{NoUnkeyedLiterals: input.NoUnkeyedLiterals, Flags: input.Flags}, err + } + iNdEx = postIndex + case 1031: + if wireType != 2 { + return protoiface.UnmarshalOutput{NoUnkeyedLiterals: input.NoUnkeyedLiterals, Flags: input.Flags}, fmt.Errorf("proto: wrong wireType = %d for field NonCriticalField", wireType) + } + var stringLen uint64 + for shift := uint(0); ; shift += 7 { + if shift >= 64 { + return protoiface.UnmarshalOutput{NoUnkeyedLiterals: input.NoUnkeyedLiterals, Flags: input.Flags}, runtime.ErrIntOverflow + } + if iNdEx >= l { + return protoiface.UnmarshalOutput{NoUnkeyedLiterals: input.NoUnkeyedLiterals, Flags: input.Flags}, io.ErrUnexpectedEOF + } + b := dAtA[iNdEx] + iNdEx++ + stringLen |= uint64(b&0x7F) << shift + if b < 0x80 { + break + } + } + intStringLen := int(stringLen) + if intStringLen < 0 { + return protoiface.UnmarshalOutput{NoUnkeyedLiterals: input.NoUnkeyedLiterals, Flags: input.Flags}, runtime.ErrInvalidLength + } + postIndex := iNdEx + intStringLen + if postIndex < 0 { + return protoiface.UnmarshalOutput{NoUnkeyedLiterals: input.NoUnkeyedLiterals, Flags: input.Flags}, runtime.ErrInvalidLength + } + if postIndex > l { + return protoiface.UnmarshalOutput{NoUnkeyedLiterals: input.NoUnkeyedLiterals, Flags: input.Flags}, io.ErrUnexpectedEOF + } + x.NonCriticalField = string(dAtA[iNdEx:postIndex]) + iNdEx = postIndex + default: + iNdEx = preIndex + skippy, err := runtime.Skip(dAtA[iNdEx:]) + if err != nil { + return protoiface.UnmarshalOutput{NoUnkeyedLiterals: input.NoUnkeyedLiterals, Flags: input.Flags}, err + } + if (skippy < 0) || (iNdEx+skippy) < 0 { + return protoiface.UnmarshalOutput{NoUnkeyedLiterals: input.NoUnkeyedLiterals, Flags: input.Flags}, runtime.ErrInvalidLength + } + if (iNdEx + skippy) > l { + return protoiface.UnmarshalOutput{NoUnkeyedLiterals: input.NoUnkeyedLiterals, Flags: input.Flags}, io.ErrUnexpectedEOF + } + if !options.DiscardUnknown { + x.unknownFields = append(x.unknownFields, dAtA[iNdEx:iNdEx+skippy]...) + } + iNdEx += skippy + } + } + + if iNdEx > l { + return protoiface.UnmarshalOutput{NoUnkeyedLiterals: input.NoUnkeyedLiterals, Flags: input.Flags}, io.ErrUnexpectedEOF + } + return protoiface.UnmarshalOutput{NoUnkeyedLiterals: input.NoUnkeyedLiterals, Flags: input.Flags}, nil + } + return &protoiface.Methods{ + NoUnkeyedLiterals: struct{}{}, + Flags: protoiface.SupportMarshalDeterministic | protoiface.SupportUnmarshalDiscardUnknown, + Size: size, + Marshal: marshal, + Unmarshal: unmarshal, + Merge: nil, + CheckInitialized: nil, + } +} + +var _ protoreflect.List = (*_TestVersion3LoneOneOfValue_4_list)(nil) + +type _TestVersion3LoneOneOfValue_4_list struct { + list *[]*TestVersion3 +} + +func (x *_TestVersion3LoneOneOfValue_4_list) Len() int { + if x.list == nil { + return 0 + } + return len(*x.list) +} + +func (x *_TestVersion3LoneOneOfValue_4_list) Get(i int) protoreflect.Value { + return protoreflect.ValueOfMessage((*x.list)[i].ProtoReflect()) +} + +func (x *_TestVersion3LoneOneOfValue_4_list) Set(i int, value protoreflect.Value) { + valueUnwrapped := value.Message() + concreteValue := valueUnwrapped.Interface().(*TestVersion3) + (*x.list)[i] = concreteValue +} + +func (x *_TestVersion3LoneOneOfValue_4_list) Append(value protoreflect.Value) { + valueUnwrapped := value.Message() + concreteValue := valueUnwrapped.Interface().(*TestVersion3) + *x.list = append(*x.list, concreteValue) +} + +func (x *_TestVersion3LoneOneOfValue_4_list) AppendMutable() protoreflect.Value { + v := new(TestVersion3) + *x.list = append(*x.list, v) + return protoreflect.ValueOfMessage(v.ProtoReflect()) +} + +func (x *_TestVersion3LoneOneOfValue_4_list) Truncate(n int) { + for i := n; i < len(*x.list); i++ { + (*x.list)[i] = nil + } + *x.list = (*x.list)[:n] +} + +func (x *_TestVersion3LoneOneOfValue_4_list) NewElement() protoreflect.Value { + v := new(TestVersion3) + return protoreflect.ValueOfMessage(v.ProtoReflect()) +} + +func (x *_TestVersion3LoneOneOfValue_4_list) IsValid() bool { + return x.list != nil +} + +var _ protoreflect.List = (*_TestVersion3LoneOneOfValue_5_list)(nil) + +type _TestVersion3LoneOneOfValue_5_list struct { + list *[]*TestVersion3 +} + +func (x *_TestVersion3LoneOneOfValue_5_list) Len() int { + if x.list == nil { + return 0 + } + return len(*x.list) +} + +func (x *_TestVersion3LoneOneOfValue_5_list) Get(i int) protoreflect.Value { + return protoreflect.ValueOfMessage((*x.list)[i].ProtoReflect()) +} + +func (x *_TestVersion3LoneOneOfValue_5_list) Set(i int, value protoreflect.Value) { + valueUnwrapped := value.Message() + concreteValue := valueUnwrapped.Interface().(*TestVersion3) + (*x.list)[i] = concreteValue +} + +func (x *_TestVersion3LoneOneOfValue_5_list) Append(value protoreflect.Value) { + valueUnwrapped := value.Message() + concreteValue := valueUnwrapped.Interface().(*TestVersion3) + *x.list = append(*x.list, concreteValue) +} + +func (x *_TestVersion3LoneOneOfValue_5_list) AppendMutable() protoreflect.Value { + v := new(TestVersion3) + *x.list = append(*x.list, v) + return protoreflect.ValueOfMessage(v.ProtoReflect()) +} + +func (x *_TestVersion3LoneOneOfValue_5_list) Truncate(n int) { + for i := n; i < len(*x.list); i++ { + (*x.list)[i] = nil + } + *x.list = (*x.list)[:n] +} + +func (x *_TestVersion3LoneOneOfValue_5_list) NewElement() protoreflect.Value { + v := new(TestVersion3) + return protoreflect.ValueOfMessage(v.ProtoReflect()) +} + +func (x *_TestVersion3LoneOneOfValue_5_list) IsValid() bool { + return x.list != nil +} + +var _ protoreflect.List = (*_TestVersion3LoneOneOfValue_9_list)(nil) + +type _TestVersion3LoneOneOfValue_9_list struct { + list *[]*TestVersion1 +} + +func (x *_TestVersion3LoneOneOfValue_9_list) Len() int { + if x.list == nil { + return 0 + } + return len(*x.list) +} + +func (x *_TestVersion3LoneOneOfValue_9_list) Get(i int) protoreflect.Value { + return protoreflect.ValueOfMessage((*x.list)[i].ProtoReflect()) +} + +func (x *_TestVersion3LoneOneOfValue_9_list) Set(i int, value protoreflect.Value) { + valueUnwrapped := value.Message() + concreteValue := valueUnwrapped.Interface().(*TestVersion1) + (*x.list)[i] = concreteValue +} + +func (x *_TestVersion3LoneOneOfValue_9_list) Append(value protoreflect.Value) { + valueUnwrapped := value.Message() + concreteValue := valueUnwrapped.Interface().(*TestVersion1) + *x.list = append(*x.list, concreteValue) +} + +func (x *_TestVersion3LoneOneOfValue_9_list) AppendMutable() protoreflect.Value { + v := new(TestVersion1) + *x.list = append(*x.list, v) + return protoreflect.ValueOfMessage(v.ProtoReflect()) +} + +func (x *_TestVersion3LoneOneOfValue_9_list) Truncate(n int) { + for i := n; i < len(*x.list); i++ { + (*x.list)[i] = nil + } + *x.list = (*x.list)[:n] +} + +func (x *_TestVersion3LoneOneOfValue_9_list) NewElement() protoreflect.Value { + v := new(TestVersion1) + return protoreflect.ValueOfMessage(v.ProtoReflect()) +} + +func (x *_TestVersion3LoneOneOfValue_9_list) IsValid() bool { + return x.list != nil +} + +var ( + md_TestVersion3LoneOneOfValue protoreflect.MessageDescriptor + fd_TestVersion3LoneOneOfValue_x protoreflect.FieldDescriptor + fd_TestVersion3LoneOneOfValue_a protoreflect.FieldDescriptor + fd_TestVersion3LoneOneOfValue_b protoreflect.FieldDescriptor + fd_TestVersion3LoneOneOfValue_c protoreflect.FieldDescriptor + fd_TestVersion3LoneOneOfValue_d protoreflect.FieldDescriptor + fd_TestVersion3LoneOneOfValue_e protoreflect.FieldDescriptor + fd_TestVersion3LoneOneOfValue_g protoreflect.FieldDescriptor + fd_TestVersion3LoneOneOfValue_h protoreflect.FieldDescriptor + fd_TestVersion3LoneOneOfValue_k protoreflect.FieldDescriptor + fd_TestVersion3LoneOneOfValue_non_critical_field protoreflect.FieldDescriptor +) + +func init() { + file_unknownproto_proto_init() + md_TestVersion3LoneOneOfValue = File_unknownproto_proto.Messages().ByName("TestVersion3LoneOneOfValue") + fd_TestVersion3LoneOneOfValue_x = md_TestVersion3LoneOneOfValue.Fields().ByName("x") + fd_TestVersion3LoneOneOfValue_a = md_TestVersion3LoneOneOfValue.Fields().ByName("a") + fd_TestVersion3LoneOneOfValue_b = md_TestVersion3LoneOneOfValue.Fields().ByName("b") + fd_TestVersion3LoneOneOfValue_c = md_TestVersion3LoneOneOfValue.Fields().ByName("c") + fd_TestVersion3LoneOneOfValue_d = md_TestVersion3LoneOneOfValue.Fields().ByName("d") + fd_TestVersion3LoneOneOfValue_e = md_TestVersion3LoneOneOfValue.Fields().ByName("e") + fd_TestVersion3LoneOneOfValue_g = md_TestVersion3LoneOneOfValue.Fields().ByName("g") + fd_TestVersion3LoneOneOfValue_h = md_TestVersion3LoneOneOfValue.Fields().ByName("h") + fd_TestVersion3LoneOneOfValue_k = md_TestVersion3LoneOneOfValue.Fields().ByName("k") + fd_TestVersion3LoneOneOfValue_non_critical_field = md_TestVersion3LoneOneOfValue.Fields().ByName("non_critical_field") +} + +var _ protoreflect.Message = (*fastReflection_TestVersion3LoneOneOfValue)(nil) + +type fastReflection_TestVersion3LoneOneOfValue TestVersion3LoneOneOfValue + +func (x *TestVersion3LoneOneOfValue) ProtoReflect() protoreflect.Message { + return (*fastReflection_TestVersion3LoneOneOfValue)(x) +} + +func (x *TestVersion3LoneOneOfValue) slowProtoReflect() protoreflect.Message { + mi := &file_unknownproto_proto_msgTypes[14] + if protoimpl.UnsafeEnabled && x != nil { + ms := protoimpl.X.MessageStateOf(protoimpl.Pointer(x)) + if ms.LoadMessageInfo() == nil { + ms.StoreMessageInfo(mi) + } + return ms + } + return mi.MessageOf(x) +} + +var _fastReflection_TestVersion3LoneOneOfValue_messageType fastReflection_TestVersion3LoneOneOfValue_messageType +var _ protoreflect.MessageType = fastReflection_TestVersion3LoneOneOfValue_messageType{} + +type fastReflection_TestVersion3LoneOneOfValue_messageType struct{} + +func (x fastReflection_TestVersion3LoneOneOfValue_messageType) Zero() protoreflect.Message { + return (*fastReflection_TestVersion3LoneOneOfValue)(nil) +} +func (x fastReflection_TestVersion3LoneOneOfValue_messageType) New() protoreflect.Message { + return new(fastReflection_TestVersion3LoneOneOfValue) +} +func (x fastReflection_TestVersion3LoneOneOfValue_messageType) Descriptor() protoreflect.MessageDescriptor { + return md_TestVersion3LoneOneOfValue +} + +// Descriptor returns message descriptor, which contains only the protobuf +// type information for the message. +func (x *fastReflection_TestVersion3LoneOneOfValue) Descriptor() protoreflect.MessageDescriptor { + return md_TestVersion3LoneOneOfValue +} + +// Type returns the message type, which encapsulates both Go and protobuf +// type information. If the Go type information is not needed, +// it is recommended that the message descriptor be used instead. +func (x *fastReflection_TestVersion3LoneOneOfValue) Type() protoreflect.MessageType { + return _fastReflection_TestVersion3LoneOneOfValue_messageType +} + +// New returns a newly allocated and mutable empty message. +func (x *fastReflection_TestVersion3LoneOneOfValue) New() protoreflect.Message { + return new(fastReflection_TestVersion3LoneOneOfValue) +} + +// Interface unwraps the message reflection interface and +// returns the underlying ProtoMessage interface. +func (x *fastReflection_TestVersion3LoneOneOfValue) Interface() protoreflect.ProtoMessage { + return (*TestVersion3LoneOneOfValue)(x) +} + +// Range iterates over every populated field in an undefined order, +// calling f for each field descriptor and value encountered. +// Range returns immediately if f returns false. +// While iterating, mutating operations may only be performed +// on the current field descriptor. +func (x *fastReflection_TestVersion3LoneOneOfValue) Range(f func(protoreflect.FieldDescriptor, protoreflect.Value) bool) { + if x.X != int64(0) { + value := protoreflect.ValueOfInt64(x.X) + if !f(fd_TestVersion3LoneOneOfValue_x, value) { + return + } + } + if x.A != nil { + value := protoreflect.ValueOfMessage(x.A.ProtoReflect()) + if !f(fd_TestVersion3LoneOneOfValue_a, value) { + return + } + } + if x.B != nil { + value := protoreflect.ValueOfMessage(x.B.ProtoReflect()) + if !f(fd_TestVersion3LoneOneOfValue_b, value) { + return + } + } + if len(x.C) != 0 { + value := protoreflect.ValueOfList(&_TestVersion3LoneOneOfValue_4_list{list: &x.C}) + if !f(fd_TestVersion3LoneOneOfValue_c, value) { + return + } + } + if len(x.D) != 0 { + value := protoreflect.ValueOfList(&_TestVersion3LoneOneOfValue_5_list{list: &x.D}) + if !f(fd_TestVersion3LoneOneOfValue_d, value) { + return + } + } + if x.Sum != nil { + switch o := x.Sum.(type) { + case *TestVersion3LoneOneOfValue_E: + v := o.E + value := protoreflect.ValueOfInt32(v) + if !f(fd_TestVersion3LoneOneOfValue_e, value) { + return + } + } + } + if x.G != nil { + value := protoreflect.ValueOfMessage(x.G.ProtoReflect()) + if !f(fd_TestVersion3LoneOneOfValue_g, value) { + return + } + } + if len(x.H) != 0 { + value := protoreflect.ValueOfList(&_TestVersion3LoneOneOfValue_9_list{list: &x.H}) + if !f(fd_TestVersion3LoneOneOfValue_h, value) { + return + } + } + if x.K != nil { + value := protoreflect.ValueOfMessage(x.K.ProtoReflect()) + if !f(fd_TestVersion3LoneOneOfValue_k, value) { + return + } + } + if x.NonCriticalField != "" { + value := protoreflect.ValueOfString(x.NonCriticalField) + if !f(fd_TestVersion3LoneOneOfValue_non_critical_field, value) { + return + } + } +} + +// Has reports whether a field is populated. +// +// Some fields have the property of nullability where it is possible to +// distinguish between the default value of a field and whether the field +// was explicitly populated with the default value. Singular message fields, +// member fields of a oneof, and proto2 scalar fields are nullable. Such +// fields are populated only if explicitly set. +// +// In other cases (aside from the nullable cases above), +// a proto3 scalar field is populated if it contains a non-zero value, and +// a repeated field is populated if it is non-empty. +func (x *fastReflection_TestVersion3LoneOneOfValue) Has(fd protoreflect.FieldDescriptor) bool { + switch fd.FullName() { + case "testpb.TestVersion3LoneOneOfValue.x": + return x.X != int64(0) + case "testpb.TestVersion3LoneOneOfValue.a": + return x.A != nil + case "testpb.TestVersion3LoneOneOfValue.b": + return x.B != nil + case "testpb.TestVersion3LoneOneOfValue.c": + return len(x.C) != 0 + case "testpb.TestVersion3LoneOneOfValue.d": + return len(x.D) != 0 + case "testpb.TestVersion3LoneOneOfValue.e": + if x.Sum == nil { + return false + } else if _, ok := x.Sum.(*TestVersion3LoneOneOfValue_E); ok { + return true + } else { + return false + } + case "testpb.TestVersion3LoneOneOfValue.g": + return x.G != nil + case "testpb.TestVersion3LoneOneOfValue.h": + return len(x.H) != 0 + case "testpb.TestVersion3LoneOneOfValue.k": + return x.K != nil + case "testpb.TestVersion3LoneOneOfValue.non_critical_field": + return x.NonCriticalField != "" + default: + if fd.IsExtension() { + panic(fmt.Errorf("proto3 declared messages do not support extensions: testpb.TestVersion3LoneOneOfValue")) + } + panic(fmt.Errorf("message testpb.TestVersion3LoneOneOfValue does not contain field %s", fd.FullName())) + } +} + +// Clear clears the field such that a subsequent Has call reports false. +// +// Clearing an extension field clears both the extension type and value +// associated with the given field number. +// +// Clear is a mutating operation and unsafe for concurrent use. +func (x *fastReflection_TestVersion3LoneOneOfValue) Clear(fd protoreflect.FieldDescriptor) { + switch fd.FullName() { + case "testpb.TestVersion3LoneOneOfValue.x": + x.X = int64(0) + case "testpb.TestVersion3LoneOneOfValue.a": + x.A = nil + case "testpb.TestVersion3LoneOneOfValue.b": + x.B = nil + case "testpb.TestVersion3LoneOneOfValue.c": + x.C = nil + case "testpb.TestVersion3LoneOneOfValue.d": + x.D = nil + case "testpb.TestVersion3LoneOneOfValue.e": + x.Sum = nil + case "testpb.TestVersion3LoneOneOfValue.g": + x.G = nil + case "testpb.TestVersion3LoneOneOfValue.h": + x.H = nil + case "testpb.TestVersion3LoneOneOfValue.k": + x.K = nil + case "testpb.TestVersion3LoneOneOfValue.non_critical_field": + x.NonCriticalField = "" + default: + if fd.IsExtension() { + panic(fmt.Errorf("proto3 declared messages do not support extensions: testpb.TestVersion3LoneOneOfValue")) + } + panic(fmt.Errorf("message testpb.TestVersion3LoneOneOfValue does not contain field %s", fd.FullName())) + } +} + +// Get retrieves the value for a field. +// +// For unpopulated scalars, it returns the default value, where +// the default value of a bytes scalar is guaranteed to be a copy. +// For unpopulated composite types, it returns an empty, read-only view +// of the value; to obtain a mutable reference, use Mutable. +func (x *fastReflection_TestVersion3LoneOneOfValue) Get(descriptor protoreflect.FieldDescriptor) protoreflect.Value { + switch descriptor.FullName() { + case "testpb.TestVersion3LoneOneOfValue.x": + value := x.X + return protoreflect.ValueOfInt64(value) + case "testpb.TestVersion3LoneOneOfValue.a": + value := x.A + return protoreflect.ValueOfMessage(value.ProtoReflect()) + case "testpb.TestVersion3LoneOneOfValue.b": + value := x.B + return protoreflect.ValueOfMessage(value.ProtoReflect()) + case "testpb.TestVersion3LoneOneOfValue.c": + if len(x.C) == 0 { + return protoreflect.ValueOfList(&_TestVersion3LoneOneOfValue_4_list{}) + } + listValue := &_TestVersion3LoneOneOfValue_4_list{list: &x.C} + return protoreflect.ValueOfList(listValue) + case "testpb.TestVersion3LoneOneOfValue.d": + if len(x.D) == 0 { + return protoreflect.ValueOfList(&_TestVersion3LoneOneOfValue_5_list{}) + } + listValue := &_TestVersion3LoneOneOfValue_5_list{list: &x.D} + return protoreflect.ValueOfList(listValue) + case "testpb.TestVersion3LoneOneOfValue.e": + if x.Sum == nil { + return protoreflect.ValueOfInt32(int32(0)) + } else if v, ok := x.Sum.(*TestVersion3LoneOneOfValue_E); ok { + return protoreflect.ValueOfInt32(v.E) + } else { + return protoreflect.ValueOfInt32(int32(0)) + } + case "testpb.TestVersion3LoneOneOfValue.g": + value := x.G + return protoreflect.ValueOfMessage(value.ProtoReflect()) + case "testpb.TestVersion3LoneOneOfValue.h": + if len(x.H) == 0 { + return protoreflect.ValueOfList(&_TestVersion3LoneOneOfValue_9_list{}) + } + listValue := &_TestVersion3LoneOneOfValue_9_list{list: &x.H} + return protoreflect.ValueOfList(listValue) + case "testpb.TestVersion3LoneOneOfValue.k": + value := x.K + return protoreflect.ValueOfMessage(value.ProtoReflect()) + case "testpb.TestVersion3LoneOneOfValue.non_critical_field": + value := x.NonCriticalField + return protoreflect.ValueOfString(value) + default: + if descriptor.IsExtension() { + panic(fmt.Errorf("proto3 declared messages do not support extensions: testpb.TestVersion3LoneOneOfValue")) + } + panic(fmt.Errorf("message testpb.TestVersion3LoneOneOfValue does not contain field %s", descriptor.FullName())) + } +} + +// Set stores the value for a field. +// +// For a field belonging to a oneof, it implicitly clears any other field +// that may be currently set within the same oneof. +// For extension fields, it implicitly stores the provided ExtensionType. +// When setting a composite type, it is unspecified whether the stored value +// aliases the source's memory in any way. If the composite value is an +// empty, read-only value, then it panics. +// +// Set is a mutating operation and unsafe for concurrent use. +func (x *fastReflection_TestVersion3LoneOneOfValue) Set(fd protoreflect.FieldDescriptor, value protoreflect.Value) { + switch fd.FullName() { + case "testpb.TestVersion3LoneOneOfValue.x": + x.X = value.Int() + case "testpb.TestVersion3LoneOneOfValue.a": + x.A = value.Message().Interface().(*TestVersion3) + case "testpb.TestVersion3LoneOneOfValue.b": + x.B = value.Message().Interface().(*TestVersion3) + case "testpb.TestVersion3LoneOneOfValue.c": + lv := value.List() + clv := lv.(*_TestVersion3LoneOneOfValue_4_list) + x.C = *clv.list + case "testpb.TestVersion3LoneOneOfValue.d": + lv := value.List() + clv := lv.(*_TestVersion3LoneOneOfValue_5_list) + x.D = *clv.list + case "testpb.TestVersion3LoneOneOfValue.e": + cv := int32(value.Int()) + x.Sum = &TestVersion3LoneOneOfValue_E{E: cv} + case "testpb.TestVersion3LoneOneOfValue.g": + x.G = value.Message().Interface().(*anypb.Any) + case "testpb.TestVersion3LoneOneOfValue.h": + lv := value.List() + clv := lv.(*_TestVersion3LoneOneOfValue_9_list) + x.H = *clv.list + case "testpb.TestVersion3LoneOneOfValue.k": + x.K = value.Message().Interface().(*Customer1) + case "testpb.TestVersion3LoneOneOfValue.non_critical_field": + x.NonCriticalField = value.Interface().(string) + default: + if fd.IsExtension() { + panic(fmt.Errorf("proto3 declared messages do not support extensions: testpb.TestVersion3LoneOneOfValue")) + } + panic(fmt.Errorf("message testpb.TestVersion3LoneOneOfValue does not contain field %s", fd.FullName())) + } +} + +// Mutable returns a mutable reference to a composite type. +// +// If the field is unpopulated, it may allocate a composite value. +// For a field belonging to a oneof, it implicitly clears any other field +// that may be currently set within the same oneof. +// For extension fields, it implicitly stores the provided ExtensionType +// if not already stored. +// It panics if the field does not contain a composite type. +// +// Mutable is a mutating operation and unsafe for concurrent use. +func (x *fastReflection_TestVersion3LoneOneOfValue) Mutable(fd protoreflect.FieldDescriptor) protoreflect.Value { + switch fd.FullName() { + case "testpb.TestVersion3LoneOneOfValue.a": + if x.A == nil { + x.A = new(TestVersion3) + } + return protoreflect.ValueOfMessage(x.A.ProtoReflect()) + case "testpb.TestVersion3LoneOneOfValue.b": + if x.B == nil { + x.B = new(TestVersion3) + } + return protoreflect.ValueOfMessage(x.B.ProtoReflect()) + case "testpb.TestVersion3LoneOneOfValue.c": + if x.C == nil { + x.C = []*TestVersion3{} + } + value := &_TestVersion3LoneOneOfValue_4_list{list: &x.C} + return protoreflect.ValueOfList(value) + case "testpb.TestVersion3LoneOneOfValue.d": + if x.D == nil { + x.D = []*TestVersion3{} + } + value := &_TestVersion3LoneOneOfValue_5_list{list: &x.D} + return protoreflect.ValueOfList(value) + case "testpb.TestVersion3LoneOneOfValue.g": + if x.G == nil { + x.G = new(anypb.Any) + } + return protoreflect.ValueOfMessage(x.G.ProtoReflect()) + case "testpb.TestVersion3LoneOneOfValue.h": + if x.H == nil { + x.H = []*TestVersion1{} + } + value := &_TestVersion3LoneOneOfValue_9_list{list: &x.H} + return protoreflect.ValueOfList(value) + case "testpb.TestVersion3LoneOneOfValue.k": + if x.K == nil { + x.K = new(Customer1) + } + return protoreflect.ValueOfMessage(x.K.ProtoReflect()) + case "testpb.TestVersion3LoneOneOfValue.x": + panic(fmt.Errorf("field x of message testpb.TestVersion3LoneOneOfValue is not mutable")) + case "testpb.TestVersion3LoneOneOfValue.e": + panic(fmt.Errorf("field e of message testpb.TestVersion3LoneOneOfValue is not mutable")) + case "testpb.TestVersion3LoneOneOfValue.non_critical_field": + panic(fmt.Errorf("field non_critical_field of message testpb.TestVersion3LoneOneOfValue is not mutable")) + default: + if fd.IsExtension() { + panic(fmt.Errorf("proto3 declared messages do not support extensions: testpb.TestVersion3LoneOneOfValue")) + } + panic(fmt.Errorf("message testpb.TestVersion3LoneOneOfValue does not contain field %s", fd.FullName())) + } +} + +// NewField returns a new value that is assignable to the field +// for the given descriptor. For scalars, this returns the default value. +// For lists, maps, and messages, this returns a new, empty, mutable value. +func (x *fastReflection_TestVersion3LoneOneOfValue) NewField(fd protoreflect.FieldDescriptor) protoreflect.Value { + switch fd.FullName() { + case "testpb.TestVersion3LoneOneOfValue.x": + return protoreflect.ValueOfInt64(int64(0)) + case "testpb.TestVersion3LoneOneOfValue.a": + m := new(TestVersion3) + return protoreflect.ValueOfMessage(m.ProtoReflect()) + case "testpb.TestVersion3LoneOneOfValue.b": + m := new(TestVersion3) + return protoreflect.ValueOfMessage(m.ProtoReflect()) + case "testpb.TestVersion3LoneOneOfValue.c": + list := []*TestVersion3{} + return protoreflect.ValueOfList(&_TestVersion3LoneOneOfValue_4_list{list: &list}) + case "testpb.TestVersion3LoneOneOfValue.d": + list := []*TestVersion3{} + return protoreflect.ValueOfList(&_TestVersion3LoneOneOfValue_5_list{list: &list}) + case "testpb.TestVersion3LoneOneOfValue.e": + return protoreflect.ValueOfInt32(int32(0)) + case "testpb.TestVersion3LoneOneOfValue.g": + m := new(anypb.Any) + return protoreflect.ValueOfMessage(m.ProtoReflect()) + case "testpb.TestVersion3LoneOneOfValue.h": + list := []*TestVersion1{} + return protoreflect.ValueOfList(&_TestVersion3LoneOneOfValue_9_list{list: &list}) + case "testpb.TestVersion3LoneOneOfValue.k": + m := new(Customer1) + return protoreflect.ValueOfMessage(m.ProtoReflect()) + case "testpb.TestVersion3LoneOneOfValue.non_critical_field": + return protoreflect.ValueOfString("") + default: + if fd.IsExtension() { + panic(fmt.Errorf("proto3 declared messages do not support extensions: testpb.TestVersion3LoneOneOfValue")) + } + panic(fmt.Errorf("message testpb.TestVersion3LoneOneOfValue does not contain field %s", fd.FullName())) + } +} + +// WhichOneof reports which field within the oneof is populated, +// returning nil if none are populated. +// It panics if the oneof descriptor does not belong to this message. +func (x *fastReflection_TestVersion3LoneOneOfValue) WhichOneof(d protoreflect.OneofDescriptor) protoreflect.FieldDescriptor { + switch d.FullName() { + case "testpb.TestVersion3LoneOneOfValue.sum": + if x.Sum == nil { + return nil + } + switch x.Sum.(type) { + case *TestVersion3LoneOneOfValue_E: + return x.Descriptor().Fields().ByName("e") + } + default: + panic(fmt.Errorf("%s is not a oneof field in testpb.TestVersion3LoneOneOfValue", d.FullName())) + } + panic("unreachable") +} + +// GetUnknown retrieves the entire list of unknown fields. +// The caller may only mutate the contents of the RawFields +// if the mutated bytes are stored back into the message with SetUnknown. +func (x *fastReflection_TestVersion3LoneOneOfValue) GetUnknown() protoreflect.RawFields { + return x.unknownFields +} + +// SetUnknown stores an entire list of unknown fields. +// The raw fields must be syntactically valid according to the wire format. +// An implementation may panic if this is not the case. +// Once stored, the caller must not mutate the content of the RawFields. +// An empty RawFields may be passed to clear the fields. +// +// SetUnknown is a mutating operation and unsafe for concurrent use. +func (x *fastReflection_TestVersion3LoneOneOfValue) SetUnknown(fields protoreflect.RawFields) { + x.unknownFields = fields +} + +// IsValid reports whether the message is valid. +// +// An invalid message is an empty, read-only value. +// +// An invalid message often corresponds to a nil pointer of the concrete +// message type, but the details are implementation dependent. +// Validity is not part of the protobuf data model, and may not +// be preserved in marshaling or other operations. +func (x *fastReflection_TestVersion3LoneOneOfValue) IsValid() bool { + return x != nil +} + +// ProtoMethods returns optional fastReflectionFeature-path implementations of various operations. +// This method may return nil. +// +// The returned methods type is identical to +// "google.golang.org/protobuf/runtime/protoiface".Methods. +// Consult the protoiface package documentation for details. +func (x *fastReflection_TestVersion3LoneOneOfValue) ProtoMethods() *protoiface.Methods { + size := func(input protoiface.SizeInput) protoiface.SizeOutput { + x := input.Message.Interface().(*TestVersion3LoneOneOfValue) + if x == nil { + return protoiface.SizeOutput{ + NoUnkeyedLiterals: input.NoUnkeyedLiterals, + Size: 0, + } + } + options := runtime.SizeInputToOptions(input) + _ = options + var n int + var l int + _ = l + if x.X != 0 { + n += 1 + runtime.Sov(uint64(x.X)) + } + if x.A != nil { + l = options.Size(x.A) + n += 1 + l + runtime.Sov(uint64(l)) + } + if x.B != nil { + l = options.Size(x.B) + n += 1 + l + runtime.Sov(uint64(l)) + } + if len(x.C) > 0 { + for _, e := range x.C { + l = options.Size(e) + n += 1 + l + runtime.Sov(uint64(l)) + } + } + if len(x.D) > 0 { + for _, e := range x.D { + l = options.Size(e) + n += 1 + l + runtime.Sov(uint64(l)) + } + } + switch x := x.Sum.(type) { + case *TestVersion3LoneOneOfValue_E: + if x == nil { + break + } + n += 1 + runtime.Sov(uint64(x.E)) + } + if x.G != nil { + l = options.Size(x.G) + n += 1 + l + runtime.Sov(uint64(l)) + } + if len(x.H) > 0 { + for _, e := range x.H { + l = options.Size(e) + n += 1 + l + runtime.Sov(uint64(l)) + } + } + if x.K != nil { + l = options.Size(x.K) + n += 1 + l + runtime.Sov(uint64(l)) + } + l = len(x.NonCriticalField) + if l > 0 { + n += 2 + l + runtime.Sov(uint64(l)) + } + if x.unknownFields != nil { + n += len(x.unknownFields) + } + return protoiface.SizeOutput{ + NoUnkeyedLiterals: input.NoUnkeyedLiterals, + Size: n, + } + } + + marshal := func(input protoiface.MarshalInput) (protoiface.MarshalOutput, error) { + x := input.Message.Interface().(*TestVersion3LoneOneOfValue) + if x == nil { + return protoiface.MarshalOutput{ + NoUnkeyedLiterals: input.NoUnkeyedLiterals, + Buf: input.Buf, + }, nil + } + options := runtime.MarshalInputToOptions(input) + _ = options + size := options.Size(x) + dAtA := make([]byte, size) + i := len(dAtA) + _ = i + var l int + _ = l + if x.unknownFields != nil { + i -= len(x.unknownFields) + copy(dAtA[i:], x.unknownFields) + } + switch x := x.Sum.(type) { + case *TestVersion3LoneOneOfValue_E: + i = runtime.EncodeVarint(dAtA, i, uint64(x.E)) + i-- + dAtA[i] = 0x30 + } + if len(x.NonCriticalField) > 0 { + i -= len(x.NonCriticalField) + copy(dAtA[i:], x.NonCriticalField) + i = runtime.EncodeVarint(dAtA, i, uint64(len(x.NonCriticalField))) + i-- + dAtA[i] = 0x40 + i-- + dAtA[i] = 0xba + } + if x.K != nil { + encoded, err := options.Marshal(x.K) + if err != nil { + return protoiface.MarshalOutput{ + NoUnkeyedLiterals: input.NoUnkeyedLiterals, + Buf: input.Buf, + }, err + } + i -= len(encoded) + copy(dAtA[i:], encoded) + i = runtime.EncodeVarint(dAtA, i, uint64(len(encoded))) + i-- + dAtA[i] = 0x62 + } + if len(x.H) > 0 { + for iNdEx := len(x.H) - 1; iNdEx >= 0; iNdEx-- { + encoded, err := options.Marshal(x.H[iNdEx]) + if err != nil { + return protoiface.MarshalOutput{ + NoUnkeyedLiterals: input.NoUnkeyedLiterals, + Buf: input.Buf, + }, err + } + i -= len(encoded) + copy(dAtA[i:], encoded) + i = runtime.EncodeVarint(dAtA, i, uint64(len(encoded))) + i-- + dAtA[i] = 0x4a + } + } + if x.G != nil { + encoded, err := options.Marshal(x.G) + if err != nil { + return protoiface.MarshalOutput{ + NoUnkeyedLiterals: input.NoUnkeyedLiterals, + Buf: input.Buf, + }, err + } + i -= len(encoded) + copy(dAtA[i:], encoded) + i = runtime.EncodeVarint(dAtA, i, uint64(len(encoded))) + i-- + dAtA[i] = 0x42 + } + if len(x.D) > 0 { + for iNdEx := len(x.D) - 1; iNdEx >= 0; iNdEx-- { + encoded, err := options.Marshal(x.D[iNdEx]) + if err != nil { + return protoiface.MarshalOutput{ + NoUnkeyedLiterals: input.NoUnkeyedLiterals, + Buf: input.Buf, + }, err + } + i -= len(encoded) + copy(dAtA[i:], encoded) + i = runtime.EncodeVarint(dAtA, i, uint64(len(encoded))) + i-- + dAtA[i] = 0x2a + } + } + if len(x.C) > 0 { + for iNdEx := len(x.C) - 1; iNdEx >= 0; iNdEx-- { + encoded, err := options.Marshal(x.C[iNdEx]) + if err != nil { + return protoiface.MarshalOutput{ + NoUnkeyedLiterals: input.NoUnkeyedLiterals, + Buf: input.Buf, + }, err + } + i -= len(encoded) + copy(dAtA[i:], encoded) + i = runtime.EncodeVarint(dAtA, i, uint64(len(encoded))) + i-- + dAtA[i] = 0x22 + } + } + if x.B != nil { + encoded, err := options.Marshal(x.B) + if err != nil { + return protoiface.MarshalOutput{ + NoUnkeyedLiterals: input.NoUnkeyedLiterals, + Buf: input.Buf, + }, err + } + i -= len(encoded) + copy(dAtA[i:], encoded) + i = runtime.EncodeVarint(dAtA, i, uint64(len(encoded))) + i-- + dAtA[i] = 0x1a + } + if x.A != nil { + encoded, err := options.Marshal(x.A) + if err != nil { + return protoiface.MarshalOutput{ + NoUnkeyedLiterals: input.NoUnkeyedLiterals, + Buf: input.Buf, + }, err + } + i -= len(encoded) + copy(dAtA[i:], encoded) + i = runtime.EncodeVarint(dAtA, i, uint64(len(encoded))) + i-- + dAtA[i] = 0x12 + } + if x.X != 0 { + i = runtime.EncodeVarint(dAtA, i, uint64(x.X)) + i-- + dAtA[i] = 0x8 + } + if input.Buf != nil { + input.Buf = append(input.Buf, dAtA...) + } else { + input.Buf = dAtA + } + return protoiface.MarshalOutput{ + NoUnkeyedLiterals: input.NoUnkeyedLiterals, + Buf: input.Buf, + }, nil + } + unmarshal := func(input protoiface.UnmarshalInput) (protoiface.UnmarshalOutput, error) { + x := input.Message.Interface().(*TestVersion3LoneOneOfValue) + if x == nil { + return protoiface.UnmarshalOutput{ + NoUnkeyedLiterals: input.NoUnkeyedLiterals, + Flags: input.Flags, + }, nil + } + options := runtime.UnmarshalInputToOptions(input) + _ = options + dAtA := input.Buf + l := len(dAtA) + iNdEx := 0 + for iNdEx < l { + preIndex := iNdEx + var wire uint64 + for shift := uint(0); ; shift += 7 { + if shift >= 64 { + return protoiface.UnmarshalOutput{NoUnkeyedLiterals: input.NoUnkeyedLiterals, Flags: input.Flags}, runtime.ErrIntOverflow + } + if iNdEx >= l { + return protoiface.UnmarshalOutput{NoUnkeyedLiterals: input.NoUnkeyedLiterals, Flags: input.Flags}, io.ErrUnexpectedEOF + } + b := dAtA[iNdEx] + iNdEx++ + wire |= uint64(b&0x7F) << shift + if b < 0x80 { + break + } + } + fieldNum := int32(wire >> 3) + wireType := int(wire & 0x7) + if wireType == 4 { + return protoiface.UnmarshalOutput{NoUnkeyedLiterals: input.NoUnkeyedLiterals, Flags: input.Flags}, fmt.Errorf("proto: TestVersion3LoneOneOfValue: wiretype end group for non-group") + } + if fieldNum <= 0 { + return protoiface.UnmarshalOutput{NoUnkeyedLiterals: input.NoUnkeyedLiterals, Flags: input.Flags}, fmt.Errorf("proto: TestVersion3LoneOneOfValue: illegal tag %d (wire type %d)", fieldNum, wire) + } + switch fieldNum { + case 1: + if wireType != 0 { + return protoiface.UnmarshalOutput{NoUnkeyedLiterals: input.NoUnkeyedLiterals, Flags: input.Flags}, fmt.Errorf("proto: wrong wireType = %d for field X", wireType) + } + x.X = 0 + for shift := uint(0); ; shift += 7 { + if shift >= 64 { + return protoiface.UnmarshalOutput{NoUnkeyedLiterals: input.NoUnkeyedLiterals, Flags: input.Flags}, runtime.ErrIntOverflow + } + if iNdEx >= l { + return protoiface.UnmarshalOutput{NoUnkeyedLiterals: input.NoUnkeyedLiterals, Flags: input.Flags}, io.ErrUnexpectedEOF + } + b := dAtA[iNdEx] + iNdEx++ + x.X |= int64(b&0x7F) << shift + if b < 0x80 { + break + } + } + case 2: + if wireType != 2 { + return protoiface.UnmarshalOutput{NoUnkeyedLiterals: input.NoUnkeyedLiterals, Flags: input.Flags}, fmt.Errorf("proto: wrong wireType = %d for field A", wireType) + } + var msglen int + for shift := uint(0); ; shift += 7 { + if shift >= 64 { + return protoiface.UnmarshalOutput{NoUnkeyedLiterals: input.NoUnkeyedLiterals, Flags: input.Flags}, runtime.ErrIntOverflow + } + if iNdEx >= l { + return protoiface.UnmarshalOutput{NoUnkeyedLiterals: input.NoUnkeyedLiterals, Flags: input.Flags}, io.ErrUnexpectedEOF + } + b := dAtA[iNdEx] + iNdEx++ + msglen |= int(b&0x7F) << shift + if b < 0x80 { + break + } + } + if msglen < 0 { + return protoiface.UnmarshalOutput{NoUnkeyedLiterals: input.NoUnkeyedLiterals, Flags: input.Flags}, runtime.ErrInvalidLength + } + postIndex := iNdEx + msglen + if postIndex < 0 { + return protoiface.UnmarshalOutput{NoUnkeyedLiterals: input.NoUnkeyedLiterals, Flags: input.Flags}, runtime.ErrInvalidLength + } + if postIndex > l { + return protoiface.UnmarshalOutput{NoUnkeyedLiterals: input.NoUnkeyedLiterals, Flags: input.Flags}, io.ErrUnexpectedEOF + } + if x.A == nil { + x.A = &TestVersion3{} + } + if err := options.Unmarshal(dAtA[iNdEx:postIndex], x.A); err != nil { + return protoiface.UnmarshalOutput{NoUnkeyedLiterals: input.NoUnkeyedLiterals, Flags: input.Flags}, err + } + iNdEx = postIndex + case 3: + if wireType != 2 { + return protoiface.UnmarshalOutput{NoUnkeyedLiterals: input.NoUnkeyedLiterals, Flags: input.Flags}, fmt.Errorf("proto: wrong wireType = %d for field B", wireType) + } + var msglen int + for shift := uint(0); ; shift += 7 { + if shift >= 64 { + return protoiface.UnmarshalOutput{NoUnkeyedLiterals: input.NoUnkeyedLiterals, Flags: input.Flags}, runtime.ErrIntOverflow + } + if iNdEx >= l { + return protoiface.UnmarshalOutput{NoUnkeyedLiterals: input.NoUnkeyedLiterals, Flags: input.Flags}, io.ErrUnexpectedEOF + } + b := dAtA[iNdEx] + iNdEx++ + msglen |= int(b&0x7F) << shift + if b < 0x80 { + break + } + } + if msglen < 0 { + return protoiface.UnmarshalOutput{NoUnkeyedLiterals: input.NoUnkeyedLiterals, Flags: input.Flags}, runtime.ErrInvalidLength + } + postIndex := iNdEx + msglen + if postIndex < 0 { + return protoiface.UnmarshalOutput{NoUnkeyedLiterals: input.NoUnkeyedLiterals, Flags: input.Flags}, runtime.ErrInvalidLength + } + if postIndex > l { + return protoiface.UnmarshalOutput{NoUnkeyedLiterals: input.NoUnkeyedLiterals, Flags: input.Flags}, io.ErrUnexpectedEOF + } + if x.B == nil { + x.B = &TestVersion3{} + } + if err := options.Unmarshal(dAtA[iNdEx:postIndex], x.B); err != nil { + return protoiface.UnmarshalOutput{NoUnkeyedLiterals: input.NoUnkeyedLiterals, Flags: input.Flags}, err + } + iNdEx = postIndex + case 4: + if wireType != 2 { + return protoiface.UnmarshalOutput{NoUnkeyedLiterals: input.NoUnkeyedLiterals, Flags: input.Flags}, fmt.Errorf("proto: wrong wireType = %d for field C", wireType) + } + var msglen int + for shift := uint(0); ; shift += 7 { + if shift >= 64 { + return protoiface.UnmarshalOutput{NoUnkeyedLiterals: input.NoUnkeyedLiterals, Flags: input.Flags}, runtime.ErrIntOverflow + } + if iNdEx >= l { + return protoiface.UnmarshalOutput{NoUnkeyedLiterals: input.NoUnkeyedLiterals, Flags: input.Flags}, io.ErrUnexpectedEOF + } + b := dAtA[iNdEx] + iNdEx++ + msglen |= int(b&0x7F) << shift + if b < 0x80 { + break + } + } + if msglen < 0 { + return protoiface.UnmarshalOutput{NoUnkeyedLiterals: input.NoUnkeyedLiterals, Flags: input.Flags}, runtime.ErrInvalidLength + } + postIndex := iNdEx + msglen + if postIndex < 0 { + return protoiface.UnmarshalOutput{NoUnkeyedLiterals: input.NoUnkeyedLiterals, Flags: input.Flags}, runtime.ErrInvalidLength + } + if postIndex > l { + return protoiface.UnmarshalOutput{NoUnkeyedLiterals: input.NoUnkeyedLiterals, Flags: input.Flags}, io.ErrUnexpectedEOF + } + x.C = append(x.C, &TestVersion3{}) + if err := options.Unmarshal(dAtA[iNdEx:postIndex], x.C[len(x.C)-1]); err != nil { + return protoiface.UnmarshalOutput{NoUnkeyedLiterals: input.NoUnkeyedLiterals, Flags: input.Flags}, err + } + iNdEx = postIndex + case 5: + if wireType != 2 { + return protoiface.UnmarshalOutput{NoUnkeyedLiterals: input.NoUnkeyedLiterals, Flags: input.Flags}, fmt.Errorf("proto: wrong wireType = %d for field D", wireType) + } + var msglen int + for shift := uint(0); ; shift += 7 { + if shift >= 64 { + return protoiface.UnmarshalOutput{NoUnkeyedLiterals: input.NoUnkeyedLiterals, Flags: input.Flags}, runtime.ErrIntOverflow + } + if iNdEx >= l { + return protoiface.UnmarshalOutput{NoUnkeyedLiterals: input.NoUnkeyedLiterals, Flags: input.Flags}, io.ErrUnexpectedEOF + } + b := dAtA[iNdEx] + iNdEx++ + msglen |= int(b&0x7F) << shift + if b < 0x80 { + break + } + } + if msglen < 0 { + return protoiface.UnmarshalOutput{NoUnkeyedLiterals: input.NoUnkeyedLiterals, Flags: input.Flags}, runtime.ErrInvalidLength + } + postIndex := iNdEx + msglen + if postIndex < 0 { + return protoiface.UnmarshalOutput{NoUnkeyedLiterals: input.NoUnkeyedLiterals, Flags: input.Flags}, runtime.ErrInvalidLength + } + if postIndex > l { + return protoiface.UnmarshalOutput{NoUnkeyedLiterals: input.NoUnkeyedLiterals, Flags: input.Flags}, io.ErrUnexpectedEOF + } + x.D = append(x.D, &TestVersion3{}) + if err := options.Unmarshal(dAtA[iNdEx:postIndex], x.D[len(x.D)-1]); err != nil { + return protoiface.UnmarshalOutput{NoUnkeyedLiterals: input.NoUnkeyedLiterals, Flags: input.Flags}, err + } + iNdEx = postIndex + case 6: + if wireType != 0 { + return protoiface.UnmarshalOutput{NoUnkeyedLiterals: input.NoUnkeyedLiterals, Flags: input.Flags}, fmt.Errorf("proto: wrong wireType = %d for field E", wireType) + } + var v int32 + for shift := uint(0); ; shift += 7 { + if shift >= 64 { + return protoiface.UnmarshalOutput{NoUnkeyedLiterals: input.NoUnkeyedLiterals, Flags: input.Flags}, runtime.ErrIntOverflow + } + if iNdEx >= l { + return protoiface.UnmarshalOutput{NoUnkeyedLiterals: input.NoUnkeyedLiterals, Flags: input.Flags}, io.ErrUnexpectedEOF + } + b := dAtA[iNdEx] + iNdEx++ + v |= int32(b&0x7F) << shift + if b < 0x80 { + break + } + } + x.Sum = &TestVersion3LoneOneOfValue_E{v} + case 8: + if wireType != 2 { + return protoiface.UnmarshalOutput{NoUnkeyedLiterals: input.NoUnkeyedLiterals, Flags: input.Flags}, fmt.Errorf("proto: wrong wireType = %d for field G", wireType) + } + var msglen int + for shift := uint(0); ; shift += 7 { + if shift >= 64 { + return protoiface.UnmarshalOutput{NoUnkeyedLiterals: input.NoUnkeyedLiterals, Flags: input.Flags}, runtime.ErrIntOverflow + } + if iNdEx >= l { + return protoiface.UnmarshalOutput{NoUnkeyedLiterals: input.NoUnkeyedLiterals, Flags: input.Flags}, io.ErrUnexpectedEOF + } + b := dAtA[iNdEx] + iNdEx++ + msglen |= int(b&0x7F) << shift + if b < 0x80 { + break + } + } + if msglen < 0 { + return protoiface.UnmarshalOutput{NoUnkeyedLiterals: input.NoUnkeyedLiterals, Flags: input.Flags}, runtime.ErrInvalidLength + } + postIndex := iNdEx + msglen + if postIndex < 0 { + return protoiface.UnmarshalOutput{NoUnkeyedLiterals: input.NoUnkeyedLiterals, Flags: input.Flags}, runtime.ErrInvalidLength + } + if postIndex > l { + return protoiface.UnmarshalOutput{NoUnkeyedLiterals: input.NoUnkeyedLiterals, Flags: input.Flags}, io.ErrUnexpectedEOF + } + if x.G == nil { + x.G = &anypb.Any{} + } + if err := options.Unmarshal(dAtA[iNdEx:postIndex], x.G); err != nil { + return protoiface.UnmarshalOutput{NoUnkeyedLiterals: input.NoUnkeyedLiterals, Flags: input.Flags}, err + } + iNdEx = postIndex + case 9: + if wireType != 2 { + return protoiface.UnmarshalOutput{NoUnkeyedLiterals: input.NoUnkeyedLiterals, Flags: input.Flags}, fmt.Errorf("proto: wrong wireType = %d for field H", wireType) + } + var msglen int + for shift := uint(0); ; shift += 7 { + if shift >= 64 { + return protoiface.UnmarshalOutput{NoUnkeyedLiterals: input.NoUnkeyedLiterals, Flags: input.Flags}, runtime.ErrIntOverflow + } + if iNdEx >= l { + return protoiface.UnmarshalOutput{NoUnkeyedLiterals: input.NoUnkeyedLiterals, Flags: input.Flags}, io.ErrUnexpectedEOF + } + b := dAtA[iNdEx] + iNdEx++ + msglen |= int(b&0x7F) << shift + if b < 0x80 { + break + } + } + if msglen < 0 { + return protoiface.UnmarshalOutput{NoUnkeyedLiterals: input.NoUnkeyedLiterals, Flags: input.Flags}, runtime.ErrInvalidLength + } + postIndex := iNdEx + msglen + if postIndex < 0 { + return protoiface.UnmarshalOutput{NoUnkeyedLiterals: input.NoUnkeyedLiterals, Flags: input.Flags}, runtime.ErrInvalidLength + } + if postIndex > l { + return protoiface.UnmarshalOutput{NoUnkeyedLiterals: input.NoUnkeyedLiterals, Flags: input.Flags}, io.ErrUnexpectedEOF + } + x.H = append(x.H, &TestVersion1{}) + if err := options.Unmarshal(dAtA[iNdEx:postIndex], x.H[len(x.H)-1]); err != nil { + return protoiface.UnmarshalOutput{NoUnkeyedLiterals: input.NoUnkeyedLiterals, Flags: input.Flags}, err + } + iNdEx = postIndex + case 12: + if wireType != 2 { + return protoiface.UnmarshalOutput{NoUnkeyedLiterals: input.NoUnkeyedLiterals, Flags: input.Flags}, fmt.Errorf("proto: wrong wireType = %d for field K", wireType) + } + var msglen int + for shift := uint(0); ; shift += 7 { + if shift >= 64 { + return protoiface.UnmarshalOutput{NoUnkeyedLiterals: input.NoUnkeyedLiterals, Flags: input.Flags}, runtime.ErrIntOverflow + } + if iNdEx >= l { + return protoiface.UnmarshalOutput{NoUnkeyedLiterals: input.NoUnkeyedLiterals, Flags: input.Flags}, io.ErrUnexpectedEOF + } + b := dAtA[iNdEx] + iNdEx++ + msglen |= int(b&0x7F) << shift + if b < 0x80 { + break + } + } + if msglen < 0 { + return protoiface.UnmarshalOutput{NoUnkeyedLiterals: input.NoUnkeyedLiterals, Flags: input.Flags}, runtime.ErrInvalidLength + } + postIndex := iNdEx + msglen + if postIndex < 0 { + return protoiface.UnmarshalOutput{NoUnkeyedLiterals: input.NoUnkeyedLiterals, Flags: input.Flags}, runtime.ErrInvalidLength + } + if postIndex > l { + return protoiface.UnmarshalOutput{NoUnkeyedLiterals: input.NoUnkeyedLiterals, Flags: input.Flags}, io.ErrUnexpectedEOF + } + if x.K == nil { + x.K = &Customer1{} + } + if err := options.Unmarshal(dAtA[iNdEx:postIndex], x.K); err != nil { + return protoiface.UnmarshalOutput{NoUnkeyedLiterals: input.NoUnkeyedLiterals, Flags: input.Flags}, err + } + iNdEx = postIndex + case 1031: + if wireType != 2 { + return protoiface.UnmarshalOutput{NoUnkeyedLiterals: input.NoUnkeyedLiterals, Flags: input.Flags}, fmt.Errorf("proto: wrong wireType = %d for field NonCriticalField", wireType) + } + var stringLen uint64 + for shift := uint(0); ; shift += 7 { + if shift >= 64 { + return protoiface.UnmarshalOutput{NoUnkeyedLiterals: input.NoUnkeyedLiterals, Flags: input.Flags}, runtime.ErrIntOverflow + } + if iNdEx >= l { + return protoiface.UnmarshalOutput{NoUnkeyedLiterals: input.NoUnkeyedLiterals, Flags: input.Flags}, io.ErrUnexpectedEOF + } + b := dAtA[iNdEx] + iNdEx++ + stringLen |= uint64(b&0x7F) << shift + if b < 0x80 { + break + } + } + intStringLen := int(stringLen) + if intStringLen < 0 { + return protoiface.UnmarshalOutput{NoUnkeyedLiterals: input.NoUnkeyedLiterals, Flags: input.Flags}, runtime.ErrInvalidLength + } + postIndex := iNdEx + intStringLen + if postIndex < 0 { + return protoiface.UnmarshalOutput{NoUnkeyedLiterals: input.NoUnkeyedLiterals, Flags: input.Flags}, runtime.ErrInvalidLength + } + if postIndex > l { + return protoiface.UnmarshalOutput{NoUnkeyedLiterals: input.NoUnkeyedLiterals, Flags: input.Flags}, io.ErrUnexpectedEOF + } + x.NonCriticalField = string(dAtA[iNdEx:postIndex]) + iNdEx = postIndex + default: + iNdEx = preIndex + skippy, err := runtime.Skip(dAtA[iNdEx:]) + if err != nil { + return protoiface.UnmarshalOutput{NoUnkeyedLiterals: input.NoUnkeyedLiterals, Flags: input.Flags}, err + } + if (skippy < 0) || (iNdEx+skippy) < 0 { + return protoiface.UnmarshalOutput{NoUnkeyedLiterals: input.NoUnkeyedLiterals, Flags: input.Flags}, runtime.ErrInvalidLength + } + if (iNdEx + skippy) > l { + return protoiface.UnmarshalOutput{NoUnkeyedLiterals: input.NoUnkeyedLiterals, Flags: input.Flags}, io.ErrUnexpectedEOF + } + if !options.DiscardUnknown { + x.unknownFields = append(x.unknownFields, dAtA[iNdEx:iNdEx+skippy]...) + } + iNdEx += skippy + } + } + + if iNdEx > l { + return protoiface.UnmarshalOutput{NoUnkeyedLiterals: input.NoUnkeyedLiterals, Flags: input.Flags}, io.ErrUnexpectedEOF + } + return protoiface.UnmarshalOutput{NoUnkeyedLiterals: input.NoUnkeyedLiterals, Flags: input.Flags}, nil + } + return &protoiface.Methods{ + NoUnkeyedLiterals: struct{}{}, + Flags: protoiface.SupportMarshalDeterministic | protoiface.SupportUnmarshalDiscardUnknown, + Size: size, + Marshal: marshal, + Unmarshal: unmarshal, + Merge: nil, + CheckInitialized: nil, + } +} + +var _ protoreflect.List = (*_TestVersion3LoneNesting_4_list)(nil) + +type _TestVersion3LoneNesting_4_list struct { + list *[]*TestVersion3 +} + +func (x *_TestVersion3LoneNesting_4_list) Len() int { + if x.list == nil { + return 0 + } + return len(*x.list) +} + +func (x *_TestVersion3LoneNesting_4_list) Get(i int) protoreflect.Value { + return protoreflect.ValueOfMessage((*x.list)[i].ProtoReflect()) +} + +func (x *_TestVersion3LoneNesting_4_list) Set(i int, value protoreflect.Value) { + valueUnwrapped := value.Message() + concreteValue := valueUnwrapped.Interface().(*TestVersion3) + (*x.list)[i] = concreteValue +} + +func (x *_TestVersion3LoneNesting_4_list) Append(value protoreflect.Value) { + valueUnwrapped := value.Message() + concreteValue := valueUnwrapped.Interface().(*TestVersion3) + *x.list = append(*x.list, concreteValue) +} + +func (x *_TestVersion3LoneNesting_4_list) AppendMutable() protoreflect.Value { + v := new(TestVersion3) + *x.list = append(*x.list, v) + return protoreflect.ValueOfMessage(v.ProtoReflect()) +} + +func (x *_TestVersion3LoneNesting_4_list) Truncate(n int) { + for i := n; i < len(*x.list); i++ { + (*x.list)[i] = nil + } + *x.list = (*x.list)[:n] +} + +func (x *_TestVersion3LoneNesting_4_list) NewElement() protoreflect.Value { + v := new(TestVersion3) + return protoreflect.ValueOfMessage(v.ProtoReflect()) +} + +func (x *_TestVersion3LoneNesting_4_list) IsValid() bool { + return x.list != nil +} + +var _ protoreflect.List = (*_TestVersion3LoneNesting_5_list)(nil) + +type _TestVersion3LoneNesting_5_list struct { + list *[]*TestVersion3 +} + +func (x *_TestVersion3LoneNesting_5_list) Len() int { + if x.list == nil { + return 0 + } + return len(*x.list) +} + +func (x *_TestVersion3LoneNesting_5_list) Get(i int) protoreflect.Value { + return protoreflect.ValueOfMessage((*x.list)[i].ProtoReflect()) +} + +func (x *_TestVersion3LoneNesting_5_list) Set(i int, value protoreflect.Value) { + valueUnwrapped := value.Message() + concreteValue := valueUnwrapped.Interface().(*TestVersion3) + (*x.list)[i] = concreteValue +} + +func (x *_TestVersion3LoneNesting_5_list) Append(value protoreflect.Value) { + valueUnwrapped := value.Message() + concreteValue := valueUnwrapped.Interface().(*TestVersion3) + *x.list = append(*x.list, concreteValue) +} + +func (x *_TestVersion3LoneNesting_5_list) AppendMutable() protoreflect.Value { + v := new(TestVersion3) + *x.list = append(*x.list, v) + return protoreflect.ValueOfMessage(v.ProtoReflect()) +} + +func (x *_TestVersion3LoneNesting_5_list) Truncate(n int) { + for i := n; i < len(*x.list); i++ { + (*x.list)[i] = nil + } + *x.list = (*x.list)[:n] +} + +func (x *_TestVersion3LoneNesting_5_list) NewElement() protoreflect.Value { + v := new(TestVersion3) + return protoreflect.ValueOfMessage(v.ProtoReflect()) +} + +func (x *_TestVersion3LoneNesting_5_list) IsValid() bool { + return x.list != nil +} + +var _ protoreflect.List = (*_TestVersion3LoneNesting_9_list)(nil) + +type _TestVersion3LoneNesting_9_list struct { + list *[]*TestVersion1 +} + +func (x *_TestVersion3LoneNesting_9_list) Len() int { + if x.list == nil { + return 0 + } + return len(*x.list) +} + +func (x *_TestVersion3LoneNesting_9_list) Get(i int) protoreflect.Value { + return protoreflect.ValueOfMessage((*x.list)[i].ProtoReflect()) +} + +func (x *_TestVersion3LoneNesting_9_list) Set(i int, value protoreflect.Value) { + valueUnwrapped := value.Message() + concreteValue := valueUnwrapped.Interface().(*TestVersion1) + (*x.list)[i] = concreteValue +} + +func (x *_TestVersion3LoneNesting_9_list) Append(value protoreflect.Value) { + valueUnwrapped := value.Message() + concreteValue := valueUnwrapped.Interface().(*TestVersion1) + *x.list = append(*x.list, concreteValue) +} + +func (x *_TestVersion3LoneNesting_9_list) AppendMutable() protoreflect.Value { + v := new(TestVersion1) + *x.list = append(*x.list, v) + return protoreflect.ValueOfMessage(v.ProtoReflect()) +} + +func (x *_TestVersion3LoneNesting_9_list) Truncate(n int) { + for i := n; i < len(*x.list); i++ { + (*x.list)[i] = nil + } + *x.list = (*x.list)[:n] +} + +func (x *_TestVersion3LoneNesting_9_list) NewElement() protoreflect.Value { + v := new(TestVersion1) + return protoreflect.ValueOfMessage(v.ProtoReflect()) +} + +func (x *_TestVersion3LoneNesting_9_list) IsValid() bool { + return x.list != nil +} + +var ( + md_TestVersion3LoneNesting protoreflect.MessageDescriptor + fd_TestVersion3LoneNesting_x protoreflect.FieldDescriptor + fd_TestVersion3LoneNesting_a protoreflect.FieldDescriptor + fd_TestVersion3LoneNesting_b protoreflect.FieldDescriptor + fd_TestVersion3LoneNesting_c protoreflect.FieldDescriptor + fd_TestVersion3LoneNesting_d protoreflect.FieldDescriptor + fd_TestVersion3LoneNesting_f protoreflect.FieldDescriptor + fd_TestVersion3LoneNesting_g protoreflect.FieldDescriptor + fd_TestVersion3LoneNesting_h protoreflect.FieldDescriptor + fd_TestVersion3LoneNesting_k protoreflect.FieldDescriptor + fd_TestVersion3LoneNesting_non_critical_field protoreflect.FieldDescriptor + fd_TestVersion3LoneNesting_inner1 protoreflect.FieldDescriptor + fd_TestVersion3LoneNesting_inner2 protoreflect.FieldDescriptor +) + +func init() { + file_unknownproto_proto_init() + md_TestVersion3LoneNesting = File_unknownproto_proto.Messages().ByName("TestVersion3LoneNesting") + fd_TestVersion3LoneNesting_x = md_TestVersion3LoneNesting.Fields().ByName("x") + fd_TestVersion3LoneNesting_a = md_TestVersion3LoneNesting.Fields().ByName("a") + fd_TestVersion3LoneNesting_b = md_TestVersion3LoneNesting.Fields().ByName("b") + fd_TestVersion3LoneNesting_c = md_TestVersion3LoneNesting.Fields().ByName("c") + fd_TestVersion3LoneNesting_d = md_TestVersion3LoneNesting.Fields().ByName("d") + fd_TestVersion3LoneNesting_f = md_TestVersion3LoneNesting.Fields().ByName("f") + fd_TestVersion3LoneNesting_g = md_TestVersion3LoneNesting.Fields().ByName("g") + fd_TestVersion3LoneNesting_h = md_TestVersion3LoneNesting.Fields().ByName("h") + fd_TestVersion3LoneNesting_k = md_TestVersion3LoneNesting.Fields().ByName("k") + fd_TestVersion3LoneNesting_non_critical_field = md_TestVersion3LoneNesting.Fields().ByName("non_critical_field") + fd_TestVersion3LoneNesting_inner1 = md_TestVersion3LoneNesting.Fields().ByName("inner1") + fd_TestVersion3LoneNesting_inner2 = md_TestVersion3LoneNesting.Fields().ByName("inner2") +} + +var _ protoreflect.Message = (*fastReflection_TestVersion3LoneNesting)(nil) + +type fastReflection_TestVersion3LoneNesting TestVersion3LoneNesting + +func (x *TestVersion3LoneNesting) ProtoReflect() protoreflect.Message { + return (*fastReflection_TestVersion3LoneNesting)(x) +} + +func (x *TestVersion3LoneNesting) slowProtoReflect() protoreflect.Message { + mi := &file_unknownproto_proto_msgTypes[15] + if protoimpl.UnsafeEnabled && x != nil { + ms := protoimpl.X.MessageStateOf(protoimpl.Pointer(x)) + if ms.LoadMessageInfo() == nil { + ms.StoreMessageInfo(mi) + } + return ms + } + return mi.MessageOf(x) +} + +var _fastReflection_TestVersion3LoneNesting_messageType fastReflection_TestVersion3LoneNesting_messageType +var _ protoreflect.MessageType = fastReflection_TestVersion3LoneNesting_messageType{} + +type fastReflection_TestVersion3LoneNesting_messageType struct{} + +func (x fastReflection_TestVersion3LoneNesting_messageType) Zero() protoreflect.Message { + return (*fastReflection_TestVersion3LoneNesting)(nil) +} +func (x fastReflection_TestVersion3LoneNesting_messageType) New() protoreflect.Message { + return new(fastReflection_TestVersion3LoneNesting) +} +func (x fastReflection_TestVersion3LoneNesting_messageType) Descriptor() protoreflect.MessageDescriptor { + return md_TestVersion3LoneNesting +} + +// Descriptor returns message descriptor, which contains only the protobuf +// type information for the message. +func (x *fastReflection_TestVersion3LoneNesting) Descriptor() protoreflect.MessageDescriptor { + return md_TestVersion3LoneNesting +} + +// Type returns the message type, which encapsulates both Go and protobuf +// type information. If the Go type information is not needed, +// it is recommended that the message descriptor be used instead. +func (x *fastReflection_TestVersion3LoneNesting) Type() protoreflect.MessageType { + return _fastReflection_TestVersion3LoneNesting_messageType +} + +// New returns a newly allocated and mutable empty message. +func (x *fastReflection_TestVersion3LoneNesting) New() protoreflect.Message { + return new(fastReflection_TestVersion3LoneNesting) +} + +// Interface unwraps the message reflection interface and +// returns the underlying ProtoMessage interface. +func (x *fastReflection_TestVersion3LoneNesting) Interface() protoreflect.ProtoMessage { + return (*TestVersion3LoneNesting)(x) +} + +// Range iterates over every populated field in an undefined order, +// calling f for each field descriptor and value encountered. +// Range returns immediately if f returns false. +// While iterating, mutating operations may only be performed +// on the current field descriptor. +func (x *fastReflection_TestVersion3LoneNesting) Range(f func(protoreflect.FieldDescriptor, protoreflect.Value) bool) { + if x.X != int64(0) { + value := protoreflect.ValueOfInt64(x.X) + if !f(fd_TestVersion3LoneNesting_x, value) { + return + } + } + if x.A != nil { + value := protoreflect.ValueOfMessage(x.A.ProtoReflect()) + if !f(fd_TestVersion3LoneNesting_a, value) { + return + } + } + if x.B != nil { + value := protoreflect.ValueOfMessage(x.B.ProtoReflect()) + if !f(fd_TestVersion3LoneNesting_b, value) { + return + } + } + if len(x.C) != 0 { + value := protoreflect.ValueOfList(&_TestVersion3LoneNesting_4_list{list: &x.C}) + if !f(fd_TestVersion3LoneNesting_c, value) { + return + } + } + if len(x.D) != 0 { + value := protoreflect.ValueOfList(&_TestVersion3LoneNesting_5_list{list: &x.D}) + if !f(fd_TestVersion3LoneNesting_d, value) { + return + } + } + if x.Sum != nil { + switch o := x.Sum.(type) { + case *TestVersion3LoneNesting_F: + v := o.F + value := protoreflect.ValueOfMessage(v.ProtoReflect()) + if !f(fd_TestVersion3LoneNesting_f, value) { + return + } + } + } + if x.G != nil { + value := protoreflect.ValueOfMessage(x.G.ProtoReflect()) + if !f(fd_TestVersion3LoneNesting_g, value) { + return + } + } + if len(x.H) != 0 { + value := protoreflect.ValueOfList(&_TestVersion3LoneNesting_9_list{list: &x.H}) + if !f(fd_TestVersion3LoneNesting_h, value) { + return + } + } + if x.K != nil { + value := protoreflect.ValueOfMessage(x.K.ProtoReflect()) + if !f(fd_TestVersion3LoneNesting_k, value) { + return + } + } + if x.NonCriticalField != "" { + value := protoreflect.ValueOfString(x.NonCriticalField) + if !f(fd_TestVersion3LoneNesting_non_critical_field, value) { + return + } + } + if x.Inner1 != nil { + value := protoreflect.ValueOfMessage(x.Inner1.ProtoReflect()) + if !f(fd_TestVersion3LoneNesting_inner1, value) { + return + } + } + if x.Inner2 != nil { + value := protoreflect.ValueOfMessage(x.Inner2.ProtoReflect()) + if !f(fd_TestVersion3LoneNesting_inner2, value) { + return + } + } +} + +// Has reports whether a field is populated. +// +// Some fields have the property of nullability where it is possible to +// distinguish between the default value of a field and whether the field +// was explicitly populated with the default value. Singular message fields, +// member fields of a oneof, and proto2 scalar fields are nullable. Such +// fields are populated only if explicitly set. +// +// In other cases (aside from the nullable cases above), +// a proto3 scalar field is populated if it contains a non-zero value, and +// a repeated field is populated if it is non-empty. +func (x *fastReflection_TestVersion3LoneNesting) Has(fd protoreflect.FieldDescriptor) bool { + switch fd.FullName() { + case "testpb.TestVersion3LoneNesting.x": + return x.X != int64(0) + case "testpb.TestVersion3LoneNesting.a": + return x.A != nil + case "testpb.TestVersion3LoneNesting.b": + return x.B != nil + case "testpb.TestVersion3LoneNesting.c": + return len(x.C) != 0 + case "testpb.TestVersion3LoneNesting.d": + return len(x.D) != 0 + case "testpb.TestVersion3LoneNesting.f": + if x.Sum == nil { + return false + } else if _, ok := x.Sum.(*TestVersion3LoneNesting_F); ok { + return true + } else { + return false + } + case "testpb.TestVersion3LoneNesting.g": + return x.G != nil + case "testpb.TestVersion3LoneNesting.h": + return len(x.H) != 0 + case "testpb.TestVersion3LoneNesting.k": + return x.K != nil + case "testpb.TestVersion3LoneNesting.non_critical_field": + return x.NonCriticalField != "" + case "testpb.TestVersion3LoneNesting.inner1": + return x.Inner1 != nil + case "testpb.TestVersion3LoneNesting.inner2": + return x.Inner2 != nil + default: + if fd.IsExtension() { + panic(fmt.Errorf("proto3 declared messages do not support extensions: testpb.TestVersion3LoneNesting")) + } + panic(fmt.Errorf("message testpb.TestVersion3LoneNesting does not contain field %s", fd.FullName())) + } +} + +// Clear clears the field such that a subsequent Has call reports false. +// +// Clearing an extension field clears both the extension type and value +// associated with the given field number. +// +// Clear is a mutating operation and unsafe for concurrent use. +func (x *fastReflection_TestVersion3LoneNesting) Clear(fd protoreflect.FieldDescriptor) { + switch fd.FullName() { + case "testpb.TestVersion3LoneNesting.x": + x.X = int64(0) + case "testpb.TestVersion3LoneNesting.a": + x.A = nil + case "testpb.TestVersion3LoneNesting.b": + x.B = nil + case "testpb.TestVersion3LoneNesting.c": + x.C = nil + case "testpb.TestVersion3LoneNesting.d": + x.D = nil + case "testpb.TestVersion3LoneNesting.f": + x.Sum = nil + case "testpb.TestVersion3LoneNesting.g": + x.G = nil + case "testpb.TestVersion3LoneNesting.h": + x.H = nil + case "testpb.TestVersion3LoneNesting.k": + x.K = nil + case "testpb.TestVersion3LoneNesting.non_critical_field": + x.NonCriticalField = "" + case "testpb.TestVersion3LoneNesting.inner1": + x.Inner1 = nil + case "testpb.TestVersion3LoneNesting.inner2": + x.Inner2 = nil + default: + if fd.IsExtension() { + panic(fmt.Errorf("proto3 declared messages do not support extensions: testpb.TestVersion3LoneNesting")) + } + panic(fmt.Errorf("message testpb.TestVersion3LoneNesting does not contain field %s", fd.FullName())) + } +} + +// Get retrieves the value for a field. +// +// For unpopulated scalars, it returns the default value, where +// the default value of a bytes scalar is guaranteed to be a copy. +// For unpopulated composite types, it returns an empty, read-only view +// of the value; to obtain a mutable reference, use Mutable. +func (x *fastReflection_TestVersion3LoneNesting) Get(descriptor protoreflect.FieldDescriptor) protoreflect.Value { + switch descriptor.FullName() { + case "testpb.TestVersion3LoneNesting.x": + value := x.X + return protoreflect.ValueOfInt64(value) + case "testpb.TestVersion3LoneNesting.a": + value := x.A + return protoreflect.ValueOfMessage(value.ProtoReflect()) + case "testpb.TestVersion3LoneNesting.b": + value := x.B + return protoreflect.ValueOfMessage(value.ProtoReflect()) + case "testpb.TestVersion3LoneNesting.c": + if len(x.C) == 0 { + return protoreflect.ValueOfList(&_TestVersion3LoneNesting_4_list{}) + } + listValue := &_TestVersion3LoneNesting_4_list{list: &x.C} + return protoreflect.ValueOfList(listValue) + case "testpb.TestVersion3LoneNesting.d": + if len(x.D) == 0 { + return protoreflect.ValueOfList(&_TestVersion3LoneNesting_5_list{}) + } + listValue := &_TestVersion3LoneNesting_5_list{list: &x.D} + return protoreflect.ValueOfList(listValue) + case "testpb.TestVersion3LoneNesting.f": + if x.Sum == nil { + return protoreflect.ValueOfMessage((*TestVersion3LoneNesting)(nil).ProtoReflect()) + } else if v, ok := x.Sum.(*TestVersion3LoneNesting_F); ok { + return protoreflect.ValueOfMessage(v.F.ProtoReflect()) + } else { + return protoreflect.ValueOfMessage((*TestVersion3LoneNesting)(nil).ProtoReflect()) + } + case "testpb.TestVersion3LoneNesting.g": + value := x.G + return protoreflect.ValueOfMessage(value.ProtoReflect()) + case "testpb.TestVersion3LoneNesting.h": + if len(x.H) == 0 { + return protoreflect.ValueOfList(&_TestVersion3LoneNesting_9_list{}) + } + listValue := &_TestVersion3LoneNesting_9_list{list: &x.H} + return protoreflect.ValueOfList(listValue) + case "testpb.TestVersion3LoneNesting.k": + value := x.K + return protoreflect.ValueOfMessage(value.ProtoReflect()) + case "testpb.TestVersion3LoneNesting.non_critical_field": + value := x.NonCriticalField + return protoreflect.ValueOfString(value) + case "testpb.TestVersion3LoneNesting.inner1": + value := x.Inner1 + return protoreflect.ValueOfMessage(value.ProtoReflect()) + case "testpb.TestVersion3LoneNesting.inner2": + value := x.Inner2 + return protoreflect.ValueOfMessage(value.ProtoReflect()) + default: + if descriptor.IsExtension() { + panic(fmt.Errorf("proto3 declared messages do not support extensions: testpb.TestVersion3LoneNesting")) + } + panic(fmt.Errorf("message testpb.TestVersion3LoneNesting does not contain field %s", descriptor.FullName())) + } +} + +// Set stores the value for a field. +// +// For a field belonging to a oneof, it implicitly clears any other field +// that may be currently set within the same oneof. +// For extension fields, it implicitly stores the provided ExtensionType. +// When setting a composite type, it is unspecified whether the stored value +// aliases the source's memory in any way. If the composite value is an +// empty, read-only value, then it panics. +// +// Set is a mutating operation and unsafe for concurrent use. +func (x *fastReflection_TestVersion3LoneNesting) Set(fd protoreflect.FieldDescriptor, value protoreflect.Value) { + switch fd.FullName() { + case "testpb.TestVersion3LoneNesting.x": + x.X = value.Int() + case "testpb.TestVersion3LoneNesting.a": + x.A = value.Message().Interface().(*TestVersion3) + case "testpb.TestVersion3LoneNesting.b": + x.B = value.Message().Interface().(*TestVersion3) + case "testpb.TestVersion3LoneNesting.c": + lv := value.List() + clv := lv.(*_TestVersion3LoneNesting_4_list) + x.C = *clv.list + case "testpb.TestVersion3LoneNesting.d": + lv := value.List() + clv := lv.(*_TestVersion3LoneNesting_5_list) + x.D = *clv.list + case "testpb.TestVersion3LoneNesting.f": + cv := value.Message().Interface().(*TestVersion3LoneNesting) + x.Sum = &TestVersion3LoneNesting_F{F: cv} + case "testpb.TestVersion3LoneNesting.g": + x.G = value.Message().Interface().(*anypb.Any) + case "testpb.TestVersion3LoneNesting.h": + lv := value.List() + clv := lv.(*_TestVersion3LoneNesting_9_list) + x.H = *clv.list + case "testpb.TestVersion3LoneNesting.k": + x.K = value.Message().Interface().(*Customer1) + case "testpb.TestVersion3LoneNesting.non_critical_field": + x.NonCriticalField = value.Interface().(string) + case "testpb.TestVersion3LoneNesting.inner1": + x.Inner1 = value.Message().Interface().(*TestVersion3LoneNesting_Inner1) + case "testpb.TestVersion3LoneNesting.inner2": + x.Inner2 = value.Message().Interface().(*TestVersion3LoneNesting_Inner2) + default: + if fd.IsExtension() { + panic(fmt.Errorf("proto3 declared messages do not support extensions: testpb.TestVersion3LoneNesting")) + } + panic(fmt.Errorf("message testpb.TestVersion3LoneNesting does not contain field %s", fd.FullName())) + } +} + +// Mutable returns a mutable reference to a composite type. +// +// If the field is unpopulated, it may allocate a composite value. +// For a field belonging to a oneof, it implicitly clears any other field +// that may be currently set within the same oneof. +// For extension fields, it implicitly stores the provided ExtensionType +// if not already stored. +// It panics if the field does not contain a composite type. +// +// Mutable is a mutating operation and unsafe for concurrent use. +func (x *fastReflection_TestVersion3LoneNesting) Mutable(fd protoreflect.FieldDescriptor) protoreflect.Value { + switch fd.FullName() { + case "testpb.TestVersion3LoneNesting.a": + if x.A == nil { + x.A = new(TestVersion3) + } + return protoreflect.ValueOfMessage(x.A.ProtoReflect()) + case "testpb.TestVersion3LoneNesting.b": + if x.B == nil { + x.B = new(TestVersion3) + } + return protoreflect.ValueOfMessage(x.B.ProtoReflect()) + case "testpb.TestVersion3LoneNesting.c": + if x.C == nil { + x.C = []*TestVersion3{} + } + value := &_TestVersion3LoneNesting_4_list{list: &x.C} + return protoreflect.ValueOfList(value) + case "testpb.TestVersion3LoneNesting.d": + if x.D == nil { + x.D = []*TestVersion3{} + } + value := &_TestVersion3LoneNesting_5_list{list: &x.D} + return protoreflect.ValueOfList(value) + case "testpb.TestVersion3LoneNesting.f": + if x.Sum == nil { + value := &TestVersion3LoneNesting{} + oneofValue := &TestVersion3LoneNesting_F{F: value} + x.Sum = oneofValue + return protoreflect.ValueOfMessage(value.ProtoReflect()) + } + switch m := x.Sum.(type) { + case *TestVersion3LoneNesting_F: + return protoreflect.ValueOfMessage(m.F.ProtoReflect()) + default: + value := &TestVersion3LoneNesting{} + oneofValue := &TestVersion3LoneNesting_F{F: value} + x.Sum = oneofValue + return protoreflect.ValueOfMessage(value.ProtoReflect()) + } + case "testpb.TestVersion3LoneNesting.g": + if x.G == nil { + x.G = new(anypb.Any) + } + return protoreflect.ValueOfMessage(x.G.ProtoReflect()) + case "testpb.TestVersion3LoneNesting.h": + if x.H == nil { + x.H = []*TestVersion1{} + } + value := &_TestVersion3LoneNesting_9_list{list: &x.H} + return protoreflect.ValueOfList(value) + case "testpb.TestVersion3LoneNesting.k": + if x.K == nil { + x.K = new(Customer1) + } + return protoreflect.ValueOfMessage(x.K.ProtoReflect()) + case "testpb.TestVersion3LoneNesting.inner1": + if x.Inner1 == nil { + x.Inner1 = new(TestVersion3LoneNesting_Inner1) + } + return protoreflect.ValueOfMessage(x.Inner1.ProtoReflect()) + case "testpb.TestVersion3LoneNesting.inner2": + if x.Inner2 == nil { + x.Inner2 = new(TestVersion3LoneNesting_Inner2) + } + return protoreflect.ValueOfMessage(x.Inner2.ProtoReflect()) + case "testpb.TestVersion3LoneNesting.x": + panic(fmt.Errorf("field x of message testpb.TestVersion3LoneNesting is not mutable")) + case "testpb.TestVersion3LoneNesting.non_critical_field": + panic(fmt.Errorf("field non_critical_field of message testpb.TestVersion3LoneNesting is not mutable")) + default: + if fd.IsExtension() { + panic(fmt.Errorf("proto3 declared messages do not support extensions: testpb.TestVersion3LoneNesting")) + } + panic(fmt.Errorf("message testpb.TestVersion3LoneNesting does not contain field %s", fd.FullName())) + } +} + +// NewField returns a new value that is assignable to the field +// for the given descriptor. For scalars, this returns the default value. +// For lists, maps, and messages, this returns a new, empty, mutable value. +func (x *fastReflection_TestVersion3LoneNesting) NewField(fd protoreflect.FieldDescriptor) protoreflect.Value { + switch fd.FullName() { + case "testpb.TestVersion3LoneNesting.x": + return protoreflect.ValueOfInt64(int64(0)) + case "testpb.TestVersion3LoneNesting.a": + m := new(TestVersion3) + return protoreflect.ValueOfMessage(m.ProtoReflect()) + case "testpb.TestVersion3LoneNesting.b": + m := new(TestVersion3) + return protoreflect.ValueOfMessage(m.ProtoReflect()) + case "testpb.TestVersion3LoneNesting.c": + list := []*TestVersion3{} + return protoreflect.ValueOfList(&_TestVersion3LoneNesting_4_list{list: &list}) + case "testpb.TestVersion3LoneNesting.d": + list := []*TestVersion3{} + return protoreflect.ValueOfList(&_TestVersion3LoneNesting_5_list{list: &list}) + case "testpb.TestVersion3LoneNesting.f": + value := &TestVersion3LoneNesting{} + return protoreflect.ValueOfMessage(value.ProtoReflect()) + case "testpb.TestVersion3LoneNesting.g": + m := new(anypb.Any) + return protoreflect.ValueOfMessage(m.ProtoReflect()) + case "testpb.TestVersion3LoneNesting.h": + list := []*TestVersion1{} + return protoreflect.ValueOfList(&_TestVersion3LoneNesting_9_list{list: &list}) + case "testpb.TestVersion3LoneNesting.k": + m := new(Customer1) + return protoreflect.ValueOfMessage(m.ProtoReflect()) + case "testpb.TestVersion3LoneNesting.non_critical_field": + return protoreflect.ValueOfString("") + case "testpb.TestVersion3LoneNesting.inner1": + m := new(TestVersion3LoneNesting_Inner1) + return protoreflect.ValueOfMessage(m.ProtoReflect()) + case "testpb.TestVersion3LoneNesting.inner2": + m := new(TestVersion3LoneNesting_Inner2) + return protoreflect.ValueOfMessage(m.ProtoReflect()) + default: + if fd.IsExtension() { + panic(fmt.Errorf("proto3 declared messages do not support extensions: testpb.TestVersion3LoneNesting")) + } + panic(fmt.Errorf("message testpb.TestVersion3LoneNesting does not contain field %s", fd.FullName())) + } +} + +// WhichOneof reports which field within the oneof is populated, +// returning nil if none are populated. +// It panics if the oneof descriptor does not belong to this message. +func (x *fastReflection_TestVersion3LoneNesting) WhichOneof(d protoreflect.OneofDescriptor) protoreflect.FieldDescriptor { + switch d.FullName() { + case "testpb.TestVersion3LoneNesting.sum": + if x.Sum == nil { + return nil + } + switch x.Sum.(type) { + case *TestVersion3LoneNesting_F: + return x.Descriptor().Fields().ByName("f") + } + default: + panic(fmt.Errorf("%s is not a oneof field in testpb.TestVersion3LoneNesting", d.FullName())) + } + panic("unreachable") +} + +// GetUnknown retrieves the entire list of unknown fields. +// The caller may only mutate the contents of the RawFields +// if the mutated bytes are stored back into the message with SetUnknown. +func (x *fastReflection_TestVersion3LoneNesting) GetUnknown() protoreflect.RawFields { + return x.unknownFields +} + +// SetUnknown stores an entire list of unknown fields. +// The raw fields must be syntactically valid according to the wire format. +// An implementation may panic if this is not the case. +// Once stored, the caller must not mutate the content of the RawFields. +// An empty RawFields may be passed to clear the fields. +// +// SetUnknown is a mutating operation and unsafe for concurrent use. +func (x *fastReflection_TestVersion3LoneNesting) SetUnknown(fields protoreflect.RawFields) { + x.unknownFields = fields +} + +// IsValid reports whether the message is valid. +// +// An invalid message is an empty, read-only value. +// +// An invalid message often corresponds to a nil pointer of the concrete +// message type, but the details are implementation dependent. +// Validity is not part of the protobuf data model, and may not +// be preserved in marshaling or other operations. +func (x *fastReflection_TestVersion3LoneNesting) IsValid() bool { + return x != nil +} + +// ProtoMethods returns optional fastReflectionFeature-path implementations of various operations. +// This method may return nil. +// +// The returned methods type is identical to +// "google.golang.org/protobuf/runtime/protoiface".Methods. +// Consult the protoiface package documentation for details. +func (x *fastReflection_TestVersion3LoneNesting) ProtoMethods() *protoiface.Methods { + size := func(input protoiface.SizeInput) protoiface.SizeOutput { + x := input.Message.Interface().(*TestVersion3LoneNesting) + if x == nil { + return protoiface.SizeOutput{ + NoUnkeyedLiterals: input.NoUnkeyedLiterals, + Size: 0, + } + } + options := runtime.SizeInputToOptions(input) + _ = options + var n int + var l int + _ = l + if x.X != 0 { + n += 1 + runtime.Sov(uint64(x.X)) + } + if x.A != nil { + l = options.Size(x.A) + n += 1 + l + runtime.Sov(uint64(l)) + } + if x.B != nil { + l = options.Size(x.B) + n += 1 + l + runtime.Sov(uint64(l)) + } + if len(x.C) > 0 { + for _, e := range x.C { + l = options.Size(e) + n += 1 + l + runtime.Sov(uint64(l)) + } + } + if len(x.D) > 0 { + for _, e := range x.D { + l = options.Size(e) + n += 1 + l + runtime.Sov(uint64(l)) + } + } + switch x := x.Sum.(type) { + case *TestVersion3LoneNesting_F: + if x == nil { + break + } + l = options.Size(x.F) + n += 1 + l + runtime.Sov(uint64(l)) + } + if x.G != nil { + l = options.Size(x.G) + n += 1 + l + runtime.Sov(uint64(l)) + } + if len(x.H) > 0 { + for _, e := range x.H { + l = options.Size(e) + n += 1 + l + runtime.Sov(uint64(l)) + } + } + if x.K != nil { + l = options.Size(x.K) + n += 1 + l + runtime.Sov(uint64(l)) + } + l = len(x.NonCriticalField) + if l > 0 { + n += 2 + l + runtime.Sov(uint64(l)) + } + if x.Inner1 != nil { + l = options.Size(x.Inner1) + n += 1 + l + runtime.Sov(uint64(l)) + } + if x.Inner2 != nil { + l = options.Size(x.Inner2) + n += 1 + l + runtime.Sov(uint64(l)) + } + if x.unknownFields != nil { + n += len(x.unknownFields) + } + return protoiface.SizeOutput{ + NoUnkeyedLiterals: input.NoUnkeyedLiterals, + Size: n, + } + } + + marshal := func(input protoiface.MarshalInput) (protoiface.MarshalOutput, error) { + x := input.Message.Interface().(*TestVersion3LoneNesting) + if x == nil { + return protoiface.MarshalOutput{ + NoUnkeyedLiterals: input.NoUnkeyedLiterals, + Buf: input.Buf, + }, nil + } + options := runtime.MarshalInputToOptions(input) + _ = options + size := options.Size(x) + dAtA := make([]byte, size) + i := len(dAtA) + _ = i + var l int + _ = l + if x.unknownFields != nil { + i -= len(x.unknownFields) + copy(dAtA[i:], x.unknownFields) + } + switch x := x.Sum.(type) { + case *TestVersion3LoneNesting_F: + encoded, err := options.Marshal(x.F) + if err != nil { + return protoiface.MarshalOutput{ + NoUnkeyedLiterals: input.NoUnkeyedLiterals, + Buf: input.Buf, + }, err + } + i -= len(encoded) + copy(dAtA[i:], encoded) + i = runtime.EncodeVarint(dAtA, i, uint64(len(encoded))) + i-- + dAtA[i] = 0x3a + } + if len(x.NonCriticalField) > 0 { + i -= len(x.NonCriticalField) + copy(dAtA[i:], x.NonCriticalField) + i = runtime.EncodeVarint(dAtA, i, uint64(len(x.NonCriticalField))) + i-- + dAtA[i] = 0x40 + i-- + dAtA[i] = 0xba + } + if x.Inner2 != nil { + encoded, err := options.Marshal(x.Inner2) + if err != nil { + return protoiface.MarshalOutput{ + NoUnkeyedLiterals: input.NoUnkeyedLiterals, + Buf: input.Buf, + }, err + } + i -= len(encoded) + copy(dAtA[i:], encoded) + i = runtime.EncodeVarint(dAtA, i, uint64(len(encoded))) + i-- + dAtA[i] = 0x7a + } + if x.Inner1 != nil { + encoded, err := options.Marshal(x.Inner1) + if err != nil { + return protoiface.MarshalOutput{ + NoUnkeyedLiterals: input.NoUnkeyedLiterals, + Buf: input.Buf, + }, err + } + i -= len(encoded) + copy(dAtA[i:], encoded) + i = runtime.EncodeVarint(dAtA, i, uint64(len(encoded))) + i-- + dAtA[i] = 0x72 + } + if x.K != nil { + encoded, err := options.Marshal(x.K) + if err != nil { + return protoiface.MarshalOutput{ + NoUnkeyedLiterals: input.NoUnkeyedLiterals, + Buf: input.Buf, + }, err + } + i -= len(encoded) + copy(dAtA[i:], encoded) + i = runtime.EncodeVarint(dAtA, i, uint64(len(encoded))) + i-- + dAtA[i] = 0x62 + } + if len(x.H) > 0 { + for iNdEx := len(x.H) - 1; iNdEx >= 0; iNdEx-- { + encoded, err := options.Marshal(x.H[iNdEx]) + if err != nil { + return protoiface.MarshalOutput{ + NoUnkeyedLiterals: input.NoUnkeyedLiterals, + Buf: input.Buf, + }, err + } + i -= len(encoded) + copy(dAtA[i:], encoded) + i = runtime.EncodeVarint(dAtA, i, uint64(len(encoded))) + i-- + dAtA[i] = 0x4a + } + } + if x.G != nil { + encoded, err := options.Marshal(x.G) + if err != nil { + return protoiface.MarshalOutput{ + NoUnkeyedLiterals: input.NoUnkeyedLiterals, + Buf: input.Buf, + }, err + } + i -= len(encoded) + copy(dAtA[i:], encoded) + i = runtime.EncodeVarint(dAtA, i, uint64(len(encoded))) + i-- + dAtA[i] = 0x42 + } + if len(x.D) > 0 { + for iNdEx := len(x.D) - 1; iNdEx >= 0; iNdEx-- { + encoded, err := options.Marshal(x.D[iNdEx]) + if err != nil { + return protoiface.MarshalOutput{ + NoUnkeyedLiterals: input.NoUnkeyedLiterals, + Buf: input.Buf, + }, err + } + i -= len(encoded) + copy(dAtA[i:], encoded) + i = runtime.EncodeVarint(dAtA, i, uint64(len(encoded))) + i-- + dAtA[i] = 0x2a + } + } + if len(x.C) > 0 { + for iNdEx := len(x.C) - 1; iNdEx >= 0; iNdEx-- { + encoded, err := options.Marshal(x.C[iNdEx]) + if err != nil { + return protoiface.MarshalOutput{ + NoUnkeyedLiterals: input.NoUnkeyedLiterals, + Buf: input.Buf, + }, err + } + i -= len(encoded) + copy(dAtA[i:], encoded) + i = runtime.EncodeVarint(dAtA, i, uint64(len(encoded))) + i-- + dAtA[i] = 0x22 + } + } + if x.B != nil { + encoded, err := options.Marshal(x.B) + if err != nil { + return protoiface.MarshalOutput{ + NoUnkeyedLiterals: input.NoUnkeyedLiterals, + Buf: input.Buf, + }, err + } + i -= len(encoded) + copy(dAtA[i:], encoded) + i = runtime.EncodeVarint(dAtA, i, uint64(len(encoded))) + i-- + dAtA[i] = 0x1a + } + if x.A != nil { + encoded, err := options.Marshal(x.A) + if err != nil { + return protoiface.MarshalOutput{ + NoUnkeyedLiterals: input.NoUnkeyedLiterals, + Buf: input.Buf, + }, err + } + i -= len(encoded) + copy(dAtA[i:], encoded) + i = runtime.EncodeVarint(dAtA, i, uint64(len(encoded))) + i-- + dAtA[i] = 0x12 + } + if x.X != 0 { + i = runtime.EncodeVarint(dAtA, i, uint64(x.X)) + i-- + dAtA[i] = 0x8 + } + if input.Buf != nil { + input.Buf = append(input.Buf, dAtA...) + } else { + input.Buf = dAtA + } + return protoiface.MarshalOutput{ + NoUnkeyedLiterals: input.NoUnkeyedLiterals, + Buf: input.Buf, + }, nil + } + unmarshal := func(input protoiface.UnmarshalInput) (protoiface.UnmarshalOutput, error) { + x := input.Message.Interface().(*TestVersion3LoneNesting) + if x == nil { + return protoiface.UnmarshalOutput{ + NoUnkeyedLiterals: input.NoUnkeyedLiterals, + Flags: input.Flags, + }, nil + } + options := runtime.UnmarshalInputToOptions(input) + _ = options + dAtA := input.Buf + l := len(dAtA) + iNdEx := 0 + for iNdEx < l { + preIndex := iNdEx + var wire uint64 + for shift := uint(0); ; shift += 7 { + if shift >= 64 { + return protoiface.UnmarshalOutput{NoUnkeyedLiterals: input.NoUnkeyedLiterals, Flags: input.Flags}, runtime.ErrIntOverflow + } + if iNdEx >= l { + return protoiface.UnmarshalOutput{NoUnkeyedLiterals: input.NoUnkeyedLiterals, Flags: input.Flags}, io.ErrUnexpectedEOF + } + b := dAtA[iNdEx] + iNdEx++ + wire |= uint64(b&0x7F) << shift + if b < 0x80 { + break + } + } + fieldNum := int32(wire >> 3) + wireType := int(wire & 0x7) + if wireType == 4 { + return protoiface.UnmarshalOutput{NoUnkeyedLiterals: input.NoUnkeyedLiterals, Flags: input.Flags}, fmt.Errorf("proto: TestVersion3LoneNesting: wiretype end group for non-group") + } + if fieldNum <= 0 { + return protoiface.UnmarshalOutput{NoUnkeyedLiterals: input.NoUnkeyedLiterals, Flags: input.Flags}, fmt.Errorf("proto: TestVersion3LoneNesting: illegal tag %d (wire type %d)", fieldNum, wire) + } + switch fieldNum { + case 1: + if wireType != 0 { + return protoiface.UnmarshalOutput{NoUnkeyedLiterals: input.NoUnkeyedLiterals, Flags: input.Flags}, fmt.Errorf("proto: wrong wireType = %d for field X", wireType) + } + x.X = 0 + for shift := uint(0); ; shift += 7 { + if shift >= 64 { + return protoiface.UnmarshalOutput{NoUnkeyedLiterals: input.NoUnkeyedLiterals, Flags: input.Flags}, runtime.ErrIntOverflow + } + if iNdEx >= l { + return protoiface.UnmarshalOutput{NoUnkeyedLiterals: input.NoUnkeyedLiterals, Flags: input.Flags}, io.ErrUnexpectedEOF + } + b := dAtA[iNdEx] + iNdEx++ + x.X |= int64(b&0x7F) << shift + if b < 0x80 { + break + } + } + case 2: + if wireType != 2 { + return protoiface.UnmarshalOutput{NoUnkeyedLiterals: input.NoUnkeyedLiterals, Flags: input.Flags}, fmt.Errorf("proto: wrong wireType = %d for field A", wireType) + } + var msglen int + for shift := uint(0); ; shift += 7 { + if shift >= 64 { + return protoiface.UnmarshalOutput{NoUnkeyedLiterals: input.NoUnkeyedLiterals, Flags: input.Flags}, runtime.ErrIntOverflow + } + if iNdEx >= l { + return protoiface.UnmarshalOutput{NoUnkeyedLiterals: input.NoUnkeyedLiterals, Flags: input.Flags}, io.ErrUnexpectedEOF + } + b := dAtA[iNdEx] + iNdEx++ + msglen |= int(b&0x7F) << shift + if b < 0x80 { + break + } + } + if msglen < 0 { + return protoiface.UnmarshalOutput{NoUnkeyedLiterals: input.NoUnkeyedLiterals, Flags: input.Flags}, runtime.ErrInvalidLength + } + postIndex := iNdEx + msglen + if postIndex < 0 { + return protoiface.UnmarshalOutput{NoUnkeyedLiterals: input.NoUnkeyedLiterals, Flags: input.Flags}, runtime.ErrInvalidLength + } + if postIndex > l { + return protoiface.UnmarshalOutput{NoUnkeyedLiterals: input.NoUnkeyedLiterals, Flags: input.Flags}, io.ErrUnexpectedEOF + } + if x.A == nil { + x.A = &TestVersion3{} + } + if err := options.Unmarshal(dAtA[iNdEx:postIndex], x.A); err != nil { + return protoiface.UnmarshalOutput{NoUnkeyedLiterals: input.NoUnkeyedLiterals, Flags: input.Flags}, err + } + iNdEx = postIndex + case 3: + if wireType != 2 { + return protoiface.UnmarshalOutput{NoUnkeyedLiterals: input.NoUnkeyedLiterals, Flags: input.Flags}, fmt.Errorf("proto: wrong wireType = %d for field B", wireType) + } + var msglen int + for shift := uint(0); ; shift += 7 { + if shift >= 64 { + return protoiface.UnmarshalOutput{NoUnkeyedLiterals: input.NoUnkeyedLiterals, Flags: input.Flags}, runtime.ErrIntOverflow + } + if iNdEx >= l { + return protoiface.UnmarshalOutput{NoUnkeyedLiterals: input.NoUnkeyedLiterals, Flags: input.Flags}, io.ErrUnexpectedEOF + } + b := dAtA[iNdEx] + iNdEx++ + msglen |= int(b&0x7F) << shift + if b < 0x80 { + break + } + } + if msglen < 0 { + return protoiface.UnmarshalOutput{NoUnkeyedLiterals: input.NoUnkeyedLiterals, Flags: input.Flags}, runtime.ErrInvalidLength + } + postIndex := iNdEx + msglen + if postIndex < 0 { + return protoiface.UnmarshalOutput{NoUnkeyedLiterals: input.NoUnkeyedLiterals, Flags: input.Flags}, runtime.ErrInvalidLength + } + if postIndex > l { + return protoiface.UnmarshalOutput{NoUnkeyedLiterals: input.NoUnkeyedLiterals, Flags: input.Flags}, io.ErrUnexpectedEOF + } + if x.B == nil { + x.B = &TestVersion3{} + } + if err := options.Unmarshal(dAtA[iNdEx:postIndex], x.B); err != nil { + return protoiface.UnmarshalOutput{NoUnkeyedLiterals: input.NoUnkeyedLiterals, Flags: input.Flags}, err + } + iNdEx = postIndex + case 4: + if wireType != 2 { + return protoiface.UnmarshalOutput{NoUnkeyedLiterals: input.NoUnkeyedLiterals, Flags: input.Flags}, fmt.Errorf("proto: wrong wireType = %d for field C", wireType) + } + var msglen int + for shift := uint(0); ; shift += 7 { + if shift >= 64 { + return protoiface.UnmarshalOutput{NoUnkeyedLiterals: input.NoUnkeyedLiterals, Flags: input.Flags}, runtime.ErrIntOverflow + } + if iNdEx >= l { + return protoiface.UnmarshalOutput{NoUnkeyedLiterals: input.NoUnkeyedLiterals, Flags: input.Flags}, io.ErrUnexpectedEOF + } + b := dAtA[iNdEx] + iNdEx++ + msglen |= int(b&0x7F) << shift + if b < 0x80 { + break + } + } + if msglen < 0 { + return protoiface.UnmarshalOutput{NoUnkeyedLiterals: input.NoUnkeyedLiterals, Flags: input.Flags}, runtime.ErrInvalidLength + } + postIndex := iNdEx + msglen + if postIndex < 0 { + return protoiface.UnmarshalOutput{NoUnkeyedLiterals: input.NoUnkeyedLiterals, Flags: input.Flags}, runtime.ErrInvalidLength + } + if postIndex > l { + return protoiface.UnmarshalOutput{NoUnkeyedLiterals: input.NoUnkeyedLiterals, Flags: input.Flags}, io.ErrUnexpectedEOF + } + x.C = append(x.C, &TestVersion3{}) + if err := options.Unmarshal(dAtA[iNdEx:postIndex], x.C[len(x.C)-1]); err != nil { + return protoiface.UnmarshalOutput{NoUnkeyedLiterals: input.NoUnkeyedLiterals, Flags: input.Flags}, err + } + iNdEx = postIndex + case 5: + if wireType != 2 { + return protoiface.UnmarshalOutput{NoUnkeyedLiterals: input.NoUnkeyedLiterals, Flags: input.Flags}, fmt.Errorf("proto: wrong wireType = %d for field D", wireType) + } + var msglen int + for shift := uint(0); ; shift += 7 { + if shift >= 64 { + return protoiface.UnmarshalOutput{NoUnkeyedLiterals: input.NoUnkeyedLiterals, Flags: input.Flags}, runtime.ErrIntOverflow + } + if iNdEx >= l { + return protoiface.UnmarshalOutput{NoUnkeyedLiterals: input.NoUnkeyedLiterals, Flags: input.Flags}, io.ErrUnexpectedEOF + } + b := dAtA[iNdEx] + iNdEx++ + msglen |= int(b&0x7F) << shift + if b < 0x80 { + break + } + } + if msglen < 0 { + return protoiface.UnmarshalOutput{NoUnkeyedLiterals: input.NoUnkeyedLiterals, Flags: input.Flags}, runtime.ErrInvalidLength + } + postIndex := iNdEx + msglen + if postIndex < 0 { + return protoiface.UnmarshalOutput{NoUnkeyedLiterals: input.NoUnkeyedLiterals, Flags: input.Flags}, runtime.ErrInvalidLength + } + if postIndex > l { + return protoiface.UnmarshalOutput{NoUnkeyedLiterals: input.NoUnkeyedLiterals, Flags: input.Flags}, io.ErrUnexpectedEOF + } + x.D = append(x.D, &TestVersion3{}) + if err := options.Unmarshal(dAtA[iNdEx:postIndex], x.D[len(x.D)-1]); err != nil { + return protoiface.UnmarshalOutput{NoUnkeyedLiterals: input.NoUnkeyedLiterals, Flags: input.Flags}, err + } + iNdEx = postIndex + case 7: + if wireType != 2 { + return protoiface.UnmarshalOutput{NoUnkeyedLiterals: input.NoUnkeyedLiterals, Flags: input.Flags}, fmt.Errorf("proto: wrong wireType = %d for field F", wireType) + } + var msglen int + for shift := uint(0); ; shift += 7 { + if shift >= 64 { + return protoiface.UnmarshalOutput{NoUnkeyedLiterals: input.NoUnkeyedLiterals, Flags: input.Flags}, runtime.ErrIntOverflow + } + if iNdEx >= l { + return protoiface.UnmarshalOutput{NoUnkeyedLiterals: input.NoUnkeyedLiterals, Flags: input.Flags}, io.ErrUnexpectedEOF + } + b := dAtA[iNdEx] + iNdEx++ + msglen |= int(b&0x7F) << shift + if b < 0x80 { + break + } + } + if msglen < 0 { + return protoiface.UnmarshalOutput{NoUnkeyedLiterals: input.NoUnkeyedLiterals, Flags: input.Flags}, runtime.ErrInvalidLength + } + postIndex := iNdEx + msglen + if postIndex < 0 { + return protoiface.UnmarshalOutput{NoUnkeyedLiterals: input.NoUnkeyedLiterals, Flags: input.Flags}, runtime.ErrInvalidLength + } + if postIndex > l { + return protoiface.UnmarshalOutput{NoUnkeyedLiterals: input.NoUnkeyedLiterals, Flags: input.Flags}, io.ErrUnexpectedEOF + } + v := &TestVersion3LoneNesting{} + if err := options.Unmarshal(dAtA[iNdEx:postIndex], v); err != nil { + return protoiface.UnmarshalOutput{NoUnkeyedLiterals: input.NoUnkeyedLiterals, Flags: input.Flags}, err + } + x.Sum = &TestVersion3LoneNesting_F{v} + iNdEx = postIndex + case 8: + if wireType != 2 { + return protoiface.UnmarshalOutput{NoUnkeyedLiterals: input.NoUnkeyedLiterals, Flags: input.Flags}, fmt.Errorf("proto: wrong wireType = %d for field G", wireType) + } + var msglen int + for shift := uint(0); ; shift += 7 { + if shift >= 64 { + return protoiface.UnmarshalOutput{NoUnkeyedLiterals: input.NoUnkeyedLiterals, Flags: input.Flags}, runtime.ErrIntOverflow + } + if iNdEx >= l { + return protoiface.UnmarshalOutput{NoUnkeyedLiterals: input.NoUnkeyedLiterals, Flags: input.Flags}, io.ErrUnexpectedEOF + } + b := dAtA[iNdEx] + iNdEx++ + msglen |= int(b&0x7F) << shift + if b < 0x80 { + break + } + } + if msglen < 0 { + return protoiface.UnmarshalOutput{NoUnkeyedLiterals: input.NoUnkeyedLiterals, Flags: input.Flags}, runtime.ErrInvalidLength + } + postIndex := iNdEx + msglen + if postIndex < 0 { + return protoiface.UnmarshalOutput{NoUnkeyedLiterals: input.NoUnkeyedLiterals, Flags: input.Flags}, runtime.ErrInvalidLength + } + if postIndex > l { + return protoiface.UnmarshalOutput{NoUnkeyedLiterals: input.NoUnkeyedLiterals, Flags: input.Flags}, io.ErrUnexpectedEOF + } + if x.G == nil { + x.G = &anypb.Any{} + } + if err := options.Unmarshal(dAtA[iNdEx:postIndex], x.G); err != nil { + return protoiface.UnmarshalOutput{NoUnkeyedLiterals: input.NoUnkeyedLiterals, Flags: input.Flags}, err + } + iNdEx = postIndex + case 9: + if wireType != 2 { + return protoiface.UnmarshalOutput{NoUnkeyedLiterals: input.NoUnkeyedLiterals, Flags: input.Flags}, fmt.Errorf("proto: wrong wireType = %d for field H", wireType) + } + var msglen int + for shift := uint(0); ; shift += 7 { + if shift >= 64 { + return protoiface.UnmarshalOutput{NoUnkeyedLiterals: input.NoUnkeyedLiterals, Flags: input.Flags}, runtime.ErrIntOverflow + } + if iNdEx >= l { + return protoiface.UnmarshalOutput{NoUnkeyedLiterals: input.NoUnkeyedLiterals, Flags: input.Flags}, io.ErrUnexpectedEOF + } + b := dAtA[iNdEx] + iNdEx++ + msglen |= int(b&0x7F) << shift + if b < 0x80 { + break + } + } + if msglen < 0 { + return protoiface.UnmarshalOutput{NoUnkeyedLiterals: input.NoUnkeyedLiterals, Flags: input.Flags}, runtime.ErrInvalidLength + } + postIndex := iNdEx + msglen + if postIndex < 0 { + return protoiface.UnmarshalOutput{NoUnkeyedLiterals: input.NoUnkeyedLiterals, Flags: input.Flags}, runtime.ErrInvalidLength + } + if postIndex > l { + return protoiface.UnmarshalOutput{NoUnkeyedLiterals: input.NoUnkeyedLiterals, Flags: input.Flags}, io.ErrUnexpectedEOF + } + x.H = append(x.H, &TestVersion1{}) + if err := options.Unmarshal(dAtA[iNdEx:postIndex], x.H[len(x.H)-1]); err != nil { + return protoiface.UnmarshalOutput{NoUnkeyedLiterals: input.NoUnkeyedLiterals, Flags: input.Flags}, err + } + iNdEx = postIndex + case 12: + if wireType != 2 { + return protoiface.UnmarshalOutput{NoUnkeyedLiterals: input.NoUnkeyedLiterals, Flags: input.Flags}, fmt.Errorf("proto: wrong wireType = %d for field K", wireType) + } + var msglen int + for shift := uint(0); ; shift += 7 { + if shift >= 64 { + return protoiface.UnmarshalOutput{NoUnkeyedLiterals: input.NoUnkeyedLiterals, Flags: input.Flags}, runtime.ErrIntOverflow + } + if iNdEx >= l { + return protoiface.UnmarshalOutput{NoUnkeyedLiterals: input.NoUnkeyedLiterals, Flags: input.Flags}, io.ErrUnexpectedEOF + } + b := dAtA[iNdEx] + iNdEx++ + msglen |= int(b&0x7F) << shift + if b < 0x80 { + break + } + } + if msglen < 0 { + return protoiface.UnmarshalOutput{NoUnkeyedLiterals: input.NoUnkeyedLiterals, Flags: input.Flags}, runtime.ErrInvalidLength + } + postIndex := iNdEx + msglen + if postIndex < 0 { + return protoiface.UnmarshalOutput{NoUnkeyedLiterals: input.NoUnkeyedLiterals, Flags: input.Flags}, runtime.ErrInvalidLength + } + if postIndex > l { + return protoiface.UnmarshalOutput{NoUnkeyedLiterals: input.NoUnkeyedLiterals, Flags: input.Flags}, io.ErrUnexpectedEOF + } + if x.K == nil { + x.K = &Customer1{} + } + if err := options.Unmarshal(dAtA[iNdEx:postIndex], x.K); err != nil { + return protoiface.UnmarshalOutput{NoUnkeyedLiterals: input.NoUnkeyedLiterals, Flags: input.Flags}, err + } + iNdEx = postIndex + case 1031: + if wireType != 2 { + return protoiface.UnmarshalOutput{NoUnkeyedLiterals: input.NoUnkeyedLiterals, Flags: input.Flags}, fmt.Errorf("proto: wrong wireType = %d for field NonCriticalField", wireType) + } + var stringLen uint64 + for shift := uint(0); ; shift += 7 { + if shift >= 64 { + return protoiface.UnmarshalOutput{NoUnkeyedLiterals: input.NoUnkeyedLiterals, Flags: input.Flags}, runtime.ErrIntOverflow + } + if iNdEx >= l { + return protoiface.UnmarshalOutput{NoUnkeyedLiterals: input.NoUnkeyedLiterals, Flags: input.Flags}, io.ErrUnexpectedEOF + } + b := dAtA[iNdEx] + iNdEx++ + stringLen |= uint64(b&0x7F) << shift + if b < 0x80 { + break + } + } + intStringLen := int(stringLen) + if intStringLen < 0 { + return protoiface.UnmarshalOutput{NoUnkeyedLiterals: input.NoUnkeyedLiterals, Flags: input.Flags}, runtime.ErrInvalidLength + } + postIndex := iNdEx + intStringLen + if postIndex < 0 { + return protoiface.UnmarshalOutput{NoUnkeyedLiterals: input.NoUnkeyedLiterals, Flags: input.Flags}, runtime.ErrInvalidLength + } + if postIndex > l { + return protoiface.UnmarshalOutput{NoUnkeyedLiterals: input.NoUnkeyedLiterals, Flags: input.Flags}, io.ErrUnexpectedEOF + } + x.NonCriticalField = string(dAtA[iNdEx:postIndex]) + iNdEx = postIndex + case 14: + if wireType != 2 { + return protoiface.UnmarshalOutput{NoUnkeyedLiterals: input.NoUnkeyedLiterals, Flags: input.Flags}, fmt.Errorf("proto: wrong wireType = %d for field Inner1", wireType) + } + var msglen int + for shift := uint(0); ; shift += 7 { + if shift >= 64 { + return protoiface.UnmarshalOutput{NoUnkeyedLiterals: input.NoUnkeyedLiterals, Flags: input.Flags}, runtime.ErrIntOverflow + } + if iNdEx >= l { + return protoiface.UnmarshalOutput{NoUnkeyedLiterals: input.NoUnkeyedLiterals, Flags: input.Flags}, io.ErrUnexpectedEOF + } + b := dAtA[iNdEx] + iNdEx++ + msglen |= int(b&0x7F) << shift + if b < 0x80 { + break + } + } + if msglen < 0 { + return protoiface.UnmarshalOutput{NoUnkeyedLiterals: input.NoUnkeyedLiterals, Flags: input.Flags}, runtime.ErrInvalidLength + } + postIndex := iNdEx + msglen + if postIndex < 0 { + return protoiface.UnmarshalOutput{NoUnkeyedLiterals: input.NoUnkeyedLiterals, Flags: input.Flags}, runtime.ErrInvalidLength + } + if postIndex > l { + return protoiface.UnmarshalOutput{NoUnkeyedLiterals: input.NoUnkeyedLiterals, Flags: input.Flags}, io.ErrUnexpectedEOF + } + if x.Inner1 == nil { + x.Inner1 = &TestVersion3LoneNesting_Inner1{} + } + if err := options.Unmarshal(dAtA[iNdEx:postIndex], x.Inner1); err != nil { + return protoiface.UnmarshalOutput{NoUnkeyedLiterals: input.NoUnkeyedLiterals, Flags: input.Flags}, err + } + iNdEx = postIndex + case 15: + if wireType != 2 { + return protoiface.UnmarshalOutput{NoUnkeyedLiterals: input.NoUnkeyedLiterals, Flags: input.Flags}, fmt.Errorf("proto: wrong wireType = %d for field Inner2", wireType) + } + var msglen int + for shift := uint(0); ; shift += 7 { + if shift >= 64 { + return protoiface.UnmarshalOutput{NoUnkeyedLiterals: input.NoUnkeyedLiterals, Flags: input.Flags}, runtime.ErrIntOverflow + } + if iNdEx >= l { + return protoiface.UnmarshalOutput{NoUnkeyedLiterals: input.NoUnkeyedLiterals, Flags: input.Flags}, io.ErrUnexpectedEOF + } + b := dAtA[iNdEx] + iNdEx++ + msglen |= int(b&0x7F) << shift + if b < 0x80 { + break + } + } + if msglen < 0 { + return protoiface.UnmarshalOutput{NoUnkeyedLiterals: input.NoUnkeyedLiterals, Flags: input.Flags}, runtime.ErrInvalidLength + } + postIndex := iNdEx + msglen + if postIndex < 0 { + return protoiface.UnmarshalOutput{NoUnkeyedLiterals: input.NoUnkeyedLiterals, Flags: input.Flags}, runtime.ErrInvalidLength + } + if postIndex > l { + return protoiface.UnmarshalOutput{NoUnkeyedLiterals: input.NoUnkeyedLiterals, Flags: input.Flags}, io.ErrUnexpectedEOF + } + if x.Inner2 == nil { + x.Inner2 = &TestVersion3LoneNesting_Inner2{} + } + if err := options.Unmarshal(dAtA[iNdEx:postIndex], x.Inner2); err != nil { + return protoiface.UnmarshalOutput{NoUnkeyedLiterals: input.NoUnkeyedLiterals, Flags: input.Flags}, err + } + iNdEx = postIndex + default: + iNdEx = preIndex + skippy, err := runtime.Skip(dAtA[iNdEx:]) + if err != nil { + return protoiface.UnmarshalOutput{NoUnkeyedLiterals: input.NoUnkeyedLiterals, Flags: input.Flags}, err + } + if (skippy < 0) || (iNdEx+skippy) < 0 { + return protoiface.UnmarshalOutput{NoUnkeyedLiterals: input.NoUnkeyedLiterals, Flags: input.Flags}, runtime.ErrInvalidLength + } + if (iNdEx + skippy) > l { + return protoiface.UnmarshalOutput{NoUnkeyedLiterals: input.NoUnkeyedLiterals, Flags: input.Flags}, io.ErrUnexpectedEOF + } + if !options.DiscardUnknown { + x.unknownFields = append(x.unknownFields, dAtA[iNdEx:iNdEx+skippy]...) + } + iNdEx += skippy + } + } + + if iNdEx > l { + return protoiface.UnmarshalOutput{NoUnkeyedLiterals: input.NoUnkeyedLiterals, Flags: input.Flags}, io.ErrUnexpectedEOF + } + return protoiface.UnmarshalOutput{NoUnkeyedLiterals: input.NoUnkeyedLiterals, Flags: input.Flags}, nil + } + return &protoiface.Methods{ + NoUnkeyedLiterals: struct{}{}, + Flags: protoiface.SupportMarshalDeterministic | protoiface.SupportUnmarshalDiscardUnknown, + Size: size, + Marshal: marshal, + Unmarshal: unmarshal, + Merge: nil, + CheckInitialized: nil, + } +} + +var ( + md_TestVersion3LoneNesting_Inner1 protoreflect.MessageDescriptor + fd_TestVersion3LoneNesting_Inner1_id protoreflect.FieldDescriptor + fd_TestVersion3LoneNesting_Inner1_name protoreflect.FieldDescriptor + fd_TestVersion3LoneNesting_Inner1_inner protoreflect.FieldDescriptor +) + +func init() { + file_unknownproto_proto_init() + md_TestVersion3LoneNesting_Inner1 = File_unknownproto_proto.Messages().ByName("TestVersion3LoneNesting").Messages().ByName("Inner1") + fd_TestVersion3LoneNesting_Inner1_id = md_TestVersion3LoneNesting_Inner1.Fields().ByName("id") + fd_TestVersion3LoneNesting_Inner1_name = md_TestVersion3LoneNesting_Inner1.Fields().ByName("name") + fd_TestVersion3LoneNesting_Inner1_inner = md_TestVersion3LoneNesting_Inner1.Fields().ByName("inner") +} + +var _ protoreflect.Message = (*fastReflection_TestVersion3LoneNesting_Inner1)(nil) + +type fastReflection_TestVersion3LoneNesting_Inner1 TestVersion3LoneNesting_Inner1 + +func (x *TestVersion3LoneNesting_Inner1) ProtoReflect() protoreflect.Message { + return (*fastReflection_TestVersion3LoneNesting_Inner1)(x) +} + +func (x *TestVersion3LoneNesting_Inner1) slowProtoReflect() protoreflect.Message { + mi := &file_unknownproto_proto_msgTypes[25] + if protoimpl.UnsafeEnabled && x != nil { + ms := protoimpl.X.MessageStateOf(protoimpl.Pointer(x)) + if ms.LoadMessageInfo() == nil { + ms.StoreMessageInfo(mi) + } + return ms + } + return mi.MessageOf(x) +} + +var _fastReflection_TestVersion3LoneNesting_Inner1_messageType fastReflection_TestVersion3LoneNesting_Inner1_messageType +var _ protoreflect.MessageType = fastReflection_TestVersion3LoneNesting_Inner1_messageType{} + +type fastReflection_TestVersion3LoneNesting_Inner1_messageType struct{} + +func (x fastReflection_TestVersion3LoneNesting_Inner1_messageType) Zero() protoreflect.Message { + return (*fastReflection_TestVersion3LoneNesting_Inner1)(nil) +} +func (x fastReflection_TestVersion3LoneNesting_Inner1_messageType) New() protoreflect.Message { + return new(fastReflection_TestVersion3LoneNesting_Inner1) +} +func (x fastReflection_TestVersion3LoneNesting_Inner1_messageType) Descriptor() protoreflect.MessageDescriptor { + return md_TestVersion3LoneNesting_Inner1 +} + +// Descriptor returns message descriptor, which contains only the protobuf +// type information for the message. +func (x *fastReflection_TestVersion3LoneNesting_Inner1) Descriptor() protoreflect.MessageDescriptor { + return md_TestVersion3LoneNesting_Inner1 +} + +// Type returns the message type, which encapsulates both Go and protobuf +// type information. If the Go type information is not needed, +// it is recommended that the message descriptor be used instead. +func (x *fastReflection_TestVersion3LoneNesting_Inner1) Type() protoreflect.MessageType { + return _fastReflection_TestVersion3LoneNesting_Inner1_messageType +} + +// New returns a newly allocated and mutable empty message. +func (x *fastReflection_TestVersion3LoneNesting_Inner1) New() protoreflect.Message { + return new(fastReflection_TestVersion3LoneNesting_Inner1) +} + +// Interface unwraps the message reflection interface and +// returns the underlying ProtoMessage interface. +func (x *fastReflection_TestVersion3LoneNesting_Inner1) Interface() protoreflect.ProtoMessage { + return (*TestVersion3LoneNesting_Inner1)(x) +} + +// Range iterates over every populated field in an undefined order, +// calling f for each field descriptor and value encountered. +// Range returns immediately if f returns false. +// While iterating, mutating operations may only be performed +// on the current field descriptor. +func (x *fastReflection_TestVersion3LoneNesting_Inner1) Range(f func(protoreflect.FieldDescriptor, protoreflect.Value) bool) { + if x.Id != int64(0) { + value := protoreflect.ValueOfInt64(x.Id) + if !f(fd_TestVersion3LoneNesting_Inner1_id, value) { + return + } + } + if x.Name != "" { + value := protoreflect.ValueOfString(x.Name) + if !f(fd_TestVersion3LoneNesting_Inner1_name, value) { + return + } + } + if x.Inner != nil { + value := protoreflect.ValueOfMessage(x.Inner.ProtoReflect()) + if !f(fd_TestVersion3LoneNesting_Inner1_inner, value) { + return + } + } +} + +// Has reports whether a field is populated. +// +// Some fields have the property of nullability where it is possible to +// distinguish between the default value of a field and whether the field +// was explicitly populated with the default value. Singular message fields, +// member fields of a oneof, and proto2 scalar fields are nullable. Such +// fields are populated only if explicitly set. +// +// In other cases (aside from the nullable cases above), +// a proto3 scalar field is populated if it contains a non-zero value, and +// a repeated field is populated if it is non-empty. +func (x *fastReflection_TestVersion3LoneNesting_Inner1) Has(fd protoreflect.FieldDescriptor) bool { + switch fd.FullName() { + case "testpb.TestVersion3LoneNesting.Inner1.id": + return x.Id != int64(0) + case "testpb.TestVersion3LoneNesting.Inner1.name": + return x.Name != "" + case "testpb.TestVersion3LoneNesting.Inner1.inner": + return x.Inner != nil + default: + if fd.IsExtension() { + panic(fmt.Errorf("proto3 declared messages do not support extensions: testpb.TestVersion3LoneNesting.Inner1")) + } + panic(fmt.Errorf("message testpb.TestVersion3LoneNesting.Inner1 does not contain field %s", fd.FullName())) + } +} + +// Clear clears the field such that a subsequent Has call reports false. +// +// Clearing an extension field clears both the extension type and value +// associated with the given field number. +// +// Clear is a mutating operation and unsafe for concurrent use. +func (x *fastReflection_TestVersion3LoneNesting_Inner1) Clear(fd protoreflect.FieldDescriptor) { + switch fd.FullName() { + case "testpb.TestVersion3LoneNesting.Inner1.id": + x.Id = int64(0) + case "testpb.TestVersion3LoneNesting.Inner1.name": + x.Name = "" + case "testpb.TestVersion3LoneNesting.Inner1.inner": + x.Inner = nil + default: + if fd.IsExtension() { + panic(fmt.Errorf("proto3 declared messages do not support extensions: testpb.TestVersion3LoneNesting.Inner1")) + } + panic(fmt.Errorf("message testpb.TestVersion3LoneNesting.Inner1 does not contain field %s", fd.FullName())) + } +} + +// Get retrieves the value for a field. +// +// For unpopulated scalars, it returns the default value, where +// the default value of a bytes scalar is guaranteed to be a copy. +// For unpopulated composite types, it returns an empty, read-only view +// of the value; to obtain a mutable reference, use Mutable. +func (x *fastReflection_TestVersion3LoneNesting_Inner1) Get(descriptor protoreflect.FieldDescriptor) protoreflect.Value { + switch descriptor.FullName() { + case "testpb.TestVersion3LoneNesting.Inner1.id": + value := x.Id + return protoreflect.ValueOfInt64(value) + case "testpb.TestVersion3LoneNesting.Inner1.name": + value := x.Name + return protoreflect.ValueOfString(value) + case "testpb.TestVersion3LoneNesting.Inner1.inner": + value := x.Inner + return protoreflect.ValueOfMessage(value.ProtoReflect()) + default: + if descriptor.IsExtension() { + panic(fmt.Errorf("proto3 declared messages do not support extensions: testpb.TestVersion3LoneNesting.Inner1")) + } + panic(fmt.Errorf("message testpb.TestVersion3LoneNesting.Inner1 does not contain field %s", descriptor.FullName())) + } +} + +// Set stores the value for a field. +// +// For a field belonging to a oneof, it implicitly clears any other field +// that may be currently set within the same oneof. +// For extension fields, it implicitly stores the provided ExtensionType. +// When setting a composite type, it is unspecified whether the stored value +// aliases the source's memory in any way. If the composite value is an +// empty, read-only value, then it panics. +// +// Set is a mutating operation and unsafe for concurrent use. +func (x *fastReflection_TestVersion3LoneNesting_Inner1) Set(fd protoreflect.FieldDescriptor, value protoreflect.Value) { + switch fd.FullName() { + case "testpb.TestVersion3LoneNesting.Inner1.id": + x.Id = value.Int() + case "testpb.TestVersion3LoneNesting.Inner1.name": + x.Name = value.Interface().(string) + case "testpb.TestVersion3LoneNesting.Inner1.inner": + x.Inner = value.Message().Interface().(*TestVersion3LoneNesting_Inner1_InnerInner) + default: + if fd.IsExtension() { + panic(fmt.Errorf("proto3 declared messages do not support extensions: testpb.TestVersion3LoneNesting.Inner1")) + } + panic(fmt.Errorf("message testpb.TestVersion3LoneNesting.Inner1 does not contain field %s", fd.FullName())) + } +} + +// Mutable returns a mutable reference to a composite type. +// +// If the field is unpopulated, it may allocate a composite value. +// For a field belonging to a oneof, it implicitly clears any other field +// that may be currently set within the same oneof. +// For extension fields, it implicitly stores the provided ExtensionType +// if not already stored. +// It panics if the field does not contain a composite type. +// +// Mutable is a mutating operation and unsafe for concurrent use. +func (x *fastReflection_TestVersion3LoneNesting_Inner1) Mutable(fd protoreflect.FieldDescriptor) protoreflect.Value { + switch fd.FullName() { + case "testpb.TestVersion3LoneNesting.Inner1.inner": + if x.Inner == nil { + x.Inner = new(TestVersion3LoneNesting_Inner1_InnerInner) + } + return protoreflect.ValueOfMessage(x.Inner.ProtoReflect()) + case "testpb.TestVersion3LoneNesting.Inner1.id": + panic(fmt.Errorf("field id of message testpb.TestVersion3LoneNesting.Inner1 is not mutable")) + case "testpb.TestVersion3LoneNesting.Inner1.name": + panic(fmt.Errorf("field name of message testpb.TestVersion3LoneNesting.Inner1 is not mutable")) + default: + if fd.IsExtension() { + panic(fmt.Errorf("proto3 declared messages do not support extensions: testpb.TestVersion3LoneNesting.Inner1")) + } + panic(fmt.Errorf("message testpb.TestVersion3LoneNesting.Inner1 does not contain field %s", fd.FullName())) + } +} + +// NewField returns a new value that is assignable to the field +// for the given descriptor. For scalars, this returns the default value. +// For lists, maps, and messages, this returns a new, empty, mutable value. +func (x *fastReflection_TestVersion3LoneNesting_Inner1) NewField(fd protoreflect.FieldDescriptor) protoreflect.Value { + switch fd.FullName() { + case "testpb.TestVersion3LoneNesting.Inner1.id": + return protoreflect.ValueOfInt64(int64(0)) + case "testpb.TestVersion3LoneNesting.Inner1.name": + return protoreflect.ValueOfString("") + case "testpb.TestVersion3LoneNesting.Inner1.inner": + m := new(TestVersion3LoneNesting_Inner1_InnerInner) + return protoreflect.ValueOfMessage(m.ProtoReflect()) + default: + if fd.IsExtension() { + panic(fmt.Errorf("proto3 declared messages do not support extensions: testpb.TestVersion3LoneNesting.Inner1")) + } + panic(fmt.Errorf("message testpb.TestVersion3LoneNesting.Inner1 does not contain field %s", fd.FullName())) + } +} + +// WhichOneof reports which field within the oneof is populated, +// returning nil if none are populated. +// It panics if the oneof descriptor does not belong to this message. +func (x *fastReflection_TestVersion3LoneNesting_Inner1) WhichOneof(d protoreflect.OneofDescriptor) protoreflect.FieldDescriptor { + switch d.FullName() { + default: + panic(fmt.Errorf("%s is not a oneof field in testpb.TestVersion3LoneNesting.Inner1", d.FullName())) + } + panic("unreachable") +} + +// GetUnknown retrieves the entire list of unknown fields. +// The caller may only mutate the contents of the RawFields +// if the mutated bytes are stored back into the message with SetUnknown. +func (x *fastReflection_TestVersion3LoneNesting_Inner1) GetUnknown() protoreflect.RawFields { + return x.unknownFields +} + +// SetUnknown stores an entire list of unknown fields. +// The raw fields must be syntactically valid according to the wire format. +// An implementation may panic if this is not the case. +// Once stored, the caller must not mutate the content of the RawFields. +// An empty RawFields may be passed to clear the fields. +// +// SetUnknown is a mutating operation and unsafe for concurrent use. +func (x *fastReflection_TestVersion3LoneNesting_Inner1) SetUnknown(fields protoreflect.RawFields) { + x.unknownFields = fields +} + +// IsValid reports whether the message is valid. +// +// An invalid message is an empty, read-only value. +// +// An invalid message often corresponds to a nil pointer of the concrete +// message type, but the details are implementation dependent. +// Validity is not part of the protobuf data model, and may not +// be preserved in marshaling or other operations. +func (x *fastReflection_TestVersion3LoneNesting_Inner1) IsValid() bool { + return x != nil +} + +// ProtoMethods returns optional fastReflectionFeature-path implementations of various operations. +// This method may return nil. +// +// The returned methods type is identical to +// "google.golang.org/protobuf/runtime/protoiface".Methods. +// Consult the protoiface package documentation for details. +func (x *fastReflection_TestVersion3LoneNesting_Inner1) ProtoMethods() *protoiface.Methods { + size := func(input protoiface.SizeInput) protoiface.SizeOutput { + x := input.Message.Interface().(*TestVersion3LoneNesting_Inner1) + if x == nil { + return protoiface.SizeOutput{ + NoUnkeyedLiterals: input.NoUnkeyedLiterals, + Size: 0, + } + } + options := runtime.SizeInputToOptions(input) + _ = options + var n int + var l int + _ = l + if x.Id != 0 { + n += 1 + runtime.Sov(uint64(x.Id)) + } + l = len(x.Name) + if l > 0 { + n += 1 + l + runtime.Sov(uint64(l)) + } + if x.Inner != nil { + l = options.Size(x.Inner) + n += 1 + l + runtime.Sov(uint64(l)) + } + if x.unknownFields != nil { + n += len(x.unknownFields) + } + return protoiface.SizeOutput{ + NoUnkeyedLiterals: input.NoUnkeyedLiterals, + Size: n, + } + } + + marshal := func(input protoiface.MarshalInput) (protoiface.MarshalOutput, error) { + x := input.Message.Interface().(*TestVersion3LoneNesting_Inner1) + if x == nil { + return protoiface.MarshalOutput{ + NoUnkeyedLiterals: input.NoUnkeyedLiterals, + Buf: input.Buf, + }, nil + } + options := runtime.MarshalInputToOptions(input) + _ = options + size := options.Size(x) + dAtA := make([]byte, size) + i := len(dAtA) + _ = i + var l int + _ = l + if x.unknownFields != nil { + i -= len(x.unknownFields) + copy(dAtA[i:], x.unknownFields) + } + if x.Inner != nil { + encoded, err := options.Marshal(x.Inner) + if err != nil { + return protoiface.MarshalOutput{ + NoUnkeyedLiterals: input.NoUnkeyedLiterals, + Buf: input.Buf, + }, err + } + i -= len(encoded) + copy(dAtA[i:], encoded) + i = runtime.EncodeVarint(dAtA, i, uint64(len(encoded))) + i-- + dAtA[i] = 0x1a + } + if len(x.Name) > 0 { + i -= len(x.Name) + copy(dAtA[i:], x.Name) + i = runtime.EncodeVarint(dAtA, i, uint64(len(x.Name))) + i-- + dAtA[i] = 0x12 + } + if x.Id != 0 { + i = runtime.EncodeVarint(dAtA, i, uint64(x.Id)) + i-- + dAtA[i] = 0x8 + } + if input.Buf != nil { + input.Buf = append(input.Buf, dAtA...) + } else { + input.Buf = dAtA + } + return protoiface.MarshalOutput{ + NoUnkeyedLiterals: input.NoUnkeyedLiterals, + Buf: input.Buf, + }, nil + } + unmarshal := func(input protoiface.UnmarshalInput) (protoiface.UnmarshalOutput, error) { + x := input.Message.Interface().(*TestVersion3LoneNesting_Inner1) + if x == nil { + return protoiface.UnmarshalOutput{ + NoUnkeyedLiterals: input.NoUnkeyedLiterals, + Flags: input.Flags, + }, nil + } + options := runtime.UnmarshalInputToOptions(input) + _ = options + dAtA := input.Buf + l := len(dAtA) + iNdEx := 0 + for iNdEx < l { + preIndex := iNdEx + var wire uint64 + for shift := uint(0); ; shift += 7 { + if shift >= 64 { + return protoiface.UnmarshalOutput{NoUnkeyedLiterals: input.NoUnkeyedLiterals, Flags: input.Flags}, runtime.ErrIntOverflow + } + if iNdEx >= l { + return protoiface.UnmarshalOutput{NoUnkeyedLiterals: input.NoUnkeyedLiterals, Flags: input.Flags}, io.ErrUnexpectedEOF + } + b := dAtA[iNdEx] + iNdEx++ + wire |= uint64(b&0x7F) << shift + if b < 0x80 { + break + } + } + fieldNum := int32(wire >> 3) + wireType := int(wire & 0x7) + if wireType == 4 { + return protoiface.UnmarshalOutput{NoUnkeyedLiterals: input.NoUnkeyedLiterals, Flags: input.Flags}, fmt.Errorf("proto: TestVersion3LoneNesting_Inner1: wiretype end group for non-group") + } + if fieldNum <= 0 { + return protoiface.UnmarshalOutput{NoUnkeyedLiterals: input.NoUnkeyedLiterals, Flags: input.Flags}, fmt.Errorf("proto: TestVersion3LoneNesting_Inner1: illegal tag %d (wire type %d)", fieldNum, wire) + } + switch fieldNum { + case 1: + if wireType != 0 { + return protoiface.UnmarshalOutput{NoUnkeyedLiterals: input.NoUnkeyedLiterals, Flags: input.Flags}, fmt.Errorf("proto: wrong wireType = %d for field Id", wireType) + } + x.Id = 0 + for shift := uint(0); ; shift += 7 { + if shift >= 64 { + return protoiface.UnmarshalOutput{NoUnkeyedLiterals: input.NoUnkeyedLiterals, Flags: input.Flags}, runtime.ErrIntOverflow + } + if iNdEx >= l { + return protoiface.UnmarshalOutput{NoUnkeyedLiterals: input.NoUnkeyedLiterals, Flags: input.Flags}, io.ErrUnexpectedEOF + } + b := dAtA[iNdEx] + iNdEx++ + x.Id |= int64(b&0x7F) << shift + if b < 0x80 { + break + } + } + case 2: + if wireType != 2 { + return protoiface.UnmarshalOutput{NoUnkeyedLiterals: input.NoUnkeyedLiterals, Flags: input.Flags}, fmt.Errorf("proto: wrong wireType = %d for field Name", wireType) + } + var stringLen uint64 + for shift := uint(0); ; shift += 7 { + if shift >= 64 { + return protoiface.UnmarshalOutput{NoUnkeyedLiterals: input.NoUnkeyedLiterals, Flags: input.Flags}, runtime.ErrIntOverflow + } + if iNdEx >= l { + return protoiface.UnmarshalOutput{NoUnkeyedLiterals: input.NoUnkeyedLiterals, Flags: input.Flags}, io.ErrUnexpectedEOF + } + b := dAtA[iNdEx] + iNdEx++ + stringLen |= uint64(b&0x7F) << shift + if b < 0x80 { + break + } + } + intStringLen := int(stringLen) + if intStringLen < 0 { + return protoiface.UnmarshalOutput{NoUnkeyedLiterals: input.NoUnkeyedLiterals, Flags: input.Flags}, runtime.ErrInvalidLength + } + postIndex := iNdEx + intStringLen + if postIndex < 0 { + return protoiface.UnmarshalOutput{NoUnkeyedLiterals: input.NoUnkeyedLiterals, Flags: input.Flags}, runtime.ErrInvalidLength + } + if postIndex > l { + return protoiface.UnmarshalOutput{NoUnkeyedLiterals: input.NoUnkeyedLiterals, Flags: input.Flags}, io.ErrUnexpectedEOF + } + x.Name = string(dAtA[iNdEx:postIndex]) + iNdEx = postIndex + case 3: + if wireType != 2 { + return protoiface.UnmarshalOutput{NoUnkeyedLiterals: input.NoUnkeyedLiterals, Flags: input.Flags}, fmt.Errorf("proto: wrong wireType = %d for field Inner", wireType) + } + var msglen int + for shift := uint(0); ; shift += 7 { + if shift >= 64 { + return protoiface.UnmarshalOutput{NoUnkeyedLiterals: input.NoUnkeyedLiterals, Flags: input.Flags}, runtime.ErrIntOverflow + } + if iNdEx >= l { + return protoiface.UnmarshalOutput{NoUnkeyedLiterals: input.NoUnkeyedLiterals, Flags: input.Flags}, io.ErrUnexpectedEOF + } + b := dAtA[iNdEx] + iNdEx++ + msglen |= int(b&0x7F) << shift + if b < 0x80 { + break + } + } + if msglen < 0 { + return protoiface.UnmarshalOutput{NoUnkeyedLiterals: input.NoUnkeyedLiterals, Flags: input.Flags}, runtime.ErrInvalidLength + } + postIndex := iNdEx + msglen + if postIndex < 0 { + return protoiface.UnmarshalOutput{NoUnkeyedLiterals: input.NoUnkeyedLiterals, Flags: input.Flags}, runtime.ErrInvalidLength + } + if postIndex > l { + return protoiface.UnmarshalOutput{NoUnkeyedLiterals: input.NoUnkeyedLiterals, Flags: input.Flags}, io.ErrUnexpectedEOF + } + if x.Inner == nil { + x.Inner = &TestVersion3LoneNesting_Inner1_InnerInner{} + } + if err := options.Unmarshal(dAtA[iNdEx:postIndex], x.Inner); err != nil { + return protoiface.UnmarshalOutput{NoUnkeyedLiterals: input.NoUnkeyedLiterals, Flags: input.Flags}, err + } + iNdEx = postIndex + default: + iNdEx = preIndex + skippy, err := runtime.Skip(dAtA[iNdEx:]) + if err != nil { + return protoiface.UnmarshalOutput{NoUnkeyedLiterals: input.NoUnkeyedLiterals, Flags: input.Flags}, err + } + if (skippy < 0) || (iNdEx+skippy) < 0 { + return protoiface.UnmarshalOutput{NoUnkeyedLiterals: input.NoUnkeyedLiterals, Flags: input.Flags}, runtime.ErrInvalidLength + } + if (iNdEx + skippy) > l { + return protoiface.UnmarshalOutput{NoUnkeyedLiterals: input.NoUnkeyedLiterals, Flags: input.Flags}, io.ErrUnexpectedEOF + } + if !options.DiscardUnknown { + x.unknownFields = append(x.unknownFields, dAtA[iNdEx:iNdEx+skippy]...) + } + iNdEx += skippy + } + } + + if iNdEx > l { + return protoiface.UnmarshalOutput{NoUnkeyedLiterals: input.NoUnkeyedLiterals, Flags: input.Flags}, io.ErrUnexpectedEOF + } + return protoiface.UnmarshalOutput{NoUnkeyedLiterals: input.NoUnkeyedLiterals, Flags: input.Flags}, nil + } + return &protoiface.Methods{ + NoUnkeyedLiterals: struct{}{}, + Flags: protoiface.SupportMarshalDeterministic | protoiface.SupportUnmarshalDiscardUnknown, + Size: size, + Marshal: marshal, + Unmarshal: unmarshal, + Merge: nil, + CheckInitialized: nil, + } +} + +var ( + md_TestVersion3LoneNesting_Inner1_InnerInner protoreflect.MessageDescriptor + fd_TestVersion3LoneNesting_Inner1_InnerInner_id protoreflect.FieldDescriptor + fd_TestVersion3LoneNesting_Inner1_InnerInner_city protoreflect.FieldDescriptor +) + +func init() { + file_unknownproto_proto_init() + md_TestVersion3LoneNesting_Inner1_InnerInner = File_unknownproto_proto.Messages().ByName("TestVersion3LoneNesting").Messages().ByName("Inner1").Messages().ByName("InnerInner") + fd_TestVersion3LoneNesting_Inner1_InnerInner_id = md_TestVersion3LoneNesting_Inner1_InnerInner.Fields().ByName("id") + fd_TestVersion3LoneNesting_Inner1_InnerInner_city = md_TestVersion3LoneNesting_Inner1_InnerInner.Fields().ByName("city") +} + +var _ protoreflect.Message = (*fastReflection_TestVersion3LoneNesting_Inner1_InnerInner)(nil) + +type fastReflection_TestVersion3LoneNesting_Inner1_InnerInner TestVersion3LoneNesting_Inner1_InnerInner + +func (x *TestVersion3LoneNesting_Inner1_InnerInner) ProtoReflect() protoreflect.Message { + return (*fastReflection_TestVersion3LoneNesting_Inner1_InnerInner)(x) +} + +func (x *TestVersion3LoneNesting_Inner1_InnerInner) slowProtoReflect() protoreflect.Message { + mi := &file_unknownproto_proto_msgTypes[27] + if protoimpl.UnsafeEnabled && x != nil { + ms := protoimpl.X.MessageStateOf(protoimpl.Pointer(x)) + if ms.LoadMessageInfo() == nil { + ms.StoreMessageInfo(mi) + } + return ms + } + return mi.MessageOf(x) +} + +var _fastReflection_TestVersion3LoneNesting_Inner1_InnerInner_messageType fastReflection_TestVersion3LoneNesting_Inner1_InnerInner_messageType +var _ protoreflect.MessageType = fastReflection_TestVersion3LoneNesting_Inner1_InnerInner_messageType{} + +type fastReflection_TestVersion3LoneNesting_Inner1_InnerInner_messageType struct{} + +func (x fastReflection_TestVersion3LoneNesting_Inner1_InnerInner_messageType) Zero() protoreflect.Message { + return (*fastReflection_TestVersion3LoneNesting_Inner1_InnerInner)(nil) +} +func (x fastReflection_TestVersion3LoneNesting_Inner1_InnerInner_messageType) New() protoreflect.Message { + return new(fastReflection_TestVersion3LoneNesting_Inner1_InnerInner) +} +func (x fastReflection_TestVersion3LoneNesting_Inner1_InnerInner_messageType) Descriptor() protoreflect.MessageDescriptor { + return md_TestVersion3LoneNesting_Inner1_InnerInner +} + +// Descriptor returns message descriptor, which contains only the protobuf +// type information for the message. +func (x *fastReflection_TestVersion3LoneNesting_Inner1_InnerInner) Descriptor() protoreflect.MessageDescriptor { + return md_TestVersion3LoneNesting_Inner1_InnerInner +} + +// Type returns the message type, which encapsulates both Go and protobuf +// type information. If the Go type information is not needed, +// it is recommended that the message descriptor be used instead. +func (x *fastReflection_TestVersion3LoneNesting_Inner1_InnerInner) Type() protoreflect.MessageType { + return _fastReflection_TestVersion3LoneNesting_Inner1_InnerInner_messageType +} + +// New returns a newly allocated and mutable empty message. +func (x *fastReflection_TestVersion3LoneNesting_Inner1_InnerInner) New() protoreflect.Message { + return new(fastReflection_TestVersion3LoneNesting_Inner1_InnerInner) +} + +// Interface unwraps the message reflection interface and +// returns the underlying ProtoMessage interface. +func (x *fastReflection_TestVersion3LoneNesting_Inner1_InnerInner) Interface() protoreflect.ProtoMessage { + return (*TestVersion3LoneNesting_Inner1_InnerInner)(x) +} + +// Range iterates over every populated field in an undefined order, +// calling f for each field descriptor and value encountered. +// Range returns immediately if f returns false. +// While iterating, mutating operations may only be performed +// on the current field descriptor. +func (x *fastReflection_TestVersion3LoneNesting_Inner1_InnerInner) Range(f func(protoreflect.FieldDescriptor, protoreflect.Value) bool) { + if x.Id != "" { + value := protoreflect.ValueOfString(x.Id) + if !f(fd_TestVersion3LoneNesting_Inner1_InnerInner_id, value) { + return + } + } + if x.City != "" { + value := protoreflect.ValueOfString(x.City) + if !f(fd_TestVersion3LoneNesting_Inner1_InnerInner_city, value) { + return + } + } +} + +// Has reports whether a field is populated. +// +// Some fields have the property of nullability where it is possible to +// distinguish between the default value of a field and whether the field +// was explicitly populated with the default value. Singular message fields, +// member fields of a oneof, and proto2 scalar fields are nullable. Such +// fields are populated only if explicitly set. +// +// In other cases (aside from the nullable cases above), +// a proto3 scalar field is populated if it contains a non-zero value, and +// a repeated field is populated if it is non-empty. +func (x *fastReflection_TestVersion3LoneNesting_Inner1_InnerInner) Has(fd protoreflect.FieldDescriptor) bool { + switch fd.FullName() { + case "testpb.TestVersion3LoneNesting.Inner1.InnerInner.id": + return x.Id != "" + case "testpb.TestVersion3LoneNesting.Inner1.InnerInner.city": + return x.City != "" + default: + if fd.IsExtension() { + panic(fmt.Errorf("proto3 declared messages do not support extensions: testpb.TestVersion3LoneNesting.Inner1.InnerInner")) + } + panic(fmt.Errorf("message testpb.TestVersion3LoneNesting.Inner1.InnerInner does not contain field %s", fd.FullName())) + } +} + +// Clear clears the field such that a subsequent Has call reports false. +// +// Clearing an extension field clears both the extension type and value +// associated with the given field number. +// +// Clear is a mutating operation and unsafe for concurrent use. +func (x *fastReflection_TestVersion3LoneNesting_Inner1_InnerInner) Clear(fd protoreflect.FieldDescriptor) { + switch fd.FullName() { + case "testpb.TestVersion3LoneNesting.Inner1.InnerInner.id": + x.Id = "" + case "testpb.TestVersion3LoneNesting.Inner1.InnerInner.city": + x.City = "" + default: + if fd.IsExtension() { + panic(fmt.Errorf("proto3 declared messages do not support extensions: testpb.TestVersion3LoneNesting.Inner1.InnerInner")) + } + panic(fmt.Errorf("message testpb.TestVersion3LoneNesting.Inner1.InnerInner does not contain field %s", fd.FullName())) + } +} + +// Get retrieves the value for a field. +// +// For unpopulated scalars, it returns the default value, where +// the default value of a bytes scalar is guaranteed to be a copy. +// For unpopulated composite types, it returns an empty, read-only view +// of the value; to obtain a mutable reference, use Mutable. +func (x *fastReflection_TestVersion3LoneNesting_Inner1_InnerInner) Get(descriptor protoreflect.FieldDescriptor) protoreflect.Value { + switch descriptor.FullName() { + case "testpb.TestVersion3LoneNesting.Inner1.InnerInner.id": + value := x.Id + return protoreflect.ValueOfString(value) + case "testpb.TestVersion3LoneNesting.Inner1.InnerInner.city": + value := x.City + return protoreflect.ValueOfString(value) + default: + if descriptor.IsExtension() { + panic(fmt.Errorf("proto3 declared messages do not support extensions: testpb.TestVersion3LoneNesting.Inner1.InnerInner")) + } + panic(fmt.Errorf("message testpb.TestVersion3LoneNesting.Inner1.InnerInner does not contain field %s", descriptor.FullName())) + } +} + +// Set stores the value for a field. +// +// For a field belonging to a oneof, it implicitly clears any other field +// that may be currently set within the same oneof. +// For extension fields, it implicitly stores the provided ExtensionType. +// When setting a composite type, it is unspecified whether the stored value +// aliases the source's memory in any way. If the composite value is an +// empty, read-only value, then it panics. +// +// Set is a mutating operation and unsafe for concurrent use. +func (x *fastReflection_TestVersion3LoneNesting_Inner1_InnerInner) Set(fd protoreflect.FieldDescriptor, value protoreflect.Value) { + switch fd.FullName() { + case "testpb.TestVersion3LoneNesting.Inner1.InnerInner.id": + x.Id = value.Interface().(string) + case "testpb.TestVersion3LoneNesting.Inner1.InnerInner.city": + x.City = value.Interface().(string) + default: + if fd.IsExtension() { + panic(fmt.Errorf("proto3 declared messages do not support extensions: testpb.TestVersion3LoneNesting.Inner1.InnerInner")) + } + panic(fmt.Errorf("message testpb.TestVersion3LoneNesting.Inner1.InnerInner does not contain field %s", fd.FullName())) + } +} + +// Mutable returns a mutable reference to a composite type. +// +// If the field is unpopulated, it may allocate a composite value. +// For a field belonging to a oneof, it implicitly clears any other field +// that may be currently set within the same oneof. +// For extension fields, it implicitly stores the provided ExtensionType +// if not already stored. +// It panics if the field does not contain a composite type. +// +// Mutable is a mutating operation and unsafe for concurrent use. +func (x *fastReflection_TestVersion3LoneNesting_Inner1_InnerInner) Mutable(fd protoreflect.FieldDescriptor) protoreflect.Value { + switch fd.FullName() { + case "testpb.TestVersion3LoneNesting.Inner1.InnerInner.id": + panic(fmt.Errorf("field id of message testpb.TestVersion3LoneNesting.Inner1.InnerInner is not mutable")) + case "testpb.TestVersion3LoneNesting.Inner1.InnerInner.city": + panic(fmt.Errorf("field city of message testpb.TestVersion3LoneNesting.Inner1.InnerInner is not mutable")) + default: + if fd.IsExtension() { + panic(fmt.Errorf("proto3 declared messages do not support extensions: testpb.TestVersion3LoneNesting.Inner1.InnerInner")) + } + panic(fmt.Errorf("message testpb.TestVersion3LoneNesting.Inner1.InnerInner does not contain field %s", fd.FullName())) + } +} + +// NewField returns a new value that is assignable to the field +// for the given descriptor. For scalars, this returns the default value. +// For lists, maps, and messages, this returns a new, empty, mutable value. +func (x *fastReflection_TestVersion3LoneNesting_Inner1_InnerInner) NewField(fd protoreflect.FieldDescriptor) protoreflect.Value { + switch fd.FullName() { + case "testpb.TestVersion3LoneNesting.Inner1.InnerInner.id": + return protoreflect.ValueOfString("") + case "testpb.TestVersion3LoneNesting.Inner1.InnerInner.city": + return protoreflect.ValueOfString("") + default: + if fd.IsExtension() { + panic(fmt.Errorf("proto3 declared messages do not support extensions: testpb.TestVersion3LoneNesting.Inner1.InnerInner")) + } + panic(fmt.Errorf("message testpb.TestVersion3LoneNesting.Inner1.InnerInner does not contain field %s", fd.FullName())) + } +} + +// WhichOneof reports which field within the oneof is populated, +// returning nil if none are populated. +// It panics if the oneof descriptor does not belong to this message. +func (x *fastReflection_TestVersion3LoneNesting_Inner1_InnerInner) WhichOneof(d protoreflect.OneofDescriptor) protoreflect.FieldDescriptor { + switch d.FullName() { + default: + panic(fmt.Errorf("%s is not a oneof field in testpb.TestVersion3LoneNesting.Inner1.InnerInner", d.FullName())) + } + panic("unreachable") +} + +// GetUnknown retrieves the entire list of unknown fields. +// The caller may only mutate the contents of the RawFields +// if the mutated bytes are stored back into the message with SetUnknown. +func (x *fastReflection_TestVersion3LoneNesting_Inner1_InnerInner) GetUnknown() protoreflect.RawFields { + return x.unknownFields +} + +// SetUnknown stores an entire list of unknown fields. +// The raw fields must be syntactically valid according to the wire format. +// An implementation may panic if this is not the case. +// Once stored, the caller must not mutate the content of the RawFields. +// An empty RawFields may be passed to clear the fields. +// +// SetUnknown is a mutating operation and unsafe for concurrent use. +func (x *fastReflection_TestVersion3LoneNesting_Inner1_InnerInner) SetUnknown(fields protoreflect.RawFields) { + x.unknownFields = fields +} + +// IsValid reports whether the message is valid. +// +// An invalid message is an empty, read-only value. +// +// An invalid message often corresponds to a nil pointer of the concrete +// message type, but the details are implementation dependent. +// Validity is not part of the protobuf data model, and may not +// be preserved in marshaling or other operations. +func (x *fastReflection_TestVersion3LoneNesting_Inner1_InnerInner) IsValid() bool { + return x != nil +} + +// ProtoMethods returns optional fastReflectionFeature-path implementations of various operations. +// This method may return nil. +// +// The returned methods type is identical to +// "google.golang.org/protobuf/runtime/protoiface".Methods. +// Consult the protoiface package documentation for details. +func (x *fastReflection_TestVersion3LoneNesting_Inner1_InnerInner) ProtoMethods() *protoiface.Methods { + size := func(input protoiface.SizeInput) protoiface.SizeOutput { + x := input.Message.Interface().(*TestVersion3LoneNesting_Inner1_InnerInner) + if x == nil { + return protoiface.SizeOutput{ + NoUnkeyedLiterals: input.NoUnkeyedLiterals, + Size: 0, + } + } + options := runtime.SizeInputToOptions(input) + _ = options + var n int + var l int + _ = l + l = len(x.Id) + if l > 0 { + n += 1 + l + runtime.Sov(uint64(l)) + } + l = len(x.City) + if l > 0 { + n += 1 + l + runtime.Sov(uint64(l)) + } + if x.unknownFields != nil { + n += len(x.unknownFields) + } + return protoiface.SizeOutput{ + NoUnkeyedLiterals: input.NoUnkeyedLiterals, + Size: n, + } + } + + marshal := func(input protoiface.MarshalInput) (protoiface.MarshalOutput, error) { + x := input.Message.Interface().(*TestVersion3LoneNesting_Inner1_InnerInner) + if x == nil { + return protoiface.MarshalOutput{ + NoUnkeyedLiterals: input.NoUnkeyedLiterals, + Buf: input.Buf, + }, nil + } + options := runtime.MarshalInputToOptions(input) + _ = options + size := options.Size(x) + dAtA := make([]byte, size) + i := len(dAtA) + _ = i + var l int + _ = l + if x.unknownFields != nil { + i -= len(x.unknownFields) + copy(dAtA[i:], x.unknownFields) + } + if len(x.City) > 0 { + i -= len(x.City) + copy(dAtA[i:], x.City) + i = runtime.EncodeVarint(dAtA, i, uint64(len(x.City))) + i-- + dAtA[i] = 0x12 + } + if len(x.Id) > 0 { + i -= len(x.Id) + copy(dAtA[i:], x.Id) + i = runtime.EncodeVarint(dAtA, i, uint64(len(x.Id))) + i-- + dAtA[i] = 0xa + } + if input.Buf != nil { + input.Buf = append(input.Buf, dAtA...) + } else { + input.Buf = dAtA + } + return protoiface.MarshalOutput{ + NoUnkeyedLiterals: input.NoUnkeyedLiterals, + Buf: input.Buf, + }, nil + } + unmarshal := func(input protoiface.UnmarshalInput) (protoiface.UnmarshalOutput, error) { + x := input.Message.Interface().(*TestVersion3LoneNesting_Inner1_InnerInner) + if x == nil { + return protoiface.UnmarshalOutput{ + NoUnkeyedLiterals: input.NoUnkeyedLiterals, + Flags: input.Flags, + }, nil + } + options := runtime.UnmarshalInputToOptions(input) + _ = options + dAtA := input.Buf + l := len(dAtA) + iNdEx := 0 + for iNdEx < l { + preIndex := iNdEx + var wire uint64 + for shift := uint(0); ; shift += 7 { + if shift >= 64 { + return protoiface.UnmarshalOutput{NoUnkeyedLiterals: input.NoUnkeyedLiterals, Flags: input.Flags}, runtime.ErrIntOverflow + } + if iNdEx >= l { + return protoiface.UnmarshalOutput{NoUnkeyedLiterals: input.NoUnkeyedLiterals, Flags: input.Flags}, io.ErrUnexpectedEOF + } + b := dAtA[iNdEx] + iNdEx++ + wire |= uint64(b&0x7F) << shift + if b < 0x80 { + break + } + } + fieldNum := int32(wire >> 3) + wireType := int(wire & 0x7) + if wireType == 4 { + return protoiface.UnmarshalOutput{NoUnkeyedLiterals: input.NoUnkeyedLiterals, Flags: input.Flags}, fmt.Errorf("proto: TestVersion3LoneNesting_Inner1_InnerInner: wiretype end group for non-group") + } + if fieldNum <= 0 { + return protoiface.UnmarshalOutput{NoUnkeyedLiterals: input.NoUnkeyedLiterals, Flags: input.Flags}, fmt.Errorf("proto: TestVersion3LoneNesting_Inner1_InnerInner: illegal tag %d (wire type %d)", fieldNum, wire) + } + switch fieldNum { + case 1: + if wireType != 2 { + return protoiface.UnmarshalOutput{NoUnkeyedLiterals: input.NoUnkeyedLiterals, Flags: input.Flags}, fmt.Errorf("proto: wrong wireType = %d for field Id", wireType) + } + var stringLen uint64 + for shift := uint(0); ; shift += 7 { + if shift >= 64 { + return protoiface.UnmarshalOutput{NoUnkeyedLiterals: input.NoUnkeyedLiterals, Flags: input.Flags}, runtime.ErrIntOverflow + } + if iNdEx >= l { + return protoiface.UnmarshalOutput{NoUnkeyedLiterals: input.NoUnkeyedLiterals, Flags: input.Flags}, io.ErrUnexpectedEOF + } + b := dAtA[iNdEx] + iNdEx++ + stringLen |= uint64(b&0x7F) << shift + if b < 0x80 { + break + } + } + intStringLen := int(stringLen) + if intStringLen < 0 { + return protoiface.UnmarshalOutput{NoUnkeyedLiterals: input.NoUnkeyedLiterals, Flags: input.Flags}, runtime.ErrInvalidLength + } + postIndex := iNdEx + intStringLen + if postIndex < 0 { + return protoiface.UnmarshalOutput{NoUnkeyedLiterals: input.NoUnkeyedLiterals, Flags: input.Flags}, runtime.ErrInvalidLength + } + if postIndex > l { + return protoiface.UnmarshalOutput{NoUnkeyedLiterals: input.NoUnkeyedLiterals, Flags: input.Flags}, io.ErrUnexpectedEOF + } + x.Id = string(dAtA[iNdEx:postIndex]) + iNdEx = postIndex + case 2: + if wireType != 2 { + return protoiface.UnmarshalOutput{NoUnkeyedLiterals: input.NoUnkeyedLiterals, Flags: input.Flags}, fmt.Errorf("proto: wrong wireType = %d for field City", wireType) + } + var stringLen uint64 + for shift := uint(0); ; shift += 7 { + if shift >= 64 { + return protoiface.UnmarshalOutput{NoUnkeyedLiterals: input.NoUnkeyedLiterals, Flags: input.Flags}, runtime.ErrIntOverflow + } + if iNdEx >= l { + return protoiface.UnmarshalOutput{NoUnkeyedLiterals: input.NoUnkeyedLiterals, Flags: input.Flags}, io.ErrUnexpectedEOF + } + b := dAtA[iNdEx] + iNdEx++ + stringLen |= uint64(b&0x7F) << shift + if b < 0x80 { + break + } + } + intStringLen := int(stringLen) + if intStringLen < 0 { + return protoiface.UnmarshalOutput{NoUnkeyedLiterals: input.NoUnkeyedLiterals, Flags: input.Flags}, runtime.ErrInvalidLength + } + postIndex := iNdEx + intStringLen + if postIndex < 0 { + return protoiface.UnmarshalOutput{NoUnkeyedLiterals: input.NoUnkeyedLiterals, Flags: input.Flags}, runtime.ErrInvalidLength + } + if postIndex > l { + return protoiface.UnmarshalOutput{NoUnkeyedLiterals: input.NoUnkeyedLiterals, Flags: input.Flags}, io.ErrUnexpectedEOF + } + x.City = string(dAtA[iNdEx:postIndex]) + iNdEx = postIndex + default: + iNdEx = preIndex + skippy, err := runtime.Skip(dAtA[iNdEx:]) + if err != nil { + return protoiface.UnmarshalOutput{NoUnkeyedLiterals: input.NoUnkeyedLiterals, Flags: input.Flags}, err + } + if (skippy < 0) || (iNdEx+skippy) < 0 { + return protoiface.UnmarshalOutput{NoUnkeyedLiterals: input.NoUnkeyedLiterals, Flags: input.Flags}, runtime.ErrInvalidLength + } + if (iNdEx + skippy) > l { + return protoiface.UnmarshalOutput{NoUnkeyedLiterals: input.NoUnkeyedLiterals, Flags: input.Flags}, io.ErrUnexpectedEOF + } + if !options.DiscardUnknown { + x.unknownFields = append(x.unknownFields, dAtA[iNdEx:iNdEx+skippy]...) + } + iNdEx += skippy + } + } + + if iNdEx > l { + return protoiface.UnmarshalOutput{NoUnkeyedLiterals: input.NoUnkeyedLiterals, Flags: input.Flags}, io.ErrUnexpectedEOF + } + return protoiface.UnmarshalOutput{NoUnkeyedLiterals: input.NoUnkeyedLiterals, Flags: input.Flags}, nil + } + return &protoiface.Methods{ + NoUnkeyedLiterals: struct{}{}, + Flags: protoiface.SupportMarshalDeterministic | protoiface.SupportUnmarshalDiscardUnknown, + Size: size, + Marshal: marshal, + Unmarshal: unmarshal, + Merge: nil, + CheckInitialized: nil, + } +} + +var ( + md_TestVersion3LoneNesting_Inner2 protoreflect.MessageDescriptor + fd_TestVersion3LoneNesting_Inner2_id protoreflect.FieldDescriptor + fd_TestVersion3LoneNesting_Inner2_country protoreflect.FieldDescriptor + fd_TestVersion3LoneNesting_Inner2_inner protoreflect.FieldDescriptor +) + +func init() { + file_unknownproto_proto_init() + md_TestVersion3LoneNesting_Inner2 = File_unknownproto_proto.Messages().ByName("TestVersion3LoneNesting").Messages().ByName("Inner2") + fd_TestVersion3LoneNesting_Inner2_id = md_TestVersion3LoneNesting_Inner2.Fields().ByName("id") + fd_TestVersion3LoneNesting_Inner2_country = md_TestVersion3LoneNesting_Inner2.Fields().ByName("country") + fd_TestVersion3LoneNesting_Inner2_inner = md_TestVersion3LoneNesting_Inner2.Fields().ByName("inner") +} + +var _ protoreflect.Message = (*fastReflection_TestVersion3LoneNesting_Inner2)(nil) + +type fastReflection_TestVersion3LoneNesting_Inner2 TestVersion3LoneNesting_Inner2 + +func (x *TestVersion3LoneNesting_Inner2) ProtoReflect() protoreflect.Message { + return (*fastReflection_TestVersion3LoneNesting_Inner2)(x) +} + +func (x *TestVersion3LoneNesting_Inner2) slowProtoReflect() protoreflect.Message { + mi := &file_unknownproto_proto_msgTypes[26] + if protoimpl.UnsafeEnabled && x != nil { + ms := protoimpl.X.MessageStateOf(protoimpl.Pointer(x)) + if ms.LoadMessageInfo() == nil { + ms.StoreMessageInfo(mi) + } + return ms + } + return mi.MessageOf(x) +} + +var _fastReflection_TestVersion3LoneNesting_Inner2_messageType fastReflection_TestVersion3LoneNesting_Inner2_messageType +var _ protoreflect.MessageType = fastReflection_TestVersion3LoneNesting_Inner2_messageType{} + +type fastReflection_TestVersion3LoneNesting_Inner2_messageType struct{} + +func (x fastReflection_TestVersion3LoneNesting_Inner2_messageType) Zero() protoreflect.Message { + return (*fastReflection_TestVersion3LoneNesting_Inner2)(nil) +} +func (x fastReflection_TestVersion3LoneNesting_Inner2_messageType) New() protoreflect.Message { + return new(fastReflection_TestVersion3LoneNesting_Inner2) +} +func (x fastReflection_TestVersion3LoneNesting_Inner2_messageType) Descriptor() protoreflect.MessageDescriptor { + return md_TestVersion3LoneNesting_Inner2 +} + +// Descriptor returns message descriptor, which contains only the protobuf +// type information for the message. +func (x *fastReflection_TestVersion3LoneNesting_Inner2) Descriptor() protoreflect.MessageDescriptor { + return md_TestVersion3LoneNesting_Inner2 +} + +// Type returns the message type, which encapsulates both Go and protobuf +// type information. If the Go type information is not needed, +// it is recommended that the message descriptor be used instead. +func (x *fastReflection_TestVersion3LoneNesting_Inner2) Type() protoreflect.MessageType { + return _fastReflection_TestVersion3LoneNesting_Inner2_messageType +} + +// New returns a newly allocated and mutable empty message. +func (x *fastReflection_TestVersion3LoneNesting_Inner2) New() protoreflect.Message { + return new(fastReflection_TestVersion3LoneNesting_Inner2) +} + +// Interface unwraps the message reflection interface and +// returns the underlying ProtoMessage interface. +func (x *fastReflection_TestVersion3LoneNesting_Inner2) Interface() protoreflect.ProtoMessage { + return (*TestVersion3LoneNesting_Inner2)(x) +} + +// Range iterates over every populated field in an undefined order, +// calling f for each field descriptor and value encountered. +// Range returns immediately if f returns false. +// While iterating, mutating operations may only be performed +// on the current field descriptor. +func (x *fastReflection_TestVersion3LoneNesting_Inner2) Range(f func(protoreflect.FieldDescriptor, protoreflect.Value) bool) { + if x.Id != "" { + value := protoreflect.ValueOfString(x.Id) + if !f(fd_TestVersion3LoneNesting_Inner2_id, value) { + return + } + } + if x.Country != "" { + value := protoreflect.ValueOfString(x.Country) + if !f(fd_TestVersion3LoneNesting_Inner2_country, value) { + return + } + } + if x.Inner != nil { + value := protoreflect.ValueOfMessage(x.Inner.ProtoReflect()) + if !f(fd_TestVersion3LoneNesting_Inner2_inner, value) { + return + } + } +} + +// Has reports whether a field is populated. +// +// Some fields have the property of nullability where it is possible to +// distinguish between the default value of a field and whether the field +// was explicitly populated with the default value. Singular message fields, +// member fields of a oneof, and proto2 scalar fields are nullable. Such +// fields are populated only if explicitly set. +// +// In other cases (aside from the nullable cases above), +// a proto3 scalar field is populated if it contains a non-zero value, and +// a repeated field is populated if it is non-empty. +func (x *fastReflection_TestVersion3LoneNesting_Inner2) Has(fd protoreflect.FieldDescriptor) bool { + switch fd.FullName() { + case "testpb.TestVersion3LoneNesting.Inner2.id": + return x.Id != "" + case "testpb.TestVersion3LoneNesting.Inner2.country": + return x.Country != "" + case "testpb.TestVersion3LoneNesting.Inner2.inner": + return x.Inner != nil + default: + if fd.IsExtension() { + panic(fmt.Errorf("proto3 declared messages do not support extensions: testpb.TestVersion3LoneNesting.Inner2")) + } + panic(fmt.Errorf("message testpb.TestVersion3LoneNesting.Inner2 does not contain field %s", fd.FullName())) + } +} + +// Clear clears the field such that a subsequent Has call reports false. +// +// Clearing an extension field clears both the extension type and value +// associated with the given field number. +// +// Clear is a mutating operation and unsafe for concurrent use. +func (x *fastReflection_TestVersion3LoneNesting_Inner2) Clear(fd protoreflect.FieldDescriptor) { + switch fd.FullName() { + case "testpb.TestVersion3LoneNesting.Inner2.id": + x.Id = "" + case "testpb.TestVersion3LoneNesting.Inner2.country": + x.Country = "" + case "testpb.TestVersion3LoneNesting.Inner2.inner": + x.Inner = nil + default: + if fd.IsExtension() { + panic(fmt.Errorf("proto3 declared messages do not support extensions: testpb.TestVersion3LoneNesting.Inner2")) + } + panic(fmt.Errorf("message testpb.TestVersion3LoneNesting.Inner2 does not contain field %s", fd.FullName())) + } +} + +// Get retrieves the value for a field. +// +// For unpopulated scalars, it returns the default value, where +// the default value of a bytes scalar is guaranteed to be a copy. +// For unpopulated composite types, it returns an empty, read-only view +// of the value; to obtain a mutable reference, use Mutable. +func (x *fastReflection_TestVersion3LoneNesting_Inner2) Get(descriptor protoreflect.FieldDescriptor) protoreflect.Value { + switch descriptor.FullName() { + case "testpb.TestVersion3LoneNesting.Inner2.id": + value := x.Id + return protoreflect.ValueOfString(value) + case "testpb.TestVersion3LoneNesting.Inner2.country": + value := x.Country + return protoreflect.ValueOfString(value) + case "testpb.TestVersion3LoneNesting.Inner2.inner": + value := x.Inner + return protoreflect.ValueOfMessage(value.ProtoReflect()) + default: + if descriptor.IsExtension() { + panic(fmt.Errorf("proto3 declared messages do not support extensions: testpb.TestVersion3LoneNesting.Inner2")) + } + panic(fmt.Errorf("message testpb.TestVersion3LoneNesting.Inner2 does not contain field %s", descriptor.FullName())) + } +} + +// Set stores the value for a field. +// +// For a field belonging to a oneof, it implicitly clears any other field +// that may be currently set within the same oneof. +// For extension fields, it implicitly stores the provided ExtensionType. +// When setting a composite type, it is unspecified whether the stored value +// aliases the source's memory in any way. If the composite value is an +// empty, read-only value, then it panics. +// +// Set is a mutating operation and unsafe for concurrent use. +func (x *fastReflection_TestVersion3LoneNesting_Inner2) Set(fd protoreflect.FieldDescriptor, value protoreflect.Value) { + switch fd.FullName() { + case "testpb.TestVersion3LoneNesting.Inner2.id": + x.Id = value.Interface().(string) + case "testpb.TestVersion3LoneNesting.Inner2.country": + x.Country = value.Interface().(string) + case "testpb.TestVersion3LoneNesting.Inner2.inner": + x.Inner = value.Message().Interface().(*TestVersion3LoneNesting_Inner2_InnerInner) + default: + if fd.IsExtension() { + panic(fmt.Errorf("proto3 declared messages do not support extensions: testpb.TestVersion3LoneNesting.Inner2")) + } + panic(fmt.Errorf("message testpb.TestVersion3LoneNesting.Inner2 does not contain field %s", fd.FullName())) + } +} + +// Mutable returns a mutable reference to a composite type. +// +// If the field is unpopulated, it may allocate a composite value. +// For a field belonging to a oneof, it implicitly clears any other field +// that may be currently set within the same oneof. +// For extension fields, it implicitly stores the provided ExtensionType +// if not already stored. +// It panics if the field does not contain a composite type. +// +// Mutable is a mutating operation and unsafe for concurrent use. +func (x *fastReflection_TestVersion3LoneNesting_Inner2) Mutable(fd protoreflect.FieldDescriptor) protoreflect.Value { + switch fd.FullName() { + case "testpb.TestVersion3LoneNesting.Inner2.inner": + if x.Inner == nil { + x.Inner = new(TestVersion3LoneNesting_Inner2_InnerInner) + } + return protoreflect.ValueOfMessage(x.Inner.ProtoReflect()) + case "testpb.TestVersion3LoneNesting.Inner2.id": + panic(fmt.Errorf("field id of message testpb.TestVersion3LoneNesting.Inner2 is not mutable")) + case "testpb.TestVersion3LoneNesting.Inner2.country": + panic(fmt.Errorf("field country of message testpb.TestVersion3LoneNesting.Inner2 is not mutable")) + default: + if fd.IsExtension() { + panic(fmt.Errorf("proto3 declared messages do not support extensions: testpb.TestVersion3LoneNesting.Inner2")) + } + panic(fmt.Errorf("message testpb.TestVersion3LoneNesting.Inner2 does not contain field %s", fd.FullName())) + } +} + +// NewField returns a new value that is assignable to the field +// for the given descriptor. For scalars, this returns the default value. +// For lists, maps, and messages, this returns a new, empty, mutable value. +func (x *fastReflection_TestVersion3LoneNesting_Inner2) NewField(fd protoreflect.FieldDescriptor) protoreflect.Value { + switch fd.FullName() { + case "testpb.TestVersion3LoneNesting.Inner2.id": + return protoreflect.ValueOfString("") + case "testpb.TestVersion3LoneNesting.Inner2.country": + return protoreflect.ValueOfString("") + case "testpb.TestVersion3LoneNesting.Inner2.inner": + m := new(TestVersion3LoneNesting_Inner2_InnerInner) + return protoreflect.ValueOfMessage(m.ProtoReflect()) + default: + if fd.IsExtension() { + panic(fmt.Errorf("proto3 declared messages do not support extensions: testpb.TestVersion3LoneNesting.Inner2")) + } + panic(fmt.Errorf("message testpb.TestVersion3LoneNesting.Inner2 does not contain field %s", fd.FullName())) + } +} + +// WhichOneof reports which field within the oneof is populated, +// returning nil if none are populated. +// It panics if the oneof descriptor does not belong to this message. +func (x *fastReflection_TestVersion3LoneNesting_Inner2) WhichOneof(d protoreflect.OneofDescriptor) protoreflect.FieldDescriptor { + switch d.FullName() { + default: + panic(fmt.Errorf("%s is not a oneof field in testpb.TestVersion3LoneNesting.Inner2", d.FullName())) + } + panic("unreachable") +} + +// GetUnknown retrieves the entire list of unknown fields. +// The caller may only mutate the contents of the RawFields +// if the mutated bytes are stored back into the message with SetUnknown. +func (x *fastReflection_TestVersion3LoneNesting_Inner2) GetUnknown() protoreflect.RawFields { + return x.unknownFields +} + +// SetUnknown stores an entire list of unknown fields. +// The raw fields must be syntactically valid according to the wire format. +// An implementation may panic if this is not the case. +// Once stored, the caller must not mutate the content of the RawFields. +// An empty RawFields may be passed to clear the fields. +// +// SetUnknown is a mutating operation and unsafe for concurrent use. +func (x *fastReflection_TestVersion3LoneNesting_Inner2) SetUnknown(fields protoreflect.RawFields) { + x.unknownFields = fields +} + +// IsValid reports whether the message is valid. +// +// An invalid message is an empty, read-only value. +// +// An invalid message often corresponds to a nil pointer of the concrete +// message type, but the details are implementation dependent. +// Validity is not part of the protobuf data model, and may not +// be preserved in marshaling or other operations. +func (x *fastReflection_TestVersion3LoneNesting_Inner2) IsValid() bool { + return x != nil +} + +// ProtoMethods returns optional fastReflectionFeature-path implementations of various operations. +// This method may return nil. +// +// The returned methods type is identical to +// "google.golang.org/protobuf/runtime/protoiface".Methods. +// Consult the protoiface package documentation for details. +func (x *fastReflection_TestVersion3LoneNesting_Inner2) ProtoMethods() *protoiface.Methods { + size := func(input protoiface.SizeInput) protoiface.SizeOutput { + x := input.Message.Interface().(*TestVersion3LoneNesting_Inner2) + if x == nil { + return protoiface.SizeOutput{ + NoUnkeyedLiterals: input.NoUnkeyedLiterals, + Size: 0, + } + } + options := runtime.SizeInputToOptions(input) + _ = options + var n int + var l int + _ = l + l = len(x.Id) + if l > 0 { + n += 1 + l + runtime.Sov(uint64(l)) + } + l = len(x.Country) + if l > 0 { + n += 1 + l + runtime.Sov(uint64(l)) + } + if x.Inner != nil { + l = options.Size(x.Inner) + n += 1 + l + runtime.Sov(uint64(l)) + } + if x.unknownFields != nil { + n += len(x.unknownFields) + } + return protoiface.SizeOutput{ + NoUnkeyedLiterals: input.NoUnkeyedLiterals, + Size: n, + } + } + + marshal := func(input protoiface.MarshalInput) (protoiface.MarshalOutput, error) { + x := input.Message.Interface().(*TestVersion3LoneNesting_Inner2) + if x == nil { + return protoiface.MarshalOutput{ + NoUnkeyedLiterals: input.NoUnkeyedLiterals, + Buf: input.Buf, + }, nil + } + options := runtime.MarshalInputToOptions(input) + _ = options + size := options.Size(x) + dAtA := make([]byte, size) + i := len(dAtA) + _ = i + var l int + _ = l + if x.unknownFields != nil { + i -= len(x.unknownFields) + copy(dAtA[i:], x.unknownFields) + } + if x.Inner != nil { + encoded, err := options.Marshal(x.Inner) + if err != nil { + return protoiface.MarshalOutput{ + NoUnkeyedLiterals: input.NoUnkeyedLiterals, + Buf: input.Buf, + }, err + } + i -= len(encoded) + copy(dAtA[i:], encoded) + i = runtime.EncodeVarint(dAtA, i, uint64(len(encoded))) + i-- + dAtA[i] = 0x1a + } + if len(x.Country) > 0 { + i -= len(x.Country) + copy(dAtA[i:], x.Country) + i = runtime.EncodeVarint(dAtA, i, uint64(len(x.Country))) + i-- + dAtA[i] = 0x12 + } + if len(x.Id) > 0 { + i -= len(x.Id) + copy(dAtA[i:], x.Id) + i = runtime.EncodeVarint(dAtA, i, uint64(len(x.Id))) + i-- + dAtA[i] = 0xa + } + if input.Buf != nil { + input.Buf = append(input.Buf, dAtA...) + } else { + input.Buf = dAtA + } + return protoiface.MarshalOutput{ + NoUnkeyedLiterals: input.NoUnkeyedLiterals, + Buf: input.Buf, + }, nil + } + unmarshal := func(input protoiface.UnmarshalInput) (protoiface.UnmarshalOutput, error) { + x := input.Message.Interface().(*TestVersion3LoneNesting_Inner2) + if x == nil { + return protoiface.UnmarshalOutput{ + NoUnkeyedLiterals: input.NoUnkeyedLiterals, + Flags: input.Flags, + }, nil + } + options := runtime.UnmarshalInputToOptions(input) + _ = options + dAtA := input.Buf + l := len(dAtA) + iNdEx := 0 + for iNdEx < l { + preIndex := iNdEx + var wire uint64 + for shift := uint(0); ; shift += 7 { + if shift >= 64 { + return protoiface.UnmarshalOutput{NoUnkeyedLiterals: input.NoUnkeyedLiterals, Flags: input.Flags}, runtime.ErrIntOverflow + } + if iNdEx >= l { + return protoiface.UnmarshalOutput{NoUnkeyedLiterals: input.NoUnkeyedLiterals, Flags: input.Flags}, io.ErrUnexpectedEOF + } + b := dAtA[iNdEx] + iNdEx++ + wire |= uint64(b&0x7F) << shift + if b < 0x80 { + break + } + } + fieldNum := int32(wire >> 3) + wireType := int(wire & 0x7) + if wireType == 4 { + return protoiface.UnmarshalOutput{NoUnkeyedLiterals: input.NoUnkeyedLiterals, Flags: input.Flags}, fmt.Errorf("proto: TestVersion3LoneNesting_Inner2: wiretype end group for non-group") + } + if fieldNum <= 0 { + return protoiface.UnmarshalOutput{NoUnkeyedLiterals: input.NoUnkeyedLiterals, Flags: input.Flags}, fmt.Errorf("proto: TestVersion3LoneNesting_Inner2: illegal tag %d (wire type %d)", fieldNum, wire) + } + switch fieldNum { + case 1: + if wireType != 2 { + return protoiface.UnmarshalOutput{NoUnkeyedLiterals: input.NoUnkeyedLiterals, Flags: input.Flags}, fmt.Errorf("proto: wrong wireType = %d for field Id", wireType) + } + var stringLen uint64 + for shift := uint(0); ; shift += 7 { + if shift >= 64 { + return protoiface.UnmarshalOutput{NoUnkeyedLiterals: input.NoUnkeyedLiterals, Flags: input.Flags}, runtime.ErrIntOverflow + } + if iNdEx >= l { + return protoiface.UnmarshalOutput{NoUnkeyedLiterals: input.NoUnkeyedLiterals, Flags: input.Flags}, io.ErrUnexpectedEOF + } + b := dAtA[iNdEx] + iNdEx++ + stringLen |= uint64(b&0x7F) << shift + if b < 0x80 { + break + } + } + intStringLen := int(stringLen) + if intStringLen < 0 { + return protoiface.UnmarshalOutput{NoUnkeyedLiterals: input.NoUnkeyedLiterals, Flags: input.Flags}, runtime.ErrInvalidLength + } + postIndex := iNdEx + intStringLen + if postIndex < 0 { + return protoiface.UnmarshalOutput{NoUnkeyedLiterals: input.NoUnkeyedLiterals, Flags: input.Flags}, runtime.ErrInvalidLength + } + if postIndex > l { + return protoiface.UnmarshalOutput{NoUnkeyedLiterals: input.NoUnkeyedLiterals, Flags: input.Flags}, io.ErrUnexpectedEOF + } + x.Id = string(dAtA[iNdEx:postIndex]) + iNdEx = postIndex + case 2: + if wireType != 2 { + return protoiface.UnmarshalOutput{NoUnkeyedLiterals: input.NoUnkeyedLiterals, Flags: input.Flags}, fmt.Errorf("proto: wrong wireType = %d for field Country", wireType) + } + var stringLen uint64 + for shift := uint(0); ; shift += 7 { + if shift >= 64 { + return protoiface.UnmarshalOutput{NoUnkeyedLiterals: input.NoUnkeyedLiterals, Flags: input.Flags}, runtime.ErrIntOverflow + } + if iNdEx >= l { + return protoiface.UnmarshalOutput{NoUnkeyedLiterals: input.NoUnkeyedLiterals, Flags: input.Flags}, io.ErrUnexpectedEOF + } + b := dAtA[iNdEx] + iNdEx++ + stringLen |= uint64(b&0x7F) << shift + if b < 0x80 { + break + } + } + intStringLen := int(stringLen) + if intStringLen < 0 { + return protoiface.UnmarshalOutput{NoUnkeyedLiterals: input.NoUnkeyedLiterals, Flags: input.Flags}, runtime.ErrInvalidLength + } + postIndex := iNdEx + intStringLen + if postIndex < 0 { + return protoiface.UnmarshalOutput{NoUnkeyedLiterals: input.NoUnkeyedLiterals, Flags: input.Flags}, runtime.ErrInvalidLength + } + if postIndex > l { + return protoiface.UnmarshalOutput{NoUnkeyedLiterals: input.NoUnkeyedLiterals, Flags: input.Flags}, io.ErrUnexpectedEOF + } + x.Country = string(dAtA[iNdEx:postIndex]) + iNdEx = postIndex + case 3: + if wireType != 2 { + return protoiface.UnmarshalOutput{NoUnkeyedLiterals: input.NoUnkeyedLiterals, Flags: input.Flags}, fmt.Errorf("proto: wrong wireType = %d for field Inner", wireType) + } + var msglen int + for shift := uint(0); ; shift += 7 { + if shift >= 64 { + return protoiface.UnmarshalOutput{NoUnkeyedLiterals: input.NoUnkeyedLiterals, Flags: input.Flags}, runtime.ErrIntOverflow + } + if iNdEx >= l { + return protoiface.UnmarshalOutput{NoUnkeyedLiterals: input.NoUnkeyedLiterals, Flags: input.Flags}, io.ErrUnexpectedEOF + } + b := dAtA[iNdEx] + iNdEx++ + msglen |= int(b&0x7F) << shift + if b < 0x80 { + break + } + } + if msglen < 0 { + return protoiface.UnmarshalOutput{NoUnkeyedLiterals: input.NoUnkeyedLiterals, Flags: input.Flags}, runtime.ErrInvalidLength + } + postIndex := iNdEx + msglen + if postIndex < 0 { + return protoiface.UnmarshalOutput{NoUnkeyedLiterals: input.NoUnkeyedLiterals, Flags: input.Flags}, runtime.ErrInvalidLength + } + if postIndex > l { + return protoiface.UnmarshalOutput{NoUnkeyedLiterals: input.NoUnkeyedLiterals, Flags: input.Flags}, io.ErrUnexpectedEOF + } + if x.Inner == nil { + x.Inner = &TestVersion3LoneNesting_Inner2_InnerInner{} + } + if err := options.Unmarshal(dAtA[iNdEx:postIndex], x.Inner); err != nil { + return protoiface.UnmarshalOutput{NoUnkeyedLiterals: input.NoUnkeyedLiterals, Flags: input.Flags}, err + } + iNdEx = postIndex + default: + iNdEx = preIndex + skippy, err := runtime.Skip(dAtA[iNdEx:]) + if err != nil { + return protoiface.UnmarshalOutput{NoUnkeyedLiterals: input.NoUnkeyedLiterals, Flags: input.Flags}, err + } + if (skippy < 0) || (iNdEx+skippy) < 0 { + return protoiface.UnmarshalOutput{NoUnkeyedLiterals: input.NoUnkeyedLiterals, Flags: input.Flags}, runtime.ErrInvalidLength + } + if (iNdEx + skippy) > l { + return protoiface.UnmarshalOutput{NoUnkeyedLiterals: input.NoUnkeyedLiterals, Flags: input.Flags}, io.ErrUnexpectedEOF + } + if !options.DiscardUnknown { + x.unknownFields = append(x.unknownFields, dAtA[iNdEx:iNdEx+skippy]...) + } + iNdEx += skippy + } + } + + if iNdEx > l { + return protoiface.UnmarshalOutput{NoUnkeyedLiterals: input.NoUnkeyedLiterals, Flags: input.Flags}, io.ErrUnexpectedEOF + } + return protoiface.UnmarshalOutput{NoUnkeyedLiterals: input.NoUnkeyedLiterals, Flags: input.Flags}, nil + } + return &protoiface.Methods{ + NoUnkeyedLiterals: struct{}{}, + Flags: protoiface.SupportMarshalDeterministic | protoiface.SupportUnmarshalDiscardUnknown, + Size: size, + Marshal: marshal, + Unmarshal: unmarshal, + Merge: nil, + CheckInitialized: nil, + } +} + +var ( + md_TestVersion3LoneNesting_Inner2_InnerInner protoreflect.MessageDescriptor + fd_TestVersion3LoneNesting_Inner2_InnerInner_id protoreflect.FieldDescriptor + fd_TestVersion3LoneNesting_Inner2_InnerInner_city protoreflect.FieldDescriptor +) + +func init() { + file_unknownproto_proto_init() + md_TestVersion3LoneNesting_Inner2_InnerInner = File_unknownproto_proto.Messages().ByName("TestVersion3LoneNesting").Messages().ByName("Inner2").Messages().ByName("InnerInner") + fd_TestVersion3LoneNesting_Inner2_InnerInner_id = md_TestVersion3LoneNesting_Inner2_InnerInner.Fields().ByName("id") + fd_TestVersion3LoneNesting_Inner2_InnerInner_city = md_TestVersion3LoneNesting_Inner2_InnerInner.Fields().ByName("city") +} + +var _ protoreflect.Message = (*fastReflection_TestVersion3LoneNesting_Inner2_InnerInner)(nil) + +type fastReflection_TestVersion3LoneNesting_Inner2_InnerInner TestVersion3LoneNesting_Inner2_InnerInner + +func (x *TestVersion3LoneNesting_Inner2_InnerInner) ProtoReflect() protoreflect.Message { + return (*fastReflection_TestVersion3LoneNesting_Inner2_InnerInner)(x) +} + +func (x *TestVersion3LoneNesting_Inner2_InnerInner) slowProtoReflect() protoreflect.Message { + mi := &file_unknownproto_proto_msgTypes[28] + if protoimpl.UnsafeEnabled && x != nil { + ms := protoimpl.X.MessageStateOf(protoimpl.Pointer(x)) + if ms.LoadMessageInfo() == nil { + ms.StoreMessageInfo(mi) + } + return ms + } + return mi.MessageOf(x) +} + +var _fastReflection_TestVersion3LoneNesting_Inner2_InnerInner_messageType fastReflection_TestVersion3LoneNesting_Inner2_InnerInner_messageType +var _ protoreflect.MessageType = fastReflection_TestVersion3LoneNesting_Inner2_InnerInner_messageType{} + +type fastReflection_TestVersion3LoneNesting_Inner2_InnerInner_messageType struct{} + +func (x fastReflection_TestVersion3LoneNesting_Inner2_InnerInner_messageType) Zero() protoreflect.Message { + return (*fastReflection_TestVersion3LoneNesting_Inner2_InnerInner)(nil) +} +func (x fastReflection_TestVersion3LoneNesting_Inner2_InnerInner_messageType) New() protoreflect.Message { + return new(fastReflection_TestVersion3LoneNesting_Inner2_InnerInner) +} +func (x fastReflection_TestVersion3LoneNesting_Inner2_InnerInner_messageType) Descriptor() protoreflect.MessageDescriptor { + return md_TestVersion3LoneNesting_Inner2_InnerInner +} + +// Descriptor returns message descriptor, which contains only the protobuf +// type information for the message. +func (x *fastReflection_TestVersion3LoneNesting_Inner2_InnerInner) Descriptor() protoreflect.MessageDescriptor { + return md_TestVersion3LoneNesting_Inner2_InnerInner +} + +// Type returns the message type, which encapsulates both Go and protobuf +// type information. If the Go type information is not needed, +// it is recommended that the message descriptor be used instead. +func (x *fastReflection_TestVersion3LoneNesting_Inner2_InnerInner) Type() protoreflect.MessageType { + return _fastReflection_TestVersion3LoneNesting_Inner2_InnerInner_messageType +} + +// New returns a newly allocated and mutable empty message. +func (x *fastReflection_TestVersion3LoneNesting_Inner2_InnerInner) New() protoreflect.Message { + return new(fastReflection_TestVersion3LoneNesting_Inner2_InnerInner) +} + +// Interface unwraps the message reflection interface and +// returns the underlying ProtoMessage interface. +func (x *fastReflection_TestVersion3LoneNesting_Inner2_InnerInner) Interface() protoreflect.ProtoMessage { + return (*TestVersion3LoneNesting_Inner2_InnerInner)(x) +} + +// Range iterates over every populated field in an undefined order, +// calling f for each field descriptor and value encountered. +// Range returns immediately if f returns false. +// While iterating, mutating operations may only be performed +// on the current field descriptor. +func (x *fastReflection_TestVersion3LoneNesting_Inner2_InnerInner) Range(f func(protoreflect.FieldDescriptor, protoreflect.Value) bool) { + if x.Id != "" { + value := protoreflect.ValueOfString(x.Id) + if !f(fd_TestVersion3LoneNesting_Inner2_InnerInner_id, value) { + return + } + } + if x.City != "" { + value := protoreflect.ValueOfString(x.City) + if !f(fd_TestVersion3LoneNesting_Inner2_InnerInner_city, value) { + return + } + } +} + +// Has reports whether a field is populated. +// +// Some fields have the property of nullability where it is possible to +// distinguish between the default value of a field and whether the field +// was explicitly populated with the default value. Singular message fields, +// member fields of a oneof, and proto2 scalar fields are nullable. Such +// fields are populated only if explicitly set. +// +// In other cases (aside from the nullable cases above), +// a proto3 scalar field is populated if it contains a non-zero value, and +// a repeated field is populated if it is non-empty. +func (x *fastReflection_TestVersion3LoneNesting_Inner2_InnerInner) Has(fd protoreflect.FieldDescriptor) bool { + switch fd.FullName() { + case "testpb.TestVersion3LoneNesting.Inner2.InnerInner.id": + return x.Id != "" + case "testpb.TestVersion3LoneNesting.Inner2.InnerInner.city": + return x.City != "" + default: + if fd.IsExtension() { + panic(fmt.Errorf("proto3 declared messages do not support extensions: testpb.TestVersion3LoneNesting.Inner2.InnerInner")) + } + panic(fmt.Errorf("message testpb.TestVersion3LoneNesting.Inner2.InnerInner does not contain field %s", fd.FullName())) + } +} + +// Clear clears the field such that a subsequent Has call reports false. +// +// Clearing an extension field clears both the extension type and value +// associated with the given field number. +// +// Clear is a mutating operation and unsafe for concurrent use. +func (x *fastReflection_TestVersion3LoneNesting_Inner2_InnerInner) Clear(fd protoreflect.FieldDescriptor) { + switch fd.FullName() { + case "testpb.TestVersion3LoneNesting.Inner2.InnerInner.id": + x.Id = "" + case "testpb.TestVersion3LoneNesting.Inner2.InnerInner.city": + x.City = "" + default: + if fd.IsExtension() { + panic(fmt.Errorf("proto3 declared messages do not support extensions: testpb.TestVersion3LoneNesting.Inner2.InnerInner")) + } + panic(fmt.Errorf("message testpb.TestVersion3LoneNesting.Inner2.InnerInner does not contain field %s", fd.FullName())) + } +} + +// Get retrieves the value for a field. +// +// For unpopulated scalars, it returns the default value, where +// the default value of a bytes scalar is guaranteed to be a copy. +// For unpopulated composite types, it returns an empty, read-only view +// of the value; to obtain a mutable reference, use Mutable. +func (x *fastReflection_TestVersion3LoneNesting_Inner2_InnerInner) Get(descriptor protoreflect.FieldDescriptor) protoreflect.Value { + switch descriptor.FullName() { + case "testpb.TestVersion3LoneNesting.Inner2.InnerInner.id": + value := x.Id + return protoreflect.ValueOfString(value) + case "testpb.TestVersion3LoneNesting.Inner2.InnerInner.city": + value := x.City + return protoreflect.ValueOfString(value) + default: + if descriptor.IsExtension() { + panic(fmt.Errorf("proto3 declared messages do not support extensions: testpb.TestVersion3LoneNesting.Inner2.InnerInner")) + } + panic(fmt.Errorf("message testpb.TestVersion3LoneNesting.Inner2.InnerInner does not contain field %s", descriptor.FullName())) + } +} + +// Set stores the value for a field. +// +// For a field belonging to a oneof, it implicitly clears any other field +// that may be currently set within the same oneof. +// For extension fields, it implicitly stores the provided ExtensionType. +// When setting a composite type, it is unspecified whether the stored value +// aliases the source's memory in any way. If the composite value is an +// empty, read-only value, then it panics. +// +// Set is a mutating operation and unsafe for concurrent use. +func (x *fastReflection_TestVersion3LoneNesting_Inner2_InnerInner) Set(fd protoreflect.FieldDescriptor, value protoreflect.Value) { + switch fd.FullName() { + case "testpb.TestVersion3LoneNesting.Inner2.InnerInner.id": + x.Id = value.Interface().(string) + case "testpb.TestVersion3LoneNesting.Inner2.InnerInner.city": + x.City = value.Interface().(string) + default: + if fd.IsExtension() { + panic(fmt.Errorf("proto3 declared messages do not support extensions: testpb.TestVersion3LoneNesting.Inner2.InnerInner")) + } + panic(fmt.Errorf("message testpb.TestVersion3LoneNesting.Inner2.InnerInner does not contain field %s", fd.FullName())) + } +} + +// Mutable returns a mutable reference to a composite type. +// +// If the field is unpopulated, it may allocate a composite value. +// For a field belonging to a oneof, it implicitly clears any other field +// that may be currently set within the same oneof. +// For extension fields, it implicitly stores the provided ExtensionType +// if not already stored. +// It panics if the field does not contain a composite type. +// +// Mutable is a mutating operation and unsafe for concurrent use. +func (x *fastReflection_TestVersion3LoneNesting_Inner2_InnerInner) Mutable(fd protoreflect.FieldDescriptor) protoreflect.Value { + switch fd.FullName() { + case "testpb.TestVersion3LoneNesting.Inner2.InnerInner.id": + panic(fmt.Errorf("field id of message testpb.TestVersion3LoneNesting.Inner2.InnerInner is not mutable")) + case "testpb.TestVersion3LoneNesting.Inner2.InnerInner.city": + panic(fmt.Errorf("field city of message testpb.TestVersion3LoneNesting.Inner2.InnerInner is not mutable")) + default: + if fd.IsExtension() { + panic(fmt.Errorf("proto3 declared messages do not support extensions: testpb.TestVersion3LoneNesting.Inner2.InnerInner")) + } + panic(fmt.Errorf("message testpb.TestVersion3LoneNesting.Inner2.InnerInner does not contain field %s", fd.FullName())) + } +} + +// NewField returns a new value that is assignable to the field +// for the given descriptor. For scalars, this returns the default value. +// For lists, maps, and messages, this returns a new, empty, mutable value. +func (x *fastReflection_TestVersion3LoneNesting_Inner2_InnerInner) NewField(fd protoreflect.FieldDescriptor) protoreflect.Value { + switch fd.FullName() { + case "testpb.TestVersion3LoneNesting.Inner2.InnerInner.id": + return protoreflect.ValueOfString("") + case "testpb.TestVersion3LoneNesting.Inner2.InnerInner.city": + return protoreflect.ValueOfString("") + default: + if fd.IsExtension() { + panic(fmt.Errorf("proto3 declared messages do not support extensions: testpb.TestVersion3LoneNesting.Inner2.InnerInner")) + } + panic(fmt.Errorf("message testpb.TestVersion3LoneNesting.Inner2.InnerInner does not contain field %s", fd.FullName())) + } +} + +// WhichOneof reports which field within the oneof is populated, +// returning nil if none are populated. +// It panics if the oneof descriptor does not belong to this message. +func (x *fastReflection_TestVersion3LoneNesting_Inner2_InnerInner) WhichOneof(d protoreflect.OneofDescriptor) protoreflect.FieldDescriptor { + switch d.FullName() { + default: + panic(fmt.Errorf("%s is not a oneof field in testpb.TestVersion3LoneNesting.Inner2.InnerInner", d.FullName())) + } + panic("unreachable") +} + +// GetUnknown retrieves the entire list of unknown fields. +// The caller may only mutate the contents of the RawFields +// if the mutated bytes are stored back into the message with SetUnknown. +func (x *fastReflection_TestVersion3LoneNesting_Inner2_InnerInner) GetUnknown() protoreflect.RawFields { + return x.unknownFields +} + +// SetUnknown stores an entire list of unknown fields. +// The raw fields must be syntactically valid according to the wire format. +// An implementation may panic if this is not the case. +// Once stored, the caller must not mutate the content of the RawFields. +// An empty RawFields may be passed to clear the fields. +// +// SetUnknown is a mutating operation and unsafe for concurrent use. +func (x *fastReflection_TestVersion3LoneNesting_Inner2_InnerInner) SetUnknown(fields protoreflect.RawFields) { + x.unknownFields = fields +} + +// IsValid reports whether the message is valid. +// +// An invalid message is an empty, read-only value. +// +// An invalid message often corresponds to a nil pointer of the concrete +// message type, but the details are implementation dependent. +// Validity is not part of the protobuf data model, and may not +// be preserved in marshaling or other operations. +func (x *fastReflection_TestVersion3LoneNesting_Inner2_InnerInner) IsValid() bool { + return x != nil +} + +// ProtoMethods returns optional fastReflectionFeature-path implementations of various operations. +// This method may return nil. +// +// The returned methods type is identical to +// "google.golang.org/protobuf/runtime/protoiface".Methods. +// Consult the protoiface package documentation for details. +func (x *fastReflection_TestVersion3LoneNesting_Inner2_InnerInner) ProtoMethods() *protoiface.Methods { + size := func(input protoiface.SizeInput) protoiface.SizeOutput { + x := input.Message.Interface().(*TestVersion3LoneNesting_Inner2_InnerInner) + if x == nil { + return protoiface.SizeOutput{ + NoUnkeyedLiterals: input.NoUnkeyedLiterals, + Size: 0, + } + } + options := runtime.SizeInputToOptions(input) + _ = options + var n int + var l int + _ = l + l = len(x.Id) + if l > 0 { + n += 1 + l + runtime.Sov(uint64(l)) + } + l = len(x.City) + if l > 0 { + n += 1 + l + runtime.Sov(uint64(l)) + } + if x.unknownFields != nil { + n += len(x.unknownFields) + } + return protoiface.SizeOutput{ + NoUnkeyedLiterals: input.NoUnkeyedLiterals, + Size: n, + } + } + + marshal := func(input protoiface.MarshalInput) (protoiface.MarshalOutput, error) { + x := input.Message.Interface().(*TestVersion3LoneNesting_Inner2_InnerInner) + if x == nil { + return protoiface.MarshalOutput{ + NoUnkeyedLiterals: input.NoUnkeyedLiterals, + Buf: input.Buf, + }, nil + } + options := runtime.MarshalInputToOptions(input) + _ = options + size := options.Size(x) + dAtA := make([]byte, size) + i := len(dAtA) + _ = i + var l int + _ = l + if x.unknownFields != nil { + i -= len(x.unknownFields) + copy(dAtA[i:], x.unknownFields) + } + if len(x.City) > 0 { + i -= len(x.City) + copy(dAtA[i:], x.City) + i = runtime.EncodeVarint(dAtA, i, uint64(len(x.City))) + i-- + dAtA[i] = 0x12 + } + if len(x.Id) > 0 { + i -= len(x.Id) + copy(dAtA[i:], x.Id) + i = runtime.EncodeVarint(dAtA, i, uint64(len(x.Id))) + i-- + dAtA[i] = 0xa + } + if input.Buf != nil { + input.Buf = append(input.Buf, dAtA...) + } else { + input.Buf = dAtA + } + return protoiface.MarshalOutput{ + NoUnkeyedLiterals: input.NoUnkeyedLiterals, + Buf: input.Buf, + }, nil + } + unmarshal := func(input protoiface.UnmarshalInput) (protoiface.UnmarshalOutput, error) { + x := input.Message.Interface().(*TestVersion3LoneNesting_Inner2_InnerInner) + if x == nil { + return protoiface.UnmarshalOutput{ + NoUnkeyedLiterals: input.NoUnkeyedLiterals, + Flags: input.Flags, + }, nil + } + options := runtime.UnmarshalInputToOptions(input) + _ = options + dAtA := input.Buf + l := len(dAtA) + iNdEx := 0 + for iNdEx < l { + preIndex := iNdEx + var wire uint64 + for shift := uint(0); ; shift += 7 { + if shift >= 64 { + return protoiface.UnmarshalOutput{NoUnkeyedLiterals: input.NoUnkeyedLiterals, Flags: input.Flags}, runtime.ErrIntOverflow + } + if iNdEx >= l { + return protoiface.UnmarshalOutput{NoUnkeyedLiterals: input.NoUnkeyedLiterals, Flags: input.Flags}, io.ErrUnexpectedEOF + } + b := dAtA[iNdEx] + iNdEx++ + wire |= uint64(b&0x7F) << shift + if b < 0x80 { + break + } + } + fieldNum := int32(wire >> 3) + wireType := int(wire & 0x7) + if wireType == 4 { + return protoiface.UnmarshalOutput{NoUnkeyedLiterals: input.NoUnkeyedLiterals, Flags: input.Flags}, fmt.Errorf("proto: TestVersion3LoneNesting_Inner2_InnerInner: wiretype end group for non-group") + } + if fieldNum <= 0 { + return protoiface.UnmarshalOutput{NoUnkeyedLiterals: input.NoUnkeyedLiterals, Flags: input.Flags}, fmt.Errorf("proto: TestVersion3LoneNesting_Inner2_InnerInner: illegal tag %d (wire type %d)", fieldNum, wire) + } + switch fieldNum { + case 1: + if wireType != 2 { + return protoiface.UnmarshalOutput{NoUnkeyedLiterals: input.NoUnkeyedLiterals, Flags: input.Flags}, fmt.Errorf("proto: wrong wireType = %d for field Id", wireType) + } + var stringLen uint64 + for shift := uint(0); ; shift += 7 { + if shift >= 64 { + return protoiface.UnmarshalOutput{NoUnkeyedLiterals: input.NoUnkeyedLiterals, Flags: input.Flags}, runtime.ErrIntOverflow + } + if iNdEx >= l { + return protoiface.UnmarshalOutput{NoUnkeyedLiterals: input.NoUnkeyedLiterals, Flags: input.Flags}, io.ErrUnexpectedEOF + } + b := dAtA[iNdEx] + iNdEx++ + stringLen |= uint64(b&0x7F) << shift + if b < 0x80 { + break + } + } + intStringLen := int(stringLen) + if intStringLen < 0 { + return protoiface.UnmarshalOutput{NoUnkeyedLiterals: input.NoUnkeyedLiterals, Flags: input.Flags}, runtime.ErrInvalidLength + } + postIndex := iNdEx + intStringLen + if postIndex < 0 { + return protoiface.UnmarshalOutput{NoUnkeyedLiterals: input.NoUnkeyedLiterals, Flags: input.Flags}, runtime.ErrInvalidLength + } + if postIndex > l { + return protoiface.UnmarshalOutput{NoUnkeyedLiterals: input.NoUnkeyedLiterals, Flags: input.Flags}, io.ErrUnexpectedEOF + } + x.Id = string(dAtA[iNdEx:postIndex]) + iNdEx = postIndex + case 2: + if wireType != 2 { + return protoiface.UnmarshalOutput{NoUnkeyedLiterals: input.NoUnkeyedLiterals, Flags: input.Flags}, fmt.Errorf("proto: wrong wireType = %d for field City", wireType) + } + var stringLen uint64 + for shift := uint(0); ; shift += 7 { + if shift >= 64 { + return protoiface.UnmarshalOutput{NoUnkeyedLiterals: input.NoUnkeyedLiterals, Flags: input.Flags}, runtime.ErrIntOverflow + } + if iNdEx >= l { + return protoiface.UnmarshalOutput{NoUnkeyedLiterals: input.NoUnkeyedLiterals, Flags: input.Flags}, io.ErrUnexpectedEOF + } + b := dAtA[iNdEx] + iNdEx++ + stringLen |= uint64(b&0x7F) << shift + if b < 0x80 { + break + } + } + intStringLen := int(stringLen) + if intStringLen < 0 { + return protoiface.UnmarshalOutput{NoUnkeyedLiterals: input.NoUnkeyedLiterals, Flags: input.Flags}, runtime.ErrInvalidLength + } + postIndex := iNdEx + intStringLen + if postIndex < 0 { + return protoiface.UnmarshalOutput{NoUnkeyedLiterals: input.NoUnkeyedLiterals, Flags: input.Flags}, runtime.ErrInvalidLength + } + if postIndex > l { + return protoiface.UnmarshalOutput{NoUnkeyedLiterals: input.NoUnkeyedLiterals, Flags: input.Flags}, io.ErrUnexpectedEOF + } + x.City = string(dAtA[iNdEx:postIndex]) + iNdEx = postIndex + default: + iNdEx = preIndex + skippy, err := runtime.Skip(dAtA[iNdEx:]) + if err != nil { + return protoiface.UnmarshalOutput{NoUnkeyedLiterals: input.NoUnkeyedLiterals, Flags: input.Flags}, err + } + if (skippy < 0) || (iNdEx+skippy) < 0 { + return protoiface.UnmarshalOutput{NoUnkeyedLiterals: input.NoUnkeyedLiterals, Flags: input.Flags}, runtime.ErrInvalidLength + } + if (iNdEx + skippy) > l { + return protoiface.UnmarshalOutput{NoUnkeyedLiterals: input.NoUnkeyedLiterals, Flags: input.Flags}, io.ErrUnexpectedEOF + } + if !options.DiscardUnknown { + x.unknownFields = append(x.unknownFields, dAtA[iNdEx:iNdEx+skippy]...) + } + iNdEx += skippy + } + } + + if iNdEx > l { + return protoiface.UnmarshalOutput{NoUnkeyedLiterals: input.NoUnkeyedLiterals, Flags: input.Flags}, io.ErrUnexpectedEOF + } + return protoiface.UnmarshalOutput{NoUnkeyedLiterals: input.NoUnkeyedLiterals, Flags: input.Flags}, nil + } + return &protoiface.Methods{ + NoUnkeyedLiterals: struct{}{}, + Flags: protoiface.SupportMarshalDeterministic | protoiface.SupportUnmarshalDiscardUnknown, + Size: size, + Marshal: marshal, + Unmarshal: unmarshal, + Merge: nil, + CheckInitialized: nil, + } +} + +var _ protoreflect.List = (*_TestVersion4LoneNesting_4_list)(nil) + +type _TestVersion4LoneNesting_4_list struct { + list *[]*TestVersion3 +} + +func (x *_TestVersion4LoneNesting_4_list) Len() int { + if x.list == nil { + return 0 + } + return len(*x.list) +} + +func (x *_TestVersion4LoneNesting_4_list) Get(i int) protoreflect.Value { + return protoreflect.ValueOfMessage((*x.list)[i].ProtoReflect()) +} + +func (x *_TestVersion4LoneNesting_4_list) Set(i int, value protoreflect.Value) { + valueUnwrapped := value.Message() + concreteValue := valueUnwrapped.Interface().(*TestVersion3) + (*x.list)[i] = concreteValue +} + +func (x *_TestVersion4LoneNesting_4_list) Append(value protoreflect.Value) { + valueUnwrapped := value.Message() + concreteValue := valueUnwrapped.Interface().(*TestVersion3) + *x.list = append(*x.list, concreteValue) +} + +func (x *_TestVersion4LoneNesting_4_list) AppendMutable() protoreflect.Value { + v := new(TestVersion3) + *x.list = append(*x.list, v) + return protoreflect.ValueOfMessage(v.ProtoReflect()) +} + +func (x *_TestVersion4LoneNesting_4_list) Truncate(n int) { + for i := n; i < len(*x.list); i++ { + (*x.list)[i] = nil + } + *x.list = (*x.list)[:n] +} + +func (x *_TestVersion4LoneNesting_4_list) NewElement() protoreflect.Value { + v := new(TestVersion3) + return protoreflect.ValueOfMessage(v.ProtoReflect()) +} + +func (x *_TestVersion4LoneNesting_4_list) IsValid() bool { + return x.list != nil +} + +var _ protoreflect.List = (*_TestVersion4LoneNesting_5_list)(nil) + +type _TestVersion4LoneNesting_5_list struct { + list *[]*TestVersion3 +} + +func (x *_TestVersion4LoneNesting_5_list) Len() int { + if x.list == nil { + return 0 + } + return len(*x.list) +} + +func (x *_TestVersion4LoneNesting_5_list) Get(i int) protoreflect.Value { + return protoreflect.ValueOfMessage((*x.list)[i].ProtoReflect()) +} + +func (x *_TestVersion4LoneNesting_5_list) Set(i int, value protoreflect.Value) { + valueUnwrapped := value.Message() + concreteValue := valueUnwrapped.Interface().(*TestVersion3) + (*x.list)[i] = concreteValue +} + +func (x *_TestVersion4LoneNesting_5_list) Append(value protoreflect.Value) { + valueUnwrapped := value.Message() + concreteValue := valueUnwrapped.Interface().(*TestVersion3) + *x.list = append(*x.list, concreteValue) +} + +func (x *_TestVersion4LoneNesting_5_list) AppendMutable() protoreflect.Value { + v := new(TestVersion3) + *x.list = append(*x.list, v) + return protoreflect.ValueOfMessage(v.ProtoReflect()) +} + +func (x *_TestVersion4LoneNesting_5_list) Truncate(n int) { + for i := n; i < len(*x.list); i++ { + (*x.list)[i] = nil + } + *x.list = (*x.list)[:n] +} + +func (x *_TestVersion4LoneNesting_5_list) NewElement() protoreflect.Value { + v := new(TestVersion3) + return protoreflect.ValueOfMessage(v.ProtoReflect()) +} + +func (x *_TestVersion4LoneNesting_5_list) IsValid() bool { + return x.list != nil +} + +var _ protoreflect.List = (*_TestVersion4LoneNesting_9_list)(nil) + +type _TestVersion4LoneNesting_9_list struct { + list *[]*TestVersion1 +} + +func (x *_TestVersion4LoneNesting_9_list) Len() int { + if x.list == nil { + return 0 + } + return len(*x.list) +} + +func (x *_TestVersion4LoneNesting_9_list) Get(i int) protoreflect.Value { + return protoreflect.ValueOfMessage((*x.list)[i].ProtoReflect()) +} + +func (x *_TestVersion4LoneNesting_9_list) Set(i int, value protoreflect.Value) { + valueUnwrapped := value.Message() + concreteValue := valueUnwrapped.Interface().(*TestVersion1) + (*x.list)[i] = concreteValue +} + +func (x *_TestVersion4LoneNesting_9_list) Append(value protoreflect.Value) { + valueUnwrapped := value.Message() + concreteValue := valueUnwrapped.Interface().(*TestVersion1) + *x.list = append(*x.list, concreteValue) +} + +func (x *_TestVersion4LoneNesting_9_list) AppendMutable() protoreflect.Value { + v := new(TestVersion1) + *x.list = append(*x.list, v) + return protoreflect.ValueOfMessage(v.ProtoReflect()) +} + +func (x *_TestVersion4LoneNesting_9_list) Truncate(n int) { + for i := n; i < len(*x.list); i++ { + (*x.list)[i] = nil + } + *x.list = (*x.list)[:n] +} + +func (x *_TestVersion4LoneNesting_9_list) NewElement() protoreflect.Value { + v := new(TestVersion1) + return protoreflect.ValueOfMessage(v.ProtoReflect()) +} + +func (x *_TestVersion4LoneNesting_9_list) IsValid() bool { + return x.list != nil +} + +var ( + md_TestVersion4LoneNesting protoreflect.MessageDescriptor + fd_TestVersion4LoneNesting_x protoreflect.FieldDescriptor + fd_TestVersion4LoneNesting_a protoreflect.FieldDescriptor + fd_TestVersion4LoneNesting_b protoreflect.FieldDescriptor + fd_TestVersion4LoneNesting_c protoreflect.FieldDescriptor + fd_TestVersion4LoneNesting_d protoreflect.FieldDescriptor + fd_TestVersion4LoneNesting_f protoreflect.FieldDescriptor + fd_TestVersion4LoneNesting_g protoreflect.FieldDescriptor + fd_TestVersion4LoneNesting_h protoreflect.FieldDescriptor + fd_TestVersion4LoneNesting_k protoreflect.FieldDescriptor + fd_TestVersion4LoneNesting_non_critical_field protoreflect.FieldDescriptor + fd_TestVersion4LoneNesting_inner1 protoreflect.FieldDescriptor + fd_TestVersion4LoneNesting_inner2 protoreflect.FieldDescriptor +) + +func init() { + file_unknownproto_proto_init() + md_TestVersion4LoneNesting = File_unknownproto_proto.Messages().ByName("TestVersion4LoneNesting") + fd_TestVersion4LoneNesting_x = md_TestVersion4LoneNesting.Fields().ByName("x") + fd_TestVersion4LoneNesting_a = md_TestVersion4LoneNesting.Fields().ByName("a") + fd_TestVersion4LoneNesting_b = md_TestVersion4LoneNesting.Fields().ByName("b") + fd_TestVersion4LoneNesting_c = md_TestVersion4LoneNesting.Fields().ByName("c") + fd_TestVersion4LoneNesting_d = md_TestVersion4LoneNesting.Fields().ByName("d") + fd_TestVersion4LoneNesting_f = md_TestVersion4LoneNesting.Fields().ByName("f") + fd_TestVersion4LoneNesting_g = md_TestVersion4LoneNesting.Fields().ByName("g") + fd_TestVersion4LoneNesting_h = md_TestVersion4LoneNesting.Fields().ByName("h") + fd_TestVersion4LoneNesting_k = md_TestVersion4LoneNesting.Fields().ByName("k") + fd_TestVersion4LoneNesting_non_critical_field = md_TestVersion4LoneNesting.Fields().ByName("non_critical_field") + fd_TestVersion4LoneNesting_inner1 = md_TestVersion4LoneNesting.Fields().ByName("inner1") + fd_TestVersion4LoneNesting_inner2 = md_TestVersion4LoneNesting.Fields().ByName("inner2") +} + +var _ protoreflect.Message = (*fastReflection_TestVersion4LoneNesting)(nil) + +type fastReflection_TestVersion4LoneNesting TestVersion4LoneNesting + +func (x *TestVersion4LoneNesting) ProtoReflect() protoreflect.Message { + return (*fastReflection_TestVersion4LoneNesting)(x) +} + +func (x *TestVersion4LoneNesting) slowProtoReflect() protoreflect.Message { + mi := &file_unknownproto_proto_msgTypes[16] + if protoimpl.UnsafeEnabled && x != nil { + ms := protoimpl.X.MessageStateOf(protoimpl.Pointer(x)) + if ms.LoadMessageInfo() == nil { + ms.StoreMessageInfo(mi) + } + return ms + } + return mi.MessageOf(x) +} + +var _fastReflection_TestVersion4LoneNesting_messageType fastReflection_TestVersion4LoneNesting_messageType +var _ protoreflect.MessageType = fastReflection_TestVersion4LoneNesting_messageType{} + +type fastReflection_TestVersion4LoneNesting_messageType struct{} + +func (x fastReflection_TestVersion4LoneNesting_messageType) Zero() protoreflect.Message { + return (*fastReflection_TestVersion4LoneNesting)(nil) +} +func (x fastReflection_TestVersion4LoneNesting_messageType) New() protoreflect.Message { + return new(fastReflection_TestVersion4LoneNesting) +} +func (x fastReflection_TestVersion4LoneNesting_messageType) Descriptor() protoreflect.MessageDescriptor { + return md_TestVersion4LoneNesting +} + +// Descriptor returns message descriptor, which contains only the protobuf +// type information for the message. +func (x *fastReflection_TestVersion4LoneNesting) Descriptor() protoreflect.MessageDescriptor { + return md_TestVersion4LoneNesting +} + +// Type returns the message type, which encapsulates both Go and protobuf +// type information. If the Go type information is not needed, +// it is recommended that the message descriptor be used instead. +func (x *fastReflection_TestVersion4LoneNesting) Type() protoreflect.MessageType { + return _fastReflection_TestVersion4LoneNesting_messageType +} + +// New returns a newly allocated and mutable empty message. +func (x *fastReflection_TestVersion4LoneNesting) New() protoreflect.Message { + return new(fastReflection_TestVersion4LoneNesting) +} + +// Interface unwraps the message reflection interface and +// returns the underlying ProtoMessage interface. +func (x *fastReflection_TestVersion4LoneNesting) Interface() protoreflect.ProtoMessage { + return (*TestVersion4LoneNesting)(x) +} + +// Range iterates over every populated field in an undefined order, +// calling f for each field descriptor and value encountered. +// Range returns immediately if f returns false. +// While iterating, mutating operations may only be performed +// on the current field descriptor. +func (x *fastReflection_TestVersion4LoneNesting) Range(f func(protoreflect.FieldDescriptor, protoreflect.Value) bool) { + if x.X != int64(0) { + value := protoreflect.ValueOfInt64(x.X) + if !f(fd_TestVersion4LoneNesting_x, value) { + return + } + } + if x.A != nil { + value := protoreflect.ValueOfMessage(x.A.ProtoReflect()) + if !f(fd_TestVersion4LoneNesting_a, value) { + return + } + } + if x.B != nil { + value := protoreflect.ValueOfMessage(x.B.ProtoReflect()) + if !f(fd_TestVersion4LoneNesting_b, value) { + return + } + } + if len(x.C) != 0 { + value := protoreflect.ValueOfList(&_TestVersion4LoneNesting_4_list{list: &x.C}) + if !f(fd_TestVersion4LoneNesting_c, value) { + return + } + } + if len(x.D) != 0 { + value := protoreflect.ValueOfList(&_TestVersion4LoneNesting_5_list{list: &x.D}) + if !f(fd_TestVersion4LoneNesting_d, value) { + return + } + } + if x.Sum != nil { + switch o := x.Sum.(type) { + case *TestVersion4LoneNesting_F: + v := o.F + value := protoreflect.ValueOfMessage(v.ProtoReflect()) + if !f(fd_TestVersion4LoneNesting_f, value) { + return + } + } + } + if x.G != nil { + value := protoreflect.ValueOfMessage(x.G.ProtoReflect()) + if !f(fd_TestVersion4LoneNesting_g, value) { + return + } + } + if len(x.H) != 0 { + value := protoreflect.ValueOfList(&_TestVersion4LoneNesting_9_list{list: &x.H}) + if !f(fd_TestVersion4LoneNesting_h, value) { + return + } + } + if x.K != nil { + value := protoreflect.ValueOfMessage(x.K.ProtoReflect()) + if !f(fd_TestVersion4LoneNesting_k, value) { + return + } + } + if x.NonCriticalField != "" { + value := protoreflect.ValueOfString(x.NonCriticalField) + if !f(fd_TestVersion4LoneNesting_non_critical_field, value) { + return + } + } + if x.Inner1 != nil { + value := protoreflect.ValueOfMessage(x.Inner1.ProtoReflect()) + if !f(fd_TestVersion4LoneNesting_inner1, value) { + return + } + } + if x.Inner2 != nil { + value := protoreflect.ValueOfMessage(x.Inner2.ProtoReflect()) + if !f(fd_TestVersion4LoneNesting_inner2, value) { + return + } + } +} + +// Has reports whether a field is populated. +// +// Some fields have the property of nullability where it is possible to +// distinguish between the default value of a field and whether the field +// was explicitly populated with the default value. Singular message fields, +// member fields of a oneof, and proto2 scalar fields are nullable. Such +// fields are populated only if explicitly set. +// +// In other cases (aside from the nullable cases above), +// a proto3 scalar field is populated if it contains a non-zero value, and +// a repeated field is populated if it is non-empty. +func (x *fastReflection_TestVersion4LoneNesting) Has(fd protoreflect.FieldDescriptor) bool { + switch fd.FullName() { + case "testpb.TestVersion4LoneNesting.x": + return x.X != int64(0) + case "testpb.TestVersion4LoneNesting.a": + return x.A != nil + case "testpb.TestVersion4LoneNesting.b": + return x.B != nil + case "testpb.TestVersion4LoneNesting.c": + return len(x.C) != 0 + case "testpb.TestVersion4LoneNesting.d": + return len(x.D) != 0 + case "testpb.TestVersion4LoneNesting.f": + if x.Sum == nil { + return false + } else if _, ok := x.Sum.(*TestVersion4LoneNesting_F); ok { + return true + } else { + return false + } + case "testpb.TestVersion4LoneNesting.g": + return x.G != nil + case "testpb.TestVersion4LoneNesting.h": + return len(x.H) != 0 + case "testpb.TestVersion4LoneNesting.k": + return x.K != nil + case "testpb.TestVersion4LoneNesting.non_critical_field": + return x.NonCriticalField != "" + case "testpb.TestVersion4LoneNesting.inner1": + return x.Inner1 != nil + case "testpb.TestVersion4LoneNesting.inner2": + return x.Inner2 != nil + default: + if fd.IsExtension() { + panic(fmt.Errorf("proto3 declared messages do not support extensions: testpb.TestVersion4LoneNesting")) + } + panic(fmt.Errorf("message testpb.TestVersion4LoneNesting does not contain field %s", fd.FullName())) + } +} + +// Clear clears the field such that a subsequent Has call reports false. +// +// Clearing an extension field clears both the extension type and value +// associated with the given field number. +// +// Clear is a mutating operation and unsafe for concurrent use. +func (x *fastReflection_TestVersion4LoneNesting) Clear(fd protoreflect.FieldDescriptor) { + switch fd.FullName() { + case "testpb.TestVersion4LoneNesting.x": + x.X = int64(0) + case "testpb.TestVersion4LoneNesting.a": + x.A = nil + case "testpb.TestVersion4LoneNesting.b": + x.B = nil + case "testpb.TestVersion4LoneNesting.c": + x.C = nil + case "testpb.TestVersion4LoneNesting.d": + x.D = nil + case "testpb.TestVersion4LoneNesting.f": + x.Sum = nil + case "testpb.TestVersion4LoneNesting.g": + x.G = nil + case "testpb.TestVersion4LoneNesting.h": + x.H = nil + case "testpb.TestVersion4LoneNesting.k": + x.K = nil + case "testpb.TestVersion4LoneNesting.non_critical_field": + x.NonCriticalField = "" + case "testpb.TestVersion4LoneNesting.inner1": + x.Inner1 = nil + case "testpb.TestVersion4LoneNesting.inner2": + x.Inner2 = nil + default: + if fd.IsExtension() { + panic(fmt.Errorf("proto3 declared messages do not support extensions: testpb.TestVersion4LoneNesting")) + } + panic(fmt.Errorf("message testpb.TestVersion4LoneNesting does not contain field %s", fd.FullName())) + } +} + +// Get retrieves the value for a field. +// +// For unpopulated scalars, it returns the default value, where +// the default value of a bytes scalar is guaranteed to be a copy. +// For unpopulated composite types, it returns an empty, read-only view +// of the value; to obtain a mutable reference, use Mutable. +func (x *fastReflection_TestVersion4LoneNesting) Get(descriptor protoreflect.FieldDescriptor) protoreflect.Value { + switch descriptor.FullName() { + case "testpb.TestVersion4LoneNesting.x": + value := x.X + return protoreflect.ValueOfInt64(value) + case "testpb.TestVersion4LoneNesting.a": + value := x.A + return protoreflect.ValueOfMessage(value.ProtoReflect()) + case "testpb.TestVersion4LoneNesting.b": + value := x.B + return protoreflect.ValueOfMessage(value.ProtoReflect()) + case "testpb.TestVersion4LoneNesting.c": + if len(x.C) == 0 { + return protoreflect.ValueOfList(&_TestVersion4LoneNesting_4_list{}) + } + listValue := &_TestVersion4LoneNesting_4_list{list: &x.C} + return protoreflect.ValueOfList(listValue) + case "testpb.TestVersion4LoneNesting.d": + if len(x.D) == 0 { + return protoreflect.ValueOfList(&_TestVersion4LoneNesting_5_list{}) + } + listValue := &_TestVersion4LoneNesting_5_list{list: &x.D} + return protoreflect.ValueOfList(listValue) + case "testpb.TestVersion4LoneNesting.f": + if x.Sum == nil { + return protoreflect.ValueOfMessage((*TestVersion3LoneNesting)(nil).ProtoReflect()) + } else if v, ok := x.Sum.(*TestVersion4LoneNesting_F); ok { + return protoreflect.ValueOfMessage(v.F.ProtoReflect()) + } else { + return protoreflect.ValueOfMessage((*TestVersion3LoneNesting)(nil).ProtoReflect()) + } + case "testpb.TestVersion4LoneNesting.g": + value := x.G + return protoreflect.ValueOfMessage(value.ProtoReflect()) + case "testpb.TestVersion4LoneNesting.h": + if len(x.H) == 0 { + return protoreflect.ValueOfList(&_TestVersion4LoneNesting_9_list{}) + } + listValue := &_TestVersion4LoneNesting_9_list{list: &x.H} + return protoreflect.ValueOfList(listValue) + case "testpb.TestVersion4LoneNesting.k": + value := x.K + return protoreflect.ValueOfMessage(value.ProtoReflect()) + case "testpb.TestVersion4LoneNesting.non_critical_field": + value := x.NonCriticalField + return protoreflect.ValueOfString(value) + case "testpb.TestVersion4LoneNesting.inner1": + value := x.Inner1 + return protoreflect.ValueOfMessage(value.ProtoReflect()) + case "testpb.TestVersion4LoneNesting.inner2": + value := x.Inner2 + return protoreflect.ValueOfMessage(value.ProtoReflect()) + default: + if descriptor.IsExtension() { + panic(fmt.Errorf("proto3 declared messages do not support extensions: testpb.TestVersion4LoneNesting")) + } + panic(fmt.Errorf("message testpb.TestVersion4LoneNesting does not contain field %s", descriptor.FullName())) + } +} + +// Set stores the value for a field. +// +// For a field belonging to a oneof, it implicitly clears any other field +// that may be currently set within the same oneof. +// For extension fields, it implicitly stores the provided ExtensionType. +// When setting a composite type, it is unspecified whether the stored value +// aliases the source's memory in any way. If the composite value is an +// empty, read-only value, then it panics. +// +// Set is a mutating operation and unsafe for concurrent use. +func (x *fastReflection_TestVersion4LoneNesting) Set(fd protoreflect.FieldDescriptor, value protoreflect.Value) { + switch fd.FullName() { + case "testpb.TestVersion4LoneNesting.x": + x.X = value.Int() + case "testpb.TestVersion4LoneNesting.a": + x.A = value.Message().Interface().(*TestVersion3) + case "testpb.TestVersion4LoneNesting.b": + x.B = value.Message().Interface().(*TestVersion3) + case "testpb.TestVersion4LoneNesting.c": + lv := value.List() + clv := lv.(*_TestVersion4LoneNesting_4_list) + x.C = *clv.list + case "testpb.TestVersion4LoneNesting.d": + lv := value.List() + clv := lv.(*_TestVersion4LoneNesting_5_list) + x.D = *clv.list + case "testpb.TestVersion4LoneNesting.f": + cv := value.Message().Interface().(*TestVersion3LoneNesting) + x.Sum = &TestVersion4LoneNesting_F{F: cv} + case "testpb.TestVersion4LoneNesting.g": + x.G = value.Message().Interface().(*anypb.Any) + case "testpb.TestVersion4LoneNesting.h": + lv := value.List() + clv := lv.(*_TestVersion4LoneNesting_9_list) + x.H = *clv.list + case "testpb.TestVersion4LoneNesting.k": + x.K = value.Message().Interface().(*Customer1) + case "testpb.TestVersion4LoneNesting.non_critical_field": + x.NonCriticalField = value.Interface().(string) + case "testpb.TestVersion4LoneNesting.inner1": + x.Inner1 = value.Message().Interface().(*TestVersion4LoneNesting_Inner1) + case "testpb.TestVersion4LoneNesting.inner2": + x.Inner2 = value.Message().Interface().(*TestVersion4LoneNesting_Inner2) + default: + if fd.IsExtension() { + panic(fmt.Errorf("proto3 declared messages do not support extensions: testpb.TestVersion4LoneNesting")) + } + panic(fmt.Errorf("message testpb.TestVersion4LoneNesting does not contain field %s", fd.FullName())) + } +} + +// Mutable returns a mutable reference to a composite type. +// +// If the field is unpopulated, it may allocate a composite value. +// For a field belonging to a oneof, it implicitly clears any other field +// that may be currently set within the same oneof. +// For extension fields, it implicitly stores the provided ExtensionType +// if not already stored. +// It panics if the field does not contain a composite type. +// +// Mutable is a mutating operation and unsafe for concurrent use. +func (x *fastReflection_TestVersion4LoneNesting) Mutable(fd protoreflect.FieldDescriptor) protoreflect.Value { + switch fd.FullName() { + case "testpb.TestVersion4LoneNesting.a": + if x.A == nil { + x.A = new(TestVersion3) + } + return protoreflect.ValueOfMessage(x.A.ProtoReflect()) + case "testpb.TestVersion4LoneNesting.b": + if x.B == nil { + x.B = new(TestVersion3) + } + return protoreflect.ValueOfMessage(x.B.ProtoReflect()) + case "testpb.TestVersion4LoneNesting.c": + if x.C == nil { + x.C = []*TestVersion3{} + } + value := &_TestVersion4LoneNesting_4_list{list: &x.C} + return protoreflect.ValueOfList(value) + case "testpb.TestVersion4LoneNesting.d": + if x.D == nil { + x.D = []*TestVersion3{} + } + value := &_TestVersion4LoneNesting_5_list{list: &x.D} + return protoreflect.ValueOfList(value) + case "testpb.TestVersion4LoneNesting.f": + if x.Sum == nil { + value := &TestVersion3LoneNesting{} + oneofValue := &TestVersion4LoneNesting_F{F: value} + x.Sum = oneofValue + return protoreflect.ValueOfMessage(value.ProtoReflect()) + } + switch m := x.Sum.(type) { + case *TestVersion4LoneNesting_F: + return protoreflect.ValueOfMessage(m.F.ProtoReflect()) + default: + value := &TestVersion3LoneNesting{} + oneofValue := &TestVersion4LoneNesting_F{F: value} + x.Sum = oneofValue + return protoreflect.ValueOfMessage(value.ProtoReflect()) + } + case "testpb.TestVersion4LoneNesting.g": + if x.G == nil { + x.G = new(anypb.Any) + } + return protoreflect.ValueOfMessage(x.G.ProtoReflect()) + case "testpb.TestVersion4LoneNesting.h": + if x.H == nil { + x.H = []*TestVersion1{} + } + value := &_TestVersion4LoneNesting_9_list{list: &x.H} + return protoreflect.ValueOfList(value) + case "testpb.TestVersion4LoneNesting.k": + if x.K == nil { + x.K = new(Customer1) + } + return protoreflect.ValueOfMessage(x.K.ProtoReflect()) + case "testpb.TestVersion4LoneNesting.inner1": + if x.Inner1 == nil { + x.Inner1 = new(TestVersion4LoneNesting_Inner1) + } + return protoreflect.ValueOfMessage(x.Inner1.ProtoReflect()) + case "testpb.TestVersion4LoneNesting.inner2": + if x.Inner2 == nil { + x.Inner2 = new(TestVersion4LoneNesting_Inner2) + } + return protoreflect.ValueOfMessage(x.Inner2.ProtoReflect()) + case "testpb.TestVersion4LoneNesting.x": + panic(fmt.Errorf("field x of message testpb.TestVersion4LoneNesting is not mutable")) + case "testpb.TestVersion4LoneNesting.non_critical_field": + panic(fmt.Errorf("field non_critical_field of message testpb.TestVersion4LoneNesting is not mutable")) + default: + if fd.IsExtension() { + panic(fmt.Errorf("proto3 declared messages do not support extensions: testpb.TestVersion4LoneNesting")) + } + panic(fmt.Errorf("message testpb.TestVersion4LoneNesting does not contain field %s", fd.FullName())) + } +} + +// NewField returns a new value that is assignable to the field +// for the given descriptor. For scalars, this returns the default value. +// For lists, maps, and messages, this returns a new, empty, mutable value. +func (x *fastReflection_TestVersion4LoneNesting) NewField(fd protoreflect.FieldDescriptor) protoreflect.Value { + switch fd.FullName() { + case "testpb.TestVersion4LoneNesting.x": + return protoreflect.ValueOfInt64(int64(0)) + case "testpb.TestVersion4LoneNesting.a": + m := new(TestVersion3) + return protoreflect.ValueOfMessage(m.ProtoReflect()) + case "testpb.TestVersion4LoneNesting.b": + m := new(TestVersion3) + return protoreflect.ValueOfMessage(m.ProtoReflect()) + case "testpb.TestVersion4LoneNesting.c": + list := []*TestVersion3{} + return protoreflect.ValueOfList(&_TestVersion4LoneNesting_4_list{list: &list}) + case "testpb.TestVersion4LoneNesting.d": + list := []*TestVersion3{} + return protoreflect.ValueOfList(&_TestVersion4LoneNesting_5_list{list: &list}) + case "testpb.TestVersion4LoneNesting.f": + value := &TestVersion3LoneNesting{} + return protoreflect.ValueOfMessage(value.ProtoReflect()) + case "testpb.TestVersion4LoneNesting.g": + m := new(anypb.Any) + return protoreflect.ValueOfMessage(m.ProtoReflect()) + case "testpb.TestVersion4LoneNesting.h": + list := []*TestVersion1{} + return protoreflect.ValueOfList(&_TestVersion4LoneNesting_9_list{list: &list}) + case "testpb.TestVersion4LoneNesting.k": + m := new(Customer1) + return protoreflect.ValueOfMessage(m.ProtoReflect()) + case "testpb.TestVersion4LoneNesting.non_critical_field": + return protoreflect.ValueOfString("") + case "testpb.TestVersion4LoneNesting.inner1": + m := new(TestVersion4LoneNesting_Inner1) + return protoreflect.ValueOfMessage(m.ProtoReflect()) + case "testpb.TestVersion4LoneNesting.inner2": + m := new(TestVersion4LoneNesting_Inner2) + return protoreflect.ValueOfMessage(m.ProtoReflect()) + default: + if fd.IsExtension() { + panic(fmt.Errorf("proto3 declared messages do not support extensions: testpb.TestVersion4LoneNesting")) + } + panic(fmt.Errorf("message testpb.TestVersion4LoneNesting does not contain field %s", fd.FullName())) + } +} + +// WhichOneof reports which field within the oneof is populated, +// returning nil if none are populated. +// It panics if the oneof descriptor does not belong to this message. +func (x *fastReflection_TestVersion4LoneNesting) WhichOneof(d protoreflect.OneofDescriptor) protoreflect.FieldDescriptor { + switch d.FullName() { + case "testpb.TestVersion4LoneNesting.sum": + if x.Sum == nil { + return nil + } + switch x.Sum.(type) { + case *TestVersion4LoneNesting_F: + return x.Descriptor().Fields().ByName("f") + } + default: + panic(fmt.Errorf("%s is not a oneof field in testpb.TestVersion4LoneNesting", d.FullName())) + } + panic("unreachable") +} + +// GetUnknown retrieves the entire list of unknown fields. +// The caller may only mutate the contents of the RawFields +// if the mutated bytes are stored back into the message with SetUnknown. +func (x *fastReflection_TestVersion4LoneNesting) GetUnknown() protoreflect.RawFields { + return x.unknownFields +} + +// SetUnknown stores an entire list of unknown fields. +// The raw fields must be syntactically valid according to the wire format. +// An implementation may panic if this is not the case. +// Once stored, the caller must not mutate the content of the RawFields. +// An empty RawFields may be passed to clear the fields. +// +// SetUnknown is a mutating operation and unsafe for concurrent use. +func (x *fastReflection_TestVersion4LoneNesting) SetUnknown(fields protoreflect.RawFields) { + x.unknownFields = fields +} + +// IsValid reports whether the message is valid. +// +// An invalid message is an empty, read-only value. +// +// An invalid message often corresponds to a nil pointer of the concrete +// message type, but the details are implementation dependent. +// Validity is not part of the protobuf data model, and may not +// be preserved in marshaling or other operations. +func (x *fastReflection_TestVersion4LoneNesting) IsValid() bool { + return x != nil +} + +// ProtoMethods returns optional fastReflectionFeature-path implementations of various operations. +// This method may return nil. +// +// The returned methods type is identical to +// "google.golang.org/protobuf/runtime/protoiface".Methods. +// Consult the protoiface package documentation for details. +func (x *fastReflection_TestVersion4LoneNesting) ProtoMethods() *protoiface.Methods { + size := func(input protoiface.SizeInput) protoiface.SizeOutput { + x := input.Message.Interface().(*TestVersion4LoneNesting) + if x == nil { + return protoiface.SizeOutput{ + NoUnkeyedLiterals: input.NoUnkeyedLiterals, + Size: 0, + } + } + options := runtime.SizeInputToOptions(input) + _ = options + var n int + var l int + _ = l + if x.X != 0 { + n += 1 + runtime.Sov(uint64(x.X)) + } + if x.A != nil { + l = options.Size(x.A) + n += 1 + l + runtime.Sov(uint64(l)) + } + if x.B != nil { + l = options.Size(x.B) + n += 1 + l + runtime.Sov(uint64(l)) + } + if len(x.C) > 0 { + for _, e := range x.C { + l = options.Size(e) + n += 1 + l + runtime.Sov(uint64(l)) + } + } + if len(x.D) > 0 { + for _, e := range x.D { + l = options.Size(e) + n += 1 + l + runtime.Sov(uint64(l)) + } + } + switch x := x.Sum.(type) { + case *TestVersion4LoneNesting_F: + if x == nil { + break + } + l = options.Size(x.F) + n += 1 + l + runtime.Sov(uint64(l)) + } + if x.G != nil { + l = options.Size(x.G) + n += 1 + l + runtime.Sov(uint64(l)) + } + if len(x.H) > 0 { + for _, e := range x.H { + l = options.Size(e) + n += 1 + l + runtime.Sov(uint64(l)) + } + } + if x.K != nil { + l = options.Size(x.K) + n += 1 + l + runtime.Sov(uint64(l)) + } + l = len(x.NonCriticalField) + if l > 0 { + n += 2 + l + runtime.Sov(uint64(l)) + } + if x.Inner1 != nil { + l = options.Size(x.Inner1) + n += 1 + l + runtime.Sov(uint64(l)) + } + if x.Inner2 != nil { + l = options.Size(x.Inner2) + n += 1 + l + runtime.Sov(uint64(l)) + } + if x.unknownFields != nil { + n += len(x.unknownFields) + } + return protoiface.SizeOutput{ + NoUnkeyedLiterals: input.NoUnkeyedLiterals, + Size: n, + } + } + + marshal := func(input protoiface.MarshalInput) (protoiface.MarshalOutput, error) { + x := input.Message.Interface().(*TestVersion4LoneNesting) + if x == nil { + return protoiface.MarshalOutput{ + NoUnkeyedLiterals: input.NoUnkeyedLiterals, + Buf: input.Buf, + }, nil + } + options := runtime.MarshalInputToOptions(input) + _ = options + size := options.Size(x) + dAtA := make([]byte, size) + i := len(dAtA) + _ = i + var l int + _ = l + if x.unknownFields != nil { + i -= len(x.unknownFields) + copy(dAtA[i:], x.unknownFields) + } + switch x := x.Sum.(type) { + case *TestVersion4LoneNesting_F: + encoded, err := options.Marshal(x.F) + if err != nil { + return protoiface.MarshalOutput{ + NoUnkeyedLiterals: input.NoUnkeyedLiterals, + Buf: input.Buf, + }, err + } + i -= len(encoded) + copy(dAtA[i:], encoded) + i = runtime.EncodeVarint(dAtA, i, uint64(len(encoded))) + i-- + dAtA[i] = 0x3a + } + if len(x.NonCriticalField) > 0 { + i -= len(x.NonCriticalField) + copy(dAtA[i:], x.NonCriticalField) + i = runtime.EncodeVarint(dAtA, i, uint64(len(x.NonCriticalField))) + i-- + dAtA[i] = 0x40 + i-- + dAtA[i] = 0xba + } + if x.Inner2 != nil { + encoded, err := options.Marshal(x.Inner2) + if err != nil { + return protoiface.MarshalOutput{ + NoUnkeyedLiterals: input.NoUnkeyedLiterals, + Buf: input.Buf, + }, err + } + i -= len(encoded) + copy(dAtA[i:], encoded) + i = runtime.EncodeVarint(dAtA, i, uint64(len(encoded))) + i-- + dAtA[i] = 0x7a + } + if x.Inner1 != nil { + encoded, err := options.Marshal(x.Inner1) + if err != nil { + return protoiface.MarshalOutput{ + NoUnkeyedLiterals: input.NoUnkeyedLiterals, + Buf: input.Buf, + }, err + } + i -= len(encoded) + copy(dAtA[i:], encoded) + i = runtime.EncodeVarint(dAtA, i, uint64(len(encoded))) + i-- + dAtA[i] = 0x72 + } + if x.K != nil { + encoded, err := options.Marshal(x.K) + if err != nil { + return protoiface.MarshalOutput{ + NoUnkeyedLiterals: input.NoUnkeyedLiterals, + Buf: input.Buf, + }, err + } + i -= len(encoded) + copy(dAtA[i:], encoded) + i = runtime.EncodeVarint(dAtA, i, uint64(len(encoded))) + i-- + dAtA[i] = 0x62 + } + if len(x.H) > 0 { + for iNdEx := len(x.H) - 1; iNdEx >= 0; iNdEx-- { + encoded, err := options.Marshal(x.H[iNdEx]) + if err != nil { + return protoiface.MarshalOutput{ + NoUnkeyedLiterals: input.NoUnkeyedLiterals, + Buf: input.Buf, + }, err + } + i -= len(encoded) + copy(dAtA[i:], encoded) + i = runtime.EncodeVarint(dAtA, i, uint64(len(encoded))) + i-- + dAtA[i] = 0x4a + } + } + if x.G != nil { + encoded, err := options.Marshal(x.G) + if err != nil { + return protoiface.MarshalOutput{ + NoUnkeyedLiterals: input.NoUnkeyedLiterals, + Buf: input.Buf, + }, err + } + i -= len(encoded) + copy(dAtA[i:], encoded) + i = runtime.EncodeVarint(dAtA, i, uint64(len(encoded))) + i-- + dAtA[i] = 0x42 + } + if len(x.D) > 0 { + for iNdEx := len(x.D) - 1; iNdEx >= 0; iNdEx-- { + encoded, err := options.Marshal(x.D[iNdEx]) + if err != nil { + return protoiface.MarshalOutput{ + NoUnkeyedLiterals: input.NoUnkeyedLiterals, + Buf: input.Buf, + }, err + } + i -= len(encoded) + copy(dAtA[i:], encoded) + i = runtime.EncodeVarint(dAtA, i, uint64(len(encoded))) + i-- + dAtA[i] = 0x2a + } + } + if len(x.C) > 0 { + for iNdEx := len(x.C) - 1; iNdEx >= 0; iNdEx-- { + encoded, err := options.Marshal(x.C[iNdEx]) + if err != nil { + return protoiface.MarshalOutput{ + NoUnkeyedLiterals: input.NoUnkeyedLiterals, + Buf: input.Buf, + }, err + } + i -= len(encoded) + copy(dAtA[i:], encoded) + i = runtime.EncodeVarint(dAtA, i, uint64(len(encoded))) + i-- + dAtA[i] = 0x22 + } + } + if x.B != nil { + encoded, err := options.Marshal(x.B) + if err != nil { + return protoiface.MarshalOutput{ + NoUnkeyedLiterals: input.NoUnkeyedLiterals, + Buf: input.Buf, + }, err + } + i -= len(encoded) + copy(dAtA[i:], encoded) + i = runtime.EncodeVarint(dAtA, i, uint64(len(encoded))) + i-- + dAtA[i] = 0x1a + } + if x.A != nil { + encoded, err := options.Marshal(x.A) + if err != nil { + return protoiface.MarshalOutput{ + NoUnkeyedLiterals: input.NoUnkeyedLiterals, + Buf: input.Buf, + }, err + } + i -= len(encoded) + copy(dAtA[i:], encoded) + i = runtime.EncodeVarint(dAtA, i, uint64(len(encoded))) + i-- + dAtA[i] = 0x12 + } + if x.X != 0 { + i = runtime.EncodeVarint(dAtA, i, uint64(x.X)) + i-- + dAtA[i] = 0x8 + } + if input.Buf != nil { + input.Buf = append(input.Buf, dAtA...) + } else { + input.Buf = dAtA + } + return protoiface.MarshalOutput{ + NoUnkeyedLiterals: input.NoUnkeyedLiterals, + Buf: input.Buf, + }, nil + } + unmarshal := func(input protoiface.UnmarshalInput) (protoiface.UnmarshalOutput, error) { + x := input.Message.Interface().(*TestVersion4LoneNesting) + if x == nil { + return protoiface.UnmarshalOutput{ + NoUnkeyedLiterals: input.NoUnkeyedLiterals, + Flags: input.Flags, + }, nil + } + options := runtime.UnmarshalInputToOptions(input) + _ = options + dAtA := input.Buf + l := len(dAtA) + iNdEx := 0 + for iNdEx < l { + preIndex := iNdEx + var wire uint64 + for shift := uint(0); ; shift += 7 { + if shift >= 64 { + return protoiface.UnmarshalOutput{NoUnkeyedLiterals: input.NoUnkeyedLiterals, Flags: input.Flags}, runtime.ErrIntOverflow + } + if iNdEx >= l { + return protoiface.UnmarshalOutput{NoUnkeyedLiterals: input.NoUnkeyedLiterals, Flags: input.Flags}, io.ErrUnexpectedEOF + } + b := dAtA[iNdEx] + iNdEx++ + wire |= uint64(b&0x7F) << shift + if b < 0x80 { + break + } + } + fieldNum := int32(wire >> 3) + wireType := int(wire & 0x7) + if wireType == 4 { + return protoiface.UnmarshalOutput{NoUnkeyedLiterals: input.NoUnkeyedLiterals, Flags: input.Flags}, fmt.Errorf("proto: TestVersion4LoneNesting: wiretype end group for non-group") + } + if fieldNum <= 0 { + return protoiface.UnmarshalOutput{NoUnkeyedLiterals: input.NoUnkeyedLiterals, Flags: input.Flags}, fmt.Errorf("proto: TestVersion4LoneNesting: illegal tag %d (wire type %d)", fieldNum, wire) + } + switch fieldNum { + case 1: + if wireType != 0 { + return protoiface.UnmarshalOutput{NoUnkeyedLiterals: input.NoUnkeyedLiterals, Flags: input.Flags}, fmt.Errorf("proto: wrong wireType = %d for field X", wireType) + } + x.X = 0 + for shift := uint(0); ; shift += 7 { + if shift >= 64 { + return protoiface.UnmarshalOutput{NoUnkeyedLiterals: input.NoUnkeyedLiterals, Flags: input.Flags}, runtime.ErrIntOverflow + } + if iNdEx >= l { + return protoiface.UnmarshalOutput{NoUnkeyedLiterals: input.NoUnkeyedLiterals, Flags: input.Flags}, io.ErrUnexpectedEOF + } + b := dAtA[iNdEx] + iNdEx++ + x.X |= int64(b&0x7F) << shift + if b < 0x80 { + break + } + } + case 2: + if wireType != 2 { + return protoiface.UnmarshalOutput{NoUnkeyedLiterals: input.NoUnkeyedLiterals, Flags: input.Flags}, fmt.Errorf("proto: wrong wireType = %d for field A", wireType) + } + var msglen int + for shift := uint(0); ; shift += 7 { + if shift >= 64 { + return protoiface.UnmarshalOutput{NoUnkeyedLiterals: input.NoUnkeyedLiterals, Flags: input.Flags}, runtime.ErrIntOverflow + } + if iNdEx >= l { + return protoiface.UnmarshalOutput{NoUnkeyedLiterals: input.NoUnkeyedLiterals, Flags: input.Flags}, io.ErrUnexpectedEOF + } + b := dAtA[iNdEx] + iNdEx++ + msglen |= int(b&0x7F) << shift + if b < 0x80 { + break + } + } + if msglen < 0 { + return protoiface.UnmarshalOutput{NoUnkeyedLiterals: input.NoUnkeyedLiterals, Flags: input.Flags}, runtime.ErrInvalidLength + } + postIndex := iNdEx + msglen + if postIndex < 0 { + return protoiface.UnmarshalOutput{NoUnkeyedLiterals: input.NoUnkeyedLiterals, Flags: input.Flags}, runtime.ErrInvalidLength + } + if postIndex > l { + return protoiface.UnmarshalOutput{NoUnkeyedLiterals: input.NoUnkeyedLiterals, Flags: input.Flags}, io.ErrUnexpectedEOF + } + if x.A == nil { + x.A = &TestVersion3{} + } + if err := options.Unmarshal(dAtA[iNdEx:postIndex], x.A); err != nil { + return protoiface.UnmarshalOutput{NoUnkeyedLiterals: input.NoUnkeyedLiterals, Flags: input.Flags}, err + } + iNdEx = postIndex + case 3: + if wireType != 2 { + return protoiface.UnmarshalOutput{NoUnkeyedLiterals: input.NoUnkeyedLiterals, Flags: input.Flags}, fmt.Errorf("proto: wrong wireType = %d for field B", wireType) + } + var msglen int + for shift := uint(0); ; shift += 7 { + if shift >= 64 { + return protoiface.UnmarshalOutput{NoUnkeyedLiterals: input.NoUnkeyedLiterals, Flags: input.Flags}, runtime.ErrIntOverflow + } + if iNdEx >= l { + return protoiface.UnmarshalOutput{NoUnkeyedLiterals: input.NoUnkeyedLiterals, Flags: input.Flags}, io.ErrUnexpectedEOF + } + b := dAtA[iNdEx] + iNdEx++ + msglen |= int(b&0x7F) << shift + if b < 0x80 { + break + } + } + if msglen < 0 { + return protoiface.UnmarshalOutput{NoUnkeyedLiterals: input.NoUnkeyedLiterals, Flags: input.Flags}, runtime.ErrInvalidLength + } + postIndex := iNdEx + msglen + if postIndex < 0 { + return protoiface.UnmarshalOutput{NoUnkeyedLiterals: input.NoUnkeyedLiterals, Flags: input.Flags}, runtime.ErrInvalidLength + } + if postIndex > l { + return protoiface.UnmarshalOutput{NoUnkeyedLiterals: input.NoUnkeyedLiterals, Flags: input.Flags}, io.ErrUnexpectedEOF + } + if x.B == nil { + x.B = &TestVersion3{} + } + if err := options.Unmarshal(dAtA[iNdEx:postIndex], x.B); err != nil { + return protoiface.UnmarshalOutput{NoUnkeyedLiterals: input.NoUnkeyedLiterals, Flags: input.Flags}, err + } + iNdEx = postIndex + case 4: + if wireType != 2 { + return protoiface.UnmarshalOutput{NoUnkeyedLiterals: input.NoUnkeyedLiterals, Flags: input.Flags}, fmt.Errorf("proto: wrong wireType = %d for field C", wireType) + } + var msglen int + for shift := uint(0); ; shift += 7 { + if shift >= 64 { + return protoiface.UnmarshalOutput{NoUnkeyedLiterals: input.NoUnkeyedLiterals, Flags: input.Flags}, runtime.ErrIntOverflow + } + if iNdEx >= l { + return protoiface.UnmarshalOutput{NoUnkeyedLiterals: input.NoUnkeyedLiterals, Flags: input.Flags}, io.ErrUnexpectedEOF + } + b := dAtA[iNdEx] + iNdEx++ + msglen |= int(b&0x7F) << shift + if b < 0x80 { + break + } + } + if msglen < 0 { + return protoiface.UnmarshalOutput{NoUnkeyedLiterals: input.NoUnkeyedLiterals, Flags: input.Flags}, runtime.ErrInvalidLength + } + postIndex := iNdEx + msglen + if postIndex < 0 { + return protoiface.UnmarshalOutput{NoUnkeyedLiterals: input.NoUnkeyedLiterals, Flags: input.Flags}, runtime.ErrInvalidLength + } + if postIndex > l { + return protoiface.UnmarshalOutput{NoUnkeyedLiterals: input.NoUnkeyedLiterals, Flags: input.Flags}, io.ErrUnexpectedEOF + } + x.C = append(x.C, &TestVersion3{}) + if err := options.Unmarshal(dAtA[iNdEx:postIndex], x.C[len(x.C)-1]); err != nil { + return protoiface.UnmarshalOutput{NoUnkeyedLiterals: input.NoUnkeyedLiterals, Flags: input.Flags}, err + } + iNdEx = postIndex + case 5: + if wireType != 2 { + return protoiface.UnmarshalOutput{NoUnkeyedLiterals: input.NoUnkeyedLiterals, Flags: input.Flags}, fmt.Errorf("proto: wrong wireType = %d for field D", wireType) + } + var msglen int + for shift := uint(0); ; shift += 7 { + if shift >= 64 { + return protoiface.UnmarshalOutput{NoUnkeyedLiterals: input.NoUnkeyedLiterals, Flags: input.Flags}, runtime.ErrIntOverflow + } + if iNdEx >= l { + return protoiface.UnmarshalOutput{NoUnkeyedLiterals: input.NoUnkeyedLiterals, Flags: input.Flags}, io.ErrUnexpectedEOF + } + b := dAtA[iNdEx] + iNdEx++ + msglen |= int(b&0x7F) << shift + if b < 0x80 { + break + } + } + if msglen < 0 { + return protoiface.UnmarshalOutput{NoUnkeyedLiterals: input.NoUnkeyedLiterals, Flags: input.Flags}, runtime.ErrInvalidLength + } + postIndex := iNdEx + msglen + if postIndex < 0 { + return protoiface.UnmarshalOutput{NoUnkeyedLiterals: input.NoUnkeyedLiterals, Flags: input.Flags}, runtime.ErrInvalidLength + } + if postIndex > l { + return protoiface.UnmarshalOutput{NoUnkeyedLiterals: input.NoUnkeyedLiterals, Flags: input.Flags}, io.ErrUnexpectedEOF + } + x.D = append(x.D, &TestVersion3{}) + if err := options.Unmarshal(dAtA[iNdEx:postIndex], x.D[len(x.D)-1]); err != nil { + return protoiface.UnmarshalOutput{NoUnkeyedLiterals: input.NoUnkeyedLiterals, Flags: input.Flags}, err + } + iNdEx = postIndex + case 7: + if wireType != 2 { + return protoiface.UnmarshalOutput{NoUnkeyedLiterals: input.NoUnkeyedLiterals, Flags: input.Flags}, fmt.Errorf("proto: wrong wireType = %d for field F", wireType) + } + var msglen int + for shift := uint(0); ; shift += 7 { + if shift >= 64 { + return protoiface.UnmarshalOutput{NoUnkeyedLiterals: input.NoUnkeyedLiterals, Flags: input.Flags}, runtime.ErrIntOverflow + } + if iNdEx >= l { + return protoiface.UnmarshalOutput{NoUnkeyedLiterals: input.NoUnkeyedLiterals, Flags: input.Flags}, io.ErrUnexpectedEOF + } + b := dAtA[iNdEx] + iNdEx++ + msglen |= int(b&0x7F) << shift + if b < 0x80 { + break + } + } + if msglen < 0 { + return protoiface.UnmarshalOutput{NoUnkeyedLiterals: input.NoUnkeyedLiterals, Flags: input.Flags}, runtime.ErrInvalidLength + } + postIndex := iNdEx + msglen + if postIndex < 0 { + return protoiface.UnmarshalOutput{NoUnkeyedLiterals: input.NoUnkeyedLiterals, Flags: input.Flags}, runtime.ErrInvalidLength + } + if postIndex > l { + return protoiface.UnmarshalOutput{NoUnkeyedLiterals: input.NoUnkeyedLiterals, Flags: input.Flags}, io.ErrUnexpectedEOF + } + v := &TestVersion3LoneNesting{} + if err := options.Unmarshal(dAtA[iNdEx:postIndex], v); err != nil { + return protoiface.UnmarshalOutput{NoUnkeyedLiterals: input.NoUnkeyedLiterals, Flags: input.Flags}, err + } + x.Sum = &TestVersion4LoneNesting_F{v} + iNdEx = postIndex + case 8: + if wireType != 2 { + return protoiface.UnmarshalOutput{NoUnkeyedLiterals: input.NoUnkeyedLiterals, Flags: input.Flags}, fmt.Errorf("proto: wrong wireType = %d for field G", wireType) + } + var msglen int + for shift := uint(0); ; shift += 7 { + if shift >= 64 { + return protoiface.UnmarshalOutput{NoUnkeyedLiterals: input.NoUnkeyedLiterals, Flags: input.Flags}, runtime.ErrIntOverflow + } + if iNdEx >= l { + return protoiface.UnmarshalOutput{NoUnkeyedLiterals: input.NoUnkeyedLiterals, Flags: input.Flags}, io.ErrUnexpectedEOF + } + b := dAtA[iNdEx] + iNdEx++ + msglen |= int(b&0x7F) << shift + if b < 0x80 { + break + } + } + if msglen < 0 { + return protoiface.UnmarshalOutput{NoUnkeyedLiterals: input.NoUnkeyedLiterals, Flags: input.Flags}, runtime.ErrInvalidLength + } + postIndex := iNdEx + msglen + if postIndex < 0 { + return protoiface.UnmarshalOutput{NoUnkeyedLiterals: input.NoUnkeyedLiterals, Flags: input.Flags}, runtime.ErrInvalidLength + } + if postIndex > l { + return protoiface.UnmarshalOutput{NoUnkeyedLiterals: input.NoUnkeyedLiterals, Flags: input.Flags}, io.ErrUnexpectedEOF + } + if x.G == nil { + x.G = &anypb.Any{} + } + if err := options.Unmarshal(dAtA[iNdEx:postIndex], x.G); err != nil { + return protoiface.UnmarshalOutput{NoUnkeyedLiterals: input.NoUnkeyedLiterals, Flags: input.Flags}, err + } + iNdEx = postIndex + case 9: + if wireType != 2 { + return protoiface.UnmarshalOutput{NoUnkeyedLiterals: input.NoUnkeyedLiterals, Flags: input.Flags}, fmt.Errorf("proto: wrong wireType = %d for field H", wireType) + } + var msglen int + for shift := uint(0); ; shift += 7 { + if shift >= 64 { + return protoiface.UnmarshalOutput{NoUnkeyedLiterals: input.NoUnkeyedLiterals, Flags: input.Flags}, runtime.ErrIntOverflow + } + if iNdEx >= l { + return protoiface.UnmarshalOutput{NoUnkeyedLiterals: input.NoUnkeyedLiterals, Flags: input.Flags}, io.ErrUnexpectedEOF + } + b := dAtA[iNdEx] + iNdEx++ + msglen |= int(b&0x7F) << shift + if b < 0x80 { + break + } + } + if msglen < 0 { + return protoiface.UnmarshalOutput{NoUnkeyedLiterals: input.NoUnkeyedLiterals, Flags: input.Flags}, runtime.ErrInvalidLength + } + postIndex := iNdEx + msglen + if postIndex < 0 { + return protoiface.UnmarshalOutput{NoUnkeyedLiterals: input.NoUnkeyedLiterals, Flags: input.Flags}, runtime.ErrInvalidLength + } + if postIndex > l { + return protoiface.UnmarshalOutput{NoUnkeyedLiterals: input.NoUnkeyedLiterals, Flags: input.Flags}, io.ErrUnexpectedEOF + } + x.H = append(x.H, &TestVersion1{}) + if err := options.Unmarshal(dAtA[iNdEx:postIndex], x.H[len(x.H)-1]); err != nil { + return protoiface.UnmarshalOutput{NoUnkeyedLiterals: input.NoUnkeyedLiterals, Flags: input.Flags}, err + } + iNdEx = postIndex + case 12: + if wireType != 2 { + return protoiface.UnmarshalOutput{NoUnkeyedLiterals: input.NoUnkeyedLiterals, Flags: input.Flags}, fmt.Errorf("proto: wrong wireType = %d for field K", wireType) + } + var msglen int + for shift := uint(0); ; shift += 7 { + if shift >= 64 { + return protoiface.UnmarshalOutput{NoUnkeyedLiterals: input.NoUnkeyedLiterals, Flags: input.Flags}, runtime.ErrIntOverflow + } + if iNdEx >= l { + return protoiface.UnmarshalOutput{NoUnkeyedLiterals: input.NoUnkeyedLiterals, Flags: input.Flags}, io.ErrUnexpectedEOF + } + b := dAtA[iNdEx] + iNdEx++ + msglen |= int(b&0x7F) << shift + if b < 0x80 { + break + } + } + if msglen < 0 { + return protoiface.UnmarshalOutput{NoUnkeyedLiterals: input.NoUnkeyedLiterals, Flags: input.Flags}, runtime.ErrInvalidLength + } + postIndex := iNdEx + msglen + if postIndex < 0 { + return protoiface.UnmarshalOutput{NoUnkeyedLiterals: input.NoUnkeyedLiterals, Flags: input.Flags}, runtime.ErrInvalidLength + } + if postIndex > l { + return protoiface.UnmarshalOutput{NoUnkeyedLiterals: input.NoUnkeyedLiterals, Flags: input.Flags}, io.ErrUnexpectedEOF + } + if x.K == nil { + x.K = &Customer1{} + } + if err := options.Unmarshal(dAtA[iNdEx:postIndex], x.K); err != nil { + return protoiface.UnmarshalOutput{NoUnkeyedLiterals: input.NoUnkeyedLiterals, Flags: input.Flags}, err + } + iNdEx = postIndex + case 1031: + if wireType != 2 { + return protoiface.UnmarshalOutput{NoUnkeyedLiterals: input.NoUnkeyedLiterals, Flags: input.Flags}, fmt.Errorf("proto: wrong wireType = %d for field NonCriticalField", wireType) + } + var stringLen uint64 + for shift := uint(0); ; shift += 7 { + if shift >= 64 { + return protoiface.UnmarshalOutput{NoUnkeyedLiterals: input.NoUnkeyedLiterals, Flags: input.Flags}, runtime.ErrIntOverflow + } + if iNdEx >= l { + return protoiface.UnmarshalOutput{NoUnkeyedLiterals: input.NoUnkeyedLiterals, Flags: input.Flags}, io.ErrUnexpectedEOF + } + b := dAtA[iNdEx] + iNdEx++ + stringLen |= uint64(b&0x7F) << shift + if b < 0x80 { + break + } + } + intStringLen := int(stringLen) + if intStringLen < 0 { + return protoiface.UnmarshalOutput{NoUnkeyedLiterals: input.NoUnkeyedLiterals, Flags: input.Flags}, runtime.ErrInvalidLength + } + postIndex := iNdEx + intStringLen + if postIndex < 0 { + return protoiface.UnmarshalOutput{NoUnkeyedLiterals: input.NoUnkeyedLiterals, Flags: input.Flags}, runtime.ErrInvalidLength + } + if postIndex > l { + return protoiface.UnmarshalOutput{NoUnkeyedLiterals: input.NoUnkeyedLiterals, Flags: input.Flags}, io.ErrUnexpectedEOF + } + x.NonCriticalField = string(dAtA[iNdEx:postIndex]) + iNdEx = postIndex + case 14: + if wireType != 2 { + return protoiface.UnmarshalOutput{NoUnkeyedLiterals: input.NoUnkeyedLiterals, Flags: input.Flags}, fmt.Errorf("proto: wrong wireType = %d for field Inner1", wireType) + } + var msglen int + for shift := uint(0); ; shift += 7 { + if shift >= 64 { + return protoiface.UnmarshalOutput{NoUnkeyedLiterals: input.NoUnkeyedLiterals, Flags: input.Flags}, runtime.ErrIntOverflow + } + if iNdEx >= l { + return protoiface.UnmarshalOutput{NoUnkeyedLiterals: input.NoUnkeyedLiterals, Flags: input.Flags}, io.ErrUnexpectedEOF + } + b := dAtA[iNdEx] + iNdEx++ + msglen |= int(b&0x7F) << shift + if b < 0x80 { + break + } + } + if msglen < 0 { + return protoiface.UnmarshalOutput{NoUnkeyedLiterals: input.NoUnkeyedLiterals, Flags: input.Flags}, runtime.ErrInvalidLength + } + postIndex := iNdEx + msglen + if postIndex < 0 { + return protoiface.UnmarshalOutput{NoUnkeyedLiterals: input.NoUnkeyedLiterals, Flags: input.Flags}, runtime.ErrInvalidLength + } + if postIndex > l { + return protoiface.UnmarshalOutput{NoUnkeyedLiterals: input.NoUnkeyedLiterals, Flags: input.Flags}, io.ErrUnexpectedEOF + } + if x.Inner1 == nil { + x.Inner1 = &TestVersion4LoneNesting_Inner1{} + } + if err := options.Unmarshal(dAtA[iNdEx:postIndex], x.Inner1); err != nil { + return protoiface.UnmarshalOutput{NoUnkeyedLiterals: input.NoUnkeyedLiterals, Flags: input.Flags}, err + } + iNdEx = postIndex + case 15: + if wireType != 2 { + return protoiface.UnmarshalOutput{NoUnkeyedLiterals: input.NoUnkeyedLiterals, Flags: input.Flags}, fmt.Errorf("proto: wrong wireType = %d for field Inner2", wireType) + } + var msglen int + for shift := uint(0); ; shift += 7 { + if shift >= 64 { + return protoiface.UnmarshalOutput{NoUnkeyedLiterals: input.NoUnkeyedLiterals, Flags: input.Flags}, runtime.ErrIntOverflow + } + if iNdEx >= l { + return protoiface.UnmarshalOutput{NoUnkeyedLiterals: input.NoUnkeyedLiterals, Flags: input.Flags}, io.ErrUnexpectedEOF + } + b := dAtA[iNdEx] + iNdEx++ + msglen |= int(b&0x7F) << shift + if b < 0x80 { + break + } + } + if msglen < 0 { + return protoiface.UnmarshalOutput{NoUnkeyedLiterals: input.NoUnkeyedLiterals, Flags: input.Flags}, runtime.ErrInvalidLength + } + postIndex := iNdEx + msglen + if postIndex < 0 { + return protoiface.UnmarshalOutput{NoUnkeyedLiterals: input.NoUnkeyedLiterals, Flags: input.Flags}, runtime.ErrInvalidLength + } + if postIndex > l { + return protoiface.UnmarshalOutput{NoUnkeyedLiterals: input.NoUnkeyedLiterals, Flags: input.Flags}, io.ErrUnexpectedEOF + } + if x.Inner2 == nil { + x.Inner2 = &TestVersion4LoneNesting_Inner2{} + } + if err := options.Unmarshal(dAtA[iNdEx:postIndex], x.Inner2); err != nil { + return protoiface.UnmarshalOutput{NoUnkeyedLiterals: input.NoUnkeyedLiterals, Flags: input.Flags}, err + } + iNdEx = postIndex + default: + iNdEx = preIndex + skippy, err := runtime.Skip(dAtA[iNdEx:]) + if err != nil { + return protoiface.UnmarshalOutput{NoUnkeyedLiterals: input.NoUnkeyedLiterals, Flags: input.Flags}, err + } + if (skippy < 0) || (iNdEx+skippy) < 0 { + return protoiface.UnmarshalOutput{NoUnkeyedLiterals: input.NoUnkeyedLiterals, Flags: input.Flags}, runtime.ErrInvalidLength + } + if (iNdEx + skippy) > l { + return protoiface.UnmarshalOutput{NoUnkeyedLiterals: input.NoUnkeyedLiterals, Flags: input.Flags}, io.ErrUnexpectedEOF + } + if !options.DiscardUnknown { + x.unknownFields = append(x.unknownFields, dAtA[iNdEx:iNdEx+skippy]...) + } + iNdEx += skippy + } + } + + if iNdEx > l { + return protoiface.UnmarshalOutput{NoUnkeyedLiterals: input.NoUnkeyedLiterals, Flags: input.Flags}, io.ErrUnexpectedEOF + } + return protoiface.UnmarshalOutput{NoUnkeyedLiterals: input.NoUnkeyedLiterals, Flags: input.Flags}, nil + } + return &protoiface.Methods{ + NoUnkeyedLiterals: struct{}{}, + Flags: protoiface.SupportMarshalDeterministic | protoiface.SupportUnmarshalDiscardUnknown, + Size: size, + Marshal: marshal, + Unmarshal: unmarshal, + Merge: nil, + CheckInitialized: nil, + } +} + +var ( + md_TestVersion4LoneNesting_Inner1 protoreflect.MessageDescriptor + fd_TestVersion4LoneNesting_Inner1_id protoreflect.FieldDescriptor + fd_TestVersion4LoneNesting_Inner1_name protoreflect.FieldDescriptor + fd_TestVersion4LoneNesting_Inner1_inner protoreflect.FieldDescriptor +) + +func init() { + file_unknownproto_proto_init() + md_TestVersion4LoneNesting_Inner1 = File_unknownproto_proto.Messages().ByName("TestVersion4LoneNesting").Messages().ByName("Inner1") + fd_TestVersion4LoneNesting_Inner1_id = md_TestVersion4LoneNesting_Inner1.Fields().ByName("id") + fd_TestVersion4LoneNesting_Inner1_name = md_TestVersion4LoneNesting_Inner1.Fields().ByName("name") + fd_TestVersion4LoneNesting_Inner1_inner = md_TestVersion4LoneNesting_Inner1.Fields().ByName("inner") +} + +var _ protoreflect.Message = (*fastReflection_TestVersion4LoneNesting_Inner1)(nil) + +type fastReflection_TestVersion4LoneNesting_Inner1 TestVersion4LoneNesting_Inner1 + +func (x *TestVersion4LoneNesting_Inner1) ProtoReflect() protoreflect.Message { + return (*fastReflection_TestVersion4LoneNesting_Inner1)(x) +} + +func (x *TestVersion4LoneNesting_Inner1) slowProtoReflect() protoreflect.Message { + mi := &file_unknownproto_proto_msgTypes[29] + if protoimpl.UnsafeEnabled && x != nil { + ms := protoimpl.X.MessageStateOf(protoimpl.Pointer(x)) + if ms.LoadMessageInfo() == nil { + ms.StoreMessageInfo(mi) + } + return ms + } + return mi.MessageOf(x) +} + +var _fastReflection_TestVersion4LoneNesting_Inner1_messageType fastReflection_TestVersion4LoneNesting_Inner1_messageType +var _ protoreflect.MessageType = fastReflection_TestVersion4LoneNesting_Inner1_messageType{} + +type fastReflection_TestVersion4LoneNesting_Inner1_messageType struct{} + +func (x fastReflection_TestVersion4LoneNesting_Inner1_messageType) Zero() protoreflect.Message { + return (*fastReflection_TestVersion4LoneNesting_Inner1)(nil) +} +func (x fastReflection_TestVersion4LoneNesting_Inner1_messageType) New() protoreflect.Message { + return new(fastReflection_TestVersion4LoneNesting_Inner1) +} +func (x fastReflection_TestVersion4LoneNesting_Inner1_messageType) Descriptor() protoreflect.MessageDescriptor { + return md_TestVersion4LoneNesting_Inner1 +} + +// Descriptor returns message descriptor, which contains only the protobuf +// type information for the message. +func (x *fastReflection_TestVersion4LoneNesting_Inner1) Descriptor() protoreflect.MessageDescriptor { + return md_TestVersion4LoneNesting_Inner1 +} + +// Type returns the message type, which encapsulates both Go and protobuf +// type information. If the Go type information is not needed, +// it is recommended that the message descriptor be used instead. +func (x *fastReflection_TestVersion4LoneNesting_Inner1) Type() protoreflect.MessageType { + return _fastReflection_TestVersion4LoneNesting_Inner1_messageType +} + +// New returns a newly allocated and mutable empty message. +func (x *fastReflection_TestVersion4LoneNesting_Inner1) New() protoreflect.Message { + return new(fastReflection_TestVersion4LoneNesting_Inner1) +} + +// Interface unwraps the message reflection interface and +// returns the underlying ProtoMessage interface. +func (x *fastReflection_TestVersion4LoneNesting_Inner1) Interface() protoreflect.ProtoMessage { + return (*TestVersion4LoneNesting_Inner1)(x) +} + +// Range iterates over every populated field in an undefined order, +// calling f for each field descriptor and value encountered. +// Range returns immediately if f returns false. +// While iterating, mutating operations may only be performed +// on the current field descriptor. +func (x *fastReflection_TestVersion4LoneNesting_Inner1) Range(f func(protoreflect.FieldDescriptor, protoreflect.Value) bool) { + if x.Id != int64(0) { + value := protoreflect.ValueOfInt64(x.Id) + if !f(fd_TestVersion4LoneNesting_Inner1_id, value) { + return + } + } + if x.Name != "" { + value := protoreflect.ValueOfString(x.Name) + if !f(fd_TestVersion4LoneNesting_Inner1_name, value) { + return + } + } + if x.Inner != nil { + value := protoreflect.ValueOfMessage(x.Inner.ProtoReflect()) + if !f(fd_TestVersion4LoneNesting_Inner1_inner, value) { + return + } + } +} + +// Has reports whether a field is populated. +// +// Some fields have the property of nullability where it is possible to +// distinguish between the default value of a field and whether the field +// was explicitly populated with the default value. Singular message fields, +// member fields of a oneof, and proto2 scalar fields are nullable. Such +// fields are populated only if explicitly set. +// +// In other cases (aside from the nullable cases above), +// a proto3 scalar field is populated if it contains a non-zero value, and +// a repeated field is populated if it is non-empty. +func (x *fastReflection_TestVersion4LoneNesting_Inner1) Has(fd protoreflect.FieldDescriptor) bool { + switch fd.FullName() { + case "testpb.TestVersion4LoneNesting.Inner1.id": + return x.Id != int64(0) + case "testpb.TestVersion4LoneNesting.Inner1.name": + return x.Name != "" + case "testpb.TestVersion4LoneNesting.Inner1.inner": + return x.Inner != nil + default: + if fd.IsExtension() { + panic(fmt.Errorf("proto3 declared messages do not support extensions: testpb.TestVersion4LoneNesting.Inner1")) + } + panic(fmt.Errorf("message testpb.TestVersion4LoneNesting.Inner1 does not contain field %s", fd.FullName())) + } +} + +// Clear clears the field such that a subsequent Has call reports false. +// +// Clearing an extension field clears both the extension type and value +// associated with the given field number. +// +// Clear is a mutating operation and unsafe for concurrent use. +func (x *fastReflection_TestVersion4LoneNesting_Inner1) Clear(fd protoreflect.FieldDescriptor) { + switch fd.FullName() { + case "testpb.TestVersion4LoneNesting.Inner1.id": + x.Id = int64(0) + case "testpb.TestVersion4LoneNesting.Inner1.name": + x.Name = "" + case "testpb.TestVersion4LoneNesting.Inner1.inner": + x.Inner = nil + default: + if fd.IsExtension() { + panic(fmt.Errorf("proto3 declared messages do not support extensions: testpb.TestVersion4LoneNesting.Inner1")) + } + panic(fmt.Errorf("message testpb.TestVersion4LoneNesting.Inner1 does not contain field %s", fd.FullName())) + } +} + +// Get retrieves the value for a field. +// +// For unpopulated scalars, it returns the default value, where +// the default value of a bytes scalar is guaranteed to be a copy. +// For unpopulated composite types, it returns an empty, read-only view +// of the value; to obtain a mutable reference, use Mutable. +func (x *fastReflection_TestVersion4LoneNesting_Inner1) Get(descriptor protoreflect.FieldDescriptor) protoreflect.Value { + switch descriptor.FullName() { + case "testpb.TestVersion4LoneNesting.Inner1.id": + value := x.Id + return protoreflect.ValueOfInt64(value) + case "testpb.TestVersion4LoneNesting.Inner1.name": + value := x.Name + return protoreflect.ValueOfString(value) + case "testpb.TestVersion4LoneNesting.Inner1.inner": + value := x.Inner + return protoreflect.ValueOfMessage(value.ProtoReflect()) + default: + if descriptor.IsExtension() { + panic(fmt.Errorf("proto3 declared messages do not support extensions: testpb.TestVersion4LoneNesting.Inner1")) + } + panic(fmt.Errorf("message testpb.TestVersion4LoneNesting.Inner1 does not contain field %s", descriptor.FullName())) + } +} + +// Set stores the value for a field. +// +// For a field belonging to a oneof, it implicitly clears any other field +// that may be currently set within the same oneof. +// For extension fields, it implicitly stores the provided ExtensionType. +// When setting a composite type, it is unspecified whether the stored value +// aliases the source's memory in any way. If the composite value is an +// empty, read-only value, then it panics. +// +// Set is a mutating operation and unsafe for concurrent use. +func (x *fastReflection_TestVersion4LoneNesting_Inner1) Set(fd protoreflect.FieldDescriptor, value protoreflect.Value) { + switch fd.FullName() { + case "testpb.TestVersion4LoneNesting.Inner1.id": + x.Id = value.Int() + case "testpb.TestVersion4LoneNesting.Inner1.name": + x.Name = value.Interface().(string) + case "testpb.TestVersion4LoneNesting.Inner1.inner": + x.Inner = value.Message().Interface().(*TestVersion4LoneNesting_Inner1_InnerInner) + default: + if fd.IsExtension() { + panic(fmt.Errorf("proto3 declared messages do not support extensions: testpb.TestVersion4LoneNesting.Inner1")) + } + panic(fmt.Errorf("message testpb.TestVersion4LoneNesting.Inner1 does not contain field %s", fd.FullName())) + } +} + +// Mutable returns a mutable reference to a composite type. +// +// If the field is unpopulated, it may allocate a composite value. +// For a field belonging to a oneof, it implicitly clears any other field +// that may be currently set within the same oneof. +// For extension fields, it implicitly stores the provided ExtensionType +// if not already stored. +// It panics if the field does not contain a composite type. +// +// Mutable is a mutating operation and unsafe for concurrent use. +func (x *fastReflection_TestVersion4LoneNesting_Inner1) Mutable(fd protoreflect.FieldDescriptor) protoreflect.Value { + switch fd.FullName() { + case "testpb.TestVersion4LoneNesting.Inner1.inner": + if x.Inner == nil { + x.Inner = new(TestVersion4LoneNesting_Inner1_InnerInner) + } + return protoreflect.ValueOfMessage(x.Inner.ProtoReflect()) + case "testpb.TestVersion4LoneNesting.Inner1.id": + panic(fmt.Errorf("field id of message testpb.TestVersion4LoneNesting.Inner1 is not mutable")) + case "testpb.TestVersion4LoneNesting.Inner1.name": + panic(fmt.Errorf("field name of message testpb.TestVersion4LoneNesting.Inner1 is not mutable")) + default: + if fd.IsExtension() { + panic(fmt.Errorf("proto3 declared messages do not support extensions: testpb.TestVersion4LoneNesting.Inner1")) + } + panic(fmt.Errorf("message testpb.TestVersion4LoneNesting.Inner1 does not contain field %s", fd.FullName())) + } +} + +// NewField returns a new value that is assignable to the field +// for the given descriptor. For scalars, this returns the default value. +// For lists, maps, and messages, this returns a new, empty, mutable value. +func (x *fastReflection_TestVersion4LoneNesting_Inner1) NewField(fd protoreflect.FieldDescriptor) protoreflect.Value { + switch fd.FullName() { + case "testpb.TestVersion4LoneNesting.Inner1.id": + return protoreflect.ValueOfInt64(int64(0)) + case "testpb.TestVersion4LoneNesting.Inner1.name": + return protoreflect.ValueOfString("") + case "testpb.TestVersion4LoneNesting.Inner1.inner": + m := new(TestVersion4LoneNesting_Inner1_InnerInner) + return protoreflect.ValueOfMessage(m.ProtoReflect()) + default: + if fd.IsExtension() { + panic(fmt.Errorf("proto3 declared messages do not support extensions: testpb.TestVersion4LoneNesting.Inner1")) + } + panic(fmt.Errorf("message testpb.TestVersion4LoneNesting.Inner1 does not contain field %s", fd.FullName())) + } +} + +// WhichOneof reports which field within the oneof is populated, +// returning nil if none are populated. +// It panics if the oneof descriptor does not belong to this message. +func (x *fastReflection_TestVersion4LoneNesting_Inner1) WhichOneof(d protoreflect.OneofDescriptor) protoreflect.FieldDescriptor { + switch d.FullName() { + default: + panic(fmt.Errorf("%s is not a oneof field in testpb.TestVersion4LoneNesting.Inner1", d.FullName())) + } + panic("unreachable") +} + +// GetUnknown retrieves the entire list of unknown fields. +// The caller may only mutate the contents of the RawFields +// if the mutated bytes are stored back into the message with SetUnknown. +func (x *fastReflection_TestVersion4LoneNesting_Inner1) GetUnknown() protoreflect.RawFields { + return x.unknownFields +} + +// SetUnknown stores an entire list of unknown fields. +// The raw fields must be syntactically valid according to the wire format. +// An implementation may panic if this is not the case. +// Once stored, the caller must not mutate the content of the RawFields. +// An empty RawFields may be passed to clear the fields. +// +// SetUnknown is a mutating operation and unsafe for concurrent use. +func (x *fastReflection_TestVersion4LoneNesting_Inner1) SetUnknown(fields protoreflect.RawFields) { + x.unknownFields = fields +} + +// IsValid reports whether the message is valid. +// +// An invalid message is an empty, read-only value. +// +// An invalid message often corresponds to a nil pointer of the concrete +// message type, but the details are implementation dependent. +// Validity is not part of the protobuf data model, and may not +// be preserved in marshaling or other operations. +func (x *fastReflection_TestVersion4LoneNesting_Inner1) IsValid() bool { + return x != nil +} + +// ProtoMethods returns optional fastReflectionFeature-path implementations of various operations. +// This method may return nil. +// +// The returned methods type is identical to +// "google.golang.org/protobuf/runtime/protoiface".Methods. +// Consult the protoiface package documentation for details. +func (x *fastReflection_TestVersion4LoneNesting_Inner1) ProtoMethods() *protoiface.Methods { + size := func(input protoiface.SizeInput) protoiface.SizeOutput { + x := input.Message.Interface().(*TestVersion4LoneNesting_Inner1) + if x == nil { + return protoiface.SizeOutput{ + NoUnkeyedLiterals: input.NoUnkeyedLiterals, + Size: 0, + } + } + options := runtime.SizeInputToOptions(input) + _ = options + var n int + var l int + _ = l + if x.Id != 0 { + n += 1 + runtime.Sov(uint64(x.Id)) + } + l = len(x.Name) + if l > 0 { + n += 1 + l + runtime.Sov(uint64(l)) + } + if x.Inner != nil { + l = options.Size(x.Inner) + n += 1 + l + runtime.Sov(uint64(l)) + } + if x.unknownFields != nil { + n += len(x.unknownFields) + } + return protoiface.SizeOutput{ + NoUnkeyedLiterals: input.NoUnkeyedLiterals, + Size: n, + } + } + + marshal := func(input protoiface.MarshalInput) (protoiface.MarshalOutput, error) { + x := input.Message.Interface().(*TestVersion4LoneNesting_Inner1) + if x == nil { + return protoiface.MarshalOutput{ + NoUnkeyedLiterals: input.NoUnkeyedLiterals, + Buf: input.Buf, + }, nil + } + options := runtime.MarshalInputToOptions(input) + _ = options + size := options.Size(x) + dAtA := make([]byte, size) + i := len(dAtA) + _ = i + var l int + _ = l + if x.unknownFields != nil { + i -= len(x.unknownFields) + copy(dAtA[i:], x.unknownFields) + } + if x.Inner != nil { + encoded, err := options.Marshal(x.Inner) + if err != nil { + return protoiface.MarshalOutput{ + NoUnkeyedLiterals: input.NoUnkeyedLiterals, + Buf: input.Buf, + }, err + } + i -= len(encoded) + copy(dAtA[i:], encoded) + i = runtime.EncodeVarint(dAtA, i, uint64(len(encoded))) + i-- + dAtA[i] = 0x1a + } + if len(x.Name) > 0 { + i -= len(x.Name) + copy(dAtA[i:], x.Name) + i = runtime.EncodeVarint(dAtA, i, uint64(len(x.Name))) + i-- + dAtA[i] = 0x12 + } + if x.Id != 0 { + i = runtime.EncodeVarint(dAtA, i, uint64(x.Id)) + i-- + dAtA[i] = 0x8 + } + if input.Buf != nil { + input.Buf = append(input.Buf, dAtA...) + } else { + input.Buf = dAtA + } + return protoiface.MarshalOutput{ + NoUnkeyedLiterals: input.NoUnkeyedLiterals, + Buf: input.Buf, + }, nil + } + unmarshal := func(input protoiface.UnmarshalInput) (protoiface.UnmarshalOutput, error) { + x := input.Message.Interface().(*TestVersion4LoneNesting_Inner1) + if x == nil { + return protoiface.UnmarshalOutput{ + NoUnkeyedLiterals: input.NoUnkeyedLiterals, + Flags: input.Flags, + }, nil + } + options := runtime.UnmarshalInputToOptions(input) + _ = options + dAtA := input.Buf + l := len(dAtA) + iNdEx := 0 + for iNdEx < l { + preIndex := iNdEx + var wire uint64 + for shift := uint(0); ; shift += 7 { + if shift >= 64 { + return protoiface.UnmarshalOutput{NoUnkeyedLiterals: input.NoUnkeyedLiterals, Flags: input.Flags}, runtime.ErrIntOverflow + } + if iNdEx >= l { + return protoiface.UnmarshalOutput{NoUnkeyedLiterals: input.NoUnkeyedLiterals, Flags: input.Flags}, io.ErrUnexpectedEOF + } + b := dAtA[iNdEx] + iNdEx++ + wire |= uint64(b&0x7F) << shift + if b < 0x80 { + break + } + } + fieldNum := int32(wire >> 3) + wireType := int(wire & 0x7) + if wireType == 4 { + return protoiface.UnmarshalOutput{NoUnkeyedLiterals: input.NoUnkeyedLiterals, Flags: input.Flags}, fmt.Errorf("proto: TestVersion4LoneNesting_Inner1: wiretype end group for non-group") + } + if fieldNum <= 0 { + return protoiface.UnmarshalOutput{NoUnkeyedLiterals: input.NoUnkeyedLiterals, Flags: input.Flags}, fmt.Errorf("proto: TestVersion4LoneNesting_Inner1: illegal tag %d (wire type %d)", fieldNum, wire) + } + switch fieldNum { + case 1: + if wireType != 0 { + return protoiface.UnmarshalOutput{NoUnkeyedLiterals: input.NoUnkeyedLiterals, Flags: input.Flags}, fmt.Errorf("proto: wrong wireType = %d for field Id", wireType) + } + x.Id = 0 + for shift := uint(0); ; shift += 7 { + if shift >= 64 { + return protoiface.UnmarshalOutput{NoUnkeyedLiterals: input.NoUnkeyedLiterals, Flags: input.Flags}, runtime.ErrIntOverflow + } + if iNdEx >= l { + return protoiface.UnmarshalOutput{NoUnkeyedLiterals: input.NoUnkeyedLiterals, Flags: input.Flags}, io.ErrUnexpectedEOF + } + b := dAtA[iNdEx] + iNdEx++ + x.Id |= int64(b&0x7F) << shift + if b < 0x80 { + break + } + } + case 2: + if wireType != 2 { + return protoiface.UnmarshalOutput{NoUnkeyedLiterals: input.NoUnkeyedLiterals, Flags: input.Flags}, fmt.Errorf("proto: wrong wireType = %d for field Name", wireType) + } + var stringLen uint64 + for shift := uint(0); ; shift += 7 { + if shift >= 64 { + return protoiface.UnmarshalOutput{NoUnkeyedLiterals: input.NoUnkeyedLiterals, Flags: input.Flags}, runtime.ErrIntOverflow + } + if iNdEx >= l { + return protoiface.UnmarshalOutput{NoUnkeyedLiterals: input.NoUnkeyedLiterals, Flags: input.Flags}, io.ErrUnexpectedEOF + } + b := dAtA[iNdEx] + iNdEx++ + stringLen |= uint64(b&0x7F) << shift + if b < 0x80 { + break + } + } + intStringLen := int(stringLen) + if intStringLen < 0 { + return protoiface.UnmarshalOutput{NoUnkeyedLiterals: input.NoUnkeyedLiterals, Flags: input.Flags}, runtime.ErrInvalidLength + } + postIndex := iNdEx + intStringLen + if postIndex < 0 { + return protoiface.UnmarshalOutput{NoUnkeyedLiterals: input.NoUnkeyedLiterals, Flags: input.Flags}, runtime.ErrInvalidLength + } + if postIndex > l { + return protoiface.UnmarshalOutput{NoUnkeyedLiterals: input.NoUnkeyedLiterals, Flags: input.Flags}, io.ErrUnexpectedEOF + } + x.Name = string(dAtA[iNdEx:postIndex]) + iNdEx = postIndex + case 3: + if wireType != 2 { + return protoiface.UnmarshalOutput{NoUnkeyedLiterals: input.NoUnkeyedLiterals, Flags: input.Flags}, fmt.Errorf("proto: wrong wireType = %d for field Inner", wireType) + } + var msglen int + for shift := uint(0); ; shift += 7 { + if shift >= 64 { + return protoiface.UnmarshalOutput{NoUnkeyedLiterals: input.NoUnkeyedLiterals, Flags: input.Flags}, runtime.ErrIntOverflow + } + if iNdEx >= l { + return protoiface.UnmarshalOutput{NoUnkeyedLiterals: input.NoUnkeyedLiterals, Flags: input.Flags}, io.ErrUnexpectedEOF + } + b := dAtA[iNdEx] + iNdEx++ + msglen |= int(b&0x7F) << shift + if b < 0x80 { + break + } + } + if msglen < 0 { + return protoiface.UnmarshalOutput{NoUnkeyedLiterals: input.NoUnkeyedLiterals, Flags: input.Flags}, runtime.ErrInvalidLength + } + postIndex := iNdEx + msglen + if postIndex < 0 { + return protoiface.UnmarshalOutput{NoUnkeyedLiterals: input.NoUnkeyedLiterals, Flags: input.Flags}, runtime.ErrInvalidLength + } + if postIndex > l { + return protoiface.UnmarshalOutput{NoUnkeyedLiterals: input.NoUnkeyedLiterals, Flags: input.Flags}, io.ErrUnexpectedEOF + } + if x.Inner == nil { + x.Inner = &TestVersion4LoneNesting_Inner1_InnerInner{} + } + if err := options.Unmarshal(dAtA[iNdEx:postIndex], x.Inner); err != nil { + return protoiface.UnmarshalOutput{NoUnkeyedLiterals: input.NoUnkeyedLiterals, Flags: input.Flags}, err + } + iNdEx = postIndex + default: + iNdEx = preIndex + skippy, err := runtime.Skip(dAtA[iNdEx:]) + if err != nil { + return protoiface.UnmarshalOutput{NoUnkeyedLiterals: input.NoUnkeyedLiterals, Flags: input.Flags}, err + } + if (skippy < 0) || (iNdEx+skippy) < 0 { + return protoiface.UnmarshalOutput{NoUnkeyedLiterals: input.NoUnkeyedLiterals, Flags: input.Flags}, runtime.ErrInvalidLength + } + if (iNdEx + skippy) > l { + return protoiface.UnmarshalOutput{NoUnkeyedLiterals: input.NoUnkeyedLiterals, Flags: input.Flags}, io.ErrUnexpectedEOF + } + if !options.DiscardUnknown { + x.unknownFields = append(x.unknownFields, dAtA[iNdEx:iNdEx+skippy]...) + } + iNdEx += skippy + } + } + + if iNdEx > l { + return protoiface.UnmarshalOutput{NoUnkeyedLiterals: input.NoUnkeyedLiterals, Flags: input.Flags}, io.ErrUnexpectedEOF + } + return protoiface.UnmarshalOutput{NoUnkeyedLiterals: input.NoUnkeyedLiterals, Flags: input.Flags}, nil + } + return &protoiface.Methods{ + NoUnkeyedLiterals: struct{}{}, + Flags: protoiface.SupportMarshalDeterministic | protoiface.SupportUnmarshalDiscardUnknown, + Size: size, + Marshal: marshal, + Unmarshal: unmarshal, + Merge: nil, + CheckInitialized: nil, + } +} + +var ( + md_TestVersion4LoneNesting_Inner1_InnerInner protoreflect.MessageDescriptor + fd_TestVersion4LoneNesting_Inner1_InnerInner_id protoreflect.FieldDescriptor + fd_TestVersion4LoneNesting_Inner1_InnerInner_city protoreflect.FieldDescriptor +) + +func init() { + file_unknownproto_proto_init() + md_TestVersion4LoneNesting_Inner1_InnerInner = File_unknownproto_proto.Messages().ByName("TestVersion4LoneNesting").Messages().ByName("Inner1").Messages().ByName("InnerInner") + fd_TestVersion4LoneNesting_Inner1_InnerInner_id = md_TestVersion4LoneNesting_Inner1_InnerInner.Fields().ByName("id") + fd_TestVersion4LoneNesting_Inner1_InnerInner_city = md_TestVersion4LoneNesting_Inner1_InnerInner.Fields().ByName("city") +} + +var _ protoreflect.Message = (*fastReflection_TestVersion4LoneNesting_Inner1_InnerInner)(nil) + +type fastReflection_TestVersion4LoneNesting_Inner1_InnerInner TestVersion4LoneNesting_Inner1_InnerInner + +func (x *TestVersion4LoneNesting_Inner1_InnerInner) ProtoReflect() protoreflect.Message { + return (*fastReflection_TestVersion4LoneNesting_Inner1_InnerInner)(x) +} + +func (x *TestVersion4LoneNesting_Inner1_InnerInner) slowProtoReflect() protoreflect.Message { + mi := &file_unknownproto_proto_msgTypes[31] + if protoimpl.UnsafeEnabled && x != nil { + ms := protoimpl.X.MessageStateOf(protoimpl.Pointer(x)) + if ms.LoadMessageInfo() == nil { + ms.StoreMessageInfo(mi) + } + return ms + } + return mi.MessageOf(x) +} + +var _fastReflection_TestVersion4LoneNesting_Inner1_InnerInner_messageType fastReflection_TestVersion4LoneNesting_Inner1_InnerInner_messageType +var _ protoreflect.MessageType = fastReflection_TestVersion4LoneNesting_Inner1_InnerInner_messageType{} + +type fastReflection_TestVersion4LoneNesting_Inner1_InnerInner_messageType struct{} + +func (x fastReflection_TestVersion4LoneNesting_Inner1_InnerInner_messageType) Zero() protoreflect.Message { + return (*fastReflection_TestVersion4LoneNesting_Inner1_InnerInner)(nil) +} +func (x fastReflection_TestVersion4LoneNesting_Inner1_InnerInner_messageType) New() protoreflect.Message { + return new(fastReflection_TestVersion4LoneNesting_Inner1_InnerInner) +} +func (x fastReflection_TestVersion4LoneNesting_Inner1_InnerInner_messageType) Descriptor() protoreflect.MessageDescriptor { + return md_TestVersion4LoneNesting_Inner1_InnerInner +} + +// Descriptor returns message descriptor, which contains only the protobuf +// type information for the message. +func (x *fastReflection_TestVersion4LoneNesting_Inner1_InnerInner) Descriptor() protoreflect.MessageDescriptor { + return md_TestVersion4LoneNesting_Inner1_InnerInner +} + +// Type returns the message type, which encapsulates both Go and protobuf +// type information. If the Go type information is not needed, +// it is recommended that the message descriptor be used instead. +func (x *fastReflection_TestVersion4LoneNesting_Inner1_InnerInner) Type() protoreflect.MessageType { + return _fastReflection_TestVersion4LoneNesting_Inner1_InnerInner_messageType +} + +// New returns a newly allocated and mutable empty message. +func (x *fastReflection_TestVersion4LoneNesting_Inner1_InnerInner) New() protoreflect.Message { + return new(fastReflection_TestVersion4LoneNesting_Inner1_InnerInner) +} + +// Interface unwraps the message reflection interface and +// returns the underlying ProtoMessage interface. +func (x *fastReflection_TestVersion4LoneNesting_Inner1_InnerInner) Interface() protoreflect.ProtoMessage { + return (*TestVersion4LoneNesting_Inner1_InnerInner)(x) +} + +// Range iterates over every populated field in an undefined order, +// calling f for each field descriptor and value encountered. +// Range returns immediately if f returns false. +// While iterating, mutating operations may only be performed +// on the current field descriptor. +func (x *fastReflection_TestVersion4LoneNesting_Inner1_InnerInner) Range(f func(protoreflect.FieldDescriptor, protoreflect.Value) bool) { + if x.Id != int64(0) { + value := protoreflect.ValueOfInt64(x.Id) + if !f(fd_TestVersion4LoneNesting_Inner1_InnerInner_id, value) { + return + } + } + if x.City != "" { + value := protoreflect.ValueOfString(x.City) + if !f(fd_TestVersion4LoneNesting_Inner1_InnerInner_city, value) { + return + } + } +} + +// Has reports whether a field is populated. +// +// Some fields have the property of nullability where it is possible to +// distinguish between the default value of a field and whether the field +// was explicitly populated with the default value. Singular message fields, +// member fields of a oneof, and proto2 scalar fields are nullable. Such +// fields are populated only if explicitly set. +// +// In other cases (aside from the nullable cases above), +// a proto3 scalar field is populated if it contains a non-zero value, and +// a repeated field is populated if it is non-empty. +func (x *fastReflection_TestVersion4LoneNesting_Inner1_InnerInner) Has(fd protoreflect.FieldDescriptor) bool { + switch fd.FullName() { + case "testpb.TestVersion4LoneNesting.Inner1.InnerInner.id": + return x.Id != int64(0) + case "testpb.TestVersion4LoneNesting.Inner1.InnerInner.city": + return x.City != "" + default: + if fd.IsExtension() { + panic(fmt.Errorf("proto3 declared messages do not support extensions: testpb.TestVersion4LoneNesting.Inner1.InnerInner")) + } + panic(fmt.Errorf("message testpb.TestVersion4LoneNesting.Inner1.InnerInner does not contain field %s", fd.FullName())) + } +} + +// Clear clears the field such that a subsequent Has call reports false. +// +// Clearing an extension field clears both the extension type and value +// associated with the given field number. +// +// Clear is a mutating operation and unsafe for concurrent use. +func (x *fastReflection_TestVersion4LoneNesting_Inner1_InnerInner) Clear(fd protoreflect.FieldDescriptor) { + switch fd.FullName() { + case "testpb.TestVersion4LoneNesting.Inner1.InnerInner.id": + x.Id = int64(0) + case "testpb.TestVersion4LoneNesting.Inner1.InnerInner.city": + x.City = "" + default: + if fd.IsExtension() { + panic(fmt.Errorf("proto3 declared messages do not support extensions: testpb.TestVersion4LoneNesting.Inner1.InnerInner")) + } + panic(fmt.Errorf("message testpb.TestVersion4LoneNesting.Inner1.InnerInner does not contain field %s", fd.FullName())) + } +} + +// Get retrieves the value for a field. +// +// For unpopulated scalars, it returns the default value, where +// the default value of a bytes scalar is guaranteed to be a copy. +// For unpopulated composite types, it returns an empty, read-only view +// of the value; to obtain a mutable reference, use Mutable. +func (x *fastReflection_TestVersion4LoneNesting_Inner1_InnerInner) Get(descriptor protoreflect.FieldDescriptor) protoreflect.Value { + switch descriptor.FullName() { + case "testpb.TestVersion4LoneNesting.Inner1.InnerInner.id": + value := x.Id + return protoreflect.ValueOfInt64(value) + case "testpb.TestVersion4LoneNesting.Inner1.InnerInner.city": + value := x.City + return protoreflect.ValueOfString(value) + default: + if descriptor.IsExtension() { + panic(fmt.Errorf("proto3 declared messages do not support extensions: testpb.TestVersion4LoneNesting.Inner1.InnerInner")) + } + panic(fmt.Errorf("message testpb.TestVersion4LoneNesting.Inner1.InnerInner does not contain field %s", descriptor.FullName())) + } +} + +// Set stores the value for a field. +// +// For a field belonging to a oneof, it implicitly clears any other field +// that may be currently set within the same oneof. +// For extension fields, it implicitly stores the provided ExtensionType. +// When setting a composite type, it is unspecified whether the stored value +// aliases the source's memory in any way. If the composite value is an +// empty, read-only value, then it panics. +// +// Set is a mutating operation and unsafe for concurrent use. +func (x *fastReflection_TestVersion4LoneNesting_Inner1_InnerInner) Set(fd protoreflect.FieldDescriptor, value protoreflect.Value) { + switch fd.FullName() { + case "testpb.TestVersion4LoneNesting.Inner1.InnerInner.id": + x.Id = value.Int() + case "testpb.TestVersion4LoneNesting.Inner1.InnerInner.city": + x.City = value.Interface().(string) + default: + if fd.IsExtension() { + panic(fmt.Errorf("proto3 declared messages do not support extensions: testpb.TestVersion4LoneNesting.Inner1.InnerInner")) + } + panic(fmt.Errorf("message testpb.TestVersion4LoneNesting.Inner1.InnerInner does not contain field %s", fd.FullName())) + } +} + +// Mutable returns a mutable reference to a composite type. +// +// If the field is unpopulated, it may allocate a composite value. +// For a field belonging to a oneof, it implicitly clears any other field +// that may be currently set within the same oneof. +// For extension fields, it implicitly stores the provided ExtensionType +// if not already stored. +// It panics if the field does not contain a composite type. +// +// Mutable is a mutating operation and unsafe for concurrent use. +func (x *fastReflection_TestVersion4LoneNesting_Inner1_InnerInner) Mutable(fd protoreflect.FieldDescriptor) protoreflect.Value { + switch fd.FullName() { + case "testpb.TestVersion4LoneNesting.Inner1.InnerInner.id": + panic(fmt.Errorf("field id of message testpb.TestVersion4LoneNesting.Inner1.InnerInner is not mutable")) + case "testpb.TestVersion4LoneNesting.Inner1.InnerInner.city": + panic(fmt.Errorf("field city of message testpb.TestVersion4LoneNesting.Inner1.InnerInner is not mutable")) + default: + if fd.IsExtension() { + panic(fmt.Errorf("proto3 declared messages do not support extensions: testpb.TestVersion4LoneNesting.Inner1.InnerInner")) + } + panic(fmt.Errorf("message testpb.TestVersion4LoneNesting.Inner1.InnerInner does not contain field %s", fd.FullName())) + } +} + +// NewField returns a new value that is assignable to the field +// for the given descriptor. For scalars, this returns the default value. +// For lists, maps, and messages, this returns a new, empty, mutable value. +func (x *fastReflection_TestVersion4LoneNesting_Inner1_InnerInner) NewField(fd protoreflect.FieldDescriptor) protoreflect.Value { + switch fd.FullName() { + case "testpb.TestVersion4LoneNesting.Inner1.InnerInner.id": + return protoreflect.ValueOfInt64(int64(0)) + case "testpb.TestVersion4LoneNesting.Inner1.InnerInner.city": + return protoreflect.ValueOfString("") + default: + if fd.IsExtension() { + panic(fmt.Errorf("proto3 declared messages do not support extensions: testpb.TestVersion4LoneNesting.Inner1.InnerInner")) + } + panic(fmt.Errorf("message testpb.TestVersion4LoneNesting.Inner1.InnerInner does not contain field %s", fd.FullName())) + } +} + +// WhichOneof reports which field within the oneof is populated, +// returning nil if none are populated. +// It panics if the oneof descriptor does not belong to this message. +func (x *fastReflection_TestVersion4LoneNesting_Inner1_InnerInner) WhichOneof(d protoreflect.OneofDescriptor) protoreflect.FieldDescriptor { + switch d.FullName() { + default: + panic(fmt.Errorf("%s is not a oneof field in testpb.TestVersion4LoneNesting.Inner1.InnerInner", d.FullName())) + } + panic("unreachable") +} + +// GetUnknown retrieves the entire list of unknown fields. +// The caller may only mutate the contents of the RawFields +// if the mutated bytes are stored back into the message with SetUnknown. +func (x *fastReflection_TestVersion4LoneNesting_Inner1_InnerInner) GetUnknown() protoreflect.RawFields { + return x.unknownFields +} + +// SetUnknown stores an entire list of unknown fields. +// The raw fields must be syntactically valid according to the wire format. +// An implementation may panic if this is not the case. +// Once stored, the caller must not mutate the content of the RawFields. +// An empty RawFields may be passed to clear the fields. +// +// SetUnknown is a mutating operation and unsafe for concurrent use. +func (x *fastReflection_TestVersion4LoneNesting_Inner1_InnerInner) SetUnknown(fields protoreflect.RawFields) { + x.unknownFields = fields +} + +// IsValid reports whether the message is valid. +// +// An invalid message is an empty, read-only value. +// +// An invalid message often corresponds to a nil pointer of the concrete +// message type, but the details are implementation dependent. +// Validity is not part of the protobuf data model, and may not +// be preserved in marshaling or other operations. +func (x *fastReflection_TestVersion4LoneNesting_Inner1_InnerInner) IsValid() bool { + return x != nil +} + +// ProtoMethods returns optional fastReflectionFeature-path implementations of various operations. +// This method may return nil. +// +// The returned methods type is identical to +// "google.golang.org/protobuf/runtime/protoiface".Methods. +// Consult the protoiface package documentation for details. +func (x *fastReflection_TestVersion4LoneNesting_Inner1_InnerInner) ProtoMethods() *protoiface.Methods { + size := func(input protoiface.SizeInput) protoiface.SizeOutput { + x := input.Message.Interface().(*TestVersion4LoneNesting_Inner1_InnerInner) + if x == nil { + return protoiface.SizeOutput{ + NoUnkeyedLiterals: input.NoUnkeyedLiterals, + Size: 0, + } + } + options := runtime.SizeInputToOptions(input) + _ = options + var n int + var l int + _ = l + if x.Id != 0 { + n += 1 + runtime.Sov(uint64(x.Id)) + } + l = len(x.City) + if l > 0 { + n += 1 + l + runtime.Sov(uint64(l)) + } + if x.unknownFields != nil { + n += len(x.unknownFields) + } + return protoiface.SizeOutput{ + NoUnkeyedLiterals: input.NoUnkeyedLiterals, + Size: n, + } + } + + marshal := func(input protoiface.MarshalInput) (protoiface.MarshalOutput, error) { + x := input.Message.Interface().(*TestVersion4LoneNesting_Inner1_InnerInner) + if x == nil { + return protoiface.MarshalOutput{ + NoUnkeyedLiterals: input.NoUnkeyedLiterals, + Buf: input.Buf, + }, nil + } + options := runtime.MarshalInputToOptions(input) + _ = options + size := options.Size(x) + dAtA := make([]byte, size) + i := len(dAtA) + _ = i + var l int + _ = l + if x.unknownFields != nil { + i -= len(x.unknownFields) + copy(dAtA[i:], x.unknownFields) + } + if len(x.City) > 0 { + i -= len(x.City) + copy(dAtA[i:], x.City) + i = runtime.EncodeVarint(dAtA, i, uint64(len(x.City))) + i-- + dAtA[i] = 0x12 + } + if x.Id != 0 { + i = runtime.EncodeVarint(dAtA, i, uint64(x.Id)) + i-- + dAtA[i] = 0x8 + } + if input.Buf != nil { + input.Buf = append(input.Buf, dAtA...) + } else { + input.Buf = dAtA + } + return protoiface.MarshalOutput{ + NoUnkeyedLiterals: input.NoUnkeyedLiterals, + Buf: input.Buf, + }, nil + } + unmarshal := func(input protoiface.UnmarshalInput) (protoiface.UnmarshalOutput, error) { + x := input.Message.Interface().(*TestVersion4LoneNesting_Inner1_InnerInner) + if x == nil { + return protoiface.UnmarshalOutput{ + NoUnkeyedLiterals: input.NoUnkeyedLiterals, + Flags: input.Flags, + }, nil + } + options := runtime.UnmarshalInputToOptions(input) + _ = options + dAtA := input.Buf + l := len(dAtA) + iNdEx := 0 + for iNdEx < l { + preIndex := iNdEx + var wire uint64 + for shift := uint(0); ; shift += 7 { + if shift >= 64 { + return protoiface.UnmarshalOutput{NoUnkeyedLiterals: input.NoUnkeyedLiterals, Flags: input.Flags}, runtime.ErrIntOverflow + } + if iNdEx >= l { + return protoiface.UnmarshalOutput{NoUnkeyedLiterals: input.NoUnkeyedLiterals, Flags: input.Flags}, io.ErrUnexpectedEOF + } + b := dAtA[iNdEx] + iNdEx++ + wire |= uint64(b&0x7F) << shift + if b < 0x80 { + break + } + } + fieldNum := int32(wire >> 3) + wireType := int(wire & 0x7) + if wireType == 4 { + return protoiface.UnmarshalOutput{NoUnkeyedLiterals: input.NoUnkeyedLiterals, Flags: input.Flags}, fmt.Errorf("proto: TestVersion4LoneNesting_Inner1_InnerInner: wiretype end group for non-group") + } + if fieldNum <= 0 { + return protoiface.UnmarshalOutput{NoUnkeyedLiterals: input.NoUnkeyedLiterals, Flags: input.Flags}, fmt.Errorf("proto: TestVersion4LoneNesting_Inner1_InnerInner: illegal tag %d (wire type %d)", fieldNum, wire) + } + switch fieldNum { + case 1: + if wireType != 0 { + return protoiface.UnmarshalOutput{NoUnkeyedLiterals: input.NoUnkeyedLiterals, Flags: input.Flags}, fmt.Errorf("proto: wrong wireType = %d for field Id", wireType) + } + x.Id = 0 + for shift := uint(0); ; shift += 7 { + if shift >= 64 { + return protoiface.UnmarshalOutput{NoUnkeyedLiterals: input.NoUnkeyedLiterals, Flags: input.Flags}, runtime.ErrIntOverflow + } + if iNdEx >= l { + return protoiface.UnmarshalOutput{NoUnkeyedLiterals: input.NoUnkeyedLiterals, Flags: input.Flags}, io.ErrUnexpectedEOF + } + b := dAtA[iNdEx] + iNdEx++ + x.Id |= int64(b&0x7F) << shift + if b < 0x80 { + break + } + } + case 2: + if wireType != 2 { + return protoiface.UnmarshalOutput{NoUnkeyedLiterals: input.NoUnkeyedLiterals, Flags: input.Flags}, fmt.Errorf("proto: wrong wireType = %d for field City", wireType) + } + var stringLen uint64 + for shift := uint(0); ; shift += 7 { + if shift >= 64 { + return protoiface.UnmarshalOutput{NoUnkeyedLiterals: input.NoUnkeyedLiterals, Flags: input.Flags}, runtime.ErrIntOverflow + } + if iNdEx >= l { + return protoiface.UnmarshalOutput{NoUnkeyedLiterals: input.NoUnkeyedLiterals, Flags: input.Flags}, io.ErrUnexpectedEOF + } + b := dAtA[iNdEx] + iNdEx++ + stringLen |= uint64(b&0x7F) << shift + if b < 0x80 { + break + } + } + intStringLen := int(stringLen) + if intStringLen < 0 { + return protoiface.UnmarshalOutput{NoUnkeyedLiterals: input.NoUnkeyedLiterals, Flags: input.Flags}, runtime.ErrInvalidLength + } + postIndex := iNdEx + intStringLen + if postIndex < 0 { + return protoiface.UnmarshalOutput{NoUnkeyedLiterals: input.NoUnkeyedLiterals, Flags: input.Flags}, runtime.ErrInvalidLength + } + if postIndex > l { + return protoiface.UnmarshalOutput{NoUnkeyedLiterals: input.NoUnkeyedLiterals, Flags: input.Flags}, io.ErrUnexpectedEOF + } + x.City = string(dAtA[iNdEx:postIndex]) + iNdEx = postIndex + default: + iNdEx = preIndex + skippy, err := runtime.Skip(dAtA[iNdEx:]) + if err != nil { + return protoiface.UnmarshalOutput{NoUnkeyedLiterals: input.NoUnkeyedLiterals, Flags: input.Flags}, err + } + if (skippy < 0) || (iNdEx+skippy) < 0 { + return protoiface.UnmarshalOutput{NoUnkeyedLiterals: input.NoUnkeyedLiterals, Flags: input.Flags}, runtime.ErrInvalidLength + } + if (iNdEx + skippy) > l { + return protoiface.UnmarshalOutput{NoUnkeyedLiterals: input.NoUnkeyedLiterals, Flags: input.Flags}, io.ErrUnexpectedEOF + } + if !options.DiscardUnknown { + x.unknownFields = append(x.unknownFields, dAtA[iNdEx:iNdEx+skippy]...) + } + iNdEx += skippy + } + } + + if iNdEx > l { + return protoiface.UnmarshalOutput{NoUnkeyedLiterals: input.NoUnkeyedLiterals, Flags: input.Flags}, io.ErrUnexpectedEOF + } + return protoiface.UnmarshalOutput{NoUnkeyedLiterals: input.NoUnkeyedLiterals, Flags: input.Flags}, nil + } + return &protoiface.Methods{ + NoUnkeyedLiterals: struct{}{}, + Flags: protoiface.SupportMarshalDeterministic | protoiface.SupportUnmarshalDiscardUnknown, + Size: size, + Marshal: marshal, + Unmarshal: unmarshal, + Merge: nil, + CheckInitialized: nil, + } +} + +var ( + md_TestVersion4LoneNesting_Inner2 protoreflect.MessageDescriptor + fd_TestVersion4LoneNesting_Inner2_id protoreflect.FieldDescriptor + fd_TestVersion4LoneNesting_Inner2_country protoreflect.FieldDescriptor + fd_TestVersion4LoneNesting_Inner2_inner protoreflect.FieldDescriptor +) + +func init() { + file_unknownproto_proto_init() + md_TestVersion4LoneNesting_Inner2 = File_unknownproto_proto.Messages().ByName("TestVersion4LoneNesting").Messages().ByName("Inner2") + fd_TestVersion4LoneNesting_Inner2_id = md_TestVersion4LoneNesting_Inner2.Fields().ByName("id") + fd_TestVersion4LoneNesting_Inner2_country = md_TestVersion4LoneNesting_Inner2.Fields().ByName("country") + fd_TestVersion4LoneNesting_Inner2_inner = md_TestVersion4LoneNesting_Inner2.Fields().ByName("inner") +} + +var _ protoreflect.Message = (*fastReflection_TestVersion4LoneNesting_Inner2)(nil) + +type fastReflection_TestVersion4LoneNesting_Inner2 TestVersion4LoneNesting_Inner2 + +func (x *TestVersion4LoneNesting_Inner2) ProtoReflect() protoreflect.Message { + return (*fastReflection_TestVersion4LoneNesting_Inner2)(x) +} + +func (x *TestVersion4LoneNesting_Inner2) slowProtoReflect() protoreflect.Message { + mi := &file_unknownproto_proto_msgTypes[30] + if protoimpl.UnsafeEnabled && x != nil { + ms := protoimpl.X.MessageStateOf(protoimpl.Pointer(x)) + if ms.LoadMessageInfo() == nil { + ms.StoreMessageInfo(mi) + } + return ms + } + return mi.MessageOf(x) +} + +var _fastReflection_TestVersion4LoneNesting_Inner2_messageType fastReflection_TestVersion4LoneNesting_Inner2_messageType +var _ protoreflect.MessageType = fastReflection_TestVersion4LoneNesting_Inner2_messageType{} + +type fastReflection_TestVersion4LoneNesting_Inner2_messageType struct{} + +func (x fastReflection_TestVersion4LoneNesting_Inner2_messageType) Zero() protoreflect.Message { + return (*fastReflection_TestVersion4LoneNesting_Inner2)(nil) +} +func (x fastReflection_TestVersion4LoneNesting_Inner2_messageType) New() protoreflect.Message { + return new(fastReflection_TestVersion4LoneNesting_Inner2) +} +func (x fastReflection_TestVersion4LoneNesting_Inner2_messageType) Descriptor() protoreflect.MessageDescriptor { + return md_TestVersion4LoneNesting_Inner2 +} + +// Descriptor returns message descriptor, which contains only the protobuf +// type information for the message. +func (x *fastReflection_TestVersion4LoneNesting_Inner2) Descriptor() protoreflect.MessageDescriptor { + return md_TestVersion4LoneNesting_Inner2 +} + +// Type returns the message type, which encapsulates both Go and protobuf +// type information. If the Go type information is not needed, +// it is recommended that the message descriptor be used instead. +func (x *fastReflection_TestVersion4LoneNesting_Inner2) Type() protoreflect.MessageType { + return _fastReflection_TestVersion4LoneNesting_Inner2_messageType +} + +// New returns a newly allocated and mutable empty message. +func (x *fastReflection_TestVersion4LoneNesting_Inner2) New() protoreflect.Message { + return new(fastReflection_TestVersion4LoneNesting_Inner2) +} + +// Interface unwraps the message reflection interface and +// returns the underlying ProtoMessage interface. +func (x *fastReflection_TestVersion4LoneNesting_Inner2) Interface() protoreflect.ProtoMessage { + return (*TestVersion4LoneNesting_Inner2)(x) +} + +// Range iterates over every populated field in an undefined order, +// calling f for each field descriptor and value encountered. +// Range returns immediately if f returns false. +// While iterating, mutating operations may only be performed +// on the current field descriptor. +func (x *fastReflection_TestVersion4LoneNesting_Inner2) Range(f func(protoreflect.FieldDescriptor, protoreflect.Value) bool) { + if x.Id != "" { + value := protoreflect.ValueOfString(x.Id) + if !f(fd_TestVersion4LoneNesting_Inner2_id, value) { + return + } + } + if x.Country != "" { + value := protoreflect.ValueOfString(x.Country) + if !f(fd_TestVersion4LoneNesting_Inner2_country, value) { + return + } + } + if x.Inner != nil { + value := protoreflect.ValueOfMessage(x.Inner.ProtoReflect()) + if !f(fd_TestVersion4LoneNesting_Inner2_inner, value) { + return + } + } +} + +// Has reports whether a field is populated. +// +// Some fields have the property of nullability where it is possible to +// distinguish between the default value of a field and whether the field +// was explicitly populated with the default value. Singular message fields, +// member fields of a oneof, and proto2 scalar fields are nullable. Such +// fields are populated only if explicitly set. +// +// In other cases (aside from the nullable cases above), +// a proto3 scalar field is populated if it contains a non-zero value, and +// a repeated field is populated if it is non-empty. +func (x *fastReflection_TestVersion4LoneNesting_Inner2) Has(fd protoreflect.FieldDescriptor) bool { + switch fd.FullName() { + case "testpb.TestVersion4LoneNesting.Inner2.id": + return x.Id != "" + case "testpb.TestVersion4LoneNesting.Inner2.country": + return x.Country != "" + case "testpb.TestVersion4LoneNesting.Inner2.inner": + return x.Inner != nil + default: + if fd.IsExtension() { + panic(fmt.Errorf("proto3 declared messages do not support extensions: testpb.TestVersion4LoneNesting.Inner2")) + } + panic(fmt.Errorf("message testpb.TestVersion4LoneNesting.Inner2 does not contain field %s", fd.FullName())) + } +} + +// Clear clears the field such that a subsequent Has call reports false. +// +// Clearing an extension field clears both the extension type and value +// associated with the given field number. +// +// Clear is a mutating operation and unsafe for concurrent use. +func (x *fastReflection_TestVersion4LoneNesting_Inner2) Clear(fd protoreflect.FieldDescriptor) { + switch fd.FullName() { + case "testpb.TestVersion4LoneNesting.Inner2.id": + x.Id = "" + case "testpb.TestVersion4LoneNesting.Inner2.country": + x.Country = "" + case "testpb.TestVersion4LoneNesting.Inner2.inner": + x.Inner = nil + default: + if fd.IsExtension() { + panic(fmt.Errorf("proto3 declared messages do not support extensions: testpb.TestVersion4LoneNesting.Inner2")) + } + panic(fmt.Errorf("message testpb.TestVersion4LoneNesting.Inner2 does not contain field %s", fd.FullName())) + } +} + +// Get retrieves the value for a field. +// +// For unpopulated scalars, it returns the default value, where +// the default value of a bytes scalar is guaranteed to be a copy. +// For unpopulated composite types, it returns an empty, read-only view +// of the value; to obtain a mutable reference, use Mutable. +func (x *fastReflection_TestVersion4LoneNesting_Inner2) Get(descriptor protoreflect.FieldDescriptor) protoreflect.Value { + switch descriptor.FullName() { + case "testpb.TestVersion4LoneNesting.Inner2.id": + value := x.Id + return protoreflect.ValueOfString(value) + case "testpb.TestVersion4LoneNesting.Inner2.country": + value := x.Country + return protoreflect.ValueOfString(value) + case "testpb.TestVersion4LoneNesting.Inner2.inner": + value := x.Inner + return protoreflect.ValueOfMessage(value.ProtoReflect()) + default: + if descriptor.IsExtension() { + panic(fmt.Errorf("proto3 declared messages do not support extensions: testpb.TestVersion4LoneNesting.Inner2")) + } + panic(fmt.Errorf("message testpb.TestVersion4LoneNesting.Inner2 does not contain field %s", descriptor.FullName())) + } +} + +// Set stores the value for a field. +// +// For a field belonging to a oneof, it implicitly clears any other field +// that may be currently set within the same oneof. +// For extension fields, it implicitly stores the provided ExtensionType. +// When setting a composite type, it is unspecified whether the stored value +// aliases the source's memory in any way. If the composite value is an +// empty, read-only value, then it panics. +// +// Set is a mutating operation and unsafe for concurrent use. +func (x *fastReflection_TestVersion4LoneNesting_Inner2) Set(fd protoreflect.FieldDescriptor, value protoreflect.Value) { + switch fd.FullName() { + case "testpb.TestVersion4LoneNesting.Inner2.id": + x.Id = value.Interface().(string) + case "testpb.TestVersion4LoneNesting.Inner2.country": + x.Country = value.Interface().(string) + case "testpb.TestVersion4LoneNesting.Inner2.inner": + x.Inner = value.Message().Interface().(*TestVersion4LoneNesting_Inner2_InnerInner) + default: + if fd.IsExtension() { + panic(fmt.Errorf("proto3 declared messages do not support extensions: testpb.TestVersion4LoneNesting.Inner2")) + } + panic(fmt.Errorf("message testpb.TestVersion4LoneNesting.Inner2 does not contain field %s", fd.FullName())) + } +} + +// Mutable returns a mutable reference to a composite type. +// +// If the field is unpopulated, it may allocate a composite value. +// For a field belonging to a oneof, it implicitly clears any other field +// that may be currently set within the same oneof. +// For extension fields, it implicitly stores the provided ExtensionType +// if not already stored. +// It panics if the field does not contain a composite type. +// +// Mutable is a mutating operation and unsafe for concurrent use. +func (x *fastReflection_TestVersion4LoneNesting_Inner2) Mutable(fd protoreflect.FieldDescriptor) protoreflect.Value { + switch fd.FullName() { + case "testpb.TestVersion4LoneNesting.Inner2.inner": + if x.Inner == nil { + x.Inner = new(TestVersion4LoneNesting_Inner2_InnerInner) + } + return protoreflect.ValueOfMessage(x.Inner.ProtoReflect()) + case "testpb.TestVersion4LoneNesting.Inner2.id": + panic(fmt.Errorf("field id of message testpb.TestVersion4LoneNesting.Inner2 is not mutable")) + case "testpb.TestVersion4LoneNesting.Inner2.country": + panic(fmt.Errorf("field country of message testpb.TestVersion4LoneNesting.Inner2 is not mutable")) + default: + if fd.IsExtension() { + panic(fmt.Errorf("proto3 declared messages do not support extensions: testpb.TestVersion4LoneNesting.Inner2")) + } + panic(fmt.Errorf("message testpb.TestVersion4LoneNesting.Inner2 does not contain field %s", fd.FullName())) + } +} + +// NewField returns a new value that is assignable to the field +// for the given descriptor. For scalars, this returns the default value. +// For lists, maps, and messages, this returns a new, empty, mutable value. +func (x *fastReflection_TestVersion4LoneNesting_Inner2) NewField(fd protoreflect.FieldDescriptor) protoreflect.Value { + switch fd.FullName() { + case "testpb.TestVersion4LoneNesting.Inner2.id": + return protoreflect.ValueOfString("") + case "testpb.TestVersion4LoneNesting.Inner2.country": + return protoreflect.ValueOfString("") + case "testpb.TestVersion4LoneNesting.Inner2.inner": + m := new(TestVersion4LoneNesting_Inner2_InnerInner) + return protoreflect.ValueOfMessage(m.ProtoReflect()) + default: + if fd.IsExtension() { + panic(fmt.Errorf("proto3 declared messages do not support extensions: testpb.TestVersion4LoneNesting.Inner2")) + } + panic(fmt.Errorf("message testpb.TestVersion4LoneNesting.Inner2 does not contain field %s", fd.FullName())) + } +} + +// WhichOneof reports which field within the oneof is populated, +// returning nil if none are populated. +// It panics if the oneof descriptor does not belong to this message. +func (x *fastReflection_TestVersion4LoneNesting_Inner2) WhichOneof(d protoreflect.OneofDescriptor) protoreflect.FieldDescriptor { + switch d.FullName() { + default: + panic(fmt.Errorf("%s is not a oneof field in testpb.TestVersion4LoneNesting.Inner2", d.FullName())) + } + panic("unreachable") +} + +// GetUnknown retrieves the entire list of unknown fields. +// The caller may only mutate the contents of the RawFields +// if the mutated bytes are stored back into the message with SetUnknown. +func (x *fastReflection_TestVersion4LoneNesting_Inner2) GetUnknown() protoreflect.RawFields { + return x.unknownFields +} + +// SetUnknown stores an entire list of unknown fields. +// The raw fields must be syntactically valid according to the wire format. +// An implementation may panic if this is not the case. +// Once stored, the caller must not mutate the content of the RawFields. +// An empty RawFields may be passed to clear the fields. +// +// SetUnknown is a mutating operation and unsafe for concurrent use. +func (x *fastReflection_TestVersion4LoneNesting_Inner2) SetUnknown(fields protoreflect.RawFields) { + x.unknownFields = fields +} + +// IsValid reports whether the message is valid. +// +// An invalid message is an empty, read-only value. +// +// An invalid message often corresponds to a nil pointer of the concrete +// message type, but the details are implementation dependent. +// Validity is not part of the protobuf data model, and may not +// be preserved in marshaling or other operations. +func (x *fastReflection_TestVersion4LoneNesting_Inner2) IsValid() bool { + return x != nil +} + +// ProtoMethods returns optional fastReflectionFeature-path implementations of various operations. +// This method may return nil. +// +// The returned methods type is identical to +// "google.golang.org/protobuf/runtime/protoiface".Methods. +// Consult the protoiface package documentation for details. +func (x *fastReflection_TestVersion4LoneNesting_Inner2) ProtoMethods() *protoiface.Methods { + size := func(input protoiface.SizeInput) protoiface.SizeOutput { + x := input.Message.Interface().(*TestVersion4LoneNesting_Inner2) + if x == nil { + return protoiface.SizeOutput{ + NoUnkeyedLiterals: input.NoUnkeyedLiterals, + Size: 0, + } + } + options := runtime.SizeInputToOptions(input) + _ = options + var n int + var l int + _ = l + l = len(x.Id) + if l > 0 { + n += 1 + l + runtime.Sov(uint64(l)) + } + l = len(x.Country) + if l > 0 { + n += 1 + l + runtime.Sov(uint64(l)) + } + if x.Inner != nil { + l = options.Size(x.Inner) + n += 1 + l + runtime.Sov(uint64(l)) + } + if x.unknownFields != nil { + n += len(x.unknownFields) + } + return protoiface.SizeOutput{ + NoUnkeyedLiterals: input.NoUnkeyedLiterals, + Size: n, + } + } + + marshal := func(input protoiface.MarshalInput) (protoiface.MarshalOutput, error) { + x := input.Message.Interface().(*TestVersion4LoneNesting_Inner2) + if x == nil { + return protoiface.MarshalOutput{ + NoUnkeyedLiterals: input.NoUnkeyedLiterals, + Buf: input.Buf, + }, nil + } + options := runtime.MarshalInputToOptions(input) + _ = options + size := options.Size(x) + dAtA := make([]byte, size) + i := len(dAtA) + _ = i + var l int + _ = l + if x.unknownFields != nil { + i -= len(x.unknownFields) + copy(dAtA[i:], x.unknownFields) + } + if x.Inner != nil { + encoded, err := options.Marshal(x.Inner) + if err != nil { + return protoiface.MarshalOutput{ + NoUnkeyedLiterals: input.NoUnkeyedLiterals, + Buf: input.Buf, + }, err + } + i -= len(encoded) + copy(dAtA[i:], encoded) + i = runtime.EncodeVarint(dAtA, i, uint64(len(encoded))) + i-- + dAtA[i] = 0x1a + } + if len(x.Country) > 0 { + i -= len(x.Country) + copy(dAtA[i:], x.Country) + i = runtime.EncodeVarint(dAtA, i, uint64(len(x.Country))) + i-- + dAtA[i] = 0x12 + } + if len(x.Id) > 0 { + i -= len(x.Id) + copy(dAtA[i:], x.Id) + i = runtime.EncodeVarint(dAtA, i, uint64(len(x.Id))) + i-- + dAtA[i] = 0xa + } + if input.Buf != nil { + input.Buf = append(input.Buf, dAtA...) + } else { + input.Buf = dAtA + } + return protoiface.MarshalOutput{ + NoUnkeyedLiterals: input.NoUnkeyedLiterals, + Buf: input.Buf, + }, nil + } + unmarshal := func(input protoiface.UnmarshalInput) (protoiface.UnmarshalOutput, error) { + x := input.Message.Interface().(*TestVersion4LoneNesting_Inner2) + if x == nil { + return protoiface.UnmarshalOutput{ + NoUnkeyedLiterals: input.NoUnkeyedLiterals, + Flags: input.Flags, + }, nil + } + options := runtime.UnmarshalInputToOptions(input) + _ = options + dAtA := input.Buf + l := len(dAtA) + iNdEx := 0 + for iNdEx < l { + preIndex := iNdEx + var wire uint64 + for shift := uint(0); ; shift += 7 { + if shift >= 64 { + return protoiface.UnmarshalOutput{NoUnkeyedLiterals: input.NoUnkeyedLiterals, Flags: input.Flags}, runtime.ErrIntOverflow + } + if iNdEx >= l { + return protoiface.UnmarshalOutput{NoUnkeyedLiterals: input.NoUnkeyedLiterals, Flags: input.Flags}, io.ErrUnexpectedEOF + } + b := dAtA[iNdEx] + iNdEx++ + wire |= uint64(b&0x7F) << shift + if b < 0x80 { + break + } + } + fieldNum := int32(wire >> 3) + wireType := int(wire & 0x7) + if wireType == 4 { + return protoiface.UnmarshalOutput{NoUnkeyedLiterals: input.NoUnkeyedLiterals, Flags: input.Flags}, fmt.Errorf("proto: TestVersion4LoneNesting_Inner2: wiretype end group for non-group") + } + if fieldNum <= 0 { + return protoiface.UnmarshalOutput{NoUnkeyedLiterals: input.NoUnkeyedLiterals, Flags: input.Flags}, fmt.Errorf("proto: TestVersion4LoneNesting_Inner2: illegal tag %d (wire type %d)", fieldNum, wire) + } + switch fieldNum { + case 1: + if wireType != 2 { + return protoiface.UnmarshalOutput{NoUnkeyedLiterals: input.NoUnkeyedLiterals, Flags: input.Flags}, fmt.Errorf("proto: wrong wireType = %d for field Id", wireType) + } + var stringLen uint64 + for shift := uint(0); ; shift += 7 { + if shift >= 64 { + return protoiface.UnmarshalOutput{NoUnkeyedLiterals: input.NoUnkeyedLiterals, Flags: input.Flags}, runtime.ErrIntOverflow + } + if iNdEx >= l { + return protoiface.UnmarshalOutput{NoUnkeyedLiterals: input.NoUnkeyedLiterals, Flags: input.Flags}, io.ErrUnexpectedEOF + } + b := dAtA[iNdEx] + iNdEx++ + stringLen |= uint64(b&0x7F) << shift + if b < 0x80 { + break + } + } + intStringLen := int(stringLen) + if intStringLen < 0 { + return protoiface.UnmarshalOutput{NoUnkeyedLiterals: input.NoUnkeyedLiterals, Flags: input.Flags}, runtime.ErrInvalidLength + } + postIndex := iNdEx + intStringLen + if postIndex < 0 { + return protoiface.UnmarshalOutput{NoUnkeyedLiterals: input.NoUnkeyedLiterals, Flags: input.Flags}, runtime.ErrInvalidLength + } + if postIndex > l { + return protoiface.UnmarshalOutput{NoUnkeyedLiterals: input.NoUnkeyedLiterals, Flags: input.Flags}, io.ErrUnexpectedEOF + } + x.Id = string(dAtA[iNdEx:postIndex]) + iNdEx = postIndex + case 2: + if wireType != 2 { + return protoiface.UnmarshalOutput{NoUnkeyedLiterals: input.NoUnkeyedLiterals, Flags: input.Flags}, fmt.Errorf("proto: wrong wireType = %d for field Country", wireType) + } + var stringLen uint64 + for shift := uint(0); ; shift += 7 { + if shift >= 64 { + return protoiface.UnmarshalOutput{NoUnkeyedLiterals: input.NoUnkeyedLiterals, Flags: input.Flags}, runtime.ErrIntOverflow + } + if iNdEx >= l { + return protoiface.UnmarshalOutput{NoUnkeyedLiterals: input.NoUnkeyedLiterals, Flags: input.Flags}, io.ErrUnexpectedEOF + } + b := dAtA[iNdEx] + iNdEx++ + stringLen |= uint64(b&0x7F) << shift + if b < 0x80 { + break + } + } + intStringLen := int(stringLen) + if intStringLen < 0 { + return protoiface.UnmarshalOutput{NoUnkeyedLiterals: input.NoUnkeyedLiterals, Flags: input.Flags}, runtime.ErrInvalidLength + } + postIndex := iNdEx + intStringLen + if postIndex < 0 { + return protoiface.UnmarshalOutput{NoUnkeyedLiterals: input.NoUnkeyedLiterals, Flags: input.Flags}, runtime.ErrInvalidLength + } + if postIndex > l { + return protoiface.UnmarshalOutput{NoUnkeyedLiterals: input.NoUnkeyedLiterals, Flags: input.Flags}, io.ErrUnexpectedEOF + } + x.Country = string(dAtA[iNdEx:postIndex]) + iNdEx = postIndex + case 3: + if wireType != 2 { + return protoiface.UnmarshalOutput{NoUnkeyedLiterals: input.NoUnkeyedLiterals, Flags: input.Flags}, fmt.Errorf("proto: wrong wireType = %d for field Inner", wireType) + } + var msglen int + for shift := uint(0); ; shift += 7 { + if shift >= 64 { + return protoiface.UnmarshalOutput{NoUnkeyedLiterals: input.NoUnkeyedLiterals, Flags: input.Flags}, runtime.ErrIntOverflow + } + if iNdEx >= l { + return protoiface.UnmarshalOutput{NoUnkeyedLiterals: input.NoUnkeyedLiterals, Flags: input.Flags}, io.ErrUnexpectedEOF + } + b := dAtA[iNdEx] + iNdEx++ + msglen |= int(b&0x7F) << shift + if b < 0x80 { + break + } + } + if msglen < 0 { + return protoiface.UnmarshalOutput{NoUnkeyedLiterals: input.NoUnkeyedLiterals, Flags: input.Flags}, runtime.ErrInvalidLength + } + postIndex := iNdEx + msglen + if postIndex < 0 { + return protoiface.UnmarshalOutput{NoUnkeyedLiterals: input.NoUnkeyedLiterals, Flags: input.Flags}, runtime.ErrInvalidLength + } + if postIndex > l { + return protoiface.UnmarshalOutput{NoUnkeyedLiterals: input.NoUnkeyedLiterals, Flags: input.Flags}, io.ErrUnexpectedEOF + } + if x.Inner == nil { + x.Inner = &TestVersion4LoneNesting_Inner2_InnerInner{} + } + if err := options.Unmarshal(dAtA[iNdEx:postIndex], x.Inner); err != nil { + return protoiface.UnmarshalOutput{NoUnkeyedLiterals: input.NoUnkeyedLiterals, Flags: input.Flags}, err + } + iNdEx = postIndex + default: + iNdEx = preIndex + skippy, err := runtime.Skip(dAtA[iNdEx:]) + if err != nil { + return protoiface.UnmarshalOutput{NoUnkeyedLiterals: input.NoUnkeyedLiterals, Flags: input.Flags}, err + } + if (skippy < 0) || (iNdEx+skippy) < 0 { + return protoiface.UnmarshalOutput{NoUnkeyedLiterals: input.NoUnkeyedLiterals, Flags: input.Flags}, runtime.ErrInvalidLength + } + if (iNdEx + skippy) > l { + return protoiface.UnmarshalOutput{NoUnkeyedLiterals: input.NoUnkeyedLiterals, Flags: input.Flags}, io.ErrUnexpectedEOF + } + if !options.DiscardUnknown { + x.unknownFields = append(x.unknownFields, dAtA[iNdEx:iNdEx+skippy]...) + } + iNdEx += skippy + } + } + + if iNdEx > l { + return protoiface.UnmarshalOutput{NoUnkeyedLiterals: input.NoUnkeyedLiterals, Flags: input.Flags}, io.ErrUnexpectedEOF + } + return protoiface.UnmarshalOutput{NoUnkeyedLiterals: input.NoUnkeyedLiterals, Flags: input.Flags}, nil + } + return &protoiface.Methods{ + NoUnkeyedLiterals: struct{}{}, + Flags: protoiface.SupportMarshalDeterministic | protoiface.SupportUnmarshalDiscardUnknown, + Size: size, + Marshal: marshal, + Unmarshal: unmarshal, + Merge: nil, + CheckInitialized: nil, + } +} + +var ( + md_TestVersion4LoneNesting_Inner2_InnerInner protoreflect.MessageDescriptor + fd_TestVersion4LoneNesting_Inner2_InnerInner_id protoreflect.FieldDescriptor + fd_TestVersion4LoneNesting_Inner2_InnerInner_value protoreflect.FieldDescriptor +) + +func init() { + file_unknownproto_proto_init() + md_TestVersion4LoneNesting_Inner2_InnerInner = File_unknownproto_proto.Messages().ByName("TestVersion4LoneNesting").Messages().ByName("Inner2").Messages().ByName("InnerInner") + fd_TestVersion4LoneNesting_Inner2_InnerInner_id = md_TestVersion4LoneNesting_Inner2_InnerInner.Fields().ByName("id") + fd_TestVersion4LoneNesting_Inner2_InnerInner_value = md_TestVersion4LoneNesting_Inner2_InnerInner.Fields().ByName("value") +} + +var _ protoreflect.Message = (*fastReflection_TestVersion4LoneNesting_Inner2_InnerInner)(nil) + +type fastReflection_TestVersion4LoneNesting_Inner2_InnerInner TestVersion4LoneNesting_Inner2_InnerInner + +func (x *TestVersion4LoneNesting_Inner2_InnerInner) ProtoReflect() protoreflect.Message { + return (*fastReflection_TestVersion4LoneNesting_Inner2_InnerInner)(x) +} + +func (x *TestVersion4LoneNesting_Inner2_InnerInner) slowProtoReflect() protoreflect.Message { + mi := &file_unknownproto_proto_msgTypes[32] + if protoimpl.UnsafeEnabled && x != nil { + ms := protoimpl.X.MessageStateOf(protoimpl.Pointer(x)) + if ms.LoadMessageInfo() == nil { + ms.StoreMessageInfo(mi) + } + return ms + } + return mi.MessageOf(x) +} + +var _fastReflection_TestVersion4LoneNesting_Inner2_InnerInner_messageType fastReflection_TestVersion4LoneNesting_Inner2_InnerInner_messageType +var _ protoreflect.MessageType = fastReflection_TestVersion4LoneNesting_Inner2_InnerInner_messageType{} + +type fastReflection_TestVersion4LoneNesting_Inner2_InnerInner_messageType struct{} + +func (x fastReflection_TestVersion4LoneNesting_Inner2_InnerInner_messageType) Zero() protoreflect.Message { + return (*fastReflection_TestVersion4LoneNesting_Inner2_InnerInner)(nil) +} +func (x fastReflection_TestVersion4LoneNesting_Inner2_InnerInner_messageType) New() protoreflect.Message { + return new(fastReflection_TestVersion4LoneNesting_Inner2_InnerInner) +} +func (x fastReflection_TestVersion4LoneNesting_Inner2_InnerInner_messageType) Descriptor() protoreflect.MessageDescriptor { + return md_TestVersion4LoneNesting_Inner2_InnerInner +} + +// Descriptor returns message descriptor, which contains only the protobuf +// type information for the message. +func (x *fastReflection_TestVersion4LoneNesting_Inner2_InnerInner) Descriptor() protoreflect.MessageDescriptor { + return md_TestVersion4LoneNesting_Inner2_InnerInner +} + +// Type returns the message type, which encapsulates both Go and protobuf +// type information. If the Go type information is not needed, +// it is recommended that the message descriptor be used instead. +func (x *fastReflection_TestVersion4LoneNesting_Inner2_InnerInner) Type() protoreflect.MessageType { + return _fastReflection_TestVersion4LoneNesting_Inner2_InnerInner_messageType +} + +// New returns a newly allocated and mutable empty message. +func (x *fastReflection_TestVersion4LoneNesting_Inner2_InnerInner) New() protoreflect.Message { + return new(fastReflection_TestVersion4LoneNesting_Inner2_InnerInner) +} + +// Interface unwraps the message reflection interface and +// returns the underlying ProtoMessage interface. +func (x *fastReflection_TestVersion4LoneNesting_Inner2_InnerInner) Interface() protoreflect.ProtoMessage { + return (*TestVersion4LoneNesting_Inner2_InnerInner)(x) +} + +// Range iterates over every populated field in an undefined order, +// calling f for each field descriptor and value encountered. +// Range returns immediately if f returns false. +// While iterating, mutating operations may only be performed +// on the current field descriptor. +func (x *fastReflection_TestVersion4LoneNesting_Inner2_InnerInner) Range(f func(protoreflect.FieldDescriptor, protoreflect.Value) bool) { + if x.Id != "" { + value := protoreflect.ValueOfString(x.Id) + if !f(fd_TestVersion4LoneNesting_Inner2_InnerInner_id, value) { + return + } + } + if x.Value != int64(0) { + value := protoreflect.ValueOfInt64(x.Value) + if !f(fd_TestVersion4LoneNesting_Inner2_InnerInner_value, value) { + return + } + } +} + +// Has reports whether a field is populated. +// +// Some fields have the property of nullability where it is possible to +// distinguish between the default value of a field and whether the field +// was explicitly populated with the default value. Singular message fields, +// member fields of a oneof, and proto2 scalar fields are nullable. Such +// fields are populated only if explicitly set. +// +// In other cases (aside from the nullable cases above), +// a proto3 scalar field is populated if it contains a non-zero value, and +// a repeated field is populated if it is non-empty. +func (x *fastReflection_TestVersion4LoneNesting_Inner2_InnerInner) Has(fd protoreflect.FieldDescriptor) bool { + switch fd.FullName() { + case "testpb.TestVersion4LoneNesting.Inner2.InnerInner.id": + return x.Id != "" + case "testpb.TestVersion4LoneNesting.Inner2.InnerInner.value": + return x.Value != int64(0) + default: + if fd.IsExtension() { + panic(fmt.Errorf("proto3 declared messages do not support extensions: testpb.TestVersion4LoneNesting.Inner2.InnerInner")) + } + panic(fmt.Errorf("message testpb.TestVersion4LoneNesting.Inner2.InnerInner does not contain field %s", fd.FullName())) + } +} + +// Clear clears the field such that a subsequent Has call reports false. +// +// Clearing an extension field clears both the extension type and value +// associated with the given field number. +// +// Clear is a mutating operation and unsafe for concurrent use. +func (x *fastReflection_TestVersion4LoneNesting_Inner2_InnerInner) Clear(fd protoreflect.FieldDescriptor) { + switch fd.FullName() { + case "testpb.TestVersion4LoneNesting.Inner2.InnerInner.id": + x.Id = "" + case "testpb.TestVersion4LoneNesting.Inner2.InnerInner.value": + x.Value = int64(0) + default: + if fd.IsExtension() { + panic(fmt.Errorf("proto3 declared messages do not support extensions: testpb.TestVersion4LoneNesting.Inner2.InnerInner")) + } + panic(fmt.Errorf("message testpb.TestVersion4LoneNesting.Inner2.InnerInner does not contain field %s", fd.FullName())) + } +} + +// Get retrieves the value for a field. +// +// For unpopulated scalars, it returns the default value, where +// the default value of a bytes scalar is guaranteed to be a copy. +// For unpopulated composite types, it returns an empty, read-only view +// of the value; to obtain a mutable reference, use Mutable. +func (x *fastReflection_TestVersion4LoneNesting_Inner2_InnerInner) Get(descriptor protoreflect.FieldDescriptor) protoreflect.Value { + switch descriptor.FullName() { + case "testpb.TestVersion4LoneNesting.Inner2.InnerInner.id": + value := x.Id + return protoreflect.ValueOfString(value) + case "testpb.TestVersion4LoneNesting.Inner2.InnerInner.value": + value := x.Value + return protoreflect.ValueOfInt64(value) + default: + if descriptor.IsExtension() { + panic(fmt.Errorf("proto3 declared messages do not support extensions: testpb.TestVersion4LoneNesting.Inner2.InnerInner")) + } + panic(fmt.Errorf("message testpb.TestVersion4LoneNesting.Inner2.InnerInner does not contain field %s", descriptor.FullName())) + } +} + +// Set stores the value for a field. +// +// For a field belonging to a oneof, it implicitly clears any other field +// that may be currently set within the same oneof. +// For extension fields, it implicitly stores the provided ExtensionType. +// When setting a composite type, it is unspecified whether the stored value +// aliases the source's memory in any way. If the composite value is an +// empty, read-only value, then it panics. +// +// Set is a mutating operation and unsafe for concurrent use. +func (x *fastReflection_TestVersion4LoneNesting_Inner2_InnerInner) Set(fd protoreflect.FieldDescriptor, value protoreflect.Value) { + switch fd.FullName() { + case "testpb.TestVersion4LoneNesting.Inner2.InnerInner.id": + x.Id = value.Interface().(string) + case "testpb.TestVersion4LoneNesting.Inner2.InnerInner.value": + x.Value = value.Int() + default: + if fd.IsExtension() { + panic(fmt.Errorf("proto3 declared messages do not support extensions: testpb.TestVersion4LoneNesting.Inner2.InnerInner")) + } + panic(fmt.Errorf("message testpb.TestVersion4LoneNesting.Inner2.InnerInner does not contain field %s", fd.FullName())) + } +} + +// Mutable returns a mutable reference to a composite type. +// +// If the field is unpopulated, it may allocate a composite value. +// For a field belonging to a oneof, it implicitly clears any other field +// that may be currently set within the same oneof. +// For extension fields, it implicitly stores the provided ExtensionType +// if not already stored. +// It panics if the field does not contain a composite type. +// +// Mutable is a mutating operation and unsafe for concurrent use. +func (x *fastReflection_TestVersion4LoneNesting_Inner2_InnerInner) Mutable(fd protoreflect.FieldDescriptor) protoreflect.Value { + switch fd.FullName() { + case "testpb.TestVersion4LoneNesting.Inner2.InnerInner.id": + panic(fmt.Errorf("field id of message testpb.TestVersion4LoneNesting.Inner2.InnerInner is not mutable")) + case "testpb.TestVersion4LoneNesting.Inner2.InnerInner.value": + panic(fmt.Errorf("field value of message testpb.TestVersion4LoneNesting.Inner2.InnerInner is not mutable")) + default: + if fd.IsExtension() { + panic(fmt.Errorf("proto3 declared messages do not support extensions: testpb.TestVersion4LoneNesting.Inner2.InnerInner")) + } + panic(fmt.Errorf("message testpb.TestVersion4LoneNesting.Inner2.InnerInner does not contain field %s", fd.FullName())) + } +} + +// NewField returns a new value that is assignable to the field +// for the given descriptor. For scalars, this returns the default value. +// For lists, maps, and messages, this returns a new, empty, mutable value. +func (x *fastReflection_TestVersion4LoneNesting_Inner2_InnerInner) NewField(fd protoreflect.FieldDescriptor) protoreflect.Value { + switch fd.FullName() { + case "testpb.TestVersion4LoneNesting.Inner2.InnerInner.id": + return protoreflect.ValueOfString("") + case "testpb.TestVersion4LoneNesting.Inner2.InnerInner.value": + return protoreflect.ValueOfInt64(int64(0)) + default: + if fd.IsExtension() { + panic(fmt.Errorf("proto3 declared messages do not support extensions: testpb.TestVersion4LoneNesting.Inner2.InnerInner")) + } + panic(fmt.Errorf("message testpb.TestVersion4LoneNesting.Inner2.InnerInner does not contain field %s", fd.FullName())) + } +} + +// WhichOneof reports which field within the oneof is populated, +// returning nil if none are populated. +// It panics if the oneof descriptor does not belong to this message. +func (x *fastReflection_TestVersion4LoneNesting_Inner2_InnerInner) WhichOneof(d protoreflect.OneofDescriptor) protoreflect.FieldDescriptor { + switch d.FullName() { + default: + panic(fmt.Errorf("%s is not a oneof field in testpb.TestVersion4LoneNesting.Inner2.InnerInner", d.FullName())) + } + panic("unreachable") +} + +// GetUnknown retrieves the entire list of unknown fields. +// The caller may only mutate the contents of the RawFields +// if the mutated bytes are stored back into the message with SetUnknown. +func (x *fastReflection_TestVersion4LoneNesting_Inner2_InnerInner) GetUnknown() protoreflect.RawFields { + return x.unknownFields +} + +// SetUnknown stores an entire list of unknown fields. +// The raw fields must be syntactically valid according to the wire format. +// An implementation may panic if this is not the case. +// Once stored, the caller must not mutate the content of the RawFields. +// An empty RawFields may be passed to clear the fields. +// +// SetUnknown is a mutating operation and unsafe for concurrent use. +func (x *fastReflection_TestVersion4LoneNesting_Inner2_InnerInner) SetUnknown(fields protoreflect.RawFields) { + x.unknownFields = fields +} + +// IsValid reports whether the message is valid. +// +// An invalid message is an empty, read-only value. +// +// An invalid message often corresponds to a nil pointer of the concrete +// message type, but the details are implementation dependent. +// Validity is not part of the protobuf data model, and may not +// be preserved in marshaling or other operations. +func (x *fastReflection_TestVersion4LoneNesting_Inner2_InnerInner) IsValid() bool { + return x != nil +} + +// ProtoMethods returns optional fastReflectionFeature-path implementations of various operations. +// This method may return nil. +// +// The returned methods type is identical to +// "google.golang.org/protobuf/runtime/protoiface".Methods. +// Consult the protoiface package documentation for details. +func (x *fastReflection_TestVersion4LoneNesting_Inner2_InnerInner) ProtoMethods() *protoiface.Methods { + size := func(input protoiface.SizeInput) protoiface.SizeOutput { + x := input.Message.Interface().(*TestVersion4LoneNesting_Inner2_InnerInner) + if x == nil { + return protoiface.SizeOutput{ + NoUnkeyedLiterals: input.NoUnkeyedLiterals, + Size: 0, + } + } + options := runtime.SizeInputToOptions(input) + _ = options + var n int + var l int + _ = l + l = len(x.Id) + if l > 0 { + n += 1 + l + runtime.Sov(uint64(l)) + } + if x.Value != 0 { + n += 1 + runtime.Sov(uint64(x.Value)) + } + if x.unknownFields != nil { + n += len(x.unknownFields) + } + return protoiface.SizeOutput{ + NoUnkeyedLiterals: input.NoUnkeyedLiterals, + Size: n, + } + } + + marshal := func(input protoiface.MarshalInput) (protoiface.MarshalOutput, error) { + x := input.Message.Interface().(*TestVersion4LoneNesting_Inner2_InnerInner) + if x == nil { + return protoiface.MarshalOutput{ + NoUnkeyedLiterals: input.NoUnkeyedLiterals, + Buf: input.Buf, + }, nil + } + options := runtime.MarshalInputToOptions(input) + _ = options + size := options.Size(x) + dAtA := make([]byte, size) + i := len(dAtA) + _ = i + var l int + _ = l + if x.unknownFields != nil { + i -= len(x.unknownFields) + copy(dAtA[i:], x.unknownFields) + } + if x.Value != 0 { + i = runtime.EncodeVarint(dAtA, i, uint64(x.Value)) + i-- + dAtA[i] = 0x10 + } + if len(x.Id) > 0 { + i -= len(x.Id) + copy(dAtA[i:], x.Id) + i = runtime.EncodeVarint(dAtA, i, uint64(len(x.Id))) + i-- + dAtA[i] = 0xa + } + if input.Buf != nil { + input.Buf = append(input.Buf, dAtA...) + } else { + input.Buf = dAtA + } + return protoiface.MarshalOutput{ + NoUnkeyedLiterals: input.NoUnkeyedLiterals, + Buf: input.Buf, + }, nil + } + unmarshal := func(input protoiface.UnmarshalInput) (protoiface.UnmarshalOutput, error) { + x := input.Message.Interface().(*TestVersion4LoneNesting_Inner2_InnerInner) + if x == nil { + return protoiface.UnmarshalOutput{ + NoUnkeyedLiterals: input.NoUnkeyedLiterals, + Flags: input.Flags, + }, nil + } + options := runtime.UnmarshalInputToOptions(input) + _ = options + dAtA := input.Buf + l := len(dAtA) + iNdEx := 0 + for iNdEx < l { + preIndex := iNdEx + var wire uint64 + for shift := uint(0); ; shift += 7 { + if shift >= 64 { + return protoiface.UnmarshalOutput{NoUnkeyedLiterals: input.NoUnkeyedLiterals, Flags: input.Flags}, runtime.ErrIntOverflow + } + if iNdEx >= l { + return protoiface.UnmarshalOutput{NoUnkeyedLiterals: input.NoUnkeyedLiterals, Flags: input.Flags}, io.ErrUnexpectedEOF + } + b := dAtA[iNdEx] + iNdEx++ + wire |= uint64(b&0x7F) << shift + if b < 0x80 { + break + } + } + fieldNum := int32(wire >> 3) + wireType := int(wire & 0x7) + if wireType == 4 { + return protoiface.UnmarshalOutput{NoUnkeyedLiterals: input.NoUnkeyedLiterals, Flags: input.Flags}, fmt.Errorf("proto: TestVersion4LoneNesting_Inner2_InnerInner: wiretype end group for non-group") + } + if fieldNum <= 0 { + return protoiface.UnmarshalOutput{NoUnkeyedLiterals: input.NoUnkeyedLiterals, Flags: input.Flags}, fmt.Errorf("proto: TestVersion4LoneNesting_Inner2_InnerInner: illegal tag %d (wire type %d)", fieldNum, wire) + } + switch fieldNum { + case 1: + if wireType != 2 { + return protoiface.UnmarshalOutput{NoUnkeyedLiterals: input.NoUnkeyedLiterals, Flags: input.Flags}, fmt.Errorf("proto: wrong wireType = %d for field Id", wireType) + } + var stringLen uint64 + for shift := uint(0); ; shift += 7 { + if shift >= 64 { + return protoiface.UnmarshalOutput{NoUnkeyedLiterals: input.NoUnkeyedLiterals, Flags: input.Flags}, runtime.ErrIntOverflow + } + if iNdEx >= l { + return protoiface.UnmarshalOutput{NoUnkeyedLiterals: input.NoUnkeyedLiterals, Flags: input.Flags}, io.ErrUnexpectedEOF + } + b := dAtA[iNdEx] + iNdEx++ + stringLen |= uint64(b&0x7F) << shift + if b < 0x80 { + break + } + } + intStringLen := int(stringLen) + if intStringLen < 0 { + return protoiface.UnmarshalOutput{NoUnkeyedLiterals: input.NoUnkeyedLiterals, Flags: input.Flags}, runtime.ErrInvalidLength + } + postIndex := iNdEx + intStringLen + if postIndex < 0 { + return protoiface.UnmarshalOutput{NoUnkeyedLiterals: input.NoUnkeyedLiterals, Flags: input.Flags}, runtime.ErrInvalidLength + } + if postIndex > l { + return protoiface.UnmarshalOutput{NoUnkeyedLiterals: input.NoUnkeyedLiterals, Flags: input.Flags}, io.ErrUnexpectedEOF + } + x.Id = string(dAtA[iNdEx:postIndex]) + iNdEx = postIndex + case 2: + if wireType != 0 { + return protoiface.UnmarshalOutput{NoUnkeyedLiterals: input.NoUnkeyedLiterals, Flags: input.Flags}, fmt.Errorf("proto: wrong wireType = %d for field Value", wireType) + } + x.Value = 0 + for shift := uint(0); ; shift += 7 { + if shift >= 64 { + return protoiface.UnmarshalOutput{NoUnkeyedLiterals: input.NoUnkeyedLiterals, Flags: input.Flags}, runtime.ErrIntOverflow + } + if iNdEx >= l { + return protoiface.UnmarshalOutput{NoUnkeyedLiterals: input.NoUnkeyedLiterals, Flags: input.Flags}, io.ErrUnexpectedEOF + } + b := dAtA[iNdEx] + iNdEx++ + x.Value |= int64(b&0x7F) << shift + if b < 0x80 { + break + } + } + default: + iNdEx = preIndex + skippy, err := runtime.Skip(dAtA[iNdEx:]) + if err != nil { + return protoiface.UnmarshalOutput{NoUnkeyedLiterals: input.NoUnkeyedLiterals, Flags: input.Flags}, err + } + if (skippy < 0) || (iNdEx+skippy) < 0 { + return protoiface.UnmarshalOutput{NoUnkeyedLiterals: input.NoUnkeyedLiterals, Flags: input.Flags}, runtime.ErrInvalidLength + } + if (iNdEx + skippy) > l { + return protoiface.UnmarshalOutput{NoUnkeyedLiterals: input.NoUnkeyedLiterals, Flags: input.Flags}, io.ErrUnexpectedEOF + } + if !options.DiscardUnknown { + x.unknownFields = append(x.unknownFields, dAtA[iNdEx:iNdEx+skippy]...) + } + iNdEx += skippy + } + } + + if iNdEx > l { + return protoiface.UnmarshalOutput{NoUnkeyedLiterals: input.NoUnkeyedLiterals, Flags: input.Flags}, io.ErrUnexpectedEOF + } + return protoiface.UnmarshalOutput{NoUnkeyedLiterals: input.NoUnkeyedLiterals, Flags: input.Flags}, nil + } + return &protoiface.Methods{ + NoUnkeyedLiterals: struct{}{}, + Flags: protoiface.SupportMarshalDeterministic | protoiface.SupportUnmarshalDiscardUnknown, + Size: size, + Marshal: marshal, + Unmarshal: unmarshal, + Merge: nil, + CheckInitialized: nil, + } +} + +var _ protoreflect.List = (*_TestVersionFD1_9_list)(nil) + +type _TestVersionFD1_9_list struct { + list *[]*TestVersion1 +} + +func (x *_TestVersionFD1_9_list) Len() int { + if x.list == nil { + return 0 + } + return len(*x.list) +} + +func (x *_TestVersionFD1_9_list) Get(i int) protoreflect.Value { + return protoreflect.ValueOfMessage((*x.list)[i].ProtoReflect()) +} + +func (x *_TestVersionFD1_9_list) Set(i int, value protoreflect.Value) { + valueUnwrapped := value.Message() + concreteValue := valueUnwrapped.Interface().(*TestVersion1) + (*x.list)[i] = concreteValue +} + +func (x *_TestVersionFD1_9_list) Append(value protoreflect.Value) { + valueUnwrapped := value.Message() + concreteValue := valueUnwrapped.Interface().(*TestVersion1) + *x.list = append(*x.list, concreteValue) +} + +func (x *_TestVersionFD1_9_list) AppendMutable() protoreflect.Value { + v := new(TestVersion1) + *x.list = append(*x.list, v) + return protoreflect.ValueOfMessage(v.ProtoReflect()) +} + +func (x *_TestVersionFD1_9_list) Truncate(n int) { + for i := n; i < len(*x.list); i++ { + (*x.list)[i] = nil + } + *x.list = (*x.list)[:n] +} + +func (x *_TestVersionFD1_9_list) NewElement() protoreflect.Value { + v := new(TestVersion1) + return protoreflect.ValueOfMessage(v.ProtoReflect()) +} + +func (x *_TestVersionFD1_9_list) IsValid() bool { + return x.list != nil +} + +var ( + md_TestVersionFD1 protoreflect.MessageDescriptor + fd_TestVersionFD1_x protoreflect.FieldDescriptor + fd_TestVersionFD1_a protoreflect.FieldDescriptor + fd_TestVersionFD1_e protoreflect.FieldDescriptor + fd_TestVersionFD1_f protoreflect.FieldDescriptor + fd_TestVersionFD1_g protoreflect.FieldDescriptor + fd_TestVersionFD1_h protoreflect.FieldDescriptor +) + +func init() { + file_unknownproto_proto_init() + md_TestVersionFD1 = File_unknownproto_proto.Messages().ByName("TestVersionFD1") + fd_TestVersionFD1_x = md_TestVersionFD1.Fields().ByName("x") + fd_TestVersionFD1_a = md_TestVersionFD1.Fields().ByName("a") + fd_TestVersionFD1_e = md_TestVersionFD1.Fields().ByName("e") + fd_TestVersionFD1_f = md_TestVersionFD1.Fields().ByName("f") + fd_TestVersionFD1_g = md_TestVersionFD1.Fields().ByName("g") + fd_TestVersionFD1_h = md_TestVersionFD1.Fields().ByName("h") +} + +var _ protoreflect.Message = (*fastReflection_TestVersionFD1)(nil) + +type fastReflection_TestVersionFD1 TestVersionFD1 + +func (x *TestVersionFD1) ProtoReflect() protoreflect.Message { + return (*fastReflection_TestVersionFD1)(x) +} + +func (x *TestVersionFD1) slowProtoReflect() protoreflect.Message { + mi := &file_unknownproto_proto_msgTypes[17] + if protoimpl.UnsafeEnabled && x != nil { + ms := protoimpl.X.MessageStateOf(protoimpl.Pointer(x)) + if ms.LoadMessageInfo() == nil { + ms.StoreMessageInfo(mi) + } + return ms + } + return mi.MessageOf(x) +} + +var _fastReflection_TestVersionFD1_messageType fastReflection_TestVersionFD1_messageType +var _ protoreflect.MessageType = fastReflection_TestVersionFD1_messageType{} + +type fastReflection_TestVersionFD1_messageType struct{} + +func (x fastReflection_TestVersionFD1_messageType) Zero() protoreflect.Message { + return (*fastReflection_TestVersionFD1)(nil) +} +func (x fastReflection_TestVersionFD1_messageType) New() protoreflect.Message { + return new(fastReflection_TestVersionFD1) +} +func (x fastReflection_TestVersionFD1_messageType) Descriptor() protoreflect.MessageDescriptor { + return md_TestVersionFD1 +} + +// Descriptor returns message descriptor, which contains only the protobuf +// type information for the message. +func (x *fastReflection_TestVersionFD1) Descriptor() protoreflect.MessageDescriptor { + return md_TestVersionFD1 +} + +// Type returns the message type, which encapsulates both Go and protobuf +// type information. If the Go type information is not needed, +// it is recommended that the message descriptor be used instead. +func (x *fastReflection_TestVersionFD1) Type() protoreflect.MessageType { + return _fastReflection_TestVersionFD1_messageType +} + +// New returns a newly allocated and mutable empty message. +func (x *fastReflection_TestVersionFD1) New() protoreflect.Message { + return new(fastReflection_TestVersionFD1) +} + +// Interface unwraps the message reflection interface and +// returns the underlying ProtoMessage interface. +func (x *fastReflection_TestVersionFD1) Interface() protoreflect.ProtoMessage { + return (*TestVersionFD1)(x) +} + +// Range iterates over every populated field in an undefined order, +// calling f for each field descriptor and value encountered. +// Range returns immediately if f returns false. +// While iterating, mutating operations may only be performed +// on the current field descriptor. +func (x *fastReflection_TestVersionFD1) Range(f func(protoreflect.FieldDescriptor, protoreflect.Value) bool) { + if x.X != int64(0) { + value := protoreflect.ValueOfInt64(x.X) + if !f(fd_TestVersionFD1_x, value) { + return + } + } + if x.A != nil { + value := protoreflect.ValueOfMessage(x.A.ProtoReflect()) + if !f(fd_TestVersionFD1_a, value) { + return + } + } + if x.Sum != nil { + switch o := x.Sum.(type) { + case *TestVersionFD1_E: + v := o.E + value := protoreflect.ValueOfInt32(v) + if !f(fd_TestVersionFD1_e, value) { + return + } + case *TestVersionFD1_F: + v := o.F + value := protoreflect.ValueOfMessage(v.ProtoReflect()) + if !f(fd_TestVersionFD1_f, value) { + return + } + } + } + if x.G != nil { + value := protoreflect.ValueOfMessage(x.G.ProtoReflect()) + if !f(fd_TestVersionFD1_g, value) { + return + } + } + if len(x.H) != 0 { + value := protoreflect.ValueOfList(&_TestVersionFD1_9_list{list: &x.H}) + if !f(fd_TestVersionFD1_h, value) { + return + } + } +} + +// Has reports whether a field is populated. +// +// Some fields have the property of nullability where it is possible to +// distinguish between the default value of a field and whether the field +// was explicitly populated with the default value. Singular message fields, +// member fields of a oneof, and proto2 scalar fields are nullable. Such +// fields are populated only if explicitly set. +// +// In other cases (aside from the nullable cases above), +// a proto3 scalar field is populated if it contains a non-zero value, and +// a repeated field is populated if it is non-empty. +func (x *fastReflection_TestVersionFD1) Has(fd protoreflect.FieldDescriptor) bool { + switch fd.FullName() { + case "testpb.TestVersionFD1.x": + return x.X != int64(0) + case "testpb.TestVersionFD1.a": + return x.A != nil + case "testpb.TestVersionFD1.e": + if x.Sum == nil { + return false + } else if _, ok := x.Sum.(*TestVersionFD1_E); ok { + return true + } else { + return false + } + case "testpb.TestVersionFD1.f": + if x.Sum == nil { + return false + } else if _, ok := x.Sum.(*TestVersionFD1_F); ok { + return true + } else { + return false + } + case "testpb.TestVersionFD1.g": + return x.G != nil + case "testpb.TestVersionFD1.h": + return len(x.H) != 0 + default: + if fd.IsExtension() { + panic(fmt.Errorf("proto3 declared messages do not support extensions: testpb.TestVersionFD1")) + } + panic(fmt.Errorf("message testpb.TestVersionFD1 does not contain field %s", fd.FullName())) + } +} + +// Clear clears the field such that a subsequent Has call reports false. +// +// Clearing an extension field clears both the extension type and value +// associated with the given field number. +// +// Clear is a mutating operation and unsafe for concurrent use. +func (x *fastReflection_TestVersionFD1) Clear(fd protoreflect.FieldDescriptor) { + switch fd.FullName() { + case "testpb.TestVersionFD1.x": + x.X = int64(0) + case "testpb.TestVersionFD1.a": + x.A = nil + case "testpb.TestVersionFD1.e": + x.Sum = nil + case "testpb.TestVersionFD1.f": + x.Sum = nil + case "testpb.TestVersionFD1.g": + x.G = nil + case "testpb.TestVersionFD1.h": + x.H = nil + default: + if fd.IsExtension() { + panic(fmt.Errorf("proto3 declared messages do not support extensions: testpb.TestVersionFD1")) + } + panic(fmt.Errorf("message testpb.TestVersionFD1 does not contain field %s", fd.FullName())) + } +} + +// Get retrieves the value for a field. +// +// For unpopulated scalars, it returns the default value, where +// the default value of a bytes scalar is guaranteed to be a copy. +// For unpopulated composite types, it returns an empty, read-only view +// of the value; to obtain a mutable reference, use Mutable. +func (x *fastReflection_TestVersionFD1) Get(descriptor protoreflect.FieldDescriptor) protoreflect.Value { + switch descriptor.FullName() { + case "testpb.TestVersionFD1.x": + value := x.X + return protoreflect.ValueOfInt64(value) + case "testpb.TestVersionFD1.a": + value := x.A + return protoreflect.ValueOfMessage(value.ProtoReflect()) + case "testpb.TestVersionFD1.e": + if x.Sum == nil { + return protoreflect.ValueOfInt32(int32(0)) + } else if v, ok := x.Sum.(*TestVersionFD1_E); ok { + return protoreflect.ValueOfInt32(v.E) + } else { + return protoreflect.ValueOfInt32(int32(0)) + } + case "testpb.TestVersionFD1.f": + if x.Sum == nil { + return protoreflect.ValueOfMessage((*TestVersion1)(nil).ProtoReflect()) + } else if v, ok := x.Sum.(*TestVersionFD1_F); ok { + return protoreflect.ValueOfMessage(v.F.ProtoReflect()) + } else { + return protoreflect.ValueOfMessage((*TestVersion1)(nil).ProtoReflect()) + } + case "testpb.TestVersionFD1.g": + value := x.G + return protoreflect.ValueOfMessage(value.ProtoReflect()) + case "testpb.TestVersionFD1.h": + if len(x.H) == 0 { + return protoreflect.ValueOfList(&_TestVersionFD1_9_list{}) + } + listValue := &_TestVersionFD1_9_list{list: &x.H} + return protoreflect.ValueOfList(listValue) + default: + if descriptor.IsExtension() { + panic(fmt.Errorf("proto3 declared messages do not support extensions: testpb.TestVersionFD1")) + } + panic(fmt.Errorf("message testpb.TestVersionFD1 does not contain field %s", descriptor.FullName())) + } +} + +// Set stores the value for a field. +// +// For a field belonging to a oneof, it implicitly clears any other field +// that may be currently set within the same oneof. +// For extension fields, it implicitly stores the provided ExtensionType. +// When setting a composite type, it is unspecified whether the stored value +// aliases the source's memory in any way. If the composite value is an +// empty, read-only value, then it panics. +// +// Set is a mutating operation and unsafe for concurrent use. +func (x *fastReflection_TestVersionFD1) Set(fd protoreflect.FieldDescriptor, value protoreflect.Value) { + switch fd.FullName() { + case "testpb.TestVersionFD1.x": + x.X = value.Int() + case "testpb.TestVersionFD1.a": + x.A = value.Message().Interface().(*TestVersion1) + case "testpb.TestVersionFD1.e": + cv := int32(value.Int()) + x.Sum = &TestVersionFD1_E{E: cv} + case "testpb.TestVersionFD1.f": + cv := value.Message().Interface().(*TestVersion1) + x.Sum = &TestVersionFD1_F{F: cv} + case "testpb.TestVersionFD1.g": + x.G = value.Message().Interface().(*anypb.Any) + case "testpb.TestVersionFD1.h": + lv := value.List() + clv := lv.(*_TestVersionFD1_9_list) + x.H = *clv.list + default: + if fd.IsExtension() { + panic(fmt.Errorf("proto3 declared messages do not support extensions: testpb.TestVersionFD1")) + } + panic(fmt.Errorf("message testpb.TestVersionFD1 does not contain field %s", fd.FullName())) + } +} + +// Mutable returns a mutable reference to a composite type. +// +// If the field is unpopulated, it may allocate a composite value. +// For a field belonging to a oneof, it implicitly clears any other field +// that may be currently set within the same oneof. +// For extension fields, it implicitly stores the provided ExtensionType +// if not already stored. +// It panics if the field does not contain a composite type. +// +// Mutable is a mutating operation and unsafe for concurrent use. +func (x *fastReflection_TestVersionFD1) Mutable(fd protoreflect.FieldDescriptor) protoreflect.Value { + switch fd.FullName() { + case "testpb.TestVersionFD1.a": + if x.A == nil { + x.A = new(TestVersion1) + } + return protoreflect.ValueOfMessage(x.A.ProtoReflect()) + case "testpb.TestVersionFD1.f": + if x.Sum == nil { + value := &TestVersion1{} + oneofValue := &TestVersionFD1_F{F: value} + x.Sum = oneofValue + return protoreflect.ValueOfMessage(value.ProtoReflect()) + } + switch m := x.Sum.(type) { + case *TestVersionFD1_F: + return protoreflect.ValueOfMessage(m.F.ProtoReflect()) + default: + value := &TestVersion1{} + oneofValue := &TestVersionFD1_F{F: value} + x.Sum = oneofValue + return protoreflect.ValueOfMessage(value.ProtoReflect()) + } + case "testpb.TestVersionFD1.g": + if x.G == nil { + x.G = new(anypb.Any) + } + return protoreflect.ValueOfMessage(x.G.ProtoReflect()) + case "testpb.TestVersionFD1.h": + if x.H == nil { + x.H = []*TestVersion1{} + } + value := &_TestVersionFD1_9_list{list: &x.H} + return protoreflect.ValueOfList(value) + case "testpb.TestVersionFD1.x": + panic(fmt.Errorf("field x of message testpb.TestVersionFD1 is not mutable")) + case "testpb.TestVersionFD1.e": + panic(fmt.Errorf("field e of message testpb.TestVersionFD1 is not mutable")) + default: + if fd.IsExtension() { + panic(fmt.Errorf("proto3 declared messages do not support extensions: testpb.TestVersionFD1")) + } + panic(fmt.Errorf("message testpb.TestVersionFD1 does not contain field %s", fd.FullName())) + } +} + +// NewField returns a new value that is assignable to the field +// for the given descriptor. For scalars, this returns the default value. +// For lists, maps, and messages, this returns a new, empty, mutable value. +func (x *fastReflection_TestVersionFD1) NewField(fd protoreflect.FieldDescriptor) protoreflect.Value { + switch fd.FullName() { + case "testpb.TestVersionFD1.x": + return protoreflect.ValueOfInt64(int64(0)) + case "testpb.TestVersionFD1.a": + m := new(TestVersion1) + return protoreflect.ValueOfMessage(m.ProtoReflect()) + case "testpb.TestVersionFD1.e": + return protoreflect.ValueOfInt32(int32(0)) + case "testpb.TestVersionFD1.f": + value := &TestVersion1{} + return protoreflect.ValueOfMessage(value.ProtoReflect()) + case "testpb.TestVersionFD1.g": + m := new(anypb.Any) + return protoreflect.ValueOfMessage(m.ProtoReflect()) + case "testpb.TestVersionFD1.h": + list := []*TestVersion1{} + return protoreflect.ValueOfList(&_TestVersionFD1_9_list{list: &list}) + default: + if fd.IsExtension() { + panic(fmt.Errorf("proto3 declared messages do not support extensions: testpb.TestVersionFD1")) + } + panic(fmt.Errorf("message testpb.TestVersionFD1 does not contain field %s", fd.FullName())) + } +} + +// WhichOneof reports which field within the oneof is populated, +// returning nil if none are populated. +// It panics if the oneof descriptor does not belong to this message. +func (x *fastReflection_TestVersionFD1) WhichOneof(d protoreflect.OneofDescriptor) protoreflect.FieldDescriptor { + switch d.FullName() { + case "testpb.TestVersionFD1.sum": + if x.Sum == nil { + return nil + } + switch x.Sum.(type) { + case *TestVersionFD1_E: + return x.Descriptor().Fields().ByName("e") + case *TestVersionFD1_F: + return x.Descriptor().Fields().ByName("f") + } + default: + panic(fmt.Errorf("%s is not a oneof field in testpb.TestVersionFD1", d.FullName())) + } + panic("unreachable") +} + +// GetUnknown retrieves the entire list of unknown fields. +// The caller may only mutate the contents of the RawFields +// if the mutated bytes are stored back into the message with SetUnknown. +func (x *fastReflection_TestVersionFD1) GetUnknown() protoreflect.RawFields { + return x.unknownFields +} + +// SetUnknown stores an entire list of unknown fields. +// The raw fields must be syntactically valid according to the wire format. +// An implementation may panic if this is not the case. +// Once stored, the caller must not mutate the content of the RawFields. +// An empty RawFields may be passed to clear the fields. +// +// SetUnknown is a mutating operation and unsafe for concurrent use. +func (x *fastReflection_TestVersionFD1) SetUnknown(fields protoreflect.RawFields) { + x.unknownFields = fields +} + +// IsValid reports whether the message is valid. +// +// An invalid message is an empty, read-only value. +// +// An invalid message often corresponds to a nil pointer of the concrete +// message type, but the details are implementation dependent. +// Validity is not part of the protobuf data model, and may not +// be preserved in marshaling or other operations. +func (x *fastReflection_TestVersionFD1) IsValid() bool { + return x != nil +} + +// ProtoMethods returns optional fastReflectionFeature-path implementations of various operations. +// This method may return nil. +// +// The returned methods type is identical to +// "google.golang.org/protobuf/runtime/protoiface".Methods. +// Consult the protoiface package documentation for details. +func (x *fastReflection_TestVersionFD1) ProtoMethods() *protoiface.Methods { + size := func(input protoiface.SizeInput) protoiface.SizeOutput { + x := input.Message.Interface().(*TestVersionFD1) + if x == nil { + return protoiface.SizeOutput{ + NoUnkeyedLiterals: input.NoUnkeyedLiterals, + Size: 0, + } + } + options := runtime.SizeInputToOptions(input) + _ = options + var n int + var l int + _ = l + if x.X != 0 { + n += 1 + runtime.Sov(uint64(x.X)) + } + if x.A != nil { + l = options.Size(x.A) + n += 1 + l + runtime.Sov(uint64(l)) + } + switch x := x.Sum.(type) { + case *TestVersionFD1_E: + if x == nil { + break + } + n += 1 + runtime.Sov(uint64(x.E)) + case *TestVersionFD1_F: + if x == nil { + break + } + l = options.Size(x.F) + n += 1 + l + runtime.Sov(uint64(l)) + } + if x.G != nil { + l = options.Size(x.G) + n += 1 + l + runtime.Sov(uint64(l)) + } + if len(x.H) > 0 { + for _, e := range x.H { + l = options.Size(e) + n += 1 + l + runtime.Sov(uint64(l)) + } + } + if x.unknownFields != nil { + n += len(x.unknownFields) + } + return protoiface.SizeOutput{ + NoUnkeyedLiterals: input.NoUnkeyedLiterals, + Size: n, + } + } + + marshal := func(input protoiface.MarshalInput) (protoiface.MarshalOutput, error) { + x := input.Message.Interface().(*TestVersionFD1) + if x == nil { + return protoiface.MarshalOutput{ + NoUnkeyedLiterals: input.NoUnkeyedLiterals, + Buf: input.Buf, + }, nil + } + options := runtime.MarshalInputToOptions(input) + _ = options + size := options.Size(x) + dAtA := make([]byte, size) + i := len(dAtA) + _ = i + var l int + _ = l + if x.unknownFields != nil { + i -= len(x.unknownFields) + copy(dAtA[i:], x.unknownFields) + } + switch x := x.Sum.(type) { + case *TestVersionFD1_E: + i = runtime.EncodeVarint(dAtA, i, uint64(x.E)) + i-- + dAtA[i] = 0x30 + case *TestVersionFD1_F: + encoded, err := options.Marshal(x.F) + if err != nil { + return protoiface.MarshalOutput{ + NoUnkeyedLiterals: input.NoUnkeyedLiterals, + Buf: input.Buf, + }, err + } + i -= len(encoded) + copy(dAtA[i:], encoded) + i = runtime.EncodeVarint(dAtA, i, uint64(len(encoded))) + i-- + dAtA[i] = 0x3a + } + if len(x.H) > 0 { + for iNdEx := len(x.H) - 1; iNdEx >= 0; iNdEx-- { + encoded, err := options.Marshal(x.H[iNdEx]) + if err != nil { + return protoiface.MarshalOutput{ + NoUnkeyedLiterals: input.NoUnkeyedLiterals, + Buf: input.Buf, + }, err + } + i -= len(encoded) + copy(dAtA[i:], encoded) + i = runtime.EncodeVarint(dAtA, i, uint64(len(encoded))) + i-- + dAtA[i] = 0x4a + } + } + if x.G != nil { + encoded, err := options.Marshal(x.G) + if err != nil { + return protoiface.MarshalOutput{ + NoUnkeyedLiterals: input.NoUnkeyedLiterals, + Buf: input.Buf, + }, err + } + i -= len(encoded) + copy(dAtA[i:], encoded) + i = runtime.EncodeVarint(dAtA, i, uint64(len(encoded))) + i-- + dAtA[i] = 0x42 + } + if x.A != nil { + encoded, err := options.Marshal(x.A) + if err != nil { + return protoiface.MarshalOutput{ + NoUnkeyedLiterals: input.NoUnkeyedLiterals, + Buf: input.Buf, + }, err + } + i -= len(encoded) + copy(dAtA[i:], encoded) + i = runtime.EncodeVarint(dAtA, i, uint64(len(encoded))) + i-- + dAtA[i] = 0x12 + } + if x.X != 0 { + i = runtime.EncodeVarint(dAtA, i, uint64(x.X)) + i-- + dAtA[i] = 0x8 + } + if input.Buf != nil { + input.Buf = append(input.Buf, dAtA...) + } else { + input.Buf = dAtA + } + return protoiface.MarshalOutput{ + NoUnkeyedLiterals: input.NoUnkeyedLiterals, + Buf: input.Buf, + }, nil + } + unmarshal := func(input protoiface.UnmarshalInput) (protoiface.UnmarshalOutput, error) { + x := input.Message.Interface().(*TestVersionFD1) + if x == nil { + return protoiface.UnmarshalOutput{ + NoUnkeyedLiterals: input.NoUnkeyedLiterals, + Flags: input.Flags, + }, nil + } + options := runtime.UnmarshalInputToOptions(input) + _ = options + dAtA := input.Buf + l := len(dAtA) + iNdEx := 0 + for iNdEx < l { + preIndex := iNdEx + var wire uint64 + for shift := uint(0); ; shift += 7 { + if shift >= 64 { + return protoiface.UnmarshalOutput{NoUnkeyedLiterals: input.NoUnkeyedLiterals, Flags: input.Flags}, runtime.ErrIntOverflow + } + if iNdEx >= l { + return protoiface.UnmarshalOutput{NoUnkeyedLiterals: input.NoUnkeyedLiterals, Flags: input.Flags}, io.ErrUnexpectedEOF + } + b := dAtA[iNdEx] + iNdEx++ + wire |= uint64(b&0x7F) << shift + if b < 0x80 { + break + } + } + fieldNum := int32(wire >> 3) + wireType := int(wire & 0x7) + if wireType == 4 { + return protoiface.UnmarshalOutput{NoUnkeyedLiterals: input.NoUnkeyedLiterals, Flags: input.Flags}, fmt.Errorf("proto: TestVersionFD1: wiretype end group for non-group") + } + if fieldNum <= 0 { + return protoiface.UnmarshalOutput{NoUnkeyedLiterals: input.NoUnkeyedLiterals, Flags: input.Flags}, fmt.Errorf("proto: TestVersionFD1: illegal tag %d (wire type %d)", fieldNum, wire) + } + switch fieldNum { + case 1: + if wireType != 0 { + return protoiface.UnmarshalOutput{NoUnkeyedLiterals: input.NoUnkeyedLiterals, Flags: input.Flags}, fmt.Errorf("proto: wrong wireType = %d for field X", wireType) + } + x.X = 0 + for shift := uint(0); ; shift += 7 { + if shift >= 64 { + return protoiface.UnmarshalOutput{NoUnkeyedLiterals: input.NoUnkeyedLiterals, Flags: input.Flags}, runtime.ErrIntOverflow + } + if iNdEx >= l { + return protoiface.UnmarshalOutput{NoUnkeyedLiterals: input.NoUnkeyedLiterals, Flags: input.Flags}, io.ErrUnexpectedEOF + } + b := dAtA[iNdEx] + iNdEx++ + x.X |= int64(b&0x7F) << shift + if b < 0x80 { + break + } + } + case 2: + if wireType != 2 { + return protoiface.UnmarshalOutput{NoUnkeyedLiterals: input.NoUnkeyedLiterals, Flags: input.Flags}, fmt.Errorf("proto: wrong wireType = %d for field A", wireType) + } + var msglen int + for shift := uint(0); ; shift += 7 { + if shift >= 64 { + return protoiface.UnmarshalOutput{NoUnkeyedLiterals: input.NoUnkeyedLiterals, Flags: input.Flags}, runtime.ErrIntOverflow + } + if iNdEx >= l { + return protoiface.UnmarshalOutput{NoUnkeyedLiterals: input.NoUnkeyedLiterals, Flags: input.Flags}, io.ErrUnexpectedEOF + } + b := dAtA[iNdEx] + iNdEx++ + msglen |= int(b&0x7F) << shift + if b < 0x80 { + break + } + } + if msglen < 0 { + return protoiface.UnmarshalOutput{NoUnkeyedLiterals: input.NoUnkeyedLiterals, Flags: input.Flags}, runtime.ErrInvalidLength + } + postIndex := iNdEx + msglen + if postIndex < 0 { + return protoiface.UnmarshalOutput{NoUnkeyedLiterals: input.NoUnkeyedLiterals, Flags: input.Flags}, runtime.ErrInvalidLength + } + if postIndex > l { + return protoiface.UnmarshalOutput{NoUnkeyedLiterals: input.NoUnkeyedLiterals, Flags: input.Flags}, io.ErrUnexpectedEOF + } + if x.A == nil { + x.A = &TestVersion1{} + } + if err := options.Unmarshal(dAtA[iNdEx:postIndex], x.A); err != nil { + return protoiface.UnmarshalOutput{NoUnkeyedLiterals: input.NoUnkeyedLiterals, Flags: input.Flags}, err + } + iNdEx = postIndex + case 6: + if wireType != 0 { + return protoiface.UnmarshalOutput{NoUnkeyedLiterals: input.NoUnkeyedLiterals, Flags: input.Flags}, fmt.Errorf("proto: wrong wireType = %d for field E", wireType) + } + var v int32 + for shift := uint(0); ; shift += 7 { + if shift >= 64 { + return protoiface.UnmarshalOutput{NoUnkeyedLiterals: input.NoUnkeyedLiterals, Flags: input.Flags}, runtime.ErrIntOverflow + } + if iNdEx >= l { + return protoiface.UnmarshalOutput{NoUnkeyedLiterals: input.NoUnkeyedLiterals, Flags: input.Flags}, io.ErrUnexpectedEOF + } + b := dAtA[iNdEx] + iNdEx++ + v |= int32(b&0x7F) << shift + if b < 0x80 { + break + } + } + x.Sum = &TestVersionFD1_E{v} + case 7: + if wireType != 2 { + return protoiface.UnmarshalOutput{NoUnkeyedLiterals: input.NoUnkeyedLiterals, Flags: input.Flags}, fmt.Errorf("proto: wrong wireType = %d for field F", wireType) + } + var msglen int + for shift := uint(0); ; shift += 7 { + if shift >= 64 { + return protoiface.UnmarshalOutput{NoUnkeyedLiterals: input.NoUnkeyedLiterals, Flags: input.Flags}, runtime.ErrIntOverflow + } + if iNdEx >= l { + return protoiface.UnmarshalOutput{NoUnkeyedLiterals: input.NoUnkeyedLiterals, Flags: input.Flags}, io.ErrUnexpectedEOF + } + b := dAtA[iNdEx] + iNdEx++ + msglen |= int(b&0x7F) << shift + if b < 0x80 { + break + } + } + if msglen < 0 { + return protoiface.UnmarshalOutput{NoUnkeyedLiterals: input.NoUnkeyedLiterals, Flags: input.Flags}, runtime.ErrInvalidLength + } + postIndex := iNdEx + msglen + if postIndex < 0 { + return protoiface.UnmarshalOutput{NoUnkeyedLiterals: input.NoUnkeyedLiterals, Flags: input.Flags}, runtime.ErrInvalidLength + } + if postIndex > l { + return protoiface.UnmarshalOutput{NoUnkeyedLiterals: input.NoUnkeyedLiterals, Flags: input.Flags}, io.ErrUnexpectedEOF + } + v := &TestVersion1{} + if err := options.Unmarshal(dAtA[iNdEx:postIndex], v); err != nil { + return protoiface.UnmarshalOutput{NoUnkeyedLiterals: input.NoUnkeyedLiterals, Flags: input.Flags}, err + } + x.Sum = &TestVersionFD1_F{v} + iNdEx = postIndex + case 8: + if wireType != 2 { + return protoiface.UnmarshalOutput{NoUnkeyedLiterals: input.NoUnkeyedLiterals, Flags: input.Flags}, fmt.Errorf("proto: wrong wireType = %d for field G", wireType) + } + var msglen int + for shift := uint(0); ; shift += 7 { + if shift >= 64 { + return protoiface.UnmarshalOutput{NoUnkeyedLiterals: input.NoUnkeyedLiterals, Flags: input.Flags}, runtime.ErrIntOverflow + } + if iNdEx >= l { + return protoiface.UnmarshalOutput{NoUnkeyedLiterals: input.NoUnkeyedLiterals, Flags: input.Flags}, io.ErrUnexpectedEOF + } + b := dAtA[iNdEx] + iNdEx++ + msglen |= int(b&0x7F) << shift + if b < 0x80 { + break + } + } + if msglen < 0 { + return protoiface.UnmarshalOutput{NoUnkeyedLiterals: input.NoUnkeyedLiterals, Flags: input.Flags}, runtime.ErrInvalidLength + } + postIndex := iNdEx + msglen + if postIndex < 0 { + return protoiface.UnmarshalOutput{NoUnkeyedLiterals: input.NoUnkeyedLiterals, Flags: input.Flags}, runtime.ErrInvalidLength + } + if postIndex > l { + return protoiface.UnmarshalOutput{NoUnkeyedLiterals: input.NoUnkeyedLiterals, Flags: input.Flags}, io.ErrUnexpectedEOF + } + if x.G == nil { + x.G = &anypb.Any{} + } + if err := options.Unmarshal(dAtA[iNdEx:postIndex], x.G); err != nil { + return protoiface.UnmarshalOutput{NoUnkeyedLiterals: input.NoUnkeyedLiterals, Flags: input.Flags}, err + } + iNdEx = postIndex + case 9: + if wireType != 2 { + return protoiface.UnmarshalOutput{NoUnkeyedLiterals: input.NoUnkeyedLiterals, Flags: input.Flags}, fmt.Errorf("proto: wrong wireType = %d for field H", wireType) + } + var msglen int + for shift := uint(0); ; shift += 7 { + if shift >= 64 { + return protoiface.UnmarshalOutput{NoUnkeyedLiterals: input.NoUnkeyedLiterals, Flags: input.Flags}, runtime.ErrIntOverflow + } + if iNdEx >= l { + return protoiface.UnmarshalOutput{NoUnkeyedLiterals: input.NoUnkeyedLiterals, Flags: input.Flags}, io.ErrUnexpectedEOF + } + b := dAtA[iNdEx] + iNdEx++ + msglen |= int(b&0x7F) << shift + if b < 0x80 { + break + } + } + if msglen < 0 { + return protoiface.UnmarshalOutput{NoUnkeyedLiterals: input.NoUnkeyedLiterals, Flags: input.Flags}, runtime.ErrInvalidLength + } + postIndex := iNdEx + msglen + if postIndex < 0 { + return protoiface.UnmarshalOutput{NoUnkeyedLiterals: input.NoUnkeyedLiterals, Flags: input.Flags}, runtime.ErrInvalidLength + } + if postIndex > l { + return protoiface.UnmarshalOutput{NoUnkeyedLiterals: input.NoUnkeyedLiterals, Flags: input.Flags}, io.ErrUnexpectedEOF + } + x.H = append(x.H, &TestVersion1{}) + if err := options.Unmarshal(dAtA[iNdEx:postIndex], x.H[len(x.H)-1]); err != nil { + return protoiface.UnmarshalOutput{NoUnkeyedLiterals: input.NoUnkeyedLiterals, Flags: input.Flags}, err + } + iNdEx = postIndex + default: + iNdEx = preIndex + skippy, err := runtime.Skip(dAtA[iNdEx:]) + if err != nil { + return protoiface.UnmarshalOutput{NoUnkeyedLiterals: input.NoUnkeyedLiterals, Flags: input.Flags}, err + } + if (skippy < 0) || (iNdEx+skippy) < 0 { + return protoiface.UnmarshalOutput{NoUnkeyedLiterals: input.NoUnkeyedLiterals, Flags: input.Flags}, runtime.ErrInvalidLength + } + if (iNdEx + skippy) > l { + return protoiface.UnmarshalOutput{NoUnkeyedLiterals: input.NoUnkeyedLiterals, Flags: input.Flags}, io.ErrUnexpectedEOF + } + if !options.DiscardUnknown { + x.unknownFields = append(x.unknownFields, dAtA[iNdEx:iNdEx+skippy]...) + } + iNdEx += skippy + } + } + + if iNdEx > l { + return protoiface.UnmarshalOutput{NoUnkeyedLiterals: input.NoUnkeyedLiterals, Flags: input.Flags}, io.ErrUnexpectedEOF + } + return protoiface.UnmarshalOutput{NoUnkeyedLiterals: input.NoUnkeyedLiterals, Flags: input.Flags}, nil + } + return &protoiface.Methods{ + NoUnkeyedLiterals: struct{}{}, + Flags: protoiface.SupportMarshalDeterministic | protoiface.SupportUnmarshalDiscardUnknown, + Size: size, + Marshal: marshal, + Unmarshal: unmarshal, + Merge: nil, + CheckInitialized: nil, + } +} + +var _ protoreflect.List = (*_TestVersionFD1WithExtraAny_9_list)(nil) + +type _TestVersionFD1WithExtraAny_9_list struct { + list *[]*TestVersion1 +} + +func (x *_TestVersionFD1WithExtraAny_9_list) Len() int { + if x.list == nil { + return 0 + } + return len(*x.list) +} + +func (x *_TestVersionFD1WithExtraAny_9_list) Get(i int) protoreflect.Value { + return protoreflect.ValueOfMessage((*x.list)[i].ProtoReflect()) +} + +func (x *_TestVersionFD1WithExtraAny_9_list) Set(i int, value protoreflect.Value) { + valueUnwrapped := value.Message() + concreteValue := valueUnwrapped.Interface().(*TestVersion1) + (*x.list)[i] = concreteValue +} + +func (x *_TestVersionFD1WithExtraAny_9_list) Append(value protoreflect.Value) { + valueUnwrapped := value.Message() + concreteValue := valueUnwrapped.Interface().(*TestVersion1) + *x.list = append(*x.list, concreteValue) +} + +func (x *_TestVersionFD1WithExtraAny_9_list) AppendMutable() protoreflect.Value { + v := new(TestVersion1) + *x.list = append(*x.list, v) + return protoreflect.ValueOfMessage(v.ProtoReflect()) +} + +func (x *_TestVersionFD1WithExtraAny_9_list) Truncate(n int) { + for i := n; i < len(*x.list); i++ { + (*x.list)[i] = nil + } + *x.list = (*x.list)[:n] +} + +func (x *_TestVersionFD1WithExtraAny_9_list) NewElement() protoreflect.Value { + v := new(TestVersion1) + return protoreflect.ValueOfMessage(v.ProtoReflect()) +} + +func (x *_TestVersionFD1WithExtraAny_9_list) IsValid() bool { + return x.list != nil +} + +var ( + md_TestVersionFD1WithExtraAny protoreflect.MessageDescriptor + fd_TestVersionFD1WithExtraAny_x protoreflect.FieldDescriptor + fd_TestVersionFD1WithExtraAny_a protoreflect.FieldDescriptor + fd_TestVersionFD1WithExtraAny_e protoreflect.FieldDescriptor + fd_TestVersionFD1WithExtraAny_f protoreflect.FieldDescriptor + fd_TestVersionFD1WithExtraAny_g protoreflect.FieldDescriptor + fd_TestVersionFD1WithExtraAny_h protoreflect.FieldDescriptor +) + +func init() { + file_unknownproto_proto_init() + md_TestVersionFD1WithExtraAny = File_unknownproto_proto.Messages().ByName("TestVersionFD1WithExtraAny") + fd_TestVersionFD1WithExtraAny_x = md_TestVersionFD1WithExtraAny.Fields().ByName("x") + fd_TestVersionFD1WithExtraAny_a = md_TestVersionFD1WithExtraAny.Fields().ByName("a") + fd_TestVersionFD1WithExtraAny_e = md_TestVersionFD1WithExtraAny.Fields().ByName("e") + fd_TestVersionFD1WithExtraAny_f = md_TestVersionFD1WithExtraAny.Fields().ByName("f") + fd_TestVersionFD1WithExtraAny_g = md_TestVersionFD1WithExtraAny.Fields().ByName("g") + fd_TestVersionFD1WithExtraAny_h = md_TestVersionFD1WithExtraAny.Fields().ByName("h") +} + +var _ protoreflect.Message = (*fastReflection_TestVersionFD1WithExtraAny)(nil) + +type fastReflection_TestVersionFD1WithExtraAny TestVersionFD1WithExtraAny + +func (x *TestVersionFD1WithExtraAny) ProtoReflect() protoreflect.Message { + return (*fastReflection_TestVersionFD1WithExtraAny)(x) +} + +func (x *TestVersionFD1WithExtraAny) slowProtoReflect() protoreflect.Message { + mi := &file_unknownproto_proto_msgTypes[18] + if protoimpl.UnsafeEnabled && x != nil { + ms := protoimpl.X.MessageStateOf(protoimpl.Pointer(x)) + if ms.LoadMessageInfo() == nil { + ms.StoreMessageInfo(mi) + } + return ms + } + return mi.MessageOf(x) +} + +var _fastReflection_TestVersionFD1WithExtraAny_messageType fastReflection_TestVersionFD1WithExtraAny_messageType +var _ protoreflect.MessageType = fastReflection_TestVersionFD1WithExtraAny_messageType{} + +type fastReflection_TestVersionFD1WithExtraAny_messageType struct{} + +func (x fastReflection_TestVersionFD1WithExtraAny_messageType) Zero() protoreflect.Message { + return (*fastReflection_TestVersionFD1WithExtraAny)(nil) +} +func (x fastReflection_TestVersionFD1WithExtraAny_messageType) New() protoreflect.Message { + return new(fastReflection_TestVersionFD1WithExtraAny) +} +func (x fastReflection_TestVersionFD1WithExtraAny_messageType) Descriptor() protoreflect.MessageDescriptor { + return md_TestVersionFD1WithExtraAny +} + +// Descriptor returns message descriptor, which contains only the protobuf +// type information for the message. +func (x *fastReflection_TestVersionFD1WithExtraAny) Descriptor() protoreflect.MessageDescriptor { + return md_TestVersionFD1WithExtraAny +} + +// Type returns the message type, which encapsulates both Go and protobuf +// type information. If the Go type information is not needed, +// it is recommended that the message descriptor be used instead. +func (x *fastReflection_TestVersionFD1WithExtraAny) Type() protoreflect.MessageType { + return _fastReflection_TestVersionFD1WithExtraAny_messageType +} + +// New returns a newly allocated and mutable empty message. +func (x *fastReflection_TestVersionFD1WithExtraAny) New() protoreflect.Message { + return new(fastReflection_TestVersionFD1WithExtraAny) +} + +// Interface unwraps the message reflection interface and +// returns the underlying ProtoMessage interface. +func (x *fastReflection_TestVersionFD1WithExtraAny) Interface() protoreflect.ProtoMessage { + return (*TestVersionFD1WithExtraAny)(x) +} + +// Range iterates over every populated field in an undefined order, +// calling f for each field descriptor and value encountered. +// Range returns immediately if f returns false. +// While iterating, mutating operations may only be performed +// on the current field descriptor. +func (x *fastReflection_TestVersionFD1WithExtraAny) Range(f func(protoreflect.FieldDescriptor, protoreflect.Value) bool) { + if x.X != int64(0) { + value := protoreflect.ValueOfInt64(x.X) + if !f(fd_TestVersionFD1WithExtraAny_x, value) { + return + } + } + if x.A != nil { + value := protoreflect.ValueOfMessage(x.A.ProtoReflect()) + if !f(fd_TestVersionFD1WithExtraAny_a, value) { + return + } + } + if x.Sum != nil { + switch o := x.Sum.(type) { + case *TestVersionFD1WithExtraAny_E: + v := o.E + value := protoreflect.ValueOfInt32(v) + if !f(fd_TestVersionFD1WithExtraAny_e, value) { + return + } + case *TestVersionFD1WithExtraAny_F: + v := o.F + value := protoreflect.ValueOfMessage(v.ProtoReflect()) + if !f(fd_TestVersionFD1WithExtraAny_f, value) { + return + } + } + } + if x.G != nil { + value := protoreflect.ValueOfMessage(x.G.ProtoReflect()) + if !f(fd_TestVersionFD1WithExtraAny_g, value) { + return + } + } + if len(x.H) != 0 { + value := protoreflect.ValueOfList(&_TestVersionFD1WithExtraAny_9_list{list: &x.H}) + if !f(fd_TestVersionFD1WithExtraAny_h, value) { + return + } + } +} + +// Has reports whether a field is populated. +// +// Some fields have the property of nullability where it is possible to +// distinguish between the default value of a field and whether the field +// was explicitly populated with the default value. Singular message fields, +// member fields of a oneof, and proto2 scalar fields are nullable. Such +// fields are populated only if explicitly set. +// +// In other cases (aside from the nullable cases above), +// a proto3 scalar field is populated if it contains a non-zero value, and +// a repeated field is populated if it is non-empty. +func (x *fastReflection_TestVersionFD1WithExtraAny) Has(fd protoreflect.FieldDescriptor) bool { + switch fd.FullName() { + case "testpb.TestVersionFD1WithExtraAny.x": + return x.X != int64(0) + case "testpb.TestVersionFD1WithExtraAny.a": + return x.A != nil + case "testpb.TestVersionFD1WithExtraAny.e": + if x.Sum == nil { + return false + } else if _, ok := x.Sum.(*TestVersionFD1WithExtraAny_E); ok { + return true + } else { + return false + } + case "testpb.TestVersionFD1WithExtraAny.f": + if x.Sum == nil { + return false + } else if _, ok := x.Sum.(*TestVersionFD1WithExtraAny_F); ok { + return true + } else { + return false + } + case "testpb.TestVersionFD1WithExtraAny.g": + return x.G != nil + case "testpb.TestVersionFD1WithExtraAny.h": + return len(x.H) != 0 + default: + if fd.IsExtension() { + panic(fmt.Errorf("proto3 declared messages do not support extensions: testpb.TestVersionFD1WithExtraAny")) + } + panic(fmt.Errorf("message testpb.TestVersionFD1WithExtraAny does not contain field %s", fd.FullName())) + } +} + +// Clear clears the field such that a subsequent Has call reports false. +// +// Clearing an extension field clears both the extension type and value +// associated with the given field number. +// +// Clear is a mutating operation and unsafe for concurrent use. +func (x *fastReflection_TestVersionFD1WithExtraAny) Clear(fd protoreflect.FieldDescriptor) { + switch fd.FullName() { + case "testpb.TestVersionFD1WithExtraAny.x": + x.X = int64(0) + case "testpb.TestVersionFD1WithExtraAny.a": + x.A = nil + case "testpb.TestVersionFD1WithExtraAny.e": + x.Sum = nil + case "testpb.TestVersionFD1WithExtraAny.f": + x.Sum = nil + case "testpb.TestVersionFD1WithExtraAny.g": + x.G = nil + case "testpb.TestVersionFD1WithExtraAny.h": + x.H = nil + default: + if fd.IsExtension() { + panic(fmt.Errorf("proto3 declared messages do not support extensions: testpb.TestVersionFD1WithExtraAny")) + } + panic(fmt.Errorf("message testpb.TestVersionFD1WithExtraAny does not contain field %s", fd.FullName())) + } +} + +// Get retrieves the value for a field. +// +// For unpopulated scalars, it returns the default value, where +// the default value of a bytes scalar is guaranteed to be a copy. +// For unpopulated composite types, it returns an empty, read-only view +// of the value; to obtain a mutable reference, use Mutable. +func (x *fastReflection_TestVersionFD1WithExtraAny) Get(descriptor protoreflect.FieldDescriptor) protoreflect.Value { + switch descriptor.FullName() { + case "testpb.TestVersionFD1WithExtraAny.x": + value := x.X + return protoreflect.ValueOfInt64(value) + case "testpb.TestVersionFD1WithExtraAny.a": + value := x.A + return protoreflect.ValueOfMessage(value.ProtoReflect()) + case "testpb.TestVersionFD1WithExtraAny.e": + if x.Sum == nil { + return protoreflect.ValueOfInt32(int32(0)) + } else if v, ok := x.Sum.(*TestVersionFD1WithExtraAny_E); ok { + return protoreflect.ValueOfInt32(v.E) + } else { + return protoreflect.ValueOfInt32(int32(0)) + } + case "testpb.TestVersionFD1WithExtraAny.f": + if x.Sum == nil { + return protoreflect.ValueOfMessage((*TestVersion1)(nil).ProtoReflect()) + } else if v, ok := x.Sum.(*TestVersionFD1WithExtraAny_F); ok { + return protoreflect.ValueOfMessage(v.F.ProtoReflect()) + } else { + return protoreflect.ValueOfMessage((*TestVersion1)(nil).ProtoReflect()) + } + case "testpb.TestVersionFD1WithExtraAny.g": + value := x.G + return protoreflect.ValueOfMessage(value.ProtoReflect()) + case "testpb.TestVersionFD1WithExtraAny.h": + if len(x.H) == 0 { + return protoreflect.ValueOfList(&_TestVersionFD1WithExtraAny_9_list{}) + } + listValue := &_TestVersionFD1WithExtraAny_9_list{list: &x.H} + return protoreflect.ValueOfList(listValue) + default: + if descriptor.IsExtension() { + panic(fmt.Errorf("proto3 declared messages do not support extensions: testpb.TestVersionFD1WithExtraAny")) + } + panic(fmt.Errorf("message testpb.TestVersionFD1WithExtraAny does not contain field %s", descriptor.FullName())) + } +} + +// Set stores the value for a field. +// +// For a field belonging to a oneof, it implicitly clears any other field +// that may be currently set within the same oneof. +// For extension fields, it implicitly stores the provided ExtensionType. +// When setting a composite type, it is unspecified whether the stored value +// aliases the source's memory in any way. If the composite value is an +// empty, read-only value, then it panics. +// +// Set is a mutating operation and unsafe for concurrent use. +func (x *fastReflection_TestVersionFD1WithExtraAny) Set(fd protoreflect.FieldDescriptor, value protoreflect.Value) { + switch fd.FullName() { + case "testpb.TestVersionFD1WithExtraAny.x": + x.X = value.Int() + case "testpb.TestVersionFD1WithExtraAny.a": + x.A = value.Message().Interface().(*TestVersion1) + case "testpb.TestVersionFD1WithExtraAny.e": + cv := int32(value.Int()) + x.Sum = &TestVersionFD1WithExtraAny_E{E: cv} + case "testpb.TestVersionFD1WithExtraAny.f": + cv := value.Message().Interface().(*TestVersion1) + x.Sum = &TestVersionFD1WithExtraAny_F{F: cv} + case "testpb.TestVersionFD1WithExtraAny.g": + x.G = value.Message().Interface().(*AnyWithExtra) + case "testpb.TestVersionFD1WithExtraAny.h": + lv := value.List() + clv := lv.(*_TestVersionFD1WithExtraAny_9_list) + x.H = *clv.list + default: + if fd.IsExtension() { + panic(fmt.Errorf("proto3 declared messages do not support extensions: testpb.TestVersionFD1WithExtraAny")) + } + panic(fmt.Errorf("message testpb.TestVersionFD1WithExtraAny does not contain field %s", fd.FullName())) + } +} + +// Mutable returns a mutable reference to a composite type. +// +// If the field is unpopulated, it may allocate a composite value. +// For a field belonging to a oneof, it implicitly clears any other field +// that may be currently set within the same oneof. +// For extension fields, it implicitly stores the provided ExtensionType +// if not already stored. +// It panics if the field does not contain a composite type. +// +// Mutable is a mutating operation and unsafe for concurrent use. +func (x *fastReflection_TestVersionFD1WithExtraAny) Mutable(fd protoreflect.FieldDescriptor) protoreflect.Value { + switch fd.FullName() { + case "testpb.TestVersionFD1WithExtraAny.a": + if x.A == nil { + x.A = new(TestVersion1) + } + return protoreflect.ValueOfMessage(x.A.ProtoReflect()) + case "testpb.TestVersionFD1WithExtraAny.f": + if x.Sum == nil { + value := &TestVersion1{} + oneofValue := &TestVersionFD1WithExtraAny_F{F: value} + x.Sum = oneofValue + return protoreflect.ValueOfMessage(value.ProtoReflect()) + } + switch m := x.Sum.(type) { + case *TestVersionFD1WithExtraAny_F: + return protoreflect.ValueOfMessage(m.F.ProtoReflect()) + default: + value := &TestVersion1{} + oneofValue := &TestVersionFD1WithExtraAny_F{F: value} + x.Sum = oneofValue + return protoreflect.ValueOfMessage(value.ProtoReflect()) + } + case "testpb.TestVersionFD1WithExtraAny.g": + if x.G == nil { + x.G = new(AnyWithExtra) + } + return protoreflect.ValueOfMessage(x.G.ProtoReflect()) + case "testpb.TestVersionFD1WithExtraAny.h": + if x.H == nil { + x.H = []*TestVersion1{} + } + value := &_TestVersionFD1WithExtraAny_9_list{list: &x.H} + return protoreflect.ValueOfList(value) + case "testpb.TestVersionFD1WithExtraAny.x": + panic(fmt.Errorf("field x of message testpb.TestVersionFD1WithExtraAny is not mutable")) + case "testpb.TestVersionFD1WithExtraAny.e": + panic(fmt.Errorf("field e of message testpb.TestVersionFD1WithExtraAny is not mutable")) + default: + if fd.IsExtension() { + panic(fmt.Errorf("proto3 declared messages do not support extensions: testpb.TestVersionFD1WithExtraAny")) + } + panic(fmt.Errorf("message testpb.TestVersionFD1WithExtraAny does not contain field %s", fd.FullName())) + } +} + +// NewField returns a new value that is assignable to the field +// for the given descriptor. For scalars, this returns the default value. +// For lists, maps, and messages, this returns a new, empty, mutable value. +func (x *fastReflection_TestVersionFD1WithExtraAny) NewField(fd protoreflect.FieldDescriptor) protoreflect.Value { + switch fd.FullName() { + case "testpb.TestVersionFD1WithExtraAny.x": + return protoreflect.ValueOfInt64(int64(0)) + case "testpb.TestVersionFD1WithExtraAny.a": + m := new(TestVersion1) + return protoreflect.ValueOfMessage(m.ProtoReflect()) + case "testpb.TestVersionFD1WithExtraAny.e": + return protoreflect.ValueOfInt32(int32(0)) + case "testpb.TestVersionFD1WithExtraAny.f": + value := &TestVersion1{} + return protoreflect.ValueOfMessage(value.ProtoReflect()) + case "testpb.TestVersionFD1WithExtraAny.g": + m := new(AnyWithExtra) + return protoreflect.ValueOfMessage(m.ProtoReflect()) + case "testpb.TestVersionFD1WithExtraAny.h": + list := []*TestVersion1{} + return protoreflect.ValueOfList(&_TestVersionFD1WithExtraAny_9_list{list: &list}) + default: + if fd.IsExtension() { + panic(fmt.Errorf("proto3 declared messages do not support extensions: testpb.TestVersionFD1WithExtraAny")) + } + panic(fmt.Errorf("message testpb.TestVersionFD1WithExtraAny does not contain field %s", fd.FullName())) + } +} + +// WhichOneof reports which field within the oneof is populated, +// returning nil if none are populated. +// It panics if the oneof descriptor does not belong to this message. +func (x *fastReflection_TestVersionFD1WithExtraAny) WhichOneof(d protoreflect.OneofDescriptor) protoreflect.FieldDescriptor { + switch d.FullName() { + case "testpb.TestVersionFD1WithExtraAny.sum": + if x.Sum == nil { + return nil + } + switch x.Sum.(type) { + case *TestVersionFD1WithExtraAny_E: + return x.Descriptor().Fields().ByName("e") + case *TestVersionFD1WithExtraAny_F: + return x.Descriptor().Fields().ByName("f") + } + default: + panic(fmt.Errorf("%s is not a oneof field in testpb.TestVersionFD1WithExtraAny", d.FullName())) + } + panic("unreachable") +} + +// GetUnknown retrieves the entire list of unknown fields. +// The caller may only mutate the contents of the RawFields +// if the mutated bytes are stored back into the message with SetUnknown. +func (x *fastReflection_TestVersionFD1WithExtraAny) GetUnknown() protoreflect.RawFields { + return x.unknownFields +} + +// SetUnknown stores an entire list of unknown fields. +// The raw fields must be syntactically valid according to the wire format. +// An implementation may panic if this is not the case. +// Once stored, the caller must not mutate the content of the RawFields. +// An empty RawFields may be passed to clear the fields. +// +// SetUnknown is a mutating operation and unsafe for concurrent use. +func (x *fastReflection_TestVersionFD1WithExtraAny) SetUnknown(fields protoreflect.RawFields) { + x.unknownFields = fields +} + +// IsValid reports whether the message is valid. +// +// An invalid message is an empty, read-only value. +// +// An invalid message often corresponds to a nil pointer of the concrete +// message type, but the details are implementation dependent. +// Validity is not part of the protobuf data model, and may not +// be preserved in marshaling or other operations. +func (x *fastReflection_TestVersionFD1WithExtraAny) IsValid() bool { + return x != nil +} + +// ProtoMethods returns optional fastReflectionFeature-path implementations of various operations. +// This method may return nil. +// +// The returned methods type is identical to +// "google.golang.org/protobuf/runtime/protoiface".Methods. +// Consult the protoiface package documentation for details. +func (x *fastReflection_TestVersionFD1WithExtraAny) ProtoMethods() *protoiface.Methods { + size := func(input protoiface.SizeInput) protoiface.SizeOutput { + x := input.Message.Interface().(*TestVersionFD1WithExtraAny) + if x == nil { + return protoiface.SizeOutput{ + NoUnkeyedLiterals: input.NoUnkeyedLiterals, + Size: 0, + } + } + options := runtime.SizeInputToOptions(input) + _ = options + var n int + var l int + _ = l + if x.X != 0 { + n += 1 + runtime.Sov(uint64(x.X)) + } + if x.A != nil { + l = options.Size(x.A) + n += 1 + l + runtime.Sov(uint64(l)) + } + switch x := x.Sum.(type) { + case *TestVersionFD1WithExtraAny_E: + if x == nil { + break + } + n += 1 + runtime.Sov(uint64(x.E)) + case *TestVersionFD1WithExtraAny_F: + if x == nil { + break + } + l = options.Size(x.F) + n += 1 + l + runtime.Sov(uint64(l)) + } + if x.G != nil { + l = options.Size(x.G) + n += 1 + l + runtime.Sov(uint64(l)) + } + if len(x.H) > 0 { + for _, e := range x.H { + l = options.Size(e) + n += 1 + l + runtime.Sov(uint64(l)) + } + } + if x.unknownFields != nil { + n += len(x.unknownFields) + } + return protoiface.SizeOutput{ + NoUnkeyedLiterals: input.NoUnkeyedLiterals, + Size: n, + } + } + + marshal := func(input protoiface.MarshalInput) (protoiface.MarshalOutput, error) { + x := input.Message.Interface().(*TestVersionFD1WithExtraAny) + if x == nil { + return protoiface.MarshalOutput{ + NoUnkeyedLiterals: input.NoUnkeyedLiterals, + Buf: input.Buf, + }, nil + } + options := runtime.MarshalInputToOptions(input) + _ = options + size := options.Size(x) + dAtA := make([]byte, size) + i := len(dAtA) + _ = i + var l int + _ = l + if x.unknownFields != nil { + i -= len(x.unknownFields) + copy(dAtA[i:], x.unknownFields) + } + switch x := x.Sum.(type) { + case *TestVersionFD1WithExtraAny_E: + i = runtime.EncodeVarint(dAtA, i, uint64(x.E)) + i-- + dAtA[i] = 0x30 + case *TestVersionFD1WithExtraAny_F: + encoded, err := options.Marshal(x.F) + if err != nil { + return protoiface.MarshalOutput{ + NoUnkeyedLiterals: input.NoUnkeyedLiterals, + Buf: input.Buf, + }, err + } + i -= len(encoded) + copy(dAtA[i:], encoded) + i = runtime.EncodeVarint(dAtA, i, uint64(len(encoded))) + i-- + dAtA[i] = 0x3a + } + if len(x.H) > 0 { + for iNdEx := len(x.H) - 1; iNdEx >= 0; iNdEx-- { + encoded, err := options.Marshal(x.H[iNdEx]) + if err != nil { + return protoiface.MarshalOutput{ + NoUnkeyedLiterals: input.NoUnkeyedLiterals, + Buf: input.Buf, + }, err + } + i -= len(encoded) + copy(dAtA[i:], encoded) + i = runtime.EncodeVarint(dAtA, i, uint64(len(encoded))) + i-- + dAtA[i] = 0x4a + } + } + if x.G != nil { + encoded, err := options.Marshal(x.G) + if err != nil { + return protoiface.MarshalOutput{ + NoUnkeyedLiterals: input.NoUnkeyedLiterals, + Buf: input.Buf, + }, err + } + i -= len(encoded) + copy(dAtA[i:], encoded) + i = runtime.EncodeVarint(dAtA, i, uint64(len(encoded))) + i-- + dAtA[i] = 0x42 + } + if x.A != nil { + encoded, err := options.Marshal(x.A) + if err != nil { + return protoiface.MarshalOutput{ + NoUnkeyedLiterals: input.NoUnkeyedLiterals, + Buf: input.Buf, + }, err + } + i -= len(encoded) + copy(dAtA[i:], encoded) + i = runtime.EncodeVarint(dAtA, i, uint64(len(encoded))) + i-- + dAtA[i] = 0x12 + } + if x.X != 0 { + i = runtime.EncodeVarint(dAtA, i, uint64(x.X)) + i-- + dAtA[i] = 0x8 + } + if input.Buf != nil { + input.Buf = append(input.Buf, dAtA...) + } else { + input.Buf = dAtA + } + return protoiface.MarshalOutput{ + NoUnkeyedLiterals: input.NoUnkeyedLiterals, + Buf: input.Buf, + }, nil + } + unmarshal := func(input protoiface.UnmarshalInput) (protoiface.UnmarshalOutput, error) { + x := input.Message.Interface().(*TestVersionFD1WithExtraAny) + if x == nil { + return protoiface.UnmarshalOutput{ + NoUnkeyedLiterals: input.NoUnkeyedLiterals, + Flags: input.Flags, + }, nil + } + options := runtime.UnmarshalInputToOptions(input) + _ = options + dAtA := input.Buf + l := len(dAtA) + iNdEx := 0 + for iNdEx < l { + preIndex := iNdEx + var wire uint64 + for shift := uint(0); ; shift += 7 { + if shift >= 64 { + return protoiface.UnmarshalOutput{NoUnkeyedLiterals: input.NoUnkeyedLiterals, Flags: input.Flags}, runtime.ErrIntOverflow + } + if iNdEx >= l { + return protoiface.UnmarshalOutput{NoUnkeyedLiterals: input.NoUnkeyedLiterals, Flags: input.Flags}, io.ErrUnexpectedEOF + } + b := dAtA[iNdEx] + iNdEx++ + wire |= uint64(b&0x7F) << shift + if b < 0x80 { + break + } + } + fieldNum := int32(wire >> 3) + wireType := int(wire & 0x7) + if wireType == 4 { + return protoiface.UnmarshalOutput{NoUnkeyedLiterals: input.NoUnkeyedLiterals, Flags: input.Flags}, fmt.Errorf("proto: TestVersionFD1WithExtraAny: wiretype end group for non-group") + } + if fieldNum <= 0 { + return protoiface.UnmarshalOutput{NoUnkeyedLiterals: input.NoUnkeyedLiterals, Flags: input.Flags}, fmt.Errorf("proto: TestVersionFD1WithExtraAny: illegal tag %d (wire type %d)", fieldNum, wire) + } + switch fieldNum { + case 1: + if wireType != 0 { + return protoiface.UnmarshalOutput{NoUnkeyedLiterals: input.NoUnkeyedLiterals, Flags: input.Flags}, fmt.Errorf("proto: wrong wireType = %d for field X", wireType) + } + x.X = 0 + for shift := uint(0); ; shift += 7 { + if shift >= 64 { + return protoiface.UnmarshalOutput{NoUnkeyedLiterals: input.NoUnkeyedLiterals, Flags: input.Flags}, runtime.ErrIntOverflow + } + if iNdEx >= l { + return protoiface.UnmarshalOutput{NoUnkeyedLiterals: input.NoUnkeyedLiterals, Flags: input.Flags}, io.ErrUnexpectedEOF + } + b := dAtA[iNdEx] + iNdEx++ + x.X |= int64(b&0x7F) << shift + if b < 0x80 { + break + } + } + case 2: + if wireType != 2 { + return protoiface.UnmarshalOutput{NoUnkeyedLiterals: input.NoUnkeyedLiterals, Flags: input.Flags}, fmt.Errorf("proto: wrong wireType = %d for field A", wireType) + } + var msglen int + for shift := uint(0); ; shift += 7 { + if shift >= 64 { + return protoiface.UnmarshalOutput{NoUnkeyedLiterals: input.NoUnkeyedLiterals, Flags: input.Flags}, runtime.ErrIntOverflow + } + if iNdEx >= l { + return protoiface.UnmarshalOutput{NoUnkeyedLiterals: input.NoUnkeyedLiterals, Flags: input.Flags}, io.ErrUnexpectedEOF + } + b := dAtA[iNdEx] + iNdEx++ + msglen |= int(b&0x7F) << shift + if b < 0x80 { + break + } + } + if msglen < 0 { + return protoiface.UnmarshalOutput{NoUnkeyedLiterals: input.NoUnkeyedLiterals, Flags: input.Flags}, runtime.ErrInvalidLength + } + postIndex := iNdEx + msglen + if postIndex < 0 { + return protoiface.UnmarshalOutput{NoUnkeyedLiterals: input.NoUnkeyedLiterals, Flags: input.Flags}, runtime.ErrInvalidLength + } + if postIndex > l { + return protoiface.UnmarshalOutput{NoUnkeyedLiterals: input.NoUnkeyedLiterals, Flags: input.Flags}, io.ErrUnexpectedEOF + } + if x.A == nil { + x.A = &TestVersion1{} + } + if err := options.Unmarshal(dAtA[iNdEx:postIndex], x.A); err != nil { + return protoiface.UnmarshalOutput{NoUnkeyedLiterals: input.NoUnkeyedLiterals, Flags: input.Flags}, err + } + iNdEx = postIndex + case 6: + if wireType != 0 { + return protoiface.UnmarshalOutput{NoUnkeyedLiterals: input.NoUnkeyedLiterals, Flags: input.Flags}, fmt.Errorf("proto: wrong wireType = %d for field E", wireType) + } + var v int32 + for shift := uint(0); ; shift += 7 { + if shift >= 64 { + return protoiface.UnmarshalOutput{NoUnkeyedLiterals: input.NoUnkeyedLiterals, Flags: input.Flags}, runtime.ErrIntOverflow + } + if iNdEx >= l { + return protoiface.UnmarshalOutput{NoUnkeyedLiterals: input.NoUnkeyedLiterals, Flags: input.Flags}, io.ErrUnexpectedEOF + } + b := dAtA[iNdEx] + iNdEx++ + v |= int32(b&0x7F) << shift + if b < 0x80 { + break + } + } + x.Sum = &TestVersionFD1WithExtraAny_E{v} + case 7: + if wireType != 2 { + return protoiface.UnmarshalOutput{NoUnkeyedLiterals: input.NoUnkeyedLiterals, Flags: input.Flags}, fmt.Errorf("proto: wrong wireType = %d for field F", wireType) + } + var msglen int + for shift := uint(0); ; shift += 7 { + if shift >= 64 { + return protoiface.UnmarshalOutput{NoUnkeyedLiterals: input.NoUnkeyedLiterals, Flags: input.Flags}, runtime.ErrIntOverflow + } + if iNdEx >= l { + return protoiface.UnmarshalOutput{NoUnkeyedLiterals: input.NoUnkeyedLiterals, Flags: input.Flags}, io.ErrUnexpectedEOF + } + b := dAtA[iNdEx] + iNdEx++ + msglen |= int(b&0x7F) << shift + if b < 0x80 { + break + } + } + if msglen < 0 { + return protoiface.UnmarshalOutput{NoUnkeyedLiterals: input.NoUnkeyedLiterals, Flags: input.Flags}, runtime.ErrInvalidLength + } + postIndex := iNdEx + msglen + if postIndex < 0 { + return protoiface.UnmarshalOutput{NoUnkeyedLiterals: input.NoUnkeyedLiterals, Flags: input.Flags}, runtime.ErrInvalidLength + } + if postIndex > l { + return protoiface.UnmarshalOutput{NoUnkeyedLiterals: input.NoUnkeyedLiterals, Flags: input.Flags}, io.ErrUnexpectedEOF + } + v := &TestVersion1{} + if err := options.Unmarshal(dAtA[iNdEx:postIndex], v); err != nil { + return protoiface.UnmarshalOutput{NoUnkeyedLiterals: input.NoUnkeyedLiterals, Flags: input.Flags}, err + } + x.Sum = &TestVersionFD1WithExtraAny_F{v} + iNdEx = postIndex + case 8: + if wireType != 2 { + return protoiface.UnmarshalOutput{NoUnkeyedLiterals: input.NoUnkeyedLiterals, Flags: input.Flags}, fmt.Errorf("proto: wrong wireType = %d for field G", wireType) + } + var msglen int + for shift := uint(0); ; shift += 7 { + if shift >= 64 { + return protoiface.UnmarshalOutput{NoUnkeyedLiterals: input.NoUnkeyedLiterals, Flags: input.Flags}, runtime.ErrIntOverflow + } + if iNdEx >= l { + return protoiface.UnmarshalOutput{NoUnkeyedLiterals: input.NoUnkeyedLiterals, Flags: input.Flags}, io.ErrUnexpectedEOF + } + b := dAtA[iNdEx] + iNdEx++ + msglen |= int(b&0x7F) << shift + if b < 0x80 { + break + } + } + if msglen < 0 { + return protoiface.UnmarshalOutput{NoUnkeyedLiterals: input.NoUnkeyedLiterals, Flags: input.Flags}, runtime.ErrInvalidLength + } + postIndex := iNdEx + msglen + if postIndex < 0 { + return protoiface.UnmarshalOutput{NoUnkeyedLiterals: input.NoUnkeyedLiterals, Flags: input.Flags}, runtime.ErrInvalidLength + } + if postIndex > l { + return protoiface.UnmarshalOutput{NoUnkeyedLiterals: input.NoUnkeyedLiterals, Flags: input.Flags}, io.ErrUnexpectedEOF + } + if x.G == nil { + x.G = &AnyWithExtra{} + } + if err := options.Unmarshal(dAtA[iNdEx:postIndex], x.G); err != nil { + return protoiface.UnmarshalOutput{NoUnkeyedLiterals: input.NoUnkeyedLiterals, Flags: input.Flags}, err + } + iNdEx = postIndex + case 9: + if wireType != 2 { + return protoiface.UnmarshalOutput{NoUnkeyedLiterals: input.NoUnkeyedLiterals, Flags: input.Flags}, fmt.Errorf("proto: wrong wireType = %d for field H", wireType) + } + var msglen int + for shift := uint(0); ; shift += 7 { + if shift >= 64 { + return protoiface.UnmarshalOutput{NoUnkeyedLiterals: input.NoUnkeyedLiterals, Flags: input.Flags}, runtime.ErrIntOverflow + } + if iNdEx >= l { + return protoiface.UnmarshalOutput{NoUnkeyedLiterals: input.NoUnkeyedLiterals, Flags: input.Flags}, io.ErrUnexpectedEOF + } + b := dAtA[iNdEx] + iNdEx++ + msglen |= int(b&0x7F) << shift + if b < 0x80 { + break + } + } + if msglen < 0 { + return protoiface.UnmarshalOutput{NoUnkeyedLiterals: input.NoUnkeyedLiterals, Flags: input.Flags}, runtime.ErrInvalidLength + } + postIndex := iNdEx + msglen + if postIndex < 0 { + return protoiface.UnmarshalOutput{NoUnkeyedLiterals: input.NoUnkeyedLiterals, Flags: input.Flags}, runtime.ErrInvalidLength + } + if postIndex > l { + return protoiface.UnmarshalOutput{NoUnkeyedLiterals: input.NoUnkeyedLiterals, Flags: input.Flags}, io.ErrUnexpectedEOF + } + x.H = append(x.H, &TestVersion1{}) + if err := options.Unmarshal(dAtA[iNdEx:postIndex], x.H[len(x.H)-1]); err != nil { + return protoiface.UnmarshalOutput{NoUnkeyedLiterals: input.NoUnkeyedLiterals, Flags: input.Flags}, err + } + iNdEx = postIndex + default: + iNdEx = preIndex + skippy, err := runtime.Skip(dAtA[iNdEx:]) + if err != nil { + return protoiface.UnmarshalOutput{NoUnkeyedLiterals: input.NoUnkeyedLiterals, Flags: input.Flags}, err + } + if (skippy < 0) || (iNdEx+skippy) < 0 { + return protoiface.UnmarshalOutput{NoUnkeyedLiterals: input.NoUnkeyedLiterals, Flags: input.Flags}, runtime.ErrInvalidLength + } + if (iNdEx + skippy) > l { + return protoiface.UnmarshalOutput{NoUnkeyedLiterals: input.NoUnkeyedLiterals, Flags: input.Flags}, io.ErrUnexpectedEOF + } + if !options.DiscardUnknown { + x.unknownFields = append(x.unknownFields, dAtA[iNdEx:iNdEx+skippy]...) + } + iNdEx += skippy + } + } + + if iNdEx > l { + return protoiface.UnmarshalOutput{NoUnkeyedLiterals: input.NoUnkeyedLiterals, Flags: input.Flags}, io.ErrUnexpectedEOF + } + return protoiface.UnmarshalOutput{NoUnkeyedLiterals: input.NoUnkeyedLiterals, Flags: input.Flags}, nil + } + return &protoiface.Methods{ + NoUnkeyedLiterals: struct{}{}, + Flags: protoiface.SupportMarshalDeterministic | protoiface.SupportUnmarshalDiscardUnknown, + Size: size, + Marshal: marshal, + Unmarshal: unmarshal, + Merge: nil, + CheckInitialized: nil, + } +} + +var ( + md_AnyWithExtra protoreflect.MessageDescriptor + fd_AnyWithExtra_a protoreflect.FieldDescriptor + fd_AnyWithExtra_b protoreflect.FieldDescriptor + fd_AnyWithExtra_c protoreflect.FieldDescriptor +) + +func init() { + file_unknownproto_proto_init() + md_AnyWithExtra = File_unknownproto_proto.Messages().ByName("AnyWithExtra") + fd_AnyWithExtra_a = md_AnyWithExtra.Fields().ByName("a") + fd_AnyWithExtra_b = md_AnyWithExtra.Fields().ByName("b") + fd_AnyWithExtra_c = md_AnyWithExtra.Fields().ByName("c") +} + +var _ protoreflect.Message = (*fastReflection_AnyWithExtra)(nil) + +type fastReflection_AnyWithExtra AnyWithExtra + +func (x *AnyWithExtra) ProtoReflect() protoreflect.Message { + return (*fastReflection_AnyWithExtra)(x) +} + +func (x *AnyWithExtra) slowProtoReflect() protoreflect.Message { + mi := &file_unknownproto_proto_msgTypes[19] + if protoimpl.UnsafeEnabled && x != nil { + ms := protoimpl.X.MessageStateOf(protoimpl.Pointer(x)) + if ms.LoadMessageInfo() == nil { + ms.StoreMessageInfo(mi) + } + return ms + } + return mi.MessageOf(x) +} + +var _fastReflection_AnyWithExtra_messageType fastReflection_AnyWithExtra_messageType +var _ protoreflect.MessageType = fastReflection_AnyWithExtra_messageType{} + +type fastReflection_AnyWithExtra_messageType struct{} + +func (x fastReflection_AnyWithExtra_messageType) Zero() protoreflect.Message { + return (*fastReflection_AnyWithExtra)(nil) +} +func (x fastReflection_AnyWithExtra_messageType) New() protoreflect.Message { + return new(fastReflection_AnyWithExtra) +} +func (x fastReflection_AnyWithExtra_messageType) Descriptor() protoreflect.MessageDescriptor { + return md_AnyWithExtra +} + +// Descriptor returns message descriptor, which contains only the protobuf +// type information for the message. +func (x *fastReflection_AnyWithExtra) Descriptor() protoreflect.MessageDescriptor { + return md_AnyWithExtra +} + +// Type returns the message type, which encapsulates both Go and protobuf +// type information. If the Go type information is not needed, +// it is recommended that the message descriptor be used instead. +func (x *fastReflection_AnyWithExtra) Type() protoreflect.MessageType { + return _fastReflection_AnyWithExtra_messageType +} + +// New returns a newly allocated and mutable empty message. +func (x *fastReflection_AnyWithExtra) New() protoreflect.Message { + return new(fastReflection_AnyWithExtra) +} + +// Interface unwraps the message reflection interface and +// returns the underlying ProtoMessage interface. +func (x *fastReflection_AnyWithExtra) Interface() protoreflect.ProtoMessage { + return (*AnyWithExtra)(x) +} + +// Range iterates over every populated field in an undefined order, +// calling f for each field descriptor and value encountered. +// Range returns immediately if f returns false. +// While iterating, mutating operations may only be performed +// on the current field descriptor. +func (x *fastReflection_AnyWithExtra) Range(f func(protoreflect.FieldDescriptor, protoreflect.Value) bool) { + if x.A != nil { + value := protoreflect.ValueOfMessage(x.A.ProtoReflect()) + if !f(fd_AnyWithExtra_a, value) { + return + } + } + if x.B != int64(0) { + value := protoreflect.ValueOfInt64(x.B) + if !f(fd_AnyWithExtra_b, value) { + return + } + } + if x.C != int64(0) { + value := protoreflect.ValueOfInt64(x.C) + if !f(fd_AnyWithExtra_c, value) { + return + } + } +} + +// Has reports whether a field is populated. +// +// Some fields have the property of nullability where it is possible to +// distinguish between the default value of a field and whether the field +// was explicitly populated with the default value. Singular message fields, +// member fields of a oneof, and proto2 scalar fields are nullable. Such +// fields are populated only if explicitly set. +// +// In other cases (aside from the nullable cases above), +// a proto3 scalar field is populated if it contains a non-zero value, and +// a repeated field is populated if it is non-empty. +func (x *fastReflection_AnyWithExtra) Has(fd protoreflect.FieldDescriptor) bool { + switch fd.FullName() { + case "testpb.AnyWithExtra.a": + return x.A != nil + case "testpb.AnyWithExtra.b": + return x.B != int64(0) + case "testpb.AnyWithExtra.c": + return x.C != int64(0) + default: + if fd.IsExtension() { + panic(fmt.Errorf("proto3 declared messages do not support extensions: testpb.AnyWithExtra")) + } + panic(fmt.Errorf("message testpb.AnyWithExtra does not contain field %s", fd.FullName())) + } +} + +// Clear clears the field such that a subsequent Has call reports false. +// +// Clearing an extension field clears both the extension type and value +// associated with the given field number. +// +// Clear is a mutating operation and unsafe for concurrent use. +func (x *fastReflection_AnyWithExtra) Clear(fd protoreflect.FieldDescriptor) { + switch fd.FullName() { + case "testpb.AnyWithExtra.a": + x.A = nil + case "testpb.AnyWithExtra.b": + x.B = int64(0) + case "testpb.AnyWithExtra.c": + x.C = int64(0) + default: + if fd.IsExtension() { + panic(fmt.Errorf("proto3 declared messages do not support extensions: testpb.AnyWithExtra")) + } + panic(fmt.Errorf("message testpb.AnyWithExtra does not contain field %s", fd.FullName())) + } +} + +// Get retrieves the value for a field. +// +// For unpopulated scalars, it returns the default value, where +// the default value of a bytes scalar is guaranteed to be a copy. +// For unpopulated composite types, it returns an empty, read-only view +// of the value; to obtain a mutable reference, use Mutable. +func (x *fastReflection_AnyWithExtra) Get(descriptor protoreflect.FieldDescriptor) protoreflect.Value { + switch descriptor.FullName() { + case "testpb.AnyWithExtra.a": + value := x.A + return protoreflect.ValueOfMessage(value.ProtoReflect()) + case "testpb.AnyWithExtra.b": + value := x.B + return protoreflect.ValueOfInt64(value) + case "testpb.AnyWithExtra.c": + value := x.C + return protoreflect.ValueOfInt64(value) + default: + if descriptor.IsExtension() { + panic(fmt.Errorf("proto3 declared messages do not support extensions: testpb.AnyWithExtra")) + } + panic(fmt.Errorf("message testpb.AnyWithExtra does not contain field %s", descriptor.FullName())) + } +} + +// Set stores the value for a field. +// +// For a field belonging to a oneof, it implicitly clears any other field +// that may be currently set within the same oneof. +// For extension fields, it implicitly stores the provided ExtensionType. +// When setting a composite type, it is unspecified whether the stored value +// aliases the source's memory in any way. If the composite value is an +// empty, read-only value, then it panics. +// +// Set is a mutating operation and unsafe for concurrent use. +func (x *fastReflection_AnyWithExtra) Set(fd protoreflect.FieldDescriptor, value protoreflect.Value) { + switch fd.FullName() { + case "testpb.AnyWithExtra.a": + x.A = value.Message().Interface().(*anypb.Any) + case "testpb.AnyWithExtra.b": + x.B = value.Int() + case "testpb.AnyWithExtra.c": + x.C = value.Int() + default: + if fd.IsExtension() { + panic(fmt.Errorf("proto3 declared messages do not support extensions: testpb.AnyWithExtra")) + } + panic(fmt.Errorf("message testpb.AnyWithExtra does not contain field %s", fd.FullName())) + } +} + +// Mutable returns a mutable reference to a composite type. +// +// If the field is unpopulated, it may allocate a composite value. +// For a field belonging to a oneof, it implicitly clears any other field +// that may be currently set within the same oneof. +// For extension fields, it implicitly stores the provided ExtensionType +// if not already stored. +// It panics if the field does not contain a composite type. +// +// Mutable is a mutating operation and unsafe for concurrent use. +func (x *fastReflection_AnyWithExtra) Mutable(fd protoreflect.FieldDescriptor) protoreflect.Value { + switch fd.FullName() { + case "testpb.AnyWithExtra.a": + if x.A == nil { + x.A = new(anypb.Any) + } + return protoreflect.ValueOfMessage(x.A.ProtoReflect()) + case "testpb.AnyWithExtra.b": + panic(fmt.Errorf("field b of message testpb.AnyWithExtra is not mutable")) + case "testpb.AnyWithExtra.c": + panic(fmt.Errorf("field c of message testpb.AnyWithExtra is not mutable")) + default: + if fd.IsExtension() { + panic(fmt.Errorf("proto3 declared messages do not support extensions: testpb.AnyWithExtra")) + } + panic(fmt.Errorf("message testpb.AnyWithExtra does not contain field %s", fd.FullName())) + } +} + +// NewField returns a new value that is assignable to the field +// for the given descriptor. For scalars, this returns the default value. +// For lists, maps, and messages, this returns a new, empty, mutable value. +func (x *fastReflection_AnyWithExtra) NewField(fd protoreflect.FieldDescriptor) protoreflect.Value { + switch fd.FullName() { + case "testpb.AnyWithExtra.a": + m := new(anypb.Any) + return protoreflect.ValueOfMessage(m.ProtoReflect()) + case "testpb.AnyWithExtra.b": + return protoreflect.ValueOfInt64(int64(0)) + case "testpb.AnyWithExtra.c": + return protoreflect.ValueOfInt64(int64(0)) + default: + if fd.IsExtension() { + panic(fmt.Errorf("proto3 declared messages do not support extensions: testpb.AnyWithExtra")) + } + panic(fmt.Errorf("message testpb.AnyWithExtra does not contain field %s", fd.FullName())) + } +} + +// WhichOneof reports which field within the oneof is populated, +// returning nil if none are populated. +// It panics if the oneof descriptor does not belong to this message. +func (x *fastReflection_AnyWithExtra) WhichOneof(d protoreflect.OneofDescriptor) protoreflect.FieldDescriptor { + switch d.FullName() { + default: + panic(fmt.Errorf("%s is not a oneof field in testpb.AnyWithExtra", d.FullName())) + } + panic("unreachable") +} + +// GetUnknown retrieves the entire list of unknown fields. +// The caller may only mutate the contents of the RawFields +// if the mutated bytes are stored back into the message with SetUnknown. +func (x *fastReflection_AnyWithExtra) GetUnknown() protoreflect.RawFields { + return x.unknownFields +} + +// SetUnknown stores an entire list of unknown fields. +// The raw fields must be syntactically valid according to the wire format. +// An implementation may panic if this is not the case. +// Once stored, the caller must not mutate the content of the RawFields. +// An empty RawFields may be passed to clear the fields. +// +// SetUnknown is a mutating operation and unsafe for concurrent use. +func (x *fastReflection_AnyWithExtra) SetUnknown(fields protoreflect.RawFields) { + x.unknownFields = fields +} + +// IsValid reports whether the message is valid. +// +// An invalid message is an empty, read-only value. +// +// An invalid message often corresponds to a nil pointer of the concrete +// message type, but the details are implementation dependent. +// Validity is not part of the protobuf data model, and may not +// be preserved in marshaling or other operations. +func (x *fastReflection_AnyWithExtra) IsValid() bool { + return x != nil +} + +// ProtoMethods returns optional fastReflectionFeature-path implementations of various operations. +// This method may return nil. +// +// The returned methods type is identical to +// "google.golang.org/protobuf/runtime/protoiface".Methods. +// Consult the protoiface package documentation for details. +func (x *fastReflection_AnyWithExtra) ProtoMethods() *protoiface.Methods { + size := func(input protoiface.SizeInput) protoiface.SizeOutput { + x := input.Message.Interface().(*AnyWithExtra) + if x == nil { + return protoiface.SizeOutput{ + NoUnkeyedLiterals: input.NoUnkeyedLiterals, + Size: 0, + } + } + options := runtime.SizeInputToOptions(input) + _ = options + var n int + var l int + _ = l + if x.A != nil { + l = options.Size(x.A) + n += 1 + l + runtime.Sov(uint64(l)) + } + if x.B != 0 { + n += 1 + runtime.Sov(uint64(x.B)) + } + if x.C != 0 { + n += 1 + runtime.Sov(uint64(x.C)) + } + if x.unknownFields != nil { + n += len(x.unknownFields) + } + return protoiface.SizeOutput{ + NoUnkeyedLiterals: input.NoUnkeyedLiterals, + Size: n, + } + } + + marshal := func(input protoiface.MarshalInput) (protoiface.MarshalOutput, error) { + x := input.Message.Interface().(*AnyWithExtra) + if x == nil { + return protoiface.MarshalOutput{ + NoUnkeyedLiterals: input.NoUnkeyedLiterals, + Buf: input.Buf, + }, nil + } + options := runtime.MarshalInputToOptions(input) + _ = options + size := options.Size(x) + dAtA := make([]byte, size) + i := len(dAtA) + _ = i + var l int + _ = l + if x.unknownFields != nil { + i -= len(x.unknownFields) + copy(dAtA[i:], x.unknownFields) + } + if x.C != 0 { + i = runtime.EncodeVarint(dAtA, i, uint64(x.C)) + i-- + dAtA[i] = 0x20 + } + if x.B != 0 { + i = runtime.EncodeVarint(dAtA, i, uint64(x.B)) + i-- + dAtA[i] = 0x18 + } + if x.A != nil { + encoded, err := options.Marshal(x.A) + if err != nil { + return protoiface.MarshalOutput{ + NoUnkeyedLiterals: input.NoUnkeyedLiterals, + Buf: input.Buf, + }, err + } + i -= len(encoded) + copy(dAtA[i:], encoded) + i = runtime.EncodeVarint(dAtA, i, uint64(len(encoded))) + i-- + dAtA[i] = 0xa + } + if input.Buf != nil { + input.Buf = append(input.Buf, dAtA...) + } else { + input.Buf = dAtA + } + return protoiface.MarshalOutput{ + NoUnkeyedLiterals: input.NoUnkeyedLiterals, + Buf: input.Buf, + }, nil + } + unmarshal := func(input protoiface.UnmarshalInput) (protoiface.UnmarshalOutput, error) { + x := input.Message.Interface().(*AnyWithExtra) + if x == nil { + return protoiface.UnmarshalOutput{ + NoUnkeyedLiterals: input.NoUnkeyedLiterals, + Flags: input.Flags, + }, nil + } + options := runtime.UnmarshalInputToOptions(input) + _ = options + dAtA := input.Buf + l := len(dAtA) + iNdEx := 0 + for iNdEx < l { + preIndex := iNdEx + var wire uint64 + for shift := uint(0); ; shift += 7 { + if shift >= 64 { + return protoiface.UnmarshalOutput{NoUnkeyedLiterals: input.NoUnkeyedLiterals, Flags: input.Flags}, runtime.ErrIntOverflow + } + if iNdEx >= l { + return protoiface.UnmarshalOutput{NoUnkeyedLiterals: input.NoUnkeyedLiterals, Flags: input.Flags}, io.ErrUnexpectedEOF + } + b := dAtA[iNdEx] + iNdEx++ + wire |= uint64(b&0x7F) << shift + if b < 0x80 { + break + } + } + fieldNum := int32(wire >> 3) + wireType := int(wire & 0x7) + if wireType == 4 { + return protoiface.UnmarshalOutput{NoUnkeyedLiterals: input.NoUnkeyedLiterals, Flags: input.Flags}, fmt.Errorf("proto: AnyWithExtra: wiretype end group for non-group") + } + if fieldNum <= 0 { + return protoiface.UnmarshalOutput{NoUnkeyedLiterals: input.NoUnkeyedLiterals, Flags: input.Flags}, fmt.Errorf("proto: AnyWithExtra: illegal tag %d (wire type %d)", fieldNum, wire) + } + switch fieldNum { + case 1: + if wireType != 2 { + return protoiface.UnmarshalOutput{NoUnkeyedLiterals: input.NoUnkeyedLiterals, Flags: input.Flags}, fmt.Errorf("proto: wrong wireType = %d for field A", wireType) + } + var msglen int + for shift := uint(0); ; shift += 7 { + if shift >= 64 { + return protoiface.UnmarshalOutput{NoUnkeyedLiterals: input.NoUnkeyedLiterals, Flags: input.Flags}, runtime.ErrIntOverflow + } + if iNdEx >= l { + return protoiface.UnmarshalOutput{NoUnkeyedLiterals: input.NoUnkeyedLiterals, Flags: input.Flags}, io.ErrUnexpectedEOF + } + b := dAtA[iNdEx] + iNdEx++ + msglen |= int(b&0x7F) << shift + if b < 0x80 { + break + } + } + if msglen < 0 { + return protoiface.UnmarshalOutput{NoUnkeyedLiterals: input.NoUnkeyedLiterals, Flags: input.Flags}, runtime.ErrInvalidLength + } + postIndex := iNdEx + msglen + if postIndex < 0 { + return protoiface.UnmarshalOutput{NoUnkeyedLiterals: input.NoUnkeyedLiterals, Flags: input.Flags}, runtime.ErrInvalidLength + } + if postIndex > l { + return protoiface.UnmarshalOutput{NoUnkeyedLiterals: input.NoUnkeyedLiterals, Flags: input.Flags}, io.ErrUnexpectedEOF + } + if x.A == nil { + x.A = &anypb.Any{} + } + if err := options.Unmarshal(dAtA[iNdEx:postIndex], x.A); err != nil { + return protoiface.UnmarshalOutput{NoUnkeyedLiterals: input.NoUnkeyedLiterals, Flags: input.Flags}, err + } + iNdEx = postIndex + case 3: + if wireType != 0 { + return protoiface.UnmarshalOutput{NoUnkeyedLiterals: input.NoUnkeyedLiterals, Flags: input.Flags}, fmt.Errorf("proto: wrong wireType = %d for field B", wireType) + } + x.B = 0 + for shift := uint(0); ; shift += 7 { + if shift >= 64 { + return protoiface.UnmarshalOutput{NoUnkeyedLiterals: input.NoUnkeyedLiterals, Flags: input.Flags}, runtime.ErrIntOverflow + } + if iNdEx >= l { + return protoiface.UnmarshalOutput{NoUnkeyedLiterals: input.NoUnkeyedLiterals, Flags: input.Flags}, io.ErrUnexpectedEOF + } + b := dAtA[iNdEx] + iNdEx++ + x.B |= int64(b&0x7F) << shift + if b < 0x80 { + break + } + } + case 4: + if wireType != 0 { + return protoiface.UnmarshalOutput{NoUnkeyedLiterals: input.NoUnkeyedLiterals, Flags: input.Flags}, fmt.Errorf("proto: wrong wireType = %d for field C", wireType) + } + x.C = 0 + for shift := uint(0); ; shift += 7 { + if shift >= 64 { + return protoiface.UnmarshalOutput{NoUnkeyedLiterals: input.NoUnkeyedLiterals, Flags: input.Flags}, runtime.ErrIntOverflow + } + if iNdEx >= l { + return protoiface.UnmarshalOutput{NoUnkeyedLiterals: input.NoUnkeyedLiterals, Flags: input.Flags}, io.ErrUnexpectedEOF + } + b := dAtA[iNdEx] + iNdEx++ + x.C |= int64(b&0x7F) << shift + if b < 0x80 { + break + } + } + default: + iNdEx = preIndex + skippy, err := runtime.Skip(dAtA[iNdEx:]) + if err != nil { + return protoiface.UnmarshalOutput{NoUnkeyedLiterals: input.NoUnkeyedLiterals, Flags: input.Flags}, err + } + if (skippy < 0) || (iNdEx+skippy) < 0 { + return protoiface.UnmarshalOutput{NoUnkeyedLiterals: input.NoUnkeyedLiterals, Flags: input.Flags}, runtime.ErrInvalidLength + } + if (iNdEx + skippy) > l { + return protoiface.UnmarshalOutput{NoUnkeyedLiterals: input.NoUnkeyedLiterals, Flags: input.Flags}, io.ErrUnexpectedEOF + } + if !options.DiscardUnknown { + x.unknownFields = append(x.unknownFields, dAtA[iNdEx:iNdEx+skippy]...) + } + iNdEx += skippy + } + } + + if iNdEx > l { + return protoiface.UnmarshalOutput{NoUnkeyedLiterals: input.NoUnkeyedLiterals, Flags: input.Flags}, io.ErrUnexpectedEOF + } + return protoiface.UnmarshalOutput{NoUnkeyedLiterals: input.NoUnkeyedLiterals, Flags: input.Flags}, nil + } + return &protoiface.Methods{ + NoUnkeyedLiterals: struct{}{}, + Flags: protoiface.SupportMarshalDeterministic | protoiface.SupportUnmarshalDiscardUnknown, + Size: size, + Marshal: marshal, + Unmarshal: unmarshal, + Merge: nil, + CheckInitialized: nil, + } +} + +var _ protoreflect.List = (*_TestUpdatedTxRaw_3_list)(nil) + +type _TestUpdatedTxRaw_3_list struct { + list *[][]byte +} + +func (x *_TestUpdatedTxRaw_3_list) Len() int { + if x.list == nil { + return 0 + } + return len(*x.list) +} + +func (x *_TestUpdatedTxRaw_3_list) Get(i int) protoreflect.Value { + return protoreflect.ValueOfBytes((*x.list)[i]) +} + +func (x *_TestUpdatedTxRaw_3_list) Set(i int, value protoreflect.Value) { + valueUnwrapped := value.Bytes() + concreteValue := valueUnwrapped + (*x.list)[i] = concreteValue +} + +func (x *_TestUpdatedTxRaw_3_list) Append(value protoreflect.Value) { + valueUnwrapped := value.Bytes() + concreteValue := valueUnwrapped + *x.list = append(*x.list, concreteValue) +} + +func (x *_TestUpdatedTxRaw_3_list) AppendMutable() protoreflect.Value { + panic(fmt.Errorf("AppendMutable can not be called on message TestUpdatedTxRaw at list field Signatures as it is not of Message kind")) +} + +func (x *_TestUpdatedTxRaw_3_list) Truncate(n int) { + *x.list = (*x.list)[:n] +} + +func (x *_TestUpdatedTxRaw_3_list) NewElement() protoreflect.Value { + var v []byte + return protoreflect.ValueOfBytes(v) +} + +func (x *_TestUpdatedTxRaw_3_list) IsValid() bool { + return x.list != nil +} + +var ( + md_TestUpdatedTxRaw protoreflect.MessageDescriptor + fd_TestUpdatedTxRaw_body_bytes protoreflect.FieldDescriptor + fd_TestUpdatedTxRaw_auth_info_bytes protoreflect.FieldDescriptor + fd_TestUpdatedTxRaw_signatures protoreflect.FieldDescriptor + fd_TestUpdatedTxRaw_new_field_5 protoreflect.FieldDescriptor + fd_TestUpdatedTxRaw_new_field_1024 protoreflect.FieldDescriptor +) + +func init() { + file_unknownproto_proto_init() + md_TestUpdatedTxRaw = File_unknownproto_proto.Messages().ByName("TestUpdatedTxRaw") + fd_TestUpdatedTxRaw_body_bytes = md_TestUpdatedTxRaw.Fields().ByName("body_bytes") + fd_TestUpdatedTxRaw_auth_info_bytes = md_TestUpdatedTxRaw.Fields().ByName("auth_info_bytes") + fd_TestUpdatedTxRaw_signatures = md_TestUpdatedTxRaw.Fields().ByName("signatures") + fd_TestUpdatedTxRaw_new_field_5 = md_TestUpdatedTxRaw.Fields().ByName("new_field_5") + fd_TestUpdatedTxRaw_new_field_1024 = md_TestUpdatedTxRaw.Fields().ByName("new_field_1024") +} + +var _ protoreflect.Message = (*fastReflection_TestUpdatedTxRaw)(nil) + +type fastReflection_TestUpdatedTxRaw TestUpdatedTxRaw + +func (x *TestUpdatedTxRaw) ProtoReflect() protoreflect.Message { + return (*fastReflection_TestUpdatedTxRaw)(x) +} + +func (x *TestUpdatedTxRaw) slowProtoReflect() protoreflect.Message { + mi := &file_unknownproto_proto_msgTypes[20] + if protoimpl.UnsafeEnabled && x != nil { + ms := protoimpl.X.MessageStateOf(protoimpl.Pointer(x)) + if ms.LoadMessageInfo() == nil { + ms.StoreMessageInfo(mi) + } + return ms + } + return mi.MessageOf(x) +} + +var _fastReflection_TestUpdatedTxRaw_messageType fastReflection_TestUpdatedTxRaw_messageType +var _ protoreflect.MessageType = fastReflection_TestUpdatedTxRaw_messageType{} + +type fastReflection_TestUpdatedTxRaw_messageType struct{} + +func (x fastReflection_TestUpdatedTxRaw_messageType) Zero() protoreflect.Message { + return (*fastReflection_TestUpdatedTxRaw)(nil) +} +func (x fastReflection_TestUpdatedTxRaw_messageType) New() protoreflect.Message { + return new(fastReflection_TestUpdatedTxRaw) +} +func (x fastReflection_TestUpdatedTxRaw_messageType) Descriptor() protoreflect.MessageDescriptor { + return md_TestUpdatedTxRaw +} + +// Descriptor returns message descriptor, which contains only the protobuf +// type information for the message. +func (x *fastReflection_TestUpdatedTxRaw) Descriptor() protoreflect.MessageDescriptor { + return md_TestUpdatedTxRaw +} + +// Type returns the message type, which encapsulates both Go and protobuf +// type information. If the Go type information is not needed, +// it is recommended that the message descriptor be used instead. +func (x *fastReflection_TestUpdatedTxRaw) Type() protoreflect.MessageType { + return _fastReflection_TestUpdatedTxRaw_messageType +} + +// New returns a newly allocated and mutable empty message. +func (x *fastReflection_TestUpdatedTxRaw) New() protoreflect.Message { + return new(fastReflection_TestUpdatedTxRaw) +} + +// Interface unwraps the message reflection interface and +// returns the underlying ProtoMessage interface. +func (x *fastReflection_TestUpdatedTxRaw) Interface() protoreflect.ProtoMessage { + return (*TestUpdatedTxRaw)(x) +} + +// Range iterates over every populated field in an undefined order, +// calling f for each field descriptor and value encountered. +// Range returns immediately if f returns false. +// While iterating, mutating operations may only be performed +// on the current field descriptor. +func (x *fastReflection_TestUpdatedTxRaw) Range(f func(protoreflect.FieldDescriptor, protoreflect.Value) bool) { + if len(x.BodyBytes) != 0 { + value := protoreflect.ValueOfBytes(x.BodyBytes) + if !f(fd_TestUpdatedTxRaw_body_bytes, value) { + return + } + } + if len(x.AuthInfoBytes) != 0 { + value := protoreflect.ValueOfBytes(x.AuthInfoBytes) + if !f(fd_TestUpdatedTxRaw_auth_info_bytes, value) { + return + } + } + if len(x.Signatures) != 0 { + value := protoreflect.ValueOfList(&_TestUpdatedTxRaw_3_list{list: &x.Signatures}) + if !f(fd_TestUpdatedTxRaw_signatures, value) { + return + } + } + if len(x.NewField_5) != 0 { + value := protoreflect.ValueOfBytes(x.NewField_5) + if !f(fd_TestUpdatedTxRaw_new_field_5, value) { + return + } + } + if len(x.NewField_1024) != 0 { + value := protoreflect.ValueOfBytes(x.NewField_1024) + if !f(fd_TestUpdatedTxRaw_new_field_1024, value) { + return + } + } +} + +// Has reports whether a field is populated. +// +// Some fields have the property of nullability where it is possible to +// distinguish between the default value of a field and whether the field +// was explicitly populated with the default value. Singular message fields, +// member fields of a oneof, and proto2 scalar fields are nullable. Such +// fields are populated only if explicitly set. +// +// In other cases (aside from the nullable cases above), +// a proto3 scalar field is populated if it contains a non-zero value, and +// a repeated field is populated if it is non-empty. +func (x *fastReflection_TestUpdatedTxRaw) Has(fd protoreflect.FieldDescriptor) bool { + switch fd.FullName() { + case "testpb.TestUpdatedTxRaw.body_bytes": + return len(x.BodyBytes) != 0 + case "testpb.TestUpdatedTxRaw.auth_info_bytes": + return len(x.AuthInfoBytes) != 0 + case "testpb.TestUpdatedTxRaw.signatures": + return len(x.Signatures) != 0 + case "testpb.TestUpdatedTxRaw.new_field_5": + return len(x.NewField_5) != 0 + case "testpb.TestUpdatedTxRaw.new_field_1024": + return len(x.NewField_1024) != 0 + default: + if fd.IsExtension() { + panic(fmt.Errorf("proto3 declared messages do not support extensions: testpb.TestUpdatedTxRaw")) + } + panic(fmt.Errorf("message testpb.TestUpdatedTxRaw does not contain field %s", fd.FullName())) + } +} + +// Clear clears the field such that a subsequent Has call reports false. +// +// Clearing an extension field clears both the extension type and value +// associated with the given field number. +// +// Clear is a mutating operation and unsafe for concurrent use. +func (x *fastReflection_TestUpdatedTxRaw) Clear(fd protoreflect.FieldDescriptor) { + switch fd.FullName() { + case "testpb.TestUpdatedTxRaw.body_bytes": + x.BodyBytes = nil + case "testpb.TestUpdatedTxRaw.auth_info_bytes": + x.AuthInfoBytes = nil + case "testpb.TestUpdatedTxRaw.signatures": + x.Signatures = nil + case "testpb.TestUpdatedTxRaw.new_field_5": + x.NewField_5 = nil + case "testpb.TestUpdatedTxRaw.new_field_1024": + x.NewField_1024 = nil + default: + if fd.IsExtension() { + panic(fmt.Errorf("proto3 declared messages do not support extensions: testpb.TestUpdatedTxRaw")) + } + panic(fmt.Errorf("message testpb.TestUpdatedTxRaw does not contain field %s", fd.FullName())) + } +} + +// Get retrieves the value for a field. +// +// For unpopulated scalars, it returns the default value, where +// the default value of a bytes scalar is guaranteed to be a copy. +// For unpopulated composite types, it returns an empty, read-only view +// of the value; to obtain a mutable reference, use Mutable. +func (x *fastReflection_TestUpdatedTxRaw) Get(descriptor protoreflect.FieldDescriptor) protoreflect.Value { + switch descriptor.FullName() { + case "testpb.TestUpdatedTxRaw.body_bytes": + value := x.BodyBytes + return protoreflect.ValueOfBytes(value) + case "testpb.TestUpdatedTxRaw.auth_info_bytes": + value := x.AuthInfoBytes + return protoreflect.ValueOfBytes(value) + case "testpb.TestUpdatedTxRaw.signatures": + if len(x.Signatures) == 0 { + return protoreflect.ValueOfList(&_TestUpdatedTxRaw_3_list{}) + } + listValue := &_TestUpdatedTxRaw_3_list{list: &x.Signatures} + return protoreflect.ValueOfList(listValue) + case "testpb.TestUpdatedTxRaw.new_field_5": + value := x.NewField_5 + return protoreflect.ValueOfBytes(value) + case "testpb.TestUpdatedTxRaw.new_field_1024": + value := x.NewField_1024 + return protoreflect.ValueOfBytes(value) + default: + if descriptor.IsExtension() { + panic(fmt.Errorf("proto3 declared messages do not support extensions: testpb.TestUpdatedTxRaw")) + } + panic(fmt.Errorf("message testpb.TestUpdatedTxRaw does not contain field %s", descriptor.FullName())) + } +} + +// Set stores the value for a field. +// +// For a field belonging to a oneof, it implicitly clears any other field +// that may be currently set within the same oneof. +// For extension fields, it implicitly stores the provided ExtensionType. +// When setting a composite type, it is unspecified whether the stored value +// aliases the source's memory in any way. If the composite value is an +// empty, read-only value, then it panics. +// +// Set is a mutating operation and unsafe for concurrent use. +func (x *fastReflection_TestUpdatedTxRaw) Set(fd protoreflect.FieldDescriptor, value protoreflect.Value) { + switch fd.FullName() { + case "testpb.TestUpdatedTxRaw.body_bytes": + x.BodyBytes = value.Bytes() + case "testpb.TestUpdatedTxRaw.auth_info_bytes": + x.AuthInfoBytes = value.Bytes() + case "testpb.TestUpdatedTxRaw.signatures": + lv := value.List() + clv := lv.(*_TestUpdatedTxRaw_3_list) + x.Signatures = *clv.list + case "testpb.TestUpdatedTxRaw.new_field_5": + x.NewField_5 = value.Bytes() + case "testpb.TestUpdatedTxRaw.new_field_1024": + x.NewField_1024 = value.Bytes() + default: + if fd.IsExtension() { + panic(fmt.Errorf("proto3 declared messages do not support extensions: testpb.TestUpdatedTxRaw")) + } + panic(fmt.Errorf("message testpb.TestUpdatedTxRaw does not contain field %s", fd.FullName())) + } +} + +// Mutable returns a mutable reference to a composite type. +// +// If the field is unpopulated, it may allocate a composite value. +// For a field belonging to a oneof, it implicitly clears any other field +// that may be currently set within the same oneof. +// For extension fields, it implicitly stores the provided ExtensionType +// if not already stored. +// It panics if the field does not contain a composite type. +// +// Mutable is a mutating operation and unsafe for concurrent use. +func (x *fastReflection_TestUpdatedTxRaw) Mutable(fd protoreflect.FieldDescriptor) protoreflect.Value { + switch fd.FullName() { + case "testpb.TestUpdatedTxRaw.signatures": + if x.Signatures == nil { + x.Signatures = [][]byte{} + } + value := &_TestUpdatedTxRaw_3_list{list: &x.Signatures} + return protoreflect.ValueOfList(value) + case "testpb.TestUpdatedTxRaw.body_bytes": + panic(fmt.Errorf("field body_bytes of message testpb.TestUpdatedTxRaw is not mutable")) + case "testpb.TestUpdatedTxRaw.auth_info_bytes": + panic(fmt.Errorf("field auth_info_bytes of message testpb.TestUpdatedTxRaw is not mutable")) + case "testpb.TestUpdatedTxRaw.new_field_5": + panic(fmt.Errorf("field new_field_5 of message testpb.TestUpdatedTxRaw is not mutable")) + case "testpb.TestUpdatedTxRaw.new_field_1024": + panic(fmt.Errorf("field new_field_1024 of message testpb.TestUpdatedTxRaw is not mutable")) + default: + if fd.IsExtension() { + panic(fmt.Errorf("proto3 declared messages do not support extensions: testpb.TestUpdatedTxRaw")) + } + panic(fmt.Errorf("message testpb.TestUpdatedTxRaw does not contain field %s", fd.FullName())) + } +} + +// NewField returns a new value that is assignable to the field +// for the given descriptor. For scalars, this returns the default value. +// For lists, maps, and messages, this returns a new, empty, mutable value. +func (x *fastReflection_TestUpdatedTxRaw) NewField(fd protoreflect.FieldDescriptor) protoreflect.Value { + switch fd.FullName() { + case "testpb.TestUpdatedTxRaw.body_bytes": + return protoreflect.ValueOfBytes(nil) + case "testpb.TestUpdatedTxRaw.auth_info_bytes": + return protoreflect.ValueOfBytes(nil) + case "testpb.TestUpdatedTxRaw.signatures": + list := [][]byte{} + return protoreflect.ValueOfList(&_TestUpdatedTxRaw_3_list{list: &list}) + case "testpb.TestUpdatedTxRaw.new_field_5": + return protoreflect.ValueOfBytes(nil) + case "testpb.TestUpdatedTxRaw.new_field_1024": + return protoreflect.ValueOfBytes(nil) + default: + if fd.IsExtension() { + panic(fmt.Errorf("proto3 declared messages do not support extensions: testpb.TestUpdatedTxRaw")) + } + panic(fmt.Errorf("message testpb.TestUpdatedTxRaw does not contain field %s", fd.FullName())) + } +} + +// WhichOneof reports which field within the oneof is populated, +// returning nil if none are populated. +// It panics if the oneof descriptor does not belong to this message. +func (x *fastReflection_TestUpdatedTxRaw) WhichOneof(d protoreflect.OneofDescriptor) protoreflect.FieldDescriptor { + switch d.FullName() { + default: + panic(fmt.Errorf("%s is not a oneof field in testpb.TestUpdatedTxRaw", d.FullName())) + } + panic("unreachable") +} + +// GetUnknown retrieves the entire list of unknown fields. +// The caller may only mutate the contents of the RawFields +// if the mutated bytes are stored back into the message with SetUnknown. +func (x *fastReflection_TestUpdatedTxRaw) GetUnknown() protoreflect.RawFields { + return x.unknownFields +} + +// SetUnknown stores an entire list of unknown fields. +// The raw fields must be syntactically valid according to the wire format. +// An implementation may panic if this is not the case. +// Once stored, the caller must not mutate the content of the RawFields. +// An empty RawFields may be passed to clear the fields. +// +// SetUnknown is a mutating operation and unsafe for concurrent use. +func (x *fastReflection_TestUpdatedTxRaw) SetUnknown(fields protoreflect.RawFields) { + x.unknownFields = fields +} + +// IsValid reports whether the message is valid. +// +// An invalid message is an empty, read-only value. +// +// An invalid message often corresponds to a nil pointer of the concrete +// message type, but the details are implementation dependent. +// Validity is not part of the protobuf data model, and may not +// be preserved in marshaling or other operations. +func (x *fastReflection_TestUpdatedTxRaw) IsValid() bool { + return x != nil +} + +// ProtoMethods returns optional fastReflectionFeature-path implementations of various operations. +// This method may return nil. +// +// The returned methods type is identical to +// "google.golang.org/protobuf/runtime/protoiface".Methods. +// Consult the protoiface package documentation for details. +func (x *fastReflection_TestUpdatedTxRaw) ProtoMethods() *protoiface.Methods { + size := func(input protoiface.SizeInput) protoiface.SizeOutput { + x := input.Message.Interface().(*TestUpdatedTxRaw) + if x == nil { + return protoiface.SizeOutput{ + NoUnkeyedLiterals: input.NoUnkeyedLiterals, + Size: 0, + } + } + options := runtime.SizeInputToOptions(input) + _ = options + var n int + var l int + _ = l + l = len(x.BodyBytes) + if l > 0 { + n += 1 + l + runtime.Sov(uint64(l)) + } + l = len(x.AuthInfoBytes) + if l > 0 { + n += 1 + l + runtime.Sov(uint64(l)) + } + if len(x.Signatures) > 0 { + for _, b := range x.Signatures { + l = len(b) + n += 1 + l + runtime.Sov(uint64(l)) + } + } + l = len(x.NewField_5) + if l > 0 { + n += 1 + l + runtime.Sov(uint64(l)) + } + l = len(x.NewField_1024) + if l > 0 { + n += 2 + l + runtime.Sov(uint64(l)) + } + if x.unknownFields != nil { + n += len(x.unknownFields) + } + return protoiface.SizeOutput{ + NoUnkeyedLiterals: input.NoUnkeyedLiterals, + Size: n, + } + } + + marshal := func(input protoiface.MarshalInput) (protoiface.MarshalOutput, error) { + x := input.Message.Interface().(*TestUpdatedTxRaw) + if x == nil { + return protoiface.MarshalOutput{ + NoUnkeyedLiterals: input.NoUnkeyedLiterals, + Buf: input.Buf, + }, nil + } + options := runtime.MarshalInputToOptions(input) + _ = options + size := options.Size(x) + dAtA := make([]byte, size) + i := len(dAtA) + _ = i + var l int + _ = l + if x.unknownFields != nil { + i -= len(x.unknownFields) + copy(dAtA[i:], x.unknownFields) + } + if len(x.NewField_1024) > 0 { + i -= len(x.NewField_1024) + copy(dAtA[i:], x.NewField_1024) + i = runtime.EncodeVarint(dAtA, i, uint64(len(x.NewField_1024))) + i-- + dAtA[i] = 0x40 + i-- + dAtA[i] = 0x82 + } + if len(x.NewField_5) > 0 { + i -= len(x.NewField_5) + copy(dAtA[i:], x.NewField_5) + i = runtime.EncodeVarint(dAtA, i, uint64(len(x.NewField_5))) + i-- + dAtA[i] = 0x2a + } + if len(x.Signatures) > 0 { + for iNdEx := len(x.Signatures) - 1; iNdEx >= 0; iNdEx-- { + i -= len(x.Signatures[iNdEx]) + copy(dAtA[i:], x.Signatures[iNdEx]) + i = runtime.EncodeVarint(dAtA, i, uint64(len(x.Signatures[iNdEx]))) + i-- + dAtA[i] = 0x1a + } + } + if len(x.AuthInfoBytes) > 0 { + i -= len(x.AuthInfoBytes) + copy(dAtA[i:], x.AuthInfoBytes) + i = runtime.EncodeVarint(dAtA, i, uint64(len(x.AuthInfoBytes))) + i-- + dAtA[i] = 0x12 + } + if len(x.BodyBytes) > 0 { + i -= len(x.BodyBytes) + copy(dAtA[i:], x.BodyBytes) + i = runtime.EncodeVarint(dAtA, i, uint64(len(x.BodyBytes))) + i-- + dAtA[i] = 0xa + } + if input.Buf != nil { + input.Buf = append(input.Buf, dAtA...) + } else { + input.Buf = dAtA + } + return protoiface.MarshalOutput{ + NoUnkeyedLiterals: input.NoUnkeyedLiterals, + Buf: input.Buf, + }, nil + } + unmarshal := func(input protoiface.UnmarshalInput) (protoiface.UnmarshalOutput, error) { + x := input.Message.Interface().(*TestUpdatedTxRaw) + if x == nil { + return protoiface.UnmarshalOutput{ + NoUnkeyedLiterals: input.NoUnkeyedLiterals, + Flags: input.Flags, + }, nil + } + options := runtime.UnmarshalInputToOptions(input) + _ = options + dAtA := input.Buf + l := len(dAtA) + iNdEx := 0 + for iNdEx < l { + preIndex := iNdEx + var wire uint64 + for shift := uint(0); ; shift += 7 { + if shift >= 64 { + return protoiface.UnmarshalOutput{NoUnkeyedLiterals: input.NoUnkeyedLiterals, Flags: input.Flags}, runtime.ErrIntOverflow + } + if iNdEx >= l { + return protoiface.UnmarshalOutput{NoUnkeyedLiterals: input.NoUnkeyedLiterals, Flags: input.Flags}, io.ErrUnexpectedEOF + } + b := dAtA[iNdEx] + iNdEx++ + wire |= uint64(b&0x7F) << shift + if b < 0x80 { + break + } + } + fieldNum := int32(wire >> 3) + wireType := int(wire & 0x7) + if wireType == 4 { + return protoiface.UnmarshalOutput{NoUnkeyedLiterals: input.NoUnkeyedLiterals, Flags: input.Flags}, fmt.Errorf("proto: TestUpdatedTxRaw: wiretype end group for non-group") + } + if fieldNum <= 0 { + return protoiface.UnmarshalOutput{NoUnkeyedLiterals: input.NoUnkeyedLiterals, Flags: input.Flags}, fmt.Errorf("proto: TestUpdatedTxRaw: illegal tag %d (wire type %d)", fieldNum, wire) + } + switch fieldNum { + case 1: + if wireType != 2 { + return protoiface.UnmarshalOutput{NoUnkeyedLiterals: input.NoUnkeyedLiterals, Flags: input.Flags}, fmt.Errorf("proto: wrong wireType = %d for field BodyBytes", wireType) + } + var byteLen int + for shift := uint(0); ; shift += 7 { + if shift >= 64 { + return protoiface.UnmarshalOutput{NoUnkeyedLiterals: input.NoUnkeyedLiterals, Flags: input.Flags}, runtime.ErrIntOverflow + } + if iNdEx >= l { + return protoiface.UnmarshalOutput{NoUnkeyedLiterals: input.NoUnkeyedLiterals, Flags: input.Flags}, io.ErrUnexpectedEOF + } + b := dAtA[iNdEx] + iNdEx++ + byteLen |= int(b&0x7F) << shift + if b < 0x80 { + break + } + } + if byteLen < 0 { + return protoiface.UnmarshalOutput{NoUnkeyedLiterals: input.NoUnkeyedLiterals, Flags: input.Flags}, runtime.ErrInvalidLength + } + postIndex := iNdEx + byteLen + if postIndex < 0 { + return protoiface.UnmarshalOutput{NoUnkeyedLiterals: input.NoUnkeyedLiterals, Flags: input.Flags}, runtime.ErrInvalidLength + } + if postIndex > l { + return protoiface.UnmarshalOutput{NoUnkeyedLiterals: input.NoUnkeyedLiterals, Flags: input.Flags}, io.ErrUnexpectedEOF + } + x.BodyBytes = append(x.BodyBytes[:0], dAtA[iNdEx:postIndex]...) + if x.BodyBytes == nil { + x.BodyBytes = []byte{} + } + iNdEx = postIndex + case 2: + if wireType != 2 { + return protoiface.UnmarshalOutput{NoUnkeyedLiterals: input.NoUnkeyedLiterals, Flags: input.Flags}, fmt.Errorf("proto: wrong wireType = %d for field AuthInfoBytes", wireType) + } + var byteLen int + for shift := uint(0); ; shift += 7 { + if shift >= 64 { + return protoiface.UnmarshalOutput{NoUnkeyedLiterals: input.NoUnkeyedLiterals, Flags: input.Flags}, runtime.ErrIntOverflow + } + if iNdEx >= l { + return protoiface.UnmarshalOutput{NoUnkeyedLiterals: input.NoUnkeyedLiterals, Flags: input.Flags}, io.ErrUnexpectedEOF + } + b := dAtA[iNdEx] + iNdEx++ + byteLen |= int(b&0x7F) << shift + if b < 0x80 { + break + } + } + if byteLen < 0 { + return protoiface.UnmarshalOutput{NoUnkeyedLiterals: input.NoUnkeyedLiterals, Flags: input.Flags}, runtime.ErrInvalidLength + } + postIndex := iNdEx + byteLen + if postIndex < 0 { + return protoiface.UnmarshalOutput{NoUnkeyedLiterals: input.NoUnkeyedLiterals, Flags: input.Flags}, runtime.ErrInvalidLength + } + if postIndex > l { + return protoiface.UnmarshalOutput{NoUnkeyedLiterals: input.NoUnkeyedLiterals, Flags: input.Flags}, io.ErrUnexpectedEOF + } + x.AuthInfoBytes = append(x.AuthInfoBytes[:0], dAtA[iNdEx:postIndex]...) + if x.AuthInfoBytes == nil { + x.AuthInfoBytes = []byte{} + } + iNdEx = postIndex + case 3: + if wireType != 2 { + return protoiface.UnmarshalOutput{NoUnkeyedLiterals: input.NoUnkeyedLiterals, Flags: input.Flags}, fmt.Errorf("proto: wrong wireType = %d for field Signatures", wireType) + } + var byteLen int + for shift := uint(0); ; shift += 7 { + if shift >= 64 { + return protoiface.UnmarshalOutput{NoUnkeyedLiterals: input.NoUnkeyedLiterals, Flags: input.Flags}, runtime.ErrIntOverflow + } + if iNdEx >= l { + return protoiface.UnmarshalOutput{NoUnkeyedLiterals: input.NoUnkeyedLiterals, Flags: input.Flags}, io.ErrUnexpectedEOF + } + b := dAtA[iNdEx] + iNdEx++ + byteLen |= int(b&0x7F) << shift + if b < 0x80 { + break + } + } + if byteLen < 0 { + return protoiface.UnmarshalOutput{NoUnkeyedLiterals: input.NoUnkeyedLiterals, Flags: input.Flags}, runtime.ErrInvalidLength + } + postIndex := iNdEx + byteLen + if postIndex < 0 { + return protoiface.UnmarshalOutput{NoUnkeyedLiterals: input.NoUnkeyedLiterals, Flags: input.Flags}, runtime.ErrInvalidLength + } + if postIndex > l { + return protoiface.UnmarshalOutput{NoUnkeyedLiterals: input.NoUnkeyedLiterals, Flags: input.Flags}, io.ErrUnexpectedEOF + } + x.Signatures = append(x.Signatures, make([]byte, postIndex-iNdEx)) + copy(x.Signatures[len(x.Signatures)-1], dAtA[iNdEx:postIndex]) + iNdEx = postIndex + case 5: + if wireType != 2 { + return protoiface.UnmarshalOutput{NoUnkeyedLiterals: input.NoUnkeyedLiterals, Flags: input.Flags}, fmt.Errorf("proto: wrong wireType = %d for field NewField_5", wireType) + } + var byteLen int + for shift := uint(0); ; shift += 7 { + if shift >= 64 { + return protoiface.UnmarshalOutput{NoUnkeyedLiterals: input.NoUnkeyedLiterals, Flags: input.Flags}, runtime.ErrIntOverflow + } + if iNdEx >= l { + return protoiface.UnmarshalOutput{NoUnkeyedLiterals: input.NoUnkeyedLiterals, Flags: input.Flags}, io.ErrUnexpectedEOF + } + b := dAtA[iNdEx] + iNdEx++ + byteLen |= int(b&0x7F) << shift + if b < 0x80 { + break + } + } + if byteLen < 0 { + return protoiface.UnmarshalOutput{NoUnkeyedLiterals: input.NoUnkeyedLiterals, Flags: input.Flags}, runtime.ErrInvalidLength + } + postIndex := iNdEx + byteLen + if postIndex < 0 { + return protoiface.UnmarshalOutput{NoUnkeyedLiterals: input.NoUnkeyedLiterals, Flags: input.Flags}, runtime.ErrInvalidLength + } + if postIndex > l { + return protoiface.UnmarshalOutput{NoUnkeyedLiterals: input.NoUnkeyedLiterals, Flags: input.Flags}, io.ErrUnexpectedEOF + } + x.NewField_5 = append(x.NewField_5[:0], dAtA[iNdEx:postIndex]...) + if x.NewField_5 == nil { + x.NewField_5 = []byte{} + } + iNdEx = postIndex + case 1024: + if wireType != 2 { + return protoiface.UnmarshalOutput{NoUnkeyedLiterals: input.NoUnkeyedLiterals, Flags: input.Flags}, fmt.Errorf("proto: wrong wireType = %d for field NewField_1024", wireType) + } + var byteLen int + for shift := uint(0); ; shift += 7 { + if shift >= 64 { + return protoiface.UnmarshalOutput{NoUnkeyedLiterals: input.NoUnkeyedLiterals, Flags: input.Flags}, runtime.ErrIntOverflow + } + if iNdEx >= l { + return protoiface.UnmarshalOutput{NoUnkeyedLiterals: input.NoUnkeyedLiterals, Flags: input.Flags}, io.ErrUnexpectedEOF + } + b := dAtA[iNdEx] + iNdEx++ + byteLen |= int(b&0x7F) << shift + if b < 0x80 { + break + } + } + if byteLen < 0 { + return protoiface.UnmarshalOutput{NoUnkeyedLiterals: input.NoUnkeyedLiterals, Flags: input.Flags}, runtime.ErrInvalidLength + } + postIndex := iNdEx + byteLen + if postIndex < 0 { + return protoiface.UnmarshalOutput{NoUnkeyedLiterals: input.NoUnkeyedLiterals, Flags: input.Flags}, runtime.ErrInvalidLength + } + if postIndex > l { + return protoiface.UnmarshalOutput{NoUnkeyedLiterals: input.NoUnkeyedLiterals, Flags: input.Flags}, io.ErrUnexpectedEOF + } + x.NewField_1024 = append(x.NewField_1024[:0], dAtA[iNdEx:postIndex]...) + if x.NewField_1024 == nil { + x.NewField_1024 = []byte{} + } + iNdEx = postIndex + default: + iNdEx = preIndex + skippy, err := runtime.Skip(dAtA[iNdEx:]) + if err != nil { + return protoiface.UnmarshalOutput{NoUnkeyedLiterals: input.NoUnkeyedLiterals, Flags: input.Flags}, err + } + if (skippy < 0) || (iNdEx+skippy) < 0 { + return protoiface.UnmarshalOutput{NoUnkeyedLiterals: input.NoUnkeyedLiterals, Flags: input.Flags}, runtime.ErrInvalidLength + } + if (iNdEx + skippy) > l { + return protoiface.UnmarshalOutput{NoUnkeyedLiterals: input.NoUnkeyedLiterals, Flags: input.Flags}, io.ErrUnexpectedEOF + } + if !options.DiscardUnknown { + x.unknownFields = append(x.unknownFields, dAtA[iNdEx:iNdEx+skippy]...) + } + iNdEx += skippy + } + } + + if iNdEx > l { + return protoiface.UnmarshalOutput{NoUnkeyedLiterals: input.NoUnkeyedLiterals, Flags: input.Flags}, io.ErrUnexpectedEOF + } + return protoiface.UnmarshalOutput{NoUnkeyedLiterals: input.NoUnkeyedLiterals, Flags: input.Flags}, nil + } + return &protoiface.Methods{ + NoUnkeyedLiterals: struct{}{}, + Flags: protoiface.SupportMarshalDeterministic | protoiface.SupportUnmarshalDiscardUnknown, + Size: size, + Marshal: marshal, + Unmarshal: unmarshal, + Merge: nil, + CheckInitialized: nil, + } +} + +var _ protoreflect.List = (*_TestUpdatedTxBody_1_list)(nil) + +type _TestUpdatedTxBody_1_list struct { + list *[]*anypb.Any +} + +func (x *_TestUpdatedTxBody_1_list) Len() int { + if x.list == nil { + return 0 + } + return len(*x.list) +} + +func (x *_TestUpdatedTxBody_1_list) Get(i int) protoreflect.Value { + return protoreflect.ValueOfMessage((*x.list)[i].ProtoReflect()) +} + +func (x *_TestUpdatedTxBody_1_list) Set(i int, value protoreflect.Value) { + valueUnwrapped := value.Message() + concreteValue := valueUnwrapped.Interface().(*anypb.Any) + (*x.list)[i] = concreteValue +} + +func (x *_TestUpdatedTxBody_1_list) Append(value protoreflect.Value) { + valueUnwrapped := value.Message() + concreteValue := valueUnwrapped.Interface().(*anypb.Any) + *x.list = append(*x.list, concreteValue) +} + +func (x *_TestUpdatedTxBody_1_list) AppendMutable() protoreflect.Value { + v := new(anypb.Any) + *x.list = append(*x.list, v) + return protoreflect.ValueOfMessage(v.ProtoReflect()) +} + +func (x *_TestUpdatedTxBody_1_list) Truncate(n int) { + for i := n; i < len(*x.list); i++ { + (*x.list)[i] = nil + } + *x.list = (*x.list)[:n] +} + +func (x *_TestUpdatedTxBody_1_list) NewElement() protoreflect.Value { + v := new(anypb.Any) + return protoreflect.ValueOfMessage(v.ProtoReflect()) +} + +func (x *_TestUpdatedTxBody_1_list) IsValid() bool { + return x.list != nil +} + +var _ protoreflect.List = (*_TestUpdatedTxBody_1023_list)(nil) + +type _TestUpdatedTxBody_1023_list struct { + list *[]*anypb.Any +} + +func (x *_TestUpdatedTxBody_1023_list) Len() int { + if x.list == nil { + return 0 + } + return len(*x.list) +} + +func (x *_TestUpdatedTxBody_1023_list) Get(i int) protoreflect.Value { + return protoreflect.ValueOfMessage((*x.list)[i].ProtoReflect()) +} + +func (x *_TestUpdatedTxBody_1023_list) Set(i int, value protoreflect.Value) { + valueUnwrapped := value.Message() + concreteValue := valueUnwrapped.Interface().(*anypb.Any) + (*x.list)[i] = concreteValue +} + +func (x *_TestUpdatedTxBody_1023_list) Append(value protoreflect.Value) { + valueUnwrapped := value.Message() + concreteValue := valueUnwrapped.Interface().(*anypb.Any) + *x.list = append(*x.list, concreteValue) +} + +func (x *_TestUpdatedTxBody_1023_list) AppendMutable() protoreflect.Value { + v := new(anypb.Any) + *x.list = append(*x.list, v) + return protoreflect.ValueOfMessage(v.ProtoReflect()) +} + +func (x *_TestUpdatedTxBody_1023_list) Truncate(n int) { + for i := n; i < len(*x.list); i++ { + (*x.list)[i] = nil + } + *x.list = (*x.list)[:n] +} + +func (x *_TestUpdatedTxBody_1023_list) NewElement() protoreflect.Value { + v := new(anypb.Any) + return protoreflect.ValueOfMessage(v.ProtoReflect()) +} + +func (x *_TestUpdatedTxBody_1023_list) IsValid() bool { + return x.list != nil +} + +var _ protoreflect.List = (*_TestUpdatedTxBody_2047_list)(nil) + +type _TestUpdatedTxBody_2047_list struct { + list *[]*anypb.Any +} + +func (x *_TestUpdatedTxBody_2047_list) Len() int { + if x.list == nil { + return 0 + } + return len(*x.list) +} + +func (x *_TestUpdatedTxBody_2047_list) Get(i int) protoreflect.Value { + return protoreflect.ValueOfMessage((*x.list)[i].ProtoReflect()) +} + +func (x *_TestUpdatedTxBody_2047_list) Set(i int, value protoreflect.Value) { + valueUnwrapped := value.Message() + concreteValue := valueUnwrapped.Interface().(*anypb.Any) + (*x.list)[i] = concreteValue +} + +func (x *_TestUpdatedTxBody_2047_list) Append(value protoreflect.Value) { + valueUnwrapped := value.Message() + concreteValue := valueUnwrapped.Interface().(*anypb.Any) + *x.list = append(*x.list, concreteValue) +} + +func (x *_TestUpdatedTxBody_2047_list) AppendMutable() protoreflect.Value { + v := new(anypb.Any) + *x.list = append(*x.list, v) + return protoreflect.ValueOfMessage(v.ProtoReflect()) +} + +func (x *_TestUpdatedTxBody_2047_list) Truncate(n int) { + for i := n; i < len(*x.list); i++ { + (*x.list)[i] = nil + } + *x.list = (*x.list)[:n] +} + +func (x *_TestUpdatedTxBody_2047_list) NewElement() protoreflect.Value { + v := new(anypb.Any) + return protoreflect.ValueOfMessage(v.ProtoReflect()) +} + +func (x *_TestUpdatedTxBody_2047_list) IsValid() bool { + return x.list != nil +} + +var ( + md_TestUpdatedTxBody protoreflect.MessageDescriptor + fd_TestUpdatedTxBody_messages protoreflect.FieldDescriptor + fd_TestUpdatedTxBody_memo protoreflect.FieldDescriptor + fd_TestUpdatedTxBody_timeout_height protoreflect.FieldDescriptor + fd_TestUpdatedTxBody_some_new_field protoreflect.FieldDescriptor + fd_TestUpdatedTxBody_some_new_field_non_critical_field protoreflect.FieldDescriptor + fd_TestUpdatedTxBody_extension_options protoreflect.FieldDescriptor + fd_TestUpdatedTxBody_non_critical_extension_options protoreflect.FieldDescriptor +) + +func init() { + file_unknownproto_proto_init() + md_TestUpdatedTxBody = File_unknownproto_proto.Messages().ByName("TestUpdatedTxBody") + fd_TestUpdatedTxBody_messages = md_TestUpdatedTxBody.Fields().ByName("messages") + fd_TestUpdatedTxBody_memo = md_TestUpdatedTxBody.Fields().ByName("memo") + fd_TestUpdatedTxBody_timeout_height = md_TestUpdatedTxBody.Fields().ByName("timeout_height") + fd_TestUpdatedTxBody_some_new_field = md_TestUpdatedTxBody.Fields().ByName("some_new_field") + fd_TestUpdatedTxBody_some_new_field_non_critical_field = md_TestUpdatedTxBody.Fields().ByName("some_new_field_non_critical_field") + fd_TestUpdatedTxBody_extension_options = md_TestUpdatedTxBody.Fields().ByName("extension_options") + fd_TestUpdatedTxBody_non_critical_extension_options = md_TestUpdatedTxBody.Fields().ByName("non_critical_extension_options") +} + +var _ protoreflect.Message = (*fastReflection_TestUpdatedTxBody)(nil) + +type fastReflection_TestUpdatedTxBody TestUpdatedTxBody + +func (x *TestUpdatedTxBody) ProtoReflect() protoreflect.Message { + return (*fastReflection_TestUpdatedTxBody)(x) +} + +func (x *TestUpdatedTxBody) slowProtoReflect() protoreflect.Message { + mi := &file_unknownproto_proto_msgTypes[21] + if protoimpl.UnsafeEnabled && x != nil { + ms := protoimpl.X.MessageStateOf(protoimpl.Pointer(x)) + if ms.LoadMessageInfo() == nil { + ms.StoreMessageInfo(mi) + } + return ms + } + return mi.MessageOf(x) +} + +var _fastReflection_TestUpdatedTxBody_messageType fastReflection_TestUpdatedTxBody_messageType +var _ protoreflect.MessageType = fastReflection_TestUpdatedTxBody_messageType{} + +type fastReflection_TestUpdatedTxBody_messageType struct{} + +func (x fastReflection_TestUpdatedTxBody_messageType) Zero() protoreflect.Message { + return (*fastReflection_TestUpdatedTxBody)(nil) +} +func (x fastReflection_TestUpdatedTxBody_messageType) New() protoreflect.Message { + return new(fastReflection_TestUpdatedTxBody) +} +func (x fastReflection_TestUpdatedTxBody_messageType) Descriptor() protoreflect.MessageDescriptor { + return md_TestUpdatedTxBody +} + +// Descriptor returns message descriptor, which contains only the protobuf +// type information for the message. +func (x *fastReflection_TestUpdatedTxBody) Descriptor() protoreflect.MessageDescriptor { + return md_TestUpdatedTxBody +} + +// Type returns the message type, which encapsulates both Go and protobuf +// type information. If the Go type information is not needed, +// it is recommended that the message descriptor be used instead. +func (x *fastReflection_TestUpdatedTxBody) Type() protoreflect.MessageType { + return _fastReflection_TestUpdatedTxBody_messageType +} + +// New returns a newly allocated and mutable empty message. +func (x *fastReflection_TestUpdatedTxBody) New() protoreflect.Message { + return new(fastReflection_TestUpdatedTxBody) +} + +// Interface unwraps the message reflection interface and +// returns the underlying ProtoMessage interface. +func (x *fastReflection_TestUpdatedTxBody) Interface() protoreflect.ProtoMessage { + return (*TestUpdatedTxBody)(x) +} + +// Range iterates over every populated field in an undefined order, +// calling f for each field descriptor and value encountered. +// Range returns immediately if f returns false. +// While iterating, mutating operations may only be performed +// on the current field descriptor. +func (x *fastReflection_TestUpdatedTxBody) Range(f func(protoreflect.FieldDescriptor, protoreflect.Value) bool) { + if len(x.Messages) != 0 { + value := protoreflect.ValueOfList(&_TestUpdatedTxBody_1_list{list: &x.Messages}) + if !f(fd_TestUpdatedTxBody_messages, value) { + return + } + } + if x.Memo != "" { + value := protoreflect.ValueOfString(x.Memo) + if !f(fd_TestUpdatedTxBody_memo, value) { + return + } + } + if x.TimeoutHeight != int64(0) { + value := protoreflect.ValueOfInt64(x.TimeoutHeight) + if !f(fd_TestUpdatedTxBody_timeout_height, value) { + return + } + } + if x.SomeNewField != uint64(0) { + value := protoreflect.ValueOfUint64(x.SomeNewField) + if !f(fd_TestUpdatedTxBody_some_new_field, value) { + return + } + } + if x.SomeNewFieldNonCriticalField != "" { + value := protoreflect.ValueOfString(x.SomeNewFieldNonCriticalField) + if !f(fd_TestUpdatedTxBody_some_new_field_non_critical_field, value) { + return + } + } + if len(x.ExtensionOptions) != 0 { + value := protoreflect.ValueOfList(&_TestUpdatedTxBody_1023_list{list: &x.ExtensionOptions}) + if !f(fd_TestUpdatedTxBody_extension_options, value) { + return + } + } + if len(x.NonCriticalExtensionOptions) != 0 { + value := protoreflect.ValueOfList(&_TestUpdatedTxBody_2047_list{list: &x.NonCriticalExtensionOptions}) + if !f(fd_TestUpdatedTxBody_non_critical_extension_options, value) { + return + } + } +} + +// Has reports whether a field is populated. +// +// Some fields have the property of nullability where it is possible to +// distinguish between the default value of a field and whether the field +// was explicitly populated with the default value. Singular message fields, +// member fields of a oneof, and proto2 scalar fields are nullable. Such +// fields are populated only if explicitly set. +// +// In other cases (aside from the nullable cases above), +// a proto3 scalar field is populated if it contains a non-zero value, and +// a repeated field is populated if it is non-empty. +func (x *fastReflection_TestUpdatedTxBody) Has(fd protoreflect.FieldDescriptor) bool { + switch fd.FullName() { + case "testpb.TestUpdatedTxBody.messages": + return len(x.Messages) != 0 + case "testpb.TestUpdatedTxBody.memo": + return x.Memo != "" + case "testpb.TestUpdatedTxBody.timeout_height": + return x.TimeoutHeight != int64(0) + case "testpb.TestUpdatedTxBody.some_new_field": + return x.SomeNewField != uint64(0) + case "testpb.TestUpdatedTxBody.some_new_field_non_critical_field": + return x.SomeNewFieldNonCriticalField != "" + case "testpb.TestUpdatedTxBody.extension_options": + return len(x.ExtensionOptions) != 0 + case "testpb.TestUpdatedTxBody.non_critical_extension_options": + return len(x.NonCriticalExtensionOptions) != 0 + default: + if fd.IsExtension() { + panic(fmt.Errorf("proto3 declared messages do not support extensions: testpb.TestUpdatedTxBody")) + } + panic(fmt.Errorf("message testpb.TestUpdatedTxBody does not contain field %s", fd.FullName())) + } +} + +// Clear clears the field such that a subsequent Has call reports false. +// +// Clearing an extension field clears both the extension type and value +// associated with the given field number. +// +// Clear is a mutating operation and unsafe for concurrent use. +func (x *fastReflection_TestUpdatedTxBody) Clear(fd protoreflect.FieldDescriptor) { + switch fd.FullName() { + case "testpb.TestUpdatedTxBody.messages": + x.Messages = nil + case "testpb.TestUpdatedTxBody.memo": + x.Memo = "" + case "testpb.TestUpdatedTxBody.timeout_height": + x.TimeoutHeight = int64(0) + case "testpb.TestUpdatedTxBody.some_new_field": + x.SomeNewField = uint64(0) + case "testpb.TestUpdatedTxBody.some_new_field_non_critical_field": + x.SomeNewFieldNonCriticalField = "" + case "testpb.TestUpdatedTxBody.extension_options": + x.ExtensionOptions = nil + case "testpb.TestUpdatedTxBody.non_critical_extension_options": + x.NonCriticalExtensionOptions = nil + default: + if fd.IsExtension() { + panic(fmt.Errorf("proto3 declared messages do not support extensions: testpb.TestUpdatedTxBody")) + } + panic(fmt.Errorf("message testpb.TestUpdatedTxBody does not contain field %s", fd.FullName())) + } +} + +// Get retrieves the value for a field. +// +// For unpopulated scalars, it returns the default value, where +// the default value of a bytes scalar is guaranteed to be a copy. +// For unpopulated composite types, it returns an empty, read-only view +// of the value; to obtain a mutable reference, use Mutable. +func (x *fastReflection_TestUpdatedTxBody) Get(descriptor protoreflect.FieldDescriptor) protoreflect.Value { + switch descriptor.FullName() { + case "testpb.TestUpdatedTxBody.messages": + if len(x.Messages) == 0 { + return protoreflect.ValueOfList(&_TestUpdatedTxBody_1_list{}) + } + listValue := &_TestUpdatedTxBody_1_list{list: &x.Messages} + return protoreflect.ValueOfList(listValue) + case "testpb.TestUpdatedTxBody.memo": + value := x.Memo + return protoreflect.ValueOfString(value) + case "testpb.TestUpdatedTxBody.timeout_height": + value := x.TimeoutHeight + return protoreflect.ValueOfInt64(value) + case "testpb.TestUpdatedTxBody.some_new_field": + value := x.SomeNewField + return protoreflect.ValueOfUint64(value) + case "testpb.TestUpdatedTxBody.some_new_field_non_critical_field": + value := x.SomeNewFieldNonCriticalField + return protoreflect.ValueOfString(value) + case "testpb.TestUpdatedTxBody.extension_options": + if len(x.ExtensionOptions) == 0 { + return protoreflect.ValueOfList(&_TestUpdatedTxBody_1023_list{}) + } + listValue := &_TestUpdatedTxBody_1023_list{list: &x.ExtensionOptions} + return protoreflect.ValueOfList(listValue) + case "testpb.TestUpdatedTxBody.non_critical_extension_options": + if len(x.NonCriticalExtensionOptions) == 0 { + return protoreflect.ValueOfList(&_TestUpdatedTxBody_2047_list{}) + } + listValue := &_TestUpdatedTxBody_2047_list{list: &x.NonCriticalExtensionOptions} + return protoreflect.ValueOfList(listValue) + default: + if descriptor.IsExtension() { + panic(fmt.Errorf("proto3 declared messages do not support extensions: testpb.TestUpdatedTxBody")) + } + panic(fmt.Errorf("message testpb.TestUpdatedTxBody does not contain field %s", descriptor.FullName())) + } +} + +// Set stores the value for a field. +// +// For a field belonging to a oneof, it implicitly clears any other field +// that may be currently set within the same oneof. +// For extension fields, it implicitly stores the provided ExtensionType. +// When setting a composite type, it is unspecified whether the stored value +// aliases the source's memory in any way. If the composite value is an +// empty, read-only value, then it panics. +// +// Set is a mutating operation and unsafe for concurrent use. +func (x *fastReflection_TestUpdatedTxBody) Set(fd protoreflect.FieldDescriptor, value protoreflect.Value) { + switch fd.FullName() { + case "testpb.TestUpdatedTxBody.messages": + lv := value.List() + clv := lv.(*_TestUpdatedTxBody_1_list) + x.Messages = *clv.list + case "testpb.TestUpdatedTxBody.memo": + x.Memo = value.Interface().(string) + case "testpb.TestUpdatedTxBody.timeout_height": + x.TimeoutHeight = value.Int() + case "testpb.TestUpdatedTxBody.some_new_field": + x.SomeNewField = value.Uint() + case "testpb.TestUpdatedTxBody.some_new_field_non_critical_field": + x.SomeNewFieldNonCriticalField = value.Interface().(string) + case "testpb.TestUpdatedTxBody.extension_options": + lv := value.List() + clv := lv.(*_TestUpdatedTxBody_1023_list) + x.ExtensionOptions = *clv.list + case "testpb.TestUpdatedTxBody.non_critical_extension_options": + lv := value.List() + clv := lv.(*_TestUpdatedTxBody_2047_list) + x.NonCriticalExtensionOptions = *clv.list + default: + if fd.IsExtension() { + panic(fmt.Errorf("proto3 declared messages do not support extensions: testpb.TestUpdatedTxBody")) + } + panic(fmt.Errorf("message testpb.TestUpdatedTxBody does not contain field %s", fd.FullName())) + } +} + +// Mutable returns a mutable reference to a composite type. +// +// If the field is unpopulated, it may allocate a composite value. +// For a field belonging to a oneof, it implicitly clears any other field +// that may be currently set within the same oneof. +// For extension fields, it implicitly stores the provided ExtensionType +// if not already stored. +// It panics if the field does not contain a composite type. +// +// Mutable is a mutating operation and unsafe for concurrent use. +func (x *fastReflection_TestUpdatedTxBody) Mutable(fd protoreflect.FieldDescriptor) protoreflect.Value { + switch fd.FullName() { + case "testpb.TestUpdatedTxBody.messages": + if x.Messages == nil { + x.Messages = []*anypb.Any{} + } + value := &_TestUpdatedTxBody_1_list{list: &x.Messages} + return protoreflect.ValueOfList(value) + case "testpb.TestUpdatedTxBody.extension_options": + if x.ExtensionOptions == nil { + x.ExtensionOptions = []*anypb.Any{} + } + value := &_TestUpdatedTxBody_1023_list{list: &x.ExtensionOptions} + return protoreflect.ValueOfList(value) + case "testpb.TestUpdatedTxBody.non_critical_extension_options": + if x.NonCriticalExtensionOptions == nil { + x.NonCriticalExtensionOptions = []*anypb.Any{} + } + value := &_TestUpdatedTxBody_2047_list{list: &x.NonCriticalExtensionOptions} + return protoreflect.ValueOfList(value) + case "testpb.TestUpdatedTxBody.memo": + panic(fmt.Errorf("field memo of message testpb.TestUpdatedTxBody is not mutable")) + case "testpb.TestUpdatedTxBody.timeout_height": + panic(fmt.Errorf("field timeout_height of message testpb.TestUpdatedTxBody is not mutable")) + case "testpb.TestUpdatedTxBody.some_new_field": + panic(fmt.Errorf("field some_new_field of message testpb.TestUpdatedTxBody is not mutable")) + case "testpb.TestUpdatedTxBody.some_new_field_non_critical_field": + panic(fmt.Errorf("field some_new_field_non_critical_field of message testpb.TestUpdatedTxBody is not mutable")) + default: + if fd.IsExtension() { + panic(fmt.Errorf("proto3 declared messages do not support extensions: testpb.TestUpdatedTxBody")) + } + panic(fmt.Errorf("message testpb.TestUpdatedTxBody does not contain field %s", fd.FullName())) + } +} + +// NewField returns a new value that is assignable to the field +// for the given descriptor. For scalars, this returns the default value. +// For lists, maps, and messages, this returns a new, empty, mutable value. +func (x *fastReflection_TestUpdatedTxBody) NewField(fd protoreflect.FieldDescriptor) protoreflect.Value { + switch fd.FullName() { + case "testpb.TestUpdatedTxBody.messages": + list := []*anypb.Any{} + return protoreflect.ValueOfList(&_TestUpdatedTxBody_1_list{list: &list}) + case "testpb.TestUpdatedTxBody.memo": + return protoreflect.ValueOfString("") + case "testpb.TestUpdatedTxBody.timeout_height": + return protoreflect.ValueOfInt64(int64(0)) + case "testpb.TestUpdatedTxBody.some_new_field": + return protoreflect.ValueOfUint64(uint64(0)) + case "testpb.TestUpdatedTxBody.some_new_field_non_critical_field": + return protoreflect.ValueOfString("") + case "testpb.TestUpdatedTxBody.extension_options": + list := []*anypb.Any{} + return protoreflect.ValueOfList(&_TestUpdatedTxBody_1023_list{list: &list}) + case "testpb.TestUpdatedTxBody.non_critical_extension_options": + list := []*anypb.Any{} + return protoreflect.ValueOfList(&_TestUpdatedTxBody_2047_list{list: &list}) + default: + if fd.IsExtension() { + panic(fmt.Errorf("proto3 declared messages do not support extensions: testpb.TestUpdatedTxBody")) + } + panic(fmt.Errorf("message testpb.TestUpdatedTxBody does not contain field %s", fd.FullName())) + } +} + +// WhichOneof reports which field within the oneof is populated, +// returning nil if none are populated. +// It panics if the oneof descriptor does not belong to this message. +func (x *fastReflection_TestUpdatedTxBody) WhichOneof(d protoreflect.OneofDescriptor) protoreflect.FieldDescriptor { + switch d.FullName() { + default: + panic(fmt.Errorf("%s is not a oneof field in testpb.TestUpdatedTxBody", d.FullName())) + } + panic("unreachable") +} + +// GetUnknown retrieves the entire list of unknown fields. +// The caller may only mutate the contents of the RawFields +// if the mutated bytes are stored back into the message with SetUnknown. +func (x *fastReflection_TestUpdatedTxBody) GetUnknown() protoreflect.RawFields { + return x.unknownFields +} + +// SetUnknown stores an entire list of unknown fields. +// The raw fields must be syntactically valid according to the wire format. +// An implementation may panic if this is not the case. +// Once stored, the caller must not mutate the content of the RawFields. +// An empty RawFields may be passed to clear the fields. +// +// SetUnknown is a mutating operation and unsafe for concurrent use. +func (x *fastReflection_TestUpdatedTxBody) SetUnknown(fields protoreflect.RawFields) { + x.unknownFields = fields +} + +// IsValid reports whether the message is valid. +// +// An invalid message is an empty, read-only value. +// +// An invalid message often corresponds to a nil pointer of the concrete +// message type, but the details are implementation dependent. +// Validity is not part of the protobuf data model, and may not +// be preserved in marshaling or other operations. +func (x *fastReflection_TestUpdatedTxBody) IsValid() bool { + return x != nil +} + +// ProtoMethods returns optional fastReflectionFeature-path implementations of various operations. +// This method may return nil. +// +// The returned methods type is identical to +// "google.golang.org/protobuf/runtime/protoiface".Methods. +// Consult the protoiface package documentation for details. +func (x *fastReflection_TestUpdatedTxBody) ProtoMethods() *protoiface.Methods { + size := func(input protoiface.SizeInput) protoiface.SizeOutput { + x := input.Message.Interface().(*TestUpdatedTxBody) + if x == nil { + return protoiface.SizeOutput{ + NoUnkeyedLiterals: input.NoUnkeyedLiterals, + Size: 0, + } + } + options := runtime.SizeInputToOptions(input) + _ = options + var n int + var l int + _ = l + if len(x.Messages) > 0 { + for _, e := range x.Messages { + l = options.Size(e) + n += 1 + l + runtime.Sov(uint64(l)) + } + } + l = len(x.Memo) + if l > 0 { + n += 1 + l + runtime.Sov(uint64(l)) + } + if x.TimeoutHeight != 0 { + n += 1 + runtime.Sov(uint64(x.TimeoutHeight)) + } + if x.SomeNewField != 0 { + n += 1 + runtime.Sov(uint64(x.SomeNewField)) + } + l = len(x.SomeNewFieldNonCriticalField) + if l > 0 { + n += 2 + l + runtime.Sov(uint64(l)) + } + if len(x.ExtensionOptions) > 0 { + for _, e := range x.ExtensionOptions { + l = options.Size(e) + n += 2 + l + runtime.Sov(uint64(l)) + } + } + if len(x.NonCriticalExtensionOptions) > 0 { + for _, e := range x.NonCriticalExtensionOptions { + l = options.Size(e) + n += 2 + l + runtime.Sov(uint64(l)) + } + } + if x.unknownFields != nil { + n += len(x.unknownFields) + } + return protoiface.SizeOutput{ + NoUnkeyedLiterals: input.NoUnkeyedLiterals, + Size: n, + } + } + + marshal := func(input protoiface.MarshalInput) (protoiface.MarshalOutput, error) { + x := input.Message.Interface().(*TestUpdatedTxBody) + if x == nil { + return protoiface.MarshalOutput{ + NoUnkeyedLiterals: input.NoUnkeyedLiterals, + Buf: input.Buf, + }, nil + } + options := runtime.MarshalInputToOptions(input) + _ = options + size := options.Size(x) + dAtA := make([]byte, size) + i := len(dAtA) + _ = i + var l int + _ = l + if x.unknownFields != nil { + i -= len(x.unknownFields) + copy(dAtA[i:], x.unknownFields) + } + if len(x.NonCriticalExtensionOptions) > 0 { + for iNdEx := len(x.NonCriticalExtensionOptions) - 1; iNdEx >= 0; iNdEx-- { + encoded, err := options.Marshal(x.NonCriticalExtensionOptions[iNdEx]) + if err != nil { + return protoiface.MarshalOutput{ + NoUnkeyedLiterals: input.NoUnkeyedLiterals, + Buf: input.Buf, + }, err + } + i -= len(encoded) + copy(dAtA[i:], encoded) + i = runtime.EncodeVarint(dAtA, i, uint64(len(encoded))) + i-- + dAtA[i] = 0x7f + i-- + dAtA[i] = 0xfa + } + } + if len(x.SomeNewFieldNonCriticalField) > 0 { + i -= len(x.SomeNewFieldNonCriticalField) + copy(dAtA[i:], x.SomeNewFieldNonCriticalField) + i = runtime.EncodeVarint(dAtA, i, uint64(len(x.SomeNewFieldNonCriticalField))) + i-- + dAtA[i] = 0x41 + i-- + dAtA[i] = 0xd2 + } + if len(x.ExtensionOptions) > 0 { + for iNdEx := len(x.ExtensionOptions) - 1; iNdEx >= 0; iNdEx-- { + encoded, err := options.Marshal(x.ExtensionOptions[iNdEx]) + if err != nil { + return protoiface.MarshalOutput{ + NoUnkeyedLiterals: input.NoUnkeyedLiterals, + Buf: input.Buf, + }, err + } + i -= len(encoded) + copy(dAtA[i:], encoded) + i = runtime.EncodeVarint(dAtA, i, uint64(len(encoded))) + i-- + dAtA[i] = 0x3f + i-- + dAtA[i] = 0xfa + } + } + if x.SomeNewField != 0 { + i = runtime.EncodeVarint(dAtA, i, uint64(x.SomeNewField)) + i-- + dAtA[i] = 0x20 + } + if x.TimeoutHeight != 0 { + i = runtime.EncodeVarint(dAtA, i, uint64(x.TimeoutHeight)) + i-- + dAtA[i] = 0x18 + } + if len(x.Memo) > 0 { + i -= len(x.Memo) + copy(dAtA[i:], x.Memo) + i = runtime.EncodeVarint(dAtA, i, uint64(len(x.Memo))) + i-- + dAtA[i] = 0x12 + } + if len(x.Messages) > 0 { + for iNdEx := len(x.Messages) - 1; iNdEx >= 0; iNdEx-- { + encoded, err := options.Marshal(x.Messages[iNdEx]) + if err != nil { + return protoiface.MarshalOutput{ + NoUnkeyedLiterals: input.NoUnkeyedLiterals, + Buf: input.Buf, + }, err + } + i -= len(encoded) + copy(dAtA[i:], encoded) + i = runtime.EncodeVarint(dAtA, i, uint64(len(encoded))) + i-- + dAtA[i] = 0xa + } + } + if input.Buf != nil { + input.Buf = append(input.Buf, dAtA...) + } else { + input.Buf = dAtA + } + return protoiface.MarshalOutput{ + NoUnkeyedLiterals: input.NoUnkeyedLiterals, + Buf: input.Buf, + }, nil + } + unmarshal := func(input protoiface.UnmarshalInput) (protoiface.UnmarshalOutput, error) { + x := input.Message.Interface().(*TestUpdatedTxBody) + if x == nil { + return protoiface.UnmarshalOutput{ + NoUnkeyedLiterals: input.NoUnkeyedLiterals, + Flags: input.Flags, + }, nil + } + options := runtime.UnmarshalInputToOptions(input) + _ = options + dAtA := input.Buf + l := len(dAtA) + iNdEx := 0 + for iNdEx < l { + preIndex := iNdEx + var wire uint64 + for shift := uint(0); ; shift += 7 { + if shift >= 64 { + return protoiface.UnmarshalOutput{NoUnkeyedLiterals: input.NoUnkeyedLiterals, Flags: input.Flags}, runtime.ErrIntOverflow + } + if iNdEx >= l { + return protoiface.UnmarshalOutput{NoUnkeyedLiterals: input.NoUnkeyedLiterals, Flags: input.Flags}, io.ErrUnexpectedEOF + } + b := dAtA[iNdEx] + iNdEx++ + wire |= uint64(b&0x7F) << shift + if b < 0x80 { + break + } + } + fieldNum := int32(wire >> 3) + wireType := int(wire & 0x7) + if wireType == 4 { + return protoiface.UnmarshalOutput{NoUnkeyedLiterals: input.NoUnkeyedLiterals, Flags: input.Flags}, fmt.Errorf("proto: TestUpdatedTxBody: wiretype end group for non-group") + } + if fieldNum <= 0 { + return protoiface.UnmarshalOutput{NoUnkeyedLiterals: input.NoUnkeyedLiterals, Flags: input.Flags}, fmt.Errorf("proto: TestUpdatedTxBody: illegal tag %d (wire type %d)", fieldNum, wire) + } + switch fieldNum { + case 1: + if wireType != 2 { + return protoiface.UnmarshalOutput{NoUnkeyedLiterals: input.NoUnkeyedLiterals, Flags: input.Flags}, fmt.Errorf("proto: wrong wireType = %d for field Messages", wireType) + } + var msglen int + for shift := uint(0); ; shift += 7 { + if shift >= 64 { + return protoiface.UnmarshalOutput{NoUnkeyedLiterals: input.NoUnkeyedLiterals, Flags: input.Flags}, runtime.ErrIntOverflow + } + if iNdEx >= l { + return protoiface.UnmarshalOutput{NoUnkeyedLiterals: input.NoUnkeyedLiterals, Flags: input.Flags}, io.ErrUnexpectedEOF + } + b := dAtA[iNdEx] + iNdEx++ + msglen |= int(b&0x7F) << shift + if b < 0x80 { + break + } + } + if msglen < 0 { + return protoiface.UnmarshalOutput{NoUnkeyedLiterals: input.NoUnkeyedLiterals, Flags: input.Flags}, runtime.ErrInvalidLength + } + postIndex := iNdEx + msglen + if postIndex < 0 { + return protoiface.UnmarshalOutput{NoUnkeyedLiterals: input.NoUnkeyedLiterals, Flags: input.Flags}, runtime.ErrInvalidLength + } + if postIndex > l { + return protoiface.UnmarshalOutput{NoUnkeyedLiterals: input.NoUnkeyedLiterals, Flags: input.Flags}, io.ErrUnexpectedEOF + } + x.Messages = append(x.Messages, &anypb.Any{}) + if err := options.Unmarshal(dAtA[iNdEx:postIndex], x.Messages[len(x.Messages)-1]); err != nil { + return protoiface.UnmarshalOutput{NoUnkeyedLiterals: input.NoUnkeyedLiterals, Flags: input.Flags}, err + } + iNdEx = postIndex + case 2: + if wireType != 2 { + return protoiface.UnmarshalOutput{NoUnkeyedLiterals: input.NoUnkeyedLiterals, Flags: input.Flags}, fmt.Errorf("proto: wrong wireType = %d for field Memo", wireType) + } + var stringLen uint64 + for shift := uint(0); ; shift += 7 { + if shift >= 64 { + return protoiface.UnmarshalOutput{NoUnkeyedLiterals: input.NoUnkeyedLiterals, Flags: input.Flags}, runtime.ErrIntOverflow + } + if iNdEx >= l { + return protoiface.UnmarshalOutput{NoUnkeyedLiterals: input.NoUnkeyedLiterals, Flags: input.Flags}, io.ErrUnexpectedEOF + } + b := dAtA[iNdEx] + iNdEx++ + stringLen |= uint64(b&0x7F) << shift + if b < 0x80 { + break + } + } + intStringLen := int(stringLen) + if intStringLen < 0 { + return protoiface.UnmarshalOutput{NoUnkeyedLiterals: input.NoUnkeyedLiterals, Flags: input.Flags}, runtime.ErrInvalidLength + } + postIndex := iNdEx + intStringLen + if postIndex < 0 { + return protoiface.UnmarshalOutput{NoUnkeyedLiterals: input.NoUnkeyedLiterals, Flags: input.Flags}, runtime.ErrInvalidLength + } + if postIndex > l { + return protoiface.UnmarshalOutput{NoUnkeyedLiterals: input.NoUnkeyedLiterals, Flags: input.Flags}, io.ErrUnexpectedEOF + } + x.Memo = string(dAtA[iNdEx:postIndex]) + iNdEx = postIndex + case 3: + if wireType != 0 { + return protoiface.UnmarshalOutput{NoUnkeyedLiterals: input.NoUnkeyedLiterals, Flags: input.Flags}, fmt.Errorf("proto: wrong wireType = %d for field TimeoutHeight", wireType) + } + x.TimeoutHeight = 0 + for shift := uint(0); ; shift += 7 { + if shift >= 64 { + return protoiface.UnmarshalOutput{NoUnkeyedLiterals: input.NoUnkeyedLiterals, Flags: input.Flags}, runtime.ErrIntOverflow + } + if iNdEx >= l { + return protoiface.UnmarshalOutput{NoUnkeyedLiterals: input.NoUnkeyedLiterals, Flags: input.Flags}, io.ErrUnexpectedEOF + } + b := dAtA[iNdEx] + iNdEx++ + x.TimeoutHeight |= int64(b&0x7F) << shift + if b < 0x80 { + break + } + } + case 4: + if wireType != 0 { + return protoiface.UnmarshalOutput{NoUnkeyedLiterals: input.NoUnkeyedLiterals, Flags: input.Flags}, fmt.Errorf("proto: wrong wireType = %d for field SomeNewField", wireType) + } + x.SomeNewField = 0 + for shift := uint(0); ; shift += 7 { + if shift >= 64 { + return protoiface.UnmarshalOutput{NoUnkeyedLiterals: input.NoUnkeyedLiterals, Flags: input.Flags}, runtime.ErrIntOverflow + } + if iNdEx >= l { + return protoiface.UnmarshalOutput{NoUnkeyedLiterals: input.NoUnkeyedLiterals, Flags: input.Flags}, io.ErrUnexpectedEOF + } + b := dAtA[iNdEx] + iNdEx++ + x.SomeNewField |= uint64(b&0x7F) << shift + if b < 0x80 { + break + } + } + case 1050: + if wireType != 2 { + return protoiface.UnmarshalOutput{NoUnkeyedLiterals: input.NoUnkeyedLiterals, Flags: input.Flags}, fmt.Errorf("proto: wrong wireType = %d for field SomeNewFieldNonCriticalField", wireType) + } + var stringLen uint64 + for shift := uint(0); ; shift += 7 { + if shift >= 64 { + return protoiface.UnmarshalOutput{NoUnkeyedLiterals: input.NoUnkeyedLiterals, Flags: input.Flags}, runtime.ErrIntOverflow + } + if iNdEx >= l { + return protoiface.UnmarshalOutput{NoUnkeyedLiterals: input.NoUnkeyedLiterals, Flags: input.Flags}, io.ErrUnexpectedEOF + } + b := dAtA[iNdEx] + iNdEx++ + stringLen |= uint64(b&0x7F) << shift + if b < 0x80 { + break + } + } + intStringLen := int(stringLen) + if intStringLen < 0 { + return protoiface.UnmarshalOutput{NoUnkeyedLiterals: input.NoUnkeyedLiterals, Flags: input.Flags}, runtime.ErrInvalidLength + } + postIndex := iNdEx + intStringLen + if postIndex < 0 { + return protoiface.UnmarshalOutput{NoUnkeyedLiterals: input.NoUnkeyedLiterals, Flags: input.Flags}, runtime.ErrInvalidLength + } + if postIndex > l { + return protoiface.UnmarshalOutput{NoUnkeyedLiterals: input.NoUnkeyedLiterals, Flags: input.Flags}, io.ErrUnexpectedEOF + } + x.SomeNewFieldNonCriticalField = string(dAtA[iNdEx:postIndex]) + iNdEx = postIndex + case 1023: + if wireType != 2 { + return protoiface.UnmarshalOutput{NoUnkeyedLiterals: input.NoUnkeyedLiterals, Flags: input.Flags}, fmt.Errorf("proto: wrong wireType = %d for field ExtensionOptions", wireType) + } + var msglen int + for shift := uint(0); ; shift += 7 { + if shift >= 64 { + return protoiface.UnmarshalOutput{NoUnkeyedLiterals: input.NoUnkeyedLiterals, Flags: input.Flags}, runtime.ErrIntOverflow + } + if iNdEx >= l { + return protoiface.UnmarshalOutput{NoUnkeyedLiterals: input.NoUnkeyedLiterals, Flags: input.Flags}, io.ErrUnexpectedEOF + } + b := dAtA[iNdEx] + iNdEx++ + msglen |= int(b&0x7F) << shift + if b < 0x80 { + break + } + } + if msglen < 0 { + return protoiface.UnmarshalOutput{NoUnkeyedLiterals: input.NoUnkeyedLiterals, Flags: input.Flags}, runtime.ErrInvalidLength + } + postIndex := iNdEx + msglen + if postIndex < 0 { + return protoiface.UnmarshalOutput{NoUnkeyedLiterals: input.NoUnkeyedLiterals, Flags: input.Flags}, runtime.ErrInvalidLength + } + if postIndex > l { + return protoiface.UnmarshalOutput{NoUnkeyedLiterals: input.NoUnkeyedLiterals, Flags: input.Flags}, io.ErrUnexpectedEOF + } + x.ExtensionOptions = append(x.ExtensionOptions, &anypb.Any{}) + if err := options.Unmarshal(dAtA[iNdEx:postIndex], x.ExtensionOptions[len(x.ExtensionOptions)-1]); err != nil { + return protoiface.UnmarshalOutput{NoUnkeyedLiterals: input.NoUnkeyedLiterals, Flags: input.Flags}, err + } + iNdEx = postIndex + case 2047: + if wireType != 2 { + return protoiface.UnmarshalOutput{NoUnkeyedLiterals: input.NoUnkeyedLiterals, Flags: input.Flags}, fmt.Errorf("proto: wrong wireType = %d for field NonCriticalExtensionOptions", wireType) + } + var msglen int + for shift := uint(0); ; shift += 7 { + if shift >= 64 { + return protoiface.UnmarshalOutput{NoUnkeyedLiterals: input.NoUnkeyedLiterals, Flags: input.Flags}, runtime.ErrIntOverflow + } + if iNdEx >= l { + return protoiface.UnmarshalOutput{NoUnkeyedLiterals: input.NoUnkeyedLiterals, Flags: input.Flags}, io.ErrUnexpectedEOF + } + b := dAtA[iNdEx] + iNdEx++ + msglen |= int(b&0x7F) << shift + if b < 0x80 { + break + } + } + if msglen < 0 { + return protoiface.UnmarshalOutput{NoUnkeyedLiterals: input.NoUnkeyedLiterals, Flags: input.Flags}, runtime.ErrInvalidLength + } + postIndex := iNdEx + msglen + if postIndex < 0 { + return protoiface.UnmarshalOutput{NoUnkeyedLiterals: input.NoUnkeyedLiterals, Flags: input.Flags}, runtime.ErrInvalidLength + } + if postIndex > l { + return protoiface.UnmarshalOutput{NoUnkeyedLiterals: input.NoUnkeyedLiterals, Flags: input.Flags}, io.ErrUnexpectedEOF + } + x.NonCriticalExtensionOptions = append(x.NonCriticalExtensionOptions, &anypb.Any{}) + if err := options.Unmarshal(dAtA[iNdEx:postIndex], x.NonCriticalExtensionOptions[len(x.NonCriticalExtensionOptions)-1]); err != nil { + return protoiface.UnmarshalOutput{NoUnkeyedLiterals: input.NoUnkeyedLiterals, Flags: input.Flags}, err + } + iNdEx = postIndex + default: + iNdEx = preIndex + skippy, err := runtime.Skip(dAtA[iNdEx:]) + if err != nil { + return protoiface.UnmarshalOutput{NoUnkeyedLiterals: input.NoUnkeyedLiterals, Flags: input.Flags}, err + } + if (skippy < 0) || (iNdEx+skippy) < 0 { + return protoiface.UnmarshalOutput{NoUnkeyedLiterals: input.NoUnkeyedLiterals, Flags: input.Flags}, runtime.ErrInvalidLength + } + if (iNdEx + skippy) > l { + return protoiface.UnmarshalOutput{NoUnkeyedLiterals: input.NoUnkeyedLiterals, Flags: input.Flags}, io.ErrUnexpectedEOF + } + if !options.DiscardUnknown { + x.unknownFields = append(x.unknownFields, dAtA[iNdEx:iNdEx+skippy]...) + } + iNdEx += skippy + } + } + + if iNdEx > l { + return protoiface.UnmarshalOutput{NoUnkeyedLiterals: input.NoUnkeyedLiterals, Flags: input.Flags}, io.ErrUnexpectedEOF + } + return protoiface.UnmarshalOutput{NoUnkeyedLiterals: input.NoUnkeyedLiterals, Flags: input.Flags}, nil + } + return &protoiface.Methods{ + NoUnkeyedLiterals: struct{}{}, + Flags: protoiface.SupportMarshalDeterministic | protoiface.SupportUnmarshalDiscardUnknown, + Size: size, + Marshal: marshal, + Unmarshal: unmarshal, + Merge: nil, + CheckInitialized: nil, + } +} + +var _ protoreflect.List = (*_TestUpdatedAuthInfo_1_list)(nil) + +type _TestUpdatedAuthInfo_1_list struct { + list *[]*v1beta1.SignerInfo +} + +func (x *_TestUpdatedAuthInfo_1_list) Len() int { + if x.list == nil { + return 0 + } + return len(*x.list) +} + +func (x *_TestUpdatedAuthInfo_1_list) Get(i int) protoreflect.Value { + return protoreflect.ValueOfMessage((*x.list)[i].ProtoReflect()) +} + +func (x *_TestUpdatedAuthInfo_1_list) Set(i int, value protoreflect.Value) { + valueUnwrapped := value.Message() + concreteValue := valueUnwrapped.Interface().(*v1beta1.SignerInfo) + (*x.list)[i] = concreteValue +} + +func (x *_TestUpdatedAuthInfo_1_list) Append(value protoreflect.Value) { + valueUnwrapped := value.Message() + concreteValue := valueUnwrapped.Interface().(*v1beta1.SignerInfo) + *x.list = append(*x.list, concreteValue) +} + +func (x *_TestUpdatedAuthInfo_1_list) AppendMutable() protoreflect.Value { + v := new(v1beta1.SignerInfo) + *x.list = append(*x.list, v) + return protoreflect.ValueOfMessage(v.ProtoReflect()) +} + +func (x *_TestUpdatedAuthInfo_1_list) Truncate(n int) { + for i := n; i < len(*x.list); i++ { + (*x.list)[i] = nil + } + *x.list = (*x.list)[:n] +} + +func (x *_TestUpdatedAuthInfo_1_list) NewElement() protoreflect.Value { + v := new(v1beta1.SignerInfo) + return protoreflect.ValueOfMessage(v.ProtoReflect()) +} + +func (x *_TestUpdatedAuthInfo_1_list) IsValid() bool { + return x.list != nil +} + +var ( + md_TestUpdatedAuthInfo protoreflect.MessageDescriptor + fd_TestUpdatedAuthInfo_signer_infos protoreflect.FieldDescriptor + fd_TestUpdatedAuthInfo_fee protoreflect.FieldDescriptor + fd_TestUpdatedAuthInfo_new_field_3 protoreflect.FieldDescriptor + fd_TestUpdatedAuthInfo_new_field_1024 protoreflect.FieldDescriptor +) + +func init() { + file_unknownproto_proto_init() + md_TestUpdatedAuthInfo = File_unknownproto_proto.Messages().ByName("TestUpdatedAuthInfo") + fd_TestUpdatedAuthInfo_signer_infos = md_TestUpdatedAuthInfo.Fields().ByName("signer_infos") + fd_TestUpdatedAuthInfo_fee = md_TestUpdatedAuthInfo.Fields().ByName("fee") + fd_TestUpdatedAuthInfo_new_field_3 = md_TestUpdatedAuthInfo.Fields().ByName("new_field_3") + fd_TestUpdatedAuthInfo_new_field_1024 = md_TestUpdatedAuthInfo.Fields().ByName("new_field_1024") +} + +var _ protoreflect.Message = (*fastReflection_TestUpdatedAuthInfo)(nil) + +type fastReflection_TestUpdatedAuthInfo TestUpdatedAuthInfo + +func (x *TestUpdatedAuthInfo) ProtoReflect() protoreflect.Message { + return (*fastReflection_TestUpdatedAuthInfo)(x) +} + +func (x *TestUpdatedAuthInfo) slowProtoReflect() protoreflect.Message { + mi := &file_unknownproto_proto_msgTypes[22] + if protoimpl.UnsafeEnabled && x != nil { + ms := protoimpl.X.MessageStateOf(protoimpl.Pointer(x)) + if ms.LoadMessageInfo() == nil { + ms.StoreMessageInfo(mi) + } + return ms + } + return mi.MessageOf(x) +} + +var _fastReflection_TestUpdatedAuthInfo_messageType fastReflection_TestUpdatedAuthInfo_messageType +var _ protoreflect.MessageType = fastReflection_TestUpdatedAuthInfo_messageType{} + +type fastReflection_TestUpdatedAuthInfo_messageType struct{} + +func (x fastReflection_TestUpdatedAuthInfo_messageType) Zero() protoreflect.Message { + return (*fastReflection_TestUpdatedAuthInfo)(nil) +} +func (x fastReflection_TestUpdatedAuthInfo_messageType) New() protoreflect.Message { + return new(fastReflection_TestUpdatedAuthInfo) +} +func (x fastReflection_TestUpdatedAuthInfo_messageType) Descriptor() protoreflect.MessageDescriptor { + return md_TestUpdatedAuthInfo +} + +// Descriptor returns message descriptor, which contains only the protobuf +// type information for the message. +func (x *fastReflection_TestUpdatedAuthInfo) Descriptor() protoreflect.MessageDescriptor { + return md_TestUpdatedAuthInfo +} + +// Type returns the message type, which encapsulates both Go and protobuf +// type information. If the Go type information is not needed, +// it is recommended that the message descriptor be used instead. +func (x *fastReflection_TestUpdatedAuthInfo) Type() protoreflect.MessageType { + return _fastReflection_TestUpdatedAuthInfo_messageType +} + +// New returns a newly allocated and mutable empty message. +func (x *fastReflection_TestUpdatedAuthInfo) New() protoreflect.Message { + return new(fastReflection_TestUpdatedAuthInfo) +} + +// Interface unwraps the message reflection interface and +// returns the underlying ProtoMessage interface. +func (x *fastReflection_TestUpdatedAuthInfo) Interface() protoreflect.ProtoMessage { + return (*TestUpdatedAuthInfo)(x) +} + +// Range iterates over every populated field in an undefined order, +// calling f for each field descriptor and value encountered. +// Range returns immediately if f returns false. +// While iterating, mutating operations may only be performed +// on the current field descriptor. +func (x *fastReflection_TestUpdatedAuthInfo) Range(f func(protoreflect.FieldDescriptor, protoreflect.Value) bool) { + if len(x.SignerInfos) != 0 { + value := protoreflect.ValueOfList(&_TestUpdatedAuthInfo_1_list{list: &x.SignerInfos}) + if !f(fd_TestUpdatedAuthInfo_signer_infos, value) { + return + } + } + if x.Fee != nil { + value := protoreflect.ValueOfMessage(x.Fee.ProtoReflect()) + if !f(fd_TestUpdatedAuthInfo_fee, value) { + return + } + } + if len(x.NewField_3) != 0 { + value := protoreflect.ValueOfBytes(x.NewField_3) + if !f(fd_TestUpdatedAuthInfo_new_field_3, value) { + return + } + } + if len(x.NewField_1024) != 0 { + value := protoreflect.ValueOfBytes(x.NewField_1024) + if !f(fd_TestUpdatedAuthInfo_new_field_1024, value) { + return + } + } +} + +// Has reports whether a field is populated. +// +// Some fields have the property of nullability where it is possible to +// distinguish between the default value of a field and whether the field +// was explicitly populated with the default value. Singular message fields, +// member fields of a oneof, and proto2 scalar fields are nullable. Such +// fields are populated only if explicitly set. +// +// In other cases (aside from the nullable cases above), +// a proto3 scalar field is populated if it contains a non-zero value, and +// a repeated field is populated if it is non-empty. +func (x *fastReflection_TestUpdatedAuthInfo) Has(fd protoreflect.FieldDescriptor) bool { + switch fd.FullName() { + case "testpb.TestUpdatedAuthInfo.signer_infos": + return len(x.SignerInfos) != 0 + case "testpb.TestUpdatedAuthInfo.fee": + return x.Fee != nil + case "testpb.TestUpdatedAuthInfo.new_field_3": + return len(x.NewField_3) != 0 + case "testpb.TestUpdatedAuthInfo.new_field_1024": + return len(x.NewField_1024) != 0 + default: + if fd.IsExtension() { + panic(fmt.Errorf("proto3 declared messages do not support extensions: testpb.TestUpdatedAuthInfo")) + } + panic(fmt.Errorf("message testpb.TestUpdatedAuthInfo does not contain field %s", fd.FullName())) + } +} + +// Clear clears the field such that a subsequent Has call reports false. +// +// Clearing an extension field clears both the extension type and value +// associated with the given field number. +// +// Clear is a mutating operation and unsafe for concurrent use. +func (x *fastReflection_TestUpdatedAuthInfo) Clear(fd protoreflect.FieldDescriptor) { + switch fd.FullName() { + case "testpb.TestUpdatedAuthInfo.signer_infos": + x.SignerInfos = nil + case "testpb.TestUpdatedAuthInfo.fee": + x.Fee = nil + case "testpb.TestUpdatedAuthInfo.new_field_3": + x.NewField_3 = nil + case "testpb.TestUpdatedAuthInfo.new_field_1024": + x.NewField_1024 = nil + default: + if fd.IsExtension() { + panic(fmt.Errorf("proto3 declared messages do not support extensions: testpb.TestUpdatedAuthInfo")) + } + panic(fmt.Errorf("message testpb.TestUpdatedAuthInfo does not contain field %s", fd.FullName())) + } +} + +// Get retrieves the value for a field. +// +// For unpopulated scalars, it returns the default value, where +// the default value of a bytes scalar is guaranteed to be a copy. +// For unpopulated composite types, it returns an empty, read-only view +// of the value; to obtain a mutable reference, use Mutable. +func (x *fastReflection_TestUpdatedAuthInfo) Get(descriptor protoreflect.FieldDescriptor) protoreflect.Value { + switch descriptor.FullName() { + case "testpb.TestUpdatedAuthInfo.signer_infos": + if len(x.SignerInfos) == 0 { + return protoreflect.ValueOfList(&_TestUpdatedAuthInfo_1_list{}) + } + listValue := &_TestUpdatedAuthInfo_1_list{list: &x.SignerInfos} + return protoreflect.ValueOfList(listValue) + case "testpb.TestUpdatedAuthInfo.fee": + value := x.Fee + return protoreflect.ValueOfMessage(value.ProtoReflect()) + case "testpb.TestUpdatedAuthInfo.new_field_3": + value := x.NewField_3 + return protoreflect.ValueOfBytes(value) + case "testpb.TestUpdatedAuthInfo.new_field_1024": + value := x.NewField_1024 + return protoreflect.ValueOfBytes(value) + default: + if descriptor.IsExtension() { + panic(fmt.Errorf("proto3 declared messages do not support extensions: testpb.TestUpdatedAuthInfo")) + } + panic(fmt.Errorf("message testpb.TestUpdatedAuthInfo does not contain field %s", descriptor.FullName())) + } +} + +// Set stores the value for a field. +// +// For a field belonging to a oneof, it implicitly clears any other field +// that may be currently set within the same oneof. +// For extension fields, it implicitly stores the provided ExtensionType. +// When setting a composite type, it is unspecified whether the stored value +// aliases the source's memory in any way. If the composite value is an +// empty, read-only value, then it panics. +// +// Set is a mutating operation and unsafe for concurrent use. +func (x *fastReflection_TestUpdatedAuthInfo) Set(fd protoreflect.FieldDescriptor, value protoreflect.Value) { + switch fd.FullName() { + case "testpb.TestUpdatedAuthInfo.signer_infos": + lv := value.List() + clv := lv.(*_TestUpdatedAuthInfo_1_list) + x.SignerInfos = *clv.list + case "testpb.TestUpdatedAuthInfo.fee": + x.Fee = value.Message().Interface().(*v1beta1.Fee) + case "testpb.TestUpdatedAuthInfo.new_field_3": + x.NewField_3 = value.Bytes() + case "testpb.TestUpdatedAuthInfo.new_field_1024": + x.NewField_1024 = value.Bytes() + default: + if fd.IsExtension() { + panic(fmt.Errorf("proto3 declared messages do not support extensions: testpb.TestUpdatedAuthInfo")) + } + panic(fmt.Errorf("message testpb.TestUpdatedAuthInfo does not contain field %s", fd.FullName())) + } +} + +// Mutable returns a mutable reference to a composite type. +// +// If the field is unpopulated, it may allocate a composite value. +// For a field belonging to a oneof, it implicitly clears any other field +// that may be currently set within the same oneof. +// For extension fields, it implicitly stores the provided ExtensionType +// if not already stored. +// It panics if the field does not contain a composite type. +// +// Mutable is a mutating operation and unsafe for concurrent use. +func (x *fastReflection_TestUpdatedAuthInfo) Mutable(fd protoreflect.FieldDescriptor) protoreflect.Value { + switch fd.FullName() { + case "testpb.TestUpdatedAuthInfo.signer_infos": + if x.SignerInfos == nil { + x.SignerInfos = []*v1beta1.SignerInfo{} + } + value := &_TestUpdatedAuthInfo_1_list{list: &x.SignerInfos} + return protoreflect.ValueOfList(value) + case "testpb.TestUpdatedAuthInfo.fee": + if x.Fee == nil { + x.Fee = new(v1beta1.Fee) + } + return protoreflect.ValueOfMessage(x.Fee.ProtoReflect()) + case "testpb.TestUpdatedAuthInfo.new_field_3": + panic(fmt.Errorf("field new_field_3 of message testpb.TestUpdatedAuthInfo is not mutable")) + case "testpb.TestUpdatedAuthInfo.new_field_1024": + panic(fmt.Errorf("field new_field_1024 of message testpb.TestUpdatedAuthInfo is not mutable")) + default: + if fd.IsExtension() { + panic(fmt.Errorf("proto3 declared messages do not support extensions: testpb.TestUpdatedAuthInfo")) + } + panic(fmt.Errorf("message testpb.TestUpdatedAuthInfo does not contain field %s", fd.FullName())) + } +} + +// NewField returns a new value that is assignable to the field +// for the given descriptor. For scalars, this returns the default value. +// For lists, maps, and messages, this returns a new, empty, mutable value. +func (x *fastReflection_TestUpdatedAuthInfo) NewField(fd protoreflect.FieldDescriptor) protoreflect.Value { + switch fd.FullName() { + case "testpb.TestUpdatedAuthInfo.signer_infos": + list := []*v1beta1.SignerInfo{} + return protoreflect.ValueOfList(&_TestUpdatedAuthInfo_1_list{list: &list}) + case "testpb.TestUpdatedAuthInfo.fee": + m := new(v1beta1.Fee) + return protoreflect.ValueOfMessage(m.ProtoReflect()) + case "testpb.TestUpdatedAuthInfo.new_field_3": + return protoreflect.ValueOfBytes(nil) + case "testpb.TestUpdatedAuthInfo.new_field_1024": + return protoreflect.ValueOfBytes(nil) + default: + if fd.IsExtension() { + panic(fmt.Errorf("proto3 declared messages do not support extensions: testpb.TestUpdatedAuthInfo")) + } + panic(fmt.Errorf("message testpb.TestUpdatedAuthInfo does not contain field %s", fd.FullName())) + } +} + +// WhichOneof reports which field within the oneof is populated, +// returning nil if none are populated. +// It panics if the oneof descriptor does not belong to this message. +func (x *fastReflection_TestUpdatedAuthInfo) WhichOneof(d protoreflect.OneofDescriptor) protoreflect.FieldDescriptor { + switch d.FullName() { + default: + panic(fmt.Errorf("%s is not a oneof field in testpb.TestUpdatedAuthInfo", d.FullName())) + } + panic("unreachable") +} + +// GetUnknown retrieves the entire list of unknown fields. +// The caller may only mutate the contents of the RawFields +// if the mutated bytes are stored back into the message with SetUnknown. +func (x *fastReflection_TestUpdatedAuthInfo) GetUnknown() protoreflect.RawFields { + return x.unknownFields +} + +// SetUnknown stores an entire list of unknown fields. +// The raw fields must be syntactically valid according to the wire format. +// An implementation may panic if this is not the case. +// Once stored, the caller must not mutate the content of the RawFields. +// An empty RawFields may be passed to clear the fields. +// +// SetUnknown is a mutating operation and unsafe for concurrent use. +func (x *fastReflection_TestUpdatedAuthInfo) SetUnknown(fields protoreflect.RawFields) { + x.unknownFields = fields +} + +// IsValid reports whether the message is valid. +// +// An invalid message is an empty, read-only value. +// +// An invalid message often corresponds to a nil pointer of the concrete +// message type, but the details are implementation dependent. +// Validity is not part of the protobuf data model, and may not +// be preserved in marshaling or other operations. +func (x *fastReflection_TestUpdatedAuthInfo) IsValid() bool { + return x != nil +} + +// ProtoMethods returns optional fastReflectionFeature-path implementations of various operations. +// This method may return nil. +// +// The returned methods type is identical to +// "google.golang.org/protobuf/runtime/protoiface".Methods. +// Consult the protoiface package documentation for details. +func (x *fastReflection_TestUpdatedAuthInfo) ProtoMethods() *protoiface.Methods { + size := func(input protoiface.SizeInput) protoiface.SizeOutput { + x := input.Message.Interface().(*TestUpdatedAuthInfo) + if x == nil { + return protoiface.SizeOutput{ + NoUnkeyedLiterals: input.NoUnkeyedLiterals, + Size: 0, + } + } + options := runtime.SizeInputToOptions(input) + _ = options + var n int + var l int + _ = l + if len(x.SignerInfos) > 0 { + for _, e := range x.SignerInfos { + l = options.Size(e) + n += 1 + l + runtime.Sov(uint64(l)) + } + } + if x.Fee != nil { + l = options.Size(x.Fee) + n += 1 + l + runtime.Sov(uint64(l)) + } + l = len(x.NewField_3) + if l > 0 { + n += 1 + l + runtime.Sov(uint64(l)) + } + l = len(x.NewField_1024) + if l > 0 { + n += 2 + l + runtime.Sov(uint64(l)) + } + if x.unknownFields != nil { + n += len(x.unknownFields) + } + return protoiface.SizeOutput{ + NoUnkeyedLiterals: input.NoUnkeyedLiterals, + Size: n, + } + } + + marshal := func(input protoiface.MarshalInput) (protoiface.MarshalOutput, error) { + x := input.Message.Interface().(*TestUpdatedAuthInfo) + if x == nil { + return protoiface.MarshalOutput{ + NoUnkeyedLiterals: input.NoUnkeyedLiterals, + Buf: input.Buf, + }, nil + } + options := runtime.MarshalInputToOptions(input) + _ = options + size := options.Size(x) + dAtA := make([]byte, size) + i := len(dAtA) + _ = i + var l int + _ = l + if x.unknownFields != nil { + i -= len(x.unknownFields) + copy(dAtA[i:], x.unknownFields) + } + if len(x.NewField_1024) > 0 { + i -= len(x.NewField_1024) + copy(dAtA[i:], x.NewField_1024) + i = runtime.EncodeVarint(dAtA, i, uint64(len(x.NewField_1024))) + i-- + dAtA[i] = 0x40 + i-- + dAtA[i] = 0x82 + } + if len(x.NewField_3) > 0 { + i -= len(x.NewField_3) + copy(dAtA[i:], x.NewField_3) + i = runtime.EncodeVarint(dAtA, i, uint64(len(x.NewField_3))) + i-- + dAtA[i] = 0x1a + } + if x.Fee != nil { + encoded, err := options.Marshal(x.Fee) + if err != nil { + return protoiface.MarshalOutput{ + NoUnkeyedLiterals: input.NoUnkeyedLiterals, + Buf: input.Buf, + }, err + } + i -= len(encoded) + copy(dAtA[i:], encoded) + i = runtime.EncodeVarint(dAtA, i, uint64(len(encoded))) + i-- + dAtA[i] = 0x12 + } + if len(x.SignerInfos) > 0 { + for iNdEx := len(x.SignerInfos) - 1; iNdEx >= 0; iNdEx-- { + encoded, err := options.Marshal(x.SignerInfos[iNdEx]) + if err != nil { + return protoiface.MarshalOutput{ + NoUnkeyedLiterals: input.NoUnkeyedLiterals, + Buf: input.Buf, + }, err + } + i -= len(encoded) + copy(dAtA[i:], encoded) + i = runtime.EncodeVarint(dAtA, i, uint64(len(encoded))) + i-- + dAtA[i] = 0xa + } + } + if input.Buf != nil { + input.Buf = append(input.Buf, dAtA...) + } else { + input.Buf = dAtA + } + return protoiface.MarshalOutput{ + NoUnkeyedLiterals: input.NoUnkeyedLiterals, + Buf: input.Buf, + }, nil + } + unmarshal := func(input protoiface.UnmarshalInput) (protoiface.UnmarshalOutput, error) { + x := input.Message.Interface().(*TestUpdatedAuthInfo) + if x == nil { + return protoiface.UnmarshalOutput{ + NoUnkeyedLiterals: input.NoUnkeyedLiterals, + Flags: input.Flags, + }, nil + } + options := runtime.UnmarshalInputToOptions(input) + _ = options + dAtA := input.Buf + l := len(dAtA) + iNdEx := 0 + for iNdEx < l { + preIndex := iNdEx + var wire uint64 + for shift := uint(0); ; shift += 7 { + if shift >= 64 { + return protoiface.UnmarshalOutput{NoUnkeyedLiterals: input.NoUnkeyedLiterals, Flags: input.Flags}, runtime.ErrIntOverflow + } + if iNdEx >= l { + return protoiface.UnmarshalOutput{NoUnkeyedLiterals: input.NoUnkeyedLiterals, Flags: input.Flags}, io.ErrUnexpectedEOF + } + b := dAtA[iNdEx] + iNdEx++ + wire |= uint64(b&0x7F) << shift + if b < 0x80 { + break + } + } + fieldNum := int32(wire >> 3) + wireType := int(wire & 0x7) + if wireType == 4 { + return protoiface.UnmarshalOutput{NoUnkeyedLiterals: input.NoUnkeyedLiterals, Flags: input.Flags}, fmt.Errorf("proto: TestUpdatedAuthInfo: wiretype end group for non-group") + } + if fieldNum <= 0 { + return protoiface.UnmarshalOutput{NoUnkeyedLiterals: input.NoUnkeyedLiterals, Flags: input.Flags}, fmt.Errorf("proto: TestUpdatedAuthInfo: illegal tag %d (wire type %d)", fieldNum, wire) + } + switch fieldNum { + case 1: + if wireType != 2 { + return protoiface.UnmarshalOutput{NoUnkeyedLiterals: input.NoUnkeyedLiterals, Flags: input.Flags}, fmt.Errorf("proto: wrong wireType = %d for field SignerInfos", wireType) + } + var msglen int + for shift := uint(0); ; shift += 7 { + if shift >= 64 { + return protoiface.UnmarshalOutput{NoUnkeyedLiterals: input.NoUnkeyedLiterals, Flags: input.Flags}, runtime.ErrIntOverflow + } + if iNdEx >= l { + return protoiface.UnmarshalOutput{NoUnkeyedLiterals: input.NoUnkeyedLiterals, Flags: input.Flags}, io.ErrUnexpectedEOF + } + b := dAtA[iNdEx] + iNdEx++ + msglen |= int(b&0x7F) << shift + if b < 0x80 { + break + } + } + if msglen < 0 { + return protoiface.UnmarshalOutput{NoUnkeyedLiterals: input.NoUnkeyedLiterals, Flags: input.Flags}, runtime.ErrInvalidLength + } + postIndex := iNdEx + msglen + if postIndex < 0 { + return protoiface.UnmarshalOutput{NoUnkeyedLiterals: input.NoUnkeyedLiterals, Flags: input.Flags}, runtime.ErrInvalidLength + } + if postIndex > l { + return protoiface.UnmarshalOutput{NoUnkeyedLiterals: input.NoUnkeyedLiterals, Flags: input.Flags}, io.ErrUnexpectedEOF + } + x.SignerInfos = append(x.SignerInfos, &v1beta1.SignerInfo{}) + if err := options.Unmarshal(dAtA[iNdEx:postIndex], x.SignerInfos[len(x.SignerInfos)-1]); err != nil { + return protoiface.UnmarshalOutput{NoUnkeyedLiterals: input.NoUnkeyedLiterals, Flags: input.Flags}, err + } + iNdEx = postIndex + case 2: + if wireType != 2 { + return protoiface.UnmarshalOutput{NoUnkeyedLiterals: input.NoUnkeyedLiterals, Flags: input.Flags}, fmt.Errorf("proto: wrong wireType = %d for field Fee", wireType) + } + var msglen int + for shift := uint(0); ; shift += 7 { + if shift >= 64 { + return protoiface.UnmarshalOutput{NoUnkeyedLiterals: input.NoUnkeyedLiterals, Flags: input.Flags}, runtime.ErrIntOverflow + } + if iNdEx >= l { + return protoiface.UnmarshalOutput{NoUnkeyedLiterals: input.NoUnkeyedLiterals, Flags: input.Flags}, io.ErrUnexpectedEOF + } + b := dAtA[iNdEx] + iNdEx++ + msglen |= int(b&0x7F) << shift + if b < 0x80 { + break + } + } + if msglen < 0 { + return protoiface.UnmarshalOutput{NoUnkeyedLiterals: input.NoUnkeyedLiterals, Flags: input.Flags}, runtime.ErrInvalidLength + } + postIndex := iNdEx + msglen + if postIndex < 0 { + return protoiface.UnmarshalOutput{NoUnkeyedLiterals: input.NoUnkeyedLiterals, Flags: input.Flags}, runtime.ErrInvalidLength + } + if postIndex > l { + return protoiface.UnmarshalOutput{NoUnkeyedLiterals: input.NoUnkeyedLiterals, Flags: input.Flags}, io.ErrUnexpectedEOF + } + if x.Fee == nil { + x.Fee = &v1beta1.Fee{} + } + if err := options.Unmarshal(dAtA[iNdEx:postIndex], x.Fee); err != nil { + return protoiface.UnmarshalOutput{NoUnkeyedLiterals: input.NoUnkeyedLiterals, Flags: input.Flags}, err + } + iNdEx = postIndex + case 3: + if wireType != 2 { + return protoiface.UnmarshalOutput{NoUnkeyedLiterals: input.NoUnkeyedLiterals, Flags: input.Flags}, fmt.Errorf("proto: wrong wireType = %d for field NewField_3", wireType) + } + var byteLen int + for shift := uint(0); ; shift += 7 { + if shift >= 64 { + return protoiface.UnmarshalOutput{NoUnkeyedLiterals: input.NoUnkeyedLiterals, Flags: input.Flags}, runtime.ErrIntOverflow + } + if iNdEx >= l { + return protoiface.UnmarshalOutput{NoUnkeyedLiterals: input.NoUnkeyedLiterals, Flags: input.Flags}, io.ErrUnexpectedEOF + } + b := dAtA[iNdEx] + iNdEx++ + byteLen |= int(b&0x7F) << shift + if b < 0x80 { + break + } + } + if byteLen < 0 { + return protoiface.UnmarshalOutput{NoUnkeyedLiterals: input.NoUnkeyedLiterals, Flags: input.Flags}, runtime.ErrInvalidLength + } + postIndex := iNdEx + byteLen + if postIndex < 0 { + return protoiface.UnmarshalOutput{NoUnkeyedLiterals: input.NoUnkeyedLiterals, Flags: input.Flags}, runtime.ErrInvalidLength + } + if postIndex > l { + return protoiface.UnmarshalOutput{NoUnkeyedLiterals: input.NoUnkeyedLiterals, Flags: input.Flags}, io.ErrUnexpectedEOF + } + x.NewField_3 = append(x.NewField_3[:0], dAtA[iNdEx:postIndex]...) + if x.NewField_3 == nil { + x.NewField_3 = []byte{} + } + iNdEx = postIndex + case 1024: + if wireType != 2 { + return protoiface.UnmarshalOutput{NoUnkeyedLiterals: input.NoUnkeyedLiterals, Flags: input.Flags}, fmt.Errorf("proto: wrong wireType = %d for field NewField_1024", wireType) + } + var byteLen int + for shift := uint(0); ; shift += 7 { + if shift >= 64 { + return protoiface.UnmarshalOutput{NoUnkeyedLiterals: input.NoUnkeyedLiterals, Flags: input.Flags}, runtime.ErrIntOverflow + } + if iNdEx >= l { + return protoiface.UnmarshalOutput{NoUnkeyedLiterals: input.NoUnkeyedLiterals, Flags: input.Flags}, io.ErrUnexpectedEOF + } + b := dAtA[iNdEx] + iNdEx++ + byteLen |= int(b&0x7F) << shift + if b < 0x80 { + break + } + } + if byteLen < 0 { + return protoiface.UnmarshalOutput{NoUnkeyedLiterals: input.NoUnkeyedLiterals, Flags: input.Flags}, runtime.ErrInvalidLength + } + postIndex := iNdEx + byteLen + if postIndex < 0 { + return protoiface.UnmarshalOutput{NoUnkeyedLiterals: input.NoUnkeyedLiterals, Flags: input.Flags}, runtime.ErrInvalidLength + } + if postIndex > l { + return protoiface.UnmarshalOutput{NoUnkeyedLiterals: input.NoUnkeyedLiterals, Flags: input.Flags}, io.ErrUnexpectedEOF + } + x.NewField_1024 = append(x.NewField_1024[:0], dAtA[iNdEx:postIndex]...) + if x.NewField_1024 == nil { + x.NewField_1024 = []byte{} + } + iNdEx = postIndex + default: + iNdEx = preIndex + skippy, err := runtime.Skip(dAtA[iNdEx:]) + if err != nil { + return protoiface.UnmarshalOutput{NoUnkeyedLiterals: input.NoUnkeyedLiterals, Flags: input.Flags}, err + } + if (skippy < 0) || (iNdEx+skippy) < 0 { + return protoiface.UnmarshalOutput{NoUnkeyedLiterals: input.NoUnkeyedLiterals, Flags: input.Flags}, runtime.ErrInvalidLength + } + if (iNdEx + skippy) > l { + return protoiface.UnmarshalOutput{NoUnkeyedLiterals: input.NoUnkeyedLiterals, Flags: input.Flags}, io.ErrUnexpectedEOF + } + if !options.DiscardUnknown { + x.unknownFields = append(x.unknownFields, dAtA[iNdEx:iNdEx+skippy]...) + } + iNdEx += skippy + } + } + + if iNdEx > l { + return protoiface.UnmarshalOutput{NoUnkeyedLiterals: input.NoUnkeyedLiterals, Flags: input.Flags}, io.ErrUnexpectedEOF + } + return protoiface.UnmarshalOutput{NoUnkeyedLiterals: input.NoUnkeyedLiterals, Flags: input.Flags}, nil + } + return &protoiface.Methods{ + NoUnkeyedLiterals: struct{}{}, + Flags: protoiface.SupportMarshalDeterministic | protoiface.SupportUnmarshalDiscardUnknown, + Size: size, + Marshal: marshal, + Unmarshal: unmarshal, + Merge: nil, + CheckInitialized: nil, + } +} + +var _ protoreflect.List = (*_TestRepeatedUints_1_list)(nil) + +type _TestRepeatedUints_1_list struct { + list *[]uint64 +} + +func (x *_TestRepeatedUints_1_list) Len() int { + if x.list == nil { + return 0 + } + return len(*x.list) +} + +func (x *_TestRepeatedUints_1_list) Get(i int) protoreflect.Value { + return protoreflect.ValueOfUint64((*x.list)[i]) +} + +func (x *_TestRepeatedUints_1_list) Set(i int, value protoreflect.Value) { + valueUnwrapped := value.Uint() + concreteValue := valueUnwrapped + (*x.list)[i] = concreteValue +} + +func (x *_TestRepeatedUints_1_list) Append(value protoreflect.Value) { + valueUnwrapped := value.Uint() + concreteValue := valueUnwrapped + *x.list = append(*x.list, concreteValue) +} + +func (x *_TestRepeatedUints_1_list) AppendMutable() protoreflect.Value { + panic(fmt.Errorf("AppendMutable can not be called on message TestRepeatedUints at list field Nums as it is not of Message kind")) +} + +func (x *_TestRepeatedUints_1_list) Truncate(n int) { + *x.list = (*x.list)[:n] +} + +func (x *_TestRepeatedUints_1_list) NewElement() protoreflect.Value { + v := uint64(0) + return protoreflect.ValueOfUint64(v) +} + +func (x *_TestRepeatedUints_1_list) IsValid() bool { + return x.list != nil +} + +var ( + md_TestRepeatedUints protoreflect.MessageDescriptor + fd_TestRepeatedUints_nums protoreflect.FieldDescriptor +) + +func init() { + file_unknownproto_proto_init() + md_TestRepeatedUints = File_unknownproto_proto.Messages().ByName("TestRepeatedUints") + fd_TestRepeatedUints_nums = md_TestRepeatedUints.Fields().ByName("nums") +} + +var _ protoreflect.Message = (*fastReflection_TestRepeatedUints)(nil) + +type fastReflection_TestRepeatedUints TestRepeatedUints + +func (x *TestRepeatedUints) ProtoReflect() protoreflect.Message { + return (*fastReflection_TestRepeatedUints)(x) +} + +func (x *TestRepeatedUints) slowProtoReflect() protoreflect.Message { + mi := &file_unknownproto_proto_msgTypes[23] + if protoimpl.UnsafeEnabled && x != nil { + ms := protoimpl.X.MessageStateOf(protoimpl.Pointer(x)) + if ms.LoadMessageInfo() == nil { + ms.StoreMessageInfo(mi) + } + return ms + } + return mi.MessageOf(x) +} + +var _fastReflection_TestRepeatedUints_messageType fastReflection_TestRepeatedUints_messageType +var _ protoreflect.MessageType = fastReflection_TestRepeatedUints_messageType{} + +type fastReflection_TestRepeatedUints_messageType struct{} + +func (x fastReflection_TestRepeatedUints_messageType) Zero() protoreflect.Message { + return (*fastReflection_TestRepeatedUints)(nil) +} +func (x fastReflection_TestRepeatedUints_messageType) New() protoreflect.Message { + return new(fastReflection_TestRepeatedUints) +} +func (x fastReflection_TestRepeatedUints_messageType) Descriptor() protoreflect.MessageDescriptor { + return md_TestRepeatedUints +} + +// Descriptor returns message descriptor, which contains only the protobuf +// type information for the message. +func (x *fastReflection_TestRepeatedUints) Descriptor() protoreflect.MessageDescriptor { + return md_TestRepeatedUints +} + +// Type returns the message type, which encapsulates both Go and protobuf +// type information. If the Go type information is not needed, +// it is recommended that the message descriptor be used instead. +func (x *fastReflection_TestRepeatedUints) Type() protoreflect.MessageType { + return _fastReflection_TestRepeatedUints_messageType +} + +// New returns a newly allocated and mutable empty message. +func (x *fastReflection_TestRepeatedUints) New() protoreflect.Message { + return new(fastReflection_TestRepeatedUints) +} + +// Interface unwraps the message reflection interface and +// returns the underlying ProtoMessage interface. +func (x *fastReflection_TestRepeatedUints) Interface() protoreflect.ProtoMessage { + return (*TestRepeatedUints)(x) +} + +// Range iterates over every populated field in an undefined order, +// calling f for each field descriptor and value encountered. +// Range returns immediately if f returns false. +// While iterating, mutating operations may only be performed +// on the current field descriptor. +func (x *fastReflection_TestRepeatedUints) Range(f func(protoreflect.FieldDescriptor, protoreflect.Value) bool) { + if len(x.Nums) != 0 { + value := protoreflect.ValueOfList(&_TestRepeatedUints_1_list{list: &x.Nums}) + if !f(fd_TestRepeatedUints_nums, value) { + return + } + } +} + +// Has reports whether a field is populated. +// +// Some fields have the property of nullability where it is possible to +// distinguish between the default value of a field and whether the field +// was explicitly populated with the default value. Singular message fields, +// member fields of a oneof, and proto2 scalar fields are nullable. Such +// fields are populated only if explicitly set. +// +// In other cases (aside from the nullable cases above), +// a proto3 scalar field is populated if it contains a non-zero value, and +// a repeated field is populated if it is non-empty. +func (x *fastReflection_TestRepeatedUints) Has(fd protoreflect.FieldDescriptor) bool { + switch fd.FullName() { + case "testpb.TestRepeatedUints.nums": + return len(x.Nums) != 0 + default: + if fd.IsExtension() { + panic(fmt.Errorf("proto3 declared messages do not support extensions: testpb.TestRepeatedUints")) + } + panic(fmt.Errorf("message testpb.TestRepeatedUints does not contain field %s", fd.FullName())) + } +} + +// Clear clears the field such that a subsequent Has call reports false. +// +// Clearing an extension field clears both the extension type and value +// associated with the given field number. +// +// Clear is a mutating operation and unsafe for concurrent use. +func (x *fastReflection_TestRepeatedUints) Clear(fd protoreflect.FieldDescriptor) { + switch fd.FullName() { + case "testpb.TestRepeatedUints.nums": + x.Nums = nil + default: + if fd.IsExtension() { + panic(fmt.Errorf("proto3 declared messages do not support extensions: testpb.TestRepeatedUints")) + } + panic(fmt.Errorf("message testpb.TestRepeatedUints does not contain field %s", fd.FullName())) + } +} + +// Get retrieves the value for a field. +// +// For unpopulated scalars, it returns the default value, where +// the default value of a bytes scalar is guaranteed to be a copy. +// For unpopulated composite types, it returns an empty, read-only view +// of the value; to obtain a mutable reference, use Mutable. +func (x *fastReflection_TestRepeatedUints) Get(descriptor protoreflect.FieldDescriptor) protoreflect.Value { + switch descriptor.FullName() { + case "testpb.TestRepeatedUints.nums": + if len(x.Nums) == 0 { + return protoreflect.ValueOfList(&_TestRepeatedUints_1_list{}) + } + listValue := &_TestRepeatedUints_1_list{list: &x.Nums} + return protoreflect.ValueOfList(listValue) + default: + if descriptor.IsExtension() { + panic(fmt.Errorf("proto3 declared messages do not support extensions: testpb.TestRepeatedUints")) + } + panic(fmt.Errorf("message testpb.TestRepeatedUints does not contain field %s", descriptor.FullName())) + } +} + +// Set stores the value for a field. +// +// For a field belonging to a oneof, it implicitly clears any other field +// that may be currently set within the same oneof. +// For extension fields, it implicitly stores the provided ExtensionType. +// When setting a composite type, it is unspecified whether the stored value +// aliases the source's memory in any way. If the composite value is an +// empty, read-only value, then it panics. +// +// Set is a mutating operation and unsafe for concurrent use. +func (x *fastReflection_TestRepeatedUints) Set(fd protoreflect.FieldDescriptor, value protoreflect.Value) { + switch fd.FullName() { + case "testpb.TestRepeatedUints.nums": + lv := value.List() + clv := lv.(*_TestRepeatedUints_1_list) + x.Nums = *clv.list + default: + if fd.IsExtension() { + panic(fmt.Errorf("proto3 declared messages do not support extensions: testpb.TestRepeatedUints")) + } + panic(fmt.Errorf("message testpb.TestRepeatedUints does not contain field %s", fd.FullName())) + } +} + +// Mutable returns a mutable reference to a composite type. +// +// If the field is unpopulated, it may allocate a composite value. +// For a field belonging to a oneof, it implicitly clears any other field +// that may be currently set within the same oneof. +// For extension fields, it implicitly stores the provided ExtensionType +// if not already stored. +// It panics if the field does not contain a composite type. +// +// Mutable is a mutating operation and unsafe for concurrent use. +func (x *fastReflection_TestRepeatedUints) Mutable(fd protoreflect.FieldDescriptor) protoreflect.Value { + switch fd.FullName() { + case "testpb.TestRepeatedUints.nums": + if x.Nums == nil { + x.Nums = []uint64{} + } + value := &_TestRepeatedUints_1_list{list: &x.Nums} + return protoreflect.ValueOfList(value) + default: + if fd.IsExtension() { + panic(fmt.Errorf("proto3 declared messages do not support extensions: testpb.TestRepeatedUints")) + } + panic(fmt.Errorf("message testpb.TestRepeatedUints does not contain field %s", fd.FullName())) + } +} + +// NewField returns a new value that is assignable to the field +// for the given descriptor. For scalars, this returns the default value. +// For lists, maps, and messages, this returns a new, empty, mutable value. +func (x *fastReflection_TestRepeatedUints) NewField(fd protoreflect.FieldDescriptor) protoreflect.Value { + switch fd.FullName() { + case "testpb.TestRepeatedUints.nums": + list := []uint64{} + return protoreflect.ValueOfList(&_TestRepeatedUints_1_list{list: &list}) + default: + if fd.IsExtension() { + panic(fmt.Errorf("proto3 declared messages do not support extensions: testpb.TestRepeatedUints")) + } + panic(fmt.Errorf("message testpb.TestRepeatedUints does not contain field %s", fd.FullName())) + } +} + +// WhichOneof reports which field within the oneof is populated, +// returning nil if none are populated. +// It panics if the oneof descriptor does not belong to this message. +func (x *fastReflection_TestRepeatedUints) WhichOneof(d protoreflect.OneofDescriptor) protoreflect.FieldDescriptor { + switch d.FullName() { + default: + panic(fmt.Errorf("%s is not a oneof field in testpb.TestRepeatedUints", d.FullName())) + } + panic("unreachable") +} + +// GetUnknown retrieves the entire list of unknown fields. +// The caller may only mutate the contents of the RawFields +// if the mutated bytes are stored back into the message with SetUnknown. +func (x *fastReflection_TestRepeatedUints) GetUnknown() protoreflect.RawFields { + return x.unknownFields +} + +// SetUnknown stores an entire list of unknown fields. +// The raw fields must be syntactically valid according to the wire format. +// An implementation may panic if this is not the case. +// Once stored, the caller must not mutate the content of the RawFields. +// An empty RawFields may be passed to clear the fields. +// +// SetUnknown is a mutating operation and unsafe for concurrent use. +func (x *fastReflection_TestRepeatedUints) SetUnknown(fields protoreflect.RawFields) { + x.unknownFields = fields +} + +// IsValid reports whether the message is valid. +// +// An invalid message is an empty, read-only value. +// +// An invalid message often corresponds to a nil pointer of the concrete +// message type, but the details are implementation dependent. +// Validity is not part of the protobuf data model, and may not +// be preserved in marshaling or other operations. +func (x *fastReflection_TestRepeatedUints) IsValid() bool { + return x != nil +} + +// ProtoMethods returns optional fastReflectionFeature-path implementations of various operations. +// This method may return nil. +// +// The returned methods type is identical to +// "google.golang.org/protobuf/runtime/protoiface".Methods. +// Consult the protoiface package documentation for details. +func (x *fastReflection_TestRepeatedUints) ProtoMethods() *protoiface.Methods { + size := func(input protoiface.SizeInput) protoiface.SizeOutput { + x := input.Message.Interface().(*TestRepeatedUints) + if x == nil { + return protoiface.SizeOutput{ + NoUnkeyedLiterals: input.NoUnkeyedLiterals, + Size: 0, + } + } + options := runtime.SizeInputToOptions(input) + _ = options + var n int + var l int + _ = l + if len(x.Nums) > 0 { + l = 0 + for _, e := range x.Nums { + l += runtime.Sov(uint64(e)) + } + n += 1 + runtime.Sov(uint64(l)) + l + } + if x.unknownFields != nil { + n += len(x.unknownFields) + } + return protoiface.SizeOutput{ + NoUnkeyedLiterals: input.NoUnkeyedLiterals, + Size: n, + } + } + + marshal := func(input protoiface.MarshalInput) (protoiface.MarshalOutput, error) { + x := input.Message.Interface().(*TestRepeatedUints) + if x == nil { + return protoiface.MarshalOutput{ + NoUnkeyedLiterals: input.NoUnkeyedLiterals, + Buf: input.Buf, + }, nil + } + options := runtime.MarshalInputToOptions(input) + _ = options + size := options.Size(x) + dAtA := make([]byte, size) + i := len(dAtA) + _ = i + var l int + _ = l + if x.unknownFields != nil { + i -= len(x.unknownFields) + copy(dAtA[i:], x.unknownFields) + } + if len(x.Nums) > 0 { + var pksize2 int + for _, num := range x.Nums { + pksize2 += runtime.Sov(uint64(num)) + } + i -= pksize2 + j1 := i + for _, num := range x.Nums { + for num >= 1<<7 { + dAtA[j1] = uint8(uint64(num)&0x7f | 0x80) + num >>= 7 + j1++ + } + dAtA[j1] = uint8(num) + j1++ + } + i = runtime.EncodeVarint(dAtA, i, uint64(pksize2)) + i-- + dAtA[i] = 0xa + } + if input.Buf != nil { + input.Buf = append(input.Buf, dAtA...) + } else { + input.Buf = dAtA + } + return protoiface.MarshalOutput{ + NoUnkeyedLiterals: input.NoUnkeyedLiterals, + Buf: input.Buf, + }, nil + } + unmarshal := func(input protoiface.UnmarshalInput) (protoiface.UnmarshalOutput, error) { + x := input.Message.Interface().(*TestRepeatedUints) + if x == nil { + return protoiface.UnmarshalOutput{ + NoUnkeyedLiterals: input.NoUnkeyedLiterals, + Flags: input.Flags, + }, nil + } + options := runtime.UnmarshalInputToOptions(input) + _ = options + dAtA := input.Buf + l := len(dAtA) + iNdEx := 0 + for iNdEx < l { + preIndex := iNdEx + var wire uint64 + for shift := uint(0); ; shift += 7 { + if shift >= 64 { + return protoiface.UnmarshalOutput{NoUnkeyedLiterals: input.NoUnkeyedLiterals, Flags: input.Flags}, runtime.ErrIntOverflow + } + if iNdEx >= l { + return protoiface.UnmarshalOutput{NoUnkeyedLiterals: input.NoUnkeyedLiterals, Flags: input.Flags}, io.ErrUnexpectedEOF + } + b := dAtA[iNdEx] + iNdEx++ + wire |= uint64(b&0x7F) << shift + if b < 0x80 { + break + } + } + fieldNum := int32(wire >> 3) + wireType := int(wire & 0x7) + if wireType == 4 { + return protoiface.UnmarshalOutput{NoUnkeyedLiterals: input.NoUnkeyedLiterals, Flags: input.Flags}, fmt.Errorf("proto: TestRepeatedUints: wiretype end group for non-group") + } + if fieldNum <= 0 { + return protoiface.UnmarshalOutput{NoUnkeyedLiterals: input.NoUnkeyedLiterals, Flags: input.Flags}, fmt.Errorf("proto: TestRepeatedUints: illegal tag %d (wire type %d)", fieldNum, wire) + } + switch fieldNum { + case 1: + if wireType == 0 { + var v uint64 + for shift := uint(0); ; shift += 7 { + if shift >= 64 { + return protoiface.UnmarshalOutput{NoUnkeyedLiterals: input.NoUnkeyedLiterals, Flags: input.Flags}, runtime.ErrIntOverflow + } + if iNdEx >= l { + return protoiface.UnmarshalOutput{NoUnkeyedLiterals: input.NoUnkeyedLiterals, Flags: input.Flags}, io.ErrUnexpectedEOF + } + b := dAtA[iNdEx] + iNdEx++ + v |= uint64(b&0x7F) << shift + if b < 0x80 { + break + } + } + x.Nums = append(x.Nums, v) + } else if wireType == 2 { + var packedLen int + for shift := uint(0); ; shift += 7 { + if shift >= 64 { + return protoiface.UnmarshalOutput{NoUnkeyedLiterals: input.NoUnkeyedLiterals, Flags: input.Flags}, runtime.ErrIntOverflow + } + if iNdEx >= l { + return protoiface.UnmarshalOutput{NoUnkeyedLiterals: input.NoUnkeyedLiterals, Flags: input.Flags}, io.ErrUnexpectedEOF + } + b := dAtA[iNdEx] + iNdEx++ + packedLen |= int(b&0x7F) << shift + if b < 0x80 { + break + } + } + if packedLen < 0 { + return protoiface.UnmarshalOutput{NoUnkeyedLiterals: input.NoUnkeyedLiterals, Flags: input.Flags}, runtime.ErrInvalidLength + } + postIndex := iNdEx + packedLen + if postIndex < 0 { + return protoiface.UnmarshalOutput{NoUnkeyedLiterals: input.NoUnkeyedLiterals, Flags: input.Flags}, runtime.ErrInvalidLength + } + if postIndex > l { + return protoiface.UnmarshalOutput{NoUnkeyedLiterals: input.NoUnkeyedLiterals, Flags: input.Flags}, io.ErrUnexpectedEOF + } + var elementCount int + var count int + for _, integer := range dAtA[iNdEx:postIndex] { + if integer < 128 { + count++ + } + } + elementCount = count + if elementCount != 0 && len(x.Nums) == 0 { + x.Nums = make([]uint64, 0, elementCount) + } + for iNdEx < postIndex { + var v uint64 + for shift := uint(0); ; shift += 7 { + if shift >= 64 { + return protoiface.UnmarshalOutput{NoUnkeyedLiterals: input.NoUnkeyedLiterals, Flags: input.Flags}, runtime.ErrIntOverflow + } + if iNdEx >= l { + return protoiface.UnmarshalOutput{NoUnkeyedLiterals: input.NoUnkeyedLiterals, Flags: input.Flags}, io.ErrUnexpectedEOF + } + b := dAtA[iNdEx] + iNdEx++ + v |= uint64(b&0x7F) << shift + if b < 0x80 { + break + } + } + x.Nums = append(x.Nums, v) + } + } else { + return protoiface.UnmarshalOutput{NoUnkeyedLiterals: input.NoUnkeyedLiterals, Flags: input.Flags}, fmt.Errorf("proto: wrong wireType = %d for field Nums", wireType) + } + default: + iNdEx = preIndex + skippy, err := runtime.Skip(dAtA[iNdEx:]) + if err != nil { + return protoiface.UnmarshalOutput{NoUnkeyedLiterals: input.NoUnkeyedLiterals, Flags: input.Flags}, err + } + if (skippy < 0) || (iNdEx+skippy) < 0 { + return protoiface.UnmarshalOutput{NoUnkeyedLiterals: input.NoUnkeyedLiterals, Flags: input.Flags}, runtime.ErrInvalidLength + } + if (iNdEx + skippy) > l { + return protoiface.UnmarshalOutput{NoUnkeyedLiterals: input.NoUnkeyedLiterals, Flags: input.Flags}, io.ErrUnexpectedEOF + } + if !options.DiscardUnknown { + x.unknownFields = append(x.unknownFields, dAtA[iNdEx:iNdEx+skippy]...) + } + iNdEx += skippy + } + } + + if iNdEx > l { + return protoiface.UnmarshalOutput{NoUnkeyedLiterals: input.NoUnkeyedLiterals, Flags: input.Flags}, io.ErrUnexpectedEOF + } + return protoiface.UnmarshalOutput{NoUnkeyedLiterals: input.NoUnkeyedLiterals, Flags: input.Flags}, nil + } + return &protoiface.Methods{ + NoUnkeyedLiterals: struct{}{}, + Flags: protoiface.SupportMarshalDeterministic | protoiface.SupportUnmarshalDiscardUnknown, + Size: size, + Marshal: marshal, + Unmarshal: unmarshal, + Merge: nil, + CheckInitialized: nil, + } +} + +// Code generated by protoc-gen-go. DO NOT EDIT. +// versions: +// protoc-gen-go v1.27.0 +// protoc (unknown) +// source: unknownproto.proto + +const ( + // Verify that this generated code is sufficiently up-to-date. + _ = protoimpl.EnforceVersion(20 - protoimpl.MinVersion) + // Verify that runtime/protoimpl is sufficiently up-to-date. + _ = protoimpl.EnforceVersion(protoimpl.MaxVersion - 20) +) + +type Customer2_City int32 + +const ( + Customer2_Laos Customer2_City = 0 + Customer2_LosAngeles Customer2_City = 1 + Customer2_PaloAlto Customer2_City = 2 + Customer2_Moscow Customer2_City = 3 + Customer2_Nairobi Customer2_City = 4 +) + +// Enum value maps for Customer2_City. +var ( + Customer2_City_name = map[int32]string{ + 0: "Laos", + 1: "LosAngeles", + 2: "PaloAlto", + 3: "Moscow", + 4: "Nairobi", + } + Customer2_City_value = map[string]int32{ + "Laos": 0, + "LosAngeles": 1, + "PaloAlto": 2, + "Moscow": 3, + "Nairobi": 4, + } +) + +func (x Customer2_City) Enum() *Customer2_City { + p := new(Customer2_City) + *p = x + return p +} + +func (x Customer2_City) String() string { + return protoimpl.X.EnumStringOf(x.Descriptor(), protoreflect.EnumNumber(x)) +} + +func (Customer2_City) Descriptor() protoreflect.EnumDescriptor { + return file_unknownproto_proto_enumTypes[0].Descriptor() +} + +func (Customer2_City) Type() protoreflect.EnumType { + return &file_unknownproto_proto_enumTypes[0] +} + +func (x Customer2_City) Number() protoreflect.EnumNumber { + return protoreflect.EnumNumber(x) +} + +// Deprecated: Use Customer2_City.Descriptor instead. +func (Customer2_City) EnumDescriptor() ([]byte, []int) { + return file_unknownproto_proto_rawDescGZIP(), []int{1, 0} +} + +type Customer1 struct { + state protoimpl.MessageState + sizeCache protoimpl.SizeCache + unknownFields protoimpl.UnknownFields + + Id int32 `protobuf:"varint,1,opt,name=id,proto3" json:"id,omitempty"` + Name string `protobuf:"bytes,2,opt,name=name,proto3" json:"name,omitempty"` + SubscriptionFee float32 `protobuf:"fixed32,3,opt,name=subscription_fee,json=subscriptionFee,proto3" json:"subscription_fee,omitempty"` + Payment string `protobuf:"bytes,7,opt,name=payment,proto3" json:"payment,omitempty"` +} + +func (x *Customer1) Reset() { + *x = Customer1{} + if protoimpl.UnsafeEnabled { + mi := &file_unknownproto_proto_msgTypes[0] + ms := protoimpl.X.MessageStateOf(protoimpl.Pointer(x)) + ms.StoreMessageInfo(mi) + } +} + +func (x *Customer1) String() string { + return protoimpl.X.MessageStringOf(x) +} + +func (*Customer1) ProtoMessage() {} + +// Deprecated: Use Customer1.ProtoReflect.Descriptor instead. +func (*Customer1) Descriptor() ([]byte, []int) { + return file_unknownproto_proto_rawDescGZIP(), []int{0} +} + +func (x *Customer1) GetId() int32 { + if x != nil { + return x.Id + } + return 0 +} + +func (x *Customer1) GetName() string { + if x != nil { + return x.Name + } + return "" +} + +func (x *Customer1) GetSubscriptionFee() float32 { + if x != nil { + return x.SubscriptionFee + } + return 0 +} + +func (x *Customer1) GetPayment() string { + if x != nil { + return x.Payment + } + return "" +} + +type Customer2 struct { + state protoimpl.MessageState + sizeCache protoimpl.SizeCache + unknownFields protoimpl.UnknownFields + + Id int32 `protobuf:"varint,1,opt,name=id,proto3" json:"id,omitempty"` + Industry int32 `protobuf:"varint,2,opt,name=industry,proto3" json:"industry,omitempty"` + Name string `protobuf:"bytes,3,opt,name=name,proto3" json:"name,omitempty"` + Fewer float32 `protobuf:"fixed32,4,opt,name=fewer,proto3" json:"fewer,omitempty"` + Reserved int64 `protobuf:"varint,1047,opt,name=reserved,proto3" json:"reserved,omitempty"` + City Customer2_City `protobuf:"varint,6,opt,name=city,proto3,enum=testpb.Customer2_City" json:"city,omitempty"` + Miscellaneous *anypb.Any `protobuf:"bytes,10,opt,name=miscellaneous,proto3" json:"miscellaneous,omitempty"` +} + +func (x *Customer2) Reset() { + *x = Customer2{} + if protoimpl.UnsafeEnabled { + mi := &file_unknownproto_proto_msgTypes[1] + ms := protoimpl.X.MessageStateOf(protoimpl.Pointer(x)) + ms.StoreMessageInfo(mi) + } +} + +func (x *Customer2) String() string { + return protoimpl.X.MessageStringOf(x) +} + +func (*Customer2) ProtoMessage() {} + +// Deprecated: Use Customer2.ProtoReflect.Descriptor instead. +func (*Customer2) Descriptor() ([]byte, []int) { + return file_unknownproto_proto_rawDescGZIP(), []int{1} +} + +func (x *Customer2) GetId() int32 { + if x != nil { + return x.Id + } + return 0 +} + +func (x *Customer2) GetIndustry() int32 { + if x != nil { + return x.Industry + } + return 0 +} + +func (x *Customer2) GetName() string { + if x != nil { + return x.Name + } + return "" +} + +func (x *Customer2) GetFewer() float32 { + if x != nil { + return x.Fewer + } + return 0 +} + +func (x *Customer2) GetReserved() int64 { + if x != nil { + return x.Reserved + } + return 0 +} + +func (x *Customer2) GetCity() Customer2_City { + if x != nil { + return x.City + } + return Customer2_Laos +} + +func (x *Customer2) GetMiscellaneous() *anypb.Any { + if x != nil { + return x.Miscellaneous + } + return nil +} + +type Nested4A struct { + state protoimpl.MessageState + sizeCache protoimpl.SizeCache + unknownFields protoimpl.UnknownFields + + Id int32 `protobuf:"varint,1,opt,name=id,proto3" json:"id,omitempty"` + Name string `protobuf:"bytes,2,opt,name=name,proto3" json:"name,omitempty"` +} + +func (x *Nested4A) Reset() { + *x = Nested4A{} + if protoimpl.UnsafeEnabled { + mi := &file_unknownproto_proto_msgTypes[2] + ms := protoimpl.X.MessageStateOf(protoimpl.Pointer(x)) + ms.StoreMessageInfo(mi) + } +} + +func (x *Nested4A) String() string { + return protoimpl.X.MessageStringOf(x) +} + +func (*Nested4A) ProtoMessage() {} + +// Deprecated: Use Nested4A.ProtoReflect.Descriptor instead. +func (*Nested4A) Descriptor() ([]byte, []int) { + return file_unknownproto_proto_rawDescGZIP(), []int{2} +} + +func (x *Nested4A) GetId() int32 { + if x != nil { + return x.Id + } + return 0 +} + +func (x *Nested4A) GetName() string { + if x != nil { + return x.Name + } + return "" +} + +type Nested3A struct { + state protoimpl.MessageState + sizeCache protoimpl.SizeCache + unknownFields protoimpl.UnknownFields + + Id int32 `protobuf:"varint,1,opt,name=id,proto3" json:"id,omitempty"` + Name string `protobuf:"bytes,2,opt,name=name,proto3" json:"name,omitempty"` + A4 []*Nested4A `protobuf:"bytes,4,rep,name=a4,proto3" json:"a4,omitempty"` + Index map[int64]*Nested4A `protobuf:"bytes,5,rep,name=index,proto3" json:"index,omitempty" protobuf_key:"varint,1,opt,name=key,proto3" protobuf_val:"bytes,2,opt,name=value,proto3"` +} + +func (x *Nested3A) Reset() { + *x = Nested3A{} + if protoimpl.UnsafeEnabled { + mi := &file_unknownproto_proto_msgTypes[3] + ms := protoimpl.X.MessageStateOf(protoimpl.Pointer(x)) + ms.StoreMessageInfo(mi) + } +} + +func (x *Nested3A) String() string { + return protoimpl.X.MessageStringOf(x) +} + +func (*Nested3A) ProtoMessage() {} + +// Deprecated: Use Nested3A.ProtoReflect.Descriptor instead. +func (*Nested3A) Descriptor() ([]byte, []int) { + return file_unknownproto_proto_rawDescGZIP(), []int{3} +} + +func (x *Nested3A) GetId() int32 { + if x != nil { + return x.Id + } + return 0 +} + +func (x *Nested3A) GetName() string { + if x != nil { + return x.Name + } + return "" +} + +func (x *Nested3A) GetA4() []*Nested4A { + if x != nil { + return x.A4 + } + return nil +} + +func (x *Nested3A) GetIndex() map[int64]*Nested4A { + if x != nil { + return x.Index + } + return nil +} + +type Nested2A struct { + state protoimpl.MessageState + sizeCache protoimpl.SizeCache + unknownFields protoimpl.UnknownFields + + Id int32 `protobuf:"varint,1,opt,name=id,proto3" json:"id,omitempty"` + Name string `protobuf:"bytes,2,opt,name=name,proto3" json:"name,omitempty"` + Nested *Nested3A `protobuf:"bytes,3,opt,name=nested,proto3" json:"nested,omitempty"` +} + +func (x *Nested2A) Reset() { + *x = Nested2A{} + if protoimpl.UnsafeEnabled { + mi := &file_unknownproto_proto_msgTypes[4] + ms := protoimpl.X.MessageStateOf(protoimpl.Pointer(x)) + ms.StoreMessageInfo(mi) + } +} + +func (x *Nested2A) String() string { + return protoimpl.X.MessageStringOf(x) +} + +func (*Nested2A) ProtoMessage() {} + +// Deprecated: Use Nested2A.ProtoReflect.Descriptor instead. +func (*Nested2A) Descriptor() ([]byte, []int) { + return file_unknownproto_proto_rawDescGZIP(), []int{4} +} + +func (x *Nested2A) GetId() int32 { + if x != nil { + return x.Id + } + return 0 +} + +func (x *Nested2A) GetName() string { + if x != nil { + return x.Name + } + return "" +} + +func (x *Nested2A) GetNested() *Nested3A { + if x != nil { + return x.Nested + } + return nil +} + +type Nested1A struct { + state protoimpl.MessageState + sizeCache protoimpl.SizeCache + unknownFields protoimpl.UnknownFields + + Id int32 `protobuf:"varint,1,opt,name=id,proto3" json:"id,omitempty"` + Nested *Nested2A `protobuf:"bytes,2,opt,name=nested,proto3" json:"nested,omitempty"` +} + +func (x *Nested1A) Reset() { + *x = Nested1A{} + if protoimpl.UnsafeEnabled { + mi := &file_unknownproto_proto_msgTypes[5] + ms := protoimpl.X.MessageStateOf(protoimpl.Pointer(x)) + ms.StoreMessageInfo(mi) + } +} + +func (x *Nested1A) String() string { + return protoimpl.X.MessageStringOf(x) +} + +func (*Nested1A) ProtoMessage() {} + +// Deprecated: Use Nested1A.ProtoReflect.Descriptor instead. +func (*Nested1A) Descriptor() ([]byte, []int) { + return file_unknownproto_proto_rawDescGZIP(), []int{5} +} + +func (x *Nested1A) GetId() int32 { + if x != nil { + return x.Id + } + return 0 +} + +func (x *Nested1A) GetNested() *Nested2A { + if x != nil { + return x.Nested + } + return nil +} + +type Nested4B struct { + state protoimpl.MessageState + sizeCache protoimpl.SizeCache + unknownFields protoimpl.UnknownFields + + Id int32 `protobuf:"varint,1,opt,name=id,proto3" json:"id,omitempty"` + Age int32 `protobuf:"varint,2,opt,name=age,proto3" json:"age,omitempty"` + Name string `protobuf:"bytes,3,opt,name=name,proto3" json:"name,omitempty"` +} + +func (x *Nested4B) Reset() { + *x = Nested4B{} + if protoimpl.UnsafeEnabled { + mi := &file_unknownproto_proto_msgTypes[6] + ms := protoimpl.X.MessageStateOf(protoimpl.Pointer(x)) + ms.StoreMessageInfo(mi) + } +} + +func (x *Nested4B) String() string { + return protoimpl.X.MessageStringOf(x) +} + +func (*Nested4B) ProtoMessage() {} + +// Deprecated: Use Nested4B.ProtoReflect.Descriptor instead. +func (*Nested4B) Descriptor() ([]byte, []int) { + return file_unknownproto_proto_rawDescGZIP(), []int{6} +} + +func (x *Nested4B) GetId() int32 { + if x != nil { + return x.Id + } + return 0 +} + +func (x *Nested4B) GetAge() int32 { + if x != nil { + return x.Age + } + return 0 +} + +func (x *Nested4B) GetName() string { + if x != nil { + return x.Name + } + return "" +} + +type Nested3B struct { + state protoimpl.MessageState + sizeCache protoimpl.SizeCache + unknownFields protoimpl.UnknownFields + + Id int32 `protobuf:"varint,1,opt,name=id,proto3" json:"id,omitempty"` + Age int32 `protobuf:"varint,2,opt,name=age,proto3" json:"age,omitempty"` + Name string `protobuf:"bytes,3,opt,name=name,proto3" json:"name,omitempty"` + B4 []*Nested4B `protobuf:"bytes,4,rep,name=b4,proto3" json:"b4,omitempty"` +} + +func (x *Nested3B) Reset() { + *x = Nested3B{} + if protoimpl.UnsafeEnabled { + mi := &file_unknownproto_proto_msgTypes[7] + ms := protoimpl.X.MessageStateOf(protoimpl.Pointer(x)) + ms.StoreMessageInfo(mi) + } +} + +func (x *Nested3B) String() string { + return protoimpl.X.MessageStringOf(x) +} + +func (*Nested3B) ProtoMessage() {} + +// Deprecated: Use Nested3B.ProtoReflect.Descriptor instead. +func (*Nested3B) Descriptor() ([]byte, []int) { + return file_unknownproto_proto_rawDescGZIP(), []int{7} +} + +func (x *Nested3B) GetId() int32 { + if x != nil { + return x.Id + } + return 0 +} + +func (x *Nested3B) GetAge() int32 { + if x != nil { + return x.Age + } + return 0 +} + +func (x *Nested3B) GetName() string { + if x != nil { + return x.Name + } + return "" +} + +func (x *Nested3B) GetB4() []*Nested4B { + if x != nil { + return x.B4 + } + return nil +} + +type Nested2B struct { + state protoimpl.MessageState + sizeCache protoimpl.SizeCache + unknownFields protoimpl.UnknownFields + + Id int32 `protobuf:"varint,1,opt,name=id,proto3" json:"id,omitempty"` + Fee float64 `protobuf:"fixed64,2,opt,name=fee,proto3" json:"fee,omitempty"` + Nested *Nested3B `protobuf:"bytes,3,opt,name=nested,proto3" json:"nested,omitempty"` + Route string `protobuf:"bytes,4,opt,name=route,proto3" json:"route,omitempty"` +} + +func (x *Nested2B) Reset() { + *x = Nested2B{} + if protoimpl.UnsafeEnabled { + mi := &file_unknownproto_proto_msgTypes[8] + ms := protoimpl.X.MessageStateOf(protoimpl.Pointer(x)) + ms.StoreMessageInfo(mi) + } +} + +func (x *Nested2B) String() string { + return protoimpl.X.MessageStringOf(x) +} + +func (*Nested2B) ProtoMessage() {} + +// Deprecated: Use Nested2B.ProtoReflect.Descriptor instead. +func (*Nested2B) Descriptor() ([]byte, []int) { + return file_unknownproto_proto_rawDescGZIP(), []int{8} +} + +func (x *Nested2B) GetId() int32 { + if x != nil { + return x.Id + } + return 0 +} + +func (x *Nested2B) GetFee() float64 { + if x != nil { + return x.Fee + } + return 0 +} + +func (x *Nested2B) GetNested() *Nested3B { + if x != nil { + return x.Nested + } + return nil +} + +func (x *Nested2B) GetRoute() string { + if x != nil { + return x.Route + } + return "" +} + +type Nested1B struct { + state protoimpl.MessageState + sizeCache protoimpl.SizeCache + unknownFields protoimpl.UnknownFields + + Id int32 `protobuf:"varint,1,opt,name=id,proto3" json:"id,omitempty"` + Nested *Nested2B `protobuf:"bytes,2,opt,name=nested,proto3" json:"nested,omitempty"` + Age int32 `protobuf:"varint,3,opt,name=age,proto3" json:"age,omitempty"` +} + +func (x *Nested1B) Reset() { + *x = Nested1B{} + if protoimpl.UnsafeEnabled { + mi := &file_unknownproto_proto_msgTypes[9] + ms := protoimpl.X.MessageStateOf(protoimpl.Pointer(x)) + ms.StoreMessageInfo(mi) + } +} + +func (x *Nested1B) String() string { + return protoimpl.X.MessageStringOf(x) +} + +func (*Nested1B) ProtoMessage() {} + +// Deprecated: Use Nested1B.ProtoReflect.Descriptor instead. +func (*Nested1B) Descriptor() ([]byte, []int) { + return file_unknownproto_proto_rawDescGZIP(), []int{9} +} + +func (x *Nested1B) GetId() int32 { + if x != nil { + return x.Id + } + return 0 +} + +func (x *Nested1B) GetNested() *Nested2B { + if x != nil { + return x.Nested + } + return nil +} + +func (x *Nested1B) GetAge() int32 { + if x != nil { + return x.Age + } + return 0 +} + +type Customer3 struct { + state protoimpl.MessageState + sizeCache protoimpl.SizeCache + unknownFields protoimpl.UnknownFields + + Id int32 `protobuf:"varint,1,opt,name=id,proto3" json:"id,omitempty"` + Name string `protobuf:"bytes,2,opt,name=name,proto3" json:"name,omitempty"` + Sf float32 `protobuf:"fixed32,3,opt,name=sf,proto3" json:"sf,omitempty"` + Surcharge float32 `protobuf:"fixed32,4,opt,name=surcharge,proto3" json:"surcharge,omitempty"` + Destination string `protobuf:"bytes,5,opt,name=destination,proto3" json:"destination,omitempty"` + // Types that are assignable to Payment: + // + // *Customer3_CreditCardNo + // *Customer3_ChequeNo + Payment isCustomer3_Payment `protobuf_oneof:"payment"` + Original *Customer1 `protobuf:"bytes,9,opt,name=original,proto3" json:"original,omitempty"` +} + +func (x *Customer3) Reset() { + *x = Customer3{} + if protoimpl.UnsafeEnabled { + mi := &file_unknownproto_proto_msgTypes[10] + ms := protoimpl.X.MessageStateOf(protoimpl.Pointer(x)) + ms.StoreMessageInfo(mi) + } +} + +func (x *Customer3) String() string { + return protoimpl.X.MessageStringOf(x) +} + +func (*Customer3) ProtoMessage() {} + +// Deprecated: Use Customer3.ProtoReflect.Descriptor instead. +func (*Customer3) Descriptor() ([]byte, []int) { + return file_unknownproto_proto_rawDescGZIP(), []int{10} +} + +func (x *Customer3) GetId() int32 { + if x != nil { + return x.Id + } + return 0 +} + +func (x *Customer3) GetName() string { + if x != nil { + return x.Name + } + return "" +} + +func (x *Customer3) GetSf() float32 { + if x != nil { + return x.Sf + } + return 0 +} + +func (x *Customer3) GetSurcharge() float32 { + if x != nil { + return x.Surcharge + } + return 0 +} + +func (x *Customer3) GetDestination() string { + if x != nil { + return x.Destination + } + return "" +} + +func (x *Customer3) GetPayment() isCustomer3_Payment { + if x != nil { + return x.Payment + } + return nil +} + +func (x *Customer3) GetCreditCardNo() string { + if x, ok := x.GetPayment().(*Customer3_CreditCardNo); ok { + return x.CreditCardNo + } + return "" +} + +func (x *Customer3) GetChequeNo() string { + if x, ok := x.GetPayment().(*Customer3_ChequeNo); ok { + return x.ChequeNo + } + return "" +} + +func (x *Customer3) GetOriginal() *Customer1 { + if x != nil { + return x.Original + } + return nil +} + +type isCustomer3_Payment interface { + isCustomer3_Payment() +} + +type Customer3_CreditCardNo struct { + CreditCardNo string `protobuf:"bytes,7,opt,name=credit_card_no,json=creditCardNo,proto3,oneof"` +} + +type Customer3_ChequeNo struct { + ChequeNo string `protobuf:"bytes,8,opt,name=cheque_no,json=chequeNo,proto3,oneof"` +} + +func (*Customer3_CreditCardNo) isCustomer3_Payment() {} + +func (*Customer3_ChequeNo) isCustomer3_Payment() {} + +type TestVersion1 struct { + state protoimpl.MessageState + sizeCache protoimpl.SizeCache + unknownFields protoimpl.UnknownFields + + X int64 `protobuf:"varint,1,opt,name=x,proto3" json:"x,omitempty"` + A *TestVersion1 `protobuf:"bytes,2,opt,name=a,proto3" json:"a,omitempty"` + B *TestVersion1 `protobuf:"bytes,3,opt,name=b,proto3" json:"b,omitempty"` // [(gogoproto.nullable) = false] generates invalid recursive structs; + C []*TestVersion1 `protobuf:"bytes,4,rep,name=c,proto3" json:"c,omitempty"` + D []*TestVersion1 `protobuf:"bytes,5,rep,name=d,proto3" json:"d,omitempty"` + // Types that are assignable to Sum: + // + // *TestVersion1_E + // *TestVersion1_F + Sum isTestVersion1_Sum `protobuf_oneof:"sum"` + G *anypb.Any `protobuf:"bytes,8,opt,name=g,proto3" json:"g,omitempty"` + H []*TestVersion1 `protobuf:"bytes,9,rep,name=h,proto3" json:"h,omitempty"` // [(gogoproto.castrepeated) = "TestVersion1"]; + // google.protobuf.Timestamp i = 10; + // google.protobuf.Timestamp j = 11; // [(gogoproto.stdtime) = true]; + K *Customer1 `protobuf:"bytes,12,opt,name=k,proto3" json:"k,omitempty"` +} + +func (x *TestVersion1) Reset() { + *x = TestVersion1{} + if protoimpl.UnsafeEnabled { + mi := &file_unknownproto_proto_msgTypes[11] + ms := protoimpl.X.MessageStateOf(protoimpl.Pointer(x)) + ms.StoreMessageInfo(mi) + } +} + +func (x *TestVersion1) String() string { + return protoimpl.X.MessageStringOf(x) +} + +func (*TestVersion1) ProtoMessage() {} + +// Deprecated: Use TestVersion1.ProtoReflect.Descriptor instead. +func (*TestVersion1) Descriptor() ([]byte, []int) { + return file_unknownproto_proto_rawDescGZIP(), []int{11} +} + +func (x *TestVersion1) GetX() int64 { + if x != nil { + return x.X + } + return 0 +} + +func (x *TestVersion1) GetA() *TestVersion1 { + if x != nil { + return x.A + } + return nil +} + +func (x *TestVersion1) GetB() *TestVersion1 { + if x != nil { + return x.B + } + return nil +} + +func (x *TestVersion1) GetC() []*TestVersion1 { + if x != nil { + return x.C + } + return nil +} + +func (x *TestVersion1) GetD() []*TestVersion1 { + if x != nil { + return x.D + } + return nil +} + +func (x *TestVersion1) GetSum() isTestVersion1_Sum { + if x != nil { + return x.Sum + } + return nil +} + +func (x *TestVersion1) GetE() int32 { + if x, ok := x.GetSum().(*TestVersion1_E); ok { + return x.E + } + return 0 +} + +func (x *TestVersion1) GetF() *TestVersion1 { + if x, ok := x.GetSum().(*TestVersion1_F); ok { + return x.F + } + return nil +} + +func (x *TestVersion1) GetG() *anypb.Any { + if x != nil { + return x.G + } + return nil +} + +func (x *TestVersion1) GetH() []*TestVersion1 { + if x != nil { + return x.H + } + return nil +} + +func (x *TestVersion1) GetK() *Customer1 { + if x != nil { + return x.K + } + return nil +} + +type isTestVersion1_Sum interface { + isTestVersion1_Sum() +} + +type TestVersion1_E struct { + E int32 `protobuf:"varint,6,opt,name=e,proto3,oneof"` +} + +type TestVersion1_F struct { + F *TestVersion1 `protobuf:"bytes,7,opt,name=f,proto3,oneof"` +} + +func (*TestVersion1_E) isTestVersion1_Sum() {} + +func (*TestVersion1_F) isTestVersion1_Sum() {} + +type TestVersion2 struct { + state protoimpl.MessageState + sizeCache protoimpl.SizeCache + unknownFields protoimpl.UnknownFields + + X int64 `protobuf:"varint,1,opt,name=x,proto3" json:"x,omitempty"` + A *TestVersion2 `protobuf:"bytes,2,opt,name=a,proto3" json:"a,omitempty"` + B *TestVersion2 `protobuf:"bytes,3,opt,name=b,proto3" json:"b,omitempty"` // [(gogoproto.nullable) = false]; + C []*TestVersion2 `protobuf:"bytes,4,rep,name=c,proto3" json:"c,omitempty"` + D []*TestVersion2 `protobuf:"bytes,5,rep,name=d,proto3" json:"d,omitempty"` // [(gogoproto.nullable) = false]; + // Types that are assignable to Sum: + // + // *TestVersion2_E + // *TestVersion2_F + Sum isTestVersion2_Sum `protobuf_oneof:"sum"` + G *anypb.Any `protobuf:"bytes,8,opt,name=g,proto3" json:"g,omitempty"` + H []*TestVersion1 `protobuf:"bytes,9,rep,name=h,proto3" json:"h,omitempty"` // [(gogoproto.castrepeated) = "TestVersion1"]; + // google.protobuf.Timestamp i = 10; + // google.protobuf.Timestamp j = 11; // [(gogoproto.stdtime) = true]; + K *Customer1 `protobuf:"bytes,12,opt,name=k,proto3" json:"k,omitempty"` + NewField_ uint64 `protobuf:"varint,25,opt,name=new_field,json=newField,proto3" json:"new_field,omitempty"` +} + +func (x *TestVersion2) Reset() { + *x = TestVersion2{} + if protoimpl.UnsafeEnabled { + mi := &file_unknownproto_proto_msgTypes[12] + ms := protoimpl.X.MessageStateOf(protoimpl.Pointer(x)) + ms.StoreMessageInfo(mi) + } +} + +func (x *TestVersion2) String() string { + return protoimpl.X.MessageStringOf(x) +} + +func (*TestVersion2) ProtoMessage() {} + +// Deprecated: Use TestVersion2.ProtoReflect.Descriptor instead. +func (*TestVersion2) Descriptor() ([]byte, []int) { + return file_unknownproto_proto_rawDescGZIP(), []int{12} +} + +func (x *TestVersion2) GetX() int64 { + if x != nil { + return x.X + } + return 0 +} + +func (x *TestVersion2) GetA() *TestVersion2 { + if x != nil { + return x.A + } + return nil +} + +func (x *TestVersion2) GetB() *TestVersion2 { + if x != nil { + return x.B + } + return nil +} + +func (x *TestVersion2) GetC() []*TestVersion2 { + if x != nil { + return x.C + } + return nil +} + +func (x *TestVersion2) GetD() []*TestVersion2 { + if x != nil { + return x.D + } + return nil +} + +func (x *TestVersion2) GetSum() isTestVersion2_Sum { + if x != nil { + return x.Sum + } + return nil +} + +func (x *TestVersion2) GetE() int32 { + if x, ok := x.GetSum().(*TestVersion2_E); ok { + return x.E + } + return 0 +} + +func (x *TestVersion2) GetF() *TestVersion2 { + if x, ok := x.GetSum().(*TestVersion2_F); ok { + return x.F + } + return nil +} + +func (x *TestVersion2) GetG() *anypb.Any { + if x != nil { + return x.G + } + return nil +} + +func (x *TestVersion2) GetH() []*TestVersion1 { + if x != nil { + return x.H + } + return nil +} + +func (x *TestVersion2) GetK() *Customer1 { + if x != nil { + return x.K + } + return nil +} + +func (x *TestVersion2) GetNewField_() uint64 { + if x != nil { + return x.NewField_ + } + return 0 +} + +type isTestVersion2_Sum interface { + isTestVersion2_Sum() +} + +type TestVersion2_E struct { + E int32 `protobuf:"varint,6,opt,name=e,proto3,oneof"` +} + +type TestVersion2_F struct { + F *TestVersion2 `protobuf:"bytes,7,opt,name=f,proto3,oneof"` +} + +func (*TestVersion2_E) isTestVersion2_Sum() {} + +func (*TestVersion2_F) isTestVersion2_Sum() {} + +type TestVersion3 struct { + state protoimpl.MessageState + sizeCache protoimpl.SizeCache + unknownFields protoimpl.UnknownFields + + X int64 `protobuf:"varint,1,opt,name=x,proto3" json:"x,omitempty"` + A *TestVersion3 `protobuf:"bytes,2,opt,name=a,proto3" json:"a,omitempty"` + B *TestVersion3 `protobuf:"bytes,3,opt,name=b,proto3" json:"b,omitempty"` // [(gogoproto.nullable) = false]; + C []*TestVersion3 `protobuf:"bytes,4,rep,name=c,proto3" json:"c,omitempty"` + D []*TestVersion3 `protobuf:"bytes,5,rep,name=d,proto3" json:"d,omitempty"` // [(gogoproto.nullable) = false]; + // Types that are assignable to Sum: + // + // *TestVersion3_E + // *TestVersion3_F + Sum isTestVersion3_Sum `protobuf_oneof:"sum"` + G *anypb.Any `protobuf:"bytes,8,opt,name=g,proto3" json:"g,omitempty"` + H []*TestVersion1 `protobuf:"bytes,9,rep,name=h,proto3" json:"h,omitempty"` //[(gogoproto.castrepeated) = "TestVersion1"]; + // google.protobuf.Timestamp i = 10; + // google.protobuf.Timestamp j = 11; // [(gogoproto.stdtime) = true]; + K *Customer1 `protobuf:"bytes,12,opt,name=k,proto3" json:"k,omitempty"` + NonCriticalField string `protobuf:"bytes,1031,opt,name=non_critical_field,json=nonCriticalField,proto3" json:"non_critical_field,omitempty"` +} + +func (x *TestVersion3) Reset() { + *x = TestVersion3{} + if protoimpl.UnsafeEnabled { + mi := &file_unknownproto_proto_msgTypes[13] + ms := protoimpl.X.MessageStateOf(protoimpl.Pointer(x)) + ms.StoreMessageInfo(mi) + } +} + +func (x *TestVersion3) String() string { + return protoimpl.X.MessageStringOf(x) +} + +func (*TestVersion3) ProtoMessage() {} + +// Deprecated: Use TestVersion3.ProtoReflect.Descriptor instead. +func (*TestVersion3) Descriptor() ([]byte, []int) { + return file_unknownproto_proto_rawDescGZIP(), []int{13} +} + +func (x *TestVersion3) GetX() int64 { + if x != nil { + return x.X + } + return 0 +} + +func (x *TestVersion3) GetA() *TestVersion3 { + if x != nil { + return x.A + } + return nil +} + +func (x *TestVersion3) GetB() *TestVersion3 { + if x != nil { + return x.B + } + return nil +} + +func (x *TestVersion3) GetC() []*TestVersion3 { + if x != nil { + return x.C + } + return nil +} + +func (x *TestVersion3) GetD() []*TestVersion3 { + if x != nil { + return x.D + } + return nil +} + +func (x *TestVersion3) GetSum() isTestVersion3_Sum { + if x != nil { + return x.Sum + } + return nil +} + +func (x *TestVersion3) GetE() int32 { + if x, ok := x.GetSum().(*TestVersion3_E); ok { + return x.E + } + return 0 +} + +func (x *TestVersion3) GetF() *TestVersion3 { + if x, ok := x.GetSum().(*TestVersion3_F); ok { + return x.F + } + return nil +} + +func (x *TestVersion3) GetG() *anypb.Any { + if x != nil { + return x.G + } + return nil +} + +func (x *TestVersion3) GetH() []*TestVersion1 { + if x != nil { + return x.H + } + return nil +} + +func (x *TestVersion3) GetK() *Customer1 { + if x != nil { + return x.K + } + return nil +} + +func (x *TestVersion3) GetNonCriticalField() string { + if x != nil { + return x.NonCriticalField + } + return "" +} + +type isTestVersion3_Sum interface { + isTestVersion3_Sum() +} + +type TestVersion3_E struct { + E int32 `protobuf:"varint,6,opt,name=e,proto3,oneof"` +} + +type TestVersion3_F struct { + F *TestVersion3 `protobuf:"bytes,7,opt,name=f,proto3,oneof"` +} + +func (*TestVersion3_E) isTestVersion3_Sum() {} + +func (*TestVersion3_F) isTestVersion3_Sum() {} + +type TestVersion3LoneOneOfValue struct { + state protoimpl.MessageState + sizeCache protoimpl.SizeCache + unknownFields protoimpl.UnknownFields + + X int64 `protobuf:"varint,1,opt,name=x,proto3" json:"x,omitempty"` + A *TestVersion3 `protobuf:"bytes,2,opt,name=a,proto3" json:"a,omitempty"` + B *TestVersion3 `protobuf:"bytes,3,opt,name=b,proto3" json:"b,omitempty"` // [(gogoproto.nullable) = false]; + C []*TestVersion3 `protobuf:"bytes,4,rep,name=c,proto3" json:"c,omitempty"` + D []*TestVersion3 `protobuf:"bytes,5,rep,name=d,proto3" json:"d,omitempty"` // [(gogoproto.nullable) = false]; + // Types that are assignable to Sum: + // + // *TestVersion3LoneOneOfValue_E + Sum isTestVersion3LoneOneOfValue_Sum `protobuf_oneof:"sum"` + G *anypb.Any `protobuf:"bytes,8,opt,name=g,proto3" json:"g,omitempty"` + H []*TestVersion1 `protobuf:"bytes,9,rep,name=h,proto3" json:"h,omitempty"` //[(gogoproto.castrepeated) = "TestVersion1"]; + // google.protobuf.Timestamp i = 10; + // google.protobuf.Timestamp j = 11; // [(gogoproto.stdtime) = true]; + K *Customer1 `protobuf:"bytes,12,opt,name=k,proto3" json:"k,omitempty"` + NonCriticalField string `protobuf:"bytes,1031,opt,name=non_critical_field,json=nonCriticalField,proto3" json:"non_critical_field,omitempty"` +} + +func (x *TestVersion3LoneOneOfValue) Reset() { + *x = TestVersion3LoneOneOfValue{} + if protoimpl.UnsafeEnabled { + mi := &file_unknownproto_proto_msgTypes[14] + ms := protoimpl.X.MessageStateOf(protoimpl.Pointer(x)) + ms.StoreMessageInfo(mi) + } +} + +func (x *TestVersion3LoneOneOfValue) String() string { + return protoimpl.X.MessageStringOf(x) +} + +func (*TestVersion3LoneOneOfValue) ProtoMessage() {} + +// Deprecated: Use TestVersion3LoneOneOfValue.ProtoReflect.Descriptor instead. +func (*TestVersion3LoneOneOfValue) Descriptor() ([]byte, []int) { + return file_unknownproto_proto_rawDescGZIP(), []int{14} +} + +func (x *TestVersion3LoneOneOfValue) GetX() int64 { + if x != nil { + return x.X + } + return 0 +} + +func (x *TestVersion3LoneOneOfValue) GetA() *TestVersion3 { + if x != nil { + return x.A + } + return nil +} + +func (x *TestVersion3LoneOneOfValue) GetB() *TestVersion3 { + if x != nil { + return x.B + } + return nil +} + +func (x *TestVersion3LoneOneOfValue) GetC() []*TestVersion3 { + if x != nil { + return x.C + } + return nil +} + +func (x *TestVersion3LoneOneOfValue) GetD() []*TestVersion3 { + if x != nil { + return x.D + } + return nil +} + +func (x *TestVersion3LoneOneOfValue) GetSum() isTestVersion3LoneOneOfValue_Sum { + if x != nil { + return x.Sum + } + return nil +} + +func (x *TestVersion3LoneOneOfValue) GetE() int32 { + if x, ok := x.GetSum().(*TestVersion3LoneOneOfValue_E); ok { + return x.E + } + return 0 +} + +func (x *TestVersion3LoneOneOfValue) GetG() *anypb.Any { + if x != nil { + return x.G + } + return nil +} + +func (x *TestVersion3LoneOneOfValue) GetH() []*TestVersion1 { + if x != nil { + return x.H + } + return nil +} + +func (x *TestVersion3LoneOneOfValue) GetK() *Customer1 { + if x != nil { + return x.K + } + return nil +} + +func (x *TestVersion3LoneOneOfValue) GetNonCriticalField() string { + if x != nil { + return x.NonCriticalField + } + return "" +} + +type isTestVersion3LoneOneOfValue_Sum interface { + isTestVersion3LoneOneOfValue_Sum() +} + +type TestVersion3LoneOneOfValue_E struct { + E int32 `protobuf:"varint,6,opt,name=e,proto3,oneof"` +} + +func (*TestVersion3LoneOneOfValue_E) isTestVersion3LoneOneOfValue_Sum() {} + +type TestVersion3LoneNesting struct { + state protoimpl.MessageState + sizeCache protoimpl.SizeCache + unknownFields protoimpl.UnknownFields + + X int64 `protobuf:"varint,1,opt,name=x,proto3" json:"x,omitempty"` + A *TestVersion3 `protobuf:"bytes,2,opt,name=a,proto3" json:"a,omitempty"` + B *TestVersion3 `protobuf:"bytes,3,opt,name=b,proto3" json:"b,omitempty"` // [(gogoproto.nullable) = false]; + C []*TestVersion3 `protobuf:"bytes,4,rep,name=c,proto3" json:"c,omitempty"` + D []*TestVersion3 `protobuf:"bytes,5,rep,name=d,proto3" json:"d,omitempty"` // [(gogoproto.nullable) = false]; + // Types that are assignable to Sum: + // + // *TestVersion3LoneNesting_F + Sum isTestVersion3LoneNesting_Sum `protobuf_oneof:"sum"` + G *anypb.Any `protobuf:"bytes,8,opt,name=g,proto3" json:"g,omitempty"` + H []*TestVersion1 `protobuf:"bytes,9,rep,name=h,proto3" json:"h,omitempty"` //[(gogoproto.castrepeated) = "TestVersion1"]; + // google.protobuf.Timestamp i = 10; + // google.protobuf.Timestamp j = 11; // [(gogoproto.stdtime) = true]; + K *Customer1 `protobuf:"bytes,12,opt,name=k,proto3" json:"k,omitempty"` + NonCriticalField string `protobuf:"bytes,1031,opt,name=non_critical_field,json=nonCriticalField,proto3" json:"non_critical_field,omitempty"` + Inner1 *TestVersion3LoneNesting_Inner1 `protobuf:"bytes,14,opt,name=inner1,proto3" json:"inner1,omitempty"` + Inner2 *TestVersion3LoneNesting_Inner2 `protobuf:"bytes,15,opt,name=inner2,proto3" json:"inner2,omitempty"` +} + +func (x *TestVersion3LoneNesting) Reset() { + *x = TestVersion3LoneNesting{} + if protoimpl.UnsafeEnabled { + mi := &file_unknownproto_proto_msgTypes[15] + ms := protoimpl.X.MessageStateOf(protoimpl.Pointer(x)) + ms.StoreMessageInfo(mi) + } +} + +func (x *TestVersion3LoneNesting) String() string { + return protoimpl.X.MessageStringOf(x) +} + +func (*TestVersion3LoneNesting) ProtoMessage() {} + +// Deprecated: Use TestVersion3LoneNesting.ProtoReflect.Descriptor instead. +func (*TestVersion3LoneNesting) Descriptor() ([]byte, []int) { + return file_unknownproto_proto_rawDescGZIP(), []int{15} +} + +func (x *TestVersion3LoneNesting) GetX() int64 { + if x != nil { + return x.X + } + return 0 +} + +func (x *TestVersion3LoneNesting) GetA() *TestVersion3 { + if x != nil { + return x.A + } + return nil +} + +func (x *TestVersion3LoneNesting) GetB() *TestVersion3 { + if x != nil { + return x.B + } + return nil +} + +func (x *TestVersion3LoneNesting) GetC() []*TestVersion3 { + if x != nil { + return x.C + } + return nil +} + +func (x *TestVersion3LoneNesting) GetD() []*TestVersion3 { + if x != nil { + return x.D + } + return nil +} + +func (x *TestVersion3LoneNesting) GetSum() isTestVersion3LoneNesting_Sum { + if x != nil { + return x.Sum + } + return nil +} + +func (x *TestVersion3LoneNesting) GetF() *TestVersion3LoneNesting { + if x, ok := x.GetSum().(*TestVersion3LoneNesting_F); ok { + return x.F + } + return nil +} + +func (x *TestVersion3LoneNesting) GetG() *anypb.Any { + if x != nil { + return x.G + } + return nil +} + +func (x *TestVersion3LoneNesting) GetH() []*TestVersion1 { + if x != nil { + return x.H + } + return nil +} + +func (x *TestVersion3LoneNesting) GetK() *Customer1 { + if x != nil { + return x.K + } + return nil +} + +func (x *TestVersion3LoneNesting) GetNonCriticalField() string { + if x != nil { + return x.NonCriticalField + } + return "" +} + +func (x *TestVersion3LoneNesting) GetInner1() *TestVersion3LoneNesting_Inner1 { + if x != nil { + return x.Inner1 + } + return nil +} + +func (x *TestVersion3LoneNesting) GetInner2() *TestVersion3LoneNesting_Inner2 { + if x != nil { + return x.Inner2 + } + return nil +} + +type isTestVersion3LoneNesting_Sum interface { + isTestVersion3LoneNesting_Sum() +} + +type TestVersion3LoneNesting_F struct { + F *TestVersion3LoneNesting `protobuf:"bytes,7,opt,name=f,proto3,oneof"` +} + +func (*TestVersion3LoneNesting_F) isTestVersion3LoneNesting_Sum() {} + +type TestVersion4LoneNesting struct { + state protoimpl.MessageState + sizeCache protoimpl.SizeCache + unknownFields protoimpl.UnknownFields + + X int64 `protobuf:"varint,1,opt,name=x,proto3" json:"x,omitempty"` + A *TestVersion3 `protobuf:"bytes,2,opt,name=a,proto3" json:"a,omitempty"` + B *TestVersion3 `protobuf:"bytes,3,opt,name=b,proto3" json:"b,omitempty"` // [(gogoproto.nullable) = false]; + C []*TestVersion3 `protobuf:"bytes,4,rep,name=c,proto3" json:"c,omitempty"` + D []*TestVersion3 `protobuf:"bytes,5,rep,name=d,proto3" json:"d,omitempty"` // [(gogoproto.nullable) = false]; + // Types that are assignable to Sum: + // + // *TestVersion4LoneNesting_F + Sum isTestVersion4LoneNesting_Sum `protobuf_oneof:"sum"` + G *anypb.Any `protobuf:"bytes,8,opt,name=g,proto3" json:"g,omitempty"` + H []*TestVersion1 `protobuf:"bytes,9,rep,name=h,proto3" json:"h,omitempty"` //[(gogoproto.castrepeated) = "TestVersion1"]; + // google.protobuf.Timestamp i = 10; + // google.protobuf.Timestamp j = 11; // [(gogoproto.stdtime) = true]; + K *Customer1 `protobuf:"bytes,12,opt,name=k,proto3" json:"k,omitempty"` + NonCriticalField string `protobuf:"bytes,1031,opt,name=non_critical_field,json=nonCriticalField,proto3" json:"non_critical_field,omitempty"` + Inner1 *TestVersion4LoneNesting_Inner1 `protobuf:"bytes,14,opt,name=inner1,proto3" json:"inner1,omitempty"` + Inner2 *TestVersion4LoneNesting_Inner2 `protobuf:"bytes,15,opt,name=inner2,proto3" json:"inner2,omitempty"` +} + +func (x *TestVersion4LoneNesting) Reset() { + *x = TestVersion4LoneNesting{} + if protoimpl.UnsafeEnabled { + mi := &file_unknownproto_proto_msgTypes[16] + ms := protoimpl.X.MessageStateOf(protoimpl.Pointer(x)) + ms.StoreMessageInfo(mi) + } +} + +func (x *TestVersion4LoneNesting) String() string { + return protoimpl.X.MessageStringOf(x) +} + +func (*TestVersion4LoneNesting) ProtoMessage() {} + +// Deprecated: Use TestVersion4LoneNesting.ProtoReflect.Descriptor instead. +func (*TestVersion4LoneNesting) Descriptor() ([]byte, []int) { + return file_unknownproto_proto_rawDescGZIP(), []int{16} +} + +func (x *TestVersion4LoneNesting) GetX() int64 { + if x != nil { + return x.X + } + return 0 +} + +func (x *TestVersion4LoneNesting) GetA() *TestVersion3 { + if x != nil { + return x.A + } + return nil +} + +func (x *TestVersion4LoneNesting) GetB() *TestVersion3 { + if x != nil { + return x.B + } + return nil +} + +func (x *TestVersion4LoneNesting) GetC() []*TestVersion3 { + if x != nil { + return x.C + } + return nil +} + +func (x *TestVersion4LoneNesting) GetD() []*TestVersion3 { + if x != nil { + return x.D + } + return nil +} + +func (x *TestVersion4LoneNesting) GetSum() isTestVersion4LoneNesting_Sum { + if x != nil { + return x.Sum + } + return nil +} + +func (x *TestVersion4LoneNesting) GetF() *TestVersion3LoneNesting { + if x, ok := x.GetSum().(*TestVersion4LoneNesting_F); ok { + return x.F + } + return nil +} + +func (x *TestVersion4LoneNesting) GetG() *anypb.Any { + if x != nil { + return x.G + } + return nil +} + +func (x *TestVersion4LoneNesting) GetH() []*TestVersion1 { + if x != nil { + return x.H + } + return nil +} + +func (x *TestVersion4LoneNesting) GetK() *Customer1 { + if x != nil { + return x.K + } + return nil +} + +func (x *TestVersion4LoneNesting) GetNonCriticalField() string { + if x != nil { + return x.NonCriticalField + } + return "" +} + +func (x *TestVersion4LoneNesting) GetInner1() *TestVersion4LoneNesting_Inner1 { + if x != nil { + return x.Inner1 + } + return nil +} + +func (x *TestVersion4LoneNesting) GetInner2() *TestVersion4LoneNesting_Inner2 { + if x != nil { + return x.Inner2 + } + return nil +} + +type isTestVersion4LoneNesting_Sum interface { + isTestVersion4LoneNesting_Sum() +} + +type TestVersion4LoneNesting_F struct { + F *TestVersion3LoneNesting `protobuf:"bytes,7,opt,name=f,proto3,oneof"` +} + +func (*TestVersion4LoneNesting_F) isTestVersion4LoneNesting_Sum() {} + +type TestVersionFD1 struct { + state protoimpl.MessageState + sizeCache protoimpl.SizeCache + unknownFields protoimpl.UnknownFields + + X int64 `protobuf:"varint,1,opt,name=x,proto3" json:"x,omitempty"` + A *TestVersion1 `protobuf:"bytes,2,opt,name=a,proto3" json:"a,omitempty"` + // Types that are assignable to Sum: + // + // *TestVersionFD1_E + // *TestVersionFD1_F + Sum isTestVersionFD1_Sum `protobuf_oneof:"sum"` + G *anypb.Any `protobuf:"bytes,8,opt,name=g,proto3" json:"g,omitempty"` + H []*TestVersion1 `protobuf:"bytes,9,rep,name=h,proto3" json:"h,omitempty"` // [(gogoproto.castrepeated) = "TestVersion1"]; +} + +func (x *TestVersionFD1) Reset() { + *x = TestVersionFD1{} + if protoimpl.UnsafeEnabled { + mi := &file_unknownproto_proto_msgTypes[17] + ms := protoimpl.X.MessageStateOf(protoimpl.Pointer(x)) + ms.StoreMessageInfo(mi) + } +} + +func (x *TestVersionFD1) String() string { + return protoimpl.X.MessageStringOf(x) +} + +func (*TestVersionFD1) ProtoMessage() {} + +// Deprecated: Use TestVersionFD1.ProtoReflect.Descriptor instead. +func (*TestVersionFD1) Descriptor() ([]byte, []int) { + return file_unknownproto_proto_rawDescGZIP(), []int{17} +} + +func (x *TestVersionFD1) GetX() int64 { + if x != nil { + return x.X + } + return 0 +} + +func (x *TestVersionFD1) GetA() *TestVersion1 { + if x != nil { + return x.A + } + return nil +} + +func (x *TestVersionFD1) GetSum() isTestVersionFD1_Sum { + if x != nil { + return x.Sum + } + return nil +} + +func (x *TestVersionFD1) GetE() int32 { + if x, ok := x.GetSum().(*TestVersionFD1_E); ok { + return x.E + } + return 0 +} + +func (x *TestVersionFD1) GetF() *TestVersion1 { + if x, ok := x.GetSum().(*TestVersionFD1_F); ok { + return x.F + } + return nil +} + +func (x *TestVersionFD1) GetG() *anypb.Any { + if x != nil { + return x.G + } + return nil +} + +func (x *TestVersionFD1) GetH() []*TestVersion1 { + if x != nil { + return x.H + } + return nil +} + +type isTestVersionFD1_Sum interface { + isTestVersionFD1_Sum() +} + +type TestVersionFD1_E struct { + E int32 `protobuf:"varint,6,opt,name=e,proto3,oneof"` +} + +type TestVersionFD1_F struct { + F *TestVersion1 `protobuf:"bytes,7,opt,name=f,proto3,oneof"` +} + +func (*TestVersionFD1_E) isTestVersionFD1_Sum() {} + +func (*TestVersionFD1_F) isTestVersionFD1_Sum() {} + +type TestVersionFD1WithExtraAny struct { + state protoimpl.MessageState + sizeCache protoimpl.SizeCache + unknownFields protoimpl.UnknownFields + + X int64 `protobuf:"varint,1,opt,name=x,proto3" json:"x,omitempty"` + A *TestVersion1 `protobuf:"bytes,2,opt,name=a,proto3" json:"a,omitempty"` + // Types that are assignable to Sum: + // + // *TestVersionFD1WithExtraAny_E + // *TestVersionFD1WithExtraAny_F + Sum isTestVersionFD1WithExtraAny_Sum `protobuf_oneof:"sum"` + G *AnyWithExtra `protobuf:"bytes,8,opt,name=g,proto3" json:"g,omitempty"` + H []*TestVersion1 `protobuf:"bytes,9,rep,name=h,proto3" json:"h,omitempty"` // [(gogoproto.castrepeated) = "TestVersion1"]; +} + +func (x *TestVersionFD1WithExtraAny) Reset() { + *x = TestVersionFD1WithExtraAny{} + if protoimpl.UnsafeEnabled { + mi := &file_unknownproto_proto_msgTypes[18] + ms := protoimpl.X.MessageStateOf(protoimpl.Pointer(x)) + ms.StoreMessageInfo(mi) + } +} + +func (x *TestVersionFD1WithExtraAny) String() string { + return protoimpl.X.MessageStringOf(x) +} + +func (*TestVersionFD1WithExtraAny) ProtoMessage() {} + +// Deprecated: Use TestVersionFD1WithExtraAny.ProtoReflect.Descriptor instead. +func (*TestVersionFD1WithExtraAny) Descriptor() ([]byte, []int) { + return file_unknownproto_proto_rawDescGZIP(), []int{18} +} + +func (x *TestVersionFD1WithExtraAny) GetX() int64 { + if x != nil { + return x.X + } + return 0 +} + +func (x *TestVersionFD1WithExtraAny) GetA() *TestVersion1 { + if x != nil { + return x.A + } + return nil +} + +func (x *TestVersionFD1WithExtraAny) GetSum() isTestVersionFD1WithExtraAny_Sum { + if x != nil { + return x.Sum + } + return nil +} + +func (x *TestVersionFD1WithExtraAny) GetE() int32 { + if x, ok := x.GetSum().(*TestVersionFD1WithExtraAny_E); ok { + return x.E + } + return 0 +} + +func (x *TestVersionFD1WithExtraAny) GetF() *TestVersion1 { + if x, ok := x.GetSum().(*TestVersionFD1WithExtraAny_F); ok { + return x.F + } + return nil +} + +func (x *TestVersionFD1WithExtraAny) GetG() *AnyWithExtra { + if x != nil { + return x.G + } + return nil +} + +func (x *TestVersionFD1WithExtraAny) GetH() []*TestVersion1 { + if x != nil { + return x.H + } + return nil +} + +type isTestVersionFD1WithExtraAny_Sum interface { + isTestVersionFD1WithExtraAny_Sum() +} + +type TestVersionFD1WithExtraAny_E struct { + E int32 `protobuf:"varint,6,opt,name=e,proto3,oneof"` +} + +type TestVersionFD1WithExtraAny_F struct { + F *TestVersion1 `protobuf:"bytes,7,opt,name=f,proto3,oneof"` +} + +func (*TestVersionFD1WithExtraAny_E) isTestVersionFD1WithExtraAny_Sum() {} + +func (*TestVersionFD1WithExtraAny_F) isTestVersionFD1WithExtraAny_Sum() {} + +type AnyWithExtra struct { + state protoimpl.MessageState + sizeCache protoimpl.SizeCache + unknownFields protoimpl.UnknownFields + + A *anypb.Any `protobuf:"bytes,1,opt,name=a,proto3" json:"a,omitempty"` + B int64 `protobuf:"varint,3,opt,name=b,proto3" json:"b,omitempty"` + C int64 `protobuf:"varint,4,opt,name=c,proto3" json:"c,omitempty"` +} + +func (x *AnyWithExtra) Reset() { + *x = AnyWithExtra{} + if protoimpl.UnsafeEnabled { + mi := &file_unknownproto_proto_msgTypes[19] + ms := protoimpl.X.MessageStateOf(protoimpl.Pointer(x)) + ms.StoreMessageInfo(mi) + } +} + +func (x *AnyWithExtra) String() string { + return protoimpl.X.MessageStringOf(x) +} + +func (*AnyWithExtra) ProtoMessage() {} + +// Deprecated: Use AnyWithExtra.ProtoReflect.Descriptor instead. +func (*AnyWithExtra) Descriptor() ([]byte, []int) { + return file_unknownproto_proto_rawDescGZIP(), []int{19} +} + +func (x *AnyWithExtra) GetA() *anypb.Any { + if x != nil { + return x.A + } + return nil +} + +func (x *AnyWithExtra) GetB() int64 { + if x != nil { + return x.B + } + return 0 +} + +func (x *AnyWithExtra) GetC() int64 { + if x != nil { + return x.C + } + return 0 +} + +type TestUpdatedTxRaw struct { + state protoimpl.MessageState + sizeCache protoimpl.SizeCache + unknownFields protoimpl.UnknownFields + + BodyBytes []byte `protobuf:"bytes,1,opt,name=body_bytes,json=bodyBytes,proto3" json:"body_bytes,omitempty"` + AuthInfoBytes []byte `protobuf:"bytes,2,opt,name=auth_info_bytes,json=authInfoBytes,proto3" json:"auth_info_bytes,omitempty"` + Signatures [][]byte `protobuf:"bytes,3,rep,name=signatures,proto3" json:"signatures,omitempty"` + NewField_5 []byte `protobuf:"bytes,5,opt,name=new_field_5,json=newField5,proto3" json:"new_field_5,omitempty"` + NewField_1024 []byte `protobuf:"bytes,1024,opt,name=new_field_1024,json=newField1024,proto3" json:"new_field_1024,omitempty"` +} + +func (x *TestUpdatedTxRaw) Reset() { + *x = TestUpdatedTxRaw{} + if protoimpl.UnsafeEnabled { + mi := &file_unknownproto_proto_msgTypes[20] + ms := protoimpl.X.MessageStateOf(protoimpl.Pointer(x)) + ms.StoreMessageInfo(mi) + } +} + +func (x *TestUpdatedTxRaw) String() string { + return protoimpl.X.MessageStringOf(x) +} + +func (*TestUpdatedTxRaw) ProtoMessage() {} + +// Deprecated: Use TestUpdatedTxRaw.ProtoReflect.Descriptor instead. +func (*TestUpdatedTxRaw) Descriptor() ([]byte, []int) { + return file_unknownproto_proto_rawDescGZIP(), []int{20} +} + +func (x *TestUpdatedTxRaw) GetBodyBytes() []byte { + if x != nil { + return x.BodyBytes + } + return nil +} + +func (x *TestUpdatedTxRaw) GetAuthInfoBytes() []byte { + if x != nil { + return x.AuthInfoBytes + } + return nil +} + +func (x *TestUpdatedTxRaw) GetSignatures() [][]byte { + if x != nil { + return x.Signatures + } + return nil +} + +func (x *TestUpdatedTxRaw) GetNewField_5() []byte { + if x != nil { + return x.NewField_5 + } + return nil +} + +func (x *TestUpdatedTxRaw) GetNewField_1024() []byte { + if x != nil { + return x.NewField_1024 + } + return nil +} + +type TestUpdatedTxBody struct { + state protoimpl.MessageState + sizeCache protoimpl.SizeCache + unknownFields protoimpl.UnknownFields + + Messages []*anypb.Any `protobuf:"bytes,1,rep,name=messages,proto3" json:"messages,omitempty"` + Memo string `protobuf:"bytes,2,opt,name=memo,proto3" json:"memo,omitempty"` + TimeoutHeight int64 `protobuf:"varint,3,opt,name=timeout_height,json=timeoutHeight,proto3" json:"timeout_height,omitempty"` + SomeNewField uint64 `protobuf:"varint,4,opt,name=some_new_field,json=someNewField,proto3" json:"some_new_field,omitempty"` + SomeNewFieldNonCriticalField string `protobuf:"bytes,1050,opt,name=some_new_field_non_critical_field,json=someNewFieldNonCriticalField,proto3" json:"some_new_field_non_critical_field,omitempty"` + ExtensionOptions []*anypb.Any `protobuf:"bytes,1023,rep,name=extension_options,json=extensionOptions,proto3" json:"extension_options,omitempty"` + NonCriticalExtensionOptions []*anypb.Any `protobuf:"bytes,2047,rep,name=non_critical_extension_options,json=nonCriticalExtensionOptions,proto3" json:"non_critical_extension_options,omitempty"` +} + +func (x *TestUpdatedTxBody) Reset() { + *x = TestUpdatedTxBody{} + if protoimpl.UnsafeEnabled { + mi := &file_unknownproto_proto_msgTypes[21] + ms := protoimpl.X.MessageStateOf(protoimpl.Pointer(x)) + ms.StoreMessageInfo(mi) + } +} + +func (x *TestUpdatedTxBody) String() string { + return protoimpl.X.MessageStringOf(x) +} + +func (*TestUpdatedTxBody) ProtoMessage() {} + +// Deprecated: Use TestUpdatedTxBody.ProtoReflect.Descriptor instead. +func (*TestUpdatedTxBody) Descriptor() ([]byte, []int) { + return file_unknownproto_proto_rawDescGZIP(), []int{21} +} + +func (x *TestUpdatedTxBody) GetMessages() []*anypb.Any { + if x != nil { + return x.Messages + } + return nil +} + +func (x *TestUpdatedTxBody) GetMemo() string { + if x != nil { + return x.Memo + } + return "" +} + +func (x *TestUpdatedTxBody) GetTimeoutHeight() int64 { + if x != nil { + return x.TimeoutHeight + } + return 0 +} + +func (x *TestUpdatedTxBody) GetSomeNewField() uint64 { + if x != nil { + return x.SomeNewField + } + return 0 +} + +func (x *TestUpdatedTxBody) GetSomeNewFieldNonCriticalField() string { + if x != nil { + return x.SomeNewFieldNonCriticalField + } + return "" +} + +func (x *TestUpdatedTxBody) GetExtensionOptions() []*anypb.Any { + if x != nil { + return x.ExtensionOptions + } + return nil +} + +func (x *TestUpdatedTxBody) GetNonCriticalExtensionOptions() []*anypb.Any { + if x != nil { + return x.NonCriticalExtensionOptions + } + return nil +} + +type TestUpdatedAuthInfo struct { + state protoimpl.MessageState + sizeCache protoimpl.SizeCache + unknownFields protoimpl.UnknownFields + + SignerInfos []*v1beta1.SignerInfo `protobuf:"bytes,1,rep,name=signer_infos,json=signerInfos,proto3" json:"signer_infos,omitempty"` + Fee *v1beta1.Fee `protobuf:"bytes,2,opt,name=fee,proto3" json:"fee,omitempty"` + NewField_3 []byte `protobuf:"bytes,3,opt,name=new_field_3,json=newField3,proto3" json:"new_field_3,omitempty"` + NewField_1024 []byte `protobuf:"bytes,1024,opt,name=new_field_1024,json=newField1024,proto3" json:"new_field_1024,omitempty"` +} + +func (x *TestUpdatedAuthInfo) Reset() { + *x = TestUpdatedAuthInfo{} + if protoimpl.UnsafeEnabled { + mi := &file_unknownproto_proto_msgTypes[22] + ms := protoimpl.X.MessageStateOf(protoimpl.Pointer(x)) + ms.StoreMessageInfo(mi) + } +} + +func (x *TestUpdatedAuthInfo) String() string { + return protoimpl.X.MessageStringOf(x) +} + +func (*TestUpdatedAuthInfo) ProtoMessage() {} + +// Deprecated: Use TestUpdatedAuthInfo.ProtoReflect.Descriptor instead. +func (*TestUpdatedAuthInfo) Descriptor() ([]byte, []int) { + return file_unknownproto_proto_rawDescGZIP(), []int{22} +} + +func (x *TestUpdatedAuthInfo) GetSignerInfos() []*v1beta1.SignerInfo { + if x != nil { + return x.SignerInfos + } + return nil +} + +func (x *TestUpdatedAuthInfo) GetFee() *v1beta1.Fee { + if x != nil { + return x.Fee + } + return nil +} + +func (x *TestUpdatedAuthInfo) GetNewField_3() []byte { + if x != nil { + return x.NewField_3 + } + return nil +} + +func (x *TestUpdatedAuthInfo) GetNewField_1024() []byte { + if x != nil { + return x.NewField_1024 + } + return nil +} + +type TestRepeatedUints struct { + state protoimpl.MessageState + sizeCache protoimpl.SizeCache + unknownFields protoimpl.UnknownFields + + Nums []uint64 `protobuf:"varint,1,rep,packed,name=nums,proto3" json:"nums,omitempty"` +} + +func (x *TestRepeatedUints) Reset() { + *x = TestRepeatedUints{} + if protoimpl.UnsafeEnabled { + mi := &file_unknownproto_proto_msgTypes[23] + ms := protoimpl.X.MessageStateOf(protoimpl.Pointer(x)) + ms.StoreMessageInfo(mi) + } +} + +func (x *TestRepeatedUints) String() string { + return protoimpl.X.MessageStringOf(x) +} + +func (*TestRepeatedUints) ProtoMessage() {} + +// Deprecated: Use TestRepeatedUints.ProtoReflect.Descriptor instead. +func (*TestRepeatedUints) Descriptor() ([]byte, []int) { + return file_unknownproto_proto_rawDescGZIP(), []int{23} +} + +func (x *TestRepeatedUints) GetNums() []uint64 { + if x != nil { + return x.Nums + } + return nil +} + +type TestVersion3LoneNesting_Inner1 struct { + state protoimpl.MessageState + sizeCache protoimpl.SizeCache + unknownFields protoimpl.UnknownFields + + Id int64 `protobuf:"varint,1,opt,name=id,proto3" json:"id,omitempty"` + Name string `protobuf:"bytes,2,opt,name=name,proto3" json:"name,omitempty"` + Inner *TestVersion3LoneNesting_Inner1_InnerInner `protobuf:"bytes,3,opt,name=inner,proto3" json:"inner,omitempty"` +} + +func (x *TestVersion3LoneNesting_Inner1) Reset() { + *x = TestVersion3LoneNesting_Inner1{} + if protoimpl.UnsafeEnabled { + mi := &file_unknownproto_proto_msgTypes[25] + ms := protoimpl.X.MessageStateOf(protoimpl.Pointer(x)) + ms.StoreMessageInfo(mi) + } +} + +func (x *TestVersion3LoneNesting_Inner1) String() string { + return protoimpl.X.MessageStringOf(x) +} + +func (*TestVersion3LoneNesting_Inner1) ProtoMessage() {} + +// Deprecated: Use TestVersion3LoneNesting_Inner1.ProtoReflect.Descriptor instead. +func (*TestVersion3LoneNesting_Inner1) Descriptor() ([]byte, []int) { + return file_unknownproto_proto_rawDescGZIP(), []int{15, 0} +} + +func (x *TestVersion3LoneNesting_Inner1) GetId() int64 { + if x != nil { + return x.Id + } + return 0 +} + +func (x *TestVersion3LoneNesting_Inner1) GetName() string { + if x != nil { + return x.Name + } + return "" +} + +func (x *TestVersion3LoneNesting_Inner1) GetInner() *TestVersion3LoneNesting_Inner1_InnerInner { + if x != nil { + return x.Inner + } + return nil +} + +type TestVersion3LoneNesting_Inner2 struct { + state protoimpl.MessageState + sizeCache protoimpl.SizeCache + unknownFields protoimpl.UnknownFields + + Id string `protobuf:"bytes,1,opt,name=id,proto3" json:"id,omitempty"` + Country string `protobuf:"bytes,2,opt,name=country,proto3" json:"country,omitempty"` + Inner *TestVersion3LoneNesting_Inner2_InnerInner `protobuf:"bytes,3,opt,name=inner,proto3" json:"inner,omitempty"` +} + +func (x *TestVersion3LoneNesting_Inner2) Reset() { + *x = TestVersion3LoneNesting_Inner2{} + if protoimpl.UnsafeEnabled { + mi := &file_unknownproto_proto_msgTypes[26] + ms := protoimpl.X.MessageStateOf(protoimpl.Pointer(x)) + ms.StoreMessageInfo(mi) + } +} + +func (x *TestVersion3LoneNesting_Inner2) String() string { + return protoimpl.X.MessageStringOf(x) +} + +func (*TestVersion3LoneNesting_Inner2) ProtoMessage() {} + +// Deprecated: Use TestVersion3LoneNesting_Inner2.ProtoReflect.Descriptor instead. +func (*TestVersion3LoneNesting_Inner2) Descriptor() ([]byte, []int) { + return file_unknownproto_proto_rawDescGZIP(), []int{15, 1} +} + +func (x *TestVersion3LoneNesting_Inner2) GetId() string { + if x != nil { + return x.Id + } + return "" +} + +func (x *TestVersion3LoneNesting_Inner2) GetCountry() string { + if x != nil { + return x.Country + } + return "" +} + +func (x *TestVersion3LoneNesting_Inner2) GetInner() *TestVersion3LoneNesting_Inner2_InnerInner { + if x != nil { + return x.Inner + } + return nil +} + +type TestVersion3LoneNesting_Inner1_InnerInner struct { + state protoimpl.MessageState + sizeCache protoimpl.SizeCache + unknownFields protoimpl.UnknownFields + + Id string `protobuf:"bytes,1,opt,name=id,proto3" json:"id,omitempty"` + City string `protobuf:"bytes,2,opt,name=city,proto3" json:"city,omitempty"` +} + +func (x *TestVersion3LoneNesting_Inner1_InnerInner) Reset() { + *x = TestVersion3LoneNesting_Inner1_InnerInner{} + if protoimpl.UnsafeEnabled { + mi := &file_unknownproto_proto_msgTypes[27] + ms := protoimpl.X.MessageStateOf(protoimpl.Pointer(x)) + ms.StoreMessageInfo(mi) + } +} + +func (x *TestVersion3LoneNesting_Inner1_InnerInner) String() string { + return protoimpl.X.MessageStringOf(x) +} + +func (*TestVersion3LoneNesting_Inner1_InnerInner) ProtoMessage() {} + +// Deprecated: Use TestVersion3LoneNesting_Inner1_InnerInner.ProtoReflect.Descriptor instead. +func (*TestVersion3LoneNesting_Inner1_InnerInner) Descriptor() ([]byte, []int) { + return file_unknownproto_proto_rawDescGZIP(), []int{15, 0, 0} +} + +func (x *TestVersion3LoneNesting_Inner1_InnerInner) GetId() string { + if x != nil { + return x.Id + } + return "" +} + +func (x *TestVersion3LoneNesting_Inner1_InnerInner) GetCity() string { + if x != nil { + return x.City + } + return "" +} + +type TestVersion3LoneNesting_Inner2_InnerInner struct { + state protoimpl.MessageState + sizeCache protoimpl.SizeCache + unknownFields protoimpl.UnknownFields + + Id string `protobuf:"bytes,1,opt,name=id,proto3" json:"id,omitempty"` + City string `protobuf:"bytes,2,opt,name=city,proto3" json:"city,omitempty"` +} + +func (x *TestVersion3LoneNesting_Inner2_InnerInner) Reset() { + *x = TestVersion3LoneNesting_Inner2_InnerInner{} + if protoimpl.UnsafeEnabled { + mi := &file_unknownproto_proto_msgTypes[28] + ms := protoimpl.X.MessageStateOf(protoimpl.Pointer(x)) + ms.StoreMessageInfo(mi) + } +} + +func (x *TestVersion3LoneNesting_Inner2_InnerInner) String() string { + return protoimpl.X.MessageStringOf(x) +} + +func (*TestVersion3LoneNesting_Inner2_InnerInner) ProtoMessage() {} + +// Deprecated: Use TestVersion3LoneNesting_Inner2_InnerInner.ProtoReflect.Descriptor instead. +func (*TestVersion3LoneNesting_Inner2_InnerInner) Descriptor() ([]byte, []int) { + return file_unknownproto_proto_rawDescGZIP(), []int{15, 1, 0} +} + +func (x *TestVersion3LoneNesting_Inner2_InnerInner) GetId() string { + if x != nil { + return x.Id + } + return "" +} + +func (x *TestVersion3LoneNesting_Inner2_InnerInner) GetCity() string { + if x != nil { + return x.City + } + return "" +} + +type TestVersion4LoneNesting_Inner1 struct { + state protoimpl.MessageState + sizeCache protoimpl.SizeCache + unknownFields protoimpl.UnknownFields + + Id int64 `protobuf:"varint,1,opt,name=id,proto3" json:"id,omitempty"` + Name string `protobuf:"bytes,2,opt,name=name,proto3" json:"name,omitempty"` + Inner *TestVersion4LoneNesting_Inner1_InnerInner `protobuf:"bytes,3,opt,name=inner,proto3" json:"inner,omitempty"` +} + +func (x *TestVersion4LoneNesting_Inner1) Reset() { + *x = TestVersion4LoneNesting_Inner1{} + if protoimpl.UnsafeEnabled { + mi := &file_unknownproto_proto_msgTypes[29] + ms := protoimpl.X.MessageStateOf(protoimpl.Pointer(x)) + ms.StoreMessageInfo(mi) + } +} + +func (x *TestVersion4LoneNesting_Inner1) String() string { + return protoimpl.X.MessageStringOf(x) +} + +func (*TestVersion4LoneNesting_Inner1) ProtoMessage() {} + +// Deprecated: Use TestVersion4LoneNesting_Inner1.ProtoReflect.Descriptor instead. +func (*TestVersion4LoneNesting_Inner1) Descriptor() ([]byte, []int) { + return file_unknownproto_proto_rawDescGZIP(), []int{16, 0} +} + +func (x *TestVersion4LoneNesting_Inner1) GetId() int64 { + if x != nil { + return x.Id + } + return 0 +} + +func (x *TestVersion4LoneNesting_Inner1) GetName() string { + if x != nil { + return x.Name + } + return "" +} + +func (x *TestVersion4LoneNesting_Inner1) GetInner() *TestVersion4LoneNesting_Inner1_InnerInner { + if x != nil { + return x.Inner + } + return nil +} + +type TestVersion4LoneNesting_Inner2 struct { + state protoimpl.MessageState + sizeCache protoimpl.SizeCache + unknownFields protoimpl.UnknownFields + + Id string `protobuf:"bytes,1,opt,name=id,proto3" json:"id,omitempty"` + Country string `protobuf:"bytes,2,opt,name=country,proto3" json:"country,omitempty"` + Inner *TestVersion4LoneNesting_Inner2_InnerInner `protobuf:"bytes,3,opt,name=inner,proto3" json:"inner,omitempty"` +} + +func (x *TestVersion4LoneNesting_Inner2) Reset() { + *x = TestVersion4LoneNesting_Inner2{} + if protoimpl.UnsafeEnabled { + mi := &file_unknownproto_proto_msgTypes[30] + ms := protoimpl.X.MessageStateOf(protoimpl.Pointer(x)) + ms.StoreMessageInfo(mi) + } +} + +func (x *TestVersion4LoneNesting_Inner2) String() string { + return protoimpl.X.MessageStringOf(x) +} + +func (*TestVersion4LoneNesting_Inner2) ProtoMessage() {} + +// Deprecated: Use TestVersion4LoneNesting_Inner2.ProtoReflect.Descriptor instead. +func (*TestVersion4LoneNesting_Inner2) Descriptor() ([]byte, []int) { + return file_unknownproto_proto_rawDescGZIP(), []int{16, 1} +} + +func (x *TestVersion4LoneNesting_Inner2) GetId() string { + if x != nil { + return x.Id + } + return "" +} + +func (x *TestVersion4LoneNesting_Inner2) GetCountry() string { + if x != nil { + return x.Country + } + return "" +} + +func (x *TestVersion4LoneNesting_Inner2) GetInner() *TestVersion4LoneNesting_Inner2_InnerInner { + if x != nil { + return x.Inner + } + return nil +} + +type TestVersion4LoneNesting_Inner1_InnerInner struct { + state protoimpl.MessageState + sizeCache protoimpl.SizeCache + unknownFields protoimpl.UnknownFields + + Id int64 `protobuf:"varint,1,opt,name=id,proto3" json:"id,omitempty"` + City string `protobuf:"bytes,2,opt,name=city,proto3" json:"city,omitempty"` +} + +func (x *TestVersion4LoneNesting_Inner1_InnerInner) Reset() { + *x = TestVersion4LoneNesting_Inner1_InnerInner{} + if protoimpl.UnsafeEnabled { + mi := &file_unknownproto_proto_msgTypes[31] + ms := protoimpl.X.MessageStateOf(protoimpl.Pointer(x)) + ms.StoreMessageInfo(mi) + } +} + +func (x *TestVersion4LoneNesting_Inner1_InnerInner) String() string { + return protoimpl.X.MessageStringOf(x) +} + +func (*TestVersion4LoneNesting_Inner1_InnerInner) ProtoMessage() {} + +// Deprecated: Use TestVersion4LoneNesting_Inner1_InnerInner.ProtoReflect.Descriptor instead. +func (*TestVersion4LoneNesting_Inner1_InnerInner) Descriptor() ([]byte, []int) { + return file_unknownproto_proto_rawDescGZIP(), []int{16, 0, 0} +} + +func (x *TestVersion4LoneNesting_Inner1_InnerInner) GetId() int64 { + if x != nil { + return x.Id + } + return 0 +} + +func (x *TestVersion4LoneNesting_Inner1_InnerInner) GetCity() string { + if x != nil { + return x.City + } + return "" +} + +type TestVersion4LoneNesting_Inner2_InnerInner struct { + state protoimpl.MessageState + sizeCache protoimpl.SizeCache + unknownFields protoimpl.UnknownFields + + Id string `protobuf:"bytes,1,opt,name=id,proto3" json:"id,omitempty"` + Value int64 `protobuf:"varint,2,opt,name=value,proto3" json:"value,omitempty"` +} + +func (x *TestVersion4LoneNesting_Inner2_InnerInner) Reset() { + *x = TestVersion4LoneNesting_Inner2_InnerInner{} + if protoimpl.UnsafeEnabled { + mi := &file_unknownproto_proto_msgTypes[32] + ms := protoimpl.X.MessageStateOf(protoimpl.Pointer(x)) + ms.StoreMessageInfo(mi) + } +} + +func (x *TestVersion4LoneNesting_Inner2_InnerInner) String() string { + return protoimpl.X.MessageStringOf(x) +} + +func (*TestVersion4LoneNesting_Inner2_InnerInner) ProtoMessage() {} + +// Deprecated: Use TestVersion4LoneNesting_Inner2_InnerInner.ProtoReflect.Descriptor instead. +func (*TestVersion4LoneNesting_Inner2_InnerInner) Descriptor() ([]byte, []int) { + return file_unknownproto_proto_rawDescGZIP(), []int{16, 1, 0} +} + +func (x *TestVersion4LoneNesting_Inner2_InnerInner) GetId() string { + if x != nil { + return x.Id + } + return "" +} + +func (x *TestVersion4LoneNesting_Inner2_InnerInner) GetValue() int64 { + if x != nil { + return x.Value + } + return 0 +} + +var File_unknownproto_proto protoreflect.FileDescriptor + +var file_unknownproto_proto_rawDesc = []byte{ + 0x0a, 0x12, 0x75, 0x6e, 0x6b, 0x6e, 0x6f, 0x77, 0x6e, 0x70, 0x72, 0x6f, 0x74, 0x6f, 0x2e, 0x70, + 0x72, 0x6f, 0x74, 0x6f, 0x12, 0x06, 0x74, 0x65, 0x73, 0x74, 0x70, 0x62, 0x1a, 0x19, 0x67, 0x6f, + 0x6f, 0x67, 0x6c, 0x65, 0x2f, 0x70, 0x72, 0x6f, 0x74, 0x6f, 0x62, 0x75, 0x66, 0x2f, 0x61, 0x6e, + 0x79, 0x2e, 0x70, 0x72, 0x6f, 0x74, 0x6f, 0x1a, 0x1a, 0x63, 0x6f, 0x73, 0x6d, 0x6f, 0x73, 0x2f, + 0x74, 0x78, 0x2f, 0x76, 0x31, 0x62, 0x65, 0x74, 0x61, 0x31, 0x2f, 0x74, 0x78, 0x2e, 0x70, 0x72, + 0x6f, 0x74, 0x6f, 0x22, 0x74, 0x0a, 0x09, 0x43, 0x75, 0x73, 0x74, 0x6f, 0x6d, 0x65, 0x72, 0x31, + 0x12, 0x0e, 0x0a, 0x02, 0x69, 0x64, 0x18, 0x01, 0x20, 0x01, 0x28, 0x05, 0x52, 0x02, 0x69, 0x64, + 0x12, 0x12, 0x0a, 0x04, 0x6e, 0x61, 0x6d, 0x65, 0x18, 0x02, 0x20, 0x01, 0x28, 0x09, 0x52, 0x04, + 0x6e, 0x61, 0x6d, 0x65, 0x12, 0x29, 0x0a, 0x10, 0x73, 0x75, 0x62, 0x73, 0x63, 0x72, 0x69, 0x70, + 0x74, 0x69, 0x6f, 0x6e, 0x5f, 0x66, 0x65, 0x65, 0x18, 0x03, 0x20, 0x01, 0x28, 0x02, 0x52, 0x0f, + 0x73, 0x75, 0x62, 0x73, 0x63, 0x72, 0x69, 0x70, 0x74, 0x69, 0x6f, 0x6e, 0x46, 0x65, 0x65, 0x12, + 0x18, 0x0a, 0x07, 0x70, 0x61, 0x79, 0x6d, 0x65, 0x6e, 0x74, 0x18, 0x07, 0x20, 0x01, 0x28, 0x09, + 0x52, 0x07, 0x70, 0x61, 0x79, 0x6d, 0x65, 0x6e, 0x74, 0x22, 0xaf, 0x02, 0x0a, 0x09, 0x43, 0x75, + 0x73, 0x74, 0x6f, 0x6d, 0x65, 0x72, 0x32, 0x12, 0x0e, 0x0a, 0x02, 0x69, 0x64, 0x18, 0x01, 0x20, + 0x01, 0x28, 0x05, 0x52, 0x02, 0x69, 0x64, 0x12, 0x1a, 0x0a, 0x08, 0x69, 0x6e, 0x64, 0x75, 0x73, + 0x74, 0x72, 0x79, 0x18, 0x02, 0x20, 0x01, 0x28, 0x05, 0x52, 0x08, 0x69, 0x6e, 0x64, 0x75, 0x73, + 0x74, 0x72, 0x79, 0x12, 0x12, 0x0a, 0x04, 0x6e, 0x61, 0x6d, 0x65, 0x18, 0x03, 0x20, 0x01, 0x28, + 0x09, 0x52, 0x04, 0x6e, 0x61, 0x6d, 0x65, 0x12, 0x14, 0x0a, 0x05, 0x66, 0x65, 0x77, 0x65, 0x72, + 0x18, 0x04, 0x20, 0x01, 0x28, 0x02, 0x52, 0x05, 0x66, 0x65, 0x77, 0x65, 0x72, 0x12, 0x1b, 0x0a, + 0x08, 0x72, 0x65, 0x73, 0x65, 0x72, 0x76, 0x65, 0x64, 0x18, 0x97, 0x08, 0x20, 0x01, 0x28, 0x03, + 0x52, 0x08, 0x72, 0x65, 0x73, 0x65, 0x72, 0x76, 0x65, 0x64, 0x12, 0x2a, 0x0a, 0x04, 0x63, 0x69, + 0x74, 0x79, 0x18, 0x06, 0x20, 0x01, 0x28, 0x0e, 0x32, 0x16, 0x2e, 0x74, 0x65, 0x73, 0x74, 0x70, + 0x62, 0x2e, 0x43, 0x75, 0x73, 0x74, 0x6f, 0x6d, 0x65, 0x72, 0x32, 0x2e, 0x43, 0x69, 0x74, 0x79, + 0x52, 0x04, 0x63, 0x69, 0x74, 0x79, 0x12, 0x3a, 0x0a, 0x0d, 0x6d, 0x69, 0x73, 0x63, 0x65, 0x6c, + 0x6c, 0x61, 0x6e, 0x65, 0x6f, 0x75, 0x73, 0x18, 0x0a, 0x20, 0x01, 0x28, 0x0b, 0x32, 0x14, 0x2e, + 0x67, 0x6f, 0x6f, 0x67, 0x6c, 0x65, 0x2e, 0x70, 0x72, 0x6f, 0x74, 0x6f, 0x62, 0x75, 0x66, 0x2e, + 0x41, 0x6e, 0x79, 0x52, 0x0d, 0x6d, 0x69, 0x73, 0x63, 0x65, 0x6c, 0x6c, 0x61, 0x6e, 0x65, 0x6f, + 0x75, 0x73, 0x22, 0x47, 0x0a, 0x04, 0x43, 0x69, 0x74, 0x79, 0x12, 0x08, 0x0a, 0x04, 0x4c, 0x61, + 0x6f, 0x73, 0x10, 0x00, 0x12, 0x0e, 0x0a, 0x0a, 0x4c, 0x6f, 0x73, 0x41, 0x6e, 0x67, 0x65, 0x6c, + 0x65, 0x73, 0x10, 0x01, 0x12, 0x0c, 0x0a, 0x08, 0x50, 0x61, 0x6c, 0x6f, 0x41, 0x6c, 0x74, 0x6f, + 0x10, 0x02, 0x12, 0x0a, 0x0a, 0x06, 0x4d, 0x6f, 0x73, 0x63, 0x6f, 0x77, 0x10, 0x03, 0x12, 0x0b, + 0x0a, 0x07, 0x4e, 0x61, 0x69, 0x72, 0x6f, 0x62, 0x69, 0x10, 0x04, 0x22, 0x2e, 0x0a, 0x08, 0x4e, + 0x65, 0x73, 0x74, 0x65, 0x64, 0x34, 0x41, 0x12, 0x0e, 0x0a, 0x02, 0x69, 0x64, 0x18, 0x01, 0x20, + 0x01, 0x28, 0x05, 0x52, 0x02, 0x69, 0x64, 0x12, 0x12, 0x0a, 0x04, 0x6e, 0x61, 0x6d, 0x65, 0x18, + 0x02, 0x20, 0x01, 0x28, 0x09, 0x52, 0x04, 0x6e, 0x61, 0x6d, 0x65, 0x22, 0xcf, 0x01, 0x0a, 0x08, + 0x4e, 0x65, 0x73, 0x74, 0x65, 0x64, 0x33, 0x41, 0x12, 0x0e, 0x0a, 0x02, 0x69, 0x64, 0x18, 0x01, + 0x20, 0x01, 0x28, 0x05, 0x52, 0x02, 0x69, 0x64, 0x12, 0x12, 0x0a, 0x04, 0x6e, 0x61, 0x6d, 0x65, + 0x18, 0x02, 0x20, 0x01, 0x28, 0x09, 0x52, 0x04, 0x6e, 0x61, 0x6d, 0x65, 0x12, 0x20, 0x0a, 0x02, + 0x61, 0x34, 0x18, 0x04, 0x20, 0x03, 0x28, 0x0b, 0x32, 0x10, 0x2e, 0x74, 0x65, 0x73, 0x74, 0x70, + 0x62, 0x2e, 0x4e, 0x65, 0x73, 0x74, 0x65, 0x64, 0x34, 0x41, 0x52, 0x02, 0x61, 0x34, 0x12, 0x31, + 0x0a, 0x05, 0x69, 0x6e, 0x64, 0x65, 0x78, 0x18, 0x05, 0x20, 0x03, 0x28, 0x0b, 0x32, 0x1b, 0x2e, + 0x74, 0x65, 0x73, 0x74, 0x70, 0x62, 0x2e, 0x4e, 0x65, 0x73, 0x74, 0x65, 0x64, 0x33, 0x41, 0x2e, + 0x49, 0x6e, 0x64, 0x65, 0x78, 0x45, 0x6e, 0x74, 0x72, 0x79, 0x52, 0x05, 0x69, 0x6e, 0x64, 0x65, + 0x78, 0x1a, 0x4a, 0x0a, 0x0a, 0x49, 0x6e, 0x64, 0x65, 0x78, 0x45, 0x6e, 0x74, 0x72, 0x79, 0x12, + 0x10, 0x0a, 0x03, 0x6b, 0x65, 0x79, 0x18, 0x01, 0x20, 0x01, 0x28, 0x03, 0x52, 0x03, 0x6b, 0x65, + 0x79, 0x12, 0x26, 0x0a, 0x05, 0x76, 0x61, 0x6c, 0x75, 0x65, 0x18, 0x02, 0x20, 0x01, 0x28, 0x0b, + 0x32, 0x10, 0x2e, 0x74, 0x65, 0x73, 0x74, 0x70, 0x62, 0x2e, 0x4e, 0x65, 0x73, 0x74, 0x65, 0x64, + 0x34, 0x41, 0x52, 0x05, 0x76, 0x61, 0x6c, 0x75, 0x65, 0x3a, 0x02, 0x38, 0x01, 0x22, 0x58, 0x0a, + 0x08, 0x4e, 0x65, 0x73, 0x74, 0x65, 0x64, 0x32, 0x41, 0x12, 0x0e, 0x0a, 0x02, 0x69, 0x64, 0x18, + 0x01, 0x20, 0x01, 0x28, 0x05, 0x52, 0x02, 0x69, 0x64, 0x12, 0x12, 0x0a, 0x04, 0x6e, 0x61, 0x6d, + 0x65, 0x18, 0x02, 0x20, 0x01, 0x28, 0x09, 0x52, 0x04, 0x6e, 0x61, 0x6d, 0x65, 0x12, 0x28, 0x0a, + 0x06, 0x6e, 0x65, 0x73, 0x74, 0x65, 0x64, 0x18, 0x03, 0x20, 0x01, 0x28, 0x0b, 0x32, 0x10, 0x2e, + 0x74, 0x65, 0x73, 0x74, 0x70, 0x62, 0x2e, 0x4e, 0x65, 0x73, 0x74, 0x65, 0x64, 0x33, 0x41, 0x52, + 0x06, 0x6e, 0x65, 0x73, 0x74, 0x65, 0x64, 0x22, 0x44, 0x0a, 0x08, 0x4e, 0x65, 0x73, 0x74, 0x65, + 0x64, 0x31, 0x41, 0x12, 0x0e, 0x0a, 0x02, 0x69, 0x64, 0x18, 0x01, 0x20, 0x01, 0x28, 0x05, 0x52, + 0x02, 0x69, 0x64, 0x12, 0x28, 0x0a, 0x06, 0x6e, 0x65, 0x73, 0x74, 0x65, 0x64, 0x18, 0x02, 0x20, + 0x01, 0x28, 0x0b, 0x32, 0x10, 0x2e, 0x74, 0x65, 0x73, 0x74, 0x70, 0x62, 0x2e, 0x4e, 0x65, 0x73, + 0x74, 0x65, 0x64, 0x32, 0x41, 0x52, 0x06, 0x6e, 0x65, 0x73, 0x74, 0x65, 0x64, 0x22, 0x40, 0x0a, + 0x08, 0x4e, 0x65, 0x73, 0x74, 0x65, 0x64, 0x34, 0x42, 0x12, 0x0e, 0x0a, 0x02, 0x69, 0x64, 0x18, + 0x01, 0x20, 0x01, 0x28, 0x05, 0x52, 0x02, 0x69, 0x64, 0x12, 0x10, 0x0a, 0x03, 0x61, 0x67, 0x65, + 0x18, 0x02, 0x20, 0x01, 0x28, 0x05, 0x52, 0x03, 0x61, 0x67, 0x65, 0x12, 0x12, 0x0a, 0x04, 0x6e, + 0x61, 0x6d, 0x65, 0x18, 0x03, 0x20, 0x01, 0x28, 0x09, 0x52, 0x04, 0x6e, 0x61, 0x6d, 0x65, 0x22, + 0x62, 0x0a, 0x08, 0x4e, 0x65, 0x73, 0x74, 0x65, 0x64, 0x33, 0x42, 0x12, 0x0e, 0x0a, 0x02, 0x69, + 0x64, 0x18, 0x01, 0x20, 0x01, 0x28, 0x05, 0x52, 0x02, 0x69, 0x64, 0x12, 0x10, 0x0a, 0x03, 0x61, + 0x67, 0x65, 0x18, 0x02, 0x20, 0x01, 0x28, 0x05, 0x52, 0x03, 0x61, 0x67, 0x65, 0x12, 0x12, 0x0a, + 0x04, 0x6e, 0x61, 0x6d, 0x65, 0x18, 0x03, 0x20, 0x01, 0x28, 0x09, 0x52, 0x04, 0x6e, 0x61, 0x6d, + 0x65, 0x12, 0x20, 0x0a, 0x02, 0x62, 0x34, 0x18, 0x04, 0x20, 0x03, 0x28, 0x0b, 0x32, 0x10, 0x2e, + 0x74, 0x65, 0x73, 0x74, 0x70, 0x62, 0x2e, 0x4e, 0x65, 0x73, 0x74, 0x65, 0x64, 0x34, 0x42, 0x52, + 0x02, 0x62, 0x34, 0x22, 0x6c, 0x0a, 0x08, 0x4e, 0x65, 0x73, 0x74, 0x65, 0x64, 0x32, 0x42, 0x12, + 0x0e, 0x0a, 0x02, 0x69, 0x64, 0x18, 0x01, 0x20, 0x01, 0x28, 0x05, 0x52, 0x02, 0x69, 0x64, 0x12, + 0x10, 0x0a, 0x03, 0x66, 0x65, 0x65, 0x18, 0x02, 0x20, 0x01, 0x28, 0x01, 0x52, 0x03, 0x66, 0x65, + 0x65, 0x12, 0x28, 0x0a, 0x06, 0x6e, 0x65, 0x73, 0x74, 0x65, 0x64, 0x18, 0x03, 0x20, 0x01, 0x28, + 0x0b, 0x32, 0x10, 0x2e, 0x74, 0x65, 0x73, 0x74, 0x70, 0x62, 0x2e, 0x4e, 0x65, 0x73, 0x74, 0x65, + 0x64, 0x33, 0x42, 0x52, 0x06, 0x6e, 0x65, 0x73, 0x74, 0x65, 0x64, 0x12, 0x14, 0x0a, 0x05, 0x72, + 0x6f, 0x75, 0x74, 0x65, 0x18, 0x04, 0x20, 0x01, 0x28, 0x09, 0x52, 0x05, 0x72, 0x6f, 0x75, 0x74, + 0x65, 0x22, 0x56, 0x0a, 0x08, 0x4e, 0x65, 0x73, 0x74, 0x65, 0x64, 0x31, 0x42, 0x12, 0x0e, 0x0a, + 0x02, 0x69, 0x64, 0x18, 0x01, 0x20, 0x01, 0x28, 0x05, 0x52, 0x02, 0x69, 0x64, 0x12, 0x28, 0x0a, + 0x06, 0x6e, 0x65, 0x73, 0x74, 0x65, 0x64, 0x18, 0x02, 0x20, 0x01, 0x28, 0x0b, 0x32, 0x10, 0x2e, + 0x74, 0x65, 0x73, 0x74, 0x70, 0x62, 0x2e, 0x4e, 0x65, 0x73, 0x74, 0x65, 0x64, 0x32, 0x42, 0x52, + 0x06, 0x6e, 0x65, 0x73, 0x74, 0x65, 0x64, 0x12, 0x10, 0x0a, 0x03, 0x61, 0x67, 0x65, 0x18, 0x03, + 0x20, 0x01, 0x28, 0x05, 0x52, 0x03, 0x61, 0x67, 0x65, 0x22, 0x80, 0x02, 0x0a, 0x09, 0x43, 0x75, + 0x73, 0x74, 0x6f, 0x6d, 0x65, 0x72, 0x33, 0x12, 0x0e, 0x0a, 0x02, 0x69, 0x64, 0x18, 0x01, 0x20, + 0x01, 0x28, 0x05, 0x52, 0x02, 0x69, 0x64, 0x12, 0x12, 0x0a, 0x04, 0x6e, 0x61, 0x6d, 0x65, 0x18, + 0x02, 0x20, 0x01, 0x28, 0x09, 0x52, 0x04, 0x6e, 0x61, 0x6d, 0x65, 0x12, 0x0e, 0x0a, 0x02, 0x73, + 0x66, 0x18, 0x03, 0x20, 0x01, 0x28, 0x02, 0x52, 0x02, 0x73, 0x66, 0x12, 0x1c, 0x0a, 0x09, 0x73, + 0x75, 0x72, 0x63, 0x68, 0x61, 0x72, 0x67, 0x65, 0x18, 0x04, 0x20, 0x01, 0x28, 0x02, 0x52, 0x09, + 0x73, 0x75, 0x72, 0x63, 0x68, 0x61, 0x72, 0x67, 0x65, 0x12, 0x20, 0x0a, 0x0b, 0x64, 0x65, 0x73, + 0x74, 0x69, 0x6e, 0x61, 0x74, 0x69, 0x6f, 0x6e, 0x18, 0x05, 0x20, 0x01, 0x28, 0x09, 0x52, 0x0b, + 0x64, 0x65, 0x73, 0x74, 0x69, 0x6e, 0x61, 0x74, 0x69, 0x6f, 0x6e, 0x12, 0x26, 0x0a, 0x0e, 0x63, + 0x72, 0x65, 0x64, 0x69, 0x74, 0x5f, 0x63, 0x61, 0x72, 0x64, 0x5f, 0x6e, 0x6f, 0x18, 0x07, 0x20, + 0x01, 0x28, 0x09, 0x48, 0x00, 0x52, 0x0c, 0x63, 0x72, 0x65, 0x64, 0x69, 0x74, 0x43, 0x61, 0x72, + 0x64, 0x4e, 0x6f, 0x12, 0x1d, 0x0a, 0x09, 0x63, 0x68, 0x65, 0x71, 0x75, 0x65, 0x5f, 0x6e, 0x6f, + 0x18, 0x08, 0x20, 0x01, 0x28, 0x09, 0x48, 0x00, 0x52, 0x08, 0x63, 0x68, 0x65, 0x71, 0x75, 0x65, + 0x4e, 0x6f, 0x12, 0x2d, 0x0a, 0x08, 0x6f, 0x72, 0x69, 0x67, 0x69, 0x6e, 0x61, 0x6c, 0x18, 0x09, + 0x20, 0x01, 0x28, 0x0b, 0x32, 0x11, 0x2e, 0x74, 0x65, 0x73, 0x74, 0x70, 0x62, 0x2e, 0x43, 0x75, + 0x73, 0x74, 0x6f, 0x6d, 0x65, 0x72, 0x31, 0x52, 0x08, 0x6f, 0x72, 0x69, 0x67, 0x69, 0x6e, 0x61, + 0x6c, 0x42, 0x09, 0x0a, 0x07, 0x70, 0x61, 0x79, 0x6d, 0x65, 0x6e, 0x74, 0x22, 0xd2, 0x02, 0x0a, + 0x0c, 0x54, 0x65, 0x73, 0x74, 0x56, 0x65, 0x72, 0x73, 0x69, 0x6f, 0x6e, 0x31, 0x12, 0x0c, 0x0a, + 0x01, 0x78, 0x18, 0x01, 0x20, 0x01, 0x28, 0x03, 0x52, 0x01, 0x78, 0x12, 0x22, 0x0a, 0x01, 0x61, + 0x18, 0x02, 0x20, 0x01, 0x28, 0x0b, 0x32, 0x14, 0x2e, 0x74, 0x65, 0x73, 0x74, 0x70, 0x62, 0x2e, + 0x54, 0x65, 0x73, 0x74, 0x56, 0x65, 0x72, 0x73, 0x69, 0x6f, 0x6e, 0x31, 0x52, 0x01, 0x61, 0x12, + 0x22, 0x0a, 0x01, 0x62, 0x18, 0x03, 0x20, 0x01, 0x28, 0x0b, 0x32, 0x14, 0x2e, 0x74, 0x65, 0x73, + 0x74, 0x70, 0x62, 0x2e, 0x54, 0x65, 0x73, 0x74, 0x56, 0x65, 0x72, 0x73, 0x69, 0x6f, 0x6e, 0x31, + 0x52, 0x01, 0x62, 0x12, 0x22, 0x0a, 0x01, 0x63, 0x18, 0x04, 0x20, 0x03, 0x28, 0x0b, 0x32, 0x14, + 0x2e, 0x74, 0x65, 0x73, 0x74, 0x70, 0x62, 0x2e, 0x54, 0x65, 0x73, 0x74, 0x56, 0x65, 0x72, 0x73, + 0x69, 0x6f, 0x6e, 0x31, 0x52, 0x01, 0x63, 0x12, 0x22, 0x0a, 0x01, 0x64, 0x18, 0x05, 0x20, 0x03, + 0x28, 0x0b, 0x32, 0x14, 0x2e, 0x74, 0x65, 0x73, 0x74, 0x70, 0x62, 0x2e, 0x54, 0x65, 0x73, 0x74, + 0x56, 0x65, 0x72, 0x73, 0x69, 0x6f, 0x6e, 0x31, 0x52, 0x01, 0x64, 0x12, 0x0e, 0x0a, 0x01, 0x65, + 0x18, 0x06, 0x20, 0x01, 0x28, 0x05, 0x48, 0x00, 0x52, 0x01, 0x65, 0x12, 0x24, 0x0a, 0x01, 0x66, + 0x18, 0x07, 0x20, 0x01, 0x28, 0x0b, 0x32, 0x14, 0x2e, 0x74, 0x65, 0x73, 0x74, 0x70, 0x62, 0x2e, + 0x54, 0x65, 0x73, 0x74, 0x56, 0x65, 0x72, 0x73, 0x69, 0x6f, 0x6e, 0x31, 0x48, 0x00, 0x52, 0x01, + 0x66, 0x12, 0x22, 0x0a, 0x01, 0x67, 0x18, 0x08, 0x20, 0x01, 0x28, 0x0b, 0x32, 0x14, 0x2e, 0x67, + 0x6f, 0x6f, 0x67, 0x6c, 0x65, 0x2e, 0x70, 0x72, 0x6f, 0x74, 0x6f, 0x62, 0x75, 0x66, 0x2e, 0x41, + 0x6e, 0x79, 0x52, 0x01, 0x67, 0x12, 0x22, 0x0a, 0x01, 0x68, 0x18, 0x09, 0x20, 0x03, 0x28, 0x0b, + 0x32, 0x14, 0x2e, 0x74, 0x65, 0x73, 0x74, 0x70, 0x62, 0x2e, 0x54, 0x65, 0x73, 0x74, 0x56, 0x65, + 0x72, 0x73, 0x69, 0x6f, 0x6e, 0x31, 0x52, 0x01, 0x68, 0x12, 0x1f, 0x0a, 0x01, 0x6b, 0x18, 0x0c, + 0x20, 0x01, 0x28, 0x0b, 0x32, 0x11, 0x2e, 0x74, 0x65, 0x73, 0x74, 0x70, 0x62, 0x2e, 0x43, 0x75, + 0x73, 0x74, 0x6f, 0x6d, 0x65, 0x72, 0x31, 0x52, 0x01, 0x6b, 0x42, 0x05, 0x0a, 0x03, 0x73, 0x75, + 0x6d, 0x22, 0xef, 0x02, 0x0a, 0x0c, 0x54, 0x65, 0x73, 0x74, 0x56, 0x65, 0x72, 0x73, 0x69, 0x6f, + 0x6e, 0x32, 0x12, 0x0c, 0x0a, 0x01, 0x78, 0x18, 0x01, 0x20, 0x01, 0x28, 0x03, 0x52, 0x01, 0x78, + 0x12, 0x22, 0x0a, 0x01, 0x61, 0x18, 0x02, 0x20, 0x01, 0x28, 0x0b, 0x32, 0x14, 0x2e, 0x74, 0x65, + 0x73, 0x74, 0x70, 0x62, 0x2e, 0x54, 0x65, 0x73, 0x74, 0x56, 0x65, 0x72, 0x73, 0x69, 0x6f, 0x6e, + 0x32, 0x52, 0x01, 0x61, 0x12, 0x22, 0x0a, 0x01, 0x62, 0x18, 0x03, 0x20, 0x01, 0x28, 0x0b, 0x32, + 0x14, 0x2e, 0x74, 0x65, 0x73, 0x74, 0x70, 0x62, 0x2e, 0x54, 0x65, 0x73, 0x74, 0x56, 0x65, 0x72, + 0x73, 0x69, 0x6f, 0x6e, 0x32, 0x52, 0x01, 0x62, 0x12, 0x22, 0x0a, 0x01, 0x63, 0x18, 0x04, 0x20, + 0x03, 0x28, 0x0b, 0x32, 0x14, 0x2e, 0x74, 0x65, 0x73, 0x74, 0x70, 0x62, 0x2e, 0x54, 0x65, 0x73, + 0x74, 0x56, 0x65, 0x72, 0x73, 0x69, 0x6f, 0x6e, 0x32, 0x52, 0x01, 0x63, 0x12, 0x22, 0x0a, 0x01, + 0x64, 0x18, 0x05, 0x20, 0x03, 0x28, 0x0b, 0x32, 0x14, 0x2e, 0x74, 0x65, 0x73, 0x74, 0x70, 0x62, + 0x2e, 0x54, 0x65, 0x73, 0x74, 0x56, 0x65, 0x72, 0x73, 0x69, 0x6f, 0x6e, 0x32, 0x52, 0x01, 0x64, + 0x12, 0x0e, 0x0a, 0x01, 0x65, 0x18, 0x06, 0x20, 0x01, 0x28, 0x05, 0x48, 0x00, 0x52, 0x01, 0x65, + 0x12, 0x24, 0x0a, 0x01, 0x66, 0x18, 0x07, 0x20, 0x01, 0x28, 0x0b, 0x32, 0x14, 0x2e, 0x74, 0x65, + 0x73, 0x74, 0x70, 0x62, 0x2e, 0x54, 0x65, 0x73, 0x74, 0x56, 0x65, 0x72, 0x73, 0x69, 0x6f, 0x6e, + 0x32, 0x48, 0x00, 0x52, 0x01, 0x66, 0x12, 0x22, 0x0a, 0x01, 0x67, 0x18, 0x08, 0x20, 0x01, 0x28, + 0x0b, 0x32, 0x14, 0x2e, 0x67, 0x6f, 0x6f, 0x67, 0x6c, 0x65, 0x2e, 0x70, 0x72, 0x6f, 0x74, 0x6f, + 0x62, 0x75, 0x66, 0x2e, 0x41, 0x6e, 0x79, 0x52, 0x01, 0x67, 0x12, 0x22, 0x0a, 0x01, 0x68, 0x18, + 0x09, 0x20, 0x03, 0x28, 0x0b, 0x32, 0x14, 0x2e, 0x74, 0x65, 0x73, 0x74, 0x70, 0x62, 0x2e, 0x54, + 0x65, 0x73, 0x74, 0x56, 0x65, 0x72, 0x73, 0x69, 0x6f, 0x6e, 0x31, 0x52, 0x01, 0x68, 0x12, 0x1f, + 0x0a, 0x01, 0x6b, 0x18, 0x0c, 0x20, 0x01, 0x28, 0x0b, 0x32, 0x11, 0x2e, 0x74, 0x65, 0x73, 0x74, + 0x70, 0x62, 0x2e, 0x43, 0x75, 0x73, 0x74, 0x6f, 0x6d, 0x65, 0x72, 0x31, 0x52, 0x01, 0x6b, 0x12, + 0x1b, 0x0a, 0x09, 0x6e, 0x65, 0x77, 0x5f, 0x66, 0x69, 0x65, 0x6c, 0x64, 0x18, 0x19, 0x20, 0x01, + 0x28, 0x04, 0x52, 0x08, 0x6e, 0x65, 0x77, 0x46, 0x69, 0x65, 0x6c, 0x64, 0x42, 0x05, 0x0a, 0x03, + 0x73, 0x75, 0x6d, 0x22, 0x81, 0x03, 0x0a, 0x0c, 0x54, 0x65, 0x73, 0x74, 0x56, 0x65, 0x72, 0x73, + 0x69, 0x6f, 0x6e, 0x33, 0x12, 0x0c, 0x0a, 0x01, 0x78, 0x18, 0x01, 0x20, 0x01, 0x28, 0x03, 0x52, + 0x01, 0x78, 0x12, 0x22, 0x0a, 0x01, 0x61, 0x18, 0x02, 0x20, 0x01, 0x28, 0x0b, 0x32, 0x14, 0x2e, + 0x74, 0x65, 0x73, 0x74, 0x70, 0x62, 0x2e, 0x54, 0x65, 0x73, 0x74, 0x56, 0x65, 0x72, 0x73, 0x69, + 0x6f, 0x6e, 0x33, 0x52, 0x01, 0x61, 0x12, 0x22, 0x0a, 0x01, 0x62, 0x18, 0x03, 0x20, 0x01, 0x28, + 0x0b, 0x32, 0x14, 0x2e, 0x74, 0x65, 0x73, 0x74, 0x70, 0x62, 0x2e, 0x54, 0x65, 0x73, 0x74, 0x56, + 0x65, 0x72, 0x73, 0x69, 0x6f, 0x6e, 0x33, 0x52, 0x01, 0x62, 0x12, 0x22, 0x0a, 0x01, 0x63, 0x18, + 0x04, 0x20, 0x03, 0x28, 0x0b, 0x32, 0x14, 0x2e, 0x74, 0x65, 0x73, 0x74, 0x70, 0x62, 0x2e, 0x54, + 0x65, 0x73, 0x74, 0x56, 0x65, 0x72, 0x73, 0x69, 0x6f, 0x6e, 0x33, 0x52, 0x01, 0x63, 0x12, 0x22, + 0x0a, 0x01, 0x64, 0x18, 0x05, 0x20, 0x03, 0x28, 0x0b, 0x32, 0x14, 0x2e, 0x74, 0x65, 0x73, 0x74, + 0x70, 0x62, 0x2e, 0x54, 0x65, 0x73, 0x74, 0x56, 0x65, 0x72, 0x73, 0x69, 0x6f, 0x6e, 0x33, 0x52, + 0x01, 0x64, 0x12, 0x0e, 0x0a, 0x01, 0x65, 0x18, 0x06, 0x20, 0x01, 0x28, 0x05, 0x48, 0x00, 0x52, + 0x01, 0x65, 0x12, 0x24, 0x0a, 0x01, 0x66, 0x18, 0x07, 0x20, 0x01, 0x28, 0x0b, 0x32, 0x14, 0x2e, + 0x74, 0x65, 0x73, 0x74, 0x70, 0x62, 0x2e, 0x54, 0x65, 0x73, 0x74, 0x56, 0x65, 0x72, 0x73, 0x69, + 0x6f, 0x6e, 0x33, 0x48, 0x00, 0x52, 0x01, 0x66, 0x12, 0x22, 0x0a, 0x01, 0x67, 0x18, 0x08, 0x20, + 0x01, 0x28, 0x0b, 0x32, 0x14, 0x2e, 0x67, 0x6f, 0x6f, 0x67, 0x6c, 0x65, 0x2e, 0x70, 0x72, 0x6f, + 0x74, 0x6f, 0x62, 0x75, 0x66, 0x2e, 0x41, 0x6e, 0x79, 0x52, 0x01, 0x67, 0x12, 0x22, 0x0a, 0x01, + 0x68, 0x18, 0x09, 0x20, 0x03, 0x28, 0x0b, 0x32, 0x14, 0x2e, 0x74, 0x65, 0x73, 0x74, 0x70, 0x62, + 0x2e, 0x54, 0x65, 0x73, 0x74, 0x56, 0x65, 0x72, 0x73, 0x69, 0x6f, 0x6e, 0x31, 0x52, 0x01, 0x68, + 0x12, 0x1f, 0x0a, 0x01, 0x6b, 0x18, 0x0c, 0x20, 0x01, 0x28, 0x0b, 0x32, 0x11, 0x2e, 0x74, 0x65, + 0x73, 0x74, 0x70, 0x62, 0x2e, 0x43, 0x75, 0x73, 0x74, 0x6f, 0x6d, 0x65, 0x72, 0x31, 0x52, 0x01, + 0x6b, 0x12, 0x2d, 0x0a, 0x12, 0x6e, 0x6f, 0x6e, 0x5f, 0x63, 0x72, 0x69, 0x74, 0x69, 0x63, 0x61, + 0x6c, 0x5f, 0x66, 0x69, 0x65, 0x6c, 0x64, 0x18, 0x87, 0x08, 0x20, 0x01, 0x28, 0x09, 0x52, 0x10, + 0x6e, 0x6f, 0x6e, 0x43, 0x72, 0x69, 0x74, 0x69, 0x63, 0x61, 0x6c, 0x46, 0x69, 0x65, 0x6c, 0x64, + 0x42, 0x05, 0x0a, 0x03, 0x73, 0x75, 0x6d, 0x22, 0xe9, 0x02, 0x0a, 0x1a, 0x54, 0x65, 0x73, 0x74, + 0x56, 0x65, 0x72, 0x73, 0x69, 0x6f, 0x6e, 0x33, 0x4c, 0x6f, 0x6e, 0x65, 0x4f, 0x6e, 0x65, 0x4f, + 0x66, 0x56, 0x61, 0x6c, 0x75, 0x65, 0x12, 0x0c, 0x0a, 0x01, 0x78, 0x18, 0x01, 0x20, 0x01, 0x28, + 0x03, 0x52, 0x01, 0x78, 0x12, 0x22, 0x0a, 0x01, 0x61, 0x18, 0x02, 0x20, 0x01, 0x28, 0x0b, 0x32, + 0x14, 0x2e, 0x74, 0x65, 0x73, 0x74, 0x70, 0x62, 0x2e, 0x54, 0x65, 0x73, 0x74, 0x56, 0x65, 0x72, + 0x73, 0x69, 0x6f, 0x6e, 0x33, 0x52, 0x01, 0x61, 0x12, 0x22, 0x0a, 0x01, 0x62, 0x18, 0x03, 0x20, + 0x01, 0x28, 0x0b, 0x32, 0x14, 0x2e, 0x74, 0x65, 0x73, 0x74, 0x70, 0x62, 0x2e, 0x54, 0x65, 0x73, + 0x74, 0x56, 0x65, 0x72, 0x73, 0x69, 0x6f, 0x6e, 0x33, 0x52, 0x01, 0x62, 0x12, 0x22, 0x0a, 0x01, + 0x63, 0x18, 0x04, 0x20, 0x03, 0x28, 0x0b, 0x32, 0x14, 0x2e, 0x74, 0x65, 0x73, 0x74, 0x70, 0x62, + 0x2e, 0x54, 0x65, 0x73, 0x74, 0x56, 0x65, 0x72, 0x73, 0x69, 0x6f, 0x6e, 0x33, 0x52, 0x01, 0x63, + 0x12, 0x22, 0x0a, 0x01, 0x64, 0x18, 0x05, 0x20, 0x03, 0x28, 0x0b, 0x32, 0x14, 0x2e, 0x74, 0x65, + 0x73, 0x74, 0x70, 0x62, 0x2e, 0x54, 0x65, 0x73, 0x74, 0x56, 0x65, 0x72, 0x73, 0x69, 0x6f, 0x6e, + 0x33, 0x52, 0x01, 0x64, 0x12, 0x0e, 0x0a, 0x01, 0x65, 0x18, 0x06, 0x20, 0x01, 0x28, 0x05, 0x48, + 0x00, 0x52, 0x01, 0x65, 0x12, 0x22, 0x0a, 0x01, 0x67, 0x18, 0x08, 0x20, 0x01, 0x28, 0x0b, 0x32, + 0x14, 0x2e, 0x67, 0x6f, 0x6f, 0x67, 0x6c, 0x65, 0x2e, 0x70, 0x72, 0x6f, 0x74, 0x6f, 0x62, 0x75, + 0x66, 0x2e, 0x41, 0x6e, 0x79, 0x52, 0x01, 0x67, 0x12, 0x22, 0x0a, 0x01, 0x68, 0x18, 0x09, 0x20, + 0x03, 0x28, 0x0b, 0x32, 0x14, 0x2e, 0x74, 0x65, 0x73, 0x74, 0x70, 0x62, 0x2e, 0x54, 0x65, 0x73, + 0x74, 0x56, 0x65, 0x72, 0x73, 0x69, 0x6f, 0x6e, 0x31, 0x52, 0x01, 0x68, 0x12, 0x1f, 0x0a, 0x01, + 0x6b, 0x18, 0x0c, 0x20, 0x01, 0x28, 0x0b, 0x32, 0x11, 0x2e, 0x74, 0x65, 0x73, 0x74, 0x70, 0x62, + 0x2e, 0x43, 0x75, 0x73, 0x74, 0x6f, 0x6d, 0x65, 0x72, 0x31, 0x52, 0x01, 0x6b, 0x12, 0x2d, 0x0a, + 0x12, 0x6e, 0x6f, 0x6e, 0x5f, 0x63, 0x72, 0x69, 0x74, 0x69, 0x63, 0x61, 0x6c, 0x5f, 0x66, 0x69, + 0x65, 0x6c, 0x64, 0x18, 0x87, 0x08, 0x20, 0x01, 0x28, 0x09, 0x52, 0x10, 0x6e, 0x6f, 0x6e, 0x43, + 0x72, 0x69, 0x74, 0x69, 0x63, 0x61, 0x6c, 0x46, 0x69, 0x65, 0x6c, 0x64, 0x42, 0x05, 0x0a, 0x03, + 0x73, 0x75, 0x6d, 0x22, 0xe1, 0x06, 0x0a, 0x17, 0x54, 0x65, 0x73, 0x74, 0x56, 0x65, 0x72, 0x73, + 0x69, 0x6f, 0x6e, 0x33, 0x4c, 0x6f, 0x6e, 0x65, 0x4e, 0x65, 0x73, 0x74, 0x69, 0x6e, 0x67, 0x12, + 0x0c, 0x0a, 0x01, 0x78, 0x18, 0x01, 0x20, 0x01, 0x28, 0x03, 0x52, 0x01, 0x78, 0x12, 0x22, 0x0a, + 0x01, 0x61, 0x18, 0x02, 0x20, 0x01, 0x28, 0x0b, 0x32, 0x14, 0x2e, 0x74, 0x65, 0x73, 0x74, 0x70, + 0x62, 0x2e, 0x54, 0x65, 0x73, 0x74, 0x56, 0x65, 0x72, 0x73, 0x69, 0x6f, 0x6e, 0x33, 0x52, 0x01, + 0x61, 0x12, 0x22, 0x0a, 0x01, 0x62, 0x18, 0x03, 0x20, 0x01, 0x28, 0x0b, 0x32, 0x14, 0x2e, 0x74, + 0x65, 0x73, 0x74, 0x70, 0x62, 0x2e, 0x54, 0x65, 0x73, 0x74, 0x56, 0x65, 0x72, 0x73, 0x69, 0x6f, + 0x6e, 0x33, 0x52, 0x01, 0x62, 0x12, 0x22, 0x0a, 0x01, 0x63, 0x18, 0x04, 0x20, 0x03, 0x28, 0x0b, + 0x32, 0x14, 0x2e, 0x74, 0x65, 0x73, 0x74, 0x70, 0x62, 0x2e, 0x54, 0x65, 0x73, 0x74, 0x56, 0x65, + 0x72, 0x73, 0x69, 0x6f, 0x6e, 0x33, 0x52, 0x01, 0x63, 0x12, 0x22, 0x0a, 0x01, 0x64, 0x18, 0x05, + 0x20, 0x03, 0x28, 0x0b, 0x32, 0x14, 0x2e, 0x74, 0x65, 0x73, 0x74, 0x70, 0x62, 0x2e, 0x54, 0x65, + 0x73, 0x74, 0x56, 0x65, 0x72, 0x73, 0x69, 0x6f, 0x6e, 0x33, 0x52, 0x01, 0x64, 0x12, 0x2f, 0x0a, + 0x01, 0x66, 0x18, 0x07, 0x20, 0x01, 0x28, 0x0b, 0x32, 0x1f, 0x2e, 0x74, 0x65, 0x73, 0x74, 0x70, + 0x62, 0x2e, 0x54, 0x65, 0x73, 0x74, 0x56, 0x65, 0x72, 0x73, 0x69, 0x6f, 0x6e, 0x33, 0x4c, 0x6f, + 0x6e, 0x65, 0x4e, 0x65, 0x73, 0x74, 0x69, 0x6e, 0x67, 0x48, 0x00, 0x52, 0x01, 0x66, 0x12, 0x22, + 0x0a, 0x01, 0x67, 0x18, 0x08, 0x20, 0x01, 0x28, 0x0b, 0x32, 0x14, 0x2e, 0x67, 0x6f, 0x6f, 0x67, + 0x6c, 0x65, 0x2e, 0x70, 0x72, 0x6f, 0x74, 0x6f, 0x62, 0x75, 0x66, 0x2e, 0x41, 0x6e, 0x79, 0x52, + 0x01, 0x67, 0x12, 0x22, 0x0a, 0x01, 0x68, 0x18, 0x09, 0x20, 0x03, 0x28, 0x0b, 0x32, 0x14, 0x2e, + 0x74, 0x65, 0x73, 0x74, 0x70, 0x62, 0x2e, 0x54, 0x65, 0x73, 0x74, 0x56, 0x65, 0x72, 0x73, 0x69, + 0x6f, 0x6e, 0x31, 0x52, 0x01, 0x68, 0x12, 0x1f, 0x0a, 0x01, 0x6b, 0x18, 0x0c, 0x20, 0x01, 0x28, + 0x0b, 0x32, 0x11, 0x2e, 0x74, 0x65, 0x73, 0x74, 0x70, 0x62, 0x2e, 0x43, 0x75, 0x73, 0x74, 0x6f, + 0x6d, 0x65, 0x72, 0x31, 0x52, 0x01, 0x6b, 0x12, 0x2d, 0x0a, 0x12, 0x6e, 0x6f, 0x6e, 0x5f, 0x63, + 0x72, 0x69, 0x74, 0x69, 0x63, 0x61, 0x6c, 0x5f, 0x66, 0x69, 0x65, 0x6c, 0x64, 0x18, 0x87, 0x08, + 0x20, 0x01, 0x28, 0x09, 0x52, 0x10, 0x6e, 0x6f, 0x6e, 0x43, 0x72, 0x69, 0x74, 0x69, 0x63, 0x61, + 0x6c, 0x46, 0x69, 0x65, 0x6c, 0x64, 0x12, 0x3e, 0x0a, 0x06, 0x69, 0x6e, 0x6e, 0x65, 0x72, 0x31, + 0x18, 0x0e, 0x20, 0x01, 0x28, 0x0b, 0x32, 0x26, 0x2e, 0x74, 0x65, 0x73, 0x74, 0x70, 0x62, 0x2e, + 0x54, 0x65, 0x73, 0x74, 0x56, 0x65, 0x72, 0x73, 0x69, 0x6f, 0x6e, 0x33, 0x4c, 0x6f, 0x6e, 0x65, + 0x4e, 0x65, 0x73, 0x74, 0x69, 0x6e, 0x67, 0x2e, 0x49, 0x6e, 0x6e, 0x65, 0x72, 0x31, 0x52, 0x06, + 0x69, 0x6e, 0x6e, 0x65, 0x72, 0x31, 0x12, 0x3e, 0x0a, 0x06, 0x69, 0x6e, 0x6e, 0x65, 0x72, 0x32, + 0x18, 0x0f, 0x20, 0x01, 0x28, 0x0b, 0x32, 0x26, 0x2e, 0x74, 0x65, 0x73, 0x74, 0x70, 0x62, 0x2e, + 0x54, 0x65, 0x73, 0x74, 0x56, 0x65, 0x72, 0x73, 0x69, 0x6f, 0x6e, 0x33, 0x4c, 0x6f, 0x6e, 0x65, + 0x4e, 0x65, 0x73, 0x74, 0x69, 0x6e, 0x67, 0x2e, 0x49, 0x6e, 0x6e, 0x65, 0x72, 0x32, 0x52, 0x06, + 0x69, 0x6e, 0x6e, 0x65, 0x72, 0x32, 0x1a, 0xa7, 0x01, 0x0a, 0x06, 0x49, 0x6e, 0x6e, 0x65, 0x72, + 0x31, 0x12, 0x0e, 0x0a, 0x02, 0x69, 0x64, 0x18, 0x01, 0x20, 0x01, 0x28, 0x03, 0x52, 0x02, 0x69, + 0x64, 0x12, 0x12, 0x0a, 0x04, 0x6e, 0x61, 0x6d, 0x65, 0x18, 0x02, 0x20, 0x01, 0x28, 0x09, 0x52, + 0x04, 0x6e, 0x61, 0x6d, 0x65, 0x12, 0x47, 0x0a, 0x05, 0x69, 0x6e, 0x6e, 0x65, 0x72, 0x18, 0x03, + 0x20, 0x01, 0x28, 0x0b, 0x32, 0x31, 0x2e, 0x74, 0x65, 0x73, 0x74, 0x70, 0x62, 0x2e, 0x54, 0x65, + 0x73, 0x74, 0x56, 0x65, 0x72, 0x73, 0x69, 0x6f, 0x6e, 0x33, 0x4c, 0x6f, 0x6e, 0x65, 0x4e, 0x65, + 0x73, 0x74, 0x69, 0x6e, 0x67, 0x2e, 0x49, 0x6e, 0x6e, 0x65, 0x72, 0x31, 0x2e, 0x49, 0x6e, 0x6e, + 0x65, 0x72, 0x49, 0x6e, 0x6e, 0x65, 0x72, 0x52, 0x05, 0x69, 0x6e, 0x6e, 0x65, 0x72, 0x1a, 0x30, + 0x0a, 0x0a, 0x49, 0x6e, 0x6e, 0x65, 0x72, 0x49, 0x6e, 0x6e, 0x65, 0x72, 0x12, 0x0e, 0x0a, 0x02, + 0x69, 0x64, 0x18, 0x01, 0x20, 0x01, 0x28, 0x09, 0x52, 0x02, 0x69, 0x64, 0x12, 0x12, 0x0a, 0x04, + 0x63, 0x69, 0x74, 0x79, 0x18, 0x02, 0x20, 0x01, 0x28, 0x09, 0x52, 0x04, 0x63, 0x69, 0x74, 0x79, + 0x1a, 0xad, 0x01, 0x0a, 0x06, 0x49, 0x6e, 0x6e, 0x65, 0x72, 0x32, 0x12, 0x0e, 0x0a, 0x02, 0x69, + 0x64, 0x18, 0x01, 0x20, 0x01, 0x28, 0x09, 0x52, 0x02, 0x69, 0x64, 0x12, 0x18, 0x0a, 0x07, 0x63, + 0x6f, 0x75, 0x6e, 0x74, 0x72, 0x79, 0x18, 0x02, 0x20, 0x01, 0x28, 0x09, 0x52, 0x07, 0x63, 0x6f, + 0x75, 0x6e, 0x74, 0x72, 0x79, 0x12, 0x47, 0x0a, 0x05, 0x69, 0x6e, 0x6e, 0x65, 0x72, 0x18, 0x03, + 0x20, 0x01, 0x28, 0x0b, 0x32, 0x31, 0x2e, 0x74, 0x65, 0x73, 0x74, 0x70, 0x62, 0x2e, 0x54, 0x65, + 0x73, 0x74, 0x56, 0x65, 0x72, 0x73, 0x69, 0x6f, 0x6e, 0x33, 0x4c, 0x6f, 0x6e, 0x65, 0x4e, 0x65, + 0x73, 0x74, 0x69, 0x6e, 0x67, 0x2e, 0x49, 0x6e, 0x6e, 0x65, 0x72, 0x32, 0x2e, 0x49, 0x6e, 0x6e, + 0x65, 0x72, 0x49, 0x6e, 0x6e, 0x65, 0x72, 0x52, 0x05, 0x69, 0x6e, 0x6e, 0x65, 0x72, 0x1a, 0x30, + 0x0a, 0x0a, 0x49, 0x6e, 0x6e, 0x65, 0x72, 0x49, 0x6e, 0x6e, 0x65, 0x72, 0x12, 0x0e, 0x0a, 0x02, + 0x69, 0x64, 0x18, 0x01, 0x20, 0x01, 0x28, 0x09, 0x52, 0x02, 0x69, 0x64, 0x12, 0x12, 0x0a, 0x04, + 0x63, 0x69, 0x74, 0x79, 0x18, 0x02, 0x20, 0x01, 0x28, 0x09, 0x52, 0x04, 0x63, 0x69, 0x74, 0x79, + 0x42, 0x05, 0x0a, 0x03, 0x73, 0x75, 0x6d, 0x22, 0xe3, 0x06, 0x0a, 0x17, 0x54, 0x65, 0x73, 0x74, + 0x56, 0x65, 0x72, 0x73, 0x69, 0x6f, 0x6e, 0x34, 0x4c, 0x6f, 0x6e, 0x65, 0x4e, 0x65, 0x73, 0x74, + 0x69, 0x6e, 0x67, 0x12, 0x0c, 0x0a, 0x01, 0x78, 0x18, 0x01, 0x20, 0x01, 0x28, 0x03, 0x52, 0x01, + 0x78, 0x12, 0x22, 0x0a, 0x01, 0x61, 0x18, 0x02, 0x20, 0x01, 0x28, 0x0b, 0x32, 0x14, 0x2e, 0x74, + 0x65, 0x73, 0x74, 0x70, 0x62, 0x2e, 0x54, 0x65, 0x73, 0x74, 0x56, 0x65, 0x72, 0x73, 0x69, 0x6f, + 0x6e, 0x33, 0x52, 0x01, 0x61, 0x12, 0x22, 0x0a, 0x01, 0x62, 0x18, 0x03, 0x20, 0x01, 0x28, 0x0b, + 0x32, 0x14, 0x2e, 0x74, 0x65, 0x73, 0x74, 0x70, 0x62, 0x2e, 0x54, 0x65, 0x73, 0x74, 0x56, 0x65, + 0x72, 0x73, 0x69, 0x6f, 0x6e, 0x33, 0x52, 0x01, 0x62, 0x12, 0x22, 0x0a, 0x01, 0x63, 0x18, 0x04, + 0x20, 0x03, 0x28, 0x0b, 0x32, 0x14, 0x2e, 0x74, 0x65, 0x73, 0x74, 0x70, 0x62, 0x2e, 0x54, 0x65, + 0x73, 0x74, 0x56, 0x65, 0x72, 0x73, 0x69, 0x6f, 0x6e, 0x33, 0x52, 0x01, 0x63, 0x12, 0x22, 0x0a, + 0x01, 0x64, 0x18, 0x05, 0x20, 0x03, 0x28, 0x0b, 0x32, 0x14, 0x2e, 0x74, 0x65, 0x73, 0x74, 0x70, + 0x62, 0x2e, 0x54, 0x65, 0x73, 0x74, 0x56, 0x65, 0x72, 0x73, 0x69, 0x6f, 0x6e, 0x33, 0x52, 0x01, + 0x64, 0x12, 0x2f, 0x0a, 0x01, 0x66, 0x18, 0x07, 0x20, 0x01, 0x28, 0x0b, 0x32, 0x1f, 0x2e, 0x74, + 0x65, 0x73, 0x74, 0x70, 0x62, 0x2e, 0x54, 0x65, 0x73, 0x74, 0x56, 0x65, 0x72, 0x73, 0x69, 0x6f, + 0x6e, 0x33, 0x4c, 0x6f, 0x6e, 0x65, 0x4e, 0x65, 0x73, 0x74, 0x69, 0x6e, 0x67, 0x48, 0x00, 0x52, + 0x01, 0x66, 0x12, 0x22, 0x0a, 0x01, 0x67, 0x18, 0x08, 0x20, 0x01, 0x28, 0x0b, 0x32, 0x14, 0x2e, + 0x67, 0x6f, 0x6f, 0x67, 0x6c, 0x65, 0x2e, 0x70, 0x72, 0x6f, 0x74, 0x6f, 0x62, 0x75, 0x66, 0x2e, + 0x41, 0x6e, 0x79, 0x52, 0x01, 0x67, 0x12, 0x22, 0x0a, 0x01, 0x68, 0x18, 0x09, 0x20, 0x03, 0x28, + 0x0b, 0x32, 0x14, 0x2e, 0x74, 0x65, 0x73, 0x74, 0x70, 0x62, 0x2e, 0x54, 0x65, 0x73, 0x74, 0x56, + 0x65, 0x72, 0x73, 0x69, 0x6f, 0x6e, 0x31, 0x52, 0x01, 0x68, 0x12, 0x1f, 0x0a, 0x01, 0x6b, 0x18, + 0x0c, 0x20, 0x01, 0x28, 0x0b, 0x32, 0x11, 0x2e, 0x74, 0x65, 0x73, 0x74, 0x70, 0x62, 0x2e, 0x43, + 0x75, 0x73, 0x74, 0x6f, 0x6d, 0x65, 0x72, 0x31, 0x52, 0x01, 0x6b, 0x12, 0x2d, 0x0a, 0x12, 0x6e, + 0x6f, 0x6e, 0x5f, 0x63, 0x72, 0x69, 0x74, 0x69, 0x63, 0x61, 0x6c, 0x5f, 0x66, 0x69, 0x65, 0x6c, + 0x64, 0x18, 0x87, 0x08, 0x20, 0x01, 0x28, 0x09, 0x52, 0x10, 0x6e, 0x6f, 0x6e, 0x43, 0x72, 0x69, + 0x74, 0x69, 0x63, 0x61, 0x6c, 0x46, 0x69, 0x65, 0x6c, 0x64, 0x12, 0x3e, 0x0a, 0x06, 0x69, 0x6e, + 0x6e, 0x65, 0x72, 0x31, 0x18, 0x0e, 0x20, 0x01, 0x28, 0x0b, 0x32, 0x26, 0x2e, 0x74, 0x65, 0x73, + 0x74, 0x70, 0x62, 0x2e, 0x54, 0x65, 0x73, 0x74, 0x56, 0x65, 0x72, 0x73, 0x69, 0x6f, 0x6e, 0x34, + 0x4c, 0x6f, 0x6e, 0x65, 0x4e, 0x65, 0x73, 0x74, 0x69, 0x6e, 0x67, 0x2e, 0x49, 0x6e, 0x6e, 0x65, + 0x72, 0x31, 0x52, 0x06, 0x69, 0x6e, 0x6e, 0x65, 0x72, 0x31, 0x12, 0x3e, 0x0a, 0x06, 0x69, 0x6e, + 0x6e, 0x65, 0x72, 0x32, 0x18, 0x0f, 0x20, 0x01, 0x28, 0x0b, 0x32, 0x26, 0x2e, 0x74, 0x65, 0x73, + 0x74, 0x70, 0x62, 0x2e, 0x54, 0x65, 0x73, 0x74, 0x56, 0x65, 0x72, 0x73, 0x69, 0x6f, 0x6e, 0x34, + 0x4c, 0x6f, 0x6e, 0x65, 0x4e, 0x65, 0x73, 0x74, 0x69, 0x6e, 0x67, 0x2e, 0x49, 0x6e, 0x6e, 0x65, + 0x72, 0x32, 0x52, 0x06, 0x69, 0x6e, 0x6e, 0x65, 0x72, 0x32, 0x1a, 0xa7, 0x01, 0x0a, 0x06, 0x49, + 0x6e, 0x6e, 0x65, 0x72, 0x31, 0x12, 0x0e, 0x0a, 0x02, 0x69, 0x64, 0x18, 0x01, 0x20, 0x01, 0x28, + 0x03, 0x52, 0x02, 0x69, 0x64, 0x12, 0x12, 0x0a, 0x04, 0x6e, 0x61, 0x6d, 0x65, 0x18, 0x02, 0x20, + 0x01, 0x28, 0x09, 0x52, 0x04, 0x6e, 0x61, 0x6d, 0x65, 0x12, 0x47, 0x0a, 0x05, 0x69, 0x6e, 0x6e, + 0x65, 0x72, 0x18, 0x03, 0x20, 0x01, 0x28, 0x0b, 0x32, 0x31, 0x2e, 0x74, 0x65, 0x73, 0x74, 0x70, + 0x62, 0x2e, 0x54, 0x65, 0x73, 0x74, 0x56, 0x65, 0x72, 0x73, 0x69, 0x6f, 0x6e, 0x34, 0x4c, 0x6f, + 0x6e, 0x65, 0x4e, 0x65, 0x73, 0x74, 0x69, 0x6e, 0x67, 0x2e, 0x49, 0x6e, 0x6e, 0x65, 0x72, 0x31, + 0x2e, 0x49, 0x6e, 0x6e, 0x65, 0x72, 0x49, 0x6e, 0x6e, 0x65, 0x72, 0x52, 0x05, 0x69, 0x6e, 0x6e, + 0x65, 0x72, 0x1a, 0x30, 0x0a, 0x0a, 0x49, 0x6e, 0x6e, 0x65, 0x72, 0x49, 0x6e, 0x6e, 0x65, 0x72, + 0x12, 0x0e, 0x0a, 0x02, 0x69, 0x64, 0x18, 0x01, 0x20, 0x01, 0x28, 0x03, 0x52, 0x02, 0x69, 0x64, + 0x12, 0x12, 0x0a, 0x04, 0x63, 0x69, 0x74, 0x79, 0x18, 0x02, 0x20, 0x01, 0x28, 0x09, 0x52, 0x04, + 0x63, 0x69, 0x74, 0x79, 0x1a, 0xaf, 0x01, 0x0a, 0x06, 0x49, 0x6e, 0x6e, 0x65, 0x72, 0x32, 0x12, + 0x0e, 0x0a, 0x02, 0x69, 0x64, 0x18, 0x01, 0x20, 0x01, 0x28, 0x09, 0x52, 0x02, 0x69, 0x64, 0x12, + 0x18, 0x0a, 0x07, 0x63, 0x6f, 0x75, 0x6e, 0x74, 0x72, 0x79, 0x18, 0x02, 0x20, 0x01, 0x28, 0x09, + 0x52, 0x07, 0x63, 0x6f, 0x75, 0x6e, 0x74, 0x72, 0x79, 0x12, 0x47, 0x0a, 0x05, 0x69, 0x6e, 0x6e, + 0x65, 0x72, 0x18, 0x03, 0x20, 0x01, 0x28, 0x0b, 0x32, 0x31, 0x2e, 0x74, 0x65, 0x73, 0x74, 0x70, + 0x62, 0x2e, 0x54, 0x65, 0x73, 0x74, 0x56, 0x65, 0x72, 0x73, 0x69, 0x6f, 0x6e, 0x34, 0x4c, 0x6f, + 0x6e, 0x65, 0x4e, 0x65, 0x73, 0x74, 0x69, 0x6e, 0x67, 0x2e, 0x49, 0x6e, 0x6e, 0x65, 0x72, 0x32, + 0x2e, 0x49, 0x6e, 0x6e, 0x65, 0x72, 0x49, 0x6e, 0x6e, 0x65, 0x72, 0x52, 0x05, 0x69, 0x6e, 0x6e, + 0x65, 0x72, 0x1a, 0x32, 0x0a, 0x0a, 0x49, 0x6e, 0x6e, 0x65, 0x72, 0x49, 0x6e, 0x6e, 0x65, 0x72, + 0x12, 0x0e, 0x0a, 0x02, 0x69, 0x64, 0x18, 0x01, 0x20, 0x01, 0x28, 0x09, 0x52, 0x02, 0x69, 0x64, + 0x12, 0x14, 0x0a, 0x05, 0x76, 0x61, 0x6c, 0x75, 0x65, 0x18, 0x02, 0x20, 0x01, 0x28, 0x03, 0x52, + 0x05, 0x76, 0x61, 0x6c, 0x75, 0x65, 0x42, 0x05, 0x0a, 0x03, 0x73, 0x75, 0x6d, 0x22, 0xc7, 0x01, + 0x0a, 0x0e, 0x54, 0x65, 0x73, 0x74, 0x56, 0x65, 0x72, 0x73, 0x69, 0x6f, 0x6e, 0x46, 0x44, 0x31, + 0x12, 0x0c, 0x0a, 0x01, 0x78, 0x18, 0x01, 0x20, 0x01, 0x28, 0x03, 0x52, 0x01, 0x78, 0x12, 0x22, + 0x0a, 0x01, 0x61, 0x18, 0x02, 0x20, 0x01, 0x28, 0x0b, 0x32, 0x14, 0x2e, 0x74, 0x65, 0x73, 0x74, + 0x70, 0x62, 0x2e, 0x54, 0x65, 0x73, 0x74, 0x56, 0x65, 0x72, 0x73, 0x69, 0x6f, 0x6e, 0x31, 0x52, + 0x01, 0x61, 0x12, 0x0e, 0x0a, 0x01, 0x65, 0x18, 0x06, 0x20, 0x01, 0x28, 0x05, 0x48, 0x00, 0x52, + 0x01, 0x65, 0x12, 0x24, 0x0a, 0x01, 0x66, 0x18, 0x07, 0x20, 0x01, 0x28, 0x0b, 0x32, 0x14, 0x2e, + 0x74, 0x65, 0x73, 0x74, 0x70, 0x62, 0x2e, 0x54, 0x65, 0x73, 0x74, 0x56, 0x65, 0x72, 0x73, 0x69, + 0x6f, 0x6e, 0x31, 0x48, 0x00, 0x52, 0x01, 0x66, 0x12, 0x22, 0x0a, 0x01, 0x67, 0x18, 0x08, 0x20, + 0x01, 0x28, 0x0b, 0x32, 0x14, 0x2e, 0x67, 0x6f, 0x6f, 0x67, 0x6c, 0x65, 0x2e, 0x70, 0x72, 0x6f, + 0x74, 0x6f, 0x62, 0x75, 0x66, 0x2e, 0x41, 0x6e, 0x79, 0x52, 0x01, 0x67, 0x12, 0x22, 0x0a, 0x01, + 0x68, 0x18, 0x09, 0x20, 0x03, 0x28, 0x0b, 0x32, 0x14, 0x2e, 0x74, 0x65, 0x73, 0x74, 0x70, 0x62, + 0x2e, 0x54, 0x65, 0x73, 0x74, 0x56, 0x65, 0x72, 0x73, 0x69, 0x6f, 0x6e, 0x31, 0x52, 0x01, 0x68, + 0x42, 0x05, 0x0a, 0x03, 0x73, 0x75, 0x6d, 0x22, 0xd3, 0x01, 0x0a, 0x1a, 0x54, 0x65, 0x73, 0x74, + 0x56, 0x65, 0x72, 0x73, 0x69, 0x6f, 0x6e, 0x46, 0x44, 0x31, 0x57, 0x69, 0x74, 0x68, 0x45, 0x78, + 0x74, 0x72, 0x61, 0x41, 0x6e, 0x79, 0x12, 0x0c, 0x0a, 0x01, 0x78, 0x18, 0x01, 0x20, 0x01, 0x28, + 0x03, 0x52, 0x01, 0x78, 0x12, 0x22, 0x0a, 0x01, 0x61, 0x18, 0x02, 0x20, 0x01, 0x28, 0x0b, 0x32, + 0x14, 0x2e, 0x74, 0x65, 0x73, 0x74, 0x70, 0x62, 0x2e, 0x54, 0x65, 0x73, 0x74, 0x56, 0x65, 0x72, + 0x73, 0x69, 0x6f, 0x6e, 0x31, 0x52, 0x01, 0x61, 0x12, 0x0e, 0x0a, 0x01, 0x65, 0x18, 0x06, 0x20, + 0x01, 0x28, 0x05, 0x48, 0x00, 0x52, 0x01, 0x65, 0x12, 0x24, 0x0a, 0x01, 0x66, 0x18, 0x07, 0x20, + 0x01, 0x28, 0x0b, 0x32, 0x14, 0x2e, 0x74, 0x65, 0x73, 0x74, 0x70, 0x62, 0x2e, 0x54, 0x65, 0x73, + 0x74, 0x56, 0x65, 0x72, 0x73, 0x69, 0x6f, 0x6e, 0x31, 0x48, 0x00, 0x52, 0x01, 0x66, 0x12, 0x22, + 0x0a, 0x01, 0x67, 0x18, 0x08, 0x20, 0x01, 0x28, 0x0b, 0x32, 0x14, 0x2e, 0x74, 0x65, 0x73, 0x74, + 0x70, 0x62, 0x2e, 0x41, 0x6e, 0x79, 0x57, 0x69, 0x74, 0x68, 0x45, 0x78, 0x74, 0x72, 0x61, 0x52, + 0x01, 0x67, 0x12, 0x22, 0x0a, 0x01, 0x68, 0x18, 0x09, 0x20, 0x03, 0x28, 0x0b, 0x32, 0x14, 0x2e, + 0x74, 0x65, 0x73, 0x74, 0x70, 0x62, 0x2e, 0x54, 0x65, 0x73, 0x74, 0x56, 0x65, 0x72, 0x73, 0x69, + 0x6f, 0x6e, 0x31, 0x52, 0x01, 0x68, 0x42, 0x05, 0x0a, 0x03, 0x73, 0x75, 0x6d, 0x22, 0x4e, 0x0a, + 0x0c, 0x41, 0x6e, 0x79, 0x57, 0x69, 0x74, 0x68, 0x45, 0x78, 0x74, 0x72, 0x61, 0x12, 0x22, 0x0a, + 0x01, 0x61, 0x18, 0x01, 0x20, 0x01, 0x28, 0x0b, 0x32, 0x14, 0x2e, 0x67, 0x6f, 0x6f, 0x67, 0x6c, + 0x65, 0x2e, 0x70, 0x72, 0x6f, 0x74, 0x6f, 0x62, 0x75, 0x66, 0x2e, 0x41, 0x6e, 0x79, 0x52, 0x01, + 0x61, 0x12, 0x0c, 0x0a, 0x01, 0x62, 0x18, 0x03, 0x20, 0x01, 0x28, 0x03, 0x52, 0x01, 0x62, 0x12, + 0x0c, 0x0a, 0x01, 0x63, 0x18, 0x04, 0x20, 0x01, 0x28, 0x03, 0x52, 0x01, 0x63, 0x22, 0xc0, 0x01, + 0x0a, 0x10, 0x54, 0x65, 0x73, 0x74, 0x55, 0x70, 0x64, 0x61, 0x74, 0x65, 0x64, 0x54, 0x78, 0x52, + 0x61, 0x77, 0x12, 0x1d, 0x0a, 0x0a, 0x62, 0x6f, 0x64, 0x79, 0x5f, 0x62, 0x79, 0x74, 0x65, 0x73, + 0x18, 0x01, 0x20, 0x01, 0x28, 0x0c, 0x52, 0x09, 0x62, 0x6f, 0x64, 0x79, 0x42, 0x79, 0x74, 0x65, + 0x73, 0x12, 0x26, 0x0a, 0x0f, 0x61, 0x75, 0x74, 0x68, 0x5f, 0x69, 0x6e, 0x66, 0x6f, 0x5f, 0x62, + 0x79, 0x74, 0x65, 0x73, 0x18, 0x02, 0x20, 0x01, 0x28, 0x0c, 0x52, 0x0d, 0x61, 0x75, 0x74, 0x68, + 0x49, 0x6e, 0x66, 0x6f, 0x42, 0x79, 0x74, 0x65, 0x73, 0x12, 0x1e, 0x0a, 0x0a, 0x73, 0x69, 0x67, + 0x6e, 0x61, 0x74, 0x75, 0x72, 0x65, 0x73, 0x18, 0x03, 0x20, 0x03, 0x28, 0x0c, 0x52, 0x0a, 0x73, + 0x69, 0x67, 0x6e, 0x61, 0x74, 0x75, 0x72, 0x65, 0x73, 0x12, 0x1e, 0x0a, 0x0b, 0x6e, 0x65, 0x77, + 0x5f, 0x66, 0x69, 0x65, 0x6c, 0x64, 0x5f, 0x35, 0x18, 0x05, 0x20, 0x01, 0x28, 0x0c, 0x52, 0x09, + 0x6e, 0x65, 0x77, 0x46, 0x69, 0x65, 0x6c, 0x64, 0x35, 0x12, 0x25, 0x0a, 0x0e, 0x6e, 0x65, 0x77, + 0x5f, 0x66, 0x69, 0x65, 0x6c, 0x64, 0x5f, 0x31, 0x30, 0x32, 0x34, 0x18, 0x80, 0x08, 0x20, 0x01, + 0x28, 0x0c, 0x52, 0x0c, 0x6e, 0x65, 0x77, 0x46, 0x69, 0x65, 0x6c, 0x64, 0x31, 0x30, 0x32, 0x34, + 0x22, 0x90, 0x03, 0x0a, 0x11, 0x54, 0x65, 0x73, 0x74, 0x55, 0x70, 0x64, 0x61, 0x74, 0x65, 0x64, + 0x54, 0x78, 0x42, 0x6f, 0x64, 0x79, 0x12, 0x30, 0x0a, 0x08, 0x6d, 0x65, 0x73, 0x73, 0x61, 0x67, + 0x65, 0x73, 0x18, 0x01, 0x20, 0x03, 0x28, 0x0b, 0x32, 0x14, 0x2e, 0x67, 0x6f, 0x6f, 0x67, 0x6c, + 0x65, 0x2e, 0x70, 0x72, 0x6f, 0x74, 0x6f, 0x62, 0x75, 0x66, 0x2e, 0x41, 0x6e, 0x79, 0x52, 0x08, + 0x6d, 0x65, 0x73, 0x73, 0x61, 0x67, 0x65, 0x73, 0x12, 0x12, 0x0a, 0x04, 0x6d, 0x65, 0x6d, 0x6f, + 0x18, 0x02, 0x20, 0x01, 0x28, 0x09, 0x52, 0x04, 0x6d, 0x65, 0x6d, 0x6f, 0x12, 0x25, 0x0a, 0x0e, + 0x74, 0x69, 0x6d, 0x65, 0x6f, 0x75, 0x74, 0x5f, 0x68, 0x65, 0x69, 0x67, 0x68, 0x74, 0x18, 0x03, + 0x20, 0x01, 0x28, 0x03, 0x52, 0x0d, 0x74, 0x69, 0x6d, 0x65, 0x6f, 0x75, 0x74, 0x48, 0x65, 0x69, + 0x67, 0x68, 0x74, 0x12, 0x24, 0x0a, 0x0e, 0x73, 0x6f, 0x6d, 0x65, 0x5f, 0x6e, 0x65, 0x77, 0x5f, + 0x66, 0x69, 0x65, 0x6c, 0x64, 0x18, 0x04, 0x20, 0x01, 0x28, 0x04, 0x52, 0x0c, 0x73, 0x6f, 0x6d, + 0x65, 0x4e, 0x65, 0x77, 0x46, 0x69, 0x65, 0x6c, 0x64, 0x12, 0x48, 0x0a, 0x21, 0x73, 0x6f, 0x6d, + 0x65, 0x5f, 0x6e, 0x65, 0x77, 0x5f, 0x66, 0x69, 0x65, 0x6c, 0x64, 0x5f, 0x6e, 0x6f, 0x6e, 0x5f, + 0x63, 0x72, 0x69, 0x74, 0x69, 0x63, 0x61, 0x6c, 0x5f, 0x66, 0x69, 0x65, 0x6c, 0x64, 0x18, 0x9a, + 0x08, 0x20, 0x01, 0x28, 0x09, 0x52, 0x1c, 0x73, 0x6f, 0x6d, 0x65, 0x4e, 0x65, 0x77, 0x46, 0x69, + 0x65, 0x6c, 0x64, 0x4e, 0x6f, 0x6e, 0x43, 0x72, 0x69, 0x74, 0x69, 0x63, 0x61, 0x6c, 0x46, 0x69, + 0x65, 0x6c, 0x64, 0x12, 0x42, 0x0a, 0x11, 0x65, 0x78, 0x74, 0x65, 0x6e, 0x73, 0x69, 0x6f, 0x6e, + 0x5f, 0x6f, 0x70, 0x74, 0x69, 0x6f, 0x6e, 0x73, 0x18, 0xff, 0x07, 0x20, 0x03, 0x28, 0x0b, 0x32, + 0x14, 0x2e, 0x67, 0x6f, 0x6f, 0x67, 0x6c, 0x65, 0x2e, 0x70, 0x72, 0x6f, 0x74, 0x6f, 0x62, 0x75, + 0x66, 0x2e, 0x41, 0x6e, 0x79, 0x52, 0x10, 0x65, 0x78, 0x74, 0x65, 0x6e, 0x73, 0x69, 0x6f, 0x6e, + 0x4f, 0x70, 0x74, 0x69, 0x6f, 0x6e, 0x73, 0x12, 0x5a, 0x0a, 0x1e, 0x6e, 0x6f, 0x6e, 0x5f, 0x63, + 0x72, 0x69, 0x74, 0x69, 0x63, 0x61, 0x6c, 0x5f, 0x65, 0x78, 0x74, 0x65, 0x6e, 0x73, 0x69, 0x6f, + 0x6e, 0x5f, 0x6f, 0x70, 0x74, 0x69, 0x6f, 0x6e, 0x73, 0x18, 0xff, 0x0f, 0x20, 0x03, 0x28, 0x0b, + 0x32, 0x14, 0x2e, 0x67, 0x6f, 0x6f, 0x67, 0x6c, 0x65, 0x2e, 0x70, 0x72, 0x6f, 0x74, 0x6f, 0x62, + 0x75, 0x66, 0x2e, 0x41, 0x6e, 0x79, 0x52, 0x1b, 0x6e, 0x6f, 0x6e, 0x43, 0x72, 0x69, 0x74, 0x69, + 0x63, 0x61, 0x6c, 0x45, 0x78, 0x74, 0x65, 0x6e, 0x73, 0x69, 0x6f, 0x6e, 0x4f, 0x70, 0x74, 0x69, + 0x6f, 0x6e, 0x73, 0x22, 0xc8, 0x01, 0x0a, 0x13, 0x54, 0x65, 0x73, 0x74, 0x55, 0x70, 0x64, 0x61, + 0x74, 0x65, 0x64, 0x41, 0x75, 0x74, 0x68, 0x49, 0x6e, 0x66, 0x6f, 0x12, 0x40, 0x0a, 0x0c, 0x73, + 0x69, 0x67, 0x6e, 0x65, 0x72, 0x5f, 0x69, 0x6e, 0x66, 0x6f, 0x73, 0x18, 0x01, 0x20, 0x03, 0x28, + 0x0b, 0x32, 0x1d, 0x2e, 0x63, 0x6f, 0x73, 0x6d, 0x6f, 0x73, 0x2e, 0x74, 0x78, 0x2e, 0x76, 0x31, + 0x62, 0x65, 0x74, 0x61, 0x31, 0x2e, 0x53, 0x69, 0x67, 0x6e, 0x65, 0x72, 0x49, 0x6e, 0x66, 0x6f, + 0x52, 0x0b, 0x73, 0x69, 0x67, 0x6e, 0x65, 0x72, 0x49, 0x6e, 0x66, 0x6f, 0x73, 0x12, 0x28, 0x0a, + 0x03, 0x66, 0x65, 0x65, 0x18, 0x02, 0x20, 0x01, 0x28, 0x0b, 0x32, 0x16, 0x2e, 0x63, 0x6f, 0x73, + 0x6d, 0x6f, 0x73, 0x2e, 0x74, 0x78, 0x2e, 0x76, 0x31, 0x62, 0x65, 0x74, 0x61, 0x31, 0x2e, 0x46, + 0x65, 0x65, 0x52, 0x03, 0x66, 0x65, 0x65, 0x12, 0x1e, 0x0a, 0x0b, 0x6e, 0x65, 0x77, 0x5f, 0x66, + 0x69, 0x65, 0x6c, 0x64, 0x5f, 0x33, 0x18, 0x03, 0x20, 0x01, 0x28, 0x0c, 0x52, 0x09, 0x6e, 0x65, + 0x77, 0x46, 0x69, 0x65, 0x6c, 0x64, 0x33, 0x12, 0x25, 0x0a, 0x0e, 0x6e, 0x65, 0x77, 0x5f, 0x66, + 0x69, 0x65, 0x6c, 0x64, 0x5f, 0x31, 0x30, 0x32, 0x34, 0x18, 0x80, 0x08, 0x20, 0x01, 0x28, 0x0c, + 0x52, 0x0c, 0x6e, 0x65, 0x77, 0x46, 0x69, 0x65, 0x6c, 0x64, 0x31, 0x30, 0x32, 0x34, 0x22, 0x27, + 0x0a, 0x11, 0x54, 0x65, 0x73, 0x74, 0x52, 0x65, 0x70, 0x65, 0x61, 0x74, 0x65, 0x64, 0x55, 0x69, + 0x6e, 0x74, 0x73, 0x12, 0x12, 0x0a, 0x04, 0x6e, 0x75, 0x6d, 0x73, 0x18, 0x01, 0x20, 0x03, 0x28, + 0x04, 0x52, 0x04, 0x6e, 0x75, 0x6d, 0x73, 0x42, 0x82, 0x01, 0x0a, 0x0a, 0x63, 0x6f, 0x6d, 0x2e, + 0x74, 0x65, 0x73, 0x74, 0x70, 0x62, 0x42, 0x11, 0x55, 0x6e, 0x6b, 0x6e, 0x6f, 0x77, 0x6e, 0x70, + 0x72, 0x6f, 0x74, 0x6f, 0x50, 0x72, 0x6f, 0x74, 0x6f, 0x50, 0x01, 0x5a, 0x29, 0x63, 0x6f, 0x73, + 0x6d, 0x6f, 0x73, 0x73, 0x64, 0x6b, 0x2e, 0x69, 0x6f, 0x2f, 0x78, 0x2f, 0x74, 0x78, 0x2f, 0x74, + 0x65, 0x78, 0x74, 0x75, 0x61, 0x6c, 0x2f, 0x69, 0x6e, 0x74, 0x65, 0x72, 0x6e, 0x61, 0x6c, 0x2f, + 0x74, 0x65, 0x73, 0x74, 0x70, 0x62, 0xa2, 0x02, 0x03, 0x54, 0x58, 0x58, 0xaa, 0x02, 0x06, 0x54, + 0x65, 0x73, 0x74, 0x70, 0x62, 0xca, 0x02, 0x06, 0x54, 0x65, 0x73, 0x74, 0x70, 0x62, 0xe2, 0x02, + 0x12, 0x54, 0x65, 0x73, 0x74, 0x70, 0x62, 0x5c, 0x47, 0x50, 0x42, 0x4d, 0x65, 0x74, 0x61, 0x64, + 0x61, 0x74, 0x61, 0xea, 0x02, 0x06, 0x54, 0x65, 0x73, 0x74, 0x70, 0x62, 0x62, 0x06, 0x70, 0x72, + 0x6f, 0x74, 0x6f, 0x33, +} + +var ( + file_unknownproto_proto_rawDescOnce sync.Once + file_unknownproto_proto_rawDescData = file_unknownproto_proto_rawDesc +) + +func file_unknownproto_proto_rawDescGZIP() []byte { + file_unknownproto_proto_rawDescOnce.Do(func() { + file_unknownproto_proto_rawDescData = protoimpl.X.CompressGZIP(file_unknownproto_proto_rawDescData) + }) + return file_unknownproto_proto_rawDescData +} + +var file_unknownproto_proto_enumTypes = make([]protoimpl.EnumInfo, 1) +var file_unknownproto_proto_msgTypes = make([]protoimpl.MessageInfo, 33) +var file_unknownproto_proto_goTypes = []interface{}{ + (Customer2_City)(0), // 0: testpb.Customer2.City + (*Customer1)(nil), // 1: testpb.Customer1 + (*Customer2)(nil), // 2: testpb.Customer2 + (*Nested4A)(nil), // 3: testpb.Nested4A + (*Nested3A)(nil), // 4: testpb.Nested3A + (*Nested2A)(nil), // 5: testpb.Nested2A + (*Nested1A)(nil), // 6: testpb.Nested1A + (*Nested4B)(nil), // 7: testpb.Nested4B + (*Nested3B)(nil), // 8: testpb.Nested3B + (*Nested2B)(nil), // 9: testpb.Nested2B + (*Nested1B)(nil), // 10: testpb.Nested1B + (*Customer3)(nil), // 11: testpb.Customer3 + (*TestVersion1)(nil), // 12: testpb.TestVersion1 + (*TestVersion2)(nil), // 13: testpb.TestVersion2 + (*TestVersion3)(nil), // 14: testpb.TestVersion3 + (*TestVersion3LoneOneOfValue)(nil), // 15: testpb.TestVersion3LoneOneOfValue + (*TestVersion3LoneNesting)(nil), // 16: testpb.TestVersion3LoneNesting + (*TestVersion4LoneNesting)(nil), // 17: testpb.TestVersion4LoneNesting + (*TestVersionFD1)(nil), // 18: testpb.TestVersionFD1 + (*TestVersionFD1WithExtraAny)(nil), // 19: testpb.TestVersionFD1WithExtraAny + (*AnyWithExtra)(nil), // 20: testpb.AnyWithExtra + (*TestUpdatedTxRaw)(nil), // 21: testpb.TestUpdatedTxRaw + (*TestUpdatedTxBody)(nil), // 22: testpb.TestUpdatedTxBody + (*TestUpdatedAuthInfo)(nil), // 23: testpb.TestUpdatedAuthInfo + (*TestRepeatedUints)(nil), // 24: testpb.TestRepeatedUints + nil, // 25: testpb.Nested3A.IndexEntry + (*TestVersion3LoneNesting_Inner1)(nil), // 26: testpb.TestVersion3LoneNesting.Inner1 + (*TestVersion3LoneNesting_Inner2)(nil), // 27: testpb.TestVersion3LoneNesting.Inner2 + (*TestVersion3LoneNesting_Inner1_InnerInner)(nil), // 28: testpb.TestVersion3LoneNesting.Inner1.InnerInner + (*TestVersion3LoneNesting_Inner2_InnerInner)(nil), // 29: testpb.TestVersion3LoneNesting.Inner2.InnerInner + (*TestVersion4LoneNesting_Inner1)(nil), // 30: testpb.TestVersion4LoneNesting.Inner1 + (*TestVersion4LoneNesting_Inner2)(nil), // 31: testpb.TestVersion4LoneNesting.Inner2 + (*TestVersion4LoneNesting_Inner1_InnerInner)(nil), // 32: testpb.TestVersion4LoneNesting.Inner1.InnerInner + (*TestVersion4LoneNesting_Inner2_InnerInner)(nil), // 33: testpb.TestVersion4LoneNesting.Inner2.InnerInner + (*anypb.Any)(nil), // 34: google.protobuf.Any + (*v1beta1.SignerInfo)(nil), // 35: cosmos.tx.v1beta1.SignerInfo + (*v1beta1.Fee)(nil), // 36: cosmos.tx.v1beta1.Fee +} +var file_unknownproto_proto_depIdxs = []int32{ + 0, // 0: testpb.Customer2.city:type_name -> testpb.Customer2.City + 34, // 1: testpb.Customer2.miscellaneous:type_name -> google.protobuf.Any + 3, // 2: testpb.Nested3A.a4:type_name -> testpb.Nested4A + 25, // 3: testpb.Nested3A.index:type_name -> testpb.Nested3A.IndexEntry + 4, // 4: testpb.Nested2A.nested:type_name -> testpb.Nested3A + 5, // 5: testpb.Nested1A.nested:type_name -> testpb.Nested2A + 7, // 6: testpb.Nested3B.b4:type_name -> testpb.Nested4B + 8, // 7: testpb.Nested2B.nested:type_name -> testpb.Nested3B + 9, // 8: testpb.Nested1B.nested:type_name -> testpb.Nested2B + 1, // 9: testpb.Customer3.original:type_name -> testpb.Customer1 + 12, // 10: testpb.TestVersion1.a:type_name -> testpb.TestVersion1 + 12, // 11: testpb.TestVersion1.b:type_name -> testpb.TestVersion1 + 12, // 12: testpb.TestVersion1.c:type_name -> testpb.TestVersion1 + 12, // 13: testpb.TestVersion1.d:type_name -> testpb.TestVersion1 + 12, // 14: testpb.TestVersion1.f:type_name -> testpb.TestVersion1 + 34, // 15: testpb.TestVersion1.g:type_name -> google.protobuf.Any + 12, // 16: testpb.TestVersion1.h:type_name -> testpb.TestVersion1 + 1, // 17: testpb.TestVersion1.k:type_name -> testpb.Customer1 + 13, // 18: testpb.TestVersion2.a:type_name -> testpb.TestVersion2 + 13, // 19: testpb.TestVersion2.b:type_name -> testpb.TestVersion2 + 13, // 20: testpb.TestVersion2.c:type_name -> testpb.TestVersion2 + 13, // 21: testpb.TestVersion2.d:type_name -> testpb.TestVersion2 + 13, // 22: testpb.TestVersion2.f:type_name -> testpb.TestVersion2 + 34, // 23: testpb.TestVersion2.g:type_name -> google.protobuf.Any + 12, // 24: testpb.TestVersion2.h:type_name -> testpb.TestVersion1 + 1, // 25: testpb.TestVersion2.k:type_name -> testpb.Customer1 + 14, // 26: testpb.TestVersion3.a:type_name -> testpb.TestVersion3 + 14, // 27: testpb.TestVersion3.b:type_name -> testpb.TestVersion3 + 14, // 28: testpb.TestVersion3.c:type_name -> testpb.TestVersion3 + 14, // 29: testpb.TestVersion3.d:type_name -> testpb.TestVersion3 + 14, // 30: testpb.TestVersion3.f:type_name -> testpb.TestVersion3 + 34, // 31: testpb.TestVersion3.g:type_name -> google.protobuf.Any + 12, // 32: testpb.TestVersion3.h:type_name -> testpb.TestVersion1 + 1, // 33: testpb.TestVersion3.k:type_name -> testpb.Customer1 + 14, // 34: testpb.TestVersion3LoneOneOfValue.a:type_name -> testpb.TestVersion3 + 14, // 35: testpb.TestVersion3LoneOneOfValue.b:type_name -> testpb.TestVersion3 + 14, // 36: testpb.TestVersion3LoneOneOfValue.c:type_name -> testpb.TestVersion3 + 14, // 37: testpb.TestVersion3LoneOneOfValue.d:type_name -> testpb.TestVersion3 + 34, // 38: testpb.TestVersion3LoneOneOfValue.g:type_name -> google.protobuf.Any + 12, // 39: testpb.TestVersion3LoneOneOfValue.h:type_name -> testpb.TestVersion1 + 1, // 40: testpb.TestVersion3LoneOneOfValue.k:type_name -> testpb.Customer1 + 14, // 41: testpb.TestVersion3LoneNesting.a:type_name -> testpb.TestVersion3 + 14, // 42: testpb.TestVersion3LoneNesting.b:type_name -> testpb.TestVersion3 + 14, // 43: testpb.TestVersion3LoneNesting.c:type_name -> testpb.TestVersion3 + 14, // 44: testpb.TestVersion3LoneNesting.d:type_name -> testpb.TestVersion3 + 16, // 45: testpb.TestVersion3LoneNesting.f:type_name -> testpb.TestVersion3LoneNesting + 34, // 46: testpb.TestVersion3LoneNesting.g:type_name -> google.protobuf.Any + 12, // 47: testpb.TestVersion3LoneNesting.h:type_name -> testpb.TestVersion1 + 1, // 48: testpb.TestVersion3LoneNesting.k:type_name -> testpb.Customer1 + 26, // 49: testpb.TestVersion3LoneNesting.inner1:type_name -> testpb.TestVersion3LoneNesting.Inner1 + 27, // 50: testpb.TestVersion3LoneNesting.inner2:type_name -> testpb.TestVersion3LoneNesting.Inner2 + 14, // 51: testpb.TestVersion4LoneNesting.a:type_name -> testpb.TestVersion3 + 14, // 52: testpb.TestVersion4LoneNesting.b:type_name -> testpb.TestVersion3 + 14, // 53: testpb.TestVersion4LoneNesting.c:type_name -> testpb.TestVersion3 + 14, // 54: testpb.TestVersion4LoneNesting.d:type_name -> testpb.TestVersion3 + 16, // 55: testpb.TestVersion4LoneNesting.f:type_name -> testpb.TestVersion3LoneNesting + 34, // 56: testpb.TestVersion4LoneNesting.g:type_name -> google.protobuf.Any + 12, // 57: testpb.TestVersion4LoneNesting.h:type_name -> testpb.TestVersion1 + 1, // 58: testpb.TestVersion4LoneNesting.k:type_name -> testpb.Customer1 + 30, // 59: testpb.TestVersion4LoneNesting.inner1:type_name -> testpb.TestVersion4LoneNesting.Inner1 + 31, // 60: testpb.TestVersion4LoneNesting.inner2:type_name -> testpb.TestVersion4LoneNesting.Inner2 + 12, // 61: testpb.TestVersionFD1.a:type_name -> testpb.TestVersion1 + 12, // 62: testpb.TestVersionFD1.f:type_name -> testpb.TestVersion1 + 34, // 63: testpb.TestVersionFD1.g:type_name -> google.protobuf.Any + 12, // 64: testpb.TestVersionFD1.h:type_name -> testpb.TestVersion1 + 12, // 65: testpb.TestVersionFD1WithExtraAny.a:type_name -> testpb.TestVersion1 + 12, // 66: testpb.TestVersionFD1WithExtraAny.f:type_name -> testpb.TestVersion1 + 20, // 67: testpb.TestVersionFD1WithExtraAny.g:type_name -> testpb.AnyWithExtra + 12, // 68: testpb.TestVersionFD1WithExtraAny.h:type_name -> testpb.TestVersion1 + 34, // 69: testpb.AnyWithExtra.a:type_name -> google.protobuf.Any + 34, // 70: testpb.TestUpdatedTxBody.messages:type_name -> google.protobuf.Any + 34, // 71: testpb.TestUpdatedTxBody.extension_options:type_name -> google.protobuf.Any + 34, // 72: testpb.TestUpdatedTxBody.non_critical_extension_options:type_name -> google.protobuf.Any + 35, // 73: testpb.TestUpdatedAuthInfo.signer_infos:type_name -> cosmos.tx.v1beta1.SignerInfo + 36, // 74: testpb.TestUpdatedAuthInfo.fee:type_name -> cosmos.tx.v1beta1.Fee + 3, // 75: testpb.Nested3A.IndexEntry.value:type_name -> testpb.Nested4A + 28, // 76: testpb.TestVersion3LoneNesting.Inner1.inner:type_name -> testpb.TestVersion3LoneNesting.Inner1.InnerInner + 29, // 77: testpb.TestVersion3LoneNesting.Inner2.inner:type_name -> testpb.TestVersion3LoneNesting.Inner2.InnerInner + 32, // 78: testpb.TestVersion4LoneNesting.Inner1.inner:type_name -> testpb.TestVersion4LoneNesting.Inner1.InnerInner + 33, // 79: testpb.TestVersion4LoneNesting.Inner2.inner:type_name -> testpb.TestVersion4LoneNesting.Inner2.InnerInner + 80, // [80:80] is the sub-list for method output_type + 80, // [80:80] is the sub-list for method input_type + 80, // [80:80] is the sub-list for extension type_name + 80, // [80:80] is the sub-list for extension extendee + 0, // [0:80] is the sub-list for field type_name +} + +func init() { file_unknownproto_proto_init() } +func file_unknownproto_proto_init() { + if File_unknownproto_proto != nil { + return + } + if !protoimpl.UnsafeEnabled { + file_unknownproto_proto_msgTypes[0].Exporter = func(v interface{}, i int) interface{} { + switch v := v.(*Customer1); i { + case 0: + return &v.state + case 1: + return &v.sizeCache + case 2: + return &v.unknownFields + default: + return nil + } + } + file_unknownproto_proto_msgTypes[1].Exporter = func(v interface{}, i int) interface{} { + switch v := v.(*Customer2); i { + case 0: + return &v.state + case 1: + return &v.sizeCache + case 2: + return &v.unknownFields + default: + return nil + } + } + file_unknownproto_proto_msgTypes[2].Exporter = func(v interface{}, i int) interface{} { + switch v := v.(*Nested4A); i { + case 0: + return &v.state + case 1: + return &v.sizeCache + case 2: + return &v.unknownFields + default: + return nil + } + } + file_unknownproto_proto_msgTypes[3].Exporter = func(v interface{}, i int) interface{} { + switch v := v.(*Nested3A); i { + case 0: + return &v.state + case 1: + return &v.sizeCache + case 2: + return &v.unknownFields + default: + return nil + } + } + file_unknownproto_proto_msgTypes[4].Exporter = func(v interface{}, i int) interface{} { + switch v := v.(*Nested2A); i { + case 0: + return &v.state + case 1: + return &v.sizeCache + case 2: + return &v.unknownFields + default: + return nil + } + } + file_unknownproto_proto_msgTypes[5].Exporter = func(v interface{}, i int) interface{} { + switch v := v.(*Nested1A); i { + case 0: + return &v.state + case 1: + return &v.sizeCache + case 2: + return &v.unknownFields + default: + return nil + } + } + file_unknownproto_proto_msgTypes[6].Exporter = func(v interface{}, i int) interface{} { + switch v := v.(*Nested4B); i { + case 0: + return &v.state + case 1: + return &v.sizeCache + case 2: + return &v.unknownFields + default: + return nil + } + } + file_unknownproto_proto_msgTypes[7].Exporter = func(v interface{}, i int) interface{} { + switch v := v.(*Nested3B); i { + case 0: + return &v.state + case 1: + return &v.sizeCache + case 2: + return &v.unknownFields + default: + return nil + } + } + file_unknownproto_proto_msgTypes[8].Exporter = func(v interface{}, i int) interface{} { + switch v := v.(*Nested2B); i { + case 0: + return &v.state + case 1: + return &v.sizeCache + case 2: + return &v.unknownFields + default: + return nil + } + } + file_unknownproto_proto_msgTypes[9].Exporter = func(v interface{}, i int) interface{} { + switch v := v.(*Nested1B); i { + case 0: + return &v.state + case 1: + return &v.sizeCache + case 2: + return &v.unknownFields + default: + return nil + } + } + file_unknownproto_proto_msgTypes[10].Exporter = func(v interface{}, i int) interface{} { + switch v := v.(*Customer3); i { + case 0: + return &v.state + case 1: + return &v.sizeCache + case 2: + return &v.unknownFields + default: + return nil + } + } + file_unknownproto_proto_msgTypes[11].Exporter = func(v interface{}, i int) interface{} { + switch v := v.(*TestVersion1); i { + case 0: + return &v.state + case 1: + return &v.sizeCache + case 2: + return &v.unknownFields + default: + return nil + } + } + file_unknownproto_proto_msgTypes[12].Exporter = func(v interface{}, i int) interface{} { + switch v := v.(*TestVersion2); i { + case 0: + return &v.state + case 1: + return &v.sizeCache + case 2: + return &v.unknownFields + default: + return nil + } + } + file_unknownproto_proto_msgTypes[13].Exporter = func(v interface{}, i int) interface{} { + switch v := v.(*TestVersion3); i { + case 0: + return &v.state + case 1: + return &v.sizeCache + case 2: + return &v.unknownFields + default: + return nil + } + } + file_unknownproto_proto_msgTypes[14].Exporter = func(v interface{}, i int) interface{} { + switch v := v.(*TestVersion3LoneOneOfValue); i { + case 0: + return &v.state + case 1: + return &v.sizeCache + case 2: + return &v.unknownFields + default: + return nil + } + } + file_unknownproto_proto_msgTypes[15].Exporter = func(v interface{}, i int) interface{} { + switch v := v.(*TestVersion3LoneNesting); i { + case 0: + return &v.state + case 1: + return &v.sizeCache + case 2: + return &v.unknownFields + default: + return nil + } + } + file_unknownproto_proto_msgTypes[16].Exporter = func(v interface{}, i int) interface{} { + switch v := v.(*TestVersion4LoneNesting); i { + case 0: + return &v.state + case 1: + return &v.sizeCache + case 2: + return &v.unknownFields + default: + return nil + } + } + file_unknownproto_proto_msgTypes[17].Exporter = func(v interface{}, i int) interface{} { + switch v := v.(*TestVersionFD1); i { + case 0: + return &v.state + case 1: + return &v.sizeCache + case 2: + return &v.unknownFields + default: + return nil + } + } + file_unknownproto_proto_msgTypes[18].Exporter = func(v interface{}, i int) interface{} { + switch v := v.(*TestVersionFD1WithExtraAny); i { + case 0: + return &v.state + case 1: + return &v.sizeCache + case 2: + return &v.unknownFields + default: + return nil + } + } + file_unknownproto_proto_msgTypes[19].Exporter = func(v interface{}, i int) interface{} { + switch v := v.(*AnyWithExtra); i { + case 0: + return &v.state + case 1: + return &v.sizeCache + case 2: + return &v.unknownFields + default: + return nil + } + } + file_unknownproto_proto_msgTypes[20].Exporter = func(v interface{}, i int) interface{} { + switch v := v.(*TestUpdatedTxRaw); i { + case 0: + return &v.state + case 1: + return &v.sizeCache + case 2: + return &v.unknownFields + default: + return nil + } + } + file_unknownproto_proto_msgTypes[21].Exporter = func(v interface{}, i int) interface{} { + switch v := v.(*TestUpdatedTxBody); i { + case 0: + return &v.state + case 1: + return &v.sizeCache + case 2: + return &v.unknownFields + default: + return nil + } + } + file_unknownproto_proto_msgTypes[22].Exporter = func(v interface{}, i int) interface{} { + switch v := v.(*TestUpdatedAuthInfo); i { + case 0: + return &v.state + case 1: + return &v.sizeCache + case 2: + return &v.unknownFields + default: + return nil + } + } + file_unknownproto_proto_msgTypes[23].Exporter = func(v interface{}, i int) interface{} { + switch v := v.(*TestRepeatedUints); i { + case 0: + return &v.state + case 1: + return &v.sizeCache + case 2: + return &v.unknownFields + default: + return nil + } + } + file_unknownproto_proto_msgTypes[25].Exporter = func(v interface{}, i int) interface{} { + switch v := v.(*TestVersion3LoneNesting_Inner1); i { + case 0: + return &v.state + case 1: + return &v.sizeCache + case 2: + return &v.unknownFields + default: + return nil + } + } + file_unknownproto_proto_msgTypes[26].Exporter = func(v interface{}, i int) interface{} { + switch v := v.(*TestVersion3LoneNesting_Inner2); i { + case 0: + return &v.state + case 1: + return &v.sizeCache + case 2: + return &v.unknownFields + default: + return nil + } + } + file_unknownproto_proto_msgTypes[27].Exporter = func(v interface{}, i int) interface{} { + switch v := v.(*TestVersion3LoneNesting_Inner1_InnerInner); i { + case 0: + return &v.state + case 1: + return &v.sizeCache + case 2: + return &v.unknownFields + default: + return nil + } + } + file_unknownproto_proto_msgTypes[28].Exporter = func(v interface{}, i int) interface{} { + switch v := v.(*TestVersion3LoneNesting_Inner2_InnerInner); i { + case 0: + return &v.state + case 1: + return &v.sizeCache + case 2: + return &v.unknownFields + default: + return nil + } + } + file_unknownproto_proto_msgTypes[29].Exporter = func(v interface{}, i int) interface{} { + switch v := v.(*TestVersion4LoneNesting_Inner1); i { + case 0: + return &v.state + case 1: + return &v.sizeCache + case 2: + return &v.unknownFields + default: + return nil + } + } + file_unknownproto_proto_msgTypes[30].Exporter = func(v interface{}, i int) interface{} { + switch v := v.(*TestVersion4LoneNesting_Inner2); i { + case 0: + return &v.state + case 1: + return &v.sizeCache + case 2: + return &v.unknownFields + default: + return nil + } + } + file_unknownproto_proto_msgTypes[31].Exporter = func(v interface{}, i int) interface{} { + switch v := v.(*TestVersion4LoneNesting_Inner1_InnerInner); i { + case 0: + return &v.state + case 1: + return &v.sizeCache + case 2: + return &v.unknownFields + default: + return nil + } + } + file_unknownproto_proto_msgTypes[32].Exporter = func(v interface{}, i int) interface{} { + switch v := v.(*TestVersion4LoneNesting_Inner2_InnerInner); i { + case 0: + return &v.state + case 1: + return &v.sizeCache + case 2: + return &v.unknownFields + default: + return nil + } + } + } + file_unknownproto_proto_msgTypes[10].OneofWrappers = []interface{}{ + (*Customer3_CreditCardNo)(nil), + (*Customer3_ChequeNo)(nil), + } + file_unknownproto_proto_msgTypes[11].OneofWrappers = []interface{}{ + (*TestVersion1_E)(nil), + (*TestVersion1_F)(nil), + } + file_unknownproto_proto_msgTypes[12].OneofWrappers = []interface{}{ + (*TestVersion2_E)(nil), + (*TestVersion2_F)(nil), + } + file_unknownproto_proto_msgTypes[13].OneofWrappers = []interface{}{ + (*TestVersion3_E)(nil), + (*TestVersion3_F)(nil), + } + file_unknownproto_proto_msgTypes[14].OneofWrappers = []interface{}{ + (*TestVersion3LoneOneOfValue_E)(nil), + } + file_unknownproto_proto_msgTypes[15].OneofWrappers = []interface{}{ + (*TestVersion3LoneNesting_F)(nil), + } + file_unknownproto_proto_msgTypes[16].OneofWrappers = []interface{}{ + (*TestVersion4LoneNesting_F)(nil), + } + file_unknownproto_proto_msgTypes[17].OneofWrappers = []interface{}{ + (*TestVersionFD1_E)(nil), + (*TestVersionFD1_F)(nil), + } + file_unknownproto_proto_msgTypes[18].OneofWrappers = []interface{}{ + (*TestVersionFD1WithExtraAny_E)(nil), + (*TestVersionFD1WithExtraAny_F)(nil), + } + type x struct{} + out := protoimpl.TypeBuilder{ + File: protoimpl.DescBuilder{ + GoPackagePath: reflect.TypeOf(x{}).PkgPath(), + RawDescriptor: file_unknownproto_proto_rawDesc, + NumEnums: 1, + NumMessages: 33, + NumExtensions: 0, + NumServices: 0, + }, + GoTypes: file_unknownproto_proto_goTypes, + DependencyIndexes: file_unknownproto_proto_depIdxs, + EnumInfos: file_unknownproto_proto_enumTypes, + MessageInfos: file_unknownproto_proto_msgTypes, + }.Build() + File_unknownproto_proto = out.File + file_unknownproto_proto_rawDesc = nil + file_unknownproto_proto_goTypes = nil + file_unknownproto_proto_depIdxs = nil +} diff --git a/x/tx/signing/aminojson/aminojson.go b/x/tx/signing/aminojson/aminojson.go new file mode 100644 index 000000000000..8fa486f88738 --- /dev/null +++ b/x/tx/signing/aminojson/aminojson.go @@ -0,0 +1,132 @@ +package aminojson + +import ( + "context" + "encoding/json" + "fmt" + + "google.golang.org/protobuf/reflect/protodesc" + "google.golang.org/protobuf/reflect/protoregistry" + + signingv1beta1 "cosmossdk.io/api/cosmos/tx/signing/v1beta1" + "cosmossdk.io/x/tx/decode" + "cosmossdk.io/x/tx/signing" + "cosmossdk.io/x/tx/signing/aminojson/internal/aminojsonpb" +) + +// SignModeHandler implements the SIGN_MODE_LEGACY_AMINO_JSON signing mode. +type SignModeHandler struct { + fileResolver protodesc.Resolver + typeResolver protoregistry.MessageTypeResolver + encoder Encoder +} + +// SignModeHandlerOptions are the options for the SignModeHandler. +type SignModeHandlerOptions struct { + FileResolver protodesc.Resolver + TypeResolver protoregistry.MessageTypeResolver + Encoder *Encoder +} + +// NewSignModeHandler returns a new SignModeHandler. +func NewSignModeHandler(options SignModeHandlerOptions) *SignModeHandler { + h := &SignModeHandler{} + if options.FileResolver == nil { + h.fileResolver = protoregistry.GlobalFiles + } else { + h.fileResolver = options.FileResolver + } + if options.TypeResolver == nil { + h.typeResolver = protoregistry.GlobalTypes + } else { + h.typeResolver = options.TypeResolver + } + if options.Encoder == nil { + h.encoder = NewAminoJSON() + } else { + h.encoder = *options.Encoder + } + return h +} + +// Mode implements the Mode method of the SignModeHandler interface. +func (h SignModeHandler) Mode() signingv1beta1.SignMode { + return signingv1beta1.SignMode_SIGN_MODE_LEGACY_AMINO_JSON +} + +// GetSignBytes implements the GetSignBytes method of the SignModeHandler interface. +func (h SignModeHandler) GetSignBytes(_ context.Context, signerData signing.SignerData, txData signing.TxData) ([]byte, error) { + body := txData.Body + _, err := decode.RejectUnknownFields( + txData.BodyBytes, body.ProtoReflect().Descriptor(), false, h.fileResolver) + if err != nil { + return nil, err + } + + if (len(body.ExtensionOptions) > 0) || (len(body.NonCriticalExtensionOptions) > 0) { + return nil, fmt.Errorf("%s does not support protobuf extension options: invalid request", h.Mode()) + } + + if signerData.Address == "" { + return nil, fmt.Errorf("got empty address in %s handler: invalid request", h.Mode()) + } + + tip := txData.AuthInfo.Tip + if tip != nil && tip.Tipper == "" { + return nil, fmt.Errorf("tipper cannot be empty") + } + isTipper := tip != nil && tip.Tipper == signerData.Address + + // We set a convention that if the tipper signs with LEGACY_AMINO_JSON, then + // they sign over empty fees and 0 gas. + var fee *aminojsonpb.AminoSignFee + if isTipper { + fee = &aminojsonpb.AminoSignFee{ + Amount: nil, + Gas: 0, + } + } else { + f := txData.AuthInfo.Fee + if f == nil { + return nil, fmt.Errorf("fee cannot be nil when tipper is not signer") + } + fee = &aminojsonpb.AminoSignFee{ + Amount: f.Amount, + Gas: f.GasLimit, + Payer: f.Payer, + Granter: f.Granter, + } + } + + signDoc := &aminojsonpb.AminoSignDoc{ + AccountNumber: signerData.AccountNumber, + TimeoutHeight: body.TimeoutHeight, + ChainId: signerData.ChainID, + Sequence: signerData.Sequence, + Memo: body.Memo, + Msgs: txData.Body.Messages, + Fee: fee, + } + + bz, err := h.encoder.Marshal(signDoc) + if err != nil { + return nil, err + } + return sortJSON(bz) +} + +// sortJSON sorts the JSON keys of the given JSON encoded byte slice. +func sortJSON(toSortJSON []byte) ([]byte, error) { + var c interface{} + err := json.Unmarshal(toSortJSON, &c) + if err != nil { + return nil, err + } + js, err := json.Marshal(c) + if err != nil { + return nil, err + } + return js, nil +} + +var _ signing.SignModeHandler = (*SignModeHandler)(nil) diff --git a/x/tx/signing/aminojson/aminojson_test.go b/x/tx/signing/aminojson/aminojson_test.go new file mode 100644 index 000000000000..10de8d1c4303 --- /dev/null +++ b/x/tx/signing/aminojson/aminojson_test.go @@ -0,0 +1,116 @@ +package aminojson_test + +import ( + "context" + "testing" + + "github.com/stretchr/testify/require" + "google.golang.org/protobuf/reflect/protoregistry" + + bankv1beta1 "cosmossdk.io/api/cosmos/bank/v1beta1" + basev1beta1 "cosmossdk.io/api/cosmos/base/v1beta1" + txv1beta1 "cosmossdk.io/api/cosmos/tx/v1beta1" + "cosmossdk.io/x/tx/signing/aminojson" + "cosmossdk.io/x/tx/signing/testutil" +) + +func TestAminoJsonSignMode(t *testing.T) { + fee := &txv1beta1.Fee{ + Amount: []*basev1beta1.Coin{{Denom: "uatom", Amount: "1000"}}, + } + handlerOptions := testutil.HandlerArgumentOptions{ + ChainID: "test-chain", + Memo: "sometestmemo", + Tip: &txv1beta1.Tip{Tipper: "tipper", Amount: []*basev1beta1.Coin{{Denom: "Tip-token", Amount: "10"}}}, + Msg: &bankv1beta1.MsgSend{ + FromAddress: "foo", + ToAddress: "bar", + Amount: []*basev1beta1.Coin{{Denom: "demon", Amount: "100"}}, + }, + AccNum: 1, + AccSeq: 2, + SignerAddress: "signerAddress", + Fee: fee, + } + + testCases := []struct { + name string + malleate func(opts testutil.HandlerArgumentOptions) testutil.HandlerArgumentOptions + error string + }{ + { + name: "happy path", + malleate: func(opts testutil.HandlerArgumentOptions) testutil.HandlerArgumentOptions { + return opts + }, + }, + { + name: "empty signer", + malleate: func(opts testutil.HandlerArgumentOptions) testutil.HandlerArgumentOptions { + opts.SignerAddress = "" + return opts + }, + error: "got empty address in SIGN_MODE_LEGACY_AMINO_JSON handler: invalid request", + }, + { + name: "nil tip", + malleate: func(opts testutil.HandlerArgumentOptions) testutil.HandlerArgumentOptions { + opts.Tip = nil + return opts + }, + }, + { + name: "empty tipper", + malleate: func(opts testutil.HandlerArgumentOptions) testutil.HandlerArgumentOptions { + opts.Tip.Tipper = "" + return opts + }, + error: "tipper cannot be empty", + }, + { + name: "nil fee", + malleate: func(opts testutil.HandlerArgumentOptions) testutil.HandlerArgumentOptions { + opts.Tip.Tipper = "tipper" + opts.Fee = nil + return opts + }, + error: "fee cannot be nil", + }, + { + name: "tipper is signer", + malleate: func(opts testutil.HandlerArgumentOptions) testutil.HandlerArgumentOptions { + opts.Tip.Tipper = opts.SignerAddress + return opts + }, + }, + } + + for _, tc := range testCases { + t.Run(tc.name, func(t *testing.T) { + opts := tc.malleate(handlerOptions) + signerData, txData, err := testutil.MakeHandlerArguments(opts) + require.NoError(t, err) + + handler := aminojson.NewSignModeHandler(aminojson.SignModeHandlerOptions{}) + _, err = handler.GetSignBytes(context.Background(), signerData, txData) + if tc.error != "" { + require.Error(t, err) + require.Contains(t, err.Error(), tc.error) + return + } + require.NoError(t, err) + }) + } +} + +func TestNewSignModeHandler(t *testing.T) { + handler := aminojson.NewSignModeHandler(aminojson.SignModeHandlerOptions{}) + require.NotNil(t, handler) + aj := aminojson.NewAminoJSON() + handler = aminojson.NewSignModeHandler(aminojson.SignModeHandlerOptions{ + FileResolver: protoregistry.GlobalFiles, + TypeResolver: protoregistry.GlobalTypes, + Encoder: &aj, + }) + require.NotNil(t, handler) +} diff --git a/x/tx/signing/aminojson/internal/Makefile b/x/tx/signing/aminojson/internal/Makefile index cb1280a5c1f9..6eb4420b60d2 100644 --- a/x/tx/signing/aminojson/internal/Makefile +++ b/x/tx/signing/aminojson/internal/Makefile @@ -1,3 +1,3 @@ codegen: @echo "Generating proto files" - buf generate \ No newline at end of file + @buf generate \ No newline at end of file diff --git a/x/tx/signing/aminojson/internal/aminojsonpb/aminojson.proto b/x/tx/signing/aminojson/internal/aminojsonpb/aminojson.proto new file mode 100644 index 000000000000..f65dab93f092 --- /dev/null +++ b/x/tx/signing/aminojson/internal/aminojsonpb/aminojson.proto @@ -0,0 +1,30 @@ +syntax = "proto3"; + +import "cosmos_proto/cosmos.proto"; +import "amino/amino.proto"; +import "cosmos/base/v1beta1/coin.proto"; +import "google/protobuf/any.proto"; +import "cosmos/tx/v1beta1/tx.proto"; + +// AminoSignFee is the legacy amino json sign mode compatible version of txv1beta1.Fee, and differs from that message +// by the name of the Gas field (GasLimit in txv1beta.Fee). +// Note: this is only used for signing, see x/tx/signing/aminojson.go for more details. +message AminoSignFee { + repeated cosmos.base.v1beta1.Coin amount = 1 [(amino.dont_omitempty) = true, (amino.encoding) = "legacy_coins"]; + uint64 gas = 2 [(amino.dont_omitempty) = true]; + string payer = 3; + string granter = 4; +} + +// AminoSignDoc is a message container used to generate the SIGN_MODE_LEGACY_AMINO_JSON sign bytes with proto3 API. +// Note: This is only used for generated JSON in signing, see x/tx/signing/aminojson.go for more details. +message AminoSignDoc { + uint64 account_number = 1; + uint64 sequence = 2; + uint64 timeout_height = 3; + string chain_id = 4; + string memo = 5; + AminoSignFee fee = 6; + repeated google.protobuf.Any msgs = 7; + cosmos.tx.v1beta1.Tip tip = 8; +} \ No newline at end of file diff --git a/x/tx/signing/aminojson/internal/aminojsonpb/aminojson.pulsar.go b/x/tx/signing/aminojson/internal/aminojsonpb/aminojson.pulsar.go new file mode 100644 index 000000000000..370dc738b34d --- /dev/null +++ b/x/tx/signing/aminojson/internal/aminojsonpb/aminojson.pulsar.go @@ -0,0 +1,1912 @@ +// Code generated by protoc-gen-go-pulsar. DO NOT EDIT. +package aminojsonpb + +import ( + _ "cosmossdk.io/api/amino" + v1beta1 "cosmossdk.io/api/cosmos/base/v1beta1" + v1beta11 "cosmossdk.io/api/cosmos/tx/v1beta1" + fmt "fmt" + _ "github.com/cosmos/cosmos-proto" + runtime "github.com/cosmos/cosmos-proto/runtime" + protoreflect "google.golang.org/protobuf/reflect/protoreflect" + protoiface "google.golang.org/protobuf/runtime/protoiface" + protoimpl "google.golang.org/protobuf/runtime/protoimpl" + anypb "google.golang.org/protobuf/types/known/anypb" + io "io" + reflect "reflect" + sync "sync" +) + +var _ protoreflect.List = (*_AminoSignFee_1_list)(nil) + +type _AminoSignFee_1_list struct { + list *[]*v1beta1.Coin +} + +func (x *_AminoSignFee_1_list) Len() int { + if x.list == nil { + return 0 + } + return len(*x.list) +} + +func (x *_AminoSignFee_1_list) Get(i int) protoreflect.Value { + return protoreflect.ValueOfMessage((*x.list)[i].ProtoReflect()) +} + +func (x *_AminoSignFee_1_list) Set(i int, value protoreflect.Value) { + valueUnwrapped := value.Message() + concreteValue := valueUnwrapped.Interface().(*v1beta1.Coin) + (*x.list)[i] = concreteValue +} + +func (x *_AminoSignFee_1_list) Append(value protoreflect.Value) { + valueUnwrapped := value.Message() + concreteValue := valueUnwrapped.Interface().(*v1beta1.Coin) + *x.list = append(*x.list, concreteValue) +} + +func (x *_AminoSignFee_1_list) AppendMutable() protoreflect.Value { + v := new(v1beta1.Coin) + *x.list = append(*x.list, v) + return protoreflect.ValueOfMessage(v.ProtoReflect()) +} + +func (x *_AminoSignFee_1_list) Truncate(n int) { + for i := n; i < len(*x.list); i++ { + (*x.list)[i] = nil + } + *x.list = (*x.list)[:n] +} + +func (x *_AminoSignFee_1_list) NewElement() protoreflect.Value { + v := new(v1beta1.Coin) + return protoreflect.ValueOfMessage(v.ProtoReflect()) +} + +func (x *_AminoSignFee_1_list) IsValid() bool { + return x.list != nil +} + +var ( + md_AminoSignFee protoreflect.MessageDescriptor + fd_AminoSignFee_amount protoreflect.FieldDescriptor + fd_AminoSignFee_gas protoreflect.FieldDescriptor + fd_AminoSignFee_payer protoreflect.FieldDescriptor + fd_AminoSignFee_granter protoreflect.FieldDescriptor +) + +func init() { + file_aminojsonpb_aminojson_proto_init() + md_AminoSignFee = File_aminojsonpb_aminojson_proto.Messages().ByName("AminoSignFee") + fd_AminoSignFee_amount = md_AminoSignFee.Fields().ByName("amount") + fd_AminoSignFee_gas = md_AminoSignFee.Fields().ByName("gas") + fd_AminoSignFee_payer = md_AminoSignFee.Fields().ByName("payer") + fd_AminoSignFee_granter = md_AminoSignFee.Fields().ByName("granter") +} + +var _ protoreflect.Message = (*fastReflection_AminoSignFee)(nil) + +type fastReflection_AminoSignFee AminoSignFee + +func (x *AminoSignFee) ProtoReflect() protoreflect.Message { + return (*fastReflection_AminoSignFee)(x) +} + +func (x *AminoSignFee) slowProtoReflect() protoreflect.Message { + mi := &file_aminojsonpb_aminojson_proto_msgTypes[0] + if protoimpl.UnsafeEnabled && x != nil { + ms := protoimpl.X.MessageStateOf(protoimpl.Pointer(x)) + if ms.LoadMessageInfo() == nil { + ms.StoreMessageInfo(mi) + } + return ms + } + return mi.MessageOf(x) +} + +var _fastReflection_AminoSignFee_messageType fastReflection_AminoSignFee_messageType +var _ protoreflect.MessageType = fastReflection_AminoSignFee_messageType{} + +type fastReflection_AminoSignFee_messageType struct{} + +func (x fastReflection_AminoSignFee_messageType) Zero() protoreflect.Message { + return (*fastReflection_AminoSignFee)(nil) +} +func (x fastReflection_AminoSignFee_messageType) New() protoreflect.Message { + return new(fastReflection_AminoSignFee) +} +func (x fastReflection_AminoSignFee_messageType) Descriptor() protoreflect.MessageDescriptor { + return md_AminoSignFee +} + +// Descriptor returns message descriptor, which contains only the protobuf +// type information for the message. +func (x *fastReflection_AminoSignFee) Descriptor() protoreflect.MessageDescriptor { + return md_AminoSignFee +} + +// Type returns the message type, which encapsulates both Go and protobuf +// type information. If the Go type information is not needed, +// it is recommended that the message descriptor be used instead. +func (x *fastReflection_AminoSignFee) Type() protoreflect.MessageType { + return _fastReflection_AminoSignFee_messageType +} + +// New returns a newly allocated and mutable empty message. +func (x *fastReflection_AminoSignFee) New() protoreflect.Message { + return new(fastReflection_AminoSignFee) +} + +// Interface unwraps the message reflection interface and +// returns the underlying ProtoMessage interface. +func (x *fastReflection_AminoSignFee) Interface() protoreflect.ProtoMessage { + return (*AminoSignFee)(x) +} + +// Range iterates over every populated field in an undefined order, +// calling f for each field descriptor and value encountered. +// Range returns immediately if f returns false. +// While iterating, mutating operations may only be performed +// on the current field descriptor. +func (x *fastReflection_AminoSignFee) Range(f func(protoreflect.FieldDescriptor, protoreflect.Value) bool) { + if len(x.Amount) != 0 { + value := protoreflect.ValueOfList(&_AminoSignFee_1_list{list: &x.Amount}) + if !f(fd_AminoSignFee_amount, value) { + return + } + } + if x.Gas != uint64(0) { + value := protoreflect.ValueOfUint64(x.Gas) + if !f(fd_AminoSignFee_gas, value) { + return + } + } + if x.Payer != "" { + value := protoreflect.ValueOfString(x.Payer) + if !f(fd_AminoSignFee_payer, value) { + return + } + } + if x.Granter != "" { + value := protoreflect.ValueOfString(x.Granter) + if !f(fd_AminoSignFee_granter, value) { + return + } + } +} + +// Has reports whether a field is populated. +// +// Some fields have the property of nullability where it is possible to +// distinguish between the default value of a field and whether the field +// was explicitly populated with the default value. Singular message fields, +// member fields of a oneof, and proto2 scalar fields are nullable. Such +// fields are populated only if explicitly set. +// +// In other cases (aside from the nullable cases above), +// a proto3 scalar field is populated if it contains a non-zero value, and +// a repeated field is populated if it is non-empty. +func (x *fastReflection_AminoSignFee) Has(fd protoreflect.FieldDescriptor) bool { + switch fd.FullName() { + case "AminoSignFee.amount": + return len(x.Amount) != 0 + case "AminoSignFee.gas": + return x.Gas != uint64(0) + case "AminoSignFee.payer": + return x.Payer != "" + case "AminoSignFee.granter": + return x.Granter != "" + default: + if fd.IsExtension() { + panic(fmt.Errorf("proto3 declared messages do not support extensions: AminoSignFee")) + } + panic(fmt.Errorf("message AminoSignFee does not contain field %s", fd.FullName())) + } +} + +// Clear clears the field such that a subsequent Has call reports false. +// +// Clearing an extension field clears both the extension type and value +// associated with the given field number. +// +// Clear is a mutating operation and unsafe for concurrent use. +func (x *fastReflection_AminoSignFee) Clear(fd protoreflect.FieldDescriptor) { + switch fd.FullName() { + case "AminoSignFee.amount": + x.Amount = nil + case "AminoSignFee.gas": + x.Gas = uint64(0) + case "AminoSignFee.payer": + x.Payer = "" + case "AminoSignFee.granter": + x.Granter = "" + default: + if fd.IsExtension() { + panic(fmt.Errorf("proto3 declared messages do not support extensions: AminoSignFee")) + } + panic(fmt.Errorf("message AminoSignFee does not contain field %s", fd.FullName())) + } +} + +// Get retrieves the value for a field. +// +// For unpopulated scalars, it returns the default value, where +// the default value of a bytes scalar is guaranteed to be a copy. +// For unpopulated composite types, it returns an empty, read-only view +// of the value; to obtain a mutable reference, use Mutable. +func (x *fastReflection_AminoSignFee) Get(descriptor protoreflect.FieldDescriptor) protoreflect.Value { + switch descriptor.FullName() { + case "AminoSignFee.amount": + if len(x.Amount) == 0 { + return protoreflect.ValueOfList(&_AminoSignFee_1_list{}) + } + listValue := &_AminoSignFee_1_list{list: &x.Amount} + return protoreflect.ValueOfList(listValue) + case "AminoSignFee.gas": + value := x.Gas + return protoreflect.ValueOfUint64(value) + case "AminoSignFee.payer": + value := x.Payer + return protoreflect.ValueOfString(value) + case "AminoSignFee.granter": + value := x.Granter + return protoreflect.ValueOfString(value) + default: + if descriptor.IsExtension() { + panic(fmt.Errorf("proto3 declared messages do not support extensions: AminoSignFee")) + } + panic(fmt.Errorf("message AminoSignFee does not contain field %s", descriptor.FullName())) + } +} + +// Set stores the value for a field. +// +// For a field belonging to a oneof, it implicitly clears any other field +// that may be currently set within the same oneof. +// For extension fields, it implicitly stores the provided ExtensionType. +// When setting a composite type, it is unspecified whether the stored value +// aliases the source's memory in any way. If the composite value is an +// empty, read-only value, then it panics. +// +// Set is a mutating operation and unsafe for concurrent use. +func (x *fastReflection_AminoSignFee) Set(fd protoreflect.FieldDescriptor, value protoreflect.Value) { + switch fd.FullName() { + case "AminoSignFee.amount": + lv := value.List() + clv := lv.(*_AminoSignFee_1_list) + x.Amount = *clv.list + case "AminoSignFee.gas": + x.Gas = value.Uint() + case "AminoSignFee.payer": + x.Payer = value.Interface().(string) + case "AminoSignFee.granter": + x.Granter = value.Interface().(string) + default: + if fd.IsExtension() { + panic(fmt.Errorf("proto3 declared messages do not support extensions: AminoSignFee")) + } + panic(fmt.Errorf("message AminoSignFee does not contain field %s", fd.FullName())) + } +} + +// Mutable returns a mutable reference to a composite type. +// +// If the field is unpopulated, it may allocate a composite value. +// For a field belonging to a oneof, it implicitly clears any other field +// that may be currently set within the same oneof. +// For extension fields, it implicitly stores the provided ExtensionType +// if not already stored. +// It panics if the field does not contain a composite type. +// +// Mutable is a mutating operation and unsafe for concurrent use. +func (x *fastReflection_AminoSignFee) Mutable(fd protoreflect.FieldDescriptor) protoreflect.Value { + switch fd.FullName() { + case "AminoSignFee.amount": + if x.Amount == nil { + x.Amount = []*v1beta1.Coin{} + } + value := &_AminoSignFee_1_list{list: &x.Amount} + return protoreflect.ValueOfList(value) + case "AminoSignFee.gas": + panic(fmt.Errorf("field gas of message AminoSignFee is not mutable")) + case "AminoSignFee.payer": + panic(fmt.Errorf("field payer of message AminoSignFee is not mutable")) + case "AminoSignFee.granter": + panic(fmt.Errorf("field granter of message AminoSignFee is not mutable")) + default: + if fd.IsExtension() { + panic(fmt.Errorf("proto3 declared messages do not support extensions: AminoSignFee")) + } + panic(fmt.Errorf("message AminoSignFee does not contain field %s", fd.FullName())) + } +} + +// NewField returns a new value that is assignable to the field +// for the given descriptor. For scalars, this returns the default value. +// For lists, maps, and messages, this returns a new, empty, mutable value. +func (x *fastReflection_AminoSignFee) NewField(fd protoreflect.FieldDescriptor) protoreflect.Value { + switch fd.FullName() { + case "AminoSignFee.amount": + list := []*v1beta1.Coin{} + return protoreflect.ValueOfList(&_AminoSignFee_1_list{list: &list}) + case "AminoSignFee.gas": + return protoreflect.ValueOfUint64(uint64(0)) + case "AminoSignFee.payer": + return protoreflect.ValueOfString("") + case "AminoSignFee.granter": + return protoreflect.ValueOfString("") + default: + if fd.IsExtension() { + panic(fmt.Errorf("proto3 declared messages do not support extensions: AminoSignFee")) + } + panic(fmt.Errorf("message AminoSignFee does not contain field %s", fd.FullName())) + } +} + +// WhichOneof reports which field within the oneof is populated, +// returning nil if none are populated. +// It panics if the oneof descriptor does not belong to this message. +func (x *fastReflection_AminoSignFee) WhichOneof(d protoreflect.OneofDescriptor) protoreflect.FieldDescriptor { + switch d.FullName() { + default: + panic(fmt.Errorf("%s is not a oneof field in AminoSignFee", d.FullName())) + } + panic("unreachable") +} + +// GetUnknown retrieves the entire list of unknown fields. +// The caller may only mutate the contents of the RawFields +// if the mutated bytes are stored back into the message with SetUnknown. +func (x *fastReflection_AminoSignFee) GetUnknown() protoreflect.RawFields { + return x.unknownFields +} + +// SetUnknown stores an entire list of unknown fields. +// The raw fields must be syntactically valid according to the wire format. +// An implementation may panic if this is not the case. +// Once stored, the caller must not mutate the content of the RawFields. +// An empty RawFields may be passed to clear the fields. +// +// SetUnknown is a mutating operation and unsafe for concurrent use. +func (x *fastReflection_AminoSignFee) SetUnknown(fields protoreflect.RawFields) { + x.unknownFields = fields +} + +// IsValid reports whether the message is valid. +// +// An invalid message is an empty, read-only value. +// +// An invalid message often corresponds to a nil pointer of the concrete +// message type, but the details are implementation dependent. +// Validity is not part of the protobuf data model, and may not +// be preserved in marshaling or other operations. +func (x *fastReflection_AminoSignFee) IsValid() bool { + return x != nil +} + +// ProtoMethods returns optional fastReflectionFeature-path implementations of various operations. +// This method may return nil. +// +// The returned methods type is identical to +// "google.golang.org/protobuf/runtime/protoiface".Methods. +// Consult the protoiface package documentation for details. +func (x *fastReflection_AminoSignFee) ProtoMethods() *protoiface.Methods { + size := func(input protoiface.SizeInput) protoiface.SizeOutput { + x := input.Message.Interface().(*AminoSignFee) + if x == nil { + return protoiface.SizeOutput{ + NoUnkeyedLiterals: input.NoUnkeyedLiterals, + Size: 0, + } + } + options := runtime.SizeInputToOptions(input) + _ = options + var n int + var l int + _ = l + if len(x.Amount) > 0 { + for _, e := range x.Amount { + l = options.Size(e) + n += 1 + l + runtime.Sov(uint64(l)) + } + } + if x.Gas != 0 { + n += 1 + runtime.Sov(uint64(x.Gas)) + } + l = len(x.Payer) + if l > 0 { + n += 1 + l + runtime.Sov(uint64(l)) + } + l = len(x.Granter) + if l > 0 { + n += 1 + l + runtime.Sov(uint64(l)) + } + if x.unknownFields != nil { + n += len(x.unknownFields) + } + return protoiface.SizeOutput{ + NoUnkeyedLiterals: input.NoUnkeyedLiterals, + Size: n, + } + } + + marshal := func(input protoiface.MarshalInput) (protoiface.MarshalOutput, error) { + x := input.Message.Interface().(*AminoSignFee) + if x == nil { + return protoiface.MarshalOutput{ + NoUnkeyedLiterals: input.NoUnkeyedLiterals, + Buf: input.Buf, + }, nil + } + options := runtime.MarshalInputToOptions(input) + _ = options + size := options.Size(x) + dAtA := make([]byte, size) + i := len(dAtA) + _ = i + var l int + _ = l + if x.unknownFields != nil { + i -= len(x.unknownFields) + copy(dAtA[i:], x.unknownFields) + } + if len(x.Granter) > 0 { + i -= len(x.Granter) + copy(dAtA[i:], x.Granter) + i = runtime.EncodeVarint(dAtA, i, uint64(len(x.Granter))) + i-- + dAtA[i] = 0x22 + } + if len(x.Payer) > 0 { + i -= len(x.Payer) + copy(dAtA[i:], x.Payer) + i = runtime.EncodeVarint(dAtA, i, uint64(len(x.Payer))) + i-- + dAtA[i] = 0x1a + } + if x.Gas != 0 { + i = runtime.EncodeVarint(dAtA, i, uint64(x.Gas)) + i-- + dAtA[i] = 0x10 + } + if len(x.Amount) > 0 { + for iNdEx := len(x.Amount) - 1; iNdEx >= 0; iNdEx-- { + encoded, err := options.Marshal(x.Amount[iNdEx]) + if err != nil { + return protoiface.MarshalOutput{ + NoUnkeyedLiterals: input.NoUnkeyedLiterals, + Buf: input.Buf, + }, err + } + i -= len(encoded) + copy(dAtA[i:], encoded) + i = runtime.EncodeVarint(dAtA, i, uint64(len(encoded))) + i-- + dAtA[i] = 0xa + } + } + if input.Buf != nil { + input.Buf = append(input.Buf, dAtA...) + } else { + input.Buf = dAtA + } + return protoiface.MarshalOutput{ + NoUnkeyedLiterals: input.NoUnkeyedLiterals, + Buf: input.Buf, + }, nil + } + unmarshal := func(input protoiface.UnmarshalInput) (protoiface.UnmarshalOutput, error) { + x := input.Message.Interface().(*AminoSignFee) + if x == nil { + return protoiface.UnmarshalOutput{ + NoUnkeyedLiterals: input.NoUnkeyedLiterals, + Flags: input.Flags, + }, nil + } + options := runtime.UnmarshalInputToOptions(input) + _ = options + dAtA := input.Buf + l := len(dAtA) + iNdEx := 0 + for iNdEx < l { + preIndex := iNdEx + var wire uint64 + for shift := uint(0); ; shift += 7 { + if shift >= 64 { + return protoiface.UnmarshalOutput{NoUnkeyedLiterals: input.NoUnkeyedLiterals, Flags: input.Flags}, runtime.ErrIntOverflow + } + if iNdEx >= l { + return protoiface.UnmarshalOutput{NoUnkeyedLiterals: input.NoUnkeyedLiterals, Flags: input.Flags}, io.ErrUnexpectedEOF + } + b := dAtA[iNdEx] + iNdEx++ + wire |= uint64(b&0x7F) << shift + if b < 0x80 { + break + } + } + fieldNum := int32(wire >> 3) + wireType := int(wire & 0x7) + if wireType == 4 { + return protoiface.UnmarshalOutput{NoUnkeyedLiterals: input.NoUnkeyedLiterals, Flags: input.Flags}, fmt.Errorf("proto: AminoSignFee: wiretype end group for non-group") + } + if fieldNum <= 0 { + return protoiface.UnmarshalOutput{NoUnkeyedLiterals: input.NoUnkeyedLiterals, Flags: input.Flags}, fmt.Errorf("proto: AminoSignFee: illegal tag %d (wire type %d)", fieldNum, wire) + } + switch fieldNum { + case 1: + if wireType != 2 { + return protoiface.UnmarshalOutput{NoUnkeyedLiterals: input.NoUnkeyedLiterals, Flags: input.Flags}, fmt.Errorf("proto: wrong wireType = %d for field Amount", wireType) + } + var msglen int + for shift := uint(0); ; shift += 7 { + if shift >= 64 { + return protoiface.UnmarshalOutput{NoUnkeyedLiterals: input.NoUnkeyedLiterals, Flags: input.Flags}, runtime.ErrIntOverflow + } + if iNdEx >= l { + return protoiface.UnmarshalOutput{NoUnkeyedLiterals: input.NoUnkeyedLiterals, Flags: input.Flags}, io.ErrUnexpectedEOF + } + b := dAtA[iNdEx] + iNdEx++ + msglen |= int(b&0x7F) << shift + if b < 0x80 { + break + } + } + if msglen < 0 { + return protoiface.UnmarshalOutput{NoUnkeyedLiterals: input.NoUnkeyedLiterals, Flags: input.Flags}, runtime.ErrInvalidLength + } + postIndex := iNdEx + msglen + if postIndex < 0 { + return protoiface.UnmarshalOutput{NoUnkeyedLiterals: input.NoUnkeyedLiterals, Flags: input.Flags}, runtime.ErrInvalidLength + } + if postIndex > l { + return protoiface.UnmarshalOutput{NoUnkeyedLiterals: input.NoUnkeyedLiterals, Flags: input.Flags}, io.ErrUnexpectedEOF + } + x.Amount = append(x.Amount, &v1beta1.Coin{}) + if err := options.Unmarshal(dAtA[iNdEx:postIndex], x.Amount[len(x.Amount)-1]); err != nil { + return protoiface.UnmarshalOutput{NoUnkeyedLiterals: input.NoUnkeyedLiterals, Flags: input.Flags}, err + } + iNdEx = postIndex + case 2: + if wireType != 0 { + return protoiface.UnmarshalOutput{NoUnkeyedLiterals: input.NoUnkeyedLiterals, Flags: input.Flags}, fmt.Errorf("proto: wrong wireType = %d for field Gas", wireType) + } + x.Gas = 0 + for shift := uint(0); ; shift += 7 { + if shift >= 64 { + return protoiface.UnmarshalOutput{NoUnkeyedLiterals: input.NoUnkeyedLiterals, Flags: input.Flags}, runtime.ErrIntOverflow + } + if iNdEx >= l { + return protoiface.UnmarshalOutput{NoUnkeyedLiterals: input.NoUnkeyedLiterals, Flags: input.Flags}, io.ErrUnexpectedEOF + } + b := dAtA[iNdEx] + iNdEx++ + x.Gas |= uint64(b&0x7F) << shift + if b < 0x80 { + break + } + } + case 3: + if wireType != 2 { + return protoiface.UnmarshalOutput{NoUnkeyedLiterals: input.NoUnkeyedLiterals, Flags: input.Flags}, fmt.Errorf("proto: wrong wireType = %d for field Payer", wireType) + } + var stringLen uint64 + for shift := uint(0); ; shift += 7 { + if shift >= 64 { + return protoiface.UnmarshalOutput{NoUnkeyedLiterals: input.NoUnkeyedLiterals, Flags: input.Flags}, runtime.ErrIntOverflow + } + if iNdEx >= l { + return protoiface.UnmarshalOutput{NoUnkeyedLiterals: input.NoUnkeyedLiterals, Flags: input.Flags}, io.ErrUnexpectedEOF + } + b := dAtA[iNdEx] + iNdEx++ + stringLen |= uint64(b&0x7F) << shift + if b < 0x80 { + break + } + } + intStringLen := int(stringLen) + if intStringLen < 0 { + return protoiface.UnmarshalOutput{NoUnkeyedLiterals: input.NoUnkeyedLiterals, Flags: input.Flags}, runtime.ErrInvalidLength + } + postIndex := iNdEx + intStringLen + if postIndex < 0 { + return protoiface.UnmarshalOutput{NoUnkeyedLiterals: input.NoUnkeyedLiterals, Flags: input.Flags}, runtime.ErrInvalidLength + } + if postIndex > l { + return protoiface.UnmarshalOutput{NoUnkeyedLiterals: input.NoUnkeyedLiterals, Flags: input.Flags}, io.ErrUnexpectedEOF + } + x.Payer = string(dAtA[iNdEx:postIndex]) + iNdEx = postIndex + case 4: + if wireType != 2 { + return protoiface.UnmarshalOutput{NoUnkeyedLiterals: input.NoUnkeyedLiterals, Flags: input.Flags}, fmt.Errorf("proto: wrong wireType = %d for field Granter", wireType) + } + var stringLen uint64 + for shift := uint(0); ; shift += 7 { + if shift >= 64 { + return protoiface.UnmarshalOutput{NoUnkeyedLiterals: input.NoUnkeyedLiterals, Flags: input.Flags}, runtime.ErrIntOverflow + } + if iNdEx >= l { + return protoiface.UnmarshalOutput{NoUnkeyedLiterals: input.NoUnkeyedLiterals, Flags: input.Flags}, io.ErrUnexpectedEOF + } + b := dAtA[iNdEx] + iNdEx++ + stringLen |= uint64(b&0x7F) << shift + if b < 0x80 { + break + } + } + intStringLen := int(stringLen) + if intStringLen < 0 { + return protoiface.UnmarshalOutput{NoUnkeyedLiterals: input.NoUnkeyedLiterals, Flags: input.Flags}, runtime.ErrInvalidLength + } + postIndex := iNdEx + intStringLen + if postIndex < 0 { + return protoiface.UnmarshalOutput{NoUnkeyedLiterals: input.NoUnkeyedLiterals, Flags: input.Flags}, runtime.ErrInvalidLength + } + if postIndex > l { + return protoiface.UnmarshalOutput{NoUnkeyedLiterals: input.NoUnkeyedLiterals, Flags: input.Flags}, io.ErrUnexpectedEOF + } + x.Granter = string(dAtA[iNdEx:postIndex]) + iNdEx = postIndex + default: + iNdEx = preIndex + skippy, err := runtime.Skip(dAtA[iNdEx:]) + if err != nil { + return protoiface.UnmarshalOutput{NoUnkeyedLiterals: input.NoUnkeyedLiterals, Flags: input.Flags}, err + } + if (skippy < 0) || (iNdEx+skippy) < 0 { + return protoiface.UnmarshalOutput{NoUnkeyedLiterals: input.NoUnkeyedLiterals, Flags: input.Flags}, runtime.ErrInvalidLength + } + if (iNdEx + skippy) > l { + return protoiface.UnmarshalOutput{NoUnkeyedLiterals: input.NoUnkeyedLiterals, Flags: input.Flags}, io.ErrUnexpectedEOF + } + if !options.DiscardUnknown { + x.unknownFields = append(x.unknownFields, dAtA[iNdEx:iNdEx+skippy]...) + } + iNdEx += skippy + } + } + + if iNdEx > l { + return protoiface.UnmarshalOutput{NoUnkeyedLiterals: input.NoUnkeyedLiterals, Flags: input.Flags}, io.ErrUnexpectedEOF + } + return protoiface.UnmarshalOutput{NoUnkeyedLiterals: input.NoUnkeyedLiterals, Flags: input.Flags}, nil + } + return &protoiface.Methods{ + NoUnkeyedLiterals: struct{}{}, + Flags: protoiface.SupportMarshalDeterministic | protoiface.SupportUnmarshalDiscardUnknown, + Size: size, + Marshal: marshal, + Unmarshal: unmarshal, + Merge: nil, + CheckInitialized: nil, + } +} + +var _ protoreflect.List = (*_AminoSignDoc_7_list)(nil) + +type _AminoSignDoc_7_list struct { + list *[]*anypb.Any +} + +func (x *_AminoSignDoc_7_list) Len() int { + if x.list == nil { + return 0 + } + return len(*x.list) +} + +func (x *_AminoSignDoc_7_list) Get(i int) protoreflect.Value { + return protoreflect.ValueOfMessage((*x.list)[i].ProtoReflect()) +} + +func (x *_AminoSignDoc_7_list) Set(i int, value protoreflect.Value) { + valueUnwrapped := value.Message() + concreteValue := valueUnwrapped.Interface().(*anypb.Any) + (*x.list)[i] = concreteValue +} + +func (x *_AminoSignDoc_7_list) Append(value protoreflect.Value) { + valueUnwrapped := value.Message() + concreteValue := valueUnwrapped.Interface().(*anypb.Any) + *x.list = append(*x.list, concreteValue) +} + +func (x *_AminoSignDoc_7_list) AppendMutable() protoreflect.Value { + v := new(anypb.Any) + *x.list = append(*x.list, v) + return protoreflect.ValueOfMessage(v.ProtoReflect()) +} + +func (x *_AminoSignDoc_7_list) Truncate(n int) { + for i := n; i < len(*x.list); i++ { + (*x.list)[i] = nil + } + *x.list = (*x.list)[:n] +} + +func (x *_AminoSignDoc_7_list) NewElement() protoreflect.Value { + v := new(anypb.Any) + return protoreflect.ValueOfMessage(v.ProtoReflect()) +} + +func (x *_AminoSignDoc_7_list) IsValid() bool { + return x.list != nil +} + +var ( + md_AminoSignDoc protoreflect.MessageDescriptor + fd_AminoSignDoc_account_number protoreflect.FieldDescriptor + fd_AminoSignDoc_sequence protoreflect.FieldDescriptor + fd_AminoSignDoc_timeout_height protoreflect.FieldDescriptor + fd_AminoSignDoc_chain_id protoreflect.FieldDescriptor + fd_AminoSignDoc_memo protoreflect.FieldDescriptor + fd_AminoSignDoc_fee protoreflect.FieldDescriptor + fd_AminoSignDoc_msgs protoreflect.FieldDescriptor + fd_AminoSignDoc_tip protoreflect.FieldDescriptor +) + +func init() { + file_aminojsonpb_aminojson_proto_init() + md_AminoSignDoc = File_aminojsonpb_aminojson_proto.Messages().ByName("AminoSignDoc") + fd_AminoSignDoc_account_number = md_AminoSignDoc.Fields().ByName("account_number") + fd_AminoSignDoc_sequence = md_AminoSignDoc.Fields().ByName("sequence") + fd_AminoSignDoc_timeout_height = md_AminoSignDoc.Fields().ByName("timeout_height") + fd_AminoSignDoc_chain_id = md_AminoSignDoc.Fields().ByName("chain_id") + fd_AminoSignDoc_memo = md_AminoSignDoc.Fields().ByName("memo") + fd_AminoSignDoc_fee = md_AminoSignDoc.Fields().ByName("fee") + fd_AminoSignDoc_msgs = md_AminoSignDoc.Fields().ByName("msgs") + fd_AminoSignDoc_tip = md_AminoSignDoc.Fields().ByName("tip") +} + +var _ protoreflect.Message = (*fastReflection_AminoSignDoc)(nil) + +type fastReflection_AminoSignDoc AminoSignDoc + +func (x *AminoSignDoc) ProtoReflect() protoreflect.Message { + return (*fastReflection_AminoSignDoc)(x) +} + +func (x *AminoSignDoc) slowProtoReflect() protoreflect.Message { + mi := &file_aminojsonpb_aminojson_proto_msgTypes[1] + if protoimpl.UnsafeEnabled && x != nil { + ms := protoimpl.X.MessageStateOf(protoimpl.Pointer(x)) + if ms.LoadMessageInfo() == nil { + ms.StoreMessageInfo(mi) + } + return ms + } + return mi.MessageOf(x) +} + +var _fastReflection_AminoSignDoc_messageType fastReflection_AminoSignDoc_messageType +var _ protoreflect.MessageType = fastReflection_AminoSignDoc_messageType{} + +type fastReflection_AminoSignDoc_messageType struct{} + +func (x fastReflection_AminoSignDoc_messageType) Zero() protoreflect.Message { + return (*fastReflection_AminoSignDoc)(nil) +} +func (x fastReflection_AminoSignDoc_messageType) New() protoreflect.Message { + return new(fastReflection_AminoSignDoc) +} +func (x fastReflection_AminoSignDoc_messageType) Descriptor() protoreflect.MessageDescriptor { + return md_AminoSignDoc +} + +// Descriptor returns message descriptor, which contains only the protobuf +// type information for the message. +func (x *fastReflection_AminoSignDoc) Descriptor() protoreflect.MessageDescriptor { + return md_AminoSignDoc +} + +// Type returns the message type, which encapsulates both Go and protobuf +// type information. If the Go type information is not needed, +// it is recommended that the message descriptor be used instead. +func (x *fastReflection_AminoSignDoc) Type() protoreflect.MessageType { + return _fastReflection_AminoSignDoc_messageType +} + +// New returns a newly allocated and mutable empty message. +func (x *fastReflection_AminoSignDoc) New() protoreflect.Message { + return new(fastReflection_AminoSignDoc) +} + +// Interface unwraps the message reflection interface and +// returns the underlying ProtoMessage interface. +func (x *fastReflection_AminoSignDoc) Interface() protoreflect.ProtoMessage { + return (*AminoSignDoc)(x) +} + +// Range iterates over every populated field in an undefined order, +// calling f for each field descriptor and value encountered. +// Range returns immediately if f returns false. +// While iterating, mutating operations may only be performed +// on the current field descriptor. +func (x *fastReflection_AminoSignDoc) Range(f func(protoreflect.FieldDescriptor, protoreflect.Value) bool) { + if x.AccountNumber != uint64(0) { + value := protoreflect.ValueOfUint64(x.AccountNumber) + if !f(fd_AminoSignDoc_account_number, value) { + return + } + } + if x.Sequence != uint64(0) { + value := protoreflect.ValueOfUint64(x.Sequence) + if !f(fd_AminoSignDoc_sequence, value) { + return + } + } + if x.TimeoutHeight != uint64(0) { + value := protoreflect.ValueOfUint64(x.TimeoutHeight) + if !f(fd_AminoSignDoc_timeout_height, value) { + return + } + } + if x.ChainId != "" { + value := protoreflect.ValueOfString(x.ChainId) + if !f(fd_AminoSignDoc_chain_id, value) { + return + } + } + if x.Memo != "" { + value := protoreflect.ValueOfString(x.Memo) + if !f(fd_AminoSignDoc_memo, value) { + return + } + } + if x.Fee != nil { + value := protoreflect.ValueOfMessage(x.Fee.ProtoReflect()) + if !f(fd_AminoSignDoc_fee, value) { + return + } + } + if len(x.Msgs) != 0 { + value := protoreflect.ValueOfList(&_AminoSignDoc_7_list{list: &x.Msgs}) + if !f(fd_AminoSignDoc_msgs, value) { + return + } + } + if x.Tip != nil { + value := protoreflect.ValueOfMessage(x.Tip.ProtoReflect()) + if !f(fd_AminoSignDoc_tip, value) { + return + } + } +} + +// Has reports whether a field is populated. +// +// Some fields have the property of nullability where it is possible to +// distinguish between the default value of a field and whether the field +// was explicitly populated with the default value. Singular message fields, +// member fields of a oneof, and proto2 scalar fields are nullable. Such +// fields are populated only if explicitly set. +// +// In other cases (aside from the nullable cases above), +// a proto3 scalar field is populated if it contains a non-zero value, and +// a repeated field is populated if it is non-empty. +func (x *fastReflection_AminoSignDoc) Has(fd protoreflect.FieldDescriptor) bool { + switch fd.FullName() { + case "AminoSignDoc.account_number": + return x.AccountNumber != uint64(0) + case "AminoSignDoc.sequence": + return x.Sequence != uint64(0) + case "AminoSignDoc.timeout_height": + return x.TimeoutHeight != uint64(0) + case "AminoSignDoc.chain_id": + return x.ChainId != "" + case "AminoSignDoc.memo": + return x.Memo != "" + case "AminoSignDoc.fee": + return x.Fee != nil + case "AminoSignDoc.msgs": + return len(x.Msgs) != 0 + case "AminoSignDoc.tip": + return x.Tip != nil + default: + if fd.IsExtension() { + panic(fmt.Errorf("proto3 declared messages do not support extensions: AminoSignDoc")) + } + panic(fmt.Errorf("message AminoSignDoc does not contain field %s", fd.FullName())) + } +} + +// Clear clears the field such that a subsequent Has call reports false. +// +// Clearing an extension field clears both the extension type and value +// associated with the given field number. +// +// Clear is a mutating operation and unsafe for concurrent use. +func (x *fastReflection_AminoSignDoc) Clear(fd protoreflect.FieldDescriptor) { + switch fd.FullName() { + case "AminoSignDoc.account_number": + x.AccountNumber = uint64(0) + case "AminoSignDoc.sequence": + x.Sequence = uint64(0) + case "AminoSignDoc.timeout_height": + x.TimeoutHeight = uint64(0) + case "AminoSignDoc.chain_id": + x.ChainId = "" + case "AminoSignDoc.memo": + x.Memo = "" + case "AminoSignDoc.fee": + x.Fee = nil + case "AminoSignDoc.msgs": + x.Msgs = nil + case "AminoSignDoc.tip": + x.Tip = nil + default: + if fd.IsExtension() { + panic(fmt.Errorf("proto3 declared messages do not support extensions: AminoSignDoc")) + } + panic(fmt.Errorf("message AminoSignDoc does not contain field %s", fd.FullName())) + } +} + +// Get retrieves the value for a field. +// +// For unpopulated scalars, it returns the default value, where +// the default value of a bytes scalar is guaranteed to be a copy. +// For unpopulated composite types, it returns an empty, read-only view +// of the value; to obtain a mutable reference, use Mutable. +func (x *fastReflection_AminoSignDoc) Get(descriptor protoreflect.FieldDescriptor) protoreflect.Value { + switch descriptor.FullName() { + case "AminoSignDoc.account_number": + value := x.AccountNumber + return protoreflect.ValueOfUint64(value) + case "AminoSignDoc.sequence": + value := x.Sequence + return protoreflect.ValueOfUint64(value) + case "AminoSignDoc.timeout_height": + value := x.TimeoutHeight + return protoreflect.ValueOfUint64(value) + case "AminoSignDoc.chain_id": + value := x.ChainId + return protoreflect.ValueOfString(value) + case "AminoSignDoc.memo": + value := x.Memo + return protoreflect.ValueOfString(value) + case "AminoSignDoc.fee": + value := x.Fee + return protoreflect.ValueOfMessage(value.ProtoReflect()) + case "AminoSignDoc.msgs": + if len(x.Msgs) == 0 { + return protoreflect.ValueOfList(&_AminoSignDoc_7_list{}) + } + listValue := &_AminoSignDoc_7_list{list: &x.Msgs} + return protoreflect.ValueOfList(listValue) + case "AminoSignDoc.tip": + value := x.Tip + return protoreflect.ValueOfMessage(value.ProtoReflect()) + default: + if descriptor.IsExtension() { + panic(fmt.Errorf("proto3 declared messages do not support extensions: AminoSignDoc")) + } + panic(fmt.Errorf("message AminoSignDoc does not contain field %s", descriptor.FullName())) + } +} + +// Set stores the value for a field. +// +// For a field belonging to a oneof, it implicitly clears any other field +// that may be currently set within the same oneof. +// For extension fields, it implicitly stores the provided ExtensionType. +// When setting a composite type, it is unspecified whether the stored value +// aliases the source's memory in any way. If the composite value is an +// empty, read-only value, then it panics. +// +// Set is a mutating operation and unsafe for concurrent use. +func (x *fastReflection_AminoSignDoc) Set(fd protoreflect.FieldDescriptor, value protoreflect.Value) { + switch fd.FullName() { + case "AminoSignDoc.account_number": + x.AccountNumber = value.Uint() + case "AminoSignDoc.sequence": + x.Sequence = value.Uint() + case "AminoSignDoc.timeout_height": + x.TimeoutHeight = value.Uint() + case "AminoSignDoc.chain_id": + x.ChainId = value.Interface().(string) + case "AminoSignDoc.memo": + x.Memo = value.Interface().(string) + case "AminoSignDoc.fee": + x.Fee = value.Message().Interface().(*AminoSignFee) + case "AminoSignDoc.msgs": + lv := value.List() + clv := lv.(*_AminoSignDoc_7_list) + x.Msgs = *clv.list + case "AminoSignDoc.tip": + x.Tip = value.Message().Interface().(*v1beta11.Tip) + default: + if fd.IsExtension() { + panic(fmt.Errorf("proto3 declared messages do not support extensions: AminoSignDoc")) + } + panic(fmt.Errorf("message AminoSignDoc does not contain field %s", fd.FullName())) + } +} + +// Mutable returns a mutable reference to a composite type. +// +// If the field is unpopulated, it may allocate a composite value. +// For a field belonging to a oneof, it implicitly clears any other field +// that may be currently set within the same oneof. +// For extension fields, it implicitly stores the provided ExtensionType +// if not already stored. +// It panics if the field does not contain a composite type. +// +// Mutable is a mutating operation and unsafe for concurrent use. +func (x *fastReflection_AminoSignDoc) Mutable(fd protoreflect.FieldDescriptor) protoreflect.Value { + switch fd.FullName() { + case "AminoSignDoc.fee": + if x.Fee == nil { + x.Fee = new(AminoSignFee) + } + return protoreflect.ValueOfMessage(x.Fee.ProtoReflect()) + case "AminoSignDoc.msgs": + if x.Msgs == nil { + x.Msgs = []*anypb.Any{} + } + value := &_AminoSignDoc_7_list{list: &x.Msgs} + return protoreflect.ValueOfList(value) + case "AminoSignDoc.tip": + if x.Tip == nil { + x.Tip = new(v1beta11.Tip) + } + return protoreflect.ValueOfMessage(x.Tip.ProtoReflect()) + case "AminoSignDoc.account_number": + panic(fmt.Errorf("field account_number of message AminoSignDoc is not mutable")) + case "AminoSignDoc.sequence": + panic(fmt.Errorf("field sequence of message AminoSignDoc is not mutable")) + case "AminoSignDoc.timeout_height": + panic(fmt.Errorf("field timeout_height of message AminoSignDoc is not mutable")) + case "AminoSignDoc.chain_id": + panic(fmt.Errorf("field chain_id of message AminoSignDoc is not mutable")) + case "AminoSignDoc.memo": + panic(fmt.Errorf("field memo of message AminoSignDoc is not mutable")) + default: + if fd.IsExtension() { + panic(fmt.Errorf("proto3 declared messages do not support extensions: AminoSignDoc")) + } + panic(fmt.Errorf("message AminoSignDoc does not contain field %s", fd.FullName())) + } +} + +// NewField returns a new value that is assignable to the field +// for the given descriptor. For scalars, this returns the default value. +// For lists, maps, and messages, this returns a new, empty, mutable value. +func (x *fastReflection_AminoSignDoc) NewField(fd protoreflect.FieldDescriptor) protoreflect.Value { + switch fd.FullName() { + case "AminoSignDoc.account_number": + return protoreflect.ValueOfUint64(uint64(0)) + case "AminoSignDoc.sequence": + return protoreflect.ValueOfUint64(uint64(0)) + case "AminoSignDoc.timeout_height": + return protoreflect.ValueOfUint64(uint64(0)) + case "AminoSignDoc.chain_id": + return protoreflect.ValueOfString("") + case "AminoSignDoc.memo": + return protoreflect.ValueOfString("") + case "AminoSignDoc.fee": + m := new(AminoSignFee) + return protoreflect.ValueOfMessage(m.ProtoReflect()) + case "AminoSignDoc.msgs": + list := []*anypb.Any{} + return protoreflect.ValueOfList(&_AminoSignDoc_7_list{list: &list}) + case "AminoSignDoc.tip": + m := new(v1beta11.Tip) + return protoreflect.ValueOfMessage(m.ProtoReflect()) + default: + if fd.IsExtension() { + panic(fmt.Errorf("proto3 declared messages do not support extensions: AminoSignDoc")) + } + panic(fmt.Errorf("message AminoSignDoc does not contain field %s", fd.FullName())) + } +} + +// WhichOneof reports which field within the oneof is populated, +// returning nil if none are populated. +// It panics if the oneof descriptor does not belong to this message. +func (x *fastReflection_AminoSignDoc) WhichOneof(d protoreflect.OneofDescriptor) protoreflect.FieldDescriptor { + switch d.FullName() { + default: + panic(fmt.Errorf("%s is not a oneof field in AminoSignDoc", d.FullName())) + } + panic("unreachable") +} + +// GetUnknown retrieves the entire list of unknown fields. +// The caller may only mutate the contents of the RawFields +// if the mutated bytes are stored back into the message with SetUnknown. +func (x *fastReflection_AminoSignDoc) GetUnknown() protoreflect.RawFields { + return x.unknownFields +} + +// SetUnknown stores an entire list of unknown fields. +// The raw fields must be syntactically valid according to the wire format. +// An implementation may panic if this is not the case. +// Once stored, the caller must not mutate the content of the RawFields. +// An empty RawFields may be passed to clear the fields. +// +// SetUnknown is a mutating operation and unsafe for concurrent use. +func (x *fastReflection_AminoSignDoc) SetUnknown(fields protoreflect.RawFields) { + x.unknownFields = fields +} + +// IsValid reports whether the message is valid. +// +// An invalid message is an empty, read-only value. +// +// An invalid message often corresponds to a nil pointer of the concrete +// message type, but the details are implementation dependent. +// Validity is not part of the protobuf data model, and may not +// be preserved in marshaling or other operations. +func (x *fastReflection_AminoSignDoc) IsValid() bool { + return x != nil +} + +// ProtoMethods returns optional fastReflectionFeature-path implementations of various operations. +// This method may return nil. +// +// The returned methods type is identical to +// "google.golang.org/protobuf/runtime/protoiface".Methods. +// Consult the protoiface package documentation for details. +func (x *fastReflection_AminoSignDoc) ProtoMethods() *protoiface.Methods { + size := func(input protoiface.SizeInput) protoiface.SizeOutput { + x := input.Message.Interface().(*AminoSignDoc) + if x == nil { + return protoiface.SizeOutput{ + NoUnkeyedLiterals: input.NoUnkeyedLiterals, + Size: 0, + } + } + options := runtime.SizeInputToOptions(input) + _ = options + var n int + var l int + _ = l + if x.AccountNumber != 0 { + n += 1 + runtime.Sov(uint64(x.AccountNumber)) + } + if x.Sequence != 0 { + n += 1 + runtime.Sov(uint64(x.Sequence)) + } + if x.TimeoutHeight != 0 { + n += 1 + runtime.Sov(uint64(x.TimeoutHeight)) + } + l = len(x.ChainId) + if l > 0 { + n += 1 + l + runtime.Sov(uint64(l)) + } + l = len(x.Memo) + if l > 0 { + n += 1 + l + runtime.Sov(uint64(l)) + } + if x.Fee != nil { + l = options.Size(x.Fee) + n += 1 + l + runtime.Sov(uint64(l)) + } + if len(x.Msgs) > 0 { + for _, e := range x.Msgs { + l = options.Size(e) + n += 1 + l + runtime.Sov(uint64(l)) + } + } + if x.Tip != nil { + l = options.Size(x.Tip) + n += 1 + l + runtime.Sov(uint64(l)) + } + if x.unknownFields != nil { + n += len(x.unknownFields) + } + return protoiface.SizeOutput{ + NoUnkeyedLiterals: input.NoUnkeyedLiterals, + Size: n, + } + } + + marshal := func(input protoiface.MarshalInput) (protoiface.MarshalOutput, error) { + x := input.Message.Interface().(*AminoSignDoc) + if x == nil { + return protoiface.MarshalOutput{ + NoUnkeyedLiterals: input.NoUnkeyedLiterals, + Buf: input.Buf, + }, nil + } + options := runtime.MarshalInputToOptions(input) + _ = options + size := options.Size(x) + dAtA := make([]byte, size) + i := len(dAtA) + _ = i + var l int + _ = l + if x.unknownFields != nil { + i -= len(x.unknownFields) + copy(dAtA[i:], x.unknownFields) + } + if x.Tip != nil { + encoded, err := options.Marshal(x.Tip) + if err != nil { + return protoiface.MarshalOutput{ + NoUnkeyedLiterals: input.NoUnkeyedLiterals, + Buf: input.Buf, + }, err + } + i -= len(encoded) + copy(dAtA[i:], encoded) + i = runtime.EncodeVarint(dAtA, i, uint64(len(encoded))) + i-- + dAtA[i] = 0x42 + } + if len(x.Msgs) > 0 { + for iNdEx := len(x.Msgs) - 1; iNdEx >= 0; iNdEx-- { + encoded, err := options.Marshal(x.Msgs[iNdEx]) + if err != nil { + return protoiface.MarshalOutput{ + NoUnkeyedLiterals: input.NoUnkeyedLiterals, + Buf: input.Buf, + }, err + } + i -= len(encoded) + copy(dAtA[i:], encoded) + i = runtime.EncodeVarint(dAtA, i, uint64(len(encoded))) + i-- + dAtA[i] = 0x3a + } + } + if x.Fee != nil { + encoded, err := options.Marshal(x.Fee) + if err != nil { + return protoiface.MarshalOutput{ + NoUnkeyedLiterals: input.NoUnkeyedLiterals, + Buf: input.Buf, + }, err + } + i -= len(encoded) + copy(dAtA[i:], encoded) + i = runtime.EncodeVarint(dAtA, i, uint64(len(encoded))) + i-- + dAtA[i] = 0x32 + } + if len(x.Memo) > 0 { + i -= len(x.Memo) + copy(dAtA[i:], x.Memo) + i = runtime.EncodeVarint(dAtA, i, uint64(len(x.Memo))) + i-- + dAtA[i] = 0x2a + } + if len(x.ChainId) > 0 { + i -= len(x.ChainId) + copy(dAtA[i:], x.ChainId) + i = runtime.EncodeVarint(dAtA, i, uint64(len(x.ChainId))) + i-- + dAtA[i] = 0x22 + } + if x.TimeoutHeight != 0 { + i = runtime.EncodeVarint(dAtA, i, uint64(x.TimeoutHeight)) + i-- + dAtA[i] = 0x18 + } + if x.Sequence != 0 { + i = runtime.EncodeVarint(dAtA, i, uint64(x.Sequence)) + i-- + dAtA[i] = 0x10 + } + if x.AccountNumber != 0 { + i = runtime.EncodeVarint(dAtA, i, uint64(x.AccountNumber)) + i-- + dAtA[i] = 0x8 + } + if input.Buf != nil { + input.Buf = append(input.Buf, dAtA...) + } else { + input.Buf = dAtA + } + return protoiface.MarshalOutput{ + NoUnkeyedLiterals: input.NoUnkeyedLiterals, + Buf: input.Buf, + }, nil + } + unmarshal := func(input protoiface.UnmarshalInput) (protoiface.UnmarshalOutput, error) { + x := input.Message.Interface().(*AminoSignDoc) + if x == nil { + return protoiface.UnmarshalOutput{ + NoUnkeyedLiterals: input.NoUnkeyedLiterals, + Flags: input.Flags, + }, nil + } + options := runtime.UnmarshalInputToOptions(input) + _ = options + dAtA := input.Buf + l := len(dAtA) + iNdEx := 0 + for iNdEx < l { + preIndex := iNdEx + var wire uint64 + for shift := uint(0); ; shift += 7 { + if shift >= 64 { + return protoiface.UnmarshalOutput{NoUnkeyedLiterals: input.NoUnkeyedLiterals, Flags: input.Flags}, runtime.ErrIntOverflow + } + if iNdEx >= l { + return protoiface.UnmarshalOutput{NoUnkeyedLiterals: input.NoUnkeyedLiterals, Flags: input.Flags}, io.ErrUnexpectedEOF + } + b := dAtA[iNdEx] + iNdEx++ + wire |= uint64(b&0x7F) << shift + if b < 0x80 { + break + } + } + fieldNum := int32(wire >> 3) + wireType := int(wire & 0x7) + if wireType == 4 { + return protoiface.UnmarshalOutput{NoUnkeyedLiterals: input.NoUnkeyedLiterals, Flags: input.Flags}, fmt.Errorf("proto: AminoSignDoc: wiretype end group for non-group") + } + if fieldNum <= 0 { + return protoiface.UnmarshalOutput{NoUnkeyedLiterals: input.NoUnkeyedLiterals, Flags: input.Flags}, fmt.Errorf("proto: AminoSignDoc: illegal tag %d (wire type %d)", fieldNum, wire) + } + switch fieldNum { + case 1: + if wireType != 0 { + return protoiface.UnmarshalOutput{NoUnkeyedLiterals: input.NoUnkeyedLiterals, Flags: input.Flags}, fmt.Errorf("proto: wrong wireType = %d for field AccountNumber", wireType) + } + x.AccountNumber = 0 + for shift := uint(0); ; shift += 7 { + if shift >= 64 { + return protoiface.UnmarshalOutput{NoUnkeyedLiterals: input.NoUnkeyedLiterals, Flags: input.Flags}, runtime.ErrIntOverflow + } + if iNdEx >= l { + return protoiface.UnmarshalOutput{NoUnkeyedLiterals: input.NoUnkeyedLiterals, Flags: input.Flags}, io.ErrUnexpectedEOF + } + b := dAtA[iNdEx] + iNdEx++ + x.AccountNumber |= uint64(b&0x7F) << shift + if b < 0x80 { + break + } + } + case 2: + if wireType != 0 { + return protoiface.UnmarshalOutput{NoUnkeyedLiterals: input.NoUnkeyedLiterals, Flags: input.Flags}, fmt.Errorf("proto: wrong wireType = %d for field Sequence", wireType) + } + x.Sequence = 0 + for shift := uint(0); ; shift += 7 { + if shift >= 64 { + return protoiface.UnmarshalOutput{NoUnkeyedLiterals: input.NoUnkeyedLiterals, Flags: input.Flags}, runtime.ErrIntOverflow + } + if iNdEx >= l { + return protoiface.UnmarshalOutput{NoUnkeyedLiterals: input.NoUnkeyedLiterals, Flags: input.Flags}, io.ErrUnexpectedEOF + } + b := dAtA[iNdEx] + iNdEx++ + x.Sequence |= uint64(b&0x7F) << shift + if b < 0x80 { + break + } + } + case 3: + if wireType != 0 { + return protoiface.UnmarshalOutput{NoUnkeyedLiterals: input.NoUnkeyedLiterals, Flags: input.Flags}, fmt.Errorf("proto: wrong wireType = %d for field TimeoutHeight", wireType) + } + x.TimeoutHeight = 0 + for shift := uint(0); ; shift += 7 { + if shift >= 64 { + return protoiface.UnmarshalOutput{NoUnkeyedLiterals: input.NoUnkeyedLiterals, Flags: input.Flags}, runtime.ErrIntOverflow + } + if iNdEx >= l { + return protoiface.UnmarshalOutput{NoUnkeyedLiterals: input.NoUnkeyedLiterals, Flags: input.Flags}, io.ErrUnexpectedEOF + } + b := dAtA[iNdEx] + iNdEx++ + x.TimeoutHeight |= uint64(b&0x7F) << shift + if b < 0x80 { + break + } + } + case 4: + if wireType != 2 { + return protoiface.UnmarshalOutput{NoUnkeyedLiterals: input.NoUnkeyedLiterals, Flags: input.Flags}, fmt.Errorf("proto: wrong wireType = %d for field ChainId", wireType) + } + var stringLen uint64 + for shift := uint(0); ; shift += 7 { + if shift >= 64 { + return protoiface.UnmarshalOutput{NoUnkeyedLiterals: input.NoUnkeyedLiterals, Flags: input.Flags}, runtime.ErrIntOverflow + } + if iNdEx >= l { + return protoiface.UnmarshalOutput{NoUnkeyedLiterals: input.NoUnkeyedLiterals, Flags: input.Flags}, io.ErrUnexpectedEOF + } + b := dAtA[iNdEx] + iNdEx++ + stringLen |= uint64(b&0x7F) << shift + if b < 0x80 { + break + } + } + intStringLen := int(stringLen) + if intStringLen < 0 { + return protoiface.UnmarshalOutput{NoUnkeyedLiterals: input.NoUnkeyedLiterals, Flags: input.Flags}, runtime.ErrInvalidLength + } + postIndex := iNdEx + intStringLen + if postIndex < 0 { + return protoiface.UnmarshalOutput{NoUnkeyedLiterals: input.NoUnkeyedLiterals, Flags: input.Flags}, runtime.ErrInvalidLength + } + if postIndex > l { + return protoiface.UnmarshalOutput{NoUnkeyedLiterals: input.NoUnkeyedLiterals, Flags: input.Flags}, io.ErrUnexpectedEOF + } + x.ChainId = string(dAtA[iNdEx:postIndex]) + iNdEx = postIndex + case 5: + if wireType != 2 { + return protoiface.UnmarshalOutput{NoUnkeyedLiterals: input.NoUnkeyedLiterals, Flags: input.Flags}, fmt.Errorf("proto: wrong wireType = %d for field Memo", wireType) + } + var stringLen uint64 + for shift := uint(0); ; shift += 7 { + if shift >= 64 { + return protoiface.UnmarshalOutput{NoUnkeyedLiterals: input.NoUnkeyedLiterals, Flags: input.Flags}, runtime.ErrIntOverflow + } + if iNdEx >= l { + return protoiface.UnmarshalOutput{NoUnkeyedLiterals: input.NoUnkeyedLiterals, Flags: input.Flags}, io.ErrUnexpectedEOF + } + b := dAtA[iNdEx] + iNdEx++ + stringLen |= uint64(b&0x7F) << shift + if b < 0x80 { + break + } + } + intStringLen := int(stringLen) + if intStringLen < 0 { + return protoiface.UnmarshalOutput{NoUnkeyedLiterals: input.NoUnkeyedLiterals, Flags: input.Flags}, runtime.ErrInvalidLength + } + postIndex := iNdEx + intStringLen + if postIndex < 0 { + return protoiface.UnmarshalOutput{NoUnkeyedLiterals: input.NoUnkeyedLiterals, Flags: input.Flags}, runtime.ErrInvalidLength + } + if postIndex > l { + return protoiface.UnmarshalOutput{NoUnkeyedLiterals: input.NoUnkeyedLiterals, Flags: input.Flags}, io.ErrUnexpectedEOF + } + x.Memo = string(dAtA[iNdEx:postIndex]) + iNdEx = postIndex + case 6: + if wireType != 2 { + return protoiface.UnmarshalOutput{NoUnkeyedLiterals: input.NoUnkeyedLiterals, Flags: input.Flags}, fmt.Errorf("proto: wrong wireType = %d for field Fee", wireType) + } + var msglen int + for shift := uint(0); ; shift += 7 { + if shift >= 64 { + return protoiface.UnmarshalOutput{NoUnkeyedLiterals: input.NoUnkeyedLiterals, Flags: input.Flags}, runtime.ErrIntOverflow + } + if iNdEx >= l { + return protoiface.UnmarshalOutput{NoUnkeyedLiterals: input.NoUnkeyedLiterals, Flags: input.Flags}, io.ErrUnexpectedEOF + } + b := dAtA[iNdEx] + iNdEx++ + msglen |= int(b&0x7F) << shift + if b < 0x80 { + break + } + } + if msglen < 0 { + return protoiface.UnmarshalOutput{NoUnkeyedLiterals: input.NoUnkeyedLiterals, Flags: input.Flags}, runtime.ErrInvalidLength + } + postIndex := iNdEx + msglen + if postIndex < 0 { + return protoiface.UnmarshalOutput{NoUnkeyedLiterals: input.NoUnkeyedLiterals, Flags: input.Flags}, runtime.ErrInvalidLength + } + if postIndex > l { + return protoiface.UnmarshalOutput{NoUnkeyedLiterals: input.NoUnkeyedLiterals, Flags: input.Flags}, io.ErrUnexpectedEOF + } + if x.Fee == nil { + x.Fee = &AminoSignFee{} + } + if err := options.Unmarshal(dAtA[iNdEx:postIndex], x.Fee); err != nil { + return protoiface.UnmarshalOutput{NoUnkeyedLiterals: input.NoUnkeyedLiterals, Flags: input.Flags}, err + } + iNdEx = postIndex + case 7: + if wireType != 2 { + return protoiface.UnmarshalOutput{NoUnkeyedLiterals: input.NoUnkeyedLiterals, Flags: input.Flags}, fmt.Errorf("proto: wrong wireType = %d for field Msgs", wireType) + } + var msglen int + for shift := uint(0); ; shift += 7 { + if shift >= 64 { + return protoiface.UnmarshalOutput{NoUnkeyedLiterals: input.NoUnkeyedLiterals, Flags: input.Flags}, runtime.ErrIntOverflow + } + if iNdEx >= l { + return protoiface.UnmarshalOutput{NoUnkeyedLiterals: input.NoUnkeyedLiterals, Flags: input.Flags}, io.ErrUnexpectedEOF + } + b := dAtA[iNdEx] + iNdEx++ + msglen |= int(b&0x7F) << shift + if b < 0x80 { + break + } + } + if msglen < 0 { + return protoiface.UnmarshalOutput{NoUnkeyedLiterals: input.NoUnkeyedLiterals, Flags: input.Flags}, runtime.ErrInvalidLength + } + postIndex := iNdEx + msglen + if postIndex < 0 { + return protoiface.UnmarshalOutput{NoUnkeyedLiterals: input.NoUnkeyedLiterals, Flags: input.Flags}, runtime.ErrInvalidLength + } + if postIndex > l { + return protoiface.UnmarshalOutput{NoUnkeyedLiterals: input.NoUnkeyedLiterals, Flags: input.Flags}, io.ErrUnexpectedEOF + } + x.Msgs = append(x.Msgs, &anypb.Any{}) + if err := options.Unmarshal(dAtA[iNdEx:postIndex], x.Msgs[len(x.Msgs)-1]); err != nil { + return protoiface.UnmarshalOutput{NoUnkeyedLiterals: input.NoUnkeyedLiterals, Flags: input.Flags}, err + } + iNdEx = postIndex + case 8: + if wireType != 2 { + return protoiface.UnmarshalOutput{NoUnkeyedLiterals: input.NoUnkeyedLiterals, Flags: input.Flags}, fmt.Errorf("proto: wrong wireType = %d for field Tip", wireType) + } + var msglen int + for shift := uint(0); ; shift += 7 { + if shift >= 64 { + return protoiface.UnmarshalOutput{NoUnkeyedLiterals: input.NoUnkeyedLiterals, Flags: input.Flags}, runtime.ErrIntOverflow + } + if iNdEx >= l { + return protoiface.UnmarshalOutput{NoUnkeyedLiterals: input.NoUnkeyedLiterals, Flags: input.Flags}, io.ErrUnexpectedEOF + } + b := dAtA[iNdEx] + iNdEx++ + msglen |= int(b&0x7F) << shift + if b < 0x80 { + break + } + } + if msglen < 0 { + return protoiface.UnmarshalOutput{NoUnkeyedLiterals: input.NoUnkeyedLiterals, Flags: input.Flags}, runtime.ErrInvalidLength + } + postIndex := iNdEx + msglen + if postIndex < 0 { + return protoiface.UnmarshalOutput{NoUnkeyedLiterals: input.NoUnkeyedLiterals, Flags: input.Flags}, runtime.ErrInvalidLength + } + if postIndex > l { + return protoiface.UnmarshalOutput{NoUnkeyedLiterals: input.NoUnkeyedLiterals, Flags: input.Flags}, io.ErrUnexpectedEOF + } + if x.Tip == nil { + x.Tip = &v1beta11.Tip{} + } + if err := options.Unmarshal(dAtA[iNdEx:postIndex], x.Tip); err != nil { + return protoiface.UnmarshalOutput{NoUnkeyedLiterals: input.NoUnkeyedLiterals, Flags: input.Flags}, err + } + iNdEx = postIndex + default: + iNdEx = preIndex + skippy, err := runtime.Skip(dAtA[iNdEx:]) + if err != nil { + return protoiface.UnmarshalOutput{NoUnkeyedLiterals: input.NoUnkeyedLiterals, Flags: input.Flags}, err + } + if (skippy < 0) || (iNdEx+skippy) < 0 { + return protoiface.UnmarshalOutput{NoUnkeyedLiterals: input.NoUnkeyedLiterals, Flags: input.Flags}, runtime.ErrInvalidLength + } + if (iNdEx + skippy) > l { + return protoiface.UnmarshalOutput{NoUnkeyedLiterals: input.NoUnkeyedLiterals, Flags: input.Flags}, io.ErrUnexpectedEOF + } + if !options.DiscardUnknown { + x.unknownFields = append(x.unknownFields, dAtA[iNdEx:iNdEx+skippy]...) + } + iNdEx += skippy + } + } + + if iNdEx > l { + return protoiface.UnmarshalOutput{NoUnkeyedLiterals: input.NoUnkeyedLiterals, Flags: input.Flags}, io.ErrUnexpectedEOF + } + return protoiface.UnmarshalOutput{NoUnkeyedLiterals: input.NoUnkeyedLiterals, Flags: input.Flags}, nil + } + return &protoiface.Methods{ + NoUnkeyedLiterals: struct{}{}, + Flags: protoiface.SupportMarshalDeterministic | protoiface.SupportUnmarshalDiscardUnknown, + Size: size, + Marshal: marshal, + Unmarshal: unmarshal, + Merge: nil, + CheckInitialized: nil, + } +} + +// Code generated by protoc-gen-go. DO NOT EDIT. +// versions: +// protoc-gen-go v1.27.0 +// protoc (unknown) +// source: aminojsonpb/aminojson.proto + +const ( + // Verify that this generated code is sufficiently up-to-date. + _ = protoimpl.EnforceVersion(20 - protoimpl.MinVersion) + // Verify that runtime/protoimpl is sufficiently up-to-date. + _ = protoimpl.EnforceVersion(protoimpl.MaxVersion - 20) +) + +// AminoSignFee is the legacy amino json sign mode compatible version of txv1beta1.Fee, and differs from that message +// by the name of the Gas field (GasLimit in txv1beta.Fee). +// Note: this is only used for signing, see x/tx/signing/aminojson.go for more details. +type AminoSignFee struct { + state protoimpl.MessageState + sizeCache protoimpl.SizeCache + unknownFields protoimpl.UnknownFields + + Amount []*v1beta1.Coin `protobuf:"bytes,1,rep,name=amount,proto3" json:"amount,omitempty"` + Gas uint64 `protobuf:"varint,2,opt,name=gas,proto3" json:"gas,omitempty"` + Payer string `protobuf:"bytes,3,opt,name=payer,proto3" json:"payer,omitempty"` + Granter string `protobuf:"bytes,4,opt,name=granter,proto3" json:"granter,omitempty"` +} + +func (x *AminoSignFee) Reset() { + *x = AminoSignFee{} + if protoimpl.UnsafeEnabled { + mi := &file_aminojsonpb_aminojson_proto_msgTypes[0] + ms := protoimpl.X.MessageStateOf(protoimpl.Pointer(x)) + ms.StoreMessageInfo(mi) + } +} + +func (x *AminoSignFee) String() string { + return protoimpl.X.MessageStringOf(x) +} + +func (*AminoSignFee) ProtoMessage() {} + +// Deprecated: Use AminoSignFee.ProtoReflect.Descriptor instead. +func (*AminoSignFee) Descriptor() ([]byte, []int) { + return file_aminojsonpb_aminojson_proto_rawDescGZIP(), []int{0} +} + +func (x *AminoSignFee) GetAmount() []*v1beta1.Coin { + if x != nil { + return x.Amount + } + return nil +} + +func (x *AminoSignFee) GetGas() uint64 { + if x != nil { + return x.Gas + } + return 0 +} + +func (x *AminoSignFee) GetPayer() string { + if x != nil { + return x.Payer + } + return "" +} + +func (x *AminoSignFee) GetGranter() string { + if x != nil { + return x.Granter + } + return "" +} + +// AminoSignDoc is a message container used to generate the SIGN_MODE_LEGACY_AMINO_JSON sign bytes with proto3 API. +// Note: This is only used for generated JSON in signing, see x/tx/signing/aminojson.go for more details. +type AminoSignDoc struct { + state protoimpl.MessageState + sizeCache protoimpl.SizeCache + unknownFields protoimpl.UnknownFields + + AccountNumber uint64 `protobuf:"varint,1,opt,name=account_number,json=accountNumber,proto3" json:"account_number,omitempty"` + Sequence uint64 `protobuf:"varint,2,opt,name=sequence,proto3" json:"sequence,omitempty"` + TimeoutHeight uint64 `protobuf:"varint,3,opt,name=timeout_height,json=timeoutHeight,proto3" json:"timeout_height,omitempty"` + ChainId string `protobuf:"bytes,4,opt,name=chain_id,json=chainId,proto3" json:"chain_id,omitempty"` + Memo string `protobuf:"bytes,5,opt,name=memo,proto3" json:"memo,omitempty"` + Fee *AminoSignFee `protobuf:"bytes,6,opt,name=fee,proto3" json:"fee,omitempty"` + Msgs []*anypb.Any `protobuf:"bytes,7,rep,name=msgs,proto3" json:"msgs,omitempty"` + Tip *v1beta11.Tip `protobuf:"bytes,8,opt,name=tip,proto3" json:"tip,omitempty"` +} + +func (x *AminoSignDoc) Reset() { + *x = AminoSignDoc{} + if protoimpl.UnsafeEnabled { + mi := &file_aminojsonpb_aminojson_proto_msgTypes[1] + ms := protoimpl.X.MessageStateOf(protoimpl.Pointer(x)) + ms.StoreMessageInfo(mi) + } +} + +func (x *AminoSignDoc) String() string { + return protoimpl.X.MessageStringOf(x) +} + +func (*AminoSignDoc) ProtoMessage() {} + +// Deprecated: Use AminoSignDoc.ProtoReflect.Descriptor instead. +func (*AminoSignDoc) Descriptor() ([]byte, []int) { + return file_aminojsonpb_aminojson_proto_rawDescGZIP(), []int{1} +} + +func (x *AminoSignDoc) GetAccountNumber() uint64 { + if x != nil { + return x.AccountNumber + } + return 0 +} + +func (x *AminoSignDoc) GetSequence() uint64 { + if x != nil { + return x.Sequence + } + return 0 +} + +func (x *AminoSignDoc) GetTimeoutHeight() uint64 { + if x != nil { + return x.TimeoutHeight + } + return 0 +} + +func (x *AminoSignDoc) GetChainId() string { + if x != nil { + return x.ChainId + } + return "" +} + +func (x *AminoSignDoc) GetMemo() string { + if x != nil { + return x.Memo + } + return "" +} + +func (x *AminoSignDoc) GetFee() *AminoSignFee { + if x != nil { + return x.Fee + } + return nil +} + +func (x *AminoSignDoc) GetMsgs() []*anypb.Any { + if x != nil { + return x.Msgs + } + return nil +} + +func (x *AminoSignDoc) GetTip() *v1beta11.Tip { + if x != nil { + return x.Tip + } + return nil +} + +var File_aminojsonpb_aminojson_proto protoreflect.FileDescriptor + +var file_aminojsonpb_aminojson_proto_rawDesc = []byte{ + 0x0a, 0x1b, 0x61, 0x6d, 0x69, 0x6e, 0x6f, 0x6a, 0x73, 0x6f, 0x6e, 0x70, 0x62, 0x2f, 0x61, 0x6d, + 0x69, 0x6e, 0x6f, 0x6a, 0x73, 0x6f, 0x6e, 0x2e, 0x70, 0x72, 0x6f, 0x74, 0x6f, 0x1a, 0x19, 0x63, + 0x6f, 0x73, 0x6d, 0x6f, 0x73, 0x5f, 0x70, 0x72, 0x6f, 0x74, 0x6f, 0x2f, 0x63, 0x6f, 0x73, 0x6d, + 0x6f, 0x73, 0x2e, 0x70, 0x72, 0x6f, 0x74, 0x6f, 0x1a, 0x11, 0x61, 0x6d, 0x69, 0x6e, 0x6f, 0x2f, + 0x61, 0x6d, 0x69, 0x6e, 0x6f, 0x2e, 0x70, 0x72, 0x6f, 0x74, 0x6f, 0x1a, 0x1e, 0x63, 0x6f, 0x73, + 0x6d, 0x6f, 0x73, 0x2f, 0x62, 0x61, 0x73, 0x65, 0x2f, 0x76, 0x31, 0x62, 0x65, 0x74, 0x61, 0x31, + 0x2f, 0x63, 0x6f, 0x69, 0x6e, 0x2e, 0x70, 0x72, 0x6f, 0x74, 0x6f, 0x1a, 0x19, 0x67, 0x6f, 0x6f, + 0x67, 0x6c, 0x65, 0x2f, 0x70, 0x72, 0x6f, 0x74, 0x6f, 0x62, 0x75, 0x66, 0x2f, 0x61, 0x6e, 0x79, + 0x2e, 0x70, 0x72, 0x6f, 0x74, 0x6f, 0x1a, 0x1a, 0x63, 0x6f, 0x73, 0x6d, 0x6f, 0x73, 0x2f, 0x74, + 0x78, 0x2f, 0x76, 0x31, 0x62, 0x65, 0x74, 0x61, 0x31, 0x2f, 0x74, 0x78, 0x2e, 0x70, 0x72, 0x6f, + 0x74, 0x6f, 0x22, 0xa2, 0x01, 0x0a, 0x0c, 0x41, 0x6d, 0x69, 0x6e, 0x6f, 0x53, 0x69, 0x67, 0x6e, + 0x46, 0x65, 0x65, 0x12, 0x49, 0x0a, 0x06, 0x61, 0x6d, 0x6f, 0x75, 0x6e, 0x74, 0x18, 0x01, 0x20, + 0x03, 0x28, 0x0b, 0x32, 0x19, 0x2e, 0x63, 0x6f, 0x73, 0x6d, 0x6f, 0x73, 0x2e, 0x62, 0x61, 0x73, + 0x65, 0x2e, 0x76, 0x31, 0x62, 0x65, 0x74, 0x61, 0x31, 0x2e, 0x43, 0x6f, 0x69, 0x6e, 0x42, 0x16, + 0x9a, 0xe7, 0xb0, 0x2a, 0x0c, 0x6c, 0x65, 0x67, 0x61, 0x63, 0x79, 0x5f, 0x63, 0x6f, 0x69, 0x6e, + 0x73, 0xa8, 0xe7, 0xb0, 0x2a, 0x01, 0x52, 0x06, 0x61, 0x6d, 0x6f, 0x75, 0x6e, 0x74, 0x12, 0x17, + 0x0a, 0x03, 0x67, 0x61, 0x73, 0x18, 0x02, 0x20, 0x01, 0x28, 0x04, 0x42, 0x05, 0xa8, 0xe7, 0xb0, + 0x2a, 0x01, 0x52, 0x03, 0x67, 0x61, 0x73, 0x12, 0x14, 0x0a, 0x05, 0x70, 0x61, 0x79, 0x65, 0x72, + 0x18, 0x03, 0x20, 0x01, 0x28, 0x09, 0x52, 0x05, 0x70, 0x61, 0x79, 0x65, 0x72, 0x12, 0x18, 0x0a, + 0x07, 0x67, 0x72, 0x61, 0x6e, 0x74, 0x65, 0x72, 0x18, 0x04, 0x20, 0x01, 0x28, 0x09, 0x52, 0x07, + 0x67, 0x72, 0x61, 0x6e, 0x74, 0x65, 0x72, 0x22, 0x9c, 0x02, 0x0a, 0x0c, 0x41, 0x6d, 0x69, 0x6e, + 0x6f, 0x53, 0x69, 0x67, 0x6e, 0x44, 0x6f, 0x63, 0x12, 0x25, 0x0a, 0x0e, 0x61, 0x63, 0x63, 0x6f, + 0x75, 0x6e, 0x74, 0x5f, 0x6e, 0x75, 0x6d, 0x62, 0x65, 0x72, 0x18, 0x01, 0x20, 0x01, 0x28, 0x04, + 0x52, 0x0d, 0x61, 0x63, 0x63, 0x6f, 0x75, 0x6e, 0x74, 0x4e, 0x75, 0x6d, 0x62, 0x65, 0x72, 0x12, + 0x1a, 0x0a, 0x08, 0x73, 0x65, 0x71, 0x75, 0x65, 0x6e, 0x63, 0x65, 0x18, 0x02, 0x20, 0x01, 0x28, + 0x04, 0x52, 0x08, 0x73, 0x65, 0x71, 0x75, 0x65, 0x6e, 0x63, 0x65, 0x12, 0x25, 0x0a, 0x0e, 0x74, + 0x69, 0x6d, 0x65, 0x6f, 0x75, 0x74, 0x5f, 0x68, 0x65, 0x69, 0x67, 0x68, 0x74, 0x18, 0x03, 0x20, + 0x01, 0x28, 0x04, 0x52, 0x0d, 0x74, 0x69, 0x6d, 0x65, 0x6f, 0x75, 0x74, 0x48, 0x65, 0x69, 0x67, + 0x68, 0x74, 0x12, 0x19, 0x0a, 0x08, 0x63, 0x68, 0x61, 0x69, 0x6e, 0x5f, 0x69, 0x64, 0x18, 0x04, + 0x20, 0x01, 0x28, 0x09, 0x52, 0x07, 0x63, 0x68, 0x61, 0x69, 0x6e, 0x49, 0x64, 0x12, 0x12, 0x0a, + 0x04, 0x6d, 0x65, 0x6d, 0x6f, 0x18, 0x05, 0x20, 0x01, 0x28, 0x09, 0x52, 0x04, 0x6d, 0x65, 0x6d, + 0x6f, 0x12, 0x1f, 0x0a, 0x03, 0x66, 0x65, 0x65, 0x18, 0x06, 0x20, 0x01, 0x28, 0x0b, 0x32, 0x0d, + 0x2e, 0x41, 0x6d, 0x69, 0x6e, 0x6f, 0x53, 0x69, 0x67, 0x6e, 0x46, 0x65, 0x65, 0x52, 0x03, 0x66, + 0x65, 0x65, 0x12, 0x28, 0x0a, 0x04, 0x6d, 0x73, 0x67, 0x73, 0x18, 0x07, 0x20, 0x03, 0x28, 0x0b, + 0x32, 0x14, 0x2e, 0x67, 0x6f, 0x6f, 0x67, 0x6c, 0x65, 0x2e, 0x70, 0x72, 0x6f, 0x74, 0x6f, 0x62, + 0x75, 0x66, 0x2e, 0x41, 0x6e, 0x79, 0x52, 0x04, 0x6d, 0x73, 0x67, 0x73, 0x12, 0x28, 0x0a, 0x03, + 0x74, 0x69, 0x70, 0x18, 0x08, 0x20, 0x01, 0x28, 0x0b, 0x32, 0x16, 0x2e, 0x63, 0x6f, 0x73, 0x6d, + 0x6f, 0x73, 0x2e, 0x74, 0x78, 0x2e, 0x76, 0x31, 0x62, 0x65, 0x74, 0x61, 0x31, 0x2e, 0x54, 0x69, + 0x70, 0x52, 0x03, 0x74, 0x69, 0x70, 0x42, 0x4b, 0x42, 0x0e, 0x41, 0x6d, 0x69, 0x6e, 0x6f, 0x6a, + 0x73, 0x6f, 0x6e, 0x50, 0x72, 0x6f, 0x74, 0x6f, 0x50, 0x01, 0x5a, 0x37, 0x63, 0x6f, 0x73, 0x6d, + 0x6f, 0x73, 0x73, 0x64, 0x6b, 0x2e, 0x69, 0x6f, 0x2f, 0x78, 0x2f, 0x74, 0x78, 0x2f, 0x61, 0x6d, + 0x69, 0x6e, 0x6f, 0x6a, 0x73, 0x6f, 0x6e, 0x2f, 0x69, 0x6e, 0x74, 0x65, 0x72, 0x6e, 0x61, 0x6c, + 0x2f, 0x74, 0x65, 0x73, 0x74, 0x70, 0x62, 0x2f, 0x61, 0x6d, 0x69, 0x6e, 0x6f, 0x6a, 0x73, 0x6f, + 0x6e, 0x70, 0x62, 0x62, 0x06, 0x70, 0x72, 0x6f, 0x74, 0x6f, 0x33, +} + +var ( + file_aminojsonpb_aminojson_proto_rawDescOnce sync.Once + file_aminojsonpb_aminojson_proto_rawDescData = file_aminojsonpb_aminojson_proto_rawDesc +) + +func file_aminojsonpb_aminojson_proto_rawDescGZIP() []byte { + file_aminojsonpb_aminojson_proto_rawDescOnce.Do(func() { + file_aminojsonpb_aminojson_proto_rawDescData = protoimpl.X.CompressGZIP(file_aminojsonpb_aminojson_proto_rawDescData) + }) + return file_aminojsonpb_aminojson_proto_rawDescData +} + +var file_aminojsonpb_aminojson_proto_msgTypes = make([]protoimpl.MessageInfo, 2) +var file_aminojsonpb_aminojson_proto_goTypes = []interface{}{ + (*AminoSignFee)(nil), // 0: AminoSignFee + (*AminoSignDoc)(nil), // 1: AminoSignDoc + (*v1beta1.Coin)(nil), // 2: cosmos.base.v1beta1.Coin + (*anypb.Any)(nil), // 3: google.protobuf.Any + (*v1beta11.Tip)(nil), // 4: cosmos.tx.v1beta1.Tip +} +var file_aminojsonpb_aminojson_proto_depIdxs = []int32{ + 2, // 0: AminoSignFee.amount:type_name -> cosmos.base.v1beta1.Coin + 0, // 1: AminoSignDoc.fee:type_name -> AminoSignFee + 3, // 2: AminoSignDoc.msgs:type_name -> google.protobuf.Any + 4, // 3: AminoSignDoc.tip:type_name -> cosmos.tx.v1beta1.Tip + 4, // [4:4] is the sub-list for method output_type + 4, // [4:4] is the sub-list for method input_type + 4, // [4:4] is the sub-list for extension type_name + 4, // [4:4] is the sub-list for extension extendee + 0, // [0:4] is the sub-list for field type_name +} + +func init() { file_aminojsonpb_aminojson_proto_init() } +func file_aminojsonpb_aminojson_proto_init() { + if File_aminojsonpb_aminojson_proto != nil { + return + } + if !protoimpl.UnsafeEnabled { + file_aminojsonpb_aminojson_proto_msgTypes[0].Exporter = func(v interface{}, i int) interface{} { + switch v := v.(*AminoSignFee); i { + case 0: + return &v.state + case 1: + return &v.sizeCache + case 2: + return &v.unknownFields + default: + return nil + } + } + file_aminojsonpb_aminojson_proto_msgTypes[1].Exporter = func(v interface{}, i int) interface{} { + switch v := v.(*AminoSignDoc); i { + case 0: + return &v.state + case 1: + return &v.sizeCache + case 2: + return &v.unknownFields + default: + return nil + } + } + } + type x struct{} + out := protoimpl.TypeBuilder{ + File: protoimpl.DescBuilder{ + GoPackagePath: reflect.TypeOf(x{}).PkgPath(), + RawDescriptor: file_aminojsonpb_aminojson_proto_rawDesc, + NumEnums: 0, + NumMessages: 2, + NumExtensions: 0, + NumServices: 0, + }, + GoTypes: file_aminojsonpb_aminojson_proto_goTypes, + DependencyIndexes: file_aminojsonpb_aminojson_proto_depIdxs, + MessageInfos: file_aminojsonpb_aminojson_proto_msgTypes, + }.Build() + File_aminojsonpb_aminojson_proto = out.File + file_aminojsonpb_aminojson_proto_rawDesc = nil + file_aminojsonpb_aminojson_proto_goTypes = nil + file_aminojsonpb_aminojson_proto_depIdxs = nil +} diff --git a/x/tx/signing/aminojson/internal/buf.lock b/x/tx/signing/aminojson/internal/buf.lock index 4dd297e431c1..88709c98ef99 100644 --- a/x/tx/signing/aminojson/internal/buf.lock +++ b/x/tx/signing/aminojson/internal/buf.lock @@ -5,3 +5,7 @@ deps: owner: cosmos repository: cosmos-proto commit: 1935555c206d4afb9e94615dfd0fad31 + - remote: buf.build + owner: cosmos + repository: gogo-proto + commit: 34d970b699f84aa382f3c29773a60836 diff --git a/x/tx/signing/aminojson/internal/buf.yaml b/x/tx/signing/aminojson/internal/buf.yaml index 2016baa2a8d7..ab3dff3940bd 100644 --- a/x/tx/signing/aminojson/internal/buf.yaml +++ b/x/tx/signing/aminojson/internal/buf.yaml @@ -1,5 +1,6 @@ version: v1 deps: + - buf.build/cosmos/gogo-proto - buf.build/cosmos/cosmos-proto lint: use: diff --git a/x/tx/signing/aminojson/json_marshal.go b/x/tx/signing/aminojson/json_marshal.go index 49c2e7f08cab..01a91c7a2e58 100644 --- a/x/tx/signing/aminojson/json_marshal.go +++ b/x/tx/signing/aminojson/json_marshal.go @@ -186,15 +186,16 @@ func (enc Encoder) marshalMessage(msg protoreflect.Message, writer io.Writer) er if !msg.Has(f) { // msg.WhichOneof(oneof) == nil: no field of the oneof has been set // !emptyOneOfWritten: we haven't written a null for this oneof yet (only write one null per empty oneof) - if isOneOf && msg.WhichOneof(oneof) == nil && !emptyOneOfWritten[oneofFieldName] { + switch { + case isOneOf && msg.WhichOneof(oneof) == nil && !emptyOneOfWritten[oneofFieldName]: name = oneofFieldName writeNil = true emptyOneOfWritten[oneofFieldName] = true - } else if omitEmpty(f) { + case omitEmpty(f): continue - } else if f.Kind() == protoreflect.MessageKind && + case f.Kind() == protoreflect.MessageKind && f.Cardinality() != protoreflect.Repeated && - !v.Message().IsValid() { + !v.Message().IsValid(): return errors.Errorf("not supported: dont_omit_empty=true on invalid (nil?) message field: %s", name) } } diff --git a/x/tx/signing/aminojson/time.go b/x/tx/signing/aminojson/time.go index aa0ca9c84f5c..da02514c0255 100644 --- a/x/tx/signing/aminojson/time.go +++ b/x/tx/signing/aminojson/time.go @@ -46,7 +46,7 @@ func marshalTimestamp(message protoreflect.Message, writer io.Writer) error { // MaxDurationSeconds the maximum number of seconds (when expressed as nanoseconds) which can fit in an int64. // gogoproto encodes google.protobuf.Duration as a time.Duration, which is 64-bit signed integer. -const MaxDurationSeconds = int64(math.MaxInt64/int(1e9)) - 1 +const MaxDurationSeconds = int64(math.MaxInt64)/1e9 - 1 func marshalDuration(message protoreflect.Message, writer io.Writer) error { fields := message.Descriptor().Fields() diff --git a/x/tx/signing/context.go b/x/tx/signing/context.go new file mode 100644 index 000000000000..c8afe2e83891 --- /dev/null +++ b/x/tx/signing/context.go @@ -0,0 +1,320 @@ +package signing + +import ( + "errors" + "fmt" + + "cosmossdk.io/core/address" + cosmos_proto "github.com/cosmos/cosmos-proto" + "google.golang.org/protobuf/proto" + "google.golang.org/protobuf/reflect/protodesc" + "google.golang.org/protobuf/reflect/protoreflect" + "google.golang.org/protobuf/reflect/protoregistry" + "google.golang.org/protobuf/types/dynamicpb" + + msgv1 "cosmossdk.io/api/cosmos/msg/v1" +) + +// Context is a context for retrieving the list of signers from a +// message where signers are specified by the cosmos.msg.v1.signer protobuf +// option. It also contains the ProtoFileResolver and address.Codec's used +// for resolving message descriptors and converting addresses. +type Context struct { + fileResolver ProtoFileResolver + typeResolver protoregistry.MessageTypeResolver + addressCodec address.Codec + validatorAddressCodec address.Codec + getSignersFuncs map[protoreflect.FullName]getSignersFunc +} + +// Options are options for creating Context which will be used for signing operations. +type Options struct { + // FileResolver is the protobuf file resolver to use for resolving message descriptors. + // If it is nil, the global protobuf registry will be used. + FileResolver ProtoFileResolver + + // TypeResolver is the protobuf type resolver to use for resolving message types. + TypeResolver protoregistry.MessageTypeResolver + + // AddressCodec is the codec for converting addresses between strings and bytes. + AddressCodec address.Codec + + // ValidatorAddressCodec is the codec for converting validator addresses between strings and bytes. + ValidatorAddressCodec address.Codec +} + +// ProtoFileResolver is a protodesc.Resolver that also allows iterating over all +// files descriptors. It is a subset of the methods supported by protoregistry.Files. +type ProtoFileResolver interface { + protodesc.Resolver + RangeFiles(func(protoreflect.FileDescriptor) bool) +} + +// NewContext creates a new Context using the provided options. +func NewContext(options Options) (*Context, error) { + protoFiles := options.FileResolver + if protoFiles == nil { + protoFiles = protoregistry.GlobalFiles + } + + protoTypes := options.TypeResolver + if protoTypes == nil { + protoTypes = protoregistry.GlobalTypes + } + + if options.AddressCodec == nil { + return nil, errors.New("address codec is required") + } + + if options.ValidatorAddressCodec == nil { + return nil, errors.New("validator address codec is required") + } + + c := &Context{ + fileResolver: protoFiles, + typeResolver: protoTypes, + addressCodec: options.AddressCodec, + validatorAddressCodec: options.ValidatorAddressCodec, + getSignersFuncs: map[protoreflect.FullName]getSignersFunc{}, + } + + return c, c.init() +} + +type getSignersFunc func(proto.Message) ([][]byte, error) + +func getSignersFieldNames(descriptor protoreflect.MessageDescriptor) ([]string, error) { + signersFields := proto.GetExtension(descriptor.Options(), msgv1.E_Signer).([]string) + if len(signersFields) == 0 { + return nil, fmt.Errorf("no cosmos.msg.v1.signer option found for message %s", descriptor.FullName()) + } + + return signersFields, nil +} + +// init performs a dry run of getting all msg's signers. This has 2 benefits: +// - it will error if any Msg has forgotten the "cosmos.msg.v1.signer" +// annotation +// - it will pre-populate the context's internal cache for getSignersFuncs +// so that calling it in antehandlers will be faster. +func (c *Context) init() error { + var errs []error + c.fileResolver.RangeFiles(func(fd protoreflect.FileDescriptor) bool { + for i := 0; i < fd.Services().Len(); i++ { + sd := fd.Services().Get(i) + // We use the heuristic that services named "Msg" are exactly the + // ones that need the proto annotation check. + if sd.Name() != "Msg" { + continue + } + + for j := 0; j < sd.Methods().Len(); j++ { + md := sd.Methods().Get(j).Input() + msg := dynamicpb.NewMessage(md) + _, err := c.GetSigners(msg) + if err != nil { + errs = append(errs, err) + } + } + } + + return true + }) + + return errors.Join(errs...) +} + +func (c *Context) makeGetSignersFunc(descriptor protoreflect.MessageDescriptor) (getSignersFunc, error) { + signersFields, err := getSignersFieldNames(descriptor) + if err != nil { + return nil, err + } + + fieldGetters := make([]func(proto.Message, [][]byte) ([][]byte, error), len(signersFields)) + for i, fieldName := range signersFields { + field := descriptor.Fields().ByName(protoreflect.Name(fieldName)) + if field == nil { + return nil, fmt.Errorf("field %s not found in message %s", fieldName, descriptor.FullName()) + } + + if field.IsMap() || field.HasOptionalKeyword() { + return nil, fmt.Errorf("cosmos.msg.v1.signer field %s in message %s must not be a map or optional", fieldName, descriptor.FullName()) + } + + switch field.Kind() { + case protoreflect.StringKind: + addrCdc := c.getAddressCodec(field) + if field.IsList() { + fieldGetters[i] = func(msg proto.Message, arr [][]byte) ([][]byte, error) { + signers := msg.ProtoReflect().Get(field).List() + n := signers.Len() + for i := 0; i < n; i++ { + addrStr := signers.Get(i).String() + addrBz, err := addrCdc.StringToBytes(addrStr) + if err != nil { + return nil, err + } + arr = append(arr, addrBz) + } + return arr, nil + } + } else { + fieldGetters[i] = func(msg proto.Message, arr [][]byte) ([][]byte, error) { + addrStr := msg.ProtoReflect().Get(field).String() + addrBz, err := addrCdc.StringToBytes(addrStr) + if err != nil { + return nil, err + } + return append(arr, addrBz), nil + } + } + case protoreflect.MessageKind: + isList := field.IsList() + nestedMessage := field.Message() + nestedSignersFields, err := getSignersFieldNames(nestedMessage) + if err != nil { + return nil, err + } + + if len(nestedSignersFields) != 1 { + return nil, fmt.Errorf("nested cosmos.msg.v1.signer option in message %s must contain only one value", nestedMessage.FullName()) + } + + nestedFieldName := nestedSignersFields[0] + nestedField := nestedMessage.Fields().ByName(protoreflect.Name(nestedFieldName)) + nestedIsList := nestedField.IsList() + if nestedField == nil { + return nil, fmt.Errorf("field %s not found in message %s", nestedFieldName, nestedMessage.FullName()) + } + + if nestedField.Kind() != protoreflect.StringKind || nestedField.IsMap() || nestedField.HasOptionalKeyword() { + return nil, fmt.Errorf("nested signer field %s in message %s must be a simple string", nestedFieldName, nestedMessage.FullName()) + } + + addrCdc := c.getAddressCodec(nestedField) + + if isList { + if nestedIsList { + fieldGetters[i] = func(msg proto.Message, arr [][]byte) ([][]byte, error) { + msgs := msg.ProtoReflect().Get(field).List() + m := msgs.Len() + for i := 0; i < m; i++ { + signers := msgs.Get(i).Message().Get(nestedField).List() + n := signers.Len() + for j := 0; j < n; j++ { + addrStr := signers.Get(j).String() + addrBz, err := addrCdc.StringToBytes(addrStr) + if err != nil { + return nil, err + } + arr = append(arr, addrBz) + } + } + return arr, nil + } + } else { + fieldGetters[i] = func(msg proto.Message, arr [][]byte) ([][]byte, error) { + msgs := msg.ProtoReflect().Get(field).List() + m := msgs.Len() + for i := 0; i < m; i++ { + addrStr := msgs.Get(i).Message().Get(nestedField).String() + addrBz, err := addrCdc.StringToBytes(addrStr) + if err != nil { + return nil, err + } + arr = append(arr, addrBz) + } + return arr, nil + } + } + } else { + if nestedIsList { + fieldGetters[i] = func(msg proto.Message, arr [][]byte) ([][]byte, error) { + nestedMsg := msg.ProtoReflect().Get(field).Message() + signers := nestedMsg.Get(nestedField).List() + n := signers.Len() + for j := 0; j < n; j++ { + addrStr := signers.Get(j).String() + addrBz, err := addrCdc.StringToBytes(addrStr) + if err != nil { + return nil, err + } + arr = append(arr, addrBz) + } + return arr, nil + } + } else { + fieldGetters[i] = func(msg proto.Message, arr [][]byte) ([][]byte, error) { + addrStr := msg.ProtoReflect().Get(field).Message().Get(nestedField).String() + addrBz, err := addrCdc.StringToBytes(addrStr) + if err != nil { + return nil, err + } + return append(arr, addrBz), nil + } + } + } + + default: + return nil, fmt.Errorf("unexpected field type %s for field %s in message %s", field.Kind(), fieldName, descriptor.FullName()) + } + } + + return func(message proto.Message) ([][]byte, error) { + var signers [][]byte + for _, getter := range fieldGetters { + signers, err = getter(message, signers) + if err != nil { + return nil, err + } + } + return signers, nil + }, nil +} + +func (c *Context) getAddressCodec(field protoreflect.FieldDescriptor) address.Codec { + scalarOpt := proto.GetExtension(field.Options(), cosmos_proto.E_Scalar) + addrCdc := c.addressCodec + if scalarOpt != nil { + if scalarOpt.(string) == "cosmos.ValidatorAddressString" { + addrCdc = c.validatorAddressCodec + } + } + + return addrCdc +} + +// GetSigners returns the signers for a given message. +func (c *Context) GetSigners(msg proto.Message) ([][]byte, error) { + messageDescriptor := msg.ProtoReflect().Descriptor() + f, ok := c.getSignersFuncs[messageDescriptor.FullName()] + if !ok { + var err error + f, err = c.makeGetSignersFunc(messageDescriptor) + if err != nil { + return nil, err + } + c.getSignersFuncs[messageDescriptor.FullName()] = f + } + + return f(msg) +} + +// AddressCodec returns the address codec used by the context. +func (c *Context) AddressCodec() address.Codec { + return c.addressCodec +} + +// ValidatorAddressCodec returns the validator address codec used by the context. +func (c *Context) ValidatorAddressCodec() address.Codec { + return c.validatorAddressCodec +} + +// FileResolver returns the proto file resolver used by the context. +func (c *Context) FileResolver() ProtoFileResolver { + return c.fileResolver +} + +func (c *Context) TypeResolver() protoregistry.MessageTypeResolver { + return c.typeResolver +} diff --git a/x/tx/signing/context_test.go b/x/tx/signing/context_test.go new file mode 100644 index 000000000000..a5979e300d73 --- /dev/null +++ b/x/tx/signing/context_test.go @@ -0,0 +1,170 @@ +package signing + +import ( + "encoding/hex" + "strings" + "testing" + + bankv1beta1 "cosmossdk.io/api/cosmos/bank/v1beta1" + groupv1 "cosmossdk.io/api/cosmos/group/v1" + "cosmossdk.io/core/address" + "github.com/stretchr/testify/require" + "google.golang.org/protobuf/proto" + + "cosmossdk.io/x/tx/internal/testpb" +) + +func TestGetSigners(t *testing.T) { + ctx, err := NewContext(Options{ + AddressCodec: dummyAddressCodec{}, + ValidatorAddressCodec: dummyValidatorAddressCodec{}, + }) + require.NoError(t, err) + tests := []struct { + name string + msg proto.Message + want [][]byte + wantErr bool + }{ + { + name: "MsgSend", + msg: &bankv1beta1.MsgSend{ + FromAddress: hex.EncodeToString([]byte("foo")), + }, + want: [][]byte{[]byte("foo")}, + }, + { + name: "MsgMultiSend", + msg: &bankv1beta1.MsgMultiSend{ + Inputs: []*bankv1beta1.Input{ + {Address: hex.EncodeToString([]byte("foo"))}, + {Address: hex.EncodeToString([]byte("bar"))}, + }, + }, + want: [][]byte{[]byte("foo"), []byte("bar")}, + }, + { + name: "MsgSubmitProposal", + msg: &groupv1.MsgSubmitProposal{ + Proposers: []string{ + hex.EncodeToString([]byte("foo")), + hex.EncodeToString([]byte("bar")), + }, + }, + want: [][]byte{[]byte("foo"), []byte("bar")}, + }, + { + name: "simple", + msg: &testpb.SimpleSigner{Signer: hex.EncodeToString([]byte("foo"))}, + want: [][]byte{[]byte("foo")}, + }, + { + name: "repeated", + msg: &testpb.RepeatedSigner{Signer: []string{ + hex.EncodeToString([]byte("foo")), + hex.EncodeToString([]byte("bar")), + }}, + want: [][]byte{[]byte("foo"), []byte("bar")}, + }, + { + name: "nested", + msg: &testpb.NestedSigner{Inner: &testpb.NestedSigner_Inner{Signer: hex.EncodeToString([]byte("foo"))}}, + want: [][]byte{[]byte("foo")}, + }, + { + name: "nested repeated", + msg: &testpb.NestedRepeatedSigner{Inner: &testpb.NestedRepeatedSigner_Inner{Signer: []string{ + hex.EncodeToString([]byte("foo")), + hex.EncodeToString([]byte("bar")), + }}}, + want: [][]byte{[]byte("foo"), []byte("bar")}, + }, + { + name: "repeated nested", + msg: &testpb.RepeatedNestedSigner{Inner: []*testpb.RepeatedNestedSigner_Inner{ + {Signer: hex.EncodeToString([]byte("foo"))}, + {Signer: hex.EncodeToString([]byte("bar"))}, + }}, + want: [][]byte{[]byte("foo"), []byte("bar")}, + }, + { + name: "nested repeated", + msg: &testpb.NestedRepeatedSigner{Inner: &testpb.NestedRepeatedSigner_Inner{ + Signer: []string{ + hex.EncodeToString([]byte("foo")), + hex.EncodeToString([]byte("bar")), + }, + }}, + want: [][]byte{[]byte("foo"), []byte("bar")}, + }, + { + name: "repeated nested repeated", + msg: &testpb.RepeatedNestedRepeatedSigner{Inner: []*testpb.RepeatedNestedRepeatedSigner_Inner{ + {Signer: []string{ + hex.EncodeToString([]byte("foo")), + hex.EncodeToString([]byte("bar")), + }}, + {Signer: []string{ + hex.EncodeToString([]byte("baz")), + hex.EncodeToString([]byte("bam")), + }}, + {Signer: []string{ + hex.EncodeToString([]byte("blah")), + }}, + }}, + want: [][]byte{[]byte("foo"), []byte("bar"), []byte("baz"), []byte("bam"), []byte("blah")}, + }, + { + name: "bad", + msg: &testpb.BadSigner{}, + wantErr: true, + }, + { + name: "no signer", + msg: &testpb.NoSignerOption{}, + wantErr: true, + }, + { + name: "validator signer", + msg: &testpb.ValidatorSigner{ + Signer: "val" + hex.EncodeToString([]byte("foo")), + }, + want: [][]byte{[]byte("foo")}, + }, + } + for _, test := range tests { + t.Run(test.name, func(t *testing.T) { + signers, err := ctx.GetSigners(test.msg) + if test.wantErr { + require.Error(t, err) + } else { + require.NoError(t, err) + } + require.Equal(t, test.want, signers) + }) + } +} + +type dummyAddressCodec struct{} + +func (d dummyAddressCodec) StringToBytes(text string) ([]byte, error) { + return hex.DecodeString(text) +} + +func (d dummyAddressCodec) BytesToString(bz []byte) (string, error) { + return hex.EncodeToString(bz), nil +} + +var _ address.Codec = dummyAddressCodec{} + +type dummyValidatorAddressCodec struct{} + +func (d dummyValidatorAddressCodec) StringToBytes(text string) ([]byte, error) { + return hex.DecodeString(strings.TrimPrefix(text, "val")) +} + +func (d dummyValidatorAddressCodec) BytesToString(bz []byte) (string, error) { + return "val" + hex.EncodeToString(bz), nil +} + +var _ address.Codec = dummyValidatorAddressCodec{} diff --git a/x/tx/signing/direct/direct.go b/x/tx/signing/direct/direct.go index 450f0af4e3ba..6cacb63aaf84 100644 --- a/x/tx/signing/direct/direct.go +++ b/x/tx/signing/direct/direct.go @@ -23,7 +23,7 @@ func (SignModeHandler) GetSignBytes(_ context.Context, signerData signing.Signer return proto.Marshal(&txv1beta1.SignDoc{ BodyBytes: txData.BodyBytes, AuthInfoBytes: txData.AuthInfoBytes, - ChainId: signerData.ChainId, + ChainId: signerData.ChainID, AccountNumber: signerData.AccountNumber, }) } diff --git a/x/tx/signing/direct/direct_test.go b/x/tx/signing/direct/direct_test.go index d28d25e6a77e..d75c39652786 100644 --- a/x/tx/signing/direct/direct_test.go +++ b/x/tx/signing/direct/direct_test.go @@ -58,12 +58,12 @@ func TestDirectModeHandler(t *testing.T) { directHandler := direct.SignModeHandler{} - chainId := "test-chain" + chainID := "test-chain" accNum := uint64(1) signingData := signing.SignerData{ Address: "", - ChainId: chainId, + ChainID: chainID, AccountNumber: accNum, PubKey: pk, } @@ -89,7 +89,7 @@ func TestDirectModeHandler(t *testing.T) { signBytes2, err := proto.Marshal(&txv1beta1.SignDoc{ BodyBytes: txData.BodyBytes, AuthInfoBytes: txData.AuthInfoBytes, - ChainId: chainId, + ChainId: chainID, AccountNumber: accNum, }) require.NoError(t, err) diff --git a/x/tx/signing/direct_aux/direct_aux.go b/x/tx/signing/directaux/direct_aux.go similarity index 66% rename from x/tx/signing/direct_aux/direct_aux.go rename to x/tx/signing/directaux/direct_aux.go index 7af3fc01ae07..f20b56f513e0 100644 --- a/x/tx/signing/direct_aux/direct_aux.go +++ b/x/tx/signing/directaux/direct_aux.go @@ -1,4 +1,4 @@ -package direct_aux +package directaux import ( "context" @@ -6,42 +6,40 @@ import ( "github.com/cosmos/cosmos-proto/anyutil" "google.golang.org/protobuf/proto" - "google.golang.org/protobuf/reflect/protodesc" "google.golang.org/protobuf/reflect/protoregistry" signingv1beta1 "cosmossdk.io/api/cosmos/tx/signing/v1beta1" txv1beta1 "cosmossdk.io/api/cosmos/tx/v1beta1" + "cosmossdk.io/x/tx/signing" ) // SignModeHandler is the SIGN_MODE_DIRECT_AUX implementation of signing.SignModeHandler. type SignModeHandler struct { - signersContext *signing.GetSignersContext - fileResolver protodesc.Resolver + signersContext *signing.Context + fileResolver signing.ProtoFileResolver typeResolver protoregistry.MessageTypeResolver } // SignModeHandlerOptions are the options for the SignModeHandler. type SignModeHandlerOptions struct { - // FileResolver is the protodesc.Resolver to use for resolving proto files when unpacking any messages. - FileResolver protodesc.Resolver - - // TypeResolver is the protoregistry.MessageTypeResolver to use for resolving proto types when unpacking any messages. + // TypeResolver is the protoregistry.MessageTypeResolver to use for resolving protobuf types when unpacking any messages. TypeResolver protoregistry.MessageTypeResolver - // SignersContext is the signing.GetSignersContext to use for getting signers. - SignersContext *signing.GetSignersContext + // SignersContext is the signing.Context to use for getting signers. + SignersContext *signing.Context } // NewSignModeHandler returns a new SignModeHandler. func NewSignModeHandler(options SignModeHandlerOptions) (SignModeHandler, error) { h := SignModeHandler{} - if options.FileResolver == nil { - h.fileResolver = protoregistry.GlobalFiles - } else { - h.fileResolver = options.FileResolver + if options.SignersContext == nil { + return h, fmt.Errorf("signers context is required") } + h.signersContext = options.SignersContext + + h.fileResolver = h.signersContext.FileResolver() if options.TypeResolver == nil { h.typeResolver = protoregistry.GlobalTypes @@ -49,16 +47,6 @@ func NewSignModeHandler(options SignModeHandlerOptions) (SignModeHandler, error) h.typeResolver = options.TypeResolver } - if options.SignersContext == nil { - var err error - h.signersContext, err = signing.NewGetSignersContext(signing.GetSignersOptions{ProtoFiles: h.fileResolver}) - if err != nil { - return h, err - } - } else { - h.signersContext = options.SignersContext - } - return h, nil } @@ -71,19 +59,20 @@ func (h SignModeHandler) Mode() signingv1beta1.SignMode { // getFirstSigner returns the first signer from the first message in the tx. It replicates behavior in // https://github.com/cosmos/cosmos-sdk/blob/4a6a1e3cb8de459891cb0495052589673d14ef51/x/auth/tx/builder.go#L142 -func (h SignModeHandler) getFirstSigner(txData signing.TxData) (string, error) { - for _, anyMsg := range txData.Body.Messages { - msg, err := anyutil.Unpack(anyMsg, h.fileResolver, h.typeResolver) - if err != nil { - return "", err - } - signer, err := h.signersContext.GetSigners(msg) - if err != nil { - return "", err - } - return signer[0], nil +func (h SignModeHandler) getFirstSigner(txData signing.TxData) ([]byte, error) { + if len(txData.Body.Messages) == 0 { + return nil, fmt.Errorf("no signer found") + } + + msg, err := anyutil.Unpack(txData.Body.Messages[0], h.fileResolver, h.typeResolver) + if err != nil { + return nil, err + } + signer, err := h.signersContext.GetSigners(msg) + if err != nil { + return nil, err } - return "", fmt.Errorf("no signer found") + return signer[0], nil } // GetSignBytes implements signing.SignModeHandler.GetSignBytes. @@ -96,7 +85,10 @@ func (h SignModeHandler) GetSignBytes( if err != nil { return nil, err } - feePayer = fp + feePayer, err = h.signersContext.AddressCodec().BytesToString(fp) + if err != nil { + return nil, err + } } if feePayer == signerData.Address { return nil, fmt.Errorf("fee payer %s cannot sign with %s: unauthorized", @@ -106,7 +98,7 @@ func (h SignModeHandler) GetSignBytes( signDocDirectAux := &txv1beta1.SignDocDirectAux{ BodyBytes: txData.BodyBytes, PublicKey: signerData.PubKey, - ChainId: signerData.ChainId, + ChainId: signerData.ChainID, AccountNumber: signerData.AccountNumber, Sequence: signerData.Sequence, Tip: txData.AuthInfo.Tip, diff --git a/x/tx/signing/direct_aux/direct_aux_test.go b/x/tx/signing/directaux/direct_aux_test.go similarity index 84% rename from x/tx/signing/direct_aux/direct_aux_test.go rename to x/tx/signing/directaux/direct_aux_test.go index 2b82ce59dd78..4fba90b7e1aa 100644 --- a/x/tx/signing/direct_aux/direct_aux_test.go +++ b/x/tx/signing/directaux/direct_aux_test.go @@ -1,10 +1,12 @@ -package direct_aux_test +package directaux_test import ( "context" + "encoding/hex" "fmt" "testing" + "cosmossdk.io/core/address" "github.com/cosmos/cosmos-proto/anyutil" "github.com/stretchr/testify/require" "google.golang.org/protobuf/proto" @@ -15,8 +17,9 @@ import ( "cosmossdk.io/api/cosmos/crypto/secp256k1" signingv1beta1 "cosmossdk.io/api/cosmos/tx/signing/v1beta1" txv1beta1 "cosmossdk.io/api/cosmos/tx/v1beta1" + "cosmossdk.io/x/tx/signing" - "cosmossdk.io/x/tx/signing/direct_aux" + "cosmossdk.io/x/tx/signing/directaux" ) func TestDirectAuxHandler(t *testing.T) { @@ -66,7 +69,7 @@ func TestDirectAuxHandler(t *testing.T) { } signingData := signing.SignerData{ - ChainId: chainID, + ChainID: chainID, AccountNumber: accNum, Sequence: accSeq, Address: "", @@ -83,12 +86,19 @@ func TestDirectAuxHandler(t *testing.T) { AuthInfoBytes: authInfoBz, BodyBytes: bodyBz, } - modeHandler, err := direct_aux.NewSignModeHandler(direct_aux.SignModeHandlerOptions{}) + signersCtx, err := signing.NewContext(signing.Options{ + AddressCodec: dummyAddressCodec{}, + ValidatorAddressCodec: dummyAddressCodec{}, + }) + require.NoError(t, err) + modeHandler, err := directaux.NewSignModeHandler(directaux.SignModeHandlerOptions{ + SignersContext: signersCtx, + }) require.NoError(t, err) t.Log("verify fee payer cannot use SIGN_MODE_DIRECT_AUX") feePayerSigningData := signing.SignerData{ - ChainId: chainID, + ChainID: chainID, AccountNumber: accNum, Address: feePayerAddr, PubKey: anyPk, @@ -143,3 +153,15 @@ func TestDirectAuxHandler(t *testing.T) { require.NoError(t, err) require.NotEqual(t, expectedSignBytes, signBytes) } + +type dummyAddressCodec struct{} + +func (d dummyAddressCodec) StringToBytes(text string) ([]byte, error) { + return hex.DecodeString(text) +} + +func (d dummyAddressCodec) BytesToString(bz []byte) (string, error) { + return hex.EncodeToString(bz), nil +} + +var _ address.Codec = dummyAddressCodec{} diff --git a/x/tx/signing/get_signers.go b/x/tx/signing/get_signers.go deleted file mode 100644 index 295f1b9ea4af..000000000000 --- a/x/tx/signing/get_signers.go +++ /dev/null @@ -1,220 +0,0 @@ -package signing - -import ( - "errors" - "fmt" - - "google.golang.org/protobuf/proto" - "google.golang.org/protobuf/reflect/protodesc" - "google.golang.org/protobuf/reflect/protoreflect" - "google.golang.org/protobuf/reflect/protoregistry" - "google.golang.org/protobuf/types/dynamicpb" - - msgv1 "cosmossdk.io/api/cosmos/msg/v1" -) - -// GetSignersContext is a context for retrieving the list of signers from a -// message where signers are specified by the cosmos.msg.v1.signer protobuf -// option. -type GetSignersContext struct { - protoFiles protodesc.Resolver - getSignersFuncs map[protoreflect.FullName]getSignersFunc -} - -// GetSignersOptions are options for creating GetSignersContext. -type GetSignersOptions struct { - // ProtoFiles are the protobuf files to use for resolving message descriptors. - // If it is nil, the global protobuf registry will be used. - ProtoFiles protodesc.Resolver -} - -// NewGetSignersContext creates a new GetSignersContext using the provided options. -func NewGetSignersContext(options GetSignersOptions) (*GetSignersContext, error) { - protoFiles := options.ProtoFiles - if protoFiles == nil { - protoFiles = protoregistry.GlobalFiles - } - - c := &GetSignersContext{ - protoFiles: protoFiles, - getSignersFuncs: map[protoreflect.FullName]getSignersFunc{}, - } - - return c, c.init() -} - -type getSignersFunc func(proto.Message) []string - -func getSignersFieldNames(descriptor protoreflect.MessageDescriptor) ([]string, error) { - signersFields := proto.GetExtension(descriptor.Options(), msgv1.E_Signer).([]string) - if signersFields == nil || len(signersFields) == 0 { - return nil, fmt.Errorf("no cosmos.msg.v1.signer option found for message %s", descriptor.FullName()) - } - - return signersFields, nil -} - -// init performs a dry run of getting all msg's signers. This has 2 benefits: -// - it will error if any Msg has forgotten the "cosmos.msg.v1.signer" -// annotation -// - it will pre-populate the context's internal cache for getSignersFuncs -// so that calling it in antehandlers will be faster. -func (c *GetSignersContext) init() error { - fs, ok := c.protoFiles.(*protoregistry.Files) - if !ok { - return fmt.Errorf("expected *protoregistry.Files in GetSignersContext, got %T", c.protoFiles) - } - - var errs []error - fs.RangeFiles(func(fd protoreflect.FileDescriptor) bool { - for i := 0; i < fd.Services().Len(); i++ { - sd := fd.Services().Get(i) - // We use the heuristic that services named "Msg" are exactly the - // ones that need the proto annotation check. - if sd.Name() != "Msg" { - continue - } - - for j := 0; j < sd.Methods().Len(); j++ { - md := sd.Methods().Get(j).Input() - msg := dynamicpb.NewMessage(md) - _, err := c.GetSigners(msg) - if err != nil { - errs = append(errs, err) - } - } - } - - return true - }) - - return errors.Join(errs...) -} - -func (*GetSignersContext) makeGetSignersFunc(descriptor protoreflect.MessageDescriptor) (getSignersFunc, error) { - signersFields, err := getSignersFieldNames(descriptor) - if err != nil { - return nil, err - } - - fieldGetters := make([]func(proto.Message, []string) []string, len(signersFields)) - for i, fieldName := range signersFields { - field := descriptor.Fields().ByName(protoreflect.Name(fieldName)) - if field == nil { - return nil, fmt.Errorf("field %s not found in message %s", fieldName, descriptor.FullName()) - } - - if field.IsMap() || field.HasOptionalKeyword() { - return nil, fmt.Errorf("cosmos.msg.v1.signer field %s in message %s must not be a map or optional", fieldName, descriptor.FullName()) - } - - switch field.Kind() { - case protoreflect.StringKind: - if field.IsList() { - fieldGetters[i] = func(msg proto.Message, arr []string) []string { - signers := msg.ProtoReflect().Get(field).List() - n := signers.Len() - for i := 0; i < n; i++ { - arr = append(arr, signers.Get(i).String()) - } - return arr - } - } else { - fieldGetters[i] = func(msg proto.Message, arr []string) []string { - return append(arr, msg.ProtoReflect().Get(field).String()) - } - } - case protoreflect.MessageKind: - isList := field.IsList() - nestedMessage := field.Message() - nestedSignersFields, err := getSignersFieldNames(nestedMessage) - if err != nil { - return nil, err - } - - if len(nestedSignersFields) != 1 { - return nil, fmt.Errorf("nested cosmos.msg.v1.signer option in message %s must contain only one value", nestedMessage.FullName()) - } - - nestedFieldName := nestedSignersFields[0] - nestedField := nestedMessage.Fields().ByName(protoreflect.Name(nestedFieldName)) - nestedIsList := nestedField.IsList() - if nestedField == nil { - return nil, fmt.Errorf("field %s not found in message %s", nestedFieldName, nestedMessage.FullName()) - } - - if nestedField.Kind() != protoreflect.StringKind || nestedField.IsMap() || nestedField.HasOptionalKeyword() { - return nil, fmt.Errorf("nested signer field %s in message %s must be a simple string", nestedFieldName, nestedMessage.FullName()) - } - - if isList { - if nestedIsList { - fieldGetters[i] = func(msg proto.Message, arr []string) []string { - msgs := msg.ProtoReflect().Get(field).List() - m := msgs.Len() - for i := 0; i < m; i++ { - signers := msgs.Get(i).Message().Get(nestedField).List() - n := signers.Len() - for j := 0; j < n; j++ { - arr = append(arr, signers.Get(j).String()) - } - } - return arr - } - } else { - fieldGetters[i] = func(msg proto.Message, arr []string) []string { - msgs := msg.ProtoReflect().Get(field).List() - m := msgs.Len() - for i := 0; i < m; i++ { - arr = append(arr, msgs.Get(i).Message().Get(nestedField).String()) - } - return arr - } - } - } else { - if nestedIsList { - fieldGetters[i] = func(msg proto.Message, arr []string) []string { - nestedMsg := msg.ProtoReflect().Get(field).Message() - signers := nestedMsg.Get(nestedField).List() - n := signers.Len() - for j := 0; j < n; j++ { - arr = append(arr, signers.Get(j).String()) - } - return arr - } - } else { - fieldGetters[i] = func(msg proto.Message, arr []string) []string { - return append(arr, msg.ProtoReflect().Get(field).Message().Get(nestedField).String()) - } - } - } - - default: - return nil, fmt.Errorf("unexpected field type %s for field %s in message %s", field.Kind(), fieldName, descriptor.FullName()) - } - } - - return func(message proto.Message) []string { - var signers []string - for _, getter := range fieldGetters { - signers = getter(message, signers) - } - return signers - }, nil -} - -// GetSigners returns the signers for a given message. -func (c *GetSignersContext) GetSigners(msg proto.Message) ([]string, error) { - messageDescriptor := msg.ProtoReflect().Descriptor() - f, ok := c.getSignersFuncs[messageDescriptor.FullName()] - if !ok { - var err error - f, err = c.makeGetSignersFunc(messageDescriptor) - if err != nil { - return nil, err - } - c.getSignersFuncs[messageDescriptor.FullName()] = f - } - - return f(msg), nil -} diff --git a/x/tx/signing/get_signers_test.go b/x/tx/signing/get_signers_test.go deleted file mode 100644 index f52fe54542aa..000000000000 --- a/x/tx/signing/get_signers_test.go +++ /dev/null @@ -1,113 +0,0 @@ -package signing - -import ( - "testing" - - bankv1beta1 "cosmossdk.io/api/cosmos/bank/v1beta1" - groupv1 "cosmossdk.io/api/cosmos/group/v1" - "github.com/stretchr/testify/require" - "google.golang.org/protobuf/proto" - - "cosmossdk.io/x/tx/internal/testpb" -) - -func TestGetSigners(t *testing.T) { - ctx, err := NewGetSignersContext(GetSignersOptions{}) - require.NoError(t, err) - tests := []struct { - name string - msg proto.Message - want []string - wantErr bool - }{ - { - name: "MsgSend", - msg: &bankv1beta1.MsgSend{ - FromAddress: "foo", - }, - want: []string{"foo"}, - }, - { - name: "MsgMultiSend", - msg: &bankv1beta1.MsgMultiSend{ - Inputs: []*bankv1beta1.Input{ - {Address: "foo"}, - {Address: "bar"}, - }, - }, - want: []string{"foo", "bar"}, - }, - { - name: "MsgSubmitProposal", - msg: &groupv1.MsgSubmitProposal{ - Proposers: []string{"foo", "bar"}, - }, - want: []string{"foo", "bar"}, - }, - { - name: "simple", - msg: &testpb.SimpleSigner{Signer: "foo"}, - want: []string{"foo"}, - }, - { - name: "repeated", - msg: &testpb.RepeatedSigner{Signer: []string{"foo", "bar"}}, - want: []string{"foo", "bar"}, - }, - { - name: "nested", - msg: &testpb.NestedSigner{Inner: &testpb.NestedSigner_Inner{Signer: "foo"}}, - want: []string{"foo"}, - }, - { - name: "nested repeated", - msg: &testpb.NestedRepeatedSigner{Inner: &testpb.NestedRepeatedSigner_Inner{Signer: []string{"foo", "bar"}}}, - want: []string{"foo", "bar"}, - }, - { - name: "repeated nested", - msg: &testpb.RepeatedNestedSigner{Inner: []*testpb.RepeatedNestedSigner_Inner{ - {Signer: "foo"}, - {Signer: "bar"}, - }}, - want: []string{"foo", "bar"}, - }, - { - name: "nested repeated", - msg: &testpb.NestedRepeatedSigner{Inner: &testpb.NestedRepeatedSigner_Inner{ - Signer: []string{"foo", "bar"}, - }}, - want: []string{"foo", "bar"}, - }, - { - name: "repeated nested repeated", - msg: &testpb.RepeatedNestedRepeatedSigner{Inner: []*testpb.RepeatedNestedRepeatedSigner_Inner{ - {Signer: []string{"foo", "bar"}}, - {Signer: []string{"baz", "bam"}}, - {Signer: []string{"blah"}}, - }}, - want: []string{"foo", "bar", "baz", "bam", "blah"}, - }, - { - name: "bad", - msg: &testpb.BadSigner{}, - wantErr: true, - }, - { - name: "no signer", - msg: &testpb.NoSignerOption{}, - wantErr: true, - }, - } - for _, test := range tests { - t.Run(test.name, func(t *testing.T) { - signers, err := ctx.GetSigners(test.msg) - if test.wantErr { - require.Error(t, err) - } else { - require.NoError(t, err) - } - require.Equal(t, test.want, signers) - }) - } -} diff --git a/x/tx/signing/signer_data.go b/x/tx/signing/signer_data.go index a4ac86eb7d5c..3b252be630bb 100644 --- a/x/tx/signing/signer_data.go +++ b/x/tx/signing/signer_data.go @@ -10,8 +10,8 @@ type SignerData struct { // In case of multisigs, this should be the multisig's address. Address string - // ChainId is the chain that this transaction is targeted - ChainId string + // ChainID is the chain that this transaction is targeting. + ChainID string // AccountNumber is the account number of the signer. // diff --git a/x/tx/signing/std/handler_map.go b/x/tx/signing/std/handler_map.go index db889be2de0f..e7f70b541a3c 100644 --- a/x/tx/signing/std/handler_map.go +++ b/x/tx/signing/std/handler_map.go @@ -2,7 +2,9 @@ package std import ( "cosmossdk.io/x/tx/signing" + "cosmossdk.io/x/tx/signing/aminojson" "cosmossdk.io/x/tx/signing/direct" + "cosmossdk.io/x/tx/signing/directaux" "cosmossdk.io/x/tx/signing/textual" ) @@ -10,6 +12,10 @@ import ( type SignModeOptions struct { // Textual are options for SIGN_MODE_TEXTUAL Textual textual.SignModeOptions + // DirectAux are options for SIGN_MODE_DIRECT_AUX + DirectAux directaux.SignModeHandlerOptions + // AminoJSON are options for SIGN_MODE_LEGACY_AMINO_JSON + AminoJSON aminojson.SignModeHandlerOptions } // HandlerMap returns a sign mode handler map that Cosmos SDK apps can use out @@ -20,8 +26,17 @@ func (s SignModeOptions) HandlerMap() (*signing.HandlerMap, error) { return nil, err } + directAux, err := directaux.NewSignModeHandler(s.DirectAux) + if err != nil { + return nil, err + } + + aminoJSON := aminojson.NewSignModeHandler(s.AminoJSON) + return signing.NewHandlerMap( direct.SignModeHandler{}, txt, + directAux, + aminoJSON, ), nil } diff --git a/x/tx/signing/testutil/util.go b/x/tx/signing/testutil/util.go new file mode 100644 index 000000000000..ef689ec1e747 --- /dev/null +++ b/x/tx/signing/testutil/util.go @@ -0,0 +1,90 @@ +package testutil + +import ( + "github.com/cosmos/cosmos-proto/anyutil" + "google.golang.org/protobuf/proto" + "google.golang.org/protobuf/types/known/anypb" + + "cosmossdk.io/api/cosmos/crypto/secp256k1" + signingv1beta1 "cosmossdk.io/api/cosmos/tx/signing/v1beta1" + txv1beta1 "cosmossdk.io/api/cosmos/tx/v1beta1" + "cosmossdk.io/x/tx/signing" +) + +type HandlerArgumentOptions struct { + ChainID string + Memo string + Msg proto.Message + AccNum uint64 + AccSeq uint64 + Tip *txv1beta1.Tip + Fee *txv1beta1.Fee + SignerAddress string +} + +func MakeHandlerArguments(options HandlerArgumentOptions) (signing.SignerData, signing.TxData, error) { + pk := &secp256k1.PubKey{ + Key: make([]byte, 256), + } + anyPk, err := anyutil.New(pk) + if err != nil { + return signing.SignerData{}, signing.TxData{}, err + } + + signerInfo := []*txv1beta1.SignerInfo{ + { + PublicKey: anyPk, + ModeInfo: &txv1beta1.ModeInfo{ + Sum: &txv1beta1.ModeInfo_Single_{ + Single: &txv1beta1.ModeInfo_Single{ + Mode: signingv1beta1.SignMode_SIGN_MODE_DIRECT_AUX, + }, + }, + }, + Sequence: options.AccSeq, + }, + } + + anyMsg, err := anyutil.New(options.Msg) + if err != nil { + return signing.SignerData{}, signing.TxData{}, err + } + + txBody := &txv1beta1.TxBody{ + Messages: []*anypb.Any{anyMsg}, + Memo: options.Memo, + } + + authInfo := &txv1beta1.AuthInfo{ + Fee: options.Fee, + Tip: options.Tip, + SignerInfos: signerInfo, + } + + bodyBz, err := proto.Marshal(txBody) + if err != nil { + return signing.SignerData{}, signing.TxData{}, err + } + authInfoBz, err := proto.Marshal(authInfo) + if err != nil { + return signing.SignerData{}, signing.TxData{}, err + } + + txData := signing.TxData{ + Body: txBody, + AuthInfo: authInfo, + AuthInfoBytes: authInfoBz, + BodyBytes: bodyBz, + } + + signerAddress := options.SignerAddress + signerData := signing.SignerData{ + ChainID: options.ChainID, + AccountNumber: options.AccNum, + Sequence: options.AccSeq, + Address: signerAddress, + PubKey: anyPk, + } + + return signerData, txData, nil +} diff --git a/x/tx/signing/textual/any.go b/x/tx/signing/textual/any.go index 516496f9fce9..cfb80188c4c2 100644 --- a/x/tx/signing/textual/any.go +++ b/x/tx/signing/textual/any.go @@ -49,10 +49,15 @@ func (ar anyValueRenderer) Format(ctx context.Context, v protoreflect.Value) ([] return nil, err } - // The Any value renderer suppresses emission of the object header + // The Any value renderer suppresses emission of the object header for all + // messages that go through the messageValueRenderer. omitHeader := 0 _, isMsgRenderer := vr.(*messageValueRenderer) - if isMsgRenderer && subscreens[0].Content == fmt.Sprintf("%s object", internalMsg.ProtoReflect().Descriptor().Name()) { + if isMsgRenderer { + if subscreens[0].Content != fmt.Sprintf("%s object", internalMsg.ProtoReflect().Descriptor().Name()) { + return nil, fmt.Errorf("any internal message expects %s, got %s", fmt.Sprintf("%s object", internalMsg.ProtoReflect().Descriptor().Name()), subscreens[0].Content) + } + omitHeader = 1 } @@ -108,7 +113,7 @@ func (ar anyValueRenderer) Parse(ctx context.Context, screens []Screen) (protore } // Prepend with a "%s object" if the message goes through the default - // messageValueRenderer. + // messageValueRenderer, and add a level of indentation. _, isMsgRenderer := vr.(*messageValueRenderer) if isMsgRenderer { for i := range subscreens { diff --git a/x/tx/signing/textual/any_test.go b/x/tx/signing/textual/any_test.go index b15d63355ecd..da64acf0df79 100644 --- a/x/tx/signing/textual/any_test.go +++ b/x/tx/signing/textual/any_test.go @@ -26,7 +26,7 @@ import ( "cosmossdk.io/x/tx/signing/textual" ) -type anyJsonTest struct { +type anyJSONTest struct { Proto json.RawMessage Screens []textual.Screen } @@ -35,7 +35,7 @@ func TestAny(t *testing.T) { raw, err := os.ReadFile("./internal/testdata/any.json") require.NoError(t, err) - var testcases []anyJsonTest + var testcases []anyJSONTest err = json.Unmarshal(raw, &testcases) require.NoError(t, err) @@ -59,7 +59,7 @@ func TestAny(t *testing.T) { parsedMsg := val.Message().Interface() require.IsType(t, &anypb.Any{}, parsedMsg) parsedAny := parsedMsg.(*anypb.Any) - diff := cmp.Diff(anyMsg, parsedAny, protocmp.Transform()) + diff := cmp.Diff(&anyMsg, parsedAny, protocmp.Transform()) require.Empty(t, diff) }) } diff --git a/x/tx/signing/textual/bench_test.go b/x/tx/signing/textual/bench_test.go index 0e2c4b70123a..d113b39bd302 100644 --- a/x/tx/signing/textual/bench_test.go +++ b/x/tx/signing/textual/bench_test.go @@ -1,11 +1,17 @@ -package textual +package textual_test import ( "bytes" "context" + "encoding/json" + "os" "testing" + "github.com/stretchr/testify/require" "google.golang.org/protobuf/reflect/protoreflect" + + "cosmossdk.io/x/tx/internal/testpb" + "cosmossdk.io/x/tx/signing/textual" ) var intValues = []protoreflect.Value{ @@ -22,7 +28,7 @@ var intValues = []protoreflect.Value{ func BenchmarkIntValueRendererFormat(b *testing.B) { ctx := context.Background() - ivr := new(intValueRenderer) + ivr := textual.NewIntValueRenderer(fieldDescriptorFromName("UINT64")) b.ResetTimer() b.ReportAllocs() @@ -49,7 +55,7 @@ var decimalValues = []protoreflect.Value{ func BenchmarkDecimalValueRendererFormat(b *testing.B) { ctx := context.Background() - dvr := new(decValueRenderer) + dvr := textual.NewDecValueRenderer() b.ResetTimer() b.ReportAllocs() @@ -76,7 +82,7 @@ var byteValues = []protoreflect.Value{ func BenchmarkBytesValueRendererFormat(b *testing.B) { ctx := context.Background() - bvr := new(bytesValueRenderer) + bvr := textual.NewBytesValueRenderer() b.ResetTimer() b.ReportAllocs() @@ -88,3 +94,52 @@ func BenchmarkBytesValueRendererFormat(b *testing.B) { } } } + +var sink any + +func BenchmarkMessageValueRenderer_parseRepeated(b *testing.B) { + ctx := context.Background() + raw, err := os.ReadFile("./internal/testdata/repeated.json") + require.NoError(b, err) + + type rendScreens struct { + rend textual.ValueRenderer + screens []textual.Screen + } + + var rsL []*rendScreens + + var testCases []repeatedJSONTest + err = json.Unmarshal(raw, &testCases) + require.NoError(b, err) + + tr, err := textual.NewSignModeHandler(textual.SignModeOptions{CoinMetadataQuerier: mockCoinMetadataQuerier}) + for _, tc := range testCases { + rend := textual.NewMessageValueRenderer(tr, (&testpb.Qux{}).ProtoReflect().Descriptor()) + require.NoError(b, err) + + screens, err := rend.Format(ctx, protoreflect.ValueOf(tc.Proto.ProtoReflect())) + require.NoError(b, err) + require.Equal(b, tc.Screens, screens) + + rsL = append(rsL, &rendScreens{ + rend: rend, + screens: screens, + }) + } + + b.ReportAllocs() + b.ResetTimer() + + for i := 0; i < b.N; i++ { + for _, rs := range rsL { + sink, _ = rs.rend.Parse(ctx, rs.screens) + } + } + + if sink == nil { + b.Fatal("Benchmark did not run!") + } + // Reset the sink for reuse. + sink = nil +} diff --git a/x/tx/signing/textual/bool.go b/x/tx/signing/textual/bool.go new file mode 100644 index 000000000000..2347ef1dd457 --- /dev/null +++ b/x/tx/signing/textual/bool.go @@ -0,0 +1,37 @@ +package textual + +import ( + "context" + "fmt" + + "google.golang.org/protobuf/reflect/protoreflect" +) + +type boolValueRenderer struct{} + +// NewBoolValueRenderer returns a ValueRenderer for protocol buffer bool values. +// It renders the boolean as YES or NO. +func NewBoolValueRenderer() ValueRenderer { + return boolValueRenderer{} +} + +func (sr boolValueRenderer) Format(_ context.Context, v protoreflect.Value) ([]Screen, error) { + str := "False" + if v.Bool() { + str = "True" + } + return []Screen{{Content: str}}, nil +} + +func (sr boolValueRenderer) Parse(_ context.Context, screens []Screen) (protoreflect.Value, error) { + if len(screens) != 1 { + return protoreflect.Value{}, fmt.Errorf("expected single screen: %v", screens) + } + + res := false + if screens[0].Content == "True" { + res = true + } + + return protoreflect.ValueOfBool(res), nil +} diff --git a/x/tx/signing/textual/bool_test.go b/x/tx/signing/textual/bool_test.go new file mode 100644 index 000000000000..07722375d6b4 --- /dev/null +++ b/x/tx/signing/textual/bool_test.go @@ -0,0 +1,31 @@ +package textual_test + +import ( + "context" + "testing" + + "cosmossdk.io/x/tx/signing/textual" + "github.com/stretchr/testify/require" + "google.golang.org/protobuf/reflect/protoreflect" +) + +func TestBool(t *testing.T) { + // test true + rend := textual.NewBoolValueRenderer() + screens, err := rend.Format(context.Background(), protoreflect.ValueOfBool(true)) + require.NoError(t, err) + require.Equal(t, 1, len(screens)) + require.Equal(t, "True", screens[0].Content) + val, err := rend.Parse(context.Background(), screens) + require.NoError(t, err) + require.Equal(t, true, val.Bool()) + + // test false + screens, err = rend.Format(context.Background(), protoreflect.ValueOfBool(false)) + require.NoError(t, err) + require.Equal(t, 1, len(screens)) + require.Equal(t, "False", screens[0].Content) + val, err = rend.Parse(context.Background(), screens) + require.NoError(t, err) + require.Equal(t, false, val.Bool()) +} diff --git a/x/tx/signing/textual/bytes_test.go b/x/tx/signing/textual/bytes_test.go index 1f9fae13a8b3..02fea06cf3d0 100644 --- a/x/tx/signing/textual/bytes_test.go +++ b/x/tx/signing/textual/bytes_test.go @@ -12,7 +12,7 @@ import ( "cosmossdk.io/x/tx/signing/textual" ) -func TestBytesJsonTestCases(t *testing.T) { +func TestBytesJSONTestCases(t *testing.T) { var testcases []bytesTest // Bytes.json contains bytes that are represented in base64 format, and // their expected results in hex. diff --git a/x/tx/signing/textual/coin_test.go b/x/tx/signing/textual/coin_test.go index 492e5d2705c8..a9ed0295b459 100644 --- a/x/tx/signing/textual/coin_test.go +++ b/x/tx/signing/textual/coin_test.go @@ -71,8 +71,8 @@ func TestMetadataQuerier(t *testing.T) { require.ErrorIs(t, err, expErr) } -func TestCoinJsonTestcases(t *testing.T) { - var testcases []coinJsonTest +func TestCoinJSONTestcases(t *testing.T) { + var testcases []coinJSONTest raw, err := os.ReadFile("./internal/testdata/coin.json") require.NoError(t, err) err = json.Unmarshal(raw, &testcases) @@ -121,7 +121,7 @@ func TestCoinJsonTestcases(t *testing.T) { // an error, otherwise match Text, then Parse() the text and expect it to // match (via proto.Equals()) the original Proto. If the test case has no // Proto, try to Parse() the Text and expect an error if Error is set. -type coinJsonTest struct { +type coinJSONTest struct { Proto *basev1beta1.Coin Metadata *bankv1beta1.Metadata Error bool diff --git a/x/tx/signing/textual/coins.go b/x/tx/signing/textual/coins.go index addd95ca8bf2..769a2f76c578 100644 --- a/x/tx/signing/textual/coins.go +++ b/x/tx/signing/textual/coins.go @@ -63,7 +63,6 @@ func (vr coinsValueRenderer) FormatRepeated(ctx context.Context, v protoreflect. protoCoins := v.List() coins, metadatas := make([]*basev1beta1.Coin, protoCoins.Len()), make([]*bankv1beta1.Metadata, protoCoins.Len()) - var err error for i := 0; i < protoCoins.Len(); i++ { coin := &basev1beta1.Coin{} err := coerceToMessage(protoCoins.Get(i).Interface().(protoreflect.Message).Interface(), coin) diff --git a/x/tx/signing/textual/coins_test.go b/x/tx/signing/textual/coins_test.go index 55ff78482cba..e7bd921e10da 100644 --- a/x/tx/signing/textual/coins_test.go +++ b/x/tx/signing/textual/coins_test.go @@ -15,8 +15,8 @@ import ( "cosmossdk.io/x/tx/signing/textual" ) -func TestCoinsJsonTestcases(t *testing.T) { - var testcases []coinsJsonTest +func TestCoinsJSONTestcases(t *testing.T) { + var testcases []coinsJSONTest raw, err := os.ReadFile("./internal/testdata/coins.json") require.NoError(t, err) err = json.Unmarshal(raw, &testcases) @@ -93,12 +93,12 @@ func checkCoinEqual(t *testing.T, coin, coin1 *basev1beta1.Coin) { require.True(t, v.Equal(v1)) } -// coinsJsonTest is the type of test cases in the testdata file. +// coinsJSONTest is the type of test cases in the testdata file. // If the test case has a Proto, try to Format() it. If Error is set, expect // an error, otherwise match Text, then Parse() the text and expect it to // match (via proto.Equals()) the original Proto. If the test case has no // Proto, try to Parse() the Text and expect an error if Error is set. -type coinsJsonTest struct { +type coinsJSONTest struct { Proto []*basev1beta1.Coin Metadata map[string]*bankv1beta1.Metadata Text string diff --git a/x/tx/signing/textual/dec_test.go b/x/tx/signing/textual/dec_test.go index 1ee1615a7b21..defb6d9cc509 100644 --- a/x/tx/signing/textual/dec_test.go +++ b/x/tx/signing/textual/dec_test.go @@ -15,7 +15,7 @@ import ( "cosmossdk.io/x/tx/signing/textual" ) -func TestDecJsonTestcases(t *testing.T) { +func TestDecJSONTestcases(t *testing.T) { type decimalTest []string var testcases []decimalTest raw, err := os.ReadFile("./internal/testdata/decimals.json") diff --git a/x/tx/signing/textual/duration.go b/x/tx/signing/textual/duration.go index 7afe077571de..f45ae95d9bbb 100644 --- a/x/tx/signing/textual/duration.go +++ b/x/tx/signing/textual/duration.go @@ -7,6 +7,7 @@ import ( "strconv" "strings" + "google.golang.org/protobuf/proto" "google.golang.org/protobuf/reflect/protoreflect" dpb "google.golang.org/protobuf/types/known/durationpb" ) @@ -23,9 +24,9 @@ func NewDurationValueRenderer() ValueRenderer { } const ( - min_sec = 60 - hour_sec = 60 * min_sec - day_sec = 24 * hour_sec + minSec = 60 + hourSec = 60 * minSec + daySec = 24 * hourSec ) type factors struct { @@ -34,12 +35,12 @@ type factors struct { func factorSeconds(x int64) factors { var f factors - f.days = x / day_sec - x -= f.days * day_sec - f.hours = x / hour_sec - x -= f.hours * hour_sec - f.minutes = x / min_sec - x -= f.minutes * min_sec + f.days = x / daySec + x -= f.days * daySec + f.hours = x / hourSec + x -= f.hours * hourSec + f.minutes = x / minSec + x -= f.minutes * minSec f.seconds = x return f } @@ -84,8 +85,7 @@ func (dr durationValueRenderer) Format(_ context.Context, v protoreflect.Value) if duration.Seconds < 0 || duration.Nanos < 0 { negative = true // copy to avoid side-effecting our input - d := *duration - duration = &d + duration = proto.Clone(duration).(*dpb.Duration) duration.Seconds *= -1 duration.Nanos *= -1 } @@ -172,7 +172,7 @@ func (dr durationValueRenderer) Parse(_ context.Context, screens []Screen) (prot } dur := &dpb.Duration{} - dur.Seconds = days*day_sec + hours*hour_sec + minutes*min_sec + seconds + dur.Seconds = days*daySec + hours*hourSec + minutes*minSec + seconds // #nosec G701 // Since there are 9 digits or fewer, this conversion is safe. dur.Nanos = int32(nanos) diff --git a/x/tx/signing/textual/duration_test.go b/x/tx/signing/textual/duration_test.go index 63b9463a562c..baf015e5e300 100644 --- a/x/tx/signing/textual/duration_test.go +++ b/x/tx/signing/textual/duration_test.go @@ -10,7 +10,6 @@ import ( "cosmossdk.io/x/tx/signing/textual" "github.com/stretchr/testify/require" - "google.golang.org/protobuf/proto" "google.golang.org/protobuf/reflect/protoreflect" dpb "google.golang.org/protobuf/types/known/durationpb" ) @@ -54,7 +53,7 @@ func TestDurationJSON(t *testing.T) { msg := val.Message().Interface() require.IsType(t, &dpb.Duration{}, msg) duration := msg.(*dpb.Duration) - require.True(t, proto.Equal(duration, tc.Proto), "%v vs %v", duration, tc.Proto) + require.Equal(t, duration.AsDuration(), tc.Proto.AsDuration(), "%v vs %v", duration, tc.Proto) }) } } diff --git a/x/tx/signing/textual/e2e_test.go b/x/tx/signing/textual/e2e_test.go index e2260b21dbf9..d6e8e26b4d24 100644 --- a/x/tx/signing/textual/e2e_test.go +++ b/x/tx/signing/textual/e2e_test.go @@ -22,16 +22,16 @@ import ( "cosmossdk.io/x/tx/signing/textual/internal/textualpb" ) -type e2eJsonTest struct { - txJsonTest +type e2eJSONTest struct { + txJSONTest Cbor string } -func TestE2EJsonTestcases(t *testing.T) { +func TestE2EJSONTestcases(t *testing.T) { raw, err := os.ReadFile("./internal/testdata/e2e.json") require.NoError(t, err) - var testcases []e2eJsonTest + var testcases []e2eJSONTest err = json.Unmarshal(raw, &testcases) require.NoError(t, err) @@ -49,7 +49,7 @@ func TestE2EJsonTestcases(t *testing.T) { AuthInfoBytes: authInfoBz, SignerData: &textualpb.SignerData{ Address: signerData.Address, - ChainId: signerData.ChainId, + ChainId: signerData.ChainID, AccountNumber: signerData.AccountNumber, Sequence: signerData.Sequence, PubKey: signerData.PubKey, diff --git a/x/tx/signing/textual/encode_test.go b/x/tx/signing/textual/encode_test.go index fbfa0163791c..4221e2308416 100644 --- a/x/tx/signing/textual/encode_test.go +++ b/x/tx/signing/textual/encode_test.go @@ -11,7 +11,7 @@ import ( "github.com/stretchr/testify/require" ) -type encodingJsonTest struct { +type encodingJSONTest struct { Screens []Screen Encoding string } @@ -20,7 +20,7 @@ func TestEncodingJson(t *testing.T) { raw, err := os.ReadFile("./internal/testdata/encode.json") require.NoError(t, err) - var testcases []encodingJsonTest + var testcases []encodingJSONTest err = json.Unmarshal(raw, &testcases) require.NoError(t, err) diff --git a/x/tx/signing/textual/enum_test.go b/x/tx/signing/textual/enum_test.go index 21daf7541a2d..a1ae24854d0a 100644 --- a/x/tx/signing/textual/enum_test.go +++ b/x/tx/signing/textual/enum_test.go @@ -22,7 +22,7 @@ type enumTest struct { Text string } -func TestEnumJsonTestcases(t *testing.T) { +func TestEnumJSONTestcases(t *testing.T) { var testcases []enumTest raw, err := os.ReadFile("./internal/testdata/enum.json") require.NoError(t, err) @@ -61,11 +61,16 @@ func TestEnumJsonTestcases(t *testing.T) { // treats empty and default values as the same, we actually parse the protojson // encoded string to retrieve which field is set. func getFd(proto json.RawMessage, m *testpb.Baz) protoreflect.FieldDescriptor { - if strings.Contains(string(proto), `"ee"`) { - return m.ProtoReflect().Descriptor().Fields().ByNumber(1) - } else if strings.Contains(string(proto), `"ie"`) { - return m.ProtoReflect().Descriptor().Fields().ByNumber(2) - } else { - return m.ProtoReflect().Descriptor().Fields().ByNumber(3) + var fnum protoreflect.FieldNumber + + switch { + case strings.Contains(string(proto), `"ee"`): + fnum = 1 + case strings.Contains(string(proto), `"ie"`): + fnum = 2 + default: + fnum = 3 } + + return m.ProtoReflect().Descriptor().Fields().ByNumber(fnum) } diff --git a/x/tx/signing/textual/fuzz_test.go b/x/tx/signing/textual/fuzz_test.go new file mode 100644 index 000000000000..81e2fbb867b4 --- /dev/null +++ b/x/tx/signing/textual/fuzz_test.go @@ -0,0 +1,103 @@ +package textual_test + +import ( + "context" + "encoding/json" + "os" + "testing" + + "google.golang.org/protobuf/reflect/protoreflect" + tspb "google.golang.org/protobuf/types/known/timestamppb" + + "cosmossdk.io/x/tx/signing/textual" +) + +func FuzzIntValueRendererParse(f *testing.F) { + if testing.Short() { + f.Skip() + } + + // 1. Firstly add some seeds + f.Add("10.11") + f.Add("-10.11") + f.Add("0.999999") + f.Add(".999999") + f.Add("1'000.999999") + f.Add("1'000'111") + f.Add("340'282'366'920'938'463'463'374'607'431'768'211'455") + + // 2. Next setup and run the fuzzer. + ivr := textual.NewIntValueRenderer(fieldDescriptorFromName("UINT64")) + ctx := context.Background() + f.Fuzz(func(t *testing.T, input string) { + _, _ = ivr.Parse(ctx, []textual.Screen{{Content: input}}) + }) +} + +func FuzzTimestampValueRendererParse(f *testing.F) { + if testing.Short() { + f.Skip() + } + + // 1. Firstly add some seed valid content. + f.Add("2006-01-02T15:04:05Z") + f.Add("1970-01-01T00:00:00.00000001Z") + f.Add("2022-07-14T11:22:20.983Z") + f.Add("1969-12-31T23:59:59Z") + + // 2. Now fuzz it. + tvr := textual.NewTimestampValueRenderer() + ctx := context.Background() + f.Fuzz(func(t *testing.T, input string) { + _, _ = tvr.Parse(ctx, []textual.Screen{{Content: input}}) + }) +} + +func FuzzTimestampJSONParseToParseRoundTrip(f *testing.F) { + // 1. Use the seeds from testdata and mutate them. + seed, err := os.ReadFile("./internal/testdata/timestamp.json") + if err != nil { + f.Fatal(err) + } + f.Add(seed) + + f.Fuzz(func(t *testing.T, input []byte) { + var testCases []timestampJSONTest + if err := json.Unmarshal(input, &testCases); err != nil { + return + } + + for _, tc := range testCases { + rend := textual.NewTimestampValueRenderer() + + // If it successfully JSON unmarshals let's test it out. + var screens []textual.Screen + var err error + + if tc.Proto != nil { + screens, err = rend.Format(context.Background(), protoreflect.ValueOf(tc.Proto.ProtoReflect())) + if err != nil { + continue + } + } + + val, err := rend.Parse(context.Background(), screens) + if err != nil { + continue + } + + msg := val.Message().Interface() + gotTs, ok := msg.(*tspb.Timestamp) + if !ok { + t.Fatalf("Wrong type for timestamp: %T", msg) + } + // Please avoid using proto.Equal to compare timestamps given they aren't + // in standardized form and will produce false positives for example given input: + // []byte(`[{"proto":{"nanos":1000000000}}]`) + // Per issue: https://github.com/cosmos/cosmos-sdk/issues/15761 + if !gotTs.AsTime().Equal(tc.Proto.AsTime()) { + t.Fatalf("Roundtrip mismatch\n\tGot: %#v\n\tWant: %#v", gotTs, tc.Proto) + } + } + }) +} diff --git a/x/tx/signing/textual/handler.go b/x/tx/signing/textual/handler.go index 45682e2c6d2d..c688398c8630 100644 --- a/x/tx/signing/textual/handler.go +++ b/x/tx/signing/textual/handler.go @@ -138,13 +138,15 @@ func (r *SignModeHandler) GetFieldValueRenderer(fd protoreflect.FieldDescriptor) return nil, fmt.Errorf("value renderers cannot format value of type map") } return NewMessageValueRenderer(r, md), nil + case fd.Kind() == protoreflect.BoolKind: + return NewBoolValueRenderer(), nil default: return nil, fmt.Errorf("value renderers cannot format value of type %s", fd.Kind()) } } -// GetMessageValueRenderer is a specialization of GetValueRenderer for messages. +// GetMessageValueRenderer returns a value renderer for a message. // It is useful when the message type is discovered outside the context of a field, // e.g. when handling a google.protobuf.Any. func (r *SignModeHandler) GetMessageValueRenderer(md protoreflect.MessageDescriptor) (ValueRenderer, error) { @@ -163,7 +165,7 @@ func (r *SignModeHandler) GetMessageValueRenderer(md protoreflect.MessageDescrip func (r *SignModeHandler) init() { if r.scalars == nil { r.scalars = map[string]ValueRendererCreator{} - r.scalars["cosmos.Int"] = func(fd protoreflect.FieldDescriptor) ValueRenderer { return NewIntValueRenderer(fd) } + r.scalars["cosmos.Int"] = NewIntValueRenderer r.scalars["cosmos.Dec"] = func(_ protoreflect.FieldDescriptor) ValueRenderer { return NewDecValueRenderer() } } if r.messages == nil { @@ -195,7 +197,7 @@ func (r *SignModeHandler) GetSignBytes(ctx context.Context, signerData signing.S AuthInfoBytes: txData.AuthInfoBytes, SignerData: &textualpb.SignerData{ Address: signerData.Address, - ChainId: signerData.ChainId, + ChainId: signerData.ChainID, AccountNumber: signerData.AccountNumber, Sequence: signerData.Sequence, PubKey: signerData.PubKey, diff --git a/x/tx/signing/textual/int.go b/x/tx/signing/textual/int.go index c04a85d05d5d..24357be8e5d2 100644 --- a/x/tx/signing/textual/int.go +++ b/x/tx/signing/textual/int.go @@ -2,6 +2,7 @@ package textual import ( "context" + "errors" "fmt" "strconv" "strings" @@ -46,7 +47,7 @@ func (vr intValueRenderer) Parse(_ context.Context, screens []Screen) (protorefl if err != nil { return nilValue, err } - return protoreflect.ValueOfUint32(uint32(value)), nil //nolint:gosec + return protoreflect.ValueOfUint32(uint32(value)), nil case protoreflect.Uint64Kind: value, err := strconv.ParseUint(parsedInt, 10, 64) @@ -60,7 +61,7 @@ func (vr intValueRenderer) Parse(_ context.Context, screens []Screen) (protorefl if err != nil { return nilValue, err } - return protoreflect.ValueOfInt32(int32(value)), nil //nolint:gosec + return protoreflect.ValueOfInt32(int32(value)), nil case protoreflect.Int64Kind: value, err := strconv.ParseInt(parsedInt, 10, 64) @@ -79,6 +80,10 @@ func (vr intValueRenderer) Parse(_ context.Context, screens []Screen) (protorefl // parseInt parses a value-rendered string into an integer func parseInt(v string) (string, error) { + if len(v) == 0 { + return "", errors.New("expecting a non-empty string") + } + sign := "" if v[0] == '-' { sign = "-" diff --git a/x/tx/signing/textual/int_test.go b/x/tx/signing/textual/int_test.go index 33dbdb4fecb1..a5e265e3f3dd 100644 --- a/x/tx/signing/textual/int_test.go +++ b/x/tx/signing/textual/int_test.go @@ -15,7 +15,7 @@ import ( "cosmossdk.io/x/tx/signing/textual" ) -func TestIntJsonTestcases(t *testing.T) { +func TestIntJSONTestcases(t *testing.T) { type integerTest []string var testcases []integerTest raw, err := os.ReadFile("./internal/testdata/integers.json") diff --git a/x/tx/signing/textual/internal/cbor/cbor.go b/x/tx/signing/textual/internal/cbor/cbor.go index 78bd2c03bb86..ca81fcbe78d2 100644 --- a/x/tx/signing/textual/internal/cbor/cbor.go +++ b/x/tx/signing/textual/internal/cbor/cbor.go @@ -22,7 +22,7 @@ const ( majorSimple byte = 7 ) -func encodeFirstByte(major byte, extra byte) byte { +func encodeFirstByte(major, extra byte) byte { return (major << 5) | extra&0x1F } diff --git a/x/tx/signing/textual/internal/testdata/coin.json b/x/tx/signing/textual/internal/testdata/coin.json index 29e6cf01c9a4..1a1ac79b9306 100644 --- a/x/tx/signing/textual/internal/testdata/coin.json +++ b/x/tx/signing/textual/internal/testdata/coin.json @@ -1,4 +1,8 @@ [ + { + "proto": null, + "text": "zero" + }, { "proto": {"amount": "0", "denom": "ucosm"}, "metadata": {"display": "COSM", "base":"ucosm", "denom_units": [{"denom": "COSM", "exponent": 6}, {"denom": "ucosm", "exponent": 0}]}, diff --git a/x/tx/signing/textual/message.go b/x/tx/signing/textual/message.go index 9affadba8602..83668cd7a298 100644 --- a/x/tx/signing/textual/message.go +++ b/x/tx/signing/textual/message.go @@ -261,11 +261,11 @@ func (mr *messageValueRenderer) Parse(ctx context.Context, screens []Screen) (pr return protoreflect.ValueOfMessage(msg), nil } +// +var headerRegex = regexp.MustCompile(`(\d+) .+`) + func (mr *messageValueRenderer) parseRepeated(ctx context.Context, screens []Screen, l protoreflect.List, vr ValueRenderer) error { - // - headerRegex := *regexp.MustCompile(`(\d+) .+`) res := headerRegex.FindAllStringSubmatch(screens[0].Content, -1) - if res == nil { return errors.New("failed to match ") } diff --git a/x/tx/signing/textual/message_test.go b/x/tx/signing/textual/message_test.go index b4d04b27f977..da6f4f99a190 100644 --- a/x/tx/signing/textual/message_test.go +++ b/x/tx/signing/textual/message_test.go @@ -23,20 +23,22 @@ func EmptyCoinMetadataQuerier(ctx context.Context, denom string) (*bankv1beta1.M return nil, nil } -type messageJsonTest struct { +type messageJSONTest struct { Proto *testpb.Foo Screens []textual.Screen } -func TestMessageJsonTestcases(t *testing.T) { +func TestMessageJSONTestcases(t *testing.T) { raw, err := os.ReadFile("./internal/testdata/message.json") require.NoError(t, err) - var testcases []messageJsonTest + var testcases []messageJSONTest err = json.Unmarshal(raw, &testcases) require.NoError(t, err) tr, err := textual.NewSignModeHandler(textual.SignModeOptions{CoinMetadataQuerier: EmptyCoinMetadataQuerier}) + require.NoError(t, err) + for i, tc := range testcases { t.Run(fmt.Sprintf("%d", i), func(t *testing.T) { rend := textual.NewMessageValueRenderer(tr, (&testpb.Foo{}).ProtoReflect().Descriptor()) diff --git a/x/tx/signing/textual/repeated_test.go b/x/tx/signing/textual/repeated_test.go index b2a6a98318b9..3eece902e465 100644 --- a/x/tx/signing/textual/repeated_test.go +++ b/x/tx/signing/textual/repeated_test.go @@ -16,16 +16,16 @@ import ( "cosmossdk.io/x/tx/signing/textual" ) -type repeatedJsonTest struct { +type repeatedJSONTest struct { Proto *testpb.Qux Screens []textual.Screen } -func TestRepeatedJsonTestcases(t *testing.T) { +func TestRepeatedJSONTestcases(t *testing.T) { raw, err := os.ReadFile("./internal/testdata/repeated.json") require.NoError(t, err) - var testcases []repeatedJsonTest + var testcases []repeatedJSONTest err = json.Unmarshal(raw, &testcases) require.NoError(t, err) diff --git a/x/tx/signing/textual/string_test.go b/x/tx/signing/textual/string_test.go index 142fae5c0d0e..4f215b8d6d11 100644 --- a/x/tx/signing/textual/string_test.go +++ b/x/tx/signing/textual/string_test.go @@ -12,15 +12,15 @@ import ( "google.golang.org/protobuf/reflect/protoreflect" ) -type stringJsonTest struct { +type stringJSONTest struct { Text string } -func TestStringJsonTestcases(t *testing.T) { +func TestStringJSONTestcases(t *testing.T) { raw, err := os.ReadFile("./internal/testdata/string.json") require.NoError(t, err) - var testcases []stringJsonTest + var testcases []stringJSONTest err = json.Unmarshal(raw, &testcases) require.NoError(t, err) diff --git a/x/tx/signing/textual/testdata/fuzz/FuzzIntValueRendererParse/5838cdfae7b16cde b/x/tx/signing/textual/testdata/fuzz/FuzzIntValueRendererParse/5838cdfae7b16cde new file mode 100644 index 000000000000..64c3abaff82f --- /dev/null +++ b/x/tx/signing/textual/testdata/fuzz/FuzzIntValueRendererParse/5838cdfae7b16cde @@ -0,0 +1,2 @@ +go test fuzz v1 +string("") diff --git a/x/tx/signing/textual/testdata/fuzz/FuzzIntValueRendererParse/e521654378d1371f b/x/tx/signing/textual/testdata/fuzz/FuzzIntValueRendererParse/e521654378d1371f new file mode 100644 index 000000000000..9272cbf95401 --- /dev/null +++ b/x/tx/signing/textual/testdata/fuzz/FuzzIntValueRendererParse/e521654378d1371f @@ -0,0 +1,2 @@ +go test fuzz v1 +string("\xb0\x1b\x16d@L0@'") diff --git a/x/tx/signing/textual/testdata/fuzz/FuzzTimestampJSON/7fee543ff80f1279 b/x/tx/signing/textual/testdata/fuzz/FuzzTimestampJSON/7fee543ff80f1279 new file mode 100644 index 000000000000..7a94f035b275 --- /dev/null +++ b/x/tx/signing/textual/testdata/fuzz/FuzzTimestampJSON/7fee543ff80f1279 @@ -0,0 +1,2 @@ +go test fuzz v1 +[]byte("[{\"proto\":{\"nAnos\":1000000000}}]") diff --git a/x/tx/signing/textual/timestamp_test.go b/x/tx/signing/textual/timestamp_test.go index c700188dcc28..d9ca6bbc0862 100644 --- a/x/tx/signing/textual/timestamp_test.go +++ b/x/tx/signing/textual/timestamp_test.go @@ -11,13 +11,12 @@ import ( "cosmossdk.io/x/tx/signing/textual" "github.com/stretchr/testify/require" - "google.golang.org/protobuf/proto" "google.golang.org/protobuf/reflect/protoreflect" dur "google.golang.org/protobuf/types/known/durationpb" tspb "google.golang.org/protobuf/types/known/timestamppb" ) -// timestampJsonTest is the type of test cases in the testdata file. +// timestampJSONTest is the type of test cases in the testdata file. // If the test case has a Proto, try to Format() it. If Error is set, expect // an error, otherwise match Text, then Parse() the text and expect it to // match (via proto.Equals()) the original Proto. If the test case has no @@ -25,18 +24,27 @@ import ( // // The Timestamp proto seconds field is int64, but restricted in range // by convention and will fit within a JSON number. -type timestampJsonTest struct { +type timestampJSONTest struct { Proto *tspb.Timestamp Error bool Text string } -func TestTimestampJsonTestcases(t *testing.T) { +func TestTimestampJSONTestcasesTestData(t *testing.T) { raw, err := os.ReadFile("./internal/testdata/timestamp.json") require.NoError(t, err) + testTimestampJSONTestcases(t, raw) +} + +// Tests to ensure that we compare standardized forms of the final timestamppb.Timestamp. +// Please see issue https://github.com/cosmos/cosmos-sdk/issues/15761 +func TestTimestampJsonTestcasesExtraneousNanos(t *testing.T) { + testTimestampJSONTestcases(t, []byte(`[{"proto":{"nAnos":1000000000},"text":"1970-01-01T00:00:01Z"}]`)) +} - var testcases []timestampJsonTest - err = json.Unmarshal(raw, &testcases) +func testTimestampJSONTestcases(t *testing.T, raw []byte) { + var testcases []timestampJSONTest + err := json.Unmarshal(raw, &testcases) require.NoError(t, err) for i, tc := range testcases { @@ -64,7 +72,11 @@ func TestTimestampJsonTestcases(t *testing.T) { msg := val.Message().Interface() require.IsType(t, &tspb.Timestamp{}, msg) timestamp := msg.(*tspb.Timestamp) - require.True(t, proto.Equal(timestamp, tc.Proto)) + // Please avoid using proto.Equal to compare timestamps given they aren't + // in standardized form and will produce false positives for example given input: + // []byte(`[{"proto":{"nanos":1000000000}}]`) + // Per issue: https://github.com/cosmos/cosmos-sdk/issues/15761 + require.True(t, timestamp.AsTime().Equal(tc.Proto.AsTime())) }) } } diff --git a/x/tx/signing/textual/tx_test.go b/x/tx/signing/textual/tx_test.go index d990366087e3..1b63b8c8c907 100644 --- a/x/tx/signing/textual/tx_test.go +++ b/x/tx/signing/textual/tx_test.go @@ -26,29 +26,29 @@ import ( "cosmossdk.io/x/tx/signing/textual/internal/textualpb" ) -// txJsonTestTx represents the type that in the JSON test +// txJSONTestTx represents the type that in the JSON test // cases `proto` field. The inner contents are protojson // encoded, so we represent them as []byte here, and decode // them inside the test. -type txJsonTestTx struct { +type txJSONTestTx struct { Body json.RawMessage AuthInfo json.RawMessage `json:"auth_info"` } -type txJsonTest struct { +type txJSONTest struct { Name string - Proto txJsonTestTx + Proto txJSONTestTx SignerData json.RawMessage `json:"signer_data"` Metadata *bankv1beta1.Metadata Error bool Screens []textual.Screen } -func TestTxJsonTestcases(t *testing.T) { +func TestTxJSONTestcases(t *testing.T) { raw, err := os.ReadFile("./internal/testdata/tx.json") require.NoError(t, err) - var testcases []txJsonTest + var testcases []txJSONTest err = json.Unmarshal(raw, &testcases) require.NoError(t, err) @@ -57,6 +57,8 @@ func TestTxJsonTestcases(t *testing.T) { txBody, bodyBz, txAuthInfo, authInfoBz, signerData := createTextualData(t, tc.Proto, tc.SignerData) tr, err := textual.NewSignModeHandler(textual.SignModeOptions{CoinMetadataQuerier: mockCoinMetadataQuerier}) + require.NoError(t, err) + rend := textual.NewTxValueRenderer(tr) ctx := addMetadataToContext(context.Background(), tc.Metadata) @@ -65,7 +67,7 @@ func TestTxJsonTestcases(t *testing.T) { AuthInfoBytes: authInfoBz, SignerData: &textualpb.SignerData{ Address: signerData.Address, - ChainId: signerData.ChainId, + ChainId: signerData.ChainID, AccountNumber: signerData.AccountNumber, Sequence: signerData.Sequence, PubKey: signerData.PubKey, @@ -115,7 +117,7 @@ func TestTxJsonTestcases(t *testing.T) { // createTextualData creates a Textual data give then JSON // test case. -func createTextualData(t *testing.T, jsonTx txJsonTestTx, jsonSignerData json.RawMessage) (*txv1beta1.TxBody, []byte, *txv1beta1.AuthInfo, []byte, signing.SignerData) { +func createTextualData(t *testing.T, jsonTx txJSONTestTx, jsonSignerData json.RawMessage) (*txv1beta1.TxBody, []byte, *txv1beta1.AuthInfo, []byte, signing.SignerData) { body := &txv1beta1.TxBody{} authInfo := &txv1beta1.AuthInfo{} protoSignerData := &textualpb.SignerData{} @@ -142,7 +144,7 @@ func createTextualData(t *testing.T, jsonTx txJsonTestTx, jsonSignerData json.Ra func signerDataFromProto(d *textualpb.SignerData) signing.SignerData { return signing.SignerData{ Address: d.Address, - ChainId: d.ChainId, + ChainID: d.ChainId, AccountNumber: d.AccountNumber, Sequence: d.Sequence, PubKey: d.PubKey, diff --git a/x/tx/signing/textual/types.go b/x/tx/signing/textual/types.go index 0f22147b02c3..c4b3ee0b34e8 100644 --- a/x/tx/signing/textual/types.go +++ b/x/tx/signing/textual/types.go @@ -34,10 +34,13 @@ type Screen struct { // here, so that optionally more value renderers could be built, for example, a // separate one for a different language. type ValueRenderer interface { - // Format should render the value to a text plus annotation. + // Format renders the Protobuf value to a list of Screens. Format(context.Context, protoreflect.Value) ([]Screen, error) - // Parse should be the inverse of Format. + // Parse is the inverse of Format. It must be able to parse all valid + // screens, meaning only those generated using this renderer's Format method. + // However the behavior of Parse on invalid screens is not specified, + // and does not necessarily error. Parse(context.Context, []Screen) (protoreflect.Value, error) } @@ -46,9 +49,13 @@ type ValueRenderer interface { type RepeatedValueRenderer interface { ValueRenderer - // FormatRepeated should render the value to a text plus annotation. + // FormatRepeated renders the Protobuf list value to a list of Screens. FormatRepeated(context.Context, protoreflect.Value) ([]Screen, error) - // ParseRepeated should be the inverse of Format. The list will be populated with the repeated values. + // ParseRepeated is the inverse of FormatRepeated. It must parse all + // valid screens, meaning only those generated using this renderer's + // FormatRepeated method. However the behavior on invalid screens is not + // specified, and does not necessarily error. The `protoreflect.List` + // argument will be mutated and populated with the repeated values. ParseRepeated(context.Context, []Screen, protoreflect.List) error } diff --git a/x/upgrade/abci.go b/x/upgrade/abci.go index 90eb2962858d..ae72c678edf2 100644 --- a/x/upgrade/abci.go +++ b/x/upgrade/abci.go @@ -38,7 +38,7 @@ func BeginBlocker(k *keeper.Keeper, ctx sdk.Context) { var appVersion uint64 cp := ctx.ConsensusParams() - if cp != nil && cp.Version != nil { + if cp.Version != nil { appVersion = cp.Version.App } diff --git a/x/upgrade/abci_test.go b/x/upgrade/abci_test.go index 0bb85a2f776c..c3ccf4a0871a 100644 --- a/x/upgrade/abci_test.go +++ b/x/upgrade/abci_test.go @@ -6,18 +6,12 @@ import ( "testing" "time" - cmtproto "github.com/cometbft/cometbft/proto/tendermint/types" - "github.com/stretchr/testify/require" - "github.com/stretchr/testify/suite" - "cosmossdk.io/core/appmodule" "cosmossdk.io/log" storetypes "cosmossdk.io/store/types" - "cosmossdk.io/x/upgrade" - "cosmossdk.io/x/upgrade/keeper" - "cosmossdk.io/x/upgrade/types" - + cmtproto "github.com/cometbft/cometbft/proto/tendermint/types" "github.com/cosmos/cosmos-sdk/baseapp" + addresscodec "github.com/cosmos/cosmos-sdk/codec/address" "github.com/cosmos/cosmos-sdk/testutil" sdk "github.com/cosmos/cosmos-sdk/types" sdkerrors "github.com/cosmos/cosmos-sdk/types/errors" @@ -26,6 +20,12 @@ import ( authtypes "github.com/cosmos/cosmos-sdk/x/auth/types" govtypes "github.com/cosmos/cosmos-sdk/x/gov/types" govtypesv1beta1 "github.com/cosmos/cosmos-sdk/x/gov/types/v1beta1" + "github.com/stretchr/testify/require" + "github.com/stretchr/testify/suite" + + "cosmossdk.io/x/upgrade" + "cosmossdk.io/x/upgrade/keeper" + "cosmossdk.io/x/upgrade/types" ) type TestSuite struct { @@ -58,7 +58,7 @@ func setupTest(t *testing.T, height int64, skip map[int64]bool) *TestSuite { s.ctx = testCtx.Ctx.WithBlockHeader(cmtproto.Header{Time: time.Now(), Height: height}) - s.module = upgrade.NewAppModule(s.keeper) + s.module = upgrade.NewAppModule(s.keeper, addresscodec.NewBech32Codec("cosmos")) s.handler = upgrade.NewSoftwareUpgradeProposalHandler(s.keeper) return &s } @@ -476,7 +476,7 @@ func TestDowngradeVerification(t *testing.T) { skip := map[int64]bool{} tempDir := t.TempDir() k := keeper.NewKeeper(skip, key, encCfg.Codec, tempDir, nil, authtypes.NewModuleAddress(govtypes.ModuleName).String()) - m := upgrade.NewAppModule(k) + m := upgrade.NewAppModule(k, addresscodec.NewBech32Codec("cosmos")) handler := upgrade.NewSoftwareUpgradeProposalHandler(k) // submit a plan. @@ -525,7 +525,7 @@ func TestDowngradeVerification(t *testing.T) { // downgrade. now keeper does not have the handler. k := keeper.NewKeeper(skip, key, encCfg.Codec, tempDir, nil, authtypes.NewModuleAddress(govtypes.ModuleName).String()) - m := upgrade.NewAppModule(k) + m := upgrade.NewAppModule(k, addresscodec.NewBech32Codec("cosmos")) // assertions lastAppliedPlan, _ := k.GetLastCompletedUpgrade(ctx) diff --git a/x/upgrade/client/cli/parse_test.go b/x/upgrade/client/cli/parse_test.go index c9ef3946b59c..3a3b38eb4105 100644 --- a/x/upgrade/client/cli/parse_test.go +++ b/x/upgrade/client/cli/parse_test.go @@ -4,12 +4,14 @@ import ( "strconv" "testing" - "cosmossdk.io/x/upgrade/types" + addresscodec "github.com/cosmos/cosmos-sdk/codec/address" "github.com/stretchr/testify/require" + + "cosmossdk.io/x/upgrade/types" ) func TestParsePlan(t *testing.T) { - fs := NewCmdSubmitUpgradeProposal().Flags() + fs := NewCmdSubmitUpgradeProposal(addresscodec.NewBech32Codec("cosmos")).Flags() proposal := types.MsgSoftwareUpgrade{ Plan: types.Plan{ diff --git a/x/upgrade/client/cli/tx.go b/x/upgrade/client/cli/tx.go index d00a59047cc0..893b74680e1f 100644 --- a/x/upgrade/client/cli/tx.go +++ b/x/upgrade/client/cli/tx.go @@ -5,17 +5,17 @@ import ( "os" "path/filepath" - "github.com/spf13/cobra" - - "cosmossdk.io/x/upgrade/plan" - "cosmossdk.io/x/upgrade/types" - + addresscodec "cosmossdk.io/core/address" "github.com/cosmos/cosmos-sdk/client" "github.com/cosmos/cosmos-sdk/client/flags" "github.com/cosmos/cosmos-sdk/client/tx" sdk "github.com/cosmos/cosmos-sdk/types" "github.com/cosmos/cosmos-sdk/types/address" "github.com/cosmos/cosmos-sdk/x/gov/client/cli" + "github.com/spf13/cobra" + + "cosmossdk.io/x/upgrade/plan" + "cosmossdk.io/x/upgrade/types" ) const ( @@ -27,22 +27,22 @@ const ( ) // GetTxCmd returns the transaction commands for this module -func GetTxCmd() *cobra.Command { +func GetTxCmd(ac addresscodec.Codec) *cobra.Command { cmd := &cobra.Command{ Use: types.ModuleName, Short: "Upgrade transaction subcommands", } cmd.AddCommand( - NewCmdSubmitUpgradeProposal(), - NewCmdSubmitCancelUpgradeProposal(), + NewCmdSubmitUpgradeProposal(ac), + NewCmdSubmitCancelUpgradeProposal(ac), ) return cmd } // NewCmdSubmitUpgradeProposal implements a command handler for submitting a software upgrade proposal transaction. -func NewCmdSubmitUpgradeProposal() *cobra.Command { +func NewCmdSubmitUpgradeProposal(ac addresscodec.Codec) *cobra.Command { cmd := &cobra.Command{ Use: "software-upgrade [name] (--upgrade-height [height]) (--upgrade-info [info]) [flags]", Args: cobra.ExactArgs(1), @@ -89,7 +89,7 @@ func NewCmdSubmitUpgradeProposal() *cobra.Command { authority, _ := cmd.Flags().GetString(FlagAuthority) if authority != "" { - if _, err = sdk.AccAddressFromBech32(authority); err != nil { + if _, err = ac.StringToBytes(authority); err != nil { return fmt.Errorf("invalid authority address: %w", err) } } else { @@ -124,7 +124,7 @@ func NewCmdSubmitUpgradeProposal() *cobra.Command { } // NewCmdSubmitCancelUpgradeProposal implements a command handler for submitting a software upgrade cancel proposal transaction. -func NewCmdSubmitCancelUpgradeProposal() *cobra.Command { +func NewCmdSubmitCancelUpgradeProposal(ac addresscodec.Codec) *cobra.Command { cmd := &cobra.Command{ Use: "cancel-software-upgrade [flags]", Args: cobra.ExactArgs(0), @@ -143,7 +143,7 @@ func NewCmdSubmitCancelUpgradeProposal() *cobra.Command { authority, _ := cmd.Flags().GetString(FlagAuthority) if authority != "" { - if _, err = sdk.AccAddressFromBech32(authority); err != nil { + if _, err = ac.StringToBytes(authority); err != nil { return fmt.Errorf("invalid authority address: %w", err) } } else { diff --git a/x/upgrade/client/cli/tx_test.go b/x/upgrade/client/cli/tx_test.go deleted file mode 100644 index dd8d5c9e347b..000000000000 --- a/x/upgrade/client/cli/tx_test.go +++ /dev/null @@ -1,85 +0,0 @@ -package cli_test - -import ( - "context" - "fmt" - "io" - "testing" - - rpcclientmock "github.com/cometbft/cometbft/rpc/client/mock" - "github.com/stretchr/testify/require" - - "cosmossdk.io/x/upgrade" - upgradecli "cosmossdk.io/x/upgrade/client/cli" - - "github.com/cosmos/cosmos-sdk/client" - "github.com/cosmos/cosmos-sdk/client/flags" - "github.com/cosmos/cosmos-sdk/crypto/keyring" - svrcmd "github.com/cosmos/cosmos-sdk/server/cmd" - clitestutil "github.com/cosmos/cosmos-sdk/testutil/cli" - testutilmod "github.com/cosmos/cosmos-sdk/types/module/testutil" -) - -func TestModuleVersionsCLI(t *testing.T) { - cmd := upgradecli.GetModuleVersionsCmd() - cmd.SetOut(io.Discard) - require.NotNil(t, cmd) - - encCfg := testutilmod.MakeTestEncodingConfig(upgrade.AppModuleBasic{}) - kr := keyring.NewInMemory(encCfg.Codec) - baseCtx := client.Context{}. - WithKeyring(kr). - WithTxConfig(encCfg.TxConfig). - WithCodec(encCfg.Codec). - WithClient(clitestutil.MockCometRPC{Client: rpcclientmock.Client{}}). - WithAccountRetriever(client.MockAccountRetriever{}). - WithOutput(io.Discard). - WithChainID("test-chain") - - testCases := []struct { - msg string - args []string - expCmdOuptut string - }{ - { - msg: "test full query with json output", - args: []string{fmt.Sprintf("--%s=1", flags.FlagHeight), fmt.Sprintf("--%s=json", flags.FlagOutput)}, - expCmdOuptut: `--height=1 --output=json`, - }, - { - msg: "test full query with text output", - args: []string{fmt.Sprintf("--%s=1", flags.FlagHeight), fmt.Sprintf("--%s=text", flags.FlagOutput)}, - expCmdOuptut: `--height=1 --output=text`, - }, - { - msg: "test single module", - args: []string{"bank", fmt.Sprintf("--%s=1", flags.FlagHeight)}, - expCmdOuptut: `bank --height=1`, - }, - { - msg: "test non-existent module", - args: []string{"abcdefg", fmt.Sprintf("--%s=1", flags.FlagHeight)}, - expCmdOuptut: `abcdefg --height=1`, - }, - } - - for _, tc := range testCases { - tc := tc - - t.Run(tc.msg, func(t *testing.T) { - ctx := svrcmd.CreateExecuteContext(context.Background()) - - cmd.SetOut(io.Discard) - require.NotNil(t, cmd) - - cmd.SetContext(ctx) - cmd.SetArgs(tc.args) - - require.NoError(t, client.SetCmdClientContextHandler(baseCtx, cmd)) - - if len(tc.args) != 0 { - require.Contains(t, fmt.Sprint(cmd), tc.expCmdOuptut) - } - }) - } -} diff --git a/x/upgrade/doc.go b/x/upgrade/doc.go index 8b101c39a6b9..4ebab204f725 100644 --- a/x/upgrade/doc.go +++ b/x/upgrade/doc.go @@ -117,7 +117,7 @@ specified here https://github.com/cosmos/cosmos-sdk/tree/main/cosmovisor/README. This will allow a properly configured cosmsod daemon to auto-download new binaries and auto-upgrade. As noted there, this is intended more for full nodes than validators. -# Cancelling Upgrades +# Canceling Upgrades There are two ways to cancel a planned upgrade - with on-chain governance or off-chain social consensus. For the first one, there is a CancelSoftwareUpgrade proposal type, which can be voted on and will diff --git a/x/upgrade/go.mod b/x/upgrade/go.mod index d6e62f308625..c940d9b2f2ec 100644 --- a/x/upgrade/go.mod +++ b/x/upgrade/go.mod @@ -3,44 +3,44 @@ module cosmossdk.io/x/upgrade go 1.20 require ( - cosmossdk.io/api v0.3.2-0.20230313131911-55bf5d4efbe7 + cosmossdk.io/api v0.4.0 cosmossdk.io/core v0.6.1 cosmossdk.io/depinject v1.0.0-alpha.3 cosmossdk.io/errors v1.0.0-beta.7 - cosmossdk.io/log v0.1.0 - cosmossdk.io/store v0.1.0-alpha.1 - github.com/cometbft/cometbft v0.37.0 + cosmossdk.io/log v1.0.0 + cosmossdk.io/store v0.1.0-alpha.1.0.20230328185921-37ba88872dbc + github.com/armon/go-metrics v0.4.1 + github.com/cometbft/cometbft v0.37.1-0.20230411132551-3a91d155e664 github.com/cosmos/cosmos-db v1.0.0-rc.1 github.com/cosmos/cosmos-proto v1.0.0-beta.3 - github.com/cosmos/cosmos-sdk v0.46.0-beta2.0.20230321173237-fe77d4bca302 - github.com/cosmos/gogoproto v1.4.6 + github.com/cosmos/cosmos-sdk v0.46.0-beta2.0.20230419074131-aa683247d515 + github.com/cosmos/gogoproto v1.4.8 github.com/golang/protobuf v1.5.3 github.com/grpc-ecosystem/grpc-gateway v1.16.0 github.com/hashicorp/go-getter v1.7.1 github.com/spf13/cast v1.5.0 - github.com/spf13/cobra v1.6.1 + github.com/spf13/cobra v1.7.0 github.com/spf13/pflag v1.0.5 github.com/stretchr/testify v1.8.2 - google.golang.org/genproto v0.0.0-20230320184635-7606e756e683 + google.golang.org/genproto v0.0.0-20230410155749-daa745c078e1 google.golang.org/grpc v1.54.0 google.golang.org/protobuf v1.30.0 ) require ( cloud.google.com/go v0.110.0 // indirect - cloud.google.com/go/compute v1.18.0 // indirect + cloud.google.com/go/compute v1.19.0 // indirect cloud.google.com/go/compute/metadata v0.2.3 // indirect cloud.google.com/go/iam v0.13.0 // indirect cloud.google.com/go/storage v1.30.0 // indirect - cosmossdk.io/collections v0.0.0-20230309163709-87da587416ba // indirect + cosmossdk.io/collections v0.1.0 // indirect cosmossdk.io/math v1.0.0 // indirect - cosmossdk.io/x/tx v0.3.1-0.20230321155358-6522dd1731b5 // indirect + cosmossdk.io/x/tx v0.5.1-0.20230407182919-057d2e09bd63 // indirect filippo.io/edwards25519 v1.0.0 // indirect github.com/99designs/go-keychain v0.0.0-20191008050251-8e49817e8af4 // indirect github.com/99designs/keyring v1.2.1 // indirect github.com/ChainSafe/go-schnorrkel v0.0.0-20200405005733-88cbf1b4c40d // indirect github.com/DataDog/zstd v1.5.2 // indirect - github.com/armon/go-metrics v0.4.1 // indirect github.com/aws/aws-sdk-go v1.44.224 // indirect github.com/beorn7/perks v1.0.1 // indirect github.com/bgentry/go-netrc v0.0.0-20140422174119-9fd32a8b3d3d // indirect @@ -52,7 +52,7 @@ require ( github.com/chzyer/readline v1.5.1 // indirect github.com/cockroachdb/errors v1.9.1 // indirect github.com/cockroachdb/logtags v0.0.0-20230118201751-21c54148d20b // indirect - github.com/cockroachdb/pebble v0.0.0-20230315223031-1e5ddd10389e // indirect + github.com/cockroachdb/pebble v0.0.0-20230412222916-60cfeb46143b // indirect github.com/cockroachdb/redact v1.1.3 // indirect github.com/cometbft/cometbft-db v0.7.0 // indirect github.com/confio/ics23/go v0.9.0 // indirect @@ -64,7 +64,7 @@ require ( github.com/creachadair/taskgroup v0.4.2 // indirect github.com/danieljoos/wincred v1.1.2 // indirect github.com/davecgh/go-spew v1.1.1 // indirect - github.com/decred/dcrd/dcrec/secp256k1/v4 v4.1.0 // indirect + github.com/decred/dcrd/dcrec/secp256k1/v4 v4.2.0 // indirect github.com/desertbit/timer v0.0.0-20180107155436-c41aec40b27f // indirect github.com/dgraph-io/badger/v2 v2.2007.4 // indirect github.com/dgraph-io/ristretto v0.1.1 // indirect @@ -74,7 +74,7 @@ require ( github.com/fatih/color v1.15.0 // indirect github.com/felixge/httpsnoop v1.0.2 // indirect github.com/fsnotify/fsnotify v1.6.0 // indirect - github.com/getsentry/sentry-go v0.19.0 // indirect + github.com/getsentry/sentry-go v0.20.0 // indirect github.com/go-kit/kit v0.12.0 // indirect github.com/go-kit/log v0.2.1 // indirect github.com/go-logfmt/logfmt v0.6.0 // indirect @@ -113,12 +113,12 @@ require ( github.com/inconshreveable/mousetrap v1.1.0 // indirect github.com/jmespath/go-jmespath v0.4.0 // indirect github.com/jmhodges/levigo v1.0.0 // indirect - github.com/klauspost/compress v1.16.3 // indirect + github.com/klauspost/compress v1.16.5 // indirect github.com/kr/pretty v0.3.1 // indirect github.com/kr/text v0.2.0 // indirect github.com/lib/pq v1.10.7 // indirect github.com/libp2p/go-buffer-pool v0.1.0 // indirect - github.com/linxGnu/grocksdb v1.7.15 // indirect + github.com/linxGnu/grocksdb v1.7.16 // indirect github.com/magiconair/properties v1.8.7 // indirect github.com/manifoldco/promptui v0.9.0 // indirect github.com/mattn/go-colorable v0.1.13 // indirect @@ -135,14 +135,14 @@ require ( github.com/petermattis/goid v0.0.0-20230317030725-371a4b8eda08 // indirect github.com/pkg/errors v0.9.1 // indirect github.com/pmezard/go-difflib v1.0.0 // indirect - github.com/prometheus/client_golang v1.14.0 // indirect + github.com/prometheus/client_golang v1.15.0 // indirect github.com/prometheus/client_model v0.3.0 // indirect github.com/prometheus/common v0.42.0 // indirect github.com/prometheus/procfs v0.9.0 // indirect github.com/rcrowley/go-metrics v0.0.0-20201227073835-cf1acfcdf475 // indirect - github.com/rogpeppe/go-internal v1.9.0 // indirect + github.com/rogpeppe/go-internal v1.10.0 // indirect github.com/rs/cors v1.8.3 // indirect - github.com/rs/zerolog v1.29.0 // indirect + github.com/rs/zerolog v1.29.1 // indirect github.com/sasha-s/go-deadlock v0.3.1 // indirect github.com/spf13/afero v1.9.3 // indirect github.com/spf13/jwalterweatherman v1.1.0 // indirect @@ -157,14 +157,14 @@ require ( github.com/zondax/ledger-go v0.14.1 // indirect go.etcd.io/bbolt v1.3.6 // indirect go.opencensus.io v0.24.0 // indirect - golang.org/x/crypto v0.7.0 // indirect + golang.org/x/crypto v0.8.0 // indirect golang.org/x/exp v0.0.0-20230321023759-10a507213a29 // indirect - golang.org/x/net v0.8.0 // indirect + golang.org/x/net v0.9.0 // indirect golang.org/x/oauth2 v0.6.0 // indirect golang.org/x/sync v0.1.0 // indirect - golang.org/x/sys v0.6.0 // indirect - golang.org/x/term v0.6.0 // indirect - golang.org/x/text v0.8.0 // indirect + golang.org/x/sys v0.7.0 // indirect + golang.org/x/term v0.7.0 // indirect + golang.org/x/text v0.9.0 // indirect golang.org/x/xerrors v0.0.0-20220907171357-04be3eba64a2 // indirect google.golang.org/api v0.114.0 // indirect google.golang.org/appengine v1.6.7 // indirect diff --git a/x/upgrade/go.sum b/x/upgrade/go.sum index dd416155b43f..2de7d339f4a6 100644 --- a/x/upgrade/go.sum +++ b/x/upgrade/go.sum @@ -70,8 +70,8 @@ cloud.google.com/go/compute v1.6.0/go.mod h1:T29tfhtVbq1wvAPo0E3+7vhgmkOYeXjhFvz cloud.google.com/go/compute v1.6.1/go.mod h1:g85FgpzFvNULZ+S8AYq87axRKuf2Kh7deLqV/jJ3thU= cloud.google.com/go/compute v1.7.0/go.mod h1:435lt8av5oL9P3fv1OEzSbSUe+ybHXGMPQHHZWZxy9U= cloud.google.com/go/compute v1.10.0/go.mod h1:ER5CLbMxl90o2jtNbGSbtfOpQKR0t15FOtRsugnLrlU= -cloud.google.com/go/compute v1.18.0 h1:FEigFqoDbys2cvFkZ9Fjq4gnHBP55anJ0yQyau2f9oY= -cloud.google.com/go/compute v1.18.0/go.mod h1:1X7yHxec2Ga+Ss6jPyjxRxpu2uu7PLgsOVXvgU0yacs= +cloud.google.com/go/compute v1.19.0 h1:+9zda3WGgW1ZSTlVppLCYFIr48Pa35q1uG2N1itbCEQ= +cloud.google.com/go/compute v1.19.0/go.mod h1:rikpw2y+UMidAe9tISo04EHNOIf42RLYF/q8Bs93scU= cloud.google.com/go/compute/metadata v0.2.3 h1:mg4jlk7mCAj6xXp9UJ4fjI9VUI5rubuGBW5aJ7UnBMY= cloud.google.com/go/compute/metadata v0.2.3/go.mod h1:VAV5nSsACxMJvgaAuX6Pk2AawlZn8kiOGuCv6gTkwuA= cloud.google.com/go/containeranalysis v0.5.1/go.mod h1:1D92jd8gRR/c0fGMlymRgxWD3Qw9C1ff6/T7mLgVL8I= @@ -188,24 +188,24 @@ cloud.google.com/go/webrisk v1.4.0/go.mod h1:Hn8X6Zr+ziE2aNd8SliSDWpEnSS1u4R9+xX cloud.google.com/go/webrisk v1.5.0/go.mod h1:iPG6fr52Tv7sGk0H6qUFzmL3HHZev1htXuWDEEsqMTg= cloud.google.com/go/workflows v1.6.0/go.mod h1:6t9F5h/unJz41YqfBmqSASJSXccBLtD1Vwf+KmJENM0= cloud.google.com/go/workflows v1.7.0/go.mod h1:JhSrZuVZWuiDfKEFxU0/F1PQjmpnpcoISEXH2bcHC3M= -cosmossdk.io/api v0.3.2-0.20230313131911-55bf5d4efbe7 h1:4LrWK+uGP5IxznxtHHsHD+ZBs2+oZRH2loYOGjHLzZM= -cosmossdk.io/api v0.3.2-0.20230313131911-55bf5d4efbe7/go.mod h1:yVns7mKgcsG+hZW/3C5FdJtC6QYWdFIcRlKb9+5HV5g= -cosmossdk.io/collections v0.0.0-20230309163709-87da587416ba h1:S4PYij/tX3Op/hwenVEN9D+M27JRcwSwVqE3UA0BnwM= -cosmossdk.io/collections v0.0.0-20230309163709-87da587416ba/go.mod h1:lpS+G8bGC2anqzWdndTzjnQnuMO/qAcgZUkGJp4i3rc= +cosmossdk.io/api v0.4.0 h1:x90DmdidP6EhzktAa/6/IofSHidDnPjahdlrUvyQZQw= +cosmossdk.io/api v0.4.0/go.mod h1:TWDzBhUBhI1LhSf2XSYpfIBf6D4mbLu/fvzvDfhcaYM= +cosmossdk.io/collections v0.1.0 h1:nzJGeiq32KnZroSrhB6rPifw4I85Cgmzw/YAmr4luv8= +cosmossdk.io/collections v0.1.0/go.mod h1:xbauc0YsbUF8qKMVeBZl0pFCunxBIhKN/WlxpZ3lBuo= cosmossdk.io/core v0.6.1 h1:OBy7TI2W+/gyn2z40vVvruK3di+cAluinA6cybFbE7s= cosmossdk.io/core v0.6.1/go.mod h1:g3MMBCBXtxbDWBURDVnJE7XML4BG5qENhs0gzkcpuFA= cosmossdk.io/depinject v1.0.0-alpha.3 h1:6evFIgj//Y3w09bqOUOzEpFj5tsxBqdc5CfkO7z+zfw= cosmossdk.io/depinject v1.0.0-alpha.3/go.mod h1:eRbcdQ7MRpIPEM5YUJh8k97nxHpYbc3sMUnEtt8HPWU= cosmossdk.io/errors v1.0.0-beta.7 h1:gypHW76pTQGVnHKo6QBkb4yFOJjC+sUGRc5Al3Odj1w= cosmossdk.io/errors v1.0.0-beta.7/go.mod h1:mz6FQMJRku4bY7aqS/Gwfcmr/ue91roMEKAmDUDpBfE= -cosmossdk.io/log v0.1.0 h1:Vnexi+KzUCjmqq/m93teAxjt5biWFfZ5PI1imx2IJw8= -cosmossdk.io/log v0.1.0/go.mod h1:p95Wq6mDY3SREMc4y7+QU9Uwy3nyvfpWGD1iSaFkVFs= +cosmossdk.io/log v1.0.0 h1:NGKZ/A5rd4PduDfoscgABklX557PWjQINbosZy/m3Jk= +cosmossdk.io/log v1.0.0/go.mod h1:CwX9BLiBruZb7lzLlRr3R231d/fVPUXk8gAdV4LQap0= cosmossdk.io/math v1.0.0 h1:ro9w7eKx23om2tZz/VM2Pf+z2WAbGX1yDQQOJ6iGeJw= cosmossdk.io/math v1.0.0/go.mod h1:Ygz4wBHrgc7g0N+8+MrnTfS9LLn9aaTGa9hKopuym5k= -cosmossdk.io/store v0.1.0-alpha.1 h1:NGomhLUXzAxvK4OF8+yP6eNUG5i4LwzOzx+S494pTCg= -cosmossdk.io/store v0.1.0-alpha.1/go.mod h1:kmCMbhrleCZ6rDZPY/EGNldNvPebFNyVPFYp+pv05/k= -cosmossdk.io/x/tx v0.3.1-0.20230321155358-6522dd1731b5 h1:AlvyRc7f7Py1mv254vrqjIIuykCnitHIz2T+nup3bU0= -cosmossdk.io/x/tx v0.3.1-0.20230321155358-6522dd1731b5/go.mod h1:FNkSEMbLP9NFdTfrbslNUtNS7OXf3wgZeJyXzfRPa4c= +cosmossdk.io/store v0.1.0-alpha.1.0.20230328185921-37ba88872dbc h1:9piuA+NYmhe+SyMPtMoboLw/djgDbrI3dD5TG020Tnk= +cosmossdk.io/store v0.1.0-alpha.1.0.20230328185921-37ba88872dbc/go.mod h1:UFF5rmjN7WYVfxo6ArdY/l1+yyWMURBWOmSJypGqFHQ= +cosmossdk.io/x/tx v0.5.1-0.20230407182919-057d2e09bd63 h1:zHqj2VwZ/MStFmR7SUe/7gErOFhL9v2rkjmWPB/st34= +cosmossdk.io/x/tx v0.5.1-0.20230407182919-057d2e09bd63/go.mod h1:Oh3Kh+IPOfMEILNxVd2e8SLqRrIjYHpdGBfDg4ghU/k= dmitri.shuralyov.com/gpu/mtl v0.0.0-20190408044501-666a987793e9/go.mod h1:H6x//7gZCb22OMCxBHrMx7a5I7Hp++hsVxbQ4BYO7hU= filippo.io/edwards25519 v1.0.0 h1:0wAIcmJUqRdI8IJ/3eGi5/HwXZWPujYXXlkrQogz0Ek= filippo.io/edwards25519 v1.0.0/go.mod h1:N1IkdkCkiLB6tki+MYJoSx2JTY9NUlxZE7eHn5EwJns= @@ -271,6 +271,7 @@ github.com/bgentry/go-netrc v0.0.0-20140422174119-9fd32a8b3d3d/go.mod h1:6QX/PXZ github.com/bgentry/speakeasy v0.1.0/go.mod h1:+zsyZBPWlz7T6j88CTgSN5bM796AkVf0kBD4zp0CCIs= github.com/bgentry/speakeasy v0.1.1-0.20220910012023-760eaf8b6816 h1:41iFGWnSlI2gVpmOtVTJZNodLdLQLn/KsJqFvXwnd/s= github.com/bgentry/speakeasy v0.1.1-0.20220910012023-760eaf8b6816/go.mod h1:+zsyZBPWlz7T6j88CTgSN5bM796AkVf0kBD4zp0CCIs= +github.com/bits-and-blooms/bitset v1.6.0 h1:FVfaUsleKAUTJnaN9Fd1YFFi1S8vAX5xeXnXHFYOojM= github.com/btcsuite/btcd/btcec/v2 v2.3.2 h1:5n0X6hX0Zk+6omWcihdYvdAlGf2DfasC0GMf7DClJ3U= github.com/btcsuite/btcd/btcec/v2 v2.3.2/go.mod h1:zYzJ8etWJQIv1Ogk7OzpWjowwOdXY1W/17j2MW85J04= github.com/btcsuite/btcd/btcutil v1.1.2 h1:XLMbX8JQEiwMcYft2EGi8zPUkoa0abKIU6/BJSRsjzQ= @@ -321,14 +322,14 @@ github.com/cockroachdb/errors v1.9.1/go.mod h1:2sxOtL2WIc096WSZqZ5h8fa17rdDq9HZO github.com/cockroachdb/logtags v0.0.0-20211118104740-dabe8e521a4f/go.mod h1:Vz9DsVWQQhf3vs21MhPMZpMGSht7O/2vFW2xusFUVOs= github.com/cockroachdb/logtags v0.0.0-20230118201751-21c54148d20b h1:r6VH0faHjZeQy818SGhaone5OnYfxFR/+AzdY3sf5aE= github.com/cockroachdb/logtags v0.0.0-20230118201751-21c54148d20b/go.mod h1:Vz9DsVWQQhf3vs21MhPMZpMGSht7O/2vFW2xusFUVOs= -github.com/cockroachdb/pebble v0.0.0-20230315223031-1e5ddd10389e h1:CDuLmyaZ1pD4OJHHtubKqgu/Byw5zAnm+gArJsyj96Q= -github.com/cockroachdb/pebble v0.0.0-20230315223031-1e5ddd10389e/go.mod h1:9lRMC4XN3/BLPtIp6kAKwIaHu369NOf2rMucPzipz50= +github.com/cockroachdb/pebble v0.0.0-20230412222916-60cfeb46143b h1:92ve6F1Pls/eqd+V+102lOMRJatgpqqsQvbT9Bl/fjg= +github.com/cockroachdb/pebble v0.0.0-20230412222916-60cfeb46143b/go.mod h1:9lRMC4XN3/BLPtIp6kAKwIaHu369NOf2rMucPzipz50= github.com/cockroachdb/redact v1.1.3 h1:AKZds10rFSIj7qADf0g46UixK8NNLwWTNdCIGS5wfSQ= github.com/cockroachdb/redact v1.1.3/go.mod h1:BVNblN9mBWFyMyqK1k3AAiSxhvhfK2oOZZ2lK+dpvRg= github.com/codahale/hdrhistogram v0.0.0-20161010025455-3a0bb77429bd/go.mod h1:sE/e/2PUdi/liOCUjSTXgM1o87ZssimdTWN964YiIeI= github.com/codegangsta/inject v0.0.0-20150114235600-33e0aa1cb7c0/go.mod h1:4Zcjuz89kmFXt9morQgcfYZAYZ5n8WHjt81YYWIwtTM= -github.com/cometbft/cometbft v0.37.0 h1:M005vBaSaugvYYmNZwJOopynQSjwLoDTwflnQ/I/eYk= -github.com/cometbft/cometbft v0.37.0/go.mod h1:Y2MMMN//O5K4YKd8ze4r9jmk4Y7h0ajqILXbH5JQFVs= +github.com/cometbft/cometbft v0.37.1-0.20230411132551-3a91d155e664 h1:BbCkbnaU3R603XpnbqvuDU8Kfv+hjhiFILOHhVFntsw= +github.com/cometbft/cometbft v0.37.1-0.20230411132551-3a91d155e664/go.mod h1:Y2MMMN//O5K4YKd8ze4r9jmk4Y7h0ajqILXbH5JQFVs= github.com/cometbft/cometbft-db v0.7.0 h1:uBjbrBx4QzU0zOEnU8KxoDl18dMNgDh+zZRUE0ucsbo= github.com/cometbft/cometbft-db v0.7.0/go.mod h1:yiKJIm2WKrt6x8Cyxtq9YTEcIMPcEe4XPxhgX59Fzf0= github.com/confio/ics23/go v0.9.0 h1:cWs+wdbS2KRPZezoaaj+qBleXgUk5WOQFMP3CQFGTr4= @@ -338,7 +339,7 @@ github.com/coreos/etcd v3.3.10+incompatible/go.mod h1:uF7uidLiAD3TWHmW31ZFd/JWoc github.com/coreos/go-etcd v2.0.0+incompatible/go.mod h1:Jez6KQU2B/sWsbdaef3ED8NzMklzPG4d5KIOhIy30Tk= github.com/coreos/go-semver v0.2.0/go.mod h1:nnelYz7RCh+5ahJtPPxZlU+153eP4D4r3EedlOD2RNk= github.com/coreos/go-systemd v0.0.0-20180511133405-39ca1b05acc7/go.mod h1:F5haX7vjVVG0kc13fIWeqUViNPyEJxv/OmvnBo0Yme4= -github.com/coreos/go-systemd/v22 v22.3.3-0.20220203105225-a9a7ef127534/go.mod h1:Y58oyj3AT4RCenI/lSvhwexgC+NSVTIJ3seZv2GcEnc= +github.com/coreos/go-systemd/v22 v22.5.0/go.mod h1:Y58oyj3AT4RCenI/lSvhwexgC+NSVTIJ3seZv2GcEnc= github.com/coreos/pkg v0.0.0-20160727233714-3ac0863d7acf/go.mod h1:E3G3o1h8I7cfcXa63jLwjI0eiQQMgzzUDFVpN/nH/eA= github.com/cosmos/btcutil v1.0.5 h1:t+ZFcX77LpKtDBhjucvnOH8C2l2ioGsBNEQ3jef8xFk= github.com/cosmos/btcutil v1.0.5/go.mod h1:IyB7iuqZMJlthe2tkIFL33xPyzbFYP0XVdS8P5lUPis= @@ -346,16 +347,16 @@ github.com/cosmos/cosmos-db v1.0.0-rc.1 h1:SjnT8B6WKMW9WEIX32qMhnEEKcI7ZP0+G1Sa9 github.com/cosmos/cosmos-db v1.0.0-rc.1/go.mod h1:Dnmk3flSf5lkwCqvvjNpoxjpXzhxnCAFzKHlbaForso= github.com/cosmos/cosmos-proto v1.0.0-beta.3 h1:VitvZ1lPORTVxkmF2fAp3IiA61xVwArQYKXTdEcpW6o= github.com/cosmos/cosmos-proto v1.0.0-beta.3/go.mod h1:t8IASdLaAq+bbHbjq4p960BvcTqtwuAxid3b/2rOD6I= -github.com/cosmos/cosmos-sdk v0.46.0-beta2.0.20230321173237-fe77d4bca302 h1:wffm9LPPG/FBW/tSRdJp2DCgkJQRX+Zsbdmn4I0aWeQ= -github.com/cosmos/cosmos-sdk v0.46.0-beta2.0.20230321173237-fe77d4bca302/go.mod h1:HzOsWXtPxhO8+Y8P4Ru+G3UWx6dTkpGXU9yvT35VEuI= +github.com/cosmos/cosmos-sdk v0.46.0-beta2.0.20230419074131-aa683247d515 h1:KMbJ5nAA0Xk79z0D1oL3kiw9lBYiqlV3ZqUxXVbbgBY= +github.com/cosmos/cosmos-sdk v0.46.0-beta2.0.20230419074131-aa683247d515/go.mod h1:BPvKPN63ettXrpz67uM1rHEqX/UVVkAfceFCPyp217E= github.com/cosmos/go-bip39 v0.0.0-20180819234021-555e2067c45d/go.mod h1:tSxLoYXyBmiFeKpvmq4dzayMdCjCnu8uqmCysIGBT2Y= github.com/cosmos/go-bip39 v1.0.0 h1:pcomnQdrdH22njcAatO0yWojsUnCO3y2tNoV1cb6hHY= github.com/cosmos/go-bip39 v1.0.0/go.mod h1:RNJv0H/pOIVgxw6KS7QeX2a0Uo0aKUlfhZ4xuwvCdJw= github.com/cosmos/gogogateway v1.2.0 h1:Ae/OivNhp8DqBi/sh2A8a1D0y638GpL3tkmLQAiKxTE= github.com/cosmos/gogogateway v1.2.0/go.mod h1:iQpLkGWxYcnCdz5iAdLcRBSw3h7NXeOkZ4GUkT+tbFI= github.com/cosmos/gogoproto v1.4.2/go.mod h1:cLxOsn1ljAHSV527CHOtaIP91kK6cCrZETRBrkzItWU= -github.com/cosmos/gogoproto v1.4.6 h1:Ee7z15dWJaGlgM2rWrK8N2IX7PQcuccu8oG68jp5RL4= -github.com/cosmos/gogoproto v1.4.6/go.mod h1:VS/ASYmPgv6zkPKLjR9EB91lwbLHOzaGCirmKKhncfI= +github.com/cosmos/gogoproto v1.4.8 h1:BrHKc6WFZt8+jRV71vKSQE+JrfF+JAnzrKo2VP7wIZ4= +github.com/cosmos/gogoproto v1.4.8/go.mod h1:hnb0DIEWTv+wdNzNcqus5xCQXq5+CXauq1FJuurRfVY= github.com/cosmos/iavl v0.21.0-beta.1 h1:fBQeBc8HLZ14plJNcmGfaOXSSMLVEHvEQXiTXSD76m0= github.com/cosmos/iavl v0.21.0-beta.1/go.mod h1:25YJYzilTErJ2mKfNB3xyWL9IsCwEQdNzdIutg2mh3U= github.com/cosmos/ledger-cosmos-go v0.13.0 h1:ex0CvCxToSR7j5WjrghPu2Bu9sSXKikjnVvUryNnx4s= @@ -374,9 +375,9 @@ github.com/danieljoos/wincred v1.1.2/go.mod h1:GijpziifJoIBfYh+S7BbkdUTU4LfM+QnG github.com/davecgh/go-spew v1.1.0/go.mod h1:J7Y8YcW2NihsgmVo/mv3lAwl/skON4iLHjSsI+c5H38= github.com/davecgh/go-spew v1.1.1 h1:vj9j/u1bqnvCEfJOwUhtlOARqs3+rkHYY13jYWTU97c= github.com/davecgh/go-spew v1.1.1/go.mod h1:J7Y8YcW2NihsgmVo/mv3lAwl/skON4iLHjSsI+c5H38= -github.com/decred/dcrd/crypto/blake256 v1.0.0 h1:/8DMNYp9SGi5f0w7uCm6d6M4OU2rGFK09Y2A4Xv7EE0= -github.com/decred/dcrd/dcrec/secp256k1/v4 v4.1.0 h1:HbphB4TFFXpv7MNrT52FGrrgVXF1owhMVTHFZIlnvd4= -github.com/decred/dcrd/dcrec/secp256k1/v4 v4.1.0/go.mod h1:DZGJHZMqrU4JJqFAWUS2UO1+lbSKsdiOoYi9Zzey7Fc= +github.com/decred/dcrd/crypto/blake256 v1.0.1 h1:7PltbUIQB7u/FfZ39+DGa/ShuMyJ5ilcvdfma9wOH6Y= +github.com/decred/dcrd/dcrec/secp256k1/v4 v4.2.0 h1:8UrgZ3GkP4i/CLijOJx79Yu+etlyjdBU4sfcs2WYQMs= +github.com/decred/dcrd/dcrec/secp256k1/v4 v4.2.0/go.mod h1:v57UDF4pDQJcEfFUCRop3lJL149eHGSe9Jvczhzjo/0= github.com/desertbit/timer v0.0.0-20180107155436-c41aec40b27f h1:U5y3Y5UE0w7amNe7Z5G/twsBW0KEalRQXZzf8ufSh9I= github.com/desertbit/timer v0.0.0-20180107155436-c41aec40b27f/go.mod h1:xH/i4TFMt8koVQZ6WFms69WAsDWr2XsYL3Hkl7jkoLE= github.com/dgraph-io/badger v1.6.0/go.mod h1:zwt7syl517jmP8s94KqSxTlM6IMsdhYy6psNgSztDR4= @@ -437,8 +438,8 @@ github.com/fsnotify/fsnotify v1.6.0 h1:n+5WquG0fcWoWp6xPWfHdbskMCQaFnG6PfBrh1Ky4 github.com/fsnotify/fsnotify v1.6.0/go.mod h1:sl3t1tCWJFWoRz9R8WJCbQihKKwmorjAbSClcnxKAGw= github.com/gavv/httpexpect v2.0.0+incompatible/go.mod h1:x+9tiU1YnrOvnB725RkpoLv1M62hOWzwo5OXotisrKc= github.com/getsentry/sentry-go v0.12.0/go.mod h1:NSap0JBYWzHND8oMbyi0+XZhUalc1TBdRL1M71JZW2c= -github.com/getsentry/sentry-go v0.19.0 h1:BcCH3CN5tXt5aML+gwmbFwVptLLQA+eT866fCO9wVOM= -github.com/getsentry/sentry-go v0.19.0/go.mod h1:y3+lGEFEFexZtpbG1GUE2WD/f9zGyKYwpEqryTOC/nE= +github.com/getsentry/sentry-go v0.20.0 h1:bwXW98iMRIWxn+4FgPW7vMrjmbym6HblXALmhjHmQaQ= +github.com/getsentry/sentry-go v0.20.0/go.mod h1:lc76E2QywIyW8WuBnwl8Lc4bkmQH4+w1gwTf25trprY= github.com/ghodss/yaml v1.0.0/go.mod h1:4dBDuWmgqj2HViK6kFavaiC9ZROes6MMH2rRYeMEF04= github.com/gin-contrib/sse v0.1.0 h1:Y/yl/+YNO8GZSjAhjMsSuLt29uWRFHdHYUb5lYOV9qE= github.com/gin-contrib/sse v0.1.0/go.mod h1:RHrZQHXnP2xjPF+u1gW/2HnVO7nvIa9PG3Gm+fLHvGI= @@ -699,7 +700,6 @@ github.com/imkira/go-interpol v1.1.0/go.mod h1:z0h2/2T3XF8kyEPpRgJ3kmNv+C43p+I/C github.com/improbable-eng/grpc-web v0.15.0 h1:BN+7z6uNXZ1tQGcNAuaU1YjsLTApzkjt2tzCixLaUPQ= github.com/improbable-eng/grpc-web v0.15.0/go.mod h1:1sy9HKV4Jt9aEs9JSnkWlRJPuPtwNr0l57L4f878wP8= github.com/inconshreveable/mousetrap v1.0.0/go.mod h1:PxqpIevigyE2G7u3NXJIT2ANytuPF1OarO4DADm73n8= -github.com/inconshreveable/mousetrap v1.0.1/go.mod h1:vpF70FUmC8bwa3OWnCshd2FqLfsEA9PFc4w1p2J65bw= github.com/inconshreveable/mousetrap v1.1.0 h1:wN+x4NVGpMsO7ErUn/mUI3vEoE6Jt13X2s0bqwp9tc8= github.com/inconshreveable/mousetrap v1.1.0/go.mod h1:vpF70FUmC8bwa3OWnCshd2FqLfsEA9PFc4w1p2J65bw= github.com/influxdata/influxdb1-client v0.0.0-20191209144304-8bf82d3c094d/go.mod h1:qj24IKcXYK6Iy9ceXlo3Tc+vtHo9lIhSX5JddghvEPo= @@ -746,8 +746,8 @@ github.com/klauspost/compress v1.10.3/go.mod h1:aoV0uJVorq1K+umq18yTdKaF57EivdYs github.com/klauspost/compress v1.11.7/go.mod h1:aoV0uJVorq1K+umq18yTdKaF57EivdYsUV+/s2qKfXs= github.com/klauspost/compress v1.12.3/go.mod h1:8dP1Hq4DHOhN9w426knH3Rhby4rFm6D8eO+e+Dq5Gzg= github.com/klauspost/compress v1.15.11/go.mod h1:QPwzmACJjUTFsnSHH934V6woptycfrDDJnH7hvFVbGM= -github.com/klauspost/compress v1.16.3 h1:XuJt9zzcnaz6a16/OU53ZjWp/v7/42WcR5t2a0PcNQY= -github.com/klauspost/compress v1.16.3/go.mod h1:ntbaceVETuRiXiv4DpjP66DpAtAGkEQskQzEyD//IeE= +github.com/klauspost/compress v1.16.5 h1:IFV2oUNUzZaz+XyusxpLzpzS8Pt5rh0Z16For/djlyI= +github.com/klauspost/compress v1.16.5/go.mod h1:ntbaceVETuRiXiv4DpjP66DpAtAGkEQskQzEyD//IeE= github.com/klauspost/cpuid v1.2.1/go.mod h1:Pj4uuM528wm8OyEC2QMXAi2YiTZ96dNQPGgoMS4s3ek= github.com/konsorten/go-windows-terminal-sequences v1.0.1/go.mod h1:T0+1ngSBFLxvqU3pZ+m/2kptfBszLMUkC4ZK/EgS/cQ= github.com/konsorten/go-windows-terminal-sequences v1.0.3/go.mod h1:T0+1ngSBFLxvqU3pZ+m/2kptfBszLMUkC4ZK/EgS/cQ= @@ -772,8 +772,8 @@ github.com/libp2p/go-buffer-pool v0.1.0 h1:oK4mSFcQz7cTQIfqbe4MIj9gLW+mnanjyFtc6 github.com/libp2p/go-buffer-pool v0.1.0/go.mod h1:N+vh8gMqimBzdKkSMVuydVDq+UV5QTWy5HSiZacSbPg= github.com/lightstep/lightstep-tracer-common/golang/gogo v0.0.0-20190605223551-bc2310a04743/go.mod h1:qklhhLq1aX+mtWk9cPHPzaBjWImj5ULL6C7HFJtXQMM= github.com/lightstep/lightstep-tracer-go v0.18.1/go.mod h1:jlF1pusYV4pidLvZ+XD0UBX0ZE6WURAspgAczcDHrL4= -github.com/linxGnu/grocksdb v1.7.15 h1:AEhP28lkeAybv5UYNYviYISpR6bJejEnKuYbnWAnxx0= -github.com/linxGnu/grocksdb v1.7.15/go.mod h1:pY55D0o+r8yUYLq70QmhdudxYvoDb9F+9puf4m3/W+U= +github.com/linxGnu/grocksdb v1.7.16 h1:Q2co1xrpdkr5Hx3Fp+f+f7fRGhQFQhvi/+226dtLmA8= +github.com/linxGnu/grocksdb v1.7.16/go.mod h1:JkS7pl5qWpGpuVb3bPqTz8nC12X3YtPZT+Xq7+QfQo4= github.com/lyft/protoc-gen-validate v0.0.13/go.mod h1:XbGvPuh87YZc5TdIa2/I4pLk0QoUACkjt2znoq26NVQ= github.com/magiconair/properties v1.8.0/go.mod h1:PppfXfuXeibc/6YijjN8zIbojt8czPbwD3XqdrwzmxQ= github.com/magiconair/properties v1.8.7 h1:IeQXZAiQcpL9mgcAe1Nu6cX9LLw6ExEHKjN0VQdvPDY= @@ -914,8 +914,8 @@ github.com/prometheus/client_golang v1.0.0/go.mod h1:db9x61etRT2tGnBNRi70OPL5Fsn github.com/prometheus/client_golang v1.3.0/go.mod h1:hJaj2vgQTGQmVCsAACORcieXFeDPbaTKGT+JTgUa3og= github.com/prometheus/client_golang v1.4.0/go.mod h1:e9GMxYsXl05ICDXkRhurwBS4Q3OK1iX/F2sw+iXX5zU= github.com/prometheus/client_golang v1.7.1/go.mod h1:PY5Wy2awLA44sXw4AOSfFBetzPP4j5+D6mVACh+pe2M= -github.com/prometheus/client_golang v1.14.0 h1:nJdhIvne2eSX/XRAFV9PcvFFRbrjbcTUj0VP62TMhnw= -github.com/prometheus/client_golang v1.14.0/go.mod h1:8vpkKitgIVNcqrRBWh1C4TIUQgYNtG/XQE4E/Zae36Y= +github.com/prometheus/client_golang v1.15.0 h1:5fCgGYogn0hFdhyhLbw7hEsWxufKtY9klyvdNfFlFhM= +github.com/prometheus/client_golang v1.15.0/go.mod h1:e9yaBhRPU2pPNsZwE+JdQl0KEt1N9XgF6zxWmaC0xOk= github.com/prometheus/client_model v0.0.0-20180712105110-5c3871d89910/go.mod h1:MbSGuTsp3dbXC40dX6PRTWyKYBIrTGTE9sqQNg2J8bo= github.com/prometheus/client_model v0.0.0-20190115171406-56726106282f/go.mod h1:MbSGuTsp3dbXC40dX6PRTWyKYBIrTGTE9sqQNg2J8bo= github.com/prometheus/client_model v0.0.0-20190129233127-fd36f4220a90/go.mod h1:xMI15A0UPsDsEKsMN9yxemIoYk6Tm2C1GtYGdfGttqA= @@ -950,14 +950,15 @@ github.com/rogpeppe/go-internal v1.3.0/go.mod h1:M8bDsm7K2OlrFYOpmOWEs/qY81heoFR github.com/rogpeppe/go-internal v1.6.1/go.mod h1:xXDCJY+GAPziupqXw64V24skbSoqbTEfhy4qGm1nDQc= github.com/rogpeppe/go-internal v1.8.0/go.mod h1:WmiCO8CzOY8rg0OYDC4/i/2WRWAB6poM+XZ2dLUbcbE= github.com/rogpeppe/go-internal v1.8.1/go.mod h1:JeRgkft04UBgHMgCIwADu4Pn6Mtm5d4nPKWu0nJ5d+o= -github.com/rogpeppe/go-internal v1.9.0 h1:73kH8U+JUqXU8lRuOHeVHaa/SZPifC7BkcraZVejAe8= github.com/rogpeppe/go-internal v1.9.0/go.mod h1:WtVeX8xhTBvf0smdhujwtBcq4Qrzq/fJaraNFVN+nFs= +github.com/rogpeppe/go-internal v1.10.0 h1:TMyTOH3F/DB16zRVcYyreMH6GnZZrwQVAoYjRBZyWFQ= +github.com/rogpeppe/go-internal v1.10.0/go.mod h1:UQnix2H7Ngw/k4C5ijL5+65zddjncjaFoBhdsK/akog= github.com/rs/cors v1.7.0/go.mod h1:gFx+x8UowdsKA9AchylcLynDq+nNFfI8FkUZdN/jGCU= github.com/rs/cors v1.8.3 h1:O+qNyWn7Z+F9M0ILBHgMVPuB1xTOucVd5gtaYyXBpRo= github.com/rs/cors v1.8.3/go.mod h1:XyqrcTp5zjWr1wsJ8PIRZssZ8b/WMcMf71DJnit4EMU= github.com/rs/xid v1.4.0/go.mod h1:trrq9SKmegXys3aeAKXMUTdJsYXVwGY3RLcfgqegfbg= -github.com/rs/zerolog v1.29.0 h1:Zes4hju04hjbvkVkOhdl2HpZa+0PmVwigmo8XoORE5w= -github.com/rs/zerolog v1.29.0/go.mod h1:NILgTygv/Uej1ra5XxGf82ZFSLk58MFGAUS2o6usyD0= +github.com/rs/zerolog v1.29.1 h1:cO+d60CHkknCbvzEWxP0S9K6KqyTjrCNUy1LdQLCGPc= +github.com/rs/zerolog v1.29.1/go.mod h1:Le6ESbR7hc+DP6Lt1THiV8CQSdkkNrd3R0XbEgp3ZBU= github.com/russross/blackfriday v1.5.2/go.mod h1:JO/DiYxRf+HjHt06OyowR9PTA263kcR/rfWxYHBV53g= github.com/russross/blackfriday/v2 v2.0.1/go.mod h1:+Rmxgy9KzJVeS9/2gXHxylqXiyQDYRxCVz55jmeOWTM= github.com/russross/blackfriday/v2 v2.1.0/go.mod h1:+Rmxgy9KzJVeS9/2gXHxylqXiyQDYRxCVz55jmeOWTM= @@ -990,8 +991,8 @@ github.com/spf13/cast v1.5.0 h1:rj3WzYc11XZaIZMPKmwP96zkFEnnAmV8s6XbB2aY32w= github.com/spf13/cast v1.5.0/go.mod h1:SpXXQ5YoyJw6s3/6cMTQuxvgRl3PCJiyaX9p6b155UU= github.com/spf13/cobra v0.0.3/go.mod h1:1l0Ry5zgKvJasoi3XT1TypsSe7PqH0Sj9dhYf7v3XqQ= github.com/spf13/cobra v0.0.5/go.mod h1:3K3wKZymM7VvHMDS9+Akkh4K60UwM26emMESw8tLCHU= -github.com/spf13/cobra v1.6.1 h1:o94oiPyS4KD1mPy2fmcYYHHfCxLqYjJOhGsCHFZtEzA= -github.com/spf13/cobra v1.6.1/go.mod h1:IOw/AERYS7UzyrGinqmz6HLUo219MORXGxhbaJUqzrY= +github.com/spf13/cobra v1.7.0 h1:hyqWnYt1ZQShIddO5kBpj3vu05/++x6tJ6dg8EC572I= +github.com/spf13/cobra v1.7.0/go.mod h1:uLxZILRyS/50WlhOIKD7W6V5bgeIt+4sICxh6uRMrb0= github.com/spf13/jwalterweatherman v1.0.0/go.mod h1:cQK4TGJAtQXfYWX+Ddv3mKDzgVb68N+wFjFa4jdeBTo= github.com/spf13/jwalterweatherman v1.1.0 h1:ue6voC5bR5F8YxI5S67j9i582FU4Qvo2bmqnqMYADFk= github.com/spf13/jwalterweatherman v1.1.0/go.mod h1:aNWZUN0dPAAO/Ljvb5BEdw96iTZ0EXowPYD95IqWIGo= @@ -1116,8 +1117,8 @@ golang.org/x/crypto v0.0.0-20210421170649-83a5a9bb288b/go.mod h1:T9bdIzuCu7OtxOm golang.org/x/crypto v0.0.0-20210711020723-a769d52b0f97/go.mod h1:GvvjBRRGRdwPK5ydBHafDWAxML/pGHZbMvKqRZ5+Abc= golang.org/x/crypto v0.0.0-20210921155107-089bfa567519/go.mod h1:GvvjBRRGRdwPK5ydBHafDWAxML/pGHZbMvKqRZ5+Abc= golang.org/x/crypto v0.0.0-20211108221036-ceb1ce70b4fa/go.mod h1:GvvjBRRGRdwPK5ydBHafDWAxML/pGHZbMvKqRZ5+Abc= -golang.org/x/crypto v0.7.0 h1:AvwMYaRytfdeVt3u6mLaxYtErKYjxA2OXjJ1HHq6t3A= -golang.org/x/crypto v0.7.0/go.mod h1:pYwdfH91IfpZVANVyUOhSIPZaFoJGxTFbZhFTx+dXZU= +golang.org/x/crypto v0.8.0 h1:pd9TJtTueMTVQXzk8E2XESSMQDj/U7OUu0PqJqPXQjQ= +golang.org/x/crypto v0.8.0/go.mod h1:mRqEX+O9/h5TFCrQhkgjo2yKi0yYA+9ecGkdQoHrywE= golang.org/x/exp v0.0.0-20190121172915-509febef88a4/go.mod h1:CJ0aWSM057203Lf6IL+f9T1iT9GByDxfZKAQTCR3kQA= golang.org/x/exp v0.0.0-20190306152737-a1d7652674e8/go.mod h1:CJ0aWSM057203Lf6IL+f9T1iT9GByDxfZKAQTCR3kQA= golang.org/x/exp v0.0.0-20190510132918-efd6b22b2522/go.mod h1:ZjyILWgesfNpC6sMxTJOJm9Kp84zZh5NQWvqDGG3Qr8= @@ -1221,8 +1222,8 @@ golang.org/x/net v0.0.0-20220722155237-a158d28d115b/go.mod h1:XRhObCWvk6IyKnWLug golang.org/x/net v0.0.0-20220909164309-bea034e7d591/go.mod h1:YDH+HFinaLZZlnHAfSS6ZXJJ9M9t4Dl22yv3iI2vPwk= golang.org/x/net v0.0.0-20221014081412-f15817d10f9b/go.mod h1:YDH+HFinaLZZlnHAfSS6ZXJJ9M9t4Dl22yv3iI2vPwk= golang.org/x/net v0.1.0/go.mod h1:Cx3nUiGt4eDBEyega/BKRp+/AlGL8hYe7U9odMt2Cco= -golang.org/x/net v0.8.0 h1:Zrh2ngAOFYneWTAIAPethzeaQLuHwhuBkuV6ZiRnUaQ= -golang.org/x/net v0.8.0/go.mod h1:QVkue5JL9kW//ek3r6jTKnTFis1tRmNAW2P1shuFdJc= +golang.org/x/net v0.9.0 h1:aWJ/m6xSmxWBx+V0XRHTlrYrPG56jKsLdTFmsSsCzOM= +golang.org/x/net v0.9.0/go.mod h1:d48xBJpPfHeWQsugry2m+kC02ZBRGRgulfHnEXEuWns= golang.org/x/oauth2 v0.0.0-20180821212333-d2e6202438be/go.mod h1:N/0e6XlmueqKjAGxoOufVs8QHGRruUQn6yWY3a++T0U= golang.org/x/oauth2 v0.0.0-20190226205417-e64efc72b421/go.mod h1:gOpvHmFTYa4IltrdGE7lF6nIHvwfUNPOp7c8zoXwtLw= golang.org/x/oauth2 v0.0.0-20190604053449-0f29369cfe45/go.mod h1:gOpvHmFTYa4IltrdGE7lF6nIHvwfUNPOp7c8zoXwtLw= @@ -1368,13 +1369,14 @@ golang.org/x/sys v0.0.0-20220811171246-fbc7d0a398ab/go.mod h1:oPkhp1MJrh7nUepCBc golang.org/x/sys v0.0.0-20220908164124-27713097b956/go.mod h1:oPkhp1MJrh7nUepCBck5+mAzfO9JrbApNNgaTdGDITg= golang.org/x/sys v0.0.0-20221010170243-090e33056c14/go.mod h1:oPkhp1MJrh7nUepCBck5+mAzfO9JrbApNNgaTdGDITg= golang.org/x/sys v0.1.0/go.mod h1:oPkhp1MJrh7nUepCBck5+mAzfO9JrbApNNgaTdGDITg= -golang.org/x/sys v0.6.0 h1:MVltZSvRTcU2ljQOhs94SXPftV6DCNnZViHeQps87pQ= golang.org/x/sys v0.6.0/go.mod h1:oPkhp1MJrh7nUepCBck5+mAzfO9JrbApNNgaTdGDITg= +golang.org/x/sys v0.7.0 h1:3jlCCIQZPdOYu1h8BkNvLz8Kgwtae2cagcG/VamtZRU= +golang.org/x/sys v0.7.0/go.mod h1:oPkhp1MJrh7nUepCBck5+mAzfO9JrbApNNgaTdGDITg= golang.org/x/term v0.0.0-20201126162022-7de9c90e9dd1/go.mod h1:bj7SfCRtBDWHUb9snDiAeCFNEtKQo2Wmx5Cou7ajbmo= golang.org/x/term v0.0.0-20210927222741-03fcf44c2211/go.mod h1:jbD1KX2456YbFQfuXm/mYQcufACuNUgVhRMnK/tPxf8= golang.org/x/term v0.1.0/go.mod h1:jbD1KX2456YbFQfuXm/mYQcufACuNUgVhRMnK/tPxf8= -golang.org/x/term v0.6.0 h1:clScbb1cHjoCkyRbWwBEUZ5H/tIFu5TAXIqaZD0Gcjw= -golang.org/x/term v0.6.0/go.mod h1:m6U89DPEgQRMq3DNkDClhWw02AUbt2daBVO4cn4Hv9U= +golang.org/x/term v0.7.0 h1:BEvjmm5fURWqcfbSKTdpkDXYBrUS1c0m8agp14W48vQ= +golang.org/x/term v0.7.0/go.mod h1:P32HKFT3hSsZrRxla30E9HqToFYAQPCMs/zFMBUFqPY= golang.org/x/text v0.0.0-20170915032832-14c0d48ead0c/go.mod h1:NqM8EUOU14njkJ3fqMW+pc6Ldnwhi/IjpwHt7yyuwOQ= golang.org/x/text v0.3.0/go.mod h1:NqM8EUOU14njkJ3fqMW+pc6Ldnwhi/IjpwHt7yyuwOQ= golang.org/x/text v0.3.1-0.20180807135948-17ff2d5776d2/go.mod h1:NqM8EUOU14njkJ3fqMW+pc6Ldnwhi/IjpwHt7yyuwOQ= @@ -1385,8 +1387,8 @@ golang.org/x/text v0.3.5/go.mod h1:5Zoc/QRtKVWzQhOtBMvqHzDpF6irO9z98xDceosuGiQ= golang.org/x/text v0.3.6/go.mod h1:5Zoc/QRtKVWzQhOtBMvqHzDpF6irO9z98xDceosuGiQ= golang.org/x/text v0.3.7/go.mod h1:u+2+/6zg+i71rQMx5EYifcz6MCKuco9NR6JIITiCfzQ= golang.org/x/text v0.4.0/go.mod h1:mrYo+phRRbMaCq/xk9113O4dZlRixOauAjOtrjsXDZ8= -golang.org/x/text v0.8.0 h1:57P1ETyNKtuIjB4SRd15iJxuhj8Gc416Y78H3qgMh68= -golang.org/x/text v0.8.0/go.mod h1:e1OnstbJyHTd6l/uOt8jFFHp6TRDWZR/bV3emEE/zU8= +golang.org/x/text v0.9.0 h1:2sjJmO8cDvYveuX97RDLsxlyUxLl+GHoLxBiRdHllBE= +golang.org/x/text v0.9.0/go.mod h1:e1OnstbJyHTd6l/uOt8jFFHp6TRDWZR/bV3emEE/zU8= golang.org/x/time v0.0.0-20180412165947-fbb02b2291d2/go.mod h1:tRJNPiyCQ0inRvYxbN9jk5I+vvW/OXSQhTDSoE431IQ= golang.org/x/time v0.0.0-20181108054448-85acf8d2951c/go.mod h1:tRJNPiyCQ0inRvYxbN9jk5I+vvW/OXSQhTDSoE431IQ= golang.org/x/time v0.0.0-20190308202827-9d24e82272b4/go.mod h1:tRJNPiyCQ0inRvYxbN9jk5I+vvW/OXSQhTDSoE431IQ= @@ -1637,8 +1639,8 @@ google.golang.org/genproto v0.0.0-20221010155953-15ba04fc1c0e/go.mod h1:3526vdqw google.golang.org/genproto v0.0.0-20221014173430-6e2ab493f96b/go.mod h1:1vXfmgAz9N9Jx0QA82PqRVauvCz1SGSz739p0f183jM= google.golang.org/genproto v0.0.0-20221014213838-99cd37c6964a/go.mod h1:1vXfmgAz9N9Jx0QA82PqRVauvCz1SGSz739p0f183jM= google.golang.org/genproto v0.0.0-20221025140454-527a21cfbd71/go.mod h1:9qHF0xnpdSfF6knlcsnpzUu5y+rpwgbvsyGAZPBMg4s= -google.golang.org/genproto v0.0.0-20230320184635-7606e756e683 h1:khxVcsk/FhnzxMKOyD+TDGwjbEOpcPuIpmafPGFmhMA= -google.golang.org/genproto v0.0.0-20230320184635-7606e756e683/go.mod h1:NWraEVixdDnqcqQ30jipen1STv2r/n24Wb7twVTGR4s= +google.golang.org/genproto v0.0.0-20230410155749-daa745c078e1 h1:KpwkzHKEF7B9Zxg18WzOa7djJ+Ha5DzthMyZYQfEn2A= +google.golang.org/genproto v0.0.0-20230410155749-daa745c078e1/go.mod h1:nKE/iIaLqn2bQwXBg8f1g2Ylh6r5MN5CmZvuzZCgsCU= google.golang.org/grpc v1.12.0/go.mod h1:yo6s7OP7yaDglbqo1J04qKzAhqBH6lvTonzMVmEdcZw= google.golang.org/grpc v1.17.0/go.mod h1:6QZJwpn2B+Zp71q/5VxRsJ6NXXVCE5NRUHRo+f3cWCs= google.golang.org/grpc v1.19.0/go.mod h1:mqu4LbDTu4XGKhr4mRzUsmM4RtVoemTSY81AxZiDr8c= diff --git a/x/upgrade/internal/conv/string_test.go b/x/upgrade/internal/conv/string_test.go index 484d0a31ea62..dfaaa038cbd8 100644 --- a/x/upgrade/internal/conv/string_test.go +++ b/x/upgrade/internal/conv/string_test.go @@ -26,7 +26,7 @@ func (s *StringSuite) TestUnsafeStrToBytes() { b := unsafeConvertStr() runtime.GC() <-time.NewTimer(2 * time.Millisecond).C - b2 := append(b, 'd') //nolint:gocritic // append is fine here + b2 := append(b, 'd') s.Equal("abc", string(b)) s.Equal("abcd", string(b2)) } diff --git a/x/upgrade/keeper/grpc_query.go b/x/upgrade/keeper/grpc_query.go index ba042693d96e..d0c30c36423e 100644 --- a/x/upgrade/keeper/grpc_query.go +++ b/x/upgrade/keeper/grpc_query.go @@ -37,17 +37,15 @@ func (k Keeper) AppliedPlan(c context.Context, req *types.QueryAppliedPlanReques } // UpgradedConsensusState implements the Query/UpgradedConsensusState gRPC method -// -//nolint:staticcheck -func (k Keeper) UpgradedConsensusState(c context.Context, req *types.QueryUpgradedConsensusStateRequest) (*types.QueryUpgradedConsensusStateResponse, error) { +func (k Keeper) UpgradedConsensusState(c context.Context, req *types.QueryUpgradedConsensusStateRequest) (*types.QueryUpgradedConsensusStateResponse, error) { //nolint:staticcheck // we're using a deprecated call for compatibility ctx := sdk.UnwrapSDKContext(c) consState, found := k.GetUpgradedConsensusState(ctx, req.LastHeight) if !found { - return &types.QueryUpgradedConsensusStateResponse{}, nil + return &types.QueryUpgradedConsensusStateResponse{}, nil //nolint:staticcheck // we're using a deprecated call for compatibility } - return &types.QueryUpgradedConsensusStateResponse{ + return &types.QueryUpgradedConsensusStateResponse{ //nolint:staticcheck // we're using a deprecated call for compatibility UpgradedConsensusState: consState, }, nil } diff --git a/x/upgrade/keeper/keeper.go b/x/upgrade/keeper/keeper.go index f4ac2d612c07..143f8225fd5e 100644 --- a/x/upgrade/keeper/keeper.go +++ b/x/upgrade/keeper/keeper.go @@ -8,6 +8,7 @@ import ( "path" "path/filepath" "sort" + "strconv" errorsmod "cosmossdk.io/errors" "cosmossdk.io/log" @@ -16,7 +17,9 @@ import ( xp "cosmossdk.io/x/upgrade/exported" "cosmossdk.io/x/upgrade/types" + "github.com/armon/go-metrics" "github.com/cosmos/cosmos-sdk/codec" + "github.com/cosmos/cosmos-sdk/telemetry" sdk "github.com/cosmos/cosmos-sdk/types" sdkerrors "github.com/cosmos/cosmos-sdk/types/errors" "github.com/cosmos/cosmos-sdk/types/kv" @@ -35,7 +38,7 @@ type Keeper struct { upgradeHandlers map[string]types.UpgradeHandler // map of plan name to upgrade handler versionSetter xp.ProtocolVersionSetter // implements setting the protocol version field on BaseApp downgradeVerified bool // tells if we've already sanity checked that this binary version isn't being used against an old state. - authority string // the address capable of executing and cancelling an upgrade. Usually the gov module account + authority string // the address capable of executing and canceling an upgrade. Usually the gov module account initVersionMap module.VersionMap // the module version map at init genesis } @@ -46,7 +49,7 @@ type Keeper struct { // homePath - root directory of the application's config // vs - the interface implemented by baseapp which allows setting baseapp's protocol version field func NewKeeper(skipUpgradeHeights map[int64]bool, storeKey storetypes.StoreKey, cdc codec.BinaryCodec, homePath string, vs xp.ProtocolVersionSetter, authority string) *Keeper { - return &Keeper{ + k := &Keeper{ homePath: homePath, skipUpgradeHeights: skipUpgradeHeights, storeKey: storeKey, @@ -55,6 +58,12 @@ func NewKeeper(skipUpgradeHeights map[int64]bool, storeKey storetypes.StoreKey, versionSetter: vs, authority: authority, } + + if upgradePlan, err := k.ReadUpgradeInfoFromDisk(); err == nil && upgradePlan.Height > 0 { + telemetry.SetGaugeWithLabels([]string{"server", "info"}, 1, []metrics.Label{telemetry.NewLabel("upgrade_height", strconv.FormatInt(upgradePlan.Height, 10))}) + } + + return k } // SetVersionSetter sets the interface implemented by baseapp which allows setting baseapp's protocol version field @@ -217,6 +226,8 @@ func (k Keeper) ScheduleUpgrade(ctx sdk.Context, plan types.Plan) error { bz := k.cdc.MustMarshal(&plan) store.Set(types.PlanKey(), bz) + telemetry.SetGaugeWithLabels([]string{"server", "info"}, 1, []metrics.Label{telemetry.NewLabel("upgrade_height", strconv.FormatInt(plan.Height, 10))}) + return nil } diff --git a/x/upgrade/keeper/keeper_test.go b/x/upgrade/keeper/keeper_test.go index eed7f80ab3e7..0e699806d18b 100644 --- a/x/upgrade/keeper/keeper_test.go +++ b/x/upgrade/keeper/keeper_test.go @@ -280,7 +280,7 @@ func (s *KeeperTestSuite) TestMigrations() { vmBefore := s.upgradeKeeper.GetModuleVersionMap(s.ctx) s.upgradeKeeper.SetUpgradeHandler("dummy", func(_ sdk.Context, _ types.Plan, vm module.VersionMap) (module.VersionMap, error) { // simulate upgrading the bank module - vm["bank"] = vm["bank"] + 1 //nolint:gocritic + vm["bank"]++ return vm, nil }) dummyPlan := types.Plan{ diff --git a/x/upgrade/keeper/msg_server.go b/x/upgrade/keeper/msg_server.go index ade16ce586c5..dcf5900b6e24 100644 --- a/x/upgrade/keeper/msg_server.go +++ b/x/upgrade/keeper/msg_server.go @@ -25,13 +25,17 @@ func NewMsgServerImpl(k *Keeper) types.MsgServer { var _ types.MsgServer = msgServer{} // SoftwareUpgrade implements the Msg/SoftwareUpgrade Msg service. -func (k msgServer) SoftwareUpgrade(goCtx context.Context, req *types.MsgSoftwareUpgrade) (*types.MsgSoftwareUpgradeResponse, error) { - if k.authority != req.Authority { - return nil, errors.Wrapf(gov.ErrInvalidSigner, "expected %s got %s", k.authority, req.Authority) +func (k msgServer) SoftwareUpgrade(goCtx context.Context, msg *types.MsgSoftwareUpgrade) (*types.MsgSoftwareUpgradeResponse, error) { + if k.authority != msg.Authority { + return nil, errors.Wrapf(gov.ErrInvalidSigner, "expected %s got %s", k.authority, msg.Authority) + } + + if err := msg.Plan.ValidateBasic(); err != nil { + return nil, errors.Wrap(err, "plan") } ctx := sdk.UnwrapSDKContext(goCtx) - err := k.ScheduleUpgrade(ctx, req.Plan) + err := k.ScheduleUpgrade(ctx, msg.Plan) if err != nil { return nil, err } @@ -40,13 +44,13 @@ func (k msgServer) SoftwareUpgrade(goCtx context.Context, req *types.MsgSoftware } // CancelUpgrade implements the Msg/CancelUpgrade Msg service. -func (k msgServer) CancelUpgrade(goCtx context.Context, req *types.MsgCancelUpgrade) (*types.MsgCancelUpgradeResponse, error) { - if k.authority != req.Authority { - return nil, errors.Wrapf(gov.ErrInvalidSigner, "expected %s got %s", k.authority, req.Authority) +func (k msgServer) CancelUpgrade(ctx context.Context, msg *types.MsgCancelUpgrade) (*types.MsgCancelUpgradeResponse, error) { + if k.authority != msg.Authority { + return nil, errors.Wrapf(gov.ErrInvalidSigner, "expected %s got %s", k.authority, msg.Authority) } - ctx := sdk.UnwrapSDKContext(goCtx) - k.ClearUpgradePlan(ctx) + sdkCtx := sdk.UnwrapSDKContext(ctx) + k.ClearUpgradePlan(sdkCtx) return &types.MsgCancelUpgradeResponse{}, nil } diff --git a/x/upgrade/keeper/msg_server_test.go b/x/upgrade/keeper/msg_server_test.go index 6833d7e3c580..aba54c5cd8dc 100644 --- a/x/upgrade/keeper/msg_server_test.go +++ b/x/upgrade/keeper/msg_server_test.go @@ -15,6 +15,18 @@ func (s *KeeperTestSuite) TestSoftwareUpgrade() { expectErr bool errMsg string }{ + { + "invalid authority address", + &types.MsgSoftwareUpgrade{ + Authority: "authority", + Plan: types.Plan{ + Name: "all-good", + Height: 123450000, + }, + }, + true, + "expected gov account as only signer for proposal message", + }, { "unauthorized authority address", &types.MsgSoftwareUpgrade{ @@ -85,6 +97,14 @@ func (s *KeeperTestSuite) TestCancelUpgrade() { expectErr bool errMsg string }{ + { + "invalid authority address", + &types.MsgCancelUpgrade{ + Authority: "authority", + }, + true, + "expected gov account as only signer for proposal message", + }, { "unauthorized authority address", &types.MsgCancelUpgrade{ @@ -94,7 +114,7 @@ func (s *KeeperTestSuite) TestCancelUpgrade() { "expected gov account as only signer for proposal message", }, { - "upgrade cancelled successfully", + "upgrade canceled successfully", &types.MsgCancelUpgrade{ Authority: govAccAddr, }, diff --git a/x/upgrade/module.go b/x/upgrade/module.go index ba20b20bf6c2..77938040fbf3 100644 --- a/x/upgrade/module.go +++ b/x/upgrade/module.go @@ -11,6 +11,7 @@ import ( "github.com/spf13/cobra" modulev1 "cosmossdk.io/api/cosmos/upgrade/module/v1" + "cosmossdk.io/core/address" "cosmossdk.io/core/appmodule" "cosmossdk.io/depinject" @@ -44,7 +45,9 @@ const ConsensusVersion uint64 = 2 var _ module.AppModuleBasic = AppModuleBasic{} // AppModuleBasic implements the sdk.AppModuleBasic interface -type AppModuleBasic struct{} +type AppModuleBasic struct { + ac address.Codec +} // Name returns the ModuleName func (AppModuleBasic) Name() string { @@ -69,12 +72,12 @@ func (AppModuleBasic) GetQueryCmd() *cobra.Command { } // GetTxCmd returns the CLI transaction commands for this module -func (AppModuleBasic) GetTxCmd() *cobra.Command { - return cli.GetTxCmd() +func (ab AppModuleBasic) GetTxCmd() *cobra.Command { + return cli.GetTxCmd(ab.ac) } // RegisterInterfaces registers interfaces and implementations of the upgrade module. -func (b AppModuleBasic) RegisterInterfaces(registry codectypes.InterfaceRegistry) { +func (AppModuleBasic) RegisterInterfaces(registry codectypes.InterfaceRegistry) { types.RegisterInterfaces(registry) } @@ -85,9 +88,9 @@ type AppModule struct { } // NewAppModule creates a new AppModule object -func NewAppModule(keeper *keeper.Keeper) AppModule { +func NewAppModule(keeper *keeper.Keeper, ac address.Codec) AppModule { return AppModule{ - AppModuleBasic: AppModuleBasic{}, + AppModuleBasic: AppModuleBasic{ac: ac}, keeper: keeper, } } @@ -171,19 +174,18 @@ func init() { ) } -//nolint:revive -type UpgradeInputs struct { +type ModuleInputs struct { depinject.In - Config *modulev1.Module - Key *store.KVStoreKey - Cdc codec.Codec + Config *modulev1.Module + Key *store.KVStoreKey + Cdc codec.Codec + AddressCodec address.Codec AppOpts servertypes.AppOptions `optional:"true"` } -//nolint:revive -type UpgradeOutputs struct { +type ModuleOutputs struct { depinject.Out UpgradeKeeper *keeper.Keeper @@ -192,7 +194,7 @@ type UpgradeOutputs struct { BaseAppOption runtime.BaseAppOption } -func ProvideModule(in UpgradeInputs) UpgradeOutputs { +func ProvideModule(in ModuleInputs) ModuleOutputs { var ( homePath string skipUpgradeHeights = make(map[int64]bool) @@ -217,10 +219,10 @@ func ProvideModule(in UpgradeInputs) UpgradeOutputs { baseappOpt := func(app *baseapp.BaseApp) { k.SetVersionSetter(app) } - m := NewAppModule(k) + m := NewAppModule(k, in.AddressCodec) gh := govv1beta1.HandlerRoute{RouteKey: types.RouterKey, Handler: NewSoftwareUpgradeProposalHandler(k)} - return UpgradeOutputs{UpgradeKeeper: k, Module: m, GovHandler: gh, BaseAppOption: baseappOpt} + return ModuleOutputs{UpgradeKeeper: k, Module: m, GovHandler: gh, BaseAppOption: baseappOpt} } func PopulateVersionMap(upgradeKeeper *keeper.Keeper, modules map[string]appmodule.AppModule) { diff --git a/x/upgrade/plan/downloader_test.go b/x/upgrade/plan/downloader_test.go index 7a48275ef687..ef0f727550ab 100644 --- a/x/upgrade/plan/downloader_test.go +++ b/x/upgrade/plan/downloader_test.go @@ -65,9 +65,7 @@ type TestZip []*TestFile func NewTestZip(testFiles ...*TestFile) TestZip { tz := make([]*TestFile, len(testFiles)) - for i, tf := range testFiles { //nolint:gosimple - tz[i] = tf - } + copy(tz, testFiles) return tz } diff --git a/x/upgrade/types/msgs.go b/x/upgrade/types/msgs.go index 8a8c92c7a806..f53c8576e4dc 100644 --- a/x/upgrade/types/msgs.go +++ b/x/upgrade/types/msgs.go @@ -1,8 +1,6 @@ package types import ( - errorsmod "cosmossdk.io/errors" - sdk "github.com/cosmos/cosmos-sdk/types" "github.com/cosmos/cosmos-sdk/x/auth/migrations/legacytx" ) @@ -17,19 +15,6 @@ func (m MsgSoftwareUpgrade) GetSignBytes() []byte { return sdk.MustSortJSON(ModuleCdc.MustMarshalJSON(&m)) } -// ValidateBasic does a sanity check on the provided data. -func (m *MsgSoftwareUpgrade) ValidateBasic() error { - if _, err := sdk.AccAddressFromBech32(m.Authority); err != nil { - return errorsmod.Wrap(err, "authority") - } - - if err := m.Plan.ValidateBasic(); err != nil { - return errorsmod.Wrap(err, "plan") - } - - return nil -} - // GetSigners returns the expected signers for MsgSoftwareUpgrade. func (m *MsgSoftwareUpgrade) GetSigners() []sdk.AccAddress { addr, _ := sdk.AccAddressFromBech32(m.Authority) @@ -41,15 +26,6 @@ func (m MsgCancelUpgrade) GetSignBytes() []byte { return sdk.MustSortJSON(ModuleCdc.MustMarshalJSON(&m)) } -// ValidateBasic does a sanity check on the provided data. -func (m *MsgCancelUpgrade) ValidateBasic() error { - if _, err := sdk.AccAddressFromBech32(m.Authority); err != nil { - return errorsmod.Wrap(err, "authority") - } - - return nil -} - // GetSigners returns the expected signers for MsgCancelUpgrade. func (m *MsgCancelUpgrade) GetSigners() []sdk.AccAddress { addr, _ := sdk.AccAddressFromBech32(m.Authority) diff --git a/x/upgrade/types/msgs_test.go b/x/upgrade/types/msgs_test.go deleted file mode 100644 index 52646943f617..000000000000 --- a/x/upgrade/types/msgs_test.go +++ /dev/null @@ -1,108 +0,0 @@ -package types_test - -import ( - "testing" - - "github.com/stretchr/testify/require" - - "cosmossdk.io/x/upgrade/types" - - sdk "github.com/cosmos/cosmos-sdk/types" -) - -var authority = sdk.AccAddress("authority") - -func TestMsgSoftwareUpgrade(t *testing.T) { - testCases := []struct { - name string - msg *types.MsgSoftwareUpgrade - expErr bool - errMsg string - }{ - { - "invalid authority address", - &types.MsgSoftwareUpgrade{ - Authority: "authority", - Plan: types.Plan{ - Name: "all-good", - Height: 123450000, - }, - }, - true, - "authority: decoding bech32 failed", - }, - { - "invalid plan", - &types.MsgSoftwareUpgrade{ - Authority: authority.String(), - Plan: types.Plan{ - Height: 123450000, - }, - }, - true, - "plan", - }, - { - "all good", - &types.MsgSoftwareUpgrade{ - Authority: authority.String(), - Plan: types.Plan{ - Name: "all-good", - Height: 123450000, - }, - }, - false, - "", - }, - } - - for _, tc := range testCases { - t.Run(tc.name, func(t *testing.T) { - err := tc.msg.ValidateBasic() - if tc.expErr { - require.Error(t, err) - require.Contains(t, err.Error(), tc.errMsg) - } else { - require.NoError(t, err) - } - }) - } -} - -func TestMsgCancelUpgrade(t *testing.T) { - testCases := []struct { - name string - msg *types.MsgCancelUpgrade - expErr bool - errMsg string - }{ - { - "invalid authority address", - &types.MsgCancelUpgrade{ - Authority: "authority", - }, - true, - "authority: decoding bech32 failed", - }, - { - "all good", - &types.MsgCancelUpgrade{ - Authority: authority.String(), - }, - false, - "", - }, - } - - for _, tc := range testCases { - t.Run(tc.name, func(t *testing.T) { - err := tc.msg.ValidateBasic() - if tc.expErr { - require.Error(t, err) - require.Contains(t, err.Error(), tc.errMsg) - } else { - require.NoError(t, err) - } - }) - } -} diff --git a/x/upgrade/types/storeloader_test.go b/x/upgrade/types/storeloader_test.go index 26926a4e0be2..cb9b678b0b56 100644 --- a/x/upgrade/types/storeloader_test.go +++ b/x/upgrade/types/storeloader_test.go @@ -74,7 +74,7 @@ func TestSetLoader(t *testing.T) { data, err := json.Marshal(upgradeInfo) require.NoError(t, err) - err = os.WriteFile(upgradeInfoFilePath, data, 0o644) //nolint:gosec + err = os.WriteFile(upgradeInfoFilePath, data, 0o600) require.NoError(t, err) // make sure it exists before running everything