diff --git a/.golangci.yml b/.golangci.yml index 311775694ac4..3e86f621fbc0 100644 --- a/.golangci.yml +++ b/.golangci.yml @@ -112,7 +112,6 @@ linters: - crypto/keys/secp256k1/internal/* - types/coin_regex.go - testutil/testdata - - x/params - x/crisis - third_party$ - builtin$ @@ -146,7 +145,6 @@ formatters: - crypto/keys/secp256k1/internal/* - types/coin_regex.go - testutil/testdata - - x/params - x/crisis - third_party$ - builtin$ diff --git a/CHANGELOG.md b/CHANGELOG.md index f240a60f6ad7..1c5622b0f117 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -40,6 +40,8 @@ Ref: https://keepachangelog.com/en/1.0.0/ ### Breaking Changes +* [#25546](https://github.com/cosmos/cosmos-sdk/pull/25546) Removed `x/params`: + * Removes all `legacySubspace` arguments from Keeper and Module instantiation * [#25090](https://github.com/cosmos/cosmos-sdk/pull/25090) Moved deprecated modules to `./contrib`. These modules are still available but will no longer be actively maintained or supported in the Cosmos SDK Bug Bounty program. * `x/group` * `x/nft` @@ -96,6 +98,12 @@ Ref: https://keepachangelog.com/en/1.0.0/ * (x/group) [#24571](https://github.com/cosmos/cosmos-sdk/pull/24571) Deprecate the `x/group` module in the Cosmos SDK repository. This module will not be maintained to the extent that our core modules will and will be kept in a [legacy repo](https://github.com/cosmos/cosmos-legacy). * (types) [#24664](https://github.com/cosmos/cosmos-sdk/pull/24664) Deprecate the `Invariant` type in the Cosmos SDK. +<<<<<<< HEAD +# Changelog + +||||||| 0d6228eaab +======= +>>>>>>> main ## [v0.53.4](https://github.com/cosmos/cosmos-sdk/releases/tag/v0.53.3) - 2025-07-25 This patch update also includes minor dependency bumps. diff --git a/api/cosmos/params/module/v1/module.pulsar.go b/api/cosmos/params/module/v1/module.pulsar.go deleted file mode 100644 index 1d4441751567..000000000000 --- a/api/cosmos/params/module/v1/module.pulsar.go +++ /dev/null @@ -1,503 +0,0 @@ -// Code generated by protoc-gen-go-pulsar. DO NOT EDIT. -package modulev1 - -import ( - _ "cosmossdk.io/api/cosmos/app/v1alpha1" - fmt "fmt" - runtime "github.com/cosmos/cosmos-proto/runtime" - protoreflect "google.golang.org/protobuf/reflect/protoreflect" - protoiface "google.golang.org/protobuf/runtime/protoiface" - protoimpl "google.golang.org/protobuf/runtime/protoimpl" - io "io" - reflect "reflect" - sync "sync" -) - -var ( - md_Module protoreflect.MessageDescriptor -) - -func init() { - file_cosmos_params_module_v1_module_proto_init() - md_Module = File_cosmos_params_module_v1_module_proto.Messages().ByName("Module") -} - -var _ protoreflect.Message = (*fastReflection_Module)(nil) - -type fastReflection_Module Module - -func (x *Module) ProtoReflect() protoreflect.Message { - return (*fastReflection_Module)(x) -} - -func (x *Module) slowProtoReflect() protoreflect.Message { - mi := &file_cosmos_params_module_v1_module_proto_msgTypes[0] - if protoimpl.UnsafeEnabled && x != nil { - ms := protoimpl.X.MessageStateOf(protoimpl.Pointer(x)) - if ms.LoadMessageInfo() == nil { - ms.StoreMessageInfo(mi) - } - return ms - } - return mi.MessageOf(x) -} - -var _fastReflection_Module_messageType fastReflection_Module_messageType -var _ protoreflect.MessageType = fastReflection_Module_messageType{} - -type fastReflection_Module_messageType struct{} - -func (x fastReflection_Module_messageType) Zero() protoreflect.Message { - return (*fastReflection_Module)(nil) -} -func (x fastReflection_Module_messageType) New() protoreflect.Message { - return new(fastReflection_Module) -} -func (x fastReflection_Module_messageType) Descriptor() protoreflect.MessageDescriptor { - return md_Module -} - -// Descriptor returns message descriptor, which contains only the protobuf -// type information for the message. -func (x *fastReflection_Module) Descriptor() protoreflect.MessageDescriptor { - return md_Module -} - -// Type returns the message type, which encapsulates both Go and protobuf -// type information. If the Go type information is not needed, -// it is recommended that the message descriptor be used instead. -func (x *fastReflection_Module) Type() protoreflect.MessageType { - return _fastReflection_Module_messageType -} - -// New returns a newly allocated and mutable empty message. -func (x *fastReflection_Module) New() protoreflect.Message { - return new(fastReflection_Module) -} - -// Interface unwraps the message reflection interface and -// returns the underlying ProtoMessage interface. -func (x *fastReflection_Module) Interface() protoreflect.ProtoMessage { - return (*Module)(x) -} - -// Range iterates over every populated field in an undefined order, -// calling f for each field descriptor and value encountered. -// Range returns immediately if f returns false. -// While iterating, mutating operations may only be performed -// on the current field descriptor. -func (x *fastReflection_Module) Range(f func(protoreflect.FieldDescriptor, protoreflect.Value) bool) { -} - -// Has reports whether a field is populated. -// -// Some fields have the property of nullability where it is possible to -// distinguish between the default value of a field and whether the field -// was explicitly populated with the default value. Singular message fields, -// member fields of a oneof, and proto2 scalar fields are nullable. Such -// fields are populated only if explicitly set. -// -// In other cases (aside from the nullable cases above), -// a proto3 scalar field is populated if it contains a non-zero value, and -// a repeated field is populated if it is non-empty. -func (x *fastReflection_Module) Has(fd protoreflect.FieldDescriptor) bool { - switch fd.FullName() { - default: - if fd.IsExtension() { - panic(fmt.Errorf("proto3 declared messages do not support extensions: cosmos.params.module.v1.Module")) - } - panic(fmt.Errorf("message cosmos.params.module.v1.Module does not contain field %s", fd.FullName())) - } -} - -// Clear clears the field such that a subsequent Has call reports false. -// -// Clearing an extension field clears both the extension type and value -// associated with the given field number. -// -// Clear is a mutating operation and unsafe for concurrent use. -func (x *fastReflection_Module) Clear(fd protoreflect.FieldDescriptor) { - switch fd.FullName() { - default: - if fd.IsExtension() { - panic(fmt.Errorf("proto3 declared messages do not support extensions: cosmos.params.module.v1.Module")) - } - panic(fmt.Errorf("message cosmos.params.module.v1.Module does not contain field %s", fd.FullName())) - } -} - -// Get retrieves the value for a field. -// -// For unpopulated scalars, it returns the default value, where -// the default value of a bytes scalar is guaranteed to be a copy. -// For unpopulated composite types, it returns an empty, read-only view -// of the value; to obtain a mutable reference, use Mutable. -func (x *fastReflection_Module) Get(descriptor protoreflect.FieldDescriptor) protoreflect.Value { - switch descriptor.FullName() { - default: - if descriptor.IsExtension() { - panic(fmt.Errorf("proto3 declared messages do not support extensions: cosmos.params.module.v1.Module")) - } - panic(fmt.Errorf("message cosmos.params.module.v1.Module does not contain field %s", descriptor.FullName())) - } -} - -// Set stores the value for a field. -// -// For a field belonging to a oneof, it implicitly clears any other field -// that may be currently set within the same oneof. -// For extension fields, it implicitly stores the provided ExtensionType. -// When setting a composite type, it is unspecified whether the stored value -// aliases the source's memory in any way. If the composite value is an -// empty, read-only value, then it panics. -// -// Set is a mutating operation and unsafe for concurrent use. -func (x *fastReflection_Module) Set(fd protoreflect.FieldDescriptor, value protoreflect.Value) { - switch fd.FullName() { - default: - if fd.IsExtension() { - panic(fmt.Errorf("proto3 declared messages do not support extensions: cosmos.params.module.v1.Module")) - } - panic(fmt.Errorf("message cosmos.params.module.v1.Module does not contain field %s", fd.FullName())) - } -} - -// Mutable returns a mutable reference to a composite type. -// -// If the field is unpopulated, it may allocate a composite value. -// For a field belonging to a oneof, it implicitly clears any other field -// that may be currently set within the same oneof. -// For extension fields, it implicitly stores the provided ExtensionType -// if not already stored. -// It panics if the field does not contain a composite type. -// -// Mutable is a mutating operation and unsafe for concurrent use. -func (x *fastReflection_Module) Mutable(fd protoreflect.FieldDescriptor) protoreflect.Value { - switch fd.FullName() { - default: - if fd.IsExtension() { - panic(fmt.Errorf("proto3 declared messages do not support extensions: cosmos.params.module.v1.Module")) - } - panic(fmt.Errorf("message cosmos.params.module.v1.Module does not contain field %s", fd.FullName())) - } -} - -// NewField returns a new value that is assignable to the field -// for the given descriptor. For scalars, this returns the default value. -// For lists, maps, and messages, this returns a new, empty, mutable value. -func (x *fastReflection_Module) NewField(fd protoreflect.FieldDescriptor) protoreflect.Value { - switch fd.FullName() { - default: - if fd.IsExtension() { - panic(fmt.Errorf("proto3 declared messages do not support extensions: cosmos.params.module.v1.Module")) - } - panic(fmt.Errorf("message cosmos.params.module.v1.Module does not contain field %s", fd.FullName())) - } -} - -// WhichOneof reports which field within the oneof is populated, -// returning nil if none are populated. -// It panics if the oneof descriptor does not belong to this message. -func (x *fastReflection_Module) WhichOneof(d protoreflect.OneofDescriptor) protoreflect.FieldDescriptor { - switch d.FullName() { - default: - panic(fmt.Errorf("%s is not a oneof field in cosmos.params.module.v1.Module", d.FullName())) - } - panic("unreachable") -} - -// GetUnknown retrieves the entire list of unknown fields. -// The caller may only mutate the contents of the RawFields -// if the mutated bytes are stored back into the message with SetUnknown. -func (x *fastReflection_Module) GetUnknown() protoreflect.RawFields { - return x.unknownFields -} - -// SetUnknown stores an entire list of unknown fields. -// The raw fields must be syntactically valid according to the wire format. -// An implementation may panic if this is not the case. -// Once stored, the caller must not mutate the content of the RawFields. -// An empty RawFields may be passed to clear the fields. -// -// SetUnknown is a mutating operation and unsafe for concurrent use. -func (x *fastReflection_Module) SetUnknown(fields protoreflect.RawFields) { - x.unknownFields = fields -} - -// IsValid reports whether the message is valid. -// -// An invalid message is an empty, read-only value. -// -// An invalid message often corresponds to a nil pointer of the concrete -// message type, but the details are implementation dependent. -// Validity is not part of the protobuf data model, and may not -// be preserved in marshaling or other operations. -func (x *fastReflection_Module) IsValid() bool { - return x != nil -} - -// ProtoMethods returns optional fastReflectionFeature-path implementations of various operations. -// This method may return nil. -// -// The returned methods type is identical to -// "google.golang.org/protobuf/runtime/protoiface".Methods. -// Consult the protoiface package documentation for details. -func (x *fastReflection_Module) ProtoMethods() *protoiface.Methods { - size := func(input protoiface.SizeInput) protoiface.SizeOutput { - x := input.Message.Interface().(*Module) - if x == nil { - return protoiface.SizeOutput{ - NoUnkeyedLiterals: input.NoUnkeyedLiterals, - Size: 0, - } - } - options := runtime.SizeInputToOptions(input) - _ = options - var n int - var l int - _ = l - if x.unknownFields != nil { - n += len(x.unknownFields) - } - return protoiface.SizeOutput{ - NoUnkeyedLiterals: input.NoUnkeyedLiterals, - Size: n, - } - } - - marshal := func(input protoiface.MarshalInput) (protoiface.MarshalOutput, error) { - x := input.Message.Interface().(*Module) - if x == nil { - return protoiface.MarshalOutput{ - NoUnkeyedLiterals: input.NoUnkeyedLiterals, - Buf: input.Buf, - }, nil - } - options := runtime.MarshalInputToOptions(input) - _ = options - size := options.Size(x) - dAtA := make([]byte, size) - i := len(dAtA) - _ = i - var l int - _ = l - if x.unknownFields != nil { - i -= len(x.unknownFields) - copy(dAtA[i:], x.unknownFields) - } - if input.Buf != nil { - input.Buf = append(input.Buf, dAtA...) - } else { - input.Buf = dAtA - } - return protoiface.MarshalOutput{ - NoUnkeyedLiterals: input.NoUnkeyedLiterals, - Buf: input.Buf, - }, nil - } - unmarshal := func(input protoiface.UnmarshalInput) (protoiface.UnmarshalOutput, error) { - x := input.Message.Interface().(*Module) - if x == nil { - return protoiface.UnmarshalOutput{ - NoUnkeyedLiterals: input.NoUnkeyedLiterals, - Flags: input.Flags, - }, nil - } - options := runtime.UnmarshalInputToOptions(input) - _ = options - dAtA := input.Buf - l := len(dAtA) - iNdEx := 0 - for iNdEx < l { - preIndex := iNdEx - var wire uint64 - for shift := uint(0); ; shift += 7 { - if shift >= 64 { - return protoiface.UnmarshalOutput{NoUnkeyedLiterals: input.NoUnkeyedLiterals, Flags: input.Flags}, runtime.ErrIntOverflow - } - if iNdEx >= l { - return protoiface.UnmarshalOutput{NoUnkeyedLiterals: input.NoUnkeyedLiterals, Flags: input.Flags}, io.ErrUnexpectedEOF - } - b := dAtA[iNdEx] - iNdEx++ - wire |= uint64(b&0x7F) << shift - if b < 0x80 { - break - } - } - fieldNum := int32(wire >> 3) - wireType := int(wire & 0x7) - if wireType == 4 { - return protoiface.UnmarshalOutput{NoUnkeyedLiterals: input.NoUnkeyedLiterals, Flags: input.Flags}, fmt.Errorf("proto: Module: wiretype end group for non-group") - } - if fieldNum <= 0 { - return protoiface.UnmarshalOutput{NoUnkeyedLiterals: input.NoUnkeyedLiterals, Flags: input.Flags}, fmt.Errorf("proto: Module: illegal tag %d (wire type %d)", fieldNum, wire) - } - switch fieldNum { - default: - iNdEx = preIndex - skippy, err := runtime.Skip(dAtA[iNdEx:]) - if err != nil { - return protoiface.UnmarshalOutput{NoUnkeyedLiterals: input.NoUnkeyedLiterals, Flags: input.Flags}, err - } - if (skippy < 0) || (iNdEx+skippy) < 0 { - return protoiface.UnmarshalOutput{NoUnkeyedLiterals: input.NoUnkeyedLiterals, Flags: input.Flags}, runtime.ErrInvalidLength - } - if (iNdEx + skippy) > l { - return protoiface.UnmarshalOutput{NoUnkeyedLiterals: input.NoUnkeyedLiterals, Flags: input.Flags}, io.ErrUnexpectedEOF - } - if !options.DiscardUnknown { - x.unknownFields = append(x.unknownFields, dAtA[iNdEx:iNdEx+skippy]...) - } - iNdEx += skippy - } - } - - if iNdEx > l { - return protoiface.UnmarshalOutput{NoUnkeyedLiterals: input.NoUnkeyedLiterals, Flags: input.Flags}, io.ErrUnexpectedEOF - } - return protoiface.UnmarshalOutput{NoUnkeyedLiterals: input.NoUnkeyedLiterals, Flags: input.Flags}, nil - } - return &protoiface.Methods{ - NoUnkeyedLiterals: struct{}{}, - Flags: protoiface.SupportMarshalDeterministic | protoiface.SupportUnmarshalDiscardUnknown, - Size: size, - Marshal: marshal, - Unmarshal: unmarshal, - Merge: nil, - CheckInitialized: nil, - } -} - -// Code generated by protoc-gen-go. DO NOT EDIT. -// versions: -// protoc-gen-go v1.27.0 -// protoc (unknown) -// source: cosmos/params/module/v1/module.proto - -const ( - // Verify that this generated code is sufficiently up-to-date. - _ = protoimpl.EnforceVersion(20 - protoimpl.MinVersion) - // Verify that runtime/protoimpl is sufficiently up-to-date. - _ = protoimpl.EnforceVersion(protoimpl.MaxVersion - 20) -) - -// Module is the config object of the params module. -type Module struct { - state protoimpl.MessageState - sizeCache protoimpl.SizeCache - unknownFields protoimpl.UnknownFields -} - -func (x *Module) Reset() { - *x = Module{} - if protoimpl.UnsafeEnabled { - mi := &file_cosmos_params_module_v1_module_proto_msgTypes[0] - ms := protoimpl.X.MessageStateOf(protoimpl.Pointer(x)) - ms.StoreMessageInfo(mi) - } -} - -func (x *Module) String() string { - return protoimpl.X.MessageStringOf(x) -} - -func (*Module) ProtoMessage() {} - -// Deprecated: Use Module.ProtoReflect.Descriptor instead. -func (*Module) Descriptor() ([]byte, []int) { - return file_cosmos_params_module_v1_module_proto_rawDescGZIP(), []int{0} -} - -var File_cosmos_params_module_v1_module_proto protoreflect.FileDescriptor - -var file_cosmos_params_module_v1_module_proto_rawDesc = []byte{ - 0x0a, 0x24, 0x63, 0x6f, 0x73, 0x6d, 0x6f, 0x73, 0x2f, 0x70, 0x61, 0x72, 0x61, 0x6d, 0x73, 0x2f, - 0x6d, 0x6f, 0x64, 0x75, 0x6c, 0x65, 0x2f, 0x76, 0x31, 0x2f, 0x6d, 0x6f, 0x64, 0x75, 0x6c, 0x65, - 0x2e, 0x70, 0x72, 0x6f, 0x74, 0x6f, 0x12, 0x17, 0x63, 0x6f, 0x73, 0x6d, 0x6f, 0x73, 0x2e, 0x70, - 0x61, 0x72, 0x61, 0x6d, 0x73, 0x2e, 0x6d, 0x6f, 0x64, 0x75, 0x6c, 0x65, 0x2e, 0x76, 0x31, 0x1a, - 0x20, 0x63, 0x6f, 0x73, 0x6d, 0x6f, 0x73, 0x2f, 0x61, 0x70, 0x70, 0x2f, 0x76, 0x31, 0x61, 0x6c, - 0x70, 0x68, 0x61, 0x31, 0x2f, 0x6d, 0x6f, 0x64, 0x75, 0x6c, 0x65, 0x2e, 0x70, 0x72, 0x6f, 0x74, - 0x6f, 0x22, 0x37, 0x0a, 0x06, 0x4d, 0x6f, 0x64, 0x75, 0x6c, 0x65, 0x3a, 0x2d, 0xba, 0xc0, 0x96, - 0xda, 0x01, 0x27, 0x0a, 0x25, 0x67, 0x69, 0x74, 0x68, 0x75, 0x62, 0x2e, 0x63, 0x6f, 0x6d, 0x2f, - 0x63, 0x6f, 0x73, 0x6d, 0x6f, 0x73, 0x2f, 0x63, 0x6f, 0x73, 0x6d, 0x6f, 0x73, 0x2d, 0x73, 0x64, - 0x6b, 0x2f, 0x78, 0x2f, 0x70, 0x61, 0x72, 0x61, 0x6d, 0x73, 0x42, 0xdc, 0x01, 0x0a, 0x1b, 0x63, - 0x6f, 0x6d, 0x2e, 0x63, 0x6f, 0x73, 0x6d, 0x6f, 0x73, 0x2e, 0x70, 0x61, 0x72, 0x61, 0x6d, 0x73, - 0x2e, 0x6d, 0x6f, 0x64, 0x75, 0x6c, 0x65, 0x2e, 0x76, 0x31, 0x42, 0x0b, 0x4d, 0x6f, 0x64, 0x75, - 0x6c, 0x65, 0x50, 0x72, 0x6f, 0x74, 0x6f, 0x50, 0x01, 0x5a, 0x31, 0x63, 0x6f, 0x73, 0x6d, 0x6f, - 0x73, 0x73, 0x64, 0x6b, 0x2e, 0x69, 0x6f, 0x2f, 0x61, 0x70, 0x69, 0x2f, 0x63, 0x6f, 0x73, 0x6d, - 0x6f, 0x73, 0x2f, 0x70, 0x61, 0x72, 0x61, 0x6d, 0x73, 0x2f, 0x6d, 0x6f, 0x64, 0x75, 0x6c, 0x65, - 0x2f, 0x76, 0x31, 0x3b, 0x6d, 0x6f, 0x64, 0x75, 0x6c, 0x65, 0x76, 0x31, 0xa2, 0x02, 0x03, 0x43, - 0x50, 0x4d, 0xaa, 0x02, 0x17, 0x43, 0x6f, 0x73, 0x6d, 0x6f, 0x73, 0x2e, 0x50, 0x61, 0x72, 0x61, - 0x6d, 0x73, 0x2e, 0x4d, 0x6f, 0x64, 0x75, 0x6c, 0x65, 0x2e, 0x56, 0x31, 0xca, 0x02, 0x17, 0x43, - 0x6f, 0x73, 0x6d, 0x6f, 0x73, 0x5c, 0x50, 0x61, 0x72, 0x61, 0x6d, 0x73, 0x5c, 0x4d, 0x6f, 0x64, - 0x75, 0x6c, 0x65, 0x5c, 0x56, 0x31, 0xe2, 0x02, 0x23, 0x43, 0x6f, 0x73, 0x6d, 0x6f, 0x73, 0x5c, - 0x50, 0x61, 0x72, 0x61, 0x6d, 0x73, 0x5c, 0x4d, 0x6f, 0x64, 0x75, 0x6c, 0x65, 0x5c, 0x56, 0x31, - 0x5c, 0x47, 0x50, 0x42, 0x4d, 0x65, 0x74, 0x61, 0x64, 0x61, 0x74, 0x61, 0xea, 0x02, 0x1a, 0x43, - 0x6f, 0x73, 0x6d, 0x6f, 0x73, 0x3a, 0x3a, 0x50, 0x61, 0x72, 0x61, 0x6d, 0x73, 0x3a, 0x3a, 0x4d, - 0x6f, 0x64, 0x75, 0x6c, 0x65, 0x3a, 0x3a, 0x56, 0x31, 0x62, 0x06, 0x70, 0x72, 0x6f, 0x74, 0x6f, - 0x33, -} - -var ( - file_cosmos_params_module_v1_module_proto_rawDescOnce sync.Once - file_cosmos_params_module_v1_module_proto_rawDescData = file_cosmos_params_module_v1_module_proto_rawDesc -) - -func file_cosmos_params_module_v1_module_proto_rawDescGZIP() []byte { - file_cosmos_params_module_v1_module_proto_rawDescOnce.Do(func() { - file_cosmos_params_module_v1_module_proto_rawDescData = protoimpl.X.CompressGZIP(file_cosmos_params_module_v1_module_proto_rawDescData) - }) - return file_cosmos_params_module_v1_module_proto_rawDescData -} - -var file_cosmos_params_module_v1_module_proto_msgTypes = make([]protoimpl.MessageInfo, 1) -var file_cosmos_params_module_v1_module_proto_goTypes = []interface{}{ - (*Module)(nil), // 0: cosmos.params.module.v1.Module -} -var file_cosmos_params_module_v1_module_proto_depIdxs = []int32{ - 0, // [0:0] is the sub-list for method output_type - 0, // [0:0] is the sub-list for method input_type - 0, // [0:0] is the sub-list for extension type_name - 0, // [0:0] is the sub-list for extension extendee - 0, // [0:0] is the sub-list for field type_name -} - -func init() { file_cosmos_params_module_v1_module_proto_init() } -func file_cosmos_params_module_v1_module_proto_init() { - if File_cosmos_params_module_v1_module_proto != nil { - return - } - if !protoimpl.UnsafeEnabled { - file_cosmos_params_module_v1_module_proto_msgTypes[0].Exporter = func(v interface{}, i int) interface{} { - switch v := v.(*Module); i { - case 0: - return &v.state - case 1: - return &v.sizeCache - case 2: - return &v.unknownFields - default: - return nil - } - } - } - type x struct{} - out := protoimpl.TypeBuilder{ - File: protoimpl.DescBuilder{ - GoPackagePath: reflect.TypeOf(x{}).PkgPath(), - RawDescriptor: file_cosmos_params_module_v1_module_proto_rawDesc, - NumEnums: 0, - NumMessages: 1, - NumExtensions: 0, - NumServices: 0, - }, - GoTypes: file_cosmos_params_module_v1_module_proto_goTypes, - DependencyIndexes: file_cosmos_params_module_v1_module_proto_depIdxs, - MessageInfos: file_cosmos_params_module_v1_module_proto_msgTypes, - }.Build() - File_cosmos_params_module_v1_module_proto = out.File - file_cosmos_params_module_v1_module_proto_rawDesc = nil - file_cosmos_params_module_v1_module_proto_goTypes = nil - file_cosmos_params_module_v1_module_proto_depIdxs = nil -} diff --git a/api/cosmos/params/v1beta1/params.pulsar.go b/api/cosmos/params/v1beta1/params.pulsar.go deleted file mode 100644 index d91dee991f64..000000000000 --- a/api/cosmos/params/v1beta1/params.pulsar.go +++ /dev/null @@ -1,1428 +0,0 @@ -// Code generated by protoc-gen-go-pulsar. DO NOT EDIT. -package paramsv1beta1 - -import ( - _ "cosmossdk.io/api/amino" - fmt "fmt" - _ "github.com/cosmos/cosmos-proto" - runtime "github.com/cosmos/cosmos-proto/runtime" - _ "github.com/cosmos/gogoproto/gogoproto" - protoreflect "google.golang.org/protobuf/reflect/protoreflect" - protoiface "google.golang.org/protobuf/runtime/protoiface" - protoimpl "google.golang.org/protobuf/runtime/protoimpl" - io "io" - reflect "reflect" - sync "sync" -) - -var _ protoreflect.List = (*_ParameterChangeProposal_3_list)(nil) - -type _ParameterChangeProposal_3_list struct { - list *[]*ParamChange -} - -func (x *_ParameterChangeProposal_3_list) Len() int { - if x.list == nil { - return 0 - } - return len(*x.list) -} - -func (x *_ParameterChangeProposal_3_list) Get(i int) protoreflect.Value { - return protoreflect.ValueOfMessage((*x.list)[i].ProtoReflect()) -} - -func (x *_ParameterChangeProposal_3_list) Set(i int, value protoreflect.Value) { - valueUnwrapped := value.Message() - concreteValue := valueUnwrapped.Interface().(*ParamChange) - (*x.list)[i] = concreteValue -} - -func (x *_ParameterChangeProposal_3_list) Append(value protoreflect.Value) { - valueUnwrapped := value.Message() - concreteValue := valueUnwrapped.Interface().(*ParamChange) - *x.list = append(*x.list, concreteValue) -} - -func (x *_ParameterChangeProposal_3_list) AppendMutable() protoreflect.Value { - v := new(ParamChange) - *x.list = append(*x.list, v) - return protoreflect.ValueOfMessage(v.ProtoReflect()) -} - -func (x *_ParameterChangeProposal_3_list) Truncate(n int) { - for i := n; i < len(*x.list); i++ { - (*x.list)[i] = nil - } - *x.list = (*x.list)[:n] -} - -func (x *_ParameterChangeProposal_3_list) NewElement() protoreflect.Value { - v := new(ParamChange) - return protoreflect.ValueOfMessage(v.ProtoReflect()) -} - -func (x *_ParameterChangeProposal_3_list) IsValid() bool { - return x.list != nil -} - -var ( - md_ParameterChangeProposal protoreflect.MessageDescriptor - fd_ParameterChangeProposal_title protoreflect.FieldDescriptor - fd_ParameterChangeProposal_description protoreflect.FieldDescriptor - fd_ParameterChangeProposal_changes protoreflect.FieldDescriptor -) - -func init() { - file_cosmos_params_v1beta1_params_proto_init() - md_ParameterChangeProposal = File_cosmos_params_v1beta1_params_proto.Messages().ByName("ParameterChangeProposal") - fd_ParameterChangeProposal_title = md_ParameterChangeProposal.Fields().ByName("title") - fd_ParameterChangeProposal_description = md_ParameterChangeProposal.Fields().ByName("description") - fd_ParameterChangeProposal_changes = md_ParameterChangeProposal.Fields().ByName("changes") -} - -var _ protoreflect.Message = (*fastReflection_ParameterChangeProposal)(nil) - -type fastReflection_ParameterChangeProposal ParameterChangeProposal - -func (x *ParameterChangeProposal) ProtoReflect() protoreflect.Message { - return (*fastReflection_ParameterChangeProposal)(x) -} - -func (x *ParameterChangeProposal) slowProtoReflect() protoreflect.Message { - mi := &file_cosmos_params_v1beta1_params_proto_msgTypes[0] - if protoimpl.UnsafeEnabled && x != nil { - ms := protoimpl.X.MessageStateOf(protoimpl.Pointer(x)) - if ms.LoadMessageInfo() == nil { - ms.StoreMessageInfo(mi) - } - return ms - } - return mi.MessageOf(x) -} - -var _fastReflection_ParameterChangeProposal_messageType fastReflection_ParameterChangeProposal_messageType -var _ protoreflect.MessageType = fastReflection_ParameterChangeProposal_messageType{} - -type fastReflection_ParameterChangeProposal_messageType struct{} - -func (x fastReflection_ParameterChangeProposal_messageType) Zero() protoreflect.Message { - return (*fastReflection_ParameterChangeProposal)(nil) -} -func (x fastReflection_ParameterChangeProposal_messageType) New() protoreflect.Message { - return new(fastReflection_ParameterChangeProposal) -} -func (x fastReflection_ParameterChangeProposal_messageType) Descriptor() protoreflect.MessageDescriptor { - return md_ParameterChangeProposal -} - -// Descriptor returns message descriptor, which contains only the protobuf -// type information for the message. -func (x *fastReflection_ParameterChangeProposal) Descriptor() protoreflect.MessageDescriptor { - return md_ParameterChangeProposal -} - -// Type returns the message type, which encapsulates both Go and protobuf -// type information. If the Go type information is not needed, -// it is recommended that the message descriptor be used instead. -func (x *fastReflection_ParameterChangeProposal) Type() protoreflect.MessageType { - return _fastReflection_ParameterChangeProposal_messageType -} - -// New returns a newly allocated and mutable empty message. -func (x *fastReflection_ParameterChangeProposal) New() protoreflect.Message { - return new(fastReflection_ParameterChangeProposal) -} - -// Interface unwraps the message reflection interface and -// returns the underlying ProtoMessage interface. -func (x *fastReflection_ParameterChangeProposal) Interface() protoreflect.ProtoMessage { - return (*ParameterChangeProposal)(x) -} - -// Range iterates over every populated field in an undefined order, -// calling f for each field descriptor and value encountered. -// Range returns immediately if f returns false. -// While iterating, mutating operations may only be performed -// on the current field descriptor. -func (x *fastReflection_ParameterChangeProposal) Range(f func(protoreflect.FieldDescriptor, protoreflect.Value) bool) { - if x.Title != "" { - value := protoreflect.ValueOfString(x.Title) - if !f(fd_ParameterChangeProposal_title, value) { - return - } - } - if x.Description != "" { - value := protoreflect.ValueOfString(x.Description) - if !f(fd_ParameterChangeProposal_description, value) { - return - } - } - if len(x.Changes) != 0 { - value := protoreflect.ValueOfList(&_ParameterChangeProposal_3_list{list: &x.Changes}) - if !f(fd_ParameterChangeProposal_changes, value) { - return - } - } -} - -// Has reports whether a field is populated. -// -// Some fields have the property of nullability where it is possible to -// distinguish between the default value of a field and whether the field -// was explicitly populated with the default value. Singular message fields, -// member fields of a oneof, and proto2 scalar fields are nullable. Such -// fields are populated only if explicitly set. -// -// In other cases (aside from the nullable cases above), -// a proto3 scalar field is populated if it contains a non-zero value, and -// a repeated field is populated if it is non-empty. -func (x *fastReflection_ParameterChangeProposal) Has(fd protoreflect.FieldDescriptor) bool { - switch fd.FullName() { - case "cosmos.params.v1beta1.ParameterChangeProposal.title": - return x.Title != "" - case "cosmos.params.v1beta1.ParameterChangeProposal.description": - return x.Description != "" - case "cosmos.params.v1beta1.ParameterChangeProposal.changes": - return len(x.Changes) != 0 - default: - if fd.IsExtension() { - panic(fmt.Errorf("proto3 declared messages do not support extensions: cosmos.params.v1beta1.ParameterChangeProposal")) - } - panic(fmt.Errorf("message cosmos.params.v1beta1.ParameterChangeProposal does not contain field %s", fd.FullName())) - } -} - -// Clear clears the field such that a subsequent Has call reports false. -// -// Clearing an extension field clears both the extension type and value -// associated with the given field number. -// -// Clear is a mutating operation and unsafe for concurrent use. -func (x *fastReflection_ParameterChangeProposal) Clear(fd protoreflect.FieldDescriptor) { - switch fd.FullName() { - case "cosmos.params.v1beta1.ParameterChangeProposal.title": - x.Title = "" - case "cosmos.params.v1beta1.ParameterChangeProposal.description": - x.Description = "" - case "cosmos.params.v1beta1.ParameterChangeProposal.changes": - x.Changes = nil - default: - if fd.IsExtension() { - panic(fmt.Errorf("proto3 declared messages do not support extensions: cosmos.params.v1beta1.ParameterChangeProposal")) - } - panic(fmt.Errorf("message cosmos.params.v1beta1.ParameterChangeProposal does not contain field %s", fd.FullName())) - } -} - -// Get retrieves the value for a field. -// -// For unpopulated scalars, it returns the default value, where -// the default value of a bytes scalar is guaranteed to be a copy. -// For unpopulated composite types, it returns an empty, read-only view -// of the value; to obtain a mutable reference, use Mutable. -func (x *fastReflection_ParameterChangeProposal) Get(descriptor protoreflect.FieldDescriptor) protoreflect.Value { - switch descriptor.FullName() { - case "cosmos.params.v1beta1.ParameterChangeProposal.title": - value := x.Title - return protoreflect.ValueOfString(value) - case "cosmos.params.v1beta1.ParameterChangeProposal.description": - value := x.Description - return protoreflect.ValueOfString(value) - case "cosmos.params.v1beta1.ParameterChangeProposal.changes": - if len(x.Changes) == 0 { - return protoreflect.ValueOfList(&_ParameterChangeProposal_3_list{}) - } - listValue := &_ParameterChangeProposal_3_list{list: &x.Changes} - return protoreflect.ValueOfList(listValue) - default: - if descriptor.IsExtension() { - panic(fmt.Errorf("proto3 declared messages do not support extensions: cosmos.params.v1beta1.ParameterChangeProposal")) - } - panic(fmt.Errorf("message cosmos.params.v1beta1.ParameterChangeProposal does not contain field %s", descriptor.FullName())) - } -} - -// Set stores the value for a field. -// -// For a field belonging to a oneof, it implicitly clears any other field -// that may be currently set within the same oneof. -// For extension fields, it implicitly stores the provided ExtensionType. -// When setting a composite type, it is unspecified whether the stored value -// aliases the source's memory in any way. If the composite value is an -// empty, read-only value, then it panics. -// -// Set is a mutating operation and unsafe for concurrent use. -func (x *fastReflection_ParameterChangeProposal) Set(fd protoreflect.FieldDescriptor, value protoreflect.Value) { - switch fd.FullName() { - case "cosmos.params.v1beta1.ParameterChangeProposal.title": - x.Title = value.Interface().(string) - case "cosmos.params.v1beta1.ParameterChangeProposal.description": - x.Description = value.Interface().(string) - case "cosmos.params.v1beta1.ParameterChangeProposal.changes": - lv := value.List() - clv := lv.(*_ParameterChangeProposal_3_list) - x.Changes = *clv.list - default: - if fd.IsExtension() { - panic(fmt.Errorf("proto3 declared messages do not support extensions: cosmos.params.v1beta1.ParameterChangeProposal")) - } - panic(fmt.Errorf("message cosmos.params.v1beta1.ParameterChangeProposal does not contain field %s", fd.FullName())) - } -} - -// Mutable returns a mutable reference to a composite type. -// -// If the field is unpopulated, it may allocate a composite value. -// For a field belonging to a oneof, it implicitly clears any other field -// that may be currently set within the same oneof. -// For extension fields, it implicitly stores the provided ExtensionType -// if not already stored. -// It panics if the field does not contain a composite type. -// -// Mutable is a mutating operation and unsafe for concurrent use. -func (x *fastReflection_ParameterChangeProposal) Mutable(fd protoreflect.FieldDescriptor) protoreflect.Value { - switch fd.FullName() { - case "cosmos.params.v1beta1.ParameterChangeProposal.changes": - if x.Changes == nil { - x.Changes = []*ParamChange{} - } - value := &_ParameterChangeProposal_3_list{list: &x.Changes} - return protoreflect.ValueOfList(value) - case "cosmos.params.v1beta1.ParameterChangeProposal.title": - panic(fmt.Errorf("field title of message cosmos.params.v1beta1.ParameterChangeProposal is not mutable")) - case "cosmos.params.v1beta1.ParameterChangeProposal.description": - panic(fmt.Errorf("field description of message cosmos.params.v1beta1.ParameterChangeProposal is not mutable")) - default: - if fd.IsExtension() { - panic(fmt.Errorf("proto3 declared messages do not support extensions: cosmos.params.v1beta1.ParameterChangeProposal")) - } - panic(fmt.Errorf("message cosmos.params.v1beta1.ParameterChangeProposal does not contain field %s", fd.FullName())) - } -} - -// NewField returns a new value that is assignable to the field -// for the given descriptor. For scalars, this returns the default value. -// For lists, maps, and messages, this returns a new, empty, mutable value. -func (x *fastReflection_ParameterChangeProposal) NewField(fd protoreflect.FieldDescriptor) protoreflect.Value { - switch fd.FullName() { - case "cosmos.params.v1beta1.ParameterChangeProposal.title": - return protoreflect.ValueOfString("") - case "cosmos.params.v1beta1.ParameterChangeProposal.description": - return protoreflect.ValueOfString("") - case "cosmos.params.v1beta1.ParameterChangeProposal.changes": - list := []*ParamChange{} - return protoreflect.ValueOfList(&_ParameterChangeProposal_3_list{list: &list}) - default: - if fd.IsExtension() { - panic(fmt.Errorf("proto3 declared messages do not support extensions: cosmos.params.v1beta1.ParameterChangeProposal")) - } - panic(fmt.Errorf("message cosmos.params.v1beta1.ParameterChangeProposal does not contain field %s", fd.FullName())) - } -} - -// WhichOneof reports which field within the oneof is populated, -// returning nil if none are populated. -// It panics if the oneof descriptor does not belong to this message. -func (x *fastReflection_ParameterChangeProposal) WhichOneof(d protoreflect.OneofDescriptor) protoreflect.FieldDescriptor { - switch d.FullName() { - default: - panic(fmt.Errorf("%s is not a oneof field in cosmos.params.v1beta1.ParameterChangeProposal", d.FullName())) - } - panic("unreachable") -} - -// GetUnknown retrieves the entire list of unknown fields. -// The caller may only mutate the contents of the RawFields -// if the mutated bytes are stored back into the message with SetUnknown. -func (x *fastReflection_ParameterChangeProposal) GetUnknown() protoreflect.RawFields { - return x.unknownFields -} - -// SetUnknown stores an entire list of unknown fields. -// The raw fields must be syntactically valid according to the wire format. -// An implementation may panic if this is not the case. -// Once stored, the caller must not mutate the content of the RawFields. -// An empty RawFields may be passed to clear the fields. -// -// SetUnknown is a mutating operation and unsafe for concurrent use. -func (x *fastReflection_ParameterChangeProposal) SetUnknown(fields protoreflect.RawFields) { - x.unknownFields = fields -} - -// IsValid reports whether the message is valid. -// -// An invalid message is an empty, read-only value. -// -// An invalid message often corresponds to a nil pointer of the concrete -// message type, but the details are implementation dependent. -// Validity is not part of the protobuf data model, and may not -// be preserved in marshaling or other operations. -func (x *fastReflection_ParameterChangeProposal) IsValid() bool { - return x != nil -} - -// ProtoMethods returns optional fastReflectionFeature-path implementations of various operations. -// This method may return nil. -// -// The returned methods type is identical to -// "google.golang.org/protobuf/runtime/protoiface".Methods. -// Consult the protoiface package documentation for details. -func (x *fastReflection_ParameterChangeProposal) ProtoMethods() *protoiface.Methods { - size := func(input protoiface.SizeInput) protoiface.SizeOutput { - x := input.Message.Interface().(*ParameterChangeProposal) - if x == nil { - return protoiface.SizeOutput{ - NoUnkeyedLiterals: input.NoUnkeyedLiterals, - Size: 0, - } - } - options := runtime.SizeInputToOptions(input) - _ = options - var n int - var l int - _ = l - l = len(x.Title) - if l > 0 { - n += 1 + l + runtime.Sov(uint64(l)) - } - l = len(x.Description) - if l > 0 { - n += 1 + l + runtime.Sov(uint64(l)) - } - if len(x.Changes) > 0 { - for _, e := range x.Changes { - l = options.Size(e) - n += 1 + l + runtime.Sov(uint64(l)) - } - } - if x.unknownFields != nil { - n += len(x.unknownFields) - } - return protoiface.SizeOutput{ - NoUnkeyedLiterals: input.NoUnkeyedLiterals, - Size: n, - } - } - - marshal := func(input protoiface.MarshalInput) (protoiface.MarshalOutput, error) { - x := input.Message.Interface().(*ParameterChangeProposal) - if x == nil { - return protoiface.MarshalOutput{ - NoUnkeyedLiterals: input.NoUnkeyedLiterals, - Buf: input.Buf, - }, nil - } - options := runtime.MarshalInputToOptions(input) - _ = options - size := options.Size(x) - dAtA := make([]byte, size) - i := len(dAtA) - _ = i - var l int - _ = l - if x.unknownFields != nil { - i -= len(x.unknownFields) - copy(dAtA[i:], x.unknownFields) - } - if len(x.Changes) > 0 { - for iNdEx := len(x.Changes) - 1; iNdEx >= 0; iNdEx-- { - encoded, err := options.Marshal(x.Changes[iNdEx]) - if err != nil { - return protoiface.MarshalOutput{ - NoUnkeyedLiterals: input.NoUnkeyedLiterals, - Buf: input.Buf, - }, err - } - i -= len(encoded) - copy(dAtA[i:], encoded) - i = runtime.EncodeVarint(dAtA, i, uint64(len(encoded))) - i-- - dAtA[i] = 0x1a - } - } - if len(x.Description) > 0 { - i -= len(x.Description) - copy(dAtA[i:], x.Description) - i = runtime.EncodeVarint(dAtA, i, uint64(len(x.Description))) - i-- - dAtA[i] = 0x12 - } - if len(x.Title) > 0 { - i -= len(x.Title) - copy(dAtA[i:], x.Title) - i = runtime.EncodeVarint(dAtA, i, uint64(len(x.Title))) - i-- - dAtA[i] = 0xa - } - if input.Buf != nil { - input.Buf = append(input.Buf, dAtA...) - } else { - input.Buf = dAtA - } - return protoiface.MarshalOutput{ - NoUnkeyedLiterals: input.NoUnkeyedLiterals, - Buf: input.Buf, - }, nil - } - unmarshal := func(input protoiface.UnmarshalInput) (protoiface.UnmarshalOutput, error) { - x := input.Message.Interface().(*ParameterChangeProposal) - if x == nil { - return protoiface.UnmarshalOutput{ - NoUnkeyedLiterals: input.NoUnkeyedLiterals, - Flags: input.Flags, - }, nil - } - options := runtime.UnmarshalInputToOptions(input) - _ = options - dAtA := input.Buf - l := len(dAtA) - iNdEx := 0 - for iNdEx < l { - preIndex := iNdEx - var wire uint64 - for shift := uint(0); ; shift += 7 { - if shift >= 64 { - return protoiface.UnmarshalOutput{NoUnkeyedLiterals: input.NoUnkeyedLiterals, Flags: input.Flags}, runtime.ErrIntOverflow - } - if iNdEx >= l { - return protoiface.UnmarshalOutput{NoUnkeyedLiterals: input.NoUnkeyedLiterals, Flags: input.Flags}, io.ErrUnexpectedEOF - } - b := dAtA[iNdEx] - iNdEx++ - wire |= uint64(b&0x7F) << shift - if b < 0x80 { - break - } - } - fieldNum := int32(wire >> 3) - wireType := int(wire & 0x7) - if wireType == 4 { - return protoiface.UnmarshalOutput{NoUnkeyedLiterals: input.NoUnkeyedLiterals, Flags: input.Flags}, fmt.Errorf("proto: ParameterChangeProposal: wiretype end group for non-group") - } - if fieldNum <= 0 { - return protoiface.UnmarshalOutput{NoUnkeyedLiterals: input.NoUnkeyedLiterals, Flags: input.Flags}, fmt.Errorf("proto: ParameterChangeProposal: illegal tag %d (wire type %d)", fieldNum, wire) - } - switch fieldNum { - case 1: - if wireType != 2 { - return protoiface.UnmarshalOutput{NoUnkeyedLiterals: input.NoUnkeyedLiterals, Flags: input.Flags}, fmt.Errorf("proto: wrong wireType = %d for field Title", wireType) - } - var stringLen uint64 - for shift := uint(0); ; shift += 7 { - if shift >= 64 { - return protoiface.UnmarshalOutput{NoUnkeyedLiterals: input.NoUnkeyedLiterals, Flags: input.Flags}, runtime.ErrIntOverflow - } - if iNdEx >= l { - return protoiface.UnmarshalOutput{NoUnkeyedLiterals: input.NoUnkeyedLiterals, Flags: input.Flags}, io.ErrUnexpectedEOF - } - b := dAtA[iNdEx] - iNdEx++ - stringLen |= uint64(b&0x7F) << shift - if b < 0x80 { - break - } - } - intStringLen := int(stringLen) - if intStringLen < 0 { - return protoiface.UnmarshalOutput{NoUnkeyedLiterals: input.NoUnkeyedLiterals, Flags: input.Flags}, runtime.ErrInvalidLength - } - postIndex := iNdEx + intStringLen - if postIndex < 0 { - return protoiface.UnmarshalOutput{NoUnkeyedLiterals: input.NoUnkeyedLiterals, Flags: input.Flags}, runtime.ErrInvalidLength - } - if postIndex > l { - return protoiface.UnmarshalOutput{NoUnkeyedLiterals: input.NoUnkeyedLiterals, Flags: input.Flags}, io.ErrUnexpectedEOF - } - x.Title = string(dAtA[iNdEx:postIndex]) - iNdEx = postIndex - case 2: - if wireType != 2 { - return protoiface.UnmarshalOutput{NoUnkeyedLiterals: input.NoUnkeyedLiterals, Flags: input.Flags}, fmt.Errorf("proto: wrong wireType = %d for field Description", wireType) - } - var stringLen uint64 - for shift := uint(0); ; shift += 7 { - if shift >= 64 { - return protoiface.UnmarshalOutput{NoUnkeyedLiterals: input.NoUnkeyedLiterals, Flags: input.Flags}, runtime.ErrIntOverflow - } - if iNdEx >= l { - return protoiface.UnmarshalOutput{NoUnkeyedLiterals: input.NoUnkeyedLiterals, Flags: input.Flags}, io.ErrUnexpectedEOF - } - b := dAtA[iNdEx] - iNdEx++ - stringLen |= uint64(b&0x7F) << shift - if b < 0x80 { - break - } - } - intStringLen := int(stringLen) - if intStringLen < 0 { - return protoiface.UnmarshalOutput{NoUnkeyedLiterals: input.NoUnkeyedLiterals, Flags: input.Flags}, runtime.ErrInvalidLength - } - postIndex := iNdEx + intStringLen - if postIndex < 0 { - return protoiface.UnmarshalOutput{NoUnkeyedLiterals: input.NoUnkeyedLiterals, Flags: input.Flags}, runtime.ErrInvalidLength - } - if postIndex > l { - return protoiface.UnmarshalOutput{NoUnkeyedLiterals: input.NoUnkeyedLiterals, Flags: input.Flags}, io.ErrUnexpectedEOF - } - x.Description = string(dAtA[iNdEx:postIndex]) - iNdEx = postIndex - case 3: - if wireType != 2 { - return protoiface.UnmarshalOutput{NoUnkeyedLiterals: input.NoUnkeyedLiterals, Flags: input.Flags}, fmt.Errorf("proto: wrong wireType = %d for field Changes", wireType) - } - var msglen int - for shift := uint(0); ; shift += 7 { - if shift >= 64 { - return protoiface.UnmarshalOutput{NoUnkeyedLiterals: input.NoUnkeyedLiterals, Flags: input.Flags}, runtime.ErrIntOverflow - } - if iNdEx >= l { - return protoiface.UnmarshalOutput{NoUnkeyedLiterals: input.NoUnkeyedLiterals, Flags: input.Flags}, io.ErrUnexpectedEOF - } - b := dAtA[iNdEx] - iNdEx++ - msglen |= int(b&0x7F) << shift - if b < 0x80 { - break - } - } - if msglen < 0 { - return protoiface.UnmarshalOutput{NoUnkeyedLiterals: input.NoUnkeyedLiterals, Flags: input.Flags}, runtime.ErrInvalidLength - } - postIndex := iNdEx + msglen - if postIndex < 0 { - return protoiface.UnmarshalOutput{NoUnkeyedLiterals: input.NoUnkeyedLiterals, Flags: input.Flags}, runtime.ErrInvalidLength - } - if postIndex > l { - return protoiface.UnmarshalOutput{NoUnkeyedLiterals: input.NoUnkeyedLiterals, Flags: input.Flags}, io.ErrUnexpectedEOF - } - x.Changes = append(x.Changes, &ParamChange{}) - if err := options.Unmarshal(dAtA[iNdEx:postIndex], x.Changes[len(x.Changes)-1]); err != nil { - return protoiface.UnmarshalOutput{NoUnkeyedLiterals: input.NoUnkeyedLiterals, Flags: input.Flags}, err - } - iNdEx = postIndex - default: - iNdEx = preIndex - skippy, err := runtime.Skip(dAtA[iNdEx:]) - if err != nil { - return protoiface.UnmarshalOutput{NoUnkeyedLiterals: input.NoUnkeyedLiterals, Flags: input.Flags}, err - } - if (skippy < 0) || (iNdEx+skippy) < 0 { - return protoiface.UnmarshalOutput{NoUnkeyedLiterals: input.NoUnkeyedLiterals, Flags: input.Flags}, runtime.ErrInvalidLength - } - if (iNdEx + skippy) > l { - return protoiface.UnmarshalOutput{NoUnkeyedLiterals: input.NoUnkeyedLiterals, Flags: input.Flags}, io.ErrUnexpectedEOF - } - if !options.DiscardUnknown { - x.unknownFields = append(x.unknownFields, dAtA[iNdEx:iNdEx+skippy]...) - } - iNdEx += skippy - } - } - - if iNdEx > l { - return protoiface.UnmarshalOutput{NoUnkeyedLiterals: input.NoUnkeyedLiterals, Flags: input.Flags}, io.ErrUnexpectedEOF - } - return protoiface.UnmarshalOutput{NoUnkeyedLiterals: input.NoUnkeyedLiterals, Flags: input.Flags}, nil - } - return &protoiface.Methods{ - NoUnkeyedLiterals: struct{}{}, - Flags: protoiface.SupportMarshalDeterministic | protoiface.SupportUnmarshalDiscardUnknown, - Size: size, - Marshal: marshal, - Unmarshal: unmarshal, - Merge: nil, - CheckInitialized: nil, - } -} - -var ( - md_ParamChange protoreflect.MessageDescriptor - fd_ParamChange_subspace protoreflect.FieldDescriptor - fd_ParamChange_key protoreflect.FieldDescriptor - fd_ParamChange_value protoreflect.FieldDescriptor -) - -func init() { - file_cosmos_params_v1beta1_params_proto_init() - md_ParamChange = File_cosmos_params_v1beta1_params_proto.Messages().ByName("ParamChange") - fd_ParamChange_subspace = md_ParamChange.Fields().ByName("subspace") - fd_ParamChange_key = md_ParamChange.Fields().ByName("key") - fd_ParamChange_value = md_ParamChange.Fields().ByName("value") -} - -var _ protoreflect.Message = (*fastReflection_ParamChange)(nil) - -type fastReflection_ParamChange ParamChange - -func (x *ParamChange) ProtoReflect() protoreflect.Message { - return (*fastReflection_ParamChange)(x) -} - -func (x *ParamChange) slowProtoReflect() protoreflect.Message { - mi := &file_cosmos_params_v1beta1_params_proto_msgTypes[1] - if protoimpl.UnsafeEnabled && x != nil { - ms := protoimpl.X.MessageStateOf(protoimpl.Pointer(x)) - if ms.LoadMessageInfo() == nil { - ms.StoreMessageInfo(mi) - } - return ms - } - return mi.MessageOf(x) -} - -var _fastReflection_ParamChange_messageType fastReflection_ParamChange_messageType -var _ protoreflect.MessageType = fastReflection_ParamChange_messageType{} - -type fastReflection_ParamChange_messageType struct{} - -func (x fastReflection_ParamChange_messageType) Zero() protoreflect.Message { - return (*fastReflection_ParamChange)(nil) -} -func (x fastReflection_ParamChange_messageType) New() protoreflect.Message { - return new(fastReflection_ParamChange) -} -func (x fastReflection_ParamChange_messageType) Descriptor() protoreflect.MessageDescriptor { - return md_ParamChange -} - -// Descriptor returns message descriptor, which contains only the protobuf -// type information for the message. -func (x *fastReflection_ParamChange) Descriptor() protoreflect.MessageDescriptor { - return md_ParamChange -} - -// Type returns the message type, which encapsulates both Go and protobuf -// type information. If the Go type information is not needed, -// it is recommended that the message descriptor be used instead. -func (x *fastReflection_ParamChange) Type() protoreflect.MessageType { - return _fastReflection_ParamChange_messageType -} - -// New returns a newly allocated and mutable empty message. -func (x *fastReflection_ParamChange) New() protoreflect.Message { - return new(fastReflection_ParamChange) -} - -// Interface unwraps the message reflection interface and -// returns the underlying ProtoMessage interface. -func (x *fastReflection_ParamChange) Interface() protoreflect.ProtoMessage { - return (*ParamChange)(x) -} - -// Range iterates over every populated field in an undefined order, -// calling f for each field descriptor and value encountered. -// Range returns immediately if f returns false. -// While iterating, mutating operations may only be performed -// on the current field descriptor. -func (x *fastReflection_ParamChange) Range(f func(protoreflect.FieldDescriptor, protoreflect.Value) bool) { - if x.Subspace != "" { - value := protoreflect.ValueOfString(x.Subspace) - if !f(fd_ParamChange_subspace, value) { - return - } - } - if x.Key != "" { - value := protoreflect.ValueOfString(x.Key) - if !f(fd_ParamChange_key, value) { - return - } - } - if x.Value != "" { - value := protoreflect.ValueOfString(x.Value) - if !f(fd_ParamChange_value, value) { - return - } - } -} - -// Has reports whether a field is populated. -// -// Some fields have the property of nullability where it is possible to -// distinguish between the default value of a field and whether the field -// was explicitly populated with the default value. Singular message fields, -// member fields of a oneof, and proto2 scalar fields are nullable. Such -// fields are populated only if explicitly set. -// -// In other cases (aside from the nullable cases above), -// a proto3 scalar field is populated if it contains a non-zero value, and -// a repeated field is populated if it is non-empty. -func (x *fastReflection_ParamChange) Has(fd protoreflect.FieldDescriptor) bool { - switch fd.FullName() { - case "cosmos.params.v1beta1.ParamChange.subspace": - return x.Subspace != "" - case "cosmos.params.v1beta1.ParamChange.key": - return x.Key != "" - case "cosmos.params.v1beta1.ParamChange.value": - return x.Value != "" - default: - if fd.IsExtension() { - panic(fmt.Errorf("proto3 declared messages do not support extensions: cosmos.params.v1beta1.ParamChange")) - } - panic(fmt.Errorf("message cosmos.params.v1beta1.ParamChange does not contain field %s", fd.FullName())) - } -} - -// Clear clears the field such that a subsequent Has call reports false. -// -// Clearing an extension field clears both the extension type and value -// associated with the given field number. -// -// Clear is a mutating operation and unsafe for concurrent use. -func (x *fastReflection_ParamChange) Clear(fd protoreflect.FieldDescriptor) { - switch fd.FullName() { - case "cosmos.params.v1beta1.ParamChange.subspace": - x.Subspace = "" - case "cosmos.params.v1beta1.ParamChange.key": - x.Key = "" - case "cosmos.params.v1beta1.ParamChange.value": - x.Value = "" - default: - if fd.IsExtension() { - panic(fmt.Errorf("proto3 declared messages do not support extensions: cosmos.params.v1beta1.ParamChange")) - } - panic(fmt.Errorf("message cosmos.params.v1beta1.ParamChange does not contain field %s", fd.FullName())) - } -} - -// Get retrieves the value for a field. -// -// For unpopulated scalars, it returns the default value, where -// the default value of a bytes scalar is guaranteed to be a copy. -// For unpopulated composite types, it returns an empty, read-only view -// of the value; to obtain a mutable reference, use Mutable. -func (x *fastReflection_ParamChange) Get(descriptor protoreflect.FieldDescriptor) protoreflect.Value { - switch descriptor.FullName() { - case "cosmos.params.v1beta1.ParamChange.subspace": - value := x.Subspace - return protoreflect.ValueOfString(value) - case "cosmos.params.v1beta1.ParamChange.key": - value := x.Key - return protoreflect.ValueOfString(value) - case "cosmos.params.v1beta1.ParamChange.value": - value := x.Value - return protoreflect.ValueOfString(value) - default: - if descriptor.IsExtension() { - panic(fmt.Errorf("proto3 declared messages do not support extensions: cosmos.params.v1beta1.ParamChange")) - } - panic(fmt.Errorf("message cosmos.params.v1beta1.ParamChange does not contain field %s", descriptor.FullName())) - } -} - -// Set stores the value for a field. -// -// For a field belonging to a oneof, it implicitly clears any other field -// that may be currently set within the same oneof. -// For extension fields, it implicitly stores the provided ExtensionType. -// When setting a composite type, it is unspecified whether the stored value -// aliases the source's memory in any way. If the composite value is an -// empty, read-only value, then it panics. -// -// Set is a mutating operation and unsafe for concurrent use. -func (x *fastReflection_ParamChange) Set(fd protoreflect.FieldDescriptor, value protoreflect.Value) { - switch fd.FullName() { - case "cosmos.params.v1beta1.ParamChange.subspace": - x.Subspace = value.Interface().(string) - case "cosmos.params.v1beta1.ParamChange.key": - x.Key = value.Interface().(string) - case "cosmos.params.v1beta1.ParamChange.value": - x.Value = value.Interface().(string) - default: - if fd.IsExtension() { - panic(fmt.Errorf("proto3 declared messages do not support extensions: cosmos.params.v1beta1.ParamChange")) - } - panic(fmt.Errorf("message cosmos.params.v1beta1.ParamChange does not contain field %s", fd.FullName())) - } -} - -// Mutable returns a mutable reference to a composite type. -// -// If the field is unpopulated, it may allocate a composite value. -// For a field belonging to a oneof, it implicitly clears any other field -// that may be currently set within the same oneof. -// For extension fields, it implicitly stores the provided ExtensionType -// if not already stored. -// It panics if the field does not contain a composite type. -// -// Mutable is a mutating operation and unsafe for concurrent use. -func (x *fastReflection_ParamChange) Mutable(fd protoreflect.FieldDescriptor) protoreflect.Value { - switch fd.FullName() { - case "cosmos.params.v1beta1.ParamChange.subspace": - panic(fmt.Errorf("field subspace of message cosmos.params.v1beta1.ParamChange is not mutable")) - case "cosmos.params.v1beta1.ParamChange.key": - panic(fmt.Errorf("field key of message cosmos.params.v1beta1.ParamChange is not mutable")) - case "cosmos.params.v1beta1.ParamChange.value": - panic(fmt.Errorf("field value of message cosmos.params.v1beta1.ParamChange is not mutable")) - default: - if fd.IsExtension() { - panic(fmt.Errorf("proto3 declared messages do not support extensions: cosmos.params.v1beta1.ParamChange")) - } - panic(fmt.Errorf("message cosmos.params.v1beta1.ParamChange does not contain field %s", fd.FullName())) - } -} - -// NewField returns a new value that is assignable to the field -// for the given descriptor. For scalars, this returns the default value. -// For lists, maps, and messages, this returns a new, empty, mutable value. -func (x *fastReflection_ParamChange) NewField(fd protoreflect.FieldDescriptor) protoreflect.Value { - switch fd.FullName() { - case "cosmos.params.v1beta1.ParamChange.subspace": - return protoreflect.ValueOfString("") - case "cosmos.params.v1beta1.ParamChange.key": - return protoreflect.ValueOfString("") - case "cosmos.params.v1beta1.ParamChange.value": - return protoreflect.ValueOfString("") - default: - if fd.IsExtension() { - panic(fmt.Errorf("proto3 declared messages do not support extensions: cosmos.params.v1beta1.ParamChange")) - } - panic(fmt.Errorf("message cosmos.params.v1beta1.ParamChange does not contain field %s", fd.FullName())) - } -} - -// WhichOneof reports which field within the oneof is populated, -// returning nil if none are populated. -// It panics if the oneof descriptor does not belong to this message. -func (x *fastReflection_ParamChange) WhichOneof(d protoreflect.OneofDescriptor) protoreflect.FieldDescriptor { - switch d.FullName() { - default: - panic(fmt.Errorf("%s is not a oneof field in cosmos.params.v1beta1.ParamChange", d.FullName())) - } - panic("unreachable") -} - -// GetUnknown retrieves the entire list of unknown fields. -// The caller may only mutate the contents of the RawFields -// if the mutated bytes are stored back into the message with SetUnknown. -func (x *fastReflection_ParamChange) GetUnknown() protoreflect.RawFields { - return x.unknownFields -} - -// SetUnknown stores an entire list of unknown fields. -// The raw fields must be syntactically valid according to the wire format. -// An implementation may panic if this is not the case. -// Once stored, the caller must not mutate the content of the RawFields. -// An empty RawFields may be passed to clear the fields. -// -// SetUnknown is a mutating operation and unsafe for concurrent use. -func (x *fastReflection_ParamChange) SetUnknown(fields protoreflect.RawFields) { - x.unknownFields = fields -} - -// IsValid reports whether the message is valid. -// -// An invalid message is an empty, read-only value. -// -// An invalid message often corresponds to a nil pointer of the concrete -// message type, but the details are implementation dependent. -// Validity is not part of the protobuf data model, and may not -// be preserved in marshaling or other operations. -func (x *fastReflection_ParamChange) IsValid() bool { - return x != nil -} - -// ProtoMethods returns optional fastReflectionFeature-path implementations of various operations. -// This method may return nil. -// -// The returned methods type is identical to -// "google.golang.org/protobuf/runtime/protoiface".Methods. -// Consult the protoiface package documentation for details. -func (x *fastReflection_ParamChange) ProtoMethods() *protoiface.Methods { - size := func(input protoiface.SizeInput) protoiface.SizeOutput { - x := input.Message.Interface().(*ParamChange) - if x == nil { - return protoiface.SizeOutput{ - NoUnkeyedLiterals: input.NoUnkeyedLiterals, - Size: 0, - } - } - options := runtime.SizeInputToOptions(input) - _ = options - var n int - var l int - _ = l - l = len(x.Subspace) - if l > 0 { - n += 1 + l + runtime.Sov(uint64(l)) - } - l = len(x.Key) - if l > 0 { - n += 1 + l + runtime.Sov(uint64(l)) - } - l = len(x.Value) - if l > 0 { - n += 1 + l + runtime.Sov(uint64(l)) - } - if x.unknownFields != nil { - n += len(x.unknownFields) - } - return protoiface.SizeOutput{ - NoUnkeyedLiterals: input.NoUnkeyedLiterals, - Size: n, - } - } - - marshal := func(input protoiface.MarshalInput) (protoiface.MarshalOutput, error) { - x := input.Message.Interface().(*ParamChange) - if x == nil { - return protoiface.MarshalOutput{ - NoUnkeyedLiterals: input.NoUnkeyedLiterals, - Buf: input.Buf, - }, nil - } - options := runtime.MarshalInputToOptions(input) - _ = options - size := options.Size(x) - dAtA := make([]byte, size) - i := len(dAtA) - _ = i - var l int - _ = l - if x.unknownFields != nil { - i -= len(x.unknownFields) - copy(dAtA[i:], x.unknownFields) - } - if len(x.Value) > 0 { - i -= len(x.Value) - copy(dAtA[i:], x.Value) - i = runtime.EncodeVarint(dAtA, i, uint64(len(x.Value))) - i-- - dAtA[i] = 0x1a - } - if len(x.Key) > 0 { - i -= len(x.Key) - copy(dAtA[i:], x.Key) - i = runtime.EncodeVarint(dAtA, i, uint64(len(x.Key))) - i-- - dAtA[i] = 0x12 - } - if len(x.Subspace) > 0 { - i -= len(x.Subspace) - copy(dAtA[i:], x.Subspace) - i = runtime.EncodeVarint(dAtA, i, uint64(len(x.Subspace))) - i-- - dAtA[i] = 0xa - } - if input.Buf != nil { - input.Buf = append(input.Buf, dAtA...) - } else { - input.Buf = dAtA - } - return protoiface.MarshalOutput{ - NoUnkeyedLiterals: input.NoUnkeyedLiterals, - Buf: input.Buf, - }, nil - } - unmarshal := func(input protoiface.UnmarshalInput) (protoiface.UnmarshalOutput, error) { - x := input.Message.Interface().(*ParamChange) - if x == nil { - return protoiface.UnmarshalOutput{ - NoUnkeyedLiterals: input.NoUnkeyedLiterals, - Flags: input.Flags, - }, nil - } - options := runtime.UnmarshalInputToOptions(input) - _ = options - dAtA := input.Buf - l := len(dAtA) - iNdEx := 0 - for iNdEx < l { - preIndex := iNdEx - var wire uint64 - for shift := uint(0); ; shift += 7 { - if shift >= 64 { - return protoiface.UnmarshalOutput{NoUnkeyedLiterals: input.NoUnkeyedLiterals, Flags: input.Flags}, runtime.ErrIntOverflow - } - if iNdEx >= l { - return protoiface.UnmarshalOutput{NoUnkeyedLiterals: input.NoUnkeyedLiterals, Flags: input.Flags}, io.ErrUnexpectedEOF - } - b := dAtA[iNdEx] - iNdEx++ - wire |= uint64(b&0x7F) << shift - if b < 0x80 { - break - } - } - fieldNum := int32(wire >> 3) - wireType := int(wire & 0x7) - if wireType == 4 { - return protoiface.UnmarshalOutput{NoUnkeyedLiterals: input.NoUnkeyedLiterals, Flags: input.Flags}, fmt.Errorf("proto: ParamChange: wiretype end group for non-group") - } - if fieldNum <= 0 { - return protoiface.UnmarshalOutput{NoUnkeyedLiterals: input.NoUnkeyedLiterals, Flags: input.Flags}, fmt.Errorf("proto: ParamChange: illegal tag %d (wire type %d)", fieldNum, wire) - } - switch fieldNum { - case 1: - if wireType != 2 { - return protoiface.UnmarshalOutput{NoUnkeyedLiterals: input.NoUnkeyedLiterals, Flags: input.Flags}, fmt.Errorf("proto: wrong wireType = %d for field Subspace", wireType) - } - var stringLen uint64 - for shift := uint(0); ; shift += 7 { - if shift >= 64 { - return protoiface.UnmarshalOutput{NoUnkeyedLiterals: input.NoUnkeyedLiterals, Flags: input.Flags}, runtime.ErrIntOverflow - } - if iNdEx >= l { - return protoiface.UnmarshalOutput{NoUnkeyedLiterals: input.NoUnkeyedLiterals, Flags: input.Flags}, io.ErrUnexpectedEOF - } - b := dAtA[iNdEx] - iNdEx++ - stringLen |= uint64(b&0x7F) << shift - if b < 0x80 { - break - } - } - intStringLen := int(stringLen) - if intStringLen < 0 { - return protoiface.UnmarshalOutput{NoUnkeyedLiterals: input.NoUnkeyedLiterals, Flags: input.Flags}, runtime.ErrInvalidLength - } - postIndex := iNdEx + intStringLen - if postIndex < 0 { - return protoiface.UnmarshalOutput{NoUnkeyedLiterals: input.NoUnkeyedLiterals, Flags: input.Flags}, runtime.ErrInvalidLength - } - if postIndex > l { - return protoiface.UnmarshalOutput{NoUnkeyedLiterals: input.NoUnkeyedLiterals, Flags: input.Flags}, io.ErrUnexpectedEOF - } - x.Subspace = string(dAtA[iNdEx:postIndex]) - iNdEx = postIndex - case 2: - if wireType != 2 { - return protoiface.UnmarshalOutput{NoUnkeyedLiterals: input.NoUnkeyedLiterals, Flags: input.Flags}, fmt.Errorf("proto: wrong wireType = %d for field Key", wireType) - } - var stringLen uint64 - for shift := uint(0); ; shift += 7 { - if shift >= 64 { - return protoiface.UnmarshalOutput{NoUnkeyedLiterals: input.NoUnkeyedLiterals, Flags: input.Flags}, runtime.ErrIntOverflow - } - if iNdEx >= l { - return protoiface.UnmarshalOutput{NoUnkeyedLiterals: input.NoUnkeyedLiterals, Flags: input.Flags}, io.ErrUnexpectedEOF - } - b := dAtA[iNdEx] - iNdEx++ - stringLen |= uint64(b&0x7F) << shift - if b < 0x80 { - break - } - } - intStringLen := int(stringLen) - if intStringLen < 0 { - return protoiface.UnmarshalOutput{NoUnkeyedLiterals: input.NoUnkeyedLiterals, Flags: input.Flags}, runtime.ErrInvalidLength - } - postIndex := iNdEx + intStringLen - if postIndex < 0 { - return protoiface.UnmarshalOutput{NoUnkeyedLiterals: input.NoUnkeyedLiterals, Flags: input.Flags}, runtime.ErrInvalidLength - } - if postIndex > l { - return protoiface.UnmarshalOutput{NoUnkeyedLiterals: input.NoUnkeyedLiterals, Flags: input.Flags}, io.ErrUnexpectedEOF - } - x.Key = string(dAtA[iNdEx:postIndex]) - iNdEx = postIndex - case 3: - if wireType != 2 { - return protoiface.UnmarshalOutput{NoUnkeyedLiterals: input.NoUnkeyedLiterals, Flags: input.Flags}, fmt.Errorf("proto: wrong wireType = %d for field Value", wireType) - } - var stringLen uint64 - for shift := uint(0); ; shift += 7 { - if shift >= 64 { - return protoiface.UnmarshalOutput{NoUnkeyedLiterals: input.NoUnkeyedLiterals, Flags: input.Flags}, runtime.ErrIntOverflow - } - if iNdEx >= l { - return protoiface.UnmarshalOutput{NoUnkeyedLiterals: input.NoUnkeyedLiterals, Flags: input.Flags}, io.ErrUnexpectedEOF - } - b := dAtA[iNdEx] - iNdEx++ - stringLen |= uint64(b&0x7F) << shift - if b < 0x80 { - break - } - } - intStringLen := int(stringLen) - if intStringLen < 0 { - return protoiface.UnmarshalOutput{NoUnkeyedLiterals: input.NoUnkeyedLiterals, Flags: input.Flags}, runtime.ErrInvalidLength - } - postIndex := iNdEx + intStringLen - if postIndex < 0 { - return protoiface.UnmarshalOutput{NoUnkeyedLiterals: input.NoUnkeyedLiterals, Flags: input.Flags}, runtime.ErrInvalidLength - } - if postIndex > l { - return protoiface.UnmarshalOutput{NoUnkeyedLiterals: input.NoUnkeyedLiterals, Flags: input.Flags}, io.ErrUnexpectedEOF - } - x.Value = string(dAtA[iNdEx:postIndex]) - iNdEx = postIndex - default: - iNdEx = preIndex - skippy, err := runtime.Skip(dAtA[iNdEx:]) - if err != nil { - return protoiface.UnmarshalOutput{NoUnkeyedLiterals: input.NoUnkeyedLiterals, Flags: input.Flags}, err - } - if (skippy < 0) || (iNdEx+skippy) < 0 { - return protoiface.UnmarshalOutput{NoUnkeyedLiterals: input.NoUnkeyedLiterals, Flags: input.Flags}, runtime.ErrInvalidLength - } - if (iNdEx + skippy) > l { - return protoiface.UnmarshalOutput{NoUnkeyedLiterals: input.NoUnkeyedLiterals, Flags: input.Flags}, io.ErrUnexpectedEOF - } - if !options.DiscardUnknown { - x.unknownFields = append(x.unknownFields, dAtA[iNdEx:iNdEx+skippy]...) - } - iNdEx += skippy - } - } - - if iNdEx > l { - return protoiface.UnmarshalOutput{NoUnkeyedLiterals: input.NoUnkeyedLiterals, Flags: input.Flags}, io.ErrUnexpectedEOF - } - return protoiface.UnmarshalOutput{NoUnkeyedLiterals: input.NoUnkeyedLiterals, Flags: input.Flags}, nil - } - return &protoiface.Methods{ - NoUnkeyedLiterals: struct{}{}, - Flags: protoiface.SupportMarshalDeterministic | protoiface.SupportUnmarshalDiscardUnknown, - Size: size, - Marshal: marshal, - Unmarshal: unmarshal, - Merge: nil, - CheckInitialized: nil, - } -} - -// Code generated by protoc-gen-go. DO NOT EDIT. -// versions: -// protoc-gen-go v1.27.0 -// protoc (unknown) -// source: cosmos/params/v1beta1/params.proto - -const ( - // Verify that this generated code is sufficiently up-to-date. - _ = protoimpl.EnforceVersion(20 - protoimpl.MinVersion) - // Verify that runtime/protoimpl is sufficiently up-to-date. - _ = protoimpl.EnforceVersion(protoimpl.MaxVersion - 20) -) - -// ParameterChangeProposal defines a proposal to change one or more parameters. -type ParameterChangeProposal struct { - state protoimpl.MessageState - sizeCache protoimpl.SizeCache - unknownFields protoimpl.UnknownFields - - Title string `protobuf:"bytes,1,opt,name=title,proto3" json:"title,omitempty"` - Description string `protobuf:"bytes,2,opt,name=description,proto3" json:"description,omitempty"` - Changes []*ParamChange `protobuf:"bytes,3,rep,name=changes,proto3" json:"changes,omitempty"` -} - -func (x *ParameterChangeProposal) Reset() { - *x = ParameterChangeProposal{} - if protoimpl.UnsafeEnabled { - mi := &file_cosmos_params_v1beta1_params_proto_msgTypes[0] - ms := protoimpl.X.MessageStateOf(protoimpl.Pointer(x)) - ms.StoreMessageInfo(mi) - } -} - -func (x *ParameterChangeProposal) String() string { - return protoimpl.X.MessageStringOf(x) -} - -func (*ParameterChangeProposal) ProtoMessage() {} - -// Deprecated: Use ParameterChangeProposal.ProtoReflect.Descriptor instead. -func (*ParameterChangeProposal) Descriptor() ([]byte, []int) { - return file_cosmos_params_v1beta1_params_proto_rawDescGZIP(), []int{0} -} - -func (x *ParameterChangeProposal) GetTitle() string { - if x != nil { - return x.Title - } - return "" -} - -func (x *ParameterChangeProposal) GetDescription() string { - if x != nil { - return x.Description - } - return "" -} - -func (x *ParameterChangeProposal) GetChanges() []*ParamChange { - if x != nil { - return x.Changes - } - return nil -} - -// ParamChange defines an individual parameter change, for use in -// ParameterChangeProposal. -type ParamChange struct { - state protoimpl.MessageState - sizeCache protoimpl.SizeCache - unknownFields protoimpl.UnknownFields - - Subspace string `protobuf:"bytes,1,opt,name=subspace,proto3" json:"subspace,omitempty"` - Key string `protobuf:"bytes,2,opt,name=key,proto3" json:"key,omitempty"` - Value string `protobuf:"bytes,3,opt,name=value,proto3" json:"value,omitempty"` -} - -func (x *ParamChange) Reset() { - *x = ParamChange{} - if protoimpl.UnsafeEnabled { - mi := &file_cosmos_params_v1beta1_params_proto_msgTypes[1] - ms := protoimpl.X.MessageStateOf(protoimpl.Pointer(x)) - ms.StoreMessageInfo(mi) - } -} - -func (x *ParamChange) String() string { - return protoimpl.X.MessageStringOf(x) -} - -func (*ParamChange) ProtoMessage() {} - -// Deprecated: Use ParamChange.ProtoReflect.Descriptor instead. -func (*ParamChange) Descriptor() ([]byte, []int) { - return file_cosmos_params_v1beta1_params_proto_rawDescGZIP(), []int{1} -} - -func (x *ParamChange) GetSubspace() string { - if x != nil { - return x.Subspace - } - return "" -} - -func (x *ParamChange) GetKey() string { - if x != nil { - return x.Key - } - return "" -} - -func (x *ParamChange) GetValue() string { - if x != nil { - return x.Value - } - return "" -} - -var File_cosmos_params_v1beta1_params_proto protoreflect.FileDescriptor - -var file_cosmos_params_v1beta1_params_proto_rawDesc = []byte{ - 0x0a, 0x22, 0x63, 0x6f, 0x73, 0x6d, 0x6f, 0x73, 0x2f, 0x70, 0x61, 0x72, 0x61, 0x6d, 0x73, 0x2f, - 0x76, 0x31, 0x62, 0x65, 0x74, 0x61, 0x31, 0x2f, 0x70, 0x61, 0x72, 0x61, 0x6d, 0x73, 0x2e, 0x70, - 0x72, 0x6f, 0x74, 0x6f, 0x12, 0x15, 0x63, 0x6f, 0x73, 0x6d, 0x6f, 0x73, 0x2e, 0x70, 0x61, 0x72, - 0x61, 0x6d, 0x73, 0x2e, 0x76, 0x31, 0x62, 0x65, 0x74, 0x61, 0x31, 0x1a, 0x14, 0x67, 0x6f, 0x67, - 0x6f, 0x70, 0x72, 0x6f, 0x74, 0x6f, 0x2f, 0x67, 0x6f, 0x67, 0x6f, 0x2e, 0x70, 0x72, 0x6f, 0x74, - 0x6f, 0x1a, 0x19, 0x63, 0x6f, 0x73, 0x6d, 0x6f, 0x73, 0x5f, 0x70, 0x72, 0x6f, 0x74, 0x6f, 0x2f, - 0x63, 0x6f, 0x73, 0x6d, 0x6f, 0x73, 0x2e, 0x70, 0x72, 0x6f, 0x74, 0x6f, 0x1a, 0x11, 0x61, 0x6d, - 0x69, 0x6e, 0x6f, 0x2f, 0x61, 0x6d, 0x69, 0x6e, 0x6f, 0x2e, 0x70, 0x72, 0x6f, 0x74, 0x6f, 0x22, - 0xe5, 0x01, 0x0a, 0x17, 0x50, 0x61, 0x72, 0x61, 0x6d, 0x65, 0x74, 0x65, 0x72, 0x43, 0x68, 0x61, - 0x6e, 0x67, 0x65, 0x50, 0x72, 0x6f, 0x70, 0x6f, 0x73, 0x61, 0x6c, 0x12, 0x14, 0x0a, 0x05, 0x74, - 0x69, 0x74, 0x6c, 0x65, 0x18, 0x01, 0x20, 0x01, 0x28, 0x09, 0x52, 0x05, 0x74, 0x69, 0x74, 0x6c, - 0x65, 0x12, 0x20, 0x0a, 0x0b, 0x64, 0x65, 0x73, 0x63, 0x72, 0x69, 0x70, 0x74, 0x69, 0x6f, 0x6e, - 0x18, 0x02, 0x20, 0x01, 0x28, 0x09, 0x52, 0x0b, 0x64, 0x65, 0x73, 0x63, 0x72, 0x69, 0x70, 0x74, - 0x69, 0x6f, 0x6e, 0x12, 0x47, 0x0a, 0x07, 0x63, 0x68, 0x61, 0x6e, 0x67, 0x65, 0x73, 0x18, 0x03, - 0x20, 0x03, 0x28, 0x0b, 0x32, 0x22, 0x2e, 0x63, 0x6f, 0x73, 0x6d, 0x6f, 0x73, 0x2e, 0x70, 0x61, - 0x72, 0x61, 0x6d, 0x73, 0x2e, 0x76, 0x31, 0x62, 0x65, 0x74, 0x61, 0x31, 0x2e, 0x50, 0x61, 0x72, - 0x61, 0x6d, 0x43, 0x68, 0x61, 0x6e, 0x67, 0x65, 0x42, 0x09, 0xc8, 0xde, 0x1f, 0x00, 0xa8, 0xe7, - 0xb0, 0x2a, 0x01, 0x52, 0x07, 0x63, 0x68, 0x61, 0x6e, 0x67, 0x65, 0x73, 0x3a, 0x49, 0x88, 0xa0, - 0x1f, 0x00, 0xca, 0xb4, 0x2d, 0x1a, 0x63, 0x6f, 0x73, 0x6d, 0x6f, 0x73, 0x2e, 0x67, 0x6f, 0x76, - 0x2e, 0x76, 0x31, 0x62, 0x65, 0x74, 0x61, 0x31, 0x2e, 0x43, 0x6f, 0x6e, 0x74, 0x65, 0x6e, 0x74, - 0x8a, 0xe7, 0xb0, 0x2a, 0x22, 0x63, 0x6f, 0x73, 0x6d, 0x6f, 0x73, 0x2d, 0x73, 0x64, 0x6b, 0x2f, - 0x50, 0x61, 0x72, 0x61, 0x6d, 0x65, 0x74, 0x65, 0x72, 0x43, 0x68, 0x61, 0x6e, 0x67, 0x65, 0x50, - 0x72, 0x6f, 0x70, 0x6f, 0x73, 0x61, 0x6c, 0x22, 0x51, 0x0a, 0x0b, 0x50, 0x61, 0x72, 0x61, 0x6d, - 0x43, 0x68, 0x61, 0x6e, 0x67, 0x65, 0x12, 0x1a, 0x0a, 0x08, 0x73, 0x75, 0x62, 0x73, 0x70, 0x61, - 0x63, 0x65, 0x18, 0x01, 0x20, 0x01, 0x28, 0x09, 0x52, 0x08, 0x73, 0x75, 0x62, 0x73, 0x70, 0x61, - 0x63, 0x65, 0x12, 0x10, 0x0a, 0x03, 0x6b, 0x65, 0x79, 0x18, 0x02, 0x20, 0x01, 0x28, 0x09, 0x52, - 0x03, 0x6b, 0x65, 0x79, 0x12, 0x14, 0x0a, 0x05, 0x76, 0x61, 0x6c, 0x75, 0x65, 0x18, 0x03, 0x20, - 0x01, 0x28, 0x09, 0x52, 0x05, 0x76, 0x61, 0x6c, 0x75, 0x65, 0x42, 0xd8, 0x01, 0xa8, 0xe2, 0x1e, - 0x01, 0x0a, 0x19, 0x63, 0x6f, 0x6d, 0x2e, 0x63, 0x6f, 0x73, 0x6d, 0x6f, 0x73, 0x2e, 0x70, 0x61, - 0x72, 0x61, 0x6d, 0x73, 0x2e, 0x76, 0x31, 0x62, 0x65, 0x74, 0x61, 0x31, 0x42, 0x0b, 0x50, 0x61, - 0x72, 0x61, 0x6d, 0x73, 0x50, 0x72, 0x6f, 0x74, 0x6f, 0x50, 0x01, 0x5a, 0x34, 0x63, 0x6f, 0x73, - 0x6d, 0x6f, 0x73, 0x73, 0x64, 0x6b, 0x2e, 0x69, 0x6f, 0x2f, 0x61, 0x70, 0x69, 0x2f, 0x63, 0x6f, - 0x73, 0x6d, 0x6f, 0x73, 0x2f, 0x70, 0x61, 0x72, 0x61, 0x6d, 0x73, 0x2f, 0x76, 0x31, 0x62, 0x65, - 0x74, 0x61, 0x31, 0x3b, 0x70, 0x61, 0x72, 0x61, 0x6d, 0x73, 0x76, 0x31, 0x62, 0x65, 0x74, 0x61, - 0x31, 0xa2, 0x02, 0x03, 0x43, 0x50, 0x58, 0xaa, 0x02, 0x15, 0x43, 0x6f, 0x73, 0x6d, 0x6f, 0x73, - 0x2e, 0x50, 0x61, 0x72, 0x61, 0x6d, 0x73, 0x2e, 0x56, 0x31, 0x62, 0x65, 0x74, 0x61, 0x31, 0xca, - 0x02, 0x15, 0x43, 0x6f, 0x73, 0x6d, 0x6f, 0x73, 0x5c, 0x50, 0x61, 0x72, 0x61, 0x6d, 0x73, 0x5c, - 0x56, 0x31, 0x62, 0x65, 0x74, 0x61, 0x31, 0xe2, 0x02, 0x21, 0x43, 0x6f, 0x73, 0x6d, 0x6f, 0x73, - 0x5c, 0x50, 0x61, 0x72, 0x61, 0x6d, 0x73, 0x5c, 0x56, 0x31, 0x62, 0x65, 0x74, 0x61, 0x31, 0x5c, - 0x47, 0x50, 0x42, 0x4d, 0x65, 0x74, 0x61, 0x64, 0x61, 0x74, 0x61, 0xea, 0x02, 0x17, 0x43, 0x6f, - 0x73, 0x6d, 0x6f, 0x73, 0x3a, 0x3a, 0x50, 0x61, 0x72, 0x61, 0x6d, 0x73, 0x3a, 0x3a, 0x56, 0x31, - 0x62, 0x65, 0x74, 0x61, 0x31, 0x62, 0x06, 0x70, 0x72, 0x6f, 0x74, 0x6f, 0x33, -} - -var ( - file_cosmos_params_v1beta1_params_proto_rawDescOnce sync.Once - file_cosmos_params_v1beta1_params_proto_rawDescData = file_cosmos_params_v1beta1_params_proto_rawDesc -) - -func file_cosmos_params_v1beta1_params_proto_rawDescGZIP() []byte { - file_cosmos_params_v1beta1_params_proto_rawDescOnce.Do(func() { - file_cosmos_params_v1beta1_params_proto_rawDescData = protoimpl.X.CompressGZIP(file_cosmos_params_v1beta1_params_proto_rawDescData) - }) - return file_cosmos_params_v1beta1_params_proto_rawDescData -} - -var file_cosmos_params_v1beta1_params_proto_msgTypes = make([]protoimpl.MessageInfo, 2) -var file_cosmos_params_v1beta1_params_proto_goTypes = []interface{}{ - (*ParameterChangeProposal)(nil), // 0: cosmos.params.v1beta1.ParameterChangeProposal - (*ParamChange)(nil), // 1: cosmos.params.v1beta1.ParamChange -} -var file_cosmos_params_v1beta1_params_proto_depIdxs = []int32{ - 1, // 0: cosmos.params.v1beta1.ParameterChangeProposal.changes:type_name -> cosmos.params.v1beta1.ParamChange - 1, // [1:1] is the sub-list for method output_type - 1, // [1:1] is the sub-list for method input_type - 1, // [1:1] is the sub-list for extension type_name - 1, // [1:1] is the sub-list for extension extendee - 0, // [0:1] is the sub-list for field type_name -} - -func init() { file_cosmos_params_v1beta1_params_proto_init() } -func file_cosmos_params_v1beta1_params_proto_init() { - if File_cosmos_params_v1beta1_params_proto != nil { - return - } - if !protoimpl.UnsafeEnabled { - file_cosmos_params_v1beta1_params_proto_msgTypes[0].Exporter = func(v interface{}, i int) interface{} { - switch v := v.(*ParameterChangeProposal); i { - case 0: - return &v.state - case 1: - return &v.sizeCache - case 2: - return &v.unknownFields - default: - return nil - } - } - file_cosmos_params_v1beta1_params_proto_msgTypes[1].Exporter = func(v interface{}, i int) interface{} { - switch v := v.(*ParamChange); i { - case 0: - return &v.state - case 1: - return &v.sizeCache - case 2: - return &v.unknownFields - default: - return nil - } - } - } - type x struct{} - out := protoimpl.TypeBuilder{ - File: protoimpl.DescBuilder{ - GoPackagePath: reflect.TypeOf(x{}).PkgPath(), - RawDescriptor: file_cosmos_params_v1beta1_params_proto_rawDesc, - NumEnums: 0, - NumMessages: 2, - NumExtensions: 0, - NumServices: 0, - }, - GoTypes: file_cosmos_params_v1beta1_params_proto_goTypes, - DependencyIndexes: file_cosmos_params_v1beta1_params_proto_depIdxs, - MessageInfos: file_cosmos_params_v1beta1_params_proto_msgTypes, - }.Build() - File_cosmos_params_v1beta1_params_proto = out.File - file_cosmos_params_v1beta1_params_proto_rawDesc = nil - file_cosmos_params_v1beta1_params_proto_goTypes = nil - file_cosmos_params_v1beta1_params_proto_depIdxs = nil -} diff --git a/api/cosmos/params/v1beta1/query.pulsar.go b/api/cosmos/params/v1beta1/query.pulsar.go deleted file mode 100644 index 24026f5c0d8c..000000000000 --- a/api/cosmos/params/v1beta1/query.pulsar.go +++ /dev/null @@ -1,2735 +0,0 @@ -// Code generated by protoc-gen-go-pulsar. DO NOT EDIT. -package paramsv1beta1 - -import ( - _ "cosmossdk.io/api/amino" - fmt "fmt" - _ "github.com/cosmos/cosmos-proto" - runtime "github.com/cosmos/cosmos-proto/runtime" - _ "github.com/cosmos/gogoproto/gogoproto" - _ "google.golang.org/genproto/googleapis/api/annotations" - protoreflect "google.golang.org/protobuf/reflect/protoreflect" - protoiface "google.golang.org/protobuf/runtime/protoiface" - protoimpl "google.golang.org/protobuf/runtime/protoimpl" - io "io" - reflect "reflect" - sync "sync" -) - -var ( - md_QueryParamsRequest protoreflect.MessageDescriptor - fd_QueryParamsRequest_subspace protoreflect.FieldDescriptor - fd_QueryParamsRequest_key protoreflect.FieldDescriptor -) - -func init() { - file_cosmos_params_v1beta1_query_proto_init() - md_QueryParamsRequest = File_cosmos_params_v1beta1_query_proto.Messages().ByName("QueryParamsRequest") - fd_QueryParamsRequest_subspace = md_QueryParamsRequest.Fields().ByName("subspace") - fd_QueryParamsRequest_key = md_QueryParamsRequest.Fields().ByName("key") -} - -var _ protoreflect.Message = (*fastReflection_QueryParamsRequest)(nil) - -type fastReflection_QueryParamsRequest QueryParamsRequest - -func (x *QueryParamsRequest) ProtoReflect() protoreflect.Message { - return (*fastReflection_QueryParamsRequest)(x) -} - -func (x *QueryParamsRequest) slowProtoReflect() protoreflect.Message { - mi := &file_cosmos_params_v1beta1_query_proto_msgTypes[0] - if protoimpl.UnsafeEnabled && x != nil { - ms := protoimpl.X.MessageStateOf(protoimpl.Pointer(x)) - if ms.LoadMessageInfo() == nil { - ms.StoreMessageInfo(mi) - } - return ms - } - return mi.MessageOf(x) -} - -var _fastReflection_QueryParamsRequest_messageType fastReflection_QueryParamsRequest_messageType -var _ protoreflect.MessageType = fastReflection_QueryParamsRequest_messageType{} - -type fastReflection_QueryParamsRequest_messageType struct{} - -func (x fastReflection_QueryParamsRequest_messageType) Zero() protoreflect.Message { - return (*fastReflection_QueryParamsRequest)(nil) -} -func (x fastReflection_QueryParamsRequest_messageType) New() protoreflect.Message { - return new(fastReflection_QueryParamsRequest) -} -func (x fastReflection_QueryParamsRequest_messageType) Descriptor() protoreflect.MessageDescriptor { - return md_QueryParamsRequest -} - -// Descriptor returns message descriptor, which contains only the protobuf -// type information for the message. -func (x *fastReflection_QueryParamsRequest) Descriptor() protoreflect.MessageDescriptor { - return md_QueryParamsRequest -} - -// Type returns the message type, which encapsulates both Go and protobuf -// type information. If the Go type information is not needed, -// it is recommended that the message descriptor be used instead. -func (x *fastReflection_QueryParamsRequest) Type() protoreflect.MessageType { - return _fastReflection_QueryParamsRequest_messageType -} - -// New returns a newly allocated and mutable empty message. -func (x *fastReflection_QueryParamsRequest) New() protoreflect.Message { - return new(fastReflection_QueryParamsRequest) -} - -// Interface unwraps the message reflection interface and -// returns the underlying ProtoMessage interface. -func (x *fastReflection_QueryParamsRequest) Interface() protoreflect.ProtoMessage { - return (*QueryParamsRequest)(x) -} - -// Range iterates over every populated field in an undefined order, -// calling f for each field descriptor and value encountered. -// Range returns immediately if f returns false. -// While iterating, mutating operations may only be performed -// on the current field descriptor. -func (x *fastReflection_QueryParamsRequest) Range(f func(protoreflect.FieldDescriptor, protoreflect.Value) bool) { - if x.Subspace != "" { - value := protoreflect.ValueOfString(x.Subspace) - if !f(fd_QueryParamsRequest_subspace, value) { - return - } - } - if x.Key != "" { - value := protoreflect.ValueOfString(x.Key) - if !f(fd_QueryParamsRequest_key, value) { - return - } - } -} - -// Has reports whether a field is populated. -// -// Some fields have the property of nullability where it is possible to -// distinguish between the default value of a field and whether the field -// was explicitly populated with the default value. Singular message fields, -// member fields of a oneof, and proto2 scalar fields are nullable. Such -// fields are populated only if explicitly set. -// -// In other cases (aside from the nullable cases above), -// a proto3 scalar field is populated if it contains a non-zero value, and -// a repeated field is populated if it is non-empty. -func (x *fastReflection_QueryParamsRequest) Has(fd protoreflect.FieldDescriptor) bool { - switch fd.FullName() { - case "cosmos.params.v1beta1.QueryParamsRequest.subspace": - return x.Subspace != "" - case "cosmos.params.v1beta1.QueryParamsRequest.key": - return x.Key != "" - default: - if fd.IsExtension() { - panic(fmt.Errorf("proto3 declared messages do not support extensions: cosmos.params.v1beta1.QueryParamsRequest")) - } - panic(fmt.Errorf("message cosmos.params.v1beta1.QueryParamsRequest does not contain field %s", fd.FullName())) - } -} - -// Clear clears the field such that a subsequent Has call reports false. -// -// Clearing an extension field clears both the extension type and value -// associated with the given field number. -// -// Clear is a mutating operation and unsafe for concurrent use. -func (x *fastReflection_QueryParamsRequest) Clear(fd protoreflect.FieldDescriptor) { - switch fd.FullName() { - case "cosmos.params.v1beta1.QueryParamsRequest.subspace": - x.Subspace = "" - case "cosmos.params.v1beta1.QueryParamsRequest.key": - x.Key = "" - default: - if fd.IsExtension() { - panic(fmt.Errorf("proto3 declared messages do not support extensions: cosmos.params.v1beta1.QueryParamsRequest")) - } - panic(fmt.Errorf("message cosmos.params.v1beta1.QueryParamsRequest does not contain field %s", fd.FullName())) - } -} - -// Get retrieves the value for a field. -// -// For unpopulated scalars, it returns the default value, where -// the default value of a bytes scalar is guaranteed to be a copy. -// For unpopulated composite types, it returns an empty, read-only view -// of the value; to obtain a mutable reference, use Mutable. -func (x *fastReflection_QueryParamsRequest) Get(descriptor protoreflect.FieldDescriptor) protoreflect.Value { - switch descriptor.FullName() { - case "cosmos.params.v1beta1.QueryParamsRequest.subspace": - value := x.Subspace - return protoreflect.ValueOfString(value) - case "cosmos.params.v1beta1.QueryParamsRequest.key": - value := x.Key - return protoreflect.ValueOfString(value) - default: - if descriptor.IsExtension() { - panic(fmt.Errorf("proto3 declared messages do not support extensions: cosmos.params.v1beta1.QueryParamsRequest")) - } - panic(fmt.Errorf("message cosmos.params.v1beta1.QueryParamsRequest does not contain field %s", descriptor.FullName())) - } -} - -// Set stores the value for a field. -// -// For a field belonging to a oneof, it implicitly clears any other field -// that may be currently set within the same oneof. -// For extension fields, it implicitly stores the provided ExtensionType. -// When setting a composite type, it is unspecified whether the stored value -// aliases the source's memory in any way. If the composite value is an -// empty, read-only value, then it panics. -// -// Set is a mutating operation and unsafe for concurrent use. -func (x *fastReflection_QueryParamsRequest) Set(fd protoreflect.FieldDescriptor, value protoreflect.Value) { - switch fd.FullName() { - case "cosmos.params.v1beta1.QueryParamsRequest.subspace": - x.Subspace = value.Interface().(string) - case "cosmos.params.v1beta1.QueryParamsRequest.key": - x.Key = value.Interface().(string) - default: - if fd.IsExtension() { - panic(fmt.Errorf("proto3 declared messages do not support extensions: cosmos.params.v1beta1.QueryParamsRequest")) - } - panic(fmt.Errorf("message cosmos.params.v1beta1.QueryParamsRequest does not contain field %s", fd.FullName())) - } -} - -// Mutable returns a mutable reference to a composite type. -// -// If the field is unpopulated, it may allocate a composite value. -// For a field belonging to a oneof, it implicitly clears any other field -// that may be currently set within the same oneof. -// For extension fields, it implicitly stores the provided ExtensionType -// if not already stored. -// It panics if the field does not contain a composite type. -// -// Mutable is a mutating operation and unsafe for concurrent use. -func (x *fastReflection_QueryParamsRequest) Mutable(fd protoreflect.FieldDescriptor) protoreflect.Value { - switch fd.FullName() { - case "cosmos.params.v1beta1.QueryParamsRequest.subspace": - panic(fmt.Errorf("field subspace of message cosmos.params.v1beta1.QueryParamsRequest is not mutable")) - case "cosmos.params.v1beta1.QueryParamsRequest.key": - panic(fmt.Errorf("field key of message cosmos.params.v1beta1.QueryParamsRequest is not mutable")) - default: - if fd.IsExtension() { - panic(fmt.Errorf("proto3 declared messages do not support extensions: cosmos.params.v1beta1.QueryParamsRequest")) - } - panic(fmt.Errorf("message cosmos.params.v1beta1.QueryParamsRequest does not contain field %s", fd.FullName())) - } -} - -// NewField returns a new value that is assignable to the field -// for the given descriptor. For scalars, this returns the default value. -// For lists, maps, and messages, this returns a new, empty, mutable value. -func (x *fastReflection_QueryParamsRequest) NewField(fd protoreflect.FieldDescriptor) protoreflect.Value { - switch fd.FullName() { - case "cosmos.params.v1beta1.QueryParamsRequest.subspace": - return protoreflect.ValueOfString("") - case "cosmos.params.v1beta1.QueryParamsRequest.key": - return protoreflect.ValueOfString("") - default: - if fd.IsExtension() { - panic(fmt.Errorf("proto3 declared messages do not support extensions: cosmos.params.v1beta1.QueryParamsRequest")) - } - panic(fmt.Errorf("message cosmos.params.v1beta1.QueryParamsRequest does not contain field %s", fd.FullName())) - } -} - -// WhichOneof reports which field within the oneof is populated, -// returning nil if none are populated. -// It panics if the oneof descriptor does not belong to this message. -func (x *fastReflection_QueryParamsRequest) WhichOneof(d protoreflect.OneofDescriptor) protoreflect.FieldDescriptor { - switch d.FullName() { - default: - panic(fmt.Errorf("%s is not a oneof field in cosmos.params.v1beta1.QueryParamsRequest", d.FullName())) - } - panic("unreachable") -} - -// GetUnknown retrieves the entire list of unknown fields. -// The caller may only mutate the contents of the RawFields -// if the mutated bytes are stored back into the message with SetUnknown. -func (x *fastReflection_QueryParamsRequest) GetUnknown() protoreflect.RawFields { - return x.unknownFields -} - -// SetUnknown stores an entire list of unknown fields. -// The raw fields must be syntactically valid according to the wire format. -// An implementation may panic if this is not the case. -// Once stored, the caller must not mutate the content of the RawFields. -// An empty RawFields may be passed to clear the fields. -// -// SetUnknown is a mutating operation and unsafe for concurrent use. -func (x *fastReflection_QueryParamsRequest) SetUnknown(fields protoreflect.RawFields) { - x.unknownFields = fields -} - -// IsValid reports whether the message is valid. -// -// An invalid message is an empty, read-only value. -// -// An invalid message often corresponds to a nil pointer of the concrete -// message type, but the details are implementation dependent. -// Validity is not part of the protobuf data model, and may not -// be preserved in marshaling or other operations. -func (x *fastReflection_QueryParamsRequest) IsValid() bool { - return x != nil -} - -// ProtoMethods returns optional fastReflectionFeature-path implementations of various operations. -// This method may return nil. -// -// The returned methods type is identical to -// "google.golang.org/protobuf/runtime/protoiface".Methods. -// Consult the protoiface package documentation for details. -func (x *fastReflection_QueryParamsRequest) ProtoMethods() *protoiface.Methods { - size := func(input protoiface.SizeInput) protoiface.SizeOutput { - x := input.Message.Interface().(*QueryParamsRequest) - if x == nil { - return protoiface.SizeOutput{ - NoUnkeyedLiterals: input.NoUnkeyedLiterals, - Size: 0, - } - } - options := runtime.SizeInputToOptions(input) - _ = options - var n int - var l int - _ = l - l = len(x.Subspace) - if l > 0 { - n += 1 + l + runtime.Sov(uint64(l)) - } - l = len(x.Key) - if l > 0 { - n += 1 + l + runtime.Sov(uint64(l)) - } - if x.unknownFields != nil { - n += len(x.unknownFields) - } - return protoiface.SizeOutput{ - NoUnkeyedLiterals: input.NoUnkeyedLiterals, - Size: n, - } - } - - marshal := func(input protoiface.MarshalInput) (protoiface.MarshalOutput, error) { - x := input.Message.Interface().(*QueryParamsRequest) - if x == nil { - return protoiface.MarshalOutput{ - NoUnkeyedLiterals: input.NoUnkeyedLiterals, - Buf: input.Buf, - }, nil - } - options := runtime.MarshalInputToOptions(input) - _ = options - size := options.Size(x) - dAtA := make([]byte, size) - i := len(dAtA) - _ = i - var l int - _ = l - if x.unknownFields != nil { - i -= len(x.unknownFields) - copy(dAtA[i:], x.unknownFields) - } - if len(x.Key) > 0 { - i -= len(x.Key) - copy(dAtA[i:], x.Key) - i = runtime.EncodeVarint(dAtA, i, uint64(len(x.Key))) - i-- - dAtA[i] = 0x12 - } - if len(x.Subspace) > 0 { - i -= len(x.Subspace) - copy(dAtA[i:], x.Subspace) - i = runtime.EncodeVarint(dAtA, i, uint64(len(x.Subspace))) - i-- - dAtA[i] = 0xa - } - if input.Buf != nil { - input.Buf = append(input.Buf, dAtA...) - } else { - input.Buf = dAtA - } - return protoiface.MarshalOutput{ - NoUnkeyedLiterals: input.NoUnkeyedLiterals, - Buf: input.Buf, - }, nil - } - unmarshal := func(input protoiface.UnmarshalInput) (protoiface.UnmarshalOutput, error) { - x := input.Message.Interface().(*QueryParamsRequest) - if x == nil { - return protoiface.UnmarshalOutput{ - NoUnkeyedLiterals: input.NoUnkeyedLiterals, - Flags: input.Flags, - }, nil - } - options := runtime.UnmarshalInputToOptions(input) - _ = options - dAtA := input.Buf - l := len(dAtA) - iNdEx := 0 - for iNdEx < l { - preIndex := iNdEx - var wire uint64 - for shift := uint(0); ; shift += 7 { - if shift >= 64 { - return protoiface.UnmarshalOutput{NoUnkeyedLiterals: input.NoUnkeyedLiterals, Flags: input.Flags}, runtime.ErrIntOverflow - } - if iNdEx >= l { - return protoiface.UnmarshalOutput{NoUnkeyedLiterals: input.NoUnkeyedLiterals, Flags: input.Flags}, io.ErrUnexpectedEOF - } - b := dAtA[iNdEx] - iNdEx++ - wire |= uint64(b&0x7F) << shift - if b < 0x80 { - break - } - } - fieldNum := int32(wire >> 3) - wireType := int(wire & 0x7) - if wireType == 4 { - return protoiface.UnmarshalOutput{NoUnkeyedLiterals: input.NoUnkeyedLiterals, Flags: input.Flags}, fmt.Errorf("proto: QueryParamsRequest: wiretype end group for non-group") - } - if fieldNum <= 0 { - return protoiface.UnmarshalOutput{NoUnkeyedLiterals: input.NoUnkeyedLiterals, Flags: input.Flags}, fmt.Errorf("proto: QueryParamsRequest: illegal tag %d (wire type %d)", fieldNum, wire) - } - switch fieldNum { - case 1: - if wireType != 2 { - return protoiface.UnmarshalOutput{NoUnkeyedLiterals: input.NoUnkeyedLiterals, Flags: input.Flags}, fmt.Errorf("proto: wrong wireType = %d for field Subspace", wireType) - } - var stringLen uint64 - for shift := uint(0); ; shift += 7 { - if shift >= 64 { - return protoiface.UnmarshalOutput{NoUnkeyedLiterals: input.NoUnkeyedLiterals, Flags: input.Flags}, runtime.ErrIntOverflow - } - if iNdEx >= l { - return protoiface.UnmarshalOutput{NoUnkeyedLiterals: input.NoUnkeyedLiterals, Flags: input.Flags}, io.ErrUnexpectedEOF - } - b := dAtA[iNdEx] - iNdEx++ - stringLen |= uint64(b&0x7F) << shift - if b < 0x80 { - break - } - } - intStringLen := int(stringLen) - if intStringLen < 0 { - return protoiface.UnmarshalOutput{NoUnkeyedLiterals: input.NoUnkeyedLiterals, Flags: input.Flags}, runtime.ErrInvalidLength - } - postIndex := iNdEx + intStringLen - if postIndex < 0 { - return protoiface.UnmarshalOutput{NoUnkeyedLiterals: input.NoUnkeyedLiterals, Flags: input.Flags}, runtime.ErrInvalidLength - } - if postIndex > l { - return protoiface.UnmarshalOutput{NoUnkeyedLiterals: input.NoUnkeyedLiterals, Flags: input.Flags}, io.ErrUnexpectedEOF - } - x.Subspace = string(dAtA[iNdEx:postIndex]) - iNdEx = postIndex - case 2: - if wireType != 2 { - return protoiface.UnmarshalOutput{NoUnkeyedLiterals: input.NoUnkeyedLiterals, Flags: input.Flags}, fmt.Errorf("proto: wrong wireType = %d for field Key", wireType) - } - var stringLen uint64 - for shift := uint(0); ; shift += 7 { - if shift >= 64 { - return protoiface.UnmarshalOutput{NoUnkeyedLiterals: input.NoUnkeyedLiterals, Flags: input.Flags}, runtime.ErrIntOverflow - } - if iNdEx >= l { - return protoiface.UnmarshalOutput{NoUnkeyedLiterals: input.NoUnkeyedLiterals, Flags: input.Flags}, io.ErrUnexpectedEOF - } - b := dAtA[iNdEx] - iNdEx++ - stringLen |= uint64(b&0x7F) << shift - if b < 0x80 { - break - } - } - intStringLen := int(stringLen) - if intStringLen < 0 { - return protoiface.UnmarshalOutput{NoUnkeyedLiterals: input.NoUnkeyedLiterals, Flags: input.Flags}, runtime.ErrInvalidLength - } - postIndex := iNdEx + intStringLen - if postIndex < 0 { - return protoiface.UnmarshalOutput{NoUnkeyedLiterals: input.NoUnkeyedLiterals, Flags: input.Flags}, runtime.ErrInvalidLength - } - if postIndex > l { - return protoiface.UnmarshalOutput{NoUnkeyedLiterals: input.NoUnkeyedLiterals, Flags: input.Flags}, io.ErrUnexpectedEOF - } - x.Key = string(dAtA[iNdEx:postIndex]) - iNdEx = postIndex - default: - iNdEx = preIndex - skippy, err := runtime.Skip(dAtA[iNdEx:]) - if err != nil { - return protoiface.UnmarshalOutput{NoUnkeyedLiterals: input.NoUnkeyedLiterals, Flags: input.Flags}, err - } - if (skippy < 0) || (iNdEx+skippy) < 0 { - return protoiface.UnmarshalOutput{NoUnkeyedLiterals: input.NoUnkeyedLiterals, Flags: input.Flags}, runtime.ErrInvalidLength - } - if (iNdEx + skippy) > l { - return protoiface.UnmarshalOutput{NoUnkeyedLiterals: input.NoUnkeyedLiterals, Flags: input.Flags}, io.ErrUnexpectedEOF - } - if !options.DiscardUnknown { - x.unknownFields = append(x.unknownFields, dAtA[iNdEx:iNdEx+skippy]...) - } - iNdEx += skippy - } - } - - if iNdEx > l { - return protoiface.UnmarshalOutput{NoUnkeyedLiterals: input.NoUnkeyedLiterals, Flags: input.Flags}, io.ErrUnexpectedEOF - } - return protoiface.UnmarshalOutput{NoUnkeyedLiterals: input.NoUnkeyedLiterals, Flags: input.Flags}, nil - } - return &protoiface.Methods{ - NoUnkeyedLiterals: struct{}{}, - Flags: protoiface.SupportMarshalDeterministic | protoiface.SupportUnmarshalDiscardUnknown, - Size: size, - Marshal: marshal, - Unmarshal: unmarshal, - Merge: nil, - CheckInitialized: nil, - } -} - -var ( - md_QueryParamsResponse protoreflect.MessageDescriptor - fd_QueryParamsResponse_param protoreflect.FieldDescriptor -) - -func init() { - file_cosmos_params_v1beta1_query_proto_init() - md_QueryParamsResponse = File_cosmos_params_v1beta1_query_proto.Messages().ByName("QueryParamsResponse") - fd_QueryParamsResponse_param = md_QueryParamsResponse.Fields().ByName("param") -} - -var _ protoreflect.Message = (*fastReflection_QueryParamsResponse)(nil) - -type fastReflection_QueryParamsResponse QueryParamsResponse - -func (x *QueryParamsResponse) ProtoReflect() protoreflect.Message { - return (*fastReflection_QueryParamsResponse)(x) -} - -func (x *QueryParamsResponse) slowProtoReflect() protoreflect.Message { - mi := &file_cosmos_params_v1beta1_query_proto_msgTypes[1] - if protoimpl.UnsafeEnabled && x != nil { - ms := protoimpl.X.MessageStateOf(protoimpl.Pointer(x)) - if ms.LoadMessageInfo() == nil { - ms.StoreMessageInfo(mi) - } - return ms - } - return mi.MessageOf(x) -} - -var _fastReflection_QueryParamsResponse_messageType fastReflection_QueryParamsResponse_messageType -var _ protoreflect.MessageType = fastReflection_QueryParamsResponse_messageType{} - -type fastReflection_QueryParamsResponse_messageType struct{} - -func (x fastReflection_QueryParamsResponse_messageType) Zero() protoreflect.Message { - return (*fastReflection_QueryParamsResponse)(nil) -} -func (x fastReflection_QueryParamsResponse_messageType) New() protoreflect.Message { - return new(fastReflection_QueryParamsResponse) -} -func (x fastReflection_QueryParamsResponse_messageType) Descriptor() protoreflect.MessageDescriptor { - return md_QueryParamsResponse -} - -// Descriptor returns message descriptor, which contains only the protobuf -// type information for the message. -func (x *fastReflection_QueryParamsResponse) Descriptor() protoreflect.MessageDescriptor { - return md_QueryParamsResponse -} - -// Type returns the message type, which encapsulates both Go and protobuf -// type information. If the Go type information is not needed, -// it is recommended that the message descriptor be used instead. -func (x *fastReflection_QueryParamsResponse) Type() protoreflect.MessageType { - return _fastReflection_QueryParamsResponse_messageType -} - -// New returns a newly allocated and mutable empty message. -func (x *fastReflection_QueryParamsResponse) New() protoreflect.Message { - return new(fastReflection_QueryParamsResponse) -} - -// Interface unwraps the message reflection interface and -// returns the underlying ProtoMessage interface. -func (x *fastReflection_QueryParamsResponse) Interface() protoreflect.ProtoMessage { - return (*QueryParamsResponse)(x) -} - -// Range iterates over every populated field in an undefined order, -// calling f for each field descriptor and value encountered. -// Range returns immediately if f returns false. -// While iterating, mutating operations may only be performed -// on the current field descriptor. -func (x *fastReflection_QueryParamsResponse) Range(f func(protoreflect.FieldDescriptor, protoreflect.Value) bool) { - if x.Param != nil { - value := protoreflect.ValueOfMessage(x.Param.ProtoReflect()) - if !f(fd_QueryParamsResponse_param, value) { - return - } - } -} - -// Has reports whether a field is populated. -// -// Some fields have the property of nullability where it is possible to -// distinguish between the default value of a field and whether the field -// was explicitly populated with the default value. Singular message fields, -// member fields of a oneof, and proto2 scalar fields are nullable. Such -// fields are populated only if explicitly set. -// -// In other cases (aside from the nullable cases above), -// a proto3 scalar field is populated if it contains a non-zero value, and -// a repeated field is populated if it is non-empty. -func (x *fastReflection_QueryParamsResponse) Has(fd protoreflect.FieldDescriptor) bool { - switch fd.FullName() { - case "cosmos.params.v1beta1.QueryParamsResponse.param": - return x.Param != nil - default: - if fd.IsExtension() { - panic(fmt.Errorf("proto3 declared messages do not support extensions: cosmos.params.v1beta1.QueryParamsResponse")) - } - panic(fmt.Errorf("message cosmos.params.v1beta1.QueryParamsResponse does not contain field %s", fd.FullName())) - } -} - -// Clear clears the field such that a subsequent Has call reports false. -// -// Clearing an extension field clears both the extension type and value -// associated with the given field number. -// -// Clear is a mutating operation and unsafe for concurrent use. -func (x *fastReflection_QueryParamsResponse) Clear(fd protoreflect.FieldDescriptor) { - switch fd.FullName() { - case "cosmos.params.v1beta1.QueryParamsResponse.param": - x.Param = nil - default: - if fd.IsExtension() { - panic(fmt.Errorf("proto3 declared messages do not support extensions: cosmos.params.v1beta1.QueryParamsResponse")) - } - panic(fmt.Errorf("message cosmos.params.v1beta1.QueryParamsResponse does not contain field %s", fd.FullName())) - } -} - -// Get retrieves the value for a field. -// -// For unpopulated scalars, it returns the default value, where -// the default value of a bytes scalar is guaranteed to be a copy. -// For unpopulated composite types, it returns an empty, read-only view -// of the value; to obtain a mutable reference, use Mutable. -func (x *fastReflection_QueryParamsResponse) Get(descriptor protoreflect.FieldDescriptor) protoreflect.Value { - switch descriptor.FullName() { - case "cosmos.params.v1beta1.QueryParamsResponse.param": - value := x.Param - return protoreflect.ValueOfMessage(value.ProtoReflect()) - default: - if descriptor.IsExtension() { - panic(fmt.Errorf("proto3 declared messages do not support extensions: cosmos.params.v1beta1.QueryParamsResponse")) - } - panic(fmt.Errorf("message cosmos.params.v1beta1.QueryParamsResponse does not contain field %s", descriptor.FullName())) - } -} - -// Set stores the value for a field. -// -// For a field belonging to a oneof, it implicitly clears any other field -// that may be currently set within the same oneof. -// For extension fields, it implicitly stores the provided ExtensionType. -// When setting a composite type, it is unspecified whether the stored value -// aliases the source's memory in any way. If the composite value is an -// empty, read-only value, then it panics. -// -// Set is a mutating operation and unsafe for concurrent use. -func (x *fastReflection_QueryParamsResponse) Set(fd protoreflect.FieldDescriptor, value protoreflect.Value) { - switch fd.FullName() { - case "cosmos.params.v1beta1.QueryParamsResponse.param": - x.Param = value.Message().Interface().(*ParamChange) - default: - if fd.IsExtension() { - panic(fmt.Errorf("proto3 declared messages do not support extensions: cosmos.params.v1beta1.QueryParamsResponse")) - } - panic(fmt.Errorf("message cosmos.params.v1beta1.QueryParamsResponse does not contain field %s", fd.FullName())) - } -} - -// Mutable returns a mutable reference to a composite type. -// -// If the field is unpopulated, it may allocate a composite value. -// For a field belonging to a oneof, it implicitly clears any other field -// that may be currently set within the same oneof. -// For extension fields, it implicitly stores the provided ExtensionType -// if not already stored. -// It panics if the field does not contain a composite type. -// -// Mutable is a mutating operation and unsafe for concurrent use. -func (x *fastReflection_QueryParamsResponse) Mutable(fd protoreflect.FieldDescriptor) protoreflect.Value { - switch fd.FullName() { - case "cosmos.params.v1beta1.QueryParamsResponse.param": - if x.Param == nil { - x.Param = new(ParamChange) - } - return protoreflect.ValueOfMessage(x.Param.ProtoReflect()) - default: - if fd.IsExtension() { - panic(fmt.Errorf("proto3 declared messages do not support extensions: cosmos.params.v1beta1.QueryParamsResponse")) - } - panic(fmt.Errorf("message cosmos.params.v1beta1.QueryParamsResponse does not contain field %s", fd.FullName())) - } -} - -// NewField returns a new value that is assignable to the field -// for the given descriptor. For scalars, this returns the default value. -// For lists, maps, and messages, this returns a new, empty, mutable value. -func (x *fastReflection_QueryParamsResponse) NewField(fd protoreflect.FieldDescriptor) protoreflect.Value { - switch fd.FullName() { - case "cosmos.params.v1beta1.QueryParamsResponse.param": - m := new(ParamChange) - return protoreflect.ValueOfMessage(m.ProtoReflect()) - default: - if fd.IsExtension() { - panic(fmt.Errorf("proto3 declared messages do not support extensions: cosmos.params.v1beta1.QueryParamsResponse")) - } - panic(fmt.Errorf("message cosmos.params.v1beta1.QueryParamsResponse does not contain field %s", fd.FullName())) - } -} - -// WhichOneof reports which field within the oneof is populated, -// returning nil if none are populated. -// It panics if the oneof descriptor does not belong to this message. -func (x *fastReflection_QueryParamsResponse) WhichOneof(d protoreflect.OneofDescriptor) protoreflect.FieldDescriptor { - switch d.FullName() { - default: - panic(fmt.Errorf("%s is not a oneof field in cosmos.params.v1beta1.QueryParamsResponse", d.FullName())) - } - panic("unreachable") -} - -// GetUnknown retrieves the entire list of unknown fields. -// The caller may only mutate the contents of the RawFields -// if the mutated bytes are stored back into the message with SetUnknown. -func (x *fastReflection_QueryParamsResponse) GetUnknown() protoreflect.RawFields { - return x.unknownFields -} - -// SetUnknown stores an entire list of unknown fields. -// The raw fields must be syntactically valid according to the wire format. -// An implementation may panic if this is not the case. -// Once stored, the caller must not mutate the content of the RawFields. -// An empty RawFields may be passed to clear the fields. -// -// SetUnknown is a mutating operation and unsafe for concurrent use. -func (x *fastReflection_QueryParamsResponse) SetUnknown(fields protoreflect.RawFields) { - x.unknownFields = fields -} - -// IsValid reports whether the message is valid. -// -// An invalid message is an empty, read-only value. -// -// An invalid message often corresponds to a nil pointer of the concrete -// message type, but the details are implementation dependent. -// Validity is not part of the protobuf data model, and may not -// be preserved in marshaling or other operations. -func (x *fastReflection_QueryParamsResponse) IsValid() bool { - return x != nil -} - -// ProtoMethods returns optional fastReflectionFeature-path implementations of various operations. -// This method may return nil. -// -// The returned methods type is identical to -// "google.golang.org/protobuf/runtime/protoiface".Methods. -// Consult the protoiface package documentation for details. -func (x *fastReflection_QueryParamsResponse) ProtoMethods() *protoiface.Methods { - size := func(input protoiface.SizeInput) protoiface.SizeOutput { - x := input.Message.Interface().(*QueryParamsResponse) - if x == nil { - return protoiface.SizeOutput{ - NoUnkeyedLiterals: input.NoUnkeyedLiterals, - Size: 0, - } - } - options := runtime.SizeInputToOptions(input) - _ = options - var n int - var l int - _ = l - if x.Param != nil { - l = options.Size(x.Param) - n += 1 + l + runtime.Sov(uint64(l)) - } - if x.unknownFields != nil { - n += len(x.unknownFields) - } - return protoiface.SizeOutput{ - NoUnkeyedLiterals: input.NoUnkeyedLiterals, - Size: n, - } - } - - marshal := func(input protoiface.MarshalInput) (protoiface.MarshalOutput, error) { - x := input.Message.Interface().(*QueryParamsResponse) - if x == nil { - return protoiface.MarshalOutput{ - NoUnkeyedLiterals: input.NoUnkeyedLiterals, - Buf: input.Buf, - }, nil - } - options := runtime.MarshalInputToOptions(input) - _ = options - size := options.Size(x) - dAtA := make([]byte, size) - i := len(dAtA) - _ = i - var l int - _ = l - if x.unknownFields != nil { - i -= len(x.unknownFields) - copy(dAtA[i:], x.unknownFields) - } - if x.Param != nil { - encoded, err := options.Marshal(x.Param) - if err != nil { - return protoiface.MarshalOutput{ - NoUnkeyedLiterals: input.NoUnkeyedLiterals, - Buf: input.Buf, - }, err - } - i -= len(encoded) - copy(dAtA[i:], encoded) - i = runtime.EncodeVarint(dAtA, i, uint64(len(encoded))) - i-- - dAtA[i] = 0xa - } - if input.Buf != nil { - input.Buf = append(input.Buf, dAtA...) - } else { - input.Buf = dAtA - } - return protoiface.MarshalOutput{ - NoUnkeyedLiterals: input.NoUnkeyedLiterals, - Buf: input.Buf, - }, nil - } - unmarshal := func(input protoiface.UnmarshalInput) (protoiface.UnmarshalOutput, error) { - x := input.Message.Interface().(*QueryParamsResponse) - if x == nil { - return protoiface.UnmarshalOutput{ - NoUnkeyedLiterals: input.NoUnkeyedLiterals, - Flags: input.Flags, - }, nil - } - options := runtime.UnmarshalInputToOptions(input) - _ = options - dAtA := input.Buf - l := len(dAtA) - iNdEx := 0 - for iNdEx < l { - preIndex := iNdEx - var wire uint64 - for shift := uint(0); ; shift += 7 { - if shift >= 64 { - return protoiface.UnmarshalOutput{NoUnkeyedLiterals: input.NoUnkeyedLiterals, Flags: input.Flags}, runtime.ErrIntOverflow - } - if iNdEx >= l { - return protoiface.UnmarshalOutput{NoUnkeyedLiterals: input.NoUnkeyedLiterals, Flags: input.Flags}, io.ErrUnexpectedEOF - } - b := dAtA[iNdEx] - iNdEx++ - wire |= uint64(b&0x7F) << shift - if b < 0x80 { - break - } - } - fieldNum := int32(wire >> 3) - wireType := int(wire & 0x7) - if wireType == 4 { - return protoiface.UnmarshalOutput{NoUnkeyedLiterals: input.NoUnkeyedLiterals, Flags: input.Flags}, fmt.Errorf("proto: QueryParamsResponse: wiretype end group for non-group") - } - if fieldNum <= 0 { - return protoiface.UnmarshalOutput{NoUnkeyedLiterals: input.NoUnkeyedLiterals, Flags: input.Flags}, fmt.Errorf("proto: QueryParamsResponse: illegal tag %d (wire type %d)", fieldNum, wire) - } - switch fieldNum { - case 1: - if wireType != 2 { - return protoiface.UnmarshalOutput{NoUnkeyedLiterals: input.NoUnkeyedLiterals, Flags: input.Flags}, fmt.Errorf("proto: wrong wireType = %d for field Param", wireType) - } - var msglen int - for shift := uint(0); ; shift += 7 { - if shift >= 64 { - return protoiface.UnmarshalOutput{NoUnkeyedLiterals: input.NoUnkeyedLiterals, Flags: input.Flags}, runtime.ErrIntOverflow - } - if iNdEx >= l { - return protoiface.UnmarshalOutput{NoUnkeyedLiterals: input.NoUnkeyedLiterals, Flags: input.Flags}, io.ErrUnexpectedEOF - } - b := dAtA[iNdEx] - iNdEx++ - msglen |= int(b&0x7F) << shift - if b < 0x80 { - break - } - } - if msglen < 0 { - return protoiface.UnmarshalOutput{NoUnkeyedLiterals: input.NoUnkeyedLiterals, Flags: input.Flags}, runtime.ErrInvalidLength - } - postIndex := iNdEx + msglen - if postIndex < 0 { - return protoiface.UnmarshalOutput{NoUnkeyedLiterals: input.NoUnkeyedLiterals, Flags: input.Flags}, runtime.ErrInvalidLength - } - if postIndex > l { - return protoiface.UnmarshalOutput{NoUnkeyedLiterals: input.NoUnkeyedLiterals, Flags: input.Flags}, io.ErrUnexpectedEOF - } - if x.Param == nil { - x.Param = &ParamChange{} - } - if err := options.Unmarshal(dAtA[iNdEx:postIndex], x.Param); err != nil { - return protoiface.UnmarshalOutput{NoUnkeyedLiterals: input.NoUnkeyedLiterals, Flags: input.Flags}, err - } - iNdEx = postIndex - default: - iNdEx = preIndex - skippy, err := runtime.Skip(dAtA[iNdEx:]) - if err != nil { - return protoiface.UnmarshalOutput{NoUnkeyedLiterals: input.NoUnkeyedLiterals, Flags: input.Flags}, err - } - if (skippy < 0) || (iNdEx+skippy) < 0 { - return protoiface.UnmarshalOutput{NoUnkeyedLiterals: input.NoUnkeyedLiterals, Flags: input.Flags}, runtime.ErrInvalidLength - } - if (iNdEx + skippy) > l { - return protoiface.UnmarshalOutput{NoUnkeyedLiterals: input.NoUnkeyedLiterals, Flags: input.Flags}, io.ErrUnexpectedEOF - } - if !options.DiscardUnknown { - x.unknownFields = append(x.unknownFields, dAtA[iNdEx:iNdEx+skippy]...) - } - iNdEx += skippy - } - } - - if iNdEx > l { - return protoiface.UnmarshalOutput{NoUnkeyedLiterals: input.NoUnkeyedLiterals, Flags: input.Flags}, io.ErrUnexpectedEOF - } - return protoiface.UnmarshalOutput{NoUnkeyedLiterals: input.NoUnkeyedLiterals, Flags: input.Flags}, nil - } - return &protoiface.Methods{ - NoUnkeyedLiterals: struct{}{}, - Flags: protoiface.SupportMarshalDeterministic | protoiface.SupportUnmarshalDiscardUnknown, - Size: size, - Marshal: marshal, - Unmarshal: unmarshal, - Merge: nil, - CheckInitialized: nil, - } -} - -var ( - md_QuerySubspacesRequest protoreflect.MessageDescriptor -) - -func init() { - file_cosmos_params_v1beta1_query_proto_init() - md_QuerySubspacesRequest = File_cosmos_params_v1beta1_query_proto.Messages().ByName("QuerySubspacesRequest") -} - -var _ protoreflect.Message = (*fastReflection_QuerySubspacesRequest)(nil) - -type fastReflection_QuerySubspacesRequest QuerySubspacesRequest - -func (x *QuerySubspacesRequest) ProtoReflect() protoreflect.Message { - return (*fastReflection_QuerySubspacesRequest)(x) -} - -func (x *QuerySubspacesRequest) slowProtoReflect() protoreflect.Message { - mi := &file_cosmos_params_v1beta1_query_proto_msgTypes[2] - if protoimpl.UnsafeEnabled && x != nil { - ms := protoimpl.X.MessageStateOf(protoimpl.Pointer(x)) - if ms.LoadMessageInfo() == nil { - ms.StoreMessageInfo(mi) - } - return ms - } - return mi.MessageOf(x) -} - -var _fastReflection_QuerySubspacesRequest_messageType fastReflection_QuerySubspacesRequest_messageType -var _ protoreflect.MessageType = fastReflection_QuerySubspacesRequest_messageType{} - -type fastReflection_QuerySubspacesRequest_messageType struct{} - -func (x fastReflection_QuerySubspacesRequest_messageType) Zero() protoreflect.Message { - return (*fastReflection_QuerySubspacesRequest)(nil) -} -func (x fastReflection_QuerySubspacesRequest_messageType) New() protoreflect.Message { - return new(fastReflection_QuerySubspacesRequest) -} -func (x fastReflection_QuerySubspacesRequest_messageType) Descriptor() protoreflect.MessageDescriptor { - return md_QuerySubspacesRequest -} - -// Descriptor returns message descriptor, which contains only the protobuf -// type information for the message. -func (x *fastReflection_QuerySubspacesRequest) Descriptor() protoreflect.MessageDescriptor { - return md_QuerySubspacesRequest -} - -// Type returns the message type, which encapsulates both Go and protobuf -// type information. If the Go type information is not needed, -// it is recommended that the message descriptor be used instead. -func (x *fastReflection_QuerySubspacesRequest) Type() protoreflect.MessageType { - return _fastReflection_QuerySubspacesRequest_messageType -} - -// New returns a newly allocated and mutable empty message. -func (x *fastReflection_QuerySubspacesRequest) New() protoreflect.Message { - return new(fastReflection_QuerySubspacesRequest) -} - -// Interface unwraps the message reflection interface and -// returns the underlying ProtoMessage interface. -func (x *fastReflection_QuerySubspacesRequest) Interface() protoreflect.ProtoMessage { - return (*QuerySubspacesRequest)(x) -} - -// Range iterates over every populated field in an undefined order, -// calling f for each field descriptor and value encountered. -// Range returns immediately if f returns false. -// While iterating, mutating operations may only be performed -// on the current field descriptor. -func (x *fastReflection_QuerySubspacesRequest) Range(f func(protoreflect.FieldDescriptor, protoreflect.Value) bool) { -} - -// Has reports whether a field is populated. -// -// Some fields have the property of nullability where it is possible to -// distinguish between the default value of a field and whether the field -// was explicitly populated with the default value. Singular message fields, -// member fields of a oneof, and proto2 scalar fields are nullable. Such -// fields are populated only if explicitly set. -// -// In other cases (aside from the nullable cases above), -// a proto3 scalar field is populated if it contains a non-zero value, and -// a repeated field is populated if it is non-empty. -func (x *fastReflection_QuerySubspacesRequest) Has(fd protoreflect.FieldDescriptor) bool { - switch fd.FullName() { - default: - if fd.IsExtension() { - panic(fmt.Errorf("proto3 declared messages do not support extensions: cosmos.params.v1beta1.QuerySubspacesRequest")) - } - panic(fmt.Errorf("message cosmos.params.v1beta1.QuerySubspacesRequest does not contain field %s", fd.FullName())) - } -} - -// Clear clears the field such that a subsequent Has call reports false. -// -// Clearing an extension field clears both the extension type and value -// associated with the given field number. -// -// Clear is a mutating operation and unsafe for concurrent use. -func (x *fastReflection_QuerySubspacesRequest) Clear(fd protoreflect.FieldDescriptor) { - switch fd.FullName() { - default: - if fd.IsExtension() { - panic(fmt.Errorf("proto3 declared messages do not support extensions: cosmos.params.v1beta1.QuerySubspacesRequest")) - } - panic(fmt.Errorf("message cosmos.params.v1beta1.QuerySubspacesRequest does not contain field %s", fd.FullName())) - } -} - -// Get retrieves the value for a field. -// -// For unpopulated scalars, it returns the default value, where -// the default value of a bytes scalar is guaranteed to be a copy. -// For unpopulated composite types, it returns an empty, read-only view -// of the value; to obtain a mutable reference, use Mutable. -func (x *fastReflection_QuerySubspacesRequest) Get(descriptor protoreflect.FieldDescriptor) protoreflect.Value { - switch descriptor.FullName() { - default: - if descriptor.IsExtension() { - panic(fmt.Errorf("proto3 declared messages do not support extensions: cosmos.params.v1beta1.QuerySubspacesRequest")) - } - panic(fmt.Errorf("message cosmos.params.v1beta1.QuerySubspacesRequest does not contain field %s", descriptor.FullName())) - } -} - -// Set stores the value for a field. -// -// For a field belonging to a oneof, it implicitly clears any other field -// that may be currently set within the same oneof. -// For extension fields, it implicitly stores the provided ExtensionType. -// When setting a composite type, it is unspecified whether the stored value -// aliases the source's memory in any way. If the composite value is an -// empty, read-only value, then it panics. -// -// Set is a mutating operation and unsafe for concurrent use. -func (x *fastReflection_QuerySubspacesRequest) Set(fd protoreflect.FieldDescriptor, value protoreflect.Value) { - switch fd.FullName() { - default: - if fd.IsExtension() { - panic(fmt.Errorf("proto3 declared messages do not support extensions: cosmos.params.v1beta1.QuerySubspacesRequest")) - } - panic(fmt.Errorf("message cosmos.params.v1beta1.QuerySubspacesRequest does not contain field %s", fd.FullName())) - } -} - -// Mutable returns a mutable reference to a composite type. -// -// If the field is unpopulated, it may allocate a composite value. -// For a field belonging to a oneof, it implicitly clears any other field -// that may be currently set within the same oneof. -// For extension fields, it implicitly stores the provided ExtensionType -// if not already stored. -// It panics if the field does not contain a composite type. -// -// Mutable is a mutating operation and unsafe for concurrent use. -func (x *fastReflection_QuerySubspacesRequest) Mutable(fd protoreflect.FieldDescriptor) protoreflect.Value { - switch fd.FullName() { - default: - if fd.IsExtension() { - panic(fmt.Errorf("proto3 declared messages do not support extensions: cosmos.params.v1beta1.QuerySubspacesRequest")) - } - panic(fmt.Errorf("message cosmos.params.v1beta1.QuerySubspacesRequest does not contain field %s", fd.FullName())) - } -} - -// NewField returns a new value that is assignable to the field -// for the given descriptor. For scalars, this returns the default value. -// For lists, maps, and messages, this returns a new, empty, mutable value. -func (x *fastReflection_QuerySubspacesRequest) NewField(fd protoreflect.FieldDescriptor) protoreflect.Value { - switch fd.FullName() { - default: - if fd.IsExtension() { - panic(fmt.Errorf("proto3 declared messages do not support extensions: cosmos.params.v1beta1.QuerySubspacesRequest")) - } - panic(fmt.Errorf("message cosmos.params.v1beta1.QuerySubspacesRequest does not contain field %s", fd.FullName())) - } -} - -// WhichOneof reports which field within the oneof is populated, -// returning nil if none are populated. -// It panics if the oneof descriptor does not belong to this message. -func (x *fastReflection_QuerySubspacesRequest) WhichOneof(d protoreflect.OneofDescriptor) protoreflect.FieldDescriptor { - switch d.FullName() { - default: - panic(fmt.Errorf("%s is not a oneof field in cosmos.params.v1beta1.QuerySubspacesRequest", d.FullName())) - } - panic("unreachable") -} - -// GetUnknown retrieves the entire list of unknown fields. -// The caller may only mutate the contents of the RawFields -// if the mutated bytes are stored back into the message with SetUnknown. -func (x *fastReflection_QuerySubspacesRequest) GetUnknown() protoreflect.RawFields { - return x.unknownFields -} - -// SetUnknown stores an entire list of unknown fields. -// The raw fields must be syntactically valid according to the wire format. -// An implementation may panic if this is not the case. -// Once stored, the caller must not mutate the content of the RawFields. -// An empty RawFields may be passed to clear the fields. -// -// SetUnknown is a mutating operation and unsafe for concurrent use. -func (x *fastReflection_QuerySubspacesRequest) SetUnknown(fields protoreflect.RawFields) { - x.unknownFields = fields -} - -// IsValid reports whether the message is valid. -// -// An invalid message is an empty, read-only value. -// -// An invalid message often corresponds to a nil pointer of the concrete -// message type, but the details are implementation dependent. -// Validity is not part of the protobuf data model, and may not -// be preserved in marshaling or other operations. -func (x *fastReflection_QuerySubspacesRequest) IsValid() bool { - return x != nil -} - -// ProtoMethods returns optional fastReflectionFeature-path implementations of various operations. -// This method may return nil. -// -// The returned methods type is identical to -// "google.golang.org/protobuf/runtime/protoiface".Methods. -// Consult the protoiface package documentation for details. -func (x *fastReflection_QuerySubspacesRequest) ProtoMethods() *protoiface.Methods { - size := func(input protoiface.SizeInput) protoiface.SizeOutput { - x := input.Message.Interface().(*QuerySubspacesRequest) - if x == nil { - return protoiface.SizeOutput{ - NoUnkeyedLiterals: input.NoUnkeyedLiterals, - Size: 0, - } - } - options := runtime.SizeInputToOptions(input) - _ = options - var n int - var l int - _ = l - if x.unknownFields != nil { - n += len(x.unknownFields) - } - return protoiface.SizeOutput{ - NoUnkeyedLiterals: input.NoUnkeyedLiterals, - Size: n, - } - } - - marshal := func(input protoiface.MarshalInput) (protoiface.MarshalOutput, error) { - x := input.Message.Interface().(*QuerySubspacesRequest) - if x == nil { - return protoiface.MarshalOutput{ - NoUnkeyedLiterals: input.NoUnkeyedLiterals, - Buf: input.Buf, - }, nil - } - options := runtime.MarshalInputToOptions(input) - _ = options - size := options.Size(x) - dAtA := make([]byte, size) - i := len(dAtA) - _ = i - var l int - _ = l - if x.unknownFields != nil { - i -= len(x.unknownFields) - copy(dAtA[i:], x.unknownFields) - } - if input.Buf != nil { - input.Buf = append(input.Buf, dAtA...) - } else { - input.Buf = dAtA - } - return protoiface.MarshalOutput{ - NoUnkeyedLiterals: input.NoUnkeyedLiterals, - Buf: input.Buf, - }, nil - } - unmarshal := func(input protoiface.UnmarshalInput) (protoiface.UnmarshalOutput, error) { - x := input.Message.Interface().(*QuerySubspacesRequest) - if x == nil { - return protoiface.UnmarshalOutput{ - NoUnkeyedLiterals: input.NoUnkeyedLiterals, - Flags: input.Flags, - }, nil - } - options := runtime.UnmarshalInputToOptions(input) - _ = options - dAtA := input.Buf - l := len(dAtA) - iNdEx := 0 - for iNdEx < l { - preIndex := iNdEx - var wire uint64 - for shift := uint(0); ; shift += 7 { - if shift >= 64 { - return protoiface.UnmarshalOutput{NoUnkeyedLiterals: input.NoUnkeyedLiterals, Flags: input.Flags}, runtime.ErrIntOverflow - } - if iNdEx >= l { - return protoiface.UnmarshalOutput{NoUnkeyedLiterals: input.NoUnkeyedLiterals, Flags: input.Flags}, io.ErrUnexpectedEOF - } - b := dAtA[iNdEx] - iNdEx++ - wire |= uint64(b&0x7F) << shift - if b < 0x80 { - break - } - } - fieldNum := int32(wire >> 3) - wireType := int(wire & 0x7) - if wireType == 4 { - return protoiface.UnmarshalOutput{NoUnkeyedLiterals: input.NoUnkeyedLiterals, Flags: input.Flags}, fmt.Errorf("proto: QuerySubspacesRequest: wiretype end group for non-group") - } - if fieldNum <= 0 { - return protoiface.UnmarshalOutput{NoUnkeyedLiterals: input.NoUnkeyedLiterals, Flags: input.Flags}, fmt.Errorf("proto: QuerySubspacesRequest: illegal tag %d (wire type %d)", fieldNum, wire) - } - switch fieldNum { - default: - iNdEx = preIndex - skippy, err := runtime.Skip(dAtA[iNdEx:]) - if err != nil { - return protoiface.UnmarshalOutput{NoUnkeyedLiterals: input.NoUnkeyedLiterals, Flags: input.Flags}, err - } - if (skippy < 0) || (iNdEx+skippy) < 0 { - return protoiface.UnmarshalOutput{NoUnkeyedLiterals: input.NoUnkeyedLiterals, Flags: input.Flags}, runtime.ErrInvalidLength - } - if (iNdEx + skippy) > l { - return protoiface.UnmarshalOutput{NoUnkeyedLiterals: input.NoUnkeyedLiterals, Flags: input.Flags}, io.ErrUnexpectedEOF - } - if !options.DiscardUnknown { - x.unknownFields = append(x.unknownFields, dAtA[iNdEx:iNdEx+skippy]...) - } - iNdEx += skippy - } - } - - if iNdEx > l { - return protoiface.UnmarshalOutput{NoUnkeyedLiterals: input.NoUnkeyedLiterals, Flags: input.Flags}, io.ErrUnexpectedEOF - } - return protoiface.UnmarshalOutput{NoUnkeyedLiterals: input.NoUnkeyedLiterals, Flags: input.Flags}, nil - } - return &protoiface.Methods{ - NoUnkeyedLiterals: struct{}{}, - Flags: protoiface.SupportMarshalDeterministic | protoiface.SupportUnmarshalDiscardUnknown, - Size: size, - Marshal: marshal, - Unmarshal: unmarshal, - Merge: nil, - CheckInitialized: nil, - } -} - -var _ protoreflect.List = (*_QuerySubspacesResponse_1_list)(nil) - -type _QuerySubspacesResponse_1_list struct { - list *[]*Subspace -} - -func (x *_QuerySubspacesResponse_1_list) Len() int { - if x.list == nil { - return 0 - } - return len(*x.list) -} - -func (x *_QuerySubspacesResponse_1_list) Get(i int) protoreflect.Value { - return protoreflect.ValueOfMessage((*x.list)[i].ProtoReflect()) -} - -func (x *_QuerySubspacesResponse_1_list) Set(i int, value protoreflect.Value) { - valueUnwrapped := value.Message() - concreteValue := valueUnwrapped.Interface().(*Subspace) - (*x.list)[i] = concreteValue -} - -func (x *_QuerySubspacesResponse_1_list) Append(value protoreflect.Value) { - valueUnwrapped := value.Message() - concreteValue := valueUnwrapped.Interface().(*Subspace) - *x.list = append(*x.list, concreteValue) -} - -func (x *_QuerySubspacesResponse_1_list) AppendMutable() protoreflect.Value { - v := new(Subspace) - *x.list = append(*x.list, v) - return protoreflect.ValueOfMessage(v.ProtoReflect()) -} - -func (x *_QuerySubspacesResponse_1_list) Truncate(n int) { - for i := n; i < len(*x.list); i++ { - (*x.list)[i] = nil - } - *x.list = (*x.list)[:n] -} - -func (x *_QuerySubspacesResponse_1_list) NewElement() protoreflect.Value { - v := new(Subspace) - return protoreflect.ValueOfMessage(v.ProtoReflect()) -} - -func (x *_QuerySubspacesResponse_1_list) IsValid() bool { - return x.list != nil -} - -var ( - md_QuerySubspacesResponse protoreflect.MessageDescriptor - fd_QuerySubspacesResponse_subspaces protoreflect.FieldDescriptor -) - -func init() { - file_cosmos_params_v1beta1_query_proto_init() - md_QuerySubspacesResponse = File_cosmos_params_v1beta1_query_proto.Messages().ByName("QuerySubspacesResponse") - fd_QuerySubspacesResponse_subspaces = md_QuerySubspacesResponse.Fields().ByName("subspaces") -} - -var _ protoreflect.Message = (*fastReflection_QuerySubspacesResponse)(nil) - -type fastReflection_QuerySubspacesResponse QuerySubspacesResponse - -func (x *QuerySubspacesResponse) ProtoReflect() protoreflect.Message { - return (*fastReflection_QuerySubspacesResponse)(x) -} - -func (x *QuerySubspacesResponse) slowProtoReflect() protoreflect.Message { - mi := &file_cosmos_params_v1beta1_query_proto_msgTypes[3] - if protoimpl.UnsafeEnabled && x != nil { - ms := protoimpl.X.MessageStateOf(protoimpl.Pointer(x)) - if ms.LoadMessageInfo() == nil { - ms.StoreMessageInfo(mi) - } - return ms - } - return mi.MessageOf(x) -} - -var _fastReflection_QuerySubspacesResponse_messageType fastReflection_QuerySubspacesResponse_messageType -var _ protoreflect.MessageType = fastReflection_QuerySubspacesResponse_messageType{} - -type fastReflection_QuerySubspacesResponse_messageType struct{} - -func (x fastReflection_QuerySubspacesResponse_messageType) Zero() protoreflect.Message { - return (*fastReflection_QuerySubspacesResponse)(nil) -} -func (x fastReflection_QuerySubspacesResponse_messageType) New() protoreflect.Message { - return new(fastReflection_QuerySubspacesResponse) -} -func (x fastReflection_QuerySubspacesResponse_messageType) Descriptor() protoreflect.MessageDescriptor { - return md_QuerySubspacesResponse -} - -// Descriptor returns message descriptor, which contains only the protobuf -// type information for the message. -func (x *fastReflection_QuerySubspacesResponse) Descriptor() protoreflect.MessageDescriptor { - return md_QuerySubspacesResponse -} - -// Type returns the message type, which encapsulates both Go and protobuf -// type information. If the Go type information is not needed, -// it is recommended that the message descriptor be used instead. -func (x *fastReflection_QuerySubspacesResponse) Type() protoreflect.MessageType { - return _fastReflection_QuerySubspacesResponse_messageType -} - -// New returns a newly allocated and mutable empty message. -func (x *fastReflection_QuerySubspacesResponse) New() protoreflect.Message { - return new(fastReflection_QuerySubspacesResponse) -} - -// Interface unwraps the message reflection interface and -// returns the underlying ProtoMessage interface. -func (x *fastReflection_QuerySubspacesResponse) Interface() protoreflect.ProtoMessage { - return (*QuerySubspacesResponse)(x) -} - -// Range iterates over every populated field in an undefined order, -// calling f for each field descriptor and value encountered. -// Range returns immediately if f returns false. -// While iterating, mutating operations may only be performed -// on the current field descriptor. -func (x *fastReflection_QuerySubspacesResponse) Range(f func(protoreflect.FieldDescriptor, protoreflect.Value) bool) { - if len(x.Subspaces) != 0 { - value := protoreflect.ValueOfList(&_QuerySubspacesResponse_1_list{list: &x.Subspaces}) - if !f(fd_QuerySubspacesResponse_subspaces, value) { - return - } - } -} - -// Has reports whether a field is populated. -// -// Some fields have the property of nullability where it is possible to -// distinguish between the default value of a field and whether the field -// was explicitly populated with the default value. Singular message fields, -// member fields of a oneof, and proto2 scalar fields are nullable. Such -// fields are populated only if explicitly set. -// -// In other cases (aside from the nullable cases above), -// a proto3 scalar field is populated if it contains a non-zero value, and -// a repeated field is populated if it is non-empty. -func (x *fastReflection_QuerySubspacesResponse) Has(fd protoreflect.FieldDescriptor) bool { - switch fd.FullName() { - case "cosmos.params.v1beta1.QuerySubspacesResponse.subspaces": - return len(x.Subspaces) != 0 - default: - if fd.IsExtension() { - panic(fmt.Errorf("proto3 declared messages do not support extensions: cosmos.params.v1beta1.QuerySubspacesResponse")) - } - panic(fmt.Errorf("message cosmos.params.v1beta1.QuerySubspacesResponse does not contain field %s", fd.FullName())) - } -} - -// Clear clears the field such that a subsequent Has call reports false. -// -// Clearing an extension field clears both the extension type and value -// associated with the given field number. -// -// Clear is a mutating operation and unsafe for concurrent use. -func (x *fastReflection_QuerySubspacesResponse) Clear(fd protoreflect.FieldDescriptor) { - switch fd.FullName() { - case "cosmos.params.v1beta1.QuerySubspacesResponse.subspaces": - x.Subspaces = nil - default: - if fd.IsExtension() { - panic(fmt.Errorf("proto3 declared messages do not support extensions: cosmos.params.v1beta1.QuerySubspacesResponse")) - } - panic(fmt.Errorf("message cosmos.params.v1beta1.QuerySubspacesResponse does not contain field %s", fd.FullName())) - } -} - -// Get retrieves the value for a field. -// -// For unpopulated scalars, it returns the default value, where -// the default value of a bytes scalar is guaranteed to be a copy. -// For unpopulated composite types, it returns an empty, read-only view -// of the value; to obtain a mutable reference, use Mutable. -func (x *fastReflection_QuerySubspacesResponse) Get(descriptor protoreflect.FieldDescriptor) protoreflect.Value { - switch descriptor.FullName() { - case "cosmos.params.v1beta1.QuerySubspacesResponse.subspaces": - if len(x.Subspaces) == 0 { - return protoreflect.ValueOfList(&_QuerySubspacesResponse_1_list{}) - } - listValue := &_QuerySubspacesResponse_1_list{list: &x.Subspaces} - return protoreflect.ValueOfList(listValue) - default: - if descriptor.IsExtension() { - panic(fmt.Errorf("proto3 declared messages do not support extensions: cosmos.params.v1beta1.QuerySubspacesResponse")) - } - panic(fmt.Errorf("message cosmos.params.v1beta1.QuerySubspacesResponse does not contain field %s", descriptor.FullName())) - } -} - -// Set stores the value for a field. -// -// For a field belonging to a oneof, it implicitly clears any other field -// that may be currently set within the same oneof. -// For extension fields, it implicitly stores the provided ExtensionType. -// When setting a composite type, it is unspecified whether the stored value -// aliases the source's memory in any way. If the composite value is an -// empty, read-only value, then it panics. -// -// Set is a mutating operation and unsafe for concurrent use. -func (x *fastReflection_QuerySubspacesResponse) Set(fd protoreflect.FieldDescriptor, value protoreflect.Value) { - switch fd.FullName() { - case "cosmos.params.v1beta1.QuerySubspacesResponse.subspaces": - lv := value.List() - clv := lv.(*_QuerySubspacesResponse_1_list) - x.Subspaces = *clv.list - default: - if fd.IsExtension() { - panic(fmt.Errorf("proto3 declared messages do not support extensions: cosmos.params.v1beta1.QuerySubspacesResponse")) - } - panic(fmt.Errorf("message cosmos.params.v1beta1.QuerySubspacesResponse does not contain field %s", fd.FullName())) - } -} - -// Mutable returns a mutable reference to a composite type. -// -// If the field is unpopulated, it may allocate a composite value. -// For a field belonging to a oneof, it implicitly clears any other field -// that may be currently set within the same oneof. -// For extension fields, it implicitly stores the provided ExtensionType -// if not already stored. -// It panics if the field does not contain a composite type. -// -// Mutable is a mutating operation and unsafe for concurrent use. -func (x *fastReflection_QuerySubspacesResponse) Mutable(fd protoreflect.FieldDescriptor) protoreflect.Value { - switch fd.FullName() { - case "cosmos.params.v1beta1.QuerySubspacesResponse.subspaces": - if x.Subspaces == nil { - x.Subspaces = []*Subspace{} - } - value := &_QuerySubspacesResponse_1_list{list: &x.Subspaces} - return protoreflect.ValueOfList(value) - default: - if fd.IsExtension() { - panic(fmt.Errorf("proto3 declared messages do not support extensions: cosmos.params.v1beta1.QuerySubspacesResponse")) - } - panic(fmt.Errorf("message cosmos.params.v1beta1.QuerySubspacesResponse does not contain field %s", fd.FullName())) - } -} - -// NewField returns a new value that is assignable to the field -// for the given descriptor. For scalars, this returns the default value. -// For lists, maps, and messages, this returns a new, empty, mutable value. -func (x *fastReflection_QuerySubspacesResponse) NewField(fd protoreflect.FieldDescriptor) protoreflect.Value { - switch fd.FullName() { - case "cosmos.params.v1beta1.QuerySubspacesResponse.subspaces": - list := []*Subspace{} - return protoreflect.ValueOfList(&_QuerySubspacesResponse_1_list{list: &list}) - default: - if fd.IsExtension() { - panic(fmt.Errorf("proto3 declared messages do not support extensions: cosmos.params.v1beta1.QuerySubspacesResponse")) - } - panic(fmt.Errorf("message cosmos.params.v1beta1.QuerySubspacesResponse does not contain field %s", fd.FullName())) - } -} - -// WhichOneof reports which field within the oneof is populated, -// returning nil if none are populated. -// It panics if the oneof descriptor does not belong to this message. -func (x *fastReflection_QuerySubspacesResponse) WhichOneof(d protoreflect.OneofDescriptor) protoreflect.FieldDescriptor { - switch d.FullName() { - default: - panic(fmt.Errorf("%s is not a oneof field in cosmos.params.v1beta1.QuerySubspacesResponse", d.FullName())) - } - panic("unreachable") -} - -// GetUnknown retrieves the entire list of unknown fields. -// The caller may only mutate the contents of the RawFields -// if the mutated bytes are stored back into the message with SetUnknown. -func (x *fastReflection_QuerySubspacesResponse) GetUnknown() protoreflect.RawFields { - return x.unknownFields -} - -// SetUnknown stores an entire list of unknown fields. -// The raw fields must be syntactically valid according to the wire format. -// An implementation may panic if this is not the case. -// Once stored, the caller must not mutate the content of the RawFields. -// An empty RawFields may be passed to clear the fields. -// -// SetUnknown is a mutating operation and unsafe for concurrent use. -func (x *fastReflection_QuerySubspacesResponse) SetUnknown(fields protoreflect.RawFields) { - x.unknownFields = fields -} - -// IsValid reports whether the message is valid. -// -// An invalid message is an empty, read-only value. -// -// An invalid message often corresponds to a nil pointer of the concrete -// message type, but the details are implementation dependent. -// Validity is not part of the protobuf data model, and may not -// be preserved in marshaling or other operations. -func (x *fastReflection_QuerySubspacesResponse) IsValid() bool { - return x != nil -} - -// ProtoMethods returns optional fastReflectionFeature-path implementations of various operations. -// This method may return nil. -// -// The returned methods type is identical to -// "google.golang.org/protobuf/runtime/protoiface".Methods. -// Consult the protoiface package documentation for details. -func (x *fastReflection_QuerySubspacesResponse) ProtoMethods() *protoiface.Methods { - size := func(input protoiface.SizeInput) protoiface.SizeOutput { - x := input.Message.Interface().(*QuerySubspacesResponse) - if x == nil { - return protoiface.SizeOutput{ - NoUnkeyedLiterals: input.NoUnkeyedLiterals, - Size: 0, - } - } - options := runtime.SizeInputToOptions(input) - _ = options - var n int - var l int - _ = l - if len(x.Subspaces) > 0 { - for _, e := range x.Subspaces { - l = options.Size(e) - n += 1 + l + runtime.Sov(uint64(l)) - } - } - if x.unknownFields != nil { - n += len(x.unknownFields) - } - return protoiface.SizeOutput{ - NoUnkeyedLiterals: input.NoUnkeyedLiterals, - Size: n, - } - } - - marshal := func(input protoiface.MarshalInput) (protoiface.MarshalOutput, error) { - x := input.Message.Interface().(*QuerySubspacesResponse) - if x == nil { - return protoiface.MarshalOutput{ - NoUnkeyedLiterals: input.NoUnkeyedLiterals, - Buf: input.Buf, - }, nil - } - options := runtime.MarshalInputToOptions(input) - _ = options - size := options.Size(x) - dAtA := make([]byte, size) - i := len(dAtA) - _ = i - var l int - _ = l - if x.unknownFields != nil { - i -= len(x.unknownFields) - copy(dAtA[i:], x.unknownFields) - } - if len(x.Subspaces) > 0 { - for iNdEx := len(x.Subspaces) - 1; iNdEx >= 0; iNdEx-- { - encoded, err := options.Marshal(x.Subspaces[iNdEx]) - if err != nil { - return protoiface.MarshalOutput{ - NoUnkeyedLiterals: input.NoUnkeyedLiterals, - Buf: input.Buf, - }, err - } - i -= len(encoded) - copy(dAtA[i:], encoded) - i = runtime.EncodeVarint(dAtA, i, uint64(len(encoded))) - i-- - dAtA[i] = 0xa - } - } - if input.Buf != nil { - input.Buf = append(input.Buf, dAtA...) - } else { - input.Buf = dAtA - } - return protoiface.MarshalOutput{ - NoUnkeyedLiterals: input.NoUnkeyedLiterals, - Buf: input.Buf, - }, nil - } - unmarshal := func(input protoiface.UnmarshalInput) (protoiface.UnmarshalOutput, error) { - x := input.Message.Interface().(*QuerySubspacesResponse) - if x == nil { - return protoiface.UnmarshalOutput{ - NoUnkeyedLiterals: input.NoUnkeyedLiterals, - Flags: input.Flags, - }, nil - } - options := runtime.UnmarshalInputToOptions(input) - _ = options - dAtA := input.Buf - l := len(dAtA) - iNdEx := 0 - for iNdEx < l { - preIndex := iNdEx - var wire uint64 - for shift := uint(0); ; shift += 7 { - if shift >= 64 { - return protoiface.UnmarshalOutput{NoUnkeyedLiterals: input.NoUnkeyedLiterals, Flags: input.Flags}, runtime.ErrIntOverflow - } - if iNdEx >= l { - return protoiface.UnmarshalOutput{NoUnkeyedLiterals: input.NoUnkeyedLiterals, Flags: input.Flags}, io.ErrUnexpectedEOF - } - b := dAtA[iNdEx] - iNdEx++ - wire |= uint64(b&0x7F) << shift - if b < 0x80 { - break - } - } - fieldNum := int32(wire >> 3) - wireType := int(wire & 0x7) - if wireType == 4 { - return protoiface.UnmarshalOutput{NoUnkeyedLiterals: input.NoUnkeyedLiterals, Flags: input.Flags}, fmt.Errorf("proto: QuerySubspacesResponse: wiretype end group for non-group") - } - if fieldNum <= 0 { - return protoiface.UnmarshalOutput{NoUnkeyedLiterals: input.NoUnkeyedLiterals, Flags: input.Flags}, fmt.Errorf("proto: QuerySubspacesResponse: illegal tag %d (wire type %d)", fieldNum, wire) - } - switch fieldNum { - case 1: - if wireType != 2 { - return protoiface.UnmarshalOutput{NoUnkeyedLiterals: input.NoUnkeyedLiterals, Flags: input.Flags}, fmt.Errorf("proto: wrong wireType = %d for field Subspaces", wireType) - } - var msglen int - for shift := uint(0); ; shift += 7 { - if shift >= 64 { - return protoiface.UnmarshalOutput{NoUnkeyedLiterals: input.NoUnkeyedLiterals, Flags: input.Flags}, runtime.ErrIntOverflow - } - if iNdEx >= l { - return protoiface.UnmarshalOutput{NoUnkeyedLiterals: input.NoUnkeyedLiterals, Flags: input.Flags}, io.ErrUnexpectedEOF - } - b := dAtA[iNdEx] - iNdEx++ - msglen |= int(b&0x7F) << shift - if b < 0x80 { - break - } - } - if msglen < 0 { - return protoiface.UnmarshalOutput{NoUnkeyedLiterals: input.NoUnkeyedLiterals, Flags: input.Flags}, runtime.ErrInvalidLength - } - postIndex := iNdEx + msglen - if postIndex < 0 { - return protoiface.UnmarshalOutput{NoUnkeyedLiterals: input.NoUnkeyedLiterals, Flags: input.Flags}, runtime.ErrInvalidLength - } - if postIndex > l { - return protoiface.UnmarshalOutput{NoUnkeyedLiterals: input.NoUnkeyedLiterals, Flags: input.Flags}, io.ErrUnexpectedEOF - } - x.Subspaces = append(x.Subspaces, &Subspace{}) - if err := options.Unmarshal(dAtA[iNdEx:postIndex], x.Subspaces[len(x.Subspaces)-1]); err != nil { - return protoiface.UnmarshalOutput{NoUnkeyedLiterals: input.NoUnkeyedLiterals, Flags: input.Flags}, err - } - iNdEx = postIndex - default: - iNdEx = preIndex - skippy, err := runtime.Skip(dAtA[iNdEx:]) - if err != nil { - return protoiface.UnmarshalOutput{NoUnkeyedLiterals: input.NoUnkeyedLiterals, Flags: input.Flags}, err - } - if (skippy < 0) || (iNdEx+skippy) < 0 { - return protoiface.UnmarshalOutput{NoUnkeyedLiterals: input.NoUnkeyedLiterals, Flags: input.Flags}, runtime.ErrInvalidLength - } - if (iNdEx + skippy) > l { - return protoiface.UnmarshalOutput{NoUnkeyedLiterals: input.NoUnkeyedLiterals, Flags: input.Flags}, io.ErrUnexpectedEOF - } - if !options.DiscardUnknown { - x.unknownFields = append(x.unknownFields, dAtA[iNdEx:iNdEx+skippy]...) - } - iNdEx += skippy - } - } - - if iNdEx > l { - return protoiface.UnmarshalOutput{NoUnkeyedLiterals: input.NoUnkeyedLiterals, Flags: input.Flags}, io.ErrUnexpectedEOF - } - return protoiface.UnmarshalOutput{NoUnkeyedLiterals: input.NoUnkeyedLiterals, Flags: input.Flags}, nil - } - return &protoiface.Methods{ - NoUnkeyedLiterals: struct{}{}, - Flags: protoiface.SupportMarshalDeterministic | protoiface.SupportUnmarshalDiscardUnknown, - Size: size, - Marshal: marshal, - Unmarshal: unmarshal, - Merge: nil, - CheckInitialized: nil, - } -} - -var _ protoreflect.List = (*_Subspace_2_list)(nil) - -type _Subspace_2_list struct { - list *[]string -} - -func (x *_Subspace_2_list) Len() int { - if x.list == nil { - return 0 - } - return len(*x.list) -} - -func (x *_Subspace_2_list) Get(i int) protoreflect.Value { - return protoreflect.ValueOfString((*x.list)[i]) -} - -func (x *_Subspace_2_list) Set(i int, value protoreflect.Value) { - valueUnwrapped := value.String() - concreteValue := valueUnwrapped - (*x.list)[i] = concreteValue -} - -func (x *_Subspace_2_list) Append(value protoreflect.Value) { - valueUnwrapped := value.String() - concreteValue := valueUnwrapped - *x.list = append(*x.list, concreteValue) -} - -func (x *_Subspace_2_list) AppendMutable() protoreflect.Value { - panic(fmt.Errorf("AppendMutable can not be called on message Subspace at list field Keys as it is not of Message kind")) -} - -func (x *_Subspace_2_list) Truncate(n int) { - *x.list = (*x.list)[:n] -} - -func (x *_Subspace_2_list) NewElement() protoreflect.Value { - v := "" - return protoreflect.ValueOfString(v) -} - -func (x *_Subspace_2_list) IsValid() bool { - return x.list != nil -} - -var ( - md_Subspace protoreflect.MessageDescriptor - fd_Subspace_subspace protoreflect.FieldDescriptor - fd_Subspace_keys protoreflect.FieldDescriptor -) - -func init() { - file_cosmos_params_v1beta1_query_proto_init() - md_Subspace = File_cosmos_params_v1beta1_query_proto.Messages().ByName("Subspace") - fd_Subspace_subspace = md_Subspace.Fields().ByName("subspace") - fd_Subspace_keys = md_Subspace.Fields().ByName("keys") -} - -var _ protoreflect.Message = (*fastReflection_Subspace)(nil) - -type fastReflection_Subspace Subspace - -func (x *Subspace) ProtoReflect() protoreflect.Message { - return (*fastReflection_Subspace)(x) -} - -func (x *Subspace) slowProtoReflect() protoreflect.Message { - mi := &file_cosmos_params_v1beta1_query_proto_msgTypes[4] - if protoimpl.UnsafeEnabled && x != nil { - ms := protoimpl.X.MessageStateOf(protoimpl.Pointer(x)) - if ms.LoadMessageInfo() == nil { - ms.StoreMessageInfo(mi) - } - return ms - } - return mi.MessageOf(x) -} - -var _fastReflection_Subspace_messageType fastReflection_Subspace_messageType -var _ protoreflect.MessageType = fastReflection_Subspace_messageType{} - -type fastReflection_Subspace_messageType struct{} - -func (x fastReflection_Subspace_messageType) Zero() protoreflect.Message { - return (*fastReflection_Subspace)(nil) -} -func (x fastReflection_Subspace_messageType) New() protoreflect.Message { - return new(fastReflection_Subspace) -} -func (x fastReflection_Subspace_messageType) Descriptor() protoreflect.MessageDescriptor { - return md_Subspace -} - -// Descriptor returns message descriptor, which contains only the protobuf -// type information for the message. -func (x *fastReflection_Subspace) Descriptor() protoreflect.MessageDescriptor { - return md_Subspace -} - -// Type returns the message type, which encapsulates both Go and protobuf -// type information. If the Go type information is not needed, -// it is recommended that the message descriptor be used instead. -func (x *fastReflection_Subspace) Type() protoreflect.MessageType { - return _fastReflection_Subspace_messageType -} - -// New returns a newly allocated and mutable empty message. -func (x *fastReflection_Subspace) New() protoreflect.Message { - return new(fastReflection_Subspace) -} - -// Interface unwraps the message reflection interface and -// returns the underlying ProtoMessage interface. -func (x *fastReflection_Subspace) Interface() protoreflect.ProtoMessage { - return (*Subspace)(x) -} - -// Range iterates over every populated field in an undefined order, -// calling f for each field descriptor and value encountered. -// Range returns immediately if f returns false. -// While iterating, mutating operations may only be performed -// on the current field descriptor. -func (x *fastReflection_Subspace) Range(f func(protoreflect.FieldDescriptor, protoreflect.Value) bool) { - if x.Subspace != "" { - value := protoreflect.ValueOfString(x.Subspace) - if !f(fd_Subspace_subspace, value) { - return - } - } - if len(x.Keys) != 0 { - value := protoreflect.ValueOfList(&_Subspace_2_list{list: &x.Keys}) - if !f(fd_Subspace_keys, value) { - return - } - } -} - -// Has reports whether a field is populated. -// -// Some fields have the property of nullability where it is possible to -// distinguish between the default value of a field and whether the field -// was explicitly populated with the default value. Singular message fields, -// member fields of a oneof, and proto2 scalar fields are nullable. Such -// fields are populated only if explicitly set. -// -// In other cases (aside from the nullable cases above), -// a proto3 scalar field is populated if it contains a non-zero value, and -// a repeated field is populated if it is non-empty. -func (x *fastReflection_Subspace) Has(fd protoreflect.FieldDescriptor) bool { - switch fd.FullName() { - case "cosmos.params.v1beta1.Subspace.subspace": - return x.Subspace != "" - case "cosmos.params.v1beta1.Subspace.keys": - return len(x.Keys) != 0 - default: - if fd.IsExtension() { - panic(fmt.Errorf("proto3 declared messages do not support extensions: cosmos.params.v1beta1.Subspace")) - } - panic(fmt.Errorf("message cosmos.params.v1beta1.Subspace does not contain field %s", fd.FullName())) - } -} - -// Clear clears the field such that a subsequent Has call reports false. -// -// Clearing an extension field clears both the extension type and value -// associated with the given field number. -// -// Clear is a mutating operation and unsafe for concurrent use. -func (x *fastReflection_Subspace) Clear(fd protoreflect.FieldDescriptor) { - switch fd.FullName() { - case "cosmos.params.v1beta1.Subspace.subspace": - x.Subspace = "" - case "cosmos.params.v1beta1.Subspace.keys": - x.Keys = nil - default: - if fd.IsExtension() { - panic(fmt.Errorf("proto3 declared messages do not support extensions: cosmos.params.v1beta1.Subspace")) - } - panic(fmt.Errorf("message cosmos.params.v1beta1.Subspace does not contain field %s", fd.FullName())) - } -} - -// Get retrieves the value for a field. -// -// For unpopulated scalars, it returns the default value, where -// the default value of a bytes scalar is guaranteed to be a copy. -// For unpopulated composite types, it returns an empty, read-only view -// of the value; to obtain a mutable reference, use Mutable. -func (x *fastReflection_Subspace) Get(descriptor protoreflect.FieldDescriptor) protoreflect.Value { - switch descriptor.FullName() { - case "cosmos.params.v1beta1.Subspace.subspace": - value := x.Subspace - return protoreflect.ValueOfString(value) - case "cosmos.params.v1beta1.Subspace.keys": - if len(x.Keys) == 0 { - return protoreflect.ValueOfList(&_Subspace_2_list{}) - } - listValue := &_Subspace_2_list{list: &x.Keys} - return protoreflect.ValueOfList(listValue) - default: - if descriptor.IsExtension() { - panic(fmt.Errorf("proto3 declared messages do not support extensions: cosmos.params.v1beta1.Subspace")) - } - panic(fmt.Errorf("message cosmos.params.v1beta1.Subspace does not contain field %s", descriptor.FullName())) - } -} - -// Set stores the value for a field. -// -// For a field belonging to a oneof, it implicitly clears any other field -// that may be currently set within the same oneof. -// For extension fields, it implicitly stores the provided ExtensionType. -// When setting a composite type, it is unspecified whether the stored value -// aliases the source's memory in any way. If the composite value is an -// empty, read-only value, then it panics. -// -// Set is a mutating operation and unsafe for concurrent use. -func (x *fastReflection_Subspace) Set(fd protoreflect.FieldDescriptor, value protoreflect.Value) { - switch fd.FullName() { - case "cosmos.params.v1beta1.Subspace.subspace": - x.Subspace = value.Interface().(string) - case "cosmos.params.v1beta1.Subspace.keys": - lv := value.List() - clv := lv.(*_Subspace_2_list) - x.Keys = *clv.list - default: - if fd.IsExtension() { - panic(fmt.Errorf("proto3 declared messages do not support extensions: cosmos.params.v1beta1.Subspace")) - } - panic(fmt.Errorf("message cosmos.params.v1beta1.Subspace does not contain field %s", fd.FullName())) - } -} - -// Mutable returns a mutable reference to a composite type. -// -// If the field is unpopulated, it may allocate a composite value. -// For a field belonging to a oneof, it implicitly clears any other field -// that may be currently set within the same oneof. -// For extension fields, it implicitly stores the provided ExtensionType -// if not already stored. -// It panics if the field does not contain a composite type. -// -// Mutable is a mutating operation and unsafe for concurrent use. -func (x *fastReflection_Subspace) Mutable(fd protoreflect.FieldDescriptor) protoreflect.Value { - switch fd.FullName() { - case "cosmos.params.v1beta1.Subspace.keys": - if x.Keys == nil { - x.Keys = []string{} - } - value := &_Subspace_2_list{list: &x.Keys} - return protoreflect.ValueOfList(value) - case "cosmos.params.v1beta1.Subspace.subspace": - panic(fmt.Errorf("field subspace of message cosmos.params.v1beta1.Subspace is not mutable")) - default: - if fd.IsExtension() { - panic(fmt.Errorf("proto3 declared messages do not support extensions: cosmos.params.v1beta1.Subspace")) - } - panic(fmt.Errorf("message cosmos.params.v1beta1.Subspace does not contain field %s", fd.FullName())) - } -} - -// NewField returns a new value that is assignable to the field -// for the given descriptor. For scalars, this returns the default value. -// For lists, maps, and messages, this returns a new, empty, mutable value. -func (x *fastReflection_Subspace) NewField(fd protoreflect.FieldDescriptor) protoreflect.Value { - switch fd.FullName() { - case "cosmos.params.v1beta1.Subspace.subspace": - return protoreflect.ValueOfString("") - case "cosmos.params.v1beta1.Subspace.keys": - list := []string{} - return protoreflect.ValueOfList(&_Subspace_2_list{list: &list}) - default: - if fd.IsExtension() { - panic(fmt.Errorf("proto3 declared messages do not support extensions: cosmos.params.v1beta1.Subspace")) - } - panic(fmt.Errorf("message cosmos.params.v1beta1.Subspace does not contain field %s", fd.FullName())) - } -} - -// WhichOneof reports which field within the oneof is populated, -// returning nil if none are populated. -// It panics if the oneof descriptor does not belong to this message. -func (x *fastReflection_Subspace) WhichOneof(d protoreflect.OneofDescriptor) protoreflect.FieldDescriptor { - switch d.FullName() { - default: - panic(fmt.Errorf("%s is not a oneof field in cosmos.params.v1beta1.Subspace", d.FullName())) - } - panic("unreachable") -} - -// GetUnknown retrieves the entire list of unknown fields. -// The caller may only mutate the contents of the RawFields -// if the mutated bytes are stored back into the message with SetUnknown. -func (x *fastReflection_Subspace) GetUnknown() protoreflect.RawFields { - return x.unknownFields -} - -// SetUnknown stores an entire list of unknown fields. -// The raw fields must be syntactically valid according to the wire format. -// An implementation may panic if this is not the case. -// Once stored, the caller must not mutate the content of the RawFields. -// An empty RawFields may be passed to clear the fields. -// -// SetUnknown is a mutating operation and unsafe for concurrent use. -func (x *fastReflection_Subspace) SetUnknown(fields protoreflect.RawFields) { - x.unknownFields = fields -} - -// IsValid reports whether the message is valid. -// -// An invalid message is an empty, read-only value. -// -// An invalid message often corresponds to a nil pointer of the concrete -// message type, but the details are implementation dependent. -// Validity is not part of the protobuf data model, and may not -// be preserved in marshaling or other operations. -func (x *fastReflection_Subspace) IsValid() bool { - return x != nil -} - -// ProtoMethods returns optional fastReflectionFeature-path implementations of various operations. -// This method may return nil. -// -// The returned methods type is identical to -// "google.golang.org/protobuf/runtime/protoiface".Methods. -// Consult the protoiface package documentation for details. -func (x *fastReflection_Subspace) ProtoMethods() *protoiface.Methods { - size := func(input protoiface.SizeInput) protoiface.SizeOutput { - x := input.Message.Interface().(*Subspace) - if x == nil { - return protoiface.SizeOutput{ - NoUnkeyedLiterals: input.NoUnkeyedLiterals, - Size: 0, - } - } - options := runtime.SizeInputToOptions(input) - _ = options - var n int - var l int - _ = l - l = len(x.Subspace) - if l > 0 { - n += 1 + l + runtime.Sov(uint64(l)) - } - if len(x.Keys) > 0 { - for _, s := range x.Keys { - l = len(s) - n += 1 + l + runtime.Sov(uint64(l)) - } - } - if x.unknownFields != nil { - n += len(x.unknownFields) - } - return protoiface.SizeOutput{ - NoUnkeyedLiterals: input.NoUnkeyedLiterals, - Size: n, - } - } - - marshal := func(input protoiface.MarshalInput) (protoiface.MarshalOutput, error) { - x := input.Message.Interface().(*Subspace) - if x == nil { - return protoiface.MarshalOutput{ - NoUnkeyedLiterals: input.NoUnkeyedLiterals, - Buf: input.Buf, - }, nil - } - options := runtime.MarshalInputToOptions(input) - _ = options - size := options.Size(x) - dAtA := make([]byte, size) - i := len(dAtA) - _ = i - var l int - _ = l - if x.unknownFields != nil { - i -= len(x.unknownFields) - copy(dAtA[i:], x.unknownFields) - } - if len(x.Keys) > 0 { - for iNdEx := len(x.Keys) - 1; iNdEx >= 0; iNdEx-- { - i -= len(x.Keys[iNdEx]) - copy(dAtA[i:], x.Keys[iNdEx]) - i = runtime.EncodeVarint(dAtA, i, uint64(len(x.Keys[iNdEx]))) - i-- - dAtA[i] = 0x12 - } - } - if len(x.Subspace) > 0 { - i -= len(x.Subspace) - copy(dAtA[i:], x.Subspace) - i = runtime.EncodeVarint(dAtA, i, uint64(len(x.Subspace))) - i-- - dAtA[i] = 0xa - } - if input.Buf != nil { - input.Buf = append(input.Buf, dAtA...) - } else { - input.Buf = dAtA - } - return protoiface.MarshalOutput{ - NoUnkeyedLiterals: input.NoUnkeyedLiterals, - Buf: input.Buf, - }, nil - } - unmarshal := func(input protoiface.UnmarshalInput) (protoiface.UnmarshalOutput, error) { - x := input.Message.Interface().(*Subspace) - if x == nil { - return protoiface.UnmarshalOutput{ - NoUnkeyedLiterals: input.NoUnkeyedLiterals, - Flags: input.Flags, - }, nil - } - options := runtime.UnmarshalInputToOptions(input) - _ = options - dAtA := input.Buf - l := len(dAtA) - iNdEx := 0 - for iNdEx < l { - preIndex := iNdEx - var wire uint64 - for shift := uint(0); ; shift += 7 { - if shift >= 64 { - return protoiface.UnmarshalOutput{NoUnkeyedLiterals: input.NoUnkeyedLiterals, Flags: input.Flags}, runtime.ErrIntOverflow - } - if iNdEx >= l { - return protoiface.UnmarshalOutput{NoUnkeyedLiterals: input.NoUnkeyedLiterals, Flags: input.Flags}, io.ErrUnexpectedEOF - } - b := dAtA[iNdEx] - iNdEx++ - wire |= uint64(b&0x7F) << shift - if b < 0x80 { - break - } - } - fieldNum := int32(wire >> 3) - wireType := int(wire & 0x7) - if wireType == 4 { - return protoiface.UnmarshalOutput{NoUnkeyedLiterals: input.NoUnkeyedLiterals, Flags: input.Flags}, fmt.Errorf("proto: Subspace: wiretype end group for non-group") - } - if fieldNum <= 0 { - return protoiface.UnmarshalOutput{NoUnkeyedLiterals: input.NoUnkeyedLiterals, Flags: input.Flags}, fmt.Errorf("proto: Subspace: illegal tag %d (wire type %d)", fieldNum, wire) - } - switch fieldNum { - case 1: - if wireType != 2 { - return protoiface.UnmarshalOutput{NoUnkeyedLiterals: input.NoUnkeyedLiterals, Flags: input.Flags}, fmt.Errorf("proto: wrong wireType = %d for field Subspace", wireType) - } - var stringLen uint64 - for shift := uint(0); ; shift += 7 { - if shift >= 64 { - return protoiface.UnmarshalOutput{NoUnkeyedLiterals: input.NoUnkeyedLiterals, Flags: input.Flags}, runtime.ErrIntOverflow - } - if iNdEx >= l { - return protoiface.UnmarshalOutput{NoUnkeyedLiterals: input.NoUnkeyedLiterals, Flags: input.Flags}, io.ErrUnexpectedEOF - } - b := dAtA[iNdEx] - iNdEx++ - stringLen |= uint64(b&0x7F) << shift - if b < 0x80 { - break - } - } - intStringLen := int(stringLen) - if intStringLen < 0 { - return protoiface.UnmarshalOutput{NoUnkeyedLiterals: input.NoUnkeyedLiterals, Flags: input.Flags}, runtime.ErrInvalidLength - } - postIndex := iNdEx + intStringLen - if postIndex < 0 { - return protoiface.UnmarshalOutput{NoUnkeyedLiterals: input.NoUnkeyedLiterals, Flags: input.Flags}, runtime.ErrInvalidLength - } - if postIndex > l { - return protoiface.UnmarshalOutput{NoUnkeyedLiterals: input.NoUnkeyedLiterals, Flags: input.Flags}, io.ErrUnexpectedEOF - } - x.Subspace = string(dAtA[iNdEx:postIndex]) - iNdEx = postIndex - case 2: - if wireType != 2 { - return protoiface.UnmarshalOutput{NoUnkeyedLiterals: input.NoUnkeyedLiterals, Flags: input.Flags}, fmt.Errorf("proto: wrong wireType = %d for field Keys", wireType) - } - var stringLen uint64 - for shift := uint(0); ; shift += 7 { - if shift >= 64 { - return protoiface.UnmarshalOutput{NoUnkeyedLiterals: input.NoUnkeyedLiterals, Flags: input.Flags}, runtime.ErrIntOverflow - } - if iNdEx >= l { - return protoiface.UnmarshalOutput{NoUnkeyedLiterals: input.NoUnkeyedLiterals, Flags: input.Flags}, io.ErrUnexpectedEOF - } - b := dAtA[iNdEx] - iNdEx++ - stringLen |= uint64(b&0x7F) << shift - if b < 0x80 { - break - } - } - intStringLen := int(stringLen) - if intStringLen < 0 { - return protoiface.UnmarshalOutput{NoUnkeyedLiterals: input.NoUnkeyedLiterals, Flags: input.Flags}, runtime.ErrInvalidLength - } - postIndex := iNdEx + intStringLen - if postIndex < 0 { - return protoiface.UnmarshalOutput{NoUnkeyedLiterals: input.NoUnkeyedLiterals, Flags: input.Flags}, runtime.ErrInvalidLength - } - if postIndex > l { - return protoiface.UnmarshalOutput{NoUnkeyedLiterals: input.NoUnkeyedLiterals, Flags: input.Flags}, io.ErrUnexpectedEOF - } - x.Keys = append(x.Keys, string(dAtA[iNdEx:postIndex])) - iNdEx = postIndex - default: - iNdEx = preIndex - skippy, err := runtime.Skip(dAtA[iNdEx:]) - if err != nil { - return protoiface.UnmarshalOutput{NoUnkeyedLiterals: input.NoUnkeyedLiterals, Flags: input.Flags}, err - } - if (skippy < 0) || (iNdEx+skippy) < 0 { - return protoiface.UnmarshalOutput{NoUnkeyedLiterals: input.NoUnkeyedLiterals, Flags: input.Flags}, runtime.ErrInvalidLength - } - if (iNdEx + skippy) > l { - return protoiface.UnmarshalOutput{NoUnkeyedLiterals: input.NoUnkeyedLiterals, Flags: input.Flags}, io.ErrUnexpectedEOF - } - if !options.DiscardUnknown { - x.unknownFields = append(x.unknownFields, dAtA[iNdEx:iNdEx+skippy]...) - } - iNdEx += skippy - } - } - - if iNdEx > l { - return protoiface.UnmarshalOutput{NoUnkeyedLiterals: input.NoUnkeyedLiterals, Flags: input.Flags}, io.ErrUnexpectedEOF - } - return protoiface.UnmarshalOutput{NoUnkeyedLiterals: input.NoUnkeyedLiterals, Flags: input.Flags}, nil - } - return &protoiface.Methods{ - NoUnkeyedLiterals: struct{}{}, - Flags: protoiface.SupportMarshalDeterministic | protoiface.SupportUnmarshalDiscardUnknown, - Size: size, - Marshal: marshal, - Unmarshal: unmarshal, - Merge: nil, - CheckInitialized: nil, - } -} - -// Code generated by protoc-gen-go. DO NOT EDIT. -// versions: -// protoc-gen-go v1.27.0 -// protoc (unknown) -// source: cosmos/params/v1beta1/query.proto - -const ( - // Verify that this generated code is sufficiently up-to-date. - _ = protoimpl.EnforceVersion(20 - protoimpl.MinVersion) - // Verify that runtime/protoimpl is sufficiently up-to-date. - _ = protoimpl.EnforceVersion(protoimpl.MaxVersion - 20) -) - -// QueryParamsRequest is request type for the Query/Params RPC method. -type QueryParamsRequest struct { - state protoimpl.MessageState - sizeCache protoimpl.SizeCache - unknownFields protoimpl.UnknownFields - - // subspace defines the module to query the parameter for. - Subspace string `protobuf:"bytes,1,opt,name=subspace,proto3" json:"subspace,omitempty"` - // key defines the key of the parameter in the subspace. - Key string `protobuf:"bytes,2,opt,name=key,proto3" json:"key,omitempty"` -} - -func (x *QueryParamsRequest) Reset() { - *x = QueryParamsRequest{} - if protoimpl.UnsafeEnabled { - mi := &file_cosmos_params_v1beta1_query_proto_msgTypes[0] - ms := protoimpl.X.MessageStateOf(protoimpl.Pointer(x)) - ms.StoreMessageInfo(mi) - } -} - -func (x *QueryParamsRequest) String() string { - return protoimpl.X.MessageStringOf(x) -} - -func (*QueryParamsRequest) ProtoMessage() {} - -// Deprecated: Use QueryParamsRequest.ProtoReflect.Descriptor instead. -func (*QueryParamsRequest) Descriptor() ([]byte, []int) { - return file_cosmos_params_v1beta1_query_proto_rawDescGZIP(), []int{0} -} - -func (x *QueryParamsRequest) GetSubspace() string { - if x != nil { - return x.Subspace - } - return "" -} - -func (x *QueryParamsRequest) GetKey() string { - if x != nil { - return x.Key - } - return "" -} - -// QueryParamsResponse is response type for the Query/Params RPC method. -type QueryParamsResponse struct { - state protoimpl.MessageState - sizeCache protoimpl.SizeCache - unknownFields protoimpl.UnknownFields - - // param defines the queried parameter. - Param *ParamChange `protobuf:"bytes,1,opt,name=param,proto3" json:"param,omitempty"` -} - -func (x *QueryParamsResponse) Reset() { - *x = QueryParamsResponse{} - if protoimpl.UnsafeEnabled { - mi := &file_cosmos_params_v1beta1_query_proto_msgTypes[1] - ms := protoimpl.X.MessageStateOf(protoimpl.Pointer(x)) - ms.StoreMessageInfo(mi) - } -} - -func (x *QueryParamsResponse) String() string { - return protoimpl.X.MessageStringOf(x) -} - -func (*QueryParamsResponse) ProtoMessage() {} - -// Deprecated: Use QueryParamsResponse.ProtoReflect.Descriptor instead. -func (*QueryParamsResponse) Descriptor() ([]byte, []int) { - return file_cosmos_params_v1beta1_query_proto_rawDescGZIP(), []int{1} -} - -func (x *QueryParamsResponse) GetParam() *ParamChange { - if x != nil { - return x.Param - } - return nil -} - -// QuerySubspacesRequest defines a request type for querying for all registered -// subspaces and all keys for a subspace. -type QuerySubspacesRequest struct { - state protoimpl.MessageState - sizeCache protoimpl.SizeCache - unknownFields protoimpl.UnknownFields -} - -func (x *QuerySubspacesRequest) Reset() { - *x = QuerySubspacesRequest{} - if protoimpl.UnsafeEnabled { - mi := &file_cosmos_params_v1beta1_query_proto_msgTypes[2] - ms := protoimpl.X.MessageStateOf(protoimpl.Pointer(x)) - ms.StoreMessageInfo(mi) - } -} - -func (x *QuerySubspacesRequest) String() string { - return protoimpl.X.MessageStringOf(x) -} - -func (*QuerySubspacesRequest) ProtoMessage() {} - -// Deprecated: Use QuerySubspacesRequest.ProtoReflect.Descriptor instead. -func (*QuerySubspacesRequest) Descriptor() ([]byte, []int) { - return file_cosmos_params_v1beta1_query_proto_rawDescGZIP(), []int{2} -} - -// QuerySubspacesResponse defines the response types for querying for all -// registered subspaces and all keys for a subspace. -type QuerySubspacesResponse struct { - state protoimpl.MessageState - sizeCache protoimpl.SizeCache - unknownFields protoimpl.UnknownFields - - Subspaces []*Subspace `protobuf:"bytes,1,rep,name=subspaces,proto3" json:"subspaces,omitempty"` -} - -func (x *QuerySubspacesResponse) Reset() { - *x = QuerySubspacesResponse{} - if protoimpl.UnsafeEnabled { - mi := &file_cosmos_params_v1beta1_query_proto_msgTypes[3] - ms := protoimpl.X.MessageStateOf(protoimpl.Pointer(x)) - ms.StoreMessageInfo(mi) - } -} - -func (x *QuerySubspacesResponse) String() string { - return protoimpl.X.MessageStringOf(x) -} - -func (*QuerySubspacesResponse) ProtoMessage() {} - -// Deprecated: Use QuerySubspacesResponse.ProtoReflect.Descriptor instead. -func (*QuerySubspacesResponse) Descriptor() ([]byte, []int) { - return file_cosmos_params_v1beta1_query_proto_rawDescGZIP(), []int{3} -} - -func (x *QuerySubspacesResponse) GetSubspaces() []*Subspace { - if x != nil { - return x.Subspaces - } - return nil -} - -// Subspace defines a parameter subspace name and all the keys that exist for -// the subspace. -type Subspace struct { - state protoimpl.MessageState - sizeCache protoimpl.SizeCache - unknownFields protoimpl.UnknownFields - - Subspace string `protobuf:"bytes,1,opt,name=subspace,proto3" json:"subspace,omitempty"` - Keys []string `protobuf:"bytes,2,rep,name=keys,proto3" json:"keys,omitempty"` -} - -func (x *Subspace) Reset() { - *x = Subspace{} - if protoimpl.UnsafeEnabled { - mi := &file_cosmos_params_v1beta1_query_proto_msgTypes[4] - ms := protoimpl.X.MessageStateOf(protoimpl.Pointer(x)) - ms.StoreMessageInfo(mi) - } -} - -func (x *Subspace) String() string { - return protoimpl.X.MessageStringOf(x) -} - -func (*Subspace) ProtoMessage() {} - -// Deprecated: Use Subspace.ProtoReflect.Descriptor instead. -func (*Subspace) Descriptor() ([]byte, []int) { - return file_cosmos_params_v1beta1_query_proto_rawDescGZIP(), []int{4} -} - -func (x *Subspace) GetSubspace() string { - if x != nil { - return x.Subspace - } - return "" -} - -func (x *Subspace) GetKeys() []string { - if x != nil { - return x.Keys - } - return nil -} - -var File_cosmos_params_v1beta1_query_proto protoreflect.FileDescriptor - -var file_cosmos_params_v1beta1_query_proto_rawDesc = []byte{ - 0x0a, 0x21, 0x63, 0x6f, 0x73, 0x6d, 0x6f, 0x73, 0x2f, 0x70, 0x61, 0x72, 0x61, 0x6d, 0x73, 0x2f, - 0x76, 0x31, 0x62, 0x65, 0x74, 0x61, 0x31, 0x2f, 0x71, 0x75, 0x65, 0x72, 0x79, 0x2e, 0x70, 0x72, - 0x6f, 0x74, 0x6f, 0x12, 0x15, 0x63, 0x6f, 0x73, 0x6d, 0x6f, 0x73, 0x2e, 0x70, 0x61, 0x72, 0x61, - 0x6d, 0x73, 0x2e, 0x76, 0x31, 0x62, 0x65, 0x74, 0x61, 0x31, 0x1a, 0x14, 0x67, 0x6f, 0x67, 0x6f, - 0x70, 0x72, 0x6f, 0x74, 0x6f, 0x2f, 0x67, 0x6f, 0x67, 0x6f, 0x2e, 0x70, 0x72, 0x6f, 0x74, 0x6f, - 0x1a, 0x1c, 0x67, 0x6f, 0x6f, 0x67, 0x6c, 0x65, 0x2f, 0x61, 0x70, 0x69, 0x2f, 0x61, 0x6e, 0x6e, - 0x6f, 0x74, 0x61, 0x74, 0x69, 0x6f, 0x6e, 0x73, 0x2e, 0x70, 0x72, 0x6f, 0x74, 0x6f, 0x1a, 0x22, - 0x63, 0x6f, 0x73, 0x6d, 0x6f, 0x73, 0x2f, 0x70, 0x61, 0x72, 0x61, 0x6d, 0x73, 0x2f, 0x76, 0x31, - 0x62, 0x65, 0x74, 0x61, 0x31, 0x2f, 0x70, 0x61, 0x72, 0x61, 0x6d, 0x73, 0x2e, 0x70, 0x72, 0x6f, - 0x74, 0x6f, 0x1a, 0x11, 0x61, 0x6d, 0x69, 0x6e, 0x6f, 0x2f, 0x61, 0x6d, 0x69, 0x6e, 0x6f, 0x2e, - 0x70, 0x72, 0x6f, 0x74, 0x6f, 0x1a, 0x19, 0x63, 0x6f, 0x73, 0x6d, 0x6f, 0x73, 0x5f, 0x70, 0x72, - 0x6f, 0x74, 0x6f, 0x2f, 0x63, 0x6f, 0x73, 0x6d, 0x6f, 0x73, 0x2e, 0x70, 0x72, 0x6f, 0x74, 0x6f, - 0x22, 0x42, 0x0a, 0x12, 0x51, 0x75, 0x65, 0x72, 0x79, 0x50, 0x61, 0x72, 0x61, 0x6d, 0x73, 0x52, - 0x65, 0x71, 0x75, 0x65, 0x73, 0x74, 0x12, 0x1a, 0x0a, 0x08, 0x73, 0x75, 0x62, 0x73, 0x70, 0x61, - 0x63, 0x65, 0x18, 0x01, 0x20, 0x01, 0x28, 0x09, 0x52, 0x08, 0x73, 0x75, 0x62, 0x73, 0x70, 0x61, - 0x63, 0x65, 0x12, 0x10, 0x0a, 0x03, 0x6b, 0x65, 0x79, 0x18, 0x02, 0x20, 0x01, 0x28, 0x09, 0x52, - 0x03, 0x6b, 0x65, 0x79, 0x22, 0x5a, 0x0a, 0x13, 0x51, 0x75, 0x65, 0x72, 0x79, 0x50, 0x61, 0x72, - 0x61, 0x6d, 0x73, 0x52, 0x65, 0x73, 0x70, 0x6f, 0x6e, 0x73, 0x65, 0x12, 0x43, 0x0a, 0x05, 0x70, - 0x61, 0x72, 0x61, 0x6d, 0x18, 0x01, 0x20, 0x01, 0x28, 0x0b, 0x32, 0x22, 0x2e, 0x63, 0x6f, 0x73, - 0x6d, 0x6f, 0x73, 0x2e, 0x70, 0x61, 0x72, 0x61, 0x6d, 0x73, 0x2e, 0x76, 0x31, 0x62, 0x65, 0x74, - 0x61, 0x31, 0x2e, 0x50, 0x61, 0x72, 0x61, 0x6d, 0x43, 0x68, 0x61, 0x6e, 0x67, 0x65, 0x42, 0x09, - 0xc8, 0xde, 0x1f, 0x00, 0xa8, 0xe7, 0xb0, 0x2a, 0x01, 0x52, 0x05, 0x70, 0x61, 0x72, 0x61, 0x6d, - 0x22, 0x2c, 0x0a, 0x15, 0x51, 0x75, 0x65, 0x72, 0x79, 0x53, 0x75, 0x62, 0x73, 0x70, 0x61, 0x63, - 0x65, 0x73, 0x52, 0x65, 0x71, 0x75, 0x65, 0x73, 0x74, 0x3a, 0x13, 0xd2, 0xb4, 0x2d, 0x0f, 0x63, - 0x6f, 0x73, 0x6d, 0x6f, 0x73, 0x2d, 0x73, 0x64, 0x6b, 0x20, 0x30, 0x2e, 0x34, 0x36, 0x22, 0x6c, - 0x0a, 0x16, 0x51, 0x75, 0x65, 0x72, 0x79, 0x53, 0x75, 0x62, 0x73, 0x70, 0x61, 0x63, 0x65, 0x73, - 0x52, 0x65, 0x73, 0x70, 0x6f, 0x6e, 0x73, 0x65, 0x12, 0x3d, 0x0a, 0x09, 0x73, 0x75, 0x62, 0x73, - 0x70, 0x61, 0x63, 0x65, 0x73, 0x18, 0x01, 0x20, 0x03, 0x28, 0x0b, 0x32, 0x1f, 0x2e, 0x63, 0x6f, - 0x73, 0x6d, 0x6f, 0x73, 0x2e, 0x70, 0x61, 0x72, 0x61, 0x6d, 0x73, 0x2e, 0x76, 0x31, 0x62, 0x65, - 0x74, 0x61, 0x31, 0x2e, 0x53, 0x75, 0x62, 0x73, 0x70, 0x61, 0x63, 0x65, 0x52, 0x09, 0x73, 0x75, - 0x62, 0x73, 0x70, 0x61, 0x63, 0x65, 0x73, 0x3a, 0x13, 0xd2, 0xb4, 0x2d, 0x0f, 0x63, 0x6f, 0x73, - 0x6d, 0x6f, 0x73, 0x2d, 0x73, 0x64, 0x6b, 0x20, 0x30, 0x2e, 0x34, 0x36, 0x22, 0x4f, 0x0a, 0x08, - 0x53, 0x75, 0x62, 0x73, 0x70, 0x61, 0x63, 0x65, 0x12, 0x1a, 0x0a, 0x08, 0x73, 0x75, 0x62, 0x73, - 0x70, 0x61, 0x63, 0x65, 0x18, 0x01, 0x20, 0x01, 0x28, 0x09, 0x52, 0x08, 0x73, 0x75, 0x62, 0x73, - 0x70, 0x61, 0x63, 0x65, 0x12, 0x12, 0x0a, 0x04, 0x6b, 0x65, 0x79, 0x73, 0x18, 0x02, 0x20, 0x03, - 0x28, 0x09, 0x52, 0x04, 0x6b, 0x65, 0x79, 0x73, 0x3a, 0x13, 0xd2, 0xb4, 0x2d, 0x0f, 0x63, 0x6f, - 0x73, 0x6d, 0x6f, 0x73, 0x2d, 0x73, 0x64, 0x6b, 0x20, 0x30, 0x2e, 0x34, 0x36, 0x32, 0xb8, 0x02, - 0x0a, 0x05, 0x51, 0x75, 0x65, 0x72, 0x79, 0x12, 0x86, 0x01, 0x0a, 0x06, 0x50, 0x61, 0x72, 0x61, - 0x6d, 0x73, 0x12, 0x29, 0x2e, 0x63, 0x6f, 0x73, 0x6d, 0x6f, 0x73, 0x2e, 0x70, 0x61, 0x72, 0x61, - 0x6d, 0x73, 0x2e, 0x76, 0x31, 0x62, 0x65, 0x74, 0x61, 0x31, 0x2e, 0x51, 0x75, 0x65, 0x72, 0x79, - 0x50, 0x61, 0x72, 0x61, 0x6d, 0x73, 0x52, 0x65, 0x71, 0x75, 0x65, 0x73, 0x74, 0x1a, 0x2a, 0x2e, - 0x63, 0x6f, 0x73, 0x6d, 0x6f, 0x73, 0x2e, 0x70, 0x61, 0x72, 0x61, 0x6d, 0x73, 0x2e, 0x76, 0x31, - 0x62, 0x65, 0x74, 0x61, 0x31, 0x2e, 0x51, 0x75, 0x65, 0x72, 0x79, 0x50, 0x61, 0x72, 0x61, 0x6d, - 0x73, 0x52, 0x65, 0x73, 0x70, 0x6f, 0x6e, 0x73, 0x65, 0x22, 0x25, 0x82, 0xd3, 0xe4, 0x93, 0x02, - 0x1f, 0x12, 0x1d, 0x2f, 0x63, 0x6f, 0x73, 0x6d, 0x6f, 0x73, 0x2f, 0x70, 0x61, 0x72, 0x61, 0x6d, - 0x73, 0x2f, 0x76, 0x31, 0x62, 0x65, 0x74, 0x61, 0x31, 0x2f, 0x70, 0x61, 0x72, 0x61, 0x6d, 0x73, - 0x12, 0xa5, 0x01, 0x0a, 0x09, 0x53, 0x75, 0x62, 0x73, 0x70, 0x61, 0x63, 0x65, 0x73, 0x12, 0x2c, - 0x2e, 0x63, 0x6f, 0x73, 0x6d, 0x6f, 0x73, 0x2e, 0x70, 0x61, 0x72, 0x61, 0x6d, 0x73, 0x2e, 0x76, - 0x31, 0x62, 0x65, 0x74, 0x61, 0x31, 0x2e, 0x51, 0x75, 0x65, 0x72, 0x79, 0x53, 0x75, 0x62, 0x73, - 0x70, 0x61, 0x63, 0x65, 0x73, 0x52, 0x65, 0x71, 0x75, 0x65, 0x73, 0x74, 0x1a, 0x2d, 0x2e, 0x63, - 0x6f, 0x73, 0x6d, 0x6f, 0x73, 0x2e, 0x70, 0x61, 0x72, 0x61, 0x6d, 0x73, 0x2e, 0x76, 0x31, 0x62, - 0x65, 0x74, 0x61, 0x31, 0x2e, 0x51, 0x75, 0x65, 0x72, 0x79, 0x53, 0x75, 0x62, 0x73, 0x70, 0x61, - 0x63, 0x65, 0x73, 0x52, 0x65, 0x73, 0x70, 0x6f, 0x6e, 0x73, 0x65, 0x22, 0x3b, 0xca, 0xb4, 0x2d, - 0x0f, 0x63, 0x6f, 0x73, 0x6d, 0x6f, 0x73, 0x2d, 0x73, 0x64, 0x6b, 0x20, 0x30, 0x2e, 0x34, 0x36, - 0x82, 0xd3, 0xe4, 0x93, 0x02, 0x22, 0x12, 0x20, 0x2f, 0x63, 0x6f, 0x73, 0x6d, 0x6f, 0x73, 0x2f, - 0x70, 0x61, 0x72, 0x61, 0x6d, 0x73, 0x2f, 0x76, 0x31, 0x62, 0x65, 0x74, 0x61, 0x31, 0x2f, 0x73, - 0x75, 0x62, 0x73, 0x70, 0x61, 0x63, 0x65, 0x73, 0x42, 0xd3, 0x01, 0x0a, 0x19, 0x63, 0x6f, 0x6d, - 0x2e, 0x63, 0x6f, 0x73, 0x6d, 0x6f, 0x73, 0x2e, 0x70, 0x61, 0x72, 0x61, 0x6d, 0x73, 0x2e, 0x76, - 0x31, 0x62, 0x65, 0x74, 0x61, 0x31, 0x42, 0x0a, 0x51, 0x75, 0x65, 0x72, 0x79, 0x50, 0x72, 0x6f, - 0x74, 0x6f, 0x50, 0x01, 0x5a, 0x34, 0x63, 0x6f, 0x73, 0x6d, 0x6f, 0x73, 0x73, 0x64, 0x6b, 0x2e, - 0x69, 0x6f, 0x2f, 0x61, 0x70, 0x69, 0x2f, 0x63, 0x6f, 0x73, 0x6d, 0x6f, 0x73, 0x2f, 0x70, 0x61, - 0x72, 0x61, 0x6d, 0x73, 0x2f, 0x76, 0x31, 0x62, 0x65, 0x74, 0x61, 0x31, 0x3b, 0x70, 0x61, 0x72, - 0x61, 0x6d, 0x73, 0x76, 0x31, 0x62, 0x65, 0x74, 0x61, 0x31, 0xa2, 0x02, 0x03, 0x43, 0x50, 0x58, - 0xaa, 0x02, 0x15, 0x43, 0x6f, 0x73, 0x6d, 0x6f, 0x73, 0x2e, 0x50, 0x61, 0x72, 0x61, 0x6d, 0x73, - 0x2e, 0x56, 0x31, 0x62, 0x65, 0x74, 0x61, 0x31, 0xca, 0x02, 0x15, 0x43, 0x6f, 0x73, 0x6d, 0x6f, - 0x73, 0x5c, 0x50, 0x61, 0x72, 0x61, 0x6d, 0x73, 0x5c, 0x56, 0x31, 0x62, 0x65, 0x74, 0x61, 0x31, - 0xe2, 0x02, 0x21, 0x43, 0x6f, 0x73, 0x6d, 0x6f, 0x73, 0x5c, 0x50, 0x61, 0x72, 0x61, 0x6d, 0x73, - 0x5c, 0x56, 0x31, 0x62, 0x65, 0x74, 0x61, 0x31, 0x5c, 0x47, 0x50, 0x42, 0x4d, 0x65, 0x74, 0x61, - 0x64, 0x61, 0x74, 0x61, 0xea, 0x02, 0x17, 0x43, 0x6f, 0x73, 0x6d, 0x6f, 0x73, 0x3a, 0x3a, 0x50, - 0x61, 0x72, 0x61, 0x6d, 0x73, 0x3a, 0x3a, 0x56, 0x31, 0x62, 0x65, 0x74, 0x61, 0x31, 0x62, 0x06, - 0x70, 0x72, 0x6f, 0x74, 0x6f, 0x33, -} - -var ( - file_cosmos_params_v1beta1_query_proto_rawDescOnce sync.Once - file_cosmos_params_v1beta1_query_proto_rawDescData = file_cosmos_params_v1beta1_query_proto_rawDesc -) - -func file_cosmos_params_v1beta1_query_proto_rawDescGZIP() []byte { - file_cosmos_params_v1beta1_query_proto_rawDescOnce.Do(func() { - file_cosmos_params_v1beta1_query_proto_rawDescData = protoimpl.X.CompressGZIP(file_cosmos_params_v1beta1_query_proto_rawDescData) - }) - return file_cosmos_params_v1beta1_query_proto_rawDescData -} - -var file_cosmos_params_v1beta1_query_proto_msgTypes = make([]protoimpl.MessageInfo, 5) -var file_cosmos_params_v1beta1_query_proto_goTypes = []interface{}{ - (*QueryParamsRequest)(nil), // 0: cosmos.params.v1beta1.QueryParamsRequest - (*QueryParamsResponse)(nil), // 1: cosmos.params.v1beta1.QueryParamsResponse - (*QuerySubspacesRequest)(nil), // 2: cosmos.params.v1beta1.QuerySubspacesRequest - (*QuerySubspacesResponse)(nil), // 3: cosmos.params.v1beta1.QuerySubspacesResponse - (*Subspace)(nil), // 4: cosmos.params.v1beta1.Subspace - (*ParamChange)(nil), // 5: cosmos.params.v1beta1.ParamChange -} -var file_cosmos_params_v1beta1_query_proto_depIdxs = []int32{ - 5, // 0: cosmos.params.v1beta1.QueryParamsResponse.param:type_name -> cosmos.params.v1beta1.ParamChange - 4, // 1: cosmos.params.v1beta1.QuerySubspacesResponse.subspaces:type_name -> cosmos.params.v1beta1.Subspace - 0, // 2: cosmos.params.v1beta1.Query.Params:input_type -> cosmos.params.v1beta1.QueryParamsRequest - 2, // 3: cosmos.params.v1beta1.Query.Subspaces:input_type -> cosmos.params.v1beta1.QuerySubspacesRequest - 1, // 4: cosmos.params.v1beta1.Query.Params:output_type -> cosmos.params.v1beta1.QueryParamsResponse - 3, // 5: cosmos.params.v1beta1.Query.Subspaces:output_type -> cosmos.params.v1beta1.QuerySubspacesResponse - 4, // [4:6] is the sub-list for method output_type - 2, // [2:4] is the sub-list for method input_type - 2, // [2:2] is the sub-list for extension type_name - 2, // [2:2] is the sub-list for extension extendee - 0, // [0:2] is the sub-list for field type_name -} - -func init() { file_cosmos_params_v1beta1_query_proto_init() } -func file_cosmos_params_v1beta1_query_proto_init() { - if File_cosmos_params_v1beta1_query_proto != nil { - return - } - file_cosmos_params_v1beta1_params_proto_init() - if !protoimpl.UnsafeEnabled { - file_cosmos_params_v1beta1_query_proto_msgTypes[0].Exporter = func(v interface{}, i int) interface{} { - switch v := v.(*QueryParamsRequest); i { - case 0: - return &v.state - case 1: - return &v.sizeCache - case 2: - return &v.unknownFields - default: - return nil - } - } - file_cosmos_params_v1beta1_query_proto_msgTypes[1].Exporter = func(v interface{}, i int) interface{} { - switch v := v.(*QueryParamsResponse); i { - case 0: - return &v.state - case 1: - return &v.sizeCache - case 2: - return &v.unknownFields - default: - return nil - } - } - file_cosmos_params_v1beta1_query_proto_msgTypes[2].Exporter = func(v interface{}, i int) interface{} { - switch v := v.(*QuerySubspacesRequest); i { - case 0: - return &v.state - case 1: - return &v.sizeCache - case 2: - return &v.unknownFields - default: - return nil - } - } - file_cosmos_params_v1beta1_query_proto_msgTypes[3].Exporter = func(v interface{}, i int) interface{} { - switch v := v.(*QuerySubspacesResponse); i { - case 0: - return &v.state - case 1: - return &v.sizeCache - case 2: - return &v.unknownFields - default: - return nil - } - } - file_cosmos_params_v1beta1_query_proto_msgTypes[4].Exporter = func(v interface{}, i int) interface{} { - switch v := v.(*Subspace); i { - case 0: - return &v.state - case 1: - return &v.sizeCache - case 2: - return &v.unknownFields - default: - return nil - } - } - } - type x struct{} - out := protoimpl.TypeBuilder{ - File: protoimpl.DescBuilder{ - GoPackagePath: reflect.TypeOf(x{}).PkgPath(), - RawDescriptor: file_cosmos_params_v1beta1_query_proto_rawDesc, - NumEnums: 0, - NumMessages: 5, - NumExtensions: 0, - NumServices: 1, - }, - GoTypes: file_cosmos_params_v1beta1_query_proto_goTypes, - DependencyIndexes: file_cosmos_params_v1beta1_query_proto_depIdxs, - MessageInfos: file_cosmos_params_v1beta1_query_proto_msgTypes, - }.Build() - File_cosmos_params_v1beta1_query_proto = out.File - file_cosmos_params_v1beta1_query_proto_rawDesc = nil - file_cosmos_params_v1beta1_query_proto_goTypes = nil - file_cosmos_params_v1beta1_query_proto_depIdxs = nil -} diff --git a/api/cosmos/params/v1beta1/query_grpc.pb.go b/api/cosmos/params/v1beta1/query_grpc.pb.go deleted file mode 100644 index 5cb43788c07e..000000000000 --- a/api/cosmos/params/v1beta1/query_grpc.pb.go +++ /dev/null @@ -1,169 +0,0 @@ -// Code generated by protoc-gen-go-grpc. DO NOT EDIT. -// versions: -// - protoc-gen-go-grpc v1.5.1 -// - protoc (unknown) -// source: cosmos/params/v1beta1/query.proto - -package paramsv1beta1 - -import ( - context "context" - grpc "google.golang.org/grpc" - codes "google.golang.org/grpc/codes" - status "google.golang.org/grpc/status" -) - -// This is a compile-time assertion to ensure that this generated file -// is compatible with the grpc package it is being compiled against. -// Requires gRPC-Go v1.64.0 or later. -const _ = grpc.SupportPackageIsVersion9 - -const ( - Query_Params_FullMethodName = "/cosmos.params.v1beta1.Query/Params" - Query_Subspaces_FullMethodName = "/cosmos.params.v1beta1.Query/Subspaces" -) - -// QueryClient is the client API for Query service. -// -// For semantics around ctx use and closing/ending streaming RPCs, please refer to https://pkg.go.dev/google.golang.org/grpc/?tab=doc#ClientConn.NewStream. -// -// Query defines the gRPC querier service. -type QueryClient interface { - // Params queries a specific parameter of a module, given its subspace and - // key. - Params(ctx context.Context, in *QueryParamsRequest, opts ...grpc.CallOption) (*QueryParamsResponse, error) - // Subspaces queries for all registered subspaces and all keys for a subspace. - Subspaces(ctx context.Context, in *QuerySubspacesRequest, opts ...grpc.CallOption) (*QuerySubspacesResponse, error) -} - -type queryClient struct { - cc grpc.ClientConnInterface -} - -func NewQueryClient(cc grpc.ClientConnInterface) QueryClient { - return &queryClient{cc} -} - -func (c *queryClient) Params(ctx context.Context, in *QueryParamsRequest, opts ...grpc.CallOption) (*QueryParamsResponse, error) { - cOpts := append([]grpc.CallOption{grpc.StaticMethod()}, opts...) - out := new(QueryParamsResponse) - err := c.cc.Invoke(ctx, Query_Params_FullMethodName, in, out, cOpts...) - if err != nil { - return nil, err - } - return out, nil -} - -func (c *queryClient) Subspaces(ctx context.Context, in *QuerySubspacesRequest, opts ...grpc.CallOption) (*QuerySubspacesResponse, error) { - cOpts := append([]grpc.CallOption{grpc.StaticMethod()}, opts...) - out := new(QuerySubspacesResponse) - err := c.cc.Invoke(ctx, Query_Subspaces_FullMethodName, in, out, cOpts...) - if err != nil { - return nil, err - } - return out, nil -} - -// QueryServer is the server API for Query service. -// All implementations must embed UnimplementedQueryServer -// for forward compatibility. -// -// Query defines the gRPC querier service. -type QueryServer interface { - // Params queries a specific parameter of a module, given its subspace and - // key. - Params(context.Context, *QueryParamsRequest) (*QueryParamsResponse, error) - // Subspaces queries for all registered subspaces and all keys for a subspace. - Subspaces(context.Context, *QuerySubspacesRequest) (*QuerySubspacesResponse, error) - mustEmbedUnimplementedQueryServer() -} - -// UnimplementedQueryServer must be embedded to have -// forward compatible implementations. -// -// NOTE: this should be embedded by value instead of pointer to avoid a nil -// pointer dereference when methods are called. -type UnimplementedQueryServer struct{} - -func (UnimplementedQueryServer) Params(context.Context, *QueryParamsRequest) (*QueryParamsResponse, error) { - return nil, status.Errorf(codes.Unimplemented, "method Params not implemented") -} -func (UnimplementedQueryServer) Subspaces(context.Context, *QuerySubspacesRequest) (*QuerySubspacesResponse, error) { - return nil, status.Errorf(codes.Unimplemented, "method Subspaces not implemented") -} -func (UnimplementedQueryServer) mustEmbedUnimplementedQueryServer() {} -func (UnimplementedQueryServer) testEmbeddedByValue() {} - -// UnsafeQueryServer may be embedded to opt out of forward compatibility for this service. -// Use of this interface is not recommended, as added methods to QueryServer will -// result in compilation errors. -type UnsafeQueryServer interface { - mustEmbedUnimplementedQueryServer() -} - -func RegisterQueryServer(s grpc.ServiceRegistrar, srv QueryServer) { - // If the following call pancis, it indicates UnimplementedQueryServer was - // embedded by pointer and is nil. This will cause panics if an - // unimplemented method is ever invoked, so we test this at initialization - // time to prevent it from happening at runtime later due to I/O. - if t, ok := srv.(interface{ testEmbeddedByValue() }); ok { - t.testEmbeddedByValue() - } - s.RegisterService(&Query_ServiceDesc, srv) -} - -func _Query_Params_Handler(srv interface{}, ctx context.Context, dec func(interface{}) error, interceptor grpc.UnaryServerInterceptor) (interface{}, error) { - in := new(QueryParamsRequest) - if err := dec(in); err != nil { - return nil, err - } - if interceptor == nil { - return srv.(QueryServer).Params(ctx, in) - } - info := &grpc.UnaryServerInfo{ - Server: srv, - FullMethod: Query_Params_FullMethodName, - } - handler := func(ctx context.Context, req interface{}) (interface{}, error) { - return srv.(QueryServer).Params(ctx, req.(*QueryParamsRequest)) - } - return interceptor(ctx, in, info, handler) -} - -func _Query_Subspaces_Handler(srv interface{}, ctx context.Context, dec func(interface{}) error, interceptor grpc.UnaryServerInterceptor) (interface{}, error) { - in := new(QuerySubspacesRequest) - if err := dec(in); err != nil { - return nil, err - } - if interceptor == nil { - return srv.(QueryServer).Subspaces(ctx, in) - } - info := &grpc.UnaryServerInfo{ - Server: srv, - FullMethod: Query_Subspaces_FullMethodName, - } - handler := func(ctx context.Context, req interface{}) (interface{}, error) { - return srv.(QueryServer).Subspaces(ctx, req.(*QuerySubspacesRequest)) - } - return interceptor(ctx, in, info, handler) -} - -// Query_ServiceDesc is the grpc.ServiceDesc for Query service. -// It's only intended for direct use with grpc.RegisterService, -// and not to be introspected or modified (even as a copy) -var Query_ServiceDesc = grpc.ServiceDesc{ - ServiceName: "cosmos.params.v1beta1.Query", - HandlerType: (*QueryServer)(nil), - Methods: []grpc.MethodDesc{ - { - MethodName: "Params", - Handler: _Query_Params_Handler, - }, - { - MethodName: "Subspaces", - Handler: _Query_Subspaces_Handler, - }, - }, - Streams: []grpc.StreamDesc{}, - Metadata: "cosmos/params/v1beta1/query.proto", -} diff --git a/baseapp/params_legacy.go b/baseapp/params_legacy.go deleted file mode 100644 index c3671946057a..000000000000 --- a/baseapp/params_legacy.go +++ /dev/null @@ -1,150 +0,0 @@ -/* -Deprecated. - -Legacy types are defined below to aid in the migration of CometBFT consensus -parameters from use of the now deprecated x/params modules to a new dedicated -x/consensus module. - -Application developers should ensure that they implement their upgrade handler -correctly such that app.ConsensusParamsKeeper.Set() is called with the values -returned by GetConsensusParams(). - -Example: - - baseAppLegacySS := app.ParamsKeeper.Subspace(baseapp.Paramspace).WithKeyTable(paramstypes.ConsensusParamsKeyTable()) - - app.UpgradeKeeper.SetUpgradeHandler( - UpgradeName, - func(ctx sdk.Context, plan upgradetypes.Plan, fromVM module.VersionMap) (module.VersionMap, error) { - if cp := baseapp.GetConsensusParams(ctx, baseAppLegacySS); cp != nil { - app.ConsensusParamsKeeper.Set(ctx, cp) - } else { - ctx.Logger().Info("warning: consensus parameters are undefined; skipping migration", "upgrade", UpgradeName) - } - - return app.ModuleManager.RunMigrations(ctx, app.Configurator(), fromVM) - }, - ) - -Developers can also bypass the use of the legacy Params subspace and set the -values to app.ConsensusParamsKeeper.Set() explicitly. - -Note, for new chains this is not necessary as CometBFT's consensus parameters -will automatically be set for you in InitChain. -*/ -package baseapp - -import ( - "errors" - "fmt" - - cmtproto "github.com/cometbft/cometbft/proto/tendermint/types" - - sdk "github.com/cosmos/cosmos-sdk/types" -) - -const Paramspace = "baseapp" - -var ( - ParamStoreKeyBlockParams = []byte("BlockParams") - ParamStoreKeyEvidenceParams = []byte("EvidenceParams") - ParamStoreKeyValidatorParams = []byte("ValidatorParams") -) - -type LegacyParamStore interface { - Get(ctx sdk.Context, key []byte, ptr any) - Has(ctx sdk.Context, key []byte) bool -} - -func ValidateBlockParams(i any) error { - v, ok := i.(cmtproto.BlockParams) - if !ok { - return fmt.Errorf("invalid parameter type: %T", i) - } - - if v.MaxBytes <= 0 { - return fmt.Errorf("block maximum bytes must be positive: %d", v.MaxBytes) - } - - if v.MaxGas < -1 { - return fmt.Errorf("block maximum gas must be greater than or equal to -1: %d", v.MaxGas) - } - - return nil -} - -func ValidateEvidenceParams(i any) error { - v, ok := i.(cmtproto.EvidenceParams) - if !ok { - return fmt.Errorf("invalid parameter type: %T", i) - } - - if v.MaxAgeNumBlocks <= 0 { - return fmt.Errorf("evidence maximum age in blocks must be positive: %d", v.MaxAgeNumBlocks) - } - - if v.MaxAgeDuration <= 0 { - return fmt.Errorf("evidence maximum age time duration must be positive: %v", v.MaxAgeDuration) - } - - if v.MaxBytes < 0 { - return fmt.Errorf("maximum evidence bytes must be non-negative: %v", v.MaxBytes) - } - - return nil -} - -func ValidateValidatorParams(i any) error { - v, ok := i.(cmtproto.ValidatorParams) - if !ok { - return fmt.Errorf("invalid parameter type: %T", i) - } - - if len(v.PubKeyTypes) == 0 { - return errors.New("validator allowed pubkey types must not be empty") - } - - return nil -} - -func GetConsensusParams(ctx sdk.Context, paramStore LegacyParamStore) *cmtproto.ConsensusParams { - if paramStore == nil { - return nil - } - - cp := new(cmtproto.ConsensusParams) - - if paramStore.Has(ctx, ParamStoreKeyBlockParams) { - var bp cmtproto.BlockParams - - paramStore.Get(ctx, ParamStoreKeyBlockParams, &bp) - cp.Block = &bp - } - - if paramStore.Has(ctx, ParamStoreKeyEvidenceParams) { - var ep cmtproto.EvidenceParams - - paramStore.Get(ctx, ParamStoreKeyEvidenceParams, &ep) - cp.Evidence = &ep - } - - if paramStore.Has(ctx, ParamStoreKeyValidatorParams) { - var vp cmtproto.ValidatorParams - - paramStore.Get(ctx, ParamStoreKeyValidatorParams, &vp) - cp.Validator = &vp - } - - return cp -} - -func MigrateParams(ctx sdk.Context, lps LegacyParamStore, ps ParamStore) error { - if cp := GetConsensusParams(ctx, lps); cp != nil { - if err := ps.Set(ctx, *cp); err != nil { - return err - } - } else { - ctx.Logger().Info("warning: consensus parameters are undefined; skipping migration") - } - return nil -} diff --git a/baseapp/utils_test.go b/baseapp/utils_test.go index b447486d1962..28334e769bf5 100644 --- a/baseapp/utils_test.go +++ b/baseapp/utils_test.go @@ -50,7 +50,6 @@ import ( banktypes "github.com/cosmos/cosmos-sdk/x/bank/types" _ "github.com/cosmos/cosmos-sdk/x/consensus" _ "github.com/cosmos/cosmos-sdk/x/mint" - _ "github.com/cosmos/cosmos-sdk/x/params" _ "github.com/cosmos/cosmos-sdk/x/staking" ) diff --git a/client/v2/go.sum b/client/v2/go.sum index ae22e878b55c..1b4a4acd28de 100644 --- a/client/v2/go.sum +++ b/client/v2/go.sum @@ -115,8 +115,6 @@ github.com/cncf/xds/go v0.0.0-20210805033703-aa0b78936158/go.mod h1:eXthEFrGJvWH github.com/cncf/xds/go v0.0.0-20210922020428-25de7278fc84/go.mod h1:eXthEFrGJvWHgFFCl3hGmgk+/aYT6PnTQLykKQRLhEs= github.com/cncf/xds/go v0.0.0-20211001041855-01bcc9b48dfe/go.mod h1:eXthEFrGJvWHgFFCl3hGmgk+/aYT6PnTQLykKQRLhEs= github.com/cncf/xds/go v0.0.0-20211011173535-cb28da3451f1/go.mod h1:eXthEFrGJvWHgFFCl3hGmgk+/aYT6PnTQLykKQRLhEs= -github.com/cockroachdb/apd/v2 v2.0.2 h1:weh8u7Cneje73dDh+2tEVLUvyBc89iwepWCD8b8034E= -github.com/cockroachdb/apd/v2 v2.0.2/go.mod h1:DDxRlzC2lo3/vSlmSoS7JkqbbrARPuFOGr0B9pvN3Gw= github.com/cockroachdb/datadriven v0.0.0-20190809214429-80d97fb3cbaa/go.mod h1:zn76sxSg3SzpJ0PPJaLDCu+Bu0Lg3sKTORVIj19EIF8= github.com/cockroachdb/datadriven v1.0.3-0.20230413201302-be42291fc80f h1:otljaYPt5hWxV3MUfO5dFPFiOXg9CyG5/kCfayTqsJ4= github.com/cockroachdb/datadriven v1.0.3-0.20230413201302-be42291fc80f/go.mod h1:a9RdTaap04u637JoCzcUoIcDmvwSUtcUFtT/C3kJlTU= diff --git a/contrib/x/crisis/exported/exported.go b/contrib/x/crisis/exported/exported.go deleted file mode 100644 index 43772091f6bc..000000000000 --- a/contrib/x/crisis/exported/exported.go +++ /dev/null @@ -1,18 +0,0 @@ -package exported - -import ( - sdk "github.com/cosmos/cosmos-sdk/types" - paramtypes "github.com/cosmos/cosmos-sdk/x/params/types" -) - -type ( - ParamSet = paramtypes.ParamSet - - // Subspace defines an interface that implements the legacy x/params Subspace - // type. - // - // NOTE: This is used solely for migration of x/params managed parameters. - Subspace interface { - Get(ctx sdk.Context, key []byte, ptr any) - } -) diff --git a/contrib/x/crisis/keeper/migrations.go b/contrib/x/crisis/keeper/migrations.go new file mode 100644 index 000000000000..9444f8eb41a0 --- /dev/null +++ b/contrib/x/crisis/keeper/migrations.go @@ -0,0 +1,11 @@ +package keeper + +// Migrator is a struct for handling in-place store migrations. +type Migrator struct { + keeper *Keeper +} + +// NewMigrator returns a new Migrator. +func NewMigrator(keeper *Keeper) Migrator { + return Migrator{keeper: keeper} +} diff --git a/contrib/x/crisis/keeper/migrator.go b/contrib/x/crisis/keeper/migrator.go deleted file mode 100644 index 9aed493a445f..000000000000 --- a/contrib/x/crisis/keeper/migrator.go +++ /dev/null @@ -1,29 +0,0 @@ -package keeper - -import ( - "github.com/cosmos/cosmos-sdk/contrib/x/crisis/exported" - "github.com/cosmos/cosmos-sdk/contrib/x/crisis/migrations/v2" - sdk "github.com/cosmos/cosmos-sdk/types" -) - -// Migrator is a struct for handling in-place state migrations. -type Migrator struct { - keeper *Keeper - legacySubspace exported.Subspace -} - -// NewMigrator returns a new Migrator. -func NewMigrator(k *Keeper, ss exported.Subspace) Migrator { - return Migrator{ - keeper: k, - legacySubspace: ss, - } -} - -// Migrate1to2 migrates the x/crisis module state from the consensus version 1 to -// version 2. Specifically, it takes the parameters that are currently stored -// and managed by the x/params modules and stores them directly into the x/crisis -// module state. -func (m Migrator) Migrate1to2(ctx sdk.Context) error { - return v2.MigrateStore(ctx, m.keeper.storeService, m.legacySubspace, m.keeper.cdc) -} diff --git a/contrib/x/crisis/migrations/v2/migrate.go b/contrib/x/crisis/migrations/v2/migrate.go deleted file mode 100644 index e8fc0ebd8f90..000000000000 --- a/contrib/x/crisis/migrations/v2/migrate.go +++ /dev/null @@ -1,40 +0,0 @@ -package v2 - -import ( - storetypes "cosmossdk.io/core/store" - "github.com/cosmos/cosmos-sdk/contrib/x/crisis/exported" - - "github.com/cosmos/cosmos-sdk/codec" - sdk "github.com/cosmos/cosmos-sdk/types" - "github.com/cosmos/cosmos-sdk/types/errors" -) - -const ( - ModuleName = "crisis" -) - -var ( - ConstantFee = []byte("ConstantFee") - ConstantFeeKey = []byte{0x01} -) - -// MigrateStore migrates the x/crisis module state from the consensus version 1 to -// version 2. Specifically, it takes the `ConstantFee` parameter that is currently stored -// and managed by the x/params module and stores it directly into the x/crisis -// module state. -func MigrateStore(ctx sdk.Context, storeService storetypes.KVStoreService, legacySubspace exported.Subspace, cdc codec.BinaryCodec) error { - store := storeService.OpenKVStore(ctx) - var currConstantFee sdk.Coin - legacySubspace.Get(ctx, ConstantFee, &currConstantFee) - - if !currConstantFee.IsValid() { - return errors.ErrInvalidCoins.Wrap("constant fee") - } - - bz, err := cdc.Marshal(&currConstantFee) - if err != nil { - return err - } - - return store.Set(ConstantFeeKey, bz) -} diff --git a/contrib/x/crisis/migrations/v2/migrate_test.go b/contrib/x/crisis/migrations/v2/migrate_test.go deleted file mode 100644 index c4c9c3d5d87e..000000000000 --- a/contrib/x/crisis/migrations/v2/migrate_test.go +++ /dev/null @@ -1,47 +0,0 @@ -package v2_test - -import ( - "testing" - - "github.com/cosmos/cosmos-sdk/contrib/x/crisis" - "github.com/cosmos/cosmos-sdk/contrib/x/crisis/migrations/v2" - "github.com/cosmos/cosmos-sdk/contrib/x/crisis/types" - "github.com/stretchr/testify/require" - - storetypes "cosmossdk.io/store/types" - - "github.com/cosmos/cosmos-sdk/runtime" - "github.com/cosmos/cosmos-sdk/testutil" - sdk "github.com/cosmos/cosmos-sdk/types" - moduletestutil "github.com/cosmos/cosmos-sdk/types/module/testutil" -) - -type mockSubspace struct { - constantFee sdk.Coin -} - -func newMockSubspace(fee sdk.Coin) mockSubspace { - return mockSubspace{constantFee: fee} -} - -func (ms mockSubspace) Get(ctx sdk.Context, key []byte, ptr any) { - *ptr.(*sdk.Coin) = ms.constantFee -} - -func TestMigrate(t *testing.T) { - cdc := moduletestutil.MakeTestEncodingConfig(crisis.AppModuleBasic{}).Codec - storeKey := storetypes.NewKVStoreKey(v2.ModuleName) - storeService := runtime.NewKVStoreService(storeKey) - tKey := storetypes.NewTransientStoreKey("transient_test") - ctx := testutil.DefaultContext(storeKey, tKey) - store := ctx.KVStore(storeKey) - - legacySubspace := newMockSubspace(types.DefaultGenesisState().ConstantFee) - require.NoError(t, v2.MigrateStore(ctx, storeService, legacySubspace, cdc)) - - var res sdk.Coin - bz := store.Get(v2.ConstantFeeKey) - require.NoError(t, cdc.Unmarshal(bz, &res)) - require.NotNil(t, res) - require.Equal(t, legacySubspace.constantFee, res) -} diff --git a/contrib/x/crisis/module.go b/contrib/x/crisis/module.go index 2d5fa6fedcb0..82d413af67ec 100644 --- a/contrib/x/crisis/module.go +++ b/contrib/x/crisis/module.go @@ -5,9 +5,8 @@ import ( "encoding/json" "fmt" - "github.com/cosmos/cosmos-sdk/contrib/x/crisis/exported" - keeper2 "github.com/cosmos/cosmos-sdk/contrib/x/crisis/keeper" - types2 "github.com/cosmos/cosmos-sdk/contrib/x/crisis/types" + "github.com/cosmos/cosmos-sdk/contrib/x/crisis/keeper" + "github.com/cosmos/cosmos-sdk/contrib/x/crisis/types" gwruntime "github.com/grpc-ecosystem/grpc-gateway/runtime" "github.com/spf13/cast" "github.com/spf13/cobra" @@ -53,28 +52,28 @@ type AppModuleBasic struct{} // Name returns the crisis module's name. func (AppModuleBasic) Name() string { - return types2.ModuleName + return types.ModuleName } // RegisterLegacyAminoCodec registers the crisis module's types on the given LegacyAmino codec. func (AppModuleBasic) RegisterLegacyAminoCodec(cdc *codec.LegacyAmino) { - types2.RegisterLegacyAminoCodec(cdc) + types.RegisterLegacyAminoCodec(cdc) } // DefaultGenesis returns default genesis state as raw bytes for the crisis // module. func (AppModuleBasic) DefaultGenesis(cdc codec.JSONCodec) json.RawMessage { - return cdc.MustMarshalJSON(types2.DefaultGenesisState()) + return cdc.MustMarshalJSON(types.DefaultGenesisState()) } // ValidateGenesis performs genesis state validation for the crisis module. func (AppModuleBasic) ValidateGenesis(cdc codec.JSONCodec, config client.TxEncodingConfig, bz json.RawMessage) error { - var data types2.GenesisState + var data types.GenesisState if err := cdc.UnmarshalJSON(bz, &data); err != nil { - return fmt.Errorf("failed to unmarshal %s genesis state: %w", types2.ModuleName, err) + return fmt.Errorf("failed to unmarshal %s genesis state: %w", types.ModuleName, err) } - return types2.ValidateGenesis(&data) + return types.ValidateGenesis(&data) } // RegisterGRPCGatewayRoutes registers the gRPC Gateway routes for the crisis module. @@ -83,7 +82,7 @@ func (AppModuleBasic) RegisterGRPCGatewayRoutes(_ client.Context, _ *gwruntime.S // RegisterInterfaces registers interfaces and implementations of the crisis // module. func (AppModuleBasic) RegisterInterfaces(registry codectypes.InterfaceRegistry) { - types2.RegisterInterfaces(registry) + types.RegisterInterfaces(registry) } // AppModule implements an application module for the crisis module. @@ -95,10 +94,7 @@ type AppModule struct { // NOTE: We store a reference to the keeper here so that after a module // manager is created, the invariants can be properly registered and // executed. - keeper *keeper2.Keeper - - // legacySubspace is used solely for migration of x/params managed parameters - legacySubspace exported.Subspace + keeper *keeper.Keeper skipGenesisInvariants bool } @@ -109,11 +105,10 @@ type AppModule struct { // modified genesis file. // // Deprecated: the crisis module is deprecated and will be removed in the next Cosmos SDK major release. -func NewAppModule(keeper *keeper2.Keeper, skipGenesisInvariants bool, ss exported.Subspace) AppModule { +func NewAppModule(keeper *keeper.Keeper, skipGenesisInvariants bool) AppModule { return AppModule{ AppModuleBasic: AppModuleBasic{}, keeper: keeper, - legacySubspace: ss, skipGenesisInvariants: skipGenesisInvariants, } @@ -134,18 +129,15 @@ func AddModuleInitFlags(startCmd *cobra.Command) { // RegisterServices registers module services. func (am AppModule) RegisterServices(cfg module.Configurator) { - types2.RegisterMsgServer(cfg.MsgServer(), am.keeper) + types.RegisterMsgServer(cfg.MsgServer(), am.keeper) - m := keeper2.NewMigrator(am.keeper, am.legacySubspace) - if err := cfg.RegisterMigration(types2.ModuleName, 1, m.Migrate1to2); err != nil { - panic(fmt.Sprintf("failed to migrate x/%s from version 1 to 2: %v", types2.ModuleName, err)) - } + _ = keeper.NewMigrator(am.keeper) } // InitGenesis performs genesis initialization for the crisis module. It returns // no validator updates. func (am AppModule) InitGenesis(ctx sdk.Context, cdc codec.JSONCodec, data json.RawMessage) { - var genesisState types2.GenesisState + var genesisState types.GenesisState cdc.MustUnmarshalJSON(data, &genesisState) am.keeper.InitGenesis(ctx, &genesisState) @@ -188,18 +180,15 @@ type ModuleInputs struct { Cdc codec.Codec AppOpts servertypes.AppOptions `optional:"true"` - BankKeeper types2.SupplyKeeper + BankKeeper types.SupplyKeeper AddressCodec address.Codec - - // LegacySubspace is used solely for migration of x/params managed parameters - LegacySubspace exported.Subspace `optional:"true"` } type ModuleOutputs struct { depinject.Out Module appmodule.AppModule - CrisisKeeper *keeper2.Keeper + CrisisKeeper *keeper.Keeper } func ProvideModule(in ModuleInputs) ModuleOutputs { @@ -219,7 +208,7 @@ func ProvideModule(in ModuleInputs) ModuleOutputs { authority = authtypes.NewModuleAddressOrBech32Address(in.Config.Authority) } - k := keeper2.NewKeeper( + k := keeper.NewKeeper( in.Cdc, in.StoreService, invalidCheckPeriod, @@ -234,7 +223,7 @@ func ProvideModule(in ModuleInputs) ModuleOutputs { skipGenesisInvariants = cast.ToBool(in.AppOpts.Get(FlagSkipGenesisInvariants)) } - m := NewAppModule(k, skipGenesisInvariants, in.LegacySubspace) + m := NewAppModule(k, skipGenesisInvariants) return ModuleOutputs{CrisisKeeper: k, Module: m} } diff --git a/contrib/x/crisis/types/legacy_params.go b/contrib/x/crisis/types/legacy_params.go deleted file mode 100644 index 5aae3e252e1c..000000000000 --- a/contrib/x/crisis/types/legacy_params.go +++ /dev/null @@ -1,31 +0,0 @@ -package types - -import ( - "fmt" - - sdk "github.com/cosmos/cosmos-sdk/types" - paramtypes "github.com/cosmos/cosmos-sdk/x/params/types" -) - -// ParamStoreKeyConstantFee is the constant fee parameter -var ParamStoreKeyConstantFee = []byte("ConstantFee") - -// Deprecated: Type declaration for parameters -func ParamKeyTable() paramtypes.KeyTable { - return paramtypes.NewKeyTable( - paramtypes.NewParamSetPair(ParamStoreKeyConstantFee, sdk.Coin{}, validateConstantFee), - ) -} - -func validateConstantFee(i any) error { - v, ok := i.(sdk.Coin) - if !ok { - return fmt.Errorf("invalid parameter type: %T", i) - } - - if !v.IsValid() { - return fmt.Errorf("invalid constant fee: %s", v) - } - - return nil -} diff --git a/contrib/x/group/testutil/app_config.go b/contrib/x/group/testutil/app_config.go index 4c6099a49960..505719b40e0a 100644 --- a/contrib/x/group/testutil/app_config.go +++ b/contrib/x/group/testutil/app_config.go @@ -10,7 +10,6 @@ import ( _ "github.com/cosmos/cosmos-sdk/x/consensus" // import as blank for app wiring _ "github.com/cosmos/cosmos-sdk/x/genutil" // import as blank for app wiring _ "github.com/cosmos/cosmos-sdk/x/mint" // import as blank for app wiring - _ "github.com/cosmos/cosmos-sdk/x/params" // import as blank for app wiring _ "github.com/cosmos/cosmos-sdk/x/staking" // import as blank for app wiring ) @@ -20,7 +19,6 @@ var AppConfig = configurator.NewAppConfig( configurator.StakingModule(), configurator.TxModule(), configurator.ConsensusModule(), - configurator.ParamsModule(), configurator.GenutilModule(), configurator.GroupModule(), ) diff --git a/contrib/x/nft/testutil/app_config.go b/contrib/x/nft/testutil/app_config.go index 7473e8a92db6..c6765f7b99d9 100644 --- a/contrib/x/nft/testutil/app_config.go +++ b/contrib/x/nft/testutil/app_config.go @@ -9,7 +9,6 @@ import ( _ "github.com/cosmos/cosmos-sdk/x/consensus" // import as blank for app wiring _ "github.com/cosmos/cosmos-sdk/x/genutil" // import as blank for app wiring _ "github.com/cosmos/cosmos-sdk/x/mint" // import as blank for app wiring - _ "github.com/cosmos/cosmos-sdk/x/params" // import as blank for app wiring _ "github.com/cosmos/cosmos-sdk/x/staking" // import as blank for app wiring ) @@ -19,7 +18,6 @@ var AppConfig = configurator.NewAppConfig( configurator.StakingModule(), configurator.TxModule(), configurator.ConsensusModule(), - configurator.ParamsModule(), configurator.GenutilModule(), configurator.MintModule(), configurator.NFTModule(), diff --git a/proto/cosmos/params/module/v1/module.proto b/proto/cosmos/params/module/v1/module.proto deleted file mode 100644 index 75e7f99583d2..000000000000 --- a/proto/cosmos/params/module/v1/module.proto +++ /dev/null @@ -1,12 +0,0 @@ -syntax = "proto3"; - -package cosmos.params.module.v1; - -import "cosmos/app/v1alpha1/module.proto"; - -// Module is the config object of the params module. -message Module { - option (cosmos.app.v1alpha1.module) = { - go_import: "github.com/cosmos/cosmos-sdk/x/params" - }; -} diff --git a/proto/cosmos/params/v1beta1/params.proto b/proto/cosmos/params/v1beta1/params.proto deleted file mode 100644 index c8efa13106d0..000000000000 --- a/proto/cosmos/params/v1beta1/params.proto +++ /dev/null @@ -1,28 +0,0 @@ -syntax = "proto3"; -package cosmos.params.v1beta1; - -option go_package = "github.com/cosmos/cosmos-sdk/x/params/types/proposal"; -option (gogoproto.equal_all) = true; - -import "gogoproto/gogo.proto"; -import "cosmos_proto/cosmos.proto"; -import "amino/amino.proto"; - -// ParameterChangeProposal defines a proposal to change one or more parameters. -message ParameterChangeProposal { - option (gogoproto.goproto_getters) = false; - option (cosmos_proto.implements_interface) = "cosmos.gov.v1beta1.Content"; - option (amino.name) = "cosmos-sdk/ParameterChangeProposal"; - - string title = 1; - string description = 2; - repeated ParamChange changes = 3 [(gogoproto.nullable) = false, (amino.dont_omitempty) = true]; -} - -// ParamChange defines an individual parameter change, for use in -// ParameterChangeProposal. -message ParamChange { - string subspace = 1; - string key = 2; - string value = 3; -} diff --git a/proto/cosmos/params/v1beta1/query.proto b/proto/cosmos/params/v1beta1/query.proto deleted file mode 100644 index e8f3bf1515bd..000000000000 --- a/proto/cosmos/params/v1beta1/query.proto +++ /dev/null @@ -1,61 +0,0 @@ -syntax = "proto3"; -package cosmos.params.v1beta1; - -import "gogoproto/gogo.proto"; -import "google/api/annotations.proto"; -import "cosmos/params/v1beta1/params.proto"; -import "amino/amino.proto"; -import "cosmos_proto/cosmos.proto"; - -option go_package = "github.com/cosmos/cosmos-sdk/x/params/types/proposal"; - -// Query defines the gRPC querier service. -service Query { - // Params queries a specific parameter of a module, given its subspace and - // key. - rpc Params(QueryParamsRequest) returns (QueryParamsResponse) { - option (google.api.http).get = "/cosmos/params/v1beta1/params"; - } - - // Subspaces queries for all registered subspaces and all keys for a subspace. - rpc Subspaces(QuerySubspacesRequest) returns (QuerySubspacesResponse) { - option (cosmos_proto.method_added_in) = "cosmos-sdk 0.46"; - option (google.api.http).get = "/cosmos/params/v1beta1/subspaces"; - } -} - -// QueryParamsRequest is request type for the Query/Params RPC method. -message QueryParamsRequest { - // subspace defines the module to query the parameter for. - string subspace = 1; - - // key defines the key of the parameter in the subspace. - string key = 2; -} - -// QueryParamsResponse is response type for the Query/Params RPC method. -message QueryParamsResponse { - // param defines the queried parameter. - ParamChange param = 1 [(gogoproto.nullable) = false, (amino.dont_omitempty) = true]; -} - -// QuerySubspacesRequest defines a request type for querying for all registered -// subspaces and all keys for a subspace. -message QuerySubspacesRequest { - option (cosmos_proto.message_added_in) = "cosmos-sdk 0.46"; -} - -// QuerySubspacesResponse defines the response types for querying for all -// registered subspaces and all keys for a subspace. -message QuerySubspacesResponse { - option (cosmos_proto.message_added_in) = "cosmos-sdk 0.46"; - repeated Subspace subspaces = 1; -} - -// Subspace defines a parameter subspace name and all the keys that exist for -// the subspace. -message Subspace { - option (cosmos_proto.message_added_in) = "cosmos-sdk 0.46"; - string subspace = 1; - repeated string keys = 2; -} diff --git a/scripts/mockgen.sh b/scripts/mockgen.sh index 1b41201e991d..b83cdf574c1c 100755 --- a/scripts/mockgen.sh +++ b/scripts/mockgen.sh @@ -11,7 +11,6 @@ $mockgen_cmd -package mock -destination testutil/mock/grpc_server.go github.com/ $mockgen_cmd -package mock -destination testutil/mock/logger.go cosmossdk.io/log Logger $mockgen_cmd -source=x/feegrant/expected_keepers.go -package testutil -destination x/feegrant/testutil/expected_keepers_mocks.go $mockgen_cmd -source=x/mint/types/expected_keepers.go -package testutil -destination x/mint/testutil/expected_keepers_mocks.go -$mockgen_cmd -source=x/params/proposal_handler_test.go -package testutil -destination x/params/testutil/staking_keeper_mock.go $mockgen_cmd -source=x/auth/tx/config/expected_keepers.go -package testutil -destination x/auth/tx/testutil/expected_keepers_mocks.go $mockgen_cmd -source=x/auth/types/expected_keepers.go -package testutil -destination x/auth/testutil/expected_keepers_mocks.go $mockgen_cmd -source=x/auth/ante/expected_keepers.go -package testutil -destination x/auth/ante/testutil/expected_keepers_mocks.go diff --git a/server/api/server_test.go b/server/api/server_test.go index c7df73bab9c6..ea2ae9bf424e 100644 --- a/server/api/server_test.go +++ b/server/api/server_test.go @@ -28,7 +28,6 @@ import ( _ "github.com/cosmos/cosmos-sdk/x/bank" banktypes "github.com/cosmos/cosmos-sdk/x/bank/types" _ "github.com/cosmos/cosmos-sdk/x/genutil" - _ "github.com/cosmos/cosmos-sdk/x/params" _ "github.com/cosmos/cosmos-sdk/x/staking" ) diff --git a/simapp/app.go b/simapp/app.go index 7c38a667d6f3..e5e7670bc885 100644 --- a/simapp/app.go +++ b/simapp/app.go @@ -470,15 +470,15 @@ func NewSimApp( app.AccountKeeper, app.StakingKeeper, app, txConfig, ), - auth.NewAppModule(appCodec, app.AccountKeeper, authsims.RandomGenesisAccounts, nil), + auth.NewAppModule(appCodec, app.AccountKeeper, authsims.RandomGenesisAccounts), vesting.NewAppModule(app.AccountKeeper, app.BankKeeper), - bank.NewAppModule(appCodec, app.BankKeeper, app.AccountKeeper, nil), + bank.NewAppModule(appCodec, app.BankKeeper, app.AccountKeeper), feegrantmodule.NewAppModule(appCodec, app.AccountKeeper, app.BankKeeper, app.FeeGrantKeeper, app.interfaceRegistry), - gov.NewAppModule(appCodec, &app.GovKeeper, app.AccountKeeper, app.BankKeeper, nil), - mint.NewAppModule(appCodec, app.MintKeeper, app.AccountKeeper, nil, nil), - slashing.NewAppModule(appCodec, app.SlashingKeeper, app.AccountKeeper, app.BankKeeper, app.StakingKeeper, nil, app.interfaceRegistry), - distr.NewAppModule(appCodec, app.DistrKeeper, app.AccountKeeper, app.BankKeeper, app.StakingKeeper, nil), - staking.NewAppModule(appCodec, app.StakingKeeper, app.AccountKeeper, app.BankKeeper, nil), + gov.NewAppModule(appCodec, &app.GovKeeper, app.AccountKeeper, app.BankKeeper), + mint.NewAppModule(appCodec, app.MintKeeper, app.AccountKeeper, nil), + slashing.NewAppModule(appCodec, app.SlashingKeeper, app.AccountKeeper, app.BankKeeper, app.StakingKeeper, app.interfaceRegistry), + distr.NewAppModule(appCodec, app.DistrKeeper, app.AccountKeeper, app.BankKeeper, app.StakingKeeper), + staking.NewAppModule(appCodec, app.StakingKeeper, app.AccountKeeper, app.BankKeeper), upgrade.NewAppModule(app.UpgradeKeeper, app.AccountKeeper.AddressCodec()), evidence.NewAppModule(app.EvidenceKeeper), authzmodule.NewAppModule(appCodec, app.AuthzKeeper, app.AccountKeeper, app.BankKeeper, app.interfaceRegistry), @@ -604,7 +604,7 @@ func NewSimApp( // NOTE: this is not required apps that don't use the simulator for fuzz testing // transactions overrideModules := map[string]module.AppModuleSimulation{ - authtypes.ModuleName: auth.NewAppModule(app.appCodec, app.AccountKeeper, authsims.RandomGenesisAccounts, nil), + authtypes.ModuleName: auth.NewAppModule(app.appCodec, app.AccountKeeper, authsims.RandomGenesisAccounts), } app.sm = module.NewSimulationManagerFromAppModules(app.ModuleManager.Modules, overrideModules) diff --git a/simapp/app_di.go b/simapp/app_di.go index 972edc75fa1a..610797eeb3dd 100644 --- a/simapp/app_di.go +++ b/simapp/app_di.go @@ -232,7 +232,7 @@ func NewSimApp( // NOTE: this is not required apps that don't use the simulator for fuzz testing // transactions overrideModules := map[string]module.AppModuleSimulation{ - authtypes.ModuleName: auth.NewAppModule(app.appCodec, app.AccountKeeper, authsims.RandomGenesisAccounts, nil), + authtypes.ModuleName: auth.NewAppModule(app.appCodec, app.AccountKeeper, authsims.RandomGenesisAccounts), } app.sm = module.NewSimulationManagerFromAppModules(app.ModuleManager.Modules, overrideModules) diff --git a/simapp/go.mod b/simapp/go.mod index 2fad2d50cfdb..6663cbec2798 100644 --- a/simapp/go.mod +++ b/simapp/go.mod @@ -76,7 +76,6 @@ require ( github.com/chzyer/readline v1.5.1 // indirect github.com/cloudwego/base64x v0.1.6 // indirect github.com/cncf/xds/go v0.0.0-20251022180443-0feb69152e9f // indirect - github.com/cockroachdb/apd/v2 v2.0.2 // indirect github.com/cockroachdb/errors v1.12.0 // indirect github.com/cockroachdb/fifo v0.0.0-20240816210425-c5d0cb0b6fc0 // indirect github.com/cockroachdb/logtags v0.0.0-20241215232642-bb51bb14a506 // indirect diff --git a/simapp/go.sum b/simapp/go.sum index 1721e6cee239..242c2ed04fc0 100644 --- a/simapp/go.sum +++ b/simapp/go.sum @@ -193,8 +193,6 @@ github.com/cncf/xds/go v0.0.0-20211001041855-01bcc9b48dfe/go.mod h1:eXthEFrGJvWH github.com/cncf/xds/go v0.0.0-20211011173535-cb28da3451f1/go.mod h1:eXthEFrGJvWHgFFCl3hGmgk+/aYT6PnTQLykKQRLhEs= github.com/cncf/xds/go v0.0.0-20251022180443-0feb69152e9f h1:Y8xYupdHxryycyPlc9Y+bSQAYZnetRJ70VMVKm5CKI0= github.com/cncf/xds/go v0.0.0-20251022180443-0feb69152e9f/go.mod h1:HlzOvOjVBOfTGSRXRyY0OiCS/3J1akRGQQpRO/7zyF4= -github.com/cockroachdb/apd/v2 v2.0.2 h1:weh8u7Cneje73dDh+2tEVLUvyBc89iwepWCD8b8034E= -github.com/cockroachdb/apd/v2 v2.0.2/go.mod h1:DDxRlzC2lo3/vSlmSoS7JkqbbrARPuFOGr0B9pvN3Gw= github.com/cockroachdb/datadriven v0.0.0-20190809214429-80d97fb3cbaa/go.mod h1:zn76sxSg3SzpJ0PPJaLDCu+Bu0Lg3sKTORVIj19EIF8= github.com/cockroachdb/datadriven v1.0.3-0.20230413201302-be42291fc80f h1:otljaYPt5hWxV3MUfO5dFPFiOXg9CyG5/kCfayTqsJ4= github.com/cockroachdb/datadriven v1.0.3-0.20230413201302-be42291fc80f/go.mod h1:a9RdTaap04u637JoCzcUoIcDmvwSUtcUFtT/C3kJlTU= diff --git a/systemtests/go.sum b/systemtests/go.sum index 63664b4509cf..209cc8fe3e44 100644 --- a/systemtests/go.sum +++ b/systemtests/go.sum @@ -113,8 +113,6 @@ github.com/cncf/xds/go v0.0.0-20210805033703-aa0b78936158/go.mod h1:eXthEFrGJvWH github.com/cncf/xds/go v0.0.0-20210922020428-25de7278fc84/go.mod h1:eXthEFrGJvWHgFFCl3hGmgk+/aYT6PnTQLykKQRLhEs= github.com/cncf/xds/go v0.0.0-20211001041855-01bcc9b48dfe/go.mod h1:eXthEFrGJvWHgFFCl3hGmgk+/aYT6PnTQLykKQRLhEs= github.com/cncf/xds/go v0.0.0-20211011173535-cb28da3451f1/go.mod h1:eXthEFrGJvWHgFFCl3hGmgk+/aYT6PnTQLykKQRLhEs= -github.com/cockroachdb/apd/v2 v2.0.2 h1:weh8u7Cneje73dDh+2tEVLUvyBc89iwepWCD8b8034E= -github.com/cockroachdb/apd/v2 v2.0.2/go.mod h1:DDxRlzC2lo3/vSlmSoS7JkqbbrARPuFOGr0B9pvN3Gw= github.com/cockroachdb/datadriven v0.0.0-20190809214429-80d97fb3cbaa/go.mod h1:zn76sxSg3SzpJ0PPJaLDCu+Bu0Lg3sKTORVIj19EIF8= github.com/cockroachdb/datadriven v1.0.3-0.20230413201302-be42291fc80f h1:otljaYPt5hWxV3MUfO5dFPFiOXg9CyG5/kCfayTqsJ4= github.com/cockroachdb/datadriven v1.0.3-0.20230413201302-be42291fc80f/go.mod h1:a9RdTaap04u637JoCzcUoIcDmvwSUtcUFtT/C3kJlTU= diff --git a/tests/integration/bank/keeper/deterministic_test.go b/tests/integration/bank/keeper/deterministic_test.go index d5fe027f5c61..8f54f93a75cb 100644 --- a/tests/integration/bank/keeper/deterministic_test.go +++ b/tests/integration/bank/keeper/deterministic_test.go @@ -30,7 +30,6 @@ import ( banktypes "github.com/cosmos/cosmos-sdk/x/bank/types" _ "github.com/cosmos/cosmos-sdk/x/consensus" minttypes "github.com/cosmos/cosmos-sdk/x/mint/types" - _ "github.com/cosmos/cosmos-sdk/x/params" _ "github.com/cosmos/cosmos-sdk/x/staking" ) @@ -102,8 +101,8 @@ func initDeterministicFixture(t *testing.T) *deterministicFixture { log.NewNopLogger(), ) - authModule := auth.NewAppModule(cdc, accountKeeper, authsims.RandomGenesisAccounts, nil) - bankModule := bank.NewAppModule(cdc, bankKeeper, accountKeeper, nil) + authModule := auth.NewAppModule(cdc, accountKeeper, authsims.RandomGenesisAccounts) + bankModule := bank.NewAppModule(cdc, bankKeeper, accountKeeper) integrationApp := integration.NewIntegrationApp(newCtx, logger, keys, cdc, map[string]appmodule.AppModule{ authtypes.ModuleName: authModule, diff --git a/tests/integration/distribution/keeper/msg_server_test.go b/tests/integration/distribution/keeper/msg_server_test.go index fdb654f4a10c..004b0dc818cb 100644 --- a/tests/integration/distribution/keeper/msg_server_test.go +++ b/tests/integration/distribution/keeper/msg_server_test.go @@ -110,10 +110,10 @@ func initFixture(tb testing.TB) *fixture { cdc, runtime.NewKVStoreService(keys[distrtypes.StoreKey]), accountKeeper, bankKeeper, stakingKeeper, distrtypes.ModuleName, authority.String(), ) - authModule := auth.NewAppModule(cdc, accountKeeper, authsims.RandomGenesisAccounts, nil) - bankModule := bank.NewAppModule(cdc, bankKeeper, accountKeeper, nil) - stakingModule := staking.NewAppModule(cdc, stakingKeeper, accountKeeper, bankKeeper, nil) - distrModule := distribution.NewAppModule(cdc, distrKeeper, accountKeeper, bankKeeper, stakingKeeper, nil) + authModule := auth.NewAppModule(cdc, accountKeeper, authsims.RandomGenesisAccounts) + bankModule := bank.NewAppModule(cdc, bankKeeper, accountKeeper) + stakingModule := staking.NewAppModule(cdc, stakingKeeper, accountKeeper, bankKeeper) + distrModule := distribution.NewAppModule(cdc, distrKeeper, accountKeeper, bankKeeper, stakingKeeper) addr := sdk.AccAddress(PKS[0].Address()) valAddr := sdk.ValAddress(addr) diff --git a/tests/integration/evidence/keeper/infraction_test.go b/tests/integration/evidence/keeper/infraction_test.go index ae92069802f8..a313218668da 100644 --- a/tests/integration/evidence/keeper/infraction_test.go +++ b/tests/integration/evidence/keeper/infraction_test.go @@ -129,10 +129,10 @@ func initFixture(tb testing.TB) *fixture { router = router.AddRoute(evidencetypes.RouteEquivocation, testEquivocationHandler(evidenceKeeper)) evidenceKeeper.SetRouter(router) - authModule := auth.NewAppModule(cdc, accountKeeper, authsims.RandomGenesisAccounts, nil) - bankModule := bank.NewAppModule(cdc, bankKeeper, accountKeeper, nil) - stakingModule := staking.NewAppModule(cdc, stakingKeeper, accountKeeper, bankKeeper, nil) - slashingModule := slashing.NewAppModule(cdc, slashingKeeper, accountKeeper, bankKeeper, stakingKeeper, nil, cdc.InterfaceRegistry()) + authModule := auth.NewAppModule(cdc, accountKeeper, authsims.RandomGenesisAccounts) + bankModule := bank.NewAppModule(cdc, bankKeeper, accountKeeper) + stakingModule := staking.NewAppModule(cdc, stakingKeeper, accountKeeper, bankKeeper) + slashingModule := slashing.NewAppModule(cdc, slashingKeeper, accountKeeper, bankKeeper, stakingKeeper, cdc.InterfaceRegistry()) evidenceModule := evidence.NewAppModule(*evidenceKeeper) integrationApp := integration.NewIntegrationApp(newCtx, logger, keys, cdc, map[string]appmodule.AppModule{ diff --git a/tests/integration/gov/genesis_test.go b/tests/integration/gov/genesis_test.go index 72c8b1753464..bc19c9399e60 100644 --- a/tests/integration/gov/genesis_test.go +++ b/tests/integration/gov/genesis_test.go @@ -30,7 +30,6 @@ import ( "github.com/cosmos/cosmos-sdk/x/gov/keeper" "github.com/cosmos/cosmos-sdk/x/gov/types" v1 "github.com/cosmos/cosmos-sdk/x/gov/types/v1" - _ "github.com/cosmos/cosmos-sdk/x/params" _ "github.com/cosmos/cosmos-sdk/x/staking" stakingkeeper "github.com/cosmos/cosmos-sdk/x/staking/keeper" stakingtypes "github.com/cosmos/cosmos-sdk/x/staking/types" @@ -48,7 +47,6 @@ type suite struct { } var appConfig = configurator.NewAppConfig( - configurator.ParamsModule(), configurator.AuthModule(), configurator.StakingModule(), configurator.BankModule(), diff --git a/tests/integration/gov/keeper/grpc_query_test.go b/tests/integration/gov/keeper/grpc_query_test.go index 7729807c5f01..ecc61f545c0d 100644 --- a/tests/integration/gov/keeper/grpc_query_test.go +++ b/tests/integration/gov/keeper/grpc_query_test.go @@ -10,7 +10,6 @@ import ( "cosmossdk.io/math" v1 "github.com/cosmos/cosmos-sdk/x/gov/types/v1" - "github.com/cosmos/cosmos-sdk/x/gov/types/v1beta1" ) func TestGRPCQueryTally(t *testing.T) { @@ -133,138 +132,3 @@ func TestGRPCQueryTally(t *testing.T) { }) } } - -func TestLegacyGRPCQueryTally(t *testing.T) { - t.Parallel() - - f := initFixture(t) - - ctx, queryClient := f.ctx, f.legacyQueryClient - - addrs, _ := createValidators(t, f, []int64{5, 5, 5}) - - var ( - req *v1beta1.QueryTallyResultRequest - expRes *v1beta1.QueryTallyResultResponse - proposal v1.Proposal - ) - - testCases := []struct { - msg string - malleate func() - expPass bool - expErrMsg string - }{ - { - "empty request", - func() { - req = &v1beta1.QueryTallyResultRequest{} - }, - false, - "proposal id can not be 0", - }, - { - "zero proposal id request", - func() { - req = &v1beta1.QueryTallyResultRequest{ProposalId: 0} - }, - false, - "proposal id can not be 0", - }, - { - "query non existed proposal", - func() { - req = &v1beta1.QueryTallyResultRequest{ProposalId: 1} - }, - false, - "proposal 1 doesn't exist", - }, - { - "create a proposal and get tally", - func() { - var err error - proposal, err = f.govKeeper.SubmitProposal(ctx, TestProposal, "", "test", "description", addrs[0], false) - assert.NilError(t, err) - assert.Assert(t, proposal.String() != "") - - req = &v1beta1.QueryTallyResultRequest{ProposalId: proposal.Id} - - tallyResult := v1beta1.EmptyTallyResult() - expRes = &v1beta1.QueryTallyResultResponse{ - Tally: tallyResult, - } - }, - true, - "", - }, - { - "request tally after few votes", - func() { - proposal.Status = v1.StatusVotingPeriod - assert.NilError(t, f.govKeeper.SetProposal(ctx, proposal)) - - assert.NilError(t, f.govKeeper.AddVote(ctx, proposal.Id, addrs[0], v1.NewNonSplitVoteOption(v1.OptionYes), "")) - assert.NilError(t, f.govKeeper.AddVote(ctx, proposal.Id, addrs[1], v1.NewNonSplitVoteOption(v1.OptionYes), "")) - assert.NilError(t, f.govKeeper.AddVote(ctx, proposal.Id, addrs[2], v1.NewNonSplitVoteOption(v1.OptionYes), "")) - - req = &v1beta1.QueryTallyResultRequest{ProposalId: proposal.Id} - - expRes = &v1beta1.QueryTallyResultResponse{ - Tally: v1beta1.TallyResult{ - Yes: math.NewInt(3 * 5 * 1000000), - No: math.NewInt(0), - Abstain: math.NewInt(0), - NoWithVeto: math.NewInt(0), - }, - } - }, - true, - "", - }, - { - "request final tally after status changed", - func() { - proposal.Status = v1.StatusPassed - assert.NilError(t, f.govKeeper.SetProposal(ctx, proposal)) - proposal, _ = f.govKeeper.Proposals.Get(ctx, proposal.Id) - - req = &v1beta1.QueryTallyResultRequest{ProposalId: proposal.Id} - - expRes = &v1beta1.QueryTallyResultResponse{ - Tally: v1TallyToV1Beta1Tally(*proposal.FinalTallyResult), - } - }, - true, - "", - }, - } - - for _, testCase := range testCases { - t.Run(fmt.Sprintf("Case %s", testCase.msg), func(t *testing.T) { - testCase.malleate() - - tally, err := queryClient.TallyResult(gocontext.Background(), req) - - if testCase.expPass { - assert.NilError(t, err) - assert.Equal(t, expRes.String(), tally.String()) - } else { - assert.ErrorContains(t, err, testCase.expErrMsg) - assert.Assert(t, tally == nil) - } - }) - } -} - -func v1TallyToV1Beta1Tally(t v1.TallyResult) v1beta1.TallyResult { - yes, _ := math.NewIntFromString(t.YesCount) - no, _ := math.NewIntFromString(t.NoCount) - noWithVeto, _ := math.NewIntFromString(t.NoWithVetoCount) - abstain, _ := math.NewIntFromString(t.AbstainCount) - return v1beta1.TallyResult{ - Yes: yes, - No: no, - NoWithVeto: noWithVeto, - Abstain: abstain, - } -} diff --git a/tests/integration/gov/keeper/keeper_test.go b/tests/integration/gov/keeper/keeper_test.go index 6bb58e03b6ac..b71f4c42f2d3 100644 --- a/tests/integration/gov/keeper/keeper_test.go +++ b/tests/integration/gov/keeper/keeper_test.go @@ -40,8 +40,7 @@ import ( type fixture struct { ctx sdk.Context - queryClient v1.QueryClient - legacyQueryClient v1beta1.QueryClient + queryClient v1.QueryClient bankKeeper bankkeeper.Keeper stakingKeeper *stakingkeeper.Keeper @@ -127,11 +126,11 @@ func initFixture(tb testing.TB) *fixture { err = govKeeper.Params.Set(newCtx, v1.DefaultParams()) assert.NilError(tb, err) - authModule := auth.NewAppModule(cdc, accountKeeper, authsims.RandomGenesisAccounts, nil) - bankModule := bank.NewAppModule(cdc, bankKeeper, accountKeeper, nil) - stakingModule := staking.NewAppModule(cdc, stakingKeeper, accountKeeper, bankKeeper, nil) - distrModule := distribution.NewAppModule(cdc, distrKeeper, accountKeeper, bankKeeper, stakingKeeper, nil) - govModule := gov.NewAppModule(cdc, govKeeper, accountKeeper, bankKeeper, nil) + authModule := auth.NewAppModule(cdc, accountKeeper, authsims.RandomGenesisAccounts) + bankModule := bank.NewAppModule(cdc, bankKeeper, accountKeeper) + stakingModule := staking.NewAppModule(cdc, stakingKeeper, accountKeeper, bankKeeper) + distrModule := distribution.NewAppModule(cdc, distrKeeper, accountKeeper, bankKeeper, stakingKeeper) + govModule := gov.NewAppModule(cdc, govKeeper, accountKeeper, bankKeeper) integrationApp := integration.NewIntegrationApp(newCtx, logger, keys, cdc, map[string]appmodule.AppModule{ authtypes.ModuleName: authModule, @@ -151,17 +150,14 @@ func initFixture(tb testing.TB) *fixture { v1beta1.RegisterMsgServer(router, legacyMsgSrvr) v1.RegisterQueryServer(integrationApp.QueryHelper(), keeper.NewQueryServer(govKeeper)) - v1beta1.RegisterQueryServer(integrationApp.QueryHelper(), keeper.NewLegacyQueryServer(govKeeper)) queryClient := v1.NewQueryClient(integrationApp.QueryHelper()) - legacyQueryClient := v1beta1.NewQueryClient(integrationApp.QueryHelper()) return &fixture{ - ctx: sdkCtx, - queryClient: queryClient, - legacyQueryClient: legacyQueryClient, - bankKeeper: bankKeeper, - stakingKeeper: stakingKeeper, - govKeeper: govKeeper, + ctx: sdkCtx, + queryClient: queryClient, + bankKeeper: bankKeeper, + stakingKeeper: stakingKeeper, + govKeeper: govKeeper, } } diff --git a/tests/integration/gov/module_test.go b/tests/integration/gov/module_test.go index 9596240afcef..b1ff34f6223d 100644 --- a/tests/integration/gov/module_test.go +++ b/tests/integration/gov/module_test.go @@ -22,7 +22,6 @@ func TestItCreatesModuleAccountOnInitBlock(t *testing.T) { app, err := simtestutil.SetupAtGenesis( depinject.Configs( configurator.NewAppConfig( - configurator.ParamsModule(), configurator.AuthModule(), configurator.StakingModule(), configurator.BankModule(), diff --git a/tests/integration/rapidgen/rapidgen.go b/tests/integration/rapidgen/rapidgen.go index 8ee2962962bc..2686abf7eeba 100644 --- a/tests/integration/rapidgen/rapidgen.go +++ b/tests/integration/rapidgen/rapidgen.go @@ -23,7 +23,6 @@ import ( gov_v1_api "cosmossdk.io/api/cosmos/gov/v1" gov_v1beta1_api "cosmossdk.io/api/cosmos/gov/v1beta1" mintapi "cosmossdk.io/api/cosmos/mint/v1beta1" - paramsapi "cosmossdk.io/api/cosmos/params/v1beta1" slashingapi "cosmossdk.io/api/cosmos/slashing/v1beta1" stakingapi "cosmossdk.io/api/cosmos/staking/v1beta1" upgradeapi "cosmossdk.io/api/cosmos/upgrade/v1beta1" @@ -40,7 +39,6 @@ import ( gov_v1_types "github.com/cosmos/cosmos-sdk/x/gov/types/v1" gov_v1beta1_types "github.com/cosmos/cosmos-sdk/x/gov/types/v1beta1" minttypes "github.com/cosmos/cosmos-sdk/x/mint/types" - "github.com/cosmos/cosmos-sdk/x/params/types/proposal" slashingtypes "github.com/cosmos/cosmos-sdk/x/slashing/types" stakingtypes "github.com/cosmos/cosmos-sdk/x/staking/types" upgradetypes "github.com/cosmos/cosmos-sdk/x/upgrade/types" @@ -222,7 +220,6 @@ var ( GenType(&minttypes.Params{}, &mintapi.Params{}, GenOpts), // params - GenType(&proposal.ParameterChangeProposal{}, ¶msapi.ParameterChangeProposal{}, GenOpts), GenType(&slashingtypes.Params{}, &slashingapi.Params{}, GenOpts.WithDisallowNil()), diff --git a/tests/integration/runtime/query_test.go b/tests/integration/runtime/query_test.go index 1642d4dfeff0..a66ca3d9ce25 100644 --- a/tests/integration/runtime/query_test.go +++ b/tests/integration/runtime/query_test.go @@ -24,7 +24,6 @@ import ( _ "github.com/cosmos/cosmos-sdk/x/auth/tx/config" _ "github.com/cosmos/cosmos-sdk/x/bank" _ "github.com/cosmos/cosmos-sdk/x/consensus" - _ "github.com/cosmos/cosmos-sdk/x/params" _ "github.com/cosmos/cosmos-sdk/x/staking" ) @@ -45,7 +44,6 @@ func initFixture(t assert.TestingT) *fixture { configurator.NewAppConfig( configurator.AuthModule(), configurator.TxModule(), - configurator.ParamsModule(), configurator.ConsensusModule(), configurator.BankModule(), configurator.StakingModule(), @@ -83,7 +81,7 @@ func TestQueryAppConfig(t *testing.T) { } // has all expected modules - for _, modName := range []string{"auth", "bank", "tx", "consensus", "runtime", "params", "staking"} { + for _, modName := range []string{"auth", "bank", "tx", "consensus", "runtime", "staking"} { modConfig := moduleConfigs[modName] if modConfig == nil { t.Fatalf("missing %s", modName) diff --git a/tests/integration/slashing/keeper/keeper_test.go b/tests/integration/slashing/keeper/keeper_test.go index 24216328bf9e..0428f8cc73a7 100644 --- a/tests/integration/slashing/keeper/keeper_test.go +++ b/tests/integration/slashing/keeper/keeper_test.go @@ -96,9 +96,9 @@ func initFixture(tb testing.TB) *fixture { slashingKeeper := slashingkeeper.NewKeeper(cdc, &codec.LegacyAmino{}, runtime.NewKVStoreService(keys[slashingtypes.StoreKey]), stakingKeeper, authority.String()) - bankModule := bank.NewAppModule(cdc, bankKeeper, accountKeeper, nil) - stakingModule := staking.NewAppModule(cdc, stakingKeeper, accountKeeper, bankKeeper, nil) - slashingModule := slashing.NewAppModule(cdc, slashingKeeper, accountKeeper, bankKeeper, stakingKeeper, nil, cdc.InterfaceRegistry()) + bankModule := bank.NewAppModule(cdc, bankKeeper, accountKeeper) + stakingModule := staking.NewAppModule(cdc, stakingKeeper, accountKeeper, bankKeeper) + slashingModule := slashing.NewAppModule(cdc, slashingKeeper, accountKeeper, bankKeeper, stakingKeeper, cdc.InterfaceRegistry()) integrationApp := integration.NewIntegrationApp(newCtx, logger, keys, cdc, map[string]appmodule.AppModule{ banktypes.ModuleName: bankModule, diff --git a/tests/integration/staking/keeper/common_test.go b/tests/integration/staking/keeper/common_test.go index 7ed49482d348..ee688201331d 100644 --- a/tests/integration/staking/keeper/common_test.go +++ b/tests/integration/staking/keeper/common_test.go @@ -141,9 +141,9 @@ func initFixture(tb testing.TB) *fixture { stakingKeeper := stakingkeeper.NewKeeper(cdc, runtime.NewKVStoreService(keys[types.StoreKey]), accountKeeper, bankKeeper, authority.String(), addresscodec.NewBech32Codec(sdk.Bech32PrefixValAddr), addresscodec.NewBech32Codec(sdk.Bech32PrefixConsAddr)) - authModule := auth.NewAppModule(cdc, accountKeeper, authsims.RandomGenesisAccounts, nil) - bankModule := bank.NewAppModule(cdc, bankKeeper, accountKeeper, nil) - stakingModule := staking.NewAppModule(cdc, stakingKeeper, accountKeeper, bankKeeper, nil) + authModule := auth.NewAppModule(cdc, accountKeeper, authsims.RandomGenesisAccounts) + bankModule := bank.NewAppModule(cdc, bankKeeper, accountKeeper) + stakingModule := staking.NewAppModule(cdc, stakingKeeper, accountKeeper, bankKeeper) integrationApp := integration.NewIntegrationApp(newCtx, logger, keys, cdc, map[string]appmodule.AppModule{ authtypes.ModuleName: authModule, diff --git a/tests/integration/staking/keeper/determinstic_test.go b/tests/integration/staking/keeper/determinstic_test.go index 170c51535d56..3083bcafad60 100644 --- a/tests/integration/staking/keeper/determinstic_test.go +++ b/tests/integration/staking/keeper/determinstic_test.go @@ -110,9 +110,9 @@ func initDeterministicFixture(t *testing.T) *deterministicFixture { stakingKeeper := stakingkeeper.NewKeeper(cdc, runtime.NewKVStoreService(keys[stakingtypes.StoreKey]), accountKeeper, bankKeeper, authority.String(), addresscodec.NewBech32Codec(sdk.Bech32PrefixValAddr), addresscodec.NewBech32Codec(sdk.Bech32PrefixConsAddr)) - authModule := auth.NewAppModule(cdc, accountKeeper, authsims.RandomGenesisAccounts, nil) - bankModule := bank.NewAppModule(cdc, bankKeeper, accountKeeper, nil) - stakingModule := staking.NewAppModule(cdc, stakingKeeper, accountKeeper, bankKeeper, nil) + authModule := auth.NewAppModule(cdc, accountKeeper, authsims.RandomGenesisAccounts) + bankModule := bank.NewAppModule(cdc, bankKeeper, accountKeeper) + stakingModule := staking.NewAppModule(cdc, stakingKeeper, accountKeeper, bankKeeper) integrationApp := integration.NewIntegrationApp(newCtx, logger, keys, cdc, map[string]appmodule.AppModule{ authtypes.ModuleName: authModule, diff --git a/tests/integration/tx/aminojson/aminojson_test.go b/tests/integration/tx/aminojson/aminojson_test.go index 965859306a7d..240dcfb60555 100644 --- a/tests/integration/tx/aminojson/aminojson_test.go +++ b/tests/integration/tx/aminojson/aminojson_test.go @@ -69,7 +69,6 @@ import ( gov_v1_types "github.com/cosmos/cosmos-sdk/x/gov/types/v1" gov_v1beta1_types "github.com/cosmos/cosmos-sdk/x/gov/types/v1beta1" "github.com/cosmos/cosmos-sdk/x/mint" - "github.com/cosmos/cosmos-sdk/x/params" "github.com/cosmos/cosmos-sdk/x/slashing" slashingtypes "github.com/cosmos/cosmos-sdk/x/slashing/types" "github.com/cosmos/cosmos-sdk/x/staking" @@ -95,7 +94,7 @@ func TestAminoJSON_Equivalence(t *testing.T) { encCfg := testutil.MakeTestEncodingConfig( auth.AppModuleBasic{}, authzmodule.AppModuleBasic{}, bank.AppModuleBasic{}, consensus.AppModuleBasic{}, distribution.AppModuleBasic{}, evidence.AppModuleBasic{}, feegrantmodule.AppModuleBasic{}, - gov.AppModuleBasic{}, groupmodule.AppModuleBasic{}, mint.AppModuleBasic{}, params.AppModuleBasic{}, + gov.AppModuleBasic{}, groupmodule.AppModuleBasic{}, mint.AppModuleBasic{}, slashing.AppModuleBasic{}, staking.AppModuleBasic{}, upgrade.AppModuleBasic{}, vesting.AppModuleBasic{}) legacytx.RegressionTestingAminoCodec = encCfg.Amino aj := aminojson.NewEncoder(aminojson.EncoderOptions{}) diff --git a/tests/integration/tx/context_test.go b/tests/integration/tx/context_test.go index 2210c9c934fd..7246a2c798d1 100644 --- a/tests/integration/tx/context_test.go +++ b/tests/integration/tx/context_test.go @@ -33,7 +33,6 @@ func TestDefineCustomGetSigners(t *testing.T) { _, err := simtestutil.SetupAtGenesis( depinject.Configs( configurator.NewAppConfig( - configurator.ParamsModule(), configurator.AuthModule(), configurator.StakingModule(), configurator.BankModule(), @@ -61,7 +60,6 @@ func TestDefineCustomGetSigners(t *testing.T) { _, err = simtestutil.SetupAtGenesis( depinject.Configs( configurator.NewAppConfig( - configurator.ParamsModule(), configurator.AuthModule(), configurator.StakingModule(), configurator.BankModule(), diff --git a/tests/integration/tx/decode_test.go b/tests/integration/tx/decode_test.go index f307a7bf0cec..f9d352adec83 100644 --- a/tests/integration/tx/decode_test.go +++ b/tests/integration/tx/decode_test.go @@ -34,7 +34,6 @@ import ( feegrantmodule "github.com/cosmos/cosmos-sdk/x/feegrant/module" "github.com/cosmos/cosmos-sdk/x/gov" "github.com/cosmos/cosmos-sdk/x/mint" - "github.com/cosmos/cosmos-sdk/x/params" "github.com/cosmos/cosmos-sdk/x/slashing" "github.com/cosmos/cosmos-sdk/x/staking" "github.com/cosmos/cosmos-sdk/x/upgrade" @@ -45,7 +44,7 @@ func TestDecode(t *testing.T) { encCfg := testutil.MakeTestEncodingConfig( auth.AppModuleBasic{}, authzmodule.AppModuleBasic{}, bank.AppModuleBasic{}, consensus.AppModuleBasic{}, distribution.AppModuleBasic{}, evidence.AppModuleBasic{}, feegrantmodule.AppModuleBasic{}, - gov.AppModuleBasic{}, groupmodule.AppModuleBasic{}, mint.AppModuleBasic{}, params.AppModuleBasic{}, + gov.AppModuleBasic{}, groupmodule.AppModuleBasic{}, mint.AppModuleBasic{}, slashing.AppModuleBasic{}, staking.AppModuleBasic{}, upgrade.AppModuleBasic{}, vesting.AppModuleBasic{}) legacytx.RegressionTestingAminoCodec = encCfg.Amino diff --git a/tests/systemtests/go.sum b/tests/systemtests/go.sum index 1823082f82be..949bbfc495f8 100644 --- a/tests/systemtests/go.sum +++ b/tests/systemtests/go.sum @@ -111,8 +111,6 @@ github.com/cncf/xds/go v0.0.0-20210805033703-aa0b78936158/go.mod h1:eXthEFrGJvWH github.com/cncf/xds/go v0.0.0-20210922020428-25de7278fc84/go.mod h1:eXthEFrGJvWHgFFCl3hGmgk+/aYT6PnTQLykKQRLhEs= github.com/cncf/xds/go v0.0.0-20211001041855-01bcc9b48dfe/go.mod h1:eXthEFrGJvWHgFFCl3hGmgk+/aYT6PnTQLykKQRLhEs= github.com/cncf/xds/go v0.0.0-20211011173535-cb28da3451f1/go.mod h1:eXthEFrGJvWHgFFCl3hGmgk+/aYT6PnTQLykKQRLhEs= -github.com/cockroachdb/apd/v2 v2.0.2 h1:weh8u7Cneje73dDh+2tEVLUvyBc89iwepWCD8b8034E= -github.com/cockroachdb/apd/v2 v2.0.2/go.mod h1:DDxRlzC2lo3/vSlmSoS7JkqbbrARPuFOGr0B9pvN3Gw= github.com/cockroachdb/datadriven v0.0.0-20190809214429-80d97fb3cbaa/go.mod h1:zn76sxSg3SzpJ0PPJaLDCu+Bu0Lg3sKTORVIj19EIF8= github.com/cockroachdb/datadriven v1.0.3-0.20230413201302-be42291fc80f h1:otljaYPt5hWxV3MUfO5dFPFiOXg9CyG5/kCfayTqsJ4= github.com/cockroachdb/datadriven v1.0.3-0.20230413201302-be42291fc80f/go.mod h1:a9RdTaap04u637JoCzcUoIcDmvwSUtcUFtT/C3kJlTU= diff --git a/testutil/configurator/configurator.go b/testutil/configurator/configurator.go index 1ad736940a8d..89f1fa012abb 100644 --- a/testutil/configurator/configurator.go +++ b/testutil/configurator/configurator.go @@ -15,7 +15,6 @@ import ( govmodulev1 "cosmossdk.io/api/cosmos/gov/module/v1" mintmodulev1 "cosmossdk.io/api/cosmos/mint/module/v1" nftmodulev1 "cosmossdk.io/api/cosmos/nft/module/v1" - paramsmodulev1 "cosmossdk.io/api/cosmos/params/module/v1" protocolpoolmodulev1 "cosmossdk.io/api/cosmos/protocolpool/module/v1" slashingmodulev1 "cosmossdk.io/api/cosmos/slashing/module/v1" stakingmodulev1 "cosmossdk.io/api/cosmos/staking/module/v1" @@ -58,7 +57,6 @@ func defaultConfig() *Config { "feegrant", "nft", "group", - "params", "consensus", "vesting", "circuit", @@ -78,7 +76,6 @@ func defaultConfig() *Config { "feegrant", "nft", "group", - "params", "consensus", "upgrade", "vesting", @@ -99,7 +96,6 @@ func defaultConfig() *Config { "feegrant", "nft", "group", - "params", "consensus", "upgrade", "vesting", @@ -167,15 +163,6 @@ func AuthModule() ModuleOption { } } -func ParamsModule() ModuleOption { - return func(config *Config) { - config.ModuleConfigs["params"] = &appv1alpha1.ModuleConfig{ - Name: "params", - Config: appconfig.WrapAny(¶msmodulev1.Module{}), - } - } -} - func TxModule() ModuleOption { return func(config *Config) { config.ModuleConfigs["tx"] = &appv1alpha1.ModuleConfig{ diff --git a/testutil/integration/example_test.go b/testutil/integration/example_test.go index b395324c1917..930c9f7a909f 100644 --- a/testutil/integration/example_test.go +++ b/testutil/integration/example_test.go @@ -51,12 +51,12 @@ func Example() { ) // subspace is nil because we don't test params (which is legacy anyway) - authModule := auth.NewAppModule(encodingCfg.Codec, accountKeeper, authsims.RandomGenesisAccounts, nil) + authModule := auth.NewAppModule(encodingCfg.Codec, accountKeeper, authsims.RandomGenesisAccounts) // here bankkeeper and staking keeper is nil because we are not testing them // subspace is nil because we don't test params (which is legacy anyway) mintKeeper := mintkeeper.NewKeeper(encodingCfg.Codec, runtime.NewKVStoreService(keys[minttypes.StoreKey]), nil, accountKeeper, nil, authtypes.FeeCollectorName, authority) - mintModule := mint.NewAppModule(encodingCfg.Codec, mintKeeper, accountKeeper, nil, nil) + mintModule := mint.NewAppModule(encodingCfg.Codec, mintKeeper, accountKeeper, nil) // create the application and register all the modules from the previous step integrationApp := integration.NewIntegrationApp( @@ -140,7 +140,7 @@ func Example_oneModule() { ) // subspace is nil because we don't test params (which is legacy anyway) - authModule := auth.NewAppModule(encodingCfg.Codec, accountKeeper, authsims.RandomGenesisAccounts, nil) + authModule := auth.NewAppModule(encodingCfg.Codec, accountKeeper, authsims.RandomGenesisAccounts) // create the application and register all the modules from the previous step integrationApp := integration.NewIntegrationApp( diff --git a/testutil/network/network.go b/testutil/network/network.go index 138b94bf77de..2036f6532179 100644 --- a/testutil/network/network.go +++ b/testutil/network/network.go @@ -57,7 +57,6 @@ import ( banktypes "github.com/cosmos/cosmos-sdk/x/bank/types" _ "github.com/cosmos/cosmos-sdk/x/consensus" // import consensus as a blank "github.com/cosmos/cosmos-sdk/x/genutil" - _ "github.com/cosmos/cosmos-sdk/x/params" // import params as a blank _ "github.com/cosmos/cosmos-sdk/x/staking" // import staking as a blank stakingtypes "github.com/cosmos/cosmos-sdk/x/staking/types" ) @@ -165,7 +164,6 @@ func DefaultConfig(factory TestFixtureFactory) Config { func MinimumAppConfig() depinject.Config { return configurator.NewAppConfig( configurator.AuthModule(), - configurator.ParamsModule(), configurator.BankModule(), configurator.GenutilModule(), configurator.StakingModule(), diff --git a/types/query/pagination_test.go b/types/query/pagination_test.go index 1e06f1629bf3..44479fc02fba 100644 --- a/types/query/pagination_test.go +++ b/types/query/pagination_test.go @@ -30,7 +30,6 @@ import ( "github.com/cosmos/cosmos-sdk/x/bank/testutil" "github.com/cosmos/cosmos-sdk/x/bank/types" _ "github.com/cosmos/cosmos-sdk/x/consensus" - _ "github.com/cosmos/cosmos-sdk/x/params" ) const ( @@ -71,7 +70,6 @@ func (s *paginationTestSuite) SetupTest() { configurator.NewAppConfig( configurator.AuthModule(), configurator.BankModule(), - configurator.ParamsModule(), configurator.ConsensusModule(), configurator.OmitInitGenesis(), ), diff --git a/x/auth/exported/exported.go b/x/auth/exported/exported.go deleted file mode 100644 index 000114e6194d..000000000000 --- a/x/auth/exported/exported.go +++ /dev/null @@ -1,18 +0,0 @@ -package exported - -import ( - sdk "github.com/cosmos/cosmos-sdk/types" - paramtypes "github.com/cosmos/cosmos-sdk/x/params/types" -) - -type ( - ParamSet = paramtypes.ParamSet - - // Subspace defines an interface that implements the legacy x/params Subspace - // type. - // - // NOTE: This is used solely for migration of x/params managed parameters. - Subspace interface { - GetParamSet(ctx sdk.Context, ps ParamSet) - } -) diff --git a/x/auth/keeper/migrations.go b/x/auth/keeper/migrations.go index 652ea3fa0b1f..227709bd8c72 100644 --- a/x/auth/keeper/migrations.go +++ b/x/auth/keeper/migrations.go @@ -2,89 +2,15 @@ package keeper import ( "github.com/cosmos/gogoproto/grpc" - - sdk "github.com/cosmos/cosmos-sdk/types" - "github.com/cosmos/cosmos-sdk/x/auth/exported" - v2 "github.com/cosmos/cosmos-sdk/x/auth/migrations/v2" - v3 "github.com/cosmos/cosmos-sdk/x/auth/migrations/v3" - v4 "github.com/cosmos/cosmos-sdk/x/auth/migrations/v4" - v5 "github.com/cosmos/cosmos-sdk/x/auth/migrations/v5" - "github.com/cosmos/cosmos-sdk/x/auth/types" ) // Migrator is a struct for handling in-place store migrations. type Migrator struct { - keeper AccountKeeper - queryServer grpc.Server - legacySubspace exported.Subspace + keeper AccountKeeper + queryServer grpc.Server } // NewMigrator returns a new Migrator. -func NewMigrator(keeper AccountKeeper, queryServer grpc.Server, ss exported.Subspace) Migrator { - return Migrator{keeper: keeper, queryServer: queryServer, legacySubspace: ss} -} - -// Migrate1to2 migrates from version 1 to 2. -func (m Migrator) Migrate1to2(ctx sdk.Context) error { - var iterErr error - - m.keeper.IterateAccounts(ctx, func(account sdk.AccountI) (stop bool) { - wb, err := v2.MigrateAccount(ctx, account, m.queryServer) - if err != nil { - iterErr = err - return true - } - - if wb == nil { - return false - } - - m.keeper.SetAccount(ctx, wb) - return false - }) - - return iterErr -} - -// Migrate2to3 migrates from consensus version 2 to version 3. Specifically, for each account -// we index the account's ID to their address. -func (m Migrator) Migrate2to3(ctx sdk.Context) error { - return v3.MigrateStore(ctx, m.keeper.storeService, m.keeper.cdc) -} - -// Migrate3to4 migrates the x/auth module state from the consensus version 3 to -// version 4. Specifically, it takes the parameters that are currently stored -// and managed by the x/params modules and stores them directly into the x/auth -// module state. -func (m Migrator) Migrate3to4(ctx sdk.Context) error { - return v4.Migrate(ctx, m.keeper.storeService, m.legacySubspace, m.keeper.cdc) -} - -// Migrate4To5 migrates the x/auth module state from the consensus version 4 to 5. -// It migrates the GlobalAccountNumber from being a protobuf defined value to a -// big-endian encoded uint64, it also migrates it to use a more canonical prefix. -func (m Migrator) Migrate4To5(ctx sdk.Context) error { - return v5.Migrate(ctx, m.keeper.storeService, m.keeper.AccountNumber) -} - -// V45SetAccount implements V45_SetAccount -// set the account without map to accAddr to accNumber. -// -// NOTE: This is used for testing purposes only. -func (m Migrator) V45SetAccount(ctx sdk.Context, acc sdk.AccountI) error { - addr := acc.GetAddress() - store := m.keeper.storeService.OpenKVStore(ctx) - - bz, err := m.keeper.Accounts.ValueCodec().Encode(acc) - if err != nil { - return err - } - - return store.Set(addressStoreKey(addr), bz) -} - -// addressStoreKey turn an address to key used to get it from the account store -// NOTE(tip): exists for legacy compatibility -func addressStoreKey(addr sdk.AccAddress) []byte { - return append(types.AddressStoreKeyPrefix, addr.Bytes()...) +func NewMigrator(keeper AccountKeeper, queryServer grpc.Server) Migrator { + return Migrator{keeper: keeper, queryServer: queryServer} } diff --git a/x/auth/migrations/v1/types.go b/x/auth/migrations/v1/types.go deleted file mode 100644 index 6aa7e996670b..000000000000 --- a/x/auth/migrations/v1/types.go +++ /dev/null @@ -1,6 +0,0 @@ -package v1 - -const ( - ModuleName = "auth" - AddrLen = 20 -) diff --git a/x/auth/migrations/v2/store.go b/x/auth/migrations/v2/store.go deleted file mode 100644 index 3e1826bb2ba4..000000000000 --- a/x/auth/migrations/v2/store.go +++ /dev/null @@ -1,294 +0,0 @@ -// Package v2 creates in-place store migrations for fixing tracking -// delegations with vesting accounts. -// ref: https://github.com/cosmos/cosmos-sdk/issues/8601 -// ref: https://github.com/cosmos/cosmos-sdk/issues/8812 -// -// The migration script modifies x/auth state, hence lives in the `x/auth/legacy` -// folder. However, it needs access to staking and bank state. To avoid -// cyclic dependencies, we cannot import those 2 keepers in this file. To solve -// this, we use the baseapp router to do inter-module querying, by importing -// the `baseapp.QueryRouter grpc.Server`. This is really hacky. -// -// PLEASE DO NOT REPLICATE THIS PATTERN IN YOUR OWN APP. -// -// Proposals to refactor this file have been made in: -// https://github.com/cosmos/cosmos-sdk/issues/9070 -// The preferred solution is to use inter-module communication (ADR-033), and -// this file will be refactored to use ADR-033 once it's ready. -package v2 - -import ( - "errors" - "fmt" - - abci "github.com/cometbft/cometbft/abci/types" - "github.com/cosmos/gogoproto/grpc" - "github.com/cosmos/gogoproto/proto" - "google.golang.org/grpc/codes" - "google.golang.org/grpc/status" - - "github.com/cosmos/cosmos-sdk/baseapp" - sdk "github.com/cosmos/cosmos-sdk/types" - sdkerrors "github.com/cosmos/cosmos-sdk/types/errors" - "github.com/cosmos/cosmos-sdk/x/auth/vesting/exported" - vestingtypes "github.com/cosmos/cosmos-sdk/x/auth/vesting/types" - banktypes "github.com/cosmos/cosmos-sdk/x/bank/types" - stakingtypes "github.com/cosmos/cosmos-sdk/x/staking/types" -) - -const ( - delegatorDelegationPath = "/cosmos.staking.v1beta1.Query/DelegatorDelegations" - stakingParamsPath = "/cosmos.staking.v1beta1.Query/Params" - delegatorUnbondingDelegationsPath = "/cosmos.staking.v1beta1.Query/DelegatorUnbondingDelegations" - balancesPath = "/cosmos.bank.v1beta1.Query/AllBalances" -) - -// We use the baseapp.QueryRouter here to do inter-module state querying. -// PLEASE DO NOT REPLICATE THIS PATTERN IN YOUR OWN APP. -func migrateVestingAccounts(ctx sdk.Context, account sdk.AccountI, queryServer grpc.Server) (sdk.AccountI, error) { - bondDenom, err := getBondDenom(ctx, queryServer) - if err != nil { - return nil, err - } - - asVesting, ok := account.(exported.VestingAccount) - if !ok { - return nil, nil - } - - addr := account.GetAddress().String() - balance, err := getBalance( - ctx, - addr, - queryServer, - ) - if err != nil { - return nil, err - } - - delegations, err := getDelegatorDelegationsSum( - ctx, - addr, - queryServer, - ) - if err != nil { - return nil, err - } - - unbondingDelegations, err := getDelegatorUnbondingDelegationsSum( - ctx, - addr, - bondDenom, - queryServer, - ) - if err != nil { - return nil, err - } - - delegations = delegations.Add(unbondingDelegations...) - - asVesting, ok = resetVestingDelegatedBalances(asVesting) - if !ok { - return nil, nil - } - - // balance before any delegation includes balance of delegation - for _, coin := range delegations { - balance = balance.Add(coin) - } - - asVesting.TrackDelegation(ctx.BlockTime(), balance, delegations) - - return asVesting.(sdk.AccountI), nil -} - -func resetVestingDelegatedBalances(evacct exported.VestingAccount) (exported.VestingAccount, bool) { - // reset `DelegatedVesting` and `DelegatedFree` to zero - df := sdk.NewCoins() - dv := sdk.NewCoins() - - switch vacct := evacct.(type) { - case *vestingtypes.ContinuousVestingAccount: - vacct.DelegatedVesting = dv - vacct.DelegatedFree = df - return vacct, true - case *vestingtypes.DelayedVestingAccount: - vacct.DelegatedVesting = dv - vacct.DelegatedFree = df - return vacct, true - case *vestingtypes.PeriodicVestingAccount: - vacct.DelegatedVesting = dv - vacct.DelegatedFree = df - return vacct, true - default: - return nil, false - } -} - -// We use the baseapp.QueryRouter here to do inter-module state querying. -// PLEASE DO NOT REPLICATE THIS PATTERN IN YOUR OWN APP. -func getDelegatorDelegationsSum(ctx sdk.Context, address string, queryServer grpc.Server) (sdk.Coins, error) { - querier, ok := queryServer.(*baseapp.GRPCQueryRouter) - if !ok { - return nil, fmt.Errorf("unexpected type: %T wanted *baseapp.GRPCQueryRouter", queryServer) - } - - queryFn := querier.Route(delegatorDelegationPath) - - q := &stakingtypes.QueryDelegatorDelegationsRequest{ - DelegatorAddr: address, - } - - b, err := proto.Marshal(q) - if err != nil { - return nil, fmt.Errorf("cannot marshal staking type query request, %w", err) - } - req := abci.RequestQuery{ - Data: b, - Path: delegatorDelegationPath, - } - resp, err := queryFn(ctx, &req) - if err != nil { - e, ok := status.FromError(err) - if ok && e.Code() == codes.NotFound { - return nil, nil - } - return nil, fmt.Errorf("staking query error, %w", err) - } - - balance := new(stakingtypes.QueryDelegatorDelegationsResponse) - if err := proto.Unmarshal(resp.Value, balance); err != nil { - return nil, fmt.Errorf("unable to unmarshal delegator query delegations: %w", err) - } - - res := sdk.NewCoins() - for _, i := range balance.DelegationResponses { - res = res.Add(i.Balance) - } - - return res, nil -} - -// We use the baseapp.QueryRouter here to do inter-module state querying. -// PLEASE DO NOT REPLICATE THIS PATTERN IN YOUR OWN APP. -func getDelegatorUnbondingDelegationsSum(ctx sdk.Context, address, bondDenom string, queryServer grpc.Server) (sdk.Coins, error) { - querier, ok := queryServer.(*baseapp.GRPCQueryRouter) - if !ok { - return nil, fmt.Errorf("unexpected type: %T wanted *baseapp.GRPCQueryRouter", queryServer) - } - - queryFn := querier.Route(delegatorUnbondingDelegationsPath) - - q := &stakingtypes.QueryDelegatorUnbondingDelegationsRequest{ - DelegatorAddr: address, - } - - b, err := proto.Marshal(q) - if err != nil { - return nil, fmt.Errorf("cannot marshal staking type query request, %w", err) - } - req := abci.RequestQuery{ - Data: b, - Path: delegatorUnbondingDelegationsPath, - } - resp, err := queryFn(ctx, &req) - if err != nil && !errors.Is(err, sdkerrors.ErrNotFound) { - e, ok := status.FromError(err) - if ok && e.Code() == codes.NotFound { - return nil, nil - } - return nil, fmt.Errorf("staking query error, %w", err) - } - - balance := new(stakingtypes.QueryDelegatorUnbondingDelegationsResponse) - if err := proto.Unmarshal(resp.Value, balance); err != nil { - return nil, fmt.Errorf("unable to unmarshal delegator query delegations: %w", err) - } - - res := sdk.NewCoins() - for _, i := range balance.UnbondingResponses { - for _, r := range i.Entries { - res = res.Add(sdk.NewCoin(bondDenom, r.Balance)) - } - } - - return res, nil -} - -// We use the baseapp.QueryRouter here to do inter-module state querying. -// PLEASE DO NOT REPLICATE THIS PATTERN IN YOUR OWN APP. -func getBalance(ctx sdk.Context, address string, queryServer grpc.Server) (sdk.Coins, error) { - querier, ok := queryServer.(*baseapp.GRPCQueryRouter) - if !ok { - return nil, fmt.Errorf("unexpected type: %T wanted *baseapp.GRPCQueryRouter", queryServer) - } - - queryFn := querier.Route(balancesPath) - - q := &banktypes.QueryAllBalancesRequest{ - Address: address, - Pagination: nil, - } - b, err := proto.Marshal(q) - if err != nil { - return nil, fmt.Errorf("cannot marshal bank type query request, %w", err) - } - - req := abci.RequestQuery{ - Data: b, - Path: balancesPath, - } - resp, err := queryFn(ctx, &req) - if err != nil { - return nil, fmt.Errorf("bank query error, %w", err) - } - balance := new(banktypes.QueryAllBalancesResponse) - if err := proto.Unmarshal(resp.Value, balance); err != nil { - return nil, fmt.Errorf("unable to unmarshal bank balance response: %w", err) - } - return balance.Balances, nil -} - -// We use the baseapp.QueryRouter here to do inter-module state querying. -// PLEASE DO NOT REPLICATE THIS PATTERN IN YOUR OWN APP. -func getBondDenom(ctx sdk.Context, queryServer grpc.Server) (string, error) { - querier, ok := queryServer.(*baseapp.GRPCQueryRouter) - if !ok { - return "", fmt.Errorf("unexpected type: %T wanted *baseapp.GRPCQueryRouter", queryServer) - } - - queryFn := querier.Route(stakingParamsPath) - - q := &stakingtypes.QueryParamsRequest{} - - b, err := proto.Marshal(q) - if err != nil { - return "", fmt.Errorf("cannot marshal staking params query request, %w", err) - } - req := abci.RequestQuery{ - Data: b, - Path: stakingParamsPath, - } - - resp, err := queryFn(ctx, &req) - if err != nil { - return "", fmt.Errorf("staking query error, %w", err) - } - - params := new(stakingtypes.QueryParamsResponse) - if err := proto.Unmarshal(resp.Value, params); err != nil { - return "", fmt.Errorf("unable to unmarshal delegator query delegations: %w", err) - } - - return params.Params.BondDenom, nil -} - -// MigrateAccount migrates vesting account to make the DelegatedVesting and DelegatedFree fields correctly -// track delegations. -// References: https://github.com/cosmos/cosmos-sdk/issues/8601, https://github.com/cosmos/cosmos-sdk/issues/8812 -// -// We use the baseapp.QueryRouter here to do inter-module state querying. -// PLEASE DO NOT REPLICATE THIS PATTERN IN YOUR OWN APP. -func MigrateAccount(ctx sdk.Context, account sdk.AccountI, queryServer grpc.Server) (sdk.AccountI, error) { - return migrateVestingAccounts(ctx, account, queryServer) -} diff --git a/x/auth/migrations/v2/store_test.go b/x/auth/migrations/v2/store_test.go deleted file mode 100644 index e1b3ae8b3962..000000000000 --- a/x/auth/migrations/v2/store_test.go +++ /dev/null @@ -1,792 +0,0 @@ -package v2_test - -import ( - "fmt" - "sync/atomic" - "testing" - "time" - - cmtproto "github.com/cometbft/cometbft/proto/tendermint/types" - "github.com/stretchr/testify/require" - - "cosmossdk.io/depinject" - "cosmossdk.io/log" - sdkmath "cosmossdk.io/math" - storetypes "cosmossdk.io/store/types" - - "github.com/cosmos/cosmos-sdk/runtime" - "github.com/cosmos/cosmos-sdk/testutil" - simtestutil "github.com/cosmos/cosmos-sdk/testutil/sims" - sdk "github.com/cosmos/cosmos-sdk/types" - moduletestutil "github.com/cosmos/cosmos-sdk/types/module/testutil" - "github.com/cosmos/cosmos-sdk/x/auth" - authexported "github.com/cosmos/cosmos-sdk/x/auth/exported" - "github.com/cosmos/cosmos-sdk/x/auth/keeper" - v1 "github.com/cosmos/cosmos-sdk/x/auth/migrations/v1" - v4 "github.com/cosmos/cosmos-sdk/x/auth/migrations/v4" - authtestutil "github.com/cosmos/cosmos-sdk/x/auth/testutil" - authtypes "github.com/cosmos/cosmos-sdk/x/auth/types" - "github.com/cosmos/cosmos-sdk/x/auth/vesting/exported" - "github.com/cosmos/cosmos-sdk/x/auth/vesting/types" - bankkeeper "github.com/cosmos/cosmos-sdk/x/bank/keeper" - stakingkeeper "github.com/cosmos/cosmos-sdk/x/staking/keeper" - stakingtypes "github.com/cosmos/cosmos-sdk/x/staking/types" -) - -type mockSubspace struct { - ps authtypes.Params -} - -func newMockSubspace(ps authtypes.Params) mockSubspace { - return mockSubspace{ps: ps} -} - -func (ms mockSubspace) GetParamSet(ctx sdk.Context, ps authexported.ParamSet) { - *ps.(*authtypes.Params) = ms.ps -} - -func TestMigrateVestingAccounts(t *testing.T) { - encCfg := moduletestutil.MakeTestEncodingConfig(auth.AppModuleBasic{}) - cdc := encCfg.Codec - - storeKey := storetypes.NewKVStoreKey(v1.ModuleName) - tKey := storetypes.NewTransientStoreKey("transient_test") - ctx := testutil.DefaultContext(storeKey, tKey) - storeService := runtime.NewKVStoreService(storeKey) - - var ( - accountKeeper keeper.AccountKeeper - bankKeeper bankkeeper.Keeper - stakingKeeper *stakingkeeper.Keeper - ) - app, err := simtestutil.Setup( - depinject.Configs( - authtestutil.AppConfig, - depinject.Supply(log.NewNopLogger()), - ), - &accountKeeper, - &bankKeeper, - &stakingKeeper, - ) - require.NoError(t, err) - - legacySubspace := newMockSubspace(authtypes.DefaultParams()) - require.NoError(t, v4.Migrate(ctx, storeService, legacySubspace, cdc)) - - ctx = app.NewContextLegacy(false, cmtproto.Header{Time: time.Now()}) - require.NoError(t, stakingKeeper.SetParams(ctx, stakingtypes.DefaultParams())) - lastAccNum := uint64(1000) - createBaseAccount := func(addr sdk.AccAddress) *authtypes.BaseAccount { - baseAccount := authtypes.NewBaseAccountWithAddress(addr) - require.NoError(t, baseAccount.SetAccountNumber(atomic.AddUint64(&lastAccNum, 1))) - return baseAccount - } - - testCases := []struct { - name string - prepareFunc func(ctx sdk.Context, validator stakingtypes.Validator, delegatorAddr sdk.AccAddress) - garbageFunc func(ctx sdk.Context, vesting exported.VestingAccount, accounKeeper keeper.AccountKeeper) error - tokenAmount int64 - expVested int64 - expFree int64 - blockTime int64 - }{ - { - "delayed vesting has vested, multiple delegations less than the total account balance", - func(ctx sdk.Context, validator stakingtypes.Validator, delegatorAddr sdk.AccAddress) { - baseAccount := createBaseAccount(delegatorAddr) - bondDenom, err := stakingKeeper.BondDenom(ctx) - require.NoError(t, err) - vestedCoins := sdk.NewCoins(sdk.NewCoin(bondDenom, sdkmath.NewInt(200))) - delayedAccount, err := types.NewDelayedVestingAccount(baseAccount, vestedCoins, ctx.BlockTime().Unix()) - require.NoError(t, err) - - ctx = ctx.WithBlockTime(ctx.BlockTime().AddDate(1, 0, 0)) - - err = accountKeeper.Params.Set(ctx, authtypes.DefaultParams()) - require.NoError(t, err) - - accountKeeper.SetAccount(ctx, delayedAccount) - - _, err = stakingKeeper.Delegate(ctx, delegatorAddr, sdkmath.NewInt(100), stakingtypes.Unbonded, validator, true) - require.NoError(t, err) - _, err = stakingKeeper.Delegate(ctx, delegatorAddr, sdkmath.NewInt(100), stakingtypes.Unbonded, validator, true) - require.NoError(t, err) - _, err = stakingKeeper.Delegate(ctx, delegatorAddr, sdkmath.NewInt(100), stakingtypes.Unbonded, validator, true) - require.NoError(t, err) - }, - clearTrackingFields, - 300, - 0, - 300, - 0, - }, - { - "delayed vesting has vested, single delegations which exceed the vested amount", - func(ctx sdk.Context, validator stakingtypes.Validator, delegatorAddr sdk.AccAddress) { - bondDenom, err := stakingKeeper.BondDenom(ctx) - require.NoError(t, err) - baseAccount := createBaseAccount(delegatorAddr) - vestedCoins := sdk.NewCoins(sdk.NewCoin(bondDenom, sdkmath.NewInt(200))) - delayedAccount, err := types.NewDelayedVestingAccount(baseAccount, vestedCoins, ctx.BlockTime().Unix()) - require.NoError(t, err) - - ctx = ctx.WithBlockTime(ctx.BlockTime().AddDate(1, 0, 0)) - - accountKeeper.SetAccount(ctx, delayedAccount) - - _, err = stakingKeeper.Delegate(ctx, delegatorAddr, sdkmath.NewInt(300), stakingtypes.Unbonded, validator, true) - require.NoError(t, err) - }, - clearTrackingFields, - 300, - 0, - 300, - 0, - }, - { - "delayed vesting has vested, multiple delegations which exceed the vested amount", - func(ctx sdk.Context, validator stakingtypes.Validator, delegatorAddr sdk.AccAddress) { - baseAccount := createBaseAccount(delegatorAddr) - bondDenom, err := stakingKeeper.BondDenom(ctx) - require.NoError(t, err) - vestedCoins := sdk.NewCoins(sdk.NewCoin(bondDenom, sdkmath.NewInt(200))) - delayedAccount, err := types.NewDelayedVestingAccount(baseAccount, vestedCoins, ctx.BlockTime().Unix()) - require.NoError(t, err) - - ctx = ctx.WithBlockTime(ctx.BlockTime().AddDate(1, 0, 0)) - - accountKeeper.SetAccount(ctx, delayedAccount) - - _, err = stakingKeeper.Delegate(ctx, delegatorAddr, sdkmath.NewInt(100), stakingtypes.Unbonded, validator, true) - require.NoError(t, err) - _, err = stakingKeeper.Delegate(ctx, delegatorAddr, sdkmath.NewInt(100), stakingtypes.Unbonded, validator, true) - require.NoError(t, err) - _, err = stakingKeeper.Delegate(ctx, delegatorAddr, sdkmath.NewInt(100), stakingtypes.Unbonded, validator, true) - require.NoError(t, err) - }, - clearTrackingFields, - 300, - 0, - 300, - 0, - }, - { - "delayed vesting has not vested, single delegations which exceed the vested amount", - func(ctx sdk.Context, validator stakingtypes.Validator, delegatorAddr sdk.AccAddress) { - baseAccount := createBaseAccount(delegatorAddr) - bondDenom, err := stakingKeeper.BondDenom(ctx) - require.NoError(t, err) - vestedCoins := sdk.NewCoins(sdk.NewCoin(bondDenom, sdkmath.NewInt(200))) - delayedAccount, err := types.NewDelayedVestingAccount(baseAccount, vestedCoins, ctx.BlockTime().AddDate(1, 0, 0).Unix()) - require.NoError(t, err) - - accountKeeper.SetAccount(ctx, delayedAccount) - - _, err = stakingKeeper.Delegate(ctx, delegatorAddr, sdkmath.NewInt(300), stakingtypes.Unbonded, validator, true) - require.NoError(t, err) - }, - clearTrackingFields, - 300, - 200, - 100, - 0, - }, - { - "delayed vesting has not vested, multiple delegations which exceed the vested amount", - func(ctx sdk.Context, validator stakingtypes.Validator, delegatorAddr sdk.AccAddress) { - baseAccount := createBaseAccount(delegatorAddr) - bondDenom, err := stakingKeeper.BondDenom(ctx) - require.NoError(t, err) - vestedCoins := sdk.NewCoins(sdk.NewCoin(bondDenom, sdkmath.NewInt(200))) - delayedAccount, err := types.NewDelayedVestingAccount(baseAccount, vestedCoins, ctx.BlockTime().AddDate(1, 0, 0).Unix()) - require.NoError(t, err) - - accountKeeper.SetAccount(ctx, delayedAccount) - - _, err = stakingKeeper.Delegate(ctx, delegatorAddr, sdkmath.NewInt(100), stakingtypes.Unbonded, validator, true) - require.NoError(t, err) - _, err = stakingKeeper.Delegate(ctx, delegatorAddr, sdkmath.NewInt(100), stakingtypes.Unbonded, validator, true) - require.NoError(t, err) - _, err = stakingKeeper.Delegate(ctx, delegatorAddr, sdkmath.NewInt(100), stakingtypes.Unbonded, validator, true) - require.NoError(t, err) - }, - clearTrackingFields, - 300, - 200, - 100, - 0, - }, - { - "not end time", - func(ctx sdk.Context, validator stakingtypes.Validator, delegatorAddr sdk.AccAddress) { - baseAccount := createBaseAccount(delegatorAddr) - bondDenom, err := stakingKeeper.BondDenom(ctx) - require.NoError(t, err) - vestedCoins := sdk.NewCoins(sdk.NewCoin(bondDenom, sdkmath.NewInt(300))) - delayedAccount, err := types.NewDelayedVestingAccount(baseAccount, vestedCoins, ctx.BlockTime().AddDate(1, 0, 0).Unix()) - require.NoError(t, err) - - accountKeeper.SetAccount(ctx, delayedAccount) - - _, err = stakingKeeper.Delegate(ctx, delegatorAddr, sdkmath.NewInt(100), stakingtypes.Unbonded, validator, true) - require.NoError(t, err) - _, err = stakingKeeper.Delegate(ctx, delegatorAddr, sdkmath.NewInt(100), stakingtypes.Unbonded, validator, true) - require.NoError(t, err) - _, err = stakingKeeper.Delegate(ctx, delegatorAddr, sdkmath.NewInt(100), stakingtypes.Unbonded, validator, true) - require.NoError(t, err) - }, - clearTrackingFields, - 300, - 300, - 0, - 0, - }, - { - "delayed vesting has not vested, single delegation greater than the total account balance", - func(ctx sdk.Context, validator stakingtypes.Validator, delegatorAddr sdk.AccAddress) { - baseAccount := createBaseAccount(delegatorAddr) - bondDenom, err := stakingKeeper.BondDenom(ctx) - require.NoError(t, err) - vestedCoins := sdk.NewCoins(sdk.NewCoin(bondDenom, sdkmath.NewInt(300))) - delayedAccount, err := types.NewDelayedVestingAccount(baseAccount, vestedCoins, ctx.BlockTime().AddDate(1, 0, 0).Unix()) - require.NoError(t, err) - - accountKeeper.SetAccount(ctx, delayedAccount) - - _, err = stakingKeeper.Delegate(ctx, delegatorAddr, sdkmath.NewInt(300), stakingtypes.Unbonded, validator, true) - require.NoError(t, err) - }, - clearTrackingFields, - 300, - 300, - 0, - 0, - }, - { - "delayed vesting has vested, single delegation greater than the total account balance", - func(ctx sdk.Context, validator stakingtypes.Validator, delegatorAddr sdk.AccAddress) { - baseAccount := createBaseAccount(delegatorAddr) - bondDenom, err := stakingKeeper.BondDenom(ctx) - require.NoError(t, err) - vestedCoins := sdk.NewCoins(sdk.NewCoin(bondDenom, sdkmath.NewInt(300))) - delayedAccount, err := types.NewDelayedVestingAccount(baseAccount, vestedCoins, ctx.BlockTime().Unix()) - require.NoError(t, err) - - ctx = ctx.WithBlockTime(ctx.BlockTime().AddDate(1, 0, 0)) - - accountKeeper.SetAccount(ctx, delayedAccount) - - _, err = stakingKeeper.Delegate(ctx, delegatorAddr, sdkmath.NewInt(300), stakingtypes.Unbonded, validator, true) - require.NoError(t, err) - }, - clearTrackingFields, - 300, - 0, - 300, - 0, - }, - { - "continuous vesting, start time after blocktime", - func(ctx sdk.Context, validator stakingtypes.Validator, delegatorAddr sdk.AccAddress) { - startTime := ctx.BlockTime().AddDate(1, 0, 0).Unix() - endTime := ctx.BlockTime().AddDate(2, 0, 0).Unix() - baseAccount := createBaseAccount(delegatorAddr) - bondDenom, err := stakingKeeper.BondDenom(ctx) - require.NoError(t, err) - vestedCoins := sdk.NewCoins(sdk.NewCoin(bondDenom, sdkmath.NewInt(300))) - delayedAccount, err := types.NewContinuousVestingAccount(baseAccount, vestedCoins, startTime, endTime) - require.NoError(t, err) - - ctx = ctx.WithBlockTime(ctx.BlockTime().AddDate(1, 0, 0)) - - accountKeeper.SetAccount(ctx, delayedAccount) - - _, err = stakingKeeper.Delegate(ctx, delegatorAddr, sdkmath.NewInt(300), stakingtypes.Unbonded, validator, true) - require.NoError(t, err) - }, - clearTrackingFields, - 300, - 300, - 0, - 0, - }, - { - "continuous vesting, start time passed but not ended", - func(ctx sdk.Context, validator stakingtypes.Validator, delegatorAddr sdk.AccAddress) { - startTime := ctx.BlockTime().AddDate(-1, 0, 0).Unix() - endTime := ctx.BlockTime().AddDate(2, 0, 0).Unix() - baseAccount := createBaseAccount(delegatorAddr) - bondDenom, err := stakingKeeper.BondDenom(ctx) - require.NoError(t, err) - vestedCoins := sdk.NewCoins(sdk.NewCoin(bondDenom, sdkmath.NewInt(300))) - delayedAccount, err := types.NewContinuousVestingAccount(baseAccount, vestedCoins, startTime, endTime) - require.NoError(t, err) - - ctx = ctx.WithBlockTime(ctx.BlockTime().AddDate(1, 0, 0)) - - accountKeeper.SetAccount(ctx, delayedAccount) - - _, err = stakingKeeper.Delegate(ctx, delegatorAddr, sdkmath.NewInt(300), stakingtypes.Unbonded, validator, true) - require.NoError(t, err) - }, - clearTrackingFields, - 300, - 200, - 100, - 0, - }, - { - "continuous vesting, start time and endtime passed", - func(ctx sdk.Context, validator stakingtypes.Validator, delegatorAddr sdk.AccAddress) { - startTime := ctx.BlockTime().AddDate(-2, 0, 0).Unix() - endTime := ctx.BlockTime().AddDate(-1, 0, 0).Unix() - baseAccount := createBaseAccount(delegatorAddr) - bondDenom, err := stakingKeeper.BondDenom(ctx) - require.NoError(t, err) - vestedCoins := sdk.NewCoins(sdk.NewCoin(bondDenom, sdkmath.NewInt(300))) - delayedAccount, err := types.NewContinuousVestingAccount(baseAccount, vestedCoins, startTime, endTime) - require.NoError(t, err) - - ctx = ctx.WithBlockTime(ctx.BlockTime().AddDate(1, 0, 0)) - - accountKeeper.SetAccount(ctx, delayedAccount) - - _, err = stakingKeeper.Delegate(ctx, delegatorAddr, sdkmath.NewInt(300), stakingtypes.Unbonded, validator, true) - require.NoError(t, err) - }, - clearTrackingFields, - 300, - 0, - 300, - 0, - }, - { - "periodic vesting account, yet to be vested, some rewards delegated", - func(ctx sdk.Context, validator stakingtypes.Validator, delegatorAddr sdk.AccAddress) { - baseAccount := createBaseAccount(delegatorAddr) - bondDenom, err := stakingKeeper.BondDenom(ctx) - require.NoError(t, err) - vestedCoins := sdk.NewCoins(sdk.NewCoin(bondDenom, sdkmath.NewInt(100))) - - start := ctx.BlockTime().Unix() + int64(time.Hour/time.Second) - - periods := []types.Period{ - { - Length: int64((24 * time.Hour) / time.Second), - Amount: vestedCoins, - }, - } - - account, err := types.NewPeriodicVestingAccount(baseAccount, vestedCoins, start, periods) - require.NoError(t, err) - - accountKeeper.SetAccount(ctx, account) - - _, err = stakingKeeper.Delegate(ctx, delegatorAddr, sdkmath.NewInt(150), stakingtypes.Unbonded, validator, true) - require.NoError(t, err) - }, - clearTrackingFields, - 300, - 100, - 50, - 0, - }, - { - "periodic vesting account, nothing has vested yet", - func(ctx sdk.Context, validator stakingtypes.Validator, delegatorAddr sdk.AccAddress) { - /* - Test case: - - periodic vesting account starts at time 1601042400 - - account balance and original vesting: 3666666670000 - - nothing has vested, we put the block time slightly after start time - - expected vested: original vesting amount - - expected free: zero - - we're delegating the full original vesting - */ - startTime := int64(1601042400) - baseAccount := createBaseAccount(delegatorAddr) - bondDenom, err := stakingKeeper.BondDenom(ctx) - require.NoError(t, err) - vestedCoins := sdk.NewCoins(sdk.NewCoin(bondDenom, sdkmath.NewInt(3666666670000))) - periods := []types.Period{ - { - Length: 31536000, - Amount: sdk.NewCoins(sdk.NewCoin(bondDenom, sdkmath.NewInt(1833333335000))), - }, - { - Length: 15638400, - Amount: sdk.NewCoins(sdk.NewCoin(bondDenom, sdkmath.NewInt(916666667500))), - }, - { - Length: 15897600, - Amount: sdk.NewCoins(sdk.NewCoin(bondDenom, sdkmath.NewInt(916666667500))), - }, - } - - delayedAccount, err := types.NewPeriodicVestingAccount(baseAccount, vestedCoins, startTime, periods) - require.NoError(t, err) - - accountKeeper.SetAccount(ctx, delayedAccount) - - // delegation of the original vesting - _, err = stakingKeeper.Delegate(ctx, delegatorAddr, sdkmath.NewInt(3666666670000), stakingtypes.Unbonded, validator, true) - require.NoError(t, err) - }, - clearTrackingFields, - 3666666670000, - 3666666670000, - 0, - 1601042400 + 1, - }, - { - "periodic vesting account, all has vested", - func(ctx sdk.Context, validator stakingtypes.Validator, delegatorAddr sdk.AccAddress) { - /* - Test case: - - periodic vesting account starts at time 1601042400 - - account balance and original vesting: 3666666670000 - - all has vested, so we set the block time at initial time + sum of all periods times + 1 => 1601042400 + 31536000 + 15897600 + 15897600 + 1 - - expected vested: zero - - expected free: original vesting amount - - we're delegating the full original vesting - */ - startTime := int64(1601042400) - baseAccount := createBaseAccount(delegatorAddr) - bondDenom, err := stakingKeeper.BondDenom(ctx) - require.NoError(t, err) - vestedCoins := sdk.NewCoins(sdk.NewCoin(bondDenom, sdkmath.NewInt(3666666670000))) - periods := []types.Period{ - { - Length: 31536000, - Amount: sdk.NewCoins(sdk.NewCoin(bondDenom, sdkmath.NewInt(1833333335000))), - }, - { - Length: 15638400, - Amount: sdk.NewCoins(sdk.NewCoin(bondDenom, sdkmath.NewInt(916666667500))), - }, - { - Length: 15897600, - Amount: sdk.NewCoins(sdk.NewCoin(bondDenom, sdkmath.NewInt(916666667500))), - }, - } - - delayedAccount, err := types.NewPeriodicVestingAccount(baseAccount, vestedCoins, startTime, periods) - require.NoError(t, err) - - ctx = ctx.WithBlockTime(time.Unix(1601042400+31536000+15897600+15897600+1, 0)) - - accountKeeper.SetAccount(ctx, delayedAccount) - - // delegation of the original vesting - _, err = stakingKeeper.Delegate(ctx, delegatorAddr, sdkmath.NewInt(3666666670000), stakingtypes.Unbonded, validator, true) - require.NoError(t, err) - }, - clearTrackingFields, - 3666666670000, - 0, - 3666666670000, - 1601042400 + 31536000 + 15897600 + 15897600 + 1, - }, - { - "periodic vesting account, first period has vested", - func(ctx sdk.Context, validator stakingtypes.Validator, delegatorAddr sdk.AccAddress) { - /* - Test case: - - periodic vesting account starts at time 1601042400 - - account balance and original vesting: 3666666670000 - - first period have vested, so we set the block time at initial time + time of the first periods + 1 => 1601042400 + 31536000 + 1 - - expected vested: original vesting - first period amount - - expected free: first period amount - - we're delegating the full original vesting - */ - startTime := int64(1601042400) - baseAccount := createBaseAccount(delegatorAddr) - bondDenom, err := stakingKeeper.BondDenom(ctx) - require.NoError(t, err) - vestedCoins := sdk.NewCoins(sdk.NewCoin(bondDenom, sdkmath.NewInt(3666666670000))) - periods := []types.Period{ - { - Length: 31536000, - Amount: sdk.NewCoins(sdk.NewCoin(bondDenom, sdkmath.NewInt(1833333335000))), - }, - { - Length: 15638400, - Amount: sdk.NewCoins(sdk.NewCoin(bondDenom, sdkmath.NewInt(916666667500))), - }, - { - Length: 15897600, - Amount: sdk.NewCoins(sdk.NewCoin(bondDenom, sdkmath.NewInt(916666667500))), - }, - } - - delayedAccount, err := types.NewPeriodicVestingAccount(baseAccount, vestedCoins, startTime, periods) - require.NoError(t, err) - - ctx = ctx.WithBlockTime(time.Unix(1601042400+31536000+1, 0)) - - accountKeeper.SetAccount(ctx, delayedAccount) - - // delegation of the original vesting - _, err = stakingKeeper.Delegate(ctx, delegatorAddr, sdkmath.NewInt(3666666670000), stakingtypes.Unbonded, validator, true) - require.NoError(t, err) - }, - clearTrackingFields, - 3666666670000, - 3666666670000 - 1833333335000, - 1833333335000, - 1601042400 + 31536000 + 1, - }, - { - "periodic vesting account, first 2 period has vested", - func(ctx sdk.Context, validator stakingtypes.Validator, delegatorAddr sdk.AccAddress) { - /* - Test case: - - periodic vesting account starts at time 1601042400 - - account balance and original vesting: 3666666670000 - - first 2 periods have vested, so we set the block time at initial time + time of the two periods + 1 => 1601042400 + 31536000 + 15638400 + 1 - - expected vested: original vesting - (sum of the first two periods amounts) - - expected free: sum of the first two periods - - we're delegating the full original vesting - */ - startTime := int64(1601042400) - baseAccount := createBaseAccount(delegatorAddr) - bondDenom, err := stakingKeeper.BondDenom(ctx) - require.NoError(t, err) - vestedCoins := sdk.NewCoins(sdk.NewCoin(bondDenom, sdkmath.NewInt(3666666670000))) - periods := []types.Period{ - { - Length: 31536000, - Amount: sdk.NewCoins(sdk.NewCoin(bondDenom, sdkmath.NewInt(1833333335000))), - }, - { - Length: 15638400, - Amount: sdk.NewCoins(sdk.NewCoin(bondDenom, sdkmath.NewInt(916666667500))), - }, - { - Length: 15897600, - Amount: sdk.NewCoins(sdk.NewCoin(bondDenom, sdkmath.NewInt(916666667500))), - }, - } - - delayedAccount, err := types.NewPeriodicVestingAccount(baseAccount, vestedCoins, startTime, periods) - require.NoError(t, err) - - ctx = ctx.WithBlockTime(time.Unix(1601042400+31536000+15638400+1, 0)) - - accountKeeper.SetAccount(ctx, delayedAccount) - - // delegation of the original vesting - _, err = stakingKeeper.Delegate(ctx, delegatorAddr, sdkmath.NewInt(3666666670000), stakingtypes.Unbonded, validator, true) - require.NoError(t, err) - }, - clearTrackingFields, - 3666666670000, - 3666666670000 - 1833333335000 - 916666667500, - 1833333335000 + 916666667500, - 1601042400 + 31536000 + 15638400 + 1, - }, - { - "vesting account has unbonding delegations in place", - func(ctx sdk.Context, validator stakingtypes.Validator, delegatorAddr sdk.AccAddress) { - baseAccount := createBaseAccount(delegatorAddr) - bondDenom, err := stakingKeeper.BondDenom(ctx) - require.NoError(t, err) - vestedCoins := sdk.NewCoins(sdk.NewCoin(bondDenom, sdkmath.NewInt(300))) - - delayedAccount, err := types.NewDelayedVestingAccount(baseAccount, vestedCoins, ctx.BlockTime().AddDate(10, 0, 0).Unix()) - require.NoError(t, err) - - accountKeeper.SetAccount(ctx, delayedAccount) - - // delegation of the original vesting - _, err = stakingKeeper.Delegate(ctx, delegatorAddr, sdkmath.NewInt(300), stakingtypes.Unbonded, validator, true) - require.NoError(t, err) - - ctx = ctx.WithBlockTime(ctx.BlockTime().AddDate(1, 0, 0)) - - valAddr, err := sdk.ValAddressFromBech32(validator.OperatorAddress) - require.NoError(t, err) - - // un-delegation of the original vesting - _, _, err = stakingKeeper.Undelegate(ctx, delegatorAddr, valAddr, sdkmath.LegacyNewDecFromInt(sdkmath.NewInt(300))) - require.NoError(t, err) - }, - clearTrackingFields, - 450, - 300, - 0, - 0, - }, - { - "vesting account has never delegated anything", - func(ctx sdk.Context, validator stakingtypes.Validator, delegatorAddr sdk.AccAddress) { - baseAccount := createBaseAccount(delegatorAddr) - bondDenom, err := stakingKeeper.BondDenom(ctx) - require.NoError(t, err) - vestedCoins := sdk.NewCoins(sdk.NewCoin(bondDenom, sdkmath.NewInt(300))) - - delayedAccount, err := types.NewDelayedVestingAccount(baseAccount, vestedCoins, ctx.BlockTime().AddDate(10, 0, 0).Unix()) - require.NoError(t, err) - - accountKeeper.SetAccount(ctx, delayedAccount) - }, - clearTrackingFields, - 450, - 0, - 0, - 0, - }, - { - "vesting account has no delegation but dirty DelegatedFree and DelegatedVesting fields", - func(ctx sdk.Context, validator stakingtypes.Validator, delegatorAddr sdk.AccAddress) { - baseAccount := createBaseAccount(delegatorAddr) - bondDenom, err := stakingKeeper.BondDenom(ctx) - require.NoError(t, err) - vestedCoins := sdk.NewCoins(sdk.NewCoin(bondDenom, sdkmath.NewInt(300))) - - delayedAccount, err := types.NewDelayedVestingAccount(baseAccount, vestedCoins, ctx.BlockTime().AddDate(10, 0, 0).Unix()) - require.NoError(t, err) - - accountKeeper.SetAccount(ctx, delayedAccount) - }, - dirtyTrackingFields, - 450, - 0, - 0, - 0, - }, - } - - for _, tc := range testCases { - t.Run(tc.name, func(t *testing.T) { - err := accountKeeper.Params.Set(ctx, authtypes.DefaultParams()) - require.NoError(t, err) - - addrs := simtestutil.AddTestAddrs(bankKeeper, stakingKeeper, ctx, 1, sdkmath.NewInt(tc.tokenAmount)) - delegatorAddr := addrs[0] - - _, valAddr := createValidator(t, ctx, bankKeeper, stakingKeeper, tc.tokenAmount*2) - validator, err := stakingKeeper.GetValidator(ctx, valAddr) - require.NoError(t, err) - - tc.prepareFunc(ctx, validator, delegatorAddr) - - if tc.blockTime != 0 { - ctx = ctx.WithBlockTime(time.Unix(tc.blockTime, 0)) - } - - // We introduce the bug - savedAccount := accountKeeper.GetAccount(ctx, delegatorAddr) - vestingAccount, ok := savedAccount.(exported.VestingAccount) - require.True(t, ok) - require.NoError(t, tc.garbageFunc(ctx, vestingAccount, accountKeeper)) - - m := keeper.NewMigrator(accountKeeper, app.GRPCQueryRouter(), legacySubspace) - require.NoError(t, m.Migrate1to2(ctx)) - - var expVested sdk.Coins - var expFree sdk.Coins - - bondDenom, err := stakingKeeper.BondDenom(ctx) - require.NoError(t, err) - - if tc.expVested != 0 { - expVested = sdk.NewCoins(sdk.NewCoin(bondDenom, sdkmath.NewInt(tc.expVested))) - } - - if tc.expFree != 0 { - expFree = sdk.NewCoins(sdk.NewCoin(bondDenom, sdkmath.NewInt(tc.expFree))) - } - - trackingCorrected( - t, - ctx, - accountKeeper, - savedAccount.GetAddress(), - expVested, - expFree, - ) - }) - } -} - -func trackingCorrected(t *testing.T, ctx sdk.Context, ak keeper.AccountKeeper, addr sdk.AccAddress, expDelVesting, expDelFree sdk.Coins) { - t.Helper() - baseAccount := ak.GetAccount(ctx, addr) - vDA, ok := baseAccount.(exported.VestingAccount) - require.True(t, ok) - - vestedOk := expDelVesting.Equal(vDA.GetDelegatedVesting()) - freeOk := expDelFree.Equal(vDA.GetDelegatedFree()) - require.True(t, vestedOk, vDA.GetDelegatedVesting().String()) - require.True(t, freeOk, vDA.GetDelegatedFree().String()) -} - -func clearTrackingFields(ctx sdk.Context, vesting exported.VestingAccount, accountKeeper keeper.AccountKeeper) error { - switch t := vesting.(type) { - case *types.DelayedVestingAccount: - t.DelegatedFree = nil - t.DelegatedVesting = nil - accountKeeper.SetAccount(ctx, t) - case *types.ContinuousVestingAccount: - t.DelegatedFree = nil - t.DelegatedVesting = nil - accountKeeper.SetAccount(ctx, t) - case *types.PeriodicVestingAccount: - t.DelegatedFree = nil - t.DelegatedVesting = nil - accountKeeper.SetAccount(ctx, t) - default: - return fmt.Errorf("expected vesting account, found %t", t) - } - - return nil -} - -func dirtyTrackingFields(ctx sdk.Context, vesting exported.VestingAccount, accountKeeper keeper.AccountKeeper) error { - dirt := sdk.NewCoins(sdk.NewInt64Coin("stake", 42)) - - switch t := vesting.(type) { - case *types.DelayedVestingAccount: - t.DelegatedFree = dirt - t.DelegatedVesting = dirt - accountKeeper.SetAccount(ctx, t) - case *types.ContinuousVestingAccount: - t.DelegatedFree = dirt - t.DelegatedVesting = dirt - accountKeeper.SetAccount(ctx, t) - case *types.PeriodicVestingAccount: - t.DelegatedFree = dirt - t.DelegatedVesting = dirt - accountKeeper.SetAccount(ctx, t) - default: - return fmt.Errorf("expected vesting account, found %t", t) - } - - return nil -} - -func createValidator(t *testing.T, ctx sdk.Context, bankKeeper bankkeeper.Keeper, stakingKeeper *stakingkeeper.Keeper, powers int64) (sdk.AccAddress, sdk.ValAddress) { - t.Helper() - - valTokens := sdk.TokensFromConsensusPower(powers, sdk.DefaultPowerReduction) - addrs := simtestutil.AddTestAddrsIncremental(bankKeeper, stakingKeeper, ctx, 1, valTokens) - valAddrs := simtestutil.ConvertAddrsToValAddrs(addrs) - pks := simtestutil.CreateTestPubKeys(1) - - val1, err := stakingtypes.NewValidator(valAddrs[0].String(), pks[0], stakingtypes.Description{}) - require.NoError(t, err) - - require.NoError(t, stakingKeeper.SetValidator(ctx, val1)) - require.NoError(t, stakingKeeper.SetValidatorByConsAddr(ctx, val1)) - require.NoError(t, stakingKeeper.SetNewValidatorByPowerIndex(ctx, val1)) - - _, err = stakingKeeper.Delegate(ctx, addrs[0], valTokens, stakingtypes.Unbonded, val1, true) - require.NoError(t, err) - - _, err = stakingKeeper.EndBlocker(ctx) - require.NoError(t, err) - - return addrs[0], valAddrs[0] -} diff --git a/x/auth/migrations/v3/store.go b/x/auth/migrations/v3/store.go deleted file mode 100644 index 3714c72c23c4..000000000000 --- a/x/auth/migrations/v3/store.go +++ /dev/null @@ -1,42 +0,0 @@ -package v3 - -import ( - corestore "cosmossdk.io/core/store" - storetypes "cosmossdk.io/store/types" - - "github.com/cosmos/cosmos-sdk/codec" - sdk "github.com/cosmos/cosmos-sdk/types" - "github.com/cosmos/cosmos-sdk/x/auth/types" -) - -func mapAccountAddressToAccountID(ctx sdk.Context, storeService corestore.KVStoreService, cdc codec.BinaryCodec) error { - store := storeService.OpenKVStore(ctx) - iterator, err := store.Iterator(types.AddressStoreKeyPrefix, storetypes.PrefixEndBytes(types.AddressStoreKeyPrefix)) - if err != nil { - return err - } - - defer iterator.Close() - for ; iterator.Valid(); iterator.Next() { - var acc sdk.AccountI - if err := cdc.UnmarshalInterface(iterator.Value(), &acc); err != nil { - return err - } - _ = store.Set(accountNumberStoreKey(acc.GetAccountNumber()), acc.GetAddress().Bytes()) - } - - return nil -} - -// MigrateStore performs in-place store migrations from v0.45 to v0.46. The -// migration includes: -// - Add an Account number as an index to get the account address -func MigrateStore(ctx sdk.Context, storeService corestore.KVStoreService, cdc codec.BinaryCodec) error { - return mapAccountAddressToAccountID(ctx, storeService, cdc) -} - -// accountNumberStoreKey turn an account number to key used to get the account address from account store -// NOTE(tip): exists for legacy compatibility -func accountNumberStoreKey(accountNumber uint64) []byte { - return append(types.AccountNumberStoreKeyPrefix, sdk.Uint64ToBigEndian(accountNumber)...) -} diff --git a/x/auth/migrations/v3/store_test.go b/x/auth/migrations/v3/store_test.go deleted file mode 100644 index 32bfb82f187a..000000000000 --- a/x/auth/migrations/v3/store_test.go +++ /dev/null @@ -1,111 +0,0 @@ -package v3_test - -import ( - "math/rand" - "testing" - "time" - - cmtproto "github.com/cometbft/cometbft/proto/tendermint/types" - "github.com/stretchr/testify/require" - - "cosmossdk.io/collections" - "cosmossdk.io/depinject" - "cosmossdk.io/log" - storetypes "cosmossdk.io/store/types" - - "github.com/cosmos/cosmos-sdk/crypto/keys/secp256k1" - "github.com/cosmos/cosmos-sdk/runtime" - "github.com/cosmos/cosmos-sdk/testutil" - simtestutil "github.com/cosmos/cosmos-sdk/testutil/sims" - sdk "github.com/cosmos/cosmos-sdk/types" - moduletestutil "github.com/cosmos/cosmos-sdk/types/module/testutil" - "github.com/cosmos/cosmos-sdk/x/auth" - authexported "github.com/cosmos/cosmos-sdk/x/auth/exported" - "github.com/cosmos/cosmos-sdk/x/auth/keeper" - v1 "github.com/cosmos/cosmos-sdk/x/auth/migrations/v1" - v4 "github.com/cosmos/cosmos-sdk/x/auth/migrations/v4" - authtestutil "github.com/cosmos/cosmos-sdk/x/auth/testutil" - authtypes "github.com/cosmos/cosmos-sdk/x/auth/types" -) - -type mockSubspace struct { - ps authtypes.Params -} - -func newMockSubspace(ps authtypes.Params) mockSubspace { - return mockSubspace{ps: ps} -} - -func (ms mockSubspace) GetParamSet(ctx sdk.Context, ps authexported.ParamSet) { - *ps.(*authtypes.Params) = ms.ps -} - -// TestMigrateMapAccAddressToAccNumberKey test cases for state migration of map to accAddr to accNum -func TestMigrateMapAccAddressToAccNumberKey(t *testing.T) { - encCfg := moduletestutil.MakeTestEncodingConfig(auth.AppModuleBasic{}) - cdc := encCfg.Codec - - storeKey := storetypes.NewKVStoreKey(v1.ModuleName) - tKey := storetypes.NewTransientStoreKey("transient_test") - ctx := testutil.DefaultContext(storeKey, tKey) - storeService := runtime.NewKVStoreService(storeKey) - - var accountKeeper keeper.AccountKeeper - - app, err := simtestutil.Setup( - depinject.Configs( - authtestutil.AppConfig, - depinject.Supply(log.NewNopLogger()), - ), - &accountKeeper, - ) - require.NoError(t, err) - - legacySubspace := newMockSubspace(authtypes.DefaultParams()) - require.NoError(t, v4.Migrate(ctx, storeService, legacySubspace, cdc)) - - // new base account - senderPrivKey := secp256k1.GenPrivKey() - randAccNumber := uint64(rand.Intn(100000-10000) + 10000) - acc := authtypes.NewBaseAccount(senderPrivKey.PubKey().Address().Bytes(), senderPrivKey.PubKey(), randAccNumber, 0) - - ctx = app.NewContextLegacy(false, cmtproto.Header{Time: time.Now()}) - - // migrator - m := keeper.NewMigrator(accountKeeper, app.GRPCQueryRouter(), legacySubspace) - // set the account to store with map acc addr to acc number - require.NoError(t, m.V45SetAccount(ctx, acc)) - - testCases := []struct { - name string - doMigration bool - accNum uint64 - }{ - { - name: "without state migration", - doMigration: false, - accNum: acc.AccountNumber, - }, - { - name: "with state migration", - doMigration: true, - accNum: acc.AccountNumber, - }, - } - - for _, tc := range testCases { - t.Run(tc.name, func(t *testing.T) { - if tc.doMigration { - require.NoError(t, m.Migrate2to3(ctx)) - } - - // get the account address by acc id - accAddr, err := accountKeeper.Accounts.Indexes.Number.MatchExact(ctx, tc.accNum) - if tc.doMigration { - require.Equal(t, accAddr.String(), acc.Address) - } else { - require.ErrorIs(t, err, collections.ErrNotFound) - } - }) - } -} diff --git a/x/auth/migrations/v4/migrate.go b/x/auth/migrations/v4/migrate.go deleted file mode 100644 index fdab856ee4e1..000000000000 --- a/x/auth/migrations/v4/migrate.go +++ /dev/null @@ -1,30 +0,0 @@ -package v4 - -import ( - storetypes "cosmossdk.io/core/store" - - "github.com/cosmos/cosmos-sdk/codec" - sdk "github.com/cosmos/cosmos-sdk/types" - "github.com/cosmos/cosmos-sdk/x/auth/exported" - "github.com/cosmos/cosmos-sdk/x/auth/types" -) - -var ParamsKey = []byte{0x00} - -// Migrate migrates the x/auth module state from the consensus version 3 to -// version 4. Specifically, it takes the parameters that are currently stored -// and managed by the x/params modules and stores them directly into the x/auth -// module state. -func Migrate(ctx sdk.Context, storeService storetypes.KVStoreService, legacySubspace exported.Subspace, cdc codec.BinaryCodec) error { - store := storeService.OpenKVStore(ctx) - var currParams types.Params - legacySubspace.GetParamSet(ctx, &currParams) - - if err := currParams.Validate(); err != nil { - return err - } - - bz := cdc.MustMarshal(&currParams) - - return store.Set(ParamsKey, bz) -} diff --git a/x/auth/migrations/v4/migrate_test.go b/x/auth/migrations/v4/migrate_test.go deleted file mode 100644 index bc55fbe3985d..000000000000 --- a/x/auth/migrations/v4/migrate_test.go +++ /dev/null @@ -1,50 +0,0 @@ -package v4_test - -import ( - "testing" - - "github.com/stretchr/testify/require" - - storetypes "cosmossdk.io/store/types" - - "github.com/cosmos/cosmos-sdk/runtime" - "github.com/cosmos/cosmos-sdk/testutil" - sdk "github.com/cosmos/cosmos-sdk/types" - moduletestutil "github.com/cosmos/cosmos-sdk/types/module/testutil" - "github.com/cosmos/cosmos-sdk/x/auth" - "github.com/cosmos/cosmos-sdk/x/auth/exported" - v1 "github.com/cosmos/cosmos-sdk/x/auth/migrations/v1" - v4 "github.com/cosmos/cosmos-sdk/x/auth/migrations/v4" - "github.com/cosmos/cosmos-sdk/x/auth/types" -) - -type mockSubspace struct { - ps types.Params -} - -func newMockSubspace(ps types.Params) mockSubspace { - return mockSubspace{ps: ps} -} - -func (ms mockSubspace) GetParamSet(ctx sdk.Context, ps exported.ParamSet) { - *ps.(*types.Params) = ms.ps -} - -func TestMigrate(t *testing.T) { - encCfg := moduletestutil.MakeTestEncodingConfig(auth.AppModuleBasic{}) - cdc := encCfg.Codec - - storeKey := storetypes.NewKVStoreKey(v1.ModuleName) - tKey := storetypes.NewTransientStoreKey("transient_test") - ctx := testutil.DefaultContext(storeKey, tKey) - storeService := runtime.NewKVStoreService(storeKey) - - legacySubspace := newMockSubspace(types.DefaultParams()) - require.NoError(t, v4.Migrate(ctx, storeService, legacySubspace, cdc)) - - var res types.Params - bz, err := storeService.OpenKVStore(ctx).Get(v4.ParamsKey) - require.NoError(t, err) - require.NoError(t, cdc.Unmarshal(bz, &res)) - require.Equal(t, legacySubspace.ps, res) -} diff --git a/x/auth/module.go b/x/auth/module.go index 134bb2293d8c..5da31dfd56c9 100644 --- a/x/auth/module.go +++ b/x/auth/module.go @@ -21,7 +21,6 @@ import ( sdk "github.com/cosmos/cosmos-sdk/types" "github.com/cosmos/cosmos-sdk/types/module" simtypes "github.com/cosmos/cosmos-sdk/types/simulation" - "github.com/cosmos/cosmos-sdk/x/auth/exported" "github.com/cosmos/cosmos-sdk/x/auth/keeper" "github.com/cosmos/cosmos-sdk/x/auth/simulation" "github.com/cosmos/cosmos-sdk/x/auth/types" @@ -92,9 +91,6 @@ type AppModule struct { accountKeeper keeper.AccountKeeper randGenAccountsFn types.RandomGenesisAccountsFn - - // legacySubspace is used solely for migration of x/params managed parameters - legacySubspace exported.Subspace } // PreBlock cleans up expired unordered transaction nonces from state. @@ -118,12 +114,11 @@ func (am AppModule) IsOnePerModuleType() {} func (am AppModule) IsAppModule() {} // NewAppModule creates a new AppModule object -func NewAppModule(cdc codec.Codec, accountKeeper keeper.AccountKeeper, randGenAccountsFn types.RandomGenesisAccountsFn, ss exported.Subspace) AppModule { +func NewAppModule(cdc codec.Codec, accountKeeper keeper.AccountKeeper, randGenAccountsFn types.RandomGenesisAccountsFn) AppModule { return AppModule{ AppModuleBasic: AppModuleBasic{ac: accountKeeper.AddressCodec()}, accountKeeper: accountKeeper, randGenAccountsFn: randGenAccountsFn, - legacySubspace: ss, } } @@ -133,22 +128,7 @@ func (am AppModule) RegisterServices(cfg module.Configurator) { types.RegisterMsgServer(cfg.MsgServer(), keeper.NewMsgServerImpl(am.accountKeeper)) types.RegisterQueryServer(cfg.QueryServer(), keeper.NewQueryServer(am.accountKeeper)) - m := keeper.NewMigrator(am.accountKeeper, cfg.QueryServer(), am.legacySubspace) - if err := cfg.RegisterMigration(types.ModuleName, 1, m.Migrate1to2); err != nil { - panic(fmt.Sprintf("failed to migrate x/%s from version 1 to 2: %v", types.ModuleName, err)) - } - - if err := cfg.RegisterMigration(types.ModuleName, 2, m.Migrate2to3); err != nil { - panic(fmt.Sprintf("failed to migrate x/%s from version 2 to 3: %v", types.ModuleName, err)) - } - - if err := cfg.RegisterMigration(types.ModuleName, 3, m.Migrate3to4); err != nil { - panic(fmt.Sprintf("failed to migrate x/%s from version 3 to 4: %v", types.ModuleName, err)) - } - - if err := cfg.RegisterMigration(types.ModuleName, 4, m.Migrate4To5); err != nil { - panic(fmt.Sprintf("failed to migrate x/%s from version 4 to 5", types.ModuleName)) - } + _ = keeper.NewMigrator(am.accountKeeper, cfg.QueryServer()) } // InitGenesis performs genesis initialization for the auth module. It returns @@ -217,9 +197,6 @@ type ModuleInputs struct { AddressCodec address.Codec RandomGenesisAccountsFn types.RandomGenesisAccountsFn `optional:"true"` AccountI func() sdk.AccountI `optional:"true"` - - // LegacySubspace is used solely for migration of x/params managed parameters - LegacySubspace exported.Subspace `optional:"true"` } type ModuleOutputs struct { @@ -252,7 +229,7 @@ func ProvideModule(in ModuleInputs) ModuleOutputs { keeperOpts := []keeper.InitOption{keeper.WithUnorderedTransactions(in.Config.EnableUnorderedTransactions)} k := keeper.NewAccountKeeper(in.Cdc, in.StoreService, in.AccountI, maccPerms, in.AddressCodec, in.Config.Bech32Prefix, authority.String(), keeperOpts...) - m := NewAppModule(in.Cdc, k, in.RandomGenesisAccountsFn, in.LegacySubspace) + m := NewAppModule(in.Cdc, k, in.RandomGenesisAccountsFn) return ModuleOutputs{AccountKeeper: k, Module: m} } diff --git a/x/auth/testutil/app_config.go b/x/auth/testutil/app_config.go index c8e88f2bc6b2..c639c6905c60 100644 --- a/x/auth/testutil/app_config.go +++ b/x/auth/testutil/app_config.go @@ -8,7 +8,6 @@ import ( _ "github.com/cosmos/cosmos-sdk/x/bank" // import as blank for app wiring _ "github.com/cosmos/cosmos-sdk/x/consensus" // import as blank for app wiring _ "github.com/cosmos/cosmos-sdk/x/genutil" // import as blank for app wiring - _ "github.com/cosmos/cosmos-sdk/x/params" // import as blank for app wiring _ "github.com/cosmos/cosmos-sdk/x/staking" // import as blank for app wiring ) @@ -19,6 +18,5 @@ var AppConfig = configurator.NewAppConfig( configurator.StakingModule(), configurator.TxModule(), configurator.ConsensusModule(), - configurator.ParamsModule(), configurator.GenutilModule(), ) diff --git a/x/auth/types/params_legacy.go b/x/auth/types/params_legacy.go deleted file mode 100644 index 8800f5822283..000000000000 --- a/x/auth/types/params_legacy.go +++ /dev/null @@ -1,38 +0,0 @@ -/* -NOTE: Usage of x/params to manage parameters is deprecated in favor of x/gov -controlled execution of MsgUpdateParams messages. These types remains solely -for migration purposes and will be removed in a future release. -*/ -package types - -import ( - paramtypes "github.com/cosmos/cosmos-sdk/x/params/types" -) - -// Parameter keys -var ( - KeyMaxMemoCharacters = []byte("MaxMemoCharacters") - KeyTxSigLimit = []byte("TxSigLimit") - KeyTxSizeCostPerByte = []byte("TxSizeCostPerByte") - KeySigVerifyCostED25519 = []byte("SigVerifyCostED25519") - KeySigVerifyCostSecp256k1 = []byte("SigVerifyCostSecp256k1") -) - -var _ paramtypes.ParamSet = &Params{} - -// Deprecated: ParamKeyTable for auth module -func ParamKeyTable() paramtypes.KeyTable { - return paramtypes.NewKeyTable().RegisterParamSet(&Params{}) -} - -// ParamSetPairs implements the ParamSet interface and returns all the key/value pairs -// pairs of auth module's parameters. -func (p *Params) ParamSetPairs() paramtypes.ParamSetPairs { - return paramtypes.ParamSetPairs{ - paramtypes.NewParamSetPair(KeyMaxMemoCharacters, &p.MaxMemoCharacters, validateMaxMemoCharacters), - paramtypes.NewParamSetPair(KeyTxSigLimit, &p.TxSigLimit, validateTxSigLimit), - paramtypes.NewParamSetPair(KeyTxSizeCostPerByte, &p.TxSizeCostPerByte, validateTxSizeCostPerByte), - paramtypes.NewParamSetPair(KeySigVerifyCostED25519, &p.SigVerifyCostED25519, validateSigVerifyCostED25519), - paramtypes.NewParamSetPair(KeySigVerifyCostSecp256k1, &p.SigVerifyCostSecp256k1, validateSigVerifyCostSecp256k1), - } -} diff --git a/x/authz/testutil/app_config.go b/x/authz/testutil/app_config.go index f1e61c100bbb..ff8be58fe3cb 100644 --- a/x/authz/testutil/app_config.go +++ b/x/authz/testutil/app_config.go @@ -10,7 +10,6 @@ import ( _ "github.com/cosmos/cosmos-sdk/x/genutil" // import as blank for app wiring _ "github.com/cosmos/cosmos-sdk/x/gov" // import as blank for app wiring _ "github.com/cosmos/cosmos-sdk/x/mint" // import as blank for app wiring - _ "github.com/cosmos/cosmos-sdk/x/params" // import as blank for app wiring _ "github.com/cosmos/cosmos-sdk/x/staking" // import as blank for app wiring ) @@ -20,7 +19,6 @@ var AppConfig = configurator.NewAppConfig( configurator.StakingModule(), configurator.TxModule(), configurator.ConsensusModule(), - configurator.ParamsModule(), configurator.GenutilModule(), configurator.AuthzModule(), configurator.MintModule(), diff --git a/x/bank/app_test.go b/x/bank/app_test.go index 8883fde6f041..64a155d855bb 100644 --- a/x/bank/app_test.go +++ b/x/bank/app_test.go @@ -31,7 +31,6 @@ import ( distrkeeper "github.com/cosmos/cosmos-sdk/x/distribution/keeper" _ "github.com/cosmos/cosmos-sdk/x/gov" govv1 "github.com/cosmos/cosmos-sdk/x/gov/types/v1" - _ "github.com/cosmos/cosmos-sdk/x/params" _ "github.com/cosmos/cosmos-sdk/x/staking" ) @@ -118,7 +117,6 @@ func createTestSuite(t *testing.T, genesisAccounts []authtypes.GenesisAccount) s app, err := simtestutil.SetupWithConfiguration( depinject.Configs( configurator.NewAppConfig( - configurator.ParamsModule(), configurator.AuthModule(), configurator.StakingModule(), configurator.TxModule(), diff --git a/x/bank/exported/exported.go b/x/bank/exported/exported.go index 6ffabfe5831d..23055f59383d 100644 --- a/x/bank/exported/exported.go +++ b/x/bank/exported/exported.go @@ -2,7 +2,6 @@ package exported import ( sdk "github.com/cosmos/cosmos-sdk/types" - paramtypes "github.com/cosmos/cosmos-sdk/x/params/types" ) // GenesisBalance defines a genesis balance interface that allows for account @@ -11,16 +10,3 @@ type GenesisBalance interface { GetAddress() string GetCoins() sdk.Coins } - -type ( - ParamSet = paramtypes.ParamSet - - // Subspace defines an interface that implements the legacy x/params Subspace - // type. - // - // NOTE: This is used solely for migration of x/params managed parameters. - Subspace interface { - GetParamSet(ctx sdk.Context, ps ParamSet) - Get(ctx sdk.Context, key []byte, ptr any) - } -) diff --git a/x/bank/keeper/keeper_test.go b/x/bank/keeper/keeper_test.go index 224f1efc0b5e..cc6ef26e33f6 100644 --- a/x/bank/keeper/keeper_test.go +++ b/x/bank/keeper/keeper_test.go @@ -33,7 +33,6 @@ import ( "github.com/cosmos/cosmos-sdk/types/query" authtypes "github.com/cosmos/cosmos-sdk/x/auth/types" vesting "github.com/cosmos/cosmos-sdk/x/auth/vesting/types" - "github.com/cosmos/cosmos-sdk/x/bank/exported" "github.com/cosmos/cosmos-sdk/x/bank/keeper" banktestutil "github.com/cosmos/cosmos-sdk/x/bank/testutil" banktypes "github.com/cosmos/cosmos-sdk/x/bank/types" @@ -2721,68 +2720,6 @@ func copyAndSortCoins(coins sdk.Coins) sdk.Coins { return rv.Sort() } -type mockSubspace struct { - ps banktypes.Params -} - -func (ms mockSubspace) GetParamSet(ctx sdk.Context, ps exported.ParamSet) { - *ps.(*banktypes.Params) = ms.ps -} - -func (ms mockSubspace) Get(ctx sdk.Context, key []byte, ptr any) {} - -func (suite *KeeperTestSuite) TestMigrator_Migrate3to4() { - bankKeeper := suite.bankKeeper - ctx := sdk.UnwrapSDKContext(suite.ctx) - require := suite.Require() - - for _, def := range []bool{true, false} { - params := banktypes.Params{DefaultSendEnabled: def} - require.NoError(bankKeeper.SetParams(ctx, params)) - - suite.T().Run(fmt.Sprintf("default %t does not change", def), func(t *testing.T) { - legacySubspace := func(ps banktypes.Params) mockSubspace { - return mockSubspace{ps: ps} - }(banktypes.NewParams(def)) - - migrator := keeper.NewMigrator(bankKeeper, legacySubspace) - require.NoError(migrator.Migrate3to4(ctx)) - - actual := bankKeeper.GetParams(ctx) - require.Equal(params.DefaultSendEnabled, actual.DefaultSendEnabled) - }) - } - - for _, def := range []bool{true, false} { - params := banktypes.Params{ - SendEnabled: []*banktypes.SendEnabled{ - {Denom: fmt.Sprintf("truecoin%t", def), Enabled: true}, - {Denom: fmt.Sprintf("falsecoin%t", def), Enabled: false}, - }, - } - - require.NoError(bankKeeper.SetParams(ctx, params)) - - suite.T().Run(fmt.Sprintf("default %t send enabled info moved to store", def), func(t *testing.T) { - legacySubspace := func(ps banktypes.Params) mockSubspace { - return mockSubspace{ps: ps} - }(banktypes.NewParams(def)) - - migrator := keeper.NewMigrator(bankKeeper, legacySubspace) - require.NoError(migrator.Migrate3to4(ctx)) - - newParams := bankKeeper.GetParams(ctx) - require.Len(newParams.SendEnabled, 0) //nolint // just using this for testing when migrating legacy - require.Equal(def, newParams.DefaultSendEnabled) - - for _, se := range params.SendEnabled { - actual := bankKeeper.IsSendEnabledDenom(ctx, se.Denom) - require.Equal(se.Enabled, actual, se.Denom) - } - }) - } -} - func (suite *KeeperTestSuite) TestSetParams() { ctx, bankKeeper := suite.ctx, suite.bankKeeper require := suite.Require() diff --git a/x/bank/keeper/migrations.go b/x/bank/keeper/migrations.go deleted file mode 100644 index c083bfa975dd..000000000000 --- a/x/bank/keeper/migrations.go +++ /dev/null @@ -1,43 +0,0 @@ -package keeper - -import ( - sdk "github.com/cosmos/cosmos-sdk/types" - "github.com/cosmos/cosmos-sdk/x/bank/exported" - v2 "github.com/cosmos/cosmos-sdk/x/bank/migrations/v2" - v3 "github.com/cosmos/cosmos-sdk/x/bank/migrations/v3" - v4 "github.com/cosmos/cosmos-sdk/x/bank/migrations/v4" - "github.com/cosmos/cosmos-sdk/x/bank/types" -) - -// Migrator is a struct for handling in-place store migrations. -type Migrator struct { - keeper BaseKeeper - legacySubspace exported.Subspace -} - -// NewMigrator returns a new Migrator. -func NewMigrator(keeper BaseKeeper, legacySubspace exported.Subspace) Migrator { - return Migrator{keeper: keeper, legacySubspace: legacySubspace} -} - -// Migrate1to2 migrates from version 1 to 2. -func (m Migrator) Migrate1to2(ctx sdk.Context) error { - return v2.MigrateStore(ctx, m.keeper.storeService, m.keeper.cdc) -} - -// Migrate2to3 migrates x/bank storage from version 2 to 3. -func (m Migrator) Migrate2to3(ctx sdk.Context) error { - return v3.MigrateStore(ctx, m.keeper.storeService, m.keeper.cdc) -} - -// Migrate3to4 migrates x/bank storage from version 3 to 4. -func (m Migrator) Migrate3to4(ctx sdk.Context) error { - m.MigrateSendEnabledParams(ctx) - return v4.MigrateStore(ctx, m.keeper.storeService, m.legacySubspace, m.keeper.cdc) -} - -// MigrateSendEnabledParams get params from x/params and update the bank params. -func (m Migrator) MigrateSendEnabledParams(ctx sdk.Context) { - sendEnabled := types.GetSendEnabledParams(ctx, m.legacySubspace) - m.keeper.SetAllSendEnabled(ctx, sendEnabled) -} diff --git a/x/bank/migrations/v1/types.go b/x/bank/migrations/v1/types.go deleted file mode 100644 index 6658af910c40..000000000000 --- a/x/bank/migrations/v1/types.go +++ /dev/null @@ -1,71 +0,0 @@ -package v1 - -import ( - "github.com/golang/protobuf/proto" - - codectypes "github.com/cosmos/cosmos-sdk/codec/types" - sdk "github.com/cosmos/cosmos-sdk/types" - "github.com/cosmos/cosmos-sdk/types/kv" - v1auth "github.com/cosmos/cosmos-sdk/x/auth/migrations/v1" - "github.com/cosmos/cosmos-sdk/x/bank/types" -) - -const ( - // ModuleName defines the module name - ModuleName = "bank" - - // StoreKey defines the primary module store key - StoreKey = ModuleName - - // RouterKey defines the module's message routing key - RouterKey = ModuleName - - // QuerierRoute defines the module's query routing key - QuerierRoute = ModuleName -) - -// KVStore keys -var ( - BalancesPrefix = []byte("balances") - SupplyKey = []byte{0x00} - DenomMetadataPrefix = []byte{0x1} -) - -// DenomMetadataKey returns the denomination metadata key. -func DenomMetadataKey(denom string) []byte { - d := []byte(denom) - return append(DenomMetadataPrefix, d...) -} - -// AddressFromBalancesStore returns an account address from a balances prefix -// store. The key must not contain the prefix BalancesPrefix as the prefix store -// iterator discards the actual prefix. -func AddressFromBalancesStore(key []byte) sdk.AccAddress { - kv.AssertKeyAtLeastLength(key, 1+v1auth.AddrLen) - addr := key[:v1auth.AddrLen] - kv.AssertKeyLength(addr, v1auth.AddrLen) - return sdk.AccAddress(addr) -} - -// SupplyI defines an inflationary supply interface for modules that handle -// token supply. -// It is copy-pasted from: -// https://github.com/cosmos/cosmos-sdk/blob/v0.42.3/x/bank/exported/exported.go -// where we stripped off the unnecessary methods. -// -// It is used in the migration script, because we save this interface as an Any -// in the supply state. -// -// Deprecated. -type SupplyI interface { - proto.Message -} - -// RegisterInterfaces registers interfaces required for the v1 migrations. -func RegisterInterfaces(registry codectypes.InterfaceRegistry) { - registry.RegisterInterface( - "cosmos.bank.v1beta1.SupplyI", - (*SupplyI)(nil), - &types.Supply{}, - ) -} diff --git a/x/bank/migrations/v2/json.go b/x/bank/migrations/v2/json.go deleted file mode 100644 index 0c128db21d3c..000000000000 --- a/x/bank/migrations/v2/json.go +++ /dev/null @@ -1,32 +0,0 @@ -package v2 - -import ( - sdk "github.com/cosmos/cosmos-sdk/types" - "github.com/cosmos/cosmos-sdk/x/bank/types" -) - -// pruneZeroBalancesJSON removes the zero balance addresses from exported genesis. -func pruneZeroBalancesJSON(oldBalances []types.Balance) []types.Balance { - var balances []types.Balance - - for _, b := range oldBalances { - if !b.Coins.IsZero() { - b.Coins = sdk.NewCoins(b.Coins...) // prunes zero denom. - balances = append(balances, b) - } - } - - return balances -} - -// MigrateJSON accepts exported v0.40 x/bank genesis state and migrates it to -// v0.43 x/bank genesis state. The migration includes: -// - Prune balances & supply with zero coins (ref: https://github.com/cosmos/cosmos-sdk/pull/9229) -func MigrateJSON(oldState *types.GenesisState) *types.GenesisState { - return &types.GenesisState{ - Params: oldState.Params, - Balances: pruneZeroBalancesJSON(oldState.Balances), - Supply: sdk.NewCoins(oldState.Supply...), // NewCoins used here to remove zero coin denoms from supply. - DenomMetadata: oldState.DenomMetadata, - } -} diff --git a/x/bank/migrations/v2/json_test.go b/x/bank/migrations/v2/json_test.go deleted file mode 100644 index 09caa926f226..000000000000 --- a/x/bank/migrations/v2/json_test.go +++ /dev/null @@ -1,96 +0,0 @@ -package v2_test - -import ( - "encoding/json" - "testing" - - "github.com/stretchr/testify/require" - - sdkmath "cosmossdk.io/math" - - "github.com/cosmos/cosmos-sdk/client" - sdk "github.com/cosmos/cosmos-sdk/types" - moduletestutil "github.com/cosmos/cosmos-sdk/types/module/testutil" - v2bank "github.com/cosmos/cosmos-sdk/x/bank/migrations/v2" - "github.com/cosmos/cosmos-sdk/x/bank/types" -) - -func TestMigrateJSON(t *testing.T) { - encodingConfig := moduletestutil.MakeTestEncodingConfig() - clientCtx := client.Context{}. - WithInterfaceRegistry(encodingConfig.InterfaceRegistry). - WithTxConfig(encodingConfig.TxConfig). - WithCodec(encodingConfig.Codec) - - voter, err := sdk.AccAddressFromBech32("cosmos1fl48vsnmsdzcv85q5d2q4z5ajdha8yu34mf0eh") - require.NoError(t, err) - bankGenState := &types.GenesisState{ - Balances: []types.Balance{ - { - Address: voter.String(), - Coins: sdk.Coins{ - sdk.NewCoin("foo", sdkmath.NewInt(10)), - sdk.NewCoin("bar", sdkmath.NewInt(20)), - sdk.NewCoin("foobar", sdkmath.NewInt(0)), - }, - }, - }, - Supply: sdk.Coins{ - sdk.NewCoin("foo", sdkmath.NewInt(10)), - sdk.NewCoin("bar", sdkmath.NewInt(20)), - sdk.NewCoin("foobar", sdkmath.NewInt(0)), - sdk.NewCoin("barfoo", sdkmath.NewInt(0)), - }, - } - - migrated := v2bank.MigrateJSON(bankGenState) - - bz, err := clientCtx.Codec.MarshalJSON(migrated) - require.NoError(t, err) - - // Indent the JSON bz correctly. - var jsonObj map[string]any - err = json.Unmarshal(bz, &jsonObj) - require.NoError(t, err) - indentedBz, err := json.MarshalIndent(jsonObj, "", "\t") - require.NoError(t, err) - - // Make sure about: - // - zero coin balances pruned. - // - zero supply denoms pruned. - expected := `{ - "balances": [ - { - "address": "cosmos1fl48vsnmsdzcv85q5d2q4z5ajdha8yu34mf0eh", - "coins": [ - { - "amount": "20", - "denom": "bar" - }, - { - "amount": "10", - "denom": "foo" - } - ] - } - ], - "denom_metadata": [], - "params": { - "default_send_enabled": false, - "send_enabled": [] - }, - "send_enabled": [], - "supply": [ - { - "amount": "20", - "denom": "bar" - }, - { - "amount": "10", - "denom": "foo" - } - ] -}` - - require.Equal(t, expected, string(indentedBz)) -} diff --git a/x/bank/migrations/v2/keys.go b/x/bank/migrations/v2/keys.go deleted file mode 100644 index eadb02e9d8d8..000000000000 --- a/x/bank/migrations/v2/keys.go +++ /dev/null @@ -1,45 +0,0 @@ -package v2 - -import ( - "errors" - - sdk "github.com/cosmos/cosmos-sdk/types" - "github.com/cosmos/cosmos-sdk/types/address" -) - -const ( - ModuleName = "bank" -) - -var ( - SupplyKey = []byte{0x00} - BalancesPrefix = []byte{0x02} - DenomMetadataPrefix = []byte{0x1} - - ErrInvalidKey = errors.New("invalid key") -) - -func CreateAccountBalancesPrefix(addr []byte) []byte { - return append(BalancesPrefix, address.MustLengthPrefix(addr)...) -} - -func AddressFromBalancesStore(key []byte) (sdk.AccAddress, error) { - if len(key) == 0 { - return nil, ErrInvalidKey - } - - addrLen := key[0] - bound := int(addrLen) - - if len(key)-1 < bound { - return nil, ErrInvalidKey - } - - return key[1 : bound+1], nil -} - -// DenomMetadataKey returns the denomination metadata key. -func DenomMetadataKey(denom string) []byte { - d := []byte(denom) - return append(DenomMetadataPrefix, d...) -} diff --git a/x/bank/migrations/v2/store.go b/x/bank/migrations/v2/store.go deleted file mode 100644 index b804ab697976..000000000000 --- a/x/bank/migrations/v2/store.go +++ /dev/null @@ -1,143 +0,0 @@ -package v2 - -import ( - "cosmossdk.io/core/store" - "cosmossdk.io/log" - "cosmossdk.io/math" - "cosmossdk.io/store/prefix" - storetypes "cosmossdk.io/store/types" - - "github.com/cosmos/cosmos-sdk/codec" - "github.com/cosmos/cosmos-sdk/runtime" - sdk "github.com/cosmos/cosmos-sdk/types" - v1auth "github.com/cosmos/cosmos-sdk/x/auth/migrations/v1" - v1 "github.com/cosmos/cosmos-sdk/x/bank/migrations/v1" - "github.com/cosmos/cosmos-sdk/x/bank/types" -) - -// migrateSupply migrates the supply to be stored by denom key instead in a -// single blob. -// ref: https://github.com/cosmos/cosmos-sdk/issues/7092 -func migrateSupply(store storetypes.KVStore, cdc codec.BinaryCodec) error { - // Old supply was stored as a single blob under the SupplyKey. - var oldSupplyI v1.SupplyI - err := cdc.UnmarshalInterface(store.Get(v1.SupplyKey), &oldSupplyI) - if err != nil { - return err - } - - // We delete the single key holding the whole blob. - store.Delete(v1.SupplyKey) - - if oldSupplyI == nil { - return nil - } - - // We add a new key for each denom - supplyStore := prefix.NewStore(store, SupplyKey) - - // We're sure that SupplyI is a Supply struct, there's no other - // implementation. - oldSupply := oldSupplyI.(*types.Supply) - for i := range oldSupply.Total { - coin := oldSupply.Total[i] - coinBz, err := coin.Amount.Marshal() - if err != nil { - return err - } - - supplyStore.Set([]byte(coin.Denom), coinBz) - } - - return nil -} - -// migrateBalanceKeys migrate the balances keys to cater for variable-length -// addresses. -func migrateBalanceKeys(store storetypes.KVStore, logger log.Logger) { - // old key is of format: - // prefix ("balances") || addrBytes (20 bytes) || denomBytes - // new key is of format - // prefix (0x02) || addrLen (1 byte) || addrBytes || denomBytes - oldStore := prefix.NewStore(store, v1.BalancesPrefix) - - oldStoreIter := oldStore.Iterator(nil, nil) - defer sdk.LogDeferred(logger, func() error { return oldStoreIter.Close() }) - - for ; oldStoreIter.Valid(); oldStoreIter.Next() { - addr := v1.AddressFromBalancesStore(oldStoreIter.Key()) - denom := oldStoreIter.Key()[v1auth.AddrLen:] - newStoreKey := CreatePrefixedAccountStoreKey(addr, denom) - - // Set new key on store. Values don't change. - store.Set(newStoreKey, oldStoreIter.Value()) - oldStore.Delete(oldStoreIter.Key()) - } -} - -// MigrateStore performs in-place store migrations from v0.40 to v0.43. The -// migration includes: -// -// - Change addresses to be length-prefixed. -// - Change balances prefix to 1 byte -// - Change supply to be indexed by denom -// - Prune balances & supply with zero coins (ref: https://github.com/cosmos/cosmos-sdk/pull/9229) -func MigrateStore(ctx sdk.Context, storeService store.KVStoreService, cdc codec.BinaryCodec) error { - store := runtime.KVStoreAdapter(storeService.OpenKVStore(ctx)) - migrateBalanceKeys(store, ctx.Logger()) - - if err := pruneZeroBalances(store, cdc); err != nil { - return err - } - - if err := migrateSupply(store, cdc); err != nil { - return err - } - - return pruneZeroSupply(store) -} - -// pruneZeroBalances removes the zero balance addresses from balances store. -func pruneZeroBalances(store storetypes.KVStore, cdc codec.BinaryCodec) error { - balancesStore := prefix.NewStore(store, BalancesPrefix) - iterator := balancesStore.Iterator(nil, nil) - defer iterator.Close() - - for ; iterator.Valid(); iterator.Next() { - var balance sdk.Coin - if err := cdc.Unmarshal(iterator.Value(), &balance); err != nil { - return err - } - - if balance.IsZero() { - balancesStore.Delete(iterator.Key()) - } - } - return nil -} - -// pruneZeroSupply removes zero balance denom from supply store. -func pruneZeroSupply(store storetypes.KVStore) error { - supplyStore := prefix.NewStore(store, SupplyKey) - iterator := supplyStore.Iterator(nil, nil) - defer iterator.Close() - - for ; iterator.Valid(); iterator.Next() { - var amount math.Int - if err := amount.Unmarshal(iterator.Value()); err != nil { - return err - } - - if amount.IsZero() { - supplyStore.Delete(iterator.Key()) - } - } - - return nil -} - -// CreatePrefixedAccountStoreKey returns the key for the given account and denomination. -// This method can be used when performing an ABCI query for the balance of an account. -func CreatePrefixedAccountStoreKey(addr, denom []byte) []byte { - return append(CreateAccountBalancesPrefix(addr), denom...) -} diff --git a/x/bank/migrations/v2/store_test.go b/x/bank/migrations/v2/store_test.go deleted file mode 100644 index 4757ec9c764e..000000000000 --- a/x/bank/migrations/v2/store_test.go +++ /dev/null @@ -1,109 +0,0 @@ -package v2_test - -import ( - "testing" - - "github.com/stretchr/testify/require" - - "cosmossdk.io/math" - "cosmossdk.io/store/prefix" - storetypes "cosmossdk.io/store/types" - - "github.com/cosmos/cosmos-sdk/runtime" - "github.com/cosmos/cosmos-sdk/testutil" - "github.com/cosmos/cosmos-sdk/testutil/testdata" - sdk "github.com/cosmos/cosmos-sdk/types" - moduletestutil "github.com/cosmos/cosmos-sdk/types/module/testutil" - v1bank "github.com/cosmos/cosmos-sdk/x/bank/migrations/v1" - v2bank "github.com/cosmos/cosmos-sdk/x/bank/migrations/v2" - "github.com/cosmos/cosmos-sdk/x/bank/types" -) - -func TestSupplyMigration(t *testing.T) { - encCfg := moduletestutil.MakeTestEncodingConfig() - bankKey := storetypes.NewKVStoreKey("bank") - storeService := runtime.NewKVStoreService(bankKey) - ctx := testutil.DefaultContext(bankKey, storetypes.NewTransientStoreKey("transient_test")) - store := runtime.KVStoreAdapter(storeService.OpenKVStore(ctx)) - - v1bank.RegisterInterfaces(encCfg.InterfaceRegistry) - - oldFooCoin := sdk.NewCoin("foo", math.NewInt(100)) - oldBarCoin := sdk.NewCoin("bar", math.NewInt(200)) - oldFooBarCoin := sdk.NewCoin("foobar", math.NewInt(0)) // to ensure the zero denom coins pruned. - - // Old supply was stored as a single blob under the `SupplyKey`. - oldSupply := &types.Supply{Total: sdk.Coins{oldFooCoin, oldBarCoin, oldFooBarCoin}} - oldSupplyBz, err := encCfg.Codec.MarshalInterface(oldSupply) - require.NoError(t, err) - store.Set(v1bank.SupplyKey, oldSupplyBz) - - // Run migration. - err = v2bank.MigrateStore(ctx, storeService, encCfg.Codec) - require.NoError(t, err) - - // New supply is indexed by denom. - supplyStore := prefix.NewStore(store, types.SupplyKey) - bz := supplyStore.Get([]byte("foo")) - var amount math.Int - err = amount.Unmarshal(bz) - require.NoError(t, err) - - newFooCoin := sdk.Coin{ - Denom: "foo", - Amount: amount, - } - require.Equal(t, oldFooCoin, newFooCoin) - - bz = supplyStore.Get([]byte("bar")) - err = amount.Unmarshal(bz) - require.NoError(t, err) - - newBarCoin := sdk.Coin{ - Denom: "bar", - Amount: amount, - } - require.Equal(t, oldBarCoin, newBarCoin) - - // foobar shouldn't be existed in the store. - bz = supplyStore.Get([]byte("foobar")) - require.Nil(t, bz) -} - -func TestBalanceKeysMigration(t *testing.T) { - encCfg := moduletestutil.MakeTestEncodingConfig() - bankKey := storetypes.NewKVStoreKey("bank") - storeService := runtime.NewKVStoreService(bankKey) - ctx := testutil.DefaultContext(bankKey, storetypes.NewTransientStoreKey("transient_test")) - store := runtime.KVStoreAdapter(storeService.OpenKVStore(ctx)) - - _, _, addr := testdata.KeyTestPubAddr() - - // set 10 foo coin - fooCoin := sdk.NewCoin("foo", math.NewInt(10)) - oldFooKey := append(append(v1bank.BalancesPrefix, addr...), []byte(fooCoin.Denom)...) - fooBz, err := encCfg.Codec.Marshal(&fooCoin) - require.NoError(t, err) - store.Set(oldFooKey, fooBz) - - // set 0 foobar coin - fooBarCoin := sdk.NewCoin("foobar", math.NewInt(0)) - oldKeyFooBar := append(append(v1bank.BalancesPrefix, addr...), []byte(fooBarCoin.Denom)...) - fooBarBz, err := encCfg.Codec.Marshal(&fooBarCoin) - require.NoError(t, err) - store.Set(oldKeyFooBar, fooBarBz) - require.NotNil(t, store.Get(oldKeyFooBar)) // before store migration zero values can also exist in store. - - err = v2bank.MigrateStore(ctx, storeService, encCfg.Codec) - require.NoError(t, err) - - newKey := v2bank.CreatePrefixedAccountStoreKey(addr, []byte(fooCoin.Denom)) - // -7 because we replaced "balances" with 0x02, - // +1 because we added length-prefix to address. - require.Equal(t, len(oldFooKey)-7+1, len(newKey)) - require.Nil(t, store.Get(oldFooKey)) - require.Equal(t, fooBz, store.Get(newKey)) - - newKeyFooBar := v2bank.CreatePrefixedAccountStoreKey(addr, []byte(fooBarCoin.Denom)) - require.Nil(t, store.Get(newKeyFooBar)) // after migration zero balances pruned from store. -} diff --git a/x/bank/migrations/v3/keys.go b/x/bank/migrations/v3/keys.go deleted file mode 100644 index e1d6bd711cee..000000000000 --- a/x/bank/migrations/v3/keys.go +++ /dev/null @@ -1,14 +0,0 @@ -package v3 - -var DenomAddressPrefix = []byte{0x03} - -// CreateDenomAddressPrefix creates a prefix for a reverse index of denomination -// to account balance for that denomination. -func CreateDenomAddressPrefix(denom string) []byte { - // we add a "zero" byte at the end - null byte terminator, to allow denom prefix - // scan. Setting it is not needed (key[last] = 0) - because this is the default. - key := make([]byte, len(DenomAddressPrefix)+len(denom)+1) - copy(key, DenomAddressPrefix) - copy(key[len(DenomAddressPrefix):], denom) - return key -} diff --git a/x/bank/migrations/v3/store.go b/x/bank/migrations/v3/store.go deleted file mode 100644 index a8a1e4e7fffa..000000000000 --- a/x/bank/migrations/v3/store.go +++ /dev/null @@ -1,103 +0,0 @@ -package v3 - -import ( - "cosmossdk.io/core/store" - "cosmossdk.io/log" - "cosmossdk.io/store/prefix" - storetypes "cosmossdk.io/store/types" - - "github.com/cosmos/cosmos-sdk/codec" - "github.com/cosmos/cosmos-sdk/runtime" - sdk "github.com/cosmos/cosmos-sdk/types" - "github.com/cosmos/cosmos-sdk/types/address" - v2 "github.com/cosmos/cosmos-sdk/x/bank/migrations/v2" - "github.com/cosmos/cosmos-sdk/x/bank/types" -) - -// MigrateStore performs in-place store migrations from v0.43 to v0.45. The -// migration includes: -// -// - Migrate coin storage to save only amount. -// - Add an additional reverse index from denomination to address. -// - Remove duplicate denom from denom metadata store key. -func MigrateStore(ctx sdk.Context, storeService store.KVStoreService, cdc codec.BinaryCodec) error { - store := runtime.KVStoreAdapter(storeService.OpenKVStore(ctx)) - err := addDenomReverseIndex(store, cdc, ctx.Logger()) - if err != nil { - return err - } - - return migrateDenomMetadata(store, ctx.Logger()) -} - -func addDenomReverseIndex(store storetypes.KVStore, cdc codec.BinaryCodec, logger log.Logger) error { - oldBalancesStore := prefix.NewStore(store, v2.BalancesPrefix) - - oldBalancesIter := oldBalancesStore.Iterator(nil, nil) - defer sdk.LogDeferred(logger, func() error { return oldBalancesIter.Close() }) - - denomPrefixStores := make(map[string]prefix.Store) // memoize prefix stores - - for ; oldBalancesIter.Valid(); oldBalancesIter.Next() { - var balance sdk.Coin - if err := cdc.Unmarshal(oldBalancesIter.Value(), &balance); err != nil { - return err - } - - addr, err := v2.AddressFromBalancesStore(oldBalancesIter.Key()) - if err != nil { - return err - } - - var coin sdk.DecCoin - if err := cdc.Unmarshal(oldBalancesIter.Value(), &coin); err != nil { - return err - } - - bz, err := coin.Amount.Marshal() - if err != nil { - return err - } - - newStore := prefix.NewStore(store, CreateAccountBalancesPrefix(addr)) - newStore.Set([]byte(coin.Denom), bz) - - denomPrefixStore, ok := denomPrefixStores[balance.Denom] - if !ok { - denomPrefixStore = prefix.NewStore(store, CreateDenomAddressPrefix(balance.Denom)) - denomPrefixStores[balance.Denom] = denomPrefixStore - } - - // Store a reverse index from denomination to account address with a - // sentinel value. - denomPrefixStore.Set(address.MustLengthPrefix(addr), []byte{0}) - } - - return nil -} - -func migrateDenomMetadata(store storetypes.KVStore, logger log.Logger) error { - oldDenomMetaDataStore := prefix.NewStore(store, v2.DenomMetadataPrefix) - - oldDenomMetaDataIter := oldDenomMetaDataStore.Iterator(nil, nil) - defer sdk.LogDeferred(logger, func() error { return oldDenomMetaDataIter.Close() }) - - for ; oldDenomMetaDataIter.Valid(); oldDenomMetaDataIter.Next() { - oldKey := oldDenomMetaDataIter.Key() - l := len(oldKey) / 2 - - newKey := make([]byte, len(types.DenomMetadataPrefix)+l) - // old key: prefix_bytes | denom_bytes | denom_bytes - copy(newKey, types.DenomMetadataPrefix) - copy(newKey[len(types.DenomMetadataPrefix):], oldKey[:l]) - store.Set(newKey, oldDenomMetaDataIter.Value()) - oldDenomMetaDataStore.Delete(oldKey) - } - - return nil -} - -// CreateAccountBalancesPrefix creates the prefix for an account's balances. -func CreateAccountBalancesPrefix(addr []byte) []byte { - return append(types.BalancesPrefix.Bytes(), address.MustLengthPrefix(addr)...) -} diff --git a/x/bank/migrations/v3/store_test.go b/x/bank/migrations/v3/store_test.go deleted file mode 100644 index 3fb5fc7a6fc5..000000000000 --- a/x/bank/migrations/v3/store_test.go +++ /dev/null @@ -1,138 +0,0 @@ -package v3_test - -import ( - "slices" - "testing" - - "github.com/stretchr/testify/require" - - "cosmossdk.io/math" - "cosmossdk.io/store/prefix" - storetypes "cosmossdk.io/store/types" - - "github.com/cosmos/cosmos-sdk/runtime" - "github.com/cosmos/cosmos-sdk/testutil" - sdk "github.com/cosmos/cosmos-sdk/types" - "github.com/cosmos/cosmos-sdk/types/address" - moduletestutil "github.com/cosmos/cosmos-sdk/types/module/testutil" - v2 "github.com/cosmos/cosmos-sdk/x/bank/migrations/v2" - v3 "github.com/cosmos/cosmos-sdk/x/bank/migrations/v3" - "github.com/cosmos/cosmos-sdk/x/bank/types" -) - -func TestMigrateStore(t *testing.T) { - encCfg := moduletestutil.MakeTestEncodingConfig() - bankKey := storetypes.NewKVStoreKey("bank") - storeService := runtime.NewKVStoreService(bankKey) - ctx := testutil.DefaultContext(bankKey, storetypes.NewTransientStoreKey("transient_test")) - store := runtime.KVStoreAdapter(storeService.OpenKVStore(ctx)) - - addr := sdk.AccAddress("addr________________") - prefixAccStore := prefix.NewStore(store, v2.CreateAccountBalancesPrefix(addr)) - - balances := sdk.NewCoins( - sdk.NewCoin("foo", math.NewInt(10000)), - sdk.NewCoin("bar", math.NewInt(20000)), - ) - - for _, b := range balances { - bz, err := encCfg.Codec.Marshal(&b) - require.NoError(t, err) - - prefixAccStore.Set([]byte(b.Denom), bz) - } - - require.NoError(t, v3.MigrateStore(ctx, storeService, encCfg.Codec)) - - for _, b := range balances { - addrPrefixStore := prefix.NewStore(store, v3.CreateAccountBalancesPrefix(addr)) - bz := addrPrefixStore.Get([]byte(b.Denom)) - var expected math.Int - require.NoError(t, expected.Unmarshal(bz)) - require.Equal(t, expected, b.Amount) - } - - for _, b := range balances { - denomPrefixStore := prefix.NewStore(store, v3.CreateDenomAddressPrefix(b.Denom)) - bz := denomPrefixStore.Get(address.MustLengthPrefix(addr)) - require.NotNil(t, bz) - } -} - -func TestMigrateDenomMetaData(t *testing.T) { - encCfg := moduletestutil.MakeTestEncodingConfig() - bankKey := storetypes.NewKVStoreKey("bank") - storeService := runtime.NewKVStoreService(bankKey) - ctx := testutil.DefaultContext(bankKey, storetypes.NewTransientStoreKey("transient_test")) - store := runtime.KVStoreAdapter(storeService.OpenKVStore(ctx)) - metaData := []types.Metadata{ - { - Name: "Cosmos Hub Atom", - Symbol: "ATOM", - Description: "The native staking token of the Cosmos Hub.", - DenomUnits: []*types.DenomUnit{ - {Denom: "uatom", Exponent: uint32(0), Aliases: []string{"microatom"}}, - {Denom: "matom", Exponent: uint32(3), Aliases: []string{"milliatom"}}, - {Denom: "atom", Exponent: uint32(6), Aliases: nil}, - }, - Base: "uatom", - Display: "atom", - }, - { - Name: "Token", - Symbol: "TOKEN", - Description: "The native staking token of the Token Hub.", - DenomUnits: []*types.DenomUnit{ - {Denom: "1token", Exponent: uint32(5), Aliases: []string{"decitoken"}}, - {Denom: "2token", Exponent: uint32(4), Aliases: []string{"centitoken"}}, - {Denom: "3token", Exponent: uint32(7), Aliases: []string{"dekatoken"}}, - }, - Base: "utoken", - Display: "token", - }, - } - denomMetadataStore := prefix.NewStore(store, v2.DenomMetadataPrefix) - - for i := range []int{0, 1} { - // keys before 0.45 had denom two times in the key - key := slices.Clone([]byte(metaData[i].Base)) - key = append(key, []byte(metaData[i].Base)...) - bz, err := encCfg.Codec.Marshal(&metaData[i]) - require.NoError(t, err) - denomMetadataStore.Set(key, bz) - } - - require.NoError(t, v3.MigrateStore(ctx, storeService, encCfg.Codec)) - - denomMetadataStore = prefix.NewStore(store, v2.DenomMetadataPrefix) - denomMetadataIter := denomMetadataStore.Iterator(nil, nil) - defer denomMetadataIter.Close() - for i := 0; denomMetadataIter.Valid(); denomMetadataIter.Next() { - var result types.Metadata - newKey := denomMetadataIter.Key() - - // make sure old entry is deleted - oldKey := append(newKey, newKey[0:]...) - bz := denomMetadataStore.Get(oldKey) - require.Nil(t, bz) - - require.Equal(t, string(newKey), metaData[i].Base, "idx: %d", i) - bz = denomMetadataStore.Get(denomMetadataIter.Key()) - require.NotNil(t, bz) - err := encCfg.Codec.Unmarshal(bz, &result) - require.NoError(t, err) - assertMetaDataEqual(t, metaData[i], result) - i++ - } -} - -func assertMetaDataEqual(t *testing.T, expected, actual types.Metadata) { - t.Helper() - - require.Equal(t, expected.GetBase(), actual.GetBase()) - require.Equal(t, expected.GetDisplay(), actual.GetDisplay()) - require.Equal(t, expected.GetDescription(), actual.GetDescription()) - require.Equal(t, expected.GetDenomUnits()[1].GetDenom(), actual.GetDenomUnits()[1].GetDenom()) - require.Equal(t, expected.GetDenomUnits()[1].GetExponent(), actual.GetDenomUnits()[1].GetExponent()) - require.Equal(t, expected.GetDenomUnits()[1].GetAliases(), actual.GetDenomUnits()[1].GetAliases()) -} diff --git a/x/bank/migrations/v4/gen_state.go b/x/bank/migrations/v4/gen_state.go deleted file mode 100644 index f81f3b6728ec..000000000000 --- a/x/bank/migrations/v4/gen_state.go +++ /dev/null @@ -1,14 +0,0 @@ -package v4 - -import ( - "github.com/cosmos/cosmos-sdk/x/bank/types" -) - -// MigrateGenState accepts exported v0.43 x/bank genesis state and migrates it to -// v0.47 x/bank genesis state. The migration includes: -// - Move the SendEnabled entries from Params to the new GenesisState.SendEnabled field. -func MigrateGenState(oldState *types.GenesisState) *types.GenesisState { - newState := *oldState - newState.MigrateSendEnabled() - return &newState -} diff --git a/x/bank/migrations/v4/gen_state_test.go b/x/bank/migrations/v4/gen_state_test.go deleted file mode 100644 index 2f038bd51bc3..000000000000 --- a/x/bank/migrations/v4/gen_state_test.go +++ /dev/null @@ -1,161 +0,0 @@ -package v4_test - -import ( - "testing" - - "github.com/stretchr/testify/assert" - - sdkmath "cosmossdk.io/math" - - sdk "github.com/cosmos/cosmos-sdk/types" - v4 "github.com/cosmos/cosmos-sdk/x/bank/migrations/v4" - "github.com/cosmos/cosmos-sdk/x/bank/types" -) - -func TestMigrateGenState(t *testing.T) { - tests := []struct { - name string - oldState *types.GenesisState - newState *types.GenesisState - }{ - { - name: "Balances supply metadata all unchanged", - oldState: &types.GenesisState{ - Params: types.Params{}, - Balances: []types.Balance{{ - Address: "balance1", - Coins: sdk.Coins{sdk.NewCoin("balance1coin", sdkmath.NewInt(8))}, - }}, - Supply: sdk.Coins{sdk.NewCoin("supplycoin", sdkmath.NewInt(800))}, - DenomMetadata: []types.Metadata{{ - Description: "metadesc", - DenomUnits: nil, - Base: "meta", - Display: "meta", - Name: "foo", - Symbol: "META", - URI: "", - URIHash: "", - }}, - SendEnabled: []types.SendEnabled{}, - }, - newState: &types.GenesisState{ - Params: types.Params{}, - Balances: []types.Balance{{ - Address: "balance1", - Coins: sdk.Coins{sdk.NewCoin("balance1coin", sdkmath.NewInt(8))}, - }}, - Supply: sdk.Coins{sdk.NewCoin("supplycoin", sdkmath.NewInt(800))}, - DenomMetadata: []types.Metadata{{ - Description: "metadesc", - DenomUnits: nil, - Base: "meta", - Display: "meta", - Name: "foo", - Symbol: "META", - URI: "", - URIHash: "", - }}, - SendEnabled: []types.SendEnabled{}, - }, - }, - - { - name: "default send enabled true not changed", - oldState: &types.GenesisState{ - Params: types.Params{DefaultSendEnabled: true}, - }, - newState: &types.GenesisState{ - Params: types.Params{DefaultSendEnabled: true}, - }, - }, - { - name: "default send enabled false not changed", - oldState: &types.GenesisState{ - Params: types.Params{DefaultSendEnabled: false, SendEnabled: []*types.SendEnabled{}}, - }, - newState: &types.GenesisState{ - Params: types.Params{DefaultSendEnabled: false}, - }, - }, - { - name: "send enabled entries moved", - oldState: &types.GenesisState{ - Params: types.Params{ - SendEnabled: []*types.SendEnabled{ - {Denom: "movecointrue", Enabled: true}, - {Denom: "movecoinfalse", Enabled: false}, - }, - }, - }, - newState: &types.GenesisState{ - Params: types.Params{}, - SendEnabled: []types.SendEnabled{ - {Denom: "movecointrue", Enabled: true}, - {Denom: "movecoinfalse", Enabled: false}, - }, - }, - }, - { - name: "params entries added to existing", - oldState: &types.GenesisState{ - Params: types.Params{ - SendEnabled: []*types.SendEnabled{ - {Denom: "movecointrue", Enabled: true}, - {Denom: "movecoinfalse", Enabled: false}, - }, - }, - SendEnabled: []types.SendEnabled{ - {Denom: "staycoin", Enabled: true}, - }, - }, - newState: &types.GenesisState{ - Params: types.Params{}, - SendEnabled: []types.SendEnabled{ - {Denom: "staycoin", Enabled: true}, - {Denom: "movecointrue", Enabled: true}, - {Denom: "movecoinfalse", Enabled: false}, - }, - }, - }, - { - name: "conflicting params ignored", - oldState: &types.GenesisState{ - Params: types.Params{ - SendEnabled: []*types.SendEnabled{ - {Denom: "staycoin", Enabled: false}, - }, - }, - SendEnabled: []types.SendEnabled{ - {Denom: "staycoin", Enabled: true}, - }, - }, - newState: &types.GenesisState{ - Params: types.Params{}, - SendEnabled: []types.SendEnabled{ - {Denom: "staycoin", Enabled: true}, - }, - }, - }, - } - - for _, tc := range tests { - t.Run(tc.name, func(t *testing.T) { - actual := v4.MigrateGenState(tc.oldState) - assert.Equal(t, tc.newState, actual) - }) - } - - t.Run("ensure original not changed", func(t *testing.T) { - origState := types.GenesisState{ - Params: types.Params{ - SendEnabled: []*types.SendEnabled{ - {Denom: "movecointrue", Enabled: true}, - {Denom: "movecoinfalse", Enabled: false}, - }, - }, - } - _ = v4.MigrateGenState(&origState) - assert.Len(t, origState.Params.SendEnabled, 2) - }) -} diff --git a/x/bank/migrations/v4/store.go b/x/bank/migrations/v4/store.go deleted file mode 100644 index 675ff785a65c..000000000000 --- a/x/bank/migrations/v4/store.go +++ /dev/null @@ -1,38 +0,0 @@ -package v4 - -import ( - "cosmossdk.io/core/store" - - "github.com/cosmos/cosmos-sdk/codec" - sdk "github.com/cosmos/cosmos-sdk/types" - "github.com/cosmos/cosmos-sdk/x/bank/exported" - "github.com/cosmos/cosmos-sdk/x/bank/types" -) - -const ModuleName = "bank" - -var ParamsKey = []byte{0x05} - -// MigrateStore migrates the x/bank module state from the consensus version 3 to -// version 4. Specifically, it takes the parameters that are currently stored -// and managed by the x/params module and stores them directly into the x/bank -// module state. -func MigrateStore(ctx sdk.Context, storeService store.KVStoreService, legacySubspace exported.Subspace, cdc codec.BinaryCodec) error { - var currParams types.Params - legacySubspace.GetParamSet(ctx, &currParams) - - // SendEnabled is migrated to the x/bank module store, so delete from the params - currParams = types.NewParams(currParams.DefaultSendEnabled) - - if err := currParams.Validate(); err != nil { - return err - } - - bz, err := cdc.Marshal(&currParams) - if err != nil { - return err - } - - store := storeService.OpenKVStore(ctx) - return store.Set(ParamsKey, bz) -} diff --git a/x/bank/migrations/v4/store_test.go b/x/bank/migrations/v4/store_test.go deleted file mode 100644 index 911a9b0207d0..000000000000 --- a/x/bank/migrations/v4/store_test.go +++ /dev/null @@ -1,53 +0,0 @@ -package v4_test - -import ( - "testing" - - "github.com/stretchr/testify/require" - - storetypes "cosmossdk.io/store/types" - - "github.com/cosmos/cosmos-sdk/runtime" - "github.com/cosmos/cosmos-sdk/testutil" - sdk "github.com/cosmos/cosmos-sdk/types" - moduletestutil "github.com/cosmos/cosmos-sdk/types/module/testutil" - "github.com/cosmos/cosmos-sdk/x/bank" - "github.com/cosmos/cosmos-sdk/x/bank/exported" - v4 "github.com/cosmos/cosmos-sdk/x/bank/migrations/v4" - "github.com/cosmos/cosmos-sdk/x/bank/types" -) - -type mockSubspace struct { - ps types.Params -} - -func newMockSubspace(ps types.Params) mockSubspace { - return mockSubspace{ps: ps} -} - -func (ms mockSubspace) GetParamSet(ctx sdk.Context, ps exported.ParamSet) { - *ps.(*types.Params) = ms.ps -} - -func (ms mockSubspace) Get(ctx sdk.Context, key []byte, ptr any) {} - -func TestMigrate(t *testing.T) { - encCfg := moduletestutil.MakeTestEncodingConfig(bank.AppModuleBasic{}) - cdc := encCfg.Codec - - storeKey := storetypes.NewKVStoreKey(v4.ModuleName) - tKey := storetypes.NewTransientStoreKey("transient_test") - ctx := testutil.DefaultContext(storeKey, tKey) - storeService := runtime.NewKVStoreService(storeKey) - - legacySubspace := newMockSubspace(types.DefaultParams()) - require.NoError(t, v4.MigrateStore(ctx, storeService, legacySubspace, cdc)) - - var res types.Params - - store := storeService.OpenKVStore(ctx) - bz, err := store.Get(v4.ParamsKey) - require.NoError(t, err) - require.NoError(t, cdc.Unmarshal(bz, &res)) - require.Equal(t, legacySubspace.ps, res) -} diff --git a/x/bank/module.go b/x/bank/module.go index b14032e1f6ac..b5805aee8d79 100644 --- a/x/bank/module.go +++ b/x/bank/module.go @@ -27,9 +27,7 @@ import ( simtypes "github.com/cosmos/cosmos-sdk/types/simulation" authtypes "github.com/cosmos/cosmos-sdk/x/auth/types" "github.com/cosmos/cosmos-sdk/x/bank/client/cli" - "github.com/cosmos/cosmos-sdk/x/bank/exported" "github.com/cosmos/cosmos-sdk/x/bank/keeper" - v1bank "github.com/cosmos/cosmos-sdk/x/bank/migrations/v1" "github.com/cosmos/cosmos-sdk/x/bank/simulation" "github.com/cosmos/cosmos-sdk/x/bank/types" govtypes "github.com/cosmos/cosmos-sdk/x/gov/types" @@ -93,9 +91,6 @@ func (ab AppModuleBasic) GetTxCmd() *cobra.Command { // RegisterInterfaces registers interfaces and implementations of the bank module. func (AppModuleBasic) RegisterInterfaces(registry codectypes.InterfaceRegistry) { types.RegisterInterfaces(registry) - - // Register legacy interfaces for migration scripts. - v1bank.RegisterInterfaces(registry) } // AppModule implements an application module for the bank module. @@ -104,9 +99,6 @@ type AppModule struct { keeper keeper.Keeper accountKeeper types.AccountKeeper - - // legacySubspace is used solely for migration of x/params managed parameters - legacySubspace exported.Subspace } // IsOnePerModuleType implements the depinject.OnePerModuleType interface. @@ -119,28 +111,14 @@ func (am AppModule) IsAppModule() {} func (am AppModule) RegisterServices(cfg module.Configurator) { types.RegisterMsgServer(cfg.MsgServer(), keeper.NewMsgServerImpl(am.keeper)) types.RegisterQueryServer(cfg.QueryServer(), am.keeper) - - m := keeper.NewMigrator(am.keeper.(keeper.BaseKeeper), am.legacySubspace) - if err := cfg.RegisterMigration(types.ModuleName, 1, m.Migrate1to2); err != nil { - panic(fmt.Sprintf("failed to migrate x/bank from version 1 to 2: %v", err)) - } - - if err := cfg.RegisterMigration(types.ModuleName, 2, m.Migrate2to3); err != nil { - panic(fmt.Sprintf("failed to migrate x/bank from version 2 to 3: %v", err)) - } - - if err := cfg.RegisterMigration(types.ModuleName, 3, m.Migrate3to4); err != nil { - panic(fmt.Sprintf("failed to migrate x/bank from version 3 to 4: %v", err)) - } } // NewAppModule creates a new AppModule object -func NewAppModule(cdc codec.Codec, keeper keeper.Keeper, accountKeeper types.AccountKeeper, ss exported.Subspace) AppModule { +func NewAppModule(cdc codec.Codec, keeper keeper.Keeper, accountKeeper types.AccountKeeper) AppModule { return AppModule{ AppModuleBasic: AppModuleBasic{cdc: cdc, ac: accountKeeper.AddressCodec()}, keeper: keeper, accountKeeper: accountKeeper, - legacySubspace: ss, } } @@ -226,9 +204,6 @@ type ModuleInputs struct { Logger log.Logger AccountKeeper types.AccountKeeper - - // LegacySubspace is used solely for migration of x/params managed parameters - LegacySubspace exported.Subspace `optional:"true"` } type ModuleOutputs struct { @@ -268,7 +243,7 @@ func ProvideModule(in ModuleInputs) ModuleOutputs { authority.String(), in.Logger, ) - m := NewAppModule(in.Cdc, bankKeeper, in.AccountKeeper, in.LegacySubspace) + m := NewAppModule(in.Cdc, bankKeeper, in.AccountKeeper) return ModuleOutputs{BankKeeper: bankKeeper, Module: m} } diff --git a/x/bank/simulation/genesis.go b/x/bank/simulation/genesis.go index 2d4cb5ef11e7..0af5a67737d4 100644 --- a/x/bank/simulation/genesis.go +++ b/x/bank/simulation/genesis.go @@ -25,6 +25,7 @@ func RandomGenesisSendEnabled(r *rand.Rand, bondDenom string) []types.SendEnable bondEnabled := r.Int63n(100) < 75 rv = append(rv, types.SendEnabled{Denom: bondDenom, Enabled: bondEnabled}) } + // Probabilities: // P(a) = 60.0% = There's SendEnable entry for the bond denom = .600 // P(a)' = 40.0% = There is NOT a SendEnable entry for the bond denom = 1 - P(a) = 1 - .600 = .400 @@ -69,17 +70,14 @@ func RandomGenesisBalances(simState *module.SimulationState) []types.Balance { // RandomizedGenState generates a random GenesisState for bank func RandomizedGenState(simState *module.SimulationState) { - var defaultSendEnabledParam bool - simState.AppParams.GetOrGenerate(string(types.KeyDefaultSendEnabled), &defaultSendEnabledParam, simState.Rand, func(r *rand.Rand) { defaultSendEnabledParam = RandomGenesisDefaultSendEnabledParam(r) }) - sendEnabled := RandomGenesisSendEnabled(simState.Rand, simState.BondDenom) numAccs := int64(len(simState.Accounts)) - totalSupply := simState.InitialStake.Mul(sdkmath.NewInt((numAccs + simState.NumBonded))) + totalSupply := simState.InitialStake.Mul(sdkmath.NewInt(numAccs + simState.NumBonded)) supply := sdk.NewCoins(sdk.NewCoin(simState.BondDenom, totalSupply)) bankGenesis := types.GenesisState{ - Params: types.NewParams(defaultSendEnabledParam), + Params: types.NewParams(true), Balances: RandomGenesisBalances(simState), Supply: supply, SendEnabled: sendEnabled, diff --git a/x/bank/simulation/operations_test.go b/x/bank/simulation/operations_test.go index c531561b845b..3f5d2868998b 100644 --- a/x/bank/simulation/operations_test.go +++ b/x/bank/simulation/operations_test.go @@ -26,7 +26,6 @@ import ( "github.com/cosmos/cosmos-sdk/x/bank/testutil" "github.com/cosmos/cosmos-sdk/x/bank/types" _ "github.com/cosmos/cosmos-sdk/x/consensus" - _ "github.com/cosmos/cosmos-sdk/x/params" _ "github.com/cosmos/cosmos-sdk/x/staking" ) @@ -50,7 +49,6 @@ func (suite *SimTestSuite) SetupTest() { depinject.Configs( configurator.NewAppConfig( configurator.AuthModule(), - configurator.ParamsModule(), configurator.BankModule(), configurator.StakingModule(), configurator.ConsensusModule(), diff --git a/x/bank/types/params.go b/x/bank/types/params.go index 287433857cf1..9f0b5c5da618 100644 --- a/x/bank/types/params.go +++ b/x/bank/types/params.go @@ -2,7 +2,6 @@ package types import ( "errors" - "fmt" sdk "github.com/cosmos/cosmos-sdk/types" ) @@ -31,7 +30,7 @@ func (p Params) Validate() error { if len(p.SendEnabled) > 0 { return errors.New("use of send_enabled in params is no longer supported") } - return validateIsBool(p.DefaultSendEnabled) + return nil } // Validate gets any errors with this SendEnabled entry. @@ -47,12 +46,3 @@ func NewSendEnabled(denom string, sendEnabled bool) *SendEnabled { Enabled: sendEnabled, } } - -// validateIsBool is used by the x/params module to validate that a thing is a bool. -func validateIsBool(i any) error { - _, ok := i.(bool) - if !ok { - return fmt.Errorf("invalid parameter type: %T", i) - } - return nil -} diff --git a/x/bank/types/params_legacy.go b/x/bank/types/params_legacy.go deleted file mode 100644 index cdbac6878811..000000000000 --- a/x/bank/types/params_legacy.go +++ /dev/null @@ -1,68 +0,0 @@ -package types - -import ( - fmt "fmt" - - sdk "github.com/cosmos/cosmos-sdk/types" - "github.com/cosmos/cosmos-sdk/x/bank/exported" - paramtypes "github.com/cosmos/cosmos-sdk/x/params/types" -) - -var ( - // KeySendEnabled is store's key for SendEnabled Params - // - // Deprecated: Use the SendEnabled functionality in the keeper. - KeySendEnabled = []byte("SendEnabled") - // KeyDefaultSendEnabled is store's key for the DefaultSendEnabled option - KeyDefaultSendEnabled = []byte("DefaultSendEnabled") -) - -// Deprecated: ParamKeyTable for bank module. -func ParamKeyTable() paramtypes.KeyTable { - return paramtypes.NewKeyTable().RegisterParamSet(&Params{}) -} - -// Deprecated: ParamSetPairs implements params.ParamSet -func (p *Params) ParamSetPairs() paramtypes.ParamSetPairs { - return paramtypes.ParamSetPairs{ - paramtypes.NewParamSetPair(KeySendEnabled, &p.SendEnabled, validateSendEnabledParams), - paramtypes.NewParamSetPair(KeyDefaultSendEnabled, &p.DefaultSendEnabled, validateIsBool), - } -} - -// SendEnabledParams is a collection of parameters indicating if a coin denom is enabled for sending -type SendEnabledParams []*SendEnabled - -// GetSendEnabledParams retrieves the send enabled parameters from the provided context and legacy subspace. -func GetSendEnabledParams(ctx sdk.Context, legacySubspace exported.Subspace) []*SendEnabled { - var sendEnabled []*SendEnabled - legacySubspace.Get(ctx, KeySendEnabled, &sendEnabled) - return sendEnabled -} - -func validateSendEnabledParams(i any) error { - params, ok := i.([]*SendEnabled) - if !ok { - return fmt.Errorf("invalid parameter type: %T", i) - } - // ensure each denom is only registered one time. - registered := make(map[string]bool) - for _, p := range params { - if _, exists := registered[p.Denom]; exists { - return fmt.Errorf("duplicate send enabled parameter found: '%s'", p.Denom) - } - if err := validateSendEnabled(*p); err != nil { - return err - } - registered[p.Denom] = true - } - return nil -} - -func validateSendEnabled(i any) error { - param, ok := i.(SendEnabled) - if !ok { - return fmt.Errorf("invalid parameter type: %T", i) - } - return sdk.ValidateDenom(param.Denom) -} diff --git a/x/consensus/exported/exported.go b/x/consensus/exported/exported.go index 6c2135f71267..fff5f5b2d98a 100644 --- a/x/consensus/exported/exported.go +++ b/x/consensus/exported/exported.go @@ -4,19 +4,9 @@ import ( "context" cmtproto "github.com/cometbft/cometbft/proto/tendermint/types" - - sdk "github.com/cosmos/cosmos-sdk/types" ) type ( - // ParamStore defines an interface that implements the legacy x/params Subspace - // type. - // - // NOTE: This is used solely for migration of x/params managed parameters. - ParamStore interface { - Get(ctx sdk.Context, key []byte, ptr any) - } - // ConsensusParamSetter defines the interface fulfilled by BaseApp's // ParamStore which allows setting its appVersion field. ConsensusParamSetter interface { diff --git a/x/distribution/exported/exported.go b/x/distribution/exported/exported.go deleted file mode 100644 index 000114e6194d..000000000000 --- a/x/distribution/exported/exported.go +++ /dev/null @@ -1,18 +0,0 @@ -package exported - -import ( - sdk "github.com/cosmos/cosmos-sdk/types" - paramtypes "github.com/cosmos/cosmos-sdk/x/params/types" -) - -type ( - ParamSet = paramtypes.ParamSet - - // Subspace defines an interface that implements the legacy x/params Subspace - // type. - // - // NOTE: This is used solely for migration of x/params managed parameters. - Subspace interface { - GetParamSet(ctx sdk.Context, ps ParamSet) - } -) diff --git a/x/distribution/keeper/migrations.go b/x/distribution/keeper/migrations.go index bfcf8805e39f..92902cbad2b9 100644 --- a/x/distribution/keeper/migrations.go +++ b/x/distribution/keeper/migrations.go @@ -1,32 +1,11 @@ package keeper -import ( - sdk "github.com/cosmos/cosmos-sdk/types" - "github.com/cosmos/cosmos-sdk/x/distribution/exported" - v2 "github.com/cosmos/cosmos-sdk/x/distribution/migrations/v2" - v3 "github.com/cosmos/cosmos-sdk/x/distribution/migrations/v3" -) - // Migrator is a struct for handling in-place store migrations. type Migrator struct { - keeper Keeper - legacySubspace exported.Subspace + keeper Keeper } // NewMigrator returns a new Migrator. -func NewMigrator(keeper Keeper, legacySubspace exported.Subspace) Migrator { - return Migrator{keeper: keeper, legacySubspace: legacySubspace} -} - -// Migrate1to2 migrates from version 1 to 2. -func (m Migrator) Migrate1to2(ctx sdk.Context) error { - return v2.MigrateStore(ctx, m.keeper.storeService) -} - -// Migrate2to3 migrates the x/distribution module state from the consensus -// version 2 to version 3. Specifically, it takes the parameters that are currently stored -// and managed by the x/params module and stores them directly into the x/distribution -// module state. -func (m Migrator) Migrate2to3(ctx sdk.Context) error { - return v3.MigrateStore(ctx, m.keeper.storeService, m.legacySubspace, m.keeper.cdc) +func NewMigrator(keeper Keeper) Migrator { + return Migrator{keeper: keeper} } diff --git a/x/distribution/migrations/v1/types.go b/x/distribution/migrations/v1/types.go deleted file mode 100644 index 1f7c2768f7db..000000000000 --- a/x/distribution/migrations/v1/types.go +++ /dev/null @@ -1,185 +0,0 @@ -package legacy - -import ( - "encoding/binary" - - sdk "github.com/cosmos/cosmos-sdk/types" - "github.com/cosmos/cosmos-sdk/types/kv" - v1auth "github.com/cosmos/cosmos-sdk/x/auth/migrations/v1" -) - -const ( - // ModuleName is the module name constant used in many places - ModuleName = "distribution" - - // StoreKey is the store key string for distribution - StoreKey = ModuleName - - // RouterKey is the message route for distribution - RouterKey = ModuleName - - // QuerierRoute is the querier route for distribution - QuerierRoute = ModuleName -) - -// Keys for distribution store -// Items are stored with the following key: values -// -// - 0x00: FeePol -// -// - 0x01: sdk.ConsAddress -// -// - 0x02: ValidatorOutstandingRewards -// -// - 0x03: sdk.AccAddress -// -// - 0x04: DelegatorStartingInfo -// -// - 0x05: ValidatorHistoricalRewards -// -// - 0x06: ValidatorCurrentRewards -// -// - 0x07: ValidatorCurrentRewards -// -// - 0x08: ValidatorSlashEvent -var ( - FeePoolKey = []byte{0x00} // key for global distribution state - ProposerKey = []byte{0x01} // key for the proposer operator address - ValidatorOutstandingRewardsPrefix = []byte{0x02} // key for outstanding rewards - - DelegatorWithdrawAddrPrefix = []byte{0x03} // key for delegator withdraw address - DelegatorStartingInfoPrefix = []byte{0x04} // key for delegator starting info - ValidatorHistoricalRewardsPrefix = []byte{0x05} // key for historical validators rewards / stake - ValidatorCurrentRewardsPrefix = []byte{0x06} // key for current validator rewards - ValidatorAccumulatedCommissionPrefix = []byte{0x07} // key for accumulated validator commission - ValidatorSlashEventPrefix = []byte{0x08} // key for validator slash fraction -) - -// GetValidatorOutstandingRewardsAddress gets an address from a validator's outstanding rewards key -func GetValidatorOutstandingRewardsAddress(key []byte) (valAddr sdk.ValAddress) { - kv.AssertKeyAtLeastLength(key, 2) - addr := key[1:] - kv.AssertKeyLength(addr, v1auth.AddrLen) - return sdk.ValAddress(addr) -} - -// GetDelegatorWithdrawInfoAddress gets an address from a delegator's withdraw info key -func GetDelegatorWithdrawInfoAddress(key []byte) (delAddr sdk.AccAddress) { - kv.AssertKeyAtLeastLength(key, 2) - addr := key[1:] - kv.AssertKeyLength(addr, v1auth.AddrLen) - return sdk.AccAddress(addr) -} - -// GetDelegatorStartingInfoAddresses gets the addresses from a delegator starting info key -func GetDelegatorStartingInfoAddresses(key []byte) (valAddr sdk.ValAddress, delAddr sdk.AccAddress) { - kv.AssertKeyAtLeastLength(key, 2+v1auth.AddrLen) - addr := key[1 : 1+v1auth.AddrLen] - kv.AssertKeyLength(addr, v1auth.AddrLen) - valAddr = addr - addr = key[1+v1auth.AddrLen:] - kv.AssertKeyLength(addr, v1auth.AddrLen) - delAddr = addr - return valAddr, delAddr -} - -// GetValidatorHistoricalRewardsAddressPeriod gets the address & period from a validator's historical rewards key -func GetValidatorHistoricalRewardsAddressPeriod(key []byte) (valAddr sdk.ValAddress, period uint64) { - kv.AssertKeyAtLeastLength(key, 2+v1auth.AddrLen) - addr := key[1 : 1+v1auth.AddrLen] - kv.AssertKeyLength(addr, v1auth.AddrLen) - valAddr = addr - b := key[1+v1auth.AddrLen:] - kv.AssertKeyLength(addr, 8) - period = binary.LittleEndian.Uint64(b) - return valAddr, period -} - -// GetValidatorCurrentRewardsAddress gets the address from a validator's current rewards key -func GetValidatorCurrentRewardsAddress(key []byte) (valAddr sdk.ValAddress) { - kv.AssertKeyAtLeastLength(key, 2) - addr := key[1:] - kv.AssertKeyLength(addr, v1auth.AddrLen) - return sdk.ValAddress(addr) -} - -// GetValidatorAccumulatedCommissionAddress gets the address from a validator's accumulated commission key -func GetValidatorAccumulatedCommissionAddress(key []byte) (valAddr sdk.ValAddress) { - kv.AssertKeyAtLeastLength(key, 2) - addr := key[1:] - kv.AssertKeyLength(addr, v1auth.AddrLen) - return addr -} - -// GetValidatorSlashEventAddressHeight gets the height from a validator's slash event key -func GetValidatorSlashEventAddressHeight(key []byte) (valAddr sdk.ValAddress, height uint64) { - kv.AssertKeyAtLeastLength(key, 2+v1auth.AddrLen) - addr := key[1 : 1+v1auth.AddrLen] - kv.AssertKeyLength(addr, v1auth.AddrLen) - valAddr = addr - startB := 1 + v1auth.AddrLen - kv.AssertKeyAtLeastLength(key, startB+9) - b := key[startB : startB+8] // the next 8 bytes represent the height - height = binary.BigEndian.Uint64(b) - return valAddr, height -} - -// GetValidatorOutstandingRewardsKey gets the outstanding rewards key for a validator -func GetValidatorOutstandingRewardsKey(valAddr sdk.ValAddress) []byte { - return append(ValidatorOutstandingRewardsPrefix, valAddr.Bytes()...) -} - -// GetDelegatorWithdrawAddrKey gets the key for a delegator's withdraw addr -func GetDelegatorWithdrawAddrKey(delAddr sdk.AccAddress) []byte { - return append(DelegatorWithdrawAddrPrefix, delAddr.Bytes()...) -} - -// GetDelegatorStartingInfoKey gets the key for a delegator's starting info -func GetDelegatorStartingInfoKey(v sdk.ValAddress, d sdk.AccAddress) []byte { - return append(append(DelegatorStartingInfoPrefix, v.Bytes()...), d.Bytes()...) -} - -// GetValidatorHistoricalRewardsPrefix gets the prefix key for a validator's historical rewards -func GetValidatorHistoricalRewardsPrefix(v sdk.ValAddress) []byte { - return append(ValidatorHistoricalRewardsPrefix, v.Bytes()...) -} - -// GetValidatorHistoricalRewardsKey gets the key for a validator's historical rewards -func GetValidatorHistoricalRewardsKey(v sdk.ValAddress, k uint64) []byte { - b := make([]byte, 8) - binary.LittleEndian.PutUint64(b, k) - return append(append(ValidatorHistoricalRewardsPrefix, v.Bytes()...), b...) -} - -// GetValidatorCurrentRewardsKey gets the key for a validator's current rewards -func GetValidatorCurrentRewardsKey(v sdk.ValAddress) []byte { - return append(ValidatorCurrentRewardsPrefix, v.Bytes()...) -} - -// GetValidatorAccumulatedCommissionKey gets the key for a validator's current commission -func GetValidatorAccumulatedCommissionKey(v sdk.ValAddress) []byte { - return append(ValidatorAccumulatedCommissionPrefix, v.Bytes()...) -} - -// GetValidatorSlashEventPrefix gets the prefix key for a validator's slash fractions -func GetValidatorSlashEventPrefix(v sdk.ValAddress) []byte { - return append(ValidatorSlashEventPrefix, v.Bytes()...) -} - -// GetValidatorSlashEventKeyPrefix gets the prefix key for a validator's slash fraction (ValidatorSlashEventPrefix + height) -func GetValidatorSlashEventKeyPrefix(v sdk.ValAddress, height uint64) []byte { - heightBz := make([]byte, 8) - binary.BigEndian.PutUint64(heightBz, height) - return append( - ValidatorSlashEventPrefix, - append(v.Bytes(), heightBz...)..., - ) -} - -// GetValidatorSlashEventKey gets the key for a validator's slash fraction -func GetValidatorSlashEventKey(v sdk.ValAddress, height, period uint64) []byte { - periodBz := make([]byte, 8) - binary.BigEndian.PutUint64(periodBz, period) - prefix := GetValidatorSlashEventKeyPrefix(v, height) - return append(prefix, periodBz...) -} diff --git a/x/distribution/migrations/v2/helpers.go b/x/distribution/migrations/v2/helpers.go deleted file mode 100644 index ed50c04a5f0a..000000000000 --- a/x/distribution/migrations/v2/helpers.go +++ /dev/null @@ -1,72 +0,0 @@ -package v2 - -import ( - "cosmossdk.io/store/prefix" - storetypes "cosmossdk.io/store/types" - - "github.com/cosmos/cosmos-sdk/types/address" - v1auth "github.com/cosmos/cosmos-sdk/x/auth/migrations/v1" -) - -// MigratePrefixAddress is a helper function that migrates all keys of format: -// prefix_bytes | address_bytes -// into format: -// prefix_bytes | address_len (1 byte) | address_bytes -func MigratePrefixAddress(store storetypes.KVStore, prefixBz []byte) { - oldStore := prefix.NewStore(store, prefixBz) - - oldStoreIter := oldStore.Iterator(nil, nil) - defer oldStoreIter.Close() - - for ; oldStoreIter.Valid(); oldStoreIter.Next() { - addr := oldStoreIter.Key() - newStoreKey := prefixBz - newStoreKey = append(newStoreKey, address.MustLengthPrefix(addr)...) - - // Set new key on store. Values don't change. - store.Set(newStoreKey, oldStoreIter.Value()) - oldStore.Delete(oldStoreIter.Key()) - } -} - -// MigratePrefixAddressBytes is a helper function that migrates all keys of format: -// prefix_bytes | address_bytes | arbitrary_bytes -// into format: -// prefix_bytes | address_len (1 byte) | address_bytes | arbitrary_bytes -func MigratePrefixAddressBytes(store storetypes.KVStore, prefixBz []byte) { - oldStore := prefix.NewStore(store, prefixBz) - - oldStoreIter := oldStore.Iterator(nil, nil) - defer oldStoreIter.Close() - - for ; oldStoreIter.Valid(); oldStoreIter.Next() { - addr := oldStoreIter.Key()[:v1auth.AddrLen] - endBz := oldStoreIter.Key()[v1auth.AddrLen:] - newStoreKey := append(append(prefixBz, address.MustLengthPrefix(addr)...), endBz...) - - // Set new key on store. Values don't change. - store.Set(newStoreKey, oldStoreIter.Value()) - oldStore.Delete(oldStoreIter.Key()) - } -} - -// MigratePrefixAddressAddress is a helper function that migrates all keys of format: -// prefix_bytes | address_1_bytes | address_2_bytes -// into format: -// prefix_bytes | address_1_len (1 byte) | address_1_bytes | address_2_len (1 byte) | address_2_bytes -func MigratePrefixAddressAddress(store storetypes.KVStore, prefixBz []byte) { - oldStore := prefix.NewStore(store, prefixBz) - - oldStoreIter := oldStore.Iterator(nil, nil) - defer oldStoreIter.Close() - - for ; oldStoreIter.Valid(); oldStoreIter.Next() { - addr1 := oldStoreIter.Key()[:v1auth.AddrLen] - addr2 := oldStoreIter.Key()[v1auth.AddrLen:] - newStoreKey := append(append(prefixBz, address.MustLengthPrefix(addr1)...), address.MustLengthPrefix(addr2)...) - - // Set new key on store. Values don't change. - store.Set(newStoreKey, oldStoreIter.Value()) - oldStore.Delete(oldStoreIter.Key()) - } -} diff --git a/x/distribution/migrations/v2/store.go b/x/distribution/migrations/v2/store.go deleted file mode 100644 index fe6aea2a5a30..000000000000 --- a/x/distribution/migrations/v2/store.go +++ /dev/null @@ -1,26 +0,0 @@ -package v2 - -import ( - "cosmossdk.io/core/store" - - "github.com/cosmos/cosmos-sdk/runtime" - sdk "github.com/cosmos/cosmos-sdk/types" - v1 "github.com/cosmos/cosmos-sdk/x/distribution/migrations/v1" -) - -// MigrateStore performs in-place store migrations from v0.40 to v0.43. The -// migration includes: -// -// - Change addresses to be length-prefixed. -func MigrateStore(ctx sdk.Context, storeService store.KVStoreService) error { - store := runtime.KVStoreAdapter(storeService.OpenKVStore(ctx)) - MigratePrefixAddress(store, v1.ValidatorOutstandingRewardsPrefix) - MigratePrefixAddress(store, v1.DelegatorWithdrawAddrPrefix) - MigratePrefixAddressAddress(store, v1.DelegatorStartingInfoPrefix) - MigratePrefixAddressBytes(store, v1.ValidatorHistoricalRewardsPrefix) - MigratePrefixAddress(store, v1.ValidatorCurrentRewardsPrefix) - MigratePrefixAddress(store, v1.ValidatorAccumulatedCommissionPrefix) - MigratePrefixAddressBytes(store, v1.ValidatorSlashEventPrefix) - - return nil -} diff --git a/x/distribution/migrations/v2/store_test.go b/x/distribution/migrations/v2/store_test.go deleted file mode 100644 index a9bc679f987f..000000000000 --- a/x/distribution/migrations/v2/store_test.go +++ /dev/null @@ -1,102 +0,0 @@ -package v2_test - -import ( - "bytes" - "testing" - - "github.com/stretchr/testify/require" - - storetypes "cosmossdk.io/store/types" - - "github.com/cosmos/cosmos-sdk/runtime" - "github.com/cosmos/cosmos-sdk/testutil" - "github.com/cosmos/cosmos-sdk/testutil/testdata" - sdk "github.com/cosmos/cosmos-sdk/types" - v1 "github.com/cosmos/cosmos-sdk/x/distribution/migrations/v1" - v2 "github.com/cosmos/cosmos-sdk/x/distribution/migrations/v2" - "github.com/cosmos/cosmos-sdk/x/distribution/types" -) - -func TestStoreMigration(t *testing.T) { - distributionKey := storetypes.NewKVStoreKey("distribution") - storeService := runtime.NewKVStoreService(distributionKey) - ctx := testutil.DefaultContext(distributionKey, storetypes.NewTransientStoreKey("transient_test")) - store := ctx.KVStore(distributionKey) - - _, _, addr1 := testdata.KeyTestPubAddr() - valAddr := sdk.ValAddress(addr1) - _, _, addr2 := testdata.KeyTestPubAddr() - // Use dummy value for all keys. - value := []byte("foo") - - testCases := []struct { - name string - oldKey []byte - newKey []byte - }{ - { - "FeePoolKey", - v1.FeePoolKey, - types.FeePoolKey, - }, - { - "ProposerKey", - v1.ProposerKey, - types.ProposerKey, - }, - { - "ValidatorOutstandingRewards", - v1.GetValidatorOutstandingRewardsKey(valAddr), - types.GetValidatorOutstandingRewardsKey(valAddr), - }, - { - "DelegatorWithdrawAddr", - v1.GetDelegatorWithdrawAddrKey(addr2), - types.GetDelegatorWithdrawAddrKey(addr2), - }, - { - "DelegatorStartingInfo", - v1.GetDelegatorStartingInfoKey(valAddr, addr2), - types.GetDelegatorStartingInfoKey(valAddr, addr2), - }, - { - "ValidatorHistoricalRewards", - v1.GetValidatorHistoricalRewardsKey(valAddr, 6), - types.GetValidatorHistoricalRewardsKey(valAddr, 6), - }, - { - "ValidatorCurrentRewards", - v1.GetValidatorCurrentRewardsKey(valAddr), - types.GetValidatorCurrentRewardsKey(valAddr), - }, - { - "ValidatorAccumulatedCommission", - v1.GetValidatorAccumulatedCommissionKey(valAddr), - types.GetValidatorAccumulatedCommissionKey(valAddr), - }, - { - "ValidatorSlashEvent", - v1.GetValidatorSlashEventKey(valAddr, 6, 8), - types.GetValidatorSlashEventKey(valAddr, 6, 8), - }, - } - - // Set all the old keys to the store - for _, tc := range testCases { - store.Set(tc.oldKey, value) - } - - // Run migrations. - err := v2.MigrateStore(ctx, storeService) - require.NoError(t, err) - - // Make sure the new keys are set and old keys are deleted. - for _, tc := range testCases { - t.Run(tc.name, func(t *testing.T) { - if !bytes.Equal(tc.oldKey, tc.newKey) { - require.Nil(t, store.Get(tc.oldKey)) - } - require.Equal(t, value, store.Get(tc.newKey)) - }) - } -} diff --git a/x/distribution/migrations/v3/json.go b/x/distribution/migrations/v3/json.go deleted file mode 100644 index e384b4869307..000000000000 --- a/x/distribution/migrations/v3/json.go +++ /dev/null @@ -1,19 +0,0 @@ -package v3 - -import ( - sdkmath "cosmossdk.io/math" - - "github.com/cosmos/cosmos-sdk/x/distribution/types" -) - -// MigrateJSON accepts exported v2 (v0.46) x/distribution genesis state and migrates it to -// v3 (v0.47) x/distribution genesis state. The migration includes: -// -// Reset of the deprecated rewards to zero. -func MigrateJSON(oldState *types.GenesisState) *types.GenesisState { - // reset deprecated rewards to zero - oldState.Params.BaseProposerReward = sdkmath.LegacyZeroDec() - oldState.Params.BonusProposerReward = sdkmath.LegacyZeroDec() - - return oldState -} diff --git a/x/distribution/migrations/v3/json_test.go b/x/distribution/migrations/v3/json_test.go deleted file mode 100644 index 399b26f8d70a..000000000000 --- a/x/distribution/migrations/v3/json_test.go +++ /dev/null @@ -1,65 +0,0 @@ -package v3_test - -import ( - "encoding/json" - "testing" - - "github.com/stretchr/testify/require" - - sdkmath "cosmossdk.io/math" - - "github.com/cosmos/cosmos-sdk/client" - moduletestutil "github.com/cosmos/cosmos-sdk/types/module/testutil" - "github.com/cosmos/cosmos-sdk/x/distribution" - v3 "github.com/cosmos/cosmos-sdk/x/distribution/migrations/v3" - "github.com/cosmos/cosmos-sdk/x/distribution/types" -) - -func TestMigrateJSON(t *testing.T) { - encodingConfig := moduletestutil.MakeTestEncodingConfig(distribution.AppModuleBasic{}) - clientCtx := client.Context{}. - WithInterfaceRegistry(encodingConfig.InterfaceRegistry). - WithTxConfig(encodingConfig.TxConfig). - WithCodec(encodingConfig.Codec) - - distrGenState := types.DefaultGenesisState() - - oldDistrState := distrGenState - oldDistrState.Params.BaseProposerReward = sdkmath.LegacyNewDecWithPrec(1, 2) - oldDistrState.Params.BonusProposerReward = sdkmath.LegacyNewDecWithPrec(4, 2) - - migrated := v3.MigrateJSON(oldDistrState) - require.Equal(t, migrated, distrGenState) - - bz, err := clientCtx.Codec.MarshalJSON(migrated) - require.NoError(t, err) - - // Indent the JSON bz correctly. - var jsonObj map[string]any - err = json.Unmarshal(bz, &jsonObj) - require.NoError(t, err) - indentedBz, err := json.MarshalIndent(jsonObj, "", "\t") - require.NoError(t, err) - - expected := `{ - "delegator_starting_infos": [], - "delegator_withdraw_infos": [], - "fee_pool": { - "community_pool": [] - }, - "outstanding_rewards": [], - "params": { - "base_proposer_reward": "0.000000000000000000", - "bonus_proposer_reward": "0.000000000000000000", - "community_tax": "0.020000000000000000", - "withdraw_addr_enabled": true - }, - "previous_proposer": "", - "validator_accumulated_commissions": [], - "validator_current_rewards": [], - "validator_historical_rewards": [], - "validator_slash_events": [] -}` - - require.Equal(t, expected, string(indentedBz)) -} diff --git a/x/distribution/migrations/v3/migrate.go b/x/distribution/migrations/v3/migrate.go deleted file mode 100644 index 5f59b59566b8..000000000000 --- a/x/distribution/migrations/v3/migrate.go +++ /dev/null @@ -1,42 +0,0 @@ -package v3 - -import ( - "cosmossdk.io/core/store" - sdkmath "cosmossdk.io/math" - - "github.com/cosmos/cosmos-sdk/codec" - sdk "github.com/cosmos/cosmos-sdk/types" - "github.com/cosmos/cosmos-sdk/x/distribution/exported" - "github.com/cosmos/cosmos-sdk/x/distribution/types" -) - -const ( - ModuleName = "distribution" -) - -var ParamsKey = []byte{0x09} - -// MigrateStore migrates the x/distribution module state from the consensus version 2 to -// version 3. Specifically, it takes the parameters that are currently stored -// and managed by the x/params module and stores them directly into the x/distribution -// module state. -func MigrateStore(ctx sdk.Context, storeService store.KVStoreService, legacySubspace exported.Subspace, cdc codec.BinaryCodec) error { - store := storeService.OpenKVStore(ctx) - var currParams types.Params - legacySubspace.GetParamSet(ctx, &currParams) - - // reset unused params - currParams.BaseProposerReward = sdkmath.LegacyZeroDec() - currParams.BonusProposerReward = sdkmath.LegacyZeroDec() - - if err := currParams.ValidateBasic(); err != nil { - return err - } - - bz, err := cdc.Marshal(&currParams) - if err != nil { - return err - } - - return store.Set(ParamsKey, bz) -} diff --git a/x/distribution/migrations/v3/migrate_test.go b/x/distribution/migrations/v3/migrate_test.go deleted file mode 100644 index 495f69270f4f..000000000000 --- a/x/distribution/migrations/v3/migrate_test.go +++ /dev/null @@ -1,47 +0,0 @@ -package v3_test - -import ( - "testing" - - "github.com/stretchr/testify/require" - - storetypes "cosmossdk.io/store/types" - - "github.com/cosmos/cosmos-sdk/runtime" - "github.com/cosmos/cosmos-sdk/testutil" - sdk "github.com/cosmos/cosmos-sdk/types" - moduletestutil "github.com/cosmos/cosmos-sdk/types/module/testutil" - "github.com/cosmos/cosmos-sdk/x/distribution" - "github.com/cosmos/cosmos-sdk/x/distribution/exported" - v3 "github.com/cosmos/cosmos-sdk/x/distribution/migrations/v3" - "github.com/cosmos/cosmos-sdk/x/distribution/types" -) - -type mockSubspace struct { - ps types.Params -} - -func newMockSubspace(ps types.Params) mockSubspace { - return mockSubspace{ps: ps} -} - -func (ms mockSubspace) GetParamSet(ctx sdk.Context, ps exported.ParamSet) { - *ps.(*types.Params) = ms.ps -} - -func TestMigrate(t *testing.T) { - cdc := moduletestutil.MakeTestEncodingConfig(distribution.AppModuleBasic{}).Codec - storeKey := storetypes.NewKVStoreKey(v3.ModuleName) - storeService := runtime.NewKVStoreService(storeKey) - tKey := storetypes.NewTransientStoreKey("transient_test") - ctx := testutil.DefaultContext(storeKey, tKey) - store := ctx.KVStore(storeKey) - - legacySubspace := newMockSubspace(types.DefaultParams()) - require.NoError(t, v3.MigrateStore(ctx, storeService, legacySubspace, cdc)) - - var res types.Params - bz := store.Get(v3.ParamsKey) - require.NoError(t, cdc.Unmarshal(bz, &res)) - require.Equal(t, legacySubspace.ps, res) -} diff --git a/x/distribution/module.go b/x/distribution/module.go index fe7afb48c8a5..8984bd128593 100644 --- a/x/distribution/module.go +++ b/x/distribution/module.go @@ -23,7 +23,6 @@ import ( simtypes "github.com/cosmos/cosmos-sdk/types/simulation" authtypes "github.com/cosmos/cosmos-sdk/x/auth/types" "github.com/cosmos/cosmos-sdk/x/distribution/client/cli" - "github.com/cosmos/cosmos-sdk/x/distribution/exported" "github.com/cosmos/cosmos-sdk/x/distribution/keeper" "github.com/cosmos/cosmos-sdk/x/distribution/simulation" "github.com/cosmos/cosmos-sdk/x/distribution/types" @@ -101,15 +100,12 @@ type AppModule struct { accountKeeper types.AccountKeeper bankKeeper types.BankKeeper stakingKeeper types.StakingKeeper - - // legacySubspace is used solely for migration of x/params managed parameters - legacySubspace exported.Subspace } // NewAppModule creates a new AppModule object func NewAppModule( cdc codec.Codec, keeper keeper.Keeper, accountKeeper types.AccountKeeper, - bankKeeper types.BankKeeper, stakingKeeper types.StakingKeeper, ss exported.Subspace, + bankKeeper types.BankKeeper, stakingKeeper types.StakingKeeper, ) AppModule { return AppModule{ AppModuleBasic: AppModuleBasic{cdc: cdc, ac: accountKeeper.AddressCodec()}, @@ -117,7 +113,6 @@ func NewAppModule( accountKeeper: accountKeeper, bankKeeper: bankKeeper, stakingKeeper: stakingKeeper, - legacySubspace: ss, } } @@ -132,14 +127,7 @@ func (am AppModule) RegisterServices(cfg module.Configurator) { types.RegisterMsgServer(cfg.MsgServer(), keeper.NewMsgServerImpl(am.keeper)) types.RegisterQueryServer(cfg.QueryServer(), keeper.NewQuerier(am.keeper)) - m := keeper.NewMigrator(am.keeper, am.legacySubspace) - if err := cfg.RegisterMigration(types.ModuleName, 1, m.Migrate1to2); err != nil { - panic(fmt.Sprintf("failed to migrate x/%s from version 1 to 2: %v", types.ModuleName, err)) - } - - if err := cfg.RegisterMigration(types.ModuleName, 2, m.Migrate2to3); err != nil { - panic(fmt.Sprintf("failed to migrate x/%s from version 2 to 3: %v", types.ModuleName, err)) - } + _ = keeper.NewMigrator(am.keeper) } // InitGenesis performs genesis initialization for the distribution module. It returns @@ -226,9 +214,6 @@ type ModuleInputs struct { BankKeeper types.BankKeeper StakingKeeper types.StakingKeeper ExternalPoolKeeper types.ExternalCommunityPoolKeeper `optional:"true"` - - // LegacySubspace is used solely for migration of x/params managed parameters - LegacySubspace exported.Subspace `optional:"true"` } type ModuleOutputs struct { @@ -267,7 +252,7 @@ func ProvideModule(in ModuleInputs) ModuleOutputs { opts..., ) - m := NewAppModule(in.Cdc, k, in.AccountKeeper, in.BankKeeper, in.StakingKeeper, in.LegacySubspace) + m := NewAppModule(in.Cdc, k, in.AccountKeeper, in.BankKeeper, in.StakingKeeper) return ModuleOutputs{ DistrKeeper: k, diff --git a/x/distribution/testutil/app_config.go b/x/distribution/testutil/app_config.go index c824f4dff45c..9bbf0910daa3 100644 --- a/x/distribution/testutil/app_config.go +++ b/x/distribution/testutil/app_config.go @@ -9,7 +9,6 @@ import ( _ "github.com/cosmos/cosmos-sdk/x/distribution" // import as blank for app wiring _ "github.com/cosmos/cosmos-sdk/x/genutil" // import as blank for app wiring _ "github.com/cosmos/cosmos-sdk/x/mint" // import as blank for app wiring - _ "github.com/cosmos/cosmos-sdk/x/params" // import as blank for app wiring _ "github.com/cosmos/cosmos-sdk/x/staking" // import as blank for app wiring ) @@ -19,7 +18,6 @@ var AppConfig = configurator.NewAppConfig( configurator.StakingModule(), configurator.TxModule(), configurator.ConsensusModule(), - configurator.ParamsModule(), configurator.GenutilModule(), configurator.DistributionModule(), configurator.MintModule(), diff --git a/x/distribution/types/params.go b/x/distribution/types/params.go index cbeab9165163..3111adcc3585 100644 --- a/x/distribution/types/params.go +++ b/x/distribution/types/params.go @@ -21,29 +21,15 @@ func (p Params) ValidateBasic() error { return validateCommunityTax(p.CommunityTax) } -func validateCommunityTax(i any) error { - v, ok := i.(math.LegacyDec) - if !ok { - return fmt.Errorf("invalid parameter type: %T", i) - } - - if v.IsNil() { +func validateCommunityTax(tax math.LegacyDec) error { + if tax.IsNil() { return fmt.Errorf("community tax must be not nil") } - if v.IsNegative() { - return fmt.Errorf("community tax must be positive: %s", v) + if tax.IsNegative() { + return fmt.Errorf("community tax must be positive: %s", tax) } - if v.GT(math.LegacyOneDec()) { - return fmt.Errorf("community tax too large: %s", v) - } - - return nil -} - -func validateWithdrawAddrEnabled(i any) error { - _, ok := i.(bool) - if !ok { - return fmt.Errorf("invalid parameter type: %T", i) + if tax.GT(math.LegacyOneDec()) { + return fmt.Errorf("community tax too large: %s", tax) } return nil diff --git a/x/distribution/types/params_internal_test.go b/x/distribution/types/params_internal_test.go index 6f03705cb6f3..e1cd11eb8012 100644 --- a/x/distribution/types/params_internal_test.go +++ b/x/distribution/types/params_internal_test.go @@ -9,23 +9,19 @@ import ( ) func Test_validateAuxFuncs(t *testing.T) { - type args struct { - i any - } tests := []struct { name string - args args + tax math.LegacyDec wantErr bool }{ - {"wrong type", args{10.5}, true}, - {"empty math.LegacyDec", args{math.LegacyDec{}}, true}, - {"negative", args{math.LegacyNewDec(-1)}, true}, - {"one dec", args{math.LegacyNewDec(1)}, false}, - {"two dec", args{math.LegacyNewDec(2)}, true}, + {"empty math.LegacyDec", math.LegacyDec{}, true}, + {"negative", math.LegacyNewDec(-1), true}, + {"one dec", math.LegacyNewDec(1), false}, + {"two dec", math.LegacyNewDec(2), true}, } for _, tt := range tests { t.Run(tt.name, func(t *testing.T) { - require.Equal(t, tt.wantErr, validateCommunityTax(tt.args.i) != nil) + require.Equal(t, tt.wantErr, validateCommunityTax(tt.tax) != nil) }) } } diff --git a/x/distribution/types/params_legacy.go b/x/distribution/types/params_legacy.go deleted file mode 100644 index 4805e8bd8c8c..000000000000 --- a/x/distribution/types/params_legacy.go +++ /dev/null @@ -1,22 +0,0 @@ -package types - -import paramtypes "github.com/cosmos/cosmos-sdk/x/params/types" - -// Parameter keys -var ( - ParamStoreKeyCommunityTax = []byte("communitytax") - ParamStoreKeyWithdrawAddrEnabled = []byte("withdrawaddrenabled") -) - -// Deprecated: ParamKeyTable returns the parameter key table. -func ParamKeyTable() paramtypes.KeyTable { - return paramtypes.NewKeyTable().RegisterParamSet(&Params{}) -} - -// Deprecated: ParamSetPairs returns the parameter set pairs. -func (p *Params) ParamSetPairs() paramtypes.ParamSetPairs { - return paramtypes.ParamSetPairs{ - paramtypes.NewParamSetPair(ParamStoreKeyCommunityTax, &p.CommunityTax, validateCommunityTax), - paramtypes.NewParamSetPair(ParamStoreKeyWithdrawAddrEnabled, &p.WithdrawAddrEnabled, validateWithdrawAddrEnabled), - } -} diff --git a/x/evidence/testutil/app_config.go b/x/evidence/testutil/app_config.go index 872535831193..d337b2016b66 100644 --- a/x/evidence/testutil/app_config.go +++ b/x/evidence/testutil/app_config.go @@ -8,7 +8,6 @@ import ( _ "github.com/cosmos/cosmos-sdk/x/consensus" // import as blank for app wiring _ "github.com/cosmos/cosmos-sdk/x/evidence" // import as blank for app wiring _ "github.com/cosmos/cosmos-sdk/x/genutil" // import as blank for app wiring - _ "github.com/cosmos/cosmos-sdk/x/params" // import as blank for app wiring _ "github.com/cosmos/cosmos-sdk/x/slashing" // import as blank for app wiring _ "github.com/cosmos/cosmos-sdk/x/staking" // import as blank for app wiring ) @@ -20,7 +19,6 @@ var AppConfig = configurator.NewAppConfig( configurator.SlashingModule(), configurator.TxModule(), configurator.ConsensusModule(), - configurator.ParamsModule(), configurator.EvidenceModule(), configurator.GenutilModule(), ) diff --git a/x/feegrant/simulation/operations_test.go b/x/feegrant/simulation/operations_test.go index 22b1a83c50f5..1db5a46d0ef2 100644 --- a/x/feegrant/simulation/operations_test.go +++ b/x/feegrant/simulation/operations_test.go @@ -35,7 +35,6 @@ import ( "github.com/cosmos/cosmos-sdk/x/feegrant/simulation" _ "github.com/cosmos/cosmos-sdk/x/genutil" _ "github.com/cosmos/cosmos-sdk/x/mint" - _ "github.com/cosmos/cosmos-sdk/x/params" _ "github.com/cosmos/cosmos-sdk/x/staking" ) @@ -63,7 +62,6 @@ func (suite *SimTestSuite) SetupTest() { configurator.StakingModule(), configurator.TxModule(), configurator.ConsensusModule(), - configurator.ParamsModule(), configurator.GenutilModule(), configurator.FeegrantModule(), ), diff --git a/x/genutil/client/cli/commands.go b/x/genutil/client/cli/commands.go index 690afd8ec29b..f9709179c210 100644 --- a/x/genutil/client/cli/commands.go +++ b/x/genutil/client/cli/commands.go @@ -19,12 +19,12 @@ func GenesisCoreCommand(txConfig client.TxConfig, moduleBasics module.BasicManag // Commands adds core sdk's sub-commands into genesis command. func Commands(txConfig client.TxConfig, moduleBasics module.BasicManager, defaultNodeHome string) *cobra.Command { - return CommandsWithCustomMigrationMap(txConfig, moduleBasics, defaultNodeHome, MigrationMap) + return CommandsWithCustomMigrationMap(txConfig, moduleBasics, defaultNodeHome) } // CommandsWithCustomMigrationMap adds core sdk's sub-commands into genesis command with custom migration map. // This custom migration map can be used by the application to add its own migration map. -func CommandsWithCustomMigrationMap(txConfig client.TxConfig, moduleBasics module.BasicManager, defaultNodeHome string, migrationMap genutiltypes.MigrationMap) *cobra.Command { +func CommandsWithCustomMigrationMap(txConfig client.TxConfig, moduleBasics module.BasicManager, defaultNodeHome string) *cobra.Command { cmd := &cobra.Command{ Use: "genesis", Short: "Application's genesis-related subcommands", @@ -36,7 +36,6 @@ func CommandsWithCustomMigrationMap(txConfig client.TxConfig, moduleBasics modul cmd.AddCommand( GenTxCmd(moduleBasics, txConfig, banktypes.GenesisBalancesIterator{}, defaultNodeHome, txConfig.SigningContext().ValidatorAddressCodec()), - MigrateGenesisCmd(migrationMap), CollectGenTxsCmd(banktypes.GenesisBalancesIterator{}, defaultNodeHome, gentxModule.GenTxValidator, txConfig.SigningContext().ValidatorAddressCodec()), ValidateGenesisCmd(moduleBasics), AddGenesisAccountCmd(defaultNodeHome, txConfig.SigningContext().AddressCodec()), diff --git a/x/genutil/client/cli/migrate.go b/x/genutil/client/cli/migrate.go deleted file mode 100644 index b9427681e064..000000000000 --- a/x/genutil/client/cli/migrate.go +++ /dev/null @@ -1,131 +0,0 @@ -package cli - -import ( - "encoding/json" - "fmt" - "maps" - "slices" - "strings" - "time" - - "github.com/spf13/cobra" - - "github.com/cosmos/cosmos-sdk/client" - "github.com/cosmos/cosmos-sdk/client/flags" - "github.com/cosmos/cosmos-sdk/version" - v043 "github.com/cosmos/cosmos-sdk/x/genutil/migrations/v043" - v046 "github.com/cosmos/cosmos-sdk/x/genutil/migrations/v046" - v047 "github.com/cosmos/cosmos-sdk/x/genutil/migrations/v047" - "github.com/cosmos/cosmos-sdk/x/genutil/types" -) - -const flagGenesisTime = "genesis-time" - -// MigrationMap is a map of SDK versions to their respective genesis migration functions. -var MigrationMap = types.MigrationMap{ - "v0.43": v043.Migrate, // NOTE: v0.43, v0.44 and v0.45 are genesis compatible. - "v0.46": v046.Migrate, - "v0.47": v047.Migrate, -} - -// MigrateGenesisCmd returns a command to execute genesis state migration. -// Applications should pass their own migration map to this function. -// When the application migration includes a SDK migration, the Cosmos SDK migration function should as well be called. -func MigrateGenesisCmd(migrations types.MigrationMap) *cobra.Command { - cmd := &cobra.Command{ - Use: "migrate [target-version] [genesis-file]", - Short: "Migrate genesis to a specified target version", - Long: "Migrate the source genesis into the target version and print to STDOUT", - Example: fmt.Sprintf("%s genesis migrate v0.47 /path/to/genesis.json --chain-id=cosmoshub-3 --genesis-time=2019-04-22T17:00:00Z", version.AppName), - Args: cobra.ExactArgs(2), - RunE: func(cmd *cobra.Command, args []string) error { - return MigrateHandler(cmd, args, migrations) - }, - } - - cmd.Flags().String(flagGenesisTime, "", "Override genesis_time with this flag") - cmd.Flags().String(flags.FlagChainID, "", "Override chain_id with this flag") - cmd.Flags().String(flags.FlagOutputDocument, "", "Exported state is written to the given file instead of STDOUT") - - return cmd -} - -// MigrateHandler handles the migration command with a migration map as input, -// returning an error upon failure. -func MigrateHandler(cmd *cobra.Command, args []string, migrations types.MigrationMap) error { - clientCtx := client.GetClientContextFromCmd(cmd) - - target := args[0] - migrationFunc, ok := migrations[target] - if !ok || migrationFunc == nil { - versions := slices.Sorted(maps.Keys(migrations)) - return fmt.Errorf("unknown migration function for version: %s (supported versions %s)", target, strings.Join(versions, ", ")) - } - - importGenesis := args[1] - appGenesis, err := types.AppGenesisFromFile(importGenesis) - if err != nil { - return err - } - - if err := appGenesis.ValidateAndComplete(); err != nil { - return fmt.Errorf("make sure that you have correctly migrated all CometBFT consensus params. Refer the UPGRADING.md (%s): %w", chainUpgradeGuide, err) - } - - // Since some default values are valid values, we just print to - // make sure the user didn't forget to update these values. - if appGenesis.Consensus.Params.Evidence.MaxBytes == 0 { - fmt.Printf("Warning: consensus.params.evidence.max_bytes is set to 0. If this is"+ - " deliberate, feel free to ignore this warning. If not, please have a look at the chain"+ - " upgrade guide at %s.\n", chainUpgradeGuide) - } - - var initialState types.AppMap - if err := json.Unmarshal(appGenesis.AppState, &initialState); err != nil { - return fmt.Errorf("failed to JSON unmarshal initial genesis state: %w", err) - } - - newGenState, err := migrationFunc(initialState, clientCtx) - if err != nil { - return fmt.Errorf("failed to migrate genesis state: %w", err) - } - - appGenesis.AppState, err = json.Marshal(newGenState) - if err != nil { - return fmt.Errorf("failed to JSON marshal migrated genesis state: %w", err) - } - - genesisTime, _ := cmd.Flags().GetString(flagGenesisTime) - if genesisTime != "" { - var t time.Time - - err := t.UnmarshalText([]byte(genesisTime)) - if err != nil { - return fmt.Errorf("failed to unmarshal genesis time: %w", err) - } - - appGenesis.GenesisTime = t - } - - chainID, _ := cmd.Flags().GetString(flags.FlagChainID) - if chainID != "" { - appGenesis.ChainID = chainID - } - - bz, err := json.Marshal(appGenesis) - if err != nil { - return fmt.Errorf("failed to marshal app genesis: %w", err) - } - - outputDocument, _ := cmd.Flags().GetString(flags.FlagOutputDocument) - if outputDocument == "" { - cmd.Println(string(bz)) - return nil - } - - if err = appGenesis.SaveAs(outputDocument); err != nil { - return err - } - - return nil -} diff --git a/x/genutil/client/cli/migrate_test.go b/x/genutil/client/cli/migrate_test.go deleted file mode 100644 index 409805745770..000000000000 --- a/x/genutil/client/cli/migrate_test.go +++ /dev/null @@ -1,72 +0,0 @@ -package cli_test - -import ( - "os" - "testing" - - "github.com/stretchr/testify/require" - - "github.com/cosmos/cosmos-sdk/client" - "github.com/cosmos/cosmos-sdk/testutil" - clitestutil "github.com/cosmos/cosmos-sdk/testutil/cli" - moduletestutil "github.com/cosmos/cosmos-sdk/types/module/testutil" - "github.com/cosmos/cosmos-sdk/x/genutil/client/cli" -) - -func TestMigrateGenesis(t *testing.T) { - testCases := []struct { - name string - genesis string - target string - expErr bool - expErrMsg string - check func(jsonOut string) - }{ - { - "migrate 0.37 to 0.43", - v037Exported, - "v0.43", - true, "make sure that you have correctly migrated all CometBFT consensus params", func(_ string) {}, - }, - { - "invalid target version", - func() string { - bz, err := os.ReadFile("../../types/testdata/app_genesis.json") - require.NoError(t, err) - - return string(bz) - }(), - "v0.10", - true, "unknown migration function for version: v0.10 (supported versions v0.43, v0.46, v0.47)", func(_ string) {}, - }, - { - "invalid target version", - func() string { - bz, err := os.ReadFile("../../types/testdata/cmt_genesis.json") - require.NoError(t, err) - - return string(bz) - }(), - "v0.10", - true, "unknown migration function for version: v0.10 (supported versions v0.43, v0.46, v0.47)", func(_ string) {}, - }, - } - - for _, tc := range testCases { - t.Run(tc.name, func(t *testing.T) { - genesisFile := testutil.WriteToNewTempFile(t, tc.genesis) - jsonOutput, err := clitestutil.ExecTestCLICmd( - // the codec does not contain any modules so that genutil does not bring unnecessary dependencies in the test - client.Context{Codec: moduletestutil.MakeTestEncodingConfig().Codec}, - cli.MigrateGenesisCmd(cli.MigrationMap), - []string{tc.target, genesisFile.Name()}, - ) - if tc.expErr { - require.Contains(t, err.Error(), tc.expErrMsg) - } else { - require.NoError(t, err) - tc.check(jsonOutput.String()) - } - }) - } -} diff --git a/x/genutil/migrations/v043/migrate.go b/x/genutil/migrations/v043/migrate.go deleted file mode 100644 index 93ed56989472..000000000000 --- a/x/genutil/migrations/v043/migrate.go +++ /dev/null @@ -1,44 +0,0 @@ -package v043 - -import ( - "github.com/cosmos/cosmos-sdk/client" - v1bank "github.com/cosmos/cosmos-sdk/x/bank/migrations/v1" - v2bank "github.com/cosmos/cosmos-sdk/x/bank/migrations/v2" - bank "github.com/cosmos/cosmos-sdk/x/bank/types" - "github.com/cosmos/cosmos-sdk/x/genutil/types" - v1gov "github.com/cosmos/cosmos-sdk/x/gov/migrations/v1" - v2gov "github.com/cosmos/cosmos-sdk/x/gov/migrations/v2" - gov "github.com/cosmos/cosmos-sdk/x/gov/types/v1beta1" -) - -// Migrate migrates exported state from v0.40 to a v0.43 genesis state. -func Migrate(appState types.AppMap, clientCtx client.Context) (types.AppMap, error) { - // Migrate x/gov. - if appState[v1gov.ModuleName] != nil { - // unmarshal relative source genesis application state - var oldGovState gov.GenesisState - clientCtx.Codec.MustUnmarshalJSON(appState[v1gov.ModuleName], &oldGovState) - - // delete deprecated x/gov genesis state - delete(appState, v1gov.ModuleName) - - // Migrate relative source genesis application state and marshal it into - // the respective key. - appState[v2gov.ModuleName] = clientCtx.Codec.MustMarshalJSON(v2gov.MigrateJSON(&oldGovState)) - } - - if appState[v1bank.ModuleName] != nil { - // unmarshal relative source genesis application state - var oldBankState bank.GenesisState - clientCtx.Codec.MustUnmarshalJSON(appState[v1bank.ModuleName], &oldBankState) - - // delete deprecated x/bank genesis state - delete(appState, v1bank.ModuleName) - - // Migrate relative source genesis application state and marshal it into - // the respective key. - appState[v2bank.ModuleName] = clientCtx.Codec.MustMarshalJSON(v2bank.MigrateJSON(&oldBankState)) - } - - return appState, nil -} diff --git a/x/genutil/migrations/v046/migrate.go b/x/genutil/migrations/v046/migrate.go deleted file mode 100644 index b6d6774feb41..000000000000 --- a/x/genutil/migrations/v046/migrate.go +++ /dev/null @@ -1,53 +0,0 @@ -package v046 - -import ( - "github.com/cosmos/cosmos-sdk/client" - "github.com/cosmos/cosmos-sdk/x/genutil/types" - v2gov "github.com/cosmos/cosmos-sdk/x/gov/migrations/v2" - v3gov "github.com/cosmos/cosmos-sdk/x/gov/migrations/v3" - govv1beta1 "github.com/cosmos/cosmos-sdk/x/gov/types/v1beta1" - stakingv2 "github.com/cosmos/cosmos-sdk/x/staking/migrations/v2" - stakingv3 "github.com/cosmos/cosmos-sdk/x/staking/migrations/v3" - stakingtypes "github.com/cosmos/cosmos-sdk/x/staking/types" -) - -// Migrate migrates exported state from v0.43 to a v0.46 genesis state. -func Migrate(appState types.AppMap, clientCtx client.Context) (types.AppMap, error) { - // Migrate x/gov. - if appState[v2gov.ModuleName] != nil { - // unmarshal relative source genesis application state - var old govv1beta1.GenesisState - clientCtx.Codec.MustUnmarshalJSON(appState[v2gov.ModuleName], &old) - - // delete deprecated x/gov genesis state - delete(appState, v2gov.ModuleName) - - // Migrate relative source genesis application state and marshal it into - // the respective key. - new, err := v3gov.MigrateJSON(&old) - if err != nil { - return nil, err - } - appState[v3gov.ModuleName] = clientCtx.Codec.MustMarshalJSON(new) - } - - // Migrate x/staking. - if appState[stakingv2.ModuleName] != nil { - // unmarshal relative source genesis application state - var old stakingtypes.GenesisState - clientCtx.Codec.MustUnmarshalJSON(appState[stakingv2.ModuleName], &old) - - // delete deprecated x/staking genesis state - delete(appState, stakingv2.ModuleName) - - // Migrate relative source genesis application state and marshal it into - // the respective key. - new, err := stakingv3.MigrateJSON(old) - if err != nil { - return nil, err - } - appState[stakingv3.ModuleName] = clientCtx.Codec.MustMarshalJSON(&new) - } - - return appState, nil -} diff --git a/x/genutil/migrations/v047/migrate.go b/x/genutil/migrations/v047/migrate.go deleted file mode 100644 index 75e468a9b69c..000000000000 --- a/x/genutil/migrations/v047/migrate.go +++ /dev/null @@ -1,62 +0,0 @@ -package v047 - -import ( - "github.com/cosmos/cosmos-sdk/client" - groupv2 "github.com/cosmos/cosmos-sdk/contrib/x/group/migrations/v2" - v1auth "github.com/cosmos/cosmos-sdk/x/auth/migrations/v1" - authtypes "github.com/cosmos/cosmos-sdk/x/auth/types" - bankv4 "github.com/cosmos/cosmos-sdk/x/bank/migrations/v4" - banktypes "github.com/cosmos/cosmos-sdk/x/bank/types" - v1distr "github.com/cosmos/cosmos-sdk/x/distribution/migrations/v1" - v3distr "github.com/cosmos/cosmos-sdk/x/distribution/migrations/v3" - distrtypes "github.com/cosmos/cosmos-sdk/x/distribution/types" - "github.com/cosmos/cosmos-sdk/x/genutil/types" - v4gov "github.com/cosmos/cosmos-sdk/x/gov/migrations/v4" - govv1 "github.com/cosmos/cosmos-sdk/x/gov/types/v1" -) - -// Migrate migrates exported state from v0.46 to a v0.47 genesis state. -func Migrate(appState types.AppMap, clientCtx client.Context) (types.AppMap, error) { - // Migrate x/bank. - bankState := appState[banktypes.ModuleName] - if len(bankState) > 0 { - var oldBankState banktypes.GenesisState - clientCtx.Codec.MustUnmarshalJSON(bankState, &oldBankState) - newBankState := bankv4.MigrateGenState(&oldBankState) - appState[banktypes.ModuleName] = clientCtx.Codec.MustMarshalJSON(newBankState) - } - - if govOldState, ok := appState[v4gov.ModuleName]; ok { - // unmarshal relative source genesis application state - var old govv1.GenesisState - clientCtx.Codec.MustUnmarshalJSON(govOldState, &old) - - // delete deprecated x/gov genesis state - delete(appState, v4gov.ModuleName) - - // set the x/gov genesis state with new state. - new, err := v4gov.MigrateJSON(&old) - if err != nil { - return nil, err - } - appState[v4gov.ModuleName] = clientCtx.Codec.MustMarshalJSON(new) - } - - // Migrate x/auth group policy accounts - if authOldState, ok := appState[v1auth.ModuleName]; ok { - var old authtypes.GenesisState - clientCtx.Codec.MustUnmarshalJSON(authOldState, &old) - newAuthState := groupv2.MigrateGenState(&old) - appState[v1auth.ModuleName] = clientCtx.Codec.MustMarshalJSON(newAuthState) - } - - // Migrate x/distribution params (reset unused) - if oldDistState, ok := appState[v1distr.ModuleName]; ok { - var old distrtypes.GenesisState - clientCtx.Codec.MustUnmarshalJSON(oldDistState, &old) - newDistState := v3distr.MigrateJSON(&old) - appState[v1distr.ModuleName] = clientCtx.Codec.MustMarshalJSON(newDistState) - } - - return appState, nil -} diff --git a/x/gov/common_test.go b/x/gov/common_test.go index bb07448fc5fa..1bb0e84c397c 100644 --- a/x/gov/common_test.go +++ b/x/gov/common_test.go @@ -30,7 +30,6 @@ import ( "github.com/cosmos/cosmos-sdk/x/gov/types" v1 "github.com/cosmos/cosmos-sdk/x/gov/types/v1" "github.com/cosmos/cosmos-sdk/x/gov/types/v1beta1" - _ "github.com/cosmos/cosmos-sdk/x/params" _ "github.com/cosmos/cosmos-sdk/x/staking" stakingkeeper "github.com/cosmos/cosmos-sdk/x/staking/keeper" stakingtypes "github.com/cosmos/cosmos-sdk/x/staking/types" @@ -122,7 +121,6 @@ func createTestSuite(t *testing.T) suite { app, err := simtestutil.SetupWithConfiguration( depinject.Configs( configurator.NewAppConfig( - configurator.ParamsModule(), configurator.AuthModule(), configurator.StakingModule(), configurator.BankModule(), diff --git a/x/gov/depinject.go b/x/gov/depinject.go index 72c8367d5359..91838a9fb13a 100644 --- a/x/gov/depinject.go +++ b/x/gov/depinject.go @@ -17,16 +17,15 @@ import ( authtypes "github.com/cosmos/cosmos-sdk/x/auth/types" "github.com/cosmos/cosmos-sdk/x/gov/keeper" govtypes "github.com/cosmos/cosmos-sdk/x/gov/types" - v1 "github.com/cosmos/cosmos-sdk/x/gov/types/v1" "github.com/cosmos/cosmos-sdk/x/gov/types/v1beta1" - paramtypes "github.com/cosmos/cosmos-sdk/x/params/types" ) func init() { appmodule.Register( &modulev1.Module{}, - appmodule.Provide(ProvideModule, ProvideKeyTable), - appmodule.Invoke(InvokeAddRoutes, InvokeSetHooks)) + appmodule.Provide(ProvideModule), + appmodule.Invoke(InvokeAddRoutes, InvokeSetHooks), + ) } type ModuleInputs struct { @@ -45,9 +44,6 @@ type ModuleInputs struct { // StakingKeeper is required if CalculateVoteResultsAndVotingPowerFn is not provided StakingKeeper govtypes.StakingKeeper `optional:"true"` - - // LegacySubspace is used solely for migration of x/params managed parameters - LegacySubspace govtypes.ParamSubspace `optional:"true"` } type ModuleOutputs struct { @@ -90,16 +86,12 @@ func ProvideModule(in ModuleInputs) ModuleOutputs { authority.String(), tallyFn, ) - m := NewAppModule(in.Cdc, k, in.AccountKeeper, in.BankKeeper, in.LegacySubspace) + m := NewAppModule(in.Cdc, k, in.AccountKeeper, in.BankKeeper) hr := v1beta1.HandlerRoute{Handler: v1beta1.ProposalHandler, RouteKey: govtypes.RouterKey} return ModuleOutputs{Module: m, Keeper: k, HandlerRoute: hr} } -func ProvideKeyTable() paramtypes.KeyTable { - return v1.ParamKeyTable() //nolint:staticcheck // we still need this for upgrades -} - func InvokeAddRoutes(keeper *keeper.Keeper, routes []v1beta1.HandlerRoute) { if keeper == nil || routes == nil { return diff --git a/x/gov/exported/exported.go b/x/gov/exported/exported.go deleted file mode 100644 index d11945425175..000000000000 --- a/x/gov/exported/exported.go +++ /dev/null @@ -1,18 +0,0 @@ -package exported - -import ( - sdk "github.com/cosmos/cosmos-sdk/types" - paramtypes "github.com/cosmos/cosmos-sdk/x/params/types" -) - -type ( - ParamSet = paramtypes.ParamSet - - // ParamSubspace defines an interface that implements the legacy x/params Subspace - // type. - // - // NOTE: This is used solely for migration of x/params managed parameters. - ParamSubspace interface { - Get(ctx sdk.Context, key []byte, ptr any) - } -) diff --git a/x/gov/keeper/grpc_query.go b/x/gov/keeper/grpc_query.go index b4d6c197a4f6..67fd62a4a793 100644 --- a/x/gov/keeper/grpc_query.go +++ b/x/gov/keeper/grpc_query.go @@ -8,13 +8,10 @@ import ( "cosmossdk.io/collections" "cosmossdk.io/errors" - sdkmath "cosmossdk.io/math" sdk "github.com/cosmos/cosmos-sdk/types" "github.com/cosmos/cosmos-sdk/types/query" - v3 "github.com/cosmos/cosmos-sdk/x/gov/migrations/v3" v1 "github.com/cosmos/cosmos-sdk/x/gov/types/v1" - "github.com/cosmos/cosmos-sdk/x/gov/types/v1beta1" ) var _ v1.QueryServer = queryServer{} @@ -274,182 +271,3 @@ func (q queryServer) TallyResult(ctx context.Context, req *v1.QueryTallyResultRe return &v1.QueryTallyResultResponse{Tally: &tallyResult}, nil } - -var _ v1beta1.QueryServer = legacyQueryServer{} - -type legacyQueryServer struct{ qs v1.QueryServer } - -// NewLegacyQueryServer returns an implementation of the v1beta1 legacy QueryServer interface. -func NewLegacyQueryServer(k *Keeper) v1beta1.QueryServer { - return &legacyQueryServer{qs: NewQueryServer(k)} -} - -func (q legacyQueryServer) Proposal(ctx context.Context, req *v1beta1.QueryProposalRequest) (*v1beta1.QueryProposalResponse, error) { - resp, err := q.qs.Proposal(ctx, &v1.QueryProposalRequest{ - ProposalId: req.ProposalId, - }) - if err != nil { - return nil, err - } - - proposal, err := v3.ConvertToLegacyProposal(*resp.Proposal) - if err != nil { - return nil, err - } - - return &v1beta1.QueryProposalResponse{Proposal: proposal}, nil -} - -func (q legacyQueryServer) Proposals(ctx context.Context, req *v1beta1.QueryProposalsRequest) (*v1beta1.QueryProposalsResponse, error) { - resp, err := q.qs.Proposals(ctx, &v1.QueryProposalsRequest{ - ProposalStatus: v1.ProposalStatus(req.ProposalStatus), - Voter: req.Voter, - Depositor: req.Depositor, - Pagination: req.Pagination, - }) - if err != nil { - return nil, err - } - - legacyProposals := make([]v1beta1.Proposal, len(resp.Proposals)) - for idx, proposal := range resp.Proposals { - legacyProposals[idx], err = v3.ConvertToLegacyProposal(*proposal) - if err != nil { - return nil, err - } - } - - return &v1beta1.QueryProposalsResponse{ - Proposals: legacyProposals, - Pagination: resp.Pagination, - }, nil -} - -func (q legacyQueryServer) Vote(ctx context.Context, req *v1beta1.QueryVoteRequest) (*v1beta1.QueryVoteResponse, error) { - resp, err := q.qs.Vote(ctx, &v1.QueryVoteRequest{ - ProposalId: req.ProposalId, - Voter: req.Voter, - }) - if err != nil { - return nil, err - } - - vote, err := v3.ConvertToLegacyVote(*resp.Vote) - if err != nil { - return nil, err - } - - return &v1beta1.QueryVoteResponse{Vote: vote}, nil -} - -func (q legacyQueryServer) Votes(ctx context.Context, req *v1beta1.QueryVotesRequest) (*v1beta1.QueryVotesResponse, error) { - resp, err := q.qs.Votes(ctx, &v1.QueryVotesRequest{ - ProposalId: req.ProposalId, - Pagination: req.Pagination, - }) - if err != nil { - return nil, err - } - - votes := make([]v1beta1.Vote, len(resp.Votes)) - for i, v := range resp.Votes { - votes[i], err = v3.ConvertToLegacyVote(*v) - if err != nil { - return nil, err - } - } - - return &v1beta1.QueryVotesResponse{ - Votes: votes, - Pagination: resp.Pagination, - }, nil -} - -//nolint:staticcheck // this is needed for legacy param support -func (q legacyQueryServer) Params(ctx context.Context, req *v1beta1.QueryParamsRequest) (*v1beta1.QueryParamsResponse, error) { - resp, err := q.qs.Params(ctx, &v1.QueryParamsRequest{ - ParamsType: req.ParamsType, - }) - if err != nil { - return nil, err - } - - response := &v1beta1.QueryParamsResponse{} - - if resp.DepositParams == nil && resp.VotingParams == nil && resp.TallyParams == nil { - return nil, status.Errorf(codes.InvalidArgument, "%s is not a valid parameter type", req.ParamsType) - } - - if resp.DepositParams != nil { - minDeposit := sdk.NewCoins(resp.DepositParams.MinDeposit...) - response.DepositParams = v1beta1.NewDepositParams(minDeposit, *resp.DepositParams.MaxDepositPeriod) - } - - if resp.VotingParams != nil { - response.VotingParams = v1beta1.NewVotingParams(*resp.VotingParams.VotingPeriod) - } - - if resp.TallyParams != nil { - quorum, err := sdkmath.LegacyNewDecFromStr(resp.TallyParams.Quorum) - if err != nil { - return nil, err - } - threshold, err := sdkmath.LegacyNewDecFromStr(resp.TallyParams.Threshold) - if err != nil { - return nil, err - } - vetoThreshold, err := sdkmath.LegacyNewDecFromStr(resp.TallyParams.VetoThreshold) - if err != nil { - return nil, err - } - - response.TallyParams = v1beta1.NewTallyParams(quorum, threshold, vetoThreshold) - } - - return response, nil -} - -func (q legacyQueryServer) Deposit(ctx context.Context, req *v1beta1.QueryDepositRequest) (*v1beta1.QueryDepositResponse, error) { - resp, err := q.qs.Deposit(ctx, &v1.QueryDepositRequest{ - ProposalId: req.ProposalId, - Depositor: req.Depositor, - }) - if err != nil { - return nil, err - } - - deposit := v3.ConvertToLegacyDeposit(resp.Deposit) - return &v1beta1.QueryDepositResponse{Deposit: deposit}, nil -} - -func (q legacyQueryServer) Deposits(ctx context.Context, req *v1beta1.QueryDepositsRequest) (*v1beta1.QueryDepositsResponse, error) { - resp, err := q.qs.Deposits(ctx, &v1.QueryDepositsRequest{ - ProposalId: req.ProposalId, - Pagination: req.Pagination, - }) - if err != nil { - return nil, err - } - deposits := make([]v1beta1.Deposit, len(resp.Deposits)) - for idx, deposit := range resp.Deposits { - deposits[idx] = v3.ConvertToLegacyDeposit(deposit) - } - - return &v1beta1.QueryDepositsResponse{Deposits: deposits, Pagination: resp.Pagination}, nil -} - -func (q legacyQueryServer) TallyResult(ctx context.Context, req *v1beta1.QueryTallyResultRequest) (*v1beta1.QueryTallyResultResponse, error) { - resp, err := q.qs.TallyResult(ctx, &v1.QueryTallyResultRequest{ - ProposalId: req.ProposalId, - }) - if err != nil { - return nil, err - } - - tally, err := v3.ConvertToLegacyTallyResult(resp.Tally) - if err != nil { - return nil, err - } - - return &v1beta1.QueryTallyResultResponse{Tally: tally}, nil -} diff --git a/x/gov/keeper/grpc_query_test.go b/x/gov/keeper/grpc_query_test.go index 9a5d6bacc6d9..c32ab127aa8e 100644 --- a/x/gov/keeper/grpc_query_test.go +++ b/x/gov/keeper/grpc_query_test.go @@ -11,7 +11,6 @@ import ( simtestutil "github.com/cosmos/cosmos-sdk/testutil/sims" sdk "github.com/cosmos/cosmos-sdk/types" "github.com/cosmos/cosmos-sdk/types/query" - v3 "github.com/cosmos/cosmos-sdk/x/gov/migrations/v3" v1 "github.com/cosmos/cosmos-sdk/x/gov/types/v1" "github.com/cosmos/cosmos-sdk/x/gov/types/v1beta1" ) @@ -97,93 +96,6 @@ func (suite *KeeperTestSuite) TestGRPCQueryConstitution() { suite.Require().Equal(expRes, constitution) } -func (suite *KeeperTestSuite) TestLegacyGRPCQueryProposal() { - suite.reset() - ctx, queryClient, addrs := suite.ctx, suite.legacyQueryClient, suite.addrs - - var ( - req *v1beta1.QueryProposalRequest - expProposal v1beta1.Proposal - ) - - testCases := []struct { - msg string - malleate func() - expPass bool - }{ - { - "empty request", - func() { - req = &v1beta1.QueryProposalRequest{} - }, - false, - }, - { - "non existing proposal request", - func() { - req = &v1beta1.QueryProposalRequest{ProposalId: 3} - }, - false, - }, - { - "zero proposal id request", - func() { - req = &v1beta1.QueryProposalRequest{ProposalId: 0} - }, - false, - }, - { - "valid request", - func() { - req = &v1beta1.QueryProposalRequest{ProposalId: 1} - testProposal := v1beta1.NewTextProposal("Proposal", "testing proposal") - msgContent, err := v1.NewLegacyContent(testProposal, govAcct.String()) - suite.Require().NoError(err) - submittedProposal, err := suite.govKeeper.SubmitProposal(ctx, []sdk.Msg{msgContent}, "", "title", "summary", addrs[0], false) - suite.Require().NoError(err) - suite.Require().NotEmpty(submittedProposal) - - expProposal, err = v3.ConvertToLegacyProposal(submittedProposal) - suite.Require().NoError(err) - }, - true, - }, - { - "valid request - expedited", - func() { - req = &v1beta1.QueryProposalRequest{ProposalId: 2} - testProposal := v1beta1.NewTextProposal("Proposal", "testing proposal") - msgContent, err := v1.NewLegacyContent(testProposal, govAcct.String()) - suite.Require().NoError(err) - submittedProposal, err := suite.govKeeper.SubmitProposal(ctx, []sdk.Msg{msgContent}, "", "title", "summary", addrs[0], true) - suite.Require().NoError(err) - suite.Require().NotEmpty(submittedProposal) - - expProposal, err = v3.ConvertToLegacyProposal(submittedProposal) - suite.Require().NoError(err) - }, - true, - }, - } - - for _, testCase := range testCases { - suite.Run(fmt.Sprintf("Case %s", testCase.msg), func() { - testCase.malleate() - - proposalRes, err := queryClient.Proposal(gocontext.Background(), req) - - if testCase.expPass { - suite.Require().NoError(err) - suite.Require().NotEmpty(proposalRes.Proposal.String()) - suite.Require().Equal(proposalRes.Proposal.String(), expProposal.String()) - } else { - suite.Require().Error(err) - suite.Require().Nil(proposalRes) - } - }) - } -} - func (suite *KeeperTestSuite) TestGRPCQueryProposals() { suite.reset() ctx, queryClient, addrs := suite.ctx, suite.queryClient, suite.addrs @@ -395,50 +307,6 @@ func (suite *KeeperTestSuite) TestGRPCQueryProposals() { } } -func (suite *KeeperTestSuite) TestLegacyGRPCQueryProposals() { - suite.reset() - ctx, queryClient, addrs := suite.ctx, suite.legacyQueryClient, suite.addrs - - var req *v1beta1.QueryProposalsRequest - - testCases := []struct { - msg string - malleate func() - expPass bool - }{ - { - "valid request", - func() { - req = &v1beta1.QueryProposalsRequest{} - testProposal := v1beta1.NewTextProposal("Proposal", "testing proposal") - msgContent, err := v1.NewLegacyContent(testProposal, govAcct.String()) - suite.Require().NoError(err) - submittedProposal, err := suite.govKeeper.SubmitProposal(ctx, []sdk.Msg{msgContent}, "", "title", "summary", addrs[0], false) - suite.Require().NoError(err) - suite.Require().NotEmpty(submittedProposal) - }, - true, - }, - } - - for _, testCase := range testCases { - suite.Run(fmt.Sprintf("Case %s", testCase.msg), func() { - testCase.malleate() - - proposalRes, err := queryClient.Proposals(gocontext.Background(), req) - - if testCase.expPass { - suite.Require().NoError(err) - suite.Require().NotNil(proposalRes.Proposals) - suite.Require().Equal(len(proposalRes.Proposals), 1) - } else { - suite.Require().Error(err) - suite.Require().Nil(proposalRes) - } - }) - } -} - func (suite *KeeperTestSuite) TestGRPCQueryVote() { ctx, queryClient, addrs := suite.ctx, suite.queryClient, suite.addrs @@ -553,120 +421,6 @@ func (suite *KeeperTestSuite) TestGRPCQueryVote() { } } -func (suite *KeeperTestSuite) TestLegacyGRPCQueryVote() { - ctx, queryClient, addrs := suite.ctx, suite.legacyQueryClient, suite.addrs - - var ( - req *v1beta1.QueryVoteRequest - expRes *v1beta1.QueryVoteResponse - proposal v1.Proposal - ) - - testCases := []struct { - msg string - malleate func() - expPass bool - }{ - { - "empty request", - func() { - req = &v1beta1.QueryVoteRequest{} - }, - false, - }, - { - "zero proposal id request", - func() { - req = &v1beta1.QueryVoteRequest{ - ProposalId: 0, - Voter: addrs[0].String(), - } - }, - false, - }, - { - "empty voter request", - func() { - req = &v1beta1.QueryVoteRequest{ - ProposalId: 1, - Voter: "", - } - }, - false, - }, - { - "non existed proposal", - func() { - req = &v1beta1.QueryVoteRequest{ - ProposalId: 3, - Voter: addrs[0].String(), - } - }, - false, - }, - { - "no votes present", - func() { - var err error - proposal, err = suite.govKeeper.SubmitProposal(ctx, TestProposal, "", "title", "summary", addrs[0], false) - suite.Require().NoError(err) - - req = &v1beta1.QueryVoteRequest{ - ProposalId: proposal.Id, - Voter: addrs[0].String(), - } - - expRes = &v1beta1.QueryVoteResponse{} - }, - false, - }, - { - "valid request", - func() { - proposal.Status = v1.StatusVotingPeriod - suite.Require().NoError(suite.govKeeper.SetProposal(ctx, proposal)) - suite.Require().NoError(suite.govKeeper.AddVote(ctx, proposal.Id, addrs[0], v1.NewNonSplitVoteOption(v1.OptionAbstain), "")) - - req = &v1beta1.QueryVoteRequest{ - ProposalId: proposal.Id, - Voter: addrs[0].String(), - } - - expRes = &v1beta1.QueryVoteResponse{Vote: v1beta1.Vote{ProposalId: proposal.Id, Voter: addrs[0].String(), Options: []v1beta1.WeightedVoteOption{{Option: v1beta1.OptionAbstain, Weight: math.LegacyMustNewDecFromStr("1.0")}}}} - }, - true, - }, - { - "wrong voter id request", - func() { - req = &v1beta1.QueryVoteRequest{ - ProposalId: proposal.Id, - Voter: addrs[1].String(), - } - - expRes = &v1beta1.QueryVoteResponse{} - }, - false, - }, - } - - for _, testCase := range testCases { - suite.Run(fmt.Sprintf("Case %s", testCase.msg), func() { - testCase.malleate() - - vote, err := queryClient.Vote(gocontext.Background(), req) - - if testCase.expPass { - suite.Require().NoError(err) - suite.Require().Equal(expRes, vote) - } else { - suite.Require().Error(err) - suite.Require().Nil(vote) - } - }) - } -} - func (suite *KeeperTestSuite) TestGRPCQueryVotes() { suite.reset() ctx, queryClient := suite.ctx, suite.queryClient @@ -771,17 +525,14 @@ func (suite *KeeperTestSuite) TestGRPCQueryVotes() { } } -func (suite *KeeperTestSuite) TestLegacyGRPCQueryVotes() { - suite.reset() - ctx, queryClient := suite.ctx, suite.legacyQueryClient +func (suite *KeeperTestSuite) TestGRPCQueryParams() { + queryClient := suite.queryClient - addrs := simtestutil.AddTestAddrsIncremental(suite.bankKeeper, suite.stakingKeeper, ctx, 2, math.NewInt(30000000)) + params := v1.DefaultParams() var ( - req *v1beta1.QueryVotesRequest - expRes *v1beta1.QueryVotesResponse - proposal v1.Proposal - votes v1beta1.Votes + req *v1.QueryParamsRequest + expRes *v1.QueryParamsResponse ) testCases := []struct { @@ -790,148 +541,47 @@ func (suite *KeeperTestSuite) TestLegacyGRPCQueryVotes() { expPass bool }{ { - "empty request", + "empty request (valid and returns all params)", func() { - req = &v1beta1.QueryVotesRequest{} + req = &v1.QueryParamsRequest{} }, - false, + true, }, { - "zero proposal id request", + "deposit params request", func() { - req = &v1beta1.QueryVotesRequest{ - ProposalId: 0, + req = &v1.QueryParamsRequest{ParamsType: v1.ParamDeposit} + depositParams := v1.NewDepositParams(params.MinDeposit, params.MaxDepositPeriod) //nolint:staticcheck // SA1019: params.MinDeposit is deprecated: Use MinInitialDeposit instead. + expRes = &v1.QueryParamsResponse{ + DepositParams: &depositParams, } }, - false, + true, }, { - "non existed proposals", + "voting params request", func() { - req = &v1beta1.QueryVotesRequest{ - ProposalId: 2, + req = &v1.QueryParamsRequest{ParamsType: v1.ParamVoting} + votingParams := v1.NewVotingParams(params.VotingPeriod) //nolint:staticcheck // SA1019: params.VotingPeriod is deprecated: Use VotingPeriod instead. + expRes = &v1.QueryParamsResponse{ + VotingParams: &votingParams, } }, true, }, { - "create a proposal and get votes", + "tally params request", func() { - var err error - proposal, err = suite.govKeeper.SubmitProposal(ctx, TestProposal, "", "title", "summary", addrs[0], false) - suite.Require().NoError(err) - - req = &v1beta1.QueryVotesRequest{ - ProposalId: proposal.Id, + req = &v1.QueryParamsRequest{ParamsType: v1.ParamTallying} + tallyParams := v1.NewTallyParams(params.Quorum, params.Threshold, params.VetoThreshold) //nolint:staticcheck // SA1019: params.Quorum is deprecated: Use Quorum instead. + expRes = &v1.QueryParamsResponse{ + TallyParams: &tallyParams, } }, true, }, { - "request after adding 2 votes", - func() { - proposal.Status = v1.StatusVotingPeriod - suite.Require().NoError(suite.govKeeper.SetProposal(ctx, proposal)) - - votes = []v1beta1.Vote{ - {ProposalId: proposal.Id, Voter: addrs[0].String(), Options: v1beta1.NewNonSplitVoteOption(v1beta1.OptionAbstain)}, - {ProposalId: proposal.Id, Voter: addrs[1].String(), Options: v1beta1.NewNonSplitVoteOption(v1beta1.OptionYes)}, - } - codec := address.NewBech32Codec("cosmos") - - accAddr1, err1 := codec.StringToBytes(votes[0].Voter) - accAddr2, err2 := codec.StringToBytes(votes[1].Voter) - suite.Require().NoError(err1) - suite.Require().NoError(err2) - suite.Require().NoError(suite.govKeeper.AddVote(ctx, proposal.Id, accAddr1, v1.NewNonSplitVoteOption(v1.OptionAbstain), "")) - suite.Require().NoError(suite.govKeeper.AddVote(ctx, proposal.Id, accAddr2, v1.NewNonSplitVoteOption(v1.OptionYes), "")) - - req = &v1beta1.QueryVotesRequest{ - ProposalId: proposal.Id, - } - - expRes = &v1beta1.QueryVotesResponse{ - Votes: votes, - } - }, - true, - }, - } - - for _, testCase := range testCases { - suite.Run(fmt.Sprintf("Case %s", testCase.msg), func() { - testCase.malleate() - - votes, err := queryClient.Votes(gocontext.Background(), req) - - if testCase.expPass { - suite.Require().NoError(err) - suite.Require().Equal(expRes.GetVotes(), votes.GetVotes()) - } else { - suite.Require().Error(err) - suite.Require().Nil(votes) - } - }) - } -} - -func (suite *KeeperTestSuite) TestGRPCQueryParams() { - queryClient := suite.queryClient - - params := v1.DefaultParams() - - var ( - req *v1.QueryParamsRequest - expRes *v1.QueryParamsResponse - ) - - testCases := []struct { - msg string - malleate func() - expPass bool - }{ - { - "empty request (valid and returns all params)", - func() { - req = &v1.QueryParamsRequest{} - }, - true, - }, - { - "deposit params request", - func() { - req = &v1.QueryParamsRequest{ParamsType: v1.ParamDeposit} - depositParams := v1.NewDepositParams(params.MinDeposit, params.MaxDepositPeriod) //nolint:staticcheck // SA1019: params.MinDeposit is deprecated: Use MinInitialDeposit instead. - expRes = &v1.QueryParamsResponse{ - DepositParams: &depositParams, - } - }, - true, - }, - { - "voting params request", - func() { - req = &v1.QueryParamsRequest{ParamsType: v1.ParamVoting} - votingParams := v1.NewVotingParams(params.VotingPeriod) //nolint:staticcheck // SA1019: params.VotingPeriod is deprecated: Use VotingPeriod instead. - expRes = &v1.QueryParamsResponse{ - VotingParams: &votingParams, - } - }, - true, - }, - { - "tally params request", - func() { - req = &v1.QueryParamsRequest{ParamsType: v1.ParamTallying} - tallyParams := v1.NewTallyParams(params.Quorum, params.Threshold, params.VetoThreshold) //nolint:staticcheck // SA1019: params.Quorum is deprecated: Use Quorum instead. - expRes = &v1.QueryParamsResponse{ - TallyParams: &tallyParams, - } - }, - true, - }, - { - "invalid request", + "invalid request", func() { req = &v1.QueryParamsRequest{ParamsType: "wrongPath"} expRes = &v1.QueryParamsResponse{} @@ -959,96 +609,6 @@ func (suite *KeeperTestSuite) TestGRPCQueryParams() { } } -func (suite *KeeperTestSuite) TestLegacyGRPCQueryParams() { - queryClient := suite.legacyQueryClient - - var ( - req *v1beta1.QueryParamsRequest - expRes *v1beta1.QueryParamsResponse - ) - - defaultTallyParams := v1beta1.TallyParams{ - Quorum: math.LegacyNewDec(0), - Threshold: math.LegacyNewDec(0), - VetoThreshold: math.LegacyNewDec(0), - } - - testCases := []struct { - msg string - malleate func() - expPass bool - }{ - { - "empty request", - func() { - req = &v1beta1.QueryParamsRequest{} - }, - false, - }, - { - "deposit params request", - func() { - req = &v1beta1.QueryParamsRequest{ParamsType: v1beta1.ParamDeposit} - depositParams := v1beta1.DefaultDepositParams() - expRes = &v1beta1.QueryParamsResponse{ - DepositParams: depositParams, - TallyParams: defaultTallyParams, - } - }, - true, - }, - { - "voting params request", - func() { - req = &v1beta1.QueryParamsRequest{ParamsType: v1beta1.ParamVoting} - votingParams := v1beta1.DefaultVotingParams() - expRes = &v1beta1.QueryParamsResponse{ - VotingParams: votingParams, - TallyParams: defaultTallyParams, - } - }, - true, - }, - { - "tally params request", - func() { - req = &v1beta1.QueryParamsRequest{ParamsType: v1beta1.ParamTallying} - tallyParams := v1beta1.DefaultTallyParams() - expRes = &v1beta1.QueryParamsResponse{ - TallyParams: tallyParams, - } - }, - true, - }, - { - "invalid request", - func() { - req = &v1beta1.QueryParamsRequest{ParamsType: "wrongPath"} - expRes = &v1beta1.QueryParamsResponse{} - }, - false, - }, - } - - for _, testCase := range testCases { - suite.Run(fmt.Sprintf("Case %s", testCase.msg), func() { - testCase.malleate() - - params, err := queryClient.Params(gocontext.Background(), req) - - if testCase.expPass { - suite.Require().NoError(err) - suite.Require().Equal(expRes.GetDepositParams(), params.GetDepositParams()) - suite.Require().Equal(expRes.GetVotingParams(), params.GetVotingParams()) - suite.Require().Equal(expRes.GetTallyParams(), params.GetTallyParams()) - } else { - suite.Require().Error(err) - suite.Require().Nil(params) - } - }) - } -} - func (suite *KeeperTestSuite) TestGRPCQueryDeposit() { suite.reset() ctx, queryClient, addrs := suite.ctx, suite.queryClient, suite.addrs @@ -1151,108 +711,6 @@ func (suite *KeeperTestSuite) TestGRPCQueryDeposit() { } } -func (suite *KeeperTestSuite) TestLegacyGRPCQueryDeposit() { - ctx, queryClient, addrs := suite.ctx, suite.legacyQueryClient, suite.addrs - - var ( - req *v1beta1.QueryDepositRequest - expRes *v1beta1.QueryDepositResponse - proposal v1.Proposal - ) - - testCases := []struct { - msg string - malleate func() - expPass bool - }{ - { - "empty request", - func() { - req = &v1beta1.QueryDepositRequest{} - }, - false, - }, - { - "zero proposal id request", - func() { - req = &v1beta1.QueryDepositRequest{ - ProposalId: 0, - Depositor: addrs[0].String(), - } - }, - false, - }, - { - "empty deposit address request", - func() { - req = &v1beta1.QueryDepositRequest{ - ProposalId: 1, - Depositor: "", - } - }, - false, - }, - { - "non existed proposal", - func() { - req = &v1beta1.QueryDepositRequest{ - ProposalId: 2, - Depositor: addrs[0].String(), - } - }, - false, - }, - { - "no deposits proposal", - func() { - var err error - proposal, err = suite.govKeeper.SubmitProposal(ctx, TestProposal, "", "title", "summary", addrs[0], false) - suite.Require().NoError(err) - suite.Require().NotNil(proposal) - - req = &v1beta1.QueryDepositRequest{ - ProposalId: proposal.Id, - Depositor: addrs[0].String(), - } - }, - false, - }, - { - "valid request", - func() { - depositCoins := sdk.NewCoins(sdk.NewCoin(sdk.DefaultBondDenom, suite.stakingKeeper.TokensFromConsensusPower(ctx, 20))) - deposit := v1beta1.NewDeposit(proposal.Id, addrs[0], depositCoins) - v1deposit := v1.NewDeposit(proposal.Id, addrs[0], depositCoins) - suite.Require().NoError(suite.govKeeper.SetDeposit(ctx, v1deposit)) - - req = &v1beta1.QueryDepositRequest{ - ProposalId: proposal.Id, - Depositor: addrs[0].String(), - } - - expRes = &v1beta1.QueryDepositResponse{Deposit: deposit} - }, - true, - }, - } - - for _, testCase := range testCases { - suite.Run(fmt.Sprintf("Case %s", testCase.msg), func() { - testCase.malleate() - - deposit, err := queryClient.Deposit(gocontext.Background(), req) - - if testCase.expPass { - suite.Require().NoError(err) - suite.Require().Equal(deposit.GetDeposit(), expRes.GetDeposit()) - } else { - suite.Require().Error(err) - suite.Require().Nil(expRes) - } - }) - } -} - func (suite *KeeperTestSuite) TestGRPCQueryDeposits() { ctx, queryClient, addrs := suite.ctx, suite.queryClient, suite.addrs @@ -1347,103 +805,6 @@ func (suite *KeeperTestSuite) TestGRPCQueryDeposits() { } } -func (suite *KeeperTestSuite) TestLegacyGRPCQueryDeposits() { - suite.reset() - ctx, queryClient, addrs := suite.ctx, suite.legacyQueryClient, suite.addrs - - var ( - req *v1beta1.QueryDepositsRequest - expRes *v1beta1.QueryDepositsResponse - proposal v1.Proposal - ) - - testCases := []struct { - msg string - malleate func() - expPass bool - }{ - { - "empty request", - func() { - req = &v1beta1.QueryDepositsRequest{} - }, - false, - }, - { - "zero proposal id request", - func() { - req = &v1beta1.QueryDepositsRequest{ - ProposalId: 0, - } - }, - false, - }, - { - "non existed proposal", - func() { - req = &v1beta1.QueryDepositsRequest{ - ProposalId: 2, - } - }, - true, - }, - { - "create a proposal and get deposits", - func() { - var err error - proposal, err = suite.govKeeper.SubmitProposal(ctx, TestProposal, "", "title", "summary", addrs[0], false) - suite.Require().NoError(err) - - req = &v1beta1.QueryDepositsRequest{ - ProposalId: proposal.Id, - } - }, - true, - }, - { - "get deposits with default limit", - func() { - depositAmount1 := sdk.NewCoins(sdk.NewCoin(sdk.DefaultBondDenom, suite.stakingKeeper.TokensFromConsensusPower(ctx, 20))) - deposit1 := v1beta1.NewDeposit(proposal.Id, addrs[0], depositAmount1) - v1deposit1 := v1.NewDeposit(proposal.Id, addrs[0], depositAmount1) - suite.Require().NoError(suite.govKeeper.SetDeposit(ctx, v1deposit1)) - - depositAmount2 := sdk.NewCoins(sdk.NewCoin(sdk.DefaultBondDenom, suite.stakingKeeper.TokensFromConsensusPower(ctx, 30))) - deposit2 := v1beta1.NewDeposit(proposal.Id, addrs[1], depositAmount2) - v1deposit2 := v1.NewDeposit(proposal.Id, addrs[1], depositAmount2) - suite.Require().NoError(suite.govKeeper.SetDeposit(ctx, v1deposit2)) - - deposits := v1beta1.Deposits{deposit1, deposit2} - - req = &v1beta1.QueryDepositsRequest{ - ProposalId: proposal.Id, - } - - expRes = &v1beta1.QueryDepositsResponse{ - Deposits: deposits, - } - }, - true, - }, - } - - for _, testCase := range testCases { - suite.Run(fmt.Sprintf("Case %s", testCase.msg), func() { - testCase.malleate() - - deposits, err := queryClient.Deposits(gocontext.Background(), req) - - if testCase.expPass { - suite.Require().NoError(err) - suite.Require().Equal(expRes.GetDeposits(), deposits.GetDeposits()) - } else { - suite.Require().Error(err) - suite.Require().Nil(deposits) - } - }) - } -} - func (suite *KeeperTestSuite) TestGRPCQueryTallyResult() { suite.reset() ctx, queryClient := suite.ctx, suite.queryClient @@ -1611,171 +972,3 @@ func (suite *KeeperTestSuite) TestGRPCQueryTallyResult() { }) } } - -func (suite *KeeperTestSuite) TestLegacyGRPCQueryTallyResult() { - suite.reset() - ctx, queryClient := suite.ctx, suite.legacyQueryClient - - var ( - req *v1beta1.QueryTallyResultRequest - expTally *v1beta1.TallyResult - ) - - testCases := []struct { - msg string - malleate func() - expPass bool - }{ - { - "empty request", - func() { - req = &v1beta1.QueryTallyResultRequest{} - }, - false, - }, - { - "non existing proposal request", - func() { - req = &v1beta1.QueryTallyResultRequest{ProposalId: 2} - }, - false, - }, - { - "zero proposal id request", - func() { - req = &v1beta1.QueryTallyResultRequest{ProposalId: 0} - }, - false, - }, - { - "valid request with proposal status passed", - func() { - propTime := time.Now() - proposal := v1.Proposal{ - Id: 1, - Status: v1.StatusPassed, - FinalTallyResult: &v1.TallyResult{ - YesCount: "4", - AbstainCount: "1", - NoCount: "0", - NoWithVetoCount: "0", - }, - SubmitTime: &propTime, - VotingStartTime: &propTime, - VotingEndTime: &propTime, - Metadata: "proposal metadata", - } - suite.Require().NoError(suite.govKeeper.SetProposal(ctx, proposal)) - - req = &v1beta1.QueryTallyResultRequest{ProposalId: proposal.Id} - - expTally = &v1beta1.TallyResult{ - Yes: math.NewInt(4), - Abstain: math.NewInt(1), - No: math.NewInt(0), - NoWithVeto: math.NewInt(0), - } - }, - true, - }, - { - "proposal status deposit", - func() { - propTime := time.Now() - proposal := v1.Proposal{ - Id: 1, - Status: v1.StatusDepositPeriod, - SubmitTime: &propTime, - VotingStartTime: &propTime, - VotingEndTime: &propTime, - Metadata: "proposal metadata", - } - suite.Require().NoError(suite.govKeeper.SetProposal(ctx, proposal)) - - req = &v1beta1.QueryTallyResultRequest{ProposalId: proposal.Id} - - expTally = &v1beta1.TallyResult{ - Yes: math.NewInt(0), - Abstain: math.NewInt(0), - No: math.NewInt(0), - NoWithVeto: math.NewInt(0), - } - }, - true, - }, - { - "proposal is in voting period", - func() { - propTime := time.Now() - proposal := v1.Proposal{ - Id: 1, - Status: v1.StatusVotingPeriod, - SubmitTime: &propTime, - VotingStartTime: &propTime, - VotingEndTime: &propTime, - Metadata: "proposal metadata", - } - suite.Require().NoError(suite.govKeeper.SetProposal(ctx, proposal)) - - req = &v1beta1.QueryTallyResultRequest{ProposalId: proposal.Id} - - expTally = &v1beta1.TallyResult{ - Yes: math.NewInt(0), - Abstain: math.NewInt(0), - No: math.NewInt(0), - NoWithVeto: math.NewInt(0), - } - }, - true, - }, - { - "proposal status failed", - func() { - propTime := time.Now() - proposal := v1.Proposal{ - Id: 1, - Status: v1.StatusFailed, - FinalTallyResult: &v1.TallyResult{ - YesCount: "4", - AbstainCount: "1", - NoCount: "0", - NoWithVetoCount: "0", - }, - SubmitTime: &propTime, - VotingStartTime: &propTime, - VotingEndTime: &propTime, - Metadata: "proposal metadata", - } - err := suite.govKeeper.Proposals.Set(suite.ctx, proposal.Id, proposal) - suite.Require().NoError(err) - - req = &v1beta1.QueryTallyResultRequest{ProposalId: proposal.Id} - - expTally = &v1beta1.TallyResult{ - Yes: math.NewInt(4), - Abstain: math.NewInt(1), - No: math.NewInt(0), - NoWithVeto: math.NewInt(0), - } - }, - true, - }, - } - - for _, testCase := range testCases { - suite.Run(fmt.Sprintf("Case %s", testCase.msg), func() { - testCase.malleate() - - tallyRes, err := queryClient.TallyResult(gocontext.Background(), req) - - if testCase.expPass { - suite.Require().NoError(err) - suite.Require().NotEmpty(tallyRes.Tally.String()) - suite.Require().Equal(expTally.String(), tallyRes.Tally.String()) - } else { - suite.Require().Error(err) - suite.Require().Nil(tallyRes) - } - }) - } -} diff --git a/x/gov/keeper/keeper_test.go b/x/gov/keeper/keeper_test.go index 748ad89de796..5fd46832ad18 100644 --- a/x/gov/keeper/keeper_test.go +++ b/x/gov/keeper/keeper_test.go @@ -27,18 +27,17 @@ var address1 = "cosmos1ghekyjucln7y67ntx7cf27m9dpuxxemn4c8g4r" type KeeperTestSuite struct { suite.Suite - cdc codec.Codec - ctx sdk.Context - govKeeper *keeper.Keeper - acctKeeper *govtestutil.MockAccountKeeper - bankKeeper *govtestutil.MockBankKeeper - stakingKeeper *govtestutil.MockStakingKeeper - distKeeper *govtestutil.MockDistributionKeeper - queryClient v1.QueryClient - legacyQueryClient v1beta1.QueryClient - addrs []sdk.AccAddress - msgSrvr v1.MsgServer - legacyMsgSrvr v1beta1.MsgServer + cdc codec.Codec + ctx sdk.Context + govKeeper *keeper.Keeper + acctKeeper *govtestutil.MockAccountKeeper + bankKeeper *govtestutil.MockBankKeeper + stakingKeeper *govtestutil.MockStakingKeeper + distKeeper *govtestutil.MockDistributionKeeper + queryClient v1.QueryClient + addrs []sdk.AccAddress + msgSrvr v1.MsgServer + legacyMsgSrvr v1beta1.MsgServer } func (suite *KeeperTestSuite) SetupSuite() { @@ -58,10 +57,7 @@ func (suite *KeeperTestSuite) reset() { queryHelper := baseapp.NewQueryServerTestHelper(ctx, encCfg.InterfaceRegistry) v1.RegisterQueryServer(queryHelper, keeper.NewQueryServer(govKeeper)) - legacyQueryHelper := baseapp.NewQueryServerTestHelper(ctx, encCfg.InterfaceRegistry) - v1beta1.RegisterQueryServer(legacyQueryHelper, keeper.NewLegacyQueryServer(govKeeper)) queryClient := v1.NewQueryClient(queryHelper) - legacyQueryClient := v1beta1.NewQueryClient(legacyQueryHelper) suite.ctx = ctx suite.govKeeper = govKeeper @@ -71,7 +67,6 @@ func (suite *KeeperTestSuite) reset() { suite.distKeeper = distKeeper suite.cdc = encCfg.Codec suite.queryClient = queryClient - suite.legacyQueryClient = legacyQueryClient suite.msgSrvr = keeper.NewMsgServerImpl(suite.govKeeper) suite.legacyMsgSrvr = keeper.NewLegacyMsgServerImpl(govAcct.String(), suite.msgSrvr) diff --git a/x/gov/keeper/migrations.go b/x/gov/keeper/migrations.go index 508d8292b96a..d59a01dfdb53 100644 --- a/x/gov/keeper/migrations.go +++ b/x/gov/keeper/migrations.go @@ -1,44 +1,13 @@ package keeper -import ( - sdk "github.com/cosmos/cosmos-sdk/types" - "github.com/cosmos/cosmos-sdk/x/gov/exported" - v2 "github.com/cosmos/cosmos-sdk/x/gov/migrations/v2" - v3 "github.com/cosmos/cosmos-sdk/x/gov/migrations/v3" - v4 "github.com/cosmos/cosmos-sdk/x/gov/migrations/v4" - v5 "github.com/cosmos/cosmos-sdk/x/gov/migrations/v5" -) - // Migrator is a struct for handling in-place store migrations. type Migrator struct { - keeper *Keeper - legacySubspace exported.ParamSubspace + keeper *Keeper } // NewMigrator returns a new Migrator. -func NewMigrator(keeper *Keeper, legacySubspace exported.ParamSubspace) Migrator { +func NewMigrator(keeper *Keeper) Migrator { return Migrator{ - keeper: keeper, - legacySubspace: legacySubspace, + keeper: keeper, } } - -// Migrate1to2 migrates from version 1 to 2. -func (m Migrator) Migrate1to2(ctx sdk.Context) error { - return v2.MigrateStore(ctx, m.keeper.storeService, m.keeper.cdc) -} - -// Migrate2to3 migrates from version 2 to 3. -func (m Migrator) Migrate2to3(ctx sdk.Context) error { - return v3.MigrateStore(ctx, m.keeper.storeService, m.keeper.cdc) -} - -// Migrate3to4 migrates from version 3 to 4. -func (m Migrator) Migrate3to4(ctx sdk.Context) error { - return v4.MigrateStore(ctx, m.keeper.storeService, m.legacySubspace, m.keeper.cdc) -} - -// Migrate4to5 migrates from version 4 to 5. -func (m Migrator) Migrate4to5(ctx sdk.Context) error { - return v5.MigrateStore(ctx, m.keeper.storeService, m.keeper.cdc, m.keeper.Constitution) -} diff --git a/x/gov/migrations/v1/types.go b/x/gov/migrations/v1/types.go deleted file mode 100644 index 604e9fefdbb1..000000000000 --- a/x/gov/migrations/v1/types.go +++ /dev/null @@ -1,163 +0,0 @@ -package v1 - -// Package v1 (v0.40) is copy-pasted from: -// https://github.com/cosmos/cosmos-sdk/blob/v0.41.0/x/gov/types/keys.go - -import ( - "encoding/binary" - "time" - - sdk "github.com/cosmos/cosmos-sdk/types" - "github.com/cosmos/cosmos-sdk/types/kv" - v1auth "github.com/cosmos/cosmos-sdk/x/auth/migrations/v1" -) - -const ( - // ModuleName is the name of the module - ModuleName = "gov" - - // StoreKey is the store key string for gov - StoreKey = ModuleName - - // RouterKey is the message route for gov - RouterKey = ModuleName - - // QuerierRoute is the querier route for gov - QuerierRoute = ModuleName -) - -// Keys for governance store -// Items are stored with the following key: values -// -// - 0x00: Proposal -// -// - 0x01: activeProposalID -// -// - 0x02: inactiveProposalID -// -// - 0x03: nextProposalID -// -// - 0x10: Deposit -// -// - 0x20: Voter -var ( - ProposalsKeyPrefix = []byte{0x00} - ActiveProposalQueuePrefix = []byte{0x01} - InactiveProposalQueuePrefix = []byte{0x02} - ProposalIDKey = []byte{0x03} - - DepositsKeyPrefix = []byte{0x10} - - VotesKeyPrefix = []byte{0x20} -) - -var lenTime = len(sdk.FormatTimeBytes(time.Now())) - -// GetProposalIDBytes returns the byte representation of the proposalID -func GetProposalIDBytes(proposalID uint64) (proposalIDBz []byte) { - proposalIDBz = make([]byte, 8) - binary.BigEndian.PutUint64(proposalIDBz, proposalID) - return proposalIDBz -} - -// GetProposalIDFromBytes returns proposalID in uint64 format from a byte array -func GetProposalIDFromBytes(bz []byte) (proposalID uint64) { - return binary.BigEndian.Uint64(bz) -} - -// ProposalKey gets a specific proposal from the store -func ProposalKey(proposalID uint64) []byte { - return append(ProposalsKeyPrefix, GetProposalIDBytes(proposalID)...) -} - -// ActiveProposalByTimeKey gets the active proposal queue key by endTime -func ActiveProposalByTimeKey(endTime time.Time) []byte { - return append(ActiveProposalQueuePrefix, sdk.FormatTimeBytes(endTime)...) -} - -// ActiveProposalQueueKey returns the key for a proposalID in the activeProposalQueue -func ActiveProposalQueueKey(proposalID uint64, endTime time.Time) []byte { - return append(ActiveProposalByTimeKey(endTime), GetProposalIDBytes(proposalID)...) -} - -// InactiveProposalByTimeKey gets the inactive proposal queue key by endTime -func InactiveProposalByTimeKey(endTime time.Time) []byte { - return append(InactiveProposalQueuePrefix, sdk.FormatTimeBytes(endTime)...) -} - -// InactiveProposalQueueKey returns the key for a proposalID in the inactiveProposalQueue -func InactiveProposalQueueKey(proposalID uint64, endTime time.Time) []byte { - return append(InactiveProposalByTimeKey(endTime), GetProposalIDBytes(proposalID)...) -} - -// DepositsKey gets the first part of the deposits key based on the proposalID -func DepositsKey(proposalID uint64) []byte { - return append(DepositsKeyPrefix, GetProposalIDBytes(proposalID)...) -} - -// DepositKey key of a specific deposit from the store -func DepositKey(proposalID uint64, depositorAddr sdk.AccAddress) []byte { - return append(DepositsKey(proposalID), depositorAddr.Bytes()...) -} - -// VotesKey gets the first part of the votes key based on the proposalID -func VotesKey(proposalID uint64) []byte { - return append(VotesKeyPrefix, GetProposalIDBytes(proposalID)...) -} - -// VoteKey key of a specific vote from the store -func VoteKey(proposalID uint64, voterAddr sdk.AccAddress) []byte { - return append(VotesKey(proposalID), voterAddr.Bytes()...) -} - -// Split keys function; used for iterators - -// SplitProposalKey split the proposal key and returns the proposal id -func SplitProposalKey(key []byte) (proposalID uint64) { - kv.AssertKeyLength(key[1:], 8) - - return GetProposalIDFromBytes(key[1:]) -} - -// SplitActiveProposalQueueKey split the active proposal key and returns the proposal id and endTime -func SplitActiveProposalQueueKey(key []byte) (proposalID uint64, endTime time.Time) { - return splitKeyWithTime(key) -} - -// SplitInactiveProposalQueueKey split the inactive proposal key and returns the proposal id and endTime -func SplitInactiveProposalQueueKey(key []byte) (proposalID uint64, endTime time.Time) { - return splitKeyWithTime(key) -} - -// SplitKeyDeposit split the deposits key and returns the proposal id and depositor address -func SplitKeyDeposit(key []byte) (proposalID uint64, depositorAddr sdk.AccAddress) { - return splitKeyWithAddress(key) -} - -// SplitKeyVote split the votes key and returns the proposal id and voter address -func SplitKeyVote(key []byte) (proposalID uint64, voterAddr sdk.AccAddress) { - return splitKeyWithAddress(key) -} - -// private functions - -func splitKeyWithTime(key []byte) (proposalID uint64, endTime time.Time) { - kv.AssertKeyLength(key[1:], 8+lenTime) - - endTime, err := sdk.ParseTimeBytes(key[1 : 1+lenTime]) - if err != nil { - panic(err) - } - - proposalID = GetProposalIDFromBytes(key[1+lenTime:]) - return proposalID, endTime -} - -func splitKeyWithAddress(key []byte) (proposalID uint64, addr sdk.AccAddress) { - kv.AssertKeyLength(key[1:], 8+v1auth.AddrLen) - - kv.AssertKeyAtLeastLength(key, 10) - proposalID = GetProposalIDFromBytes(key[1:9]) - addr = sdk.AccAddress(key[9:]) - return proposalID, addr -} diff --git a/x/gov/migrations/v2/json.go b/x/gov/migrations/v2/json.go deleted file mode 100644 index 5d44a0de0ff2..000000000000 --- a/x/gov/migrations/v2/json.go +++ /dev/null @@ -1,31 +0,0 @@ -package v2 - -import ( - "github.com/cosmos/cosmos-sdk/x/gov/types/v1beta1" -) - -// migrateJSONWeightedVotes migrates the ADR-037 weighted votes. -func migrateJSONWeightedVotes(oldVotes v1beta1.Votes) v1beta1.Votes { - newVotes := make(v1beta1.Votes, len(oldVotes)) - for i, oldVote := range oldVotes { - newVotes[i] = migrateVote(oldVote) - } - - return newVotes -} - -// MigrateJSON accepts exported v1 (v0.40) x/gov genesis state and migrates it to -// v2 (v0.43) x/gov genesis state. The migration includes: -// -// - Gov weighted votes. -func MigrateJSON(oldState *v1beta1.GenesisState) *v1beta1.GenesisState { - return &v1beta1.GenesisState{ - StartingProposalId: oldState.StartingProposalId, - Deposits: oldState.Deposits, - Votes: migrateJSONWeightedVotes(oldState.Votes), - Proposals: oldState.Proposals, - DepositParams: oldState.DepositParams, - VotingParams: oldState.VotingParams, - TallyParams: oldState.TallyParams, - } -} diff --git a/x/gov/migrations/v2/json_test.go b/x/gov/migrations/v2/json_test.go deleted file mode 100644 index fb26e080e06d..000000000000 --- a/x/gov/migrations/v2/json_test.go +++ /dev/null @@ -1,125 +0,0 @@ -package v2_test - -import ( - "encoding/json" - "testing" - - "github.com/stretchr/testify/require" - - "github.com/cosmos/cosmos-sdk/client" - sdk "github.com/cosmos/cosmos-sdk/types" - moduletestutil "github.com/cosmos/cosmos-sdk/types/module/testutil" - v2 "github.com/cosmos/cosmos-sdk/x/gov/migrations/v2" - "github.com/cosmos/cosmos-sdk/x/gov/types/v1beta1" -) - -func TestMigrateJSON(t *testing.T) { - encodingConfig := moduletestutil.MakeTestEncodingConfig() - clientCtx := client.Context{}. - WithInterfaceRegistry(encodingConfig.InterfaceRegistry). - WithTxConfig(encodingConfig.TxConfig). - WithCodec(encodingConfig.Codec) - - voter, err := sdk.AccAddressFromBech32("cosmos1fl48vsnmsdzcv85q5d2q4z5ajdha8yu34mf0eh") - require.NoError(t, err) - govGenState := &v1beta1.GenesisState{ - Votes: v1beta1.Votes{ - v1beta1.Vote{ProposalId: 1, Voter: voter.String(), Option: v1beta1.OptionAbstain}, - v1beta1.Vote{ProposalId: 2, Voter: voter.String(), Option: v1beta1.OptionEmpty}, - v1beta1.Vote{ProposalId: 3, Voter: voter.String(), Option: v1beta1.OptionNo}, - v1beta1.Vote{ProposalId: 4, Voter: voter.String(), Option: v1beta1.OptionNoWithVeto}, - v1beta1.Vote{ProposalId: 5, Voter: voter.String(), Option: v1beta1.OptionYes}, - }, - } - - migrated := v2.MigrateJSON(govGenState) - - bz, err := clientCtx.Codec.MarshalJSON(migrated) - require.NoError(t, err) - - // Indent the JSON bz correctly. - var jsonObj map[string]any - err = json.Unmarshal(bz, &jsonObj) - require.NoError(t, err) - indentedBz, err := json.MarshalIndent(jsonObj, "", "\t") - require.NoError(t, err) - - // Make sure about: - // - Votes are all ADR-037 weighted votes with weight 1. - expected := `{ - "deposit_params": { - "max_deposit_period": "0s", - "min_deposit": [] - }, - "deposits": [], - "proposals": [], - "starting_proposal_id": "0", - "tally_params": { - "quorum": "0", - "threshold": "0", - "veto_threshold": "0" - }, - "votes": [ - { - "option": "VOTE_OPTION_UNSPECIFIED", - "options": [ - { - "option": "VOTE_OPTION_ABSTAIN", - "weight": "1.000000000000000000" - } - ], - "proposal_id": "1", - "voter": "cosmos1fl48vsnmsdzcv85q5d2q4z5ajdha8yu34mf0eh" - }, - { - "option": "VOTE_OPTION_UNSPECIFIED", - "options": [ - { - "option": "VOTE_OPTION_UNSPECIFIED", - "weight": "1.000000000000000000" - } - ], - "proposal_id": "2", - "voter": "cosmos1fl48vsnmsdzcv85q5d2q4z5ajdha8yu34mf0eh" - }, - { - "option": "VOTE_OPTION_UNSPECIFIED", - "options": [ - { - "option": "VOTE_OPTION_NO", - "weight": "1.000000000000000000" - } - ], - "proposal_id": "3", - "voter": "cosmos1fl48vsnmsdzcv85q5d2q4z5ajdha8yu34mf0eh" - }, - { - "option": "VOTE_OPTION_UNSPECIFIED", - "options": [ - { - "option": "VOTE_OPTION_NO_WITH_VETO", - "weight": "1.000000000000000000" - } - ], - "proposal_id": "4", - "voter": "cosmos1fl48vsnmsdzcv85q5d2q4z5ajdha8yu34mf0eh" - }, - { - "option": "VOTE_OPTION_UNSPECIFIED", - "options": [ - { - "option": "VOTE_OPTION_YES", - "weight": "1.000000000000000000" - } - ], - "proposal_id": "5", - "voter": "cosmos1fl48vsnmsdzcv85q5d2q4z5ajdha8yu34mf0eh" - } - ], - "voting_params": { - "voting_period": "0s" - } -}` - - require.Equal(t, expected, string(indentedBz)) -} diff --git a/x/gov/migrations/v2/keys.go b/x/gov/migrations/v2/keys.go deleted file mode 100644 index fcedde0a5f46..000000000000 --- a/x/gov/migrations/v2/keys.go +++ /dev/null @@ -1,6 +0,0 @@ -package v2 - -const ( - // ModuleName is the name of the module - ModuleName = "gov" -) diff --git a/x/gov/migrations/v2/store.go b/x/gov/migrations/v2/store.go deleted file mode 100644 index 151df2f55bd4..000000000000 --- a/x/gov/migrations/v2/store.go +++ /dev/null @@ -1,102 +0,0 @@ -package v2 - -import ( - "fmt" - - corestoretypes "cosmossdk.io/core/store" - "cosmossdk.io/store/prefix" - storetypes "cosmossdk.io/store/types" - - "github.com/cosmos/cosmos-sdk/codec" - "github.com/cosmos/cosmos-sdk/runtime" - sdk "github.com/cosmos/cosmos-sdk/types" - "github.com/cosmos/cosmos-sdk/types/address" - "github.com/cosmos/cosmos-sdk/x/gov/types" - "github.com/cosmos/cosmos-sdk/x/gov/types/v1beta1" -) - -const proposalIDLen = 8 - -// migratePrefixProposalAddress is a helper function that migrates all keys of format: -// -// into format: -// -func migratePrefixProposalAddress(store corestoretypes.KVStore, prefixBz []byte) error { - oldStore := prefix.NewStore(runtime.KVStoreAdapter(store), prefixBz) - - oldStoreIter := oldStore.Iterator(nil, nil) - defer oldStoreIter.Close() - - for ; oldStoreIter.Valid(); oldStoreIter.Next() { - proposalID := oldStoreIter.Key()[:proposalIDLen] - addr := oldStoreIter.Key()[proposalIDLen:] - newStoreKey := append(append(prefixBz, proposalID...), address.MustLengthPrefix(addr)...) - - // Set new key on store. Values don't change. - err := store.Set(newStoreKey, oldStoreIter.Value()) - if err != nil { - return err - } - oldStore.Delete(oldStoreIter.Key()) - } - return nil -} - -// migrateStoreWeightedVotes migrates a legacy vote to an ADR-037 weighted vote. -// Important: the `oldVote` has its `Option` field set, whereas the new weighted -// vote has its `Options` field set. -func migrateVote(oldVote v1beta1.Vote) v1beta1.Vote { - return v1beta1.Vote{ - ProposalId: oldVote.ProposalId, - Voter: oldVote.Voter, - Options: v1beta1.NewNonSplitVoteOption(oldVote.Option), - } -} - -// migrateStoreWeightedVotes migrates in-place all legacy votes to ADR-037 weighted votes. -func migrateStoreWeightedVotes(store corestoretypes.KVStore, cdc codec.BinaryCodec) error { - iterator := storetypes.KVStorePrefixIterator(runtime.KVStoreAdapter(store), types.VotesKeyPrefix) - - defer iterator.Close() - for ; iterator.Valid(); iterator.Next() { - var oldVote v1beta1.Vote - err := cdc.Unmarshal(iterator.Value(), &oldVote) - if err != nil { - return err - } - - newVote := migrateVote(oldVote) - fmt.Println("migrateStoreWeightedVotes newVote=", newVote) - bz, err := cdc.Marshal(&newVote) - if err != nil { - return err - } - - err = store.Set(iterator.Key(), bz) - if err != nil { - return err - } - } - - return nil -} - -// MigrateStore performs in-place store migrations from v1 (v0.40) to v2 (v0.43). The -// migration includes: -// -// - Change addresses to be length-prefixed. -// - Change all legacy votes to ADR-037 weighted votes. -func MigrateStore(ctx sdk.Context, storeService corestoretypes.KVStoreService, cdc codec.BinaryCodec) error { - store := storeService.OpenKVStore(ctx) - err := migratePrefixProposalAddress(store, types.DepositsKeyPrefix) - if err != nil { - return err - } - - err = migratePrefixProposalAddress(store, types.VotesKeyPrefix) - if err != nil { - return err - } - - return migrateStoreWeightedVotes(store, cdc) -} diff --git a/x/gov/migrations/v2/store_test.go b/x/gov/migrations/v2/store_test.go deleted file mode 100644 index 5033f1e3ec23..000000000000 --- a/x/gov/migrations/v2/store_test.go +++ /dev/null @@ -1,116 +0,0 @@ -package v2_test - -import ( - "bytes" - "testing" - "time" - - "github.com/stretchr/testify/require" - - "cosmossdk.io/math" - storetypes "cosmossdk.io/store/types" - - "github.com/cosmos/cosmos-sdk/runtime" - "github.com/cosmos/cosmos-sdk/testutil" - "github.com/cosmos/cosmos-sdk/testutil/testdata" - sdk "github.com/cosmos/cosmos-sdk/types" - "github.com/cosmos/cosmos-sdk/types/address" - moduletestutil "github.com/cosmos/cosmos-sdk/types/module/testutil" - v1 "github.com/cosmos/cosmos-sdk/x/gov/migrations/v1" - v2 "github.com/cosmos/cosmos-sdk/x/gov/migrations/v2" - "github.com/cosmos/cosmos-sdk/x/gov/types" - "github.com/cosmos/cosmos-sdk/x/gov/types/v1beta1" -) - -func TestMigrateStore(t *testing.T) { - cdc := moduletestutil.MakeTestEncodingConfig().Codec - govKey := storetypes.NewKVStoreKey("gov") - ctx := testutil.DefaultContext(govKey, storetypes.NewTransientStoreKey("transient_test")) - store := ctx.KVStore(govKey) - - _, _, addr1 := testdata.KeyTestPubAddr() - proposalID := uint64(6) - now := time.Now() - // Use dummy value for keys where we don't test values. - dummyValue := []byte("foo") - // Use real values for votes, as we're testing weighted votes. - oldVote := v1beta1.Vote{ProposalId: 1, Voter: "foobar", Option: v1beta1.OptionNoWithVeto} - oldVoteValue := cdc.MustMarshal(&oldVote) - newVote := v1beta1.Vote{ProposalId: 1, Voter: "foobar", Options: v1beta1.WeightedVoteOptions{{Option: v1beta1.OptionNoWithVeto, Weight: math.LegacyNewDec(1)}}} - newVoteValue := cdc.MustMarshal(&newVote) - - testCases := []struct { - name string - oldKey, oldValue, newKey, newValue []byte - }{ - { - "ProposalKey", - v1.ProposalKey(proposalID), dummyValue, - append(types.ProposalsKeyPrefix, sdk.Uint64ToBigEndian(proposalID)...), dummyValue, - }, - { - "ActiveProposalQueue", - v1.ActiveProposalQueueKey(proposalID, now), dummyValue, - activeProposalQueueKey(proposalID, now), dummyValue, - }, - { - "InactiveProposalQueue", - v1.InactiveProposalQueueKey(proposalID, now), dummyValue, - inactiveProposalQueueKey(proposalID, now), dummyValue, - }, - { - "ProposalIDKey", - v1.ProposalIDKey, dummyValue, - types.ProposalIDKey, dummyValue, - }, - { - "DepositKey", - v1.DepositKey(proposalID, addr1), dummyValue, - depositKey(proposalID, addr1), dummyValue, - }, - { - "VotesKeyPrefix", - v1.VoteKey(proposalID, addr1), oldVoteValue, - voteKey(proposalID, addr1), newVoteValue, - }, - } - - // Set all the old keys to the store - for _, tc := range testCases { - store.Set(tc.oldKey, tc.oldValue) - } - - // Run migration - storeService := runtime.NewKVStoreService(govKey) - err := v2.MigrateStore(ctx, storeService, cdc) - require.NoError(t, err) - - // Make sure the new keys are set and old keys are deleted. - for _, tc := range testCases { - t.Run(tc.name, func(t *testing.T) { - if !bytes.Equal(tc.oldKey, tc.newKey) { - require.Nil(t, store.Get(tc.oldKey)) - } - require.Equal(t, tc.newValue, store.Get(tc.newKey)) - }) - } -} - -// TODO(tip): remove all the functions below once we delete the migrations - -func depositKey(proposalID uint64, depositorAddr sdk.AccAddress) []byte { - return append(append(types.DepositsKeyPrefix, sdk.Uint64ToBigEndian(proposalID)...), address.MustLengthPrefix(depositorAddr.Bytes())...) -} - -func voteKey(proposalID uint64, addr sdk.AccAddress) []byte { - return append(append(types.VotesKeyPrefix, sdk.Uint64ToBigEndian(proposalID)...), address.MustLengthPrefix(addr.Bytes())...) -} - -func activeProposalQueueKey(proposalID uint64, endTime time.Time) []byte { - return append(append(types.ActiveProposalQueuePrefix, sdk.FormatTimeBytes(endTime)...), sdk.Uint64ToBigEndian(proposalID)...) -} - -// InactiveProposalQueueKey returns the key for a proposalID in the inactiveProposalQueue -func inactiveProposalQueueKey(proposalID uint64, endTime time.Time) []byte { - return append(append(types.InactiveProposalQueuePrefix, sdk.FormatTimeBytes(endTime)...), sdk.Uint64ToBigEndian(proposalID)...) -} diff --git a/x/gov/migrations/v3/convert.go b/x/gov/migrations/v3/convert.go deleted file mode 100644 index d584ac5eced5..000000000000 --- a/x/gov/migrations/v3/convert.go +++ /dev/null @@ -1,244 +0,0 @@ -package v3 - -import ( - "fmt" - - "cosmossdk.io/math" - - codectypes "github.com/cosmos/cosmos-sdk/codec/types" - "github.com/cosmos/cosmos-sdk/types" - sdkerrors "github.com/cosmos/cosmos-sdk/types/errors" - authtypes "github.com/cosmos/cosmos-sdk/x/auth/types" - v1 "github.com/cosmos/cosmos-sdk/x/gov/types/v1" - "github.com/cosmos/cosmos-sdk/x/gov/types/v1beta1" -) - -// ConvertToLegacyProposal takes a new proposal and attempts to convert it to the -// legacy proposal format. This conversion is best effort. New proposal types that -// don't have a legacy message will return a "nil" content. -// Returns error when the amount of messages in `proposal` is different than one. -func ConvertToLegacyProposal(proposal v1.Proposal) (v1beta1.Proposal, error) { - var err error - legacyProposal := v1beta1.Proposal{ - ProposalId: proposal.Id, - Status: v1beta1.ProposalStatus(proposal.Status), - TotalDeposit: types.NewCoins(proposal.TotalDeposit...), - } - - legacyProposal.FinalTallyResult, err = ConvertToLegacyTallyResult(proposal.FinalTallyResult) - if err != nil { - return v1beta1.Proposal{}, err - } - - if proposal.VotingStartTime != nil { - legacyProposal.VotingStartTime = *proposal.VotingStartTime - } - - if proposal.VotingEndTime != nil { - legacyProposal.VotingEndTime = *proposal.VotingEndTime - } - - if proposal.SubmitTime != nil { - legacyProposal.SubmitTime = *proposal.SubmitTime - } - - if proposal.DepositEndTime != nil { - legacyProposal.DepositEndTime = *proposal.DepositEndTime - } - - msgs, err := proposal.GetMsgs() - if err != nil { - return v1beta1.Proposal{}, err - } - if len(msgs) != 1 { - return v1beta1.Proposal{}, sdkerrors.ErrInvalidType.Wrap("can't convert a gov/v1 Proposal to gov/v1beta1 Proposal when amount of proposal messages not exactly one") - } - if legacyMsg, ok := msgs[0].(*v1.MsgExecLegacyContent); ok { - // check that the content struct can be unmarshalled - _, err := v1.LegacyContentFromMessage(legacyMsg) - if err != nil { - return v1beta1.Proposal{}, err - } - legacyProposal.Content = legacyMsg.Content - return legacyProposal, nil - } - // hack to fill up the content with the first message - // this is to support clients that have not yet (properly) use gov/v1 endpoints - // https://github.com/cosmos/cosmos-sdk/issues/14334 - // VerifyBasic assures that we have at least one message. - legacyProposal.Content, err = codectypes.NewAnyWithValue(msgs[0]) - - return legacyProposal, err -} - -func ConvertToLegacyTallyResult(tally *v1.TallyResult) (v1beta1.TallyResult, error) { - yes, ok := math.NewIntFromString(tally.YesCount) - if !ok { - return v1beta1.TallyResult{}, fmt.Errorf("unable to convert yes tally string (%s) to int", tally.YesCount) - } - no, ok := math.NewIntFromString(tally.NoCount) - if !ok { - return v1beta1.TallyResult{}, fmt.Errorf("unable to convert no tally string (%s) to int", tally.NoCount) - } - veto, ok := math.NewIntFromString(tally.NoWithVetoCount) - if !ok { - return v1beta1.TallyResult{}, fmt.Errorf("unable to convert no with veto tally string (%s) to int", tally.NoWithVetoCount) - } - abstain, ok := math.NewIntFromString(tally.AbstainCount) - if !ok { - return v1beta1.TallyResult{}, fmt.Errorf("unable to convert abstain tally string (%s) to int", tally.AbstainCount) - } - - return v1beta1.TallyResult{ - Yes: yes, - No: no, - NoWithVeto: veto, - Abstain: abstain, - }, nil -} - -func ConvertToLegacyVote(vote v1.Vote) (v1beta1.Vote, error) { - options, err := ConvertToLegacyVoteOptions(vote.Options) - if err != nil { - return v1beta1.Vote{}, err - } - return v1beta1.Vote{ - ProposalId: vote.ProposalId, - Voter: vote.Voter, - Options: options, - }, nil -} - -func ConvertToLegacyVoteOptions(voteOptions []*v1.WeightedVoteOption) ([]v1beta1.WeightedVoteOption, error) { - options := make([]v1beta1.WeightedVoteOption, len(voteOptions)) - for i, option := range voteOptions { - weight, err := math.LegacyNewDecFromStr(option.Weight) - if err != nil { - return options, err - } - options[i] = v1beta1.WeightedVoteOption{ - Option: v1beta1.VoteOption(option.Option), - Weight: weight, - } - } - return options, nil -} - -func ConvertToLegacyDeposit(deposit *v1.Deposit) v1beta1.Deposit { - return v1beta1.Deposit{ - ProposalId: deposit.ProposalId, - Depositor: deposit.Depositor, - Amount: types.NewCoins(deposit.Amount...), - } -} - -func convertToNewDeposits(oldDeps v1beta1.Deposits) v1.Deposits { - newDeps := make([]*v1.Deposit, len(oldDeps)) - for i, oldDep := range oldDeps { - newDeps[i] = &v1.Deposit{ - ProposalId: oldDep.ProposalId, - Depositor: oldDep.Depositor, - Amount: oldDep.Amount, - } - } - - return newDeps -} - -func convertToNewVotes(oldVotes v1beta1.Votes) (v1.Votes, error) { - newVotes := make([]*v1.Vote, len(oldVotes)) - for i, oldVote := range oldVotes { - var newWVOs []*v1.WeightedVoteOption - - // We deprecated Vote.Option in v043. However, it might still be set. - // - if only Options is set, or both Option & Options are set, we read from Options, - // - if Options is not set, and Option is set, we read from Option, - // - if none are set, we throw error. - switch { - case oldVote.Options != nil: - newWVOs = make([]*v1.WeightedVoteOption, len(oldVote.Options)) - for j, oldWVO := range oldVote.Options { - newWVOs[j] = v1.NewWeightedVoteOption(v1.VoteOption(oldWVO.Option), oldWVO.Weight) - } - - case oldVote.Option != v1beta1.OptionEmpty: - newWVOs = v1.NewNonSplitVoteOption(v1.VoteOption(oldVote.Option)) - - default: - return nil, fmt.Errorf("vote does not have neither InterfaceRegistryOptions nor Option") - } - - newVotes[i] = &v1.Vote{ - ProposalId: oldVote.ProposalId, - Voter: oldVote.Voter, - Options: newWVOs, - } - } - - return newVotes, nil -} - -func convertToNewDepParams(oldDepParams v1beta1.DepositParams) v1.DepositParams { - return v1.DepositParams{ - MinDeposit: oldDepParams.MinDeposit, - MaxDepositPeriod: &oldDepParams.MaxDepositPeriod, - } -} - -func convertToNewVotingParams(oldVoteParams v1beta1.VotingParams) v1.VotingParams { - return v1.VotingParams{ - VotingPeriod: &oldVoteParams.VotingPeriod, - } -} - -func convertToNewTallyParams(oldTallyParams v1beta1.TallyParams) v1.TallyParams { - return v1.TallyParams{ - Quorum: oldTallyParams.Quorum.String(), - Threshold: oldTallyParams.Threshold.String(), - VetoThreshold: oldTallyParams.VetoThreshold.String(), - } -} - -func convertToNewProposal(oldProp v1beta1.Proposal) (v1.Proposal, error) { - msg, err := v1.NewLegacyContent(oldProp.GetContent(), authtypes.NewModuleAddress(ModuleName).String()) - if err != nil { - return v1.Proposal{}, err - } - msgAny, err := codectypes.NewAnyWithValue(msg) - if err != nil { - return v1.Proposal{}, err - } - - return v1.Proposal{ - Id: oldProp.ProposalId, - Messages: []*codectypes.Any{msgAny}, - Status: v1.ProposalStatus(oldProp.Status), - FinalTallyResult: &v1.TallyResult{ - YesCount: oldProp.FinalTallyResult.Yes.String(), - NoCount: oldProp.FinalTallyResult.No.String(), - AbstainCount: oldProp.FinalTallyResult.Abstain.String(), - NoWithVetoCount: oldProp.FinalTallyResult.NoWithVeto.String(), - }, - SubmitTime: &oldProp.SubmitTime, - DepositEndTime: &oldProp.DepositEndTime, - TotalDeposit: oldProp.TotalDeposit, - VotingStartTime: &oldProp.VotingStartTime, - VotingEndTime: &oldProp.VotingEndTime, - Title: oldProp.GetContent().GetTitle(), - Summary: oldProp.GetContent().GetDescription(), - }, nil -} - -func convertToNewProposals(oldProps v1beta1.Proposals) (v1.Proposals, error) { - newProps := make([]*v1.Proposal, len(oldProps)) - for i, oldProp := range oldProps { - p, err := convertToNewProposal(oldProp) - if err != nil { - return nil, err - } - - newProps[i] = &p - } - - return newProps, nil -} diff --git a/x/gov/migrations/v3/convert_test.go b/x/gov/migrations/v3/convert_test.go deleted file mode 100644 index fb339ea9dd1b..000000000000 --- a/x/gov/migrations/v3/convert_test.go +++ /dev/null @@ -1,213 +0,0 @@ -package v3_test - -import ( - "testing" - "time" - - "github.com/stretchr/testify/require" - - "cosmossdk.io/math" - - sdk "github.com/cosmos/cosmos-sdk/types" - sdkerrors "github.com/cosmos/cosmos-sdk/types/errors" - "github.com/cosmos/cosmos-sdk/types/tx" - v3 "github.com/cosmos/cosmos-sdk/x/gov/migrations/v3" - v1 "github.com/cosmos/cosmos-sdk/x/gov/types/v1" - "github.com/cosmos/cosmos-sdk/x/gov/types/v1beta1" -) - -func TestConvertToLegacyProposal(t *testing.T) { - propTime := time.Unix(1e9, 0) - legacyContentMsg, err := v1.NewLegacyContent(v1beta1.NewTextProposal("title", "description"), "cosmos1fl48vsnmsdzcv85q5d2q4z5ajdha8yu34mf0eh") - require.NoError(t, err) - msgs := []sdk.Msg{legacyContentMsg} - msgsAny, err := tx.SetMsgs(msgs) - require.NoError(t, err) - proposal := v1.Proposal{ - Id: 1, - Status: v1.StatusDepositPeriod, - Messages: msgsAny, - SubmitTime: &propTime, - DepositEndTime: &propTime, - VotingStartTime: &propTime, - VotingEndTime: &propTime, - Metadata: "proposal metadata", - } - - testCases := map[string]struct { - tallyResult v1.TallyResult - expErr bool - }{ - "valid": { - tallyResult: v1.EmptyTallyResult(), - }, - "invalid final tally result": { - tallyResult: v1.TallyResult{}, - expErr: true, - }, - } - - for name, tc := range testCases { - t.Run(name, func(t *testing.T) { - proposal.FinalTallyResult = &tc.tallyResult - v1beta1Proposal, err := v3.ConvertToLegacyProposal(proposal) - if tc.expErr { - require.Error(t, err) - } else { - require.NoError(t, err) - require.Equal(t, v1beta1Proposal.ProposalId, proposal.Id) - require.Equal(t, v1beta1Proposal.VotingStartTime, *proposal.VotingStartTime) - require.Equal(t, v1beta1Proposal.VotingEndTime, *proposal.VotingEndTime) - require.Equal(t, v1beta1Proposal.SubmitTime, *proposal.SubmitTime) - require.Equal(t, v1beta1Proposal.DepositEndTime, *proposal.DepositEndTime) - require.Equal(t, v1beta1Proposal.FinalTallyResult.Yes, math.NewInt(0)) - require.Equal(t, v1beta1Proposal.FinalTallyResult.No, math.NewInt(0)) - require.Equal(t, v1beta1Proposal.FinalTallyResult.NoWithVeto, math.NewInt(0)) - require.Equal(t, v1beta1Proposal.FinalTallyResult.Abstain, math.NewInt(0)) - tp, ok := v1beta1Proposal.Content.GetCachedValue().(*v1beta1.TextProposal) - require.Truef(t, ok, "expected *TextProposal, got %T", v1beta1Proposal.Content.GetCachedValue()) - require.Equal(t, tp.Title, "title") - require.Equal(t, tp.Description, "description") - } - }) - } -} - -func TestConvertToLegacyProposalContent(t *testing.T) { - msg := v1.MsgCancelProposal{ProposalId: 1, Proposer: "cosmos1fl48vsnmsdzcv85q5d2q4z5ajdha8yu34mf0eh"} - msgsAny, err := tx.SetMsgs([]sdk.Msg{&msg}) - require.NoError(t, err) - tallyResult := v1.EmptyTallyResult() - proposal := v1.Proposal{ - Id: 1, - Status: v1.StatusDepositPeriod, - Messages: msgsAny, - Metadata: "proposal metadata", - FinalTallyResult: &tallyResult, - } - - legacyP, err := v3.ConvertToLegacyProposal(proposal) - require.NoError(t, err) - tp, ok := legacyP.Content.GetCachedValue().(*v1.MsgCancelProposal) - require.Truef(t, ok, "expected *MsgCancelProposal, got %T", legacyP.Content.GetCachedValue()) - require.Equal(t, &msg, tp) - - // more than one message is not supported - proposal.Messages, err = tx.SetMsgs([]sdk.Msg{&msg, &msg}) - require.NoError(t, err) - _, err = v3.ConvertToLegacyProposal(proposal) - require.ErrorIs(t, sdkerrors.ErrInvalidType, err) - - // zero messages is not supported - proposal.Messages = nil - _, err = v3.ConvertToLegacyProposal(proposal) - require.ErrorIs(t, sdkerrors.ErrInvalidType, err) -} - -func TestConvertToLegacyTallyResult(t *testing.T) { - tallyResult := v1.EmptyTallyResult() - testCases := map[string]struct { - tallyResult v1.TallyResult - expErr bool - }{ - "valid": { - tallyResult: tallyResult, - }, - "invalid yes count": { - tallyResult: v1.TallyResult{ - YesCount: "invalid", - NoCount: tallyResult.NoCount, - AbstainCount: tallyResult.AbstainCount, - NoWithVetoCount: tallyResult.NoWithVetoCount, - }, - expErr: true, - }, - "invalid no count": { - tallyResult: v1.TallyResult{ - YesCount: tallyResult.YesCount, - NoCount: "invalid", - AbstainCount: tallyResult.AbstainCount, - NoWithVetoCount: tallyResult.NoWithVetoCount, - }, - expErr: true, - }, - "invalid abstain count": { - tallyResult: v1.TallyResult{ - YesCount: tallyResult.YesCount, - NoCount: tallyResult.NoCount, - AbstainCount: "invalid", - NoWithVetoCount: tallyResult.NoWithVetoCount, - }, - expErr: true, - }, - "invalid no with veto count": { - tallyResult: v1.TallyResult{ - YesCount: tallyResult.YesCount, - NoCount: tallyResult.NoCount, - AbstainCount: tallyResult.AbstainCount, - NoWithVetoCount: "invalid", - }, - expErr: true, - }, - } - for name, tc := range testCases { - t.Run(name, func(t *testing.T) { - _, err := v3.ConvertToLegacyTallyResult(&tc.tallyResult) - if tc.expErr { - require.Error(t, err) - } else { - require.NoError(t, err) - } - }) - } -} - -func TestConvertToLegacyVote(t *testing.T) { - vote := v1.Vote{ - ProposalId: 1, - Voter: "cosmos1fl48vsnmsdzcv85q5d2q4z5ajdha8yu34mf0eh", - Metadata: "vote metadata", - } - - testCases := map[string]struct { - options []*v1.WeightedVoteOption - expErr bool - }{ - "valid": { - options: v1.NewNonSplitVoteOption(v1.OptionYes), - }, - "invalid options": { - options: []*v1.WeightedVoteOption{{Option: 1, Weight: "invalid"}}, - expErr: true, - }, - } - - for name, tc := range testCases { - t.Run(name, func(t *testing.T) { - vote.Options = tc.options - v1beta1Vote, err := v3.ConvertToLegacyVote(vote) - if tc.expErr { - require.Error(t, err) - } else { - require.NoError(t, err) - require.Equal(t, v1beta1Vote.ProposalId, vote.ProposalId) - require.Equal(t, v1beta1Vote.Voter, vote.Voter) - require.Equal(t, v1beta1Vote.Options[0].Option, v1beta1.OptionYes) - require.Equal(t, v1beta1Vote.Options[0].Weight, math.LegacyNewDec(1)) - } - }) - } -} - -func TestConvertToLegacyDeposit(t *testing.T) { - deposit := v1.Deposit{ - ProposalId: 1, - Depositor: "cosmos1fl48vsnmsdzcv85q5d2q4z5ajdha8yu34mf0eh", - Amount: sdk.NewCoins(sdk.NewCoin(sdk.DefaultBondDenom, math.NewInt(1))), - } - - v1beta1Deposit := v3.ConvertToLegacyDeposit(&deposit) - require.Equal(t, v1beta1Deposit.ProposalId, deposit.ProposalId) - require.Equal(t, v1beta1Deposit.Depositor, deposit.Depositor) - require.Equal(t, v1beta1Deposit.Amount[0], deposit.Amount[0]) -} diff --git a/x/gov/migrations/v3/json.go b/x/gov/migrations/v3/json.go deleted file mode 100644 index 4b02b522c640..000000000000 --- a/x/gov/migrations/v3/json.go +++ /dev/null @@ -1,34 +0,0 @@ -package v3 - -import ( - v1 "github.com/cosmos/cosmos-sdk/x/gov/types/v1" - "github.com/cosmos/cosmos-sdk/x/gov/types/v1beta1" -) - -// MigrateJSON accepts exported v2 (v0.43) x/gov genesis state and migrates it to -// v3 (V0.46) x/gov genesis state. The migration includes: -// -// - Updating everything to v1. -// - Migrating proposals to be Msg-based. -func MigrateJSON(oldState *v1beta1.GenesisState) (*v1.GenesisState, error) { - newProps, err := convertToNewProposals(oldState.Proposals) - if err != nil { - return nil, err - } - newVotes, err := convertToNewVotes(oldState.Votes) - if err != nil { - return nil, err - } - - depParams, votingParams, tallyParams := convertToNewDepParams(oldState.DepositParams), convertToNewVotingParams(oldState.VotingParams), convertToNewTallyParams(oldState.TallyParams) - - return &v1.GenesisState{ - StartingProposalId: oldState.StartingProposalId, - Deposits: convertToNewDeposits(oldState.Deposits), - Votes: newVotes, - Proposals: newProps, - DepositParams: &depParams, - VotingParams: &votingParams, - TallyParams: &tallyParams, - }, nil -} diff --git a/x/gov/migrations/v3/json_test.go b/x/gov/migrations/v3/json_test.go deleted file mode 100644 index 177e3c6fa3a4..000000000000 --- a/x/gov/migrations/v3/json_test.go +++ /dev/null @@ -1,165 +0,0 @@ -package v3_test - -import ( - "encoding/json" - "testing" - "time" - - "github.com/cosmos/gogoproto/proto" - "github.com/stretchr/testify/require" - - sdkmath "cosmossdk.io/math" - - "github.com/cosmos/cosmos-sdk/client" - codectypes "github.com/cosmos/cosmos-sdk/codec/types" - sdk "github.com/cosmos/cosmos-sdk/types" - moduletestutil "github.com/cosmos/cosmos-sdk/types/module/testutil" - authtypes "github.com/cosmos/cosmos-sdk/x/auth/types" - "github.com/cosmos/cosmos-sdk/x/gov" - v3 "github.com/cosmos/cosmos-sdk/x/gov/migrations/v3" - "github.com/cosmos/cosmos-sdk/x/gov/types" - v1 "github.com/cosmos/cosmos-sdk/x/gov/types/v1" - "github.com/cosmos/cosmos-sdk/x/gov/types/v1beta1" -) - -var voter = sdk.MustAccAddressFromBech32("cosmos1fl48vsnmsdzcv85q5d2q4z5ajdha8yu34mf0eh") - -func TestMigrateJSON(t *testing.T) { - encodingConfig := moduletestutil.MakeTestEncodingConfig(gov.AppModuleBasic{}) - clientCtx := client.Context{}. - WithInterfaceRegistry(encodingConfig.InterfaceRegistry). - WithTxConfig(encodingConfig.TxConfig). - WithCodec(encodingConfig.Codec) - - govGenState := v1beta1.DefaultGenesisState() - propTime := time.Unix(1e9, 0) - contentAny, err := codectypes.NewAnyWithValue(v1beta1.NewTextProposal("my title", "my desc").(proto.Message)) - require.NoError(t, err) - govGenState.Proposals = v1beta1.Proposals{ - v1beta1.Proposal{ - ProposalId: 1, - Content: contentAny, - SubmitTime: propTime, - DepositEndTime: propTime, - VotingStartTime: propTime, - VotingEndTime: propTime, - Status: v1beta1.StatusDepositPeriod, - FinalTallyResult: v1beta1.EmptyTallyResult(), - TotalDeposit: sdk.NewCoins(sdk.NewCoin("stake", sdkmath.NewInt(123))), - }, - } - govGenState.Votes = v1beta1.Votes{ - v1beta1.Vote{ProposalId: 1, Voter: voter.String(), Option: v1beta1.OptionAbstain}, - v1beta1.Vote{ProposalId: 2, Voter: voter.String(), Options: v1beta1.NewNonSplitVoteOption(v1beta1.OptionNo)}, - } - - migrated, err := v3.MigrateJSON(govGenState) - require.NoError(t, err) - - // Make sure the migrated proposal's Msg signer is the gov acct. - require.Equal(t, - authtypes.NewModuleAddress(types.ModuleName).String(), - migrated.Proposals[0].Messages[0].GetCachedValue().(*v1.MsgExecLegacyContent).Authority, - ) - - bz, err := clientCtx.Codec.MarshalJSON(migrated) - require.NoError(t, err) - - // Indent the JSON bz correctly. - var jsonObj map[string]any - err = json.Unmarshal(bz, &jsonObj) - require.NoError(t, err) - indentedBz, err := json.MarshalIndent(jsonObj, "", "\t") - require.NoError(t, err) - - // Make sure about: - // - Proposals use MsgExecLegacyContent - expected := `{ - "constitution": "", - "deposit_params": { - "max_deposit_period": "172800s", - "min_deposit": [ - { - "amount": "10000000", - "denom": "stake" - } - ] - }, - "deposits": [], - "params": null, - "proposals": [ - { - "deposit_end_time": "2001-09-09T01:46:40Z", - "expedited": false, - "failed_reason": "", - "final_tally_result": { - "abstain_count": "0", - "no_count": "0", - "no_with_veto_count": "0", - "yes_count": "0" - }, - "id": "1", - "messages": [ - { - "@type": "/cosmos.gov.v1.MsgExecLegacyContent", - "authority": "cosmos10d07y265gmmuvt4z0w9aw880jnsr700j6zn9kn", - "content": { - "@type": "/cosmos.gov.v1beta1.TextProposal", - "description": "my desc", - "title": "my title" - } - } - ], - "metadata": "", - "proposer": "", - "status": "PROPOSAL_STATUS_DEPOSIT_PERIOD", - "submit_time": "2001-09-09T01:46:40Z", - "summary": "my desc", - "title": "my title", - "total_deposit": [ - { - "amount": "123", - "denom": "stake" - } - ], - "voting_end_time": "2001-09-09T01:46:40Z", - "voting_start_time": "2001-09-09T01:46:40Z" - } - ], - "starting_proposal_id": "1", - "tally_params": { - "quorum": "0.334000000000000000", - "threshold": "0.500000000000000000", - "veto_threshold": "0.334000000000000000" - }, - "votes": [ - { - "metadata": "", - "options": [ - { - "option": "VOTE_OPTION_ABSTAIN", - "weight": "1.000000000000000000" - } - ], - "proposal_id": "1", - "voter": "cosmos1fl48vsnmsdzcv85q5d2q4z5ajdha8yu34mf0eh" - }, - { - "metadata": "", - "options": [ - { - "option": "VOTE_OPTION_NO", - "weight": "1.000000000000000000" - } - ], - "proposal_id": "2", - "voter": "cosmos1fl48vsnmsdzcv85q5d2q4z5ajdha8yu34mf0eh" - } - ], - "voting_params": { - "voting_period": "172800s" - } -}` - - require.Equal(t, expected, string(indentedBz)) -} diff --git a/x/gov/migrations/v3/keys.go b/x/gov/migrations/v3/keys.go deleted file mode 100644 index a4aa0fe28a70..000000000000 --- a/x/gov/migrations/v3/keys.go +++ /dev/null @@ -1,6 +0,0 @@ -package v3 - -const ( - // ModuleName is the name of the module - ModuleName = "gov" -) diff --git a/x/gov/migrations/v3/store.go b/x/gov/migrations/v3/store.go deleted file mode 100644 index b1a17b8ef202..000000000000 --- a/x/gov/migrations/v3/store.go +++ /dev/null @@ -1,98 +0,0 @@ -package v3 - -import ( - corestoretypes "cosmossdk.io/core/store" - "cosmossdk.io/store/prefix" - storetypes "cosmossdk.io/store/types" - - "github.com/cosmos/cosmos-sdk/codec" - "github.com/cosmos/cosmos-sdk/runtime" - sdk "github.com/cosmos/cosmos-sdk/types" - v1 "github.com/cosmos/cosmos-sdk/x/gov/migrations/v1" - govv1 "github.com/cosmos/cosmos-sdk/x/gov/types/v1" - govv1beta1 "github.com/cosmos/cosmos-sdk/x/gov/types/v1beta1" -) - -// migrateProposals migrates all legacy proposals into MsgExecLegacyContent -// proposals. -func migrateProposals(store storetypes.KVStore, cdc codec.BinaryCodec) error { - propStore := prefix.NewStore(store, v1.ProposalsKeyPrefix) - - iter := propStore.Iterator(nil, nil) - defer iter.Close() - - for ; iter.Valid(); iter.Next() { - var oldProp govv1beta1.Proposal - err := cdc.Unmarshal(iter.Value(), &oldProp) - if err != nil { - return err - } - - newProp, err := convertToNewProposal(oldProp) - if err != nil { - return err - } - bz, err := cdc.Marshal(&newProp) - if err != nil { - return err - } - - // Set new value on store. - propStore.Set(iter.Key(), bz) - } - - return nil -} - -// migrateVotes migrates all v1beta1 weighted votes (with sdk.Dec as weight) -// to v1 weighted votes (with string as weight) -func migrateVotes(store storetypes.KVStore, cdc codec.BinaryCodec) error { - votesStore := prefix.NewStore(store, v1.VotesKeyPrefix) - - iter := votesStore.Iterator(nil, nil) - defer iter.Close() - - for ; iter.Valid(); iter.Next() { - var oldVote govv1beta1.Vote - err := cdc.Unmarshal(iter.Value(), &oldVote) - if err != nil { - return err - } - - newVote := govv1.Vote{ - ProposalId: oldVote.ProposalId, - Voter: oldVote.Voter, - } - newOptions := make([]*govv1.WeightedVoteOption, len(oldVote.Options)) - for i, o := range oldVote.Options { - newOptions[i] = &govv1.WeightedVoteOption{ - Option: govv1.VoteOption(o.Option), - Weight: o.Weight.String(), // Convert to decimal string - } - } - newVote.Options = newOptions - bz, err := cdc.Marshal(&newVote) - if err != nil { - return err - } - - // Set new value on store. - votesStore.Set(iter.Key(), bz) - } - - return nil -} - -// MigrateStore performs in-place store migrations from v2 (v0.43) to v3 (v0.46). The -// migration includes: -// -// - Migrate proposals to be Msg-based. -func MigrateStore(ctx sdk.Context, storeService corestoretypes.KVStoreService, cdc codec.BinaryCodec) error { - store := storeService.OpenKVStore(ctx) - - if err := migrateVotes(runtime.KVStoreAdapter(store), cdc); err != nil { - return err - } - - return migrateProposals(runtime.KVStoreAdapter(store), cdc) -} diff --git a/x/gov/migrations/v3/store_test.go b/x/gov/migrations/v3/store_test.go deleted file mode 100644 index 3296f827368d..000000000000 --- a/x/gov/migrations/v3/store_test.go +++ /dev/null @@ -1,99 +0,0 @@ -package v3_test - -import ( - "testing" - "time" - - "github.com/stretchr/testify/require" - - "cosmossdk.io/math" - storetypes "cosmossdk.io/store/types" - - "github.com/cosmos/cosmos-sdk/runtime" - "github.com/cosmos/cosmos-sdk/testutil" - sdk "github.com/cosmos/cosmos-sdk/types" - moduletestutil "github.com/cosmos/cosmos-sdk/types/module/testutil" - "github.com/cosmos/cosmos-sdk/x/gov" - v1gov "github.com/cosmos/cosmos-sdk/x/gov/migrations/v1" - v3gov "github.com/cosmos/cosmos-sdk/x/gov/migrations/v3" - v1 "github.com/cosmos/cosmos-sdk/x/gov/types/v1" - "github.com/cosmos/cosmos-sdk/x/gov/types/v1beta1" -) - -func TestMigrateStore(t *testing.T) { - cdc := moduletestutil.MakeTestEncodingConfig(gov.AppModuleBasic{}).Codec - govKey := storetypes.NewKVStoreKey("gov") - ctx := testutil.DefaultContext(govKey, storetypes.NewTransientStoreKey("transient_test")) - store := ctx.KVStore(govKey) - - propTime := time.Unix(1e9, 0) - - // Create 2 proposals - prop1, err := v1beta1.NewProposal(v1beta1.NewTextProposal("my title 1", "my desc 1"), 1, propTime, propTime) - require.NoError(t, err) - prop1Bz, err := cdc.Marshal(&prop1) - require.NoError(t, err) - prop2, err := v1beta1.NewProposal(v1beta1.NewTextProposal("my title 2", "my desc 2"), 2, propTime, propTime) - require.NoError(t, err) - require.NoError(t, err) - prop2Bz, err := cdc.Marshal(&prop2) - require.NoError(t, err) - - store.Set(v1gov.ProposalKey(prop1.ProposalId), prop1Bz) - store.Set(v1gov.ProposalKey(prop2.ProposalId), prop2Bz) - - // Vote on prop 1 - options := []v1beta1.WeightedVoteOption{ - {Option: v1beta1.OptionNo, Weight: math.LegacyMustNewDecFromStr("0.3")}, - {Option: v1beta1.OptionYes, Weight: math.LegacyMustNewDecFromStr("0.7")}, - } - vote1 := v1beta1.NewVote(1, voter, options) - vote1Bz := cdc.MustMarshal(&vote1) - store.Set(v1gov.VoteKey(1, voter), vote1Bz) - - // Run migrations. - storeService := runtime.NewKVStoreService(govKey) - err = v3gov.MigrateStore(ctx, storeService, cdc) - require.NoError(t, err) - - var newProp1 v1.Proposal - err = cdc.Unmarshal(store.Get(v1gov.ProposalKey(prop1.ProposalId)), &newProp1) - require.NoError(t, err) - compareProps(t, prop1, newProp1) - - var newProp2 v1.Proposal - err = cdc.Unmarshal(store.Get(v1gov.ProposalKey(prop2.ProposalId)), &newProp2) - require.NoError(t, err) - compareProps(t, prop2, newProp2) - - var newVote1 v1.Vote - err = cdc.Unmarshal(store.Get(v1gov.VoteKey(prop1.ProposalId, voter)), &newVote1) - require.NoError(t, err) - // Without the votes migration, we would have 300000000000000000 in state, - // because of how sdk.Dec stores itself in state. - require.Equal(t, "0.300000000000000000", newVote1.Options[0].Weight) - require.Equal(t, "0.700000000000000000", newVote1.Options[1].Weight) -} - -func compareProps(t *testing.T, oldProp v1beta1.Proposal, newProp v1.Proposal) { - t.Helper() - - require.Equal(t, oldProp.ProposalId, newProp.Id) - require.Equal(t, oldProp.TotalDeposit.String(), sdk.Coins(newProp.TotalDeposit).String()) - require.Equal(t, oldProp.Status.String(), newProp.Status.String()) - require.Equal(t, oldProp.FinalTallyResult.Yes.String(), newProp.FinalTallyResult.YesCount) - require.Equal(t, oldProp.FinalTallyResult.No.String(), newProp.FinalTallyResult.NoCount) - require.Equal(t, oldProp.FinalTallyResult.NoWithVeto.String(), newProp.FinalTallyResult.NoWithVetoCount) - require.Equal(t, oldProp.FinalTallyResult.Abstain.String(), newProp.FinalTallyResult.AbstainCount) - - newContent := newProp.Messages[0].GetCachedValue().(*v1.MsgExecLegacyContent).Content.GetCachedValue().(v1beta1.Content) - require.Equal(t, oldProp.Content.GetCachedValue().(v1beta1.Content), newContent) - - // Compare UNIX times, as a simple Equal gives difference between Local and - // UTC times. - // ref: https://github.com/golang/go/issues/19486#issuecomment-292968278 - require.Equal(t, oldProp.SubmitTime.Unix(), newProp.SubmitTime.Unix()) - require.Equal(t, oldProp.DepositEndTime.Unix(), newProp.DepositEndTime.Unix()) - require.Equal(t, oldProp.VotingStartTime.Unix(), newProp.VotingStartTime.Unix()) - require.Equal(t, oldProp.VotingEndTime.Unix(), newProp.VotingEndTime.Unix()) -} diff --git a/x/gov/migrations/v4/json.go b/x/gov/migrations/v4/json.go deleted file mode 100644 index bed36ff14412..000000000000 --- a/x/gov/migrations/v4/json.go +++ /dev/null @@ -1,42 +0,0 @@ -package v4 - -import ( - v1 "github.com/cosmos/cosmos-sdk/x/gov/types/v1" -) - -// MigrateJSON accepts exported v3 (v0.46) x/gov genesis state and migrates it to -// v4 (v0.47) x/gov genesis state. The migration includes: -// -// Params migrations from x/params to gov -// Addition of the new min initial deposit ratio parameter that is set to 0 by default. -// Proposals in voting period are tracked in a separate index. -func MigrateJSON(oldState *v1.GenesisState) (*v1.GenesisState, error) { - defaultParams := v1.DefaultParams() - - params := v1.NewParams( - oldState.DepositParams.MinDeposit, - defaultParams.ExpeditedMinDeposit, - *oldState.DepositParams.MaxDepositPeriod, - *oldState.VotingParams.VotingPeriod, - *defaultParams.ExpeditedVotingPeriod, - oldState.TallyParams.Quorum, - oldState.TallyParams.Threshold, - defaultParams.ExpeditedThreshold, - oldState.TallyParams.VetoThreshold, - defaultParams.MinInitialDepositRatio, - defaultParams.ProposalCancelRatio, - defaultParams.ProposalCancelDest, - defaultParams.BurnProposalDepositPrevote, - defaultParams.BurnVoteQuorum, - defaultParams.BurnVoteVeto, - defaultParams.MinDepositRatio, - ) - - return &v1.GenesisState{ - StartingProposalId: oldState.StartingProposalId, - Deposits: oldState.Deposits, - Votes: oldState.Votes, - Proposals: oldState.Proposals, - Params: ¶ms, - }, nil -} diff --git a/x/gov/migrations/v4/json_test.go b/x/gov/migrations/v4/json_test.go deleted file mode 100644 index cc9a2fa8ebbb..000000000000 --- a/x/gov/migrations/v4/json_test.go +++ /dev/null @@ -1,99 +0,0 @@ -package v4_test - -import ( - "encoding/json" - "testing" - - "github.com/stretchr/testify/require" - - "github.com/cosmos/cosmos-sdk/client" - moduletestutil "github.com/cosmos/cosmos-sdk/types/module/testutil" - "github.com/cosmos/cosmos-sdk/x/gov" - v4 "github.com/cosmos/cosmos-sdk/x/gov/migrations/v4" - v1 "github.com/cosmos/cosmos-sdk/x/gov/types/v1" -) - -func TestMigrateJSON(t *testing.T) { - encodingConfig := moduletestutil.MakeTestEncodingConfig(gov.AppModuleBasic{}) - clientCtx := client.Context{}. - WithInterfaceRegistry(encodingConfig.InterfaceRegistry). - WithTxConfig(encodingConfig.TxConfig). - WithCodec(encodingConfig.Codec) - - govGenState := v1.DefaultGenesisState() - oldGovState := &v1.GenesisState{ - StartingProposalId: govGenState.StartingProposalId, - Deposits: govGenState.Deposits, - Votes: govGenState.Votes, - Proposals: govGenState.Proposals, - DepositParams: &v1.DepositParams{ - MinDeposit: govGenState.Params.MinDeposit, - MaxDepositPeriod: govGenState.Params.MaxDepositPeriod, - }, - VotingParams: &v1.VotingParams{ - VotingPeriod: govGenState.Params.VotingPeriod, - }, - TallyParams: &v1.TallyParams{ - Quorum: govGenState.Params.Quorum, - Threshold: govGenState.Params.Threshold, - VetoThreshold: govGenState.Params.VetoThreshold, - }, - } - - migrated, err := v4.MigrateJSON(oldGovState) - require.NoError(t, err) - require.Equal(t, migrated, govGenState) - - bz, err := clientCtx.Codec.MarshalJSON(migrated) - require.NoError(t, err) - - // Indent the JSON bz correctly. - var jsonObj map[string]any - err = json.Unmarshal(bz, &jsonObj) - require.NoError(t, err) - indentedBz, err := json.MarshalIndent(jsonObj, "", "\t") - require.NoError(t, err) - - // Make sure about: - // - Proposals use MsgExecLegacyContent - expected := `{ - "constitution": "", - "deposit_params": null, - "deposits": [], - "params": { - "burn_proposal_deposit_prevote": false, - "burn_vote_quorum": false, - "burn_vote_veto": true, - "expedited_min_deposit": [ - { - "amount": "50000000", - "denom": "stake" - } - ], - "expedited_threshold": "0.667000000000000000", - "expedited_voting_period": "86400s", - "max_deposit_period": "172800s", - "min_deposit": [ - { - "amount": "10000000", - "denom": "stake" - } - ], - "min_deposit_ratio": "0.010000000000000000", - "min_initial_deposit_ratio": "0.000000000000000000", - "proposal_cancel_dest": "", - "proposal_cancel_ratio": "0.500000000000000000", - "quorum": "0.334000000000000000", - "threshold": "0.500000000000000000", - "veto_threshold": "0.334000000000000000", - "voting_period": "172800s" - }, - "proposals": [], - "starting_proposal_id": "1", - "tally_params": null, - "votes": [], - "voting_params": null -}` - - require.Equal(t, expected, string(indentedBz)) -} diff --git a/x/gov/migrations/v4/keys.go b/x/gov/migrations/v4/keys.go deleted file mode 100644 index 0ad676201f8c..000000000000 --- a/x/gov/migrations/v4/keys.go +++ /dev/null @@ -1,28 +0,0 @@ -package v4 - -import "encoding/binary" - -const ( - // ModuleName is the name of the module - ModuleName = "gov" -) - -var ( - // ParamsKey is the key of x/gov params - ParamsKey = []byte{0x30} - - // VotingPeriodProposalKeyPrefix - 0x04: ProposalContents - VotingPeriodProposalKeyPrefix = []byte{0x04} -) - -// VotingPeriodProposalKey gets if a proposal is in voting period. -func VotingPeriodProposalKey(proposalID uint64) []byte { - return append(VotingPeriodProposalKeyPrefix, GetProposalIDBytes(proposalID)...) -} - -// GetProposalIDBytes returns the byte representation of the proposalID -func GetProposalIDBytes(proposalID uint64) (proposalIDBz []byte) { - proposalIDBz = make([]byte, 8) - binary.BigEndian.PutUint64(proposalIDBz, proposalID) - return proposalIDBz -} diff --git a/x/gov/migrations/v4/store.go b/x/gov/migrations/v4/store.go deleted file mode 100644 index 0bb5bbf3c835..000000000000 --- a/x/gov/migrations/v4/store.go +++ /dev/null @@ -1,139 +0,0 @@ -package v4 - -import ( - "fmt" - "slices" - - corestoretypes "cosmossdk.io/core/store" - "cosmossdk.io/store/prefix" - storetypes "cosmossdk.io/store/types" - - "github.com/cosmos/cosmos-sdk/codec" - "github.com/cosmos/cosmos-sdk/runtime" - sdk "github.com/cosmos/cosmos-sdk/types" - "github.com/cosmos/cosmos-sdk/x/gov/exported" - v1 "github.com/cosmos/cosmos-sdk/x/gov/migrations/v1" - "github.com/cosmos/cosmos-sdk/x/gov/types" - govv1 "github.com/cosmos/cosmos-sdk/x/gov/types/v1" -) - -func migrateParams(ctx sdk.Context, store storetypes.KVStore, legacySubspace exported.ParamSubspace, cdc codec.BinaryCodec) error { - dp := govv1.DepositParams{} - vp := govv1.VotingParams{} - tp := govv1.TallyParams{} - legacySubspace.Get(ctx, govv1.ParamStoreKeyDepositParams, &dp) - legacySubspace.Get(ctx, govv1.ParamStoreKeyVotingParams, &vp) - legacySubspace.Get(ctx, govv1.ParamStoreKeyTallyParams, &tp) - - defaultParams := govv1.DefaultParams() - params := govv1.NewParams( - dp.MinDeposit, - defaultParams.ExpeditedMinDeposit, - *dp.MaxDepositPeriod, - *vp.VotingPeriod, - *defaultParams.ExpeditedVotingPeriod, - tp.Quorum, - tp.Threshold, - defaultParams.ExpeditedThreshold, - tp.VetoThreshold, - defaultParams.MinInitialDepositRatio, - defaultParams.ProposalCancelRatio, - defaultParams.ProposalCancelDest, - defaultParams.BurnProposalDepositPrevote, - defaultParams.BurnVoteQuorum, - defaultParams.BurnVoteVeto, - defaultParams.MinDepositRatio, - ) - - bz, err := cdc.Marshal(¶ms) - if err != nil { - return err - } - - store.Set(ParamsKey, bz) - - return nil -} - -func migrateProposalVotingPeriod(ctx sdk.Context, store storetypes.KVStore, cdc codec.BinaryCodec) error { - propStore := prefix.NewStore(store, v1.ProposalsKeyPrefix) - - iter := propStore.Iterator(nil, nil) - defer iter.Close() - - for ; iter.Valid(); iter.Next() { - var prop govv1.Proposal - err := cdc.Unmarshal(iter.Value(), &prop) - if err != nil { - return err - } - - if prop.Status == govv1.StatusVotingPeriod { - store.Set(VotingPeriodProposalKey(prop.Id), []byte{1}) - } - } - - return nil -} - -// MigrateStore performs in-place store migrations from v3 (v0.46) to v4 (v0.47). The -// migration includes: -// -// Params migrations from x/params to gov -// Addition of the new min initial deposit ratio parameter that is set to 0 by default. -// Proposals in voting period are tracked in a separate index. -func MigrateStore(ctx sdk.Context, storeService corestoretypes.KVStoreService, legacySubspace exported.ParamSubspace, cdc codec.BinaryCodec) error { - store := runtime.KVStoreAdapter(storeService.OpenKVStore(ctx)) - if err := migrateProposalVotingPeriod(ctx, store, cdc); err != nil { - return err - } - - return migrateParams(ctx, store, legacySubspace, cdc) -} - -// AddProposerAddressToProposal will add proposer to proposal and set to the store. This function is optional. -func AddProposerAddressToProposal(ctx sdk.Context, storeService corestoretypes.KVStoreService, cdc codec.BinaryCodec, proposals map[uint64]string) error { - proposalIDs := make([]uint64, 0, len(proposals)) - - for proposalID := range proposals { - proposalIDs = append(proposalIDs, proposalID) - } - - // sort the proposalIDs - slices.Sort(proposalIDs) - - store := runtime.KVStoreAdapter(storeService.OpenKVStore(ctx)) - - for _, proposalID := range proposalIDs { - if len(proposals[proposalID]) == 0 { - return fmt.Errorf("found missing proposer for proposal ID: %d", proposalID) - } - - if _, err := sdk.AccAddressFromBech32(proposals[proposalID]); err != nil { - return fmt.Errorf("invalid proposer address : %s", proposals[proposalID]) - } - - bz := store.Get(append(types.ProposalsKeyPrefix, sdk.Uint64ToBigEndian(proposalID)...)) - var proposal govv1.Proposal - if err := cdc.Unmarshal(bz, &proposal); err != nil { - panic(err) - } - - // Check if proposal is active - if proposal.Status != govv1.ProposalStatus_PROPOSAL_STATUS_VOTING_PERIOD && - proposal.Status != govv1.ProposalStatus_PROPOSAL_STATUS_DEPOSIT_PERIOD { - return fmt.Errorf("invalid proposal : %s, proposal not active", proposals[proposalID]) - } - - proposal.Proposer = proposals[proposalID] - - // set the new proposal with proposer - bz, err := cdc.Marshal(&proposal) - if err != nil { - panic(err) - } - store.Set(append(types.ProposalsKeyPrefix, sdk.Uint64ToBigEndian(proposalID)...), bz) - } - - return nil -} diff --git a/x/gov/migrations/v4/store_test.go b/x/gov/migrations/v4/store_test.go deleted file mode 100644 index 059e40b289ef..000000000000 --- a/x/gov/migrations/v4/store_test.go +++ /dev/null @@ -1,138 +0,0 @@ -package v4_test - -import ( - "testing" - "time" - - "github.com/stretchr/testify/require" - - "cosmossdk.io/math" - storetypes "cosmossdk.io/store/types" - - "github.com/cosmos/cosmos-sdk/runtime" - "github.com/cosmos/cosmos-sdk/testutil" - "github.com/cosmos/cosmos-sdk/testutil/testdata" - sdk "github.com/cosmos/cosmos-sdk/types" - moduletestutil "github.com/cosmos/cosmos-sdk/types/module/testutil" - authtypes "github.com/cosmos/cosmos-sdk/x/auth/types" - "github.com/cosmos/cosmos-sdk/x/bank" - banktypes "github.com/cosmos/cosmos-sdk/x/bank/types" - "github.com/cosmos/cosmos-sdk/x/gov" - v1gov "github.com/cosmos/cosmos-sdk/x/gov/migrations/v1" - v4 "github.com/cosmos/cosmos-sdk/x/gov/migrations/v4" - "github.com/cosmos/cosmos-sdk/x/gov/types" - v1 "github.com/cosmos/cosmos-sdk/x/gov/types/v1" - "github.com/cosmos/cosmos-sdk/x/gov/types/v1beta1" -) - -var ( - _, _, addr = testdata.KeyTestPubAddr() - govAcct = authtypes.NewModuleAddress(types.ModuleName) - TestProposal = getTestProposal() -) - -type mockSubspace struct { - dp v1.DepositParams - vp v1.VotingParams - tp v1.TallyParams -} - -func newMockSubspace(p v1.Params) mockSubspace { - return mockSubspace{ - dp: v1.DepositParams{ - MinDeposit: p.MinDeposit, - MaxDepositPeriod: p.MaxDepositPeriod, - }, - vp: v1.VotingParams{ - VotingPeriod: p.VotingPeriod, - }, - tp: v1.TallyParams{ - Quorum: p.Quorum, - Threshold: p.Threshold, - VetoThreshold: p.VetoThreshold, - }, - } -} - -func (ms mockSubspace) Get(ctx sdk.Context, key []byte, ptr any) { - switch string(key) { - case string(v1.ParamStoreKeyDepositParams): - *ptr.(*v1.DepositParams) = ms.dp - case string(v1.ParamStoreKeyVotingParams): - *ptr.(*v1.VotingParams) = ms.vp - case string(v1.ParamStoreKeyTallyParams): - *ptr.(*v1.TallyParams) = ms.tp - } -} - -func TestMigrateStore(t *testing.T) { - cdc := moduletestutil.MakeTestEncodingConfig(gov.AppModuleBasic{}, bank.AppModuleBasic{}).Codec - govKey := storetypes.NewKVStoreKey("gov") - ctx := testutil.DefaultContext(govKey, storetypes.NewTransientStoreKey("transient_test")) - store := ctx.KVStore(govKey) - - legacySubspace := newMockSubspace(v1.DefaultParams()) - - propTime := time.Unix(1e9, 0) - - // Create 2 proposals - prop1Content, err := v1.NewLegacyContent(v1beta1.NewTextProposal("Test", "description"), authtypes.NewModuleAddress("gov").String()) - require.NoError(t, err) - proposal1, err := v1.NewProposal([]sdk.Msg{prop1Content}, 1, propTime, propTime, "some metadata for the legacy content", "Test", "description", sdk.AccAddress("cosmos1ghekyjucln7y67ntx7cf27m9dpuxxemn4c8g4r"), false) - require.NoError(t, err) - prop1Bz, err := cdc.Marshal(&proposal1) - require.NoError(t, err) - store.Set(v1gov.ProposalKey(proposal1.Id), prop1Bz) - - proposal2, err := v1.NewProposal(getTestProposal(), 2, propTime, propTime, "some metadata for the legacy content", "Test", "description", sdk.AccAddress("cosmos1ghekyjucln7y67ntx7cf27m9dpuxxemn4c8g4r"), false) - proposal2.Status = v1.StatusVotingPeriod - require.NoError(t, err) - prop2Bz, err := cdc.Marshal(&proposal2) - require.NoError(t, err) - store.Set(v1gov.ProposalKey(proposal2.Id), prop2Bz) - - // Run migrations. - storeService := runtime.NewKVStoreService(govKey) - err = v4.MigrateStore(ctx, storeService, legacySubspace, cdc) - require.NoError(t, err) - - // Check params - var params v1.Params - bz := store.Get(v4.ParamsKey) - require.NoError(t, cdc.Unmarshal(bz, ¶ms)) - require.NotNil(t, params) - require.Equal(t, legacySubspace.dp.MinDeposit, params.MinDeposit) - require.Equal(t, legacySubspace.dp.MaxDepositPeriod, params.MaxDepositPeriod) - require.Equal(t, legacySubspace.vp.VotingPeriod, params.VotingPeriod) - require.Equal(t, legacySubspace.tp.Quorum, params.Quorum) - require.Equal(t, legacySubspace.tp.Threshold, params.Threshold) - require.Equal(t, legacySubspace.tp.VetoThreshold, params.VetoThreshold) - require.Equal(t, math.LegacyZeroDec().String(), params.MinInitialDepositRatio) - - // Check proposals' status - var migratedProp1 v1.Proposal - bz = store.Get(v1gov.ProposalKey(proposal1.Id)) - require.NoError(t, cdc.Unmarshal(bz, &migratedProp1)) - require.Equal(t, v1.StatusDepositPeriod, migratedProp1.Status) - - var migratedProp2 v1.Proposal - bz = store.Get(v1gov.ProposalKey(proposal2.Id)) - require.NoError(t, cdc.Unmarshal(bz, &migratedProp2)) - require.Equal(t, v1.StatusVotingPeriod, migratedProp2.Status) - - // Check if proposal 2 is in the new store but not proposal 1 - require.Nil(t, store.Get(v4.VotingPeriodProposalKey(proposal1.Id))) - require.Equal(t, []byte{0x1}, store.Get(v4.VotingPeriodProposalKey(proposal2.Id))) -} - -func getTestProposal() []sdk.Msg { - legacyProposalMsg, err := v1.NewLegacyContent(v1beta1.NewTextProposal("Title", "description"), authtypes.NewModuleAddress(types.ModuleName).String()) - if err != nil { - panic(err) - } - - return []sdk.Msg{ - banktypes.NewMsgSend(govAcct, addr, sdk.NewCoins(sdk.NewCoin("stake", math.NewInt(1000)))), - legacyProposalMsg, - } -} diff --git a/x/gov/migrations/v5/store.go b/x/gov/migrations/v5/store.go deleted file mode 100644 index 4e74659f7e41..000000000000 --- a/x/gov/migrations/v5/store.go +++ /dev/null @@ -1,63 +0,0 @@ -package v5 - -import ( - "cosmossdk.io/collections" - corestoretypes "cosmossdk.io/core/store" - - "github.com/cosmos/cosmos-sdk/codec" - sdk "github.com/cosmos/cosmos-sdk/types" - v4 "github.com/cosmos/cosmos-sdk/x/gov/migrations/v4" - govv1 "github.com/cosmos/cosmos-sdk/x/gov/types/v1" -) - -var ( - // ParamsKey is the key of x/gov params - ParamsKey = []byte{0x30} - // ConstitutionKey is the key of x/gov constitution - ConstitutionKey = collections.NewPrefix(49) -) - -// MigrateStore performs in-place store migrations from v4 (v0.47) to v5 (v0.50). The -// migration includes: -// -// Addition of the new proposal expedited parameters that are set to 0 by default. -// Set of default chain constitution. -func MigrateStore(ctx sdk.Context, storeService corestoretypes.KVStoreService, cdc codec.BinaryCodec, constitutionCollection collections.Item[string]) error { - store := storeService.OpenKVStore(ctx) - paramsBz, err := store.Get(v4.ParamsKey) - if err != nil { - return err - } - - var params govv1.Params - err = cdc.Unmarshal(paramsBz, ¶ms) - if err != nil { - return err - } - - defaultParams := govv1.DefaultParams() - params.ExpeditedMinDeposit = defaultParams.ExpeditedMinDeposit - params.ExpeditedVotingPeriod = defaultParams.ExpeditedVotingPeriod - params.ExpeditedThreshold = defaultParams.ExpeditedThreshold - params.ProposalCancelRatio = defaultParams.ProposalCancelRatio - params.ProposalCancelDest = defaultParams.ProposalCancelDest - params.MinDepositRatio = defaultParams.MinDepositRatio - - bz, err := cdc.Marshal(¶ms) - if err != nil { - return err - } - - if err := store.Set(ParamsKey, bz); err != nil { - return err - } - - // Set the default constitution if it is not set - if ok, err := constitutionCollection.Has(ctx); !ok || err != nil { - if err := constitutionCollection.Set(ctx, "This chain has no constitution."); err != nil { - return err - } - } - - return nil -} diff --git a/x/gov/migrations/v5/store_test.go b/x/gov/migrations/v5/store_test.go deleted file mode 100644 index 550b77d0658a..000000000000 --- a/x/gov/migrations/v5/store_test.go +++ /dev/null @@ -1,55 +0,0 @@ -package v5_test - -import ( - "testing" - "time" - - "github.com/stretchr/testify/require" - - "cosmossdk.io/collections" - storetypes "cosmossdk.io/store/types" - - "github.com/cosmos/cosmos-sdk/runtime" - "github.com/cosmos/cosmos-sdk/testutil" - moduletestutil "github.com/cosmos/cosmos-sdk/types/module/testutil" - "github.com/cosmos/cosmos-sdk/x/bank" - "github.com/cosmos/cosmos-sdk/x/gov" - v4 "github.com/cosmos/cosmos-sdk/x/gov/migrations/v4" - v5 "github.com/cosmos/cosmos-sdk/x/gov/migrations/v5" - v1 "github.com/cosmos/cosmos-sdk/x/gov/types/v1" -) - -func TestMigrateStore(t *testing.T) { - cdc := moduletestutil.MakeTestEncodingConfig(gov.AppModuleBasic{}, bank.AppModuleBasic{}).Codec - govKey := storetypes.NewKVStoreKey("gov") - ctx := testutil.DefaultContext(govKey, storetypes.NewTransientStoreKey("transient_test")) - store := ctx.KVStore(govKey) - storeService := runtime.NewKVStoreService(govKey) - sb := collections.NewSchemaBuilder(storeService) - constitutionCollection := collections.NewItem(sb, v5.ConstitutionKey, "constitution", collections.StringValue) - - var params v1.Params - bz := store.Get(v4.ParamsKey) - require.NoError(t, cdc.Unmarshal(bz, ¶ms)) - require.NotNil(t, params) - require.Equal(t, "", params.ExpeditedThreshold) - require.Equal(t, (*time.Duration)(nil), params.ExpeditedVotingPeriod) - - // Run migrations. - err := v5.MigrateStore(ctx, storeService, cdc, constitutionCollection) - require.NoError(t, err) - - // Check params - bz = store.Get(v4.ParamsKey) - require.NoError(t, cdc.Unmarshal(bz, ¶ms)) - require.NotNil(t, params) - require.Equal(t, v1.DefaultParams().ExpeditedMinDeposit, params.ExpeditedMinDeposit) - require.Equal(t, v1.DefaultParams().ExpeditedThreshold, params.ExpeditedThreshold) - require.Equal(t, v1.DefaultParams().ExpeditedVotingPeriod, params.ExpeditedVotingPeriod) - require.Equal(t, v1.DefaultParams().MinDepositRatio, params.MinDepositRatio) - - // Check constitution - result, err := constitutionCollection.Get(ctx) - require.NoError(t, err) - require.Equal(t, "This chain has no constitution.", result) -} diff --git a/x/gov/module.go b/x/gov/module.go index fab4e2b5ca31..d9197d26334d 100644 --- a/x/gov/module.go +++ b/x/gov/module.go @@ -118,22 +118,18 @@ type AppModule struct { keeper *keeper.Keeper accountKeeper govtypes.AccountKeeper bankKeeper govtypes.BankKeeper - - // legacySubspace is used solely for migration of x/params managed parameters - legacySubspace govtypes.ParamSubspace } // NewAppModule creates a new AppModule object func NewAppModule( cdc codec.Codec, keeper *keeper.Keeper, - ak govtypes.AccountKeeper, bk govtypes.BankKeeper, ss govtypes.ParamSubspace, + ak govtypes.AccountKeeper, bk govtypes.BankKeeper, ) AppModule { return AppModule{ AppModuleBasic: AppModuleBasic{cdc: cdc, ac: ak.AddressCodec()}, keeper: keeper, accountKeeper: ak, bankKeeper: bk, - legacySubspace: ss, } } @@ -149,26 +145,9 @@ func (am AppModule) RegisterServices(cfg module.Configurator) { v1beta1.RegisterMsgServer(cfg.MsgServer(), keeper.NewLegacyMsgServerImpl(am.accountKeeper.GetModuleAddress(govtypes.ModuleName).String(), msgServer)) v1.RegisterMsgServer(cfg.MsgServer(), msgServer) - legacyQueryServer := keeper.NewLegacyQueryServer(am.keeper) - v1beta1.RegisterQueryServer(cfg.QueryServer(), legacyQueryServer) v1.RegisterQueryServer(cfg.QueryServer(), keeper.NewQueryServer(am.keeper)) - m := keeper.NewMigrator(am.keeper, am.legacySubspace) - if err := cfg.RegisterMigration(govtypes.ModuleName, 1, m.Migrate1to2); err != nil { - panic(fmt.Sprintf("failed to migrate x/gov from version 1 to 2: %v", err)) - } - - if err := cfg.RegisterMigration(govtypes.ModuleName, 2, m.Migrate2to3); err != nil { - panic(fmt.Sprintf("failed to migrate x/gov from version 2 to 3: %v", err)) - } - - if err := cfg.RegisterMigration(govtypes.ModuleName, 3, m.Migrate3to4); err != nil { - panic(fmt.Sprintf("failed to migrate x/gov from version 3 to 4: %v", err)) - } - - if err := cfg.RegisterMigration(govtypes.ModuleName, 4, m.Migrate4to5); err != nil { - panic(fmt.Sprintf("failed to migrate x/gov from version 4 to 5: %v", err)) - } + _ = keeper.NewMigrator(am.keeper) } // InitGenesis performs genesis initialization for the gov module. It returns diff --git a/x/gov/simulation/operations_test.go b/x/gov/simulation/operations_test.go index 7f9c441c4318..046301238c16 100644 --- a/x/gov/simulation/operations_test.go +++ b/x/gov/simulation/operations_test.go @@ -34,7 +34,6 @@ import ( "github.com/cosmos/cosmos-sdk/x/gov/types" v1 "github.com/cosmos/cosmos-sdk/x/gov/types/v1" "github.com/cosmos/cosmos-sdk/x/gov/types/v1beta1" - _ "github.com/cosmos/cosmos-sdk/x/params" _ "github.com/cosmos/cosmos-sdk/x/staking" stakingkeeper "github.com/cosmos/cosmos-sdk/x/staking/keeper" ) @@ -422,7 +421,6 @@ func createTestSuite(t *testing.T, isCheckTx bool) (suite, sdk.Context) { configurator.NewAppConfig( configurator.AuthModule(), configurator.TxModule(), - configurator.ParamsModule(), configurator.BankModule(), configurator.StakingModule(), configurator.ConsensusModule(), diff --git a/x/gov/types/v1/params_legacy.go b/x/gov/types/v1/params_legacy.go deleted file mode 100644 index 522bda56ebbc..000000000000 --- a/x/gov/types/v1/params_legacy.go +++ /dev/null @@ -1,102 +0,0 @@ -package v1 - -import ( - "errors" - "fmt" - - "cosmossdk.io/math" - - sdk "github.com/cosmos/cosmos-sdk/types" - paramtypes "github.com/cosmos/cosmos-sdk/x/params/types" -) - -// Parameter store key -var ( - ParamStoreKeyDepositParams = []byte("depositparams") - ParamStoreKeyVotingParams = []byte("votingparams") - ParamStoreKeyTallyParams = []byte("tallyparams") -) - -// Deprecated: ParamKeyTable - Key declaration for parameters -func ParamKeyTable() paramtypes.KeyTable { - return paramtypes.NewKeyTable( - paramtypes.NewParamSetPair(ParamStoreKeyDepositParams, DepositParams{}, validateDepositParams), - paramtypes.NewParamSetPair(ParamStoreKeyVotingParams, VotingParams{}, validateVotingParams), - paramtypes.NewParamSetPair(ParamStoreKeyTallyParams, TallyParams{}, validateTallyParams), - ) -} - -func validateDepositParams(i any) error { - v, ok := i.(DepositParams) - if !ok { - return fmt.Errorf("invalid parameter type: %T", i) - } - - if !sdk.Coins(v.MinDeposit).IsValid() { - return fmt.Errorf("invalid minimum deposit: %s", v.MinDeposit) - } - if v.MaxDepositPeriod == nil || v.MaxDepositPeriod.Seconds() <= 0 { - return fmt.Errorf("maximum deposit period must be positive: %d", v.MaxDepositPeriod) - } - - return nil -} - -func validateTallyParams(i any) error { - v, ok := i.(TallyParams) - if !ok { - return fmt.Errorf("invalid parameter type: %T", i) - } - - quorum, err := math.LegacyNewDecFromStr(v.Quorum) - if err != nil { - return fmt.Errorf("invalid quorum string: %w", err) - } - if quorum.IsNegative() { - return fmt.Errorf("quorom cannot be negative: %s", quorum) - } - if quorum.GT(math.LegacyOneDec()) { - return fmt.Errorf("quorom too large: %s", v) - } - - threshold, err := math.LegacyNewDecFromStr(v.Threshold) - if err != nil { - return fmt.Errorf("invalid threshold string: %w", err) - } - if !threshold.IsPositive() { - return fmt.Errorf("vote threshold must be positive: %s", threshold) - } - if threshold.GT(math.LegacyOneDec()) { - return fmt.Errorf("vote threshold too large: %s", v) - } - - vetoThreshold, err := math.LegacyNewDecFromStr(v.VetoThreshold) - if err != nil { - return fmt.Errorf("invalid vetoThreshold string: %w", err) - } - if !vetoThreshold.IsPositive() { - return fmt.Errorf("veto threshold must be positive: %s", vetoThreshold) - } - if vetoThreshold.GT(math.LegacyOneDec()) { - return fmt.Errorf("veto threshold too large: %s", v) - } - - return nil -} - -func validateVotingParams(i any) error { - v, ok := i.(VotingParams) - if !ok { - return fmt.Errorf("invalid parameter type: %T", i) - } - - if v.VotingPeriod == nil { - return errors.New("voting period must not be nil") - } - - if v.VotingPeriod.Seconds() <= 0 { - return fmt.Errorf("voting period must be positive: %s", v.VotingPeriod) - } - - return nil -} diff --git a/x/mint/exported/exported.go b/x/mint/exported/exported.go deleted file mode 100644 index 000114e6194d..000000000000 --- a/x/mint/exported/exported.go +++ /dev/null @@ -1,18 +0,0 @@ -package exported - -import ( - sdk "github.com/cosmos/cosmos-sdk/types" - paramtypes "github.com/cosmos/cosmos-sdk/x/params/types" -) - -type ( - ParamSet = paramtypes.ParamSet - - // Subspace defines an interface that implements the legacy x/params Subspace - // type. - // - // NOTE: This is used solely for migration of x/params managed parameters. - Subspace interface { - GetParamSet(ctx sdk.Context, ps ParamSet) - } -) diff --git a/x/mint/keeper/migrator.go b/x/mint/keeper/migrator.go index d07e9ff5076c..8735e7f54b5c 100644 --- a/x/mint/keeper/migrator.go +++ b/x/mint/keeper/migrator.go @@ -1,19 +1,13 @@ package keeper -import ( - "github.com/cosmos/cosmos-sdk/x/mint/exported" -) - // Migrator is a struct for handling in-place state migrations. type Migrator struct { - keeper Keeper - legacySubspace exported.Subspace + keeper Keeper } // NewMigrator returns Migrator instance for the state migration. -func NewMigrator(k Keeper, ss exported.Subspace) Migrator { +func NewMigrator(k Keeper) Migrator { return Migrator{ - keeper: k, - legacySubspace: ss, + keeper: k, } } diff --git a/x/mint/module.go b/x/mint/module.go index 11dfac4bfdcf..68a3e0aab8ae 100644 --- a/x/mint/module.go +++ b/x/mint/module.go @@ -21,7 +21,6 @@ import ( simtypes "github.com/cosmos/cosmos-sdk/types/simulation" authtypes "github.com/cosmos/cosmos-sdk/x/auth/types" govtypes "github.com/cosmos/cosmos-sdk/x/gov/types" - "github.com/cosmos/cosmos-sdk/x/mint/exported" "github.com/cosmos/cosmos-sdk/x/mint/keeper" "github.com/cosmos/cosmos-sdk/x/mint/simulation" "github.com/cosmos/cosmos-sdk/x/mint/types" @@ -89,9 +88,6 @@ type AppModule struct { keeper keeper.Keeper authKeeper types.AccountKeeper - - // legacySubspace is used solely for migration of x/params managed parameters - legacySubspace exported.Subspace } // NewAppModule creates a new AppModule object. If the InflationCalculationFn @@ -102,7 +98,6 @@ func NewAppModule( ak types.AccountKeeper, // This input is unused as of Cosmos SDK v0.53 and will be removed in a future release of the Cosmos SDK. ic types.InflationCalculationFn, - ss exported.Subspace, ) AppModule { if ic != nil { panic("inflation calculation function argument must be nil as it is no longer used. This argument will be removed in a future release of the Cosmos SDK. To set a custom inflation calculation function, use the WithMintFn option when constructing the x/mint keeper as follows: mintkeeper.WithMintFn(mintkeeper.DefaultMintFn(minttypes.DefaultInflationCalculationFn))") @@ -112,7 +107,6 @@ func NewAppModule( AppModuleBasic: AppModuleBasic{cdc: cdc}, keeper: keeper, authKeeper: ak, - legacySubspace: ss, } } @@ -128,7 +122,7 @@ func (am AppModule) RegisterServices(cfg module.Configurator) { types.RegisterMsgServer(cfg.MsgServer(), keeper.NewMsgServerImpl(am.keeper)) types.RegisterQueryServer(cfg.QueryServer(), keeper.NewQueryServerImpl(am.keeper)) - _ = keeper.NewMigrator(am.keeper, am.legacySubspace) + _ = keeper.NewMigrator(am.keeper) } // InitGenesis performs genesis initialization for the mint module. It returns @@ -204,9 +198,6 @@ type ModuleInputs struct { InflationCalculationFn types.InflationCalculationFn `optional:"true"` MintFn keeper.MintFn `optional:"true"` - // LegacySubspace is used solely for migration of x/params managed parameters - LegacySubspace exported.Subspace `optional:"true"` - AccountKeeper types.AccountKeeper BankKeeper types.BankKeeper StakingKeeper types.StakingKeeper @@ -252,7 +243,7 @@ func ProvideModule(in ModuleInputs) ModuleOutputs { ) // when no inflation calculation function is provided it will use the default types.DefaultInflationCalculationFn - m := NewAppModule(in.Cdc, k, in.AccountKeeper, nil, in.LegacySubspace) + m := NewAppModule(in.Cdc, k, in.AccountKeeper, nil) return ModuleOutputs{MintKeeper: k, Module: m} } diff --git a/x/mint/testutil/app_config.go b/x/mint/testutil/app_config.go index 4f385518dcb8..ece7b9f08dd8 100644 --- a/x/mint/testutil/app_config.go +++ b/x/mint/testutil/app_config.go @@ -8,7 +8,6 @@ import ( _ "github.com/cosmos/cosmos-sdk/x/consensus" // import as blank for app wiring _ "github.com/cosmos/cosmos-sdk/x/genutil" // import as blank for app wiring _ "github.com/cosmos/cosmos-sdk/x/mint" // import as blank for app wiring - _ "github.com/cosmos/cosmos-sdk/x/params" // import as blank for app wiring _ "github.com/cosmos/cosmos-sdk/x/staking" // import as blank for app wiring ) @@ -18,7 +17,6 @@ var AppConfig = configurator.NewAppConfig( configurator.StakingModule(), configurator.TxModule(), configurator.ConsensusModule(), - configurator.ParamsModule(), configurator.GenutilModule(), configurator.MintModule(), ) diff --git a/x/params/README.md b/x/params/README.md deleted file mode 100644 index 10b47da44e13..000000000000 --- a/x/params/README.md +++ /dev/null @@ -1,79 +0,0 @@ ---- -sidebar_position: 1 ---- - -# `x/params` - -NOTE: `x/params` is deprecated as of Cosmos SDK v0.53 and will be removed in the next release. - -## Abstract - -Package params provides a globally available parameter store. - -There are two main types, Keeper and Subspace. Subspace is an isolated namespace for a -paramstore, where keys are prefixed by preconfigured spacename. Keeper has a -permission to access all existing spaces. - -Subspace can be used by the individual keepers, which need a private parameter store -that the other keepers cannot modify. The params Keeper can be used to add a route to `x/gov` router in order to modify any parameter in case a proposal passes. - -The following contents explains how to use params module for master and user modules. - -## Contents - -* [Keeper](#keeper) -* [Subspace](#subspace) - * [Key](#key) - * [KeyTable](#keytable) - * [ParamSet](#paramset) - -## Keeper - -In the app initialization stage, [subspaces](#subspace) can be allocated for other modules' keeper using `Keeper.Subspace` and are stored in `Keeper.spaces`. Then, those modules can have a reference to their specific parameter store through `Keeper.GetSubspace`. - -Example: - -```go -type ExampleKeeper struct { - paramSpace paramtypes.Subspace -} - -func (k ExampleKeeper) SetParams(ctx sdk.Context, params types.Params) { - k.paramSpace.SetParamSet(ctx, ¶ms) -} -``` - -## Subspace - -`Subspace` is a prefixed subspace of the parameter store. Each module which uses the -parameter store will take a `Subspace` to isolate permission to access. - -### Key - -Parameter keys are human readable alphanumeric strings. A parameter for the key -`"ExampleParameter"` is stored under `[]byte("SubspaceName" + "/" + "ExampleParameter")`, - where `"SubspaceName"` is the name of the subspace. - -Subkeys are secondary parameter keys those are used along with a primary parameter key. -Subkeys can be used for grouping or dynamic parameter key generation during runtime. - -### KeyTable - -All of the parameter keys that will be used should be registered at the compile -time. `KeyTable` is essentially a `map[string]attribute`, where the `string` is a parameter key. - -Currently, `attribute` consists of a `reflect.Type`, which indicates the parameter -type to check that provided key and value are compatible and registered, as well as a function `ValueValidatorFn` to validate values. - -Only primary keys have to be registered on the `KeyTable`. Subkeys inherit the -attribute of the primary key. - -### ParamSet - -Modules often define parameters as a proto message. The generated struct can implement -`ParamSet` interface to be used with the following methods: - -* `KeyTable.RegisterParamSet()`: registers all parameters in the struct -* `Subspace.{Get, Set}ParamSet()`: Get to & Set from the struct - -The implementer should be a pointer in order to use `GetParamSet()`. diff --git a/x/params/autocli.go b/x/params/autocli.go deleted file mode 100644 index b01e73e45504..000000000000 --- a/x/params/autocli.go +++ /dev/null @@ -1,31 +0,0 @@ -package params - -import ( - autocliv1 "cosmossdk.io/api/cosmos/autocli/v1" - paramsv1beta1 "cosmossdk.io/api/cosmos/params/v1beta1" -) - -// AutoCLIOptions implements the autocli.HasAutoCLIConfig interface. -func (am AppModule) AutoCLIOptions() *autocliv1.ModuleOptions { - return &autocliv1.ModuleOptions{ - Query: &autocliv1.ServiceCommandDescriptor{ - Service: paramsv1beta1.Query_ServiceDesc.ServiceName, - RpcCommandOptions: []*autocliv1.RpcCommandOptions{ - { - RpcMethod: "Params", - Use: "subspace [subspace] [key]", - Short: "Query for raw parameters by subspace and key", - PositionalArgs: []*autocliv1.PositionalArgDescriptor{ - {ProtoField: "subspace"}, - {ProtoField: "key"}, - }, - }, - { - RpcMethod: "Subspaces", - Use: "subspaces", - Short: "Query for all registered subspaces and all keys for a subspace", - }, - }, - }, - } -} diff --git a/x/params/client/cli/tx.go b/x/params/client/cli/tx.go deleted file mode 100644 index d7726dec6d4c..000000000000 --- a/x/params/client/cli/tx.go +++ /dev/null @@ -1,87 +0,0 @@ -package cli - -import ( - "fmt" - "strings" - - "github.com/spf13/cobra" - - "github.com/cosmos/cosmos-sdk/client" - "github.com/cosmos/cosmos-sdk/client/tx" - sdk "github.com/cosmos/cosmos-sdk/types" - "github.com/cosmos/cosmos-sdk/version" - govv1beta1 "github.com/cosmos/cosmos-sdk/x/gov/types/v1beta1" - paramscutils "github.com/cosmos/cosmos-sdk/x/params/client/utils" - paramproposal "github.com/cosmos/cosmos-sdk/x/params/types/proposal" -) - -// NewSubmitParamChangeProposalTxCmd returns a CLI command handler for creating -// a parameter change proposal governance transaction. -func NewSubmitParamChangeProposalTxCmd() *cobra.Command { - return &cobra.Command{ - Use: "param-change [proposal-file]", - Args: cobra.ExactArgs(1), - Short: "Submit a parameter change proposal", - Long: strings.TrimSpace( - fmt.Sprintf(`Submit a parameter proposal along with an initial deposit. -The proposal details must be supplied via a JSON file. For values that contains -objects, only non-empty fields will be updated. - -IMPORTANT: Currently parameter changes are evaluated but not validated, so it is -very important that any "value" change is valid (ie. correct type and within bounds) -for its respective parameter, eg. "MaxValidators" should be an integer and not a decimal. - -Proper vetting of a parameter change proposal should prevent this from happening -(no deposits should occur during the governance process), but it should be noted -regardless. - -Example: -$ %s tx gov submit-proposal param-change --from= - -Where proposal.json contains: - -{ - "title": "Staking Param Change", - "description": "Update max validators", - "changes": [ - { - "subspace": "staking", - "key": "MaxValidators", - "value": 105 - } - ], - "deposit": "1000stake" -} -`, - version.AppName, - ), - ), - RunE: func(cmd *cobra.Command, args []string) error { - clientCtx, err := client.GetClientTxContext(cmd) - if err != nil { - return err - } - proposal, err := paramscutils.ParseParamChangeProposalJSON(clientCtx.LegacyAmino, args[0]) - if err != nil { - return err - } - - from := clientCtx.GetFromAddress() - content := paramproposal.NewParameterChangeProposal( - proposal.Title, proposal.Description, proposal.Changes.ToParamChanges(), - ) - - deposit, err := sdk.ParseCoinsNormalized(proposal.Deposit) - if err != nil { - return err - } - - msg, err := govv1beta1.NewMsgSubmitProposal(content, deposit, from) - if err != nil { - return err - } - - return tx.GenerateOrBroadcastTxCLI(clientCtx, cmd.Flags(), msg) - }, - } -} diff --git a/x/params/client/cli/tx_test.go b/x/params/client/cli/tx_test.go deleted file mode 100644 index 215fb41c8202..000000000000 --- a/x/params/client/cli/tx_test.go +++ /dev/null @@ -1,42 +0,0 @@ -package cli - -import ( - "testing" - - "github.com/stretchr/testify/require" - - "github.com/cosmos/cosmos-sdk/codec" - "github.com/cosmos/cosmos-sdk/testutil" - "github.com/cosmos/cosmos-sdk/x/params/client/utils" -) - -func TestParseProposal(t *testing.T) { - cdc := codec.NewLegacyAmino() - okJSON := testutil.WriteToNewTempFile(t, ` -{ - "title": "Staking Param Change", - "description": "Update max validators", - "changes": [ - { - "subspace": "staking", - "key": "MaxValidators", - "value": 1 - } - ], - "deposit": "1000stake" -} -`) - proposal, err := utils.ParseParamChangeProposalJSON(cdc, okJSON.Name()) - require.NoError(t, err) - - require.Equal(t, "Staking Param Change", proposal.Title) - require.Equal(t, "Update max validators", proposal.Description) - require.Equal(t, "1000stake", proposal.Deposit) - require.Equal(t, utils.ParamChangesJSON{ - { - Subspace: "staking", - Key: "MaxValidators", - Value: []byte{0x31}, - }, - }, proposal.Changes) -} diff --git a/x/params/client/proposal_handler.go b/x/params/client/proposal_handler.go deleted file mode 100644 index a0e946b6401e..000000000000 --- a/x/params/client/proposal_handler.go +++ /dev/null @@ -1,9 +0,0 @@ -package client - -import ( - govclient "github.com/cosmos/cosmos-sdk/x/gov/client" - "github.com/cosmos/cosmos-sdk/x/params/client/cli" -) - -// ProposalHandler is the param change proposal handler. -var ProposalHandler = govclient.NewProposalHandler(cli.NewSubmitParamChangeProposalTxCmd) diff --git a/x/params/client/utils/utils.go b/x/params/client/utils/utils.go deleted file mode 100644 index 4c106913b016..000000000000 --- a/x/params/client/utils/utils.go +++ /dev/null @@ -1,68 +0,0 @@ -package utils - -import ( - "encoding/json" - "os" - - "github.com/cosmos/cosmos-sdk/codec" - "github.com/cosmos/cosmos-sdk/x/params/types/proposal" -) - -type ( - // ParamChangesJSON defines a slice of ParamChangeJSON objects which can be - // converted to a slice of ParamChange objects. - ParamChangesJSON []ParamChangeJSON - - // ParamChangeJSON defines a parameter change used in JSON input. This - // allows values to be specified in raw JSON instead of being string encoded. - ParamChangeJSON struct { - Subspace string `json:"subspace" yaml:"subspace"` - Key string `json:"key" yaml:"key"` - Value json.RawMessage `json:"value" yaml:"value"` - } - - // ParamChangeProposalJSON defines a ParameterChangeProposal with a deposit used - // to parse parameter change proposals from a JSON file. - ParamChangeProposalJSON struct { - Title string `json:"title" yaml:"title"` - Description string `json:"description" yaml:"description"` - Changes ParamChangesJSON `json:"changes" yaml:"changes"` - Deposit string `json:"deposit" yaml:"deposit"` - } -) - -func NewParamChangeJSON(subspace, key string, value json.RawMessage) ParamChangeJSON { - return ParamChangeJSON{subspace, key, value} -} - -// ToParamChange converts a ParamChangeJSON object to ParamChange. -func (pcj ParamChangeJSON) ToParamChange() proposal.ParamChange { - return proposal.NewParamChange(pcj.Subspace, pcj.Key, string(pcj.Value)) -} - -// ToParamChanges converts a slice of ParamChangeJSON objects to a slice of -// ParamChange. -func (pcj ParamChangesJSON) ToParamChanges() []proposal.ParamChange { - res := make([]proposal.ParamChange, len(pcj)) - for i, pc := range pcj { - res[i] = pc.ToParamChange() - } - return res -} - -// ParseParamChangeProposalJSON reads and parses a ParamChangeProposalJSON from -// file. -func ParseParamChangeProposalJSON(cdc *codec.LegacyAmino, proposalFile string) (ParamChangeProposalJSON, error) { - proposal := ParamChangeProposalJSON{} - - contents, err := os.ReadFile(proposalFile) - if err != nil { - return proposal, err - } - - if err := cdc.UnmarshalJSON(contents, &proposal); err != nil { - return proposal, err - } - - return proposal, nil -} diff --git a/x/params/client/utils/utils_test.go b/x/params/client/utils/utils_test.go deleted file mode 100644 index c19857339b42..000000000000 --- a/x/params/client/utils/utils_test.go +++ /dev/null @@ -1,32 +0,0 @@ -package utils - -import ( - "encoding/json" - "testing" - - "github.com/stretchr/testify/require" -) - -func TestNewParamChangeJSON(t *testing.T) { - pcj := NewParamChangeJSON("subspace", "key", json.RawMessage(`{}`)) - require.Equal(t, "subspace", pcj.Subspace) - require.Equal(t, "key", pcj.Key) - require.Equal(t, json.RawMessage(`{}`), pcj.Value) -} - -func TestToParamChanges(t *testing.T) { - pcj1 := NewParamChangeJSON("subspace", "key1", json.RawMessage(`{}`)) - pcj2 := NewParamChangeJSON("subspace", "key2", json.RawMessage(`{}`)) - pcjs := ParamChangesJSON{pcj1, pcj2} - - paramChanges := pcjs.ToParamChanges() - require.Len(t, paramChanges, 2) - - require.Equal(t, paramChanges[0].Subspace, pcj1.Subspace) - require.Equal(t, paramChanges[0].Key, pcj1.Key) - require.Equal(t, paramChanges[0].Value, string(pcj1.Value)) - - require.Equal(t, paramChanges[1].Subspace, pcj2.Subspace) - require.Equal(t, paramChanges[1].Key, pcj2.Key) - require.Equal(t, paramChanges[1].Value, string(pcj2.Value)) -} diff --git a/x/params/doc.go b/x/params/doc.go deleted file mode 100644 index 2a79b0fd51a6..000000000000 --- a/x/params/doc.go +++ /dev/null @@ -1,110 +0,0 @@ -/* -Package params provides a namespaced module parameter store. - -There are two core components, Keeper and Subspace. Subspace is an isolated -namespace for a parameter store, where keys are prefixed by pre-configured -subspace names which modules provide. The Keeper has a permission to access all -existing subspaces. - -Subspace can be used by the individual keepers, which need a private parameter store -that the other keepers cannot modify. - -Basic Usage: - -1. Declare constant module parameter keys and the globally unique Subspace name: - - const ( - ModuleSubspace = "mymodule" - ) - - const ( - KeyParameter1 = "myparameter1" - KeyParameter2 = "myparameter2" - ) - -2. Define parameters as proto message and define the validation functions: - - message MyParams { - int64 my_param1 = 1; - bool my_param2 = 2; - } - - func validateMyParam1(i interface{}) error { - _, ok := i.(int64) - if !ok { - return fmt.Errorf("invalid parameter type: %T", i) - } - - // validate (if necessary)... - - return nil - } - - func validateMyParam2(i interface{}) error { - _, ok := i.(bool) - if !ok { - return fmt.Errorf("invalid parameter type: %T", i) - } - - // validate (if necessary)... - - return nil - } - -3. Implement the params.ParamSet interface: - - func (p *MyParams) ParamSetPairs() params.ParamSetPairs { - return params.ParamSetPairs{ - params.NewParamSetPair(KeyParameter1, &p.MyParam1, validateMyParam1), - params.NewParamSetPair(KeyParameter2, &p.MyParam2, validateMyParam2), - } - } - - func ParamKeyTable() params.KeyTable { - return params.NewKeyTable().RegisterParamSet(&MyParams{}) - } - -4. Have the module accept a Subspace in the constructor and set the KeyTable (if necessary): - - func NewKeeper(..., paramSpace params.Subspace, ...) Keeper { - // set KeyTable if it has not already been set - if !paramSpace.HasKeyTable() { - paramSpace = paramSpace.WithKeyTable(ParamKeyTable()) - } - - return Keeper { - // ... - paramSpace: paramSpace, - } - } - -Now we have access to the module's parameters that are namespaced using the keys defined: - - func InitGenesis(ctx sdk.Context, k Keeper, gs GenesisState) { - // ... - k.SetParams(ctx, gs.Params) - } - - func (k Keeper) SetParams(ctx sdk.Context, params Params) { - k.paramSpace.SetParamSet(ctx, ¶ms) - } - - func (k Keeper) GetParams(ctx sdk.Context) (params Params) { - k.paramSpace.GetParamSet(ctx, ¶ms) - return params - } - - func (k Keeper) MyParam1(ctx sdk.Context) (res int64) { - k.paramSpace.Get(ctx, KeyParameter1, &res) - return res - } - - func (k Keeper) MyParam2(ctx sdk.Context) (res bool) { - k.paramSpace.Get(ctx, KeyParameter2, &res) - return res - } - -NOTE: Any call to SetParamSet will panic or any call to Update will error if any -given parameter value is invalid based on the registered value validation function. -*/ -package params diff --git a/x/params/keeper/common_test.go b/x/params/keeper/common_test.go deleted file mode 100644 index 7f5e0fbd9e9c..000000000000 --- a/x/params/keeper/common_test.go +++ /dev/null @@ -1,39 +0,0 @@ -package keeper_test - -import ( - storetypes "cosmossdk.io/store/types" - - "github.com/cosmos/cosmos-sdk/codec" - sdktestutil "github.com/cosmos/cosmos-sdk/testutil" - sdk "github.com/cosmos/cosmos-sdk/types" - moduletestutil "github.com/cosmos/cosmos-sdk/types/module/testutil" - "github.com/cosmos/cosmos-sdk/x/params" - paramskeeper "github.com/cosmos/cosmos-sdk/x/params/keeper" -) - -func testComponents() (*codec.LegacyAmino, sdk.Context, storetypes.StoreKey, storetypes.StoreKey, paramskeeper.Keeper) { - encodingConfig := moduletestutil.MakeTestEncodingConfig(params.AppModuleBasic{}) - cdc := encodingConfig.Codec - - legacyAmino := createTestCodec() - mkey := storetypes.NewKVStoreKey("test") - tkey := storetypes.NewTransientStoreKey("transient_test") - ctx := sdktestutil.DefaultContext(mkey, tkey) - keeper := paramskeeper.NewKeeper(cdc, legacyAmino, mkey, tkey) - - return legacyAmino, ctx, mkey, tkey, keeper -} - -type invalid struct{} - -type s struct { - I int -} - -func createTestCodec() *codec.LegacyAmino { - cdc := codec.NewLegacyAmino() - sdk.RegisterLegacyAminoCodec(cdc) - cdc.RegisterConcrete(s{}, "test/s", nil) - cdc.RegisterConcrete(invalid{}, "test/invalid", nil) - return cdc -} diff --git a/x/params/keeper/grpc_query.go b/x/params/keeper/grpc_query.go deleted file mode 100644 index 54d1c33a17a3..000000000000 --- a/x/params/keeper/grpc_query.go +++ /dev/null @@ -1,69 +0,0 @@ -package keeper - -import ( - "context" - - "google.golang.org/grpc/codes" - "google.golang.org/grpc/status" - - "cosmossdk.io/errors" - - sdk "github.com/cosmos/cosmos-sdk/types" - "github.com/cosmos/cosmos-sdk/x/params/types/proposal" -) - -var _ proposal.QueryServer = Keeper{} - -// Params returns subspace params -func (k Keeper) Params(c context.Context, req *proposal.QueryParamsRequest) (*proposal.QueryParamsResponse, error) { - if req == nil { - return nil, status.Errorf(codes.InvalidArgument, "empty request") - } - - if req.Subspace == "" || req.Key == "" { - return nil, status.Errorf(codes.InvalidArgument, "invalid request") - } - - ss, ok := k.GetSubspace(req.Subspace) - if !ok { - return nil, errors.Wrap(proposal.ErrUnknownSubspace, req.Subspace) - } - - ctx := sdk.UnwrapSDKContext(c) - rawValue := ss.GetRaw(ctx, []byte(req.Key)) - param := proposal.NewParamChange(req.Subspace, req.Key, string(rawValue)) - - return &proposal.QueryParamsResponse{Param: param}, nil -} - -// Subspaces implements the gRPC query handler for fetching all registered -// subspaces and all the keys for each subspace. -func (k Keeper) Subspaces( - goCtx context.Context, - req *proposal.QuerySubspacesRequest, -) (*proposal.QuerySubspacesResponse, error) { - if req == nil { - return nil, status.Errorf(codes.InvalidArgument, "empty request") - } - - spaces := k.GetSubspaces() - resp := &proposal.QuerySubspacesResponse{ - Subspaces: make([]*proposal.Subspace, len(spaces)), - } - - ctx := sdk.UnwrapSDKContext(goCtx) - for i, ss := range spaces { - var keys []string - ss.IterateKeys(ctx, func(key []byte) bool { - keys = append(keys, string(key)) - return false - }) - - resp.Subspaces[i] = &proposal.Subspace{ - Subspace: ss.Name(), - Keys: keys, - } - } - - return resp, nil -} diff --git a/x/params/keeper/grpc_query_test.go b/x/params/keeper/grpc_query_test.go deleted file mode 100644 index abe252c19119..000000000000 --- a/x/params/keeper/grpc_query_test.go +++ /dev/null @@ -1,103 +0,0 @@ -package keeper_test - -import ( - "fmt" - - "github.com/cosmos/cosmos-sdk/x/params/types" - "github.com/cosmos/cosmos-sdk/x/params/types/proposal" -) - -func (suite *KeeperTestSuite) TestGRPCQueryParams() { - var ( - req *proposal.QueryParamsRequest - expValue string - space types.Subspace - ) - key := []byte("key") - - testCases := []struct { - msg string - malleate func() - expPass bool - }{ - { - "empty request", - func() { - req = &proposal.QueryParamsRequest{} - }, - false, - }, - { - "invalid request with subspace not found", - func() { - req = &proposal.QueryParamsRequest{Subspace: "test"} - }, - false, - }, - { - "invalid request with subspace and key not found", - func() { - req = &proposal.QueryParamsRequest{Subspace: "test", Key: "key"} - }, - false, - }, - { - "success", - func() { - space = suite.paramsKeeper.Subspace("test"). - WithKeyTable(types.NewKeyTable(types.NewParamSetPair(key, paramJSON{}, validateNoOp))) - req = &proposal.QueryParamsRequest{Subspace: "test", Key: "key"} - expValue = "" - }, - true, - }, - { - "update value success", - func() { - err := space.Update(suite.ctx, key, []byte(`{"param1":"10241024"}`)) - suite.Require().NoError(err) - req = &proposal.QueryParamsRequest{Subspace: "test", Key: "key"} - expValue = `{"param1":"10241024"}` - }, - true, - }, - } - - suite.SetupTest() - - for _, tc := range testCases { - suite.Run(fmt.Sprintf("Case %s", tc.msg), func() { - tc.malleate() - - res, err := suite.queryClient.Params(suite.ctx, req) - - if tc.expPass { - suite.Require().NoError(err) - suite.Require().NotNil(res) - suite.Require().Equal(expValue, res.Param.Value) - } else { - suite.Require().Error(err) - suite.Require().Nil(res) - } - }) - } -} - -func (suite *KeeperTestSuite) TestGRPCQuerySubspaces() { - // NOTE: Each subspace will not have any keys that we can check against - // because InitGenesis has not been called during app construction. - resp, err := suite.queryClient.Subspaces(suite.ctx, &proposal.QuerySubspacesRequest{}) - suite.Require().NoError(err) - suite.Require().NotNil(resp) - - spaces := make([]string, len(resp.Subspaces)) - i := 0 - for _, ss := range resp.Subspaces { - spaces[i] = ss.Subspace - i++ - } - - // require the response contains a few subspaces we know exist - suite.Require().Contains(spaces, "bank") - suite.Require().Contains(spaces, "staking") -} diff --git a/x/params/keeper/keeper.go b/x/params/keeper/keeper.go deleted file mode 100644 index a57124d6dc60..000000000000 --- a/x/params/keeper/keeper.go +++ /dev/null @@ -1,78 +0,0 @@ -package keeper - -import ( - "cosmossdk.io/log" - storetypes "cosmossdk.io/store/types" - - "github.com/cosmos/cosmos-sdk/codec" - sdk "github.com/cosmos/cosmos-sdk/types" - "github.com/cosmos/cosmos-sdk/x/params/types" - "github.com/cosmos/cosmos-sdk/x/params/types/proposal" -) - -// Keeper of the global paramstore -// -// Deprecated: the params keeper is deprecated and will be removed in the next Cosmos SDK major release. -type Keeper struct { - cdc codec.BinaryCodec - legacyAmino *codec.LegacyAmino - key storetypes.StoreKey - tkey storetypes.StoreKey - spaces map[string]*types.Subspace -} - -// NewKeeper constructs a params keeper -// -// Deprecated: the params keeper is deprecated and will be removed in the next Cosmos SDK major release. -func NewKeeper(cdc codec.BinaryCodec, legacyAmino *codec.LegacyAmino, key, tkey storetypes.StoreKey) Keeper { - return Keeper{ - cdc: cdc, - legacyAmino: legacyAmino, - key: key, - tkey: tkey, - spaces: make(map[string]*types.Subspace), - } -} - -// Logger returns a module-specific logger. -func (k Keeper) Logger(ctx sdk.Context) log.Logger { - return ctx.Logger().With("module", "x/"+proposal.ModuleName) -} - -// Allocate subspace used for keepers -func (k Keeper) Subspace(s string) types.Subspace { - _, ok := k.spaces[s] - if ok { - panic("subspace already occupied") - } - - if s == "" { - panic("cannot use empty string for subspace") - } - - space := types.NewSubspace(k.cdc, k.legacyAmino, k.key, k.tkey, s) - k.spaces[s] = &space - - return space -} - -// Get existing substore from keeper -func (k Keeper) GetSubspace(s string) (types.Subspace, bool) { - space, ok := k.spaces[s] - if !ok { - return types.Subspace{}, false - } - return *space, ok -} - -// GetSubspaces returns all the registered subspaces. -func (k Keeper) GetSubspaces() []types.Subspace { - spaces := make([]types.Subspace, len(k.spaces)) - i := 0 - for _, ss := range k.spaces { - spaces[i] = *ss - i++ - } - - return spaces -} diff --git a/x/params/keeper/keeper_test.go b/x/params/keeper/keeper_test.go deleted file mode 100644 index f765c7b7902c..000000000000 --- a/x/params/keeper/keeper_test.go +++ /dev/null @@ -1,283 +0,0 @@ -package keeper_test - -import ( - "reflect" - "testing" - - "github.com/stretchr/testify/require" - "github.com/stretchr/testify/suite" - - "cosmossdk.io/math" - "cosmossdk.io/store/prefix" - storetypes "cosmossdk.io/store/types" - - "github.com/cosmos/cosmos-sdk/baseapp" - "github.com/cosmos/cosmos-sdk/testutil" - sdk "github.com/cosmos/cosmos-sdk/types" - moduletestutil "github.com/cosmos/cosmos-sdk/types/module/testutil" - "github.com/cosmos/cosmos-sdk/x/params" - "github.com/cosmos/cosmos-sdk/x/params/keeper" - "github.com/cosmos/cosmos-sdk/x/params/types" - "github.com/cosmos/cosmos-sdk/x/params/types/proposal" -) - -type KeeperTestSuite struct { - suite.Suite - - ctx sdk.Context - paramsKeeper keeper.Keeper - queryClient proposal.QueryClient -} - -func (suite *KeeperTestSuite) SetupTest() { - encodingCfg := moduletestutil.MakeTestEncodingConfig(params.AppModuleBasic{}) - key := storetypes.NewKVStoreKey(types.StoreKey) - tkey := storetypes.NewTransientStoreKey("params_transient_test") - - suite.ctx = testutil.DefaultContext(key, tkey) - suite.paramsKeeper = keeper.NewKeeper(encodingCfg.Codec, encodingCfg.Amino, key, tkey) - suite.paramsKeeper.Subspace("bank") - suite.paramsKeeper.Subspace("staking") - - queryHelper := baseapp.NewQueryServerTestHelper(suite.ctx, encodingCfg.InterfaceRegistry) - proposal.RegisterQueryServer(queryHelper, suite.paramsKeeper) - - suite.queryClient = proposal.NewQueryClient(queryHelper) -} - -func TestKeeperTestSuite(t *testing.T) { - suite.Run(t, new(KeeperTestSuite)) -} - -func validateNoOp(_ any) error { return nil } - -func TestKeeper(t *testing.T) { - kvs := []struct { - key string - param int64 - }{ - {"key1", 10}, - {"key2", 55}, - {"key3", 182}, - {"key4", 17582}, - {"key5", 2768554}, - {"key6", 1157279}, - {"key7", 9058701}, - } - - table := types.NewKeyTable( - types.NewParamSetPair([]byte("key1"), int64(0), validateNoOp), - types.NewParamSetPair([]byte("key2"), int64(0), validateNoOp), - types.NewParamSetPair([]byte("key3"), int64(0), validateNoOp), - types.NewParamSetPair([]byte("key4"), int64(0), validateNoOp), - types.NewParamSetPair([]byte("key5"), int64(0), validateNoOp), - types.NewParamSetPair([]byte("key6"), int64(0), validateNoOp), - types.NewParamSetPair([]byte("key7"), int64(0), validateNoOp), - types.NewParamSetPair([]byte("extra1"), bool(false), validateNoOp), - types.NewParamSetPair([]byte("extra2"), string(""), validateNoOp), - ) - - cdc, ctx, skey, _, keeper := testComponents() - - store := prefix.NewStore(ctx.KVStore(skey), []byte("test/")) - space := keeper.Subspace("test") - require.False(t, space.HasKeyTable()) - space = space.WithKeyTable(table) - require.True(t, space.HasKeyTable()) - - // Set params - for i, kv := range kvs { - require.NotPanics(t, func() { space.Set(ctx, []byte(kv.key), kv.param) }, "space.Set panics, tc #%d", i) - } - - // Test space.Get - for i, kv := range kvs { - var param int64 - require.NotPanics(t, func() { space.Get(ctx, []byte(kv.key), ¶m) }, "space.Get panics, tc #%d", i) - require.Equal(t, kv.param, param, "stored param not equal, tc #%d", i) - } - - // Test space.GetRaw - for i, kv := range kvs { - var param int64 - bz := space.GetRaw(ctx, []byte(kv.key)) - err := cdc.UnmarshalJSON(bz, ¶m) - require.Nil(t, err, "err is not nil, tc #%d", i) - require.Equal(t, kv.param, param, "stored param not equal, tc #%d", i) - } - - // Test store.Get equals space.Get - for i, kv := range kvs { - var param int64 - bz := store.Get([]byte(kv.key)) - require.NotNil(t, bz, "KVStore.Get returns nil, tc #%d", i) - err := cdc.UnmarshalJSON(bz, ¶m) - require.NoError(t, err, "UnmarshalJSON returns error, tc #%d", i) - require.Equal(t, kv.param, param, "stored param not equal, tc #%d", i) - } - - // Test invalid space.Get - for i, kv := range kvs { - var param bool - require.Panics(t, func() { space.Get(ctx, []byte(kv.key), ¶m) }, "invalid space.Get not panics, tc #%d", i) - } - - // Test invalid space.Set - for i, kv := range kvs { - require.Panics(t, func() { space.Set(ctx, []byte(kv.key), true) }, "invalid space.Set not panics, tc #%d", i) - } - - // Test GetSubspace - for i, kv := range kvs { - var gparam, param int64 - gspace, ok := keeper.GetSubspace("test") - require.True(t, ok, "cannot retrieve subspace, tc #%d", i) - - require.NotPanics(t, func() { gspace.Get(ctx, []byte(kv.key), &gparam) }) - require.NotPanics(t, func() { space.Get(ctx, []byte(kv.key), ¶m) }) - require.Equal(t, gparam, param, "GetSubspace().Get not equal with space.Get, tc #%d", i) - - require.NotPanics(t, func() { gspace.Set(ctx, []byte(kv.key), int64(i)) }) - require.NotPanics(t, func() { space.Get(ctx, []byte(kv.key), ¶m) }) - require.Equal(t, int64(i), param, "GetSubspace().Set not equal with space.Get, tc #%d", i) - } -} - -func indirect(ptr any) any { - return reflect.ValueOf(ptr).Elem().Interface() -} - -func TestGetSubspaces(t *testing.T) { - _, _, _, _, keeper := testComponents() - - table := types.NewKeyTable( - types.NewParamSetPair([]byte("string"), "", validateNoOp), - types.NewParamSetPair([]byte("bool"), false, validateNoOp), - ) - - _ = keeper.Subspace("key1").WithKeyTable(table) - _ = keeper.Subspace("key2").WithKeyTable(table) - - spaces := keeper.GetSubspaces() - require.Len(t, spaces, 2) - - var names []string - for _, ss := range spaces { - names = append(names, ss.Name()) - } - - require.Contains(t, names, "key1") - require.Contains(t, names, "key2") -} - -func TestSubspace(t *testing.T) { - cdc, ctx, key, _, keeper := testComponents() - - kvs := []struct { - key string - param any - zero any - ptr any - }{ - {"string", "test", "", new(string)}, - {"bool", true, false, new(bool)}, - {"int16", int16(1), int16(0), new(int16)}, - {"int32", int32(1), int32(0), new(int32)}, - {"int64", int64(1), int64(0), new(int64)}, - {"uint16", uint16(1), uint16(0), new(uint16)}, - {"uint32", uint32(1), uint32(0), new(uint32)}, - {"uint64", uint64(1), uint64(0), new(uint64)}, - {"int", math.NewInt(1), math.Int{}, new(math.Int)}, - {"uint", math.NewUint(1), math.Uint{}, new(math.Uint)}, - {"dec", math.LegacyNewDec(1), math.LegacyDec{}, new(math.LegacyDec)}, - {"struct", s{1}, s{0}, new(s)}, - } - - table := types.NewKeyTable( - types.NewParamSetPair([]byte("string"), "", validateNoOp), - types.NewParamSetPair([]byte("bool"), false, validateNoOp), - types.NewParamSetPair([]byte("int16"), int16(0), validateNoOp), - types.NewParamSetPair([]byte("int32"), int32(0), validateNoOp), - types.NewParamSetPair([]byte("int64"), int64(0), validateNoOp), - types.NewParamSetPair([]byte("uint16"), uint16(0), validateNoOp), - types.NewParamSetPair([]byte("uint32"), uint32(0), validateNoOp), - types.NewParamSetPair([]byte("uint64"), uint64(0), validateNoOp), - types.NewParamSetPair([]byte("int"), math.Int{}, validateNoOp), - types.NewParamSetPair([]byte("uint"), math.Uint{}, validateNoOp), - types.NewParamSetPair([]byte("dec"), math.LegacyDec{}, validateNoOp), - types.NewParamSetPair([]byte("struct"), s{}, validateNoOp), - ) - - store := prefix.NewStore(ctx.KVStore(key), []byte("test/")) - space := keeper.Subspace("test").WithKeyTable(table) - - // Test space.Set, space.Modified - for i, kv := range kvs { - require.False(t, space.Modified(ctx, []byte(kv.key)), "space.Modified returns true before setting, tc #%d", i) - require.NotPanics(t, func() { space.Set(ctx, []byte(kv.key), kv.param) }, "space.Set panics, tc #%d", i) - require.True(t, space.Modified(ctx, []byte(kv.key)), "space.Modified returns false after setting, tc #%d", i) - } - - // Test space.Get, space.GetIfExists - for i, kv := range kvs { - require.NotPanics(t, func() { space.GetIfExists(ctx, []byte("invalid"), kv.ptr) }, "space.GetIfExists panics when no value exists, tc #%d", i) - require.Equal(t, kv.zero, indirect(kv.ptr), "space.GetIfExists unmarshals when no value exists, tc #%d", i) - require.Panics(t, func() { space.Get(ctx, []byte("invalid"), kv.ptr) }, "invalid space.Get not panics when no value exists, tc #%d", i) - require.Equal(t, kv.zero, indirect(kv.ptr), "invalid space.Get unmarshals when no value exists, tc #%d", i) - - require.NotPanics(t, func() { space.GetIfExists(ctx, []byte(kv.key), kv.ptr) }, "space.GetIfExists panics, tc #%d", i) - require.Equal(t, kv.param, indirect(kv.ptr), "stored param not equal, tc #%d", i) - require.NotPanics(t, func() { space.Get(ctx, []byte(kv.key), kv.ptr) }, "space.Get panics, tc #%d", i) - require.Equal(t, kv.param, indirect(kv.ptr), "stored param not equal, tc #%d", i) - - require.Panics(t, func() { space.Get(ctx, []byte("invalid"), kv.ptr) }, "invalid space.Get not panics when no value exists, tc #%d", i) - require.Equal(t, kv.param, indirect(kv.ptr), "invalid space.Get unmarshals when no value exist, tc #%d", i) - - require.Panics(t, func() { space.Get(ctx, []byte(kv.key), nil) }, "invalid space.Get not panics when the pointer is nil, tc #%d", i) - require.Panics(t, func() { space.Get(ctx, []byte(kv.key), new(invalid)) }, "invalid space.Get not panics when the pointer is different type, tc #%d", i) - } - - // Test store.Get equals space.Get - for i, kv := range kvs { - bz := store.Get([]byte(kv.key)) - require.NotNil(t, bz, "store.Get() returns nil, tc #%d", i) - err := cdc.UnmarshalJSON(bz, kv.ptr) - require.NoError(t, err, "cdc.UnmarshalJSON() returns error, tc #%d", i) - require.Equal(t, kv.param, indirect(kv.ptr), "stored param not equal, tc #%d", i) - } -} - -type paramJSON struct { - Param1 int64 `json:"param1,omitempty" yaml:"param1,omitempty"` - Param2 string `json:"param2,omitempty" yaml:"param2,omitempty"` -} - -func TestJSONUpdate(t *testing.T) { - _, ctx, _, _, keeper := testComponents() - - key := []byte("key") - - space := keeper.Subspace("test").WithKeyTable(types.NewKeyTable(types.NewParamSetPair(key, paramJSON{}, validateNoOp))) - - var param paramJSON - - err := space.Update(ctx, key, []byte(`{"param1": "10241024"}`)) - require.NoError(t, err) - space.Get(ctx, key, ¶m) - require.Equal(t, paramJSON{10241024, ""}, param) - - err = space.Update(ctx, key, []byte(`{"param2": "helloworld"}`)) - require.NoError(t, err) - space.Get(ctx, key, ¶m) - require.Equal(t, paramJSON{10241024, "helloworld"}, param) - - err = space.Update(ctx, key, []byte(`{"param1": "20482048"}`)) - require.NoError(t, err) - space.Get(ctx, key, ¶m) - require.Equal(t, paramJSON{20482048, "helloworld"}, param) - - err = space.Update(ctx, key, []byte(`{"param1": "40964096", "param2": "goodbyeworld"}`)) - require.NoError(t, err) - space.Get(ctx, key, ¶m) - require.Equal(t, paramJSON{40964096, "goodbyeworld"}, param) -} diff --git a/x/params/module.go b/x/params/module.go deleted file mode 100644 index 133900c4324d..000000000000 --- a/x/params/module.go +++ /dev/null @@ -1,157 +0,0 @@ -package params - -import ( - "context" - - gwruntime "github.com/grpc-ecosystem/grpc-gateway/runtime" - - modulev1 "cosmossdk.io/api/cosmos/params/module/v1" - "cosmossdk.io/core/appmodule" - "cosmossdk.io/depinject" - store "cosmossdk.io/store/types" - - "github.com/cosmos/cosmos-sdk/client" - "github.com/cosmos/cosmos-sdk/codec" - codectypes "github.com/cosmos/cosmos-sdk/codec/types" - "github.com/cosmos/cosmos-sdk/types/module" - simtypes "github.com/cosmos/cosmos-sdk/types/simulation" - govv1beta1 "github.com/cosmos/cosmos-sdk/x/gov/types/v1beta1" - "github.com/cosmos/cosmos-sdk/x/params/keeper" - "github.com/cosmos/cosmos-sdk/x/params/types" - "github.com/cosmos/cosmos-sdk/x/params/types/proposal" -) - -var ( - _ module.AppModuleBasic = AppModule{} - _ module.AppModuleSimulation = AppModule{} - _ module.HasServices = AppModule{} - - _ appmodule.AppModule = AppModule{} -) - -// ConsensusVersion defines the current x/params module consensus version. -const ConsensusVersion = 1 - -// AppModuleBasic defines the basic application module used by the params module. -type AppModuleBasic struct{} - -// Name returns the params module's name. -func (AppModuleBasic) Name() string { - return proposal.ModuleName -} - -// RegisterLegacyAminoCodec registers the params module's types on the given LegacyAmino codec. -func (AppModuleBasic) RegisterLegacyAminoCodec(cdc *codec.LegacyAmino) { - proposal.RegisterLegacyAminoCodec(cdc) -} - -// RegisterGRPCGatewayRoutes registers the gRPC Gateway routes for the params module. -func (AppModuleBasic) RegisterGRPCGatewayRoutes(clientCtx client.Context, mux *gwruntime.ServeMux) { - if err := proposal.RegisterQueryHandlerClient(context.Background(), mux, proposal.NewQueryClient(clientCtx)); err != nil { - panic(err) - } -} - -func (am AppModuleBasic) RegisterInterfaces(registry codectypes.InterfaceRegistry) { - proposal.RegisterInterfaces(registry) -} - -// AppModule implements an application module for the distribution module. -// -// Deprecated: the params module is deprecated and will be removed in the next Cosmos SDK major release. -type AppModule struct { - AppModuleBasic - - keeper keeper.Keeper -} - -// NewAppModule creates a new AppModule object -// -// Deprecated: the params module is deprecated and will be removed in the next Cosmos SDK major release. -func NewAppModule(k keeper.Keeper) AppModule { - return AppModule{ - AppModuleBasic: AppModuleBasic{}, - keeper: k, - } -} - -// IsOnePerModuleType implements the depinject.OnePerModuleType interface. -func (am AppModule) IsOnePerModuleType() {} - -// IsAppModule implements the appmodule.AppModule interface. -func (am AppModule) IsAppModule() {} - -// GenerateGenesisState performs a no-op. -func (AppModule) GenerateGenesisState(simState *module.SimulationState) {} - -// RegisterServices registers a gRPC query service to respond to the -// module-specific gRPC queries. -func (am AppModule) RegisterServices(cfg module.Configurator) { - proposal.RegisterQueryServer(cfg.QueryServer(), am.keeper) -} - -// RegisterStoreDecoder doesn't register any type. -func (AppModule) RegisterStoreDecoder(sdr simtypes.StoreDecoderRegistry) {} - -// WeightedOperations returns the all the gov module operations with their respective weights. -func (am AppModule) WeightedOperations(_ module.SimulationState) []simtypes.WeightedOperation { - return nil -} - -// ConsensusVersion implements AppModule/ConsensusVersion. -func (AppModule) ConsensusVersion() uint64 { return ConsensusVersion } - -// -// App Wiring Setup -// - -func init() { - appmodule.Register(&modulev1.Module{}, - appmodule.Provide( - ProvideModule, - ProvideSubspace, - )) -} - -type ModuleInputs struct { - depinject.In - - KvStoreKey *store.KVStoreKey - TransientStoreKey *store.TransientStoreKey - Cdc codec.Codec - LegacyAmino *codec.LegacyAmino -} - -type ModuleOutputs struct { - depinject.Out - - ParamsKeeper keeper.Keeper - Module appmodule.AppModule - GovHandler govv1beta1.HandlerRoute -} - -func ProvideModule(in ModuleInputs) ModuleOutputs { - k := keeper.NewKeeper(in.Cdc, in.LegacyAmino, in.KvStoreKey, in.TransientStoreKey) - - m := NewAppModule(k) - govHandler := govv1beta1.HandlerRoute{RouteKey: proposal.RouterKey, Handler: NewParamChangeProposalHandler(k)} - - return ModuleOutputs{ParamsKeeper: k, Module: m, GovHandler: govHandler} -} - -type SubspaceInputs struct { - depinject.In - - Key depinject.ModuleKey - Keeper keeper.Keeper - KeyTables map[string]types.KeyTable -} - -func ProvideSubspace(in SubspaceInputs) types.Subspace { - moduleName := in.Key.Name() - kt, exists := in.KeyTables[moduleName] - if !exists { - return in.Keeper.Subspace(moduleName) - } - return in.Keeper.Subspace(moduleName).WithKeyTable(kt) -} diff --git a/x/params/proposal_handler.go b/x/params/proposal_handler.go deleted file mode 100644 index cc24dd0109d4..000000000000 --- a/x/params/proposal_handler.go +++ /dev/null @@ -1,45 +0,0 @@ -package params - -import ( - "fmt" - - errorsmod "cosmossdk.io/errors" - - sdk "github.com/cosmos/cosmos-sdk/types" - sdkerrors "github.com/cosmos/cosmos-sdk/types/errors" - govtypes "github.com/cosmos/cosmos-sdk/x/gov/types/v1beta1" - "github.com/cosmos/cosmos-sdk/x/params/keeper" - "github.com/cosmos/cosmos-sdk/x/params/types/proposal" -) - -// NewParamChangeProposalHandler creates a new governance Handler for a ParamChangeProposal -func NewParamChangeProposalHandler(k keeper.Keeper) govtypes.Handler { - return func(ctx sdk.Context, content govtypes.Content) error { - switch c := content.(type) { - case *proposal.ParameterChangeProposal: - return handleParameterChangeProposal(ctx, k, c) - - default: - return errorsmod.Wrapf(sdkerrors.ErrUnknownRequest, "unrecognized param proposal content type: %T", c) - } - } -} - -func handleParameterChangeProposal(ctx sdk.Context, k keeper.Keeper, p *proposal.ParameterChangeProposal) error { - for _, c := range p.Changes { - ss, ok := k.GetSubspace(c.Subspace) - if !ok { - return errorsmod.Wrap(proposal.ErrUnknownSubspace, c.Subspace) - } - - k.Logger(ctx).Info( - fmt.Sprintf("attempt to set new parameter value; key: %s, value: %s", c.Key, c.Value), - ) - - if err := ss.Update(ctx, []byte(c.Key), []byte(c.Value)); err != nil { - return errorsmod.Wrapf(proposal.ErrSettingParameter, "key: %s, value: %s, err: %s", c.Key, c.Value, err.Error()) - } - } - - return nil -} diff --git a/x/params/proposal_handler_test.go b/x/params/proposal_handler_test.go deleted file mode 100644 index cc8a83903c3b..000000000000 --- a/x/params/proposal_handler_test.go +++ /dev/null @@ -1,115 +0,0 @@ -package params_test - -import ( - "context" - "testing" - - "github.com/stretchr/testify/suite" - "go.uber.org/mock/gomock" - - storetypes "cosmossdk.io/store/types" - - "github.com/cosmos/cosmos-sdk/testutil" - sdk "github.com/cosmos/cosmos-sdk/types" - moduletestutil "github.com/cosmos/cosmos-sdk/types/module/testutil" - govv1beta1 "github.com/cosmos/cosmos-sdk/x/gov/types/v1beta1" - "github.com/cosmos/cosmos-sdk/x/params" - "github.com/cosmos/cosmos-sdk/x/params/keeper" - paramstestutil "github.com/cosmos/cosmos-sdk/x/params/testutil" - paramtypes "github.com/cosmos/cosmos-sdk/x/params/types" - "github.com/cosmos/cosmos-sdk/x/params/types/proposal" - stakingtypes "github.com/cosmos/cosmos-sdk/x/staking/types" -) - -// StakingKeeper defines the expected staking keeper -type StakingKeeper interface { - MaxValidators(ctx context.Context) (res uint32, err error) -} - -type HandlerTestSuite struct { - suite.Suite - - ctx sdk.Context - govHandler govv1beta1.Handler - stakingKeeper StakingKeeper -} - -func (suite *HandlerTestSuite) SetupTest() { - encodingCfg := moduletestutil.MakeTestEncodingConfig(params.AppModuleBasic{}) - key := storetypes.NewKVStoreKey(paramtypes.StoreKey) - tkey := storetypes.NewTransientStoreKey("params_transient_test") - - ctx := testutil.DefaultContext(key, tkey) - paramsKeeper := keeper.NewKeeper(encodingCfg.Codec, encodingCfg.Amino, key, tkey) - paramsKeeper.Subspace("staking").WithKeyTable(stakingtypes.ParamKeyTable()) //nolint:staticcheck // TODO: deprecate this test case - ctrl := gomock.NewController(suite.T()) - stakingKeeper := paramstestutil.NewMockStakingKeeper(ctrl) - stakingKeeper.EXPECT().MaxValidators(ctx).Return(uint32(1), nil) - - suite.govHandler = params.NewParamChangeProposalHandler(paramsKeeper) - suite.stakingKeeper = stakingKeeper - suite.ctx = ctx -} - -func TestHandlerTestSuite(t *testing.T) { - suite.Run(t, new(HandlerTestSuite)) -} - -func testProposal(changes ...proposal.ParamChange) *proposal.ParameterChangeProposal { - return proposal.NewParameterChangeProposal("title", "description", changes) -} - -func (suite *HandlerTestSuite) TestProposalHandler() { - testCases := []struct { - name string - proposal *proposal.ParameterChangeProposal - onHandle func() - expErr bool - }{ - { - "all fields", - testProposal(proposal.NewParamChange(stakingtypes.ModuleName, string(stakingtypes.KeyMaxValidators), "1")), - func() { - maxVals, err := suite.stakingKeeper.MaxValidators(suite.ctx) - suite.Require().NoError(err) - suite.Require().Equal(uint32(1), maxVals) - }, - false, - }, - { - "invalid type", - testProposal(proposal.NewParamChange(stakingtypes.ModuleName, string(stakingtypes.KeyMaxValidators), "-")), - func() {}, - true, - }, - //{ - // "omit empty fields", - // testProposal(proposal.ParamChange{ - // Subspace: govtypes.ModuleName, - // Key: string(govv1.ParamStoreKeyDepositParams), - // Value: `{"min_deposit": [{"denom": "uatom","amount": "64000000"}], "max_deposit_period": "172800000000000"}`, - // }), - // func() { - // depositParams := suite.app.GovKeeper.GetDepositParams(suite.ctx) - // defaultPeriod := govv1.DefaultPeriod - // suite.Require().Equal(govv1.DepositParams{ - // MinDeposit: sdk.NewCoins(sdk.NewCoin("uatom", sdkmath.NewInt(64000000))), - // MaxDepositPeriod: &defaultPeriod, - // }, depositParams) - // }, - // false, - // }, - } - - for _, tc := range testCases { - suite.Run(tc.name, func() { - err := suite.govHandler(suite.ctx, tc.proposal) - if tc.expErr { - suite.Require().Error(err) - } else { - suite.Require().NoError(err) - tc.onHandle() - } - }) - } -} diff --git a/x/params/simulation/operations.go b/x/params/simulation/operations.go deleted file mode 100644 index 1a3b7f4fed20..000000000000 --- a/x/params/simulation/operations.go +++ /dev/null @@ -1,47 +0,0 @@ -package simulation - -import ( - "fmt" - "math/rand" - - sdk "github.com/cosmos/cosmos-sdk/types" - "github.com/cosmos/cosmos-sdk/types/simulation" - "github.com/cosmos/cosmos-sdk/x/params/types/proposal" -) - -// SimulateParamChangeProposalContent returns random parameter change content. -// It will generate a ParameterChangeProposal object with anywhere between 1 and -// the total amount of defined parameters changes, all of which have random valid values. -// Deprecated: This method will be removed in the future -func SimulateParamChangeProposalContent(paramChangePool []simulation.LegacyParamChange) simulation.ContentSimulatorFn { //nolint:staticcheck // used for legacy testing - numProposals := 0 - // Bound the maximum number of simultaneous parameter changes - maxSimultaneousParamChanges := min(len(paramChangePool), 1000) - if maxSimultaneousParamChanges == 0 { - panic("param changes array is empty") - } - - return func(r *rand.Rand, _ sdk.Context, _ []simulation.Account) simulation.Content { //nolint:staticcheck // used for legacy testing - numChanges := simulation.RandIntBetween(r, 1, maxSimultaneousParamChanges) - paramChanges := make([]proposal.ParamChange, numChanges) - - // perm here takes at most len(paramChangePool) calls to random - paramChoices := r.Perm(len(paramChangePool)) - - for i := range numChanges { - spc := paramChangePool[paramChoices[i]] - // add a new distinct parameter to the set of changes - paramChanges[i] = proposal.NewParamChange(spc.Subspace(), spc.Key(), spc.SimValue()(r)) - } - - title := fmt.Sprintf("title from SimulateParamChangeProposalContent-%d", numProposals) - desc := fmt.Sprintf("desc from SimulateParamChangeProposalContent-%d. Random short desc: %s", - numProposals, simulation.RandStringOfLength(r, 20)) - numProposals++ - return proposal.NewParameterChangeProposal( - title, // title - desc, // description - paramChanges, // set of changes - ) - } -} diff --git a/x/params/simulation/operations_test.go b/x/params/simulation/operations_test.go deleted file mode 100644 index a23e42bf7011..000000000000 --- a/x/params/simulation/operations_test.go +++ /dev/null @@ -1,65 +0,0 @@ -package simulation_test - -import ( - "fmt" - "math/rand" - "testing" - - cmtproto "github.com/cometbft/cometbft/proto/tendermint/types" - "github.com/stretchr/testify/require" - - sdk "github.com/cosmos/cosmos-sdk/types" - simtypes "github.com/cosmos/cosmos-sdk/types/simulation" - "github.com/cosmos/cosmos-sdk/x/params/simulation" - "github.com/cosmos/cosmos-sdk/x/params/types/proposal" -) - -type MockParamChange struct { - n int -} - -func (pc MockParamChange) Subspace() string { - return fmt.Sprintf("test-Subspace%d", pc.n) -} - -func (pc MockParamChange) Key() string { - return fmt.Sprintf("test-Key%d", pc.n) -} - -func (pc MockParamChange) ComposedKey() string { - return fmt.Sprintf("test-ComposedKey%d", pc.n) -} - -func (pc MockParamChange) SimValue() simtypes.SimValFn { - return func(r *rand.Rand) string { - return fmt.Sprintf("test-value %d%d ", pc.n, int64(simtypes.RandIntBetween(r, 10, 1000))) - } -} - -// make sure that the MockParamChange satisfied the ParamChange interface -var _ simtypes.LegacyParamChange = MockParamChange{} - -func TestSimulateParamChangeProposalContent(t *testing.T) { - s := rand.NewSource(1) - r := rand.New(s) - - ctx := sdk.NewContext(nil, cmtproto.Header{}, true, nil) - accounts := simtypes.RandomAccounts(r, 3) - paramChangePool := []simtypes.LegacyParamChange{MockParamChange{1}, MockParamChange{2}, MockParamChange{3}} - - // execute operation - op := simulation.SimulateParamChangeProposalContent(paramChangePool) - content := op(r, ctx, accounts) - - require.Equal(t, "desc from SimulateParamChangeProposalContent-0. Random short desc: IivHSlcxgdXhhuTSkuxK", content.GetDescription()) - require.Equal(t, "title from SimulateParamChangeProposalContent-0", content.GetTitle()) - require.Equal(t, "params", content.ProposalRoute()) - require.Equal(t, "ParameterChange", content.ProposalType()) - - pcp, ok := content.(*proposal.ParameterChangeProposal) - require.True(t, ok) - - require.Equal(t, "test-Key2", pcp.Changes[0].GetKey()) - require.Equal(t, "test-value 2791 ", pcp.Changes[0].GetValue()) - require.Equal(t, "test-Subspace2", pcp.Changes[0].GetSubspace()) -} diff --git a/x/params/simulation/proposals.go b/x/params/simulation/proposals.go deleted file mode 100644 index 512313ff75f7..000000000000 --- a/x/params/simulation/proposals.go +++ /dev/null @@ -1,28 +0,0 @@ -package simulation - -import ( - simtypes "github.com/cosmos/cosmos-sdk/types/simulation" - "github.com/cosmos/cosmos-sdk/x/simulation" -) - -// will be removed in the future -const ( - // OpWeightSubmitParamChangeProposal app params key for param change proposal - OpWeightSubmitParamChangeProposal = "op_weight_submit_param_change_proposal" - DefaultWeightParamChangeProposal = 5 -) - -// ProposalContents defines the module weighted proposals' contents -// -// will be removed in the future -// -//nolint:staticcheck // used for legacy testing -func ProposalContents(paramChanges []simtypes.LegacyParamChange) []simtypes.WeightedProposalContent { - return []simtypes.WeightedProposalContent{ - simulation.NewWeightedProposalContent( - OpWeightSubmitParamChangeProposal, - DefaultWeightParamChangeProposal, - SimulateParamChangeProposalContent(paramChanges), - ), - } -} diff --git a/x/params/simulation/proposals_test.go b/x/params/simulation/proposals_test.go deleted file mode 100644 index aa80a6f0073d..000000000000 --- a/x/params/simulation/proposals_test.go +++ /dev/null @@ -1,50 +0,0 @@ -package simulation_test - -import ( - "math/rand" - "testing" - - cmtproto "github.com/cometbft/cometbft/proto/tendermint/types" - "github.com/stretchr/testify/require" - - sdk "github.com/cosmos/cosmos-sdk/types" - simtypes "github.com/cosmos/cosmos-sdk/types/simulation" - "github.com/cosmos/cosmos-sdk/x/params/simulation" - "github.com/cosmos/cosmos-sdk/x/params/types/proposal" -) - -func TestProposalContents(t *testing.T) { - // initialize parameters - s := rand.NewSource(1) - r := rand.New(s) - - ctx := sdk.NewContext(nil, cmtproto.Header{}, true, nil) - accounts := simtypes.RandomAccounts(r, 3) - - paramChangePool := []simtypes.LegacyParamChange{MockParamChange{1}, MockParamChange{2}, MockParamChange{3}} - - // execute ProposalContents function - weightedProposalContent := simulation.ProposalContents(paramChangePool) - require.Len(t, weightedProposalContent, 1) - - w0 := weightedProposalContent[0] - - // tests w0 interface: - require.Equal(t, simulation.OpWeightSubmitParamChangeProposal, w0.AppParamsKey()) - require.Equal(t, simulation.DefaultWeightParamChangeProposal, w0.DefaultWeight()) - - content := w0.ContentSimulatorFn()(r, ctx, accounts) - - require.Equal(t, "desc from SimulateParamChangeProposalContent-0. Random short desc: IivHSlcxgdXhhuTSkuxK", content.GetDescription()) - require.Equal(t, "title from SimulateParamChangeProposalContent-0", content.GetTitle()) - require.Equal(t, "params", content.ProposalRoute()) - require.Equal(t, "ParameterChange", content.ProposalType()) - - pcp, ok := content.(*proposal.ParameterChangeProposal) - require.True(t, ok) - - require.Len(t, pcp.Changes, 1) - require.Equal(t, "test-Key2", pcp.Changes[0].GetKey()) - require.Equal(t, "test-value 2791 ", pcp.Changes[0].GetValue()) - require.Equal(t, "test-Subspace2", pcp.Changes[0].GetSubspace()) -} diff --git a/x/params/testutil/staking_keeper_mock.go b/x/params/testutil/staking_keeper_mock.go deleted file mode 100644 index a12919790473..000000000000 --- a/x/params/testutil/staking_keeper_mock.go +++ /dev/null @@ -1,56 +0,0 @@ -// Code generated by MockGen. DO NOT EDIT. -// Source: x/params/proposal_handler_test.go -// -// Generated by this command: -// -// mockgen -source=x/params/proposal_handler_test.go -package testutil -destination x/params/testutil/staking_keeper_mock.go -// - -// Package testutil is a generated GoMock package. -package testutil - -import ( - context "context" - reflect "reflect" - - gomock "go.uber.org/mock/gomock" -) - -// MockStakingKeeper is a mock of StakingKeeper interface. -type MockStakingKeeper struct { - ctrl *gomock.Controller - recorder *MockStakingKeeperMockRecorder - isgomock struct{} -} - -// MockStakingKeeperMockRecorder is the mock recorder for MockStakingKeeper. -type MockStakingKeeperMockRecorder struct { - mock *MockStakingKeeper -} - -// NewMockStakingKeeper creates a new mock instance. -func NewMockStakingKeeper(ctrl *gomock.Controller) *MockStakingKeeper { - mock := &MockStakingKeeper{ctrl: ctrl} - mock.recorder = &MockStakingKeeperMockRecorder{mock} - return mock -} - -// EXPECT returns an object that allows the caller to indicate expected use. -func (m *MockStakingKeeper) EXPECT() *MockStakingKeeperMockRecorder { - return m.recorder -} - -// MaxValidators mocks base method. -func (m *MockStakingKeeper) MaxValidators(ctx context.Context) (uint32, error) { - m.ctrl.T.Helper() - ret := m.ctrl.Call(m, "MaxValidators", ctx) - ret0, _ := ret[0].(uint32) - ret1, _ := ret[1].(error) - return ret0, ret1 -} - -// MaxValidators indicates an expected call of MaxValidators. -func (mr *MockStakingKeeperMockRecorder) MaxValidators(ctx any) *gomock.Call { - mr.mock.ctrl.T.Helper() - return mr.mock.ctrl.RecordCallWithMethodType(mr.mock, "MaxValidators", reflect.TypeOf((*MockStakingKeeper)(nil).MaxValidators), ctx) -} diff --git a/x/params/types/common_test.go b/x/params/types/common_test.go deleted file mode 100644 index 2300a4106db7..000000000000 --- a/x/params/types/common_test.go +++ /dev/null @@ -1,99 +0,0 @@ -package types_test - -import ( - "errors" - "fmt" - "time" - - storetypes "cosmossdk.io/store/types" - - "github.com/cosmos/cosmos-sdk/x/params/types" -) - -var ( - keyUnbondingTime = []byte("UnbondingTime") - keyMaxValidators = []byte("MaxValidators") - keyBondDenom = []byte("BondDenom") - keyMaxRedelegationEntries = []byte("MaxRedelegationEntries") - - key = storetypes.NewKVStoreKey("storekey") - tkey = storetypes.NewTransientStoreKey("transientstorekey") -) - -type params struct { - UnbondingTime time.Duration `json:"unbonding_time" yaml:"unbonding_time"` - MaxValidators uint16 `json:"max_validators" yaml:"max_validators"` - BondDenom string `json:"bond_denom" yaml:"bond_denom"` -} - -type paramsV2 struct { - UnbondingTime time.Duration `json:"unbonding_time" yaml:"unbonding_time"` - MaxValidators uint16 `json:"max_validators" yaml:"max_validators"` - BondDenom string `json:"bond_denom" yaml:"bond_denom"` - MaxRedelegationEntries uint32 `json:"max_redelegation_entries" yaml:"max_redelegation_entries"` -} - -func validateUnbondingTime(i any) error { - v, ok := i.(time.Duration) - if !ok { - return fmt.Errorf("invalid parameter type: %T", i) - } - - if v < (24 * time.Hour) { - return fmt.Errorf("unbonding time must be at least one day") - } - - return nil -} - -func validateMaxValidators(i any) error { - _, ok := i.(uint16) - if !ok { - return fmt.Errorf("invalid parameter type: %T", i) - } - - return nil -} - -func validateBondDenom(i any) error { - v, ok := i.(string) - if !ok { - return fmt.Errorf("invalid parameter type: %T", i) - } - - if len(v) == 0 { - return errors.New("denom cannot be empty") - } - - return nil -} - -func validateMaxRedelegationEntries(i any) error { - _, ok := i.(uint32) - if !ok { - return fmt.Errorf("invalid parameter type: %T", i) - } - - return nil -} - -func (p *params) ParamSetPairs() types.ParamSetPairs { - return types.ParamSetPairs{ - {keyUnbondingTime, &p.UnbondingTime, validateUnbondingTime}, - {keyMaxValidators, &p.MaxValidators, validateMaxValidators}, - {keyBondDenom, &p.BondDenom, validateBondDenom}, - } -} - -func (p *paramsV2) ParamSetPairs() types.ParamSetPairs { - return types.ParamSetPairs{ - {keyUnbondingTime, &p.UnbondingTime, validateUnbondingTime}, - {keyMaxValidators, &p.MaxValidators, validateMaxValidators}, - {keyBondDenom, &p.BondDenom, validateBondDenom}, - {keyMaxRedelegationEntries, &p.MaxRedelegationEntries, validateMaxRedelegationEntries}, - } -} - -func paramKeyTable() types.KeyTable { - return types.NewKeyTable().RegisterParamSet(¶ms{}) -} diff --git a/x/params/types/consensus_params_legacy.go b/x/params/types/consensus_params_legacy.go deleted file mode 100644 index 2ea43d366f47..000000000000 --- a/x/params/types/consensus_params_legacy.go +++ /dev/null @@ -1,22 +0,0 @@ -package types - -import ( - cmtproto "github.com/cometbft/cometbft/proto/tendermint/types" - - "github.com/cosmos/cosmos-sdk/baseapp" -) - -// Deprecated. -func ConsensusParamsKeyTable() KeyTable { - return NewKeyTable( - NewParamSetPair( - baseapp.ParamStoreKeyBlockParams, cmtproto.BlockParams{}, baseapp.ValidateBlockParams, - ), - NewParamSetPair( - baseapp.ParamStoreKeyEvidenceParams, cmtproto.EvidenceParams{}, baseapp.ValidateEvidenceParams, - ), - NewParamSetPair( - baseapp.ParamStoreKeyValidatorParams, cmtproto.ValidatorParams{}, baseapp.ValidateValidatorParams, - ), - ) -} diff --git a/x/params/types/deref_test.go b/x/params/types/deref_test.go deleted file mode 100644 index ecf9b7ce8990..000000000000 --- a/x/params/types/deref_test.go +++ /dev/null @@ -1,27 +0,0 @@ -package types - -import ( - "reflect" - "testing" - - "github.com/stretchr/testify/require" -) - -func TestKeyTableUnfurlsPointers(t *testing.T) { - tbl := NewKeyTable() - validator := func(_ any) error { - return nil - } - tbl = tbl.RegisterType(ParamSetPair{ - Key: []byte("key"), - Value: (*****string)(nil), - ValidatorFn: validator, - }) - - got := tbl.m["key"] - want := attribute{ - vfn: validator, - ty: reflect.ValueOf("").Type(), - } - require.Equal(t, got.ty, want.ty) -} diff --git a/x/params/types/doc.go b/x/params/types/doc.go deleted file mode 100644 index 861a4a2f5842..000000000000 --- a/x/params/types/doc.go +++ /dev/null @@ -1,13 +0,0 @@ -/* -To prevent namespace collision between consumer modules, we define a type -Subspace. A Subspace can only be generated by the keeper, and the keeper checks -the existence of the Subspace having the same name before generating the -Subspace. - -Consumer modules must take a Subspace (via Keeper.Subspace), not the keeper -itself. This isolates each modules from the others and make them modify their -respective parameters safely. Keeper can be treated as master permission for all -Subspaces (via Keeper.GetSubspace), so should be passed to proper modules -(ex. x/governance). -*/ -package types diff --git a/x/params/types/keys.go b/x/params/types/keys.go deleted file mode 100644 index 87c925383ccc..000000000000 --- a/x/params/types/keys.go +++ /dev/null @@ -1,6 +0,0 @@ -package types - -const ( - // ModuleName defines the module name - ModuleName = "params" -) diff --git a/x/params/types/paramset.go b/x/params/types/paramset.go deleted file mode 100644 index 1c196b61ade3..000000000000 --- a/x/params/types/paramset.go +++ /dev/null @@ -1,26 +0,0 @@ -package types - -type ( - ValueValidatorFn func(value any) error - - // ParamSetPair is used for associating paramsubspace key and field of param - // structs. - ParamSetPair struct { - Key []byte - Value any - ValidatorFn ValueValidatorFn - } -) - -// NewParamSetPair creates a new ParamSetPair instance. -func NewParamSetPair(key []byte, value any, vfn ValueValidatorFn) ParamSetPair { - return ParamSetPair{key, value, vfn} -} - -// ParamSetPairs Slice of KeyFieldPair -type ParamSetPairs []ParamSetPair - -// ParamSet defines an interface for structs containing parameters for a module -type ParamSet interface { - ParamSetPairs() ParamSetPairs -} diff --git a/x/params/types/proposal/codec.go b/x/params/types/proposal/codec.go deleted file mode 100644 index 028c0686e3eb..000000000000 --- a/x/params/types/proposal/codec.go +++ /dev/null @@ -1,19 +0,0 @@ -package proposal - -import ( - "github.com/cosmos/cosmos-sdk/codec" - "github.com/cosmos/cosmos-sdk/codec/types" - govtypes "github.com/cosmos/cosmos-sdk/x/gov/types/v1beta1" -) - -// RegisterLegacyAminoCodec registers all necessary param module types with a given LegacyAmino codec. -func RegisterLegacyAminoCodec(cdc *codec.LegacyAmino) { - cdc.RegisterConcrete(&ParameterChangeProposal{}, "cosmos-sdk/ParameterChangeProposal", nil) -} - -func RegisterInterfaces(registry types.InterfaceRegistry) { - registry.RegisterImplementations( - (*govtypes.Content)(nil), - &ParameterChangeProposal{}, - ) -} diff --git a/x/params/types/proposal/errors.go b/x/params/types/proposal/errors.go deleted file mode 100644 index 880864b84433..000000000000 --- a/x/params/types/proposal/errors.go +++ /dev/null @@ -1,13 +0,0 @@ -package proposal - -import "cosmossdk.io/errors" - -// x/params module sentinel errors -var ( - ErrUnknownSubspace = errors.Register(ModuleName, 2, "unknown subspace") - ErrSettingParameter = errors.Register(ModuleName, 3, "failed to set parameter") - ErrEmptyChanges = errors.Register(ModuleName, 4, "submitted parameter changes are empty") - ErrEmptySubspace = errors.Register(ModuleName, 5, "parameter subspace is empty") - ErrEmptyKey = errors.Register(ModuleName, 6, "parameter key is empty") - ErrEmptyValue = errors.Register(ModuleName, 7, "parameter value is empty") -) diff --git a/x/params/types/proposal/keys.go b/x/params/types/proposal/keys.go deleted file mode 100644 index 0649f417433c..000000000000 --- a/x/params/types/proposal/keys.go +++ /dev/null @@ -1,9 +0,0 @@ -package proposal - -const ( - // ModuleName defines the name of the module - ModuleName = "params" - - // RouterKey defines the routing key for a ParameterChangeProposal - RouterKey = "params" -) diff --git a/x/params/types/proposal/params.pb.go b/x/params/types/proposal/params.pb.go deleted file mode 100644 index fbc9036fd948..000000000000 --- a/x/params/types/proposal/params.pb.go +++ /dev/null @@ -1,764 +0,0 @@ -// Code generated by protoc-gen-gogo. DO NOT EDIT. -// source: cosmos/params/v1beta1/params.proto - -package proposal - -import ( - fmt "fmt" - _ "github.com/cosmos/cosmos-proto" - _ "github.com/cosmos/cosmos-sdk/types/tx/amino" - _ "github.com/cosmos/gogoproto/gogoproto" - proto "github.com/cosmos/gogoproto/proto" - io "io" - math "math" - math_bits "math/bits" -) - -// Reference imports to suppress errors if they are not otherwise used. -var _ = proto.Marshal -var _ = fmt.Errorf -var _ = math.Inf - -// This is a compile-time assertion to ensure that this generated file -// is compatible with the proto package it is being compiled against. -// A compilation error at this line likely means your copy of the -// proto package needs to be updated. -const _ = proto.GoGoProtoPackageIsVersion3 // please upgrade the proto package - -// ParameterChangeProposal defines a proposal to change one or more parameters. -type ParameterChangeProposal struct { - Title string `protobuf:"bytes,1,opt,name=title,proto3" json:"title,omitempty"` - Description string `protobuf:"bytes,2,opt,name=description,proto3" json:"description,omitempty"` - Changes []ParamChange `protobuf:"bytes,3,rep,name=changes,proto3" json:"changes"` -} - -func (m *ParameterChangeProposal) Reset() { *m = ParameterChangeProposal{} } -func (m *ParameterChangeProposal) String() string { return proto.CompactTextString(m) } -func (*ParameterChangeProposal) ProtoMessage() {} -func (*ParameterChangeProposal) Descriptor() ([]byte, []int) { - return fileDescriptor_53a944ecb0483e4c, []int{0} -} -func (m *ParameterChangeProposal) XXX_Unmarshal(b []byte) error { - return m.Unmarshal(b) -} -func (m *ParameterChangeProposal) XXX_Marshal(b []byte, deterministic bool) ([]byte, error) { - if deterministic { - return xxx_messageInfo_ParameterChangeProposal.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 *ParameterChangeProposal) XXX_Merge(src proto.Message) { - xxx_messageInfo_ParameterChangeProposal.Merge(m, src) -} -func (m *ParameterChangeProposal) XXX_Size() int { - return m.Size() -} -func (m *ParameterChangeProposal) XXX_DiscardUnknown() { - xxx_messageInfo_ParameterChangeProposal.DiscardUnknown(m) -} - -var xxx_messageInfo_ParameterChangeProposal proto.InternalMessageInfo - -// ParamChange defines an individual parameter change, for use in -// ParameterChangeProposal. -type ParamChange struct { - Subspace string `protobuf:"bytes,1,opt,name=subspace,proto3" json:"subspace,omitempty"` - Key string `protobuf:"bytes,2,opt,name=key,proto3" json:"key,omitempty"` - Value string `protobuf:"bytes,3,opt,name=value,proto3" json:"value,omitempty"` -} - -func (m *ParamChange) Reset() { *m = ParamChange{} } -func (m *ParamChange) String() string { return proto.CompactTextString(m) } -func (*ParamChange) ProtoMessage() {} -func (*ParamChange) Descriptor() ([]byte, []int) { - return fileDescriptor_53a944ecb0483e4c, []int{1} -} -func (m *ParamChange) XXX_Unmarshal(b []byte) error { - return m.Unmarshal(b) -} -func (m *ParamChange) XXX_Marshal(b []byte, deterministic bool) ([]byte, error) { - if deterministic { - return xxx_messageInfo_ParamChange.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 *ParamChange) XXX_Merge(src proto.Message) { - xxx_messageInfo_ParamChange.Merge(m, src) -} -func (m *ParamChange) XXX_Size() int { - return m.Size() -} -func (m *ParamChange) XXX_DiscardUnknown() { - xxx_messageInfo_ParamChange.DiscardUnknown(m) -} - -var xxx_messageInfo_ParamChange proto.InternalMessageInfo - -func (m *ParamChange) GetSubspace() string { - if m != nil { - return m.Subspace - } - return "" -} - -func (m *ParamChange) GetKey() string { - if m != nil { - return m.Key - } - return "" -} - -func (m *ParamChange) GetValue() string { - if m != nil { - return m.Value - } - return "" -} - -func init() { - proto.RegisterType((*ParameterChangeProposal)(nil), "cosmos.params.v1beta1.ParameterChangeProposal") - proto.RegisterType((*ParamChange)(nil), "cosmos.params.v1beta1.ParamChange") -} - -func init() { - proto.RegisterFile("cosmos/params/v1beta1/params.proto", fileDescriptor_53a944ecb0483e4c) -} - -var fileDescriptor_53a944ecb0483e4c = []byte{ - // 354 bytes of a gzipped FileDescriptorProto - 0x1f, 0x8b, 0x08, 0x00, 0x00, 0x00, 0x00, 0x00, 0x02, 0xff, 0xe2, 0x52, 0x4a, 0xce, 0x2f, 0xce, - 0xcd, 0x2f, 0xd6, 0x2f, 0x48, 0x2c, 0x4a, 0xcc, 0x2d, 0xd6, 0x2f, 0x33, 0x4c, 0x4a, 0x2d, 0x49, - 0x34, 0x84, 0x72, 0xf5, 0x0a, 0x8a, 0xf2, 0x4b, 0xf2, 0x85, 0x44, 0x21, 0x6a, 0xf4, 0xa0, 0x82, - 0x50, 0x35, 0x52, 0x22, 0xe9, 0xf9, 0xe9, 0xf9, 0x60, 0x15, 0xfa, 0x20, 0x16, 0x44, 0xb1, 0x94, - 0x24, 0x44, 0x71, 0x3c, 0x44, 0x02, 0xa6, 0x13, 0x2c, 0x25, 0x98, 0x98, 0x9b, 0x99, 0x97, 0xaf, - 0x0f, 0x26, 0x21, 0x42, 0x4a, 0x4f, 0x19, 0xb9, 0xc4, 0x03, 0x40, 0xc6, 0xa6, 0x96, 0xa4, 0x16, - 0x39, 0x67, 0x24, 0xe6, 0xa5, 0xa7, 0x06, 0x14, 0xe5, 0x17, 0xe4, 0x17, 0x27, 0xe6, 0x08, 0x89, - 0x70, 0xb1, 0x96, 0x64, 0x96, 0xe4, 0xa4, 0x4a, 0x30, 0x2a, 0x30, 0x6a, 0x70, 0x06, 0x41, 0x38, - 0x42, 0x0a, 0x5c, 0xdc, 0x29, 0xa9, 0xc5, 0xc9, 0x45, 0x99, 0x05, 0x25, 0x99, 0xf9, 0x79, 0x12, - 0x4c, 0x60, 0x39, 0x64, 0x21, 0x21, 0x77, 0x2e, 0xf6, 0x64, 0xb0, 0x49, 0xc5, 0x12, 0xcc, 0x0a, - 0xcc, 0x1a, 0xdc, 0x46, 0x4a, 0x7a, 0x58, 0x3d, 0xa0, 0x07, 0xb6, 0x18, 0x62, 0xa9, 0x13, 0xe7, - 0x89, 0x7b, 0xf2, 0x0c, 0x2b, 0x9e, 0x6f, 0xd0, 0x62, 0x0c, 0x82, 0xe9, 0xb6, 0xf2, 0xec, 0x58, - 0x20, 0xcf, 0x70, 0x6a, 0x8b, 0xae, 0x14, 0x54, 0x7b, 0x7a, 0x7e, 0x19, 0x5c, 0xaf, 0x73, 0x7e, - 0x5e, 0x49, 0x6a, 0x5e, 0x49, 0xd7, 0xf3, 0x0d, 0x5a, 0xd0, 0x20, 0xd4, 0x2d, 0x4e, 0xc9, 0xd6, - 0xc7, 0xe1, 0x17, 0xa5, 0x40, 0x2e, 0x6e, 0x24, 0xdb, 0x84, 0xa4, 0xb8, 0x38, 0x8a, 0x4b, 0x93, - 0x8a, 0x0b, 0x12, 0x93, 0x61, 0xbe, 0x83, 0xf3, 0x85, 0x04, 0xb8, 0x98, 0xb3, 0x53, 0x2b, 0xa1, - 0x1e, 0x03, 0x31, 0x41, 0x01, 0x51, 0x96, 0x98, 0x53, 0x9a, 0x2a, 0xc1, 0x0c, 0x09, 0x08, 0x30, - 0xc7, 0x29, 0x68, 0xc5, 0x23, 0x39, 0xc6, 0x13, 0x8f, 0xe4, 0x18, 0x2f, 0x3c, 0x92, 0x63, 0x7c, - 0xf0, 0x48, 0x8e, 0x71, 0xc2, 0x63, 0x39, 0x86, 0x0b, 0x8f, 0xe5, 0x18, 0x6e, 0x3c, 0x96, 0x63, - 0x88, 0x32, 0x49, 0xcf, 0x2c, 0xc9, 0x28, 0x4d, 0xd2, 0x4b, 0xce, 0xcf, 0x85, 0x46, 0x82, 0x3e, - 0x92, 0x33, 0x2b, 0x60, 0xf1, 0x5d, 0x52, 0x59, 0x90, 0x5a, 0xac, 0x5f, 0x00, 0x75, 0x66, 0x12, - 0x1b, 0x38, 0x56, 0x8c, 0x01, 0x01, 0x00, 0x00, 0xff, 0xff, 0xb3, 0x70, 0xe1, 0x82, 0x16, 0x02, - 0x00, 0x00, -} - -func (this *ParameterChangeProposal) Equal(that interface{}) bool { - if that == nil { - return this == nil - } - - that1, ok := that.(*ParameterChangeProposal) - if !ok { - that2, ok := that.(ParameterChangeProposal) - if ok { - that1 = &that2 - } else { - return false - } - } - if that1 == nil { - return this == nil - } else if this == nil { - return false - } - if this.Title != that1.Title { - return false - } - if this.Description != that1.Description { - return false - } - if len(this.Changes) != len(that1.Changes) { - return false - } - for i := range this.Changes { - if !this.Changes[i].Equal(&that1.Changes[i]) { - return false - } - } - return true -} -func (this *ParamChange) Equal(that interface{}) bool { - if that == nil { - return this == nil - } - - that1, ok := that.(*ParamChange) - if !ok { - that2, ok := that.(ParamChange) - if ok { - that1 = &that2 - } else { - return false - } - } - if that1 == nil { - return this == nil - } else if this == nil { - return false - } - if this.Subspace != that1.Subspace { - return false - } - if this.Key != that1.Key { - return false - } - if this.Value != that1.Value { - return false - } - return true -} -func (m *ParameterChangeProposal) 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 *ParameterChangeProposal) MarshalTo(dAtA []byte) (int, error) { - size := m.Size() - return m.MarshalToSizedBuffer(dAtA[:size]) -} - -func (m *ParameterChangeProposal) MarshalToSizedBuffer(dAtA []byte) (int, error) { - i := len(dAtA) - _ = i - var l int - _ = l - if len(m.Changes) > 0 { - for iNdEx := len(m.Changes) - 1; iNdEx >= 0; iNdEx-- { - { - size, err := m.Changes[iNdEx].MarshalToSizedBuffer(dAtA[:i]) - if err != nil { - return 0, err - } - i -= size - i = encodeVarintParams(dAtA, i, uint64(size)) - } - i-- - dAtA[i] = 0x1a - } - } - if len(m.Description) > 0 { - i -= len(m.Description) - copy(dAtA[i:], m.Description) - i = encodeVarintParams(dAtA, i, uint64(len(m.Description))) - i-- - dAtA[i] = 0x12 - } - if len(m.Title) > 0 { - i -= len(m.Title) - copy(dAtA[i:], m.Title) - i = encodeVarintParams(dAtA, i, uint64(len(m.Title))) - i-- - dAtA[i] = 0xa - } - return len(dAtA) - i, nil -} - -func (m *ParamChange) 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 *ParamChange) MarshalTo(dAtA []byte) (int, error) { - size := m.Size() - return m.MarshalToSizedBuffer(dAtA[:size]) -} - -func (m *ParamChange) MarshalToSizedBuffer(dAtA []byte) (int, error) { - i := len(dAtA) - _ = i - var l int - _ = l - if len(m.Value) > 0 { - i -= len(m.Value) - copy(dAtA[i:], m.Value) - i = encodeVarintParams(dAtA, i, uint64(len(m.Value))) - i-- - dAtA[i] = 0x1a - } - if len(m.Key) > 0 { - i -= len(m.Key) - copy(dAtA[i:], m.Key) - i = encodeVarintParams(dAtA, i, uint64(len(m.Key))) - i-- - dAtA[i] = 0x12 - } - if len(m.Subspace) > 0 { - i -= len(m.Subspace) - copy(dAtA[i:], m.Subspace) - i = encodeVarintParams(dAtA, i, uint64(len(m.Subspace))) - i-- - dAtA[i] = 0xa - } - return len(dAtA) - i, nil -} - -func encodeVarintParams(dAtA []byte, offset int, v uint64) int { - offset -= sovParams(v) - base := offset - for v >= 1<<7 { - dAtA[offset] = uint8(v&0x7f | 0x80) - v >>= 7 - offset++ - } - dAtA[offset] = uint8(v) - return base -} -func (m *ParameterChangeProposal) Size() (n int) { - if m == nil { - return 0 - } - var l int - _ = l - l = len(m.Title) - if l > 0 { - n += 1 + l + sovParams(uint64(l)) - } - l = len(m.Description) - if l > 0 { - n += 1 + l + sovParams(uint64(l)) - } - if len(m.Changes) > 0 { - for _, e := range m.Changes { - l = e.Size() - n += 1 + l + sovParams(uint64(l)) - } - } - return n -} - -func (m *ParamChange) Size() (n int) { - if m == nil { - return 0 - } - var l int - _ = l - l = len(m.Subspace) - if l > 0 { - n += 1 + l + sovParams(uint64(l)) - } - l = len(m.Key) - if l > 0 { - n += 1 + l + sovParams(uint64(l)) - } - l = len(m.Value) - if l > 0 { - n += 1 + l + sovParams(uint64(l)) - } - return n -} - -func sovParams(x uint64) (n int) { - return (math_bits.Len64(x|1) + 6) / 7 -} -func sozParams(x uint64) (n int) { - return sovParams(uint64((x << 1) ^ uint64((int64(x) >> 63)))) -} -func (m *ParameterChangeProposal) 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 ErrIntOverflowParams - } - 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: ParameterChangeProposal: wiretype end group for non-group") - } - if fieldNum <= 0 { - return fmt.Errorf("proto: ParameterChangeProposal: 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 ErrIntOverflowParams - } - 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 ErrInvalidLengthParams - } - postIndex := iNdEx + intStringLen - if postIndex < 0 { - return ErrInvalidLengthParams - } - 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 ErrIntOverflowParams - } - 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 ErrInvalidLengthParams - } - postIndex := iNdEx + intStringLen - if postIndex < 0 { - return ErrInvalidLengthParams - } - 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 Changes", wireType) - } - var msglen int - for shift := uint(0); ; shift += 7 { - if shift >= 64 { - return ErrIntOverflowParams - } - if iNdEx >= l { - return io.ErrUnexpectedEOF - } - b := dAtA[iNdEx] - iNdEx++ - msglen |= int(b&0x7F) << shift - if b < 0x80 { - break - } - } - if msglen < 0 { - return ErrInvalidLengthParams - } - postIndex := iNdEx + msglen - if postIndex < 0 { - return ErrInvalidLengthParams - } - if postIndex > l { - return io.ErrUnexpectedEOF - } - m.Changes = append(m.Changes, ParamChange{}) - if err := m.Changes[len(m.Changes)-1].Unmarshal(dAtA[iNdEx:postIndex]); err != nil { - return err - } - iNdEx = postIndex - default: - iNdEx = preIndex - skippy, err := skipParams(dAtA[iNdEx:]) - if err != nil { - return err - } - if (skippy < 0) || (iNdEx+skippy) < 0 { - return ErrInvalidLengthParams - } - if (iNdEx + skippy) > l { - return io.ErrUnexpectedEOF - } - iNdEx += skippy - } - } - - if iNdEx > l { - return io.ErrUnexpectedEOF - } - return nil -} -func (m *ParamChange) 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 ErrIntOverflowParams - } - 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: ParamChange: wiretype end group for non-group") - } - if fieldNum <= 0 { - return fmt.Errorf("proto: ParamChange: illegal tag %d (wire type %d)", fieldNum, wire) - } - switch fieldNum { - case 1: - if wireType != 2 { - return fmt.Errorf("proto: wrong wireType = %d for field Subspace", wireType) - } - var stringLen uint64 - for shift := uint(0); ; shift += 7 { - if shift >= 64 { - return ErrIntOverflowParams - } - 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 ErrInvalidLengthParams - } - postIndex := iNdEx + intStringLen - if postIndex < 0 { - return ErrInvalidLengthParams - } - if postIndex > l { - return io.ErrUnexpectedEOF - } - m.Subspace = string(dAtA[iNdEx:postIndex]) - iNdEx = postIndex - case 2: - if wireType != 2 { - return fmt.Errorf("proto: wrong wireType = %d for field Key", wireType) - } - var stringLen uint64 - for shift := uint(0); ; shift += 7 { - if shift >= 64 { - return ErrIntOverflowParams - } - 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 ErrInvalidLengthParams - } - postIndex := iNdEx + intStringLen - if postIndex < 0 { - return ErrInvalidLengthParams - } - if postIndex > l { - return io.ErrUnexpectedEOF - } - m.Key = string(dAtA[iNdEx:postIndex]) - iNdEx = postIndex - case 3: - if wireType != 2 { - return fmt.Errorf("proto: wrong wireType = %d for field Value", wireType) - } - var stringLen uint64 - for shift := uint(0); ; shift += 7 { - if shift >= 64 { - return ErrIntOverflowParams - } - 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 ErrInvalidLengthParams - } - postIndex := iNdEx + intStringLen - if postIndex < 0 { - return ErrInvalidLengthParams - } - if postIndex > l { - return io.ErrUnexpectedEOF - } - m.Value = string(dAtA[iNdEx:postIndex]) - iNdEx = postIndex - default: - iNdEx = preIndex - skippy, err := skipParams(dAtA[iNdEx:]) - if err != nil { - return err - } - if (skippy < 0) || (iNdEx+skippy) < 0 { - return ErrInvalidLengthParams - } - if (iNdEx + skippy) > l { - return io.ErrUnexpectedEOF - } - iNdEx += skippy - } - } - - if iNdEx > l { - return io.ErrUnexpectedEOF - } - return nil -} -func skipParams(dAtA []byte) (n int, err error) { - l := len(dAtA) - iNdEx := 0 - depth := 0 - for iNdEx < l { - var wire uint64 - for shift := uint(0); ; shift += 7 { - if shift >= 64 { - return 0, ErrIntOverflowParams - } - if iNdEx >= l { - return 0, io.ErrUnexpectedEOF - } - b := dAtA[iNdEx] - iNdEx++ - wire |= (uint64(b) & 0x7F) << shift - if b < 0x80 { - break - } - } - wireType := int(wire & 0x7) - switch wireType { - case 0: - for shift := uint(0); ; shift += 7 { - if shift >= 64 { - return 0, ErrIntOverflowParams - } - if iNdEx >= l { - return 0, io.ErrUnexpectedEOF - } - iNdEx++ - if dAtA[iNdEx-1] < 0x80 { - break - } - } - case 1: - iNdEx += 8 - case 2: - var length int - for shift := uint(0); ; shift += 7 { - if shift >= 64 { - return 0, ErrIntOverflowParams - } - if iNdEx >= l { - return 0, io.ErrUnexpectedEOF - } - b := dAtA[iNdEx] - iNdEx++ - length |= (int(b) & 0x7F) << shift - if b < 0x80 { - break - } - } - if length < 0 { - return 0, ErrInvalidLengthParams - } - iNdEx += length - case 3: - depth++ - case 4: - if depth == 0 { - return 0, ErrUnexpectedEndOfGroupParams - } - depth-- - case 5: - iNdEx += 4 - default: - return 0, fmt.Errorf("proto: illegal wireType %d", wireType) - } - if iNdEx < 0 { - return 0, ErrInvalidLengthParams - } - if depth == 0 { - return iNdEx, nil - } - } - return 0, io.ErrUnexpectedEOF -} - -var ( - ErrInvalidLengthParams = fmt.Errorf("proto: negative length found during unmarshaling") - ErrIntOverflowParams = fmt.Errorf("proto: integer overflow") - ErrUnexpectedEndOfGroupParams = fmt.Errorf("proto: unexpected end of group") -) diff --git a/x/params/types/proposal/proposal.go b/x/params/types/proposal/proposal.go deleted file mode 100644 index de4ece18ef70..000000000000 --- a/x/params/types/proposal/proposal.go +++ /dev/null @@ -1,69 +0,0 @@ -package proposal - -import ( - govtypes "github.com/cosmos/cosmos-sdk/x/gov/types/v1beta1" -) - -const ( - // ProposalTypeChange defines the type for a ParameterChangeProposal - ProposalTypeChange = "ParameterChange" -) - -// Assert ParameterChangeProposal implements govtypes.Content at compile-time -var _ govtypes.Content = &ParameterChangeProposal{} - -func init() { - govtypes.RegisterProposalType(ProposalTypeChange) -} - -func NewParameterChangeProposal(title, description string, changes []ParamChange) *ParameterChangeProposal { - return &ParameterChangeProposal{title, description, changes} -} - -// GetTitle returns the title of a parameter change proposal. -func (pcp *ParameterChangeProposal) GetTitle() string { return pcp.Title } - -// GetDescription returns the description of a parameter change proposal. -func (pcp *ParameterChangeProposal) GetDescription() string { return pcp.Description } - -// ProposalRoute returns the routing key of a parameter change proposal. -func (pcp *ParameterChangeProposal) ProposalRoute() string { return RouterKey } - -// ProposalType returns the type of a parameter change proposal. -func (pcp *ParameterChangeProposal) ProposalType() string { return ProposalTypeChange } - -// ValidateBasic validates the parameter change proposal -func (pcp *ParameterChangeProposal) ValidateBasic() error { - err := govtypes.ValidateAbstract(pcp) - if err != nil { - return err - } - - return ValidateChanges(pcp.Changes) -} - -func NewParamChange(subspace, key, value string) ParamChange { - return ParamChange{subspace, key, value} -} - -// ValidateChanges performs basic validation checks over a set of ParamChange. It -// returns an error if any ParamChange is invalid. -func ValidateChanges(changes []ParamChange) error { - if len(changes) == 0 { - return ErrEmptyChanges - } - - for _, pc := range changes { - if len(pc.Subspace) == 0 { - return ErrEmptySubspace - } - if len(pc.Key) == 0 { - return ErrEmptyKey - } - if len(pc.Value) == 0 { - return ErrEmptyValue - } - } - - return nil -} diff --git a/x/params/types/proposal/proposal_test.go b/x/params/types/proposal/proposal_test.go deleted file mode 100644 index a18f9c407609..000000000000 --- a/x/params/types/proposal/proposal_test.go +++ /dev/null @@ -1,27 +0,0 @@ -package proposal - -import ( - "testing" - - "github.com/stretchr/testify/require" -) - -func TestParameterChangeProposal(t *testing.T) { - pc1 := NewParamChange("sub", "foo", "baz") - pc2 := NewParamChange("sub", "bar", "cat") - pcp := NewParameterChangeProposal("test title", "test description", []ParamChange{pc1, pc2}) - - require.Equal(t, "test title", pcp.GetTitle()) - require.Equal(t, "test description", pcp.GetDescription()) - require.Equal(t, RouterKey, pcp.ProposalRoute()) - require.Equal(t, ProposalTypeChange, pcp.ProposalType()) - require.Nil(t, pcp.ValidateBasic()) - - pc3 := NewParamChange("", "bar", "cat") - pcp = NewParameterChangeProposal("test title", "test description", []ParamChange{pc3}) - require.Error(t, pcp.ValidateBasic()) - - pc4 := NewParamChange("sub", "", "cat") - pcp = NewParameterChangeProposal("test title", "test description", []ParamChange{pc4}) - require.Error(t, pcp.ValidateBasic()) -} diff --git a/x/params/types/proposal/query.pb.go b/x/params/types/proposal/query.pb.go deleted file mode 100644 index 1d1f8712868a..000000000000 --- a/x/params/types/proposal/query.pb.go +++ /dev/null @@ -1,1225 +0,0 @@ -// Code generated by protoc-gen-gogo. DO NOT EDIT. -// source: cosmos/params/v1beta1/query.proto - -package proposal - -import ( - context "context" - fmt "fmt" - _ "github.com/cosmos/cosmos-proto" - _ "github.com/cosmos/cosmos-sdk/types/tx/amino" - _ "github.com/cosmos/gogoproto/gogoproto" - grpc1 "github.com/cosmos/gogoproto/grpc" - proto "github.com/cosmos/gogoproto/proto" - _ "google.golang.org/genproto/googleapis/api/annotations" - grpc "google.golang.org/grpc" - codes "google.golang.org/grpc/codes" - status "google.golang.org/grpc/status" - io "io" - math "math" - math_bits "math/bits" -) - -// Reference imports to suppress errors if they are not otherwise used. -var _ = proto.Marshal -var _ = fmt.Errorf -var _ = math.Inf - -// This is a compile-time assertion to ensure that this generated file -// is compatible with the proto package it is being compiled against. -// A compilation error at this line likely means your copy of the -// proto package needs to be updated. -const _ = proto.GoGoProtoPackageIsVersion3 // please upgrade the proto package - -// QueryParamsRequest is request type for the Query/Params RPC method. -type QueryParamsRequest struct { - // subspace defines the module to query the parameter for. - Subspace string `protobuf:"bytes,1,opt,name=subspace,proto3" json:"subspace,omitempty"` - // key defines the key of the parameter in the subspace. - Key string `protobuf:"bytes,2,opt,name=key,proto3" json:"key,omitempty"` -} - -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_2b32979c1792ccc4, []int{0} -} -func (m *QueryParamsRequest) XXX_Unmarshal(b []byte) error { - return m.Unmarshal(b) -} -func (m *QueryParamsRequest) XXX_Marshal(b []byte, deterministic bool) ([]byte, error) { - if deterministic { - return xxx_messageInfo_QueryParamsRequest.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 *QueryParamsRequest) XXX_Merge(src proto.Message) { - xxx_messageInfo_QueryParamsRequest.Merge(m, src) -} -func (m *QueryParamsRequest) XXX_Size() int { - return m.Size() -} -func (m *QueryParamsRequest) XXX_DiscardUnknown() { - xxx_messageInfo_QueryParamsRequest.DiscardUnknown(m) -} - -var xxx_messageInfo_QueryParamsRequest proto.InternalMessageInfo - -func (m *QueryParamsRequest) GetSubspace() string { - if m != nil { - return m.Subspace - } - return "" -} - -func (m *QueryParamsRequest) GetKey() string { - if m != nil { - return m.Key - } - return "" -} - -// QueryParamsResponse is response type for the Query/Params RPC method. -type QueryParamsResponse struct { - // param defines the queried parameter. - Param ParamChange `protobuf:"bytes,1,opt,name=param,proto3" json:"param"` -} - -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_2b32979c1792ccc4, []int{1} -} -func (m *QueryParamsResponse) XXX_Unmarshal(b []byte) error { - return m.Unmarshal(b) -} -func (m *QueryParamsResponse) XXX_Marshal(b []byte, deterministic bool) ([]byte, error) { - if deterministic { - return xxx_messageInfo_QueryParamsResponse.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 *QueryParamsResponse) XXX_Merge(src proto.Message) { - xxx_messageInfo_QueryParamsResponse.Merge(m, src) -} -func (m *QueryParamsResponse) XXX_Size() int { - return m.Size() -} -func (m *QueryParamsResponse) XXX_DiscardUnknown() { - xxx_messageInfo_QueryParamsResponse.DiscardUnknown(m) -} - -var xxx_messageInfo_QueryParamsResponse proto.InternalMessageInfo - -func (m *QueryParamsResponse) GetParam() ParamChange { - if m != nil { - return m.Param - } - return ParamChange{} -} - -// QuerySubspacesRequest defines a request type for querying for all registered -// subspaces and all keys for a subspace. -type QuerySubspacesRequest struct { -} - -func (m *QuerySubspacesRequest) Reset() { *m = QuerySubspacesRequest{} } -func (m *QuerySubspacesRequest) String() string { return proto.CompactTextString(m) } -func (*QuerySubspacesRequest) ProtoMessage() {} -func (*QuerySubspacesRequest) Descriptor() ([]byte, []int) { - return fileDescriptor_2b32979c1792ccc4, []int{2} -} -func (m *QuerySubspacesRequest) XXX_Unmarshal(b []byte) error { - return m.Unmarshal(b) -} -func (m *QuerySubspacesRequest) XXX_Marshal(b []byte, deterministic bool) ([]byte, error) { - if deterministic { - return xxx_messageInfo_QuerySubspacesRequest.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 *QuerySubspacesRequest) XXX_Merge(src proto.Message) { - xxx_messageInfo_QuerySubspacesRequest.Merge(m, src) -} -func (m *QuerySubspacesRequest) XXX_Size() int { - return m.Size() -} -func (m *QuerySubspacesRequest) XXX_DiscardUnknown() { - xxx_messageInfo_QuerySubspacesRequest.DiscardUnknown(m) -} - -var xxx_messageInfo_QuerySubspacesRequest proto.InternalMessageInfo - -// QuerySubspacesResponse defines the response types for querying for all -// registered subspaces and all keys for a subspace. -type QuerySubspacesResponse struct { - Subspaces []*Subspace `protobuf:"bytes,1,rep,name=subspaces,proto3" json:"subspaces,omitempty"` -} - -func (m *QuerySubspacesResponse) Reset() { *m = QuerySubspacesResponse{} } -func (m *QuerySubspacesResponse) String() string { return proto.CompactTextString(m) } -func (*QuerySubspacesResponse) ProtoMessage() {} -func (*QuerySubspacesResponse) Descriptor() ([]byte, []int) { - return fileDescriptor_2b32979c1792ccc4, []int{3} -} -func (m *QuerySubspacesResponse) XXX_Unmarshal(b []byte) error { - return m.Unmarshal(b) -} -func (m *QuerySubspacesResponse) XXX_Marshal(b []byte, deterministic bool) ([]byte, error) { - if deterministic { - return xxx_messageInfo_QuerySubspacesResponse.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 *QuerySubspacesResponse) XXX_Merge(src proto.Message) { - xxx_messageInfo_QuerySubspacesResponse.Merge(m, src) -} -func (m *QuerySubspacesResponse) XXX_Size() int { - return m.Size() -} -func (m *QuerySubspacesResponse) XXX_DiscardUnknown() { - xxx_messageInfo_QuerySubspacesResponse.DiscardUnknown(m) -} - -var xxx_messageInfo_QuerySubspacesResponse proto.InternalMessageInfo - -func (m *QuerySubspacesResponse) GetSubspaces() []*Subspace { - if m != nil { - return m.Subspaces - } - return nil -} - -// Subspace defines a parameter subspace name and all the keys that exist for -// the subspace. -type Subspace struct { - Subspace string `protobuf:"bytes,1,opt,name=subspace,proto3" json:"subspace,omitempty"` - Keys []string `protobuf:"bytes,2,rep,name=keys,proto3" json:"keys,omitempty"` -} - -func (m *Subspace) Reset() { *m = Subspace{} } -func (m *Subspace) String() string { return proto.CompactTextString(m) } -func (*Subspace) ProtoMessage() {} -func (*Subspace) Descriptor() ([]byte, []int) { - return fileDescriptor_2b32979c1792ccc4, []int{4} -} -func (m *Subspace) XXX_Unmarshal(b []byte) error { - return m.Unmarshal(b) -} -func (m *Subspace) XXX_Marshal(b []byte, deterministic bool) ([]byte, error) { - if deterministic { - return xxx_messageInfo_Subspace.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 *Subspace) XXX_Merge(src proto.Message) { - xxx_messageInfo_Subspace.Merge(m, src) -} -func (m *Subspace) XXX_Size() int { - return m.Size() -} -func (m *Subspace) XXX_DiscardUnknown() { - xxx_messageInfo_Subspace.DiscardUnknown(m) -} - -var xxx_messageInfo_Subspace proto.InternalMessageInfo - -func (m *Subspace) GetSubspace() string { - if m != nil { - return m.Subspace - } - return "" -} - -func (m *Subspace) GetKeys() []string { - if m != nil { - return m.Keys - } - return nil -} - -func init() { - proto.RegisterType((*QueryParamsRequest)(nil), "cosmos.params.v1beta1.QueryParamsRequest") - proto.RegisterType((*QueryParamsResponse)(nil), "cosmos.params.v1beta1.QueryParamsResponse") - proto.RegisterType((*QuerySubspacesRequest)(nil), "cosmos.params.v1beta1.QuerySubspacesRequest") - proto.RegisterType((*QuerySubspacesResponse)(nil), "cosmos.params.v1beta1.QuerySubspacesResponse") - proto.RegisterType((*Subspace)(nil), "cosmos.params.v1beta1.Subspace") -} - -func init() { proto.RegisterFile("cosmos/params/v1beta1/query.proto", fileDescriptor_2b32979c1792ccc4) } - -var fileDescriptor_2b32979c1792ccc4 = []byte{ - // 469 bytes of a gzipped FileDescriptorProto - 0x1f, 0x8b, 0x08, 0x00, 0x00, 0x00, 0x00, 0x00, 0x02, 0xff, 0x8c, 0x93, 0xbf, 0x6f, 0xd3, 0x40, - 0x1c, 0xc5, 0x7d, 0x0e, 0xad, 0xea, 0xeb, 0x00, 0x5c, 0x29, 0x32, 0x16, 0x38, 0xe6, 0x24, 0xa4, - 0x50, 0x35, 0x3e, 0x1a, 0x2a, 0x06, 0x10, 0x4b, 0xba, 0xf3, 0xc3, 0x6c, 0x5d, 0xd0, 0x39, 0x9c, - 0x5c, 0x2b, 0xb1, 0xef, 0xea, 0xb3, 0x11, 0x5e, 0x19, 0x98, 0x91, 0xf8, 0x1b, 0x90, 0x18, 0x19, - 0x18, 0xf8, 0x13, 0x2a, 0xa6, 0x0a, 0x16, 0x26, 0x84, 0x12, 0x24, 0xfe, 0x0d, 0xe4, 0x3b, 0x3b, - 0x15, 0xad, 0x13, 0x65, 0x89, 0xee, 0x2e, 0xef, 0xfb, 0xde, 0xc7, 0xef, 0x6c, 0x78, 0x7b, 0xc4, - 0x65, 0xc2, 0x25, 0x11, 0x34, 0xa3, 0x89, 0x24, 0xaf, 0xf7, 0x42, 0x96, 0xd3, 0x3d, 0x72, 0x5c, - 0xb0, 0xac, 0xf4, 0x45, 0xc6, 0x73, 0x8e, 0xb6, 0xb5, 0xc4, 0xd7, 0x12, 0xbf, 0x96, 0x38, 0xd7, - 0x22, 0x1e, 0x71, 0xa5, 0x20, 0xd5, 0x4a, 0x8b, 0x9d, 0x9b, 0x11, 0xe7, 0xd1, 0x84, 0x11, 0x2a, - 0x62, 0x42, 0xd3, 0x94, 0xe7, 0x34, 0x8f, 0x79, 0x2a, 0xeb, 0x7f, 0x71, 0x7b, 0x5a, 0xed, 0xac, - 0x35, 0x57, 0x69, 0x12, 0xa7, 0x9c, 0xa8, 0xdf, 0xfa, 0xe8, 0x86, 0x1e, 0x7b, 0xa9, 0xd3, 0x1a, - 0x9c, 0x6a, 0x83, 0x87, 0x10, 0x3d, 0xaf, 0x58, 0x9f, 0x29, 0x8b, 0x80, 0x1d, 0x17, 0x4c, 0xe6, - 0xc8, 0x81, 0x1b, 0xb2, 0x08, 0xa5, 0xa0, 0x23, 0x66, 0x03, 0x0f, 0xf4, 0xac, 0x60, 0xbe, 0x47, - 0x57, 0x60, 0x67, 0xcc, 0x4a, 0xdb, 0x54, 0xc7, 0xd5, 0x12, 0x1f, 0xc2, 0xad, 0xff, 0x3c, 0xa4, - 0xe0, 0xa9, 0x64, 0xe8, 0x00, 0xae, 0x29, 0x30, 0xe5, 0xb0, 0x39, 0xc0, 0x7e, 0x6b, 0x0f, 0xbe, - 0x9a, 0x3a, 0x38, 0xa2, 0x69, 0xc4, 0x86, 0xd6, 0xc9, 0xaf, 0xae, 0xf1, 0xe9, 0xef, 0xe7, 0x1d, - 0x10, 0xe8, 0x59, 0xbc, 0x0b, 0xb7, 0x95, 0xf7, 0x8b, 0x3a, 0xbe, 0x41, 0x7c, 0xb8, 0xf5, 0xfd, - 0x4b, 0xff, 0xb2, 0x76, 0xec, 0xcb, 0x57, 0x63, 0xef, 0x9e, 0xbf, 0xff, 0x00, 0x4f, 0xe0, 0xf5, - 0xf3, 0xea, 0x1a, 0xe6, 0x31, 0xb4, 0x9a, 0x27, 0x90, 0x36, 0xf0, 0x3a, 0xbd, 0xcd, 0x41, 0x77, - 0x01, 0x50, 0x33, 0x1c, 0x9c, 0x4d, 0xb4, 0xa7, 0x3d, 0x85, 0x1b, 0x8d, 0x76, 0x69, 0x63, 0x08, - 0x5e, 0x1a, 0xb3, 0x52, 0xda, 0xa6, 0xd7, 0xe9, 0x59, 0x81, 0x5a, 0xb7, 0x1a, 0x0e, 0xbe, 0x9a, - 0x70, 0x4d, 0xf1, 0xa3, 0x77, 0x00, 0xae, 0xeb, 0x3a, 0xd1, 0xdd, 0x05, 0x98, 0x17, 0xaf, 0xcd, - 0xd9, 0x59, 0x45, 0xaa, 0x0b, 0xc1, 0x77, 0xde, 0xfe, 0xf8, 0xf3, 0xc1, 0xec, 0xa2, 0x5b, 0x64, - 0xd9, 0x3b, 0x85, 0x3e, 0x02, 0x68, 0xcd, 0xdb, 0x44, 0xbb, 0xcb, 0x02, 0xce, 0x5f, 0x91, 0xd3, - 0x5f, 0x51, 0x5d, 0x13, 0x3d, 0xfa, 0x76, 0xb1, 0x12, 0x05, 0x89, 0x91, 0xb7, 0x00, 0x72, 0x7e, - 0x41, 0xc3, 0x27, 0x27, 0x53, 0x17, 0x9c, 0x4e, 0x5d, 0xf0, 0x7b, 0xea, 0x82, 0xf7, 0x33, 0xd7, - 0x38, 0x9d, 0xb9, 0xc6, 0xcf, 0x99, 0x6b, 0x1c, 0xee, 0x47, 0x71, 0x7e, 0x54, 0x84, 0xfe, 0x88, - 0x27, 0x8d, 0xcb, 0x59, 0x08, 0x79, 0xd3, 0x58, 0xe6, 0xa5, 0x60, 0x92, 0x88, 0x8c, 0x0b, 0x2e, - 0xe9, 0x24, 0x5c, 0x57, 0x9f, 0xc7, 0xfd, 0x7f, 0x01, 0x00, 0x00, 0xff, 0xff, 0x50, 0xe1, 0x1e, - 0x04, 0xe0, 0x03, 0x00, 0x00, -} - -// Reference imports to suppress errors if they are not otherwise used. -var _ context.Context -var _ grpc.ClientConn - -// This is a compile-time assertion to ensure that this generated file -// is compatible with the grpc package it is being compiled against. -const _ = grpc.SupportPackageIsVersion4 - -// QueryClient is the client API for Query service. -// -// For semantics around ctx use and closing/ending streaming RPCs, please refer to https://godoc.org/google.golang.org/grpc#ClientConn.NewStream. -type QueryClient interface { - // Params queries a specific parameter of a module, given its subspace and - // key. - Params(ctx context.Context, in *QueryParamsRequest, opts ...grpc.CallOption) (*QueryParamsResponse, error) - // Subspaces queries for all registered subspaces and all keys for a subspace. - Subspaces(ctx context.Context, in *QuerySubspacesRequest, opts ...grpc.CallOption) (*QuerySubspacesResponse, error) -} - -type queryClient struct { - cc grpc1.ClientConn -} - -func NewQueryClient(cc grpc1.ClientConn) QueryClient { - return &queryClient{cc} -} - -func (c *queryClient) Params(ctx context.Context, in *QueryParamsRequest, opts ...grpc.CallOption) (*QueryParamsResponse, error) { - out := new(QueryParamsResponse) - err := c.cc.Invoke(ctx, "/cosmos.params.v1beta1.Query/Params", in, out, opts...) - if err != nil { - return nil, err - } - return out, nil -} - -func (c *queryClient) Subspaces(ctx context.Context, in *QuerySubspacesRequest, opts ...grpc.CallOption) (*QuerySubspacesResponse, error) { - out := new(QuerySubspacesResponse) - err := c.cc.Invoke(ctx, "/cosmos.params.v1beta1.Query/Subspaces", in, out, opts...) - if err != nil { - return nil, err - } - return out, nil -} - -// QueryServer is the server API for Query service. -type QueryServer interface { - // Params queries a specific parameter of a module, given its subspace and - // key. - Params(context.Context, *QueryParamsRequest) (*QueryParamsResponse, error) - // Subspaces queries for all registered subspaces and all keys for a subspace. - Subspaces(context.Context, *QuerySubspacesRequest) (*QuerySubspacesResponse, error) -} - -// UnimplementedQueryServer can be embedded to have forward compatible implementations. -type UnimplementedQueryServer struct { -} - -func (*UnimplementedQueryServer) Params(ctx context.Context, req *QueryParamsRequest) (*QueryParamsResponse, error) { - return nil, status.Errorf(codes.Unimplemented, "method Params not implemented") -} -func (*UnimplementedQueryServer) Subspaces(ctx context.Context, req *QuerySubspacesRequest) (*QuerySubspacesResponse, error) { - return nil, status.Errorf(codes.Unimplemented, "method Subspaces not implemented") -} - -func RegisterQueryServer(s grpc1.Server, srv QueryServer) { - s.RegisterService(&_Query_serviceDesc, srv) -} - -func _Query_Params_Handler(srv interface{}, ctx context.Context, dec func(interface{}) error, interceptor grpc.UnaryServerInterceptor) (interface{}, error) { - in := new(QueryParamsRequest) - if err := dec(in); err != nil { - return nil, err - } - if interceptor == nil { - return srv.(QueryServer).Params(ctx, in) - } - info := &grpc.UnaryServerInfo{ - Server: srv, - FullMethod: "/cosmos.params.v1beta1.Query/Params", - } - handler := func(ctx context.Context, req interface{}) (interface{}, error) { - return srv.(QueryServer).Params(ctx, req.(*QueryParamsRequest)) - } - return interceptor(ctx, in, info, handler) -} - -func _Query_Subspaces_Handler(srv interface{}, ctx context.Context, dec func(interface{}) error, interceptor grpc.UnaryServerInterceptor) (interface{}, error) { - in := new(QuerySubspacesRequest) - if err := dec(in); err != nil { - return nil, err - } - if interceptor == nil { - return srv.(QueryServer).Subspaces(ctx, in) - } - info := &grpc.UnaryServerInfo{ - Server: srv, - FullMethod: "/cosmos.params.v1beta1.Query/Subspaces", - } - handler := func(ctx context.Context, req interface{}) (interface{}, error) { - return srv.(QueryServer).Subspaces(ctx, req.(*QuerySubspacesRequest)) - } - return interceptor(ctx, in, info, handler) -} - -var Query_serviceDesc = _Query_serviceDesc -var _Query_serviceDesc = grpc.ServiceDesc{ - ServiceName: "cosmos.params.v1beta1.Query", - HandlerType: (*QueryServer)(nil), - Methods: []grpc.MethodDesc{ - { - MethodName: "Params", - Handler: _Query_Params_Handler, - }, - { - MethodName: "Subspaces", - Handler: _Query_Subspaces_Handler, - }, - }, - Streams: []grpc.StreamDesc{}, - Metadata: "cosmos/params/v1beta1/query.proto", -} - -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 - if len(m.Key) > 0 { - i -= len(m.Key) - copy(dAtA[i:], m.Key) - i = encodeVarintQuery(dAtA, i, uint64(len(m.Key))) - i-- - dAtA[i] = 0x12 - } - if len(m.Subspace) > 0 { - i -= len(m.Subspace) - copy(dAtA[i:], m.Subspace) - i = encodeVarintQuery(dAtA, i, uint64(len(m.Subspace))) - i-- - dAtA[i] = 0xa - } - 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.Param.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 *QuerySubspacesRequest) 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 *QuerySubspacesRequest) MarshalTo(dAtA []byte) (int, error) { - size := m.Size() - return m.MarshalToSizedBuffer(dAtA[:size]) -} - -func (m *QuerySubspacesRequest) MarshalToSizedBuffer(dAtA []byte) (int, error) { - i := len(dAtA) - _ = i - var l int - _ = l - return len(dAtA) - i, nil -} - -func (m *QuerySubspacesResponse) 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 *QuerySubspacesResponse) MarshalTo(dAtA []byte) (int, error) { - size := m.Size() - return m.MarshalToSizedBuffer(dAtA[:size]) -} - -func (m *QuerySubspacesResponse) MarshalToSizedBuffer(dAtA []byte) (int, error) { - i := len(dAtA) - _ = i - var l int - _ = l - if len(m.Subspaces) > 0 { - for iNdEx := len(m.Subspaces) - 1; iNdEx >= 0; iNdEx-- { - { - size, err := m.Subspaces[iNdEx].MarshalToSizedBuffer(dAtA[:i]) - if err != nil { - return 0, err - } - i -= size - i = encodeVarintQuery(dAtA, i, uint64(size)) - } - i-- - dAtA[i] = 0xa - } - } - return len(dAtA) - i, nil -} - -func (m *Subspace) 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 *Subspace) MarshalTo(dAtA []byte) (int, error) { - size := m.Size() - return m.MarshalToSizedBuffer(dAtA[:size]) -} - -func (m *Subspace) MarshalToSizedBuffer(dAtA []byte) (int, error) { - i := len(dAtA) - _ = i - var l int - _ = l - if len(m.Keys) > 0 { - for iNdEx := len(m.Keys) - 1; iNdEx >= 0; iNdEx-- { - i -= len(m.Keys[iNdEx]) - copy(dAtA[i:], m.Keys[iNdEx]) - i = encodeVarintQuery(dAtA, i, uint64(len(m.Keys[iNdEx]))) - i-- - dAtA[i] = 0x12 - } - } - if len(m.Subspace) > 0 { - i -= len(m.Subspace) - copy(dAtA[i:], m.Subspace) - i = encodeVarintQuery(dAtA, i, uint64(len(m.Subspace))) - 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 *QueryParamsRequest) Size() (n int) { - if m == nil { - return 0 - } - var l int - _ = l - l = len(m.Subspace) - if l > 0 { - n += 1 + l + sovQuery(uint64(l)) - } - l = len(m.Key) - if l > 0 { - n += 1 + l + sovQuery(uint64(l)) - } - return n -} - -func (m *QueryParamsResponse) Size() (n int) { - if m == nil { - return 0 - } - var l int - _ = l - l = m.Param.Size() - n += 1 + l + sovQuery(uint64(l)) - return n -} - -func (m *QuerySubspacesRequest) Size() (n int) { - if m == nil { - return 0 - } - var l int - _ = l - return n -} - -func (m *QuerySubspacesResponse) Size() (n int) { - if m == nil { - return 0 - } - var l int - _ = l - if len(m.Subspaces) > 0 { - for _, e := range m.Subspaces { - l = e.Size() - n += 1 + l + sovQuery(uint64(l)) - } - } - return n -} - -func (m *Subspace) Size() (n int) { - if m == nil { - return 0 - } - var l int - _ = l - l = len(m.Subspace) - if l > 0 { - n += 1 + l + sovQuery(uint64(l)) - } - if len(m.Keys) > 0 { - for _, s := range m.Keys { - l = len(s) - n += 1 + l + sovQuery(uint64(l)) - } - } - return n -} - -func sovQuery(x uint64) (n int) { - return (math_bits.Len64(x|1) + 6) / 7 -} -func sozQuery(x uint64) (n int) { - return sovQuery(uint64((x << 1) ^ uint64((int64(x) >> 63)))) -} -func (m *QueryParamsRequest) 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: 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 { - case 1: - if wireType != 2 { - return fmt.Errorf("proto: wrong wireType = %d for field Subspace", 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.Subspace = string(dAtA[iNdEx:postIndex]) - iNdEx = postIndex - case 2: - if wireType != 2 { - return fmt.Errorf("proto: wrong wireType = %d for field Key", 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.Key = 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 *QueryParamsResponse) 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: QueryParamsResponse: wiretype end group for non-group") - } - if fieldNum <= 0 { - 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 Param", 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.Param.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 *QuerySubspacesRequest) 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: QuerySubspacesRequest: wiretype end group for non-group") - } - if fieldNum <= 0 { - return fmt.Errorf("proto: QuerySubspacesRequest: 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 *QuerySubspacesResponse) 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: QuerySubspacesResponse: wiretype end group for non-group") - } - if fieldNum <= 0 { - return fmt.Errorf("proto: QuerySubspacesResponse: illegal tag %d (wire type %d)", fieldNum, wire) - } - switch fieldNum { - case 1: - if wireType != 2 { - return fmt.Errorf("proto: wrong wireType = %d for field Subspaces", 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.Subspaces = append(m.Subspaces, &Subspace{}) - if err := m.Subspaces[len(m.Subspaces)-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 *Subspace) 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: Subspace: wiretype end group for non-group") - } - if fieldNum <= 0 { - return fmt.Errorf("proto: Subspace: illegal tag %d (wire type %d)", fieldNum, wire) - } - switch fieldNum { - case 1: - if wireType != 2 { - return fmt.Errorf("proto: wrong wireType = %d for field Subspace", 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.Subspace = string(dAtA[iNdEx:postIndex]) - iNdEx = postIndex - case 2: - if wireType != 2 { - return fmt.Errorf("proto: wrong wireType = %d for field Keys", 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.Keys = append(m.Keys, string(dAtA[iNdEx:postIndex])) - iNdEx = postIndex - default: - iNdEx = preIndex - skippy, err := skipQuery(dAtA[iNdEx:]) - if err != nil { - return err - } - if (skippy < 0) || (iNdEx+skippy) < 0 { - return ErrInvalidLengthQuery - } - if (iNdEx + skippy) > l { - return io.ErrUnexpectedEOF - } - iNdEx += skippy - } - } - - if iNdEx > l { - return io.ErrUnexpectedEOF - } - return nil -} -func skipQuery(dAtA []byte) (n int, err error) { - l := len(dAtA) - iNdEx := 0 - depth := 0 - for iNdEx < l { - var wire uint64 - for shift := uint(0); ; shift += 7 { - if shift >= 64 { - return 0, ErrIntOverflowQuery - } - if iNdEx >= l { - return 0, io.ErrUnexpectedEOF - } - b := dAtA[iNdEx] - iNdEx++ - wire |= (uint64(b) & 0x7F) << shift - if b < 0x80 { - break - } - } - wireType := int(wire & 0x7) - switch wireType { - case 0: - for shift := uint(0); ; shift += 7 { - if shift >= 64 { - return 0, ErrIntOverflowQuery - } - if iNdEx >= l { - return 0, io.ErrUnexpectedEOF - } - iNdEx++ - if dAtA[iNdEx-1] < 0x80 { - break - } - } - case 1: - iNdEx += 8 - case 2: - var length int - for shift := uint(0); ; shift += 7 { - if shift >= 64 { - return 0, ErrIntOverflowQuery - } - if iNdEx >= l { - return 0, io.ErrUnexpectedEOF - } - b := dAtA[iNdEx] - iNdEx++ - length |= (int(b) & 0x7F) << shift - if b < 0x80 { - break - } - } - if length < 0 { - return 0, ErrInvalidLengthQuery - } - iNdEx += length - case 3: - depth++ - case 4: - if depth == 0 { - return 0, ErrUnexpectedEndOfGroupQuery - } - depth-- - case 5: - iNdEx += 4 - default: - return 0, fmt.Errorf("proto: illegal wireType %d", wireType) - } - if iNdEx < 0 { - return 0, ErrInvalidLengthQuery - } - if depth == 0 { - return iNdEx, nil - } - } - return 0, io.ErrUnexpectedEOF -} - -var ( - ErrInvalidLengthQuery = fmt.Errorf("proto: negative length found during unmarshaling") - ErrIntOverflowQuery = fmt.Errorf("proto: integer overflow") - ErrUnexpectedEndOfGroupQuery = fmt.Errorf("proto: unexpected end of group") -) diff --git a/x/params/types/proposal/query.pb.gw.go b/x/params/types/proposal/query.pb.gw.go deleted file mode 100644 index 6454d314e358..000000000000 --- a/x/params/types/proposal/query.pb.gw.go +++ /dev/null @@ -1,236 +0,0 @@ -// Code generated by protoc-gen-grpc-gateway. DO NOT EDIT. -// source: cosmos/params/v1beta1/query.proto - -/* -Package proposal is a reverse proxy. - -It translates gRPC into RESTful JSON APIs. -*/ -package proposal - -import ( - "context" - "io" - "net/http" - - "github.com/golang/protobuf/descriptor" - "github.com/golang/protobuf/proto" - "github.com/grpc-ecosystem/grpc-gateway/runtime" - "github.com/grpc-ecosystem/grpc-gateway/utilities" - "google.golang.org/grpc" - "google.golang.org/grpc/codes" - "google.golang.org/grpc/grpclog" - "google.golang.org/grpc/metadata" - "google.golang.org/grpc/status" -) - -// Suppress "imported and not used" errors -var _ codes.Code -var _ io.Reader -var _ status.Status -var _ = runtime.String -var _ = utilities.NewDoubleArray -var _ = descriptor.ForMessage -var _ = metadata.Join - -var ( - filter_Query_Params_0 = &utilities.DoubleArray{Encoding: map[string]int{}, Base: []int(nil), Check: []int(nil)} -) - -func request_Query_Params_0(ctx context.Context, marshaler runtime.Marshaler, client QueryClient, req *http.Request, pathParams map[string]string) (proto.Message, runtime.ServerMetadata, error) { - var protoReq QueryParamsRequest - var metadata runtime.ServerMetadata - - if err := req.ParseForm(); err != nil { - return nil, metadata, status.Errorf(codes.InvalidArgument, "%v", err) - } - if err := runtime.PopulateQueryParameters(&protoReq, req.Form, filter_Query_Params_0); err != nil { - return nil, metadata, status.Errorf(codes.InvalidArgument, "%v", err) - } - - msg, err := client.Params(ctx, &protoReq, grpc.Header(&metadata.HeaderMD), grpc.Trailer(&metadata.TrailerMD)) - return msg, metadata, err - -} - -func local_request_Query_Params_0(ctx context.Context, marshaler runtime.Marshaler, server QueryServer, req *http.Request, pathParams map[string]string) (proto.Message, runtime.ServerMetadata, error) { - var protoReq QueryParamsRequest - var metadata runtime.ServerMetadata - - if err := req.ParseForm(); err != nil { - return nil, metadata, status.Errorf(codes.InvalidArgument, "%v", err) - } - if err := runtime.PopulateQueryParameters(&protoReq, req.Form, filter_Query_Params_0); err != nil { - return nil, metadata, status.Errorf(codes.InvalidArgument, "%v", err) - } - - msg, err := server.Params(ctx, &protoReq) - return msg, metadata, err - -} - -func request_Query_Subspaces_0(ctx context.Context, marshaler runtime.Marshaler, client QueryClient, req *http.Request, pathParams map[string]string) (proto.Message, runtime.ServerMetadata, error) { - var protoReq QuerySubspacesRequest - var metadata runtime.ServerMetadata - - msg, err := client.Subspaces(ctx, &protoReq, grpc.Header(&metadata.HeaderMD), grpc.Trailer(&metadata.TrailerMD)) - return msg, metadata, err - -} - -func local_request_Query_Subspaces_0(ctx context.Context, marshaler runtime.Marshaler, server QueryServer, req *http.Request, pathParams map[string]string) (proto.Message, runtime.ServerMetadata, error) { - var protoReq QuerySubspacesRequest - var metadata runtime.ServerMetadata - - msg, err := server.Subspaces(ctx, &protoReq) - return msg, metadata, err - -} - -// RegisterQueryHandlerServer registers the http handlers for service Query to "mux". -// UnaryRPC :call QueryServer directly. -// StreamingRPC :currently unsupported pending https://github.com/grpc/grpc-go/issues/906. -// Note that using this registration option will cause many gRPC library features to stop working. Consider using RegisterQueryHandlerFromEndpoint instead. -func RegisterQueryHandlerServer(ctx context.Context, mux *runtime.ServeMux, server QueryServer) error { - - mux.Handle("GET", pattern_Query_Params_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_Params_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_Params_0(ctx, mux, outboundMarshaler, w, req, resp, mux.GetForwardResponseOptions()...) - - }) - - mux.Handle("GET", pattern_Query_Subspaces_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_Subspaces_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_Subspaces_0(ctx, mux, outboundMarshaler, w, req, resp, mux.GetForwardResponseOptions()...) - - }) - - return nil -} - -// RegisterQueryHandlerFromEndpoint is same as RegisterQueryHandler but -// automatically dials to "endpoint" and closes the connection when "ctx" gets done. -func RegisterQueryHandlerFromEndpoint(ctx context.Context, mux *runtime.ServeMux, endpoint string, opts []grpc.DialOption) (err error) { - conn, err := grpc.Dial(endpoint, opts...) - if err != nil { - return err - } - defer func() { - if err != nil { - if cerr := conn.Close(); cerr != nil { - grpclog.Infof("Failed to close conn to %s: %v", endpoint, cerr) - } - return - } - go func() { - <-ctx.Done() - if cerr := conn.Close(); cerr != nil { - grpclog.Infof("Failed to close conn to %s: %v", endpoint, cerr) - } - }() - }() - - return RegisterQueryHandler(ctx, mux, conn) -} - -// RegisterQueryHandler registers the http handlers for service Query to "mux". -// The handlers forward requests to the grpc endpoint over "conn". -func RegisterQueryHandler(ctx context.Context, mux *runtime.ServeMux, conn *grpc.ClientConn) error { - return RegisterQueryHandlerClient(ctx, mux, NewQueryClient(conn)) -} - -// RegisterQueryHandlerClient registers the http handlers for service Query -// to "mux". The handlers forward requests to the grpc endpoint over the given implementation of "QueryClient". -// Note: the gRPC framework executes interceptors within the gRPC handler. If the passed in "QueryClient" -// doesn't go through the normal gRPC flow (creating a gRPC client etc.) then it will be up to the passed in -// "QueryClient" to call the correct interceptors. -func RegisterQueryHandlerClient(ctx context.Context, mux *runtime.ServeMux, client QueryClient) error { - - mux.Handle("GET", pattern_Query_Params_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_Params_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_Params_0(ctx, mux, outboundMarshaler, w, req, resp, mux.GetForwardResponseOptions()...) - - }) - - mux.Handle("GET", pattern_Query_Subspaces_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_Subspaces_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_Subspaces_0(ctx, mux, outboundMarshaler, w, req, resp, mux.GetForwardResponseOptions()...) - - }) - - return nil -} - -var ( - pattern_Query_Params_0 = runtime.MustPattern(runtime.NewPattern(1, []int{2, 0, 2, 1, 2, 2, 2, 1}, []string{"cosmos", "params", "v1beta1"}, "", runtime.AssumeColonVerbOpt(false))) - - pattern_Query_Subspaces_0 = runtime.MustPattern(runtime.NewPattern(1, []int{2, 0, 2, 1, 2, 2, 2, 3}, []string{"cosmos", "params", "v1beta1", "subspaces"}, "", runtime.AssumeColonVerbOpt(false))) -) - -var ( - forward_Query_Params_0 = runtime.ForwardResponseMessage - - forward_Query_Subspaces_0 = runtime.ForwardResponseMessage -) diff --git a/x/params/types/querier.go b/x/params/types/querier.go deleted file mode 100644 index 43914df66ad8..000000000000 --- a/x/params/types/querier.go +++ /dev/null @@ -1,35 +0,0 @@ -package types - -// Querier path constants -const ( - QueryParams = "params" -) - -// QuerySubspaceParams defines the params for querying module params by a given -// subspace and key. -type QuerySubspaceParams struct { - Subspace string - Key string -} - -// SubspaceParamsResponse defines the response for querying parameters by subspace. -type SubspaceParamsResponse struct { - Subspace string - Key string - Value string -} - -func NewQuerySubspaceParams(ss, key string) QuerySubspaceParams { - return QuerySubspaceParams{ - Subspace: ss, - Key: key, - } -} - -func NewSubspaceParamsResponse(ss, key, value string) SubspaceParamsResponse { - return SubspaceParamsResponse{ - Subspace: ss, - Key: key, - Value: value, - } -} diff --git a/x/params/types/subspace.go b/x/params/types/subspace.go deleted file mode 100644 index 4bf299c2b15d..000000000000 --- a/x/params/types/subspace.go +++ /dev/null @@ -1,303 +0,0 @@ -package types - -import ( - "fmt" - "maps" - "reflect" - - "cosmossdk.io/store/prefix" - storetypes "cosmossdk.io/store/types" - - "github.com/cosmos/cosmos-sdk/codec" - sdk "github.com/cosmos/cosmos-sdk/types" -) - -const ( - // StoreKey is the string store key for the param store - StoreKey = "params" - - // TStoreKey is the string store key for the param transient store - TStoreKey = "transient_params" -) - -// Individual parameter store for each keeper -// Transient store persists for a block, so we use it for -// recording whether the parameter has been changed or not -type Subspace struct { - cdc codec.BinaryCodec - legacyAmino *codec.LegacyAmino - key storetypes.StoreKey // []byte -> []byte, stores parameter - tkey storetypes.StoreKey // []byte -> bool, stores parameter change - name []byte - table KeyTable -} - -// NewSubspace constructs a store with namestore -func NewSubspace(cdc codec.BinaryCodec, legacyAmino *codec.LegacyAmino, key, tkey storetypes.StoreKey, name string) Subspace { - return Subspace{ - cdc: cdc, - legacyAmino: legacyAmino, - key: key, - tkey: tkey, - name: []byte(name), - table: NewKeyTable(), - } -} - -// HasKeyTable returns if the Subspace has a KeyTable registered. -func (s Subspace) HasKeyTable() bool { - return len(s.table.m) > 0 -} - -// WithKeyTable initializes KeyTable and returns modified Subspace -func (s Subspace) WithKeyTable(table KeyTable) Subspace { - if table.m == nil { - panic("WithKeyTable() called with nil KeyTable") - } - if len(s.table.m) != 0 { - panic("WithKeyTable() called on already initialized Subspace") - } - - maps.Copy(s.table.m, table.m) - - // Allocate additional capacity for Subspace.name - // So we don't have to allocate extra space each time appending to the key - name := s.name - s.name = make([]byte, len(name), len(name)+table.maxKeyLength()) - copy(s.name, name) - - return s -} - -// Returns a KVStore identical with ctx.KVStore(s.key).Prefix() -func (s Subspace) kvStore(ctx sdk.Context) storetypes.KVStore { - // append here is safe, appends within a function won't cause - // weird side effects when its singlethreaded - return prefix.NewStore(ctx.KVStore(s.key), append(s.name, '/')) -} - -// Returns a transient store for modification -func (s Subspace) transientStore(ctx sdk.Context) storetypes.KVStore { - // append here is safe, appends within a function won't cause - // weird side effects when its singlethreaded - return prefix.NewStore(ctx.TransientStore(s.tkey), append(s.name, '/')) -} - -// Validate attempts to validate a parameter value by its key. If the key is not -// registered or if the validation of the value fails, an error is returned. -func (s Subspace) Validate(ctx sdk.Context, key []byte, value any) error { - attr, ok := s.table.m[string(key)] - if !ok { - return fmt.Errorf("parameter %s not registered", key) - } - - if err := attr.vfn(value); err != nil { - return fmt.Errorf("invalid parameter value: %w", err) - } - - return nil -} - -// Get queries for a parameter by key from the Subspace's KVStore and sets the -// value to the provided pointer. If the value does not exist, it will panic. -func (s Subspace) Get(ctx sdk.Context, key []byte, ptr any) { - s.checkType(key, ptr) - - store := s.kvStore(ctx) - bz := store.Get(key) - - if err := s.legacyAmino.UnmarshalJSON(bz, ptr); err != nil { - panic(err) - } -} - -// GetIfExists queries for a parameter by key from the Subspace's KVStore and -// sets the value to the provided pointer. If the value does not exist, it will -// perform a no-op. -func (s Subspace) GetIfExists(ctx sdk.Context, key []byte, ptr any) { - store := s.kvStore(ctx) - bz := store.Get(key) - if bz == nil { - return - } - - s.checkType(key, ptr) - - if err := s.legacyAmino.UnmarshalJSON(bz, ptr); err != nil { - panic(err) - } -} - -// IterateKeys iterates over all the keys in the subspace and executes the -// provided callback. If the callback returns true for a given key, iteration -// will halt. -func (s Subspace) IterateKeys(ctx sdk.Context, cb func(key []byte) bool) { - store := s.kvStore(ctx) - - iter := storetypes.KVStorePrefixIterator(store, nil) - defer iter.Close() - - for ; iter.Valid(); iter.Next() { - if cb(iter.Key()) { - break - } - } -} - -// GetRaw queries for the raw values bytes for a parameter by key. -func (s Subspace) GetRaw(ctx sdk.Context, key []byte) []byte { - store := s.kvStore(ctx) - return store.Get(key) -} - -// Has returns if a parameter key exists or not in the Subspace's KVStore. -func (s Subspace) Has(ctx sdk.Context, key []byte) bool { - store := s.kvStore(ctx) - return store.Has(key) -} - -// Modified returns true if the parameter key is set in the Subspace's transient -// KVStore. -func (s Subspace) Modified(ctx sdk.Context, key []byte) bool { - tstore := s.transientStore(ctx) - return tstore.Has(key) -} - -// checkType verifies that the provided key and value are compatible and registered. -func (s Subspace) checkType(key []byte, value any) { - attr, ok := s.table.m[string(key)] - if !ok { - panic(fmt.Sprintf("parameter %s not registered", key)) - } - - ty := attr.ty - pty := reflect.TypeOf(value) - if pty.Kind() == reflect.Ptr { - pty = pty.Elem() - } - - if pty != ty { - panic("type mismatch with registered table") - } -} - -// Set stores a value for given a parameter key assuming the parameter type has -// been registered. It will panic if the parameter type has not been registered -// or if the value cannot be encoded. A change record is also set in the Subspace's -// transient KVStore to mark the parameter as modified. -func (s Subspace) Set(ctx sdk.Context, key []byte, value any) { - s.checkType(key, value) - store := s.kvStore(ctx) - - bz, err := s.legacyAmino.MarshalJSON(value) - if err != nil { - panic(err) - } - - store.Set(key, bz) - - tstore := s.transientStore(ctx) - tstore.Set(key, []byte{}) -} - -// Update stores an updated raw value for a given parameter key assuming the -// parameter type has been registered. It will panic if the parameter type has -// not been registered or if the value cannot be encoded. An error is returned -// if the raw value is not compatible with the registered type for the parameter -// key or if the new value is invalid as determined by the registered type's -// validation function. -func (s Subspace) Update(ctx sdk.Context, key, value []byte) error { - attr, ok := s.table.m[string(key)] - if !ok { - panic(fmt.Sprintf("parameter %s not registered", key)) - } - - ty := attr.ty - dest := reflect.New(ty).Interface() - s.GetIfExists(ctx, key, dest) - - if err := s.legacyAmino.UnmarshalJSON(value, dest); err != nil { - return err - } - - // destValue contains the dereferenced value of dest so validation function do - // not have to operate on pointers. - destValue := reflect.Indirect(reflect.ValueOf(dest)).Interface() - if err := s.Validate(ctx, key, destValue); err != nil { - return err - } - - s.Set(ctx, key, dest) - return nil -} - -// GetParamSet iterates through each ParamSetPair where for each pair, it will -// retrieve the value and set it to the corresponding value pointer provided -// in the ParamSetPair by calling Subspace#Get. -func (s Subspace) GetParamSet(ctx sdk.Context, ps ParamSet) { - for _, pair := range ps.ParamSetPairs() { - s.Get(ctx, pair.Key, pair.Value) - } -} - -// GetParamSetIfExists iterates through each ParamSetPair where for each pair, it will -// retrieve the value and set it to the corresponding value pointer provided -// in the ParamSetPair by calling Subspace#GetIfExists. -func (s Subspace) GetParamSetIfExists(ctx sdk.Context, ps ParamSet) { - for _, pair := range ps.ParamSetPairs() { - s.GetIfExists(ctx, pair.Key, pair.Value) - } -} - -// SetParamSet iterates through each ParamSetPair and sets the value with the -// corresponding parameter key in the Subspace's KVStore. -func (s Subspace) SetParamSet(ctx sdk.Context, ps ParamSet) { - for _, pair := range ps.ParamSetPairs() { - // pair.Field is a pointer to the field, so indirecting the ptr. - // go-amino automatically handles it but just for sure, - // since SetStruct is meant to be used in InitGenesis - // so this method will not be called frequently - v := reflect.Indirect(reflect.ValueOf(pair.Value)).Interface() - - if err := pair.ValidatorFn(v); err != nil { - panic(fmt.Sprintf("value from ParamSetPair is invalid: %s", err)) - } - - s.Set(ctx, pair.Key, v) - } -} - -// Name returns the name of the Subspace. -func (s Subspace) Name() string { - return string(s.name) -} - -// Wrapper of Subspace, provides immutable functions only -type ReadOnlySubspace struct { - s Subspace -} - -// Get delegates a read-only Get call to the Subspace. -func (ros ReadOnlySubspace) Get(ctx sdk.Context, key []byte, ptr any) { - ros.s.Get(ctx, key, ptr) -} - -// GetRaw delegates a read-only GetRaw call to the Subspace. -func (ros ReadOnlySubspace) GetRaw(ctx sdk.Context, key []byte) []byte { - return ros.s.GetRaw(ctx, key) -} - -// Has delegates a read-only Has call to the Subspace. -func (ros ReadOnlySubspace) Has(ctx sdk.Context, key []byte) bool { - return ros.s.Has(ctx, key) -} - -// Modified delegates a read-only Modified call to the Subspace. -func (ros ReadOnlySubspace) Modified(ctx sdk.Context, key []byte) bool { - return ros.s.Modified(ctx, key) -} - -// Name delegates a read-only Name call to the Subspace. -func (ros ReadOnlySubspace) Name() string { - return ros.s.Name() -} diff --git a/x/params/types/subspace_test.go b/x/params/types/subspace_test.go deleted file mode 100644 index 5f0d24d65afc..000000000000 --- a/x/params/types/subspace_test.go +++ /dev/null @@ -1,269 +0,0 @@ -package types_test - -import ( - "bytes" - "fmt" - "testing" - "time" - - cmtproto "github.com/cometbft/cometbft/proto/tendermint/types" - dbm "github.com/cosmos/cosmos-db" - "github.com/stretchr/testify/suite" - - "cosmossdk.io/log" - "cosmossdk.io/store" - "cosmossdk.io/store/metrics" - storetypes "cosmossdk.io/store/types" - - "github.com/cosmos/cosmos-sdk/codec" - sdk "github.com/cosmos/cosmos-sdk/types" - moduletestutil "github.com/cosmos/cosmos-sdk/types/module/testutil" - paramsmodule "github.com/cosmos/cosmos-sdk/x/params" - "github.com/cosmos/cosmos-sdk/x/params/types" -) - -type SubspaceTestSuite struct { - suite.Suite - - cdc codec.Codec - amino *codec.LegacyAmino - ctx sdk.Context - ss types.Subspace -} - -func (suite *SubspaceTestSuite) SetupTest() { - db := dbm.NewMemDB() - - ms := store.NewCommitMultiStore(db, log.NewNopLogger(), metrics.NewNoOpMetrics()) - ms.MountStoreWithDB(key, storetypes.StoreTypeIAVL, db) - ms.MountStoreWithDB(tkey, storetypes.StoreTypeTransient, db) - suite.NoError(ms.LoadLatestVersion()) - - encodingConfig := moduletestutil.MakeTestEncodingConfig(paramsmodule.AppModuleBasic{}) - suite.cdc = encodingConfig.Codec - suite.amino = encodingConfig.Amino - - ss := types.NewSubspace(suite.cdc, suite.amino, key, tkey, "testsubspace") - suite.ctx = sdk.NewContext(ms, cmtproto.Header{}, false, log.NewNopLogger()) - suite.ss = ss.WithKeyTable(paramKeyTable()) -} - -func (suite *SubspaceTestSuite) TestKeyTable() { - suite.Require().True(suite.ss.HasKeyTable()) - suite.Require().Panics(func() { - suite.ss.WithKeyTable(paramKeyTable()) - }) - suite.Require().NotPanics(func() { - ss := types.NewSubspace(suite.cdc, suite.amino, key, tkey, "testsubspace2") - _ = ss.WithKeyTable(paramKeyTable()) - }) -} - -func (suite *SubspaceTestSuite) TestGetSet() { - var v time.Duration - t := time.Hour * 48 - - suite.Require().Panics(func() { - suite.ss.Get(suite.ctx, keyUnbondingTime, &v) - }) - suite.Require().NotEqual(t, v) - suite.Require().NotPanics(func() { - suite.ss.Set(suite.ctx, keyUnbondingTime, t) - }) - suite.Require().NotPanics(func() { - suite.ss.Get(suite.ctx, keyUnbondingTime, &v) - }) - suite.Require().Equal(t, v) -} - -func (suite *SubspaceTestSuite) TestGetIfExists() { - var v time.Duration - - suite.Require().NotPanics(func() { - suite.ss.GetIfExists(suite.ctx, keyUnbondingTime, &v) - }) - suite.Require().Equal(time.Duration(0), v) -} - -func (suite *SubspaceTestSuite) TestGetRaw() { - t := time.Hour * 48 - - suite.Require().NotPanics(func() { - suite.ss.Set(suite.ctx, keyUnbondingTime, t) - }) - suite.Require().NotPanics(func() { - res := suite.ss.GetRaw(suite.ctx, keyUnbondingTime) - suite.Require().Equal("2231373238303030303030303030303022", fmt.Sprintf("%X", res)) - }) -} - -func (suite *SubspaceTestSuite) TestIterateKeys() { - suite.Require().NotPanics(func() { - suite.ss.Set(suite.ctx, keyUnbondingTime, time.Second) - }) - suite.Require().NotPanics(func() { - suite.ss.Set(suite.ctx, keyMaxValidators, uint16(50)) - }) - suite.Require().NotPanics(func() { - suite.ss.Set(suite.ctx, keyBondDenom, "stake") - }) - - var keys [][]byte - suite.ss.IterateKeys(suite.ctx, func(key []byte) bool { - keys = append(keys, key) - return false - }) - suite.Require().Len(keys, 3) - suite.Require().Contains(keys, keyUnbondingTime) - suite.Require().Contains(keys, keyMaxValidators) - suite.Require().Contains(keys, keyBondDenom) - - var keys2 [][]byte - suite.ss.IterateKeys(suite.ctx, func(key []byte) bool { - if bytes.Equal(key, keyUnbondingTime) { - return true - } - - keys2 = append(keys2, key) - return false - }) - suite.Require().Len(keys2, 2) - suite.Require().Contains(keys2, keyMaxValidators) - suite.Require().Contains(keys2, keyBondDenom) -} - -func (suite *SubspaceTestSuite) TestHas() { - t := time.Hour * 48 - - suite.Require().False(suite.ss.Has(suite.ctx, keyUnbondingTime)) - suite.Require().NotPanics(func() { - suite.ss.Set(suite.ctx, keyUnbondingTime, t) - }) - suite.Require().True(suite.ss.Has(suite.ctx, keyUnbondingTime)) -} - -func (suite *SubspaceTestSuite) TestModified() { - t := time.Hour * 48 - - suite.Require().False(suite.ss.Modified(suite.ctx, keyUnbondingTime)) - suite.Require().NotPanics(func() { - suite.ss.Set(suite.ctx, keyUnbondingTime, t) - }) - suite.Require().True(suite.ss.Modified(suite.ctx, keyUnbondingTime)) -} - -func (suite *SubspaceTestSuite) TestUpdate() { - suite.Require().Panics(func() { - suite.ss.Update(suite.ctx, []byte("invalid_key"), nil) - }) - - t := time.Hour * 48 - suite.Require().NotPanics(func() { - suite.ss.Set(suite.ctx, keyUnbondingTime, t) - }) - - bad := time.Minute * 5 - - bz, err := suite.amino.MarshalJSON(bad) - suite.Require().NoError(err) - suite.Require().Error(suite.ss.Update(suite.ctx, keyUnbondingTime, bz)) - - good := time.Hour * 360 - bz, err = suite.amino.MarshalJSON(good) - suite.Require().NoError(err) - suite.Require().NoError(suite.ss.Update(suite.ctx, keyUnbondingTime, bz)) - - var v time.Duration - - suite.Require().NotPanics(func() { - suite.ss.Get(suite.ctx, keyUnbondingTime, &v) - }) - suite.Require().Equal(good, v) -} - -func (suite *SubspaceTestSuite) TestGetParamSet() { - a := params{ - UnbondingTime: time.Hour * 48, - MaxValidators: 100, - BondDenom: "stake", - } - suite.Require().NotPanics(func() { - suite.ss.Set(suite.ctx, keyUnbondingTime, a.UnbondingTime) - suite.ss.Set(suite.ctx, keyMaxValidators, a.MaxValidators) - suite.ss.Set(suite.ctx, keyBondDenom, a.BondDenom) - }) - - b := params{} - suite.Require().NotPanics(func() { - suite.ss.GetParamSet(suite.ctx, &b) - }) - suite.Require().Equal(a.UnbondingTime, b.UnbondingTime) - suite.Require().Equal(a.MaxValidators, b.MaxValidators) - suite.Require().Equal(a.BondDenom, b.BondDenom) -} - -func (suite *SubspaceTestSuite) TestGetParamSetIfExists() { - a := params{ - UnbondingTime: time.Hour * 48, - MaxValidators: 100, - BondDenom: "stake", - } - suite.Require().NotPanics(func() { - suite.ss.Set(suite.ctx, keyUnbondingTime, a.UnbondingTime) - suite.ss.Set(suite.ctx, keyMaxValidators, a.MaxValidators) - suite.ss.Set(suite.ctx, keyBondDenom, a.BondDenom) - }) - - b := paramsV2{} - suite.Require().NotPanics(func() { - suite.ss.GetParamSetIfExists(suite.ctx, &b) - }) - suite.Require().Equal(a.UnbondingTime, b.UnbondingTime) - suite.Require().Equal(a.MaxValidators, b.MaxValidators) - suite.Require().Equal(a.BondDenom, b.BondDenom) - suite.Require().Zero(b.MaxRedelegationEntries) - suite.Require().False(suite.ss.Has(suite.ctx, keyMaxRedelegationEntries), "key from the new param version should not yet exist") -} - -func (suite *SubspaceTestSuite) TestSetParamSet() { - testCases := []struct { - name string - ps types.ParamSet - }{ - {"invalid unbonding time", ¶ms{time.Hour * 1, 100, "stake"}}, - {"invalid bond denom", ¶ms{time.Hour * 48, 100, ""}}, - } - - for _, tc := range testCases { - suite.Run(tc.name, func() { - suite.Require().Panics(func() { - suite.ss.SetParamSet(suite.ctx, tc.ps) - }) - }) - } - - a := params{ - UnbondingTime: time.Hour * 48, - MaxValidators: 100, - BondDenom: "stake", - } - suite.Require().NotPanics(func() { - suite.ss.SetParamSet(suite.ctx, &a) - }) - - b := params{} - suite.Require().NotPanics(func() { - suite.ss.GetParamSet(suite.ctx, &b) - }) - suite.Require().Equal(a.UnbondingTime, b.UnbondingTime) - suite.Require().Equal(a.MaxValidators, b.MaxValidators) - suite.Require().Equal(a.BondDenom, b.BondDenom) -} - -func (suite *SubspaceTestSuite) TestName() { - suite.Require().Equal("testsubspace", suite.ss.Name()) -} - -func TestKeeperTestSuite(t *testing.T) { - suite.Run(t, new(SubspaceTestSuite)) -} diff --git a/x/params/types/table.go b/x/params/types/table.go deleted file mode 100644 index 5982d592ec3a..000000000000 --- a/x/params/types/table.go +++ /dev/null @@ -1,83 +0,0 @@ -package types - -import ( - "reflect" - - sdk "github.com/cosmos/cosmos-sdk/types" -) - -type attribute struct { - ty reflect.Type - vfn ValueValidatorFn -} - -// KeyTable subspaces appropriate type for each parameter key -type KeyTable struct { - m map[string]attribute -} - -// IsOnePerModuleType implements depinject.OnePerModuleType -func (KeyTable) IsOnePerModuleType() {} - -func NewKeyTable(pairs ...ParamSetPair) KeyTable { - keyTable := KeyTable{ - m: make(map[string]attribute), - } - - for _, psp := range pairs { - keyTable = keyTable.RegisterType(psp) - } - - return keyTable -} - -// RegisterType registers a single ParamSetPair (key-type pair) in a KeyTable. -func (t KeyTable) RegisterType(psp ParamSetPair) KeyTable { - if len(psp.Key) == 0 { - panic("cannot register ParamSetPair with a parameter empty key") - } - if !sdk.IsAlphaNumeric(string(psp.Key)) { - panic("cannot register ParamSetPair with a non-alphanumeric parameter key") - } - if psp.ValidatorFn == nil { - panic("cannot register ParamSetPair without a value validation function") - } - - keystr := string(psp.Key) - if _, ok := t.m[keystr]; ok { - panic("duplicate parameter key") - } - - rty := reflect.TypeOf(psp.Value) - - // indirect rty if it is a pointer - for rty.Kind() == reflect.Ptr { - rty = rty.Elem() - } - - t.m[keystr] = attribute{ - vfn: psp.ValidatorFn, - ty: rty, - } - - return t -} - -// RegisterParamSet registers multiple ParamSetPairs from a ParamSet in a KeyTable. -func (t KeyTable) RegisterParamSet(ps ParamSet) KeyTable { - for _, psp := range ps.ParamSetPairs() { - t = t.RegisterType(psp) - } - return t -} - -func (t KeyTable) maxKeyLength() (res int) { - for k := range t.m { - l := len(k) - if l > res { - res = l - } - } - - return -} diff --git a/x/params/types/table_test.go b/x/params/types/table_test.go deleted file mode 100644 index 0baff40f8c6c..000000000000 --- a/x/params/types/table_test.go +++ /dev/null @@ -1,46 +0,0 @@ -package types_test - -import ( - "testing" - "time" - - "github.com/stretchr/testify/require" - - "github.com/cosmos/cosmos-sdk/x/params/types" -) - -func TestKeyTable(t *testing.T) { - table := types.NewKeyTable() - - require.Panics(t, func() { table.RegisterType(types.ParamSetPair{[]byte(""), nil, nil}) }) - require.Panics(t, func() { table.RegisterType(types.ParamSetPair{[]byte("!@#$%"), nil, nil}) }) - require.Panics(t, func() { table.RegisterType(types.ParamSetPair{[]byte("hello,"), nil, nil}) }) - require.Panics(t, func() { table.RegisterType(types.ParamSetPair{[]byte("hello"), nil, nil}) }) - - require.NotPanics(t, func() { - table.RegisterType(types.ParamSetPair{keyBondDenom, string("stake"), validateBondDenom}) - }) - require.NotPanics(t, func() { - table.RegisterType(types.ParamSetPair{keyMaxValidators, uint16(100), validateMaxValidators}) - }) - require.Panics(t, func() { - table.RegisterType(types.ParamSetPair{keyUnbondingTime, time.Duration(1), nil}) - }) - require.NotPanics(t, func() { - table.RegisterType(types.ParamSetPair{keyUnbondingTime, time.Duration(1), validateMaxValidators}) - }) - require.NotPanics(t, func() { - newTable := types.NewKeyTable() - newTable.RegisterParamSet(¶ms{}) - }) - - require.Panics(t, func() { table.RegisterParamSet(¶ms{}) }) - require.Panics(t, func() { types.NewKeyTable(types.ParamSetPair{[]byte(""), nil, nil}) }) - - require.NotPanics(t, func() { - types.NewKeyTable( - types.ParamSetPair{[]byte("test"), string("stake"), validateBondDenom}, - types.ParamSetPair{[]byte("test2"), uint16(100), validateMaxValidators}, - ) - }) -} diff --git a/x/protocolpool/testutil/app_config.go b/x/protocolpool/testutil/app_config.go index e6d3a4ba6c88..5ec5eb62ba21 100644 --- a/x/protocolpool/testutil/app_config.go +++ b/x/protocolpool/testutil/app_config.go @@ -9,7 +9,6 @@ import ( _ "github.com/cosmos/cosmos-sdk/x/distribution" // import as blank for app wiring _ "github.com/cosmos/cosmos-sdk/x/genutil" // import as blank for app wiring _ "github.com/cosmos/cosmos-sdk/x/mint" // import as blank for app wiring - _ "github.com/cosmos/cosmos-sdk/x/params" // import as blank for app wiring _ "github.com/cosmos/cosmos-sdk/x/protocolpool" // import as blank for app wiring _ "github.com/cosmos/cosmos-sdk/x/staking" // import as blank for app wiring ) @@ -20,7 +19,6 @@ var AppConfig = configurator.NewAppConfig( configurator.StakingModule(), configurator.TxModule(), configurator.ConsensusModule(), - configurator.ParamsModule(), configurator.GenutilModule(), configurator.DistributionModule(), configurator.MintModule(), diff --git a/x/slashing/app_test.go b/x/slashing/app_test.go index 06679bc420f1..008edc97fe81 100644 --- a/x/slashing/app_test.go +++ b/x/slashing/app_test.go @@ -57,7 +57,6 @@ func TestSlashingMsgs(t *testing.T) { app, err := sims.SetupWithConfiguration( depinject.Configs( configurator.NewAppConfig( - configurator.ParamsModule(), configurator.AuthModule(), configurator.StakingModule(), configurator.SlashingModule(), diff --git a/x/slashing/exported/exported.go b/x/slashing/exported/exported.go deleted file mode 100644 index 000114e6194d..000000000000 --- a/x/slashing/exported/exported.go +++ /dev/null @@ -1,18 +0,0 @@ -package exported - -import ( - sdk "github.com/cosmos/cosmos-sdk/types" - paramtypes "github.com/cosmos/cosmos-sdk/x/params/types" -) - -type ( - ParamSet = paramtypes.ParamSet - - // Subspace defines an interface that implements the legacy x/params Subspace - // type. - // - // NOTE: This is used solely for migration of x/params managed parameters. - Subspace interface { - GetParamSet(ctx sdk.Context, ps ParamSet) - } -) diff --git a/x/slashing/keeper/migrations.go b/x/slashing/keeper/migrations.go deleted file mode 100644 index 356db7336f1a..000000000000 --- a/x/slashing/keeper/migrations.go +++ /dev/null @@ -1,47 +0,0 @@ -package keeper - -import ( - "github.com/cosmos/cosmos-sdk/runtime" - sdk "github.com/cosmos/cosmos-sdk/types" - "github.com/cosmos/cosmos-sdk/x/slashing/exported" - v2 "github.com/cosmos/cosmos-sdk/x/slashing/migrations/v2" - v3 "github.com/cosmos/cosmos-sdk/x/slashing/migrations/v3" - v4 "github.com/cosmos/cosmos-sdk/x/slashing/migrations/v4" -) - -// Migrator is a struct for handling in-place store migrations. -type Migrator struct { - keeper Keeper - legacySubspace exported.Subspace -} - -// NewMigrator returns a new Migrator. -func NewMigrator(keeper Keeper, ss exported.Subspace) Migrator { - return Migrator{keeper: keeper, legacySubspace: ss} -} - -// Migrate1to2 migrates from version 1 to 2. -func (m Migrator) Migrate1to2(ctx sdk.Context) error { - return v2.MigrateStore(ctx, m.keeper.storeService) -} - -// Migrate2to3 migrates the x/slashing module state from the consensus -// version 2 to version 3. Specifically, it takes the parameters that are currently stored -// and managed by the x/params modules and stores them directly into the x/slashing -// module state. -func (m Migrator) Migrate2to3(ctx sdk.Context) error { - store := runtime.KVStoreAdapter(m.keeper.storeService.OpenKVStore(ctx)) - return v3.Migrate(ctx, store, m.legacySubspace, m.keeper.cdc) -} - -// Migrate3to4 migrates the x/slashing module state from the consensus -// version 3 to version 4. Specifically, it migrates the validator missed block -// bitmap. -func (m Migrator) Migrate3to4(ctx sdk.Context) error { - store := runtime.KVStoreAdapter(m.keeper.storeService.OpenKVStore(ctx)) - params, err := m.keeper.GetParams(ctx) - if err != nil { - return err - } - return v4.Migrate(ctx, m.keeper.cdc, store, params) -} diff --git a/x/slashing/migrations/v1/types.go b/x/slashing/migrations/v1/types.go deleted file mode 100644 index 8267a6d83659..000000000000 --- a/x/slashing/migrations/v1/types.go +++ /dev/null @@ -1,69 +0,0 @@ -// Package v040 is copy-pasted from: -// https://github.com/cosmos/cosmos-sdk/blob/v0.41.0/x/slashing/types/keys.go -package legacy - -import ( - "encoding/binary" - - sdk "github.com/cosmos/cosmos-sdk/types" - "github.com/cosmos/cosmos-sdk/types/kv" - v1auth "github.com/cosmos/cosmos-sdk/x/auth/migrations/v1" -) - -const ( - // ModuleName is the name of the module - ModuleName = "slashing" - - // StoreKey is the store key string for slashing - StoreKey = ModuleName - - // RouterKey is the message route for slashing - RouterKey = ModuleName - - // QuerierRoute is the querier route for slashing - QuerierRoute = ModuleName -) - -// Keys for slashing store -// Items are stored with the following key: values -// -// - 0x01: ValidatorSigningInfo -// -// - 0x02: bool -// -// - 0x03: crypto.PubKey -var ( - ValidatorSigningInfoKeyPrefix = []byte{0x01} // Prefix for signing info - ValidatorMissedBlockBitArrayKeyPrefix = []byte{0x02} // Prefix for missed block bit array - AddrPubkeyRelationKeyPrefix = []byte{0x03} // Prefix for address-pubkey relation -) - -// ValidatorSigningInfoKey - stored by *Consensus* address (not operator address) -func ValidatorSigningInfoKey(v sdk.ConsAddress) []byte { - return append(ValidatorSigningInfoKeyPrefix, v.Bytes()...) -} - -// ValidatorSigningInfoAddress - extract the address from a validator signing info key -func ValidatorSigningInfoAddress(key []byte) (v sdk.ConsAddress) { - kv.AssertKeyAtLeastLength(key, 2) - addr := key[1:] - kv.AssertKeyLength(addr, v1auth.AddrLen) - return sdk.ConsAddress(addr) -} - -// ValidatorMissedBlockBitArrayPrefixKey - stored by *Consensus* address (not operator address) -func ValidatorMissedBlockBitArrayPrefixKey(v sdk.ConsAddress) []byte { - return append(ValidatorMissedBlockBitArrayKeyPrefix, v.Bytes()...) -} - -// ValidatorMissedBlockBitArrayKey - stored by *Consensus* address (not operator address) -func ValidatorMissedBlockBitArrayKey(v sdk.ConsAddress, i int64) []byte { - b := make([]byte, 8) - binary.LittleEndian.PutUint64(b, uint64(i)) - return append(ValidatorMissedBlockBitArrayPrefixKey(v), b...) -} - -// AddrPubkeyRelationKey gets pubkey relation key used to get the pubkey from the address -func AddrPubkeyRelationKey(address []byte) []byte { - return append(AddrPubkeyRelationKeyPrefix, address...) -} diff --git a/x/slashing/migrations/v2/keys.go b/x/slashing/migrations/v2/keys.go deleted file mode 100644 index 26f3f97544f3..000000000000 --- a/x/slashing/migrations/v2/keys.go +++ /dev/null @@ -1,21 +0,0 @@ -package v2 - -import ( - "encoding/binary" - - sdk "github.com/cosmos/cosmos-sdk/types" - "github.com/cosmos/cosmos-sdk/types/address" -) - -var ValidatorMissedBlockBitArrayKeyPrefix = []byte{0x02} - -func ValidatorMissedBlockBitArrayPrefixKey(v sdk.ConsAddress) []byte { - return append(ValidatorMissedBlockBitArrayKeyPrefix, address.MustLengthPrefix(v.Bytes())...) -} - -func ValidatorMissedBlockBitArrayKey(v sdk.ConsAddress, i int64) []byte { - b := make([]byte, 8) - binary.LittleEndian.PutUint64(b, uint64(i)) - - return append(ValidatorMissedBlockBitArrayPrefixKey(v), b...) -} diff --git a/x/slashing/migrations/v2/store.go b/x/slashing/migrations/v2/store.go deleted file mode 100644 index 6d1179ea12da..000000000000 --- a/x/slashing/migrations/v2/store.go +++ /dev/null @@ -1,24 +0,0 @@ -package v2 - -import ( - "context" - - storetypes "cosmossdk.io/core/store" - - "github.com/cosmos/cosmos-sdk/runtime" - v2distribution "github.com/cosmos/cosmos-sdk/x/distribution/migrations/v2" - v1 "github.com/cosmos/cosmos-sdk/x/slashing/migrations/v1" -) - -// MigrateStore performs in-place store migrations from v0.40 to v0.43. The -// migration includes: -// -// - Change addresses to be length-prefixed. -func MigrateStore(ctx context.Context, storeService storetypes.KVStoreService) error { - store := runtime.KVStoreAdapter(storeService.OpenKVStore(ctx)) - v2distribution.MigratePrefixAddress(store, v1.ValidatorSigningInfoKeyPrefix) - v2distribution.MigratePrefixAddressBytes(store, v1.ValidatorMissedBlockBitArrayKeyPrefix) - v2distribution.MigratePrefixAddress(store, v1.AddrPubkeyRelationKeyPrefix) - - return nil -} diff --git a/x/slashing/migrations/v2/store_test.go b/x/slashing/migrations/v2/store_test.go deleted file mode 100644 index cdba954d023c..000000000000 --- a/x/slashing/migrations/v2/store_test.go +++ /dev/null @@ -1,76 +0,0 @@ -package v2_test - -import ( - "bytes" - "testing" - - "github.com/stretchr/testify/require" - - storetypes "cosmossdk.io/store/types" - - "github.com/cosmos/cosmos-sdk/runtime" - "github.com/cosmos/cosmos-sdk/testutil" - "github.com/cosmos/cosmos-sdk/testutil/testdata" - sdk "github.com/cosmos/cosmos-sdk/types" - v1 "github.com/cosmos/cosmos-sdk/x/slashing/migrations/v1" - v2 "github.com/cosmos/cosmos-sdk/x/slashing/migrations/v2" - "github.com/cosmos/cosmos-sdk/x/slashing/types" -) - -func TestStoreMigration(t *testing.T) { - slashingKey := storetypes.NewKVStoreKey("slashing") - ctx := testutil.DefaultContext(slashingKey, storetypes.NewTransientStoreKey("transient_test")) - storeService := runtime.NewKVStoreService(slashingKey) - store := storeService.OpenKVStore(ctx) - - _, _, addr1 := testdata.KeyTestPubAddr() - consAddr := sdk.ConsAddress(addr1) - // Use dummy value for all keys. - value := []byte("foo") - - testCases := []struct { - name string - oldKey []byte - newKey []byte - }{ - { - "ValidatorSigningInfoKey", - v1.ValidatorSigningInfoKey(consAddr), - types.ValidatorSigningInfoKey(consAddr), - }, - { - "ValidatorMissedBlockBitArrayKey", - v1.ValidatorMissedBlockBitArrayKey(consAddr, 2), - v2.ValidatorMissedBlockBitArrayKey(consAddr, 2), - }, - { - "AddrPubkeyRelationKey", - v1.AddrPubkeyRelationKey(consAddr), - types.AddrPubkeyRelationKey(consAddr), - }, - } - - // Set all the old keys to the store - for _, tc := range testCases { - err := store.Set(tc.oldKey, value) - require.NoError(t, err) - } - - // Run migrations. - err := v2.MigrateStore(ctx, storeService) - require.NoError(t, err) - - // Make sure the new keys are set and old keys are deleted. - for _, tc := range testCases { - t.Run(tc.name, func(t *testing.T) { - if !bytes.Equal(tc.oldKey, tc.newKey) { - v, err := store.Get(tc.oldKey) - require.NoError(t, err) - require.Nil(t, v) - } - v, err := store.Get(tc.newKey) - require.NoError(t, err) - require.Equal(t, value, v) - }) - } -} diff --git a/x/slashing/migrations/v3/migrate.go b/x/slashing/migrations/v3/migrate.go deleted file mode 100644 index c740ccd15a35..000000000000 --- a/x/slashing/migrations/v3/migrate.go +++ /dev/null @@ -1,34 +0,0 @@ -package v3 - -import ( - storetypes "cosmossdk.io/store/types" - - "github.com/cosmos/cosmos-sdk/codec" - sdk "github.com/cosmos/cosmos-sdk/types" - "github.com/cosmos/cosmos-sdk/x/slashing/exported" - "github.com/cosmos/cosmos-sdk/x/slashing/types" -) - -const ( - ModuleName = "slashing" -) - -var ParamsKey = []byte{0x00} - -// Migrate migrates the x/slashing module state from the consensus version 2 to -// version 3. Specifically, it takes the parameters that are currently stored -// and managed by the x/params modules and stores them directly into the x/slashing -// module state. -func Migrate(ctx sdk.Context, store storetypes.KVStore, legacySubspace exported.Subspace, cdc codec.BinaryCodec) error { - var currParams types.Params - legacySubspace.GetParamSet(ctx, &currParams) - - if err := currParams.Validate(); err != nil { - return err - } - - bz := cdc.MustMarshal(&currParams) - store.Set(ParamsKey, bz) - - return nil -} diff --git a/x/slashing/migrations/v3/migrator_test.go b/x/slashing/migrations/v3/migrator_test.go deleted file mode 100644 index 514848273504..000000000000 --- a/x/slashing/migrations/v3/migrator_test.go +++ /dev/null @@ -1,45 +0,0 @@ -package v3_test - -import ( - "testing" - - "github.com/stretchr/testify/require" - - storetypes "cosmossdk.io/store/types" - - "github.com/cosmos/cosmos-sdk/testutil" - sdk "github.com/cosmos/cosmos-sdk/types" - moduletestutil "github.com/cosmos/cosmos-sdk/types/module/testutil" - "github.com/cosmos/cosmos-sdk/x/slashing" - "github.com/cosmos/cosmos-sdk/x/slashing/exported" - v3 "github.com/cosmos/cosmos-sdk/x/slashing/migrations/v3" - "github.com/cosmos/cosmos-sdk/x/slashing/types" -) - -type mockSubspace struct { - ps types.Params -} - -func newMockSubspace(ps types.Params) mockSubspace { - return mockSubspace{ps: ps} -} - -func (ms mockSubspace) GetParamSet(ctx sdk.Context, ps exported.ParamSet) { - *ps.(*types.Params) = ms.ps -} - -func TestMigrate(t *testing.T) { - cdc := moduletestutil.MakeTestEncodingConfig(slashing.AppModuleBasic{}).Codec - storeKey := storetypes.NewKVStoreKey(v3.ModuleName) - tKey := storetypes.NewTransientStoreKey("transient_test") - ctx := testutil.DefaultContext(storeKey, tKey) - store := ctx.KVStore(storeKey) - - legacySubspace := newMockSubspace(types.DefaultParams()) - require.NoError(t, v3.Migrate(ctx, store, legacySubspace, cdc)) - - var res types.Params - bz := store.Get(v3.ParamsKey) - require.NoError(t, cdc.Unmarshal(bz, &res)) - require.Equal(t, legacySubspace.ps, res) -} diff --git a/x/slashing/migrations/v4/keys.go b/x/slashing/migrations/v4/keys.go deleted file mode 100644 index c5ab30ff72bd..000000000000 --- a/x/slashing/migrations/v4/keys.go +++ /dev/null @@ -1,49 +0,0 @@ -package v4 - -import ( - "encoding/binary" - - sdk "github.com/cosmos/cosmos-sdk/types" - "github.com/cosmos/cosmos-sdk/types/address" - "github.com/cosmos/cosmos-sdk/types/kv" -) - -const MissedBlockBitmapChunkSize = 1024 // 2^10 bits - -var ( - ValidatorSigningInfoKeyPrefix = []byte{0x01} - validatorMissedBlockBitArrayKeyPrefix = []byte{0x02} -) - -func ValidatorSigningInfoKey(v sdk.ConsAddress) []byte { - return append(ValidatorSigningInfoKeyPrefix, address.MustLengthPrefix(v.Bytes())...) -} - -func ValidatorSigningInfoAddress(key []byte) (v sdk.ConsAddress) { - // Remove prefix and address length. - kv.AssertKeyAtLeastLength(key, 3) - addr := key[2:] - - return sdk.ConsAddress(addr) -} - -func validatorMissedBlockBitArrayPrefixKey(v sdk.ConsAddress) []byte { - return append(validatorMissedBlockBitArrayKeyPrefix, address.MustLengthPrefix(v.Bytes())...) -} - -func ValidatorMissedBlockBitArrayKey(v sdk.ConsAddress, i int64) []byte { - b := make([]byte, 8) - binary.LittleEndian.PutUint64(b, uint64(i)) - return append(validatorMissedBlockBitArrayPrefixKey(v), b...) -} - -func validatorMissedBlockBitmapPrefixKey(v sdk.ConsAddress) []byte { - return append(validatorMissedBlockBitArrayKeyPrefix, address.MustLengthPrefix(v.Bytes())...) -} - -func ValidatorMissedBlockBitmapKey(v sdk.ConsAddress, chunkIndex int64) []byte { - bz := make([]byte, 8) - binary.LittleEndian.PutUint64(bz, uint64(chunkIndex)) - - return append(validatorMissedBlockBitmapPrefixKey(v), bz...) -} diff --git a/x/slashing/migrations/v4/migrate.go b/x/slashing/migrations/v4/migrate.go deleted file mode 100644 index 2771e877b3da..000000000000 --- a/x/slashing/migrations/v4/migrate.go +++ /dev/null @@ -1,154 +0,0 @@ -package v4 - -import ( - "github.com/bits-and-blooms/bitset" - gogotypes "github.com/cosmos/gogoproto/types" - - "cosmossdk.io/errors" - storetypes "cosmossdk.io/store/types" - - "github.com/cosmos/cosmos-sdk/codec" - sdk "github.com/cosmos/cosmos-sdk/types" - "github.com/cosmos/cosmos-sdk/x/slashing/types" -) - -// Migrate migrates state to consensus version 4. Specifically, the migration -// deletes all existing validator bitmap entries and replaces them with a real -// "chunked" bitmap. -func Migrate(ctx sdk.Context, cdc codec.BinaryCodec, store storetypes.KVStore, params types.Params) error { - // Get all the missed blocks for each validator, based on the existing signing - // info. - var missedBlocks []types.ValidatorMissedBlocks - iterateValidatorSigningInfos(ctx, cdc, store, func(addr sdk.ConsAddress, info types.ValidatorSigningInfo) (stop bool) { - bechAddr := addr.String() - localMissedBlocks := GetValidatorMissedBlocks(ctx, cdc, store, addr, params) - - missedBlocks = append(missedBlocks, types.ValidatorMissedBlocks{ - Address: bechAddr, - MissedBlocks: localMissedBlocks, - }) - - return false - }) - - // For each missed blocks entry, of which there should only be one per validator, - // we clear all the old entries and insert the new chunked entry. - for _, mb := range missedBlocks { - addr, err := sdk.ConsAddressFromBech32(mb.Address) - if err != nil { - return err - } - - deleteValidatorMissedBlockBitArray(ctx, store, addr) - - for _, b := range mb.MissedBlocks { - // Note: It is not necessary to store entries with missed=false, i.e. where - // the bit is zero, since when the bitmap is initialized, all non-set bits - // are already zero. - if b.Missed { - if err := setMissedBlockBitmapValue(ctx, store, addr, b.Index, true); err != nil { - return err - } - } - } - } - - return nil -} - -func iterateValidatorSigningInfos( - ctx sdk.Context, - cdc codec.BinaryCodec, - store storetypes.KVStore, - cb func(address sdk.ConsAddress, info types.ValidatorSigningInfo) (stop bool), -) { - iter := storetypes.KVStorePrefixIterator(store, ValidatorSigningInfoKeyPrefix) - defer iter.Close() - - for ; iter.Valid(); iter.Next() { - address := ValidatorSigningInfoAddress(iter.Key()) - var info types.ValidatorSigningInfo - cdc.MustUnmarshal(iter.Value(), &info) - - if cb(address, info) { - break - } - } -} - -func iterateValidatorMissedBlockBitArray( - ctx sdk.Context, - cdc codec.BinaryCodec, - store storetypes.KVStore, - addr sdk.ConsAddress, - params types.Params, - cb func(index int64, missed bool) (stop bool), -) { - for i := int64(0); i < params.SignedBlocksWindow; i++ { - var missed gogotypes.BoolValue - bz := store.Get(ValidatorMissedBlockBitArrayKey(addr, i)) - if bz == nil { - continue - } - - cdc.MustUnmarshal(bz, &missed) - if cb(i, missed.Value) { - break - } - } -} - -func GetValidatorMissedBlocks( - ctx sdk.Context, - cdc codec.BinaryCodec, - store storetypes.KVStore, - addr sdk.ConsAddress, - params types.Params, -) []types.MissedBlock { - var missedBlocks []types.MissedBlock - iterateValidatorMissedBlockBitArray(ctx, cdc, store, addr, params, func(index int64, missed bool) (stop bool) { - missedBlocks = append(missedBlocks, types.NewMissedBlock(index, missed)) - return false - }) - - return missedBlocks -} - -func deleteValidatorMissedBlockBitArray(ctx sdk.Context, store storetypes.KVStore, addr sdk.ConsAddress) { - iter := storetypes.KVStorePrefixIterator(store, validatorMissedBlockBitArrayPrefixKey(addr)) - defer iter.Close() - - for ; iter.Valid(); iter.Next() { - store.Delete(iter.Key()) - } -} - -func setMissedBlockBitmapValue(ctx sdk.Context, store storetypes.KVStore, addr sdk.ConsAddress, index int64, missed bool) error { - // get the chunk or "word" in the logical bitmap - chunkIndex := index / MissedBlockBitmapChunkSize - key := ValidatorMissedBlockBitmapKey(addr, chunkIndex) - - bs := bitset.New(uint(MissedBlockBitmapChunkSize)) - chunk := store.Get(key) - if chunk != nil { - if err := bs.UnmarshalBinary(chunk); err != nil { - return errors.Wrapf(err, "failed to decode bitmap chunk; index: %d", index) - } - } - - // get the bit position in the chunk of the logical bitmap - bitIndex := uint(index % MissedBlockBitmapChunkSize) - if missed { - bs.Set(bitIndex) - } else { - bs.Clear(bitIndex) - } - - updatedChunk, err := bs.MarshalBinary() - if err != nil { - return errors.Wrapf(err, "failed to encode bitmap chunk; index: %d", index) - } - - store.Set(key, updatedChunk) - return nil -} diff --git a/x/slashing/migrations/v4/migrate_test.go b/x/slashing/migrations/v4/migrate_test.go deleted file mode 100644 index fc8a043610b9..000000000000 --- a/x/slashing/migrations/v4/migrate_test.go +++ /dev/null @@ -1,61 +0,0 @@ -package v4_test - -import ( - "testing" - - "github.com/bits-and-blooms/bitset" - gogotypes "github.com/cosmos/gogoproto/types" - "github.com/stretchr/testify/require" - - storetypes "cosmossdk.io/store/types" - - "github.com/cosmos/cosmos-sdk/testutil" - sdk "github.com/cosmos/cosmos-sdk/types" - moduletestutil "github.com/cosmos/cosmos-sdk/types/module/testutil" - "github.com/cosmos/cosmos-sdk/x/slashing" - v4 "github.com/cosmos/cosmos-sdk/x/slashing/migrations/v4" - slashingtypes "github.com/cosmos/cosmos-sdk/x/slashing/types" -) - -var consAddr = sdk.ConsAddress(sdk.AccAddress([]byte("addr1_______________"))) - -func TestMigrate(t *testing.T) { - cdc := moduletestutil.MakeTestEncodingConfig(slashing.AppModuleBasic{}).Codec - storeKey := storetypes.NewKVStoreKey(slashingtypes.ModuleName) - tKey := storetypes.NewTransientStoreKey("transient_test") - ctx := testutil.DefaultContext(storeKey, tKey) - store := ctx.KVStore(storeKey) - params := slashingtypes.Params{SignedBlocksWindow: 100} - - // store old signing info and bitmap entries - bz := cdc.MustMarshal(&slashingtypes.ValidatorSigningInfo{Address: consAddr.String()}) - store.Set(v4.ValidatorSigningInfoKey(consAddr), bz) - - for i := int64(0); i < params.SignedBlocksWindow; i++ { - // all even blocks are missed - missed := &gogotypes.BoolValue{Value: i%2 == 0} - bz := cdc.MustMarshal(missed) - store.Set(v4.ValidatorMissedBlockBitArrayKey(consAddr, i), bz) - } - - err := v4.Migrate(ctx, cdc, store, params) - require.NoError(t, err) - - for i := int64(0); i < params.SignedBlocksWindow; i++ { - chunkIndex := i / v4.MissedBlockBitmapChunkSize - chunk := store.Get(v4.ValidatorMissedBlockBitmapKey(consAddr, chunkIndex)) - require.NotNil(t, chunk) - - bs := bitset.New(uint(v4.MissedBlockBitmapChunkSize)) - require.NoError(t, bs.UnmarshalBinary(chunk)) - - // ensure all even blocks are missed - bitIndex := uint(i % v4.MissedBlockBitmapChunkSize) - require.Equal(t, i%2 == 0, bs.Test(bitIndex)) - require.Equal(t, i%2 == 1, !bs.Test(bitIndex)) - } - - // ensure there's only one chunk for a window of size 100 - chunk := store.Get(v4.ValidatorMissedBlockBitmapKey(consAddr, 1)) - require.Nil(t, chunk) -} diff --git a/x/slashing/module.go b/x/slashing/module.go index 67f7fe5e2e0a..947cf1dc7852 100644 --- a/x/slashing/module.go +++ b/x/slashing/module.go @@ -21,7 +21,6 @@ import ( simtypes "github.com/cosmos/cosmos-sdk/types/simulation" authtypes "github.com/cosmos/cosmos-sdk/x/auth/types" govtypes "github.com/cosmos/cosmos-sdk/x/gov/types" - "github.com/cosmos/cosmos-sdk/x/slashing/exported" "github.com/cosmos/cosmos-sdk/x/slashing/keeper" "github.com/cosmos/cosmos-sdk/x/slashing/simulation" "github.com/cosmos/cosmos-sdk/x/slashing/types" @@ -94,9 +93,6 @@ type AppModule struct { accountKeeper types.AccountKeeper bankKeeper types.BankKeeper stakingKeeper types.StakingKeeper - - // legacySubspace is used solely for migration of x/slashing managed parameters - legacySubspace exported.Subspace } // NewAppModule creates a new AppModule object @@ -106,7 +102,6 @@ func NewAppModule( ak types.AccountKeeper, bk types.BankKeeper, sk types.StakingKeeper, - ss exported.Subspace, registry cdctypes.InterfaceRegistry, ) AppModule { return AppModule{ @@ -115,7 +110,6 @@ func NewAppModule( accountKeeper: ak, bankKeeper: bk, stakingKeeper: sk, - legacySubspace: ss, } } @@ -129,19 +123,6 @@ func (am AppModule) IsAppModule() {} func (am AppModule) RegisterServices(cfg module.Configurator) { types.RegisterMsgServer(cfg.MsgServer(), keeper.NewMsgServerImpl(am.keeper)) types.RegisterQueryServer(cfg.QueryServer(), am.keeper) - - m := keeper.NewMigrator(am.keeper, am.legacySubspace) - if err := cfg.RegisterMigration(types.ModuleName, 1, m.Migrate1to2); err != nil { - panic(fmt.Sprintf("failed to migrate x/%s from version 1 to 2: %v", types.ModuleName, err)) - } - - if err := cfg.RegisterMigration(types.ModuleName, 2, m.Migrate2to3); err != nil { - panic(fmt.Sprintf("failed to migrate x/%s from version 2 to 3: %v", types.ModuleName, err)) - } - - if err := cfg.RegisterMigration(types.ModuleName, 3, m.Migrate3to4); err != nil { - panic(fmt.Sprintf("failed to migrate x/%s from version 3 to 4: %v", types.ModuleName, err)) - } } // InitGenesis performs genesis initialization for the slashing module. It returns @@ -227,9 +208,6 @@ type ModuleInputs struct { AccountKeeper types.AccountKeeper BankKeeper types.BankKeeper StakingKeeper types.StakingKeeper - - // LegacySubspace is used solely for migration of x/params managed parameters - LegacySubspace exported.Subspace `optional:"true"` } type ModuleOutputs struct { @@ -248,7 +226,7 @@ func ProvideModule(in ModuleInputs) ModuleOutputs { } k := keeper.NewKeeper(in.Cdc, in.LegacyAmino, in.StoreService, in.StakingKeeper, authority.String()) - m := NewAppModule(in.Cdc, k, in.AccountKeeper, in.BankKeeper, in.StakingKeeper, in.LegacySubspace, in.Registry) + m := NewAppModule(in.Cdc, k, in.AccountKeeper, in.BankKeeper, in.StakingKeeper, in.Registry) return ModuleOutputs{ Keeper: k, Module: m, diff --git a/x/slashing/testutil/app_config.go b/x/slashing/testutil/app_config.go index f2fd2d14e061..8e2afcc3be72 100644 --- a/x/slashing/testutil/app_config.go +++ b/x/slashing/testutil/app_config.go @@ -9,7 +9,6 @@ import ( _ "github.com/cosmos/cosmos-sdk/x/distribution" // import as blank for app wiring _ "github.com/cosmos/cosmos-sdk/x/genutil" // import as blank for app wiring _ "github.com/cosmos/cosmos-sdk/x/mint" // import as blank for app wiring - _ "github.com/cosmos/cosmos-sdk/x/params" // import as blank for app wiring _ "github.com/cosmos/cosmos-sdk/x/slashing" // import as blank for app wiring _ "github.com/cosmos/cosmos-sdk/x/staking" // import as blank for app wiring ) @@ -21,7 +20,6 @@ var AppConfig = configurator.NewAppConfig( configurator.SlashingModule(), configurator.TxModule(), configurator.ConsensusModule(), - configurator.ParamsModule(), configurator.GenutilModule(), configurator.MintModule(), configurator.DistributionModule(), diff --git a/x/slashing/testutil/expected_keepers_mocks.go b/x/slashing/testutil/expected_keepers_mocks.go index e4844a5dd7c8..cb47ed090fbe 100644 --- a/x/slashing/testutil/expected_keepers_mocks.go +++ b/x/slashing/testutil/expected_keepers_mocks.go @@ -16,8 +16,7 @@ import ( address "cosmossdk.io/core/address" math "cosmossdk.io/math" types "github.com/cosmos/cosmos-sdk/types" - types0 "github.com/cosmos/cosmos-sdk/x/params/types" - types1 "github.com/cosmos/cosmos-sdk/x/staking/types" + types0 "github.com/cosmos/cosmos-sdk/x/staking/types" gomock "go.uber.org/mock/gomock" ) @@ -151,94 +150,6 @@ func (mr *MockBankKeeperMockRecorder) SpendableCoins(ctx, addr any) *gomock.Call return mr.mock.ctrl.RecordCallWithMethodType(mr.mock, "SpendableCoins", reflect.TypeOf((*MockBankKeeper)(nil).SpendableCoins), ctx, addr) } -// MockParamSubspace is a mock of ParamSubspace interface. -type MockParamSubspace struct { - ctrl *gomock.Controller - recorder *MockParamSubspaceMockRecorder - isgomock struct{} -} - -// MockParamSubspaceMockRecorder is the mock recorder for MockParamSubspace. -type MockParamSubspaceMockRecorder struct { - mock *MockParamSubspace -} - -// NewMockParamSubspace creates a new mock instance. -func NewMockParamSubspace(ctrl *gomock.Controller) *MockParamSubspace { - mock := &MockParamSubspace{ctrl: ctrl} - mock.recorder = &MockParamSubspaceMockRecorder{mock} - return mock -} - -// EXPECT returns an object that allows the caller to indicate expected use. -func (m *MockParamSubspace) EXPECT() *MockParamSubspaceMockRecorder { - return m.recorder -} - -// Get mocks base method. -func (m *MockParamSubspace) Get(ctx types.Context, key []byte, ptr any) { - m.ctrl.T.Helper() - m.ctrl.Call(m, "Get", ctx, key, ptr) -} - -// Get indicates an expected call of Get. -func (mr *MockParamSubspaceMockRecorder) Get(ctx, key, ptr any) *gomock.Call { - mr.mock.ctrl.T.Helper() - return mr.mock.ctrl.RecordCallWithMethodType(mr.mock, "Get", reflect.TypeOf((*MockParamSubspace)(nil).Get), ctx, key, ptr) -} - -// GetParamSet mocks base method. -func (m *MockParamSubspace) GetParamSet(ctx types.Context, ps types0.ParamSet) { - m.ctrl.T.Helper() - m.ctrl.Call(m, "GetParamSet", ctx, ps) -} - -// GetParamSet indicates an expected call of GetParamSet. -func (mr *MockParamSubspaceMockRecorder) GetParamSet(ctx, ps any) *gomock.Call { - mr.mock.ctrl.T.Helper() - return mr.mock.ctrl.RecordCallWithMethodType(mr.mock, "GetParamSet", reflect.TypeOf((*MockParamSubspace)(nil).GetParamSet), ctx, ps) -} - -// HasKeyTable mocks base method. -func (m *MockParamSubspace) HasKeyTable() bool { - m.ctrl.T.Helper() - ret := m.ctrl.Call(m, "HasKeyTable") - ret0, _ := ret[0].(bool) - return ret0 -} - -// HasKeyTable indicates an expected call of HasKeyTable. -func (mr *MockParamSubspaceMockRecorder) HasKeyTable() *gomock.Call { - mr.mock.ctrl.T.Helper() - return mr.mock.ctrl.RecordCallWithMethodType(mr.mock, "HasKeyTable", reflect.TypeOf((*MockParamSubspace)(nil).HasKeyTable)) -} - -// SetParamSet mocks base method. -func (m *MockParamSubspace) SetParamSet(ctx types.Context, ps types0.ParamSet) { - m.ctrl.T.Helper() - m.ctrl.Call(m, "SetParamSet", ctx, ps) -} - -// SetParamSet indicates an expected call of SetParamSet. -func (mr *MockParamSubspaceMockRecorder) SetParamSet(ctx, ps any) *gomock.Call { - mr.mock.ctrl.T.Helper() - return mr.mock.ctrl.RecordCallWithMethodType(mr.mock, "SetParamSet", reflect.TypeOf((*MockParamSubspace)(nil).SetParamSet), ctx, ps) -} - -// WithKeyTable mocks base method. -func (m *MockParamSubspace) WithKeyTable(table types0.KeyTable) types0.Subspace { - m.ctrl.T.Helper() - ret := m.ctrl.Call(m, "WithKeyTable", table) - ret0, _ := ret[0].(types0.Subspace) - return ret0 -} - -// WithKeyTable indicates an expected call of WithKeyTable. -func (mr *MockParamSubspaceMockRecorder) WithKeyTable(table any) *gomock.Call { - mr.mock.ctrl.T.Helper() - return mr.mock.ctrl.RecordCallWithMethodType(mr.mock, "WithKeyTable", reflect.TypeOf((*MockParamSubspace)(nil).WithKeyTable), table) -} - // MockStakingKeeper is a mock of StakingKeeper interface. type MockStakingKeeper struct { ctrl *gomock.Controller @@ -278,10 +189,10 @@ func (mr *MockStakingKeeperMockRecorder) ConsensusAddressCodec() *gomock.Call { } // Delegation mocks base method. -func (m *MockStakingKeeper) Delegation(arg0 context.Context, arg1 types.AccAddress, arg2 types.ValAddress) (types1.DelegationI, error) { +func (m *MockStakingKeeper) Delegation(arg0 context.Context, arg1 types.AccAddress, arg2 types.ValAddress) (types0.DelegationI, error) { m.ctrl.T.Helper() ret := m.ctrl.Call(m, "Delegation", arg0, arg1, arg2) - ret0, _ := ret[0].(types1.DelegationI) + ret0, _ := ret[0].(types0.DelegationI) ret1, _ := ret[1].(error) return ret0, ret1 } @@ -293,10 +204,10 @@ func (mr *MockStakingKeeperMockRecorder) Delegation(arg0, arg1, arg2 any) *gomoc } // GetAllValidators mocks base method. -func (m *MockStakingKeeper) GetAllValidators(ctx context.Context) ([]types1.Validator, error) { +func (m *MockStakingKeeper) GetAllValidators(ctx context.Context) ([]types0.Validator, error) { m.ctrl.T.Helper() ret := m.ctrl.Call(m, "GetAllValidators", ctx) - ret0, _ := ret[0].([]types1.Validator) + ret0, _ := ret[0].([]types0.Validator) ret1, _ := ret[1].(error) return ret0, ret1 } @@ -323,7 +234,7 @@ func (mr *MockStakingKeeperMockRecorder) IsValidatorJailed(ctx, addr any) *gomoc } // IterateValidators mocks base method. -func (m *MockStakingKeeper) IterateValidators(arg0 context.Context, arg1 func(int64, types1.ValidatorI) bool) error { +func (m *MockStakingKeeper) IterateValidators(arg0 context.Context, arg1 func(int64, types0.ValidatorI) bool) error { m.ctrl.T.Helper() ret := m.ctrl.Call(m, "IterateValidators", arg0, arg1) ret0, _ := ret[0].(error) @@ -381,7 +292,7 @@ func (mr *MockStakingKeeperMockRecorder) Slash(arg0, arg1, arg2, arg3, arg4 any) } // SlashWithInfractionReason mocks base method. -func (m *MockStakingKeeper) SlashWithInfractionReason(arg0 context.Context, arg1 types.ConsAddress, arg2, arg3 int64, arg4 math.LegacyDec, arg5 types1.Infraction) (math.Int, error) { +func (m *MockStakingKeeper) SlashWithInfractionReason(arg0 context.Context, arg1 types.ConsAddress, arg2, arg3 int64, arg4 math.LegacyDec, arg5 types0.Infraction) (math.Int, error) { m.ctrl.T.Helper() ret := m.ctrl.Call(m, "SlashWithInfractionReason", arg0, arg1, arg2, arg3, arg4, arg5) ret0, _ := ret[0].(math.Int) @@ -410,10 +321,10 @@ func (mr *MockStakingKeeperMockRecorder) Unjail(arg0, arg1 any) *gomock.Call { } // Validator mocks base method. -func (m *MockStakingKeeper) Validator(arg0 context.Context, arg1 types.ValAddress) (types1.ValidatorI, error) { +func (m *MockStakingKeeper) Validator(arg0 context.Context, arg1 types.ValAddress) (types0.ValidatorI, error) { m.ctrl.T.Helper() ret := m.ctrl.Call(m, "Validator", arg0, arg1) - ret0, _ := ret[0].(types1.ValidatorI) + ret0, _ := ret[0].(types0.ValidatorI) ret1, _ := ret[1].(error) return ret0, ret1 } @@ -439,10 +350,10 @@ func (mr *MockStakingKeeperMockRecorder) ValidatorAddressCodec() *gomock.Call { } // ValidatorByConsAddr mocks base method. -func (m *MockStakingKeeper) ValidatorByConsAddr(arg0 context.Context, arg1 types.ConsAddress) (types1.ValidatorI, error) { +func (m *MockStakingKeeper) ValidatorByConsAddr(arg0 context.Context, arg1 types.ConsAddress) (types0.ValidatorI, error) { m.ctrl.T.Helper() ret := m.ctrl.Call(m, "ValidatorByConsAddr", arg0, arg1) - ret0, _ := ret[0].(types1.ValidatorI) + ret0, _ := ret[0].(types0.ValidatorI) ret1, _ := ret[1].(error) return ret0, ret1 } diff --git a/x/slashing/types/expected_keepers.go b/x/slashing/types/expected_keepers.go index d38d82e540cc..4309b4510b44 100644 --- a/x/slashing/types/expected_keepers.go +++ b/x/slashing/types/expected_keepers.go @@ -1,13 +1,12 @@ package types import ( - context "context" + "context" "cosmossdk.io/core/address" "cosmossdk.io/math" sdk "github.com/cosmos/cosmos-sdk/types" - paramtypes "github.com/cosmos/cosmos-sdk/x/params/types" stakingtypes "github.com/cosmos/cosmos-sdk/x/staking/types" ) @@ -25,15 +24,6 @@ type BankKeeper interface { SpendableCoins(ctx context.Context, addr sdk.AccAddress) sdk.Coins } -// ParamSubspace defines the expected Subspace interface -type ParamSubspace interface { - HasKeyTable() bool - WithKeyTable(table paramtypes.KeyTable) paramtypes.Subspace - Get(ctx sdk.Context, key []byte, ptr any) - GetParamSet(ctx sdk.Context, ps paramtypes.ParamSet) - SetParamSet(ctx sdk.Context, ps paramtypes.ParamSet) -} - // StakingKeeper expected staking keeper type StakingKeeper interface { ValidatorAddressCodec() address.Codec diff --git a/x/slashing/types/params_legacy.go b/x/slashing/types/params_legacy.go deleted file mode 100644 index f7ea30db0d55..000000000000 --- a/x/slashing/types/params_legacy.go +++ /dev/null @@ -1,35 +0,0 @@ -/* -NOTE: Usage of x/params to manage parameters is deprecated in favor of x/gov -controlled execution of MsgUpdateParams messages. These types remains solely -for migration purposes and will be removed in a future release. -*/ -package types - -import ( - paramtypes "github.com/cosmos/cosmos-sdk/x/params/types" -) - -// Parameter store keys -var ( - KeySignedBlocksWindow = []byte("SignedBlocksWindow") - KeyMinSignedPerWindow = []byte("MinSignedPerWindow") - KeyDowntimeJailDuration = []byte("DowntimeJailDuration") - KeySlashFractionDoubleSign = []byte("SlashFractionDoubleSign") - KeySlashFractionDowntime = []byte("SlashFractionDowntime") -) - -// Deprecated: ParamKeyTable for slashing module -func ParamKeyTable() paramtypes.KeyTable { - return paramtypes.NewKeyTable().RegisterParamSet(&Params{}) -} - -// Deprecated: ParamSetPairs implements params.ParamSet -func (p *Params) ParamSetPairs() paramtypes.ParamSetPairs { - return paramtypes.ParamSetPairs{ - paramtypes.NewParamSetPair(KeySignedBlocksWindow, &p.SignedBlocksWindow, validateSignedBlocksWindow), - paramtypes.NewParamSetPair(KeyMinSignedPerWindow, &p.MinSignedPerWindow, validateMinSignedPerWindow), - paramtypes.NewParamSetPair(KeyDowntimeJailDuration, &p.DowntimeJailDuration, validateDowntimeJailDuration), - paramtypes.NewParamSetPair(KeySlashFractionDoubleSign, &p.SlashFractionDoubleSign, validateSlashFractionDoubleSign), - paramtypes.NewParamSetPair(KeySlashFractionDowntime, &p.SlashFractionDowntime, validateSlashFractionDowntime), - } -} diff --git a/x/staking/exported/exported.go b/x/staking/exported/exported.go deleted file mode 100644 index 2d0c2fd1c391..000000000000 --- a/x/staking/exported/exported.go +++ /dev/null @@ -1,16 +0,0 @@ -package exported - -import ( - sdk "github.com/cosmos/cosmos-sdk/types" - paramtypes "github.com/cosmos/cosmos-sdk/x/params/types" -) - -type ( - // Subspace defines an interface that implements the legacy x/params Subspace - // type. - // - // NOTE: This is used solely for migration of x/params managed parameters. - Subspace interface { - GetParamSet(ctx sdk.Context, ps paramtypes.ParamSet) - } -) diff --git a/x/staking/keeper/migrations.go b/x/staking/keeper/migrations.go index e94848b13397..33fbd6b4edf5 100644 --- a/x/staking/keeper/migrations.go +++ b/x/staking/keeper/migrations.go @@ -1,49 +1,13 @@ package keeper -import ( - "github.com/cosmos/cosmos-sdk/runtime" - sdk "github.com/cosmos/cosmos-sdk/types" - "github.com/cosmos/cosmos-sdk/x/staking/exported" - v2 "github.com/cosmos/cosmos-sdk/x/staking/migrations/v2" - v3 "github.com/cosmos/cosmos-sdk/x/staking/migrations/v3" - v4 "github.com/cosmos/cosmos-sdk/x/staking/migrations/v4" - v5 "github.com/cosmos/cosmos-sdk/x/staking/migrations/v5" -) - // Migrator is a struct for handling in-place store migrations. type Migrator struct { - keeper *Keeper - legacySubspace exported.Subspace + keeper *Keeper } // NewMigrator returns a new Migrator instance. -func NewMigrator(keeper *Keeper, legacySubspace exported.Subspace) Migrator { +func NewMigrator(keeper *Keeper) Migrator { return Migrator{ - keeper: keeper, - legacySubspace: legacySubspace, + keeper: keeper, } } - -// Migrate1to2 migrates from version 1 to 2. -func (m Migrator) Migrate1to2(ctx sdk.Context) error { - store := runtime.KVStoreAdapter(m.keeper.storeService.OpenKVStore(ctx)) - return v2.MigrateStore(ctx, store) -} - -// Migrate2to3 migrates x/staking state from consensus version 2 to 3. -func (m Migrator) Migrate2to3(ctx sdk.Context) error { - store := runtime.KVStoreAdapter(m.keeper.storeService.OpenKVStore(ctx)) - return v3.MigrateStore(ctx, store, m.keeper.cdc, m.legacySubspace) -} - -// Migrate3to4 migrates x/staking state from consensus version 3 to 4. -func (m Migrator) Migrate3to4(ctx sdk.Context) error { - store := runtime.KVStoreAdapter(m.keeper.storeService.OpenKVStore(ctx)) - return v4.MigrateStore(ctx, store, m.keeper.cdc, m.legacySubspace) -} - -// Migrate4to5 migrates x/staking state from consensus version 4 to 5. -func (m Migrator) Migrate4to5(ctx sdk.Context) error { - store := runtime.KVStoreAdapter(m.keeper.storeService.OpenKVStore(ctx)) - return v5.MigrateStore(ctx, store, m.keeper.cdc) -} diff --git a/x/staking/migrations/v1/types.go b/x/staking/migrations/v1/types.go deleted file mode 100644 index a2f27723db28..000000000000 --- a/x/staking/migrations/v1/types.go +++ /dev/null @@ -1,307 +0,0 @@ -package v1 - -import ( - "bytes" - "encoding/binary" - "fmt" - "strconv" - "time" - - sdk "github.com/cosmos/cosmos-sdk/types" - "github.com/cosmos/cosmos-sdk/types/kv" - v1auth "github.com/cosmos/cosmos-sdk/x/auth/migrations/v1" - "github.com/cosmos/cosmos-sdk/x/staking/types" -) - -// Staking params default values -const ( - // DefaultUnbondingTime reflects three weeks in seconds as the default - // unbonding time. - // TODO: Justify our choice of default here. - DefaultUnbondingTime time.Duration = time.Hour * 24 * 7 * 3 - - // DefaultMaxValidators is the maximum number of bonded validators - DefaultMaxValidators uint32 = 100 - - // DefaultMaxEntries maximum entries in a UBD/RED pair - DefaultMaxEntries uint32 = 7 - - // DefaultHistoricalEntries entries is 10000. Apps that don't use IBC can ignore this - // value by not adding the staking module to the application module manager's - // SetOrderBeginBlockers. - DefaultHistoricalEntries uint32 = 10000 -) - -// Keys for store prefixes -// Last* values are constant during a block. - -var ( - LastValidatorPowerKey = []byte{0x11} // prefix for each key to a validator index, for bonded validators - LastTotalPowerKey = []byte{0x12} // prefix for the total power - - ValidatorsKey = []byte{0x21} // prefix for each key to a validator - ValidatorsByConsAddrKey = []byte{0x22} // prefix for each key to a validator index, by pubkey - ValidatorsByPowerIndexKey = []byte{0x23} // prefix for each key to a validator index, sorted by power - - DelegationKey = []byte{0x31} // key for a delegation - UnbondingDelegationKey = []byte{0x32} // key for an unbonding-delegation - UnbondingDelegationByValIndexKey = []byte{0x33} // prefix for each key for an unbonding-delegation, by validator operator - RedelegationKey = []byte{0x34} // key for a redelegation - RedelegationByValSrcIndexKey = []byte{0x35} // prefix for each key for an redelegation, by source validator operator - RedelegationByValDstIndexKey = []byte{0x36} // prefix for each key for an redelegation, by destination validator operator - - UnbondingQueueKey = []byte{0x41} // prefix for the timestamps in unbonding queue - RedelegationQueueKey = []byte{0x42} // prefix for the timestamps in redelegations queue - ValidatorQueueKey = []byte{0x43} // prefix for the timestamps in validator queue - - HistoricalInfoKey = []byte{0x50} // prefix for the historical info -) - -// GetValidatorKey gets the key for the validator with address -// VALUE: staking/Validator -func GetValidatorKey(operatorAddr sdk.ValAddress) []byte { - return append(ValidatorsKey, operatorAddr.Bytes()...) -} - -// GetValidatorByConsAddrKey gets the key for the validator with pubkey -// VALUE: validator operator address ([]byte) -func GetValidatorByConsAddrKey(addr sdk.ConsAddress) []byte { - return append(ValidatorsByConsAddrKey, addr.Bytes()...) -} - -// AddressFromLastValidatorPowerKey gets the validator operator address from LastValidatorPowerKey -func AddressFromLastValidatorPowerKey(key []byte) []byte { - kv.AssertKeyAtLeastLength(key, 2) - return key[1:] // remove prefix bytes -} - -// GetValidatorsByPowerIndexKey gets the validator by power index. -// Power index is the key used in the power-store, and represents the relative -// power ranking of the validator. -// VALUE: validator operator address ([]byte) -func GetValidatorsByPowerIndexKey(validator types.Validator) []byte { - // NOTE the address doesn't need to be stored because counter bytes must always be different - // NOTE the larger values are of higher value - - consensusPower := sdk.TokensToConsensusPower(validator.Tokens, sdk.DefaultPowerReduction) - consensusPowerBytes := make([]byte, 8) - binary.BigEndian.PutUint64(consensusPowerBytes, uint64(consensusPower)) - - powerBytes := consensusPowerBytes - powerBytesLen := len(powerBytes) // 8 - - // key is of format prefix || powerbytes || addrBytes - key := make([]byte, 1+powerBytesLen+v1auth.AddrLen) - - key[0] = ValidatorsByPowerIndexKey[0] - copy(key[1:powerBytesLen+1], powerBytes) - addr, err := sdk.ValAddressFromBech32(validator.OperatorAddress) - if err != nil { - panic(err) - } - operAddrInvr := sdk.CopyBytes(addr) - - for i, b := range operAddrInvr { - operAddrInvr[i] = ^b - } - - copy(key[powerBytesLen+1:], operAddrInvr) - - return key -} - -// GetLastValidatorPowerKey get the bonded validator index key for an operator address -func GetLastValidatorPowerKey(operator sdk.ValAddress) []byte { - return append(LastValidatorPowerKey, operator...) -} - -// GetREDKey returns a key prefix for indexing a redelegation from a delegator -// and source validator to a destination validator. -func GetREDKey(delAddr sdk.AccAddress, valSrcAddr, valDstAddr sdk.ValAddress) []byte { - key := make([]byte, 1+v1auth.AddrLen*3) - - copy(key[0:v1auth.AddrLen+1], GetREDsKey(delAddr.Bytes())) - copy(key[v1auth.AddrLen+1:2*v1auth.AddrLen+1], valSrcAddr.Bytes()) - copy(key[2*v1auth.AddrLen+1:3*v1auth.AddrLen+1], valDstAddr.Bytes()) - - return key -} - -// GetREDByValSrcIndexKey gets the index-key for a redelegation, stored by source-validator-index -// VALUE: none (key rearrangement used) -func GetREDByValSrcIndexKey(delAddr sdk.AccAddress, valSrcAddr, valDstAddr sdk.ValAddress) []byte { - REDSFromValsSrcKey := GetREDsFromValSrcIndexKey(valSrcAddr) - offset := len(REDSFromValsSrcKey) - - // key is of the form REDSFromValsSrcKey || delAddr || valDstAddr - key := make([]byte, len(REDSFromValsSrcKey)+2*v1auth.AddrLen) - copy(key[0:offset], REDSFromValsSrcKey) - copy(key[offset:offset+v1auth.AddrLen], delAddr.Bytes()) - copy(key[offset+v1auth.AddrLen:offset+2*v1auth.AddrLen], valDstAddr.Bytes()) - - return key -} - -// GetREDByValDstIndexKey gets the index-key for a redelegation, stored by destination-validator-index -// VALUE: none (key rearrangement used) -func GetREDByValDstIndexKey(delAddr sdk.AccAddress, valSrcAddr, valDstAddr sdk.ValAddress) []byte { - REDSToValsDstKey := GetREDsToValDstIndexKey(valDstAddr) - offset := len(REDSToValsDstKey) - - // key is of the form REDSToValsDstKey || delAddr || valSrcAddr - key := make([]byte, len(REDSToValsDstKey)+2*v1auth.AddrLen) - copy(key[0:offset], REDSToValsDstKey) - copy(key[offset:offset+v1auth.AddrLen], delAddr.Bytes()) - copy(key[offset+v1auth.AddrLen:offset+2*v1auth.AddrLen], valSrcAddr.Bytes()) - - return key -} - -// GetREDKeyFromValSrcIndexKey rearranges the ValSrcIndexKey to get the REDKey -func GetREDKeyFromValSrcIndexKey(indexKey []byte) []byte { - // note that first byte is prefix byte - kv.AssertKeyLength(indexKey, 3*v1auth.AddrLen+1) - - valSrcAddr := indexKey[1 : v1auth.AddrLen+1] - delAddr := indexKey[v1auth.AddrLen+1 : 2*v1auth.AddrLen+1] - valDstAddr := indexKey[2*v1auth.AddrLen+1 : 3*v1auth.AddrLen+1] - - return GetREDKey(delAddr, valSrcAddr, valDstAddr) -} - -// GetREDKeyFromValDstIndexKey rearranges the ValDstIndexKey to get the REDKey -func GetREDKeyFromValDstIndexKey(indexKey []byte) []byte { - // note that first byte is prefix byte - kv.AssertKeyLength(indexKey, 3*v1auth.AddrLen+1) - - valDstAddr := indexKey[1 : v1auth.AddrLen+1] - delAddr := indexKey[v1auth.AddrLen+1 : 2*v1auth.AddrLen+1] - valSrcAddr := indexKey[2*v1auth.AddrLen+1 : 3*v1auth.AddrLen+1] - - return GetREDKey(delAddr, valSrcAddr, valDstAddr) -} - -func GetREDsToValDstIndexKey(valDstAddr sdk.ValAddress) []byte { - return append(RedelegationByValDstIndexKey, valDstAddr.Bytes()...) -} - -// GetREDsFromValSrcIndexKey returns a key prefix for indexing a redelegation to -// a source validator. -func GetREDsFromValSrcIndexKey(valSrcAddr sdk.ValAddress) []byte { - return append(RedelegationByValSrcIndexKey, valSrcAddr.Bytes()...) -} - -// GetREDsKey returns a key prefix for indexing a redelegation from a delegator -// address. -func GetREDsKey(delAddr sdk.AccAddress) []byte { - return append(RedelegationKey, delAddr.Bytes()...) -} - -// GetUBDsKey gets the prefix for all unbonding delegations from a delegator -func GetUBDsKey(delAddr sdk.AccAddress) []byte { - return append(UnbondingDelegationKey, delAddr.Bytes()...) -} - -// GetUBDsByValIndexKey gets the prefix keyspace for the indexes of unbonding delegations for a validator -func GetUBDsByValIndexKey(valAddr sdk.ValAddress) []byte { - return append(UnbondingDelegationByValIndexKey, valAddr.Bytes()...) -} - -// GetUnbondingDelegationTimeKey gets the prefix for all unbonding delegations from a delegator -func GetUnbondingDelegationTimeKey(timestamp time.Time) []byte { - bz := sdk.FormatTimeBytes(timestamp) - return append(UnbondingQueueKey, bz...) -} - -// ParseValidatorQueueKey parses the time and height from the given validator queue key. -func ParseValidatorQueueKey(bz []byte) (time.Time, int64, error) { - prefixL := len(ValidatorQueueKey) - if prefix := bz[:prefixL]; !bytes.Equal(prefix, ValidatorQueueKey) { - return time.Time{}, 0, fmt.Errorf("invalid prefix; expected: %X, got: %X", ValidatorQueueKey, prefix) - } - - timeBzL := sdk.BigEndianToUint64(bz[prefixL : prefixL+8]) - ts, err := sdk.ParseTimeBytes(bz[prefixL+8 : prefixL+8+int(timeBzL)]) - if err != nil { - return time.Time{}, 0, err - } - - height := sdk.BigEndianToUint64(bz[prefixL+8+int(timeBzL):]) - - return ts, int64(height), nil -} - -// GetDelegationKey gets the key for delegator bond with validator -// VALUE: staking/Delegation -func GetDelegationKey(delAddr sdk.AccAddress, valAddr sdk.ValAddress) []byte { - return append(GetDelegationsKey(delAddr), valAddr.Bytes()...) -} - -// GetDelegationsKey gets the prefix for a delegator for all validators -func GetDelegationsKey(delAddr sdk.AccAddress) []byte { - return append(DelegationKey, delAddr.Bytes()...) -} - -// GetUBDKey gets the key for an unbonding delegation by delegator and validator addr -// VALUE: staking/UnbondingDelegation -func GetUBDKey(delAddr sdk.AccAddress, valAddr sdk.ValAddress) []byte { - return append( - GetUBDsKey(delAddr.Bytes()), - valAddr.Bytes()...) -} - -// GetUBDByValIndexKey gets the index-key for an unbonding delegation, stored by validator-index -// VALUE: none (key rearrangement used) -func GetUBDByValIndexKey(delAddr sdk.AccAddress, valAddr sdk.ValAddress) []byte { - return append(GetUBDsByValIndexKey(valAddr), delAddr.Bytes()...) -} - -// GetUBDKeyFromValIndexKey rearranges the ValIndexKey to get the UBDKey -func GetUBDKeyFromValIndexKey(indexKey []byte) []byte { - kv.AssertKeyAtLeastLength(indexKey, 2) - addrs := indexKey[1:] // remove prefix bytes - kv.AssertKeyLength(addrs, 2*v1auth.AddrLen) - - kv.AssertKeyAtLeastLength(addrs, v1auth.AddrLen+1) - valAddr := addrs[:v1auth.AddrLen] - delAddr := addrs[v1auth.AddrLen:] - - return GetUBDKey(delAddr, valAddr) -} - -// GetValidatorQueueKey returns the prefix key used for getting a set of unbonding -// validators whose unbonding completion occurs at the given time and height. -func GetValidatorQueueKey(timestamp time.Time, height int64) []byte { - heightBz := sdk.Uint64ToBigEndian(uint64(height)) - timeBz := sdk.FormatTimeBytes(timestamp) - timeBzL := len(timeBz) - prefixL := len(ValidatorQueueKey) - - bz := make([]byte, prefixL+8+timeBzL+8) - - // copy the prefix - copy(bz[:prefixL], ValidatorQueueKey) - - // copy the encoded time bytes length - copy(bz[prefixL:prefixL+8], sdk.Uint64ToBigEndian(uint64(timeBzL))) - - // copy the encoded time bytes - copy(bz[prefixL+8:prefixL+8+timeBzL], timeBz) - - // copy the encoded height - copy(bz[prefixL+8+timeBzL:], heightBz) - - return bz -} - -// GetRedelegationTimeKey returns a key prefix for indexing an unbonding -// redelegation based on a completion time. -func GetRedelegationTimeKey(timestamp time.Time) []byte { - bz := sdk.FormatTimeBytes(timestamp) - return append(RedelegationQueueKey, bz...) -} - -// GetHistoricalInfoKey returns a key prefix for indexing HistoricalInfo objects. -func GetHistoricalInfoKey(height int64) []byte { - return append(HistoricalInfoKey, []byte(strconv.FormatInt(height, 10))...) -} diff --git a/x/staking/migrations/v2/keys.go b/x/staking/migrations/v2/keys.go deleted file mode 100644 index 57ccb0aebeea..000000000000 --- a/x/staking/migrations/v2/keys.go +++ /dev/null @@ -1,15 +0,0 @@ -package v2 - -import "strconv" - -const ( - // ModuleName is the name of the module - ModuleName = "staking" -) - -var HistoricalInfoKey = []byte{0x50} // prefix for the historical info - -// GetHistoricalInfoKey returns a key prefix for indexing HistoricalInfo objects. -func GetHistoricalInfoKey(height int64) []byte { - return append(HistoricalInfoKey, []byte(strconv.FormatInt(height, 10))...) -} diff --git a/x/staking/migrations/v2/store.go b/x/staking/migrations/v2/store.go deleted file mode 100644 index 7b20394eac8a..000000000000 --- a/x/staking/migrations/v2/store.go +++ /dev/null @@ -1,77 +0,0 @@ -package v2 - -import ( - "cosmossdk.io/store/prefix" - storetypes "cosmossdk.io/store/types" - - sdk "github.com/cosmos/cosmos-sdk/types" - "github.com/cosmos/cosmos-sdk/types/address" - v1auth "github.com/cosmos/cosmos-sdk/x/auth/migrations/v1" - v2distribution "github.com/cosmos/cosmos-sdk/x/distribution/migrations/v2" - v1 "github.com/cosmos/cosmos-sdk/x/staking/migrations/v1" - "github.com/cosmos/cosmos-sdk/x/staking/types" -) - -// migratePrefixAddressAddressAddress is a helper function that migrates all keys of format: -// prefix_bytes | address_1_bytes | address_2_bytes | address_3_bytes -// into format: -// prefix_bytes | address_1_len (1 byte) | address_1_bytes | address_2_len (1 byte) | address_2_bytes | address_3_len (1 byte) | address_3_bytes -func migratePrefixAddressAddressAddress(store storetypes.KVStore, prefixBz []byte) { - oldStore := prefix.NewStore(store, prefixBz) - - oldStoreIter := oldStore.Iterator(nil, nil) - defer oldStoreIter.Close() - - for ; oldStoreIter.Valid(); oldStoreIter.Next() { - addr1 := oldStoreIter.Key()[:v1auth.AddrLen] - addr2 := oldStoreIter.Key()[v1auth.AddrLen : 2*v1auth.AddrLen] - addr3 := oldStoreIter.Key()[2*v1auth.AddrLen:] - newStoreKey := append(append(append( - prefixBz, - address.MustLengthPrefix(addr1)...), address.MustLengthPrefix(addr2)...), address.MustLengthPrefix(addr3)..., - ) - - // Set new key on store. Values don't change. - store.Set(newStoreKey, oldStoreIter.Value()) - oldStore.Delete(oldStoreIter.Key()) - } -} - -const powerBytesLen = 8 - -func migrateValidatorsByPowerIndexKey(store storetypes.KVStore) { - oldStore := prefix.NewStore(store, v1.ValidatorsByPowerIndexKey) - - oldStoreIter := oldStore.Iterator(nil, nil) - defer oldStoreIter.Close() - - for ; oldStoreIter.Valid(); oldStoreIter.Next() { - powerBytes := oldStoreIter.Key()[:powerBytesLen] - valAddr := oldStoreIter.Key()[powerBytesLen:] - newStoreKey := append(append(types.ValidatorsByPowerIndexKey, powerBytes...), address.MustLengthPrefix(valAddr)...) - - // Set new key on store. Values don't change. - store.Set(newStoreKey, oldStoreIter.Value()) - oldStore.Delete(oldStoreIter.Key()) - } -} - -// MigrateStore performs in-place store migrations from v0.40 to v0.43. The -// migration includes: -// -// - Setting the Power Reduction param in the paramstore -func MigrateStore(ctx sdk.Context, store storetypes.KVStore) error { - v2distribution.MigratePrefixAddress(store, v1.LastValidatorPowerKey) - v2distribution.MigratePrefixAddress(store, v1.ValidatorsKey) - v2distribution.MigratePrefixAddress(store, v1.ValidatorsByConsAddrKey) - migrateValidatorsByPowerIndexKey(store) - - v2distribution.MigratePrefixAddressAddress(store, v1.DelegationKey) - v2distribution.MigratePrefixAddressAddress(store, v1.UnbondingDelegationKey) - v2distribution.MigratePrefixAddressAddress(store, v1.UnbondingDelegationByValIndexKey) - migratePrefixAddressAddressAddress(store, v1.RedelegationKey) - migratePrefixAddressAddressAddress(store, v1.RedelegationByValSrcIndexKey) - migratePrefixAddressAddressAddress(store, v1.RedelegationByValDstIndexKey) - - return nil -} diff --git a/x/staking/migrations/v2/store_test.go b/x/staking/migrations/v2/store_test.go deleted file mode 100644 index a7a987550d41..000000000000 --- a/x/staking/migrations/v2/store_test.go +++ /dev/null @@ -1,140 +0,0 @@ -package v2_test - -import ( - "bytes" - "testing" - "time" - - "github.com/stretchr/testify/require" - - storetypes "cosmossdk.io/store/types" - - "github.com/cosmos/cosmos-sdk/codec/address" - sdktestutil "github.com/cosmos/cosmos-sdk/testutil" - "github.com/cosmos/cosmos-sdk/testutil/testdata" - sdk "github.com/cosmos/cosmos-sdk/types" - v1 "github.com/cosmos/cosmos-sdk/x/staking/migrations/v1" - v2 "github.com/cosmos/cosmos-sdk/x/staking/migrations/v2" - "github.com/cosmos/cosmos-sdk/x/staking/testutil" - "github.com/cosmos/cosmos-sdk/x/staking/types" -) - -func TestStoreMigration(t *testing.T) { - stakingKey := storetypes.NewKVStoreKey("staking") - tStakingKey := storetypes.NewTransientStoreKey("transient_test") - ctx := sdktestutil.DefaultContext(stakingKey, tStakingKey) - store := ctx.KVStore(stakingKey) - - _, pk1, addr1 := testdata.KeyTestPubAddr() - valAddr1 := sdk.ValAddress(addr1) - val := testutil.NewValidator(t, valAddr1, pk1) - _, _, addr2 := testdata.KeyTestPubAddr() - valAddr2 := sdk.ValAddress(addr2) - _, _, addr3 := testdata.KeyTestPubAddr() - consAddr := sdk.ConsAddress(addr3.String()) - _, _, addr4 := testdata.KeyTestPubAddr() - now := time.Now() - // Use dummy value for all keys. - value := []byte("foo") - - testCases := []struct { - name string - oldKey []byte - newKey []byte - }{ - { - "LastValidatorPowerKey", - v1.GetLastValidatorPowerKey(valAddr1), - types.GetLastValidatorPowerKey(valAddr1), - }, - { - "LastTotalPowerKey", - v1.LastTotalPowerKey, - types.LastTotalPowerKey, - }, - { - "ValidatorsKey", - v1.GetValidatorKey(valAddr1), - types.GetValidatorKey(valAddr1), - }, - { - "ValidatorsByConsAddrKey", - v1.GetValidatorByConsAddrKey(consAddr), - types.GetValidatorByConsAddrKey(consAddr), - }, - { - "ValidatorsByPowerIndexKey", - v1.GetValidatorsByPowerIndexKey(val), - types.GetValidatorsByPowerIndexKey(val, sdk.DefaultPowerReduction, address.NewBech32Codec("cosmosvaloper")), - }, - { - "DelegationKey", - v1.GetDelegationKey(addr4, valAddr1), - types.GetDelegationKey(addr4, valAddr1), - }, - { - "UnbondingDelegationKey", - v1.GetUBDKey(addr4, valAddr1), - types.GetUBDKey(addr4, valAddr1), - }, - { - "UnbondingDelegationByValIndexKey", - v1.GetUBDByValIndexKey(addr4, valAddr1), - types.GetUBDByValIndexKey(addr4, valAddr1), - }, - { - "RedelegationKey", - v1.GetREDKey(addr4, valAddr1, valAddr2), - types.GetREDKey(addr4, valAddr1, valAddr2), - }, - { - "RedelegationByValSrcIndexKey", - v1.GetREDByValSrcIndexKey(addr4, valAddr1, valAddr2), - types.GetREDByValSrcIndexKey(addr4, valAddr1, valAddr2), - }, - { - "RedelegationByValDstIndexKey", - v1.GetREDByValDstIndexKey(addr4, valAddr1, valAddr2), - types.GetREDByValDstIndexKey(addr4, valAddr1, valAddr2), - }, - { - "UnbondingQueueKey", - v1.GetUnbondingDelegationTimeKey(now), - types.GetUnbondingDelegationTimeKey(now), - }, - { - "RedelegationQueueKey", - v1.GetRedelegationTimeKey(now), - types.GetRedelegationTimeKey(now), - }, - { - "ValidatorQueueKey", - v1.GetValidatorQueueKey(now, 4), - types.GetValidatorQueueKey(now, 4), - }, - { - "HistoricalInfoKey", - v1.GetHistoricalInfoKey(4), - v2.GetHistoricalInfoKey(4), - }, - } - - // Set all the old keys to the store - for _, tc := range testCases { - store.Set(tc.oldKey, value) - } - - // Run migrations. - err := v2.MigrateStore(ctx, store) - require.NoError(t, err) - - // Make sure the new keys are set and old keys are deleted. - for _, tc := range testCases { - t.Run(tc.name, func(t *testing.T) { - if !bytes.Equal(tc.oldKey, tc.newKey) { - require.Nil(t, store.Get(tc.oldKey)) - } - require.Equal(t, value, store.Get(tc.newKey)) - }) - } -} diff --git a/x/staking/migrations/v3/json.go b/x/staking/migrations/v3/json.go deleted file mode 100644 index 6c3fef922512..000000000000 --- a/x/staking/migrations/v3/json.go +++ /dev/null @@ -1,13 +0,0 @@ -package v3 - -import "github.com/cosmos/cosmos-sdk/x/staking/types" - -// MigrateJSON accepts exported v0.43 x/staking genesis state and migrates it to -// v0.46 x/staking genesis state. The migration includes: -// -// - Add MinCommissionRate param. -func MigrateJSON(oldState types.GenesisState) (types.GenesisState, error) { - oldState.Params.MinCommissionRate = types.DefaultMinCommissionRate - - return oldState, nil -} diff --git a/x/staking/migrations/v3/json_test.go b/x/staking/migrations/v3/json_test.go deleted file mode 100644 index b72a91d17c00..000000000000 --- a/x/staking/migrations/v3/json_test.go +++ /dev/null @@ -1,57 +0,0 @@ -package v3_test - -import ( - "encoding/json" - "testing" - - "github.com/stretchr/testify/require" - - "github.com/cosmos/cosmos-sdk/client" - moduletestutil "github.com/cosmos/cosmos-sdk/types/module/testutil" - v3 "github.com/cosmos/cosmos-sdk/x/staking/migrations/v3" - "github.com/cosmos/cosmos-sdk/x/staking/types" -) - -func TestMigrateJSON(t *testing.T) { - encodingConfig := moduletestutil.MakeTestEncodingConfig() - clientCtx := client.Context{}. - WithInterfaceRegistry(encodingConfig.InterfaceRegistry). - WithTxConfig(encodingConfig.TxConfig). - WithCodec(encodingConfig.Codec) - - oldState := types.DefaultGenesisState() - - newState, err := v3.MigrateJSON(*oldState) - require.NoError(t, err) - - bz, err := clientCtx.Codec.MarshalJSON(&newState) - require.NoError(t, err) - - // Indent the JSON bz correctly. - var jsonObj map[string]any - err = json.Unmarshal(bz, &jsonObj) - require.NoError(t, err) - indentedBz, err := json.MarshalIndent(jsonObj, "", "\t") - require.NoError(t, err) - - // Make sure about new param MinCommissionRate. - expected := `{ - "delegations": [], - "exported": false, - "last_total_power": "0", - "last_validator_powers": [], - "params": { - "bond_denom": "stake", - "historical_entries": 10000, - "max_entries": 7, - "max_validators": 100, - "min_commission_rate": "0.000000000000000000", - "unbonding_time": "1814400s" - }, - "redelegations": [], - "unbonding_delegations": [], - "validators": [] -}` - - require.Equal(t, expected, string(indentedBz)) -} diff --git a/x/staking/migrations/v3/keys.go b/x/staking/migrations/v3/keys.go deleted file mode 100644 index fd6dd3693a35..000000000000 --- a/x/staking/migrations/v3/keys.go +++ /dev/null @@ -1,6 +0,0 @@ -package v3 - -const ( - // ModuleName is the name of the module - ModuleName = "staking" -) diff --git a/x/staking/migrations/v3/store.go b/x/staking/migrations/v3/store.go deleted file mode 100644 index 5142b95f2e44..000000000000 --- a/x/staking/migrations/v3/store.go +++ /dev/null @@ -1,39 +0,0 @@ -package v3 - -import ( - storetypes "cosmossdk.io/store/types" - - "github.com/cosmos/cosmos-sdk/codec" - sdk "github.com/cosmos/cosmos-sdk/types" - paramtypes "github.com/cosmos/cosmos-sdk/x/params/types" - "github.com/cosmos/cosmos-sdk/x/staking/exported" - "github.com/cosmos/cosmos-sdk/x/staking/types" -) - -// subspace contains the method needed for migrations of the -// legacy Params subspace -type subspace interface { - GetParamSet(ctx sdk.Context, ps paramtypes.ParamSet) - HasKeyTable() bool - WithKeyTable(paramtypes.KeyTable) paramtypes.Subspace - Set(ctx sdk.Context, key []byte, value any) -} - -// MigrateStore performs in-place store migrations from v0.43/v0.44/v0.45 to v0.46. -// The migration includes: -// -// - Setting the MinCommissionRate param in the paramstore -func MigrateStore(ctx sdk.Context, store storetypes.KVStore, cdc codec.BinaryCodec, paramstore exported.Subspace) error { - migrateParamsStore(ctx, paramstore.(subspace)) - - return nil -} - -func migrateParamsStore(ctx sdk.Context, paramstore subspace) { - if paramstore.HasKeyTable() { - paramstore.Set(ctx, types.KeyMinCommissionRate, types.DefaultMinCommissionRate) - } else { - paramstore.WithKeyTable(types.ParamKeyTable()) - paramstore.Set(ctx, types.KeyMinCommissionRate, types.DefaultMinCommissionRate) - } -} diff --git a/x/staking/migrations/v3/store_test.go b/x/staking/migrations/v3/store_test.go deleted file mode 100644 index 96d9af167638..000000000000 --- a/x/staking/migrations/v3/store_test.go +++ /dev/null @@ -1,34 +0,0 @@ -package v3_test - -import ( - "testing" - - "github.com/stretchr/testify/require" - - storetypes "cosmossdk.io/store/types" - - "github.com/cosmos/cosmos-sdk/testutil" - moduletestutil "github.com/cosmos/cosmos-sdk/types/module/testutil" - paramtypes "github.com/cosmos/cosmos-sdk/x/params/types" - v3 "github.com/cosmos/cosmos-sdk/x/staking/migrations/v3" - "github.com/cosmos/cosmos-sdk/x/staking/types" -) - -func TestStoreMigration(t *testing.T) { - encCfg := moduletestutil.MakeTestEncodingConfig() - stakingKey := storetypes.NewKVStoreKey("staking") - tStakingKey := storetypes.NewTransientStoreKey("transient_test") - ctx := testutil.DefaultContext(stakingKey, tStakingKey) - paramstore := paramtypes.NewSubspace(encCfg.Codec, encCfg.Amino, stakingKey, tStakingKey, "staking") - store := ctx.KVStore(stakingKey) - - // Check no params - require.False(t, paramstore.Has(ctx, types.KeyMinCommissionRate)) - - // Run migrations. - err := v3.MigrateStore(ctx, store, encCfg.Codec, paramstore) - require.NoError(t, err) - - // Make sure the new params are set. - require.True(t, paramstore.Has(ctx, types.KeyMinCommissionRate)) -} diff --git a/x/staking/migrations/v4/keys.go b/x/staking/migrations/v4/keys.go deleted file mode 100644 index 77bf41bfa93d..000000000000 --- a/x/staking/migrations/v4/keys.go +++ /dev/null @@ -1,8 +0,0 @@ -package v4 - -const ( - // ModuleName is the name of the module - ModuleName = "staking" -) - -var ParamsKey = []byte{0x51} // prefix for parameters for module x/staking diff --git a/x/staking/migrations/v4/migrations_test.go b/x/staking/migrations/v4/migrations_test.go deleted file mode 100644 index 8f762cdf4cd9..000000000000 --- a/x/staking/migrations/v4/migrations_test.go +++ /dev/null @@ -1,147 +0,0 @@ -package v4_test - -import ( - "testing" - "time" - - "github.com/stretchr/testify/require" - - "cosmossdk.io/math" - storetypes "cosmossdk.io/store/types" - - "github.com/cosmos/cosmos-sdk/codec" - "github.com/cosmos/cosmos-sdk/testutil" - "github.com/cosmos/cosmos-sdk/testutil/sims" - sdk "github.com/cosmos/cosmos-sdk/types" - moduletestutil "github.com/cosmos/cosmos-sdk/types/module/testutil" - paramtypes "github.com/cosmos/cosmos-sdk/x/params/types" - "github.com/cosmos/cosmos-sdk/x/staking" - v4 "github.com/cosmos/cosmos-sdk/x/staking/migrations/v4" - "github.com/cosmos/cosmos-sdk/x/staking/types" -) - -type mockSubspace struct { - ps types.Params -} - -func newMockSubspace(ps types.Params) mockSubspace { - return mockSubspace{ps: ps} -} - -func (ms mockSubspace) GetParamSet(ctx sdk.Context, ps paramtypes.ParamSet) { - *ps.(*types.Params) = ms.ps -} - -func TestMigrate(t *testing.T) { - cdc := moduletestutil.MakeTestEncodingConfig(staking.AppModuleBasic{}).Codec - - storeKey := storetypes.NewKVStoreKey(v4.ModuleName) - tKey := storetypes.NewTransientStoreKey("transient_test") - ctx := testutil.DefaultContext(storeKey, tKey) - store := ctx.KVStore(storeKey) - duplicateCreationHeight := int64(1) - - accAddrs := sims.CreateIncrementalAccounts(1) - accAddr := accAddrs[0] - - valAddrs := sims.ConvertAddrsToValAddrs(accAddrs) - valAddr := valAddrs[0] - - // creating 10 ubdEntries with same height and 10 ubdEntries with different creation height - err := createOldStateUnbonding(t, duplicateCreationHeight, valAddr, accAddr, cdc, store) - require.NoError(t, err) - - legacySubspace := newMockSubspace(types.DefaultParams()) - - testCases := []struct { - name string - doMigration bool - }{ - { - name: "without state migration", - doMigration: false, - }, - { - name: "with state migration", - doMigration: true, - }, - } - - for _, tc := range testCases { - t.Run(tc.name, func(t *testing.T) { - if tc.doMigration { - require.NoError(t, v4.MigrateStore(ctx, store, cdc, legacySubspace)) - } - - ubd := getUBD(t, accAddr, valAddr, store, cdc) - if tc.doMigration { - var res types.Params - bz := store.Get(v4.ParamsKey) - require.NoError(t, cdc.Unmarshal(bz, &res)) - require.Equal(t, legacySubspace.ps, res) - - // checking the updated balance for duplicateCreationHeight - for _, ubdEntry := range ubd.Entries { - if ubdEntry.CreationHeight == duplicateCreationHeight { - require.Equal(t, math.NewInt(100*10), ubdEntry.Balance) - break - } - } - require.Equal(t, 11, len(ubd.Entries)) - } else { - require.Equal(t, true, true) - require.Equal(t, 20, len(ubd.Entries)) - } - }) - } -} - -// createOldStateUnbonding will create the ubd entries with duplicate heights -// 10 duplicate heights and 10 unique ubd with creation height -func createOldStateUnbonding(t *testing.T, creationHeight int64, valAddr sdk.ValAddress, accAddr sdk.AccAddress, cdc codec.BinaryCodec, store storetypes.KVStore) error { - t.Helper() - - unbondBalance := math.NewInt(100) - completionTime := time.Now() - ubdEntries := make([]types.UnbondingDelegationEntry, 0, 10) - - for i := int64(0); i < 10; i++ { - ubdEntry := types.UnbondingDelegationEntry{ - CreationHeight: creationHeight, - Balance: unbondBalance, - InitialBalance: unbondBalance, - CompletionTime: completionTime, - } - ubdEntries = append(ubdEntries, ubdEntry) - // creating more entries for testing the creation_heights - ubdEntry.CreationHeight = i + 2 - ubdEntry.CompletionTime = completionTime.Add(time.Minute * 10) - ubdEntries = append(ubdEntries, ubdEntry) - } - - ubd := types.UnbondingDelegation{ - ValidatorAddress: valAddr.String(), - DelegatorAddress: accAddr.String(), - Entries: ubdEntries, - } - - // set the unbond delegation with validator and delegator - bz := types.MustMarshalUBD(cdc, ubd) - key := getUBDKey(accAddr, valAddr) - store.Set(key, bz) - return nil -} - -func getUBD(t *testing.T, accAddr sdk.AccAddress, valAddr sdk.ValAddress, store storetypes.KVStore, cdc codec.BinaryCodec) types.UnbondingDelegation { - t.Helper() - - // get the unbonding delegations - var ubdRes types.UnbondingDelegation - ubdbz := store.Get(getUBDKey(accAddr, valAddr)) - require.NoError(t, cdc.Unmarshal(ubdbz, &ubdRes)) - return ubdRes -} - -func getUBDKey(accAddr sdk.AccAddress, valAddr sdk.ValAddress) []byte { - return types.GetUBDKey(accAddr, valAddr) -} diff --git a/x/staking/migrations/v4/store.go b/x/staking/migrations/v4/store.go deleted file mode 100644 index 945c2b1f9f2f..000000000000 --- a/x/staking/migrations/v4/store.go +++ /dev/null @@ -1,98 +0,0 @@ -package v4 - -import ( - "slices" - - sdkmath "cosmossdk.io/math" - storetypes "cosmossdk.io/store/types" - - "github.com/cosmos/cosmos-sdk/codec" - sdk "github.com/cosmos/cosmos-sdk/types" - "github.com/cosmos/cosmos-sdk/x/staking/exported" - "github.com/cosmos/cosmos-sdk/x/staking/types" -) - -// MigrateStore performs in-place store migrations from v3 to v4. -func MigrateStore(ctx sdk.Context, store storetypes.KVStore, cdc codec.BinaryCodec, legacySubspace exported.Subspace) error { - // migrate params - if err := migrateParams(ctx, store, cdc, legacySubspace); err != nil { - return err - } - - // migrate unbonding delegations - if err := migrateUBDEntries(ctx, store, cdc, legacySubspace); err != nil { - return err - } - - return nil -} - -// migrateParams will set the params to store from legacySubspace -func migrateParams(ctx sdk.Context, store storetypes.KVStore, cdc codec.BinaryCodec, legacySubspace exported.Subspace) error { - var legacyParams types.Params - legacySubspace.GetParamSet(ctx, &legacyParams) - - if err := legacyParams.Validate(); err != nil { - return err - } - - bz := cdc.MustMarshal(&legacyParams) - store.Set(types.ParamsKey, bz) - return nil -} - -// migrateUBDEntries will remove the ubdEntries with same creation_height -// and create a new ubdEntry with updated balance and initial_balance -func migrateUBDEntries(ctx sdk.Context, store storetypes.KVStore, cdc codec.BinaryCodec, legacySubspace exported.Subspace) error { - iterator := storetypes.KVStorePrefixIterator(store, types.UnbondingDelegationKey) - defer iterator.Close() - - for ; iterator.Valid(); iterator.Next() { - ubd := types.MustUnmarshalUBD(cdc, iterator.Value()) - - entriesAtSameCreationHeight := make(map[int64][]types.UnbondingDelegationEntry) - for _, ubdEntry := range ubd.Entries { - entriesAtSameCreationHeight[ubdEntry.CreationHeight] = append(entriesAtSameCreationHeight[ubdEntry.CreationHeight], ubdEntry) - } - - creationHeights := make([]int64, 0, len(entriesAtSameCreationHeight)) - for k := range entriesAtSameCreationHeight { - creationHeights = append(creationHeights, k) - } - slices.Sort(creationHeights) - ubd.Entries = make([]types.UnbondingDelegationEntry, 0, len(creationHeights)) - - for _, h := range creationHeights { - ubdEntry := types.UnbondingDelegationEntry{ - Balance: sdkmath.ZeroInt(), - InitialBalance: sdkmath.ZeroInt(), - } - for _, entry := range entriesAtSameCreationHeight[h] { - ubdEntry.Balance = ubdEntry.Balance.Add(entry.Balance) - ubdEntry.InitialBalance = ubdEntry.InitialBalance.Add(entry.InitialBalance) - ubdEntry.CreationHeight = entry.CreationHeight - ubdEntry.CompletionTime = entry.CompletionTime - } - ubd.Entries = append(ubd.Entries, ubdEntry) - } - - // set the new ubd to the store - setUBDToStore(ctx, store, cdc, ubd) - } - return nil -} - -func setUBDToStore(ctx sdk.Context, store storetypes.KVStore, cdc codec.BinaryCodec, ubd types.UnbondingDelegation) { - delegatorAddress := sdk.MustAccAddressFromBech32(ubd.DelegatorAddress) - - bz := types.MustMarshalUBD(cdc, ubd) - - addr, err := sdk.ValAddressFromBech32(ubd.ValidatorAddress) - if err != nil { - panic(err) - } - - key := types.GetUBDKey(delegatorAddress, addr) - - store.Set(key, bz) -} diff --git a/x/staking/migrations/v5/keys.go b/x/staking/migrations/v5/keys.go deleted file mode 100644 index 653aeb625639..000000000000 --- a/x/staking/migrations/v5/keys.go +++ /dev/null @@ -1,73 +0,0 @@ -package v5 - -import ( - "bytes" - "encoding/binary" - "fmt" - - sdk "github.com/cosmos/cosmos-sdk/types" - "github.com/cosmos/cosmos-sdk/types/address" -) - -const ( - // ModuleName is the name of the module - ModuleName = "staking" -) - -var ( - DelegationKey = []byte{0x31} // key for a delegation - HistoricalInfoKey = []byte{0x50} // prefix for the historical info - DelegationByValIndexKey = []byte{0x71} // key for delegations by a validator -) - -// ParseDelegationKey parses given key and returns delegator, validator address bytes -func ParseDelegationKey(bz []byte) (sdk.AccAddress, sdk.ValAddress, error) { - prefixLength := len(DelegationKey) - if prefix := bz[:prefixLength]; !bytes.Equal(prefix, DelegationKey) { - return nil, nil, fmt.Errorf("invalid prefix; expected: %X, got: %x", DelegationKey, prefix) - } - - bz = bz[prefixLength:] // remove the prefix byte - if len(bz) == 0 { - return nil, nil, fmt.Errorf("no bytes left to parse: %X", bz) - } - - delAddrLen := bz[0] - bz = bz[1:] // remove the length byte of delegator address. - if len(bz) == 0 { - return nil, nil, fmt.Errorf("no bytes left to parse delegator address: %X", bz) - } - - del := bz[:int(delAddrLen)] - bz = bz[int(delAddrLen):] // remove the length byte of a delegator address - if len(bz) == 0 { - return nil, nil, fmt.Errorf("no bytes left to parse delegator address: %X", bz) - } - - bz = bz[1:] // remove the validator address bytes. - if len(bz) == 0 { - return nil, nil, fmt.Errorf("no bytes left to parse validator address: %X", bz) - } - - val := bz - - return del, val, nil -} - -// GetHistoricalInfoKey returns a key prefix for indexing HistoricalInfo objects. -func GetHistoricalInfoKey(height int64) []byte { - heightBytes := make([]byte, 8) - binary.BigEndian.PutUint64(heightBytes, uint64(height)) - return append(HistoricalInfoKey, heightBytes...) -} - -// GetDelegationsByValPrefixKey builds a prefix key bytes with the given validator address bytes. -func GetDelegationsByValPrefixKey(valAddr sdk.ValAddress) []byte { - return append(DelegationByValIndexKey, address.MustLengthPrefix(valAddr)...) -} - -// GetDelegationsByValKey creates the key for delegations by validator address -// VALUE: staking/Delegation -func GetDelegationsByValKey(valAddr sdk.ValAddress, delAddr sdk.AccAddress) []byte { - return append(GetDelegationsByValPrefixKey(valAddr), delAddr...) -} diff --git a/x/staking/migrations/v5/migrations_test.go b/x/staking/migrations/v5/migrations_test.go deleted file mode 100644 index 6d00e8068742..000000000000 --- a/x/staking/migrations/v5/migrations_test.go +++ /dev/null @@ -1,131 +0,0 @@ -package v5_test - -import ( - "math" - "math/rand" - "testing" - "time" - - cmtproto "github.com/cometbft/cometbft/proto/tendermint/types" - "github.com/stretchr/testify/assert" - "github.com/stretchr/testify/require" - - sdkmath "cosmossdk.io/math" - storetypes "cosmossdk.io/store/types" - - "github.com/cosmos/cosmos-sdk/codec" - "github.com/cosmos/cosmos-sdk/testutil" - "github.com/cosmos/cosmos-sdk/testutil/sims" - sdk "github.com/cosmos/cosmos-sdk/types" - moduletestutil "github.com/cosmos/cosmos-sdk/types/module/testutil" - "github.com/cosmos/cosmos-sdk/x/staking" - v2 "github.com/cosmos/cosmos-sdk/x/staking/migrations/v2" - v5 "github.com/cosmos/cosmos-sdk/x/staking/migrations/v5" - stakingtypes "github.com/cosmos/cosmos-sdk/x/staking/types" -) - -func TestHistoricalKeysMigration(t *testing.T) { - storeKey := storetypes.NewKVStoreKey("staking") - tKey := storetypes.NewTransientStoreKey("transient_test") - ctx := testutil.DefaultContext(storeKey, tKey) - store := ctx.KVStore(storeKey) - - type testCase struct { - oldKey, newKey []byte - historicalInfo []byte - } - - testCases := make(map[int64]testCase) - - // edge cases - testCases[0], testCases[1], testCases[math.MaxInt32] = testCase{}, testCase{}, testCase{} - - // random cases - seed := time.Now().UnixNano() - r := rand.New(rand.NewSource(seed)) - for range 10 { - height := r.Intn(math.MaxInt32-2) + 2 - - testCases[int64(height)] = testCase{} - } - - cdc := moduletestutil.MakeTestEncodingConfig().Codec - for height := range testCases { - testCases[height] = testCase{ - oldKey: v2.GetHistoricalInfoKey(height), - newKey: v5.GetHistoricalInfoKey(height), - historicalInfo: cdc.MustMarshal(createHistoricalInfo(height, "testChainID")), - } - } - - // populate store using old key format - for _, tc := range testCases { - store.Set(tc.oldKey, tc.historicalInfo) - } - - // migrate store to new key format - require.NoErrorf(t, v5.MigrateStore(ctx, store, cdc), "v5.MigrateStore failed, seed: %d", seed) - - // check results - for _, tc := range testCases { - require.Nilf(t, store.Get(tc.oldKey), "old key should be deleted, seed: %d", seed) - require.NotNilf(t, store.Get(tc.newKey), "new key should be created, seed: %d", seed) - require.Equalf(t, tc.historicalInfo, store.Get(tc.newKey), "seed: %d", seed) - } -} - -func createHistoricalInfo(height int64, chainID string) *stakingtypes.HistoricalInfo { - return &stakingtypes.HistoricalInfo{Header: cmtproto.Header{ChainID: chainID, Height: height}} -} - -func TestDelegationsByValidatorMigrations(t *testing.T) { - cdc := moduletestutil.MakeTestEncodingConfig(staking.AppModuleBasic{}).Codec - storeKey := storetypes.NewKVStoreKey(v5.ModuleName) - tKey := storetypes.NewTransientStoreKey("transient_test") - ctx := testutil.DefaultContext(storeKey, tKey) - store := ctx.KVStore(storeKey) - - accAddrs := sims.CreateIncrementalAccounts(11) - valAddrs := sims.ConvertAddrsToValAddrs(accAddrs[0:1]) - var addedDels []stakingtypes.Delegation - - for i := 1; i < 11; i++ { - del1 := stakingtypes.NewDelegation(accAddrs[i].String(), valAddrs[0].String(), sdkmath.LegacyNewDec(100)) - store.Set(stakingtypes.GetDelegationKey(accAddrs[i], valAddrs[0]), stakingtypes.MustMarshalDelegation(cdc, del1)) - addedDels = append(addedDels, del1) - } - - // before migration the state of delegations by val index should be empty - dels := getValDelegations(ctx, cdc, storeKey, valAddrs[0]) - assert.Len(t, dels, 0) - - err := v5.MigrateStore(ctx, store, cdc) - assert.NoError(t, err) - - // after migration the state of delegations by val index should not be empty - dels = getValDelegations(ctx, cdc, storeKey, valAddrs[0]) - assert.Len(t, dels, len(addedDels)) - assert.Equal(t, addedDels, dels) -} - -func getValDelegations(ctx sdk.Context, cdc codec.Codec, storeKey storetypes.StoreKey, valAddr sdk.ValAddress) []stakingtypes.Delegation { - var delegations []stakingtypes.Delegation - - store := ctx.KVStore(storeKey) - iterator := storetypes.KVStorePrefixIterator(store, v5.GetDelegationsByValPrefixKey(valAddr)) - for ; iterator.Valid(); iterator.Next() { - var delegation stakingtypes.Delegation - valAddr, delAddr, err := stakingtypes.ParseDelegationsByValKey(iterator.Key()) - if err != nil { - panic(err) - } - - bz := store.Get(stakingtypes.GetDelegationKey(delAddr, valAddr)) - - cdc.MustUnmarshal(bz, &delegation) - - delegations = append(delegations, delegation) - } - - return delegations -} diff --git a/x/staking/migrations/v5/store.go b/x/staking/migrations/v5/store.go deleted file mode 100644 index a572d35d8f9b..000000000000 --- a/x/staking/migrations/v5/store.go +++ /dev/null @@ -1,66 +0,0 @@ -package v5 - -import ( - "fmt" - "strconv" - - "cosmossdk.io/log" - "cosmossdk.io/store/prefix" - storetypes "cosmossdk.io/store/types" - - "github.com/cosmos/cosmos-sdk/codec" - sdk "github.com/cosmos/cosmos-sdk/types" -) - -func migrateDelegationsByValidatorIndex(ctx sdk.Context, store storetypes.KVStore, cdc codec.BinaryCodec) error { - iterator := storetypes.KVStorePrefixIterator(store, DelegationKey) - - for ; iterator.Valid(); iterator.Next() { - key := iterator.Key() - del, val, err := ParseDelegationKey(key) - if err != nil { - return err - } - - store.Set(GetDelegationsByValKey(val, del), []byte{}) - } - - return nil -} - -// MigrateStore performs in-place store migrations from v4 to v5. -func MigrateStore(ctx sdk.Context, store storetypes.KVStore, cdc codec.BinaryCodec) error { - if err := migrateDelegationsByValidatorIndex(ctx, store, cdc); err != nil { - return err - } - return migrateHistoricalInfoKeys(store, ctx.Logger()) -} - -// migrateHistoricalInfoKeys migrate HistoricalInfo keys to binary format -func migrateHistoricalInfoKeys(store storetypes.KVStore, logger log.Logger) error { - // old key is of format: - // prefix (0x50) || heightBytes (string representation of height in 10 base) - // new key is of format: - // prefix (0x50) || heightBytes (byte array representation using big-endian byte order) - oldStore := prefix.NewStore(store, HistoricalInfoKey) - - oldStoreIter := oldStore.Iterator(nil, nil) - defer sdk.LogDeferred(logger, func() error { return oldStoreIter.Close() }) - - for ; oldStoreIter.Valid(); oldStoreIter.Next() { - strHeight := oldStoreIter.Key() - - intHeight, err := strconv.ParseInt(string(strHeight), 10, 64) - if err != nil { - return fmt.Errorf("can't parse height from key %q to int64: %w", strHeight, err) - } - - newStoreKey := GetHistoricalInfoKey(intHeight) - - // Set new key on store. Values don't change. - store.Set(newStoreKey, oldStoreIter.Value()) - oldStore.Delete(oldStoreIter.Key()) - } - - return nil -} diff --git a/x/staking/module.go b/x/staking/module.go index 427ff607afae..6dcdfbe758ad 100644 --- a/x/staking/module.go +++ b/x/staking/module.go @@ -28,7 +28,6 @@ import ( authtypes "github.com/cosmos/cosmos-sdk/x/auth/types" govtypes "github.com/cosmos/cosmos-sdk/x/gov/types" "github.com/cosmos/cosmos-sdk/x/staking/client/cli" - "github.com/cosmos/cosmos-sdk/x/staking/exported" "github.com/cosmos/cosmos-sdk/x/staking/keeper" "github.com/cosmos/cosmos-sdk/x/staking/simulation" "github.com/cosmos/cosmos-sdk/x/staking/types" @@ -104,9 +103,6 @@ type AppModule struct { keeper *keeper.Keeper accountKeeper types.AccountKeeper bankKeeper types.BankKeeper - - // legacySubspace is used solely for migration of x/params managed parameters - legacySubspace exported.Subspace } // NewAppModule creates a new AppModule object @@ -115,14 +111,12 @@ func NewAppModule( keeper *keeper.Keeper, ak types.AccountKeeper, bk types.BankKeeper, - ls exported.Subspace, ) AppModule { return AppModule{ AppModuleBasic: AppModuleBasic{cdc: cdc}, keeper: keeper, accountKeeper: ak, bankKeeper: bk, - legacySubspace: ls, } } @@ -138,19 +132,7 @@ func (am AppModule) RegisterServices(cfg module.Configurator) { querier := keeper.Querier{Keeper: am.keeper} types.RegisterQueryServer(cfg.QueryServer(), querier) - m := keeper.NewMigrator(am.keeper, am.legacySubspace) - if err := cfg.RegisterMigration(types.ModuleName, 1, m.Migrate1to2); err != nil { - panic(fmt.Sprintf("failed to migrate x/%s from version 1 to 2: %v", types.ModuleName, err)) - } - if err := cfg.RegisterMigration(types.ModuleName, 2, m.Migrate2to3); err != nil { - panic(fmt.Sprintf("failed to migrate x/%s from version 2 to 3: %v", types.ModuleName, err)) - } - if err := cfg.RegisterMigration(types.ModuleName, 3, m.Migrate3to4); err != nil { - panic(fmt.Sprintf("failed to migrate x/%s from version 3 to 4: %v", types.ModuleName, err)) - } - if err := cfg.RegisterMigration(types.ModuleName, 4, m.Migrate4to5); err != nil { - panic(fmt.Sprintf("failed to migrate x/%s from version 4 to 5: %v", types.ModuleName, err)) - } + _ = keeper.NewMigrator(am.keeper) } // InitGenesis performs genesis initialization for the staking module. @@ -200,9 +182,6 @@ type ModuleInputs struct { BankKeeper types.BankKeeper Cdc codec.Codec StoreService store.KVStoreService - - // LegacySubspace is used solely for migration of x/params managed parameters - LegacySubspace exported.Subspace `optional:"true"` } // ModuleOutputs contains Dependency Injection Outputs @@ -229,7 +208,7 @@ func ProvideModule(in ModuleInputs) ModuleOutputs { in.ValidatorAddressCodec, in.ConsensusAddressCodec, ) - m := NewAppModule(in.Cdc, k, in.AccountKeeper, in.BankKeeper, in.LegacySubspace) + m := NewAppModule(in.Cdc, k, in.AccountKeeper, in.BankKeeper) return ModuleOutputs{StakingKeeper: k, Module: m} } diff --git a/x/staking/testutil/app_config.go b/x/staking/testutil/app_config.go index 4f9118e395ce..4bebab4a670a 100644 --- a/x/staking/testutil/app_config.go +++ b/x/staking/testutil/app_config.go @@ -9,7 +9,6 @@ import ( _ "github.com/cosmos/cosmos-sdk/x/distribution" // import as blank for app wiring _ "github.com/cosmos/cosmos-sdk/x/genutil" // import as blank for app wiring _ "github.com/cosmos/cosmos-sdk/x/mint" // import as blank for app wiring - _ "github.com/cosmos/cosmos-sdk/x/params" // import as blank for app wiring _ "github.com/cosmos/cosmos-sdk/x/slashing" // import as blank for app wiring _ "github.com/cosmos/cosmos-sdk/x/staking" // import as blank for app wiring ) @@ -20,7 +19,6 @@ var AppConfig = configurator.NewAppConfig( configurator.StakingModule(), configurator.TxModule(), configurator.ConsensusModule(), - configurator.ParamsModule(), configurator.GenutilModule(), configurator.MintModule(), configurator.DistributionModule(), diff --git a/x/staking/types/params_legacy.go b/x/staking/types/params_legacy.go deleted file mode 100644 index f2ab55624976..000000000000 --- a/x/staking/types/params_legacy.go +++ /dev/null @@ -1,32 +0,0 @@ -package types - -import paramtypes "github.com/cosmos/cosmos-sdk/x/params/types" - -var ( - KeyUnbondingTime = []byte("UnbondingTime") - KeyMaxValidators = []byte("MaxValidators") - KeyMaxEntries = []byte("MaxEntries") - KeyBondDenom = []byte("BondDenom") - KeyHistoricalEntries = []byte("HistoricalEntries") - KeyMinCommissionRate = []byte("MinCommissionRate") -) - -var _ paramtypes.ParamSet = (*Params)(nil) - -// Deprecated: now params can be accessed on key `0x51` on the staking store. -// ParamTable for staking module -func ParamKeyTable() paramtypes.KeyTable { - return paramtypes.NewKeyTable().RegisterParamSet(&Params{}) -} - -// Deprecated: Implements params.ParamSet -func (p *Params) ParamSetPairs() paramtypes.ParamSetPairs { - return paramtypes.ParamSetPairs{ - paramtypes.NewParamSetPair(KeyUnbondingTime, &p.UnbondingTime, validateUnbondingTime), - paramtypes.NewParamSetPair(KeyMaxValidators, &p.MaxValidators, validateMaxValidators), - paramtypes.NewParamSetPair(KeyMaxEntries, &p.MaxEntries, validateMaxEntries), - paramtypes.NewParamSetPair(KeyHistoricalEntries, &p.HistoricalEntries, validateHistoricalEntries), - paramtypes.NewParamSetPair(KeyBondDenom, &p.BondDenom, validateBondDenom), - paramtypes.NewParamSetPair(KeyMinCommissionRate, &p.MinCommissionRate, validateMinCommissionRate), - } -}