diff --git a/.changelog/unreleased/features/provider/2211-deprecate-migration.md b/.changelog/unreleased/features/provider/2211-deprecate-migration.md new file mode 100644 index 0000000000..2363098b91 --- /dev/null +++ b/.changelog/unreleased/features/provider/2211-deprecate-migration.md @@ -0,0 +1,4 @@ +- Remove provider migrations to consensus versions lower than 7. + To migrate the provider module from consensus version 3, 4, or 5 to consensus version 7 or higher, + users should use v4.3.x in production to migrate to consensus version 6. + ([\#2211](https://github.com/cosmos/interchain-security/pull/2211)) \ No newline at end of file diff --git a/Makefile b/Makefile index 1e8eb8e5bc..ec2493c9b4 100644 --- a/Makefile +++ b/Makefile @@ -33,8 +33,8 @@ install: go.sum go install -ldflags "$(democracyFlags)" ./cmd/interchain-security-cdd go install -ldflags "$(standaloneFlags)" ./cmd/interchain-security-sd -# run all tests: unit, integration, diff, and E2E -test: test-unit test-integration test-mbt test-e2e +# run all tests: unit, integration, and E2E +test: test-unit test-integration test-e2e # shortcut for local development test-dev: test-unit test-integration test-mbt @@ -271,4 +271,4 @@ build-docs-local: ############################################################################### e2e-traces: - cd tests/e2e; go test -timeout 30s -run ^TestWriteExamples -v \ No newline at end of file + cd tests/e2e; go test -timeout 30s -run ^TestWriteExamples -v diff --git a/docs/docs/adrs/adr-019-permissionless-ics.md b/docs/docs/adrs/adr-019-permissionless-ics.md index 59b13659a4..70273ee2f3 100644 --- a/docs/docs/adrs/adr-019-permissionless-ics.md +++ b/docs/docs/adrs/adr-019-permissionless-ics.md @@ -95,8 +95,7 @@ consumer chains with the exact same `chainId`, and it is the responsibility of t to interact with by providing the right `consumerId`. Note that with Permissionless ICS, all interactions on a consumer chain have to use the `consumerId` instead of the `chainId`. -For example, if a validator opts in on a chain using `MsgOptIn`, the validator has to provide the `consumerId`. To also -provide the `consumerId` for Top N consumers chains, we store a mapping between `proposalID` to `consumerId`. This storing +For example, if a validator opts in on a chain using `MsgOptIn`, the validator has to provide the `consumerId`. To also provide the `consumerId` for Top N consumers chains, we store a mapping between `proposalID` to `consumerId`. This storing takes place in the [`AfterProposalSubmission`](https://github.com/cosmos/cosmos-sdk/blob/v0.50.8/x/gov/types/hooks.go#L19) hook. Specifically, for the equivocation evidence, we update the `MsgSubmitConsumerMisbehaviour` and `MsgSubmitConsumerDoubleVoting` messages to include the `consumerId`, and change [Hermes](https://github.com/informalsystems/hermes) to include `consumerId` in those constructed messages as well. @@ -161,9 +160,9 @@ where `ConsumerRegistrationRecord` contains information about the to-be-launched ```protobuf message ConsumerRegistrationRecord { - // the title of the chain to-be-launched + // the title of the chain to-be-registered string title; - // the description of the chain to-be-launched + // the description of the chain to-be-registered string description; // the chain id of the new consumer chain string chain_id; @@ -183,7 +182,7 @@ To move an Opt In consumer chain to its initialized phase, we issue a `MsgInitia ```protobuf message MsgInitializeConsumer { - // consumer id of the to-be-updated consumer chain + // consumer id of the to-be-initialized consumer chain string consumer_id; // the initialization record that contains initialization parameters for the upcoming chain ConsumerInitializationRecord initialization_record; @@ -332,6 +331,9 @@ Because we only have two consumer chains at the moment, this is not going to be consumer chains that are being voted upon. Similarly, all the messages, queries, etc. would need to be changed to operate on a `consumerId` instead of a `chainId`. +To prevent a validator from accidentally opting in to a wrong chain, we disallow a validator from opting in to two or more +different chains (different `consumerId`) with the same `chainId`. + It is **important** to migrate any ongoing `ConsumerAdditionProposal`s when we upgrade before we actually deprecate `ConsumerAdditionProposal`s. ## Consequences diff --git a/proto/interchain_security/ccv/provider/v1/genesis.proto b/proto/interchain_security/ccv/provider/v1/genesis.proto index 34c0daf633..0f212b0271 100644 --- a/proto/interchain_security/ccv/provider/v1/genesis.proto +++ b/proto/interchain_security/ccv/provider/v1/genesis.proto @@ -17,6 +17,12 @@ message GenesisState { // Reserve 4th slot for removed mature_unbonding_ops field reserved 4; + // Reserve 6th slot for removed consumer_addition_proposals field + reserved 6; + + // Reserve 7th slot for removed consumer_removal_proposals field + reserved 7; + // Reserve 11th slot for consumer_addrs_to_prune field reserved 11; @@ -36,12 +42,6 @@ message GenesisState { // empty for a new chain repeated ValsetUpdateIdToHeight valset_update_id_to_height = 5 [ (gogoproto.nullable) = false ]; - // empty for a new chain - repeated ConsumerAdditionProposal consumer_addition_proposals = 6 - [ (gogoproto.nullable) = false ]; - // empty for a new chain - repeated ConsumerRemovalProposal consumer_removal_proposals = 7 - [ (gogoproto.nullable) = false ]; Params params = 8 [ (gogoproto.nullable) = false ]; // empty for a new chain repeated ValidatorConsumerPubKey validator_consumer_pubkeys = 9 @@ -78,6 +78,8 @@ message ConsumerState { repeated interchain_security.ccv.v1.ValidatorSetChangePacketData pending_valset_changes = 6 [ (gogoproto.nullable) = false ]; repeated string slash_downtime_ack = 7; + // the phase of the consumer chain + ConsumerPhase phase = 9; } // ValsetUpdateIdToHeight defines the genesis information for the mapping diff --git a/proto/interchain_security/ccv/provider/v1/provider.proto b/proto/interchain_security/ccv/provider/v1/provider.proto index 7e1836cf38..f1af229759 100644 --- a/proto/interchain_security/ccv/provider/v1/provider.proto +++ b/proto/interchain_security/ccv/provider/v1/provider.proto @@ -21,6 +21,7 @@ import "amino/amino.proto"; // These schemas can change with proper consideration of compatibility or migration. // +// WARNING: This message is deprecated in favor of `MsgCreateConsumer`. // ConsumerAdditionProposal is a governance proposal on the provider chain to // spawn a new consumer chain. If it passes, then all validators on the provider // chain are expected to validate the consumer chain at spawn time or get @@ -112,6 +113,7 @@ message ConsumerAdditionProposal { bool allow_inactive_vals = 21; } +// WARNING: This message is deprecated in favor of `MsgRemoveConsumer`. // ConsumerRemovalProposal is a governance proposal on the provider chain to // remove (and stop) a consumer chain. If it passes, all the consumer chain's // state is removed from the provider chain. The outstanding unbonding operation @@ -132,6 +134,7 @@ message ConsumerRemovalProposal { [ (gogoproto.stdtime) = true, (gogoproto.nullable) = false ]; } +// WARNING: This message is deprecated in favor of `MsgUpdateConsumer`. // ConsumerModificationProposal is a governance proposal on the provider chain to modify parameters of a running // consumer chain. If it passes, the consumer chain's state is updated to take into account the newest params. message ConsumerModificationProposal { @@ -285,6 +288,7 @@ message ConsumerRemovalProposals { // AddressList contains a list of consensus addresses message AddressList { repeated bytes addresses = 1; } +// WARNING: This message is deprecated and is not used. // ChannelToChain is used to map a CCV channel ID to the consumer chainID message ChannelToChain { string channel_id = 1; @@ -362,3 +366,122 @@ message ConsumerRewardsAllocation { (gogoproto.castrepeated) = "github.com/cosmos/cosmos-sdk/types.DecCoins" ]; } + +// ConsumerMetadata contains general information about the registered chain +message ConsumerMetadata { + // the name of the chain + string name = 1; + // the description of the chain + string description = 2; + // the metadata (e.g., GitHub repository URL) of the chain + string metadata = 3; +} + +// ConsumerInitializationParameters are the parameters needed to launch a chain +message ConsumerInitializationParameters { + // ---------- ---------- ---------- + // Following fields are used when the consumer chain launches and are not needed by the provider afterwards. + // ---------- ---------- ---------- + + // the proposed initial height of new consumer chain. + // For a completely new chain, this will be {0,1}. However, it may be + // different if this is a chain that is converting to a consumer chain. + ibc.core.client.v1.Height initial_height = 1 [ (gogoproto.nullable) = false ]; + // The hash of the consumer chain genesis state without the consumer CCV + // module genesis params. It is used for off-chain confirmation of + // genesis.json validity by validators and other parties. + bytes genesis_hash = 2; + // The hash of the consumer chain binary that should be run by validators on + // chain initialization. It is used for off-chain confirmation of binary + // validity by validators and other parties. + bytes binary_hash = 3; + // spawn time is the time on the provider chain at which the consumer chain + // genesis is finalized and all validators will be responsible for starting + // their consumer chain validator node. + google.protobuf.Timestamp spawn_time = 4 [ (gogoproto.nullable) = false, (gogoproto.stdtime) = true ]; + // Unbonding period for the consumer, + // which should be smaller than that of the provider in general. + google.protobuf.Duration unbonding_period = 5 [ (gogoproto.nullable) = false, (gogoproto.stdduration) = true ]; + + + // ---------- ---------- ---------- + // Following fields are used to construct the consumer genesis of the to-be-launched consumer chain + // and are set up as params on the consumer chain. Those params can then be directly modified by the consumer chain. + // ---------- ---------- ---------- + + // Sent CCV related IBC packets will timeout after this duration + google.protobuf.Duration ccv_timeout_period = 6 [ (gogoproto.nullable) = false, (gogoproto.stdduration) = true ]; + // Sent transfer related IBC packets will timeout after this duration + google.protobuf.Duration transfer_timeout_period = 7 [ (gogoproto.nullable) = false, (gogoproto.stdduration) = true ]; + // The fraction of tokens allocated to the consumer redistribution address + // during distribution events. The fraction is a string representing a + // decimal number. For example "0.75" would represent 75%. + string consumer_redistribution_fraction = 8; + // BlocksPerDistributionTransmission is the number of blocks between + // ibc-token-transfers from the consumer chain to the provider chain. On + // sending transmission event, `consumer_redistribution_fraction` of the + // accumulated tokens are sent to the consumer redistribution address. + int64 blocks_per_distribution_transmission = 9; + // The number of historical info entries to persist in store. + // This param is a part of the cosmos sdk staking module. In the case of + // a ccv enabled consumer chain, the ccv module acts as the staking module. + int64 historical_entries = 10; + // The ID of a token transfer channel used for the Reward Distribution + // sub-protocol. If DistributionTransmissionChannel == "", a new transfer + // channel is created on top of the same connection as the CCV channel. + // Note that transfer_channel_id is the ID of the channel end on the consumer + // chain. it is most relevant for chains performing a sovereign to consumer + // changeover in order to maintain the existing ibc transfer channel + string distribution_transmission_channel = 11; +} + +// PowerShapingParameters contains parameters that shape the validator set that we send to the consumer chain +message PowerShapingParameters { + // Corresponds to the percentage of validators that have to validate the chain under the Top N case. + // For example, 53 corresponds to a Top 53% chain, meaning that the top 53% provider validators by voting power + // have to validate the proposed consumer chain. top_N can either be 0 or any value in [50, 100]. + // A chain can join with top_N == 0 as an Opt In chain, or with top_N ∈ [50, 100] as a Top N chain. + uint32 top_N = 1; + // Corresponds to the maximum power (percentage-wise) a validator can have on the consumer chain. For instance, if + // `validators_power_cap` is set to 32, it means that no validator can have more than 32% of the voting power on the + // consumer chain. Note that this might not be feasible. For example, think of a consumer chain with only + // 5 validators and with `validators_power_cap` set to 10%. In such a scenario, at least one validator would need + // to have more than 20% of the total voting power. Therefore, `validators_power_cap` operates on a best-effort basis. + uint32 validators_power_cap = 2; + // Corresponds to the maximum number of validators that can validate a consumer chain. + // Only applicable to Opt In chains. Setting `validator_set_cap` on a Top N chain is a no-op. + uint32 validator_set_cap = 3; + // corresponds to a list of provider consensus addresses of validators that are the ONLY ones that can validate the consumer chain + repeated string allowlist = 4; + // corresponds to a list of provider consensus addresses of validators that CANNOT validate the consumer chain + repeated string denylist = 5; + // Corresponds to the minimal amount of (provider chain) stake required to validate on the consumer chain. + uint64 min_stake = 6; + // Corresponds to whether inactive validators are allowed to validate the consumer chain. + bool allow_inactive_vals = 7; +} + +// ConsumerIds contains consumer ids of chains +// Used so we can easily (de)serialize slices of strings +message ConsumerIds { repeated string ids = 1; } + +// ConsumerPhase indicates the phases of a consumer chain according to ADR 019 +enum ConsumerPhase { + option (gogoproto.goproto_enum_prefix) = false; + + // UNSPECIFIED defines an empty phase. + CONSUMER_PHASE_UNSPECIFIED = 0; + // REGISTERED defines the phase in which a consumer chain has been assigned a unique consumer id. + // A chain in this phase cannot yet launch. + CONSUMER_PHASE_REGISTERED = 1; + // INITIALIZED defines the phase in which a consumer chain has set all the needed parameters to launch but + // has not yet launched (e.g., because the `spawnTime` of the consumer chain has not yet been reached). + CONSUMER_PHASE_INITIALIZED = 2; + // LAUNCHED defines the phase in which a consumer chain is running and consuming a subset of the validator + // set of the provider. + CONSUMER_PHASE_LAUNCHED = 3; + // STOPPED defines the phase in which a previously-launched chain has stopped. + CONSUMER_PHASE_STOPPED = 4; + // DELETED defines the phase in which the state of a stopped chain has been deleted. + CONSUMER_PHASE_DELETED = 5; +} diff --git a/proto/interchain_security/ccv/provider/v1/query.proto b/proto/interchain_security/ccv/provider/v1/query.proto index 0ac1baa477..2b2b0dc60e 100644 --- a/proto/interchain_security/ccv/provider/v1/query.proto +++ b/proto/interchain_security/ccv/provider/v1/query.proto @@ -11,14 +11,16 @@ import "interchain_security/ccv/v1/shared_consumer.proto"; import "interchain_security/ccv/v1/wire.proto"; import "tendermint/crypto/keys.proto"; import "cosmos_proto/cosmos.proto"; +import "cosmos/staking/v1beta1/staking.proto"; service Query { // ConsumerGenesis queries the genesis state needed to start a consumer chain // whose proposal has been accepted rpc QueryConsumerGenesis(QueryConsumerGenesisRequest) returns (QueryConsumerGenesisResponse) { - option (google.api.http).get = - "/interchain_security/ccv/provider/consumer_genesis/{chain_id}"; + option (google.api.http) = { + get: "/interchain_security/ccv/provider/consumer_genesis/{consumer_id}"; + }; } // ConsumerChains queries active consumer chains supported by the provider @@ -26,21 +28,7 @@ service Query { rpc QueryConsumerChains(QueryConsumerChainsRequest) returns (QueryConsumerChainsResponse) { option (google.api.http).get = - "/interchain_security/ccv/provider/consumer_chains"; - } - - // QueryConsumerChainStarts queries consumer chain start proposals. - rpc QueryConsumerChainStarts(QueryConsumerChainStartProposalsRequest) - returns (QueryConsumerChainStartProposalsResponse) { - option (google.api.http).get = - "/interchain_security/ccv/provider/consumer_chain_start_proposals"; - } - - // QueryConsumerChainStops queries consumer chain stop proposals. - rpc QueryConsumerChainStops(QueryConsumerChainStopProposalsRequest) - returns (QueryConsumerChainStopProposalsResponse) { - option (google.api.http).get = - "/interchain_security/ccv/provider/consumer_chain_stop_proposals"; + "/interchain_security/ccv/provider/consumer_chains/{phase}/{limit}"; } // QueryValidatorConsumerAddr queries the address @@ -48,7 +36,7 @@ service Query { rpc QueryValidatorConsumerAddr(QueryValidatorConsumerAddrRequest) returns (QueryValidatorConsumerAddrResponse) { option (google.api.http).get = - "/interchain_security/ccv/provider/validator_consumer_addr"; + "/interchain_security/ccv/provider/validator_consumer_addr/{consumer_id}/{provider_address}"; } // QueryProviderAddr returns the provider chain validator @@ -56,7 +44,7 @@ service Query { rpc QueryValidatorProviderAddr(QueryValidatorProviderAddrRequest) returns (QueryValidatorProviderAddrResponse) { option (google.api.http).get = - "/interchain_security/ccv/provider/validator_provider_addr"; + "/interchain_security/ccv/provider/validator_provider_addr/{consumer_id}/{consumer_address}"; } // QueryThrottleState returns the main on-chain state relevant to currently @@ -76,22 +64,14 @@ service Query { "/interchain_security/ccv/provider/registered_consumer_reward_denoms"; } - // QueryProposedConsumerChainIDs returns the chain IDs of the proposed consumer chain addition proposals - // that are still in the voting period - rpc QueryProposedConsumerChainIDs( - QueryProposedChainIDsRequest) - returns (QueryProposedChainIDsResponse) { - option (google.api.http).get = - "/interchain_security/ccv/provider/proposed_consumer_chains"; - } - - // QueryAllPairsValConAddrByConsumerChainID returns a list of pair valconsensus address + // QueryAllPairsValConsAddrByConsumer returns a list of pair valconsensus address // between provider and consumer chain - rpc QueryAllPairsValConAddrByConsumerChainID ( - QueryAllPairsValConAddrByConsumerChainIDRequest) - returns (QueryAllPairsValConAddrByConsumerChainIDResponse) { - option (google.api.http).get = - "/interchain_security/ccv/provider/consumer_chain_id"; + rpc QueryAllPairsValConsAddrByConsumer ( + QueryAllPairsValConsAddrByConsumerRequest) + returns (QueryAllPairsValConsAddrByConsumerResponse) { + option (google.api.http) = { + get: "/interchain_security/ccv/provider/address_pairs/{consumer_id}"; + }; } // QueryParams returns all current values of provider parameters @@ -106,8 +86,9 @@ service Query { rpc QueryConsumerChainOptedInValidators( QueryConsumerChainOptedInValidatorsRequest) returns (QueryConsumerChainOptedInValidatorsResponse) { - option (google.api.http).get = - "/interchain_security/ccv/provider/opted_in_validators/{chain_id}"; + option (google.api.http) = { + get: "/interchain_security/ccv/provider/opted_in_validators/{consumer_id}"; + }; } // QueryConsumerChainsValidatorHasToValidate returns a list of consumer chains @@ -124,17 +105,19 @@ service Query { rpc QueryValidatorConsumerCommissionRate( QueryValidatorConsumerCommissionRateRequest) returns (QueryValidatorConsumerCommissionRateResponse) { - option (google.api.http).get = - "/interchain_security/ccv/provider/consumer_commission_rate/{chain_id}/{provider_address}"; + option (google.api.http) = { + get: "/interchain_security/ccv/provider/consumer_commission_rate/{consumer_id}/{provider_address}"; + }; } - // QueryConsumerValidators returns the latest set consumer-validator set for a given chainID + // QueryConsumerValidators returns the latest set consumer-validator set for a given consumer ID // Note that this does not necessarily mean that the consumer chain is using this validator set at this exact moment // because a VSCPacket could be delayed to be delivered on the consumer chain. rpc QueryConsumerValidators(QueryConsumerValidatorsRequest) returns (QueryConsumerValidatorsResponse) { - option (google.api.http).get = - "/interchain_security/ccv/provider/consumer_validators/{chain_id}"; + option (google.api.http) = { + get: "/interchain_security/ccv/provider/consumer_validators/{consumer_id}"; + }; } // QueryBlocksUntilNextEpoch returns the number of blocks until the next epoch @@ -144,35 +127,47 @@ service Query { option (google.api.http).get = "/interchain_security/ccv/provider/blocks_until_next_epoch"; } + + // QueryConsumerIdFromClientId returns the consumer id of the chain + // associated with the provided client id + rpc QueryConsumerIdFromClientId(QueryConsumerIdFromClientIdRequest) + returns (QueryConsumerIdFromClientIdResponse) { + option (google.api.http).get = + "/interchain_security/ccv/provider/consumer_id/{client_id}"; + } + + // QueryConsumerChain returns the consumer chain + // associated with the provided consumer id + rpc QueryConsumerChain(QueryConsumerChainRequest) + returns (QueryConsumerChainResponse) { + option (google.api.http).get = + "/interchain_security/ccv/provider/consumer_chain/{consumer_id}"; + } } -message QueryConsumerGenesisRequest { string chain_id = 1; } +message QueryConsumerGenesisRequest { + string consumer_id = 1; +} message QueryConsumerGenesisResponse { interchain_security.ccv.v1.ConsumerGenesisState genesis_state = 1 [ (gogoproto.nullable) = false ]; } -message QueryConsumerChainsRequest {} - -message QueryConsumerChainsResponse { repeated Chain chains = 1; } - -message QueryConsumerChainStartProposalsRequest {} - -message QueryConsumerChainStartProposalsResponse { - ConsumerAdditionProposals proposals = 1; +message QueryConsumerChainsRequest { + // The phase of the consumer chains returned (optional) + // Registered=1|Initialized=2|Launched=3|Stopped=4|Deleted=5 + ConsumerPhase phase = 1; + // The limit of consumer chains returned (optional) + // default is 100 + int32 limit = 2; } -message QueryConsumerChainStopProposalsRequest {} - -message QueryConsumerChainStopProposalsResponse { - ConsumerRemovalProposals proposals = 1; -} +message QueryConsumerChainsResponse { repeated Chain chains = 1; } message Chain { string chain_id = 1; string client_id = 2; - // If chain with `chainID` is a Top-N chain, i.e., enforces at least one validator to validate chain `chainID` uint32 top_N = 3; // If the chain is a Top-N chain, this is the minimum power required to be in the top N. // Otherwise, this is -1. @@ -187,20 +182,24 @@ message Chain { repeated string allowlist = 7; // Corresponds to a list of provider consensus addresses of validators that CANNOT validate the consumer chain. repeated string denylist = 8; + // The phase the consumer chain + string phase = 9; + // The metadata of the consumer chain + ConsumerMetadata metadata = 10 [(gogoproto.nullable) = false ]; // Corresponds to the minimal amount of (provider chain) stake required to validate on the consumer chain. - uint64 min_stake = 9; + uint64 min_stake = 11; // Corresponds to whether inactive validators are allowed to validate the consumer chain. - bool allow_inactive_vals = 10; - + bool allow_inactive_vals = 12; + string consumer_id = 13; } message QueryValidatorConsumerAddrRequest { option (gogoproto.equal) = false; option (gogoproto.goproto_getters) = false; - // The id of the consumer chain - string chain_id = 1; // The consensus address of the validator on the provider chain - string provider_address = 2 [ (gogoproto.moretags) = "yaml:\"address\"" ]; + string provider_address = 1 [ (gogoproto.moretags) = "yaml:\"address\"" ]; + // The id of the consumer chain + string consumer_id = 2; } message QueryValidatorConsumerAddrResponse { @@ -211,10 +210,10 @@ message QueryValidatorConsumerAddrResponse { message QueryValidatorProviderAddrRequest { option (gogoproto.equal) = false; option (gogoproto.goproto_getters) = false; - // The id of the provider chain - string chain_id = 1; // The consensus address of the validator on the consumer chain - string consumer_address = 2 [ (gogoproto.moretags) = "yaml:\"address\"" ]; + string consumer_address = 1 [ (gogoproto.moretags) = "yaml:\"address\"" ]; + // The id of the consumer chain + string consumer_id = 2; } message QueryValidatorProviderAddrResponse { @@ -242,24 +241,12 @@ message QueryRegisteredConsumerRewardDenomsResponse { repeated string denoms = 1; } -message QueryProposedChainIDsRequest {} - -message QueryProposedChainIDsResponse { - repeated ProposedChain proposedChains = 1 - [ (gogoproto.nullable) = false ]; -} - -message ProposedChain { - string chainID = 1; - uint64 proposalID = 2; -} - -message QueryAllPairsValConAddrByConsumerChainIDRequest { +message QueryAllPairsValConsAddrByConsumerRequest { // The id of the consumer chain - string chain_id = 1; + string consumer_id = 1; } -message QueryAllPairsValConAddrByConsumerChainIDResponse { +message QueryAllPairsValConsAddrByConsumerResponse { repeated PairValConAddrProviderAndConsumer pair_val_con_addr = 1; } @@ -278,7 +265,7 @@ message QueryParamsResponse { } message QueryConsumerChainOptedInValidatorsRequest { - string chain_id = 1; + string consumer_id = 1; } message QueryConsumerChainOptedInValidatorsResponse { @@ -287,7 +274,7 @@ message QueryConsumerChainOptedInValidatorsResponse { } message QueryConsumerValidatorsRequest { - string chain_id = 1; + string consumer_id = 1; } message QueryConsumerValidatorsValidator { @@ -295,13 +282,44 @@ message QueryConsumerValidatorsValidator { string provider_address = 1 [ (gogoproto.moretags) = "yaml:\"address\"" ]; // The consumer public key of the validator used on the consumer chain tendermint.crypto.PublicKey consumer_key = 2; + // [DEPRECATED] use `consumer_power` instead + int64 power = 3 [deprecated = true]; + + // [DEPRECATED] use `consumer_commission_rate` instead + string rate = 4 [ deprecated = true, + (gogoproto.customtype) = "cosmossdk.io/math.LegacyDec", + (gogoproto.nullable) = false + ]; // The power of the validator used on the consumer chain - int64 power = 3; + int64 consumer_power = 5; // The rate to charge delegators on the consumer chain, as a fraction - string rate = 4 [ + string consumer_commission_rate = 6 [ (gogoproto.customtype) = "cosmossdk.io/math.LegacyDec", (gogoproto.nullable) = false ]; + // The rate to charge delegators on the provider chain, as a fraction + string provider_commission_rate = 7 [ + (gogoproto.customtype) = "cosmossdk.io/math.LegacyDec", + (gogoproto.nullable) = false + ]; + // description defines the description terms for the validator + cosmos.staking.v1beta1.Description description = 8 [(gogoproto.nullable) = false]; + // provider_operator_address defines the address of the validator's operator + string provider_operator_address = 9 [(cosmos_proto.scalar) = "cosmos.ValidatorAddressString"]; + // jailed defined whether the validator has been jailed from bonded status or not. + bool jailed = 10; + // status is the validator status (bonded/unbonding/unbonded). + cosmos.staking.v1beta1.BondStatus status = 11; + // provider_tokens defines the delegated tokens (incl. self-delegation). + string provider_tokens = 12 [ + (cosmos_proto.scalar) = "cosmos.Int", + (gogoproto.customtype) = "cosmossdk.io/math.Int", + (gogoproto.nullable) = false + ]; + // The power of the validator used on the provider chain + int64 provider_power = 13; + // validates_current_epoch defines whether the validator has to validate for the current epoch or not + bool validates_current_epoch = 14; } message QueryConsumerValidatorsResponse { @@ -314,12 +332,12 @@ message QueryConsumerChainsValidatorHasToValidateRequest { } message QueryConsumerChainsValidatorHasToValidateResponse { - repeated string consumer_chain_ids = 1; + repeated string consumer_ids = 1; } message QueryValidatorConsumerCommissionRateRequest { - string chain_id = 1; - // The consensus address of the validator on the provider chain + string consumer_id = 1; + // The consensus address of the validator on the provider chain string provider_address = 2 [ (gogoproto.moretags) = "yaml:\"address\"" ]; } @@ -337,3 +355,27 @@ message QueryBlocksUntilNextEpochResponse { // The number of blocks until the next epoch starts uint64 blocks_until_next_epoch = 1; } + +message QueryConsumerIdFromClientIdRequest { + // the client id (on the provider) that is tracking the consumer chain + // the client id can be found from the consumer chain by querying (i.e., `query ccvconsumer provider-info`) + string client_id = 1; +} + +message QueryConsumerIdFromClientIdResponse { + // the consumer id of the chain associated with this client id + string consumer_id = 1; +} + +message QueryConsumerChainRequest { + string consumer_id = 1; +} + +message QueryConsumerChainResponse { + string chain_id = 1; + string owner_address = 2; + string phase = 3; + ConsumerMetadata metadata = 4 [ (gogoproto.nullable) = false ]; + ConsumerInitializationParameters init_params = 5; + PowerShapingParameters power_shaping_params = 6; +} diff --git a/proto/interchain_security/ccv/provider/v1/tx.proto b/proto/interchain_security/ccv/provider/v1/tx.proto index 113923b11c..d4f4eace11 100644 --- a/proto/interchain_security/ccv/provider/v1/tx.proto +++ b/proto/interchain_security/ccv/provider/v1/tx.proto @@ -23,25 +23,34 @@ service Msg { rpc AssignConsumerKey(MsgAssignConsumerKey) returns (MsgAssignConsumerKeyResponse); rpc SubmitConsumerMisbehaviour(MsgSubmitConsumerMisbehaviour) returns (MsgSubmitConsumerMisbehaviourResponse); rpc SubmitConsumerDoubleVoting(MsgSubmitConsumerDoubleVoting) returns (MsgSubmitConsumerDoubleVotingResponse); - rpc ConsumerAddition(MsgConsumerAddition) returns (MsgConsumerAdditionResponse); - rpc ConsumerRemoval(MsgConsumerRemoval) returns (MsgConsumerRemovalResponse); + rpc ConsumerAddition(MsgConsumerAddition) returns (MsgConsumerAdditionResponse) { + option deprecated = true; + }; + rpc ConsumerRemoval(MsgConsumerRemoval) returns (MsgConsumerRemovalResponse) { + option deprecated = true; + }; + rpc CreateConsumer(MsgCreateConsumer) returns (MsgCreateConsumerResponse); + rpc UpdateConsumer(MsgUpdateConsumer) returns (MsgUpdateConsumerResponse); + rpc RemoveConsumer(MsgRemoveConsumer) returns (MsgRemoveConsumerResponse); rpc UpdateParams(MsgUpdateParams) returns (MsgUpdateParamsResponse); rpc OptIn(MsgOptIn) returns (MsgOptInResponse); rpc OptOut(MsgOptOut) returns (MsgOptOutResponse); rpc SetConsumerCommissionRate(MsgSetConsumerCommissionRate) returns (MsgSetConsumerCommissionRateResponse); - rpc ConsumerModification(MsgConsumerModification) returns (MsgConsumerModificationResponse); + rpc ConsumerModification(MsgConsumerModification) returns (MsgConsumerModificationResponse) { + option deprecated = true; + } rpc ChangeRewardDenoms(MsgChangeRewardDenoms) returns (MsgChangeRewardDenomsResponse); } message MsgAssignConsumerKey { - option (cosmos.msg.v1.signer) = "signer"; + option (cosmos.msg.v1.signer) = "submitter"; option (gogoproto.equal) = false; option (gogoproto.goproto_getters) = false; - // The chain id of the consumer chain to assign a consensus public key to - string chain_id = 1; + // [DEPRECATED] use `consumer_id` instead + string chain_id = 1 [deprecated = true]; // The validator address on the provider string provider_addr = 2 [ (gogoproto.moretags) = "yaml:\"address\"" ]; // The consensus public key to use on the consumer. @@ -49,8 +58,10 @@ message MsgAssignConsumerKey { // `{"@type":"/cosmos.crypto.ed25519.PubKey","key":"Ui5Gf1+mtWUdH8u3xlmzdKID+F3PK0sfXZ73GZ6q6is="}` string consumer_key = 3; - // Tx signer address - string signer = 4 [(cosmos_proto.scalar) = "cosmos.AddressString"]; + string submitter = 4 [(cosmos_proto.scalar) = "cosmos.AddressString"]; + + // the consumer id of the consumer chain to assign a consensus public key to + string consumer_id = 5; } message MsgAssignConsumerKeyResponse {} @@ -67,6 +78,8 @@ message MsgSubmitConsumerMisbehaviour { // The Misbehaviour of the consumer chain wrapping // two conflicting IBC headers ibc.lightclients.tendermint.v1.Misbehaviour misbehaviour = 2; + // the consumer id of the consumer chain where the misbehaviour occurred + string consumer_id = 3; } message MsgSubmitConsumerMisbehaviourResponse {} @@ -85,6 +98,8 @@ message MsgSubmitConsumerDoubleVoting { tendermint.types.DuplicateVoteEvidence duplicate_vote_evidence = 2; // The light client header of the infraction block ibc.lightclients.tendermint.v1.Header infraction_block_header = 3; + // the consumer id of the consumer chain where the double-voting took place + string consumer_id = 4; } message MsgSubmitConsumerDoubleVotingResponse {} @@ -93,7 +108,7 @@ message MsgSubmitConsumerDoubleVotingResponse {} message MsgUpdateParams { option (cosmos.msg.v1.signer) = "authority"; - // signer is the address of the governance account. + // authority is the address of the governance account. string authority = 1 [(cosmos_proto.scalar) = "cosmos.AddressString"]; // params defines the x/provider parameters to update. @@ -102,13 +117,7 @@ message MsgUpdateParams { message MsgUpdateParamsResponse {} - -// MsgConsumerAddition defines the message used to spawn a new consumer chain using a v1 governance proposal. -// If it passes, then all validators on the provider chain are expected to validate -// the consumer chain at spawn time or get slashed. -// It is recommended that spawn time occurs after the proposal end time. -// -// Note: this replaces ConsumerAdditionProposal which is deprecated and will be removed soon +// [DEPRECATED] Use `MsgCreateConsumer` instead message MsgConsumerAddition { option (cosmos.msg.v1.signer) = "authority"; @@ -193,13 +202,7 @@ message MsgConsumerAddition { // MsgConsumerAdditionResponse defines response type for MsgConsumerAddition messages message MsgConsumerAdditionResponse {} - -// MsgConsumerRemoval message contains a governance proposal on the provider chain to -// remove (and stop) a consumer chain. If it passes, all the consumer chain's -// state is removed from the provider chain. The outstanding unbonding operation -// funds are released. -// -// Note: this replaces ConsumerRemovalProposal which is deprecated and will be removed soon +// [DEPRECATED] Use `MsgRemoveConsumer` instead message MsgConsumerRemoval { option (cosmos.msg.v1.signer) = "authority"; @@ -216,6 +219,21 @@ message MsgConsumerRemoval { // MsgConsumerRemovalResponse defines response type for MsgConsumerRemoval messages message MsgConsumerRemovalResponse {} + +// MsgRemoveConsumer defines the message used to remove (and stop) a consumer chain. +// If it passes, all the consumer chain's state is eventually removed from the provider chain. +message MsgRemoveConsumer { + option (cosmos.msg.v1.signer) = "owner"; + + // the consumer id of the consumer chain to be stopped + string consumer_id = 1; + // the address of the owner of the consumer chain to be stopped + string owner = 2 [(cosmos_proto.scalar) = "cosmos.AddressString"]; +} + +// MsgRemoveConsumerResponse defines response type for MsgRemoveConsumer messages +message MsgRemoveConsumerResponse {} + // ChangeRewardDenomsProposal is a governance proposal on the provider chain to // mutate the set of denoms accepted by the provider as rewards. // @@ -227,7 +245,7 @@ message MsgChangeRewardDenoms { repeated string denoms_to_add = 1; // the list of consumer reward denoms to remove repeated string denoms_to_remove = 2; - // signer address + // authority is the address of the governance account string authority = 3 [(cosmos_proto.scalar) = "cosmos.AddressString"]; } @@ -238,9 +256,9 @@ message MsgChangeRewardDenomsResponse {} message MsgOptIn { option (gogoproto.equal) = false; option (gogoproto.goproto_getters) = false; - option (cosmos.msg.v1.signer) = "signer"; - // the chain id of the consumer chain to opt in to - string chain_id = 1; + option (cosmos.msg.v1.signer) = "submitter"; + // [DEPRECATED] use `consumer_id` instead + string chain_id = 1 [deprecated = true]; // the validator address on the provider string provider_addr = 2 [ (gogoproto.moretags) = "yaml:\"address\"" ]; // (optional) The consensus public key to use on the consumer in json string format corresponding to proto-any, @@ -248,9 +266,10 @@ message MsgOptIn { // This field is optional and can remain empty (i.e., `consumer_key = ""`). A validator can always change the // consumer public key at a later stage by issuing a `MsgAssignConsumerKey` message. string consumer_key = 3; - // signer address - string signer = 4 [(cosmos_proto.scalar) = "cosmos.AddressString"]; - + // submitter address + string submitter = 4 [(cosmos_proto.scalar) = "cosmos.AddressString"]; + // the consumer id of the consumer chain to opt in to + string consumer_id = 5; } message MsgOptInResponse {} @@ -258,14 +277,15 @@ message MsgOptInResponse {} message MsgOptOut { option (gogoproto.equal) = false; option (gogoproto.goproto_getters) = false; - option (cosmos.msg.v1.signer) = "signer"; - // the chain id of the consumer chain to opt out from - string chain_id = 1; + option (cosmos.msg.v1.signer) = "submitter"; + // [DEPRECATED] use `consumer_id` instead + string chain_id = 1 [deprecated = true]; // the validator address on the provider string provider_addr = 2 [ (gogoproto.moretags) = "yaml:\"address\"" ]; - // signer address - string signer = 3 [(cosmos_proto.scalar) = "cosmos.AddressString"]; - + // submitter address + string submitter = 3 [(cosmos_proto.scalar) = "cosmos.AddressString"]; + // the consumer id of the consumer chain to opt out from + string consumer_id = 4; } message MsgOptOutResponse {} @@ -275,12 +295,12 @@ message MsgOptOutResponse {} message MsgSetConsumerCommissionRate { option (gogoproto.equal) = false; option (gogoproto.goproto_getters) = false; - option (cosmos.msg.v1.signer) = "signer"; + option (cosmos.msg.v1.signer) = "submitter"; - // The validator address on the provider - string provider_addr = 1 [ (gogoproto.moretags) = "yaml:\"address\"" ]; - // The chain id of the consumer chain to set a commission rate - string chain_id = 2; + // The validator address on the provider + string provider_addr = 1 [ (gogoproto.moretags) = "yaml:\"address\"" ]; + // [DEPRECATED] use `consumer_id` instead + string chain_id = 2 [deprecated = true]; // The rate to charge delegators on the consumer chain, as a fraction // TODO: migrate rate from sdk.Dec to math.LegacyDec string rate = 3 [ @@ -288,18 +308,16 @@ message MsgSetConsumerCommissionRate { (gogoproto.customtype) = "cosmossdk.io/math.LegacyDec", (gogoproto.nullable) = false ]; - // signer address - string signer = 4 [(cosmos_proto.scalar) = "cosmos.AddressString"]; + // submitter address + string submitter = 4 [(cosmos_proto.scalar) = "cosmos.AddressString"]; + // the consumer id of the consumer chain to set the commission rate + string consumer_id = 5; } message MsgSetConsumerCommissionRateResponse {} -// MsgConsumerModification message contains a governance proposal on the provider chain to -// modify a running consumer chain. If it passes, the consumer chain's -// parameters are updated. -// -// Note: this replaces ConsumerModificationProposal which is deprecated and will be removed soon +// [DEPRECATED] Use `MsgUpdateConsumer` instead message MsgConsumerModification { option (cosmos.msg.v1.signer) = "authority"; @@ -337,3 +355,52 @@ message MsgConsumerModification { } message MsgConsumerModificationResponse {} + +// MsgCreateConsumer defines the message that creates a consumer chain +message MsgCreateConsumer { + option (cosmos.msg.v1.signer) = "submitter"; + + // Submitter address. If the message is successfully handled, the ownership of + // the consumer chain will given to this address. + string submitter = 1 [(cosmos_proto.scalar) = "cosmos.AddressString"]; + + // the chain id of the new consumer chain + string chain_id = 2; + + ConsumerMetadata metadata = 3 [ (gogoproto.nullable) = false ]; + + ConsumerInitializationParameters initialization_parameters = 4; + + PowerShapingParameters power_shaping_parameters = 5; +} + +// MsgCreateConsumerResponse defines response type for MsgCreateConsumer +message MsgCreateConsumerResponse { + string consumer_id = 1; +} + +// MsgUpdateConsumer defines the message used to modify a consumer chain. +message MsgUpdateConsumer { + option (cosmos.msg.v1.signer) = "owner"; + + // the address of the owner of the consumer chain to be updated + string owner = 1 [(cosmos_proto.scalar) = "cosmos.AddressString"]; + + // the consumer id of the consumer chain to be updated + string consumer_id = 2; + + // the new owner of the consumer when updated + string new_owner_address = 3 [(cosmos_proto.scalar) = "cosmos.AddressString"]; + + // the metadata of the consumer when updated + ConsumerMetadata metadata = 4; + + // initialization parameters can only be updated before a chain has launched + ConsumerInitializationParameters initialization_parameters = 5; + + // the power-shaping parameters of the consumer when updated + PowerShapingParameters power_shaping_parameters = 6; +} + +// MsgUpdateConsumerResponse defines response type for MsgUpdateConsumer messages +message MsgUpdateConsumerResponse {} \ No newline at end of file diff --git a/tests/e2e/action_rapid_test.go b/tests/e2e/action_rapid_test.go index 004eb30d95..d51cb64129 100644 --- a/tests/e2e/action_rapid_test.go +++ b/tests/e2e/action_rapid_test.go @@ -261,11 +261,10 @@ func GetSubmitConsumerAdditionProposalActionGen() *rapid.Generator[SubmitConsume func GetSubmitConsumerRemovalProposalActionGen() *rapid.Generator[SubmitConsumerRemovalProposalAction] { return rapid.Custom(func(t *rapid.T) SubmitConsumerRemovalProposalAction { return SubmitConsumerRemovalProposalAction{ - Chain: GetChainIDGen().Draw(t, "Chain"), - From: GetValidatorIDGen().Draw(t, "From"), - Deposit: rapid.Uint().Draw(t, "Deposit"), - ConsumerChain: GetChainIDGen().Draw(t, "ConsumerChain"), - StopTimeOffset: time.Duration(rapid.Int64().Draw(t, "StopTimeOffset")), + Chain: GetChainIDGen().Draw(t, "Chain"), + From: GetValidatorIDGen().Draw(t, "From"), + Deposit: rapid.Uint().Draw(t, "Deposit"), + ConsumerChain: GetChainIDGen().Draw(t, "ConsumerChain"), } }) } diff --git a/tests/e2e/actions.go b/tests/e2e/actions.go index 088ad19801..18f1c6de4a 100644 --- a/tests/e2e/actions.go +++ b/tests/e2e/actions.go @@ -2,7 +2,6 @@ package main import ( "bufio" - "encoding/base64" "encoding/json" "fmt" "log" @@ -16,10 +15,12 @@ import ( "sync" "time" + sdk "github.com/cosmos/cosmos-sdk/types" clienttypes "github.com/cosmos/ibc-go/v8/modules/core/02-client/types" "github.com/tidwall/gjson" "golang.org/x/mod/semver" + ibctransfertypes "github.com/cosmos/ibc-go/v8/modules/apps/transfer/types" e2e "github.com/cosmos/interchain-security/v5/tests/e2e/testlib" "github.com/cosmos/interchain-security/v5/x/ccv/provider/client" "github.com/cosmos/interchain-security/v5/x/ccv/provider/types" @@ -42,6 +43,13 @@ type SendTokensAction struct { Amount uint } +type TxResponse struct { + TxHash string `json:"txhash"` + Code int `json:"code"` + RawLog string `json:"raw_log"` + Events []sdk.Event `json:"events"` +} + func (tr Chain) sendTokens( action SendTokensAction, verbose bool, @@ -250,6 +258,121 @@ func (tr Chain) submitTextProposal( tr.waitBlocks(action.Chain, 1, 10*time.Second) } +type UpdateConsumerChainAction struct { + Chain ChainID + From ValidatorID + ConsumerChain ChainID + NewOwner string + InitialHeight clienttypes.Height + SpawnTime uint + DistributionChannel string + TopN uint32 + ValidatorsPowerCap uint32 + ValidatorSetCap uint32 + Allowlist []string + Denylist []string + MinStake uint64 + AllowInactiveVals bool +} + +func (tr Chain) updateConsumerChain(action UpdateConsumerChainAction, verbose bool) { + + spawnTime := tr.testConfig.containerConfig.Now.Add(time.Duration(action.SpawnTime) * time.Millisecond) + params := ccvtypes.DefaultParams() + initParams := types.ConsumerInitializationParameters{ + InitialHeight: action.InitialHeight, + GenesisHash: []byte("gen_hash"), + BinaryHash: []byte("bin_hash"), + SpawnTime: spawnTime, + + UnbondingPeriod: params.UnbondingPeriod, + CcvTimeoutPeriod: params.CcvTimeoutPeriod, + TransferTimeoutPeriod: params.TransferTimeoutPeriod, + ConsumerRedistributionFraction: params.ConsumerRedistributionFraction, + BlocksPerDistributionTransmission: params.BlocksPerDistributionTransmission, + HistoricalEntries: params.HistoricalEntries, + DistributionTransmissionChannel: action.DistributionChannel, + } + + powerShapingParams := types.PowerShapingParameters{ + Top_N: action.TopN, + ValidatorsPowerCap: action.ValidatorsPowerCap, + ValidatorSetCap: action.ValidatorSetCap, + Allowlist: action.Allowlist, + Denylist: action.Denylist, + MinStake: action.MinStake, + AllowInactiveVals: action.AllowInactiveVals, + } + + consumerId := tr.testConfig.chainConfigs[action.ConsumerChain].ConsumerId + msg := types.MsgUpdateConsumer{ + ConsumerId: string(consumerId), + NewOwnerAddress: action.NewOwner, + InitializationParameters: &initParams, + PowerShapingParameters: &powerShapingParams, + } + tr.UpdateConsumer(action.Chain, action.From, msg) +} + +type CreateConsumerChainAction struct { + Chain ChainID + From ValidatorID + ConsumerChain ChainID + InitialHeight clienttypes.Height + SpawnTime uint + DistributionChannel string + TopN uint32 + ValidatorsPowerCap uint32 + ValidatorSetCap uint32 + Allowlist []string + Denylist []string + MinStake uint64 + AllowInactiveVals bool +} + +// createConsumerChain creates and initializes a consumer chain +func (tr Chain) createConsumerChain(action CreateConsumerChainAction, verbose bool) { + + spawnTime := tr.testConfig.containerConfig.Now.Add(time.Duration(action.SpawnTime) * time.Millisecond) + params := ccvtypes.DefaultParams() + initParams := types.ConsumerInitializationParameters{ + InitialHeight: action.InitialHeight, + GenesisHash: []byte("gen_hash"), + BinaryHash: []byte("bin_hash"), + SpawnTime: spawnTime, + + UnbondingPeriod: params.UnbondingPeriod, + CcvTimeoutPeriod: params.CcvTimeoutPeriod, + TransferTimeoutPeriod: params.TransferTimeoutPeriod, + ConsumerRedistributionFraction: params.ConsumerRedistributionFraction, + BlocksPerDistributionTransmission: params.BlocksPerDistributionTransmission, + HistoricalEntries: params.HistoricalEntries, + DistributionTransmissionChannel: action.DistributionChannel, + } + + powerShapingParams := types.PowerShapingParameters{ + Top_N: action.TopN, + ValidatorsPowerCap: action.ValidatorsPowerCap, + ValidatorSetCap: action.ValidatorSetCap, + Allowlist: action.Allowlist, + Denylist: action.Denylist, + MinStake: action.MinStake, + AllowInactiveVals: action.AllowInactiveVals, + } + + metadata := types.ConsumerMetadata{ + Name: "chain name of " + string(action.Chain), + Description: "no description", + Metadata: "no metadata", + } + + // create consumer to get a consumer-id + consumerId := tr.CreateConsumer(action.Chain, action.ConsumerChain, action.From, metadata, &initParams, &powerShapingParams) + if verbose { + fmt.Println("Create consumer chain", string(action.ConsumerChain), " with consumer-id", string(consumerId)) + } +} + type SubmitConsumerAdditionProposalAction struct { PreCCV bool Chain ChainID @@ -268,73 +391,223 @@ type SubmitConsumerAdditionProposalAction struct { AllowInactiveVals bool } +func (tr Chain) UpdateConsumer(providerChain ChainID, validator ValidatorID, update types.MsgUpdateConsumer) { + content, err := json.Marshal(update) + if err != nil { + log.Fatal("failed marshalling MsgUpdateConsumer: ", err.Error()) + } + jsonFile := "/update-consumer.json" + bz, err := tr.target.ExecCommand( + "/bin/bash", "-c", fmt.Sprintf(`echo '%s' > %s`, content, jsonFile), + ).CombinedOutput() + if err != nil { + log.Fatal(err, "\n", string(bz)) + } + + // Send consumer chain update + cmd := tr.target.ExecCommand( + tr.testConfig.chainConfigs[providerChain].BinaryName, + "tx", "provider", "update-consumer", jsonFile, + `--from`, `validator`+fmt.Sprint(validator), + `--chain-id`, string(tr.testConfig.chainConfigs[providerChain].ChainId), + `--home`, tr.getValidatorHome(providerChain, validator), + `--gas`, `900000`, + `--node`, tr.getValidatorNode(providerChain, validator), + `--keyring-backend`, `test`, + "--output", "json", + `-y`, + ) + + bz, err = cmd.CombinedOutput() + if err != nil { + log.Fatal("update consumer failed ", "error: ", err, "output: ", string(bz)) + } + + // Check transaction + txResponse := &TxResponse{} + err = json.Unmarshal(bz, txResponse) + if err != nil { + log.Fatalf("unmarshalling tx response on update-consumer: %s, json: %s", err.Error(), string(bz)) + } + + if txResponse.Code != 0 { + log.Fatalf("sending update-consumer transaction failed with error code %d, Log:'%s'", txResponse.Code, txResponse.RawLog) + } + tr.waitBlocks(providerChain, 2, 10*time.Second) +} + +// CreateConsumer creates a consumer chain and returns its consumer-id +func (tr Chain) CreateConsumer(providerChain, consumerChain ChainID, validator ValidatorID, metadata types.ConsumerMetadata, initParams *types.ConsumerInitializationParameters, powerShapingParams *types.PowerShapingParameters) ConsumerID { + + chainID := string(tr.testConfig.chainConfigs[consumerChain].ChainId) + msg := types.MsgCreateConsumer{ + ChainId: chainID, + Metadata: metadata, + InitializationParameters: initParams, + PowerShapingParameters: powerShapingParams, + } + + content, err := json.Marshal(msg) + if err != nil { + log.Fatalf("failed marshalling MsgCreateConsumer: %s", err.Error()) + } + jsonFile := "/create-consumer.json" + bz, err := tr.target.ExecCommand( + "/bin/bash", "-c", fmt.Sprintf(`echo '%s' > %s`, content, jsonFile), + ).CombinedOutput() + if err != nil { + log.Fatal(err, "\n", string(bz)) + } + + // Send consumer chain creation + cmd := tr.target.ExecCommand( + tr.testConfig.chainConfigs[providerChain].BinaryName, + "tx", "provider", "create-consumer", jsonFile, + `--from`, `validator`+fmt.Sprint(validator), + `--chain-id`, string(tr.testConfig.chainConfigs[providerChain].ChainId), + `--home`, tr.getValidatorHome(providerChain, validator), + `--gas`, `900000`, + `--node`, tr.getValidatorNode(providerChain, validator), + `--keyring-backend`, `test`, + "--output", "json", + `-y`, + ) + + bz, err = cmd.CombinedOutput() + if err != nil { + log.Fatal("create consumer failed ", "error: ", err, "output: ", string(bz)) + } + + txResponse := &TxResponse{} + err = json.Unmarshal(bz, txResponse) + if err != nil { + log.Fatalf("unmarshalling tx response on create-consumer: %s, json: %s", err.Error(), string(bz)) + } + + if txResponse.Code != 0 { + log.Fatalf("sending transaction failed with error code %d, Log:'%s'", txResponse.Code, txResponse.RawLog) + } + + // TODO: introduce waitForTx (see issue #2198) + tr.waitBlocks(providerChain, 2, 10*time.Second) + + // Get Consumer ID from transaction + cmd = tr.target.ExecCommand( + tr.testConfig.chainConfigs[providerChain].BinaryName, + "query", "tx", txResponse.TxHash, + `--node`, tr.getValidatorNode(providerChain, validator), + "--output", "json", + ) + bz, err = cmd.CombinedOutput() + if err != nil { + log.Fatalf("not able to query tx containing creation-consumer: tx: %s, err: %s, out: %s", + txResponse.TxHash, err.Error(), string(bz)) + } + + err = json.Unmarshal(bz, txResponse) + if err != nil { + log.Fatalf("unmarshalling tx containing create-consumer: %s, json: %s", err.Error(), string(bz)) + } + + consumerId := "" + for _, event := range txResponse.Events { + if event.Type != "consumer_creation" { + continue + } + attr, exists := event.GetAttribute("consumer_id") + if !exists { + log.Fatalf("no event with consumer_id found in tx content of create-consumer: %v", event) + } + consumerId = attr.Value + } + if consumerId == "" { + log.Fatalf("no consumer-id found in consumer creation transaction events for chain '%s'. events: %v", consumerChain, txResponse.Events) + } + + cfg, exists := tr.testConfig.chainConfigs[e2e.ChainID(chainID)] + if !exists { + log.Fatal("no chain config found for consumer chain", chainID) + } + if cfg.ConsumerId != "" && cfg.ConsumerId != e2e.ConsumerID(consumerId) { + log.Fatalf("chain '%s'registered already with a different consumer ID '%s'", chainID, consumerId) + } + + // Set the new created consumer-id on the chain's config + cfg.ConsumerId = e2e.ConsumerID(consumerId) + tr.testConfig.chainConfigs[e2e.ChainID(chainID)] = cfg + + return e2e.ConsumerID(consumerId) +} + +// submitConsumerAdditionProposal initializes a consumer chain and submits a governance proposal func (tr Chain) submitConsumerAdditionProposal( action SubmitConsumerAdditionProposalAction, verbose bool, ) { - spawnTime := tr.testConfig.containerConfig.Now.Add(time.Duration(action.SpawnTime) * time.Millisecond) params := ccvtypes.DefaultParams() - template := ` - { - "messages": [ - { - "@type": "/interchain_security.ccv.provider.v1.MsgConsumerAddition", - "chain_id": "%s", - "initial_height": { - "revision_number": "%d", - "revision_height": "%d" - }, - "genesis_hash": "%s", - "binary_hash": "%s", - "spawn_time": "%s", - "unbonding_period": "%s", - "ccv_timeout_period": "%s", - "transfer_timeout_period": "%s", - "consumer_redistribution_fraction": "%s", - "blocks_per_distribution_transmission": "%d", - "historical_entries": "%d", - "distribution_transmission_channel": "%s", - "top_N": %d, - "validators_power_cap": %d, - "validator_set_cap": %d, - "allowlist": %s, - "denylist": %s, - "authority": "cosmos10d07y265gmmuvt4z0w9aw880jnsr700j6zn9kn", - "allow_inactive_vals": %t, - "min_stake": "%d" - } - ], -"metadata": "ipfs://CID", -"deposit": "%dstake", -"title": "Propose the addition of a new chain", -"summary": "Gonna be a great chain", -"expedited": false -}` - jsonStr := fmt.Sprintf(template, - string(tr.testConfig.chainConfigs[action.ConsumerChain].ChainId), - action.InitialHeight.RevisionNumber, - action.InitialHeight.RevisionHeight, - base64.StdEncoding.EncodeToString([]byte("gen_hash")), - base64.StdEncoding.EncodeToString([]byte("bin_hash")), - spawnTime.Local().Format(time.RFC3339Nano), - params.UnbondingPeriod, - params.CcvTimeoutPeriod, - params.TransferTimeoutPeriod, - params.ConsumerRedistributionFraction, - params.BlocksPerDistributionTransmission, - params.HistoricalEntries, - action.DistributionChannel, - action.TopN, - action.ValidatorsPowerCap, - action.ValidatorSetCap, - action.Allowlist, - action.Denylist, - action.AllowInactiveVals, - action.MinStake, - action.Deposit) + spawnTime := tr.testConfig.containerConfig.Now.Add(time.Duration(action.SpawnTime) * time.Millisecond) - //#nosec G204 -- bypass unsafe quoting warning (no production code) - proposalFile := "/consumer-addition.proposal" + Metadata := types.ConsumerMetadata{ + Name: "chain " + string(action.Chain), + Description: "no description", + Metadata: "no metadata", + } + + initializationParameters := types.ConsumerInitializationParameters{ + InitialHeight: action.InitialHeight, + GenesisHash: []byte("gen_hash"), + BinaryHash: []byte("bin_hash"), + SpawnTime: spawnTime, + + UnbondingPeriod: params.UnbondingPeriod, + CcvTimeoutPeriod: params.CcvTimeoutPeriod, + TransferTimeoutPeriod: params.TransferTimeoutPeriod, + ConsumerRedistributionFraction: params.ConsumerRedistributionFraction, + BlocksPerDistributionTransmission: params.BlocksPerDistributionTransmission, + HistoricalEntries: params.HistoricalEntries, + DistributionTransmissionChannel: action.DistributionChannel, + } + + consumerId := tr.CreateConsumer(action.Chain, action.ConsumerChain, action.From, Metadata, nil, nil) + authority := "cosmos10d07y265gmmuvt4z0w9aw880jnsr700j6zn9kn" + + // Update consumer to change owner to governance before submitting the proposal + update := &types.MsgUpdateConsumer{ + ConsumerId: string(consumerId), + NewOwnerAddress: authority, + } + // For the MsgUpdateConsumer sent in the proposal + powerShapingParameters := types.PowerShapingParameters{ + Top_N: 0, + ValidatorsPowerCap: action.ValidatorsPowerCap, + ValidatorSetCap: action.ValidatorSetCap, + Allowlist: action.Allowlist, + Denylist: action.Denylist, + MinStake: action.MinStake, + AllowInactiveVals: action.AllowInactiveVals, + } + update.PowerShapingParameters = &powerShapingParameters + tr.UpdateConsumer(action.Chain, action.From, *update) + + // - set PowerShaping params TopN > 0 for consumer chain + update.PowerShapingParameters.Top_N = action.TopN + update.Owner = authority + update.NewOwnerAddress = "" + update.InitializationParameters = &initializationParameters + update.InitializationParameters.SpawnTime = spawnTime + update.Metadata = &Metadata + + // Generate proposal content + title := "Propose the addition of a new chain" + description := "description of the consumer modification proposal" + summary := "Gonna be a great chain" + expedited := false + metadata := "ipfs://CID" + deposit := fmt.Sprintf("%dstake", action.Deposit) + jsonStr := e2e.GenerateGovProposalContent(title, summary, metadata, deposit, description, expedited, update) + + // #nosec G204 -- bypass unsafe quoting warning (no production code) + proposalFile := "/update-consumer-proposal.json" bz, err := tr.target.ExecCommand( "/bin/bash", "-c", fmt.Sprintf(`echo '%s' > %s`, jsonStr, proposalFile), ).CombinedOutput() @@ -352,6 +625,7 @@ func (tr Chain) submitConsumerAdditionProposal( `--gas`, `900000`, `--node`, tr.getValidatorNode(action.Chain, action.From), `--keyring-backend`, `test`, + `-o json`, `-y`, ) @@ -361,7 +635,17 @@ func (tr Chain) submitConsumerAdditionProposal( } bz, err = cmd.CombinedOutput() if err != nil { - log.Fatal("submit-proposal failed:", err, "\n", string(bz)) + log.Fatal("executing submit-proposal failed:", err, "\n", string(bz)) + } + + txResponse := &TxResponse{} + err = json.Unmarshal(bz, txResponse) + if err != nil { + log.Fatalf("failed unmarshalling tx response on submit consumer update: %s, json: %s", err.Error(), string(bz)) + } + + if txResponse.Code != 0 { + log.Fatalf("gov submit consumer update transaction failed with error code %d, Log:'%s'", txResponse.Code, txResponse.RawLog) } if verbose { @@ -456,45 +740,34 @@ func (tr Chain) submitConsumerAdditionLegacyProposal( } type SubmitConsumerRemovalProposalAction struct { - Chain ChainID - From ValidatorID - Deposit uint - ConsumerChain ChainID - StopTimeOffset time.Duration // offset from time.Now() + Chain ChainID + From ValidatorID + Deposit uint + ConsumerChain ChainID } func (tr Chain) submitConsumerRemovalProposal( action SubmitConsumerRemovalProposalAction, verbose bool, ) { - template := ` - { - "messages": [ - { - "@type": "/interchain_security.ccv.provider.v1.MsgConsumerRemoval", - "chain_id": "%s", - "stop_time": "%s", - "authority": "cosmos10d07y265gmmuvt4z0w9aw880jnsr700j6zn9kn" - } - ], - "metadata": "ipfs://CID", - "deposit": "%dstake", - "title": "%s", - "summary": "It was a great chain", - "expedited": false - } -` + consumerId := string(tr.testConfig.chainConfigs[action.ConsumerChain].ConsumerId) title := fmt.Sprintf("Stop the %v chain", action.ConsumerChain) - stopTime := tr.testConfig.containerConfig.Now.Add(action.StopTimeOffset).Format(time.RFC3339Nano) + description := "stop consumer chain" + summary := "It was a great chain" + expedited := false + metadata := "ipfs://CID" + deposit := fmt.Sprintf("%dstake", action.Deposit) + authority := "cosmos10d07y265gmmuvt4z0w9aw880jnsr700j6zn9kn" + + msg := types.MsgRemoveConsumer{ + ConsumerId: consumerId, + Owner: authority, + } - jsonStr := fmt.Sprintf(template, - string(tr.testConfig.chainConfigs[action.ConsumerChain].ChainId), - stopTime, - action.Deposit, - title) + jsonStr := e2e.GenerateGovProposalContent(title, summary, metadata, deposit, description, expedited, &msg) // #nosec G204 -- bypass unsafe quoting warning (no production code) - proposalFile := "/consumer-removal.proposal" + proposalFile := "/remove-consumer-proposal.json" bz, err := tr.target.ExecCommand( "/bin/bash", "-c", fmt.Sprintf(`echo '%s' > %s`, jsonStr, proposalFile), ).CombinedOutput() @@ -536,13 +809,11 @@ func (tr Chain) submitConsumerRemovalLegacyProposal( action SubmitConsumerRemovalProposalAction, verbose bool, ) { - stopTime := tr.testConfig.containerConfig.Now.Add(action.StopTimeOffset) prop := client.ConsumerRemovalProposalJSON{ - Title: fmt.Sprintf("Stop the %v chain", action.ConsumerChain), - Summary: "It was a great chain", - ChainId: string(tr.testConfig.chainConfigs[action.ConsumerChain].ChainId), - StopTime: stopTime, - Deposit: fmt.Sprint(action.Deposit) + `stake`, + Title: fmt.Sprintf("Stop the %v chain", action.ConsumerChain), + Summary: "It was a great chain", + ChainId: string(tr.testConfig.chainConfigs[action.ConsumerChain].ChainId), + Deposit: fmt.Sprint(action.Deposit) + `stake`, } bz, err := json.Marshal(prop) @@ -599,47 +870,31 @@ func (tr Chain) submitConsumerModificationProposal( action SubmitConsumerModificationProposalAction, verbose bool, ) { - template := ` -{ -"messages": [ - { - "@type": "/interchain_security.ccv.provider.v1.MsgConsumerModification", - "title": "Propose the modification of the PSS parameters of a chain", - "description": "description of the consumer modification proposal", - "chain_id": "%s", - "top_N": %d, - "validators_power_cap": %d, - "validator_set_cap": %d, - "allowlist": %s, - "denylist": %s, - "authority": "cosmos10d07y265gmmuvt4z0w9aw880jnsr700j6zn9kn", - "min_stake": %d, - "allow_inactive_vals": %t - } - ], -"metadata": "ipfs://CID", -"deposit": "%sstake", -"title": "Propose the modification of the PSS parameters of a chain", -"summary": "summary of a modification proposal", -"expedited": false - } -` - - jsonStr := fmt.Sprintf(template, - string(tr.testConfig.chainConfigs[action.ConsumerChain].ChainId), - action.TopN, - action.ValidatorsPowerCap, - action.ValidatorSetCap, - action.Allowlist, - action.Denylist, - action.Deposit, - action.MinStake, - action.AllowInactiveVals, - ) + consumerId := string(tr.testConfig.chainConfigs[action.ConsumerChain].ConsumerId) + title := "Propose the modification of the PSS parameters of a chain" + description := "description of the consumer modification proposal" + summary := "summary of a modification proposal" + expedited := false + metadata := "ipfs://CID" + deposit := fmt.Sprintf("%dstake", action.Deposit) + authority := "cosmos10d07y265gmmuvt4z0w9aw880jnsr700j6zn9kn" + + msg := types.MsgUpdateConsumer{ + Owner: authority, + ConsumerId: consumerId, + PowerShapingParameters: &types.PowerShapingParameters{ + Top_N: action.TopN, + ValidatorsPowerCap: action.ValidatorsPowerCap, + ValidatorSetCap: action.ValidatorSetCap, + Allowlist: action.Allowlist, + Denylist: action.Denylist, + }, + } + jsonStr := e2e.GenerateGovProposalContent(title, summary, metadata, deposit, description, expedited, &msg) // #nosec G204 -- bypass unsafe quoting warning (no production code) - proposalFile := "/consumer-mod.proposal" + proposalFile := "/update-consumer-proposal.json" bz, err := tr.target.ExecCommand( "/bin/bash", "-c", fmt.Sprintf(`echo '%s' > %s`, jsonStr, proposalFile), ).CombinedOutput() @@ -754,26 +1009,21 @@ func (tr Chain) submitEnableTransfersProposalAction( ) { // gov signed address got by checking the gov module acc address in the test container // interchain-security-cdd q auth module-account gov --node tcp://7.7.9.253:26658 - template := ` - { - "messages": [ - { - "@type": "/ibc.applications.transfer.v1.MsgUpdateParams", - "signer": "consumer10d07y265gmmuvt4z0w9aw880jnsr700jlh7295", - "params": { - "send_enabled": true, - "receive_enabled": true - } - } - ], - "metadata": "ipfs://CID", - "deposit": "%dstake", - "title": "%s", - "summary": "Enable transfer send", - "expedited": false - } - ` - jsonStr := fmt.Sprintf(template, action.Deposit, action.Title) + + msgUpdateParams := ibctransfertypes.MsgUpdateParams{ + Signer: "consumer10d07y265gmmuvt4z0w9aw880jnsr700jlh7295", + Params: ibctransfertypes.Params{ + SendEnabled: true, + ReceiveEnabled: true, + }, + } + // Generate proposal content + description := "update IBC params" + summary := "Enable transfer send/receive" + expedited := false + metadata := "ipfs://CID" + deposit := fmt.Sprintf("%dstake", action.Deposit) + jsonStr := e2e.GenerateGovProposalContent(action.Title, summary, metadata, deposit, description, expedited, &msgUpdateParams) //#nosec G204 -- bypass unsafe quoting warning (no production code) bz, err := tr.target.ExecCommand( @@ -880,23 +1130,34 @@ func (tr *Chain) startConsumerChain( func (tr *Chain) getConsumerGenesis(providerChain, consumerChain ChainID) string { fmt.Println("Exporting consumer genesis from provider") providerBinaryName := tr.testConfig.chainConfigs[providerChain].BinaryName + consumerId := string(tr.testConfig.chainConfigs[consumerChain].ConsumerId) - cmd := tr.target.ExecCommand( - providerBinaryName, + now := time.Now() + timeout := now.Add(30 * time.Second) + var bz []byte + var err error + for { + cmd := tr.target.ExecCommand( + providerBinaryName, - "query", "provider", "consumer-genesis", - string(tr.testConfig.chainConfigs[consumerChain].ChainId), + "query", "provider", "consumer-genesis", consumerId, - `--node`, tr.target.GetQueryNode(providerChain), - `-o`, `json`, - ) + `--node`, tr.target.GetQueryNode(providerChain), + `-o`, `json`, + ) + bz, err = cmd.CombinedOutput() + if err == nil { + break + } - bz, err := cmd.CombinedOutput() - if err != nil { - log.Fatal(err, "\n", string(bz)) + if time.Now().After(timeout) { + log.Print("Failed running command: ", cmd) + log.Fatal(err, "\n", string(bz)) + } + time.Sleep(2 * time.Second) } - if tr.testConfig.transformGenesis || needsGenesisTransform(tr.testConfig) { + if tr.testConfig.transformGenesis || needsGenesisTransform(*tr.testConfig) { return string(tr.transformConsumerGenesis(consumerChain, bz)) } else { fmt.Println("No genesis transformation performed") @@ -1071,28 +1332,9 @@ func (tr Chain) changeoverChain( action ChangeoverChainAction, verbose bool, ) { - // sleep until the consumer chain genesis is ready on consumer - time.Sleep(5 * time.Second) - cmd := tr.target.ExecCommand( - tr.testConfig.chainConfigs[action.ProviderChain].BinaryName, - - "query", "provider", "consumer-genesis", - string(tr.testConfig.chainConfigs[action.SovereignChain].ChainId), - - `--node`, tr.target.GetQueryNode(action.ProviderChain), - `-o`, `json`, - ) - - if verbose { - log.Println("changeoverChain cmd: ", cmd.String()) - } - bz, err := cmd.CombinedOutput() - if err != nil { - log.Fatal(err, "\n", string(bz)) - } + consumerGenesis := ".app_state.ccvconsumer = " + tr.getConsumerGenesis(action.ProviderChain, action.SovereignChain) - consumerGenesis := ".app_state.ccvconsumer = " + string(bz) consumerGenesisChanges := tr.testConfig.chainConfigs[action.SovereignChain].GenesisChanges if consumerGenesisChanges != "" { consumerGenesis = consumerGenesis + " | " + consumerGenesisChanges @@ -2229,32 +2471,24 @@ type SubmitChangeRewardDenomsProposalAction struct { } func (tr Chain) submitChangeRewardDenomsProposal(action SubmitChangeRewardDenomsProposalAction, verbose bool) { - template := ` -{ - "messages": [ - { - "@type": "/interchain_security.ccv.provider.v1.MsgChangeRewardDenoms", - "denoms_to_add": ["%s"], - "denoms_to_remove": ["%s"], - "authority": "cosmos10d07y265gmmuvt4z0w9aw880jnsr700j6zn9kn" - } - ], - "metadata": "ipfs://CID", - "deposit": "%dstake", - "title": "change reward denoms", - "summary": "Proposal to change reward denoms", - "expedited": false -}` - denomsToAdd := action.Denom - denomsToRemove := "stake" - jsonStr := fmt.Sprintf(template, - denomsToAdd, - denomsToRemove, - action.Deposit) + changeRewMsg := types.MsgChangeRewardDenoms{ + DenomsToAdd: []string{action.Denom}, + DenomsToRemove: []string{"stake"}, + Authority: "cosmos10d07y265gmmuvt4z0w9aw880jnsr700j6zn9kn", + } + + // Generate proposal content + title := "change reward denoms" + description := "change reward denoms" + summary := "Proposal to change reward denoms" + expedited := false + metadata := "ipfs://CID" + deposit := fmt.Sprintf("%dstake", action.Deposit) + jsonStr := e2e.GenerateGovProposalContent(title, summary, metadata, deposit, description, expedited, &changeRewMsg) //#nosec G204 -- bypass unsafe quoting warning (no production code) - proposalFile := "/change-reward.proposal" + proposalFile := "/change-rewards-proposal.json" bz, err := tr.target.ExecCommand( "/bin/bash", "-c", fmt.Sprintf(`echo '%s' > %s`, jsonStr, proposalFile), ).CombinedOutput() @@ -2480,10 +2714,11 @@ func (tr Chain) assignConsumerPubKey(action AssignConsumerPubKeyAction, verbose if tr.testConfig.useCometmock { gas = "9000000" } + assignKey := fmt.Sprintf( `%s tx provider assign-consensus-key %s '%s' --from validator%s --chain-id %s --home %s --node %s --gas %s --keyring-backend test -y -o json`, tr.testConfig.chainConfigs[ChainID("provi")].BinaryName, - string(tr.testConfig.chainConfigs[action.Chain].ChainId), + string(tr.testConfig.chainConfigs[action.Chain].ConsumerId), action.ConsumerPubkey, action.Validator, tr.testConfig.chainConfigs[ChainID("provi")].ChainId, @@ -2659,7 +2894,7 @@ type OptInAction struct { Validator ValidatorID } -func (tr Chain) optIn(action OptInAction, target ExecutionTarget, verbose bool) { +func (tr Chain) optIn(action OptInAction, verbose bool) { // Note: to get error response reported back from this command '--gas auto' needs to be set. gas := "auto" // Unfortunately, --gas auto does not work with CometMock. so when using CometMock, just use --gas 9000000 then @@ -2671,7 +2906,7 @@ func (tr Chain) optIn(action OptInAction, target ExecutionTarget, verbose bool) optIn := fmt.Sprintf( `%s tx provider opt-in %s --from validator%s --chain-id %s --home %s --node %s --gas %s --keyring-backend test -y -o json`, tr.testConfig.chainConfigs[ChainID("provi")].BinaryName, - string(tr.testConfig.chainConfigs[action.Chain].ChainId), + string(tr.testConfig.chainConfigs[action.Chain].ConsumerId), action.Validator, tr.testConfig.chainConfigs[ChainID("provi")].ChainId, tr.getValidatorHome(ChainID("provi"), action.Validator), @@ -2679,7 +2914,7 @@ func (tr Chain) optIn(action OptInAction, target ExecutionTarget, verbose bool) gas, ) - cmd := target.ExecCommand( + cmd := tr.target.ExecCommand( "/bin/bash", "-c", optIn, ) @@ -2709,7 +2944,7 @@ type OptOutAction struct { ExpectError bool } -func (tr Chain) optOut(action OptOutAction, target ExecutionTarget, verbose bool) { +func (tr Chain) optOut(action OptOutAction, verbose bool) { // Note: to get error response reported back from this command '--gas auto' needs to be set. gas := "auto" // Unfortunately, --gas auto does not work with CometMock. so when using CometMock, just use --gas 9000000 then @@ -2721,7 +2956,7 @@ func (tr Chain) optOut(action OptOutAction, target ExecutionTarget, verbose bool optOut := fmt.Sprintf( `%s tx provider opt-out %s --from validator%s --chain-id %s --home %s --node %s --gas %s --keyring-backend test -y -o json`, tr.testConfig.chainConfigs[ChainID("provi")].BinaryName, - string(tr.testConfig.chainConfigs[action.Chain].ChainId), + string(tr.testConfig.chainConfigs[action.Chain].ConsumerId), action.Validator, tr.testConfig.chainConfigs[ChainID("provi")].ChainId, tr.getValidatorHome(ChainID("provi"), action.Validator), @@ -2729,7 +2964,7 @@ func (tr Chain) optOut(action OptOutAction, target ExecutionTarget, verbose bool gas, ) - cmd := target.ExecCommand( + cmd := tr.target.ExecCommand( "/bin/bash", "-c", optOut, ) @@ -2759,6 +2994,7 @@ func (tr Chain) optOut(action OptOutAction, target ExecutionTarget, verbose bool type SetConsumerCommissionRateAction struct { Chain ChainID + ConsumerID ConsumerID Validator ValidatorID CommissionRate float64 @@ -2767,7 +3003,7 @@ type SetConsumerCommissionRateAction struct { ExpectedError string } -func (tr Chain) setConsumerCommissionRate(action SetConsumerCommissionRateAction, target ExecutionTarget, verbose bool) { +func (tr Chain) setConsumerCommissionRate(action SetConsumerCommissionRateAction, verbose bool) { // Note: to get error response reported back from this command '--gas auto' needs to be set. gas := "auto" // Unfortunately, --gas auto does not work with CometMock. so when using CometMock, just use --gas 9000000 then @@ -2775,11 +3011,16 @@ func (tr Chain) setConsumerCommissionRate(action SetConsumerCommissionRateAction gas = "9000000" } + consumerId := string(tr.testConfig.chainConfigs[action.Chain].ConsumerId) + if action.ConsumerID != "" { + consumerId = string(action.ConsumerID) + } + // Use: "set-consumer-commission-rate [consumer-chain-id] [commission-rate]" setCommissionRate := fmt.Sprintf( `%s tx provider set-consumer-commission-rate %s %f --from validator%s --chain-id %s --home %s --node %s --gas %s --keyring-backend test -y -o json`, tr.testConfig.chainConfigs[ChainID("provi")].BinaryName, - string(tr.testConfig.chainConfigs[action.Chain].ChainId), + consumerId, action.CommissionRate, action.Validator, tr.testConfig.chainConfigs[ChainID("provi")].ChainId, @@ -2788,7 +3029,7 @@ func (tr Chain) setConsumerCommissionRate(action SetConsumerCommissionRateAction gas, ) - cmd := target.ExecCommand( + cmd := tr.target.ExecCommand( "/bin/bash", "-c", setCommissionRate, ) diff --git a/tests/e2e/config.go b/tests/e2e/config.go index 4fa762b5f7..c3f8f712b1 100644 --- a/tests/e2e/config.go +++ b/tests/e2e/config.go @@ -74,6 +74,7 @@ var hermesTemplates = map[string]string{ // type aliases for shared types from e2e package type ( ChainID = e2e.ChainID + ConsumerID = e2e.ConsumerID ValidatorID = e2e.ValidatorID ValidatorConfig = e2e.ValidatorConfig ChainConfig = e2e.ChainConfig diff --git a/tests/e2e/main.go b/tests/e2e/main.go index 2864c9b413..e8ae6b2166 100644 --- a/tests/e2e/main.go +++ b/tests/e2e/main.go @@ -246,6 +246,13 @@ var stepChoices = map[string]StepChoice{ description: "test minting without inactive validators as a sanity check", testConfig: MintTestCfg, }, + // TODO PERMISSIONLESS: ADD NEW E2E TEST + /* "permissionless-ics": { + name: "permissionless-ics", + steps: stepsPermissionlessICS(), + description: "test permissionless ics", + testConfig: DefaultTestCfg, + }, */ "inactive-vals-outside-max-validators": { name: "inactive-vals-outside-max-validators", steps: stepsInactiveValsTopNReproduce(), diff --git a/tests/e2e/state.go b/tests/e2e/state.go index f29c8f59f0..f6cac89947 100644 --- a/tests/e2e/state.go +++ b/tests/e2e/state.go @@ -12,6 +12,7 @@ import ( clienttypes "github.com/cosmos/ibc-go/v8/modules/core/02-client/types" e2e "github.com/cosmos/interchain-security/v5/tests/e2e/testlib" + "github.com/cosmos/interchain-security/v5/x/ccv/provider/types" "github.com/kylelemons/godebug/pretty" "github.com/tidwall/gjson" "gopkg.in/yaml.v2" @@ -38,7 +39,7 @@ type State map[ChainID]ChainState type Chain struct { target e2e.TargetDriver - testConfig TestConfig + testConfig *TestConfig } func (tr Chain) GetChainState(chain ChainID, modelState ChainState) ChainState { @@ -335,7 +336,7 @@ func intPtr(i int) *int { } type Commands struct { - containerConfig ContainerConfig // FIXME only needed for 'Now' time tracking + containerConfig *ContainerConfig validatorConfigs map[ValidatorID]ValidatorConfig chainConfigs map[ChainID]ChainConfig target e2e.PlatformDriver @@ -465,6 +466,30 @@ func (tr Commands) GetProposal(chain ChainID, proposal uint) Proposal { Title: title, Description: description, } + case "/interchain_security.ccv.provider.v1.MsgUpdateConsumer": + consumerId := rawContent.Get("consumer_id").String() + consumerChainId := ChainID("") + for _, chainCfg := range tr.chainConfigs { + if chainCfg.ConsumerId == e2e.ConsumerID(consumerId) { + consumerChainId = chainCfg.ChainId + break + } + } + + updateProposal := ConsumerAdditionProposal{ + Deposit: uint(deposit), + Chain: consumerChainId, + Status: status, + } + if rawContent.Get("initialization_parameters").Exists() { + spawnTime := rawContent.Get("initialization_parameters.spawn_time").Time().Sub(tr.containerConfig.Now) + updateProposal.SpawnTime = int(spawnTime.Milliseconds()) + updateProposal.InitialHeight = clienttypes.Height{ + RevisionNumber: rawContent.Get("initialization_parameters.initial_height.revision_number").Uint(), + RevisionHeight: rawContent.Get("initialization_parameters.initial_height.revision_height").Uint(), + } + } + return updateProposal case "/interchain_security.ccv.provider.v1.MsgConsumerAddition": chainId := rawContent.Get("chain_id").String() spawnTime := rawContent.Get("spawn_time").Time().Sub(tr.containerConfig.Now) @@ -498,23 +523,21 @@ func (tr Commands) GetProposal(chain ChainID, proposal uint) Proposal { Title: title, Type: "/cosmos.upgrade.v1beta1.SoftwareUpgradeProposal", } - case "/interchain_security.ccv.provider.v1.MsgConsumerRemoval": - chainId := rawContent.Get("chain_id").String() - stopTime := rawContent.Get("stop_time").Time().Sub(tr.containerConfig.Now) + case "/interchain_security.ccv.provider.v1.MsgRemoveConsumer": + consumerId := rawContent.Get("consumer_id").String() var chain ChainID for i, conf := range tr.chainConfigs { - if string(conf.ChainId) == chainId { + if string(conf.ConsumerId) == consumerId { chain = i break } } return ConsumerRemovalProposal{ - Deposit: uint(deposit), - Status: status, - Chain: chain, - StopTime: int(stopTime.Milliseconds()), + Deposit: uint(deposit), + Status: status, + Chain: chain, } case "/ibc.applications.transfer.v1.MsgUpdateParams": var params IBCTransferParams @@ -732,7 +755,6 @@ func (tr Commands) GetIBCTransferParams(chain ChainID) IBCTransferParams { func (tr Commands) GetConsumerChains(chain ChainID) map[ChainID]bool { binaryName := tr.chainConfigs[chain].BinaryName cmd := tr.target.ExecCommand(binaryName, - "query", "provider", "list-consumer-chains", `--node`, tr.GetQueryNode(chain), `-o`, `json`, @@ -746,8 +768,13 @@ func (tr Commands) GetConsumerChains(chain ChainID) map[ChainID]bool { arr := gjson.Get(string(bz), "chains").Array() chains := make(map[ChainID]bool) for _, c := range arr { - id := c.Get("chain_id").String() - chains[ChainID(id)] = true + phase := c.Get("phase").String() + if phase == types.ConsumerPhase_name[int32(types.CONSUMER_PHASE_INITIALIZED)] || + phase == types.ConsumerPhase_name[int32(types.CONSUMER_PHASE_REGISTERED)] || + phase == types.ConsumerPhase_name[int32(types.CONSUMER_PHASE_LAUNCHED)] { + id := c.Get("chain_id").String() + chains[ChainID(id)] = true + } } return chains @@ -755,10 +782,11 @@ func (tr Commands) GetConsumerChains(chain ChainID) map[ChainID]bool { func (tr Commands) GetConsumerAddress(consumerChain ChainID, validator ValidatorID) string { binaryName := tr.chainConfigs[ChainID("provi")].BinaryName + consumerId := tr.chainConfigs[ChainID(consumerChain)].ConsumerId cmd := tr.target.ExecCommand(binaryName, "query", "provider", "validator-consumer-key", - string(consumerChain), tr.validatorConfigs[validator].ValconsAddress, + string(consumerId), tr.validatorConfigs[validator].ValconsAddress, `--node`, tr.GetQueryNode(ChainID("provi")), `-o`, `json`, ) @@ -773,10 +801,12 @@ func (tr Commands) GetConsumerAddress(consumerChain ChainID, validator Validator func (tr Commands) GetProviderAddressFromConsumer(consumerChain ChainID, validator ValidatorID) string { binaryName := tr.chainConfigs[ChainID("provi")].BinaryName + consumerId := tr.chainConfigs[ChainID(consumerChain)].ConsumerId + cmd := tr.target.ExecCommand(binaryName, "query", "provider", "validator-provider-key", - string(consumerChain), tr.validatorConfigs[validator].ConsumerValconsAddressOnProvider, + string(consumerId), tr.validatorConfigs[validator].ConsumerValconsAddressOnProvider, `--node`, tr.GetQueryNode(ChainID("provi")), `-o`, `json`, ) @@ -898,7 +928,12 @@ func (tr Commands) GetHasToValidate( arr := gjson.Get(string(bz), "consumer_chain_ids").Array() chains := []ChainID{} for _, c := range arr { - chains = append(chains, ChainID(c.String())) + for _, chain := range tr.chainConfigs { + if chain.ConsumerId == ConsumerID(c.String()) { + chains = append(chains, chain.ChainId) + break + } + } } return chains @@ -969,20 +1004,25 @@ func (tr Commands) GetTrustedHeight( func (tr Commands) GetProposedConsumerChains(chain ChainID) []string { binaryName := tr.chainConfigs[chain].BinaryName - bz, err := tr.target.ExecCommand(binaryName, - "query", "provider", "list-proposed-consumer-chains", + cmd := tr.target.ExecCommand(binaryName, + "query", "provider", "list-consumer-chains", `--node`, tr.GetQueryNode(chain), `-o`, `json`, - ).CombinedOutput() + ) + bz, err := cmd.CombinedOutput() if err != nil { log.Fatal(err, "\n", string(bz)) } - arr := gjson.Get(string(bz), "proposedChains").Array() + arr := gjson.Get(string(bz), "chains").Array() chains := []string{} for _, c := range arr { - cid := c.Get("chainID").String() - chains = append(chains, cid) + cid := c.Get("chain_id").String() + phase := c.Get("phase").String() + if phase == types.ConsumerPhase_name[int32(types.CONSUMER_PHASE_INITIALIZED)] || + phase == types.ConsumerPhase_name[int32(types.CONSUMER_PHASE_REGISTERED)] { + chains = append(chains, cid) + } } return chains @@ -1013,9 +1053,11 @@ func (tr Commands) GetQueryNodeIP(chain ChainID) string { // GetConsumerCommissionRate returns the commission rate of the given validator on the given consumerChain func (tr Commands) GetConsumerCommissionRate(consumerChain ChainID, validator ValidatorID) float64 { binaryName := tr.chainConfigs[ChainID("provi")].BinaryName + consumerId := tr.chainConfigs[consumerChain].ConsumerId + cmd := tr.target.ExecCommand(binaryName, "query", "provider", "validator-consumer-commission-rate", - string(consumerChain), tr.validatorConfigs[validator].ValconsAddress, + string(consumerId), tr.validatorConfigs[validator].ValconsAddress, `--node`, tr.GetQueryNode(ChainID("provi")), `-o`, `json`, ) diff --git a/tests/e2e/state_rapid_test.go b/tests/e2e/state_rapid_test.go index 1ca36d5578..fc591d5db1 100644 --- a/tests/e2e/state_rapid_test.go +++ b/tests/e2e/state_rapid_test.go @@ -203,10 +203,9 @@ func GetConsumerAdditionProposalGen() *rapid.Generator[ConsumerAdditionProposal] func GetConsumerRemovalProposalGen() *rapid.Generator[ConsumerRemovalProposal] { return rapid.Custom(func(t *rapid.T) ConsumerRemovalProposal { return ConsumerRemovalProposal{ - Deposit: rapid.Uint().Draw(t, "Deposit"), - Chain: GetChainIDGen().Draw(t, "Chain"), - StopTime: rapid.Int().Draw(t, "StopTime"), - Status: rapid.String().Draw(t, "Status"), + Deposit: rapid.Uint().Draw(t, "Deposit"), + Chain: GetChainIDGen().Draw(t, "Chain"), + Status: rapid.String().Draw(t, "Status"), } }) } diff --git a/tests/e2e/steps_partial_set_security.go b/tests/e2e/steps_partial_set_security.go index 80eff1aedd..156457769b 100644 --- a/tests/e2e/steps_partial_set_security.go +++ b/tests/e2e/steps_partial_set_security.go @@ -2,6 +2,7 @@ package main import ( "strconv" + "time" gov "github.com/cosmos/cosmos-sdk/x/gov/types/v1" clienttypes "github.com/cosmos/ibc-go/v8/modules/core/02-client/types" @@ -32,6 +33,7 @@ func stepsOptInChain() []Step { { Action: SetConsumerCommissionRateAction{ Chain: ChainID("consu"), + ConsumerID: "99999", Validator: ValidatorID("bob"), CommissionRate: 0.123, ExpectError: true, @@ -40,31 +42,17 @@ func stepsOptInChain() []Step { State: State{}, }, { - Action: SubmitConsumerAdditionProposalAction{ + Action: CreateConsumerChainAction{ Chain: ChainID("provi"), From: ValidatorID("alice"), - Deposit: 10000001, ConsumerChain: ChainID("consu"), - SpawnTime: 0, + SpawnTime: uint(time.Minute * 10), // set spawn-time far in the future InitialHeight: clienttypes.Height{RevisionNumber: 0, RevisionHeight: 1}, TopN: 0, }, State: State{ ChainID("provi"): ChainState{ - Proposals: &map[uint]Proposal{ - 1: ConsumerAdditionProposal{ - Deposit: 10000001, - Chain: ChainID("consu"), - SpawnTime: 0, - InitialHeight: clienttypes.Height{RevisionNumber: 0, RevisionHeight: 1}, - Status: strconv.Itoa(int(gov.ProposalStatus_PROPOSAL_STATUS_VOTING_PERIOD)), - }, - }, - HasToValidate: &map[ValidatorID][]ChainID{ - ValidatorID("alice"): {}, - ValidatorID("bob"): {}, - ValidatorID("carol"): {}, - }, + ProposedConsumerChains: &[]string{"consu"}, }, }, }, @@ -127,25 +115,15 @@ func stepsOptInChain() []Step { }, }, { - Action: VoteGovProposalAction{ - Chain: ChainID("provi"), - From: []ValidatorID{ValidatorID("alice"), ValidatorID("bob")}, - Vote: []string{"yes", "yes"}, - PropNumber: 1, - }, - State: State{ - ChainID("provi"): ChainState{ - Proposals: &map[uint]Proposal{ - 1: ConsumerAdditionProposal{ - Deposit: 10000001, - Chain: ChainID("consu"), - SpawnTime: 0, - InitialHeight: clienttypes.Height{RevisionNumber: 0, RevisionHeight: 1}, - Status: strconv.Itoa(int(gov.ProposalStatus_PROPOSAL_STATUS_PASSED)), - }, - }, - }, + Action: UpdateConsumerChainAction{ + Chain: ChainID("provi"), + From: ValidatorID("alice"), + ConsumerChain: ChainID("consu"), + SpawnTime: 0, // launch now + InitialHeight: clienttypes.Height{RevisionNumber: 0, RevisionHeight: 1}, + TopN: 0, }, + State: State{}, }, { // we start all the validators but only "alice" and "bob" have opted in and hence @@ -1052,33 +1030,18 @@ func stepsValidatorSetCappedChain() []Step { }, }, { - Action: SubmitConsumerAdditionProposalAction{ - Chain: ChainID("provi"), - From: ValidatorID("alice"), - Deposit: 10000001, - ConsumerChain: ChainID("consu"), - SpawnTime: 0, - InitialHeight: clienttypes.Height{RevisionNumber: 0, RevisionHeight: 1}, - TopN: 0, - // we can have at most 2 validators validating the consumer chain + Action: CreateConsumerChainAction{ + Chain: ChainID("provi"), + From: ValidatorID("alice"), + ConsumerChain: ChainID("consu"), + SpawnTime: uint(time.Minute * 10), // set spawn-time far in the future + InitialHeight: clienttypes.Height{RevisionNumber: 0, RevisionHeight: 1}, + TopN: 0, ValidatorSetCap: 2, }, State: State{ ChainID("provi"): ChainState{ - Proposals: &map[uint]Proposal{ - 1: ConsumerAdditionProposal{ - Deposit: 10000001, - Chain: ChainID("consu"), - SpawnTime: 0, - InitialHeight: clienttypes.Height{RevisionNumber: 0, RevisionHeight: 1}, - Status: strconv.Itoa(int(gov.ProposalStatus_PROPOSAL_STATUS_VOTING_PERIOD)), - }, - }, - HasToValidate: &map[ValidatorID][]ChainID{ - ValidatorID("alice"): {}, - ValidatorID("bob"): {}, - ValidatorID("carol"): {}, - }, + ProposedConsumerChains: &[]string{"consu"}, }, }, }, @@ -1143,25 +1106,17 @@ func stepsValidatorSetCappedChain() []Step { State: State{}, }, { - Action: VoteGovProposalAction{ - Chain: ChainID("provi"), - From: []ValidatorID{ValidatorID("alice"), ValidatorID("bob")}, - Vote: []string{"yes", "yes"}, - PropNumber: 1, - }, - State: State{ - ChainID("provi"): ChainState{ - Proposals: &map[uint]Proposal{ - 1: ConsumerAdditionProposal{ - Deposit: 10000001, - Chain: ChainID("consu"), - SpawnTime: 0, - InitialHeight: clienttypes.Height{RevisionNumber: 0, RevisionHeight: 1}, - Status: strconv.Itoa(int(gov.ProposalStatus_PROPOSAL_STATUS_PASSED)), - }, - }, - }, + // Update with SpawnTime 0 will trigger launch of consumer chain + Action: UpdateConsumerChainAction{ + Chain: ChainID("provi"), + From: ValidatorID("alice"), + ConsumerChain: ChainID("consu"), + SpawnTime: 0, // launch now + InitialHeight: clienttypes.Height{RevisionNumber: 0, RevisionHeight: 1}, + TopN: 0, + ValidatorSetCap: 2, }, + State: State{}, }, { Action: StartConsumerChainAction{ @@ -1513,36 +1468,17 @@ func stepsValidatorsAllowlistedChain() []Step { }, }, { - Action: SubmitConsumerAdditionProposalAction{ + Action: CreateConsumerChainAction{ Chain: ChainID("provi"), From: ValidatorID("alice"), - Deposit: 10000001, ConsumerChain: ChainID("consu"), - SpawnTime: 0, + SpawnTime: uint(time.Minute * 10), // set spawn-time far in the future InitialHeight: clienttypes.Height{RevisionNumber: 0, RevisionHeight: 1}, TopN: 0, - // only "alice" and "bob" are allowlisted (see `getDefaultValidators` in `tests/e2e/config.go`) - Allowlist: []string{ - "cosmosvalcons1qmq08eruchr5sf5s3rwz7djpr5a25f7xw4mceq", - "cosmosvalcons1nx7n5uh0ztxsynn4sje6eyq2ud6rc6klc96w39", - }, }, State: State{ ChainID("provi"): ChainState{ - Proposals: &map[uint]Proposal{ - 1: ConsumerAdditionProposal{ - Deposit: 10000001, - Chain: ChainID("consu"), - SpawnTime: 0, - InitialHeight: clienttypes.Height{RevisionNumber: 0, RevisionHeight: 1}, - Status: strconv.Itoa(int(gov.ProposalStatus_PROPOSAL_STATUS_VOTING_PERIOD)), - }, - }, - HasToValidate: &map[ValidatorID][]ChainID{ - ValidatorID("alice"): {}, - ValidatorID("bob"): {}, - ValidatorID("carol"): {}, - }, + ProposedConsumerChains: &[]string{"consu"}, }, }, }, @@ -1606,25 +1542,21 @@ func stepsValidatorsAllowlistedChain() []Step { State: State{}, }, { - Action: VoteGovProposalAction{ - Chain: ChainID("provi"), - From: []ValidatorID{ValidatorID("alice"), ValidatorID("bob")}, - Vote: []string{"yes", "yes"}, - PropNumber: 1, - }, - State: State{ - ChainID("provi"): ChainState{ - Proposals: &map[uint]Proposal{ - 1: ConsumerAdditionProposal{ - Deposit: 10000001, - Chain: ChainID("consu"), - SpawnTime: 0, - InitialHeight: clienttypes.Height{RevisionNumber: 0, RevisionHeight: 1}, - Status: strconv.Itoa(int(gov.ProposalStatus_PROPOSAL_STATUS_PASSED)), - }, - }, + // Update with SpawnTime 0 will trigger launch of consumer chain + Action: UpdateConsumerChainAction{ + Chain: ChainID("provi"), + From: ValidatorID("alice"), + ConsumerChain: ChainID("consu"), + SpawnTime: 0, // launch now + InitialHeight: clienttypes.Height{RevisionNumber: 0, RevisionHeight: 1}, + TopN: 0, + // only "alice" and "bob" are allowlisted (see `getDefaultValidators` in `tests/e2e/config.go`) + Allowlist: []string{ + "cosmosvalcons1qmq08eruchr5sf5s3rwz7djpr5a25f7xw4mceq", + "cosmosvalcons1nx7n5uh0ztxsynn4sje6eyq2ud6rc6klc96w39", }, }, + State: State{}, }, { Action: StartConsumerChainAction{ @@ -1719,33 +1651,18 @@ func stepsValidatorsDenylistedChain() []Step { }, }, { - Action: SubmitConsumerAdditionProposalAction{ - Chain: ChainID("provi"), - From: ValidatorID("alice"), - Deposit: 10000001, - ConsumerChain: ChainID("consu"), - SpawnTime: 0, - InitialHeight: clienttypes.Height{RevisionNumber: 0, RevisionHeight: 1}, - TopN: 0, - // only "bob" is denylisted (see `getDefaultValidators` in `tests/e2e/config.go`) - Denylist: []string{"cosmosvalcons1nx7n5uh0ztxsynn4sje6eyq2ud6rc6klc96w39"}, + Action: CreateConsumerChainAction{ + Chain: ChainID("provi"), + From: ValidatorID("alice"), + ConsumerChain: ChainID("consu"), + SpawnTime: uint(time.Minute * 10), // set spawn-time far in the future + InitialHeight: clienttypes.Height{RevisionNumber: 0, RevisionHeight: 1}, + TopN: 0, + ValidatorSetCap: 2, }, State: State{ ChainID("provi"): ChainState{ - Proposals: &map[uint]Proposal{ - 1: ConsumerAdditionProposal{ - Deposit: 10000001, - Chain: ChainID("consu"), - SpawnTime: 0, - InitialHeight: clienttypes.Height{RevisionNumber: 0, RevisionHeight: 1}, - Status: strconv.Itoa(int(gov.ProposalStatus_PROPOSAL_STATUS_VOTING_PERIOD)), - }, - }, - HasToValidate: &map[ValidatorID][]ChainID{ - ValidatorID("alice"): {}, - ValidatorID("bob"): {}, - ValidatorID("carol"): {}, - }, + ProposedConsumerChains: &[]string{"consu"}, }, }, }, @@ -1809,25 +1726,17 @@ func stepsValidatorsDenylistedChain() []Step { State: State{}, }, { - Action: VoteGovProposalAction{ - Chain: ChainID("provi"), - From: []ValidatorID{ValidatorID("alice"), ValidatorID("bob")}, - Vote: []string{"yes", "yes"}, - PropNumber: 1, - }, - State: State{ - ChainID("provi"): ChainState{ - Proposals: &map[uint]Proposal{ - 1: ConsumerAdditionProposal{ - Deposit: 10000001, - Chain: ChainID("consu"), - SpawnTime: 0, - InitialHeight: clienttypes.Height{RevisionNumber: 0, RevisionHeight: 1}, - Status: strconv.Itoa(int(gov.ProposalStatus_PROPOSAL_STATUS_PASSED)), - }, - }, - }, + // Update with SpawnTime 0 will trigger launch of consumer chain + Action: UpdateConsumerChainAction{ + Chain: ChainID("provi"), + From: ValidatorID("alice"), + ConsumerChain: ChainID("consu"), + SpawnTime: 0, // launch now + InitialHeight: clienttypes.Height{RevisionNumber: 0, RevisionHeight: 1}, + TopN: 0, + Denylist: []string{"cosmosvalcons1nx7n5uh0ztxsynn4sje6eyq2ud6rc6klc96w39"}, }, + State: State{}, }, { Action: StartConsumerChainAction{ @@ -1923,31 +1832,17 @@ func stepsModifyChain() []Step { }, }, { - Action: SubmitConsumerAdditionProposalAction{ + Action: CreateConsumerChainAction{ Chain: ChainID("provi"), From: ValidatorID("alice"), - Deposit: 10000001, ConsumerChain: ChainID("consu"), - SpawnTime: 0, + SpawnTime: uint(time.Minute * 10), // set spawn-time far in the future InitialHeight: clienttypes.Height{RevisionNumber: 0, RevisionHeight: 1}, TopN: 0, }, State: State{ ChainID("provi"): ChainState{ - Proposals: &map[uint]Proposal{ - 1: ConsumerAdditionProposal{ - Deposit: 10000001, - Chain: ChainID("consu"), - SpawnTime: 0, - InitialHeight: clienttypes.Height{RevisionNumber: 0, RevisionHeight: 1}, - Status: strconv.Itoa(int(gov.ProposalStatus_PROPOSAL_STATUS_VOTING_PERIOD)), - }, - }, - HasToValidate: &map[ValidatorID][]ChainID{ - ValidatorID("alice"): {}, - ValidatorID("bob"): {}, - ValidatorID("carol"): {}, - }, + ProposedConsumerChains: &[]string{"consu"}, }, }, }, @@ -2011,25 +1906,16 @@ func stepsModifyChain() []Step { State: State{}, }, { - Action: VoteGovProposalAction{ - Chain: ChainID("provi"), - From: []ValidatorID{ValidatorID("alice"), ValidatorID("bob"), ValidatorID("carol")}, - Vote: []string{"yes", "yes", "yes"}, - PropNumber: 1, - }, - State: State{ - ChainID("provi"): ChainState{ - Proposals: &map[uint]Proposal{ - 1: ConsumerAdditionProposal{ - Deposit: 10000001, - Chain: ChainID("consu"), - SpawnTime: 0, - InitialHeight: clienttypes.Height{RevisionNumber: 0, RevisionHeight: 1}, - Status: strconv.Itoa(int(gov.ProposalStatus_PROPOSAL_STATUS_PASSED)), - }, - }, - }, + // Update with SpawnTime 0 will trigger launch of consumer chain + Action: UpdateConsumerChainAction{ + Chain: ChainID("provi"), + From: ValidatorID("alice"), + ConsumerChain: ChainID("consu"), + SpawnTime: 0, // launch now + InitialHeight: clienttypes.Height{RevisionNumber: 0, RevisionHeight: 1}, + TopN: 0, }, + State: State{}, }, { Action: StartConsumerChainAction{ @@ -2105,43 +1991,16 @@ func stepsModifyChain() []Step { // 1. set `ValidatorsPowerCap` to 40% { - Action: SubmitConsumerModificationProposalAction{ + Action: UpdateConsumerChainAction{ Chain: ChainID("provi"), From: ValidatorID("alice"), - Deposit: 10000001, ConsumerChain: ChainID("consu"), + SpawnTime: 0, + InitialHeight: clienttypes.Height{RevisionNumber: 0, RevisionHeight: 1}, + TopN: 0, ValidatorsPowerCap: 40, }, - State: State{ - ChainID("provi"): ChainState{ - Proposals: &map[uint]Proposal{ - 2: ConsumerModificationProposal{ - Deposit: 10000001, - Chain: ChainID("consu"), - Status: strconv.Itoa(int(gov.ProposalStatus_PROPOSAL_STATUS_VOTING_PERIOD)), - }, - }, - }, - }, - }, - { - Action: VoteGovProposalAction{ - Chain: ChainID("provi"), - From: []ValidatorID{ValidatorID("alice"), ValidatorID("bob"), ValidatorID("carol")}, - Vote: []string{"yes", "yes", "yes"}, - PropNumber: 2, - }, - State: State{ - ChainID("provi"): ChainState{ - Proposals: &map[uint]Proposal{ - 2: ConsumerModificationProposal{ - Deposit: 10000001, - Chain: ChainID("consu"), - Status: strconv.Itoa(int(gov.ProposalStatus_PROPOSAL_STATUS_PASSED)), - }, - }, - }, - }, + State: State{}, }, { Action: RelayPacketsAction{ @@ -2171,43 +2030,16 @@ func stepsModifyChain() []Step { // 2. set the `ValidatorSetCap` to a maximum of 2 validators { - Action: SubmitConsumerModificationProposalAction{ + Action: UpdateConsumerChainAction{ Chain: ChainID("provi"), From: ValidatorID("alice"), - Deposit: 10000001, ConsumerChain: ChainID("consu"), + SpawnTime: 0, + InitialHeight: clienttypes.Height{RevisionNumber: 0, RevisionHeight: 1}, + TopN: 0, ValidatorSetCap: 2, }, - State: State{ - ChainID("provi"): ChainState{ - Proposals: &map[uint]Proposal{ - 3: ConsumerModificationProposal{ - Deposit: 10000001, - Chain: ChainID("consu"), - Status: strconv.Itoa(int(gov.ProposalStatus_PROPOSAL_STATUS_VOTING_PERIOD)), - }, - }, - }, - }, - }, - { - Action: VoteGovProposalAction{ - Chain: ChainID("provi"), - From: []ValidatorID{ValidatorID("alice"), ValidatorID("bob"), ValidatorID("carol")}, - Vote: []string{"yes", "yes", "yes"}, - PropNumber: 3, - }, - State: State{ - ChainID("provi"): ChainState{ - Proposals: &map[uint]Proposal{ - 3: ConsumerModificationProposal{ - Deposit: 10000001, - Chain: ChainID("consu"), - Status: strconv.Itoa(int(gov.ProposalStatus_PROPOSAL_STATUS_PASSED)), - }, - }, - }, - }, + State: State{}, }, { Action: RelayPacketsAction{ @@ -2235,50 +2067,21 @@ func stepsModifyChain() []Step { }, }, }, - // 3. set an allowlist with 2 validators { - Action: SubmitConsumerModificationProposalAction{ + Action: UpdateConsumerChainAction{ Chain: ChainID("provi"), From: ValidatorID("alice"), - Deposit: 10000001, ConsumerChain: ChainID("consu"), - // only "alice" and "carol" are allowlisted (see `getDefaultValidators` in `tests/e2e/config.go`) + SpawnTime: 0, + InitialHeight: clienttypes.Height{RevisionNumber: 0, RevisionHeight: 1}, + TopN: 0, Allowlist: []string{ "cosmosvalcons1qmq08eruchr5sf5s3rwz7djpr5a25f7xw4mceq", "cosmosvalcons1ezyrq65s3gshhx5585w6mpusq3xsj3ayzf4uv6", }, }, - State: State{ - ChainID("provi"): ChainState{ - Proposals: &map[uint]Proposal{ - 4: ConsumerModificationProposal{ - Deposit: 10000001, - Chain: ChainID("consu"), - Status: strconv.Itoa(int(gov.ProposalStatus_PROPOSAL_STATUS_VOTING_PERIOD)), - }, - }, - }, - }, - }, - { - Action: VoteGovProposalAction{ - Chain: ChainID("provi"), - From: []ValidatorID{ValidatorID("alice"), ValidatorID("bob"), ValidatorID("carol")}, - Vote: []string{"yes", "yes", "yes"}, - PropNumber: 4, - }, - State: State{ - ChainID("provi"): ChainState{ - Proposals: &map[uint]Proposal{ - 4: ConsumerModificationProposal{ - Deposit: 10000001, - Chain: ChainID("consu"), - Status: strconv.Itoa(int(gov.ProposalStatus_PROPOSAL_STATUS_PASSED)), - }, - }, - }, - }, + State: State{}, }, { Action: RelayPacketsAction{ @@ -2304,47 +2107,19 @@ func stepsModifyChain() []Step { }, }, }, - // 4. set a denylist with 1 validator { - Action: SubmitConsumerModificationProposalAction{ + Action: UpdateConsumerChainAction{ Chain: ChainID("provi"), From: ValidatorID("alice"), - Deposit: 10000001, ConsumerChain: ChainID("consu"), + SpawnTime: 0, + InitialHeight: clienttypes.Height{RevisionNumber: 0, RevisionHeight: 1}, + TopN: 0, // only "alice" is denylisted (see `getDefaultValidators` in `tests/e2e/config.go`) Denylist: []string{"cosmosvalcons1qmq08eruchr5sf5s3rwz7djpr5a25f7xw4mceq"}, }, - State: State{ - ChainID("provi"): ChainState{ - Proposals: &map[uint]Proposal{ - 5: ConsumerModificationProposal{ - Deposit: 10000001, - Chain: ChainID("consu"), - Status: strconv.Itoa(int(gov.ProposalStatus_PROPOSAL_STATUS_VOTING_PERIOD)), - }, - }, - }, - }, - }, - { - Action: VoteGovProposalAction{ - Chain: ChainID("provi"), - From: []ValidatorID{ValidatorID("alice"), ValidatorID("bob"), ValidatorID("carol")}, - Vote: []string{"yes", "yes", "yes"}, - PropNumber: 5, - }, - State: State{ - ChainID("provi"): ChainState{ - Proposals: &map[uint]Proposal{ - 5: ConsumerModificationProposal{ - Deposit: 10000001, - Chain: ChainID("consu"), - Status: strconv.Itoa(int(gov.ProposalStatus_PROPOSAL_STATUS_PASSED)), - }, - }, - }, - }, + State: State{}, }, { Action: RelayPacketsAction{ @@ -2370,8 +2145,20 @@ func stepsModifyChain() []Step { }, }, }, - // 5. modify the chain from Opt In to Top 100% + // -- Change the owner to governance authority + { + Action: UpdateConsumerChainAction{ + Chain: ChainID("provi"), + From: ValidatorID("alice"), + ConsumerChain: ChainID("consu"), + NewOwner: "cosmos10d07y265gmmuvt4z0w9aw880jnsr700j6zn9kn", + SpawnTime: 0, + InitialHeight: clienttypes.Height{RevisionNumber: 0, RevisionHeight: 1}, + TopN: 0, + }, + State: State{}, + }, { Action: SubmitConsumerModificationProposalAction{ Chain: ChainID("provi"), @@ -2383,7 +2170,7 @@ func stepsModifyChain() []Step { State: State{ ChainID("provi"): ChainState{ Proposals: &map[uint]Proposal{ - 6: ConsumerModificationProposal{ + 1: ConsumerAdditionProposal{ Deposit: 10000001, Chain: ChainID("consu"), Status: strconv.Itoa(int(gov.ProposalStatus_PROPOSAL_STATUS_VOTING_PERIOD)), @@ -2397,12 +2184,12 @@ func stepsModifyChain() []Step { Chain: ChainID("provi"), From: []ValidatorID{ValidatorID("alice"), ValidatorID("bob"), ValidatorID("carol")}, Vote: []string{"yes", "yes", "yes"}, - PropNumber: 6, + PropNumber: 1, }, State: State{ ChainID("provi"): ChainState{ Proposals: &map[uint]Proposal{ - 6: ConsumerModificationProposal{ + 1: ConsumerAdditionProposal{ Deposit: 10000001, Chain: ChainID("consu"), Status: strconv.Itoa(int(gov.ProposalStatus_PROPOSAL_STATUS_PASSED)), diff --git a/tests/e2e/steps_stop_chain.go b/tests/e2e/steps_stop_chain.go index fbf86e4733..9efc240ee6 100644 --- a/tests/e2e/steps_stop_chain.go +++ b/tests/e2e/steps_stop_chain.go @@ -1,10 +1,8 @@ package main import ( - "strconv" - "time" - gov "github.com/cosmos/cosmos-sdk/x/gov/types/v1" + "strconv" ) // start relayer so that all messages are relayed @@ -22,11 +20,10 @@ func stepsStopChain(consumerName string, propNumber uint) []Step { s := []Step{ { Action: SubmitConsumerRemovalProposalAction{ - Chain: ChainID("provi"), - From: ValidatorID("bob"), - Deposit: 10000001, - ConsumerChain: ChainID(consumerName), - StopTimeOffset: 0 * time.Millisecond, + Chain: ChainID("provi"), + From: ValidatorID("bob"), + Deposit: 10000001, + ConsumerChain: ChainID(consumerName), }, State: State{ ChainID("provi"): ChainState{ @@ -35,10 +32,9 @@ func stepsStopChain(consumerName string, propNumber uint) []Step { }, Proposals: &map[uint]Proposal{ propNumber: ConsumerRemovalProposal{ - Deposit: 10000001, - Chain: ChainID(consumerName), - StopTime: 0, - Status: strconv.Itoa(int(gov.ProposalStatus_PROPOSAL_STATUS_VOTING_PERIOD)), + Deposit: 10000001, + Chain: ChainID(consumerName), + Status: strconv.Itoa(int(gov.ProposalStatus_PROPOSAL_STATUS_VOTING_PERIOD)), }, }, ConsumerChains: &map[ChainID]bool{"consu": true}, // consumer chain not yet removed @@ -56,10 +52,9 @@ func stepsStopChain(consumerName string, propNumber uint) []Step { ChainID("provi"): ChainState{ Proposals: &map[uint]Proposal{ propNumber: ConsumerRemovalProposal{ - Deposit: 10000001, - Chain: ChainID(consumerName), - StopTime: 0, - Status: strconv.Itoa(int(gov.ProposalStatus_PROPOSAL_STATUS_PASSED)), + Deposit: 10000001, + Chain: ChainID(consumerName), + Status: strconv.Itoa(int(gov.ProposalStatus_PROPOSAL_STATUS_PASSED)), }, }, ValBalances: &map[ValidatorID]uint{ @@ -80,11 +75,10 @@ func stepsConsumerRemovalPropNotPassing(consumerName string, propNumber uint) [] s := []Step{ { Action: SubmitConsumerRemovalProposalAction{ - Chain: ChainID("provi"), - From: ValidatorID("bob"), - Deposit: 10000001, - ConsumerChain: ChainID(consumerName), - StopTimeOffset: 0 * time.Millisecond, + Chain: ChainID("provi"), + From: ValidatorID("bob"), + Deposit: 10000001, + ConsumerChain: ChainID(consumerName), }, State: State{ ChainID("provi"): ChainState{ @@ -93,10 +87,9 @@ func stepsConsumerRemovalPropNotPassing(consumerName string, propNumber uint) [] }, Proposals: &map[uint]Proposal{ propNumber: ConsumerRemovalProposal{ - Deposit: 10000001, - Chain: ChainID(consumerName), - StopTime: 0, - Status: strconv.Itoa(int(gov.ProposalStatus_PROPOSAL_STATUS_VOTING_PERIOD)), + Deposit: 10000001, + Chain: ChainID(consumerName), + Status: strconv.Itoa(int(gov.ProposalStatus_PROPOSAL_STATUS_VOTING_PERIOD)), }, }, ConsumerChains: &map[ChainID]bool{"consu": true}, // consumer chain not removed @@ -114,10 +107,9 @@ func stepsConsumerRemovalPropNotPassing(consumerName string, propNumber uint) [] ChainID("provi"): ChainState{ Proposals: &map[uint]Proposal{ propNumber: ConsumerRemovalProposal{ - Deposit: 10000001, - Chain: ChainID(consumerName), - StopTime: 0, - Status: strconv.Itoa(int(gov.ProposalStatus_PROPOSAL_STATUS_REJECTED)), + Deposit: 10000001, + Chain: ChainID(consumerName), + Status: strconv.Itoa(int(gov.ProposalStatus_PROPOSAL_STATUS_REJECTED)), }, }, ValBalances: &map[ValidatorID]uint{ diff --git a/tests/e2e/test_driver.go b/tests/e2e/test_driver.go index f65ddfe6ab..6c2bc35d77 100644 --- a/tests/e2e/test_driver.go +++ b/tests/e2e/test_driver.go @@ -79,7 +79,7 @@ func (td *DefaultDriver) getIcsVersion(chainID ChainID) string { func (td *DefaultDriver) getTargetDriver(chainID ChainID) Chain { target := Chain{ - testConfig: td.testCfg, + testConfig: &td.testCfg, } icsVersion := td.getIcsVersion(chainID) switch icsVersion { @@ -95,7 +95,7 @@ func (td *DefaultDriver) getTargetDriver(chainID ChainID) Chain { } default: target.target = Commands{ - containerConfig: td.testCfg.containerConfig, + containerConfig: &td.testCfg.containerConfig, validatorConfigs: td.testCfg.validatorConfigs, chainConfigs: td.testCfg.chainConfigs, target: td.target, @@ -227,12 +227,16 @@ func (td *DefaultDriver) runAction(action interface{}) error { } else { target.submitChangeRewardDenomsProposal(action, td.verbose) } + case CreateConsumerChainAction: + target.createConsumerChain(action, td.verbose) + case UpdateConsumerChainAction: + target.updateConsumerChain(action, td.verbose) case OptInAction: - target.optIn(action, td.target, td.verbose) + target.optIn(action, td.verbose) case OptOutAction: - target.optOut(action, td.target, td.verbose) + target.optOut(action, td.verbose) case SetConsumerCommissionRateAction: - target.setConsumerCommissionRate(action, td.target, td.verbose) + target.setConsumerCommissionRate(action, td.verbose) default: log.Fatalf("unknown action in testRun %s: %#v", td.testCfg.name, action) } diff --git a/tests/e2e/testlib/types.go b/tests/e2e/testlib/types.go index bd7996b988..0c10d8578d 100644 --- a/tests/e2e/testlib/types.go +++ b/tests/e2e/testlib/types.go @@ -12,6 +12,7 @@ import ( type ( ChainID string + ConsumerID string ValidatorID string ) @@ -124,7 +125,8 @@ type ValidatorConfig struct { // Attributes that are unique to a chain. Allows us to map (part of) // the set of strings defined above to a set of viable chains type ChainConfig struct { - ChainId ChainID + ChainId ChainID + ConsumerId ConsumerID // The account prefix configured on the chain. For example, on the Hub, this is "cosmos" AccountPrefix string // Must be unique per chain @@ -304,10 +306,9 @@ func (p UpgradeProposal) isProposal() {} func (p ConsumerAdditionProposal) isProposal() {} type ConsumerRemovalProposal struct { - Deposit uint - Chain ChainID - StopTime int - Status string + Deposit uint + Chain ChainID + Status string } func (p ConsumerRemovalProposal) isProposal() {} diff --git a/tests/e2e/testlib/utils.go b/tests/e2e/testlib/utils.go index 08f410269f..c9d663a3f5 100644 --- a/tests/e2e/testlib/utils.go +++ b/tests/e2e/testlib/utils.go @@ -2,11 +2,60 @@ package e2e import ( "bufio" + "encoding/json" "fmt" "log" "os/exec" + + "github.com/cosmos/cosmos-sdk/codec" + codectypes "github.com/cosmos/cosmos-sdk/codec/types" + sdk "github.com/cosmos/cosmos-sdk/types" ) +// GovernanceProposal is used to generate content to be used for `gov submit-proposal` command +type GovernanceProposal struct { + // Msgs defines an array of sdk.Msgs proto-JSON-encoded as Anys. + Messages []json.RawMessage `json:"messages,omitempty"` + Metadata string `json:"metadata"` + Deposit string `json:"deposit"` + Title string `json:"title"` + Summary string `json:"summary"` + Expedited bool `json:"expedited"` +} + +// GenerateGovProposalContent creates proposal content ready to be used by `gov submit-proposal` command +func GenerateGovProposalContent(title, summary, metadata, deposit, description string, expedited bool, msgs ...sdk.Msg) string { + + // Register the messages. Needed for correct type annotation in the resulting json + modcodec := codec.NewProtoCodec(codectypes.NewInterfaceRegistry()) + modcodec.InterfaceRegistry().RegisterImplementations( + (*sdk.Msg)(nil), + msgs..., + ) + + proposal := GovernanceProposal{ + Metadata: metadata, + Deposit: deposit, + Title: title, + Summary: summary, + Expedited: expedited, + } + + for _, msg := range msgs { + msgJson, err := modcodec.MarshalInterfaceJSON(msg) + if err != nil { + panic(fmt.Errorf("failed marshalling message '%v' for gov proposal: err=%s", msg, err)) + } + proposal.Messages = append(proposal.Messages, msgJson) + } + raw, err := json.MarshalIndent(proposal, "", " ") + if err != nil { + panic(fmt.Errorf("failed to marshal proposal: %w", err)) + } + + return string(raw) +} + func ExecuteCommand(cmd *exec.Cmd, cmdName string, verbose bool) { if verbose { fmt.Println(cmdName+" cmd:", cmd.String()) diff --git a/tests/e2e/trace_handlers_test.go b/tests/e2e/trace_handlers_test.go index e4f9e46f12..a773d00fe5 100644 --- a/tests/e2e/trace_handlers_test.go +++ b/tests/e2e/trace_handlers_test.go @@ -27,10 +27,9 @@ var proposalInStateSteps = []Step{ ChainID("provi"): ChainState{ Proposals: &map[uint]Proposal{ 1: ConsumerRemovalProposal{ - Deposit: 10000001, - Chain: ChainID("foo"), - StopTime: 0, - Status: strconv.Itoa(int(gov.ProposalStatus_PROPOSAL_STATUS_VOTING_PERIOD)), + Deposit: 10000001, + Chain: ChainID("foo"), + Status: strconv.Itoa(int(gov.ProposalStatus_PROPOSAL_STATUS_VOTING_PERIOD)), }, }, }, @@ -136,10 +135,9 @@ func TestMarshalAndUnmarshalChainState(t *testing.T) { "consumer removal proposal": {ChainState{ Proposals: &map[uint]Proposal{ 5: ConsumerRemovalProposal{ - Deposit: 10000001, - Chain: ChainID("test123"), - StopTime: 5000000000, - Status: strconv.Itoa(int(gov.ProposalStatus_PROPOSAL_STATUS_PASSED)), + Deposit: 10000001, + Chain: ChainID("test123"), + Status: strconv.Itoa(int(gov.ProposalStatus_PROPOSAL_STATUS_PASSED)), }, }, ValBalances: &map[ValidatorID]uint{ diff --git a/tests/e2e/v4/state.go b/tests/e2e/v4/state.go index 594004bc24..b4b7b70190 100644 --- a/tests/e2e/v4/state.go +++ b/tests/e2e/v4/state.go @@ -317,7 +317,6 @@ func (tr Commands) GetProposal(chain ChainID, proposal uint) Proposal { } case "/interchain_security.ccv.provider.v1.ConsumerRemovalProposal": chainId := gjson.Get(string(bz), `messages.0.content.chain_id`).String() - stopTime := gjson.Get(string(bz), `messages.0.content.stop_time`).Time().Sub(containerConfig.Now) var chain ChainID for i, conf := range chainConfigs { @@ -328,10 +327,9 @@ func (tr Commands) GetProposal(chain ChainID, proposal uint) Proposal { } return ConsumerRemovalProposal{ - Deposit: uint(deposit), - Status: status, - Chain: chain, - StopTime: int(stopTime.Milliseconds()), + Deposit: uint(deposit), + Status: status, + Chain: chain, } case "/cosmos.params.v1beta1.ParameterChangeProposal": return ParamsProposal{ @@ -391,7 +389,6 @@ func (tr Commands) GetParam(chain ChainID, param Param) string { func (tr Commands) GetConsumerChains(chain ChainID) map[ChainID]bool { binaryName := tr.ChainConfigs[chain].BinaryName cmd := tr.Target.ExecCommand(binaryName, - "query", "provider", "list-consumer-chains", `--node`, tr.GetQueryNode(chain), `-o`, `json`, diff --git a/tests/integration/common.go b/tests/integration/common.go index 46ef499d01..97cd3fbf29 100644 --- a/tests/integration/common.go +++ b/tests/integration/common.go @@ -42,7 +42,7 @@ func (s *CCVTestSuite) getFirstBundle() icstestingutils.ConsumerBundle { } func (s *CCVTestSuite) getBundleByIdx(index int) icstestingutils.ConsumerBundle { - return *s.consumerBundles[ibctesting.GetChainID(2+index)] + return *s.consumerBundles[fmt.Sprintf("%d", index)] } func (s *CCVTestSuite) providerCtx() sdk.Context { diff --git a/tests/integration/distribution.go b/tests/integration/distribution.go index 8fecaccfc8..316b343f0a 100644 --- a/tests/integration/distribution.go +++ b/tests/integration/distribution.go @@ -125,7 +125,7 @@ func (s *CCVTestSuite) TestRewardsDistribution() { // Save the consumer validators total outstanding rewards on the provider consumerValsOutstandingRewardsFunc := func(ctx sdk.Context) sdk.DecCoins { totalRewards := sdk.DecCoins{} - vals, err := providerKeeper.GetConsumerValSet(ctx, s.consumerChain.ChainID) + vals, err := providerKeeper.GetConsumerValSet(ctx, s.getFirstBundle().ConsumerId) s.Require().NoError(err) for _, v := range vals { @@ -160,7 +160,7 @@ func (s *CCVTestSuite) TestRewardsDistribution() { // Consumer allocations are distributed between the validators and the community pool. // The decimals resulting from the distribution are expected to remain in the consumer allocations. - rewardsAlloc := providerKeeper.GetConsumerRewardsAllocation(s.providerCtx(), s.consumerChain.ChainID) + rewardsAlloc := providerKeeper.GetConsumerRewardsAllocation(s.providerCtx(), s.getFirstBundle().ConsumerId) remainingAlloc := rewardsAlloc.Rewards.AmountOf(rewardsIBCdenom) s.Require().True(remainingAlloc.LTE(math.LegacyOneDec())) @@ -601,7 +601,7 @@ func (s *CCVTestSuite) TestIBCTransferMiddleware() { // update consumer allocation keeper.SetConsumerRewardsAllocation( ctx, - s.consumerChain.ChainID, + s.getFirstBundle().ConsumerId, providertypes.ConsumerRewardsAllocation{ Rewards: sdk.NewDecCoins(sdk.NewDecCoin(sdk.DefaultBondDenom, math.NewInt(100_000))), }, @@ -668,7 +668,7 @@ func (s *CCVTestSuite) TestIBCTransferMiddleware() { rewardsPoolBalance := bankKeeper.GetAllBalances(s.providerCtx(), sdk.MustAccAddressFromBech32(data.Receiver)) // save the consumer's rewards allocated - consumerRewardsAllocations := providerKeeper.GetConsumerRewardsAllocation(s.providerCtx(), s.consumerChain.ChainID) + consumerRewardsAllocations := providerKeeper.GetConsumerRewardsAllocation(s.providerCtx(), s.getFirstBundle().ConsumerId) // execute middleware OnRecvPacket logic ack := cbs.OnRecvPacket(s.providerCtx(), packet, sdk.AccAddress{}) @@ -682,7 +682,7 @@ func (s *CCVTestSuite) TestIBCTransferMiddleware() { // compute the balance and allocation difference rewardsTransferred := bankKeeper.GetAllBalances(s.providerCtx(), sdk.MustAccAddressFromBech32(data.Receiver)). Sub(rewardsPoolBalance...) - rewardsAllocated := providerKeeper.GetConsumerRewardsAllocation(s.providerCtx(), s.consumerChain.ChainID). + rewardsAllocated := providerKeeper.GetConsumerRewardsAllocation(s.providerCtx(), s.getFirstBundle().ConsumerId). Rewards.Sub(consumerRewardsAllocations.Rewards) if !tc.expErr { @@ -739,11 +739,11 @@ func (s *CCVTestSuite) TestAllocateTokens() { // Allocate rewards evenly between consumers rewardsPerChain := totalRewards.QuoInt(math.NewInt(int64(len(s.consumerBundles)))) - for chainID := range s.consumerBundles { + for consumerId := range s.consumerBundles { // update consumer allocation providerKeeper.SetConsumerRewardsAllocation( providerCtx, - chainID, + consumerId, providertypes.ConsumerRewardsAllocation{ Rewards: sdk.NewDecCoinsFromCoins(rewardsPerChain...), }, @@ -797,7 +797,7 @@ func (s *CCVTestSuite) TestAllocateTokens() { // check that the total expected rewards are transferred to the distribution module account // store the decimal remainders in the consumer reward allocations - allocRemainderPerChain := providerKeeper.GetConsumerRewardsAllocation(providerCtx, s.consumerChain.ChainID).Rewards + allocRemainderPerChain := providerKeeper.GetConsumerRewardsAllocation(providerCtx, s.getFirstBundle().ConsumerId).Rewards // compute the total rewards distributed to the distribution module balance (validator outstanding rewards + community pool tax), totalRewardsDistributed := sdk.NewDecCoinsFromCoins(totalRewards...).Sub(allocRemainderPerChain.MulDec(math.LegacyNewDec(int64(consNum)))) @@ -843,7 +843,7 @@ func (s *CCVTestSuite) TestAllocateTokensToConsumerValidators() { distributionKeeper := s.providerApp.GetTestDistributionKeeper() bankKeeper := s.providerApp.GetTestBankKeeper() - chainID := s.consumerChain.ChainID + consumerId := s.getFirstBundle().ConsumerId testCases := []struct { name string @@ -889,11 +889,11 @@ func (s *CCVTestSuite) TestAllocateTokensToConsumerValidators() { ctx.BlockHeight()) // change the consumer valset - consuVals, err := providerKeeper.GetConsumerValSet(ctx, chainID) + consuVals, err := providerKeeper.GetConsumerValSet(ctx, consumerId) s.Require().NoError(err) - providerKeeper.DeleteConsumerValSet(ctx, chainID) - providerKeeper.SetConsumerValSet(ctx, chainID, consuVals[0:tc.consuValLen]) - consuVals, err = providerKeeper.GetConsumerValSet(ctx, chainID) + providerKeeper.DeleteConsumerValSet(ctx, consumerId) + providerKeeper.SetConsumerValSet(ctx, consumerId, consuVals[0:tc.consuValLen]) + consuVals, err = providerKeeper.GetConsumerValSet(ctx, consumerId) s.Require().NoError(err) // set the same consumer commission rate for all consumer validators @@ -901,7 +901,7 @@ func (s *CCVTestSuite) TestAllocateTokensToConsumerValidators() { provAddr := providertypes.NewProviderConsAddress(sdk.ConsAddress(v.ProviderConsAddr)) err := providerKeeper.SetConsumerCommissionRate( ctx, - chainID, + consumerId, provAddr, tc.rate, ) @@ -911,7 +911,7 @@ func (s *CCVTestSuite) TestAllocateTokensToConsumerValidators() { // allocate tokens res := providerKeeper.AllocateTokensToConsumerValidators( ctx, - chainID, + consumerId, tc.tokens, ) @@ -981,7 +981,7 @@ func (s *CCVTestSuite) TestAllocateTokensToConsumerValidatorsWithDifferentValida distributionKeeper := s.providerApp.GetTestDistributionKeeper() bankKeeper := s.providerApp.GetTestBankKeeper() - chainID := s.consumerChain.ChainID + consumerId := s.getFirstBundle().ConsumerId tokens := sdk.DecCoins{sdk.NewDecCoinFromDec(sdk.DefaultBondDenom, math.LegacyNewDecFromIntWithPrec(math.NewInt(999), 2))} rate := math.LegacyOneDec() @@ -994,7 +994,7 @@ func (s *CCVTestSuite) TestAllocateTokensToConsumerValidatorsWithDifferentValida ctx = ctx.WithBlockHeight(providerKeeper.GetNumberOfEpochsToStartReceivingRewards(ctx)*providerKeeper.GetBlocksPerEpoch(ctx) + 1) // update the consumer validators - consuVals, err := providerKeeper.GetConsumerValSet(ctx, chainID) + consuVals, err := providerKeeper.GetConsumerValSet(ctx, consumerId) s.Require().NoError(err) // first 2 validators were consumer validators since block height 1 and hence get rewards consuVals[0].JoinHeight = 1 @@ -1003,11 +1003,11 @@ func (s *CCVTestSuite) TestAllocateTokensToConsumerValidatorsWithDifferentValida // have not been consumer validators for `GetNumberOfEpochsToStartReceivingRewards * GetBlocksPerEpoch` blocks consuVals[2].JoinHeight = 2 consuVals[3].JoinHeight = 2 - providerKeeper.SetConsumerValSet(ctx, chainID, consuVals) + providerKeeper.SetConsumerValSet(ctx, consumerId, consuVals) - providerKeeper.DeleteConsumerValSet(ctx, chainID) - providerKeeper.SetConsumerValSet(ctx, chainID, consuVals) - consuVals, err = providerKeeper.GetConsumerValSet(ctx, chainID) + providerKeeper.DeleteConsumerValSet(ctx, consumerId) + providerKeeper.SetConsumerValSet(ctx, consumerId, consuVals) + consuVals, err = providerKeeper.GetConsumerValSet(ctx, consumerId) s.Require().NoError(err) // set the same consumer commission rate for all consumer validators @@ -1015,7 +1015,7 @@ func (s *CCVTestSuite) TestAllocateTokensToConsumerValidatorsWithDifferentValida provAddr := providertypes.NewProviderConsAddress(sdk.ConsAddress(v.ProviderConsAddr)) err := providerKeeper.SetConsumerCommissionRate( ctx, - chainID, + consumerId, provAddr, rate, ) @@ -1025,7 +1025,7 @@ func (s *CCVTestSuite) TestAllocateTokensToConsumerValidatorsWithDifferentValida // allocate tokens res := providerKeeper.AllocateTokensToConsumerValidators( ctx, - chainID, + consumerId, tokens, ) @@ -1101,8 +1101,8 @@ func (s *CCVTestSuite) TestMultiConsumerRewardsDistribution() { // Iterate over the consumers and perform the reward distribution // to the provider - for chainID := range s.consumerBundles { - bundle := s.consumerBundles[chainID] + for consumerId := range s.consumerBundles { + bundle := s.consumerBundles[consumerId] consumerKeeper := bundle.App.GetConsumerKeeper() bankKeeper := bundle.App.GetTestBankKeeper() accountKeeper := bundle.App.GetTestAccountKeeper() diff --git a/tests/integration/double_vote.go b/tests/integration/double_vote.go index 2f275fd95c..b4c9f82c10 100644 --- a/tests/integration/double_vote.go +++ b/tests/integration/double_vote.go @@ -42,7 +42,7 @@ func (s *CCVTestSuite) TestHandleConsumerDoubleVoting() { equivocationEvidenceMinHeight := uint64(s.consumerCtx().BlockHeight() - 1) s.providerApp.GetProviderKeeper().SetEquivocationEvidenceMinHeight( s.providerCtx(), - s.consumerChain.ChainID, + s.getFirstBundle().ConsumerId, equivocationEvidenceMinHeight, ) @@ -56,7 +56,7 @@ func (s *CCVTestSuite) TestHandleConsumerDoubleVoting() { s.consumerCtx().BlockTime(), consuValSet, consuSigner, - s.consumerChain.ChainID, + s.getFirstBundle().Chain.ChainID, ) consuBadVote := testutil.MakeAndSignVote( @@ -65,7 +65,7 @@ func (s *CCVTestSuite) TestHandleConsumerDoubleVoting() { s.consumerCtx().BlockTime(), consuValSet, consuSigner, - s.consumerChain.ChainID, + s.getFirstBundle().Chain.ChainID, ) // create two votes using the provider validator key @@ -75,7 +75,7 @@ func (s *CCVTestSuite) TestHandleConsumerDoubleVoting() { s.consumerCtx().BlockTime(), provValSet, provSigner, - s.consumerChain.ChainID, + s.getFirstBundle().Chain.ChainID, ) provBadVote := testutil.MakeAndSignVote( @@ -84,7 +84,7 @@ func (s *CCVTestSuite) TestHandleConsumerDoubleVoting() { s.consumerCtx().BlockTime(), provValSet, provSigner, - s.consumerChain.ChainID, + s.getFirstBundle().Chain.ChainID, ) // create two votes using the consumer validator key that both have @@ -95,7 +95,7 @@ func (s *CCVTestSuite) TestHandleConsumerDoubleVoting() { s.consumerCtx().BlockTime(), consuValSet, consuSigner, - s.consumerChain.ChainID, + s.getFirstBundle().Chain.ChainID, ) consuVoteOld2 := testutil.MakeAndSignVote( @@ -104,15 +104,15 @@ func (s *CCVTestSuite) TestHandleConsumerDoubleVoting() { s.consumerCtx().BlockTime(), consuValSet, consuSigner, - s.consumerChain.ChainID, + s.getFirstBundle().Chain.ChainID, ) testCases := []struct { - name string - ev *tmtypes.DuplicateVoteEvidence - chainID string - pubkey tmcrypto.PubKey - expPass bool + name string + ev *tmtypes.DuplicateVoteEvidence + consumerId string + pubkey tmcrypto.PubKey + expPass bool }{ { "cannot find consumer chain for the given chain ID - shouldn't pass", @@ -123,7 +123,7 @@ func (s *CCVTestSuite) TestHandleConsumerDoubleVoting() { TotalVotingPower: consuVal.VotingPower, Timestamp: s.consumerCtx().BlockTime(), }, - "chainID", + "consumerId", consuVal.PubKey, false, }, @@ -136,7 +136,7 @@ func (s *CCVTestSuite) TestHandleConsumerDoubleVoting() { TotalVotingPower: consuVal.VotingPower, Timestamp: s.consumerCtx().BlockTime(), }, - s.consumerChain.ChainID, + s.getFirstBundle().ConsumerId, consuVal.PubKey, false, }, @@ -149,7 +149,7 @@ func (s *CCVTestSuite) TestHandleConsumerDoubleVoting() { TotalVotingPower: consuVal.VotingPower, Timestamp: s.consumerCtx().BlockTime(), }, - s.consumerChain.ChainID, + s.getFirstBundle().ConsumerId, consuVal.PubKey, false, }, @@ -162,7 +162,7 @@ func (s *CCVTestSuite) TestHandleConsumerDoubleVoting() { TotalVotingPower: consuVal.VotingPower, Timestamp: s.consumerCtx().BlockTime(), }, - s.consumerChain.ChainID, + s.getFirstBundle().ConsumerId, provVal.PubKey, false, }, @@ -176,7 +176,7 @@ func (s *CCVTestSuite) TestHandleConsumerDoubleVoting() { TotalVotingPower: consuVal.VotingPower, Timestamp: s.consumerCtx().BlockTime(), }, - s.consumerChain.ChainID, + s.getFirstBundle().ConsumerId, consuVal.PubKey, false, }, @@ -193,7 +193,7 @@ func (s *CCVTestSuite) TestHandleConsumerDoubleVoting() { TotalVotingPower: consuVal.VotingPower, Timestamp: s.consumerCtx().BlockTime(), }, - s.consumerChain.ChainID, + s.getFirstBundle().ConsumerId, consuVal.PubKey, true, }, @@ -207,7 +207,7 @@ func (s *CCVTestSuite) TestHandleConsumerDoubleVoting() { TotalVotingPower: consuVal.VotingPower, Timestamp: s.consumerCtx().BlockTime(), }, - s.consumerChain.ChainID, + s.getFirstBundle().ConsumerId, provVal.PubKey, true, }, @@ -216,7 +216,7 @@ func (s *CCVTestSuite) TestHandleConsumerDoubleVoting() { for _, tc := range testCases { s.Run(tc.name, func() { consuAddr := types.NewConsumerConsAddress(sdk.ConsAddress(tc.ev.VoteA.ValidatorAddress.Bytes())) - provAddr := s.providerApp.GetProviderKeeper().GetProviderAddrFromConsumerAddr(s.providerCtx(), s.consumerChain.ChainID, consuAddr) + provAddr := s.providerApp.GetProviderKeeper().GetProviderAddrFromConsumerAddr(s.providerCtx(), s.getFirstBundle().ConsumerId, consuAddr) validator, _ := s.providerApp.GetTestStakingKeeper().GetValidator(s.providerCtx(), provAddr.ToSdkConsAddr().Bytes()) initialTokens := math.LegacyNewDecFromInt(validator.GetTokens()) @@ -228,7 +228,7 @@ func (s *CCVTestSuite) TestHandleConsumerDoubleVoting() { // we remove the consumer key assigned to the validator otherwise // HandleConsumerDoubleVoting uses the consumer key to verify the signature if tc.ev.VoteA.ValidatorAddress.String() != consuVal.Address.String() { - s.providerApp.GetProviderKeeper().DeleteKeyAssignments(provCtx, s.consumerChain.ChainID) + s.providerApp.GetProviderKeeper().DeleteKeyAssignments(provCtx, s.getFirstBundle().ConsumerId) } // convert validator public key @@ -237,8 +237,8 @@ func (s *CCVTestSuite) TestHandleConsumerDoubleVoting() { err = s.providerApp.GetProviderKeeper().HandleConsumerDoubleVoting( provCtx, + tc.consumerId, tc.ev, - tc.chainID, pk, ) @@ -296,7 +296,7 @@ func (s *CCVTestSuite) TestHandleConsumerDoubleVotingSlashesUndelegationsAndRele s.consumerCtx().BlockTime(), consuValSet, consuSigner, - s.consumerChain.ChainID, + s.getFirstBundle().Chain.ChainID, ) consuBadVote := testutil.MakeAndSignVote( @@ -305,7 +305,7 @@ func (s *CCVTestSuite) TestHandleConsumerDoubleVotingSlashesUndelegationsAndRele s.consumerCtx().BlockTime(), consuValSet, consuSigner, - s.consumerChain.ChainID, + s.getFirstBundle().Chain.ChainID, ) // In order to create an evidence for a consumer chain, @@ -320,14 +320,13 @@ func (s *CCVTestSuite) TestHandleConsumerDoubleVotingSlashesUndelegationsAndRele Timestamp: s.consumerCtx().BlockTime(), } - chainID := s.consumerChain.ChainID pubKey := consuVal.PubKey consuAddr := types.NewConsumerConsAddress(sdk.ConsAddress(consuVal.Address.Bytes())) - provAddr := s.providerApp.GetProviderKeeper().GetProviderAddrFromConsumerAddr(s.providerCtx(), s.consumerChain.ChainID, consuAddr) + provAddr := s.providerApp.GetProviderKeeper().GetProviderAddrFromConsumerAddr(s.providerCtx(), s.getFirstBundle().ConsumerId, consuAddr) consuAddr2 := types.NewConsumerConsAddress(sdk.ConsAddress(consuVal2.Address.Bytes())) - provAddr2 := s.providerApp.GetProviderKeeper().GetProviderAddrFromConsumerAddr(s.providerCtx(), s.consumerChain.ChainID, consuAddr2) + provAddr2 := s.providerApp.GetProviderKeeper().GetProviderAddrFromConsumerAddr(s.providerCtx(), s.getFirstBundle().ConsumerId, consuAddr2) validator, err := s.providerApp.GetTestStakingKeeper().GetValidator(s.providerCtx(), provAddr.ToSdkConsAddr().Bytes()) s.Require().NoError(err) @@ -392,8 +391,8 @@ func (s *CCVTestSuite) TestHandleConsumerDoubleVotingSlashesUndelegationsAndRele // cause double voting err = s.providerApp.GetProviderKeeper().HandleConsumerDoubleVoting( s.providerCtx(), + s.getFirstBundle().ConsumerId, evidence, - chainID, pk, ) s.Require().NoError(err) diff --git a/tests/integration/expired_client.go b/tests/integration/expired_client.go index e5c6099203..3d662382e1 100644 --- a/tests/integration/expired_client.go +++ b/tests/integration/expired_client.go @@ -36,7 +36,7 @@ func (s *CCVTestSuite) TestVSCPacketSendExpiredClient() { s.nextEpoch() // check that the packet was added to the list of pending VSC packets - packets := providerKeeper.GetPendingVSCPackets(s.providerCtx(), s.consumerChain.ChainID) + packets := providerKeeper.GetPendingVSCPackets(s.providerCtx(), s.getFirstBundle().ConsumerId) s.Require().NotEmpty(packets, "no pending VSC packets found") s.Require().Equal(1, len(packets), "unexpected number of pending VSC packets") @@ -44,7 +44,7 @@ func (s *CCVTestSuite) TestVSCPacketSendExpiredClient() { s.nextEpoch() // check that the packet is still in the list of pending VSC packets - packets = providerKeeper.GetPendingVSCPackets(s.providerCtx(), s.consumerChain.ChainID) + packets = providerKeeper.GetPendingVSCPackets(s.providerCtx(), s.getFirstBundle().ConsumerId) s.Require().NotEmpty(packets, "no pending VSC packets found") s.Require().Equal(1, len(packets), "unexpected number of pending VSC packets") @@ -55,7 +55,7 @@ func (s *CCVTestSuite) TestVSCPacketSendExpiredClient() { s.nextEpoch() // check that the packets are still in the list of pending VSC packets - packets = providerKeeper.GetPendingVSCPackets(s.providerCtx(), s.consumerChain.ChainID) + packets = providerKeeper.GetPendingVSCPackets(s.providerCtx(), s.getFirstBundle().ConsumerId) s.Require().NotEmpty(packets, "no pending VSC packets found") s.Require().Equal(2, len(packets), "unexpected number of pending VSC packets") @@ -66,7 +66,7 @@ func (s *CCVTestSuite) TestVSCPacketSendExpiredClient() { s.nextEpoch() // check that the packets are not in the list of pending VSC packets - packets = providerKeeper.GetPendingVSCPackets(s.providerCtx(), s.consumerChain.ChainID) + packets = providerKeeper.GetPendingVSCPackets(s.providerCtx(), s.getFirstBundle().ConsumerId) s.Require().Empty(packets, "unexpected pending VSC packets found") // check that validator updates work @@ -105,7 +105,7 @@ func (s *CCVTestSuite) TestConsumerPacketSendExpiredClient() { s.nextEpoch() // check that the packets are not in the list of pending VSC packets - providerPackets := providerKeeper.GetPendingVSCPackets(s.providerCtx(), s.consumerChain.ChainID) + providerPackets := providerKeeper.GetPendingVSCPackets(s.providerCtx(), s.getFirstBundle().ConsumerId) s.Require().Empty(providerPackets, "pending VSC packets found") // relay all VSC packet from provider to consumer diff --git a/tests/integration/key_assignment.go b/tests/integration/key_assignment.go index c6478d98ba..73defc1b57 100644 --- a/tests/integration/key_assignment.go +++ b/tests/integration/key_assignment.go @@ -24,14 +24,14 @@ func (s *CCVTestSuite) TestKeyAssignment() { "assignment during channel init", func(pk *providerkeeper.Keeper) error { // key assignment validator, consumerKey := generateNewConsumerKey(s, 0) - err := pk.AssignConsumerKey(s.providerCtx(), s.consumerChain.ChainID, validator, consumerKey) + err := pk.AssignConsumerKey(s.providerCtx(), s.getFirstBundle().ConsumerId, validator, consumerKey) if err != nil { return err } // check that a VSCPacket is queued s.nextEpoch() - pendingPackets := pk.GetPendingVSCPackets(s.providerCtx(), s.consumerChain.ChainID) + pendingPackets := pk.GetPendingVSCPackets(s.providerCtx(), s.getFirstBundle().ConsumerId) s.Require().Len(pendingPackets, 1) // establish CCV channel @@ -47,7 +47,7 @@ func (s *CCVTestSuite) TestKeyAssignment() { // key assignment validator, consumerKey := generateNewConsumerKey(s, 0) - err := pk.AssignConsumerKey(s.providerCtx(), s.consumerChain.ChainID, validator, consumerKey) + err := pk.AssignConsumerKey(s.providerCtx(), s.getFirstBundle().ConsumerId, validator, consumerKey) if err != nil { return err } @@ -63,7 +63,7 @@ func (s *CCVTestSuite) TestKeyAssignment() { // key assignment validator, consumerKey := generateNewConsumerKey(s, 0) - err := pk.AssignConsumerKey(s.providerCtx(), s.consumerChain.ChainID, validator, consumerKey) + err := pk.AssignConsumerKey(s.providerCtx(), s.getFirstBundle().ConsumerId, validator, consumerKey) if err != nil { return err } @@ -85,14 +85,14 @@ func (s *CCVTestSuite) TestKeyAssignment() { // key assignment validator, consumerKey := generateNewConsumerKey(s, 0) - err := pk.AssignConsumerKey(s.providerCtx(), s.consumerChain.ChainID, validator, consumerKey) + err := pk.AssignConsumerKey(s.providerCtx(), s.getFirstBundle().ConsumerId, validator, consumerKey) if err != nil { return err } // same key assignment, but different validator validator2, _ := generateNewConsumerKey(s, 1) - err = pk.AssignConsumerKey(s.providerCtx(), s.consumerChain.ChainID, validator2, consumerKey) + err = pk.AssignConsumerKey(s.providerCtx(), s.getFirstBundle().ConsumerId, validator2, consumerKey) if err != nil { return err } @@ -108,13 +108,13 @@ func (s *CCVTestSuite) TestKeyAssignment() { // key assignment validator, consumerKey := generateNewConsumerKey(s, 0) - err := pk.AssignConsumerKey(s.providerCtx(), s.consumerChain.ChainID, validator, consumerKey) + err := pk.AssignConsumerKey(s.providerCtx(), s.getFirstBundle().ConsumerId, validator, consumerKey) if err != nil { return err } // same key assignment, but different validator - err = pk.AssignConsumerKey(s.providerCtx(), s.consumerChain.ChainID, validator, consumerKey) + err = pk.AssignConsumerKey(s.providerCtx(), s.getFirstBundle().ConsumerId, validator, consumerKey) if err != nil { return err } @@ -130,14 +130,14 @@ func (s *CCVTestSuite) TestKeyAssignment() { // key assignment validator, consumerKey := generateNewConsumerKey(s, 0) - err := pk.AssignConsumerKey(s.providerCtx(), s.consumerChain.ChainID, validator, consumerKey) + err := pk.AssignConsumerKey(s.providerCtx(), s.getFirstBundle().ConsumerId, validator, consumerKey) if err != nil { return err } // same key assignment validator, consumerKey = generateNewConsumerKey(s, 0) - err = pk.AssignConsumerKey(s.providerCtx(), s.consumerChain.ChainID, validator, consumerKey) + err = pk.AssignConsumerKey(s.providerCtx(), s.getFirstBundle().ConsumerId, validator, consumerKey) if err != nil { return err } @@ -153,7 +153,7 @@ func (s *CCVTestSuite) TestKeyAssignment() { // key assignment validator, consumerKey := generateNewConsumerKey(s, 0) - err := pk.AssignConsumerKey(s.providerCtx(), s.consumerChain.ChainID, validator, consumerKey) + err := pk.AssignConsumerKey(s.providerCtx(), s.getFirstBundle().ConsumerId, validator, consumerKey) if err != nil { return err } @@ -161,7 +161,7 @@ func (s *CCVTestSuite) TestKeyAssignment() { // same key assignment validator2, _ := generateNewConsumerKey(s, 1) - err = pk.AssignConsumerKey(s.providerCtx(), s.consumerChain.ChainID, validator2, consumerKey) + err = pk.AssignConsumerKey(s.providerCtx(), s.getFirstBundle().ConsumerId, validator2, consumerKey) if err != nil { return err } @@ -177,14 +177,14 @@ func (s *CCVTestSuite) TestKeyAssignment() { // key assignment validator, consumerKey := generateNewConsumerKey(s, 0) - err := pk.AssignConsumerKey(s.providerCtx(), s.consumerChain.ChainID, validator, consumerKey) + err := pk.AssignConsumerKey(s.providerCtx(), s.getFirstBundle().ConsumerId, validator, consumerKey) if err != nil { return err } s.nextEpoch() // same key assignment - err = pk.AssignConsumerKey(s.providerCtx(), s.consumerChain.ChainID, validator, consumerKey) + err = pk.AssignConsumerKey(s.providerCtx(), s.getFirstBundle().ConsumerId, validator, consumerKey) if err != nil { return err } @@ -200,7 +200,7 @@ func (s *CCVTestSuite) TestKeyAssignment() { // key assignment validator, consumerKey := generateNewConsumerKey(s, 0) - err := pk.AssignConsumerKey(s.providerCtx(), s.consumerChain.ChainID, validator, consumerKey) + err := pk.AssignConsumerKey(s.providerCtx(), s.getFirstBundle().ConsumerId, validator, consumerKey) if err != nil { return err } @@ -208,7 +208,7 @@ func (s *CCVTestSuite) TestKeyAssignment() { // same key assignment validator, consumerKey = generateNewConsumerKey(s, 0) - err = pk.AssignConsumerKey(s.providerCtx(), s.consumerChain.ChainID, validator, consumerKey) + err = pk.AssignConsumerKey(s.providerCtx(), s.getFirstBundle().ConsumerId, validator, consumerKey) if err != nil { return err } diff --git a/tests/integration/misbehaviour.go b/tests/integration/misbehaviour.go index 5924c90df1..127b3a23a3 100644 --- a/tests/integration/misbehaviour.go +++ b/tests/integration/misbehaviour.go @@ -34,7 +34,7 @@ func (s *CCVTestSuite) TestHandleConsumerMisbehaviour() { misb := &ibctmtypes.Misbehaviour{ ClientId: s.path.EndpointA.ClientID, Header1: s.consumerChain.CreateTMClientHeader( - s.consumerChain.ChainID, + s.getFirstBundle().Chain.ChainID, int64(clientHeight.RevisionHeight+1), clientHeight, altTime, @@ -46,7 +46,7 @@ func (s *CCVTestSuite) TestHandleConsumerMisbehaviour() { // create a different header by changing the header timestamp only // in order to create an equivocation, i.e. both headers have the same deterministic states Header2: s.consumerChain.CreateTMClientHeader( - s.consumerChain.ChainID, + s.getFirstBundle().Chain.ChainID, int64(clientHeight.RevisionHeight+1), clientHeight, altTime.Add(10*time.Second), @@ -61,13 +61,13 @@ func (s *CCVTestSuite) TestHandleConsumerMisbehaviour() { validator, _ := s.getValByIdx(0) initialTokens := math.LegacyNewDecFromInt(validator.GetTokens()) - err := s.providerApp.GetProviderKeeper().HandleConsumerMisbehaviour(s.providerCtx(), *misb) + err := s.providerApp.GetProviderKeeper().HandleConsumerMisbehaviour(s.providerCtx(), s.getFirstBundle().ConsumerId, *misb) s.NoError(err) // verify that validators are jailed, tombstoned, and slashed for _, v := range clientTMValset.Validators { consuAddr := sdk.ConsAddress(v.Address.Bytes()) - provAddr := s.providerApp.GetProviderKeeper().GetProviderAddrFromConsumerAddr(s.providerCtx(), s.consumerChain.ChainID, types.NewConsumerConsAddress(consuAddr)) + provAddr := s.providerApp.GetProviderKeeper().GetProviderAddrFromConsumerAddr(s.providerCtx(), s.getFirstBundle().ConsumerId, types.NewConsumerConsAddress(consuAddr)) val, err := s.providerApp.GetTestStakingKeeper().GetValidatorByConsAddr(s.providerCtx(), provAddr.Address) s.Require().NoError(err) s.Require().True(val.Jailed) @@ -102,7 +102,7 @@ func (s *CCVTestSuite) TestGetByzantineValidators() { // create a consumer client header clientHeader := s.consumerChain.CreateTMClientHeader( - s.consumerChain.ChainID, + s.getFirstBundle().Chain.ChainID, int64(clientHeight.RevisionHeight+1), clientHeight, altTime, @@ -144,7 +144,7 @@ func (s *CCVTestSuite) TestGetByzantineValidators() { "incorrect valset - shouldn't pass", func() *ibctmtypes.Misbehaviour { clientHeader := s.consumerChain.CreateTMClientHeader( - s.consumerChain.ChainID, + s.getFirstBundle().Chain.ChainID, int64(clientHeight.RevisionHeight+1), clientHeight, altTime.Add(time.Minute), @@ -155,7 +155,7 @@ func (s *CCVTestSuite) TestGetByzantineValidators() { ) clientHeaderWithCorruptedValset := s.consumerChain.CreateTMClientHeader( - s.consumerChain.ChainID, + s.getFirstBundle().Chain.ChainID, int64(clientHeight.RevisionHeight+1), clientHeight, altTime.Add(time.Hour), @@ -181,7 +181,7 @@ func (s *CCVTestSuite) TestGetByzantineValidators() { "incorrect valset 2 - shouldn't pass", func() *ibctmtypes.Misbehaviour { clientHeader := s.consumerChain.CreateTMClientHeader( - s.consumerChain.ChainID, + s.getFirstBundle().Chain.ChainID, int64(clientHeight.RevisionHeight+1), clientHeight, altTime.Add(time.Minute), @@ -192,7 +192,7 @@ func (s *CCVTestSuite) TestGetByzantineValidators() { ) clientHeaderWithCorruptedSigs := s.consumerChain.CreateTMClientHeader( - s.consumerChain.ChainID, + s.getFirstBundle().Chain.ChainID, int64(clientHeight.RevisionHeight+1), clientHeight, altTime.Add(time.Hour), @@ -220,7 +220,7 @@ func (s *CCVTestSuite) TestGetByzantineValidators() { "incorrect signatures - shouldn't pass", func() *ibctmtypes.Misbehaviour { clientHeader := s.consumerChain.CreateTMClientHeader( - s.consumerChain.ChainID, + s.getFirstBundle().Chain.ChainID, int64(clientHeight.RevisionHeight+1), clientHeight, altTime.Add(time.Minute), @@ -231,7 +231,7 @@ func (s *CCVTestSuite) TestGetByzantineValidators() { ) clientHeaderWithCorruptedSigs := s.consumerChain.CreateTMClientHeader( - s.consumerChain.ChainID, + s.getFirstBundle().Chain.ChainID, int64(clientHeight.RevisionHeight+1), clientHeight, altTime.Add(time.Hour), @@ -262,7 +262,7 @@ func (s *CCVTestSuite) TestGetByzantineValidators() { // the resulting header contains invalid fields // i.e. ValidatorsHash, NextValidatorsHash. Header2: s.consumerChain.CreateTMClientHeader( - s.consumerChain.ChainID, + s.getFirstBundle().Chain.ChainID, int64(clientHeight.RevisionHeight+1), clientHeight, altTime, @@ -286,7 +286,7 @@ func (s *CCVTestSuite) TestGetByzantineValidators() { Header1: clientHeader, // the resulting header contains a different BlockID Header2: s.consumerChain.CreateTMClientHeader( - s.consumerChain.ChainID, + s.getFirstBundle().Chain.ChainID, int64(clientHeight.RevisionHeight+1), clientHeight, altTime.Add(time.Minute), @@ -308,7 +308,7 @@ func (s *CCVTestSuite) TestGetByzantineValidators() { // create a valid header with a different hash // and commit round amnesiaHeader := s.consumerChain.CreateTMClientHeader( - s.consumerChain.ChainID, + s.getFirstBundle().Chain.ChainID, int64(clientHeight.RevisionHeight+1), clientHeight, altTime.Add(time.Minute), @@ -383,7 +383,7 @@ func (s *CCVTestSuite) TestCheckMisbehaviour() { // create a valid client header clientHeader := s.consumerChain.CreateTMClientHeader( - s.consumerChain.ChainID, + s.getFirstBundle().Chain.ChainID, int64(clientHeight.RevisionHeight+1), clientHeight, headerTs, @@ -402,7 +402,7 @@ func (s *CCVTestSuite) TestCheckMisbehaviour() { // create a conflicting client with different block ID using // to alternative validator set clientHeaderWithDiffBlockID := s.consumerChain.CreateTMClientHeader( - s.consumerChain.ChainID, + s.getFirstBundle().Chain.ChainID, int64(clientHeight.RevisionHeight+1), clientHeight, headerTs, @@ -419,7 +419,7 @@ func (s *CCVTestSuite) TestCheckMisbehaviour() { // create a conflicting client header with insufficient voting power clientHeaderWithInsufficientVotingPower := s.consumerChain.CreateTMClientHeader( - s.consumerChain.ChainID, + s.getFirstBundle().Chain.ChainID, int64(clientHeight.RevisionHeight+1), clientHeight, // use a different block time to change the header BlockID @@ -434,7 +434,7 @@ func (s *CCVTestSuite) TestCheckMisbehaviour() { equivocationEvidenceMinHeight := clientHeight.RevisionHeight + 1 s.providerApp.GetProviderKeeper().SetEquivocationEvidenceMinHeight( s.providerCtx(), - s.consumerChain.ChainID, + s.getFirstBundle().ConsumerId, equivocationEvidenceMinHeight, ) @@ -485,7 +485,7 @@ func (s *CCVTestSuite) TestCheckMisbehaviour() { ClientId: s.path.EndpointA.ClientID, Header1: clientHeader, Header2: s.consumerChain.CreateTMClientHeader( - s.consumerChain.ChainID, + s.getFirstBundle().Chain.ChainID, int64(clientHeight.RevisionHeight+2), clientHeight, headerTs, @@ -502,7 +502,7 @@ func (s *CCVTestSuite) TestCheckMisbehaviour() { &ibctmtypes.Misbehaviour{ ClientId: s.path.EndpointA.ClientID, Header1: s.consumerChain.CreateTMClientHeader( - s.consumerChain.ChainID, + s.getFirstBundle().Chain.ChainID, int64(equivocationEvidenceMinHeight-1), clientHeight, headerTs, @@ -512,7 +512,7 @@ func (s *CCVTestSuite) TestCheckMisbehaviour() { altSigners, ), Header2: s.consumerChain.CreateTMClientHeader( - s.consumerChain.ChainID, + s.getFirstBundle().Chain.ChainID, int64(equivocationEvidenceMinHeight-1), clientHeight, headerTs, @@ -547,7 +547,7 @@ func (s *CCVTestSuite) TestCheckMisbehaviour() { for _, tc := range testCases { s.Run(tc.name, func() { - err := s.providerApp.GetProviderKeeper().CheckMisbehaviour(s.providerCtx(), *tc.misbehaviour) + err := s.providerApp.GetProviderKeeper().CheckMisbehaviour(s.providerCtx(), s.getFirstBundle().ConsumerId, *tc.misbehaviour) cs, ok := s.providerApp.GetIBCKeeper().ClientKeeper.GetClientState(s.providerCtx(), s.path.EndpointA.ClientID) s.Require().True(ok) // verify that the client wasn't frozen diff --git a/tests/integration/partial_set_security_test.go b/tests/integration/partial_set_security_test.go index ebc6336fee..db628aaccd 100644 --- a/tests/integration/partial_set_security_test.go +++ b/tests/integration/partial_set_security_test.go @@ -5,6 +5,8 @@ import ( "sort" "testing" + "github.com/cosmos/interchain-security/v5/x/ccv/provider/types" + "cosmossdk.io/math" ccv "github.com/cosmos/interchain-security/v5/x/ccv/types" "github.com/stretchr/testify/require" @@ -151,7 +153,14 @@ func TestMinStake(t *testing.T) { // adjust parameters // set the minStake according to the test case - providerKeeper.SetMinStake(s.providerChain.GetContext(), s.consumerChain.ChainID, tc.minStake) + err = providerKeeper.SetConsumerPowerShapingParameters( + s.providerChain.GetContext(), + s.getFirstBundle().ConsumerId, + types.PowerShapingParameters{ + MinStake: tc.minStake, + }, + ) + s.Require().NoError(err) // delegate and undelegate to trigger a vscupdate diff --git a/tests/integration/provider_gov_hooks.go b/tests/integration/provider_gov_hooks.go deleted file mode 100644 index 813a62a671..0000000000 --- a/tests/integration/provider_gov_hooks.go +++ /dev/null @@ -1,156 +0,0 @@ -package integration - -import ( - "time" - - "cosmossdk.io/math" - 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" - v1 "github.com/cosmos/cosmos-sdk/x/gov/types/v1" - "github.com/cosmos/cosmos-sdk/x/gov/types/v1beta1" - - testkeeper "github.com/cosmos/interchain-security/v5/testutil/keeper" -) - -// tests AfterProposalSubmission and AfterProposalVotingPeriodEnded hooks -// hooks require adding a proposal in the gov module and registering a consumer chain with the provider module -func (s *CCVTestSuite) TestAfterPropSubmissionAndVotingPeriodEnded() { - ctx := s.providerChain.GetContext() - providerKeeper := s.providerApp.GetProviderKeeper() - govKeeper := s.providerApp.GetTestGovKeeper() - proposer := s.providerChain.SenderAccount - - addConsumerProp := testkeeper.GetTestMsgConsumerAddition() - - proposal, err := v1.NewProposal([]sdk.Msg{&addConsumerProp}, 1, time.Now(), time.Now().Add(1*time.Hour), "metadata", "title", "summary", proposer.GetAddress(), false) - s.Require().NoError(err) - - err = govKeeper.SetProposal(ctx, proposal) - s.Require().NoError(err) - - providerKeeper.Hooks().AfterProposalSubmission(ctx, proposal.Id) - - // verify that the proposal ID is created - proposalIdOnProvider, ok := providerKeeper.GetProposedConsumerChain(ctx, proposal.Id) - s.Require().True(ok) - s.Require().NotEmpty(proposalIdOnProvider) - s.Require().Equal(addConsumerProp.ChainId, proposalIdOnProvider) - - providerKeeper.Hooks().AfterProposalVotingPeriodEnded(ctx, proposal.Id) - // verify that the proposal ID is deleted - s.Require().Empty(providerKeeper.GetProposedConsumerChain(ctx, proposal.Id)) -} - -func (s *CCVTestSuite) TestGetConsumerAdditionFromProp() { - ctx := s.providerChain.GetContext() - proposer := s.providerChain.SenderAccount - - // create a dummy bank send message - dummyMsg := &banktypes.MsgSend{ - FromAddress: sdk.AccAddress(proposer.GetAddress()).String(), - ToAddress: sdk.AccAddress(proposer.GetAddress()).String(), - Amount: sdk.NewCoins(sdk.NewCoin("stake", math.OneInt())), - } - - // create a legacy proposal - textProp, err := v1.NewLegacyContent( - v1beta1.NewTextProposal("a title", "a legacy text prop"), - authtypes.NewModuleAddress("gov").String(), - ) - s.Require().NoError(err) - - // create a valid consumer addition message - msgConsumerAddition := testkeeper.GetTestMsgConsumerAddition() - - // create a legacy consumer addition proposal content - // (not supported anymore) - addConsumerPropLegacy, err := v1.NewLegacyContent( - testkeeper.GetTestConsumerAdditionProp(), - authtypes.NewModuleAddress("gov").String(), - ) - s.Require().NoError(err) - - testCases := []struct { - name string - propMsg sdk.Msg - expectConsumerPropFound bool - expPanic bool - }{ - { - name: "prop not found", - propMsg: nil, - expectConsumerPropFound: false, - expPanic: false, - }, - { - name: "msgs in prop contain no consumer addition props", - propMsg: dummyMsg, - expectConsumerPropFound: false, - expPanic: false, - }, - { - name: "msgs contain a legacy prop but not of ConsumerAdditionProposal type", - propMsg: textProp, - expectConsumerPropFound: false, - }, - { - name: "msgs contain an invalid legacy prop", - propMsg: &v1.MsgExecLegacyContent{}, - expectConsumerPropFound: false, - expPanic: false, - }, - { - name: "msg contains a prop of legacy ConsumerAdditionProposal type - hook should NOT create a new proposed chain", - propMsg: addConsumerPropLegacy, - expectConsumerPropFound: false, - expPanic: false, - }, - { - name: "msg contains a prop of MsgConsumerAddition type - hook should create a new proposed chain", - propMsg: &msgConsumerAddition, - expectConsumerPropFound: true, - expPanic: false, - }, - } - - for _, tc := range testCases { - s.Run(tc.name, func() { - providerKeeper := s.providerApp.GetProviderKeeper() - govKeeper := s.providerApp.GetTestGovKeeper() - - var proposal v1.Proposal - var err error - - if tc.propMsg == nil { - // cover edgecase where proposal has no messages - proposal, err = v1.NewProposal([]sdk.Msg{}, 1, time.Now(), time.Now().Add(1*time.Hour), "metadata", "title", "summary", proposer.GetAddress(), false) - s.Require().NoError(err) - } else { - // cover variolus cases where proposal has messages but only some are consumer addition proposals - proposal, err = v1.NewProposal([]sdk.Msg{tc.propMsg}, 1, time.Now(), time.Now().Add(1*time.Hour), "metadata", "title", "summary", proposer.GetAddress(), false) - s.Require().NoError(err) - } - - err = govKeeper.SetProposal(ctx, proposal) - s.Require().NoError(err) - - if tc.expPanic { - s.Require().Panics(func() { - // this panics with a nil pointer dereference because the proposal is invalid and cannot be unmarshalled - providerKeeper.Hooks().GetConsumerAdditionFromProp(ctx, proposal.Id) - }) - return - } - - savedProp, found := providerKeeper.Hooks().GetConsumerAdditionFromProp(ctx, proposal.Id) - if tc.expectConsumerPropFound { - s.Require().True(found) - s.Require().NotEmpty(savedProp, savedProp) - } else { - s.Require().False(found) - s.Require().Empty(savedProp) - } - }) - } -} diff --git a/tests/integration/setup.go b/tests/integration/setup.go index eeb980200f..218f6febb0 100644 --- a/tests/integration/setup.go +++ b/tests/integration/setup.go @@ -21,7 +21,7 @@ import ( icstestingutils "github.com/cosmos/interchain-security/v5/testutil/ibc_testing" testutil "github.com/cosmos/interchain-security/v5/testutil/integration" consumertypes "github.com/cosmos/interchain-security/v5/x/ccv/consumer/types" - "github.com/cosmos/interchain-security/v5/x/ccv/provider/types" + providertypes "github.com/cosmos/interchain-security/v5/x/ccv/provider/types" ccv "github.com/cosmos/interchain-security/v5/x/ccv/types" ) @@ -60,7 +60,7 @@ type CCVTestSuite struct { // The transfer path to the first consumer among multiple. transferPath *ibctesting.Path - // A map from consumer chain ID to its consumer bundle. + // A map from consumer id to its consumer bundle. // The preferred way to access chains, apps, and paths when designing tests around multiple consumers. consumerBundles map[string]*icstestingutils.ConsumerBundle skippedTests map[string]bool @@ -149,35 +149,28 @@ func (suite *CCVTestSuite) SetupTest() { // 1. the consumer chain is added to the coordinator // 2. MakeGenesis is called on the provider chain // 3. ibc/testing sets the tendermint header for the consumer chain app - providerKeeper.SetPendingConsumerAdditionProp(suite.providerCtx(), &types.ConsumerAdditionProposal{ - ChainId: icstestingutils.FirstConsumerChainID, - }) - ps := providerKeeper.GetAllPendingConsumerAdditionProps(suite.providerCtx()) - preProposalKeyAssignment(suite, icstestingutils.FirstConsumerChainID) - - // remove props so they don't interfere with the rest of the setup - // if not removed here, setupConsumerCallback will have 2 proposals for adding the first consumer chain - providerKeeper.DeletePendingConsumerAdditionProps(suite.providerCtx(), ps...) + providerKeeper.SetConsumerPhase(suite.providerCtx(), icstestingutils.FirstConsumerID, providertypes.CONSUMER_PHASE_INITIALIZED) + preProposalKeyAssignment(suite, icstestingutils.FirstConsumerID) // start consumer chains suite.consumerBundles = make(map[string]*icstestingutils.ConsumerBundle) for i := 0; i < icstestingutils.NumConsumers; i++ { bundle := suite.setupConsumerCallback(&suite.Suite, suite.coordinator, i) - suite.consumerBundles[bundle.Chain.ChainID] = bundle + suite.consumerBundles[bundle.ConsumerId] = bundle suite.registerPacketSniffer(bundle.Chain) // check that TopN is correctly set for the consumer - topN, found := providerKeeper.GetTopN(suite.providerCtx(), bundle.Chain.ChainID) - suite.Require().True(found) - suite.Require().Equal(bundle.TopN, topN) + powerShapingParameters, err := providerKeeper.GetConsumerPowerShapingParameters(suite.providerCtx(), bundle.ConsumerId) + suite.Require().NoError(err) + suite.Require().Equal(bundle.TopN, powerShapingParameters.Top_N) } // initialize each consumer chain with it's corresponding genesis state // stored on the provider. - for chainID := range suite.consumerBundles { + for consumerId := range suite.consumerBundles { consumerGenesisState, found := providerKeeper.GetConsumerGenesis( suite.providerCtx(), - chainID, + consumerId, ) suite.Require().True(found, "consumer genesis not found") @@ -186,7 +179,7 @@ func (suite *CCVTestSuite) SetupTest() { Provider: consumerGenesisState.Provider, NewChain: consumerGenesisState.NewChain, } - initConsumerChain(suite, chainID, &genesisState) + initConsumerChain(suite, consumerId, &genesisState) } // try updating all clients @@ -221,11 +214,11 @@ func (s *CCVTestSuite) getSentPacket(chain *ibctesting.TestChain, sequence uint6 // initConsumerChain initializes a consumer chain given a genesis state func initConsumerChain( s *CCVTestSuite, - chainID string, + consumerId string, genesisState *consumertypes.GenesisState, ) { providerKeeper := s.providerApp.GetProviderKeeper() - bundle := s.consumerBundles[chainID] + bundle := s.consumerBundles[consumerId] // run CCV module init genesis s.NotPanics(func() { @@ -249,7 +242,7 @@ func initConsumerChain( // Set provider endpoint's clientID for each consumer providerEndpointClientID, found := providerKeeper.GetConsumerClientId( s.providerCtx(), - chainID, + consumerId, ) s.Require().True(found, "provider endpoint clientID not found") bundle.Path.EndpointB.ClientID = providerEndpointClientID @@ -291,7 +284,7 @@ func initConsumerChain( err = bundle.Path.EndpointA.UpdateClient() s.Require().NoError(err) - if chainID == icstestingutils.FirstConsumerChainID { + if consumerId == icstestingutils.FirstConsumerID { // Support tests that were written before multiple consumers were supported. firstBundle := s.getFirstBundle() s.consumerApp = firstBundle.App @@ -379,14 +372,14 @@ func (suite *CCVTestSuite) SetupAllTransferChannels() { suite.SetupTransferChannel() // setup all the remaining consumers transfer channels - for chainID := range suite.consumerBundles { + for consumerId := range suite.consumerBundles { // skip fist consumer - if chainID == suite.consumerChain.ChainID { + if consumerId == suite.getFirstBundle().ConsumerId { continue } // get the bundle for the chain ID - bundle := suite.consumerBundles[chainID] + bundle := suite.consumerBundles[consumerId] // setup the transfer channel suite.setupTransferChannel( bundle.TransferPath, @@ -423,9 +416,9 @@ func (s CCVTestSuite) validateEndpointsClientConfig(consumerBundle icstestinguti } // preProposalKeyAssignment assigns keys to all provider validators for -// the consumer with chainID before the chain is registered, i.e., +// the consumer with consumerId before the chain is registered, i.e., // before a client to the consumer is created -func preProposalKeyAssignment(s *CCVTestSuite, chainID string) { +func preProposalKeyAssignment(s *CCVTestSuite, consumerId string) { providerKeeper := s.providerApp.GetProviderKeeper() for _, val := range s.providerChain.Vals.Validators { @@ -445,7 +438,7 @@ func preProposalKeyAssignment(s *CCVTestSuite, chainID string) { // as a result, NewTestChainWithValSet in AddConsumer uses providerChain.Signers s.providerChain.Signers[tmPubKey.Address().String()] = privVal - err = providerKeeper.AssignConsumerKey(s.providerCtx(), chainID, validator, consumerKey) + err = providerKeeper.AssignConsumerKey(s.providerCtx(), consumerId, validator, consumerKey) s.Require().NoError(err) } } diff --git a/tests/integration/slashing.go b/tests/integration/slashing.go index eab288deb3..8156672a0d 100644 --- a/tests/integration/slashing.go +++ b/tests/integration/slashing.go @@ -57,7 +57,7 @@ func (s *CCVTestSuite) TestRelayAndApplyDowntimePacket() { // map consumer consensus address to provider consensus address providerConsAddr, found := providerKeeper.GetValidatorByConsumerAddr( s.providerCtx(), - s.consumerChain.ChainID, + s.getFirstBundle().ConsumerId, consumerConsAddr, ) s.Require().True(found) @@ -188,7 +188,7 @@ func (s *CCVTestSuite) TestRelayAndApplyDoubleSignPacket() { // map consumer consensus address to provider consensus address providerConsAddr, found := providerKeeper.GetValidatorByConsumerAddr( s.providerCtx(), - s.consumerChain.ChainID, + s.getFirstBundle().ConsumerId, consumerConsAddr) s.Require().True(found) @@ -307,7 +307,7 @@ func (suite *CCVTestSuite) TestHandleSlashPacketDowntime() { suite.Require().Equal(stakingtypes.Bonded, validator.GetStatus()) // set init VSC id for chain0 - providerKeeper.SetInitChainHeight(suite.providerCtx(), suite.consumerChain.ChainID, uint64(suite.providerCtx().BlockHeight())) + providerKeeper.SetInitChainHeight(suite.providerCtx(), suite.getFirstBundle().ConsumerId, uint64(suite.providerCtx().BlockHeight())) // set validator signing-info providerSlashingKeeper.SetValidatorSigningInfo( @@ -316,7 +316,7 @@ func (suite *CCVTestSuite) TestHandleSlashPacketDowntime() { slashingtypes.ValidatorSigningInfo{Address: consAddr.String()}, ) - providerKeeper.HandleSlashPacket(suite.providerCtx(), suite.consumerChain.ChainID, + providerKeeper.HandleSlashPacket(suite.providerCtx(), suite.getFirstBundle().ConsumerId, *ccv.NewSlashPacketData( abci.Validator{Address: tmVal.Address, Power: 0}, uint64(0), @@ -413,7 +413,7 @@ func (suite *CCVTestSuite) TestOnRecvSlashPacketErrors() { suite.Require().NoError(err, "no error expected") suite.Require().Equal(ccv.SlashPacketHandledResult, ackResult, "expected successful ack") - providerKeeper.SetConsumerValidator(ctx, firstBundle.Chain.ChainID, providertypes.ConsensusValidator{ + providerKeeper.SetConsumerValidator(ctx, firstBundle.ConsumerId, providertypes.ConsensusValidator{ ProviderConsAddr: validAddress, }) diff --git a/tests/integration/stop_consumer.go b/tests/integration/stop_consumer.go index 839bd10771..8ce2e99cbf 100644 --- a/tests/integration/stop_consumer.go +++ b/tests/integration/stop_consumer.go @@ -3,6 +3,7 @@ package integration import ( "cosmossdk.io/math" channeltypes "github.com/cosmos/ibc-go/v8/modules/core/04-channel/types" + "github.com/cosmos/interchain-security/v5/x/ccv/provider/types" sdk "github.com/cosmos/cosmos-sdk/types" stakingtypes "github.com/cosmos/cosmos-sdk/x/staking/types" @@ -75,8 +76,8 @@ func (s *CCVTestSuite) TestStopConsumerChain() { }, { func(suite *CCVTestSuite) error { - providerKeeper.SetSlashAcks(s.providerCtx(), firstBundle.Chain.ChainID, []string{"validator-1", "validator-2", "validator-3"}) - providerKeeper.AppendPendingVSCPackets(s.providerCtx(), firstBundle.Chain.ChainID, ccv.ValidatorSetChangePacketData{ValsetUpdateId: 1}) + providerKeeper.SetSlashAcks(s.providerCtx(), firstBundle.ConsumerId, []string{"validator-1", "validator-2", "validator-3"}) + providerKeeper.AppendPendingVSCPackets(s.providerCtx(), firstBundle.ConsumerId, ccv.ValidatorSetChangePacketData{ValsetUpdateId: 1}) return nil }, }, @@ -88,11 +89,12 @@ func (s *CCVTestSuite) TestStopConsumerChain() { } // stop the consumer chain - err = providerKeeper.StopConsumerChain(s.providerCtx(), firstBundle.Chain.ChainID, true) + providerKeeper.SetConsumerPhase(s.providerCtx(), firstBundle.ConsumerId, types.CONSUMER_PHASE_STOPPED) + err = providerKeeper.DeleteConsumerChain(s.providerCtx(), firstBundle.ConsumerId) s.Require().NoError(err) // check all states are removed and the unbonding operation released - s.checkConsumerChainIsRemoved(firstBundle.Chain.ChainID, true) + s.checkConsumerChainIsRemoved(firstBundle.ConsumerId, true) } // TODO Simon: implement OnChanCloseConfirm in IBC-GO testing to close the consumer chain's channel end @@ -105,7 +107,8 @@ func (s *CCVTestSuite) TestStopConsumerOnChannelClosed() { providerKeeper := s.providerApp.GetProviderKeeper() // stop the consumer chain - err := providerKeeper.StopConsumerChain(s.providerCtx(), s.consumerChain.ChainID, true) + providerKeeper.SetConsumerPhase(s.providerCtx(), s.getFirstBundle().ConsumerId, types.CONSUMER_PHASE_STOPPED) + err := providerKeeper.DeleteConsumerChain(s.providerCtx(), s.getFirstBundle().ConsumerId) s.Require().NoError(err) err = s.path.EndpointA.UpdateClient() @@ -126,7 +129,7 @@ func (s *CCVTestSuite) TestStopConsumerOnChannelClosed() { // s.Require().False(found) } -func (s *CCVTestSuite) checkConsumerChainIsRemoved(chainID string, checkChannel bool) { +func (s *CCVTestSuite) checkConsumerChainIsRemoved(consumerId string, checkChannel bool) { channelID := s.path.EndpointB.ChannelID providerKeeper := s.providerApp.GetProviderKeeper() @@ -136,18 +139,18 @@ func (s *CCVTestSuite) checkConsumerChainIsRemoved(chainID string, checkChannel } // verify consumer chain's states are removed - _, found := providerKeeper.GetConsumerGenesis(s.providerCtx(), chainID) + _, found := providerKeeper.GetConsumerGenesis(s.providerCtx(), consumerId) s.Require().False(found) - _, found = providerKeeper.GetConsumerClientId(s.providerCtx(), chainID) + _, found = providerKeeper.GetConsumerClientId(s.providerCtx(), consumerId) s.Require().False(found) - _, found = providerKeeper.GetChainToChannel(s.providerCtx(), chainID) + _, found = providerKeeper.GetConsumerIdToChannelId(s.providerCtx(), consumerId) s.Require().False(found) - _, found = providerKeeper.GetChannelToChain(s.providerCtx(), channelID) + _, found = providerKeeper.GetChannelIdToConsumerId(s.providerCtx(), channelID) s.Require().False(found) - s.Require().Nil(providerKeeper.GetSlashAcks(s.providerCtx(), chainID)) - s.Require().Zero(providerKeeper.GetInitChainHeight(s.providerCtx(), chainID)) - s.Require().Empty(providerKeeper.GetPendingVSCPackets(s.providerCtx(), chainID)) + s.Require().Nil(providerKeeper.GetSlashAcks(s.providerCtx(), consumerId)) + s.Require().Zero(providerKeeper.GetInitChainHeight(s.providerCtx(), consumerId)) + s.Require().Empty(providerKeeper.GetPendingVSCPackets(s.providerCtx(), consumerId)) } diff --git a/tests/mbt/driver/core.go b/tests/mbt/driver/core.go index 2cd618096f..897b713a42 100644 --- a/tests/mbt/driver/core.go +++ b/tests/mbt/driver/core.go @@ -10,7 +10,6 @@ import ( "cosmossdk.io/math" - channeltypes "github.com/cosmos/ibc-go/v8/modules/core/04-channel/types" tendermint "github.com/cosmos/ibc-go/v8/modules/light-clients/07-tendermint" ibctesting "github.com/cosmos/ibc-go/v8/testing" "github.com/stretchr/testify/require" @@ -220,8 +219,8 @@ func (s *Driver) getStateString() string { state.WriteString("\n") state.WriteString("Consumers Chains:\n") - chainIds := s.providerKeeper().GetAllRegisteredConsumerChainIDs(s.providerCtx()) - state.WriteString(strings.Join(chainIds, ", ")) + // chainIds := s.providerKeeper().GetAllRegisteredConsumerIds(s.providerCtx()) + // state.WriteString(strings.Join(chainIds, ", ")) state.WriteString("\n\n") for chain := range s.simibcs { @@ -255,24 +254,24 @@ func (s *Driver) getChainStateString(chain ChainId) string { chainInfo.WriteString(fmt.Sprintf(" Running Time: %s\n", runningTime)) chainInfo.WriteString(fmt.Sprintf(" Last Time entered on chain: %s\n", lastTime)) - if !s.isProviderChain(chain) { - // Check whether the chain is in the consumer chains on the provider + // if !s.isProviderChain(chain) { + // Check whether the chain is in the consumer chains on the provider - consumerChainIDs := s.providerKeeper().GetAllRegisteredConsumerChainIDs(s.providerCtx()) + // consumerChainIDs := s.providerKeeper().GetAllRegisteredConsumerIds(s.providerCtx()) - found := false - for _, consumerChainID := range consumerChainIDs { - if consumerChainID == string(chain) { - found = true - } - } + // found := false + // for _, consumerChainID := range consumerChainIDs { + // if consumerChainID == string(chain) { + // found = true + // } + // } - if found { - chainInfo.WriteString("...is currently a consumer chain") - } else { - chainInfo.WriteString("...is currently not a consumer chain") - } - } + // if found { + // chainInfo.WriteString("...is currently a consumer chain") + // } else { + // chainInfo.WriteString("...is currently not a consumer chain") + // } + // } // Build the validator info string var validatorInfo strings.Builder @@ -366,16 +365,16 @@ func (s *Driver) endAndBeginBlock(chain ChainId, timeAdvancement time.Duration) } func (s *Driver) runningConsumerChainIDs() []ChainId { - consumerIDsOnProvider := s.providerKeeper().GetAllRegisteredConsumerChainIDs(s.providerCtx()) + // consumerIDsOnProvider := s.providerKeeper().GetAllRegisteredConsumerIds(s.providerCtx()) consumersWithIntactChannel := make([]ChainId, 0) - for _, consumerChainID := range consumerIDsOnProvider { - if s.path(ChainId(consumerChainID)).Path.EndpointA.GetChannel().State == channeltypes.CLOSED || - s.path(ChainId(consumerChainID)).Path.EndpointB.GetChannel().State == channeltypes.CLOSED { - continue - } - consumersWithIntactChannel = append(consumersWithIntactChannel, ChainId(consumerChainID)) - } + // for _, consumerChainID := range consumerIDsOnProvider { + // if s.path(ChainId(consumerChainID)).Path.EndpointA.GetChannel().State == channeltypes.CLOSED || + // s.path(ChainId(consumerChainID)).Path.EndpointB.GetChannel().State == channeltypes.CLOSED { + // continue + // } + // consumersWithIntactChannel = append(consumersWithIntactChannel, ChainId(consumerChainID)) + // } return consumersWithIntactChannel } @@ -452,7 +451,8 @@ func (s *Driver) DeliverAcks() { // stopConsumer stops a given consumer chain. func (s *Driver) stopConsumer(chain ChainId) error { // stop the consumer chain on the provider - return s.providerKeeper().StopConsumerChain(s.providerCtx(), string(chain), true) + // return s.providerKeeper().StopConsumerChain(s.providerCtx(), string(chain), true) + return nil } // newDriver creates a new Driver object. diff --git a/tests/mbt/driver/mbt_test.go b/tests/mbt/driver/mbt_test.go index 35ea2f4e1f..278c276d82 100644 --- a/tests/mbt/driver/mbt_test.go +++ b/tests/mbt/driver/mbt_test.go @@ -404,7 +404,7 @@ func RunItfTrace(t *testing.T, path string) { driver.DeliverPacketToConsumer(ChainId(consumerChain), expectError) // stop the consumer chain - driver.providerKeeper().StopConsumerChain(driver.providerCtx(), consumerChain, expectError) + // driver.providerKeeper().StopConsumerChain(driver.providerCtx(), consumerChain, expectError) } else { expectError = false driver.DeliverPacketToConsumer(ChainId(consumerChain), expectError) @@ -421,7 +421,7 @@ func RunItfTrace(t *testing.T, path string) { driver.DeliverPacketFromConsumer(ChainId(consumerChain), expectError) // stop the consumer chain on the provider - driver.providerKeeper().StopConsumerChain(driver.providerCtx(), consumerChain, expectError) + // driver.providerKeeper().StopConsumerChain(driver.providerCtx(), consumerChain, expectError) } else { expectError = false driver.DeliverPacketFromConsumer(ChainId(consumerChain), expectError) diff --git a/tests/mbt/driver/setup.go b/tests/mbt/driver/setup.go index d9e658c030..97102960d6 100644 --- a/tests/mbt/driver/setup.go +++ b/tests/mbt/driver/setup.go @@ -12,6 +12,7 @@ import ( commitmenttypes "github.com/cosmos/ibc-go/v8/modules/core/23-commitment/types" ibctmtypes "github.com/cosmos/ibc-go/v8/modules/light-clients/07-tendermint" ibctesting "github.com/cosmos/ibc-go/v8/testing" + "github.com/cosmos/interchain-security/v5/x/ccv/provider/types" providertypes "github.com/cosmos/interchain-security/v5/x/ccv/provider/types" "github.com/stretchr/testify/require" @@ -388,7 +389,10 @@ func (s *Driver) ConfigureNewPath(consumerChain, providerChain *ibctesting.TestC require.NoError(s.t, err, "Error setting consumer genesis on provider for chain %v", consumerChain.ChainID) // set the top N percentage to 100 to simulate a full consumer - s.providerKeeper().SetTopN(providerChain.GetContext(), consumerChain.ChainID, 100) + err = s.providerKeeper().SetConsumerPowerShapingParameters(providerChain.GetContext(), consumerChain.ChainID, types.PowerShapingParameters{ + Top_N: 100, + }) + require.NoError(s.t, err, "Error setting consumer top N for chain %v", consumerChain.ChainID) // Client ID is set in InitGenesis and we treat it as a black box. So // must query it to use it with the endpoint. diff --git a/testutil/ibc_testing/generic_setup.go b/testutil/ibc_testing/generic_setup.go index 3aaae5702f..84ccf347f2 100644 --- a/testutil/ibc_testing/generic_setup.go +++ b/testutil/ibc_testing/generic_setup.go @@ -6,6 +6,7 @@ import ( "testing" clienttypes "github.com/cosmos/ibc-go/v8/modules/core/02-client/types" + ibctesting "github.com/cosmos/ibc-go/v8/testing" testkeeper "github.com/cosmos/interchain-security/v5/testutil/keeper" "github.com/stretchr/testify/require" @@ -37,7 +38,8 @@ const ( ) var ( - FirstConsumerChainID string + firstConsumerChainID string + FirstConsumerID string provChainID string democConsumerChainID string consumerTopNParams [NumConsumers]uint32 @@ -46,7 +48,8 @@ var ( func init() { // Disable revision format ibctesting.ChainIDSuffix = "" - FirstConsumerChainID = ibctesting.GetChainID(2) + firstConsumerChainID = ibctesting.GetChainID(2) + FirstConsumerID = "" provChainID = ibctesting.GetChainID(1) democConsumerChainID = ibctesting.GetChainID(5000) // TopN parameter values per consumer chain initiated @@ -57,6 +60,7 @@ func init() { // ConsumerBundle serves as a way to store useful in-mem consumer app chain state // and relevant IBC paths in the context of CCV integration testing. type ConsumerBundle struct { + ConsumerId string Chain *ibctesting.TestChain App testutil.ConsumerApp Path *ibctesting.Path @@ -138,20 +142,33 @@ func AddConsumer[Tp testutil.ProviderApp, Tc testutil.ConsumerApp]( providerApp := providerChain.App.(Tp) providerKeeper := providerApp.GetProviderKeeper() - prop := testkeeper.GetTestConsumerAdditionProp() - prop.ChainId = chainID - prop.Top_N = consumerTopNParams[index] // isn't used in CreateConsumerClient + consumerMetadata := testkeeper.GetTestConsumerMetadata() + initializationParameters := testkeeper.GetTestInitializationParameters() // NOTE: we cannot use the time.Now() because the coordinator chooses a hardcoded start time // using time.Now() could set the spawn time to be too far in the past or too far in the future - prop.SpawnTime = coordinator.CurrentTime + initializationParameters.SpawnTime = coordinator.CurrentTime // NOTE: the initial height passed to CreateConsumerClient // must be the height on the consumer when InitGenesis is called - prop.InitialHeight = clienttypes.Height{RevisionNumber: 0, RevisionHeight: 2} + initializationParameters.InitialHeight = clienttypes.Height{RevisionNumber: 0, RevisionHeight: 2} - providerKeeper.SetPendingConsumerAdditionProp(providerChain.GetContext(), prop) - props := providerKeeper.GetAllPendingConsumerAdditionProps(providerChain.GetContext()) - s.Require().Len(props, 1, "unexpected len consumer addition proposals in AddConsumer") + powerShapingParameters := testkeeper.GetTestPowerShapingParameters() + powerShapingParameters.Top_N = consumerTopNParams[index] // isn't used in CreateConsumerClient + + consumerId := providerKeeper.FetchAndIncrementConsumerId(providerChain.GetContext()) + if chainID == firstConsumerChainID { + FirstConsumerID = consumerId + } + providerKeeper.SetConsumerChainId(providerChain.GetContext(), consumerId, chainID) + err := providerKeeper.SetConsumerMetadata(providerChain.GetContext(), consumerId, consumerMetadata) + s.Require().NoError(err) + err = providerKeeper.SetConsumerInitializationParameters(providerChain.GetContext(), consumerId, initializationParameters) + s.Require().NoError(err) + err = providerKeeper.SetConsumerPowerShapingParameters(providerChain.GetContext(), consumerId, powerShapingParameters) + s.Require().NoError(err) + providerKeeper.SetConsumerPhase(providerChain.GetContext(), consumerId, providertypes.CONSUMER_PHASE_INITIALIZED) + err = providerKeeper.AppendConsumerToBeLaunched(providerChain.GetContext(), consumerId, coordinator.CurrentTime) + s.Require().NoError(err) // opt-in all validators lastVals, err := providerApp.GetProviderKeeper().GetLastBondedValidators(providerChain.GetContext()) @@ -159,7 +176,9 @@ func AddConsumer[Tp testutil.ProviderApp, Tc testutil.ConsumerApp]( for _, v := range lastVals { consAddr, _ := v.GetConsAddr() - providerKeeper.SetOptedIn(providerChain.GetContext(), chainID, providertypes.NewProviderConsAddress(consAddr)) + providerKeeper.SetOptedIn(providerChain.GetContext(), consumerId, providertypes.NewProviderConsAddress(consAddr)) + err = providerKeeper.AppendOptedInConsumerId(providerChain.GetContext(), providertypes.NewProviderConsAddress(consAddr), consumerId) + s.Require().NoError(err) } // commit the state on the provider chain @@ -169,11 +188,16 @@ func AddConsumer[Tp testutil.ProviderApp, Tc testutil.ConsumerApp]( // get genesis state created by the provider consumerGenesisState, found := providerKeeper.GetConsumerGenesis( providerChain.GetContext(), - chainID, + consumerId, ) - s.Require().True(found, "consumer genesis not found in AddConsumer") + _, found = providerKeeper.GetConsumerClientId( + providerChain.GetContext(), + consumerId, + ) + s.Require().True(found, "clientID not found in AddConsumer") + // use InitialValSet as the valset on the consumer var valz []*tmtypes.Validator for _, update := range consumerGenesisState.Provider.InitialValSet { @@ -201,8 +225,9 @@ func AddConsumer[Tp testutil.ProviderApp, Tc testutil.ConsumerApp]( } return &ConsumerBundle{ - Chain: testChain, - App: consumerToReturn, - TopN: prop.Top_N, + ConsumerId: consumerId, + Chain: testChain, + App: consumerToReturn, + TopN: powerShapingParameters.Top_N, } } diff --git a/testutil/keeper/expectations.go b/testutil/keeper/expectations.go index 3ceaf4fd2b..53d16a6581 100644 --- a/testutil/keeper/expectations.go +++ b/testutil/keeper/expectations.go @@ -80,9 +80,8 @@ func GetMocksForSetConsumerChain(ctx sdk.Context, mocks *MockedKeepers, } } -// GetMocksForStopConsumerChainWithCloseChannel returns mock expectations needed to call StopConsumerChain() when -// `closeChan` is true. -func GetMocksForStopConsumerChainWithCloseChannel(ctx sdk.Context, mocks *MockedKeepers) []*gomock.Call { +// GetMocksForDeleteConsumerChain returns mock expectations needed to call `DeleteConsumerChain` +func GetMocksForDeleteConsumerChain(ctx sdk.Context, mocks *MockedKeepers) []*gomock.Call { dummyCap := &capabilitytypes.Capability{} return []*gomock.Call{ mocks.MockChannelKeeper.EXPECT().GetChannel(gomock.Any(), types.ProviderPortID, "channelID").Return( diff --git a/testutil/keeper/mocks.go b/testutil/keeper/mocks.go index 1a1cd971d5..94ef8e1f98 100644 --- a/testutil/keeper/mocks.go +++ b/testutil/keeper/mocks.go @@ -1234,6 +1234,20 @@ func (m *MockAccountKeeper) EXPECT() *MockAccountKeeperMockRecorder { return m.recorder } +// AddressCodec mocks base method. +func (m *MockAccountKeeper) AddressCodec() address.Codec { + m.ctrl.T.Helper() + ret := m.ctrl.Call(m, "AddressCodec") + ret0, _ := ret[0].(address.Codec) + return ret0 +} + +// AddressCodec indicates an expected call of AddressCodec. +func (mr *MockAccountKeeperMockRecorder) AddressCodec() *gomock.Call { + mr.mock.ctrl.T.Helper() + return mr.mock.ctrl.RecordCallWithMethodType(mr.mock, "AddressCodec", reflect.TypeOf((*MockAccountKeeper)(nil).AddressCodec)) +} + // GetModuleAccount mocks base method. func (m *MockAccountKeeper) GetModuleAccount(ctx context.Context, name string) types1.ModuleAccountI { m.ctrl.T.Helper() diff --git a/testutil/keeper/unit_test_helpers.go b/testutil/keeper/unit_test_helpers.go index f458ac4c3b..1c11c2c7e9 100644 --- a/testutil/keeper/unit_test_helpers.go +++ b/testutil/keeper/unit_test_helpers.go @@ -212,13 +212,14 @@ func GetNewSlashPacketData() types.SlashPacketData { } } -// SetupForStoppingConsumerChain registers expected mock calls and corresponding state setup -// which assert that a consumer chain was properly setup to be later stopped from `StopConsumerChain`. -// Note: This function only setups and tests that we correctly setup a consumer chain that we could later stop when -// calling `StopConsumerChain` -- this does NOT necessarily mean that the consumer chain is stopped. -// Also see `TestProviderStateIsCleanedAfterConsumerChainIsStopped`. -func SetupForStoppingConsumerChain(t *testing.T, ctx sdk.Context, +// SetupForDeleteConsumerChain registers expected mock calls and corresponding state setup +// which assert that a consumer chain was properly setup to be later deleted with `DeleteConsumerChain`. +// Note: This function only setups and tests that we correctly setup a consumer chain that we could later delete when +// calling `DeleteConsumerChain` -- this does NOT necessarily mean that the consumer chain is deleted. +// Also see `TestProviderStateIsCleanedAfterConsumerChainIsDeleted`. +func SetupForDeleteConsumerChain(t *testing.T, ctx sdk.Context, providerKeeper *providerkeeper.Keeper, mocks MockedKeepers, + consumerId string, ) { t.Helper() @@ -230,73 +231,101 @@ func SetupForStoppingConsumerChain(t *testing.T, ctx sdk.Context, gomock.InOrder(expectations...) - prop := GetTestConsumerAdditionProp() - err := providerKeeper.CreateConsumerClient(ctx, prop) + providerKeeper.SetConsumerChainId(ctx, consumerId, "chainID") + err := providerKeeper.SetConsumerMetadata(ctx, consumerId, GetTestConsumerMetadata()) require.NoError(t, err) + err = providerKeeper.SetConsumerInitializationParameters(ctx, consumerId, GetTestInitializationParameters()) + require.NoError(t, err) + err = providerKeeper.SetConsumerPowerShapingParameters(ctx, consumerId, GetTestPowerShapingParameters()) + require.NoError(t, err) + + // set the chain to initialized so that we can create a consumer client + providerKeeper.SetConsumerPhase(ctx, consumerId, providertypes.CONSUMER_PHASE_INITIALIZED) + + err = providerKeeper.CreateConsumerClient(ctx, consumerId) + require.NoError(t, err) + // set the mapping consumer ID <> client ID for the consumer chain + providerKeeper.SetConsumerClientId(ctx, consumerId, "clientID") + // set the channel ID for the consumer chain err = providerKeeper.SetConsumerChain(ctx, "channelID") require.NoError(t, err) + + // set the chain to stopped sto the chain can be deleted + providerKeeper.SetConsumerPhase(ctx, consumerId, providertypes.CONSUMER_PHASE_STOPPED) } -// TestProviderStateIsCleanedAfterConsumerChainIsStopped executes test assertions for the provider's state being cleaned -// after a stopped consumer chain. -func TestProviderStateIsCleanedAfterConsumerChainIsStopped(t *testing.T, ctx sdk.Context, providerKeeper providerkeeper.Keeper, - expectedChainID, expectedChannelID string, +// TestProviderStateIsCleanedAfterConsumerChainIsDeleted executes test assertions for the provider's state being cleaned +// after a deleted consumer chain. +func TestProviderStateIsCleanedAfterConsumerChainIsDeleted(t *testing.T, ctx sdk.Context, providerKeeper providerkeeper.Keeper, + consumerId, expectedChannelID string, expErr bool, ) { t.Helper() - _, found := providerKeeper.GetConsumerClientId(ctx, expectedChainID) + _, found := providerKeeper.GetConsumerClientId(ctx, consumerId) require.False(t, found) - _, found = providerKeeper.GetChainToChannel(ctx, expectedChainID) + _, found = providerKeeper.GetConsumerIdToChannelId(ctx, consumerId) require.False(t, found) - _, found = providerKeeper.GetChannelToChain(ctx, expectedChannelID) + _, found = providerKeeper.GetChannelIdToConsumerId(ctx, expectedChannelID) require.False(t, found) - _, found = providerKeeper.GetInitChainHeight(ctx, expectedChainID) + _, found = providerKeeper.GetInitChainHeight(ctx, consumerId) require.False(t, found) - acks := providerKeeper.GetSlashAcks(ctx, expectedChainID) + acks := providerKeeper.GetSlashAcks(ctx, consumerId) require.Empty(t, acks) - // in case the chain was successfully stopped, it should not contain a Top N associated to it - _, found = providerKeeper.GetTopN(ctx, expectedChainID) - require.False(t, found) - // test key assignment state is cleaned - require.Empty(t, providerKeeper.GetAllValidatorConsumerPubKeys(ctx, &expectedChainID)) - require.Empty(t, providerKeeper.GetAllValidatorsByConsumerAddr(ctx, &expectedChainID)) - require.Empty(t, providerKeeper.GetAllConsumerAddrsToPrune(ctx, expectedChainID)) - require.Empty(t, providerKeeper.GetAllCommissionRateValidators(ctx, expectedChainID)) - require.Zero(t, providerKeeper.GetEquivocationEvidenceMinHeight(ctx, expectedChainID)) + require.Empty(t, providerKeeper.GetAllValidatorConsumerPubKeys(ctx, &consumerId)) + require.Empty(t, providerKeeper.GetAllValidatorsByConsumerAddr(ctx, &consumerId)) + require.Empty(t, providerKeeper.GetAllConsumerAddrsToPrune(ctx, consumerId)) + require.Empty(t, providerKeeper.GetAllCommissionRateValidators(ctx, consumerId)) + require.Zero(t, providerKeeper.GetEquivocationEvidenceMinHeight(ctx, consumerId)) +} + +func GetTestConsumerMetadata() providertypes.ConsumerMetadata { + return providertypes.ConsumerMetadata{ + Name: "chain name", + Description: "description", + Metadata: "metadata", + } +} + +func GetTestInitializationParameters() providertypes.ConsumerInitializationParameters { + return providertypes.ConsumerInitializationParameters{ + InitialHeight: clienttypes.NewHeight(4, 5), + GenesisHash: []byte("gen_hash"), + BinaryHash: []byte("bin_hash"), + SpawnTime: time.Now().UTC(), + ConsumerRedistributionFraction: types.DefaultConsumerRedistributeFrac, + BlocksPerDistributionTransmission: types.DefaultBlocksPerDistributionTransmission, + DistributionTransmissionChannel: "", + HistoricalEntries: types.DefaultHistoricalEntries, + CcvTimeoutPeriod: types.DefaultCCVTimeoutPeriod, + TransferTimeoutPeriod: types.DefaultTransferTimeoutPeriod, + UnbondingPeriod: types.DefaultConsumerUnbondingPeriod, + } +} + +func GetTestPowerShapingParameters() providertypes.PowerShapingParameters { + return providertypes.PowerShapingParameters{ + Top_N: 0, + ValidatorsPowerCap: 0, + ValidatorSetCap: 0, + Allowlist: nil, + Denylist: nil, + MinStake: 0, + AllowInactiveVals: false, + } } -func GetTestConsumerAdditionProp() *providertypes.ConsumerAdditionProposal { - prop := providertypes.NewConsumerAdditionProposal( - "chainID", - "description", - "chainID", - clienttypes.NewHeight(4, 5), - []byte("gen_hash"), - []byte("bin_hash"), - time.Now(), - types.DefaultConsumerRedistributeFrac, - types.DefaultBlocksPerDistributionTransmission, - "", - types.DefaultHistoricalEntries, - types.DefaultCCVTimeoutPeriod, - types.DefaultTransferTimeoutPeriod, - types.DefaultConsumerUnbondingPeriod, - 0, - 0, - 0, - nil, - nil, - 0, - false, - ).(*providertypes.ConsumerAdditionProposal) - - return prop +func GetTestMsgUpdateConsumer() providertypes.MsgUpdateConsumer { + return providertypes.MsgUpdateConsumer{ + Owner: "owner", + ConsumerId: "consumerId", + NewOwnerAddress: "newOwnerAddress", + } } func GetTestMsgConsumerAddition() providertypes.MsgConsumerAddition { return providertypes.MsgConsumerAddition{ - ChainId: "a ChainID", + ChainId: "a ChainId", InitialHeight: clienttypes.NewHeight(4, 5), GenesisHash: []byte(base64.StdEncoding.EncodeToString([]byte("gen_hash"))), BinaryHash: []byte(base64.StdEncoding.EncodeToString([]byte("bin_hash"))), diff --git a/x/ccv/provider/client/cli/query.go b/x/ccv/provider/client/cli/query.go index 84fbff3fd0..c6e0d53159 100644 --- a/x/ccv/provider/client/cli/query.go +++ b/x/ccv/provider/client/cli/query.go @@ -2,6 +2,7 @@ package cli import ( "fmt" + "strconv" "strings" "github.com/spf13/cobra" @@ -26,20 +27,19 @@ func NewQueryCmd() *cobra.Command { cmd.AddCommand(CmdConsumerGenesis()) cmd.AddCommand(CmdConsumerChains()) - cmd.AddCommand(CmdConsumerStartProposals()) - cmd.AddCommand(CmdConsumerStopProposals()) cmd.AddCommand(CmdConsumerValidatorKeyAssignment()) cmd.AddCommand(CmdProviderValidatorKey()) cmd.AddCommand(CmdThrottleState()) cmd.AddCommand(CmdRegisteredConsumerRewardDenoms()) - cmd.AddCommand(CmdProposedConsumerChains()) - cmd.AddCommand(CmdAllPairsValConAddrByConsumerChainID()) + cmd.AddCommand(CmdAllPairsValConsAddrByConsumer()) cmd.AddCommand(CmdProviderParameters()) cmd.AddCommand(CmdConsumerChainOptedInValidators()) cmd.AddCommand(CmdConsumerValidators()) cmd.AddCommand(CmdConsumerChainsValidatorHasToValidate()) cmd.AddCommand(CmdValidatorConsumerCommissionRate()) cmd.AddCommand(CmdBlocksUntilNextEpoch()) + cmd.AddCommand(CmdConsumerIdFromClientId()) + cmd.AddCommand(CmdConsumerChain()) return cmd } @@ -47,8 +47,8 @@ func NewQueryCmd() *cobra.Command { // parameters managed by the x/params module. func CmdConsumerGenesis() *cobra.Command { cmd := &cobra.Command{ - Use: "consumer-genesis [chainid]", - Short: "Query for consumer chain genesis state by chain id", + Use: "consumer-genesis [consumer-id]", + Short: "Query for consumer chain genesis state by consumer id", Args: cobra.ExactArgs(1), RunE: func(cmd *cobra.Command, args []string) error { clientCtx, err := client.GetClientQueryContext(cmd) @@ -57,7 +57,7 @@ func CmdConsumerGenesis() *cobra.Command { } queryClient := types.NewQueryClient(clientCtx) - req := types.QueryConsumerGenesisRequest{ChainId: args[0]} + req := types.QueryConsumerGenesisRequest{ConsumerId: args[0]} res, err := queryClient.QueryConsumerGenesis(cmd.Context(), &req) if err != nil { return err @@ -74,9 +74,12 @@ func CmdConsumerGenesis() *cobra.Command { func CmdConsumerChains() *cobra.Command { cmd := &cobra.Command{ - Use: "list-consumer-chains", - Short: "Query active consumer chains for provider chain.", - Args: cobra.ExactArgs(0), + Use: "list-consumer-chains [phase] [limit]", + Short: "Query consumer chains for provider chain.", + Long: `Query consumer chains for provider chain. An optional + integer parameter can be passed for phase filtering of consumer chains, + (Registered=1|Initialized=2|Launched=3|Stopped=4|Deleted=5).`, + Args: cobra.MaximumNArgs(2), RunE: func(cmd *cobra.Command, args []string) (err error) { clientCtx, err := client.GetClientQueryContext(cmd) if err != nil { @@ -85,96 +88,24 @@ func CmdConsumerChains() *cobra.Command { queryClient := types.NewQueryClient(clientCtx) req := &types.QueryConsumerChainsRequest{} - res, err := queryClient.QueryConsumerChains(cmd.Context(), req) - if err != nil { - return err - } - - return clientCtx.PrintProto(res) - }, - } - - flags.AddQueryFlagsToCmd(cmd) - - return cmd -} - -func CmdProposedConsumerChains() *cobra.Command { - cmd := &cobra.Command{ - Use: "list-proposed-consumer-chains", - Short: "Query chainIDs in consumer addition proposal before voting finishes", - Args: cobra.ExactArgs(0), - RunE: func(cmd *cobra.Command, args []string) (err error) { - clientCtx, err := client.GetClientQueryContext(cmd) - if err != nil { - return err - } - queryClient := types.NewQueryClient(clientCtx) - - req := &types.QueryProposedChainIDsRequest{} - res, err := queryClient.QueryProposedConsumerChainIDs(cmd.Context(), req) - if err != nil { - return err - } - return clientCtx.PrintProto(res) - }, - } - - flags.AddQueryFlagsToCmd(cmd) - - return cmd -} - -func CmdConsumerStartProposals() *cobra.Command { - cmd := &cobra.Command{ - Use: "list-start-proposals", - Short: "Query consumer chains start proposals on provider chain.", - Long: `Query mature and pending consumer chains start proposals on provider chain. - Matured proposals will be executed on the next block - their spawn_time has passed - Pending proposals are waiting for their spawn_time to pass. - `, - Args: cobra.ExactArgs(0), - RunE: func(cmd *cobra.Command, args []string) (err error) { - clientCtx, err := client.GetClientQueryContext(cmd) - if err != nil { - return err + if len(args) >= 1 && args[0] != "" { + phase, err := strconv.ParseInt(args[0], 10, 32) + if err != nil { + return err + } + req.Phase = types.ConsumerPhase(phase) } - queryClient := types.NewQueryClient(clientCtx) - - req := &types.QueryConsumerChainStartProposalsRequest{} - res, err := queryClient.QueryConsumerChainStarts(cmd.Context(), req) - if err != nil { - return err - } - - return clientCtx.PrintProto(res) - }, - } - - flags.AddQueryFlagsToCmd(cmd) - - return cmd -} -func CmdConsumerStopProposals() *cobra.Command { - cmd := &cobra.Command{ - Use: "list-stop-proposals", - Short: "Query consumer chains stop proposals on provider chain.", - Long: `Query mature and pending consumer chains stop proposals on provider chain. - Matured proposals will be executed on the next block - their stop_time has passed - Pending proposals are waiting for their stop_time to pass. - `, - Args: cobra.ExactArgs(0), - RunE: func(cmd *cobra.Command, args []string) (err error) { - clientCtx, err := client.GetClientQueryContext(cmd) - if err != nil { - return err + if len(args) == 2 && args[1] != "" { + limit, err := strconv.ParseInt(args[1], 10, 32) + if err != nil { + return err + } + req.Limit = int32(limit) } - queryClient := types.NewQueryClient(clientCtx) - req := &types.QueryConsumerChainStopProposalsRequest{} - res, err := queryClient.QueryConsumerChainStops(cmd.Context(), req) + res, err := queryClient.QueryConsumerChains(cmd.Context(), req) if err != nil { return err } @@ -192,13 +123,13 @@ func CmdConsumerStopProposals() *cobra.Command { func CmdConsumerValidatorKeyAssignment() *cobra.Command { bech32PrefixConsAddr := sdk.GetConfig().GetBech32ConsensusAddrPrefix() cmd := &cobra.Command{ - Use: "validator-consumer-key [chainid] [provider-validator-address]", + Use: "validator-consumer-key [consumerId] [provider-validator-address]", Short: "Query assigned validator consensus public key for a consumer chain", Long: strings.TrimSpace( fmt.Sprintf(`Returns the currently assigned validator consensus public key for a consumer chain, if one has been assigned. Example: -$ %s query provider validator-consumer-key foochain %s1gghjut3ccd8ay0zduzj64hwre2fxs9ldmqhffj +$ %s query provider validator-consumer-key 3 %s1gghjut3ccd8ay0zduzj64hwre2fxs9ldmqhffj `, version.AppName, bech32PrefixConsAddr, ), @@ -211,7 +142,7 @@ $ %s query provider validator-consumer-key foochain %s1gghjut3ccd8ay0zduzj64hwre } queryClient := types.NewQueryClient(clientCtx) - consumerChainID := args[0] + consumerId := args[0] addr, err := sdk.ConsAddressFromBech32(args[1]) if err != nil { @@ -219,7 +150,7 @@ $ %s query provider validator-consumer-key foochain %s1gghjut3ccd8ay0zduzj64hwre } req := &types.QueryValidatorConsumerAddrRequest{ - ChainId: consumerChainID, + ConsumerId: consumerId, ProviderAddress: addr.String(), } res, err := queryClient.QueryValidatorConsumerAddr(cmd.Context(), req) @@ -240,12 +171,12 @@ $ %s query provider validator-consumer-key foochain %s1gghjut3ccd8ay0zduzj64hwre func CmdProviderValidatorKey() *cobra.Command { bech32PrefixConsAddr := sdk.GetConfig().GetBech32ConsensusAddrPrefix() cmd := &cobra.Command{ - Use: "validator-provider-key [chainid] [consumer-validator-address]", + Use: "validator-provider-key [consumer-id] [consumer-validator-address]", Short: "Query validator consensus public key for the provider chain", Long: strings.TrimSpace( fmt.Sprintf(`Returns the currently assigned validator consensus public key for the provider chain. Example: -$ %s query provider validator-provider-key foochain %s1gghjut3ccd8ay0zduzj64hwre2fxs9ldmqhffj +$ %s query provider validator-provider-key 333 %s1gghjut3ccd8ay0zduzj64hwre2fxs9ldmqhffj `, version.AppName, bech32PrefixConsAddr, ), @@ -258,7 +189,7 @@ $ %s query provider validator-provider-key foochain %s1gghjut3ccd8ay0zduzj64hwre } queryClient := types.NewQueryClient(clientCtx) - consumerChainID := args[0] + consumerID := args[0] addr, err := sdk.ConsAddressFromBech32(args[1]) if err != nil { @@ -266,7 +197,7 @@ $ %s query provider validator-provider-key foochain %s1gghjut3ccd8ay0zduzj64hwre } req := &types.QueryValidatorProviderAddrRequest{ - ChainId: consumerChainID, + ConsumerId: consumerID, ConsumerAddress: addr.String(), } res, err := queryClient.QueryValidatorProviderAddr(cmd.Context(), req) @@ -354,10 +285,10 @@ $ %s query provider registered-consumer-reward-denoms return cmd } -func CmdAllPairsValConAddrByConsumerChainID() *cobra.Command { +func CmdAllPairsValConsAddrByConsumer() *cobra.Command { cmd := &cobra.Command{ - Use: "all-pairs-valconsensus-address [consumer-chain-id]", - Short: "Query all pairs of valconsensus address by consumer chainId.", + Use: "all-pairs-valconsensus-address [consumer-id]", + Short: "Query all pairs of valconsensus address by consumer ID.", Args: cobra.ExactArgs(1), RunE: func(cmd *cobra.Command, args []string) error { clientCtx, err := client.GetClientQueryContext(cmd) @@ -366,8 +297,8 @@ func CmdAllPairsValConAddrByConsumerChainID() *cobra.Command { } queryClient := types.NewQueryClient(clientCtx) - req := types.QueryAllPairsValConAddrByConsumerChainIDRequest{ChainId: args[0]} - res, err := queryClient.QueryAllPairsValConAddrByConsumerChainID(cmd.Context(), &req) + req := types.QueryAllPairsValConsAddrByConsumerRequest{ConsumerId: args[0]} + res, err := queryClient.QueryAllPairsValConsAddrByConsumer(cmd.Context(), &req) if err != nil { return err } @@ -415,15 +346,15 @@ $ %s query provider params return cmd } -// Command to query opted-in validators by consumer chain ID +// Command to query opted-in validators by consumer ID func CmdConsumerChainOptedInValidators() *cobra.Command { cmd := &cobra.Command{ - Use: "consumer-opted-in-validators [chainid]", + Use: "consumer-opted-in-validators [consumer-id]", Short: "Query opted-in validators for a given consumer chain", Long: strings.TrimSpace( fmt.Sprintf(`Query opted-in validators for a given consumer chain. Example: -$ %s consumer-opted-in-validators foochain +$ %s consumer-opted-in-validators 3 `, version.AppName), ), Args: cobra.ExactArgs(1), @@ -435,7 +366,7 @@ $ %s consumer-opted-in-validators foochain queryClient := types.NewQueryClient(clientCtx) res, err := queryClient.QueryConsumerChainOptedInValidators(cmd.Context(), - &types.QueryConsumerChainOptedInValidatorsRequest{ChainId: args[0]}) + &types.QueryConsumerChainOptedInValidatorsRequest{ConsumerId: args[0]}) if err != nil { return err } @@ -449,16 +380,16 @@ $ %s consumer-opted-in-validators foochain return cmd } -// Command to query the consumer validators by consumer chain ID +// Command to query the consumer validators by consumer ID func CmdConsumerValidators() *cobra.Command { cmd := &cobra.Command{ - Use: "consumer-validators [chainid]", + Use: "consumer-validators [consumer-id]", Short: "Query the last set consumer-validator set for a given consumer chain", Long: strings.TrimSpace( fmt.Sprintf(`Query the last set consumer-validator set for a given consumer chain. Note that this does not necessarily mean that the consumer chain is currently using this validator set because a VSCPacket could be delayed, etc. Example: -$ %s consumer-validators foochain +$ %s consumer-validators 3 `, version.AppName), ), Args: cobra.ExactArgs(1), @@ -470,7 +401,7 @@ $ %s consumer-validators foochain queryClient := types.NewQueryClient(clientCtx) res, err := queryClient.QueryConsumerValidators(cmd.Context(), - &types.QueryConsumerValidatorsRequest{ChainId: args[0]}) + &types.QueryConsumerValidatorsRequest{ConsumerId: args[0]}) if err != nil { return err } @@ -531,12 +462,12 @@ $ %s has-to-validate %s1gghjut3ccd8ay0zduzj64hwre2fxs9ldmqhffj func CmdValidatorConsumerCommissionRate() *cobra.Command { bech32PrefixConsAddr := sdk.GetConfig().GetBech32ConsensusAddrPrefix() cmd := &cobra.Command{ - Use: "validator-consumer-commission-rate [chainid] [provider-validator-address]", + Use: "validator-consumer-commission-rate [consumer-id] [provider-validator-address]", Short: "Query the consumer commission rate a validator charges on a consumer chain", Long: strings.TrimSpace( fmt.Sprintf(`Query the consumer commission rate a validator charges on a consumer chain. Example: -$ %s validator-consumer-commission-rate foochain %s1gghjut3ccd8ay0zduzj64hwre2fxs9ldmqhffj +$ %s validator-consumer-commission-rate 3 %s1gghjut3ccd8ay0zduzj64hwre2fxs9ldmqhffj `, version.AppName, bech32PrefixConsAddr), ), Args: cobra.ExactArgs(2), @@ -554,7 +485,7 @@ $ %s validator-consumer-commission-rate foochain %s1gghjut3ccd8ay0zduzj64hwre2fx res, err := queryClient.QueryValidatorConsumerCommissionRate(cmd.Context(), &types.QueryValidatorConsumerCommissionRateRequest{ - ChainId: args[0], + ConsumerId: args[0], ProviderAddress: addr.String(), }) if err != nil { @@ -596,3 +527,57 @@ func CmdBlocksUntilNextEpoch() *cobra.Command { return cmd } + +func CmdConsumerIdFromClientId() *cobra.Command { + cmd := &cobra.Command{ + Use: "consumer-id-from-client-id [client-id]", + Short: "Query the consumer id of the chain associated with the provided client id", + Args: cobra.ExactArgs(1), + RunE: func(cmd *cobra.Command, args []string) error { + clientCtx, err := client.GetClientQueryContext(cmd) + if err != nil { + return err + } + queryClient := types.NewQueryClient(clientCtx) + + req := &types.QueryConsumerIdFromClientIdRequest{ClientId: args[0]} + res, err := queryClient.QueryConsumerIdFromClientId(cmd.Context(), req) + if err != nil { + return err + } + + return clientCtx.PrintProto(res) + }, + } + + flags.AddQueryFlagsToCmd(cmd) + + return cmd +} + +func CmdConsumerChain() *cobra.Command { + cmd := &cobra.Command{ + Use: "consumer-chain [consumer-id]", + Short: "Query the consumer chain associated with the consumer id", + Args: cobra.ExactArgs(1), + RunE: func(cmd *cobra.Command, args []string) error { + clientCtx, err := client.GetClientQueryContext(cmd) + if err != nil { + return err + } + queryClient := types.NewQueryClient(clientCtx) + + req := &types.QueryConsumerChainRequest{ConsumerId: args[0]} + res, err := queryClient.QueryConsumerChain(cmd.Context(), req) + if err != nil { + return err + } + + return clientCtx.PrintProto(res) + }, + } + + flags.AddQueryFlagsToCmd(cmd) + + return cmd +} diff --git a/x/ccv/provider/client/cli/tx.go b/x/ccv/provider/client/cli/tx.go index 4011a36a79..17414bc5ef 100644 --- a/x/ccv/provider/client/cli/tx.go +++ b/x/ccv/provider/client/cli/tx.go @@ -36,6 +36,9 @@ func GetTxCmd() *cobra.Command { cmd.AddCommand(NewAssignConsumerKeyCmd()) cmd.AddCommand(NewSubmitConsumerMisbehaviourCmd()) cmd.AddCommand(NewSubmitConsumerDoubleVotingCmd()) + cmd.AddCommand(NewCreateConsumerCmd()) + cmd.AddCommand(NewUpdateConsumerCmd()) + cmd.AddCommand(NewRemoveConsumerCmd()) cmd.AddCommand(NewOptInCmd()) cmd.AddCommand(NewOptOutCmd()) cmd.AddCommand(NewSetConsumerCommissionRateCmd()) @@ -45,7 +48,7 @@ func GetTxCmd() *cobra.Command { func NewAssignConsumerKeyCmd() *cobra.Command { cmd := &cobra.Command{ - Use: "assign-consensus-key [consumer-chain-id] [consumer-pubkey]", + Use: "assign-consensus-key [consumer-id] [consumer-pubkey]", Short: "assign a consensus public key to use for a consumer chain", Args: cobra.ExactArgs(2), RunE: func(cmd *cobra.Command, args []string) error { @@ -54,7 +57,7 @@ func NewAssignConsumerKeyCmd() *cobra.Command { return err } - signer := clientCtx.GetFromAddress().String() + submitter := clientCtx.GetFromAddress().String() txf, err := tx.NewFactoryCLI(clientCtx, cmd.Flags()) if err != nil { return err @@ -63,7 +66,7 @@ func NewAssignConsumerKeyCmd() *cobra.Command { providerValAddr := clientCtx.GetFromAddress() - msg, err := types.NewMsgAssignConsumerKey(args[0], sdk.ValAddress(providerValAddr), args[1], signer) + msg, err := types.NewMsgAssignConsumerKey(args[0], sdk.ValAddress(providerValAddr), args[1], submitter) if err != nil { return err } @@ -84,7 +87,7 @@ func NewAssignConsumerKeyCmd() *cobra.Command { func NewSubmitConsumerMisbehaviourCmd() *cobra.Command { cmd := &cobra.Command{ - Use: "submit-consumer-misbehaviour [misbehaviour]", + Use: "submit-consumer-misbehaviour [consumer-id] [misbehaviour]", Short: "submit an IBC misbehaviour for a consumer chain", Long: strings.TrimSpace( fmt.Sprintf(`Submit an IBC misbehaviour detected on a consumer chain. @@ -92,9 +95,9 @@ An IBC misbehaviour contains two conflicting IBC client headers, which are used The misbehaviour type definition can be found in the IBC client messages, see ibc-go/proto/ibc/core/client/v1/tx.proto. Example: -%s tx provider submit-consumer-misbehaviour [path/to/misbehaviour.json] --from node0 --home ../node0 --chain-id $CID +%s tx provider submit-consumer-misbehaviour [consumer-id] [path/to/misbehaviour.json] --from node0 --home ../node0 --chain-id $CID `, version.AppName)), - Args: cobra.ExactArgs(1), + Args: cobra.ExactArgs(2), RunE: func(cmd *cobra.Command, args []string) error { clientCtx, err := client.GetClientTxContext(cmd) if err != nil { @@ -120,7 +123,7 @@ Example: return fmt.Errorf("misbehaviour unmarshalling failed: %s", err) } - msg, err := types.NewMsgSubmitConsumerMisbehaviour(submitter, &misbehaviour) + msg, err := types.NewMsgSubmitConsumerMisbehaviour(args[0], submitter, &misbehaviour) if err != nil { return err } @@ -141,7 +144,7 @@ Example: func NewSubmitConsumerDoubleVotingCmd() *cobra.Command { cmd := &cobra.Command{ - Use: "submit-consumer-double-voting [evidence] [infraction_header]", + Use: "submit-consumer-double-voting [consumer-id] [evidence] [infraction_header]", Short: "submit a double voting evidence for a consumer chain", Long: strings.TrimSpace( fmt.Sprintf(`Submit a Tendermint duplicate vote evidence detected on a consumer chain with @@ -151,9 +154,9 @@ func NewSubmitConsumerDoubleVotingCmd() *cobra.Command { definition can be found in the IBC messages, see ibc-go/proto/ibc/lightclients/tendermint/v1/tendermint.proto. Example: -%s tx provider submit-consumer-double-voting [path/to/evidence.json] [path/to/infraction_header.json] --from node0 --home ../node0 --chain-id $CID +%s tx provider submit-consumer-double-voting [consumer-id] [path/to/evidence.json] [path/to/infraction_header.json] --from node0 --home ../node0 --chain-id $CID `, version.AppName)), - Args: cobra.ExactArgs(2), + Args: cobra.ExactArgs(3), RunE: func(cmd *cobra.Command, args []string) error { clientCtx, err := client.GetClientTxContext(cmd) if err != nil { @@ -190,7 +193,246 @@ Example: return fmt.Errorf("infraction IBC header unmarshalling failed: %s", err) } - msg, err := types.NewMsgSubmitConsumerDoubleVoting(submitter, &ev, &header) + msg, err := types.NewMsgSubmitConsumerDoubleVoting(args[0], submitter, &ev, &header) + if err != nil { + return err + } + if err := msg.ValidateBasic(); err != nil { + return err + } + + return tx.GenerateOrBroadcastTxWithFactory(clientCtx, txf, msg) + }, + } + + flags.AddTxFlagsToCmd(cmd) + + _ = cmd.MarkFlagRequired(flags.FlagFrom) + + return cmd +} + +func NewCreateConsumerCmd() *cobra.Command { + cmd := &cobra.Command{ + Use: "create-consumer [consumer-parameters]", + Short: "create a consumer chain", + Long: strings.TrimSpace( + fmt.Sprintf(`Create a consumer chain and get the assigned consumer id of this chain. +Note that the one that signs this message is the owner of this consumer chain. The owner can be later +changed by updating the consumer chain. + +Example: +%s tx provider create-consumer [path/to/create_consumer.json] --from node0 --home ../node0 --chain-id $CID + +where create_consumer.json has the following structure: +{ + "chain_id": "consu", + "metadata": { + "name": "chain consumer", + "description": "description", + "metadata": "metadata" + }, + "initialization_parameters": { + "initial_height": { + "revision_number": 0, + "revision_height": 1 + }, + "genesis_hash": "Z2VuX2hhc2g=", + "binary_hash": "YmluX2hhc2g=", + "spawn_time": "2024-08-29T12:26:16.529913Z", + "unbonding_period": 1728000000000000, + "ccv_timeout_period": 2419200000000000, + "transfer_timeout_period": 1800000000000, + "consumer_redistribution_fraction": "0.75", + "blocks_per_distribution_transmission": 1000, + "historical_entries": 10000, + "distribution_transmission_channel": "" + }, + "power_shaping_parameters": { + "top_N": 100, + "validators_power_cap": 0, + "validator_set_cap": 0, + "allowlist": [], + "denylist": [], + "min_stake": "0", + "allow_inactive_vals": false + } +} + +Note that both 'chain_id' and 'metadata' are mandatory; +and both 'initialization_parameters' and 'power_shaping_parameters' are optional. +The parameters not provided are set to their zero value. +`, version.AppName)), + Args: cobra.ExactArgs(1), + RunE: func(cmd *cobra.Command, args []string) error { + clientCtx, err := client.GetClientTxContext(cmd) + if err != nil { + return err + } + + txf, err := tx.NewFactoryCLI(clientCtx, cmd.Flags()) + if err != nil { + return err + } + txf = txf.WithTxConfig(clientCtx.TxConfig).WithAccountRetriever(clientCtx.AccountRetriever) + + submitter := clientCtx.GetFromAddress().String() + + consCreateJson, err := os.ReadFile(args[0]) + if err != nil { + return err + } + consCreate := types.MsgCreateConsumer{} + if err = json.Unmarshal(consCreateJson, &consCreate); err != nil { + return fmt.Errorf("consumer data unmarshalling failed: %w", err) + } + + msg, err := types.NewMsgCreateConsumer(submitter, consCreate.ChainId, consCreate.Metadata, consCreate.InitializationParameters, consCreate.PowerShapingParameters) + if err != nil { + return err + } + if err = msg.ValidateBasic(); err != nil { + return err + } + + return tx.GenerateOrBroadcastTxWithFactory(clientCtx, txf, msg) + }, + } + + flags.AddTxFlagsToCmd(cmd) + + _ = cmd.MarkFlagRequired(flags.FlagFrom) + + return cmd +} + +func NewUpdateConsumerCmd() *cobra.Command { + cmd := &cobra.Command{ + Use: "update-consumer [consumer-parameters]", + Short: "update a consumer chain", + Long: strings.TrimSpace( + fmt.Sprintf(`Update a consumer chain to change its parameters (e.g., spawn time, allow list, etc.). +Note that only the owner of the chain can initialize it. + +Example: +%s tx provider update-consumer [path/to/update_consumer.json] --from node0 --home ../node0 --chain-id $CID + +where update_consumer.json has the following structure: +{ + "consumer_id": "0", + "new_owner_address": "cosmos10d07y265gmmuvt4z0w9aw880jnsr700j6zn9kn", + "metadata": { + "name": "chain consumer", + "description": "description", + "metadata": "metadata" + }, + "initialization_parameters": { + "initial_height": { + "revision_number": 0, + "revision_height": 1 + }, + "genesis_hash": "Z2VuX2hhc2g=", + "binary_hash": "YmluX2hhc2g=", + "spawn_time": "2024-08-29T12:26:16.529913Z", + "unbonding_period": 1728000000000000, + "ccv_timeout_period": 2419200000000000, + "transfer_timeout_period": 1800000000000, + "consumer_redistribution_fraction": "0.75", + "blocks_per_distribution_transmission": 1000, + "historical_entries": 10000, + "distribution_transmission_channel": "" + }, + "power_shaping_parameters": { + "top_N": 100, + "validators_power_cap": 0, + "validator_set_cap": 0, + "allowlist": [], + "denylist": [], + "min_stake": "0", + "allow_inactive_vals": false + } +} + +Note that only 'consumer_id' is mandatory. The others are optional. +Not providing one of them will leave the existing values unchanged. +Providing one of 'metadata', 'initialization_parameters' or 'power_shaping_parameters', +will update all the containing fields. +If one of the fields is missing, it will be set to its zero value. +`, version.AppName)), + Args: cobra.ExactArgs(1), + RunE: func(cmd *cobra.Command, args []string) error { + clientCtx, err := client.GetClientTxContext(cmd) + if err != nil { + return err + } + + txf, err := tx.NewFactoryCLI(clientCtx, cmd.Flags()) + if err != nil { + return err + } + txf = txf.WithTxConfig(clientCtx.TxConfig).WithAccountRetriever(clientCtx.AccountRetriever) + + owner := clientCtx.GetFromAddress().String() + + consUpdateJson, err := os.ReadFile(args[0]) + if err != nil { + return err + } + + consUpdate := types.MsgUpdateConsumer{} + if err = json.Unmarshal(consUpdateJson, &consUpdate); err != nil { + return fmt.Errorf("consumer data unmarshalling failed: %w", err) + } + + if strings.TrimSpace(consUpdate.ConsumerId) == "" { + return fmt.Errorf("consumer_id can't be empty") + } + + msg, err := types.NewMsgUpdateConsumer(owner, consUpdate.ConsumerId, consUpdate.NewOwnerAddress, consUpdate.Metadata, consUpdate.InitializationParameters, consUpdate.PowerShapingParameters) + if err != nil { + return err + } + if err := msg.ValidateBasic(); err != nil { + return err + } + + return tx.GenerateOrBroadcastTxWithFactory(clientCtx, txf, msg) + }, + } + + flags.AddTxFlagsToCmd(cmd) + + _ = cmd.MarkFlagRequired(flags.FlagFrom) + + return cmd +} + +func NewRemoveConsumerCmd() *cobra.Command { + cmd := &cobra.Command{ + Use: "remove-consumer [consumer-id]", + Short: "remove a consumer chain", + Long: strings.TrimSpace( + fmt.Sprintf(`Removes (and stops) a consumer chain. Note that only the owner of the chain can remove it. +Example: +%s tx provider remove-consumer [consumer-id] --from node0 --home ../node0 --chain-id $CID +`, version.AppName)), + Args: cobra.ExactArgs(1), + RunE: func(cmd *cobra.Command, args []string) error { + clientCtx, err := client.GetClientTxContext(cmd) + if err != nil { + return err + } + + txf, err := tx.NewFactoryCLI(clientCtx, cmd.Flags()) + if err != nil { + return err + } + txf = txf.WithTxConfig(clientCtx.TxConfig).WithAccountRetriever(clientCtx.AccountRetriever) + + owner := clientCtx.GetFromAddress().String() + consumerId := args[0] + + msg, err := types.NewMsgRemoveConsumer(owner, consumerId) if err != nil { return err } @@ -211,7 +453,7 @@ Example: func NewOptInCmd() *cobra.Command { cmd := &cobra.Command{ - Use: "opt-in [consumer-chain-id] [consumer-pubkey]", + Use: "opt-in [consumer-id] [consumer-pubkey]", Short: "opts in validator to the consumer chain, and if given uses the " + "provided consensus public key for this consumer chain", Args: cobra.RangeArgs(1, 2), @@ -237,8 +479,8 @@ func NewOptInCmd() *cobra.Command { consumerPubKey = "" } - signer := clientCtx.GetFromAddress().String() - msg, err := types.NewMsgOptIn(args[0], sdk.ValAddress(providerValAddr), consumerPubKey, signer) + submitter := clientCtx.GetFromAddress().String() + msg, err := types.NewMsgOptIn(args[0], sdk.ValAddress(providerValAddr), consumerPubKey, submitter) if err != nil { return err } @@ -259,7 +501,7 @@ func NewOptInCmd() *cobra.Command { func NewOptOutCmd() *cobra.Command { cmd := &cobra.Command{ - Use: "opt-out [consumer-chain-id]", + Use: "opt-out [consumer-id]", Short: "opts out validator from this consumer chain", Args: cobra.ExactArgs(1), RunE: func(cmd *cobra.Command, args []string) error { @@ -276,8 +518,8 @@ func NewOptOutCmd() *cobra.Command { providerValAddr := clientCtx.GetFromAddress() - signer := clientCtx.GetFromAddress().String() - msg, err := types.NewMsgOptOut(args[0], sdk.ValAddress(providerValAddr), signer) + submitter := clientCtx.GetFromAddress().String() + msg, err := types.NewMsgOptOut(args[0], sdk.ValAddress(providerValAddr), submitter) if err != nil { return err } @@ -298,12 +540,12 @@ func NewOptOutCmd() *cobra.Command { func NewSetConsumerCommissionRateCmd() *cobra.Command { cmd := &cobra.Command{ - Use: "set-consumer-commission-rate [consumer-chain-id] [commission-rate]", + Use: "set-consumer-commission-rate [consumer-id] [commission-rate]", Short: "set a per-consumer chain commission", Long: strings.TrimSpace( fmt.Sprintf(`Note that the "commission-rate" argument is a fraction and should be in the range [0,1]. Example: - %s set-consumer-commission-rate consumer-1 0.5 --from node0 --home ../node0`, + %s set-consumer-commission-rate 123 0.5 --from node0 --home ../node0`, version.AppName), ), Args: cobra.ExactArgs(2), @@ -325,8 +567,8 @@ func NewSetConsumerCommissionRateCmd() *cobra.Command { if err != nil { return err } - signer := clientCtx.GetFromAddress().String() - msg := types.NewMsgSetConsumerCommissionRate(args[0], commission, sdk.ValAddress(providerValAddr), signer) + submitter := clientCtx.GetFromAddress().String() + msg := types.NewMsgSetConsumerCommissionRate(args[0], commission, sdk.ValAddress(providerValAddr), submitter) if err := msg.ValidateBasic(); err != nil { return err } diff --git a/x/ccv/provider/handler.go b/x/ccv/provider/handler.go index 78e17257de..937fcb1805 100644 --- a/x/ccv/provider/handler.go +++ b/x/ccv/provider/handler.go @@ -36,6 +36,15 @@ func NewHandler(k *keeper.Keeper) baseapp.MsgServiceHandler { case *types.MsgSetConsumerCommissionRate: res, err := msgServer.SetConsumerCommissionRate(ctx, msg) return sdk.WrapServiceResult(ctx, res, err) + case *types.MsgCreateConsumer: + res, err := msgServer.CreateConsumer(ctx, msg) + return sdk.WrapServiceResult(ctx, res, err) + case *types.MsgUpdateConsumer: + res, err := msgServer.UpdateConsumer(ctx, msg) + return sdk.WrapServiceResult(ctx, res, err) + case *types.MsgRemoveConsumer: + res, err := msgServer.RemoveConsumer(ctx, msg) + return sdk.WrapServiceResult(ctx, res, err) default: return nil, errorsmod.Wrapf(sdkerrors.ErrUnknownRequest, "unrecognized %s message type: %T", types.ModuleName, msg) } diff --git a/x/ccv/provider/handler_test.go b/x/ccv/provider/handler_test.go index 9c14efe91b..e8fa15d4d2 100644 --- a/x/ccv/provider/handler_test.go +++ b/x/ccv/provider/handler_test.go @@ -46,18 +46,16 @@ func TestAssignConsensusKeyMsgHandling(t *testing.T) { testCases := []struct { name string // State-mutating setup specific to this test case - setup func(sdk.Context, keeper.Keeper, testkeeper.MockedKeepers) - expError bool - chainID string + setup func(sdk.Context, keeper.Keeper, testkeeper.MockedKeepers) + expError bool + consumerId string }{ { name: "success", setup: func(ctx sdk.Context, k keeper.Keeper, mocks testkeeper.MockedKeepers, ) { - k.SetPendingConsumerAdditionProp(ctx, &providertypes.ConsumerAdditionProposal{ - ChainId: "chainid", - }) + k.SetConsumerPhase(ctx, "consumerId", providertypes.CONSUMER_PHASE_INITIALIZED) gomock.InOrder( mocks.MockStakingKeeper.EXPECT().GetValidator( ctx, providerCryptoId.SDKValOpAddress(), @@ -67,11 +65,11 @@ func TestAssignConsensusKeyMsgHandling(t *testing.T) { ).Return(stakingtypes.Validator{}, stakingtypes.ErrNoValidatorFound), ) }, - expError: false, - chainID: "chainid", + expError: false, + consumerId: "consumerId", }, { - name: "fail: chain ID not registered", + name: "fail: consumer id does not correspond to a registered chain", setup: func(ctx sdk.Context, k keeper.Keeper, mocks testkeeper.MockedKeepers, ) { @@ -82,36 +80,33 @@ func TestAssignConsensusKeyMsgHandling(t *testing.T) { ).Return(providerCryptoId.SDKStakingValidator(), nil).Times(1), ) }, - expError: true, - chainID: "chainid", + expError: true, + consumerId: "consumerId", }, { name: "fail: missing validator", setup: func(ctx sdk.Context, k keeper.Keeper, mocks testkeeper.MockedKeepers, ) { - k.SetPendingConsumerAdditionProp(ctx, &providertypes.ConsumerAdditionProposal{ - ChainId: "chainid", - }) + k.SetConsumerPhase(ctx, "consumerId", providertypes.CONSUMER_PHASE_INITIALIZED) gomock.InOrder( mocks.MockStakingKeeper.EXPECT().GetValidator( ctx, providerCryptoId.SDKValOpAddress(), ).Return(stakingtypes.Validator{}, stakingtypes.ErrNoValidatorFound).Times(1), ) }, - expError: true, - chainID: "chainid", + expError: true, + consumerId: "consumerId", }, { name: "fail: consumer key in use by other validator", setup: func(ctx sdk.Context, k keeper.Keeper, mocks testkeeper.MockedKeepers, ) { - k.SetPendingConsumerAdditionProp(ctx, &providertypes.ConsumerAdditionProposal{ - ChainId: "chainid", - }) + k.SetConsumerPhase(ctx, "consumerId", providertypes.CONSUMER_PHASE_INITIALIZED) + // Use the consumer key already used by some other validator - k.SetValidatorByConsumerAddr(ctx, "chainid", consumerConsAddr, providerConsAddr2) + k.SetValidatorByConsumerAddr(ctx, "consumerId", consumerConsAddr, providerConsAddr2) gomock.InOrder( mocks.MockStakingKeeper.EXPECT().GetValidator( @@ -124,19 +119,18 @@ func TestAssignConsensusKeyMsgHandling(t *testing.T) { ).Return(stakingtypes.Validator{}, nil), ) }, - expError: true, - chainID: "chainid", + expError: true, + consumerId: "consumerId", }, { name: "fail: consumer key in use by the same validator", setup: func(ctx sdk.Context, k keeper.Keeper, mocks testkeeper.MockedKeepers, ) { - k.SetPendingConsumerAdditionProp(ctx, &providertypes.ConsumerAdditionProposal{ - ChainId: "chainid", - }) + k.SetConsumerPhase(ctx, "consumerId", providertypes.CONSUMER_PHASE_INITIALIZED) + // Use the consumer key already - k.SetValidatorByConsumerAddr(ctx, "chainid", consumerConsAddr, providerConsAddr) + k.SetValidatorByConsumerAddr(ctx, "consumerId", consumerConsAddr, providerConsAddr) gomock.InOrder( mocks.MockStakingKeeper.EXPECT().GetValidator( @@ -147,20 +141,18 @@ func TestAssignConsensusKeyMsgHandling(t *testing.T) { ).Return(stakingtypes.Validator{}, stakingtypes.ErrNoValidatorFound), ) }, - expError: true, - chainID: "chainid", + expError: true, + consumerId: "consumerId", }, { name: "fail: consumer key in use by other validator", setup: func(ctx sdk.Context, k keeper.Keeper, mocks testkeeper.MockedKeepers, ) { - k.SetPendingConsumerAdditionProp(ctx, &providertypes.ConsumerAdditionProposal{ - ChainId: "chainid", - }) + k.SetConsumerPhase(ctx, "consumerId", providertypes.CONSUMER_PHASE_INITIALIZED) // Use the consumer key already used by some other validator - k.SetValidatorByConsumerAddr(ctx, "chainid", consumerConsAddr, providerConsAddr2) + k.SetValidatorByConsumerAddr(ctx, "consumerId", consumerConsAddr, providerConsAddr2) gomock.InOrder( mocks.MockStakingKeeper.EXPECT().GetValidator( @@ -173,8 +165,8 @@ func TestAssignConsensusKeyMsgHandling(t *testing.T) { ).Return(stakingtypes.Validator{}, stakingtypes.ErrNoValidatorFound), ) }, - expError: true, - chainID: "chainid", + expError: true, + consumerId: "consumerId", }, } @@ -183,8 +175,9 @@ func TestAssignConsensusKeyMsgHandling(t *testing.T) { k, ctx, ctrl, mocks := testkeeper.GetProviderKeeperAndCtx(t, testkeeper.NewInMemKeeperParams(t)) tc.setup(ctx, k, mocks) + k.SetConsumerChainId(ctx, tc.consumerId, tc.name) - msg, err := providertypes.NewMsgAssignConsumerKey(tc.chainID, + msg, err := providertypes.NewMsgAssignConsumerKey(tc.consumerId, providerCryptoId.SDKValOpAddress(), consumerKey, providerCryptoId.SDKStakingValidator().OperatorAddress, ) diff --git a/x/ccv/provider/ibc_middleware.go b/x/ccv/provider/ibc_middleware.go index d9d816ab93..3872fd5fbe 100644 --- a/x/ccv/provider/ibc_middleware.go +++ b/x/ccv/provider/ibc_middleware.go @@ -122,7 +122,7 @@ func (im IBCMiddleware) OnRecvPacket( // deserialized without checking errors. if ack.Success() { // execute the middleware logic only if the sender is a consumer chain - consumerID, err := im.keeper.IdentifyConsumerChainIDFromIBCPacket(ctx, packet) + consumerId, err := im.keeper.IdentifyConsumerIdFromIBCPacket(ctx, packet) if err != nil { return ack } @@ -144,13 +144,13 @@ func (im IBCMiddleware) OnRecvPacket( // and if so, adds it to the consumer chain rewards allocation, // otherwise the prohibited coin just stays in the pool forever. if im.keeper.ConsumerRewardDenomExists(ctx, coinDenom) { - alloc := im.keeper.GetConsumerRewardsAllocation(ctx, consumerID) + alloc := im.keeper.GetConsumerRewardsAllocation(ctx, consumerId) alloc.Rewards = alloc.Rewards.Add( sdk.NewDecCoinsFromCoins(sdk.Coin{ Denom: coinDenom, Amount: coinAmt, })...) - im.keeper.SetConsumerRewardsAllocation(ctx, consumerID, alloc) + im.keeper.SetConsumerRewardsAllocation(ctx, consumerId, alloc) } } diff --git a/x/ccv/provider/ibc_module_test.go b/x/ccv/provider/ibc_module_test.go index 58573d3e3b..0a06bf6091 100644 --- a/x/ccv/provider/ibc_module_test.go +++ b/x/ccv/provider/ibc_module_test.go @@ -96,17 +96,17 @@ func TestOnChanOpenTry(t *testing.T) { "unexpected client ID mapped to chain ID", func(params *params, keeper *providerkeeper.Keeper) { keeper.SetConsumerClientId( params.ctx, - "consumerChainID", - "invalidClientID", + "consumerId", + "invalidClientId", ) }, false, }, { "other CCV channel exists for this consumer chain", func(params *params, keeper *providerkeeper.Keeper) { - keeper.SetChainToChannel( + keeper.SetConsumerIdToChannelId( params.ctx, - "consumerChainID", + "consumerId", "some existing channel ID", ) }, false, @@ -122,7 +122,7 @@ func TestOnChanOpenTry(t *testing.T) { providerModule := provider.NewAppModule(&providerKeeper, *keeperParams.ParamsSubspace, keeperParams.StoreKey) providerKeeper.SetPort(ctx, ccv.ProviderPortID) - providerKeeper.SetConsumerClientId(ctx, "consumerChainID", "clientIDToConsumer") + providerKeeper.SetConsumerClientId(ctx, "consumerId", "clientIdToConsumer") // Instantiate valid params as default. Individual test cases mutate these as needed. params := params{ @@ -145,9 +145,9 @@ func TestOnChanOpenTry(t *testing.T) { mocks.MockScopedKeeper.EXPECT().ClaimCapability( params.ctx, params.chanCap, host.ChannelCapabilityPath(params.portID, params.channelID)).AnyTimes(), mocks.MockConnectionKeeper.EXPECT().GetConnection(ctx, "connectionIDToConsumer").Return( - conntypes.ConnectionEnd{ClientId: "clientIDToConsumer"}, true, + conntypes.ConnectionEnd{ClientId: "clientIdToConsumer"}, true, ).AnyTimes(), - mocks.MockClientKeeper.EXPECT().GetClientState(ctx, "clientIDToConsumer").Return( + mocks.MockClientKeeper.EXPECT().GetClientState(ctx, "clientIdToConsumer").Return( &ibctmtypes.ClientState{ChainId: "consumerChainID"}, true, ).AnyTimes(), mocks.MockAccountKeeper.EXPECT().GetModuleAccount(ctx, providertypes.ConsumerRewardsPool).Return(&moduleAcct).AnyTimes(), @@ -170,13 +170,13 @@ func TestOnChanOpenTry(t *testing.T) { require.NoError(t, err) md := &ccv.HandshakeMetadata{} err = md.Unmarshal([]byte(metadata)) - require.NoError(t, err) + require.NoError(t, err, tc.name) require.Equal(t, moduleAcct.BaseAccount.Address, md.ProviderFeePoolAddr, "returned dist account metadata must match expected") require.Equal(t, ccv.Version, md.Version, "returned ccv version metadata must match expected") ctrl.Finish() } else { - require.Error(t, err) + require.Error(t, err, tc.name) } } } @@ -309,9 +309,11 @@ func TestOnChanOpenConfirm(t *testing.T) { gomock.InOrder(tc.mockExpectations(ctx, mocks)...) if tc.setDuplicateChannel { - providerKeeper.SetChainToChannel(ctx, "consumerChainID", "existingChannelID") + providerKeeper.SetConsumerIdToChannelId(ctx, "consumerChainID", "existingChannelID") } + providerKeeper.SetConsumerClientId(ctx, "consumerChainID", "clientID") + providerModule := provider.NewAppModule(&providerKeeper, *keeperParams.ParamsSubspace, keeperParams.StoreKey) err := providerModule.OnChanOpenConfirm(ctx, "providerPortID", "channelID") @@ -320,11 +322,11 @@ func TestOnChanOpenConfirm(t *testing.T) { require.NoError(t, err) // Validate channel mappings - channelID, found := providerKeeper.GetChainToChannel(ctx, "consumerChainID") + channelID, found := providerKeeper.GetConsumerIdToChannelId(ctx, "consumerChainID") require.True(t, found) require.Equal(t, "channelID", channelID) - chainID, found := providerKeeper.GetChannelToChain(ctx, "channelID") + chainID, found := providerKeeper.GetChannelIdToConsumerId(ctx, "channelID") require.True(t, found) require.Equal(t, "consumerChainID", chainID) diff --git a/x/ccv/provider/keeper/consumer_equivocation.go b/x/ccv/provider/keeper/consumer_equivocation.go index 8f4f59732a..7bd7bac45c 100644 --- a/x/ccv/provider/keeper/consumer_equivocation.go +++ b/x/ccv/provider/keeper/consumer_equivocation.go @@ -28,56 +28,64 @@ import ( // Double Voting section // -// HandleConsumerDoubleVoting verifies a double voting evidence for a given a consumer chain ID +// HandleConsumerDoubleVoting verifies a double voting evidence for a given a consumer id // and a public key and, if successful, executes the slashing, jailing, and tombstoning of the malicious validator. func (k Keeper) HandleConsumerDoubleVoting( ctx sdk.Context, + consumerId string, evidence *tmtypes.DuplicateVoteEvidence, - chainID string, pubkey cryptotypes.PubKey, ) error { // check that the evidence is for an ICS consumer chain - if _, found := k.GetConsumerClientId(ctx, chainID); !found { + if _, found := k.GetConsumerClientId(ctx, consumerId); !found { return errorsmod.Wrapf( ccvtypes.ErrInvalidDoubleVotingEvidence, "cannot find consumer chain %s", - chainID, + consumerId, ) } // check that the evidence is not too old - minHeight := k.GetEquivocationEvidenceMinHeight(ctx, chainID) + minHeight := k.GetEquivocationEvidenceMinHeight(ctx, consumerId) if uint64(evidence.VoteA.Height) < minHeight { return errorsmod.Wrapf( ccvtypes.ErrInvalidDoubleVotingEvidence, "evidence for consumer chain %s is too old - evidence height (%d), min (%d)", - chainID, + consumerId, evidence.VoteA.Height, minHeight, ) } + // get the chainId of this consumer chain to verify the double-voting evidence + chainId, err := k.GetConsumerChainId(ctx, consumerId) + if err != nil { + return err + } + // verifies the double voting evidence using the consumer chain public key - if err := k.VerifyDoubleVotingEvidence(*evidence, chainID, pubkey); err != nil { + if err = k.VerifyDoubleVotingEvidence(*evidence, chainId, pubkey); err != nil { return err } // get the validator's consensus address on the provider providerAddr := k.GetProviderAddrFromConsumerAddr( ctx, - chainID, + consumerId, types.NewConsumerConsAddress(sdk.ConsAddress(evidence.VoteA.ValidatorAddress.Bytes())), ) - if err := k.SlashValidator(ctx, providerAddr); err != nil { + if err = k.SlashValidator(ctx, providerAddr); err != nil { return err } - if err := k.JailAndTombstoneValidator(ctx, providerAddr); err != nil { + if err = k.JailAndTombstoneValidator(ctx, providerAddr); err != nil { return err } k.Logger(ctx).Info( "confirmed equivocation", + "consumerId", consumerId, + "chainId", chainId, "byzantine validator address", providerAddr.String(), ) @@ -88,7 +96,7 @@ func (k Keeper) HandleConsumerDoubleVoting( // for a given chain id and a validator public key func (k Keeper) VerifyDoubleVotingEvidence( evidence tmtypes.DuplicateVoteEvidence, - chainID string, + chainId string, pubkey cryptotypes.PubKey, ) error { if pubkey == nil { @@ -140,10 +148,10 @@ func (k Keeper) VerifyDoubleVotingEvidence( vb := evidence.VoteB.ToProto() // signatures must be valid - if !pubkey.VerifySignature(tmtypes.VoteSignBytes(chainID, va), evidence.VoteA.Signature) { + if !pubkey.VerifySignature(tmtypes.VoteSignBytes(chainId, va), evidence.VoteA.Signature) { return fmt.Errorf("verifying VoteA: %w", tmtypes.ErrVoteInvalidSignature) } - if !pubkey.VerifySignature(tmtypes.VoteSignBytes(chainID, vb), evidence.VoteB.Signature) { + if !pubkey.VerifySignature(tmtypes.VoteSignBytes(chainId, vb), evidence.VoteB.Signature) { return fmt.Errorf("verifying VoteB: %w", tmtypes.ErrVoteInvalidSignature) } @@ -156,11 +164,11 @@ func (k Keeper) VerifyDoubleVotingEvidence( // HandleConsumerMisbehaviour checks if the given IBC misbehaviour corresponds to an equivocation light client attack, // and in this case, slashes, jails, and tombstones -func (k Keeper) HandleConsumerMisbehaviour(ctx sdk.Context, misbehaviour ibctmtypes.Misbehaviour) error { +func (k Keeper) HandleConsumerMisbehaviour(ctx sdk.Context, consumerId string, misbehaviour ibctmtypes.Misbehaviour) error { logger := k.Logger(ctx) // Check that the misbehaviour is valid and that the client consensus states at trusted heights are within trusting period - if err := k.CheckMisbehaviour(ctx, misbehaviour); err != nil { + if err := k.CheckMisbehaviour(ctx, consumerId, misbehaviour); err != nil { logger.Info("Misbehaviour rejected", err.Error()) return err @@ -182,7 +190,7 @@ func (k Keeper) HandleConsumerMisbehaviour(ctx sdk.Context, misbehaviour ibctmty for _, v := range byzantineValidators { providerAddr := k.GetProviderAddrFromConsumerAddr( ctx, - misbehaviour.Header1.Header.ChainID, + consumerId, types.NewConsumerConsAddress(sdk.ConsAddress(v.Address.Bytes())), ) err := k.SlashValidator(ctx, providerAddr) @@ -208,6 +216,7 @@ func (k Keeper) HandleConsumerMisbehaviour(ctx sdk.Context, misbehaviour ibctmty logger.Info( "confirmed equivocation light client attack", + "consumerId", consumerId, "byzantine validators slashed, jailed and tombstoned", provAddrs, ) @@ -292,16 +301,26 @@ func headerToLightBlock(h ibctmtypes.Header) (*tmtypes.LightBlock, error) { // CheckMisbehaviour checks that headers in the given misbehaviour forms // a valid light client attack from an ICS consumer chain and that the light client isn't expired -func (k Keeper) CheckMisbehaviour(ctx sdk.Context, misbehaviour ibctmtypes.Misbehaviour) error { - consumerChainID := misbehaviour.Header1.Header.ChainID +func (k Keeper) CheckMisbehaviour(ctx sdk.Context, consumerId string, misbehaviour ibctmtypes.Misbehaviour) error { + chainId := misbehaviour.Header1.Header.ChainID + + consumerChainId, err := k.GetConsumerChainId(ctx, consumerId) + if err != nil { + return err + } else if consumerChainId != chainId { + return fmt.Errorf("incorrect misbehaviour for a different chain id (%s) than that of the consumer chain %s (consumerId: %s)", + chainId, + consumerChainId, + consumerId) + } // check that the misbehaviour is for an ICS consumer chain - clientId, found := k.GetConsumerClientId(ctx, consumerChainID) + clientId, found := k.GetConsumerClientId(ctx, consumerId) if !found { - return fmt.Errorf("incorrect misbehaviour with conflicting headers from a non-existent consumer chain: %s", consumerChainID) + return fmt.Errorf("incorrect misbehaviour with conflicting headers from a non-existent consumer chain (consumerId: %s)", consumerId) } else if misbehaviour.ClientId != clientId { - return fmt.Errorf("incorrect misbehaviour: expected client ID for consumer chain %s is %s got %s", - consumerChainID, + return fmt.Errorf("incorrect misbehaviour: expected client ID for consumer chain with id %s is %s got %s", + consumerId, clientId, misbehaviour.ClientId, ) @@ -315,7 +334,7 @@ func (k Keeper) CheckMisbehaviour(ctx sdk.Context, misbehaviour ibctmtypes.Misbe } // Check that the evidence is not too old - minHeight := k.GetEquivocationEvidenceMinHeight(ctx, consumerChainID) + minHeight := k.GetEquivocationEvidenceMinHeight(ctx, consumerId) evidenceHeight := misbehaviour.Header1.GetHeight().GetRevisionHeight() // Note that the revision number is not relevant for checking the age of evidence // as it's already part of the chain ID and the minimum height is mapped to chain IDs @@ -323,7 +342,7 @@ func (k Keeper) CheckMisbehaviour(ctx sdk.Context, misbehaviour ibctmtypes.Misbe return errorsmod.Wrapf( ccvtypes.ErrInvalidDoubleVotingEvidence, "evidence for consumer chain %s is too old - evidence height (%d), min (%d)", - consumerChainID, + consumerId, evidenceHeight, minHeight, ) @@ -517,20 +536,20 @@ func (k Keeper) SlashValidator(ctx sdk.Context, providerAddr types.ProviderConsA // // SetEquivocationEvidenceMinHeight sets the minimum height -// of a valid consumer equivocation evidence for a given consumer chain ID -func (k Keeper) SetEquivocationEvidenceMinHeight(ctx sdk.Context, chainID string, height uint64) { +// of a valid consumer equivocation evidence for a given consumer id +func (k Keeper) SetEquivocationEvidenceMinHeight(ctx sdk.Context, consumerId string, height uint64) { store := ctx.KVStore(k.storeKey) heightBytes := make([]byte, 8) binary.BigEndian.PutUint64(heightBytes, height) - store.Set(types.EquivocationEvidenceMinHeightKey(chainID), heightBytes) + store.Set(types.EquivocationEvidenceMinHeightKey(consumerId), heightBytes) } // GetEquivocationEvidenceMinHeight returns the minimum height -// of a valid consumer equivocation evidence for a given consumer chain ID -func (k Keeper) GetEquivocationEvidenceMinHeight(ctx sdk.Context, chainID string) uint64 { +// of a valid consumer equivocation evidence for a given consumer id +func (k Keeper) GetEquivocationEvidenceMinHeight(ctx sdk.Context, consumerId string) uint64 { store := ctx.KVStore(k.storeKey) - bz := store.Get(types.EquivocationEvidenceMinHeightKey(chainID)) + bz := store.Get(types.EquivocationEvidenceMinHeightKey(consumerId)) if bz == nil { return 0 } @@ -539,8 +558,8 @@ func (k Keeper) GetEquivocationEvidenceMinHeight(ctx sdk.Context, chainID string } // DeleteEquivocationEvidenceMinHeight deletes the minimum height -// of a valid consumer equivocation evidence for a given consumer chain ID -func (k Keeper) DeleteEquivocationEvidenceMinHeight(ctx sdk.Context, chainID string) { +// of a valid consumer equivocation evidence for a given consumer id +func (k Keeper) DeleteEquivocationEvidenceMinHeight(ctx sdk.Context, consumerId string) { store := ctx.KVStore(k.storeKey) - store.Delete(types.EquivocationEvidenceMinHeightKey(chainID)) + store.Delete(types.EquivocationEvidenceMinHeightKey(consumerId)) } diff --git a/x/ccv/provider/keeper/consumer_lifecycle.go b/x/ccv/provider/keeper/consumer_lifecycle.go new file mode 100644 index 0000000000..20014c3c35 --- /dev/null +++ b/x/ccv/provider/keeper/consumer_lifecycle.go @@ -0,0 +1,670 @@ +package keeper + +import ( + "fmt" + "time" + + tmtypes "github.com/cometbft/cometbft/types" + + errorsmod "cosmossdk.io/errors" + storetypes "cosmossdk.io/store/types" + + sdk "github.com/cosmos/cosmos-sdk/types" + sdkerrors "github.com/cosmos/cosmos-sdk/types/errors" + stakingtypes "github.com/cosmos/cosmos-sdk/x/staking/types" + + clienttypes "github.com/cosmos/ibc-go/v8/modules/core/02-client/types" + channeltypes "github.com/cosmos/ibc-go/v8/modules/core/04-channel/types" + commitmenttypes "github.com/cosmos/ibc-go/v8/modules/core/23-commitment/types" + ibctmtypes "github.com/cosmos/ibc-go/v8/modules/light-clients/07-tendermint" + + "github.com/cosmos/interchain-security/v5/x/ccv/provider/types" + ccv "github.com/cosmos/interchain-security/v5/x/ccv/types" +) + +// PrepareConsumerForLaunch prepares to move the launch of a consumer chain from the previous spawn time to spawn time. +// Previous spawn time can correspond to its zero value if the validator was not previously set for launch. +func (k Keeper) PrepareConsumerForLaunch(ctx sdk.Context, consumerId string, previousSpawnTime time.Time, spawnTime time.Time) error { + if !previousSpawnTime.Equal(time.Time{}) { + // if this is not the first initialization and hence `previousSpawnTime` does not contain the zero value of `Time` + // remove the consumer id from the previous spawn time + err := k.RemoveConsumerToBeLaunched(ctx, consumerId, previousSpawnTime) + if err != nil { + return err + } + } + return k.AppendConsumerToBeLaunched(ctx, consumerId, spawnTime) +} + +// InitializeConsumer tries to move a consumer with `consumerId` to the initialized phase. +// If successfull, it returns the spawn time and true. +func (k Keeper) InitializeConsumer(ctx sdk.Context, consumerId string) (time.Time, bool) { + // a chain needs to be in the registered or initialized phase + phase := k.GetConsumerPhase(ctx, consumerId) + if phase != types.CONSUMER_PHASE_REGISTERED && phase != types.CONSUMER_PHASE_INITIALIZED { + return time.Time{}, false + } + + initializationParameters, err := k.GetConsumerInitializationParameters(ctx, consumerId) + if err != nil { + return time.Time{}, false + } + + // the spawn time needs to be positive + if initializationParameters.SpawnTime.IsZero() { + return time.Time{}, false + } + + k.SetConsumerPhase(ctx, consumerId, types.CONSUMER_PHASE_INITIALIZED) + + return initializationParameters.SpawnTime, true +} + +// BeginBlockLaunchConsumers launches initialized consumers that are ready to launch +func (k Keeper) BeginBlockLaunchConsumers(ctx sdk.Context) { + // TODO (PERMISSIONLESS): we can parameterize the limit + for _, consumerId := range k.GetConsumersReadyToLaunch(ctx, 200) { + initializationParameters, err := k.GetConsumerInitializationParameters(ctx, consumerId) + if err != nil { + ctx.Logger().Error("could not retrieve initialization record", + "consumerId", consumerId, + "error", err) + continue + } + // Remove consumer to prevent re-trying launching this chain. + // We would only try to re-launch this chain if a new `MsgUpdateConsumer` message is sent. + err = k.RemoveConsumerToBeLaunched(ctx, consumerId, initializationParameters.SpawnTime) + if err != nil { + ctx.Logger().Error("could not remove consumer from to-be-launched queue", + "consumerId", consumerId, + "error", err) + continue + } + + cachedCtx, writeFn := ctx.CacheContext() + err = k.LaunchConsumer(cachedCtx, consumerId) + if err != nil { + ctx.Logger().Error("could not launch chain", + "consumerId", consumerId, + "error", err) + continue + } + + // the cached context is created with a new EventManager, so we merge the events into the original context + ctx.EventManager().EmitEvents(cachedCtx.EventManager().Events()) + writeFn() + } +} + +// GetConsumersReadyToLaunch returns the consumer ids of the pending initialized consumer chains +// that are ready to launch, i.e., consumer clients to be created. +func (k Keeper) GetConsumersReadyToLaunch(ctx sdk.Context, limit uint32) []string { + store := ctx.KVStore(k.storeKey) + + spawnTimeToConsumerIdsKeyPrefix := types.SpawnTimeToConsumerIdsKeyPrefix() + iterator := storetypes.KVStorePrefixIterator(store, []byte{spawnTimeToConsumerIdsKeyPrefix}) + defer iterator.Close() + + result := []string{} + for ; iterator.Valid(); iterator.Next() { + spawnTime, err := types.ParseTime(spawnTimeToConsumerIdsKeyPrefix, iterator.Key()) + if err != nil { + k.Logger(ctx).Error("failed to parse spawn time", + "error", err) + continue + } + if spawnTime.After(ctx.BlockTime()) { + return result + } + + // if current block time is equal to or after spawnTime, and the chain is initialized, we can launch the chain + consumerIds, err := k.GetConsumersToBeLaunched(ctx, spawnTime) + if err != nil { + k.Logger(ctx).Error("failed to retrieve consumers to launch", + "spawn time", spawnTime, + "error", err) + continue + } + if len(result)+len(consumerIds.Ids) >= int(limit) { + remainingConsumerIds := len(result) + len(consumerIds.Ids) - int(limit) + if len(consumerIds.Ids[:len(consumerIds.Ids)-remainingConsumerIds]) == 0 { + return result + } + return append(result, consumerIds.Ids[:len(consumerIds.Ids)-remainingConsumerIds]...) + } else { + result = append(result, consumerIds.Ids...) + } + } + + return result +} + +// LaunchConsumer launches the chain with the provided consumer id by creating the consumer client and the respective +// consumer genesis file +func (k Keeper) LaunchConsumer(ctx sdk.Context, consumerId string) error { + err := k.CreateConsumerClient(ctx, consumerId) + if err != nil { + return err + } + + consumerGenesis, found := k.GetConsumerGenesis(ctx, consumerId) + if !found { + return errorsmod.Wrapf(types.ErrNoConsumerGenesis, "consumer genesis could not be found for consumer id: %s", consumerId) + } + + if len(consumerGenesis.Provider.InitialValSet) == 0 { + return errorsmod.Wrapf(types.ErrInvalidConsumerGenesis, "consumer genesis initial validator set is empty - no validators opted in consumer id: %s", consumerId) + } + + k.SetConsumerPhase(ctx, consumerId, types.CONSUMER_PHASE_LAUNCHED) + + return nil +} + +// CreateConsumerClient will create the CCV client for the given consumer chain. The CCV channel must be built +// on top of the CCV client to ensure connection with the right consumer chain. +func (k Keeper) CreateConsumerClient(ctx sdk.Context, consumerId string) error { + initializationRecord, err := k.GetConsumerInitializationParameters(ctx, consumerId) + if err != nil { + return err + } + + phase := k.GetConsumerPhase(ctx, consumerId) + if phase != types.CONSUMER_PHASE_INITIALIZED { + return errorsmod.Wrapf(types.ErrInvalidPhase, + "cannot create client for consumer chain that is not in the Initialized phase but in phase %d: %s", phase, consumerId) + } + + chainId, err := k.GetConsumerChainId(ctx, consumerId) + if err != nil { + return err + } + + // Set minimum height for equivocation evidence from this consumer chain + k.SetEquivocationEvidenceMinHeight(ctx, consumerId, initializationRecord.InitialHeight.RevisionHeight) + + // Consumers start out with the unbonding period from the consumer addition prop + consumerUnbondingPeriod := initializationRecord.UnbondingPeriod + + // Create client state by getting template client from parameters and filling in zeroed fields from proposal. + clientState := k.GetTemplateClient(ctx) + clientState.ChainId = chainId + clientState.LatestHeight = initializationRecord.InitialHeight + + trustPeriod, err := ccv.CalculateTrustPeriod(consumerUnbondingPeriod, k.GetTrustingPeriodFraction(ctx)) + if err != nil { + return err + } + clientState.TrustingPeriod = trustPeriod + clientState.UnbondingPeriod = consumerUnbondingPeriod + + consumerGen, validatorSetHash, err := k.MakeConsumerGenesis(ctx, consumerId) + if err != nil { + return err + } + err = k.SetConsumerGenesis(ctx, consumerId, consumerGen) + if err != nil { + return err + } + + // Create consensus state + consensusState := ibctmtypes.NewConsensusState( + ctx.BlockTime(), + commitmenttypes.NewMerkleRoot([]byte(ibctmtypes.SentinelRoot)), + validatorSetHash, // use the hash of the updated initial valset + ) + + clientID, err := k.clientKeeper.CreateClient(ctx, clientState, consensusState) + if err != nil { + return err + } + k.SetConsumerClientId(ctx, consumerId, clientID) + + k.Logger(ctx).Info("consumer chain launched (client created)", + "consumer id", consumerId, + "client id", clientID, + ) + + ctx.EventManager().EmitEvent( + sdk.NewEvent( + types.EventTypeConsumerClientCreated, + sdk.NewAttribute(sdk.AttributeKeyModule, types.ModuleName), + sdk.NewAttribute(types.AttributeConsumerId, consumerId), + sdk.NewAttribute(types.AttributeConsumerChainId, chainId), + sdk.NewAttribute(clienttypes.AttributeKeyClientID, clientID), + sdk.NewAttribute(types.AttributeInitialHeight, initializationRecord.InitialHeight.String()), + sdk.NewAttribute(types.AttributeTrustingPeriod, clientState.TrustingPeriod.String()), + sdk.NewAttribute(types.AttributeUnbondingPeriod, clientState.UnbondingPeriod.String()), + ), + ) + + return nil +} + +// MakeConsumerGenesis returns the created consumer genesis state for consumer chain `consumerId`, +// as well as the validator hash of the initial validator set of the consumer chain +func (k Keeper) MakeConsumerGenesis( + ctx sdk.Context, + consumerId string, +) (gen ccv.ConsumerGenesisState, nextValidatorsHash []byte, err error) { + initializationRecord, err := k.GetConsumerInitializationParameters(ctx, consumerId) + if err != nil { + return gen, nil, errorsmod.Wrapf(ccv.ErrInvalidConsumerState, + "cannot retrieve initialization parameters: %s", err.Error()) + } + powerShapingParameters, err := k.GetConsumerPowerShapingParameters(ctx, consumerId) + if err != nil { + return gen, nil, errorsmod.Wrapf(ccv.ErrInvalidConsumerState, + "cannot retrieve power shaping parameters: %s", err.Error()) + } + + providerUnbondingPeriod, err := k.stakingKeeper.UnbondingTime(ctx) + if err != nil { + return gen, nil, errorsmod.Wrapf(types.ErrNoUnbondingTime, "unbonding time not found: %s", err) + } + height := clienttypes.GetSelfHeight(ctx) + + clientState := k.GetTemplateClient(ctx) + // this is the counter party chain ID for the consumer + clientState.ChainId = ctx.ChainID() + // this is the latest height the client was updated at, i.e., + // the height of the latest consensus state (see below) + clientState.LatestHeight = height + trustPeriod, err := ccv.CalculateTrustPeriod(providerUnbondingPeriod, k.GetTrustingPeriodFraction(ctx)) + if err != nil { + return gen, nil, errorsmod.Wrapf(sdkerrors.ErrInvalidHeight, "error %s calculating trusting_period for: %s", err, height) + } + clientState.TrustingPeriod = trustPeriod + clientState.UnbondingPeriod = providerUnbondingPeriod + + consState, err := k.clientKeeper.GetSelfConsensusState(ctx, height) + if err != nil { + return gen, nil, errorsmod.Wrapf(clienttypes.ErrConsensusStateNotFound, "error %s getting self consensus state for: %s", err, height) + } + + // get the bonded validators from the staking module + bondedValidators, err := k.GetLastBondedValidators(ctx) + if err != nil { + return gen, nil, errorsmod.Wrapf(stakingtypes.ErrNoValidatorFound, "error getting last bonded validators: %s", err) + } + + minPower := int64(0) + if powerShapingParameters.Top_N > 0 { + // get the consensus active validators + // we do not want to base the power calculation for the top N + // on inactive validators, too, since the top N will be a percentage of the active set power + // otherwise, it could be that inactive validators are forced to validate + activeValidators, err := k.GetLastProviderConsensusActiveValidators(ctx) + if err != nil { + return gen, nil, errorsmod.Wrapf(stakingtypes.ErrNoValidatorFound, "error getting last active bonded validators: %s", err) + } + + // in a Top-N chain, we automatically opt in all validators that belong to the top N + minPower, err = k.ComputeMinPowerInTopN(ctx, activeValidators, powerShapingParameters.Top_N) + if err != nil { + return gen, nil, err + } + // log the minimum power in top N + k.Logger(ctx).Info("minimum power in top N at consumer genesis", + "consumerId", consumerId, + "minPower", minPower, + ) + k.OptInTopNValidators(ctx, consumerId, activeValidators, minPower) + k.SetMinimumPowerInTopN(ctx, consumerId, minPower) + } + + // need to use the bondedValidators, not activeValidators, here since the chain might be opt-in and allow inactive vals + nextValidators := k.ComputeNextValidators(ctx, consumerId, bondedValidators, powerShapingParameters, minPower) + k.SetConsumerValSet(ctx, consumerId, nextValidators) + + // get the initial updates with the latest set consumer public keys + initialUpdatesWithConsumerKeys := DiffValidators([]types.ConsensusValidator{}, nextValidators) + + // Get a hash of the consumer validator set from the update with applied consumer assigned keys + updatesAsValSet, err := tmtypes.PB2TM.ValidatorUpdates(initialUpdatesWithConsumerKeys) + if err != nil { + return gen, nil, fmt.Errorf("unable to create validator set from updates computed from key assignment in MakeConsumerGenesis: %s", err) + } + hash := tmtypes.NewValidatorSet(updatesAsValSet).Hash() + + consumerGenesisParams := ccv.NewParams( + true, + initializationRecord.BlocksPerDistributionTransmission, + initializationRecord.DistributionTransmissionChannel, + "", // providerFeePoolAddrStr, + initializationRecord.CcvTimeoutPeriod, + initializationRecord.TransferTimeoutPeriod, + initializationRecord.ConsumerRedistributionFraction, + initializationRecord.HistoricalEntries, + initializationRecord.UnbondingPeriod, + []string{}, + []string{}, + ccv.DefaultRetryDelayPeriod, + ) + + gen = *ccv.NewInitialConsumerGenesisState( + clientState, + consState.(*ibctmtypes.ConsensusState), + initialUpdatesWithConsumerKeys, + consumerGenesisParams, + ) + return gen, hash, nil +} + +// StopAndPrepareForConsumerRemoval sets the phase of the chain to stopped and prepares to get the state of the +// chain removed after unbonding period elapses +func (k Keeper) StopAndPrepareForConsumerRemoval(ctx sdk.Context, consumerId string) error { + // The phase of the chain is immediately set to stopped, albeit its state is removed later (see below). + // Setting the phase here helps in not considering this chain when we look at launched chains (e.g., in `QueueVSCPackets) + k.SetConsumerPhase(ctx, consumerId, types.CONSUMER_PHASE_STOPPED) + + // state of this chain is removed once UnbondingPeriod elapses + unbondingPeriod, err := k.stakingKeeper.UnbondingTime(ctx) + if err != nil { + return err + } + removalTime := ctx.BlockTime().Add(unbondingPeriod) + + if err := k.SetConsumerRemovalTime(ctx, consumerId, removalTime); err != nil { + return fmt.Errorf("cannot set removal time (%s): %s", removalTime.String(), err.Error()) + } + if err := k.AppendConsumerToBeRemoved(ctx, consumerId, removalTime); err != nil { + return errorsmod.Wrapf(ccv.ErrInvalidConsumerState, "cannot set consumer to be removed: %s", err.Error()) + } + + return nil +} + +// BeginBlockRemoveConsumers iterates over the pending consumer proposals and stop/removes the chain if the removal time has passed +func (k Keeper) BeginBlockRemoveConsumers(ctx sdk.Context) { + // TODO (PERMISSIONLESS): parameterize the limit + for _, consumerId := range k.GetConsumersReadyToStop(ctx, 200) { + removalTime, err := k.GetConsumerRemovalTime(ctx, consumerId) + if err != nil { + k.Logger(ctx).Error("chain could not be stopped", + "consumerId", consumerId, + "error", err.Error()) + continue + } + + // Remove consumer to prevent re-trying removing this chain. + err = k.RemoveConsumerToBeRemoved(ctx, consumerId, removalTime) + if err != nil { + ctx.Logger().Error("could not remove consumer from to-be-removed queue", + "consumerId", consumerId, + "error", err) + continue + } + + // delete consumer chain in a cached context to abort deletion in case of errors + cachedCtx, writeFn := ctx.CacheContext() + err = k.DeleteConsumerChain(cachedCtx, consumerId) + if err != nil { + k.Logger(ctx).Error("consumer chain could not be removed", + "consumerId", consumerId, + "error", err.Error()) + continue + } + + // The cached context is created with a new EventManager so we merge the event into the original context + ctx.EventManager().EmitEvents(cachedCtx.EventManager().Events()) + + writeFn() + + k.Logger(ctx).Info("executed consumer deletion", + "consumer id", consumerId, + "removal time", removalTime, + ) + } +} + +// GetConsumersReadyToStop returns the consumer ids of the pending launched consumer chains +// that are ready to stop +func (k Keeper) GetConsumersReadyToStop(ctx sdk.Context, limit uint32) []string { + store := ctx.KVStore(k.storeKey) + + removalTimeToConsumerIdsKeyPrefix := types.RemovalTimeToConsumerIdsKeyPrefix() + iterator := storetypes.KVStorePrefixIterator(store, []byte{removalTimeToConsumerIdsKeyPrefix}) + defer iterator.Close() + + result := []string{} + for ; iterator.Valid(); iterator.Next() { + removalTime, err := types.ParseTime(removalTimeToConsumerIdsKeyPrefix, iterator.Key()) + if err != nil { + k.Logger(ctx).Error("failed to parse removal time", + "error", err) + continue + } + if removalTime.After(ctx.BlockTime()) { + return result + } + + consumers, err := k.GetConsumersToBeRemoved(ctx, removalTime) + if err != nil { + k.Logger(ctx).Error("failed to retrieve consumers to remove", + "removal time", removalTime, + "error", err) + continue + } + if len(result)+len(consumers.Ids) >= int(limit) { + remainingConsumerIds := len(result) + len(consumers.Ids) - int(limit) + if len(consumers.Ids[:len(consumers.Ids)-remainingConsumerIds]) == 0 { + return result + } + return append(result, consumers.Ids[:len(consumers.Ids)-remainingConsumerIds]...) + } else { + result = append(result, consumers.Ids...) + } + } + + return result +} + +// DeleteConsumerChain cleans up the state of the given consumer chain +func (k Keeper) DeleteConsumerChain(ctx sdk.Context, consumerId string) (err error) { + phase := k.GetConsumerPhase(ctx, consumerId) + if phase != types.CONSUMER_PHASE_STOPPED { + return fmt.Errorf("cannot delete non-stopped chain: %s", consumerId) + } + + // clean up states + k.DeleteConsumerClientId(ctx, consumerId) + k.DeleteConsumerGenesis(ctx, consumerId) + // Note: this call panics if the key assignment state is invalid + k.DeleteKeyAssignments(ctx, consumerId) + k.DeleteMinimumPowerInTopN(ctx, consumerId) + k.DeleteEquivocationEvidenceMinHeight(ctx, consumerId) + + // close channel and delete the mappings between chain ID and channel ID + if channelID, found := k.GetConsumerIdToChannelId(ctx, consumerId); found { + // Close the channel for the given channel ID on the condition + // that the channel exists and isn't already in the CLOSED state + channel, found := k.channelKeeper.GetChannel(ctx, ccv.ProviderPortID, channelID) + if found && channel.State != channeltypes.CLOSED { + err := k.chanCloseInit(ctx, channelID) + if err != nil { + k.Logger(ctx).Error("channel to consumer chain could not be closed", + "consumerId", consumerId, + "channelID", channelID, + "error", err.Error(), + ) + } + } + k.DeleteConsumerIdToChannelId(ctx, consumerId) + k.DeleteChannelIdToConsumerId(ctx, channelID) + } + + // delete consumer commission rate + provAddrs := k.GetAllCommissionRateValidators(ctx, consumerId) + for _, addr := range provAddrs { + k.DeleteConsumerCommissionRate(ctx, consumerId, addr) + } + + k.DeleteInitChainHeight(ctx, consumerId) + k.DeleteSlashAcks(ctx, consumerId) + k.DeletePendingVSCPackets(ctx, consumerId) + + k.DeleteAllowlist(ctx, consumerId) + k.DeleteDenylist(ctx, consumerId) + k.DeleteAllOptedIn(ctx, consumerId) + k.DeleteConsumerValSet(ctx, consumerId) + + k.DeleteConsumerRewardsAllocation(ctx, consumerId) + k.DeleteConsumerRemovalTime(ctx, consumerId) + + // TODO (PERMISSIONLESS) add newly-added state to be deleted + // Note that we do not delete ConsumerIdToChainIdKey and ConsumerIdToPhase, as well + // as consumer metadata, initialization and power-shaping parameters. + + k.SetConsumerPhase(ctx, consumerId, types.CONSUMER_PHASE_DELETED) + k.Logger(ctx).Info("consumer chain deleted from provider", "consumerId", consumerId) + + return nil +} + +// +// Setters and Getters +// + +// GetConsumerRemovalTime returns the removal time associated with the to-be-removed chain with consumer id +func (k Keeper) GetConsumerRemovalTime(ctx sdk.Context, consumerId string) (time.Time, error) { + store := ctx.KVStore(k.storeKey) + buf := store.Get(types.ConsumerIdToRemovalTimeKey(consumerId)) + if buf == nil { + return time.Time{}, fmt.Errorf("failed to retrieve removal time for consumer id (%s)", consumerId) + } + var time time.Time + if err := time.UnmarshalBinary(buf); err != nil { + return time, fmt.Errorf("failed to unmarshal removal time for consumer id (%s): %w", consumerId, err) + } + return time, nil +} + +// SetConsumerRemovalTime sets the removal time associated with this consumer id +func (k Keeper) SetConsumerRemovalTime(ctx sdk.Context, consumerId string, removalTime time.Time) error { + store := ctx.KVStore(k.storeKey) + buf, err := removalTime.MarshalBinary() + if err != nil { + return fmt.Errorf("failed to marshal removal time (%+v) for consumer id (%s): %w", removalTime, consumerId, err) + } + store.Set(types.ConsumerIdToRemovalTimeKey(consumerId), buf) + return nil +} + +// DeleteConsumerRemovalTime deletes the removal time associated with this consumer id +func (k Keeper) DeleteConsumerRemovalTime(ctx sdk.Context, consumerId string) { + store := ctx.KVStore(k.storeKey) + store.Delete(types.ConsumerIdToRemovalTimeKey(consumerId)) +} + +// getConsumerIdsBasedOnTime returns all the consumer ids stored under this specific `key(time)` +func (k Keeper) getConsumerIdsBasedOnTime(ctx sdk.Context, key func(time.Time) []byte, time time.Time) (types.ConsumerIds, error) { + store := ctx.KVStore(k.storeKey) + bz := store.Get(key(time)) + if bz == nil { + return types.ConsumerIds{}, nil + } + + var consumerIds types.ConsumerIds + + if err := consumerIds.Unmarshal(bz); err != nil { + return types.ConsumerIds{}, fmt.Errorf("failed to unmarshal consumer ids: %w", err) + } + return consumerIds, nil +} + +// appendConsumerIdOnTime appends the consumer id on all the other consumer ids under `key(time)` +func (k Keeper) appendConsumerIdOnTime(ctx sdk.Context, consumerId string, key func(time.Time) []byte, time time.Time) error { + store := ctx.KVStore(k.storeKey) + + consumers, err := k.getConsumerIdsBasedOnTime(ctx, key, time) + if err != nil { + return err + } + + consumersWithAppend := types.ConsumerIds{ + Ids: append(consumers.Ids, consumerId), + } + + bz, err := consumersWithAppend.Marshal() + if err != nil { + return err + } + + store.Set(key(time), bz) + return nil +} + +// removeConsumerIdFromTime removes consumer id stored under `key(time)` +func (k Keeper) removeConsumerIdFromTime(ctx sdk.Context, consumerId string, key func(time.Time) []byte, time time.Time) error { + store := ctx.KVStore(k.storeKey) + + consumers, err := k.getConsumerIdsBasedOnTime(ctx, key, time) + if err != nil { + return err + } + + if len(consumers.Ids) == 0 { + return fmt.Errorf("no consumer ids found for this time: %s", time.String()) + } + + // find the index of the consumer we want to remove + index := -1 + for i := 0; i < len(consumers.Ids); i = i + 1 { + if consumers.Ids[i] == consumerId { + index = i + break + } + } + + if index == -1 { + return fmt.Errorf("failed to find consumer id (%s)", consumerId) + } + + if len(consumers.Ids) == 1 { + store.Delete(key(time)) + return nil + } + + consumersWithRemoval := types.ConsumerIds{ + Ids: append(consumers.Ids[:index], consumers.Ids[index+1:]...), + } + + bz, err := consumersWithRemoval.Marshal() + if err != nil { + return err + } + + store.Set(key(time), bz) + return nil +} + +// GetConsumersToBeLaunched returns all the consumer ids of chains stored under this spawn time +func (k Keeper) GetConsumersToBeLaunched(ctx sdk.Context, spawnTime time.Time) (types.ConsumerIds, error) { + return k.getConsumerIdsBasedOnTime(ctx, types.SpawnTimeToConsumerIdsKey, spawnTime) +} + +// AppendConsumerToBeLaunched appends the provider consumer id for the given spawn time +func (k Keeper) AppendConsumerToBeLaunched(ctx sdk.Context, consumerId string, spawnTime time.Time) error { + return k.appendConsumerIdOnTime(ctx, consumerId, types.SpawnTimeToConsumerIdsKey, spawnTime) +} + +// RemoveConsumerToBeLaunched removes consumer id from if stored for this specific spawn time +func (k Keeper) RemoveConsumerToBeLaunched(ctx sdk.Context, consumerId string, spawnTime time.Time) error { + return k.removeConsumerIdFromTime(ctx, consumerId, types.SpawnTimeToConsumerIdsKey, spawnTime) +} + +// GetConsumersToBeRemoved returns all the consumer ids of chains stored under this removal time +func (k Keeper) GetConsumersToBeRemoved(ctx sdk.Context, removalTime time.Time) (types.ConsumerIds, error) { + return k.getConsumerIdsBasedOnTime(ctx, types.RemovalTimeToConsumerIdsKey, removalTime) +} + +// AppendConsumerToBeRemoved appends the provider consumer id for the given removal time +func (k Keeper) AppendConsumerToBeRemoved(ctx sdk.Context, consumerId string, removalTime time.Time) error { + return k.appendConsumerIdOnTime(ctx, consumerId, types.RemovalTimeToConsumerIdsKey, removalTime) +} + +// RemoveConsumerToBeRemoved removes consumer id from the given removal time +func (k Keeper) RemoveConsumerToBeRemoved(ctx sdk.Context, consumerId string, removalTime time.Time) error { + return k.removeConsumerIdFromTime(ctx, consumerId, types.RemovalTimeToConsumerIdsKey, removalTime) +} diff --git a/x/ccv/provider/keeper/consumer_lifecycle_test.go b/x/ccv/provider/keeper/consumer_lifecycle_test.go new file mode 100644 index 0000000000..76d654c0c3 --- /dev/null +++ b/x/ccv/provider/keeper/consumer_lifecycle_test.go @@ -0,0 +1,1012 @@ +package keeper_test + +import ( + "encoding/json" + "fmt" + "testing" + "time" + + "github.com/golang/mock/gomock" + "github.com/stretchr/testify/require" + + abci "github.com/cometbft/cometbft/abci/types" + + "cosmossdk.io/math" + + sdk "github.com/cosmos/cosmos-sdk/types" + stakingtypes "github.com/cosmos/cosmos-sdk/x/staking/types" + + clienttypes "github.com/cosmos/ibc-go/v8/modules/core/02-client/types" + ibctmtypes "github.com/cosmos/ibc-go/v8/modules/light-clients/07-tendermint" + _go "github.com/cosmos/ics23/go" + + cryptotestutil "github.com/cosmos/interchain-security/v5/testutil/crypto" + testkeeper "github.com/cosmos/interchain-security/v5/testutil/keeper" + providerkeeper "github.com/cosmos/interchain-security/v5/x/ccv/provider/keeper" + providertypes "github.com/cosmos/interchain-security/v5/x/ccv/provider/types" + ccvtypes "github.com/cosmos/interchain-security/v5/x/ccv/types" +) + +func TestPrepareConsumerForLaunch(t *testing.T) { + providerKeeper, ctx, ctrl, _ := testkeeper.GetProviderKeeperAndCtx(t, testkeeper.NewInMemKeeperParams(t)) + defer ctrl.Finish() + + spawnTime := time.Now().UTC() + err := providerKeeper.PrepareConsumerForLaunch(ctx, "consumerId", time.Time{}, spawnTime) + require.NoError(t, err) + + consumers, err := providerKeeper.GetConsumersToBeLaunched(ctx, spawnTime) + require.NoError(t, err) + require.Equal(t, providertypes.ConsumerIds{Ids: []string{"consumerId"}}, consumers) + + nextSpawnTime := spawnTime.Add(time.Hour) + err = providerKeeper.PrepareConsumerForLaunch(ctx, "consumerId", spawnTime, nextSpawnTime) + require.NoError(t, err) + + consumers, err = providerKeeper.GetConsumersToBeLaunched(ctx, spawnTime) + require.NoError(t, err) + require.Empty(t, consumers) + + consumers, err = providerKeeper.GetConsumersToBeLaunched(ctx, nextSpawnTime) + require.NoError(t, err) + require.Equal(t, providertypes.ConsumerIds{Ids: []string{"consumerId"}}, consumers) +} + +func TestInitializeConsumer(t *testing.T) { + now := time.Now().UTC() + consumerId := "13" + + testCases := []struct { + name string + spawnTime time.Time + setup func(*providerkeeper.Keeper, sdk.Context, time.Time) + expInitialized bool + }{ + { + name: "valid", + spawnTime: now, + setup: func(pk *providerkeeper.Keeper, ctx sdk.Context, spawnTime time.Time) { + pk.SetConsumerPhase(ctx, consumerId, providertypes.CONSUMER_PHASE_REGISTERED) + err := pk.SetConsumerInitializationParameters(ctx, consumerId, + providertypes.ConsumerInitializationParameters{ + SpawnTime: spawnTime, + }) + require.NoError(t, err) + }, + expInitialized: true, + }, + { + name: "invalid: no phase", + spawnTime: now, + setup: func(pk *providerkeeper.Keeper, ctx sdk.Context, spawnTime time.Time) { + }, + expInitialized: false, + }, + { + name: "invalid: wrong phase", + spawnTime: now, + setup: func(pk *providerkeeper.Keeper, ctx sdk.Context, spawnTime time.Time) { + pk.SetConsumerPhase(ctx, consumerId, providertypes.CONSUMER_PHASE_LAUNCHED) + err := pk.SetConsumerInitializationParameters(ctx, consumerId, + providertypes.ConsumerInitializationParameters{ + SpawnTime: spawnTime, + }) + require.NoError(t, err) + }, + expInitialized: false, + }, + { + name: "invalid: no init params", + spawnTime: now, + setup: func(pk *providerkeeper.Keeper, ctx sdk.Context, spawnTime time.Time) { + pk.SetConsumerPhase(ctx, consumerId, providertypes.CONSUMER_PHASE_REGISTERED) + }, + expInitialized: false, + }, + { + name: "invalid: zero spawn time", + spawnTime: now, + setup: func(pk *providerkeeper.Keeper, ctx sdk.Context, spawnTime time.Time) { + pk.SetConsumerPhase(ctx, consumerId, providertypes.CONSUMER_PHASE_REGISTERED) + err := pk.SetConsumerInitializationParameters(ctx, consumerId, + providertypes.ConsumerInitializationParameters{ + SpawnTime: time.Time{}, + }) + require.NoError(t, err) + }, + expInitialized: false, + }, + } + + for _, tc := range testCases { + pk, ctx, ctrl, _ := testkeeper.GetProviderKeeperAndCtx(t, testkeeper.NewInMemKeeperParams(t)) + defer ctrl.Finish() + + tc.setup(&pk, ctx, tc.spawnTime) + + spawnTime, initialized := pk.InitializeConsumer(ctx, consumerId) + require.Equal(t, tc.expInitialized, initialized, tc.name) + if initialized { + require.Equal(t, tc.spawnTime, spawnTime, tc.name) + require.Equal(t, providertypes.CONSUMER_PHASE_INITIALIZED, pk.GetConsumerPhase(ctx, consumerId)) + } + } +} + +// TestBeginBlockInit directly tests BeginBlockLaunchConsumers against the spec using helpers defined above. +func TestBeginBlockLaunchConsumers(t *testing.T) { + now := time.Now().UTC() + + keeperParams := testkeeper.NewInMemKeeperParams(t) + providerKeeper, ctx, ctrl, mocks := testkeeper.GetProviderKeeperAndCtx(t, keeperParams) + providerKeeper.SetParams(ctx, providertypes.DefaultParams()) + defer ctrl.Finish() + ctx = ctx.WithBlockTime(now) + + // initialize registration, initialization, and update records + consumerMetadata := []providertypes.ConsumerMetadata{ + { + Name: "name", + Description: "spawn time passed", + }, + { + Name: "title", + Description: "spawn time passed", + }, + { + Name: "title", + Description: "spawn time not passed", + }, + { + Name: "title", + Description: "opt-in chain with at least one validator opted in", + }, + { + Name: "title", + Description: "opt-in chain with no validator opted in", + }, + } + chainIds := []string{"chain0", "chain1", "chain2", "chain3", "chain4"} + + initializationParameters := []providertypes.ConsumerInitializationParameters{ + { + InitialHeight: clienttypes.NewHeight(3, 4), + GenesisHash: []byte{}, + BinaryHash: []byte{}, + SpawnTime: now.Add(-time.Hour * 2).UTC(), + UnbondingPeriod: time.Duration(100000000000), + CcvTimeoutPeriod: time.Duration(100000000000), + TransferTimeoutPeriod: time.Duration(100000000000), + ConsumerRedistributionFraction: "0.75", + BlocksPerDistributionTransmission: 10, + HistoricalEntries: 10000, + DistributionTransmissionChannel: "", + }, + { + InitialHeight: clienttypes.NewHeight(3, 4), + GenesisHash: []byte{}, + BinaryHash: []byte{}, + SpawnTime: now.Add(-time.Hour).UTC(), + UnbondingPeriod: time.Duration(100000000000), + CcvTimeoutPeriod: time.Duration(100000000000), + TransferTimeoutPeriod: time.Duration(100000000000), + ConsumerRedistributionFraction: "0.75", + BlocksPerDistributionTransmission: 10, + HistoricalEntries: 10000, + DistributionTransmissionChannel: "", + }, + { + InitialHeight: clienttypes.NewHeight(3, 4), + GenesisHash: []byte{}, + BinaryHash: []byte{}, + SpawnTime: now.Add(time.Hour).UTC(), + UnbondingPeriod: time.Duration(100000000000), + CcvTimeoutPeriod: time.Duration(100000000000), + TransferTimeoutPeriod: time.Duration(100000000000), + ConsumerRedistributionFraction: "0.75", + BlocksPerDistributionTransmission: 10, + HistoricalEntries: 10000, + DistributionTransmissionChannel: "", + }, + { + InitialHeight: clienttypes.NewHeight(3, 4), + GenesisHash: []byte{}, + BinaryHash: []byte{}, + SpawnTime: now.Add(-time.Hour).UTC(), + UnbondingPeriod: time.Duration(100000000000), + CcvTimeoutPeriod: time.Duration(100000000000), + TransferTimeoutPeriod: time.Duration(100000000000), + ConsumerRedistributionFraction: "0.75", + BlocksPerDistributionTransmission: 10, + HistoricalEntries: 10000, + DistributionTransmissionChannel: "", + }, + { + InitialHeight: clienttypes.NewHeight(3, 4), + GenesisHash: []byte{}, + BinaryHash: []byte{}, + SpawnTime: now.Add(-time.Minute).UTC(), + UnbondingPeriod: time.Duration(100000000000), + CcvTimeoutPeriod: time.Duration(100000000000), + TransferTimeoutPeriod: time.Duration(100000000000), + ConsumerRedistributionFraction: "0.75", + BlocksPerDistributionTransmission: 10, + HistoricalEntries: 10000, + DistributionTransmissionChannel: "", + }, + } + powerShapingParameters := []providertypes.PowerShapingParameters{ + { + Top_N: 50, + ValidatorsPowerCap: 0, + ValidatorSetCap: 0, + Allowlist: []string{}, + Denylist: []string{}, + }, + { + Top_N: 50, + ValidatorsPowerCap: 0, + ValidatorSetCap: 0, + Allowlist: []string{}, + Denylist: []string{}, + }, + { + Top_N: 50, + ValidatorsPowerCap: 0, + ValidatorSetCap: 0, + Allowlist: []string{}, + Denylist: []string{}, + }, + { + Top_N: 0, + ValidatorsPowerCap: 0, + ValidatorSetCap: 0, + Allowlist: []string{}, + Denylist: []string{}, + }, + { + Top_N: 0, + ValidatorsPowerCap: 0, + ValidatorSetCap: 0, + Allowlist: []string{}, + Denylist: []string{}, + }} + + // Expect client creation for only the first, second, and fifth proposals (spawn time already passed and valid) + expectedCalls := testkeeper.GetMocksForCreateConsumerClient(ctx, &mocks, "chain0", clienttypes.NewHeight(3, 4)) + expectedCalls = append(expectedCalls, testkeeper.GetMocksForCreateConsumerClient(ctx, &mocks, "chain1", clienttypes.NewHeight(3, 4))...) + expectedCalls = append(expectedCalls, testkeeper.GetMocksForCreateConsumerClient(ctx, &mocks, "chain3", clienttypes.NewHeight(3, 4))...) + + // The fifth chain would have spawn time passed and hence needs the mocks but the client will not be + // created because `chain4` is an Opt In chain and has no validator opted in + expectedCalls = append(expectedCalls, testkeeper.GetMocksForCreateConsumerClient(ctx, &mocks, "chain4", clienttypes.NewHeight(3, 4))...) + + gomock.InOrder(expectedCalls...) + + // set up all the records + for i, chainId := range chainIds { + providerKeeper.SetConsumerChainId(ctx, fmt.Sprintf("%d", i), chainId) + } + + for i, r := range consumerMetadata { + providerKeeper.SetConsumerMetadata(ctx, fmt.Sprintf("%d", i), r) + } + for i, r := range initializationParameters { + err := providerKeeper.SetConsumerInitializationParameters(ctx, fmt.Sprintf("%d", i), r) + require.NoError(t, err) + // set up the chains in their initialized phase, hence they could launch + providerKeeper.SetConsumerPhase(ctx, fmt.Sprintf("%d", i), providertypes.CONSUMER_PHASE_INITIALIZED) + err = providerKeeper.AppendConsumerToBeLaunched(ctx, fmt.Sprintf("%d", i), r.SpawnTime) + require.NoError(t, err) + } + for i, r := range powerShapingParameters { + err := providerKeeper.SetConsumerPowerShapingParameters(ctx, fmt.Sprintf("%d", i), r) + require.NoError(t, err) + } + + // opt in a sample validator so the chain's proposal can successfully execute + validator := cryptotestutil.NewCryptoIdentityFromIntSeed(0).SDKStakingValidator() + consAddr, _ := validator.GetConsAddr() + testkeeper.SetupMocksForLastBondedValidatorsExpectation(mocks.MockStakingKeeper, 1, []stakingtypes.Validator{validator}, -1) // -1 to allow any number of calls + + valAddr, _ := sdk.ValAddressFromBech32(validator.GetOperator()) + mocks.MockStakingKeeper.EXPECT().GetLastValidatorPower(gomock.Any(), valAddr).Return(int64(1), nil).AnyTimes() + // for the validator, expect a call to GetValidatorByConsAddr with its consensus address + mocks.MockStakingKeeper.EXPECT().GetValidatorByConsAddr(gomock.Any(), consAddr).Return(validator, nil).AnyTimes() + + providerKeeper.SetOptedIn(ctx, "3", providertypes.NewProviderConsAddress(consAddr)) + + providerKeeper.BeginBlockLaunchConsumers(ctx) + + // first chain was successfully launched + phase := providerKeeper.GetConsumerPhase(ctx, "0") + require.Equal(t, providertypes.CONSUMER_PHASE_LAUNCHED, phase) + _, found := providerKeeper.GetConsumerGenesis(ctx, "0") + require.True(t, found) + + // second chain was successfully launched + phase = providerKeeper.GetConsumerPhase(ctx, "1") + require.Equal(t, providertypes.CONSUMER_PHASE_LAUNCHED, phase) + _, found = providerKeeper.GetConsumerGenesis(ctx, "1") + require.True(t, found) + + // third chain was not launched because its spawn time has not passed + phase = providerKeeper.GetConsumerPhase(ctx, "2") + require.Equal(t, providertypes.CONSUMER_PHASE_INITIALIZED, phase) + _, found = providerKeeper.GetConsumerGenesis(ctx, "2") + require.False(t, found) + + // fourth chain corresponds to an Opt-In chain with one opted-in validator and hence the chain gets + // successfully executed + phase = providerKeeper.GetConsumerPhase(ctx, "3") + require.Equal(t, providertypes.CONSUMER_PHASE_LAUNCHED, phase) + _, found = providerKeeper.GetConsumerGenesis(ctx, "3") + require.True(t, found) + + // fifth chain corresponds to an Opt-In chain with no opted-in validators and hence the + // chain launch is NOT successful + phase = providerKeeper.GetConsumerPhase(ctx, "4") + require.Equal(t, providertypes.CONSUMER_PHASE_INITIALIZED, phase) + _, found = providerKeeper.GetConsumerGenesis(ctx, "4") + require.False(t, found) +} + +// TestGetConsumersReadyToLaunch tests that the ready to-be-launched consumer chains are returned +func TestGetConsumersReadyToLaunch(t *testing.T) { + providerKeeper, ctx, ctrl, _ := testkeeper.GetProviderKeeperAndCtx(t, testkeeper.NewInMemKeeperParams(t)) + defer ctrl.Finish() + + // no chains to-be-launched exist + require.Empty(t, providerKeeper.GetConsumersReadyToLaunch(ctx, 5)) + + err := providerKeeper.AppendConsumerToBeLaunched(ctx, "consumerId1", time.Unix(10, 0)) + require.NoError(t, err) + err = providerKeeper.AppendConsumerToBeLaunched(ctx, "consumerId2", time.Unix(20, 0)) + require.NoError(t, err) + err = providerKeeper.AppendConsumerToBeLaunched(ctx, "consumerId3", time.Unix(30, 0)) + require.NoError(t, err) + + // time has not yet reached the spawn time of "consumerId1" + ctx = ctx.WithBlockTime(time.Unix(9, 999999999)) + require.Empty(t, providerKeeper.GetConsumersReadyToLaunch(ctx, 3)) + + // time has reached the spawn time of "consumerId1" + ctx = ctx.WithBlockTime(time.Unix(10, 0)) + require.Equal(t, []string{"consumerId1"}, providerKeeper.GetConsumersReadyToLaunch(ctx, 3)) + + // time has reached the spawn time of "consumerId1" and "consumerId2" + ctx = ctx.WithBlockTime(time.Unix(20, 0)) + require.Equal(t, []string{"consumerId1", "consumerId2"}, providerKeeper.GetConsumersReadyToLaunch(ctx, 3)) + + // time has reached the spawn time of all chains + ctx = ctx.WithBlockTime(time.Unix(30, 0)) + require.Equal(t, []string{"consumerId1", "consumerId2", "consumerId3"}, providerKeeper.GetConsumersReadyToLaunch(ctx, 3)) + + // limit the number of returned consumer chains + require.Equal(t, []string{}, providerKeeper.GetConsumersReadyToLaunch(ctx, 0)) + require.Equal(t, []string{"consumerId1"}, providerKeeper.GetConsumersReadyToLaunch(ctx, 1)) + require.Equal(t, []string{"consumerId1", "consumerId2"}, providerKeeper.GetConsumersReadyToLaunch(ctx, 2)) +} + +// Tests the CreateConsumerClient method against the spec, +// with more granularity than what's covered in TestHandleCreateConsumerChainProposal. +func TestCreateConsumerClient(t *testing.T) { + type testCase struct { + description string + // Any state-mutating setup on keeper and expected mock calls, specific to this test case + setup func(*providerkeeper.Keeper, sdk.Context, *testkeeper.MockedKeepers) + // Whether a client should be created + expClientCreated bool + } + tests := []testCase{ + { + description: "No state mutation, new client should be created", + setup: func(providerKeeper *providerkeeper.Keeper, ctx sdk.Context, mocks *testkeeper.MockedKeepers) { + providerKeeper.SetConsumerPhase(ctx, "0", providertypes.CONSUMER_PHASE_INITIALIZED) + + // Valid client creation is asserted with mock expectations here + testkeeper.SetupMocksForLastBondedValidatorsExpectation(mocks.MockStakingKeeper, 0, []stakingtypes.Validator{}, 1) // returns empty validator set + gomock.InOrder( + testkeeper.GetMocksForCreateConsumerClient(ctx, mocks, "chainID", clienttypes.NewHeight(4, 5))..., + ) + }, + expClientCreated: true, + }, + { + description: "chain for this consumer id has already launched, and hence client was created, NO new one is created", + setup: func(providerKeeper *providerkeeper.Keeper, ctx sdk.Context, mocks *testkeeper.MockedKeepers) { + providerKeeper.SetConsumerPhase(ctx, "0", providertypes.CONSUMER_PHASE_LAUNCHED) + + // Expect none of the client creation related calls to happen + mocks.MockStakingKeeper.EXPECT().UnbondingTime(gomock.Any()).Times(0) + mocks.MockClientKeeper.EXPECT().CreateClient(gomock.Any(), gomock.Any(), gomock.Any()).Times(0) + mocks.MockClientKeeper.EXPECT().GetSelfConsensusState(gomock.Any(), gomock.Any()).Times(0) + testkeeper.SetupMocksForLastBondedValidatorsExpectation(mocks.MockStakingKeeper, 0, []stakingtypes.Validator{}, 0) // returns empty validator set + }, + expClientCreated: false, + }, + } + + for _, tc := range tests { + // Common setup + keeperParams := testkeeper.NewInMemKeeperParams(t) + providerKeeper, ctx, ctrl, mocks := testkeeper.GetProviderKeeperAndCtx(t, keeperParams) + providerKeeper.SetParams(ctx, providertypes.DefaultParams()) + + // Test specific setup + tc.setup(&providerKeeper, ctx, &mocks) + + // Call method with same arbitrary values as defined above in mock expectations. + providerKeeper.SetConsumerChainId(ctx, "0", "chainID") + err := providerKeeper.SetConsumerMetadata(ctx, "0", testkeeper.GetTestConsumerMetadata()) + require.NoError(t, err) + err = providerKeeper.SetConsumerInitializationParameters(ctx, "0", testkeeper.GetTestInitializationParameters()) + require.NoError(t, err) + err = providerKeeper.SetConsumerPowerShapingParameters(ctx, "0", testkeeper.GetTestPowerShapingParameters()) + require.NoError(t, err) + + err = providerKeeper.CreateConsumerClient(ctx, "0") + if tc.expClientCreated { + require.NoError(t, err) + testCreatedConsumerClient(t, ctx, providerKeeper, "0", "clientID") + } else { + require.Error(t, err) + } + + // Assert mock calls from setup functions + ctrl.Finish() + } +} + +// Executes test assertions for a created consumer client. +// +// Note: Separated from TestCreateConsumerClient to also be called from TestCreateConsumerChainProposal. +func testCreatedConsumerClient(t *testing.T, + ctx sdk.Context, providerKeeper providerkeeper.Keeper, consumerId, expectedClientID string, +) { + t.Helper() + // ClientID should be stored. + clientId, found := providerKeeper.GetConsumerClientId(ctx, consumerId) + require.True(t, found, "consumer client not found") + require.Equal(t, expectedClientID, clientId) + + // Only assert that consumer genesis was set, + // more granular tests on consumer genesis should be defined in TestMakeConsumerGenesis + _, ok := providerKeeper.GetConsumerGenesis(ctx, consumerId) + require.True(t, ok) +} + +// TestMakeConsumerGenesis tests the MakeConsumerGenesis keeper method. +// An expected genesis state is hardcoded in json, unmarshaled, and compared +// against an actual consumer genesis state constructed by a provider keeper. +func TestMakeConsumerGenesis(t *testing.T) { + keeperParams := testkeeper.NewInMemKeeperParams(t) + providerKeeper, ctx, ctrl, mocks := testkeeper.GetProviderKeeperAndCtx(t, keeperParams) + moduleParams := providertypes.Params{ + TemplateClient: &ibctmtypes.ClientState{ + TrustLevel: ibctmtypes.DefaultTrustLevel, + MaxClockDrift: 10000000000, + ProofSpecs: []*_go.ProofSpec{ + { + LeafSpec: &_go.LeafOp{ + Hash: _go.HashOp_SHA256, + PrehashKey: _go.HashOp_NO_HASH, + PrehashValue: _go.HashOp_SHA256, + Length: _go.LengthOp_VAR_PROTO, + Prefix: []byte{0x00}, + }, + InnerSpec: &_go.InnerSpec{ + ChildOrder: []int32{0, 1}, + ChildSize: 33, + MinPrefixLength: 4, + MaxPrefixLength: 12, + Hash: _go.HashOp_SHA256, + }, + MaxDepth: 0, + MinDepth: 0, + }, + { + LeafSpec: &_go.LeafOp{ + Hash: _go.HashOp_SHA256, + PrehashKey: _go.HashOp_NO_HASH, + PrehashValue: _go.HashOp_SHA256, + Length: _go.LengthOp_VAR_PROTO, + Prefix: []byte{0x00}, + }, + InnerSpec: &_go.InnerSpec{ + ChildOrder: []int32{0, 1}, + ChildSize: 32, + MinPrefixLength: 1, + MaxPrefixLength: 1, + Hash: _go.HashOp_SHA256, + }, + MaxDepth: 0, + }, + }, + UpgradePath: []string{"upgrade", "upgradedIBCState"}, + AllowUpdateAfterExpiry: true, + AllowUpdateAfterMisbehaviour: true, + }, + // Note these are unused provider parameters for this test, and not actually asserted against + // They must be populated with reasonable values to satisfy SetParams though. + TrustingPeriodFraction: providertypes.DefaultTrustingPeriodFraction, + CcvTimeoutPeriod: ccvtypes.DefaultCCVTimeoutPeriod, + SlashMeterReplenishPeriod: providertypes.DefaultSlashMeterReplenishPeriod, + SlashMeterReplenishFraction: providertypes.DefaultSlashMeterReplenishFraction, + ConsumerRewardDenomRegistrationFee: sdk.Coin{ + Denom: "stake", + Amount: math.NewInt(1000000), + }, + BlocksPerEpoch: 600, + NumberOfEpochsToStartReceivingRewards: 24, + } + providerKeeper.SetParams(ctx, moduleParams) + defer ctrl.Finish() + + // + // Other setup not covered by custom template client state + // + ctx = ctx.WithChainID("testchain1") // consumerId is obtained from ctx + ctx = ctx.WithBlockHeight(5) // RevisionHeight obtained from ctx + testkeeper.SetupMocksForLastBondedValidatorsExpectation(mocks.MockStakingKeeper, 0, []stakingtypes.Validator{}, 1) + gomock.InOrder(testkeeper.GetMocksForMakeConsumerGenesis(ctx, &mocks, 1814400000000000)...) + + // matches params from jsonString + consumerMetadata := providertypes.ConsumerMetadata{ + Name: "name", + Description: "description", + } + + ccvTimeoutPeriod := time.Duration(2419200000000000) + transferTimeoutPeriod := time.Duration(3600000000000) + unbondingPeriod := time.Duration(1728000000000000) + initializationParameters := providertypes.ConsumerInitializationParameters{ + BlocksPerDistributionTransmission: 1000, + CcvTimeoutPeriod: ccvTimeoutPeriod, + TransferTimeoutPeriod: transferTimeoutPeriod, + ConsumerRedistributionFraction: "0.75", + HistoricalEntries: 10000, + UnbondingPeriod: unbondingPeriod, + } + providerKeeper.SetConsumerChainId(ctx, "0", "testchain1") + err := providerKeeper.SetConsumerMetadata(ctx, "0", consumerMetadata) + require.NoError(t, err) + err = providerKeeper.SetConsumerInitializationParameters(ctx, "0", initializationParameters) + require.NoError(t, err) + err = providerKeeper.SetConsumerPowerShapingParameters(ctx, "0", providertypes.PowerShapingParameters{}) + require.NoError(t, err) + + actualGenesis, _, err := providerKeeper.MakeConsumerGenesis(ctx, "0") + require.NoError(t, err) + + // JSON string with tabs, newlines and spaces for readability + jsonString := `{ + "params": { + "enabled": true, + "blocks_per_distribution_transmission": 1000, + "ccv_timeout_period": 2419200000000000, + "transfer_timeout_period": 3600000000000, + "consumer_redistribution_fraction": "0.75", + "historical_entries": 10000, + "unbonding_period": 1728000000000000, + "soft_opt_out_threshold": "0", + "reward_denoms": [], + "provider_reward_denoms": [], + "retry_delay_period": 3600000000000 + }, + "new_chain": true, + "provider" : { + "client_state": { + "chain_id": "testchain1", + "trust_level": { + "numerator": 1, + "denominator": 3 + }, + "trusting_period": 1197504000000000, + "unbonding_period": 1814400000000000, + "max_clock_drift": 10000000000, + "frozen_height": {}, + "latest_height": { + "revision_height": 5 + }, + "proof_specs": [ + { + "leaf_spec": { + "hash": 1, + "prehash_value": 1, + "length": 1, + "prefix": "AA==" + }, + "inner_spec": { + "child_order": [0, 1], + "child_size": 33, + "min_prefix_length": 4, + "max_prefix_length": 12, + "hash": 1 + } + }, + { + "leaf_spec": { + "hash": 1, + "prehash_value": 1, + "length": 1, + "prefix": "AA==" + }, + "inner_spec": { + "child_order": [0, 1], + "child_size": 32, + "min_prefix_length": 1, + "max_prefix_length": 1, + "hash": 1 + } + } + ], + "upgrade_path": ["upgrade", "upgradedIBCState"], + "allow_update_after_expiry": true, + "allow_update_after_misbehaviour": true + }, + "consensus_state": { + "timestamp": "2020-01-02T00:00:10Z", + "root": { + "hash": "LpGpeyQVLUo9HpdsgJr12NP2eCICspcULiWa5u9udOA=" + }, + "next_validators_hash": "E30CE736441FB9101FADDAF7E578ABBE6DFDB67207112350A9A904D554E1F5BE" + }, + "initial_val_set": [ + { + "pub_key": { + "type": "tendermint/PubKeyEd25519", + "value": "dcASx5/LIKZqagJWN0frOlFtcvz91frYmj/zmoZRWro=" + }, + "power": 1 + } + ] + } + }` + + var expectedGenesis ccvtypes.ConsumerGenesisState + err = json.Unmarshal([]byte(jsonString), &expectedGenesis) // ignores tabs, newlines and spaces + require.NoError(t, err) + + // Zeroing out different fields that are challenging to mock + actualGenesis.Provider.InitialValSet = []abci.ValidatorUpdate{} + expectedGenesis.Provider.InitialValSet = []abci.ValidatorUpdate{} + actualGenesis.Provider.ConsensusState = &ibctmtypes.ConsensusState{} + expectedGenesis.Provider.ConsensusState = &ibctmtypes.ConsensusState{} + + require.Equal(t, expectedGenesis, actualGenesis, "consumer chain genesis created incorrectly") +} + +func TestBeginBlockStopConsumers(t *testing.T) { + now := time.Now().UTC() + + keeperParams := testkeeper.NewInMemKeeperParams(t) + providerKeeper, ctx, ctrl, mocks := testkeeper.GetProviderKeeperAndCtx(t, keeperParams) + providerKeeper.SetParams(ctx, providertypes.DefaultParams()) + defer ctrl.Finish() + ctx = ctx.WithBlockTime(now) + + chainIds := []string{"chain1", "chain2", "chain3"} + consumerIds := []string{"consumerId1", "consumerId2", "consumerId3"} + err := providerKeeper.SetConsumerRemovalTime(ctx, consumerIds[0], now.Add(-time.Hour)) + require.NoError(t, err) + err = providerKeeper.AppendConsumerToBeRemoved(ctx, consumerIds[0], now.Add(-time.Hour)) + require.NoError(t, err) + err = providerKeeper.SetConsumerRemovalTime(ctx, consumerIds[1], now) + require.NoError(t, err) + err = providerKeeper.AppendConsumerToBeRemoved(ctx, consumerIds[1], now) + require.NoError(t, err) + err = providerKeeper.SetConsumerRemovalTime(ctx, consumerIds[2], now.Add(time.Hour)) + require.NoError(t, err) + err = providerKeeper.AppendConsumerToBeRemoved(ctx, consumerIds[2], now.Add(time.Hour)) + require.NoError(t, err) + + // + // Mock expectations + // + expectations := []*gomock.Call{} + for i := range consumerIds { + chainId := chainIds[i] + // A consumer chain is setup corresponding to each consumerId, making these mocks necessary + testkeeper.SetupMocksForLastBondedValidatorsExpectation(mocks.MockStakingKeeper, 0, []stakingtypes.Validator{}, 1) + expectations = append(expectations, testkeeper.GetMocksForCreateConsumerClient(ctx, &mocks, + chainId, clienttypes.NewHeight(2, 3))...) + expectations = append(expectations, testkeeper.GetMocksForSetConsumerChain(ctx, &mocks, chainId)...) + } + // Only first two consumer chains should be stopped + expectations = append(expectations, testkeeper.GetMocksForDeleteConsumerChain(ctx, &mocks)...) + expectations = append(expectations, testkeeper.GetMocksForDeleteConsumerChain(ctx, &mocks)...) + + gomock.InOrder(expectations...) + + // + // Remaining setup + // + for i, consumerId := range consumerIds { + // Setup a valid consumer chain for each consumerId + initializationRecord := testkeeper.GetTestInitializationParameters() + initializationRecord.InitialHeight = clienttypes.NewHeight(2, 3) + registrationRecord := testkeeper.GetTestConsumerMetadata() + + providerKeeper.SetConsumerChainId(ctx, consumerId, chainIds[i]) + err = providerKeeper.SetConsumerMetadata(ctx, consumerId, registrationRecord) + require.NoError(t, err) + err = providerKeeper.SetConsumerInitializationParameters(ctx, consumerId, initializationRecord) + require.NoError(t, err) + err = providerKeeper.SetConsumerPowerShapingParameters(ctx, consumerId, testkeeper.GetTestPowerShapingParameters()) + require.NoError(t, err) + providerKeeper.SetConsumerPhase(ctx, consumerId, providertypes.CONSUMER_PHASE_INITIALIZED) + providerKeeper.SetConsumerClientId(ctx, consumerId, "clientID") + + err = providerKeeper.CreateConsumerClient(ctx, consumerId) + require.NoError(t, err) + err = providerKeeper.SetConsumerChain(ctx, "channelID") + require.NoError(t, err) + + // the chain is considered to be stopped and ready for deletion (i.e., `StopAndPrepareForConsumerRemoval` is called) + providerKeeper.SetConsumerPhase(ctx, consumerId, providertypes.CONSUMER_PHASE_STOPPED) + } + + // + // Test execution + // + + providerKeeper.BeginBlockRemoveConsumers(ctx) + + // Only the 3rd (final) proposal is still stored as pending + phase := providerKeeper.GetConsumerPhase(ctx, consumerIds[0]) + require.Equal(t, providertypes.CONSUMER_PHASE_DELETED, phase) + phase = providerKeeper.GetConsumerPhase(ctx, consumerIds[1]) + require.Equal(t, providertypes.CONSUMER_PHASE_DELETED, phase) + // third chain had a removal time in the future and hence did not get deleted + phase = providerKeeper.GetConsumerPhase(ctx, consumerIds[2]) + require.Equal(t, providertypes.CONSUMER_PHASE_STOPPED, phase) +} + +func TestGetConsumersReadyToStop(t *testing.T) { + providerKeeper, ctx, ctrl, _ := testkeeper.GetProviderKeeperAndCtx(t, testkeeper.NewInMemKeeperParams(t)) + defer ctrl.Finish() + + // no chains to-be-stopped exist + require.Empty(t, providerKeeper.GetConsumersReadyToStop(ctx, 3)) + + err := providerKeeper.AppendConsumerToBeRemoved(ctx, "consumerId1", time.Unix(10, 0)) + require.NoError(t, err) + err = providerKeeper.AppendConsumerToBeRemoved(ctx, "consumerId2", time.Unix(20, 0)) + require.NoError(t, err) + err = providerKeeper.AppendConsumerToBeRemoved(ctx, "consumerId3", time.Unix(30, 0)) + require.NoError(t, err) + + // time has not yet reached the removal time of "consumerId1" + ctx = ctx.WithBlockTime(time.Unix(9, 999999999)) + require.Empty(t, providerKeeper.GetConsumersReadyToStop(ctx, 3)) + + // time has reached the removal time of "consumerId1" + ctx = ctx.WithBlockTime(time.Unix(10, 0)) + require.Equal(t, []string{"consumerId1"}, providerKeeper.GetConsumersReadyToStop(ctx, 3)) + + // time has reached the removal time of "consumerId1" and "consumerId2" + ctx = ctx.WithBlockTime(time.Unix(20, 0)) + require.Equal(t, []string{"consumerId1", "consumerId2"}, providerKeeper.GetConsumersReadyToStop(ctx, 3)) + + // time has reached the removal time of all chains + ctx = ctx.WithBlockTime(time.Unix(30, 0)) + require.Equal(t, []string{"consumerId1", "consumerId2", "consumerId3"}, providerKeeper.GetConsumersReadyToStop(ctx, 3)) +} + +// Tests the DeleteConsumerChain method against the spec, +// with more granularity than what's covered in TestHandleLegacyConsumerRemovalProposal, or integration tests. +// See: https://github.com/cosmos/ibc/blob/main/spec/app/ics-028-cross-chain-validation/methods.md#ccv-pcf-stcc1 +// Spec tag: [CCV-PCF-STCC.1] +func TestStopConsumerChain(t *testing.T) { + type testCase struct { + description string + // State-mutating setup specific to this test case + setup func(sdk.Context, *providerkeeper.Keeper, testkeeper.MockedKeepers) + // Whether we should expect the method to return an error + expErr bool + } + + consumerId := "0" + + tests := []testCase{ + { + description: "proposal dropped, client doesn't exist", + setup: func(ctx sdk.Context, providerKeeper *providerkeeper.Keeper, mocks testkeeper.MockedKeepers) { + // No mocks, meaning no external keeper methods are allowed to be called. + }, + expErr: true, + }, + { + description: "valid stop of consumer chain, all mock calls hit", + setup: func(ctx sdk.Context, providerKeeper *providerkeeper.Keeper, mocks testkeeper.MockedKeepers) { + testkeeper.SetupForDeleteConsumerChain(t, ctx, providerKeeper, mocks, consumerId) + + // set consumer minimum equivocation height + providerKeeper.SetEquivocationEvidenceMinHeight(ctx, consumerId, 1) + + // assert mocks for expected calls to `DeleteConsumerChain` when closing the underlying channel + gomock.InOrder(testkeeper.GetMocksForDeleteConsumerChain(ctx, &mocks)...) + }, + expErr: false, + }, + } + + for _, tc := range tests { + + // Common setup + keeperParams := testkeeper.NewInMemKeeperParams(t) + providerKeeper, ctx, ctrl, mocks := testkeeper.GetProviderKeeperAndCtx(t, keeperParams) + providerKeeper.SetParams(ctx, providertypes.DefaultParams()) + + // Setup specific to test case + tc.setup(ctx, &providerKeeper, mocks) + + err := providerKeeper.DeleteConsumerChain(ctx, consumerId) + + if tc.expErr { + require.Error(t, err, t) + } else { + require.NoError(t, err) + } + + testkeeper.TestProviderStateIsCleanedAfterConsumerChainIsDeleted(t, ctx, providerKeeper, consumerId, "channelID", tc.expErr) + + ctrl.Finish() + } +} + +// +// Setters and Getters +// + +// TestConsumerRemovalTime tests the getter, setter, and deletion of the consumer id to removal times methods +func TestConsumerRemovalTime(t *testing.T) { + providerKeeper, ctx, ctrl, _ := testkeeper.GetProviderKeeperAndCtx(t, testkeeper.NewInMemKeeperParams(t)) + defer ctrl.Finish() + + _, err := providerKeeper.GetConsumerRemovalTime(ctx, "consumerId") + require.Error(t, err) + + expectedRemovalTime := time.Unix(1234, 56789) + providerKeeper.SetConsumerRemovalTime(ctx, "consumerId", expectedRemovalTime) + actualRemovalTime, err := providerKeeper.GetConsumerRemovalTime(ctx, "consumerId") + require.NoError(t, err) + require.Equal(t, actualRemovalTime, expectedRemovalTime) + + providerKeeper.DeleteConsumerRemovalTime(ctx, "consumerId") + _, err = providerKeeper.GetConsumerRemovalTime(ctx, "consumerId") + require.Error(t, err) +} + +// TestConsumersToBeLaunched tests `AppendConsumerToBeLaunched`, `GetConsumersToBeLaunched`, and `RemoveConsumerToBeLaunched` +func TestConsumersToBeLaunched(t *testing.T) { + providerKeeper, ctx, ctrl, _ := testkeeper.GetProviderKeeperAndCtx(t, testkeeper.NewInMemKeeperParams(t)) + defer ctrl.Finish() + + spawnTime := time.Now() + err := providerKeeper.AppendConsumerToBeLaunched(ctx, "consumerId1", spawnTime) + require.NoError(t, err) + consumers, err := providerKeeper.GetConsumersToBeLaunched(ctx, spawnTime) + require.NoError(t, err) + require.Equal(t, []string{"consumerId1"}, consumers.Ids) + + err = providerKeeper.AppendConsumerToBeLaunched(ctx, "consumerId2", spawnTime) + require.NoError(t, err) + consumers, err = providerKeeper.GetConsumersToBeLaunched(ctx, spawnTime) + require.NoError(t, err) + require.Equal(t, []string{"consumerId1", "consumerId2"}, consumers.Ids) + + err = providerKeeper.AppendConsumerToBeLaunched(ctx, "consumerId3", spawnTime) + require.NoError(t, err) + consumers, err = providerKeeper.GetConsumersToBeLaunched(ctx, spawnTime) + require.NoError(t, err) + require.Equal(t, []string{"consumerId1", "consumerId2", "consumerId3"}, consumers.Ids) + + err = providerKeeper.RemoveConsumerToBeLaunched(ctx, "consumerId2", spawnTime) + require.NoError(t, err) + consumers, err = providerKeeper.GetConsumersToBeLaunched(ctx, spawnTime) + require.NoError(t, err) + require.Equal(t, []string{"consumerId1", "consumerId3"}, consumers.Ids) + + // also add consumer ids under a different spawn time and verify everything under the original spawn time is still there + spawnTimePlusOneHour := spawnTime.Add(time.Hour) + err = providerKeeper.AppendConsumerToBeLaunched(ctx, "consumerId4", spawnTimePlusOneHour) + require.NoError(t, err) + consumers, err = providerKeeper.GetConsumersToBeLaunched(ctx, spawnTimePlusOneHour) + require.NoError(t, err) + require.Equal(t, []string{"consumerId4"}, consumers.Ids) + + consumers, err = providerKeeper.GetConsumersToBeLaunched(ctx, spawnTime) + require.NoError(t, err) + require.Equal(t, []string{"consumerId1", "consumerId3"}, consumers.Ids) + + // start removing all consumers from `spawnTime` + err = providerKeeper.RemoveConsumerToBeLaunched(ctx, "consumerId3", spawnTime) + require.NoError(t, err) + err = providerKeeper.RemoveConsumerToBeLaunched(ctx, "consumerId1", spawnTime) + require.NoError(t, err) + consumers, err = providerKeeper.GetConsumersToBeLaunched(ctx, spawnTime) + require.NoError(t, err) + require.Empty(t, consumers.Ids) + + // remove from `spawnTimePlusOneHour` + err = providerKeeper.RemoveConsumerToBeLaunched(ctx, "consumerId4", spawnTimePlusOneHour) + require.NoError(t, err) + consumers, err = providerKeeper.GetConsumersToBeLaunched(ctx, spawnTimePlusOneHour) + require.NoError(t, err) + require.Empty(t, consumers.Ids) + + // add another consumer for `spawnTime` + err = providerKeeper.AppendConsumerToBeLaunched(ctx, "consumerId5", spawnTime) + require.NoError(t, err) + consumers, err = providerKeeper.GetConsumersToBeLaunched(ctx, spawnTime) + require.NoError(t, err) + require.Equal(t, []string{"consumerId5"}, consumers.Ids) +} + +// TestConsumersToBeRemoved tests `AppendConsumerToBeRemoved`, `GetConsumersToBeRemoved`, and `RemoveConsumerToBeRemoved` +func TestConsumersToBeRemoved(t *testing.T) { + providerKeeper, ctx, ctrl, _ := testkeeper.GetProviderKeeperAndCtx(t, testkeeper.NewInMemKeeperParams(t)) + defer ctrl.Finish() + + removalTime := time.Now() + err := providerKeeper.AppendConsumerToBeRemoved(ctx, "consumerId1", removalTime) + require.NoError(t, err) + consumers, err := providerKeeper.GetConsumersToBeRemoved(ctx, removalTime) + require.NoError(t, err) + require.Equal(t, []string{"consumerId1"}, consumers.Ids) + + err = providerKeeper.AppendConsumerToBeRemoved(ctx, "consumerId2", removalTime) + require.NoError(t, err) + consumers, err = providerKeeper.GetConsumersToBeRemoved(ctx, removalTime) + require.NoError(t, err) + require.Equal(t, []string{"consumerId1", "consumerId2"}, consumers.Ids) + + err = providerKeeper.AppendConsumerToBeRemoved(ctx, "consumerId3", removalTime) + require.NoError(t, err) + consumers, err = providerKeeper.GetConsumersToBeRemoved(ctx, removalTime) + require.NoError(t, err) + require.Equal(t, []string{"consumerId1", "consumerId2", "consumerId3"}, consumers.Ids) + + err = providerKeeper.RemoveConsumerToBeRemoved(ctx, "consumerId2", removalTime) + require.NoError(t, err) + consumers, err = providerKeeper.GetConsumersToBeRemoved(ctx, removalTime) + require.NoError(t, err) + require.Equal(t, []string{"consumerId1", "consumerId3"}, consumers.Ids) + + // also add consumer ids under a different removal time and verify everything under the original removal time is still there + removalTimePlusOneHour := removalTime.Add(time.Hour) + err = providerKeeper.AppendConsumerToBeRemoved(ctx, "consumerId4", removalTimePlusOneHour) + require.NoError(t, err) + consumers, err = providerKeeper.GetConsumersToBeRemoved(ctx, removalTimePlusOneHour) + require.NoError(t, err) + require.Equal(t, []string{"consumerId4"}, consumers.Ids) + + consumers, err = providerKeeper.GetConsumersToBeRemoved(ctx, removalTime) + require.NoError(t, err) + require.Equal(t, []string{"consumerId1", "consumerId3"}, consumers.Ids) + + // start removing all consumers from `removalTime` + err = providerKeeper.RemoveConsumerToBeRemoved(ctx, "consumerId3", removalTime) + require.NoError(t, err) + err = providerKeeper.RemoveConsumerToBeRemoved(ctx, "consumerId1", removalTime) + require.NoError(t, err) + consumers, err = providerKeeper.GetConsumersToBeRemoved(ctx, removalTime) + require.NoError(t, err) + require.Empty(t, consumers.Ids) + + // remove from `removalTimePlusOneHour` + err = providerKeeper.RemoveConsumerToBeRemoved(ctx, "consumerId4", removalTimePlusOneHour) + require.NoError(t, err) + consumers, err = providerKeeper.GetConsumersToBeRemoved(ctx, removalTimePlusOneHour) + require.NoError(t, err) + require.Empty(t, consumers.Ids) + + // add another consumer for `removalTime` + err = providerKeeper.AppendConsumerToBeRemoved(ctx, "consumerId5", removalTime) + require.NoError(t, err) + consumers, err = providerKeeper.GetConsumersToBeRemoved(ctx, removalTime) + require.NoError(t, err) + require.Equal(t, []string{"consumerId5"}, consumers.Ids) +} diff --git a/x/ccv/provider/keeper/distribution.go b/x/ccv/provider/keeper/distribution.go index 7970a8c682..db75ff9b6e 100644 --- a/x/ccv/provider/keeper/distribution.go +++ b/x/ccv/provider/keeper/distribution.go @@ -74,33 +74,35 @@ func (k Keeper) AllocateTokens(ctx sdk.Context) { return } - // Iterate over all registered consumer chains - for _, consumerChainID := range k.GetAllRegisteredConsumerChainIDs(ctx) { + // Iterate over all launched consumer chains. + // To avoid large iterations over all the consumer IDs, iterate only over + // chains with an IBC client created. + for _, consumerId := range k.GetAllConsumersWithIBCClients(ctx) { // note that it's possible that no rewards are collected even though the // reward pool isn't empty. This can happen if the reward pool holds some tokens // of non-whitelisted denominations. - alloc := k.GetConsumerRewardsAllocation(ctx, consumerChainID) + alloc := k.GetConsumerRewardsAllocation(ctx, consumerId) if alloc.Rewards.IsZero() { continue } // temporary workaround to keep CanWithdrawInvariant happy // general discussions here: https://github.com/cosmos/cosmos-sdk/issues/2906#issuecomment-441867634 - if k.ComputeConsumerTotalVotingPower(ctx, consumerChainID) == 0 { + if k.ComputeConsumerTotalVotingPower(ctx, consumerId) == 0 { rewardsToSend, rewardsChange := alloc.Rewards.TruncateDecimal() err := k.distributionKeeper.FundCommunityPool(context.Context(ctx), rewardsToSend, k.accountKeeper.GetModuleAccount(ctx, types.ConsumerRewardsPool).GetAddress()) if err != nil { k.Logger(ctx).Error( "fail to allocate rewards from consumer chain %s to community pool: %s", - consumerChainID, + consumerId, err, ) } // set the consumer allocation to the remaining reward decimals alloc.Rewards = rewardsChange - k.SetConsumerRewardsAllocation(ctx, consumerChainID, alloc) + k.SetConsumerRewardsAllocation(ctx, consumerId, alloc) return } @@ -112,7 +114,7 @@ func (k Keeper) AllocateTokens(ctx sdk.Context) { if err != nil { k.Logger(ctx).Error( "cannot get community tax while allocating rewards from consumer chain %s: %s", - consumerChainID, + consumerId, err, ) continue @@ -132,7 +134,7 @@ func (k Keeper) AllocateTokens(ctx sdk.Context) { if err != nil { k.Logger(ctx).Error( "cannot send rewards to distribution module account %s: %s", - consumerChainID, + consumerId, err, ) continue @@ -141,7 +143,7 @@ func (k Keeper) AllocateTokens(ctx sdk.Context) { // allocate tokens to consumer validators k.AllocateTokensToConsumerValidators( ctx, - consumerChainID, + consumerId, sdk.NewDecCoinsFromCoins(validatorsRewardsTrunc...), ) @@ -151,7 +153,7 @@ func (k Keeper) AllocateTokens(ctx sdk.Context) { if err != nil { k.Logger(ctx).Error( "fail to allocate rewards from consumer chain %s to community pool: %s", - consumerChainID, + consumerId, err, ) continue @@ -159,7 +161,7 @@ func (k Keeper) AllocateTokens(ctx sdk.Context) { // set consumer allocations to the remaining rewards decimals alloc.Rewards = validatorsRewardsChange.Add(remainingChanges...) - k.SetConsumerRewardsAllocation(ctx, consumerChainID, alloc) + k.SetConsumerRewardsAllocation(ctx, consumerId, alloc) } } @@ -176,7 +178,7 @@ func (k Keeper) IsEligibleForConsumerRewards(ctx sdk.Context, consumerValidatorH // to the given consumer chain's validator set func (k Keeper) AllocateTokensToConsumerValidators( ctx sdk.Context, - chainID string, + consumerId string, tokens sdk.DecCoins, ) (allocated sdk.DecCoins) { // return early if the tokens are empty @@ -185,17 +187,17 @@ func (k Keeper) AllocateTokensToConsumerValidators( } // get the total voting power of the consumer valset - totalPower := math.LegacyNewDec(k.ComputeConsumerTotalVotingPower(ctx, chainID)) + totalPower := math.LegacyNewDec(k.ComputeConsumerTotalVotingPower(ctx, consumerId)) if totalPower.IsZero() { return allocated } // Allocate tokens by iterating over the consumer validators - consumerVals, err := k.GetConsumerValSet(ctx, chainID) + consumerVals, err := k.GetConsumerValSet(ctx, consumerId) if err != nil { k.Logger(ctx).Error( "cannot get consumer validator set while allocating rewards from consumer chain", - chainID, + consumerId, "error", err, ) @@ -220,7 +222,7 @@ func (k Keeper) AllocateTokensToConsumerValidators( "cannot find validator by consensus address", consAddr, "while allocating rewards from consumer chain", - chainID, + consumerId, "error", err, ) @@ -228,7 +230,7 @@ func (k Keeper) AllocateTokensToConsumerValidators( } // check if the validator set a custom commission rate for the consumer chain - if cr, found := k.GetConsumerCommissionRate(ctx, chainID, types.NewProviderConsAddress(consAddr)); found { + if cr, found := k.GetConsumerCommissionRate(ctx, consumerId, types.NewProviderConsAddress(consAddr)); found { // set the validator commission rate val.Commission.CommissionRates.Rate = cr } @@ -241,7 +243,7 @@ func (k Keeper) AllocateTokensToConsumerValidators( ) if err != nil { k.Logger(ctx).Error("fail to allocate tokens to validator :%s while allocating rewards from consumer chain: %s", - consAddr, chainID) + consAddr, consumerId) continue } @@ -254,19 +256,25 @@ func (k Keeper) AllocateTokensToConsumerValidators( // consumer reward pools getter and setter -// GetConsumerRewardsAllocation returns the consumer rewards allocation for the given chain ID -func (k Keeper) GetConsumerRewardsAllocation(ctx sdk.Context, chainID string) (pool types.ConsumerRewardsAllocation) { +// GetConsumerRewardsAllocation returns the consumer rewards allocation for the given consumer id +func (k Keeper) GetConsumerRewardsAllocation(ctx sdk.Context, consumerId string) (pool types.ConsumerRewardsAllocation) { store := ctx.KVStore(k.storeKey) - b := store.Get(types.ConsumerRewardsAllocationKey(chainID)) + b := store.Get(types.ConsumerRewardsAllocationKey(consumerId)) k.cdc.MustUnmarshal(b, &pool) return } -// SetConsumerRewardsAllocation sets the consumer rewards allocation for the given chain ID -func (k Keeper) SetConsumerRewardsAllocation(ctx sdk.Context, chainID string, pool types.ConsumerRewardsAllocation) { +// SetConsumerRewardsAllocation sets the consumer rewards allocation for the given consumer id +func (k Keeper) SetConsumerRewardsAllocation(ctx sdk.Context, consumerId string, pool types.ConsumerRewardsAllocation) { store := ctx.KVStore(k.storeKey) b := k.cdc.MustMarshal(&pool) - store.Set(types.ConsumerRewardsAllocationKey(chainID), b) + store.Set(types.ConsumerRewardsAllocationKey(consumerId), b) +} + +// DeleteConsumerRewardsAllocation deletes the consumer rewards allocation for the given consumer id +func (k Keeper) DeleteConsumerRewardsAllocation(ctx sdk.Context, consumerId string) { + store := ctx.KVStore(k.storeKey) + store.Delete(types.ConsumerRewardsAllocationKey(consumerId)) } // GetConsumerRewardsPool returns the balance @@ -280,20 +288,19 @@ func (k Keeper) GetConsumerRewardsPool(ctx sdk.Context) sdk.Coins { // ComputeConsumerTotalVotingPower returns the validator set total voting power // for the given consumer chain -func (k Keeper) ComputeConsumerTotalVotingPower(ctx sdk.Context, chainID string) (totalPower int64) { +func (k Keeper) ComputeConsumerTotalVotingPower(ctx sdk.Context, consumerId string) (totalPower int64) { // sum the consumer validators set voting powers - vals, err := k.GetConsumerValSet(ctx, chainID) + vals, err := k.GetConsumerValSet(ctx, consumerId) if err != nil { k.Logger(ctx).Error( "cannot get consumer validator set while computing total voting power for consumer chain", - chainID, + consumerId, "error", err, ) return } for _, v := range vals { - // only consider the voting power of a validator that would receive rewards (i.e., validator has been validating for a number of blocks) if !k.IsEligibleForConsumerRewards(ctx, v.JoinHeight) { continue @@ -305,9 +312,9 @@ func (k Keeper) ComputeConsumerTotalVotingPower(ctx sdk.Context, chainID string) return } -// IdentifyConsumerChainIDFromIBCPacket checks if the packet destination matches a registered consumer chain. +// IdentifyConsumerIdFromIBCPacket checks if the packet destination matches a registered consumer chain. // If so, it returns the consumer chain ID, otherwise an error. -func (k Keeper) IdentifyConsumerChainIDFromIBCPacket(ctx sdk.Context, packet channeltypes.Packet) (string, error) { +func (k Keeper) IdentifyConsumerIdFromIBCPacket(ctx sdk.Context, packet channeltypes.Packet) (string, error) { channel, ok := k.channelKeeper.GetChannel(ctx, packet.DestinationPort, packet.DestinationChannel) if !ok { return "", errorsmod.Wrapf(channeltypes.ErrChannelNotFound, "channel not found for channel ID: %s", packet.DestinationChannel) @@ -316,27 +323,31 @@ func (k Keeper) IdentifyConsumerChainIDFromIBCPacket(ctx sdk.Context, packet cha return "", errorsmod.Wrap(channeltypes.ErrTooManyConnectionHops, "must have direct connection to consumer chain") } connectionID := channel.ConnectionHops[0] - _, tmClient, err := k.getUnderlyingClient(ctx, connectionID) + clientId, _, err := k.getUnderlyingClient(ctx, connectionID) if err != nil { return "", err } - chainID := tmClient.ChainId - if _, ok := k.GetChainToChannel(ctx, chainID); !ok { - return "", errorsmod.Wrapf(types.ErrUnknownConsumerChannelId, "no CCV channel found for chain with ID: %s", chainID) + consumerId, found := k.GetClientIdToConsumerId(ctx, clientId) + if !found { + return "", errorsmod.Wrapf(types.ErrUnknownConsumerId, "no consumer id for client with id: %s", clientId) + } + + if _, ok := k.GetConsumerIdToChannelId(ctx, consumerId); !ok { + return "", errorsmod.Wrapf(types.ErrUnknownConsumerChannelId, "no CCV channel found for chain with ID: %s", consumerId) } - return chainID, nil + return consumerId, nil } // HandleSetConsumerCommissionRate sets a per-consumer chain commission rate for the given provider address // on the condition that the given consumer chain exists. -func (k Keeper) HandleSetConsumerCommissionRate(ctx sdk.Context, chainID string, providerAddr types.ProviderConsAddress, commissionRate math.LegacyDec) error { - // check that the consumer chain exists - if !k.IsConsumerProposedOrRegistered(ctx, chainID) { +func (k Keeper) HandleSetConsumerCommissionRate(ctx sdk.Context, consumerId string, providerAddr types.ProviderConsAddress, commissionRate math.LegacyDec) error { + // check that the consumer chain is active -- registered, initialized, or launched + if !k.IsConsumerActive(ctx, consumerId) { return errorsmod.Wrapf( - types.ErrUnknownConsumerChainId, - "unknown consumer chain, with id: %s", chainID) + types.ErrInvalidPhase, + "unknown consumer chain, with id: %s", consumerId) } // validate against the minimum commission rate @@ -353,8 +364,45 @@ func (k Keeper) HandleSetConsumerCommissionRate(ctx sdk.Context, chainID string, // set per-consumer chain commission rate for the validator address return k.SetConsumerCommissionRate( ctx, - chainID, + consumerId, providerAddr, commissionRate, ) } + +// TODO: this method needs to be tested +func (k Keeper) ChangeRewardDenoms(ctx sdk.Context, denomsToAdd, denomsToRemove []string) []sdk.Attribute { + // initialize an empty slice to store event attributes + eventAttributes := []sdk.Attribute{} + + // loop through denomsToAdd and add each denomination if it is not already registered + for _, denomToAdd := range denomsToAdd { + // Log error and move on if one of the denoms is already registered + if k.ConsumerRewardDenomExists(ctx, denomToAdd) { + k.Logger(ctx).Error("ChangeRewardDenoms: denom already registered", + "denomToAdd", denomToAdd, + ) + continue + } + k.SetConsumerRewardDenom(ctx, denomToAdd) + + eventAttributes = append(eventAttributes, sdk.NewAttribute(types.AttributeAddConsumerRewardDenom, denomToAdd)) + } + + // loop through denomsToRemove and remove each denomination if it is registered + for _, denomToRemove := range denomsToRemove { + // Log error and move on if one of the denoms is not registered + if !k.ConsumerRewardDenomExists(ctx, denomToRemove) { + k.Logger(ctx).Error("ChangeRewardDenoms: denom not registered", + "denomToRemove", denomToRemove, + ) + continue + } + k.DeleteConsumerRewardDenom(ctx, denomToRemove) + + eventAttributes = append(eventAttributes, sdk.NewAttribute(types.AttributeRemoveConsumerRewardDenom, denomToRemove)) + } + + // return the slice of event attributes + return eventAttributes +} diff --git a/x/ccv/provider/keeper/distribution_test.go b/x/ccv/provider/keeper/distribution_test.go index e8caeb7c36..c449b0149c 100644 --- a/x/ccv/provider/keeper/distribution_test.go +++ b/x/ccv/provider/keeper/distribution_test.go @@ -225,13 +225,13 @@ func TestIdentifyConsumerChainIDFromIBCPacket(t *testing.T) { defer ctrl.Finish() tc.expectedCalls(ctx, mocks, tc.packet) - _, err := keeper.IdentifyConsumerChainIDFromIBCPacket( + _, err := keeper.IdentifyConsumerIdFromIBCPacket( ctx, tc.packet, ) if tc.expCCVChannel { - keeper.SetChainToChannel(ctx, chainID, ccvChannel) + keeper.SetConsumerIdToChannelId(ctx, chainID, ccvChannel) } if !tc.expErr { @@ -296,3 +296,35 @@ func TestIsEligibleForConsumerRewards(t *testing.T) { require.True(t, keeper.IsEligibleForConsumerRewards(ctx.WithBlockHeight(numberOfBlocks+1), 1)) require.False(t, keeper.IsEligibleForConsumerRewards(ctx.WithBlockHeight(numberOfBlocks+1), 2)) } + +func TestChangeRewardDenoms(t *testing.T) { + keeper, ctx, _, _ := testkeeper.GetProviderKeeperAndCtx(t, testkeeper.NewInMemKeeperParams(t)) + + // Test adding a new denomination + denomsToAdd := []string{"denom1"} + denomsToRemove := []string{} + attributes := keeper.ChangeRewardDenoms(ctx, denomsToAdd, denomsToRemove) + + require.Len(t, attributes, 1) + require.Equal(t, providertypes.AttributeAddConsumerRewardDenom, attributes[0].Key) + require.Equal(t, "denom1", attributes[0].Value) + require.True(t, keeper.ConsumerRewardDenomExists(ctx, "denom1")) + + // Test adding a denomination that is already registered + attributes = keeper.ChangeRewardDenoms(ctx, denomsToAdd, denomsToRemove) + require.Len(t, attributes, 0) // No attributes should be returned since the denom is already registered + + // Test removing a registered denomination + denomsToAdd = []string{} + denomsToRemove = []string{"denom1"} + attributes = keeper.ChangeRewardDenoms(ctx, denomsToAdd, denomsToRemove) + + require.Len(t, attributes, 1) + require.Equal(t, providertypes.AttributeRemoveConsumerRewardDenom, attributes[0].Key) + require.Equal(t, "denom1", attributes[0].Value) + require.False(t, keeper.ConsumerRewardDenomExists(ctx, "denom1")) + + // Test removing a denomination that is not registered + attributes = keeper.ChangeRewardDenoms(ctx, denomsToAdd, denomsToRemove) + require.Len(t, attributes, 0) // No attributes should be returned since the denom is not registered +} diff --git a/x/ccv/provider/keeper/genesis.go b/x/ccv/provider/keeper/genesis.go index 5b44227f90..7e8fd4bb76 100644 --- a/x/ccv/provider/keeper/genesis.go +++ b/x/ccv/provider/keeper/genesis.go @@ -32,20 +32,11 @@ func (k Keeper) InitGenesis(ctx sdk.Context, genState *types.GenesisState) []abc k.SetValsetUpdateBlockHeight(ctx, v2h.ValsetUpdateId, v2h.Height) } - for _, prop := range genState.ConsumerAdditionProposals { - // prevent implicit memory aliasing - p := prop - k.SetPendingConsumerAdditionProp(ctx, &p) - } - for _, prop := range genState.ConsumerRemovalProposals { - p := prop - k.SetPendingConsumerRemovalProp(ctx, &p) - } - // Set initial state for each consumer chain for _, cs := range genState.ConsumerStates { chainID := cs.ChainId k.SetConsumerClientId(ctx, chainID, cs.ClientId) + k.SetConsumerPhase(ctx, chainID, cs.Phase) if err := k.SetConsumerGenesis(ctx, chainID, cs.ConsumerGenesis); err != nil { // An error here would indicate something is very wrong, // the ConsumerGenesis validated in ConsumerState.Validate(). @@ -53,8 +44,8 @@ func (k Keeper) InitGenesis(ctx sdk.Context, genState *types.GenesisState) []abc } // check if the CCV channel was established if cs.ChannelId != "" { - k.SetChannelToChain(ctx, cs.ChannelId, chainID) - k.SetChainToChannel(ctx, chainID, cs.ChannelId) + k.SetChannelToConsumerId(ctx, cs.ChannelId, chainID) + k.SetConsumerIdToChannelId(ctx, chainID, cs.ChannelId) k.SetInitChainHeight(ctx, chainID, cs.InitialHeight) k.SetSlashAcks(ctx, cs.ChainId, cs.SlashDowntimeAck) } else { @@ -128,57 +119,56 @@ func (k Keeper) InitGenesisValUpdates(ctx sdk.Context) []abci.ValidatorUpdate { // ExportGenesis returns the CCV provider module's exported genesis func (k Keeper) ExportGenesis(ctx sdk.Context) *types.GenesisState { - // get a list of all registered consumer chains - registeredChainIDs := k.GetAllRegisteredConsumerChainIDs(ctx) + launchedConsumerIds := k.GetAllConsumersWithIBCClients(ctx) // export states for each consumer chains var consumerStates []types.ConsumerState - for _, chainID := range registeredChainIDs { + for _, consumerId := range launchedConsumerIds { // no need for the second return value of GetConsumerClientId - // as GetAllRegisteredConsumerChainIDs already iterated through + // as GetAllConsumersWithIBCClients already iterated through // the entire prefix range - clientID, _ := k.GetConsumerClientId(ctx, chainID) - gen, found := k.GetConsumerGenesis(ctx, chainID) + clientId, _ := k.GetConsumerClientId(ctx, consumerId) + gen, found := k.GetConsumerGenesis(ctx, consumerId) if !found { - panic(fmt.Errorf("cannot find genesis for consumer chain %s with client %s", chainID, clientID)) + panic(fmt.Errorf("cannot find genesis for consumer chain %s with client %s", consumerId, clientId)) } // initial consumer chain states cs := types.ConsumerState{ - ChainId: chainID, - ClientId: clientID, + ChainId: consumerId, + ClientId: clientId, ConsumerGenesis: gen, + Phase: k.GetConsumerPhase(ctx, consumerId), } // try to find channel id for the current consumer chain - channelId, found := k.GetChainToChannel(ctx, chainID) + channelId, found := k.GetConsumerIdToChannelId(ctx, consumerId) if found { cs.ChannelId = channelId - cs.InitialHeight, found = k.GetInitChainHeight(ctx, chainID) + cs.InitialHeight, found = k.GetInitChainHeight(ctx, consumerId) if !found { - panic(fmt.Errorf("cannot find init height for consumer chain %s", chainID)) + panic(fmt.Errorf("cannot find init height for consumer chain %s", consumerId)) } - cs.SlashDowntimeAck = k.GetSlashAcks(ctx, chainID) + cs.SlashDowntimeAck = k.GetSlashAcks(ctx, consumerId) } - cs.PendingValsetChanges = k.GetPendingVSCPackets(ctx, chainID) + cs.PendingValsetChanges = k.GetPendingVSCPackets(ctx, consumerId) consumerStates = append(consumerStates, cs) } // ConsumerAddrsToPrune are added only for registered consumer chains consumerAddrsToPrune := []types.ConsumerAddrsToPruneV2{} - for _, chainID := range registeredChainIDs { + for _, chainID := range launchedConsumerIds { consumerAddrsToPrune = append(consumerAddrsToPrune, k.GetAllConsumerAddrsToPrune(ctx, chainID)...) } params := k.GetParams(ctx) + // TODO (PERMISSIONLESS) return types.NewGenesisState( k.GetValidatorSetUpdateId(ctx), k.GetAllValsetUpdateBlockHeights(ctx), consumerStates, - k.GetAllPendingConsumerAdditionProps(ctx), - k.GetAllPendingConsumerRemovalProps(ctx), params, k.GetAllValidatorConsumerPubKeys(ctx, nil), k.GetAllValidatorsByConsumerAddr(ctx, nil), diff --git a/x/ccv/provider/keeper/genesis_test.go b/x/ccv/provider/keeper/genesis_test.go index 82069b4b8d..af3e0ea843 100644 --- a/x/ccv/provider/keeper/genesis_test.go +++ b/x/ccv/provider/keeper/genesis_test.go @@ -51,6 +51,7 @@ func TestInitAndExportGenesis(t *testing.T) { *ccv.DefaultConsumerGenesisState(), []ccv.ValidatorSetChangePacketData{}, []string{"slashedValidatorConsAddress"}, + providertypes.CONSUMER_PHASE_LAUNCHED, ), providertypes.NewConsumerStates( cChainIDs[1], @@ -60,16 +61,9 @@ func TestInitAndExportGenesis(t *testing.T) { *ccv.DefaultConsumerGenesisState(), []ccv.ValidatorSetChangePacketData{{ValsetUpdateId: vscID}}, nil, + providertypes.CONSUMER_PHASE_LAUNCHED, ), }, - []providertypes.ConsumerAdditionProposal{{ - ChainId: cChainIDs[0], - SpawnTime: oneHourFromNow, - }}, - []providertypes.ConsumerRemovalProposal{{ - ChainId: cChainIDs[0], - StopTime: oneHourFromNow, - }}, params, []providertypes.ValidatorConsumerPubKey{ { @@ -132,17 +126,13 @@ func TestInitAndExportGenesis(t *testing.T) { require.Equal(t, expectedCandidate, pk.GetSlashMeterReplenishTimeCandidate(ctx)) // check local provider chain states - chainID, found := pk.GetChannelToChain(ctx, provGenesis.ConsumerStates[0].ChannelId) + chainID, found := pk.GetChannelIdToConsumerId(ctx, provGenesis.ConsumerStates[0].ChannelId) require.True(t, found) require.Equal(t, cChainIDs[0], chainID) require.Equal(t, vscID, pk.GetValidatorSetUpdateId(ctx)) height, found := pk.GetValsetUpdateBlockHeight(ctx, vscID) require.True(t, found) require.Equal(t, initHeight, height) - addProp, found := pk.GetPendingConsumerAdditionProp(ctx, oneHourFromNow, cChainIDs[0]) - require.True(t, found) - require.Equal(t, provGenesis.ConsumerAdditionProposals[0], addProp) - require.True(t, pk.PendingConsumerRemovalPropExists(ctx, cChainIDs[0], oneHourFromNow)) require.Equal(t, provGenesis.Params, pk.GetParams(ctx)) providerConsensusValSet, err := pk.GetLastProviderConsensusValSet(ctx) @@ -189,7 +179,7 @@ func assertConsumerChainStates(t *testing.T, ctx sdk.Context, pk keeper.Keeper, require.Equal(t, cs.ClientId, clientID) if expChan := cs.ChannelId; expChan != "" { - gotChan, found := pk.GetChainToChannel(ctx, chainID) + gotChan, found := pk.GetConsumerIdToChannelId(ctx, chainID) require.True(t, found) require.Equal(t, expChan, gotChan) } diff --git a/x/ccv/provider/keeper/grpc_query.go b/x/ccv/provider/keeper/grpc_query.go index 2635648a6a..170b3ba29b 100644 --- a/x/ccv/provider/keeper/grpc_query.go +++ b/x/ccv/provider/keeper/grpc_query.go @@ -1,17 +1,17 @@ package keeper import ( + "bytes" "context" "fmt" + "sort" "google.golang.org/grpc/codes" "google.golang.org/grpc/status" errorsmod "cosmossdk.io/errors" - "cosmossdk.io/math" sdk "github.com/cosmos/cosmos-sdk/types" - "github.com/cosmos/interchain-security/v5/x/ccv/provider/types" ccvtypes "github.com/cosmos/interchain-security/v5/x/ccv/types" ) @@ -25,15 +25,16 @@ func (k Keeper) QueryConsumerGenesis(c context.Context, req *types.QueryConsumer return nil, status.Errorf(codes.InvalidArgument, "empty request") } - if req.ChainId == "" { - return nil, status.Errorf(codes.InvalidArgument, "invalid request: chain id cannot be empty") + consumerId := req.ConsumerId + if err := types.ValidateConsumerId(consumerId); err != nil { + return nil, status.Error(codes.InvalidArgument, errorsmod.Wrap(types.ErrInvalidConsumerId, consumerId).Error()) } - gen, ok := k.GetConsumerGenesis(ctx, req.ChainId) + gen, ok := k.GetConsumerGenesis(ctx, consumerId) if !ok { return nil, status.Error( codes.NotFound, - errorsmod.Wrap(types.ErrUnknownConsumerChainId, req.ChainId).Error(), + errorsmod.Wrap(types.ErrUnknownConsumerId, consumerId).Error(), ) } @@ -47,119 +48,108 @@ func (k Keeper) QueryConsumerChains(goCtx context.Context, req *types.QueryConsu ctx := sdk.UnwrapSDKContext(goCtx) - chains := []*types.Chain{} - for _, chainID := range k.GetAllRegisteredConsumerChainIDs(ctx) { - c, err := k.GetConsumerChain(ctx, chainID) + consumerIds := []string{} + for _, consumerID := range k.GetAllConsumerIds(ctx) { + phase := k.GetConsumerPhase(ctx, consumerID) + if req.Phase != types.CONSUMER_PHASE_UNSPECIFIED && req.Phase != phase { + // ignore consumer chain + continue + } + consumerIds = append(consumerIds, consumerID) + } + + // set limit to default value + limit := 100 + if req.Limit != 0 { + // update limit if specified + limit = int(req.Limit) + } + if len(consumerIds) > limit { + consumerIds = consumerIds[:limit] + } + + chains := make([]*types.Chain, len(consumerIds)) + for i, cID := range consumerIds { + c, err := k.GetConsumerChain(ctx, cID) if err != nil { return nil, status.Error(codes.Internal, err.Error()) } - chains = append(chains, &c) + chains[i] = &c } return &types.QueryConsumerChainsResponse{Chains: chains}, nil } // GetConsumerChain returns a Chain data structure with all the necessary fields -func (k Keeper) GetConsumerChain(ctx sdk.Context, chainID string) (types.Chain, error) { - clientID, found := k.GetConsumerClientId(ctx, chainID) - if !found { - return types.Chain{}, fmt.Errorf("cannot find clientID for consumer (%s)", chainID) +func (k Keeper) GetConsumerChain(ctx sdk.Context, consumerId string) (types.Chain, error) { + chainID, err := k.GetConsumerChainId(ctx, consumerId) + if err != nil { + return types.Chain{}, fmt.Errorf("cannot find chainID for consumer (%s)", consumerId) } - topN, found := k.GetTopN(ctx, chainID) - if !found { - k.Logger(ctx).Error("failed to get top N, treating as 0", "chain", chainID) - topN = 0 + clientID, _ := k.GetConsumerClientId(ctx, consumerId) + + powerShapingParameters, err := k.GetConsumerPowerShapingParameters(ctx, consumerId) + if err != nil { + return types.Chain{}, fmt.Errorf("cannot find power shaping parameters for consumer (%s): %s", consumerId, err.Error()) } // Get the minimal power in the top N for the consumer chain - minPowerInTopN, found := k.GetMinimumPowerInTopN(ctx, chainID) + minPowerInTopN, found := k.GetMinimumPowerInTopN(ctx, consumerId) if !found { - k.Logger(ctx).Error("failed to get minimum power in top N, treating as -1", "chain", chainID) minPowerInTopN = -1 } - validatorSetCap, _ := k.GetValidatorSetCap(ctx, chainID) - - validatorsPowerCap, _ := k.GetValidatorsPowerCap(ctx, chainID) - - allowlist := k.GetAllowList(ctx, chainID) + allowlist := k.GetAllowList(ctx, consumerId) strAllowlist := make([]string, len(allowlist)) for i, addr := range allowlist { strAllowlist[i] = addr.String() } - denylist := k.GetDenyList(ctx, chainID) + denylist := k.GetDenyList(ctx, consumerId) strDenylist := make([]string, len(denylist)) for i, addr := range denylist { strDenylist[i] = addr.String() } - allowInactiveVals := k.AllowsInactiveValidators(ctx, chainID) - - minStake, _ := k.GetMinStake(ctx, chainID) + metadata, _ := k.GetConsumerMetadata(ctx, consumerId) return types.Chain{ ChainId: chainID, ClientId: clientID, - Top_N: topN, + Top_N: powerShapingParameters.Top_N, MinPowerInTop_N: minPowerInTopN, - ValidatorSetCap: validatorSetCap, - ValidatorsPowerCap: validatorsPowerCap, + ValidatorSetCap: powerShapingParameters.ValidatorSetCap, + ValidatorsPowerCap: powerShapingParameters.ValidatorsPowerCap, Allowlist: strAllowlist, Denylist: strDenylist, - AllowInactiveVals: allowInactiveVals, - MinStake: minStake, + Phase: k.GetConsumerPhase(ctx, consumerId).String(), + Metadata: metadata, + AllowInactiveVals: powerShapingParameters.AllowInactiveVals, + MinStake: powerShapingParameters.MinStake, + ConsumerId: consumerId, }, nil } -func (k Keeper) QueryConsumerChainStarts(goCtx context.Context, req *types.QueryConsumerChainStartProposalsRequest) (*types.QueryConsumerChainStartProposalsResponse, error) { +func (k Keeper) QueryValidatorConsumerAddr(goCtx context.Context, req *types.QueryValidatorConsumerAddrRequest) (*types.QueryValidatorConsumerAddrResponse, error) { if req == nil { - return nil, status.Error(codes.InvalidArgument, "empty request") + return nil, status.Errorf(codes.InvalidArgument, "empty request") } ctx := sdk.UnwrapSDKContext(goCtx) - var props []*types.ConsumerAdditionProposal - - for _, prop := range k.GetAllPendingConsumerAdditionProps(ctx) { - // prevent implicit memory aliasing - p := prop - props = append(props, &p) - } - return &types.QueryConsumerChainStartProposalsResponse{Proposals: &types.ConsumerAdditionProposals{Pending: props}}, nil -} - -func (k Keeper) QueryConsumerChainStops(goCtx context.Context, req *types.QueryConsumerChainStopProposalsRequest) (*types.QueryConsumerChainStopProposalsResponse, error) { - if req == nil { - return nil, status.Error(codes.InvalidArgument, "empty request") + consumerId := req.ConsumerId + if err := types.ValidateConsumerId(consumerId); err != nil { + return nil, status.Error(codes.InvalidArgument, errorsmod.Wrap(types.ErrInvalidConsumerId, consumerId).Error()) } - ctx := sdk.UnwrapSDKContext(goCtx) - var props []*types.ConsumerRemovalProposal - for _, prop := range k.GetAllPendingConsumerRemovalProps(ctx) { - // prevent implicit memory aliasing - p := prop - props = append(props, &p) - } - - return &types.QueryConsumerChainStopProposalsResponse{Proposals: &types.ConsumerRemovalProposals{Pending: props}}, nil -} - -func (k Keeper) QueryValidatorConsumerAddr(goCtx context.Context, req *types.QueryValidatorConsumerAddrRequest) (*types.QueryValidatorConsumerAddrResponse, error) { - if req == nil { - return nil, status.Error(codes.InvalidArgument, "empty request") - } - - ctx := sdk.UnwrapSDKContext(goCtx) - providerAddrTmp, err := sdk.ConsAddressFromBech32(req.ProviderAddress) if err != nil { return nil, err } providerAddr := types.NewProviderConsAddress(providerAddrTmp) - consumerKey, found := k.GetValidatorConsumerPubKey(ctx, req.ChainId, providerAddr) + consumerKey, found := k.GetValidatorConsumerPubKey(ctx, consumerId, providerAddr) if !found { return &types.QueryValidatorConsumerAddrResponse{}, nil } @@ -176,7 +166,7 @@ func (k Keeper) QueryValidatorConsumerAddr(goCtx context.Context, req *types.Que func (k Keeper) QueryValidatorProviderAddr(goCtx context.Context, req *types.QueryValidatorProviderAddrRequest) (*types.QueryValidatorProviderAddrResponse, error) { if req == nil { - return nil, status.Error(codes.InvalidArgument, "empty request") + return nil, status.Errorf(codes.InvalidArgument, "empty request") } ctx := sdk.UnwrapSDKContext(goCtx) @@ -187,7 +177,7 @@ func (k Keeper) QueryValidatorProviderAddr(goCtx context.Context, req *types.Que } consumerAddr := types.NewConsumerConsAddress(consumerAddrTmp) - providerAddr, found := k.GetValidatorByConsumerAddr(ctx, req.ChainId, consumerAddr) + providerAddr, found := k.GetValidatorByConsumerAddr(ctx, req.ConsumerId, consumerAddr) if !found { return &types.QueryValidatorProviderAddrResponse{}, nil } @@ -229,34 +219,24 @@ func (k Keeper) QueryRegisteredConsumerRewardDenoms(goCtx context.Context, req * }, nil } -func (k Keeper) QueryProposedConsumerChainIDs(goCtx context.Context, req *types.QueryProposedChainIDsRequest) (*types.QueryProposedChainIDsResponse, error) { - if req == nil { - return nil, status.Error(codes.InvalidArgument, "empty request") - } - - ctx := sdk.UnwrapSDKContext(goCtx) - - chains := k.GetAllProposedConsumerChainIDs(ctx) - - return &types.QueryProposedChainIDsResponse{ - ProposedChains: chains, - }, nil -} - -func (k Keeper) QueryAllPairsValConAddrByConsumerChainID(goCtx context.Context, req *types.QueryAllPairsValConAddrByConsumerChainIDRequest) (*types.QueryAllPairsValConAddrByConsumerChainIDResponse, error) { +func (k Keeper) QueryAllPairsValConsAddrByConsumer( + goCtx context.Context, + req *types.QueryAllPairsValConsAddrByConsumerRequest, +) (*types.QueryAllPairsValConsAddrByConsumerResponse, error) { if req == nil { - return nil, status.Error(codes.InvalidArgument, "empty request") + return nil, status.Errorf(codes.InvalidArgument, "empty request") } - if req.ChainId == "" { - return nil, status.Error(codes.InvalidArgument, "empty chainId") + consumerId := req.ConsumerId + if err := types.ValidateConsumerId(consumerId); err != nil { + return nil, status.Error(codes.InvalidArgument, errorsmod.Wrap(types.ErrInvalidConsumerId, consumerId).Error()) } // list of pairs valconsensus addr pairValConAddrs := []*types.PairValConAddrProviderAndConsumer{} ctx := sdk.UnwrapSDKContext(goCtx) - validatorConsumerPubKeys := k.GetAllValidatorConsumerPubKeys(ctx, &req.ChainId) + validatorConsumerPubKeys := k.GetAllValidatorConsumerPubKeys(ctx, &consumerId) for _, data := range validatorConsumerPubKeys { consumerAddr, err := ccvtypes.TMCryptoPublicKeyToConsAddr(*data.ConsumerKey) if err != nil { @@ -269,7 +249,7 @@ func (k Keeper) QueryAllPairsValConAddrByConsumerChainID(goCtx context.Context, }) } - return &types.QueryAllPairsValConAddrByConsumerChainIDResponse{ + return &types.QueryAllPairsValConsAddrByConsumerResponse{ PairValConAddr: pairValConAddrs, }, nil } @@ -289,22 +269,22 @@ func (k Keeper) QueryParams(goCtx context.Context, req *types.QueryParamsRequest // QueryConsumerChainOptedInValidators returns all validators that opted-in to a given consumer chain func (k Keeper) QueryConsumerChainOptedInValidators(goCtx context.Context, req *types.QueryConsumerChainOptedInValidatorsRequest) (*types.QueryConsumerChainOptedInValidatorsResponse, error) { if req == nil { - return nil, status.Error(codes.InvalidArgument, "empty request") + return nil, status.Errorf(codes.InvalidArgument, "empty request") } - consumerChainID := req.ChainId - if consumerChainID == "" { - return nil, status.Error(codes.InvalidArgument, "empty chainId") + consumerId := req.ConsumerId + if err := types.ValidateConsumerId(consumerId); err != nil { + return nil, status.Error(codes.InvalidArgument, errorsmod.Wrap(types.ErrInvalidConsumerId, consumerId).Error()) } optedInVals := []string{} ctx := sdk.UnwrapSDKContext(goCtx) - if !k.IsConsumerProposedOrRegistered(ctx, consumerChainID) { - return nil, status.Error(codes.InvalidArgument, fmt.Sprintf("unknown consumer chain: %s", consumerChainID)) + if !k.IsConsumerActive(ctx, consumerId) { + return nil, status.Error(codes.InvalidArgument, fmt.Sprintf("unknown consumer chain: %s", consumerId)) } - for _, v := range k.GetAllOptedIn(ctx, consumerChainID) { + for _, v := range k.GetAllOptedIn(ctx, consumerId) { optedInVals = append(optedInVals, v.ToSdkConsAddr().String()) } @@ -316,52 +296,104 @@ func (k Keeper) QueryConsumerChainOptedInValidators(goCtx context.Context, req * // QueryConsumerValidators returns all validators that are consumer validators in a given consumer chain func (k Keeper) QueryConsumerValidators(goCtx context.Context, req *types.QueryConsumerValidatorsRequest) (*types.QueryConsumerValidatorsResponse, error) { if req == nil { - return nil, status.Error(codes.InvalidArgument, "empty request") + return nil, status.Errorf(codes.InvalidArgument, "empty request") } - consumerChainID := req.ChainId - if consumerChainID == "" { - return nil, status.Error(codes.InvalidArgument, "empty chainId") + consumerId := req.ConsumerId + if err := types.ValidateConsumerId(consumerId); err != nil { + return nil, status.Error(codes.InvalidArgument, errorsmod.Wrap(types.ErrInvalidConsumerId, consumerId).Error()) } ctx := sdk.UnwrapSDKContext(goCtx) - if _, found := k.GetConsumerClientId(ctx, consumerChainID); !found { - // chain has to have started; consumer client id is set for a chain during the chain's spawn time - return nil, status.Error(codes.InvalidArgument, fmt.Sprintf("no started consumer chain: %s", consumerChainID)) + // get the consumer phase + phase := k.GetConsumerPhase(ctx, consumerId) + if phase == types.CONSUMER_PHASE_UNSPECIFIED { + return nil, status.Errorf(codes.InvalidArgument, "cannot find a phase for consumer: %s", consumerId) } - var validators []*types.QueryConsumerValidatorsValidator - - consumerValSet, err := k.GetConsumerValSet(ctx, consumerChainID) - if err != nil { - return nil, status.Error(codes.Internal, err.Error()) - } + // query consumer validator set - for _, v := range consumerValSet { + var consumerValSet []types.ConsensusValidator + var err error - consAddr, err := sdk.ConsAddressFromBech32(sdk.ConsAddress(v.ProviderConsAddr).String()) + // if the consumer launched, the consumer valset has been persisted + if phase == types.CONSUMER_PHASE_LAUNCHED { + consumerValSet, err = k.GetConsumerValSet(ctx, consumerId) + if err != nil { + return nil, status.Error(codes.Internal, err.Error()) + } + // if the consumer hasn't been launched or stopped, compute the consumer validator set + } else if phase != types.CONSUMER_PHASE_STOPPED { + bondedValidators, err := k.GetLastBondedValidators(ctx) if err != nil { - return nil, status.Error(codes.InvalidArgument, "invalid provider address") + return nil, status.Error(codes.Internal, fmt.Sprintf("failed to get last validators: %s", err)) } + minPower := int64(0) + // for TopN chains, compute the minPower that will be automatically opted in + powerShapingParameters, err := k.GetConsumerPowerShapingParameters(ctx, consumerId) + if err != nil { + return nil, status.Error(codes.Internal, fmt.Sprintf("failed to get power shaping params: %s", err)) + } + if powerShapingParameters.Top_N > 0 { + activeValidators, err := k.GetLastProviderConsensusActiveValidators(ctx) + if err != nil { + return nil, status.Error(codes.Internal, fmt.Sprintf("failed to get active validators: %s", err)) + } - var rate math.LegacyDec - consumerRate, found := k.GetConsumerCommissionRate(ctx, consumerChainID, types.NewProviderConsAddress(consAddr)) - if found { - rate = consumerRate - } else { - v, err := k.stakingKeeper.GetValidatorByConsAddr(ctx, consAddr) + minPower, err = k.ComputeMinPowerInTopN(ctx, activeValidators, powerShapingParameters.Top_N) if err != nil { - return nil, status.Error(codes.InvalidArgument, fmt.Sprintf("unknown validator: %s", consAddr.String())) + return nil, status.Error(codes.Internal, fmt.Sprintf("failed to compute min power to opt in for chain %s: %s", consumerId, err)) } - rate = v.Commission.Rate + } + + consumerValSet = k.ComputeNextValidators(ctx, consumerId, bondedValidators, powerShapingParameters, minPower) + + // sort the address of the validators by ascending lexical order as they were persisted to the store + sort.Slice(consumerValSet, func(i, j int) bool { + return bytes.Compare( + consumerValSet[i].ProviderConsAddr, + consumerValSet[j].ProviderConsAddr, + ) == -1 + }) + } + + var validators []*types.QueryConsumerValidatorsValidator + for _, consumerVal := range consumerValSet { + provAddr := types.ProviderConsAddress{Address: consumerVal.ProviderConsAddr} + consAddr := provAddr.ToSdkConsAddr() + + providerVal, err := k.stakingKeeper.GetValidatorByConsAddr(ctx, consAddr) + if err != nil { + k.Logger(ctx).Error("cannot find consensus address for provider address:%s", provAddr.String()) + continue + } + + hasToValidate, err := k.hasToValidate(ctx, provAddr, consumerId) + if err != nil { + k.Logger(ctx).Error("cannot define if validator %s has to validate for consumer %s for current epoch", + provAddr.String(), consumerId) + continue + } + + consumerRate, found := k.GetConsumerCommissionRate(ctx, consumerId, types.NewProviderConsAddress(consAddr)) + if !found { + consumerRate = providerVal.Commission.Rate } validators = append(validators, &types.QueryConsumerValidatorsValidator{ - ProviderAddress: sdk.ConsAddress(v.ProviderConsAddr).String(), - ConsumerKey: v.PublicKey, - Power: v.Power, - Rate: rate, + ProviderAddress: sdk.ConsAddress(consumerVal.ProviderConsAddr).String(), + ConsumerKey: consumerVal.PublicKey, + ConsumerPower: consumerVal.Power, + ConsumerCommissionRate: consumerRate, + Description: providerVal.Description, + ProviderOperatorAddress: providerVal.OperatorAddress, + Jailed: providerVal.Jailed, + Status: providerVal.Status, + ProviderTokens: providerVal.Tokens, + ProviderCommissionRate: providerVal.Commission.Rate, + ProviderPower: providerVal.GetConsensusPower(k.stakingKeeper.PowerReduction(ctx)), + ValidatesCurrentEpoch: hasToValidate, }) } return &types.QueryConsumerValidatorsResponse{ @@ -392,14 +424,16 @@ func (k Keeper) QueryConsumerChainsValidatorHasToValidate(goCtx context.Context, // get all the consumer chains for which the validator is either already // opted-in, currently a consumer validator or if its voting power is within the TopN validators consumersToValidate := []string{} - for _, consumerChainID := range k.GetAllRegisteredConsumerChainIDs(ctx) { - if hasToValidate, err := k.hasToValidate(ctx, provAddr, consumerChainID); err == nil && hasToValidate { - consumersToValidate = append(consumersToValidate, consumerChainID) + // To avoid large iterations over all the consumer IDs, iterate only over + // chains with an IBC client created. + for _, consumerId := range k.GetAllConsumersWithIBCClients(ctx) { + if hasToValidate, err := k.hasToValidate(ctx, provAddr, consumerId); err == nil && hasToValidate { + consumersToValidate = append(consumersToValidate, consumerId) } } return &types.QueryConsumerChainsValidatorHasToValidateResponse{ - ConsumerChainIds: consumersToValidate, + ConsumerIds: consumersToValidate, }, nil } @@ -407,10 +441,10 @@ func (k Keeper) QueryConsumerChainsValidatorHasToValidate(goCtx context.Context, func (k Keeper) hasToValidate( ctx sdk.Context, provAddr types.ProviderConsAddress, - chainID string, + consumerId string, ) (bool, error) { // if the validator was sent as part of the packet in the last epoch, it has to validate - if k.IsConsumerValidator(ctx, chainID, provAddr) { + if k.IsConsumerValidator(ctx, consumerId, provAddr) { return true, nil } @@ -419,29 +453,33 @@ func (k Keeper) hasToValidate( if err != nil { return false, nil } - if topN, found := k.GetTopN(ctx, chainID); found && topN > 0 { - // in a Top-N chain, we automatically opt in all validators that belong to the top N - minPower, found := k.GetMinimumPowerInTopN(ctx, chainID) - if found { - k.OptInTopNValidators(ctx, chainID, activeValidators, minPower) - } else { - k.Logger(ctx).Error("did not find min power in top N for chain", "chain", chainID) - } - } - // if the validator is opted in and belongs to the validators of the next epoch, then if nothing changes - // the validator would have to validate in the next epoch - if k.IsOptedIn(ctx, chainID, provAddr) { - lastVals, err := k.GetLastBondedValidators(ctx) + minPowerToOptIn := int64(0) + // If the consumer is TopN compute the minimum power + powerShapingParameters, err := k.GetConsumerPowerShapingParameters(ctx, consumerId) + if err != nil { + return false, err + } + if powerShapingParameters.Top_N > 0 { + // compute the minimum power to opt-in since the one in the state is stale + // Note that the effective min power will be computed at the end of the epoch + minPowerToOptIn, err = k.ComputeMinPowerInTopN(ctx, activeValidators, powerShapingParameters.Top_N) if err != nil { return false, err } - nextValidators := k.ComputeNextValidators(ctx, chainID, lastVals) - for _, v := range nextValidators { - consAddr := sdk.ConsAddress(v.ProviderConsAddr) - if provAddr.ToSdkConsAddr().Equals(consAddr) { - return true, nil - } + } + + // if the validator belongs to the validators of the next epoch, then if nothing changes + // the validator would have to validate in the next epoch + lastVals, err := k.GetLastBondedValidators(ctx) + if err != nil { + return false, err + } + nextValidators := k.ComputeNextValidators(ctx, consumerId, lastVals, powerShapingParameters, minPowerToOptIn) + for _, v := range nextValidators { + consAddr := sdk.ConsAddress(v.ProviderConsAddr) + if provAddr.ToSdkConsAddr().Equals(consAddr) { + return true, nil } } @@ -452,12 +490,12 @@ func (k Keeper) hasToValidate( // validator charges on a given consumer chain func (k Keeper) QueryValidatorConsumerCommissionRate(goCtx context.Context, req *types.QueryValidatorConsumerCommissionRateRequest) (*types.QueryValidatorConsumerCommissionRateResponse, error) { if req == nil { - return nil, status.Error(codes.InvalidArgument, "empty request") + return nil, status.Errorf(codes.InvalidArgument, "empty request") } - consumerChainID := req.ChainId - if consumerChainID == "" { - return nil, status.Error(codes.InvalidArgument, "empty chainId") + consumerId := req.ConsumerId + if err := types.ValidateConsumerId(consumerId); err != nil { + return nil, status.Error(codes.InvalidArgument, errorsmod.Wrap(types.ErrInvalidConsumerId, consumerId).Error()) } consAddr, err := sdk.ConsAddressFromBech32(req.ProviderAddress) @@ -467,15 +505,15 @@ func (k Keeper) QueryValidatorConsumerCommissionRate(goCtx context.Context, req ctx := sdk.UnwrapSDKContext(goCtx) - if !k.IsConsumerProposedOrRegistered(ctx, consumerChainID) { - return nil, status.Error(codes.InvalidArgument, fmt.Sprintf("unknown consumer chain: %s", consumerChainID)) + if !k.IsConsumerActive(ctx, consumerId) { + return nil, status.Error(codes.InvalidArgument, fmt.Sprintf("unknown consumer chain: %s", consumerId)) } res := &types.QueryValidatorConsumerCommissionRateResponse{} // Check if the validator has a commission rate set for the consumer chain, // otherwise use the commission rate from the validator staking module struct - consumerRate, found := k.GetConsumerCommissionRate(ctx, consumerChainID, types.NewProviderConsAddress(consAddr)) + consumerRate, found := k.GetConsumerCommissionRate(ctx, consumerId, types.NewProviderConsAddress(consAddr)) if found { res.Rate = consumerRate } else { @@ -498,3 +536,61 @@ func (k Keeper) QueryBlocksUntilNextEpoch(goCtx context.Context, req *types.Quer return &types.QueryBlocksUntilNextEpochResponse{BlocksUntilNextEpoch: uint64(blocksUntilNextEpoch)}, nil } + +// QueryConsumerIdFromClientId returns the consumer id of the chain associated with this client id +func (k Keeper) QueryConsumerIdFromClientId(goCtx context.Context, req *types.QueryConsumerIdFromClientIdRequest) (*types.QueryConsumerIdFromClientIdResponse, error) { + ctx := sdk.UnwrapSDKContext(goCtx) + + consumerId, found := k.GetClientIdToConsumerId(ctx, req.ClientId) + if !found { + return nil, status.Error(codes.InvalidArgument, fmt.Sprintf("no known consumer chain for this client id: %s", req.ClientId)) + } + + return &types.QueryConsumerIdFromClientIdResponse{ConsumerId: consumerId}, nil +} + +// QueryConsumerChain returns the consumer chain associated with the consumer id +func (k Keeper) QueryConsumerChain(goCtx context.Context, req *types.QueryConsumerChainRequest) (*types.QueryConsumerChainResponse, error) { + if req == nil { + return nil, status.Errorf(codes.InvalidArgument, "empty request") + } + + consumerId := req.ConsumerId + if err := types.ValidateConsumerId(consumerId); err != nil { + return nil, status.Error(codes.InvalidArgument, errorsmod.Wrap(types.ErrInvalidConsumerId, consumerId).Error()) + } + ctx := sdk.UnwrapSDKContext(goCtx) + + chainId, err := k.GetConsumerChainId(ctx, consumerId) + if err != nil { + return nil, status.Errorf(codes.InvalidArgument, "cannot retrieve chain id for consumer id: %s", consumerId) + } + + ownerAddress, err := k.GetConsumerOwnerAddress(ctx, consumerId) + if err != nil { + return nil, status.Errorf(codes.InvalidArgument, "cannot retrieve owner address for consumer id: %s", consumerId) + } + + phase := k.GetConsumerPhase(ctx, consumerId) + if phase == types.CONSUMER_PHASE_UNSPECIFIED { + return nil, status.Errorf(codes.InvalidArgument, "cannot retrieve phase for consumer id: %s", consumerId) + } + + metadata, err := k.GetConsumerMetadata(ctx, consumerId) + if err != nil { + return nil, status.Errorf(codes.InvalidArgument, "cannot retrieve metadata for consumer id: %s", consumerId) + } + + // neither the init nor the power shaping params are mandatory for consumers + initParams, _ := k.GetConsumerInitializationParameters(ctx, consumerId) + powerParams, _ := k.GetConsumerPowerShapingParameters(ctx, consumerId) + + return &types.QueryConsumerChainResponse{ + ChainId: chainId, + OwnerAddress: ownerAddress, + Phase: phase.String(), + Metadata: metadata, + InitParams: &initParams, + PowerShapingParams: &powerParams, + }, nil +} diff --git a/x/ccv/provider/keeper/grpc_query_test.go b/x/ccv/provider/keeper/grpc_query_test.go index d0ba94174a..3ba2cc9059 100644 --- a/x/ccv/provider/keeper/grpc_query_test.go +++ b/x/ccv/provider/keeper/grpc_query_test.go @@ -1,7 +1,10 @@ package keeper_test import ( + "bytes" "fmt" + "sort" + "strconv" "testing" "github.com/golang/mock/gomock" @@ -16,12 +19,13 @@ import ( cryptotestutil "github.com/cosmos/interchain-security/v5/testutil/crypto" testkeeper "github.com/cosmos/interchain-security/v5/testutil/keeper" + "github.com/cosmos/interchain-security/v5/x/ccv/provider/keeper" "github.com/cosmos/interchain-security/v5/x/ccv/provider/types" ccvtypes "github.com/cosmos/interchain-security/v5/x/ccv/types" ) -func TestQueryAllPairsValConAddrByConsumerChainID(t *testing.T) { - chainID := consumer +func TestQueryAllPairsValConsAddrByConsumer(t *testing.T) { + consumerId := "0" providerConsAddress, err := sdk.ConsAddressFromBech32("cosmosvalcons1wpex7anfv3jhystyv3eq20r35a") require.NoError(t, err) @@ -34,28 +38,27 @@ func TestQueryAllPairsValConAddrByConsumerChainID(t *testing.T) { pk, ctx, ctrl, _ := testkeeper.GetProviderKeeperAndCtx(t, testkeeper.NewInMemKeeperParams(t)) defer ctrl.Finish() - pk.SetValidatorConsumerPubKey(ctx, chainID, providerAddr, consumerKey) + pk.SetValidatorConsumerPubKey(ctx, consumerId, providerAddr, consumerKey) - consumerPubKey, found := pk.GetValidatorConsumerPubKey(ctx, chainID, providerAddr) + consumerPubKey, found := pk.GetValidatorConsumerPubKey(ctx, consumerId, providerAddr) require.True(t, found, "consumer pubkey not found") require.NotEmpty(t, consumerPubKey, "consumer pubkey is empty") require.Equal(t, consumerPubKey, consumerKey) // Request is nil - _, err = pk.QueryAllPairsValConAddrByConsumerChainID(ctx, nil) + _, err = pk.QueryAllPairsValConsAddrByConsumer(ctx, nil) require.Error(t, err) - // Request with chainId is empty - _, err = pk.QueryAllPairsValConAddrByConsumerChainID(ctx, &types.QueryAllPairsValConAddrByConsumerChainIDRequest{}) + // Request with empty consumer id + _, err = pk.QueryAllPairsValConsAddrByConsumer(ctx, &types.QueryAllPairsValConsAddrByConsumerRequest{}) require.Error(t, err) - // Request with chainId is invalid - response, err := pk.QueryAllPairsValConAddrByConsumerChainID(ctx, &types.QueryAllPairsValConAddrByConsumerChainIDRequest{ChainId: "invalidChainId"}) - require.NoError(t, err) - require.Equal(t, []*types.PairValConAddrProviderAndConsumer{}, response.PairValConAddr) + // Request with invalid consumer id + _, err = pk.QueryAllPairsValConsAddrByConsumer(ctx, &types.QueryAllPairsValConsAddrByConsumerRequest{ConsumerId: "invalidConsumerId"}) + require.Error(t, err) // Request is valid - response, err = pk.QueryAllPairsValConAddrByConsumerChainID(ctx, &types.QueryAllPairsValConAddrByConsumerChainIDRequest{ChainId: chainID}) + response, err := pk.QueryAllPairsValConsAddrByConsumer(ctx, &types.QueryAllPairsValConsAddrByConsumerRequest{ConsumerId: consumerId}) require.NoError(t, err) expectedResult := types.PairValConAddrProviderAndConsumer{ @@ -68,20 +71,21 @@ func TestQueryAllPairsValConAddrByConsumerChainID(t *testing.T) { } func TestQueryConsumerChainOptedInValidators(t *testing.T) { - chainID := "chainID" - pk, ctx, ctrl, _ := testkeeper.GetProviderKeeperAndCtx(t, testkeeper.NewInMemKeeperParams(t)) defer ctrl.Finish() + consumerId := "0" + req := types.QueryConsumerChainOptedInValidatorsRequest{ - ChainId: chainID, + ConsumerId: consumerId, } // error returned from not yet proposed or not yet registered chain _, err := pk.QueryConsumerChainOptedInValidators(ctx, &req) require.Error(t, err) - pk.SetProposedConsumerChain(ctx, chainID, 1) + pk.FetchAndIncrementConsumerId(ctx) + pk.SetConsumerPhase(ctx, consumerId, types.CONSUMER_PHASE_INITIALIZED) providerAddr1 := types.NewProviderConsAddress([]byte("providerAddr1")) providerAddr2 := types.NewProviderConsAddress([]byte("providerAddr2")) @@ -89,70 +93,207 @@ func TestQueryConsumerChainOptedInValidators(t *testing.T) { ValidatorsProviderAddresses: []string{providerAddr1.String(), providerAddr2.String()}, } - pk.SetOptedIn(ctx, chainID, providerAddr1) - pk.SetOptedIn(ctx, chainID, providerAddr2) + pk.SetOptedIn(ctx, consumerId, providerAddr1) + pk.SetOptedIn(ctx, consumerId, providerAddr2) res, err := pk.QueryConsumerChainOptedInValidators(ctx, &req) require.NoError(t, err) require.Equal(t, &expectedResponse, res) } func TestQueryConsumerValidators(t *testing.T) { - chainID := "chainID" - pk, ctx, ctrl, mocks := testkeeper.GetProviderKeeperAndCtx(t, testkeeper.NewInMemKeeperParams(t)) defer ctrl.Finish() + consumerId := "0" req := types.QueryConsumerValidatorsRequest{ - ChainId: chainID, + ConsumerId: consumerId, } - // error returned from not-started chain + // error returned from not-existing chain _, err := pk.QueryConsumerValidators(ctx, &req) require.Error(t, err) - providerAddr1 := types.NewProviderConsAddress([]byte("providerAddr1")) - consumerKey1 := cryptotestutil.NewCryptoIdentityFromIntSeed(1).TMProtoCryptoPublicKey() - consumerValidator1 := types.ConsensusValidator{ProviderConsAddr: providerAddr1.ToSdkConsAddr(), Power: 1, PublicKey: &consumerKey1} - expectedCommissionRate1 := math.LegacyMustNewDecFromStr("0.123") - pk.SetConsumerCommissionRate(ctx, chainID, providerAddr1, expectedCommissionRate1) + // set the consumer to the "registered" phase + pk.SetConsumerPhase(ctx, consumerId, types.CONSUMER_PHASE_REGISTERED) - providerAddr2 := types.NewProviderConsAddress([]byte("providerAddr2")) - consumerKey2 := cryptotestutil.NewCryptoIdentityFromIntSeed(2).TMProtoCryptoPublicKey() - consumerValidator2 := types.ConsensusValidator{ProviderConsAddr: providerAddr2.ToSdkConsAddr(), Power: 2, PublicKey: &consumerKey2} - expectedCommissionRate2 := math.LegacyMustNewDecFromStr("0.123") - pk.SetConsumerCommissionRate(ctx, chainID, providerAddr2, expectedCommissionRate2) + // set power shaping params + err = pk.SetConsumerPowerShapingParameters(ctx, consumerId, types.PowerShapingParameters{}) + require.NoError(t, err) + + // expect empty valset + testkeeper.SetupMocksForLastBondedValidatorsExpectation(mocks.MockStakingKeeper, 0, []stakingtypes.Validator{}, 1) // -1 to allow the calls "AnyTimes" + res, err := pk.QueryConsumerValidators(ctx, &req) + require.NoError(t, err) + require.Len(t, res.Validators, 0) + + // create bonded validators + val1 := createStakingValidator(ctx, mocks, 1, 1) + pk1, _ := val1.CmtConsPublicKey() + valConsAddr1, _ := val1.GetConsAddr() + providerAddr1 := types.NewProviderConsAddress(valConsAddr1) + consumerValidator1 := types.ConsensusValidator{ProviderConsAddr: providerAddr1.ToSdkConsAddr(), Power: 1, PublicKey: &pk1} + val1.Tokens = sdk.TokensFromConsensusPower(1, sdk.DefaultPowerReduction) + val1.Description = stakingtypes.Description{Moniker: "ConsumerValidator1"} + val1.Commission.Rate = math.LegacyMustNewDecFromStr("0.123") + + val2 := createStakingValidator(ctx, mocks, 2, 2) + pk2, _ := val2.CmtConsPublicKey() + valConsAddr2, _ := val2.GetConsAddr() + providerAddr2 := types.NewProviderConsAddress(valConsAddr2) + consumerValidator2 := types.ConsensusValidator{ProviderConsAddr: providerAddr2.ToSdkConsAddr(), Power: 2, PublicKey: &pk2} + val2.Tokens = sdk.TokensFromConsensusPower(2, sdk.DefaultPowerReduction) + val2.Description = stakingtypes.Description{Moniker: "ConsumerValidator2"} + val2.Commission.Rate = math.LegacyMustNewDecFromStr("0.456") + + val3 := createStakingValidator(ctx, mocks, 3, 3) + pk3, _ := val3.CmtConsPublicKey() + valConsAddr3, _ := val3.GetConsAddr() + providerAddr3 := types.NewProviderConsAddress(valConsAddr3) + consumerValidator3 := types.ConsensusValidator{ProviderConsAddr: providerAddr3.ToSdkConsAddr(), Power: 3, PublicKey: &pk3} + val3.Tokens = sdk.TokensFromConsensusPower(3, sdk.DefaultPowerReduction) + val3.Description = stakingtypes.Description{Moniker: "ConsumerValidator3"} + + mocks.MockStakingKeeper.EXPECT().GetValidatorByConsAddr(ctx, valConsAddr1).Return(val1, nil).AnyTimes() + mocks.MockStakingKeeper.EXPECT().GetValidatorByConsAddr(ctx, valConsAddr2).Return(val2, nil).AnyTimes() + mocks.MockStakingKeeper.EXPECT().GetValidatorByConsAddr(ctx, valConsAddr3).Return(val3, nil).AnyTimes() + mocks.MockStakingKeeper.EXPECT().PowerReduction(ctx).Return(sdk.DefaultPowerReduction).AnyTimes() + testkeeper.SetupMocksForLastBondedValidatorsExpectation(mocks.MockStakingKeeper, 2, []stakingtypes.Validator{val1, val2}, -1) // -1 to allow the calls "AnyTimes" + + // set max provider consensus vals to include all validators + params := pk.GetParams(ctx) + params.MaxProviderConsensusValidators = 3 + pk.SetParams(ctx, params) - expectedResponse := types.QueryConsumerValidatorsResponse{ + // expect no validator to be returned since the consumer is Opt-In + res, err = pk.QueryConsumerValidators(ctx, &req) + require.NoError(t, err) + require.Len(t, res.Validators, 0) + + // opt in one validator + pk.SetOptedIn(ctx, consumerId, providerAddr1) + + // set a consumer commission rate for val1 + val1ConsComRate := math.LegacyMustNewDecFromStr("0.789") + pk.SetConsumerCommissionRate(ctx, consumerId, providerAddr1, val1ConsComRate) + + // expect opted-in validator + res, err = pk.QueryConsumerValidators(ctx, &req) + require.NoError(t, err) + require.Len(t, res.Validators, 1) + require.Equal(t, res.Validators[0].ProviderAddress, providerAddr1.String()) + + // update consumer TopN param + err = pk.SetConsumerPowerShapingParameters(ctx, consumerId, types.PowerShapingParameters{Top_N: 50}) + require.NoError(t, err) + + // expect both opted-in and topN validator + expRes := types.QueryConsumerValidatorsResponse{ Validators: []*types.QueryConsumerValidatorsValidator{ - {ProviderAddress: providerAddr1.String(), ConsumerKey: &consumerKey1, Power: 1, Rate: expectedCommissionRate1}, - {ProviderAddress: providerAddr2.String(), ConsumerKey: &consumerKey2, Power: 2, Rate: expectedCommissionRate2}, + { + ProviderAddress: providerAddr1.String(), + ConsumerKey: &pk1, + ConsumerPower: 1, + ConsumerCommissionRate: val1ConsComRate, + Description: val1.Description, + ProviderOperatorAddress: val1.OperatorAddress, + Jailed: val1.Jailed, + Status: val1.Status, + ProviderTokens: val1.Tokens, + ProviderCommissionRate: val1.Commission.Rate, + ProviderPower: 1, + ValidatesCurrentEpoch: true, + }, + { + ProviderAddress: providerAddr2.String(), + ConsumerKey: &pk2, + ConsumerPower: 2, + ConsumerCommissionRate: val2.Commission.Rate, + Description: val2.Description, + ProviderOperatorAddress: val2.OperatorAddress, + Jailed: val2.Jailed, + Status: val2.Status, + ProviderTokens: val2.Tokens, + ProviderCommissionRate: val2.Commission.Rate, + ProviderPower: 2, + ValidatesCurrentEpoch: true, + }, }, } - // set up the client id so the chain looks like it "started" - pk.SetConsumerClientId(ctx, chainID, "clientID") - pk.SetConsumerValSet(ctx, chainID, []types.ConsensusValidator{consumerValidator1, consumerValidator2}) + // sort the address of the validators by ascending lexical order as they were persisted to the store + sort.Slice(expRes.Validators, func(i, j int) bool { + return bytes.Compare( + expRes.Validators[i].ConsumerKey.GetEd25519(), + expRes.Validators[j].ConsumerKey.GetEd25519(), + ) == -1 + }) - res, err := pk.QueryConsumerValidators(ctx, &req) + res, err = pk.QueryConsumerValidators(ctx, &req) require.NoError(t, err) - require.Equal(t, &expectedResponse, res) + require.Equal(t, &expRes, res) + + // expect same result when consumer is in "initialized" phase + pk.SetConsumerPhase(ctx, consumerId, types.CONSUMER_PHASE_INITIALIZED) + res, err = pk.QueryConsumerValidators(ctx, &req) + require.NoError(t, err) + require.Equal(t, &expRes, res) + + // set consumer to the "launched" phase + pk.SetConsumerPhase(ctx, consumerId, types.CONSUMER_PHASE_LAUNCHED) + + // expect an empty consumer valset + // since neither QueueVSCPackets or MakeConsumerGenesis was called at this point + res, err = pk.QueryConsumerValidators(ctx, &req) + require.NoError(t, err) + require.Empty(t, res) + + // set consumer valset + pk.SetConsumerValSet(ctx, consumerId, []types.ConsensusValidator{ + consumerValidator1, + consumerValidator2, + consumerValidator3, + }) + + expRes.Validators = append(expRes.Validators, &types.QueryConsumerValidatorsValidator{ + ProviderAddress: providerAddr3.String(), + ConsumerKey: &pk3, + ConsumerPower: 3, + ConsumerCommissionRate: val3.Commission.Rate, + Description: val3.Description, + ProviderOperatorAddress: val3.OperatorAddress, + Jailed: val3.Jailed, + Status: val3.Status, + ProviderTokens: val3.Tokens, + ProviderCommissionRate: val3.Commission.Rate, + ProviderPower: 3, + ValidatesCurrentEpoch: true, + }) + + // sort the address of the validators by ascending lexical order as they were persisted to the store + sort.Slice(expRes.Validators, func(i, j int) bool { + return bytes.Compare( + expRes.Validators[i].ConsumerKey.GetEd25519(), + expRes.Validators[j].ConsumerKey.GetEd25519(), + ) == -1 + }) + + res, err = pk.QueryConsumerValidators(ctx, &req) + require.NoError(t, err) + require.Equal(t, &expRes, res) // validator with no set consumer commission rate - pk.DeleteConsumerCommissionRate(ctx, chainID, providerAddr1) - expectedCommissionRate := math.LegacyMustNewDecFromStr("0.456") + pk.DeleteConsumerCommissionRate(ctx, consumerId, providerAddr1) // because no consumer commission rate is set, the validator's set commission rate on the provider is used - val := stakingtypes.Validator{Commission: stakingtypes.Commission{CommissionRates: stakingtypes.CommissionRates{Rate: expectedCommissionRate}}} - mocks.MockStakingKeeper.EXPECT().GetValidatorByConsAddr( - ctx, providerAddr1.ToSdkConsAddr()).Return(val, nil).Times(1) - res, _ = pk.QueryConsumerValidators(ctx, &req) - require.Equal(t, expectedCommissionRate, res.Validators[0].Rate) + res, err = pk.QueryConsumerValidators(ctx, &req) + require.NoError(t, err) + require.Equal(t, val1.Commission.Rate, res.Validators[0].ConsumerCommissionRate) } func TestQueryConsumerChainsValidatorHasToValidate(t *testing.T) { pk, ctx, ctrl, mocks := testkeeper.GetProviderKeeperAndCtx(t, testkeeper.NewInMemKeeperParams(t)) defer ctrl.Finish() - val := createStakingValidator(ctx, mocks, 1, 1, 1) + val := createStakingValidator(ctx, mocks, 1, 1) valConsAddr, _ := val.GetConsAddr() providerAddr := types.NewProviderConsAddress(valConsAddr) mocks.MockStakingKeeper.EXPECT().GetValidatorByConsAddr(ctx, valConsAddr).Return(val, nil).AnyTimes() @@ -162,14 +303,33 @@ func TestQueryConsumerChainsValidatorHasToValidate(t *testing.T) { ProviderAddress: providerAddr.String(), } + consumerNum := 4 + consumerIds := make([]string, consumerNum) + + msgServer := keeper.NewMsgServerImpl(&pk) + // set up some consumer chains - consumerChains := []string{"chain1", "chain2", "chain3", "chain4"} - for _, cc := range consumerChains { - pk.SetConsumerClientId(ctx, cc, "clientID") + for i := 0; i < consumerNum; i++ { + chainID := "consumer-" + strconv.Itoa(i) + metadata := types.ConsumerMetadata{Name: chainID} + msg := types.MsgCreateConsumer{ + ChainId: chainID, + Metadata: metadata, + } + resp, err := msgServer.CreateConsumer(ctx, &msg) + require.NoError(t, err) + consumerId := resp.ConsumerId + + // set a consumer client id, so that `GetAllConsumersWithIBCClients` is non-empty + clientID := "client-" + strconv.Itoa(i) + pk.SetConsumerClientId(ctx, consumerId, clientID) + + pk.SetConsumerPhase(ctx, consumerId, types.CONSUMER_PHASE_LAUNCHED) + consumerIds[i] = consumerId } - // set `providerAddr` as a consumer validator on "chain1" - pk.SetConsumerValidator(ctx, "chain1", types.ConsensusValidator{ + // set `providerAddr` as a consumer validator on first consumer chain + pk.SetConsumerValidator(ctx, consumerIds[0], types.ConsensusValidator{ ProviderConsAddr: providerAddr.ToSdkConsAddr(), Power: 1, PublicKey: &crypto.PublicKey{ @@ -179,32 +339,33 @@ func TestQueryConsumerChainsValidatorHasToValidate(t *testing.T) { }, }) - // set `providerAddr` as an opted-in validator on "chain3" - pk.SetOptedIn(ctx, "chain3", providerAddr) + // set `providerAddr` as an opted-in validator on third consumer chain + pk.SetOptedIn(ctx, consumerIds[2], providerAddr) // set max provider consensus vals to include all validators params := pk.GetParams(ctx) params.MaxProviderConsensusValidators = 3 pk.SetParams(ctx, params) - // `providerAddr` has to validate "chain1" because it is a consumer validator in this chain, as well as "chain3" - // because it opted in, in "chain3" and `providerAddr` belongs to the bonded validators - expectedChains := []string{"chain1", "chain3"} + // `providerAddr` has to validate + // - first consumer because it is a consumer validator in this chain, + // - third consumer because it opted in + expectedChains := []string{consumerIds[0], consumerIds[2]} res, err := pk.QueryConsumerChainsValidatorHasToValidate(ctx, &req) require.NoError(t, err) - require.Equal(t, expectedChains, res.ConsumerChainIds) + require.Equal(t, expectedChains, res.ConsumerIds) } func TestQueryValidatorConsumerCommissionRate(t *testing.T) { - chainID := "chainID" + consumerId := "0" pk, ctx, ctrl, mocks := testkeeper.GetProviderKeeperAndCtx(t, testkeeper.NewInMemKeeperParams(t)) defer ctrl.Finish() providerAddr := types.NewProviderConsAddress([]byte("providerAddr")) req := types.QueryValidatorConsumerCommissionRateRequest{ - ChainId: chainID, + ConsumerId: consumerId, ProviderAddress: providerAddr.String(), } @@ -212,15 +373,17 @@ func TestQueryValidatorConsumerCommissionRate(t *testing.T) { _, err := pk.QueryValidatorConsumerCommissionRate(ctx, &req) require.Error(t, err) - pk.SetProposedConsumerChain(ctx, chainID, 1) + pk.FetchAndIncrementConsumerId(ctx) + pk.SetConsumerPhase(ctx, consumerId, types.CONSUMER_PHASE_INITIALIZED) + // validator with set consumer commission rate expectedCommissionRate := math.LegacyMustNewDecFromStr("0.123") - pk.SetConsumerCommissionRate(ctx, chainID, providerAddr, expectedCommissionRate) + pk.SetConsumerCommissionRate(ctx, consumerId, providerAddr, expectedCommissionRate) res, _ := pk.QueryValidatorConsumerCommissionRate(ctx, &req) require.Equal(t, expectedCommissionRate, res.Rate) // validator with no set consumer commission rate - pk.DeleteConsumerCommissionRate(ctx, chainID, providerAddr) + pk.DeleteConsumerCommissionRate(ctx, consumerId, providerAddr) expectedCommissionRate = math.LegacyMustNewDecFromStr("0.456") // because no consumer commission rate is set, the validator's set commission rate on the provider is used @@ -236,6 +399,8 @@ func TestGetConsumerChain(t *testing.T) { pk, ctx, ctrl, mocks := testkeeper.GetProviderKeeperAndCtx(t, testkeeper.NewInMemKeeperParams(t)) defer ctrl.Finish() + consumerIDs := []string{"1", "23", "345", "6789"} + chainIDs := []string{"chain-1", "chain-2", "chain-3", "chain-4"} // mock the validator set @@ -289,22 +454,28 @@ func TestGetConsumerChain(t *testing.T) { math.NewInt(300), } + metadataLists := []types.ConsumerMetadata{} + expectedGetAllOrder := []types.Chain{} - for i, chainID := range chainIDs { - clientID := fmt.Sprintf("client-%d", len(chainIDs)-i) + for i, consumerID := range consumerIDs { + pk.SetConsumerChainId(ctx, consumerID, chainIDs[i]) + clientID := fmt.Sprintf("client-%d", len(consumerID)-i) topN := topNs[i] - pk.SetConsumerClientId(ctx, chainID, clientID) - pk.SetTopN(ctx, chainID, topN) - pk.SetValidatorSetCap(ctx, chainID, validatorSetCaps[i]) - pk.SetValidatorsPowerCap(ctx, chainID, validatorPowerCaps[i]) - pk.SetMinimumPowerInTopN(ctx, chainID, expectedMinPowerInTopNs[i]) - pk.SetInactiveValidatorsAllowed(ctx, chainID, allowInactiveVals[i]) - pk.SetMinStake(ctx, chainID, minStakes[i].Uint64()) + pk.SetConsumerClientId(ctx, consumerID, clientID) + err := pk.SetConsumerPowerShapingParameters(ctx, consumerID, types.PowerShapingParameters{ + Top_N: topN, + ValidatorSetCap: validatorSetCaps[i], + ValidatorsPowerCap: validatorPowerCaps[i], + MinStake: minStakes[i].Uint64(), + AllowInactiveVals: allowInactiveVals[i], + }) + require.NoError(t, err) + pk.SetMinimumPowerInTopN(ctx, consumerID, expectedMinPowerInTopNs[i]) for _, addr := range allowlists[i] { - pk.SetAllowlist(ctx, chainID, addr) + pk.SetAllowlist(ctx, consumerID, addr) } for _, addr := range denylists[i] { - pk.SetDenylist(ctx, chainID, addr) + pk.SetDenylist(ctx, consumerID, addr) } strAllowlist := make([]string, len(allowlists[i])) for j, addr := range allowlists[i] { @@ -316,9 +487,15 @@ func TestGetConsumerChain(t *testing.T) { strDenylist[j] = addr.String() } + metadataLists = append(metadataLists, types.ConsumerMetadata{Name: chainIDs[i]}) + pk.SetConsumerMetadata(ctx, consumerID, metadataLists[i]) + + phase := types.ConsumerPhase(int32(i + 1)) + pk.SetConsumerPhase(ctx, consumerID, phase) + expectedGetAllOrder = append(expectedGetAllOrder, types.Chain{ - ChainId: chainID, + ChainId: chainIDs[i], ClientId: clientID, Top_N: topN, MinPowerInTop_N: expectedMinPowerInTopNs[i], @@ -326,14 +503,229 @@ func TestGetConsumerChain(t *testing.T) { ValidatorsPowerCap: validatorPowerCaps[i], Allowlist: strAllowlist, Denylist: strDenylist, + Phase: phase.String(), + Metadata: metadataLists[i], AllowInactiveVals: allowInactiveVals[i], MinStake: minStakes[i].Uint64(), + ConsumerId: consumerIDs[i], }) } - for i, chainID := range pk.GetAllRegisteredAndProposedChainIDs(ctx) { - c, err := pk.GetConsumerChain(ctx, chainID) + for i, cId := range consumerIDs { + c, err := pk.GetConsumerChain(ctx, cId) require.NoError(t, err) require.Equal(t, expectedGetAllOrder[i], c) } } + +func TestQueryConsumerChain(t *testing.T) { + providerKeeper, ctx, ctrl, _ := testkeeper.GetProviderKeeperAndCtx(t, testkeeper.NewInMemKeeperParams(t)) + defer ctrl.Finish() + + consumerId := "0" + chainId := "consumer-1" + + req := types.QueryConsumerChainRequest{ + ConsumerId: consumerId, + } + + // expect error when consumer isn't associated with a chain id + _, err := providerKeeper.QueryConsumerChain(ctx, &req) + require.Error(t, err) + + providerKeeper.SetConsumerChainId(ctx, consumerId, chainId) + + // expect error when consumer doesn't have an owner address set + _, err = providerKeeper.QueryConsumerChain(ctx, &req) + require.Error(t, err) + + providerKeeper.SetConsumerOwnerAddress(ctx, consumerId, providerKeeper.GetAuthority()) + + // expect error when consumer doesn't have a valid phase + _, err = providerKeeper.QueryConsumerChain(ctx, &req) + require.Error(t, err) + + providerKeeper.SetConsumerPhase(ctx, consumerId, types.CONSUMER_PHASE_REGISTERED) + + // expect error when consumer doesn't have metadata + _, err = providerKeeper.QueryConsumerChain(ctx, &req) + require.Error(t, err) + + err = providerKeeper.SetConsumerMetadata(ctx, consumerId, types.ConsumerMetadata{Name: chainId}) + require.NoError(t, err) + + expRes := types.QueryConsumerChainResponse{ + ChainId: chainId, + OwnerAddress: providerKeeper.GetAuthority(), + Metadata: types.ConsumerMetadata{Name: chainId}, + Phase: types.CONSUMER_PHASE_REGISTERED.String(), + InitParams: &types.ConsumerInitializationParameters{}, + PowerShapingParams: &types.PowerShapingParameters{}, + } + + // expect no error when neither the consumer init and power shaping params are set + res, err := providerKeeper.QueryConsumerChain(ctx, &req) + require.NoError(t, err) + require.Equal(t, &expRes, res) + + err = providerKeeper.SetConsumerInitializationParameters( + ctx, + consumerId, + types.ConsumerInitializationParameters{SpawnTime: ctx.BlockTime()}, + ) + require.NoError(t, err) + + err = providerKeeper.SetConsumerPowerShapingParameters( + ctx, + consumerId, + types.PowerShapingParameters{Top_N: uint32(50)}, + ) + require.NoError(t, err) + + expRes.InitParams = &types.ConsumerInitializationParameters{SpawnTime: ctx.BlockTime()} + expRes.PowerShapingParams = &types.PowerShapingParameters{Top_N: uint32(50)} + + // expect no error + res, err = providerKeeper.QueryConsumerChain(ctx, &req) + require.NoError(t, err) + require.Equal(t, &expRes, res) +} + +func TestQueryConsumerIdFromClientId(t *testing.T) { + providerKeeper, ctx, ctrl, _ := testkeeper.GetProviderKeeperAndCtx(t, testkeeper.NewInMemKeeperParams(t)) + defer ctrl.Finish() + + _, err := providerKeeper.QueryConsumerIdFromClientId(ctx, &types.QueryConsumerIdFromClientIdRequest{ClientId: "clientId"}) + require.Error(t, err) + require.ErrorContains(t, err, "no known consumer chain") + + expectedConsumerId := "consumerId" + providerKeeper.SetConsumerClientId(ctx, expectedConsumerId, "clientId") + + res, err := providerKeeper.QueryConsumerIdFromClientId(ctx, &types.QueryConsumerIdFromClientIdRequest{ClientId: "clientId"}) + require.NoError(t, err) + require.Equal(t, expectedConsumerId, res.ConsumerId) +} + +func TestQueryConsumerChains(t *testing.T) { + pk, ctx, ctrl, _ := testkeeper.GetProviderKeeperAndCtx(t, testkeeper.NewInMemKeeperParams(t)) + defer ctrl.Finish() + + consumerNum := 4 + consumerIds := make([]string, consumerNum) + consumers := make([]*types.Chain, consumerNum) + + // expect no error and returned chains + res, err := pk.QueryConsumerChains(ctx, &types.QueryConsumerChainsRequest{}) + require.NoError(t, err) + require.Len(t, res.Chains, 0) + + msgServer := keeper.NewMsgServerImpl(&pk) + + phases := []types.ConsumerPhase{ + types.CONSUMER_PHASE_REGISTERED, + types.CONSUMER_PHASE_INITIALIZED, + types.CONSUMER_PHASE_LAUNCHED, + types.CONSUMER_PHASE_STOPPED, + } + + // create four consumer chains in different phase + for i := 0; i < consumerNum; i++ { + chainID := "consumer-" + strconv.Itoa(i) + metadata := types.ConsumerMetadata{Name: chainID} + msg := types.MsgCreateConsumer{ + ChainId: chainID, + Metadata: metadata, + } + resp, err := msgServer.CreateConsumer(ctx, &msg) + require.NoError(t, err) + consumerId := resp.ConsumerId + + pk.SetConsumerPhase(ctx, consumerId, phases[i]) + c := types.Chain{ + ChainId: chainID, + MinPowerInTop_N: -1, + ValidatorsPowerCap: 0, + ValidatorSetCap: 0, + Allowlist: []string{}, + Denylist: []string{}, + Phase: phases[i].String(), + Metadata: metadata, + ConsumerId: consumerId, + } + consumerIds[i] = consumerId + consumers[i] = &c + } + + testCases := []struct { + name string + setup func(ctx sdk.Context, pk keeper.Keeper) + phase_filter types.ConsumerPhase + limit int32 + expConsumers []*types.Chain + }{ + { + name: "expect all consumers when phase filter isn't set", + setup: func(ctx sdk.Context, pk keeper.Keeper) {}, + expConsumers: consumers, + }, + { + name: "expect an amount of consumer equal to the limit", + setup: func(ctx sdk.Context, pk keeper.Keeper) {}, + expConsumers: consumers[:3], + limit: int32(3), + }, + { + name: "expect registered consumers when phase filter is set to Registered", + setup: func(ctx sdk.Context, pk keeper.Keeper) { + consumers[0].Phase = types.CONSUMER_PHASE_REGISTERED.String() + pk.SetConsumerPhase(ctx, consumerIds[0], types.CONSUMER_PHASE_REGISTERED) + }, + phase_filter: types.CONSUMER_PHASE_REGISTERED, + expConsumers: consumers[0:1], + }, + { + name: "expect initialized consumers when phase is set to Initialized", + setup: func(ctx sdk.Context, pk keeper.Keeper) { + consumers[1].Phase = types.CONSUMER_PHASE_INITIALIZED.String() + pk.SetConsumerPhase(ctx, consumerIds[1], types.CONSUMER_PHASE_INITIALIZED) + }, + phase_filter: types.CONSUMER_PHASE_INITIALIZED, + expConsumers: consumers[1:2], + }, + { + name: "expect launched consumers when phase is set to Launched", + setup: func(ctx sdk.Context, pk keeper.Keeper) { + consumers[2].Phase = types.CONSUMER_PHASE_LAUNCHED.String() + pk.SetConsumerPhase(ctx, consumerIds[2], types.CONSUMER_PHASE_LAUNCHED) + }, + phase_filter: types.CONSUMER_PHASE_LAUNCHED, + expConsumers: consumers[2:3], + }, + { + name: "expect stopped consumers when phase is set to Stopped", + setup: func(ctx sdk.Context, pk keeper.Keeper) { + consumers[3].Phase = types.CONSUMER_PHASE_STOPPED.String() + pk.SetConsumerPhase(ctx, consumerIds[3], types.CONSUMER_PHASE_STOPPED) + }, + phase_filter: types.CONSUMER_PHASE_STOPPED, + expConsumers: consumers[3:], + }, + } + + for _, tc := range testCases { + t.Run(tc.name, func(t *testing.T) { + tc.setup(ctx, pk) + req := types.QueryConsumerChainsRequest{ + Phase: tc.phase_filter, + Limit: tc.limit, + } + expectedResponse := types.QueryConsumerChainsResponse{ + Chains: tc.expConsumers, + } + res, err := pk.QueryConsumerChains(ctx, &req) + require.NoError(t, err) + require.Equal(t, &expectedResponse, res, tc.name) + }) + } +} diff --git a/x/ccv/provider/keeper/hooks.go b/x/ccv/provider/keeper/hooks.go index 3f7f9d21a9..f61facac50 100644 --- a/x/ccv/provider/keeper/hooks.go +++ b/x/ccv/provider/keeper/hooks.go @@ -105,27 +105,11 @@ func (h Hooks) BeforeTokenizeShareRecordRemoved(_ context.Context, _ uint64) err // gov hooks // -// AfterProposalSubmission - call hook if registered -// After a consumerAddition proposal submission, a record is created -// that maps the proposal ID to the consumer chain ID. -func (h Hooks) AfterProposalSubmission(goCtx context.Context, proposalID uint64) error { - ctx := sdk.UnwrapSDKContext(goCtx) - if p, ok := h.GetConsumerAdditionFromProp(ctx, proposalID); ok { - h.k.SetProposedConsumerChain(ctx, p.ChainId, proposalID) - } +func (h Hooks) AfterProposalSubmission(goCtx context.Context, proposalId uint64) error { return nil } -// AfterProposalVotingPeriodEnded - call hook if registered -// After proposal voting ends, the consumer chainID in store is deleted. -// When a consumerAddition proposal passes, the consumer chainID is available in providerKeeper.GetAllPendingConsumerAdditionProps -// or providerKeeper.GetAllConsumerChains(ctx). -func (h Hooks) AfterProposalVotingPeriodEnded(goCtx context.Context, proposalID uint64) error { - ctx := sdk.UnwrapSDKContext(goCtx) - - if _, ok := h.GetConsumerAdditionFromProp(ctx, proposalID); ok { - h.k.DeleteProposedConsumerChainInStore(ctx, proposalID) - } +func (h Hooks) AfterProposalVotingPeriodEnded(goCtx context.Context, proposalId uint64) error { return nil } @@ -140,50 +124,3 @@ func (h Hooks) AfterProposalVote(ctx context.Context, proposalID uint64, voterAd func (h Hooks) AfterProposalFailedMinDeposit(ctx context.Context, proposalID uint64) error { return nil } - -// GetConsumerAdditionFromProp extracts a consumer addition proposal from -// the proposal with the given ID -func (h Hooks) GetConsumerAdditionFromProp( - ctx sdk.Context, - proposalID uint64, -) (providertypes.ConsumerAdditionProposal, bool) { - p, err := h.k.govKeeper.Proposals.Get(ctx, proposalID) - if err != nil { - return providertypes.ConsumerAdditionProposal{}, false - } - - // Iterate over the messages in the proposal - // Note that it's assumed that at most ONE message can contain a consumer addition proposal - for _, msg := range p.GetMessages() { - sdkMsg, isConsumerAddition := msg.GetCachedValue().(*providertypes.MsgConsumerAddition) - if !isConsumerAddition { - continue - } - - proposal := providertypes.ConsumerAdditionProposal{ - Title: p.Title, - Description: p.Summary, - ChainId: sdkMsg.ChainId, - InitialHeight: sdkMsg.InitialHeight, - GenesisHash: sdkMsg.GenesisHash, - BinaryHash: sdkMsg.BinaryHash, - SpawnTime: sdkMsg.SpawnTime, - UnbondingPeriod: sdkMsg.UnbondingPeriod, - CcvTimeoutPeriod: sdkMsg.CcvTimeoutPeriod, - TransferTimeoutPeriod: sdkMsg.TransferTimeoutPeriod, - ConsumerRedistributionFraction: sdkMsg.ConsumerRedistributionFraction, - BlocksPerDistributionTransmission: sdkMsg.BlocksPerDistributionTransmission, - HistoricalEntries: sdkMsg.HistoricalEntries, - DistributionTransmissionChannel: sdkMsg.DistributionTransmissionChannel, - Top_N: sdkMsg.Top_N, - ValidatorsPowerCap: sdkMsg.ValidatorsPowerCap, - ValidatorSetCap: sdkMsg.ValidatorSetCap, - Allowlist: sdkMsg.Allowlist, - Denylist: sdkMsg.Denylist, - MinStake: sdkMsg.MinStake, - AllowInactiveVals: sdkMsg.AllowInactiveVals, - } - return proposal, true - } - return providertypes.ConsumerAdditionProposal{}, false -} diff --git a/x/ccv/provider/keeper/hooks_test.go b/x/ccv/provider/keeper/hooks_test.go index 2447b5edf3..e76eece5ad 100644 --- a/x/ccv/provider/keeper/hooks_test.go +++ b/x/ccv/provider/keeper/hooks_test.go @@ -7,6 +7,7 @@ import ( cryptotestutil "github.com/cosmos/interchain-security/v5/testutil/crypto" testkeeper "github.com/cosmos/interchain-security/v5/testutil/keeper" providerkeeper "github.com/cosmos/interchain-security/v5/x/ccv/provider/keeper" + "github.com/cosmos/interchain-security/v5/x/ccv/provider/types" "github.com/golang/mock/gomock" ) @@ -30,32 +31,40 @@ func TestValidatorConsensusKeyInUse(t *testing.T) { { name: "in use by another validator", setup: func(ctx sdk.Context, k providerkeeper.Keeper) { + k.FetchAndIncrementConsumerId(ctx) + k.SetConsumerPhase(ctx, "0", types.CONSUMER_PHASE_INITIALIZED) + // We are trying to add a new validator, but its address has already been used // by another validator - k.SetValidatorByConsumerAddr(ctx, "chainid", + k.SetValidatorByConsumerAddr(ctx, "0", newValidator.ConsumerConsAddress(), anotherValidator0.ProviderConsAddress(), ) - k.SetConsumerClientId(ctx, "chainid", "clientID") + k.SetConsumerClientId(ctx, "0", "clientId") }, expect: true, }, { name: "in use by one of several other validators", setup: func(ctx sdk.Context, k providerkeeper.Keeper) { + k.FetchAndIncrementConsumerId(ctx) + k.FetchAndIncrementConsumerId(ctx) + k.SetConsumerPhase(ctx, "0", types.CONSUMER_PHASE_INITIALIZED) + k.SetConsumerPhase(ctx, "1", types.CONSUMER_PHASE_INITIALIZED) + // We are trying to add a new validator, but its address has already been used // by another validator, of which there are several, across potentially several chains - k.SetValidatorByConsumerAddr(ctx, "chainid0", + k.SetValidatorByConsumerAddr(ctx, "0", newValidator.ConsumerConsAddress(), anotherValidator0.ProviderConsAddress(), ) - k.SetConsumerClientId(ctx, "chainid0", "clientID0") + k.SetConsumerClientId(ctx, "0", "clientId0") - k.SetValidatorByConsumerAddr(ctx, "chainid1", + k.SetValidatorByConsumerAddr(ctx, "1", anotherValidator1.ConsumerConsAddress(), anotherValidator1.ProviderConsAddress(), ) - k.SetConsumerClientId(ctx, "chainid1", "clientID1") + k.SetConsumerClientId(ctx, "1", "clientId1") }, expect: true, }, diff --git a/x/ccv/provider/keeper/keeper.go b/x/ccv/provider/keeper/keeper.go index 1125ae52c8..3d624f10f3 100644 --- a/x/ccv/provider/keeper/keeper.go +++ b/x/ccv/provider/keeper/keeper.go @@ -189,171 +189,113 @@ func (k Keeper) ClaimCapability(ctx sdk.Context, cap *capabilitytypes.Capability return k.scopedKeeper.ClaimCapability(ctx, cap, name) } -// SetChainToChannel sets the mapping from a consumer chainID to the CCV channel ID for that consumer chain. -func (k Keeper) SetChainToChannel(ctx sdk.Context, chainID, channelID string) { +// SetConsumerIdToChannelId sets the mapping from a consumer id to the CCV channel id for that consumer chain. +func (k Keeper) SetConsumerIdToChannelId(ctx sdk.Context, consumerId, channelId string) { store := ctx.KVStore(k.storeKey) - store.Set(types.ChainToChannelKey(chainID), []byte(channelID)) + store.Set(types.ConsumerIdToChannelIdKey(consumerId), []byte(channelId)) } -// GetChainToChannel gets the CCV channelID for the given consumer chainID -func (k Keeper) GetChainToChannel(ctx sdk.Context, chainID string) (string, bool) { +// GetConsumerIdToChannelId gets the CCV channelId for the given consumer id +func (k Keeper) GetConsumerIdToChannelId(ctx sdk.Context, consumerId string) (string, bool) { store := ctx.KVStore(k.storeKey) - bz := store.Get(types.ChainToChannelKey(chainID)) + bz := store.Get(types.ConsumerIdToChannelIdKey(consumerId)) if bz == nil { return "", false } return string(bz), true } -// DeleteChainToChannel deletes the CCV channel ID for the given consumer chain ID -func (k Keeper) DeleteChainToChannel(ctx sdk.Context, chainID string) { +// DeleteConsumerIdToChannelId deletes the CCV channel id for the given consumer id +func (k Keeper) DeleteConsumerIdToChannelId(ctx sdk.Context, consumerId string) { store := ctx.KVStore(k.storeKey) - store.Delete(types.ChainToChannelKey(chainID)) + store.Delete(types.ConsumerIdToChannelIdKey(consumerId)) } -// SetProposedConsumerChain stores a consumer chainId corresponding to a submitted consumer addition proposal -// This consumer chainId is deleted once the voting period for the proposal ends. -func (k Keeper) SetProposedConsumerChain(ctx sdk.Context, chainID string, proposalID uint64) { - store := ctx.KVStore(k.storeKey) - store.Set(types.ProposedConsumerChainKey(proposalID), []byte(chainID)) -} - -// GetProposedConsumerChain returns the proposed chainID for the given consumerAddition proposal ID. -// This method is only used for testing. -func (k Keeper) GetProposedConsumerChain(ctx sdk.Context, proposalID uint64) (string, bool) { - store := ctx.KVStore(k.storeKey) - consumerChain := store.Get(types.ProposedConsumerChainKey(proposalID)) - if consumerChain != nil { - return string(consumerChain), true - } - return "", false -} - -// DeleteProposedConsumerChainInStore deletes the consumer chainID from store -// which is in gov consumerAddition proposal -func (k Keeper) DeleteProposedConsumerChainInStore(ctx sdk.Context, proposalID uint64) { - store := ctx.KVStore(k.storeKey) - store.Delete(types.ProposedConsumerChainKey(proposalID)) -} +// GetAllConsumersWithIBCClients returns the ids of all consumer chains that with IBC clients created. +func (k Keeper) GetAllConsumersWithIBCClients(ctx sdk.Context) []string { + consumerIds := []string{} -// GetAllProposedConsumerChainIDs returns the proposed chainID of all gov consumerAddition proposals that are still in the voting period. -func (k Keeper) GetAllProposedConsumerChainIDs(ctx sdk.Context) []types.ProposedChain { store := ctx.KVStore(k.storeKey) - iterator := storetypes.KVStorePrefixIterator(store, types.ProposedConsumerChainKeyPrefix()) + iterator := storetypes.KVStorePrefixIterator(store, types.ConsumerIdToClientIdKeyPrefix()) defer iterator.Close() - proposedChains := []types.ProposedChain{} for ; iterator.Valid(); iterator.Next() { - proposalID, err := types.ParseProposedConsumerChainKey(iterator.Key()) - if err != nil { - panic(fmt.Errorf("proposed chains cannot be parsed: %w", err)) - } - - proposedChains = append(proposedChains, types.ProposedChain{ - ChainID: string(iterator.Value()), - ProposalID: proposalID, - }) - + // remove 1 byte prefix from key to retrieve consumerId + consumerId := string(iterator.Key()[1:]) + consumerIds = append(consumerIds, consumerId) } - return proposedChains + return consumerIds } -// GetAllPendingConsumerChainIDs gets pending consumer chains have not reach spawn time -func (k Keeper) GetAllPendingConsumerChainIDs(ctx sdk.Context) []string { - chainIDs := []string{} - props := k.GetAllPendingConsumerAdditionProps(ctx) - for _, prop := range props { - chainIDs = append(chainIDs, prop.ChainId) - } - - return chainIDs -} - -// GetAllRegisteredConsumerChainIDs gets all of the consumer chain IDs, for which the provider module -// created IBC clients. Consumer chains with created clients are also referred to as registered. -// -// Note that the registered consumer chains are stored under keys with the following format: -// ChainToClientKeyPrefix | chainID -// Thus, the returned array is in ascending order of chainIDs. -func (k Keeper) GetAllRegisteredConsumerChainIDs(ctx sdk.Context) []string { - chainIDs := []string{} - +// SetChannelToConsumerId sets the mapping from the CCV channel id to the consumer id. +func (k Keeper) SetChannelToConsumerId(ctx sdk.Context, channelId, consumerId string) { store := ctx.KVStore(k.storeKey) - iterator := storetypes.KVStorePrefixIterator(store, types.ChainToClientKeyPrefix()) - defer iterator.Close() - - for ; iterator.Valid(); iterator.Next() { - // remove 1 byte prefix from key to retrieve chainID - chainID := string(iterator.Key()[1:]) - chainIDs = append(chainIDs, chainID) - } - - return chainIDs + store.Set(types.ChannelToConsumerIdKey(channelId), []byte(consumerId)) } -// SetChannelToChain sets the mapping from the CCV channel ID to the consumer chainID. -func (k Keeper) SetChannelToChain(ctx sdk.Context, channelID, chainID string) { +// GetChannelIdToConsumerId gets the consumer id for a given CCV channel id +func (k Keeper) GetChannelIdToConsumerId(ctx sdk.Context, channelID string) (string, bool) { store := ctx.KVStore(k.storeKey) - store.Set(types.ChannelToChainKey(channelID), []byte(chainID)) -} - -// GetChannelToChain gets the consumer chainID for a given CCV channelID -func (k Keeper) GetChannelToChain(ctx sdk.Context, channelID string) (string, bool) { - store := ctx.KVStore(k.storeKey) - bz := store.Get(types.ChannelToChainKey(channelID)) + bz := store.Get(types.ChannelToConsumerIdKey(channelID)) if bz == nil { return "", false } return string(bz), true } -// DeleteChannelToChain deletes the consumer chain ID for a given CCV channelID -func (k Keeper) DeleteChannelToChain(ctx sdk.Context, channelID string) { +// DeleteChannelIdToConsumerId deletes the consumer id for a given CCV channel id +func (k Keeper) DeleteChannelIdToConsumerId(ctx sdk.Context, channelId string) { store := ctx.KVStore(k.storeKey) - store.Delete(types.ChannelToChainKey(channelID)) + store.Delete(types.ChannelToConsumerIdKey(channelId)) } -// GetAllChannelToChains gets all channel to chain mappings. If a mapping exists, +// GetAllChannelToConsumers gets all channel to chain mappings. If a mapping exists, // then the CCV channel to that consumer chain is established. // -// Note that mapping from CCV channel IDs to consumer chainIDs +// Note that mapping from CCV channel IDs to consumer IDs // is stored under keys with the following format: -// ChannelToChainKeyPrefix | channelID +// ChannelIdToConsumerIdKeyPrefix | channelID // Thus, the returned array is in ascending order of channelIDs. -func (k Keeper) GetAllChannelToChains(ctx sdk.Context) (channels []types.ChannelToChain) { +func (k Keeper) GetAllChannelToConsumers(ctx sdk.Context) (channelsToConsumers []struct { + ChannelId string + ConsumerId string +}) { store := ctx.KVStore(k.storeKey) - iterator := storetypes.KVStorePrefixIterator(store, types.ChannelToChainKeyPrefix()) + iterator := storetypes.KVStorePrefixIterator(store, types.ChannelIdToConsumerIdKeyPrefix()) defer iterator.Close() for ; iterator.Valid(); iterator.Next() { // remove prefix from key to retrieve channelID channelID := string(iterator.Key()[1:]) - chainID := string(iterator.Value()) - - channels = append(channels, types.ChannelToChain{ - ChannelId: channelID, - ChainId: chainID, + consumerId := string(iterator.Value()) + + channelsToConsumers = append(channelsToConsumers, struct { + ChannelId string + ConsumerId string + }{ + ChannelId: channelID, + ConsumerId: consumerId, }) } - return channels + return channelsToConsumers } -func (k Keeper) SetConsumerGenesis(ctx sdk.Context, chainID string, gen ccv.ConsumerGenesisState) error { +func (k Keeper) SetConsumerGenesis(ctx sdk.Context, consumerId string, gen ccv.ConsumerGenesisState) error { store := ctx.KVStore(k.storeKey) bz, err := gen.Marshal() if err != nil { return err } - store.Set(types.ConsumerGenesisKey(chainID), bz) + store.Set(types.ConsumerGenesisKey(consumerId), bz) return nil } -func (k Keeper) GetConsumerGenesis(ctx sdk.Context, chainID string) (ccv.ConsumerGenesisState, bool) { +func (k Keeper) GetConsumerGenesis(ctx sdk.Context, consumerId string) (ccv.ConsumerGenesisState, bool) { store := ctx.KVStore(k.storeKey) - bz := store.Get(types.ConsumerGenesisKey(chainID)) + bz := store.Get(types.ConsumerGenesisKey(consumerId)) if bz == nil { return ccv.ConsumerGenesisState{}, false } @@ -367,9 +309,9 @@ func (k Keeper) GetConsumerGenesis(ctx sdk.Context, chainID string) (ccv.Consume return data, true } -func (k Keeper) DeleteConsumerGenesis(ctx sdk.Context, chainID string) { +func (k Keeper) DeleteConsumerGenesis(ctx sdk.Context, consumerId string) { store := ctx.KVStore(k.storeKey) - store.Delete(types.ConsumerGenesisKey(chainID)) + store.Delete(types.ConsumerGenesisKey(consumerId)) } // VerifyConsumerChain verifies that the chain trying to connect on the channel handshake @@ -379,21 +321,26 @@ func (k Keeper) VerifyConsumerChain(ctx sdk.Context, channelID string, connectio return errorsmod.Wrap(channeltypes.ErrTooManyConnectionHops, "must have direct connection to provider chain") } connectionID := connectionHops[0] - clientID, tmClient, err := k.getUnderlyingClient(ctx, connectionID) + clientId, _, err := k.getUnderlyingClient(ctx, connectionID) if err != nil { return err } - ccvClientId, found := k.GetConsumerClientId(ctx, tmClient.ChainId) + + consumerId, found := k.GetClientIdToConsumerId(ctx, clientId) if !found { - return errorsmod.Wrapf(ccv.ErrClientNotFound, "cannot find client for consumer chain %s", tmClient.ChainId) + return errorsmod.Wrapf(ccv.ErrConsumerChainNotFound, "cannot find consumer id associated with client id: %s", clientId) } - if ccvClientId != clientID { - return errorsmod.Wrapf(types.ErrInvalidConsumerClient, "CCV channel must be built on top of CCV client. expected %s, got %s", ccvClientId, clientID) + ccvClientId, found := k.GetConsumerClientId(ctx, consumerId) + if !found { + return errorsmod.Wrapf(ccv.ErrClientNotFound, "cannot find client for consumer chain %s", consumerId) + } + if ccvClientId != clientId { + return errorsmod.Wrapf(types.ErrInvalidConsumerClient, "CCV channel must be built on top of CCV client. expected %s, got %s", ccvClientId, clientId) } // Verify that there isn't already a CCV channel for the consumer chain - if prevChannel, ok := k.GetChainToChannel(ctx, tmClient.ChainId); ok { - return errorsmod.Wrapf(ccv.ErrDuplicateChannel, "CCV channel with ID: %s already created for consumer chain %s", prevChannel, tmClient.ChainId) + if prevChannel, ok := k.GetConsumerIdToChannelId(ctx, consumerId); ok { + return errorsmod.Wrapf(ccv.ErrDuplicateChannel, "CCV channel with ID: %s already created for consumer chain %s", prevChannel, consumerId) } return nil } @@ -418,25 +365,30 @@ func (k Keeper) SetConsumerChain(ctx sdk.Context, channelID string) error { if err != nil { return err } + consumerId, found := k.GetClientIdToConsumerId(ctx, clientID) + if !found { + return errorsmod.Wrapf(types.ErrNoConsumerId, "cannot find a consumer chain associated for this client: %s", clientID) + } // Verify that there isn't already a CCV channel for the consumer chain chainID := tmClient.ChainId - if prevChannelID, ok := k.GetChainToChannel(ctx, chainID); ok { - return errorsmod.Wrapf(ccv.ErrDuplicateChannel, "CCV channel with ID: %s already created for consumer chain %s", prevChannelID, chainID) + if prevChannelID, ok := k.GetConsumerIdToChannelId(ctx, consumerId); ok { + return errorsmod.Wrapf(ccv.ErrDuplicateChannel, "CCV channel with ID: %s already created for consumer chain with id %s", prevChannelID, consumerId) } // the CCV channel is established: // - set channel mappings - k.SetChainToChannel(ctx, chainID, channelID) - k.SetChannelToChain(ctx, channelID, chainID) + k.SetConsumerIdToChannelId(ctx, consumerId, channelID) + k.SetChannelToConsumerId(ctx, channelID, consumerId) // - set current block height for the consumer chain initialization - k.SetInitChainHeight(ctx, chainID, uint64(ctx.BlockHeight())) + k.SetInitChainHeight(ctx, consumerId, uint64(ctx.BlockHeight())) // emit event on successful addition ctx.EventManager().EmitEvent( sdk.NewEvent( ccv.EventTypeChannelEstablished, sdk.NewAttribute(sdk.AttributeKeyModule, consumertypes.ModuleName), - sdk.NewAttribute(ccv.AttributeChainID, chainID), + sdk.NewAttribute(types.AttributeConsumerId, consumerId), + sdk.NewAttribute(types.AttributeConsumerChainId, chainID), sdk.NewAttribute(conntypes.AttributeKeyClientID, clientID), sdk.NewAttribute(channeltypes.AttributeKeyChannelID, channelID), sdk.NewAttribute(conntypes.AttributeKeyConnectionID, connectionID), @@ -554,7 +506,7 @@ func (k Keeper) DeleteValsetUpdateBlockHeight(ctx sdk.Context, valsetUpdateId ui // // TODO: SlashAcks should be persisted as a list of ConsumerConsAddr types, not strings. // See https://github.com/cosmos/interchain-security/issues/728 -func (k Keeper) SetSlashAcks(ctx sdk.Context, chainID string, acks []string) { +func (k Keeper) SetSlashAcks(ctx sdk.Context, consumerId string, acks []string) { store := ctx.KVStore(k.storeKey) sa := types.SlashAcks{ @@ -566,16 +518,16 @@ func (k Keeper) SetSlashAcks(ctx sdk.Context, chainID string, acks []string) { // sa is instantiated in this method and should be able to be marshaled. panic(fmt.Errorf("failed to marshal SlashAcks: %w", err)) } - store.Set(types.SlashAcksKey(chainID), bz) + store.Set(types.SlashAcksKey(consumerId), bz) } -// GetSlashAcks returns the slash acks stored under the given chain ID +// GetSlashAcks returns the slash acks stored under the given consumer id // // TODO: SlashAcks should be persisted as a list of ConsumerConsAddr types, not strings. // See https://github.com/cosmos/interchain-security/issues/728 -func (k Keeper) GetSlashAcks(ctx sdk.Context, chainID string) []string { +func (k Keeper) GetSlashAcks(ctx sdk.Context, consumerId string) []string { store := ctx.KVStore(k.storeKey) - bz := store.Get(types.SlashAcksKey(chainID)) + bz := store.Get(types.SlashAcksKey(consumerId)) if bz == nil { return nil } @@ -589,45 +541,45 @@ func (k Keeper) GetSlashAcks(ctx sdk.Context, chainID string) []string { return acks.GetAddresses() } -// ConsumeSlashAcks empties and returns the slash acks for a given chain ID -func (k Keeper) ConsumeSlashAcks(ctx sdk.Context, chainID string) (acks []string) { - acks = k.GetSlashAcks(ctx, chainID) +// ConsumeSlashAcks empties and returns the slash acks for a given consumer id +func (k Keeper) ConsumeSlashAcks(ctx sdk.Context, consumerId string) (acks []string) { + acks = k.GetSlashAcks(ctx, consumerId) if len(acks) < 1 { return } store := ctx.KVStore(k.storeKey) - store.Delete(types.SlashAcksKey(chainID)) + store.Delete(types.SlashAcksKey(consumerId)) return } -// DeleteSlashAcks deletes the slash acks for a given chain ID -func (k Keeper) DeleteSlashAcks(ctx sdk.Context, chainID string) { +// DeleteSlashAcks deletes the slash acks for a given consumer id +func (k Keeper) DeleteSlashAcks(ctx sdk.Context, consumerId string) { store := ctx.KVStore(k.storeKey) - store.Delete(types.SlashAcksKey(chainID)) + store.Delete(types.SlashAcksKey(consumerId)) } -// AppendSlashAck appends the given slash ack to the given chain ID slash acks in store -func (k Keeper) AppendSlashAck(ctx sdk.Context, chainID, +// AppendSlashAck appends the given slash ack to the given consumer id slash acks in store +func (k Keeper) AppendSlashAck(ctx sdk.Context, consumerId, ack string, // TODO: consumer cons addr should be accepted here, see https://github.com/cosmos/interchain-security/issues/728 ) { - acks := k.GetSlashAcks(ctx, chainID) + acks := k.GetSlashAcks(ctx, consumerId) acks = append(acks, ack) - k.SetSlashAcks(ctx, chainID, acks) + k.SetSlashAcks(ctx, consumerId, acks) } // SetInitChainHeight sets the provider block height when the given consumer chain was initiated -func (k Keeper) SetInitChainHeight(ctx sdk.Context, chainID string, height uint64) { +func (k Keeper) SetInitChainHeight(ctx sdk.Context, consumerId string, height uint64) { store := ctx.KVStore(k.storeKey) heightBytes := make([]byte, 8) binary.BigEndian.PutUint64(heightBytes, height) - store.Set(types.InitChainHeightKey(chainID), heightBytes) + store.Set(types.InitChainHeightKey(consumerId), heightBytes) } // GetInitChainHeight returns the provider block height when the given consumer chain was initiated -func (k Keeper) GetInitChainHeight(ctx sdk.Context, chainID string) (uint64, bool) { +func (k Keeper) GetInitChainHeight(ctx sdk.Context, consumerId string) (uint64, bool) { store := ctx.KVStore(k.storeKey) - bz := store.Get(types.InitChainHeightKey(chainID)) + bz := store.Get(types.InitChainHeightKey(consumerId)) if bz == nil { return 0, false } @@ -636,17 +588,17 @@ func (k Keeper) GetInitChainHeight(ctx sdk.Context, chainID string) (uint64, boo } // DeleteInitChainHeight deletes the block height value for which the given consumer chain's channel was established -func (k Keeper) DeleteInitChainHeight(ctx sdk.Context, chainID string) { +func (k Keeper) DeleteInitChainHeight(ctx sdk.Context, consumerId string) { store := ctx.KVStore(k.storeKey) - store.Delete(types.InitChainHeightKey(chainID)) + store.Delete(types.InitChainHeightKey(consumerId)) } -// GetPendingVSCPackets returns the list of pending ValidatorSetChange packets stored under chain ID -func (k Keeper) GetPendingVSCPackets(ctx sdk.Context, chainID string) []ccv.ValidatorSetChangePacketData { +// GetPendingVSCPackets returns the list of pending ValidatorSetChange packets stored under consumer id +func (k Keeper) GetPendingVSCPackets(ctx sdk.Context, consumerId string) []ccv.ValidatorSetChangePacketData { var packets types.ValidatorSetChangePackets store := ctx.KVStore(k.storeKey) - bz := store.Get(types.PendingVSCsKey(chainID)) + bz := store.Get(types.PendingVSCsKey(consumerId)) if bz == nil { return []ccv.ValidatorSetChangePacketData{} } @@ -659,9 +611,9 @@ func (k Keeper) GetPendingVSCPackets(ctx sdk.Context, chainID string) []ccv.Vali } // AppendPendingVSCPackets adds the given ValidatorSetChange packet to the list -// of pending ValidatorSetChange packets stored under chain ID -func (k Keeper) AppendPendingVSCPackets(ctx sdk.Context, chainID string, newPackets ...ccv.ValidatorSetChangePacketData) { - pds := append(k.GetPendingVSCPackets(ctx, chainID), newPackets...) +// of pending ValidatorSetChange packets stored under consumer id +func (k Keeper) AppendPendingVSCPackets(ctx sdk.Context, consumerId string, newPackets ...ccv.ValidatorSetChangePacketData) { + pds := append(k.GetPendingVSCPackets(ctx, consumerId), newPackets...) store := ctx.KVStore(k.storeKey) packets := types.ValidatorSetChangePackets{List: pds} @@ -671,35 +623,63 @@ func (k Keeper) AppendPendingVSCPackets(ctx sdk.Context, chainID string, newPack // packets is instantiated in this method and should be able to be marshaled. panic(fmt.Errorf("cannot marshal pending validator set changes: %w", err)) } - store.Set(types.PendingVSCsKey(chainID), buf) + store.Set(types.PendingVSCsKey(consumerId), buf) } // DeletePendingVSCPackets deletes the list of pending ValidatorSetChange packets for chain ID -func (k Keeper) DeletePendingVSCPackets(ctx sdk.Context, chainID string) { +func (k Keeper) DeletePendingVSCPackets(ctx sdk.Context, consumerId string) { store := ctx.KVStore(k.storeKey) - store.Delete(types.PendingVSCsKey(chainID)) + store.Delete(types.PendingVSCsKey(consumerId)) } -// SetConsumerClientId sets the client ID for the given chain ID -func (k Keeper) SetConsumerClientId(ctx sdk.Context, chainID, clientID string) { +// SetConsumerClientId sets the client id for the given consumer id. +// Note that the method also stores a reverse index that can be accessed +// by calling GetClientIdToConsumerId. +func (k Keeper) SetConsumerClientId(ctx sdk.Context, consumerId, clientId string) { store := ctx.KVStore(k.storeKey) - store.Set(types.ChainToClientKey(chainID), []byte(clientID)) + + if prevClientId, found := k.GetConsumerClientId(ctx, consumerId); found { + // delete reverse index + store.Delete(types.ClientIdToConsumerIdKey(prevClientId)) + } + + store.Set(types.ConsumerIdToClientIdKey(consumerId), []byte(clientId)) + + // set the reverse index + store.Set(types.ClientIdToConsumerIdKey(clientId), []byte(consumerId)) } -// GetConsumerClientId returns the client ID for the given chain ID. -func (k Keeper) GetConsumerClientId(ctx sdk.Context, chainID string) (string, bool) { +// GetConsumerClientId returns the client id for the given consumer id. +func (k Keeper) GetConsumerClientId(ctx sdk.Context, consumerId string) (string, bool) { store := ctx.KVStore(k.storeKey) - clientIdBytes := store.Get(types.ChainToClientKey(chainID)) + clientIdBytes := store.Get(types.ConsumerIdToClientIdKey(consumerId)) if clientIdBytes == nil { return "", false } return string(clientIdBytes), true } -// DeleteConsumerClientId removes from the store the clientID for the given chainID. -func (k Keeper) DeleteConsumerClientId(ctx sdk.Context, chainID string) { +// GetClientIdToConsumerId returns the consumer id associated with this client id +func (k Keeper) GetClientIdToConsumerId(ctx sdk.Context, clientId string) (string, bool) { store := ctx.KVStore(k.storeKey) - store.Delete(types.ChainToClientKey(chainID)) + consumerIdBytes := store.Get(types.ClientIdToConsumerIdKey(clientId)) + if consumerIdBytes == nil { + return "", false + } + return string(consumerIdBytes), true +} + +// DeleteConsumerClientId removes from the store the client id for the given consumer id. +// Note that the method also removes the reverse index. +func (k Keeper) DeleteConsumerClientId(ctx sdk.Context, consumerId string) { + store := ctx.KVStore(k.storeKey) + + if clientId, found := k.GetConsumerClientId(ctx, consumerId); found { + // delete reverse index + store.Delete(types.ClientIdToConsumerIdKey(clientId)) + } + + store.Delete(types.ConsumerIdToClientIdKey(consumerId)) } // SetSlashLog updates validator's slash log for a consumer chain @@ -728,101 +708,68 @@ func (k Keeper) BondDenom(ctx sdk.Context) (string, error) { return k.stakingKeeper.BondDenom(ctx) } -func (k Keeper) GetAllRegisteredAndProposedChainIDs(ctx sdk.Context) []string { - allConsumerChains := []string{} - allConsumerChains = append(allConsumerChains, k.GetAllRegisteredConsumerChainIDs(ctx)...) - proposedChains := k.GetAllProposedConsumerChainIDs(ctx) - for _, proposedChain := range proposedChains { - allConsumerChains = append(allConsumerChains, proposedChain.ChainID) +// GetAllConsumerIds returns all the existing consumer ids +func (k Keeper) GetAllConsumerIds(ctx sdk.Context) []string { + latestConsumerId, found := k.GetConsumerId(ctx) + if !found { + return []string{} } - pendingChainIDs := k.GetAllPendingConsumerChainIDs(ctx) - allConsumerChains = append(allConsumerChains, pendingChainIDs...) - - return allConsumerChains -} - -// SetTopN stores the N value associated to chain with `chainID` -func (k Keeper) SetTopN( - ctx sdk.Context, - chainID string, - N uint32, -) { - store := ctx.KVStore(k.storeKey) - - buf := make([]byte, 4) - binary.BigEndian.PutUint32(buf, N) - - store.Set(types.TopNKey(chainID), buf) -} - -// DeleteTopN removes the N value associated to chain with `chainID` -func (k Keeper) DeleteTopN( - ctx sdk.Context, - chainID string, -) { - store := ctx.KVStore(k.storeKey) - store.Delete(types.TopNKey(chainID)) -} -// GetTopN returns (N, true) if chain `chainID` has a top N associated, and (0, false) otherwise. -func (k Keeper) GetTopN( - ctx sdk.Context, - chainID string, -) (uint32, bool) { - store := ctx.KVStore(k.storeKey) - buf := store.Get(types.TopNKey(chainID)) - if buf == nil { - return 0, false + consumerIds := []string{} + for i := uint64(0); i < latestConsumerId; i++ { + consumerId := fmt.Sprintf("%d", i) + consumerIds = append(consumerIds, consumerId) } - return binary.BigEndian.Uint32(buf), true -} -// IsTopN returns true if chain with `chainID` is a Top-N chain (i.e., enforces at least one validator to validate chain `chainID`) -func (k Keeper) IsTopN(ctx sdk.Context, chainID string) bool { - topN, found := k.GetTopN(ctx, chainID) - return found && topN > 0 + return consumerIds } -// IsOptIn returns true if chain with `chainID` is an Opt-In chain (i.e., no validator is forced to validate chain `chainID`) -func (k Keeper) IsOptIn(ctx sdk.Context, chainID string) bool { - topN, found := k.GetTopN(ctx, chainID) - return !found || topN == 0 +// GetAllActiveConsumerIds returns all the consumer ids of chains that are registered, initialized, or launched +func (k Keeper) GetAllActiveConsumerIds(ctx sdk.Context) []string { + consumerIds := []string{} + for _, consumerId := range k.GetAllConsumerIds(ctx) { + if !k.IsConsumerActive(ctx, consumerId) { + continue + } + consumerIds = append(consumerIds, consumerId) + } + return consumerIds } func (k Keeper) SetOptedIn( ctx sdk.Context, - chainID string, + consumerId string, providerConsAddress types.ProviderConsAddress, ) { store := ctx.KVStore(k.storeKey) - store.Set(types.OptedInKey(chainID, providerConsAddress), []byte{}) + store.Set(types.OptedInKey(consumerId, providerConsAddress), []byte{}) } func (k Keeper) DeleteOptedIn( ctx sdk.Context, - chainID string, + consumerId string, providerAddr types.ProviderConsAddress, ) { store := ctx.KVStore(k.storeKey) - store.Delete(types.OptedInKey(chainID, providerAddr)) + store.Delete(types.OptedInKey(consumerId, providerAddr)) } func (k Keeper) IsOptedIn( ctx sdk.Context, - chainID string, + consumerId string, providerAddr types.ProviderConsAddress, ) bool { store := ctx.KVStore(k.storeKey) - return store.Get(types.OptedInKey(chainID, providerAddr)) != nil + return store.Get(types.OptedInKey(consumerId, providerAddr)) != nil } -// GetAllOptedIn returns all the opted-in validators on chain `chainID` +// GetAllOptedIn returns all the opted-in validators on chain `consumerId` func (k Keeper) GetAllOptedIn( ctx sdk.Context, - chainID string, + consumerId string, ) (providerConsAddresses []types.ProviderConsAddress) { store := ctx.KVStore(k.storeKey) - key := types.ChainIdWithLenKey(types.OptedInKeyPrefix(), chainID) + key := types.StringIdWithLenKey(types.OptedInKeyPrefix(), consumerId) iterator := storetypes.KVStorePrefixIterator(store, key) defer iterator.Close() @@ -833,13 +780,13 @@ func (k Keeper) GetAllOptedIn( return providerConsAddresses } -// DeleteAllOptedIn deletes all the opted-in validators for chain with `chainID` +// DeleteAllOptedIn deletes all the opted-in validators for chain with `consumerId` func (k Keeper) DeleteAllOptedIn( ctx sdk.Context, - chainID string, + consumerId string, ) { store := ctx.KVStore(k.storeKey) - key := types.ChainIdWithLenKey(types.OptedInKeyPrefix(), chainID) + key := types.StringIdWithLenKey(types.OptedInKeyPrefix(), consumerId) iterator := storetypes.KVStorePrefixIterator(store, key) var keysToDel [][]byte @@ -856,7 +803,7 @@ func (k Keeper) DeleteAllOptedIn( // for the given validator address func (k Keeper) SetConsumerCommissionRate( ctx sdk.Context, - chainID string, + consumerId string, providerAddr types.ProviderConsAddress, commissionRate math.LegacyDec, ) error { @@ -868,7 +815,7 @@ func (k Keeper) SetConsumerCommissionRate( return err } - store.Set(types.ConsumerCommissionRateKey(chainID, providerAddr), bz) + store.Set(types.ConsumerCommissionRateKey(consumerId, providerAddr), bz) return nil } @@ -876,11 +823,11 @@ func (k Keeper) SetConsumerCommissionRate( // for the given validator address func (k Keeper) GetConsumerCommissionRate( ctx sdk.Context, - chainID string, + consumerId string, providerAddr types.ProviderConsAddress, ) (math.LegacyDec, bool) { store := ctx.KVStore(k.storeKey) - bz := store.Get(types.ConsumerCommissionRateKey(chainID, providerAddr)) + bz := store.Get(types.ConsumerCommissionRateKey(consumerId, providerAddr)) if bz == nil { return math.LegacyZeroDec(), false } @@ -896,13 +843,13 @@ func (k Keeper) GetConsumerCommissionRate( } // GetAllCommissionRateValidators returns all the validator address -// that set a commission rate for the given chain ID +// that set a commission rate for the given consumer id func (k Keeper) GetAllCommissionRateValidators( ctx sdk.Context, - chainID string, + consumerId string, ) (addresses []types.ProviderConsAddress) { store := ctx.KVStore(k.storeKey) - key := types.ChainIdWithLenKey(types.ConsumerCommissionRateKeyPrefix(), chainID) + key := types.StringIdWithLenKey(types.ConsumerCommissionRateKeyPrefix(), consumerId) iterator := storetypes.KVStorePrefixIterator(store, key) defer iterator.Close() @@ -918,331 +865,11 @@ func (k Keeper) GetAllCommissionRateValidators( // associated to the given validator address func (k Keeper) DeleteConsumerCommissionRate( ctx sdk.Context, - chainID string, - providerAddr types.ProviderConsAddress, -) { - store := ctx.KVStore(k.storeKey) - store.Delete(types.ConsumerCommissionRateKey(chainID, providerAddr)) -} - -// SetValidatorsPowerCap sets the power-cap value `p` associated to chain with `chainID` -func (k Keeper) SetValidatorsPowerCap( - ctx sdk.Context, - chainID string, - p uint32, -) { - store := ctx.KVStore(k.storeKey) - - buf := make([]byte, 4) - binary.BigEndian.PutUint32(buf, p) - - store.Set(types.ValidatorsPowerCapKey(chainID), buf) -} - -// DeleteValidatorsPowerCap removes the power-cap value associated to chain with `chainID` -func (k Keeper) DeleteValidatorsPowerCap( - ctx sdk.Context, - chainID string, -) { - store := ctx.KVStore(k.storeKey) - store.Delete(types.ValidatorsPowerCapKey(chainID)) -} - -// GetValidatorsPowerCap returns `(p, true)` if chain `chainID` has power cap `p` associated with it, and (0, false) otherwise -func (k Keeper) GetValidatorsPowerCap( - ctx sdk.Context, - chainID string, -) (uint32, bool) { - store := ctx.KVStore(k.storeKey) - buf := store.Get(types.ValidatorsPowerCapKey(chainID)) - if buf == nil { - return 0, false - } - return binary.BigEndian.Uint32(buf), true -} - -// SetValidatorSetCap stores the validator-set cap value `c` associated to chain with `chainID` -func (k Keeper) SetValidatorSetCap( - ctx sdk.Context, - chainID string, - c uint32, -) { - store := ctx.KVStore(k.storeKey) - - buf := make([]byte, 4) - binary.BigEndian.PutUint32(buf, c) - - store.Set(types.ValidatorSetCapKey(chainID), buf) -} - -// DeleteValidatorSetCap removes the validator-set cap value associated to chain with `chainID` -func (k Keeper) DeleteValidatorSetCap( - ctx sdk.Context, - chainID string, -) { - store := ctx.KVStore(k.storeKey) - store.Delete(types.ValidatorSetCapKey(chainID)) -} - -// GetValidatorSetCap returns `(c, true)` if chain `chainID` has validator-set cap `c` associated with it, and (0, false) otherwise -func (k Keeper) GetValidatorSetCap( - ctx sdk.Context, - chainID string, -) (uint32, bool) { - store := ctx.KVStore(k.storeKey) - buf := store.Get(types.ValidatorSetCapKey(chainID)) - if buf == nil { - return 0, false - } - return binary.BigEndian.Uint32(buf), true -} - -// SetAllowlist allowlists validator with `providerAddr` address on chain `chainID` -func (k Keeper) SetAllowlist( - ctx sdk.Context, - chainID string, + consumerId string, providerAddr types.ProviderConsAddress, ) { store := ctx.KVStore(k.storeKey) - store.Set(types.AllowlistKey(chainID, providerAddr), []byte{}) -} - -// GetAllowList returns all allowlisted validators -func (k Keeper) GetAllowList( - ctx sdk.Context, - chainID string, -) (providerConsAddresses []types.ProviderConsAddress) { - store := ctx.KVStore(k.storeKey) - key := types.ChainIdWithLenKey(types.AllowlistKeyPrefix(), chainID) - iterator := storetypes.KVStorePrefixIterator(store, key) - defer iterator.Close() - - for ; iterator.Valid(); iterator.Next() { - providerConsAddresses = append(providerConsAddresses, types.NewProviderConsAddress(iterator.Key()[len(key):])) - } - - return providerConsAddresses -} - -// IsAllowlisted returns `true` if validator with `providerAddr` has been allowlisted on chain `chainID` -func (k Keeper) IsAllowlisted( - ctx sdk.Context, - chainID string, - providerAddr types.ProviderConsAddress, -) bool { - store := ctx.KVStore(k.storeKey) - bz := store.Get(types.AllowlistKey(chainID, providerAddr)) - return bz != nil -} - -// DeleteAllowlist deletes all allowlisted validators -func (k Keeper) DeleteAllowlist(ctx sdk.Context, chainID string) { - store := ctx.KVStore(k.storeKey) - iterator := storetypes.KVStorePrefixIterator(store, types.ChainIdWithLenKey(types.AllowlistKeyPrefix(), chainID)) - defer iterator.Close() - - keysToDel := [][]byte{} - for ; iterator.Valid(); iterator.Next() { - keysToDel = append(keysToDel, iterator.Key()) - } - - for _, key := range keysToDel { - store.Delete(key) - } -} - -// IsAllowlistEmpty returns `true` if no validator is allowlisted on chain `chainID` -func (k Keeper) IsAllowlistEmpty(ctx sdk.Context, chainID string) bool { - store := ctx.KVStore(k.storeKey) - iterator := storetypes.KVStorePrefixIterator(store, types.ChainIdWithLenKey(types.AllowlistKeyPrefix(), chainID)) - defer iterator.Close() - - return !iterator.Valid() -} - -// SetDenylist denylists validator with `providerAddr` address on chain `chainID` -func (k Keeper) SetDenylist( - ctx sdk.Context, - chainID string, - providerAddr types.ProviderConsAddress, -) { - store := ctx.KVStore(k.storeKey) - store.Set(types.DenylistKey(chainID, providerAddr), []byte{}) -} - -// GetDenyList returns all denylisted validators -func (k Keeper) GetDenyList( - ctx sdk.Context, - chainID string, -) (providerConsAddresses []types.ProviderConsAddress) { - store := ctx.KVStore(k.storeKey) - key := types.ChainIdWithLenKey(types.DenylistKeyPrefix(), chainID) - iterator := storetypes.KVStorePrefixIterator(store, key) - defer iterator.Close() - - for ; iterator.Valid(); iterator.Next() { - providerConsAddresses = append(providerConsAddresses, types.NewProviderConsAddress(iterator.Key()[len(key):])) - } - - return providerConsAddresses -} - -// IsDenylisted returns `true` if validator with `providerAddr` has been denylisted on chain `chainID` -func (k Keeper) IsDenylisted( - ctx sdk.Context, - chainID string, - providerAddr types.ProviderConsAddress, -) bool { - store := ctx.KVStore(k.storeKey) - bz := store.Get(types.DenylistKey(chainID, providerAddr)) - return bz != nil -} - -// DeleteDenylist deletes all denylisted validators -func (k Keeper) DeleteDenylist(ctx sdk.Context, chainID string) { - store := ctx.KVStore(k.storeKey) - iterator := storetypes.KVStorePrefixIterator(store, types.ChainIdWithLenKey(types.DenylistKeyPrefix(), chainID)) - defer iterator.Close() - - keysToDel := [][]byte{} - for ; iterator.Valid(); iterator.Next() { - keysToDel = append(keysToDel, iterator.Key()) - } - - for _, key := range keysToDel { - store.Delete(key) - } -} - -// IsDenylistEmpty returns `true` if no validator is denylisted on chain `chainID` -func (k Keeper) IsDenylistEmpty(ctx sdk.Context, chainID string) bool { - store := ctx.KVStore(k.storeKey) - iterator := storetypes.KVStorePrefixIterator(store, types.ChainIdWithLenKey(types.DenylistKeyPrefix(), chainID)) - defer iterator.Close() - - return !iterator.Valid() -} - -// SetMinimumPowerInTopN sets the minimum power required for a validator to be in the top N -// for a given consumer chain. -func (k Keeper) SetMinimumPowerInTopN( - ctx sdk.Context, - chainID string, - power int64, -) { - store := ctx.KVStore(k.storeKey) - - buf := make([]byte, 8) - binary.BigEndian.PutUint64(buf, uint64(power)) - - store.Set(types.MinimumPowerInTopNKey(chainID), buf) -} - -// GetMinimumPowerInTopN returns the minimum power required for a validator to be in the top N -// for a given consumer chain. -func (k Keeper) GetMinimumPowerInTopN( - ctx sdk.Context, - chainID string, -) (int64, bool) { - store := ctx.KVStore(k.storeKey) - buf := store.Get(types.MinimumPowerInTopNKey(chainID)) - if buf == nil { - return 0, false - } - return int64(binary.BigEndian.Uint64(buf)), true -} - -// DeleteMinimumPowerInTopN removes the minimum power required for a validator to be in the top N -// for a given consumer chain. -func (k Keeper) DeleteMinimumPowerInTopN( - ctx sdk.Context, - chainID string, -) { - store := ctx.KVStore(k.storeKey) - store.Delete(types.MinimumPowerInTopNKey(chainID)) -} - -// SetMinStake sets the minimum stake required for a validator to validate -// a given consumer chain. -func (k Keeper) SetMinStake( - ctx sdk.Context, - chainID string, - minStake uint64, -) { - store := ctx.KVStore(k.storeKey) - - buf := make([]byte, 8) - binary.BigEndian.PutUint64(buf, minStake) - - store.Set(types.MinStakeKey(chainID), buf) -} - -// GetMinStake returns the minimum stake required for a validator to validate -// a given consumer chain. -func (k Keeper) GetMinStake( - ctx sdk.Context, - chainID string, -) (uint64, bool) { - store := ctx.KVStore(k.storeKey) - buf := store.Get(types.MinStakeKey(chainID)) - if buf == nil { - return 0, false - } - return binary.BigEndian.Uint64(buf), true -} - -// DeleteMinStake removes the minimum stake required for a validator to validate -// a given consumer chain. -func (k Keeper) DeleteMinStake( - ctx sdk.Context, - chainID string, -) { - store := ctx.KVStore(k.storeKey) - store.Delete(types.MinStakeKey(chainID)) -} - -// SetInactiveValidatorsAllowed sets whether inactive validators are allowed to validate -// a given consumer chain. -func (k Keeper) SetInactiveValidatorsAllowed( - ctx sdk.Context, - chainID string, - allowed bool, -) { - if allowed { - k.EnableInactiveValidators(ctx, chainID) - } else { - k.DisableInactiveValidators(ctx, chainID) - } -} - -// EnableInactiveValidators sets the flag to signal that inactive validators are allowed to validate -// a given consumer chain. -func (k Keeper) EnableInactiveValidators( - ctx sdk.Context, - chainID string, -) { - store := ctx.KVStore(k.storeKey) - store.Set(types.AllowInactiveValidatorsKey(chainID), []byte{}) -} - -// AllowsInactiveValidators returns whether inactive validators are allowed to validate -// a given consumer chain. -func (k Keeper) AllowsInactiveValidators( - ctx sdk.Context, - chainID string, -) bool { - store := ctx.KVStore(k.storeKey) - return store.Has(types.AllowInactiveValidatorsKey(chainID)) -} - -// DisableInactiveValidators removes the flag of whether inactive validators are allowed to validate -// a given consumer chain. -func (k Keeper) DisableInactiveValidators( - ctx sdk.Context, - chainID string, -) { - store := ctx.KVStore(k.storeKey) - store.Delete(types.AllowInactiveValidatorsKey(chainID)) + store.Delete(types.ConsumerCommissionRateKey(consumerId, providerAddr)) } func (k Keeper) UnbondingCanComplete(ctx sdk.Context, id uint64) error { diff --git a/x/ccv/provider/keeper/keeper_test.go b/x/ccv/provider/keeper/keeper_test.go index 442e86c09d..9485c9efd7 100644 --- a/x/ccv/provider/keeper/keeper_test.go +++ b/x/ccv/provider/keeper/keeper_test.go @@ -11,14 +11,13 @@ import ( "github.com/stretchr/testify/require" cryptocodec "github.com/cosmos/cosmos-sdk/crypto/codec" - sdk "github.com/cosmos/cosmos-sdk/types" abci "github.com/cometbft/cometbft/abci/types" tmprotocrypto "github.com/cometbft/cometbft/proto/tendermint/crypto" cryptotestutil "github.com/cosmos/interchain-security/v5/testutil/crypto" testkeeper "github.com/cosmos/interchain-security/v5/testutil/keeper" - "github.com/cosmos/interchain-security/v5/x/ccv/provider/types" + providertypes "github.com/cosmos/interchain-security/v5/x/ccv/provider/types" ccv "github.com/cosmos/interchain-security/v5/x/ccv/types" ) @@ -55,7 +54,7 @@ func TestGetAllValsetUpdateBlockHeights(t *testing.T) { pk, ctx, ctrl, _ := testkeeper.GetProviderKeeperAndCtx(t, testkeeper.NewInMemKeeperParams(t)) defer ctrl.Finish() - cases := []types.ValsetUpdateIdToHeight{ + cases := []providertypes.ValsetUpdateIdToHeight{ { ValsetUpdateId: 2, Height: 22, @@ -224,43 +223,56 @@ func TestInitHeight(t *testing.T) { } } -func TestGetAllRegisteredConsumerChainIDs(t *testing.T) { +func TestGetAllConsumersWithIBCClients(t *testing.T) { pk, ctx, ctrl, _ := testkeeper.GetProviderKeeperAndCtx(t, testkeeper.NewInMemKeeperParams(t)) defer ctrl.Finish() - chainIDs := []string{"chain-2", "chain-1", "chain-4", "chain-3"} - // GetAllRegisteredConsumerChainIDs iterates over chainID in lexicographical order - expectedChainIDs := []string{"chain-1", "chain-2", "chain-3", "chain-4"} - - for i, chainID := range chainIDs { - clientID := fmt.Sprintf("client-%d", len(chainIDs)-i) - pk.SetConsumerClientId(ctx, chainID, clientID) + consumerIds := []string{"2", "1", "4", "3"} + for i, consumerId := range consumerIds { + clientId := fmt.Sprintf("client-%d", len(consumerIds)-i) + pk.SetConsumerClientId(ctx, consumerId, clientId) + pk.SetConsumerPhase(ctx, consumerId, providertypes.CONSUMER_PHASE_LAUNCHED) } - result := pk.GetAllRegisteredConsumerChainIDs(ctx) - require.Len(t, result, len(chainIDs)) - require.Equal(t, expectedChainIDs, result) + actualConsumerIds := pk.GetAllConsumersWithIBCClients(ctx) + require.Len(t, actualConsumerIds, len(consumerIds)) + + // sort the consumer ids before comparing they are equal + sort.Slice(consumerIds, func(i, j int) bool { + return consumerIds[i] < consumerIds[j] + }) + sort.Slice(actualConsumerIds, func(i, j int) bool { + return actualConsumerIds[i] < actualConsumerIds[j] + }) + require.Equal(t, consumerIds, actualConsumerIds) } -// TestGetAllChannelToChains tests GetAllChannelToChains behaviour correctness +// TestGetAllChannelToChains tests GetAllChannelToConsumers behaviour correctness func TestGetAllChannelToChains(t *testing.T) { pk, ctx, ctrl, _ := testkeeper.GetProviderKeeperAndCtx(t, testkeeper.NewInMemKeeperParams(t)) defer ctrl.Finish() - chainIDs := []string{"chain-2", "chain-1", "chain-4", "chain-3"} - expectedGetAllOrder := []types.ChannelToChain{} - for i, chainID := range chainIDs { - channelID := fmt.Sprintf("client-%d", len(chainIDs)-i) - pk.SetChannelToChain(ctx, channelID, chainID) - expectedGetAllOrder = append(expectedGetAllOrder, types.ChannelToChain{ChainId: chainID, ChannelId: channelID}) + consumerIds := []string{"2", "1", "4", "3"} + var expectedGetAllOrder []struct { + ChannelId string + ConsumerId string + } + + for i, consumerId := range consumerIds { + channelID := fmt.Sprintf("client-%d", len(consumerIds)-i) + pk.SetChannelToConsumerId(ctx, channelID, consumerId) + expectedGetAllOrder = append(expectedGetAllOrder, struct { + ChannelId string + ConsumerId string + }{ConsumerId: consumerId, ChannelId: channelID}) } // sorting by channelID sort.Slice(expectedGetAllOrder, func(i, j int) bool { return expectedGetAllOrder[i].ChannelId < expectedGetAllOrder[j].ChannelId }) - result := pk.GetAllChannelToChains(ctx) - require.Len(t, result, len(chainIDs)) + result := pk.GetAllChannelToConsumers(ctx) + require.Len(t, result, len(consumerIds)) require.Equal(t, expectedGetAllOrder, result) } @@ -277,150 +289,24 @@ func TestSetSlashLog(t *testing.T) { require.False(t, providerKeeper.GetSlashLog(ctx, addrWithoutDoubleSigns)) } -func TestSetProposedConsumerChains(t *testing.T) { - providerKeeper, ctx, ctrl, _ := testkeeper.GetProviderKeeperAndCtx(t, testkeeper.NewInMemKeeperParams(t)) - defer ctrl.Finish() - - tests := []struct { - chainID string - proposalID uint64 - }{ - {chainID: "1", proposalID: 1}, - {chainID: "some other ID", proposalID: 12}, - {chainID: "some other other chain ID", proposalID: 123}, - {chainID: "", proposalID: 1234}, - } - - for _, test := range tests { - providerKeeper.SetProposedConsumerChain(ctx, test.chainID, test.proposalID) - cID, _ := providerKeeper.GetProposedConsumerChain(ctx, test.proposalID) - require.Equal(t, cID, test.chainID) - } -} - -func TestDeleteProposedConsumerChainInStore(t *testing.T) { - providerKeeper, ctx, ctrl, _ := testkeeper.GetProviderKeeperAndCtx(t, testkeeper.NewInMemKeeperParams(t)) - defer ctrl.Finish() - - tests := []struct { - chainID string - proposalID uint64 - deleteProposalID uint64 - ok bool - }{ - {chainID: "1", proposalID: 1, deleteProposalID: 1, ok: true}, - {chainID: "", proposalID: 12, deleteProposalID: 12, ok: true}, - {chainID: "1", proposalID: 0, deleteProposalID: 1, ok: false}, - } - for _, test := range tests { - providerKeeper.SetProposedConsumerChain(ctx, test.chainID, test.proposalID) - providerKeeper.DeleteProposedConsumerChainInStore(ctx, test.deleteProposalID) - cID, found := providerKeeper.GetProposedConsumerChain(ctx, test.proposalID) - if test.ok { - require.False(t, found) - } else { - require.Equal(t, cID, test.chainID) - } - } -} - -func TestGetAllProposedConsumerChainIDs(t *testing.T) { - providerKeeper, ctx, ctrl, _ := testkeeper.GetProviderKeeperAndCtx(t, testkeeper.NewInMemKeeperParams(t)) - defer ctrl.Finish() - tests := [][]types.ProposedChain{ - {}, - { - { - ChainID: "1", - ProposalID: 1, - }, - }, - { - { - ChainID: "1", - ProposalID: 1, - }, - { - ChainID: "2", - ProposalID: 2, - }, - { - ChainID: "", - ProposalID: 3, - }, - }, - } - - for _, test := range tests { - for _, tc := range test { - providerKeeper.SetProposedConsumerChain(ctx, tc.ChainID, tc.ProposalID) - } - - chains := providerKeeper.GetAllProposedConsumerChainIDs(ctx) - - sort.Slice(chains, func(i, j int) bool { - return chains[i].ProposalID < chains[j].ProposalID - }) - sort.Slice(test, func(i, j int) bool { - return test[i].ProposalID < test[j].ProposalID - }) - require.Equal(t, chains, test) - - for _, tc := range test { - providerKeeper.DeleteProposedConsumerChainInStore(ctx, tc.ProposalID) - } - } -} - -// TestTopN tests the `SetTopN`, `GetTopN`, `IsTopN`, and `IsOptIn` methods -func TestTopN(t *testing.T) { - providerKeeper, ctx, ctrl, _ := testkeeper.GetProviderKeeperAndCtx(t, testkeeper.NewInMemKeeperParams(t)) - defer ctrl.Finish() - - tests := []struct { - chainID string - N uint32 - isOptIn bool - }{ - {chainID: "TopNChain1", N: 50, isOptIn: false}, - {chainID: "TopNChain2", N: 100, isOptIn: false}, - {chainID: "OptInChain", N: 0, isOptIn: true}, - } - - for _, test := range tests { - providerKeeper.SetTopN(ctx, test.chainID, test.N) - topN, found := providerKeeper.GetTopN(ctx, test.chainID) - require.Equal(t, test.N, topN) - require.True(t, found) - - if test.isOptIn { - require.True(t, providerKeeper.IsOptIn(ctx, test.chainID)) - require.False(t, providerKeeper.IsTopN(ctx, test.chainID)) - } else { - require.False(t, providerKeeper.IsOptIn(ctx, test.chainID)) - require.True(t, providerKeeper.IsTopN(ctx, test.chainID)) - } - } -} - func TestGetAllOptedIn(t *testing.T) { providerKeeper, ctx, ctrl, _ := testkeeper.GetProviderKeeperAndCtx(t, testkeeper.NewInMemKeeperParams(t)) defer ctrl.Finish() - expectedOptedInValidators := []types.ProviderConsAddress{ - types.NewProviderConsAddress([]byte("providerAddr1")), - types.NewProviderConsAddress([]byte("providerAddr2")), - types.NewProviderConsAddress([]byte("providerAddr3")), + expectedOptedInValidators := []providertypes.ProviderConsAddress{ + providertypes.NewProviderConsAddress([]byte("providerAddr1")), + providertypes.NewProviderConsAddress([]byte("providerAddr2")), + providertypes.NewProviderConsAddress([]byte("providerAddr3")), } for _, expectedOptedInValidator := range expectedOptedInValidators { - providerKeeper.SetOptedIn(ctx, "chainID", expectedOptedInValidator) + providerKeeper.SetOptedIn(ctx, "consumerId", expectedOptedInValidator) } - actualOptedInValidators := providerKeeper.GetAllOptedIn(ctx, "chainID") + actualOptedInValidators := providerKeeper.GetAllOptedIn(ctx, "consumerId") // sort validators first to be able to compare - sortOptedInValidators := func(addresses []types.ProviderConsAddress) { + sortOptedInValidators := func(addresses []providertypes.ProviderConsAddress) { sort.Slice(addresses, func(i, j int) bool { return bytes.Compare(addresses[i].ToSdkConsAddr(), addresses[j].ToSdkConsAddr()) < 0 }) @@ -435,22 +321,22 @@ func TestOptedIn(t *testing.T) { providerKeeper, ctx, ctrl, _ := testkeeper.GetProviderKeeperAndCtx(t, testkeeper.NewInMemKeeperParams(t)) defer ctrl.Finish() - optedInValidator1 := types.NewProviderConsAddress([]byte("providerAddr1")) - optedInValidator2 := types.NewProviderConsAddress([]byte("providerAddr2")) - - require.False(t, providerKeeper.IsOptedIn(ctx, "chainID", optedInValidator1)) - providerKeeper.SetOptedIn(ctx, "chainID", optedInValidator1) - require.True(t, providerKeeper.IsOptedIn(ctx, "chainID", optedInValidator1)) - providerKeeper.DeleteOptedIn(ctx, "chainID", optedInValidator1) - require.False(t, providerKeeper.IsOptedIn(ctx, "chainID", optedInValidator1)) - - providerKeeper.SetOptedIn(ctx, "chainID", optedInValidator1) - providerKeeper.SetOptedIn(ctx, "chainID", optedInValidator2) - require.True(t, providerKeeper.IsOptedIn(ctx, "chainID", optedInValidator1)) - require.True(t, providerKeeper.IsOptedIn(ctx, "chainID", optedInValidator2)) - providerKeeper.DeleteAllOptedIn(ctx, "chainID") - require.False(t, providerKeeper.IsOptedIn(ctx, "chainID", optedInValidator1)) - require.False(t, providerKeeper.IsOptedIn(ctx, "chainID", optedInValidator2)) + optedInValidator1 := providertypes.NewProviderConsAddress([]byte("providerAddr1")) + optedInValidator2 := providertypes.NewProviderConsAddress([]byte("providerAddr2")) + + require.False(t, providerKeeper.IsOptedIn(ctx, "consumerId", optedInValidator1)) + providerKeeper.SetOptedIn(ctx, "consumerId", optedInValidator1) + require.True(t, providerKeeper.IsOptedIn(ctx, "consumerId", optedInValidator1)) + providerKeeper.DeleteOptedIn(ctx, "consumerId", optedInValidator1) + require.False(t, providerKeeper.IsOptedIn(ctx, "consumerId", optedInValidator1)) + + providerKeeper.SetOptedIn(ctx, "consumerId", optedInValidator1) + providerKeeper.SetOptedIn(ctx, "consumerId", optedInValidator2) + require.True(t, providerKeeper.IsOptedIn(ctx, "consumerId", optedInValidator1)) + require.True(t, providerKeeper.IsOptedIn(ctx, "consumerId", optedInValidator2)) + providerKeeper.DeleteAllOptedIn(ctx, "consumerId") + require.False(t, providerKeeper.IsOptedIn(ctx, "consumerId", optedInValidator1)) + require.False(t, providerKeeper.IsOptedIn(ctx, "consumerId", optedInValidator2)) } // TestConsumerCommissionRate tests the `SetConsumerCommissionRate`, `GetConsumerCommissionRate`, and `DeleteConsumerCommissionRate` methods @@ -458,211 +344,78 @@ func TestConsumerCommissionRate(t *testing.T) { providerKeeper, ctx, ctrl, _ := testkeeper.GetProviderKeeperAndCtx(t, testkeeper.NewInMemKeeperParams(t)) defer ctrl.Finish() - providerAddr1 := types.NewProviderConsAddress([]byte("providerAddr1")) - providerAddr2 := types.NewProviderConsAddress([]byte("providerAddr2")) + providerAddr1 := providertypes.NewProviderConsAddress([]byte("providerAddr1")) + providerAddr2 := providertypes.NewProviderConsAddress([]byte("providerAddr2")) - cr, found := providerKeeper.GetConsumerCommissionRate(ctx, "chainID", providerAddr1) + cr, found := providerKeeper.GetConsumerCommissionRate(ctx, "consumerId", providerAddr1) require.False(t, found) require.Equal(t, math.LegacyZeroDec(), cr) - providerKeeper.SetConsumerCommissionRate(ctx, "chainID", providerAddr1, math.LegacyOneDec()) - cr, found = providerKeeper.GetConsumerCommissionRate(ctx, "chainID", providerAddr1) + providerKeeper.SetConsumerCommissionRate(ctx, "consumerId", providerAddr1, math.LegacyOneDec()) + cr, found = providerKeeper.GetConsumerCommissionRate(ctx, "consumerId", providerAddr1) require.True(t, found) require.Equal(t, math.LegacyOneDec(), cr) - providerKeeper.SetConsumerCommissionRate(ctx, "chainID", providerAddr2, math.LegacyZeroDec()) - cr, found = providerKeeper.GetConsumerCommissionRate(ctx, "chainID", providerAddr2) + providerKeeper.SetConsumerCommissionRate(ctx, "consumerId", providerAddr2, math.LegacyZeroDec()) + cr, found = providerKeeper.GetConsumerCommissionRate(ctx, "consumerId", providerAddr2) require.True(t, found) require.Equal(t, math.LegacyZeroDec(), cr) - provAddrs := providerKeeper.GetAllCommissionRateValidators(ctx, "chainID") + provAddrs := providerKeeper.GetAllCommissionRateValidators(ctx, "consumerId") require.Len(t, provAddrs, 2) for _, addr := range provAddrs { - providerKeeper.DeleteConsumerCommissionRate(ctx, "chainID", addr) + providerKeeper.DeleteConsumerCommissionRate(ctx, "consumerId", addr) } - _, found = providerKeeper.GetConsumerCommissionRate(ctx, "chainID", providerAddr1) + _, found = providerKeeper.GetConsumerCommissionRate(ctx, "consumerId", providerAddr1) require.False(t, found) - _, found = providerKeeper.GetConsumerCommissionRate(ctx, "chainID", providerAddr2) + _, found = providerKeeper.GetConsumerCommissionRate(ctx, "consumerId", providerAddr2) require.False(t, found) } -// TestAllowlist tests the `SetAllowlist`, `IsAllowlisted`, `DeleteAllowlist`, and `IsAllowlistEmpty` methods -func TestAllowlist(t *testing.T) { +// TestConsumerClientId tests the getter, setter, and deletion of the client id <> consumer id mappings +func TestConsumerClientId(t *testing.T) { providerKeeper, ctx, ctrl, _ := testkeeper.GetProviderKeeperAndCtx(t, testkeeper.NewInMemKeeperParams(t)) defer ctrl.Finish() - chainID := "chainID" - - // no validator was allowlisted and hence the allowlist is empty - require.True(t, providerKeeper.IsAllowlistEmpty(ctx, chainID)) - - providerAddr1 := types.NewProviderConsAddress([]byte("providerAddr1")) - providerKeeper.SetAllowlist(ctx, chainID, providerAddr1) - require.True(t, providerKeeper.IsAllowlisted(ctx, chainID, providerAddr1)) - - // allowlist is not empty anymore - require.False(t, providerKeeper.IsAllowlistEmpty(ctx, chainID)) + consumerId := "123" + clientIds := []string{"clientId1", "clientId2"} - providerAddr2 := types.NewProviderConsAddress([]byte("providerAddr2")) - providerKeeper.SetAllowlist(ctx, chainID, providerAddr2) - require.True(t, providerKeeper.IsAllowlisted(ctx, chainID, providerAddr2)) - require.False(t, providerKeeper.IsAllowlistEmpty(ctx, chainID)) - - providerKeeper.DeleteAllowlist(ctx, chainID) - require.False(t, providerKeeper.IsAllowlisted(ctx, chainID, providerAddr1)) - require.False(t, providerKeeper.IsAllowlisted(ctx, chainID, providerAddr2)) - require.True(t, providerKeeper.IsAllowlistEmpty(ctx, chainID)) -} - -// TestDenylist tests the `SetDenylist`, `IsDenylisted`, `DeleteDenylist`, and `IsDenylistEmpty` methods -func TestDenylist(t *testing.T) { - providerKeeper, ctx, ctrl, _ := testkeeper.GetProviderKeeperAndCtx(t, testkeeper.NewInMemKeeperParams(t)) - defer ctrl.Finish() - - chainID := "chainID" - - // no validator was denylisted and hence the denylist is empty - require.True(t, providerKeeper.IsDenylistEmpty(ctx, chainID)) - - providerAddr1 := types.NewProviderConsAddress([]byte("providerAddr1")) - providerKeeper.SetDenylist(ctx, chainID, providerAddr1) - require.True(t, providerKeeper.IsDenylisted(ctx, chainID, providerAddr1)) - - // denylist is not empty anymore - require.False(t, providerKeeper.IsDenylistEmpty(ctx, chainID)) - - providerAddr2 := types.NewProviderConsAddress([]byte("providerAddr2")) - providerKeeper.SetDenylist(ctx, chainID, providerAddr2) - require.True(t, providerKeeper.IsDenylisted(ctx, chainID, providerAddr2)) - require.False(t, providerKeeper.IsDenylistEmpty(ctx, chainID)) - - providerKeeper.DeleteDenylist(ctx, chainID) - require.False(t, providerKeeper.IsDenylisted(ctx, chainID, providerAddr1)) - require.False(t, providerKeeper.IsDenylisted(ctx, chainID, providerAddr2)) - require.True(t, providerKeeper.IsDenylistEmpty(ctx, chainID)) -} - -// TestAllowInactiveValidators tests the `SetAllowInactiveValidators` and `AllowsInactiveValidators` methods -func TestAllowInactiveValidators(t *testing.T) { - k, ctx, _, _ := testkeeper.GetProviderKeeperAndCtx(t, testkeeper.NewInMemKeeperParams(t)) - - chainID := "chainID" - - // check that by default, AllowsInactiveValidators returns false - require.False(t, k.AllowsInactiveValidators(ctx, chainID)) - - // set the chain to allow inactive validators - k.SetInactiveValidatorsAllowed(ctx, chainID, true) - - // check that AllowsInactiveValidators returns true - require.True(t, k.AllowsInactiveValidators(ctx, chainID)) - - // set the chain to not allow inactive validators - k.SetInactiveValidatorsAllowed(ctx, chainID, false) - - // check that AllowsInactiveValidators returns false - require.False(t, k.AllowsInactiveValidators(ctx, chainID)) -} - -// Tests setting, getting and deleting parameters that are stored per-consumer chain. -// The tests cover the following parameters: -// - MinimumPowerInTopN -// - MinStake -// - ValidatorSetCap -// - ValidatorPowersCap -func TestKeeperConsumerParams(t *testing.T) { - k, ctx, _, _ := testkeeper.GetProviderKeeperAndCtx(t, testkeeper.NewInMemKeeperParams(t)) - - tests := []struct { - name string - settingFunc func(sdk.Context, string, int64) - getFunc func(sdk.Context, string) (int64, bool) - deleteFunc func(sdk.Context, string) - initialValue int64 - updatedValue int64 - }{ - { - name: "Minimum Power In Top N", - settingFunc: func(ctx sdk.Context, id string, val int64) { k.SetMinimumPowerInTopN(ctx, id, val) }, - getFunc: func(ctx sdk.Context, id string) (int64, bool) { return k.GetMinimumPowerInTopN(ctx, id) }, - deleteFunc: func(ctx sdk.Context, id string) { k.DeleteMinimumPowerInTopN(ctx, id) }, - initialValue: 1000, - updatedValue: 2000, - }, - { - name: "Minimum Stake", - settingFunc: func(ctx sdk.Context, id string, val int64) { k.SetMinStake(ctx, id, uint64(val)) }, - getFunc: func(ctx sdk.Context, id string) (int64, bool) { - val, found := k.GetMinStake(ctx, id) - return int64(val), found - }, - deleteFunc: func(ctx sdk.Context, id string) { k.DeleteMinStake(ctx, id) }, - initialValue: 1000, - updatedValue: 2000, - }, - { - name: "Validator Set Cap", - settingFunc: func(ctx sdk.Context, id string, val int64) { k.SetValidatorSetCap(ctx, id, uint32(val)) }, - getFunc: func(ctx sdk.Context, id string) (int64, bool) { - val, found := k.GetValidatorSetCap(ctx, id) - return int64(val), found - }, - deleteFunc: func(ctx sdk.Context, id string) { k.DeleteValidatorSetCap(ctx, id) }, - initialValue: 10, - updatedValue: 200, - }, - { - name: "Validator Powers Cap", - settingFunc: func(ctx sdk.Context, id string, val int64) { k.SetValidatorsPowerCap(ctx, id, uint32(val)) }, - getFunc: func(ctx sdk.Context, id string) (int64, bool) { - val, found := k.GetValidatorsPowerCap(ctx, id) - return int64(val), found - }, - deleteFunc: func(ctx sdk.Context, id string) { k.DeleteValidatorsPowerCap(ctx, id) }, - initialValue: 10, - updatedValue: 11, - }, - } - - for _, tt := range tests { - t.Run(tt.name, func(t *testing.T) { - chainID := "chainID" - // Set initial value - tt.settingFunc(ctx, chainID, int64(tt.initialValue)) - - // Retrieve and check initial value - actualValue, found := tt.getFunc(ctx, chainID) - require.True(t, found) - require.EqualValues(t, tt.initialValue, actualValue) - - // Update value - tt.settingFunc(ctx, chainID, int64(tt.updatedValue)) - - // Retrieve and check updated value - newActualValue, found := tt.getFunc(ctx, chainID) - require.True(t, found) - require.EqualValues(t, tt.updatedValue, newActualValue) - - // Check non-existent chain ID - _, found = tt.getFunc(ctx, "not the chainID") - require.False(t, found) - - // Delete value - tt.deleteFunc(ctx, chainID) + _, found := providerKeeper.GetConsumerClientId(ctx, consumerId) + require.False(t, found) + _, found = providerKeeper.GetClientIdToConsumerId(ctx, clientIds[0]) + require.False(t, found) + _, found = providerKeeper.GetClientIdToConsumerId(ctx, clientIds[1]) + require.False(t, found) - // Check that value was deleted - _, found = tt.getFunc(ctx, chainID) - require.False(t, found) + providerKeeper.SetConsumerClientId(ctx, consumerId, clientIds[0]) + res, found := providerKeeper.GetConsumerClientId(ctx, consumerId) + require.True(t, found) + require.Equal(t, clientIds[0], res) + res, found = providerKeeper.GetClientIdToConsumerId(ctx, clientIds[0]) + require.True(t, found) + require.Equal(t, consumerId, res) + _, found = providerKeeper.GetClientIdToConsumerId(ctx, clientIds[1]) + require.False(t, found) - // Try deleting again - tt.deleteFunc(ctx, chainID) + // overwrite the client ID + providerKeeper.SetConsumerClientId(ctx, consumerId, clientIds[1]) + res, found = providerKeeper.GetConsumerClientId(ctx, consumerId) + require.True(t, found) + require.Equal(t, clientIds[1], res) + res, found = providerKeeper.GetClientIdToConsumerId(ctx, clientIds[1]) + require.True(t, found) + require.Equal(t, consumerId, res) + _, found = providerKeeper.GetClientIdToConsumerId(ctx, clientIds[0]) + require.False(t, found) - // Check that the value is still deleted - _, found = tt.getFunc(ctx, chainID) - require.False(t, found) - }) - } + providerKeeper.DeleteConsumerClientId(ctx, consumerId) + _, found = providerKeeper.GetConsumerClientId(ctx, consumerId) + require.False(t, found) + _, found = providerKeeper.GetClientIdToConsumerId(ctx, clientIds[0]) + require.False(t, found) + _, found = providerKeeper.GetClientIdToConsumerId(ctx, clientIds[1]) + require.False(t, found) } diff --git a/x/ccv/provider/keeper/key_assignment.go b/x/ccv/provider/keeper/key_assignment.go index 23dd20109d..f2f10dd368 100644 --- a/x/ccv/provider/keeper/key_assignment.go +++ b/x/ccv/provider/keeper/key_assignment.go @@ -67,11 +67,11 @@ func (k Keeper) ParseConsumerKey(consumerKey string) (tmprotocrypto.PublicKey, e // GetValidatorConsumerPubKey returns a validator's public key assigned for a consumer chain func (k Keeper) GetValidatorConsumerPubKey( ctx sdk.Context, - chainID string, + consumerId string, providerAddr types.ProviderConsAddress, ) (consumerKey tmprotocrypto.PublicKey, found bool) { store := ctx.KVStore(k.storeKey) - bz := store.Get(types.ConsumerValidatorsKey(chainID, providerAddr)) + bz := store.Get(types.ConsumerValidatorsKey(consumerId, providerAddr)) if bz == nil { return consumerKey, false } @@ -87,7 +87,7 @@ func (k Keeper) GetValidatorConsumerPubKey( // SetValidatorConsumerPubKey sets a validator's public key assigned for a consumer chain func (k Keeper) SetValidatorConsumerPubKey( ctx sdk.Context, - chainID string, + consumerId string, providerAddr types.ProviderConsAddress, consumerKey tmprotocrypto.PublicKey, ) { @@ -98,33 +98,33 @@ func (k Keeper) SetValidatorConsumerPubKey( // the consumer key is obtained from GetValidatorConsumerPubKey, called from panic(fmt.Sprintf("failed to marshal consumer key: %v", err)) } - store.Set(types.ConsumerValidatorsKey(chainID, providerAddr), bz) + store.Set(types.ConsumerValidatorsKey(consumerId, providerAddr), bz) } // GetAllValidatorConsumerPubKeys gets all the validators public keys assigned for a consumer chain -// If chainID is nil, it returns all the validators public keys assigned for all consumer chains +// If consumerId is nil, it returns all the validators public keys assigned for all consumer chains // // Note that the validators public keys assigned for a consumer chain are stored under keys -// with the following format: ConsumerValidatorsBytePrefix | len(chainID) | chainID | providerAddress +// with the following format: ConsumerValidatorsBytePrefix | len(consumerId) | consumerId | providerAddress // Thus, the returned array is -// - in ascending order of providerAddresses, if chainID is not nil; -// - in undetermined order, if chainID is nil. -func (k Keeper) GetAllValidatorConsumerPubKeys(ctx sdk.Context, chainID *string) (validatorConsumerPubKeys []types.ValidatorConsumerPubKey) { +// - in ascending order of providerAddresses, if consumerId is not nil; +// - in undetermined order, if consumerId is nil. +func (k Keeper) GetAllValidatorConsumerPubKeys(ctx sdk.Context, consumerId *string) (validatorConsumerPubKeys []types.ValidatorConsumerPubKey) { store := ctx.KVStore(k.storeKey) var prefix []byte consumerValidatorsKeyPrefix := types.ConsumerValidatorsKeyPrefix() - if chainID == nil { + if consumerId == nil { // iterate over the validators public keys assigned for all consumer chains prefix = []byte{consumerValidatorsKeyPrefix} } else { - // iterate over the validators public keys assigned for chainID - prefix = types.ChainIdWithLenKey(consumerValidatorsKeyPrefix, *chainID) + // iterate over the validators public keys assigned for consumerId + prefix = types.StringIdWithLenKey(consumerValidatorsKeyPrefix, *consumerId) } iterator := storetypes.KVStorePrefixIterator(store, prefix) defer iterator.Close() for ; iterator.Valid(); iterator.Next() { - // TODO: store chainID and provider cons address in value bytes, marshaled as protobuf type - chainID, providerAddrTmp, err := types.ParseChainIdAndConsAddrKey(consumerValidatorsKeyPrefix, iterator.Key()) + // TODO: store consumerId and provider cons address in value bytes, marshaled as protobuf type + consumerId, providerAddrTmp, err := types.ParseStringIdAndConsAddrKey(consumerValidatorsKeyPrefix, iterator.Key()) if err != nil { // An error here would indicate something is very wrong, // the store key is assumed to be correctly serialized in SetValidatorConsumerPubKey. @@ -140,7 +140,7 @@ func (k Keeper) GetAllValidatorConsumerPubKeys(ctx sdk.Context, chainID *string) } validatorConsumerPubKeys = append(validatorConsumerPubKeys, types.ValidatorConsumerPubKey{ - ChainId: chainID, + ChainId: consumerId, ProviderAddr: providerAddr.ToSdkConsAddr(), ConsumerKey: &consumerKey, }) @@ -150,20 +150,20 @@ func (k Keeper) GetAllValidatorConsumerPubKeys(ctx sdk.Context, chainID *string) } // DeleteValidatorConsumerPubKey deletes a validator's public key assigned for a consumer chain -func (k Keeper) DeleteValidatorConsumerPubKey(ctx sdk.Context, chainID string, providerAddr types.ProviderConsAddress) { +func (k Keeper) DeleteValidatorConsumerPubKey(ctx sdk.Context, consumerId string, providerAddr types.ProviderConsAddress) { store := ctx.KVStore(k.storeKey) - store.Delete(types.ConsumerValidatorsKey(chainID, providerAddr)) + store.Delete(types.ConsumerValidatorsKey(consumerId, providerAddr)) } // GetValidatorByConsumerAddr returns a validator's consensus address on the provider // given the validator's consensus address on a consumer func (k Keeper) GetValidatorByConsumerAddr( ctx sdk.Context, - chainID string, + consumerId string, consumerAddr types.ConsumerConsAddress, ) (providerAddr types.ProviderConsAddress, found bool) { store := ctx.KVStore(k.storeKey) - bz := store.Get(types.ValidatorsByConsumerAddrKey(chainID, consumerAddr)) + bz := store.Get(types.ValidatorsByConsumerAddrKey(consumerId, consumerAddr)) if bz == nil { return providerAddr, false } @@ -175,45 +175,45 @@ func (k Keeper) GetValidatorByConsumerAddr( // to the validator's consensus address on the provider func (k Keeper) SetValidatorByConsumerAddr( ctx sdk.Context, - chainID string, + consumerId string, consumerAddr types.ConsumerConsAddress, providerAddr types.ProviderConsAddress, ) { store := ctx.KVStore(k.storeKey) // Cons address is a type alias for a byte string, no marshaling needed bz := providerAddr.ToSdkConsAddr() - store.Set(types.ValidatorsByConsumerAddrKey(chainID, consumerAddr), bz) + store.Set(types.ValidatorsByConsumerAddrKey(consumerId, consumerAddr), bz) } // GetValidatorsByConsumerAddrs gets all the mappings from consensus addresses // on a given consumer chain to consensus addresses on the provider chain. -// If chainID is nil, it returns all the mappings from consensus addresses on all consumer chains. +// If consumerId is nil, it returns all the mappings from consensus addresses on all consumer chains. // // Note that the mappings for a consumer chain are stored under keys with the following format: -// ValidatorsByConsumerAddrKeyPrefix | len(chainID) | chainID | consumerAddress +// ValidatorsByConsumerAddrKeyPrefix | len(consumerId) | consumerId | consumerAddress // Thus, the returned array is -// - in ascending order of consumerAddresses, if chainID is not nil; -// - in undetermined order, if chainID is nil. -func (k Keeper) GetAllValidatorsByConsumerAddr(ctx sdk.Context, chainID *string) (validatorConsumerAddrs []types.ValidatorByConsumerAddr) { +// - in ascending order of consumerAddresses, if consumerId is not nil; +// - in undetermined order, if consumerId is nil. +func (k Keeper) GetAllValidatorsByConsumerAddr(ctx sdk.Context, consumerId *string) (validatorConsumerAddrs []types.ValidatorByConsumerAddr) { store := ctx.KVStore(k.storeKey) var prefix []byte validatorsByConsumerAddrKeyPrefix := types.ValidatorsByConsumerAddrKeyPrefix() - if chainID == nil { + if consumerId == nil { // iterate over the mappings from consensus addresses on all consumer chains prefix = []byte{validatorsByConsumerAddrKeyPrefix} } else { - // iterate over the mappings from consensus addresses on chainID - prefix = types.ChainIdWithLenKey(validatorsByConsumerAddrKeyPrefix, *chainID) + // iterate over the mappings from consensus addresses on consumerId + prefix = types.StringIdWithLenKey(validatorsByConsumerAddrKeyPrefix, *consumerId) } iterator := storetypes.KVStorePrefixIterator(store, prefix) defer iterator.Close() for ; iterator.Valid(); iterator.Next() { - // TODO: store chainID and consumer cons address in value bytes, marshaled as protobuf type - chainID, consumerAddrTmp, err := types.ParseChainIdAndConsAddrKey(validatorsByConsumerAddrKeyPrefix, iterator.Key()) + // TODO: store consumerId and consumer cons address in value bytes, marshaled as protobuf type + consumerId, consumerAddrTmp, err := types.ParseStringIdAndConsAddrKey(validatorsByConsumerAddrKeyPrefix, iterator.Key()) if err != nil { // An error here would indicate something is very wrong, // store keys are assumed to be correctly serialized in SetValidatorByConsumerAddr. - panic(fmt.Sprintf("failed to parse chainID and consumer address: %v", err)) + panic(fmt.Sprintf("failed to parse consumerId and consumer address: %v", err)) } consumerAddr := types.NewConsumerConsAddress(consumerAddrTmp) providerAddr := types.NewProviderConsAddress(iterator.Value()) @@ -221,7 +221,7 @@ func (k Keeper) GetAllValidatorsByConsumerAddr(ctx sdk.Context, chainID *string) validatorConsumerAddrs = append(validatorConsumerAddrs, types.ValidatorByConsumerAddr{ ConsumerAddr: consumerAddr.ToSdkConsAddr(), ProviderAddr: providerAddr.ToSdkConsAddr(), - ChainId: chainID, + ChainId: consumerId, }) } @@ -230,9 +230,9 @@ func (k Keeper) GetAllValidatorsByConsumerAddr(ctx sdk.Context, chainID *string) // DeleteValidatorByConsumerAddr deletes the mapping from a validator's consensus address on a consumer // to the validator's consensus address on the provider -func (k Keeper) DeleteValidatorByConsumerAddr(ctx sdk.Context, chainID string, consumerAddr types.ConsumerConsAddress) { +func (k Keeper) DeleteValidatorByConsumerAddr(ctx sdk.Context, consumerId string, consumerAddr types.ConsumerConsAddress) { store := ctx.KVStore(k.storeKey) - store.Delete(types.ValidatorsByConsumerAddrKey(chainID, consumerAddr)) + store.Delete(types.ValidatorsByConsumerAddrKey(consumerId, consumerAddr)) } // AppendConsumerAddrsToPrune appends a consumer validator address to the list of consumer addresses @@ -245,12 +245,12 @@ func (k Keeper) DeleteValidatorByConsumerAddr(ctx sdk.Context, chainID string, c // - or there exists a timestamp in ConsumerAddrsToPrune s.t. cAddr in ConsumerAddrsToPrune(timestamp) func (k Keeper) AppendConsumerAddrsToPrune( ctx sdk.Context, - chainID string, + consumerId string, pruneTs time.Time, consumerAddr types.ConsumerConsAddress, ) { store := ctx.KVStore(k.storeKey) - storeKey := types.ConsumerAddrsToPruneV2Key(chainID, pruneTs) + storeKey := types.ConsumerAddrsToPruneV2Key(consumerId, pruneTs) bz := store.Get(storeKey) var consumerAddrsToPrune types.AddressList if bz != nil { @@ -275,12 +275,12 @@ func (k Keeper) AppendConsumerAddrsToPrune( // Note that this method is only used in testing. func (k Keeper) GetConsumerAddrsToPrune( ctx sdk.Context, - chainID string, + consumerId string, ts time.Time, ) (consumerAddrsToPrune types.AddressList) { store := ctx.KVStore(k.storeKey) - bz := store.Get(types.ConsumerAddrsToPruneV2Key(chainID, ts)) + bz := store.Get(types.ConsumerAddrsToPruneV2Key(consumerId, ts)) if bz == nil { return } @@ -297,28 +297,28 @@ func (k Keeper) GetConsumerAddrsToPrune( // The returned addresses are removed from the store. // // Note that the list of all consumer addresses is stored under keys with the following format: -// ConsumerAddrsToPruneV2BytePrefix | len(chainID) | chainID | timestamp +// ConsumerAddrsToPruneV2BytePrefix | len(consumerId) | consumerId | timestamp // Thus, this method returns all the consumer addresses stored under keys in the following range: -// (ConsumerAddrsToPruneV2BytePrefix | len(chainID) | chainID | ts') where ts' <= ts +// (ConsumerAddrsToPruneV2BytePrefix | len(consumerId) | consumerId | ts') where ts' <= ts func (k Keeper) ConsumeConsumerAddrsToPrune( ctx sdk.Context, - chainID string, + consumerId string, ts time.Time, ) (consumerAddrsToPrune types.AddressList) { store := ctx.KVStore(k.storeKey) consumerAddrsToPruneKeyPrefix := types.ConsumerAddrsToPruneV2KeyPrefix() - startPrefix := types.ChainIdWithLenKey(consumerAddrsToPruneKeyPrefix, chainID) + startPrefix := types.StringIdWithLenKey(consumerAddrsToPruneKeyPrefix, consumerId) iterator := store.Iterator(startPrefix, - storetypes.InclusiveEndBytes(types.ConsumerAddrsToPruneV2Key(chainID, ts))) + storetypes.InclusiveEndBytes(types.ConsumerAddrsToPruneV2Key(consumerId, ts))) defer iterator.Close() var keysToDel [][]byte for ; iterator.Valid(); iterator.Next() { // Sanity check - if _, pruneTs, err := types.ParseChainIdAndTsKey(consumerAddrsToPruneKeyPrefix, iterator.Key()); err != nil { + if _, pruneTs, err := types.ParseStringIdAndTsKey(consumerAddrsToPruneKeyPrefix, iterator.Key()); err != nil { // An error here would indicate something is very wrong, // store keys are assumed to be correctly serialized in AppendConsumerAddrsToPrune. - k.Logger(ctx).Error("ParseChainIdAndTsKey failed", + k.Logger(ctx).Error("ParseStringIdAndTsKey failed", "key", string(iterator.Key()), "error", err.Error(), ) @@ -352,19 +352,19 @@ func (k Keeper) ConsumeConsumerAddrsToPrune( return } -// GetAllConsumerAddrsToPrune gets all consumer addresses that can be eventually pruned for a given chainID. +// GetAllConsumerAddrsToPrune gets all consumer addresses that can be eventually pruned for a given consumerId. // // Note that the list of all consumer addresses is stored under keys with the following format: -// ConsumerAddrsToPruneV2BytePrefix | len(chainID) | chainID | timestamp +// ConsumerAddrsToPruneV2BytePrefix | len(consumerId) | consumerId | timestamp // Thus, the returned array is in ascending order of timestamps. -func (k Keeper) GetAllConsumerAddrsToPrune(ctx sdk.Context, chainID string) (consumerAddrsToPrune []types.ConsumerAddrsToPruneV2) { +func (k Keeper) GetAllConsumerAddrsToPrune(ctx sdk.Context, consumerId string) (consumerAddrsToPrune []types.ConsumerAddrsToPruneV2) { store := ctx.KVStore(k.storeKey) consumerAddrsToPruneKeyPrefix := types.ConsumerAddrsToPruneV2KeyPrefix() - iteratorPrefix := types.ChainIdWithLenKey(consumerAddrsToPruneKeyPrefix, chainID) + iteratorPrefix := types.StringIdWithLenKey(consumerAddrsToPruneKeyPrefix, consumerId) iterator := storetypes.KVStorePrefixIterator(store, iteratorPrefix) defer iterator.Close() for ; iterator.Valid(); iterator.Next() { - _, ts, err := types.ParseChainIdAndTsKey(consumerAddrsToPruneKeyPrefix, iterator.Key()) + _, ts, err := types.ParseStringIdAndTsKey(consumerAddrsToPruneKeyPrefix, iterator.Key()) if err != nil { // An error here would indicate something is very wrong, // store keys are assumed to be correctly serialized in AppendConsumerAddrsToPrune. @@ -381,7 +381,7 @@ func (k Keeper) GetAllConsumerAddrsToPrune(ctx sdk.Context, chainID string) (con consumerAddrsToPrune = append(consumerAddrsToPrune, types.ConsumerAddrsToPruneV2{ PruneTs: ts, ConsumerAddrs: &addrs, - ChainId: chainID, + ChainId: consumerId, }) } @@ -389,26 +389,25 @@ func (k Keeper) GetAllConsumerAddrsToPrune(ctx sdk.Context, chainID string) (con } // DeleteConsumerAddrsToPruneV2 deletes the list of consumer addresses mapped to a timestamp -func (k Keeper) DeleteConsumerAddrsToPrune(ctx sdk.Context, chainID string, pruneTs time.Time) { +func (k Keeper) DeleteConsumerAddrsToPrune(ctx sdk.Context, consumerId string, pruneTs time.Time) { store := ctx.KVStore(k.storeKey) - store.Delete(types.ConsumerAddrsToPruneV2Key(chainID, pruneTs)) + store.Delete(types.ConsumerAddrsToPruneV2Key(consumerId, pruneTs)) } // AssignConsumerKey assigns the consumerKey to the validator with providerAddr -// on the consumer chain with ID chainID, if it is either registered or currently +// on the consumer chain with the given `consumerId`, if it is either registered or currently // voted on in a ConsumerAddition governance proposal func (k Keeper) AssignConsumerKey( ctx sdk.Context, - chainID string, + consumerId string, validator stakingtypes.Validator, consumerKey tmprotocrypto.PublicKey, ) error { - // check that the consumer chain is either registered or that - // a ConsumerAdditionProposal was submitted. - if !k.IsConsumerProposedOrRegistered(ctx, chainID) { + if !k.IsConsumerActive(ctx, consumerId) { + // check that the consumer chain is either registered, initialized, or launched return errorsmod.Wrapf( - types.ErrUnknownConsumerChainId, chainID, - ) + types.ErrInvalidPhase, + "cannot assign a key to a consumer chain that is not in the registered, initialized, or launched phase: %s", consumerId) } consAddrTmp, err := ccvtypes.TMCryptoPublicKeyToConsAddr(consumerKey) @@ -433,7 +432,7 @@ func (k Keeper) AssignConsumerKey( } // We prevent a validator from assigning the default provider key as a consumer key // if it has not already assigned a different consumer key - _, found := k.GetValidatorConsumerPubKey(ctx, chainID, providerAddr) + _, found := k.GetValidatorConsumerPubKey(ctx, consumerId, providerAddr) if !found { return errorsmod.Wrapf( types.ErrCannotAssignDefaultKeyAssignment, @@ -442,7 +441,7 @@ func (k Keeper) AssignConsumerKey( } } - if _, found := k.GetValidatorByConsumerAddr(ctx, chainID, consumerAddr); found { + if _, found := k.GetValidatorByConsumerAddr(ctx, consumerId, consumerAddr); found { // This consumer key is already in use, or it is to be pruned. With this check we prevent another validator // from assigning the same consumer key as some other validator. Additionally, we prevent a validator from // reusing a consumer key that it used in the past and is now to be pruned. @@ -452,16 +451,16 @@ func (k Keeper) AssignConsumerKey( } // get the previous key assigned for this validator on this consumer chain - if oldConsumerKey, found := k.GetValidatorConsumerPubKey(ctx, chainID, providerAddr); found { + if oldConsumerKey, found := k.GetValidatorConsumerPubKey(ctx, consumerId, providerAddr); found { oldConsumerAddrTmp, err := ccvtypes.TMCryptoPublicKeyToConsAddr(oldConsumerKey) if err != nil { return err } oldConsumerAddr := types.NewConsumerConsAddress(oldConsumerAddrTmp) - // check whether the consumer chain is already registered, - // i.e., a client to the consumer was already created - if _, consumerRegistered := k.GetConsumerClientId(ctx, chainID); consumerRegistered { + // check whether the consumer chain has already launched (i.e., a client to the consumer was already created) + phase := k.GetConsumerPhase(ctx, consumerId) + if phase == types.CONSUMER_PHASE_LAUNCHED { // mark the old consumer address as prunable once UnbondingPeriod elapses; // note: this state is removed on EndBlock unbondingPeriod, err := k.stakingKeeper.UnbondingTime(ctx) @@ -470,26 +469,26 @@ func (k Keeper) AssignConsumerKey( } k.AppendConsumerAddrsToPrune( ctx, - chainID, + consumerId, ctx.BlockTime().Add(unbondingPeriod), oldConsumerAddr, ) } else { // if the consumer chain is not registered, then remove the mapping // from the old consumer address to the provider address - k.DeleteValidatorByConsumerAddr(ctx, chainID, oldConsumerAddr) + k.DeleteValidatorByConsumerAddr(ctx, consumerId, oldConsumerAddr) } } // set the mapping from this validator's provider address to the new consumer key; // overwrite if already exists // note: this state is deleted when the validator is removed from the staking module - k.SetValidatorConsumerPubKey(ctx, chainID, providerAddr, consumerKey) + k.SetValidatorConsumerPubKey(ctx, consumerId, providerAddr, consumerKey) // set the mapping from this validator's new consensus address on the consumer // to its consensus address on the provider; // note: this state must be deleted through the pruning mechanism - k.SetValidatorByConsumerAddr(ctx, chainID, consumerAddr, providerAddr) + k.SetValidatorByConsumerAddr(ctx, consumerId, consumerAddr, providerAddr) return nil } @@ -498,11 +497,11 @@ func (k Keeper) AssignConsumerKey( // consAddr set as the consensus address on a consumer chain func (k Keeper) GetProviderAddrFromConsumerAddr( ctx sdk.Context, - chainID string, + consumerId string, consumerAddr types.ConsumerConsAddress, ) types.ProviderConsAddress { // check if this address is known only to the consumer chain - if providerConsAddr, found := k.GetValidatorByConsumerAddr(ctx, chainID, consumerAddr); found { + if providerConsAddr, found := k.GetValidatorByConsumerAddr(ctx, consumerId, consumerAddr); found { return providerConsAddr } // If mapping from consumer -> provider addr is not found, there is no assigned key, @@ -512,51 +511,38 @@ func (k Keeper) GetProviderAddrFromConsumerAddr( // PruneKeyAssignments prunes the consumer addresses no longer needed // as they cannot be referenced in slash requests (by a correct consumer) -func (k Keeper) PruneKeyAssignments(ctx sdk.Context, chainID string) { +func (k Keeper) PruneKeyAssignments(ctx sdk.Context, consumerId string) { now := ctx.BlockTime() - consumerAddrs := k.ConsumeConsumerAddrsToPrune(ctx, chainID, now) + consumerAddrs := k.ConsumeConsumerAddrsToPrune(ctx, consumerId, now) for _, addrBz := range consumerAddrs.Addresses { consumerAddr := types.NewConsumerConsAddress(addrBz) - k.DeleteValidatorByConsumerAddr(ctx, chainID, consumerAddr) + k.DeleteValidatorByConsumerAddr(ctx, consumerId, consumerAddr) k.Logger(ctx).Info("consumer address was pruned", - "consumer chainID", chainID, + "consumer consumerId", consumerId, "consumer consensus addr", consumerAddr.String(), ) } } // DeleteKeyAssignments deletes all the state needed for key assignments on a consumer chain -func (k Keeper) DeleteKeyAssignments(ctx sdk.Context, chainID string) { +func (k Keeper) DeleteKeyAssignments(ctx sdk.Context, consumerId string) { // delete ValidatorConsumerPubKey - for _, validatorConsumerAddr := range k.GetAllValidatorConsumerPubKeys(ctx, &chainID) { + for _, validatorConsumerAddr := range k.GetAllValidatorConsumerPubKeys(ctx, &consumerId) { providerAddr := types.NewProviderConsAddress(validatorConsumerAddr.ProviderAddr) - k.DeleteValidatorConsumerPubKey(ctx, chainID, providerAddr) + k.DeleteValidatorConsumerPubKey(ctx, consumerId, providerAddr) } // delete ValidatorsByConsumerAddr - for _, validatorConsumerAddr := range k.GetAllValidatorsByConsumerAddr(ctx, &chainID) { + for _, validatorConsumerAddr := range k.GetAllValidatorsByConsumerAddr(ctx, &consumerId) { consumerAddr := types.NewConsumerConsAddress(validatorConsumerAddr.ConsumerAddr) - k.DeleteValidatorByConsumerAddr(ctx, chainID, consumerAddr) + k.DeleteValidatorByConsumerAddr(ctx, consumerId, consumerAddr) } // delete ValidatorConsumerPubKey - for _, consumerAddrsToPrune := range k.GetAllConsumerAddrsToPrune(ctx, chainID) { - k.DeleteConsumerAddrsToPrune(ctx, chainID, consumerAddrsToPrune.PruneTs) - } -} - -// IsConsumerProposedOrRegistered checks if a consumer chain is either registered, meaning either already running -// or will run soon, or proposed its ConsumerAdditionProposal was submitted but the chain was not yet added to ICS yet. -func (k Keeper) IsConsumerProposedOrRegistered(ctx sdk.Context, chainID string) bool { - allConsumerChains := k.GetAllRegisteredAndProposedChainIDs(ctx) - for _, c := range allConsumerChains { - if c == chainID { - return true - } + for _, consumerAddrsToPrune := range k.GetAllConsumerAddrsToPrune(ctx, consumerId) { + k.DeleteConsumerAddrsToPrune(ctx, consumerId, consumerAddrsToPrune.PruneTs) } - - return false } // ValidatorConsensusKeyInUse checks if the given consensus key is already @@ -578,8 +564,8 @@ func (k Keeper) ValidatorConsensusKeyInUse(ctx sdk.Context, valAddr sdk.ValAddre panic("could not get validator cons addr ") } - allConsumerChains := k.GetAllRegisteredAndProposedChainIDs(ctx) - for _, c := range allConsumerChains { + allConsumerIds := k.GetAllActiveConsumerIds(ctx) + for _, c := range allConsumerIds { if _, exist := k.GetValidatorByConsumerAddr(ctx, c, types.NewConsumerConsAddress(consensusAddr), diff --git a/x/ccv/provider/keeper/key_assignment_test.go b/x/ccv/provider/keeper/key_assignment_test.go index 7dbec09f40..fced8ad7a7 100644 --- a/x/ccv/provider/keeper/key_assignment_test.go +++ b/x/ccv/provider/keeper/key_assignment_test.go @@ -24,7 +24,7 @@ import ( ccvtypes "github.com/cosmos/interchain-security/v5/x/ccv/types" ) -const ChainID = "chainID" +const ChainID = "consumerId" func TestValidatorConsumerPubKeyCRUD(t *testing.T) { chainID := consumer @@ -69,7 +69,7 @@ func TestGetAllValidatorConsumerPubKey(t *testing.T) { }, ) } - // select a chainID with more than two assignments + // select a consumerId with more than two assignments var chainID string for i := range chainIDs { chainID = chainIDs[i] @@ -149,7 +149,7 @@ func TestGetAllValidatorsByConsumerAddr(t *testing.T) { }, ) } - // select a chainID with more than two assignments + // select a consumerId with more than two assignments var chainID string for i := range chainIDs { chainID = chainIDs[i] @@ -261,7 +261,7 @@ func TestGetAllConsumerAddrsToPrune(t *testing.T) { }, ) } - // select a chainID with more than two assignments + // select a consumerId with more than two assignments var chainID string for i := range chainIDs { chainID = chainIDs[i] @@ -342,7 +342,7 @@ func checkCorrectPruningProperty(ctx sdk.Context, k providerkeeper.Keeper, chain } func TestAssignConsensusKeyForConsumerChain(t *testing.T) { - chainID := ChainID + consumerId := "0" providerIdentities := []*cryptotestutil.CryptoIdentity{ cryptotestutil.NewCryptoIdentityFromIntSeed(0), cryptotestutil.NewCryptoIdentityFromIntSeed(1), @@ -359,26 +359,26 @@ func TestAssignConsensusKeyForConsumerChain(t *testing.T) { doActions func(sdk.Context, providerkeeper.Keeper) }{ /* - 0. Consumer not registered: Assign PK0->CK0 and error - 1. Consumer registered: Assign PK0->CK0 and retrieve PK0->CK0 - 2. Consumer registered: Assign PK0->CK0, PK0->CK1 and retrieve PK0->CK1 - 3. Consumer registered: Assign PK0->CK0, PK1->CK0 and error - 4. Consumer registered: Assign PK1->PK0 and error - 5. Consumer proposed: Assign Assign PK0->CK0 and retrieve PK0->CK0 - 6. Consumer proposed: Assign PK0->CK0, PK0->CK1 and retrieve PK0->CK1 - 7. Consumer proposed: Assign PK0->CK0, PK1->CK0 and error - 8. Consumer proposed: Assign PK1->PK0 and error + 0. Consumer not in the right phase: Assign PK0->CK0 and error + 1. Consumer launched: Assign PK0->CK0 and retrieve PK0->CK0 + 2. Consumer launched: Assign PK0->CK0, PK0->CK1 and retrieve PK0->CK1 + 3. Consumer launched: Assign PK0->CK0, PK1->CK0 and error + 4. Consumer launched: Assign PK1->PK0 and error + 5. Consumer registered: Assign PK0->CK0 and retrieve PK0->CK0 + 6. Consumer registered: Assign PK0->CK0, PK0->CK1 and retrieve PK0->CK1 + 7. Consumer registered: Assign PK0->CK0, PK1->CK0 and error + 8. Consumer registered: Assign PK1->PK0 and error */ { name: "0", mockSetup: func(ctx sdk.Context, k providerkeeper.Keeper, mocks testkeeper.MockedKeepers) {}, doActions: func(ctx sdk.Context, k providerkeeper.Keeper) { - err := k.AssignConsumerKey(ctx, chainID, + err := k.AssignConsumerKey(ctx, consumerId, providerIdentities[0].SDKStakingValidator(), consumerIdentities[0].TMProtoCryptoPublicKey(), ) require.Error(t, err) - _, found := k.GetValidatorByConsumerAddr(ctx, chainID, + _, found := k.GetValidatorByConsumerAddr(ctx, consumerId, consumerIdentities[0].ConsumerConsAddress()) require.False(t, found) }, @@ -393,13 +393,13 @@ func TestAssignConsensusKeyForConsumerChain(t *testing.T) { ) }, doActions: func(ctx sdk.Context, k providerkeeper.Keeper) { - k.SetConsumerClientId(ctx, chainID, "") - err := k.AssignConsumerKey(ctx, chainID, + k.SetConsumerPhase(ctx, consumerId, types.CONSUMER_PHASE_LAUNCHED) + err := k.AssignConsumerKey(ctx, consumerId, providerIdentities[0].SDKStakingValidator(), consumerIdentities[0].TMProtoCryptoPublicKey(), ) require.NoError(t, err) - providerAddr, found := k.GetValidatorByConsumerAddr(ctx, chainID, + providerAddr, found := k.GetValidatorByConsumerAddr(ctx, consumerId, consumerIdentities[0].ConsumerConsAddress()) require.True(t, found) require.Equal(t, providerIdentities[0].ProviderConsAddress(), providerAddr) @@ -420,18 +420,18 @@ func TestAssignConsensusKeyForConsumerChain(t *testing.T) { ) }, doActions: func(sdkCtx sdk.Context, k providerkeeper.Keeper) { - k.SetConsumerClientId(sdkCtx, chainID, "") - err := k.AssignConsumerKey(sdkCtx, chainID, + k.SetConsumerPhase(sdkCtx, consumerId, types.CONSUMER_PHASE_LAUNCHED) + err := k.AssignConsumerKey(sdkCtx, consumerId, providerIdentities[0].SDKStakingValidator(), consumerIdentities[0].TMProtoCryptoPublicKey(), ) require.NoError(t, err) - err = k.AssignConsumerKey(sdkCtx, chainID, + err = k.AssignConsumerKey(sdkCtx, consumerId, providerIdentities[0].SDKStakingValidator(), consumerIdentities[1].TMProtoCryptoPublicKey(), ) require.NoError(t, err) - providerAddr, found := k.GetValidatorByConsumerAddr(sdkCtx, chainID, + providerAddr, found := k.GetValidatorByConsumerAddr(sdkCtx, consumerId, consumerIdentities[1].ConsumerConsAddress()) require.True(t, found) require.Equal(t, providerIdentities[0].ProviderConsAddress(), providerAddr) @@ -450,18 +450,18 @@ func TestAssignConsensusKeyForConsumerChain(t *testing.T) { ) }, doActions: func(ctx sdk.Context, k providerkeeper.Keeper) { - k.SetConsumerClientId(ctx, chainID, "") - err := k.AssignConsumerKey(ctx, chainID, + k.SetConsumerPhase(ctx, consumerId, types.CONSUMER_PHASE_LAUNCHED) + err := k.AssignConsumerKey(ctx, consumerId, providerIdentities[0].SDKStakingValidator(), consumerIdentities[0].TMProtoCryptoPublicKey(), ) require.NoError(t, err) - err = k.AssignConsumerKey(ctx, chainID, + err = k.AssignConsumerKey(ctx, consumerId, providerIdentities[1].SDKStakingValidator(), consumerIdentities[0].TMProtoCryptoPublicKey(), ) require.Error(t, err) - providerAddr, found := k.GetValidatorByConsumerAddr(ctx, chainID, + providerAddr, found := k.GetValidatorByConsumerAddr(ctx, consumerId, consumerIdentities[0].ConsumerConsAddress()) require.True(t, found) require.Equal(t, providerIdentities[0].ProviderConsAddress(), providerAddr) @@ -477,8 +477,8 @@ func TestAssignConsensusKeyForConsumerChain(t *testing.T) { ) }, doActions: func(ctx sdk.Context, k providerkeeper.Keeper) { - k.SetConsumerClientId(ctx, chainID, "") - err := k.AssignConsumerKey(ctx, chainID, + k.SetConsumerPhase(ctx, consumerId, types.CONSUMER_PHASE_LAUNCHED) + err := k.AssignConsumerKey(ctx, consumerId, providerIdentities[1].SDKStakingValidator(), providerIdentities[0].TMProtoCryptoPublicKey(), ) @@ -495,13 +495,13 @@ func TestAssignConsensusKeyForConsumerChain(t *testing.T) { ) }, doActions: func(ctx sdk.Context, k providerkeeper.Keeper) { - k.SetProposedConsumerChain(ctx, chainID, 0) - err := k.AssignConsumerKey(ctx, chainID, + k.SetConsumerPhase(ctx, consumerId, types.CONSUMER_PHASE_INITIALIZED) + err := k.AssignConsumerKey(ctx, consumerId, providerIdentities[0].SDKStakingValidator(), consumerIdentities[0].TMProtoCryptoPublicKey(), ) require.NoError(t, err) - providerAddr, found := k.GetValidatorByConsumerAddr(ctx, chainID, + providerAddr, found := k.GetValidatorByConsumerAddr(ctx, consumerId, consumerIdentities[0].ConsumerConsAddress()) require.True(t, found) require.Equal(t, providerIdentities[0].ProviderConsAddress(), providerAddr) @@ -520,18 +520,18 @@ func TestAssignConsensusKeyForConsumerChain(t *testing.T) { ) }, doActions: func(ctx sdk.Context, k providerkeeper.Keeper) { - k.SetProposedConsumerChain(ctx, chainID, 0) - err := k.AssignConsumerKey(ctx, chainID, + k.SetConsumerPhase(ctx, consumerId, types.CONSUMER_PHASE_INITIALIZED) + err := k.AssignConsumerKey(ctx, consumerId, providerIdentities[0].SDKStakingValidator(), consumerIdentities[0].TMProtoCryptoPublicKey(), ) require.NoError(t, err) - err = k.AssignConsumerKey(ctx, chainID, + err = k.AssignConsumerKey(ctx, consumerId, providerIdentities[0].SDKStakingValidator(), consumerIdentities[1].TMProtoCryptoPublicKey(), ) require.NoError(t, err) - providerAddr, found := k.GetValidatorByConsumerAddr(ctx, chainID, + providerAddr, found := k.GetValidatorByConsumerAddr(ctx, consumerId, consumerIdentities[1].ConsumerConsAddress()) require.True(t, found) require.Equal(t, providerIdentities[0].ProviderConsAddress(), providerAddr) @@ -550,18 +550,18 @@ func TestAssignConsensusKeyForConsumerChain(t *testing.T) { ) }, doActions: func(ctx sdk.Context, k providerkeeper.Keeper) { - k.SetProposedConsumerChain(ctx, chainID, 0) - err := k.AssignConsumerKey(ctx, chainID, + k.SetConsumerPhase(ctx, consumerId, types.CONSUMER_PHASE_INITIALIZED) + err := k.AssignConsumerKey(ctx, consumerId, providerIdentities[0].SDKStakingValidator(), consumerIdentities[0].TMProtoCryptoPublicKey(), ) require.NoError(t, err) - err = k.AssignConsumerKey(ctx, chainID, + err = k.AssignConsumerKey(ctx, consumerId, providerIdentities[1].SDKStakingValidator(), consumerIdentities[0].TMProtoCryptoPublicKey(), ) require.Error(t, err) - providerAddr, found := k.GetValidatorByConsumerAddr(ctx, chainID, + providerAddr, found := k.GetValidatorByConsumerAddr(ctx, consumerId, consumerIdentities[0].ConsumerConsAddress()) require.True(t, found) require.Equal(t, providerIdentities[0].ProviderConsAddress(), providerAddr) @@ -577,8 +577,8 @@ func TestAssignConsensusKeyForConsumerChain(t *testing.T) { ) }, doActions: func(ctx sdk.Context, k providerkeeper.Keeper) { - k.SetProposedConsumerChain(ctx, chainID, 0) - err := k.AssignConsumerKey(ctx, chainID, + k.SetConsumerPhase(ctx, consumerId, types.CONSUMER_PHASE_INITIALIZED) + err := k.AssignConsumerKey(ctx, consumerId, providerIdentities[1].SDKStakingValidator(), providerIdentities[0].TMProtoCryptoPublicKey(), ) @@ -593,7 +593,7 @@ func TestAssignConsensusKeyForConsumerChain(t *testing.T) { tc.mockSetup(ctx, k, mocks) tc.doActions(ctx, k) - require.True(t, checkCorrectPruningProperty(ctx, k, chainID)) + require.True(t, checkCorrectPruningProperty(ctx, k, consumerId)) ctrl.Finish() }) @@ -613,9 +613,7 @@ func TestCannotReassignDefaultKeyAssignment(t *testing.T) { providerKeeper, ctx, ctrl, mocks := testkeeper.GetProviderKeeperAndCtx(t, testkeeper.NewInMemKeeperParams(t)) defer ctrl.Finish() - providerKeeper.SetPendingConsumerAdditionProp(ctx, &types.ConsumerAdditionProposal{ - ChainId: "chain", - }) + providerKeeper.SetConsumerPhase(ctx, "consumerId", types.CONSUMER_PHASE_INITIALIZED) // Mock that the validator is validating with the single key, as confirmed by provider's staking keeper gomock.InOrder( @@ -625,7 +623,7 @@ func TestCannotReassignDefaultKeyAssignment(t *testing.T) { ) // AssignConsumerKey should return an error if we try to re-assign the already existing default key assignment - err := providerKeeper.AssignConsumerKey(ctx, "chain", cId.SDKStakingValidator(), cId.TMProtoCryptoPublicKey()) + err := providerKeeper.AssignConsumerKey(ctx, "consumerId", cId.SDKStakingValidator(), cId.TMProtoCryptoPublicKey()) require.Error(t, err) // Confirm we're not returning an error for some other reason diff --git a/x/ccv/provider/keeper/legacy_proposal.go b/x/ccv/provider/keeper/legacy_proposal.go deleted file mode 100644 index d14773e5ed..0000000000 --- a/x/ccv/provider/keeper/legacy_proposal.go +++ /dev/null @@ -1,144 +0,0 @@ -package keeper - -import ( - errorsmod "cosmossdk.io/errors" - sdk "github.com/cosmos/cosmos-sdk/types" - - "github.com/cosmos/interchain-security/v5/x/ccv/provider/types" -) - -func (k Keeper) HandleLegacyConsumerRewardDenomProposal(ctx sdk.Context, p *types.ChangeRewardDenomsProposal) error { - for _, denomToAdd := range p.DenomsToAdd { - // Log error and move on if one of the denoms is already registered - if k.ConsumerRewardDenomExists(ctx, denomToAdd) { - ctx.Logger().Error("denom %s already registered", denomToAdd) - continue - } - k.SetConsumerRewardDenom(ctx, denomToAdd) - ctx.EventManager().EmitEvent(sdk.NewEvent( - types.EventTypeAddConsumerRewardDenom, - sdk.NewAttribute(types.AttributeConsumerRewardDenom, denomToAdd), - )) - } - for _, denomToRemove := range p.DenomsToRemove { - // Log error and move on if one of the denoms is not registered - if !k.ConsumerRewardDenomExists(ctx, denomToRemove) { - ctx.Logger().Error("denom %s not registered", denomToRemove) - continue - } - k.DeleteConsumerRewardDenom(ctx, denomToRemove) - ctx.EventManager().EmitEvent(sdk.NewEvent( - types.EventTypeRemoveConsumerRewardDenom, - sdk.NewAttribute(types.AttributeConsumerRewardDenom, denomToRemove), - )) - } - return nil -} - -// HandleConsumerAdditionProposal will receive the consumer chain's client state from the proposal. -// If the client can be successfully created in a cached context, it stores the proposal as a pending proposal. -// -// Note: This method implements SpawnConsumerChainProposalHandler in spec. -// See: https://github.com/cosmos/ibc/blob/main/spec/app/ics-028-cross-chain-validation/methods.md#ccv-pcf-hcaprop1 -// Spec tag: [CCV-PCF-HCAPROP.1] -func (k Keeper) HandleLegacyConsumerAdditionProposal(ctx sdk.Context, p *types.ConsumerAdditionProposal) error { - // verify the consumer addition proposal execution - // in cached context and discard the cached writes - if _, _, err := k.CreateConsumerClientInCachedCtx(ctx, *p); err != nil { - return err - } - - k.SetPendingConsumerAdditionProp(ctx, p) - - k.Logger(ctx).Info("consumer addition proposal enqueued", - "chainID", p.ChainId, - "title", p.Title, - "spawn time", p.SpawnTime.UTC(), - ) - - return nil -} - -// HandleConsumerRemovalProposal stops a consumer chain and released the outstanding unbonding operations. -// If the consumer can be successfully stopped in a cached context, it stores the proposal as a pending proposal. -// -// This method implements StopConsumerChainProposalHandler from spec. -// See: https://github.com/cosmos/ibc/blob/main/spec/app/ics-028-cross-chain-validation/methods.md#ccv-pcf-hcrprop1 -// Spec tag: [CCV-PCF-HCRPROP.1] -func (k Keeper) HandleLegacyConsumerRemovalProposal(ctx sdk.Context, p *types.ConsumerRemovalProposal) error { - // verify the consumer removal proposal execution - // in cached context and discard the cached writes - if _, _, err := k.StopConsumerChainInCachedCtx(ctx, *p); err != nil { - return err - } - - k.SetPendingConsumerRemovalProp(ctx, p) - - k.Logger(ctx).Info("consumer removal proposal enqueued", - "chainID", p.ChainId, - "title", p.Title, - "stop time", p.StopTime.UTC(), - ) - - return nil -} - -// HandleConsumerModificationProposal modifies a running consumer chain -func (k Keeper) HandleLegacyConsumerModificationProposal(ctx sdk.Context, p *types.ConsumerModificationProposal) error { - if _, found := k.GetConsumerClientId(ctx, p.ChainId); !found { - return errorsmod.Wrapf(types.ErrInvalidConsumerChainID, "consumer %s chain is not running", p.ChainId) - } - - k.SetTopN(ctx, p.ChainId, p.Top_N) - k.SetValidatorsPowerCap(ctx, p.ChainId, p.ValidatorsPowerCap) - k.SetValidatorSetCap(ctx, p.ChainId, p.ValidatorSetCap) - k.SetMinStake(ctx, p.ChainId, p.MinStake) - k.SetInactiveValidatorsAllowed(ctx, p.ChainId, p.AllowInactiveVals) - - k.DeleteAllowlist(ctx, p.ChainId) - for _, address := range p.Allowlist { - consAddr, err := sdk.ConsAddressFromBech32(address) - if err != nil { - continue - } - - k.SetAllowlist(ctx, p.ChainId, types.NewProviderConsAddress(consAddr)) - } - - k.DeleteDenylist(ctx, p.ChainId) - for _, address := range p.Denylist { - consAddr, err := sdk.ConsAddressFromBech32(address) - if err != nil { - continue - } - - k.SetDenylist(ctx, p.ChainId, types.NewProviderConsAddress(consAddr)) - } - - oldTopN, found := k.GetTopN(ctx, p.ChainId) - if !found { - oldTopN = 0 - k.Logger(ctx).Info("consumer chain top N not found, treating as 0", "chainID", p.ChainId) - } - - // if the top N changes, we need to update the new minimum power in top N - if p.Top_N != oldTopN { - if p.Top_N > 0 { - // if the chain receives a non-zero top N value, store the minimum power in the top N - activeValidators, err := k.GetLastProviderConsensusActiveValidators(ctx) - if err != nil { - return err - } - minPower, err := k.ComputeMinPowerInTopN(ctx, activeValidators, p.Top_N) - if err != nil { - return err - } - k.SetMinimumPowerInTopN(ctx, p.ChainId, minPower) - } else { - // if the chain receives a zero top N value, we delete the min power - k.DeleteMinimumPowerInTopN(ctx, p.ChainId) - } - } - - return nil -} diff --git a/x/ccv/provider/keeper/legacy_proposal_test.go b/x/ccv/provider/keeper/legacy_proposal_test.go deleted file mode 100644 index 23c2c6a948..0000000000 --- a/x/ccv/provider/keeper/legacy_proposal_test.go +++ /dev/null @@ -1,334 +0,0 @@ -package keeper_test - -import ( - "testing" - "time" - - clienttypes "github.com/cosmos/ibc-go/v8/modules/core/02-client/types" - "github.com/golang/mock/gomock" - "github.com/stretchr/testify/require" - - sdk "github.com/cosmos/cosmos-sdk/types" - stakingtypes "github.com/cosmos/cosmos-sdk/x/staking/types" - - testkeeper "github.com/cosmos/interchain-security/v5/testutil/keeper" - providerkeeper "github.com/cosmos/interchain-security/v5/x/ccv/provider/keeper" - providertypes "github.com/cosmos/interchain-security/v5/x/ccv/provider/types" -) - -// -// Initialization sub-protocol related tests of proposal.go -// - -// Tests the HandleConsumerAdditionProposal method against the SpawnConsumerChainProposalHandler spec. -// See: https://github.com/cosmos/ibc/blob/main/spec/app/ics-028-cross-chain-validation/methods.md#ccv-pcf-hcaprop1 -// Spec tag: [CCV-PCF-HCAPROP.1] -func TestHandleLegacyConsumerAdditionProposal(t *testing.T) { - type testCase struct { - description string - malleate func(ctx sdk.Context, k providerkeeper.Keeper, chainID string) - prop *providertypes.ConsumerAdditionProposal - // Time when prop is handled - blockTime time.Time - // Whether it's expected that the proposal is successfully verified - // and appended to the pending proposals - expAppendProp bool - } - - // Snapshot times asserted in tests - now := time.Now().UTC() - - tests := []testCase{ - { - description: "expect to append valid proposal", - malleate: func(ctx sdk.Context, k providerkeeper.Keeper, chainID string) {}, - prop: providertypes.NewConsumerAdditionProposal( - "title", - "description", - "chainID", - clienttypes.NewHeight(2, 3), - []byte("gen_hash"), - []byte("bin_hash"), - now, // Spawn time - "0.75", - 10, - "", - 10000, - 100000000000, - 100000000000, - 100000000000, - 0, - 0, - 0, - nil, - nil, - 0, - false, - ).(*providertypes.ConsumerAdditionProposal), - blockTime: now, - expAppendProp: true, - }, - { - description: "expect to not append invalid proposal using an already existing chain id", - malleate: func(ctx sdk.Context, k providerkeeper.Keeper, chainID string) { - k.SetConsumerClientId(ctx, chainID, "anyClientId") - }, - - prop: providertypes.NewConsumerAdditionProposal( - "title", - "description", - "chainID", - clienttypes.NewHeight(2, 3), - []byte("gen_hash"), - []byte("bin_hash"), - now, - "0.75", - 10, - "", - 10000, - 100000000000, - 100000000000, - 100000000000, - 0, - 0, - 0, - nil, - nil, - 0, - false, - ).(*providertypes.ConsumerAdditionProposal), - blockTime: now, - expAppendProp: false, - }, - } - - for _, tc := range tests { - // Common setup - keeperParams := testkeeper.NewInMemKeeperParams(t) - providerKeeper, ctx, ctrl, mocks := testkeeper.GetProviderKeeperAndCtx(t, keeperParams) - providerKeeper.SetParams(ctx, providertypes.DefaultParams()) - ctx = ctx.WithBlockTime(tc.blockTime) - - if tc.expAppendProp { - // Mock calls are only asserted if we expect a client to be created. - testkeeper.SetupMocksForLastBondedValidatorsExpectation(mocks.MockStakingKeeper, 1, []stakingtypes.Validator{}, 1) - gomock.InOrder( - testkeeper.GetMocksForCreateConsumerClient(ctx, &mocks, tc.prop.ChainId, clienttypes.NewHeight(2, 3))..., - ) - } - - tc.malleate(ctx, providerKeeper, tc.prop.ChainId) - - err := providerKeeper.HandleLegacyConsumerAdditionProposal(ctx, tc.prop) - - if tc.expAppendProp { - require.NoError(t, err) - // check that prop was added to the stored pending props - gotProposal, found := providerKeeper.GetPendingConsumerAdditionProp(ctx, tc.prop.SpawnTime, tc.prop.ChainId) - require.True(t, found) - require.Equal(t, *tc.prop, gotProposal) - } else { - require.Error(t, err) - // check that prop wasn't added to the stored pending props - _, found := providerKeeper.GetPendingConsumerAdditionProp(ctx, tc.prop.SpawnTime, tc.prop.ChainId) - require.False(t, found) - } - - ctrl.Finish() - } -} - -// TestHandleConsumerRemovalProposal tests HandleConsumerRemovalProposal against its corresponding spec method. -// -// See: https://github.com/cosmos/ibc/blob/main/spec/app/ics-028-cross-chain-validation/methods.md#ccv-pcf-hcrprop1 -// Spec tag: [CCV-PCF-HCRPROP.1] -func TestHandleLegacyConsumerRemovalProposal(t *testing.T) { - type testCase struct { - description string - setupMocks func(ctx sdk.Context, k providerkeeper.Keeper, chainID string) - - // Consumer removal proposal to handle - prop *providertypes.ConsumerRemovalProposal - // Time when prop is handled - blockTime time.Time - // Whether it's expected that the proposal is successfully verified - // and appended to the pending proposals - expAppendProp bool - - // chainID of the consumer chain - // tests need to check that the CCV channel is not closed prematurely - chainId string - } - - // Snapshot times asserted in tests - now := time.Now().UTC() - hourAfterNow := now.Add(time.Hour).UTC() - hourBeforeNow := now.Add(-time.Hour).UTC() - - tests := []testCase{ - { - description: "valid proposal", - setupMocks: func(ctx sdk.Context, k providerkeeper.Keeper, chainID string) { - k.SetConsumerClientId(ctx, chainID, "ClientID") - }, - prop: providertypes.NewConsumerRemovalProposal( - "title", - "description", - "chainID", - now, - ).(*providertypes.ConsumerRemovalProposal), - blockTime: hourAfterNow, // After stop time. - expAppendProp: true, - chainId: "chainID", - }, - { - description: "valid proposal - stop_time in the past", - setupMocks: func(ctx sdk.Context, k providerkeeper.Keeper, chainID string) { - k.SetConsumerClientId(ctx, chainID, "ClientID") - }, - prop: providertypes.NewConsumerRemovalProposal( - "title", - "description", - "chainID", - hourBeforeNow, - ).(*providertypes.ConsumerRemovalProposal), - blockTime: hourAfterNow, // After stop time. - expAppendProp: true, - chainId: "chainID", - }, - { - description: "valid proposal - before stop_time in the future", - setupMocks: func(ctx sdk.Context, k providerkeeper.Keeper, chainID string) { - k.SetConsumerClientId(ctx, chainID, "ClientID") - }, - prop: providertypes.NewConsumerRemovalProposal( - "title", - "description", - "chainID", - hourAfterNow, - ).(*providertypes.ConsumerRemovalProposal), - blockTime: now, - expAppendProp: true, - chainId: "chainID", - }, - { - description: "rejected valid proposal - consumer chain does not exist", - setupMocks: func(ctx sdk.Context, k providerkeeper.Keeper, chainID string) {}, - prop: providertypes.NewConsumerRemovalProposal( - "title", - "description", - "chainID-2", - hourAfterNow, - ).(*providertypes.ConsumerRemovalProposal), - blockTime: hourAfterNow, // After stop time. - expAppendProp: false, - chainId: "chainID-2", - }, - } - - for _, tc := range tests { - - // Common setup - keeperParams := testkeeper.NewInMemKeeperParams(t) - providerKeeper, ctx, ctrl, mocks := testkeeper.GetProviderKeeperAndCtx(t, keeperParams) - providerKeeper.SetParams(ctx, providertypes.DefaultParams()) - ctx = ctx.WithBlockTime(tc.blockTime) - - // Mock expectations and setup for stopping the consumer chain, if applicable - // Note: when expAppendProp is false, no mocks are setup, - // meaning no external keeper methods are allowed to be called. - if tc.expAppendProp { - testkeeper.SetupForStoppingConsumerChain(t, ctx, &providerKeeper, mocks) - // Valid client creation is asserted with mock expectations here - gomock.InOrder(testkeeper.GetMocksForStopConsumerChainWithCloseChannel(ctx, &mocks)...) - } - - tc.setupMocks(ctx, providerKeeper, tc.prop.ChainId) - - err := providerKeeper.HandleLegacyConsumerRemovalProposal(ctx, tc.prop) - - if tc.expAppendProp { - require.NoError(t, err) - - // Proposal should be stored as pending - found := providerKeeper.PendingConsumerRemovalPropExists(ctx, tc.prop.ChainId, tc.prop.StopTime) - require.True(t, found) - - // confirm that the channel was not closed - _, found = providerKeeper.GetChainToChannel(ctx, tc.chainId) - require.True(t, found) - } else { - require.Error(t, err) - - // Expect no pending proposal to exist - found := providerKeeper.PendingConsumerRemovalPropExists(ctx, tc.prop.ChainId, tc.prop.StopTime) - require.False(t, found) - } - - // Assert mock calls from setup function - ctrl.Finish() - } -} - -func TestHandleConsumerModificationProposal(t *testing.T) { - providerKeeper, ctx, ctrl, _ := testkeeper.GetProviderKeeperAndCtx(t, testkeeper.NewInMemKeeperParams(t)) - defer ctrl.Finish() - - chainID := "chainID" - - // set up a consumer client, so it seems that "chainID" is running - providerKeeper.SetConsumerClientId(ctx, "chainID", "clientID") - - // set PSS-related fields to update them later on - providerKeeper.SetTopN(ctx, chainID, 50) - providerKeeper.SetValidatorSetCap(ctx, chainID, 10) - providerKeeper.SetValidatorsPowerCap(ctx, chainID, 34) - providerKeeper.SetAllowlist(ctx, chainID, providertypes.NewProviderConsAddress([]byte("allowlistedAddr1"))) - providerKeeper.SetAllowlist(ctx, chainID, providertypes.NewProviderConsAddress([]byte("allowlistedAddr2"))) - providerKeeper.SetDenylist(ctx, chainID, providertypes.NewProviderConsAddress([]byte("denylistedAddr1"))) - providerKeeper.SetMinStake(ctx, chainID, 1000) - providerKeeper.SetInactiveValidatorsAllowed(ctx, chainID, true) - - expectedTopN := uint32(75) - expectedValidatorsPowerCap := uint32(67) - expectedValidatorSetCap := uint32(20) - expectedAllowlistedValidator := "cosmosvalcons1wpex7anfv3jhystyv3eq20r35a" - expectedDenylistedValidator := "cosmosvalcons1nx7n5uh0ztxsynn4sje6eyq2ud6rc6klc96w39" - expectedMinStake := uint64(0) - expectedAllowInactiveValidators := false - proposal := providertypes.NewConsumerModificationProposal("title", "description", chainID, - expectedTopN, - expectedValidatorsPowerCap, - expectedValidatorSetCap, - []string{expectedAllowlistedValidator}, - []string{expectedDenylistedValidator}, - expectedMinStake, - expectedAllowInactiveValidators, - ).(*providertypes.ConsumerModificationProposal) - - err := providerKeeper.HandleLegacyConsumerModificationProposal(ctx, proposal) - require.NoError(t, err) - - actualTopN, _ := providerKeeper.GetTopN(ctx, chainID) - require.Equal(t, expectedTopN, actualTopN) - actualValidatorsPowerCap, _ := providerKeeper.GetValidatorsPowerCap(ctx, chainID) - require.Equal(t, expectedValidatorsPowerCap, actualValidatorsPowerCap) - actualValidatorSetCap, _ := providerKeeper.GetValidatorSetCap(ctx, chainID) - require.Equal(t, expectedValidatorSetCap, actualValidatorSetCap) - - allowlistedValidator, err := sdk.ConsAddressFromBech32(expectedAllowlistedValidator) - require.NoError(t, err) - require.Equal(t, 1, len(providerKeeper.GetAllowList(ctx, chainID))) - require.Equal(t, providertypes.NewProviderConsAddress(allowlistedValidator), providerKeeper.GetAllowList(ctx, chainID)[0]) - - denylistedValidator, err := sdk.ConsAddressFromBech32(expectedDenylistedValidator) - require.NoError(t, err) - require.Equal(t, 1, len(providerKeeper.GetDenyList(ctx, chainID))) - require.Equal(t, providertypes.NewProviderConsAddress(denylistedValidator), providerKeeper.GetDenyList(ctx, chainID)[0]) - - actualMinStake, _ := providerKeeper.GetMinStake(ctx, chainID) - require.Equal(t, expectedMinStake, actualMinStake) - - actualAllowInactiveValidators := providerKeeper.AllowsInactiveValidators(ctx, chainID) - require.Equal(t, expectedAllowInactiveValidators, actualAllowInactiveValidators) -} diff --git a/x/ccv/provider/keeper/msg_server.go b/x/ccv/provider/keeper/msg_server.go index da6f63cf8a..e5148b5a37 100644 --- a/x/ccv/provider/keeper/msg_server.go +++ b/x/ccv/provider/keeper/msg_server.go @@ -2,16 +2,16 @@ package keeper import ( "context" + "fmt" + "strings" + "time" errorsmod "cosmossdk.io/errors" - + tmtypes "github.com/cometbft/cometbft/types" cryptocodec "github.com/cosmos/cosmos-sdk/crypto/codec" sdk "github.com/cosmos/cosmos-sdk/types" govtypes "github.com/cosmos/cosmos-sdk/x/gov/types" stakingtypes "github.com/cosmos/cosmos-sdk/x/staking/types" - - tmtypes "github.com/cometbft/cometbft/types" - "github.com/cosmos/interchain-security/v5/x/ccv/provider/types" ccvtypes "github.com/cosmos/interchain-security/v5/x/ccv/types" ) @@ -67,89 +67,76 @@ func (k msgServer) AssignConsumerKey(goCtx context.Context, msg *types.MsgAssign return nil, err } - if err := k.Keeper.AssignConsumerKey(ctx, msg.ChainId, validator, consumerTMPublicKey); err != nil { + if err := k.Keeper.AssignConsumerKey(ctx, msg.ConsumerId, validator, consumerTMPublicKey); err != nil { return nil, err } - k.Logger(ctx).Info("assigned consumer key", - "consumer chainID", msg.ChainId, + + chainId, err := k.GetConsumerChainId(ctx, msg.ConsumerId) + if err != nil { + return nil, errorsmod.Wrapf(ccvtypes.ErrInvalidConsumerState, "cannot get consumer chain ID: %s", err.Error()) + } + + k.Logger(ctx).Info("validator assigned consumer key", + "consumerId", msg.ConsumerId, + "chainId", chainId, "validator operator addr", msg.ProviderAddr, "consumer public key", msg.ConsumerKey, ) - ctx.EventManager().EmitEvents(sdk.Events{ + ctx.EventManager().EmitEvent( sdk.NewEvent( types.EventTypeAssignConsumerKey, + sdk.NewAttribute(sdk.AttributeKeyModule, types.ModuleName), + sdk.NewAttribute(types.AttributeConsumerId, msg.ConsumerId), + sdk.NewAttribute(types.AttributeConsumerChainId, chainId), sdk.NewAttribute(types.AttributeProviderValidatorAddress, msg.ProviderAddr), sdk.NewAttribute(types.AttributeConsumerConsensusPubKey, msg.ConsumerKey), + sdk.NewAttribute(types.AttributeSubmitterAddress, msg.Submitter), ), - }) + ) return &types.MsgAssignConsumerKeyResponse{}, nil } -// ConsumerAddition defines an RPC handler method for MsgConsumerAddition -func (k msgServer) ConsumerAddition(goCtx context.Context, msg *types.MsgConsumerAddition) (*types.MsgConsumerAdditionResponse, error) { - if k.GetAuthority() != msg.Authority { - return nil, errorsmod.Wrapf(types.ErrUnauthorized, "expected %s, got %s", k.GetAuthority(), msg.Authority) - } - +// ChangeRewardDenoms defines a rpc handler method for MsgChangeRewardDenoms +func (k msgServer) ChangeRewardDenoms(goCtx context.Context, msg *types.MsgChangeRewardDenoms) (*types.MsgChangeRewardDenomsResponse, error) { ctx := sdk.UnwrapSDKContext(goCtx) - err := k.Keeper.HandleConsumerAdditionProposal(ctx, msg) - if err != nil { - return nil, errorsmod.Wrapf(err, "failed handling ConsumerAddition proposal") - } - return &types.MsgConsumerAdditionResponse{}, nil -} -// ConsumerRemoval defines an RPC handler method for MsgConsumerRemoval -func (k msgServer) ConsumerRemoval( - goCtx context.Context, - msg *types.MsgConsumerRemoval, -) (*types.MsgConsumerRemovalResponse, error) { if k.GetAuthority() != msg.Authority { return nil, errorsmod.Wrapf(types.ErrUnauthorized, "expected %s, got %s", k.GetAuthority(), msg.Authority) } - ctx := sdk.UnwrapSDKContext(goCtx) - err := k.Keeper.HandleConsumerRemovalProposal(ctx, msg) - if err != nil { - return nil, errorsmod.Wrapf(err, "failed handling ConsumerAddition proposal") - } - - return &types.MsgConsumerRemovalResponse{}, nil -} + eventAttributes := k.Keeper.ChangeRewardDenoms(ctx, msg.DenomsToAdd, msg.DenomsToRemove) -// ChangeRewardDenoms defines a rpc handler method for MsgChangeRewardDenoms -func (k msgServer) ChangeRewardDenoms(goCtx context.Context, msg *types.MsgChangeRewardDenoms) (*types.MsgChangeRewardDenomsResponse, error) { - if k.GetAuthority() != msg.Authority { - return nil, errorsmod.Wrapf(types.ErrUnauthorized, "expected %s, got %s", k.GetAuthority(), msg.Authority) - } - - sdkCtx := sdk.UnwrapSDKContext(goCtx) - err := k.Keeper.HandleConsumerRewardDenomProposal(sdkCtx, msg) - if err != nil { - return nil, errorsmod.Wrapf(err, "failed handling Change Reward Denoms proposal") - } + ctx.EventManager().EmitEvent( + sdk.NewEvent( + types.EventTypeChangeConsumerRewardDenom, + eventAttributes..., + ), + ) return &types.MsgChangeRewardDenomsResponse{}, nil } func (k msgServer) SubmitConsumerMisbehaviour(goCtx context.Context, msg *types.MsgSubmitConsumerMisbehaviour) (*types.MsgSubmitConsumerMisbehaviourResponse, error) { ctx := sdk.UnwrapSDKContext(goCtx) - if err := k.Keeper.HandleConsumerMisbehaviour(ctx, *msg.Misbehaviour); err != nil { + if err := k.Keeper.HandleConsumerMisbehaviour(ctx, msg.ConsumerId, *msg.Misbehaviour); err != nil { return nil, err } - ctx.EventManager().EmitEvents(sdk.Events{ + ctx.EventManager().EmitEvent( sdk.NewEvent( ccvtypes.EventTypeSubmitConsumerMisbehaviour, + sdk.NewAttribute(sdk.AttributeKeyModule, types.ModuleName), + sdk.NewAttribute(types.AttributeConsumerId, msg.ConsumerId), + sdk.NewAttribute(types.AttributeConsumerChainId, msg.Misbehaviour.Header1.Header.ChainID), sdk.NewAttribute(ccvtypes.AttributeConsumerMisbehaviour, msg.Misbehaviour.String()), - sdk.NewAttribute(ccvtypes.AttributeSubmitterAddress, msg.Submitter), sdk.NewAttribute(ccvtypes.AttributeMisbehaviourClientId, msg.Misbehaviour.ClientId), sdk.NewAttribute(ccvtypes.AttributeMisbehaviourHeight1, msg.Misbehaviour.Header1.GetHeight().String()), sdk.NewAttribute(ccvtypes.AttributeMisbehaviourHeight2, msg.Misbehaviour.Header2.GetHeight().String()), + sdk.NewAttribute(types.AttributeSubmitterAddress, msg.Submitter), ), - }) + ) return &types.MsgSubmitConsumerMisbehaviourResponse{}, nil } @@ -185,20 +172,22 @@ func (k msgServer) SubmitConsumerDoubleVoting(goCtx context.Context, msg *types. return nil, err } - // handle the double voting evidence using the chain ID of the infraction block header - // and the malicious validator's public key - if err := k.Keeper.HandleConsumerDoubleVoting(ctx, evidence, msg.InfractionBlockHeader.Header.ChainID, pubkey); err != nil { + // handle the double voting evidence using the malicious validator's public key + consumerId := msg.ConsumerId + if err := k.Keeper.HandleConsumerDoubleVoting(ctx, consumerId, evidence, pubkey); err != nil { return nil, err } - ctx.EventManager().EmitEvents(sdk.Events{ + ctx.EventManager().EmitEvent( sdk.NewEvent( ccvtypes.EventTypeSubmitConsumerDoubleVoting, + sdk.NewAttribute(sdk.AttributeKeyModule, types.ModuleName), + sdk.NewAttribute(types.AttributeConsumerId, msg.ConsumerId), + sdk.NewAttribute(types.AttributeConsumerChainId, msg.InfractionBlockHeader.Header.ChainID), sdk.NewAttribute(ccvtypes.AttributeConsumerDoubleVoting, msg.DuplicateVoteEvidence.String()), - sdk.NewAttribute(ccvtypes.AttributeChainID, msg.InfractionBlockHeader.Header.ChainID), - sdk.NewAttribute(ccvtypes.AttributeSubmitterAddress, msg.Submitter), + sdk.NewAttribute(types.AttributeSubmitterAddress, msg.Submitter), ), - }) + ) return &types.MsgSubmitConsumerDoubleVotingResponse{}, nil } @@ -223,18 +212,34 @@ func (k msgServer) OptIn(goCtx context.Context, msg *types.MsgOptIn) (*types.Msg } providerConsAddr := types.NewProviderConsAddress(consAddrTmp) - err = k.Keeper.HandleOptIn(ctx, msg.ChainId, providerConsAddr, msg.ConsumerKey) + err = k.Keeper.HandleOptIn(ctx, msg.ConsumerId, providerConsAddr, msg.ConsumerKey) if err != nil { return nil, err } - ctx.EventManager().EmitEvents(sdk.Events{ + chainId, err := k.GetConsumerChainId(ctx, msg.ConsumerId) + if err != nil { + return nil, errorsmod.Wrapf(ccvtypes.ErrInvalidConsumerState, "cannot get consumer chain ID: %s", err.Error()) + } + + k.Logger(ctx).Info("validator opted in", + "consumerId", msg.ConsumerId, + "chainId", chainId, + "validator operator addr", msg.ProviderAddr, + "consumer public key", msg.ConsumerKey, + ) + + ctx.EventManager().EmitEvent( sdk.NewEvent( types.EventTypeOptIn, + sdk.NewAttribute(sdk.AttributeKeyModule, types.ModuleName), + sdk.NewAttribute(types.AttributeConsumerId, msg.ConsumerId), + sdk.NewAttribute(types.AttributeConsumerChainId, chainId), sdk.NewAttribute(types.AttributeProviderValidatorAddress, msg.ProviderAddr), sdk.NewAttribute(types.AttributeConsumerConsensusPubKey, msg.ConsumerKey), + sdk.NewAttribute(types.AttributeSubmitterAddress, msg.Submitter), ), - }) + ) return &types.MsgOptInResponse{}, nil } @@ -259,17 +264,32 @@ func (k msgServer) OptOut(goCtx context.Context, msg *types.MsgOptOut) (*types.M } providerConsAddr := types.NewProviderConsAddress(consAddrTmp) - err = k.Keeper.HandleOptOut(ctx, msg.ChainId, providerConsAddr) + err = k.Keeper.HandleOptOut(ctx, msg.ConsumerId, providerConsAddr) if err != nil { return nil, err } - ctx.EventManager().EmitEvents(sdk.Events{ + chainId, err := k.GetConsumerChainId(ctx, msg.ConsumerId) + if err != nil { + return nil, errorsmod.Wrapf(ccvtypes.ErrInvalidConsumerState, "cannot get consumer chain ID: %s", err.Error()) + } + + k.Logger(ctx).Info("validator opted out", + "consumerId", msg.ConsumerId, + "chainId", chainId, + "validator operator addr", msg.ProviderAddr, + ) + + ctx.EventManager().EmitEvent( sdk.NewEvent( types.EventTypeOptOut, + sdk.NewAttribute(sdk.AttributeKeyModule, types.ModuleName), + sdk.NewAttribute(types.AttributeConsumerId, msg.ConsumerId), + sdk.NewAttribute(types.AttributeConsumerChainId, chainId), sdk.NewAttribute(types.AttributeProviderValidatorAddress, msg.ProviderAddr), + sdk.NewAttribute(types.AttributeSubmitterAddress, msg.Submitter), ), - }) + ) return &types.MsgOptOutResponse{}, nil } @@ -293,32 +313,342 @@ func (k msgServer) SetConsumerCommissionRate(goCtx context.Context, msg *types.M return nil, err } - if err := k.HandleSetConsumerCommissionRate(ctx, msg.ChainId, types.NewProviderConsAddress(consAddr), msg.Rate); err != nil { + if err := k.HandleSetConsumerCommissionRate(ctx, msg.ConsumerId, types.NewProviderConsAddress(consAddr), msg.Rate); err != nil { return nil, err } - ctx.EventManager().EmitEvents(sdk.Events{ + chainId, err := k.GetConsumerChainId(ctx, msg.ConsumerId) + if err != nil { + return nil, errorsmod.Wrapf(ccvtypes.ErrInvalidConsumerState, "cannot get consumer chain ID: %s", err.Error()) + } + + k.Logger(ctx).Info("validator set commission rate on consumer", + "consumerId", msg.ConsumerId, + "chainId", chainId, + "validator operator addr", msg.ProviderAddr, + "rate", msg.Rate, + ) + + ctx.EventManager().EmitEvent( sdk.NewEvent( types.EventTypeSetConsumerCommissionRate, - sdk.NewAttribute(types.AttributeConsumerChainID, msg.ChainId), + sdk.NewAttribute(sdk.AttributeKeyModule, types.ModuleName), + sdk.NewAttribute(types.AttributeConsumerId, msg.ConsumerId), + sdk.NewAttribute(types.AttributeConsumerChainId, chainId), sdk.NewAttribute(types.AttributeProviderValidatorAddress, msg.ProviderAddr), sdk.NewAttribute(types.AttributeConsumerCommissionRate, msg.Rate.String()), + sdk.NewAttribute(types.AttributeSubmitterAddress, msg.Submitter), ), - }) + ) return &types.MsgSetConsumerCommissionRateResponse{}, nil } -func (k msgServer) ConsumerModification(goCtx context.Context, msg *types.MsgConsumerModification) (*types.MsgConsumerModificationResponse, error) { - if k.GetAuthority() != msg.Authority { - return nil, errorsmod.Wrapf(types.ErrUnauthorized, "expected %s, got %s", k.GetAuthority(), msg.Authority) +// CreateConsumer creates a consumer chain +func (k msgServer) CreateConsumer(goCtx context.Context, msg *types.MsgCreateConsumer) (*types.MsgCreateConsumerResponse, error) { + ctx := sdk.UnwrapSDKContext(goCtx) + resp := types.MsgCreateConsumerResponse{} + + // initialize an empty slice to store event attributes + eventAttributes := []sdk.Attribute{} + + consumerId := k.Keeper.FetchAndIncrementConsumerId(ctx) + + k.Keeper.SetConsumerOwnerAddress(ctx, consumerId, msg.Submitter) + k.Keeper.SetConsumerChainId(ctx, consumerId, msg.ChainId) + k.Keeper.SetConsumerPhase(ctx, consumerId, types.CONSUMER_PHASE_REGISTERED) + + if err := k.Keeper.SetConsumerMetadata(ctx, consumerId, msg.Metadata); err != nil { + return &resp, errorsmod.Wrapf(types.ErrInvalidConsumerMetadata, + "cannot set consumer metadata: %s", err.Error()) + } + + // add event attributes + eventAttributes = append(eventAttributes, []sdk.Attribute{ + sdk.NewAttribute(sdk.AttributeKeyModule, types.ModuleName), + sdk.NewAttribute(types.AttributeConsumerId, consumerId), + sdk.NewAttribute(types.AttributeConsumerChainId, msg.ChainId), + sdk.NewAttribute(types.AttributeConsumerName, msg.Metadata.Name), + sdk.NewAttribute(types.AttributeSubmitterAddress, msg.Submitter), + sdk.NewAttribute(types.AttributeConsumerOwner, msg.Submitter), + }...) + + // initialization parameters are optional and hence could be nil; + // in that case, set the default + initializationParameters := types.ConsumerInitializationParameters{} // default params + if msg.InitializationParameters != nil { + initializationParameters = *msg.InitializationParameters + } + if err := k.Keeper.SetConsumerInitializationParameters(ctx, consumerId, initializationParameters); err != nil { + return &resp, errorsmod.Wrapf(types.ErrInvalidConsumerInitializationParameters, + "cannot set consumer initialization parameters: %s", err.Error()) + } + if !initializationParameters.SpawnTime.IsZero() { + // add SpawnTime event attribute + eventAttributes = append(eventAttributes, + sdk.NewAttribute(types.AttributeConsumerSpawnTime, initializationParameters.SpawnTime.String())) + } + + // power-shaping parameters are optional and hence could be nil; + // in that case, set the default + powerShapingParameters := types.PowerShapingParameters{} // default params + if msg.PowerShapingParameters != nil { + powerShapingParameters = *msg.PowerShapingParameters + + if powerShapingParameters.Top_N != 0 { + return &resp, errorsmod.Wrap(types.ErrCannotCreateTopNChain, + "cannot create a Top N chain using the `MsgCreateConsumer` message; use `MsgUpdateConsumer` instead") + } + } + if err := k.Keeper.SetConsumerPowerShapingParameters(ctx, consumerId, powerShapingParameters); err != nil { + return &resp, errorsmod.Wrapf(types.ErrInvalidPowerShapingParameters, + "cannot set power shaping parameters") } + if spawnTime, initialized := k.Keeper.InitializeConsumer(ctx, consumerId); initialized { + if err := k.Keeper.PrepareConsumerForLaunch(ctx, consumerId, time.Time{}, spawnTime); err != nil { + return &resp, errorsmod.Wrapf(ccvtypes.ErrInvalidConsumerState, + "cannot prepare chain with consumer id (%s) for launch", consumerId) + } + } + + // add Phase event attribute + phase := k.GetConsumerPhase(ctx, consumerId) + eventAttributes = append(eventAttributes, sdk.NewAttribute(types.AttributeConsumerPhase, phase.String())) + + k.Logger(ctx).Info("created consumer", + "consumerId", consumerId, + "chainId", msg.ChainId, + "owner", msg.Submitter, + "phase", phase, + "spawn time", initializationParameters.SpawnTime, + ) + + ctx.EventManager().EmitEvent( + sdk.NewEvent( + types.EventTypeCreateConsumer, + eventAttributes..., + ), + ) + + resp.ConsumerId = consumerId + return &resp, nil +} + +// UpdateConsumer updates the metadata, power-shaping or initialization parameters of a consumer chain +func (k msgServer) UpdateConsumer(goCtx context.Context, msg *types.MsgUpdateConsumer) (*types.MsgUpdateConsumerResponse, error) { ctx := sdk.UnwrapSDKContext(goCtx) - err := k.Keeper.HandleConsumerModificationProposal(ctx, msg) + resp := types.MsgUpdateConsumerResponse{} + + // initialize an empty slice to store event attributes + eventAttributes := []sdk.Attribute{} + + consumerId := msg.ConsumerId + + if !k.Keeper.IsConsumerActive(ctx, consumerId) { + return &resp, errorsmod.Wrapf(types.ErrInvalidPhase, + "cannot update consumer chain that is not in the registered, initialized, or launched phase: %s", consumerId) + } + + ownerAddress, err := k.Keeper.GetConsumerOwnerAddress(ctx, consumerId) + if err != nil { + return &resp, errorsmod.Wrapf(types.ErrNoOwnerAddress, "cannot retrieve owner address %s", ownerAddress) + } + + if msg.Owner != ownerAddress { + return &resp, errorsmod.Wrapf(types.ErrUnauthorized, "expected owner address %s, got %s", ownerAddress, msg.Owner) + } + + chainId, err := k.GetConsumerChainId(ctx, consumerId) if err != nil { - return nil, errorsmod.Wrapf(err, "failed handling ConsumerModification proposal") + return &resp, errorsmod.Wrapf(ccvtypes.ErrInvalidConsumerState, "cannot get consumer chain ID: %s", err.Error()) + } + + // add event attributes + eventAttributes = append(eventAttributes, []sdk.Attribute{ + sdk.NewAttribute(sdk.AttributeKeyModule, types.ModuleName), + sdk.NewAttribute(types.AttributeConsumerId, consumerId), + sdk.NewAttribute(types.AttributeConsumerChainId, chainId), + sdk.NewAttribute(types.AttributeSubmitterAddress, msg.Owner), + }...) + + // The new owner address can be empty, in which case the consumer chain does not change its owner. + // However, if the new owner address is not empty, we verify that it's a valid account address. + if strings.TrimSpace(msg.NewOwnerAddress) != "" { + if _, err := k.accountKeeper.AddressCodec().StringToBytes(msg.NewOwnerAddress); err != nil { + return &resp, errorsmod.Wrapf(types.ErrInvalidNewOwnerAddress, "invalid new owner address %s", msg.NewOwnerAddress) + } + + k.Keeper.SetConsumerOwnerAddress(ctx, consumerId, msg.NewOwnerAddress) } - return &types.MsgConsumerModificationResponse{}, nil + if msg.Metadata != nil { + if err := k.Keeper.SetConsumerMetadata(ctx, consumerId, *msg.Metadata); err != nil { + return &resp, errorsmod.Wrapf(types.ErrInvalidConsumerMetadata, + "cannot set consumer metadata: %s", err.Error()) + } + + // add Name event attribute + eventAttributes = append(eventAttributes, sdk.NewAttribute(types.AttributeConsumerName, msg.Metadata.Name)) + } + + // get the previous spawn time so that we can use it in `PrepareConsumerForLaunch` + previousInitializationParameters, err := k.Keeper.GetConsumerInitializationParameters(ctx, consumerId) + if err != nil { + return &resp, errorsmod.Wrapf(ccvtypes.ErrInvalidConsumerState, + "cannot get consumer initialized parameters, consumerId(%s): %s", consumerId, err.Error()) + } + previousSpawnTime := previousInitializationParameters.SpawnTime + + if msg.InitializationParameters != nil { + if err = k.Keeper.SetConsumerInitializationParameters(ctx, msg.ConsumerId, *msg.InitializationParameters); err != nil { + return &resp, errorsmod.Wrapf(types.ErrInvalidConsumerInitializationParameters, + "cannot set consumer initialization parameters: %s", err.Error()) + } + + if !msg.InitializationParameters.SpawnTime.IsZero() { + // add SpawnTime event attribute + eventAttributes = append(eventAttributes, + sdk.NewAttribute(types.AttributeConsumerSpawnTime, msg.InitializationParameters.SpawnTime.String())) + } + } + + if msg.PowerShapingParameters != nil { + // A consumer chain can only become a Top N chain if the owner is the gov module. Because of this, to create a + // Top N chain, we need two `MsgUpdateConsumer` messages: i) one that would set the `ownerAddress` to the gov module + // and ii) one that would set the `Top_N` to something greater than 0. + if msg.PowerShapingParameters.Top_N > 0 && ownerAddress != k.GetAuthority() { + return &resp, errorsmod.Wrapf(types.ErrInvalidTransformToTopN, + "an update to a Top N chain can only be done if chain is owner is the gov module") + } + + oldPowerShapingParameters, err := k.Keeper.GetConsumerPowerShapingParameters(ctx, consumerId) + if err != nil { + return &resp, errorsmod.Wrapf(ccvtypes.ErrInvalidConsumerState, + "cannot get consumer previous power shaping parameters: %s", err.Error()) + } + oldTopN := oldPowerShapingParameters.Top_N + + if err = k.Keeper.SetConsumerPowerShapingParameters(ctx, consumerId, *msg.PowerShapingParameters); err != nil { + return &resp, errorsmod.Wrapf(types.ErrInvalidPowerShapingParameters, + "cannot set power shaping parameters") + } + err = k.Keeper.UpdateMinimumPowerInTopN(ctx, consumerId, oldTopN, msg.PowerShapingParameters.Top_N) + if err != nil { + return &resp, errorsmod.Wrapf(types.ErrCannotUpdateMinimumPowerInTopN, + "could not update minimum power in top N, oldTopN: %d, newTopN: %d, error: %s", oldTopN, msg.PowerShapingParameters.Top_N, err.Error()) + } + + // add TopN event attribute + eventAttributes = append(eventAttributes, + sdk.NewAttribute(types.AttributeConsumerTopN, fmt.Sprintf("%v", msg.PowerShapingParameters.Top_N))) + } + + // A Top N cannot change its owner address to something different from the gov module if the chain + // remains a Top N chain. + currentOwnerAddress, err := k.Keeper.GetConsumerOwnerAddress(ctx, consumerId) + if err != nil { + return &resp, errorsmod.Wrapf(ccvtypes.ErrInvalidConsumerState, "cannot retrieve owner address %s: %s", ownerAddress, err.Error()) + } + + currentPowerShapingParameters, err := k.Keeper.GetConsumerPowerShapingParameters(ctx, consumerId) + if err != nil { + return &resp, errorsmod.Wrapf(ccvtypes.ErrInvalidConsumerState, "cannot retrieve power shaping parameters: %s", err.Error()) + } + + if currentPowerShapingParameters.Top_N != 0 && currentOwnerAddress != k.GetAuthority() { + return &resp, errorsmod.Wrapf(types.ErrInvalidTransformToOptIn, + "a move to a new owner address that is not the gov module can only be done if `Top N` is set to 0") + } + + if spawnTime, initialized := k.Keeper.InitializeConsumer(ctx, consumerId); initialized { + if err := k.Keeper.PrepareConsumerForLaunch(ctx, consumerId, previousSpawnTime, spawnTime); err != nil { + return &resp, errorsmod.Wrapf(ccvtypes.ErrInvalidConsumerState, + "cannot prepare chain with consumer id (%s) for launch", consumerId) + } + } + + // add Owner event attribute + eventAttributes = append(eventAttributes, sdk.NewAttribute(types.AttributeConsumerOwner, currentOwnerAddress)) + + // add Phase event attribute + phase := k.GetConsumerPhase(ctx, consumerId) + eventAttributes = append(eventAttributes, sdk.NewAttribute(types.AttributeConsumerPhase, phase.String())) + + k.Logger(ctx).Info("updated consumer", + "consumerId", consumerId, + "chainId", chainId, + "owner", currentOwnerAddress, + "phase", phase, + "topN", currentPowerShapingParameters.Top_N, + ) + + ctx.EventManager().EmitEvent( + sdk.NewEvent( + types.EventTypeUpdateConsumer, + eventAttributes..., + ), + ) + + return &resp, nil +} + +// RemoveConsumer defines an RPC handler method for MsgRemoveConsumer +func (k msgServer) RemoveConsumer(goCtx context.Context, msg *types.MsgRemoveConsumer) (*types.MsgRemoveConsumerResponse, error) { + ctx := sdk.UnwrapSDKContext(goCtx) + + resp := types.MsgRemoveConsumerResponse{} + + consumerId := msg.ConsumerId + ownerAddress, err := k.Keeper.GetConsumerOwnerAddress(ctx, consumerId) + if err != nil { + return &resp, errorsmod.Wrapf(types.ErrNoOwnerAddress, "cannot retrieve owner address %s", ownerAddress) + } + + chainId, err := k.GetConsumerChainId(ctx, consumerId) + if err != nil { + return &resp, errorsmod.Wrapf(ccvtypes.ErrInvalidConsumerState, "cannot get consumer chain ID: %s", err.Error()) + } + + if msg.Owner != ownerAddress { + return &resp, errorsmod.Wrapf(types.ErrUnauthorized, "expected owner address %s, got %s", ownerAddress, msg.Owner) + } + + phase := k.Keeper.GetConsumerPhase(ctx, consumerId) + if phase != types.CONSUMER_PHASE_LAUNCHED { + return &resp, errorsmod.Wrapf(types.ErrInvalidPhase, + "chain with consumer id: %s has to be in its launched phase", consumerId) + } + + err = k.Keeper.StopAndPrepareForConsumerRemoval(ctx, consumerId) + + k.Logger(ctx).Info("stopped consumer", + "consumerId", consumerId, + "chainId", chainId, + "phase", phase, + ) + + ctx.EventManager().EmitEvent( + sdk.NewEvent( + types.EventTypeRemoveConsumer, + sdk.NewAttribute(sdk.AttributeKeyModule, types.ModuleName), + sdk.NewAttribute(types.AttributeConsumerId, consumerId), + sdk.NewAttribute(types.AttributeConsumerChainId, chainId), + sdk.NewAttribute(types.AttributeSubmitterAddress, msg.Owner), + ), + ) + + return &resp, err +} + +func (k msgServer) ConsumerAddition(_ context.Context, _ *types.MsgConsumerAddition) (*types.MsgConsumerAdditionResponse, error) { + return nil, fmt.Errorf("`MsgConsumerAddition` is deprecated. Use `MsgCreateConsumer`") +} + +func (k msgServer) ConsumerModification(_ context.Context, _ *types.MsgConsumerModification) (*types.MsgConsumerModificationResponse, error) { + return nil, fmt.Errorf("`MsgConsumerModification` is deprecated. Use `MsgUpdateConsumer` instead") +} + +func (k msgServer) ConsumerRemoval(_ context.Context, _ *types.MsgConsumerRemoval) (*types.MsgConsumerRemovalResponse, error) { + return nil, fmt.Errorf("`MsgConsumerRemoval` is deprecated. Use `MsgRemoveConsumer` instead") } diff --git a/x/ccv/provider/keeper/msg_server_test.go b/x/ccv/provider/keeper/msg_server_test.go new file mode 100644 index 0000000000..66ddaefff9 --- /dev/null +++ b/x/ccv/provider/keeper/msg_server_test.go @@ -0,0 +1,166 @@ +package keeper_test + +import ( + "testing" + "time" + + "github.com/cosmos/cosmos-sdk/codec/address" + testkeeper "github.com/cosmos/interchain-security/v5/testutil/keeper" + providerkeeper "github.com/cosmos/interchain-security/v5/x/ccv/provider/keeper" + providertypes "github.com/cosmos/interchain-security/v5/x/ccv/provider/types" + "github.com/stretchr/testify/require" +) + +func TestCreateConsumer(t *testing.T) { + providerKeeper, ctx, ctrl, _ := testkeeper.GetProviderKeeperAndCtx(t, testkeeper.NewInMemKeeperParams(t)) + defer ctrl.Finish() + + msgServer := providerkeeper.NewMsgServerImpl(&providerKeeper) + + consumerMetadata := providertypes.ConsumerMetadata{ + Name: "chain name", + Description: "description", + } + response, err := msgServer.CreateConsumer(ctx, + &providertypes.MsgCreateConsumer{Submitter: "submitter", ChainId: "chainId", Metadata: consumerMetadata, + InitializationParameters: &providertypes.ConsumerInitializationParameters{}, + PowerShapingParameters: &providertypes.PowerShapingParameters{}}) + require.NoError(t, err) + require.Equal(t, "0", response.ConsumerId) + actualMetadata, err := providerKeeper.GetConsumerMetadata(ctx, "0") + require.NoError(t, err) + require.Equal(t, consumerMetadata, actualMetadata) + ownerAddress, err := providerKeeper.GetConsumerOwnerAddress(ctx, "0") + require.NoError(t, err) + require.Equal(t, "submitter", ownerAddress) + phase := providerKeeper.GetConsumerPhase(ctx, "0") + require.Equal(t, providertypes.CONSUMER_PHASE_REGISTERED, phase) + + consumerMetadata = providertypes.ConsumerMetadata{ + Name: "chain name", + Description: "description2", + } + response, err = msgServer.CreateConsumer(ctx, + &providertypes.MsgCreateConsumer{Submitter: "submitter2", ChainId: "chainId", Metadata: consumerMetadata, + InitializationParameters: &providertypes.ConsumerInitializationParameters{}, + PowerShapingParameters: &providertypes.PowerShapingParameters{}}) + require.NoError(t, err) + // assert that the consumer id is different from the previously registered chain + require.Equal(t, "1", response.ConsumerId) + actualMetadata, err = providerKeeper.GetConsumerMetadata(ctx, "1") + require.NoError(t, err) + require.Equal(t, consumerMetadata, actualMetadata) + ownerAddress, err = providerKeeper.GetConsumerOwnerAddress(ctx, "1") + require.NoError(t, err) + require.Equal(t, "submitter2", ownerAddress) + phase = providerKeeper.GetConsumerPhase(ctx, "1") + require.Equal(t, providertypes.CONSUMER_PHASE_REGISTERED, phase) +} + +func TestUpdateConsumer(t *testing.T) { + providerKeeper, ctx, ctrl, mocks := testkeeper.GetProviderKeeperAndCtx(t, testkeeper.NewInMemKeeperParams(t)) + defer ctrl.Finish() + + msgServer := providerkeeper.NewMsgServerImpl(&providerKeeper) + + // try to update a non-existing (i.e., no consumer id exists) + _, err := msgServer.UpdateConsumer(ctx, + &providertypes.MsgUpdateConsumer{Owner: "owner", ConsumerId: "0", NewOwnerAddress: "cosmos1dkas8mu4kyhl5jrh4nzvm65qz588hy9qcz08la", + Metadata: nil, + InitializationParameters: nil, + PowerShapingParameters: nil, + }) + require.Error(t, err, "cannot update consumer chain") + + // create a chain before updating it + createConsumerResponse, err := msgServer.CreateConsumer(ctx, + &providertypes.MsgCreateConsumer{Submitter: "submitter", ChainId: "chainId", + Metadata: providertypes.ConsumerMetadata{ + Name: "name", + Description: "description", + Metadata: "metadata", + }, + InitializationParameters: nil, + PowerShapingParameters: nil, + }) + require.NoError(t, err) + consumerId := createConsumerResponse.ConsumerId + + mocks.MockAccountKeeper.EXPECT().AddressCodec().Return(address.NewBech32Codec("cosmos")).AnyTimes() + _, err = msgServer.UpdateConsumer(ctx, + &providertypes.MsgUpdateConsumer{Owner: "wrong owner", ConsumerId: consumerId, NewOwnerAddress: "cosmos1dkas8mu4kyhl5jrh4nzvm65qz588hy9qcz08la", + Metadata: nil, + InitializationParameters: nil, + PowerShapingParameters: nil, + }) + require.Error(t, err, "expected owner address") + + expectedConsumerMetadata := providertypes.ConsumerMetadata{ + Name: "name2", + Description: "description2", + Metadata: "metadata2", + } + + expectedInitializationParameters := testkeeper.GetTestInitializationParameters() + expectedPowerShapingParameters := testkeeper.GetTestPowerShapingParameters() + + expectedOwnerAddress := "cosmos1dkas8mu4kyhl5jrh4nzvm65qz588hy9qcz08la" + _, err = msgServer.UpdateConsumer(ctx, + &providertypes.MsgUpdateConsumer{Owner: "submitter", ConsumerId: consumerId, NewOwnerAddress: expectedOwnerAddress, + Metadata: &expectedConsumerMetadata, + InitializationParameters: &expectedInitializationParameters, + PowerShapingParameters: &expectedPowerShapingParameters}) + require.NoError(t, err) + + // assert that owner address was updated + ownerAddress, err := providerKeeper.GetConsumerOwnerAddress(ctx, consumerId) + require.NoError(t, err) + require.Equal(t, expectedOwnerAddress, ownerAddress) + + // assert that consumer metadata were updated + actualConsumerMetadata, err := providerKeeper.GetConsumerMetadata(ctx, consumerId) + require.NoError(t, err) + require.Equal(t, expectedConsumerMetadata, actualConsumerMetadata) + + // assert that initialization parameters were updated + actualInitializationParameters, err := providerKeeper.GetConsumerInitializationParameters(ctx, consumerId) + require.NoError(t, err) + require.Equal(t, expectedInitializationParameters, actualInitializationParameters) + + // assert that power-shaping parameters were updated + actualPowerShapingParameters, err := providerKeeper.GetConsumerPowerShapingParameters(ctx, consumerId) + require.NoError(t, err) + require.Equal(t, expectedPowerShapingParameters, actualPowerShapingParameters) + + // assert phase + phase := providerKeeper.GetConsumerPhase(ctx, consumerId) + require.Equal(t, providertypes.CONSUMER_PHASE_INITIALIZED, phase) + + // assert that chain is set to launch + consumerIds, err := providerKeeper.GetConsumersToBeLaunched(ctx, expectedInitializationParameters.SpawnTime) + require.NoError(t, err) + require.Equal(t, providertypes.ConsumerIds{ + Ids: []string{consumerId}, + }, consumerIds) + + // re-update (change spawnTime) and verify that the chain is still to be launched at the new spawn time + previousSpawnTime := expectedInitializationParameters.SpawnTime + updatedSpawnTime := expectedInitializationParameters.SpawnTime.Add(time.Hour) + expectedInitializationParameters.SpawnTime = updatedSpawnTime + _, err = msgServer.UpdateConsumer(ctx, + &providertypes.MsgUpdateConsumer{Owner: expectedOwnerAddress, ConsumerId: consumerId, + Metadata: &expectedConsumerMetadata, + InitializationParameters: &expectedInitializationParameters, + PowerShapingParameters: &expectedPowerShapingParameters}) + require.NoError(t, err) + + consumerIds, err = providerKeeper.GetConsumersToBeLaunched(ctx, previousSpawnTime) + require.NoError(t, err) + require.Empty(t, consumerIds) + + consumerIds, err = providerKeeper.GetConsumersToBeLaunched(ctx, updatedSpawnTime) + require.NoError(t, err) + require.Equal(t, providertypes.ConsumerIds{ + Ids: []string{consumerId}, + }, consumerIds) +} diff --git a/x/ccv/provider/keeper/partial_set_security.go b/x/ccv/provider/keeper/partial_set_security.go index 3112124724..5d654516ab 100644 --- a/x/ccv/provider/keeper/partial_set_security.go +++ b/x/ccv/provider/keeper/partial_set_security.go @@ -11,18 +11,37 @@ import ( stakingtypes "github.com/cosmos/cosmos-sdk/x/staking/types" "github.com/cosmos/interchain-security/v5/x/ccv/provider/types" + ccvtypes "github.com/cosmos/interchain-security/v5/x/ccv/types" ) -// HandleOptIn prepares validator `providerAddr` to opt in to `chainID` with an optional `consumerKey` consumer public key. +// HandleOptIn prepares validator `providerAddr` to opt in to `consumerId` with an optional `consumerKey` consumer public key. // Note that the validator only opts in at the end of an epoch. -func (k Keeper) HandleOptIn(ctx sdk.Context, chainID string, providerAddr types.ProviderConsAddress, consumerKey string) error { - if !k.IsConsumerProposedOrRegistered(ctx, chainID) { +func (k Keeper) HandleOptIn(ctx sdk.Context, consumerId string, providerAddr types.ProviderConsAddress, consumerKey string) error { + if !k.IsConsumerActive(ctx, consumerId) { return errorsmod.Wrapf( - types.ErrUnknownConsumerChainId, - "opting in to an unknown consumer chain, with id: %s", chainID) + types.ErrInvalidPhase, + "cannot opt in to a consumer chain that is not in the registered, initialized, or launched phase: %s", consumerId) } - k.SetOptedIn(ctx, chainID, providerAddr) + chainId, err := k.GetConsumerChainId(ctx, consumerId) + if err != nil { + // TODO (PERMISSIONLESS): fix error types + return errorsmod.Wrapf( + types.ErrUnknownConsumerId, + "opting in to an unknown consumer chain, with id (%s): %s", consumerId, err.Error()) + } + optedInToConsumerId, found := k.IsValidatorOptedInToChainId(ctx, providerAddr, chainId) + if found { + return errorsmod.Wrapf(types.ErrAlreadyOptedIn, + "validator is already opted in to a chain (%s) with this chain id (%s)", + optedInToConsumerId, chainId) + } + + k.SetOptedIn(ctx, consumerId, providerAddr) + err = k.AppendOptedInConsumerId(ctx, providerAddr, consumerId) + if err != nil { + return err + } if consumerKey != "" { consumerTMPublicKey, err := k.ParseConsumerKey(consumerKey) @@ -35,7 +54,7 @@ func (k Keeper) HandleOptIn(ctx sdk.Context, chainID string, providerAddr types. return err } - err = k.AssignConsumerKey(ctx, chainID, validator, consumerTMPublicKey) + err = k.AssignConsumerKey(ctx, consumerId, validator, consumerTMPublicKey) if err != nil { return err } @@ -44,18 +63,31 @@ func (k Keeper) HandleOptIn(ctx sdk.Context, chainID string, providerAddr types. return nil } -// HandleOptOut prepares validator `providerAddr` to opt out from running `chainID`. +// HandleOptOut prepares validator `providerAddr` to opt out from running `consumerId`. // Note that the validator only opts out at the end of an epoch. -func (k Keeper) HandleOptOut(ctx sdk.Context, chainID string, providerAddr types.ProviderConsAddress) error { - if _, found := k.GetConsumerClientId(ctx, chainID); !found { - // A validator can only opt out from a running chain. We check this by checking the consumer client id, because - // `SetConsumerClientId` is set when the chain starts in `CreateConsumerClientInCachedCtx` of `BeginBlockInit`. +func (k Keeper) HandleOptOut(ctx sdk.Context, consumerId string, providerAddr types.ProviderConsAddress) error { + phase := k.GetConsumerPhase(ctx, consumerId) + if phase == types.CONSUMER_PHASE_UNSPECIFIED { + return errorsmod.Wrapf( + types.ErrUnknownConsumerId, + "opting out of an unknown consumer chain, consumerId(%s)", consumerId, + ) + } + if phase != types.CONSUMER_PHASE_LAUNCHED { + // A validator can only opt out from a running chain return errorsmod.Wrapf( - types.ErrUnknownConsumerChainId, - "opting out of an unknown or not running consumer chain, with id: %s", chainID) + types.ErrInvalidPhase, + "opting out of a consumer chain not yet launched, consumerId(%s)", consumerId, + ) } - if topN, found := k.GetTopN(ctx, chainID); found && topN > 0 { + powerShapingParameters, err := k.GetConsumerPowerShapingParameters(ctx, consumerId) + if err != nil { + return errorsmod.Wrapf(ccvtypes.ErrInvalidConsumerState, + "cannot get consumer power shaping parameters: %s", err.Error(), + ) + } + if powerShapingParameters.Top_N > 0 { // a validator cannot opt out from a Top N chain if the validator is in the Top N validators validator, err := k.stakingKeeper.GetValidatorByConsAddr(ctx, providerAddr.ToSdkConsAddr()) if err != nil { @@ -69,56 +101,67 @@ func (k Keeper) HandleOptOut(ctx sdk.Context, chainID string, providerAddr types if err != nil { return err } - minPowerInTopN, found := k.GetMinimumPowerInTopN(ctx, chainID) + minPowerInTopN, found := k.GetMinimumPowerInTopN(ctx, consumerId) if !found { return errorsmod.Wrapf( - types.ErrUnknownConsumerChainId, - "Could not find minimum power in top N for chain with id: %s", chainID) + types.ErrUnknownConsumerId, + "Could not find minimum power in top N for chain with consumer id: %s", consumerId) } if power >= minPowerInTopN { return errorsmod.Wrapf( types.ErrCannotOptOutFromTopN, - "validator with power (%d) cannot opt out from Top N chain (%s) because all validators"+ - " with at least %d power have to validate", power, chainID, minPowerInTopN) + "validator with power (%d) cannot opt out from Top N chain with consumer id (%s) because all validators"+ + " with at least %d power have to validate", power, consumerId, minPowerInTopN) } } - k.DeleteOptedIn(ctx, chainID, providerAddr) - return nil + k.DeleteOptedIn(ctx, consumerId, providerAddr) + return k.RemoveOptedInConsumerId(ctx, providerAddr, consumerId) } -// OptInTopNValidators opts in to `chainID` all the `bondedValidators` that have at least `minPowerToOptIn` power -func (k Keeper) OptInTopNValidators(ctx sdk.Context, chainID string, bondedValidators []stakingtypes.Validator, minPowerToOptIn int64) { +// OptInTopNValidators opts in to `consumerId` all the `bondedValidators` that have at least `minPowerToOptIn` power +func (k Keeper) OptInTopNValidators(ctx sdk.Context, consumerId string, bondedValidators []stakingtypes.Validator, minPowerToOptIn int64) { for _, val := range bondedValidators { // log the validator k.Logger(ctx).Debug("Checking whether to opt in validator because of top N", "validator", val.GetOperator()) valAddr, err := sdk.ValAddressFromBech32(val.GetOperator()) if err != nil { - k.Logger(ctx).Error("could not retrieve validator address: %s: %s", - val.GetOperator(), err) + k.Logger(ctx).Error("could not retrieve validator address from operator address", + "validator operator address", val.GetOperator(), + "error", err.Error()) continue } power, err := k.stakingKeeper.GetLastValidatorPower(ctx, valAddr) if err != nil { - k.Logger(ctx).Error("could not retrieve last power of validator address: %s: %s", - val.GetOperator(), err) + k.Logger(ctx).Error("could not retrieve last power of validator", + "validator operator address", val.GetOperator(), + "error", err.Error()) continue } if power >= minPowerToOptIn { consAddr, err := val.GetConsAddr() if err != nil { - k.Logger(ctx).Error("could not retrieve validators consensus address: %s: %s", - val, err) + k.Logger(ctx).Error("could not retrieve validator consensus address", + "validator operator address", val.GetOperator(), + "error", err.Error()) continue } k.Logger(ctx).Debug("Opting in validator", "validator", val.GetOperator()) // if validator already exists it gets overwritten - k.SetOptedIn(ctx, chainID, types.NewProviderConsAddress(consAddr)) - } + err = k.AppendOptedInConsumerId(ctx, types.NewProviderConsAddress(consAddr), consumerId) + if err != nil { + k.Logger(ctx).Error("could not append validator as opted-in validator for this consumer chain", + "validator operator address", val.GetOperator(), + "consumer id", consumerId, + "error", err.Error()) + continue + } + k.SetOptedIn(ctx, consumerId, types.NewProviderConsAddress(consAddr)) + } // else validators that do not belong to the top N validators but were opted in, remain opted in } } @@ -168,15 +211,20 @@ func (k Keeper) ComputeMinPowerInTopN(ctx sdk.Context, bondedValidators []stakin return 0, fmt.Errorf("should never reach this point with topN (%d), totalPower (%d), and powerSum (%d)", topN, totalPower, powerSum) } -// CapValidatorSet caps the provided `validators` if chain `chainID` is an Opt In chain with a validator-set cap. If cap -// is `k`, `CapValidatorSet` returns the first `k` validators from `validators` with the highest power. -func (k Keeper) CapValidatorSet(ctx sdk.Context, chainID string, validators []types.ConsensusValidator) []types.ConsensusValidator { - if topN, found := k.GetTopN(ctx, chainID); found && topN > 0 { +// CapValidatorSet caps the provided `validators` if chain with `consumerId` is an Opt In chain with a validator-set cap. +// If cap is `k`, `CapValidatorSet` returns the first `k` validators from `validators` with the highest power. +func (k Keeper) CapValidatorSet( + ctx sdk.Context, + powerShapingParameters types.PowerShapingParameters, + validators []types.ConsensusValidator, +) []types.ConsensusValidator { + if powerShapingParameters.Top_N > 0 { // is a no-op if the chain is a Top N chain return validators } - if validatorSetCap, found := k.GetValidatorSetCap(ctx, chainID); found && validatorSetCap != 0 && int(validatorSetCap) < len(validators) { + validatorSetCap := powerShapingParameters.ValidatorSetCap + if validatorSetCap != 0 && int(validatorSetCap) < len(validators) { sort.Slice(validators, func(i, j int) bool { return validators[i].Power > validators[j].Power }) @@ -187,15 +235,19 @@ func (k Keeper) CapValidatorSet(ctx sdk.Context, chainID string, validators []ty } } -// CapValidatorsPower caps the power of the validators on chain `chainID` and returns an updated slice of validators +// CapValidatorsPower caps the power of the validators on chain with `consumerId` and returns an updated slice of validators // with their new powers. Works on a best-basis effort because there are cases where we cannot guarantee that all validators // on the consumer chain have less power than the set validators-power cap. For example, if we have 10 validators and // the power cap is set to 5%, we need at least one validator to have more than 10% of the voting power on the consumer chain. -func (k Keeper) CapValidatorsPower(ctx sdk.Context, chainID string, validators []types.ConsensusValidator) []types.ConsensusValidator { - if p, found := k.GetValidatorsPowerCap(ctx, chainID); found && p > 0 { - return NoMoreThanPercentOfTheSum(validators, p) +func (k Keeper) CapValidatorsPower( + ctx sdk.Context, + validatorsPowerCap uint32, + validators []types.ConsensusValidator, +) []types.ConsensusValidator { + if validatorsPowerCap > 0 { + return NoMoreThanPercentOfTheSum(validators, validatorsPowerCap) } else { - // is a no-op if power cap is not set for `chainID` + // is a no-op if power cap is not set for `consumerId` return validators } } @@ -300,24 +352,41 @@ func NoMoreThanPercentOfTheSum(validators []types.ConsensusValidator, percent ui return updatedValidators } -// CanValidateChain returns true if the validator `providerAddr` is opted-in to chain `chainID` and the allowlist and -// denylist do not prevent the validator from validating the chain. -func (k Keeper) CanValidateChain(ctx sdk.Context, chainID string, providerAddr types.ProviderConsAddress) bool { +// CanValidateChain returns true if the validator `providerAddr` is opted-in to chain with `consumerId` and the allowlist +// and denylist do not prevent the validator from validating the chain. +func (k Keeper) CanValidateChain( + ctx sdk.Context, + consumerId string, + providerAddr types.ProviderConsAddress, + topN uint32, + minPowerToOptIn int64, +) bool { + // check if the validator is already opted-in + optedIn := k.IsOptedIn(ctx, consumerId, providerAddr) + + // check if the validator is automatically opted-in for a topN chain + if !optedIn && topN > 0 { + optedIn = k.HasMinPower(ctx, providerAddr, minPowerToOptIn) + } + // only consider opted-in validators - return k.IsOptedIn(ctx, chainID, providerAddr) && + return optedIn && // if an allowlist is declared, only consider allowlisted validators - (k.IsAllowlistEmpty(ctx, chainID) || - k.IsAllowlisted(ctx, chainID, providerAddr)) && + (k.IsAllowlistEmpty(ctx, consumerId) || + k.IsAllowlisted(ctx, consumerId, providerAddr)) && // if a denylist is declared, only consider denylisted validators - (k.IsDenylistEmpty(ctx, chainID) || - !k.IsDenylisted(ctx, chainID, providerAddr)) + (k.IsDenylistEmpty(ctx, consumerId) || + !k.IsDenylisted(ctx, consumerId, providerAddr)) } -// FulfillsMinStake returns true if the validator `providerAddr` has enough stake to validate chain `chainID` +// FulfillsMinStake returns true if the validator `providerAddr` has enough stake to validate chain with `consumerId` // by checking its staked tokens against the minimum stake required to validate the chain. -func (k Keeper) FulfillsMinStake(ctx sdk.Context, chainID string, providerAddr types.ProviderConsAddress) bool { - minStake, found := k.GetMinStake(ctx, chainID) - if !found { +func (k Keeper) FulfillsMinStake( + ctx sdk.Context, + minStake uint64, + providerAddr types.ProviderConsAddress, +) bool { + if minStake == 0 { return true } @@ -332,7 +401,13 @@ func (k Keeper) FulfillsMinStake(ctx sdk.Context, chainID string, providerAddr t } // ComputeNextValidators computes the validators for the upcoming epoch based on the currently `bondedValidators`. -func (k Keeper) ComputeNextValidators(ctx sdk.Context, chainID string, bondedValidators []stakingtypes.Validator) []types.ConsensusValidator { +func (k Keeper) ComputeNextValidators( + ctx sdk.Context, + consumerId string, + bondedValidators []stakingtypes.Validator, + powerShapingParameters types.PowerShapingParameters, + minPowerToOptIn int64, +) []types.ConsensusValidator { // sort the bonded validators by number of staked tokens in descending order sort.Slice(bondedValidators, func(i, j int) bool { return bondedValidators[i].GetBondedTokens().GT(bondedValidators[j].GetBondedTokens()) @@ -340,8 +415,7 @@ func (k Keeper) ComputeNextValidators(ctx sdk.Context, chainID string, bondedVal // if inactive validators are not allowed, only consider the first `MaxProviderConsensusValidators` validators // since those are the ones that participate in consensus - allowInactiveVals := k.AllowsInactiveValidators(ctx, chainID) - if !allowInactiveVals { + if !powerShapingParameters.AllowInactiveVals { // only leave the first MaxProviderConsensusValidators bonded validators maxProviderConsensusVals := k.GetMaxProviderConsensusValidators(ctx) if len(bondedValidators) > int(maxProviderConsensusVals) { @@ -349,11 +423,52 @@ func (k Keeper) ComputeNextValidators(ctx sdk.Context, chainID string, bondedVal } } - nextValidators := k.FilterValidators(ctx, chainID, bondedValidators, + nextValidators := k.FilterValidators(ctx, consumerId, bondedValidators, func(providerAddr types.ProviderConsAddress) bool { - return k.CanValidateChain(ctx, chainID, providerAddr) && k.FulfillsMinStake(ctx, chainID, providerAddr) + return k.CanValidateChain(ctx, consumerId, providerAddr, powerShapingParameters.Top_N, minPowerToOptIn) && + k.FulfillsMinStake(ctx, powerShapingParameters.MinStake, providerAddr) }) - nextValidators = k.CapValidatorSet(ctx, chainID, nextValidators) - return k.CapValidatorsPower(ctx, chainID, nextValidators) + nextValidators = k.CapValidatorSet(ctx, powerShapingParameters, nextValidators) + return k.CapValidatorsPower(ctx, powerShapingParameters.ValidatorsPowerCap, nextValidators) +} + +// HasMinPower returns true if the `providerAddr` voting power is GTE than the given minimum power +func (k Keeper) HasMinPower(ctx sdk.Context, providerAddr types.ProviderConsAddress, minPower int64) bool { + val, err := k.stakingKeeper.GetValidatorByConsAddr(ctx, providerAddr.Address) + if err != nil { + k.Logger(ctx).Error( + "cannot get last validator power", + "provider address", + providerAddr, + "error", + err, + ) + return false + } + + valAddr, err := sdk.ValAddressFromBech32(val.GetOperator()) + if err != nil { + k.Logger(ctx).Error( + "could not retrieve validator address", + "operator address", + val.GetOperator(), + "error", + err, + ) + return false + } + + power, err := k.stakingKeeper.GetLastValidatorPower(ctx, valAddr) + if err != nil { + k.Logger(ctx).Error("could not retrieve last power of validator address", + "operator address", + val.GetOperator(), + "error", + err, + ) + return false + } + + return power >= minPower } diff --git a/x/ccv/provider/keeper/partial_set_security_test.go b/x/ccv/provider/keeper/partial_set_security_test.go index e180554239..c9ef563914 100644 --- a/x/ccv/provider/keeper/partial_set_security_test.go +++ b/x/ccv/provider/keeper/partial_set_security_test.go @@ -2,6 +2,7 @@ package keeper_test import ( "bytes" + "fmt" "sort" "testing" @@ -32,13 +33,26 @@ func TestHandleOptIn(t *testing.T) { providerAddr := types.NewProviderConsAddress([]byte("providerAddr")) - // trying to opt in to a non-proposed and non-registered chain returns an error - require.Error(t, providerKeeper.HandleOptIn(ctx, "unknownChainID", providerAddr, "")) + // trying to opt in to an unknown chain + require.Error(t, providerKeeper.HandleOptIn(ctx, "unknownConsumerId", providerAddr, "")) - providerKeeper.SetProposedConsumerChain(ctx, "chainID", 1) - require.False(t, providerKeeper.IsOptedIn(ctx, "chainID", providerAddr)) - providerKeeper.HandleOptIn(ctx, "chainID", providerAddr, "") - require.True(t, providerKeeper.IsOptedIn(ctx, "chainID", providerAddr)) + // trying to opt in to a stopped consumer chain + providerKeeper.SetConsumerPhase(ctx, "stoppedConsumerId", types.CONSUMER_PHASE_STOPPED) + require.Error(t, providerKeeper.HandleOptIn(ctx, "stoppedConsumerId", providerAddr, "")) + + providerKeeper.SetConsumerPhase(ctx, "consumerId", types.CONSUMER_PHASE_INITIALIZED) + providerKeeper.SetConsumerChainId(ctx, "consumerId", "chainId") + require.False(t, providerKeeper.IsOptedIn(ctx, "consumerId", providerAddr)) + err := providerKeeper.HandleOptIn(ctx, "consumerId", providerAddr, "") + require.NoError(t, err) + require.True(t, providerKeeper.IsOptedIn(ctx, "consumerId", providerAddr)) + + // validator tries to opt in to another chain with chain id ("chainId") while it is already opted in to + // a different chain with the same chain id + providerKeeper.SetConsumerPhase(ctx, "consumerId2", types.CONSUMER_PHASE_INITIALIZED) + providerKeeper.SetConsumerChainId(ctx, "consumerId2", "chainId") + err = providerKeeper.HandleOptIn(ctx, "consumerId2", providerAddr, "") + require.ErrorContains(t, err, "validator is already opted in to a chain") } func TestHandleOptInWithConsumerKey(t *testing.T) { @@ -67,25 +81,26 @@ func TestHandleOptInWithConsumerKey(t *testing.T) { } gomock.InOrder(calls...) - providerKeeper.SetProposedConsumerChain(ctx, "chainID", 1) // create a sample consumer key to assign to the `providerAddr` validator - // on the consumer chain with id `chainID` + // on the consumer chain with `consumerId` consumerKey := "{\"@type\":\"/cosmos.crypto.ed25519.PubKey\",\"key\":\"Ui5Gf1+mtWUdH8u3xlmzdKID+F3PK0sfXZ73GZ6q6is=\"}" expectedConsumerPubKey, err := providerKeeper.ParseConsumerKey(consumerKey) require.NoError(t, err) - err = providerKeeper.HandleOptIn(ctx, "chainID", providerAddr, consumerKey) + providerKeeper.SetConsumerPhase(ctx, "consumerId", types.CONSUMER_PHASE_INITIALIZED) + providerKeeper.SetConsumerChainId(ctx, "consumerId", "consumerId") + err = providerKeeper.HandleOptIn(ctx, "consumerId", providerAddr, consumerKey) require.NoError(t, err) - // assert that the consumeKey was assigned to `providerAddr` validator on chain with id `chainID` - actualConsumerPubKey, found := providerKeeper.GetValidatorConsumerPubKey(ctx, "chainID", providerAddr) + // assert that the consumeKey was assigned to `providerAddr` validator on chain with `consumerId` + actualConsumerPubKey, found := providerKeeper.GetValidatorConsumerPubKey(ctx, "consumerId", providerAddr) require.True(t, found) require.Equal(t, expectedConsumerPubKey, actualConsumerPubKey) // assert that the `consumerAddr` to `providerAddr` association was set as well consumerAddr, _ := ccvtypes.TMCryptoPublicKeyToConsAddr(actualConsumerPubKey) - actualProviderConsAddr, found := providerKeeper.GetValidatorByConsumerAddr(ctx, "chainID", types.NewConsumerConsAddress(consumerAddr)) + actualProviderConsAddr, found := providerKeeper.GetValidatorByConsumerAddr(ctx, "consumerId", types.NewConsumerConsAddress(consumerAddr)) require.True(t, found) require.Equal(t, providerAddr, actualProviderConsAddr) } @@ -94,43 +109,53 @@ func TestHandleOptOut(t *testing.T) { providerKeeper, ctx, ctrl, _ := testkeeper.GetProviderKeeperAndCtx(t, testkeeper.NewInMemKeeperParams(t)) defer ctrl.Finish() + consumerId := "consumerId" + providerAddr := types.NewProviderConsAddress([]byte("providerAddr")) // trying to opt out from a not running chain returns an error require.Error(t, providerKeeper.HandleOptOut(ctx, "unknownChainID", providerAddr)) - // set a consumer client so that the chain is considered running - providerKeeper.SetConsumerClientId(ctx, "chainID", "clientID") + // set the phase and power shaping params + providerKeeper.SetConsumerPhase(ctx, consumerId, types.CONSUMER_PHASE_LAUNCHED) + err := providerKeeper.SetConsumerPowerShapingParameters(ctx, consumerId, types.PowerShapingParameters{}) + require.NoError(t, err) // if validator (`providerAddr`) is already opted in, then an opt-out would remove this validator - providerKeeper.SetOptedIn(ctx, "chainID", providerAddr) - require.True(t, providerKeeper.IsOptedIn(ctx, "chainID", providerAddr)) - providerKeeper.HandleOptOut(ctx, "chainID", providerAddr) - require.False(t, providerKeeper.IsOptedIn(ctx, "chainID", providerAddr)) + providerKeeper.SetOptedIn(ctx, consumerId, providerAddr) + require.True(t, providerKeeper.IsOptedIn(ctx, consumerId, providerAddr)) + err = providerKeeper.AppendOptedInConsumerId(ctx, providerAddr, consumerId) + require.NoError(t, err) + err = providerKeeper.HandleOptOut(ctx, consumerId, providerAddr) + require.NoError(t, err) + require.False(t, providerKeeper.IsOptedIn(ctx, consumerId, providerAddr)) } func TestHandleOptOutFromTopNChain(t *testing.T) { providerKeeper, ctx, ctrl, mocks := testkeeper.GetProviderKeeperAndCtx(t, testkeeper.NewInMemKeeperParams(t)) defer ctrl.Finish() - chainID := "chainID" + consumerId := "consumerId" - // set a consumer client so that the chain is considered running - providerKeeper.SetConsumerClientId(ctx, chainID, "clientID") + // set the phase + providerKeeper.SetConsumerPhase(ctx, consumerId, types.CONSUMER_PHASE_LAUNCHED) // set the chain as Top 50 and create 4 validators with 10%, 20%, 30%, and 40% of the total voting power // respectively - providerKeeper.SetTopN(ctx, "chainID", 50) - valA := createStakingValidator(ctx, mocks, 1, 1, 1) // 10% of the total voting power (can opt out) + err := providerKeeper.SetConsumerPowerShapingParameters(ctx, consumerId, types.PowerShapingParameters{ + Top_N: 50, + }) + require.NoError(t, err) + valA := createStakingValidator(ctx, mocks, 1, 1) // 10% of the total voting power (can opt out) valAConsAddr, _ := valA.GetConsAddr() mocks.MockStakingKeeper.EXPECT().GetValidatorByConsAddr(ctx, valAConsAddr).Return(valA, nil).AnyTimes() - valB := createStakingValidator(ctx, mocks, 2, 2, 2) // 20% of the total voting power (can opt out) + valB := createStakingValidator(ctx, mocks, 2, 2) // 20% of the total voting power (can opt out) valBConsAddr, _ := valB.GetConsAddr() mocks.MockStakingKeeper.EXPECT().GetValidatorByConsAddr(ctx, valBConsAddr).Return(valB, nil).AnyTimes() - valC := createStakingValidator(ctx, mocks, 3, 3, 3) // 30% of the total voting power (cannot opt out) + valC := createStakingValidator(ctx, mocks, 3, 3) // 30% of the total voting power (cannot opt out) valCConsAddr, _ := valC.GetConsAddr() mocks.MockStakingKeeper.EXPECT().GetValidatorByConsAddr(ctx, valCConsAddr).Return(valC, nil).AnyTimes() - valD := createStakingValidator(ctx, mocks, 4, 4, 4) // 40% of the total voting power (cannot opt out) + valD := createStakingValidator(ctx, mocks, 4, 4) // 40% of the total voting power (cannot opt out) valDConsAddr, _ := valD.GetConsAddr() mocks.MockStakingKeeper.EXPECT().GetValidatorByConsAddr(ctx, valDConsAddr).Return(valD, nil).AnyTimes() @@ -139,29 +164,38 @@ func TestHandleOptOutFromTopNChain(t *testing.T) { // initialize the minPowerInTopN correctly minPowerInTopN, err := providerKeeper.ComputeMinPowerInTopN(ctx, []stakingtypes.Validator{valA, valB, valC, valD}, 50) require.NoError(t, err) - providerKeeper.SetMinimumPowerInTopN(ctx, chainID, minPowerInTopN) + providerKeeper.SetMinimumPowerInTopN(ctx, consumerId, minPowerInTopN) // opt in all validators - providerKeeper.SetOptedIn(ctx, chainID, types.NewProviderConsAddress(valAConsAddr)) - providerKeeper.SetOptedIn(ctx, chainID, types.NewProviderConsAddress(valBConsAddr)) - providerKeeper.SetOptedIn(ctx, chainID, types.NewProviderConsAddress(valCConsAddr)) - providerKeeper.SetOptedIn(ctx, chainID, types.NewProviderConsAddress(valDConsAddr)) + providerKeeper.SetOptedIn(ctx, consumerId, types.NewProviderConsAddress(valAConsAddr)) + err = providerKeeper.AppendOptedInConsumerId(ctx, types.NewProviderConsAddress(valAConsAddr), consumerId) + require.NoError(t, err) + providerKeeper.SetOptedIn(ctx, consumerId, types.NewProviderConsAddress(valBConsAddr)) + err = providerKeeper.AppendOptedInConsumerId(ctx, types.NewProviderConsAddress(valBConsAddr), consumerId) + require.NoError(t, err) + providerKeeper.SetOptedIn(ctx, consumerId, types.NewProviderConsAddress(valCConsAddr)) + err = providerKeeper.AppendOptedInConsumerId(ctx, types.NewProviderConsAddress(valCConsAddr), consumerId) + require.NoError(t, err) + providerKeeper.SetOptedIn(ctx, consumerId, types.NewProviderConsAddress(valDConsAddr)) + err = providerKeeper.AppendOptedInConsumerId(ctx, types.NewProviderConsAddress(valDConsAddr), consumerId) + require.NoError(t, err) // validators A and B can opt out because they belong the bottom 30% of validators - require.NoError(t, providerKeeper.HandleOptOut(ctx, chainID, types.NewProviderConsAddress(valAConsAddr))) - require.NoError(t, providerKeeper.HandleOptOut(ctx, chainID, types.NewProviderConsAddress(valBConsAddr))) + require.NoError(t, providerKeeper.HandleOptOut(ctx, consumerId, types.NewProviderConsAddress(valAConsAddr))) + require.NoError(t, providerKeeper.HandleOptOut(ctx, consumerId, types.NewProviderConsAddress(valBConsAddr))) // validators C and D cannot opt out because C has 30% of the voting power and D has 40% of the voting power // and hence both are needed to keep validating a Top 50 chain - require.Error(t, providerKeeper.HandleOptOut(ctx, chainID, types.NewProviderConsAddress(valCConsAddr))) - require.Error(t, providerKeeper.HandleOptOut(ctx, chainID, types.NewProviderConsAddress(valDConsAddr))) + require.Error(t, providerKeeper.HandleOptOut(ctx, consumerId, types.NewProviderConsAddress(valCConsAddr))) + require.Error(t, providerKeeper.HandleOptOut(ctx, consumerId, types.NewProviderConsAddress(valDConsAddr))) // opting out a validator that cannot be found from a Top N chain should also return an error - notFoundValidator := createStakingValidator(ctx, mocks, 5, 5, 5) - notFoundValidatorConsAddr, _ := notFoundValidator.GetConsAddr() + notFoundValidator := createStakingValidator(ctx, mocks, 5, 5) + notFoundValidatorConsAddr, err := notFoundValidator.GetConsAddr() + require.NoError(t, err) mocks.MockStakingKeeper.EXPECT().GetValidatorByConsAddr(ctx, notFoundValidatorConsAddr). Return(stakingtypes.Validator{}, stakingtypes.ErrNoValidatorFound) - require.Error(t, providerKeeper.HandleOptOut(ctx, chainID, types.NewProviderConsAddress(notFoundValidatorConsAddr))) + require.Error(t, providerKeeper.HandleOptOut(ctx, consumerId, types.NewProviderConsAddress(notFoundValidatorConsAddr))) } func TestHandleSetConsumerCommissionRate(t *testing.T) { @@ -174,18 +208,19 @@ func TestHandleSetConsumerCommissionRate(t *testing.T) { require.Error(t, providerKeeper.HandleSetConsumerCommissionRate(ctx, "unknownChainID", providerAddr, math.LegacyZeroDec())) // setup a pending consumer chain - chainID := "pendingChainID" - providerKeeper.SetPendingConsumerAdditionProp(ctx, &types.ConsumerAdditionProposal{ChainId: chainID}) + consumerId := "0" + providerKeeper.FetchAndIncrementConsumerId(ctx) + providerKeeper.SetConsumerPhase(ctx, consumerId, types.CONSUMER_PHASE_INITIALIZED) // check that there's no commission rate set for the validator yet - _, found := providerKeeper.GetConsumerCommissionRate(ctx, chainID, providerAddr) + _, found := providerKeeper.GetConsumerCommissionRate(ctx, consumerId, providerAddr) require.False(t, found) mocks.MockStakingKeeper.EXPECT().MinCommissionRate(ctx).Return(math.LegacyZeroDec(), nil).Times(1) - require.NoError(t, providerKeeper.HandleSetConsumerCommissionRate(ctx, chainID, providerAddr, math.LegacyOneDec())) + require.NoError(t, providerKeeper.HandleSetConsumerCommissionRate(ctx, consumerId, providerAddr, math.LegacyOneDec())) // check that the commission rate is now set - cr, found := providerKeeper.GetConsumerCommissionRate(ctx, chainID, providerAddr) + cr, found := providerKeeper.GetConsumerCommissionRate(ctx, consumerId, providerAddr) require.Equal(t, math.LegacyOneDec(), cr) require.True(t, found) @@ -196,16 +231,16 @@ func TestHandleSetConsumerCommissionRate(t *testing.T) { // try to set a rate slightly below the minimum require.Error(t, providerKeeper.HandleSetConsumerCommissionRate( ctx, - chainID, + consumerId, providerAddr, commissionRate.Sub(math.LegacyNewDec(1).Quo(math.LegacyNewDec(100)))), // 0.5 - 0.01 "commission rate should be rejected (below min), but is not", ) // set a valid commission equal to the minimum - require.NoError(t, providerKeeper.HandleSetConsumerCommissionRate(ctx, chainID, providerAddr, commissionRate)) + require.NoError(t, providerKeeper.HandleSetConsumerCommissionRate(ctx, consumerId, providerAddr, commissionRate)) // check that the rate was set - cr, found = providerKeeper.GetConsumerCommissionRate(ctx, chainID, providerAddr) + cr, found = providerKeeper.GetConsumerCommissionRate(ctx, consumerId, providerAddr) require.Equal(t, commissionRate, cr) require.True(t, found) } @@ -215,24 +250,24 @@ func TestOptInTopNValidators(t *testing.T) { defer ctrl.Finish() // create 4 validators with powers 1, 2, 3, and 1 respectively - valA := createStakingValidator(ctx, mocks, 1, 1, 1) + valA := createStakingValidator(ctx, mocks, 1, 1) valAConsAddr, _ := valA.GetConsAddr() - valB := createStakingValidator(ctx, mocks, 2, 2, 2) + valB := createStakingValidator(ctx, mocks, 2, 2) valBConsAddr, _ := valB.GetConsAddr() - valC := createStakingValidator(ctx, mocks, 3, 3, 3) + valC := createStakingValidator(ctx, mocks, 3, 3) valCConsAddr, _ := valC.GetConsAddr() - valD := createStakingValidator(ctx, mocks, 4, 1, 4) + valD := createStakingValidator(ctx, mocks, 1, 4) valDConsAddr, _ := valD.GetConsAddr() // Start Test 1: opt in all validators with power >= 0 - providerKeeper.OptInTopNValidators(ctx, "chainID", []stakingtypes.Validator{valA, valB, valC, valD}, 0) + providerKeeper.OptInTopNValidators(ctx, "consumerId", []stakingtypes.Validator{valA, valB, valC, valD}, 0) expectedOptedInValidators := []types.ProviderConsAddress{ types.NewProviderConsAddress(valAConsAddr), types.NewProviderConsAddress(valBConsAddr), types.NewProviderConsAddress(valCConsAddr), types.NewProviderConsAddress(valDConsAddr), } - actualOptedInValidators := providerKeeper.GetAllOptedIn(ctx, "chainID") + actualOptedInValidators := providerKeeper.GetAllOptedIn(ctx, "consumerId") // sort validators first to be able to compare sortUpdates := func(addresses []types.ProviderConsAddress) { @@ -246,31 +281,31 @@ func TestOptInTopNValidators(t *testing.T) { require.Equal(t, expectedOptedInValidators, actualOptedInValidators) // reset state for the upcoming checks - providerKeeper.DeleteOptedIn(ctx, "chainID", types.NewProviderConsAddress(valAConsAddr)) - providerKeeper.DeleteOptedIn(ctx, "chainID", types.NewProviderConsAddress(valBConsAddr)) - providerKeeper.DeleteOptedIn(ctx, "chainID", types.NewProviderConsAddress(valCConsAddr)) - providerKeeper.DeleteOptedIn(ctx, "chainID", types.NewProviderConsAddress(valDConsAddr)) + providerKeeper.DeleteOptedIn(ctx, "consumerId", types.NewProviderConsAddress(valAConsAddr)) + providerKeeper.DeleteOptedIn(ctx, "consumerId", types.NewProviderConsAddress(valBConsAddr)) + providerKeeper.DeleteOptedIn(ctx, "consumerId", types.NewProviderConsAddress(valCConsAddr)) + providerKeeper.DeleteOptedIn(ctx, "consumerId", types.NewProviderConsAddress(valDConsAddr)) // Start Test 2: opt in all validators with power >= 1 // We expect the same `expectedOptedInValidators` as when we opted in all validators with power >= 0 because the // validators with the smallest power have power == 1 - providerKeeper.OptInTopNValidators(ctx, "chainID", []stakingtypes.Validator{valA, valB, valC, valD}, 0) - actualOptedInValidators = providerKeeper.GetAllOptedIn(ctx, "chainID") + providerKeeper.OptInTopNValidators(ctx, "consumerId", []stakingtypes.Validator{valA, valB, valC, valD}, 0) + actualOptedInValidators = providerKeeper.GetAllOptedIn(ctx, "consumerId") sortUpdates(actualOptedInValidators) require.Equal(t, expectedOptedInValidators, actualOptedInValidators) - providerKeeper.DeleteOptedIn(ctx, "chainID", types.NewProviderConsAddress(valAConsAddr)) - providerKeeper.DeleteOptedIn(ctx, "chainID", types.NewProviderConsAddress(valBConsAddr)) - providerKeeper.DeleteOptedIn(ctx, "chainID", types.NewProviderConsAddress(valCConsAddr)) - providerKeeper.DeleteOptedIn(ctx, "chainID", types.NewProviderConsAddress(valDConsAddr)) + providerKeeper.DeleteOptedIn(ctx, "consumerId", types.NewProviderConsAddress(valAConsAddr)) + providerKeeper.DeleteOptedIn(ctx, "consumerId", types.NewProviderConsAddress(valBConsAddr)) + providerKeeper.DeleteOptedIn(ctx, "consumerId", types.NewProviderConsAddress(valCConsAddr)) + providerKeeper.DeleteOptedIn(ctx, "consumerId", types.NewProviderConsAddress(valDConsAddr)) // Start Test 3: opt in all validators with power >= 2 and hence we do not expect to opt in validator A - providerKeeper.OptInTopNValidators(ctx, "chainID", []stakingtypes.Validator{valA, valB, valC, valD}, 2) + providerKeeper.OptInTopNValidators(ctx, "consumerId", []stakingtypes.Validator{valA, valB, valC, valD}, 2) expectedOptedInValidators = []types.ProviderConsAddress{ types.NewProviderConsAddress(valBConsAddr), types.NewProviderConsAddress(valCConsAddr), } - actualOptedInValidators = providerKeeper.GetAllOptedIn(ctx, "chainID") + actualOptedInValidators = providerKeeper.GetAllOptedIn(ctx, "consumerId") // sort validators first to be able to compare sortUpdates(expectedOptedInValidators) @@ -278,14 +313,14 @@ func TestOptInTopNValidators(t *testing.T) { require.Equal(t, expectedOptedInValidators, actualOptedInValidators) // reset state for the upcoming checks - providerKeeper.DeleteOptedIn(ctx, "chainID", types.NewProviderConsAddress(valAConsAddr)) - providerKeeper.DeleteOptedIn(ctx, "chainID", types.NewProviderConsAddress(valBConsAddr)) - providerKeeper.DeleteOptedIn(ctx, "chainID", types.NewProviderConsAddress(valCConsAddr)) - providerKeeper.DeleteOptedIn(ctx, "chainID", types.NewProviderConsAddress(valDConsAddr)) + providerKeeper.DeleteOptedIn(ctx, "consumerId", types.NewProviderConsAddress(valAConsAddr)) + providerKeeper.DeleteOptedIn(ctx, "consumerId", types.NewProviderConsAddress(valBConsAddr)) + providerKeeper.DeleteOptedIn(ctx, "consumerId", types.NewProviderConsAddress(valCConsAddr)) + providerKeeper.DeleteOptedIn(ctx, "consumerId", types.NewProviderConsAddress(valDConsAddr)) // Start Test 4: opt in all validators with power >= 4 and hence we do not expect any opted-in validators - providerKeeper.OptInTopNValidators(ctx, "chainID", []stakingtypes.Validator{valA, valB, valC, valD}, 4) - require.Empty(t, providerKeeper.GetAllOptedIn(ctx, "chainID")) + providerKeeper.OptInTopNValidators(ctx, "consumerId", []stakingtypes.Validator{valA, valB, valC, valD}, 4) + require.Empty(t, providerKeeper.GetAllOptedIn(ctx, "consumerId")) } func TestComputeMinPowerInTopN(t *testing.T) { @@ -302,11 +337,11 @@ func TestComputeMinPowerInTopN(t *testing.T) { // 1 => 100% bondedValidators := []stakingtypes.Validator{ - createStakingValidator(ctx, mocks, 1, 5, 1), - createStakingValidator(ctx, mocks, 2, 10, 2), - createStakingValidator(ctx, mocks, 3, 3, 3), - createStakingValidator(ctx, mocks, 4, 1, 4), - createStakingValidator(ctx, mocks, 5, 6, 5), + createStakingValidator(ctx, mocks, 5, 1), + createStakingValidator(ctx, mocks, 10, 2), + createStakingValidator(ctx, mocks, 3, 3), + createStakingValidator(ctx, mocks, 1, 4), + createStakingValidator(ctx, mocks, 6, 5), } m, err := providerKeeper.ComputeMinPowerInTopN(ctx, bondedValidators, 100) @@ -356,34 +391,58 @@ func TestComputeMinPowerInTopN(t *testing.T) { require.Error(t, err) } -// TestCanValidateChain returns true if `validator` is opted in, in `chainID. +// TestCanValidateChain returns true if `validator` is opted in, in `consumerId. func TestCanValidateChain(t *testing.T) { providerKeeper, ctx, ctrl, mocks := testkeeper.GetProviderKeeperAndCtx(t, testkeeper.NewInMemKeeperParams(t)) defer ctrl.Finish() - validator := createStakingValidator(ctx, mocks, 0, 1, 1) + consumerID := "0" + + validator := createStakingValidator(ctx, mocks, 1, 1) // adds GetLastValidatorPower expectation to mocks consAddr, _ := validator.GetConsAddr() providerAddr := types.NewProviderConsAddress(consAddr) // with no allowlist or denylist, the validator has to be opted in, in order to consider it - require.False(t, providerKeeper.CanValidateChain(ctx, "chainID", providerAddr)) - providerKeeper.SetOptedIn(ctx, "chainID", types.NewProviderConsAddress(consAddr)) - require.True(t, providerKeeper.CanValidateChain(ctx, "chainID", providerAddr)) + powerShapingParameters, err := providerKeeper.GetConsumerPowerShapingParameters(ctx, consumerID) + require.Error(t, err) + require.False(t, providerKeeper.CanValidateChain(ctx, consumerID, providerAddr, powerShapingParameters.Top_N, 0)) + + // with TopN chains, the validator can be considered, + mocks.MockStakingKeeper.EXPECT().GetValidatorByConsAddr(gomock.Any(), providerAddr.Address).Return(validator, nil).Times(2) + err = providerKeeper.SetConsumerPowerShapingParameters(ctx, consumerID, types.PowerShapingParameters{Top_N: 50}) + require.NoError(t, err) + powerShapingParameters, err = providerKeeper.GetConsumerPowerShapingParameters(ctx, consumerID) + require.NoError(t, err) + // validator's power is LT the min power + require.False(t, providerKeeper.CanValidateChain(ctx, consumerID, providerAddr, powerShapingParameters.Top_N, 2)) + // validator's power is GTE the min power + require.True(t, providerKeeper.CanValidateChain(ctx, consumerID, providerAddr, powerShapingParameters.Top_N, 1)) + + // when validator is opted-in it can validate regardless of its min power + providerKeeper.SetOptedIn(ctx, consumerID, types.NewProviderConsAddress(consAddr)) + require.True(t, providerKeeper.CanValidateChain(ctx, consumerID, providerAddr, powerShapingParameters.Top_N, 2)) + + // With OptIn chains, validator can validate only if it has already opted-in + err = providerKeeper.SetConsumerPowerShapingParameters(ctx, consumerID, types.PowerShapingParameters{Top_N: 0}) + require.NoError(t, err) + powerShapingParameters, err = providerKeeper.GetConsumerPowerShapingParameters(ctx, consumerID) + require.NoError(t, err) + require.True(t, providerKeeper.CanValidateChain(ctx, consumerID, providerAddr, powerShapingParameters.Top_N, 2)) // create an allow list but do not add the validator `providerAddr` to it - validatorA := createStakingValidator(ctx, mocks, 1, 1, 2) + validatorA := createStakingValidator(ctx, mocks, 1, 2) consAddrA, _ := validatorA.GetConsAddr() - providerKeeper.SetAllowlist(ctx, "chainID", types.NewProviderConsAddress(consAddrA)) - require.False(t, providerKeeper.CanValidateChain(ctx, "chainID", providerAddr)) - providerKeeper.SetAllowlist(ctx, "chainID", types.NewProviderConsAddress(consAddr)) - require.True(t, providerKeeper.CanValidateChain(ctx, "chainID", providerAddr)) + providerKeeper.SetAllowlist(ctx, consumerID, types.NewProviderConsAddress(consAddrA)) + require.False(t, providerKeeper.CanValidateChain(ctx, consumerID, providerAddr, powerShapingParameters.Top_N, 1)) + providerKeeper.SetAllowlist(ctx, consumerID, types.NewProviderConsAddress(consAddr)) + require.True(t, providerKeeper.CanValidateChain(ctx, consumerID, providerAddr, powerShapingParameters.Top_N, 1)) // create a denylist but do not add validator `providerAddr` to it - providerKeeper.SetDenylist(ctx, "chainID", types.NewProviderConsAddress(consAddrA)) - require.True(t, providerKeeper.CanValidateChain(ctx, "chainID", providerAddr)) + providerKeeper.SetDenylist(ctx, consumerID, types.NewProviderConsAddress(consAddrA)) + require.True(t, providerKeeper.CanValidateChain(ctx, consumerID, providerAddr, powerShapingParameters.Top_N, 1)) // add validator `providerAddr` to the denylist - providerKeeper.SetDenylist(ctx, "chainID", types.NewProviderConsAddress(consAddr)) - require.False(t, providerKeeper.CanValidateChain(ctx, "chainID", providerAddr)) + providerKeeper.SetDenylist(ctx, consumerID, types.NewProviderConsAddress(consAddr)) + require.False(t, providerKeeper.CanValidateChain(ctx, consumerID, providerAddr, powerShapingParameters.Top_N, 1)) } func TestCapValidatorSet(t *testing.T) { @@ -409,27 +468,54 @@ func TestCapValidatorSet(t *testing.T) { } validators := []types.ConsensusValidator{validatorA, validatorB, validatorC} - consumerValidators := providerKeeper.CapValidatorSet(ctx, "chainID", validators) + powerShapingParameters, err := providerKeeper.GetConsumerPowerShapingParameters(ctx, "consumerId") + require.Error(t, err) + consumerValidators := providerKeeper.CapValidatorSet(ctx, powerShapingParameters, validators) require.Equal(t, validators, consumerValidators) - providerKeeper.SetValidatorSetCap(ctx, "chainID", 0) - consumerValidators = providerKeeper.CapValidatorSet(ctx, "chainID", validators) + err = providerKeeper.SetConsumerPowerShapingParameters(ctx, "consumerId", types.PowerShapingParameters{ + ValidatorSetCap: 0, + }) + require.NoError(t, err) + powerShapingParameters, err = providerKeeper.GetConsumerPowerShapingParameters(ctx, "consumerId") + require.NoError(t, err) + consumerValidators = providerKeeper.CapValidatorSet(ctx, powerShapingParameters, validators) require.Equal(t, validators, consumerValidators) - providerKeeper.SetValidatorSetCap(ctx, "chainID", 100) - consumerValidators = providerKeeper.CapValidatorSet(ctx, "chainID", validators) + err = providerKeeper.SetConsumerPowerShapingParameters(ctx, "consumerId", types.PowerShapingParameters{ + ValidatorSetCap: 100, + }) + require.NoError(t, err) + powerShapingParameters, err = providerKeeper.GetConsumerPowerShapingParameters(ctx, "consumerId") + require.NoError(t, err) + consumerValidators = providerKeeper.CapValidatorSet(ctx, powerShapingParameters, validators) require.Equal(t, validators, consumerValidators) - providerKeeper.SetValidatorSetCap(ctx, "chainID", 1) - consumerValidators = providerKeeper.CapValidatorSet(ctx, "chainID", validators) + err = providerKeeper.SetConsumerPowerShapingParameters(ctx, "consumerId", types.PowerShapingParameters{ + ValidatorSetCap: 1, + }) + require.NoError(t, err) + powerShapingParameters, err = providerKeeper.GetConsumerPowerShapingParameters(ctx, "consumerId") + require.NoError(t, err) + consumerValidators = providerKeeper.CapValidatorSet(ctx, powerShapingParameters, validators) require.Equal(t, []types.ConsensusValidator{validatorC}, consumerValidators) - providerKeeper.SetValidatorSetCap(ctx, "chainID", 2) - consumerValidators = providerKeeper.CapValidatorSet(ctx, "chainID", validators) + err = providerKeeper.SetConsumerPowerShapingParameters(ctx, "consumerId", types.PowerShapingParameters{ + ValidatorSetCap: 2, + }) + require.NoError(t, err) + powerShapingParameters, err = providerKeeper.GetConsumerPowerShapingParameters(ctx, "consumerId") + require.NoError(t, err) + consumerValidators = providerKeeper.CapValidatorSet(ctx, powerShapingParameters, validators) require.Equal(t, []types.ConsensusValidator{validatorC, validatorB}, consumerValidators) - providerKeeper.SetValidatorSetCap(ctx, "chainID", 3) - consumerValidators = providerKeeper.CapValidatorSet(ctx, "chainID", validators) + err = providerKeeper.SetConsumerPowerShapingParameters(ctx, "consumerId", types.PowerShapingParameters{ + ValidatorSetCap: 3, + }) + require.NoError(t, err) + powerShapingParameters, err = providerKeeper.GetConsumerPowerShapingParameters(ctx, "consumerId") + require.NoError(t, err) + consumerValidators = providerKeeper.CapValidatorSet(ctx, powerShapingParameters, validators) require.Equal(t, []types.ConsensusValidator{validatorC, validatorB, validatorA}, consumerValidators) } @@ -477,13 +563,20 @@ func TestCapValidatorsPower(t *testing.T) { } // no capping takes place because validators power-cap is not set - cappedValidators := providerKeeper.CapValidatorsPower(ctx, "chainID", validators) + powerShapingParameters, err := providerKeeper.GetConsumerPowerShapingParameters(ctx, "consumerId") + require.Error(t, err) + cappedValidators := providerKeeper.CapValidatorsPower(ctx, powerShapingParameters.ValidatorsPowerCap, validators) sortValidators(validators) sortValidators(cappedValidators) require.Equal(t, validators, cappedValidators) - providerKeeper.SetValidatorsPowerCap(ctx, "chainID", 33) - cappedValidators = providerKeeper.CapValidatorsPower(ctx, "chainID", validators) + err = providerKeeper.SetConsumerPowerShapingParameters(ctx, "consumerId", types.PowerShapingParameters{ + ValidatorsPowerCap: 33, + }) + require.NoError(t, err) + powerShapingParameters, err = providerKeeper.GetConsumerPowerShapingParameters(ctx, "consumerId") + require.NoError(t, err) + cappedValidators = providerKeeper.CapValidatorsPower(ctx, powerShapingParameters.ValidatorsPowerCap, validators) sortValidators(expectedValidators) sortValidators(cappedValidators) require.Equal(t, expectedValidators, cappedValidators) @@ -687,7 +780,7 @@ func findConsumerValidator(t *testing.T, v types.ConsensusValidator, valsAfter [ func createStakingValidatorsAndMocks(ctx sdk.Context, mocks testkeeper.MockedKeepers, powers ...int64) ([]stakingtypes.Validator, []types.ProviderConsAddress) { var validators []stakingtypes.Validator for i, power := range powers { - val := createStakingValidator(ctx, mocks, i, power, i) + val := createStakingValidator(ctx, mocks, power, i) val.Tokens = math.NewInt(power) val.Status = stakingtypes.Bonded validators = append(validators, val) @@ -742,9 +835,8 @@ func TestFulfillsMinStake(t *testing.T) { for _, tc := range testCases { t.Run(tc.name, func(t *testing.T) { - providerKeeper.SetMinStake(ctx, "chainID", tc.minStake) for i, valAddr := range consAddrs { - result := providerKeeper.FulfillsMinStake(ctx, "chainID", valAddr) + result := providerKeeper.FulfillsMinStake(ctx, tc.minStake, valAddr) require.Equal(t, tc.expectedFulfill[i], result) } }) @@ -764,7 +856,7 @@ func TestIfInactiveValsDisallowedProperty(t *testing.T) { // opt the validators in for _, valAddr := range consAddrs { - providerKeeper.SetOptedIn(ctx, "chainID", valAddr) + providerKeeper.SetOptedIn(ctx, "consumerId", valAddr) } // Randomly choose values for parameters @@ -774,14 +866,20 @@ func TestIfInactiveValsDisallowedProperty(t *testing.T) { // Set up the parameters in the provider keeper // do not allow inactive validators - providerKeeper.SetInactiveValidatorsAllowed(ctx, "chainID", false) - providerKeeper.SetMinStake(ctx, "chainID", minStake) + err := providerKeeper.SetConsumerPowerShapingParameters(ctx, "consumerId", types.PowerShapingParameters{ + MinStake: minStake, + AllowInactiveVals: false, + }) + require.NoError(t, err) params := providerKeeper.GetParams(ctx) params.MaxProviderConsensusValidators = int64(maxProviderConsensusVals) providerKeeper.SetParams(ctx, params) + powerShapingParameters, err := providerKeeper.GetConsumerPowerShapingParameters(ctx, "consumerId") + require.NoError(t, err) + // Compute the next validators - nextVals := providerKeeper.ComputeNextValidators(ctx, "chainID", vals) + nextVals := providerKeeper.ComputeNextValidators(ctx, "consumerId", vals, powerShapingParameters, 0) // Check that the length of nextVals is at most maxProviderConsensusVals require.LessOrEqual(r, len(nextVals), int(maxProviderConsensusVals), "The length of nextVals should be at most maxProviderConsensusVals") @@ -804,3 +902,73 @@ func TestIfInactiveValsDisallowedProperty(t *testing.T) { } }) } + +func TestHasMinPower(t *testing.T) { + pk, ctx, ctrl, mocks := testkeeper.GetProviderKeeperAndCtx(t, testkeeper.NewInMemKeeperParams(t)) + defer ctrl.Finish() + + providerConsPubKey := ed25519.GenPrivKeyFromSecret([]byte{1}).PubKey() + consAddr := sdk.ConsAddress(providerConsPubKey.Address()) + providerAddr := types.NewProviderConsAddress(consAddr) + + testCases := []struct { + name string + minPower uint64 + expectation func(sdk.ConsAddress, testkeeper.MockedKeepers) + hasMinPower bool + }{ + { + name: "cannot find validator by cons address", + expectation: func(sdk.ConsAddress, testkeeper.MockedKeepers) { + mocks.MockStakingKeeper.EXPECT().GetValidatorByConsAddr(gomock.Any(), consAddr). + Return(stakingtypes.Validator{}, fmt.Errorf("validator not found")).Times(1) + }, + hasMinPower: false, + }, { + name: "cannot convert validator operator address", + expectation: func(consAddr sdk.ConsAddress, mocks testkeeper.MockedKeepers) { + mocks.MockStakingKeeper.EXPECT().GetValidatorByConsAddr(gomock.Any(), consAddr).Return(stakingtypes.Validator{OperatorAddress: "xxxx"}, nil).Times(1) + }, + hasMinPower: false, + }, { + name: "cannot find last validator power", + expectation: func(consAddr sdk.ConsAddress, mocks testkeeper.MockedKeepers) { + valAddr := sdk.ValAddress(providerAddr.Address.Bytes()) + mocks.MockStakingKeeper.EXPECT().GetValidatorByConsAddr(gomock.Any(), consAddr). + Return(stakingtypes.Validator{OperatorAddress: valAddr.String()}, nil) + mocks.MockStakingKeeper.EXPECT().GetLastValidatorPower(gomock.Any(), valAddr). + Return(int64(0), fmt.Errorf("last power not found")).Times(1) + }, + hasMinPower: false, + }, { + name: "validator power is LT min power", + expectation: func(consAddr sdk.ConsAddress, mocks testkeeper.MockedKeepers) { + valAddr := sdk.ValAddress(providerAddr.Address.Bytes()) + mocks.MockStakingKeeper.EXPECT().GetValidatorByConsAddr(gomock.Any(), consAddr). + Return(stakingtypes.Validator{OperatorAddress: valAddr.String()}, nil) + mocks.MockStakingKeeper.EXPECT().GetLastValidatorPower(gomock.Any(), valAddr). + Return(int64(5), nil).Times(1) + }, + hasMinPower: false, + }, { + name: "validator power is GTE min power", + expectation: func(consAddr sdk.ConsAddress, mocks testkeeper.MockedKeepers) { + valAddr := sdk.ValAddress(providerAddr.Address.Bytes()) + mocks.MockStakingKeeper.EXPECT().GetValidatorByConsAddr(gomock.Any(), consAddr). + Return(stakingtypes.Validator{OperatorAddress: valAddr.String()}, nil) + mocks.MockStakingKeeper.EXPECT().GetLastValidatorPower(gomock.Any(), valAddr). + Return(int64(10), nil).Times(1) + }, + hasMinPower: true, + }, + } + + minPower := int64(10) + + for _, tc := range testCases { + t.Run(tc.name, func(t *testing.T) { + tc.expectation(consAddr, mocks) + require.Equal(t, tc.hasMinPower, pk.HasMinPower(ctx, providerAddr, minPower)) + }) + } +} diff --git a/x/ccv/provider/keeper/permissionless.go b/x/ccv/provider/keeper/permissionless.go new file mode 100644 index 0000000000..aa32b496a4 --- /dev/null +++ b/x/ccv/provider/keeper/permissionless.go @@ -0,0 +1,289 @@ +package keeper + +import ( + "encoding/binary" + "fmt" + "strconv" + + sdk "github.com/cosmos/cosmos-sdk/types" + "github.com/cosmos/interchain-security/v5/x/ccv/provider/types" +) + +// setConsumerId sets the provided consumerId +func (k Keeper) setConsumerId(ctx sdk.Context, consumerId uint64) { + store := ctx.KVStore(k.storeKey) + + buf := make([]byte, 8) + binary.BigEndian.PutUint64(buf, consumerId) + + store.Set(types.ConsumerIdKey(), buf) +} + +// GetConsumerId returns the next to-be-assigned consumer id +func (k Keeper) GetConsumerId(ctx sdk.Context) (uint64, bool) { + store := ctx.KVStore(k.storeKey) + buf := store.Get(types.ConsumerIdKey()) + if buf == nil { + return 0, false + } + return binary.BigEndian.Uint64(buf), true +} + +// FetchAndIncrementConsumerId fetches the first consumer id that can be used and increments the +// underlying consumer id +func (k Keeper) FetchAndIncrementConsumerId(ctx sdk.Context) string { + consumerId, _ := k.GetConsumerId(ctx) + k.setConsumerId(ctx, consumerId+1) + return strconv.FormatUint(consumerId, 10) +} + +// GetConsumerChainId returns the chain id associated with this consumer id +func (k Keeper) GetConsumerChainId(ctx sdk.Context, consumerId string) (string, error) { + store := ctx.KVStore(k.storeKey) + bz := store.Get(types.ConsumerIdToChainIdKey(consumerId)) + if bz == nil { + return "", fmt.Errorf("failed to retrieve chain id for consumer id (%s)", consumerId) + } + return string(bz), nil +} + +// SetConsumerChainId sets the chain id associated with this consumer id +func (k Keeper) SetConsumerChainId(ctx sdk.Context, consumerId string, chainId string) { + store := ctx.KVStore(k.storeKey) + store.Set(types.ConsumerIdToChainIdKey(consumerId), []byte(chainId)) +} + +// DeleteConsumerChainId deletes the chain id associated with this consumer id +func (k Keeper) DeleteConsumerChainId(ctx sdk.Context, consumerId string) { + store := ctx.KVStore(k.storeKey) + store.Delete(types.ConsumerIdToChainIdKey(consumerId)) +} + +// GetConsumerOwnerAddress returns the owner address associated with this consumer id +func (k Keeper) GetConsumerOwnerAddress(ctx sdk.Context, consumerId string) (string, error) { + store := ctx.KVStore(k.storeKey) + bz := store.Get(types.ConsumerIdToOwnerAddressKey(consumerId)) + if bz == nil { + return "", fmt.Errorf("failed to retrieve owner address for consumer id (%s)", consumerId) + } + return string(bz), nil +} + +// SetConsumerOwnerAddress sets the chain id associated with this consumer id +func (k Keeper) SetConsumerOwnerAddress(ctx sdk.Context, consumerId string, chainId string) { + store := ctx.KVStore(k.storeKey) + store.Set(types.ConsumerIdToOwnerAddressKey(consumerId), []byte(chainId)) +} + +// DeleteConsumerOwnerAddress deletes the owner address associated with this consumer id +func (k Keeper) DeleteConsumerOwnerAddress(ctx sdk.Context, consumerId string) { + store := ctx.KVStore(k.storeKey) + store.Delete(types.ConsumerIdToOwnerAddressKey(consumerId)) +} + +// GetConsumerMetadata returns the registration record associated with this consumer id +func (k Keeper) GetConsumerMetadata(ctx sdk.Context, consumerId string) (types.ConsumerMetadata, error) { + store := ctx.KVStore(k.storeKey) + bz := store.Get(types.ConsumerIdToMetadataKey(consumerId)) + if bz == nil { + return types.ConsumerMetadata{}, fmt.Errorf("failed to retrieve metadata for consumer id (%s)", consumerId) + } + var metadata types.ConsumerMetadata + if err := metadata.Unmarshal(bz); err != nil { + return types.ConsumerMetadata{}, fmt.Errorf("failed to unmarshal metadata for consumer id (%s): %w", consumerId, err) + } + return metadata, nil +} + +// SetConsumerMetadata sets the registration record associated with this consumer id +func (k Keeper) SetConsumerMetadata(ctx sdk.Context, consumerId string, metadata types.ConsumerMetadata) error { + store := ctx.KVStore(k.storeKey) + bz, err := metadata.Marshal() + if err != nil { + return fmt.Errorf("failed to marshal registration metadata (%+v) for consumer id (%s): %w", metadata, consumerId, err) + } + store.Set(types.ConsumerIdToMetadataKey(consumerId), bz) + return nil +} + +// DeleteConsumerMetadata deletes the metadata associated with this consumer id +func (k Keeper) DeleteConsumerMetadata(ctx sdk.Context, consumerId string) { + store := ctx.KVStore(k.storeKey) + store.Delete(types.ConsumerIdToMetadataKey(consumerId)) +} + +// GetConsumerInitializationParameters returns the initialization parameters associated with this consumer id +func (k Keeper) GetConsumerInitializationParameters(ctx sdk.Context, consumerId string) (types.ConsumerInitializationParameters, error) { + store := ctx.KVStore(k.storeKey) + bz := store.Get(types.ConsumerIdToInitializationParametersKey(consumerId)) + if bz == nil { + return types.ConsumerInitializationParameters{}, fmt.Errorf("failed to retrieve initialization parameters for consumer id (%s)", consumerId) + } + var initializationParameters types.ConsumerInitializationParameters + if err := initializationParameters.Unmarshal(bz); err != nil { + return types.ConsumerInitializationParameters{}, fmt.Errorf("failed to unmarshal initialization parameters for consumer id (%s): %w", consumerId, err) + } + return initializationParameters, nil +} + +// SetConsumerInitializationParameters sets the initialization parameters associated with this consumer id +func (k Keeper) SetConsumerInitializationParameters(ctx sdk.Context, consumerId string, parameters types.ConsumerInitializationParameters) error { + store := ctx.KVStore(k.storeKey) + bz, err := parameters.Marshal() + if err != nil { + return fmt.Errorf("failed to marshal initialization parameters (%+v) for consumer id (%s): %w", parameters, consumerId, err) + } + store.Set(types.ConsumerIdToInitializationParametersKey(consumerId), bz) + return nil +} + +// DeleteConsumerInitializationParameters deletes the initialization parameters associated with this consumer id +func (k Keeper) DeleteConsumerInitializationParameters(ctx sdk.Context, consumerId string) { + store := ctx.KVStore(k.storeKey) + store.Delete(types.ConsumerIdToInitializationParametersKey(consumerId)) +} + +// GetConsumerPhase returns the phase associated with this consumer id +func (k Keeper) GetConsumerPhase(ctx sdk.Context, consumerId string) types.ConsumerPhase { + store := ctx.KVStore(k.storeKey) + buf := store.Get(types.ConsumerIdToPhaseKey(consumerId)) + if buf == nil { + return types.CONSUMER_PHASE_UNSPECIFIED + } + phase := types.ConsumerPhase(binary.BigEndian.Uint32(buf)) + return phase +} + +// SetConsumerPhase sets the phase associated with this consumer id +func (k Keeper) SetConsumerPhase(ctx sdk.Context, consumerId string, phase types.ConsumerPhase) { + store := ctx.KVStore(k.storeKey) + phaseBytes := make([]byte, 8) + binary.BigEndian.PutUint32(phaseBytes, uint32(phase)) + store.Set(types.ConsumerIdToPhaseKey(consumerId), phaseBytes) +} + +// DeleteConsumerPhase deletes the phase associated with this consumer id +func (k Keeper) DeleteConsumerPhase(ctx sdk.Context, consumerId string) { + store := ctx.KVStore(k.storeKey) + store.Delete(types.ConsumerIdToPhaseKey(consumerId)) +} + +// IsConsumerActive checks if a consumer chain is either registered, initialized, or launched. +func (k Keeper) IsConsumerActive(ctx sdk.Context, consumerId string) bool { + phase := k.GetConsumerPhase(ctx, consumerId) + return phase == types.CONSUMER_PHASE_REGISTERED || + phase == types.CONSUMER_PHASE_INITIALIZED || + phase == types.CONSUMER_PHASE_LAUNCHED +} + +// GetOptedInConsumerIds returns all the consumer ids where the given validator is opted in +func (k Keeper) GetOptedInConsumerIds(ctx sdk.Context, providerAddr types.ProviderConsAddress) (types.ConsumerIds, error) { + store := ctx.KVStore(k.storeKey) + bz := store.Get(types.ProviderConsAddrToOptedInConsumerIdsKey(providerAddr)) + if bz == nil { + return types.ConsumerIds{}, nil + } + + var consumerIds types.ConsumerIds + if err := consumerIds.Unmarshal(bz); err != nil { + return types.ConsumerIds{}, fmt.Errorf("failed to unmarshal consumer ids: %w", err) + } + + return consumerIds, nil +} + +// AppendOptedInConsumerId appends given consumer id to the list of consumers that validator has opted in +// TODO (PERMISSIONLESS) -- combine it with SetOptedIn +func (k Keeper) AppendOptedInConsumerId(ctx sdk.Context, providerAddr types.ProviderConsAddress, consumerId string) error { + store := ctx.KVStore(k.storeKey) + + consumers, err := k.GetOptedInConsumerIds(ctx, providerAddr) + if err != nil { + return err + } + + consumersWithAppend := types.ConsumerIds{ + Ids: append(consumers.Ids, consumerId), + } + + bz, err := consumersWithAppend.Marshal() + if err != nil { + return err + } + + store.Set(types.ProviderConsAddrToOptedInConsumerIdsKey(providerAddr), bz) + return nil +} + +// RemoveOptedInConsumerId removes the consumer id from this validator because it is not opted in anymore +func (k Keeper) RemoveOptedInConsumerId(ctx sdk.Context, providerAddr types.ProviderConsAddress, consumerId string) error { + store := ctx.KVStore(k.storeKey) + + consumers, err := k.GetOptedInConsumerIds(ctx, providerAddr) + if err != nil { + return err + } + + if len(consumers.Ids) == 0 { + return fmt.Errorf("no consumer ids found for this provviderAddr: %s", providerAddr.String()) + } + + // find the index of the consumer we want to remove + index := -1 + for i := 0; i < len(consumers.Ids); i = i + 1 { + if consumers.Ids[i] == consumerId { + index = i + break + } + } + + if index == -1 { + return fmt.Errorf("failed to find consumer id (%s)", consumerId) + } + + if len(consumers.Ids) == 1 { + store.Delete(types.ProviderConsAddrToOptedInConsumerIdsKey(providerAddr)) + return nil + } + + consumersWithRemoval := types.ConsumerIds{ + Ids: append(consumers.Ids[:index], consumers.Ids[index+1:]...), + } + + bz, err := consumersWithRemoval.Marshal() + if err != nil { + return err + } + + store.Set(types.ProviderConsAddrToOptedInConsumerIdsKey(providerAddr), bz) + return nil +} + +// IsValidatorOptedInToChainId checks if the validator with `providerAddr` is opted into the chain with the specified `chainId`. +// It returns `found == true` and the corresponding chain's `consumerId` if the validator is opted in. Otherwise, it returns an empty string +// for `consumerId` and `found == false`. +func (k Keeper) IsValidatorOptedInToChainId(ctx sdk.Context, providerAddr types.ProviderConsAddress, chainId string) (string, bool) { + consumers, err := k.GetOptedInConsumerIds(ctx, providerAddr) + if err != nil { + k.Logger(ctx).Error("failed to retrieve the consumer ids this validator is opted in to", + "providerAddr", providerAddr, + "error", err) + return "", false + } + + for _, consumerId := range consumers.Ids { + consumerChainId, err := k.GetConsumerChainId(ctx, consumerId) + if err != nil { + k.Logger(ctx).Error("cannot find chain id", + "consumerId", consumerId, + "error", err) + continue + } + + if consumerChainId == chainId { + return consumerId, true + } + + } + return "", false +} diff --git a/x/ccv/provider/keeper/permissionless_test.go b/x/ccv/provider/keeper/permissionless_test.go new file mode 100644 index 0000000000..dbb86cb4d4 --- /dev/null +++ b/x/ccv/provider/keeper/permissionless_test.go @@ -0,0 +1,269 @@ +package keeper_test + +import ( + "testing" + "time" + + "github.com/cosmos/ibc-go/v8/modules/core/02-client/types" + testkeeper "github.com/cosmos/interchain-security/v5/testutil/keeper" + providertypes "github.com/cosmos/interchain-security/v5/x/ccv/provider/types" + "github.com/stretchr/testify/require" +) + +// TestConsumerId tests setters and getters of consumer id (i.e., `FetchAndIncrementConsumerId` and `GetConsumerId`) +func TestConsumerId(t *testing.T) { + providerKeeper, ctx, ctrl, _ := testkeeper.GetProviderKeeperAndCtx(t, testkeeper.NewInMemKeeperParams(t)) + defer ctrl.Finish() + + _, found := providerKeeper.GetConsumerId(ctx) + require.False(t, found) + + consumerId := providerKeeper.FetchAndIncrementConsumerId(ctx) + require.Equal(t, "0", consumerId) + consumerIdNum, found := providerKeeper.GetConsumerId(ctx) + require.Equal(t, uint64(1), consumerIdNum) + require.True(t, found) + + consumerId = providerKeeper.FetchAndIncrementConsumerId(ctx) + require.Equal(t, "1", consumerId) + consumerIdNum, found = providerKeeper.GetConsumerId(ctx) + require.Equal(t, uint64(2), consumerIdNum) + require.True(t, found) +} + +// TestConsumerChainId tests the getter, setter, and deletion of the consumer to chain id methods +func TestConsumerChainId(t *testing.T) { + providerKeeper, ctx, ctrl, _ := testkeeper.GetProviderKeeperAndCtx(t, testkeeper.NewInMemKeeperParams(t)) + defer ctrl.Finish() + + _, err := providerKeeper.GetConsumerChainId(ctx, "chainId") + require.Error(t, err, "failed to retrieve chain id") + + providerKeeper.SetConsumerChainId(ctx, "chainId", "chainId") + chainId, err := providerKeeper.GetConsumerChainId(ctx, "chainId") + require.NoError(t, err) + require.Equal(t, "chainId", chainId) + + // write under a different key + providerKeeper.SetConsumerChainId(ctx, "consumerId2", "chainId") + chainId, err = providerKeeper.GetConsumerChainId(ctx, "consumerId2") + require.NoError(t, err) + require.Equal(t, "chainId", chainId) + + // assert that overwriting the current key works + providerKeeper.SetConsumerChainId(ctx, "chainId", "chainId2") + chainId, err = providerKeeper.GetConsumerChainId(ctx, "chainId") + require.NoError(t, err) + require.Equal(t, "chainId2", chainId) + + providerKeeper.DeleteConsumerChainId(ctx, "chainId") + _, err = providerKeeper.GetConsumerChainId(ctx, "chainId") + require.Error(t, err, "failed to retrieve chain id") +} + +// TestConsumerOwnerAddress tests the getter, setter, and deletion of the consumer to owner address methods +func TestConsumerOwnerAddress(t *testing.T) { + providerKeeper, ctx, ctrl, _ := testkeeper.GetProviderKeeperAndCtx(t, testkeeper.NewInMemKeeperParams(t)) + defer ctrl.Finish() + + _, err := providerKeeper.GetConsumerOwnerAddress(ctx, "ownerAddress") + require.Error(t, err, "failed to retrieve owner address") + + providerKeeper.SetConsumerOwnerAddress(ctx, "consumerId", "owner address") + ownerAddress, err := providerKeeper.GetConsumerOwnerAddress(ctx, "consumerId") + require.NoError(t, err) + require.Equal(t, "owner address", ownerAddress) + + // write under a different key + providerKeeper.SetConsumerOwnerAddress(ctx, "consumerId2", "owner address") + ownerAddress, err = providerKeeper.GetConsumerOwnerAddress(ctx, "consumerId2") + require.NoError(t, err) + require.Equal(t, "owner address", ownerAddress) + + // assert that overwriting the current key works + providerKeeper.SetConsumerOwnerAddress(ctx, "consumerId", "owner address2") + ownerAddress, err = providerKeeper.GetConsumerOwnerAddress(ctx, "consumerId") + require.NoError(t, err) + require.Equal(t, "owner address2", ownerAddress) + + providerKeeper.DeleteConsumerOwnerAddress(ctx, "consumerId") + _, err = providerKeeper.GetConsumerChainId(ctx, "consumerId") + require.Error(t, err, "failed to retrieve owner address") +} + +// TestConsumerMetadata tests the getter, setter, and deletion of the consumer id to consumer metadata methods +func TestConsumerMetadata(t *testing.T) { + providerKeeper, ctx, ctrl, _ := testkeeper.GetProviderKeeperAndCtx(t, testkeeper.NewInMemKeeperParams(t)) + defer ctrl.Finish() + + _, err := providerKeeper.GetConsumerMetadata(ctx, "consumerId") + require.Error(t, err) + + expectedMetadata := providertypes.ConsumerMetadata{ + Name: "name", + Description: "description", + Metadata: "metadata", + //ChainId: "chain_id", + } + providerKeeper.SetConsumerMetadata(ctx, "consumerId", expectedMetadata) + actualMetadata, err := providerKeeper.GetConsumerMetadata(ctx, "consumerId") + require.NoError(t, err) + require.Equal(t, expectedMetadata, actualMetadata) + + // assert that overwriting the current registration record works + expectedMetadata = providertypes.ConsumerMetadata{ + Name: "name 2", + Description: "description 2", + Metadata: "metadata 2", + //ChainId: "chain_id2", + } + providerKeeper.SetConsumerMetadata(ctx, "consumerId", expectedMetadata) + actualMetadata, err = providerKeeper.GetConsumerMetadata(ctx, "consumerId") + require.NoError(t, err) + require.Equal(t, expectedMetadata, actualMetadata) + + providerKeeper.DeleteConsumerMetadata(ctx, "consumerId") + actualMetadata, err = providerKeeper.GetConsumerMetadata(ctx, "consumerId") + require.Error(t, err) + require.Equal(t, providertypes.ConsumerMetadata{}, actualMetadata) +} + +// TestConsumerInitializationParameters tests the getter, setter, and deletion of the consumer id to initialization parameters methods +func TestConsumerInitializationParameters(t *testing.T) { + providerKeeper, ctx, ctrl, _ := testkeeper.GetProviderKeeperAndCtx(t, testkeeper.NewInMemKeeperParams(t)) + defer ctrl.Finish() + + _, err := providerKeeper.GetConsumerInitializationParameters(ctx, "consumerId") + require.Error(t, err) + + expectedInitializationParameters := providertypes.ConsumerInitializationParameters{ + InitialHeight: types.Height{RevisionNumber: 1, RevisionHeight: 2}, + GenesisHash: []byte{0, 1}, + BinaryHash: []byte{2, 3}, + SpawnTime: time.Unix(1, 2).UTC(), + UnbondingPeriod: time.Duration(3456), + CcvTimeoutPeriod: time.Duration(789), + TransferTimeoutPeriod: time.Duration(101112), + ConsumerRedistributionFraction: "consumer_redistribution_fraction", + BlocksPerDistributionTransmission: 123, + HistoricalEntries: 456, + DistributionTransmissionChannel: "distribution_transmission_channel", + } + providerKeeper.SetConsumerInitializationParameters(ctx, "consumerId", expectedInitializationParameters) + actualInitializationParameters, err := providerKeeper.GetConsumerInitializationParameters(ctx, "consumerId") + require.NoError(t, err) + require.Equal(t, expectedInitializationParameters, actualInitializationParameters) + + // assert that overwriting the current initialization record works + expectedInitializationParameters = providertypes.ConsumerInitializationParameters{ + InitialHeight: types.Height{RevisionNumber: 2, RevisionHeight: 3}, + GenesisHash: []byte{2, 3}, + BinaryHash: []byte{4, 5}, + SpawnTime: time.Unix(2, 3).UTC(), + UnbondingPeriod: time.Duration(789), + CcvTimeoutPeriod: time.Duration(101112), + TransferTimeoutPeriod: time.Duration(131415), + ConsumerRedistributionFraction: "consumer_redistribution_fraction2", + BlocksPerDistributionTransmission: 456, + HistoricalEntries: 789, + DistributionTransmissionChannel: "distribution_transmission_channel2", + } + providerKeeper.SetConsumerInitializationParameters(ctx, "consumerId", expectedInitializationParameters) + actualInitializationParameters, err = providerKeeper.GetConsumerInitializationParameters(ctx, "consumerId") + require.NoError(t, err) + require.Equal(t, expectedInitializationParameters, actualInitializationParameters) + + providerKeeper.DeleteConsumerInitializationParameters(ctx, "consumerId") + actualInitializationParameters, err = providerKeeper.GetConsumerInitializationParameters(ctx, "consumerId") + require.Error(t, err) + require.Equal(t, providertypes.ConsumerInitializationParameters{}, actualInitializationParameters) +} + +// TestConsumerPhase tests the getter, setter, and deletion of the consumer id to phase methods +func TestConsumerPhase(t *testing.T) { + providerKeeper, ctx, ctrl, _ := testkeeper.GetProviderKeeperAndCtx(t, testkeeper.NewInMemKeeperParams(t)) + defer ctrl.Finish() + + phase := providerKeeper.GetConsumerPhase(ctx, "consumerId") + require.Equal(t, providertypes.CONSUMER_PHASE_UNSPECIFIED, phase) + + providerKeeper.SetConsumerPhase(ctx, "consumerId", providertypes.CONSUMER_PHASE_INITIALIZED) + phase = providerKeeper.GetConsumerPhase(ctx, "consumerId") + require.Equal(t, providertypes.CONSUMER_PHASE_INITIALIZED, phase) + + providerKeeper.SetConsumerPhase(ctx, "consumerId", providertypes.CONSUMER_PHASE_LAUNCHED) + phase = providerKeeper.GetConsumerPhase(ctx, "consumerId") + require.Equal(t, providertypes.CONSUMER_PHASE_LAUNCHED, phase) +} + +// TestOptedInConsumerIds tests the `GetOptedInConsumerIds`, `AppendOptedInConsumerId`, and `RemoveOptedInConsumerId` methods +func TestGetOptedInConsumerIds(t *testing.T) { + providerKeeper, ctx, ctrl, _ := testkeeper.GetProviderKeeperAndCtx(t, testkeeper.NewInMemKeeperParams(t)) + defer ctrl.Finish() + + providerAddr := providertypes.NewProviderConsAddress([]byte("providerAddr")) + consumers, err := providerKeeper.GetOptedInConsumerIds(ctx, providerAddr) + require.NoError(t, err) + require.Empty(t, consumers) + + err = providerKeeper.AppendOptedInConsumerId(ctx, providerAddr, "consumerId1") + require.NoError(t, err) + consumers, err = providerKeeper.GetOptedInConsumerIds(ctx, providerAddr) + require.NoError(t, err) + require.Equal(t, providertypes.ConsumerIds{ + Ids: []string{"consumerId1"}, + }, consumers) + + err = providerKeeper.AppendOptedInConsumerId(ctx, providerAddr, "consumerId2") + require.NoError(t, err) + consumers, err = providerKeeper.GetOptedInConsumerIds(ctx, providerAddr) + require.NoError(t, err) + require.Equal(t, providertypes.ConsumerIds{ + Ids: []string{"consumerId1", "consumerId2"}, + }, consumers) + + err = providerKeeper.AppendOptedInConsumerId(ctx, providerAddr, "consumerId3") + require.NoError(t, err) + consumers, err = providerKeeper.GetOptedInConsumerIds(ctx, providerAddr) + require.NoError(t, err) + require.Equal(t, providertypes.ConsumerIds{ + Ids: []string{"consumerId1", "consumerId2", "consumerId3"}, + }, consumers) + + // remove all the consumer ids + err = providerKeeper.RemoveOptedInConsumerId(ctx, providerAddr, "consumerId2") + require.NoError(t, err) + consumers, err = providerKeeper.GetOptedInConsumerIds(ctx, providerAddr) + require.NoError(t, err) + require.Equal(t, providertypes.ConsumerIds{ + Ids: []string{"consumerId1", "consumerId3"}, + }, consumers) + + err = providerKeeper.RemoveOptedInConsumerId(ctx, providerAddr, "consumerId3") + require.NoError(t, err) + + err = providerKeeper.RemoveOptedInConsumerId(ctx, providerAddr, "consumerId1") + require.NoError(t, err) + + consumers, err = providerKeeper.GetOptedInConsumerIds(ctx, providerAddr) + require.NoError(t, err) + require.Empty(t, consumers) +} + +func TestIsValidatorOptedInToChain(t *testing.T) { + providerKeeper, ctx, ctrl, _ := testkeeper.GetProviderKeeperAndCtx(t, testkeeper.NewInMemKeeperParams(t)) + defer ctrl.Finish() + + chainId := "chainId" + providerAddr := providertypes.NewProviderConsAddress([]byte("providerAddr")) + _, found := providerKeeper.IsValidatorOptedInToChainId(ctx, providerAddr, chainId) + require.False(t, found) + + expectedConsumerId := "consumerId" + providerKeeper.SetConsumerChainId(ctx, expectedConsumerId, chainId) + providerKeeper.SetOptedIn(ctx, expectedConsumerId, providerAddr) + providerKeeper.AppendOptedInConsumerId(ctx, providerAddr, expectedConsumerId) + actualConsumerId, found := providerKeeper.IsValidatorOptedInToChainId(ctx, providerAddr, chainId) + require.True(t, found) + require.Equal(t, expectedConsumerId, actualConsumerId) +} diff --git a/x/ccv/provider/keeper/power_shaping.go b/x/ccv/provider/keeper/power_shaping.go new file mode 100644 index 0000000000..c54ca41e4e --- /dev/null +++ b/x/ccv/provider/keeper/power_shaping.go @@ -0,0 +1,286 @@ +package keeper + +import ( + "encoding/binary" + "errors" + "fmt" + + errorsmod "cosmossdk.io/errors" + storetypes "cosmossdk.io/store/types" + sdk "github.com/cosmos/cosmos-sdk/types" + "github.com/cosmos/interchain-security/v5/x/ccv/provider/types" + ccvtypes "github.com/cosmos/interchain-security/v5/x/ccv/types" +) + +// GetConsumerPowerShapingParameters returns the power-shaping parameters associated with this consumer id +func (k Keeper) GetConsumerPowerShapingParameters(ctx sdk.Context, consumerId string) (types.PowerShapingParameters, error) { + store := ctx.KVStore(k.storeKey) + bz := store.Get(types.ConsumerIdToPowerShapingParametersKey(consumerId)) + if bz == nil { + return types.PowerShapingParameters{}, errorsmod.Wrapf(ccvtypes.ErrStoreKeyNotFound, + "GetConsumerPowerShapingParameters, consumerId(%s)", consumerId) + } + var parameters types.PowerShapingParameters + if err := parameters.Unmarshal(bz); err != nil { + return types.PowerShapingParameters{}, errorsmod.Wrapf(ccvtypes.ErrStoreUnmarshal, + "GetConsumerPowerShapingParameters, consumerId(%s): %s", consumerId, err.Error()) + } + return parameters, nil +} + +// SetConsumerPowerShapingParameters sets the power-shaping parameters associated with this consumer id. +// Note that it also updates the allowlist and denylist indexes if they are different +func (k Keeper) SetConsumerPowerShapingParameters(ctx sdk.Context, consumerId string, parameters types.PowerShapingParameters) error { + store := ctx.KVStore(k.storeKey) + bz, err := parameters.Marshal() + if err != nil { + return fmt.Errorf("failed to marshal power-shaping parameters (%+v) for consumer id (%s): %w", parameters, consumerId, err) + } + + // get old power shaping params + oldParameters, err := k.GetConsumerPowerShapingParameters(ctx, consumerId) + // ignore ErrStoreKeyNotFound errors as this might be the first time the power shaping params are set + if errors.Is(err, ccvtypes.ErrStoreUnmarshal) { + return fmt.Errorf("cannot get consumer previous power shaping parameters: %w", err) + } + + store.Set(types.ConsumerIdToPowerShapingParametersKey(consumerId), bz) + + // update allowlist and denylist indexes if needed + if !equalStringSlices(oldParameters.Allowlist, parameters.Allowlist) { + k.UpdateAllowlist(ctx, consumerId, parameters.Allowlist) + } + if !equalStringSlices(oldParameters.Denylist, parameters.Denylist) { + k.UpdateDenylist(ctx, consumerId, parameters.Denylist) + } + + return nil +} + +// equalStringSlices returns true if two string slices are equal +func equalStringSlices(a, b []string) bool { + if len(a) != len(b) { + return false + } + for i, v := range a { + if v != b[i] { + return false + } + } + return true +} + +// SetAllowlist allowlists validator with `providerAddr` address on chain `consumerId` +func (k Keeper) SetAllowlist( + ctx sdk.Context, + consumerId string, + providerAddr types.ProviderConsAddress, +) { + store := ctx.KVStore(k.storeKey) + store.Set(types.AllowlistKey(consumerId, providerAddr), []byte{}) +} + +// GetAllowList returns all allowlisted validators +func (k Keeper) GetAllowList( + ctx sdk.Context, + consumerId string, +) (providerConsAddresses []types.ProviderConsAddress) { + store := ctx.KVStore(k.storeKey) + key := types.StringIdWithLenKey(types.AllowlistKeyPrefix(), consumerId) + iterator := storetypes.KVStorePrefixIterator(store, key) + defer iterator.Close() + + for ; iterator.Valid(); iterator.Next() { + providerConsAddresses = append(providerConsAddresses, types.NewProviderConsAddress(iterator.Key()[len(key):])) + } + + return providerConsAddresses +} + +// IsAllowlisted returns `true` if validator with `providerAddr` has been allowlisted on chain `consumerId` +func (k Keeper) IsAllowlisted( + ctx sdk.Context, + consumerId string, + providerAddr types.ProviderConsAddress, +) bool { + store := ctx.KVStore(k.storeKey) + bz := store.Get(types.AllowlistKey(consumerId, providerAddr)) + return bz != nil +} + +// DeleteAllowlist deletes all allowlisted validators +func (k Keeper) DeleteAllowlist(ctx sdk.Context, consumerId string) { + store := ctx.KVStore(k.storeKey) + iterator := storetypes.KVStorePrefixIterator(store, types.StringIdWithLenKey(types.AllowlistKeyPrefix(), consumerId)) + defer iterator.Close() + + keysToDel := [][]byte{} + for ; iterator.Valid(); iterator.Next() { + keysToDel = append(keysToDel, iterator.Key()) + } + + for _, key := range keysToDel { + store.Delete(key) + } +} + +// IsAllowlistEmpty returns `true` if no validator is allowlisted on chain `consumerId` +func (k Keeper) IsAllowlistEmpty(ctx sdk.Context, consumerId string) bool { + store := ctx.KVStore(k.storeKey) + iterator := storetypes.KVStorePrefixIterator(store, types.StringIdWithLenKey(types.AllowlistKeyPrefix(), consumerId)) + defer iterator.Close() + + return !iterator.Valid() +} + +// UpdateAllowlist populates the allowlist store for the consumer chain with this consumer id +func (k Keeper) UpdateAllowlist(ctx sdk.Context, consumerId string, allowlist []string) { + k.DeleteAllowlist(ctx, consumerId) + for _, address := range allowlist { + consAddr, err := sdk.ConsAddressFromBech32(address) + if err != nil { + continue + } + + k.SetAllowlist(ctx, consumerId, types.NewProviderConsAddress(consAddr)) + } +} + +// SetDenylist denylists validator with `providerAddr` address on chain `consumerId` +func (k Keeper) SetDenylist( + ctx sdk.Context, + consumerId string, + providerAddr types.ProviderConsAddress, +) { + store := ctx.KVStore(k.storeKey) + store.Set(types.DenylistKey(consumerId, providerAddr), []byte{}) +} + +// GetDenyList returns all denylisted validators +func (k Keeper) GetDenyList( + ctx sdk.Context, + consumerId string, +) (providerConsAddresses []types.ProviderConsAddress) { + store := ctx.KVStore(k.storeKey) + key := types.StringIdWithLenKey(types.DenylistKeyPrefix(), consumerId) + iterator := storetypes.KVStorePrefixIterator(store, key) + defer iterator.Close() + + for ; iterator.Valid(); iterator.Next() { + providerConsAddresses = append(providerConsAddresses, types.NewProviderConsAddress(iterator.Key()[len(key):])) + } + + return providerConsAddresses +} + +// IsDenylisted returns `true` if validator with `providerAddr` has been denylisted on chain `consumerId` +func (k Keeper) IsDenylisted( + ctx sdk.Context, + consumerId string, + providerAddr types.ProviderConsAddress, +) bool { + store := ctx.KVStore(k.storeKey) + bz := store.Get(types.DenylistKey(consumerId, providerAddr)) + return bz != nil +} + +// DeleteDenylist deletes all denylisted validators +func (k Keeper) DeleteDenylist(ctx sdk.Context, consumerId string) { + store := ctx.KVStore(k.storeKey) + iterator := storetypes.KVStorePrefixIterator(store, types.StringIdWithLenKey(types.DenylistKeyPrefix(), consumerId)) + defer iterator.Close() + + keysToDel := [][]byte{} + for ; iterator.Valid(); iterator.Next() { + keysToDel = append(keysToDel, iterator.Key()) + } + + for _, key := range keysToDel { + store.Delete(key) + } +} + +// IsDenylistEmpty returns `true` if no validator is denylisted on chain `consumerId` +func (k Keeper) IsDenylistEmpty(ctx sdk.Context, consumerId string) bool { + store := ctx.KVStore(k.storeKey) + iterator := storetypes.KVStorePrefixIterator(store, types.StringIdWithLenKey(types.DenylistKeyPrefix(), consumerId)) + defer iterator.Close() + + return !iterator.Valid() +} + +// UpdateDenylist populates the denylist store for the consumer chain with this consumer id +func (k Keeper) UpdateDenylist(ctx sdk.Context, consumerId string, denylist []string) { + k.DeleteDenylist(ctx, consumerId) + for _, address := range denylist { + consAddr, err := sdk.ConsAddressFromBech32(address) + if err != nil { + continue + } + + k.SetDenylist(ctx, consumerId, types.NewProviderConsAddress(consAddr)) + } +} + +// SetMinimumPowerInTopN sets the minimum power required for a validator to be in the top N +// for a given consumer chain. +func (k Keeper) SetMinimumPowerInTopN( + ctx sdk.Context, + consumerId string, + power int64, +) { + store := ctx.KVStore(k.storeKey) + + buf := make([]byte, 8) + binary.BigEndian.PutUint64(buf, uint64(power)) + + store.Set(types.MinimumPowerInTopNKey(consumerId), buf) +} + +// GetMinimumPowerInTopN returns the minimum power required for a validator to be in the top N +// for a given consumer chain. +func (k Keeper) GetMinimumPowerInTopN( + ctx sdk.Context, + consumerId string, +) (int64, bool) { + store := ctx.KVStore(k.storeKey) + buf := store.Get(types.MinimumPowerInTopNKey(consumerId)) + if buf == nil { + return 0, false + } + return int64(binary.BigEndian.Uint64(buf)), true +} + +// DeleteMinimumPowerInTopN removes the minimum power required for a validator to be in the top N +// for a given consumer chain. +func (k Keeper) DeleteMinimumPowerInTopN( + ctx sdk.Context, + consumerId string, +) { + store := ctx.KVStore(k.storeKey) + store.Delete(types.MinimumPowerInTopNKey(consumerId)) +} + +// UpdateMinimumPowerInTopN populates the minimum power in Top N for the consumer chain with this consumer id +func (k Keeper) UpdateMinimumPowerInTopN(ctx sdk.Context, consumerId string, oldTopN uint32, newTopN uint32) error { + // if the top N changes, we need to update the new minimum power in top N + if newTopN != oldTopN { + if newTopN > 0 { + // if the chain receives a non-zero top N value, store the minimum power in the top N + bondedValidators, err := k.GetLastProviderConsensusActiveValidators(ctx) + if err != nil { + return err + } + minPower, err := k.ComputeMinPowerInTopN(ctx, bondedValidators, newTopN) + if err != nil { + return err + } + k.SetMinimumPowerInTopN(ctx, consumerId, minPower) + } else { + // if the chain receives a zero top N value, we delete the min power + k.DeleteMinimumPowerInTopN(ctx, consumerId) + } + } + + return nil +} diff --git a/x/ccv/provider/keeper/power_shaping_test.go b/x/ccv/provider/keeper/power_shaping_test.go new file mode 100644 index 0000000000..bcf49373c6 --- /dev/null +++ b/x/ccv/provider/keeper/power_shaping_test.go @@ -0,0 +1,313 @@ +package keeper_test + +import ( + "bytes" + "errors" + "sort" + "testing" + + sdk "github.com/cosmos/cosmos-sdk/types" + stakingtypes "github.com/cosmos/cosmos-sdk/x/staking/types" + testkeeper "github.com/cosmos/interchain-security/v5/testutil/keeper" + providertypes "github.com/cosmos/interchain-security/v5/x/ccv/provider/types" + ccvtypes "github.com/cosmos/interchain-security/v5/x/ccv/types" + "github.com/golang/mock/gomock" + "github.com/stretchr/testify/require" +) + +// TestConsumerPowerShapingParameters tests the getter and setter of the consumer id to power-shaping parameters methods +func TestConsumerPowerShapingParameters(t *testing.T) { + providerKeeper, ctx, ctrl, _ := testkeeper.GetProviderKeeperAndCtx(t, testkeeper.NewInMemKeeperParams(t)) + defer ctrl.Finish() + + consumerId := "consumerId" + consAddrs := []string{ + "cosmosvalcons1kswr5sq599365kcjmhgufevfps9njf43e4lwdk", + "cosmosvalcons1ezyrq65s3gshhx5585w6mpusq3xsj3ayzf4uv6", + "cosmosvalcons1muys5jyqk4xd27e208nym85kn0t4zjcfeu63fe", + "cosmosvalcons1nx7n5uh0ztxsynn4sje6eyq2ud6rc6klc96w39", + "cosmosvalcons1qmq08eruchr5sf5s3rwz7djpr5a25f7xw4mceq", + "cosmosvalcons1uuec3cjxajv5te08p220usrjhkfhg9wyvqn0tm", + } + providerConsAddr := []providertypes.ProviderConsAddress{} + for _, addr := range consAddrs { + ca, _ := sdk.ConsAddressFromBech32(addr) + providerConsAddr = append(providerConsAddr, providertypes.NewProviderConsAddress(ca)) + } + sortProviderConsAddr := func(consAddrs []providertypes.ProviderConsAddress) { + sort.Slice(consAddrs, func(i, j int) bool { + return bytes.Compare(consAddrs[i].Address, consAddrs[j].Address) < 0 + }) + } + + _, err := providerKeeper.GetConsumerPowerShapingParameters(ctx, consumerId) + require.Error(t, err) + require.True(t, errors.Is(err, ccvtypes.ErrStoreKeyNotFound)) + + expectedPowerShapingParameters := providertypes.PowerShapingParameters{ + Top_N: 10, + ValidatorsPowerCap: 34, + ValidatorSetCap: 10, + Allowlist: []string{consAddrs[0], consAddrs[1]}, + Denylist: []string{consAddrs[2], consAddrs[3]}, + MinStake: 234, + AllowInactiveVals: true, + } + expectedAllowlist := []providertypes.ProviderConsAddress{providerConsAddr[0], providerConsAddr[1]} + sortProviderConsAddr(expectedAllowlist) + expectedDenylist := []providertypes.ProviderConsAddress{providerConsAddr[2], providerConsAddr[3]} + sortProviderConsAddr(expectedDenylist) + err = providerKeeper.SetConsumerPowerShapingParameters(ctx, consumerId, expectedPowerShapingParameters) + require.NoError(t, err) + actualPowerShapingParameters, err := providerKeeper.GetConsumerPowerShapingParameters(ctx, consumerId) + require.NoError(t, err) + require.Equal(t, expectedPowerShapingParameters, actualPowerShapingParameters) + require.Equal(t, expectedAllowlist, providerKeeper.GetAllowList(ctx, consumerId)) + require.Equal(t, expectedDenylist, providerKeeper.GetDenyList(ctx, consumerId)) + + // assert that overwriting the current initialization record works + expectedPowerShapingParameters = providertypes.PowerShapingParameters{ + Top_N: 12, + ValidatorsPowerCap: 67, + ValidatorSetCap: 20, + Allowlist: []string{consAddrs[4], consAddrs[5]}, + Denylist: []string{consAddrs[2], consAddrs[3]}, + MinStake: 567, + AllowInactiveVals: false, + } + expectedAllowlist = []providertypes.ProviderConsAddress{providerConsAddr[4], providerConsAddr[5]} + sortProviderConsAddr(expectedAllowlist) + expectedDenylist = []providertypes.ProviderConsAddress{providerConsAddr[2], providerConsAddr[3]} + sortProviderConsAddr(expectedDenylist) + err = providerKeeper.SetConsumerPowerShapingParameters(ctx, consumerId, expectedPowerShapingParameters) + require.NoError(t, err) + actualPowerShapingParameters, err = providerKeeper.GetConsumerPowerShapingParameters(ctx, consumerId) + require.NoError(t, err) + require.Equal(t, expectedPowerShapingParameters, actualPowerShapingParameters) + require.Equal(t, expectedAllowlist, providerKeeper.GetAllowList(ctx, consumerId)) + require.Equal(t, expectedDenylist, providerKeeper.GetDenyList(ctx, consumerId)) +} + +// TestAllowlist tests the `SetAllowlist`, `IsAllowlisted`, `DeleteAllowlist`, and `IsAllowlistEmpty` methods +func TestAllowlist(t *testing.T) { + providerKeeper, ctx, ctrl, _ := testkeeper.GetProviderKeeperAndCtx(t, testkeeper.NewInMemKeeperParams(t)) + defer ctrl.Finish() + + chainID := "consumerId" + + // no validator was allowlisted and hence the allowlist is empty + require.True(t, providerKeeper.IsAllowlistEmpty(ctx, chainID)) + + providerAddr1 := providertypes.NewProviderConsAddress([]byte("providerAddr1")) + providerKeeper.SetAllowlist(ctx, chainID, providerAddr1) + require.True(t, providerKeeper.IsAllowlisted(ctx, chainID, providerAddr1)) + + // allowlist is not empty anymore + require.False(t, providerKeeper.IsAllowlistEmpty(ctx, chainID)) + + providerAddr2 := providertypes.NewProviderConsAddress([]byte("providerAddr2")) + providerKeeper.SetAllowlist(ctx, chainID, providerAddr2) + require.True(t, providerKeeper.IsAllowlisted(ctx, chainID, providerAddr2)) + require.False(t, providerKeeper.IsAllowlistEmpty(ctx, chainID)) + + providerKeeper.DeleteAllowlist(ctx, chainID) + require.False(t, providerKeeper.IsAllowlisted(ctx, chainID, providerAddr1)) + require.False(t, providerKeeper.IsAllowlisted(ctx, chainID, providerAddr2)) + require.True(t, providerKeeper.IsAllowlistEmpty(ctx, chainID)) +} + +func TestUpdateAllowlist(t *testing.T) { + providerKeeper, ctx, ctrl, _ := testkeeper.GetProviderKeeperAndCtx(t, testkeeper.NewInMemKeeperParams(t)) + defer ctrl.Finish() + + consumerId := "0" + + providerConsAddr1 := "cosmosvalcons1qmq08eruchr5sf5s3rwz7djpr5a25f7xw4mceq" + consAddr1, _ := sdk.ConsAddressFromBech32(providerConsAddr1) + providerConsAddr2 := "cosmosvalcons1nx7n5uh0ztxsynn4sje6eyq2ud6rc6klc96w39" + consAddr2, _ := sdk.ConsAddressFromBech32(providerConsAddr2) + + providerKeeper.UpdateAllowlist(ctx, consumerId, []string{providerConsAddr1, providerConsAddr2}) + + expectedAllowlist := []providertypes.ProviderConsAddress{ + providertypes.NewProviderConsAddress(consAddr1), + providertypes.NewProviderConsAddress(consAddr2)} + require.Equal(t, expectedAllowlist, providerKeeper.GetAllowList(ctx, consumerId)) +} + +// TestDenylist tests the `SetDenylist`, `IsDenylisted`, `DeleteDenylist`, and `IsDenylistEmpty` methods +func TestDenylist(t *testing.T) { + providerKeeper, ctx, ctrl, _ := testkeeper.GetProviderKeeperAndCtx(t, testkeeper.NewInMemKeeperParams(t)) + defer ctrl.Finish() + + chainID := "consumerId" + + // no validator was denylisted and hence the denylist is empty + require.True(t, providerKeeper.IsDenylistEmpty(ctx, chainID)) + + providerAddr1 := providertypes.NewProviderConsAddress([]byte("providerAddr1")) + providerKeeper.SetDenylist(ctx, chainID, providerAddr1) + require.True(t, providerKeeper.IsDenylisted(ctx, chainID, providerAddr1)) + + // denylist is not empty anymore + require.False(t, providerKeeper.IsDenylistEmpty(ctx, chainID)) + + providerAddr2 := providertypes.NewProviderConsAddress([]byte("providerAddr2")) + providerKeeper.SetDenylist(ctx, chainID, providerAddr2) + require.True(t, providerKeeper.IsDenylisted(ctx, chainID, providerAddr2)) + require.False(t, providerKeeper.IsDenylistEmpty(ctx, chainID)) + + providerKeeper.DeleteDenylist(ctx, chainID) + require.False(t, providerKeeper.IsDenylisted(ctx, chainID, providerAddr1)) + require.False(t, providerKeeper.IsDenylisted(ctx, chainID, providerAddr2)) + require.True(t, providerKeeper.IsDenylistEmpty(ctx, chainID)) +} + +func TestUpdateDenylist(t *testing.T) { + providerKeeper, ctx, ctrl, _ := testkeeper.GetProviderKeeperAndCtx(t, testkeeper.NewInMemKeeperParams(t)) + defer ctrl.Finish() + + consumerId := "0" + + providerConsAddr1 := "cosmosvalcons1qmq08eruchr5sf5s3rwz7djpr5a25f7xw4mceq" + consAddr1, _ := sdk.ConsAddressFromBech32(providerConsAddr1) + providerConsAddr2 := "cosmosvalcons1nx7n5uh0ztxsynn4sje6eyq2ud6rc6klc96w39" + consAddr2, _ := sdk.ConsAddressFromBech32(providerConsAddr2) + + providerKeeper.UpdateDenylist(ctx, consumerId, []string{providerConsAddr1, providerConsAddr2}) + + expectedDenylist := []providertypes.ProviderConsAddress{ + providertypes.NewProviderConsAddress(consAddr1), + providertypes.NewProviderConsAddress(consAddr2)} + require.Equal(t, expectedDenylist, providerKeeper.GetDenyList(ctx, consumerId)) +} + +// Tests setting, getting and deleting parameters that are stored per-consumer chain. +// The tests cover the following parameters: +// - MinimumPowerInTopN +func TestKeeperConsumerParams(t *testing.T) { + k, ctx, _, _ := testkeeper.GetProviderKeeperAndCtx(t, testkeeper.NewInMemKeeperParams(t)) + + tests := []struct { + name string + settingFunc func(sdk.Context, string, int64) + getFunc func(sdk.Context, string) int64 + deleteFunc func(sdk.Context, string) + initialValue int64 + updatedValue int64 + }{ + { + name: "Minimum Power In Top N", + settingFunc: func(ctx sdk.Context, id string, val int64) { k.SetMinimumPowerInTopN(ctx, id, val) }, + getFunc: func(ctx sdk.Context, id string) int64 { + minimumPowerInTopN, _ := k.GetMinimumPowerInTopN(ctx, id) + return minimumPowerInTopN + }, + deleteFunc: func(ctx sdk.Context, id string) { k.DeleteMinimumPowerInTopN(ctx, id) }, + initialValue: 1000, + updatedValue: 2000, + }, + } + + for _, tt := range tests { + t.Run(tt.name, func(t *testing.T) { + chainID := "consumerId" + // Set initial value + tt.settingFunc(ctx, chainID, int64(tt.initialValue)) + + // Retrieve and check initial value + actualValue := tt.getFunc(ctx, chainID) + require.EqualValues(t, tt.initialValue, actualValue) + + // Update value + tt.settingFunc(ctx, chainID, int64(tt.updatedValue)) + + // Retrieve and check updated value + newActualValue := tt.getFunc(ctx, chainID) + require.EqualValues(t, tt.updatedValue, newActualValue) + + // Check non-existent consumer id + res := tt.getFunc(ctx, "not the consumerId") + require.Zero(t, res) + + // Delete value + tt.deleteFunc(ctx, chainID) + + // Check that value was deleted + res = tt.getFunc(ctx, chainID) + require.Zero(t, res) + + // Try deleting again + tt.deleteFunc(ctx, chainID) + + // Check that the value is still deleted + res = tt.getFunc(ctx, chainID) + require.Zero(t, res) + }) + } +} + +func TestUpdateMinimumPowerInTopN(t *testing.T) { + providerKeeper, ctx, ctrl, mocks := testkeeper.GetProviderKeeperAndCtx(t, testkeeper.NewInMemKeeperParams(t)) + defer ctrl.Finish() + + consumerId := "0" + + // test case where Top N is 0 in which case there's no minimum power in top N + err := providerKeeper.SetConsumerPowerShapingParameters(ctx, consumerId, providertypes.PowerShapingParameters{ + Top_N: 0, + }) + require.NoError(t, err) + + err = providerKeeper.UpdateMinimumPowerInTopN(ctx, consumerId, 0, 0) + require.NoError(t, err) + _, found := providerKeeper.GetMinimumPowerInTopN(ctx, consumerId) + require.False(t, found) + + // test cases where Top N > 0 and for this we mock some validators + powers := []int64{10, 20, 30} + validators := []stakingtypes.Validator{ + createStakingValidator(ctx, mocks, powers[0], 1), // this validator has ~16 of the total voting power + createStakingValidator(ctx, mocks, powers[1], 2), // this validator has ~33% of the total voting gpower + createStakingValidator(ctx, mocks, powers[2], 3), // this validator has 50% of the total voting power + } + mocks.MockStakingKeeper.EXPECT().GetBondedValidatorsByPower(gomock.Any()).Return(validators, nil).AnyTimes() + + maxProviderConsensusValidators := int64(3) + params := providerKeeper.GetParams(ctx) + params.MaxProviderConsensusValidators = maxProviderConsensusValidators + providerKeeper.SetParams(ctx, params) + + // when top N is 50, the minimum power is 30 (because top validator has to validate) + err = providerKeeper.SetConsumerPowerShapingParameters(ctx, consumerId, providertypes.PowerShapingParameters{ + Top_N: 50, + }) + require.NoError(t, err) + err = providerKeeper.UpdateMinimumPowerInTopN(ctx, consumerId, 0, 50) + require.NoError(t, err) + minimumPowerInTopN, found := providerKeeper.GetMinimumPowerInTopN(ctx, consumerId) + require.True(t, found) + require.Equal(t, int64(30), minimumPowerInTopN) + + // when top N is 51, the minimum power is 20 (because top 2 validators have to validate) + err = providerKeeper.SetConsumerPowerShapingParameters(ctx, consumerId, providertypes.PowerShapingParameters{ + Top_N: 51, + }) + require.NoError(t, err) + err = providerKeeper.UpdateMinimumPowerInTopN(ctx, consumerId, 50, 51) + require.NoError(t, err) + minimumPowerInTopN, found = providerKeeper.GetMinimumPowerInTopN(ctx, consumerId) + require.True(t, found) + require.Equal(t, int64(20), minimumPowerInTopN) + + // when top N is 100, the minimum power is 10 (that of the validator with the lowest power) + err = providerKeeper.SetConsumerPowerShapingParameters(ctx, consumerId, providertypes.PowerShapingParameters{ + Top_N: 100, + }) + require.NoError(t, err) + err = providerKeeper.UpdateMinimumPowerInTopN(ctx, consumerId, 51, 100) + require.NoError(t, err) + minimumPowerInTopN, found = providerKeeper.GetMinimumPowerInTopN(ctx, consumerId) + require.True(t, found) + require.Equal(t, int64(10), minimumPowerInTopN) +} diff --git a/x/ccv/provider/keeper/proposal.go b/x/ccv/provider/keeper/proposal.go deleted file mode 100644 index f67f597370..0000000000 --- a/x/ccv/provider/keeper/proposal.go +++ /dev/null @@ -1,653 +0,0 @@ -package keeper - -import ( - "fmt" - "time" - - stakingtypes "github.com/cosmos/cosmos-sdk/x/staking/types" - - clienttypes "github.com/cosmos/ibc-go/v8/modules/core/02-client/types" - channeltypes "github.com/cosmos/ibc-go/v8/modules/core/04-channel/types" - commitmenttypes "github.com/cosmos/ibc-go/v8/modules/core/23-commitment/types" - ibctmtypes "github.com/cosmos/ibc-go/v8/modules/light-clients/07-tendermint" - - errorsmod "cosmossdk.io/errors" - storetypes "cosmossdk.io/store/types" - - sdk "github.com/cosmos/cosmos-sdk/types" - sdkerrors "github.com/cosmos/cosmos-sdk/types/errors" - - tmtypes "github.com/cometbft/cometbft/types" - - "github.com/cosmos/interchain-security/v5/x/ccv/provider/types" - ccv "github.com/cosmos/interchain-security/v5/x/ccv/types" -) - -// Wrapper for the new proposal message MsgConsumerAddition -// Will replace legacy handler HandleLegacyConsumerAdditionProposal -func (k Keeper) HandleConsumerAdditionProposal(ctx sdk.Context, proposal *types.MsgConsumerAddition) error { - p := types.ConsumerAdditionProposal{ - ChainId: proposal.ChainId, - InitialHeight: proposal.InitialHeight, - GenesisHash: proposal.GenesisHash, - BinaryHash: proposal.BinaryHash, - SpawnTime: proposal.SpawnTime, - UnbondingPeriod: proposal.UnbondingPeriod, - CcvTimeoutPeriod: proposal.CcvTimeoutPeriod, - TransferTimeoutPeriod: proposal.TransferTimeoutPeriod, - ConsumerRedistributionFraction: proposal.ConsumerRedistributionFraction, - BlocksPerDistributionTransmission: proposal.BlocksPerDistributionTransmission, - HistoricalEntries: proposal.HistoricalEntries, - DistributionTransmissionChannel: proposal.DistributionTransmissionChannel, - Top_N: proposal.Top_N, - ValidatorsPowerCap: proposal.ValidatorsPowerCap, - ValidatorSetCap: proposal.ValidatorSetCap, - Allowlist: proposal.Allowlist, - Denylist: proposal.Denylist, - MinStake: proposal.MinStake, - AllowInactiveVals: proposal.AllowInactiveVals, - } - - return k.HandleLegacyConsumerAdditionProposal(ctx, &p) -} - -// Wrapper for the new proposal message MsgConsumerRemoval -// Will replace legacy handler HandleLegacyConsumerRemovalProposal -func (k Keeper) HandleConsumerRemovalProposal(ctx sdk.Context, proposal *types.MsgConsumerRemoval) error { - p := types.ConsumerRemovalProposal{ - ChainId: proposal.ChainId, - StopTime: proposal.StopTime, - } - - return k.HandleLegacyConsumerRemovalProposal(ctx, &p) -} - -// Wrapper for the new proposal message MsgChangeRewardDenoms -// Will replace legacy handler HandleLegacyConsumerRewardDenomProposal -func (k Keeper) HandleConsumerRewardDenomProposal(ctx sdk.Context, proposal *types.MsgChangeRewardDenoms) error { - p := types.ChangeRewardDenomsProposal{ - DenomsToAdd: proposal.DenomsToAdd, - DenomsToRemove: proposal.DenomsToRemove, - } - - return k.HandleLegacyConsumerRewardDenomProposal(ctx, &p) -} - -// HandleConsumerModificationProposal modifies a running consumer chain -func (k Keeper) HandleConsumerModificationProposal(ctx sdk.Context, proposal *types.MsgConsumerModification) error { - p := types.ConsumerModificationProposal{ - Title: proposal.Title, - Description: proposal.Description, - ChainId: proposal.ChainId, - Top_N: proposal.Top_N, - ValidatorsPowerCap: proposal.ValidatorsPowerCap, - ValidatorSetCap: proposal.ValidatorSetCap, - Allowlist: proposal.Allowlist, - Denylist: proposal.Denylist, - MinStake: proposal.MinStake, - AllowInactiveVals: proposal.AllowInactiveVals, - } - - return k.HandleLegacyConsumerModificationProposal(ctx, &p) -} - -// CreateConsumerClient will create the CCV client for the given consumer chain. The CCV channel must be built -// on top of the CCV client to ensure connection with the right consumer chain. -// -// See: https://github.com/cosmos/ibc/blob/main/spec/app/ics-028-cross-chain-validation/methods.md#ccv-pcf-crclient1 -// Spec tag: [CCV-PCF-CRCLIENT.1] -func (k Keeper) CreateConsumerClient(ctx sdk.Context, prop *types.ConsumerAdditionProposal) error { - chainID := prop.ChainId - // check that a client for this chain does not exist - if _, found := k.GetConsumerClientId(ctx, chainID); found { - return errorsmod.Wrap(types.ErrDuplicateConsumerChain, - fmt.Sprintf("cannot create client for existent consumer chain: %s", chainID)) - } - - // Set minimum height for equivocation evidence from this consumer chain - k.SetEquivocationEvidenceMinHeight(ctx, chainID, prop.InitialHeight.RevisionHeight) - - // Consumers start out with the unbonding period from the consumer addition prop - consumerUnbondingPeriod := prop.UnbondingPeriod - - // Create client state by getting template client from parameters and filling in zeroed fields from proposal. - clientState := k.GetTemplateClient(ctx) - clientState.ChainId = chainID - clientState.LatestHeight = prop.InitialHeight - - trustPeriod, err := ccv.CalculateTrustPeriod(consumerUnbondingPeriod, k.GetTrustingPeriodFraction(ctx)) - if err != nil { - return err - } - clientState.TrustingPeriod = trustPeriod - clientState.UnbondingPeriod = consumerUnbondingPeriod - - consumerGen, validatorSetHash, err := k.MakeConsumerGenesis(ctx, prop) - if err != nil { - return err - } - err = k.SetConsumerGenesis(ctx, chainID, consumerGen) - if err != nil { - return err - } - - // Create consensus state - consensusState := ibctmtypes.NewConsensusState( - ctx.BlockTime(), - commitmenttypes.NewMerkleRoot([]byte(ibctmtypes.SentinelRoot)), - validatorSetHash, // use the hash of the updated initial valset - ) - - clientID, err := k.clientKeeper.CreateClient(ctx, clientState, consensusState) - if err != nil { - return err - } - k.SetConsumerClientId(ctx, chainID, clientID) - - k.Logger(ctx).Info("consumer chain registered (client created)", - "chainID", chainID, - "clientID", clientID, - ) - - ctx.EventManager().EmitEvent( - sdk.NewEvent( - types.EventTypeConsumerClientCreated, - sdk.NewAttribute(sdk.AttributeKeyModule, types.ModuleName), - sdk.NewAttribute(ccv.AttributeChainID, chainID), - sdk.NewAttribute(clienttypes.AttributeKeyClientID, clientID), - sdk.NewAttribute(types.AttributeInitialHeight, prop.InitialHeight.String()), - sdk.NewAttribute(types.AttributeTrustingPeriod, clientState.TrustingPeriod.String()), - sdk.NewAttribute(types.AttributeUnbondingPeriod, clientState.UnbondingPeriod.String()), - ), - ) - - return nil -} - -// StopConsumerChain cleans up the states for the given consumer chain ID and -// completes the outstanding unbonding operations on the consumer chain. -// -// This method implements StopConsumerChain from spec. -// See: https://github.com/cosmos/ibc/blob/main/spec/app/ics-028-cross-chain-validation/methods.md#ccv-pcf-stcc1 -// Spec tag: [CCV-PCF-STCC.1] -func (k Keeper) StopConsumerChain(ctx sdk.Context, chainID string, closeChan bool) (err error) { - // check that a client for chainID exists - if _, found := k.GetConsumerClientId(ctx, chainID); !found { - return errorsmod.Wrap(types.ErrConsumerChainNotFound, - fmt.Sprintf("cannot stop non-existent consumer chain: %s", chainID)) - } - - // clean up states - k.DeleteConsumerClientId(ctx, chainID) - k.DeleteConsumerGenesis(ctx, chainID) - // Note: this call panics if the key assignment state is invalid - k.DeleteKeyAssignments(ctx, chainID) - k.DeleteMinimumPowerInTopN(ctx, chainID) - k.DeleteEquivocationEvidenceMinHeight(ctx, chainID) - - // close channel and delete the mappings between chain ID and channel ID - if channelID, found := k.GetChainToChannel(ctx, chainID); found { - if closeChan { - // Close the channel for the given channel ID on the condition - // that the channel exists and isn't already in the CLOSED state - channel, found := k.channelKeeper.GetChannel(ctx, ccv.ProviderPortID, channelID) - if found && channel.State != channeltypes.CLOSED { - err := k.chanCloseInit(ctx, channelID) - if err != nil { - k.Logger(ctx).Error("channel to consumer chain could not be closed", - "chainID", chainID, - "channelID", channelID, - "error", err.Error(), - ) - } - } - } - k.DeleteChainToChannel(ctx, chainID) - k.DeleteChannelToChain(ctx, channelID) - } - - // delete consumer commission rate - provAddrs := k.GetAllCommissionRateValidators(ctx, chainID) - for _, addr := range provAddrs { - k.DeleteConsumerCommissionRate(ctx, chainID, addr) - } - - k.DeleteInitChainHeight(ctx, chainID) - k.DeleteSlashAcks(ctx, chainID) - k.DeletePendingVSCPackets(ctx, chainID) - - k.DeleteTopN(ctx, chainID) - k.DeleteValidatorsPowerCap(ctx, chainID) - k.DeleteValidatorSetCap(ctx, chainID) - k.DeleteAllowlist(ctx, chainID) - k.DeleteDenylist(ctx, chainID) - k.DeleteMinStake(ctx, chainID) - k.DisableInactiveValidators(ctx, chainID) - - k.DeleteAllOptedIn(ctx, chainID) - k.DeleteConsumerValSet(ctx, chainID) - - k.Logger(ctx).Info("consumer chain removed from provider", "chainID", chainID) - - return nil -} - -// MakeConsumerGenesis constructs the consumer CCV module part of the genesis state. -func (k Keeper) MakeConsumerGenesis( - ctx sdk.Context, - prop *types.ConsumerAdditionProposal, -) (gen ccv.ConsumerGenesisState, nextValidatorsHash []byte, err error) { - chainID := prop.ChainId - providerUnbondingPeriod, err := k.stakingKeeper.UnbondingTime(ctx) - if err != nil { - return gen, nil, errorsmod.Wrapf(types.ErrNoUnbondingTime, "unbonding time not found: %s", err) - } - height := clienttypes.GetSelfHeight(ctx) - - clientState := k.GetTemplateClient(ctx) - // this is the counter party chain ID for the consumer - clientState.ChainId = ctx.ChainID() - // this is the latest height the client was updated at, i.e., - // the height of the latest consensus state (see below) - clientState.LatestHeight = height - trustPeriod, err := ccv.CalculateTrustPeriod(providerUnbondingPeriod, k.GetTrustingPeriodFraction(ctx)) - if err != nil { - return gen, nil, errorsmod.Wrapf(sdkerrors.ErrInvalidHeight, "error %s calculating trusting_period for: %s", err, height) - } - clientState.TrustingPeriod = trustPeriod - clientState.UnbondingPeriod = providerUnbondingPeriod - - consState, err := k.clientKeeper.GetSelfConsensusState(ctx, height) - if err != nil { - return gen, nil, errorsmod.Wrapf(clienttypes.ErrConsensusStateNotFound, "error %s getting self consensus state for: %s", err, height) - } - - // get the bonded validators from the staking module - bondedValidators, err := k.GetLastBondedValidators(ctx) - if err != nil { - return gen, nil, errorsmod.Wrapf(stakingtypes.ErrNoValidatorFound, "error getting last bonded validators: %s", err) - } - - if prop.Top_N > 0 { - // get the consensus active validators - // we do not want to base the power calculation for the top N - // on inactive validators, too, since the top N will be a percentage of the active set power - // otherwise, it could be that inactive validators are forced to validate - activeValidators, err := k.GetLastProviderConsensusActiveValidators(ctx) - if err != nil { - return gen, nil, errorsmod.Wrapf(stakingtypes.ErrNoValidatorFound, "error getting last active bonded validators: %s", err) - } - - // in a Top-N chain, we automatically opt in all validators that belong to the top N - minPower, err := k.ComputeMinPowerInTopN(ctx, activeValidators, prop.Top_N) - if err != nil { - return gen, nil, err - } - // log the minimum power in top N - k.Logger(ctx).Info("minimum power in top N at consumer genesis", - "chainID", chainID, - "minPower", minPower, - ) - k.OptInTopNValidators(ctx, chainID, activeValidators, minPower) - k.SetMinimumPowerInTopN(ctx, chainID, minPower) - } - // need to use the bondedValidators, not activeValidators, here since the chain might be opt-in and allow inactive vals - nextValidators := k.ComputeNextValidators(ctx, chainID, bondedValidators) - - k.SetConsumerValSet(ctx, chainID, nextValidators) - - // get the initial updates with the latest set consumer public keys - initialUpdatesWithConsumerKeys := DiffValidators([]types.ConsensusValidator{}, nextValidators) - - // Get a hash of the consumer validator set from the update with applied consumer assigned keys - updatesAsValSet, err := tmtypes.PB2TM.ValidatorUpdates(initialUpdatesWithConsumerKeys) - if err != nil { - return gen, nil, fmt.Errorf("unable to create validator set from updates computed from key assignment in MakeConsumerGenesis: %s", err) - } - hash := tmtypes.NewValidatorSet(updatesAsValSet).Hash() - - consumerGenesisParams := ccv.NewParams( - true, - prop.BlocksPerDistributionTransmission, - prop.DistributionTransmissionChannel, - "", // providerFeePoolAddrStr, - prop.CcvTimeoutPeriod, - prop.TransferTimeoutPeriod, - prop.ConsumerRedistributionFraction, - prop.HistoricalEntries, - prop.UnbondingPeriod, - []string{}, - []string{}, - ccv.DefaultRetryDelayPeriod, - ) - - gen = *ccv.NewInitialConsumerGenesisState( - clientState, - consState.(*ibctmtypes.ConsensusState), - initialUpdatesWithConsumerKeys, - consumerGenesisParams, - ) - return gen, hash, nil -} - -// SetPendingConsumerAdditionProp stores a pending consumer addition proposal. -// -// Note that the pending consumer addition proposals are stored under keys with -// the following format: PendingCAPKeyPrefix | spawnTime | chainID -// Thus, if multiple consumer addition proposal for the same chain will pass at -// the same time, then only the last one will be stored. -func (k Keeper) SetPendingConsumerAdditionProp(ctx sdk.Context, prop *types.ConsumerAdditionProposal) { - store := ctx.KVStore(k.storeKey) - bz, err := prop.Marshal() - if err != nil { - // An error here would indicate something is very wrong - panic(fmt.Errorf("failed to marshal consumer addition proposal: %w", err)) - } - store.Set(types.PendingCAPKey(prop.SpawnTime, prop.ChainId), bz) -} - -// GetPendingConsumerAdditionProp retrieves a pending consumer addition proposal -// by spawn time and chain id. -// -// Note: this method is only used in testing -func (k Keeper) GetPendingConsumerAdditionProp(ctx sdk.Context, spawnTime time.Time, - chainID string, -) (prop types.ConsumerAdditionProposal, found bool) { - store := ctx.KVStore(k.storeKey) - bz := store.Get(types.PendingCAPKey(spawnTime, chainID)) - if bz == nil { - return prop, false - } - err := prop.Unmarshal(bz) - if err != nil { - // An error here would indicate something is very wrong, - // the ConsumerAdditionProp is assumed to be correctly serialized in SetPendingConsumerAdditionProp. - panic(fmt.Errorf("failed to unmarshal consumer addition proposal: %w", err)) - } - - return prop, true -} - -// BeginBlockInit iterates over the pending consumer addition proposals in order, and creates -// clients for props in which the spawn time has passed. Executed proposals are deleted. -// -// See: https://github.com/cosmos/ibc/blob/main/spec/app/ics-028-cross-chain-validation/methods.md#ccv-pcf-bblock-init1 -// Spec tag:[CCV-PCF-BBLOCK-INIT.1] -func (k Keeper) BeginBlockInit(ctx sdk.Context) { - propsToExecute := k.GetConsumerAdditionPropsToExecute(ctx) - - for i, prop := range propsToExecute { - // create consumer client in a cached context to handle errors - cachedCtx, writeFn := ctx.CacheContext() - - k.SetTopN(cachedCtx, prop.ChainId, prop.Top_N) - k.SetValidatorSetCap(cachedCtx, prop.ChainId, prop.ValidatorSetCap) - k.SetValidatorsPowerCap(cachedCtx, prop.ChainId, prop.ValidatorsPowerCap) - k.SetMinStake(cachedCtx, prop.ChainId, prop.MinStake) - k.SetInactiveValidatorsAllowed(cachedCtx, prop.ChainId, prop.AllowInactiveVals) - - for _, address := range prop.Allowlist { - consAddr, err := sdk.ConsAddressFromBech32(address) - if err != nil { - continue - } - - k.SetAllowlist(cachedCtx, prop.ChainId, types.NewProviderConsAddress(consAddr)) - } - - for _, address := range prop.Denylist { - consAddr, err := sdk.ConsAddressFromBech32(address) - if err != nil { - continue - } - - k.SetDenylist(cachedCtx, prop.ChainId, types.NewProviderConsAddress(consAddr)) - } - - err := k.CreateConsumerClient(cachedCtx, &propsToExecute[i]) - if err != nil { - // drop the proposal - ctx.Logger().Info("consumer client could not be created: %w", err) - continue - } - - consumerGenesis, found := k.GetConsumerGenesis(cachedCtx, prop.ChainId) - if !found { - // drop the proposal - ctx.Logger().Info("consumer genesis could not be created") - continue - } - - if len(consumerGenesis.Provider.InitialValSet) == 0 { - // drop the proposal - ctx.Logger().Info("consumer genesis initial validator set is empty - no validators opted in") - continue - } - - // The cached context is created with a new EventManager so we merge the event - // into the original context - ctx.EventManager().EmitEvents(cachedCtx.EventManager().Events()) - // write cache - writeFn() - - k.Logger(ctx).Info("executed consumer addition proposal", - "chainID", prop.ChainId, - "title", prop.Title, - "spawn time", prop.SpawnTime.UTC(), - ) - } - // delete the executed proposals - k.DeletePendingConsumerAdditionProps(ctx, propsToExecute...) -} - -// GetConsumerAdditionPropsToExecute returns the pending consumer addition proposals -// that are ready to be executed, i.e., consumer clients to be created. -// A prop is included in the returned list if its proposed spawn time has passed. -// -// Note: this method is split out from BeginBlockInit to be easily unit tested. -func (k Keeper) GetConsumerAdditionPropsToExecute(ctx sdk.Context) (propsToExecute []types.ConsumerAdditionProposal) { - store := ctx.KVStore(k.storeKey) - iterator := storetypes.KVStorePrefixIterator(store, types.PendingCAPKeyPrefix()) - - defer iterator.Close() - - for ; iterator.Valid(); iterator.Next() { - var prop types.ConsumerAdditionProposal - err := prop.Unmarshal(iterator.Value()) - if err != nil { - // An error here would indicate something is very wrong, - // the ConsumerAdditionProp is assumed to be correctly serialized in SetPendingConsumerAdditionProp. - panic(fmt.Errorf("failed to unmarshal consumer addition proposal: %w", err)) - } - - if !ctx.BlockTime().Before(prop.SpawnTime) { - propsToExecute = append(propsToExecute, prop) - } else { - break - } - } - - return propsToExecute -} - -// GetAllPendingConsumerAdditionProps gets all pending consumer addition proposals. -// -// Note that the pending consumer addition proposals are stored under keys with the following format: -// PendingCAPKeyPrefix | spawnTime.UnixNano() | chainID -// Thus, the returned array is in spawnTime order. If two proposals have the same spawnTime, -// then they are ordered by chainID. -func (k Keeper) GetAllPendingConsumerAdditionProps(ctx sdk.Context) (props []types.ConsumerAdditionProposal) { - store := ctx.KVStore(k.storeKey) - iterator := storetypes.KVStorePrefixIterator(store, types.PendingCAPKeyPrefix()) - - defer iterator.Close() - - for ; iterator.Valid(); iterator.Next() { - var prop types.ConsumerAdditionProposal - err := prop.Unmarshal(iterator.Value()) - if err != nil { - // An error here would indicate something is very wrong, - // the ConsumerAdditionProp is assumed to be correctly serialized in SetPendingConsumerAdditionProp. - panic(fmt.Errorf("failed to unmarshal consumer addition proposal: %w", err)) - } - - props = append(props, prop) - } - - return props -} - -// DeletePendingConsumerAdditionProps deletes the given consumer addition proposals -func (k Keeper) DeletePendingConsumerAdditionProps(ctx sdk.Context, proposals ...types.ConsumerAdditionProposal) { - store := ctx.KVStore(k.storeKey) - - for _, p := range proposals { - store.Delete(types.PendingCAPKey(p.SpawnTime, p.ChainId)) - } -} - -// SetPendingConsumerRemovalProp stores a pending consumer removal proposal. -// -// Note that the pending removal addition proposals are stored under keys with -// the following format: PendingCRPKeyPrefix | stopTime | chainID -// Thus, if multiple removal addition proposal for the same chain will pass at -// the same time, then only the last one will be stored. -func (k Keeper) SetPendingConsumerRemovalProp(ctx sdk.Context, prop *types.ConsumerRemovalProposal) { - store := ctx.KVStore(k.storeKey) - bz, err := prop.Marshal() - if err != nil { - // An error here would indicate something is very wrong - panic(fmt.Errorf("failed to marshal consumer removal proposal: %w", err)) - } - store.Set(types.PendingCRPKey(prop.StopTime, prop.ChainId), bz) -} - -// PendingConsumerRemovalPropExists checks whether a pending consumer removal proposal -// exists for the given consumer chain ID and stopTime -// -// Note: this method is only used in testing -func (k Keeper) PendingConsumerRemovalPropExists(ctx sdk.Context, chainID string, timestamp time.Time) bool { - store := ctx.KVStore(k.storeKey) - bz := store.Get(types.PendingCRPKey(timestamp, chainID)) - - return bz != nil -} - -// DeletePendingConsumerRemovalProps deletes the given pending consumer removal proposals. -// This method should be called once the proposal has been acted upon. -func (k Keeper) DeletePendingConsumerRemovalProps(ctx sdk.Context, proposals ...types.ConsumerRemovalProposal) { - store := ctx.KVStore(k.storeKey) - - for _, p := range proposals { - store.Delete(types.PendingCRPKey(p.StopTime, p.ChainId)) - } -} - -// BeginBlockCCR iterates over the pending consumer removal proposals -// in order and stop/removes the chain if the stop time has passed, -// otherwise it will break out of loop and return. Executed proposals are deleted. -// -// See: https://github.com/cosmos/ibc/blob/main/spec/app/ics-028-cross-chain-validation/methods.md#ccv-pcf-bblock-ccr1 -// Spec tag: [CCV-PCF-BBLOCK-CCR.1] -func (k Keeper) BeginBlockCCR(ctx sdk.Context) { - propsToExecute := k.GetConsumerRemovalPropsToExecute(ctx) - - for _, prop := range propsToExecute { - // stop consumer chain in a cached context to handle errors - cachedCtx, writeFn, err := k.StopConsumerChainInCachedCtx(ctx, prop) - if err != nil { - // drop the proposal - ctx.Logger().Info("consumer chain could not be stopped: %w", err) - continue - } - // The cached context is created with a new EventManager so we merge the event - // into the original context - ctx.EventManager().EmitEvents(cachedCtx.EventManager().Events()) - // write cache - writeFn() - - k.Logger(ctx).Info("executed consumer removal proposal", - "chainID", prop.ChainId, - "title", prop.Title, - "stop time", prop.StopTime.UTC(), - ) - } - // delete the executed proposals - k.DeletePendingConsumerRemovalProps(ctx, propsToExecute...) -} - -// GetConsumerRemovalPropsToExecute iterates over the pending consumer removal proposals -// and returns an ordered list of consumer removal proposals to be executed, -// ie. consumer chains to be stopped and removed from the provider chain. -// A prop is included in the returned list if its proposed stop time has passed. -// -// Note: this method is split out from BeginBlockCCR to be easily unit tested. -func (k Keeper) GetConsumerRemovalPropsToExecute(ctx sdk.Context) []types.ConsumerRemovalProposal { - // store the (to be) executed consumer removal proposals in order - propsToExecute := []types.ConsumerRemovalProposal{} - - store := ctx.KVStore(k.storeKey) - iterator := storetypes.KVStorePrefixIterator(store, types.PendingCRPKeyPrefix()) - defer iterator.Close() - - for ; iterator.Valid(); iterator.Next() { - var prop types.ConsumerRemovalProposal - err := prop.Unmarshal(iterator.Value()) - if err != nil { - // An error here would indicate something is very wrong, - // the ConsumerRemovalProposal is assumed to be correctly serialized in SetPendingConsumerRemovalProp. - panic(fmt.Errorf("failed to unmarshal consumer removal proposal: %w", err)) - } - - // If current block time is equal to or after stop time, proposal is ready to be executed - if !ctx.BlockTime().Before(prop.StopTime) { - propsToExecute = append(propsToExecute, prop) - } else { - // No more proposals to check, since they're stored/ordered by timestamp. - break - } - } - - return propsToExecute -} - -// GetAllPendingConsumerRemovalProps iterates through the pending consumer removal proposals. -// -// Note that the pending consumer removal proposals are stored under keys with the following format: -// PendingCRPKeyPrefix | stopTime.UnixNano() | chainID -// Thus, the returned array is in stopTime order. -func (k Keeper) GetAllPendingConsumerRemovalProps(ctx sdk.Context) (props []types.ConsumerRemovalProposal) { - store := ctx.KVStore(k.storeKey) - iterator := storetypes.KVStorePrefixIterator(store, types.PendingCRPKeyPrefix()) - defer iterator.Close() - - for ; iterator.Valid(); iterator.Next() { - var prop types.ConsumerRemovalProposal - err := prop.Unmarshal(iterator.Value()) - if err != nil { - // An error here would indicate something is very wrong, - // the ConsumerRemovalProposal is assumed to be correctly serialized in SetPendingConsumerRemovalProp. - panic(fmt.Errorf("failed to unmarshal consumer removal proposal: %w", err)) - } - - props = append(props, prop) - } - - return props -} - -// CreateConsumerClientInCachedCtx creates a consumer client -// from a given consumer addition proposal in a cached context -func (k Keeper) CreateConsumerClientInCachedCtx(ctx sdk.Context, p types.ConsumerAdditionProposal) (cc sdk.Context, writeCache func(), err error) { - cc, writeCache = ctx.CacheContext() - err = k.CreateConsumerClient(cc, &p) - return -} - -// StopConsumerChainInCachedCtx stop a consumer chain -// from a given consumer removal proposal in a cached context -func (k Keeper) StopConsumerChainInCachedCtx(ctx sdk.Context, p types.ConsumerRemovalProposal) (cc sdk.Context, writeCache func(), err error) { - cc, writeCache = ctx.CacheContext() - err = k.StopConsumerChain(cc, p.ChainId, true) - return -} diff --git a/x/ccv/provider/keeper/proposal_test.go b/x/ccv/provider/keeper/proposal_test.go deleted file mode 100644 index 472cb3c64c..0000000000 --- a/x/ccv/provider/keeper/proposal_test.go +++ /dev/null @@ -1,1098 +0,0 @@ -package keeper_test - -import ( - "bytes" - "encoding/json" - "sort" - "testing" - "time" - - stakingtypes "github.com/cosmos/cosmos-sdk/x/staking/types" - - "cosmossdk.io/math" - clienttypes "github.com/cosmos/ibc-go/v8/modules/core/02-client/types" - ibctmtypes "github.com/cosmos/ibc-go/v8/modules/light-clients/07-tendermint" - _go "github.com/cosmos/ics23/go" - "github.com/golang/mock/gomock" - "github.com/stretchr/testify/require" - - abci "github.com/cometbft/cometbft/abci/types" - sdk "github.com/cosmos/cosmos-sdk/types" - - cryptotestutil "github.com/cosmos/interchain-security/v5/testutil/crypto" - testkeeper "github.com/cosmos/interchain-security/v5/testutil/keeper" - providerkeeper "github.com/cosmos/interchain-security/v5/x/ccv/provider/keeper" - providertypes "github.com/cosmos/interchain-security/v5/x/ccv/provider/types" - ccvtypes "github.com/cosmos/interchain-security/v5/x/ccv/types" -) - -// -// Initialization sub-protocol related tests of proposal.go -// - -// Tests the HandleConsumerAdditionProposal method against the SpawnConsumerChainProposalHandler spec. -// See: https://github.com/cosmos/ibc/blob/main/spec/app/ics-028-cross-chain-validation/methods.md#ccv-pcf-hcaprop1 -// Spec tag: [CCV-PCF-HCAPROP.1] -func TestHandleConsumerAdditionProposal(t *testing.T) { - type testCase struct { - description string - malleate func(ctx sdk.Context, k providerkeeper.Keeper, chainID string) - prop *providertypes.ConsumerAdditionProposal - // Time when prop is handled - blockTime time.Time - // Whether it's expected that the proposal is successfully verified - // and appended to the pending proposals - expAppendProp bool - } - - // Snapshot times asserted in tests - now := time.Now().UTC() - - tests := []testCase{ - { - description: "expect to append valid proposal", - malleate: func(ctx sdk.Context, k providerkeeper.Keeper, chainID string) {}, - prop: providertypes.NewConsumerAdditionProposal( - "title", - "description", - "chainID", - clienttypes.NewHeight(2, 3), - []byte("gen_hash"), - []byte("bin_hash"), - now, // Spawn time - "0.75", - 10, - "", - 10000, - 100000000000, - 100000000000, - 100000000000, - 0, - 0, - 0, - nil, - nil, - 0, - false, - ).(*providertypes.ConsumerAdditionProposal), - blockTime: now, - expAppendProp: true, - }, - { - description: "expect to not append invalid proposal using an already existing chain id", - malleate: func(ctx sdk.Context, k providerkeeper.Keeper, chainID string) { - k.SetConsumerClientId(ctx, chainID, "anyClientId") - }, - - prop: providertypes.NewConsumerAdditionProposal( - "title", - "description", - "chainID", - clienttypes.NewHeight(2, 3), - []byte("gen_hash"), - []byte("bin_hash"), - now, - "0.75", - 10, - "", - 10000, - 100000000000, - 100000000000, - 100000000000, - 0, - 0, - 0, - nil, - nil, - 0, - false, - ).(*providertypes.ConsumerAdditionProposal), - blockTime: now, - expAppendProp: false, - }, - } - - for _, tc := range tests { - // Common setup - keeperParams := testkeeper.NewInMemKeeperParams(t) - providerKeeper, ctx, ctrl, mocks := testkeeper.GetProviderKeeperAndCtx(t, keeperParams) - providerKeeper.SetParams(ctx, providertypes.DefaultParams()) - ctx = ctx.WithBlockTime(tc.blockTime) - - if tc.expAppendProp { - // Mock calls are only asserted if we expect a client to be created. - testkeeper.SetupMocksForLastBondedValidatorsExpectation(mocks.MockStakingKeeper, 0, []stakingtypes.Validator{}, 1) // returns empty validator set - gomock.InOrder( - testkeeper.GetMocksForCreateConsumerClient(ctx, &mocks, tc.prop.ChainId, clienttypes.NewHeight(2, 3))..., - ) - } - - tc.malleate(ctx, providerKeeper, tc.prop.ChainId) - - err := providerKeeper.HandleLegacyConsumerAdditionProposal(ctx, tc.prop) - - if tc.expAppendProp { - require.NoError(t, err) - // check that prop was added to the stored pending props - gotProposal, found := providerKeeper.GetPendingConsumerAdditionProp(ctx, tc.prop.SpawnTime, tc.prop.ChainId) - require.True(t, found) - require.Equal(t, *tc.prop, gotProposal) - } else { - require.Error(t, err) - // check that prop wasn't added to the stored pending props - _, found := providerKeeper.GetPendingConsumerAdditionProp(ctx, tc.prop.SpawnTime, tc.prop.ChainId) - require.False(t, found) - } - - ctrl.Finish() - } -} - -// Tests the CreateConsumerClient method against the spec, -// with more granularity than what's covered in TestHandleCreateConsumerChainProposal. -// See: https://github.com/cosmos/ibc/blob/main/spec/app/ics-028-cross-chain-validation/methods.md#ccv-pcf-crclient1 -// Spec tag: [CCV-PCF-CRCLIENT.1] -func TestCreateConsumerClient(t *testing.T) { - type testCase struct { - description string - // Any state-mutating setup on keeper and expected mock calls, specific to this test case - setup func(*providerkeeper.Keeper, sdk.Context, *testkeeper.MockedKeepers) - // Whether a client should be created - expClientCreated bool - } - tests := []testCase{ - { - description: "No state mutation, new client should be created", - setup: func(providerKeeper *providerkeeper.Keeper, ctx sdk.Context, mocks *testkeeper.MockedKeepers) { - // Valid client creation is asserted with mock expectations here - testkeeper.SetupMocksForLastBondedValidatorsExpectation(mocks.MockStakingKeeper, 0, []stakingtypes.Validator{}, 1) // returns empty validator set - gomock.InOrder( - testkeeper.GetMocksForCreateConsumerClient(ctx, mocks, "chainID", clienttypes.NewHeight(4, 5))..., - ) - }, - expClientCreated: true, - }, - { - description: "client for this chain already exists, new one is not created", - setup: func(providerKeeper *providerkeeper.Keeper, ctx sdk.Context, mocks *testkeeper.MockedKeepers) { - providerKeeper.SetConsumerClientId(ctx, "chainID", "clientID") - - // Expect none of the client creation related calls to happen - mocks.MockStakingKeeper.EXPECT().UnbondingTime(gomock.Any()).Times(0) - mocks.MockClientKeeper.EXPECT().CreateClient(gomock.Any(), gomock.Any(), gomock.Any()).Times(0) - mocks.MockClientKeeper.EXPECT().GetSelfConsensusState(gomock.Any(), gomock.Any()).Times(0) - testkeeper.SetupMocksForLastBondedValidatorsExpectation(mocks.MockStakingKeeper, 0, []stakingtypes.Validator{}, 0) // returns empty validator set - }, - expClientCreated: false, - }, - } - - for _, tc := range tests { - // Common setup - keeperParams := testkeeper.NewInMemKeeperParams(t) - providerKeeper, ctx, ctrl, mocks := testkeeper.GetProviderKeeperAndCtx(t, keeperParams) - providerKeeper.SetParams(ctx, providertypes.DefaultParams()) - - // Test specific setup - tc.setup(&providerKeeper, ctx, &mocks) - - // Call method with same arbitrary values as defined above in mock expectations. - err := providerKeeper.CreateConsumerClient(ctx, testkeeper.GetTestConsumerAdditionProp()) - - if tc.expClientCreated { - require.NoError(t, err) - testCreatedConsumerClient(t, ctx, providerKeeper, "chainID", "clientID") - } else { - require.Error(t, err) - } - - // Assert mock calls from setup functions - ctrl.Finish() - } -} - -// Executes test assertions for a created consumer client. -// -// Note: Separated from TestCreateConsumerClient to also be called from TestCreateConsumerChainProposal. -func testCreatedConsumerClient(t *testing.T, - ctx sdk.Context, providerKeeper providerkeeper.Keeper, expectedChainID, expectedClientID string, -) { - t.Helper() - // ClientID should be stored. - clientId, found := providerKeeper.GetConsumerClientId(ctx, expectedChainID) - require.True(t, found, "consumer client not found") - require.Equal(t, expectedClientID, clientId) - - // Only assert that consumer genesis was set, - // more granular tests on consumer genesis should be defined in TestMakeConsumerGenesis - _, ok := providerKeeper.GetConsumerGenesis(ctx, expectedChainID) - require.True(t, ok) -} - -// TestPendingConsumerAdditionPropDeletion tests the getting/setting -// and deletion keeper methods for pending consumer addition props -func TestPendingConsumerAdditionPropDeletion(t *testing.T) { - testCases := []struct { - providertypes.ConsumerAdditionProposal - ExpDeleted bool - }{ - { - ConsumerAdditionProposal: providertypes.ConsumerAdditionProposal{ChainId: "0", SpawnTime: time.Now().UTC()}, - ExpDeleted: true, - }, - { - ConsumerAdditionProposal: providertypes.ConsumerAdditionProposal{ChainId: "1", SpawnTime: time.Now().UTC().Add(time.Hour)}, - ExpDeleted: false, - }, - } - providerKeeper, ctx, ctrl, _ := testkeeper.GetProviderKeeperAndCtx(t, testkeeper.NewInMemKeeperParams(t)) - defer ctrl.Finish() - - for _, tc := range testCases { - tc := tc - providerKeeper.SetPendingConsumerAdditionProp(ctx, &tc.ConsumerAdditionProposal) - } - - ctx = ctx.WithBlockTime(time.Now().UTC()) - - propsToExecute := providerKeeper.GetConsumerAdditionPropsToExecute(ctx) - // Delete consumer addition proposals, same as what would be done by BeginBlockInit - providerKeeper.DeletePendingConsumerAdditionProps(ctx, propsToExecute...) - numDeleted := 0 - for _, tc := range testCases { - res, found := providerKeeper.GetPendingConsumerAdditionProp(ctx, tc.SpawnTime, tc.ChainId) - if !tc.ExpDeleted { - require.True(t, found) - require.NotEmpty(t, res, "consumer addition proposal was deleted: %s %s", tc.ChainId, tc.SpawnTime.String()) - continue - } - require.Empty(t, res, "consumer addition proposal was not deleted %s %s", tc.ChainId, tc.SpawnTime.String()) - require.Equal(t, propsToExecute[numDeleted].ChainId, tc.ChainId) - numDeleted += 1 - } -} - -// TestGetConsumerAdditionPropsToExecute tests that pending consumer addition proposals -// that are ready to execute are accessed in order by timestamp via the iterator -func TestGetConsumerAdditionPropsToExecute(t *testing.T) { - now := time.Now().UTC() - sampleProp1 := providertypes.ConsumerAdditionProposal{ChainId: "chain-2", SpawnTime: now} - sampleProp2 := providertypes.ConsumerAdditionProposal{ChainId: "chain-1", SpawnTime: now.Add(time.Hour)} - sampleProp3 := providertypes.ConsumerAdditionProposal{ChainId: "chain-4", SpawnTime: now.Add(-time.Hour)} - sampleProp4 := providertypes.ConsumerAdditionProposal{ChainId: "chain-3", SpawnTime: now} - sampleProp5 := providertypes.ConsumerAdditionProposal{ChainId: "chain-1", SpawnTime: now.Add(2 * time.Hour)} - - getExpectedOrder := func(props []providertypes.ConsumerAdditionProposal, accessTime time.Time) []providertypes.ConsumerAdditionProposal { - expectedOrder := []providertypes.ConsumerAdditionProposal{} - for _, prop := range props { - if !accessTime.Before(prop.SpawnTime) { - expectedOrder = append(expectedOrder, prop) - } - } - if len(expectedOrder) == 0 { - return nil - } - // sorting by SpawnTime.UnixNano() - sort.Slice(expectedOrder, func(i, j int) bool { - if expectedOrder[i].SpawnTime.UTC() == expectedOrder[j].SpawnTime.UTC() { - // proposals with same SpawnTime - return expectedOrder[i].ChainId < expectedOrder[j].ChainId - } - return expectedOrder[i].SpawnTime.UTC().Before(expectedOrder[j].SpawnTime.UTC()) - }) - return expectedOrder - } - - testCases := []struct { - propSubmitOrder []providertypes.ConsumerAdditionProposal - accessTime time.Time - }{ - { - propSubmitOrder: []providertypes.ConsumerAdditionProposal{ - sampleProp1, sampleProp2, sampleProp3, sampleProp4, sampleProp5, - }, - accessTime: now, - }, - { - propSubmitOrder: []providertypes.ConsumerAdditionProposal{ - sampleProp3, sampleProp2, sampleProp1, sampleProp5, sampleProp4, - }, - accessTime: now.Add(time.Hour), - }, - { - propSubmitOrder: []providertypes.ConsumerAdditionProposal{ - sampleProp5, sampleProp4, sampleProp3, sampleProp2, sampleProp1, - }, - accessTime: now.Add(-2 * time.Hour), - }, - { - propSubmitOrder: []providertypes.ConsumerAdditionProposal{ - sampleProp5, sampleProp4, sampleProp3, sampleProp2, sampleProp1, - }, - accessTime: now.Add(3 * time.Hour), - }, - } - - for _, tc := range testCases { - providerKeeper, ctx, ctrl, _ := testkeeper.GetProviderKeeperAndCtx(t, testkeeper.NewInMemKeeperParams(t)) - defer ctrl.Finish() - - expectedOrderedProps := getExpectedOrder(tc.propSubmitOrder, tc.accessTime) - - for _, prop := range tc.propSubmitOrder { - cpProp := prop - providerKeeper.SetPendingConsumerAdditionProp(ctx, &cpProp) - } - propsToExecute := providerKeeper.GetConsumerAdditionPropsToExecute(ctx.WithBlockTime(tc.accessTime)) - require.Equal(t, expectedOrderedProps, propsToExecute) - } -} - -// Test getting both matured and pending consumer addition proposals -func TestGetAllConsumerAdditionProps(t *testing.T) { - pk, ctx, ctrl, _ := testkeeper.GetProviderKeeperAndCtx(t, testkeeper.NewInMemKeeperParams(t)) - defer ctrl.Finish() - - now := time.Now().UTC() - props := []providertypes.ConsumerAdditionProposal{ - {ChainId: "chain-2", SpawnTime: now}, - {ChainId: "chain-1", SpawnTime: now.Add(2 * time.Hour)}, - {ChainId: "chain-4", SpawnTime: now.Add(-time.Hour)}, - {ChainId: "chain-3", SpawnTime: now.Add(4 * time.Hour)}, - {ChainId: "chain-1", SpawnTime: now}, - } - expectedGetAllOrder := props - // sorting by SpawnTime.UnixNano() - sort.Slice(expectedGetAllOrder, func(i, j int) bool { - tsi := uint64(expectedGetAllOrder[i].SpawnTime.UTC().UnixNano()) - tsj := uint64(expectedGetAllOrder[j].SpawnTime.UTC().UnixNano()) - cmpTimestamps := bytes.Compare(sdk.Uint64ToBigEndian(tsi), sdk.Uint64ToBigEndian(tsj)) - if cmpTimestamps == 0 { - // proposals with same SpawnTime - return expectedGetAllOrder[i].ChainId < expectedGetAllOrder[j].ChainId - } - return cmpTimestamps == -1 - }) - - for _, prop := range props { - cpProp := prop // bring into loop scope - avoids using iterator pointer instead of value pointer - pk.SetPendingConsumerAdditionProp(ctx, &cpProp) - } - - // iterate and check all results are returned in the expected order - result := pk.GetAllPendingConsumerAdditionProps(ctx.WithBlockTime(now)) - require.Len(t, result, len(props)) - require.Equal(t, expectedGetAllOrder, result) -} - -// Tests the StopConsumerChain method against the spec, -// with more granularity than what's covered in TestHandleLegacyConsumerRemovalProposal, or integration tests. -// See: https://github.com/cosmos/ibc/blob/main/spec/app/ics-028-cross-chain-validation/methods.md#ccv-pcf-stcc1 -// Spec tag: [CCV-PCF-STCC.1] -func TestStopConsumerChain(t *testing.T) { - type testCase struct { - description string - // State-mutating setup specific to this test case - setup func(sdk.Context, *providerkeeper.Keeper, testkeeper.MockedKeepers) - // Whether we should expect the method to return an error - expErr bool - } - - consumerCID := "chainID" - - tests := []testCase{ - { - description: "proposal dropped, client doesn't exist", - setup: func(ctx sdk.Context, providerKeeper *providerkeeper.Keeper, mocks testkeeper.MockedKeepers) { - // No mocks, meaning no external keeper methods are allowed to be called. - }, - expErr: true, - }, - { - description: "valid stop of consumer chain, all mock calls hit", - setup: func(ctx sdk.Context, providerKeeper *providerkeeper.Keeper, mocks testkeeper.MockedKeepers) { - testkeeper.SetupForStoppingConsumerChain(t, ctx, providerKeeper, mocks) - - // set consumer minimum equivocation height - providerKeeper.SetEquivocationEvidenceMinHeight(ctx, consumerCID, 1) - - // assert mocks for expected calls to `StopConsumerChain` when closing the underlying channel - gomock.InOrder(testkeeper.GetMocksForStopConsumerChainWithCloseChannel(ctx, &mocks)...) - }, - expErr: false, - }, - } - - for _, tc := range tests { - - // Common setup - keeperParams := testkeeper.NewInMemKeeperParams(t) - providerKeeper, ctx, ctrl, mocks := testkeeper.GetProviderKeeperAndCtx(t, keeperParams) - providerKeeper.SetParams(ctx, providertypes.DefaultParams()) - - // Setup specific to test case - tc.setup(ctx, &providerKeeper, mocks) - - err := providerKeeper.StopConsumerChain(ctx, consumerCID, true) - - if tc.expErr { - require.Error(t, err) - } else { - require.NoError(t, err) - } - - testkeeper.TestProviderStateIsCleanedAfterConsumerChainIsStopped(t, ctx, providerKeeper, consumerCID, "channelID") - - ctrl.Finish() - } -} - -// TestPendingConsumerRemovalPropDeletion tests the getting/setting -// and deletion methods for pending consumer removal props -func TestPendingConsumerRemovalPropDeletion(t *testing.T) { - testCases := []struct { - providertypes.ConsumerRemovalProposal - ExpDeleted bool - }{ - { - ConsumerRemovalProposal: providertypes.ConsumerRemovalProposal{ChainId: "8", StopTime: time.Now().UTC()}, - ExpDeleted: true, - }, - { - ConsumerRemovalProposal: providertypes.ConsumerRemovalProposal{ChainId: "9", StopTime: time.Now().UTC().Add(time.Hour)}, - ExpDeleted: false, - }, - } - providerKeeper, ctx, ctrl, _ := testkeeper.GetProviderKeeperAndCtx(t, testkeeper.NewInMemKeeperParams(t)) - defer ctrl.Finish() - - for _, tc := range testCases { - tc := tc - providerKeeper.SetPendingConsumerRemovalProp(ctx, &tc.ConsumerRemovalProposal) - } - - ctx = ctx.WithBlockTime(time.Now().UTC()) - - propsToExecute := providerKeeper.GetConsumerRemovalPropsToExecute(ctx) - // Delete consumer removal proposals, same as what would be done by BeginBlockCCR - providerKeeper.DeletePendingConsumerRemovalProps(ctx, propsToExecute...) - numDeleted := 0 - for _, tc := range testCases { - res := providerKeeper.PendingConsumerRemovalPropExists(ctx, tc.ChainId, tc.StopTime) - if !tc.ExpDeleted { - require.NotEmpty(t, res, "consumer removal prop was deleted: %s %s", tc.ChainId, tc.StopTime.String()) - continue - } - require.Empty(t, res, "consumer removal prop was not deleted %s %s", tc.ChainId, tc.StopTime.String()) - require.Equal(t, propsToExecute[numDeleted].ChainId, tc.ChainId) - numDeleted += 1 - } -} - -// TestGetConsumerRemovalPropsToExecute tests that pending consumer removal proposals -// that are ready to execute are accessed in order by timestamp via the iterator -func TestGetConsumerRemovalPropsToExecute(t *testing.T) { - now := time.Now().UTC() - sampleProp1 := providertypes.ConsumerRemovalProposal{ChainId: "chain-2", StopTime: now} - sampleProp2 := providertypes.ConsumerRemovalProposal{ChainId: "chain-1", StopTime: now.Add(time.Hour)} - sampleProp3 := providertypes.ConsumerRemovalProposal{ChainId: "chain-4", StopTime: now.Add(-time.Hour)} - sampleProp4 := providertypes.ConsumerRemovalProposal{ChainId: "chain-3", StopTime: now} - sampleProp5 := providertypes.ConsumerRemovalProposal{ChainId: "chain-1", StopTime: now.Add(2 * time.Hour)} - - getExpectedOrder := func(props []providertypes.ConsumerRemovalProposal, accessTime time.Time) []providertypes.ConsumerRemovalProposal { - expectedOrder := []providertypes.ConsumerRemovalProposal{} - for _, prop := range props { - if !accessTime.Before(prop.StopTime) { - expectedOrder = append(expectedOrder, prop) - } - } - // sorting by SpawnTime.UnixNano() - sort.Slice(expectedOrder, func(i, j int) bool { - if expectedOrder[i].StopTime.UTC() == expectedOrder[j].StopTime.UTC() { - // proposals with same StopTime - return expectedOrder[i].ChainId < expectedOrder[j].ChainId - } - return expectedOrder[i].StopTime.UTC().Before(expectedOrder[j].StopTime.UTC()) - }) - return expectedOrder - } - - testCases := []struct { - propSubmitOrder []providertypes.ConsumerRemovalProposal - accessTime time.Time - }{ - { - propSubmitOrder: []providertypes.ConsumerRemovalProposal{ - sampleProp1, sampleProp2, sampleProp3, sampleProp4, sampleProp5, - }, - accessTime: now, - }, - { - propSubmitOrder: []providertypes.ConsumerRemovalProposal{ - sampleProp3, sampleProp2, sampleProp1, sampleProp5, sampleProp4, - }, - accessTime: now.Add(time.Hour), - }, - { - propSubmitOrder: []providertypes.ConsumerRemovalProposal{ - sampleProp5, sampleProp4, sampleProp3, sampleProp2, sampleProp1, - }, - accessTime: now.Add(-2 * time.Hour), - }, - { - propSubmitOrder: []providertypes.ConsumerRemovalProposal{ - sampleProp5, sampleProp4, sampleProp3, sampleProp2, sampleProp1, - }, - accessTime: now.Add(3 * time.Hour), - }, - } - - for _, tc := range testCases { - providerKeeper, ctx, ctrl, _ := testkeeper.GetProviderKeeperAndCtx(t, testkeeper.NewInMemKeeperParams(t)) - defer ctrl.Finish() - - expectedOrderedProps := getExpectedOrder(tc.propSubmitOrder, tc.accessTime) - - for _, prop := range tc.propSubmitOrder { - cpProp := prop - providerKeeper.SetPendingConsumerRemovalProp(ctx, &cpProp) - } - propsToExecute := providerKeeper.GetConsumerRemovalPropsToExecute(ctx.WithBlockTime(tc.accessTime)) - require.Equal(t, expectedOrderedProps, propsToExecute) - } -} - -// Test getting both matured and pending consumer removal proposals -func TestGetAllConsumerRemovalProps(t *testing.T) { - pk, ctx, ctrl, _ := testkeeper.GetProviderKeeperAndCtx(t, testkeeper.NewInMemKeeperParams(t)) - defer ctrl.Finish() - - now := time.Now().UTC() - props := []providertypes.ConsumerRemovalProposal{ - {ChainId: "chain-2", StopTime: now}, - {ChainId: "chain-1", StopTime: now.Add(2 * time.Hour)}, - {ChainId: "chain-4", StopTime: now.Add(-time.Hour)}, - {ChainId: "chain-3", StopTime: now.Add(4 * time.Hour)}, - {ChainId: "chain-1", StopTime: now}, - } - expectedGetAllOrder := props - // sorting by StopTime.UnixNano() - sort.Slice(expectedGetAllOrder, func(i, j int) bool { - tsi := uint64(expectedGetAllOrder[i].StopTime.UTC().UnixNano()) - tsj := uint64(expectedGetAllOrder[j].StopTime.UTC().UnixNano()) - cmpTimestamps := bytes.Compare(sdk.Uint64ToBigEndian(tsi), sdk.Uint64ToBigEndian(tsj)) - if cmpTimestamps == 0 { - // proposals with same StopTime - return expectedGetAllOrder[i].ChainId < expectedGetAllOrder[j].ChainId - } - return cmpTimestamps == -1 - }) - - for _, prop := range props { - cpProp := prop // bring into loop scope - avoids using iterator pointer instead of value pointer - pk.SetPendingConsumerRemovalProp(ctx, &cpProp) - } - - // iterate and check all results are returned in the expected order - result := pk.GetAllPendingConsumerRemovalProps(ctx.WithBlockTime(now)) - require.Len(t, result, len(props)) - require.Equal(t, expectedGetAllOrder, result) -} - -// TestMakeConsumerGenesis tests the MakeConsumerGenesis keeper method. -// An expected genesis state is hardcoded in json, unmarshaled, and compared -// against an actual consumer genesis state constructed by a provider keeper. -func TestMakeConsumerGenesis(t *testing.T) { - keeperParams := testkeeper.NewInMemKeeperParams(t) - providerKeeper, ctx, ctrl, mocks := testkeeper.GetProviderKeeperAndCtx(t, keeperParams) - moduleParams := providertypes.Params{ - TemplateClient: &ibctmtypes.ClientState{ - TrustLevel: ibctmtypes.DefaultTrustLevel, - MaxClockDrift: 10000000000, - ProofSpecs: []*_go.ProofSpec{ - { - LeafSpec: &_go.LeafOp{ - Hash: _go.HashOp_SHA256, - PrehashKey: _go.HashOp_NO_HASH, - PrehashValue: _go.HashOp_SHA256, - Length: _go.LengthOp_VAR_PROTO, - Prefix: []byte{0x00}, - }, - InnerSpec: &_go.InnerSpec{ - ChildOrder: []int32{0, 1}, - ChildSize: 33, - MinPrefixLength: 4, - MaxPrefixLength: 12, - Hash: _go.HashOp_SHA256, - }, - MaxDepth: 0, - MinDepth: 0, - }, - { - LeafSpec: &_go.LeafOp{ - Hash: _go.HashOp_SHA256, - PrehashKey: _go.HashOp_NO_HASH, - PrehashValue: _go.HashOp_SHA256, - Length: _go.LengthOp_VAR_PROTO, - Prefix: []byte{0x00}, - }, - InnerSpec: &_go.InnerSpec{ - ChildOrder: []int32{0, 1}, - ChildSize: 32, - MinPrefixLength: 1, - MaxPrefixLength: 1, - Hash: _go.HashOp_SHA256, - }, - MaxDepth: 0, - }, - }, - UpgradePath: []string{"upgrade", "upgradedIBCState"}, - AllowUpdateAfterExpiry: true, - AllowUpdateAfterMisbehaviour: true, - }, - // Note these are unused provider parameters for this test, and not actually asserted against - // They must be populated with reasonable values to satisfy SetParams though. - TrustingPeriodFraction: providertypes.DefaultTrustingPeriodFraction, - CcvTimeoutPeriod: ccvtypes.DefaultCCVTimeoutPeriod, - SlashMeterReplenishPeriod: providertypes.DefaultSlashMeterReplenishPeriod, - SlashMeterReplenishFraction: providertypes.DefaultSlashMeterReplenishFraction, - ConsumerRewardDenomRegistrationFee: sdk.Coin{ - Denom: "stake", - Amount: math.NewInt(1000000), - }, - BlocksPerEpoch: 600, - NumberOfEpochsToStartReceivingRewards: 24, - } - providerKeeper.SetParams(ctx, moduleParams) - defer ctrl.Finish() - - // - // Other setup not covered by custom template client state - // - ctx = ctx.WithChainID("testchain1") // chainID is obtained from ctx - ctx = ctx.WithBlockHeight(5) // RevisionHeight obtained from ctx - testkeeper.SetupMocksForLastBondedValidatorsExpectation(mocks.MockStakingKeeper, 0, []stakingtypes.Validator{}, 1) - gomock.InOrder(testkeeper.GetMocksForMakeConsumerGenesis(ctx, &mocks, 1814400000000000)...) - - // matches params from jsonString - prop := providertypes.ConsumerAdditionProposal{ - Title: "title", - Description: "desc", - ChainId: "testchain1", - BlocksPerDistributionTransmission: 1000, - CcvTimeoutPeriod: 2419200000000000, - TransferTimeoutPeriod: 3600000000000, - ConsumerRedistributionFraction: "0.75", - HistoricalEntries: 10000, - UnbondingPeriod: 1728000000000000, - } - actualGenesis, _, err := providerKeeper.MakeConsumerGenesis(ctx, &prop) - require.NoError(t, err) - - // JSON string with tabs, newlines and spaces for readability - jsonString := `{ - "params": { - "enabled": true, - "blocks_per_distribution_transmission": 1000, - "ccv_timeout_period": 2419200000000000, - "transfer_timeout_period": 3600000000000, - "consumer_redistribution_fraction": "0.75", - "historical_entries": 10000, - "unbonding_period": 1728000000000000, - "soft_opt_out_threshold": "0", - "reward_denoms": [], - "provider_reward_denoms": [], - "retry_delay_period": 3600000000000 - }, - "new_chain": true, - "provider" : { - "client_state": { - "chain_id": "testchain1", - "trust_level": { - "numerator": 1, - "denominator": 3 - }, - "trusting_period": 1197504000000000, - "unbonding_period": 1814400000000000, - "max_clock_drift": 10000000000, - "frozen_height": {}, - "latest_height": { - "revision_height": 5 - }, - "proof_specs": [ - { - "leaf_spec": { - "hash": 1, - "prehash_value": 1, - "length": 1, - "prefix": "AA==" - }, - "inner_spec": { - "child_order": [0, 1], - "child_size": 33, - "min_prefix_length": 4, - "max_prefix_length": 12, - "hash": 1 - } - }, - { - "leaf_spec": { - "hash": 1, - "prehash_value": 1, - "length": 1, - "prefix": "AA==" - }, - "inner_spec": { - "child_order": [0, 1], - "child_size": 32, - "min_prefix_length": 1, - "max_prefix_length": 1, - "hash": 1 - } - } - ], - "upgrade_path": ["upgrade", "upgradedIBCState"], - "allow_update_after_expiry": true, - "allow_update_after_misbehaviour": true - }, - "consensus_state": { - "timestamp": "2020-01-02T00:00:10Z", - "root": { - "hash": "LpGpeyQVLUo9HpdsgJr12NP2eCICspcULiWa5u9udOA=" - }, - "next_validators_hash": "E30CE736441FB9101FADDAF7E578ABBE6DFDB67207112350A9A904D554E1F5BE" - }, - "initial_val_set": [ - { - "pub_key": { - "type": "tendermint/PubKeyEd25519", - "value": "dcASx5/LIKZqagJWN0frOlFtcvz91frYmj/zmoZRWro=" - }, - "power": 1 - } - ] - } - }` - - var expectedGenesis ccvtypes.ConsumerGenesisState - err = json.Unmarshal([]byte(jsonString), &expectedGenesis) // ignores tabs, newlines and spaces - require.NoError(t, err) - - // Zeroing out different fields that are challenging to mock - actualGenesis.Provider.InitialValSet = []abci.ValidatorUpdate{} - expectedGenesis.Provider.InitialValSet = []abci.ValidatorUpdate{} - actualGenesis.Provider.ConsensusState = &ibctmtypes.ConsensusState{} - expectedGenesis.Provider.ConsensusState = &ibctmtypes.ConsensusState{} - - require.Equal(t, expectedGenesis, actualGenesis, "consumer chain genesis created incorrectly") -} - -// TestBeginBlockInit directly tests BeginBlockInit against the spec using helpers defined above. -// -// See: https://github.com/cosmos/ibc/blob/main/spec/app/ics-028-cross-chain-validation/methods.md#ccv-pcf-bblock-init1 -// Spec tag:[CCV-PCF-BBLOCK-INIT.1] -func TestBeginBlockInit(t *testing.T) { - now := time.Now().UTC() - - keeperParams := testkeeper.NewInMemKeeperParams(t) - providerKeeper, ctx, ctrl, mocks := testkeeper.GetProviderKeeperAndCtx(t, keeperParams) - providerKeeper.SetParams(ctx, providertypes.DefaultParams()) - defer ctrl.Finish() - ctx = ctx.WithBlockTime(now) - - pendingProps := []*providertypes.ConsumerAdditionProposal{ - providertypes.NewConsumerAdditionProposal( - "title", "spawn time passed", "chain1", clienttypes.NewHeight(3, 4), []byte{}, []byte{}, - now.Add(-time.Hour*2).UTC(), - "0.75", - 10, - "", - 10000, - 100000000000, - 100000000000, - 100000000000, - 50, - 0, - 0, - nil, - nil, - 0, - false, - ).(*providertypes.ConsumerAdditionProposal), - providertypes.NewConsumerAdditionProposal( - "title", "spawn time passed", "chain2", clienttypes.NewHeight(3, 4), []byte{}, []byte{}, - now.Add(-time.Hour*1).UTC(), - "0.75", - 10, - "", - 10000, - 100000000000, - 100000000000, - 100000000000, - 50, - 0, - 0, - nil, - nil, - 0, - false, - ).(*providertypes.ConsumerAdditionProposal), - providertypes.NewConsumerAdditionProposal( - "title", "spawn time not passed", "chain3", clienttypes.NewHeight(3, 4), []byte{}, []byte{}, - now.Add(time.Hour).UTC(), - "0.75", - 10, - "", - 10000, - 100000000000, - 100000000000, - 100000000000, - 50, - 0, - 0, - nil, - nil, - 0, - false, - ).(*providertypes.ConsumerAdditionProposal), - providertypes.NewConsumerAdditionProposal( - "title", "invalid proposal: chain id already exists", "chain2", clienttypes.NewHeight(4, 5), []byte{}, []byte{}, - now.UTC(), - "0.75", - 10, - "", - 10000, - 100000000000, - 100000000000, - 100000000000, - 50, - 0, - 0, - nil, - nil, - 0, - false, - ).(*providertypes.ConsumerAdditionProposal), - providertypes.NewConsumerAdditionProposal( - "title", "opt-in chain with at least one validator opted in", "chain5", clienttypes.NewHeight(3, 4), []byte{}, []byte{}, - now.Add(-time.Hour*1).UTC(), - "0.75", - 10, - "", - 10000, - 100000000000, - 100000000000, - 100000000000, - 0, - 0, - 0, - nil, - nil, - 0, - false, - ).(*providertypes.ConsumerAdditionProposal), - providertypes.NewConsumerAdditionProposal( - "title", "opt-in chain with no validator opted in", "chain6", clienttypes.NewHeight(3, 4), []byte{}, []byte{}, - now.Add(-time.Minute).UTC(), - "0.75", - 10, - "", - 10000, - 100000000000, - 100000000000, - 100000000000, - 0, - 0, - 0, - nil, - nil, - 0, - false, - ).(*providertypes.ConsumerAdditionProposal), - } - - // Expect client creation for only the first, second, and fifth proposals (spawn time already passed and valid) - expectedCalls := testkeeper.GetMocksForCreateConsumerClient(ctx, &mocks, "chain1", clienttypes.NewHeight(3, 4)) - expectedCalls = append(expectedCalls, testkeeper.GetMocksForCreateConsumerClient(ctx, &mocks, "chain2", clienttypes.NewHeight(3, 4))...) - expectedCalls = append(expectedCalls, testkeeper.GetMocksForCreateConsumerClient(ctx, &mocks, "chain5", clienttypes.NewHeight(3, 4))...) - - // The sixth proposal would have spawn time passed and hence needs the mocks but the client will not be - // created because `chain6` is an Opt In chain and has no validator opted in - expectedCalls = append(expectedCalls, testkeeper.GetMocksForCreateConsumerClient(ctx, &mocks, "chain6", clienttypes.NewHeight(3, 4))...) - - gomock.InOrder(expectedCalls...) - - for _, prop := range pendingProps { - providerKeeper.SetPendingConsumerAdditionProp(ctx, prop) - } - - // opt in a sample validator so the chain's proposal can successfully execute - validator := cryptotestutil.NewCryptoIdentityFromIntSeed(0).SDKStakingValidator() - consAddr, _ := validator.GetConsAddr() - testkeeper.SetupMocksForLastBondedValidatorsExpectation(mocks.MockStakingKeeper, 1, []stakingtypes.Validator{validator}, -1) // -1 to allow any number of calls - - valAddr, _ := sdk.ValAddressFromBech32(validator.GetOperator()) - mocks.MockStakingKeeper.EXPECT().GetLastValidatorPower(gomock.Any(), valAddr).Return(int64(1), nil).AnyTimes() - - // for the validator, expect a call to GetValidatorByConsAddr with its consensus address - mocks.MockStakingKeeper.EXPECT().GetValidatorByConsAddr(gomock.Any(), consAddr).Return(validator, nil).AnyTimes() - - providerKeeper.SetOptedIn(ctx, pendingProps[4].ChainId, providertypes.NewProviderConsAddress(consAddr)) - - providerKeeper.BeginBlockInit(ctx) - - // first proposal is not pending anymore because its spawn time already passed and was executed - _, found := providerKeeper.GetPendingConsumerAdditionProp( - ctx, pendingProps[0].SpawnTime, pendingProps[0].ChainId) - require.False(t, found) - // first proposal was successfully executed and hence consumer genesis was created - _, found = providerKeeper.GetConsumerGenesis(ctx, pendingProps[0].ChainId) - require.True(t, found) - - // second proposal is not pending anymore because its spawn time already passed and was executed - _, found = providerKeeper.GetPendingConsumerAdditionProp( - ctx, pendingProps[1].SpawnTime, pendingProps[1].ChainId) - require.False(t, found) - // second proposal was successfully executed and hence consumer genesis was created - _, found = providerKeeper.GetConsumerGenesis(ctx, pendingProps[1].ChainId) - require.True(t, found) - - // third proposal is still stored as pending because its spawn time has not passed - _, found = providerKeeper.GetPendingConsumerAdditionProp( - ctx, pendingProps[2].SpawnTime, pendingProps[2].ChainId) - require.True(t, found) - // because the proposal is still pending, no consumer genesis was created - _, found = providerKeeper.GetConsumerGenesis(ctx, pendingProps[2].ChainId) - require.False(t, found) - - // check that the invalid proposals were dropped - _, found = providerKeeper.GetPendingConsumerAdditionProp( - ctx, pendingProps[3].SpawnTime, pendingProps[3].ChainId) - require.False(t, found) - // Note that we do not check that `GetConsumerGenesis(ctx, pendingProps[3].ChainId)` returns `false` here because - // `pendingProps[3]` is an invalid proposal due to the chain id already existing so the consumer genesis also exists - - // fifth proposal corresponds to an Opt-In chain with one opted-in validator and hence the proposal gets - // successfully executed - _, found = providerKeeper.GetPendingConsumerAdditionProp( - ctx, pendingProps[4].SpawnTime, pendingProps[4].ChainId) - require.False(t, found) - // fifth proposal was successfully executed and hence consumer genesis was created - _, found = providerKeeper.GetConsumerGenesis(ctx, pendingProps[4].ChainId) - require.True(t, found) - - // sixth proposal corresponds to an Opt-In chain with no opted-in validators and hence the - // proposal is not successful - _, found = providerKeeper.GetPendingConsumerAdditionProp( - ctx, pendingProps[5].SpawnTime, pendingProps[5].ChainId) - // the proposal was dropped and deleted - require.False(t, found) - // no consumer genesis is created - _, found = providerKeeper.GetConsumerGenesis(ctx, pendingProps[5].ChainId) - require.False(t, found) - // no consumer client is associated with this chain - _, found = providerKeeper.GetConsumerClientId(ctx, pendingProps[5].ChainId) - require.False(t, found) - // no fields should be set for this (check some of them) - _, found = providerKeeper.GetTopN(ctx, pendingProps[5].ChainId) - require.False(t, found) - _, found = providerKeeper.GetValidatorsPowerCap(ctx, pendingProps[5].ChainId) - require.False(t, found) - _, found = providerKeeper.GetValidatorSetCap(ctx, pendingProps[5].ChainId) - require.False(t, found) - - // test that Top N is set correctly - require.True(t, providerKeeper.IsTopN(ctx, "chain1")) - topN, found := providerKeeper.GetTopN(ctx, "chain1") - require.True(t, found) - require.Equal(t, uint32(50), topN) - - require.True(t, providerKeeper.IsOptIn(ctx, "chain4")) -} - -// TestBeginBlockCCR tests BeginBlockCCR against the spec. -// -// See: https://github.com/cosmos/ibc/blob/main/spec/app/ics-028-cross-chain-validation/methods.md#ccv-pcf-bblock-ccr1 -// Spec tag: [CCV-PCF-BBLOCK-CCR.1] -func TestBeginBlockCCR(t *testing.T) { - now := time.Now().UTC() - - keeperParams := testkeeper.NewInMemKeeperParams(t) - providerKeeper, ctx, ctrl, mocks := testkeeper.GetProviderKeeperAndCtx(t, keeperParams) - providerKeeper.SetParams(ctx, providertypes.DefaultParams()) - defer ctrl.Finish() - ctx = ctx.WithBlockTime(now) - - pendingProps := []*providertypes.ConsumerRemovalProposal{ - providertypes.NewConsumerRemovalProposal( - "title", "description", "chain1", now.Add(-time.Hour).UTC(), - ).(*providertypes.ConsumerRemovalProposal), - providertypes.NewConsumerRemovalProposal( - "title", "description", "chain2", now, - ).(*providertypes.ConsumerRemovalProposal), - providertypes.NewConsumerRemovalProposal( - "title", "description", "chain3", now.Add(time.Hour).UTC(), - ).(*providertypes.ConsumerRemovalProposal), - } - - // - // Mock expectations - // - expectations := []*gomock.Call{} - for _, prop := range pendingProps { - // A consumer chain is setup corresponding to each prop, making these mocks necessary - testkeeper.SetupMocksForLastBondedValidatorsExpectation(mocks.MockStakingKeeper, 0, []stakingtypes.Validator{}, 1) - expectations = append(expectations, testkeeper.GetMocksForCreateConsumerClient(ctx, &mocks, - prop.ChainId, clienttypes.NewHeight(2, 3))...) - expectations = append(expectations, testkeeper.GetMocksForSetConsumerChain(ctx, &mocks, prop.ChainId)...) - } - // Only first two consumer chains should be stopped - expectations = append(expectations, testkeeper.GetMocksForStopConsumerChainWithCloseChannel(ctx, &mocks)...) - expectations = append(expectations, testkeeper.GetMocksForStopConsumerChainWithCloseChannel(ctx, &mocks)...) - - gomock.InOrder(expectations...) - - // - // Remaining setup - // - for _, prop := range pendingProps { - // Setup a valid consumer chain for each prop - additionProp := testkeeper.GetTestConsumerAdditionProp() - additionProp.ChainId = prop.ChainId - additionProp.InitialHeight = clienttypes.NewHeight(2, 3) - - err := providerKeeper.CreateConsumerClient(ctx, additionProp) - require.NoError(t, err) - err = providerKeeper.SetConsumerChain(ctx, "channelID") - require.NoError(t, err) - - // Set removal props for all consumer chains - providerKeeper.SetPendingConsumerRemovalProp(ctx, prop) - } - - // Add an invalid prop to the store with an non-existing chain id - invalidProp := providertypes.NewConsumerRemovalProposal( - "title", "description", "chain4", now.Add(-time.Hour).UTC(), - ).(*providertypes.ConsumerRemovalProposal) - providerKeeper.SetPendingConsumerRemovalProp(ctx, invalidProp) - - // - // Test execution - // - - providerKeeper.BeginBlockCCR(ctx) - - // Only the 3rd (final) proposal is still stored as pending - found := providerKeeper.PendingConsumerRemovalPropExists( - ctx, pendingProps[0].ChainId, pendingProps[0].StopTime) - require.False(t, found) - found = providerKeeper.PendingConsumerRemovalPropExists( - ctx, pendingProps[1].ChainId, pendingProps[1].StopTime) - require.False(t, found) - found = providerKeeper.PendingConsumerRemovalPropExists( - ctx, pendingProps[2].ChainId, pendingProps[2].StopTime) - require.True(t, found) - found = providerKeeper.PendingConsumerRemovalPropExists( - ctx, invalidProp.ChainId, invalidProp.StopTime) - require.False(t, found) -} diff --git a/x/ccv/provider/keeper/relay.go b/x/ccv/provider/keeper/relay.go index b008d79d54..8fc0c08500 100644 --- a/x/ccv/provider/keeper/relay.go +++ b/x/ccv/provider/keeper/relay.go @@ -15,7 +15,6 @@ import ( abci "github.com/cometbft/cometbft/abci/types" - "github.com/cosmos/interchain-security/v5/x/ccv/provider/types" providertypes "github.com/cosmos/interchain-security/v5/x/ccv/provider/types" ccv "github.com/cosmos/interchain-security/v5/x/ccv/types" ) @@ -30,9 +29,8 @@ func (k Keeper) OnAcknowledgementPacket(ctx sdk.Context, packet channeltypes.Pac "channelID", packet.SourceChannel, "error", err, ) - if chainID, ok := k.GetChannelToChain(ctx, packet.SourceChannel); ok { - // stop consumer chain and release unbonding - return k.StopConsumerChain(ctx, chainID, false) + if consumerId, ok := k.GetChannelIdToConsumerId(ctx, packet.SourceChannel); ok { + return k.StopAndPrepareForConsumerRemoval(ctx, consumerId) } return errorsmod.Wrapf(providertypes.ErrUnknownConsumerChannelId, "recv ErrorAcknowledgement on unknown channel %s", packet.SourceChannel) } @@ -42,7 +40,7 @@ func (k Keeper) OnAcknowledgementPacket(ctx sdk.Context, packet channeltypes.Pac // OnTimeoutPacket aborts the transaction if no chain exists for the destination channel, // otherwise it stops the chain func (k Keeper) OnTimeoutPacket(ctx sdk.Context, packet channeltypes.Packet) error { - chainID, found := k.GetChannelToChain(ctx, packet.SourceChannel) + consumerId, found := k.GetChannelIdToConsumerId(ctx, packet.SourceChannel) if !found { k.Logger(ctx).Error("packet timeout, unknown channel:", "channelID", packet.SourceChannel) // abort transaction @@ -51,9 +49,8 @@ func (k Keeper) OnTimeoutPacket(ctx sdk.Context, packet channeltypes.Packet) err packet.SourceChannel, ) } - k.Logger(ctx).Info("packet timeout, removing the consumer:", "chainID", chainID) - // stop consumer chain and release unbondings - return k.StopConsumerChain(ctx, chainID, false) + k.Logger(ctx).Info("packet timeout, deleting the consumer:", "consumerId", consumerId) + return k.StopAndPrepareForConsumerRemoval(ctx, consumerId) } // EndBlockVSU contains the EndBlock logic needed for @@ -102,7 +99,7 @@ func (k Keeper) ProviderValidatorUpdates(ctx sdk.Context) ([]abci.ValidatorUpdat return []abci.ValidatorUpdate{}, fmt.Errorf("getting last provider consensus validator set: %w", err) } - nextValidators := []types.ConsensusValidator{} + nextValidators := []providertypes.ConsensusValidator{} maxValidators := k.GetMaxProviderConsensusValidators(ctx) // avoid out of range errors by bounding the max validators to the number of bonded validators if maxValidators > int64(len(bondedValidators)) { @@ -138,16 +135,23 @@ func (k Keeper) BlocksUntilNextEpoch(ctx sdk.Context) int64 { } } -// SendVSCPackets iterates over all registered consumers and sends pending -// VSC packets to the chains with established CCV channels. +// SendVSCPackets iterates over all consumers chains with created IBC clients +// and sends pending VSC packets to the chains with established CCV channels. // If the CCV channel is not established for a consumer chain, // the updates will remain queued until the channel is established +// +// TODO (mpoke): iterate only over consumers with established channel -- GetAllChannelToConsumers func (k Keeper) SendVSCPackets(ctx sdk.Context) error { - for _, chainID := range k.GetAllRegisteredConsumerChainIDs(ctx) { + for _, consumerId := range k.GetAllConsumersWithIBCClients(ctx) { + if k.GetConsumerPhase(ctx, consumerId) != providertypes.CONSUMER_PHASE_LAUNCHED { + // only send VSCPackets to launched chains + continue + } + // check if CCV channel is established and send - if channelID, found := k.GetChainToChannel(ctx, chainID); found { - if err := k.SendVSCPacketsToChain(ctx, chainID, channelID); err != nil { - return fmt.Errorf("sending VSCPacket to consumer, chainID(%s): %w", chainID, err) + if channelID, found := k.GetConsumerIdToChannelId(ctx, consumerId); found { + if err := k.SendVSCPacketsToChain(ctx, consumerId, channelID); err != nil { + return fmt.Errorf("sending VSCPacket to consumer, consumerId(%s): %w", consumerId, err) } } } @@ -155,15 +159,15 @@ func (k Keeper) SendVSCPackets(ctx sdk.Context) error { } // SendVSCPacketsToChain sends all queued VSC packets to the specified chain -func (k Keeper) SendVSCPacketsToChain(ctx sdk.Context, chainID, channelID string) error { - pendingPackets := k.GetPendingVSCPackets(ctx, chainID) +func (k Keeper) SendVSCPacketsToChain(ctx sdk.Context, consumerId, channelId string) error { + pendingPackets := k.GetPendingVSCPackets(ctx, consumerId) for _, data := range pendingPackets { // send packet over IBC err := ccv.SendIBCPacket( ctx, k.scopedKeeper, k.channelKeeper, - channelID, // source channel id + channelId, // source channel id ccv.ProviderPortID, // source port id data.GetBytes(), k.GetCCVTimeoutPeriod(ctx), @@ -173,25 +177,32 @@ func (k Keeper) SendVSCPacketsToChain(ctx sdk.Context, chainID, channelID string // IBC client is expired! // leave the packet data stored to be sent once the client is upgraded // the client cannot expire during iteration (in the middle of a block) - k.Logger(ctx).Info("IBC client is expired, cannot send VSC, leaving packet data stored:", "chainID", chainID, "vscid", data.ValsetUpdateId) + k.Logger(ctx).Info("IBC client is expired, cannot send VSC, leaving packet data stored:", + "consumerId", consumerId, + "vscid", data.ValsetUpdateId, + ) return nil } // Not able to send packet over IBC! - k.Logger(ctx).Error("cannot send VSC, removing consumer:", "chainID", chainID, "vscid", data.ValsetUpdateId, "err", err.Error()) - // If this happens, most likely the consumer is malicious; remove it - err := k.StopConsumerChain(ctx, chainID, true) + k.Logger(ctx).Error("cannot send VSC, removing consumer:", "consumerId", consumerId, "vscid", data.ValsetUpdateId, "err", err.Error()) + + err := k.StopAndPrepareForConsumerRemoval(ctx, consumerId) if err != nil { - return fmt.Errorf("stopping consumer, chainID(%s): %w", chainID, err) + k.Logger(ctx).Info("consumer chain failed to stop:", "consumerId", consumerId, "error", err.Error()) + // return fmt.Errorf("stopping consumer, consumerId(%s): %w", consumerId, err) } return nil } } - k.DeletePendingVSCPackets(ctx, chainID) + k.DeletePendingVSCPackets(ctx, consumerId) return nil } -// QueueVSCPackets queues latest validator updates for every registered consumer chain +// QueueVSCPackets queues latest validator updates for every consumer chain +// with the IBC client created. +// +// TODO (mpoke): iterate only over consumers with established channel -- GetAllChannelToConsumers func (k Keeper) QueueVSCPackets(ctx sdk.Context) error { valUpdateID := k.GetValidatorSetUpdateId(ctx) // current valset update ID @@ -207,39 +218,48 @@ func (k Keeper) QueueVSCPackets(ctx sdk.Context) error { return fmt.Errorf("getting provider active validators: %w", err) } - for _, chainID := range k.GetAllRegisteredConsumerChainIDs(ctx) { - currentValidators, err := k.GetConsumerValSet(ctx, chainID) + for _, consumerId := range k.GetAllConsumersWithIBCClients(ctx) { + if k.GetConsumerPhase(ctx, consumerId) != providertypes.CONSUMER_PHASE_LAUNCHED { + // only queue VSCPackets to launched chains + continue + } + + currentValidators, err := k.GetConsumerValSet(ctx, consumerId) + if err != nil { + return fmt.Errorf("getting consumer validators, consumerId(%s): %w", consumerId, err) + } + powerShapingParameters, err := k.GetConsumerPowerShapingParameters(ctx, consumerId) if err != nil { - return fmt.Errorf("getting consumer validators, chainID(%s): %w", chainID, err) + return fmt.Errorf("getting consumer power shaping parameters, consumerId(%s): %w", consumerId, err) } - topN, _ := k.GetTopN(ctx, chainID) - if topN > 0 { + minPower := int64(0) + if powerShapingParameters.Top_N > 0 { // in a Top-N chain, we automatically opt in all validators that belong to the top N // of the active validators - minPower, err := k.ComputeMinPowerInTopN(ctx, activeValidators, topN) + minPower, err = k.ComputeMinPowerInTopN(ctx, activeValidators, powerShapingParameters.Top_N) if err != nil { - return fmt.Errorf("computing min power to opt in, chainID(%s): %w", chainID, err) + return fmt.Errorf("computing min power to opt in, consumerId(%s): %w", consumerId, err) } // set the minimal power of validators in the top N in the store - k.SetMinimumPowerInTopN(ctx, chainID, minPower) + k.SetMinimumPowerInTopN(ctx, consumerId, minPower) - k.OptInTopNValidators(ctx, chainID, activeValidators, minPower) + k.OptInTopNValidators(ctx, consumerId, activeValidators, minPower) } - nextValidators := k.ComputeNextValidators(ctx, chainID, bondedValidators) + nextValidators := k.ComputeNextValidators(ctx, consumerId, bondedValidators, powerShapingParameters, minPower) valUpdates := DiffValidators(currentValidators, nextValidators) - k.SetConsumerValSet(ctx, chainID, nextValidators) + k.SetConsumerValSet(ctx, consumerId, nextValidators) // check whether there are changes in the validator set if len(valUpdates) != 0 { // construct validator set change packet data - packet := ccv.NewValidatorSetChangePacketData(valUpdates, valUpdateID, k.ConsumeSlashAcks(ctx, chainID)) - k.AppendPendingVSCPackets(ctx, chainID, packet) + packet := ccv.NewValidatorSetChangePacketData(valUpdates, valUpdateID, k.ConsumeSlashAcks(ctx, consumerId)) + k.AppendPendingVSCPackets(ctx, consumerId, packet) k.Logger(ctx).Info("VSCPacket enqueued:", - "chainID", chainID, + "consumerId", consumerId, "vscID", valUpdateID, "len updates", len(valUpdates), ) @@ -276,8 +296,8 @@ func (k Keeper) EndBlockCIS(ctx sdk.Context) { k.Logger(ctx).Debug("vscID was mapped to block height", "vscID", valUpdateID, "height", blockHeight) // prune previous consumer validator addresses that are no longer needed - for _, chainID := range k.GetAllRegisteredConsumerChainIDs(ctx) { - k.PruneKeyAssignments(ctx, chainID) + for _, consumerId := range k.GetAllConsumersWithIBCClients(ctx) { + k.PruneKeyAssignments(ctx, consumerId) } } @@ -289,7 +309,7 @@ func (k Keeper) OnRecvSlashPacket( data ccv.SlashPacketData, ) (ccv.PacketAckResult, error) { // check that the channel is established, panic if not - chainID, found := k.GetChannelToChain(ctx, packet.DestinationChannel) + consumerId, found := k.GetChannelIdToConsumerId(ctx, packet.DestinationChannel) if !found { // SlashPacket packet was sent on a channel different than any of the established CCV channels; // this should never happen @@ -304,10 +324,10 @@ func (k Keeper) OnRecvSlashPacket( return nil, errorsmod.Wrapf(err, "error validating SlashPacket data") } - if err := k.ValidateSlashPacket(ctx, chainID, packet, data); err != nil { + if err := k.ValidateSlashPacket(ctx, consumerId, packet, data); err != nil { k.Logger(ctx).Error("invalid slash packet", "error", err.Error(), - "chainID", chainID, + "consumerId", consumerId, "consumer cons addr", sdk.ConsAddress(data.Validator.Address).String(), "vscID", data.ValsetUpdateId, "infractionType", data.Infraction, @@ -318,15 +338,15 @@ func (k Keeper) OnRecvSlashPacket( // The slash packet validator address may be known only on the consumer chain, // in this case, it must be mapped back to the consensus address on the provider chain consumerConsAddr := providertypes.NewConsumerConsAddress(data.Validator.Address) - providerConsAddr := k.GetProviderAddrFromConsumerAddr(ctx, chainID, consumerConsAddr) + providerConsAddr := k.GetProviderAddrFromConsumerAddr(ctx, consumerId, consumerConsAddr) if data.Infraction == stakingtypes.Infraction_INFRACTION_DOUBLE_SIGN { // getMappedInfractionHeight is already checked in ValidateSlashPacket - infractionHeight, _ := k.getMappedInfractionHeight(ctx, chainID, data.ValsetUpdateId) + infractionHeight, _ := k.getMappedInfractionHeight(ctx, consumerId, data.ValsetUpdateId) k.SetSlashLog(ctx, providerConsAddr) k.Logger(ctx).Info("SlashPacket received for double-signing", - "chainID", chainID, + "consumerId", consumerId, "consumer cons addr", consumerConsAddr.String(), "provider cons addr", providerConsAddr.String(), "vscID", data.ValsetUpdateId, @@ -339,11 +359,11 @@ func (k Keeper) OnRecvSlashPacket( } // Check that the validator belongs to the consumer chain valset - if !k.IsConsumerValidator(ctx, chainID, providerConsAddr) { + if !k.IsConsumerValidator(ctx, consumerId, providerConsAddr) { k.Logger(ctx).Error("cannot jail validator %s that does not belong to consumer %s valset", - providerConsAddr.String(), chainID) + providerConsAddr.String(), consumerId) // drop packet but return a slash ack so that the consumer can send another slash packet - k.AppendSlashAck(ctx, chainID, consumerConsAddr.String()) + k.AppendSlashAck(ctx, consumerId, consumerConsAddr.String()) return ccv.SlashPacketHandledResult, nil } @@ -352,7 +372,7 @@ func (k Keeper) OnRecvSlashPacket( // Return bounce ack if meter is negative in value if meter.IsNegative() { k.Logger(ctx).Info("SlashPacket received, but meter is negative. Packet will be bounced", - "chainID", chainID, + "consumerId", consumerId, "consumer cons addr", consumerConsAddr.String(), "provider cons addr", providerConsAddr.String(), "vscID", data.ValsetUpdateId, @@ -366,10 +386,10 @@ func (k Keeper) OnRecvSlashPacket( meter = meter.Sub(k.GetEffectiveValPower(ctx, providerConsAddr)) k.SetSlashMeter(ctx, meter) - k.HandleSlashPacket(ctx, chainID, data) + k.HandleSlashPacket(ctx, consumerId, data) k.Logger(ctx).Info("slash packet received and handled", - "chainID", chainID, + "consumerId", consumerId, "consumer cons addr", consumerConsAddr.String(), "provider cons addr", providerConsAddr.String(), "vscID", data.ValsetUpdateId, @@ -383,14 +403,14 @@ func (k Keeper) OnRecvSlashPacket( // ValidateSlashPacket validates a recv slash packet before it is // handled or persisted in store. An error is returned if the packet is invalid, // and an error ack should be relayed to the sender. -func (k Keeper) ValidateSlashPacket(ctx sdk.Context, chainID string, +func (k Keeper) ValidateSlashPacket(ctx sdk.Context, consumerId string, packet channeltypes.Packet, data ccv.SlashPacketData, ) error { - _, found := k.getMappedInfractionHeight(ctx, chainID, data.ValsetUpdateId) + _, found := k.getMappedInfractionHeight(ctx, consumerId, data.ValsetUpdateId) // return error if we cannot find infraction height matching the validator update id if !found { return fmt.Errorf("cannot find infraction height matching "+ - "the validator update id %d for chain %s", data.ValsetUpdateId, chainID) + "the validator update id %d for chain %s", data.ValsetUpdateId, consumerId) } return nil @@ -398,13 +418,13 @@ func (k Keeper) ValidateSlashPacket(ctx sdk.Context, chainID string, // HandleSlashPacket potentially jails a misbehaving validator for a downtime infraction. // This method should NEVER be called with a double-sign infraction. -func (k Keeper) HandleSlashPacket(ctx sdk.Context, chainID string, data ccv.SlashPacketData) { +func (k Keeper) HandleSlashPacket(ctx sdk.Context, consumerId string, data ccv.SlashPacketData) { consumerConsAddr := providertypes.NewConsumerConsAddress(data.Validator.Address) // Obtain provider chain consensus address using the consumer chain consensus address - providerConsAddr := k.GetProviderAddrFromConsumerAddr(ctx, chainID, consumerConsAddr) + providerConsAddr := k.GetProviderAddrFromConsumerAddr(ctx, consumerId, consumerConsAddr) k.Logger(ctx).Debug("HandleSlashPacket", - "chainID", chainID, + "consumerId", consumerId, "consumer cons addr", consumerConsAddr.String(), "provider cons addr", providerConsAddr.String(), "vscID", data.ValsetUpdateId, @@ -439,7 +459,7 @@ func (k Keeper) HandleSlashPacket(ctx sdk.Context, chainID string, data ccv.Slas return } - infractionHeight, found := k.getMappedInfractionHeight(ctx, chainID, data.ValsetUpdateId) + infractionHeight, found := k.getMappedInfractionHeight(ctx, consumerId, data.ValsetUpdateId) if !found { k.Logger(ctx).Error( "HandleSlashPacket - infraction height not found. But was found during slash packet validation", @@ -452,9 +472,9 @@ func (k Keeper) HandleSlashPacket(ctx sdk.Context, chainID string, data ccv.Slas // Note: the SlashPacket is for downtime infraction, as SlashPackets // for double-signing infractions are already dropped when received - // append the validator address to the slash ack for its chain id + // append the validator address to the slash ack for its consumer id // TODO: consumer cons address should be accepted here - k.AppendSlashAck(ctx, chainID, consumerConsAddr.String()) + k.AppendSlashAck(ctx, consumerId, consumerConsAddr.String()) // jail validator if !validator.IsJailed() { @@ -489,12 +509,12 @@ func (k Keeper) HandleSlashPacket(ctx sdk.Context, chainID string, data ccv.Slas ) } -// getMappedInfractionHeight gets the infraction height mapped from val set ID for the given chain ID +// getMappedInfractionHeight gets the infraction height mapped from val set ID for the given consumer id func (k Keeper) getMappedInfractionHeight(ctx sdk.Context, - chainID string, valsetUpdateID uint64, + consumerId string, valsetUpdateID uint64, ) (height uint64, found bool) { if valsetUpdateID == 0 { - return k.GetInitChainHeight(ctx, chainID) + return k.GetInitChainHeight(ctx, consumerId) } else { return k.GetValsetUpdateBlockHeight(ctx, valsetUpdateID) } diff --git a/x/ccv/provider/keeper/relay_test.go b/x/ccv/provider/keeper/relay_test.go index ad427ca6c7..753700214b 100644 --- a/x/ccv/provider/keeper/relay_test.go +++ b/x/ccv/provider/keeper/relay_test.go @@ -4,8 +4,10 @@ import ( "sort" "strings" "testing" + "time" "cosmossdk.io/math" + capabilitytypes "github.com/cosmos/ibc-go/modules/capability/types" clienttypes "github.com/cosmos/ibc-go/v8/modules/core/02-client/types" channeltypes "github.com/cosmos/ibc-go/v8/modules/core/04-channel/types" ibctesting "github.com/cosmos/ibc-go/v8/testing" @@ -97,42 +99,47 @@ func TestQueueVSCPacketsDoesNotResetConsumerValidatorsHeights(t *testing.T) { providerKeeper.SetParams(ctx, providertypes.DefaultParams()) // mock 2 bonded validators - valA := createStakingValidator(ctx, mocks, 1, 1, 1) + valA := createStakingValidator(ctx, mocks, 1, 1) valAConsAddr, _ := valA.GetConsAddr() valAPubKey, _ := valA.TmConsPublicKey() mocks.MockStakingKeeper.EXPECT().GetValidatorByConsAddr(ctx, valAConsAddr).Return(valA, nil).AnyTimes() - valB := createStakingValidator(ctx, mocks, 2, 2, 2) + valB := createStakingValidator(ctx, mocks, 2, 2) valBConsAddr, _ := valB.GetConsAddr() mocks.MockStakingKeeper.EXPECT().GetValidatorByConsAddr(ctx, valBConsAddr).Return(valB, nil).AnyTimes() testkeeper.SetupMocksForLastBondedValidatorsExpectation(mocks.MockStakingKeeper, 2, []stakingtypes.Validator{valA, valB}, -1) - // set a consumer client, so we have a consumer chain (i.e., `k.GetAllConsumerChains(ctx)` is non empty) - providerKeeper.SetConsumerClientId(ctx, "chainID", "clientID") + // set a consumer client id and its phase, so we have a consumer chain (i.e., `GetAllConsumersWithIBCClients` is non-empty) + providerKeeper.SetConsumerClientId(ctx, "consumerId", "clientID") + providerKeeper.SetConsumerPhase(ctx, "consumerId", providertypes.CONSUMER_PHASE_LAUNCHED) // opt in validator A and set as a consumer validator - providerKeeper.SetOptedIn(ctx, "chainID", providertypes.NewProviderConsAddress(valAConsAddr)) + providerKeeper.SetOptedIn(ctx, "consumerId", providertypes.NewProviderConsAddress(valAConsAddr)) consumerValidatorA := providertypes.ConsensusValidator{ ProviderConsAddr: valAConsAddr, Power: 1, PublicKey: &valAPubKey, JoinHeight: 123456789, } - providerKeeper.SetConsumerValidator(ctx, "chainID", consumerValidatorA) + providerKeeper.SetConsumerValidator(ctx, "consumerId", consumerValidatorA) // Opt in validator B. Note that validator B is not a consumer validator and hence would become a consumer // validator for the first time after the `QueueVSCPackets` call. - providerKeeper.SetOptedIn(ctx, "chainID", providertypes.NewProviderConsAddress(valBConsAddr)) + providerKeeper.SetOptedIn(ctx, "consumerId", providertypes.NewProviderConsAddress(valBConsAddr)) - err := providerKeeper.QueueVSCPackets(ctx) + // set power shaping params + err := providerKeeper.SetConsumerPowerShapingParameters(ctx, "consumerId", providertypes.PowerShapingParameters{}) + require.NoError(t, err) + + err = providerKeeper.QueueVSCPackets(ctx) require.NoError(t, err) // the height of consumer validator A should not be modified because A was already a consumer validator - cv, _ := providerKeeper.GetConsumerValidator(ctx, "chainID", providertypes.NewProviderConsAddress(valAConsAddr)) + cv, _ := providerKeeper.GetConsumerValidator(ctx, "consumerId", providertypes.NewProviderConsAddress(valAConsAddr)) require.Equal(t, consumerValidatorA.JoinHeight, cv.JoinHeight, "the consumer validator's height was erroneously modified") // the height of consumer validator B is set to be the same as the one of the current chain height because this // consumer validator becomes a consumer validator for the first time (i.e., was not a consumer validator in the previous epoch) - cv, _ = providerKeeper.GetConsumerValidator(ctx, "chainID", providertypes.NewProviderConsAddress(valBConsAddr)) + cv, _ = providerKeeper.GetConsumerValidator(ctx, "consumerId", providertypes.NewProviderConsAddress(valBConsAddr)) require.Equal(t, chainHeight, cv.JoinHeight, "the consumer validator's height was not correctly set") } @@ -143,8 +150,8 @@ func TestOnRecvDowntimeSlashPacket(t *testing.T) { providerKeeper.SetParams(ctx, providertypes.DefaultParams()) // Set channel to chain (faking multiple established channels) - providerKeeper.SetChannelToChain(ctx, "channel-1", "chain-1") - providerKeeper.SetChannelToChain(ctx, "channel-2", "chain-2") + providerKeeper.SetChannelToConsumerId(ctx, "channel-1", "chain-1") + providerKeeper.SetChannelToConsumerId(ctx, "channel-2", "chain-2") // Generate a new slash packet data instance with double sign infraction type packetData := testkeeper.GetNewSlashPacketData() @@ -216,8 +223,8 @@ func TestOnRecvDoubleSignSlashPacket(t *testing.T) { providerKeeper.SetParams(ctx, providertypes.DefaultParams()) // Set channel to chain (faking multiple established channels) - providerKeeper.SetChannelToChain(ctx, "channel-1", "chain-1") - providerKeeper.SetChannelToChain(ctx, "channel-2", "chain-2") + providerKeeper.SetChannelToConsumerId(ctx, "channel-1", "chain-1") + providerKeeper.SetChannelToConsumerId(ctx, "channel-2", "chain-2") // Generate a new slash packet data instance with double sign infraction type packetData := testkeeper.GetNewSlashPacketData() @@ -298,7 +305,7 @@ func TestValidateSlashPacket(t *testing.T) { packet := channeltypes.Packet{DestinationChannel: "channel-9"} // Pseudo setup ccv channel for channel ID specified in packet. - providerKeeper.SetChannelToChain(ctx, "channel-9", "consumer-chain-id") + providerKeeper.SetChannelToConsumerId(ctx, "channel-9", "consumer-chain-id") // Setup init chain height for consumer (allowing 0 vscID to be valid). providerKeeper.SetInitChainHeight(ctx, "consumer-chain-id", uint64(89)) @@ -483,10 +490,10 @@ func TestSendVSCPacketsToChainFailure(t *testing.T) { providerKeeper.SetParams(ctx, providertypes.DefaultParams()) // Append mocks for full consumer setup - mockCalls := testkeeper.GetMocksForSetConsumerChain(ctx, &mocks, "consumerChainID") + mockCalls := testkeeper.GetMocksForSetConsumerChain(ctx, &mocks, "consumerId") // Set 3 pending vsc packets - providerKeeper.AppendPendingVSCPackets(ctx, "consumerChainID", []ccv.ValidatorSetChangePacketData{{}, {}, {}}...) + providerKeeper.AppendPendingVSCPackets(ctx, "consumerId", []ccv.ValidatorSetChangePacketData{{}, {}, {}}...) // append mocks for the channel keeper to return an error mockCalls = append(mockCalls, @@ -494,23 +501,36 @@ func TestSendVSCPacketsToChainFailure(t *testing.T) { "CCVChannelID").Return(channeltypes.Channel{}, false).Times(1), ) - // Append mocks for expected call to StopConsumerChain - mockCalls = append(mockCalls, testkeeper.GetMocksForStopConsumerChainWithCloseChannel(ctx, &mocks)...) + // Append mocks for expected call to DeleteConsumerChain + mockCalls = append(mockCalls, testkeeper.GetMocksForDeleteConsumerChain(ctx, &mocks)...) // Assert mock calls hit gomock.InOrder(mockCalls...) // Execute setup + providerKeeper.SetConsumerClientId(ctx, "consumerId", "clientID") err := providerKeeper.SetConsumerChain(ctx, "channelID") require.NoError(t, err) - providerKeeper.SetConsumerClientId(ctx, "consumerChainID", "clientID") - // No error should occur, StopConsumerChain should be called - err = providerKeeper.SendVSCPacketsToChain(ctx, "consumerChainID", "CCVChannelID") + unbondingTime := 123 * time.Second + mocks.MockStakingKeeper.EXPECT().UnbondingTime(gomock.Any()).Return(unbondingTime, nil).AnyTimes() + + // No error should occur, DeleteConsumerChain should be called + err = providerKeeper.SendVSCPacketsToChain(ctx, "consumerId", "CCVChannelID") + require.NoError(t, err) + + // Verify the chain is about to be deleted + removalTime, err := providerKeeper.GetConsumerRemovalTime(ctx, "consumerId") require.NoError(t, err) + require.Equal(t, ctx.BlockTime().Add(unbondingTime), removalTime) - // Pending VSC packets should be deleted in StopConsumerChain - require.Empty(t, providerKeeper.GetPendingVSCPackets(ctx, "consumerChainID")) + // Increase the block time by `unbondingTime` so the chain actually gets deleted + ctx = ctx.WithBlockTime(ctx.BlockTime().Add(unbondingTime)) + providerKeeper.BeginBlockRemoveConsumers(ctx) + + // Pending VSC packets should be deleted in DeleteConsumerChain + require.Empty(t, providerKeeper.GetPendingVSCPackets(ctx, "consumerId")) + require.Equal(t, providertypes.CONSUMER_PHASE_DELETED, providerKeeper.GetConsumerPhase(ctx, "consumerId")) } // TestOnTimeoutPacketWithNoChainFound tests the `OnTimeoutPacket` method fails when no chain is found @@ -519,7 +539,7 @@ func TestOnTimeoutPacketWithNoChainFound(t *testing.T) { providerKeeper, ctx, ctrl, _ := testkeeper.GetProviderKeeperAndCtx(t, testkeeper.NewInMemKeeperParams(t)) defer ctrl.Finish() - // We do not `SetChannelToChain` for "channelID" and therefore `OnTimeoutPacket` fails + // We do not `SetChannelToConsumerId` for "channelID" and therefore `OnTimeoutPacket` fails packet := channeltypes.Packet{ SourceChannel: "channelID", } @@ -535,15 +555,30 @@ func TestOnTimeoutPacketStopsChain(t *testing.T) { defer ctrl.Finish() providerKeeper.SetParams(ctx, providertypes.DefaultParams()) - testkeeper.SetupForStoppingConsumerChain(t, ctx, &providerKeeper, mocks) + testkeeper.SetupForDeleteConsumerChain(t, ctx, &providerKeeper, mocks, "consumerId") + mocks.MockChannelKeeper.EXPECT().GetChannel(gomock.Any(), ccv.ProviderPortID, "channelID").Return( + channeltypes.Channel{State: channeltypes.OPEN, + ConnectionHops: []string{"connectionID"}, + }, true, + ).Times(1) + dummyCap := &capabilitytypes.Capability{} + mocks.MockScopedKeeper.EXPECT().GetCapability(gomock.Any(), gomock.Any()).Return(dummyCap, true).Times(1) + mocks.MockChannelKeeper.EXPECT().ChanCloseInit(gomock.Any(), ccv.ProviderPortID, "channelID", dummyCap).Times(1) + + unbondingTime := 123 * time.Second + mocks.MockStakingKeeper.EXPECT().UnbondingTime(gomock.Any()).Return(unbondingTime, nil).AnyTimes() packet := channeltypes.Packet{ SourceChannel: "channelID", } err := providerKeeper.OnTimeoutPacket(ctx, packet) - - testkeeper.TestProviderStateIsCleanedAfterConsumerChainIsStopped(t, ctx, providerKeeper, "chainID", "channelID") require.NoError(t, err) + + // increase the block time by `unbondingTime` so the chain actually gets deleted + ctx = ctx.WithBlockTime(ctx.BlockTime().Add(unbondingTime)) + providerKeeper.BeginBlockRemoveConsumers(ctx) + + testkeeper.TestProviderStateIsCleanedAfterConsumerChainIsDeleted(t, ctx, providerKeeper, "consumerId", "channelID", false) } // TestOnAcknowledgementPacketWithNoAckError tests `OnAcknowledgementPacket` when the underlying ack contains no error @@ -571,15 +606,30 @@ func TestOnAcknowledgementPacketWithAckError(t *testing.T) { require.True(t, strings.Contains(err.Error(), providertypes.ErrUnknownConsumerChannelId.Error())) // test that we stop the consumer chain when `OnAcknowledgementPacket` returns an error and the chain is found - testkeeper.SetupForStoppingConsumerChain(t, ctx, &providerKeeper, mocks) + testkeeper.SetupForDeleteConsumerChain(t, ctx, &providerKeeper, mocks, "consumerId") packet := channeltypes.Packet{ SourceChannel: "channelID", } - err = providerKeeper.OnAcknowledgementPacket(ctx, packet, ackError) + unbondingTime := 123 * time.Second + mocks.MockStakingKeeper.EXPECT().UnbondingTime(gomock.Any()).Return(unbondingTime, nil).AnyTimes() + mocks.MockChannelKeeper.EXPECT().GetChannel(gomock.Any(), ccv.ProviderPortID, "channelID").Return( + channeltypes.Channel{State: channeltypes.OPEN, + ConnectionHops: []string{"connectionID"}, + }, true, + ).Times(1) + dummyCap := &capabilitytypes.Capability{} + mocks.MockScopedKeeper.EXPECT().GetCapability(gomock.Any(), gomock.Any()).Return(dummyCap, true).Times(1) + mocks.MockChannelKeeper.EXPECT().ChanCloseInit(gomock.Any(), ccv.ProviderPortID, "channelID", dummyCap).Times(1) - testkeeper.TestProviderStateIsCleanedAfterConsumerChainIsStopped(t, ctx, providerKeeper, "chainID", "channelID") + err = providerKeeper.OnAcknowledgementPacket(ctx, packet, ackError) require.NoError(t, err) + + // increase the block time by `unbondingTime` so the chain actually gets deleted + ctx = ctx.WithBlockTime(ctx.BlockTime().Add(unbondingTime)) + providerKeeper.BeginBlockRemoveConsumers(ctx) + + testkeeper.TestProviderStateIsCleanedAfterConsumerChainIsDeleted(t, ctx, providerKeeper, "consumerId", "channelID", false) } // TestEndBlockVSU tests that during `EndBlockVSU`, we only queue VSC packets at the boundaries of an epoch @@ -587,9 +637,12 @@ func TestEndBlockVSU(t *testing.T) { providerKeeper, ctx, ctrl, mocks := testkeeper.GetProviderKeeperAndCtx(t, testkeeper.NewInMemKeeperParams(t)) defer ctrl.Finish() - chainID := "chainID" + consumerId := "0" - providerKeeper.SetTopN(ctx, chainID, 100) + err := providerKeeper.SetConsumerPowerShapingParameters(ctx, "consumerId", providertypes.PowerShapingParameters{ + Top_N: 100, + }) + require.NoError(t, err) // 10 blocks constitute an epoch params := providertypes.DefaultParams() @@ -598,14 +651,12 @@ func TestEndBlockVSU(t *testing.T) { // create 4 sample lastValidators var lastValidators []stakingtypes.Validator - var powers []int64 for i := 0; i < 4; i++ { validator := cryptotestutil.NewCryptoIdentityFromIntSeed(i).SDKStakingValidator() lastValidators = append(lastValidators, validator) valAdrr, err := sdk.ValAddressFromBech32(validator.GetOperator()) require.NoError(t, err) mocks.MockStakingKeeper.EXPECT().GetLastValidatorPower(gomock.Any(), valAdrr).Return(int64(i+1), nil).AnyTimes() - powers = append(powers, int64(i+1)) } testkeeper.SetupMocksForLastBondedValidatorsExpectation(mocks.MockStakingKeeper, 5, lastValidators, -1) @@ -616,26 +667,28 @@ func TestEndBlockVSU(t *testing.T) { }) mocks.MockStakingKeeper.EXPECT().GetBondedValidatorsByPower(gomock.Any()).Return(lastValidators, nil).AnyTimes() - // set a sample client for a consumer chain so that `GetAllConsumerChains` in `QueueVSCPackets` iterates at least once - providerKeeper.SetConsumerClientId(ctx, chainID, "clientID") + // set a sample client for a launched consumer chain so that `GetAllConsumersWithIBCClients` in `QueueVSCPackets` iterates at least once + providerKeeper.SetConsumerClientId(ctx, consumerId, "clientId") + providerKeeper.SetConsumerPowerShapingParameters(ctx, consumerId, providertypes.PowerShapingParameters{Top_N: 100}) + providerKeeper.SetConsumerPhase(ctx, consumerId, providertypes.CONSUMER_PHASE_LAUNCHED) // with block height of 1 we do not expect any queueing of VSC packets ctx = ctx.WithBlockHeight(1) - _, err := providerKeeper.EndBlockVSU(ctx) + _, err = providerKeeper.EndBlockVSU(ctx) require.NoError(t, err) - require.Equal(t, 0, len(providerKeeper.GetPendingVSCPackets(ctx, chainID))) + require.Equal(t, 0, len(providerKeeper.GetPendingVSCPackets(ctx, consumerId))) // with block height of 5 we do not expect any queueing of VSC packets ctx = ctx.WithBlockHeight(5) _, err = providerKeeper.EndBlockVSU(ctx) require.NoError(t, err) - require.Equal(t, 0, len(providerKeeper.GetPendingVSCPackets(ctx, chainID))) + require.Equal(t, 0, len(providerKeeper.GetPendingVSCPackets(ctx, consumerId))) // with block height of 10 we expect the queueing of one VSC packet ctx = ctx.WithBlockHeight(10) _, err = providerKeeper.EndBlockVSU(ctx) require.NoError(t, err) - require.Equal(t, 1, len(providerKeeper.GetPendingVSCPackets(ctx, chainID))) + require.Equal(t, 1, len(providerKeeper.GetPendingVSCPackets(ctx, consumerId))) // With block height of 15 we expect no additional queueing of a VSC packet. // Note that the pending VSC packet is still there because `SendVSCPackets` does not send the packet. We @@ -643,7 +696,7 @@ func TestEndBlockVSU(t *testing.T) { ctx = ctx.WithBlockHeight(15) _, err = providerKeeper.EndBlockVSU(ctx) require.NoError(t, err) - require.Equal(t, 1, len(providerKeeper.GetPendingVSCPackets(ctx, chainID))) + require.Equal(t, 1, len(providerKeeper.GetPendingVSCPackets(ctx, consumerId))) } // TestProviderValidatorUpdates tests that the provider validator updates are correctly calculated, @@ -655,14 +708,14 @@ func TestProviderValidatorUpdates(t *testing.T) { // Mocking bonded validators in the staking keeper. // be aware that the powers need to be in descending order validators := []stakingtypes.Validator{ - createStakingValidator(ctx, mocks, 3, 30, 3), - createStakingValidator(ctx, mocks, 2, 20, 2), - createStakingValidator(ctx, mocks, 1, 10, 1), + createStakingValidator(ctx, mocks, 30, 3), + createStakingValidator(ctx, mocks, 20, 2), + createStakingValidator(ctx, mocks, 10, 1), } mocks.MockStakingKeeper.EXPECT().GetBondedValidatorsByPower(ctx).Return(validators, nil).Times(1) // set up a validator that we will only use for the last provider consensus validator set - removedValidator := createStakingValidator(ctx, mocks, 4, 40, 4) + removedValidator := createStakingValidator(ctx, mocks, 40, 4) // Set up the last provider consensus validators consensusVals := make([]providertypes.ConsensusValidator, 0, len(validators)) @@ -722,22 +775,22 @@ func TestQueueVSCPacketsWithPowerCapping(t *testing.T) { providerKeeper.SetValidatorSetUpdateId(ctx, 1) - valA := createStakingValidator(ctx, mocks, 1, 1, 1) // 3.125% of the total voting power + valA := createStakingValidator(ctx, mocks, 1, 1) // 3.125% of the total voting power valAConsAddr, _ := valA.GetConsAddr() valAPubKey, _ := valA.TmConsPublicKey() mocks.MockStakingKeeper.EXPECT().GetValidatorByConsAddr(ctx, valAConsAddr).Return(valA, nil).AnyTimes() - valB := createStakingValidator(ctx, mocks, 2, 3, 2) // 9.375% of the total voting power + valB := createStakingValidator(ctx, mocks, 3, 2) // 9.375% of the total voting power valBConsAddr, _ := valB.GetConsAddr() valBPubKey, _ := valB.TmConsPublicKey() mocks.MockStakingKeeper.EXPECT().GetValidatorByConsAddr(ctx, valBConsAddr).Return(valB, nil).AnyTimes() - valC := createStakingValidator(ctx, mocks, 3, 4, 3) // 12.5% of the total voting power + valC := createStakingValidator(ctx, mocks, 4, 3) // 12.5% of the total voting power valCConsAddr, _ := valC.GetConsAddr() valCPubKey, _ := valC.TmConsPublicKey() mocks.MockStakingKeeper.EXPECT().GetValidatorByConsAddr(ctx, valCConsAddr).Return(valC, nil).AnyTimes() - valD := createStakingValidator(ctx, mocks, 4, 8, 4) // 25% of the total voting power + valD := createStakingValidator(ctx, mocks, 8, 4) // 25% of the total voting power valDConsAddr, _ := valD.GetConsAddr() mocks.MockStakingKeeper.EXPECT().GetValidatorByConsAddr(ctx, valDConsAddr).Return(valD, nil).AnyTimes() - valE := createStakingValidator(ctx, mocks, 5, 16, 5) // 50% of the total voting power + valE := createStakingValidator(ctx, mocks, 16, 5) // 50% of the total voting power valEConsAddr, _ := valE.GetConsAddr() valEPubKey, _ := valE.TmConsPublicKey() mocks.MockStakingKeeper.EXPECT().GetValidatorByConsAddr(ctx, valEConsAddr).Return(valE, nil).AnyTimes() @@ -745,31 +798,33 @@ func TestQueueVSCPacketsWithPowerCapping(t *testing.T) { testkeeper.SetupMocksForLastBondedValidatorsExpectation(mocks.MockStakingKeeper, 5, []stakingtypes.Validator{valA, valB, valC, valD, valE}, -1) // add a consumer chain - providerKeeper.SetConsumerClientId(ctx, "chainID", "clientID") + providerKeeper.SetConsumerClientId(ctx, "consumerId", "clientId") + providerKeeper.SetConsumerPhase(ctx, "consumerId", providertypes.CONSUMER_PHASE_LAUNCHED) - providerKeeper.SetTopN(ctx, "chainID", 50) // would opt in E + err := providerKeeper.SetConsumerPowerShapingParameters(ctx, "consumerId", providertypes.PowerShapingParameters{ + Top_N: 50, // would opt in E + ValidatorsPowerCap: 40, // set a power-capping of 40% + }) + require.NoError(t, err) // opt in all validators - providerKeeper.SetOptedIn(ctx, "chainID", providertypes.NewProviderConsAddress(valAConsAddr)) - providerKeeper.SetOptedIn(ctx, "chainID", providertypes.NewProviderConsAddress(valBConsAddr)) - providerKeeper.SetOptedIn(ctx, "chainID", providertypes.NewProviderConsAddress(valCConsAddr)) - providerKeeper.SetOptedIn(ctx, "chainID", providertypes.NewProviderConsAddress(valDConsAddr)) + providerKeeper.SetOptedIn(ctx, "consumerId", providertypes.NewProviderConsAddress(valAConsAddr)) + providerKeeper.SetOptedIn(ctx, "consumerId", providertypes.NewProviderConsAddress(valBConsAddr)) + providerKeeper.SetOptedIn(ctx, "consumerId", providertypes.NewProviderConsAddress(valCConsAddr)) + providerKeeper.SetOptedIn(ctx, "consumerId", providertypes.NewProviderConsAddress(valDConsAddr)) // denylist validator D - providerKeeper.SetDenylist(ctx, "chainID", providertypes.NewProviderConsAddress(valDConsAddr)) - - // set a power-capping of 40% - providerKeeper.SetValidatorsPowerCap(ctx, "chainID", 40) + providerKeeper.SetDenylist(ctx, "consumerId", providertypes.NewProviderConsAddress(valDConsAddr)) // set max provider consensus vals to include all validators params := providerKeeper.GetParams(ctx) params.MaxProviderConsensusValidators = 180 providerKeeper.SetParams(ctx, params) - err := providerKeeper.QueueVSCPackets(ctx) + err = providerKeeper.QueueVSCPackets(ctx) require.NoError(t, err) - actualQueuedVSCPackets := providerKeeper.GetPendingVSCPackets(ctx, "chainID") + actualQueuedVSCPackets := providerKeeper.GetPendingVSCPackets(ctx, "consumerId") expectedQueuedVSCPackets := []ccv.ValidatorSetChangePacketData{ ccv.NewValidatorSetChangePacketData( []abci.ValidatorUpdate{ diff --git a/x/ccv/provider/keeper/staking_keeper_interface_test.go b/x/ccv/provider/keeper/staking_keeper_interface_test.go index 2eb9c9f1bd..40cfb5c0d7 100644 --- a/x/ccv/provider/keeper/staking_keeper_interface_test.go +++ b/x/ccv/provider/keeper/staking_keeper_interface_test.go @@ -6,7 +6,6 @@ import ( "cosmossdk.io/math" sdk "github.com/cosmos/cosmos-sdk/types" - "github.com/cosmos/cosmos-sdk/x/staking/types" stakingtypes "github.com/cosmos/cosmos-sdk/x/staking/types" testkeeper "github.com/cosmos/interchain-security/v5/testutil/keeper" "github.com/golang/mock/gomock" @@ -107,7 +106,7 @@ func TestStakingKeeperInterface(t *testing.T) { return nil }).AnyTimes() actualValPowers := []int64{} - err := providerKeeper.IterateBondedValidatorsByPower(ctx, func(index int64, validator types.ValidatorI) (stop bool) { + err := providerKeeper.IterateBondedValidatorsByPower(ctx, func(index int64, validator stakingtypes.ValidatorI) (stop bool) { counter++ actualValPowers = append(actualValPowers, validator.GetTokens().Int64()) return false diff --git a/x/ccv/provider/keeper/validator_set_update.go b/x/ccv/provider/keeper/validator_set_update.go index 1c55f26553..95a8d5c9a7 100644 --- a/x/ccv/provider/keeper/validator_set_update.go +++ b/x/ccv/provider/keeper/validator_set_update.go @@ -12,53 +12,53 @@ import ( ccv "github.com/cosmos/interchain-security/v5/x/ccv/types" ) -// GetConsumerChainConsensusValidatorsKey returns the store key for consumer validators of the consumer chain with `chainID` -func (k Keeper) GetConsumerChainConsensusValidatorsKey(ctx sdk.Context, chainID string) []byte { - return types.ChainIdWithLenKey(types.ConsumerValidatorKeyPrefix(), chainID) +// GetConsumerChainConsensusValidatorsKey returns the store key for consumer validators of the consumer chain with `consumerId` +func (k Keeper) GetConsumerChainConsensusValidatorsKey(ctx sdk.Context, consumerId string) []byte { + return types.StringIdWithLenKey(types.ConsumerValidatorKeyPrefix(), consumerId) } -// SetConsumerValidator sets provided consumer `validator` on the consumer chain with `chainID` +// SetConsumerValidator sets provided consumer `validator` on the consumer chain with `consumerId` func (k Keeper) SetConsumerValidator( ctx sdk.Context, - chainID string, + consumerId string, validator types.ConsensusValidator, ) { - k.setValidator(ctx, k.GetConsumerChainConsensusValidatorsKey(ctx, chainID), validator) + k.setValidator(ctx, k.GetConsumerChainConsensusValidatorsKey(ctx, consumerId), validator) } // SetConsumerValSet resets the current consumer validators with the `nextValidators` computed by // `FilterValidators` and hence this method should only be called after `FilterValidators` has completed. -func (k Keeper) SetConsumerValSet(ctx sdk.Context, chainID string, nextValidators []types.ConsensusValidator) { - k.setValSet(ctx, k.GetConsumerChainConsensusValidatorsKey(ctx, chainID), nextValidators) +func (k Keeper) SetConsumerValSet(ctx sdk.Context, consumerId string, nextValidators []types.ConsensusValidator) { + k.setValSet(ctx, k.GetConsumerChainConsensusValidatorsKey(ctx, consumerId), nextValidators) } // DeleteConsumerValidator removes consumer validator with `providerAddr` address func (k Keeper) DeleteConsumerValidator( ctx sdk.Context, - chainID string, + consumerId string, providerConsAddr types.ProviderConsAddress, ) { - k.deleteValidator(ctx, k.GetConsumerChainConsensusValidatorsKey(ctx, chainID), providerConsAddr) + k.deleteValidator(ctx, k.GetConsumerChainConsensusValidatorsKey(ctx, consumerId), providerConsAddr) } -// DeleteConsumerValSet deletes all the stored consumer validators for chain `chainID` +// DeleteConsumerValSet deletes all the stored consumer validators for chain with `consumerId` func (k Keeper) DeleteConsumerValSet( ctx sdk.Context, - chainID string, + consumerId string, ) { - k.deleteValSet(ctx, k.GetConsumerChainConsensusValidatorsKey(ctx, chainID)) + k.deleteValSet(ctx, k.GetConsumerChainConsensusValidatorsKey(ctx, consumerId)) } -// IsConsumerValidator returns `true` if the consumer validator with `providerAddr` exists for chain `chainID` +// IsConsumerValidator returns `true` if the consumer validator with `providerAddr` exists for chain with `consumerId` // and `false` otherwise -func (k Keeper) IsConsumerValidator(ctx sdk.Context, chainID string, providerAddr types.ProviderConsAddress) bool { - return k.isValidator(ctx, k.GetConsumerChainConsensusValidatorsKey(ctx, chainID), providerAddr) +func (k Keeper) IsConsumerValidator(ctx sdk.Context, consumerId string, providerAddr types.ProviderConsAddress) bool { + return k.isValidator(ctx, k.GetConsumerChainConsensusValidatorsKey(ctx, consumerId), providerAddr) } -// GetConsumerValidator returns the consumer validator with `providerAddr` if it exists for chain `chainID` -func (k Keeper) GetConsumerValidator(ctx sdk.Context, chainID string, providerAddr types.ProviderConsAddress) (types.ConsensusValidator, bool) { +// GetConsumerValidator returns the consumer validator with `providerAddr` if it exists for chain with `consumerId` +func (k Keeper) GetConsumerValidator(ctx sdk.Context, consumerId string, providerAddr types.ProviderConsAddress) (types.ConsensusValidator, bool) { store := ctx.KVStore(k.storeKey) - marshalledConsumerValidator := store.Get(types.ConsumerValidatorKey(chainID, providerAddr.ToSdkConsAddr())) + marshalledConsumerValidator := store.Get(types.ConsumerValidatorKey(consumerId, providerAddr.ToSdkConsAddr())) if marshalledConsumerValidator == nil { return types.ConsensusValidator{}, false @@ -72,12 +72,12 @@ func (k Keeper) GetConsumerValidator(ctx sdk.Context, chainID string, providerAd return validator, true } -// GetConsumerValSet returns all the consumer validators for chain `chainID` +// GetConsumerValSet returns all the consumer validators for chain with `consumerId` func (k Keeper) GetConsumerValSet( ctx sdk.Context, - chainID string, + consumerId string, ) ([]types.ConsensusValidator, error) { - return k.getValSet(ctx, k.GetConsumerChainConsensusValidatorsKey(ctx, chainID)) + return k.getValSet(ctx, k.GetConsumerChainConsensusValidatorsKey(ctx, consumerId)) } // DiffValidators compares the current and the next epoch's consumer validators and returns the `ValidatorUpdate` diff @@ -121,8 +121,8 @@ func DiffValidators( return updates } -// CreateConsumerValidator creates a consumer validator for `chainID` from the given staking `validator` -func (k Keeper) CreateConsumerValidator(ctx sdk.Context, chainID string, validator stakingtypes.Validator) (types.ConsensusValidator, error) { +// CreateConsumerValidator creates a consumer validator for `consumerId` from the given staking `validator` +func (k Keeper) CreateConsumerValidator(ctx sdk.Context, consumerId string, validator stakingtypes.Validator) (types.ConsensusValidator, error) { valAddr, err := sdk.ValAddressFromBech32(validator.GetOperator()) if err != nil { return types.ConsensusValidator{}, err @@ -138,7 +138,7 @@ func (k Keeper) CreateConsumerValidator(ctx sdk.Context, chainID string, validat validator, err) } - consumerPublicKey, found := k.GetValidatorConsumerPubKey(ctx, chainID, types.NewProviderConsAddress(consAddr)) + consumerPublicKey, found := k.GetValidatorConsumerPubKey(ctx, consumerId, types.NewProviderConsAddress(consAddr)) if !found { consumerPublicKey, err = validator.TmConsPublicKey() if err != nil { @@ -147,7 +147,7 @@ func (k Keeper) CreateConsumerValidator(ctx sdk.Context, chainID string, validat } height := ctx.BlockHeight() - if v, found := k.GetConsumerValidator(ctx, chainID, types.ProviderConsAddress{Address: consAddr}); found { + if v, found := k.GetConsumerValidator(ctx, consumerId, types.ProviderConsAddress{Address: consAddr}); found { // if validator was already a consumer validator, then do not update the height set the first time // the validator became a consumer validator height = v.JoinHeight @@ -165,7 +165,7 @@ func (k Keeper) CreateConsumerValidator(ctx sdk.Context, chainID string, validat // the filtered set. func (k Keeper) FilterValidators( ctx sdk.Context, - chainID string, + consumerId string, bondedValidators []stakingtypes.Validator, predicate func(providerAddr types.ProviderConsAddress) bool, ) []types.ConsensusValidator { @@ -177,7 +177,7 @@ func (k Keeper) FilterValidators( } if predicate(types.NewProviderConsAddress(consAddr)) { - nextValidator, err := k.CreateConsumerValidator(ctx, chainID, val) + nextValidator, err := k.CreateConsumerValidator(ctx, consumerId, val) if err != nil { // this should never happen but is recoverable if we exclude this validator from the next validator set k.Logger(ctx).Error("could not create consumer validator", diff --git a/x/ccv/provider/keeper/validator_set_update_test.go b/x/ccv/provider/keeper/validator_set_update_test.go index e343093dad..aa9ae6abba 100644 --- a/x/ccv/provider/keeper/validator_set_update_test.go +++ b/x/ccv/provider/keeper/validator_set_update_test.go @@ -32,11 +32,11 @@ func TestConsumerValidator(t *testing.T) { PublicKey: &crypto.PublicKey{}, } - require.False(t, providerKeeper.IsConsumerValidator(ctx, "chainID", types.NewProviderConsAddress(validator.ProviderConsAddr))) - providerKeeper.SetConsumerValidator(ctx, "chainID", validator) - require.True(t, providerKeeper.IsConsumerValidator(ctx, "chainID", types.NewProviderConsAddress(validator.ProviderConsAddr))) - providerKeeper.DeleteConsumerValidator(ctx, "chainID", types.NewProviderConsAddress(validator.ProviderConsAddr)) - require.False(t, providerKeeper.IsConsumerValidator(ctx, "chainID", types.NewProviderConsAddress(validator.ProviderConsAddr))) + require.False(t, providerKeeper.IsConsumerValidator(ctx, "consumerId", types.NewProviderConsAddress(validator.ProviderConsAddr))) + providerKeeper.SetConsumerValidator(ctx, "consumerId", validator) + require.True(t, providerKeeper.IsConsumerValidator(ctx, "consumerId", types.NewProviderConsAddress(validator.ProviderConsAddr))) + providerKeeper.DeleteConsumerValidator(ctx, "consumerId", types.NewProviderConsAddress(validator.ProviderConsAddr)) + require.False(t, providerKeeper.IsConsumerValidator(ctx, "consumerId", types.NewProviderConsAddress(validator.ProviderConsAddr))) } func TestGetConsumerValSet(t *testing.T) { @@ -75,7 +75,7 @@ func TestGetConsumerValSet(t *testing.T) { } for _, expectedValidator := range expectedValidators { - providerKeeper.SetConsumerValidator(ctx, "chainID", + providerKeeper.SetConsumerValidator(ctx, "consumerId", types.ConsensusValidator{ ProviderConsAddr: expectedValidator.ProviderConsAddr, Power: expectedValidator.Power, @@ -83,7 +83,7 @@ func TestGetConsumerValSet(t *testing.T) { }) } - actualValidators, err := providerKeeper.GetConsumerValSet(ctx, "chainID") + actualValidators, err := providerKeeper.GetConsumerValSet(ctx, "consumerId") require.NoError(t, err) // sort validators first to be able to compare @@ -111,7 +111,7 @@ func createConsumerValidator(index int, power int64, seed int) (types.ConsensusV } // createStakingValidator helper function to generate a validator with the given power and with a provider address based on index -func createStakingValidator(ctx sdk.Context, mocks testkeeper.MockedKeepers, index int, power int64, seed int) stakingtypes.Validator { +func createStakingValidator(ctx sdk.Context, mocks testkeeper.MockedKeepers, power int64, seed int) stakingtypes.Validator { providerConsPubKey := cryptotestutil.NewCryptoIdentityFromIntSeed(seed).TMProtoCryptoPublicKey() pk, _ := cryptocodec.FromCmtProtoPublicKey(providerConsPubKey) @@ -126,6 +126,7 @@ func createStakingValidator(ctx sdk.Context, mocks testkeeper.MockedKeepers, ind return stakingtypes.Validator{ OperatorAddress: providerValidatorAddr.String(), ConsensusPubkey: pkAny, + Status: stakingtypes.Bonded, } } @@ -253,7 +254,7 @@ func TestSetConsumerValSet(t *testing.T) { providerKeeper, ctx, ctrl, _ := testkeeper.GetProviderKeeperAndCtx(t, testkeeper.NewInMemKeeperParams(t)) defer ctrl.Finish() - chainID := "chainID" + chainID := "consumerId" currentValidators := []types.ConsensusValidator{ { @@ -306,7 +307,7 @@ func TestSetConsumerValSet(t *testing.T) { }, } - // set the `currentValidators` for chain `chainID` + // set the `currentValidators` for chain `consumerId` valSet, err := providerKeeper.GetConsumerValSet(ctx, chainID) require.NoError(t, err) require.Empty(t, valSet) @@ -338,7 +339,7 @@ func TestFilterValidatorsConsiderAll(t *testing.T) { providerKeeper, ctx, ctrl, mocks := testkeeper.GetProviderKeeperAndCtx(t, testkeeper.NewInMemKeeperParams(t)) defer ctrl.Finish() - chainID := "chainID" + chainID := "consumerId" // no consumer validators returned if we have no bonded validators considerAll := func(providerAddr types.ProviderConsAddress) bool { return true } @@ -347,7 +348,7 @@ func TestFilterValidatorsConsiderAll(t *testing.T) { var expectedValidators []types.ConsensusValidator // create a staking validator A that has not set a consumer public key - valA := createStakingValidator(ctx, mocks, 1, 1, 1) + valA := createStakingValidator(ctx, mocks, 1, 1) // because validator A has no consumer key set, the `PublicKey` we expect is the key on the provider chain valAConsAddr, _ := valA.GetConsAddr() valAPublicKey, _ := valA.TmConsPublicKey() @@ -358,7 +359,7 @@ func TestFilterValidatorsConsiderAll(t *testing.T) { }) // create a staking validator B that has set a consumer public key - valB := createStakingValidator(ctx, mocks, 2, 2, 2) + valB := createStakingValidator(ctx, mocks, 2, 2) // validator B has set a consumer key, the `PublicKey` we expect is the key set by `SetValidatorConsumerPubKey` valBConsumerKey := cryptotestutil.NewCryptoIdentityFromIntSeed(1).TMProtoCryptoPublicKey() valBConsAddr, _ := valB.GetConsAddr() @@ -378,7 +379,7 @@ func TestFilterValidatorsConsiderOnlyOptIn(t *testing.T) { providerKeeper, ctx, ctrl, mocks := testkeeper.GetProviderKeeperAndCtx(t, testkeeper.NewInMemKeeperParams(t)) defer ctrl.Finish() - chainID := "chainID" + chainID := "consumerId" // no consumer validators returned if we have no opted-in validators require.Empty(t, providerKeeper.FilterValidators(ctx, chainID, []stakingtypes.Validator{}, @@ -389,7 +390,7 @@ func TestFilterValidatorsConsiderOnlyOptIn(t *testing.T) { var expectedValidators []types.ConsensusValidator // create a staking validator A that has not set a consumer public key - valA := createStakingValidator(ctx, mocks, 1, 1, 1) + valA := createStakingValidator(ctx, mocks, 1, 1) // because validator A has no consumer key set, the `PublicKey` we expect is the key on the provider chain valAConsAddr, _ := valA.GetConsAddr() valAPublicKey, _ := valA.TmConsPublicKey() @@ -401,7 +402,7 @@ func TestFilterValidatorsConsiderOnlyOptIn(t *testing.T) { expectedValidators = append(expectedValidators, expectedValAConsumerValidator) // create a staking validator B that has set a consumer public key - valB := createStakingValidator(ctx, mocks, 2, 2, 2) + valB := createStakingValidator(ctx, mocks, 2, 2) // validator B has set a consumer key, the `PublicKey` we expect is the key set by `SetValidatorConsumerPubKey` valBConsumerKey := cryptotestutil.NewCryptoIdentityFromIntSeed(1).TMProtoCryptoPublicKey() valBConsAddr, _ := valB.GetConsAddr() @@ -419,7 +420,7 @@ func TestFilterValidatorsConsiderOnlyOptIn(t *testing.T) { // the expected actual validators are the opted-in validators but with the correct power and consumer public keys set bondedValidators := []stakingtypes.Validator{valA, valB} - actualValidators := providerKeeper.FilterValidators(ctx, "chainID", bondedValidators, + actualValidators := providerKeeper.FilterValidators(ctx, "consumerId", bondedValidators, func(providerAddr types.ProviderConsAddress) bool { return providerKeeper.IsOptedIn(ctx, chainID, providerAddr) }) @@ -436,9 +437,9 @@ func TestFilterValidatorsConsiderOnlyOptIn(t *testing.T) { require.Equal(t, expectedValidators, actualValidators) // create a staking validator C that is not opted in, hence `expectedValidators` remains the same - valC := createStakingValidator(ctx, mocks, 3, 3, 3) + valC := createStakingValidator(ctx, mocks, 3, 3) bondedValidators = []stakingtypes.Validator{valA, valB, valC} - actualValidators = providerKeeper.FilterValidators(ctx, "chainID", bondedValidators, + actualValidators = providerKeeper.FilterValidators(ctx, "consumerId", bondedValidators, func(providerAddr types.ProviderConsAddress) bool { return providerKeeper.IsOptedIn(ctx, chainID, providerAddr) }) @@ -452,10 +453,10 @@ func TestCreateConsumerValidator(t *testing.T) { providerKeeper, ctx, ctrl, mocks := testkeeper.GetProviderKeeperAndCtx(t, testkeeper.NewInMemKeeperParams(t)) defer ctrl.Finish() - chainID := "chainID" + chainID := "consumerId" // create a validator which has set a consumer public key - valA := createStakingValidator(ctx, mocks, 0, 1, 1) + valA := createStakingValidator(ctx, mocks, 1, 1) valAConsumerKey := cryptotestutil.NewCryptoIdentityFromIntSeed(1).TMProtoCryptoPublicKey() valAConsAddr, _ := valA.GetConsAddr() valAProviderConsAddr := types.NewProviderConsAddress(valAConsAddr) @@ -470,7 +471,7 @@ func TestCreateConsumerValidator(t *testing.T) { require.NoError(t, err) // create a validator which has not set a consumer public key - valB := createStakingValidator(ctx, mocks, 1, 2, 2) + valB := createStakingValidator(ctx, mocks, 2, 2) valBConsAddr, _ := valB.GetConsAddr() valBProviderConsAddr := types.NewProviderConsAddress(valBConsAddr) valBPublicKey, _ := valB.TmConsPublicKey() diff --git a/x/ccv/provider/migrations/migrator.go b/x/ccv/provider/migrations/migrator.go index 4678fe83cd..edc80ef6ce 100644 --- a/x/ccv/provider/migrations/migrator.go +++ b/x/ccv/provider/migrations/migrator.go @@ -8,9 +8,6 @@ import ( paramtypes "github.com/cosmos/cosmos-sdk/x/params/types" providerkeeper "github.com/cosmos/interchain-security/v5/x/ccv/provider/keeper" - v4 "github.com/cosmos/interchain-security/v5/x/ccv/provider/migrations/v4" - v5 "github.com/cosmos/interchain-security/v5/x/ccv/provider/migrations/v5" - v6 "github.com/cosmos/interchain-security/v5/x/ccv/provider/migrations/v6" v7 "github.com/cosmos/interchain-security/v5/x/ccv/provider/migrations/v7" v8 "github.com/cosmos/interchain-security/v5/x/ccv/provider/migrations/v8" ) @@ -55,24 +52,23 @@ func (m Migrator) Migrate2to3(ctx sdktypes.Context) error { // Migrate3to4 migrates x/ccvprovider state from consensus version 3 to 4. // The migration consists of provider chain params additions. func (m Migrator) Migrate3to4(ctx sdktypes.Context) error { - v4.MigrateParams(ctx, m.paramSpace) - return nil + return fmt.Errorf("state migration failed: " + + "first run provider@v4.3.x in production to migrate from consensus version 3 to 4") } // Migrate4to5 migrates x/ccvprovider state from consensus version 4 to 5. // The migration consists of setting a top N of 95 for all registered consumer chains. func (m Migrator) Migrate4to5(ctx sdktypes.Context) error { - v5.MigrateTopNForRegisteredChains(ctx, m.providerKeeper) - return nil + return fmt.Errorf("state migration failed: " + + "first run provider@v4.3.x in production to migrate from consensus version 4 to 5") } // Migrate5to6 migrates x/ccvprovider state from consensus version 5 to 6. // It consists of setting the `NumberOfEpochsToStartReceivingRewards` param, as well as // computing and storing the minimal power in the top N for all registered consumer chains. func (m Migrator) Migrate5to6(ctx sdktypes.Context) error { - v6.MigrateParams(ctx, m.paramSpace) - v6.MigrateMinPowerInTopN(ctx, m.providerKeeper) - return nil + return fmt.Errorf("state migration failed: " + + "first run provider@v4.3.x in production to migrate from consensus version 5 to 6") } // Migrate6to7 migrates x/ccvprovider state from consensus version 6 to 7. @@ -92,6 +88,9 @@ func (m Migrator) Migrate7to8(ctx sdktypes.Context) error { if err := v8.MigrateConsumerAddrsToPrune(ctx, store, m.providerKeeper); err != nil { return err } + if err := v8.MigrateLaunchedConsumerChains(ctx, store, m.providerKeeper); err != nil { + return err + } v8.CleanupState(store) return nil diff --git a/x/ccv/provider/migrations/v4/migration_test.go b/x/ccv/provider/migrations/v4/migration_test.go deleted file mode 100644 index 4423842149..0000000000 --- a/x/ccv/provider/migrations/v4/migration_test.go +++ /dev/null @@ -1,27 +0,0 @@ -package v4 - -import ( - "testing" - - "github.com/stretchr/testify/require" - - testutil "github.com/cosmos/interchain-security/v5/testutil/keeper" - providertypes "github.com/cosmos/interchain-security/v5/x/ccv/provider/types" -) - -func TestMigrateParams(t *testing.T) { - inMemParams := testutil.NewInMemKeeperParams(t) - _, ctx, ctrl, _ := testutil.GetProviderKeeperAndCtx(t, inMemParams) - defer ctrl.Finish() - - // initially blocks per epoch param does not exist - require.False(t, inMemParams.ParamsSubspace.Has(ctx, providertypes.KeyBlocksPerEpoch)) - - MigrateParams(ctx, *inMemParams.ParamsSubspace) - - // after migration, blocks per epoch param should exist and be equal to default - require.True(t, inMemParams.ParamsSubspace.Has(ctx, providertypes.KeyBlocksPerEpoch)) - var blocksPerEpochParam int64 - inMemParams.ParamsSubspace.Get(ctx, providertypes.KeyBlocksPerEpoch, &blocksPerEpochParam) - require.Equal(t, providertypes.DefaultBlocksPerEpoch, blocksPerEpochParam) -} diff --git a/x/ccv/provider/migrations/v4/migrations.go b/x/ccv/provider/migrations/v4/migrations.go deleted file mode 100644 index e60c98700e..0000000000 --- a/x/ccv/provider/migrations/v4/migrations.go +++ /dev/null @@ -1,18 +0,0 @@ -package v4 - -import ( - sdk "github.com/cosmos/cosmos-sdk/types" - paramtypes "github.com/cosmos/cosmos-sdk/x/params/types" - - providertypes "github.com/cosmos/interchain-security/v5/x/ccv/provider/types" -) - -// MigrateParams adds missing provider chain params to the param store. -func MigrateParams(ctx sdk.Context, paramsSubspace paramtypes.Subspace) { - if paramsSubspace.HasKeyTable() { - paramsSubspace.Set(ctx, providertypes.KeyBlocksPerEpoch, providertypes.DefaultBlocksPerEpoch) - } else { - paramsSubspace.WithKeyTable(providertypes.ParamKeyTable()) - paramsSubspace.Set(ctx, providertypes.KeyBlocksPerEpoch, providertypes.DefaultBlocksPerEpoch) - } -} diff --git a/x/ccv/provider/migrations/v5/migration_test.go b/x/ccv/provider/migrations/v5/migration_test.go deleted file mode 100644 index 907aa1b019..0000000000 --- a/x/ccv/provider/migrations/v5/migration_test.go +++ /dev/null @@ -1,30 +0,0 @@ -package v5 - -import ( - "testing" - - "github.com/stretchr/testify/require" - - testutil "github.com/cosmos/interchain-security/v5/testutil/keeper" -) - -func TestMigrateParams(t *testing.T) { - inMemParams := testutil.NewInMemKeeperParams(t) - provKeeper, ctx, ctrl, _ := testutil.GetProviderKeeperAndCtx(t, inMemParams) - defer ctrl.Finish() - - provKeeper.SetConsumerClientId(ctx, "chainID", "clientID") - - // initially top N should not exist - topN, found := provKeeper.GetTopN(ctx, "chainID") - require.False(t, found) - require.Zero(t, topN) - - // migrate - MigrateTopNForRegisteredChains(ctx, provKeeper) - - // after migration, top N should be 95 - topN, found = provKeeper.GetTopN(ctx, "chainID") - require.True(t, found) - require.Equal(t, uint32(95), topN) -} diff --git a/x/ccv/provider/migrations/v5/migrations.go b/x/ccv/provider/migrations/v5/migrations.go deleted file mode 100644 index 411efd49e1..0000000000 --- a/x/ccv/provider/migrations/v5/migrations.go +++ /dev/null @@ -1,21 +0,0 @@ -package v5 - -import ( - sdk "github.com/cosmos/cosmos-sdk/types" - - providerkeeper "github.com/cosmos/interchain-security/v5/x/ccv/provider/keeper" -) - -// This migration only takes already registered chains into account. -// If a chain is in voting while the upgrade happens, this is not sufficient, -// and a migration to rewrite the proposal is needed. -func MigrateTopNForRegisteredChains(ctx sdk.Context, providerKeeper providerkeeper.Keeper) { - // Set the topN of each chain to 95 - for _, chainID := range providerKeeper.GetAllRegisteredConsumerChainIDs(ctx) { - providerKeeper.SetTopN(ctx, chainID, 95) - } -} - -// // If there are consumer addition proposals in the voting period at the upgrade time, they may need the topN value updated. -// func MigrateTopNForVotingPeriodChains(ctx sdk.Context, govKeeper govkeeper.Keeper, providerKeeper providerkeeper.Keeper) { -// } diff --git a/x/ccv/provider/migrations/v6/migration_test.go b/x/ccv/provider/migrations/v6/migration_test.go deleted file mode 100644 index 9396a3e05d..0000000000 --- a/x/ccv/provider/migrations/v6/migration_test.go +++ /dev/null @@ -1,27 +0,0 @@ -package v6 - -import ( - "testing" - - "github.com/stretchr/testify/require" - - testutil "github.com/cosmos/interchain-security/v5/testutil/keeper" - providertypes "github.com/cosmos/interchain-security/v5/x/ccv/provider/types" -) - -func TestMigrateParams(t *testing.T) { - inMemParams := testutil.NewInMemKeeperParams(t) - _, ctx, ctrl, _ := testutil.GetProviderKeeperAndCtx(t, inMemParams) - defer ctrl.Finish() - - // initially number of epochs param does not exist - require.False(t, inMemParams.ParamsSubspace.Has(ctx, providertypes.KeyNumberOfEpochsToStartReceivingRewards)) - - MigrateParams(ctx, *inMemParams.ParamsSubspace) - - // after migration, number of epochs to start receiving rewards param should exist and be equal to default - require.True(t, inMemParams.ParamsSubspace.Has(ctx, providertypes.KeyNumberOfEpochsToStartReceivingRewards)) - var numberOfEpochsParam int64 - inMemParams.ParamsSubspace.Get(ctx, providertypes.KeyNumberOfEpochsToStartReceivingRewards, &numberOfEpochsParam) - require.Equal(t, providertypes.DefaultNumberOfEpochsToStartReceivingRewards, numberOfEpochsParam) -} diff --git a/x/ccv/provider/migrations/v6/migrations.go b/x/ccv/provider/migrations/v6/migrations.go deleted file mode 100644 index 5829f29222..0000000000 --- a/x/ccv/provider/migrations/v6/migrations.go +++ /dev/null @@ -1,47 +0,0 @@ -package v6 - -import ( - sdk "github.com/cosmos/cosmos-sdk/types" - paramtypes "github.com/cosmos/cosmos-sdk/x/params/types" - - providerkeeper "github.com/cosmos/interchain-security/v5/x/ccv/provider/keeper" - providertypes "github.com/cosmos/interchain-security/v5/x/ccv/provider/types" -) - -// MigrateParams adds missing provider chain params to the param store. -func MigrateParams(ctx sdk.Context, paramsSubspace paramtypes.Subspace) { - if !paramsSubspace.HasKeyTable() { - paramsSubspace.WithKeyTable(providertypes.ParamKeyTable()) - } - paramsSubspace.Set(ctx, providertypes.KeyNumberOfEpochsToStartReceivingRewards, providertypes.DefaultNumberOfEpochsToStartReceivingRewards) -} - -func MigrateMinPowerInTopN(ctx sdk.Context, providerKeeper providerkeeper.Keeper) { - // we only get the registered consumer chains and not also the proposed consumer chains because - // the minimal power is first set when the consumer chain addition proposal passes - registeredConsumerChains := providerKeeper.GetAllRegisteredConsumerChainIDs(ctx) - - for _, chain := range registeredConsumerChains { - // get the top N - topN, found := providerKeeper.GetTopN(ctx, chain) - if !found { - providerKeeper.Logger(ctx).Error("failed to get top N", "chain", chain) - continue - } else if topN == 0 { - providerKeeper.Logger(ctx).Info("top N is 0, not setting minimal power", "chain", chain) - } else { - // set the minimal power in the top N - bondedValidators, err := providerKeeper.GetLastBondedValidators(ctx) - if err != nil { - providerKeeper.Logger(ctx).Error("failed to get last bonded validators", "chain", chain, "error", err) - continue - } - minPower, err := providerKeeper.ComputeMinPowerInTopN(ctx, bondedValidators, topN) - if err != nil { - providerKeeper.Logger(ctx).Error("failed to compute min power in top N", "chain", chain, "topN", topN, "error", err) - continue - } - providerKeeper.SetMinimumPowerInTopN(ctx, chain, minPower) - } - } -} diff --git a/x/ccv/provider/migrations/v8/migrations.go b/x/ccv/provider/migrations/v8/migrations.go index cdf299f91f..c7ace6eb3f 100644 --- a/x/ccv/provider/migrations/v8/migrations.go +++ b/x/ccv/provider/migrations/v8/migrations.go @@ -4,11 +4,15 @@ import ( "encoding/binary" "time" + "github.com/cosmos/cosmos-sdk/types/bech32" + + errorsmod "cosmossdk.io/errors" storetypes "cosmossdk.io/store/types" sdk "github.com/cosmos/cosmos-sdk/types" providerkeeper "github.com/cosmos/interchain-security/v5/x/ccv/provider/keeper" providertypes "github.com/cosmos/interchain-security/v5/x/ccv/provider/types" + ccv "github.com/cosmos/interchain-security/v5/x/ccv/types" ) const ( @@ -19,6 +23,30 @@ const ( LegacyInitTimeoutTimestampBytePrefix = byte(8) LegacyVscSendTimestampBytePrefix = byte(18) LegacyVSCMaturedHandledThisBlockBytePrefix = byte(28) + + LegacyPendingCAPKeyPrefix = byte(9) + LegacyPendingCRPKeyPrefix = byte(10) + LegacyProposedConsumerChainKeyPrefix = byte(30) + + LegacyThrottledPacketDataSizeKeyPrefix = byte(19) + LegacyThrottledPacketDataKeyPrefix = byte(20) + LegacyGlobalSlashEntryKeyPrefix = byte(21) + LegacyTopNKeyPrefix = byte(33) + LegacyValidatorsPowerCapKeyPrefix = byte(34) + LegacyValidatorSetCapKeyPrefix = byte(35) + + LegacyChainToChannelKeyPrefix = byte(5) + LegacyChannelToChainKeyPrefix = byte(6) + LegacyChainToClientKeyPrefix = byte(7) + + // needed for rekeying + ConsumerGenesisKeyPrefix = byte(14) + SlashAcksKeyPrefix = byte(15) + InitChainHeightKeyPrefix = byte(16) + PendingVSCsKeyPrefix = byte(17) + EquivocationEvidenceMinHeightKeyPrefix = byte(29) + ConsumerRewardsAllocationKeyPrefix = byte(38) + MinimumPowerInTopNKeyPrefix = byte(40) ) // CompleteUnbondingOps completes all unbonding operations. @@ -51,7 +79,7 @@ func MigrateConsumerAddrsToPrune(ctx sdk.Context, store storetypes.KVStore, pk p } for ; iterator.Valid(); iterator.Next() { - chainID, vscID, err := providertypes.ParseChainIdAndUintIdKey(LegacyConsumerAddrsToPruneBytePrefix, iterator.Key()) + chainID, vscID, err := providertypes.ParseStringIdAndUintIdKey(LegacyConsumerAddrsToPruneBytePrefix, iterator.Key()) if err != nil { pk.Logger(ctx).Error("ParseChainIdAndUintIdKey failed while migrating ConsumerAddrsToPrune", "key", string(iterator.Key()), @@ -60,7 +88,7 @@ func MigrateConsumerAddrsToPrune(ctx sdk.Context, store storetypes.KVStore, pk p continue } // use the VscSendTimestamp index to compute the timestamp after which this consumer address can be pruned - vscSendTimestampKey := providertypes.ChainIdAndUintIdKey(LegacyVscSendTimestampBytePrefix, chainID, vscID) + vscSendTimestampKey := providertypes.StringIdAndUintIdKey(LegacyVscSendTimestampBytePrefix, chainID, vscID) var sentTime time.Time if timeBz := store.Get(vscSendTimestampKey); timeBz != nil { if ts, err := sdk.ParseTimeBytes(timeBz); err == nil { @@ -95,6 +123,268 @@ func MigrateConsumerAddrsToPrune(ctx sdk.Context, store storetypes.KVStore, pk p return nil } +// MigrateLaunchedConsumerChains migrates all the state for consumer chains with an existing client +// Note that it must be executed before CleanupState. +func MigrateLaunchedConsumerChains(ctx sdk.Context, store storetypes.KVStore, pk providerkeeper.Keeper) error { + chainIds := []string{} + iterator := storetypes.KVStorePrefixIterator(store, []byte{LegacyChainToClientKeyPrefix}) + for ; iterator.Valid(); iterator.Next() { + // remove 1 byte prefix from key to retrieve chainId + chainId := string(iterator.Key()[1:]) + chainIds = append(chainIds, chainId) + } + err := iterator.Close() + if err != nil { + return err + } + + for _, chainId := range chainIds { + // create new consumerId + consumerId := pk.FetchAndIncrementConsumerId(ctx) + + // re-key store + + // channelId -> chainId + channelId, found := pk.GetConsumerIdToChannelId(ctx, chainId) + if !found { + return errorsmod.Wrapf(ccv.ErrInvalidConsumerState, "cannot find channel id associated with consumer id: %s", consumerId) + } + pk.SetChannelToConsumerId(ctx, channelId, consumerId) + + // chainId -> channelId + rekeyFromChainIdToConsumerId(store, LegacyChainToChannelKeyPrefix, chainId, consumerId) + + // chainId -> clientId + rekeyFromChainIdToConsumerId(store, LegacyChainToClientKeyPrefix, chainId, consumerId) + + // chainId -> consumer genesis + rekeyFromChainIdToConsumerId(store, ConsumerGenesisKeyPrefix, chainId, consumerId) + + // chainId -> SlashAcks + rekeyFromChainIdToConsumerId(store, SlashAcksKeyPrefix, chainId, consumerId) + + // chainId -> InitChainHeight + rekeyFromChainIdToConsumerId(store, InitChainHeightKeyPrefix, chainId, consumerId) + + // chainId -> PendingVSCs + rekeyFromChainIdToConsumerId(store, PendingVSCsKeyPrefix, chainId, consumerId) + + // chainId -> ConsumerValidators + rekeyChainIdAndConsAddrKey(store, providertypes.ConsumerValidatorsKeyPrefix(), chainId, consumerId) + + // chainId -> ValidatorsByConsumerAddr + rekeyChainIdAndConsAddrKey(store, providertypes.ValidatorsByConsumerAddrKeyPrefix(), chainId, consumerId) + + // chainId -> EquivocationEvidenceMinHeight + rekeyFromChainIdToConsumerId(store, EquivocationEvidenceMinHeightKeyPrefix, chainId, consumerId) + + // chainId -> ConsumerValidator + rekeyChainIdAndConsAddrKey(store, providertypes.ConsumerValidatorKeyPrefix(), chainId, consumerId) + + // chainId -> OptedIn + rekeyChainIdAndConsAddrKey(store, providertypes.OptedInKeyPrefix(), chainId, consumerId) + + // chainId -> Allowlist + rekeyChainIdAndConsAddrKey(store, providertypes.AllowlistKeyPrefix(), chainId, consumerId) + + // chainId -> Denylist + rekeyChainIdAndConsAddrKey(store, providertypes.DenylistKeyPrefix(), chainId, consumerId) + + // chainId -> ConsumerRewardsAllocations + rekeyFromChainIdToConsumerId(store, ConsumerRewardsAllocationKeyPrefix, chainId, consumerId) + + // chainId -> ConsumerCommissionRate + rekeyChainIdAndConsAddrKey(store, providertypes.ConsumerCommissionRateKeyPrefix(), chainId, consumerId) + + // chainId -> MinimumPowerInTopN + oldKey := providertypes.StringIdWithLenKey(MinimumPowerInTopNKeyPrefix, chainId) + value := store.Get(oldKey) + if value != nil { + newKey := providertypes.StringIdWithLenKey(MinimumPowerInTopNKeyPrefix, consumerId) + store.Set(newKey, value) + store.Delete(oldKey) + } + + // chainId -> ConsumerAddrsToPruneV2 + rekeyChainIdAndTsKey(store, providertypes.ConsumerAddrsToPruneV2KeyPrefix(), chainId, consumerId) + + pk.SetConsumerChainId(ctx, consumerId, chainId) + + // set ownership -- all existing chains are owned by gov + pk.SetConsumerOwnerAddress(ctx, consumerId, pk.GetAuthority()) + + // Note: ConsumerMetadata will be populated in the upgrade handler + // Note: InitializationParameters is not needed since the chain is already launched + + // migrate power shaping params + topNKey := providertypes.StringIdWithLenKey(LegacyTopNKeyPrefix, chainId) + var topN uint32 = 0 + buf := store.Get(topNKey) + if buf != nil { + topN = binary.BigEndian.Uint32(buf) + } + + validatorsPowerCapKey := providertypes.StringIdWithLenKey(LegacyValidatorsPowerCapKeyPrefix, chainId) + var validatorsPowerCap uint32 = 0 + buf = store.Get(validatorsPowerCapKey) + if buf != nil { + validatorsPowerCap = binary.BigEndian.Uint32(buf) + } + + validatorSetCapKey := providertypes.StringIdWithLenKey(LegacyValidatorSetCapKeyPrefix, chainId) + var validatorSetCap uint32 = 0 + buf = store.Get(validatorSetCapKey) + if buf != nil { + validatorSetCap = binary.BigEndian.Uint32(buf) + } + + bech32PrefixConsAddr := sdk.GetConfig().GetBech32ConsensusAddrPrefix() + var allowlist []string + for _, addr := range pk.GetAllowList(ctx, consumerId) { + bech32Addr, _ := bech32.ConvertAndEncode(bech32PrefixConsAddr, addr.ToSdkConsAddr().Bytes()) + allowlist = append(allowlist, bech32Addr) + } + + var denylist []string + for _, addr := range pk.GetDenyList(ctx, consumerId) { + bech32Addr, _ := bech32.ConvertAndEncode(bech32PrefixConsAddr, addr.ToSdkConsAddr().Bytes()) + allowlist = append(allowlist, bech32Addr) + } + + powerShapingParameters := providertypes.PowerShapingParameters{ + Top_N: topN, + ValidatorsPowerCap: validatorsPowerCap, + ValidatorSetCap: validatorSetCap, + Allowlist: allowlist, + Denylist: denylist, + // do not set those since they do not exist in a previous interchain-security version and hence cannot be set + MinStake: 0, + AllowInactiveVals: false, + } + err := pk.SetConsumerPowerShapingParameters(ctx, consumerId, powerShapingParameters) + if err != nil { + return err + } + + // set phase to launched + pk.SetConsumerPhase(ctx, consumerId, providertypes.CONSUMER_PHASE_LAUNCHED) + + // This is to migrate everything under `ProviderConsAddrToOptedInConsumerIdsKey` + // `OptedIn` was already re-keyed earlier (see above) and hence we can use `consumerId` here. + for _, providerConsAddr := range pk.GetAllOptedIn(ctx, consumerId) { + err := pk.AppendOptedInConsumerId(ctx, providerConsAddr, consumerId) + if err != nil { + return err + } + } + + // set clientId -> consumerId mapping + // consumer to client was already re-keyed so we can use `consumerId` here + // however, during the rekeying, the reverse index was not set + clientId, found := pk.GetConsumerClientId(ctx, consumerId) + if !found { + return errorsmod.Wrapf(ccv.ErrInvalidConsumerState, "cannot find client ID associated with consumer ID: %s", consumerId) + } + pk.SetConsumerClientId(ctx, consumerId, clientId) + } + + return nil +} + +// rekeyFromChainIdToConsumerId migrates store keys from `keyPrefix | chainId` +// to `keyPrefix | consumerId` leaving the value unchanged +func rekeyFromChainIdToConsumerId( + store storetypes.KVStore, + keyPrefix byte, + chainId, consumerId string, +) { + oldKey := append([]byte{keyPrefix}, []byte(chainId)...) + value := store.Get(oldKey) + if value != nil { + newKey := append([]byte{keyPrefix}, []byte(consumerId)...) + store.Set(newKey, value) + store.Delete(oldKey) + } +} + +// rekeyChainIdAndConsAddrKey migrates store keys +// from `keyPrefix | len(chainID) | chainID | ConsAddress` +// to `keyPrefix | len(consumerId) | consumerId | ConsAddress“ +// leaving the value unchanged +func rekeyChainIdAndConsAddrKey( + store storetypes.KVStore, + keyPrefix byte, + chainId, consumerId string, +) error { + oldPartialKey := providertypes.StringIdWithLenKey(keyPrefix, chainId) + addrs := []sdk.ConsAddress{} + iterator := storetypes.KVStorePrefixIterator(store, oldPartialKey) + for ; iterator.Valid(); iterator.Next() { + _, addr, err := providertypes.ParseStringIdAndConsAddrKey(keyPrefix, iterator.Key()) + if err != nil { + return err + } + addrs = append(addrs, addr) + } + err := iterator.Close() + if err != nil { + return err + } + + for _, addr := range addrs { + oldKey := providertypes.StringIdAndConsAddrKey(keyPrefix, chainId, addr) + value := store.Get(oldKey) + if value == nil { + // this should not happen, but just in case as Set will fail if value is nil + continue + } + newKey := providertypes.StringIdAndConsAddrKey(keyPrefix, consumerId, addr) + store.Set(newKey, value) + store.Delete(oldKey) + } + + return nil +} + +// rekeyChainIdAndTsKey migrates store keys +// from `keyPrefix | len(chainID) | chainID | timestamp` +// to `keyPrefix | len(consumerId) | consumerId | timestamp +// leaving the value unchanged +func rekeyChainIdAndTsKey( + store storetypes.KVStore, + keyPrefix byte, + chainId, consumerId string, +) error { + oldPartialKey := providertypes.StringIdWithLenKey(keyPrefix, chainId) + timestamps := []time.Time{} + iterator := storetypes.KVStorePrefixIterator(store, oldPartialKey) + for ; iterator.Valid(); iterator.Next() { + _, ts, err := providertypes.ParseStringIdAndTsKey(keyPrefix, iterator.Key()) + if err != nil { + return err + } + timestamps = append(timestamps, ts) + } + err := iterator.Close() + if err != nil { + return err + } + + for _, ts := range timestamps { + oldKey := providertypes.StringIdAndTsKey(keyPrefix, chainId, ts) + value := store.Get(oldKey) + if value == nil { + // this should not happen, but just in case as Set will fail if value is nil + continue + } + newKey := providertypes.StringIdAndTsKey(keyPrefix, consumerId, ts) + store.Set(newKey, value) + store.Delete(oldKey) + } + + return nil +} + // CleanupState removes deprecated state func CleanupState(store storetypes.KVStore) { removePrefix(store, LegacyMaturedUnbondingOpsByteKey) @@ -104,6 +394,18 @@ func CleanupState(store storetypes.KVStore) { removePrefix(store, LegacyVscSendTimestampBytePrefix) removePrefix(store, LegacyVSCMaturedHandledThisBlockBytePrefix) removePrefix(store, LegacyConsumerAddrsToPruneBytePrefix) + + removePrefix(store, LegacyPendingCAPKeyPrefix) + removePrefix(store, LegacyPendingCRPKeyPrefix) + removePrefix(store, LegacyProposedConsumerChainKeyPrefix) + + removePrefix(store, LegacyThrottledPacketDataSizeKeyPrefix) + removePrefix(store, LegacyThrottledPacketDataKeyPrefix) + removePrefix(store, LegacyGlobalSlashEntryKeyPrefix) + + removePrefix(store, LegacyTopNKeyPrefix) + removePrefix(store, LegacyValidatorsPowerCapKeyPrefix) + removePrefix(store, LegacyValidatorSetCapKeyPrefix) } func removePrefix(store storetypes.KVStore, prefix byte) { diff --git a/x/ccv/provider/migrations/v8/migrations_test.go b/x/ccv/provider/migrations/v8/migrations_test.go index 8c23fccc64..8f37f84d13 100644 --- a/x/ccv/provider/migrations/v8/migrations_test.go +++ b/x/ccv/provider/migrations/v8/migrations_test.go @@ -14,7 +14,7 @@ import ( ) func legacyConsumerAddrsToPruneKey(chainID string, vscID uint64) []byte { - return providertypes.ChainIdAndUintIdKey(LegacyConsumerAddrsToPruneBytePrefix, chainID, vscID) + return providertypes.StringIdAndUintIdKey(LegacyConsumerAddrsToPruneBytePrefix, chainID, vscID) } func legacyAppendConsumerAddrsToPrune( @@ -44,7 +44,7 @@ func legacyAppendConsumerAddrsToPrune( } func legacyVscSendingTimestampKey(chainID string, vscID uint64) []byte { - return providertypes.ChainIdAndUintIdKey(LegacyVscSendTimestampBytePrefix, chainID, vscID) + return providertypes.StringIdAndUintIdKey(LegacyVscSendTimestampBytePrefix, chainID, vscID) } func legacySetVscSendTimestamp( diff --git a/x/ccv/provider/module.go b/x/ccv/provider/module.go index 320a135a69..2f089509ee 100644 --- a/x/ccv/provider/module.go +++ b/x/ccv/provider/module.go @@ -171,11 +171,12 @@ func (AppModule) ConsensusVersion() uint64 { return 8 } // BeginBlock implements the AppModule interface func (am AppModule) BeginBlock(ctx context.Context) error { - sdkCtx := sdk.UnwrapSDKContext(ctx) // Create clients to consumer chains that are due to be spawned via pending consumer addition proposals + sdkCtx := sdk.UnwrapSDKContext(ctx) - am.keeper.BeginBlockInit(sdkCtx) - // Stop and remove state for any consumer chains that are due to be stopped via pending consumer removal proposals - am.keeper.BeginBlockCCR(sdkCtx) + // Create clients to consumer chains that are due to be spawned + am.keeper.BeginBlockLaunchConsumers(sdkCtx) + // Stop and remove state for any consumer chains that are due to be stopped + am.keeper.BeginBlockRemoveConsumers(sdkCtx) // Check for replenishing slash meter before any slash packets are processed for this block am.keeper.BeginBlockCIS(sdkCtx) // BeginBlock logic needed for the Reward Distribution sub-protocol diff --git a/x/ccv/provider/module_test.go b/x/ccv/provider/module_test.go index 2b2ac1c63f..9cbe5d6f4c 100644 --- a/x/ccv/provider/module_test.go +++ b/x/ccv/provider/module_test.go @@ -104,8 +104,6 @@ func TestInitGenesis(t *testing.T) { providerKeeper.GetValidatorSetUpdateId(ctx), nil, tc.consumerStates, - nil, - nil, types.DefaultParams(), nil, nil, @@ -174,11 +172,11 @@ func TestInitGenesis(t *testing.T) { numStatesCounted := 0 for _, state := range tc.consumerStates { numStatesCounted += 1 - channelID, found := providerKeeper.GetChainToChannel(ctx, state.ChainId) + channelID, found := providerKeeper.GetConsumerIdToChannelId(ctx, state.ChainId) require.True(t, found) require.Equal(t, state.ChannelId, channelID) - chainID, found := providerKeeper.GetChannelToChain(ctx, state.ChannelId) + chainID, found := providerKeeper.GetChannelIdToConsumerId(ctx, state.ChannelId) require.True(t, found) require.Equal(t, state.ChainId, chainID) } diff --git a/x/ccv/provider/proposal_handler.go b/x/ccv/provider/proposal_handler.go index 40a551d185..ea66146039 100644 --- a/x/ccv/provider/proposal_handler.go +++ b/x/ccv/provider/proposal_handler.go @@ -18,13 +18,11 @@ func NewProviderProposalHandler(k keeper.Keeper) govv1beta1.Handler { return func(ctx sdk.Context, content govv1beta1.Content) error { switch c := content.(type) { case *types.ConsumerAdditionProposal: - return k.HandleLegacyConsumerAdditionProposal(ctx, c) + return nil case *types.ConsumerRemovalProposal: - return k.HandleLegacyConsumerRemovalProposal(ctx, c) - case *types.ConsumerModificationProposal: - return k.HandleLegacyConsumerModificationProposal(ctx, c) + return nil case *types.ChangeRewardDenomsProposal: - return k.HandleLegacyConsumerRewardDenomProposal(ctx, c) + return nil default: return errorsmod.Wrapf(sdkerrors.ErrUnknownRequest, "unrecognized ccv proposal content type: %T", c) } diff --git a/x/ccv/provider/proposal_handler_test.go b/x/ccv/provider/proposal_handler_test.go index 67bcad7d15..cf1e82284b 100644 --- a/x/ccv/provider/proposal_handler_test.go +++ b/x/ccv/provider/proposal_handler_test.go @@ -6,14 +6,10 @@ import ( "cosmossdk.io/math" sdk "github.com/cosmos/cosmos-sdk/types" - clienttypes "github.com/cosmos/ibc-go/v8/modules/core/02-client/types" - "github.com/golang/mock/gomock" "github.com/stretchr/testify/require" distributiontypes "github.com/cosmos/cosmos-sdk/x/distribution/types" govv1beta1 "github.com/cosmos/cosmos-sdk/x/gov/types/v1beta1" - stakingtypes "github.com/cosmos/cosmos-sdk/x/staking/types" - testkeeper "github.com/cosmos/interchain-security/v5/testutil/keeper" "github.com/cosmos/interchain-security/v5/x/ccv/provider" providertypes "github.com/cosmos/interchain-security/v5/x/ccv/provider/types" @@ -30,40 +26,9 @@ func TestProviderProposalHandler(t *testing.T) { name string content govv1beta1.Content blockTime time.Time - expValidConsumerAddition bool expValidConsumerRemoval bool expValidChangeRewardDenom bool }{ - { - name: "valid consumer addition proposal", - content: providertypes.NewConsumerAdditionProposal( - "title", "description", "chainID", - clienttypes.NewHeight(2, 3), []byte("gen_hash"), []byte("bin_hash"), now, - "0.75", - 10, - "", - 10000, - 100000000000, - 100000000000, - 100000000000, - 0, - 0, - 0, - nil, - nil, - 0, - false, - ), - blockTime: hourFromNow, // ctx blocktime is after proposal's spawn time - expValidConsumerAddition: true, - }, - { - name: "valid consumer removal proposal", - content: providertypes.NewConsumerRemovalProposal( - "title", "description", "chainID", now), - blockTime: hourFromNow, - expValidConsumerRemoval: true, - }, { name: "valid change reward denoms proposal", content: providertypes.NewChangeRewardDenomsProposal( @@ -93,23 +58,12 @@ func TestProviderProposalHandler(t *testing.T) { // Setup keeperParams := testkeeper.NewInMemKeeperParams(t) - providerKeeper, ctx, _, mocks := testkeeper.GetProviderKeeperAndCtx(t, keeperParams) + providerKeeper, ctx, _, _ := testkeeper.GetProviderKeeperAndCtx(t, keeperParams) providerKeeper.SetParams(ctx, providertypes.DefaultParams()) ctx = ctx.WithBlockTime(tc.blockTime) // Mock expectations depending on expected outcome switch { - case tc.expValidConsumerAddition: - testkeeper.SetupMocksForLastBondedValidatorsExpectation(mocks.MockStakingKeeper, 1, []stakingtypes.Validator{}, 1) - gomock.InOrder(testkeeper.GetMocksForCreateConsumerClient( - ctx, &mocks, "chainID", clienttypes.NewHeight(2, 3), - )...) - - case tc.expValidConsumerRemoval: - testkeeper.SetupForStoppingConsumerChain(t, ctx, &providerKeeper, mocks) - - // assert mocks for expected calls to `StopConsumerChain` when closing the underlying channel - gomock.InOrder(testkeeper.GetMocksForStopConsumerChainWithCloseChannel(ctx, &mocks)...) case tc.expValidChangeRewardDenom: // Nothing to mock } @@ -117,9 +71,7 @@ func TestProviderProposalHandler(t *testing.T) { // Execution proposalHandler := provider.NewProviderProposalHandler(providerKeeper) err := proposalHandler(ctx, tc.content) - - if tc.expValidConsumerAddition || tc.expValidConsumerRemoval || - tc.expValidChangeRewardDenom { + if tc.expValidChangeRewardDenom { require.NoError(t, err) } else { require.Error(t, err) diff --git a/x/ccv/provider/types/codec.go b/x/ccv/provider/types/codec.go index a3593fb22f..bc2ec27fa2 100644 --- a/x/ccv/provider/types/codec.go +++ b/x/ccv/provider/types/codec.go @@ -19,20 +19,19 @@ func RegisterInterfaces(registry codectypes.InterfaceRegistry) { registry.RegisterImplementations( (*govv1beta1.Content)(nil), &ConsumerAdditionProposal{}, - ) - registry.RegisterImplementations( - (*govv1beta1.Content)(nil), &ConsumerRemovalProposal{}, - ) - registry.RegisterImplementations( - (*govv1beta1.Content)(nil), &ConsumerModificationProposal{}, + &ChangeRewardDenomsProposal{}, ) registry.RegisterImplementations( (*sdk.Msg)(nil), - &MsgAssignConsumerKey{}, &MsgConsumerAddition{}, &MsgConsumerRemoval{}, + &MsgConsumerModification{}, + &MsgAssignConsumerKey{}, + &MsgCreateConsumer{}, + &MsgUpdateConsumer{}, + &MsgRemoveConsumer{}, &MsgChangeRewardDenoms{}, &MsgUpdateParams{}, ) @@ -41,10 +40,6 @@ func RegisterInterfaces(registry codectypes.InterfaceRegistry) { (*govv1beta1.Content)(nil), &EquivocationProposal{}, ) - registry.RegisterImplementations( - (*govv1beta1.Content)(nil), - &ChangeRewardDenomsProposal{}, - ) registry.RegisterImplementations( (*sdk.Msg)(nil), &MsgSubmitConsumerMisbehaviour{}, diff --git a/x/ccv/provider/types/consumer.go b/x/ccv/provider/types/consumer.go index 37c286422f..ebc1bcbf30 100644 --- a/x/ccv/provider/types/consumer.go +++ b/x/ccv/provider/types/consumer.go @@ -12,6 +12,7 @@ func NewConsumerStates( genesis ccv.ConsumerGenesisState, pendingValsetChanges []ccv.ValidatorSetChangePacketData, slashDowntimeAck []string, + phase ConsumerPhase, ) ConsumerState { return ConsumerState{ ChainId: chainID, @@ -21,5 +22,6 @@ func NewConsumerStates( PendingValsetChanges: pendingValsetChanges, ConsumerGenesis: genesis, SlashDowntimeAck: slashDowntimeAck, + Phase: phase, } } diff --git a/x/ccv/provider/types/errors.go b/x/ccv/provider/types/errors.go index 5109489d76..2d87ee1345 100644 --- a/x/ccv/provider/types/errors.go +++ b/x/ccv/provider/types/errors.go @@ -6,30 +6,43 @@ import ( // Provider sentinel errors var ( - ErrInvalidConsumerAdditionProposal = errorsmod.Register(ModuleName, 1, "invalid consumer addition proposal") - ErrInvalidConsumerRemovalProp = errorsmod.Register(ModuleName, 2, "invalid consumer removal proposal") - ErrUnknownConsumerChainId = errorsmod.Register(ModuleName, 3, "no consumer chain with this chain id") - ErrUnknownConsumerChannelId = errorsmod.Register(ModuleName, 4, "no consumer chain with this channel id") - ErrInvalidConsumerConsensusPubKey = errorsmod.Register(ModuleName, 5, "empty consumer consensus public key") - ErrInvalidConsumerChainID = errorsmod.Register(ModuleName, 6, "invalid consumer chain id") - ErrConsumerKeyNotFound = errorsmod.Register(ModuleName, 7, "consumer key not found") - ErrNoValidatorConsumerAddress = errorsmod.Register(ModuleName, 8, "error getting validator consumer address") - ErrNoValidatorProviderAddress = errorsmod.Register(ModuleName, 9, "error getting validator provider address") - ErrConsumerKeyInUse = errorsmod.Register(ModuleName, 10, "consumer key is already in use by a validator") - ErrCannotAssignDefaultKeyAssignment = errorsmod.Register(ModuleName, 11, "cannot re-assign default key assignment") - ErrInvalidConsumerParams = errorsmod.Register(ModuleName, 12, "invalid consumer params") - ErrInvalidProviderAddress = errorsmod.Register(ModuleName, 13, "invalid provider address") - ErrInvalidConsumerRewardDenom = errorsmod.Register(ModuleName, 14, "invalid consumer reward denom") - ErrInvalidDepositorAddress = errorsmod.Register(ModuleName, 15, "invalid depositor address") - ErrInvalidConsumerClient = errorsmod.Register(ModuleName, 16, "ccv channel is not built on correct client") - ErrDuplicateConsumerChain = errorsmod.Register(ModuleName, 17, "consumer chain already exists") - ErrConsumerChainNotFound = errorsmod.Register(ModuleName, 18, "consumer chain not found") - ErrInvalidConsumerCommissionRate = errorsmod.Register(ModuleName, 19, "consumer commission rate is invalid") - ErrCannotOptOutFromTopN = errorsmod.Register(ModuleName, 20, "cannot opt out from a Top N chain") - ErrNoUnconfirmedVSCPacket = errorsmod.Register(ModuleName, 21, "no unconfirmed vsc packet for this chain id") - ErrInvalidConsumerModificationProposal = errorsmod.Register(ModuleName, 22, "invalid consumer modification proposal") - ErrNoUnbondingTime = errorsmod.Register(ModuleName, 23, "provider unbonding time not found") - ErrInvalidAddress = errorsmod.Register(ModuleName, 24, "invalid address") - ErrUnauthorized = errorsmod.Register(ModuleName, 25, "unauthorized") - ErrBlankConsumerChainID = errorsmod.Register(ModuleName, 26, "consumer chain id must not be blank") + ErrInvalidConsumerAdditionProposal = errorsmod.Register(ModuleName, 1, "invalid consumer addition proposal") + ErrInvalidConsumerRemovalProp = errorsmod.Register(ModuleName, 2, "invalid consumer removal proposal") + ErrUnknownConsumerId = errorsmod.Register(ModuleName, 3, "no consumer chain with this consumer id") + ErrUnknownConsumerChannelId = errorsmod.Register(ModuleName, 4, "no consumer chain with this channel id") + ErrInvalidConsumerId = errorsmod.Register(ModuleName, 6, "invalid consumer id") + ErrConsumerKeyInUse = errorsmod.Register(ModuleName, 10, "consumer key is already in use by a validator") + ErrCannotAssignDefaultKeyAssignment = errorsmod.Register(ModuleName, 11, "cannot re-assign default key assignment") + ErrInvalidConsumerRewardDenom = errorsmod.Register(ModuleName, 14, "invalid consumer reward denom") + ErrInvalidConsumerClient = errorsmod.Register(ModuleName, 16, "ccv channel is not built on correct client") + ErrConsumerChainNotFound = errorsmod.Register(ModuleName, 18, "consumer chain not found") + ErrCannotOptOutFromTopN = errorsmod.Register(ModuleName, 20, "cannot opt out from a Top N chain") + ErrInvalidConsumerModificationProposal = errorsmod.Register(ModuleName, 22, "invalid consumer modification proposal") + ErrNoUnbondingTime = errorsmod.Register(ModuleName, 23, "provider unbonding time not found") + ErrUnauthorized = errorsmod.Register(ModuleName, 25, "unauthorized") + ErrBlankConsumerChainID = errorsmod.Register(ModuleName, 26, "consumer chain id must not be blank") + ErrInvalidPhase = errorsmod.Register(ModuleName, 27, "cannot perform action in the current phase of consumer chain") + ErrInvalidConsumerMetadata = errorsmod.Register(ModuleName, 28, "invalid consumer metadata") + ErrInvalidPowerShapingParameters = errorsmod.Register(ModuleName, 29, "invalid power shaping parameters") + ErrInvalidConsumerInitializationParameters = errorsmod.Register(ModuleName, 30, "invalid consumer initialization parameters") + ErrCannotUpdateMinimumPowerInTopN = errorsmod.Register(ModuleName, 31, "cannot update minimum power in Top N") + ErrNoConsumerGenesis = errorsmod.Register(ModuleName, 33, "missing consumer genesis") + ErrInvalidConsumerGenesis = errorsmod.Register(ModuleName, 34, "invalid consumer genesis") + ErrNoConsumerId = errorsmod.Register(ModuleName, 35, "missing consumer id") + ErrAlreadyOptedIn = errorsmod.Register(ModuleName, 36, "already opted in to a chain with the same chain id") + ErrNoOwnerAddress = errorsmod.Register(ModuleName, 37, "missing owner address") + ErrInvalidNewOwnerAddress = errorsmod.Register(ModuleName, 38, "invalid new owner address") + ErrInvalidTransformToTopN = errorsmod.Register(ModuleName, 39, "invalid transform to Top N chain") + ErrInvalidTransformToOptIn = errorsmod.Register(ModuleName, 40, "invalid transform to Opt In chain") + ErrCannotCreateTopNChain = errorsmod.Register(ModuleName, 41, "cannot create Top N chain outside permissionlessly") + ErrInvalidRemovalTime = errorsmod.Register(ModuleName, 43, "invalid removal time") + ErrInvalidMsgCreateConsumer = errorsmod.Register(ModuleName, 44, "invalid create consumer message") + ErrInvalidMsgUpdateConsumer = errorsmod.Register(ModuleName, 45, "invalid update consumer message") + ErrInvalidMsgAssignConsumerKey = errorsmod.Register(ModuleName, 46, "invalid assign consumer key message") + ErrInvalidMsgSubmitConsumerMisbehaviour = errorsmod.Register(ModuleName, 47, "invalid submit consumer misbehaviour message") + ErrInvalidMsgSubmitConsumerDoubleVoting = errorsmod.Register(ModuleName, 48, "invalid submit consumer double voting message") + ErrInvalidMsgOptIn = errorsmod.Register(ModuleName, 49, "invalid opt in message") + ErrInvalidMsgOptOut = errorsmod.Register(ModuleName, 50, "invalid opt out message") + ErrInvalidMsgSetConsumerCommissionRate = errorsmod.Register(ModuleName, 51, "invalid set consumer commission rate message") + ErrInvalidMsgChangeRewardDenoms = errorsmod.Register(ModuleName, 52, "invalid change reward denoms message") ) diff --git a/x/ccv/provider/types/events.go b/x/ccv/provider/types/events.go index 9abcba7836..77992a7e02 100644 --- a/x/ccv/provider/types/events.go +++ b/x/ccv/provider/types/events.go @@ -4,19 +4,30 @@ package types const ( EventTypeConsumerClientCreated = "consumer_client_created" EventTypeAssignConsumerKey = "assign_consumer_key" - EventTypeAddConsumerRewardDenom = "add_consumer_reward_denom" - EventTypeRemoveConsumerRewardDenom = "remove_consumer_reward_denom" + EventTypeChangeConsumerRewardDenom = "change_consumer_reward_denom" EventTypeExecuteConsumerChainSlash = "execute_consumer_chain_slash" EventTypeSetConsumerCommissionRate = "set_consumer_commission_rate" EventTypeOptIn = "opt_in" EventTypeOptOut = "opt_out" + EventTypeCreateConsumer = "create_consumer" + EventTypeUpdateConsumer = "update_consumer" + EventTypeRemoveConsumer = "remove_consumer" + AttributeInfractionHeight = "infraction_height" AttributeInitialHeight = "initial_height" AttributeTrustingPeriod = "trusting_period" AttributeUnbondingPeriod = "unbonding_period" AttributeProviderValidatorAddress = "provider_validator_address" AttributeConsumerConsensusPubKey = "consumer_consensus_pub_key" - AttributeConsumerRewardDenom = "consumer_reward_denom" + AttributeAddConsumerRewardDenom = "add_consumer_reward_denom" + AttributeRemoveConsumerRewardDenom = "remove_consumer_reward_denom" + AttributeSubmitterAddress = "submitter_address" AttributeConsumerCommissionRate = "consumer_commission_rate" - AttributeConsumerChainID = "consumer_chain_id" + AttributeConsumerId = "consumer_id" + AttributeConsumerChainId = "consumer_chain_id" + AttributeConsumerName = "consumer_name" + AttributeConsumerOwner = "consumer_owner" + AttributeConsumerSpawnTime = "consumer_spawn_time" + AttributeConsumerPhase = "consumer_phase" + AttributeConsumerTopN = "consumer_topn" ) diff --git a/x/ccv/provider/types/genesis.go b/x/ccv/provider/types/genesis.go index 5cd60982a6..be4b9d8934 100644 --- a/x/ccv/provider/types/genesis.go +++ b/x/ccv/provider/types/genesis.go @@ -16,23 +16,19 @@ func NewGenesisState( vscID uint64, vscIdToHeights []ValsetUpdateIdToHeight, consumerStates []ConsumerState, - additionProposals []ConsumerAdditionProposal, - removalProposals []ConsumerRemovalProposal, params Params, validatorConsumerPubkeys []ValidatorConsumerPubKey, validatorsByConsumerAddr []ValidatorByConsumerAddr, consumerAddrsToPrune []ConsumerAddrsToPruneV2, ) *GenesisState { return &GenesisState{ - ValsetUpdateId: vscID, - ValsetUpdateIdToHeight: vscIdToHeights, - ConsumerStates: consumerStates, - ConsumerAdditionProposals: additionProposals, - ConsumerRemovalProposals: removalProposals, - Params: params, - ValidatorConsumerPubkeys: validatorConsumerPubkeys, - ValidatorsByConsumerAddr: validatorsByConsumerAddr, - ConsumerAddrsToPruneV2: consumerAddrsToPrune, + ValsetUpdateId: vscID, + ValsetUpdateIdToHeight: vscIdToHeights, + ConsumerStates: consumerStates, + Params: params, + ValidatorConsumerPubkeys: validatorConsumerPubkeys, + ValidatorsByConsumerAddr: validatorsByConsumerAddr, + ConsumerAddrsToPruneV2: consumerAddrsToPrune, } } @@ -49,18 +45,6 @@ func (gs GenesisState) Validate() error { return errorsmod.Wrap(ccv.ErrInvalidGenesis, "valset update ID cannot be equal to zero") } - for _, prop := range gs.ConsumerAdditionProposals { - if err := prop.ValidateBasic(); err != nil { - return errorsmod.Wrap(ccv.ErrInvalidGenesis, err.Error()) - } - } - - for _, prop := range gs.ConsumerRemovalProposals { - if err := prop.ValidateBasic(); err != nil { - return errorsmod.Wrap(ccv.ErrInvalidGenesis, err.Error()) - } - } - if len(gs.ValsetUpdateIdToHeight) > 0 { // check only the first tuple of the list since it is ordered by VSC ID if gs.ValsetUpdateIdToHeight[0].ValsetUpdateId == 0 { diff --git a/x/ccv/provider/types/genesis.pb.go b/x/ccv/provider/types/genesis.pb.go index 7097cd1a2b..bbf069fec6 100644 --- a/x/ccv/provider/types/genesis.pb.go +++ b/x/ccv/provider/types/genesis.pb.go @@ -32,11 +32,7 @@ type GenesisState struct { ConsumerStates []ConsumerState `protobuf:"bytes,2,rep,name=consumer_states,json=consumerStates,proto3" json:"consumer_states" yaml:"consumer_states"` // empty for a new chain ValsetUpdateIdToHeight []ValsetUpdateIdToHeight `protobuf:"bytes,5,rep,name=valset_update_id_to_height,json=valsetUpdateIdToHeight,proto3" json:"valset_update_id_to_height"` - // empty for a new chain - ConsumerAdditionProposals []ConsumerAdditionProposal `protobuf:"bytes,6,rep,name=consumer_addition_proposals,json=consumerAdditionProposals,proto3" json:"consumer_addition_proposals"` - // empty for a new chain - ConsumerRemovalProposals []ConsumerRemovalProposal `protobuf:"bytes,7,rep,name=consumer_removal_proposals,json=consumerRemovalProposals,proto3" json:"consumer_removal_proposals"` - Params Params `protobuf:"bytes,8,opt,name=params,proto3" json:"params"` + Params Params `protobuf:"bytes,8,opt,name=params,proto3" json:"params"` // empty for a new chain ValidatorConsumerPubkeys []ValidatorConsumerPubKey `protobuf:"bytes,9,rep,name=validator_consumer_pubkeys,json=validatorConsumerPubkeys,proto3" json:"validator_consumer_pubkeys"` // empty for a new chain @@ -99,20 +95,6 @@ func (m *GenesisState) GetValsetUpdateIdToHeight() []ValsetUpdateIdToHeight { return nil } -func (m *GenesisState) GetConsumerAdditionProposals() []ConsumerAdditionProposal { - if m != nil { - return m.ConsumerAdditionProposals - } - return nil -} - -func (m *GenesisState) GetConsumerRemovalProposals() []ConsumerRemovalProposal { - if m != nil { - return m.ConsumerRemovalProposals - } - return nil -} - func (m *GenesisState) GetParams() Params { if m != nil { return m.Params @@ -159,6 +141,8 @@ type ConsumerState struct { // consumer chain PendingValsetChanges []types.ValidatorSetChangePacketData `protobuf:"bytes,6,rep,name=pending_valset_changes,json=pendingValsetChanges,proto3" json:"pending_valset_changes"` SlashDowntimeAck []string `protobuf:"bytes,7,rep,name=slash_downtime_ack,json=slashDowntimeAck,proto3" json:"slash_downtime_ack,omitempty"` + // the phase of the consumer chain + Phase ConsumerPhase `protobuf:"varint,9,opt,name=phase,proto3,enum=interchain_security.ccv.provider.v1.ConsumerPhase" json:"phase,omitempty"` } func (m *ConsumerState) Reset() { *m = ConsumerState{} } @@ -243,6 +227,13 @@ func (m *ConsumerState) GetSlashDowntimeAck() []string { return nil } +func (m *ConsumerState) GetPhase() ConsumerPhase { + if m != nil { + return m.Phase + } + return CONSUMER_PHASE_UNSPECIFIED +} + // ValsetUpdateIdToHeight defines the genesis information for the mapping // of each valset update id to a block height type ValsetUpdateIdToHeight struct { @@ -308,56 +299,54 @@ func init() { } var fileDescriptor_48411d9c7900d48e = []byte{ - // 782 bytes of a gzipped FileDescriptorProto - 0x1f, 0x8b, 0x08, 0x00, 0x00, 0x00, 0x00, 0x00, 0x02, 0xff, 0x9c, 0x55, 0xd1, 0x6e, 0xda, 0x48, - 0x14, 0xc5, 0xc1, 0x21, 0x66, 0x12, 0x58, 0xcb, 0x8a, 0x90, 0x43, 0xb4, 0x24, 0x62, 0x15, 0x09, - 0x69, 0x77, 0x71, 0x60, 0xb5, 0xd2, 0x6a, 0x77, 0xf3, 0x10, 0x12, 0x69, 0x17, 0xfa, 0x82, 0x48, - 0x9a, 0x4a, 0x79, 0xb1, 0x86, 0xf1, 0x08, 0x46, 0x18, 0x8f, 0xe5, 0x19, 0x9c, 0xa2, 0xaa, 0x52, - 0xab, 0xfe, 0x40, 0x9f, 0xfb, 0x0d, 0xfd, 0x90, 0x3c, 0xe6, 0xb1, 0x4f, 0x51, 0x95, 0xfc, 0x41, - 0xbf, 0xa0, 0xf2, 0x78, 0xec, 0x42, 0x4a, 0x22, 0xe8, 0x1b, 0xcc, 0x99, 0x73, 0xee, 0xb9, 0xd7, - 0xf7, 0xde, 0x01, 0x0d, 0xe2, 0x71, 0x1c, 0xa0, 0x21, 0x24, 0x9e, 0xcd, 0x30, 0x9a, 0x04, 0x84, - 0x4f, 0x2d, 0x84, 0x42, 0xcb, 0x0f, 0x68, 0x48, 0x1c, 0x1c, 0x58, 0x61, 0xc3, 0x1a, 0x60, 0x0f, - 0x33, 0xc2, 0xea, 0x7e, 0x40, 0x39, 0x35, 0x7e, 0x59, 0x40, 0xa9, 0x23, 0x14, 0xd6, 0x13, 0x4a, - 0x3d, 0x6c, 0x94, 0xb7, 0x07, 0x74, 0x40, 0xc5, 0x7d, 0x2b, 0xfa, 0x15, 0x53, 0xcb, 0x87, 0x8f, - 0x45, 0x0b, 0x1b, 0x16, 0x1b, 0xc2, 0x00, 0x3b, 0x36, 0xa2, 0x1e, 0x9b, 0x8c, 0x71, 0x20, 0x19, - 0x07, 0x4f, 0x30, 0xae, 0x48, 0x80, 0xe5, 0xb5, 0xe6, 0x32, 0x69, 0xa4, 0xfe, 0x04, 0xa7, 0xfa, - 0x51, 0x03, 0x5b, 0xff, 0xc5, 0x99, 0x9d, 0x71, 0xc8, 0xb1, 0x51, 0x03, 0x7a, 0x08, 0x5d, 0x86, - 0xb9, 0x3d, 0xf1, 0x1d, 0xc8, 0xb1, 0x4d, 0x1c, 0x53, 0xd9, 0x57, 0x6a, 0x6a, 0xaf, 0x18, 0x9f, - 0x3f, 0x17, 0xc7, 0x6d, 0xc7, 0x78, 0x05, 0x7e, 0x4a, 0x7c, 0xda, 0x2c, 0xe2, 0x32, 0x73, 0x6d, - 0x3f, 0x5b, 0xdb, 0x6c, 0x36, 0xeb, 0x4b, 0x14, 0xa7, 0x7e, 0x22, 0xb9, 0x22, 0x6c, 0xab, 0x72, - 0x7d, 0xbb, 0x97, 0xf9, 0x72, 0xbb, 0x57, 0x9a, 0xc2, 0xb1, 0xfb, 0x77, 0xf5, 0x81, 0x70, 0xb5, - 0x57, 0x44, 0xb3, 0xd7, 0x99, 0xf1, 0x1a, 0x94, 0x1f, 0xda, 0xb4, 0x39, 0xb5, 0x87, 0x98, 0x0c, - 0x86, 0xdc, 0x5c, 0x17, 0x3e, 0xfe, 0x59, 0xca, 0xc7, 0xc5, 0x5c, 0x56, 0xe7, 0xf4, 0x7f, 0x21, - 0xd1, 0x52, 0x23, 0x43, 0xbd, 0x52, 0xb8, 0x10, 0x35, 0xde, 0x29, 0x60, 0x37, 0xf5, 0x08, 0x1d, - 0x87, 0x70, 0x42, 0x3d, 0xdb, 0x0f, 0xa8, 0x4f, 0x19, 0x74, 0x99, 0x99, 0x13, 0x06, 0x8e, 0x56, - 0x2a, 0xc4, 0xb1, 0x94, 0xe9, 0x4a, 0x15, 0x69, 0x61, 0x07, 0x3d, 0x82, 0x33, 0xe3, 0x8d, 0x02, - 0xca, 0xa9, 0x8b, 0x00, 0x8f, 0x69, 0x08, 0xdd, 0x19, 0x13, 0x1b, 0xc2, 0xc4, 0xbf, 0x2b, 0x99, - 0xe8, 0xc5, 0x2a, 0x0f, 0x3c, 0x98, 0x68, 0x31, 0xcc, 0x8c, 0x36, 0xc8, 0xf9, 0x30, 0x80, 0x63, - 0x66, 0x6a, 0xfb, 0x4a, 0x6d, 0xb3, 0xf9, 0xeb, 0x52, 0xd1, 0xba, 0x82, 0x22, 0xc5, 0xa5, 0x80, - 0xc8, 0x26, 0x84, 0x2e, 0x71, 0x20, 0xa7, 0x41, 0x3a, 0x02, 0xb6, 0x3f, 0xe9, 0x8f, 0xf0, 0x94, - 0x99, 0xf9, 0x15, 0xb2, 0xb9, 0x48, 0x64, 0x92, 0xb4, 0xba, 0x93, 0xfe, 0x33, 0x3c, 0x4d, 0xb2, - 0x09, 0x17, 0xc0, 0x51, 0x0c, 0xe3, 0xad, 0x02, 0x76, 0x53, 0x90, 0xd9, 0xfd, 0xa9, 0x3d, 0xfb, - 0x91, 0x03, 0x13, 0xfc, 0x88, 0x87, 0xd6, 0x74, 0xe6, 0x0b, 0x07, 0xdf, 0x79, 0x60, 0xf3, 0x78, - 0xd4, 0xd9, 0x73, 0x41, 0x59, 0xd4, 0xd7, 0x7e, 0x30, 0xf1, 0xb0, 0x1d, 0x36, 0xcd, 0xe2, 0x0a, - 0x9d, 0x3d, 0x2b, 0xcb, 0xce, 0x69, 0x37, 0xd2, 0xb8, 0x68, 0x26, 0x9d, 0x8d, 0x16, 0xa2, 0x1d, - 0x55, 0xcb, 0xea, 0x6a, 0x47, 0xd5, 0x54, 0x7d, 0xbd, 0xa3, 0x6a, 0x9b, 0xfa, 0x56, 0x47, 0xd5, - 0xb6, 0xf4, 0x42, 0x47, 0xd5, 0x0a, 0x7a, 0xb1, 0xfa, 0x21, 0x0b, 0x0a, 0x73, 0x83, 0x6b, 0xec, - 0x00, 0x2d, 0xb6, 0x21, 0xf7, 0x44, 0xbe, 0xb7, 0x21, 0xfe, 0xb7, 0x1d, 0xe3, 0x67, 0x00, 0xd0, - 0x10, 0x7a, 0x1e, 0x76, 0x23, 0x70, 0x4d, 0x80, 0x79, 0x79, 0xd2, 0x76, 0x8c, 0x5d, 0x90, 0x47, - 0x2e, 0xc1, 0x1e, 0x8f, 0xd0, 0xac, 0x40, 0xb5, 0xf8, 0xa0, 0xed, 0x18, 0x07, 0xa0, 0x48, 0x3c, - 0xc2, 0x09, 0x74, 0x93, 0x99, 0x56, 0xc5, 0x12, 0x2a, 0xc8, 0x53, 0x39, 0x87, 0x10, 0xe8, 0x69, - 0xb1, 0xe4, 0x82, 0x36, 0xd7, 0x45, 0x23, 0x1e, 0x3e, 0x5a, 0xa2, 0x99, 0xca, 0xcc, 0x6e, 0x3e, - 0x59, 0x97, 0x74, 0xa7, 0x49, 0xcc, 0xe0, 0xa0, 0xe4, 0x63, 0xcf, 0x21, 0xde, 0xc0, 0x96, 0x1b, - 0x27, 0x4a, 0x61, 0x80, 0x93, 0x21, 0xff, 0xeb, 0xa9, 0x40, 0x69, 0x13, 0x9c, 0x61, 0x7e, 0x22, - 0x68, 0x5d, 0x88, 0x46, 0x98, 0x9f, 0x42, 0x0e, 0x65, 0xc0, 0x6d, 0xa9, 0x1e, 0xef, 0xa1, 0xf8, - 0x12, 0x33, 0x7e, 0x03, 0x06, 0x73, 0x21, 0x1b, 0xda, 0x0e, 0xbd, 0xf2, 0x38, 0x19, 0x63, 0x1b, - 0xa2, 0x91, 0x98, 0xe8, 0x7c, 0x4f, 0x17, 0xc8, 0xa9, 0x04, 0x8e, 0xd1, 0xa8, 0xa3, 0x6a, 0x9a, - 0x9e, 0xaf, 0x5e, 0x82, 0xd2, 0xe2, 0x65, 0xb6, 0xc2, 0x52, 0x2f, 0x81, 0x9c, 0xac, 0xf7, 0x9a, - 0xc0, 0xe5, 0xbf, 0xd6, 0x8b, 0xeb, 0xbb, 0x8a, 0x72, 0x73, 0x57, 0x51, 0x3e, 0xdf, 0x55, 0x94, - 0xf7, 0xf7, 0x95, 0xcc, 0xcd, 0x7d, 0x25, 0xf3, 0xe9, 0xbe, 0x92, 0xb9, 0x3c, 0x1a, 0x10, 0x3e, - 0x9c, 0xf4, 0xeb, 0x88, 0x8e, 0x2d, 0x44, 0xd9, 0x98, 0x32, 0xeb, 0x5b, 0x41, 0x7e, 0x4f, 0xdf, - 0xa1, 0xf0, 0x4f, 0xeb, 0xe5, 0xfc, 0x63, 0xc4, 0xa7, 0x3e, 0x66, 0xfd, 0x9c, 0x78, 0x87, 0xfe, - 0xf8, 0x1a, 0x00, 0x00, 0xff, 0xff, 0xa4, 0x95, 0x75, 0xdb, 0x84, 0x07, 0x00, 0x00, + // 750 bytes of a gzipped FileDescriptorProto + 0x1f, 0x8b, 0x08, 0x00, 0x00, 0x00, 0x00, 0x00, 0x02, 0xff, 0x9c, 0x54, 0xdd, 0x6e, 0xda, 0x48, + 0x14, 0xc6, 0xc1, 0x80, 0x99, 0x04, 0xd6, 0xb2, 0x22, 0xe4, 0x4d, 0xb4, 0x04, 0xb1, 0x8a, 0x84, + 0xb4, 0xbb, 0x38, 0xb0, 0xaa, 0x54, 0xf5, 0xe7, 0x22, 0x24, 0x52, 0x83, 0x7b, 0x83, 0x48, 0x9a, + 0x4a, 0xb9, 0xb1, 0x86, 0x99, 0x11, 0x1e, 0x01, 0xb6, 0xe5, 0x19, 0x9c, 0xa2, 0xaa, 0x52, 0xfb, + 0x06, 0x7d, 0x93, 0xbe, 0x46, 0x2e, 0x73, 0xd9, 0xab, 0xa8, 0x4a, 0xfa, 0x04, 0x7d, 0x82, 0xca, + 0xe3, 0x81, 0x40, 0x4a, 0x22, 0xd2, 0x3b, 0xfb, 0x7c, 0xf3, 0x9d, 0xf3, 0x9d, 0x5f, 0xd0, 0xa0, + 0x1e, 0x27, 0x21, 0x72, 0x21, 0xf5, 0x1c, 0x46, 0xd0, 0x38, 0xa4, 0x7c, 0x62, 0x21, 0x14, 0x59, + 0x41, 0xe8, 0x47, 0x14, 0x93, 0xd0, 0x8a, 0x1a, 0x56, 0x9f, 0x78, 0x84, 0x51, 0x56, 0x0f, 0x42, + 0x9f, 0xfb, 0xc6, 0xdf, 0x4b, 0x28, 0x75, 0x84, 0xa2, 0xfa, 0x94, 0x52, 0x8f, 0x1a, 0x5b, 0x9b, + 0x7d, 0xbf, 0xef, 0x8b, 0xf7, 0x56, 0xfc, 0x95, 0x50, 0xb7, 0xf6, 0xee, 0x8b, 0x16, 0x35, 0x2c, + 0xe6, 0xc2, 0x90, 0x60, 0x07, 0xf9, 0x1e, 0x1b, 0x8f, 0x48, 0x28, 0x19, 0xbb, 0x0f, 0x30, 0xce, + 0x69, 0x48, 0xe4, 0xb3, 0xe6, 0x2a, 0x69, 0xcc, 0xf4, 0x09, 0x4e, 0xf5, 0x4b, 0x16, 0x6c, 0xbc, + 0x4a, 0x32, 0x3b, 0xe6, 0x90, 0x13, 0xa3, 0x06, 0xf4, 0x08, 0x0e, 0x19, 0xe1, 0xce, 0x38, 0xc0, + 0x90, 0x13, 0x87, 0x62, 0x53, 0xa9, 0x28, 0x35, 0xb5, 0x5b, 0x4c, 0xec, 0x6f, 0x84, 0xb9, 0x8d, + 0x8d, 0xf7, 0xe0, 0x8f, 0xa9, 0x4e, 0x87, 0xc5, 0x5c, 0x66, 0xae, 0x55, 0xd2, 0xb5, 0xf5, 0x66, + 0xb3, 0xbe, 0x42, 0x71, 0xea, 0x07, 0x92, 0x2b, 0xc2, 0xb6, 0xca, 0x17, 0x57, 0x3b, 0xa9, 0x1f, + 0x57, 0x3b, 0xa5, 0x09, 0x1c, 0x0d, 0x9f, 0x55, 0xef, 0x38, 0xae, 0x76, 0x8b, 0x68, 0xfe, 0x39, + 0x33, 0x3e, 0x80, 0xad, 0xbb, 0x32, 0x1d, 0xee, 0x3b, 0x2e, 0xa1, 0x7d, 0x97, 0x9b, 0x19, 0xa1, + 0xe3, 0xf9, 0x4a, 0x3a, 0x4e, 0x17, 0xb2, 0x3a, 0xf1, 0x8f, 0x84, 0x8b, 0x96, 0x1a, 0x0b, 0xea, + 0x96, 0xa2, 0xa5, 0xa8, 0xd1, 0x06, 0xd9, 0x00, 0x86, 0x70, 0xc4, 0x4c, 0xad, 0xa2, 0xd4, 0xd6, + 0x9b, 0xff, 0xac, 0x14, 0xaa, 0x23, 0x28, 0xd2, 0xb5, 0x74, 0x60, 0x7c, 0x54, 0x44, 0x2a, 0x14, + 0x43, 0xee, 0x87, 0xb3, 0xce, 0x3b, 0xc1, 0xb8, 0x37, 0x20, 0x13, 0x66, 0xe6, 0x45, 0x2a, 0x2f, + 0x56, 0x4d, 0x25, 0x71, 0x33, 0xad, 0x6d, 0x67, 0xdc, 0x7b, 0x4d, 0x26, 0x32, 0xa0, 0x19, 0x2d, + 0x81, 0xe3, 0x18, 0xc6, 0x27, 0x05, 0x6c, 0xcf, 0x40, 0xe6, 0xf4, 0x26, 0xb7, 0x32, 0x20, 0xc6, + 0xa1, 0x09, 0x7e, 0x47, 0x43, 0x6b, 0x32, 0x0d, 0xb3, 0x8f, 0x71, 0xf8, 0x8b, 0x06, 0xb6, 0x88, + 0xc7, 0x0d, 0x5d, 0x08, 0xca, 0xe2, 0x76, 0x06, 0xe1, 0xd8, 0x23, 0x4e, 0xd4, 0x34, 0x8b, 0x8f, + 0x68, 0xe8, 0xbc, 0x5b, 0x76, 0xe2, 0x77, 0x62, 0x1f, 0xa7, 0xcd, 0x69, 0x43, 0xd1, 0x52, 0xd4, + 0x56, 0xb5, 0xb4, 0xae, 0xda, 0xaa, 0xa6, 0xea, 0x19, 0x5b, 0xd5, 0xb2, 0x7a, 0xce, 0x56, 0xb5, + 0x9c, 0xae, 0xd9, 0xaa, 0xb6, 0xae, 0x6f, 0xd8, 0xaa, 0xb6, 0xa1, 0x17, 0x6c, 0x55, 0x2b, 0xe8, + 0xc5, 0xea, 0xf7, 0x34, 0x28, 0x2c, 0xcc, 0xae, 0xf1, 0x27, 0xd0, 0x12, 0x49, 0x72, 0x55, 0xf2, + 0xdd, 0x9c, 0xf8, 0x6f, 0x63, 0xe3, 0x2f, 0x00, 0x90, 0x0b, 0x3d, 0x8f, 0x0c, 0x63, 0x70, 0x4d, + 0x80, 0x79, 0x69, 0x69, 0x63, 0x63, 0x1b, 0xe4, 0xd1, 0x90, 0x12, 0x8f, 0xc7, 0x68, 0x5a, 0xa0, + 0x5a, 0x62, 0x68, 0x63, 0x63, 0x17, 0x14, 0xa9, 0x47, 0x39, 0x85, 0xc3, 0xe9, 0x58, 0xab, 0x62, + 0x0f, 0x0b, 0xd2, 0x2a, 0x47, 0x11, 0x02, 0x7d, 0x56, 0x38, 0x79, 0xa3, 0xcc, 0x8c, 0x18, 0xca, + 0xbd, 0x7b, 0xcb, 0x35, 0x57, 0xa5, 0xf9, 0xe5, 0x97, 0x35, 0x9a, 0xad, 0xb5, 0xc4, 0x0c, 0x0e, + 0x4a, 0x01, 0xf1, 0x30, 0xf5, 0xfa, 0x8e, 0x5c, 0xba, 0x38, 0x85, 0x3e, 0x61, 0x66, 0x56, 0xf4, + 0xe5, 0xe9, 0x43, 0x81, 0x66, 0x03, 0x71, 0x4c, 0xf8, 0x81, 0xa0, 0x75, 0x20, 0x1a, 0x10, 0x7e, + 0x08, 0x39, 0x94, 0x01, 0x37, 0xa5, 0xf7, 0x64, 0x15, 0x93, 0x47, 0xcc, 0xf8, 0x17, 0x18, 0x6c, + 0x08, 0x99, 0xeb, 0x60, 0xff, 0xdc, 0xe3, 0x74, 0x44, 0x1c, 0x88, 0x06, 0x66, 0xae, 0x92, 0xae, + 0xe5, 0xbb, 0xba, 0x40, 0x0e, 0x25, 0xb0, 0x8f, 0x06, 0xc6, 0x11, 0xc8, 0x04, 0x2e, 0x64, 0xc4, + 0xcc, 0x57, 0x94, 0x5a, 0xf1, 0x91, 0x37, 0xa8, 0x13, 0x33, 0xbb, 0x89, 0x03, 0x5b, 0xd5, 0x34, + 0x3d, 0x5f, 0x3d, 0x03, 0xa5, 0xe5, 0x97, 0xe1, 0x11, 0x17, 0xb2, 0x04, 0xb2, 0xb2, 0x73, 0x6b, + 0x02, 0x97, 0x7f, 0xad, 0xb7, 0x17, 0xd7, 0x65, 0xe5, 0xf2, 0xba, 0xac, 0x7c, 0xbb, 0x2e, 0x2b, + 0x9f, 0x6f, 0xca, 0xa9, 0xcb, 0x9b, 0x72, 0xea, 0xeb, 0x4d, 0x39, 0x75, 0xf6, 0xb2, 0x4f, 0xb9, + 0x3b, 0xee, 0xd5, 0x91, 0x3f, 0xb2, 0x90, 0xcf, 0x46, 0x3e, 0xb3, 0x6e, 0xf3, 0xf8, 0x6f, 0x76, + 0xd4, 0xa3, 0x27, 0xd6, 0xbb, 0xc5, 0xcb, 0xce, 0x27, 0x01, 0x61, 0xbd, 0xac, 0x38, 0xea, 0xff, + 0xff, 0x0c, 0x00, 0x00, 0xff, 0xff, 0x1e, 0x1f, 0x55, 0x38, 0xd1, 0x06, 0x00, 0x00, } func (m *GenesisState) Marshal() (dAtA []byte, err error) { @@ -432,34 +421,6 @@ func (m *GenesisState) MarshalToSizedBuffer(dAtA []byte) (int, error) { } i-- dAtA[i] = 0x42 - if len(m.ConsumerRemovalProposals) > 0 { - for iNdEx := len(m.ConsumerRemovalProposals) - 1; iNdEx >= 0; iNdEx-- { - { - size, err := m.ConsumerRemovalProposals[iNdEx].MarshalToSizedBuffer(dAtA[:i]) - if err != nil { - return 0, err - } - i -= size - i = encodeVarintGenesis(dAtA, i, uint64(size)) - } - i-- - dAtA[i] = 0x3a - } - } - if len(m.ConsumerAdditionProposals) > 0 { - for iNdEx := len(m.ConsumerAdditionProposals) - 1; iNdEx >= 0; iNdEx-- { - { - size, err := m.ConsumerAdditionProposals[iNdEx].MarshalToSizedBuffer(dAtA[:i]) - if err != nil { - return 0, err - } - i -= size - i = encodeVarintGenesis(dAtA, i, uint64(size)) - } - i-- - dAtA[i] = 0x32 - } - } if len(m.ValsetUpdateIdToHeight) > 0 { for iNdEx := len(m.ValsetUpdateIdToHeight) - 1; iNdEx >= 0; iNdEx-- { { @@ -516,6 +477,11 @@ func (m *ConsumerState) MarshalToSizedBuffer(dAtA []byte) (int, error) { _ = i var l int _ = l + if m.Phase != 0 { + i = encodeVarintGenesis(dAtA, i, uint64(m.Phase)) + i-- + dAtA[i] = 0x48 + } if len(m.SlashDowntimeAck) > 0 { for iNdEx := len(m.SlashDowntimeAck) - 1; iNdEx >= 0; iNdEx-- { i -= len(m.SlashDowntimeAck[iNdEx]) @@ -643,18 +609,6 @@ func (m *GenesisState) Size() (n int) { n += 1 + l + sovGenesis(uint64(l)) } } - if len(m.ConsumerAdditionProposals) > 0 { - for _, e := range m.ConsumerAdditionProposals { - l = e.Size() - n += 1 + l + sovGenesis(uint64(l)) - } - } - if len(m.ConsumerRemovalProposals) > 0 { - for _, e := range m.ConsumerRemovalProposals { - l = e.Size() - n += 1 + l + sovGenesis(uint64(l)) - } - } l = m.Params.Size() n += 1 + l + sovGenesis(uint64(l)) if len(m.ValidatorConsumerPubkeys) > 0 { @@ -713,6 +667,9 @@ func (m *ConsumerState) Size() (n int) { n += 1 + l + sovGenesis(uint64(l)) } } + if m.Phase != 0 { + n += 1 + sovGenesis(uint64(m.Phase)) + } return n } @@ -853,74 +810,6 @@ func (m *GenesisState) Unmarshal(dAtA []byte) error { return err } iNdEx = postIndex - case 6: - if wireType != 2 { - return fmt.Errorf("proto: wrong wireType = %d for field ConsumerAdditionProposals", wireType) - } - var msglen int - for shift := uint(0); ; shift += 7 { - if shift >= 64 { - return ErrIntOverflowGenesis - } - if iNdEx >= l { - return io.ErrUnexpectedEOF - } - b := dAtA[iNdEx] - iNdEx++ - msglen |= int(b&0x7F) << shift - if b < 0x80 { - break - } - } - if msglen < 0 { - return ErrInvalidLengthGenesis - } - postIndex := iNdEx + msglen - if postIndex < 0 { - return ErrInvalidLengthGenesis - } - if postIndex > l { - return io.ErrUnexpectedEOF - } - m.ConsumerAdditionProposals = append(m.ConsumerAdditionProposals, ConsumerAdditionProposal{}) - if err := m.ConsumerAdditionProposals[len(m.ConsumerAdditionProposals)-1].Unmarshal(dAtA[iNdEx:postIndex]); err != nil { - return err - } - iNdEx = postIndex - case 7: - if wireType != 2 { - return fmt.Errorf("proto: wrong wireType = %d for field ConsumerRemovalProposals", wireType) - } - var msglen int - for shift := uint(0); ; shift += 7 { - if shift >= 64 { - return ErrIntOverflowGenesis - } - if iNdEx >= l { - return io.ErrUnexpectedEOF - } - b := dAtA[iNdEx] - iNdEx++ - msglen |= int(b&0x7F) << shift - if b < 0x80 { - break - } - } - if msglen < 0 { - return ErrInvalidLengthGenesis - } - postIndex := iNdEx + msglen - if postIndex < 0 { - return ErrInvalidLengthGenesis - } - if postIndex > l { - return io.ErrUnexpectedEOF - } - m.ConsumerRemovalProposals = append(m.ConsumerRemovalProposals, ConsumerRemovalProposal{}) - if err := m.ConsumerRemovalProposals[len(m.ConsumerRemovalProposals)-1].Unmarshal(dAtA[iNdEx:postIndex]); err != nil { - return err - } - iNdEx = postIndex case 8: if wireType != 2 { return fmt.Errorf("proto: wrong wireType = %d for field Params", wireType) @@ -1320,6 +1209,25 @@ func (m *ConsumerState) Unmarshal(dAtA []byte) error { } m.SlashDowntimeAck = append(m.SlashDowntimeAck, string(dAtA[iNdEx:postIndex])) iNdEx = postIndex + case 9: + if wireType != 0 { + return fmt.Errorf("proto: wrong wireType = %d for field Phase", wireType) + } + m.Phase = 0 + for shift := uint(0); ; shift += 7 { + if shift >= 64 { + return ErrIntOverflowGenesis + } + if iNdEx >= l { + return io.ErrUnexpectedEOF + } + b := dAtA[iNdEx] + iNdEx++ + m.Phase |= ConsumerPhase(b&0x7F) << shift + if b < 0x80 { + break + } + } default: iNdEx = preIndex skippy, err := skipGenesis(dAtA[iNdEx:]) diff --git a/x/ccv/provider/types/genesis_test.go b/x/ccv/provider/types/genesis_test.go index c5472e07d5..09256a3cdd 100644 --- a/x/ccv/provider/types/genesis_test.go +++ b/x/ccv/provider/types/genesis_test.go @@ -33,8 +33,6 @@ func TestValidateGenesisState(t *testing.T) { types.DefaultValsetUpdateID, nil, []types.ConsumerState{{ChainId: "chainid-1", ChannelId: "channelid", ClientId: "client-id", ConsumerGenesis: getInitialConsumerGenesis(t, "chainid-1")}}, - nil, - nil, types.DefaultParams(), nil, nil, @@ -53,8 +51,6 @@ func TestValidateGenesisState(t *testing.T) { {ChainId: "chainid-3", ChannelId: "channelid3", ClientId: "client-id", ConsumerGenesis: getInitialConsumerGenesis(t, "chainid-3")}, {ChainId: "chainid-4", ChannelId: "channelid4", ClientId: "client-id", ConsumerGenesis: getInitialConsumerGenesis(t, "chainid-4")}, }, - nil, - nil, types.DefaultParams(), nil, nil, @@ -68,8 +64,6 @@ func TestValidateGenesisState(t *testing.T) { types.DefaultValsetUpdateID, nil, []types.ConsumerState{{ChainId: "chainid-1", ChannelId: "channelid", ClientId: "client-id", ConsumerGenesis: getInitialConsumerGenesis(t, "chainid-1")}}, - nil, - nil, types.NewParams(ibctmtypes.NewClientState("", ibctmtypes.DefaultTrustLevel, 0, 0, time.Second*40, clienttypes.Height{}, commitmenttypes.GetSDKSpecs(), []string{"ibc", "upgradedIBCState"}), types.DefaultTrustingPeriodFraction, time.Hour, time.Hour, "0.1", sdk.Coin{Denom: "stake", Amount: math.NewInt(10000000)}, 600, 24, 180), @@ -85,8 +79,6 @@ func TestValidateGenesisState(t *testing.T) { 0, nil, nil, - nil, - nil, types.NewParams(ibctmtypes.NewClientState("", ibctmtypes.DefaultTrustLevel, 0, 0, time.Second*40, clienttypes.Height{}, commitmenttypes.GetSDKSpecs(), []string{"ibc", "upgradedIBCState"}), types.DefaultTrustingPeriodFraction, time.Hour, time.Hour, "0.1", sdk.Coin{Denom: "stake", Amount: math.NewInt(10000000)}, 600, 24, 180), @@ -102,8 +94,6 @@ func TestValidateGenesisState(t *testing.T) { types.DefaultValsetUpdateID, []types.ValsetUpdateIdToHeight{{ValsetUpdateId: 0}}, nil, - nil, - nil, types.NewParams(ibctmtypes.NewClientState("", ibctmtypes.DefaultTrustLevel, 0, 0, time.Second*40, clienttypes.Height{}, commitmenttypes.GetSDKSpecs(), []string{"ibc", "upgradedIBCState"}), types.DefaultTrustingPeriodFraction, time.Hour, time.Hour, "0.1", sdk.Coin{Denom: "stake", Amount: math.NewInt(10000000)}, 600, 24, 180), @@ -119,8 +109,6 @@ func TestValidateGenesisState(t *testing.T) { types.DefaultValsetUpdateID, nil, []types.ConsumerState{{ChainId: "chainid-1", ChannelId: "channelid", ClientId: "client-id"}}, - nil, - nil, types.NewParams(ibctmtypes.NewClientState("", ibctmtypes.DefaultTrustLevel, 0, 0, 0, clienttypes.Height{}, nil, []string{"ibc", "upgradedIBCState"}), types.DefaultTrustingPeriodFraction, @@ -140,8 +128,6 @@ func TestValidateGenesisState(t *testing.T) { types.DefaultValsetUpdateID, nil, []types.ConsumerState{{ChainId: "chainid-1", ChannelId: "channelid", ClientId: "client-id"}}, - nil, - nil, types.NewParams(ibctmtypes.NewClientState("", ibctmtypes.DefaultTrustLevel, 0, 0, time.Second*40, clienttypes.Height{}, commitmenttypes.GetSDKSpecs(), []string{"ibc", "upgradedIBCState"}), "0.0", // 0 trusting period fraction here @@ -161,8 +147,6 @@ func TestValidateGenesisState(t *testing.T) { types.DefaultValsetUpdateID, nil, []types.ConsumerState{{ChainId: "chainid-1", ChannelId: "channelid", ClientId: "client-id"}}, - nil, - nil, types.NewParams(ibctmtypes.NewClientState("", ibctmtypes.DefaultTrustLevel, 0, 0, time.Second*40, clienttypes.Height{}, commitmenttypes.GetSDKSpecs(), []string{"ibc", "upgradedIBCState"}), types.DefaultTrustingPeriodFraction, @@ -182,8 +166,6 @@ func TestValidateGenesisState(t *testing.T) { types.DefaultValsetUpdateID, nil, []types.ConsumerState{{ChainId: "chainid-1", ChannelId: "channelid", ClientId: "client-id"}}, - nil, - nil, types.NewParams(ibctmtypes.NewClientState("", ibctmtypes.DefaultTrustLevel, 0, 0, time.Second*40, clienttypes.Height{}, commitmenttypes.GetSDKSpecs(), []string{"ibc", "upgradedIBCState"}), types.DefaultTrustingPeriodFraction, @@ -203,8 +185,6 @@ func TestValidateGenesisState(t *testing.T) { types.DefaultValsetUpdateID, nil, []types.ConsumerState{{ChainId: "chainid-1", ChannelId: "channelid", ClientId: "client-id"}}, - nil, - nil, types.NewParams(ibctmtypes.NewClientState("", ibctmtypes.DefaultTrustLevel, 0, 0, time.Second*40, clienttypes.Height{}, commitmenttypes.GetSDKSpecs(), []string{"ibc", "upgradedIBCState"}), types.DefaultTrustingPeriodFraction, @@ -224,8 +204,6 @@ func TestValidateGenesisState(t *testing.T) { types.DefaultValsetUpdateID, nil, []types.ConsumerState{{ChainId: "", ChannelId: "channelid", ClientId: "client-id"}}, - nil, - nil, types.DefaultParams(), nil, nil, @@ -239,8 +217,6 @@ func TestValidateGenesisState(t *testing.T) { types.DefaultValsetUpdateID, nil, []types.ConsumerState{{ChainId: "chainid", ChannelId: "ivnalidChannel{}", ClientId: "client-id"}}, - nil, - nil, types.DefaultParams(), nil, nil, @@ -254,8 +230,6 @@ func TestValidateGenesisState(t *testing.T) { types.DefaultValsetUpdateID, nil, []types.ConsumerState{{ChainId: "chainid", ChannelId: "channel-0", ClientId: ""}}, - nil, - nil, types.DefaultParams(), nil, nil, @@ -269,8 +243,6 @@ func TestValidateGenesisState(t *testing.T) { types.DefaultValsetUpdateID, nil, []types.ConsumerState{{ChainId: "chainid", ChannelId: "channel-0", ClientId: "abc", ConsumerGenesis: getInitialConsumerGenesis(t, "chainid")}}, - nil, - nil, types.DefaultParams(), nil, nil, @@ -287,8 +259,6 @@ func TestValidateGenesisState(t *testing.T) { ChainId: "chainid", ChannelId: "channel-0", ClientId: "client-id", ConsumerGenesis: ccv.ConsumerGenesisState{}, }}, - nil, - nil, types.DefaultParams(), nil, nil, @@ -306,8 +276,6 @@ func TestValidateGenesisState(t *testing.T) { ConsumerGenesis: getInitialConsumerGenesis(t, "chainid"), SlashDowntimeAck: []string{"cosmosvaloper1qlmk6r5w5taqrky4ycur4zq6jqxmuzr688htpp"}, }}, - nil, - nil, types.DefaultParams(), nil, nil, @@ -325,8 +293,6 @@ func TestValidateGenesisState(t *testing.T) { ConsumerGenesis: getInitialConsumerGenesis(t, "chainid"), PendingValsetChanges: []ccv.ValidatorSetChangePacketData{{}}, }}, - nil, - nil, types.DefaultParams(), nil, nil, @@ -348,8 +314,6 @@ func TestValidateGenesisState(t *testing.T) { ValidatorUpdates: []abci.ValidatorUpdate{{}}, }}, }}, - nil, - nil, types.DefaultParams(), nil, nil, @@ -363,8 +327,6 @@ func TestValidateGenesisState(t *testing.T) { types.DefaultValsetUpdateID, nil, []types.ConsumerState{{ChainId: "chainid-1", ChannelId: "channelid", ClientId: "client-id", ConsumerGenesis: getInitialConsumerGenesis(t, "chainid-1")}}, - nil, - nil, types.NewParams(ibctmtypes.NewClientState("", ibctmtypes.DefaultTrustLevel, 0, 0, time.Second*40, clienttypes.Height{}, commitmenttypes.GetSDKSpecs(), []string{"ibc", "upgradedIBCState"}), types.DefaultTrustingPeriodFraction, time.Hour, time.Hour, "0.1", sdk.Coin{Denom: "st", Amount: math.NewInt(10000000)}, 600, 24, 180), @@ -380,8 +342,6 @@ func TestValidateGenesisState(t *testing.T) { types.DefaultValsetUpdateID, nil, []types.ConsumerState{{ChainId: "chainid-1", ChannelId: "channelid", ClientId: "client-id", ConsumerGenesis: getInitialConsumerGenesis(t, "chainid-1")}}, - nil, - nil, types.NewParams(ibctmtypes.NewClientState("", ibctmtypes.DefaultTrustLevel, 0, 0, time.Second*40, clienttypes.Height{}, commitmenttypes.GetSDKSpecs(), []string{"ibc", "upgradedIBCState"}), types.DefaultTrustingPeriodFraction, time.Hour, time.Hour, "0.1", sdk.Coin{Denom: "stake", Amount: math.NewInt(-1000000)}, 600, 24, 180), diff --git a/x/ccv/provider/types/keys.go b/x/ccv/provider/types/keys.go index bd9ccbd807..ef7eae0172 100644 --- a/x/ccv/provider/types/keys.go +++ b/x/ccv/provider/types/keys.go @@ -49,17 +49,17 @@ const ( SlashMeterReplenishTimeCandidateKeyName = "SlashMeterReplenishTimeCandidateKey" - ChainToChannelKeyName = "ChainToChannelKey" + ConsumerIdToChannelIdKeyName = "ConsumerIdToChannelIdKey" - ChannelToChainKeyName = "ChannelToChainKey" + ChannelIdToConsumerIdKeyName = "ChannelToConsumerIdKey" - ChainToClientKeyName = "ChainToClientKey" + ConsumerIdToClientIdKeyName = "ConsumerIdToClientIdKey" DeprecatedInitTimeoutTimestampKeyName = "DeprecatedInitTimeoutTimestampKey" - PendingCAPKeyName = "PendingCAPKey" + DeprecatedPendingCAPKeyName = "DeprecatedPendingCAPKey" - PendingCRPKeyName = "PendingCRPKey" + DeprecatedPendingCRPKeyName = "DeprecatedPendingCRPKey" DeprecatedUnbondingOpKeyName = "DeprecatedUnbondingOpKey" @@ -77,11 +77,11 @@ const ( DeprecatedVscSendTimestampKeyName = "DeprecatedVscSendTimestampKey" - ThrottledPacketDataSizeKeyName = "ThrottledPacketDataSizeKey" + DeprecatedThrottledPacketDataSizeKeyName = "DeprecatedThrottledPacketDataSizeKey" - ThrottledPacketDataKeyName = "ThrottledPacketDataKey" + DeprecatedThrottledPacketDataKeyName = "DeprecatedThrottledPacketDataKey" - GlobalSlashEntryKeyName = "GlobalSlashEntryKey" + DeprecatedGlobalSlashEntryKeyName = "DeprecatedGlobalSlashEntryKey" ConsumerValidatorsKeyName = "ConsumerValidatorsKey" @@ -99,17 +99,17 @@ const ( EquivocationEvidenceMinHeightKeyName = "EquivocationEvidenceMinHeightKey" - ProposedConsumerChainKeyName = "ProposedConsumerChainKey" + DeprecatedProposedConsumerChainKeyName = "DeprecatedProposedConsumerChainKey" ConsumerValidatorKeyName = "ConsumerValidatorKey" OptedInKeyName = "OptedInKey" - TopNKeyName = "TopNKey" + DeprecatedTopNKeyName = "DeprecatedTopNKey" - ValidatorsPowerCapKeyName = "ValidatorsPowerCapKey" + DeprecatedValidatorsPowerCapKeyName = "DeprecatedValidatorsPowerCapKey" - ValidatorSetCapKeyName = "ValidatorSetCapKey" + DeprecatedValidatorSetCapKeyName = "DeprecatedValidatorSetCapKey" AllowlistKeyName = "AllowlistKey" @@ -123,11 +123,31 @@ const ( LastProviderConsensusValsKeyName = "LastProviderConsensusValsKey" - MinStakeKeyName = "MinStakeKey" + ConsumerAddrsToPruneV2KeyName = "ConsumerAddrsToPruneV2Key" - AllowInactiveValidatorsKeyName = "AllowInactiveValidatorsKey" + ConsumerIdKeyName = "ConsumerIdKey" - ConsumerAddrsToPruneV2KeyName = "ConsumerAddrsToPruneV2Key" + ConsumerIdToChainIdKeyName = "ConsumerIdToChainIdKey" + + ConsumerIdToOwnerAddressKeyName = "ConsumerIdToOwnerAddress" + + ConsumerIdToConsumerMetadataKeyName = "ConsumerIdToMetadataKey" + + ConsumerIdToInitializationParametersKeyName = "ConsumerIdToInitializationParametersKey" + + ConsumerIdToPowerShapingParameters = "ConsumerIdToPowerShapingParametersKey" + + ConsumerIdToPhaseKeyName = "ConsumerIdToPhaseKey" + + ConsumerIdToRemovalTimeKeyName = "ConsumerIdToRemovalTimeKey" + + SpawnTimeToConsumerIdsKeyName = "SpawnTimeToConsumerIdsKeyName" + + RemovalTimeToConsumerIdsKeyName = "RemovalTimeToConsumerIdsKeyName" + + ProviderConsAddrToOptedInConsumerIdsKeyName = "ProviderConsAddrToOptedInConsumerIdsKeyName" + + ClientIdToConsumerIdKeyName = "ClientIdToConsumerIdKey" ) // getKeyPrefixes returns a constant map of all the byte prefixes for existing keys @@ -157,16 +177,16 @@ func getKeyPrefixes() map[string]byte { // SlashMeterReplenishTimeCandidateKey is the key for storing the slash meter replenish time candidate SlashMeterReplenishTimeCandidateKeyName: 4, - // ChainToChannelKey is the key for storing mapping + // ConsumerIdToChannelIdKey is the key for storing mapping // from chainID to the channel ID that is used to send over validator set changes. - ChainToChannelKeyName: 5, + ConsumerIdToChannelIdKeyName: 5, - // ChannelToChainKey is the key for storing mapping + // ChannelToConsumerIdKey is the key for storing mapping // from the CCV channel ID to the consumer chain ID. - ChannelToChainKeyName: 6, + ChannelIdToConsumerIdKeyName: 6, - // ChainToClientKey is the key for storing the client ID for a given consumer chainID. - ChainToClientKeyName: 7, + // ConsumerIdToClientIdKey is the key for storing the client ID for a given consumer chainID. + ConsumerIdToClientIdKeyName: 7, // InitTimeoutTimestampKey is the key for storing // the init timeout timestamp for a given consumer chainID. @@ -176,11 +196,13 @@ func getKeyPrefixes() map[string]byte { // PendingCAPKey is the key for storing pending consumer addition proposals before the spawn time occurs. // The key includes the BigEndian timestamp to allow for efficient chronological iteration - PendingCAPKeyName: 9, + // [DEPRECATED] + DeprecatedPendingCAPKeyName: 9, // PendingCRPKey is the key for storing pending consumer removal proposals before the stop time occurs. // The key includes the BigEndian timestamp to allow for efficient chronological iteration - PendingCRPKeyName: 10, + // [DEPRECATED] + DeprecatedPendingCRPKeyName: 10, // UnbondingOpKey is the key that stores a record of all the ids of consumer chains that // need to unbond before a given unbonding operation can unbond on this chain. @@ -217,13 +239,16 @@ func getKeyPrefixes() map[string]byte { DeprecatedVscSendTimestampKeyName: 18, // ThrottledPacketDataSizeKey is the key for storing the size of chain-specific throttled packet data queues - ThrottledPacketDataSizeKeyName: 19, + // [DEPRECATED] + DeprecatedThrottledPacketDataSizeKeyName: 19, // ThrottledPacketDataKey is the key for storing throttled packet data - ThrottledPacketDataKeyName: 20, + // [DEPRECATED] + DeprecatedThrottledPacketDataKeyName: 20, // GlobalSlashEntryKey is the key for storing global slash queue entries - GlobalSlashEntryKeyName: 21, + // [DEPRECATED] + DeprecatedGlobalSlashEntryKeyName: 21, // ConsumerValidatorsKey is the key for storing the validator assigned keys for every consumer chain ConsumerValidatorsKeyName: 22, @@ -261,7 +286,8 @@ func getKeyPrefixes() map[string]byte { EquivocationEvidenceMinHeightKeyName: 29, // ProposedConsumerChainKey is the key for storing the consumer chainId in consumerAddition gov proposal submitted before voting finishes - ProposedConsumerChainKeyName: 30, + // [DEPRECATED] + DeprecatedProposedConsumerChainKeyName: 30, // ConsumerValidatorKey is the key for storing for each consumer chain all the consumer // validators in this epoch that are validating the consumer chain @@ -270,18 +296,24 @@ func getKeyPrefixes() map[string]byte { // OptedInKey is the key for storing whether a validator is opted in to validate on a consumer chain OptedInKeyName: 32, - // TopNKey is the key for storing the mapping from a consumer chain to the N value of this chain, + // DeprecatedTopNKey is the key for storing the mapping from a consumer chain to the N value of this chain, // that corresponds to the N% of the top validators that have to validate this consumer chain - TopNKeyName: 33, + // NOTE: This prefix is deprecated, but left in place to avoid state migrations + // [DEPRECATED] + DeprecatedTopNKeyName: 33, - // ValidatorsPowerCapKey is the key for storing the mapping from a consumer chain to the power-cap value of this chain, + // DeprecatedValidatorsPowerCapKey is the key for storing the mapping from a consumer chain to the power-cap value of this chain, // that corresponds to p% such that no validator can have more than p% of the voting power on the consumer chain. // Operates on a best-effort basis. - ValidatorsPowerCapKeyName: 34, + // NOTE: This prefix is deprecated, but left in place to avoid state migrations + // [DEPRECATED] + DeprecatedValidatorsPowerCapKeyName: 34, - // ValidatorSetCapKey is the key for storing the mapping from a consumer chain to the validator-set cap value + // DeprecatedValidatorSetCapKey is the key for storing the mapping from a consumer chain to the validator-set cap value // of this chain. - ValidatorSetCapKeyName: 35, + // NOTE: This prefix is deprecated, but left in place to avoid state migrations + // [DEPRECATED] + DeprecatedValidatorSetCapKeyName: 35, // AllowlistKey is the key for storing the mapping from a consumer chain to the set of validators that are // allowlisted. @@ -311,14 +343,44 @@ func getKeyPrefixes() map[string]byte { // sent to the consensus engine of the provider chain LastProviderConsensusValsKeyName: 42, - // MinStakeKey is the byte prefix for storing the mapping from consumer chains to the minimum stake required to be a validator on the consumer chain - // The minimum stake must be stored on the provider chain, not on the consumer chain itself, since it filters out - // validators from the VSCPackets that we send to the consumer chain. - MinStakeKeyName: 43, + // ConsumerIdKeyName is the key for storing the consumer id for the next registered consumer chain + ConsumerIdKeyName: 43, + + // ConsumerIdToChainIdKeyName is the key for storing the chain id for the given consumer id + ConsumerIdToChainIdKeyName: 44, + + // ConsumerIdToOwnerAddressKeyName is the key for storing the owner address for the given consumer id + ConsumerIdToOwnerAddressKeyName: 45, + + // ConsumerIdToConsumerMetadataKeyName is the key for storing the metadata for the given consumer id + ConsumerIdToConsumerMetadataKeyName: 46, + + // ConsumerIdToInitializationParametersKeyName is the key for storing the initialization parameters for the given consumer id + ConsumerIdToInitializationParametersKeyName: 47, + + // ConsumerIdToPowerShapingParameters is the key for storing the power-shaping parameters for the given consumer id + ConsumerIdToPowerShapingParameters: 48, - // AllowInactiveValidatorsKey is the byte prefix for storing the mapping from consumer chains to the boolean value - // that determines whether inactive validators can validate on that chain - AllowInactiveValidatorsKeyName: 44, + // ConsumerIdToPhaseKeyName is the key for storing the phase of a consumer chain with the given consumer id + ConsumerIdToPhaseKeyName: 49, + + // ConsumerIdToRemovalTimeKeyName is the key for storing the removal time of a consumer chain that is to be removed + ConsumerIdToRemovalTimeKeyName: 50, + + // SpawnTimeToConsumerIdKeyName is the key for storing pending initialized consumers that are to be launched. + // For a specific spawn time, it might store multiple consumer chain ids for chains that are to be launched. + SpawnTimeToConsumerIdsKeyName: 51, + + // RemovalTimeToConsumerIdsKeyName is the key for storing pending launched consumers that are to be removed. + // For a specific removal time, it might store multiple consumer chain ids for chains that are to be removed. + RemovalTimeToConsumerIdsKeyName: 52, + + // ProviderConsAddrToOptedInConsumerIdsKeyName is the key for storing all the consumer ids that a validator + // is currently opted in to. + ProviderConsAddrToOptedInConsumerIdsKeyName: 53, + + // ClientIdToConsumerIdKeyName is the key for storing the consumer id for the given client id + ClientIdToConsumerIdKeyName: 54, // NOTE: DO NOT ADD NEW BYTE PREFIXES HERE WITHOUT ADDING THEM TO TestPreserveBytePrefix() IN keys_test.go } @@ -392,67 +454,29 @@ func SlashMeterReplenishTimeCandidateKey() []byte { return []byte{mustGetKeyPrefix(SlashMeterReplenishTimeCandidateKeyName)} } -// ChainToChannelKey returns the key under which the CCV channel ID will be stored for the given consumer chain. -func ChainToChannelKey(chainID string) []byte { - return append([]byte{mustGetKeyPrefix(ChainToChannelKeyName)}, []byte(chainID)...) -} - -// ChannelToChainKeyPrefix returns the key prefix for storing the consumer chain IDs. -func ChannelToChainKeyPrefix() []byte { - return []byte{mustGetKeyPrefix(ChannelToChainKeyName)} -} - -// ChannelToChainKey returns the key under which the consumer chain ID will be stored for the given channelID. -func ChannelToChainKey(channelID string) []byte { - return append(ChannelToChainKeyPrefix(), []byte(channelID)...) +// ConsumerIdToChannelIdKey returns the key under which the CCV channel ID will be stored for the given consumer chain. +func ConsumerIdToChannelIdKey(consumerId string) []byte { + return append([]byte{mustGetKeyPrefix(ConsumerIdToChannelIdKeyName)}, []byte(consumerId)...) } -// ChainToClientKeyPrefix returns the key prefix for storing the clientID for the given chainID. -func ChainToClientKeyPrefix() []byte { - return []byte{mustGetKeyPrefix(ChainToClientKeyName)} +// ChannelIdToConsumerIdKeyPrefix returns the key prefix for storing the consumer chain ids. +func ChannelIdToConsumerIdKeyPrefix() []byte { + return []byte{mustGetKeyPrefix(ChannelIdToConsumerIdKeyName)} } -// ChainToClientKey returns the key under which the clientID for the given chainID is stored. -func ChainToClientKey(chainID string) []byte { - return append(ChainToClientKeyPrefix(), []byte(chainID)...) +// ChannelToConsumerIdKey returns the key under which the consumer chain id will be stored for the given channelId. +func ChannelToConsumerIdKey(channelId string) []byte { + return append(ChannelIdToConsumerIdKeyPrefix(), []byte(channelId)...) } -// PendingCAPKeyPrefix returns the key prefix for storing a pending consumer addition proposal -func PendingCAPKeyPrefix() []byte { - return []byte{mustGetKeyPrefix(PendingCAPKeyName)} +// ConsumerIdToClientIdKeyPrefix returns the key prefix for storing the clientId for the given consumerId. +func ConsumerIdToClientIdKeyPrefix() []byte { + return []byte{mustGetKeyPrefix(ConsumerIdToClientIdKeyName)} } -// PendingCAPKey returns the key under which a pending consumer addition proposal is stored. -// The key has the following format: PendingCAPKeyPrefix | timestamp.UnixNano() | chainID -func PendingCAPKey(timestamp time.Time, chainID string) []byte { - ts := uint64(timestamp.UTC().UnixNano()) - return ccvtypes.AppendMany( - // Append the prefix - PendingCAPKeyPrefix(), - // Append the time - sdk.Uint64ToBigEndian(ts), - // Append the chainId - []byte(chainID), - ) -} - -// PendingCRPKeyPrefix returns the key prefix for storing pending consumer removal proposals. -func PendingCRPKeyPrefix() []byte { - return []byte{mustGetKeyPrefix(PendingCRPKeyName)} -} - -// PendingCRPKey returns the key under which pending consumer removal proposals are stored. -// The key has the following format: PendingCRPKeyPrefix | timestamp.UnixNano() | chainID -func PendingCRPKey(timestamp time.Time, chainID string) []byte { - ts := uint64(timestamp.UTC().UnixNano()) - return ccvtypes.AppendMany( - // Append the prefix - PendingCRPKeyPrefix(), - // Append the time - sdk.Uint64ToBigEndian(ts), - // Append the chainId - []byte(chainID), - ) +// ConsumerIdToClientIdKey returns the key under which the clientId for the given consumerId is stored. +func ConsumerIdToClientIdKey(consumerId string) []byte { + return append(ConsumerIdToClientIdKeyPrefix(), []byte(consumerId)...) } // ValsetUpdateBlockHeightKeyPrefix returns the key prefix that storing the mapping from valset update ID to block height @@ -468,98 +492,25 @@ func ValsetUpdateBlockHeightKey(valsetUpdateId uint64) []byte { } // ConsumerGenesisKey returns the key corresponding to consumer genesis state material -// (consensus state and client state) indexed by consumer chain id -func ConsumerGenesisKey(chainID string) []byte { - return append([]byte{mustGetKeyPrefix(ConsumerGenesisKeyName)}, []byte(chainID)...) +// (consensus state and client state) indexed by consumer id +func ConsumerGenesisKey(consumerId string) []byte { + return append([]byte{mustGetKeyPrefix(ConsumerGenesisKeyName)}, []byte(consumerId)...) } -// SlashAcksKey returns the key under which slashing acks are stored for a given chain ID -func SlashAcksKey(chainID string) []byte { - return append([]byte{mustGetKeyPrefix(SlashAcksKeyName)}, []byte(chainID)...) +// SlashAcksKey returns the key under which slashing acks are stored for a given consumer id +func SlashAcksKey(consumerId string) []byte { + return append([]byte{mustGetKeyPrefix(SlashAcksKeyName)}, []byte(consumerId)...) } -// InitChainHeightKey returns the key under which the block height for a given chain ID is stored -func InitChainHeightKey(chainID string) []byte { - return append([]byte{mustGetKeyPrefix(InitChainHeightKeyName)}, []byte(chainID)...) +// InitChainHeightKey returns the key under which the block height for a given consumer id is stored +func InitChainHeightKey(consumerId string) []byte { + return append([]byte{mustGetKeyPrefix(InitChainHeightKeyName)}, []byte(consumerId)...) } // PendingVSCsKey returns the key under which -// pending ValidatorSetChangePacket data is stored for a given chain ID -func PendingVSCsKey(chainID string) []byte { - return append([]byte{mustGetKeyPrefix(PendingVSCsKeyName)}, []byte(chainID)...) -} - -// ThrottledPacketDataSizeKey returns the key storing the size of the throttled packet data queue for a given chain ID -func ThrottledPacketDataSizeKey(consumerChainID string) []byte { - return append([]byte{mustGetKeyPrefix(ThrottledPacketDataSizeKeyName)}, []byte(consumerChainID)...) -} - -// ThrottledPacketDataKeyPrefix returns the key prefix for storing the throttled packet data queue -func ThrottledPacketDataKeyPrefix() byte { - return mustGetKeyPrefix(ThrottledPacketDataKeyName) -} - -// ThrottledPacketDataKey returns the key for storing the throttled packet data queue for a given chain ID and ibc seq num -func ThrottledPacketDataKey(consumerChainID string, ibcSeqNum uint64) []byte { - return ChainIdAndUintIdKey(ThrottledPacketDataKeyPrefix(), consumerChainID, ibcSeqNum) -} - -// MustParseThrottledPacketDataKey parses a throttled packet data key or panics upon failure -func MustParseThrottledPacketDataKey(key []byte) (string, uint64) { - chainId, ibcSeqNum, err := ParseThrottledPacketDataKey(key) - if err != nil { - panic(fmt.Sprintf("failed to parse throttled packet data key: %s", err.Error())) - } - return chainId, ibcSeqNum -} - -// ParseThrottledPacketDataKey parses a throttled packet data key -func ParseThrottledPacketDataKey(key []byte) (chainId string, ibcSeqNum uint64, err error) { - return ParseChainIdAndUintIdKey(ThrottledPacketDataKeyPrefix(), key) -} - -// GlobalSlashEntryKeyPrefix returns the key for storing a global slash queue entry. -func GlobalSlashEntryKeyPrefix() []byte { - return []byte{mustGetKeyPrefix(GlobalSlashEntryKeyName)} -} - -// GlobalSlashEntryKey returns the key for storing a global slash queue entry. -func GlobalSlashEntryKey(entry GlobalSlashEntry) []byte { - recvTime := uint64(entry.RecvTime.UTC().UnixNano()) - return ccvtypes.AppendMany( - // Append byte prefix - GlobalSlashEntryKeyPrefix(), - // Append time bz - sdk.Uint64ToBigEndian(recvTime), - // Append ibc seq num - sdk.Uint64ToBigEndian(entry.IbcSeqNum), - // Append consumer chain id - []byte(entry.ConsumerChainID), - ) -} - -// MustParseGlobalSlashEntryKey returns the received time and chainID for a global slash queue entry key, -// or panics if the key is invalid. -func MustParseGlobalSlashEntryKey(bz []byte) ( - recvTime time.Time, consumerChainID string, ibcSeqNum uint64, -) { - // Prefix is in first byte - expectedPrefix := GlobalSlashEntryKeyPrefix() - if prefix := bz[:1]; !bytes.Equal(prefix, expectedPrefix) { - panic(fmt.Sprintf("invalid prefix; expected: %X, got: %X", expectedPrefix, prefix)) - } - - // 8 bytes for uint64 storing time bytes - timeBz := sdk.BigEndianToUint64(bz[1:9]) - recvTime = time.Unix(0, int64(timeBz)).UTC() - - // 8 bytes for uint64 storing ibc seq num - ibcSeqNum = sdk.BigEndianToUint64(bz[9:17]) - - // ChainID is stored after 8 byte ibc seq num - chainID := string(bz[17:]) - - return recvTime, chainID, ibcSeqNum +// pending ValidatorSetChangePacket data is stored for a given consumer id +func PendingVSCsKey(consumerId string) []byte { + return append([]byte{mustGetKeyPrefix(PendingVSCsKeyName)}, []byte(consumerId)...) } // ConsumerValidatorsKey returns the key for storing the validator assigned keys for every consumer chain @@ -569,8 +520,8 @@ func ConsumerValidatorsKeyPrefix() byte { // ConsumerValidatorsKey returns the key under which the // validator assigned keys for every consumer chain are stored -func ConsumerValidatorsKey(chainID string, addr ProviderConsAddress) []byte { - return ChainIdAndConsAddrKey(ConsumerValidatorsKeyPrefix(), chainID, addr.ToSdkConsAddr()) +func ConsumerValidatorsKey(consumerId string, addr ProviderConsAddress) []byte { + return StringIdAndConsAddrKey(ConsumerValidatorsKeyPrefix(), consumerId, addr.ToSdkConsAddr()) } // ValidatorsByConsumerAddrKeyPrefix returns the key prefix for storing the mapping from validator addresses @@ -581,8 +532,8 @@ func ValidatorsByConsumerAddrKeyPrefix() byte { // ValidatorsByConsumerAddrKey returns the key for storing the mapping from validator addresses // on consumer chains to validator addresses on the provider chain -func ValidatorsByConsumerAddrKey(chainID string, addr ConsumerConsAddress) []byte { - return ChainIdAndConsAddrKey(ValidatorsByConsumerAddrKeyPrefix(), chainID, addr.ToSdkConsAddr()) +func ValidatorsByConsumerAddrKey(consumerId string, addr ConsumerConsAddress) []byte { + return StringIdAndConsAddrKey(ValidatorsByConsumerAddrKeyPrefix(), consumerId, addr.ToSdkConsAddr()) } // SlashLogKey returns the key to a validator's slash log @@ -601,35 +552,9 @@ func ConsumerRewardDenomsKey(denom string) []byte { } // EquivocationEvidenceMinHeightKey returns the key storing the minimum height -// of a valid consumer equivocation evidence for a given consumer chain ID -func EquivocationEvidenceMinHeightKey(consumerChainID string) []byte { - return append([]byte{mustGetKeyPrefix(EquivocationEvidenceMinHeightKeyName)}, []byte(consumerChainID)...) -} - -// ProposedConsumerChainKeyPrefix returns the key prefix for storing proposed consumer chainId -// in consumerAddition gov proposal before voting finishes -func ProposedConsumerChainKeyPrefix() []byte { - return []byte{mustGetKeyPrefix(ProposedConsumerChainKeyName)} -} - -// ProposedConsumerChainKey returns the key of proposed consumer chainId in consumerAddition gov proposal before voting finishes, the stored key format is prefix|proposalID, value is chainID -func ProposedConsumerChainKey(proposalID uint64) []byte { - return ccvtypes.AppendMany( - ProposedConsumerChainKeyPrefix(), - sdk.Uint64ToBigEndian(proposalID), - ) -} - -// ParseProposedConsumerChainKey get the proposalID in the key -func ParseProposedConsumerChainKey(bz []byte) (uint64, error) { - expectedPrefix := ProposedConsumerChainKeyPrefix() - prefixL := len(expectedPrefix) - if prefix := bz[:prefixL]; !bytes.Equal(prefix, expectedPrefix) { - return 0, fmt.Errorf("invalid prefix; expected: %X, got: %X", expectedPrefix, prefix) - } - proposalID := sdk.BigEndianToUint64(bz[prefixL:]) - - return proposalID, nil +// of a valid consumer equivocation evidence for a given consumer id +func EquivocationEvidenceMinHeightKey(consumerId string) []byte { + return append([]byte{mustGetKeyPrefix(EquivocationEvidenceMinHeightKeyName)}, []byte(consumerId)...) } // ConsumerValidatorKeyPrefix returns the key prefix for storing consumer validators @@ -638,26 +563,9 @@ func ConsumerValidatorKeyPrefix() byte { } // ConsumerValidatorKey returns the key for storing consumer validators -// for the given consumer chain `chainID` and validator with `providerAddr` -func ConsumerValidatorKey(chainID string, providerAddr []byte) []byte { - prefix := ChainIdWithLenKey(ConsumerValidatorKeyPrefix(), chainID) - return append(prefix, providerAddr...) -} - -// TopNKey returns the key used to store the Top N value per consumer chain. -// This value corresponds to the N% of the top validators that have to validate the consumer chain. -func TopNKey(chainID string) []byte { - return ChainIdWithLenKey(mustGetKeyPrefix(TopNKeyName), chainID) -} - -// ValidatorSetPowerKey returns the key of consumer chain `chainID` -func ValidatorsPowerCapKey(chainID string) []byte { - return ChainIdWithLenKey(mustGetKeyPrefix(ValidatorsPowerCapKeyName), chainID) -} - -// ValidatorSetCapKey returns the key of consumer chain `chainID` -func ValidatorSetCapKey(chainID string) []byte { - return ChainIdWithLenKey(mustGetKeyPrefix(ValidatorSetCapKeyName), chainID) +// for the given consumer chain `consumerId` and validator with `providerAddr` +func ConsumerValidatorKey(consumerId string, providerAddr []byte) []byte { + return StringIdAndConsAddrKey(ConsumerValidatorKeyPrefix(), consumerId, sdk.ConsAddress(providerAddr)) } // AllowlistKeyPrefix returns the key prefix for storing consumer chains allowlists @@ -666,11 +574,8 @@ func AllowlistKeyPrefix() byte { } // AllowlistKey returns the key for storing consumer chains allowlists -func AllowlistKey(chainID string, providerAddr ProviderConsAddress) []byte { - return append( - ChainIdWithLenKey(AllowlistKeyPrefix(), chainID), - providerAddr.ToSdkConsAddr().Bytes()..., - ) +func AllowlistKey(consumerId string, providerAddr ProviderConsAddress) []byte { + return StringIdAndConsAddrKey(AllowlistKeyPrefix(), consumerId, providerAddr.ToSdkConsAddr()) } // DenylistKeyPrefix returns the key prefix for storing consumer chains denylists @@ -679,11 +584,8 @@ func DenylistKeyPrefix() byte { } // DenylistKey returns the key for storing consumer chains denylists -func DenylistKey(chainID string, providerAddr ProviderConsAddress) []byte { - return append( - ChainIdWithLenKey(DenylistKeyPrefix(), chainID), - providerAddr.ToSdkConsAddr().Bytes()..., - ) +func DenylistKey(consumerId string, providerAddr ProviderConsAddress) []byte { + return StringIdAndConsAddrKey(DenylistKeyPrefix(), consumerId, providerAddr.ToSdkConsAddr()) } // OptedInKeyPrefix returns the key prefix for storing whether a validator is opted in on a consumer chain. @@ -692,14 +594,13 @@ func OptedInKeyPrefix() byte { } // OptedInKey returns the key used to store whether a validator is opted in on a consumer chain. -func OptedInKey(chainID string, providerAddr ProviderConsAddress) []byte { - prefix := ChainIdWithLenKey(OptedInKeyPrefix(), chainID) - return append(prefix, providerAddr.ToSdkConsAddr().Bytes()...) +func OptedInKey(consumerId string, providerAddr ProviderConsAddress) []byte { + return StringIdAndConsAddrKey(OptedInKeyPrefix(), consumerId, providerAddr.ToSdkConsAddr()) } // ConsumerRewardsAllocationKey returns the key used to store the ICS rewards per consumer chain -func ConsumerRewardsAllocationKey(chainID string) []byte { - return append([]byte{mustGetKeyPrefix(ConsumerRewardsAllocationKeyName)}, []byte(chainID)...) +func ConsumerRewardsAllocationKey(consumerId string) []byte { + return append([]byte{mustGetKeyPrefix(ConsumerRewardsAllocationKeyName)}, []byte(consumerId)...) } // ConsumerCommissionRateKeyPrefix returns the key prefix for storing the commission rate per validator per consumer chain. @@ -708,16 +609,16 @@ func ConsumerCommissionRateKeyPrefix() byte { } // ConsumerCommissionRateKey returns the key used to store the commission rate per validator per consumer chain. -func ConsumerCommissionRateKey(chainID string, providerAddr ProviderConsAddress) []byte { - return ChainIdAndConsAddrKey( +func ConsumerCommissionRateKey(consumerId string, providerAddr ProviderConsAddress) []byte { + return StringIdAndConsAddrKey( ConsumerCommissionRateKeyPrefix(), - chainID, + consumerId, providerAddr.ToSdkConsAddr(), ) } -func MinimumPowerInTopNKey(chainID string) []byte { - return ChainIdWithLenKey(mustGetKeyPrefix(MinimumPowerInTopNKeyName), chainID) +func MinimumPowerInTopNKey(consumerId string) []byte { + return StringIdWithLenKey(mustGetKeyPrefix(MinimumPowerInTopNKeyName), consumerId) } // ConsumerAddrsToPruneV2KeyPrefix returns the key prefix for storing the consumer validators @@ -730,8 +631,8 @@ func ConsumerAddrsToPruneV2KeyPrefix() byte { // ConsumerAddrsToPruneV2Key returns the key for storing the consumer validators // addresses that need to be pruned. -func ConsumerAddrsToPruneV2Key(chainID string, pruneTs time.Time) []byte { - return ChainIdAndTsKey(ConsumerAddrsToPruneV2KeyPrefix(), chainID, pruneTs) +func ConsumerAddrsToPruneV2Key(consumerId string, pruneTs time.Time) []byte { + return StringIdAndTsKey(ConsumerAddrsToPruneV2KeyPrefix(), consumerId, pruneTs) } // LastProviderConsensusValsPrefix returns the key prefix for storing the last validator set sent to the consensus engine of the provider chain @@ -739,13 +640,125 @@ func LastProviderConsensusValsPrefix() []byte { return []byte{mustGetKeyPrefix(LastProviderConsensusValsKeyName)} } -// MinStakeKey returns the key used to store the minimum stake required to validate on consumer chain `chainID` -func MinStakeKey(chainID string) []byte { - return ChainIdWithLenKey(mustGetKeyPrefix(MinStakeKeyName), chainID) +// ConsumerIdKey returns the key used to store the consumerId of the next registered chain +func ConsumerIdKey() []byte { + return []byte{mustGetKeyPrefix(ConsumerIdKeyName)} +} + +// ConsumerIdToChainIdKey returns the key used to store the chain id of this consumer id +func ConsumerIdToChainIdKey(consumerId string) []byte { + return StringIdWithLenKey(mustGetKeyPrefix(ConsumerIdToChainIdKeyName), consumerId) +} + +// ConsumerIdToOwnerAddressKey returns the owner address of this consumer id +func ConsumerIdToOwnerAddressKey(consumerId string) []byte { + return StringIdWithLenKey(mustGetKeyPrefix(ConsumerIdToOwnerAddressKeyName), consumerId) +} + +// ConsumerIdToMetadataKeyPrefix returns the key prefix for storing consumer metadata +func ConsumerIdToMetadataKeyPrefix() byte { + return mustGetKeyPrefix(ConsumerIdToConsumerMetadataKeyName) +} + +// ConsumerIdToMetadataKey returns the key used to store the metadata that corresponds to this consumer id +func ConsumerIdToMetadataKey(consumerId string) []byte { + return StringIdWithLenKey(ConsumerIdToMetadataKeyPrefix(), consumerId) +} + +// ConsumerIdToInitializationParametersKeyPrefix returns the key prefix for storing consumer initialization parameters +func ConsumerIdToInitializationParametersKeyPrefix() byte { + return mustGetKeyPrefix(ConsumerIdToInitializationParametersKeyName) +} + +// ConsumerIdToInitializationParametersKey returns the key used to store the initialization parameters that corresponds to this consumer id +func ConsumerIdToInitializationParametersKey(consumerId string) []byte { + return StringIdWithLenKey(ConsumerIdToInitializationParametersKeyPrefix(), consumerId) +} + +// ConsumerIdToPowerShapingParametersKey returns the key used to store the power-shaping parameters that corresponds to this consumer id +func ConsumerIdToPowerShapingParametersKey(consumerId string) []byte { + return StringIdWithLenKey(mustGetKeyPrefix(ConsumerIdToPowerShapingParameters), consumerId) +} + +// ConsumerIdToPhaseKey returns the key used to store the phase that corresponds to this consumer id +func ConsumerIdToPhaseKey(consumerId string) []byte { + return StringIdWithLenKey(mustGetKeyPrefix(ConsumerIdToPhaseKeyName), consumerId) +} + +// ConsumerIdToRemovalTimeKeyPrefix returns the key prefix for storing the removal times of consumer chains +// that are about to be removed +func ConsumerIdToRemovalTimeKeyPrefix() byte { + return mustGetKeyPrefix(ConsumerIdToRemovalTimeKeyName) +} + +// ConsumerIdToRemovalTimeKey returns the key used to store the removal time that corresponds to a to-be-removed chain with consumer id +func ConsumerIdToRemovalTimeKey(consumerId string) []byte { + return StringIdWithLenKey(ConsumerIdToRemovalTimeKeyPrefix(), consumerId) +} + +// SpawnTimeToConsumerIdsKeyPrefix returns the key prefix for storing pending chains that are to be launched +func SpawnTimeToConsumerIdsKeyPrefix() byte { + return mustGetKeyPrefix(SpawnTimeToConsumerIdsKeyName) +} + +// SpawnTimeToConsumerIdsKey returns the key prefix for storing the spawn times of consumer chains +// that are about to be launched +func SpawnTimeToConsumerIdsKey(spawnTime time.Time) []byte { + return ccvtypes.AppendMany( + // append the prefix + []byte{SpawnTimeToConsumerIdsKeyPrefix()}, + // append the time + sdk.FormatTimeBytes(spawnTime), + ) +} + +// RemovalTimeToConsumerIdsKeyPrefix returns the key prefix for storing pending chains that are to be removed +func RemovalTimeToConsumerIdsKeyPrefix() byte { + return mustGetKeyPrefix(RemovalTimeToConsumerIdsKeyName) +} + +// RemovalTimeToConsumerIdsKey returns the key prefix for storing the removal times of consumer chains +// that are about to be removed +func RemovalTimeToConsumerIdsKey(spawnTime time.Time) []byte { + return ccvtypes.AppendMany( + // append the prefix + []byte{RemovalTimeToConsumerIdsKeyPrefix()}, + // append the time + sdk.FormatTimeBytes(spawnTime), + ) +} + +// ParseTime returns the marshalled time +func ParseTime(prefix byte, bz []byte) (time.Time, error) { + expectedPrefix := []byte{prefix} + prefixL := len(expectedPrefix) + if prefix := bz[:prefixL]; !bytes.Equal(prefix, expectedPrefix) { + return time.Time{}, fmt.Errorf("invalid prefix; expected: %X, got: %X", expectedPrefix, prefix) + } + timestamp, err := sdk.ParseTimeBytes(bz[prefixL:]) + if err != nil { + return time.Time{}, err + } + return timestamp, nil +} + +// ProviderConsAddrToOptedInConsumerIdsKey returns the key for storing all the consumer ids that `providerAddr` +// has opted-in to +func ProviderConsAddrToOptedInConsumerIdsKey(providerAddr ProviderConsAddress) []byte { + return append([]byte{mustGetKeyPrefix(ProviderConsAddrToOptedInConsumerIdsKeyName)}, providerAddr.ToSdkConsAddr().Bytes()...) } -func AllowInactiveValidatorsKey(chainID string) []byte { - return ChainIdWithLenKey(mustGetKeyPrefix(AllowInactiveValidatorsKeyName), chainID) +// ClientIdToConsumerIdKey returns the consumer id that corresponds to this client id +func ClientIdToConsumerIdKey(clientId string) []byte { + clientIdLength := len(clientId) + return ccvtypes.AppendMany( + // Append the prefix + []byte{mustGetKeyPrefix(ClientIdToConsumerIdKeyName)}, + // Append the client id length + sdk.Uint64ToBigEndian(uint64(clientIdLength)), + // Append the client id + []byte(clientId), + ) } // NOTE: DO NOT ADD FULLY DEFINED KEY FUNCTIONS WITHOUT ADDING THEM TO getAllFullyDefinedKeys() IN keys_test.go @@ -758,97 +771,98 @@ func AllowInactiveValidatorsKey(chainID string) []byte { // Generic helpers section // -// ChainIdAndTsKey returns the key with the following format: -// bytePrefix | len(chainID) | chainID | timestamp -func ChainIdAndTsKey(prefix byte, chainID string, timestamp time.Time) []byte { - partialKey := ChainIdWithLenKey(prefix, chainID) - timeBz := sdk.FormatTimeBytes(timestamp) +// StringIdAndTsKey returns the key with the following format: +// bytePrefix | len(stringId) | stringId | timestamp +func StringIdAndTsKey(prefix byte, stringId string, timestamp time.Time) []byte { return ccvtypes.AppendMany( - // Append the partialKey - partialKey, - // Append the time bytes - timeBz, + StringIdWithLenKey(prefix, stringId), + sdk.FormatTimeBytes(timestamp), ) } -// ChainIdWithLenKey returns the key with the following format: -// bytePrefix | len(chainID) | chainID -func ChainIdWithLenKey(prefix byte, chainID string) []byte { - chainIdL := len(chainID) +// ParseStringIdAndTsKey returns the string id and time for a StringIdAndTs key +func ParseStringIdAndTsKey(prefix byte, bz []byte) (string, time.Time, error) { + expectedPrefix := []byte{prefix} + prefixL := len(expectedPrefix) + if prefix := bz[:prefixL]; !bytes.Equal(prefix, expectedPrefix) { + return "", time.Time{}, fmt.Errorf("invalid prefix; expected: %X, got: %X", expectedPrefix, prefix) + } + stringIdL := sdk.BigEndianToUint64(bz[prefixL : prefixL+8]) + stringId := string(bz[prefixL+8 : prefixL+8+int(stringIdL)]) + timestamp, err := sdk.ParseTimeBytes(bz[prefixL+8+int(stringIdL):]) + if err != nil { + return "", time.Time{}, err + } + return stringId, timestamp, nil +} + +// StringIdWithLenKey returns the key with the following format: +// bytePrefix | len(stringId) | stringId +func StringIdWithLenKey(prefix byte, stringId string) []byte { return ccvtypes.AppendMany( // Append the prefix []byte{prefix}, - // Append the chainID length - sdk.Uint64ToBigEndian(uint64(chainIdL)), - // Append the chainID - []byte(chainID), + // Append the string id length + sdk.Uint64ToBigEndian(uint64(len(stringId))), + // Append the string id + []byte(stringId), ) } -// ParseChainIdAndTsKey returns the chain ID and time for a ChainIdAndTs key -func ParseChainIdAndTsKey(prefix byte, bz []byte) (string, time.Time, error) { +// ParseStringIdWithLenKey returns the stringId of a StringIdWithLen key +func ParseStringIdWithLenKey(prefix byte, bz []byte) (string, error) { expectedPrefix := []byte{prefix} prefixL := len(expectedPrefix) if prefix := bz[:prefixL]; !bytes.Equal(prefix, expectedPrefix) { - return "", time.Time{}, fmt.Errorf("invalid prefix; expected: %X, got: %X", expectedPrefix, prefix) - } - chainIdL := sdk.BigEndianToUint64(bz[prefixL : prefixL+8]) - chainID := string(bz[prefixL+8 : prefixL+8+int(chainIdL)]) - timestamp, err := sdk.ParseTimeBytes(bz[prefixL+8+int(chainIdL):]) - if err != nil { - return "", time.Time{}, err + return "", fmt.Errorf("invalid prefix; expected: %X, got: %X", expectedPrefix, prefix) } - return chainID, timestamp, nil + stringIdL := sdk.BigEndianToUint64(bz[prefixL : prefixL+8]) + stringId := string(bz[prefixL+8 : prefixL+8+int(stringIdL)]) + return stringId, nil } -// ChainIdAndUintIdKey returns the key with the following format: -// bytePrefix | len(chainID) | chainID | uint64(ID) -func ChainIdAndUintIdKey(prefix byte, chainID string, uintId uint64) []byte { - partialKey := ChainIdWithLenKey(prefix, chainID) +// StringIdAndUintIdKey returns the key with the following format: +// bytePrefix | len(stringId) | stringId | uint64(ID) +func StringIdAndUintIdKey(prefix byte, stringId string, uintId uint64) []byte { return ccvtypes.AppendMany( - // Append the partialKey - partialKey, - // Append the uint id bytes + StringIdWithLenKey(prefix, stringId), sdk.Uint64ToBigEndian(uintId), ) } -// ParseChainIdAndUintIdKey returns the chain ID and uint ID for a ChainIdAndUintId key -func ParseChainIdAndUintIdKey(prefix byte, bz []byte) (string, uint64, error) { +// ParseStringIdAndUintIdKey returns the string ID and uint ID for a StringIdAndUintId key +func ParseStringIdAndUintIdKey(prefix byte, bz []byte) (string, uint64, error) { expectedPrefix := []byte{prefix} prefixL := len(expectedPrefix) if prefix := bz[:prefixL]; !bytes.Equal(prefix, expectedPrefix) { return "", 0, fmt.Errorf("invalid prefix; expected: %X, got: %X", expectedPrefix, prefix) } - chainIdL := sdk.BigEndianToUint64(bz[prefixL : prefixL+8]) - chainID := string(bz[prefixL+8 : prefixL+8+int(chainIdL)]) - uintID := sdk.BigEndianToUint64(bz[prefixL+8+int(chainIdL):]) - return chainID, uintID, nil + stringIdL := sdk.BigEndianToUint64(bz[prefixL : prefixL+8]) + stringId := string(bz[prefixL+8 : prefixL+8+int(stringIdL)]) + uintID := sdk.BigEndianToUint64(bz[prefixL+8+int(stringIdL):]) + return stringId, uintID, nil } -// ChainIdAndConsAddrKey returns the key with the following format: -// bytePrefix | len(chainID) | chainID | ConsAddress -func ChainIdAndConsAddrKey(prefix byte, chainID string, addr sdk.ConsAddress) []byte { - partialKey := ChainIdWithLenKey(prefix, chainID) +// StringIdAndConsAddrKey returns the key with the following format: +// bytePrefix | len(stringId) | stringId | ConsAddress +func StringIdAndConsAddrKey(prefix byte, stringId string, addr sdk.ConsAddress) []byte { return ccvtypes.AppendMany( - // Append the partialKey - partialKey, - // Append the addr bytes + StringIdWithLenKey(prefix, stringId), addr, ) } -// ParseChainIdAndConsAddrKey returns the chain ID and ConsAddress for a ChainIdAndConsAddrKey key -func ParseChainIdAndConsAddrKey(prefix byte, bz []byte) (string, sdk.ConsAddress, error) { +// ParseStringIdAndConsAddrKey returns the string ID and ConsAddress for a StringIdAndConsAddr key +func ParseStringIdAndConsAddrKey(prefix byte, bz []byte) (string, sdk.ConsAddress, error) { expectedPrefix := []byte{prefix} prefixL := len(expectedPrefix) if prefix := bz[:prefixL]; !bytes.Equal(prefix, expectedPrefix) { return "", nil, fmt.Errorf("invalid prefix; expected: %X, got: %X", expectedPrefix, prefix) } - chainIdL := sdk.BigEndianToUint64(bz[prefixL : prefixL+8]) - chainID := string(bz[prefixL+8 : prefixL+8+int(chainIdL)]) - addr := bz[prefixL+8+int(chainIdL):] - return chainID, addr, nil + stringIdL := sdk.BigEndianToUint64(bz[prefixL : prefixL+8]) + stringId := string(bz[prefixL+8 : prefixL+8+int(stringIdL)]) + addr := bz[prefixL+8+int(stringIdL):] + return stringId, addr, nil } // diff --git a/x/ccv/provider/types/keys_test.go b/x/ccv/provider/types/keys_test.go index 800b6ee669..92ec762845 100644 --- a/x/ccv/provider/types/keys_test.go +++ b/x/ccv/provider/types/keys_test.go @@ -11,7 +11,6 @@ import ( cryptoutil "github.com/cosmos/interchain-security/v5/testutil/crypto" providerkeeper "github.com/cosmos/interchain-security/v5/x/ccv/provider/keeper" - "github.com/cosmos/interchain-security/v5/x/ccv/provider/types" providertypes "github.com/cosmos/interchain-security/v5/x/ccv/provider/types" ) @@ -41,17 +40,17 @@ func TestPreserveBytePrefix(t *testing.T) { i++ require.Equal(t, byte(4), providertypes.SlashMeterReplenishTimeCandidateKey()[0]) i++ - require.Equal(t, byte(5), providertypes.ChainToChannelKey("chainID")[0]) + require.Equal(t, byte(5), providertypes.ConsumerIdToChannelIdKey("13")[0]) i++ - require.Equal(t, byte(6), providertypes.ChannelToChainKeyPrefix()[0]) + require.Equal(t, byte(6), providertypes.ChannelIdToConsumerIdKeyPrefix()[0]) i++ - require.Equal(t, byte(7), providertypes.ChainToClientKeyPrefix()[0]) + require.Equal(t, byte(7), providertypes.ConsumerIdToClientIdKeyPrefix()[0]) i++ // reserve 8 as deprecated i++ - require.Equal(t, byte(9), providertypes.PendingCAPKeyPrefix()[0]) + // reserve 9 as deprecated i++ - require.Equal(t, byte(10), providertypes.PendingCRPKeyPrefix()[0]) + // reserve 10 as deprecated i++ // reserve 11 as deprecated i++ @@ -59,21 +58,22 @@ func TestPreserveBytePrefix(t *testing.T) { i++ require.Equal(t, byte(13), providertypes.ValsetUpdateBlockHeightKeyPrefix()[0]) i++ - require.Equal(t, byte(14), providertypes.ConsumerGenesisKey("chainID")[0]) + require.Equal(t, byte(14), providertypes.ConsumerGenesisKey("13")[0]) i++ - require.Equal(t, byte(15), providertypes.SlashAcksKey("chainID")[0]) + require.Equal(t, byte(15), providertypes.SlashAcksKey("13")[0]) i++ - require.Equal(t, byte(16), providertypes.InitChainHeightKey("chainID")[0]) + require.Equal(t, byte(16), providertypes.InitChainHeightKey("13")[0]) i++ - require.Equal(t, byte(17), providertypes.PendingVSCsKey("chainID")[0]) + require.Equal(t, byte(17), providertypes.PendingVSCsKey("13")[0]) i++ // reserve 18 as deprecated i++ - require.Equal(t, byte(19), providertypes.ThrottledPacketDataSizeKey("chainID")[0]) + // reserve 19 as deprecated i++ - require.Equal(t, byte(20), providertypes.ThrottledPacketDataKeyPrefix()) + // reserve 20 as deprecated i++ - require.Equal(t, byte(21), providertypes.GlobalSlashEntryKeyPrefix()[0]) + // DEPRECATED + // require.Equal(t, uint8(21), providertypes.GlobalSlashEntryKeyPrefix()[0]) i++ require.Equal(t, byte(22), providertypes.ConsumerValidatorsKeyPrefix()) i++ @@ -89,37 +89,60 @@ func TestPreserveBytePrefix(t *testing.T) { i++ // reserve 28 as deprecated i++ - require.Equal(t, byte(29), providertypes.EquivocationEvidenceMinHeightKey("chainID")[0]) + require.Equal(t, byte(29), providertypes.EquivocationEvidenceMinHeightKey("13")[0]) i++ - require.Equal(t, byte(30), providertypes.ProposedConsumerChainKeyPrefix()[0]) + // reserve 30 as deprecated i++ require.Equal(t, byte(31), providertypes.ConsumerValidatorKeyPrefix()) i++ require.Equal(t, byte(32), providertypes.OptedInKeyPrefix()) i++ - require.Equal(t, byte(33), providertypes.TopNKey("chainID")[0]) + // DEPRECATED + //require.Equal(t, byte(33), providertypes.TopNKey("13")[0]) i++ - require.Equal(t, byte(34), providertypes.ValidatorsPowerCapKey("chainID")[0]) + // DEPRECATED + //require.Equal(t, byte(34), providertypes.ValidatorsPowerCapKey("13")[0]) i++ - require.Equal(t, byte(35), providertypes.ValidatorSetCapKey("chainID")[0]) + // DEPRECATED + //require.Equal(t, byte(35), providertypes.ValidatorSetCapKey("13")[0]) i++ require.Equal(t, byte(36), providertypes.AllowlistKeyPrefix()) i++ require.Equal(t, byte(37), providertypes.DenylistKeyPrefix()) i++ - require.Equal(t, byte(38), providertypes.ConsumerRewardsAllocationKey("chainID")[0]) + require.Equal(t, byte(38), providertypes.ConsumerRewardsAllocationKey("13")[0]) i++ require.Equal(t, byte(39), providertypes.ConsumerCommissionRateKeyPrefix()) i++ - require.Equal(t, byte(40), providertypes.MinimumPowerInTopNKey("chainID")[0]) + require.Equal(t, byte(40), providertypes.MinimumPowerInTopNKey("13")[0]) i++ require.Equal(t, byte(41), providertypes.ConsumerAddrsToPruneV2KeyPrefix()) i++ require.Equal(t, byte(42), providertypes.LastProviderConsensusValsPrefix()[0]) i++ - require.Equal(t, byte(43), providertypes.MinStakeKey("chainID")[0]) + require.Equal(t, byte(43), providertypes.ConsumerIdKey()[0]) i++ - require.Equal(t, byte(44), providertypes.AllowInactiveValidatorsKey("chainID")[0]) + require.Equal(t, byte(44), providertypes.ConsumerIdToChainIdKey("13")[0]) + i++ + require.Equal(t, byte(45), providertypes.ConsumerIdToOwnerAddressKey("13")[0]) + i++ + require.Equal(t, byte(46), providertypes.ConsumerIdToMetadataKeyPrefix()) + i++ + require.Equal(t, byte(47), providertypes.ConsumerIdToInitializationParametersKeyPrefix()) + i++ + require.Equal(t, byte(48), providertypes.ConsumerIdToPowerShapingParametersKey("13")[0]) + i++ + require.Equal(t, byte(49), providertypes.ConsumerIdToPhaseKey("13")[0]) + i++ + require.Equal(t, byte(50), providertypes.ConsumerIdToRemovalTimeKeyPrefix()) + i++ + require.Equal(t, byte(51), providertypes.SpawnTimeToConsumerIdsKeyPrefix()) + i++ + require.Equal(t, byte(52), providertypes.RemovalTimeToConsumerIdsKeyPrefix()) + i++ + require.Equal(t, byte(53), providertypes.ProviderConsAddrToOptedInConsumerIdsKey(providertypes.NewProviderConsAddress([]byte{0x05}))[0]) + i++ + require.Equal(t, byte(54), providertypes.ClientIdToConsumerIdKey("clientId")[0]) i++ prefixes := providertypes.GetAllKeyPrefixes() @@ -156,149 +179,96 @@ func getAllFullyDefinedKeys() [][]byte { providertypes.ValidatorSetUpdateIdKey(), providertypes.SlashMeterKey(), providertypes.SlashMeterReplenishTimeCandidateKey(), - providertypes.ChainToChannelKey("chainID"), - providertypes.ChannelToChainKey("channelID"), - providertypes.ChainToClientKey("chainID"), - providertypes.PendingCAPKey(time.Time{}, "chainID"), - providertypes.PendingCRPKey(time.Time{}, "chainID"), + providertypes.ConsumerIdToChannelIdKey("13"), + providertypes.ChannelToConsumerIdKey("channelID"), + providertypes.ConsumerIdToClientIdKey("13"), providertypes.ValsetUpdateBlockHeightKey(7), - providertypes.ConsumerGenesisKey("chainID"), - providertypes.SlashAcksKey("chainID"), - providertypes.InitChainHeightKey("chainID"), - providertypes.PendingVSCsKey("chainID"), - providertypes.ThrottledPacketDataSizeKey("chainID"), - providertypes.ThrottledPacketDataKey("chainID", 88), - providertypes.GlobalSlashEntryKey(providertypes.GlobalSlashEntry{}), - providertypes.ConsumerValidatorsKey("chainID", providertypes.NewProviderConsAddress([]byte{0x05})), - providertypes.ValidatorsByConsumerAddrKey("chainID", providertypes.NewConsumerConsAddress([]byte{0x05})), + providertypes.ConsumerGenesisKey("13"), + providertypes.SlashAcksKey("13"), + providertypes.InitChainHeightKey("13"), + providertypes.PendingVSCsKey("13"), + providertypes.ConsumerValidatorsKey("13", providertypes.NewProviderConsAddress([]byte{0x05})), + providertypes.ValidatorsByConsumerAddrKey("13", providertypes.NewConsumerConsAddress([]byte{0x05})), providertypes.SlashLogKey(providertypes.NewProviderConsAddress([]byte{0x05})), providertypes.ConsumerRewardDenomsKey("uatom"), - providertypes.EquivocationEvidenceMinHeightKey("chainID"), - providertypes.ProposedConsumerChainKey(1), - providertypes.ConsumerValidatorKey("chainID", providertypes.NewProviderConsAddress([]byte{0x05}).Address.Bytes()), - providertypes.TopNKey("chainID"), - providertypes.ValidatorsPowerCapKey("chainID"), - providertypes.ValidatorSetCapKey("chainID"), - providertypes.AllowlistKey("chainID", providertypes.NewProviderConsAddress([]byte{0x05})), - providertypes.DenylistKey("chainID", providertypes.NewProviderConsAddress([]byte{0x05})), - providertypes.OptedInKey("chainID", providertypes.NewProviderConsAddress([]byte{0x05})), - providertypes.ConsumerRewardsAllocationKey("chainID"), - providertypes.ConsumerCommissionRateKey("chainID", providertypes.NewProviderConsAddress([]byte{0x05})), - providertypes.MinimumPowerInTopNKey("chainID"), - providertypes.ConsumerAddrsToPruneV2Key("chainID", time.Time{}), - providertypes.MinStakeKey("chainID"), - providertypes.AllowInactiveValidatorsKey("chainID"), - providerkeeper.GetValidatorKey(types.LastProviderConsensusValsPrefix(), providertypes.NewProviderConsAddress([]byte{0x05})), + providertypes.EquivocationEvidenceMinHeightKey("13"), + providertypes.ConsumerValidatorKey("13", providertypes.NewProviderConsAddress([]byte{0x05}).Address.Bytes()), + providertypes.AllowlistKey("13", providertypes.NewProviderConsAddress([]byte{0x05})), + providertypes.DenylistKey("13", providertypes.NewProviderConsAddress([]byte{0x05})), + providertypes.OptedInKey("13", providertypes.NewProviderConsAddress([]byte{0x05})), + providertypes.ConsumerRewardsAllocationKey("13"), + providertypes.ConsumerCommissionRateKey("13", providertypes.NewProviderConsAddress([]byte{0x05})), + providertypes.MinimumPowerInTopNKey("13"), + providertypes.ConsumerAddrsToPruneV2Key("13", time.Time{}), + providerkeeper.GetValidatorKey(providertypes.LastProviderConsensusValsPrefix(), providertypes.NewProviderConsAddress([]byte{0x05})), + providertypes.ConsumerIdKey(), + providertypes.ConsumerIdToChainIdKey("13"), + providertypes.ConsumerIdToOwnerAddressKey("13"), + providertypes.ConsumerIdToMetadataKey("13"), + providertypes.ConsumerIdToInitializationParametersKey("13"), + providertypes.ConsumerIdToPowerShapingParametersKey("13"), + providertypes.ConsumerIdToPhaseKey("13"), + providertypes.ConsumerIdToRemovalTimeKey("13"), + providertypes.SpawnTimeToConsumerIdsKey(time.Time{}), + providertypes.RemovalTimeToConsumerIdsKey(time.Time{}), + providertypes.ProviderConsAddrToOptedInConsumerIdsKey(providertypes.NewProviderConsAddress([]byte{0x05})), + providertypes.ClientIdToConsumerIdKey("clientId"), } } -// Tests the construction and parsing of ChainIdAndTs keys -func TestChainIdAndTsKeyAndParse(t *testing.T) { +// Tests the construction and parsing of StringIdAndTs keys +func TestStringIdAndTsKeyAndParse(t *testing.T) { tests := []struct { - prefix byte - chainID string - timestamp time.Time + prefix byte + consumerID string + timestamp time.Time }{ - {prefix: 0x01, chainID: "1", timestamp: time.Now()}, - {prefix: 0x02, chainID: "some other ID", timestamp: time.Date( + {prefix: 0x01, consumerID: "1", timestamp: time.Now()}, + {prefix: 0x02, consumerID: "111", timestamp: time.Date( 2003, 11, 17, 20, 34, 58, 651387237, time.UTC)}, - {prefix: 0x03, chainID: "some other other chain ID", timestamp: time.Now().Add(5000 * time.Hour)}, + {prefix: 0x03, consumerID: "2000", timestamp: time.Now().Add(5000 * time.Hour)}, } for _, test := range tests { - key := providertypes.ChainIdAndTsKey(test.prefix, test.chainID, test.timestamp) + key := providertypes.StringIdAndTsKey(test.prefix, test.consumerID, test.timestamp) require.NotEmpty(t, key) - // Expected bytes = prefix + chainID length + chainID + time bytes - expectedLen := 1 + 8 + len(test.chainID) + len(sdk.FormatTimeBytes(time.Time{})) + // Expected bytes = prefix + consumerID length + consumerID + time bytes + expectedLen := 1 + 8 + len(test.consumerID) + len(sdk.FormatTimeBytes(time.Time{})) require.Equal(t, expectedLen, len(key)) - parsedID, parsedTime, err := providertypes.ParseChainIdAndTsKey(test.prefix, key) - require.Equal(t, test.chainID, parsedID) + parsedID, parsedTime, err := providertypes.ParseStringIdAndTsKey(test.prefix, key) + require.Equal(t, test.consumerID, parsedID) require.Equal(t, test.timestamp.UTC(), parsedTime.UTC()) require.NoError(t, err) } } -// Tests the construction and parsing of ChainIdAndUintId keys -func TestChainIdAndUintIdAndParse(t *testing.T) { +// Tests the construction and parsing of StringIdAndUintId keys +func TestStringIdAndUintIdAndParse(t *testing.T) { tests := []struct { - prefix byte - chainID string - uintID uint64 + prefix byte + consumerID string + uintID uint64 }{ - {prefix: 0x01, chainID: "1", uintID: 1}, - {prefix: 0x02, chainID: "some other ID", uintID: 2}, - {prefix: 0x03, chainID: "some other other chain ID", uintID: 3}, + {prefix: 0x01, consumerID: "1", uintID: 1}, + {prefix: 0x02, consumerID: "13", uintID: 2}, + {prefix: 0x03, consumerID: "245", uintID: 3}, } for _, test := range tests { - key := providertypes.ChainIdAndUintIdKey(test.prefix, test.chainID, test.uintID) + key := providertypes.StringIdAndUintIdKey(test.prefix, test.consumerID, test.uintID) require.NotEmpty(t, key) - // Expected bytes = prefix + chainID length + chainID + vscId bytes - expectedLen := 1 + 8 + len(test.chainID) + 8 + // Expected bytes = prefix + consumerID length + consumerID + vscId bytes + expectedLen := 1 + 8 + len(test.consumerID) + 8 require.Equal(t, expectedLen, len(key)) - parsedChainID, parsedUintID, err := providertypes.ParseChainIdAndUintIdKey(test.prefix, key) - require.Equal(t, test.chainID, parsedChainID) + parsedChainID, parsedUintID, err := providertypes.ParseStringIdAndUintIdKey(test.prefix, key) + require.Equal(t, test.consumerID, parsedChainID) require.Equal(t, test.uintID, parsedUintID) require.NoError(t, err) } } -// Tests the construction and parsing of keys for throttled packet data -func TestThrottledPacketDataKeyAndParse(t *testing.T) { - tests := []struct { - consumerChainID string - ibcSeqNum uint64 - }{ - {consumerChainID: "some chain id", ibcSeqNum: 45}, - {consumerChainID: "some chain id that is longer", ibcSeqNum: 54038}, - {consumerChainID: "some chain id that is longer-er ", ibcSeqNum: 9999999999999999999}, - } - - for _, test := range tests { - key := providertypes.ThrottledPacketDataKey(test.consumerChainID, test.ibcSeqNum) - require.NotEmpty(t, key) - // This key should be of len: prefix + chainID length + chainID + ibcSeqNum - require.Equal(t, 1+8+len(test.consumerChainID)+8, len(key)) - parsedChainID, parsedSeqNum := providertypes.MustParseThrottledPacketDataKey(key) - require.Equal(t, test.consumerChainID, parsedChainID) - require.Equal(t, test.ibcSeqNum, parsedSeqNum) - } - - // Sanity check that two keys with different chain ids but same seq num are different - key1 := providertypes.ThrottledPacketDataKey("chain-7", 45) - key2 := providertypes.ThrottledPacketDataKey("chain-8", 45) - require.NotEqual(t, key1, key2) -} - -// Tests the construction and parsing of keys for global slash entries -func TestGlobalSlashEntryKeyAndParse(t *testing.T) { - now := time.Now() - - providerConsAddrs := []providertypes.ProviderConsAddress{ - cryptoutil.NewCryptoIdentityFromIntSeed(0).ProviderConsAddress(), - cryptoutil.NewCryptoIdentityFromIntSeed(1).ProviderConsAddress(), - cryptoutil.NewCryptoIdentityFromIntSeed(2).ProviderConsAddress(), - } - - entries := []providertypes.GlobalSlashEntry{} - entries = append(entries, providertypes.NewGlobalSlashEntry(now, "chain-0", 2, providerConsAddrs[0])) - entries = append(entries, providertypes.NewGlobalSlashEntry(now.Add(2*time.Hour), "chain-7896978", 3, providerConsAddrs[1])) - entries = append(entries, providertypes.NewGlobalSlashEntry(now.Add(3*time.Hour), "chain-1", 4723894, providerConsAddrs[2])) - - for _, entry := range entries { - key := providertypes.GlobalSlashEntryKey(entry) - require.NotEmpty(t, key) - // This key should be of set length: prefix + 8 + 8 + chainID - require.Equal(t, 1+8+8+len(entry.ConsumerChainID), len(key)) - parsedRecvTime, parsedChainID, parsedIBCSeqNum := providertypes.MustParseGlobalSlashEntryKey(key) - require.Equal(t, entry.RecvTime, parsedRecvTime) - require.Equal(t, entry.ConsumerChainID, parsedChainID) - require.Equal(t, entry.IbcSeqNum, parsedIBCSeqNum) - } -} - -// Tests the construction and parsing of ChainIdAndConsAddr keys -func TestChainIdAndConsAddrAndParse(t *testing.T) { +// Tests the construction and parsing of StringIdAndConsAddr keys +func TestStringIdAndConsAddrAndParse(t *testing.T) { cIds := []*cryptoutil.CryptoIdentity{ cryptoutil.NewCryptoIdentityFromIntSeed(99998), cryptoutil.NewCryptoIdentityFromIntSeed(99999), @@ -309,23 +279,23 @@ func TestChainIdAndConsAddrAndParse(t *testing.T) { pubKey3 := cIds[2].TMCryptoPubKey() tests := []struct { - prefix byte - chainID string - addr sdk.ConsAddress + prefix byte + consumerId string + addr sdk.ConsAddress }{ - {prefix: 0x01, chainID: "1", addr: sdk.ConsAddress(pubKey1.Address())}, - {prefix: 0x02, chainID: "some other ID", addr: sdk.ConsAddress(pubKey2.Address())}, - {prefix: 0x03, chainID: "some other other chain ID", addr: sdk.ConsAddress(pubKey3.Address())}, + {prefix: 0x01, consumerId: "1", addr: sdk.ConsAddress(pubKey1.Address())}, + {prefix: 0x02, consumerId: "23", addr: sdk.ConsAddress(pubKey2.Address())}, + {prefix: 0x03, consumerId: "456", addr: sdk.ConsAddress(pubKey3.Address())}, } for _, test := range tests { - key := providertypes.ChainIdAndConsAddrKey(test.prefix, test.chainID, test.addr) + key := providertypes.StringIdAndConsAddrKey(test.prefix, test.consumerId, test.addr) require.NotEmpty(t, key) - // Expected bytes = prefix + chainID length + chainID + consAddr bytes - expectedLen := 1 + 8 + len(test.chainID) + len(test.addr) + // Expected bytes = prefix + consumerID length + consumerID + consAddr bytes + expectedLen := 1 + 8 + len(test.consumerId) + len(test.addr) require.Equal(t, expectedLen, len(key)) - parsedID, parsedConsAddr, err := providertypes.ParseChainIdAndConsAddrKey(test.prefix, key) - require.Equal(t, test.chainID, parsedID) + parsedID, parsedConsAddr, err := providertypes.ParseStringIdAndConsAddrKey(test.prefix, key) + require.Equal(t, test.consumerId, parsedID) require.Equal(t, test.addr, parsedConsAddr) require.NoError(t, err) } @@ -334,9 +304,9 @@ func TestChainIdAndConsAddrAndParse(t *testing.T) { // Test key packing functions with the format func TestKeysWithPrefixAndId(t *testing.T) { funcs := []func(string) []byte{ - providertypes.ChainToChannelKey, - providertypes.ChannelToChainKey, - providertypes.ChainToClientKey, + providertypes.ConsumerIdToChannelIdKey, + providertypes.ChannelToConsumerIdKey, + providertypes.ConsumerIdToClientIdKey, providertypes.ConsumerGenesisKey, providertypes.SlashAcksKey, providertypes.InitChainHeightKey, @@ -380,21 +350,3 @@ func TestKeysWithUint64Payload(t *testing.T) { } } } - -func TestParseProposedConsumerChainKey(t *testing.T) { - tests := []struct { - chainID string - proposalID uint64 - }{ - {chainID: "1", proposalID: 1}, - {chainID: "some other ID", proposalID: 12}, - {chainID: "some other other chain ID", proposalID: 123}, - } - - for _, test := range tests { - key := providertypes.ProposedConsumerChainKey(test.proposalID) - pID, err := providertypes.ParseProposedConsumerChainKey(key) - require.NoError(t, err) - require.Equal(t, pID, test.proposalID) - } -} diff --git a/x/ccv/provider/types/legacy_proposal.go b/x/ccv/provider/types/legacy_proposal.go index 3124cc3d87..9cc6ef2a77 100644 --- a/x/ccv/provider/types/legacy_proposal.go +++ b/x/ccv/provider/types/legacy_proposal.go @@ -1,21 +1,13 @@ package types import ( - "errors" "fmt" - "strings" time "time" clienttypes "github.com/cosmos/ibc-go/v8/modules/core/02-client/types" - errorsmod "cosmossdk.io/errors" - "cosmossdk.io/math" - evidencetypes "cosmossdk.io/x/evidence/types" - sdk "github.com/cosmos/cosmos-sdk/types" govv1beta1 "github.com/cosmos/cosmos-sdk/x/gov/types/v1beta1" - - ccvtypes "github.com/cosmos/interchain-security/v5/x/ccv/types" ) const ( @@ -100,79 +92,9 @@ func (cccp *ConsumerAdditionProposal) ProposalType() string { return ProposalTypeConsumerAddition } -// ValidatePSSFeatures returns an error if the `topN` and `validatorsPowerCap` parameters are no in the correct ranges -func ValidatePSSFeatures(topN, validatorsPowerCap uint32) error { - // Top N corresponds to the top N% of validators that have to validate the consumer chain and can only be 0 (for an - // Opt In chain) or in the range [50, 100] (for a Top N chain). - if topN != 0 && (topN < 50 || topN > 100) { - return fmt.Errorf("Top N can either be 0 or in the range [50, 100]") - } - - if validatorsPowerCap != 0 && validatorsPowerCap > 100 { - return fmt.Errorf("validators' power cap has to be in the range [1, 100]") - } - - return nil -} - // ValidateBasic runs basic stateless validity checks func (cccp *ConsumerAdditionProposal) ValidateBasic() error { - if err := govv1beta1.ValidateAbstract(cccp); err != nil { - return err - } - - if strings.TrimSpace(cccp.ChainId) == "" { - return errorsmod.Wrap(ErrInvalidConsumerAdditionProposal, "consumer chain id must not be blank") - } - - if cccp.InitialHeight.IsZero() { - return errorsmod.Wrap(ErrInvalidConsumerAdditionProposal, "initial height cannot be zero") - } - - if len(cccp.GenesisHash) == 0 { - return errorsmod.Wrap(ErrInvalidConsumerAdditionProposal, "genesis hash cannot be empty") - } - if len(cccp.BinaryHash) == 0 { - return errorsmod.Wrap(ErrInvalidConsumerAdditionProposal, "binary hash cannot be empty") - } - - if cccp.SpawnTime.IsZero() { - return errorsmod.Wrap(ErrInvalidConsumerAdditionProposal, "spawn time cannot be zero") - } - - if err := ccvtypes.ValidateStringFraction(cccp.ConsumerRedistributionFraction); err != nil { - return errorsmod.Wrapf(ErrInvalidConsumerAdditionProposal, "consumer redistribution fraction is invalid: %s", err) - } - - if err := ccvtypes.ValidatePositiveInt64(cccp.BlocksPerDistributionTransmission); err != nil { - return errorsmod.Wrap(ErrInvalidConsumerAdditionProposal, "blocks per distribution transmission cannot be < 1") - } - - if err := ccvtypes.ValidateDistributionTransmissionChannel(cccp.DistributionTransmissionChannel); err != nil { - return errorsmod.Wrap(ErrInvalidConsumerAdditionProposal, "distribution transmission channel") - } - - if err := ccvtypes.ValidatePositiveInt64(cccp.HistoricalEntries); err != nil { - return errorsmod.Wrap(ErrInvalidConsumerAdditionProposal, "historical entries cannot be < 1") - } - - if err := ccvtypes.ValidateDuration(cccp.CcvTimeoutPeriod); err != nil { - return errorsmod.Wrap(ErrInvalidConsumerAdditionProposal, "ccv timeout period cannot be zero") - } - - if err := ccvtypes.ValidateDuration(cccp.TransferTimeoutPeriod); err != nil { - return errorsmod.Wrap(ErrInvalidConsumerAdditionProposal, "transfer timeout period cannot be zero") - } - - if err := ccvtypes.ValidateDuration(cccp.UnbondingPeriod); err != nil { - return errorsmod.Wrap(ErrInvalidConsumerAdditionProposal, "unbonding period cannot be zero") - } - - err := ValidatePSSFeatures(cccp.Top_N, cccp.ValidatorsPowerCap) - if err != nil { - return errorsmod.Wrapf(ErrInvalidConsumerAdditionProposal, "invalid PSS features: %s", err.Error()) - } - return nil + return fmt.Errorf("ConsumerAdditionProposal is deprecated") } // String returns the string representation of the ConsumerAdditionProposal. @@ -226,18 +148,7 @@ func (sccp *ConsumerRemovalProposal) ProposalType() string { return ProposalType // ValidateBasic runs basic stateless validity checks func (sccp *ConsumerRemovalProposal) ValidateBasic() error { - if err := govv1beta1.ValidateAbstract(sccp); err != nil { - return err - } - - if strings.TrimSpace(sccp.ChainId) == "" { - return errorsmod.Wrap(ErrInvalidConsumerRemovalProp, "consumer chain id must not be blank") - } - - if sccp.StopTime.IsZero() { - return errorsmod.Wrap(ErrInvalidConsumerRemovalProp, "spawn time cannot be zero") - } - return nil + return fmt.Errorf("ConsumerRemovalProposal is deprecated") } // NewConsumerModificationProposal creates a new consumer modification proposal. @@ -274,19 +185,7 @@ func (cccp *ConsumerModificationProposal) ProposalType() string { // ValidateBasic runs basic stateless validity checks func (cccp *ConsumerModificationProposal) ValidateBasic() error { - if err := govv1beta1.ValidateAbstract(cccp); err != nil { - return err - } - - if strings.TrimSpace(cccp.ChainId) == "" { - return errorsmod.Wrap(ErrInvalidConsumerModificationProposal, "consumer chain id must not be blank") - } - - err := ValidatePSSFeatures(cccp.Top_N, cccp.ValidatorsPowerCap) - if err != nil { - return errorsmod.Wrapf(ErrInvalidConsumerModificationProposal, "invalid PSS features: %s", err.Error()) - } - return nil + return fmt.Errorf("ConsumerModificationProposal is deprecated") } // NewEquivocationProposal creates a new equivocation proposal. @@ -310,18 +209,7 @@ func (sp *EquivocationProposal) ProposalType() string { // ValidateBasic runs basic stateless validity checks func (sp *EquivocationProposal) ValidateBasic() error { - if err := govv1beta1.ValidateAbstract(sp); err != nil { - return err - } - if len(sp.Equivocations) == 0 { - return errors.New("invalid equivocation proposal: empty equivocations") - } - for i := 0; i < len(sp.Equivocations); i++ { - if err := sp.Equivocations[i].ValidateBasic(); err != nil { - return err - } - } - return nil + return fmt.Errorf("EquivocationProposal is deprecated") } func NewChangeRewardDenomsProposal(title, description string, @@ -345,35 +233,5 @@ func (crdp *ChangeRewardDenomsProposal) ProposalType() string { // ValidateBasic runs basic stateless validity checks on a ChangeRewardDenomsProposal. func (crdp *ChangeRewardDenomsProposal) ValidateBasic() error { - emptyDenomsToAdd := len(crdp.DenomsToAdd) == 0 - emptyDenomsToRemove := len(crdp.DenomsToRemove) == 0 - // Return error if both sets are empty or nil - if emptyDenomsToAdd && emptyDenomsToRemove { - return fmt.Errorf( - "invalid change reward denoms proposal: both denoms to add and denoms to remove are empty") - } - - // Return error if a denom is in both sets - for _, denomToAdd := range crdp.DenomsToAdd { - for _, denomToRemove := range crdp.DenomsToRemove { - if denomToAdd == denomToRemove { - return fmt.Errorf( - "invalid change reward denoms proposal: %s cannot be both added and removed", denomToAdd) - } - } - } - - // Return error if any denom is "invalid" - for _, denom := range crdp.DenomsToAdd { - if !sdk.NewCoin(denom, math.NewInt(1)).IsValid() { - return fmt.Errorf("invalid change reward denoms proposal: %s is not a valid denom", denom) - } - } - for _, denom := range crdp.DenomsToRemove { - if !sdk.NewCoin(denom, math.NewInt(1)).IsValid() { - return fmt.Errorf("invalid change reward denoms proposal: %s is not a valid denom", denom) - } - } - - return nil + return fmt.Errorf("ChangeRewardDenomsProposal is deprecated") } diff --git a/x/ccv/provider/types/legacy_proposal_test.go b/x/ccv/provider/types/legacy_proposal_test.go deleted file mode 100644 index 02fdb5245e..0000000000 --- a/x/ccv/provider/types/legacy_proposal_test.go +++ /dev/null @@ -1,641 +0,0 @@ -package types_test - -import ( - fmt "fmt" - "testing" - "time" - - clienttypes "github.com/cosmos/ibc-go/v8/modules/core/02-client/types" - ibctmtypes "github.com/cosmos/ibc-go/v8/modules/light-clients/07-tendermint" - "github.com/golang/protobuf/proto" //nolint:staticcheck // see: https://github.com/cosmos/interchain-security/issues/236 - "github.com/stretchr/testify/require" - - "github.com/cosmos/cosmos-sdk/codec" - codectypes "github.com/cosmos/cosmos-sdk/codec/types" - govv1 "github.com/cosmos/cosmos-sdk/x/gov/types/v1" - govv1beta1 "github.com/cosmos/cosmos-sdk/x/gov/types/v1beta1" - - "github.com/cosmos/interchain-security/v5/x/ccv/provider/types" -) - -func TestConsumerAdditionProposalValidateBasic(t *testing.T) { - initialHeight := clienttypes.NewHeight(2, 3) - - testCases := []struct { - name string - proposal govv1beta1.Content - expPass bool - }{ - { - "success", - types.NewConsumerAdditionProposal("title", "description", "chainID", initialHeight, []byte("gen_hash"), []byte("bin_hash"), time.Now(), - "0.75", - 10, - "", - 10000, - 100000000000, - 100000000000, - 100000000000, - 0, - 0, - 0, - nil, - nil, - 0, - false, - ), - true, - }, - { - "success with 0.0 fraction", - types.NewConsumerAdditionProposal("title", "description", "chainID", initialHeight, []byte("gen_hash"), []byte("bin_hash"), time.Now(), - "0.0", // fraction can be 0.0 but not empty - 10, - "", - 10000, - 100000000000, - 100000000000, - 100000000000, - 0, - 0, - 0, - nil, - nil, - 0, - false, - ), - true, - }, - { - "fails validate abstract - empty title", - types.NewConsumerAdditionProposal(" ", "description", "chainID", initialHeight, []byte("gen_hash"), []byte("bin_hash"), time.Now(), - "0.75", - 10, - "", - 10000, - 100000000000, - 100000000000, - 100000000000, - 0, - 0, - 0, - nil, - nil, - 0, - false, - ), - false, - }, - { - "chainID is empty", - types.NewConsumerAdditionProposal("title", "description", " ", initialHeight, []byte("gen_hash"), []byte("bin_hash"), time.Now(), - "0.75", - 10, - "", - 10000, - 100000000000, - 100000000000, - 100000000000, - 0, - 0, - 0, - nil, - nil, - 0, - false, - ), - false, - }, - { - "initial height is zero", - &types.ConsumerAdditionProposal{ - Title: "title", - Description: "description", - ChainId: "chainID", - InitialHeight: clienttypes.Height{}, - GenesisHash: []byte("gen_hash"), - BinaryHash: []byte("bin_hash"), - SpawnTime: time.Now(), - BlocksPerDistributionTransmission: 10, - CcvTimeoutPeriod: 100000000000, - TransferTimeoutPeriod: 100000000000, - ConsumerRedistributionFraction: "0.75", - DistributionTransmissionChannel: "", - HistoricalEntries: 10000, - UnbondingPeriod: 100000000000, - }, - false, - }, - { - "genesis hash is empty", - types.NewConsumerAdditionProposal("title", "description", "chainID", initialHeight, []byte(""), []byte("bin_hash"), time.Now(), - "0.75", - 10, - "", - 10000, - 100000000000, - 100000000000, - 100000000000, - 0, - 0, - 0, - nil, - nil, - 0, - false, - ), - false, - }, - { - "binary hash is empty", - types.NewConsumerAdditionProposal("title", "description", "chainID", initialHeight, []byte("gen_hash"), []byte(""), time.Now(), - "0.75", - 10, - "", - 10000, - 100000000000, - 100000000000, - 100000000000, - 0, - 0, - 0, - nil, - nil, - 0, - false, - ), - false, - }, - { - "spawn time is zero", - types.NewConsumerAdditionProposal("title", "description", "chainID", initialHeight, []byte("gen_hash"), []byte("bin_hash"), time.Time{}, - "0.75", - 10, - "", - 10000, - 100000000000, - 100000000000, - 100000000000, - 0, - 0, - 0, - nil, - nil, - 0, - false, - ), - false, - }, - { - "consumer redistribution fraction is invalid", - types.NewConsumerAdditionProposal("title", "description", "chainID", initialHeight, []byte("gen_hash"), []byte("bin_hash"), time.Now(), - "", // fraction can be 0.0 but not empty - 10, - "", - 10000, - 100000000000, - 100000000000, - 100000000000, - 0, - 0, - 0, - nil, - nil, - 0, - false, - ), - false, - }, - { - "blocks per distribution transmission is invalid", - types.NewConsumerAdditionProposal("title", "description", "chainID", initialHeight, []byte("gen_hash"), []byte("bin_hash"), time.Now(), - "0.75", - 0, - "", - 100000000000, - 10000, - 100000000000, - 100000000000, - 0, - 0, - 0, - nil, - nil, - 0, - false, - ), - false, - }, - { - "distribution transmission channel is invalid", - types.NewConsumerAdditionProposal("title", "description", "chainID", initialHeight, []byte("gen_hash"), []byte("bin_hash"), time.Now(), - "0.75", - 10, - "badchannel/", - 10000, - 100000000000, - 100000000000, - 100000000000, - 0, - 0, - 0, - nil, - nil, - 0, - false, - ), - false, - }, - { - "historical entries is invalid", - types.NewConsumerAdditionProposal("title", "description", "chainID", initialHeight, []byte("gen_hash"), []byte("bin_hash"), time.Now(), - "0.75", - 10, - "", - -2, - 100000000000, - 100000000000, - 100000000000, - 0, - 0, - 0, - nil, - nil, - 0, - false, - ), - false, - }, - { - "ccv timeout period is invalid", - types.NewConsumerAdditionProposal("title", "description", "chainID", initialHeight, []byte("gen_hash"), []byte("bin_hash"), time.Now(), - "0.75", - 10, - "", - 10000, - 0, - 100000000000, - 100000000000, - 0, - 0, - 0, - nil, - nil, - 0, - false, - ), - false, - }, - { - "transfer timeout period is invalid", - types.NewConsumerAdditionProposal("title", "description", "chainID", initialHeight, []byte("gen_hash"), []byte("bin_hash"), time.Now(), - "0.75", - 10, - "", - 10000, - 100000000000, - 0, - 100000000000, - 0, - 0, - 0, - nil, - nil, - 0, - false, - ), - false, - }, - { - "unbonding period is invalid", - types.NewConsumerAdditionProposal("title", "description", "chainID", initialHeight, []byte("gen_hash"), []byte("bin_hash"), time.Now(), - "0.75", - 10, - "", - 10000, - 100000000000, - 100000000000, - 0, - 0, - 0, - 0, - nil, - nil, - 0, - false, - ), - false, - }, - { - "top N is invalid", - types.NewConsumerAdditionProposal("title", "description", "chainID", initialHeight, []byte("gen_hash"), []byte("bin_hash"), time.Now(), - "0.75", - 10, - "", - 10000, - 100000000000, - 100000000000, - 100000000000, - 10, - 0, - 0, - nil, - nil, - 0, - false, - ), - false, - }, - { - "validators power cap is invalid", - types.NewConsumerAdditionProposal("title", "description", "chainID", initialHeight, []byte("gen_hash"), []byte("bin_hash"), time.Now(), - "0.75", - 10, - "", - 10000, - 100000000000, - 100000000000, - 100000000000, - 50, - 101, - 0, - nil, - nil, - 0, - false, - ), - false, - }, - { - "valid proposal with PSS features", - types.NewConsumerAdditionProposal("title", "description", "chainID", initialHeight, []byte("gen_hash"), []byte("bin_hash"), time.Now(), - "0.75", - 10, - "", - 10000, - 100000000000, - 100000000000, - 100000000000, - 0, - 34, - 101, - []string{"addr1"}, - []string{"addr2", "addr3"}, - 0, - false, - ), - true, - }, - } - - for _, tc := range testCases { - - err := tc.proposal.ValidateBasic() - if tc.expPass { - require.NoError(t, err, "valid case: %s should not return error. got %w", tc.name, err) - } else { - require.Error(t, err, "invalid case: '%s' must return error but got none", tc.name) - } - } -} - -func TestMarshalConsumerAdditionProposal(t *testing.T) { - content := types.NewConsumerAdditionProposal("title", "description", "chainID", clienttypes.NewHeight(0, 1), []byte("gen_hash"), []byte("bin_hash"), time.Now().UTC(), - "0.75", - 10, - "", - 10000, - 100000000000, - 100000000000, - 100000000000, - 0, - 0, - 0, - nil, - nil, - 0, - false, - ) - - cccp, ok := content.(*types.ConsumerAdditionProposal) - require.True(t, ok) - - // create codec - ir := codectypes.NewInterfaceRegistry() - types.RegisterInterfaces(ir) - govv1.RegisterInterfaces(ir) - clienttypes.RegisterInterfaces(ir) - ibctmtypes.RegisterInterfaces(ir) - cdc := codec.NewProtoCodec(ir) - - // marshal proposal - bz, err := cdc.MarshalJSON(cccp) - require.NoError(t, err) - - // unmarshal proposal - newCccp := &types.ConsumerAdditionProposal{} - err = cdc.UnmarshalJSON(bz, newCccp) - require.NoError(t, err) - - require.True(t, proto.Equal(cccp, newCccp), "unmarshalled proposal does not equal original proposal") -} - -func TestConsumerAdditionProposalString(t *testing.T) { - initialHeight := clienttypes.NewHeight(2, 3) - spawnTime := time.Now() - proposal := types.NewConsumerAdditionProposal( - "title", - "description", - "chainID", - initialHeight, - []byte("gen_hash"), - []byte("bin_hash"), - spawnTime, - "0.75", - 10001, - "", - 500000, - 100000000000, - 10000000000, - 100000000000, - 0, - 0, - 0, - []string{}, - []string{}, - 0, - false, - ) - - expect := fmt.Sprintf(`CreateConsumerChain Proposal - Title: title - Description: description - ChainID: chainID - InitialHeight: %s - GenesisHash: %s - BinaryHash: %s - SpawnTime: %s - ConsumerRedistributionFraction: %s - BlocksPerDistributionTransmission: %d - DistributionTransmissionChannel: %s - HistoricalEntries: %d - CcvTimeoutPeriod: %d - TransferTimeoutPeriod: %d - UnbondingPeriod: %d`, initialHeight, []byte("gen_hash"), []byte("bin_hash"), spawnTime, - "0.75", - 10001, - "", - 500000, - 100000000000, - 10000000000, - 100000000000) - - require.Equal(t, expect, proposal.String(), "string method for ConsumerAdditionProposal returned unexpected string") -} - -func TestChangeRewardDenomsProposalValidateBasic(t *testing.T) { - tcs := []struct { - name string - proposal govv1beta1.Content - expectError bool - expectPanic bool - }{ - { - name: "invalid change reward denoms proposal, none to add or remove", - proposal: types.NewChangeRewardDenomsProposal( - "title", "description", []string{}, []string{}), - expectError: true, - }, - { - name: "invalid change reward denoms proposal, same denom in both sets", - proposal: types.NewChangeRewardDenomsProposal( - "title", "description", []string{"denom1"}, []string{"denom1"}), - expectError: true, - }, - { - name: "valid change reward denoms proposal", - proposal: types.NewChangeRewardDenomsProposal( - "title", "description", []string{"denom1"}, []string{"denom2"}), - expectError: false, - }, - { - name: "invalid prop, invalid denom, will panic", - proposal: types.NewChangeRewardDenomsProposal( - "title", "description", []string{"!@blah"}, []string{"denom2"}), - expectPanic: true, - }, - } - - for _, tc := range tcs { - t.Run(tc.name, func(t *testing.T) { - if tc.expectPanic { - require.Panics(t, func() { tc.proposal.ValidateBasic() }) - return - } - err := tc.proposal.ValidateBasic() - if tc.expectError { - require.Error(t, err) - return - } - require.NoError(t, err) - }) - } -} - -func TestConsumerModificationProposalValidateBasic(t *testing.T) { - testCases := []struct { - name string - proposal govv1beta1.Content - expPass bool - }{ - { - "success", - types.NewConsumerModificationProposal("title", "description", "chainID", - 50, - 100, - 34, - []string{"addr1"}, - nil, - 0, - false, - ), - true, - }, - { - "invalid chain id", - types.NewConsumerModificationProposal("title", "description", " ", - 0, - 0, - 0, - nil, - nil, - 0, - false, - ), - false, - }, - { - "top N is invalid", - types.NewConsumerModificationProposal("title", "description", "chainID", - 10, - 0, - 0, - nil, - nil, - 0, - false, - ), - false, - }, - { - "validators power cap is invalid", - types.NewConsumerModificationProposal("title", "description", "chainID", - 50, - 101, - 0, - nil, - nil, - 0, - false, - ), - false, - }, - { - "valid proposal", - types.NewConsumerModificationProposal("title", "description", "chainID", - 0, - 34, - 101, - []string{"addr1"}, - []string{"addr2", "addr3"}, - 0, - false, - ), - true, - }, - } - - for _, tc := range testCases { - - err := tc.proposal.ValidateBasic() - if tc.expPass { - require.NoError(t, err, "valid case: %s should not return error. got %w", tc.name, err) - } else { - require.Error(t, err, "invalid case: '%s' must return error but got none", tc.name) - } - } -} - -func TestValidatePSSFeatures(t *testing.T) { - require.NoError(t, types.ValidatePSSFeatures(0, 0)) - require.NoError(t, types.ValidatePSSFeatures(50, 0)) - require.NoError(t, types.ValidatePSSFeatures(100, 0)) - require.NoError(t, types.ValidatePSSFeatures(0, 10)) - require.NoError(t, types.ValidatePSSFeatures(0, 100)) - require.NoError(t, types.ValidatePSSFeatures(50, 100)) - - require.Error(t, types.ValidatePSSFeatures(10, 0)) - require.Error(t, types.ValidatePSSFeatures(49, 0)) - require.Error(t, types.ValidatePSSFeatures(101, 0)) - require.Error(t, types.ValidatePSSFeatures(50, 101)) -} diff --git a/x/ccv/provider/types/msg.go b/x/ccv/provider/types/msg.go index f9b84af0e4..f7ddd1ad4a 100644 --- a/x/ccv/provider/types/msg.go +++ b/x/ccv/provider/types/msg.go @@ -3,50 +3,55 @@ package types import ( "encoding/json" "fmt" + "strconv" "strings" + cmttypes "github.com/cometbft/cometbft/types" + ibctmtypes "github.com/cosmos/ibc-go/v8/modules/light-clients/07-tendermint" errorsmod "cosmossdk.io/errors" "cosmossdk.io/math" sdk "github.com/cosmos/cosmos-sdk/types" - sdkerrors "github.com/cosmos/cosmos-sdk/types/errors" tmtypes "github.com/cometbft/cometbft/proto/tendermint/types" ccvtypes "github.com/cosmos/interchain-security/v5/x/ccv/types" ) -// provider message types const ( - TypeMsgAssignConsumerKey = "assign_consumer_key" - TypeMsgSubmitConsumerMisbehaviour = "submit_consumer_misbehaviour" - TypeMsgSubmitConsumerDoubleVoting = "submit_consumer_double_vote" - TypeMsgOptIn = "opt_in" - TypeMsgOptOut = "opt_out" - TypeMsgSetConsumerCommissionRate = "set_consumer_commission_rate" + // MaxNameLength defines the maximum consumer name length + MaxNameLength = 50 + // MaxDescriptionLength defines the maximum consumer description length + MaxDescriptionLength = 10000 + // MaxMetadataLength defines the maximum consumer metadata length + MaxMetadataLength = 255 + // MaxHashLength defines the maximum length of a hash + MaxHashLength = 64 + // MaxValidatorCount defines the maximum number of validators + MaxValidatorCount = 1000 ) var ( _ sdk.Msg = (*MsgAssignConsumerKey)(nil) - _ sdk.Msg = (*MsgConsumerAddition)(nil) - _ sdk.Msg = (*MsgConsumerRemoval)(nil) - _ sdk.Msg = (*MsgConsumerModification)(nil) _ sdk.Msg = (*MsgChangeRewardDenoms)(nil) _ sdk.Msg = (*MsgSubmitConsumerMisbehaviour)(nil) _ sdk.Msg = (*MsgSubmitConsumerDoubleVoting)(nil) + _ sdk.Msg = (*MsgCreateConsumer)(nil) + _ sdk.Msg = (*MsgUpdateConsumer)(nil) + _ sdk.Msg = (*MsgRemoveConsumer)(nil) _ sdk.Msg = (*MsgOptIn)(nil) _ sdk.Msg = (*MsgOptOut)(nil) _ sdk.Msg = (*MsgSetConsumerCommissionRate)(nil) _ sdk.HasValidateBasic = (*MsgAssignConsumerKey)(nil) - _ sdk.HasValidateBasic = (*MsgConsumerAddition)(nil) - _ sdk.HasValidateBasic = (*MsgConsumerRemoval)(nil) - _ sdk.HasValidateBasic = (*MsgConsumerModification)(nil) _ sdk.HasValidateBasic = (*MsgChangeRewardDenoms)(nil) _ sdk.HasValidateBasic = (*MsgSubmitConsumerMisbehaviour)(nil) _ sdk.HasValidateBasic = (*MsgSubmitConsumerDoubleVoting)(nil) + _ sdk.HasValidateBasic = (*MsgCreateConsumer)(nil) + _ sdk.HasValidateBasic = (*MsgUpdateConsumer)(nil) + _ sdk.HasValidateBasic = (*MsgRemoveConsumer)(nil) _ sdk.HasValidateBasic = (*MsgOptIn)(nil) _ sdk.HasValidateBasic = (*MsgOptOut)(nil) _ sdk.HasValidateBasic = (*MsgSetConsumerCommissionRate)(nil) @@ -54,470 +59,538 @@ var ( // NewMsgAssignConsumerKey creates a new MsgAssignConsumerKey instance. // Delegator address and validator address are the same. -func NewMsgAssignConsumerKey(chainID string, providerValidatorAddress sdk.ValAddress, - consumerConsensusPubKey, signer string, +func NewMsgAssignConsumerKey(consumerId string, providerValidatorAddress sdk.ValAddress, + consumerConsensusPubKey, submitter string, ) (*MsgAssignConsumerKey, error) { return &MsgAssignConsumerKey{ - ChainId: chainID, + ConsumerId: consumerId, ProviderAddr: providerValidatorAddress.String(), ConsumerKey: consumerConsensusPubKey, - Signer: signer, + Submitter: submitter, }, nil } -// Route implements the sdk.Msg interface. -func (msg MsgAssignConsumerKey) Route() string { return RouterKey } - -// Type implements the sdk.Msg interface. -func (msg MsgAssignConsumerKey) Type() string { - return TypeMsgAssignConsumerKey -} - -// GetSigners implements the sdk.Msg interface. It returns the address(es) that -// must sign over msg.GetSignBytes(). -// If the validator address is not same as delegator's, then the validator must -// sign the msg as well. -func (msg MsgAssignConsumerKey) GetSigners() []sdk.AccAddress { - valAddr, err := sdk.ValAddressFromBech32(msg.ProviderAddr) - if err != nil { - // same behavior as in cosmos-sdk - panic(err) - } - return []sdk.AccAddress{valAddr.Bytes()} -} - -// GetSignBytes returns the message bytes to sign over. -func (msg MsgAssignConsumerKey) GetSignBytes() []byte { - bz := ccvtypes.ModuleCdc.MustMarshalJSON(&msg) - return sdk.MustSortJSON(bz) -} - -// ValidateBasic implements the sdk.Msg interface. +// ValidateBasic implements the sdk.HasValidateBasic interface. func (msg MsgAssignConsumerKey) ValidateBasic() error { - if strings.TrimSpace(msg.ChainId) == "" { - return errorsmod.Wrapf(ErrInvalidConsumerChainID, "chainId cannot be blank") - } - // It is possible to assign keys for consumer chains that are not yet approved. - // This can only be done by a signing validator, but it is still sensible - // to limit the chainID size to prevent abuse. - if 128 < len(msg.ChainId) { - return errorsmod.Wrapf(ErrInvalidConsumerChainID, "chainId cannot exceed 128 length") + if err := validateDeprecatedChainId(msg.ChainId); err != nil { + return errorsmod.Wrapf(ErrInvalidMsgAssignConsumerKey, "ChainId: %s", err.Error()) } - valAddr, err := sdk.ValAddressFromBech32(msg.ProviderAddr) - if err != nil { - return ErrInvalidProviderAddress + + if err := ValidateConsumerId(msg.ConsumerId); err != nil { + return errorsmod.Wrapf(ErrInvalidMsgAssignConsumerKey, "ConsumerId: %s", err.Error()) } - // Check that the provider validator address and the signer address are the same - if sdk.AccAddress(valAddr.Bytes()).String() != msg.Signer { - return errorsmod.Wrapf(ErrInvalidProviderAddress, "provider validator address must be the same as the signer address") + + if err := validateProviderAddress(msg.ProviderAddr, msg.Submitter); err != nil { + return errorsmod.Wrapf(ErrInvalidMsgAssignConsumerKey, "ProviderAddr: %s", err.Error()) } + if msg.ConsumerKey == "" { - return ErrInvalidConsumerConsensusPubKey + return errorsmod.Wrapf(ErrInvalidMsgAssignConsumerKey, "ConsumerKey cannot be empty") } if _, _, err := ParseConsumerKeyFromJson(msg.ConsumerKey); err != nil { - return ErrInvalidConsumerConsensusPubKey + return errorsmod.Wrapf(ErrInvalidMsgAssignConsumerKey, "ConsumerKey: %s", err.Error()) } + return nil } -// ParseConsumerKeyFromJson parses the consumer key from a JSON string, -// this replaces deserializing a protobuf any. -func ParseConsumerKeyFromJson(jsonStr string) (pkType, key string, err error) { - type PubKey struct { - Type string `json:"@type"` - Key string `json:"key"` +// ValidateBasic implements the sdk.HasValidateBasic interface. +func (msg *MsgChangeRewardDenoms) ValidateBasic() error { + emptyDenomsToAdd := len(msg.DenomsToAdd) == 0 + emptyDenomsToRemove := len(msg.DenomsToRemove) == 0 + // Return error if both sets are empty or nil + if emptyDenomsToAdd && emptyDenomsToRemove { + return errorsmod.Wrapf(ErrInvalidMsgChangeRewardDenoms, "both DenomsToAdd and DenomsToRemove are empty") } - var pubKey PubKey - err = json.Unmarshal([]byte(jsonStr), &pubKey) - if err != nil { - return "", "", err + + denomMap := map[string]struct{}{} + for _, denom := range msg.DenomsToAdd { + // validate the denom + if !sdk.NewCoin(denom, math.NewInt(1)).IsValid() { + return errorsmod.Wrapf(ErrInvalidMsgChangeRewardDenoms, "DenomsToAdd: invalid denom(%s)", denom) + } + denomMap[denom] = struct{}{} + } + for _, denom := range msg.DenomsToRemove { + // validate the denom + if !sdk.NewCoin(denom, math.NewInt(1)).IsValid() { + return errorsmod.Wrapf(ErrInvalidMsgChangeRewardDenoms, "DenomsToRemove: invalid denom(%s)", denom) + } + // denom cannot be in both sets + if _, found := denomMap[denom]; found { + return errorsmod.Wrapf(ErrInvalidMsgChangeRewardDenoms, + "denom(%s) cannot be both added and removed", denom) + } } - return pubKey.Type, pubKey.Key, nil -} -func NewMsgSubmitConsumerMisbehaviour(submitter sdk.AccAddress, misbehaviour *ibctmtypes.Misbehaviour) (*MsgSubmitConsumerMisbehaviour, error) { - return &MsgSubmitConsumerMisbehaviour{Submitter: submitter.String(), Misbehaviour: misbehaviour}, nil + return nil } -// Route implements the sdk.Msg interface. -func (msg MsgSubmitConsumerMisbehaviour) Route() string { return RouterKey } - -// Type implements the sdk.Msg interface. -func (msg MsgSubmitConsumerMisbehaviour) Type() string { - return TypeMsgSubmitConsumerMisbehaviour +func NewMsgSubmitConsumerMisbehaviour( + consumerId string, + submitter sdk.AccAddress, + misbehaviour *ibctmtypes.Misbehaviour, +) (*MsgSubmitConsumerMisbehaviour, error) { + return &MsgSubmitConsumerMisbehaviour{ + Submitter: submitter.String(), + Misbehaviour: misbehaviour, + ConsumerId: consumerId, + }, nil } -// Type implements the sdk.Msg interface. +// ValidateBasic implements the sdk.HasValidateBasic interface. func (msg MsgSubmitConsumerMisbehaviour) ValidateBasic() error { - if msg.Submitter == "" { - return errorsmod.Wrap(sdkerrors.ErrInvalidAddress, msg.Submitter) + if err := ValidateConsumerId(msg.ConsumerId); err != nil { + return errorsmod.Wrapf(ErrInvalidMsgSubmitConsumerMisbehaviour, "ConsumerId: %s", err.Error()) } if err := msg.Misbehaviour.ValidateBasic(); err != nil { - return err + return errorsmod.Wrapf(ErrInvalidMsgSubmitConsumerMisbehaviour, "Misbehaviour: %s", err.Error()) } return nil } -// Type implements the sdk.Msg interface. -func (msg MsgSubmitConsumerMisbehaviour) GetSignBytes() []byte { - bz := ccvtypes.ModuleCdc.MustMarshalJSON(&msg) - return sdk.MustSortJSON(bz) +func NewMsgSubmitConsumerDoubleVoting( + consumerId string, + submitter sdk.AccAddress, + ev *tmtypes.DuplicateVoteEvidence, + header *ibctmtypes.Header, +) (*MsgSubmitConsumerDoubleVoting, error) { + return &MsgSubmitConsumerDoubleVoting{ + Submitter: submitter.String(), + DuplicateVoteEvidence: ev, + InfractionBlockHeader: header, + ConsumerId: consumerId, + }, nil } -// Type implements the sdk.Msg interface. -func (msg MsgSubmitConsumerMisbehaviour) GetSigners() []sdk.AccAddress { - addr, err := sdk.AccAddressFromBech32(msg.Submitter) - if err != nil { - // same behavior as in cosmos-sdk - panic(err) +// ValidateBasic implements the sdk.HasValidateBasic interface. +func (msg MsgSubmitConsumerDoubleVoting) ValidateBasic() error { + if dve, err := cmttypes.DuplicateVoteEvidenceFromProto(msg.DuplicateVoteEvidence); err != nil { + return errorsmod.Wrapf(ErrInvalidMsgSubmitConsumerDoubleVoting, "DuplicateVoteEvidence: %s", err.Error()) + } else { + if err = dve.ValidateBasic(); err != nil { + return errorsmod.Wrapf(ErrInvalidMsgSubmitConsumerDoubleVoting, "DuplicateVoteEvidence: %s", err.Error()) + } } - return []sdk.AccAddress{addr} -} -func NewMsgSubmitConsumerDoubleVoting(submitter sdk.AccAddress, ev *tmtypes.DuplicateVoteEvidence, header *ibctmtypes.Header) (*MsgSubmitConsumerDoubleVoting, error) { - return &MsgSubmitConsumerDoubleVoting{Submitter: submitter.String(), DuplicateVoteEvidence: ev, InfractionBlockHeader: header}, nil -} + if err := ValidateHeaderForConsumerDoubleVoting(msg.InfractionBlockHeader); err != nil { + return errorsmod.Wrapf(ErrInvalidMsgSubmitConsumerDoubleVoting, "ValidateTendermintHeader: %s", err.Error()) + } -// Route implements the sdk.Msg interface. -func (msg MsgSubmitConsumerDoubleVoting) Route() string { return RouterKey } + if err := ValidateConsumerId(msg.ConsumerId); err != nil { + return errorsmod.Wrapf(ErrInvalidMsgSubmitConsumerDoubleVoting, "ConsumerId: %s", err.Error()) + } -// Type implements the sdk.Msg interface. -func (msg MsgSubmitConsumerDoubleVoting) Type() string { - return TypeMsgSubmitConsumerDoubleVoting + return nil } -// Type implements the sdk.Msg interface. -func (msg MsgSubmitConsumerDoubleVoting) ValidateBasic() error { - if msg.Submitter == "" { - return errorsmod.Wrap(sdkerrors.ErrInvalidAddress, msg.Submitter) - } - if msg.DuplicateVoteEvidence == nil { - return fmt.Errorf("double voting evidence cannot be nil") - } +// NewMsgOptIn creates a new NewMsgOptIn instance. +func NewMsgOptIn(consumerId string, providerValidatorAddress sdk.ValAddress, consumerConsensusPubKey, submitter string) (*MsgOptIn, error) { + return &MsgOptIn{ + ConsumerId: consumerId, + ProviderAddr: providerValidatorAddress.String(), + ConsumerKey: consumerConsensusPubKey, + Submitter: submitter, + }, nil +} - if msg.InfractionBlockHeader == nil { - return fmt.Errorf("infraction block header cannot be nil") +// ValidateBasic implements the sdk.HasValidateBasic interface. +func (msg MsgOptIn) ValidateBasic() error { + if err := validateDeprecatedChainId(msg.ChainId); err != nil { + return errorsmod.Wrapf(ErrInvalidMsgOptIn, "ChainId: %s", err.Error()) } - if msg.InfractionBlockHeader.SignedHeader == nil { - return fmt.Errorf("signed header in infraction block header cannot be nil") + if err := ValidateConsumerId(msg.ConsumerId); err != nil { + return errorsmod.Wrapf(ErrInvalidMsgOptIn, "ConsumerId: %s", err.Error()) } - if msg.InfractionBlockHeader.SignedHeader.Header == nil { - return fmt.Errorf("invalid signed header in infraction block header, 'SignedHeader.Header' is nil") + if err := validateProviderAddress(msg.ProviderAddr, msg.Submitter); err != nil { + return errorsmod.Wrapf(ErrInvalidMsgOptIn, "ProviderAddr: %s", err.Error()) } - if msg.InfractionBlockHeader.ValidatorSet == nil { - return fmt.Errorf("invalid infraction block header, validator set is nil") + if msg.ConsumerKey != "" { + if _, _, err := ParseConsumerKeyFromJson(msg.ConsumerKey); err != nil { + return errorsmod.Wrapf(ErrInvalidMsgOptIn, "ConsumerKey: %s", err.Error()) + } } - return nil } -// Type implements the sdk.Msg interface. -func (msg MsgSubmitConsumerDoubleVoting) GetSignBytes() []byte { - bz := ccvtypes.ModuleCdc.MustMarshalJSON(&msg) - return sdk.MustSortJSON(bz) +// NewMsgOptOut creates a new NewMsgOptIn instance. +func NewMsgOptOut(consumerId string, providerValidatorAddress sdk.ValAddress, submitter string) (*MsgOptOut, error) { + return &MsgOptOut{ + ConsumerId: consumerId, + ProviderAddr: providerValidatorAddress.String(), + Submitter: submitter, + }, nil } -// Type implements the sdk.Msg interface. -func (msg MsgSubmitConsumerDoubleVoting) GetSigners() []sdk.AccAddress { - addr, err := sdk.AccAddressFromBech32(msg.Submitter) - if err != nil { - // same behavior as in cosmos-sdk - panic(err) +// ValidateBasic implements the sdk.HasValidateBasic interface. +func (msg MsgOptOut) ValidateBasic() error { + if err := validateDeprecatedChainId(msg.ChainId); err != nil { + return errorsmod.Wrapf(ErrInvalidMsgOptOut, "ChainId: %s", err.Error()) } - return []sdk.AccAddress{addr} -} -// GetSigners implements the sdk.Msg interface. It returns the address(es) that -// must sign over msg.GetSignBytes(). -// If the validator address is not same as delegator's, then the validator must -// sign the msg as well. -func (msg *MsgConsumerAddition) GetSigners() []sdk.AccAddress { - valAddr, err := sdk.ValAddressFromBech32(msg.Authority) - if err != nil { - // same behavior as in cosmos-sdk - panic(err) + if err := ValidateConsumerId(msg.ConsumerId); err != nil { + return errorsmod.Wrapf(ErrInvalidMsgOptOut, "ConsumerId: %s", err.Error()) } - return []sdk.AccAddress{valAddr.Bytes()} -} -// ValidateBasic implements the sdk.Msg interface. -func (msg *MsgConsumerAddition) ValidateBasic() error { - if strings.TrimSpace(msg.ChainId) == "" { - return ErrBlankConsumerChainID + if err := validateProviderAddress(msg.ProviderAddr, msg.Submitter); err != nil { + return errorsmod.Wrapf(ErrInvalidMsgOptOut, "ProviderAddr: %s", err.Error()) } - if msg.InitialHeight.IsZero() { - return errorsmod.Wrap(ErrInvalidConsumerAdditionProposal, "initial height cannot be zero") - } + return nil +} - if len(msg.GenesisHash) == 0 { - return errorsmod.Wrap(ErrInvalidConsumerAdditionProposal, "genesis hash cannot be empty") - } - if len(msg.BinaryHash) == 0 { - return errorsmod.Wrap(ErrInvalidConsumerAdditionProposal, "binary hash cannot be empty") +// NewMsgSetConsumerCommissionRate creates a new MsgSetConsumerCommissionRate msg instance. +func NewMsgSetConsumerCommissionRate( + consumerId string, + commission math.LegacyDec, + providerValidatorAddress sdk.ValAddress, + submitter string, +) *MsgSetConsumerCommissionRate { + return &MsgSetConsumerCommissionRate{ + ConsumerId: consumerId, + Rate: commission, + ProviderAddr: providerValidatorAddress.String(), + Submitter: submitter, } +} - if msg.SpawnTime.IsZero() { - return errorsmod.Wrap(ErrInvalidConsumerAdditionProposal, "spawn time cannot be zero") +// ValidateBasic implements the sdk.HasValidateBasic interface. +func (msg MsgSetConsumerCommissionRate) ValidateBasic() error { + if err := validateDeprecatedChainId(msg.ChainId); err != nil { + return errorsmod.Wrapf(ErrInvalidMsgSetConsumerCommissionRate, "ChainId: %s", err.Error()) } - if err := ccvtypes.ValidateStringFraction(msg.ConsumerRedistributionFraction); err != nil { - return errorsmod.Wrapf(ErrInvalidConsumerAdditionProposal, "consumer redistribution fraction is invalid: %s", err) + if err := ValidateConsumerId(msg.ConsumerId); err != nil { + return errorsmod.Wrapf(ErrInvalidMsgSetConsumerCommissionRate, "ConsumerId: %s", err.Error()) } - if err := ccvtypes.ValidatePositiveInt64(msg.BlocksPerDistributionTransmission); err != nil { - return errorsmod.Wrap(ErrInvalidConsumerAdditionProposal, "blocks per distribution transmission cannot be < 1") + if err := validateProviderAddress(msg.ProviderAddr, msg.Submitter); err != nil { + return errorsmod.Wrapf(ErrInvalidMsgSetConsumerCommissionRate, "ProviderAddr: %s", err.Error()) } - if err := ccvtypes.ValidateDistributionTransmissionChannel(msg.DistributionTransmissionChannel); err != nil { - return errorsmod.Wrap(ErrInvalidConsumerAdditionProposal, "distribution transmission channel") + if msg.Rate.IsNegative() || msg.Rate.GT(math.LegacyOneDec()) { + return errorsmod.Wrapf(ErrInvalidMsgSetConsumerCommissionRate, "consumer commission rate should be in the range [0, 1]") } - if err := ccvtypes.ValidatePositiveInt64(msg.HistoricalEntries); err != nil { - return errorsmod.Wrap(ErrInvalidConsumerAdditionProposal, "historical entries cannot be < 1") + return nil +} + +// NewMsgCreateConsumer creates a new MsgCreateConsumer instance +func NewMsgCreateConsumer(submitter string, chainId string, metadata ConsumerMetadata, + initializationParameters *ConsumerInitializationParameters, powerShapingParameters *PowerShapingParameters) (*MsgCreateConsumer, error) { + return &MsgCreateConsumer{ + Submitter: submitter, + ChainId: chainId, + Metadata: metadata, + InitializationParameters: initializationParameters, + PowerShapingParameters: powerShapingParameters, + }, nil +} + +// ValidateBasic implements the sdk.HasValidateBasic interface. +func (msg MsgCreateConsumer) ValidateBasic() error { + if err := ValidateStringField("ChainId", msg.ChainId, cmttypes.MaxChainIDLen); err != nil { + return errorsmod.Wrapf(ErrInvalidMsgCreateConsumer, "ChainId: %s", err.Error()) } - if err := ccvtypes.ValidateDuration(msg.CcvTimeoutPeriod); err != nil { - return errorsmod.Wrap(ErrInvalidConsumerAdditionProposal, "ccv timeout period cannot be zero") + if err := ValidateConsumerMetadata(msg.Metadata); err != nil { + return errorsmod.Wrapf(ErrInvalidMsgCreateConsumer, "Metadata: %s", err.Error()) } - if err := ccvtypes.ValidateDuration(msg.TransferTimeoutPeriod); err != nil { - return errorsmod.Wrap(ErrInvalidConsumerAdditionProposal, "transfer timeout period cannot be zero") + if msg.InitializationParameters != nil { + if err := ValidateInitializationParameters(*msg.InitializationParameters); err != nil { + return errorsmod.Wrapf(ErrInvalidMsgCreateConsumer, "InitializationParameters: %s", err.Error()) + } } - if err := ccvtypes.ValidateDuration(msg.UnbondingPeriod); err != nil { - return errorsmod.Wrap(ErrInvalidConsumerAdditionProposal, "unbonding period cannot be zero") + if msg.PowerShapingParameters != nil { + if msg.PowerShapingParameters.Top_N != 0 { + return fmt.Errorf("cannot create a Top N chain through `MsgCreateConsumer`; " + + "first create the chain and then use `MsgUpdateConsumer` to make the chain Top N") + } + if err := ValidatePowerShapingParameters(*msg.PowerShapingParameters); err != nil { + return errorsmod.Wrapf(ErrInvalidMsgCreateConsumer, "PowerShapingParameters: %s", err.Error()) + } } return nil } -func (msg *MsgConsumerRemoval) ValidateBasic() error { - if strings.TrimSpace(msg.ChainId) == "" { - return errorsmod.Wrap(ErrInvalidConsumerRemovalProp, "consumer chain id must not be blank") +// NewMsgUpdateConsumer creates a new MsgUpdateConsumer instance +func NewMsgUpdateConsumer(owner string, consumerId string, ownerAddress string, metadata *ConsumerMetadata, + initializationParameters *ConsumerInitializationParameters, powerShapingParameters *PowerShapingParameters) (*MsgUpdateConsumer, error) { + return &MsgUpdateConsumer{ + Owner: owner, + ConsumerId: consumerId, + NewOwnerAddress: ownerAddress, + Metadata: metadata, + InitializationParameters: initializationParameters, + PowerShapingParameters: powerShapingParameters, + }, nil +} + +// ValidateBasic implements the sdk.HasValidateBasic interface. +func (msg MsgUpdateConsumer) ValidateBasic() error { + if err := ValidateConsumerId(msg.ConsumerId); err != nil { + return errorsmod.Wrapf(ErrInvalidMsgUpdateConsumer, "ConsumerId: %s", err.Error()) } - if msg.StopTime.IsZero() { - return errorsmod.Wrap(ErrInvalidConsumerRemovalProp, "spawn time cannot be zero") + // Note that NewOwnerAddress is validated when handling the message in UpdateConsumer + + if msg.Metadata != nil { + if err := ValidateConsumerMetadata(*msg.Metadata); err != nil { + return errorsmod.Wrapf(ErrInvalidMsgUpdateConsumer, "Metadata: %s", err.Error()) + } } - return nil -} -// ValidateBasic implements the sdk.Msg interface. -func (msg *MsgConsumerModification) ValidateBasic() error { - if strings.TrimSpace(msg.ChainId) == "" { - return ErrBlankConsumerChainID + if msg.InitializationParameters != nil { + if err := ValidateInitializationParameters(*msg.InitializationParameters); err != nil { + return errorsmod.Wrapf(ErrInvalidMsgUpdateConsumer, "InitializationParameters: %s", err.Error()) + } } - err := ValidatePSSFeatures(msg.Top_N, msg.ValidatorsPowerCap) - if err != nil { - return errorsmod.Wrapf(ErrInvalidConsumerModificationProposal, "invalid PSS features: %s", err.Error()) + if msg.PowerShapingParameters != nil { + if err := ValidatePowerShapingParameters(*msg.PowerShapingParameters); err != nil { + return errorsmod.Wrapf(ErrInvalidMsgUpdateConsumer, "PowerShapingParameters: %s", err.Error()) + } } return nil } -// NewMsgOptIn creates a new NewMsgOptIn instance. -func NewMsgOptIn(chainID string, providerValidatorAddress sdk.ValAddress, consumerConsensusPubKey, signer string) (*MsgOptIn, error) { - return &MsgOptIn{ - ChainId: chainID, - ProviderAddr: providerValidatorAddress.String(), - ConsumerKey: consumerConsensusPubKey, - Signer: signer, +// NewMsgRemoveConsumer creates a new MsgRemoveConsumer instance +func NewMsgRemoveConsumer(owner string, consumerId string) (*MsgRemoveConsumer, error) { + return &MsgRemoveConsumer{ + Owner: owner, + ConsumerId: consumerId, }, nil } -// Type implements the sdk.Msg interface. -func (msg MsgOptIn) Type() string { - return TypeMsgOptIn +// ValidateBasic implements the sdk.HasValidateBasic interface. +func (msg MsgRemoveConsumer) ValidateBasic() error { + if err := ValidateConsumerId(msg.ConsumerId); err != nil { + return err + } + return nil } -// Route implements the sdk.Msg interface. -func (msg MsgOptIn) Route() string { return RouterKey } +// +// Validation methods +// -// GetSigners implements the sdk.Msg interface. It returns the address(es) that -// must sign over msg.GetSignBytes(). -func (msg MsgOptIn) GetSigners() []sdk.AccAddress { - valAddr, err := sdk.ValAddressFromBech32(msg.ProviderAddr) +// ParseConsumerKeyFromJson parses the consumer key from a JSON string, +// this replaces deserializing a protobuf any. +func ParseConsumerKeyFromJson(jsonStr string) (pkType, key string, err error) { + type PubKey struct { + Type string `json:"@type"` + Key string `json:"key"` + } + var pubKey PubKey + err = json.Unmarshal([]byte(jsonStr), &pubKey) if err != nil { - // same behavior as in cosmos-sdk - panic(err) + return "", "", err } - return []sdk.AccAddress{valAddr.Bytes()} + return pubKey.Type, pubKey.Key, nil } -// ValidateBasic implements the sdk.Msg interface. -func (msg MsgOptIn) ValidateBasic() error { - if strings.TrimSpace(msg.ChainId) == "" { - return errorsmod.Wrapf(ErrInvalidConsumerChainID, "chainId cannot be blank") +// ValidateHeaderForConsumerDoubleVoting validates Tendermint light client header +// for consumer double voting evidence. +// +// TODO create unit test +func ValidateHeaderForConsumerDoubleVoting(header *ibctmtypes.Header) error { + if header == nil { + return fmt.Errorf("infraction block header cannot be nil") } - // It is possible to opt in to validate on consumer chains that are not yet approved. - // This can only be done by a signing validator, but it is still sensible - // to limit the chainID size to prevent abuse. - if 128 < len(msg.ChainId) { - return errorsmod.Wrapf(ErrInvalidConsumerChainID, "chainId cannot exceed 128 length") + + if header.SignedHeader == nil { + return fmt.Errorf("signed header in infraction block header cannot be nil") } - valAddr, err := sdk.ValAddressFromBech32(msg.ProviderAddr) - if err != nil { - return ErrInvalidProviderAddress + + if header.SignedHeader.Header == nil { + return fmt.Errorf("invalid signed header in infraction block header, 'SignedHeader.Header' is nil") } - // Check that the provider validator address and the signer address are the same - if sdk.AccAddress(valAddr.Bytes()).String() != msg.Signer { - return errorsmod.Wrapf(ErrInvalidProviderAddress, "provider validator address must be the same as the signer address") + + if header.ValidatorSet == nil { + return fmt.Errorf("invalid infraction block header, validator set is nil") } - if msg.ConsumerKey != "" { - if _, _, err := ParseConsumerKeyFromJson(msg.ConsumerKey); err != nil { - return ErrInvalidConsumerConsensusPubKey - } + + return nil +} + +// ValidateConsumerId validates the provided consumer id and returns an error if it is not valid +func ValidateConsumerId(consumerId string) error { + if strings.TrimSpace(consumerId) == "" { + return errorsmod.Wrapf(ErrInvalidConsumerId, "consumer id cannot be blank") } + + // check that `consumerId` corresponds to a `uint64` + _, err := strconv.ParseUint(consumerId, 10, 64) + if err != nil { + return errorsmod.Wrapf(ErrInvalidConsumerId, "consumer id (%s) cannot be parsed: %s", consumerId, err.Error()) + } + return nil } -// NewMsgOptOut creates a new NewMsgOptIn instance. -func NewMsgOptOut(chainID string, providerValidatorAddress sdk.ValAddress, signer string) (*MsgOptOut, error) { - return &MsgOptOut{ - ChainId: chainID, - ProviderAddr: providerValidatorAddress.String(), - Signer: signer, - }, nil +// ValidateStringField validates that a string `field` satisfies the following properties: +// - is not empty +// - has at most `maxLength` characters +func ValidateStringField(nameOfTheField string, field string, maxLength int) error { + if strings.TrimSpace(field) == "" { + return fmt.Errorf("%s cannot be empty", nameOfTheField) + } else if len(field) > maxLength { + return fmt.Errorf("%s is too long; got: %d, max: %d", nameOfTheField, len(field), maxLength) + } + return nil } -// Type implements the sdk.Msg interface. -func (msg MsgOptOut) Type() string { - return TypeMsgOptOut +// TruncateString truncates a string to maximum length characters +func TruncateString(str string, maxLength int) string { + if maxLength <= 0 { + return "" + } + + truncated := "" + count := 0 + for _, char := range str { + truncated += string(char) + count++ + if count >= maxLength { + break + } + } + return truncated } -// Route implements the sdk.Msg interface. -func (msg MsgOptOut) Route() string { return RouterKey } +// ValidateConsumerMetadata validates that all the provided metadata are in the expected range +func ValidateConsumerMetadata(metadata ConsumerMetadata) error { + if err := ValidateStringField("name", metadata.Name, MaxNameLength); err != nil { + return errorsmod.Wrapf(ErrInvalidConsumerMetadata, "Name: %s", err.Error()) + } -// GetSigners implements the sdk.Msg interface. It returns the address(es) that -// must sign over msg.GetSignBytes(). -func (msg MsgOptOut) GetSigners() []sdk.AccAddress { - valAddr, err := sdk.ValAddressFromBech32(msg.ProviderAddr) - if err != nil { - // same behavior as in cosmos-sdk - panic(err) + if err := ValidateStringField("description", metadata.Description, MaxDescriptionLength); err != nil { + return errorsmod.Wrapf(ErrInvalidConsumerMetadata, "Description: %s", err.Error()) + } + + if err := ValidateStringField("metadata", metadata.Metadata, MaxMetadataLength); err != nil { + return errorsmod.Wrapf(ErrInvalidConsumerMetadata, "Metadata: %s", err.Error()) } - return []sdk.AccAddress{valAddr.Bytes()} + + return nil } -// GetSignBytes returns the message bytes to sign over. -func (msg MsgOptOut) GetSignBytes() []byte { - bz := ccvtypes.ModuleCdc.MustMarshalJSON(&msg) - return sdk.MustSortJSON(bz) +// ValidateConsAddressList validates a list of consensus addresses +func ValidateConsAddressList(list []string, maxLength int) error { + if len(list) > maxLength { + return fmt.Errorf("consensus address list too long; got: %d, max: %d", len(list), maxLength) + } + for _, address := range list { + _, err := sdk.ConsAddressFromBech32(address) + if err != nil { + return fmt.Errorf("invalid address %s: %s", address, err.Error()) + } + } + return nil } -// ValidateBasic implements the sdk.Msg interface. -func (msg MsgOptOut) ValidateBasic() error { - if strings.TrimSpace(msg.ChainId) == "" { - return errorsmod.Wrapf(ErrInvalidConsumerChainID, "chainId cannot be blank") +// ValidatePowerShapingParameters validates that all the provided power-shaping parameters are in the expected range +func ValidatePowerShapingParameters(powerShapingParameters PowerShapingParameters) error { + // Top N corresponds to the top N% of validators that have to validate the consumer chain and can only be 0 (for an + // Opt In chain) or in the range [50, 100] (for a Top N chain). + if powerShapingParameters.Top_N != 0 && (powerShapingParameters.Top_N < 50 || powerShapingParameters.Top_N > 100) { + return errorsmod.Wrap(ErrInvalidPowerShapingParameters, "Top N can either be 0 or in the range [50, 100]") } - // It is possible to assign keys for consumer chains that are not yet approved. - // This can only be done by a signing validator, but it is still sensible - // to limit the chainID size to prevent abuse. - if 128 < len(msg.ChainId) { - return errorsmod.Wrapf(ErrInvalidConsumerChainID, "chainId cannot exceed 128 length") + + if powerShapingParameters.ValidatorsPowerCap > 100 { + return errorsmod.Wrap(ErrInvalidPowerShapingParameters, "ValidatorsPowerCap has to be in the range [0, 100]") } - valAddr, err := sdk.ValAddressFromBech32(msg.ProviderAddr) - if err != nil { - return ErrInvalidProviderAddress + + if err := ValidateConsAddressList(powerShapingParameters.Allowlist, MaxValidatorCount); err != nil { + return errorsmod.Wrapf(ErrInvalidPowerShapingParameters, "Allowlist: %s", err.Error()) } - // Check that the provider validator address and the signer address are the same - if sdk.AccAddress(valAddr.Bytes()).String() != msg.Signer { - return errorsmod.Wrapf(ErrInvalidProviderAddress, "provider validator address must be the same as the signer address") + if err := ValidateConsAddressList(powerShapingParameters.Denylist, MaxValidatorCount); err != nil { + return errorsmod.Wrapf(ErrInvalidPowerShapingParameters, "Denylist: %s", err.Error()) } return nil } -// NewMsgSetConsumerCommissionRate creates a new MsgSetConsumerCommissionRate msg instance. -func NewMsgSetConsumerCommissionRate(chainID string, commission math.LegacyDec, providerValidatorAddress sdk.ValAddress, signer string) *MsgSetConsumerCommissionRate { - return &MsgSetConsumerCommissionRate{ - ChainId: chainID, - Rate: commission, - ProviderAddr: providerValidatorAddress.String(), - Signer: signer, +// ValidateInitializationParameters validates that all the provided parameters are in the expected range +func ValidateInitializationParameters(initializationParameters ConsumerInitializationParameters) error { + if initializationParameters.InitialHeight.IsZero() { + return errorsmod.Wrap(ErrInvalidConsumerInitializationParameters, "InitialHeight cannot be zero") } -} -func (msg MsgSetConsumerCommissionRate) Route() string { - return RouterKey -} - -func (msg MsgSetConsumerCommissionRate) Type() string { - return TypeMsgSetConsumerCommissionRate -} + if err := ValidateByteSlice(initializationParameters.GenesisHash, MaxHashLength); err != nil { + return errorsmod.Wrapf(ErrInvalidConsumerInitializationParameters, "GenesisHash: %s", err.Error()) + } -func (msg MsgSetConsumerCommissionRate) ValidateBasic() error { - if strings.TrimSpace(msg.ChainId) == "" { - return errorsmod.Wrapf(ErrInvalidConsumerChainID, "chainId cannot be blank") + if err := ValidateByteSlice(initializationParameters.BinaryHash, MaxHashLength); err != nil { + return errorsmod.Wrapf(ErrInvalidConsumerInitializationParameters, "BinaryHash: %s", err.Error()) } - if 128 < len(msg.ChainId) { - return errorsmod.Wrapf(ErrInvalidConsumerChainID, "chainId cannot exceed 128 length") + + if err := ccvtypes.ValidateStringFraction(initializationParameters.ConsumerRedistributionFraction); err != nil { + return errorsmod.Wrapf(ErrInvalidConsumerInitializationParameters, "ConsumerRedistributionFraction: %s", err.Error()) } - valAddr, err := sdk.ValAddressFromBech32(msg.ProviderAddr) - if err != nil { - return ErrInvalidProviderAddress + + if err := ccvtypes.ValidatePositiveInt64(initializationParameters.BlocksPerDistributionTransmission); err != nil { + return errorsmod.Wrapf(ErrInvalidConsumerInitializationParameters, "BlocksPerDistributionTransmission: %s", err.Error()) } - // Check that the provider validator address and the signer address are the same - if sdk.AccAddress(valAddr.Bytes()).String() != msg.Signer { - return errorsmod.Wrapf(ErrInvalidProviderAddress, "provider validator address must be the same as the signer address") + + if err := ccvtypes.ValidateDistributionTransmissionChannel(initializationParameters.DistributionTransmissionChannel); err != nil { + return errorsmod.Wrapf(ErrInvalidConsumerInitializationParameters, "DistributionTransmissionChannel: %s", err.Error()) } - if msg.Rate.IsNegative() || msg.Rate.GT(math.LegacyOneDec()) { - return errorsmod.Wrapf(ErrInvalidConsumerCommissionRate, "consumer commission rate should be in the range [0, 1]") + + if err := ccvtypes.ValidatePositiveInt64(initializationParameters.HistoricalEntries); err != nil { + return errorsmod.Wrapf(ErrInvalidConsumerInitializationParameters, "HistoricalEntries: %s", err.Error()) } - return nil -} + if err := ccvtypes.ValidateDuration(initializationParameters.CcvTimeoutPeriod); err != nil { + return errorsmod.Wrapf(ErrInvalidConsumerInitializationParameters, "CcvTimeoutPeriod: %s", err.Error()) + } -func (msg *MsgChangeRewardDenoms) ValidateBasic() error { - emptyDenomsToAdd := len(msg.DenomsToAdd) == 0 - emptyDenomsToRemove := len(msg.DenomsToRemove) == 0 - // Return error if both sets are empty or nil - if emptyDenomsToAdd && emptyDenomsToRemove { - return fmt.Errorf( - "invalid change reward denoms proposal: both denoms to add and denoms to remove are empty") + if err := ccvtypes.ValidateDuration(initializationParameters.TransferTimeoutPeriod); err != nil { + return errorsmod.Wrapf(ErrInvalidConsumerInitializationParameters, "TransferTimeoutPeriod: %s", err.Error()) } - // Return error if a denom is in both sets - for _, denomToAdd := range msg.DenomsToAdd { - for _, denomToRemove := range msg.DenomsToRemove { - if denomToAdd == denomToRemove { - return fmt.Errorf( - "invalid change reward denoms proposal: %s cannot be both added and removed", denomToAdd) - } - } + if err := ccvtypes.ValidateDuration(initializationParameters.UnbondingPeriod); err != nil { + return errorsmod.Wrapf(ErrInvalidConsumerInitializationParameters, "UnbondingPeriod: %s", err.Error()) } - // Return error if any denom is "invalid" - for _, denom := range msg.DenomsToAdd { - if !sdk.NewCoin(denom, math.NewInt(1)).IsValid() { - return fmt.Errorf("invalid change reward denoms proposal: %s is not a valid denom", denom) - } + return nil +} + +func ValidateByteSlice(hash []byte, maxLength int) error { + if len(hash) > maxLength { + return fmt.Errorf("hash is too long; got: %d, max: %d", len(hash), MaxHashLength) } - for _, denom := range msg.DenomsToRemove { - if !sdk.NewCoin(denom, math.NewInt(1)).IsValid() { - return fmt.Errorf("invalid change reward denoms proposal: %s is not a valid denom", denom) - } + return nil +} + +func validateDeprecatedChainId(chainId string) error { + if strings.TrimSpace(chainId) != "" { + return fmt.Errorf("found non-empty chainId(%s); chainId is deprecated, use consumerId instead", chainId) } return nil } -func (msg MsgSetConsumerCommissionRate) GetSigners() []sdk.AccAddress { - valAddr, err := sdk.ValAddressFromBech32(msg.ProviderAddr) +// validateProviderAddress validates that the address is a sdk.ValAddress in Bech32 string format +func validateProviderAddress(addr, signer string) error { + valAddr, err := sdk.ValAddressFromBech32(addr) if err != nil { - // same behavior as in cosmos-sdk - panic(err) + return fmt.Errorf("invalid ValAddress (%s)", addr) + } + + // Check that the provider validator address and the signer address are the same + accAddr := sdk.AccAddress(valAddr.Bytes()).String() + if accAddr != signer { + return fmt.Errorf("ValAddress converted to AccAddress (%s) must match the signer address (%s)", accAddr, signer) } - return []sdk.AccAddress{valAddr.Bytes()} -} -func (msg MsgSetConsumerCommissionRate) GetSignBytes() []byte { - bz := ccvtypes.ModuleCdc.MustMarshalJSON(&msg) - return sdk.MustSortJSON(bz) + return nil } diff --git a/x/ccv/provider/types/msg_test.go b/x/ccv/provider/types/msg_test.go index 4ef2a7efc8..c05a628ac4 100644 --- a/x/ccv/provider/types/msg_test.go +++ b/x/ccv/provider/types/msg_test.go @@ -2,13 +2,443 @@ package types_test import ( "testing" + "time" sdk "github.com/cosmos/cosmos-sdk/types" + clienttypes "github.com/cosmos/ibc-go/v8/modules/core/02-client/types" cryptoutil "github.com/cosmos/interchain-security/v5/testutil/crypto" "github.com/cosmos/interchain-security/v5/x/ccv/provider/types" "github.com/stretchr/testify/require" ) +func TestValidateConsumerId(t *testing.T) { + // empty consumer id + require.Error(t, types.ValidateConsumerId("")) + + // not a `uint64` where `uint64` is in the range [0, 2^64) + require.Error(t, types.ValidateConsumerId("a")) + require.Error(t, types.ValidateConsumerId("-2545")) + require.Error(t, types.ValidateConsumerId("18446744073709551616")) // 2^64 + + // valid consumer id + require.NoError(t, types.ValidateConsumerId("0")) + require.NoError(t, types.ValidateConsumerId("18446744073709551615")) // 2^64 - 1 +} + +func TestValidateStringField(t *testing.T) { + testCases := []struct { + name string + field string + maxLength int + valid bool + }{ + { + name: "invalid: empty", + field: "", + maxLength: 5, + valid: false, + }, + { + name: "invalid: too long", + field: "this field is too long", + maxLength: 5, + valid: false, + }, + { + name: "valid", + field: "valid", + maxLength: 5, + valid: true, + }, + } + + for _, tc := range testCases { + err := types.ValidateStringField(tc.name, tc.field, tc.maxLength) + if tc.valid { + require.NoError(t, err, tc.name) + } else { + require.Error(t, err, tc.name) + } + } +} + +func TestTruncateString(t *testing.T) { + testCases := []struct { + str string + maxLength int + expStr string + }{ + {"drink", 3, "dri"}, + {"drink", 6, "drink"}, + {"drink", 0, ""}, + {"drink", -1, ""}, + {"drink", 100, "drink"}, + {"pub", 100, "pub"}, + {"こんにちは", 3, "こんに"}, + } + + for _, tc := range testCases { + truncated := types.TruncateString(tc.str, tc.maxLength) + require.Equal(t, tc.expStr, truncated) + } +} + +func TestValidateInitializationParameters(t *testing.T) { + now := time.Now().UTC() + coolStr := "Cosmos Hub is the best place to launch a chain. Interchain Security is awesome." + tooLongHash := []byte(coolStr) + + testCases := []struct { + name string + params types.ConsumerInitializationParameters + valid bool + }{ + { + name: "valid", + params: types.ConsumerInitializationParameters{ + InitialHeight: clienttypes.NewHeight(3, 4), + GenesisHash: []byte{0x01}, + BinaryHash: []byte{0x01}, + SpawnTime: now, + UnbondingPeriod: time.Duration(100000000000), + CcvTimeoutPeriod: time.Duration(100000000000), + TransferTimeoutPeriod: time.Duration(100000000000), + ConsumerRedistributionFraction: "0.75", + BlocksPerDistributionTransmission: 10, + HistoricalEntries: 10000, + DistributionTransmissionChannel: "", + }, + valid: true, + }, + { + name: "invalid - zero height", + params: types.ConsumerInitializationParameters{ + InitialHeight: clienttypes.ZeroHeight(), + GenesisHash: []byte{0x01}, + BinaryHash: []byte{0x01}, + SpawnTime: now, + UnbondingPeriod: time.Duration(100000000000), + CcvTimeoutPeriod: time.Duration(100000000000), + TransferTimeoutPeriod: time.Duration(100000000000), + ConsumerRedistributionFraction: "0.75", + BlocksPerDistributionTransmission: 10, + HistoricalEntries: 10000, + DistributionTransmissionChannel: "", + }, + valid: false, + }, + { + name: "invalid - hash too long", + params: types.ConsumerInitializationParameters{ + InitialHeight: clienttypes.NewHeight(3, 4), + GenesisHash: tooLongHash, + BinaryHash: []byte{0x01}, + SpawnTime: now, + UnbondingPeriod: time.Duration(100000000000), + CcvTimeoutPeriod: time.Duration(100000000000), + TransferTimeoutPeriod: time.Duration(100000000000), + ConsumerRedistributionFraction: "0.75", + BlocksPerDistributionTransmission: 10, + HistoricalEntries: 10000, + DistributionTransmissionChannel: "", + }, + valid: false, + }, + { + name: "invalid - zero spawn time", + params: types.ConsumerInitializationParameters{ + InitialHeight: clienttypes.NewHeight(3, 4), + GenesisHash: []byte{0x01}, + BinaryHash: []byte{0x01}, + SpawnTime: time.Time{}, + UnbondingPeriod: time.Duration(100000000000), + CcvTimeoutPeriod: time.Duration(100000000000), + TransferTimeoutPeriod: time.Duration(100000000000), + ConsumerRedistributionFraction: "0.75", + BlocksPerDistributionTransmission: 10, + HistoricalEntries: 10000, + DistributionTransmissionChannel: "", + }, + valid: true, + }, + { + name: "invalid - zero duration", + params: types.ConsumerInitializationParameters{ + InitialHeight: clienttypes.NewHeight(3, 4), + GenesisHash: []byte{0x01}, + BinaryHash: []byte{0x01}, + SpawnTime: now, + UnbondingPeriod: 0, + CcvTimeoutPeriod: time.Duration(100000000000), + TransferTimeoutPeriod: time.Duration(100000000000), + ConsumerRedistributionFraction: "0.75", + BlocksPerDistributionTransmission: 10, + HistoricalEntries: 10000, + DistributionTransmissionChannel: "", + }, + valid: false, + }, + { + name: "invalid -- ConsumerRedistributionFraction > 1", + params: types.ConsumerInitializationParameters{ + InitialHeight: clienttypes.NewHeight(3, 4), + GenesisHash: []byte{0x01}, + BinaryHash: []byte{0x01}, + SpawnTime: now, + UnbondingPeriod: time.Duration(100000000000), + CcvTimeoutPeriod: time.Duration(100000000000), + TransferTimeoutPeriod: time.Duration(100000000000), + ConsumerRedistributionFraction: "1.75", + BlocksPerDistributionTransmission: 10, + HistoricalEntries: 10000, + DistributionTransmissionChannel: "", + }, + valid: false, + }, + { + name: "invalid -- ConsumerRedistributionFraction wrong format", + params: types.ConsumerInitializationParameters{ + InitialHeight: clienttypes.NewHeight(3, 4), + GenesisHash: []byte{0x01}, + BinaryHash: []byte{0x01}, + SpawnTime: now, + UnbondingPeriod: time.Duration(100000000000), + CcvTimeoutPeriod: time.Duration(100000000000), + TransferTimeoutPeriod: time.Duration(100000000000), + ConsumerRedistributionFraction: coolStr, + BlocksPerDistributionTransmission: 10, + HistoricalEntries: 10000, + DistributionTransmissionChannel: "", + }, + valid: false, + }, + { + name: "invalid - BlocksPerDistributionTransmission zero", + params: types.ConsumerInitializationParameters{ + InitialHeight: clienttypes.NewHeight(3, 4), + GenesisHash: []byte{0x01}, + BinaryHash: []byte{0x01}, + SpawnTime: now, + UnbondingPeriod: time.Duration(100000000000), + CcvTimeoutPeriod: time.Duration(100000000000), + TransferTimeoutPeriod: time.Duration(100000000000), + ConsumerRedistributionFraction: "0.75", + BlocksPerDistributionTransmission: 0, + HistoricalEntries: 10000, + DistributionTransmissionChannel: "", + }, + valid: false, + }, + { + name: "invalid - HistoricalEntries zero", + params: types.ConsumerInitializationParameters{ + InitialHeight: clienttypes.NewHeight(3, 4), + GenesisHash: []byte{0x01}, + BinaryHash: []byte{0x01}, + SpawnTime: now, + UnbondingPeriod: time.Duration(100000000000), + CcvTimeoutPeriod: time.Duration(100000000000), + TransferTimeoutPeriod: time.Duration(100000000000), + ConsumerRedistributionFraction: "0.75", + BlocksPerDistributionTransmission: 10, + HistoricalEntries: 0, + DistributionTransmissionChannel: "", + }, + valid: false, + }, + { + name: "invalid - DistributionTransmissionChannel too long", + params: types.ConsumerInitializationParameters{ + InitialHeight: clienttypes.NewHeight(3, 4), + GenesisHash: []byte{0x01}, + BinaryHash: []byte{0x01}, + SpawnTime: now, + UnbondingPeriod: time.Duration(100000000000), + CcvTimeoutPeriod: time.Duration(100000000000), + TransferTimeoutPeriod: time.Duration(100000000000), + ConsumerRedistributionFraction: "0.75", + BlocksPerDistributionTransmission: 10, + HistoricalEntries: 10000, + DistributionTransmissionChannel: coolStr, + }, + valid: false, + }, + } + + for _, tc := range testCases { + err := types.ValidateInitializationParameters(tc.params) + if tc.valid { + require.NoError(t, err, tc.name) + } else { + require.Error(t, err, tc.name) + } + } +} + +func TestValidateConsAddressList(t *testing.T) { + consAddr1 := "cosmosvalcons1qmq08eruchr5sf5s3rwz7djpr5a25f7xw4mceq" + consAddr2 := "cosmosvalcons1nx7n5uh0ztxsynn4sje6eyq2ud6rc6klc96w39" + invalidConsAddr := "cosmosvalcons1nx7n5uh0ztxsynn4sje6ey" + + testCases := []struct { + name string + list []string + maxLength int + valid bool + }{ + { + name: "valid - empty list", + list: []string{}, + maxLength: 10, + valid: true, + }, + { + name: "valid - non-empty list", + list: []string{consAddr1, consAddr2}, + maxLength: 10, + valid: true, + }, + { + name: "invalid - address with wrong format", + list: []string{invalidConsAddr}, + maxLength: 10, + valid: false, + }, + { + name: "invalid - empty address", + list: []string{""}, + maxLength: 10, + valid: false, + }, + { + name: "invalid - list length", + list: []string{consAddr1, consAddr2}, + maxLength: 1, + valid: false, + }, + } + + for _, tc := range testCases { + err := types.ValidateConsAddressList(tc.list, tc.maxLength) + if tc.valid { + require.NoError(t, err, tc.name) + } else { + require.Error(t, err, tc.name) + } + } +} + +func TestValidateByteSlice(t *testing.T) { + testCases := []struct { + name string + slice []byte + maxLength int + valid bool + }{ + { + name: "valid: empty", + slice: []byte{}, + maxLength: 5, + valid: true, + }, + { + name: "invalid: too long", + slice: []byte{0x01, 0x02}, + maxLength: 1, + valid: false, + }, + { + name: "valid", + slice: []byte{0x01, 0x02}, + maxLength: 5, + valid: true, + }, + } + + for _, tc := range testCases { + err := types.ValidateByteSlice(tc.slice, tc.maxLength) + if tc.valid { + require.NoError(t, err, tc.name) + } else { + require.Error(t, err, tc.name) + } + } +} + +func TestMsgUpdateConsumerValidateBasic(t *testing.T) { + consAddr1 := "cosmosvalcons1qmq08eruchr5sf5s3rwz7djpr5a25f7xw4mceq" + consAddr2 := "cosmosvalcons1nx7n5uh0ztxsynn4sje6eyq2ud6rc6klc96w39" + consAddr3 := "cosmosvalcons1muys5jyqk4xd27e208nym85kn0t4zjcfeu63fe" + + testCases := []struct { + name string + powerShapingParameters types.PowerShapingParameters + expPass bool + }{ + { + "success", + types.PowerShapingParameters{ + Top_N: 50, + ValidatorsPowerCap: 100, + ValidatorSetCap: 34, + Allowlist: []string{consAddr1}, + Denylist: nil, + MinStake: 0, + AllowInactiveVals: false, + }, + true, + }, + { + "top N is invalid", + types.PowerShapingParameters{ + Top_N: 10, + ValidatorsPowerCap: 0, + ValidatorSetCap: 0, + Allowlist: nil, + Denylist: nil, + }, + false, + }, + { + "validators power cap is invalid", + types.PowerShapingParameters{ + Top_N: 50, + ValidatorsPowerCap: 101, + ValidatorSetCap: 0, + Allowlist: nil, + Denylist: nil, + MinStake: 0, + AllowInactiveVals: false, + }, + false, + }, + { + "valid proposal", + types.PowerShapingParameters{ + Top_N: 54, + ValidatorsPowerCap: 92, + ValidatorSetCap: 0, + Allowlist: []string{consAddr1}, + Denylist: []string{consAddr2, consAddr3}, + MinStake: 0, + AllowInactiveVals: false, + }, + true, + }, + } + + for _, tc := range testCases { + // TODO (PERMISSIONLESS) add more tests + msg, _ := types.NewMsgUpdateConsumer("", "0", "cosmos1p3ucd3ptpw902fluyjzhq3ffgq4ntddac9sa3s", nil, nil, &tc.powerShapingParameters) + err := msg.ValidateBasic() + if tc.expPass { + require.NoError(t, err, "valid case: %s should not return error. got %w", tc.name, err) + } else { + require.Error(t, err, "invalid case: '%s' must return error but got none", tc.name) + } + } +} + func TestMsgAssignConsumerKeyValidateBasic(t *testing.T) { cId1 := cryptoutil.NewCryptoIdentityFromIntSeed(35443543534) cId2 := cryptoutil.NewCryptoIdentityFromIntSeed(65465464564) @@ -26,44 +456,57 @@ func TestMsgAssignConsumerKeyValidateBasic(t *testing.T) { name string chainId string providerAddr string - signer string + submitter string consumerKey string + consumerId string expErr bool }{ { - name: "chain Id empty", - expErr: true, + name: "invalid: chainId non-empty", + chainId: "chainId", + expErr: true, }, { - name: "chain Id too long", - chainId: longChainId, - expErr: true, + name: "invalid: consumerId empty", + consumerId: "", + expErr: true, }, { - name: "invalid provider address", - chainId: "chainId", - expErr: true, + name: "invalid: consumerId is not a number", + consumerId: "consumerId", + expErr: true, + }, + { + name: "invalid: provider address is empty", + consumerId: "1", + expErr: true, + }, + { + name: "invalid: provider address is invalid", + consumerId: "1", + providerAddr: "some address", + expErr: true, }, { - name: "invalid signer address: must be the same as the provider address", - chainId: "chainId", + name: "invalid: provider address != submitter address", + consumerId: "1", providerAddr: valOpAddr1.String(), - signer: acc2, + submitter: acc2, expErr: true, }, { - name: "invalid consumer pubkey", - chainId: "chainId", + name: "invalid: consumer pubkey empty", + consumerId: "1", providerAddr: valOpAddr1.String(), - signer: acc1, + submitter: acc1, expErr: true, }, { - name: "valid assign consumer key msg", - chainId: "chainId", + name: "valid", + consumerId: "1", providerAddr: valOpAddr1.String(), + submitter: acc1, consumerKey: "{\"@type\": \"/cosmos.crypto.ed25519.PubKey\", \"key\": \"e3BehnEIlGUAnJYn9V8gBXuMh4tXO8xxlxyXD1APGyk=\"}", - signer: acc1, expErr: false, }, } @@ -75,14 +518,15 @@ func TestMsgAssignConsumerKeyValidateBasic(t *testing.T) { ChainId: tc.chainId, ConsumerKey: tc.consumerKey, ProviderAddr: tc.providerAddr, - Signer: tc.signer, + Submitter: tc.submitter, + ConsumerId: tc.consumerId, } err := msg.ValidateBasic() if tc.expErr { - require.Error(t, err) + require.Error(t, err, tc.name) } else { - require.NoError(t, err) + require.NoError(t, err, tc.name) } }) } diff --git a/x/ccv/provider/types/provider.pb.go b/x/ccv/provider/types/provider.pb.go index 7c30781221..77d0dc6d98 100644 --- a/x/ccv/provider/types/provider.pb.go +++ b/x/ccv/provider/types/provider.pb.go @@ -37,6 +37,54 @@ var _ = time.Kitchen // proto package needs to be updated. const _ = proto.GoGoProtoPackageIsVersion3 // please upgrade the proto package +// ConsumerPhase indicates the phases of a consumer chain according to ADR 019 +type ConsumerPhase int32 + +const ( + // UNSPECIFIED defines an empty phase. + CONSUMER_PHASE_UNSPECIFIED ConsumerPhase = 0 + // REGISTERED defines the phase in which a consumer chain has been assigned a unique consumer id. + // A chain in this phase cannot yet launch. + CONSUMER_PHASE_REGISTERED ConsumerPhase = 1 + // INITIALIZED defines the phase in which a consumer chain has set all the needed parameters to launch but + // has not yet launched (e.g., because the `spawnTime` of the consumer chain has not yet been reached). + CONSUMER_PHASE_INITIALIZED ConsumerPhase = 2 + // LAUNCHED defines the phase in which a consumer chain is running and consuming a subset of the validator + // set of the provider. + CONSUMER_PHASE_LAUNCHED ConsumerPhase = 3 + // STOPPED defines the phase in which a previously-launched chain has stopped. + CONSUMER_PHASE_STOPPED ConsumerPhase = 4 + // DELETED defines the phase in which the state of a stopped chain has been deleted. + CONSUMER_PHASE_DELETED ConsumerPhase = 5 +) + +var ConsumerPhase_name = map[int32]string{ + 0: "CONSUMER_PHASE_UNSPECIFIED", + 1: "CONSUMER_PHASE_REGISTERED", + 2: "CONSUMER_PHASE_INITIALIZED", + 3: "CONSUMER_PHASE_LAUNCHED", + 4: "CONSUMER_PHASE_STOPPED", + 5: "CONSUMER_PHASE_DELETED", +} + +var ConsumerPhase_value = map[string]int32{ + "CONSUMER_PHASE_UNSPECIFIED": 0, + "CONSUMER_PHASE_REGISTERED": 1, + "CONSUMER_PHASE_INITIALIZED": 2, + "CONSUMER_PHASE_LAUNCHED": 3, + "CONSUMER_PHASE_STOPPED": 4, + "CONSUMER_PHASE_DELETED": 5, +} + +func (x ConsumerPhase) String() string { + return proto.EnumName(ConsumerPhase_name, int32(x)) +} + +func (ConsumerPhase) EnumDescriptor() ([]byte, []int) { + return fileDescriptor_f22ec409a72b7b72, []int{0} +} + +// WARNING: This message is deprecated in favor of `MsgCreateConsumer`. // ConsumerAdditionProposal is a governance proposal on the provider chain to // spawn a new consumer chain. If it passes, then all validators on the provider // chain are expected to validate the consumer chain at spawn time or get @@ -151,6 +199,7 @@ func (m *ConsumerAdditionProposal) XXX_DiscardUnknown() { var xxx_messageInfo_ConsumerAdditionProposal proto.InternalMessageInfo +// WARNING: This message is deprecated in favor of `MsgRemoveConsumer`. // ConsumerRemovalProposal is a governance proposal on the provider chain to // remove (and stop) a consumer chain. If it passes, all the consumer chain's // state is removed from the provider chain. The outstanding unbonding operation @@ -229,6 +278,7 @@ func (m *ConsumerRemovalProposal) GetStopTime() time.Time { return time.Time{} } +// WARNING: This message is deprecated in favor of `MsgUpdateConsumer`. // ConsumerModificationProposal is a governance proposal on the provider chain to modify parameters of a running // consumer chain. If it passes, the consumer chain's state is updated to take into account the newest params. type ConsumerModificationProposal struct { @@ -899,6 +949,7 @@ func (m *AddressList) GetAddresses() [][]byte { return nil } +// WARNING: This message is deprecated and is not used. // ChannelToChain is used to map a CCV channel ID to the consumer chainID type ChannelToChain struct { ChannelId string `protobuf:"bytes,1,opt,name=channel_id,json=channelId,proto3" json:"channel_id,omitempty"` @@ -1372,279 +1423,677 @@ func (m *ConsumerRewardsAllocation) GetRewards() github_com_cosmos_cosmos_sdk_ty return nil } -func init() { - proto.RegisterType((*ConsumerAdditionProposal)(nil), "interchain_security.ccv.provider.v1.ConsumerAdditionProposal") - proto.RegisterType((*ConsumerRemovalProposal)(nil), "interchain_security.ccv.provider.v1.ConsumerRemovalProposal") - proto.RegisterType((*ConsumerModificationProposal)(nil), "interchain_security.ccv.provider.v1.ConsumerModificationProposal") - proto.RegisterType((*EquivocationProposal)(nil), "interchain_security.ccv.provider.v1.EquivocationProposal") - proto.RegisterType((*ChangeRewardDenomsProposal)(nil), "interchain_security.ccv.provider.v1.ChangeRewardDenomsProposal") - proto.RegisterType((*GlobalSlashEntry)(nil), "interchain_security.ccv.provider.v1.GlobalSlashEntry") - proto.RegisterType((*Params)(nil), "interchain_security.ccv.provider.v1.Params") - proto.RegisterType((*SlashAcks)(nil), "interchain_security.ccv.provider.v1.SlashAcks") - proto.RegisterType((*ConsumerAdditionProposals)(nil), "interchain_security.ccv.provider.v1.ConsumerAdditionProposals") - proto.RegisterType((*ConsumerRemovalProposals)(nil), "interchain_security.ccv.provider.v1.ConsumerRemovalProposals") - proto.RegisterType((*AddressList)(nil), "interchain_security.ccv.provider.v1.AddressList") - proto.RegisterType((*ChannelToChain)(nil), "interchain_security.ccv.provider.v1.ChannelToChain") - proto.RegisterType((*ValidatorSetChangePackets)(nil), "interchain_security.ccv.provider.v1.ValidatorSetChangePackets") - proto.RegisterType((*KeyAssignmentReplacement)(nil), "interchain_security.ccv.provider.v1.KeyAssignmentReplacement") - proto.RegisterType((*ValidatorConsumerPubKey)(nil), "interchain_security.ccv.provider.v1.ValidatorConsumerPubKey") - proto.RegisterType((*ValidatorByConsumerAddr)(nil), "interchain_security.ccv.provider.v1.ValidatorByConsumerAddr") - proto.RegisterType((*ConsumerAddrsToPruneV2)(nil), "interchain_security.ccv.provider.v1.ConsumerAddrsToPruneV2") - proto.RegisterType((*ConsensusValidator)(nil), "interchain_security.ccv.provider.v1.ConsensusValidator") - proto.RegisterType((*ConsumerRewardsAllocation)(nil), "interchain_security.ccv.provider.v1.ConsumerRewardsAllocation") +// ConsumerMetadata contains general information about the registered chain +type ConsumerMetadata struct { + // the name of the chain + Name string `protobuf:"bytes,1,opt,name=name,proto3" json:"name,omitempty"` + // the description of the chain + Description string `protobuf:"bytes,2,opt,name=description,proto3" json:"description,omitempty"` + // the metadata (e.g., GitHub repository URL) of the chain + Metadata string `protobuf:"bytes,3,opt,name=metadata,proto3" json:"metadata,omitempty"` } -func init() { - proto.RegisterFile("interchain_security/ccv/provider/v1/provider.proto", fileDescriptor_f22ec409a72b7b72) +func (m *ConsumerMetadata) Reset() { *m = ConsumerMetadata{} } +func (m *ConsumerMetadata) String() string { return proto.CompactTextString(m) } +func (*ConsumerMetadata) ProtoMessage() {} +func (*ConsumerMetadata) Descriptor() ([]byte, []int) { + return fileDescriptor_f22ec409a72b7b72, []int{19} +} +func (m *ConsumerMetadata) XXX_Unmarshal(b []byte) error { + return m.Unmarshal(b) +} +func (m *ConsumerMetadata) XXX_Marshal(b []byte, deterministic bool) ([]byte, error) { + if deterministic { + return xxx_messageInfo_ConsumerMetadata.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 *ConsumerMetadata) XXX_Merge(src proto.Message) { + xxx_messageInfo_ConsumerMetadata.Merge(m, src) +} +func (m *ConsumerMetadata) XXX_Size() int { + return m.Size() +} +func (m *ConsumerMetadata) XXX_DiscardUnknown() { + xxx_messageInfo_ConsumerMetadata.DiscardUnknown(m) } -var fileDescriptor_f22ec409a72b7b72 = []byte{ - // 1946 bytes of a gzipped FileDescriptorProto - 0x1f, 0x8b, 0x08, 0x00, 0x00, 0x00, 0x00, 0x00, 0x02, 0xff, 0xb4, 0x58, 0xcd, 0x6f, 0x1b, 0xc7, - 0x15, 0xd7, 0x8a, 0x94, 0x44, 0x0e, 0xf5, 0x39, 0x52, 0xec, 0x95, 0xa2, 0x92, 0x34, 0x53, 0x1b, - 0x6c, 0x5c, 0x2f, 0x23, 0x05, 0x05, 0x0c, 0xb7, 0x81, 0x21, 0x51, 0x4e, 0x6c, 0xa9, 0x71, 0xd8, - 0x15, 0xa1, 0x00, 0xe9, 0x61, 0x31, 0x9c, 0x1d, 0x91, 0x53, 0xed, 0xee, 0xac, 0x67, 0x86, 0x2b, - 0xf3, 0xd2, 0x73, 0x2f, 0x05, 0xd2, 0x5b, 0xd0, 0x4b, 0x73, 0x2c, 0x7a, 0xea, 0xa1, 0xe8, 0x1f, - 0xd0, 0x53, 0x50, 0xa0, 0x68, 0x8e, 0x3d, 0x25, 0x85, 0x7d, 0xe8, 0xa1, 0x40, 0xaf, 0xbd, 0x16, - 0x33, 0xfb, 0xc1, 0xa5, 0x3e, 0x1c, 0x1a, 0x69, 0x2e, 0xd2, 0xee, 0x7b, 0xbf, 0xf7, 0x9b, 0x37, - 0x33, 0xef, 0x8b, 0x0b, 0x76, 0x69, 0x20, 0x09, 0xc7, 0x03, 0x44, 0x03, 0x47, 0x10, 0x3c, 0xe4, - 0x54, 0x8e, 0x5a, 0x18, 0x47, 0xad, 0x90, 0xb3, 0x88, 0xba, 0x84, 0xb7, 0xa2, 0x9d, 0xec, 0xd9, - 0x0a, 0x39, 0x93, 0x0c, 0xbe, 0x75, 0x85, 0x8d, 0x85, 0x71, 0x64, 0x65, 0xb8, 0x68, 0x67, 0xeb, - 0xf6, 0x75, 0xc4, 0xd1, 0x4e, 0xeb, 0x9c, 0x72, 0x12, 0x73, 0x6d, 0x6d, 0xf4, 0x59, 0x9f, 0xe9, - 0xc7, 0x96, 0x7a, 0x4a, 0xa4, 0xb5, 0x3e, 0x63, 0x7d, 0x8f, 0xb4, 0xf4, 0x5b, 0x6f, 0x78, 0xda, - 0x92, 0xd4, 0x27, 0x42, 0x22, 0x3f, 0x4c, 0x00, 0xd5, 0x8b, 0x00, 0x77, 0xc8, 0x91, 0xa4, 0x2c, - 0x48, 0x09, 0x68, 0x0f, 0xb7, 0x30, 0xe3, 0xa4, 0x85, 0x3d, 0x4a, 0x02, 0xa9, 0x56, 0x8d, 0x9f, - 0x12, 0x40, 0x4b, 0x01, 0x3c, 0xda, 0x1f, 0xc8, 0x58, 0x2c, 0x5a, 0x92, 0x04, 0x2e, 0xe1, 0x3e, - 0x8d, 0xc1, 0xe3, 0xb7, 0xc4, 0x60, 0x3b, 0xa7, 0xc7, 0x7c, 0x14, 0x4a, 0xd6, 0x3a, 0x23, 0x23, - 0x91, 0x68, 0xef, 0x60, 0x26, 0x7c, 0x26, 0x5a, 0x44, 0xed, 0x3f, 0xc0, 0xa4, 0x15, 0xed, 0xf4, - 0x88, 0x44, 0x3b, 0x99, 0x20, 0xf5, 0x3b, 0xc1, 0xf5, 0x90, 0x18, 0x63, 0x30, 0xa3, 0xa9, 0xdf, - 0x9b, 0xb1, 0xde, 0x89, 0x4f, 0x24, 0x7e, 0x49, 0x54, 0x6b, 0xc8, 0xa7, 0x01, 0x6b, 0xe9, 0xbf, - 0xb1, 0xa8, 0xf1, 0xdf, 0x12, 0x30, 0xdb, 0x2c, 0x10, 0x43, 0x9f, 0xf0, 0x3d, 0xd7, 0xa5, 0xea, - 0x00, 0x3a, 0x9c, 0x85, 0x4c, 0x20, 0x0f, 0x6e, 0x80, 0x39, 0x49, 0xa5, 0x47, 0x4c, 0xa3, 0x6e, - 0x34, 0xcb, 0x76, 0xfc, 0x02, 0xeb, 0xa0, 0xe2, 0x12, 0x81, 0x39, 0x0d, 0x15, 0xd8, 0x9c, 0xd5, - 0xba, 0xbc, 0x08, 0x6e, 0x82, 0x52, 0x7c, 0x6b, 0xd4, 0x35, 0x0b, 0x5a, 0xbd, 0xa0, 0xdf, 0x9f, - 0xb8, 0xf0, 0x03, 0xb0, 0x4c, 0x03, 0x2a, 0x29, 0xf2, 0x9c, 0x01, 0x51, 0x67, 0x67, 0x16, 0xeb, - 0x46, 0xb3, 0xb2, 0xbb, 0x65, 0xd1, 0x1e, 0xb6, 0xd4, 0x71, 0x5b, 0xc9, 0x21, 0x47, 0x3b, 0xd6, - 0x63, 0x8d, 0xd8, 0x2f, 0x7e, 0xf1, 0x55, 0x6d, 0xc6, 0x5e, 0x4a, 0xec, 0x62, 0x21, 0xbc, 0x05, - 0x16, 0xfb, 0x24, 0x20, 0x82, 0x0a, 0x67, 0x80, 0xc4, 0xc0, 0x9c, 0xab, 0x1b, 0xcd, 0x45, 0xbb, - 0x92, 0xc8, 0x1e, 0x23, 0x31, 0x80, 0x35, 0x50, 0xe9, 0xd1, 0x00, 0xf1, 0x51, 0x8c, 0x98, 0xd7, - 0x08, 0x10, 0x8b, 0x34, 0xa0, 0x0d, 0x80, 0x08, 0xd1, 0x79, 0xe0, 0xa8, 0xd8, 0x30, 0x17, 0x12, - 0x47, 0xe2, 0xb8, 0xb0, 0xd2, 0xb8, 0xb0, 0xba, 0x69, 0xe0, 0xec, 0x97, 0x94, 0x23, 0x9f, 0x7e, - 0x5d, 0x33, 0xec, 0xb2, 0xb6, 0x53, 0x1a, 0xf8, 0x14, 0xac, 0x0e, 0x83, 0x1e, 0x0b, 0x5c, 0x1a, - 0xf4, 0x9d, 0x90, 0x70, 0xca, 0x5c, 0xb3, 0xa4, 0xa9, 0x36, 0x2f, 0x51, 0x1d, 0x24, 0x21, 0x16, - 0x33, 0x7d, 0xa6, 0x98, 0x56, 0x32, 0xe3, 0x8e, 0xb6, 0x85, 0x3f, 0x03, 0x10, 0xe3, 0x48, 0xbb, - 0xc4, 0x86, 0x32, 0x65, 0x2c, 0x4f, 0xcf, 0xb8, 0x8a, 0x71, 0xd4, 0x8d, 0xad, 0x13, 0xca, 0x9f, - 0x83, 0x9b, 0x92, 0xa3, 0x40, 0x9c, 0x12, 0x7e, 0x91, 0x17, 0x4c, 0xcf, 0xfb, 0x46, 0xca, 0x31, - 0x49, 0xfe, 0x18, 0xd4, 0x71, 0x12, 0x40, 0x0e, 0x27, 0x2e, 0x15, 0x92, 0xd3, 0xde, 0x50, 0xd9, - 0x3a, 0xa7, 0x1c, 0x61, 0x1d, 0x23, 0x15, 0x1d, 0x04, 0xd5, 0x14, 0x67, 0x4f, 0xc0, 0xde, 0x4f, - 0x50, 0xf0, 0x23, 0xf0, 0xfd, 0x9e, 0xc7, 0xf0, 0x99, 0x50, 0xce, 0x39, 0x13, 0x4c, 0x7a, 0x69, - 0x9f, 0x0a, 0xa1, 0xd8, 0x16, 0xeb, 0x46, 0xb3, 0x60, 0xdf, 0x8a, 0xb1, 0x1d, 0xc2, 0x0f, 0x72, - 0xc8, 0x6e, 0x0e, 0x08, 0xef, 0x01, 0x38, 0xa0, 0x42, 0x32, 0x4e, 0x31, 0xf2, 0x1c, 0x12, 0x48, - 0x4e, 0x89, 0x30, 0x97, 0xb4, 0xf9, 0xda, 0x58, 0xf3, 0x28, 0x56, 0xc0, 0x43, 0x70, 0xeb, 0xda, - 0x45, 0x1d, 0x3c, 0x40, 0x41, 0x40, 0x3c, 0x73, 0x59, 0x6f, 0xa5, 0xe6, 0x5e, 0xb3, 0x66, 0x3b, - 0x86, 0xc1, 0x75, 0x30, 0x27, 0x59, 0xe8, 0x3c, 0x35, 0x57, 0xea, 0x46, 0x73, 0xc9, 0x2e, 0x4a, - 0x16, 0x3e, 0x85, 0xef, 0x80, 0x8d, 0x08, 0x79, 0xd4, 0x45, 0x92, 0x71, 0xe1, 0x84, 0xec, 0x9c, - 0x70, 0x07, 0xa3, 0xd0, 0x5c, 0xd5, 0x18, 0x38, 0xd6, 0x75, 0x94, 0xaa, 0x8d, 0x42, 0xf8, 0x36, - 0x58, 0xcb, 0xa4, 0x8e, 0x20, 0x52, 0xc3, 0xd7, 0x34, 0x7c, 0x25, 0x53, 0x1c, 0x13, 0xa9, 0xb0, - 0xdb, 0xa0, 0x8c, 0x3c, 0x8f, 0x9d, 0x7b, 0x54, 0x48, 0x13, 0xd6, 0x0b, 0xcd, 0xb2, 0x3d, 0x16, - 0xc0, 0x2d, 0x50, 0x72, 0x49, 0x30, 0xd2, 0xca, 0x75, 0xad, 0xcc, 0xde, 0xe1, 0x9b, 0xa0, 0xec, - 0xab, 0x1a, 0x2b, 0xd1, 0x19, 0x31, 0x37, 0xea, 0x46, 0xb3, 0x68, 0x97, 0x7c, 0x1a, 0x1c, 0xab, - 0x77, 0x68, 0x81, 0x75, 0xcd, 0xe2, 0xd0, 0x40, 0xdd, 0x53, 0x44, 0x9c, 0x08, 0x79, 0xc2, 0x7c, - 0xa3, 0x6e, 0x34, 0x4b, 0xf6, 0x9a, 0x56, 0x3d, 0x49, 0x34, 0x27, 0xc8, 0x13, 0x0f, 0xee, 0xfc, - 0xea, 0xf3, 0xda, 0xcc, 0x67, 0x9f, 0xd7, 0x66, 0xfe, 0xfa, 0xa7, 0x7b, 0x5b, 0x49, 0xf9, 0xe9, - 0xb3, 0xc8, 0x4a, 0x4a, 0x95, 0xd5, 0x66, 0x81, 0x24, 0x81, 0x6c, 0xfc, 0xdd, 0x00, 0x37, 0xdb, - 0x59, 0x40, 0xf8, 0x2c, 0x42, 0xde, 0x77, 0x59, 0x78, 0xf6, 0x40, 0x59, 0xa8, 0x1b, 0xd1, 0xa9, - 0x5e, 0x7c, 0x8d, 0x54, 0x2f, 0x29, 0x33, 0xa5, 0x78, 0x50, 0xfd, 0x86, 0x1d, 0xfd, 0x7b, 0x16, - 0x6c, 0xa7, 0x3b, 0xfa, 0x90, 0xb9, 0xf4, 0x94, 0x62, 0xf4, 0x5d, 0xd7, 0xd3, 0x2c, 0xce, 0x8a, - 0x53, 0xc4, 0xd9, 0xdc, 0xeb, 0xc5, 0xd9, 0xfc, 0x14, 0x71, 0xb6, 0xf0, 0xaa, 0x38, 0x2b, 0xbd, - 0x2a, 0xce, 0xca, 0xd3, 0xc5, 0x19, 0xb8, 0x26, 0xce, 0x1a, 0xbf, 0x33, 0xc0, 0xc6, 0xa3, 0x67, - 0x43, 0x1a, 0xb1, 0xff, 0xd3, 0x29, 0x1f, 0x81, 0x25, 0x92, 0xe3, 0x13, 0x66, 0xa1, 0x5e, 0x68, - 0x56, 0x76, 0x6f, 0x5b, 0xc9, 0x95, 0x67, 0x7d, 0x38, 0xbd, 0xf7, 0xfc, 0xea, 0xf6, 0xa4, 0xed, - 0x83, 0x59, 0xd3, 0x68, 0xfc, 0xc5, 0x00, 0x5b, 0xaa, 0x1e, 0xf4, 0x89, 0x4d, 0xce, 0x11, 0x77, - 0x0f, 0x48, 0xc0, 0x7c, 0xf1, 0xad, 0xfd, 0x6c, 0x80, 0x25, 0x57, 0x33, 0x39, 0x92, 0x39, 0xc8, - 0x75, 0xb5, 0x9f, 0x1a, 0xa3, 0x84, 0x5d, 0xb6, 0xe7, 0xba, 0xb0, 0x09, 0x56, 0xc7, 0x18, 0xae, - 0xb2, 0x4b, 0x05, 0xbd, 0x82, 0x2d, 0xa7, 0x30, 0x9d, 0x73, 0x53, 0x04, 0xb5, 0x01, 0x56, 0x3f, - 0xf0, 0x58, 0x0f, 0x79, 0xc7, 0x1e, 0x12, 0x03, 0x55, 0x2b, 0x47, 0x2a, 0x99, 0x38, 0x49, 0x9a, - 0x94, 0x76, 0x7f, 0xea, 0x64, 0x52, 0x66, 0xba, 0x6d, 0x3e, 0x04, 0x6b, 0x59, 0xdb, 0xc8, 0x82, - 0x5b, 0xef, 0x76, 0x7f, 0xfd, 0xc5, 0x57, 0xb5, 0x95, 0x34, 0x91, 0xda, 0x3a, 0xd0, 0x0f, 0xec, - 0x15, 0x3c, 0x21, 0x70, 0x61, 0x15, 0x54, 0x68, 0x0f, 0x3b, 0x82, 0x3c, 0x73, 0x82, 0xa1, 0xaf, - 0xf3, 0xa2, 0x68, 0x97, 0x69, 0x0f, 0x1f, 0x93, 0x67, 0x4f, 0x87, 0x3e, 0x7c, 0x17, 0xdc, 0x48, - 0x87, 0x49, 0x15, 0x49, 0x8e, 0xb2, 0x57, 0xc7, 0xc5, 0x75, 0xaa, 0x2c, 0xda, 0xeb, 0xa9, 0xf6, - 0x04, 0x79, 0x6a, 0xb1, 0x3d, 0xd7, 0xe5, 0x8d, 0xff, 0xcc, 0x81, 0xf9, 0x0e, 0xe2, 0xc8, 0x17, - 0xb0, 0x0b, 0x56, 0x24, 0xf1, 0x43, 0x0f, 0x49, 0xe2, 0xc4, 0x23, 0x49, 0xb2, 0xd3, 0xbb, 0x7a, - 0x54, 0xc9, 0x0f, 0x7e, 0x56, 0x6e, 0xd4, 0x8b, 0x76, 0xac, 0xb6, 0x96, 0x1e, 0x4b, 0x24, 0x89, - 0xbd, 0x9c, 0x72, 0xc4, 0x42, 0x78, 0x1f, 0x98, 0x92, 0x0f, 0x85, 0x1c, 0x0f, 0x0b, 0xe3, 0x2e, - 0x19, 0xdf, 0xf5, 0x8d, 0x54, 0x1f, 0xf7, 0xd7, 0xac, 0x3b, 0x5e, 0x3d, 0x17, 0x14, 0xbe, 0xcd, - 0x5c, 0xe0, 0x82, 0x6d, 0xa1, 0x2e, 0xd5, 0xf1, 0x89, 0xd4, 0xdd, 0x3b, 0xf4, 0x48, 0x40, 0xc5, - 0x20, 0x25, 0x9f, 0x9f, 0x9e, 0x7c, 0x53, 0x13, 0x7d, 0xa8, 0x78, 0xec, 0x94, 0x26, 0x59, 0xa5, - 0x0d, 0xaa, 0x57, 0xaf, 0x92, 0x6d, 0x7c, 0x41, 0x6f, 0xfc, 0xcd, 0x2b, 0x28, 0xb2, 0xdd, 0x0b, - 0x70, 0x27, 0x37, 0x65, 0xa8, 0x6c, 0x72, 0x74, 0x20, 0x3b, 0x9c, 0xf4, 0x55, 0x2b, 0x46, 0xf1, - 0xc0, 0x41, 0x48, 0x36, 0x29, 0x25, 0x31, 0xad, 0xc6, 0xe4, 0x5c, 0x50, 0xd3, 0x20, 0x19, 0x27, - 0x1b, 0xe3, 0x61, 0x24, 0xcb, 0x4d, 0x3b, 0xc7, 0xf5, 0x3e, 0x21, 0x2a, 0x8b, 0x72, 0x03, 0x09, - 0x09, 0x19, 0x1e, 0xe8, 0x7a, 0x54, 0xb0, 0x97, 0xb3, 0xe1, 0xe3, 0x91, 0x92, 0xc2, 0x4f, 0xc0, - 0xdd, 0x60, 0xe8, 0xf7, 0x08, 0x77, 0xd8, 0x69, 0x0c, 0xd4, 0x99, 0x27, 0x24, 0xe2, 0xd2, 0xe1, - 0x04, 0x13, 0x1a, 0xa9, 0x1b, 0x8f, 0x3d, 0x17, 0x7a, 0x1e, 0x2a, 0xd8, 0xb7, 0x63, 0x93, 0x8f, - 0x4e, 0x35, 0x87, 0xe8, 0xb2, 0x63, 0x05, 0xb7, 0x53, 0x74, 0xec, 0x98, 0x80, 0x4f, 0xc0, 0x2d, - 0x1f, 0x3d, 0x77, 0xb2, 0x60, 0x56, 0x8e, 0x93, 0x40, 0x0c, 0x85, 0x33, 0x2e, 0xe4, 0xc9, 0x4c, - 0x54, 0xf5, 0xd1, 0xf3, 0x4e, 0x82, 0x6b, 0xa7, 0xb0, 0x93, 0x0c, 0x75, 0x58, 0x2c, 0x15, 0x57, - 0xe7, 0x0e, 0x8b, 0xa5, 0xb9, 0xd5, 0xf9, 0xc3, 0x62, 0xa9, 0xb4, 0x5a, 0x6e, 0xfc, 0x00, 0x94, - 0x75, 0x5e, 0xef, 0xe1, 0x33, 0xa1, 0x2b, 0xbb, 0xeb, 0x72, 0x22, 0x04, 0x11, 0xa6, 0x91, 0x54, - 0xf6, 0x54, 0xd0, 0x90, 0x60, 0xf3, 0xba, 0x5f, 0x0a, 0x02, 0x7e, 0x0c, 0x16, 0x42, 0xa2, 0xc7, - 0x58, 0x6d, 0x58, 0xd9, 0x7d, 0xcf, 0x9a, 0xe2, 0x27, 0x9e, 0x75, 0x1d, 0xa1, 0x9d, 0xb2, 0x35, - 0xf8, 0xf8, 0xf7, 0xc9, 0x85, 0x29, 0x41, 0xc0, 0x93, 0x8b, 0x8b, 0xfe, 0xe4, 0xb5, 0x16, 0xbd, - 0xc0, 0x37, 0x5e, 0xf3, 0x2e, 0xa8, 0xec, 0xc5, 0xdb, 0xfe, 0xa9, 0x6a, 0x5b, 0x97, 0x8e, 0x65, - 0x31, 0x7f, 0x2c, 0x87, 0x60, 0x39, 0x19, 0xfa, 0xba, 0x4c, 0xd7, 0x26, 0xf8, 0x3d, 0x00, 0x92, - 0x69, 0x51, 0xd5, 0xb4, 0xb8, 0xba, 0x97, 0x13, 0xc9, 0x13, 0x77, 0xa2, 0x9b, 0xcf, 0x4e, 0x74, - 0xf3, 0x06, 0x03, 0x9b, 0x27, 0xf9, 0x6e, 0xab, 0x9b, 0x47, 0x07, 0xe1, 0x33, 0x22, 0x05, 0xb4, - 0x41, 0x51, 0x77, 0xd5, 0x78, 0xab, 0xf7, 0xaf, 0xdd, 0x6a, 0xb4, 0x63, 0x5d, 0x47, 0x72, 0x80, - 0x24, 0x4a, 0xe2, 0x5f, 0x73, 0x35, 0x7e, 0x63, 0x00, 0xf3, 0x88, 0x8c, 0xf6, 0x84, 0xa0, 0xfd, - 0xc0, 0x27, 0x81, 0x54, 0x99, 0x87, 0x30, 0x51, 0x8f, 0xf0, 0x2d, 0xb0, 0x94, 0x05, 0x9d, 0x2e, - 0x9c, 0x86, 0x2e, 0x9c, 0x8b, 0xa9, 0x50, 0x9d, 0x11, 0x7c, 0x00, 0x40, 0xc8, 0x49, 0xe4, 0x60, - 0xe7, 0x8c, 0x8c, 0xf4, 0x7e, 0x2a, 0xbb, 0xdb, 0xf9, 0x82, 0x18, 0xff, 0xd2, 0xb5, 0x3a, 0xc3, - 0x9e, 0x47, 0xf1, 0x11, 0x19, 0xd9, 0x25, 0x85, 0x6f, 0x1f, 0x91, 0x91, 0xea, 0x80, 0x7a, 0x38, - 0xd1, 0x55, 0xac, 0x60, 0xc7, 0x2f, 0x8d, 0xdf, 0x1a, 0xe0, 0x66, 0xb6, 0x81, 0xf4, 0xae, 0x3a, - 0xc3, 0x9e, 0xb2, 0xc8, 0x9f, 0x9d, 0x31, 0x39, 0x09, 0x5d, 0xf2, 0x76, 0xf6, 0x0a, 0x6f, 0x1f, - 0x82, 0xc5, 0xac, 0x8c, 0x28, 0x7f, 0x0b, 0x53, 0xf8, 0x5b, 0x49, 0x2d, 0x8e, 0xc8, 0xa8, 0xf1, - 0xcb, 0x9c, 0x6f, 0xfb, 0xa3, 0x5c, 0xf8, 0xf2, 0x6f, 0xf0, 0x2d, 0x5b, 0x36, 0xef, 0x1b, 0xce, - 0xdb, 0x5f, 0xda, 0x40, 0xe1, 0xf2, 0x06, 0x1a, 0x7f, 0x33, 0xc0, 0x8d, 0xfc, 0xaa, 0xa2, 0xcb, - 0x3a, 0x7c, 0x18, 0x90, 0x93, 0xdd, 0x57, 0xad, 0xff, 0x10, 0x94, 0x42, 0x85, 0x72, 0xa4, 0x48, - 0xae, 0x68, 0xba, 0x76, 0xbd, 0xa0, 0xad, 0xba, 0x2a, 0xbd, 0x97, 0x27, 0x36, 0x20, 0x92, 0x93, - 0x7b, 0x67, 0xaa, 0x84, 0xcb, 0x25, 0x93, 0xbd, 0x94, 0xdf, 0xb3, 0x68, 0xfc, 0xd9, 0x00, 0xf0, - 0x72, 0xa5, 0x82, 0x3f, 0x04, 0x70, 0xa2, 0xde, 0xe5, 0xe3, 0x6f, 0x35, 0xcc, 0x55, 0x38, 0x7d, - 0x72, 0x59, 0x1c, 0xcd, 0xe6, 0xe2, 0x08, 0xfe, 0x18, 0x80, 0x50, 0x5f, 0xe2, 0xd4, 0x37, 0x5d, - 0x0e, 0xd3, 0x47, 0x58, 0x03, 0x95, 0x5f, 0x30, 0x1a, 0xe4, 0x3f, 0x52, 0x14, 0x6c, 0xa0, 0x44, - 0xf1, 0xf7, 0x87, 0xc6, 0xaf, 0x8d, 0x71, 0x39, 0x4c, 0x2a, 0xf5, 0x9e, 0xe7, 0x25, 0xf3, 0x1f, - 0x0c, 0xc1, 0x42, 0x5a, 0xeb, 0xe3, 0x74, 0xdd, 0xbe, 0xb2, 0x1f, 0x1d, 0x10, 0xac, 0x5b, 0xd2, - 0x7d, 0x75, 0xe2, 0x7f, 0xf8, 0xba, 0x76, 0xb7, 0x4f, 0xe5, 0x60, 0xd8, 0xb3, 0x30, 0xf3, 0x93, - 0x2f, 0x37, 0xc9, 0xbf, 0x7b, 0xc2, 0x3d, 0x6b, 0xc9, 0x51, 0x48, 0x44, 0x6a, 0x23, 0x7e, 0xff, - 0xaf, 0x3f, 0xbe, 0x6d, 0xd8, 0xe9, 0x32, 0xfb, 0x1f, 0x7f, 0xf1, 0xa2, 0x6a, 0x7c, 0xf9, 0xa2, - 0x6a, 0xfc, 0xf3, 0x45, 0xd5, 0xf8, 0xf4, 0x65, 0x75, 0xe6, 0xcb, 0x97, 0xd5, 0x99, 0x7f, 0xbc, - 0xac, 0xce, 0x7c, 0xf2, 0xde, 0x65, 0xd2, 0xf1, 0xa5, 0xdd, 0xcb, 0x3e, 0xac, 0x45, 0x3f, 0x6a, - 0x3d, 0x9f, 0xfc, 0x6c, 0xa7, 0xd7, 0xeb, 0xcd, 0xeb, 0x08, 0x79, 0xf7, 0x7f, 0x01, 0x00, 0x00, - 0xff, 0xff, 0x8d, 0xfa, 0x87, 0x04, 0xe7, 0x13, 0x00, 0x00, +var xxx_messageInfo_ConsumerMetadata proto.InternalMessageInfo + +func (m *ConsumerMetadata) GetName() string { + if m != nil { + return m.Name + } + return "" } -func (m *ConsumerAdditionProposal) Marshal() (dAtA []byte, err error) { - size := m.Size() - dAtA = make([]byte, size) - n, err := m.MarshalToSizedBuffer(dAtA[:size]) - if err != nil { - return nil, err +func (m *ConsumerMetadata) GetDescription() string { + if m != nil { + return m.Description } - return dAtA[:n], nil + return "" } -func (m *ConsumerAdditionProposal) MarshalTo(dAtA []byte) (int, error) { - size := m.Size() - return m.MarshalToSizedBuffer(dAtA[:size]) +func (m *ConsumerMetadata) GetMetadata() string { + if m != nil { + return m.Metadata + } + return "" } -func (m *ConsumerAdditionProposal) MarshalToSizedBuffer(dAtA []byte) (int, error) { - i := len(dAtA) - _ = i - var l int - _ = l - if m.AllowInactiveVals { - i-- - if m.AllowInactiveVals { - dAtA[i] = 1 - } else { - dAtA[i] = 0 +// ConsumerInitializationParameters are the parameters needed to launch a chain +type ConsumerInitializationParameters struct { + // the proposed initial height of new consumer chain. + // For a completely new chain, this will be {0,1}. However, it may be + // different if this is a chain that is converting to a consumer chain. + InitialHeight types.Height `protobuf:"bytes,1,opt,name=initial_height,json=initialHeight,proto3" json:"initial_height"` + // The hash of the consumer chain genesis state without the consumer CCV + // module genesis params. It is used for off-chain confirmation of + // genesis.json validity by validators and other parties. + GenesisHash []byte `protobuf:"bytes,2,opt,name=genesis_hash,json=genesisHash,proto3" json:"genesis_hash,omitempty"` + // The hash of the consumer chain binary that should be run by validators on + // chain initialization. It is used for off-chain confirmation of binary + // validity by validators and other parties. + BinaryHash []byte `protobuf:"bytes,3,opt,name=binary_hash,json=binaryHash,proto3" json:"binary_hash,omitempty"` + // spawn time is the time on the provider chain at which the consumer chain + // genesis is finalized and all validators will be responsible for starting + // their consumer chain validator node. + SpawnTime time.Time `protobuf:"bytes,4,opt,name=spawn_time,json=spawnTime,proto3,stdtime" json:"spawn_time"` + // Unbonding period for the consumer, + // which should be smaller than that of the provider in general. + UnbondingPeriod time.Duration `protobuf:"bytes,5,opt,name=unbonding_period,json=unbondingPeriod,proto3,stdduration" json:"unbonding_period"` + // Sent CCV related IBC packets will timeout after this duration + CcvTimeoutPeriod time.Duration `protobuf:"bytes,6,opt,name=ccv_timeout_period,json=ccvTimeoutPeriod,proto3,stdduration" json:"ccv_timeout_period"` + // Sent transfer related IBC packets will timeout after this duration + TransferTimeoutPeriod time.Duration `protobuf:"bytes,7,opt,name=transfer_timeout_period,json=transferTimeoutPeriod,proto3,stdduration" json:"transfer_timeout_period"` + // The fraction of tokens allocated to the consumer redistribution address + // during distribution events. The fraction is a string representing a + // decimal number. For example "0.75" would represent 75%. + ConsumerRedistributionFraction string `protobuf:"bytes,8,opt,name=consumer_redistribution_fraction,json=consumerRedistributionFraction,proto3" json:"consumer_redistribution_fraction,omitempty"` + // BlocksPerDistributionTransmission is the number of blocks between + // ibc-token-transfers from the consumer chain to the provider chain. On + // sending transmission event, `consumer_redistribution_fraction` of the + // accumulated tokens are sent to the consumer redistribution address. + BlocksPerDistributionTransmission int64 `protobuf:"varint,9,opt,name=blocks_per_distribution_transmission,json=blocksPerDistributionTransmission,proto3" json:"blocks_per_distribution_transmission,omitempty"` + // The number of historical info entries to persist in store. + // This param is a part of the cosmos sdk staking module. In the case of + // a ccv enabled consumer chain, the ccv module acts as the staking module. + HistoricalEntries int64 `protobuf:"varint,10,opt,name=historical_entries,json=historicalEntries,proto3" json:"historical_entries,omitempty"` + // The ID of a token transfer channel used for the Reward Distribution + // sub-protocol. If DistributionTransmissionChannel == "", a new transfer + // channel is created on top of the same connection as the CCV channel. + // Note that transfer_channel_id is the ID of the channel end on the consumer + // chain. it is most relevant for chains performing a sovereign to consumer + // changeover in order to maintain the existing ibc transfer channel + DistributionTransmissionChannel string `protobuf:"bytes,11,opt,name=distribution_transmission_channel,json=distributionTransmissionChannel,proto3" json:"distribution_transmission_channel,omitempty"` +} + +func (m *ConsumerInitializationParameters) Reset() { *m = ConsumerInitializationParameters{} } +func (m *ConsumerInitializationParameters) String() string { return proto.CompactTextString(m) } +func (*ConsumerInitializationParameters) ProtoMessage() {} +func (*ConsumerInitializationParameters) Descriptor() ([]byte, []int) { + return fileDescriptor_f22ec409a72b7b72, []int{20} +} +func (m *ConsumerInitializationParameters) XXX_Unmarshal(b []byte) error { + return m.Unmarshal(b) +} +func (m *ConsumerInitializationParameters) XXX_Marshal(b []byte, deterministic bool) ([]byte, error) { + if deterministic { + return xxx_messageInfo_ConsumerInitializationParameters.Marshal(b, m, deterministic) + } else { + b = b[:cap(b)] + n, err := m.MarshalToSizedBuffer(b) + if err != nil { + return nil, err } - i-- - dAtA[i] = 0x1 - i-- - dAtA[i] = 0xa8 - } - if m.MinStake != 0 { - i = encodeVarintProvider(dAtA, i, uint64(m.MinStake)) - i-- - dAtA[i] = 0x1 - i-- - dAtA[i] = 0xa0 + return b[:n], nil } - if len(m.Denylist) > 0 { - for iNdEx := len(m.Denylist) - 1; iNdEx >= 0; iNdEx-- { - i -= len(m.Denylist[iNdEx]) - copy(dAtA[i:], m.Denylist[iNdEx]) - i = encodeVarintProvider(dAtA, i, uint64(len(m.Denylist[iNdEx]))) - i-- - dAtA[i] = 0x1 - i-- - dAtA[i] = 0x9a - } +} +func (m *ConsumerInitializationParameters) XXX_Merge(src proto.Message) { + xxx_messageInfo_ConsumerInitializationParameters.Merge(m, src) +} +func (m *ConsumerInitializationParameters) XXX_Size() int { + return m.Size() +} +func (m *ConsumerInitializationParameters) XXX_DiscardUnknown() { + xxx_messageInfo_ConsumerInitializationParameters.DiscardUnknown(m) +} + +var xxx_messageInfo_ConsumerInitializationParameters proto.InternalMessageInfo + +func (m *ConsumerInitializationParameters) GetInitialHeight() types.Height { + if m != nil { + return m.InitialHeight } - if len(m.Allowlist) > 0 { - for iNdEx := len(m.Allowlist) - 1; iNdEx >= 0; iNdEx-- { - i -= len(m.Allowlist[iNdEx]) - copy(dAtA[i:], m.Allowlist[iNdEx]) - i = encodeVarintProvider(dAtA, i, uint64(len(m.Allowlist[iNdEx]))) - i-- - dAtA[i] = 0x1 - i-- - dAtA[i] = 0x92 - } + return types.Height{} +} + +func (m *ConsumerInitializationParameters) GetGenesisHash() []byte { + if m != nil { + return m.GenesisHash } - if m.ValidatorSetCap != 0 { - i = encodeVarintProvider(dAtA, i, uint64(m.ValidatorSetCap)) - i-- - dAtA[i] = 0x1 - i-- - dAtA[i] = 0x88 + return nil +} + +func (m *ConsumerInitializationParameters) GetBinaryHash() []byte { + if m != nil { + return m.BinaryHash } - if m.ValidatorsPowerCap != 0 { - i = encodeVarintProvider(dAtA, i, uint64(m.ValidatorsPowerCap)) - i-- - dAtA[i] = 0x1 - i-- - dAtA[i] = 0x80 + return nil +} + +func (m *ConsumerInitializationParameters) GetSpawnTime() time.Time { + if m != nil { + return m.SpawnTime } - if m.Top_N != 0 { - i = encodeVarintProvider(dAtA, i, uint64(m.Top_N)) - i-- - dAtA[i] = 0x78 + return time.Time{} +} + +func (m *ConsumerInitializationParameters) GetUnbondingPeriod() time.Duration { + if m != nil { + return m.UnbondingPeriod } - if len(m.DistributionTransmissionChannel) > 0 { - i -= len(m.DistributionTransmissionChannel) - copy(dAtA[i:], m.DistributionTransmissionChannel) - i = encodeVarintProvider(dAtA, i, uint64(len(m.DistributionTransmissionChannel))) - i-- - dAtA[i] = 0x72 + return 0 +} + +func (m *ConsumerInitializationParameters) GetCcvTimeoutPeriod() time.Duration { + if m != nil { + return m.CcvTimeoutPeriod } - if m.HistoricalEntries != 0 { - i = encodeVarintProvider(dAtA, i, uint64(m.HistoricalEntries)) - i-- - dAtA[i] = 0x68 + return 0 +} + +func (m *ConsumerInitializationParameters) GetTransferTimeoutPeriod() time.Duration { + if m != nil { + return m.TransferTimeoutPeriod } - if m.BlocksPerDistributionTransmission != 0 { - i = encodeVarintProvider(dAtA, i, uint64(m.BlocksPerDistributionTransmission)) - i-- - dAtA[i] = 0x60 + return 0 +} + +func (m *ConsumerInitializationParameters) GetConsumerRedistributionFraction() string { + if m != nil { + return m.ConsumerRedistributionFraction } - if len(m.ConsumerRedistributionFraction) > 0 { - i -= len(m.ConsumerRedistributionFraction) - copy(dAtA[i:], m.ConsumerRedistributionFraction) - i = encodeVarintProvider(dAtA, i, uint64(len(m.ConsumerRedistributionFraction))) - i-- - dAtA[i] = 0x5a + return "" +} + +func (m *ConsumerInitializationParameters) GetBlocksPerDistributionTransmission() int64 { + if m != nil { + return m.BlocksPerDistributionTransmission } - n1, err1 := github_com_cosmos_gogoproto_types.StdDurationMarshalTo(m.TransferTimeoutPeriod, dAtA[i-github_com_cosmos_gogoproto_types.SizeOfStdDuration(m.TransferTimeoutPeriod):]) - if err1 != nil { - return 0, err1 + return 0 +} + +func (m *ConsumerInitializationParameters) GetHistoricalEntries() int64 { + if m != nil { + return m.HistoricalEntries } - i -= n1 - i = encodeVarintProvider(dAtA, i, uint64(n1)) - i-- - dAtA[i] = 0x52 - n2, err2 := github_com_cosmos_gogoproto_types.StdDurationMarshalTo(m.CcvTimeoutPeriod, dAtA[i-github_com_cosmos_gogoproto_types.SizeOfStdDuration(m.CcvTimeoutPeriod):]) - if err2 != nil { - return 0, err2 + return 0 +} + +func (m *ConsumerInitializationParameters) GetDistributionTransmissionChannel() string { + if m != nil { + return m.DistributionTransmissionChannel } - i -= n2 - i = encodeVarintProvider(dAtA, i, uint64(n2)) - i-- - dAtA[i] = 0x4a - n3, err3 := github_com_cosmos_gogoproto_types.StdDurationMarshalTo(m.UnbondingPeriod, dAtA[i-github_com_cosmos_gogoproto_types.SizeOfStdDuration(m.UnbondingPeriod):]) + return "" +} + +// PowerShapingParameters contains parameters that shape the validator set that we send to the consumer chain +type PowerShapingParameters struct { + // Corresponds to the percentage of validators that have to validate the chain under the Top N case. + // For example, 53 corresponds to a Top 53% chain, meaning that the top 53% provider validators by voting power + // have to validate the proposed consumer chain. top_N can either be 0 or any value in [50, 100]. + // A chain can join with top_N == 0 as an Opt In chain, or with top_N ∈ [50, 100] as a Top N chain. + Top_N uint32 `protobuf:"varint,1,opt,name=top_N,json=topN,proto3" json:"top_N,omitempty"` + // Corresponds to the maximum power (percentage-wise) a validator can have on the consumer chain. For instance, if + // `validators_power_cap` is set to 32, it means that no validator can have more than 32% of the voting power on the + // consumer chain. Note that this might not be feasible. For example, think of a consumer chain with only + // 5 validators and with `validators_power_cap` set to 10%. In such a scenario, at least one validator would need + // to have more than 20% of the total voting power. Therefore, `validators_power_cap` operates on a best-effort basis. + ValidatorsPowerCap uint32 `protobuf:"varint,2,opt,name=validators_power_cap,json=validatorsPowerCap,proto3" json:"validators_power_cap,omitempty"` + // Corresponds to the maximum number of validators that can validate a consumer chain. + // Only applicable to Opt In chains. Setting `validator_set_cap` on a Top N chain is a no-op. + ValidatorSetCap uint32 `protobuf:"varint,3,opt,name=validator_set_cap,json=validatorSetCap,proto3" json:"validator_set_cap,omitempty"` + // corresponds to a list of provider consensus addresses of validators that are the ONLY ones that can validate the consumer chain + Allowlist []string `protobuf:"bytes,4,rep,name=allowlist,proto3" json:"allowlist,omitempty"` + // corresponds to a list of provider consensus addresses of validators that CANNOT validate the consumer chain + Denylist []string `protobuf:"bytes,5,rep,name=denylist,proto3" json:"denylist,omitempty"` + // Corresponds to the minimal amount of (provider chain) stake required to validate on the consumer chain. + MinStake uint64 `protobuf:"varint,6,opt,name=min_stake,json=minStake,proto3" json:"min_stake,omitempty"` + // Corresponds to whether inactive validators are allowed to validate the consumer chain. + AllowInactiveVals bool `protobuf:"varint,7,opt,name=allow_inactive_vals,json=allowInactiveVals,proto3" json:"allow_inactive_vals,omitempty"` +} + +func (m *PowerShapingParameters) Reset() { *m = PowerShapingParameters{} } +func (m *PowerShapingParameters) String() string { return proto.CompactTextString(m) } +func (*PowerShapingParameters) ProtoMessage() {} +func (*PowerShapingParameters) Descriptor() ([]byte, []int) { + return fileDescriptor_f22ec409a72b7b72, []int{21} +} +func (m *PowerShapingParameters) XXX_Unmarshal(b []byte) error { + return m.Unmarshal(b) +} +func (m *PowerShapingParameters) XXX_Marshal(b []byte, deterministic bool) ([]byte, error) { + if deterministic { + return xxx_messageInfo_PowerShapingParameters.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 *PowerShapingParameters) XXX_Merge(src proto.Message) { + xxx_messageInfo_PowerShapingParameters.Merge(m, src) +} +func (m *PowerShapingParameters) XXX_Size() int { + return m.Size() +} +func (m *PowerShapingParameters) XXX_DiscardUnknown() { + xxx_messageInfo_PowerShapingParameters.DiscardUnknown(m) +} + +var xxx_messageInfo_PowerShapingParameters proto.InternalMessageInfo + +func (m *PowerShapingParameters) GetTop_N() uint32 { + if m != nil { + return m.Top_N + } + return 0 +} + +func (m *PowerShapingParameters) GetValidatorsPowerCap() uint32 { + if m != nil { + return m.ValidatorsPowerCap + } + return 0 +} + +func (m *PowerShapingParameters) GetValidatorSetCap() uint32 { + if m != nil { + return m.ValidatorSetCap + } + return 0 +} + +func (m *PowerShapingParameters) GetAllowlist() []string { + if m != nil { + return m.Allowlist + } + return nil +} + +func (m *PowerShapingParameters) GetDenylist() []string { + if m != nil { + return m.Denylist + } + return nil +} + +func (m *PowerShapingParameters) GetMinStake() uint64 { + if m != nil { + return m.MinStake + } + return 0 +} + +func (m *PowerShapingParameters) GetAllowInactiveVals() bool { + if m != nil { + return m.AllowInactiveVals + } + return false +} + +// ConsumerIds contains consumer ids of chains +// Used so we can easily (de)serialize slices of strings +type ConsumerIds struct { + Ids []string `protobuf:"bytes,1,rep,name=ids,proto3" json:"ids,omitempty"` +} + +func (m *ConsumerIds) Reset() { *m = ConsumerIds{} } +func (m *ConsumerIds) String() string { return proto.CompactTextString(m) } +func (*ConsumerIds) ProtoMessage() {} +func (*ConsumerIds) Descriptor() ([]byte, []int) { + return fileDescriptor_f22ec409a72b7b72, []int{22} +} +func (m *ConsumerIds) XXX_Unmarshal(b []byte) error { + return m.Unmarshal(b) +} +func (m *ConsumerIds) XXX_Marshal(b []byte, deterministic bool) ([]byte, error) { + if deterministic { + return xxx_messageInfo_ConsumerIds.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 *ConsumerIds) XXX_Merge(src proto.Message) { + xxx_messageInfo_ConsumerIds.Merge(m, src) +} +func (m *ConsumerIds) XXX_Size() int { + return m.Size() +} +func (m *ConsumerIds) XXX_DiscardUnknown() { + xxx_messageInfo_ConsumerIds.DiscardUnknown(m) +} + +var xxx_messageInfo_ConsumerIds proto.InternalMessageInfo + +func (m *ConsumerIds) GetIds() []string { + if m != nil { + return m.Ids + } + return nil +} + +func init() { + proto.RegisterEnum("interchain_security.ccv.provider.v1.ConsumerPhase", ConsumerPhase_name, ConsumerPhase_value) + proto.RegisterType((*ConsumerAdditionProposal)(nil), "interchain_security.ccv.provider.v1.ConsumerAdditionProposal") + proto.RegisterType((*ConsumerRemovalProposal)(nil), "interchain_security.ccv.provider.v1.ConsumerRemovalProposal") + proto.RegisterType((*ConsumerModificationProposal)(nil), "interchain_security.ccv.provider.v1.ConsumerModificationProposal") + proto.RegisterType((*EquivocationProposal)(nil), "interchain_security.ccv.provider.v1.EquivocationProposal") + proto.RegisterType((*ChangeRewardDenomsProposal)(nil), "interchain_security.ccv.provider.v1.ChangeRewardDenomsProposal") + proto.RegisterType((*GlobalSlashEntry)(nil), "interchain_security.ccv.provider.v1.GlobalSlashEntry") + proto.RegisterType((*Params)(nil), "interchain_security.ccv.provider.v1.Params") + proto.RegisterType((*SlashAcks)(nil), "interchain_security.ccv.provider.v1.SlashAcks") + proto.RegisterType((*ConsumerAdditionProposals)(nil), "interchain_security.ccv.provider.v1.ConsumerAdditionProposals") + proto.RegisterType((*ConsumerRemovalProposals)(nil), "interchain_security.ccv.provider.v1.ConsumerRemovalProposals") + proto.RegisterType((*AddressList)(nil), "interchain_security.ccv.provider.v1.AddressList") + proto.RegisterType((*ChannelToChain)(nil), "interchain_security.ccv.provider.v1.ChannelToChain") + proto.RegisterType((*ValidatorSetChangePackets)(nil), "interchain_security.ccv.provider.v1.ValidatorSetChangePackets") + proto.RegisterType((*KeyAssignmentReplacement)(nil), "interchain_security.ccv.provider.v1.KeyAssignmentReplacement") + proto.RegisterType((*ValidatorConsumerPubKey)(nil), "interchain_security.ccv.provider.v1.ValidatorConsumerPubKey") + proto.RegisterType((*ValidatorByConsumerAddr)(nil), "interchain_security.ccv.provider.v1.ValidatorByConsumerAddr") + proto.RegisterType((*ConsumerAddrsToPruneV2)(nil), "interchain_security.ccv.provider.v1.ConsumerAddrsToPruneV2") + proto.RegisterType((*ConsensusValidator)(nil), "interchain_security.ccv.provider.v1.ConsensusValidator") + proto.RegisterType((*ConsumerRewardsAllocation)(nil), "interchain_security.ccv.provider.v1.ConsumerRewardsAllocation") + proto.RegisterType((*ConsumerMetadata)(nil), "interchain_security.ccv.provider.v1.ConsumerMetadata") + proto.RegisterType((*ConsumerInitializationParameters)(nil), "interchain_security.ccv.provider.v1.ConsumerInitializationParameters") + proto.RegisterType((*PowerShapingParameters)(nil), "interchain_security.ccv.provider.v1.PowerShapingParameters") + proto.RegisterType((*ConsumerIds)(nil), "interchain_security.ccv.provider.v1.ConsumerIds") +} + +func init() { + proto.RegisterFile("interchain_security/ccv/provider/v1/provider.proto", fileDescriptor_f22ec409a72b7b72) +} + +var fileDescriptor_f22ec409a72b7b72 = []byte{ + // 2238 bytes of a gzipped FileDescriptorProto + 0x1f, 0x8b, 0x08, 0x00, 0x00, 0x00, 0x00, 0x00, 0x02, 0xff, 0xbc, 0x59, 0xbd, 0x6f, 0x1b, 0xc9, + 0x15, 0xd7, 0x8a, 0x94, 0x44, 0x3e, 0xea, 0x83, 0x1a, 0xfb, 0x6c, 0x4a, 0xa7, 0xa3, 0x68, 0x5e, + 0x6c, 0x28, 0x76, 0x4c, 0x9e, 0x74, 0x08, 0x60, 0x38, 0x39, 0x18, 0x32, 0x49, 0xdb, 0xf4, 0x87, + 0xcc, 0x2c, 0x69, 0x1d, 0xe0, 0x14, 0x8b, 0xe1, 0xee, 0x88, 0x9c, 0x68, 0x77, 0x67, 0xbd, 0x33, + 0xa4, 0xcd, 0x14, 0xa9, 0x0f, 0x01, 0x02, 0x5c, 0x52, 0x1d, 0xd2, 0xe4, 0x80, 0x34, 0x41, 0xaa, + 0x14, 0x41, 0xfe, 0x80, 0x54, 0x97, 0x00, 0x41, 0xae, 0x4c, 0x75, 0x17, 0xd8, 0x45, 0x8a, 0x00, + 0x69, 0xd3, 0x06, 0x33, 0xfb, 0xc1, 0xa5, 0x3e, 0x6c, 0x1a, 0xb6, 0xd3, 0x48, 0x3b, 0xef, 0xfd, + 0xde, 0x9b, 0x37, 0x33, 0xef, 0x6b, 0x86, 0xb0, 0x43, 0x5d, 0x41, 0x7c, 0xb3, 0x8f, 0xa9, 0x6b, + 0x70, 0x62, 0x0e, 0x7c, 0x2a, 0x46, 0x55, 0xd3, 0x1c, 0x56, 0x3d, 0x9f, 0x0d, 0xa9, 0x45, 0xfc, + 0xea, 0x70, 0x3b, 0xfe, 0xae, 0x78, 0x3e, 0x13, 0x0c, 0x7d, 0x78, 0x82, 0x4c, 0xc5, 0x34, 0x87, + 0x95, 0x18, 0x37, 0xdc, 0x5e, 0xbf, 0x78, 0x9a, 0xe2, 0xe1, 0x76, 0xf5, 0x29, 0xf5, 0x49, 0xa0, + 0x6b, 0xfd, 0x6c, 0x8f, 0xf5, 0x98, 0xfa, 0xac, 0xca, 0xaf, 0x90, 0xba, 0xd9, 0x63, 0xac, 0x67, + 0x93, 0xaa, 0x1a, 0x75, 0x07, 0x07, 0x55, 0x41, 0x1d, 0xc2, 0x05, 0x76, 0xbc, 0x10, 0x50, 0x3c, + 0x0a, 0xb0, 0x06, 0x3e, 0x16, 0x94, 0xb9, 0x91, 0x02, 0xda, 0x35, 0xab, 0x26, 0xf3, 0x49, 0xd5, + 0xb4, 0x29, 0x71, 0x85, 0x9c, 0x35, 0xf8, 0x0a, 0x01, 0x55, 0x09, 0xb0, 0x69, 0xaf, 0x2f, 0x02, + 0x32, 0xaf, 0x0a, 0xe2, 0x5a, 0xc4, 0x77, 0x68, 0x00, 0x1e, 0x8f, 0x42, 0x81, 0x8d, 0x04, 0xdf, + 0xf4, 0x47, 0x9e, 0x60, 0xd5, 0x43, 0x32, 0xe2, 0x21, 0xf7, 0x92, 0xc9, 0xb8, 0xc3, 0x78, 0x95, + 0xc8, 0xf5, 0xbb, 0x26, 0xa9, 0x0e, 0xb7, 0xbb, 0x44, 0xe0, 0xed, 0x98, 0x10, 0xd9, 0x1d, 0xe2, + 0xba, 0x98, 0x8f, 0x31, 0x26, 0xa3, 0x91, 0xdd, 0x6b, 0x01, 0xdf, 0x08, 0x76, 0x24, 0x18, 0x84, + 0xac, 0x55, 0xec, 0x50, 0x97, 0x55, 0xd5, 0xdf, 0x80, 0x54, 0xfe, 0x6f, 0x06, 0x0a, 0x35, 0xe6, + 0xf2, 0x81, 0x43, 0xfc, 0x5d, 0xcb, 0xa2, 0x72, 0x03, 0x5a, 0x3e, 0xf3, 0x18, 0xc7, 0x36, 0x3a, + 0x0b, 0x73, 0x82, 0x0a, 0x9b, 0x14, 0xb4, 0x92, 0xb6, 0x95, 0xd5, 0x83, 0x01, 0x2a, 0x41, 0xce, + 0x22, 0xdc, 0xf4, 0xa9, 0x27, 0xc1, 0x85, 0x59, 0xc5, 0x4b, 0x92, 0xd0, 0x1a, 0x64, 0x82, 0x53, + 0xa3, 0x56, 0x21, 0xa5, 0xd8, 0x0b, 0x6a, 0xdc, 0xb4, 0xd0, 0x6d, 0x58, 0xa6, 0x2e, 0x15, 0x14, + 0xdb, 0x46, 0x9f, 0xc8, 0xbd, 0x2b, 0xa4, 0x4b, 0xda, 0x56, 0x6e, 0x67, 0xbd, 0x42, 0xbb, 0x66, + 0x45, 0x6e, 0x77, 0x25, 0xdc, 0xe4, 0xe1, 0x76, 0xe5, 0x8e, 0x42, 0xdc, 0x4c, 0x7f, 0xf5, 0xcd, + 0xe6, 0x8c, 0xbe, 0x14, 0xca, 0x05, 0x44, 0x74, 0x01, 0x16, 0x7b, 0xc4, 0x25, 0x9c, 0x72, 0xa3, + 0x8f, 0x79, 0xbf, 0x30, 0x57, 0xd2, 0xb6, 0x16, 0xf5, 0x5c, 0x48, 0xbb, 0x83, 0x79, 0x1f, 0x6d, + 0x42, 0xae, 0x4b, 0x5d, 0xec, 0x8f, 0x02, 0xc4, 0xbc, 0x42, 0x40, 0x40, 0x52, 0x80, 0x1a, 0x00, + 0xf7, 0xf0, 0x53, 0xd7, 0x90, 0xbe, 0x51, 0x58, 0x08, 0x0d, 0x09, 0xfc, 0xa2, 0x12, 0xf9, 0x45, + 0xa5, 0x13, 0x39, 0xce, 0xcd, 0x8c, 0x34, 0xe4, 0xf3, 0x6f, 0x37, 0x35, 0x3d, 0xab, 0xe4, 0x24, + 0x07, 0xed, 0x41, 0x7e, 0xe0, 0x76, 0x99, 0x6b, 0x51, 0xb7, 0x67, 0x78, 0xc4, 0xa7, 0xcc, 0x2a, + 0x64, 0x94, 0xaa, 0xb5, 0x63, 0xaa, 0xea, 0xa1, 0x8b, 0x05, 0x9a, 0xbe, 0x90, 0x9a, 0x56, 0x62, + 0xe1, 0x96, 0x92, 0x45, 0x3f, 0x02, 0x64, 0x9a, 0x43, 0x65, 0x12, 0x1b, 0x88, 0x48, 0x63, 0x76, + 0x7a, 0x8d, 0x79, 0xd3, 0x1c, 0x76, 0x02, 0xe9, 0x50, 0xe5, 0x8f, 0xe1, 0xbc, 0xf0, 0xb1, 0xcb, + 0x0f, 0x88, 0x7f, 0x54, 0x2f, 0x4c, 0xaf, 0xf7, 0xbd, 0x48, 0xc7, 0xa4, 0xf2, 0x3b, 0x50, 0x32, + 0x43, 0x07, 0x32, 0x7c, 0x62, 0x51, 0x2e, 0x7c, 0xda, 0x1d, 0x48, 0x59, 0xe3, 0xc0, 0xc7, 0xa6, + 0xf2, 0x91, 0x9c, 0x72, 0x82, 0x62, 0x84, 0xd3, 0x27, 0x60, 0xb7, 0x42, 0x14, 0x7a, 0x08, 0xdf, + 0xe9, 0xda, 0xcc, 0x3c, 0xe4, 0xd2, 0x38, 0x63, 0x42, 0x93, 0x9a, 0xda, 0xa1, 0x9c, 0x4b, 0x6d, + 0x8b, 0x25, 0x6d, 0x2b, 0xa5, 0x5f, 0x08, 0xb0, 0x2d, 0xe2, 0xd7, 0x13, 0xc8, 0x4e, 0x02, 0x88, + 0xae, 0x02, 0xea, 0x53, 0x2e, 0x98, 0x4f, 0x4d, 0x6c, 0x1b, 0xc4, 0x15, 0x3e, 0x25, 0xbc, 0xb0, + 0xa4, 0xc4, 0x57, 0xc7, 0x9c, 0x46, 0xc0, 0x40, 0x77, 0xe1, 0xc2, 0xa9, 0x93, 0x1a, 0x66, 0x1f, + 0xbb, 0x2e, 0xb1, 0x0b, 0xcb, 0x6a, 0x29, 0x9b, 0xd6, 0x29, 0x73, 0xd6, 0x02, 0x18, 0x3a, 0x03, + 0x73, 0x82, 0x79, 0xc6, 0x5e, 0x61, 0xa5, 0xa4, 0x6d, 0x2d, 0xe9, 0x69, 0xc1, 0xbc, 0x3d, 0xf4, + 0x11, 0x9c, 0x1d, 0x62, 0x9b, 0x5a, 0x58, 0x30, 0x9f, 0x1b, 0x1e, 0x7b, 0x4a, 0x7c, 0xc3, 0xc4, + 0x5e, 0x21, 0xaf, 0x30, 0x68, 0xcc, 0x6b, 0x49, 0x56, 0x0d, 0x7b, 0xe8, 0x32, 0xac, 0xc6, 0x54, + 0x83, 0x13, 0xa1, 0xe0, 0xab, 0x0a, 0xbe, 0x12, 0x33, 0xda, 0x44, 0x48, 0xec, 0x06, 0x64, 0xb1, + 0x6d, 0xb3, 0xa7, 0x36, 0xe5, 0xa2, 0x80, 0x4a, 0xa9, 0xad, 0xac, 0x3e, 0x26, 0xa0, 0x75, 0xc8, + 0x58, 0xc4, 0x1d, 0x29, 0xe6, 0x19, 0xc5, 0x8c, 0xc7, 0xe8, 0x7d, 0xc8, 0x3a, 0x32, 0xc7, 0x0a, + 0x7c, 0x48, 0x0a, 0x67, 0x4b, 0xda, 0x56, 0x5a, 0xcf, 0x38, 0xd4, 0x6d, 0xcb, 0x31, 0xaa, 0xc0, + 0x19, 0xa5, 0xc5, 0xa0, 0xae, 0x3c, 0xa7, 0x21, 0x31, 0x86, 0xd8, 0xe6, 0x85, 0xf7, 0x4a, 0xda, + 0x56, 0x46, 0x5f, 0x55, 0xac, 0x66, 0xc8, 0xd9, 0xc7, 0x36, 0xbf, 0x7e, 0xe9, 0xb3, 0x2f, 0x37, + 0x67, 0xbe, 0xf8, 0x72, 0x73, 0xe6, 0xaf, 0x7f, 0xbc, 0xba, 0x1e, 0xa6, 0x9f, 0x1e, 0x1b, 0x56, + 0xc2, 0x54, 0x55, 0xa9, 0x31, 0x57, 0x10, 0x57, 0x94, 0xff, 0xae, 0xc1, 0xf9, 0x5a, 0xec, 0x10, + 0x0e, 0x1b, 0x62, 0xfb, 0x5d, 0x26, 0x9e, 0x5d, 0xc8, 0x72, 0x79, 0x22, 0x2a, 0xd4, 0xd3, 0xaf, + 0x11, 0xea, 0x19, 0x29, 0x26, 0x19, 0xd7, 0x8b, 0xaf, 0x58, 0xd1, 0xbf, 0x67, 0x61, 0x23, 0x5a, + 0xd1, 0x03, 0x66, 0xd1, 0x03, 0x6a, 0xe2, 0x77, 0x9d, 0x4f, 0x63, 0x3f, 0x4b, 0x4f, 0xe1, 0x67, + 0x73, 0xaf, 0xe7, 0x67, 0xf3, 0x53, 0xf8, 0xd9, 0xc2, 0xcb, 0xfc, 0x2c, 0xf3, 0x32, 0x3f, 0xcb, + 0x4e, 0xe7, 0x67, 0x70, 0x8a, 0x9f, 0x95, 0x7f, 0xa3, 0xc1, 0xd9, 0xc6, 0x93, 0x01, 0x1d, 0xb2, + 0xb7, 0xb4, 0xcb, 0xf7, 0x60, 0x89, 0x24, 0xf4, 0xf1, 0x42, 0xaa, 0x94, 0xda, 0xca, 0xed, 0x5c, + 0xac, 0x84, 0x47, 0x1e, 0xd7, 0xe1, 0xe8, 0xdc, 0x93, 0xb3, 0xeb, 0x93, 0xb2, 0xd7, 0x67, 0x0b, + 0x5a, 0xf9, 0xcf, 0x1a, 0xac, 0xcb, 0x7c, 0xd0, 0x23, 0x3a, 0x79, 0x8a, 0x7d, 0xab, 0x4e, 0x5c, + 0xe6, 0xf0, 0x37, 0xb6, 0xb3, 0x0c, 0x4b, 0x96, 0xd2, 0x64, 0x08, 0x66, 0x60, 0xcb, 0x52, 0x76, + 0x2a, 0x8c, 0x24, 0x76, 0xd8, 0xae, 0x65, 0xa1, 0x2d, 0xc8, 0x8f, 0x31, 0xbe, 0x8c, 0x2e, 0xe9, + 0xf4, 0x12, 0xb6, 0x1c, 0xc1, 0x54, 0xcc, 0x4d, 0xe1, 0xd4, 0x1a, 0xe4, 0x6f, 0xdb, 0xac, 0x8b, + 0xed, 0xb6, 0x8d, 0x79, 0x5f, 0xe6, 0xca, 0x91, 0x0c, 0x26, 0x9f, 0x84, 0x45, 0x4a, 0x99, 0x3f, + 0x75, 0x30, 0x49, 0x31, 0x55, 0x36, 0x6f, 0xc0, 0x6a, 0x5c, 0x36, 0x62, 0xe7, 0x56, 0xab, 0xbd, + 0x79, 0xe6, 0xf9, 0x37, 0x9b, 0x2b, 0x51, 0x20, 0xd5, 0x94, 0xa3, 0xd7, 0xf5, 0x15, 0x73, 0x82, + 0x60, 0xa1, 0x22, 0xe4, 0x68, 0xd7, 0x34, 0x38, 0x79, 0x62, 0xb8, 0x03, 0x47, 0xc5, 0x45, 0x5a, + 0xcf, 0xd2, 0xae, 0xd9, 0x26, 0x4f, 0xf6, 0x06, 0x0e, 0xfa, 0x18, 0xce, 0x45, 0xcd, 0xa4, 0xf4, + 0x24, 0x43, 0xca, 0xcb, 0xed, 0xf2, 0x55, 0xa8, 0x2c, 0xea, 0x67, 0x22, 0xee, 0x3e, 0xb6, 0xe5, + 0x64, 0xbb, 0x96, 0xe5, 0x97, 0xff, 0x33, 0x07, 0xf3, 0x2d, 0xec, 0x63, 0x87, 0xa3, 0x0e, 0xac, + 0x08, 0xe2, 0x78, 0x36, 0x16, 0xc4, 0x08, 0x5a, 0x92, 0x70, 0xa5, 0x57, 0x54, 0xab, 0x92, 0x6c, + 0xfc, 0x2a, 0x89, 0x56, 0x6f, 0xb8, 0x5d, 0xa9, 0x29, 0x6a, 0x5b, 0x60, 0x41, 0xf4, 0xe5, 0x48, + 0x47, 0x40, 0x44, 0xd7, 0xa0, 0x20, 0xfc, 0x01, 0x17, 0xe3, 0x66, 0x61, 0x5c, 0x25, 0x83, 0xb3, + 0x3e, 0x17, 0xf1, 0x83, 0xfa, 0x1a, 0x57, 0xc7, 0x93, 0xfb, 0x82, 0xd4, 0x9b, 0xf4, 0x05, 0x16, + 0x6c, 0x70, 0x79, 0xa8, 0x86, 0x43, 0x84, 0xaa, 0xde, 0x9e, 0x4d, 0x5c, 0xca, 0xfb, 0x91, 0xf2, + 0xf9, 0xe9, 0x95, 0xaf, 0x29, 0x45, 0x0f, 0xa4, 0x1e, 0x3d, 0x52, 0x13, 0xce, 0x52, 0x83, 0xe2, + 0xc9, 0xb3, 0xc4, 0x0b, 0x5f, 0x50, 0x0b, 0x7f, 0xff, 0x04, 0x15, 0xf1, 0xea, 0x39, 0x5c, 0x4a, + 0x74, 0x19, 0x32, 0x9a, 0x0c, 0xe5, 0xc8, 0x86, 0x4f, 0x7a, 0xb2, 0x14, 0xe3, 0xa0, 0xe1, 0x20, + 0x24, 0xee, 0x94, 0x42, 0x9f, 0x96, 0x6d, 0x72, 0xc2, 0xa9, 0xa9, 0x1b, 0xb6, 0x93, 0xe5, 0x71, + 0x33, 0x12, 0xc7, 0xa6, 0x9e, 0xd0, 0x75, 0x8b, 0x10, 0x19, 0x45, 0x89, 0x86, 0x84, 0x78, 0xcc, + 0xec, 0xab, 0x7c, 0x94, 0xd2, 0x97, 0xe3, 0xe6, 0xa3, 0x21, 0xa9, 0xe8, 0x31, 0x5c, 0x71, 0x07, + 0x4e, 0x97, 0xf8, 0x06, 0x3b, 0x08, 0x80, 0x2a, 0xf2, 0xb8, 0xc0, 0xbe, 0x30, 0x7c, 0x62, 0x12, + 0x3a, 0x94, 0x27, 0x1e, 0x58, 0xce, 0x55, 0x3f, 0x94, 0xd2, 0x2f, 0x06, 0x22, 0x0f, 0x0f, 0x94, + 0x0e, 0xde, 0x61, 0x6d, 0x09, 0xd7, 0x23, 0x74, 0x60, 0x18, 0x47, 0x4d, 0xb8, 0xe0, 0xe0, 0x67, + 0x46, 0xec, 0xcc, 0xd2, 0x70, 0xe2, 0xf2, 0x01, 0x37, 0xc6, 0x89, 0x3c, 0xec, 0x89, 0x8a, 0x0e, + 0x7e, 0xd6, 0x0a, 0x71, 0xb5, 0x08, 0xb6, 0x1f, 0xa3, 0xee, 0xa6, 0x33, 0xe9, 0xfc, 0xdc, 0xdd, + 0x74, 0x66, 0x2e, 0x3f, 0x7f, 0x37, 0x9d, 0xc9, 0xe4, 0xb3, 0xe5, 0xef, 0x42, 0x56, 0xc5, 0xf5, + 0xae, 0x79, 0xc8, 0x55, 0x66, 0xb7, 0x2c, 0x9f, 0x70, 0x4e, 0x78, 0x41, 0x0b, 0x33, 0x7b, 0x44, + 0x28, 0x0b, 0x58, 0x3b, 0xed, 0xa6, 0xc0, 0xd1, 0xa7, 0xb0, 0xe0, 0x11, 0xd5, 0xc6, 0x2a, 0xc1, + 0xdc, 0xce, 0x27, 0x95, 0x29, 0xae, 0x78, 0x95, 0xd3, 0x14, 0xea, 0x91, 0xb6, 0xb2, 0x3f, 0xbe, + 0x9f, 0x1c, 0xe9, 0x12, 0x38, 0xda, 0x3f, 0x3a, 0xe9, 0x0f, 0x5f, 0x6b, 0xd2, 0x23, 0xfa, 0xc6, + 0x73, 0x5e, 0x81, 0xdc, 0x6e, 0xb0, 0xec, 0xfb, 0xb2, 0x6c, 0x1d, 0xdb, 0x96, 0xc5, 0xe4, 0xb6, + 0xdc, 0x85, 0xe5, 0xb0, 0xe9, 0xeb, 0x30, 0x95, 0x9b, 0xd0, 0x07, 0x00, 0x61, 0xb7, 0x28, 0x73, + 0x5a, 0x90, 0xdd, 0xb3, 0x21, 0xa5, 0x69, 0x4d, 0x54, 0xf3, 0xd9, 0x89, 0x6a, 0x5e, 0x66, 0xb0, + 0xb6, 0x9f, 0xac, 0xb6, 0xaa, 0x78, 0xb4, 0xb0, 0x79, 0x48, 0x04, 0x47, 0x3a, 0xa4, 0x55, 0x55, + 0x0d, 0x96, 0x7a, 0xed, 0xd4, 0xa5, 0x0e, 0xb7, 0x2b, 0xa7, 0x29, 0xa9, 0x63, 0x81, 0x43, 0xff, + 0x57, 0xba, 0xca, 0xbf, 0xd4, 0xa0, 0x70, 0x8f, 0x8c, 0x76, 0x39, 0xa7, 0x3d, 0xd7, 0x21, 0xae, + 0x90, 0x91, 0x87, 0x4d, 0x22, 0x3f, 0xd1, 0x87, 0xb0, 0x14, 0x3b, 0x9d, 0x4a, 0x9c, 0x9a, 0x4a, + 0x9c, 0x8b, 0x11, 0x51, 0xee, 0x11, 0xba, 0x0e, 0xe0, 0xf9, 0x64, 0x68, 0x98, 0xc6, 0x21, 0x19, + 0xa9, 0xf5, 0xe4, 0x76, 0x36, 0x92, 0x09, 0x31, 0xb8, 0xe9, 0x56, 0x5a, 0x83, 0xae, 0x4d, 0xcd, + 0x7b, 0x64, 0xa4, 0x67, 0x24, 0xbe, 0x76, 0x8f, 0x8c, 0x64, 0x05, 0x54, 0xcd, 0x89, 0xca, 0x62, + 0x29, 0x3d, 0x18, 0x94, 0x7f, 0xad, 0xc1, 0xf9, 0x78, 0x01, 0xd1, 0x59, 0xb5, 0x06, 0x5d, 0x29, + 0x91, 0xdc, 0x3b, 0x6d, 0xb2, 0x13, 0x3a, 0x66, 0xed, 0xec, 0x09, 0xd6, 0xde, 0x80, 0xc5, 0x38, + 0x8d, 0x48, 0x7b, 0x53, 0x53, 0xd8, 0x9b, 0x8b, 0x24, 0xee, 0x91, 0x51, 0xf9, 0x67, 0x09, 0xdb, + 0x6e, 0x8e, 0x12, 0xee, 0xeb, 0xbf, 0xc2, 0xb6, 0x78, 0xda, 0xa4, 0x6d, 0x66, 0x52, 0xfe, 0xd8, + 0x02, 0x52, 0xc7, 0x17, 0x50, 0xfe, 0x9b, 0x06, 0xe7, 0x92, 0xb3, 0xf2, 0x0e, 0x6b, 0xf9, 0x03, + 0x97, 0xec, 0xef, 0xbc, 0x6c, 0xfe, 0x1b, 0x90, 0xf1, 0x24, 0xca, 0x10, 0x3c, 0x3c, 0xa2, 0xe9, + 0xca, 0xf5, 0x82, 0x92, 0xea, 0xc8, 0xf0, 0x5e, 0x9e, 0x58, 0x00, 0x0f, 0x77, 0xee, 0xa3, 0xa9, + 0x02, 0x2e, 0x11, 0x4c, 0xfa, 0x52, 0x72, 0xcd, 0xbc, 0xfc, 0x27, 0x0d, 0xd0, 0xf1, 0x4c, 0x85, + 0xbe, 0x07, 0x68, 0x22, 0xdf, 0x25, 0xfd, 0x2f, 0xef, 0x25, 0x32, 0x9c, 0xda, 0xb9, 0xd8, 0x8f, + 0x66, 0x13, 0x7e, 0x84, 0x7e, 0x00, 0xe0, 0xa9, 0x43, 0x9c, 0xfa, 0xa4, 0xb3, 0x5e, 0xf4, 0x89, + 0x36, 0x21, 0xf7, 0x13, 0x46, 0xdd, 0xe4, 0x23, 0x45, 0x4a, 0x07, 0x49, 0x0a, 0xde, 0x1f, 0xca, + 0xbf, 0xd0, 0xc6, 0xe9, 0x30, 0xcc, 0xd4, 0xbb, 0xb6, 0x1d, 0xf6, 0x7f, 0xc8, 0x83, 0x85, 0x28, + 0xd7, 0x07, 0xe1, 0xba, 0x71, 0x62, 0x3d, 0xaa, 0x13, 0x53, 0x95, 0xa4, 0x6b, 0x72, 0xc7, 0x7f, + 0xff, 0xed, 0xe6, 0x95, 0x1e, 0x15, 0xfd, 0x41, 0xb7, 0x62, 0x32, 0x27, 0x7c, 0xb9, 0x09, 0xff, + 0x5d, 0xe5, 0xd6, 0x61, 0x55, 0x8c, 0x3c, 0xc2, 0x23, 0x19, 0xfe, 0xbb, 0x7f, 0xfd, 0xe1, 0xb2, + 0xa6, 0x47, 0xd3, 0x94, 0x2d, 0xc8, 0xc7, 0x77, 0x0f, 0x22, 0xb0, 0x85, 0x05, 0x46, 0x08, 0xd2, + 0x2e, 0x76, 0xa2, 0x06, 0x53, 0x7d, 0x4f, 0xd1, 0x5f, 0xae, 0x43, 0xc6, 0x09, 0x35, 0x84, 0xb7, + 0x8d, 0x78, 0x5c, 0xfe, 0xf9, 0x3c, 0x94, 0xa2, 0x69, 0x9a, 0xc1, 0x7b, 0x0c, 0xfd, 0x69, 0xd0, + 0x7e, 0xcb, 0xae, 0x49, 0xd6, 0x6e, 0x7e, 0xc2, 0x1b, 0x8f, 0xf6, 0x76, 0xde, 0x78, 0x66, 0x5f, + 0xf9, 0xc6, 0x93, 0x7a, 0xc5, 0x1b, 0x4f, 0xfa, 0xed, 0xbd, 0xf1, 0xcc, 0xbd, 0xf5, 0x37, 0x9e, + 0xf9, 0x77, 0xf4, 0xc6, 0xb3, 0xf0, 0x7f, 0x79, 0xe3, 0xc9, 0xbc, 0xd5, 0x37, 0x9e, 0xec, 0x9b, + 0xbd, 0xf1, 0xc0, 0x1b, 0xbd, 0xf1, 0xe4, 0xa6, 0x7a, 0xe3, 0x29, 0xff, 0x6a, 0x16, 0xce, 0xa9, + 0x1b, 0x74, 0xbb, 0x8f, 0x3d, 0x79, 0xb8, 0xe3, 0x10, 0x88, 0xaf, 0xe5, 0xda, 0x14, 0xd7, 0xf2, + 0xd9, 0xd7, 0xbb, 0x96, 0xa7, 0xa6, 0xb8, 0x96, 0xa7, 0x5f, 0x76, 0x2d, 0x9f, 0x7b, 0xd9, 0xb5, + 0x7c, 0x7e, 0xba, 0x6b, 0xf9, 0xc2, 0x69, 0xd7, 0xf2, 0x4d, 0xc8, 0xc5, 0x09, 0xc2, 0xe2, 0x28, + 0x0f, 0x29, 0x6a, 0x45, 0xcd, 0xa4, 0xfc, 0xbc, 0xfc, 0x17, 0x0d, 0x96, 0xe2, 0xaa, 0xde, 0xc7, + 0x9c, 0xa0, 0x22, 0xac, 0xd7, 0x1e, 0xee, 0xb5, 0x1f, 0x3d, 0x68, 0xe8, 0x46, 0xeb, 0xce, 0x6e, + 0xbb, 0x61, 0x3c, 0xda, 0x6b, 0xb7, 0x1a, 0xb5, 0xe6, 0xad, 0x66, 0xa3, 0x9e, 0x9f, 0x41, 0x1f, + 0xc0, 0xda, 0x11, 0xbe, 0xde, 0xb8, 0xdd, 0x6c, 0x77, 0x1a, 0x7a, 0xa3, 0x9e, 0xd7, 0x4e, 0x10, + 0x6f, 0xee, 0x35, 0x3b, 0xcd, 0xdd, 0xfb, 0xcd, 0xc7, 0x8d, 0x7a, 0x7e, 0x16, 0xbd, 0x0f, 0xe7, + 0x8f, 0xf0, 0xef, 0xef, 0x3e, 0xda, 0xab, 0xdd, 0x69, 0xd4, 0xf3, 0x29, 0xb4, 0x0e, 0xe7, 0x8e, + 0x30, 0xdb, 0x9d, 0x87, 0xad, 0x56, 0xa3, 0x9e, 0x4f, 0x9f, 0xc0, 0xab, 0x37, 0xee, 0x37, 0x3a, + 0x8d, 0x7a, 0x7e, 0x6e, 0x3d, 0xfd, 0xd9, 0x6f, 0x8b, 0x33, 0x37, 0x3f, 0xfd, 0xea, 0x79, 0x51, + 0xfb, 0xfa, 0x79, 0x51, 0xfb, 0xe7, 0xf3, 0xa2, 0xf6, 0xf9, 0x8b, 0xe2, 0xcc, 0xd7, 0x2f, 0x8a, + 0x33, 0xff, 0x78, 0x51, 0x9c, 0x79, 0xfc, 0xc9, 0xf1, 0x4c, 0x3e, 0xae, 0x94, 0x57, 0xe3, 0x5f, + 0x33, 0x86, 0xdf, 0xaf, 0x3e, 0x9b, 0xfc, 0xad, 0x44, 0x25, 0xf9, 0xee, 0xbc, 0x0a, 0xd2, 0x8f, + 0xff, 0x17, 0x00, 0x00, 0xff, 0xff, 0x79, 0x8b, 0xb8, 0x2d, 0x5c, 0x19, 0x00, 0x00, +} + +func (m *ConsumerAdditionProposal) 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 *ConsumerAdditionProposal) MarshalTo(dAtA []byte) (int, error) { + size := m.Size() + return m.MarshalToSizedBuffer(dAtA[:size]) +} + +func (m *ConsumerAdditionProposal) MarshalToSizedBuffer(dAtA []byte) (int, error) { + i := len(dAtA) + _ = i + var l int + _ = l + if m.AllowInactiveVals { + i-- + if m.AllowInactiveVals { + dAtA[i] = 1 + } else { + dAtA[i] = 0 + } + i-- + dAtA[i] = 0x1 + i-- + dAtA[i] = 0xa8 + } + if m.MinStake != 0 { + i = encodeVarintProvider(dAtA, i, uint64(m.MinStake)) + i-- + dAtA[i] = 0x1 + i-- + dAtA[i] = 0xa0 + } + if len(m.Denylist) > 0 { + for iNdEx := len(m.Denylist) - 1; iNdEx >= 0; iNdEx-- { + i -= len(m.Denylist[iNdEx]) + copy(dAtA[i:], m.Denylist[iNdEx]) + i = encodeVarintProvider(dAtA, i, uint64(len(m.Denylist[iNdEx]))) + i-- + dAtA[i] = 0x1 + i-- + dAtA[i] = 0x9a + } + } + if len(m.Allowlist) > 0 { + for iNdEx := len(m.Allowlist) - 1; iNdEx >= 0; iNdEx-- { + i -= len(m.Allowlist[iNdEx]) + copy(dAtA[i:], m.Allowlist[iNdEx]) + i = encodeVarintProvider(dAtA, i, uint64(len(m.Allowlist[iNdEx]))) + i-- + dAtA[i] = 0x1 + i-- + dAtA[i] = 0x92 + } + } + if m.ValidatorSetCap != 0 { + i = encodeVarintProvider(dAtA, i, uint64(m.ValidatorSetCap)) + i-- + dAtA[i] = 0x1 + i-- + dAtA[i] = 0x88 + } + if m.ValidatorsPowerCap != 0 { + i = encodeVarintProvider(dAtA, i, uint64(m.ValidatorsPowerCap)) + i-- + dAtA[i] = 0x1 + i-- + dAtA[i] = 0x80 + } + if m.Top_N != 0 { + i = encodeVarintProvider(dAtA, i, uint64(m.Top_N)) + i-- + dAtA[i] = 0x78 + } + if len(m.DistributionTransmissionChannel) > 0 { + i -= len(m.DistributionTransmissionChannel) + copy(dAtA[i:], m.DistributionTransmissionChannel) + i = encodeVarintProvider(dAtA, i, uint64(len(m.DistributionTransmissionChannel))) + i-- + dAtA[i] = 0x72 + } + if m.HistoricalEntries != 0 { + i = encodeVarintProvider(dAtA, i, uint64(m.HistoricalEntries)) + i-- + dAtA[i] = 0x68 + } + if m.BlocksPerDistributionTransmission != 0 { + i = encodeVarintProvider(dAtA, i, uint64(m.BlocksPerDistributionTransmission)) + i-- + dAtA[i] = 0x60 + } + if len(m.ConsumerRedistributionFraction) > 0 { + i -= len(m.ConsumerRedistributionFraction) + copy(dAtA[i:], m.ConsumerRedistributionFraction) + i = encodeVarintProvider(dAtA, i, uint64(len(m.ConsumerRedistributionFraction))) + i-- + dAtA[i] = 0x5a + } + n1, err1 := github_com_cosmos_gogoproto_types.StdDurationMarshalTo(m.TransferTimeoutPeriod, dAtA[i-github_com_cosmos_gogoproto_types.SizeOfStdDuration(m.TransferTimeoutPeriod):]) + if err1 != nil { + return 0, err1 + } + i -= n1 + i = encodeVarintProvider(dAtA, i, uint64(n1)) + i-- + dAtA[i] = 0x52 + n2, err2 := github_com_cosmos_gogoproto_types.StdDurationMarshalTo(m.CcvTimeoutPeriod, dAtA[i-github_com_cosmos_gogoproto_types.SizeOfStdDuration(m.CcvTimeoutPeriod):]) + if err2 != nil { + return 0, err2 + } + i -= n2 + i = encodeVarintProvider(dAtA, i, uint64(n2)) + i-- + dAtA[i] = 0x4a + n3, err3 := github_com_cosmos_gogoproto_types.StdDurationMarshalTo(m.UnbondingPeriod, dAtA[i-github_com_cosmos_gogoproto_types.SizeOfStdDuration(m.UnbondingPeriod):]) if err3 != nil { return 0, err3 } @@ -2589,7 +3038,257 @@ func (m *ConsumerRewardsAllocation) MarshalToSizedBuffer(dAtA []byte) (int, erro return len(dAtA) - i, nil } -func encodeVarintProvider(dAtA []byte, offset int, v uint64) int { +func (m *ConsumerMetadata) 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 *ConsumerMetadata) MarshalTo(dAtA []byte) (int, error) { + size := m.Size() + return m.MarshalToSizedBuffer(dAtA[:size]) +} + +func (m *ConsumerMetadata) MarshalToSizedBuffer(dAtA []byte) (int, error) { + i := len(dAtA) + _ = i + var l int + _ = l + if len(m.Metadata) > 0 { + i -= len(m.Metadata) + copy(dAtA[i:], m.Metadata) + i = encodeVarintProvider(dAtA, i, uint64(len(m.Metadata))) + i-- + dAtA[i] = 0x1a + } + if len(m.Description) > 0 { + i -= len(m.Description) + copy(dAtA[i:], m.Description) + i = encodeVarintProvider(dAtA, i, uint64(len(m.Description))) + i-- + dAtA[i] = 0x12 + } + if len(m.Name) > 0 { + i -= len(m.Name) + copy(dAtA[i:], m.Name) + i = encodeVarintProvider(dAtA, i, uint64(len(m.Name))) + i-- + dAtA[i] = 0xa + } + return len(dAtA) - i, nil +} + +func (m *ConsumerInitializationParameters) 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 *ConsumerInitializationParameters) MarshalTo(dAtA []byte) (int, error) { + size := m.Size() + return m.MarshalToSizedBuffer(dAtA[:size]) +} + +func (m *ConsumerInitializationParameters) MarshalToSizedBuffer(dAtA []byte) (int, error) { + i := len(dAtA) + _ = i + var l int + _ = l + if len(m.DistributionTransmissionChannel) > 0 { + i -= len(m.DistributionTransmissionChannel) + copy(dAtA[i:], m.DistributionTransmissionChannel) + i = encodeVarintProvider(dAtA, i, uint64(len(m.DistributionTransmissionChannel))) + i-- + dAtA[i] = 0x5a + } + if m.HistoricalEntries != 0 { + i = encodeVarintProvider(dAtA, i, uint64(m.HistoricalEntries)) + i-- + dAtA[i] = 0x50 + } + if m.BlocksPerDistributionTransmission != 0 { + i = encodeVarintProvider(dAtA, i, uint64(m.BlocksPerDistributionTransmission)) + i-- + dAtA[i] = 0x48 + } + if len(m.ConsumerRedistributionFraction) > 0 { + i -= len(m.ConsumerRedistributionFraction) + copy(dAtA[i:], m.ConsumerRedistributionFraction) + i = encodeVarintProvider(dAtA, i, uint64(len(m.ConsumerRedistributionFraction))) + i-- + dAtA[i] = 0x42 + } + n17, err17 := github_com_cosmos_gogoproto_types.StdDurationMarshalTo(m.TransferTimeoutPeriod, dAtA[i-github_com_cosmos_gogoproto_types.SizeOfStdDuration(m.TransferTimeoutPeriod):]) + if err17 != nil { + return 0, err17 + } + i -= n17 + i = encodeVarintProvider(dAtA, i, uint64(n17)) + i-- + dAtA[i] = 0x3a + n18, err18 := github_com_cosmos_gogoproto_types.StdDurationMarshalTo(m.CcvTimeoutPeriod, dAtA[i-github_com_cosmos_gogoproto_types.SizeOfStdDuration(m.CcvTimeoutPeriod):]) + if err18 != nil { + return 0, err18 + } + i -= n18 + i = encodeVarintProvider(dAtA, i, uint64(n18)) + i-- + dAtA[i] = 0x32 + n19, err19 := github_com_cosmos_gogoproto_types.StdDurationMarshalTo(m.UnbondingPeriod, dAtA[i-github_com_cosmos_gogoproto_types.SizeOfStdDuration(m.UnbondingPeriod):]) + if err19 != nil { + return 0, err19 + } + i -= n19 + i = encodeVarintProvider(dAtA, i, uint64(n19)) + i-- + dAtA[i] = 0x2a + n20, err20 := github_com_cosmos_gogoproto_types.StdTimeMarshalTo(m.SpawnTime, dAtA[i-github_com_cosmos_gogoproto_types.SizeOfStdTime(m.SpawnTime):]) + if err20 != nil { + return 0, err20 + } + i -= n20 + i = encodeVarintProvider(dAtA, i, uint64(n20)) + i-- + dAtA[i] = 0x22 + if len(m.BinaryHash) > 0 { + i -= len(m.BinaryHash) + copy(dAtA[i:], m.BinaryHash) + i = encodeVarintProvider(dAtA, i, uint64(len(m.BinaryHash))) + i-- + dAtA[i] = 0x1a + } + if len(m.GenesisHash) > 0 { + i -= len(m.GenesisHash) + copy(dAtA[i:], m.GenesisHash) + i = encodeVarintProvider(dAtA, i, uint64(len(m.GenesisHash))) + i-- + dAtA[i] = 0x12 + } + { + size, err := m.InitialHeight.MarshalToSizedBuffer(dAtA[:i]) + if err != nil { + return 0, err + } + i -= size + i = encodeVarintProvider(dAtA, i, uint64(size)) + } + i-- + dAtA[i] = 0xa + return len(dAtA) - i, nil +} + +func (m *PowerShapingParameters) 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 *PowerShapingParameters) MarshalTo(dAtA []byte) (int, error) { + size := m.Size() + return m.MarshalToSizedBuffer(dAtA[:size]) +} + +func (m *PowerShapingParameters) MarshalToSizedBuffer(dAtA []byte) (int, error) { + i := len(dAtA) + _ = i + var l int + _ = l + if m.AllowInactiveVals { + i-- + if m.AllowInactiveVals { + dAtA[i] = 1 + } else { + dAtA[i] = 0 + } + i-- + dAtA[i] = 0x38 + } + if m.MinStake != 0 { + i = encodeVarintProvider(dAtA, i, uint64(m.MinStake)) + i-- + dAtA[i] = 0x30 + } + if len(m.Denylist) > 0 { + for iNdEx := len(m.Denylist) - 1; iNdEx >= 0; iNdEx-- { + i -= len(m.Denylist[iNdEx]) + copy(dAtA[i:], m.Denylist[iNdEx]) + i = encodeVarintProvider(dAtA, i, uint64(len(m.Denylist[iNdEx]))) + i-- + dAtA[i] = 0x2a + } + } + if len(m.Allowlist) > 0 { + for iNdEx := len(m.Allowlist) - 1; iNdEx >= 0; iNdEx-- { + i -= len(m.Allowlist[iNdEx]) + copy(dAtA[i:], m.Allowlist[iNdEx]) + i = encodeVarintProvider(dAtA, i, uint64(len(m.Allowlist[iNdEx]))) + i-- + dAtA[i] = 0x22 + } + } + if m.ValidatorSetCap != 0 { + i = encodeVarintProvider(dAtA, i, uint64(m.ValidatorSetCap)) + i-- + dAtA[i] = 0x18 + } + if m.ValidatorsPowerCap != 0 { + i = encodeVarintProvider(dAtA, i, uint64(m.ValidatorsPowerCap)) + i-- + dAtA[i] = 0x10 + } + if m.Top_N != 0 { + i = encodeVarintProvider(dAtA, i, uint64(m.Top_N)) + i-- + dAtA[i] = 0x8 + } + return len(dAtA) - i, nil +} + +func (m *ConsumerIds) 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 *ConsumerIds) MarshalTo(dAtA []byte) (int, error) { + size := m.Size() + return m.MarshalToSizedBuffer(dAtA[:size]) +} + +func (m *ConsumerIds) MarshalToSizedBuffer(dAtA []byte) (int, error) { + i := len(dAtA) + _ = i + var l int + _ = l + if len(m.Ids) > 0 { + for iNdEx := len(m.Ids) - 1; iNdEx >= 0; iNdEx-- { + i -= len(m.Ids[iNdEx]) + copy(dAtA[i:], m.Ids[iNdEx]) + i = encodeVarintProvider(dAtA, i, uint64(len(m.Ids[iNdEx]))) + i-- + dAtA[i] = 0xa + } + } + return len(dAtA) - i, nil +} + +func encodeVarintProvider(dAtA []byte, offset int, v uint64) int { offset -= sovProvider(v) base := offset for v >= 1<<7 { @@ -3072,46 +3771,159 @@ func (m *ConsumerRewardsAllocation) Size() (n int) { return n } -func sovProvider(x uint64) (n int) { - return (math_bits.Len64(x|1) + 6) / 7 -} -func sozProvider(x uint64) (n int) { - return sovProvider(uint64((x << 1) ^ uint64((int64(x) >> 63)))) +func (m *ConsumerMetadata) Size() (n int) { + if m == nil { + return 0 + } + var l int + _ = l + l = len(m.Name) + if l > 0 { + n += 1 + l + sovProvider(uint64(l)) + } + l = len(m.Description) + if l > 0 { + n += 1 + l + sovProvider(uint64(l)) + } + l = len(m.Metadata) + if l > 0 { + n += 1 + l + sovProvider(uint64(l)) + } + return n } -func (m *ConsumerAdditionProposal) 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 ErrIntOverflowProvider - } - 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: ConsumerAdditionProposal: wiretype end group for non-group") - } - if fieldNum <= 0 { - return fmt.Errorf("proto: ConsumerAdditionProposal: illegal tag %d (wire type %d)", fieldNum, wire) - } - switch fieldNum { - case 1: - if wireType != 2 { - return fmt.Errorf("proto: wrong wireType = %d for field Title", wireType) - } - var stringLen uint64 + +func (m *ConsumerInitializationParameters) Size() (n int) { + if m == nil { + return 0 + } + var l int + _ = l + l = m.InitialHeight.Size() + n += 1 + l + sovProvider(uint64(l)) + l = len(m.GenesisHash) + if l > 0 { + n += 1 + l + sovProvider(uint64(l)) + } + l = len(m.BinaryHash) + if l > 0 { + n += 1 + l + sovProvider(uint64(l)) + } + l = github_com_cosmos_gogoproto_types.SizeOfStdTime(m.SpawnTime) + n += 1 + l + sovProvider(uint64(l)) + l = github_com_cosmos_gogoproto_types.SizeOfStdDuration(m.UnbondingPeriod) + n += 1 + l + sovProvider(uint64(l)) + l = github_com_cosmos_gogoproto_types.SizeOfStdDuration(m.CcvTimeoutPeriod) + n += 1 + l + sovProvider(uint64(l)) + l = github_com_cosmos_gogoproto_types.SizeOfStdDuration(m.TransferTimeoutPeriod) + n += 1 + l + sovProvider(uint64(l)) + l = len(m.ConsumerRedistributionFraction) + if l > 0 { + n += 1 + l + sovProvider(uint64(l)) + } + if m.BlocksPerDistributionTransmission != 0 { + n += 1 + sovProvider(uint64(m.BlocksPerDistributionTransmission)) + } + if m.HistoricalEntries != 0 { + n += 1 + sovProvider(uint64(m.HistoricalEntries)) + } + l = len(m.DistributionTransmissionChannel) + if l > 0 { + n += 1 + l + sovProvider(uint64(l)) + } + return n +} + +func (m *PowerShapingParameters) Size() (n int) { + if m == nil { + return 0 + } + var l int + _ = l + if m.Top_N != 0 { + n += 1 + sovProvider(uint64(m.Top_N)) + } + if m.ValidatorsPowerCap != 0 { + n += 1 + sovProvider(uint64(m.ValidatorsPowerCap)) + } + if m.ValidatorSetCap != 0 { + n += 1 + sovProvider(uint64(m.ValidatorSetCap)) + } + if len(m.Allowlist) > 0 { + for _, s := range m.Allowlist { + l = len(s) + n += 1 + l + sovProvider(uint64(l)) + } + } + if len(m.Denylist) > 0 { + for _, s := range m.Denylist { + l = len(s) + n += 1 + l + sovProvider(uint64(l)) + } + } + if m.MinStake != 0 { + n += 1 + sovProvider(uint64(m.MinStake)) + } + if m.AllowInactiveVals { + n += 2 + } + return n +} + +func (m *ConsumerIds) Size() (n int) { + if m == nil { + return 0 + } + var l int + _ = l + if len(m.Ids) > 0 { + for _, s := range m.Ids { + l = len(s) + n += 1 + l + sovProvider(uint64(l)) + } + } + return n +} + +func sovProvider(x uint64) (n int) { + return (math_bits.Len64(x|1) + 6) / 7 +} +func sozProvider(x uint64) (n int) { + return sovProvider(uint64((x << 1) ^ uint64((int64(x) >> 63)))) +} +func (m *ConsumerAdditionProposal) 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 ErrIntOverflowProvider + } + 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: ConsumerAdditionProposal: wiretype end group for non-group") + } + if fieldNum <= 0 { + return fmt.Errorf("proto: ConsumerAdditionProposal: illegal tag %d (wire type %d)", fieldNum, wire) + } + switch fieldNum { + case 1: + if wireType != 2 { + return fmt.Errorf("proto: wrong wireType = %d for field Title", wireType) + } + var stringLen uint64 for shift := uint(0); ; shift += 7 { if shift >= 64 { return ErrIntOverflowProvider @@ -6368,6 +7180,829 @@ func (m *ConsumerRewardsAllocation) Unmarshal(dAtA []byte) error { } return nil } +func (m *ConsumerMetadata) 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 ErrIntOverflowProvider + } + 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: ConsumerMetadata: wiretype end group for non-group") + } + if fieldNum <= 0 { + return fmt.Errorf("proto: ConsumerMetadata: illegal tag %d (wire type %d)", fieldNum, wire) + } + switch fieldNum { + case 1: + if wireType != 2 { + return fmt.Errorf("proto: wrong wireType = %d for field Name", wireType) + } + var stringLen uint64 + for shift := uint(0); ; shift += 7 { + if shift >= 64 { + return ErrIntOverflowProvider + } + 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 ErrInvalidLengthProvider + } + postIndex := iNdEx + intStringLen + if postIndex < 0 { + return ErrInvalidLengthProvider + } + if postIndex > l { + return io.ErrUnexpectedEOF + } + m.Name = string(dAtA[iNdEx:postIndex]) + iNdEx = postIndex + case 2: + if wireType != 2 { + return fmt.Errorf("proto: wrong wireType = %d for field Description", wireType) + } + var stringLen uint64 + for shift := uint(0); ; shift += 7 { + if shift >= 64 { + return ErrIntOverflowProvider + } + 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 ErrInvalidLengthProvider + } + postIndex := iNdEx + intStringLen + if postIndex < 0 { + return ErrInvalidLengthProvider + } + if postIndex > l { + return io.ErrUnexpectedEOF + } + m.Description = string(dAtA[iNdEx:postIndex]) + iNdEx = postIndex + case 3: + if wireType != 2 { + return fmt.Errorf("proto: wrong wireType = %d for field Metadata", wireType) + } + var stringLen uint64 + for shift := uint(0); ; shift += 7 { + if shift >= 64 { + return ErrIntOverflowProvider + } + 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 ErrInvalidLengthProvider + } + postIndex := iNdEx + intStringLen + if postIndex < 0 { + return ErrInvalidLengthProvider + } + if postIndex > l { + return io.ErrUnexpectedEOF + } + m.Metadata = string(dAtA[iNdEx:postIndex]) + iNdEx = postIndex + default: + iNdEx = preIndex + skippy, err := skipProvider(dAtA[iNdEx:]) + if err != nil { + return err + } + if (skippy < 0) || (iNdEx+skippy) < 0 { + return ErrInvalidLengthProvider + } + if (iNdEx + skippy) > l { + return io.ErrUnexpectedEOF + } + iNdEx += skippy + } + } + + if iNdEx > l { + return io.ErrUnexpectedEOF + } + return nil +} +func (m *ConsumerInitializationParameters) 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 ErrIntOverflowProvider + } + 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: ConsumerInitializationParameters: wiretype end group for non-group") + } + if fieldNum <= 0 { + return fmt.Errorf("proto: ConsumerInitializationParameters: illegal tag %d (wire type %d)", fieldNum, wire) + } + switch fieldNum { + case 1: + if wireType != 2 { + return fmt.Errorf("proto: wrong wireType = %d for field InitialHeight", wireType) + } + var msglen int + for shift := uint(0); ; shift += 7 { + if shift >= 64 { + return ErrIntOverflowProvider + } + if iNdEx >= l { + return io.ErrUnexpectedEOF + } + b := dAtA[iNdEx] + iNdEx++ + msglen |= int(b&0x7F) << shift + if b < 0x80 { + break + } + } + if msglen < 0 { + return ErrInvalidLengthProvider + } + postIndex := iNdEx + msglen + if postIndex < 0 { + return ErrInvalidLengthProvider + } + if postIndex > l { + return io.ErrUnexpectedEOF + } + if err := m.InitialHeight.Unmarshal(dAtA[iNdEx:postIndex]); err != nil { + return err + } + iNdEx = postIndex + case 2: + if wireType != 2 { + return fmt.Errorf("proto: wrong wireType = %d for field GenesisHash", wireType) + } + var byteLen int + for shift := uint(0); ; shift += 7 { + if shift >= 64 { + return ErrIntOverflowProvider + } + if iNdEx >= l { + return io.ErrUnexpectedEOF + } + b := dAtA[iNdEx] + iNdEx++ + byteLen |= int(b&0x7F) << shift + if b < 0x80 { + break + } + } + if byteLen < 0 { + return ErrInvalidLengthProvider + } + postIndex := iNdEx + byteLen + if postIndex < 0 { + return ErrInvalidLengthProvider + } + if postIndex > l { + return io.ErrUnexpectedEOF + } + m.GenesisHash = append(m.GenesisHash[:0], dAtA[iNdEx:postIndex]...) + if m.GenesisHash == nil { + m.GenesisHash = []byte{} + } + iNdEx = postIndex + case 3: + if wireType != 2 { + return fmt.Errorf("proto: wrong wireType = %d for field BinaryHash", wireType) + } + var byteLen int + for shift := uint(0); ; shift += 7 { + if shift >= 64 { + return ErrIntOverflowProvider + } + if iNdEx >= l { + return io.ErrUnexpectedEOF + } + b := dAtA[iNdEx] + iNdEx++ + byteLen |= int(b&0x7F) << shift + if b < 0x80 { + break + } + } + if byteLen < 0 { + return ErrInvalidLengthProvider + } + postIndex := iNdEx + byteLen + if postIndex < 0 { + return ErrInvalidLengthProvider + } + if postIndex > l { + return io.ErrUnexpectedEOF + } + m.BinaryHash = append(m.BinaryHash[:0], dAtA[iNdEx:postIndex]...) + if m.BinaryHash == nil { + m.BinaryHash = []byte{} + } + iNdEx = postIndex + case 4: + if wireType != 2 { + return fmt.Errorf("proto: wrong wireType = %d for field SpawnTime", wireType) + } + var msglen int + for shift := uint(0); ; shift += 7 { + if shift >= 64 { + return ErrIntOverflowProvider + } + if iNdEx >= l { + return io.ErrUnexpectedEOF + } + b := dAtA[iNdEx] + iNdEx++ + msglen |= int(b&0x7F) << shift + if b < 0x80 { + break + } + } + if msglen < 0 { + return ErrInvalidLengthProvider + } + postIndex := iNdEx + msglen + if postIndex < 0 { + return ErrInvalidLengthProvider + } + if postIndex > l { + return io.ErrUnexpectedEOF + } + if err := github_com_cosmos_gogoproto_types.StdTimeUnmarshal(&m.SpawnTime, dAtA[iNdEx:postIndex]); err != nil { + return err + } + iNdEx = postIndex + case 5: + if wireType != 2 { + return fmt.Errorf("proto: wrong wireType = %d for field UnbondingPeriod", wireType) + } + var msglen int + for shift := uint(0); ; shift += 7 { + if shift >= 64 { + return ErrIntOverflowProvider + } + if iNdEx >= l { + return io.ErrUnexpectedEOF + } + b := dAtA[iNdEx] + iNdEx++ + msglen |= int(b&0x7F) << shift + if b < 0x80 { + break + } + } + if msglen < 0 { + return ErrInvalidLengthProvider + } + postIndex := iNdEx + msglen + if postIndex < 0 { + return ErrInvalidLengthProvider + } + if postIndex > l { + return io.ErrUnexpectedEOF + } + if err := github_com_cosmos_gogoproto_types.StdDurationUnmarshal(&m.UnbondingPeriod, dAtA[iNdEx:postIndex]); err != nil { + return err + } + iNdEx = postIndex + case 6: + if wireType != 2 { + return fmt.Errorf("proto: wrong wireType = %d for field CcvTimeoutPeriod", wireType) + } + var msglen int + for shift := uint(0); ; shift += 7 { + if shift >= 64 { + return ErrIntOverflowProvider + } + if iNdEx >= l { + return io.ErrUnexpectedEOF + } + b := dAtA[iNdEx] + iNdEx++ + msglen |= int(b&0x7F) << shift + if b < 0x80 { + break + } + } + if msglen < 0 { + return ErrInvalidLengthProvider + } + postIndex := iNdEx + msglen + if postIndex < 0 { + return ErrInvalidLengthProvider + } + if postIndex > l { + return io.ErrUnexpectedEOF + } + if err := github_com_cosmos_gogoproto_types.StdDurationUnmarshal(&m.CcvTimeoutPeriod, dAtA[iNdEx:postIndex]); err != nil { + return err + } + iNdEx = postIndex + case 7: + if wireType != 2 { + return fmt.Errorf("proto: wrong wireType = %d for field TransferTimeoutPeriod", wireType) + } + var msglen int + for shift := uint(0); ; shift += 7 { + if shift >= 64 { + return ErrIntOverflowProvider + } + if iNdEx >= l { + return io.ErrUnexpectedEOF + } + b := dAtA[iNdEx] + iNdEx++ + msglen |= int(b&0x7F) << shift + if b < 0x80 { + break + } + } + if msglen < 0 { + return ErrInvalidLengthProvider + } + postIndex := iNdEx + msglen + if postIndex < 0 { + return ErrInvalidLengthProvider + } + if postIndex > l { + return io.ErrUnexpectedEOF + } + if err := github_com_cosmos_gogoproto_types.StdDurationUnmarshal(&m.TransferTimeoutPeriod, dAtA[iNdEx:postIndex]); err != nil { + return err + } + iNdEx = postIndex + case 8: + if wireType != 2 { + return fmt.Errorf("proto: wrong wireType = %d for field ConsumerRedistributionFraction", wireType) + } + var stringLen uint64 + for shift := uint(0); ; shift += 7 { + if shift >= 64 { + return ErrIntOverflowProvider + } + 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 ErrInvalidLengthProvider + } + postIndex := iNdEx + intStringLen + if postIndex < 0 { + return ErrInvalidLengthProvider + } + if postIndex > l { + return io.ErrUnexpectedEOF + } + m.ConsumerRedistributionFraction = string(dAtA[iNdEx:postIndex]) + iNdEx = postIndex + case 9: + if wireType != 0 { + return fmt.Errorf("proto: wrong wireType = %d for field BlocksPerDistributionTransmission", wireType) + } + m.BlocksPerDistributionTransmission = 0 + for shift := uint(0); ; shift += 7 { + if shift >= 64 { + return ErrIntOverflowProvider + } + if iNdEx >= l { + return io.ErrUnexpectedEOF + } + b := dAtA[iNdEx] + iNdEx++ + m.BlocksPerDistributionTransmission |= int64(b&0x7F) << shift + if b < 0x80 { + break + } + } + case 10: + if wireType != 0 { + return fmt.Errorf("proto: wrong wireType = %d for field HistoricalEntries", wireType) + } + m.HistoricalEntries = 0 + for shift := uint(0); ; shift += 7 { + if shift >= 64 { + return ErrIntOverflowProvider + } + if iNdEx >= l { + return io.ErrUnexpectedEOF + } + b := dAtA[iNdEx] + iNdEx++ + m.HistoricalEntries |= int64(b&0x7F) << shift + if b < 0x80 { + break + } + } + case 11: + if wireType != 2 { + return fmt.Errorf("proto: wrong wireType = %d for field DistributionTransmissionChannel", wireType) + } + var stringLen uint64 + for shift := uint(0); ; shift += 7 { + if shift >= 64 { + return ErrIntOverflowProvider + } + 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 ErrInvalidLengthProvider + } + postIndex := iNdEx + intStringLen + if postIndex < 0 { + return ErrInvalidLengthProvider + } + if postIndex > l { + return io.ErrUnexpectedEOF + } + m.DistributionTransmissionChannel = string(dAtA[iNdEx:postIndex]) + iNdEx = postIndex + default: + iNdEx = preIndex + skippy, err := skipProvider(dAtA[iNdEx:]) + if err != nil { + return err + } + if (skippy < 0) || (iNdEx+skippy) < 0 { + return ErrInvalidLengthProvider + } + if (iNdEx + skippy) > l { + return io.ErrUnexpectedEOF + } + iNdEx += skippy + } + } + + if iNdEx > l { + return io.ErrUnexpectedEOF + } + return nil +} +func (m *PowerShapingParameters) 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 ErrIntOverflowProvider + } + 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: PowerShapingParameters: wiretype end group for non-group") + } + if fieldNum <= 0 { + return fmt.Errorf("proto: PowerShapingParameters: illegal tag %d (wire type %d)", fieldNum, wire) + } + switch fieldNum { + case 1: + if wireType != 0 { + return fmt.Errorf("proto: wrong wireType = %d for field Top_N", wireType) + } + m.Top_N = 0 + for shift := uint(0); ; shift += 7 { + if shift >= 64 { + return ErrIntOverflowProvider + } + if iNdEx >= l { + return io.ErrUnexpectedEOF + } + b := dAtA[iNdEx] + iNdEx++ + m.Top_N |= uint32(b&0x7F) << shift + if b < 0x80 { + break + } + } + case 2: + if wireType != 0 { + return fmt.Errorf("proto: wrong wireType = %d for field ValidatorsPowerCap", wireType) + } + m.ValidatorsPowerCap = 0 + for shift := uint(0); ; shift += 7 { + if shift >= 64 { + return ErrIntOverflowProvider + } + if iNdEx >= l { + return io.ErrUnexpectedEOF + } + b := dAtA[iNdEx] + iNdEx++ + m.ValidatorsPowerCap |= uint32(b&0x7F) << shift + if b < 0x80 { + break + } + } + case 3: + if wireType != 0 { + return fmt.Errorf("proto: wrong wireType = %d for field ValidatorSetCap", wireType) + } + m.ValidatorSetCap = 0 + for shift := uint(0); ; shift += 7 { + if shift >= 64 { + return ErrIntOverflowProvider + } + if iNdEx >= l { + return io.ErrUnexpectedEOF + } + b := dAtA[iNdEx] + iNdEx++ + m.ValidatorSetCap |= uint32(b&0x7F) << shift + if b < 0x80 { + break + } + } + case 4: + if wireType != 2 { + return fmt.Errorf("proto: wrong wireType = %d for field Allowlist", wireType) + } + var stringLen uint64 + for shift := uint(0); ; shift += 7 { + if shift >= 64 { + return ErrIntOverflowProvider + } + 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 ErrInvalidLengthProvider + } + postIndex := iNdEx + intStringLen + if postIndex < 0 { + return ErrInvalidLengthProvider + } + if postIndex > l { + return io.ErrUnexpectedEOF + } + m.Allowlist = append(m.Allowlist, string(dAtA[iNdEx:postIndex])) + iNdEx = postIndex + case 5: + if wireType != 2 { + return fmt.Errorf("proto: wrong wireType = %d for field Denylist", wireType) + } + var stringLen uint64 + for shift := uint(0); ; shift += 7 { + if shift >= 64 { + return ErrIntOverflowProvider + } + 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 ErrInvalidLengthProvider + } + postIndex := iNdEx + intStringLen + if postIndex < 0 { + return ErrInvalidLengthProvider + } + if postIndex > l { + return io.ErrUnexpectedEOF + } + m.Denylist = append(m.Denylist, string(dAtA[iNdEx:postIndex])) + iNdEx = postIndex + case 6: + if wireType != 0 { + return fmt.Errorf("proto: wrong wireType = %d for field MinStake", wireType) + } + m.MinStake = 0 + for shift := uint(0); ; shift += 7 { + if shift >= 64 { + return ErrIntOverflowProvider + } + if iNdEx >= l { + return io.ErrUnexpectedEOF + } + b := dAtA[iNdEx] + iNdEx++ + m.MinStake |= uint64(b&0x7F) << shift + if b < 0x80 { + break + } + } + case 7: + if wireType != 0 { + return fmt.Errorf("proto: wrong wireType = %d for field AllowInactiveVals", wireType) + } + var v int + for shift := uint(0); ; shift += 7 { + if shift >= 64 { + return ErrIntOverflowProvider + } + if iNdEx >= l { + return io.ErrUnexpectedEOF + } + b := dAtA[iNdEx] + iNdEx++ + v |= int(b&0x7F) << shift + if b < 0x80 { + break + } + } + m.AllowInactiveVals = bool(v != 0) + default: + iNdEx = preIndex + skippy, err := skipProvider(dAtA[iNdEx:]) + if err != nil { + return err + } + if (skippy < 0) || (iNdEx+skippy) < 0 { + return ErrInvalidLengthProvider + } + if (iNdEx + skippy) > l { + return io.ErrUnexpectedEOF + } + iNdEx += skippy + } + } + + if iNdEx > l { + return io.ErrUnexpectedEOF + } + return nil +} +func (m *ConsumerIds) 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 ErrIntOverflowProvider + } + 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: ConsumerIds: wiretype end group for non-group") + } + if fieldNum <= 0 { + return fmt.Errorf("proto: ConsumerIds: illegal tag %d (wire type %d)", fieldNum, wire) + } + switch fieldNum { + case 1: + if wireType != 2 { + return fmt.Errorf("proto: wrong wireType = %d for field Ids", wireType) + } + var stringLen uint64 + for shift := uint(0); ; shift += 7 { + if shift >= 64 { + return ErrIntOverflowProvider + } + 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 ErrInvalidLengthProvider + } + postIndex := iNdEx + intStringLen + if postIndex < 0 { + return ErrInvalidLengthProvider + } + if postIndex > l { + return io.ErrUnexpectedEOF + } + m.Ids = append(m.Ids, string(dAtA[iNdEx:postIndex])) + iNdEx = postIndex + default: + iNdEx = preIndex + skippy, err := skipProvider(dAtA[iNdEx:]) + if err != nil { + return err + } + if (skippy < 0) || (iNdEx+skippy) < 0 { + return ErrInvalidLengthProvider + } + if (iNdEx + skippy) > l { + return io.ErrUnexpectedEOF + } + iNdEx += skippy + } + } + + if iNdEx > l { + return io.ErrUnexpectedEOF + } + return nil +} func skipProvider(dAtA []byte) (n int, err error) { l := len(dAtA) iNdEx := 0 diff --git a/x/ccv/provider/types/query.pb.go b/x/ccv/provider/types/query.pb.go index 10a78b00c7..fa0c569918 100644 --- a/x/ccv/provider/types/query.pb.go +++ b/x/ccv/provider/types/query.pb.go @@ -9,6 +9,7 @@ import ( fmt "fmt" crypto "github.com/cometbft/cometbft/proto/tendermint/crypto" _ "github.com/cosmos/cosmos-proto" + types1 "github.com/cosmos/cosmos-sdk/x/staking/types" _ "github.com/cosmos/gogoproto/gogoproto" grpc1 "github.com/cosmos/gogoproto/grpc" proto "github.com/cosmos/gogoproto/proto" @@ -38,7 +39,7 @@ var _ = time.Kitchen const _ = proto.GoGoProtoPackageIsVersion3 // please upgrade the proto package type QueryConsumerGenesisRequest struct { - ChainId string `protobuf:"bytes,1,opt,name=chain_id,json=chainId,proto3" json:"chain_id,omitempty"` + ConsumerId string `protobuf:"bytes,1,opt,name=consumer_id,json=consumerId,proto3" json:"consumer_id,omitempty"` } func (m *QueryConsumerGenesisRequest) Reset() { *m = QueryConsumerGenesisRequest{} } @@ -74,9 +75,9 @@ func (m *QueryConsumerGenesisRequest) XXX_DiscardUnknown() { var xxx_messageInfo_QueryConsumerGenesisRequest proto.InternalMessageInfo -func (m *QueryConsumerGenesisRequest) GetChainId() string { +func (m *QueryConsumerGenesisRequest) GetConsumerId() string { if m != nil { - return m.ChainId + return m.ConsumerId } return "" } @@ -126,6 +127,12 @@ func (m *QueryConsumerGenesisResponse) GetGenesisState() types.ConsumerGenesisSt } type QueryConsumerChainsRequest struct { + // The phase of the consumer chains returned (optional) + // Registered=1|Initialized=2|Launched=3|Stopped=4|Deleted=5 + Phase ConsumerPhase `protobuf:"varint,1,opt,name=phase,proto3,enum=interchain_security.ccv.provider.v1.ConsumerPhase" json:"phase,omitempty"` + // The limit of consumer chains returned (optional) + // default is 100 + Limit int32 `protobuf:"varint,2,opt,name=limit,proto3" json:"limit,omitempty"` } func (m *QueryConsumerChainsRequest) Reset() { *m = QueryConsumerChainsRequest{} } @@ -161,6 +168,20 @@ func (m *QueryConsumerChainsRequest) XXX_DiscardUnknown() { var xxx_messageInfo_QueryConsumerChainsRequest proto.InternalMessageInfo +func (m *QueryConsumerChainsRequest) GetPhase() ConsumerPhase { + if m != nil { + return m.Phase + } + return CONSUMER_PHASE_UNSPECIFIED +} + +func (m *QueryConsumerChainsRequest) GetLimit() int32 { + if m != nil { + return m.Limit + } + return 0 +} + type QueryConsumerChainsResponse struct { Chains []*Chain `protobuf:"bytes,1,rep,name=chains,proto3" json:"chains,omitempty"` } @@ -205,179 +226,10 @@ func (m *QueryConsumerChainsResponse) GetChains() []*Chain { return nil } -type QueryConsumerChainStartProposalsRequest struct { -} - -func (m *QueryConsumerChainStartProposalsRequest) Reset() { - *m = QueryConsumerChainStartProposalsRequest{} -} -func (m *QueryConsumerChainStartProposalsRequest) String() string { return proto.CompactTextString(m) } -func (*QueryConsumerChainStartProposalsRequest) ProtoMessage() {} -func (*QueryConsumerChainStartProposalsRequest) Descriptor() ([]byte, []int) { - return fileDescriptor_422512d7b7586cd7, []int{4} -} -func (m *QueryConsumerChainStartProposalsRequest) XXX_Unmarshal(b []byte) error { - return m.Unmarshal(b) -} -func (m *QueryConsumerChainStartProposalsRequest) XXX_Marshal(b []byte, deterministic bool) ([]byte, error) { - if deterministic { - return xxx_messageInfo_QueryConsumerChainStartProposalsRequest.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 *QueryConsumerChainStartProposalsRequest) XXX_Merge(src proto.Message) { - xxx_messageInfo_QueryConsumerChainStartProposalsRequest.Merge(m, src) -} -func (m *QueryConsumerChainStartProposalsRequest) XXX_Size() int { - return m.Size() -} -func (m *QueryConsumerChainStartProposalsRequest) XXX_DiscardUnknown() { - xxx_messageInfo_QueryConsumerChainStartProposalsRequest.DiscardUnknown(m) -} - -var xxx_messageInfo_QueryConsumerChainStartProposalsRequest proto.InternalMessageInfo - -type QueryConsumerChainStartProposalsResponse struct { - Proposals *ConsumerAdditionProposals `protobuf:"bytes,1,opt,name=proposals,proto3" json:"proposals,omitempty"` -} - -func (m *QueryConsumerChainStartProposalsResponse) Reset() { - *m = QueryConsumerChainStartProposalsResponse{} -} -func (m *QueryConsumerChainStartProposalsResponse) String() string { return proto.CompactTextString(m) } -func (*QueryConsumerChainStartProposalsResponse) ProtoMessage() {} -func (*QueryConsumerChainStartProposalsResponse) Descriptor() ([]byte, []int) { - return fileDescriptor_422512d7b7586cd7, []int{5} -} -func (m *QueryConsumerChainStartProposalsResponse) XXX_Unmarshal(b []byte) error { - return m.Unmarshal(b) -} -func (m *QueryConsumerChainStartProposalsResponse) XXX_Marshal(b []byte, deterministic bool) ([]byte, error) { - if deterministic { - return xxx_messageInfo_QueryConsumerChainStartProposalsResponse.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 *QueryConsumerChainStartProposalsResponse) XXX_Merge(src proto.Message) { - xxx_messageInfo_QueryConsumerChainStartProposalsResponse.Merge(m, src) -} -func (m *QueryConsumerChainStartProposalsResponse) XXX_Size() int { - return m.Size() -} -func (m *QueryConsumerChainStartProposalsResponse) XXX_DiscardUnknown() { - xxx_messageInfo_QueryConsumerChainStartProposalsResponse.DiscardUnknown(m) -} - -var xxx_messageInfo_QueryConsumerChainStartProposalsResponse proto.InternalMessageInfo - -func (m *QueryConsumerChainStartProposalsResponse) GetProposals() *ConsumerAdditionProposals { - if m != nil { - return m.Proposals - } - return nil -} - -type QueryConsumerChainStopProposalsRequest struct { -} - -func (m *QueryConsumerChainStopProposalsRequest) Reset() { - *m = QueryConsumerChainStopProposalsRequest{} -} -func (m *QueryConsumerChainStopProposalsRequest) String() string { return proto.CompactTextString(m) } -func (*QueryConsumerChainStopProposalsRequest) ProtoMessage() {} -func (*QueryConsumerChainStopProposalsRequest) Descriptor() ([]byte, []int) { - return fileDescriptor_422512d7b7586cd7, []int{6} -} -func (m *QueryConsumerChainStopProposalsRequest) XXX_Unmarshal(b []byte) error { - return m.Unmarshal(b) -} -func (m *QueryConsumerChainStopProposalsRequest) XXX_Marshal(b []byte, deterministic bool) ([]byte, error) { - if deterministic { - return xxx_messageInfo_QueryConsumerChainStopProposalsRequest.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 *QueryConsumerChainStopProposalsRequest) XXX_Merge(src proto.Message) { - xxx_messageInfo_QueryConsumerChainStopProposalsRequest.Merge(m, src) -} -func (m *QueryConsumerChainStopProposalsRequest) XXX_Size() int { - return m.Size() -} -func (m *QueryConsumerChainStopProposalsRequest) XXX_DiscardUnknown() { - xxx_messageInfo_QueryConsumerChainStopProposalsRequest.DiscardUnknown(m) -} - -var xxx_messageInfo_QueryConsumerChainStopProposalsRequest proto.InternalMessageInfo - -type QueryConsumerChainStopProposalsResponse struct { - Proposals *ConsumerRemovalProposals `protobuf:"bytes,1,opt,name=proposals,proto3" json:"proposals,omitempty"` -} - -func (m *QueryConsumerChainStopProposalsResponse) Reset() { - *m = QueryConsumerChainStopProposalsResponse{} -} -func (m *QueryConsumerChainStopProposalsResponse) String() string { return proto.CompactTextString(m) } -func (*QueryConsumerChainStopProposalsResponse) ProtoMessage() {} -func (*QueryConsumerChainStopProposalsResponse) Descriptor() ([]byte, []int) { - return fileDescriptor_422512d7b7586cd7, []int{7} -} -func (m *QueryConsumerChainStopProposalsResponse) XXX_Unmarshal(b []byte) error { - return m.Unmarshal(b) -} -func (m *QueryConsumerChainStopProposalsResponse) XXX_Marshal(b []byte, deterministic bool) ([]byte, error) { - if deterministic { - return xxx_messageInfo_QueryConsumerChainStopProposalsResponse.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 *QueryConsumerChainStopProposalsResponse) XXX_Merge(src proto.Message) { - xxx_messageInfo_QueryConsumerChainStopProposalsResponse.Merge(m, src) -} -func (m *QueryConsumerChainStopProposalsResponse) XXX_Size() int { - return m.Size() -} -func (m *QueryConsumerChainStopProposalsResponse) XXX_DiscardUnknown() { - xxx_messageInfo_QueryConsumerChainStopProposalsResponse.DiscardUnknown(m) -} - -var xxx_messageInfo_QueryConsumerChainStopProposalsResponse proto.InternalMessageInfo - -func (m *QueryConsumerChainStopProposalsResponse) GetProposals() *ConsumerRemovalProposals { - if m != nil { - return m.Proposals - } - return nil -} - type Chain struct { ChainId string `protobuf:"bytes,1,opt,name=chain_id,json=chainId,proto3" json:"chain_id,omitempty"` ClientId string `protobuf:"bytes,2,opt,name=client_id,json=clientId,proto3" json:"client_id,omitempty"` - // If chain with `chainID` is a Top-N chain, i.e., enforces at least one validator to validate chain `chainID` - Top_N uint32 `protobuf:"varint,3,opt,name=top_N,json=topN,proto3" json:"top_N,omitempty"` + Top_N uint32 `protobuf:"varint,3,opt,name=top_N,json=topN,proto3" json:"top_N,omitempty"` // If the chain is a Top-N chain, this is the minimum power required to be in the top N. // Otherwise, this is -1. MinPowerInTop_N int64 `protobuf:"varint,4,opt,name=min_power_in_top_N,json=minPowerInTopN,proto3" json:"min_power_in_top_N,omitempty"` @@ -391,17 +243,22 @@ type Chain struct { Allowlist []string `protobuf:"bytes,7,rep,name=allowlist,proto3" json:"allowlist,omitempty"` // Corresponds to a list of provider consensus addresses of validators that CANNOT validate the consumer chain. Denylist []string `protobuf:"bytes,8,rep,name=denylist,proto3" json:"denylist,omitempty"` + // The phase the consumer chain + Phase string `protobuf:"bytes,9,opt,name=phase,proto3" json:"phase,omitempty"` + // The metadata of the consumer chain + Metadata ConsumerMetadata `protobuf:"bytes,10,opt,name=metadata,proto3" json:"metadata"` // Corresponds to the minimal amount of (provider chain) stake required to validate on the consumer chain. - MinStake uint64 `protobuf:"varint,9,opt,name=min_stake,json=minStake,proto3" json:"min_stake,omitempty"` + MinStake uint64 `protobuf:"varint,11,opt,name=min_stake,json=minStake,proto3" json:"min_stake,omitempty"` // Corresponds to whether inactive validators are allowed to validate the consumer chain. - AllowInactiveVals bool `protobuf:"varint,10,opt,name=allow_inactive_vals,json=allowInactiveVals,proto3" json:"allow_inactive_vals,omitempty"` + AllowInactiveVals bool `protobuf:"varint,12,opt,name=allow_inactive_vals,json=allowInactiveVals,proto3" json:"allow_inactive_vals,omitempty"` + ConsumerId string `protobuf:"bytes,13,opt,name=consumer_id,json=consumerId,proto3" json:"consumer_id,omitempty"` } func (m *Chain) Reset() { *m = Chain{} } func (m *Chain) String() string { return proto.CompactTextString(m) } func (*Chain) ProtoMessage() {} func (*Chain) Descriptor() ([]byte, []int) { - return fileDescriptor_422512d7b7586cd7, []int{8} + return fileDescriptor_422512d7b7586cd7, []int{4} } func (m *Chain) XXX_Unmarshal(b []byte) error { return m.Unmarshal(b) @@ -486,6 +343,20 @@ func (m *Chain) GetDenylist() []string { return nil } +func (m *Chain) GetPhase() string { + if m != nil { + return m.Phase + } + return "" +} + +func (m *Chain) GetMetadata() ConsumerMetadata { + if m != nil { + return m.Metadata + } + return ConsumerMetadata{} +} + func (m *Chain) GetMinStake() uint64 { if m != nil { return m.MinStake @@ -500,18 +371,25 @@ func (m *Chain) GetAllowInactiveVals() bool { return false } +func (m *Chain) GetConsumerId() string { + if m != nil { + return m.ConsumerId + } + return "" +} + type QueryValidatorConsumerAddrRequest struct { - // The id of the consumer chain - ChainId string `protobuf:"bytes,1,opt,name=chain_id,json=chainId,proto3" json:"chain_id,omitempty"` // The consensus address of the validator on the provider chain - ProviderAddress string `protobuf:"bytes,2,opt,name=provider_address,json=providerAddress,proto3" json:"provider_address,omitempty" yaml:"address"` + ProviderAddress string `protobuf:"bytes,1,opt,name=provider_address,json=providerAddress,proto3" json:"provider_address,omitempty" yaml:"address"` + // The id of the consumer chain + ConsumerId string `protobuf:"bytes,2,opt,name=consumer_id,json=consumerId,proto3" json:"consumer_id,omitempty"` } func (m *QueryValidatorConsumerAddrRequest) Reset() { *m = QueryValidatorConsumerAddrRequest{} } func (m *QueryValidatorConsumerAddrRequest) String() string { return proto.CompactTextString(m) } func (*QueryValidatorConsumerAddrRequest) ProtoMessage() {} func (*QueryValidatorConsumerAddrRequest) Descriptor() ([]byte, []int) { - return fileDescriptor_422512d7b7586cd7, []int{9} + return fileDescriptor_422512d7b7586cd7, []int{5} } func (m *QueryValidatorConsumerAddrRequest) XXX_Unmarshal(b []byte) error { return m.Unmarshal(b) @@ -549,7 +427,7 @@ func (m *QueryValidatorConsumerAddrResponse) Reset() { *m = QueryValidat func (m *QueryValidatorConsumerAddrResponse) String() string { return proto.CompactTextString(m) } func (*QueryValidatorConsumerAddrResponse) ProtoMessage() {} func (*QueryValidatorConsumerAddrResponse) Descriptor() ([]byte, []int) { - return fileDescriptor_422512d7b7586cd7, []int{10} + return fileDescriptor_422512d7b7586cd7, []int{6} } func (m *QueryValidatorConsumerAddrResponse) XXX_Unmarshal(b []byte) error { return m.Unmarshal(b) @@ -586,17 +464,17 @@ func (m *QueryValidatorConsumerAddrResponse) GetConsumerAddress() string { } type QueryValidatorProviderAddrRequest struct { - // The id of the provider chain - ChainId string `protobuf:"bytes,1,opt,name=chain_id,json=chainId,proto3" json:"chain_id,omitempty"` // The consensus address of the validator on the consumer chain - ConsumerAddress string `protobuf:"bytes,2,opt,name=consumer_address,json=consumerAddress,proto3" json:"consumer_address,omitempty" yaml:"address"` + ConsumerAddress string `protobuf:"bytes,1,opt,name=consumer_address,json=consumerAddress,proto3" json:"consumer_address,omitempty" yaml:"address"` + // The id of the consumer chain + ConsumerId string `protobuf:"bytes,2,opt,name=consumer_id,json=consumerId,proto3" json:"consumer_id,omitempty"` } func (m *QueryValidatorProviderAddrRequest) Reset() { *m = QueryValidatorProviderAddrRequest{} } func (m *QueryValidatorProviderAddrRequest) String() string { return proto.CompactTextString(m) } func (*QueryValidatorProviderAddrRequest) ProtoMessage() {} func (*QueryValidatorProviderAddrRequest) Descriptor() ([]byte, []int) { - return fileDescriptor_422512d7b7586cd7, []int{11} + return fileDescriptor_422512d7b7586cd7, []int{7} } func (m *QueryValidatorProviderAddrRequest) XXX_Unmarshal(b []byte) error { return m.Unmarshal(b) @@ -634,7 +512,7 @@ func (m *QueryValidatorProviderAddrResponse) Reset() { *m = QueryValidat func (m *QueryValidatorProviderAddrResponse) String() string { return proto.CompactTextString(m) } func (*QueryValidatorProviderAddrResponse) ProtoMessage() {} func (*QueryValidatorProviderAddrResponse) Descriptor() ([]byte, []int) { - return fileDescriptor_422512d7b7586cd7, []int{12} + return fileDescriptor_422512d7b7586cd7, []int{8} } func (m *QueryValidatorProviderAddrResponse) XXX_Unmarshal(b []byte) error { return m.Unmarshal(b) @@ -677,7 +555,7 @@ func (m *QueryThrottleStateRequest) Reset() { *m = QueryThrottleStateReq func (m *QueryThrottleStateRequest) String() string { return proto.CompactTextString(m) } func (*QueryThrottleStateRequest) ProtoMessage() {} func (*QueryThrottleStateRequest) Descriptor() ([]byte, []int) { - return fileDescriptor_422512d7b7586cd7, []int{13} + return fileDescriptor_422512d7b7586cd7, []int{9} } func (m *QueryThrottleStateRequest) XXX_Unmarshal(b []byte) error { return m.Unmarshal(b) @@ -721,7 +599,7 @@ func (m *QueryThrottleStateResponse) Reset() { *m = QueryThrottleStateRe func (m *QueryThrottleStateResponse) String() string { return proto.CompactTextString(m) } func (*QueryThrottleStateResponse) ProtoMessage() {} func (*QueryThrottleStateResponse) Descriptor() ([]byte, []int) { - return fileDescriptor_422512d7b7586cd7, []int{14} + return fileDescriptor_422512d7b7586cd7, []int{10} } func (m *QueryThrottleStateResponse) XXX_Unmarshal(b []byte) error { return m.Unmarshal(b) @@ -782,7 +660,7 @@ func (m *QueryRegisteredConsumerRewardDenomsRequest) String() string { } func (*QueryRegisteredConsumerRewardDenomsRequest) ProtoMessage() {} func (*QueryRegisteredConsumerRewardDenomsRequest) Descriptor() ([]byte, []int) { - return fileDescriptor_422512d7b7586cd7, []int{15} + return fileDescriptor_422512d7b7586cd7, []int{11} } func (m *QueryRegisteredConsumerRewardDenomsRequest) XXX_Unmarshal(b []byte) error { return m.Unmarshal(b) @@ -823,7 +701,7 @@ func (m *QueryRegisteredConsumerRewardDenomsResponse) String() string { } func (*QueryRegisteredConsumerRewardDenomsResponse) ProtoMessage() {} func (*QueryRegisteredConsumerRewardDenomsResponse) Descriptor() ([]byte, []int) { - return fileDescriptor_422512d7b7586cd7, []int{16} + return fileDescriptor_422512d7b7586cd7, []int{12} } func (m *QueryRegisteredConsumerRewardDenomsResponse) XXX_Unmarshal(b []byte) error { return m.Unmarshal(b) @@ -859,159 +737,27 @@ func (m *QueryRegisteredConsumerRewardDenomsResponse) GetDenoms() []string { return nil } -type QueryProposedChainIDsRequest struct { -} - -func (m *QueryProposedChainIDsRequest) Reset() { *m = QueryProposedChainIDsRequest{} } -func (m *QueryProposedChainIDsRequest) String() string { return proto.CompactTextString(m) } -func (*QueryProposedChainIDsRequest) ProtoMessage() {} -func (*QueryProposedChainIDsRequest) Descriptor() ([]byte, []int) { - return fileDescriptor_422512d7b7586cd7, []int{17} -} -func (m *QueryProposedChainIDsRequest) XXX_Unmarshal(b []byte) error { - return m.Unmarshal(b) -} -func (m *QueryProposedChainIDsRequest) XXX_Marshal(b []byte, deterministic bool) ([]byte, error) { - if deterministic { - return xxx_messageInfo_QueryProposedChainIDsRequest.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 *QueryProposedChainIDsRequest) XXX_Merge(src proto.Message) { - xxx_messageInfo_QueryProposedChainIDsRequest.Merge(m, src) -} -func (m *QueryProposedChainIDsRequest) XXX_Size() int { - return m.Size() -} -func (m *QueryProposedChainIDsRequest) XXX_DiscardUnknown() { - xxx_messageInfo_QueryProposedChainIDsRequest.DiscardUnknown(m) -} - -var xxx_messageInfo_QueryProposedChainIDsRequest proto.InternalMessageInfo - -type QueryProposedChainIDsResponse struct { - ProposedChains []ProposedChain `protobuf:"bytes,1,rep,name=proposedChains,proto3" json:"proposedChains"` -} - -func (m *QueryProposedChainIDsResponse) Reset() { *m = QueryProposedChainIDsResponse{} } -func (m *QueryProposedChainIDsResponse) String() string { return proto.CompactTextString(m) } -func (*QueryProposedChainIDsResponse) ProtoMessage() {} -func (*QueryProposedChainIDsResponse) Descriptor() ([]byte, []int) { - return fileDescriptor_422512d7b7586cd7, []int{18} -} -func (m *QueryProposedChainIDsResponse) XXX_Unmarshal(b []byte) error { - return m.Unmarshal(b) -} -func (m *QueryProposedChainIDsResponse) XXX_Marshal(b []byte, deterministic bool) ([]byte, error) { - if deterministic { - return xxx_messageInfo_QueryProposedChainIDsResponse.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 *QueryProposedChainIDsResponse) XXX_Merge(src proto.Message) { - xxx_messageInfo_QueryProposedChainIDsResponse.Merge(m, src) -} -func (m *QueryProposedChainIDsResponse) XXX_Size() int { - return m.Size() -} -func (m *QueryProposedChainIDsResponse) XXX_DiscardUnknown() { - xxx_messageInfo_QueryProposedChainIDsResponse.DiscardUnknown(m) -} - -var xxx_messageInfo_QueryProposedChainIDsResponse proto.InternalMessageInfo - -func (m *QueryProposedChainIDsResponse) GetProposedChains() []ProposedChain { - if m != nil { - return m.ProposedChains - } - return nil -} - -type ProposedChain struct { - ChainID string `protobuf:"bytes,1,opt,name=chainID,proto3" json:"chainID,omitempty"` - ProposalID uint64 `protobuf:"varint,2,opt,name=proposalID,proto3" json:"proposalID,omitempty"` -} - -func (m *ProposedChain) Reset() { *m = ProposedChain{} } -func (m *ProposedChain) String() string { return proto.CompactTextString(m) } -func (*ProposedChain) ProtoMessage() {} -func (*ProposedChain) Descriptor() ([]byte, []int) { - return fileDescriptor_422512d7b7586cd7, []int{19} -} -func (m *ProposedChain) XXX_Unmarshal(b []byte) error { - return m.Unmarshal(b) -} -func (m *ProposedChain) XXX_Marshal(b []byte, deterministic bool) ([]byte, error) { - if deterministic { - return xxx_messageInfo_ProposedChain.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 *ProposedChain) XXX_Merge(src proto.Message) { - xxx_messageInfo_ProposedChain.Merge(m, src) -} -func (m *ProposedChain) XXX_Size() int { - return m.Size() -} -func (m *ProposedChain) XXX_DiscardUnknown() { - xxx_messageInfo_ProposedChain.DiscardUnknown(m) -} - -var xxx_messageInfo_ProposedChain proto.InternalMessageInfo - -func (m *ProposedChain) GetChainID() string { - if m != nil { - return m.ChainID - } - return "" -} - -func (m *ProposedChain) GetProposalID() uint64 { - if m != nil { - return m.ProposalID - } - return 0 -} - -type QueryAllPairsValConAddrByConsumerChainIDRequest struct { +type QueryAllPairsValConsAddrByConsumerRequest struct { // The id of the consumer chain - ChainId string `protobuf:"bytes,1,opt,name=chain_id,json=chainId,proto3" json:"chain_id,omitempty"` + ConsumerId string `protobuf:"bytes,1,opt,name=consumer_id,json=consumerId,proto3" json:"consumer_id,omitempty"` } -func (m *QueryAllPairsValConAddrByConsumerChainIDRequest) Reset() { - *m = QueryAllPairsValConAddrByConsumerChainIDRequest{} +func (m *QueryAllPairsValConsAddrByConsumerRequest) Reset() { + *m = QueryAllPairsValConsAddrByConsumerRequest{} } -func (m *QueryAllPairsValConAddrByConsumerChainIDRequest) String() string { +func (m *QueryAllPairsValConsAddrByConsumerRequest) String() string { return proto.CompactTextString(m) } -func (*QueryAllPairsValConAddrByConsumerChainIDRequest) ProtoMessage() {} -func (*QueryAllPairsValConAddrByConsumerChainIDRequest) Descriptor() ([]byte, []int) { - return fileDescriptor_422512d7b7586cd7, []int{20} +func (*QueryAllPairsValConsAddrByConsumerRequest) ProtoMessage() {} +func (*QueryAllPairsValConsAddrByConsumerRequest) Descriptor() ([]byte, []int) { + return fileDescriptor_422512d7b7586cd7, []int{13} } -func (m *QueryAllPairsValConAddrByConsumerChainIDRequest) XXX_Unmarshal(b []byte) error { +func (m *QueryAllPairsValConsAddrByConsumerRequest) XXX_Unmarshal(b []byte) error { return m.Unmarshal(b) } -func (m *QueryAllPairsValConAddrByConsumerChainIDRequest) XXX_Marshal(b []byte, deterministic bool) ([]byte, error) { +func (m *QueryAllPairsValConsAddrByConsumerRequest) XXX_Marshal(b []byte, deterministic bool) ([]byte, error) { if deterministic { - return xxx_messageInfo_QueryAllPairsValConAddrByConsumerChainIDRequest.Marshal(b, m, deterministic) + return xxx_messageInfo_QueryAllPairsValConsAddrByConsumerRequest.Marshal(b, m, deterministic) } else { b = b[:cap(b)] n, err := m.MarshalToSizedBuffer(b) @@ -1021,45 +767,45 @@ func (m *QueryAllPairsValConAddrByConsumerChainIDRequest) XXX_Marshal(b []byte, return b[:n], nil } } -func (m *QueryAllPairsValConAddrByConsumerChainIDRequest) XXX_Merge(src proto.Message) { - xxx_messageInfo_QueryAllPairsValConAddrByConsumerChainIDRequest.Merge(m, src) +func (m *QueryAllPairsValConsAddrByConsumerRequest) XXX_Merge(src proto.Message) { + xxx_messageInfo_QueryAllPairsValConsAddrByConsumerRequest.Merge(m, src) } -func (m *QueryAllPairsValConAddrByConsumerChainIDRequest) XXX_Size() int { +func (m *QueryAllPairsValConsAddrByConsumerRequest) XXX_Size() int { return m.Size() } -func (m *QueryAllPairsValConAddrByConsumerChainIDRequest) XXX_DiscardUnknown() { - xxx_messageInfo_QueryAllPairsValConAddrByConsumerChainIDRequest.DiscardUnknown(m) +func (m *QueryAllPairsValConsAddrByConsumerRequest) XXX_DiscardUnknown() { + xxx_messageInfo_QueryAllPairsValConsAddrByConsumerRequest.DiscardUnknown(m) } -var xxx_messageInfo_QueryAllPairsValConAddrByConsumerChainIDRequest proto.InternalMessageInfo +var xxx_messageInfo_QueryAllPairsValConsAddrByConsumerRequest proto.InternalMessageInfo -func (m *QueryAllPairsValConAddrByConsumerChainIDRequest) GetChainId() string { +func (m *QueryAllPairsValConsAddrByConsumerRequest) GetConsumerId() string { if m != nil { - return m.ChainId + return m.ConsumerId } return "" } -type QueryAllPairsValConAddrByConsumerChainIDResponse struct { +type QueryAllPairsValConsAddrByConsumerResponse struct { PairValConAddr []*PairValConAddrProviderAndConsumer `protobuf:"bytes,1,rep,name=pair_val_con_addr,json=pairValConAddr,proto3" json:"pair_val_con_addr,omitempty"` } -func (m *QueryAllPairsValConAddrByConsumerChainIDResponse) Reset() { - *m = QueryAllPairsValConAddrByConsumerChainIDResponse{} +func (m *QueryAllPairsValConsAddrByConsumerResponse) Reset() { + *m = QueryAllPairsValConsAddrByConsumerResponse{} } -func (m *QueryAllPairsValConAddrByConsumerChainIDResponse) String() string { +func (m *QueryAllPairsValConsAddrByConsumerResponse) String() string { return proto.CompactTextString(m) } -func (*QueryAllPairsValConAddrByConsumerChainIDResponse) ProtoMessage() {} -func (*QueryAllPairsValConAddrByConsumerChainIDResponse) Descriptor() ([]byte, []int) { - return fileDescriptor_422512d7b7586cd7, []int{21} +func (*QueryAllPairsValConsAddrByConsumerResponse) ProtoMessage() {} +func (*QueryAllPairsValConsAddrByConsumerResponse) Descriptor() ([]byte, []int) { + return fileDescriptor_422512d7b7586cd7, []int{14} } -func (m *QueryAllPairsValConAddrByConsumerChainIDResponse) XXX_Unmarshal(b []byte) error { +func (m *QueryAllPairsValConsAddrByConsumerResponse) XXX_Unmarshal(b []byte) error { return m.Unmarshal(b) } -func (m *QueryAllPairsValConAddrByConsumerChainIDResponse) XXX_Marshal(b []byte, deterministic bool) ([]byte, error) { +func (m *QueryAllPairsValConsAddrByConsumerResponse) XXX_Marshal(b []byte, deterministic bool) ([]byte, error) { if deterministic { - return xxx_messageInfo_QueryAllPairsValConAddrByConsumerChainIDResponse.Marshal(b, m, deterministic) + return xxx_messageInfo_QueryAllPairsValConsAddrByConsumerResponse.Marshal(b, m, deterministic) } else { b = b[:cap(b)] n, err := m.MarshalToSizedBuffer(b) @@ -1069,19 +815,19 @@ func (m *QueryAllPairsValConAddrByConsumerChainIDResponse) XXX_Marshal(b []byte, return b[:n], nil } } -func (m *QueryAllPairsValConAddrByConsumerChainIDResponse) XXX_Merge(src proto.Message) { - xxx_messageInfo_QueryAllPairsValConAddrByConsumerChainIDResponse.Merge(m, src) +func (m *QueryAllPairsValConsAddrByConsumerResponse) XXX_Merge(src proto.Message) { + xxx_messageInfo_QueryAllPairsValConsAddrByConsumerResponse.Merge(m, src) } -func (m *QueryAllPairsValConAddrByConsumerChainIDResponse) XXX_Size() int { +func (m *QueryAllPairsValConsAddrByConsumerResponse) XXX_Size() int { return m.Size() } -func (m *QueryAllPairsValConAddrByConsumerChainIDResponse) XXX_DiscardUnknown() { - xxx_messageInfo_QueryAllPairsValConAddrByConsumerChainIDResponse.DiscardUnknown(m) +func (m *QueryAllPairsValConsAddrByConsumerResponse) XXX_DiscardUnknown() { + xxx_messageInfo_QueryAllPairsValConsAddrByConsumerResponse.DiscardUnknown(m) } -var xxx_messageInfo_QueryAllPairsValConAddrByConsumerChainIDResponse proto.InternalMessageInfo +var xxx_messageInfo_QueryAllPairsValConsAddrByConsumerResponse proto.InternalMessageInfo -func (m *QueryAllPairsValConAddrByConsumerChainIDResponse) GetPairValConAddr() []*PairValConAddrProviderAndConsumer { +func (m *QueryAllPairsValConsAddrByConsumerResponse) GetPairValConAddr() []*PairValConAddrProviderAndConsumer { if m != nil { return m.PairValConAddr } @@ -1100,7 +846,7 @@ func (m *PairValConAddrProviderAndConsumer) Reset() { *m = PairValConAdd func (m *PairValConAddrProviderAndConsumer) String() string { return proto.CompactTextString(m) } func (*PairValConAddrProviderAndConsumer) ProtoMessage() {} func (*PairValConAddrProviderAndConsumer) Descriptor() ([]byte, []int) { - return fileDescriptor_422512d7b7586cd7, []int{22} + return fileDescriptor_422512d7b7586cd7, []int{15} } func (m *PairValConAddrProviderAndConsumer) XXX_Unmarshal(b []byte) error { return m.Unmarshal(b) @@ -1157,7 +903,7 @@ func (m *QueryParamsRequest) Reset() { *m = QueryParamsRequest{} } func (m *QueryParamsRequest) String() string { return proto.CompactTextString(m) } func (*QueryParamsRequest) ProtoMessage() {} func (*QueryParamsRequest) Descriptor() ([]byte, []int) { - return fileDescriptor_422512d7b7586cd7, []int{23} + return fileDescriptor_422512d7b7586cd7, []int{16} } func (m *QueryParamsRequest) XXX_Unmarshal(b []byte) error { return m.Unmarshal(b) @@ -1194,7 +940,7 @@ func (m *QueryParamsResponse) Reset() { *m = QueryParamsResponse{} } func (m *QueryParamsResponse) String() string { return proto.CompactTextString(m) } func (*QueryParamsResponse) ProtoMessage() {} func (*QueryParamsResponse) Descriptor() ([]byte, []int) { - return fileDescriptor_422512d7b7586cd7, []int{24} + return fileDescriptor_422512d7b7586cd7, []int{17} } func (m *QueryParamsResponse) XXX_Unmarshal(b []byte) error { return m.Unmarshal(b) @@ -1231,7 +977,7 @@ func (m *QueryParamsResponse) GetParams() Params { } type QueryConsumerChainOptedInValidatorsRequest struct { - ChainId string `protobuf:"bytes,1,opt,name=chain_id,json=chainId,proto3" json:"chain_id,omitempty"` + ConsumerId string `protobuf:"bytes,1,opt,name=consumer_id,json=consumerId,proto3" json:"consumer_id,omitempty"` } func (m *QueryConsumerChainOptedInValidatorsRequest) Reset() { @@ -1242,7 +988,7 @@ func (m *QueryConsumerChainOptedInValidatorsRequest) String() string { } func (*QueryConsumerChainOptedInValidatorsRequest) ProtoMessage() {} func (*QueryConsumerChainOptedInValidatorsRequest) Descriptor() ([]byte, []int) { - return fileDescriptor_422512d7b7586cd7, []int{25} + return fileDescriptor_422512d7b7586cd7, []int{18} } func (m *QueryConsumerChainOptedInValidatorsRequest) XXX_Unmarshal(b []byte) error { return m.Unmarshal(b) @@ -1271,9 +1017,9 @@ func (m *QueryConsumerChainOptedInValidatorsRequest) XXX_DiscardUnknown() { var xxx_messageInfo_QueryConsumerChainOptedInValidatorsRequest proto.InternalMessageInfo -func (m *QueryConsumerChainOptedInValidatorsRequest) GetChainId() string { +func (m *QueryConsumerChainOptedInValidatorsRequest) GetConsumerId() string { if m != nil { - return m.ChainId + return m.ConsumerId } return "" } @@ -1291,7 +1037,7 @@ func (m *QueryConsumerChainOptedInValidatorsResponse) String() string { } func (*QueryConsumerChainOptedInValidatorsResponse) ProtoMessage() {} func (*QueryConsumerChainOptedInValidatorsResponse) Descriptor() ([]byte, []int) { - return fileDescriptor_422512d7b7586cd7, []int{26} + return fileDescriptor_422512d7b7586cd7, []int{19} } func (m *QueryConsumerChainOptedInValidatorsResponse) XXX_Unmarshal(b []byte) error { return m.Unmarshal(b) @@ -1328,14 +1074,14 @@ func (m *QueryConsumerChainOptedInValidatorsResponse) GetValidatorsProviderAddre } type QueryConsumerValidatorsRequest struct { - ChainId string `protobuf:"bytes,1,opt,name=chain_id,json=chainId,proto3" json:"chain_id,omitempty"` + ConsumerId string `protobuf:"bytes,1,opt,name=consumer_id,json=consumerId,proto3" json:"consumer_id,omitempty"` } func (m *QueryConsumerValidatorsRequest) Reset() { *m = QueryConsumerValidatorsRequest{} } func (m *QueryConsumerValidatorsRequest) String() string { return proto.CompactTextString(m) } func (*QueryConsumerValidatorsRequest) ProtoMessage() {} func (*QueryConsumerValidatorsRequest) Descriptor() ([]byte, []int) { - return fileDescriptor_422512d7b7586cd7, []int{27} + return fileDescriptor_422512d7b7586cd7, []int{20} } func (m *QueryConsumerValidatorsRequest) XXX_Unmarshal(b []byte) error { return m.Unmarshal(b) @@ -1364,9 +1110,9 @@ func (m *QueryConsumerValidatorsRequest) XXX_DiscardUnknown() { var xxx_messageInfo_QueryConsumerValidatorsRequest proto.InternalMessageInfo -func (m *QueryConsumerValidatorsRequest) GetChainId() string { +func (m *QueryConsumerValidatorsRequest) GetConsumerId() string { if m != nil { - return m.ChainId + return m.ConsumerId } return "" } @@ -1376,17 +1122,37 @@ type QueryConsumerValidatorsValidator struct { ProviderAddress string `protobuf:"bytes,1,opt,name=provider_address,json=providerAddress,proto3" json:"provider_address,omitempty" yaml:"address"` // The consumer public key of the validator used on the consumer chain ConsumerKey *crypto.PublicKey `protobuf:"bytes,2,opt,name=consumer_key,json=consumerKey,proto3" json:"consumer_key,omitempty"` + // [DEPRECATED] use `consumer_power` instead + Power int64 `protobuf:"varint,3,opt,name=power,proto3" json:"power,omitempty"` // Deprecated: Do not use. + // [DEPRECATED] use `consumer_commission_rate` instead + Rate cosmossdk_io_math.LegacyDec `protobuf:"bytes,4,opt,name=rate,proto3,customtype=cosmossdk.io/math.LegacyDec" json:"rate"` // Deprecated: Do not use. // The power of the validator used on the consumer chain - Power int64 `protobuf:"varint,3,opt,name=power,proto3" json:"power,omitempty"` + ConsumerPower int64 `protobuf:"varint,5,opt,name=consumer_power,json=consumerPower,proto3" json:"consumer_power,omitempty"` // The rate to charge delegators on the consumer chain, as a fraction - Rate cosmossdk_io_math.LegacyDec `protobuf:"bytes,4,opt,name=rate,proto3,customtype=cosmossdk.io/math.LegacyDec" json:"rate"` + ConsumerCommissionRate cosmossdk_io_math.LegacyDec `protobuf:"bytes,6,opt,name=consumer_commission_rate,json=consumerCommissionRate,proto3,customtype=cosmossdk.io/math.LegacyDec" json:"consumer_commission_rate"` + // The rate to charge delegators on the provider chain, as a fraction + ProviderCommissionRate cosmossdk_io_math.LegacyDec `protobuf:"bytes,7,opt,name=provider_commission_rate,json=providerCommissionRate,proto3,customtype=cosmossdk.io/math.LegacyDec" json:"provider_commission_rate"` + // description defines the description terms for the validator + Description types1.Description `protobuf:"bytes,8,opt,name=description,proto3" json:"description"` + // provider_operator_address defines the address of the validator's operator + ProviderOperatorAddress string `protobuf:"bytes,9,opt,name=provider_operator_address,json=providerOperatorAddress,proto3" json:"provider_operator_address,omitempty"` + // jailed defined whether the validator has been jailed from bonded status or not. + Jailed bool `protobuf:"varint,10,opt,name=jailed,proto3" json:"jailed,omitempty"` + // status is the validator status (bonded/unbonding/unbonded). + Status types1.BondStatus `protobuf:"varint,11,opt,name=status,proto3,enum=cosmos.staking.v1beta1.BondStatus" json:"status,omitempty"` + // provider_tokens defines the delegated tokens (incl. self-delegation). + ProviderTokens cosmossdk_io_math.Int `protobuf:"bytes,12,opt,name=provider_tokens,json=providerTokens,proto3,customtype=cosmossdk.io/math.Int" json:"provider_tokens"` + // The power of the validator used on the provider chain + ProviderPower int64 `protobuf:"varint,13,opt,name=provider_power,json=providerPower,proto3" json:"provider_power,omitempty"` + // validates_current_epoch defines whether the validator has to validate for the current epoch or not + ValidatesCurrentEpoch bool `protobuf:"varint,14,opt,name=validates_current_epoch,json=validatesCurrentEpoch,proto3" json:"validates_current_epoch,omitempty"` } func (m *QueryConsumerValidatorsValidator) Reset() { *m = QueryConsumerValidatorsValidator{} } func (m *QueryConsumerValidatorsValidator) String() string { return proto.CompactTextString(m) } func (*QueryConsumerValidatorsValidator) ProtoMessage() {} func (*QueryConsumerValidatorsValidator) Descriptor() ([]byte, []int) { - return fileDescriptor_422512d7b7586cd7, []int{28} + return fileDescriptor_422512d7b7586cd7, []int{21} } func (m *QueryConsumerValidatorsValidator) XXX_Unmarshal(b []byte) error { return m.Unmarshal(b) @@ -1429,6 +1195,7 @@ func (m *QueryConsumerValidatorsValidator) GetConsumerKey() *crypto.PublicKey { return nil } +// Deprecated: Do not use. func (m *QueryConsumerValidatorsValidator) GetPower() int64 { if m != nil { return m.Power @@ -1436,15 +1203,64 @@ func (m *QueryConsumerValidatorsValidator) GetPower() int64 { return 0 } -type QueryConsumerValidatorsResponse struct { - Validators []*QueryConsumerValidatorsValidator `protobuf:"bytes,1,rep,name=validators,proto3" json:"validators,omitempty"` +func (m *QueryConsumerValidatorsValidator) GetConsumerPower() int64 { + if m != nil { + return m.ConsumerPower + } + return 0 +} + +func (m *QueryConsumerValidatorsValidator) GetDescription() types1.Description { + if m != nil { + return m.Description + } + return types1.Description{} +} + +func (m *QueryConsumerValidatorsValidator) GetProviderOperatorAddress() string { + if m != nil { + return m.ProviderOperatorAddress + } + return "" +} + +func (m *QueryConsumerValidatorsValidator) GetJailed() bool { + if m != nil { + return m.Jailed + } + return false +} + +func (m *QueryConsumerValidatorsValidator) GetStatus() types1.BondStatus { + if m != nil { + return m.Status + } + return types1.Unspecified +} + +func (m *QueryConsumerValidatorsValidator) GetProviderPower() int64 { + if m != nil { + return m.ProviderPower + } + return 0 +} + +func (m *QueryConsumerValidatorsValidator) GetValidatesCurrentEpoch() bool { + if m != nil { + return m.ValidatesCurrentEpoch + } + return false +} + +type QueryConsumerValidatorsResponse struct { + Validators []*QueryConsumerValidatorsValidator `protobuf:"bytes,1,rep,name=validators,proto3" json:"validators,omitempty"` } func (m *QueryConsumerValidatorsResponse) Reset() { *m = QueryConsumerValidatorsResponse{} } func (m *QueryConsumerValidatorsResponse) String() string { return proto.CompactTextString(m) } func (*QueryConsumerValidatorsResponse) ProtoMessage() {} func (*QueryConsumerValidatorsResponse) Descriptor() ([]byte, []int) { - return fileDescriptor_422512d7b7586cd7, []int{29} + return fileDescriptor_422512d7b7586cd7, []int{22} } func (m *QueryConsumerValidatorsResponse) XXX_Unmarshal(b []byte) error { return m.Unmarshal(b) @@ -1493,7 +1309,7 @@ func (m *QueryConsumerChainsValidatorHasToValidateRequest) String() string { } func (*QueryConsumerChainsValidatorHasToValidateRequest) ProtoMessage() {} func (*QueryConsumerChainsValidatorHasToValidateRequest) Descriptor() ([]byte, []int) { - return fileDescriptor_422512d7b7586cd7, []int{30} + return fileDescriptor_422512d7b7586cd7, []int{23} } func (m *QueryConsumerChainsValidatorHasToValidateRequest) XXX_Unmarshal(b []byte) error { return m.Unmarshal(b) @@ -1530,7 +1346,7 @@ func (m *QueryConsumerChainsValidatorHasToValidateRequest) GetProviderAddress() } type QueryConsumerChainsValidatorHasToValidateResponse struct { - ConsumerChainIds []string `protobuf:"bytes,1,rep,name=consumer_chain_ids,json=consumerChainIds,proto3" json:"consumer_chain_ids,omitempty"` + ConsumerIds []string `protobuf:"bytes,1,rep,name=consumer_ids,json=consumerIds,proto3" json:"consumer_ids,omitempty"` } func (m *QueryConsumerChainsValidatorHasToValidateResponse) Reset() { @@ -1541,7 +1357,7 @@ func (m *QueryConsumerChainsValidatorHasToValidateResponse) String() string { } func (*QueryConsumerChainsValidatorHasToValidateResponse) ProtoMessage() {} func (*QueryConsumerChainsValidatorHasToValidateResponse) Descriptor() ([]byte, []int) { - return fileDescriptor_422512d7b7586cd7, []int{31} + return fileDescriptor_422512d7b7586cd7, []int{24} } func (m *QueryConsumerChainsValidatorHasToValidateResponse) XXX_Unmarshal(b []byte) error { return m.Unmarshal(b) @@ -1570,15 +1386,15 @@ func (m *QueryConsumerChainsValidatorHasToValidateResponse) XXX_DiscardUnknown() var xxx_messageInfo_QueryConsumerChainsValidatorHasToValidateResponse proto.InternalMessageInfo -func (m *QueryConsumerChainsValidatorHasToValidateResponse) GetConsumerChainIds() []string { +func (m *QueryConsumerChainsValidatorHasToValidateResponse) GetConsumerIds() []string { if m != nil { - return m.ConsumerChainIds + return m.ConsumerIds } return nil } type QueryValidatorConsumerCommissionRateRequest struct { - ChainId string `protobuf:"bytes,1,opt,name=chain_id,json=chainId,proto3" json:"chain_id,omitempty"` + ConsumerId string `protobuf:"bytes,1,opt,name=consumer_id,json=consumerId,proto3" json:"consumer_id,omitempty"` // The consensus address of the validator on the provider chain ProviderAddress string `protobuf:"bytes,2,opt,name=provider_address,json=providerAddress,proto3" json:"provider_address,omitempty" yaml:"address"` } @@ -1591,7 +1407,7 @@ func (m *QueryValidatorConsumerCommissionRateRequest) String() string { } func (*QueryValidatorConsumerCommissionRateRequest) ProtoMessage() {} func (*QueryValidatorConsumerCommissionRateRequest) Descriptor() ([]byte, []int) { - return fileDescriptor_422512d7b7586cd7, []int{32} + return fileDescriptor_422512d7b7586cd7, []int{25} } func (m *QueryValidatorConsumerCommissionRateRequest) XXX_Unmarshal(b []byte) error { return m.Unmarshal(b) @@ -1620,9 +1436,9 @@ func (m *QueryValidatorConsumerCommissionRateRequest) XXX_DiscardUnknown() { var xxx_messageInfo_QueryValidatorConsumerCommissionRateRequest proto.InternalMessageInfo -func (m *QueryValidatorConsumerCommissionRateRequest) GetChainId() string { +func (m *QueryValidatorConsumerCommissionRateRequest) GetConsumerId() string { if m != nil { - return m.ChainId + return m.ConsumerId } return "" } @@ -1647,7 +1463,7 @@ func (m *QueryValidatorConsumerCommissionRateResponse) String() string { } func (*QueryValidatorConsumerCommissionRateResponse) ProtoMessage() {} func (*QueryValidatorConsumerCommissionRateResponse) Descriptor() ([]byte, []int) { - return fileDescriptor_422512d7b7586cd7, []int{33} + return fileDescriptor_422512d7b7586cd7, []int{26} } func (m *QueryValidatorConsumerCommissionRateResponse) XXX_Unmarshal(b []byte) error { return m.Unmarshal(b) @@ -1683,7 +1499,7 @@ func (m *QueryBlocksUntilNextEpochRequest) Reset() { *m = QueryBlocksUnt func (m *QueryBlocksUntilNextEpochRequest) String() string { return proto.CompactTextString(m) } func (*QueryBlocksUntilNextEpochRequest) ProtoMessage() {} func (*QueryBlocksUntilNextEpochRequest) Descriptor() ([]byte, []int) { - return fileDescriptor_422512d7b7586cd7, []int{34} + return fileDescriptor_422512d7b7586cd7, []int{27} } func (m *QueryBlocksUntilNextEpochRequest) XXX_Unmarshal(b []byte) error { return m.Unmarshal(b) @@ -1721,7 +1537,7 @@ func (m *QueryBlocksUntilNextEpochResponse) Reset() { *m = QueryBlocksUn func (m *QueryBlocksUntilNextEpochResponse) String() string { return proto.CompactTextString(m) } func (*QueryBlocksUntilNextEpochResponse) ProtoMessage() {} func (*QueryBlocksUntilNextEpochResponse) Descriptor() ([]byte, []int) { - return fileDescriptor_422512d7b7586cd7, []int{35} + return fileDescriptor_422512d7b7586cd7, []int{28} } func (m *QueryBlocksUntilNextEpochResponse) XXX_Unmarshal(b []byte) error { return m.Unmarshal(b) @@ -1757,15 +1573,230 @@ func (m *QueryBlocksUntilNextEpochResponse) GetBlocksUntilNextEpoch() uint64 { return 0 } +type QueryConsumerIdFromClientIdRequest struct { + // the client id (on the provider) that is tracking the consumer chain + // the client id can be found from the consumer chain by querying (i.e., `query ccvconsumer provider-info`) + ClientId string `protobuf:"bytes,1,opt,name=client_id,json=clientId,proto3" json:"client_id,omitempty"` +} + +func (m *QueryConsumerIdFromClientIdRequest) Reset() { *m = QueryConsumerIdFromClientIdRequest{} } +func (m *QueryConsumerIdFromClientIdRequest) String() string { return proto.CompactTextString(m) } +func (*QueryConsumerIdFromClientIdRequest) ProtoMessage() {} +func (*QueryConsumerIdFromClientIdRequest) Descriptor() ([]byte, []int) { + return fileDescriptor_422512d7b7586cd7, []int{29} +} +func (m *QueryConsumerIdFromClientIdRequest) XXX_Unmarshal(b []byte) error { + return m.Unmarshal(b) +} +func (m *QueryConsumerIdFromClientIdRequest) XXX_Marshal(b []byte, deterministic bool) ([]byte, error) { + if deterministic { + return xxx_messageInfo_QueryConsumerIdFromClientIdRequest.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 *QueryConsumerIdFromClientIdRequest) XXX_Merge(src proto.Message) { + xxx_messageInfo_QueryConsumerIdFromClientIdRequest.Merge(m, src) +} +func (m *QueryConsumerIdFromClientIdRequest) XXX_Size() int { + return m.Size() +} +func (m *QueryConsumerIdFromClientIdRequest) XXX_DiscardUnknown() { + xxx_messageInfo_QueryConsumerIdFromClientIdRequest.DiscardUnknown(m) +} + +var xxx_messageInfo_QueryConsumerIdFromClientIdRequest proto.InternalMessageInfo + +func (m *QueryConsumerIdFromClientIdRequest) GetClientId() string { + if m != nil { + return m.ClientId + } + return "" +} + +type QueryConsumerIdFromClientIdResponse struct { + // the consumer id of the chain associated with this client id + ConsumerId string `protobuf:"bytes,1,opt,name=consumer_id,json=consumerId,proto3" json:"consumer_id,omitempty"` +} + +func (m *QueryConsumerIdFromClientIdResponse) Reset() { *m = QueryConsumerIdFromClientIdResponse{} } +func (m *QueryConsumerIdFromClientIdResponse) String() string { return proto.CompactTextString(m) } +func (*QueryConsumerIdFromClientIdResponse) ProtoMessage() {} +func (*QueryConsumerIdFromClientIdResponse) Descriptor() ([]byte, []int) { + return fileDescriptor_422512d7b7586cd7, []int{30} +} +func (m *QueryConsumerIdFromClientIdResponse) XXX_Unmarshal(b []byte) error { + return m.Unmarshal(b) +} +func (m *QueryConsumerIdFromClientIdResponse) XXX_Marshal(b []byte, deterministic bool) ([]byte, error) { + if deterministic { + return xxx_messageInfo_QueryConsumerIdFromClientIdResponse.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 *QueryConsumerIdFromClientIdResponse) XXX_Merge(src proto.Message) { + xxx_messageInfo_QueryConsumerIdFromClientIdResponse.Merge(m, src) +} +func (m *QueryConsumerIdFromClientIdResponse) XXX_Size() int { + return m.Size() +} +func (m *QueryConsumerIdFromClientIdResponse) XXX_DiscardUnknown() { + xxx_messageInfo_QueryConsumerIdFromClientIdResponse.DiscardUnknown(m) +} + +var xxx_messageInfo_QueryConsumerIdFromClientIdResponse proto.InternalMessageInfo + +func (m *QueryConsumerIdFromClientIdResponse) GetConsumerId() string { + if m != nil { + return m.ConsumerId + } + return "" +} + +type QueryConsumerChainRequest struct { + ConsumerId string `protobuf:"bytes,1,opt,name=consumer_id,json=consumerId,proto3" json:"consumer_id,omitempty"` +} + +func (m *QueryConsumerChainRequest) Reset() { *m = QueryConsumerChainRequest{} } +func (m *QueryConsumerChainRequest) String() string { return proto.CompactTextString(m) } +func (*QueryConsumerChainRequest) ProtoMessage() {} +func (*QueryConsumerChainRequest) Descriptor() ([]byte, []int) { + return fileDescriptor_422512d7b7586cd7, []int{31} +} +func (m *QueryConsumerChainRequest) XXX_Unmarshal(b []byte) error { + return m.Unmarshal(b) +} +func (m *QueryConsumerChainRequest) XXX_Marshal(b []byte, deterministic bool) ([]byte, error) { + if deterministic { + return xxx_messageInfo_QueryConsumerChainRequest.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 *QueryConsumerChainRequest) XXX_Merge(src proto.Message) { + xxx_messageInfo_QueryConsumerChainRequest.Merge(m, src) +} +func (m *QueryConsumerChainRequest) XXX_Size() int { + return m.Size() +} +func (m *QueryConsumerChainRequest) XXX_DiscardUnknown() { + xxx_messageInfo_QueryConsumerChainRequest.DiscardUnknown(m) +} + +var xxx_messageInfo_QueryConsumerChainRequest proto.InternalMessageInfo + +func (m *QueryConsumerChainRequest) GetConsumerId() string { + if m != nil { + return m.ConsumerId + } + return "" +} + +type QueryConsumerChainResponse struct { + ChainId string `protobuf:"bytes,1,opt,name=chain_id,json=chainId,proto3" json:"chain_id,omitempty"` + OwnerAddress string `protobuf:"bytes,2,opt,name=owner_address,json=ownerAddress,proto3" json:"owner_address,omitempty"` + Phase string `protobuf:"bytes,3,opt,name=phase,proto3" json:"phase,omitempty"` + Metadata ConsumerMetadata `protobuf:"bytes,4,opt,name=metadata,proto3" json:"metadata"` + InitParams *ConsumerInitializationParameters `protobuf:"bytes,5,opt,name=init_params,json=initParams,proto3" json:"init_params,omitempty"` + PowerShapingParams *PowerShapingParameters `protobuf:"bytes,6,opt,name=power_shaping_params,json=powerShapingParams,proto3" json:"power_shaping_params,omitempty"` +} + +func (m *QueryConsumerChainResponse) Reset() { *m = QueryConsumerChainResponse{} } +func (m *QueryConsumerChainResponse) String() string { return proto.CompactTextString(m) } +func (*QueryConsumerChainResponse) ProtoMessage() {} +func (*QueryConsumerChainResponse) Descriptor() ([]byte, []int) { + return fileDescriptor_422512d7b7586cd7, []int{32} +} +func (m *QueryConsumerChainResponse) XXX_Unmarshal(b []byte) error { + return m.Unmarshal(b) +} +func (m *QueryConsumerChainResponse) XXX_Marshal(b []byte, deterministic bool) ([]byte, error) { + if deterministic { + return xxx_messageInfo_QueryConsumerChainResponse.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 *QueryConsumerChainResponse) XXX_Merge(src proto.Message) { + xxx_messageInfo_QueryConsumerChainResponse.Merge(m, src) +} +func (m *QueryConsumerChainResponse) XXX_Size() int { + return m.Size() +} +func (m *QueryConsumerChainResponse) XXX_DiscardUnknown() { + xxx_messageInfo_QueryConsumerChainResponse.DiscardUnknown(m) +} + +var xxx_messageInfo_QueryConsumerChainResponse proto.InternalMessageInfo + +func (m *QueryConsumerChainResponse) GetChainId() string { + if m != nil { + return m.ChainId + } + return "" +} + +func (m *QueryConsumerChainResponse) GetOwnerAddress() string { + if m != nil { + return m.OwnerAddress + } + return "" +} + +func (m *QueryConsumerChainResponse) GetPhase() string { + if m != nil { + return m.Phase + } + return "" +} + +func (m *QueryConsumerChainResponse) GetMetadata() ConsumerMetadata { + if m != nil { + return m.Metadata + } + return ConsumerMetadata{} +} + +func (m *QueryConsumerChainResponse) GetInitParams() *ConsumerInitializationParameters { + if m != nil { + return m.InitParams + } + return nil +} + +func (m *QueryConsumerChainResponse) GetPowerShapingParams() *PowerShapingParameters { + if m != nil { + return m.PowerShapingParams + } + return nil +} + func init() { proto.RegisterType((*QueryConsumerGenesisRequest)(nil), "interchain_security.ccv.provider.v1.QueryConsumerGenesisRequest") proto.RegisterType((*QueryConsumerGenesisResponse)(nil), "interchain_security.ccv.provider.v1.QueryConsumerGenesisResponse") proto.RegisterType((*QueryConsumerChainsRequest)(nil), "interchain_security.ccv.provider.v1.QueryConsumerChainsRequest") proto.RegisterType((*QueryConsumerChainsResponse)(nil), "interchain_security.ccv.provider.v1.QueryConsumerChainsResponse") - proto.RegisterType((*QueryConsumerChainStartProposalsRequest)(nil), "interchain_security.ccv.provider.v1.QueryConsumerChainStartProposalsRequest") - proto.RegisterType((*QueryConsumerChainStartProposalsResponse)(nil), "interchain_security.ccv.provider.v1.QueryConsumerChainStartProposalsResponse") - proto.RegisterType((*QueryConsumerChainStopProposalsRequest)(nil), "interchain_security.ccv.provider.v1.QueryConsumerChainStopProposalsRequest") - proto.RegisterType((*QueryConsumerChainStopProposalsResponse)(nil), "interchain_security.ccv.provider.v1.QueryConsumerChainStopProposalsResponse") proto.RegisterType((*Chain)(nil), "interchain_security.ccv.provider.v1.Chain") proto.RegisterType((*QueryValidatorConsumerAddrRequest)(nil), "interchain_security.ccv.provider.v1.QueryValidatorConsumerAddrRequest") proto.RegisterType((*QueryValidatorConsumerAddrResponse)(nil), "interchain_security.ccv.provider.v1.QueryValidatorConsumerAddrResponse") @@ -1775,11 +1806,8 @@ func init() { proto.RegisterType((*QueryThrottleStateResponse)(nil), "interchain_security.ccv.provider.v1.QueryThrottleStateResponse") proto.RegisterType((*QueryRegisteredConsumerRewardDenomsRequest)(nil), "interchain_security.ccv.provider.v1.QueryRegisteredConsumerRewardDenomsRequest") proto.RegisterType((*QueryRegisteredConsumerRewardDenomsResponse)(nil), "interchain_security.ccv.provider.v1.QueryRegisteredConsumerRewardDenomsResponse") - proto.RegisterType((*QueryProposedChainIDsRequest)(nil), "interchain_security.ccv.provider.v1.QueryProposedChainIDsRequest") - proto.RegisterType((*QueryProposedChainIDsResponse)(nil), "interchain_security.ccv.provider.v1.QueryProposedChainIDsResponse") - proto.RegisterType((*ProposedChain)(nil), "interchain_security.ccv.provider.v1.ProposedChain") - proto.RegisterType((*QueryAllPairsValConAddrByConsumerChainIDRequest)(nil), "interchain_security.ccv.provider.v1.QueryAllPairsValConAddrByConsumerChainIDRequest") - proto.RegisterType((*QueryAllPairsValConAddrByConsumerChainIDResponse)(nil), "interchain_security.ccv.provider.v1.QueryAllPairsValConAddrByConsumerChainIDResponse") + proto.RegisterType((*QueryAllPairsValConsAddrByConsumerRequest)(nil), "interchain_security.ccv.provider.v1.QueryAllPairsValConsAddrByConsumerRequest") + proto.RegisterType((*QueryAllPairsValConsAddrByConsumerResponse)(nil), "interchain_security.ccv.provider.v1.QueryAllPairsValConsAddrByConsumerResponse") proto.RegisterType((*PairValConAddrProviderAndConsumer)(nil), "interchain_security.ccv.provider.v1.PairValConAddrProviderAndConsumer") proto.RegisterType((*QueryParamsRequest)(nil), "interchain_security.ccv.provider.v1.QueryParamsRequest") proto.RegisterType((*QueryParamsResponse)(nil), "interchain_security.ccv.provider.v1.QueryParamsResponse") @@ -1794,6 +1822,10 @@ func init() { proto.RegisterType((*QueryValidatorConsumerCommissionRateResponse)(nil), "interchain_security.ccv.provider.v1.QueryValidatorConsumerCommissionRateResponse") proto.RegisterType((*QueryBlocksUntilNextEpochRequest)(nil), "interchain_security.ccv.provider.v1.QueryBlocksUntilNextEpochRequest") proto.RegisterType((*QueryBlocksUntilNextEpochResponse)(nil), "interchain_security.ccv.provider.v1.QueryBlocksUntilNextEpochResponse") + proto.RegisterType((*QueryConsumerIdFromClientIdRequest)(nil), "interchain_security.ccv.provider.v1.QueryConsumerIdFromClientIdRequest") + proto.RegisterType((*QueryConsumerIdFromClientIdResponse)(nil), "interchain_security.ccv.provider.v1.QueryConsumerIdFromClientIdResponse") + proto.RegisterType((*QueryConsumerChainRequest)(nil), "interchain_security.ccv.provider.v1.QueryConsumerChainRequest") + proto.RegisterType((*QueryConsumerChainResponse)(nil), "interchain_security.ccv.provider.v1.QueryConsumerChainResponse") } func init() { @@ -1801,136 +1833,157 @@ func init() { } var fileDescriptor_422512d7b7586cd7 = []byte{ - // 2049 bytes of a gzipped FileDescriptorProto - 0x1f, 0x8b, 0x08, 0x00, 0x00, 0x00, 0x00, 0x00, 0x02, 0xff, 0xb4, 0x59, 0xcd, 0x6f, 0xdc, 0xc6, - 0x15, 0x17, 0x57, 0x1f, 0x91, 0x46, 0xb1, 0x1d, 0x8f, 0xd5, 0x78, 0x4d, 0x29, 0xbb, 0x0a, 0xdd, - 0x8f, 0xb5, 0xec, 0x92, 0x92, 0x0c, 0x23, 0x8e, 0x5d, 0x47, 0xd6, 0x4a, 0xb2, 0xb3, 0xb0, 0x63, - 0x2b, 0xb4, 0xec, 0x16, 0x6e, 0x51, 0x9a, 0x22, 0xa7, 0x2b, 0x42, 0x5c, 0x0e, 0xc5, 0x19, 0xad, - 0xbd, 0x30, 0x72, 0x48, 0x0f, 0x6d, 0x8e, 0x41, 0x3f, 0xee, 0xb9, 0xf4, 0xd8, 0x1e, 0x7a, 0xe8, - 0xdf, 0x90, 0x5b, 0x53, 0xe4, 0x52, 0xf4, 0xe0, 0x16, 0x72, 0x0b, 0x14, 0x05, 0x5a, 0xb4, 0x46, - 0xaf, 0x05, 0x0a, 0x0e, 0x87, 0x5c, 0x72, 0x97, 0xbb, 0x4b, 0xee, 0x2a, 0xb7, 0xe5, 0xcc, 0x7b, - 0xbf, 0x79, 0xef, 0xcd, 0x9b, 0x37, 0xef, 0x37, 0x0b, 0x14, 0xcb, 0xa1, 0xc8, 0x33, 0xf6, 0x74, - 0xcb, 0xd1, 0x08, 0x32, 0x0e, 0x3d, 0x8b, 0xb6, 0x14, 0xc3, 0x68, 0x2a, 0xae, 0x87, 0x9b, 0x96, - 0x89, 0x3c, 0xa5, 0xb9, 0xa2, 0x1c, 0x1c, 0x22, 0xaf, 0x25, 0xbb, 0x1e, 0xa6, 0x18, 0x9e, 0x4f, - 0x51, 0x90, 0x0d, 0xa3, 0x29, 0x87, 0x0a, 0x72, 0x73, 0x45, 0x5c, 0xa8, 0x63, 0x5c, 0xb7, 0x91, - 0xa2, 0xbb, 0x96, 0xa2, 0x3b, 0x0e, 0xa6, 0x3a, 0xb5, 0xb0, 0x43, 0x02, 0x08, 0x71, 0xae, 0x8e, - 0xeb, 0x98, 0xfd, 0x54, 0xfc, 0x5f, 0x7c, 0xb4, 0xcc, 0x75, 0xd8, 0xd7, 0xee, 0xe1, 0x8f, 0x14, - 0x6a, 0x35, 0x10, 0xa1, 0x7a, 0xc3, 0xe5, 0x02, 0xab, 0x59, 0x4c, 0x8d, 0xac, 0x08, 0x74, 0x96, - 0x7b, 0xe9, 0x34, 0x57, 0x14, 0xb2, 0xa7, 0x7b, 0xc8, 0xd4, 0x0c, 0xec, 0x90, 0xc3, 0x46, 0xa4, - 0xf1, 0x8d, 0x3e, 0x1a, 0x4f, 0x2d, 0x0f, 0x71, 0xb1, 0x05, 0x8a, 0x1c, 0x13, 0x79, 0x0d, 0xcb, - 0xa1, 0x8a, 0xe1, 0xb5, 0x5c, 0x8a, 0x95, 0x7d, 0xd4, 0x0a, 0x3d, 0x3c, 0x67, 0x60, 0xd2, 0xc0, - 0x44, 0x0b, 0x9c, 0x0c, 0x3e, 0x82, 0x29, 0xe9, 0x2a, 0x98, 0xff, 0xd0, 0x0f, 0xe7, 0x06, 0x5f, - 0xf6, 0x36, 0x72, 0x10, 0xb1, 0x88, 0x8a, 0x0e, 0x0e, 0x11, 0xa1, 0xf0, 0x1c, 0x98, 0x0e, 0xd6, - 0xb6, 0xcc, 0xa2, 0xb0, 0x28, 0x54, 0x66, 0xd4, 0xd7, 0xd8, 0x77, 0xcd, 0x94, 0x9e, 0x83, 0x85, - 0x74, 0x4d, 0xe2, 0x62, 0x87, 0x20, 0xf8, 0x7d, 0x70, 0xa2, 0x1e, 0x0c, 0x69, 0x84, 0xea, 0x14, - 0x31, 0xfd, 0xd9, 0xd5, 0x65, 0xb9, 0xd7, 0x8e, 0x35, 0x57, 0xe4, 0x0e, 0xac, 0x07, 0xbe, 0x5e, - 0x75, 0xe2, 0xf3, 0x17, 0xe5, 0x31, 0xf5, 0xf5, 0x7a, 0x6c, 0x4c, 0x5a, 0x00, 0x62, 0x62, 0xf1, - 0x0d, 0x1f, 0x2e, 0xb4, 0x5a, 0xd2, 0x3b, 0x9c, 0x0a, 0x67, 0xb9, 0x65, 0x55, 0x30, 0xc5, 0x96, - 0x27, 0x45, 0x61, 0x71, 0xbc, 0x32, 0xbb, 0xba, 0x24, 0x67, 0x48, 0x22, 0x99, 0x81, 0xa8, 0x5c, - 0x53, 0xba, 0x00, 0xbe, 0xd5, 0xbd, 0xc4, 0x03, 0xaa, 0x7b, 0x74, 0xdb, 0xc3, 0x2e, 0x26, 0xba, - 0x1d, 0x59, 0xf3, 0x89, 0x00, 0x2a, 0x83, 0x65, 0xb9, 0x6d, 0x3f, 0x00, 0x33, 0x6e, 0x38, 0xc8, - 0x23, 0xf6, 0x5e, 0x36, 0xf3, 0x38, 0xf8, 0xba, 0x69, 0x5a, 0x7e, 0x76, 0xb7, 0xa1, 0xdb, 0x80, - 0x52, 0x05, 0x7c, 0x33, 0xcd, 0x12, 0xec, 0x76, 0x19, 0xfd, 0x13, 0x21, 0xdd, 0xc1, 0x84, 0x68, - 0xb4, 0xd3, 0x5d, 0x36, 0xdf, 0xc8, 0x65, 0xb3, 0x8a, 0x1a, 0xb8, 0xa9, 0xdb, 0xa9, 0x26, 0xff, - 0xad, 0x00, 0x26, 0xd9, 0xda, 0x7d, 0x72, 0x11, 0xce, 0x83, 0x19, 0xc3, 0xb6, 0x90, 0x43, 0xfd, - 0xb9, 0x02, 0x9b, 0x9b, 0x0e, 0x06, 0x6a, 0x26, 0x3c, 0x03, 0x26, 0x29, 0x76, 0xb5, 0x7b, 0xc5, - 0xf1, 0x45, 0xa1, 0x72, 0x42, 0x9d, 0xa0, 0xd8, 0xbd, 0x07, 0x97, 0x00, 0x6c, 0x58, 0x8e, 0xe6, - 0xe2, 0xa7, 0xc8, 0xd3, 0x2c, 0x47, 0x0b, 0x24, 0x26, 0x16, 0x85, 0xca, 0xb8, 0x7a, 0xb2, 0x61, - 0x39, 0xdb, 0xfe, 0x44, 0xcd, 0xd9, 0xf1, 0x65, 0x97, 0xc1, 0x5c, 0x53, 0xb7, 0x2d, 0x53, 0xa7, - 0xd8, 0x23, 0x5c, 0xc5, 0xd0, 0xdd, 0xe2, 0x24, 0xc3, 0x83, 0xed, 0x39, 0xa6, 0xb4, 0xa1, 0xbb, - 0x70, 0x09, 0x9c, 0x8e, 0x46, 0x35, 0x82, 0x28, 0x13, 0x9f, 0x62, 0xe2, 0xa7, 0xa2, 0x89, 0x07, - 0x88, 0xfa, 0xb2, 0x0b, 0x60, 0x46, 0xb7, 0x6d, 0xfc, 0xd4, 0xb6, 0x08, 0x2d, 0xbe, 0xb6, 0x38, - 0x5e, 0x99, 0x51, 0xdb, 0x03, 0x50, 0x04, 0xd3, 0x26, 0x72, 0x5a, 0x6c, 0x72, 0x9a, 0x4d, 0x46, - 0xdf, 0xbe, 0xd7, 0xbe, 0x0f, 0x84, 0xea, 0xfb, 0xa8, 0x38, 0xb3, 0x28, 0x54, 0x26, 0xd4, 0xe9, - 0x06, 0xcb, 0xac, 0x7d, 0x04, 0x65, 0x70, 0x86, 0xa1, 0x68, 0x96, 0xa3, 0x1b, 0xd4, 0x6a, 0x22, - 0xad, 0xe9, 0x6f, 0x0f, 0x58, 0x14, 0x2a, 0xd3, 0xea, 0x69, 0x36, 0x55, 0xe3, 0x33, 0x8f, 0xfc, - 0x38, 0xff, 0x54, 0x00, 0x6f, 0xb3, 0x0d, 0x7f, 0x14, 0xda, 0x17, 0xcb, 0x28, 0x6f, 0x70, 0x3d, - 0x80, 0x37, 0xc0, 0x1b, 0xe1, 0xde, 0x6a, 0xba, 0x69, 0x7a, 0x88, 0x90, 0x60, 0x2b, 0xaa, 0xf0, - 0xd5, 0x8b, 0xf2, 0xc9, 0x96, 0xde, 0xb0, 0xaf, 0x49, 0x7c, 0x42, 0x52, 0x4f, 0x85, 0xb2, 0xeb, - 0xc1, 0xc8, 0xb5, 0xe9, 0x4f, 0x3e, 0x2b, 0x8f, 0xfd, 0xfd, 0xb3, 0xf2, 0x98, 0x74, 0x1f, 0x48, - 0xfd, 0x0c, 0xe1, 0x49, 0x77, 0x01, 0xbc, 0x11, 0x96, 0xca, 0x68, 0xb9, 0xc0, 0xa2, 0x53, 0x46, - 0x4c, 0xde, 0x5f, 0xac, 0xdb, 0xb5, 0xed, 0xd8, 0xe2, 0xd9, 0x5c, 0xeb, 0x5a, 0xab, 0x8f, 0x6b, - 0x1d, 0xeb, 0xf7, 0x73, 0x2d, 0x69, 0x48, 0xdb, 0xb5, 0xae, 0x48, 0x72, 0xd7, 0x3a, 0xa2, 0x26, - 0xcd, 0x83, 0x73, 0x0c, 0x70, 0x67, 0xcf, 0xc3, 0x94, 0xda, 0x88, 0x55, 0xc7, 0xf0, 0x0c, 0xff, - 0x41, 0xe0, 0x55, 0xb2, 0x63, 0x96, 0x2f, 0x53, 0x06, 0xb3, 0xc4, 0xd6, 0xc9, 0x9e, 0xd6, 0x40, - 0x14, 0x79, 0x6c, 0x85, 0x71, 0x15, 0xb0, 0xa1, 0x0f, 0xfc, 0x11, 0xb8, 0x0a, 0xbe, 0x16, 0x13, - 0xd0, 0x58, 0xce, 0xe8, 0x8e, 0x81, 0x98, 0xef, 0xe3, 0xea, 0x99, 0xb6, 0xe8, 0x7a, 0x38, 0x05, - 0x7f, 0x08, 0x8a, 0x0e, 0x7a, 0x46, 0x35, 0x0f, 0xb9, 0x36, 0x72, 0x2c, 0xb2, 0xa7, 0x19, 0xba, - 0x63, 0xfa, 0xce, 0x22, 0x76, 0xfe, 0x66, 0x57, 0x45, 0x39, 0xb8, 0x59, 0xe5, 0xf0, 0x66, 0x95, - 0x77, 0xc2, 0x9b, 0xb5, 0x3a, 0xed, 0x97, 0xfa, 0x4f, 0xff, 0x5c, 0x16, 0xd4, 0x37, 0x7d, 0x14, - 0x35, 0x04, 0xd9, 0x08, 0x31, 0xa4, 0x4b, 0x60, 0x89, 0xb9, 0xa4, 0xa2, 0xba, 0x45, 0x28, 0xf2, - 0x90, 0xd9, 0x2e, 0x22, 0x4f, 0x75, 0xcf, 0xdc, 0x44, 0x0e, 0x6e, 0x44, 0x55, 0x6c, 0x0b, 0x5c, - 0xcc, 0x24, 0xcd, 0x23, 0xf2, 0x26, 0x98, 0x32, 0xd9, 0x08, 0xbb, 0x18, 0x66, 0x54, 0xfe, 0x25, - 0x95, 0xf8, 0x55, 0x17, 0x14, 0x28, 0x64, 0xb2, 0x7a, 0x54, 0xdb, 0x8c, 0x96, 0xf9, 0x58, 0x00, - 0x6f, 0xf5, 0x10, 0xe0, 0xc8, 0x4f, 0xc0, 0x49, 0x37, 0x3e, 0x17, 0x5e, 0x3d, 0xab, 0x99, 0xea, - 0x64, 0x02, 0x96, 0xdf, 0x87, 0x1d, 0x78, 0x52, 0x0d, 0x9c, 0x48, 0x88, 0xc1, 0x22, 0xe0, 0xf9, - 0xbb, 0x99, 0x4c, 0xe7, 0x4d, 0x58, 0x02, 0x20, 0xac, 0xaf, 0xb5, 0x4d, 0xb6, 0x99, 0x13, 0x6a, - 0x6c, 0x44, 0xba, 0x0b, 0x14, 0xe6, 0xcd, 0xba, 0x6d, 0x6f, 0xeb, 0x96, 0x47, 0x1e, 0xe9, 0xf6, - 0x06, 0x76, 0xfc, 0x94, 0xab, 0x26, 0xaf, 0x83, 0xda, 0x66, 0x86, 0x3e, 0xe1, 0x57, 0x02, 0x58, - 0xce, 0x0e, 0xc7, 0xe3, 0x75, 0x00, 0x4e, 0xbb, 0xba, 0xe5, 0xf9, 0x35, 0xcb, 0xef, 0x88, 0xd8, - 0x31, 0xe0, 0x21, 0xbb, 0x95, 0x2d, 0x64, 0xba, 0xe5, 0xb5, 0x17, 0x8a, 0x8e, 0x99, 0xd3, 0x4e, - 0x80, 0x93, 0x6e, 0x42, 0x44, 0xfa, 0xaf, 0x00, 0xde, 0x1e, 0xa8, 0x05, 0x6f, 0xf5, 0x3a, 0x9b, - 0xd5, 0xf9, 0x57, 0x2f, 0xca, 0x67, 0x83, 0x52, 0xd0, 0x29, 0xd1, 0x5d, 0xee, 0x7c, 0x9c, 0x1e, - 0x25, 0x25, 0x86, 0xd3, 0x29, 0xd1, 0x5d, 0x5b, 0xe0, 0x1a, 0x78, 0x3d, 0x92, 0xda, 0x47, 0x2d, - 0x7e, 0xc6, 0x16, 0xe4, 0x76, 0x3f, 0x28, 0x07, 0xfd, 0xa0, 0xbc, 0x7d, 0xb8, 0x6b, 0x5b, 0xc6, - 0x1d, 0xd4, 0x52, 0x67, 0x43, 0x8d, 0x3b, 0xa8, 0x25, 0xcd, 0x01, 0x18, 0xa4, 0xae, 0xee, 0xe9, - 0xed, 0x83, 0xf3, 0x04, 0x9c, 0x49, 0x8c, 0xf2, 0x6d, 0xa9, 0x81, 0x29, 0x97, 0x8d, 0xf0, 0x6b, - 0xfe, 0x62, 0xc6, 0xbd, 0xf0, 0x55, 0x78, 0xde, 0x72, 0x00, 0xe9, 0x36, 0x3f, 0xc8, 0x89, 0x0c, - 0xb8, 0xef, 0x52, 0x64, 0xd6, 0x9c, 0xa8, 0x3c, 0x66, 0xe9, 0x43, 0x0f, 0xf8, 0x19, 0x1f, 0x04, - 0x14, 0x35, 0x7f, 0x6f, 0xc5, 0x2f, 0xf3, 0x8e, 0x9d, 0x42, 0xe1, 0xd1, 0x9f, 0x8f, 0xdd, 0xea, - 0xc9, 0xad, 0x43, 0x44, 0xba, 0x0e, 0x4a, 0x89, 0x25, 0x73, 0xd9, 0xfb, 0x1f, 0x01, 0x2c, 0xf6, - 0xd0, 0x8e, 0x7e, 0xa5, 0x5e, 0xa6, 0x42, 0xe6, 0xcb, 0xb4, 0x2b, 0x2b, 0x0a, 0x39, 0xb3, 0x02, - 0xce, 0x81, 0x49, 0xd6, 0xe7, 0xb0, 0x7c, 0x1a, 0x57, 0x83, 0x0f, 0xf8, 0x0e, 0x98, 0xf0, 0xfc, - 0x42, 0x3e, 0xc1, 0x2c, 0x39, 0xef, 0xef, 0xe7, 0x9f, 0x5e, 0x94, 0xe7, 0x03, 0x42, 0x41, 0xcc, - 0x7d, 0xd9, 0xc2, 0x4a, 0x43, 0xa7, 0x7b, 0xf2, 0x5d, 0x54, 0xd7, 0x8d, 0xd6, 0x26, 0x32, 0x54, - 0xa6, 0xe0, 0xb7, 0xc0, 0xe5, 0x9e, 0x11, 0xe3, 0x1b, 0x83, 0x00, 0x68, 0xc7, 0x9c, 0x9f, 0xf5, - 0xad, 0x4c, 0xf9, 0x35, 0x28, 0x9a, 0x6a, 0x0c, 0x58, 0x3a, 0xe0, 0xd5, 0x28, 0xc9, 0x0d, 0x22, - 0xd9, 0xf7, 0x75, 0xb2, 0x83, 0xf9, 0x57, 0x78, 0x91, 0x8e, 0xb8, 0x1b, 0x92, 0x0e, 0x56, 0x72, - 0x2c, 0xc9, 0xc3, 0x71, 0x09, 0xc0, 0x68, 0x0b, 0xc3, 0x54, 0x0a, 0x93, 0x33, 0x2a, 0x1d, 0x41, - 0xd9, 0x34, 0x59, 0x8b, 0x73, 0x31, 0xbd, 0x69, 0xda, 0xc0, 0x8d, 0x86, 0x45, 0x88, 0x85, 0x1d, - 0x35, 0xe6, 0xd1, 0x57, 0xd6, 0xc7, 0x49, 0x75, 0x70, 0x29, 0x9b, 0x21, 0xdc, 0xcf, 0x30, 0xa7, - 0x84, 0xbc, 0x39, 0x25, 0xf1, 0x63, 0x54, 0xb5, 0xb1, 0xb1, 0x4f, 0x1e, 0x3a, 0xd4, 0xb2, 0xef, - 0xa1, 0x67, 0x74, 0xcb, 0xc5, 0xc6, 0x5e, 0x58, 0xc6, 0x1e, 0xf3, 0xc6, 0x2f, 0x5d, 0x86, 0x5b, - 0x70, 0x05, 0x9c, 0xdd, 0x65, 0xf3, 0xda, 0xa1, 0x2f, 0xa0, 0xb1, 0xfe, 0x05, 0xf9, 0x22, 0xcc, - 0xa8, 0x09, 0x75, 0x6e, 0x37, 0x45, 0x7d, 0xf5, 0x37, 0x65, 0x30, 0xc9, 0xc0, 0xe1, 0x91, 0x00, - 0xe6, 0xd2, 0xa8, 0x30, 0xbc, 0x99, 0x3f, 0x7d, 0x93, 0xfc, 0x5b, 0x5c, 0x1f, 0x01, 0x21, 0x70, - 0x4f, 0xda, 0xfa, 0xf1, 0x97, 0x7f, 0xfd, 0x79, 0x61, 0x0d, 0xde, 0x18, 0xfc, 0xb6, 0x12, 0x25, - 0x1c, 0xe7, 0xda, 0xca, 0xf3, 0x30, 0x49, 0x3e, 0x82, 0x5f, 0x0a, 0xfc, 0x4a, 0x48, 0x66, 0x31, - 0x5c, 0xcb, 0x6f, 0x61, 0x82, 0xac, 0x8b, 0x37, 0x87, 0x07, 0xe0, 0x1e, 0xbe, 0xcb, 0x3c, 0xbc, - 0x0c, 0x57, 0x72, 0x78, 0x18, 0xd0, 0x78, 0xf8, 0x71, 0x01, 0x14, 0x7b, 0x70, 0x73, 0x02, 0xef, - 0x0e, 0x69, 0x59, 0xea, 0x33, 0x80, 0xf8, 0xc1, 0x31, 0xa1, 0x71, 0xa7, 0xdf, 0x67, 0x4e, 0x57, - 0xe1, 0xcd, 0xbc, 0x4e, 0xfb, 0x7c, 0xd1, 0xa3, 0x5a, 0xc4, 0xb0, 0xe1, 0xff, 0x04, 0x70, 0x36, - 0x9d, 0xea, 0x13, 0x78, 0x67, 0x68, 0xa3, 0xbb, 0xdf, 0x14, 0xc4, 0xbb, 0xc7, 0x03, 0xc6, 0x03, - 0x70, 0x9b, 0x05, 0x60, 0x1d, 0xae, 0x0d, 0x11, 0x00, 0xec, 0xc6, 0xfc, 0xff, 0x77, 0x48, 0x93, - 0x52, 0x09, 0x27, 0xbc, 0x95, 0xdd, 0xea, 0x7e, 0xd4, 0x59, 0xbc, 0x3d, 0x32, 0x0e, 0x77, 0x7c, - 0x9d, 0x39, 0x7e, 0x1d, 0xbe, 0x9b, 0xe1, 0xb1, 0x34, 0x7a, 0x84, 0x48, 0xb4, 0x92, 0x29, 0x2e, - 0xc7, 0x9b, 0x9c, 0xa1, 0x5c, 0x4e, 0xa1, 0xd4, 0x43, 0xb9, 0x9c, 0xc6, 0x88, 0x87, 0x73, 0x39, - 0x71, 0x8b, 0xc1, 0xdf, 0x0b, 0xbc, 0xd1, 0x4d, 0x90, 0x61, 0xf8, 0x5e, 0x76, 0x13, 0xd3, 0x38, - 0xb6, 0xb8, 0x36, 0xb4, 0x3e, 0x77, 0xed, 0x2a, 0x73, 0x6d, 0x15, 0x2e, 0x0f, 0x76, 0x8d, 0x72, - 0x80, 0xe0, 0x3d, 0x15, 0xfe, 0xb2, 0x00, 0xce, 0x67, 0x60, 0xb7, 0xf0, 0x7e, 0x76, 0x13, 0x33, - 0xb1, 0x6a, 0x71, 0xfb, 0xf8, 0x00, 0x79, 0x10, 0xee, 0xb0, 0x20, 0x6c, 0xc1, 0x8d, 0xc1, 0x41, - 0xf0, 0x22, 0xc4, 0x76, 0x4e, 0x7b, 0x0c, 0x53, 0x0b, 0xd8, 0x3a, 0xfc, 0x47, 0x17, 0x1b, 0x4f, - 0x92, 0x4c, 0x02, 0x73, 0xdc, 0xaa, 0x3d, 0x28, 0xbf, 0x58, 0x1d, 0x05, 0x82, 0x7b, 0x5d, 0x65, - 0x5e, 0x7f, 0x07, 0x5e, 0x1b, 0xec, 0x75, 0x48, 0xf6, 0xb5, 0xce, 0x0b, 0xec, 0x17, 0x05, 0xfe, - 0xb8, 0x9c, 0x81, 0x5d, 0xc3, 0x9d, 0xec, 0x46, 0x67, 0xe7, 0xfe, 0xe2, 0xc3, 0x63, 0x46, 0xe5, - 0xd1, 0xb9, 0xce, 0xa2, 0x73, 0x05, 0x5e, 0xce, 0x5d, 0xdf, 0x2d, 0x13, 0xfe, 0x56, 0x00, 0xb3, - 0x31, 0x02, 0x0b, 0xdf, 0xc9, 0xb1, 0x5d, 0x71, 0x22, 0x2c, 0x5e, 0xcd, 0xaf, 0xc8, 0xed, 0x5f, - 0x66, 0xf6, 0x2f, 0xc1, 0x4a, 0x86, 0xdd, 0x0d, 0x8c, 0xfc, 0x59, 0x78, 0xa0, 0xfb, 0x53, 0xd9, - 0x3c, 0x07, 0x3a, 0x13, 0xbb, 0xce, 0x73, 0xa0, 0xb3, 0xb1, 0xec, 0x3c, 0xdd, 0x09, 0xf6, 0x41, - 0x34, 0xcb, 0xd1, 0xda, 0x24, 0x2d, 0xde, 0x77, 0xfe, 0xae, 0x00, 0x2e, 0x64, 0x66, 0x4f, 0xf0, - 0xe1, 0xb0, 0xcd, 0x64, 0x5f, 0x02, 0x28, 0x3e, 0x3a, 0x6e, 0x58, 0x1e, 0xa6, 0xc7, 0x2c, 0x4c, - 0x3b, 0x50, 0xcd, 0xdd, 0xb9, 0x6a, 0x2e, 0xf2, 0xda, 0x11, 0x53, 0x9e, 0x77, 0x52, 0xb6, 0x8f, - 0xe0, 0xaf, 0x0b, 0xe0, 0xeb, 0x59, 0x98, 0x18, 0xdc, 0x1e, 0xa1, 0x31, 0x49, 0x65, 0x97, 0xe2, - 0x87, 0xc7, 0x88, 0xc8, 0x23, 0xf5, 0x84, 0x45, 0xea, 0x31, 0xfc, 0x5e, 0x9e, 0x48, 0x45, 0x50, - 0x9a, 0xcf, 0x18, 0x63, 0x59, 0x95, 0x16, 0xaf, 0x7f, 0x75, 0xb6, 0xc1, 0xb1, 0x13, 0xb7, 0x31, - 0xca, 0x3b, 0x44, 0x18, 0x95, 0xcd, 0xd1, 0x40, 0x46, 0xe8, 0xfb, 0xd3, 0x4f, 0xd6, 0x3f, 0x05, - 0xfe, 0xe7, 0x41, 0x1a, 0x3b, 0x86, 0x39, 0x9e, 0x5e, 0xfa, 0x30, 0x70, 0xf1, 0xd6, 0xa8, 0x30, - 0xf9, 0x3b, 0xc0, 0x1e, 0x64, 0xbe, 0xfa, 0xdd, 0xcf, 0x8f, 0x4a, 0xc2, 0x17, 0x47, 0x25, 0xe1, - 0x2f, 0x47, 0x25, 0xe1, 0xd3, 0x97, 0xa5, 0xb1, 0x2f, 0x5e, 0x96, 0xc6, 0xfe, 0xf8, 0xb2, 0x34, - 0xf6, 0xf8, 0x46, 0xdd, 0xa2, 0x7b, 0x87, 0xbb, 0xb2, 0x81, 0x1b, 0xfc, 0xdf, 0xf1, 0xd8, 0x2a, - 0xdf, 0x8e, 0x56, 0x69, 0x5e, 0x51, 0x9e, 0x75, 0x74, 0x64, 0x2d, 0x17, 0x91, 0xdd, 0x29, 0xf6, - 0x4f, 0xc6, 0xe5, 0xff, 0x07, 0x00, 0x00, 0xff, 0xff, 0x7d, 0x81, 0x96, 0x00, 0xbd, 0x20, 0x00, - 0x00, + // 2386 bytes of a gzipped FileDescriptorProto + 0x1f, 0x8b, 0x08, 0x00, 0x00, 0x00, 0x00, 0x00, 0x02, 0xff, 0xac, 0x5a, 0xcd, 0x73, 0xdb, 0xc6, + 0x15, 0x17, 0xa8, 0x0f, 0x53, 0x2b, 0x4b, 0x8e, 0xd7, 0xb2, 0x4d, 0x53, 0xb6, 0x28, 0xc3, 0xf1, + 0x8c, 0x62, 0xc7, 0x84, 0xa4, 0x8e, 0x9b, 0xc4, 0xa9, 0x3f, 0x44, 0x5a, 0xb2, 0x39, 0x8e, 0x6d, + 0x05, 0x52, 0x9c, 0x19, 0xa7, 0x2e, 0x0a, 0x01, 0x1b, 0x72, 0x2b, 0x10, 0x80, 0xb1, 0x4b, 0xda, + 0xac, 0xea, 0x4b, 0x4f, 0x39, 0xb4, 0x33, 0xc9, 0x74, 0x7a, 0x6e, 0xa6, 0x7f, 0x41, 0xa7, 0x93, + 0xe9, 0xdf, 0x90, 0x5b, 0xd3, 0xf4, 0xd2, 0xe9, 0x4c, 0xdd, 0x8e, 0xdd, 0xce, 0xb4, 0x87, 0x1e, + 0x9a, 0xb6, 0xf7, 0xcc, 0x2e, 0x16, 0x20, 0x01, 0x83, 0x24, 0x20, 0xe9, 0x46, 0xec, 0xbe, 0xf7, + 0x7b, 0x1f, 0xfb, 0xf6, 0xed, 0x7b, 0x4f, 0x02, 0x0a, 0xb6, 0x29, 0xf2, 0x8c, 0x86, 0x8e, 0x6d, + 0x8d, 0x20, 0xa3, 0xe5, 0x61, 0xda, 0x51, 0x0c, 0xa3, 0xad, 0xb8, 0x9e, 0xd3, 0xc6, 0x26, 0xf2, + 0x94, 0xf6, 0xb2, 0xf2, 0xb8, 0x85, 0xbc, 0x4e, 0xd9, 0xf5, 0x1c, 0xea, 0xc0, 0x73, 0x09, 0x0c, + 0x65, 0xc3, 0x68, 0x97, 0x03, 0x86, 0x72, 0x7b, 0xb9, 0x78, 0xba, 0xee, 0x38, 0x75, 0x0b, 0x29, + 0xba, 0x8b, 0x15, 0xdd, 0xb6, 0x1d, 0xaa, 0x53, 0xec, 0xd8, 0xc4, 0x87, 0x28, 0xce, 0xd6, 0x9d, + 0xba, 0xc3, 0x7f, 0x2a, 0xec, 0x97, 0x58, 0x2d, 0x09, 0x1e, 0xfe, 0xb5, 0xdd, 0xfa, 0x58, 0xa1, + 0xb8, 0x89, 0x08, 0xd5, 0x9b, 0xae, 0x20, 0x58, 0x49, 0xa3, 0x6a, 0xa8, 0x85, 0xcf, 0xb3, 0xd4, + 0x8f, 0xa7, 0xbd, 0xac, 0x90, 0x86, 0xee, 0x21, 0x53, 0x33, 0x1c, 0x9b, 0xb4, 0x9a, 0x21, 0xc7, + 0xf9, 0x01, 0x1c, 0x4f, 0xb0, 0x87, 0x04, 0xd9, 0x69, 0x8a, 0x6c, 0x13, 0x79, 0x4d, 0x6c, 0x53, + 0xc5, 0xf0, 0x3a, 0x2e, 0x75, 0x94, 0x1d, 0xd4, 0x09, 0x2c, 0x3c, 0x65, 0x38, 0xa4, 0xe9, 0x10, + 0xcd, 0x37, 0xd2, 0xff, 0x10, 0x5b, 0xaf, 0xfb, 0x5f, 0x0a, 0xa1, 0xfa, 0x0e, 0xb6, 0xeb, 0x4a, + 0x7b, 0x79, 0x1b, 0x51, 0x7d, 0x39, 0xf8, 0xf6, 0xa9, 0xe4, 0x6b, 0x60, 0xee, 0x7d, 0xe6, 0xf4, + 0xaa, 0x50, 0xee, 0x16, 0xb2, 0x11, 0xc1, 0x44, 0x45, 0x8f, 0x5b, 0x88, 0x50, 0x58, 0x02, 0x53, + 0x81, 0xda, 0x1a, 0x36, 0x0b, 0xd2, 0x82, 0xb4, 0x38, 0xa9, 0x82, 0x60, 0xa9, 0x66, 0xca, 0xbb, + 0xe0, 0x74, 0x32, 0x3f, 0x71, 0x1d, 0x9b, 0x20, 0xf8, 0x11, 0x98, 0xae, 0xfb, 0x4b, 0x1a, 0xa1, + 0x3a, 0x45, 0x1c, 0x62, 0x6a, 0x65, 0xa9, 0xdc, 0xef, 0x74, 0xdb, 0xcb, 0xe5, 0x18, 0xd6, 0x26, + 0xe3, 0xab, 0x8c, 0x7d, 0xf9, 0xbc, 0x34, 0xa2, 0x1e, 0xae, 0xf7, 0xac, 0xc9, 0x3f, 0x01, 0xc5, + 0x88, 0xf0, 0x2a, 0x83, 0x0b, 0x75, 0xbf, 0x0d, 0xc6, 0xdd, 0x86, 0x4e, 0x7c, 0x91, 0x33, 0x2b, + 0x2b, 0xe5, 0x14, 0x01, 0x15, 0xca, 0xde, 0x60, 0x9c, 0xaa, 0x0f, 0x00, 0x67, 0xc1, 0xb8, 0x85, + 0x9b, 0x98, 0x16, 0x72, 0x0b, 0xd2, 0xe2, 0xb8, 0xea, 0x7f, 0xc8, 0x7a, 0xcc, 0x75, 0x81, 0x74, + 0x61, 0x79, 0x05, 0x4c, 0x70, 0x59, 0xa4, 0x20, 0x2d, 0x8c, 0x2e, 0x4e, 0xad, 0x5c, 0x48, 0x27, + 0x9f, 0x6d, 0xab, 0x82, 0x53, 0xfe, 0xff, 0x28, 0x18, 0xe7, 0x2b, 0xf0, 0x14, 0xc8, 0xfb, 0x9c, + 0xe1, 0x29, 0x1c, 0xe2, 0xdf, 0x35, 0x13, 0xce, 0x81, 0x49, 0xc3, 0xc2, 0xc8, 0xa6, 0x6c, 0x2f, + 0xc7, 0xf7, 0xf2, 0xfe, 0x42, 0xcd, 0x84, 0xc7, 0xc0, 0x38, 0x75, 0x5c, 0xed, 0x5e, 0x61, 0x74, + 0x41, 0x5a, 0x9c, 0x56, 0xc7, 0xa8, 0xe3, 0xde, 0x83, 0x17, 0x00, 0x6c, 0x62, 0x5b, 0x73, 0x9d, + 0x27, 0xec, 0x58, 0x6d, 0xcd, 0xa7, 0x18, 0x5b, 0x90, 0x16, 0x47, 0xd5, 0x99, 0x26, 0xb6, 0x37, + 0xd8, 0x46, 0xcd, 0xde, 0x62, 0xb4, 0x4b, 0x60, 0xb6, 0xad, 0x5b, 0xd8, 0xd4, 0xa9, 0xe3, 0x11, + 0xc1, 0x62, 0xe8, 0x6e, 0x61, 0x9c, 0xe3, 0xc1, 0xee, 0x1e, 0x67, 0xaa, 0xea, 0x2e, 0xbc, 0x00, + 0x8e, 0x86, 0xab, 0x1a, 0x41, 0x94, 0x93, 0x4f, 0x70, 0xf2, 0x23, 0xe1, 0xc6, 0x26, 0xa2, 0x8c, + 0xf6, 0x34, 0x98, 0xd4, 0x2d, 0xcb, 0x79, 0x62, 0x61, 0x42, 0x0b, 0x87, 0x16, 0x46, 0x17, 0x27, + 0xd5, 0xee, 0x02, 0x2c, 0x82, 0xbc, 0x89, 0xec, 0x0e, 0xdf, 0xcc, 0xf3, 0xcd, 0xf0, 0x9b, 0x9d, + 0x89, 0x7f, 0xba, 0x93, 0xdc, 0x62, 0x71, 0x52, 0x1f, 0x82, 0x7c, 0x13, 0x51, 0xdd, 0xd4, 0xa9, + 0x5e, 0x00, 0x3c, 0xd2, 0x2e, 0x67, 0x3a, 0xf6, 0xbb, 0x82, 0x59, 0x84, 0x5b, 0x08, 0xc6, 0x9c, + 0xcc, 0x5c, 0xc6, 0x2e, 0x0f, 0x2a, 0x4c, 0x2d, 0x48, 0x8b, 0x63, 0x6a, 0xbe, 0x89, 0xed, 0x4d, + 0xf6, 0x0d, 0xcb, 0xe0, 0x18, 0x57, 0x5a, 0xc3, 0xb6, 0x6e, 0x50, 0xdc, 0x46, 0x5a, 0x5b, 0xb7, + 0x48, 0xe1, 0xf0, 0x82, 0xb4, 0x98, 0x57, 0x8f, 0xf2, 0xad, 0x9a, 0xd8, 0x79, 0xa0, 0x5b, 0x24, + 0x7e, 0xab, 0xa6, 0x5f, 0xb9, 0x55, 0x3f, 0x97, 0xc0, 0x59, 0x1e, 0x5b, 0x0f, 0x02, 0x7f, 0x05, + 0x0a, 0xae, 0x9a, 0xa6, 0x17, 0x04, 0xf8, 0x55, 0xf0, 0x5a, 0x60, 0x83, 0xa6, 0x9b, 0xa6, 0x87, + 0x08, 0xf1, 0x63, 0xa3, 0x02, 0xbf, 0x79, 0x5e, 0x9a, 0xe9, 0xe8, 0x4d, 0xeb, 0x8a, 0x2c, 0x36, + 0x64, 0xf5, 0x48, 0x40, 0xbb, 0xea, 0xaf, 0xc4, 0xb5, 0xc8, 0xc5, 0xb5, 0xb8, 0x92, 0xff, 0xe4, + 0xf3, 0xd2, 0xc8, 0x3f, 0x3f, 0x2f, 0x8d, 0xc8, 0xf7, 0x81, 0x3c, 0x48, 0x1d, 0x11, 0xf1, 0x6f, + 0x80, 0xd7, 0x42, 0xc0, 0x88, 0x3e, 0xea, 0x11, 0xa3, 0x87, 0x9e, 0x69, 0xf3, 0xaa, 0x81, 0x1b, + 0x3d, 0xda, 0xf5, 0x18, 0x98, 0x0c, 0x98, 0x6c, 0x60, 0x4c, 0xc8, 0xbe, 0x0c, 0x8c, 0xaa, 0xd3, + 0x35, 0x30, 0xd9, 0xe1, 0xaf, 0x38, 0x57, 0x9e, 0x03, 0xa7, 0x38, 0xe0, 0x56, 0xc3, 0x73, 0x28, + 0xb5, 0x10, 0x4f, 0x58, 0xc2, 0x2e, 0xf9, 0x0f, 0x92, 0x48, 0x5c, 0xb1, 0x5d, 0x21, 0xa6, 0x04, + 0xa6, 0x88, 0xa5, 0x93, 0x86, 0xd6, 0x44, 0x14, 0x79, 0x5c, 0xc2, 0xa8, 0x0a, 0xf8, 0xd2, 0x5d, + 0xb6, 0x02, 0x57, 0xc0, 0xf1, 0x1e, 0x02, 0x8d, 0x07, 0x98, 0x6e, 0x1b, 0x88, 0x9b, 0x38, 0xaa, + 0x1e, 0xeb, 0x92, 0xae, 0x06, 0x5b, 0xf0, 0x07, 0xa0, 0x60, 0xa3, 0xa7, 0x54, 0xf3, 0x90, 0x6b, + 0x21, 0x1b, 0x93, 0x86, 0x66, 0xe8, 0xb6, 0xc9, 0x8c, 0x45, 0x3c, 0x37, 0x4c, 0xad, 0x14, 0xcb, + 0xfe, 0xc3, 0x58, 0x0e, 0x1e, 0xc6, 0xf2, 0x56, 0xf0, 0x30, 0x56, 0xf2, 0xec, 0x3a, 0x7c, 0xfa, + 0xd7, 0x92, 0xa4, 0x9e, 0x60, 0x28, 0x6a, 0x00, 0x52, 0x0d, 0x30, 0xe4, 0x37, 0xc1, 0x05, 0x6e, + 0x92, 0x8a, 0xea, 0x98, 0x50, 0xe4, 0x21, 0x33, 0x88, 0x11, 0x15, 0x3d, 0xd1, 0x3d, 0xf3, 0x26, + 0xb2, 0x9d, 0x66, 0x90, 0x9b, 0xe5, 0x35, 0x70, 0x31, 0x15, 0xb5, 0xf0, 0xc8, 0x09, 0x30, 0x61, + 0xf2, 0x15, 0x9e, 0x4b, 0x27, 0x55, 0xf1, 0x25, 0xbf, 0x07, 0xde, 0xe0, 0x30, 0xab, 0x96, 0xb5, + 0xa1, 0x63, 0x8f, 0x3c, 0xd0, 0x2d, 0x86, 0xc3, 0x0e, 0xa1, 0xd2, 0xe9, 0x22, 0xa6, 0x7c, 0xcb, + 0x7e, 0x25, 0x09, 0x1b, 0x86, 0xc0, 0x09, 0xa5, 0x1e, 0x83, 0xa3, 0xae, 0x8e, 0x3d, 0x76, 0xd7, + 0xd9, 0xdb, 0xce, 0x23, 0x42, 0xe4, 0xfa, 0xf5, 0x54, 0x49, 0x87, 0xc9, 0xf0, 0x45, 0x30, 0x09, + 0x61, 0xc4, 0xd9, 0x5d, 0x5f, 0xcc, 0xb8, 0x11, 0x12, 0xf9, 0x7f, 0x12, 0x38, 0x3b, 0x94, 0x0b, + 0xae, 0xf7, 0xcd, 0x0b, 0x73, 0xdf, 0x3c, 0x2f, 0x9d, 0xf4, 0xaf, 0x4d, 0x9c, 0x22, 0x21, 0x41, + 0xac, 0x27, 0x5c, 0xbf, 0x5c, 0x1c, 0x27, 0x4e, 0x91, 0x70, 0x0f, 0xaf, 0x83, 0xc3, 0x21, 0xd5, + 0x0e, 0xea, 0x88, 0x70, 0x3b, 0x5d, 0xee, 0x56, 0x36, 0x65, 0xbf, 0xb2, 0x29, 0x6f, 0xb4, 0xb6, + 0x2d, 0x6c, 0xdc, 0x41, 0x1d, 0x35, 0x3c, 0xaa, 0x3b, 0xa8, 0x23, 0xcf, 0x02, 0xc8, 0xcf, 0x65, + 0x43, 0xf7, 0xf4, 0x6e, 0x0c, 0xfd, 0x10, 0x1c, 0x8b, 0xac, 0x8a, 0x63, 0xa9, 0x81, 0x09, 0x97, + 0xaf, 0x88, 0x52, 0xe3, 0x62, 0xca, 0xb3, 0x60, 0x2c, 0x22, 0xed, 0x0b, 0x00, 0xf9, 0xae, 0x88, + 0x87, 0xc8, 0x0b, 0x7f, 0xdf, 0xa5, 0xc8, 0xac, 0xd9, 0x61, 0xa6, 0x48, 0x5f, 0x2b, 0x3d, 0x16, + 0x41, 0x3f, 0x0c, 0x2e, 0x2c, 0x20, 0xce, 0xf4, 0xbe, 0xbc, 0xb1, 0xf3, 0x42, 0xc1, 0x5d, 0x98, + 0xeb, 0x79, 0x82, 0xa3, 0x07, 0x88, 0x88, 0xbc, 0x0a, 0xe6, 0x23, 0x22, 0xf7, 0xa0, 0xf5, 0x67, + 0x87, 0xc0, 0x42, 0x1f, 0x8c, 0xf0, 0xd7, 0x7e, 0x9f, 0xa2, 0x78, 0x84, 0xe4, 0x32, 0x46, 0x08, + 0x2c, 0x80, 0x71, 0x5e, 0x9a, 0xf0, 0xd8, 0x1a, 0xad, 0xe4, 0x0a, 0x92, 0xea, 0x2f, 0xc0, 0x77, + 0xc0, 0x98, 0xc7, 0x72, 0xdc, 0x18, 0xd7, 0xe6, 0x3c, 0x3b, 0xdf, 0x3f, 0x3f, 0x2f, 0xcd, 0xf9, + 0xc5, 0x31, 0x31, 0x77, 0xca, 0xd8, 0x51, 0x9a, 0x3a, 0x6d, 0x94, 0xdf, 0x43, 0x75, 0xdd, 0xe8, + 0xdc, 0x44, 0x46, 0x41, 0x52, 0x39, 0x0b, 0x3c, 0x0f, 0x66, 0x42, 0xad, 0x7c, 0xf4, 0x71, 0x9e, + 0x5f, 0xa7, 0x83, 0x55, 0x5e, 0xf2, 0xc0, 0x47, 0xa0, 0x10, 0x92, 0x19, 0x4e, 0xb3, 0x89, 0x09, + 0xc1, 0x8e, 0xad, 0x71, 0xa9, 0x13, 0x5c, 0xea, 0xb9, 0x14, 0x52, 0xd5, 0x13, 0x01, 0x48, 0x35, + 0xc4, 0x50, 0x99, 0x16, 0x8f, 0x40, 0x21, 0x74, 0x6d, 0x1c, 0xfe, 0x50, 0x06, 0xf8, 0x00, 0x24, + 0x06, 0x7f, 0x07, 0x4c, 0x99, 0x88, 0x18, 0x1e, 0x76, 0x59, 0xe7, 0x54, 0xc8, 0x73, 0xcf, 0x9f, + 0x2b, 0x8b, 0x56, 0x22, 0x68, 0x16, 0x44, 0xf3, 0x50, 0xbe, 0xd9, 0x25, 0x15, 0x77, 0xa5, 0x97, + 0x1b, 0x3e, 0x02, 0xa7, 0x42, 0x5d, 0x1d, 0x17, 0x79, 0xbc, 0x04, 0x0c, 0xe2, 0x81, 0x17, 0x6a, + 0x95, 0xb3, 0x5f, 0x7f, 0x71, 0xe9, 0x8c, 0x40, 0x0f, 0xe3, 0x47, 0xc4, 0xc1, 0x26, 0xf5, 0xb0, + 0x5d, 0x57, 0x4f, 0x06, 0x18, 0xf7, 0x05, 0x44, 0x10, 0x26, 0x27, 0xc0, 0xc4, 0x8f, 0x74, 0x6c, + 0x21, 0x93, 0xd7, 0x76, 0x79, 0x55, 0x7c, 0xc1, 0x2b, 0x60, 0x82, 0x35, 0x17, 0x2d, 0xc2, 0x2b, + 0xb3, 0x99, 0x15, 0xb9, 0x9f, 0xfa, 0x15, 0xc7, 0x36, 0x37, 0x39, 0xa5, 0x2a, 0x38, 0xe0, 0x16, + 0x08, 0xa3, 0x51, 0xa3, 0xce, 0x0e, 0xb2, 0xfd, 0xba, 0x6d, 0xb2, 0x72, 0x51, 0x78, 0xf5, 0xf8, + 0xab, 0x5e, 0xad, 0xd9, 0xf4, 0xeb, 0x2f, 0x2e, 0x01, 0x21, 0xa4, 0x66, 0x53, 0x75, 0x26, 0xc0, + 0xd8, 0xe2, 0x10, 0x2c, 0x74, 0x42, 0x54, 0x3f, 0x74, 0xa6, 0xfd, 0xd0, 0x09, 0x56, 0xfd, 0xd0, + 0xf9, 0x2e, 0x38, 0x29, 0x6e, 0x2f, 0x22, 0x9a, 0xd1, 0xf2, 0x3c, 0x56, 0xc5, 0x23, 0xd7, 0x31, + 0x1a, 0x85, 0x19, 0x6e, 0xe1, 0xf1, 0x70, 0xbb, 0xea, 0xef, 0xae, 0xb1, 0x4d, 0xf9, 0x13, 0x09, + 0x94, 0xfa, 0xde, 0x6b, 0x91, 0x3e, 0x10, 0x00, 0xdd, 0xcc, 0x20, 0xde, 0xa5, 0xb5, 0x54, 0xb9, + 0x70, 0xd8, 0x6d, 0x57, 0x7b, 0x80, 0xe5, 0xc7, 0x60, 0x29, 0xa1, 0x0b, 0x0a, 0x69, 0x6f, 0xeb, + 0x64, 0xcb, 0x11, 0x5f, 0xe8, 0x60, 0x0a, 0x57, 0xf9, 0x01, 0x58, 0xce, 0x20, 0x52, 0xb8, 0xe3, + 0x6c, 0x4f, 0x8a, 0xc1, 0x66, 0x90, 0x3c, 0xa7, 0xba, 0x89, 0x8e, 0x17, 0xa5, 0x17, 0x93, 0xcb, + 0xdc, 0xe8, 0x9d, 0x49, 0x9b, 0x3a, 0x13, 0xed, 0xcc, 0xa5, 0xb7, 0xb3, 0x0e, 0xde, 0x4c, 0xa7, + 0x8e, 0x30, 0xf1, 0x2d, 0x91, 0xea, 0xa4, 0xf4, 0x59, 0x81, 0x33, 0xc8, 0xb2, 0xc8, 0xf0, 0x15, + 0xcb, 0x31, 0x76, 0xc8, 0x07, 0x36, 0xc5, 0xd6, 0x3d, 0xf4, 0xd4, 0x8f, 0xb5, 0xe0, 0xb5, 0x7d, + 0x28, 0x0a, 0xf6, 0x64, 0x1a, 0xa1, 0xc1, 0x65, 0x70, 0x72, 0x9b, 0xef, 0x6b, 0x2d, 0x46, 0xa0, + 0xf1, 0x8a, 0xd3, 0x8f, 0x67, 0x89, 0xf7, 0x4c, 0xb3, 0xdb, 0x09, 0xec, 0xf2, 0xaa, 0xa8, 0xbe, + 0xab, 0xa1, 0xeb, 0xd6, 0x3d, 0xa7, 0x59, 0x15, 0x3d, 0x6c, 0xe0, 0xee, 0x48, 0x9f, 0x2b, 0x45, + 0xfb, 0x5c, 0x79, 0x1d, 0x9c, 0x1b, 0x08, 0xd1, 0x2d, 0xad, 0x07, 0xbf, 0x76, 0xdf, 0x13, 0x75, + 0x7b, 0x24, 0xb6, 0x52, 0xbf, 0x95, 0xbf, 0x1e, 0x4d, 0x9a, 0x48, 0x84, 0xd2, 0x07, 0x34, 0xf1, + 0xe7, 0xc0, 0xb4, 0xf3, 0xc4, 0x8e, 0xc7, 0x89, 0x7a, 0x98, 0x2f, 0x06, 0xf9, 0x2f, 0xec, 0x79, + 0x47, 0xfb, 0xf5, 0xbc, 0x63, 0x07, 0xd9, 0xf3, 0x7e, 0x0c, 0xa6, 0xb0, 0x8d, 0xa9, 0x26, 0xca, + 0xa9, 0x71, 0x8e, 0xbd, 0x96, 0x09, 0xbb, 0x66, 0x63, 0x8a, 0x75, 0x0b, 0xff, 0x98, 0xcf, 0xe5, + 0x78, 0x91, 0xc5, 0xda, 0x12, 0xa2, 0x02, 0x86, 0xec, 0x17, 0x5d, 0xb0, 0x09, 0x66, 0xfd, 0xb9, + 0x02, 0x69, 0xe8, 0x2e, 0xb6, 0xeb, 0x81, 0xc0, 0x09, 0x2e, 0xf0, 0xdd, 0x74, 0xf5, 0x1b, 0x03, + 0xd8, 0xf4, 0xf9, 0x7b, 0xc4, 0x40, 0x37, 0xbe, 0x4e, 0x56, 0xfe, 0x75, 0x06, 0x8c, 0xf3, 0x43, + 0x82, 0xff, 0x90, 0xc0, 0x6c, 0xd2, 0xf4, 0x0a, 0xde, 0xc8, 0x9e, 0x27, 0xa3, 0x83, 0xb3, 0xe2, + 0xea, 0x3e, 0x10, 0xfc, 0x68, 0x91, 0x6f, 0xff, 0xf4, 0x8f, 0x7f, 0xff, 0x45, 0xae, 0x02, 0x6f, + 0x0c, 0x1f, 0x9d, 0x86, 0x51, 0x29, 0xc6, 0x63, 0xca, 0x6e, 0x4f, 0x9c, 0x3e, 0x83, 0x2f, 0x25, + 0x51, 0x2a, 0x47, 0x33, 0x26, 0xbc, 0x9e, 0x5d, 0xc9, 0xc8, 0x88, 0xad, 0x78, 0x63, 0xef, 0x00, + 0xc2, 0xc8, 0x1a, 0x37, 0xb2, 0x0a, 0x57, 0x33, 0x18, 0xe9, 0x0f, 0xc7, 0x94, 0x5d, 0x1e, 0xfe, + 0xcf, 0x94, 0x5d, 0x3e, 0x8e, 0x7b, 0x06, 0x3f, 0xcb, 0x89, 0xcb, 0x97, 0x38, 0xa5, 0x80, 0xeb, + 0xe9, 0x75, 0x1d, 0x34, 0x75, 0x29, 0xde, 0xda, 0x37, 0x8e, 0x30, 0x7d, 0x9b, 0x9b, 0xfe, 0x7d, + 0xf8, 0x30, 0xc5, 0x68, 0x3c, 0x9c, 0xa7, 0x45, 0xda, 0xad, 0xe8, 0x31, 0x2b, 0xbb, 0xf1, 0xc7, + 0x26, 0xc9, 0x27, 0xbd, 0x3d, 0xc2, 0x9e, 0x7c, 0x92, 0x30, 0xa8, 0xd9, 0x93, 0x4f, 0x92, 0x26, + 0x2c, 0x7b, 0xf3, 0x49, 0xc4, 0xec, 0xb8, 0x4f, 0xe2, 0xfd, 0xe9, 0x33, 0xf8, 0x7b, 0x49, 0xb4, + 0x93, 0x91, 0xe9, 0x0b, 0xbc, 0x96, 0xde, 0x86, 0xa4, 0xa1, 0x4e, 0xf1, 0xfa, 0x9e, 0xf9, 0x85, + 0xed, 0x6f, 0x73, 0xdb, 0x57, 0xe0, 0xd2, 0x70, 0xdb, 0xa9, 0x00, 0xf0, 0x67, 0xea, 0xf0, 0x97, + 0x39, 0xf1, 0xfa, 0x0d, 0x1e, 0xa7, 0xc0, 0xfb, 0xe9, 0x55, 0x4c, 0x35, 0xc6, 0x29, 0x6e, 0x1c, + 0x1c, 0xa0, 0x70, 0xc2, 0x1d, 0xee, 0x84, 0x35, 0x58, 0x1d, 0xee, 0x04, 0x2f, 0x44, 0xec, 0xde, + 0x0a, 0x8f, 0x63, 0x6a, 0xfe, 0x78, 0x08, 0xfe, 0x2c, 0x27, 0x0a, 0x8b, 0x81, 0x03, 0x1d, 0x78, + 0x2f, 0xbd, 0x15, 0x69, 0x06, 0x4d, 0xc5, 0xfb, 0x07, 0x86, 0x27, 0x9c, 0xb2, 0xc6, 0x9d, 0x72, + 0x1d, 0x5e, 0x1d, 0xee, 0x14, 0x11, 0xe5, 0x9a, 0xcb, 0x50, 0x63, 0xcf, 0xc0, 0x6f, 0x25, 0x30, + 0xd5, 0x33, 0x31, 0x81, 0x6f, 0xa5, 0xd7, 0x33, 0x32, 0x79, 0x29, 0xbe, 0x9d, 0x9d, 0x51, 0x58, + 0xb2, 0xc4, 0x2d, 0xb9, 0x00, 0x17, 0x87, 0x5b, 0xe2, 0x17, 0x01, 0xdd, 0xd8, 0x1e, 0x3c, 0x35, + 0xc9, 0x12, 0xdb, 0xa9, 0xc6, 0x39, 0x59, 0x62, 0x3b, 0xdd, 0x40, 0x27, 0x4b, 0x6c, 0x3b, 0x0c, + 0x44, 0xc3, 0xb6, 0xd6, 0xed, 0xb4, 0x62, 0x87, 0xf9, 0xbb, 0x9c, 0x98, 0x7d, 0xa6, 0xe9, 0x82, + 0xe0, 0x07, 0x7b, 0x7d, 0xa8, 0x07, 0x36, 0x72, 0xc5, 0x07, 0x07, 0x0d, 0x2b, 0x3c, 0xf5, 0x90, + 0x7b, 0x6a, 0x0b, 0xaa, 0x99, 0xab, 0x02, 0xcd, 0x45, 0x5e, 0xd7, 0x69, 0x49, 0x4f, 0xe2, 0x6f, + 0x72, 0xe0, 0xf5, 0x34, 0x6d, 0x15, 0xdc, 0xd8, 0xc7, 0x43, 0x9f, 0xd8, 0x30, 0x16, 0xdf, 0x3f, + 0x40, 0x44, 0xe1, 0x29, 0x83, 0x7b, 0xea, 0x11, 0xfc, 0x28, 0x8b, 0xa7, 0xa2, 0x53, 0xa4, 0xe1, + 0x55, 0xc4, 0x7f, 0x24, 0x70, 0xb2, 0xcf, 0x50, 0x00, 0x56, 0xf7, 0x33, 0x52, 0x08, 0x1c, 0x73, + 0x73, 0x7f, 0x20, 0xd9, 0xef, 0x57, 0x68, 0x71, 0xdf, 0xfb, 0xf5, 0x6f, 0x49, 0x74, 0x82, 0x49, + 0x0d, 0x2f, 0xcc, 0x30, 0x48, 0x19, 0xd0, 0x54, 0x17, 0xd7, 0xf7, 0x0b, 0x23, 0x2c, 0x5f, 0xe5, + 0x96, 0xbf, 0x0b, 0xdf, 0x19, 0x6e, 0x79, 0x9f, 0xfe, 0x1c, 0xfe, 0x57, 0x8a, 0xfd, 0x39, 0x3b, + 0xda, 0x41, 0xc3, 0x5b, 0xd9, 0x8f, 0x28, 0xb1, 0x8d, 0x2f, 0xde, 0xde, 0x3f, 0x50, 0x76, 0xab, + 0x7b, 0x8e, 0x56, 0xd9, 0x0d, 0xa7, 0x08, 0xcf, 0xe0, 0x5f, 0x82, 0x5a, 0x30, 0x92, 0x9e, 0xb2, + 0xd4, 0x82, 0x49, 0x83, 0x82, 0xe2, 0xf5, 0x3d, 0xf3, 0x0b, 0xd3, 0xd6, 0xb9, 0x69, 0x37, 0xe0, + 0xb5, 0xac, 0x09, 0x30, 0x1a, 0xc5, 0x95, 0x0f, 0xbf, 0x7c, 0x31, 0x2f, 0x7d, 0xf5, 0x62, 0x5e, + 0xfa, 0xdb, 0x8b, 0x79, 0xe9, 0xd3, 0x97, 0xf3, 0x23, 0x5f, 0xbd, 0x9c, 0x1f, 0xf9, 0xd3, 0xcb, + 0xf9, 0x91, 0x87, 0x57, 0xeb, 0x98, 0x36, 0x5a, 0xdb, 0x65, 0xc3, 0x69, 0x8a, 0xff, 0x1b, 0xe9, + 0x11, 0x75, 0x29, 0x14, 0xd5, 0xbe, 0xac, 0x3c, 0x8d, 0xd5, 0x9e, 0x1d, 0x17, 0x91, 0xed, 0x09, + 0xfe, 0x47, 0xc2, 0xef, 0x7c, 0x1b, 0x00, 0x00, 0xff, 0xff, 0x64, 0xaa, 0xd9, 0x88, 0xd7, 0x23, + 0x00, 0x00, } // Reference imports to suppress errors if they are not otherwise used. @@ -1951,10 +2004,6 @@ type QueryClient interface { // ConsumerChains queries active consumer chains supported by the provider // chain QueryConsumerChains(ctx context.Context, in *QueryConsumerChainsRequest, opts ...grpc.CallOption) (*QueryConsumerChainsResponse, error) - // QueryConsumerChainStarts queries consumer chain start proposals. - QueryConsumerChainStarts(ctx context.Context, in *QueryConsumerChainStartProposalsRequest, opts ...grpc.CallOption) (*QueryConsumerChainStartProposalsResponse, error) - // QueryConsumerChainStops queries consumer chain stop proposals. - QueryConsumerChainStops(ctx context.Context, in *QueryConsumerChainStopProposalsRequest, opts ...grpc.CallOption) (*QueryConsumerChainStopProposalsResponse, error) // QueryValidatorConsumerAddr queries the address // assigned by a validator for a consumer chain. QueryValidatorConsumerAddr(ctx context.Context, in *QueryValidatorConsumerAddrRequest, opts ...grpc.CallOption) (*QueryValidatorConsumerAddrResponse, error) @@ -1967,12 +2016,9 @@ type QueryClient interface { // QueryRegisteredConsumerRewardDenoms returns a list of consumer reward // denoms that are registered QueryRegisteredConsumerRewardDenoms(ctx context.Context, in *QueryRegisteredConsumerRewardDenomsRequest, opts ...grpc.CallOption) (*QueryRegisteredConsumerRewardDenomsResponse, error) - // QueryProposedConsumerChainIDs returns the chain IDs of the proposed consumer chain addition proposals - // that are still in the voting period - QueryProposedConsumerChainIDs(ctx context.Context, in *QueryProposedChainIDsRequest, opts ...grpc.CallOption) (*QueryProposedChainIDsResponse, error) - // QueryAllPairsValConAddrByConsumerChainID returns a list of pair valconsensus address + // QueryAllPairsValConsAddrByConsumer returns a list of pair valconsensus address // between provider and consumer chain - QueryAllPairsValConAddrByConsumerChainID(ctx context.Context, in *QueryAllPairsValConAddrByConsumerChainIDRequest, opts ...grpc.CallOption) (*QueryAllPairsValConAddrByConsumerChainIDResponse, error) + QueryAllPairsValConsAddrByConsumer(ctx context.Context, in *QueryAllPairsValConsAddrByConsumerRequest, opts ...grpc.CallOption) (*QueryAllPairsValConsAddrByConsumerResponse, error) // QueryParams returns all current values of provider parameters QueryParams(ctx context.Context, in *QueryParamsRequest, opts ...grpc.CallOption) (*QueryParamsResponse, error) // QueryConsumerChainOptedInValidators returns a list of validators consensus addresses @@ -1984,13 +2030,19 @@ type QueryClient interface { // QueryValidatorConsumerCommissionRate returns the commission rate a given // validator charges on a given consumer chain QueryValidatorConsumerCommissionRate(ctx context.Context, in *QueryValidatorConsumerCommissionRateRequest, opts ...grpc.CallOption) (*QueryValidatorConsumerCommissionRateResponse, error) - // QueryConsumerValidators returns the latest set consumer-validator set for a given chainID + // QueryConsumerValidators returns the latest set consumer-validator set for a given consumer ID // Note that this does not necessarily mean that the consumer chain is using this validator set at this exact moment // because a VSCPacket could be delayed to be delivered on the consumer chain. QueryConsumerValidators(ctx context.Context, in *QueryConsumerValidatorsRequest, opts ...grpc.CallOption) (*QueryConsumerValidatorsResponse, error) // QueryBlocksUntilNextEpoch returns the number of blocks until the next epoch // starts and validator updates are sent to the consumer chains QueryBlocksUntilNextEpoch(ctx context.Context, in *QueryBlocksUntilNextEpochRequest, opts ...grpc.CallOption) (*QueryBlocksUntilNextEpochResponse, error) + // QueryConsumerIdFromClientId returns the consumer id of the chain + // associated with the provided client id + QueryConsumerIdFromClientId(ctx context.Context, in *QueryConsumerIdFromClientIdRequest, opts ...grpc.CallOption) (*QueryConsumerIdFromClientIdResponse, error) + // QueryConsumerChain returns the consumer chain + // associated with the provided consumer id + QueryConsumerChain(ctx context.Context, in *QueryConsumerChainRequest, opts ...grpc.CallOption) (*QueryConsumerChainResponse, error) } type queryClient struct { @@ -2019,24 +2071,6 @@ func (c *queryClient) QueryConsumerChains(ctx context.Context, in *QueryConsumer return out, nil } -func (c *queryClient) QueryConsumerChainStarts(ctx context.Context, in *QueryConsumerChainStartProposalsRequest, opts ...grpc.CallOption) (*QueryConsumerChainStartProposalsResponse, error) { - out := new(QueryConsumerChainStartProposalsResponse) - err := c.cc.Invoke(ctx, "/interchain_security.ccv.provider.v1.Query/QueryConsumerChainStarts", in, out, opts...) - if err != nil { - return nil, err - } - return out, nil -} - -func (c *queryClient) QueryConsumerChainStops(ctx context.Context, in *QueryConsumerChainStopProposalsRequest, opts ...grpc.CallOption) (*QueryConsumerChainStopProposalsResponse, error) { - out := new(QueryConsumerChainStopProposalsResponse) - err := c.cc.Invoke(ctx, "/interchain_security.ccv.provider.v1.Query/QueryConsumerChainStops", in, out, opts...) - if err != nil { - return nil, err - } - return out, nil -} - func (c *queryClient) QueryValidatorConsumerAddr(ctx context.Context, in *QueryValidatorConsumerAddrRequest, opts ...grpc.CallOption) (*QueryValidatorConsumerAddrResponse, error) { out := new(QueryValidatorConsumerAddrResponse) err := c.cc.Invoke(ctx, "/interchain_security.ccv.provider.v1.Query/QueryValidatorConsumerAddr", in, out, opts...) @@ -2073,18 +2107,9 @@ func (c *queryClient) QueryRegisteredConsumerRewardDenoms(ctx context.Context, i return out, nil } -func (c *queryClient) QueryProposedConsumerChainIDs(ctx context.Context, in *QueryProposedChainIDsRequest, opts ...grpc.CallOption) (*QueryProposedChainIDsResponse, error) { - out := new(QueryProposedChainIDsResponse) - err := c.cc.Invoke(ctx, "/interchain_security.ccv.provider.v1.Query/QueryProposedConsumerChainIDs", in, out, opts...) - if err != nil { - return nil, err - } - return out, nil -} - -func (c *queryClient) QueryAllPairsValConAddrByConsumerChainID(ctx context.Context, in *QueryAllPairsValConAddrByConsumerChainIDRequest, opts ...grpc.CallOption) (*QueryAllPairsValConAddrByConsumerChainIDResponse, error) { - out := new(QueryAllPairsValConAddrByConsumerChainIDResponse) - err := c.cc.Invoke(ctx, "/interchain_security.ccv.provider.v1.Query/QueryAllPairsValConAddrByConsumerChainID", in, out, opts...) +func (c *queryClient) QueryAllPairsValConsAddrByConsumer(ctx context.Context, in *QueryAllPairsValConsAddrByConsumerRequest, opts ...grpc.CallOption) (*QueryAllPairsValConsAddrByConsumerResponse, error) { + out := new(QueryAllPairsValConsAddrByConsumerResponse) + err := c.cc.Invoke(ctx, "/interchain_security.ccv.provider.v1.Query/QueryAllPairsValConsAddrByConsumer", in, out, opts...) if err != nil { return nil, err } @@ -2145,6 +2170,24 @@ func (c *queryClient) QueryBlocksUntilNextEpoch(ctx context.Context, in *QueryBl return out, nil } +func (c *queryClient) QueryConsumerIdFromClientId(ctx context.Context, in *QueryConsumerIdFromClientIdRequest, opts ...grpc.CallOption) (*QueryConsumerIdFromClientIdResponse, error) { + out := new(QueryConsumerIdFromClientIdResponse) + err := c.cc.Invoke(ctx, "/interchain_security.ccv.provider.v1.Query/QueryConsumerIdFromClientId", in, out, opts...) + if err != nil { + return nil, err + } + return out, nil +} + +func (c *queryClient) QueryConsumerChain(ctx context.Context, in *QueryConsumerChainRequest, opts ...grpc.CallOption) (*QueryConsumerChainResponse, error) { + out := new(QueryConsumerChainResponse) + err := c.cc.Invoke(ctx, "/interchain_security.ccv.provider.v1.Query/QueryConsumerChain", in, out, opts...) + if err != nil { + return nil, err + } + return out, nil +} + // QueryServer is the server API for Query service. type QueryServer interface { // ConsumerGenesis queries the genesis state needed to start a consumer chain @@ -2153,10 +2196,6 @@ type QueryServer interface { // ConsumerChains queries active consumer chains supported by the provider // chain QueryConsumerChains(context.Context, *QueryConsumerChainsRequest) (*QueryConsumerChainsResponse, error) - // QueryConsumerChainStarts queries consumer chain start proposals. - QueryConsumerChainStarts(context.Context, *QueryConsumerChainStartProposalsRequest) (*QueryConsumerChainStartProposalsResponse, error) - // QueryConsumerChainStops queries consumer chain stop proposals. - QueryConsumerChainStops(context.Context, *QueryConsumerChainStopProposalsRequest) (*QueryConsumerChainStopProposalsResponse, error) // QueryValidatorConsumerAddr queries the address // assigned by a validator for a consumer chain. QueryValidatorConsumerAddr(context.Context, *QueryValidatorConsumerAddrRequest) (*QueryValidatorConsumerAddrResponse, error) @@ -2169,12 +2208,9 @@ type QueryServer interface { // QueryRegisteredConsumerRewardDenoms returns a list of consumer reward // denoms that are registered QueryRegisteredConsumerRewardDenoms(context.Context, *QueryRegisteredConsumerRewardDenomsRequest) (*QueryRegisteredConsumerRewardDenomsResponse, error) - // QueryProposedConsumerChainIDs returns the chain IDs of the proposed consumer chain addition proposals - // that are still in the voting period - QueryProposedConsumerChainIDs(context.Context, *QueryProposedChainIDsRequest) (*QueryProposedChainIDsResponse, error) - // QueryAllPairsValConAddrByConsumerChainID returns a list of pair valconsensus address + // QueryAllPairsValConsAddrByConsumer returns a list of pair valconsensus address // between provider and consumer chain - QueryAllPairsValConAddrByConsumerChainID(context.Context, *QueryAllPairsValConAddrByConsumerChainIDRequest) (*QueryAllPairsValConAddrByConsumerChainIDResponse, error) + QueryAllPairsValConsAddrByConsumer(context.Context, *QueryAllPairsValConsAddrByConsumerRequest) (*QueryAllPairsValConsAddrByConsumerResponse, error) // QueryParams returns all current values of provider parameters QueryParams(context.Context, *QueryParamsRequest) (*QueryParamsResponse, error) // QueryConsumerChainOptedInValidators returns a list of validators consensus addresses @@ -2186,13 +2222,19 @@ type QueryServer interface { // QueryValidatorConsumerCommissionRate returns the commission rate a given // validator charges on a given consumer chain QueryValidatorConsumerCommissionRate(context.Context, *QueryValidatorConsumerCommissionRateRequest) (*QueryValidatorConsumerCommissionRateResponse, error) - // QueryConsumerValidators returns the latest set consumer-validator set for a given chainID + // QueryConsumerValidators returns the latest set consumer-validator set for a given consumer ID // Note that this does not necessarily mean that the consumer chain is using this validator set at this exact moment // because a VSCPacket could be delayed to be delivered on the consumer chain. QueryConsumerValidators(context.Context, *QueryConsumerValidatorsRequest) (*QueryConsumerValidatorsResponse, error) // QueryBlocksUntilNextEpoch returns the number of blocks until the next epoch // starts and validator updates are sent to the consumer chains QueryBlocksUntilNextEpoch(context.Context, *QueryBlocksUntilNextEpochRequest) (*QueryBlocksUntilNextEpochResponse, error) + // QueryConsumerIdFromClientId returns the consumer id of the chain + // associated with the provided client id + QueryConsumerIdFromClientId(context.Context, *QueryConsumerIdFromClientIdRequest) (*QueryConsumerIdFromClientIdResponse, error) + // QueryConsumerChain returns the consumer chain + // associated with the provided consumer id + QueryConsumerChain(context.Context, *QueryConsumerChainRequest) (*QueryConsumerChainResponse, error) } // UnimplementedQueryServer can be embedded to have forward compatible implementations. @@ -2205,12 +2247,6 @@ func (*UnimplementedQueryServer) QueryConsumerGenesis(ctx context.Context, req * func (*UnimplementedQueryServer) QueryConsumerChains(ctx context.Context, req *QueryConsumerChainsRequest) (*QueryConsumerChainsResponse, error) { return nil, status.Errorf(codes.Unimplemented, "method QueryConsumerChains not implemented") } -func (*UnimplementedQueryServer) QueryConsumerChainStarts(ctx context.Context, req *QueryConsumerChainStartProposalsRequest) (*QueryConsumerChainStartProposalsResponse, error) { - return nil, status.Errorf(codes.Unimplemented, "method QueryConsumerChainStarts not implemented") -} -func (*UnimplementedQueryServer) QueryConsumerChainStops(ctx context.Context, req *QueryConsumerChainStopProposalsRequest) (*QueryConsumerChainStopProposalsResponse, error) { - return nil, status.Errorf(codes.Unimplemented, "method QueryConsumerChainStops not implemented") -} func (*UnimplementedQueryServer) QueryValidatorConsumerAddr(ctx context.Context, req *QueryValidatorConsumerAddrRequest) (*QueryValidatorConsumerAddrResponse, error) { return nil, status.Errorf(codes.Unimplemented, "method QueryValidatorConsumerAddr not implemented") } @@ -2223,11 +2259,8 @@ func (*UnimplementedQueryServer) QueryThrottleState(ctx context.Context, req *Qu func (*UnimplementedQueryServer) QueryRegisteredConsumerRewardDenoms(ctx context.Context, req *QueryRegisteredConsumerRewardDenomsRequest) (*QueryRegisteredConsumerRewardDenomsResponse, error) { return nil, status.Errorf(codes.Unimplemented, "method QueryRegisteredConsumerRewardDenoms not implemented") } -func (*UnimplementedQueryServer) QueryProposedConsumerChainIDs(ctx context.Context, req *QueryProposedChainIDsRequest) (*QueryProposedChainIDsResponse, error) { - return nil, status.Errorf(codes.Unimplemented, "method QueryProposedConsumerChainIDs not implemented") -} -func (*UnimplementedQueryServer) QueryAllPairsValConAddrByConsumerChainID(ctx context.Context, req *QueryAllPairsValConAddrByConsumerChainIDRequest) (*QueryAllPairsValConAddrByConsumerChainIDResponse, error) { - return nil, status.Errorf(codes.Unimplemented, "method QueryAllPairsValConAddrByConsumerChainID not implemented") +func (*UnimplementedQueryServer) QueryAllPairsValConsAddrByConsumer(ctx context.Context, req *QueryAllPairsValConsAddrByConsumerRequest) (*QueryAllPairsValConsAddrByConsumerResponse, error) { + return nil, status.Errorf(codes.Unimplemented, "method QueryAllPairsValConsAddrByConsumer not implemented") } func (*UnimplementedQueryServer) QueryParams(ctx context.Context, req *QueryParamsRequest) (*QueryParamsResponse, error) { return nil, status.Errorf(codes.Unimplemented, "method QueryParams not implemented") @@ -2247,6 +2280,12 @@ func (*UnimplementedQueryServer) QueryConsumerValidators(ctx context.Context, re func (*UnimplementedQueryServer) QueryBlocksUntilNextEpoch(ctx context.Context, req *QueryBlocksUntilNextEpochRequest) (*QueryBlocksUntilNextEpochResponse, error) { return nil, status.Errorf(codes.Unimplemented, "method QueryBlocksUntilNextEpoch not implemented") } +func (*UnimplementedQueryServer) QueryConsumerIdFromClientId(ctx context.Context, req *QueryConsumerIdFromClientIdRequest) (*QueryConsumerIdFromClientIdResponse, error) { + return nil, status.Errorf(codes.Unimplemented, "method QueryConsumerIdFromClientId not implemented") +} +func (*UnimplementedQueryServer) QueryConsumerChain(ctx context.Context, req *QueryConsumerChainRequest) (*QueryConsumerChainResponse, error) { + return nil, status.Errorf(codes.Unimplemented, "method QueryConsumerChain not implemented") +} func RegisterQueryServer(s grpc1.Server, srv QueryServer) { s.RegisterService(&_Query_serviceDesc, srv) @@ -2288,42 +2327,6 @@ func _Query_QueryConsumerChains_Handler(srv interface{}, ctx context.Context, de return interceptor(ctx, in, info, handler) } -func _Query_QueryConsumerChainStarts_Handler(srv interface{}, ctx context.Context, dec func(interface{}) error, interceptor grpc.UnaryServerInterceptor) (interface{}, error) { - in := new(QueryConsumerChainStartProposalsRequest) - if err := dec(in); err != nil { - return nil, err - } - if interceptor == nil { - return srv.(QueryServer).QueryConsumerChainStarts(ctx, in) - } - info := &grpc.UnaryServerInfo{ - Server: srv, - FullMethod: "/interchain_security.ccv.provider.v1.Query/QueryConsumerChainStarts", - } - handler := func(ctx context.Context, req interface{}) (interface{}, error) { - return srv.(QueryServer).QueryConsumerChainStarts(ctx, req.(*QueryConsumerChainStartProposalsRequest)) - } - return interceptor(ctx, in, info, handler) -} - -func _Query_QueryConsumerChainStops_Handler(srv interface{}, ctx context.Context, dec func(interface{}) error, interceptor grpc.UnaryServerInterceptor) (interface{}, error) { - in := new(QueryConsumerChainStopProposalsRequest) - if err := dec(in); err != nil { - return nil, err - } - if interceptor == nil { - return srv.(QueryServer).QueryConsumerChainStops(ctx, in) - } - info := &grpc.UnaryServerInfo{ - Server: srv, - FullMethod: "/interchain_security.ccv.provider.v1.Query/QueryConsumerChainStops", - } - handler := func(ctx context.Context, req interface{}) (interface{}, error) { - return srv.(QueryServer).QueryConsumerChainStops(ctx, req.(*QueryConsumerChainStopProposalsRequest)) - } - return interceptor(ctx, in, info, handler) -} - func _Query_QueryValidatorConsumerAddr_Handler(srv interface{}, ctx context.Context, dec func(interface{}) error, interceptor grpc.UnaryServerInterceptor) (interface{}, error) { in := new(QueryValidatorConsumerAddrRequest) if err := dec(in); err != nil { @@ -2396,38 +2399,20 @@ func _Query_QueryRegisteredConsumerRewardDenoms_Handler(srv interface{}, ctx con return interceptor(ctx, in, info, handler) } -func _Query_QueryProposedConsumerChainIDs_Handler(srv interface{}, ctx context.Context, dec func(interface{}) error, interceptor grpc.UnaryServerInterceptor) (interface{}, error) { - in := new(QueryProposedChainIDsRequest) - if err := dec(in); err != nil { - return nil, err - } - if interceptor == nil { - return srv.(QueryServer).QueryProposedConsumerChainIDs(ctx, in) - } - info := &grpc.UnaryServerInfo{ - Server: srv, - FullMethod: "/interchain_security.ccv.provider.v1.Query/QueryProposedConsumerChainIDs", - } - handler := func(ctx context.Context, req interface{}) (interface{}, error) { - return srv.(QueryServer).QueryProposedConsumerChainIDs(ctx, req.(*QueryProposedChainIDsRequest)) - } - return interceptor(ctx, in, info, handler) -} - -func _Query_QueryAllPairsValConAddrByConsumerChainID_Handler(srv interface{}, ctx context.Context, dec func(interface{}) error, interceptor grpc.UnaryServerInterceptor) (interface{}, error) { - in := new(QueryAllPairsValConAddrByConsumerChainIDRequest) +func _Query_QueryAllPairsValConsAddrByConsumer_Handler(srv interface{}, ctx context.Context, dec func(interface{}) error, interceptor grpc.UnaryServerInterceptor) (interface{}, error) { + in := new(QueryAllPairsValConsAddrByConsumerRequest) if err := dec(in); err != nil { return nil, err } if interceptor == nil { - return srv.(QueryServer).QueryAllPairsValConAddrByConsumerChainID(ctx, in) + return srv.(QueryServer).QueryAllPairsValConsAddrByConsumer(ctx, in) } info := &grpc.UnaryServerInfo{ Server: srv, - FullMethod: "/interchain_security.ccv.provider.v1.Query/QueryAllPairsValConAddrByConsumerChainID", + FullMethod: "/interchain_security.ccv.provider.v1.Query/QueryAllPairsValConsAddrByConsumer", } handler := func(ctx context.Context, req interface{}) (interface{}, error) { - return srv.(QueryServer).QueryAllPairsValConAddrByConsumerChainID(ctx, req.(*QueryAllPairsValConAddrByConsumerChainIDRequest)) + return srv.(QueryServer).QueryAllPairsValConsAddrByConsumer(ctx, req.(*QueryAllPairsValConsAddrByConsumerRequest)) } return interceptor(ctx, in, info, handler) } @@ -2540,10 +2525,46 @@ func _Query_QueryBlocksUntilNextEpoch_Handler(srv interface{}, ctx context.Conte return interceptor(ctx, in, info, handler) } -var _Query_serviceDesc = grpc.ServiceDesc{ - ServiceName: "interchain_security.ccv.provider.v1.Query", - HandlerType: (*QueryServer)(nil), - Methods: []grpc.MethodDesc{ +func _Query_QueryConsumerIdFromClientId_Handler(srv interface{}, ctx context.Context, dec func(interface{}) error, interceptor grpc.UnaryServerInterceptor) (interface{}, error) { + in := new(QueryConsumerIdFromClientIdRequest) + if err := dec(in); err != nil { + return nil, err + } + if interceptor == nil { + return srv.(QueryServer).QueryConsumerIdFromClientId(ctx, in) + } + info := &grpc.UnaryServerInfo{ + Server: srv, + FullMethod: "/interchain_security.ccv.provider.v1.Query/QueryConsumerIdFromClientId", + } + handler := func(ctx context.Context, req interface{}) (interface{}, error) { + return srv.(QueryServer).QueryConsumerIdFromClientId(ctx, req.(*QueryConsumerIdFromClientIdRequest)) + } + return interceptor(ctx, in, info, handler) +} + +func _Query_QueryConsumerChain_Handler(srv interface{}, ctx context.Context, dec func(interface{}) error, interceptor grpc.UnaryServerInterceptor) (interface{}, error) { + in := new(QueryConsumerChainRequest) + if err := dec(in); err != nil { + return nil, err + } + if interceptor == nil { + return srv.(QueryServer).QueryConsumerChain(ctx, in) + } + info := &grpc.UnaryServerInfo{ + Server: srv, + FullMethod: "/interchain_security.ccv.provider.v1.Query/QueryConsumerChain", + } + handler := func(ctx context.Context, req interface{}) (interface{}, error) { + return srv.(QueryServer).QueryConsumerChain(ctx, req.(*QueryConsumerChainRequest)) + } + return interceptor(ctx, in, info, handler) +} + +var _Query_serviceDesc = grpc.ServiceDesc{ + ServiceName: "interchain_security.ccv.provider.v1.Query", + HandlerType: (*QueryServer)(nil), + Methods: []grpc.MethodDesc{ { MethodName: "QueryConsumerGenesis", Handler: _Query_QueryConsumerGenesis_Handler, @@ -2552,14 +2573,6 @@ var _Query_serviceDesc = grpc.ServiceDesc{ MethodName: "QueryConsumerChains", Handler: _Query_QueryConsumerChains_Handler, }, - { - MethodName: "QueryConsumerChainStarts", - Handler: _Query_QueryConsumerChainStarts_Handler, - }, - { - MethodName: "QueryConsumerChainStops", - Handler: _Query_QueryConsumerChainStops_Handler, - }, { MethodName: "QueryValidatorConsumerAddr", Handler: _Query_QueryValidatorConsumerAddr_Handler, @@ -2577,12 +2590,8 @@ var _Query_serviceDesc = grpc.ServiceDesc{ Handler: _Query_QueryRegisteredConsumerRewardDenoms_Handler, }, { - MethodName: "QueryProposedConsumerChainIDs", - Handler: _Query_QueryProposedConsumerChainIDs_Handler, - }, - { - MethodName: "QueryAllPairsValConAddrByConsumerChainID", - Handler: _Query_QueryAllPairsValConAddrByConsumerChainID_Handler, + MethodName: "QueryAllPairsValConsAddrByConsumer", + Handler: _Query_QueryAllPairsValConsAddrByConsumer_Handler, }, { MethodName: "QueryParams", @@ -2608,6 +2617,14 @@ var _Query_serviceDesc = grpc.ServiceDesc{ MethodName: "QueryBlocksUntilNextEpoch", Handler: _Query_QueryBlocksUntilNextEpoch_Handler, }, + { + MethodName: "QueryConsumerIdFromClientId", + Handler: _Query_QueryConsumerIdFromClientId_Handler, + }, + { + MethodName: "QueryConsumerChain", + Handler: _Query_QueryConsumerChain_Handler, + }, }, Streams: []grpc.StreamDesc{}, Metadata: "interchain_security/ccv/provider/v1/query.proto", @@ -2633,10 +2650,10 @@ func (m *QueryConsumerGenesisRequest) MarshalToSizedBuffer(dAtA []byte) (int, er _ = i var l int _ = l - if len(m.ChainId) > 0 { - i -= len(m.ChainId) - copy(dAtA[i:], m.ChainId) - i = encodeVarintQuery(dAtA, i, uint64(len(m.ChainId))) + if len(m.ConsumerId) > 0 { + i -= len(m.ConsumerId) + copy(dAtA[i:], m.ConsumerId) + i = encodeVarintQuery(dAtA, i, uint64(len(m.ConsumerId))) i-- dAtA[i] = 0xa } @@ -2696,6 +2713,16 @@ func (m *QueryConsumerChainsRequest) MarshalToSizedBuffer(dAtA []byte) (int, err _ = i var l int _ = l + if m.Limit != 0 { + i = encodeVarintQuery(dAtA, i, uint64(m.Limit)) + i-- + dAtA[i] = 0x10 + } + if m.Phase != 0 { + i = encodeVarintQuery(dAtA, i, uint64(m.Phase)) + i-- + dAtA[i] = 0x8 + } return len(dAtA) - i, nil } @@ -2736,122 +2763,6 @@ func (m *QueryConsumerChainsResponse) MarshalToSizedBuffer(dAtA []byte) (int, er return len(dAtA) - i, nil } -func (m *QueryConsumerChainStartProposalsRequest) 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 *QueryConsumerChainStartProposalsRequest) MarshalTo(dAtA []byte) (int, error) { - size := m.Size() - return m.MarshalToSizedBuffer(dAtA[:size]) -} - -func (m *QueryConsumerChainStartProposalsRequest) MarshalToSizedBuffer(dAtA []byte) (int, error) { - i := len(dAtA) - _ = i - var l int - _ = l - return len(dAtA) - i, nil -} - -func (m *QueryConsumerChainStartProposalsResponse) 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 *QueryConsumerChainStartProposalsResponse) MarshalTo(dAtA []byte) (int, error) { - size := m.Size() - return m.MarshalToSizedBuffer(dAtA[:size]) -} - -func (m *QueryConsumerChainStartProposalsResponse) MarshalToSizedBuffer(dAtA []byte) (int, error) { - i := len(dAtA) - _ = i - var l int - _ = l - if m.Proposals != nil { - { - size, err := m.Proposals.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 *QueryConsumerChainStopProposalsRequest) 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 *QueryConsumerChainStopProposalsRequest) MarshalTo(dAtA []byte) (int, error) { - size := m.Size() - return m.MarshalToSizedBuffer(dAtA[:size]) -} - -func (m *QueryConsumerChainStopProposalsRequest) MarshalToSizedBuffer(dAtA []byte) (int, error) { - i := len(dAtA) - _ = i - var l int - _ = l - return len(dAtA) - i, nil -} - -func (m *QueryConsumerChainStopProposalsResponse) 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 *QueryConsumerChainStopProposalsResponse) MarshalTo(dAtA []byte) (int, error) { - size := m.Size() - return m.MarshalToSizedBuffer(dAtA[:size]) -} - -func (m *QueryConsumerChainStopProposalsResponse) MarshalToSizedBuffer(dAtA []byte) (int, error) { - i := len(dAtA) - _ = i - var l int - _ = l - if m.Proposals != nil { - { - size, err := m.Proposals.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 *Chain) Marshal() (dAtA []byte, err error) { size := m.Size() dAtA = make([]byte, size) @@ -2872,6 +2783,13 @@ func (m *Chain) MarshalToSizedBuffer(dAtA []byte) (int, error) { _ = i var l int _ = l + if len(m.ConsumerId) > 0 { + i -= len(m.ConsumerId) + copy(dAtA[i:], m.ConsumerId) + i = encodeVarintQuery(dAtA, i, uint64(len(m.ConsumerId))) + i-- + dAtA[i] = 0x6a + } if m.AllowInactiveVals { i-- if m.AllowInactiveVals { @@ -2880,12 +2798,29 @@ func (m *Chain) MarshalToSizedBuffer(dAtA []byte) (int, error) { dAtA[i] = 0 } i-- - dAtA[i] = 0x50 + dAtA[i] = 0x60 } if m.MinStake != 0 { i = encodeVarintQuery(dAtA, i, uint64(m.MinStake)) i-- - dAtA[i] = 0x48 + dAtA[i] = 0x58 + } + { + size, err := m.Metadata.MarshalToSizedBuffer(dAtA[:i]) + if err != nil { + return 0, err + } + i -= size + i = encodeVarintQuery(dAtA, i, uint64(size)) + } + i-- + dAtA[i] = 0x52 + if len(m.Phase) > 0 { + i -= len(m.Phase) + copy(dAtA[i:], m.Phase) + i = encodeVarintQuery(dAtA, i, uint64(len(m.Phase))) + i-- + dAtA[i] = 0x4a } if len(m.Denylist) > 0 { for iNdEx := len(m.Denylist) - 1; iNdEx >= 0; iNdEx-- { @@ -2962,18 +2897,18 @@ func (m *QueryValidatorConsumerAddrRequest) MarshalToSizedBuffer(dAtA []byte) (i _ = i var l int _ = l + if len(m.ConsumerId) > 0 { + i -= len(m.ConsumerId) + copy(dAtA[i:], m.ConsumerId) + i = encodeVarintQuery(dAtA, i, uint64(len(m.ConsumerId))) + i-- + dAtA[i] = 0x12 + } if len(m.ProviderAddress) > 0 { i -= len(m.ProviderAddress) copy(dAtA[i:], m.ProviderAddress) i = encodeVarintQuery(dAtA, i, uint64(len(m.ProviderAddress))) i-- - dAtA[i] = 0x12 - } - if len(m.ChainId) > 0 { - i -= len(m.ChainId) - copy(dAtA[i:], m.ChainId) - i = encodeVarintQuery(dAtA, i, uint64(len(m.ChainId))) - i-- dAtA[i] = 0xa } return len(dAtA) - i, nil @@ -3029,18 +2964,18 @@ func (m *QueryValidatorProviderAddrRequest) MarshalToSizedBuffer(dAtA []byte) (i _ = i var l int _ = l + if len(m.ConsumerId) > 0 { + i -= len(m.ConsumerId) + copy(dAtA[i:], m.ConsumerId) + i = encodeVarintQuery(dAtA, i, uint64(len(m.ConsumerId))) + i-- + dAtA[i] = 0x12 + } if len(m.ConsumerAddress) > 0 { i -= len(m.ConsumerAddress) copy(dAtA[i:], m.ConsumerAddress) i = encodeVarintQuery(dAtA, i, uint64(len(m.ConsumerAddress))) i-- - dAtA[i] = 0x12 - } - if len(m.ChainId) > 0 { - i -= len(m.ChainId) - copy(dAtA[i:], m.ChainId) - i = encodeVarintQuery(dAtA, i, uint64(len(m.ChainId))) - i-- dAtA[i] = 0xa } return len(dAtA) - i, nil @@ -3119,12 +3054,12 @@ func (m *QueryThrottleStateResponse) MarshalToSizedBuffer(dAtA []byte) (int, err _ = i var l int _ = l - n4, err4 := github_com_cosmos_gogoproto_types.StdTimeMarshalTo(m.NextReplenishCandidate, dAtA[i-github_com_cosmos_gogoproto_types.SizeOfStdTime(m.NextReplenishCandidate):]) - if err4 != nil { - return 0, err4 + n3, err3 := github_com_cosmos_gogoproto_types.StdTimeMarshalTo(m.NextReplenishCandidate, dAtA[i-github_com_cosmos_gogoproto_types.SizeOfStdTime(m.NextReplenishCandidate):]) + if err3 != nil { + return 0, err3 } - i -= n4 - i = encodeVarintQuery(dAtA, i, uint64(n4)) + i -= n3 + i = encodeVarintQuery(dAtA, i, uint64(n3)) i-- dAtA[i] = 0x1a if m.SlashMeterAllowance != 0 { @@ -3195,7 +3130,7 @@ func (m *QueryRegisteredConsumerRewardDenomsResponse) MarshalToSizedBuffer(dAtA return len(dAtA) - i, nil } -func (m *QueryProposedChainIDsRequest) Marshal() (dAtA []byte, err error) { +func (m *QueryAllPairsValConsAddrByConsumerRequest) Marshal() (dAtA []byte, err error) { size := m.Size() dAtA = make([]byte, size) n, err := m.MarshalToSizedBuffer(dAtA[:size]) @@ -3205,20 +3140,27 @@ func (m *QueryProposedChainIDsRequest) Marshal() (dAtA []byte, err error) { return dAtA[:n], nil } -func (m *QueryProposedChainIDsRequest) MarshalTo(dAtA []byte) (int, error) { +func (m *QueryAllPairsValConsAddrByConsumerRequest) MarshalTo(dAtA []byte) (int, error) { size := m.Size() return m.MarshalToSizedBuffer(dAtA[:size]) } -func (m *QueryProposedChainIDsRequest) MarshalToSizedBuffer(dAtA []byte) (int, error) { +func (m *QueryAllPairsValConsAddrByConsumerRequest) MarshalToSizedBuffer(dAtA []byte) (int, error) { i := len(dAtA) _ = i var l int _ = l + if len(m.ConsumerId) > 0 { + i -= len(m.ConsumerId) + copy(dAtA[i:], m.ConsumerId) + i = encodeVarintQuery(dAtA, i, uint64(len(m.ConsumerId))) + i-- + dAtA[i] = 0xa + } return len(dAtA) - i, nil } -func (m *QueryProposedChainIDsResponse) Marshal() (dAtA []byte, err error) { +func (m *QueryAllPairsValConsAddrByConsumerResponse) Marshal() (dAtA []byte, err error) { size := m.Size() dAtA = make([]byte, size) n, err := m.MarshalToSizedBuffer(dAtA[:size]) @@ -3228,20 +3170,20 @@ func (m *QueryProposedChainIDsResponse) Marshal() (dAtA []byte, err error) { return dAtA[:n], nil } -func (m *QueryProposedChainIDsResponse) MarshalTo(dAtA []byte) (int, error) { +func (m *QueryAllPairsValConsAddrByConsumerResponse) MarshalTo(dAtA []byte) (int, error) { size := m.Size() return m.MarshalToSizedBuffer(dAtA[:size]) } -func (m *QueryProposedChainIDsResponse) MarshalToSizedBuffer(dAtA []byte) (int, error) { +func (m *QueryAllPairsValConsAddrByConsumerResponse) MarshalToSizedBuffer(dAtA []byte) (int, error) { i := len(dAtA) _ = i var l int _ = l - if len(m.ProposedChains) > 0 { - for iNdEx := len(m.ProposedChains) - 1; iNdEx >= 0; iNdEx-- { + if len(m.PairValConAddr) > 0 { + for iNdEx := len(m.PairValConAddr) - 1; iNdEx >= 0; iNdEx-- { { - size, err := m.ProposedChains[iNdEx].MarshalToSizedBuffer(dAtA[:i]) + size, err := m.PairValConAddr[iNdEx].MarshalToSizedBuffer(dAtA[:i]) if err != nil { return 0, err } @@ -3255,7 +3197,7 @@ func (m *QueryProposedChainIDsResponse) MarshalToSizedBuffer(dAtA []byte) (int, return len(dAtA) - i, nil } -func (m *ProposedChain) Marshal() (dAtA []byte, err error) { +func (m *PairValConAddrProviderAndConsumer) Marshal() (dAtA []byte, err error) { size := m.Size() dAtA = make([]byte, size) n, err := m.MarshalToSizedBuffer(dAtA[:size]) @@ -3265,32 +3207,46 @@ func (m *ProposedChain) Marshal() (dAtA []byte, err error) { return dAtA[:n], nil } -func (m *ProposedChain) MarshalTo(dAtA []byte) (int, error) { +func (m *PairValConAddrProviderAndConsumer) MarshalTo(dAtA []byte) (int, error) { size := m.Size() return m.MarshalToSizedBuffer(dAtA[:size]) } -func (m *ProposedChain) MarshalToSizedBuffer(dAtA []byte) (int, error) { +func (m *PairValConAddrProviderAndConsumer) MarshalToSizedBuffer(dAtA []byte) (int, error) { i := len(dAtA) _ = i var l int _ = l - if m.ProposalID != 0 { - i = encodeVarintQuery(dAtA, i, uint64(m.ProposalID)) + if m.ConsumerKey != nil { + { + size, err := m.ConsumerKey.MarshalToSizedBuffer(dAtA[:i]) + if err != nil { + return 0, err + } + i -= size + i = encodeVarintQuery(dAtA, i, uint64(size)) + } i-- - dAtA[i] = 0x10 + dAtA[i] = 0x1a + } + if len(m.ConsumerAddress) > 0 { + i -= len(m.ConsumerAddress) + copy(dAtA[i:], m.ConsumerAddress) + i = encodeVarintQuery(dAtA, i, uint64(len(m.ConsumerAddress))) + i-- + dAtA[i] = 0x12 } - if len(m.ChainID) > 0 { - i -= len(m.ChainID) - copy(dAtA[i:], m.ChainID) - i = encodeVarintQuery(dAtA, i, uint64(len(m.ChainID))) + if len(m.ProviderAddress) > 0 { + i -= len(m.ProviderAddress) + copy(dAtA[i:], m.ProviderAddress) + i = encodeVarintQuery(dAtA, i, uint64(len(m.ProviderAddress))) i-- dAtA[i] = 0xa } return len(dAtA) - i, nil } -func (m *QueryAllPairsValConAddrByConsumerChainIDRequest) Marshal() (dAtA []byte, err error) { +func (m *QueryParamsRequest) Marshal() (dAtA []byte, err error) { size := m.Size() dAtA = make([]byte, size) n, err := m.MarshalToSizedBuffer(dAtA[:size]) @@ -3300,27 +3256,20 @@ func (m *QueryAllPairsValConAddrByConsumerChainIDRequest) Marshal() (dAtA []byte return dAtA[:n], nil } -func (m *QueryAllPairsValConAddrByConsumerChainIDRequest) MarshalTo(dAtA []byte) (int, error) { +func (m *QueryParamsRequest) MarshalTo(dAtA []byte) (int, error) { size := m.Size() return m.MarshalToSizedBuffer(dAtA[:size]) } -func (m *QueryAllPairsValConAddrByConsumerChainIDRequest) MarshalToSizedBuffer(dAtA []byte) (int, error) { +func (m *QueryParamsRequest) MarshalToSizedBuffer(dAtA []byte) (int, error) { i := len(dAtA) _ = i var l int _ = l - if len(m.ChainId) > 0 { - i -= len(m.ChainId) - copy(dAtA[i:], m.ChainId) - i = encodeVarintQuery(dAtA, i, uint64(len(m.ChainId))) - i-- - dAtA[i] = 0xa - } return len(dAtA) - i, nil } -func (m *QueryAllPairsValConAddrByConsumerChainIDResponse) Marshal() (dAtA []byte, err error) { +func (m *QueryParamsResponse) Marshal() (dAtA []byte, err error) { size := m.Size() dAtA = make([]byte, size) n, err := m.MarshalToSizedBuffer(dAtA[:size]) @@ -3330,34 +3279,30 @@ func (m *QueryAllPairsValConAddrByConsumerChainIDResponse) Marshal() (dAtA []byt return dAtA[:n], nil } -func (m *QueryAllPairsValConAddrByConsumerChainIDResponse) MarshalTo(dAtA []byte) (int, error) { +func (m *QueryParamsResponse) MarshalTo(dAtA []byte) (int, error) { size := m.Size() return m.MarshalToSizedBuffer(dAtA[:size]) } -func (m *QueryAllPairsValConAddrByConsumerChainIDResponse) MarshalToSizedBuffer(dAtA []byte) (int, error) { +func (m *QueryParamsResponse) MarshalToSizedBuffer(dAtA []byte) (int, error) { i := len(dAtA) _ = i var l int _ = l - if len(m.PairValConAddr) > 0 { - for iNdEx := len(m.PairValConAddr) - 1; iNdEx >= 0; iNdEx-- { - { - size, err := m.PairValConAddr[iNdEx].MarshalToSizedBuffer(dAtA[:i]) - if err != nil { - return 0, err - } - i -= size - i = encodeVarintQuery(dAtA, i, uint64(size)) - } - i-- - dAtA[i] = 0xa + { + size, err := m.Params.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 *PairValConAddrProviderAndConsumer) Marshal() (dAtA []byte, err error) { +func (m *QueryConsumerChainOptedInValidatorsRequest) Marshal() (dAtA []byte, err error) { size := m.Size() dAtA = make([]byte, size) n, err := m.MarshalToSizedBuffer(dAtA[:size]) @@ -3367,125 +3312,20 @@ func (m *PairValConAddrProviderAndConsumer) Marshal() (dAtA []byte, err error) { return dAtA[:n], nil } -func (m *PairValConAddrProviderAndConsumer) MarshalTo(dAtA []byte) (int, error) { +func (m *QueryConsumerChainOptedInValidatorsRequest) MarshalTo(dAtA []byte) (int, error) { size := m.Size() return m.MarshalToSizedBuffer(dAtA[:size]) } -func (m *PairValConAddrProviderAndConsumer) MarshalToSizedBuffer(dAtA []byte) (int, error) { +func (m *QueryConsumerChainOptedInValidatorsRequest) MarshalToSizedBuffer(dAtA []byte) (int, error) { i := len(dAtA) _ = i var l int _ = l - if m.ConsumerKey != nil { - { - size, err := m.ConsumerKey.MarshalToSizedBuffer(dAtA[:i]) - if err != nil { - return 0, err - } - i -= size - i = encodeVarintQuery(dAtA, i, uint64(size)) - } - i-- - dAtA[i] = 0x1a - } - if len(m.ConsumerAddress) > 0 { - i -= len(m.ConsumerAddress) - copy(dAtA[i:], m.ConsumerAddress) - i = encodeVarintQuery(dAtA, i, uint64(len(m.ConsumerAddress))) - i-- - dAtA[i] = 0x12 - } - if len(m.ProviderAddress) > 0 { - i -= len(m.ProviderAddress) - copy(dAtA[i:], m.ProviderAddress) - i = encodeVarintQuery(dAtA, i, uint64(len(m.ProviderAddress))) - i-- - dAtA[i] = 0xa - } - return len(dAtA) - i, nil -} - -func (m *QueryParamsRequest) 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 *QueryParamsRequest) MarshalTo(dAtA []byte) (int, error) { - size := m.Size() - return m.MarshalToSizedBuffer(dAtA[:size]) -} - -func (m *QueryParamsRequest) MarshalToSizedBuffer(dAtA []byte) (int, error) { - i := len(dAtA) - _ = i - var l int - _ = l - return len(dAtA) - i, nil -} - -func (m *QueryParamsResponse) 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 *QueryParamsResponse) MarshalTo(dAtA []byte) (int, error) { - size := m.Size() - return m.MarshalToSizedBuffer(dAtA[:size]) -} - -func (m *QueryParamsResponse) MarshalToSizedBuffer(dAtA []byte) (int, error) { - i := len(dAtA) - _ = i - var l int - _ = l - { - size, err := m.Params.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 *QueryConsumerChainOptedInValidatorsRequest) 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 *QueryConsumerChainOptedInValidatorsRequest) MarshalTo(dAtA []byte) (int, error) { - size := m.Size() - return m.MarshalToSizedBuffer(dAtA[:size]) -} - -func (m *QueryConsumerChainOptedInValidatorsRequest) MarshalToSizedBuffer(dAtA []byte) (int, error) { - i := len(dAtA) - _ = i - var l int - _ = l - if len(m.ChainId) > 0 { - i -= len(m.ChainId) - copy(dAtA[i:], m.ChainId) - i = encodeVarintQuery(dAtA, i, uint64(len(m.ChainId))) + if len(m.ConsumerId) > 0 { + i -= len(m.ConsumerId) + copy(dAtA[i:], m.ConsumerId) + i = encodeVarintQuery(dAtA, i, uint64(len(m.ConsumerId))) i-- dAtA[i] = 0xa } @@ -3544,10 +3384,10 @@ func (m *QueryConsumerValidatorsRequest) MarshalToSizedBuffer(dAtA []byte) (int, _ = i var l int _ = l - if len(m.ChainId) > 0 { - i -= len(m.ChainId) - copy(dAtA[i:], m.ChainId) - i = encodeVarintQuery(dAtA, i, uint64(len(m.ChainId))) + if len(m.ConsumerId) > 0 { + i -= len(m.ConsumerId) + copy(dAtA[i:], m.ConsumerId) + i = encodeVarintQuery(dAtA, i, uint64(len(m.ConsumerId))) i-- dAtA[i] = 0xa } @@ -3574,6 +3414,88 @@ func (m *QueryConsumerValidatorsValidator) MarshalToSizedBuffer(dAtA []byte) (in _ = i var l int _ = l + if m.ValidatesCurrentEpoch { + i-- + if m.ValidatesCurrentEpoch { + dAtA[i] = 1 + } else { + dAtA[i] = 0 + } + i-- + dAtA[i] = 0x70 + } + if m.ProviderPower != 0 { + i = encodeVarintQuery(dAtA, i, uint64(m.ProviderPower)) + i-- + dAtA[i] = 0x68 + } + { + size := m.ProviderTokens.Size() + i -= size + if _, err := m.ProviderTokens.MarshalTo(dAtA[i:]); err != nil { + return 0, err + } + i = encodeVarintQuery(dAtA, i, uint64(size)) + } + i-- + dAtA[i] = 0x62 + if m.Status != 0 { + i = encodeVarintQuery(dAtA, i, uint64(m.Status)) + i-- + dAtA[i] = 0x58 + } + if m.Jailed { + i-- + if m.Jailed { + dAtA[i] = 1 + } else { + dAtA[i] = 0 + } + i-- + dAtA[i] = 0x50 + } + if len(m.ProviderOperatorAddress) > 0 { + i -= len(m.ProviderOperatorAddress) + copy(dAtA[i:], m.ProviderOperatorAddress) + i = encodeVarintQuery(dAtA, i, uint64(len(m.ProviderOperatorAddress))) + i-- + dAtA[i] = 0x4a + } + { + size, err := m.Description.MarshalToSizedBuffer(dAtA[:i]) + if err != nil { + return 0, err + } + i -= size + i = encodeVarintQuery(dAtA, i, uint64(size)) + } + i-- + dAtA[i] = 0x42 + { + size := m.ProviderCommissionRate.Size() + i -= size + if _, err := m.ProviderCommissionRate.MarshalTo(dAtA[i:]); err != nil { + return 0, err + } + i = encodeVarintQuery(dAtA, i, uint64(size)) + } + i-- + dAtA[i] = 0x3a + { + size := m.ConsumerCommissionRate.Size() + i -= size + if _, err := m.ConsumerCommissionRate.MarshalTo(dAtA[i:]); err != nil { + return 0, err + } + i = encodeVarintQuery(dAtA, i, uint64(size)) + } + i-- + dAtA[i] = 0x32 + if m.ConsumerPower != 0 { + i = encodeVarintQuery(dAtA, i, uint64(m.ConsumerPower)) + i-- + dAtA[i] = 0x28 + } { size := m.Rate.Size() i -= size @@ -3698,11 +3620,11 @@ func (m *QueryConsumerChainsValidatorHasToValidateResponse) MarshalToSizedBuffer _ = i var l int _ = l - if len(m.ConsumerChainIds) > 0 { - for iNdEx := len(m.ConsumerChainIds) - 1; iNdEx >= 0; iNdEx-- { - i -= len(m.ConsumerChainIds[iNdEx]) - copy(dAtA[i:], m.ConsumerChainIds[iNdEx]) - i = encodeVarintQuery(dAtA, i, uint64(len(m.ConsumerChainIds[iNdEx]))) + if len(m.ConsumerIds) > 0 { + for iNdEx := len(m.ConsumerIds) - 1; iNdEx >= 0; iNdEx-- { + i -= len(m.ConsumerIds[iNdEx]) + copy(dAtA[i:], m.ConsumerIds[iNdEx]) + i = encodeVarintQuery(dAtA, i, uint64(len(m.ConsumerIds[iNdEx]))) i-- dAtA[i] = 0xa } @@ -3737,10 +3659,10 @@ func (m *QueryValidatorConsumerCommissionRateRequest) MarshalToSizedBuffer(dAtA i-- dAtA[i] = 0x12 } - if len(m.ChainId) > 0 { - i -= len(m.ChainId) - copy(dAtA[i:], m.ChainId) - i = encodeVarintQuery(dAtA, i, uint64(len(m.ChainId))) + if len(m.ConsumerId) > 0 { + i -= len(m.ConsumerId) + copy(dAtA[i:], m.ConsumerId) + i = encodeVarintQuery(dAtA, i, uint64(len(m.ConsumerId))) i-- dAtA[i] = 0xa } @@ -3831,105 +3753,235 @@ func (m *QueryBlocksUntilNextEpochResponse) MarshalToSizedBuffer(dAtA []byte) (i 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++ +func (m *QueryConsumerIdFromClientIdRequest) Marshal() (dAtA []byte, err error) { + size := m.Size() + dAtA = make([]byte, size) + n, err := m.MarshalToSizedBuffer(dAtA[:size]) + if err != nil { + return nil, err } - dAtA[offset] = uint8(v) - return base + return dAtA[:n], nil } -func (m *QueryConsumerGenesisRequest) Size() (n int) { - if m == nil { - return 0 - } + +func (m *QueryConsumerIdFromClientIdRequest) MarshalTo(dAtA []byte) (int, error) { + size := m.Size() + return m.MarshalToSizedBuffer(dAtA[:size]) +} + +func (m *QueryConsumerIdFromClientIdRequest) MarshalToSizedBuffer(dAtA []byte) (int, error) { + i := len(dAtA) + _ = i var l int _ = l - l = len(m.ChainId) - if l > 0 { - n += 1 + l + sovQuery(uint64(l)) + if len(m.ClientId) > 0 { + i -= len(m.ClientId) + copy(dAtA[i:], m.ClientId) + i = encodeVarintQuery(dAtA, i, uint64(len(m.ClientId))) + i-- + dAtA[i] = 0xa } - return n + return len(dAtA) - i, nil } -func (m *QueryConsumerGenesisResponse) Size() (n int) { - if m == nil { - return 0 +func (m *QueryConsumerIdFromClientIdResponse) Marshal() (dAtA []byte, err error) { + size := m.Size() + dAtA = make([]byte, size) + n, err := m.MarshalToSizedBuffer(dAtA[:size]) + if err != nil { + return nil, err } - var l int - _ = l - l = m.GenesisState.Size() - n += 1 + l + sovQuery(uint64(l)) - return n + return dAtA[:n], nil } -func (m *QueryConsumerChainsRequest) Size() (n int) { - if m == nil { - return 0 - } - var l int - _ = l - return n +func (m *QueryConsumerIdFromClientIdResponse) MarshalTo(dAtA []byte) (int, error) { + size := m.Size() + return m.MarshalToSizedBuffer(dAtA[:size]) } -func (m *QueryConsumerChainsResponse) Size() (n int) { - if m == nil { - return 0 - } +func (m *QueryConsumerIdFromClientIdResponse) MarshalToSizedBuffer(dAtA []byte) (int, error) { + i := len(dAtA) + _ = i var l int _ = l - if len(m.Chains) > 0 { - for _, e := range m.Chains { - l = e.Size() - n += 1 + l + sovQuery(uint64(l)) - } + if len(m.ConsumerId) > 0 { + i -= len(m.ConsumerId) + copy(dAtA[i:], m.ConsumerId) + i = encodeVarintQuery(dAtA, i, uint64(len(m.ConsumerId))) + i-- + dAtA[i] = 0xa } - return n + return len(dAtA) - i, nil } -func (m *QueryConsumerChainStartProposalsRequest) Size() (n int) { - if m == nil { - return 0 +func (m *QueryConsumerChainRequest) Marshal() (dAtA []byte, err error) { + size := m.Size() + dAtA = make([]byte, size) + n, err := m.MarshalToSizedBuffer(dAtA[:size]) + if err != nil { + return nil, err } - var l int - _ = l - return n + return dAtA[:n], nil } -func (m *QueryConsumerChainStartProposalsResponse) Size() (n int) { - if m == nil { - return 0 - } +func (m *QueryConsumerChainRequest) MarshalTo(dAtA []byte) (int, error) { + size := m.Size() + return m.MarshalToSizedBuffer(dAtA[:size]) +} + +func (m *QueryConsumerChainRequest) MarshalToSizedBuffer(dAtA []byte) (int, error) { + i := len(dAtA) + _ = i + var l int + _ = l + if len(m.ConsumerId) > 0 { + i -= len(m.ConsumerId) + copy(dAtA[i:], m.ConsumerId) + i = encodeVarintQuery(dAtA, i, uint64(len(m.ConsumerId))) + i-- + dAtA[i] = 0xa + } + return len(dAtA) - i, nil +} + +func (m *QueryConsumerChainResponse) 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 *QueryConsumerChainResponse) MarshalTo(dAtA []byte) (int, error) { + size := m.Size() + return m.MarshalToSizedBuffer(dAtA[:size]) +} + +func (m *QueryConsumerChainResponse) MarshalToSizedBuffer(dAtA []byte) (int, error) { + i := len(dAtA) + _ = i + var l int + _ = l + if m.PowerShapingParams != nil { + { + size, err := m.PowerShapingParams.MarshalToSizedBuffer(dAtA[:i]) + if err != nil { + return 0, err + } + i -= size + i = encodeVarintQuery(dAtA, i, uint64(size)) + } + i-- + dAtA[i] = 0x32 + } + if m.InitParams != nil { + { + size, err := m.InitParams.MarshalToSizedBuffer(dAtA[:i]) + if err != nil { + return 0, err + } + i -= size + i = encodeVarintQuery(dAtA, i, uint64(size)) + } + i-- + dAtA[i] = 0x2a + } + { + size, err := m.Metadata.MarshalToSizedBuffer(dAtA[:i]) + if err != nil { + return 0, err + } + i -= size + i = encodeVarintQuery(dAtA, i, uint64(size)) + } + i-- + dAtA[i] = 0x22 + if len(m.Phase) > 0 { + i -= len(m.Phase) + copy(dAtA[i:], m.Phase) + i = encodeVarintQuery(dAtA, i, uint64(len(m.Phase))) + i-- + dAtA[i] = 0x1a + } + if len(m.OwnerAddress) > 0 { + i -= len(m.OwnerAddress) + copy(dAtA[i:], m.OwnerAddress) + i = encodeVarintQuery(dAtA, i, uint64(len(m.OwnerAddress))) + i-- + dAtA[i] = 0x12 + } + if len(m.ChainId) > 0 { + i -= len(m.ChainId) + copy(dAtA[i:], m.ChainId) + i = encodeVarintQuery(dAtA, i, uint64(len(m.ChainId))) + 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 *QueryConsumerGenesisRequest) Size() (n int) { + if m == nil { + return 0 + } var l int _ = l - if m.Proposals != nil { - l = m.Proposals.Size() + l = len(m.ConsumerId) + if l > 0 { n += 1 + l + sovQuery(uint64(l)) } return n } -func (m *QueryConsumerChainStopProposalsRequest) Size() (n int) { +func (m *QueryConsumerGenesisResponse) Size() (n int) { if m == nil { return 0 } var l int _ = l + l = m.GenesisState.Size() + n += 1 + l + sovQuery(uint64(l)) return n } -func (m *QueryConsumerChainStopProposalsResponse) Size() (n int) { +func (m *QueryConsumerChainsRequest) Size() (n int) { if m == nil { return 0 } var l int _ = l - if m.Proposals != nil { - l = m.Proposals.Size() - n += 1 + l + sovQuery(uint64(l)) + if m.Phase != 0 { + n += 1 + sovQuery(uint64(m.Phase)) + } + if m.Limit != 0 { + n += 1 + sovQuery(uint64(m.Limit)) + } + return n +} + +func (m *QueryConsumerChainsResponse) Size() (n int) { + if m == nil { + return 0 + } + var l int + _ = l + if len(m.Chains) > 0 { + for _, e := range m.Chains { + l = e.Size() + n += 1 + l + sovQuery(uint64(l)) + } } return n } @@ -3972,12 +4024,22 @@ func (m *Chain) Size() (n int) { n += 1 + l + sovQuery(uint64(l)) } } + l = len(m.Phase) + if l > 0 { + n += 1 + l + sovQuery(uint64(l)) + } + l = m.Metadata.Size() + n += 1 + l + sovQuery(uint64(l)) if m.MinStake != 0 { n += 1 + sovQuery(uint64(m.MinStake)) } if m.AllowInactiveVals { n += 2 } + l = len(m.ConsumerId) + if l > 0 { + n += 1 + l + sovQuery(uint64(l)) + } return n } @@ -3987,11 +4049,11 @@ func (m *QueryValidatorConsumerAddrRequest) Size() (n int) { } var l int _ = l - l = len(m.ChainId) + l = len(m.ProviderAddress) if l > 0 { n += 1 + l + sovQuery(uint64(l)) } - l = len(m.ProviderAddress) + l = len(m.ConsumerId) if l > 0 { n += 1 + l + sovQuery(uint64(l)) } @@ -4017,11 +4079,11 @@ func (m *QueryValidatorProviderAddrRequest) Size() (n int) { } var l int _ = l - l = len(m.ChainId) + l = len(m.ConsumerAddress) if l > 0 { n += 1 + l + sovQuery(uint64(l)) } - l = len(m.ConsumerAddress) + l = len(m.ConsumerId) if l > 0 { n += 1 + l + sovQuery(uint64(l)) } @@ -4091,60 +4153,20 @@ func (m *QueryRegisteredConsumerRewardDenomsResponse) Size() (n int) { return n } -func (m *QueryProposedChainIDsRequest) Size() (n int) { - if m == nil { - return 0 - } - var l int - _ = l - return n -} - -func (m *QueryProposedChainIDsResponse) Size() (n int) { - if m == nil { - return 0 - } - var l int - _ = l - if len(m.ProposedChains) > 0 { - for _, e := range m.ProposedChains { - l = e.Size() - n += 1 + l + sovQuery(uint64(l)) - } - } - return n -} - -func (m *ProposedChain) Size() (n int) { +func (m *QueryAllPairsValConsAddrByConsumerRequest) Size() (n int) { if m == nil { return 0 } var l int _ = l - l = len(m.ChainID) - if l > 0 { - n += 1 + l + sovQuery(uint64(l)) - } - if m.ProposalID != 0 { - n += 1 + sovQuery(uint64(m.ProposalID)) - } - return n -} - -func (m *QueryAllPairsValConAddrByConsumerChainIDRequest) Size() (n int) { - if m == nil { - return 0 - } - var l int - _ = l - l = len(m.ChainId) + l = len(m.ConsumerId) if l > 0 { n += 1 + l + sovQuery(uint64(l)) } return n } -func (m *QueryAllPairsValConAddrByConsumerChainIDResponse) Size() (n int) { +func (m *QueryAllPairsValConsAddrByConsumerResponse) Size() (n int) { if m == nil { return 0 } @@ -4206,7 +4228,7 @@ func (m *QueryConsumerChainOptedInValidatorsRequest) Size() (n int) { } var l int _ = l - l = len(m.ChainId) + l = len(m.ConsumerId) if l > 0 { n += 1 + l + sovQuery(uint64(l)) } @@ -4234,7 +4256,7 @@ func (m *QueryConsumerValidatorsRequest) Size() (n int) { } var l int _ = l - l = len(m.ChainId) + l = len(m.ConsumerId) if l > 0 { n += 1 + l + sovQuery(uint64(l)) } @@ -4260,6 +4282,33 @@ func (m *QueryConsumerValidatorsValidator) Size() (n int) { } l = m.Rate.Size() n += 1 + l + sovQuery(uint64(l)) + if m.ConsumerPower != 0 { + n += 1 + sovQuery(uint64(m.ConsumerPower)) + } + l = m.ConsumerCommissionRate.Size() + n += 1 + l + sovQuery(uint64(l)) + l = m.ProviderCommissionRate.Size() + n += 1 + l + sovQuery(uint64(l)) + l = m.Description.Size() + n += 1 + l + sovQuery(uint64(l)) + l = len(m.ProviderOperatorAddress) + if l > 0 { + n += 1 + l + sovQuery(uint64(l)) + } + if m.Jailed { + n += 2 + } + if m.Status != 0 { + n += 1 + sovQuery(uint64(m.Status)) + } + l = m.ProviderTokens.Size() + n += 1 + l + sovQuery(uint64(l)) + if m.ProviderPower != 0 { + n += 1 + sovQuery(uint64(m.ProviderPower)) + } + if m.ValidatesCurrentEpoch { + n += 2 + } return n } @@ -4297,8 +4346,8 @@ func (m *QueryConsumerChainsValidatorHasToValidateResponse) Size() (n int) { } var l int _ = l - if len(m.ConsumerChainIds) > 0 { - for _, s := range m.ConsumerChainIds { + if len(m.ConsumerIds) > 0 { + for _, s := range m.ConsumerIds { l = len(s) n += 1 + l + sovQuery(uint64(l)) } @@ -4312,7 +4361,7 @@ func (m *QueryValidatorConsumerCommissionRateRequest) Size() (n int) { } var l int _ = l - l = len(m.ChainId) + l = len(m.ConsumerId) if l > 0 { n += 1 + l + sovQuery(uint64(l)) } @@ -4355,6 +4404,76 @@ func (m *QueryBlocksUntilNextEpochResponse) Size() (n int) { return n } +func (m *QueryConsumerIdFromClientIdRequest) Size() (n int) { + if m == nil { + return 0 + } + var l int + _ = l + l = len(m.ClientId) + if l > 0 { + n += 1 + l + sovQuery(uint64(l)) + } + return n +} + +func (m *QueryConsumerIdFromClientIdResponse) Size() (n int) { + if m == nil { + return 0 + } + var l int + _ = l + l = len(m.ConsumerId) + if l > 0 { + n += 1 + l + sovQuery(uint64(l)) + } + return n +} + +func (m *QueryConsumerChainRequest) Size() (n int) { + if m == nil { + return 0 + } + var l int + _ = l + l = len(m.ConsumerId) + if l > 0 { + n += 1 + l + sovQuery(uint64(l)) + } + return n +} + +func (m *QueryConsumerChainResponse) Size() (n int) { + if m == nil { + return 0 + } + var l int + _ = l + l = len(m.ChainId) + if l > 0 { + n += 1 + l + sovQuery(uint64(l)) + } + l = len(m.OwnerAddress) + if l > 0 { + n += 1 + l + sovQuery(uint64(l)) + } + l = len(m.Phase) + if l > 0 { + n += 1 + l + sovQuery(uint64(l)) + } + l = m.Metadata.Size() + n += 1 + l + sovQuery(uint64(l)) + if m.InitParams != nil { + l = m.InitParams.Size() + n += 1 + l + sovQuery(uint64(l)) + } + if m.PowerShapingParams != nil { + l = m.PowerShapingParams.Size() + n += 1 + l + sovQuery(uint64(l)) + } + return n +} + func sovQuery(x uint64) (n int) { return (math_bits.Len64(x|1) + 6) / 7 } @@ -4392,7 +4511,7 @@ func (m *QueryConsumerGenesisRequest) Unmarshal(dAtA []byte) error { switch fieldNum { case 1: if wireType != 2 { - return fmt.Errorf("proto: wrong wireType = %d for field ChainId", wireType) + return fmt.Errorf("proto: wrong wireType = %d for field ConsumerId", wireType) } var stringLen uint64 for shift := uint(0); ; shift += 7 { @@ -4420,7 +4539,7 @@ func (m *QueryConsumerGenesisRequest) Unmarshal(dAtA []byte) error { if postIndex > l { return io.ErrUnexpectedEOF } - m.ChainId = string(dAtA[iNdEx:postIndex]) + m.ConsumerId = string(dAtA[iNdEx:postIndex]) iNdEx = postIndex default: iNdEx = preIndex @@ -4555,195 +4674,30 @@ func (m *QueryConsumerChainsRequest) Unmarshal(dAtA []byte) error { return fmt.Errorf("proto: QueryConsumerChainsRequest: illegal tag %d (wire type %d)", fieldNum, wire) } switch fieldNum { - default: - iNdEx = preIndex - skippy, err := skipQuery(dAtA[iNdEx:]) - if err != nil { - return err + case 1: + if wireType != 0 { + return fmt.Errorf("proto: wrong wireType = %d for field Phase", wireType) } - if (skippy < 0) || (iNdEx+skippy) < 0 { - return ErrInvalidLengthQuery + m.Phase = 0 + for shift := uint(0); ; shift += 7 { + if shift >= 64 { + return ErrIntOverflowQuery + } + if iNdEx >= l { + return io.ErrUnexpectedEOF + } + b := dAtA[iNdEx] + iNdEx++ + m.Phase |= ConsumerPhase(b&0x7F) << shift + if b < 0x80 { + break + } } - if (iNdEx + skippy) > l { - return io.ErrUnexpectedEOF - } - iNdEx += skippy - } - } - - if iNdEx > l { - return io.ErrUnexpectedEOF - } - return nil -} -func (m *QueryConsumerChainsResponse) 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: QueryConsumerChainsResponse: wiretype end group for non-group") - } - if fieldNum <= 0 { - return fmt.Errorf("proto: QueryConsumerChainsResponse: illegal tag %d (wire type %d)", fieldNum, wire) - } - switch fieldNum { - case 1: - if wireType != 2 { - return fmt.Errorf("proto: wrong wireType = %d for field Chains", 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.Chains = append(m.Chains, &Chain{}) - if err := m.Chains[len(m.Chains)-1].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 *QueryConsumerChainStartProposalsRequest) 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: QueryConsumerChainStartProposalsRequest: wiretype end group for non-group") - } - if fieldNum <= 0 { - return fmt.Errorf("proto: QueryConsumerChainStartProposalsRequest: 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 *QueryConsumerChainStartProposalsResponse) 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: QueryConsumerChainStartProposalsResponse: wiretype end group for non-group") - } - if fieldNum <= 0 { - return fmt.Errorf("proto: QueryConsumerChainStartProposalsResponse: illegal tag %d (wire type %d)", fieldNum, wire) - } - switch fieldNum { - case 1: - if wireType != 2 { - return fmt.Errorf("proto: wrong wireType = %d for field Proposals", wireType) + case 2: + if wireType != 0 { + return fmt.Errorf("proto: wrong wireType = %d for field Limit", wireType) } - var msglen int + m.Limit = 0 for shift := uint(0); ; shift += 7 { if shift >= 64 { return ErrIntOverflowQuery @@ -4753,78 +4707,11 @@ func (m *QueryConsumerChainStartProposalsResponse) Unmarshal(dAtA []byte) error } b := dAtA[iNdEx] iNdEx++ - msglen |= int(b&0x7F) << shift + m.Limit |= int32(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.Proposals == nil { - m.Proposals = &ConsumerAdditionProposals{} - } - if err := m.Proposals.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 *QueryConsumerChainStopProposalsRequest) 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: QueryConsumerChainStopProposalsRequest: wiretype end group for non-group") - } - if fieldNum <= 0 { - return fmt.Errorf("proto: QueryConsumerChainStopProposalsRequest: illegal tag %d (wire type %d)", fieldNum, wire) - } - switch fieldNum { default: iNdEx = preIndex skippy, err := skipQuery(dAtA[iNdEx:]) @@ -4846,7 +4733,7 @@ func (m *QueryConsumerChainStopProposalsRequest) Unmarshal(dAtA []byte) error { } return nil } -func (m *QueryConsumerChainStopProposalsResponse) Unmarshal(dAtA []byte) error { +func (m *QueryConsumerChainsResponse) Unmarshal(dAtA []byte) error { l := len(dAtA) iNdEx := 0 for iNdEx < l { @@ -4869,15 +4756,15 @@ func (m *QueryConsumerChainStopProposalsResponse) Unmarshal(dAtA []byte) error { fieldNum := int32(wire >> 3) wireType := int(wire & 0x7) if wireType == 4 { - return fmt.Errorf("proto: QueryConsumerChainStopProposalsResponse: wiretype end group for non-group") + return fmt.Errorf("proto: QueryConsumerChainsResponse: wiretype end group for non-group") } if fieldNum <= 0 { - return fmt.Errorf("proto: QueryConsumerChainStopProposalsResponse: illegal tag %d (wire type %d)", fieldNum, wire) + return fmt.Errorf("proto: QueryConsumerChainsResponse: illegal tag %d (wire type %d)", fieldNum, wire) } switch fieldNum { case 1: if wireType != 2 { - return fmt.Errorf("proto: wrong wireType = %d for field Proposals", wireType) + return fmt.Errorf("proto: wrong wireType = %d for field Chains", wireType) } var msglen int for shift := uint(0); ; shift += 7 { @@ -4904,10 +4791,8 @@ func (m *QueryConsumerChainStopProposalsResponse) Unmarshal(dAtA []byte) error { if postIndex > l { return io.ErrUnexpectedEOF } - if m.Proposals == nil { - m.Proposals = &ConsumerRemovalProposals{} - } - if err := m.Proposals.Unmarshal(dAtA[iNdEx:postIndex]); err != nil { + m.Chains = append(m.Chains, &Chain{}) + if err := m.Chains[len(m.Chains)-1].Unmarshal(dAtA[iNdEx:postIndex]); err != nil { return err } iNdEx = postIndex @@ -5166,10 +5051,10 @@ func (m *Chain) Unmarshal(dAtA []byte) error { m.Denylist = append(m.Denylist, string(dAtA[iNdEx:postIndex])) iNdEx = postIndex case 9: - if wireType != 0 { - return fmt.Errorf("proto: wrong wireType = %d for field MinStake", wireType) + if wireType != 2 { + return fmt.Errorf("proto: wrong wireType = %d for field Phase", wireType) } - m.MinStake = 0 + var stringLen uint64 for shift := uint(0); ; shift += 7 { if shift >= 64 { return ErrIntOverflowQuery @@ -5179,17 +5064,82 @@ func (m *Chain) Unmarshal(dAtA []byte) error { } b := dAtA[iNdEx] iNdEx++ - m.MinStake |= uint64(b&0x7F) << shift + stringLen |= uint64(b&0x7F) << shift if b < 0x80 { break } } - case 10: - if wireType != 0 { - return fmt.Errorf("proto: wrong wireType = %d for field AllowInactiveVals", wireType) + intStringLen := int(stringLen) + if intStringLen < 0 { + return ErrInvalidLengthQuery } - var v int - for shift := uint(0); ; shift += 7 { + postIndex := iNdEx + intStringLen + if postIndex < 0 { + return ErrInvalidLengthQuery + } + if postIndex > l { + return io.ErrUnexpectedEOF + } + m.Phase = string(dAtA[iNdEx:postIndex]) + iNdEx = postIndex + case 10: + if wireType != 2 { + return fmt.Errorf("proto: wrong wireType = %d for field Metadata", 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 err := m.Metadata.Unmarshal(dAtA[iNdEx:postIndex]); err != nil { + return err + } + iNdEx = postIndex + case 11: + if wireType != 0 { + return fmt.Errorf("proto: wrong wireType = %d for field MinStake", wireType) + } + m.MinStake = 0 + for shift := uint(0); ; shift += 7 { + if shift >= 64 { + return ErrIntOverflowQuery + } + if iNdEx >= l { + return io.ErrUnexpectedEOF + } + b := dAtA[iNdEx] + iNdEx++ + m.MinStake |= uint64(b&0x7F) << shift + if b < 0x80 { + break + } + } + case 12: + if wireType != 0 { + return fmt.Errorf("proto: wrong wireType = %d for field AllowInactiveVals", wireType) + } + var v int + for shift := uint(0); ; shift += 7 { if shift >= 64 { return ErrIntOverflowQuery } @@ -5204,6 +5154,38 @@ func (m *Chain) Unmarshal(dAtA []byte) error { } } m.AllowInactiveVals = bool(v != 0) + case 13: + if wireType != 2 { + return fmt.Errorf("proto: wrong wireType = %d for field ConsumerId", 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.ConsumerId = string(dAtA[iNdEx:postIndex]) + iNdEx = postIndex default: iNdEx = preIndex skippy, err := skipQuery(dAtA[iNdEx:]) @@ -5256,7 +5238,7 @@ func (m *QueryValidatorConsumerAddrRequest) Unmarshal(dAtA []byte) error { switch fieldNum { case 1: if wireType != 2 { - return fmt.Errorf("proto: wrong wireType = %d for field ChainId", wireType) + return fmt.Errorf("proto: wrong wireType = %d for field ProviderAddress", wireType) } var stringLen uint64 for shift := uint(0); ; shift += 7 { @@ -5284,11 +5266,11 @@ func (m *QueryValidatorConsumerAddrRequest) Unmarshal(dAtA []byte) error { if postIndex > l { return io.ErrUnexpectedEOF } - m.ChainId = string(dAtA[iNdEx:postIndex]) + m.ProviderAddress = string(dAtA[iNdEx:postIndex]) iNdEx = postIndex case 2: if wireType != 2 { - return fmt.Errorf("proto: wrong wireType = %d for field ProviderAddress", wireType) + return fmt.Errorf("proto: wrong wireType = %d for field ConsumerId", wireType) } var stringLen uint64 for shift := uint(0); ; shift += 7 { @@ -5316,7 +5298,7 @@ func (m *QueryValidatorConsumerAddrRequest) Unmarshal(dAtA []byte) error { if postIndex > l { return io.ErrUnexpectedEOF } - m.ProviderAddress = string(dAtA[iNdEx:postIndex]) + m.ConsumerId = string(dAtA[iNdEx:postIndex]) iNdEx = postIndex default: iNdEx = preIndex @@ -5452,7 +5434,7 @@ func (m *QueryValidatorProviderAddrRequest) Unmarshal(dAtA []byte) error { switch fieldNum { case 1: if wireType != 2 { - return fmt.Errorf("proto: wrong wireType = %d for field ChainId", wireType) + return fmt.Errorf("proto: wrong wireType = %d for field ConsumerAddress", wireType) } var stringLen uint64 for shift := uint(0); ; shift += 7 { @@ -5480,11 +5462,11 @@ func (m *QueryValidatorProviderAddrRequest) Unmarshal(dAtA []byte) error { if postIndex > l { return io.ErrUnexpectedEOF } - m.ChainId = string(dAtA[iNdEx:postIndex]) + m.ConsumerAddress = string(dAtA[iNdEx:postIndex]) iNdEx = postIndex case 2: if wireType != 2 { - return fmt.Errorf("proto: wrong wireType = %d for field ConsumerAddress", wireType) + return fmt.Errorf("proto: wrong wireType = %d for field ConsumerId", wireType) } var stringLen uint64 for shift := uint(0); ; shift += 7 { @@ -5512,7 +5494,7 @@ func (m *QueryValidatorProviderAddrRequest) Unmarshal(dAtA []byte) error { if postIndex > l { return io.ErrUnexpectedEOF } - m.ConsumerAddress = string(dAtA[iNdEx:postIndex]) + m.ConsumerId = string(dAtA[iNdEx:postIndex]) iNdEx = postIndex default: iNdEx = preIndex @@ -5920,7 +5902,7 @@ func (m *QueryRegisteredConsumerRewardDenomsResponse) Unmarshal(dAtA []byte) err } return nil } -func (m *QueryProposedChainIDsRequest) Unmarshal(dAtA []byte) error { +func (m *QueryAllPairsValConsAddrByConsumerRequest) Unmarshal(dAtA []byte) error { l := len(dAtA) iNdEx := 0 for iNdEx < l { @@ -5943,12 +5925,44 @@ func (m *QueryProposedChainIDsRequest) Unmarshal(dAtA []byte) error { fieldNum := int32(wire >> 3) wireType := int(wire & 0x7) if wireType == 4 { - return fmt.Errorf("proto: QueryProposedChainIDsRequest: wiretype end group for non-group") + return fmt.Errorf("proto: QueryAllPairsValConsAddrByConsumerRequest: wiretype end group for non-group") } if fieldNum <= 0 { - return fmt.Errorf("proto: QueryProposedChainIDsRequest: illegal tag %d (wire type %d)", fieldNum, wire) + return fmt.Errorf("proto: QueryAllPairsValConsAddrByConsumerRequest: illegal tag %d (wire type %d)", fieldNum, wire) } switch fieldNum { + case 1: + if wireType != 2 { + return fmt.Errorf("proto: wrong wireType = %d for field ConsumerId", 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.ConsumerId = string(dAtA[iNdEx:postIndex]) + iNdEx = postIndex default: iNdEx = preIndex skippy, err := skipQuery(dAtA[iNdEx:]) @@ -5970,7 +5984,7 @@ func (m *QueryProposedChainIDsRequest) Unmarshal(dAtA []byte) error { } return nil } -func (m *QueryProposedChainIDsResponse) Unmarshal(dAtA []byte) error { +func (m *QueryAllPairsValConsAddrByConsumerResponse) Unmarshal(dAtA []byte) error { l := len(dAtA) iNdEx := 0 for iNdEx < l { @@ -5993,15 +6007,15 @@ func (m *QueryProposedChainIDsResponse) Unmarshal(dAtA []byte) error { fieldNum := int32(wire >> 3) wireType := int(wire & 0x7) if wireType == 4 { - return fmt.Errorf("proto: QueryProposedChainIDsResponse: wiretype end group for non-group") + return fmt.Errorf("proto: QueryAllPairsValConsAddrByConsumerResponse: wiretype end group for non-group") } if fieldNum <= 0 { - return fmt.Errorf("proto: QueryProposedChainIDsResponse: illegal tag %d (wire type %d)", fieldNum, wire) + return fmt.Errorf("proto: QueryAllPairsValConsAddrByConsumerResponse: illegal tag %d (wire type %d)", fieldNum, wire) } switch fieldNum { case 1: if wireType != 2 { - return fmt.Errorf("proto: wrong wireType = %d for field ProposedChains", wireType) + return fmt.Errorf("proto: wrong wireType = %d for field PairValConAddr", wireType) } var msglen int for shift := uint(0); ; shift += 7 { @@ -6028,8 +6042,8 @@ func (m *QueryProposedChainIDsResponse) Unmarshal(dAtA []byte) error { if postIndex > l { return io.ErrUnexpectedEOF } - m.ProposedChains = append(m.ProposedChains, ProposedChain{}) - if err := m.ProposedChains[len(m.ProposedChains)-1].Unmarshal(dAtA[iNdEx:postIndex]); err != nil { + m.PairValConAddr = append(m.PairValConAddr, &PairValConAddrProviderAndConsumer{}) + if err := m.PairValConAddr[len(m.PairValConAddr)-1].Unmarshal(dAtA[iNdEx:postIndex]); err != nil { return err } iNdEx = postIndex @@ -6054,7 +6068,7 @@ func (m *QueryProposedChainIDsResponse) Unmarshal(dAtA []byte) error { } return nil } -func (m *ProposedChain) Unmarshal(dAtA []byte) error { +func (m *PairValConAddrProviderAndConsumer) Unmarshal(dAtA []byte) error { l := len(dAtA) iNdEx := 0 for iNdEx < l { @@ -6077,15 +6091,15 @@ func (m *ProposedChain) Unmarshal(dAtA []byte) error { fieldNum := int32(wire >> 3) wireType := int(wire & 0x7) if wireType == 4 { - return fmt.Errorf("proto: ProposedChain: wiretype end group for non-group") + return fmt.Errorf("proto: PairValConAddrProviderAndConsumer: wiretype end group for non-group") } if fieldNum <= 0 { - return fmt.Errorf("proto: ProposedChain: illegal tag %d (wire type %d)", fieldNum, wire) + return fmt.Errorf("proto: PairValConAddrProviderAndConsumer: illegal tag %d (wire type %d)", fieldNum, wire) } switch fieldNum { case 1: if wireType != 2 { - return fmt.Errorf("proto: wrong wireType = %d for field ChainID", wireType) + return fmt.Errorf("proto: wrong wireType = %d for field ProviderAddress", wireType) } var stringLen uint64 for shift := uint(0); ; shift += 7 { @@ -6113,13 +6127,45 @@ func (m *ProposedChain) Unmarshal(dAtA []byte) error { if postIndex > l { return io.ErrUnexpectedEOF } - m.ChainID = string(dAtA[iNdEx:postIndex]) + m.ProviderAddress = string(dAtA[iNdEx:postIndex]) iNdEx = postIndex case 2: - if wireType != 0 { - return fmt.Errorf("proto: wrong wireType = %d for field ProposalID", wireType) + if wireType != 2 { + return fmt.Errorf("proto: wrong wireType = %d for field ConsumerAddress", 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.ConsumerAddress = string(dAtA[iNdEx:postIndex]) + iNdEx = postIndex + case 3: + if wireType != 2 { + return fmt.Errorf("proto: wrong wireType = %d for field ConsumerKey", wireType) } - m.ProposalID = 0 + var msglen int for shift := uint(0); ; shift += 7 { if shift >= 64 { return ErrIntOverflowQuery @@ -6129,11 +6175,28 @@ func (m *ProposedChain) Unmarshal(dAtA []byte) error { } b := dAtA[iNdEx] iNdEx++ - m.ProposalID |= uint64(b&0x7F) << shift + 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.ConsumerKey == nil { + m.ConsumerKey = &crypto.PublicKey{} + } + if err := m.ConsumerKey.Unmarshal(dAtA[iNdEx:postIndex]); err != nil { + return err + } + iNdEx = postIndex default: iNdEx = preIndex skippy, err := skipQuery(dAtA[iNdEx:]) @@ -6155,7 +6218,7 @@ func (m *ProposedChain) Unmarshal(dAtA []byte) error { } return nil } -func (m *QueryAllPairsValConAddrByConsumerChainIDRequest) Unmarshal(dAtA []byte) error { +func (m *QueryParamsRequest) Unmarshal(dAtA []byte) error { l := len(dAtA) iNdEx := 0 for iNdEx < l { @@ -6178,44 +6241,12 @@ func (m *QueryAllPairsValConAddrByConsumerChainIDRequest) Unmarshal(dAtA []byte) fieldNum := int32(wire >> 3) wireType := int(wire & 0x7) if wireType == 4 { - return fmt.Errorf("proto: QueryAllPairsValConAddrByConsumerChainIDRequest: wiretype end group for non-group") + return fmt.Errorf("proto: QueryParamsRequest: wiretype end group for non-group") } if fieldNum <= 0 { - return fmt.Errorf("proto: QueryAllPairsValConAddrByConsumerChainIDRequest: illegal tag %d (wire type %d)", fieldNum, wire) + return fmt.Errorf("proto: QueryParamsRequest: illegal tag %d (wire type %d)", fieldNum, wire) } switch fieldNum { - case 1: - if wireType != 2 { - return fmt.Errorf("proto: wrong wireType = %d for field ChainId", 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.ChainId = string(dAtA[iNdEx:postIndex]) - iNdEx = postIndex default: iNdEx = preIndex skippy, err := skipQuery(dAtA[iNdEx:]) @@ -6237,7 +6268,7 @@ func (m *QueryAllPairsValConAddrByConsumerChainIDRequest) Unmarshal(dAtA []byte) } return nil } -func (m *QueryAllPairsValConAddrByConsumerChainIDResponse) Unmarshal(dAtA []byte) error { +func (m *QueryParamsResponse) Unmarshal(dAtA []byte) error { l := len(dAtA) iNdEx := 0 for iNdEx < l { @@ -6260,15 +6291,15 @@ func (m *QueryAllPairsValConAddrByConsumerChainIDResponse) Unmarshal(dAtA []byte fieldNum := int32(wire >> 3) wireType := int(wire & 0x7) if wireType == 4 { - return fmt.Errorf("proto: QueryAllPairsValConAddrByConsumerChainIDResponse: wiretype end group for non-group") + return fmt.Errorf("proto: QueryParamsResponse: wiretype end group for non-group") } if fieldNum <= 0 { - return fmt.Errorf("proto: QueryAllPairsValConAddrByConsumerChainIDResponse: illegal tag %d (wire type %d)", fieldNum, wire) + return fmt.Errorf("proto: QueryParamsResponse: illegal tag %d (wire type %d)", fieldNum, wire) } switch fieldNum { case 1: if wireType != 2 { - return fmt.Errorf("proto: wrong wireType = %d for field PairValConAddr", wireType) + return fmt.Errorf("proto: wrong wireType = %d for field Params", wireType) } var msglen int for shift := uint(0); ; shift += 7 { @@ -6295,8 +6326,7 @@ func (m *QueryAllPairsValConAddrByConsumerChainIDResponse) Unmarshal(dAtA []byte if postIndex > l { return io.ErrUnexpectedEOF } - m.PairValConAddr = append(m.PairValConAddr, &PairValConAddrProviderAndConsumer{}) - if err := m.PairValConAddr[len(m.PairValConAddr)-1].Unmarshal(dAtA[iNdEx:postIndex]); err != nil { + if err := m.Params.Unmarshal(dAtA[iNdEx:postIndex]); err != nil { return err } iNdEx = postIndex @@ -6321,7 +6351,7 @@ func (m *QueryAllPairsValConAddrByConsumerChainIDResponse) Unmarshal(dAtA []byte } return nil } -func (m *PairValConAddrProviderAndConsumer) Unmarshal(dAtA []byte) error { +func (m *QueryConsumerChainOptedInValidatorsRequest) Unmarshal(dAtA []byte) error { l := len(dAtA) iNdEx := 0 for iNdEx < l { @@ -6344,15 +6374,15 @@ func (m *PairValConAddrProviderAndConsumer) Unmarshal(dAtA []byte) error { fieldNum := int32(wire >> 3) wireType := int(wire & 0x7) if wireType == 4 { - return fmt.Errorf("proto: PairValConAddrProviderAndConsumer: wiretype end group for non-group") + return fmt.Errorf("proto: QueryConsumerChainOptedInValidatorsRequest: wiretype end group for non-group") } if fieldNum <= 0 { - return fmt.Errorf("proto: PairValConAddrProviderAndConsumer: illegal tag %d (wire type %d)", fieldNum, wire) + return fmt.Errorf("proto: QueryConsumerChainOptedInValidatorsRequest: illegal tag %d (wire type %d)", fieldNum, wire) } switch fieldNum { case 1: if wireType != 2 { - return fmt.Errorf("proto: wrong wireType = %d for field ProviderAddress", wireType) + return fmt.Errorf("proto: wrong wireType = %d for field ConsumerId", wireType) } var stringLen uint64 for shift := uint(0); ; shift += 7 { @@ -6380,14 +6410,64 @@ func (m *PairValConAddrProviderAndConsumer) Unmarshal(dAtA []byte) error { if postIndex > l { return io.ErrUnexpectedEOF } - m.ProviderAddress = string(dAtA[iNdEx:postIndex]) + m.ConsumerId = string(dAtA[iNdEx:postIndex]) iNdEx = postIndex - case 2: - if wireType != 2 { - return fmt.Errorf("proto: wrong wireType = %d for field ConsumerAddress", wireType) + default: + iNdEx = preIndex + skippy, err := skipQuery(dAtA[iNdEx:]) + if err != nil { + return err } - var stringLen uint64 - for shift := uint(0); ; shift += 7 { + 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 *QueryConsumerChainOptedInValidatorsResponse) 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: QueryConsumerChainOptedInValidatorsResponse: wiretype end group for non-group") + } + if fieldNum <= 0 { + return fmt.Errorf("proto: QueryConsumerChainOptedInValidatorsResponse: illegal tag %d (wire type %d)", fieldNum, wire) + } + switch fieldNum { + case 1: + if wireType != 2 { + return fmt.Errorf("proto: wrong wireType = %d for field ValidatorsProviderAddresses", wireType) + } + var stringLen uint64 + for shift := uint(0); ; shift += 7 { if shift >= 64 { return ErrIntOverflowQuery } @@ -6412,13 +6492,63 @@ func (m *PairValConAddrProviderAndConsumer) Unmarshal(dAtA []byte) error { if postIndex > l { return io.ErrUnexpectedEOF } - m.ConsumerAddress = string(dAtA[iNdEx:postIndex]) + m.ValidatorsProviderAddresses = append(m.ValidatorsProviderAddresses, string(dAtA[iNdEx:postIndex])) iNdEx = postIndex - case 3: + 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 *QueryConsumerValidatorsRequest) 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: QueryConsumerValidatorsRequest: wiretype end group for non-group") + } + if fieldNum <= 0 { + return fmt.Errorf("proto: QueryConsumerValidatorsRequest: illegal tag %d (wire type %d)", fieldNum, wire) + } + switch fieldNum { + case 1: if wireType != 2 { - return fmt.Errorf("proto: wrong wireType = %d for field ConsumerKey", wireType) + return fmt.Errorf("proto: wrong wireType = %d for field ConsumerId", wireType) } - var msglen int + var stringLen uint64 for shift := uint(0); ; shift += 7 { if shift >= 64 { return ErrIntOverflowQuery @@ -6428,27 +6558,23 @@ func (m *PairValConAddrProviderAndConsumer) Unmarshal(dAtA []byte) error { } b := dAtA[iNdEx] iNdEx++ - msglen |= int(b&0x7F) << shift + stringLen |= uint64(b&0x7F) << shift if b < 0x80 { break } } - if msglen < 0 { + intStringLen := int(stringLen) + if intStringLen < 0 { return ErrInvalidLengthQuery } - postIndex := iNdEx + msglen + postIndex := iNdEx + intStringLen if postIndex < 0 { return ErrInvalidLengthQuery } if postIndex > l { return io.ErrUnexpectedEOF } - if m.ConsumerKey == nil { - m.ConsumerKey = &crypto.PublicKey{} - } - if err := m.ConsumerKey.Unmarshal(dAtA[iNdEx:postIndex]); err != nil { - return err - } + m.ConsumerId = string(dAtA[iNdEx:postIndex]) iNdEx = postIndex default: iNdEx = preIndex @@ -6471,7 +6597,7 @@ func (m *PairValConAddrProviderAndConsumer) Unmarshal(dAtA []byte) error { } return nil } -func (m *QueryParamsRequest) Unmarshal(dAtA []byte) error { +func (m *QueryConsumerValidatorsValidator) Unmarshal(dAtA []byte) error { l := len(dAtA) iNdEx := 0 for iNdEx < l { @@ -6490,16 +6616,401 @@ func (m *QueryParamsRequest) Unmarshal(dAtA []byte) error { if b < 0x80 { break } - } - fieldNum := int32(wire >> 3) - wireType := int(wire & 0x7) - if wireType == 4 { - return fmt.Errorf("proto: QueryParamsRequest: wiretype end group for non-group") - } - if fieldNum <= 0 { - return fmt.Errorf("proto: QueryParamsRequest: illegal tag %d (wire type %d)", fieldNum, wire) - } - switch fieldNum { + } + fieldNum := int32(wire >> 3) + wireType := int(wire & 0x7) + if wireType == 4 { + return fmt.Errorf("proto: QueryConsumerValidatorsValidator: wiretype end group for non-group") + } + if fieldNum <= 0 { + return fmt.Errorf("proto: QueryConsumerValidatorsValidator: illegal tag %d (wire type %d)", fieldNum, wire) + } + switch fieldNum { + case 1: + if wireType != 2 { + return fmt.Errorf("proto: wrong wireType = %d for field ProviderAddress", 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.ProviderAddress = string(dAtA[iNdEx:postIndex]) + iNdEx = postIndex + case 2: + if wireType != 2 { + return fmt.Errorf("proto: wrong wireType = %d for field ConsumerKey", 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.ConsumerKey == nil { + m.ConsumerKey = &crypto.PublicKey{} + } + if err := m.ConsumerKey.Unmarshal(dAtA[iNdEx:postIndex]); err != nil { + return err + } + iNdEx = postIndex + case 3: + if wireType != 0 { + return fmt.Errorf("proto: wrong wireType = %d for field Power", wireType) + } + m.Power = 0 + for shift := uint(0); ; shift += 7 { + if shift >= 64 { + return ErrIntOverflowQuery + } + if iNdEx >= l { + return io.ErrUnexpectedEOF + } + b := dAtA[iNdEx] + iNdEx++ + m.Power |= int64(b&0x7F) << shift + if b < 0x80 { + break + } + } + case 4: + if wireType != 2 { + return fmt.Errorf("proto: wrong wireType = %d for field Rate", 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 + } + if err := m.Rate.Unmarshal(dAtA[iNdEx:postIndex]); err != nil { + return err + } + iNdEx = postIndex + case 5: + if wireType != 0 { + return fmt.Errorf("proto: wrong wireType = %d for field ConsumerPower", wireType) + } + m.ConsumerPower = 0 + for shift := uint(0); ; shift += 7 { + if shift >= 64 { + return ErrIntOverflowQuery + } + if iNdEx >= l { + return io.ErrUnexpectedEOF + } + b := dAtA[iNdEx] + iNdEx++ + m.ConsumerPower |= int64(b&0x7F) << shift + if b < 0x80 { + break + } + } + case 6: + if wireType != 2 { + return fmt.Errorf("proto: wrong wireType = %d for field ConsumerCommissionRate", 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 + } + if err := m.ConsumerCommissionRate.Unmarshal(dAtA[iNdEx:postIndex]); err != nil { + return err + } + iNdEx = postIndex + case 7: + if wireType != 2 { + return fmt.Errorf("proto: wrong wireType = %d for field ProviderCommissionRate", 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 + } + if err := m.ProviderCommissionRate.Unmarshal(dAtA[iNdEx:postIndex]); err != nil { + return err + } + iNdEx = postIndex + case 8: + if wireType != 2 { + return fmt.Errorf("proto: wrong wireType = %d for field Description", 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 err := m.Description.Unmarshal(dAtA[iNdEx:postIndex]); err != nil { + return err + } + iNdEx = postIndex + case 9: + if wireType != 2 { + return fmt.Errorf("proto: wrong wireType = %d for field ProviderOperatorAddress", 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.ProviderOperatorAddress = string(dAtA[iNdEx:postIndex]) + iNdEx = postIndex + case 10: + if wireType != 0 { + return fmt.Errorf("proto: wrong wireType = %d for field Jailed", wireType) + } + var v int + for shift := uint(0); ; shift += 7 { + if shift >= 64 { + return ErrIntOverflowQuery + } + if iNdEx >= l { + return io.ErrUnexpectedEOF + } + b := dAtA[iNdEx] + iNdEx++ + v |= int(b&0x7F) << shift + if b < 0x80 { + break + } + } + m.Jailed = bool(v != 0) + case 11: + if wireType != 0 { + return fmt.Errorf("proto: wrong wireType = %d for field Status", wireType) + } + m.Status = 0 + for shift := uint(0); ; shift += 7 { + if shift >= 64 { + return ErrIntOverflowQuery + } + if iNdEx >= l { + return io.ErrUnexpectedEOF + } + b := dAtA[iNdEx] + iNdEx++ + m.Status |= types1.BondStatus(b&0x7F) << shift + if b < 0x80 { + break + } + } + case 12: + if wireType != 2 { + return fmt.Errorf("proto: wrong wireType = %d for field ProviderTokens", 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 + } + if err := m.ProviderTokens.Unmarshal(dAtA[iNdEx:postIndex]); err != nil { + return err + } + iNdEx = postIndex + case 13: + if wireType != 0 { + return fmt.Errorf("proto: wrong wireType = %d for field ProviderPower", wireType) + } + m.ProviderPower = 0 + for shift := uint(0); ; shift += 7 { + if shift >= 64 { + return ErrIntOverflowQuery + } + if iNdEx >= l { + return io.ErrUnexpectedEOF + } + b := dAtA[iNdEx] + iNdEx++ + m.ProviderPower |= int64(b&0x7F) << shift + if b < 0x80 { + break + } + } + case 14: + if wireType != 0 { + return fmt.Errorf("proto: wrong wireType = %d for field ValidatesCurrentEpoch", wireType) + } + var v int + for shift := uint(0); ; shift += 7 { + if shift >= 64 { + return ErrIntOverflowQuery + } + if iNdEx >= l { + return io.ErrUnexpectedEOF + } + b := dAtA[iNdEx] + iNdEx++ + v |= int(b&0x7F) << shift + if b < 0x80 { + break + } + } + m.ValidatesCurrentEpoch = bool(v != 0) default: iNdEx = preIndex skippy, err := skipQuery(dAtA[iNdEx:]) @@ -6521,7 +7032,7 @@ func (m *QueryParamsRequest) Unmarshal(dAtA []byte) error { } return nil } -func (m *QueryParamsResponse) Unmarshal(dAtA []byte) error { +func (m *QueryConsumerValidatorsResponse) Unmarshal(dAtA []byte) error { l := len(dAtA) iNdEx := 0 for iNdEx < l { @@ -6544,15 +7055,15 @@ func (m *QueryParamsResponse) Unmarshal(dAtA []byte) error { fieldNum := int32(wire >> 3) wireType := int(wire & 0x7) if wireType == 4 { - return fmt.Errorf("proto: QueryParamsResponse: wiretype end group for non-group") + return fmt.Errorf("proto: QueryConsumerValidatorsResponse: wiretype end group for non-group") } if fieldNum <= 0 { - return fmt.Errorf("proto: QueryParamsResponse: illegal tag %d (wire type %d)", fieldNum, wire) + return fmt.Errorf("proto: QueryConsumerValidatorsResponse: illegal tag %d (wire type %d)", fieldNum, wire) } switch fieldNum { case 1: if wireType != 2 { - return fmt.Errorf("proto: wrong wireType = %d for field Params", wireType) + return fmt.Errorf("proto: wrong wireType = %d for field Validators", wireType) } var msglen int for shift := uint(0); ; shift += 7 { @@ -6579,7 +7090,8 @@ func (m *QueryParamsResponse) Unmarshal(dAtA []byte) error { if postIndex > l { return io.ErrUnexpectedEOF } - if err := m.Params.Unmarshal(dAtA[iNdEx:postIndex]); err != nil { + m.Validators = append(m.Validators, &QueryConsumerValidatorsValidator{}) + if err := m.Validators[len(m.Validators)-1].Unmarshal(dAtA[iNdEx:postIndex]); err != nil { return err } iNdEx = postIndex @@ -6604,7 +7116,7 @@ func (m *QueryParamsResponse) Unmarshal(dAtA []byte) error { } return nil } -func (m *QueryConsumerChainOptedInValidatorsRequest) Unmarshal(dAtA []byte) error { +func (m *QueryConsumerChainsValidatorHasToValidateRequest) Unmarshal(dAtA []byte) error { l := len(dAtA) iNdEx := 0 for iNdEx < l { @@ -6627,15 +7139,15 @@ func (m *QueryConsumerChainOptedInValidatorsRequest) Unmarshal(dAtA []byte) erro fieldNum := int32(wire >> 3) wireType := int(wire & 0x7) if wireType == 4 { - return fmt.Errorf("proto: QueryConsumerChainOptedInValidatorsRequest: wiretype end group for non-group") + return fmt.Errorf("proto: QueryConsumerChainsValidatorHasToValidateRequest: wiretype end group for non-group") } if fieldNum <= 0 { - return fmt.Errorf("proto: QueryConsumerChainOptedInValidatorsRequest: illegal tag %d (wire type %d)", fieldNum, wire) + return fmt.Errorf("proto: QueryConsumerChainsValidatorHasToValidateRequest: illegal tag %d (wire type %d)", fieldNum, wire) } switch fieldNum { case 1: if wireType != 2 { - return fmt.Errorf("proto: wrong wireType = %d for field ChainId", wireType) + return fmt.Errorf("proto: wrong wireType = %d for field ProviderAddress", wireType) } var stringLen uint64 for shift := uint(0); ; shift += 7 { @@ -6663,7 +7175,7 @@ func (m *QueryConsumerChainOptedInValidatorsRequest) Unmarshal(dAtA []byte) erro if postIndex > l { return io.ErrUnexpectedEOF } - m.ChainId = string(dAtA[iNdEx:postIndex]) + m.ProviderAddress = string(dAtA[iNdEx:postIndex]) iNdEx = postIndex default: iNdEx = preIndex @@ -6686,7 +7198,7 @@ func (m *QueryConsumerChainOptedInValidatorsRequest) Unmarshal(dAtA []byte) erro } return nil } -func (m *QueryConsumerChainOptedInValidatorsResponse) Unmarshal(dAtA []byte) error { +func (m *QueryConsumerChainsValidatorHasToValidateResponse) Unmarshal(dAtA []byte) error { l := len(dAtA) iNdEx := 0 for iNdEx < l { @@ -6709,15 +7221,15 @@ func (m *QueryConsumerChainOptedInValidatorsResponse) Unmarshal(dAtA []byte) err fieldNum := int32(wire >> 3) wireType := int(wire & 0x7) if wireType == 4 { - return fmt.Errorf("proto: QueryConsumerChainOptedInValidatorsResponse: wiretype end group for non-group") + return fmt.Errorf("proto: QueryConsumerChainsValidatorHasToValidateResponse: wiretype end group for non-group") } if fieldNum <= 0 { - return fmt.Errorf("proto: QueryConsumerChainOptedInValidatorsResponse: illegal tag %d (wire type %d)", fieldNum, wire) + return fmt.Errorf("proto: QueryConsumerChainsValidatorHasToValidateResponse: illegal tag %d (wire type %d)", fieldNum, wire) } switch fieldNum { case 1: if wireType != 2 { - return fmt.Errorf("proto: wrong wireType = %d for field ValidatorsProviderAddresses", wireType) + return fmt.Errorf("proto: wrong wireType = %d for field ConsumerIds", wireType) } var stringLen uint64 for shift := uint(0); ; shift += 7 { @@ -6745,7 +7257,7 @@ func (m *QueryConsumerChainOptedInValidatorsResponse) Unmarshal(dAtA []byte) err if postIndex > l { return io.ErrUnexpectedEOF } - m.ValidatorsProviderAddresses = append(m.ValidatorsProviderAddresses, string(dAtA[iNdEx:postIndex])) + m.ConsumerIds = append(m.ConsumerIds, string(dAtA[iNdEx:postIndex])) iNdEx = postIndex default: iNdEx = preIndex @@ -6768,7 +7280,7 @@ func (m *QueryConsumerChainOptedInValidatorsResponse) Unmarshal(dAtA []byte) err } return nil } -func (m *QueryConsumerValidatorsRequest) Unmarshal(dAtA []byte) error { +func (m *QueryValidatorConsumerCommissionRateRequest) Unmarshal(dAtA []byte) error { l := len(dAtA) iNdEx := 0 for iNdEx < l { @@ -6791,15 +7303,15 @@ func (m *QueryConsumerValidatorsRequest) Unmarshal(dAtA []byte) error { fieldNum := int32(wire >> 3) wireType := int(wire & 0x7) if wireType == 4 { - return fmt.Errorf("proto: QueryConsumerValidatorsRequest: wiretype end group for non-group") + return fmt.Errorf("proto: QueryValidatorConsumerCommissionRateRequest: wiretype end group for non-group") } if fieldNum <= 0 { - return fmt.Errorf("proto: QueryConsumerValidatorsRequest: illegal tag %d (wire type %d)", fieldNum, wire) + return fmt.Errorf("proto: QueryValidatorConsumerCommissionRateRequest: illegal tag %d (wire type %d)", fieldNum, wire) } switch fieldNum { case 1: if wireType != 2 { - return fmt.Errorf("proto: wrong wireType = %d for field ChainId", wireType) + return fmt.Errorf("proto: wrong wireType = %d for field ConsumerId", wireType) } var stringLen uint64 for shift := uint(0); ; shift += 7 { @@ -6827,7 +7339,39 @@ func (m *QueryConsumerValidatorsRequest) Unmarshal(dAtA []byte) error { if postIndex > l { return io.ErrUnexpectedEOF } - m.ChainId = string(dAtA[iNdEx:postIndex]) + m.ConsumerId = string(dAtA[iNdEx:postIndex]) + iNdEx = postIndex + case 2: + if wireType != 2 { + return fmt.Errorf("proto: wrong wireType = %d for field ProviderAddress", 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.ProviderAddress = string(dAtA[iNdEx:postIndex]) iNdEx = postIndex default: iNdEx = preIndex @@ -6850,7 +7394,7 @@ func (m *QueryConsumerValidatorsRequest) Unmarshal(dAtA []byte) error { } return nil } -func (m *QueryConsumerValidatorsValidator) Unmarshal(dAtA []byte) error { +func (m *QueryValidatorConsumerCommissionRateResponse) Unmarshal(dAtA []byte) error { l := len(dAtA) iNdEx := 0 for iNdEx < l { @@ -6873,15 +7417,15 @@ func (m *QueryConsumerValidatorsValidator) Unmarshal(dAtA []byte) error { fieldNum := int32(wire >> 3) wireType := int(wire & 0x7) if wireType == 4 { - return fmt.Errorf("proto: QueryConsumerValidatorsValidator: wiretype end group for non-group") + return fmt.Errorf("proto: QueryValidatorConsumerCommissionRateResponse: wiretype end group for non-group") } if fieldNum <= 0 { - return fmt.Errorf("proto: QueryConsumerValidatorsValidator: illegal tag %d (wire type %d)", fieldNum, wire) + return fmt.Errorf("proto: QueryValidatorConsumerCommissionRateResponse: illegal tag %d (wire type %d)", fieldNum, wire) } switch fieldNum { case 1: if wireType != 2 { - return fmt.Errorf("proto: wrong wireType = %d for field ProviderAddress", wireType) + return fmt.Errorf("proto: wrong wireType = %d for field Rate", wireType) } var stringLen uint64 for shift := uint(0); ; shift += 7 { @@ -6909,97 +7453,129 @@ func (m *QueryConsumerValidatorsValidator) Unmarshal(dAtA []byte) error { if postIndex > l { return io.ErrUnexpectedEOF } - m.ProviderAddress = string(dAtA[iNdEx:postIndex]) - iNdEx = postIndex - case 2: - if wireType != 2 { - return fmt.Errorf("proto: wrong wireType = %d for field ConsumerKey", wireType) + if err := m.Rate.Unmarshal(dAtA[iNdEx:postIndex]); err != nil { + return err } - 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 - } + iNdEx = postIndex + default: + iNdEx = preIndex + skippy, err := skipQuery(dAtA[iNdEx:]) + if err != nil { + return err } - if msglen < 0 { + if (skippy < 0) || (iNdEx+skippy) < 0 { return ErrInvalidLengthQuery } - postIndex := iNdEx + msglen - if postIndex < 0 { - return ErrInvalidLengthQuery + if (iNdEx + skippy) > l { + return io.ErrUnexpectedEOF } - if postIndex > l { + iNdEx += skippy + } + } + + if iNdEx > l { + return io.ErrUnexpectedEOF + } + return nil +} +func (m *QueryBlocksUntilNextEpochRequest) 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 } - if m.ConsumerKey == nil { - m.ConsumerKey = &crypto.PublicKey{} + b := dAtA[iNdEx] + iNdEx++ + wire |= uint64(b&0x7F) << shift + if b < 0x80 { + break } - if err := m.ConsumerKey.Unmarshal(dAtA[iNdEx:postIndex]); err != nil { + } + fieldNum := int32(wire >> 3) + wireType := int(wire & 0x7) + if wireType == 4 { + return fmt.Errorf("proto: QueryBlocksUntilNextEpochRequest: wiretype end group for non-group") + } + if fieldNum <= 0 { + return fmt.Errorf("proto: QueryBlocksUntilNextEpochRequest: illegal tag %d (wire type %d)", fieldNum, wire) + } + switch fieldNum { + default: + iNdEx = preIndex + skippy, err := skipQuery(dAtA[iNdEx:]) + if err != nil { return err } - iNdEx = postIndex - case 3: - if wireType != 0 { - return fmt.Errorf("proto: wrong wireType = %d for field Power", wireType) - } - m.Power = 0 - for shift := uint(0); ; shift += 7 { - if shift >= 64 { - return ErrIntOverflowQuery - } - if iNdEx >= l { - return io.ErrUnexpectedEOF - } - b := dAtA[iNdEx] - iNdEx++ - m.Power |= int64(b&0x7F) << shift - if b < 0x80 { - break - } + if (skippy < 0) || (iNdEx+skippy) < 0 { + return ErrInvalidLengthQuery } - case 4: - if wireType != 2 { - return fmt.Errorf("proto: wrong wireType = %d for field Rate", wireType) + if (iNdEx + skippy) > l { + return io.ErrUnexpectedEOF } - 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 - } + iNdEx += skippy + } + } + + if iNdEx > l { + return io.ErrUnexpectedEOF + } + return nil +} +func (m *QueryBlocksUntilNextEpochResponse) 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 } - intStringLen := int(stringLen) - if intStringLen < 0 { - return ErrInvalidLengthQuery + if iNdEx >= l { + return io.ErrUnexpectedEOF } - postIndex := iNdEx + intStringLen - if postIndex < 0 { - return ErrInvalidLengthQuery + b := dAtA[iNdEx] + iNdEx++ + wire |= uint64(b&0x7F) << shift + if b < 0x80 { + break } - if postIndex > l { - return io.ErrUnexpectedEOF + } + fieldNum := int32(wire >> 3) + wireType := int(wire & 0x7) + if wireType == 4 { + return fmt.Errorf("proto: QueryBlocksUntilNextEpochResponse: wiretype end group for non-group") + } + if fieldNum <= 0 { + return fmt.Errorf("proto: QueryBlocksUntilNextEpochResponse: illegal tag %d (wire type %d)", fieldNum, wire) + } + switch fieldNum { + case 1: + if wireType != 0 { + return fmt.Errorf("proto: wrong wireType = %d for field BlocksUntilNextEpoch", wireType) } - if err := m.Rate.Unmarshal(dAtA[iNdEx:postIndex]); err != nil { - return err + m.BlocksUntilNextEpoch = 0 + for shift := uint(0); ; shift += 7 { + if shift >= 64 { + return ErrIntOverflowQuery + } + if iNdEx >= l { + return io.ErrUnexpectedEOF + } + b := dAtA[iNdEx] + iNdEx++ + m.BlocksUntilNextEpoch |= uint64(b&0x7F) << shift + if b < 0x80 { + break + } } - iNdEx = postIndex default: iNdEx = preIndex skippy, err := skipQuery(dAtA[iNdEx:]) @@ -7021,7 +7597,7 @@ func (m *QueryConsumerValidatorsValidator) Unmarshal(dAtA []byte) error { } return nil } -func (m *QueryConsumerValidatorsResponse) Unmarshal(dAtA []byte) error { +func (m *QueryConsumerIdFromClientIdRequest) Unmarshal(dAtA []byte) error { l := len(dAtA) iNdEx := 0 for iNdEx < l { @@ -7044,17 +7620,17 @@ func (m *QueryConsumerValidatorsResponse) Unmarshal(dAtA []byte) error { fieldNum := int32(wire >> 3) wireType := int(wire & 0x7) if wireType == 4 { - return fmt.Errorf("proto: QueryConsumerValidatorsResponse: wiretype end group for non-group") + return fmt.Errorf("proto: QueryConsumerIdFromClientIdRequest: wiretype end group for non-group") } if fieldNum <= 0 { - return fmt.Errorf("proto: QueryConsumerValidatorsResponse: illegal tag %d (wire type %d)", fieldNum, wire) + return fmt.Errorf("proto: QueryConsumerIdFromClientIdRequest: illegal tag %d (wire type %d)", fieldNum, wire) } switch fieldNum { case 1: if wireType != 2 { - return fmt.Errorf("proto: wrong wireType = %d for field Validators", wireType) + return fmt.Errorf("proto: wrong wireType = %d for field ClientId", wireType) } - var msglen int + var stringLen uint64 for shift := uint(0); ; shift += 7 { if shift >= 64 { return ErrIntOverflowQuery @@ -7064,25 +7640,23 @@ func (m *QueryConsumerValidatorsResponse) Unmarshal(dAtA []byte) error { } b := dAtA[iNdEx] iNdEx++ - msglen |= int(b&0x7F) << shift + stringLen |= uint64(b&0x7F) << shift if b < 0x80 { break } } - if msglen < 0 { + intStringLen := int(stringLen) + if intStringLen < 0 { return ErrInvalidLengthQuery } - postIndex := iNdEx + msglen + postIndex := iNdEx + intStringLen if postIndex < 0 { return ErrInvalidLengthQuery } if postIndex > l { return io.ErrUnexpectedEOF } - m.Validators = append(m.Validators, &QueryConsumerValidatorsValidator{}) - if err := m.Validators[len(m.Validators)-1].Unmarshal(dAtA[iNdEx:postIndex]); err != nil { - return err - } + m.ClientId = string(dAtA[iNdEx:postIndex]) iNdEx = postIndex default: iNdEx = preIndex @@ -7105,7 +7679,7 @@ func (m *QueryConsumerValidatorsResponse) Unmarshal(dAtA []byte) error { } return nil } -func (m *QueryConsumerChainsValidatorHasToValidateRequest) Unmarshal(dAtA []byte) error { +func (m *QueryConsumerIdFromClientIdResponse) Unmarshal(dAtA []byte) error { l := len(dAtA) iNdEx := 0 for iNdEx < l { @@ -7128,15 +7702,15 @@ func (m *QueryConsumerChainsValidatorHasToValidateRequest) Unmarshal(dAtA []byte fieldNum := int32(wire >> 3) wireType := int(wire & 0x7) if wireType == 4 { - return fmt.Errorf("proto: QueryConsumerChainsValidatorHasToValidateRequest: wiretype end group for non-group") + return fmt.Errorf("proto: QueryConsumerIdFromClientIdResponse: wiretype end group for non-group") } if fieldNum <= 0 { - return fmt.Errorf("proto: QueryConsumerChainsValidatorHasToValidateRequest: illegal tag %d (wire type %d)", fieldNum, wire) + return fmt.Errorf("proto: QueryConsumerIdFromClientIdResponse: illegal tag %d (wire type %d)", fieldNum, wire) } switch fieldNum { case 1: if wireType != 2 { - return fmt.Errorf("proto: wrong wireType = %d for field ProviderAddress", wireType) + return fmt.Errorf("proto: wrong wireType = %d for field ConsumerId", wireType) } var stringLen uint64 for shift := uint(0); ; shift += 7 { @@ -7164,7 +7738,7 @@ func (m *QueryConsumerChainsValidatorHasToValidateRequest) Unmarshal(dAtA []byte if postIndex > l { return io.ErrUnexpectedEOF } - m.ProviderAddress = string(dAtA[iNdEx:postIndex]) + m.ConsumerId = string(dAtA[iNdEx:postIndex]) iNdEx = postIndex default: iNdEx = preIndex @@ -7187,7 +7761,7 @@ func (m *QueryConsumerChainsValidatorHasToValidateRequest) Unmarshal(dAtA []byte } return nil } -func (m *QueryConsumerChainsValidatorHasToValidateResponse) Unmarshal(dAtA []byte) error { +func (m *QueryConsumerChainRequest) Unmarshal(dAtA []byte) error { l := len(dAtA) iNdEx := 0 for iNdEx < l { @@ -7210,15 +7784,15 @@ func (m *QueryConsumerChainsValidatorHasToValidateResponse) Unmarshal(dAtA []byt fieldNum := int32(wire >> 3) wireType := int(wire & 0x7) if wireType == 4 { - return fmt.Errorf("proto: QueryConsumerChainsValidatorHasToValidateResponse: wiretype end group for non-group") + return fmt.Errorf("proto: QueryConsumerChainRequest: wiretype end group for non-group") } if fieldNum <= 0 { - return fmt.Errorf("proto: QueryConsumerChainsValidatorHasToValidateResponse: illegal tag %d (wire type %d)", fieldNum, wire) + return fmt.Errorf("proto: QueryConsumerChainRequest: illegal tag %d (wire type %d)", fieldNum, wire) } switch fieldNum { case 1: if wireType != 2 { - return fmt.Errorf("proto: wrong wireType = %d for field ConsumerChainIds", wireType) + return fmt.Errorf("proto: wrong wireType = %d for field ConsumerId", wireType) } var stringLen uint64 for shift := uint(0); ; shift += 7 { @@ -7246,7 +7820,7 @@ func (m *QueryConsumerChainsValidatorHasToValidateResponse) Unmarshal(dAtA []byt if postIndex > l { return io.ErrUnexpectedEOF } - m.ConsumerChainIds = append(m.ConsumerChainIds, string(dAtA[iNdEx:postIndex])) + m.ConsumerId = string(dAtA[iNdEx:postIndex]) iNdEx = postIndex default: iNdEx = preIndex @@ -7269,7 +7843,7 @@ func (m *QueryConsumerChainsValidatorHasToValidateResponse) Unmarshal(dAtA []byt } return nil } -func (m *QueryValidatorConsumerCommissionRateRequest) Unmarshal(dAtA []byte) error { +func (m *QueryConsumerChainResponse) Unmarshal(dAtA []byte) error { l := len(dAtA) iNdEx := 0 for iNdEx < l { @@ -7292,10 +7866,10 @@ func (m *QueryValidatorConsumerCommissionRateRequest) Unmarshal(dAtA []byte) err fieldNum := int32(wire >> 3) wireType := int(wire & 0x7) if wireType == 4 { - return fmt.Errorf("proto: QueryValidatorConsumerCommissionRateRequest: wiretype end group for non-group") + return fmt.Errorf("proto: QueryConsumerChainResponse: wiretype end group for non-group") } if fieldNum <= 0 { - return fmt.Errorf("proto: QueryValidatorConsumerCommissionRateRequest: illegal tag %d (wire type %d)", fieldNum, wire) + return fmt.Errorf("proto: QueryConsumerChainResponse: illegal tag %d (wire type %d)", fieldNum, wire) } switch fieldNum { case 1: @@ -7332,7 +7906,7 @@ func (m *QueryValidatorConsumerCommissionRateRequest) Unmarshal(dAtA []byte) err iNdEx = postIndex case 2: if wireType != 2 { - return fmt.Errorf("proto: wrong wireType = %d for field ProviderAddress", wireType) + return fmt.Errorf("proto: wrong wireType = %d for field OwnerAddress", wireType) } var stringLen uint64 for shift := uint(0); ; shift += 7 { @@ -7360,61 +7934,11 @@ func (m *QueryValidatorConsumerCommissionRateRequest) Unmarshal(dAtA []byte) err if postIndex > l { return io.ErrUnexpectedEOF } - m.ProviderAddress = string(dAtA[iNdEx:postIndex]) + m.OwnerAddress = 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 *QueryValidatorConsumerCommissionRateResponse) 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: QueryValidatorConsumerCommissionRateResponse: wiretype end group for non-group") - } - if fieldNum <= 0 { - return fmt.Errorf("proto: QueryValidatorConsumerCommissionRateResponse: illegal tag %d (wire type %d)", fieldNum, wire) - } - switch fieldNum { - case 1: + case 3: if wireType != 2 { - return fmt.Errorf("proto: wrong wireType = %d for field Rate", wireType) + return fmt.Errorf("proto: wrong wireType = %d for field Phase", wireType) } var stringLen uint64 for shift := uint(0); ; shift += 7 { @@ -7442,115 +7966,82 @@ func (m *QueryValidatorConsumerCommissionRateResponse) Unmarshal(dAtA []byte) er if postIndex > l { return io.ErrUnexpectedEOF } - if err := m.Rate.Unmarshal(dAtA[iNdEx:postIndex]); err != nil { - return err - } + m.Phase = string(dAtA[iNdEx:postIndex]) iNdEx = postIndex - default: - iNdEx = preIndex - skippy, err := skipQuery(dAtA[iNdEx:]) - if err != nil { - return err + case 4: + if wireType != 2 { + return fmt.Errorf("proto: wrong wireType = %d for field Metadata", wireType) } - if (skippy < 0) || (iNdEx+skippy) < 0 { + 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 } - if (iNdEx + skippy) > l { + postIndex := iNdEx + msglen + if postIndex < 0 { + return ErrInvalidLengthQuery + } + if postIndex > l { return io.ErrUnexpectedEOF } - iNdEx += skippy - } - } - - if iNdEx > l { - return io.ErrUnexpectedEOF - } - return nil -} -func (m *QueryBlocksUntilNextEpochRequest) 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 err := m.Metadata.Unmarshal(dAtA[iNdEx:postIndex]); err != nil { + return err } - if iNdEx >= l { - return io.ErrUnexpectedEOF + iNdEx = postIndex + case 5: + if wireType != 2 { + return fmt.Errorf("proto: wrong wireType = %d for field InitParams", wireType) } - b := dAtA[iNdEx] - iNdEx++ - wire |= uint64(b&0x7F) << shift - if b < 0x80 { - break + 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 + } } - } - fieldNum := int32(wire >> 3) - wireType := int(wire & 0x7) - if wireType == 4 { - return fmt.Errorf("proto: QueryBlocksUntilNextEpochRequest: wiretype end group for non-group") - } - if fieldNum <= 0 { - return fmt.Errorf("proto: QueryBlocksUntilNextEpochRequest: illegal tag %d (wire type %d)", fieldNum, wire) - } - switch fieldNum { - default: - iNdEx = preIndex - skippy, err := skipQuery(dAtA[iNdEx:]) - if err != nil { - return err + if msglen < 0 { + return ErrInvalidLengthQuery } - if (skippy < 0) || (iNdEx+skippy) < 0 { + postIndex := iNdEx + msglen + if postIndex < 0 { return ErrInvalidLengthQuery } - if (iNdEx + skippy) > l { + if postIndex > l { return io.ErrUnexpectedEOF } - iNdEx += skippy - } - } - - if iNdEx > l { - return io.ErrUnexpectedEOF - } - return nil -} -func (m *QueryBlocksUntilNextEpochResponse) 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 + if m.InitParams == nil { + m.InitParams = &ConsumerInitializationParameters{} } - b := dAtA[iNdEx] - iNdEx++ - wire |= uint64(b&0x7F) << shift - if b < 0x80 { - break + if err := m.InitParams.Unmarshal(dAtA[iNdEx:postIndex]); err != nil { + return err } - } - fieldNum := int32(wire >> 3) - wireType := int(wire & 0x7) - if wireType == 4 { - return fmt.Errorf("proto: QueryBlocksUntilNextEpochResponse: wiretype end group for non-group") - } - if fieldNum <= 0 { - return fmt.Errorf("proto: QueryBlocksUntilNextEpochResponse: illegal tag %d (wire type %d)", fieldNum, wire) - } - switch fieldNum { - case 1: - if wireType != 0 { - return fmt.Errorf("proto: wrong wireType = %d for field BlocksUntilNextEpoch", wireType) + iNdEx = postIndex + case 6: + if wireType != 2 { + return fmt.Errorf("proto: wrong wireType = %d for field PowerShapingParams", wireType) } - m.BlocksUntilNextEpoch = 0 + var msglen int for shift := uint(0); ; shift += 7 { if shift >= 64 { return ErrIntOverflowQuery @@ -7560,11 +8051,28 @@ func (m *QueryBlocksUntilNextEpochResponse) Unmarshal(dAtA []byte) error { } b := dAtA[iNdEx] iNdEx++ - m.BlocksUntilNextEpoch |= uint64(b&0x7F) << shift + 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.PowerShapingParams == nil { + m.PowerShapingParams = &PowerShapingParameters{} + } + if err := m.PowerShapingParams.Unmarshal(dAtA[iNdEx:postIndex]); err != nil { + return err + } + iNdEx = postIndex default: iNdEx = preIndex skippy, err := skipQuery(dAtA[iNdEx:]) diff --git a/x/ccv/provider/types/query.pb.gw.go b/x/ccv/provider/types/query.pb.gw.go index a115ace156..e6fdfc5f76 100644 --- a/x/ccv/provider/types/query.pb.gw.go +++ b/x/ccv/provider/types/query.pb.gw.go @@ -44,15 +44,15 @@ func request_Query_QueryConsumerGenesis_0(ctx context.Context, marshaler runtime _ = err ) - val, ok = pathParams["chain_id"] + val, ok = pathParams["consumer_id"] if !ok { - return nil, metadata, status.Errorf(codes.InvalidArgument, "missing parameter %s", "chain_id") + return nil, metadata, status.Errorf(codes.InvalidArgument, "missing parameter %s", "consumer_id") } - protoReq.ChainId, err = runtime.String(val) + protoReq.ConsumerId, err = runtime.String(val) if err != nil { - return nil, metadata, status.Errorf(codes.InvalidArgument, "type mismatch, parameter: %s, error: %v", "chain_id", err) + return nil, metadata, status.Errorf(codes.InvalidArgument, "type mismatch, parameter: %s, error: %v", "consumer_id", err) } msg, err := client.QueryConsumerGenesis(ctx, &protoReq, grpc.Header(&metadata.HeaderMD), grpc.Trailer(&metadata.TrailerMD)) @@ -71,15 +71,15 @@ func local_request_Query_QueryConsumerGenesis_0(ctx context.Context, marshaler r _ = err ) - val, ok = pathParams["chain_id"] + val, ok = pathParams["consumer_id"] if !ok { - return nil, metadata, status.Errorf(codes.InvalidArgument, "missing parameter %s", "chain_id") + return nil, metadata, status.Errorf(codes.InvalidArgument, "missing parameter %s", "consumer_id") } - protoReq.ChainId, err = runtime.String(val) + protoReq.ConsumerId, err = runtime.String(val) if err != nil { - return nil, metadata, status.Errorf(codes.InvalidArgument, "type mismatch, parameter: %s, error: %v", "chain_id", err) + return nil, metadata, status.Errorf(codes.InvalidArgument, "type mismatch, parameter: %s, error: %v", "consumer_id", err) } msg, err := server.QueryConsumerGenesis(ctx, &protoReq) @@ -91,6 +91,38 @@ func request_Query_QueryConsumerChains_0(ctx context.Context, marshaler runtime. var protoReq QueryConsumerChainsRequest var metadata runtime.ServerMetadata + var ( + val string + e int32 + ok bool + err error + _ = err + ) + + val, ok = pathParams["phase"] + if !ok { + return nil, metadata, status.Errorf(codes.InvalidArgument, "missing parameter %s", "phase") + } + + e, err = runtime.Enum(val, ConsumerPhase_value) + + if err != nil { + return nil, metadata, status.Errorf(codes.InvalidArgument, "type mismatch, parameter: %s, error: %v", "phase", err) + } + + protoReq.Phase = ConsumerPhase(e) + + val, ok = pathParams["limit"] + if !ok { + return nil, metadata, status.Errorf(codes.InvalidArgument, "missing parameter %s", "limit") + } + + protoReq.Limit, err = runtime.Int32(val) + + if err != nil { + return nil, metadata, status.Errorf(codes.InvalidArgument, "type mismatch, parameter: %s, error: %v", "limit", err) + } + msg, err := client.QueryConsumerChains(ctx, &protoReq, grpc.Header(&metadata.HeaderMD), grpc.Trailer(&metadata.TrailerMD)) return msg, metadata, err @@ -100,60 +132,74 @@ func local_request_Query_QueryConsumerChains_0(ctx context.Context, marshaler ru var protoReq QueryConsumerChainsRequest var metadata runtime.ServerMetadata - msg, err := server.QueryConsumerChains(ctx, &protoReq) - return msg, metadata, err - -} + var ( + val string + e int32 + ok bool + err error + _ = err + ) -func request_Query_QueryConsumerChainStarts_0(ctx context.Context, marshaler runtime.Marshaler, client QueryClient, req *http.Request, pathParams map[string]string) (proto.Message, runtime.ServerMetadata, error) { - var protoReq QueryConsumerChainStartProposalsRequest - var metadata runtime.ServerMetadata + val, ok = pathParams["phase"] + if !ok { + return nil, metadata, status.Errorf(codes.InvalidArgument, "missing parameter %s", "phase") + } - msg, err := client.QueryConsumerChainStarts(ctx, &protoReq, grpc.Header(&metadata.HeaderMD), grpc.Trailer(&metadata.TrailerMD)) - return msg, metadata, err + e, err = runtime.Enum(val, ConsumerPhase_value) -} + if err != nil { + return nil, metadata, status.Errorf(codes.InvalidArgument, "type mismatch, parameter: %s, error: %v", "phase", err) + } -func local_request_Query_QueryConsumerChainStarts_0(ctx context.Context, marshaler runtime.Marshaler, server QueryServer, req *http.Request, pathParams map[string]string) (proto.Message, runtime.ServerMetadata, error) { - var protoReq QueryConsumerChainStartProposalsRequest - var metadata runtime.ServerMetadata + protoReq.Phase = ConsumerPhase(e) - msg, err := server.QueryConsumerChainStarts(ctx, &protoReq) - return msg, metadata, err + val, ok = pathParams["limit"] + if !ok { + return nil, metadata, status.Errorf(codes.InvalidArgument, "missing parameter %s", "limit") + } -} + protoReq.Limit, err = runtime.Int32(val) -func request_Query_QueryConsumerChainStops_0(ctx context.Context, marshaler runtime.Marshaler, client QueryClient, req *http.Request, pathParams map[string]string) (proto.Message, runtime.ServerMetadata, error) { - var protoReq QueryConsumerChainStopProposalsRequest - var metadata runtime.ServerMetadata + if err != nil { + return nil, metadata, status.Errorf(codes.InvalidArgument, "type mismatch, parameter: %s, error: %v", "limit", err) + } - msg, err := client.QueryConsumerChainStops(ctx, &protoReq, grpc.Header(&metadata.HeaderMD), grpc.Trailer(&metadata.TrailerMD)) + msg, err := server.QueryConsumerChains(ctx, &protoReq) return msg, metadata, err } -func local_request_Query_QueryConsumerChainStops_0(ctx context.Context, marshaler runtime.Marshaler, server QueryServer, req *http.Request, pathParams map[string]string) (proto.Message, runtime.ServerMetadata, error) { - var protoReq QueryConsumerChainStopProposalsRequest +func request_Query_QueryValidatorConsumerAddr_0(ctx context.Context, marshaler runtime.Marshaler, client QueryClient, req *http.Request, pathParams map[string]string) (proto.Message, runtime.ServerMetadata, error) { + var protoReq QueryValidatorConsumerAddrRequest var metadata runtime.ServerMetadata - msg, err := server.QueryConsumerChainStops(ctx, &protoReq) - return msg, metadata, err + var ( + val string + ok bool + err error + _ = err + ) -} + val, ok = pathParams["consumer_id"] + if !ok { + return nil, metadata, status.Errorf(codes.InvalidArgument, "missing parameter %s", "consumer_id") + } -var ( - filter_Query_QueryValidatorConsumerAddr_0 = &utilities.DoubleArray{Encoding: map[string]int{}, Base: []int(nil), Check: []int(nil)} -) + protoReq.ConsumerId, err = runtime.String(val) -func request_Query_QueryValidatorConsumerAddr_0(ctx context.Context, marshaler runtime.Marshaler, client QueryClient, req *http.Request, pathParams map[string]string) (proto.Message, runtime.ServerMetadata, error) { - var protoReq QueryValidatorConsumerAddrRequest - var metadata runtime.ServerMetadata + if err != nil { + return nil, metadata, status.Errorf(codes.InvalidArgument, "type mismatch, parameter: %s, error: %v", "consumer_id", err) + } - if err := req.ParseForm(); err != nil { - return nil, metadata, status.Errorf(codes.InvalidArgument, "%v", err) + val, ok = pathParams["provider_address"] + if !ok { + return nil, metadata, status.Errorf(codes.InvalidArgument, "missing parameter %s", "provider_address") } - if err := runtime.PopulateQueryParameters(&protoReq, req.Form, filter_Query_QueryValidatorConsumerAddr_0); err != nil { - return nil, metadata, status.Errorf(codes.InvalidArgument, "%v", err) + + protoReq.ProviderAddress, err = runtime.String(val) + + if err != nil { + return nil, metadata, status.Errorf(codes.InvalidArgument, "type mismatch, parameter: %s, error: %v", "provider_address", err) } msg, err := client.QueryValidatorConsumerAddr(ctx, &protoReq, grpc.Header(&metadata.HeaderMD), grpc.Trailer(&metadata.TrailerMD)) @@ -165,11 +211,33 @@ func local_request_Query_QueryValidatorConsumerAddr_0(ctx context.Context, marsh var protoReq QueryValidatorConsumerAddrRequest var metadata runtime.ServerMetadata - if err := req.ParseForm(); err != nil { - return nil, metadata, status.Errorf(codes.InvalidArgument, "%v", err) + var ( + val string + ok bool + err error + _ = err + ) + + val, ok = pathParams["consumer_id"] + if !ok { + return nil, metadata, status.Errorf(codes.InvalidArgument, "missing parameter %s", "consumer_id") + } + + protoReq.ConsumerId, err = runtime.String(val) + + if err != nil { + return nil, metadata, status.Errorf(codes.InvalidArgument, "type mismatch, parameter: %s, error: %v", "consumer_id", err) + } + + val, ok = pathParams["provider_address"] + if !ok { + return nil, metadata, status.Errorf(codes.InvalidArgument, "missing parameter %s", "provider_address") } - if err := runtime.PopulateQueryParameters(&protoReq, req.Form, filter_Query_QueryValidatorConsumerAddr_0); err != nil { - return nil, metadata, status.Errorf(codes.InvalidArgument, "%v", err) + + protoReq.ProviderAddress, err = runtime.String(val) + + if err != nil { + return nil, metadata, status.Errorf(codes.InvalidArgument, "type mismatch, parameter: %s, error: %v", "provider_address", err) } msg, err := server.QueryValidatorConsumerAddr(ctx, &protoReq) @@ -177,19 +245,37 @@ func local_request_Query_QueryValidatorConsumerAddr_0(ctx context.Context, marsh } -var ( - filter_Query_QueryValidatorProviderAddr_0 = &utilities.DoubleArray{Encoding: map[string]int{}, Base: []int(nil), Check: []int(nil)} -) - func request_Query_QueryValidatorProviderAddr_0(ctx context.Context, marshaler runtime.Marshaler, client QueryClient, req *http.Request, pathParams map[string]string) (proto.Message, runtime.ServerMetadata, error) { var protoReq QueryValidatorProviderAddrRequest var metadata runtime.ServerMetadata - if err := req.ParseForm(); err != nil { - return nil, metadata, status.Errorf(codes.InvalidArgument, "%v", err) + var ( + val string + ok bool + err error + _ = err + ) + + val, ok = pathParams["consumer_id"] + if !ok { + return nil, metadata, status.Errorf(codes.InvalidArgument, "missing parameter %s", "consumer_id") } - if err := runtime.PopulateQueryParameters(&protoReq, req.Form, filter_Query_QueryValidatorProviderAddr_0); err != nil { - return nil, metadata, status.Errorf(codes.InvalidArgument, "%v", err) + + protoReq.ConsumerId, err = runtime.String(val) + + if err != nil { + return nil, metadata, status.Errorf(codes.InvalidArgument, "type mismatch, parameter: %s, error: %v", "consumer_id", err) + } + + val, ok = pathParams["consumer_address"] + if !ok { + return nil, metadata, status.Errorf(codes.InvalidArgument, "missing parameter %s", "consumer_address") + } + + protoReq.ConsumerAddress, err = runtime.String(val) + + if err != nil { + return nil, metadata, status.Errorf(codes.InvalidArgument, "type mismatch, parameter: %s, error: %v", "consumer_address", err) } msg, err := client.QueryValidatorProviderAddr(ctx, &protoReq, grpc.Header(&metadata.HeaderMD), grpc.Trailer(&metadata.TrailerMD)) @@ -201,11 +287,33 @@ func local_request_Query_QueryValidatorProviderAddr_0(ctx context.Context, marsh var protoReq QueryValidatorProviderAddrRequest var metadata runtime.ServerMetadata - if err := req.ParseForm(); err != nil { - return nil, metadata, status.Errorf(codes.InvalidArgument, "%v", err) + var ( + val string + ok bool + err error + _ = err + ) + + val, ok = pathParams["consumer_id"] + if !ok { + return nil, metadata, status.Errorf(codes.InvalidArgument, "missing parameter %s", "consumer_id") + } + + protoReq.ConsumerId, err = runtime.String(val) + + if err != nil { + return nil, metadata, status.Errorf(codes.InvalidArgument, "type mismatch, parameter: %s, error: %v", "consumer_id", err) + } + + val, ok = pathParams["consumer_address"] + if !ok { + return nil, metadata, status.Errorf(codes.InvalidArgument, "missing parameter %s", "consumer_address") } - if err := runtime.PopulateQueryParameters(&protoReq, req.Form, filter_Query_QueryValidatorProviderAddr_0); err != nil { - return nil, metadata, status.Errorf(codes.InvalidArgument, "%v", err) + + protoReq.ConsumerAddress, err = runtime.String(val) + + if err != nil { + return nil, metadata, status.Errorf(codes.InvalidArgument, "type mismatch, parameter: %s, error: %v", "consumer_address", err) } msg, err := server.QueryValidatorProviderAddr(ctx, &protoReq) @@ -249,56 +357,56 @@ func local_request_Query_QueryRegisteredConsumerRewardDenoms_0(ctx context.Conte } -func request_Query_QueryProposedConsumerChainIDs_0(ctx context.Context, marshaler runtime.Marshaler, client QueryClient, req *http.Request, pathParams map[string]string) (proto.Message, runtime.ServerMetadata, error) { - var protoReq QueryProposedChainIDsRequest +func request_Query_QueryAllPairsValConsAddrByConsumer_0(ctx context.Context, marshaler runtime.Marshaler, client QueryClient, req *http.Request, pathParams map[string]string) (proto.Message, runtime.ServerMetadata, error) { + var protoReq QueryAllPairsValConsAddrByConsumerRequest var metadata runtime.ServerMetadata - msg, err := client.QueryProposedConsumerChainIDs(ctx, &protoReq, grpc.Header(&metadata.HeaderMD), grpc.Trailer(&metadata.TrailerMD)) - return msg, metadata, err - -} - -func local_request_Query_QueryProposedConsumerChainIDs_0(ctx context.Context, marshaler runtime.Marshaler, server QueryServer, req *http.Request, pathParams map[string]string) (proto.Message, runtime.ServerMetadata, error) { - var protoReq QueryProposedChainIDsRequest - var metadata runtime.ServerMetadata - - msg, err := server.QueryProposedConsumerChainIDs(ctx, &protoReq) - return msg, metadata, err - -} + var ( + val string + ok bool + err error + _ = err + ) -var ( - filter_Query_QueryAllPairsValConAddrByConsumerChainID_0 = &utilities.DoubleArray{Encoding: map[string]int{}, Base: []int(nil), Check: []int(nil)} -) + val, ok = pathParams["consumer_id"] + if !ok { + return nil, metadata, status.Errorf(codes.InvalidArgument, "missing parameter %s", "consumer_id") + } -func request_Query_QueryAllPairsValConAddrByConsumerChainID_0(ctx context.Context, marshaler runtime.Marshaler, client QueryClient, req *http.Request, pathParams map[string]string) (proto.Message, runtime.ServerMetadata, error) { - var protoReq QueryAllPairsValConAddrByConsumerChainIDRequest - var metadata runtime.ServerMetadata + protoReq.ConsumerId, err = runtime.String(val) - if err := req.ParseForm(); err != nil { - return nil, metadata, status.Errorf(codes.InvalidArgument, "%v", err) - } - if err := runtime.PopulateQueryParameters(&protoReq, req.Form, filter_Query_QueryAllPairsValConAddrByConsumerChainID_0); err != nil { - return nil, metadata, status.Errorf(codes.InvalidArgument, "%v", err) + if err != nil { + return nil, metadata, status.Errorf(codes.InvalidArgument, "type mismatch, parameter: %s, error: %v", "consumer_id", err) } - msg, err := client.QueryAllPairsValConAddrByConsumerChainID(ctx, &protoReq, grpc.Header(&metadata.HeaderMD), grpc.Trailer(&metadata.TrailerMD)) + msg, err := client.QueryAllPairsValConsAddrByConsumer(ctx, &protoReq, grpc.Header(&metadata.HeaderMD), grpc.Trailer(&metadata.TrailerMD)) return msg, metadata, err } -func local_request_Query_QueryAllPairsValConAddrByConsumerChainID_0(ctx context.Context, marshaler runtime.Marshaler, server QueryServer, req *http.Request, pathParams map[string]string) (proto.Message, runtime.ServerMetadata, error) { - var protoReq QueryAllPairsValConAddrByConsumerChainIDRequest +func local_request_Query_QueryAllPairsValConsAddrByConsumer_0(ctx context.Context, marshaler runtime.Marshaler, server QueryServer, req *http.Request, pathParams map[string]string) (proto.Message, runtime.ServerMetadata, error) { + var protoReq QueryAllPairsValConsAddrByConsumerRequest var metadata runtime.ServerMetadata - if err := req.ParseForm(); err != nil { - return nil, metadata, status.Errorf(codes.InvalidArgument, "%v", err) + var ( + val string + ok bool + err error + _ = err + ) + + val, ok = pathParams["consumer_id"] + if !ok { + return nil, metadata, status.Errorf(codes.InvalidArgument, "missing parameter %s", "consumer_id") } - if err := runtime.PopulateQueryParameters(&protoReq, req.Form, filter_Query_QueryAllPairsValConAddrByConsumerChainID_0); err != nil { - return nil, metadata, status.Errorf(codes.InvalidArgument, "%v", err) + + protoReq.ConsumerId, err = runtime.String(val) + + if err != nil { + return nil, metadata, status.Errorf(codes.InvalidArgument, "type mismatch, parameter: %s, error: %v", "consumer_id", err) } - msg, err := server.QueryAllPairsValConAddrByConsumerChainID(ctx, &protoReq) + msg, err := server.QueryAllPairsValConsAddrByConsumer(ctx, &protoReq) return msg, metadata, err } @@ -332,15 +440,15 @@ func request_Query_QueryConsumerChainOptedInValidators_0(ctx context.Context, ma _ = err ) - val, ok = pathParams["chain_id"] + val, ok = pathParams["consumer_id"] if !ok { - return nil, metadata, status.Errorf(codes.InvalidArgument, "missing parameter %s", "chain_id") + return nil, metadata, status.Errorf(codes.InvalidArgument, "missing parameter %s", "consumer_id") } - protoReq.ChainId, err = runtime.String(val) + protoReq.ConsumerId, err = runtime.String(val) if err != nil { - return nil, metadata, status.Errorf(codes.InvalidArgument, "type mismatch, parameter: %s, error: %v", "chain_id", err) + return nil, metadata, status.Errorf(codes.InvalidArgument, "type mismatch, parameter: %s, error: %v", "consumer_id", err) } msg, err := client.QueryConsumerChainOptedInValidators(ctx, &protoReq, grpc.Header(&metadata.HeaderMD), grpc.Trailer(&metadata.TrailerMD)) @@ -359,15 +467,15 @@ func local_request_Query_QueryConsumerChainOptedInValidators_0(ctx context.Conte _ = err ) - val, ok = pathParams["chain_id"] + val, ok = pathParams["consumer_id"] if !ok { - return nil, metadata, status.Errorf(codes.InvalidArgument, "missing parameter %s", "chain_id") + return nil, metadata, status.Errorf(codes.InvalidArgument, "missing parameter %s", "consumer_id") } - protoReq.ChainId, err = runtime.String(val) + protoReq.ConsumerId, err = runtime.String(val) if err != nil { - return nil, metadata, status.Errorf(codes.InvalidArgument, "type mismatch, parameter: %s, error: %v", "chain_id", err) + return nil, metadata, status.Errorf(codes.InvalidArgument, "type mismatch, parameter: %s, error: %v", "consumer_id", err) } msg, err := server.QueryConsumerChainOptedInValidators(ctx, &protoReq) @@ -440,15 +548,15 @@ func request_Query_QueryValidatorConsumerCommissionRate_0(ctx context.Context, m _ = err ) - val, ok = pathParams["chain_id"] + val, ok = pathParams["consumer_id"] if !ok { - return nil, metadata, status.Errorf(codes.InvalidArgument, "missing parameter %s", "chain_id") + return nil, metadata, status.Errorf(codes.InvalidArgument, "missing parameter %s", "consumer_id") } - protoReq.ChainId, err = runtime.String(val) + protoReq.ConsumerId, err = runtime.String(val) if err != nil { - return nil, metadata, status.Errorf(codes.InvalidArgument, "type mismatch, parameter: %s, error: %v", "chain_id", err) + return nil, metadata, status.Errorf(codes.InvalidArgument, "type mismatch, parameter: %s, error: %v", "consumer_id", err) } val, ok = pathParams["provider_address"] @@ -478,15 +586,15 @@ func local_request_Query_QueryValidatorConsumerCommissionRate_0(ctx context.Cont _ = err ) - val, ok = pathParams["chain_id"] + val, ok = pathParams["consumer_id"] if !ok { - return nil, metadata, status.Errorf(codes.InvalidArgument, "missing parameter %s", "chain_id") + return nil, metadata, status.Errorf(codes.InvalidArgument, "missing parameter %s", "consumer_id") } - protoReq.ChainId, err = runtime.String(val) + protoReq.ConsumerId, err = runtime.String(val) if err != nil { - return nil, metadata, status.Errorf(codes.InvalidArgument, "type mismatch, parameter: %s, error: %v", "chain_id", err) + return nil, metadata, status.Errorf(codes.InvalidArgument, "type mismatch, parameter: %s, error: %v", "consumer_id", err) } val, ok = pathParams["provider_address"] @@ -516,15 +624,15 @@ func request_Query_QueryConsumerValidators_0(ctx context.Context, marshaler runt _ = err ) - val, ok = pathParams["chain_id"] + val, ok = pathParams["consumer_id"] if !ok { - return nil, metadata, status.Errorf(codes.InvalidArgument, "missing parameter %s", "chain_id") + return nil, metadata, status.Errorf(codes.InvalidArgument, "missing parameter %s", "consumer_id") } - protoReq.ChainId, err = runtime.String(val) + protoReq.ConsumerId, err = runtime.String(val) if err != nil { - return nil, metadata, status.Errorf(codes.InvalidArgument, "type mismatch, parameter: %s, error: %v", "chain_id", err) + return nil, metadata, status.Errorf(codes.InvalidArgument, "type mismatch, parameter: %s, error: %v", "consumer_id", err) } msg, err := client.QueryConsumerValidators(ctx, &protoReq, grpc.Header(&metadata.HeaderMD), grpc.Trailer(&metadata.TrailerMD)) @@ -543,15 +651,15 @@ func local_request_Query_QueryConsumerValidators_0(ctx context.Context, marshale _ = err ) - val, ok = pathParams["chain_id"] + val, ok = pathParams["consumer_id"] if !ok { - return nil, metadata, status.Errorf(codes.InvalidArgument, "missing parameter %s", "chain_id") + return nil, metadata, status.Errorf(codes.InvalidArgument, "missing parameter %s", "consumer_id") } - protoReq.ChainId, err = runtime.String(val) + protoReq.ConsumerId, err = runtime.String(val) if err != nil { - return nil, metadata, status.Errorf(codes.InvalidArgument, "type mismatch, parameter: %s, error: %v", "chain_id", err) + return nil, metadata, status.Errorf(codes.InvalidArgument, "type mismatch, parameter: %s, error: %v", "consumer_id", err) } msg, err := server.QueryConsumerValidators(ctx, &protoReq) @@ -577,6 +685,114 @@ func local_request_Query_QueryBlocksUntilNextEpoch_0(ctx context.Context, marsha } +func request_Query_QueryConsumerIdFromClientId_0(ctx context.Context, marshaler runtime.Marshaler, client QueryClient, req *http.Request, pathParams map[string]string) (proto.Message, runtime.ServerMetadata, error) { + var protoReq QueryConsumerIdFromClientIdRequest + var metadata runtime.ServerMetadata + + var ( + val string + ok bool + err error + _ = err + ) + + val, ok = pathParams["client_id"] + if !ok { + return nil, metadata, status.Errorf(codes.InvalidArgument, "missing parameter %s", "client_id") + } + + protoReq.ClientId, err = runtime.String(val) + + if err != nil { + return nil, metadata, status.Errorf(codes.InvalidArgument, "type mismatch, parameter: %s, error: %v", "client_id", err) + } + + msg, err := client.QueryConsumerIdFromClientId(ctx, &protoReq, grpc.Header(&metadata.HeaderMD), grpc.Trailer(&metadata.TrailerMD)) + return msg, metadata, err + +} + +func local_request_Query_QueryConsumerIdFromClientId_0(ctx context.Context, marshaler runtime.Marshaler, server QueryServer, req *http.Request, pathParams map[string]string) (proto.Message, runtime.ServerMetadata, error) { + var protoReq QueryConsumerIdFromClientIdRequest + var metadata runtime.ServerMetadata + + var ( + val string + ok bool + err error + _ = err + ) + + val, ok = pathParams["client_id"] + if !ok { + return nil, metadata, status.Errorf(codes.InvalidArgument, "missing parameter %s", "client_id") + } + + protoReq.ClientId, err = runtime.String(val) + + if err != nil { + return nil, metadata, status.Errorf(codes.InvalidArgument, "type mismatch, parameter: %s, error: %v", "client_id", err) + } + + msg, err := server.QueryConsumerIdFromClientId(ctx, &protoReq) + return msg, metadata, err + +} + +func request_Query_QueryConsumerChain_0(ctx context.Context, marshaler runtime.Marshaler, client QueryClient, req *http.Request, pathParams map[string]string) (proto.Message, runtime.ServerMetadata, error) { + var protoReq QueryConsumerChainRequest + var metadata runtime.ServerMetadata + + var ( + val string + ok bool + err error + _ = err + ) + + val, ok = pathParams["consumer_id"] + if !ok { + return nil, metadata, status.Errorf(codes.InvalidArgument, "missing parameter %s", "consumer_id") + } + + protoReq.ConsumerId, err = runtime.String(val) + + if err != nil { + return nil, metadata, status.Errorf(codes.InvalidArgument, "type mismatch, parameter: %s, error: %v", "consumer_id", err) + } + + msg, err := client.QueryConsumerChain(ctx, &protoReq, grpc.Header(&metadata.HeaderMD), grpc.Trailer(&metadata.TrailerMD)) + return msg, metadata, err + +} + +func local_request_Query_QueryConsumerChain_0(ctx context.Context, marshaler runtime.Marshaler, server QueryServer, req *http.Request, pathParams map[string]string) (proto.Message, runtime.ServerMetadata, error) { + var protoReq QueryConsumerChainRequest + var metadata runtime.ServerMetadata + + var ( + val string + ok bool + err error + _ = err + ) + + val, ok = pathParams["consumer_id"] + if !ok { + return nil, metadata, status.Errorf(codes.InvalidArgument, "missing parameter %s", "consumer_id") + } + + protoReq.ConsumerId, err = runtime.String(val) + + if err != nil { + return nil, metadata, status.Errorf(codes.InvalidArgument, "type mismatch, parameter: %s, error: %v", "consumer_id", err) + } + + msg, err := server.QueryConsumerChain(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. @@ -629,30 +845,7 @@ func RegisterQueryHandlerServer(ctx context.Context, mux *runtime.ServeMux, serv }) - mux.Handle("GET", pattern_Query_QueryConsumerChainStarts_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_QueryConsumerChainStarts_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_QueryConsumerChainStarts_0(ctx, mux, outboundMarshaler, w, req, resp, mux.GetForwardResponseOptions()...) - - }) - - mux.Handle("GET", pattern_Query_QueryConsumerChainStops_0, func(w http.ResponseWriter, req *http.Request, pathParams map[string]string) { + mux.Handle("GET", pattern_Query_QueryValidatorConsumerAddr_0, func(w http.ResponseWriter, req *http.Request, pathParams map[string]string) { ctx, cancel := context.WithCancel(req.Context()) defer cancel() var stream runtime.ServerTransportStream @@ -663,7 +856,7 @@ func RegisterQueryHandlerServer(ctx context.Context, mux *runtime.ServeMux, serv runtime.HTTPError(ctx, mux, outboundMarshaler, w, req, err) return } - resp, md, err := local_request_Query_QueryConsumerChainStops_0(rctx, inboundMarshaler, server, req, pathParams) + resp, md, err := local_request_Query_QueryValidatorConsumerAddr_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 { @@ -671,11 +864,11 @@ func RegisterQueryHandlerServer(ctx context.Context, mux *runtime.ServeMux, serv return } - forward_Query_QueryConsumerChainStops_0(ctx, mux, outboundMarshaler, w, req, resp, mux.GetForwardResponseOptions()...) + forward_Query_QueryValidatorConsumerAddr_0(ctx, mux, outboundMarshaler, w, req, resp, mux.GetForwardResponseOptions()...) }) - mux.Handle("GET", pattern_Query_QueryValidatorConsumerAddr_0, func(w http.ResponseWriter, req *http.Request, pathParams map[string]string) { + mux.Handle("GET", pattern_Query_QueryValidatorProviderAddr_0, func(w http.ResponseWriter, req *http.Request, pathParams map[string]string) { ctx, cancel := context.WithCancel(req.Context()) defer cancel() var stream runtime.ServerTransportStream @@ -686,7 +879,7 @@ func RegisterQueryHandlerServer(ctx context.Context, mux *runtime.ServeMux, serv runtime.HTTPError(ctx, mux, outboundMarshaler, w, req, err) return } - resp, md, err := local_request_Query_QueryValidatorConsumerAddr_0(rctx, inboundMarshaler, server, req, pathParams) + resp, md, err := local_request_Query_QueryValidatorProviderAddr_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 { @@ -694,11 +887,11 @@ func RegisterQueryHandlerServer(ctx context.Context, mux *runtime.ServeMux, serv return } - forward_Query_QueryValidatorConsumerAddr_0(ctx, mux, outboundMarshaler, w, req, resp, mux.GetForwardResponseOptions()...) + forward_Query_QueryValidatorProviderAddr_0(ctx, mux, outboundMarshaler, w, req, resp, mux.GetForwardResponseOptions()...) }) - mux.Handle("GET", pattern_Query_QueryValidatorProviderAddr_0, func(w http.ResponseWriter, req *http.Request, pathParams map[string]string) { + mux.Handle("GET", pattern_Query_QueryThrottleState_0, func(w http.ResponseWriter, req *http.Request, pathParams map[string]string) { ctx, cancel := context.WithCancel(req.Context()) defer cancel() var stream runtime.ServerTransportStream @@ -709,7 +902,7 @@ func RegisterQueryHandlerServer(ctx context.Context, mux *runtime.ServeMux, serv runtime.HTTPError(ctx, mux, outboundMarshaler, w, req, err) return } - resp, md, err := local_request_Query_QueryValidatorProviderAddr_0(rctx, inboundMarshaler, server, req, pathParams) + resp, md, err := local_request_Query_QueryThrottleState_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 { @@ -717,11 +910,11 @@ func RegisterQueryHandlerServer(ctx context.Context, mux *runtime.ServeMux, serv return } - forward_Query_QueryValidatorProviderAddr_0(ctx, mux, outboundMarshaler, w, req, resp, mux.GetForwardResponseOptions()...) + forward_Query_QueryThrottleState_0(ctx, mux, outboundMarshaler, w, req, resp, mux.GetForwardResponseOptions()...) }) - mux.Handle("GET", pattern_Query_QueryThrottleState_0, func(w http.ResponseWriter, req *http.Request, pathParams map[string]string) { + mux.Handle("GET", pattern_Query_QueryRegisteredConsumerRewardDenoms_0, func(w http.ResponseWriter, req *http.Request, pathParams map[string]string) { ctx, cancel := context.WithCancel(req.Context()) defer cancel() var stream runtime.ServerTransportStream @@ -732,7 +925,7 @@ func RegisterQueryHandlerServer(ctx context.Context, mux *runtime.ServeMux, serv runtime.HTTPError(ctx, mux, outboundMarshaler, w, req, err) return } - resp, md, err := local_request_Query_QueryThrottleState_0(rctx, inboundMarshaler, server, req, pathParams) + resp, md, err := local_request_Query_QueryRegisteredConsumerRewardDenoms_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 { @@ -740,11 +933,11 @@ func RegisterQueryHandlerServer(ctx context.Context, mux *runtime.ServeMux, serv return } - forward_Query_QueryThrottleState_0(ctx, mux, outboundMarshaler, w, req, resp, mux.GetForwardResponseOptions()...) + forward_Query_QueryRegisteredConsumerRewardDenoms_0(ctx, mux, outboundMarshaler, w, req, resp, mux.GetForwardResponseOptions()...) }) - mux.Handle("GET", pattern_Query_QueryRegisteredConsumerRewardDenoms_0, func(w http.ResponseWriter, req *http.Request, pathParams map[string]string) { + mux.Handle("GET", pattern_Query_QueryAllPairsValConsAddrByConsumer_0, func(w http.ResponseWriter, req *http.Request, pathParams map[string]string) { ctx, cancel := context.WithCancel(req.Context()) defer cancel() var stream runtime.ServerTransportStream @@ -755,7 +948,7 @@ func RegisterQueryHandlerServer(ctx context.Context, mux *runtime.ServeMux, serv runtime.HTTPError(ctx, mux, outboundMarshaler, w, req, err) return } - resp, md, err := local_request_Query_QueryRegisteredConsumerRewardDenoms_0(rctx, inboundMarshaler, server, req, pathParams) + resp, md, err := local_request_Query_QueryAllPairsValConsAddrByConsumer_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 { @@ -763,11 +956,11 @@ func RegisterQueryHandlerServer(ctx context.Context, mux *runtime.ServeMux, serv return } - forward_Query_QueryRegisteredConsumerRewardDenoms_0(ctx, mux, outboundMarshaler, w, req, resp, mux.GetForwardResponseOptions()...) + forward_Query_QueryAllPairsValConsAddrByConsumer_0(ctx, mux, outboundMarshaler, w, req, resp, mux.GetForwardResponseOptions()...) }) - mux.Handle("GET", pattern_Query_QueryProposedConsumerChainIDs_0, func(w http.ResponseWriter, req *http.Request, pathParams map[string]string) { + mux.Handle("GET", pattern_Query_QueryParams_0, func(w http.ResponseWriter, req *http.Request, pathParams map[string]string) { ctx, cancel := context.WithCancel(req.Context()) defer cancel() var stream runtime.ServerTransportStream @@ -778,7 +971,7 @@ func RegisterQueryHandlerServer(ctx context.Context, mux *runtime.ServeMux, serv runtime.HTTPError(ctx, mux, outboundMarshaler, w, req, err) return } - resp, md, err := local_request_Query_QueryProposedConsumerChainIDs_0(rctx, inboundMarshaler, server, req, pathParams) + resp, md, err := local_request_Query_QueryParams_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 { @@ -786,11 +979,11 @@ func RegisterQueryHandlerServer(ctx context.Context, mux *runtime.ServeMux, serv return } - forward_Query_QueryProposedConsumerChainIDs_0(ctx, mux, outboundMarshaler, w, req, resp, mux.GetForwardResponseOptions()...) + forward_Query_QueryParams_0(ctx, mux, outboundMarshaler, w, req, resp, mux.GetForwardResponseOptions()...) }) - mux.Handle("GET", pattern_Query_QueryAllPairsValConAddrByConsumerChainID_0, func(w http.ResponseWriter, req *http.Request, pathParams map[string]string) { + mux.Handle("GET", pattern_Query_QueryConsumerChainOptedInValidators_0, func(w http.ResponseWriter, req *http.Request, pathParams map[string]string) { ctx, cancel := context.WithCancel(req.Context()) defer cancel() var stream runtime.ServerTransportStream @@ -801,7 +994,7 @@ func RegisterQueryHandlerServer(ctx context.Context, mux *runtime.ServeMux, serv runtime.HTTPError(ctx, mux, outboundMarshaler, w, req, err) return } - resp, md, err := local_request_Query_QueryAllPairsValConAddrByConsumerChainID_0(rctx, inboundMarshaler, server, req, pathParams) + resp, md, err := local_request_Query_QueryConsumerChainOptedInValidators_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 { @@ -809,11 +1002,11 @@ func RegisterQueryHandlerServer(ctx context.Context, mux *runtime.ServeMux, serv return } - forward_Query_QueryAllPairsValConAddrByConsumerChainID_0(ctx, mux, outboundMarshaler, w, req, resp, mux.GetForwardResponseOptions()...) + forward_Query_QueryConsumerChainOptedInValidators_0(ctx, mux, outboundMarshaler, w, req, resp, mux.GetForwardResponseOptions()...) }) - mux.Handle("GET", pattern_Query_QueryParams_0, func(w http.ResponseWriter, req *http.Request, pathParams map[string]string) { + mux.Handle("GET", pattern_Query_QueryConsumerChainsValidatorHasToValidate_0, func(w http.ResponseWriter, req *http.Request, pathParams map[string]string) { ctx, cancel := context.WithCancel(req.Context()) defer cancel() var stream runtime.ServerTransportStream @@ -824,7 +1017,7 @@ func RegisterQueryHandlerServer(ctx context.Context, mux *runtime.ServeMux, serv runtime.HTTPError(ctx, mux, outboundMarshaler, w, req, err) return } - resp, md, err := local_request_Query_QueryParams_0(rctx, inboundMarshaler, server, req, pathParams) + resp, md, err := local_request_Query_QueryConsumerChainsValidatorHasToValidate_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 { @@ -832,11 +1025,11 @@ func RegisterQueryHandlerServer(ctx context.Context, mux *runtime.ServeMux, serv return } - forward_Query_QueryParams_0(ctx, mux, outboundMarshaler, w, req, resp, mux.GetForwardResponseOptions()...) + forward_Query_QueryConsumerChainsValidatorHasToValidate_0(ctx, mux, outboundMarshaler, w, req, resp, mux.GetForwardResponseOptions()...) }) - mux.Handle("GET", pattern_Query_QueryConsumerChainOptedInValidators_0, func(w http.ResponseWriter, req *http.Request, pathParams map[string]string) { + mux.Handle("GET", pattern_Query_QueryValidatorConsumerCommissionRate_0, func(w http.ResponseWriter, req *http.Request, pathParams map[string]string) { ctx, cancel := context.WithCancel(req.Context()) defer cancel() var stream runtime.ServerTransportStream @@ -847,7 +1040,7 @@ func RegisterQueryHandlerServer(ctx context.Context, mux *runtime.ServeMux, serv runtime.HTTPError(ctx, mux, outboundMarshaler, w, req, err) return } - resp, md, err := local_request_Query_QueryConsumerChainOptedInValidators_0(rctx, inboundMarshaler, server, req, pathParams) + resp, md, err := local_request_Query_QueryValidatorConsumerCommissionRate_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 { @@ -855,11 +1048,11 @@ func RegisterQueryHandlerServer(ctx context.Context, mux *runtime.ServeMux, serv return } - forward_Query_QueryConsumerChainOptedInValidators_0(ctx, mux, outboundMarshaler, w, req, resp, mux.GetForwardResponseOptions()...) + forward_Query_QueryValidatorConsumerCommissionRate_0(ctx, mux, outboundMarshaler, w, req, resp, mux.GetForwardResponseOptions()...) }) - mux.Handle("GET", pattern_Query_QueryConsumerChainsValidatorHasToValidate_0, func(w http.ResponseWriter, req *http.Request, pathParams map[string]string) { + mux.Handle("GET", pattern_Query_QueryConsumerValidators_0, func(w http.ResponseWriter, req *http.Request, pathParams map[string]string) { ctx, cancel := context.WithCancel(req.Context()) defer cancel() var stream runtime.ServerTransportStream @@ -870,7 +1063,7 @@ func RegisterQueryHandlerServer(ctx context.Context, mux *runtime.ServeMux, serv runtime.HTTPError(ctx, mux, outboundMarshaler, w, req, err) return } - resp, md, err := local_request_Query_QueryConsumerChainsValidatorHasToValidate_0(rctx, inboundMarshaler, server, req, pathParams) + resp, md, err := local_request_Query_QueryConsumerValidators_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 { @@ -878,11 +1071,11 @@ func RegisterQueryHandlerServer(ctx context.Context, mux *runtime.ServeMux, serv return } - forward_Query_QueryConsumerChainsValidatorHasToValidate_0(ctx, mux, outboundMarshaler, w, req, resp, mux.GetForwardResponseOptions()...) + forward_Query_QueryConsumerValidators_0(ctx, mux, outboundMarshaler, w, req, resp, mux.GetForwardResponseOptions()...) }) - mux.Handle("GET", pattern_Query_QueryValidatorConsumerCommissionRate_0, func(w http.ResponseWriter, req *http.Request, pathParams map[string]string) { + mux.Handle("GET", pattern_Query_QueryBlocksUntilNextEpoch_0, func(w http.ResponseWriter, req *http.Request, pathParams map[string]string) { ctx, cancel := context.WithCancel(req.Context()) defer cancel() var stream runtime.ServerTransportStream @@ -893,7 +1086,7 @@ func RegisterQueryHandlerServer(ctx context.Context, mux *runtime.ServeMux, serv runtime.HTTPError(ctx, mux, outboundMarshaler, w, req, err) return } - resp, md, err := local_request_Query_QueryValidatorConsumerCommissionRate_0(rctx, inboundMarshaler, server, req, pathParams) + resp, md, err := local_request_Query_QueryBlocksUntilNextEpoch_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 { @@ -901,11 +1094,11 @@ func RegisterQueryHandlerServer(ctx context.Context, mux *runtime.ServeMux, serv return } - forward_Query_QueryValidatorConsumerCommissionRate_0(ctx, mux, outboundMarshaler, w, req, resp, mux.GetForwardResponseOptions()...) + forward_Query_QueryBlocksUntilNextEpoch_0(ctx, mux, outboundMarshaler, w, req, resp, mux.GetForwardResponseOptions()...) }) - mux.Handle("GET", pattern_Query_QueryConsumerValidators_0, func(w http.ResponseWriter, req *http.Request, pathParams map[string]string) { + mux.Handle("GET", pattern_Query_QueryConsumerIdFromClientId_0, func(w http.ResponseWriter, req *http.Request, pathParams map[string]string) { ctx, cancel := context.WithCancel(req.Context()) defer cancel() var stream runtime.ServerTransportStream @@ -916,7 +1109,7 @@ func RegisterQueryHandlerServer(ctx context.Context, mux *runtime.ServeMux, serv runtime.HTTPError(ctx, mux, outboundMarshaler, w, req, err) return } - resp, md, err := local_request_Query_QueryConsumerValidators_0(rctx, inboundMarshaler, server, req, pathParams) + resp, md, err := local_request_Query_QueryConsumerIdFromClientId_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 { @@ -924,11 +1117,11 @@ func RegisterQueryHandlerServer(ctx context.Context, mux *runtime.ServeMux, serv return } - forward_Query_QueryConsumerValidators_0(ctx, mux, outboundMarshaler, w, req, resp, mux.GetForwardResponseOptions()...) + forward_Query_QueryConsumerIdFromClientId_0(ctx, mux, outboundMarshaler, w, req, resp, mux.GetForwardResponseOptions()...) }) - mux.Handle("GET", pattern_Query_QueryBlocksUntilNextEpoch_0, func(w http.ResponseWriter, req *http.Request, pathParams map[string]string) { + mux.Handle("GET", pattern_Query_QueryConsumerChain_0, func(w http.ResponseWriter, req *http.Request, pathParams map[string]string) { ctx, cancel := context.WithCancel(req.Context()) defer cancel() var stream runtime.ServerTransportStream @@ -939,7 +1132,7 @@ func RegisterQueryHandlerServer(ctx context.Context, mux *runtime.ServeMux, serv runtime.HTTPError(ctx, mux, outboundMarshaler, w, req, err) return } - resp, md, err := local_request_Query_QueryBlocksUntilNextEpoch_0(rctx, inboundMarshaler, server, req, pathParams) + resp, md, err := local_request_Query_QueryConsumerChain_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 { @@ -947,7 +1140,7 @@ func RegisterQueryHandlerServer(ctx context.Context, mux *runtime.ServeMux, serv return } - forward_Query_QueryBlocksUntilNextEpoch_0(ctx, mux, outboundMarshaler, w, req, resp, mux.GetForwardResponseOptions()...) + forward_Query_QueryConsumerChain_0(ctx, mux, outboundMarshaler, w, req, resp, mux.GetForwardResponseOptions()...) }) @@ -1032,27 +1225,7 @@ func RegisterQueryHandlerClient(ctx context.Context, mux *runtime.ServeMux, clie }) - mux.Handle("GET", pattern_Query_QueryConsumerChainStarts_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_QueryConsumerChainStarts_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_QueryConsumerChainStarts_0(ctx, mux, outboundMarshaler, w, req, resp, mux.GetForwardResponseOptions()...) - - }) - - mux.Handle("GET", pattern_Query_QueryConsumerChainStops_0, func(w http.ResponseWriter, req *http.Request, pathParams map[string]string) { + mux.Handle("GET", pattern_Query_QueryValidatorConsumerAddr_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) @@ -1061,18 +1234,18 @@ func RegisterQueryHandlerClient(ctx context.Context, mux *runtime.ServeMux, clie runtime.HTTPError(ctx, mux, outboundMarshaler, w, req, err) return } - resp, md, err := request_Query_QueryConsumerChainStops_0(rctx, inboundMarshaler, client, req, pathParams) + resp, md, err := request_Query_QueryValidatorConsumerAddr_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_QueryConsumerChainStops_0(ctx, mux, outboundMarshaler, w, req, resp, mux.GetForwardResponseOptions()...) + forward_Query_QueryValidatorConsumerAddr_0(ctx, mux, outboundMarshaler, w, req, resp, mux.GetForwardResponseOptions()...) }) - mux.Handle("GET", pattern_Query_QueryValidatorConsumerAddr_0, func(w http.ResponseWriter, req *http.Request, pathParams map[string]string) { + mux.Handle("GET", pattern_Query_QueryValidatorProviderAddr_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) @@ -1081,18 +1254,18 @@ func RegisterQueryHandlerClient(ctx context.Context, mux *runtime.ServeMux, clie runtime.HTTPError(ctx, mux, outboundMarshaler, w, req, err) return } - resp, md, err := request_Query_QueryValidatorConsumerAddr_0(rctx, inboundMarshaler, client, req, pathParams) + resp, md, err := request_Query_QueryValidatorProviderAddr_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_QueryValidatorConsumerAddr_0(ctx, mux, outboundMarshaler, w, req, resp, mux.GetForwardResponseOptions()...) + forward_Query_QueryValidatorProviderAddr_0(ctx, mux, outboundMarshaler, w, req, resp, mux.GetForwardResponseOptions()...) }) - mux.Handle("GET", pattern_Query_QueryValidatorProviderAddr_0, func(w http.ResponseWriter, req *http.Request, pathParams map[string]string) { + mux.Handle("GET", pattern_Query_QueryThrottleState_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) @@ -1101,18 +1274,18 @@ func RegisterQueryHandlerClient(ctx context.Context, mux *runtime.ServeMux, clie runtime.HTTPError(ctx, mux, outboundMarshaler, w, req, err) return } - resp, md, err := request_Query_QueryValidatorProviderAddr_0(rctx, inboundMarshaler, client, req, pathParams) + resp, md, err := request_Query_QueryThrottleState_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_QueryValidatorProviderAddr_0(ctx, mux, outboundMarshaler, w, req, resp, mux.GetForwardResponseOptions()...) + forward_Query_QueryThrottleState_0(ctx, mux, outboundMarshaler, w, req, resp, mux.GetForwardResponseOptions()...) }) - mux.Handle("GET", pattern_Query_QueryThrottleState_0, func(w http.ResponseWriter, req *http.Request, pathParams map[string]string) { + mux.Handle("GET", pattern_Query_QueryRegisteredConsumerRewardDenoms_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) @@ -1121,18 +1294,18 @@ func RegisterQueryHandlerClient(ctx context.Context, mux *runtime.ServeMux, clie runtime.HTTPError(ctx, mux, outboundMarshaler, w, req, err) return } - resp, md, err := request_Query_QueryThrottleState_0(rctx, inboundMarshaler, client, req, pathParams) + resp, md, err := request_Query_QueryRegisteredConsumerRewardDenoms_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_QueryThrottleState_0(ctx, mux, outboundMarshaler, w, req, resp, mux.GetForwardResponseOptions()...) + forward_Query_QueryRegisteredConsumerRewardDenoms_0(ctx, mux, outboundMarshaler, w, req, resp, mux.GetForwardResponseOptions()...) }) - mux.Handle("GET", pattern_Query_QueryRegisteredConsumerRewardDenoms_0, func(w http.ResponseWriter, req *http.Request, pathParams map[string]string) { + mux.Handle("GET", pattern_Query_QueryAllPairsValConsAddrByConsumer_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) @@ -1141,18 +1314,18 @@ func RegisterQueryHandlerClient(ctx context.Context, mux *runtime.ServeMux, clie runtime.HTTPError(ctx, mux, outboundMarshaler, w, req, err) return } - resp, md, err := request_Query_QueryRegisteredConsumerRewardDenoms_0(rctx, inboundMarshaler, client, req, pathParams) + resp, md, err := request_Query_QueryAllPairsValConsAddrByConsumer_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_QueryRegisteredConsumerRewardDenoms_0(ctx, mux, outboundMarshaler, w, req, resp, mux.GetForwardResponseOptions()...) + forward_Query_QueryAllPairsValConsAddrByConsumer_0(ctx, mux, outboundMarshaler, w, req, resp, mux.GetForwardResponseOptions()...) }) - mux.Handle("GET", pattern_Query_QueryProposedConsumerChainIDs_0, func(w http.ResponseWriter, req *http.Request, pathParams map[string]string) { + mux.Handle("GET", pattern_Query_QueryParams_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) @@ -1161,18 +1334,18 @@ func RegisterQueryHandlerClient(ctx context.Context, mux *runtime.ServeMux, clie runtime.HTTPError(ctx, mux, outboundMarshaler, w, req, err) return } - resp, md, err := request_Query_QueryProposedConsumerChainIDs_0(rctx, inboundMarshaler, client, req, pathParams) + resp, md, err := request_Query_QueryParams_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_QueryProposedConsumerChainIDs_0(ctx, mux, outboundMarshaler, w, req, resp, mux.GetForwardResponseOptions()...) + forward_Query_QueryParams_0(ctx, mux, outboundMarshaler, w, req, resp, mux.GetForwardResponseOptions()...) }) - mux.Handle("GET", pattern_Query_QueryAllPairsValConAddrByConsumerChainID_0, func(w http.ResponseWriter, req *http.Request, pathParams map[string]string) { + mux.Handle("GET", pattern_Query_QueryConsumerChainOptedInValidators_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) @@ -1181,18 +1354,18 @@ func RegisterQueryHandlerClient(ctx context.Context, mux *runtime.ServeMux, clie runtime.HTTPError(ctx, mux, outboundMarshaler, w, req, err) return } - resp, md, err := request_Query_QueryAllPairsValConAddrByConsumerChainID_0(rctx, inboundMarshaler, client, req, pathParams) + resp, md, err := request_Query_QueryConsumerChainOptedInValidators_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_QueryAllPairsValConAddrByConsumerChainID_0(ctx, mux, outboundMarshaler, w, req, resp, mux.GetForwardResponseOptions()...) + forward_Query_QueryConsumerChainOptedInValidators_0(ctx, mux, outboundMarshaler, w, req, resp, mux.GetForwardResponseOptions()...) }) - mux.Handle("GET", pattern_Query_QueryParams_0, func(w http.ResponseWriter, req *http.Request, pathParams map[string]string) { + mux.Handle("GET", pattern_Query_QueryConsumerChainsValidatorHasToValidate_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) @@ -1201,18 +1374,18 @@ func RegisterQueryHandlerClient(ctx context.Context, mux *runtime.ServeMux, clie runtime.HTTPError(ctx, mux, outboundMarshaler, w, req, err) return } - resp, md, err := request_Query_QueryParams_0(rctx, inboundMarshaler, client, req, pathParams) + resp, md, err := request_Query_QueryConsumerChainsValidatorHasToValidate_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_QueryParams_0(ctx, mux, outboundMarshaler, w, req, resp, mux.GetForwardResponseOptions()...) + forward_Query_QueryConsumerChainsValidatorHasToValidate_0(ctx, mux, outboundMarshaler, w, req, resp, mux.GetForwardResponseOptions()...) }) - mux.Handle("GET", pattern_Query_QueryConsumerChainOptedInValidators_0, func(w http.ResponseWriter, req *http.Request, pathParams map[string]string) { + mux.Handle("GET", pattern_Query_QueryValidatorConsumerCommissionRate_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) @@ -1221,18 +1394,18 @@ func RegisterQueryHandlerClient(ctx context.Context, mux *runtime.ServeMux, clie runtime.HTTPError(ctx, mux, outboundMarshaler, w, req, err) return } - resp, md, err := request_Query_QueryConsumerChainOptedInValidators_0(rctx, inboundMarshaler, client, req, pathParams) + resp, md, err := request_Query_QueryValidatorConsumerCommissionRate_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_QueryConsumerChainOptedInValidators_0(ctx, mux, outboundMarshaler, w, req, resp, mux.GetForwardResponseOptions()...) + forward_Query_QueryValidatorConsumerCommissionRate_0(ctx, mux, outboundMarshaler, w, req, resp, mux.GetForwardResponseOptions()...) }) - mux.Handle("GET", pattern_Query_QueryConsumerChainsValidatorHasToValidate_0, func(w http.ResponseWriter, req *http.Request, pathParams map[string]string) { + mux.Handle("GET", pattern_Query_QueryConsumerValidators_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) @@ -1241,18 +1414,18 @@ func RegisterQueryHandlerClient(ctx context.Context, mux *runtime.ServeMux, clie runtime.HTTPError(ctx, mux, outboundMarshaler, w, req, err) return } - resp, md, err := request_Query_QueryConsumerChainsValidatorHasToValidate_0(rctx, inboundMarshaler, client, req, pathParams) + resp, md, err := request_Query_QueryConsumerValidators_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_QueryConsumerChainsValidatorHasToValidate_0(ctx, mux, outboundMarshaler, w, req, resp, mux.GetForwardResponseOptions()...) + forward_Query_QueryConsumerValidators_0(ctx, mux, outboundMarshaler, w, req, resp, mux.GetForwardResponseOptions()...) }) - mux.Handle("GET", pattern_Query_QueryValidatorConsumerCommissionRate_0, func(w http.ResponseWriter, req *http.Request, pathParams map[string]string) { + mux.Handle("GET", pattern_Query_QueryBlocksUntilNextEpoch_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) @@ -1261,18 +1434,18 @@ func RegisterQueryHandlerClient(ctx context.Context, mux *runtime.ServeMux, clie runtime.HTTPError(ctx, mux, outboundMarshaler, w, req, err) return } - resp, md, err := request_Query_QueryValidatorConsumerCommissionRate_0(rctx, inboundMarshaler, client, req, pathParams) + resp, md, err := request_Query_QueryBlocksUntilNextEpoch_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_QueryValidatorConsumerCommissionRate_0(ctx, mux, outboundMarshaler, w, req, resp, mux.GetForwardResponseOptions()...) + forward_Query_QueryBlocksUntilNextEpoch_0(ctx, mux, outboundMarshaler, w, req, resp, mux.GetForwardResponseOptions()...) }) - mux.Handle("GET", pattern_Query_QueryConsumerValidators_0, func(w http.ResponseWriter, req *http.Request, pathParams map[string]string) { + mux.Handle("GET", pattern_Query_QueryConsumerIdFromClientId_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) @@ -1281,18 +1454,18 @@ func RegisterQueryHandlerClient(ctx context.Context, mux *runtime.ServeMux, clie runtime.HTTPError(ctx, mux, outboundMarshaler, w, req, err) return } - resp, md, err := request_Query_QueryConsumerValidators_0(rctx, inboundMarshaler, client, req, pathParams) + resp, md, err := request_Query_QueryConsumerIdFromClientId_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_QueryConsumerValidators_0(ctx, mux, outboundMarshaler, w, req, resp, mux.GetForwardResponseOptions()...) + forward_Query_QueryConsumerIdFromClientId_0(ctx, mux, outboundMarshaler, w, req, resp, mux.GetForwardResponseOptions()...) }) - mux.Handle("GET", pattern_Query_QueryBlocksUntilNextEpoch_0, func(w http.ResponseWriter, req *http.Request, pathParams map[string]string) { + mux.Handle("GET", pattern_Query_QueryConsumerChain_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) @@ -1301,14 +1474,14 @@ func RegisterQueryHandlerClient(ctx context.Context, mux *runtime.ServeMux, clie runtime.HTTPError(ctx, mux, outboundMarshaler, w, req, err) return } - resp, md, err := request_Query_QueryBlocksUntilNextEpoch_0(rctx, inboundMarshaler, client, req, pathParams) + resp, md, err := request_Query_QueryConsumerChain_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_QueryBlocksUntilNextEpoch_0(ctx, mux, outboundMarshaler, w, req, resp, mux.GetForwardResponseOptions()...) + forward_Query_QueryConsumerChain_0(ctx, mux, outboundMarshaler, w, req, resp, mux.GetForwardResponseOptions()...) }) @@ -1316,37 +1489,35 @@ func RegisterQueryHandlerClient(ctx context.Context, mux *runtime.ServeMux, clie } var ( - pattern_Query_QueryConsumerGenesis_0 = runtime.MustPattern(runtime.NewPattern(1, []int{2, 0, 2, 1, 2, 2, 2, 3, 1, 0, 4, 1, 5, 4}, []string{"interchain_security", "ccv", "provider", "consumer_genesis", "chain_id"}, "", runtime.AssumeColonVerbOpt(false))) - - pattern_Query_QueryConsumerChains_0 = runtime.MustPattern(runtime.NewPattern(1, []int{2, 0, 2, 1, 2, 2, 2, 3}, []string{"interchain_security", "ccv", "provider", "consumer_chains"}, "", runtime.AssumeColonVerbOpt(false))) + pattern_Query_QueryConsumerGenesis_0 = runtime.MustPattern(runtime.NewPattern(1, []int{2, 0, 2, 1, 2, 2, 2, 3, 1, 0, 4, 1, 5, 4}, []string{"interchain_security", "ccv", "provider", "consumer_genesis", "consumer_id"}, "", runtime.AssumeColonVerbOpt(false))) - pattern_Query_QueryConsumerChainStarts_0 = runtime.MustPattern(runtime.NewPattern(1, []int{2, 0, 2, 1, 2, 2, 2, 3}, []string{"interchain_security", "ccv", "provider", "consumer_chain_start_proposals"}, "", runtime.AssumeColonVerbOpt(false))) + pattern_Query_QueryConsumerChains_0 = runtime.MustPattern(runtime.NewPattern(1, []int{2, 0, 2, 1, 2, 2, 2, 3, 1, 0, 4, 1, 5, 4, 1, 0, 4, 1, 5, 5}, []string{"interchain_security", "ccv", "provider", "consumer_chains", "phase", "limit"}, "", runtime.AssumeColonVerbOpt(false))) - pattern_Query_QueryConsumerChainStops_0 = runtime.MustPattern(runtime.NewPattern(1, []int{2, 0, 2, 1, 2, 2, 2, 3}, []string{"interchain_security", "ccv", "provider", "consumer_chain_stop_proposals"}, "", runtime.AssumeColonVerbOpt(false))) + pattern_Query_QueryValidatorConsumerAddr_0 = runtime.MustPattern(runtime.NewPattern(1, []int{2, 0, 2, 1, 2, 2, 2, 3, 1, 0, 4, 1, 5, 4, 1, 0, 4, 1, 5, 5}, []string{"interchain_security", "ccv", "provider", "validator_consumer_addr", "consumer_id", "provider_address"}, "", runtime.AssumeColonVerbOpt(false))) - pattern_Query_QueryValidatorConsumerAddr_0 = runtime.MustPattern(runtime.NewPattern(1, []int{2, 0, 2, 1, 2, 2, 2, 3}, []string{"interchain_security", "ccv", "provider", "validator_consumer_addr"}, "", runtime.AssumeColonVerbOpt(false))) - - pattern_Query_QueryValidatorProviderAddr_0 = runtime.MustPattern(runtime.NewPattern(1, []int{2, 0, 2, 1, 2, 2, 2, 3}, []string{"interchain_security", "ccv", "provider", "validator_provider_addr"}, "", runtime.AssumeColonVerbOpt(false))) + pattern_Query_QueryValidatorProviderAddr_0 = runtime.MustPattern(runtime.NewPattern(1, []int{2, 0, 2, 1, 2, 2, 2, 3, 1, 0, 4, 1, 5, 4, 1, 0, 4, 1, 5, 5}, []string{"interchain_security", "ccv", "provider", "validator_provider_addr", "consumer_id", "consumer_address"}, "", runtime.AssumeColonVerbOpt(false))) pattern_Query_QueryThrottleState_0 = runtime.MustPattern(runtime.NewPattern(1, []int{2, 0, 2, 1, 2, 2, 2, 3}, []string{"interchain_security", "ccv", "provider", "throttle_state"}, "", runtime.AssumeColonVerbOpt(false))) pattern_Query_QueryRegisteredConsumerRewardDenoms_0 = runtime.MustPattern(runtime.NewPattern(1, []int{2, 0, 2, 1, 2, 2, 2, 3}, []string{"interchain_security", "ccv", "provider", "registered_consumer_reward_denoms"}, "", runtime.AssumeColonVerbOpt(false))) - pattern_Query_QueryProposedConsumerChainIDs_0 = runtime.MustPattern(runtime.NewPattern(1, []int{2, 0, 2, 1, 2, 2, 2, 3}, []string{"interchain_security", "ccv", "provider", "proposed_consumer_chains"}, "", runtime.AssumeColonVerbOpt(false))) - - pattern_Query_QueryAllPairsValConAddrByConsumerChainID_0 = runtime.MustPattern(runtime.NewPattern(1, []int{2, 0, 2, 1, 2, 2, 2, 3}, []string{"interchain_security", "ccv", "provider", "consumer_chain_id"}, "", runtime.AssumeColonVerbOpt(false))) + pattern_Query_QueryAllPairsValConsAddrByConsumer_0 = runtime.MustPattern(runtime.NewPattern(1, []int{2, 0, 2, 1, 2, 2, 2, 3, 1, 0, 4, 1, 5, 4}, []string{"interchain_security", "ccv", "provider", "address_pairs", "consumer_id"}, "", runtime.AssumeColonVerbOpt(false))) pattern_Query_QueryParams_0 = runtime.MustPattern(runtime.NewPattern(1, []int{2, 0, 2, 1, 2, 2, 2, 3}, []string{"interchain_security", "ccv", "provider", "params"}, "", runtime.AssumeColonVerbOpt(false))) - pattern_Query_QueryConsumerChainOptedInValidators_0 = runtime.MustPattern(runtime.NewPattern(1, []int{2, 0, 2, 1, 2, 2, 2, 3, 1, 0, 4, 1, 5, 4}, []string{"interchain_security", "ccv", "provider", "opted_in_validators", "chain_id"}, "", runtime.AssumeColonVerbOpt(false))) + pattern_Query_QueryConsumerChainOptedInValidators_0 = runtime.MustPattern(runtime.NewPattern(1, []int{2, 0, 2, 1, 2, 2, 2, 3, 1, 0, 4, 1, 5, 4}, []string{"interchain_security", "ccv", "provider", "opted_in_validators", "consumer_id"}, "", runtime.AssumeColonVerbOpt(false))) pattern_Query_QueryConsumerChainsValidatorHasToValidate_0 = runtime.MustPattern(runtime.NewPattern(1, []int{2, 0, 2, 1, 2, 2, 2, 3, 1, 0, 4, 1, 5, 4}, []string{"interchain_security", "ccv", "provider", "consumer_chains_per_validator", "provider_address"}, "", runtime.AssumeColonVerbOpt(false))) - pattern_Query_QueryValidatorConsumerCommissionRate_0 = runtime.MustPattern(runtime.NewPattern(1, []int{2, 0, 2, 1, 2, 2, 2, 3, 1, 0, 4, 1, 5, 4, 1, 0, 4, 1, 5, 5}, []string{"interchain_security", "ccv", "provider", "consumer_commission_rate", "chain_id", "provider_address"}, "", runtime.AssumeColonVerbOpt(false))) + pattern_Query_QueryValidatorConsumerCommissionRate_0 = runtime.MustPattern(runtime.NewPattern(1, []int{2, 0, 2, 1, 2, 2, 2, 3, 1, 0, 4, 1, 5, 4, 1, 0, 4, 1, 5, 5}, []string{"interchain_security", "ccv", "provider", "consumer_commission_rate", "consumer_id", "provider_address"}, "", runtime.AssumeColonVerbOpt(false))) - pattern_Query_QueryConsumerValidators_0 = runtime.MustPattern(runtime.NewPattern(1, []int{2, 0, 2, 1, 2, 2, 2, 3, 1, 0, 4, 1, 5, 4}, []string{"interchain_security", "ccv", "provider", "consumer_validators", "chain_id"}, "", runtime.AssumeColonVerbOpt(false))) + pattern_Query_QueryConsumerValidators_0 = runtime.MustPattern(runtime.NewPattern(1, []int{2, 0, 2, 1, 2, 2, 2, 3, 1, 0, 4, 1, 5, 4}, []string{"interchain_security", "ccv", "provider", "consumer_validators", "consumer_id"}, "", runtime.AssumeColonVerbOpt(false))) pattern_Query_QueryBlocksUntilNextEpoch_0 = runtime.MustPattern(runtime.NewPattern(1, []int{2, 0, 2, 1, 2, 2, 2, 3}, []string{"interchain_security", "ccv", "provider", "blocks_until_next_epoch"}, "", runtime.AssumeColonVerbOpt(false))) + + pattern_Query_QueryConsumerIdFromClientId_0 = runtime.MustPattern(runtime.NewPattern(1, []int{2, 0, 2, 1, 2, 2, 2, 3, 1, 0, 4, 1, 5, 4}, []string{"interchain_security", "ccv", "provider", "consumer_id", "client_id"}, "", runtime.AssumeColonVerbOpt(false))) + + pattern_Query_QueryConsumerChain_0 = runtime.MustPattern(runtime.NewPattern(1, []int{2, 0, 2, 1, 2, 2, 2, 3, 1, 0, 4, 1, 5, 4}, []string{"interchain_security", "ccv", "provider", "consumer_chain", "consumer_id"}, "", runtime.AssumeColonVerbOpt(false))) ) var ( @@ -1354,10 +1525,6 @@ var ( forward_Query_QueryConsumerChains_0 = runtime.ForwardResponseMessage - forward_Query_QueryConsumerChainStarts_0 = runtime.ForwardResponseMessage - - forward_Query_QueryConsumerChainStops_0 = runtime.ForwardResponseMessage - forward_Query_QueryValidatorConsumerAddr_0 = runtime.ForwardResponseMessage forward_Query_QueryValidatorProviderAddr_0 = runtime.ForwardResponseMessage @@ -1366,9 +1533,7 @@ var ( forward_Query_QueryRegisteredConsumerRewardDenoms_0 = runtime.ForwardResponseMessage - forward_Query_QueryProposedConsumerChainIDs_0 = runtime.ForwardResponseMessage - - forward_Query_QueryAllPairsValConAddrByConsumerChainID_0 = runtime.ForwardResponseMessage + forward_Query_QueryAllPairsValConsAddrByConsumer_0 = runtime.ForwardResponseMessage forward_Query_QueryParams_0 = runtime.ForwardResponseMessage @@ -1381,4 +1546,8 @@ var ( forward_Query_QueryConsumerValidators_0 = runtime.ForwardResponseMessage forward_Query_QueryBlocksUntilNextEpoch_0 = runtime.ForwardResponseMessage + + forward_Query_QueryConsumerIdFromClientId_0 = runtime.ForwardResponseMessage + + forward_Query_QueryConsumerChain_0 = runtime.ForwardResponseMessage ) diff --git a/x/ccv/provider/types/throttle.go b/x/ccv/provider/types/throttle.go deleted file mode 100644 index e41396eb3a..0000000000 --- a/x/ccv/provider/types/throttle.go +++ /dev/null @@ -1,17 +0,0 @@ -package types - -import ( - "time" -) - -// NewGlobalSlashEntry creates a new GlobalSlashEntry. -func NewGlobalSlashEntry(recvTime time.Time, consumerChainID string, - ibcSeqNum uint64, providerValConsAddr ProviderConsAddress, -) GlobalSlashEntry { - return GlobalSlashEntry{ - RecvTime: recvTime.UTC(), // UTC prevents serialization inconsistencies - ConsumerChainID: consumerChainID, - IbcSeqNum: ibcSeqNum, - ProviderValConsAddr: providerValConsAddr.ToSdkConsAddr(), - } -} diff --git a/x/ccv/provider/types/tx.pb.go b/x/ccv/provider/types/tx.pb.go index 292e870a9b..999fffef8a 100644 --- a/x/ccv/provider/types/tx.pb.go +++ b/x/ccv/provider/types/tx.pb.go @@ -43,16 +43,17 @@ var _ = time.Kitchen const _ = proto.GoGoProtoPackageIsVersion3 // please upgrade the proto package type MsgAssignConsumerKey struct { - // The chain id of the consumer chain to assign a consensus public key to - ChainId string `protobuf:"bytes,1,opt,name=chain_id,json=chainId,proto3" json:"chain_id,omitempty"` + // [DEPRECATED] use `consumer_id` instead + ChainId string `protobuf:"bytes,1,opt,name=chain_id,json=chainId,proto3" json:"chain_id,omitempty"` // Deprecated: Do not use. // The validator address on the provider ProviderAddr string `protobuf:"bytes,2,opt,name=provider_addr,json=providerAddr,proto3" json:"provider_addr,omitempty" yaml:"address"` // The consensus public key to use on the consumer. // in json string format corresponding to proto-any, ex: // `{"@type":"/cosmos.crypto.ed25519.PubKey","key":"Ui5Gf1+mtWUdH8u3xlmzdKID+F3PK0sfXZ73GZ6q6is="}` ConsumerKey string `protobuf:"bytes,3,opt,name=consumer_key,json=consumerKey,proto3" json:"consumer_key,omitempty"` - // Tx signer address - Signer string `protobuf:"bytes,4,opt,name=signer,proto3" json:"signer,omitempty"` + Submitter string `protobuf:"bytes,4,opt,name=submitter,proto3" json:"submitter,omitempty"` + // the consumer id of the consumer chain to assign a consensus public key to + ConsumerId string `protobuf:"bytes,5,opt,name=consumer_id,json=consumerId,proto3" json:"consumer_id,omitempty"` } func (m *MsgAssignConsumerKey) Reset() { *m = MsgAssignConsumerKey{} } @@ -131,6 +132,8 @@ type MsgSubmitConsumerMisbehaviour struct { // The Misbehaviour of the consumer chain wrapping // two conflicting IBC headers Misbehaviour *_07_tendermint.Misbehaviour `protobuf:"bytes,2,opt,name=misbehaviour,proto3" json:"misbehaviour,omitempty"` + // the consumer id of the consumer chain where the misbehaviour occurred + ConsumerId string `protobuf:"bytes,3,opt,name=consumer_id,json=consumerId,proto3" json:"consumer_id,omitempty"` } func (m *MsgSubmitConsumerMisbehaviour) Reset() { *m = MsgSubmitConsumerMisbehaviour{} } @@ -211,6 +214,8 @@ type MsgSubmitConsumerDoubleVoting struct { DuplicateVoteEvidence *types.DuplicateVoteEvidence `protobuf:"bytes,2,opt,name=duplicate_vote_evidence,json=duplicateVoteEvidence,proto3" json:"duplicate_vote_evidence,omitempty"` // The light client header of the infraction block InfractionBlockHeader *_07_tendermint.Header `protobuf:"bytes,3,opt,name=infraction_block_header,json=infractionBlockHeader,proto3" json:"infraction_block_header,omitempty"` + // the consumer id of the consumer chain where the double-voting took place + ConsumerId string `protobuf:"bytes,4,opt,name=consumer_id,json=consumerId,proto3" json:"consumer_id,omitempty"` } func (m *MsgSubmitConsumerDoubleVoting) Reset() { *m = MsgSubmitConsumerDoubleVoting{} } @@ -284,7 +289,7 @@ var xxx_messageInfo_MsgSubmitConsumerDoubleVotingResponse proto.InternalMessageI // MsgUpdateParams is the Msg/UpdateParams request type type MsgUpdateParams struct { - // signer is the address of the governance account. + // authority is the address of the governance account. Authority string `protobuf:"bytes,1,opt,name=authority,proto3" json:"authority,omitempty"` // params defines the x/provider parameters to update. Params Params `protobuf:"bytes,2,opt,name=params,proto3" json:"params"` @@ -373,12 +378,7 @@ func (m *MsgUpdateParamsResponse) XXX_DiscardUnknown() { var xxx_messageInfo_MsgUpdateParamsResponse proto.InternalMessageInfo -// MsgConsumerAddition defines the message used to spawn a new consumer chain using a v1 governance proposal. -// If it passes, then all validators on the provider chain are expected to validate -// the consumer chain at spawn time or get slashed. -// It is recommended that spawn time occurs after the proposal end time. -// -// Note: this replaces ConsumerAdditionProposal which is deprecated and will be removed soon +// [DEPRECATED] Use `MsgCreateConsumer` instead type MsgConsumerAddition struct { // the proposed chain-id of the new consumer chain, must be different from all // other consumer chain ids of the executing provider chain. @@ -663,12 +663,7 @@ func (m *MsgConsumerAdditionResponse) XXX_DiscardUnknown() { var xxx_messageInfo_MsgConsumerAdditionResponse proto.InternalMessageInfo -// MsgConsumerRemoval message contains a governance proposal on the provider chain to -// remove (and stop) a consumer chain. If it passes, all the consumer chain's -// state is removed from the provider chain. The outstanding unbonding operation -// funds are released. -// -// Note: this replaces ConsumerRemovalProposal which is deprecated and will be removed soon +// [DEPRECATED] Use `MsgRemoveConsumer` instead type MsgConsumerRemoval struct { // the chain-id of the consumer chain to be stopped ChainId string `protobuf:"bytes,1,opt,name=chain_id,json=chainId,proto3" json:"chain_id,omitempty"` @@ -770,6 +765,99 @@ func (m *MsgConsumerRemovalResponse) XXX_DiscardUnknown() { var xxx_messageInfo_MsgConsumerRemovalResponse proto.InternalMessageInfo +// MsgRemoveConsumer defines the message used to remove (and stop) a consumer chain. +// If it passes, all the consumer chain's state is eventually removed from the provider chain. +type MsgRemoveConsumer struct { + // the consumer id of the consumer chain to be stopped + ConsumerId string `protobuf:"bytes,1,opt,name=consumer_id,json=consumerId,proto3" json:"consumer_id,omitempty"` + // the address of the owner of the consumer chain to be stopped + Owner string `protobuf:"bytes,2,opt,name=owner,proto3" json:"owner,omitempty"` +} + +func (m *MsgRemoveConsumer) Reset() { *m = MsgRemoveConsumer{} } +func (m *MsgRemoveConsumer) String() string { return proto.CompactTextString(m) } +func (*MsgRemoveConsumer) ProtoMessage() {} +func (*MsgRemoveConsumer) Descriptor() ([]byte, []int) { + return fileDescriptor_43221a4391e9fbf4, []int{12} +} +func (m *MsgRemoveConsumer) XXX_Unmarshal(b []byte) error { + return m.Unmarshal(b) +} +func (m *MsgRemoveConsumer) XXX_Marshal(b []byte, deterministic bool) ([]byte, error) { + if deterministic { + return xxx_messageInfo_MsgRemoveConsumer.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 *MsgRemoveConsumer) XXX_Merge(src proto.Message) { + xxx_messageInfo_MsgRemoveConsumer.Merge(m, src) +} +func (m *MsgRemoveConsumer) XXX_Size() int { + return m.Size() +} +func (m *MsgRemoveConsumer) XXX_DiscardUnknown() { + xxx_messageInfo_MsgRemoveConsumer.DiscardUnknown(m) +} + +var xxx_messageInfo_MsgRemoveConsumer proto.InternalMessageInfo + +func (m *MsgRemoveConsumer) GetConsumerId() string { + if m != nil { + return m.ConsumerId + } + return "" +} + +func (m *MsgRemoveConsumer) GetOwner() string { + if m != nil { + return m.Owner + } + return "" +} + +// MsgRemoveConsumerResponse defines response type for MsgRemoveConsumer messages +type MsgRemoveConsumerResponse struct { +} + +func (m *MsgRemoveConsumerResponse) Reset() { *m = MsgRemoveConsumerResponse{} } +func (m *MsgRemoveConsumerResponse) String() string { return proto.CompactTextString(m) } +func (*MsgRemoveConsumerResponse) ProtoMessage() {} +func (*MsgRemoveConsumerResponse) Descriptor() ([]byte, []int) { + return fileDescriptor_43221a4391e9fbf4, []int{13} +} +func (m *MsgRemoveConsumerResponse) XXX_Unmarshal(b []byte) error { + return m.Unmarshal(b) +} +func (m *MsgRemoveConsumerResponse) XXX_Marshal(b []byte, deterministic bool) ([]byte, error) { + if deterministic { + return xxx_messageInfo_MsgRemoveConsumerResponse.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 *MsgRemoveConsumerResponse) XXX_Merge(src proto.Message) { + xxx_messageInfo_MsgRemoveConsumerResponse.Merge(m, src) +} +func (m *MsgRemoveConsumerResponse) XXX_Size() int { + return m.Size() +} +func (m *MsgRemoveConsumerResponse) XXX_DiscardUnknown() { + xxx_messageInfo_MsgRemoveConsumerResponse.DiscardUnknown(m) +} + +var xxx_messageInfo_MsgRemoveConsumerResponse proto.InternalMessageInfo + // ChangeRewardDenomsProposal is a governance proposal on the provider chain to // mutate the set of denoms accepted by the provider as rewards. // @@ -779,7 +867,7 @@ type MsgChangeRewardDenoms struct { DenomsToAdd []string `protobuf:"bytes,1,rep,name=denoms_to_add,json=denomsToAdd,proto3" json:"denoms_to_add,omitempty"` // the list of consumer reward denoms to remove DenomsToRemove []string `protobuf:"bytes,2,rep,name=denoms_to_remove,json=denomsToRemove,proto3" json:"denoms_to_remove,omitempty"` - // signer address + // authority is the address of the governance account Authority string `protobuf:"bytes,3,opt,name=authority,proto3" json:"authority,omitempty"` } @@ -787,7 +875,7 @@ func (m *MsgChangeRewardDenoms) Reset() { *m = MsgChangeRewardDenoms{} } func (m *MsgChangeRewardDenoms) String() string { return proto.CompactTextString(m) } func (*MsgChangeRewardDenoms) ProtoMessage() {} func (*MsgChangeRewardDenoms) Descriptor() ([]byte, []int) { - return fileDescriptor_43221a4391e9fbf4, []int{12} + return fileDescriptor_43221a4391e9fbf4, []int{14} } func (m *MsgChangeRewardDenoms) XXX_Unmarshal(b []byte) error { return m.Unmarshal(b) @@ -845,7 +933,7 @@ func (m *MsgChangeRewardDenomsResponse) Reset() { *m = MsgChangeRewardDe func (m *MsgChangeRewardDenomsResponse) String() string { return proto.CompactTextString(m) } func (*MsgChangeRewardDenomsResponse) ProtoMessage() {} func (*MsgChangeRewardDenomsResponse) Descriptor() ([]byte, []int) { - return fileDescriptor_43221a4391e9fbf4, []int{13} + return fileDescriptor_43221a4391e9fbf4, []int{15} } func (m *MsgChangeRewardDenomsResponse) XXX_Unmarshal(b []byte) error { return m.Unmarshal(b) @@ -875,8 +963,8 @@ func (m *MsgChangeRewardDenomsResponse) XXX_DiscardUnknown() { var xxx_messageInfo_MsgChangeRewardDenomsResponse proto.InternalMessageInfo type MsgOptIn struct { - // the chain id of the consumer chain to opt in to - ChainId string `protobuf:"bytes,1,opt,name=chain_id,json=chainId,proto3" json:"chain_id,omitempty"` + // [DEPRECATED] use `consumer_id` instead + ChainId string `protobuf:"bytes,1,opt,name=chain_id,json=chainId,proto3" json:"chain_id,omitempty"` // Deprecated: Do not use. // the validator address on the provider ProviderAddr string `protobuf:"bytes,2,opt,name=provider_addr,json=providerAddr,proto3" json:"provider_addr,omitempty" yaml:"address"` // (optional) The consensus public key to use on the consumer in json string format corresponding to proto-any, @@ -884,15 +972,17 @@ type MsgOptIn struct { // This field is optional and can remain empty (i.e., `consumer_key = ""`). A validator can always change the // consumer public key at a later stage by issuing a `MsgAssignConsumerKey` message. ConsumerKey string `protobuf:"bytes,3,opt,name=consumer_key,json=consumerKey,proto3" json:"consumer_key,omitempty"` - // signer address - Signer string `protobuf:"bytes,4,opt,name=signer,proto3" json:"signer,omitempty"` + // submitter address + Submitter string `protobuf:"bytes,4,opt,name=submitter,proto3" json:"submitter,omitempty"` + // the consumer id of the consumer chain to opt in to + ConsumerId string `protobuf:"bytes,5,opt,name=consumer_id,json=consumerId,proto3" json:"consumer_id,omitempty"` } func (m *MsgOptIn) Reset() { *m = MsgOptIn{} } func (m *MsgOptIn) String() string { return proto.CompactTextString(m) } func (*MsgOptIn) ProtoMessage() {} func (*MsgOptIn) Descriptor() ([]byte, []int) { - return fileDescriptor_43221a4391e9fbf4, []int{14} + return fileDescriptor_43221a4391e9fbf4, []int{16} } func (m *MsgOptIn) XXX_Unmarshal(b []byte) error { return m.Unmarshal(b) @@ -928,7 +1018,7 @@ func (m *MsgOptInResponse) Reset() { *m = MsgOptInResponse{} } func (m *MsgOptInResponse) String() string { return proto.CompactTextString(m) } func (*MsgOptInResponse) ProtoMessage() {} func (*MsgOptInResponse) Descriptor() ([]byte, []int) { - return fileDescriptor_43221a4391e9fbf4, []int{15} + return fileDescriptor_43221a4391e9fbf4, []int{17} } func (m *MsgOptInResponse) XXX_Unmarshal(b []byte) error { return m.Unmarshal(b) @@ -958,19 +1048,21 @@ func (m *MsgOptInResponse) XXX_DiscardUnknown() { var xxx_messageInfo_MsgOptInResponse proto.InternalMessageInfo type MsgOptOut struct { - // the chain id of the consumer chain to opt out from - ChainId string `protobuf:"bytes,1,opt,name=chain_id,json=chainId,proto3" json:"chain_id,omitempty"` + // [DEPRECATED] use `consumer_id` instead + ChainId string `protobuf:"bytes,1,opt,name=chain_id,json=chainId,proto3" json:"chain_id,omitempty"` // Deprecated: Do not use. // the validator address on the provider ProviderAddr string `protobuf:"bytes,2,opt,name=provider_addr,json=providerAddr,proto3" json:"provider_addr,omitempty" yaml:"address"` - // signer address - Signer string `protobuf:"bytes,3,opt,name=signer,proto3" json:"signer,omitempty"` + // submitter address + Submitter string `protobuf:"bytes,3,opt,name=submitter,proto3" json:"submitter,omitempty"` + // the consumer id of the consumer chain to opt out from + ConsumerId string `protobuf:"bytes,4,opt,name=consumer_id,json=consumerId,proto3" json:"consumer_id,omitempty"` } func (m *MsgOptOut) Reset() { *m = MsgOptOut{} } func (m *MsgOptOut) String() string { return proto.CompactTextString(m) } func (*MsgOptOut) ProtoMessage() {} func (*MsgOptOut) Descriptor() ([]byte, []int) { - return fileDescriptor_43221a4391e9fbf4, []int{16} + return fileDescriptor_43221a4391e9fbf4, []int{18} } func (m *MsgOptOut) XXX_Unmarshal(b []byte) error { return m.Unmarshal(b) @@ -1006,7 +1098,7 @@ func (m *MsgOptOutResponse) Reset() { *m = MsgOptOutResponse{} } func (m *MsgOptOutResponse) String() string { return proto.CompactTextString(m) } func (*MsgOptOutResponse) ProtoMessage() {} func (*MsgOptOutResponse) Descriptor() ([]byte, []int) { - return fileDescriptor_43221a4391e9fbf4, []int{17} + return fileDescriptor_43221a4391e9fbf4, []int{19} } func (m *MsgOptOutResponse) XXX_Unmarshal(b []byte) error { return m.Unmarshal(b) @@ -1040,20 +1132,22 @@ var xxx_messageInfo_MsgOptOutResponse proto.InternalMessageInfo type MsgSetConsumerCommissionRate struct { // The validator address on the provider ProviderAddr string `protobuf:"bytes,1,opt,name=provider_addr,json=providerAddr,proto3" json:"provider_addr,omitempty" yaml:"address"` - // The chain id of the consumer chain to set a commission rate - ChainId string `protobuf:"bytes,2,opt,name=chain_id,json=chainId,proto3" json:"chain_id,omitempty"` + // [DEPRECATED] use `consumer_id` instead + ChainId string `protobuf:"bytes,2,opt,name=chain_id,json=chainId,proto3" json:"chain_id,omitempty"` // Deprecated: Do not use. // The rate to charge delegators on the consumer chain, as a fraction // TODO: migrate rate from sdk.Dec to math.LegacyDec Rate cosmossdk_io_math.LegacyDec `protobuf:"bytes,3,opt,name=rate,proto3,customtype=cosmossdk.io/math.LegacyDec" json:"rate"` - // signer address - Signer string `protobuf:"bytes,4,opt,name=signer,proto3" json:"signer,omitempty"` + // submitter address + Submitter string `protobuf:"bytes,4,opt,name=submitter,proto3" json:"submitter,omitempty"` + // the consumer id of the consumer chain to set the commission rate + ConsumerId string `protobuf:"bytes,5,opt,name=consumer_id,json=consumerId,proto3" json:"consumer_id,omitempty"` } func (m *MsgSetConsumerCommissionRate) Reset() { *m = MsgSetConsumerCommissionRate{} } func (m *MsgSetConsumerCommissionRate) String() string { return proto.CompactTextString(m) } func (*MsgSetConsumerCommissionRate) ProtoMessage() {} func (*MsgSetConsumerCommissionRate) Descriptor() ([]byte, []int) { - return fileDescriptor_43221a4391e9fbf4, []int{18} + return fileDescriptor_43221a4391e9fbf4, []int{20} } func (m *MsgSetConsumerCommissionRate) XXX_Unmarshal(b []byte) error { return m.Unmarshal(b) @@ -1089,7 +1183,7 @@ func (m *MsgSetConsumerCommissionRateResponse) Reset() { *m = MsgSetCons func (m *MsgSetConsumerCommissionRateResponse) String() string { return proto.CompactTextString(m) } func (*MsgSetConsumerCommissionRateResponse) ProtoMessage() {} func (*MsgSetConsumerCommissionRateResponse) Descriptor() ([]byte, []int) { - return fileDescriptor_43221a4391e9fbf4, []int{19} + return fileDescriptor_43221a4391e9fbf4, []int{21} } func (m *MsgSetConsumerCommissionRateResponse) XXX_Unmarshal(b []byte) error { return m.Unmarshal(b) @@ -1118,11 +1212,7 @@ func (m *MsgSetConsumerCommissionRateResponse) XXX_DiscardUnknown() { var xxx_messageInfo_MsgSetConsumerCommissionRateResponse proto.InternalMessageInfo -// MsgConsumerModification message contains a governance proposal on the provider chain to -// modify a running consumer chain. If it passes, the consumer chain's -// parameters are updated. -// -// Note: this replaces ConsumerModificationProposal which is deprecated and will be removed soon +// [DEPRECATED] Use `MsgUpdateConsumer` instead type MsgConsumerModification struct { // the title of the proposal Title string `protobuf:"bytes,1,opt,name=title,proto3" json:"title,omitempty"` @@ -1161,7 +1251,7 @@ func (m *MsgConsumerModification) Reset() { *m = MsgConsumerModification func (m *MsgConsumerModification) String() string { return proto.CompactTextString(m) } func (*MsgConsumerModification) ProtoMessage() {} func (*MsgConsumerModification) Descriptor() ([]byte, []int) { - return fileDescriptor_43221a4391e9fbf4, []int{20} + return fileDescriptor_43221a4391e9fbf4, []int{22} } func (m *MsgConsumerModification) XXX_Unmarshal(b []byte) error { return m.Unmarshal(b) @@ -1274,7 +1364,7 @@ func (m *MsgConsumerModificationResponse) Reset() { *m = MsgConsumerModi func (m *MsgConsumerModificationResponse) String() string { return proto.CompactTextString(m) } func (*MsgConsumerModificationResponse) ProtoMessage() {} func (*MsgConsumerModificationResponse) Descriptor() ([]byte, []int) { - return fileDescriptor_43221a4391e9fbf4, []int{21} + return fileDescriptor_43221a4391e9fbf4, []int{23} } func (m *MsgConsumerModificationResponse) XXX_Unmarshal(b []byte) error { return m.Unmarshal(b) @@ -1303,6 +1393,259 @@ func (m *MsgConsumerModificationResponse) XXX_DiscardUnknown() { var xxx_messageInfo_MsgConsumerModificationResponse proto.InternalMessageInfo +// MsgCreateConsumer defines the message that creates a consumer chain +type MsgCreateConsumer struct { + // Submitter address. If the message is successfully handled, the ownership of + // the consumer chain will given to this address. + Submitter string `protobuf:"bytes,1,opt,name=submitter,proto3" json:"submitter,omitempty"` + // the chain id of the new consumer chain + ChainId string `protobuf:"bytes,2,opt,name=chain_id,json=chainId,proto3" json:"chain_id,omitempty"` + Metadata ConsumerMetadata `protobuf:"bytes,3,opt,name=metadata,proto3" json:"metadata"` + InitializationParameters *ConsumerInitializationParameters `protobuf:"bytes,4,opt,name=initialization_parameters,json=initializationParameters,proto3" json:"initialization_parameters,omitempty"` + PowerShapingParameters *PowerShapingParameters `protobuf:"bytes,5,opt,name=power_shaping_parameters,json=powerShapingParameters,proto3" json:"power_shaping_parameters,omitempty"` +} + +func (m *MsgCreateConsumer) Reset() { *m = MsgCreateConsumer{} } +func (m *MsgCreateConsumer) String() string { return proto.CompactTextString(m) } +func (*MsgCreateConsumer) ProtoMessage() {} +func (*MsgCreateConsumer) Descriptor() ([]byte, []int) { + return fileDescriptor_43221a4391e9fbf4, []int{24} +} +func (m *MsgCreateConsumer) XXX_Unmarshal(b []byte) error { + return m.Unmarshal(b) +} +func (m *MsgCreateConsumer) XXX_Marshal(b []byte, deterministic bool) ([]byte, error) { + if deterministic { + return xxx_messageInfo_MsgCreateConsumer.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 *MsgCreateConsumer) XXX_Merge(src proto.Message) { + xxx_messageInfo_MsgCreateConsumer.Merge(m, src) +} +func (m *MsgCreateConsumer) XXX_Size() int { + return m.Size() +} +func (m *MsgCreateConsumer) XXX_DiscardUnknown() { + xxx_messageInfo_MsgCreateConsumer.DiscardUnknown(m) +} + +var xxx_messageInfo_MsgCreateConsumer proto.InternalMessageInfo + +func (m *MsgCreateConsumer) GetSubmitter() string { + if m != nil { + return m.Submitter + } + return "" +} + +func (m *MsgCreateConsumer) GetChainId() string { + if m != nil { + return m.ChainId + } + return "" +} + +func (m *MsgCreateConsumer) GetMetadata() ConsumerMetadata { + if m != nil { + return m.Metadata + } + return ConsumerMetadata{} +} + +func (m *MsgCreateConsumer) GetInitializationParameters() *ConsumerInitializationParameters { + if m != nil { + return m.InitializationParameters + } + return nil +} + +func (m *MsgCreateConsumer) GetPowerShapingParameters() *PowerShapingParameters { + if m != nil { + return m.PowerShapingParameters + } + return nil +} + +// MsgCreateConsumerResponse defines response type for MsgCreateConsumer +type MsgCreateConsumerResponse struct { + ConsumerId string `protobuf:"bytes,1,opt,name=consumer_id,json=consumerId,proto3" json:"consumer_id,omitempty"` +} + +func (m *MsgCreateConsumerResponse) Reset() { *m = MsgCreateConsumerResponse{} } +func (m *MsgCreateConsumerResponse) String() string { return proto.CompactTextString(m) } +func (*MsgCreateConsumerResponse) ProtoMessage() {} +func (*MsgCreateConsumerResponse) Descriptor() ([]byte, []int) { + return fileDescriptor_43221a4391e9fbf4, []int{25} +} +func (m *MsgCreateConsumerResponse) XXX_Unmarshal(b []byte) error { + return m.Unmarshal(b) +} +func (m *MsgCreateConsumerResponse) XXX_Marshal(b []byte, deterministic bool) ([]byte, error) { + if deterministic { + return xxx_messageInfo_MsgCreateConsumerResponse.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 *MsgCreateConsumerResponse) XXX_Merge(src proto.Message) { + xxx_messageInfo_MsgCreateConsumerResponse.Merge(m, src) +} +func (m *MsgCreateConsumerResponse) XXX_Size() int { + return m.Size() +} +func (m *MsgCreateConsumerResponse) XXX_DiscardUnknown() { + xxx_messageInfo_MsgCreateConsumerResponse.DiscardUnknown(m) +} + +var xxx_messageInfo_MsgCreateConsumerResponse proto.InternalMessageInfo + +func (m *MsgCreateConsumerResponse) GetConsumerId() string { + if m != nil { + return m.ConsumerId + } + return "" +} + +// MsgUpdateConsumer defines the message used to modify a consumer chain. +type MsgUpdateConsumer struct { + // the address of the owner of the consumer chain to be updated + Owner string `protobuf:"bytes,1,opt,name=owner,proto3" json:"owner,omitempty"` + // the consumer id of the consumer chain to be updated + ConsumerId string `protobuf:"bytes,2,opt,name=consumer_id,json=consumerId,proto3" json:"consumer_id,omitempty"` + // the new owner of the consumer when updated + NewOwnerAddress string `protobuf:"bytes,3,opt,name=new_owner_address,json=newOwnerAddress,proto3" json:"new_owner_address,omitempty"` + // the metadata of the consumer when updated + Metadata *ConsumerMetadata `protobuf:"bytes,4,opt,name=metadata,proto3" json:"metadata,omitempty"` + // initialization parameters can only be updated before a chain has launched + InitializationParameters *ConsumerInitializationParameters `protobuf:"bytes,5,opt,name=initialization_parameters,json=initializationParameters,proto3" json:"initialization_parameters,omitempty"` + // the power-shaping parameters of the consumer when updated + PowerShapingParameters *PowerShapingParameters `protobuf:"bytes,6,opt,name=power_shaping_parameters,json=powerShapingParameters,proto3" json:"power_shaping_parameters,omitempty"` +} + +func (m *MsgUpdateConsumer) Reset() { *m = MsgUpdateConsumer{} } +func (m *MsgUpdateConsumer) String() string { return proto.CompactTextString(m) } +func (*MsgUpdateConsumer) ProtoMessage() {} +func (*MsgUpdateConsumer) Descriptor() ([]byte, []int) { + return fileDescriptor_43221a4391e9fbf4, []int{26} +} +func (m *MsgUpdateConsumer) XXX_Unmarshal(b []byte) error { + return m.Unmarshal(b) +} +func (m *MsgUpdateConsumer) XXX_Marshal(b []byte, deterministic bool) ([]byte, error) { + if deterministic { + return xxx_messageInfo_MsgUpdateConsumer.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 *MsgUpdateConsumer) XXX_Merge(src proto.Message) { + xxx_messageInfo_MsgUpdateConsumer.Merge(m, src) +} +func (m *MsgUpdateConsumer) XXX_Size() int { + return m.Size() +} +func (m *MsgUpdateConsumer) XXX_DiscardUnknown() { + xxx_messageInfo_MsgUpdateConsumer.DiscardUnknown(m) +} + +var xxx_messageInfo_MsgUpdateConsumer proto.InternalMessageInfo + +func (m *MsgUpdateConsumer) GetOwner() string { + if m != nil { + return m.Owner + } + return "" +} + +func (m *MsgUpdateConsumer) GetConsumerId() string { + if m != nil { + return m.ConsumerId + } + return "" +} + +func (m *MsgUpdateConsumer) GetNewOwnerAddress() string { + if m != nil { + return m.NewOwnerAddress + } + return "" +} + +func (m *MsgUpdateConsumer) GetMetadata() *ConsumerMetadata { + if m != nil { + return m.Metadata + } + return nil +} + +func (m *MsgUpdateConsumer) GetInitializationParameters() *ConsumerInitializationParameters { + if m != nil { + return m.InitializationParameters + } + return nil +} + +func (m *MsgUpdateConsumer) GetPowerShapingParameters() *PowerShapingParameters { + if m != nil { + return m.PowerShapingParameters + } + return nil +} + +// MsgUpdateConsumerResponse defines response type for MsgUpdateConsumer messages +type MsgUpdateConsumerResponse struct { +} + +func (m *MsgUpdateConsumerResponse) Reset() { *m = MsgUpdateConsumerResponse{} } +func (m *MsgUpdateConsumerResponse) String() string { return proto.CompactTextString(m) } +func (*MsgUpdateConsumerResponse) ProtoMessage() {} +func (*MsgUpdateConsumerResponse) Descriptor() ([]byte, []int) { + return fileDescriptor_43221a4391e9fbf4, []int{27} +} +func (m *MsgUpdateConsumerResponse) XXX_Unmarshal(b []byte) error { + return m.Unmarshal(b) +} +func (m *MsgUpdateConsumerResponse) XXX_Marshal(b []byte, deterministic bool) ([]byte, error) { + if deterministic { + return xxx_messageInfo_MsgUpdateConsumerResponse.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 *MsgUpdateConsumerResponse) XXX_Merge(src proto.Message) { + xxx_messageInfo_MsgUpdateConsumerResponse.Merge(m, src) +} +func (m *MsgUpdateConsumerResponse) XXX_Size() int { + return m.Size() +} +func (m *MsgUpdateConsumerResponse) XXX_DiscardUnknown() { + xxx_messageInfo_MsgUpdateConsumerResponse.DiscardUnknown(m) +} + +var xxx_messageInfo_MsgUpdateConsumerResponse proto.InternalMessageInfo + func init() { proto.RegisterType((*MsgAssignConsumerKey)(nil), "interchain_security.ccv.provider.v1.MsgAssignConsumerKey") proto.RegisterType((*MsgAssignConsumerKeyResponse)(nil), "interchain_security.ccv.provider.v1.MsgAssignConsumerKeyResponse") @@ -1316,6 +1659,8 @@ func init() { proto.RegisterType((*MsgConsumerAdditionResponse)(nil), "interchain_security.ccv.provider.v1.MsgConsumerAdditionResponse") proto.RegisterType((*MsgConsumerRemoval)(nil), "interchain_security.ccv.provider.v1.MsgConsumerRemoval") proto.RegisterType((*MsgConsumerRemovalResponse)(nil), "interchain_security.ccv.provider.v1.MsgConsumerRemovalResponse") + proto.RegisterType((*MsgRemoveConsumer)(nil), "interchain_security.ccv.provider.v1.MsgRemoveConsumer") + proto.RegisterType((*MsgRemoveConsumerResponse)(nil), "interchain_security.ccv.provider.v1.MsgRemoveConsumerResponse") proto.RegisterType((*MsgChangeRewardDenoms)(nil), "interchain_security.ccv.provider.v1.MsgChangeRewardDenoms") proto.RegisterType((*MsgChangeRewardDenomsResponse)(nil), "interchain_security.ccv.provider.v1.MsgChangeRewardDenomsResponse") proto.RegisterType((*MsgOptIn)(nil), "interchain_security.ccv.provider.v1.MsgOptIn") @@ -1326,6 +1671,10 @@ func init() { proto.RegisterType((*MsgSetConsumerCommissionRateResponse)(nil), "interchain_security.ccv.provider.v1.MsgSetConsumerCommissionRateResponse") proto.RegisterType((*MsgConsumerModification)(nil), "interchain_security.ccv.provider.v1.MsgConsumerModification") proto.RegisterType((*MsgConsumerModificationResponse)(nil), "interchain_security.ccv.provider.v1.MsgConsumerModificationResponse") + proto.RegisterType((*MsgCreateConsumer)(nil), "interchain_security.ccv.provider.v1.MsgCreateConsumer") + proto.RegisterType((*MsgCreateConsumerResponse)(nil), "interchain_security.ccv.provider.v1.MsgCreateConsumerResponse") + proto.RegisterType((*MsgUpdateConsumer)(nil), "interchain_security.ccv.provider.v1.MsgUpdateConsumer") + proto.RegisterType((*MsgUpdateConsumerResponse)(nil), "interchain_security.ccv.provider.v1.MsgUpdateConsumerResponse") } func init() { @@ -1333,118 +1682,137 @@ func init() { } var fileDescriptor_43221a4391e9fbf4 = []byte{ - // 1764 bytes of a gzipped FileDescriptorProto - 0x1f, 0x8b, 0x08, 0x00, 0x00, 0x00, 0x00, 0x00, 0x02, 0xff, 0xd4, 0x58, 0xcd, 0x8f, 0x1c, 0x47, - 0x15, 0xdf, 0xf6, 0x7e, 0x78, 0xe6, 0xcd, 0x7e, 0xf6, 0xae, 0xd9, 0xd9, 0xb6, 0x33, 0xb3, 0x5e, - 0x42, 0xb2, 0x32, 0xd9, 0xee, 0xd8, 0x90, 0x04, 0x56, 0x41, 0xb0, 0x1f, 0x06, 0x6f, 0x60, 0xed, - 0xa5, 0x6d, 0x8c, 0x04, 0x12, 0xad, 0x9a, 0xee, 0x72, 0x4f, 0xc9, 0xdd, 0x5d, 0xad, 0xae, 0x9a, - 0x71, 0xe6, 0x16, 0xe5, 0x84, 0x84, 0x84, 0x82, 0xc4, 0x01, 0x71, 0xca, 0x01, 0x21, 0x21, 0x01, - 0xf2, 0x21, 0x27, 0x6e, 0xdc, 0x7c, 0x8c, 0x22, 0x0e, 0x28, 0x07, 0x83, 0xec, 0x43, 0x38, 0xf3, - 0x17, 0xa0, 0xaa, 0xae, 0xee, 0xe9, 0xd9, 0x99, 0x9d, 0xf4, 0x8e, 0xc3, 0x21, 0x97, 0xd1, 0x74, - 0xbd, 0xdf, 0xfb, 0xd5, 0xef, 0xbd, 0xea, 0x7a, 0xaf, 0xaa, 0xe1, 0x35, 0x12, 0x71, 0x9c, 0xb8, - 0x6d, 0x44, 0x22, 0x87, 0x61, 0xb7, 0x93, 0x10, 0xde, 0xb3, 0x5c, 0xb7, 0x6b, 0xc5, 0x09, 0xed, - 0x12, 0x0f, 0x27, 0x56, 0xf7, 0xba, 0xc5, 0xdf, 0x35, 0xe3, 0x84, 0x72, 0xaa, 0x7f, 0x75, 0x04, - 0xda, 0x74, 0xdd, 0xae, 0x99, 0xa1, 0xcd, 0xee, 0x75, 0x63, 0x05, 0x85, 0x24, 0xa2, 0x96, 0xfc, - 0x4d, 0xfd, 0x8c, 0x2b, 0x3e, 0xa5, 0x7e, 0x80, 0x2d, 0x14, 0x13, 0x0b, 0x45, 0x11, 0xe5, 0x88, - 0x13, 0x1a, 0x31, 0x65, 0x6d, 0x2a, 0xab, 0x7c, 0x6a, 0x75, 0x1e, 0x58, 0x9c, 0x84, 0x98, 0x71, - 0x14, 0xc6, 0x0a, 0xd0, 0x38, 0x0d, 0xf0, 0x3a, 0x89, 0x64, 0x50, 0xf6, 0x8d, 0xd3, 0x76, 0x14, - 0xf5, 0x94, 0x69, 0xcd, 0xa7, 0x3e, 0x95, 0x7f, 0x2d, 0xf1, 0x2f, 0x73, 0x70, 0x29, 0x0b, 0x29, - 0x73, 0x52, 0x43, 0xfa, 0xa0, 0x4c, 0xeb, 0xe9, 0x93, 0x15, 0x32, 0x5f, 0x84, 0x1e, 0x32, 0x3f, - 0x53, 0x49, 0x5a, 0xae, 0xe5, 0xd2, 0x04, 0x5b, 0x6e, 0x40, 0x70, 0xc4, 0x85, 0x35, 0xfd, 0xa7, - 0x00, 0x37, 0xca, 0xa4, 0x32, 0x4f, 0x54, 0xea, 0x63, 0x09, 0xd2, 0x80, 0xf8, 0x6d, 0x9e, 0x52, - 0x31, 0x8b, 0xe3, 0xc8, 0xc3, 0x49, 0x48, 0xd2, 0x09, 0xfa, 0x4f, 0x99, 0x8a, 0x82, 0x9d, 0xf7, - 0x62, 0xcc, 0x2c, 0x2c, 0xf8, 0x22, 0x17, 0xa7, 0x80, 0xad, 0x7f, 0x68, 0xb0, 0x76, 0xcc, 0xfc, - 0x3d, 0xc6, 0x88, 0x1f, 0x1d, 0xd0, 0x88, 0x75, 0x42, 0x9c, 0xfc, 0x10, 0xf7, 0xf4, 0x0d, 0xa8, - 0xa4, 0xda, 0x88, 0x57, 0xd7, 0x36, 0xb5, 0xed, 0xaa, 0x7d, 0x51, 0x3e, 0x1f, 0x79, 0xfa, 0x5b, - 0xb0, 0x90, 0xe9, 0x72, 0x90, 0xe7, 0x25, 0xf5, 0x0b, 0xc2, 0xbe, 0xaf, 0xff, 0xf7, 0x69, 0x73, - 0xb1, 0x87, 0xc2, 0x60, 0x77, 0x4b, 0x8c, 0x62, 0xc6, 0xb6, 0xec, 0xf9, 0x0c, 0xb8, 0xe7, 0x79, - 0x89, 0x7e, 0x15, 0xe6, 0x5d, 0x35, 0x85, 0xf3, 0x10, 0xf7, 0xea, 0xd3, 0x92, 0xb7, 0xe6, 0x16, - 0xa6, 0x7d, 0x1d, 0xe6, 0x84, 0x12, 0x9c, 0xd4, 0x67, 0x24, 0x69, 0xfd, 0x93, 0x8f, 0x76, 0xd6, - 0x54, 0xc6, 0xf7, 0x52, 0xd6, 0xbb, 0x3c, 0x21, 0x91, 0x6f, 0x2b, 0xdc, 0xee, 0xea, 0x2f, 0x3f, - 0x6c, 0x4e, 0xfd, 0xe7, 0xc3, 0xe6, 0xd4, 0xfb, 0x9f, 0x3d, 0xbe, 0xa6, 0x06, 0xb7, 0x1a, 0x70, - 0x65, 0x54, 0x54, 0x36, 0x66, 0x31, 0x8d, 0x18, 0xde, 0xfa, 0xbb, 0x06, 0x2f, 0x1d, 0x33, 0xff, - 0x6e, 0xa7, 0x15, 0x12, 0x9e, 0x01, 0x8e, 0x09, 0x6b, 0xe1, 0x36, 0xea, 0x12, 0xda, 0x49, 0xf4, - 0x37, 0xa1, 0xca, 0xa4, 0x95, 0xe3, 0x24, 0x4d, 0xc0, 0x18, 0x2d, 0x7d, 0xa8, 0x7e, 0x02, 0xf3, - 0x61, 0x81, 0x47, 0xe6, 0xa6, 0x76, 0xe3, 0x35, 0x93, 0xb4, 0x5c, 0xb3, 0xb8, 0x72, 0x66, 0x61, - 0xad, 0xba, 0xd7, 0xcd, 0xe2, 0xdc, 0xf6, 0x00, 0xc3, 0xee, 0x57, 0x8a, 0x01, 0xf6, 0x67, 0xda, - 0x7a, 0x15, 0xbe, 0x36, 0x36, 0x84, 0x3c, 0xd8, 0xc7, 0x17, 0x46, 0x04, 0x7b, 0x48, 0x3b, 0xad, - 0x00, 0xdf, 0xa7, 0x9c, 0x44, 0xfe, 0xc4, 0xc1, 0x3a, 0xb0, 0xee, 0x75, 0xe2, 0x80, 0xb8, 0x88, - 0x63, 0xa7, 0x4b, 0x39, 0x76, 0xb2, 0xd7, 0x4b, 0xc5, 0xfd, 0x6a, 0x31, 0x4c, 0xf9, 0x02, 0x9a, - 0x87, 0x99, 0xc3, 0x7d, 0xca, 0xf1, 0x4d, 0x05, 0xb7, 0x2f, 0x79, 0xa3, 0x86, 0xf5, 0x5f, 0xc0, - 0x3a, 0x89, 0x1e, 0x24, 0xc8, 0x15, 0xdb, 0xd7, 0x69, 0x05, 0xd4, 0x7d, 0xe8, 0xb4, 0x31, 0xf2, - 0x70, 0x22, 0x5f, 0x9e, 0xda, 0x8d, 0x57, 0x3e, 0x2f, 0xb1, 0xb7, 0x24, 0xda, 0xbe, 0xd4, 0xa7, - 0xd9, 0x17, 0x2c, 0xe9, 0xf0, 0xb9, 0x72, 0x5b, 0xcc, 0x58, 0x9e, 0xdb, 0x3f, 0x68, 0xb0, 0x74, - 0xcc, 0xfc, 0x9f, 0xc4, 0x1e, 0xe2, 0xf8, 0x04, 0x25, 0x28, 0x64, 0x22, 0x9b, 0xa8, 0xc3, 0xdb, - 0x54, 0xec, 0xe8, 0xcf, 0xcf, 0x66, 0x0e, 0xd5, 0x8f, 0x60, 0x2e, 0x96, 0x0c, 0x2a, 0x79, 0x5f, - 0x37, 0x4b, 0xd4, 0x4f, 0x33, 0x9d, 0x74, 0x7f, 0xe6, 0xc9, 0xd3, 0xe6, 0x94, 0xad, 0x08, 0x76, - 0x17, 0x65, 0x3c, 0x39, 0xf5, 0xd6, 0x06, 0xac, 0x9f, 0x52, 0x99, 0x47, 0xf0, 0x69, 0x05, 0x56, - 0x8f, 0x99, 0x9f, 0x45, 0xb9, 0xe7, 0x79, 0x44, 0x64, 0x69, 0x5c, 0x01, 0xf8, 0x01, 0x2c, 0x92, - 0x88, 0x70, 0x82, 0x02, 0xa7, 0x8d, 0x45, 0xea, 0x95, 0x60, 0x43, 0x2e, 0x86, 0x28, 0x7a, 0xa6, - 0x2a, 0x75, 0x72, 0x01, 0x04, 0x42, 0xe9, 0x5b, 0x50, 0x7e, 0xe9, 0xa0, 0x28, 0x08, 0x3e, 0x8e, - 0x30, 0x23, 0xcc, 0x69, 0x23, 0xd6, 0x96, 0x6b, 0x3a, 0x6f, 0xd7, 0xd4, 0xd8, 0x2d, 0xc4, 0xda, - 0x7a, 0x13, 0x6a, 0x2d, 0x12, 0xa1, 0xa4, 0x97, 0x22, 0x66, 0x24, 0x02, 0xd2, 0x21, 0x09, 0x38, - 0x00, 0x60, 0x31, 0x7a, 0x14, 0x39, 0xa2, 0x0d, 0xd4, 0x67, 0x95, 0x90, 0xb4, 0xc4, 0x9b, 0x59, - 0x89, 0x37, 0xef, 0x65, 0x3d, 0x62, 0xbf, 0x22, 0x84, 0x7c, 0xf0, 0xaf, 0xa6, 0x66, 0x57, 0xa5, - 0x9f, 0xb0, 0xe8, 0xb7, 0x61, 0xb9, 0x13, 0xb5, 0x68, 0xe4, 0x91, 0xc8, 0x77, 0x62, 0x9c, 0x10, - 0xea, 0xd5, 0xe7, 0x24, 0xd5, 0xc6, 0x10, 0xd5, 0xa1, 0xea, 0x26, 0x29, 0xd3, 0xef, 0x04, 0xd3, - 0x52, 0xee, 0x7c, 0x22, 0x7d, 0xf5, 0x1f, 0x83, 0xee, 0xba, 0x5d, 0x29, 0x89, 0x76, 0x78, 0xc6, - 0x78, 0xb1, 0x3c, 0xe3, 0xb2, 0xeb, 0x76, 0xef, 0xa5, 0xde, 0x8a, 0xf2, 0xe7, 0xb0, 0xce, 0x13, - 0x14, 0xb1, 0x07, 0x38, 0x39, 0xcd, 0x5b, 0x29, 0xcf, 0x7b, 0x29, 0xe3, 0x18, 0x24, 0xbf, 0x05, - 0x9b, 0x79, 0x65, 0x4e, 0xb0, 0x47, 0x18, 0x4f, 0x48, 0xab, 0x23, 0x37, 0x5d, 0xb6, 0x6d, 0xea, - 0x55, 0xf9, 0x12, 0x34, 0x32, 0x9c, 0x3d, 0x00, 0xfb, 0xbe, 0x42, 0xe9, 0x77, 0xe0, 0x65, 0xb9, - 0x4d, 0x99, 0x10, 0xe7, 0x0c, 0x30, 0xc9, 0xa9, 0x43, 0xc2, 0x98, 0x60, 0x83, 0x4d, 0x6d, 0x7b, - 0xda, 0xbe, 0x9a, 0x62, 0x4f, 0x70, 0x72, 0x58, 0x40, 0xde, 0x2b, 0x00, 0xf5, 0x1d, 0xd0, 0xdb, - 0x84, 0x71, 0x9a, 0x10, 0x17, 0x05, 0x0e, 0x8e, 0x78, 0x42, 0x30, 0xab, 0xd7, 0xa4, 0xfb, 0x4a, - 0xdf, 0x72, 0x33, 0x35, 0xe8, 0xef, 0xc0, 0xd5, 0x33, 0x27, 0x75, 0xdc, 0x36, 0x8a, 0x22, 0x1c, - 0xd4, 0xe7, 0x65, 0x28, 0x4d, 0xef, 0x8c, 0x39, 0x0f, 0x52, 0x98, 0xbe, 0x0a, 0xb3, 0x9c, 0xc6, - 0xce, 0xed, 0xfa, 0xc2, 0xa6, 0xb6, 0xbd, 0x60, 0xcf, 0x70, 0x1a, 0xdf, 0xd6, 0x5f, 0x87, 0xb5, - 0x2e, 0x0a, 0x88, 0x87, 0x38, 0x4d, 0x98, 0x13, 0xd3, 0x47, 0x38, 0x71, 0x5c, 0x14, 0xd7, 0x17, - 0x25, 0x46, 0xef, 0xdb, 0x4e, 0x84, 0xe9, 0x00, 0xc5, 0xfa, 0x35, 0x58, 0xc9, 0x47, 0x1d, 0x86, - 0xb9, 0x84, 0x2f, 0x49, 0xf8, 0x52, 0x6e, 0xb8, 0x8b, 0xb9, 0xc0, 0x5e, 0x81, 0x2a, 0x0a, 0x02, - 0xfa, 0x28, 0x20, 0x8c, 0xd7, 0x97, 0x37, 0xa7, 0xb7, 0xab, 0x76, 0x7f, 0x40, 0x37, 0xa0, 0xe2, - 0xe1, 0xa8, 0x27, 0x8d, 0x2b, 0xd2, 0x98, 0x3f, 0x0f, 0x56, 0x1d, 0xbd, 0x7c, 0xd5, 0xb9, 0x0c, - 0xd5, 0x50, 0xd4, 0x17, 0x8e, 0x1e, 0xe2, 0xfa, 0xea, 0xa6, 0xb6, 0x3d, 0x63, 0x57, 0x42, 0x12, - 0xdd, 0x15, 0xcf, 0xba, 0x09, 0xab, 0x72, 0x76, 0x87, 0x44, 0x62, 0x7d, 0xbb, 0xd8, 0xe9, 0xa2, - 0x80, 0xd5, 0xd7, 0x36, 0xb5, 0xed, 0x8a, 0xbd, 0x22, 0x4d, 0x47, 0xca, 0x72, 0x1f, 0x05, 0xc3, - 0x75, 0xe7, 0x25, 0xb8, 0x3c, 0xa2, 0xb6, 0xe4, 0xb5, 0xe7, 0x6f, 0x1a, 0xe8, 0x05, 0xbb, 0x8d, - 0x43, 0xda, 0x45, 0xc1, 0xb8, 0xd2, 0xb3, 0x07, 0x55, 0x26, 0xd6, 0x44, 0x6e, 0xf6, 0x0b, 0xe7, - 0xd8, 0xec, 0x15, 0xe1, 0x26, 0xf7, 0xfa, 0x40, 0xa2, 0xa6, 0x4b, 0x27, 0x6a, 0x28, 0xb6, 0x2b, - 0x60, 0x0c, 0x6b, 0xcf, 0x43, 0xfb, 0x8b, 0x06, 0x97, 0x84, 0xb9, 0x8d, 0x22, 0x1f, 0xdb, 0xf8, - 0x11, 0x4a, 0xbc, 0x43, 0x1c, 0xd1, 0x90, 0xe9, 0x5b, 0xb0, 0xe0, 0xc9, 0x7f, 0x0e, 0xa7, 0xe2, - 0xfc, 0x54, 0xd7, 0xe4, 0x4a, 0xd6, 0xd2, 0xc1, 0x7b, 0x74, 0xcf, 0xf3, 0xf4, 0x6d, 0x58, 0xee, - 0x63, 0x12, 0x41, 0x2d, 0xa2, 0x15, 0xb0, 0xc5, 0x0c, 0x26, 0x27, 0xfc, 0xe2, 0xa2, 0x69, 0xca, - 0x33, 0xc2, 0xb0, 0xdc, 0x3c, 0xa0, 0x27, 0x1a, 0x54, 0x8e, 0x99, 0x7f, 0x27, 0xe6, 0x47, 0xd1, - 0x97, 0xfc, 0x74, 0xa8, 0xc3, 0x72, 0x16, 0x49, 0x1e, 0xde, 0x1f, 0x35, 0xa8, 0xa6, 0x83, 0x77, - 0x3a, 0xfc, 0xff, 0x12, 0x5f, 0x5f, 0xfc, 0xf4, 0x8b, 0x88, 0x5f, 0x85, 0x95, 0x5c, 0x67, 0xae, - 0xfe, 0xbd, 0x0b, 0xf2, 0xc0, 0x2b, 0x8a, 0x88, 0x4a, 0xd7, 0x01, 0x0d, 0x55, 0x35, 0xb3, 0x11, - 0xc7, 0xc3, 0xaa, 0xb5, 0x92, 0xaa, 0x8b, 0x99, 0xb8, 0x30, 0x98, 0x89, 0x9b, 0x30, 0x93, 0x20, - 0x8e, 0x55, 0x38, 0xd7, 0xc5, 0x56, 0xfb, 0xf4, 0x69, 0xf3, 0x72, 0x1a, 0x12, 0xf3, 0x1e, 0x9a, - 0x84, 0x5a, 0x21, 0xe2, 0x6d, 0xf3, 0x47, 0xd8, 0x47, 0x6e, 0xef, 0x10, 0xbb, 0x9f, 0x7c, 0xb4, - 0x03, 0x2a, 0xe2, 0x43, 0xec, 0xda, 0xd2, 0xfd, 0x8b, 0x5a, 0xd4, 0x57, 0xe0, 0xe5, 0x71, 0x19, - 0xc8, 0x53, 0xf5, 0xd7, 0x69, 0x79, 0x16, 0xca, 0x4f, 0xcc, 0xd4, 0x23, 0x0f, 0xc4, 0xc1, 0x53, - 0xf4, 0x9a, 0x35, 0x98, 0xe5, 0x84, 0x07, 0x58, 0xad, 0x79, 0xfa, 0xa0, 0x6f, 0x42, 0xcd, 0xc3, - 0xcc, 0x4d, 0x48, 0x2c, 0xfb, 0x60, 0x9a, 0x85, 0xe2, 0xd0, 0x40, 0x92, 0xa6, 0x07, 0x93, 0x94, - 0xf7, 0x90, 0x99, 0x12, 0x3d, 0x64, 0xf6, 0x7c, 0x3d, 0x64, 0xae, 0x44, 0x0f, 0xb9, 0x38, 0xae, - 0x87, 0x54, 0xc6, 0xf5, 0x90, 0xea, 0x84, 0x3d, 0x04, 0xca, 0xf5, 0x90, 0x5a, 0xd9, 0x1e, 0x72, - 0x15, 0x9a, 0x67, 0xac, 0x57, 0xb6, 0xa6, 0x37, 0x9e, 0xcf, 0xc3, 0xf4, 0x31, 0xf3, 0xf5, 0xdf, - 0x68, 0xb0, 0x32, 0x7c, 0x95, 0xfd, 0x76, 0xa9, 0x73, 0xf4, 0xa8, 0xfb, 0xa2, 0xb1, 0x37, 0xb1, - 0x6b, 0xa6, 0x4d, 0xff, 0xb3, 0x06, 0xc6, 0x98, 0x7b, 0xe6, 0x7e, 0xd9, 0x19, 0xce, 0xe6, 0x30, - 0xde, 0x79, 0x71, 0x8e, 0x31, 0x72, 0x07, 0x6e, 0x8a, 0x13, 0xca, 0x2d, 0x72, 0x4c, 0x2a, 0x77, - 0xd4, 0xfd, 0x4b, 0xff, 0xb5, 0x06, 0xcb, 0x43, 0x57, 0x97, 0x6f, 0x95, 0x9d, 0xe0, 0xb4, 0xa7, - 0xf1, 0xbd, 0x49, 0x3d, 0x73, 0x41, 0xbf, 0xd2, 0x60, 0xe9, 0xf4, 0x79, 0xe6, 0xad, 0xf3, 0xb2, - 0x2a, 0x47, 0xe3, 0xbb, 0x13, 0x3a, 0xe6, 0x6a, 0xde, 0xd7, 0x60, 0x7e, 0xe0, 0x6e, 0xfa, 0xcd, - 0xb2, 0x8c, 0x45, 0x2f, 0xe3, 0xed, 0x49, 0xbc, 0x72, 0x11, 0x21, 0xcc, 0xa6, 0xa7, 0x86, 0x9d, - 0xb2, 0x34, 0x12, 0x6e, 0xbc, 0x71, 0x2e, 0x78, 0x3e, 0x5d, 0x0c, 0x73, 0xaa, 0x8b, 0x9b, 0xe7, - 0x20, 0xb8, 0xd3, 0xe1, 0xc6, 0x9b, 0xe7, 0xc3, 0xe7, 0x33, 0xfe, 0x49, 0x83, 0x8d, 0xb3, 0x5b, - 0x6f, 0xe9, 0x1a, 0x72, 0x26, 0x85, 0x71, 0xf4, 0xc2, 0x14, 0xb9, 0xd6, 0xdf, 0x6b, 0xb0, 0x36, - 0xb2, 0xf7, 0xbd, 0x7d, 0xde, 0x77, 0xad, 0xe8, 0x6d, 0x1c, 0xbe, 0x88, 0x77, 0x2e, 0xee, 0xb7, - 0x1a, 0xe8, 0x23, 0x4e, 0xcc, 0xbb, 0xa5, 0xc9, 0x87, 0x7c, 0x8d, 0xfd, 0xc9, 0x7d, 0x33, 0x59, - 0xc6, 0xec, 0x7b, 0x9f, 0x3d, 0xbe, 0xa6, 0xed, 0xff, 0xf4, 0xc9, 0xb3, 0x86, 0xf6, 0xf1, 0xb3, - 0x86, 0xf6, 0xef, 0x67, 0x0d, 0xed, 0x83, 0xe7, 0x8d, 0xa9, 0x8f, 0x9f, 0x37, 0xa6, 0xfe, 0xf9, - 0xbc, 0x31, 0xf5, 0xb3, 0xef, 0xf8, 0x84, 0xb7, 0x3b, 0x2d, 0xd3, 0xa5, 0xa1, 0xfa, 0x3c, 0x6c, - 0xf5, 0x67, 0xdd, 0xc9, 0xbf, 0xee, 0x76, 0xdf, 0xb0, 0xde, 0x1d, 0xfc, 0xc4, 0x2b, 0x3f, 0x89, - 0xb5, 0xe6, 0xe4, 0xcd, 0xe5, 0x1b, 0xff, 0x0b, 0x00, 0x00, 0xff, 0xff, 0x88, 0x80, 0xb2, 0x2a, - 0x5e, 0x17, 0x00, 0x00, + // 2075 bytes of a gzipped FileDescriptorProto + 0x1f, 0x8b, 0x08, 0x00, 0x00, 0x00, 0x00, 0x00, 0x02, 0xff, 0xe4, 0x59, 0xcb, 0x6f, 0x1c, 0x49, + 0x19, 0x77, 0xcf, 0x8c, 0xbd, 0x33, 0xe5, 0x77, 0xdb, 0x59, 0xb7, 0x27, 0x89, 0xc7, 0x31, 0xcb, + 0xae, 0x15, 0xd6, 0x3d, 0xc4, 0x90, 0x5d, 0x30, 0xe1, 0xe1, 0x47, 0x20, 0x5e, 0x70, 0xec, 0x6d, + 0x87, 0xac, 0x04, 0x12, 0xad, 0x9a, 0xee, 0x4a, 0x4f, 0x29, 0xdd, 0x5d, 0xad, 0xae, 0x9a, 0xf1, + 0x9a, 0x13, 0x8a, 0x84, 0x94, 0x63, 0xd0, 0x72, 0xe0, 0xc6, 0x1e, 0xb8, 0x20, 0x01, 0xda, 0xc3, + 0x9e, 0xf8, 0x0b, 0x56, 0xe2, 0xb2, 0xac, 0x38, 0xa0, 0x3d, 0x04, 0x94, 0x1c, 0x96, 0x33, 0x07, + 0xce, 0xa8, 0x1e, 0xdd, 0x33, 0x3d, 0x33, 0x76, 0x7a, 0xc6, 0x2c, 0x1c, 0xb8, 0x8c, 0xba, 0xeb, + 0xfb, 0x7d, 0xbf, 0xef, 0x51, 0x55, 0xdf, 0x57, 0xd5, 0x03, 0x5e, 0xc7, 0x21, 0x43, 0xb1, 0xd3, + 0x84, 0x38, 0xb4, 0x29, 0x72, 0x5a, 0x31, 0x66, 0xa7, 0x75, 0xc7, 0x69, 0xd7, 0xa3, 0x98, 0xb4, + 0xb1, 0x8b, 0xe2, 0x7a, 0xfb, 0x46, 0x9d, 0xbd, 0x6b, 0x46, 0x31, 0x61, 0x44, 0xff, 0xc2, 0x00, + 0xb4, 0xe9, 0x38, 0x6d, 0x33, 0x41, 0x9b, 0xed, 0x1b, 0xd5, 0x79, 0x18, 0xe0, 0x90, 0xd4, 0xc5, + 0xaf, 0xd4, 0xab, 0x5e, 0xf1, 0x08, 0xf1, 0x7c, 0x54, 0x87, 0x11, 0xae, 0xc3, 0x30, 0x24, 0x0c, + 0x32, 0x4c, 0x42, 0xaa, 0xa4, 0x35, 0x25, 0x15, 0x6f, 0x8d, 0xd6, 0x83, 0x3a, 0xc3, 0x01, 0xa2, + 0x0c, 0x06, 0x91, 0x02, 0xac, 0xf4, 0x02, 0xdc, 0x56, 0x2c, 0x18, 0x94, 0x7c, 0xb9, 0x57, 0x0e, + 0xc3, 0x53, 0x25, 0x5a, 0xf4, 0x88, 0x47, 0xc4, 0x63, 0x9d, 0x3f, 0x25, 0x0a, 0x0e, 0xa1, 0x01, + 0xa1, 0xb6, 0x14, 0xc8, 0x17, 0x25, 0x5a, 0x92, 0x6f, 0xf5, 0x80, 0x7a, 0x3c, 0xf4, 0x80, 0x7a, + 0x89, 0x97, 0xb8, 0xe1, 0xd4, 0x1d, 0x12, 0xa3, 0xba, 0xe3, 0x63, 0x14, 0x32, 0x2e, 0x95, 0x4f, + 0x0a, 0xb0, 0x99, 0x27, 0x95, 0x69, 0xa2, 0xa4, 0x4e, 0x9d, 0x93, 0xfa, 0xd8, 0x6b, 0x32, 0x49, + 0x45, 0xeb, 0x0c, 0x85, 0x2e, 0x8a, 0x03, 0x2c, 0x0d, 0x74, 0xde, 0x12, 0x2f, 0xba, 0xe4, 0xec, + 0x34, 0x42, 0xb4, 0x8e, 0x38, 0x5f, 0xe8, 0x20, 0x09, 0x58, 0x7b, 0x54, 0x00, 0x8b, 0x07, 0xd4, + 0xdb, 0xa6, 0x14, 0x7b, 0xe1, 0x2e, 0x09, 0x69, 0x2b, 0x40, 0xf1, 0xf7, 0xd1, 0xa9, 0x7e, 0x15, + 0x94, 0xa5, 0x6f, 0xd8, 0x35, 0xb4, 0x55, 0x6d, 0xbd, 0xb2, 0x53, 0x30, 0x34, 0xeb, 0x25, 0x31, + 0xb6, 0xef, 0xea, 0x6f, 0x82, 0xe9, 0xc4, 0x37, 0x1b, 0xba, 0x6e, 0x6c, 0x14, 0x04, 0x46, 0xff, + 0xe7, 0xd3, 0xda, 0xcc, 0x29, 0x0c, 0xfc, 0xad, 0x35, 0x3e, 0x8a, 0x28, 0x5d, 0xb3, 0xa6, 0x12, + 0xe0, 0xb6, 0xeb, 0xc6, 0xfa, 0x35, 0x30, 0xe5, 0x28, 0x33, 0xf6, 0x43, 0x74, 0x6a, 0x14, 0xb9, + 0x9e, 0x35, 0xe9, 0x74, 0x99, 0x7e, 0x03, 0x54, 0x68, 0xab, 0x11, 0x60, 0xc6, 0x50, 0x6c, 0x94, + 0x04, 0xaf, 0xf1, 0xc9, 0x87, 0x1b, 0x8b, 0x2a, 0xf1, 0xdb, 0x92, 0xf8, 0x98, 0xc5, 0x38, 0xf4, + 0xac, 0x0e, 0x54, 0xaf, 0x81, 0x94, 0x86, 0x7b, 0x3d, 0x2e, 0x98, 0x41, 0x32, 0xb4, 0xef, 0x6e, + 0xbd, 0xfc, 0xf8, 0xfd, 0xda, 0xd8, 0x3f, 0xde, 0xaf, 0x8d, 0x3d, 0xfa, 0xec, 0x83, 0xeb, 0x1d, + 0xc5, 0xb5, 0x15, 0x70, 0x65, 0x50, 0x0e, 0x2c, 0x44, 0x23, 0x12, 0x52, 0xb4, 0xf6, 0x4c, 0x03, + 0x57, 0x0f, 0xa8, 0x77, 0x2c, 0x14, 0x12, 0xc0, 0x01, 0xa6, 0x0d, 0xd4, 0x84, 0x6d, 0x4c, 0x5a, + 0x71, 0xd6, 0x65, 0x2d, 0xbf, 0xcb, 0x47, 0x60, 0x2a, 0xe8, 0xe2, 0x11, 0x59, 0x9c, 0xdc, 0x7c, + 0xdd, 0xc4, 0x0d, 0xc7, 0xec, 0x9e, 0x67, 0xb3, 0x6b, 0x66, 0xdb, 0x37, 0xcc, 0x6e, 0xdb, 0x56, + 0x86, 0xa1, 0x37, 0x09, 0xc5, 0xdc, 0x49, 0x78, 0x0d, 0x7c, 0xf1, 0xdc, 0x18, 0xd3, 0x6c, 0xfc, + 0xb9, 0x30, 0x20, 0x1b, 0x7b, 0xa4, 0xd5, 0xf0, 0xd1, 0x7d, 0xc2, 0x70, 0xe8, 0x8d, 0x9c, 0x0d, + 0x1b, 0x2c, 0xb9, 0xad, 0xc8, 0xc7, 0x0e, 0x64, 0xc8, 0x6e, 0x13, 0x86, 0xec, 0x64, 0xb5, 0xaa, + 0xc4, 0xbc, 0xd6, 0x9d, 0x07, 0xb1, 0x9e, 0xcd, 0xbd, 0x44, 0xe1, 0x3e, 0x61, 0xe8, 0xb6, 0x82, + 0x5b, 0x97, 0xdc, 0x41, 0xc3, 0xfa, 0x4f, 0xc0, 0x12, 0x0e, 0x1f, 0xc4, 0xd0, 0xe1, 0xd5, 0xc0, + 0x6e, 0xf8, 0xc4, 0x79, 0x68, 0x37, 0x11, 0x74, 0x51, 0x2c, 0x12, 0x35, 0xb9, 0xf9, 0xea, 0x8b, + 0x32, 0x7f, 0x47, 0xa0, 0xad, 0x4b, 0x1d, 0x9a, 0x1d, 0xce, 0x22, 0x87, 0x7b, 0x93, 0x5f, 0xba, + 0x50, 0xf2, 0xbb, 0x53, 0x9a, 0x26, 0xff, 0x37, 0x1a, 0x98, 0x3d, 0xa0, 0xde, 0x0f, 0x23, 0x17, + 0x32, 0x74, 0x04, 0x63, 0x18, 0x50, 0x9e, 0x6e, 0xd8, 0x62, 0x4d, 0xc2, 0x2b, 0xc8, 0x8b, 0xd3, + 0x9d, 0x42, 0xf5, 0x7d, 0x30, 0x11, 0x09, 0x06, 0x95, 0xdd, 0x2f, 0x99, 0x39, 0xea, 0xb5, 0x29, + 0x8d, 0xee, 0x94, 0x3e, 0x7a, 0x5a, 0x1b, 0xb3, 0x14, 0xc1, 0xd6, 0x8c, 0x88, 0x27, 0xa5, 0x5e, + 0x5b, 0x06, 0x4b, 0x3d, 0x5e, 0xa6, 0x11, 0x7c, 0x5a, 0x06, 0x0b, 0x07, 0xd4, 0x4b, 0xa2, 0xdc, + 0x76, 0x5d, 0xcc, 0xd3, 0xa8, 0x2f, 0xf7, 0x16, 0x9c, 0x4e, 0xb1, 0xf9, 0x1e, 0x98, 0xc1, 0x21, + 0x66, 0x18, 0xfa, 0x76, 0x13, 0xf1, 0xb9, 0x51, 0x0e, 0x57, 0xc5, 0x6c, 0xf1, 0x22, 0x6b, 0xaa, + 0xd2, 0x2a, 0x66, 0x88, 0x23, 0x94, 0x7f, 0xd3, 0x4a, 0x4f, 0x0e, 0xf2, 0xe2, 0xe3, 0xa1, 0x10, + 0x51, 0x4c, 0xed, 0x26, 0xa4, 0x4d, 0x31, 0xe9, 0x53, 0xd6, 0xa4, 0x1a, 0xbb, 0x03, 0x69, 0x93, + 0x4f, 0x61, 0x03, 0x87, 0x30, 0x3e, 0x95, 0x88, 0x92, 0x40, 0x00, 0x39, 0x24, 0x00, 0xbb, 0x00, + 0xd0, 0x08, 0x9e, 0x84, 0x36, 0x6f, 0x3b, 0xa2, 0xc8, 0x70, 0x47, 0x64, 0x4b, 0x31, 0x93, 0x96, + 0x62, 0xde, 0x4b, 0x7a, 0xd2, 0x4e, 0x99, 0x3b, 0xf2, 0xe4, 0x6f, 0x35, 0xcd, 0xaa, 0x08, 0x3d, + 0x2e, 0xd1, 0xef, 0x82, 0xb9, 0x56, 0xd8, 0x20, 0xa1, 0x8b, 0x43, 0xcf, 0x8e, 0x50, 0x8c, 0x89, + 0x6b, 0x4c, 0x08, 0xaa, 0xe5, 0x3e, 0xaa, 0x3d, 0xd5, 0xbd, 0x24, 0xd3, 0xaf, 0x38, 0xd3, 0x6c, + 0xaa, 0x7c, 0x24, 0x74, 0xf5, 0xb7, 0x81, 0xee, 0x38, 0x6d, 0xe1, 0x12, 0x69, 0xb1, 0x84, 0xf1, + 0xa5, 0xfc, 0x8c, 0x73, 0x8e, 0xd3, 0xbe, 0x27, 0xb5, 0x15, 0xe5, 0x8f, 0xc1, 0x12, 0x8b, 0x61, + 0x48, 0x1f, 0xa0, 0xb8, 0x97, 0xb7, 0x9c, 0x9f, 0xf7, 0x52, 0xc2, 0x91, 0x25, 0xbf, 0x03, 0x56, + 0xd3, 0x8d, 0x12, 0x23, 0x17, 0x53, 0x16, 0xe3, 0x46, 0x4b, 0xec, 0xca, 0x64, 0x5f, 0x19, 0x15, + 0xb1, 0x08, 0x56, 0x12, 0x9c, 0x95, 0x81, 0x7d, 0x57, 0xa1, 0xf4, 0x43, 0xf0, 0x8a, 0xd8, 0xc7, + 0x94, 0x3b, 0x67, 0x67, 0x98, 0x84, 0xe9, 0x00, 0x53, 0xca, 0xd9, 0xc0, 0xaa, 0xb6, 0x5e, 0xb4, + 0xae, 0x49, 0xec, 0x11, 0x8a, 0xf7, 0xba, 0x90, 0xf7, 0xba, 0x80, 0xfa, 0x06, 0xd0, 0x9b, 0x98, + 0x32, 0x12, 0x63, 0x07, 0xfa, 0x36, 0x0a, 0x59, 0x8c, 0x11, 0x35, 0x26, 0x85, 0xfa, 0x7c, 0x47, + 0x72, 0x5b, 0x0a, 0xf4, 0xb7, 0xc0, 0xb5, 0x33, 0x8d, 0xda, 0x4e, 0x13, 0x86, 0x21, 0xf2, 0x8d, + 0x29, 0x11, 0x4a, 0xcd, 0x3d, 0xc3, 0xe6, 0xae, 0x84, 0xe9, 0x0b, 0x60, 0x9c, 0x91, 0xc8, 0xbe, + 0x6b, 0x4c, 0xaf, 0x6a, 0xeb, 0xd3, 0x56, 0x89, 0x91, 0xe8, 0xae, 0xfe, 0x65, 0xb0, 0xd8, 0x86, + 0x3e, 0x76, 0x21, 0x23, 0x31, 0xb5, 0x23, 0x72, 0x82, 0x62, 0xdb, 0x81, 0x91, 0x31, 0x23, 0x30, + 0x7a, 0x47, 0x76, 0xc4, 0x45, 0xbb, 0x30, 0xd2, 0xaf, 0x83, 0xf9, 0x74, 0xd4, 0xa6, 0x88, 0x09, + 0xf8, 0xac, 0x80, 0xcf, 0xa6, 0x82, 0x63, 0xc4, 0x38, 0xf6, 0x0a, 0xa8, 0x40, 0xdf, 0x27, 0x27, + 0x3e, 0xa6, 0xcc, 0x98, 0x5b, 0x2d, 0xae, 0x57, 0xac, 0xce, 0x80, 0x5e, 0x05, 0x65, 0x17, 0x85, + 0xa7, 0x42, 0x38, 0x2f, 0x84, 0xe9, 0x7b, 0xb6, 0xea, 0xe8, 0xf9, 0xab, 0xce, 0x65, 0x50, 0x09, + 0x78, 0x7d, 0x61, 0xf0, 0x21, 0x32, 0x16, 0x56, 0xb5, 0xf5, 0x92, 0x55, 0x0e, 0x70, 0x78, 0xcc, + 0xdf, 0x75, 0x13, 0x2c, 0x08, 0xeb, 0x36, 0x0e, 0xf9, 0xfc, 0xb6, 0x91, 0xdd, 0x86, 0x3e, 0x35, + 0x16, 0x57, 0xb5, 0xf5, 0xb2, 0x35, 0x2f, 0x44, 0xfb, 0x4a, 0x72, 0x1f, 0xfa, 0xfd, 0x75, 0xe7, + 0x2a, 0xb8, 0x3c, 0xa0, 0xb6, 0xa4, 0xb5, 0xe7, 0x8f, 0x1a, 0xd0, 0xbb, 0xe4, 0x16, 0x0a, 0x48, + 0x1b, 0xfa, 0xe7, 0x95, 0x9e, 0x6d, 0x50, 0xa1, 0x7c, 0x4e, 0xc4, 0x66, 0x2f, 0x0c, 0xb1, 0xd9, + 0xcb, 0x5c, 0x4d, 0xec, 0xf5, 0x4c, 0xa2, 0x8a, 0xb9, 0x13, 0xd5, 0x17, 0xdb, 0x15, 0x50, 0xed, + 0xf7, 0x3d, 0x0d, 0x2d, 0x02, 0xf3, 0x07, 0xd4, 0x13, 0xa3, 0x28, 0xc1, 0xf4, 0xf6, 0x23, 0xad, + 0xb7, 0x1f, 0xe9, 0x26, 0x18, 0x27, 0x27, 0x21, 0x4a, 0x8e, 0x6f, 0x67, 0xfb, 0x25, 0x61, 0x5b, + 0x80, 0xfb, 0x24, 0x9f, 0xd7, 0x2e, 0x83, 0xe5, 0x3e, 0x8b, 0xa9, 0x3b, 0xbf, 0xd7, 0xc0, 0x25, + 0xee, 0x6d, 0x13, 0x86, 0x1e, 0xb2, 0xd0, 0x09, 0x8c, 0xdd, 0x3d, 0x14, 0x92, 0x80, 0xea, 0x6b, + 0x60, 0xda, 0x15, 0x4f, 0x36, 0x23, 0xfc, 0xe8, 0x68, 0x68, 0x62, 0x61, 0x4d, 0xca, 0xc1, 0x7b, + 0x64, 0xdb, 0x75, 0xf5, 0x75, 0x30, 0xd7, 0xc1, 0xc4, 0xc2, 0x82, 0x51, 0x10, 0xb0, 0x99, 0x04, + 0x26, 0xed, 0xfe, 0xc7, 0x92, 0x5b, 0x13, 0x67, 0x9a, 0x7e, 0x77, 0xd3, 0x80, 0xfe, 0xa5, 0x81, + 0xf2, 0x01, 0xf5, 0x0e, 0x23, 0xb6, 0x1f, 0xfe, 0x5f, 0x1d, 0x8e, 0x75, 0x30, 0x97, 0xc4, 0x9d, + 0x26, 0xe3, 0x2f, 0x1a, 0xa8, 0xc8, 0xc1, 0xc3, 0x16, 0xfb, 0xdc, 0xb2, 0x91, 0x09, 0xb5, 0x38, + 0x72, 0xa8, 0xf9, 0x4f, 0x61, 0x0b, 0x62, 0x0f, 0xc9, 0xa8, 0xd2, 0x58, 0xff, 0x50, 0x10, 0xb7, + 0x03, 0x5e, 0x2f, 0x15, 0xc3, 0x2e, 0x09, 0x54, 0xe1, 0xb6, 0x20, 0x43, 0xfd, 0xf1, 0x69, 0x39, + 0xe3, 0xeb, 0xce, 0x5b, 0xa1, 0x3f, 0x6f, 0xb7, 0x41, 0x29, 0x86, 0x0c, 0xa9, 0xc8, 0x6f, 0xf0, + 0xca, 0xf2, 0xe9, 0xd3, 0xda, 0x65, 0x19, 0x3d, 0x75, 0x1f, 0x9a, 0x98, 0xd4, 0x03, 0xc8, 0x9a, + 0xe6, 0x0f, 0x90, 0x07, 0x9d, 0xd3, 0x3d, 0xe4, 0x7c, 0xf2, 0xe1, 0x06, 0x50, 0xc9, 0xd9, 0x43, + 0x8e, 0x25, 0xd4, 0xff, 0xfb, 0x0b, 0xe6, 0x55, 0xf0, 0xca, 0x79, 0xf9, 0xea, 0x24, 0xb6, 0x28, + 0x0e, 0x89, 0xe9, 0x5d, 0x83, 0xb8, 0xf8, 0x01, 0x3f, 0xb2, 0xf3, 0x26, 0xbc, 0x08, 0xc6, 0x19, + 0x66, 0x3e, 0x52, 0x25, 0x4b, 0xbe, 0xe8, 0xab, 0x60, 0xd2, 0x45, 0xd4, 0x89, 0x71, 0x24, 0x0e, + 0x08, 0x05, 0xb9, 0x3b, 0xba, 0x86, 0x32, 0x95, 0xbc, 0x98, 0xad, 0xe4, 0x69, 0x73, 0x2d, 0xe5, + 0x68, 0xae, 0xe3, 0xc3, 0x35, 0xd7, 0x89, 0x1c, 0xcd, 0xf5, 0xa5, 0xf3, 0x9a, 0x6b, 0xf9, 0xbc, + 0xe6, 0x5a, 0x19, 0xb1, 0xb9, 0x82, 0x7c, 0xcd, 0x75, 0x32, 0x6f, 0x73, 0xbd, 0x06, 0x6a, 0x67, + 0xcc, 0x57, 0x3a, 0xa7, 0x7f, 0x2a, 0x8a, 0x2d, 0xb4, 0x1b, 0x23, 0xc8, 0x3a, 0x6d, 0x68, 0xd4, + 0xfb, 0xe0, 0x72, 0xef, 0x06, 0xe9, 0xcc, 0xe6, 0x3b, 0xa0, 0x1c, 0x20, 0x06, 0x5d, 0xc8, 0xa0, + 0xba, 0xba, 0xdd, 0xcc, 0x75, 0x7b, 0x49, 0xbd, 0x57, 0xca, 0xea, 0x9e, 0x90, 0x92, 0xe9, 0x8f, + 0x34, 0xb0, 0xac, 0x2e, 0x0d, 0xf8, 0xa7, 0x22, 0x38, 0x5b, 0xdc, 0x71, 0x10, 0x43, 0x31, 0x15, + 0x6b, 0x67, 0x72, 0xf3, 0xf6, 0x50, 0xa6, 0xf6, 0x33, 0x6c, 0x47, 0x29, 0x99, 0x65, 0xe0, 0x33, + 0x24, 0x7a, 0x0b, 0x18, 0x72, 0x2d, 0xd2, 0x26, 0x8c, 0xc4, 0x15, 0xa1, 0xe3, 0x82, 0xbc, 0x71, + 0x7c, 0x23, 0xdf, 0x5d, 0x8d, 0x93, 0x1c, 0x4b, 0x8e, 0x2e, 0xc3, 0x2f, 0x47, 0x03, 0xc7, 0xd5, + 0x84, 0x77, 0x76, 0xf2, 0x2d, 0xd1, 0xe1, 0xb3, 0x93, 0x99, 0x4c, 0xf5, 0x0b, 0xcf, 0x16, 0x6b, + 0x3f, 0x2f, 0x89, 0xb5, 0x20, 0x2f, 0x81, 0xe9, 0x5a, 0x48, 0x4f, 0x1c, 0x5a, 0xae, 0x13, 0x47, + 0xaf, 0x99, 0x42, 0xdf, 0x11, 0x66, 0x0f, 0xcc, 0x87, 0xe8, 0xc4, 0x16, 0x68, 0x5b, 0x55, 0xda, + 0x17, 0x76, 0x8b, 0xd9, 0x10, 0x9d, 0x1c, 0x72, 0x0d, 0x35, 0xac, 0xbf, 0xdd, 0xb5, 0x9e, 0x4a, + 0x17, 0x58, 0x4f, 0xb9, 0x57, 0xd2, 0xf8, 0xff, 0x7e, 0x25, 0x4d, 0x7c, 0x7e, 0x2b, 0xa9, 0xff, + 0x9c, 0x98, 0x5d, 0x06, 0xc9, 0x2a, 0xda, 0x7c, 0x6f, 0x0e, 0x14, 0x0f, 0xa8, 0xa7, 0xff, 0x42, + 0x03, 0xf3, 0xfd, 0x1f, 0x21, 0xbf, 0x9e, 0xcb, 0xb7, 0x41, 0xdf, 0xee, 0xaa, 0xdb, 0x23, 0xab, + 0xa6, 0x2b, 0xfc, 0x77, 0x1a, 0xa8, 0x9e, 0xf3, 0xcd, 0x6f, 0x27, 0xaf, 0x85, 0xb3, 0x39, 0xaa, + 0x6f, 0x5d, 0x9c, 0xe3, 0x1c, 0x77, 0x33, 0x1f, 0xe5, 0x46, 0x74, 0xb7, 0x9b, 0x63, 0x54, 0x77, + 0x07, 0x7d, 0xc9, 0xd2, 0xdf, 0xd3, 0xc0, 0x5c, 0xdf, 0x47, 0xa0, 0xaf, 0xe5, 0x35, 0xd0, 0xab, + 0x59, 0xfd, 0xce, 0xa8, 0x9a, 0x69, 0xef, 0x2a, 0x3e, 0x2e, 0x68, 0xfa, 0x13, 0x0d, 0xcc, 0xf6, + 0x5e, 0x0f, 0xdf, 0x1c, 0x96, 0x5a, 0x29, 0x56, 0xbf, 0x3d, 0xa2, 0x62, 0xd6, 0xa5, 0xc7, 0x1a, + 0x98, 0xe9, 0x6d, 0xa8, 0xb9, 0x89, 0x33, 0x7a, 0xd5, 0x6f, 0x8d, 0xa6, 0x97, 0xce, 0x19, 0x77, + 0xa5, 0xa7, 0x9e, 0xe7, 0x76, 0x25, 0xab, 0x97, 0xdf, 0x95, 0xc1, 0x85, 0x43, 0xb8, 0xd2, 0x73, + 0xdb, 0xcd, 0xed, 0x4a, 0x56, 0x2f, 0xbf, 0x2b, 0x83, 0xef, 0xba, 0xbc, 0xd0, 0x4f, 0x65, 0x3e, + 0xc8, 0x7e, 0x75, 0xb8, 0xd8, 0xa4, 0x56, 0xf5, 0xd6, 0x28, 0x5a, 0xa9, 0x13, 0x01, 0x18, 0x97, + 0x77, 0xd3, 0x8d, 0xbc, 0x34, 0x02, 0x5e, 0xbd, 0x39, 0x14, 0x3c, 0x35, 0x17, 0x81, 0x09, 0x75, + 0xfb, 0x33, 0x87, 0x20, 0x38, 0x6c, 0xb1, 0xea, 0x1b, 0xc3, 0xe1, 0x53, 0x8b, 0xbf, 0xd5, 0xc0, + 0xf2, 0xd9, 0x97, 0xb0, 0xdc, 0xe5, 0xfe, 0x4c, 0x8a, 0xea, 0xfe, 0x85, 0x29, 0x52, 0x5f, 0x7f, + 0xad, 0x81, 0xc5, 0x81, 0xf7, 0x9a, 0x5b, 0xc3, 0x56, 0x84, 0x6e, 0xed, 0xea, 0xde, 0x45, 0xb4, + 0xb3, 0x45, 0xe5, 0x97, 0x1a, 0xd0, 0x07, 0x7c, 0x9c, 0xd9, 0xca, 0x6d, 0xa1, 0x4f, 0xb7, 0xba, + 0x33, 0xba, 0x6e, 0xe2, 0x5b, 0x75, 0xfc, 0x67, 0x9f, 0x7d, 0x70, 0x5d, 0xdb, 0x79, 0xe7, 0xa3, + 0x67, 0x2b, 0xda, 0xc7, 0xcf, 0x56, 0xb4, 0xbf, 0x3f, 0x5b, 0xd1, 0x9e, 0x3c, 0x5f, 0x19, 0xfb, + 0xf8, 0xf9, 0xca, 0xd8, 0x5f, 0x9f, 0xaf, 0x8c, 0xfd, 0xe8, 0x9b, 0x1e, 0x66, 0xcd, 0x56, 0xc3, + 0x74, 0x48, 0xa0, 0xfe, 0x88, 0xad, 0x77, 0xac, 0x6e, 0xa4, 0xff, 0xa3, 0xb6, 0x6f, 0xd6, 0xdf, + 0xcd, 0xfe, 0x99, 0x2a, 0xfe, 0x2d, 0x6a, 0x4c, 0x88, 0x6f, 0x76, 0x5f, 0xf9, 0x77, 0x00, 0x00, + 0x00, 0xff, 0xff, 0x72, 0x99, 0x09, 0x26, 0xc8, 0x1e, 0x00, 0x00, } // Reference imports to suppress errors if they are not otherwise used. @@ -1464,6 +1832,9 @@ type MsgClient interface { SubmitConsumerDoubleVoting(ctx context.Context, in *MsgSubmitConsumerDoubleVoting, opts ...grpc.CallOption) (*MsgSubmitConsumerDoubleVotingResponse, error) ConsumerAddition(ctx context.Context, in *MsgConsumerAddition, opts ...grpc.CallOption) (*MsgConsumerAdditionResponse, error) ConsumerRemoval(ctx context.Context, in *MsgConsumerRemoval, opts ...grpc.CallOption) (*MsgConsumerRemovalResponse, error) + CreateConsumer(ctx context.Context, in *MsgCreateConsumer, opts ...grpc.CallOption) (*MsgCreateConsumerResponse, error) + UpdateConsumer(ctx context.Context, in *MsgUpdateConsumer, opts ...grpc.CallOption) (*MsgUpdateConsumerResponse, error) + RemoveConsumer(ctx context.Context, in *MsgRemoveConsumer, opts ...grpc.CallOption) (*MsgRemoveConsumerResponse, error) UpdateParams(ctx context.Context, in *MsgUpdateParams, opts ...grpc.CallOption) (*MsgUpdateParamsResponse, error) OptIn(ctx context.Context, in *MsgOptIn, opts ...grpc.CallOption) (*MsgOptInResponse, error) OptOut(ctx context.Context, in *MsgOptOut, opts ...grpc.CallOption) (*MsgOptOutResponse, error) @@ -1507,6 +1878,7 @@ func (c *msgClient) SubmitConsumerDoubleVoting(ctx context.Context, in *MsgSubmi return out, nil } +// Deprecated: Do not use. func (c *msgClient) ConsumerAddition(ctx context.Context, in *MsgConsumerAddition, opts ...grpc.CallOption) (*MsgConsumerAdditionResponse, error) { out := new(MsgConsumerAdditionResponse) err := c.cc.Invoke(ctx, "/interchain_security.ccv.provider.v1.Msg/ConsumerAddition", in, out, opts...) @@ -1516,6 +1888,7 @@ func (c *msgClient) ConsumerAddition(ctx context.Context, in *MsgConsumerAdditio return out, nil } +// Deprecated: Do not use. func (c *msgClient) ConsumerRemoval(ctx context.Context, in *MsgConsumerRemoval, opts ...grpc.CallOption) (*MsgConsumerRemovalResponse, error) { out := new(MsgConsumerRemovalResponse) err := c.cc.Invoke(ctx, "/interchain_security.ccv.provider.v1.Msg/ConsumerRemoval", in, out, opts...) @@ -1525,6 +1898,33 @@ func (c *msgClient) ConsumerRemoval(ctx context.Context, in *MsgConsumerRemoval, return out, nil } +func (c *msgClient) CreateConsumer(ctx context.Context, in *MsgCreateConsumer, opts ...grpc.CallOption) (*MsgCreateConsumerResponse, error) { + out := new(MsgCreateConsumerResponse) + err := c.cc.Invoke(ctx, "/interchain_security.ccv.provider.v1.Msg/CreateConsumer", in, out, opts...) + if err != nil { + return nil, err + } + return out, nil +} + +func (c *msgClient) UpdateConsumer(ctx context.Context, in *MsgUpdateConsumer, opts ...grpc.CallOption) (*MsgUpdateConsumerResponse, error) { + out := new(MsgUpdateConsumerResponse) + err := c.cc.Invoke(ctx, "/interchain_security.ccv.provider.v1.Msg/UpdateConsumer", in, out, opts...) + if err != nil { + return nil, err + } + return out, nil +} + +func (c *msgClient) RemoveConsumer(ctx context.Context, in *MsgRemoveConsumer, opts ...grpc.CallOption) (*MsgRemoveConsumerResponse, error) { + out := new(MsgRemoveConsumerResponse) + err := c.cc.Invoke(ctx, "/interchain_security.ccv.provider.v1.Msg/RemoveConsumer", in, out, opts...) + if err != nil { + return nil, err + } + return out, nil +} + func (c *msgClient) UpdateParams(ctx context.Context, in *MsgUpdateParams, opts ...grpc.CallOption) (*MsgUpdateParamsResponse, error) { out := new(MsgUpdateParamsResponse) err := c.cc.Invoke(ctx, "/interchain_security.ccv.provider.v1.Msg/UpdateParams", in, out, opts...) @@ -1561,6 +1961,7 @@ func (c *msgClient) SetConsumerCommissionRate(ctx context.Context, in *MsgSetCon return out, nil } +// Deprecated: Do not use. func (c *msgClient) ConsumerModification(ctx context.Context, in *MsgConsumerModification, opts ...grpc.CallOption) (*MsgConsumerModificationResponse, error) { out := new(MsgConsumerModificationResponse) err := c.cc.Invoke(ctx, "/interchain_security.ccv.provider.v1.Msg/ConsumerModification", in, out, opts...) @@ -1586,6 +1987,9 @@ type MsgServer interface { SubmitConsumerDoubleVoting(context.Context, *MsgSubmitConsumerDoubleVoting) (*MsgSubmitConsumerDoubleVotingResponse, error) ConsumerAddition(context.Context, *MsgConsumerAddition) (*MsgConsumerAdditionResponse, error) ConsumerRemoval(context.Context, *MsgConsumerRemoval) (*MsgConsumerRemovalResponse, error) + CreateConsumer(context.Context, *MsgCreateConsumer) (*MsgCreateConsumerResponse, error) + UpdateConsumer(context.Context, *MsgUpdateConsumer) (*MsgUpdateConsumerResponse, error) + RemoveConsumer(context.Context, *MsgRemoveConsumer) (*MsgRemoveConsumerResponse, error) UpdateParams(context.Context, *MsgUpdateParams) (*MsgUpdateParamsResponse, error) OptIn(context.Context, *MsgOptIn) (*MsgOptInResponse, error) OptOut(context.Context, *MsgOptOut) (*MsgOptOutResponse, error) @@ -1613,6 +2017,15 @@ func (*UnimplementedMsgServer) ConsumerAddition(ctx context.Context, req *MsgCon func (*UnimplementedMsgServer) ConsumerRemoval(ctx context.Context, req *MsgConsumerRemoval) (*MsgConsumerRemovalResponse, error) { return nil, status.Errorf(codes.Unimplemented, "method ConsumerRemoval not implemented") } +func (*UnimplementedMsgServer) CreateConsumer(ctx context.Context, req *MsgCreateConsumer) (*MsgCreateConsumerResponse, error) { + return nil, status.Errorf(codes.Unimplemented, "method CreateConsumer not implemented") +} +func (*UnimplementedMsgServer) UpdateConsumer(ctx context.Context, req *MsgUpdateConsumer) (*MsgUpdateConsumerResponse, error) { + return nil, status.Errorf(codes.Unimplemented, "method UpdateConsumer not implemented") +} +func (*UnimplementedMsgServer) RemoveConsumer(ctx context.Context, req *MsgRemoveConsumer) (*MsgRemoveConsumerResponse, error) { + return nil, status.Errorf(codes.Unimplemented, "method RemoveConsumer not implemented") +} func (*UnimplementedMsgServer) UpdateParams(ctx context.Context, req *MsgUpdateParams) (*MsgUpdateParamsResponse, error) { return nil, status.Errorf(codes.Unimplemented, "method UpdateParams not implemented") } @@ -1726,43 +2139,97 @@ func _Msg_ConsumerRemoval_Handler(srv interface{}, ctx context.Context, dec func return interceptor(ctx, in, info, handler) } -func _Msg_UpdateParams_Handler(srv interface{}, ctx context.Context, dec func(interface{}) error, interceptor grpc.UnaryServerInterceptor) (interface{}, error) { - in := new(MsgUpdateParams) +func _Msg_CreateConsumer_Handler(srv interface{}, ctx context.Context, dec func(interface{}) error, interceptor grpc.UnaryServerInterceptor) (interface{}, error) { + in := new(MsgCreateConsumer) if err := dec(in); err != nil { return nil, err } if interceptor == nil { - return srv.(MsgServer).UpdateParams(ctx, in) + return srv.(MsgServer).CreateConsumer(ctx, in) } info := &grpc.UnaryServerInfo{ Server: srv, - FullMethod: "/interchain_security.ccv.provider.v1.Msg/UpdateParams", + FullMethod: "/interchain_security.ccv.provider.v1.Msg/CreateConsumer", } handler := func(ctx context.Context, req interface{}) (interface{}, error) { - return srv.(MsgServer).UpdateParams(ctx, req.(*MsgUpdateParams)) + return srv.(MsgServer).CreateConsumer(ctx, req.(*MsgCreateConsumer)) } return interceptor(ctx, in, info, handler) } -func _Msg_OptIn_Handler(srv interface{}, ctx context.Context, dec func(interface{}) error, interceptor grpc.UnaryServerInterceptor) (interface{}, error) { - in := new(MsgOptIn) +func _Msg_UpdateConsumer_Handler(srv interface{}, ctx context.Context, dec func(interface{}) error, interceptor grpc.UnaryServerInterceptor) (interface{}, error) { + in := new(MsgUpdateConsumer) if err := dec(in); err != nil { return nil, err } if interceptor == nil { - return srv.(MsgServer).OptIn(ctx, in) + return srv.(MsgServer).UpdateConsumer(ctx, in) } info := &grpc.UnaryServerInfo{ Server: srv, - FullMethod: "/interchain_security.ccv.provider.v1.Msg/OptIn", + FullMethod: "/interchain_security.ccv.provider.v1.Msg/UpdateConsumer", } handler := func(ctx context.Context, req interface{}) (interface{}, error) { - return srv.(MsgServer).OptIn(ctx, req.(*MsgOptIn)) + return srv.(MsgServer).UpdateConsumer(ctx, req.(*MsgUpdateConsumer)) } return interceptor(ctx, in, info, handler) } -func _Msg_OptOut_Handler(srv interface{}, ctx context.Context, dec func(interface{}) error, interceptor grpc.UnaryServerInterceptor) (interface{}, error) { +func _Msg_RemoveConsumer_Handler(srv interface{}, ctx context.Context, dec func(interface{}) error, interceptor grpc.UnaryServerInterceptor) (interface{}, error) { + in := new(MsgRemoveConsumer) + if err := dec(in); err != nil { + return nil, err + } + if interceptor == nil { + return srv.(MsgServer).RemoveConsumer(ctx, in) + } + info := &grpc.UnaryServerInfo{ + Server: srv, + FullMethod: "/interchain_security.ccv.provider.v1.Msg/RemoveConsumer", + } + handler := func(ctx context.Context, req interface{}) (interface{}, error) { + return srv.(MsgServer).RemoveConsumer(ctx, req.(*MsgRemoveConsumer)) + } + return interceptor(ctx, in, info, handler) +} + +func _Msg_UpdateParams_Handler(srv interface{}, ctx context.Context, dec func(interface{}) error, interceptor grpc.UnaryServerInterceptor) (interface{}, error) { + in := new(MsgUpdateParams) + if err := dec(in); err != nil { + return nil, err + } + if interceptor == nil { + return srv.(MsgServer).UpdateParams(ctx, in) + } + info := &grpc.UnaryServerInfo{ + Server: srv, + FullMethod: "/interchain_security.ccv.provider.v1.Msg/UpdateParams", + } + handler := func(ctx context.Context, req interface{}) (interface{}, error) { + return srv.(MsgServer).UpdateParams(ctx, req.(*MsgUpdateParams)) + } + return interceptor(ctx, in, info, handler) +} + +func _Msg_OptIn_Handler(srv interface{}, ctx context.Context, dec func(interface{}) error, interceptor grpc.UnaryServerInterceptor) (interface{}, error) { + in := new(MsgOptIn) + if err := dec(in); err != nil { + return nil, err + } + if interceptor == nil { + return srv.(MsgServer).OptIn(ctx, in) + } + info := &grpc.UnaryServerInfo{ + Server: srv, + FullMethod: "/interchain_security.ccv.provider.v1.Msg/OptIn", + } + handler := func(ctx context.Context, req interface{}) (interface{}, error) { + return srv.(MsgServer).OptIn(ctx, req.(*MsgOptIn)) + } + return interceptor(ctx, in, info, handler) +} + +func _Msg_OptOut_Handler(srv interface{}, ctx context.Context, dec func(interface{}) error, interceptor grpc.UnaryServerInterceptor) (interface{}, error) { in := new(MsgOptOut) if err := dec(in); err != nil { return nil, err @@ -1858,6 +2325,18 @@ var _Msg_serviceDesc = grpc.ServiceDesc{ MethodName: "ConsumerRemoval", Handler: _Msg_ConsumerRemoval_Handler, }, + { + MethodName: "CreateConsumer", + Handler: _Msg_CreateConsumer_Handler, + }, + { + MethodName: "UpdateConsumer", + Handler: _Msg_UpdateConsumer_Handler, + }, + { + MethodName: "RemoveConsumer", + Handler: _Msg_RemoveConsumer_Handler, + }, { MethodName: "UpdateParams", Handler: _Msg_UpdateParams_Handler, @@ -1907,10 +2386,17 @@ func (m *MsgAssignConsumerKey) MarshalToSizedBuffer(dAtA []byte) (int, error) { _ = i var l int _ = l - if len(m.Signer) > 0 { - i -= len(m.Signer) - copy(dAtA[i:], m.Signer) - i = encodeVarintTx(dAtA, i, uint64(len(m.Signer))) + if len(m.ConsumerId) > 0 { + i -= len(m.ConsumerId) + copy(dAtA[i:], m.ConsumerId) + i = encodeVarintTx(dAtA, i, uint64(len(m.ConsumerId))) + i-- + dAtA[i] = 0x2a + } + if len(m.Submitter) > 0 { + i -= len(m.Submitter) + copy(dAtA[i:], m.Submitter) + i = encodeVarintTx(dAtA, i, uint64(len(m.Submitter))) i-- dAtA[i] = 0x22 } @@ -1981,6 +2467,13 @@ func (m *MsgSubmitConsumerMisbehaviour) MarshalToSizedBuffer(dAtA []byte) (int, _ = i var l int _ = l + if len(m.ConsumerId) > 0 { + i -= len(m.ConsumerId) + copy(dAtA[i:], m.ConsumerId) + i = encodeVarintTx(dAtA, i, uint64(len(m.ConsumerId))) + i-- + dAtA[i] = 0x1a + } if m.Misbehaviour != nil { { size, err := m.Misbehaviour.MarshalToSizedBuffer(dAtA[:i]) @@ -2046,6 +2539,13 @@ func (m *MsgSubmitConsumerDoubleVoting) MarshalToSizedBuffer(dAtA []byte) (int, _ = i var l int _ = l + if len(m.ConsumerId) > 0 { + i -= len(m.ConsumerId) + copy(dAtA[i:], m.ConsumerId) + i = encodeVarintTx(dAtA, i, uint64(len(m.ConsumerId))) + i-- + dAtA[i] = 0x22 + } if m.InfractionBlockHeader != nil { { size, err := m.InfractionBlockHeader.MarshalToSizedBuffer(dAtA[:i]) @@ -2432,6 +2932,66 @@ func (m *MsgConsumerRemovalResponse) MarshalToSizedBuffer(dAtA []byte) (int, err return len(dAtA) - i, nil } +func (m *MsgRemoveConsumer) 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 *MsgRemoveConsumer) MarshalTo(dAtA []byte) (int, error) { + size := m.Size() + return m.MarshalToSizedBuffer(dAtA[:size]) +} + +func (m *MsgRemoveConsumer) MarshalToSizedBuffer(dAtA []byte) (int, error) { + i := len(dAtA) + _ = i + var l int + _ = l + if len(m.Owner) > 0 { + i -= len(m.Owner) + copy(dAtA[i:], m.Owner) + i = encodeVarintTx(dAtA, i, uint64(len(m.Owner))) + i-- + dAtA[i] = 0x12 + } + if len(m.ConsumerId) > 0 { + i -= len(m.ConsumerId) + copy(dAtA[i:], m.ConsumerId) + i = encodeVarintTx(dAtA, i, uint64(len(m.ConsumerId))) + i-- + dAtA[i] = 0xa + } + return len(dAtA) - i, nil +} + +func (m *MsgRemoveConsumerResponse) 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 *MsgRemoveConsumerResponse) MarshalTo(dAtA []byte) (int, error) { + size := m.Size() + return m.MarshalToSizedBuffer(dAtA[:size]) +} + +func (m *MsgRemoveConsumerResponse) MarshalToSizedBuffer(dAtA []byte) (int, error) { + i := len(dAtA) + _ = i + var l int + _ = l + return len(dAtA) - i, nil +} + func (m *MsgChangeRewardDenoms) Marshal() (dAtA []byte, err error) { size := m.Size() dAtA = make([]byte, size) @@ -2523,10 +3083,17 @@ func (m *MsgOptIn) MarshalToSizedBuffer(dAtA []byte) (int, error) { _ = i var l int _ = l - if len(m.Signer) > 0 { - i -= len(m.Signer) - copy(dAtA[i:], m.Signer) - i = encodeVarintTx(dAtA, i, uint64(len(m.Signer))) + if len(m.ConsumerId) > 0 { + i -= len(m.ConsumerId) + copy(dAtA[i:], m.ConsumerId) + i = encodeVarintTx(dAtA, i, uint64(len(m.ConsumerId))) + i-- + dAtA[i] = 0x2a + } + if len(m.Submitter) > 0 { + i -= len(m.Submitter) + copy(dAtA[i:], m.Submitter) + i = encodeVarintTx(dAtA, i, uint64(len(m.Submitter))) i-- dAtA[i] = 0x22 } @@ -2597,10 +3164,17 @@ func (m *MsgOptOut) MarshalToSizedBuffer(dAtA []byte) (int, error) { _ = i var l int _ = l - if len(m.Signer) > 0 { - i -= len(m.Signer) - copy(dAtA[i:], m.Signer) - i = encodeVarintTx(dAtA, i, uint64(len(m.Signer))) + if len(m.ConsumerId) > 0 { + i -= len(m.ConsumerId) + copy(dAtA[i:], m.ConsumerId) + i = encodeVarintTx(dAtA, i, uint64(len(m.ConsumerId))) + i-- + dAtA[i] = 0x22 + } + if len(m.Submitter) > 0 { + i -= len(m.Submitter) + copy(dAtA[i:], m.Submitter) + i = encodeVarintTx(dAtA, i, uint64(len(m.Submitter))) i-- dAtA[i] = 0x1a } @@ -2664,10 +3238,17 @@ func (m *MsgSetConsumerCommissionRate) MarshalToSizedBuffer(dAtA []byte) (int, e _ = i var l int _ = l - if len(m.Signer) > 0 { - i -= len(m.Signer) - copy(dAtA[i:], m.Signer) - i = encodeVarintTx(dAtA, i, uint64(len(m.Signer))) + if len(m.ConsumerId) > 0 { + i -= len(m.ConsumerId) + copy(dAtA[i:], m.ConsumerId) + i = encodeVarintTx(dAtA, i, uint64(len(m.ConsumerId))) + i-- + dAtA[i] = 0x2a + } + if len(m.Submitter) > 0 { + i -= len(m.Submitter) + copy(dAtA[i:], m.Submitter) + i = encodeVarintTx(dAtA, i, uint64(len(m.Submitter))) i-- dAtA[i] = 0x22 } @@ -2843,78 +3424,290 @@ func (m *MsgConsumerModificationResponse) MarshalToSizedBuffer(dAtA []byte) (int return len(dAtA) - i, nil } -func encodeVarintTx(dAtA []byte, offset int, v uint64) int { - offset -= sovTx(v) - base := offset - for v >= 1<<7 { - dAtA[offset] = uint8(v&0x7f | 0x80) - v >>= 7 - offset++ +func (m *MsgCreateConsumer) Marshal() (dAtA []byte, err error) { + size := m.Size() + dAtA = make([]byte, size) + n, err := m.MarshalToSizedBuffer(dAtA[:size]) + if err != nil { + return nil, err } - dAtA[offset] = uint8(v) - return base + return dAtA[:n], nil } -func (m *MsgAssignConsumerKey) Size() (n int) { - if m == nil { - return 0 - } + +func (m *MsgCreateConsumer) MarshalTo(dAtA []byte) (int, error) { + size := m.Size() + return m.MarshalToSizedBuffer(dAtA[:size]) +} + +func (m *MsgCreateConsumer) MarshalToSizedBuffer(dAtA []byte) (int, error) { + i := len(dAtA) + _ = i var l int _ = l - l = len(m.ChainId) - if l > 0 { - n += 1 + l + sovTx(uint64(l)) + if m.PowerShapingParameters != nil { + { + size, err := m.PowerShapingParameters.MarshalToSizedBuffer(dAtA[:i]) + if err != nil { + return 0, err + } + i -= size + i = encodeVarintTx(dAtA, i, uint64(size)) + } + i-- + dAtA[i] = 0x2a } - l = len(m.ProviderAddr) - if l > 0 { - n += 1 + l + sovTx(uint64(l)) + if m.InitializationParameters != nil { + { + size, err := m.InitializationParameters.MarshalToSizedBuffer(dAtA[:i]) + if err != nil { + return 0, err + } + i -= size + i = encodeVarintTx(dAtA, i, uint64(size)) + } + i-- + dAtA[i] = 0x22 } - l = len(m.ConsumerKey) - if l > 0 { - n += 1 + l + sovTx(uint64(l)) + { + size, err := m.Metadata.MarshalToSizedBuffer(dAtA[:i]) + if err != nil { + return 0, err + } + i -= size + i = encodeVarintTx(dAtA, i, uint64(size)) } - l = len(m.Signer) - if l > 0 { - n += 1 + l + sovTx(uint64(l)) + i-- + dAtA[i] = 0x1a + if len(m.ChainId) > 0 { + i -= len(m.ChainId) + copy(dAtA[i:], m.ChainId) + i = encodeVarintTx(dAtA, i, uint64(len(m.ChainId))) + i-- + dAtA[i] = 0x12 } - return n + if len(m.Submitter) > 0 { + i -= len(m.Submitter) + copy(dAtA[i:], m.Submitter) + i = encodeVarintTx(dAtA, i, uint64(len(m.Submitter))) + i-- + dAtA[i] = 0xa + } + return len(dAtA) - i, nil } -func (m *MsgAssignConsumerKeyResponse) Size() (n int) { - if m == nil { - return 0 +func (m *MsgCreateConsumerResponse) Marshal() (dAtA []byte, err error) { + size := m.Size() + dAtA = make([]byte, size) + n, err := m.MarshalToSizedBuffer(dAtA[:size]) + if err != nil { + return nil, err } - var l int - _ = l - return n + return dAtA[:n], nil } -func (m *MsgSubmitConsumerMisbehaviour) Size() (n int) { - if m == nil { - return 0 - } +func (m *MsgCreateConsumerResponse) MarshalTo(dAtA []byte) (int, error) { + size := m.Size() + return m.MarshalToSizedBuffer(dAtA[:size]) +} + +func (m *MsgCreateConsumerResponse) MarshalToSizedBuffer(dAtA []byte) (int, error) { + i := len(dAtA) + _ = i var l int _ = l - l = len(m.Submitter) - if l > 0 { - n += 1 + l + sovTx(uint64(l)) - } - if m.Misbehaviour != nil { - l = m.Misbehaviour.Size() - n += 1 + l + sovTx(uint64(l)) + if len(m.ConsumerId) > 0 { + i -= len(m.ConsumerId) + copy(dAtA[i:], m.ConsumerId) + i = encodeVarintTx(dAtA, i, uint64(len(m.ConsumerId))) + i-- + dAtA[i] = 0xa } - return n + return len(dAtA) - i, nil } -func (m *MsgSubmitConsumerMisbehaviourResponse) Size() (n int) { - if m == nil { - return 0 +func (m *MsgUpdateConsumer) Marshal() (dAtA []byte, err error) { + size := m.Size() + dAtA = make([]byte, size) + n, err := m.MarshalToSizedBuffer(dAtA[:size]) + if err != nil { + return nil, err } - var l int - _ = l - return n + return dAtA[:n], nil } -func (m *MsgSubmitConsumerDoubleVoting) Size() (n int) { +func (m *MsgUpdateConsumer) MarshalTo(dAtA []byte) (int, error) { + size := m.Size() + return m.MarshalToSizedBuffer(dAtA[:size]) +} + +func (m *MsgUpdateConsumer) MarshalToSizedBuffer(dAtA []byte) (int, error) { + i := len(dAtA) + _ = i + var l int + _ = l + if m.PowerShapingParameters != nil { + { + size, err := m.PowerShapingParameters.MarshalToSizedBuffer(dAtA[:i]) + if err != nil { + return 0, err + } + i -= size + i = encodeVarintTx(dAtA, i, uint64(size)) + } + i-- + dAtA[i] = 0x32 + } + if m.InitializationParameters != nil { + { + size, err := m.InitializationParameters.MarshalToSizedBuffer(dAtA[:i]) + if err != nil { + return 0, err + } + i -= size + i = encodeVarintTx(dAtA, i, uint64(size)) + } + i-- + dAtA[i] = 0x2a + } + if m.Metadata != nil { + { + size, err := m.Metadata.MarshalToSizedBuffer(dAtA[:i]) + if err != nil { + return 0, err + } + i -= size + i = encodeVarintTx(dAtA, i, uint64(size)) + } + i-- + dAtA[i] = 0x22 + } + if len(m.NewOwnerAddress) > 0 { + i -= len(m.NewOwnerAddress) + copy(dAtA[i:], m.NewOwnerAddress) + i = encodeVarintTx(dAtA, i, uint64(len(m.NewOwnerAddress))) + i-- + dAtA[i] = 0x1a + } + if len(m.ConsumerId) > 0 { + i -= len(m.ConsumerId) + copy(dAtA[i:], m.ConsumerId) + i = encodeVarintTx(dAtA, i, uint64(len(m.ConsumerId))) + i-- + dAtA[i] = 0x12 + } + if len(m.Owner) > 0 { + i -= len(m.Owner) + copy(dAtA[i:], m.Owner) + i = encodeVarintTx(dAtA, i, uint64(len(m.Owner))) + i-- + dAtA[i] = 0xa + } + return len(dAtA) - i, nil +} + +func (m *MsgUpdateConsumerResponse) 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 *MsgUpdateConsumerResponse) MarshalTo(dAtA []byte) (int, error) { + size := m.Size() + return m.MarshalToSizedBuffer(dAtA[:size]) +} + +func (m *MsgUpdateConsumerResponse) MarshalToSizedBuffer(dAtA []byte) (int, error) { + i := len(dAtA) + _ = i + var l int + _ = l + return len(dAtA) - i, nil +} + +func encodeVarintTx(dAtA []byte, offset int, v uint64) int { + offset -= sovTx(v) + base := offset + for v >= 1<<7 { + dAtA[offset] = uint8(v&0x7f | 0x80) + v >>= 7 + offset++ + } + dAtA[offset] = uint8(v) + return base +} +func (m *MsgAssignConsumerKey) Size() (n int) { + if m == nil { + return 0 + } + var l int + _ = l + l = len(m.ChainId) + if l > 0 { + n += 1 + l + sovTx(uint64(l)) + } + l = len(m.ProviderAddr) + if l > 0 { + n += 1 + l + sovTx(uint64(l)) + } + l = len(m.ConsumerKey) + if l > 0 { + n += 1 + l + sovTx(uint64(l)) + } + l = len(m.Submitter) + if l > 0 { + n += 1 + l + sovTx(uint64(l)) + } + l = len(m.ConsumerId) + if l > 0 { + n += 1 + l + sovTx(uint64(l)) + } + return n +} + +func (m *MsgAssignConsumerKeyResponse) Size() (n int) { + if m == nil { + return 0 + } + var l int + _ = l + return n +} + +func (m *MsgSubmitConsumerMisbehaviour) Size() (n int) { + if m == nil { + return 0 + } + var l int + _ = l + l = len(m.Submitter) + if l > 0 { + n += 1 + l + sovTx(uint64(l)) + } + if m.Misbehaviour != nil { + l = m.Misbehaviour.Size() + n += 1 + l + sovTx(uint64(l)) + } + l = len(m.ConsumerId) + if l > 0 { + n += 1 + l + sovTx(uint64(l)) + } + return n +} + +func (m *MsgSubmitConsumerMisbehaviourResponse) Size() (n int) { + if m == nil { + return 0 + } + var l int + _ = l + return n +} + +func (m *MsgSubmitConsumerDoubleVoting) Size() (n int) { if m == nil { return 0 } @@ -2932,6 +3725,10 @@ func (m *MsgSubmitConsumerDoubleVoting) Size() (n int) { l = m.InfractionBlockHeader.Size() n += 1 + l + sovTx(uint64(l)) } + l = len(m.ConsumerId) + if l > 0 { + n += 1 + l + sovTx(uint64(l)) + } return n } @@ -3081,6 +3878,32 @@ func (m *MsgConsumerRemovalResponse) Size() (n int) { return n } +func (m *MsgRemoveConsumer) Size() (n int) { + if m == nil { + return 0 + } + var l int + _ = l + l = len(m.ConsumerId) + if l > 0 { + n += 1 + l + sovTx(uint64(l)) + } + l = len(m.Owner) + if l > 0 { + n += 1 + l + sovTx(uint64(l)) + } + return n +} + +func (m *MsgRemoveConsumerResponse) Size() (n int) { + if m == nil { + return 0 + } + var l int + _ = l + return n +} + func (m *MsgChangeRewardDenoms) Size() (n int) { if m == nil { return 0 @@ -3133,7 +3956,11 @@ func (m *MsgOptIn) Size() (n int) { if l > 0 { n += 1 + l + sovTx(uint64(l)) } - l = len(m.Signer) + l = len(m.Submitter) + if l > 0 { + n += 1 + l + sovTx(uint64(l)) + } + l = len(m.ConsumerId) if l > 0 { n += 1 + l + sovTx(uint64(l)) } @@ -3163,7 +3990,11 @@ func (m *MsgOptOut) Size() (n int) { if l > 0 { n += 1 + l + sovTx(uint64(l)) } - l = len(m.Signer) + l = len(m.Submitter) + if l > 0 { + n += 1 + l + sovTx(uint64(l)) + } + l = len(m.ConsumerId) if l > 0 { n += 1 + l + sovTx(uint64(l)) } @@ -3195,7 +4026,11 @@ func (m *MsgSetConsumerCommissionRate) Size() (n int) { } l = m.Rate.Size() n += 1 + l + sovTx(uint64(l)) - l = len(m.Signer) + l = len(m.Submitter) + if l > 0 { + n += 1 + l + sovTx(uint64(l)) + } + l = len(m.ConsumerId) if l > 0 { n += 1 + l + sovTx(uint64(l)) } @@ -3272,6 +4107,88 @@ func (m *MsgConsumerModificationResponse) Size() (n int) { return n } +func (m *MsgCreateConsumer) Size() (n int) { + if m == nil { + return 0 + } + var l int + _ = l + l = len(m.Submitter) + if l > 0 { + n += 1 + l + sovTx(uint64(l)) + } + l = len(m.ChainId) + if l > 0 { + n += 1 + l + sovTx(uint64(l)) + } + l = m.Metadata.Size() + n += 1 + l + sovTx(uint64(l)) + if m.InitializationParameters != nil { + l = m.InitializationParameters.Size() + n += 1 + l + sovTx(uint64(l)) + } + if m.PowerShapingParameters != nil { + l = m.PowerShapingParameters.Size() + n += 1 + l + sovTx(uint64(l)) + } + return n +} + +func (m *MsgCreateConsumerResponse) Size() (n int) { + if m == nil { + return 0 + } + var l int + _ = l + l = len(m.ConsumerId) + if l > 0 { + n += 1 + l + sovTx(uint64(l)) + } + return n +} + +func (m *MsgUpdateConsumer) Size() (n int) { + if m == nil { + return 0 + } + var l int + _ = l + l = len(m.Owner) + if l > 0 { + n += 1 + l + sovTx(uint64(l)) + } + l = len(m.ConsumerId) + if l > 0 { + n += 1 + l + sovTx(uint64(l)) + } + l = len(m.NewOwnerAddress) + if l > 0 { + n += 1 + l + sovTx(uint64(l)) + } + if m.Metadata != nil { + l = m.Metadata.Size() + n += 1 + l + sovTx(uint64(l)) + } + if m.InitializationParameters != nil { + l = m.InitializationParameters.Size() + n += 1 + l + sovTx(uint64(l)) + } + if m.PowerShapingParameters != nil { + l = m.PowerShapingParameters.Size() + n += 1 + l + sovTx(uint64(l)) + } + return n +} + +func (m *MsgUpdateConsumerResponse) Size() (n int) { + if m == nil { + return 0 + } + var l int + _ = l + return n +} + func sovTx(x uint64) (n int) { return (math_bits.Len64(x|1) + 6) / 7 } @@ -3405,7 +4322,7 @@ func (m *MsgAssignConsumerKey) Unmarshal(dAtA []byte) error { iNdEx = postIndex case 4: if wireType != 2 { - return fmt.Errorf("proto: wrong wireType = %d for field Signer", wireType) + return fmt.Errorf("proto: wrong wireType = %d for field Submitter", wireType) } var stringLen uint64 for shift := uint(0); ; shift += 7 { @@ -3433,15 +4350,47 @@ func (m *MsgAssignConsumerKey) Unmarshal(dAtA []byte) error { if postIndex > l { return io.ErrUnexpectedEOF } - m.Signer = string(dAtA[iNdEx:postIndex]) + m.Submitter = string(dAtA[iNdEx:postIndex]) iNdEx = postIndex - default: - iNdEx = preIndex - skippy, err := skipTx(dAtA[iNdEx:]) - if err != nil { - return err + case 5: + if wireType != 2 { + return fmt.Errorf("proto: wrong wireType = %d for field ConsumerId", wireType) } - if (skippy < 0) || (iNdEx+skippy) < 0 { + 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.ConsumerId = string(dAtA[iNdEx:postIndex]) + iNdEx = postIndex + 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 { @@ -3603,6 +4552,38 @@ func (m *MsgSubmitConsumerMisbehaviour) Unmarshal(dAtA []byte) error { return err } iNdEx = postIndex + case 3: + if wireType != 2 { + return fmt.Errorf("proto: wrong wireType = %d for field ConsumerId", 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.ConsumerId = string(dAtA[iNdEx:postIndex]) + iNdEx = postIndex default: iNdEx = preIndex skippy, err := skipTx(dAtA[iNdEx:]) @@ -3807,6 +4788,38 @@ func (m *MsgSubmitConsumerDoubleVoting) Unmarshal(dAtA []byte) error { return err } iNdEx = postIndex + case 4: + if wireType != 2 { + return fmt.Errorf("proto: wrong wireType = %d for field ConsumerId", 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.ConsumerId = string(dAtA[iNdEx:postIndex]) + iNdEx = postIndex default: iNdEx = preIndex skippy, err := skipTx(dAtA[iNdEx:]) @@ -4899,7 +5912,7 @@ func (m *MsgConsumerRemovalResponse) Unmarshal(dAtA []byte) error { } return nil } -func (m *MsgChangeRewardDenoms) Unmarshal(dAtA []byte) error { +func (m *MsgRemoveConsumer) Unmarshal(dAtA []byte) error { l := len(dAtA) iNdEx := 0 for iNdEx < l { @@ -4922,15 +5935,15 @@ func (m *MsgChangeRewardDenoms) Unmarshal(dAtA []byte) error { fieldNum := int32(wire >> 3) wireType := int(wire & 0x7) if wireType == 4 { - return fmt.Errorf("proto: MsgChangeRewardDenoms: wiretype end group for non-group") + return fmt.Errorf("proto: MsgRemoveConsumer: wiretype end group for non-group") } if fieldNum <= 0 { - return fmt.Errorf("proto: MsgChangeRewardDenoms: illegal tag %d (wire type %d)", fieldNum, wire) + return fmt.Errorf("proto: MsgRemoveConsumer: illegal tag %d (wire type %d)", fieldNum, wire) } switch fieldNum { case 1: if wireType != 2 { - return fmt.Errorf("proto: wrong wireType = %d for field DenomsToAdd", wireType) + return fmt.Errorf("proto: wrong wireType = %d for field ConsumerId", wireType) } var stringLen uint64 for shift := uint(0); ; shift += 7 { @@ -4958,43 +5971,11 @@ func (m *MsgChangeRewardDenoms) Unmarshal(dAtA []byte) error { if postIndex > l { return io.ErrUnexpectedEOF } - m.DenomsToAdd = append(m.DenomsToAdd, string(dAtA[iNdEx:postIndex])) + m.ConsumerId = string(dAtA[iNdEx:postIndex]) iNdEx = postIndex case 2: if wireType != 2 { - return fmt.Errorf("proto: wrong wireType = %d for field DenomsToRemove", 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.DenomsToRemove = append(m.DenomsToRemove, string(dAtA[iNdEx:postIndex])) - iNdEx = postIndex - case 3: - if wireType != 2 { - return fmt.Errorf("proto: wrong wireType = %d for field Authority", wireType) + return fmt.Errorf("proto: wrong wireType = %d for field Owner", wireType) } var stringLen uint64 for shift := uint(0); ; shift += 7 { @@ -5022,7 +6003,7 @@ func (m *MsgChangeRewardDenoms) Unmarshal(dAtA []byte) error { if postIndex > l { return io.ErrUnexpectedEOF } - m.Authority = string(dAtA[iNdEx:postIndex]) + m.Owner = string(dAtA[iNdEx:postIndex]) iNdEx = postIndex default: iNdEx = preIndex @@ -5045,7 +6026,7 @@ func (m *MsgChangeRewardDenoms) Unmarshal(dAtA []byte) error { } return nil } -func (m *MsgChangeRewardDenomsResponse) Unmarshal(dAtA []byte) error { +func (m *MsgRemoveConsumerResponse) Unmarshal(dAtA []byte) error { l := len(dAtA) iNdEx := 0 for iNdEx < l { @@ -5068,10 +6049,10 @@ func (m *MsgChangeRewardDenomsResponse) Unmarshal(dAtA []byte) error { fieldNum := int32(wire >> 3) wireType := int(wire & 0x7) if wireType == 4 { - return fmt.Errorf("proto: MsgChangeRewardDenomsResponse: wiretype end group for non-group") + return fmt.Errorf("proto: MsgRemoveConsumerResponse: wiretype end group for non-group") } if fieldNum <= 0 { - return fmt.Errorf("proto: MsgChangeRewardDenomsResponse: illegal tag %d (wire type %d)", fieldNum, wire) + return fmt.Errorf("proto: MsgRemoveConsumerResponse: illegal tag %d (wire type %d)", fieldNum, wire) } switch fieldNum { default: @@ -5095,7 +6076,7 @@ func (m *MsgChangeRewardDenomsResponse) Unmarshal(dAtA []byte) error { } return nil } -func (m *MsgOptIn) Unmarshal(dAtA []byte) error { +func (m *MsgChangeRewardDenoms) Unmarshal(dAtA []byte) error { l := len(dAtA) iNdEx := 0 for iNdEx < l { @@ -5118,15 +6099,15 @@ func (m *MsgOptIn) Unmarshal(dAtA []byte) error { fieldNum := int32(wire >> 3) wireType := int(wire & 0x7) if wireType == 4 { - return fmt.Errorf("proto: MsgOptIn: wiretype end group for non-group") + return fmt.Errorf("proto: MsgChangeRewardDenoms: wiretype end group for non-group") } if fieldNum <= 0 { - return fmt.Errorf("proto: MsgOptIn: illegal tag %d (wire type %d)", fieldNum, wire) + return fmt.Errorf("proto: MsgChangeRewardDenoms: illegal tag %d (wire type %d)", fieldNum, wire) } switch fieldNum { case 1: if wireType != 2 { - return fmt.Errorf("proto: wrong wireType = %d for field ChainId", wireType) + return fmt.Errorf("proto: wrong wireType = %d for field DenomsToAdd", wireType) } var stringLen uint64 for shift := uint(0); ; shift += 7 { @@ -5154,11 +6135,11 @@ func (m *MsgOptIn) Unmarshal(dAtA []byte) error { if postIndex > l { return io.ErrUnexpectedEOF } - m.ChainId = string(dAtA[iNdEx:postIndex]) + m.DenomsToAdd = append(m.DenomsToAdd, string(dAtA[iNdEx:postIndex])) iNdEx = postIndex case 2: if wireType != 2 { - return fmt.Errorf("proto: wrong wireType = %d for field ProviderAddr", wireType) + return fmt.Errorf("proto: wrong wireType = %d for field DenomsToRemove", wireType) } var stringLen uint64 for shift := uint(0); ; shift += 7 { @@ -5186,43 +6167,11 @@ func (m *MsgOptIn) Unmarshal(dAtA []byte) error { if postIndex > l { return io.ErrUnexpectedEOF } - m.ProviderAddr = string(dAtA[iNdEx:postIndex]) + m.DenomsToRemove = append(m.DenomsToRemove, string(dAtA[iNdEx:postIndex])) iNdEx = postIndex case 3: if wireType != 2 { - return fmt.Errorf("proto: wrong wireType = %d for field ConsumerKey", 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.ConsumerKey = string(dAtA[iNdEx:postIndex]) - iNdEx = postIndex - case 4: - if wireType != 2 { - return fmt.Errorf("proto: wrong wireType = %d for field Signer", wireType) + return fmt.Errorf("proto: wrong wireType = %d for field Authority", wireType) } var stringLen uint64 for shift := uint(0); ; shift += 7 { @@ -5250,7 +6199,7 @@ func (m *MsgOptIn) Unmarshal(dAtA []byte) error { if postIndex > l { return io.ErrUnexpectedEOF } - m.Signer = string(dAtA[iNdEx:postIndex]) + m.Authority = string(dAtA[iNdEx:postIndex]) iNdEx = postIndex default: iNdEx = preIndex @@ -5273,7 +6222,7 @@ func (m *MsgOptIn) Unmarshal(dAtA []byte) error { } return nil } -func (m *MsgOptInResponse) Unmarshal(dAtA []byte) error { +func (m *MsgChangeRewardDenomsResponse) Unmarshal(dAtA []byte) error { l := len(dAtA) iNdEx := 0 for iNdEx < l { @@ -5296,10 +6245,10 @@ func (m *MsgOptInResponse) Unmarshal(dAtA []byte) error { fieldNum := int32(wire >> 3) wireType := int(wire & 0x7) if wireType == 4 { - return fmt.Errorf("proto: MsgOptInResponse: wiretype end group for non-group") + return fmt.Errorf("proto: MsgChangeRewardDenomsResponse: wiretype end group for non-group") } if fieldNum <= 0 { - return fmt.Errorf("proto: MsgOptInResponse: illegal tag %d (wire type %d)", fieldNum, wire) + return fmt.Errorf("proto: MsgChangeRewardDenomsResponse: illegal tag %d (wire type %d)", fieldNum, wire) } switch fieldNum { default: @@ -5323,7 +6272,7 @@ func (m *MsgOptInResponse) Unmarshal(dAtA []byte) error { } return nil } -func (m *MsgOptOut) Unmarshal(dAtA []byte) error { +func (m *MsgOptIn) Unmarshal(dAtA []byte) error { l := len(dAtA) iNdEx := 0 for iNdEx < l { @@ -5346,10 +6295,10 @@ func (m *MsgOptOut) Unmarshal(dAtA []byte) error { fieldNum := int32(wire >> 3) wireType := int(wire & 0x7) if wireType == 4 { - return fmt.Errorf("proto: MsgOptOut: wiretype end group for non-group") + return fmt.Errorf("proto: MsgOptIn: wiretype end group for non-group") } if fieldNum <= 0 { - return fmt.Errorf("proto: MsgOptOut: illegal tag %d (wire type %d)", fieldNum, wire) + return fmt.Errorf("proto: MsgOptIn: illegal tag %d (wire type %d)", fieldNum, wire) } switch fieldNum { case 1: @@ -5418,7 +6367,7 @@ func (m *MsgOptOut) Unmarshal(dAtA []byte) error { iNdEx = postIndex case 3: if wireType != 2 { - return fmt.Errorf("proto: wrong wireType = %d for field Signer", wireType) + return fmt.Errorf("proto: wrong wireType = %d for field ConsumerKey", wireType) } var stringLen uint64 for shift := uint(0); ; shift += 7 { @@ -5446,56 +6395,998 @@ func (m *MsgOptOut) Unmarshal(dAtA []byte) error { if postIndex > l { return io.ErrUnexpectedEOF } - m.Signer = string(dAtA[iNdEx:postIndex]) + m.ConsumerKey = string(dAtA[iNdEx:postIndex]) iNdEx = postIndex - default: - iNdEx = preIndex - skippy, err := skipTx(dAtA[iNdEx:]) - if err != nil { - return err + case 4: + if wireType != 2 { + return fmt.Errorf("proto: wrong wireType = %d for field Submitter", wireType) } - if (skippy < 0) || (iNdEx+skippy) < 0 { - return ErrInvalidLengthTx + 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 + } } - if (iNdEx + skippy) > l { - return io.ErrUnexpectedEOF + intStringLen := int(stringLen) + if intStringLen < 0 { + return ErrInvalidLengthTx } - iNdEx += skippy - } - } - - if iNdEx > l { - return io.ErrUnexpectedEOF - } - return nil -} -func (m *MsgOptOutResponse) 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 + postIndex := iNdEx + intStringLen + if postIndex < 0 { + return ErrInvalidLengthTx } - if iNdEx >= l { + if postIndex > l { return io.ErrUnexpectedEOF } - b := dAtA[iNdEx] - iNdEx++ - wire |= uint64(b&0x7F) << shift - if b < 0x80 { - break - } + m.Submitter = string(dAtA[iNdEx:postIndex]) + iNdEx = postIndex + case 5: + if wireType != 2 { + return fmt.Errorf("proto: wrong wireType = %d for field ConsumerId", 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.ConsumerId = string(dAtA[iNdEx:postIndex]) + iNdEx = postIndex + 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 *MsgOptInResponse) 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: MsgOptInResponse: wiretype end group for non-group") + } + if fieldNum <= 0 { + return fmt.Errorf("proto: MsgOptInResponse: 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 *MsgOptOut) 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: MsgOptOut: wiretype end group for non-group") + } + if fieldNum <= 0 { + return fmt.Errorf("proto: MsgOptOut: illegal tag %d (wire type %d)", fieldNum, wire) + } + switch fieldNum { + case 1: + if wireType != 2 { + return fmt.Errorf("proto: wrong wireType = %d for field ChainId", 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.ChainId = string(dAtA[iNdEx:postIndex]) + iNdEx = postIndex + case 2: + if wireType != 2 { + return fmt.Errorf("proto: wrong wireType = %d for field ProviderAddr", 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.ProviderAddr = string(dAtA[iNdEx:postIndex]) + iNdEx = postIndex + case 3: + if wireType != 2 { + return fmt.Errorf("proto: wrong wireType = %d for field Submitter", 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.Submitter = string(dAtA[iNdEx:postIndex]) + iNdEx = postIndex + case 4: + if wireType != 2 { + return fmt.Errorf("proto: wrong wireType = %d for field ConsumerId", 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.ConsumerId = string(dAtA[iNdEx:postIndex]) + iNdEx = postIndex + 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 *MsgOptOutResponse) 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: MsgOptOutResponse: wiretype end group for non-group") + } + if fieldNum <= 0 { + return fmt.Errorf("proto: MsgOptOutResponse: 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 *MsgSetConsumerCommissionRate) 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: MsgSetConsumerCommissionRate: wiretype end group for non-group") + } + if fieldNum <= 0 { + return fmt.Errorf("proto: MsgSetConsumerCommissionRate: illegal tag %d (wire type %d)", fieldNum, wire) + } + switch fieldNum { + case 1: + if wireType != 2 { + return fmt.Errorf("proto: wrong wireType = %d for field ProviderAddr", 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.ProviderAddr = string(dAtA[iNdEx:postIndex]) + iNdEx = postIndex + case 2: + if wireType != 2 { + return fmt.Errorf("proto: wrong wireType = %d for field ChainId", 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.ChainId = string(dAtA[iNdEx:postIndex]) + iNdEx = postIndex + case 3: + if wireType != 2 { + return fmt.Errorf("proto: wrong wireType = %d for field Rate", 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 + } + if err := m.Rate.Unmarshal(dAtA[iNdEx:postIndex]); err != nil { + return err + } + iNdEx = postIndex + case 4: + if wireType != 2 { + return fmt.Errorf("proto: wrong wireType = %d for field Submitter", 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.Submitter = string(dAtA[iNdEx:postIndex]) + iNdEx = postIndex + case 5: + if wireType != 2 { + return fmt.Errorf("proto: wrong wireType = %d for field ConsumerId", 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.ConsumerId = string(dAtA[iNdEx:postIndex]) + iNdEx = postIndex + 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 *MsgSetConsumerCommissionRateResponse) 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: MsgSetConsumerCommissionRateResponse: wiretype end group for non-group") + } + if fieldNum <= 0 { + return fmt.Errorf("proto: MsgSetConsumerCommissionRateResponse: 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 *MsgConsumerModification) 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: MsgConsumerModification: wiretype end group for non-group") + } + if fieldNum <= 0 { + return fmt.Errorf("proto: MsgConsumerModification: illegal tag %d (wire type %d)", fieldNum, wire) + } + switch fieldNum { + case 1: + if wireType != 2 { + return fmt.Errorf("proto: wrong wireType = %d for field Title", 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.Title = string(dAtA[iNdEx:postIndex]) + iNdEx = postIndex + case 2: + if wireType != 2 { + return fmt.Errorf("proto: wrong wireType = %d for field Description", 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.Description = string(dAtA[iNdEx:postIndex]) + iNdEx = postIndex + case 3: + if wireType != 2 { + return fmt.Errorf("proto: wrong wireType = %d for field ChainId", 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.ChainId = string(dAtA[iNdEx:postIndex]) + iNdEx = postIndex + case 4: + if wireType != 0 { + return fmt.Errorf("proto: wrong wireType = %d for field Top_N", wireType) + } + m.Top_N = 0 + for shift := uint(0); ; shift += 7 { + if shift >= 64 { + return ErrIntOverflowTx + } + if iNdEx >= l { + return io.ErrUnexpectedEOF + } + b := dAtA[iNdEx] + iNdEx++ + m.Top_N |= uint32(b&0x7F) << shift + if b < 0x80 { + break + } + } + case 5: + if wireType != 0 { + return fmt.Errorf("proto: wrong wireType = %d for field ValidatorsPowerCap", wireType) + } + m.ValidatorsPowerCap = 0 + for shift := uint(0); ; shift += 7 { + if shift >= 64 { + return ErrIntOverflowTx + } + if iNdEx >= l { + return io.ErrUnexpectedEOF + } + b := dAtA[iNdEx] + iNdEx++ + m.ValidatorsPowerCap |= uint32(b&0x7F) << shift + if b < 0x80 { + break + } + } + case 6: + if wireType != 0 { + return fmt.Errorf("proto: wrong wireType = %d for field ValidatorSetCap", wireType) + } + m.ValidatorSetCap = 0 + for shift := uint(0); ; shift += 7 { + if shift >= 64 { + return ErrIntOverflowTx + } + if iNdEx >= l { + return io.ErrUnexpectedEOF + } + b := dAtA[iNdEx] + iNdEx++ + m.ValidatorSetCap |= uint32(b&0x7F) << shift + if b < 0x80 { + break + } + } + case 7: + if wireType != 2 { + return fmt.Errorf("proto: wrong wireType = %d for field Allowlist", 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.Allowlist = append(m.Allowlist, string(dAtA[iNdEx:postIndex])) + iNdEx = postIndex + case 8: + if wireType != 2 { + return fmt.Errorf("proto: wrong wireType = %d for field Denylist", 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.Denylist = append(m.Denylist, string(dAtA[iNdEx:postIndex])) + iNdEx = postIndex + case 9: + if wireType != 2 { + return fmt.Errorf("proto: wrong wireType = %d for field Authority", 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.Authority = string(dAtA[iNdEx:postIndex]) + iNdEx = postIndex + case 10: + if wireType != 0 { + return fmt.Errorf("proto: wrong wireType = %d for field MinStake", wireType) + } + m.MinStake = 0 + for shift := uint(0); ; shift += 7 { + if shift >= 64 { + return ErrIntOverflowTx + } + if iNdEx >= l { + return io.ErrUnexpectedEOF + } + b := dAtA[iNdEx] + iNdEx++ + m.MinStake |= uint64(b&0x7F) << shift + if b < 0x80 { + break + } + } + case 11: + if wireType != 0 { + return fmt.Errorf("proto: wrong wireType = %d for field AllowInactiveVals", 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.AllowInactiveVals = bool(v != 0) + 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 *MsgConsumerModificationResponse) 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: MsgOptOutResponse: wiretype end group for non-group") + return fmt.Errorf("proto: MsgConsumerModificationResponse: wiretype end group for non-group") } if fieldNum <= 0 { - return fmt.Errorf("proto: MsgOptOutResponse: illegal tag %d (wire type %d)", fieldNum, wire) + return fmt.Errorf("proto: MsgConsumerModificationResponse: illegal tag %d (wire type %d)", fieldNum, wire) } switch fieldNum { default: @@ -5519,7 +7410,7 @@ func (m *MsgOptOutResponse) Unmarshal(dAtA []byte) error { } return nil } -func (m *MsgSetConsumerCommissionRate) Unmarshal(dAtA []byte) error { +func (m *MsgCreateConsumer) Unmarshal(dAtA []byte) error { l := len(dAtA) iNdEx := 0 for iNdEx < l { @@ -5542,15 +7433,15 @@ func (m *MsgSetConsumerCommissionRate) Unmarshal(dAtA []byte) error { fieldNum := int32(wire >> 3) wireType := int(wire & 0x7) if wireType == 4 { - return fmt.Errorf("proto: MsgSetConsumerCommissionRate: wiretype end group for non-group") + return fmt.Errorf("proto: MsgCreateConsumer: wiretype end group for non-group") } if fieldNum <= 0 { - return fmt.Errorf("proto: MsgSetConsumerCommissionRate: illegal tag %d (wire type %d)", fieldNum, wire) + return fmt.Errorf("proto: MsgCreateConsumer: illegal tag %d (wire type %d)", fieldNum, wire) } switch fieldNum { case 1: if wireType != 2 { - return fmt.Errorf("proto: wrong wireType = %d for field ProviderAddr", wireType) + return fmt.Errorf("proto: wrong wireType = %d for field Submitter", wireType) } var stringLen uint64 for shift := uint(0); ; shift += 7 { @@ -5578,7 +7469,7 @@ func (m *MsgSetConsumerCommissionRate) Unmarshal(dAtA []byte) error { if postIndex > l { return io.ErrUnexpectedEOF } - m.ProviderAddr = string(dAtA[iNdEx:postIndex]) + m.Submitter = string(dAtA[iNdEx:postIndex]) iNdEx = postIndex case 2: if wireType != 2 { @@ -5614,9 +7505,9 @@ func (m *MsgSetConsumerCommissionRate) Unmarshal(dAtA []byte) error { iNdEx = postIndex case 3: if wireType != 2 { - return fmt.Errorf("proto: wrong wireType = %d for field Rate", wireType) + return fmt.Errorf("proto: wrong wireType = %d for field Metadata", wireType) } - var stringLen uint64 + var msglen int for shift := uint(0); ; shift += 7 { if shift >= 64 { return ErrIntOverflowTx @@ -5626,31 +7517,30 @@ func (m *MsgSetConsumerCommissionRate) Unmarshal(dAtA []byte) error { } 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 ErrInvalidLengthTx } - postIndex := iNdEx + intStringLen + postIndex := iNdEx + msglen if postIndex < 0 { return ErrInvalidLengthTx } if postIndex > l { return io.ErrUnexpectedEOF } - if err := m.Rate.Unmarshal(dAtA[iNdEx:postIndex]); err != nil { + if err := m.Metadata.Unmarshal(dAtA[iNdEx:postIndex]); err != nil { return err } iNdEx = postIndex case 4: if wireType != 2 { - return fmt.Errorf("proto: wrong wireType = %d for field Signer", wireType) + return fmt.Errorf("proto: wrong wireType = %d for field InitializationParameters", wireType) } - var stringLen uint64 + var msglen int for shift := uint(0); ; shift += 7 { if shift >= 64 { return ErrIntOverflowTx @@ -5660,23 +7550,63 @@ func (m *MsgSetConsumerCommissionRate) Unmarshal(dAtA []byte) error { } 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 ErrInvalidLengthTx } - postIndex := iNdEx + intStringLen + postIndex := iNdEx + msglen + if postIndex < 0 { + return ErrInvalidLengthTx + } + if postIndex > l { + return io.ErrUnexpectedEOF + } + if m.InitializationParameters == nil { + m.InitializationParameters = &ConsumerInitializationParameters{} + } + if err := m.InitializationParameters.Unmarshal(dAtA[iNdEx:postIndex]); err != nil { + return err + } + iNdEx = postIndex + case 5: + if wireType != 2 { + return fmt.Errorf("proto: wrong wireType = %d for field PowerShapingParameters", wireType) + } + var msglen int + for shift := uint(0); ; shift += 7 { + if shift >= 64 { + return ErrIntOverflowTx + } + if iNdEx >= l { + return io.ErrUnexpectedEOF + } + b := dAtA[iNdEx] + iNdEx++ + msglen |= int(b&0x7F) << shift + if b < 0x80 { + break + } + } + if msglen < 0 { + return ErrInvalidLengthTx + } + postIndex := iNdEx + msglen if postIndex < 0 { return ErrInvalidLengthTx } if postIndex > l { return io.ErrUnexpectedEOF } - m.Signer = string(dAtA[iNdEx:postIndex]) + if m.PowerShapingParameters == nil { + m.PowerShapingParameters = &PowerShapingParameters{} + } + if err := m.PowerShapingParameters.Unmarshal(dAtA[iNdEx:postIndex]); err != nil { + return err + } iNdEx = postIndex default: iNdEx = preIndex @@ -5699,7 +7629,7 @@ func (m *MsgSetConsumerCommissionRate) Unmarshal(dAtA []byte) error { } return nil } -func (m *MsgSetConsumerCommissionRateResponse) Unmarshal(dAtA []byte) error { +func (m *MsgCreateConsumerResponse) Unmarshal(dAtA []byte) error { l := len(dAtA) iNdEx := 0 for iNdEx < l { @@ -5722,12 +7652,44 @@ func (m *MsgSetConsumerCommissionRateResponse) Unmarshal(dAtA []byte) error { fieldNum := int32(wire >> 3) wireType := int(wire & 0x7) if wireType == 4 { - return fmt.Errorf("proto: MsgSetConsumerCommissionRateResponse: wiretype end group for non-group") + return fmt.Errorf("proto: MsgCreateConsumerResponse: wiretype end group for non-group") } if fieldNum <= 0 { - return fmt.Errorf("proto: MsgSetConsumerCommissionRateResponse: illegal tag %d (wire type %d)", fieldNum, wire) + return fmt.Errorf("proto: MsgCreateConsumerResponse: illegal tag %d (wire type %d)", fieldNum, wire) } switch fieldNum { + case 1: + if wireType != 2 { + return fmt.Errorf("proto: wrong wireType = %d for field ConsumerId", 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.ConsumerId = string(dAtA[iNdEx:postIndex]) + iNdEx = postIndex default: iNdEx = preIndex skippy, err := skipTx(dAtA[iNdEx:]) @@ -5749,7 +7711,7 @@ func (m *MsgSetConsumerCommissionRateResponse) Unmarshal(dAtA []byte) error { } return nil } -func (m *MsgConsumerModification) Unmarshal(dAtA []byte) error { +func (m *MsgUpdateConsumer) Unmarshal(dAtA []byte) error { l := len(dAtA) iNdEx := 0 for iNdEx < l { @@ -5772,15 +7734,15 @@ func (m *MsgConsumerModification) Unmarshal(dAtA []byte) error { fieldNum := int32(wire >> 3) wireType := int(wire & 0x7) if wireType == 4 { - return fmt.Errorf("proto: MsgConsumerModification: wiretype end group for non-group") + return fmt.Errorf("proto: MsgUpdateConsumer: wiretype end group for non-group") } if fieldNum <= 0 { - return fmt.Errorf("proto: MsgConsumerModification: illegal tag %d (wire type %d)", fieldNum, wire) + return fmt.Errorf("proto: MsgUpdateConsumer: illegal tag %d (wire type %d)", fieldNum, wire) } switch fieldNum { case 1: if wireType != 2 { - return fmt.Errorf("proto: wrong wireType = %d for field Title", wireType) + return fmt.Errorf("proto: wrong wireType = %d for field Owner", wireType) } var stringLen uint64 for shift := uint(0); ; shift += 7 { @@ -5808,11 +7770,11 @@ func (m *MsgConsumerModification) Unmarshal(dAtA []byte) error { if postIndex > l { return io.ErrUnexpectedEOF } - m.Title = string(dAtA[iNdEx:postIndex]) + m.Owner = string(dAtA[iNdEx:postIndex]) iNdEx = postIndex case 2: if wireType != 2 { - return fmt.Errorf("proto: wrong wireType = %d for field Description", wireType) + return fmt.Errorf("proto: wrong wireType = %d for field ConsumerId", wireType) } var stringLen uint64 for shift := uint(0); ; shift += 7 { @@ -5840,11 +7802,11 @@ func (m *MsgConsumerModification) Unmarshal(dAtA []byte) error { if postIndex > l { return io.ErrUnexpectedEOF } - m.Description = string(dAtA[iNdEx:postIndex]) + m.ConsumerId = string(dAtA[iNdEx:postIndex]) iNdEx = postIndex case 3: if wireType != 2 { - return fmt.Errorf("proto: wrong wireType = %d for field ChainId", wireType) + return fmt.Errorf("proto: wrong wireType = %d for field NewOwnerAddress", wireType) } var stringLen uint64 for shift := uint(0); ; shift += 7 { @@ -5872,70 +7834,13 @@ func (m *MsgConsumerModification) Unmarshal(dAtA []byte) error { if postIndex > l { return io.ErrUnexpectedEOF } - m.ChainId = string(dAtA[iNdEx:postIndex]) + m.NewOwnerAddress = string(dAtA[iNdEx:postIndex]) iNdEx = postIndex case 4: - if wireType != 0 { - return fmt.Errorf("proto: wrong wireType = %d for field Top_N", wireType) - } - m.Top_N = 0 - for shift := uint(0); ; shift += 7 { - if shift >= 64 { - return ErrIntOverflowTx - } - if iNdEx >= l { - return io.ErrUnexpectedEOF - } - b := dAtA[iNdEx] - iNdEx++ - m.Top_N |= uint32(b&0x7F) << shift - if b < 0x80 { - break - } - } - case 5: - if wireType != 0 { - return fmt.Errorf("proto: wrong wireType = %d for field ValidatorsPowerCap", wireType) - } - m.ValidatorsPowerCap = 0 - for shift := uint(0); ; shift += 7 { - if shift >= 64 { - return ErrIntOverflowTx - } - if iNdEx >= l { - return io.ErrUnexpectedEOF - } - b := dAtA[iNdEx] - iNdEx++ - m.ValidatorsPowerCap |= uint32(b&0x7F) << shift - if b < 0x80 { - break - } - } - case 6: - if wireType != 0 { - return fmt.Errorf("proto: wrong wireType = %d for field ValidatorSetCap", wireType) - } - m.ValidatorSetCap = 0 - for shift := uint(0); ; shift += 7 { - if shift >= 64 { - return ErrIntOverflowTx - } - if iNdEx >= l { - return io.ErrUnexpectedEOF - } - b := dAtA[iNdEx] - iNdEx++ - m.ValidatorSetCap |= uint32(b&0x7F) << shift - if b < 0x80 { - break - } - } - case 7: if wireType != 2 { - return fmt.Errorf("proto: wrong wireType = %d for field Allowlist", wireType) + return fmt.Errorf("proto: wrong wireType = %d for field Metadata", wireType) } - var stringLen uint64 + var msglen int for shift := uint(0); ; shift += 7 { if shift >= 64 { return ErrIntOverflowTx @@ -5945,29 +7850,33 @@ func (m *MsgConsumerModification) Unmarshal(dAtA []byte) error { } 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 ErrInvalidLengthTx } - postIndex := iNdEx + intStringLen + postIndex := iNdEx + msglen if postIndex < 0 { return ErrInvalidLengthTx } if postIndex > l { return io.ErrUnexpectedEOF } - m.Allowlist = append(m.Allowlist, string(dAtA[iNdEx:postIndex])) + if m.Metadata == nil { + m.Metadata = &ConsumerMetadata{} + } + if err := m.Metadata.Unmarshal(dAtA[iNdEx:postIndex]); err != nil { + return err + } iNdEx = postIndex - case 8: + case 5: if wireType != 2 { - return fmt.Errorf("proto: wrong wireType = %d for field Denylist", wireType) + return fmt.Errorf("proto: wrong wireType = %d for field InitializationParameters", wireType) } - var stringLen uint64 + var msglen int for shift := uint(0); ; shift += 7 { if shift >= 64 { return ErrIntOverflowTx @@ -5977,29 +7886,33 @@ func (m *MsgConsumerModification) Unmarshal(dAtA []byte) error { } 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 ErrInvalidLengthTx } - postIndex := iNdEx + intStringLen + postIndex := iNdEx + msglen if postIndex < 0 { return ErrInvalidLengthTx } if postIndex > l { return io.ErrUnexpectedEOF } - m.Denylist = append(m.Denylist, string(dAtA[iNdEx:postIndex])) + if m.InitializationParameters == nil { + m.InitializationParameters = &ConsumerInitializationParameters{} + } + if err := m.InitializationParameters.Unmarshal(dAtA[iNdEx:postIndex]); err != nil { + return err + } iNdEx = postIndex - case 9: + case 6: if wireType != 2 { - return fmt.Errorf("proto: wrong wireType = %d for field Authority", wireType) + return fmt.Errorf("proto: wrong wireType = %d for field PowerShapingParameters", wireType) } - var stringLen uint64 + var msglen int for shift := uint(0); ; shift += 7 { if shift >= 64 { return ErrIntOverflowTx @@ -6009,63 +7922,28 @@ func (m *MsgConsumerModification) Unmarshal(dAtA []byte) error { } 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 ErrInvalidLengthTx } - postIndex := iNdEx + intStringLen + postIndex := iNdEx + msglen if postIndex < 0 { return ErrInvalidLengthTx } if postIndex > l { return io.ErrUnexpectedEOF } - m.Authority = string(dAtA[iNdEx:postIndex]) - iNdEx = postIndex - case 10: - if wireType != 0 { - return fmt.Errorf("proto: wrong wireType = %d for field MinStake", wireType) - } - m.MinStake = 0 - for shift := uint(0); ; shift += 7 { - if shift >= 64 { - return ErrIntOverflowTx - } - if iNdEx >= l { - return io.ErrUnexpectedEOF - } - b := dAtA[iNdEx] - iNdEx++ - m.MinStake |= uint64(b&0x7F) << shift - if b < 0x80 { - break - } - } - case 11: - if wireType != 0 { - return fmt.Errorf("proto: wrong wireType = %d for field AllowInactiveVals", wireType) + if m.PowerShapingParameters == nil { + m.PowerShapingParameters = &PowerShapingParameters{} } - 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 - } + if err := m.PowerShapingParameters.Unmarshal(dAtA[iNdEx:postIndex]); err != nil { + return err } - m.AllowInactiveVals = bool(v != 0) + iNdEx = postIndex default: iNdEx = preIndex skippy, err := skipTx(dAtA[iNdEx:]) @@ -6087,7 +7965,7 @@ func (m *MsgConsumerModification) Unmarshal(dAtA []byte) error { } return nil } -func (m *MsgConsumerModificationResponse) Unmarshal(dAtA []byte) error { +func (m *MsgUpdateConsumerResponse) Unmarshal(dAtA []byte) error { l := len(dAtA) iNdEx := 0 for iNdEx < l { @@ -6110,10 +7988,10 @@ func (m *MsgConsumerModificationResponse) Unmarshal(dAtA []byte) error { fieldNum := int32(wire >> 3) wireType := int(wire & 0x7) if wireType == 4 { - return fmt.Errorf("proto: MsgConsumerModificationResponse: wiretype end group for non-group") + return fmt.Errorf("proto: MsgUpdateConsumerResponse: wiretype end group for non-group") } if fieldNum <= 0 { - return fmt.Errorf("proto: MsgConsumerModificationResponse: illegal tag %d (wire type %d)", fieldNum, wire) + return fmt.Errorf("proto: MsgUpdateConsumerResponse: illegal tag %d (wire type %d)", fieldNum, wire) } switch fieldNum { default: diff --git a/x/ccv/types/errors.go b/x/ccv/types/errors.go index e492984e48..995d9905e8 100644 --- a/x/ccv/types/errors.go +++ b/x/ccv/types/errors.go @@ -22,4 +22,6 @@ var ( ErrDuplicateConsumerChain = errorsmod.Register(ModuleName, 14, "consumer chain already exists") ErrConsumerChainNotFound = errorsmod.Register(ModuleName, 15, "consumer chain not found") ErrInvalidDoubleVotingEvidence = errorsmod.Register(ModuleName, 16, "invalid consumer double voting evidence") + ErrStoreKeyNotFound = errorsmod.Register(ModuleName, 17, "store key not found") + ErrStoreUnmarshal = errorsmod.Register(ModuleName, 18, "cannot unmarshal value from store") ) diff --git a/x/ccv/types/events.go b/x/ccv/types/events.go index 3c63fd7954..8ee8388eb3 100644 --- a/x/ccv/types/events.go +++ b/x/ccv/types/events.go @@ -28,7 +28,6 @@ const ( AttributeUnbondingPeriod = "unbonding_period" AttributeProviderValidatorAddress = "provider_validator_address" AttributeConsumerConsensusPubKey = "consumer_consensus_pub_key" - AttributeSubmitterAddress = "submitter_address" AttributeConsumerMisbehaviour = "consumer_misbehaviour" AttributeMisbehaviourClientId = "misbehaviour_client_id" AttributeMisbehaviourHeight1 = "misbehaviour_height_1" diff --git a/x/ccv/types/expected_keepers.go b/x/ccv/types/expected_keepers.go index 5773461c34..b643bb1a6d 100644 --- a/x/ccv/types/expected_keepers.go +++ b/x/ccv/types/expected_keepers.go @@ -143,6 +143,7 @@ type BankKeeper interface { // AccountKeeper defines the expected account keeper used for simulations type AccountKeeper interface { GetModuleAccount(ctx context.Context, name string) sdk.ModuleAccountI + AddressCodec() addresscodec.Codec } // IBCTransferKeeper defines the expected interface needed for distribution transfer diff --git a/x/ccv/types/shared_params.go b/x/ccv/types/shared_params.go index fa2e28c81c..d1a82df576 100644 --- a/x/ccv/types/shared_params.go +++ b/x/ccv/types/shared_params.go @@ -77,7 +77,7 @@ func ValidateChannelIdentifier(i interface{}) error { return ibchost.ChannelIdentifierValidator(value) } -func ValidateBech32(i interface{}) error { +func ValidateAccAddress(i interface{}) error { value, ok := i.(string) if !ok { return fmt.Errorf("invalid parameter type: %T", i)