From 5fbc85eaa6f65dda59efeabcd0fd049d1e162521 Mon Sep 17 00:00:00 2001 From: Aaron Craelius Date: Tue, 1 Jun 2021 17:34:22 -0400 Subject: [PATCH 01/24] feat: add minimal dependency-injection based app.go wiring --- docs/core/proto-docs.md | 52 ++ proto/cosmos/auth/module/v1/module.proto | 21 + x/auth/module/module.go | 83 +++ x/auth/module/module.pb.go | 624 +++++++++++++++++++++++ x/auth/types/account.go | 4 + x/auth/types/keeper.go | 21 + 6 files changed, 805 insertions(+) create mode 100644 proto/cosmos/auth/module/v1/module.proto create mode 100644 x/auth/module/module.go create mode 100644 x/auth/module/module.pb.go create mode 100644 x/auth/types/keeper.go diff --git a/docs/core/proto-docs.md b/docs/core/proto-docs.md index 4b67f25205a8..cb07fed05418 100644 --- a/docs/core/proto-docs.md +++ b/docs/core/proto-docs.md @@ -4,6 +4,10 @@ ## Table of Contents +- [cosmos/auth/module/v1/module.proto](#cosmos/auth/module/v1/module.proto) + - [Module](#cosmos.auth.module.v1.Module) + - [Permission](#cosmos.auth.module.v1.Permission) + - [cosmos/auth/v1beta1/auth.proto](#cosmos/auth/v1beta1/auth.proto) - [BaseAccount](#cosmos.auth.v1beta1.BaseAccount) - [ModuleAccount](#cosmos.auth.v1beta1.ModuleAccount) @@ -589,6 +593,54 @@ + +

Top

+ +## cosmos/auth/module/v1/module.proto + + + + + +### Module + + + +| Field | Type | Label | Description | +| ----- | ---- | ----- | ----------- | +| `permissions` | [Permission](#cosmos.auth.module.v1.Permission) | repeated | | +| `account_constructor` | [google.protobuf.Any](#google.protobuf.Any) | | account_constructor is an optional AccountI constructor config object that can be provided to override the default BaseAccount constructor. The provided config object must have an `NewAccount() AccountI` method defined. If this is left empty, the default constructor will be used | + + + + + + + + +### Permission + + + +| Field | Type | Label | Description | +| ----- | ---- | ----- | ----------- | +| `address` | [string](#string) | | | +| `permissions` | [string](#string) | repeated | | + + + + + + + + + + + + + + +

Top

diff --git a/proto/cosmos/auth/module/v1/module.proto b/proto/cosmos/auth/module/v1/module.proto new file mode 100644 index 000000000000..50233de83e3f --- /dev/null +++ b/proto/cosmos/auth/module/v1/module.proto @@ -0,0 +1,21 @@ +syntax = "proto3"; +package cosmos.auth.module.v1; + +import "google/protobuf/any.proto"; + +option go_package = "github.com/cosmos/cosmos-sdk/x/auth/module"; + +message Module { + repeated Permission permissions = 1; + + // account_constructor is an optional AccountI constructor config object that can be provided + // to override the default BaseAccount constructor. The provided config object must have + // an `NewAccount() AccountI` method defined. If this is left empty, the default constructor + // will be used + google.protobuf.Any account_constructor = 2; +} + +message Permission { + string address = 1; + repeated string permissions = 2; +} diff --git a/x/auth/module/module.go b/x/auth/module/module.go new file mode 100644 index 000000000000..b4e1c391480c --- /dev/null +++ b/x/auth/module/module.go @@ -0,0 +1,83 @@ +package module + +import ( + "github.com/cosmos/cosmos-sdk/codec" + sdk "github.com/cosmos/cosmos-sdk/types" + "github.com/cosmos/cosmos-sdk/types/module" + "github.com/cosmos/cosmos-sdk/x/auth" + authkeeper "github.com/cosmos/cosmos-sdk/x/auth/keeper" + "github.com/cosmos/cosmos-sdk/x/auth/types" + paramtypes "github.com/cosmos/cosmos-sdk/x/params/types" +) + +type Inputs struct { + Codec codec.Codec + StoreKey sdk.StoreKey + ParamStore paramtypes.Subspace + RandomGenesisAccountsFn types.RandomGenesisAccountsFn +} + +type Outputs struct { + ViewKeeper types.ViewKeeper + Keeper types.Keeper `security:"admin"` +} + +func (m Module) NewAppModule(inputs Inputs) (module.AppModule, Outputs, error) { + newAccFn := func() types.AccountI { + return &types.BaseAccount{} + } + if m.AccountConstructor != nil { + var accCtr types.AccountConstructor + err := inputs.Codec.UnpackAny(m.AccountConstructor, &accCtr) + if err != nil { + return nil, Outputs{}, err + } + newAccFn = func() types.AccountI { + return accCtr.NewAccount() + } + } + + perms := map[string][]string{} + for _, perm := range m.Permissions { + perms[perm.Address] = perm.Permissions + } + + keeper := authkeeper.NewAccountKeeper(inputs.Codec, inputs.StoreKey, inputs.ParamStore, newAccFn, perms) + appMod := auth.NewAppModule(inputs.Codec, keeper, inputs.RandomGenesisAccountsFn) + + return appMod, Outputs{ + ViewKeeper: viewOnlyKeeper{keeper}, + Keeper: keeper, + }, nil +} + +// viewOnlyKeeper wraps the full keeper in a view-only interface which can't be easily type cast to the full keeper interface +type viewOnlyKeeper struct { + k authkeeper.AccountKeeper +} + +func (v viewOnlyKeeper) GetAccount(ctx sdk.Context, addr sdk.AccAddress) types.AccountI { + return v.k.GetAccount(ctx, addr) +} + +func (v viewOnlyKeeper) GetModuleAddress(moduleName string) sdk.AccAddress { + return v.k.GetModuleAddress(moduleName) +} + +func (v viewOnlyKeeper) ValidatePermissions(macc types.ModuleAccountI) error { + return v.k.ValidatePermissions(macc) +} + +func (v viewOnlyKeeper) GetModuleAddressAndPermissions(moduleName string) (addr sdk.AccAddress, permissions []string) { + return v.GetModuleAddressAndPermissions(moduleName) +} + +func (v viewOnlyKeeper) GetModuleAccountAndPermissions(ctx sdk.Context, moduleName string) (types.ModuleAccountI, []string) { + return v.GetModuleAccountAndPermissions(ctx, moduleName) +} + +func (v viewOnlyKeeper) GetModuleAccount(ctx sdk.Context, moduleName string) types.ModuleAccountI { + return v.k.GetModuleAccount(ctx, moduleName) +} + +var _ types.ViewKeeper = viewOnlyKeeper{} diff --git a/x/auth/module/module.pb.go b/x/auth/module/module.pb.go new file mode 100644 index 000000000000..6e8ca4356304 --- /dev/null +++ b/x/auth/module/module.pb.go @@ -0,0 +1,624 @@ +// Code generated by protoc-gen-gogo. DO NOT EDIT. +// source: cosmos/auth/module/v1/module.proto + +package module + +import ( + fmt "fmt" + types "github.com/cosmos/cosmos-sdk/codec/types" + proto "github.com/gogo/protobuf/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 + +type Module struct { + Permissions []*Permission `protobuf:"bytes,1,rep,name=permissions,proto3" json:"permissions,omitempty"` + // account_constructor is an optional AccountI constructor config object that can be provided + // to override the default BaseAccount constructor. The provided config object must have + // an `NewAccount() AccountI` method defined. If this is left empty, the default constructor + // will be used + AccountConstructor *types.Any `protobuf:"bytes,2,opt,name=account_constructor,json=accountConstructor,proto3" json:"account_constructor,omitempty"` +} + +func (m *Module) Reset() { *m = Module{} } +func (m *Module) String() string { return proto.CompactTextString(m) } +func (*Module) ProtoMessage() {} +func (*Module) Descriptor() ([]byte, []int) { + return fileDescriptor_0f7f34be9f8952c0, []int{0} +} +func (m *Module) XXX_Unmarshal(b []byte) error { + return m.Unmarshal(b) +} +func (m *Module) XXX_Marshal(b []byte, deterministic bool) ([]byte, error) { + if deterministic { + return xxx_messageInfo_Module.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 *Module) XXX_Merge(src proto.Message) { + xxx_messageInfo_Module.Merge(m, src) +} +func (m *Module) XXX_Size() int { + return m.Size() +} +func (m *Module) XXX_DiscardUnknown() { + xxx_messageInfo_Module.DiscardUnknown(m) +} + +var xxx_messageInfo_Module proto.InternalMessageInfo + +func (m *Module) GetPermissions() []*Permission { + if m != nil { + return m.Permissions + } + return nil +} + +func (m *Module) GetAccountConstructor() *types.Any { + if m != nil { + return m.AccountConstructor + } + return nil +} + +type Permission struct { + Address string `protobuf:"bytes,1,opt,name=address,proto3" json:"address,omitempty"` + Permissions []string `protobuf:"bytes,2,rep,name=permissions,proto3" json:"permissions,omitempty"` +} + +func (m *Permission) Reset() { *m = Permission{} } +func (m *Permission) String() string { return proto.CompactTextString(m) } +func (*Permission) ProtoMessage() {} +func (*Permission) Descriptor() ([]byte, []int) { + return fileDescriptor_0f7f34be9f8952c0, []int{1} +} +func (m *Permission) XXX_Unmarshal(b []byte) error { + return m.Unmarshal(b) +} +func (m *Permission) XXX_Marshal(b []byte, deterministic bool) ([]byte, error) { + if deterministic { + return xxx_messageInfo_Permission.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 *Permission) XXX_Merge(src proto.Message) { + xxx_messageInfo_Permission.Merge(m, src) +} +func (m *Permission) XXX_Size() int { + return m.Size() +} +func (m *Permission) XXX_DiscardUnknown() { + xxx_messageInfo_Permission.DiscardUnknown(m) +} + +var xxx_messageInfo_Permission proto.InternalMessageInfo + +func (m *Permission) GetAddress() string { + if m != nil { + return m.Address + } + return "" +} + +func (m *Permission) GetPermissions() []string { + if m != nil { + return m.Permissions + } + return nil +} + +func init() { + proto.RegisterType((*Module)(nil), "cosmos.auth.module.v1.Module") + proto.RegisterType((*Permission)(nil), "cosmos.auth.module.v1.Permission") +} + +func init() { + proto.RegisterFile("cosmos/auth/module/v1/module.proto", fileDescriptor_0f7f34be9f8952c0) +} + +var fileDescriptor_0f7f34be9f8952c0 = []byte{ + // 271 bytes of a gzipped FileDescriptorProto + 0x1f, 0x8b, 0x08, 0x00, 0x00, 0x00, 0x00, 0x00, 0x02, 0xff, 0xe2, 0x52, 0x4a, 0xce, 0x2f, 0xce, + 0xcd, 0x2f, 0xd6, 0x4f, 0x2c, 0x2d, 0xc9, 0xd0, 0xcf, 0xcd, 0x4f, 0x29, 0xcd, 0x49, 0xd5, 0x2f, + 0x33, 0x84, 0xb2, 0xf4, 0x0a, 0x8a, 0xf2, 0x4b, 0xf2, 0x85, 0x44, 0x21, 0x6a, 0xf4, 0x40, 0x6a, + 0xf4, 0xa0, 0x32, 0x65, 0x86, 0x52, 0x92, 0xe9, 0xf9, 0xf9, 0xe9, 0x39, 0xa9, 0xfa, 0x60, 0x45, + 0x49, 0xa5, 0x69, 0xfa, 0x89, 0x79, 0x95, 0x10, 0x1d, 0x4a, 0x53, 0x18, 0xb9, 0xd8, 0x7c, 0xc1, + 0x0a, 0x85, 0x9c, 0xb9, 0xb8, 0x0b, 0x52, 0x8b, 0x72, 0x33, 0x8b, 0x8b, 0x33, 0xf3, 0xf3, 0x8a, + 0x25, 0x18, 0x15, 0x98, 0x35, 0xb8, 0x8d, 0x14, 0xf5, 0xb0, 0x1a, 0xa9, 0x17, 0x00, 0x57, 0x19, + 0x84, 0xac, 0x4b, 0xc8, 0x95, 0x4b, 0x38, 0x31, 0x39, 0x39, 0xbf, 0x34, 0xaf, 0x24, 0x3e, 0x39, + 0x3f, 0xaf, 0xb8, 0xa4, 0xa8, 0x34, 0xb9, 0x24, 0xbf, 0x48, 0x82, 0x49, 0x81, 0x51, 0x83, 0xdb, + 0x48, 0x44, 0x0f, 0xe2, 0x10, 0x3d, 0x98, 0x43, 0xf4, 0x1c, 0xf3, 0x2a, 0x83, 0x84, 0xa0, 0x1a, + 0x9c, 0x11, 0xea, 0x95, 0x3c, 0xb8, 0xb8, 0x10, 0x36, 0x08, 0x49, 0x70, 0xb1, 0x27, 0xa6, 0xa4, + 0x14, 0xa5, 0x16, 0x83, 0x5c, 0xc5, 0xa8, 0xc1, 0x19, 0x04, 0xe3, 0x0a, 0x29, 0xa0, 0xba, 0x99, + 0x49, 0x81, 0x59, 0x83, 0x13, 0xc5, 0x41, 0x4e, 0x2e, 0x27, 0x1e, 0xc9, 0x31, 0x5e, 0x78, 0x24, + 0xc7, 0xf8, 0xe0, 0x91, 0x1c, 0xe3, 0x84, 0xc7, 0x72, 0x0c, 0x17, 0x1e, 0xcb, 0x31, 0xdc, 0x78, + 0x2c, 0xc7, 0x10, 0xa5, 0x95, 0x9e, 0x59, 0x92, 0x51, 0x9a, 0xa4, 0x97, 0x9c, 0x9f, 0xab, 0x0f, + 0x0d, 0x5b, 0x08, 0xa5, 0x5b, 0x9c, 0x92, 0xad, 0x5f, 0x81, 0x1c, 0xd0, 0x49, 0x6c, 0x60, 0x17, + 0x1b, 0x03, 0x02, 0x00, 0x00, 0xff, 0xff, 0xf8, 0x35, 0x73, 0x5f, 0x85, 0x01, 0x00, 0x00, +} + +func (m *Module) 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 *Module) MarshalTo(dAtA []byte) (int, error) { + size := m.Size() + return m.MarshalToSizedBuffer(dAtA[:size]) +} + +func (m *Module) MarshalToSizedBuffer(dAtA []byte) (int, error) { + i := len(dAtA) + _ = i + var l int + _ = l + if m.AccountConstructor != nil { + { + size, err := m.AccountConstructor.MarshalToSizedBuffer(dAtA[:i]) + if err != nil { + return 0, err + } + i -= size + i = encodeVarintModule(dAtA, i, uint64(size)) + } + i-- + dAtA[i] = 0x12 + } + if len(m.Permissions) > 0 { + for iNdEx := len(m.Permissions) - 1; iNdEx >= 0; iNdEx-- { + { + size, err := m.Permissions[iNdEx].MarshalToSizedBuffer(dAtA[:i]) + if err != nil { + return 0, err + } + i -= size + i = encodeVarintModule(dAtA, i, uint64(size)) + } + i-- + dAtA[i] = 0xa + } + } + return len(dAtA) - i, nil +} + +func (m *Permission) 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 *Permission) MarshalTo(dAtA []byte) (int, error) { + size := m.Size() + return m.MarshalToSizedBuffer(dAtA[:size]) +} + +func (m *Permission) MarshalToSizedBuffer(dAtA []byte) (int, error) { + i := len(dAtA) + _ = i + var l int + _ = l + if len(m.Permissions) > 0 { + for iNdEx := len(m.Permissions) - 1; iNdEx >= 0; iNdEx-- { + i -= len(m.Permissions[iNdEx]) + copy(dAtA[i:], m.Permissions[iNdEx]) + i = encodeVarintModule(dAtA, i, uint64(len(m.Permissions[iNdEx]))) + i-- + dAtA[i] = 0x12 + } + } + if len(m.Address) > 0 { + i -= len(m.Address) + copy(dAtA[i:], m.Address) + i = encodeVarintModule(dAtA, i, uint64(len(m.Address))) + i-- + dAtA[i] = 0xa + } + return len(dAtA) - i, nil +} + +func encodeVarintModule(dAtA []byte, offset int, v uint64) int { + offset -= sovModule(v) + base := offset + for v >= 1<<7 { + dAtA[offset] = uint8(v&0x7f | 0x80) + v >>= 7 + offset++ + } + dAtA[offset] = uint8(v) + return base +} +func (m *Module) Size() (n int) { + if m == nil { + return 0 + } + var l int + _ = l + if len(m.Permissions) > 0 { + for _, e := range m.Permissions { + l = e.Size() + n += 1 + l + sovModule(uint64(l)) + } + } + if m.AccountConstructor != nil { + l = m.AccountConstructor.Size() + n += 1 + l + sovModule(uint64(l)) + } + return n +} + +func (m *Permission) Size() (n int) { + if m == nil { + return 0 + } + var l int + _ = l + l = len(m.Address) + if l > 0 { + n += 1 + l + sovModule(uint64(l)) + } + if len(m.Permissions) > 0 { + for _, s := range m.Permissions { + l = len(s) + n += 1 + l + sovModule(uint64(l)) + } + } + return n +} + +func sovModule(x uint64) (n int) { + return (math_bits.Len64(x|1) + 6) / 7 +} +func sozModule(x uint64) (n int) { + return sovModule(uint64((x << 1) ^ uint64((int64(x) >> 63)))) +} +func (m *Module) 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 ErrIntOverflowModule + } + 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: Module: wiretype end group for non-group") + } + if fieldNum <= 0 { + return fmt.Errorf("proto: Module: illegal tag %d (wire type %d)", fieldNum, wire) + } + switch fieldNum { + case 1: + if wireType != 2 { + return fmt.Errorf("proto: wrong wireType = %d for field Permissions", wireType) + } + var msglen int + for shift := uint(0); ; shift += 7 { + if shift >= 64 { + return ErrIntOverflowModule + } + if iNdEx >= l { + return io.ErrUnexpectedEOF + } + b := dAtA[iNdEx] + iNdEx++ + msglen |= int(b&0x7F) << shift + if b < 0x80 { + break + } + } + if msglen < 0 { + return ErrInvalidLengthModule + } + postIndex := iNdEx + msglen + if postIndex < 0 { + return ErrInvalidLengthModule + } + if postIndex > l { + return io.ErrUnexpectedEOF + } + m.Permissions = append(m.Permissions, &Permission{}) + if err := m.Permissions[len(m.Permissions)-1].Unmarshal(dAtA[iNdEx:postIndex]); err != nil { + return err + } + iNdEx = postIndex + case 2: + if wireType != 2 { + return fmt.Errorf("proto: wrong wireType = %d for field AccountConstructor", wireType) + } + var msglen int + for shift := uint(0); ; shift += 7 { + if shift >= 64 { + return ErrIntOverflowModule + } + if iNdEx >= l { + return io.ErrUnexpectedEOF + } + b := dAtA[iNdEx] + iNdEx++ + msglen |= int(b&0x7F) << shift + if b < 0x80 { + break + } + } + if msglen < 0 { + return ErrInvalidLengthModule + } + postIndex := iNdEx + msglen + if postIndex < 0 { + return ErrInvalidLengthModule + } + if postIndex > l { + return io.ErrUnexpectedEOF + } + if m.AccountConstructor == nil { + m.AccountConstructor = &types.Any{} + } + if err := m.AccountConstructor.Unmarshal(dAtA[iNdEx:postIndex]); err != nil { + return err + } + iNdEx = postIndex + default: + iNdEx = preIndex + skippy, err := skipModule(dAtA[iNdEx:]) + if err != nil { + return err + } + if (skippy < 0) || (iNdEx+skippy) < 0 { + return ErrInvalidLengthModule + } + if (iNdEx + skippy) > l { + return io.ErrUnexpectedEOF + } + iNdEx += skippy + } + } + + if iNdEx > l { + return io.ErrUnexpectedEOF + } + return nil +} +func (m *Permission) 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 ErrIntOverflowModule + } + 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: Permission: wiretype end group for non-group") + } + if fieldNum <= 0 { + return fmt.Errorf("proto: Permission: illegal tag %d (wire type %d)", fieldNum, wire) + } + switch fieldNum { + case 1: + if wireType != 2 { + return fmt.Errorf("proto: wrong wireType = %d for field Address", wireType) + } + var stringLen uint64 + for shift := uint(0); ; shift += 7 { + if shift >= 64 { + return ErrIntOverflowModule + } + 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 ErrInvalidLengthModule + } + postIndex := iNdEx + intStringLen + if postIndex < 0 { + return ErrInvalidLengthModule + } + if postIndex > l { + return io.ErrUnexpectedEOF + } + m.Address = string(dAtA[iNdEx:postIndex]) + iNdEx = postIndex + case 2: + if wireType != 2 { + return fmt.Errorf("proto: wrong wireType = %d for field Permissions", wireType) + } + var stringLen uint64 + for shift := uint(0); ; shift += 7 { + if shift >= 64 { + return ErrIntOverflowModule + } + 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 ErrInvalidLengthModule + } + postIndex := iNdEx + intStringLen + if postIndex < 0 { + return ErrInvalidLengthModule + } + if postIndex > l { + return io.ErrUnexpectedEOF + } + m.Permissions = append(m.Permissions, string(dAtA[iNdEx:postIndex])) + iNdEx = postIndex + default: + iNdEx = preIndex + skippy, err := skipModule(dAtA[iNdEx:]) + if err != nil { + return err + } + if (skippy < 0) || (iNdEx+skippy) < 0 { + return ErrInvalidLengthModule + } + if (iNdEx + skippy) > l { + return io.ErrUnexpectedEOF + } + iNdEx += skippy + } + } + + if iNdEx > l { + return io.ErrUnexpectedEOF + } + return nil +} +func skipModule(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, ErrIntOverflowModule + } + 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, ErrIntOverflowModule + } + 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, ErrIntOverflowModule + } + 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, ErrInvalidLengthModule + } + iNdEx += length + case 3: + depth++ + case 4: + if depth == 0 { + return 0, ErrUnexpectedEndOfGroupModule + } + depth-- + case 5: + iNdEx += 4 + default: + return 0, fmt.Errorf("proto: illegal wireType %d", wireType) + } + if iNdEx < 0 { + return 0, ErrInvalidLengthModule + } + if depth == 0 { + return iNdEx, nil + } + } + return 0, io.ErrUnexpectedEOF +} + +var ( + ErrInvalidLengthModule = fmt.Errorf("proto: negative length found during unmarshaling") + ErrIntOverflowModule = fmt.Errorf("proto: integer overflow") + ErrUnexpectedEndOfGroupModule = fmt.Errorf("proto: unexpected end of group") +) diff --git a/x/auth/types/account.go b/x/auth/types/account.go index 653f89bcac4a..a51cff5c2b23 100644 --- a/x/auth/types/account.go +++ b/x/auth/types/account.go @@ -360,3 +360,7 @@ type GenesisAccount interface { Validate() error } + +type AccountConstructor interface { + NewAccount() AccountI +} diff --git a/x/auth/types/keeper.go b/x/auth/types/keeper.go new file mode 100644 index 000000000000..b333eab5061f --- /dev/null +++ b/x/auth/types/keeper.go @@ -0,0 +1,21 @@ +package types + +import sdk "github.com/cosmos/cosmos-sdk/types" + +type ViewKeeper interface { + GetAccount(ctx sdk.Context, addr sdk.AccAddress) AccountI + GetModuleAddress(moduleName string) sdk.AccAddress + ValidatePermissions(macc ModuleAccountI) error + GetModuleAddressAndPermissions(moduleName string) (addr sdk.AccAddress, permissions []string) + GetModuleAccountAndPermissions(ctx sdk.Context, moduleName string) (ModuleAccountI, []string) + GetModuleAccount(ctx sdk.Context, moduleName string) ModuleAccountI +} + +type Keeper interface { + ViewKeeper + + NewAccount(sdk.Context, AccountI) AccountI + NewAccountWithAddress(ctx sdk.Context, addr sdk.AccAddress) AccountI + SetAccount(ctx sdk.Context, acc AccountI) + SetModuleAccount(ctx sdk.Context, macc ModuleAccountI) +} From c7be62de6966d506d807ea6705f06462a182a717 Mon Sep 17 00:00:00 2001 From: Aaron Craelius Date: Tue, 1 Jun 2021 17:50:48 -0400 Subject: [PATCH 02/24] add params module wiring --- container/container.go | 5 +++ container/go.mod | 3 ++ container/scope.go | 3 ++ container/struct_args.go | 7 ++++ docs/core/proto-docs.md | 29 +++++++++++++++++ proto/cosmos/params/module/v1/module.proto | 8 +++++ x/auth/module/module.go | 11 +++++-- x/params/module/module.go | 38 ++++++++++++++++++++++ 8 files changed, 101 insertions(+), 3 deletions(-) create mode 100644 container/container.go create mode 100644 container/go.mod create mode 100644 container/scope.go create mode 100644 container/struct_args.go create mode 100644 proto/cosmos/params/module/v1/module.proto create mode 100644 x/params/module/module.go diff --git a/container/container.go b/container/container.go new file mode 100644 index 000000000000..1d09df746495 --- /dev/null +++ b/container/container.go @@ -0,0 +1,5 @@ +package container + +type Registrar interface { + RegisterProvider(fn interface{}) error +} diff --git a/container/go.mod b/container/go.mod new file mode 100644 index 000000000000..5ad6ca3fb3ab --- /dev/null +++ b/container/go.mod @@ -0,0 +1,3 @@ +go 1.15 + +module github.com/cosmos/cosmos-sdk/container diff --git a/container/scope.go b/container/scope.go new file mode 100644 index 000000000000..503ba778ce61 --- /dev/null +++ b/container/scope.go @@ -0,0 +1,3 @@ +package container + +type Scope string diff --git a/container/struct_args.go b/container/struct_args.go new file mode 100644 index 000000000000..fb859df5ea54 --- /dev/null +++ b/container/struct_args.go @@ -0,0 +1,7 @@ +package container + +type StructArgs struct{} + +func (StructArgs) isStructArgs() {} + +type isStructArgs interface{ isStructArgs() } diff --git a/docs/core/proto-docs.md b/docs/core/proto-docs.md index cb07fed05418..edc16d65ccbd 100644 --- a/docs/core/proto-docs.md +++ b/docs/core/proto-docs.md @@ -405,6 +405,9 @@ - [Query](#cosmos.mint.v1beta1.Query) +- [cosmos/params/module/v1/module.proto](#cosmos/params/module/v1/module.proto) + - [Module](#cosmos.params.modulev1beta1.Module) + - [cosmos/params/v1beta1/params.proto](#cosmos/params/v1beta1/params.proto) - [ParamChange](#cosmos.params.v1beta1.ParamChange) - [ParameterChangeProposal](#cosmos.params.v1beta1.ParameterChangeProposal) @@ -5772,6 +5775,32 @@ Query provides defines the gRPC querier service. + +

Top

+ +## cosmos/params/module/v1/module.proto + + + + + +### Module + + + + + + + + + + + + + + + +

Top

diff --git a/proto/cosmos/params/module/v1/module.proto b/proto/cosmos/params/module/v1/module.proto new file mode 100644 index 000000000000..599458e58e52 --- /dev/null +++ b/proto/cosmos/params/module/v1/module.proto @@ -0,0 +1,8 @@ +syntax = "proto3"; +package cosmos.params.modulev1beta1; + +option go_package = "github.com/cosmos/cosmos-sdk/x/params/module"; + +message Module { + +} diff --git a/x/auth/module/module.go b/x/auth/module/module.go index b4e1c391480c..efca6edf12f1 100644 --- a/x/auth/module/module.go +++ b/x/auth/module/module.go @@ -2,6 +2,7 @@ package module import ( "github.com/cosmos/cosmos-sdk/codec" + "github.com/cosmos/cosmos-sdk/container" sdk "github.com/cosmos/cosmos-sdk/types" "github.com/cosmos/cosmos-sdk/types/module" "github.com/cosmos/cosmos-sdk/x/auth" @@ -11,15 +12,19 @@ import ( ) type Inputs struct { + container.StructArgs + Codec codec.Codec - StoreKey sdk.StoreKey + Key *sdk.KVStoreKey ParamStore paramtypes.Subspace RandomGenesisAccountsFn types.RandomGenesisAccountsFn } type Outputs struct { + container.StructArgs + ViewKeeper types.ViewKeeper - Keeper types.Keeper `security:"admin"` + Keeper types.Keeper `security-role:"admin"` } func (m Module) NewAppModule(inputs Inputs) (module.AppModule, Outputs, error) { @@ -42,7 +47,7 @@ func (m Module) NewAppModule(inputs Inputs) (module.AppModule, Outputs, error) { perms[perm.Address] = perm.Permissions } - keeper := authkeeper.NewAccountKeeper(inputs.Codec, inputs.StoreKey, inputs.ParamStore, newAccFn, perms) + keeper := authkeeper.NewAccountKeeper(inputs.Codec, inputs.Key, inputs.ParamStore, newAccFn, perms) appMod := auth.NewAppModule(inputs.Codec, keeper, inputs.RandomGenesisAccountsFn) return appMod, Outputs{ diff --git a/x/params/module/module.go b/x/params/module/module.go new file mode 100644 index 000000000000..a234804102eb --- /dev/null +++ b/x/params/module/module.go @@ -0,0 +1,38 @@ +package module + +import ( + "github.com/cosmos/cosmos-sdk/codec" + "github.com/cosmos/cosmos-sdk/container" + sdk "github.com/cosmos/cosmos-sdk/types" + "github.com/cosmos/cosmos-sdk/types/module" + "github.com/cosmos/cosmos-sdk/x/params" + paramskeeper "github.com/cosmos/cosmos-sdk/x/params/keeper" + "github.com/cosmos/cosmos-sdk/x/params/types" +) + +type Inputs struct { + container.StructArgs + Codec codec.BinaryCodec + LegacyAmino *codec.LegacyAmino + Key *sdk.KVStoreKey + TransientKey *sdk.TransientStoreKey +} + +type Outputs struct { + container.StructArgs + + Keeper paramskeeper.Keeper `security-role:"admin"` +} + +func (m Module) NewAppModule(inputs Inputs) (module.AppModule, Outputs, error) { + keeper := paramskeeper.NewKeeper(inputs.Codec, inputs.LegacyAmino, inputs.Key, inputs.TransientKey) + appMod := params.NewAppModule(keeper) + + return appMod, Outputs{Keeper: keeper}, nil +} + +func (m Module) Provide(registrar container.Registrar) error { + return registrar.RegisterProvider(func(scope container.Scope, keeper paramskeeper.Keeper) types.Subspace { + return keeper.Subspace(string(scope)) + }) +} From 8e0f2e2ea130ca9e5f55b920b442c5377757a2c4 Mon Sep 17 00:00:00 2001 From: Aaron Craelius Date: Tue, 1 Jun 2021 17:51:05 -0400 Subject: [PATCH 03/24] add params module wiring --- x/params/module/module.pb.go | 264 +++++++++++++++++++++++++++++++++++ 1 file changed, 264 insertions(+) create mode 100644 x/params/module/module.pb.go diff --git a/x/params/module/module.pb.go b/x/params/module/module.pb.go new file mode 100644 index 000000000000..fdf0567ca53f --- /dev/null +++ b/x/params/module/module.pb.go @@ -0,0 +1,264 @@ +// Code generated by protoc-gen-gogo. DO NOT EDIT. +// source: cosmos/params/module/v1/module.proto + +package module + +import ( + fmt "fmt" + proto "github.com/gogo/protobuf/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 + +type Module struct { +} + +func (m *Module) Reset() { *m = Module{} } +func (m *Module) String() string { return proto.CompactTextString(m) } +func (*Module) ProtoMessage() {} +func (*Module) Descriptor() ([]byte, []int) { + return fileDescriptor_b0bff310e651d184, []int{0} +} +func (m *Module) XXX_Unmarshal(b []byte) error { + return m.Unmarshal(b) +} +func (m *Module) XXX_Marshal(b []byte, deterministic bool) ([]byte, error) { + if deterministic { + return xxx_messageInfo_Module.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 *Module) XXX_Merge(src proto.Message) { + xxx_messageInfo_Module.Merge(m, src) +} +func (m *Module) XXX_Size() int { + return m.Size() +} +func (m *Module) XXX_DiscardUnknown() { + xxx_messageInfo_Module.DiscardUnknown(m) +} + +var xxx_messageInfo_Module proto.InternalMessageInfo + +func init() { + proto.RegisterType((*Module)(nil), "cosmos.params.modulev1beta1.Module") +} + +func init() { + proto.RegisterFile("cosmos/params/module/v1/module.proto", fileDescriptor_b0bff310e651d184) +} + +var fileDescriptor_b0bff310e651d184 = []byte{ + // 138 bytes of a gzipped FileDescriptorProto + 0x1f, 0x8b, 0x08, 0x00, 0x00, 0x00, 0x00, 0x00, 0x02, 0xff, 0xe2, 0x52, 0x49, 0xce, 0x2f, 0xce, + 0xcd, 0x2f, 0xd6, 0x2f, 0x48, 0x2c, 0x4a, 0xcc, 0x2d, 0xd6, 0xcf, 0xcd, 0x4f, 0x29, 0xcd, 0x49, + 0xd5, 0x2f, 0x33, 0x84, 0xb2, 0xf4, 0x0a, 0x8a, 0xf2, 0x4b, 0xf2, 0x85, 0xa4, 0x21, 0xaa, 0xf4, + 0x20, 0xaa, 0xf4, 0x20, 0x72, 0x65, 0x86, 0x49, 0xa9, 0x25, 0x89, 0x86, 0x4a, 0x1c, 0x5c, 0x6c, + 0xbe, 0x60, 0x01, 0x27, 0xb7, 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, 0xd2, + 0x49, 0xcf, 0x2c, 0xc9, 0x28, 0x4d, 0xd2, 0x4b, 0xce, 0xcf, 0xd5, 0x87, 0xda, 0x08, 0xa1, 0x74, + 0x8b, 0x53, 0xb2, 0xf5, 0x2b, 0x50, 0xad, 0x4f, 0x62, 0x03, 0xdb, 0x6a, 0x0c, 0x08, 0x00, 0x00, + 0xff, 0xff, 0x81, 0xbe, 0x90, 0x03, 0x9d, 0x00, 0x00, 0x00, +} + +func (m *Module) 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 *Module) MarshalTo(dAtA []byte) (int, error) { + size := m.Size() + return m.MarshalToSizedBuffer(dAtA[:size]) +} + +func (m *Module) MarshalToSizedBuffer(dAtA []byte) (int, error) { + i := len(dAtA) + _ = i + var l int + _ = l + return len(dAtA) - i, nil +} + +func encodeVarintModule(dAtA []byte, offset int, v uint64) int { + offset -= sovModule(v) + base := offset + for v >= 1<<7 { + dAtA[offset] = uint8(v&0x7f | 0x80) + v >>= 7 + offset++ + } + dAtA[offset] = uint8(v) + return base +} +func (m *Module) Size() (n int) { + if m == nil { + return 0 + } + var l int + _ = l + return n +} + +func sovModule(x uint64) (n int) { + return (math_bits.Len64(x|1) + 6) / 7 +} +func sozModule(x uint64) (n int) { + return sovModule(uint64((x << 1) ^ uint64((int64(x) >> 63)))) +} +func (m *Module) 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 ErrIntOverflowModule + } + 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: Module: wiretype end group for non-group") + } + if fieldNum <= 0 { + return fmt.Errorf("proto: Module: illegal tag %d (wire type %d)", fieldNum, wire) + } + switch fieldNum { + default: + iNdEx = preIndex + skippy, err := skipModule(dAtA[iNdEx:]) + if err != nil { + return err + } + if (skippy < 0) || (iNdEx+skippy) < 0 { + return ErrInvalidLengthModule + } + if (iNdEx + skippy) > l { + return io.ErrUnexpectedEOF + } + iNdEx += skippy + } + } + + if iNdEx > l { + return io.ErrUnexpectedEOF + } + return nil +} +func skipModule(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, ErrIntOverflowModule + } + 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, ErrIntOverflowModule + } + 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, ErrIntOverflowModule + } + 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, ErrInvalidLengthModule + } + iNdEx += length + case 3: + depth++ + case 4: + if depth == 0 { + return 0, ErrUnexpectedEndOfGroupModule + } + depth-- + case 5: + iNdEx += 4 + default: + return 0, fmt.Errorf("proto: illegal wireType %d", wireType) + } + if iNdEx < 0 { + return 0, ErrInvalidLengthModule + } + if depth == 0 { + return iNdEx, nil + } + } + return 0, io.ErrUnexpectedEOF +} + +var ( + ErrInvalidLengthModule = fmt.Errorf("proto: negative length found during unmarshaling") + ErrIntOverflowModule = fmt.Errorf("proto: integer overflow") + ErrUnexpectedEndOfGroupModule = fmt.Errorf("proto: unexpected end of group") +) From 145a0efe038536f5066656c42a773aa37660e8c4 Mon Sep 17 00:00:00 2001 From: Aaron Craelius Date: Tue, 1 Jun 2021 21:13:03 -0400 Subject: [PATCH 04/24] WIP --- app/app.go | 269 +++++++++++ app/app_provider.go | 162 +++++++ app/cli/run.go | 178 +++++++ app/config.pb.go | 561 +++++++++++++++++++++++ app/decode.go | 34 ++ container/container.go | 17 +- container/registrar.go | 5 + docs/core/proto-docs.md | 108 +++++ go.mod | 3 + proto/cosmos/app/v1/config.proto | 22 + proto/cosmos/auth/module/v1/module.proto | 6 + proto/cosmos/bank/module/v1/module.proto | 10 + simapp/v2/app.go | 25 + simapp/v2/app.yaml | 7 + x/auth/module/module.go | 44 +- x/auth/module/module.pb.go | 341 +++++++++++++- x/auth/types/genesis.go | 4 + x/bank/module/module.pb.go | 323 +++++++++++++ x/params/module/module.go | 1 + 19 files changed, 2086 insertions(+), 34 deletions(-) create mode 100644 app/app.go create mode 100644 app/app_provider.go create mode 100644 app/cli/run.go create mode 100644 app/config.pb.go create mode 100644 app/decode.go create mode 100644 container/registrar.go create mode 100644 proto/cosmos/app/v1/config.proto create mode 100644 proto/cosmos/bank/module/v1/module.proto create mode 100644 simapp/v2/app.go create mode 100644 simapp/v2/app.yaml create mode 100644 x/bank/module/module.pb.go diff --git a/app/app.go b/app/app.go new file mode 100644 index 000000000000..efc108fb1908 --- /dev/null +++ b/app/app.go @@ -0,0 +1,269 @@ +package app + +import ( + "github.com/cosmos/cosmos-sdk/types/module" + + sdk "github.com/cosmos/cosmos-sdk/types" + + "github.com/cosmos/cosmos-sdk/baseapp" + + grpc1 "github.com/gogo/protobuf/grpc" + abci "github.com/tendermint/tendermint/abci/types" + + "github.com/cosmos/cosmos-sdk/client" + "github.com/cosmos/cosmos-sdk/server/api" + "github.com/cosmos/cosmos-sdk/server/config" + servertypes "github.com/cosmos/cosmos-sdk/server/types" +) + +type app struct { + *baseapp.BaseApp + appProvider *AppProvider + mm module.Manager +} + +var _ servertypes.Application = &app{} + +func (a *app) exportAppStateAndValidators( + forZeroHeight bool, jailAllowedAddrs []string, +) (servertypes.ExportedApp, error) { + //// as if they could withdraw from the start of the next block + //ctx := a.NewContext(true, tmproto.Header{Height: a.LastBlockHeight()}) + // + //// We export at last height + 1, because that's the height at which + //// Tendermint will start InitChain. + //height := a.LastBlockHeight() + 1 + //if forZeroHeight { + // height = 0 + // a.prepForZeroHeightGenesis(ctx, jailAllowedAddrs) + //} + // + //genState := a.mm.ExportGenesis(ctx, a.appProvider.codec) + //appState, err := json.MarshalIndent(genState, "", " ") + //if err != nil { + // return servertypes.ExportedApp{}, err + //} + + panic("TODO") + //validators, err := staking.WriteValidators(ctx, app.stakingKeeper) + //return servertypes.ExportedApp{ + // AppState: appState, + // Validators: validators, + // Height: height, + // ConsensusParams: a.GetConsensusParams(ctx), + //}, err +} + +func (a *app) Info(info abci.RequestInfo) abci.ResponseInfo { + panic("implement me") +} + +func (a *app) SetOption(option abci.RequestSetOption) abci.ResponseSetOption { + panic("implement me") +} + +func (a *app) Query(query abci.RequestQuery) abci.ResponseQuery { + panic("implement me") +} + +func (a *app) CheckTx(checkTx abci.RequestCheckTx) abci.ResponseCheckTx { + panic("implement me") +} + +func (a *app) InitChain(chain abci.RequestInitChain) abci.ResponseInitChain { + panic("implement me") +} + +func (a *app) BeginBlock(block abci.RequestBeginBlock) abci.ResponseBeginBlock { + panic("implement me") +} + +func (a *app) DeliverTx(deliverTx abci.RequestDeliverTx) abci.ResponseDeliverTx { + panic("implement me") +} + +func (a *app) EndBlock(block abci.RequestEndBlock) abci.ResponseEndBlock { + panic("implement me") +} + +func (a *app) Commit() abci.ResponseCommit { + panic("implement me") +} + +func (a *app) ListSnapshots(listSnapshots abci.RequestListSnapshots) abci.ResponseListSnapshots { + panic("implement me") +} + +func (a *app) OfferSnapshot(snapshot abci.RequestOfferSnapshot) abci.ResponseOfferSnapshot { + panic("implement me") +} + +func (a *app) LoadSnapshotChunk(chunk abci.RequestLoadSnapshotChunk) abci.ResponseLoadSnapshotChunk { + panic("implement me") +} + +func (a *app) ApplySnapshotChunk(chunk abci.RequestApplySnapshotChunk) abci.ResponseApplySnapshotChunk { + panic("implement me") +} + +func (a *app) RegisterAPIRoutes(a2 *api.Server, config config.APIConfig) { + panic("implement me") +} + +func (a *app) RegisterGRPCServer(context client.Context, g grpc1.Server) { + panic("implement me") +} + +func (a *app) RegisterTxService(clientCtx client.Context) { + panic("implement me") +} + +func (a *app) RegisterTendermintService(clientCtx client.Context) { + panic("implement me") +} + +func (a *app) prepForZeroHeightGenesis(ctx sdk.Context, jailAllowedAddrs []string) { + panic("TODO") + //applyAllowedAddrs := false + // + //// check if there is a allowed address list + //if len(jailAllowedAddrs) > 0 { + // applyAllowedAddrs = true + //} + // + //allowedAddrsMap := make(map[string]bool) + // + //for _, addr := range jailAllowedAddrs { + // _, err := sdk.ValAddressFromBech32(addr) + // if err != nil { + // log.Fatal(err) + // } + // allowedAddrsMap[addr] = true + //} + // + ///* Just to be safe, assert the invariants on current state. */ + //app.CrisisKeeper.AssertInvariants(ctx) + // + ///* Handle fee distribution state. */ + // + //// withdraw all validator commission + //app.StakingKeeper.IterateValidators(ctx, func(_ int64, val stakingtypes.ValidatorI) (stop bool) { + // _, _ = app.DistrKeeper.WithdrawValidatorCommission(ctx, val.GetOperator()) + // return false + //}) + // + //// withdraw all delegator rewards + //dels := app.StakingKeeper.GetAllDelegations(ctx) + //for _, delegation := range dels { + // valAddr, err := sdk.ValAddressFromBech32(delegation.ValidatorAddress) + // if err != nil { + // panic(err) + // } + // + // delAddr, err := sdk.AccAddressFromBech32(delegation.DelegatorAddress) + // if err != nil { + // panic(err) + // } + // _, _ = app.DistrKeeper.WithdrawDelegationRewards(ctx, delAddr, valAddr) + //} + // + //// clear validator slash events + //app.DistrKeeper.DeleteAllValidatorSlashEvents(ctx) + // + //// clear validator historical rewards + //app.DistrKeeper.DeleteAllValidatorHistoricalRewards(ctx) + // + //// set context height to zero + //height := ctx.BlockHeight() + //ctx = ctx.WithBlockHeight(0) + // + //// reinitialize all validators + //app.StakingKeeper.IterateValidators(ctx, func(_ int64, val stakingtypes.ValidatorI) (stop bool) { + // // donate any unwithdrawn outstanding reward fraction tokens to the community pool + // scraps := app.DistrKeeper.GetValidatorOutstandingRewardsCoins(ctx, val.GetOperator()) + // feePool := app.DistrKeeper.GetFeePool(ctx) + // feePool.CommunityPool = feePool.CommunityPool.Add(scraps...) + // app.DistrKeeper.SetFeePool(ctx, feePool) + // + // app.DistrKeeper.Hooks().AfterValidatorCreated(ctx, val.GetOperator()) + // return false + //}) + // + //// reinitialize all delegations + //for _, del := range dels { + // valAddr, err := sdk.ValAddressFromBech32(del.ValidatorAddress) + // if err != nil { + // panic(err) + // } + // delAddr, err := sdk.AccAddressFromBech32(del.DelegatorAddress) + // if err != nil { + // panic(err) + // } + // app.DistrKeeper.Hooks().BeforeDelegationCreated(ctx, delAddr, valAddr) + // app.DistrKeeper.Hooks().AfterDelegationModified(ctx, delAddr, valAddr) + //} + // + //// reset context height + //ctx = ctx.WithBlockHeight(height) + // + ///* Handle staking state. */ + // + //// iterate through redelegations, reset creation height + //app.StakingKeeper.IterateRedelegations(ctx, func(_ int64, red stakingtypes.Redelegation) (stop bool) { + // for i := range red.Entries { + // red.Entries[i].CreationHeight = 0 + // } + // app.StakingKeeper.SetRedelegation(ctx, red) + // return false + //}) + // + //// iterate through unbonding delegations, reset creation height + //app.StakingKeeper.IterateUnbondingDelegations(ctx, func(_ int64, ubd stakingtypes.UnbondingDelegation) (stop bool) { + // for i := range ubd.Entries { + // ubd.Entries[i].CreationHeight = 0 + // } + // app.StakingKeeper.SetUnbondingDelegation(ctx, ubd) + // return false + //}) + // + //// Iterate through validators by power descending, reset bond heights, and + //// update bond intra-tx counters. + //store := ctx.KVStore(app.keys[stakingtypes.StoreKey]) + //iter := sdk.KVStoreReversePrefixIterator(store, stakingtypes.ValidatorsKey) + //counter := int16(0) + // + //for ; iter.Valid(); iter.Next() { + // addr := sdk.ValAddress(stakingtypes.AddressFromValidatorsKey(iter.Key())) + // validator, found := app.StakingKeeper.GetValidator(ctx, addr) + // if !found { + // panic("expected validator, not found") + // } + // + // validator.UnbondingHeight = 0 + // if applyAllowedAddrs && !allowedAddrsMap[addr.String()] { + // validator.Jailed = true + // } + // + // app.StakingKeeper.SetValidator(ctx, validator) + // counter++ + //} + // + //iter.Close() + // + //_, err := app.StakingKeeper.ApplyAndReturnValidatorSetUpdates(ctx) + //if err != nil { + // log.Fatal(err) + //} + // + ///* Handle slashing state. */ + // + //// reset start height on signing infos + //app.SlashingKeeper.IterateValidatorSigningInfos( + // ctx, + // func(addr sdk.ConsAddress, info slashingtypes.ValidatorSigningInfo) (stop bool) { + // info.StartHeight = 0 + // app.SlashingKeeper.SetValidatorSigningInfo(ctx, addr, info) + // return false + // }, + //) +} diff --git a/app/app_provider.go b/app/app_provider.go new file mode 100644 index 000000000000..f302f41c793e --- /dev/null +++ b/app/app_provider.go @@ -0,0 +1,162 @@ +package app + +import ( + "errors" + "io" + "path/filepath" + + "github.com/spf13/cast" + + "github.com/cosmos/cosmos-sdk/baseapp" + "github.com/cosmos/cosmos-sdk/client/flags" + "github.com/cosmos/cosmos-sdk/server" + "github.com/cosmos/cosmos-sdk/snapshots" + "github.com/cosmos/cosmos-sdk/store" + sdk "github.com/cosmos/cosmos-sdk/types" + + "github.com/cosmos/cosmos-sdk/container" + + "github.com/cosmos/cosmos-sdk/x/auth/tx" + + "github.com/cosmos/cosmos-sdk/client" + "github.com/cosmos/cosmos-sdk/codec" + codecTypes "github.com/cosmos/cosmos-sdk/codec/types" + + "github.com/tendermint/tendermint/libs/log" + dbm "github.com/tendermint/tm-db" + + servertypes "github.com/cosmos/cosmos-sdk/server/types" +) + +type AppProvider struct { + config *Config + container *container.Container + interfaceRegistry codecTypes.InterfaceRegistry + codec codec.Codec + txConfig client.TxConfig + amino *codec.LegacyAmino +} + +func (ap *AppProvider) InterfaceRegistry() codecTypes.InterfaceRegistry { + return ap.interfaceRegistry +} + +func (ap *AppProvider) Codec() codec.Codec { + return ap.codec +} + +func (ap *AppProvider) TxConfig() client.TxConfig { + return ap.txConfig +} + +func (ap *AppProvider) Amino() *codec.LegacyAmino { + return ap.amino +} + +func NewApp(config *Config) (*AppProvider, error) { + ctr := container.NewContainer() + interfaceRegistry := codecTypes.NewInterfaceRegistry() + marshaler := codec.NewProtoCodec(interfaceRegistry) + txConfig := tx.NewTxConfig(marshaler, tx.DefaultSignModes) + amino := codec.NewLegacyAmino() + + err := ctr.RegisterProvider(func() (codecTypes.InterfaceRegistry, codec.Codec, client.TxConfig, *codec.LegacyAmino) { + return interfaceRegistry, marshaler, txConfig, amino + }) + if err != nil { + return nil, err + } + + return &AppProvider{ + config: config, + container: ctr, + interfaceRegistry: interfaceRegistry, + codec: marshaler, + txConfig: txConfig, + amino: amino, + }, nil +} + +// NewApp is an AppCreator +func (ap *AppProvider) AppCreator( + logger log.Logger, + db dbm.DB, + traceStore io.Writer, + appOpts servertypes.AppOptions, +) servertypes.Application { + var cache sdk.MultiStorePersistentCache + + if cast.ToBool(appOpts.Get(server.FlagInterBlockCache)) { + cache = store.NewCommitKVStoreCacheManager() + } + + skipUpgradeHeights := make(map[int64]bool) + for _, h := range cast.ToIntSlice(appOpts.Get(server.FlagUnsafeSkipUpgrades)) { + skipUpgradeHeights[int64(h)] = true + } + + pruningOpts, err := server.GetPruningOptionsFromFlags(appOpts) + if err != nil { + panic(err) + } + + snapshotDir := filepath.Join(cast.ToString(appOpts.Get(flags.FlagHome)), "data", "snapshots") + snapshotDB, err := sdk.NewLevelDB("metadata", snapshotDir) + if err != nil { + panic(err) + } + snapshotStore, err := snapshots.NewStore(snapshotDB, snapshotDir) + if err != nil { + panic(err) + } + + return ap.newApp( + logger, db, traceStore, true, skipUpgradeHeights, + cast.ToString(appOpts.Get(flags.FlagHome)), + cast.ToUint(appOpts.Get(server.FlagInvCheckPeriod)), + appOpts, + baseapp.SetPruning(pruningOpts), + baseapp.SetMinGasPrices(cast.ToString(appOpts.Get(server.FlagMinGasPrices))), + baseapp.SetHaltHeight(cast.ToUint64(appOpts.Get(server.FlagHaltHeight))), + baseapp.SetHaltTime(cast.ToUint64(appOpts.Get(server.FlagHaltTime))), + baseapp.SetMinRetainBlocks(cast.ToUint64(appOpts.Get(server.FlagMinRetainBlocks))), + baseapp.SetInterBlockCache(cache), + baseapp.SetTrace(cast.ToBool(appOpts.Get(server.FlagTrace))), + baseapp.SetIndexEvents(cast.ToStringSlice(appOpts.Get(server.FlagIndexEvents))), + baseapp.SetSnapshotStore(snapshotStore), + baseapp.SetSnapshotInterval(cast.ToUint64(appOpts.Get(server.FlagStateSyncSnapshotInterval))), + baseapp.SetSnapshotKeepRecent(cast.ToUint32(appOpts.Get(server.FlagStateSyncSnapshotKeepRecent))), + ) +} + +func (ap *AppProvider) newApp( + logger log.Logger, db dbm.DB, traceStore io.Writer, loadLatest bool, skipUpgradeHeights map[int64]bool, + homePath string, invCheckPeriod uint, + appOpts servertypes.AppOptions, baseAppOptions ...func(*baseapp.BaseApp), +) *app { + return &app{} +} + +// AppExport creates a new app (optionally at a given height) and exports state. +func (ap *AppProvider) AppExportor( + logger log.Logger, db dbm.DB, traceStore io.Writer, height int64, forZeroHeight bool, jailAllowedAddrs []string, + appOpts servertypes.AppOptions) (servertypes.ExportedApp, error) { + + var a *app + homePath, ok := appOpts.Get(flags.FlagHome).(string) + if !ok || homePath == "" { + return servertypes.ExportedApp{}, errors.New("application home not set") + } + + if height != -1 { + a = ap.newApp(logger, db, traceStore, false, map[int64]bool{}, homePath, uint(1), appOpts) + + if err := a.LoadVersion(height); err != nil { + return servertypes.ExportedApp{}, err + } + } else { + a = ap.newApp(logger, db, traceStore, true, map[int64]bool{}, homePath, uint(1), appOpts) + } + + return a.exportAppStateAndValidators(forZeroHeight, jailAllowedAddrs) +} diff --git a/app/cli/run.go b/app/cli/run.go new file mode 100644 index 000000000000..7bbfc3afbaaf --- /dev/null +++ b/app/cli/run.go @@ -0,0 +1,178 @@ +package cli + +import ( + "os" + + "github.com/spf13/cobra" + tmcli "github.com/tendermint/tendermint/libs/cli" + + "github.com/cosmos/cosmos-sdk/app" + "github.com/cosmos/cosmos-sdk/client" + "github.com/cosmos/cosmos-sdk/client/config" + "github.com/cosmos/cosmos-sdk/client/debug" + "github.com/cosmos/cosmos-sdk/client/flags" + "github.com/cosmos/cosmos-sdk/client/keys" + "github.com/cosmos/cosmos-sdk/client/rpc" + "github.com/cosmos/cosmos-sdk/server" + svrcmd "github.com/cosmos/cosmos-sdk/server/cmd" + "github.com/cosmos/cosmos-sdk/simapp" + sdk "github.com/cosmos/cosmos-sdk/types" + authcmd "github.com/cosmos/cosmos-sdk/x/auth/client/cli" + "github.com/cosmos/cosmos-sdk/x/auth/types" + vestingcli "github.com/cosmos/cosmos-sdk/x/auth/vesting/client/cli" + banktypes "github.com/cosmos/cosmos-sdk/x/bank/types" + "github.com/cosmos/cosmos-sdk/x/crisis" + genutilcli "github.com/cosmos/cosmos-sdk/x/genutil/client/cli" +) + +type Options struct { + DefaultAppConfig *app.Config + DefaultHome string + EnvPrefix string +} + +func Run(options Options) { + rootCmd := newRootCmd(options) + + if err := svrcmd.Execute(rootCmd, options.DefaultHome); err != nil { + switch e := err.(type) { + case server.ErrorCode: + os.Exit(e.Code) + + default: + os.Exit(1) + } + } +} + +func newRootCmd(options Options) *cobra.Command { + a, err := app.NewApp(options.DefaultAppConfig) + if err != nil { + panic(err) + } + + initClientCtx := client.Context{}. + WithJSONCodec(a.Codec()). + WithInterfaceRegistry(a.InterfaceRegistry()). + WithTxConfig(a.TxConfig()). + WithLegacyAmino(a.Amino()). + WithInput(os.Stdin). + WithAccountRetriever(types.AccountRetriever{}). + WithHomeDir(options.DefaultHome). + WithViper("") // In simapp, we don't use any prefix for env variables. + + rootCmd := &cobra.Command{ + Use: "simd", + Short: "simulation app", + PersistentPreRunE: func(cmd *cobra.Command, _ []string) error { + // set the default command outputs + cmd.SetOut(cmd.OutOrStdout()) + cmd.SetErr(cmd.ErrOrStderr()) + + initClientCtx = client.ReadHomeFlag(initClientCtx, cmd) + + initClientCtx, err := config.ReadFromClientConfig(initClientCtx) + if err != nil { + return err + } + + if err := client.SetCmdClientContextHandler(initClientCtx, cmd); err != nil { + return err + } + + return server.InterceptConfigsPreRunHandler(cmd) + }, + } + + initRootCmd(options, rootCmd, a) + + return rootCmd +} + +func initRootCmd(options Options, rootCmd *cobra.Command, a *app.AppProvider) { + cfg := sdk.GetConfig() + cfg.Seal() + + rootCmd.AddCommand( + genutilcli.InitCmd(simapp.ModuleBasics, options.DefaultHome), + genutilcli.CollectGenTxsCmd(banktypes.GenesisBalancesIterator{}, options.DefaultHome), + genutilcli.MigrateGenesisCmd(), + genutilcli.GenTxCmd(simapp.ModuleBasics, a.TxConfig(), banktypes.GenesisBalancesIterator{}, options.DefaultHome), + genutilcli.ValidateGenesisCmd(simapp.ModuleBasics), + //AddGenesisAccountCmd(options.DefaultHome), + tmcli.NewCompletionCmd(rootCmd, true), + //TODO: testnetCmd(simapp.ModuleBasics, banktypes.GenesisBalancesIterator{}), + debug.Cmd(), + config.Cmd(), + ) + + server.AddCommands(rootCmd, options.DefaultHome, a.AppCreator, a.AppExportor, addModuleInitFlags) + + // add keybase, auxiliary RPC, query, and tx child commands + rootCmd.AddCommand( + rpc.StatusCommand(), + queryCommand(), + txCommand(), + keys.Commands(options.DefaultHome), + ) + + // add rosetta + rootCmd.AddCommand(server.RosettaCommand(a.InterfaceRegistry(), a.Codec())) +} + +func addModuleInitFlags(startCmd *cobra.Command) { + crisis.AddModuleInitFlags(startCmd) +} + +func queryCommand() *cobra.Command { + cmd := &cobra.Command{ + Use: "query", + Aliases: []string{"q"}, + Short: "Querying subcommands", + DisableFlagParsing: true, + SuggestionsMinimumDistance: 2, + RunE: client.ValidateCmd, + } + + cmd.AddCommand( + authcmd.GetAccountCmd(), + rpc.ValidatorCommand(), + rpc.BlockCommand(), + authcmd.QueryTxsByEventsCmd(), + authcmd.QueryTxCmd(), + ) + + simapp.ModuleBasics.AddQueryCommands(cmd) + cmd.PersistentFlags().String(flags.FlagChainID, "", "The network chain ID") + + return cmd +} + +func txCommand() *cobra.Command { + cmd := &cobra.Command{ + Use: "tx", + Short: "Transactions subcommands", + DisableFlagParsing: true, + SuggestionsMinimumDistance: 2, + RunE: client.ValidateCmd, + } + + cmd.AddCommand( + authcmd.GetSignCommand(), + authcmd.GetSignBatchCommand(), + authcmd.GetMultiSignCommand(), + authcmd.GetMultiSignBatchCmd(), + authcmd.GetValidateSignaturesCommand(), + flags.LineBreak, + authcmd.GetBroadcastCommand(), + authcmd.GetEncodeCommand(), + authcmd.GetDecodeCommand(), + flags.LineBreak, + vestingcli.GetTxCmd(), + ) + + simapp.ModuleBasics.AddTxCommands(cmd) + cmd.PersistentFlags().String(flags.FlagChainID, "", "The network chain ID") + + return cmd +} diff --git a/app/config.pb.go b/app/config.pb.go new file mode 100644 index 000000000000..608f2f427e22 --- /dev/null +++ b/app/config.pb.go @@ -0,0 +1,561 @@ +// Code generated by protoc-gen-gogo. DO NOT EDIT. +// source: cosmos/app/v1/config.proto + +package app + +import ( + fmt "fmt" + types "github.com/cosmos/cosmos-sdk/codec/types" + proto "github.com/gogo/protobuf/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 + +type Config struct { + Modules []*ModuleConfig `protobuf:"bytes,1,rep,name=modules,proto3" json:"modules,omitempty"` +} + +func (m *Config) Reset() { *m = Config{} } +func (m *Config) String() string { return proto.CompactTextString(m) } +func (*Config) ProtoMessage() {} +func (*Config) Descriptor() ([]byte, []int) { + return fileDescriptor_9c5c7e08cb1a0bd9, []int{0} +} +func (m *Config) XXX_Unmarshal(b []byte) error { + return m.Unmarshal(b) +} +func (m *Config) XXX_Marshal(b []byte, deterministic bool) ([]byte, error) { + if deterministic { + return xxx_messageInfo_Config.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 *Config) XXX_Merge(src proto.Message) { + xxx_messageInfo_Config.Merge(m, src) +} +func (m *Config) XXX_Size() int { + return m.Size() +} +func (m *Config) XXX_DiscardUnknown() { + xxx_messageInfo_Config.DiscardUnknown(m) +} + +var xxx_messageInfo_Config proto.InternalMessageInfo + +func (m *Config) GetModules() []*ModuleConfig { + if m != nil { + return m.Modules + } + return nil +} + +type ModuleConfig struct { + Config *types.Any `protobuf:"bytes,1,opt,name=config,proto3" json:"config,omitempty"` + Name string `protobuf:"bytes,2,opt,name=name,proto3" json:"name,omitempty"` +} + +func (m *ModuleConfig) Reset() { *m = ModuleConfig{} } +func (m *ModuleConfig) String() string { return proto.CompactTextString(m) } +func (*ModuleConfig) ProtoMessage() {} +func (*ModuleConfig) Descriptor() ([]byte, []int) { + return fileDescriptor_9c5c7e08cb1a0bd9, []int{1} +} +func (m *ModuleConfig) XXX_Unmarshal(b []byte) error { + return m.Unmarshal(b) +} +func (m *ModuleConfig) XXX_Marshal(b []byte, deterministic bool) ([]byte, error) { + if deterministic { + return xxx_messageInfo_ModuleConfig.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 *ModuleConfig) XXX_Merge(src proto.Message) { + xxx_messageInfo_ModuleConfig.Merge(m, src) +} +func (m *ModuleConfig) XXX_Size() int { + return m.Size() +} +func (m *ModuleConfig) XXX_DiscardUnknown() { + xxx_messageInfo_ModuleConfig.DiscardUnknown(m) +} + +var xxx_messageInfo_ModuleConfig proto.InternalMessageInfo + +func (m *ModuleConfig) GetConfig() *types.Any { + if m != nil { + return m.Config + } + return nil +} + +func (m *ModuleConfig) GetName() string { + if m != nil { + return m.Name + } + return "" +} + +func init() { + proto.RegisterType((*Config)(nil), "cosmos.app.v1.Config") + proto.RegisterType((*ModuleConfig)(nil), "cosmos.app.v1.ModuleConfig") +} + +func init() { proto.RegisterFile("cosmos/app/v1/config.proto", fileDescriptor_9c5c7e08cb1a0bd9) } + +var fileDescriptor_9c5c7e08cb1a0bd9 = []byte{ + // 227 bytes of a gzipped FileDescriptorProto + 0x1f, 0x8b, 0x08, 0x00, 0x00, 0x00, 0x00, 0x00, 0x02, 0xff, 0xe2, 0x92, 0x4a, 0xce, 0x2f, 0xce, + 0xcd, 0x2f, 0xd6, 0x4f, 0x2c, 0x28, 0xd0, 0x2f, 0x33, 0xd4, 0x4f, 0xce, 0xcf, 0x4b, 0xcb, 0x4c, + 0xd7, 0x2b, 0x28, 0xca, 0x2f, 0xc9, 0x17, 0xe2, 0x85, 0xc8, 0xe9, 0x25, 0x16, 0x14, 0xe8, 0x95, + 0x19, 0x4a, 0x49, 0xa6, 0xe7, 0xe7, 0xa7, 0xe7, 0xa4, 0xea, 0x83, 0x25, 0x93, 0x4a, 0xd3, 0xf4, + 0x13, 0xf3, 0x2a, 0x21, 0x2a, 0x95, 0xec, 0xb9, 0xd8, 0x9c, 0xc1, 0x3a, 0x85, 0x4c, 0xb9, 0xd8, + 0x73, 0xf3, 0x53, 0x4a, 0x73, 0x52, 0x8b, 0x25, 0x18, 0x15, 0x98, 0x35, 0xb8, 0x8d, 0xa4, 0xf5, + 0x50, 0x4c, 0xd1, 0xf3, 0x05, 0xcb, 0x42, 0x54, 0x07, 0xc1, 0xd4, 0x2a, 0x05, 0x70, 0xf1, 0x20, + 0x4b, 0x08, 0xe9, 0x70, 0xb1, 0x41, 0x9c, 0x22, 0xc1, 0xa8, 0xc0, 0xa8, 0xc1, 0x6d, 0x24, 0xa2, + 0x07, 0xb1, 0x5c, 0x0f, 0x66, 0xb9, 0x9e, 0x63, 0x5e, 0x65, 0x10, 0x54, 0x8d, 0x90, 0x10, 0x17, + 0x4b, 0x5e, 0x62, 0x6e, 0xaa, 0x04, 0x93, 0x02, 0xa3, 0x06, 0x67, 0x10, 0x98, 0xed, 0x64, 0x75, + 0xe2, 0x91, 0x1c, 0xe3, 0x85, 0x47, 0x72, 0x8c, 0x0f, 0x1e, 0xc9, 0x31, 0x4e, 0x78, 0x2c, 0xc7, + 0x70, 0xe1, 0xb1, 0x1c, 0xc3, 0x8d, 0xc7, 0x72, 0x0c, 0x51, 0x0a, 0xe9, 0x99, 0x25, 0x19, 0xa5, + 0x49, 0x7a, 0xc9, 0xf9, 0xb9, 0xfa, 0x50, 0xdf, 0x43, 0x28, 0xdd, 0xe2, 0x94, 0x6c, 0x50, 0x40, + 0x24, 0xb1, 0x81, 0x6d, 0x31, 0x06, 0x04, 0x00, 0x00, 0xff, 0xff, 0x52, 0x6f, 0xad, 0x11, 0x1d, + 0x01, 0x00, 0x00, +} + +func (m *Config) 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 *Config) MarshalTo(dAtA []byte) (int, error) { + size := m.Size() + return m.MarshalToSizedBuffer(dAtA[:size]) +} + +func (m *Config) MarshalToSizedBuffer(dAtA []byte) (int, error) { + i := len(dAtA) + _ = i + var l int + _ = l + if len(m.Modules) > 0 { + for iNdEx := len(m.Modules) - 1; iNdEx >= 0; iNdEx-- { + { + size, err := m.Modules[iNdEx].MarshalToSizedBuffer(dAtA[:i]) + if err != nil { + return 0, err + } + i -= size + i = encodeVarintConfig(dAtA, i, uint64(size)) + } + i-- + dAtA[i] = 0xa + } + } + return len(dAtA) - i, nil +} + +func (m *ModuleConfig) 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 *ModuleConfig) MarshalTo(dAtA []byte) (int, error) { + size := m.Size() + return m.MarshalToSizedBuffer(dAtA[:size]) +} + +func (m *ModuleConfig) MarshalToSizedBuffer(dAtA []byte) (int, error) { + i := len(dAtA) + _ = i + var l int + _ = l + if len(m.Name) > 0 { + i -= len(m.Name) + copy(dAtA[i:], m.Name) + i = encodeVarintConfig(dAtA, i, uint64(len(m.Name))) + i-- + dAtA[i] = 0x12 + } + if m.Config != nil { + { + size, err := m.Config.MarshalToSizedBuffer(dAtA[:i]) + if err != nil { + return 0, err + } + i -= size + i = encodeVarintConfig(dAtA, i, uint64(size)) + } + i-- + dAtA[i] = 0xa + } + return len(dAtA) - i, nil +} + +func encodeVarintConfig(dAtA []byte, offset int, v uint64) int { + offset -= sovConfig(v) + base := offset + for v >= 1<<7 { + dAtA[offset] = uint8(v&0x7f | 0x80) + v >>= 7 + offset++ + } + dAtA[offset] = uint8(v) + return base +} +func (m *Config) Size() (n int) { + if m == nil { + return 0 + } + var l int + _ = l + if len(m.Modules) > 0 { + for _, e := range m.Modules { + l = e.Size() + n += 1 + l + sovConfig(uint64(l)) + } + } + return n +} + +func (m *ModuleConfig) Size() (n int) { + if m == nil { + return 0 + } + var l int + _ = l + if m.Config != nil { + l = m.Config.Size() + n += 1 + l + sovConfig(uint64(l)) + } + l = len(m.Name) + if l > 0 { + n += 1 + l + sovConfig(uint64(l)) + } + return n +} + +func sovConfig(x uint64) (n int) { + return (math_bits.Len64(x|1) + 6) / 7 +} +func sozConfig(x uint64) (n int) { + return sovConfig(uint64((x << 1) ^ uint64((int64(x) >> 63)))) +} +func (m *Config) 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 ErrIntOverflowConfig + } + 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: Config: wiretype end group for non-group") + } + if fieldNum <= 0 { + return fmt.Errorf("proto: Config: illegal tag %d (wire type %d)", fieldNum, wire) + } + switch fieldNum { + case 1: + if wireType != 2 { + return fmt.Errorf("proto: wrong wireType = %d for field Modules", wireType) + } + var msglen int + for shift := uint(0); ; shift += 7 { + if shift >= 64 { + return ErrIntOverflowConfig + } + if iNdEx >= l { + return io.ErrUnexpectedEOF + } + b := dAtA[iNdEx] + iNdEx++ + msglen |= int(b&0x7F) << shift + if b < 0x80 { + break + } + } + if msglen < 0 { + return ErrInvalidLengthConfig + } + postIndex := iNdEx + msglen + if postIndex < 0 { + return ErrInvalidLengthConfig + } + if postIndex > l { + return io.ErrUnexpectedEOF + } + m.Modules = append(m.Modules, &ModuleConfig{}) + if err := m.Modules[len(m.Modules)-1].Unmarshal(dAtA[iNdEx:postIndex]); err != nil { + return err + } + iNdEx = postIndex + default: + iNdEx = preIndex + skippy, err := skipConfig(dAtA[iNdEx:]) + if err != nil { + return err + } + if (skippy < 0) || (iNdEx+skippy) < 0 { + return ErrInvalidLengthConfig + } + if (iNdEx + skippy) > l { + return io.ErrUnexpectedEOF + } + iNdEx += skippy + } + } + + if iNdEx > l { + return io.ErrUnexpectedEOF + } + return nil +} +func (m *ModuleConfig) 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 ErrIntOverflowConfig + } + 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: ModuleConfig: wiretype end group for non-group") + } + if fieldNum <= 0 { + return fmt.Errorf("proto: ModuleConfig: illegal tag %d (wire type %d)", fieldNum, wire) + } + switch fieldNum { + case 1: + if wireType != 2 { + return fmt.Errorf("proto: wrong wireType = %d for field Config", wireType) + } + var msglen int + for shift := uint(0); ; shift += 7 { + if shift >= 64 { + return ErrIntOverflowConfig + } + if iNdEx >= l { + return io.ErrUnexpectedEOF + } + b := dAtA[iNdEx] + iNdEx++ + msglen |= int(b&0x7F) << shift + if b < 0x80 { + break + } + } + if msglen < 0 { + return ErrInvalidLengthConfig + } + postIndex := iNdEx + msglen + if postIndex < 0 { + return ErrInvalidLengthConfig + } + if postIndex > l { + return io.ErrUnexpectedEOF + } + if m.Config == nil { + m.Config = &types.Any{} + } + if err := m.Config.Unmarshal(dAtA[iNdEx:postIndex]); err != nil { + return err + } + iNdEx = postIndex + case 2: + if wireType != 2 { + return fmt.Errorf("proto: wrong wireType = %d for field Name", wireType) + } + var stringLen uint64 + for shift := uint(0); ; shift += 7 { + if shift >= 64 { + return ErrIntOverflowConfig + } + 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 ErrInvalidLengthConfig + } + postIndex := iNdEx + intStringLen + if postIndex < 0 { + return ErrInvalidLengthConfig + } + if postIndex > l { + return io.ErrUnexpectedEOF + } + m.Name = string(dAtA[iNdEx:postIndex]) + iNdEx = postIndex + default: + iNdEx = preIndex + skippy, err := skipConfig(dAtA[iNdEx:]) + if err != nil { + return err + } + if (skippy < 0) || (iNdEx+skippy) < 0 { + return ErrInvalidLengthConfig + } + if (iNdEx + skippy) > l { + return io.ErrUnexpectedEOF + } + iNdEx += skippy + } + } + + if iNdEx > l { + return io.ErrUnexpectedEOF + } + return nil +} +func skipConfig(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, ErrIntOverflowConfig + } + 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, ErrIntOverflowConfig + } + 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, ErrIntOverflowConfig + } + 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, ErrInvalidLengthConfig + } + iNdEx += length + case 3: + depth++ + case 4: + if depth == 0 { + return 0, ErrUnexpectedEndOfGroupConfig + } + depth-- + case 5: + iNdEx += 4 + default: + return 0, fmt.Errorf("proto: illegal wireType %d", wireType) + } + if iNdEx < 0 { + return 0, ErrInvalidLengthConfig + } + if depth == 0 { + return iNdEx, nil + } + } + return 0, io.ErrUnexpectedEOF +} + +var ( + ErrInvalidLengthConfig = fmt.Errorf("proto: negative length found during unmarshaling") + ErrIntOverflowConfig = fmt.Errorf("proto: integer overflow") + ErrUnexpectedEndOfGroupConfig = fmt.Errorf("proto: unexpected end of group") +) diff --git a/app/decode.go b/app/decode.go new file mode 100644 index 000000000000..89806d126fc6 --- /dev/null +++ b/app/decode.go @@ -0,0 +1,34 @@ +package app + +import ( + "encoding/json" + + "github.com/gogo/protobuf/proto" + + "gopkg.in/yaml.v2" +) + +func ReadJSONConfig(bz []byte) (*Config, error) { + var cfg Config + err := proto.Unmarshal(bz, &cfg) + if err != nil { + return nil, err + } + + return &cfg, nil +} + +func ReadYAMLConfig(bz []byte) (*Config, error) { + var cfg map[string]interface{} + err := yaml.Unmarshal(bz, &cfg) + if err != nil { + return nil, err + } + + jsonBz, err := json.Marshal(cfg) + if err != nil { + return nil, err + } + + return ReadJSONConfig(jsonBz) +} diff --git a/container/container.go b/container/container.go index 1d09df746495..6302487dbf6e 100644 --- a/container/container.go +++ b/container/container.go @@ -1,5 +1,18 @@ package container -type Registrar interface { - RegisterProvider(fn interface{}) error +type Container struct { +} + +var _ Registrar = &Container{} + +func NewContainer() *Container { + panic("TODO") +} + +func (c *Container) RegisterProvider(fn interface{}) error { + panic("implement me") +} + +func (c *Container) Invoke(fn interface{}) error { + panic("TODO") } diff --git a/container/registrar.go b/container/registrar.go new file mode 100644 index 000000000000..1d09df746495 --- /dev/null +++ b/container/registrar.go @@ -0,0 +1,5 @@ +package container + +type Registrar interface { + RegisterProvider(fn interface{}) error +} diff --git a/docs/core/proto-docs.md b/docs/core/proto-docs.md index edc16d65ccbd..8b9701673ade 100644 --- a/docs/core/proto-docs.md +++ b/docs/core/proto-docs.md @@ -4,7 +4,13 @@ ## Table of Contents +- [cosmos/app/v1/config.proto](#cosmos/app/v1/config.proto) + - [Config](#cosmos.app.v1.Config) + - [ModuleConfig](#cosmos.app.v1.ModuleConfig) + - [cosmos/auth/module/v1/module.proto](#cosmos/auth/module/v1/module.proto) + - [DefaultAccountConstructor](#cosmos.auth.module.v1.DefaultAccountConstructor) + - [DefaultRandomGenesisAccountsProvider](#cosmos.auth.module.v1.DefaultRandomGenesisAccountsProvider) - [Module](#cosmos.auth.module.v1.Module) - [Permission](#cosmos.auth.module.v1.Permission) @@ -70,6 +76,9 @@ - [Msg](#cosmos.authz.v1beta1.Msg) +- [cosmos/bank/module/v1/module.proto](#cosmos/bank/module/v1/module.proto) + - [Module](#cosmos.bank.module.v1.Module) + - [cosmos/base/v1beta1/coin.proto](#cosmos/base/v1beta1/coin.proto) - [Coin](#cosmos.base.v1beta1.Coin) - [DecCoin](#cosmos.base.v1beta1.DecCoin) @@ -596,6 +605,53 @@ + +

Top

+ +## cosmos/app/v1/config.proto + + + + + +### Config + + + +| Field | Type | Label | Description | +| ----- | ---- | ----- | ----------- | +| `modules` | [ModuleConfig](#cosmos.app.v1.ModuleConfig) | repeated | | + + + + + + + + +### ModuleConfig + + + +| Field | Type | Label | Description | +| ----- | ---- | ----- | ----------- | +| `config` | [google.protobuf.Any](#google.protobuf.Any) | | | +| `name` | [string](#string) | | | + + + + + + + + + + + + + + +

Top

@@ -603,6 +659,26 @@ + + +### DefaultAccountConstructor + + + + + + + + + +### DefaultRandomGenesisAccountsProvider + + + + + + + ### Module @@ -613,6 +689,7 @@ | ----- | ---- | ----- | ----------- | | `permissions` | [Permission](#cosmos.auth.module.v1.Permission) | repeated | | | `account_constructor` | [google.protobuf.Any](#google.protobuf.Any) | | account_constructor is an optional AccountI constructor config object that can be provided to override the default BaseAccount constructor. The provided config object must have an `NewAccount() AccountI` method defined. If this is left empty, the default constructor will be used | +| `random_genesis_accounts_provider` | [google.protobuf.Any](#google.protobuf.Any) | | | @@ -1447,6 +1524,37 @@ Msg defines the authz Msg service. + +

Top

+ +## cosmos/bank/module/v1/module.proto + + + + + +### Module + + + +| Field | Type | Label | Description | +| ----- | ---- | ----- | ----------- | +| `blocked_addrs` | [string](#string) | repeated | TODO: this shouldn't be a config param, rather we should have a more generic solution, such as: blocked module accounts should register themselves in genesis | + + + + + + + + + + + + + + +

Top

diff --git a/go.mod b/go.mod index aeed58848add..54b122aa9af1 100644 --- a/go.mod +++ b/go.mod @@ -10,6 +10,7 @@ require ( github.com/btcsuite/btcutil v1.0.2 github.com/coinbase/rosetta-sdk-go v0.6.10 github.com/confio/ics23/go v0.6.6 + github.com/cosmos/cosmos-sdk/container v0.0.0-20210601215105-8e0f2e2ea130 github.com/cosmos/go-bip39 v1.0.0 github.com/cosmos/iavl v0.16.0 github.com/cosmos/ledger-cosmos-go v0.11.1 @@ -62,3 +63,5 @@ require ( replace google.golang.org/grpc => google.golang.org/grpc v1.33.2 replace github.com/gogo/protobuf => github.com/regen-network/protobuf v1.3.3-alpha.regen.1 + +replace github.com/cosmos/cosmos-sdk/container => ./container diff --git a/proto/cosmos/app/v1/config.proto b/proto/cosmos/app/v1/config.proto new file mode 100644 index 000000000000..5b098fffd359 --- /dev/null +++ b/proto/cosmos/app/v1/config.proto @@ -0,0 +1,22 @@ +syntax = "proto3"; +package cosmos.app.v1; + +import "google/protobuf/any.proto"; + +option go_package = "github.com/cosmos/cosmos-sdk/app"; + +message Config { + repeated ModuleConfig modules = 1; + ABCIHandlers abci = 2; +} + +message ModuleConfig { + google.protobuf.Any config = 1; + string name = 2; +} + +message ABCIHandlers { + repeated string init_genesis = 1; + repeated string begin_block = 2; + repeated string end_block = 3; +} diff --git a/proto/cosmos/auth/module/v1/module.proto b/proto/cosmos/auth/module/v1/module.proto index 50233de83e3f..e24fd0da22a8 100644 --- a/proto/cosmos/auth/module/v1/module.proto +++ b/proto/cosmos/auth/module/v1/module.proto @@ -13,9 +13,15 @@ message Module { // an `NewAccount() AccountI` method defined. If this is left empty, the default constructor // will be used google.protobuf.Any account_constructor = 2; + + google.protobuf.Any random_genesis_accounts_provider = 3; } message Permission { string address = 1; repeated string permissions = 2; } + +message DefaultAccountConstructor {} + +message DefaultRandomGenesisAccountsProvider {} \ No newline at end of file diff --git a/proto/cosmos/bank/module/v1/module.proto b/proto/cosmos/bank/module/v1/module.proto new file mode 100644 index 000000000000..a0c698643676 --- /dev/null +++ b/proto/cosmos/bank/module/v1/module.proto @@ -0,0 +1,10 @@ +syntax = "proto3"; +package cosmos.bank.module.v1; + +option go_package = "github.com/cosmos/cosmos-sdk/x/bank/module"; + +message Module { + // TODO: this shouldn't be a config param, rather we should have a more generic + // solution, such as: blocked module accounts should register themselves in genesis + repeated string blocked_addrs = 1; +} diff --git a/simapp/v2/app.go b/simapp/v2/app.go new file mode 100644 index 000000000000..179fdb8c1d59 --- /dev/null +++ b/simapp/v2/app.go @@ -0,0 +1,25 @@ +package main + +import ( + _ "embed" + + "github.com/cosmos/cosmos-sdk/app/cli" + + "github.com/cosmos/cosmos-sdk/app" +) + +//go:embed app.yaml +var configYaml []byte + +func main() { + config, err := app.ReadYAMLConfig(configYaml) + if err != nil { + panic(err) + } + + cli.Run(cli.Options{ + DefaultAppConfig: config, + DefaultHome: "simapp", + EnvPrefix: "SIMAPP", + }) +} diff --git a/simapp/v2/app.yaml b/simapp/v2/app.yaml new file mode 100644 index 000000000000..399cd481883e --- /dev/null +++ b/simapp/v2/app.yaml @@ -0,0 +1,7 @@ +modules: + - config: + @type: cosmos.auth.module.v1.Module + - config: + @type: cosmos.bank.module.v1.Module + - config: + @type: cosmos.params.module.v1.Module \ No newline at end of file diff --git a/x/auth/module/module.go b/x/auth/module/module.go index efca6edf12f1..404e8bedc766 100644 --- a/x/auth/module/module.go +++ b/x/auth/module/module.go @@ -7,6 +7,7 @@ import ( "github.com/cosmos/cosmos-sdk/types/module" "github.com/cosmos/cosmos-sdk/x/auth" authkeeper "github.com/cosmos/cosmos-sdk/x/auth/keeper" + "github.com/cosmos/cosmos-sdk/x/auth/simulation" "github.com/cosmos/cosmos-sdk/x/auth/types" paramtypes "github.com/cosmos/cosmos-sdk/x/params/types" ) @@ -14,10 +15,9 @@ import ( type Inputs struct { container.StructArgs - Codec codec.Codec - Key *sdk.KVStoreKey - ParamStore paramtypes.Subspace - RandomGenesisAccountsFn types.RandomGenesisAccountsFn + Codec codec.Codec + Key *sdk.KVStoreKey + ParamStore paramtypes.Subspace } type Outputs struct { @@ -28,18 +28,14 @@ type Outputs struct { } func (m Module) NewAppModule(inputs Inputs) (module.AppModule, Outputs, error) { - newAccFn := func() types.AccountI { - return &types.BaseAccount{} - } + var accCtr types.AccountConstructor if m.AccountConstructor != nil { - var accCtr types.AccountConstructor err := inputs.Codec.UnpackAny(m.AccountConstructor, &accCtr) if err != nil { return nil, Outputs{}, err } - newAccFn = func() types.AccountI { - return accCtr.NewAccount() - } + } else { + accCtr = DefaultAccountConstructor{} } perms := map[string][]string{} @@ -47,8 +43,22 @@ func (m Module) NewAppModule(inputs Inputs) (module.AppModule, Outputs, error) { perms[perm.Address] = perm.Permissions } - keeper := authkeeper.NewAccountKeeper(inputs.Codec, inputs.Key, inputs.ParamStore, newAccFn, perms) - appMod := auth.NewAppModule(inputs.Codec, keeper, inputs.RandomGenesisAccountsFn) + var randomGenesisAccountsProvider types.RandomGenesisAccountsProvider + if m.RandomGenesisAccountsProvider != nil { + err := inputs.Codec.UnpackAny(m.RandomGenesisAccountsProvider, &randomGenesisAccountsProvider) + if err != nil { + return nil, Outputs{}, err + } + } else { + randomGenesisAccountsProvider = DefaultRandomGenesisAccountsProvider{} + } + + keeper := authkeeper.NewAccountKeeper(inputs.Codec, inputs.Key, inputs.ParamStore, func() types.AccountI { + return accCtr.NewAccount() + }, perms) + appMod := auth.NewAppModule(inputs.Codec, keeper, func(simState *module.SimulationState) types.GenesisAccounts { + return randomGenesisAccountsProvider.RandomGenesisAccounts(simState) + }) return appMod, Outputs{ ViewKeeper: viewOnlyKeeper{keeper}, @@ -86,3 +96,11 @@ func (v viewOnlyKeeper) GetModuleAccount(ctx sdk.Context, moduleName string) typ } var _ types.ViewKeeper = viewOnlyKeeper{} + +func (m DefaultAccountConstructor) NewAccount() types.AccountI { + return &types.BaseAccount{} +} + +func (m DefaultRandomGenesisAccountsProvider) RandomGenesisAccounts(simState *module.SimulationState) types.GenesisAccounts { + return simulation.RandomGenesisAccounts(simState) +} diff --git a/x/auth/module/module.pb.go b/x/auth/module/module.pb.go index 6e8ca4356304..fa167689aa1c 100644 --- a/x/auth/module/module.pb.go +++ b/x/auth/module/module.pb.go @@ -29,7 +29,8 @@ type Module struct { // to override the default BaseAccount constructor. The provided config object must have // an `NewAccount() AccountI` method defined. If this is left empty, the default constructor // will be used - AccountConstructor *types.Any `protobuf:"bytes,2,opt,name=account_constructor,json=accountConstructor,proto3" json:"account_constructor,omitempty"` + AccountConstructor *types.Any `protobuf:"bytes,2,opt,name=account_constructor,json=accountConstructor,proto3" json:"account_constructor,omitempty"` + RandomGenesisAccountsProvider *types.Any `protobuf:"bytes,3,opt,name=random_genesis_accounts_provider,json=randomGenesisAccountsProvider,proto3" json:"random_genesis_accounts_provider,omitempty"` } func (m *Module) Reset() { *m = Module{} } @@ -79,6 +80,13 @@ func (m *Module) GetAccountConstructor() *types.Any { return nil } +func (m *Module) GetRandomGenesisAccountsProvider() *types.Any { + if m != nil { + return m.RandomGenesisAccountsProvider + } + return nil +} + type Permission struct { Address string `protobuf:"bytes,1,opt,name=address,proto3" json:"address,omitempty"` Permissions []string `protobuf:"bytes,2,rep,name=permissions,proto3" json:"permissions,omitempty"` @@ -131,9 +139,83 @@ func (m *Permission) GetPermissions() []string { return nil } +type DefaultAccountConstructor struct { +} + +func (m *DefaultAccountConstructor) Reset() { *m = DefaultAccountConstructor{} } +func (m *DefaultAccountConstructor) String() string { return proto.CompactTextString(m) } +func (*DefaultAccountConstructor) ProtoMessage() {} +func (*DefaultAccountConstructor) Descriptor() ([]byte, []int) { + return fileDescriptor_0f7f34be9f8952c0, []int{2} +} +func (m *DefaultAccountConstructor) XXX_Unmarshal(b []byte) error { + return m.Unmarshal(b) +} +func (m *DefaultAccountConstructor) XXX_Marshal(b []byte, deterministic bool) ([]byte, error) { + if deterministic { + return xxx_messageInfo_DefaultAccountConstructor.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 *DefaultAccountConstructor) XXX_Merge(src proto.Message) { + xxx_messageInfo_DefaultAccountConstructor.Merge(m, src) +} +func (m *DefaultAccountConstructor) XXX_Size() int { + return m.Size() +} +func (m *DefaultAccountConstructor) XXX_DiscardUnknown() { + xxx_messageInfo_DefaultAccountConstructor.DiscardUnknown(m) +} + +var xxx_messageInfo_DefaultAccountConstructor proto.InternalMessageInfo + +type DefaultRandomGenesisAccountsProvider struct { +} + +func (m *DefaultRandomGenesisAccountsProvider) Reset() { *m = DefaultRandomGenesisAccountsProvider{} } +func (m *DefaultRandomGenesisAccountsProvider) String() string { return proto.CompactTextString(m) } +func (*DefaultRandomGenesisAccountsProvider) ProtoMessage() {} +func (*DefaultRandomGenesisAccountsProvider) Descriptor() ([]byte, []int) { + return fileDescriptor_0f7f34be9f8952c0, []int{3} +} +func (m *DefaultRandomGenesisAccountsProvider) XXX_Unmarshal(b []byte) error { + return m.Unmarshal(b) +} +func (m *DefaultRandomGenesisAccountsProvider) XXX_Marshal(b []byte, deterministic bool) ([]byte, error) { + if deterministic { + return xxx_messageInfo_DefaultRandomGenesisAccountsProvider.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 *DefaultRandomGenesisAccountsProvider) XXX_Merge(src proto.Message) { + xxx_messageInfo_DefaultRandomGenesisAccountsProvider.Merge(m, src) +} +func (m *DefaultRandomGenesisAccountsProvider) XXX_Size() int { + return m.Size() +} +func (m *DefaultRandomGenesisAccountsProvider) XXX_DiscardUnknown() { + xxx_messageInfo_DefaultRandomGenesisAccountsProvider.DiscardUnknown(m) +} + +var xxx_messageInfo_DefaultRandomGenesisAccountsProvider proto.InternalMessageInfo + func init() { proto.RegisterType((*Module)(nil), "cosmos.auth.module.v1.Module") proto.RegisterType((*Permission)(nil), "cosmos.auth.module.v1.Permission") + proto.RegisterType((*DefaultAccountConstructor)(nil), "cosmos.auth.module.v1.DefaultAccountConstructor") + proto.RegisterType((*DefaultRandomGenesisAccountsProvider)(nil), "cosmos.auth.module.v1.DefaultRandomGenesisAccountsProvider") } func init() { @@ -141,24 +223,29 @@ func init() { } var fileDescriptor_0f7f34be9f8952c0 = []byte{ - // 271 bytes of a gzipped FileDescriptorProto - 0x1f, 0x8b, 0x08, 0x00, 0x00, 0x00, 0x00, 0x00, 0x02, 0xff, 0xe2, 0x52, 0x4a, 0xce, 0x2f, 0xce, - 0xcd, 0x2f, 0xd6, 0x4f, 0x2c, 0x2d, 0xc9, 0xd0, 0xcf, 0xcd, 0x4f, 0x29, 0xcd, 0x49, 0xd5, 0x2f, - 0x33, 0x84, 0xb2, 0xf4, 0x0a, 0x8a, 0xf2, 0x4b, 0xf2, 0x85, 0x44, 0x21, 0x6a, 0xf4, 0x40, 0x6a, - 0xf4, 0xa0, 0x32, 0x65, 0x86, 0x52, 0x92, 0xe9, 0xf9, 0xf9, 0xe9, 0x39, 0xa9, 0xfa, 0x60, 0x45, - 0x49, 0xa5, 0x69, 0xfa, 0x89, 0x79, 0x95, 0x10, 0x1d, 0x4a, 0x53, 0x18, 0xb9, 0xd8, 0x7c, 0xc1, - 0x0a, 0x85, 0x9c, 0xb9, 0xb8, 0x0b, 0x52, 0x8b, 0x72, 0x33, 0x8b, 0x8b, 0x33, 0xf3, 0xf3, 0x8a, - 0x25, 0x18, 0x15, 0x98, 0x35, 0xb8, 0x8d, 0x14, 0xf5, 0xb0, 0x1a, 0xa9, 0x17, 0x00, 0x57, 0x19, - 0x84, 0xac, 0x4b, 0xc8, 0x95, 0x4b, 0x38, 0x31, 0x39, 0x39, 0xbf, 0x34, 0xaf, 0x24, 0x3e, 0x39, - 0x3f, 0xaf, 0xb8, 0xa4, 0xa8, 0x34, 0xb9, 0x24, 0xbf, 0x48, 0x82, 0x49, 0x81, 0x51, 0x83, 0xdb, - 0x48, 0x44, 0x0f, 0xe2, 0x10, 0x3d, 0x98, 0x43, 0xf4, 0x1c, 0xf3, 0x2a, 0x83, 0x84, 0xa0, 0x1a, - 0x9c, 0x11, 0xea, 0x95, 0x3c, 0xb8, 0xb8, 0x10, 0x36, 0x08, 0x49, 0x70, 0xb1, 0x27, 0xa6, 0xa4, - 0x14, 0xa5, 0x16, 0x83, 0x5c, 0xc5, 0xa8, 0xc1, 0x19, 0x04, 0xe3, 0x0a, 0x29, 0xa0, 0xba, 0x99, - 0x49, 0x81, 0x59, 0x83, 0x13, 0xc5, 0x41, 0x4e, 0x2e, 0x27, 0x1e, 0xc9, 0x31, 0x5e, 0x78, 0x24, - 0xc7, 0xf8, 0xe0, 0x91, 0x1c, 0xe3, 0x84, 0xc7, 0x72, 0x0c, 0x17, 0x1e, 0xcb, 0x31, 0xdc, 0x78, - 0x2c, 0xc7, 0x10, 0xa5, 0x95, 0x9e, 0x59, 0x92, 0x51, 0x9a, 0xa4, 0x97, 0x9c, 0x9f, 0xab, 0x0f, - 0x0d, 0x5b, 0x08, 0xa5, 0x5b, 0x9c, 0x92, 0xad, 0x5f, 0x81, 0x1c, 0xd0, 0x49, 0x6c, 0x60, 0x17, - 0x1b, 0x03, 0x02, 0x00, 0x00, 0xff, 0xff, 0xf8, 0x35, 0x73, 0x5f, 0x85, 0x01, 0x00, 0x00, + // 338 bytes of a gzipped FileDescriptorProto + 0x1f, 0x8b, 0x08, 0x00, 0x00, 0x00, 0x00, 0x00, 0x02, 0xff, 0x7c, 0x92, 0xcf, 0x6a, 0xea, 0x40, + 0x14, 0x87, 0x1d, 0x05, 0x2f, 0x8e, 0xbb, 0xb9, 0xf7, 0x42, 0xbc, 0x97, 0x86, 0x34, 0x94, 0x12, + 0x0a, 0x9d, 0x41, 0xfb, 0x04, 0x56, 0x4b, 0xbb, 0x29, 0x48, 0x96, 0x85, 0x12, 0x62, 0x32, 0xc6, + 0x50, 0x33, 0x47, 0xe6, 0x8f, 0xd4, 0xb7, 0xe8, 0x63, 0x75, 0xe9, 0xb2, 0xcb, 0xa2, 0x8f, 0xd0, + 0x17, 0x28, 0x9a, 0xb1, 0x2a, 0x2d, 0xae, 0x92, 0xe1, 0x7c, 0xdf, 0xe1, 0xfc, 0xce, 0x0c, 0xf6, + 0x13, 0x50, 0x05, 0x28, 0x16, 0x1b, 0x3d, 0x66, 0x05, 0xa4, 0x66, 0xc2, 0xd9, 0xac, 0x6d, 0xff, + 0xe8, 0x54, 0x82, 0x06, 0xf2, 0xb7, 0x64, 0xe8, 0x9a, 0xa1, 0xb6, 0x32, 0x6b, 0xff, 0x6b, 0x65, + 0x00, 0xd9, 0x84, 0xb3, 0x0d, 0x34, 0x34, 0x23, 0x16, 0x8b, 0x79, 0x69, 0xf8, 0x1f, 0x08, 0xd7, + 0xef, 0x37, 0x20, 0xe9, 0xe1, 0xe6, 0x94, 0xcb, 0x22, 0x57, 0x2a, 0x07, 0xa1, 0x1c, 0xe4, 0xd5, + 0x82, 0x66, 0xe7, 0x94, 0xfe, 0xd8, 0x92, 0x0e, 0xbe, 0xc8, 0x70, 0xdf, 0x22, 0x37, 0xf8, 0x77, + 0x9c, 0x24, 0x60, 0x84, 0x8e, 0x12, 0x10, 0x4a, 0x4b, 0x93, 0x68, 0x90, 0x4e, 0xd5, 0x43, 0x41, + 0xb3, 0xf3, 0x87, 0x96, 0x83, 0xd0, 0xed, 0x20, 0xb4, 0x2b, 0xe6, 0x21, 0xb1, 0x42, 0x6f, 0xc7, + 0x93, 0x47, 0xec, 0xc9, 0x58, 0xa4, 0x50, 0x44, 0x19, 0x17, 0x5c, 0xe5, 0x2a, 0xb2, 0x90, 0x8a, + 0xa6, 0x12, 0x66, 0x79, 0xca, 0xa5, 0x53, 0x3b, 0xd2, 0xf3, 0xa4, 0xb4, 0x6f, 0x4b, 0xb9, 0x6b, + 0xdd, 0x81, 0x55, 0xfd, 0x3b, 0x8c, 0x77, 0x01, 0x88, 0x83, 0x7f, 0xc5, 0x69, 0x2a, 0xb9, 0x5a, + 0x87, 0x46, 0x41, 0x23, 0xdc, 0x1e, 0x89, 0x77, 0xb8, 0x92, 0xaa, 0x57, 0x0b, 0x1a, 0x07, 0x79, + 0xfd, 0xff, 0xb8, 0xd5, 0xe7, 0xa3, 0xd8, 0x4c, 0x74, 0xf7, 0x5b, 0x0a, 0xff, 0x1c, 0x9f, 0xd9, + 0x62, 0x78, 0x6c, 0x9c, 0xeb, 0xfe, 0xeb, 0xd2, 0x45, 0x8b, 0xa5, 0x8b, 0xde, 0x97, 0x2e, 0x7a, + 0x59, 0xb9, 0x95, 0xc5, 0xca, 0xad, 0xbc, 0xad, 0xdc, 0xca, 0xc3, 0x45, 0x96, 0xeb, 0xb1, 0x19, + 0xd2, 0x04, 0x0a, 0x66, 0xef, 0xbf, 0xfc, 0x5c, 0xaa, 0xf4, 0x89, 0x3d, 0xef, 0x3f, 0x86, 0x61, + 0x7d, 0xb3, 0x81, 0xab, 0xcf, 0x00, 0x00, 0x00, 0xff, 0xff, 0x88, 0x8b, 0x32, 0x17, 0x29, 0x02, + 0x00, 0x00, } func (m *Module) Marshal() (dAtA []byte, err error) { @@ -181,6 +268,18 @@ func (m *Module) MarshalToSizedBuffer(dAtA []byte) (int, error) { _ = i var l int _ = l + if m.RandomGenesisAccountsProvider != nil { + { + size, err := m.RandomGenesisAccountsProvider.MarshalToSizedBuffer(dAtA[:i]) + if err != nil { + return 0, err + } + i -= size + i = encodeVarintModule(dAtA, i, uint64(size)) + } + i-- + dAtA[i] = 0x1a + } if m.AccountConstructor != nil { { size, err := m.AccountConstructor.MarshalToSizedBuffer(dAtA[:i]) @@ -249,6 +348,52 @@ func (m *Permission) MarshalToSizedBuffer(dAtA []byte) (int, error) { return len(dAtA) - i, nil } +func (m *DefaultAccountConstructor) 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 *DefaultAccountConstructor) MarshalTo(dAtA []byte) (int, error) { + size := m.Size() + return m.MarshalToSizedBuffer(dAtA[:size]) +} + +func (m *DefaultAccountConstructor) MarshalToSizedBuffer(dAtA []byte) (int, error) { + i := len(dAtA) + _ = i + var l int + _ = l + return len(dAtA) - i, nil +} + +func (m *DefaultRandomGenesisAccountsProvider) 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 *DefaultRandomGenesisAccountsProvider) MarshalTo(dAtA []byte) (int, error) { + size := m.Size() + return m.MarshalToSizedBuffer(dAtA[:size]) +} + +func (m *DefaultRandomGenesisAccountsProvider) MarshalToSizedBuffer(dAtA []byte) (int, error) { + i := len(dAtA) + _ = i + var l int + _ = l + return len(dAtA) - i, nil +} + func encodeVarintModule(dAtA []byte, offset int, v uint64) int { offset -= sovModule(v) base := offset @@ -276,6 +421,10 @@ func (m *Module) Size() (n int) { l = m.AccountConstructor.Size() n += 1 + l + sovModule(uint64(l)) } + if m.RandomGenesisAccountsProvider != nil { + l = m.RandomGenesisAccountsProvider.Size() + n += 1 + l + sovModule(uint64(l)) + } return n } @@ -298,6 +447,24 @@ func (m *Permission) Size() (n int) { return n } +func (m *DefaultAccountConstructor) Size() (n int) { + if m == nil { + return 0 + } + var l int + _ = l + return n +} + +func (m *DefaultRandomGenesisAccountsProvider) Size() (n int) { + if m == nil { + return 0 + } + var l int + _ = l + return n +} + func sovModule(x uint64) (n int) { return (math_bits.Len64(x|1) + 6) / 7 } @@ -403,6 +570,42 @@ func (m *Module) Unmarshal(dAtA []byte) error { return err } iNdEx = postIndex + case 3: + if wireType != 2 { + return fmt.Errorf("proto: wrong wireType = %d for field RandomGenesisAccountsProvider", wireType) + } + var msglen int + for shift := uint(0); ; shift += 7 { + if shift >= 64 { + return ErrIntOverflowModule + } + if iNdEx >= l { + return io.ErrUnexpectedEOF + } + b := dAtA[iNdEx] + iNdEx++ + msglen |= int(b&0x7F) << shift + if b < 0x80 { + break + } + } + if msglen < 0 { + return ErrInvalidLengthModule + } + postIndex := iNdEx + msglen + if postIndex < 0 { + return ErrInvalidLengthModule + } + if postIndex > l { + return io.ErrUnexpectedEOF + } + if m.RandomGenesisAccountsProvider == nil { + m.RandomGenesisAccountsProvider = &types.Any{} + } + if err := m.RandomGenesisAccountsProvider.Unmarshal(dAtA[iNdEx:postIndex]); err != nil { + return err + } + iNdEx = postIndex default: iNdEx = preIndex skippy, err := skipModule(dAtA[iNdEx:]) @@ -538,6 +741,106 @@ func (m *Permission) Unmarshal(dAtA []byte) error { } return nil } +func (m *DefaultAccountConstructor) 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 ErrIntOverflowModule + } + 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: DefaultAccountConstructor: wiretype end group for non-group") + } + if fieldNum <= 0 { + return fmt.Errorf("proto: DefaultAccountConstructor: illegal tag %d (wire type %d)", fieldNum, wire) + } + switch fieldNum { + default: + iNdEx = preIndex + skippy, err := skipModule(dAtA[iNdEx:]) + if err != nil { + return err + } + if (skippy < 0) || (iNdEx+skippy) < 0 { + return ErrInvalidLengthModule + } + if (iNdEx + skippy) > l { + return io.ErrUnexpectedEOF + } + iNdEx += skippy + } + } + + if iNdEx > l { + return io.ErrUnexpectedEOF + } + return nil +} +func (m *DefaultRandomGenesisAccountsProvider) 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 ErrIntOverflowModule + } + 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: DefaultRandomGenesisAccountsProvider: wiretype end group for non-group") + } + if fieldNum <= 0 { + return fmt.Errorf("proto: DefaultRandomGenesisAccountsProvider: illegal tag %d (wire type %d)", fieldNum, wire) + } + switch fieldNum { + default: + iNdEx = preIndex + skippy, err := skipModule(dAtA[iNdEx:]) + if err != nil { + return err + } + if (skippy < 0) || (iNdEx+skippy) < 0 { + return ErrInvalidLengthModule + } + if (iNdEx + skippy) > l { + return io.ErrUnexpectedEOF + } + iNdEx += skippy + } + } + + if iNdEx > l { + return io.ErrUnexpectedEOF + } + return nil +} func skipModule(dAtA []byte) (n int, err error) { l := len(dAtA) iNdEx := 0 diff --git a/x/auth/types/genesis.go b/x/auth/types/genesis.go index 380d85fc6b81..4ecaed60d032 100644 --- a/x/auth/types/genesis.go +++ b/x/auth/types/genesis.go @@ -17,6 +17,10 @@ var _ types.UnpackInterfacesMessage = GenesisState{} // RandomGenesisAccountsFn defines the function required to generate custom account types type RandomGenesisAccountsFn func(simState *module.SimulationState) GenesisAccounts +type RandomGenesisAccountsProvider interface { + RandomGenesisAccounts(simState *module.SimulationState) GenesisAccounts +} + // NewGenesisState - Create a new genesis state func NewGenesisState(params Params, accounts GenesisAccounts) *GenesisState { genAccounts, err := PackAccounts(accounts) diff --git a/x/bank/module/module.pb.go b/x/bank/module/module.pb.go new file mode 100644 index 000000000000..5ded78f054a2 --- /dev/null +++ b/x/bank/module/module.pb.go @@ -0,0 +1,323 @@ +// Code generated by protoc-gen-gogo. DO NOT EDIT. +// source: cosmos/bank/module/v1/module.proto + +package module + +import ( + fmt "fmt" + proto "github.com/gogo/protobuf/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 + +type Module struct { + // TODO: this shouldn't be a config param, rather we should have a more generic + // solution, such as: blocked module accounts should register themselves in genesis + BlockedAddrs []string `protobuf:"bytes,1,rep,name=blocked_addrs,json=blockedAddrs,proto3" json:"blocked_addrs,omitempty"` +} + +func (m *Module) Reset() { *m = Module{} } +func (m *Module) String() string { return proto.CompactTextString(m) } +func (*Module) ProtoMessage() {} +func (*Module) Descriptor() ([]byte, []int) { + return fileDescriptor_a5851c1385b6c5fb, []int{0} +} +func (m *Module) XXX_Unmarshal(b []byte) error { + return m.Unmarshal(b) +} +func (m *Module) XXX_Marshal(b []byte, deterministic bool) ([]byte, error) { + if deterministic { + return xxx_messageInfo_Module.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 *Module) XXX_Merge(src proto.Message) { + xxx_messageInfo_Module.Merge(m, src) +} +func (m *Module) XXX_Size() int { + return m.Size() +} +func (m *Module) XXX_DiscardUnknown() { + xxx_messageInfo_Module.DiscardUnknown(m) +} + +var xxx_messageInfo_Module proto.InternalMessageInfo + +func (m *Module) GetBlockedAddrs() []string { + if m != nil { + return m.BlockedAddrs + } + return nil +} + +func init() { + proto.RegisterType((*Module)(nil), "cosmos.bank.module.v1.Module") +} + +func init() { + proto.RegisterFile("cosmos/bank/module/v1/module.proto", fileDescriptor_a5851c1385b6c5fb) +} + +var fileDescriptor_a5851c1385b6c5fb = []byte{ + // 161 bytes of a gzipped FileDescriptorProto + 0x1f, 0x8b, 0x08, 0x00, 0x00, 0x00, 0x00, 0x00, 0x02, 0xff, 0xe2, 0x52, 0x4a, 0xce, 0x2f, 0xce, + 0xcd, 0x2f, 0xd6, 0x4f, 0x4a, 0xcc, 0xcb, 0xd6, 0xcf, 0xcd, 0x4f, 0x29, 0xcd, 0x49, 0xd5, 0x2f, + 0x33, 0x84, 0xb2, 0xf4, 0x0a, 0x8a, 0xf2, 0x4b, 0xf2, 0x85, 0x44, 0x21, 0x6a, 0xf4, 0x40, 0x6a, + 0xf4, 0xa0, 0x32, 0x65, 0x86, 0x4a, 0xba, 0x5c, 0x6c, 0xbe, 0x60, 0x8e, 0x90, 0x32, 0x17, 0x6f, + 0x52, 0x4e, 0x7e, 0x72, 0x76, 0x6a, 0x4a, 0x7c, 0x62, 0x4a, 0x4a, 0x51, 0xb1, 0x04, 0xa3, 0x02, + 0xb3, 0x06, 0x67, 0x10, 0x0f, 0x54, 0xd0, 0x11, 0x24, 0xe6, 0xe4, 0x72, 0xe2, 0x91, 0x1c, 0xe3, + 0x85, 0x47, 0x72, 0x8c, 0x0f, 0x1e, 0xc9, 0x31, 0x4e, 0x78, 0x2c, 0xc7, 0x70, 0xe1, 0xb1, 0x1c, + 0xc3, 0x8d, 0xc7, 0x72, 0x0c, 0x51, 0x5a, 0xe9, 0x99, 0x25, 0x19, 0xa5, 0x49, 0x7a, 0xc9, 0xf9, + 0xb9, 0xfa, 0x50, 0xe7, 0x40, 0x28, 0xdd, 0xe2, 0x94, 0x6c, 0xfd, 0x0a, 0x64, 0xb7, 0x25, 0xb1, + 0x81, 0x9d, 0x64, 0x0c, 0x08, 0x00, 0x00, 0xff, 0xff, 0x9c, 0x38, 0x33, 0x52, 0xb8, 0x00, 0x00, + 0x00, +} + +func (m *Module) 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 *Module) MarshalTo(dAtA []byte) (int, error) { + size := m.Size() + return m.MarshalToSizedBuffer(dAtA[:size]) +} + +func (m *Module) MarshalToSizedBuffer(dAtA []byte) (int, error) { + i := len(dAtA) + _ = i + var l int + _ = l + if len(m.BlockedAddrs) > 0 { + for iNdEx := len(m.BlockedAddrs) - 1; iNdEx >= 0; iNdEx-- { + i -= len(m.BlockedAddrs[iNdEx]) + copy(dAtA[i:], m.BlockedAddrs[iNdEx]) + i = encodeVarintModule(dAtA, i, uint64(len(m.BlockedAddrs[iNdEx]))) + i-- + dAtA[i] = 0xa + } + } + return len(dAtA) - i, nil +} + +func encodeVarintModule(dAtA []byte, offset int, v uint64) int { + offset -= sovModule(v) + base := offset + for v >= 1<<7 { + dAtA[offset] = uint8(v&0x7f | 0x80) + v >>= 7 + offset++ + } + dAtA[offset] = uint8(v) + return base +} +func (m *Module) Size() (n int) { + if m == nil { + return 0 + } + var l int + _ = l + if len(m.BlockedAddrs) > 0 { + for _, s := range m.BlockedAddrs { + l = len(s) + n += 1 + l + sovModule(uint64(l)) + } + } + return n +} + +func sovModule(x uint64) (n int) { + return (math_bits.Len64(x|1) + 6) / 7 +} +func sozModule(x uint64) (n int) { + return sovModule(uint64((x << 1) ^ uint64((int64(x) >> 63)))) +} +func (m *Module) 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 ErrIntOverflowModule + } + 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: Module: wiretype end group for non-group") + } + if fieldNum <= 0 { + return fmt.Errorf("proto: Module: illegal tag %d (wire type %d)", fieldNum, wire) + } + switch fieldNum { + case 1: + if wireType != 2 { + return fmt.Errorf("proto: wrong wireType = %d for field BlockedAddrs", wireType) + } + var stringLen uint64 + for shift := uint(0); ; shift += 7 { + if shift >= 64 { + return ErrIntOverflowModule + } + 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 ErrInvalidLengthModule + } + postIndex := iNdEx + intStringLen + if postIndex < 0 { + return ErrInvalidLengthModule + } + if postIndex > l { + return io.ErrUnexpectedEOF + } + m.BlockedAddrs = append(m.BlockedAddrs, string(dAtA[iNdEx:postIndex])) + iNdEx = postIndex + default: + iNdEx = preIndex + skippy, err := skipModule(dAtA[iNdEx:]) + if err != nil { + return err + } + if (skippy < 0) || (iNdEx+skippy) < 0 { + return ErrInvalidLengthModule + } + if (iNdEx + skippy) > l { + return io.ErrUnexpectedEOF + } + iNdEx += skippy + } + } + + if iNdEx > l { + return io.ErrUnexpectedEOF + } + return nil +} +func skipModule(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, ErrIntOverflowModule + } + 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, ErrIntOverflowModule + } + 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, ErrIntOverflowModule + } + 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, ErrInvalidLengthModule + } + iNdEx += length + case 3: + depth++ + case 4: + if depth == 0 { + return 0, ErrUnexpectedEndOfGroupModule + } + depth-- + case 5: + iNdEx += 4 + default: + return 0, fmt.Errorf("proto: illegal wireType %d", wireType) + } + if iNdEx < 0 { + return 0, ErrInvalidLengthModule + } + if depth == 0 { + return iNdEx, nil + } + } + return 0, io.ErrUnexpectedEOF +} + +var ( + ErrInvalidLengthModule = fmt.Errorf("proto: negative length found during unmarshaling") + ErrIntOverflowModule = fmt.Errorf("proto: integer overflow") + ErrUnexpectedEndOfGroupModule = fmt.Errorf("proto: unexpected end of group") +) diff --git a/x/params/module/module.go b/x/params/module/module.go index a234804102eb..b33a15262e0f 100644 --- a/x/params/module/module.go +++ b/x/params/module/module.go @@ -12,6 +12,7 @@ import ( type Inputs struct { container.StructArgs + Codec codec.BinaryCodec LegacyAmino *codec.LegacyAmino Key *sdk.KVStoreKey From e7dbc83b13ef4f9d00a4c59397f9d78ff29a8e1a Mon Sep 17 00:00:00 2001 From: Aaron Craelius Date: Wed, 2 Jun 2021 11:49:44 -0400 Subject: [PATCH 05/24] WIP --- app/app_provider.go | 162 ----------------------------- app/cli/run.go | 6 +- app/{ => internal}/app.go | 195 +++++++++++++++++++++-------------- app/internal/app_provider.go | 110 ++++++++++++++++++++ app/internal/module.go | 23 +++++ container/container.go | 2 +- container/registrar.go | 2 +- x/params/module/module.go | 4 +- 8 files changed, 257 insertions(+), 247 deletions(-) delete mode 100644 app/app_provider.go rename app/{ => internal}/app.go (61%) create mode 100644 app/internal/app_provider.go create mode 100644 app/internal/module.go diff --git a/app/app_provider.go b/app/app_provider.go deleted file mode 100644 index f302f41c793e..000000000000 --- a/app/app_provider.go +++ /dev/null @@ -1,162 +0,0 @@ -package app - -import ( - "errors" - "io" - "path/filepath" - - "github.com/spf13/cast" - - "github.com/cosmos/cosmos-sdk/baseapp" - "github.com/cosmos/cosmos-sdk/client/flags" - "github.com/cosmos/cosmos-sdk/server" - "github.com/cosmos/cosmos-sdk/snapshots" - "github.com/cosmos/cosmos-sdk/store" - sdk "github.com/cosmos/cosmos-sdk/types" - - "github.com/cosmos/cosmos-sdk/container" - - "github.com/cosmos/cosmos-sdk/x/auth/tx" - - "github.com/cosmos/cosmos-sdk/client" - "github.com/cosmos/cosmos-sdk/codec" - codecTypes "github.com/cosmos/cosmos-sdk/codec/types" - - "github.com/tendermint/tendermint/libs/log" - dbm "github.com/tendermint/tm-db" - - servertypes "github.com/cosmos/cosmos-sdk/server/types" -) - -type AppProvider struct { - config *Config - container *container.Container - interfaceRegistry codecTypes.InterfaceRegistry - codec codec.Codec - txConfig client.TxConfig - amino *codec.LegacyAmino -} - -func (ap *AppProvider) InterfaceRegistry() codecTypes.InterfaceRegistry { - return ap.interfaceRegistry -} - -func (ap *AppProvider) Codec() codec.Codec { - return ap.codec -} - -func (ap *AppProvider) TxConfig() client.TxConfig { - return ap.txConfig -} - -func (ap *AppProvider) Amino() *codec.LegacyAmino { - return ap.amino -} - -func NewApp(config *Config) (*AppProvider, error) { - ctr := container.NewContainer() - interfaceRegistry := codecTypes.NewInterfaceRegistry() - marshaler := codec.NewProtoCodec(interfaceRegistry) - txConfig := tx.NewTxConfig(marshaler, tx.DefaultSignModes) - amino := codec.NewLegacyAmino() - - err := ctr.RegisterProvider(func() (codecTypes.InterfaceRegistry, codec.Codec, client.TxConfig, *codec.LegacyAmino) { - return interfaceRegistry, marshaler, txConfig, amino - }) - if err != nil { - return nil, err - } - - return &AppProvider{ - config: config, - container: ctr, - interfaceRegistry: interfaceRegistry, - codec: marshaler, - txConfig: txConfig, - amino: amino, - }, nil -} - -// NewApp is an AppCreator -func (ap *AppProvider) AppCreator( - logger log.Logger, - db dbm.DB, - traceStore io.Writer, - appOpts servertypes.AppOptions, -) servertypes.Application { - var cache sdk.MultiStorePersistentCache - - if cast.ToBool(appOpts.Get(server.FlagInterBlockCache)) { - cache = store.NewCommitKVStoreCacheManager() - } - - skipUpgradeHeights := make(map[int64]bool) - for _, h := range cast.ToIntSlice(appOpts.Get(server.FlagUnsafeSkipUpgrades)) { - skipUpgradeHeights[int64(h)] = true - } - - pruningOpts, err := server.GetPruningOptionsFromFlags(appOpts) - if err != nil { - panic(err) - } - - snapshotDir := filepath.Join(cast.ToString(appOpts.Get(flags.FlagHome)), "data", "snapshots") - snapshotDB, err := sdk.NewLevelDB("metadata", snapshotDir) - if err != nil { - panic(err) - } - snapshotStore, err := snapshots.NewStore(snapshotDB, snapshotDir) - if err != nil { - panic(err) - } - - return ap.newApp( - logger, db, traceStore, true, skipUpgradeHeights, - cast.ToString(appOpts.Get(flags.FlagHome)), - cast.ToUint(appOpts.Get(server.FlagInvCheckPeriod)), - appOpts, - baseapp.SetPruning(pruningOpts), - baseapp.SetMinGasPrices(cast.ToString(appOpts.Get(server.FlagMinGasPrices))), - baseapp.SetHaltHeight(cast.ToUint64(appOpts.Get(server.FlagHaltHeight))), - baseapp.SetHaltTime(cast.ToUint64(appOpts.Get(server.FlagHaltTime))), - baseapp.SetMinRetainBlocks(cast.ToUint64(appOpts.Get(server.FlagMinRetainBlocks))), - baseapp.SetInterBlockCache(cache), - baseapp.SetTrace(cast.ToBool(appOpts.Get(server.FlagTrace))), - baseapp.SetIndexEvents(cast.ToStringSlice(appOpts.Get(server.FlagIndexEvents))), - baseapp.SetSnapshotStore(snapshotStore), - baseapp.SetSnapshotInterval(cast.ToUint64(appOpts.Get(server.FlagStateSyncSnapshotInterval))), - baseapp.SetSnapshotKeepRecent(cast.ToUint32(appOpts.Get(server.FlagStateSyncSnapshotKeepRecent))), - ) -} - -func (ap *AppProvider) newApp( - logger log.Logger, db dbm.DB, traceStore io.Writer, loadLatest bool, skipUpgradeHeights map[int64]bool, - homePath string, invCheckPeriod uint, - appOpts servertypes.AppOptions, baseAppOptions ...func(*baseapp.BaseApp), -) *app { - return &app{} -} - -// AppExport creates a new app (optionally at a given height) and exports state. -func (ap *AppProvider) AppExportor( - logger log.Logger, db dbm.DB, traceStore io.Writer, height int64, forZeroHeight bool, jailAllowedAddrs []string, - appOpts servertypes.AppOptions) (servertypes.ExportedApp, error) { - - var a *app - homePath, ok := appOpts.Get(flags.FlagHome).(string) - if !ok || homePath == "" { - return servertypes.ExportedApp{}, errors.New("application home not set") - } - - if height != -1 { - a = ap.newApp(logger, db, traceStore, false, map[int64]bool{}, homePath, uint(1), appOpts) - - if err := a.LoadVersion(height); err != nil { - return servertypes.ExportedApp{}, err - } - } else { - a = ap.newApp(logger, db, traceStore, true, map[int64]bool{}, homePath, uint(1), appOpts) - } - - return a.exportAppStateAndValidators(forZeroHeight, jailAllowedAddrs) -} diff --git a/app/cli/run.go b/app/cli/run.go index 7bbfc3afbaaf..f88e7c1aa0c2 100644 --- a/app/cli/run.go +++ b/app/cli/run.go @@ -3,6 +3,8 @@ package cli import ( "os" + "github.com/cosmos/cosmos-sdk/app/internal" + "github.com/spf13/cobra" tmcli "github.com/tendermint/tendermint/libs/cli" @@ -46,7 +48,7 @@ func Run(options Options) { } func newRootCmd(options Options) *cobra.Command { - a, err := app.NewApp(options.DefaultAppConfig) + a, err := internal.NewApp(options.DefaultAppConfig) if err != nil { panic(err) } @@ -89,7 +91,7 @@ func newRootCmd(options Options) *cobra.Command { return rootCmd } -func initRootCmd(options Options, rootCmd *cobra.Command, a *app.AppProvider) { +func initRootCmd(options Options, rootCmd *cobra.Command, a *internal.AppProvider) { cfg := sdk.GetConfig() cfg.Seal() diff --git a/app/app.go b/app/internal/app.go similarity index 61% rename from app/app.go rename to app/internal/app.go index efc108fb1908..fabd0eceddb8 100644 --- a/app/app.go +++ b/app/internal/app.go @@ -1,30 +1,135 @@ -package app +package internal import ( + "errors" + "io" + "path/filepath" + + "github.com/tendermint/tendermint/libs/log" + + "github.com/cosmos/cosmos-sdk/client" + "github.com/cosmos/cosmos-sdk/client/flags" + "github.com/cosmos/cosmos-sdk/server" + "github.com/cosmos/cosmos-sdk/server/api" + "github.com/cosmos/cosmos-sdk/server/config" + "github.com/cosmos/cosmos-sdk/snapshots" + "github.com/cosmos/cosmos-sdk/store" "github.com/cosmos/cosmos-sdk/types/module" + "github.com/spf13/cast" + dbm "github.com/tendermint/tm-db" sdk "github.com/cosmos/cosmos-sdk/types" "github.com/cosmos/cosmos-sdk/baseapp" - grpc1 "github.com/gogo/protobuf/grpc" - abci "github.com/tendermint/tendermint/abci/types" - - "github.com/cosmos/cosmos-sdk/client" - "github.com/cosmos/cosmos-sdk/server/api" - "github.com/cosmos/cosmos-sdk/server/config" servertypes "github.com/cosmos/cosmos-sdk/server/types" ) -type app struct { +// NewApp is an AppCreator +func (ap *AppProvider) AppCreator( + logger log.Logger, + db dbm.DB, + traceStore io.Writer, + appOpts servertypes.AppOptions, +) servertypes.Application { + var cache sdk.MultiStorePersistentCache + + if cast.ToBool(appOpts.Get(server.FlagInterBlockCache)) { + cache = store.NewCommitKVStoreCacheManager() + } + + skipUpgradeHeights := make(map[int64]bool) + for _, h := range cast.ToIntSlice(appOpts.Get(server.FlagUnsafeSkipUpgrades)) { + skipUpgradeHeights[int64(h)] = true + } + + pruningOpts, err := server.GetPruningOptionsFromFlags(appOpts) + if err != nil { + panic(err) + } + + snapshotDir := filepath.Join(cast.ToString(appOpts.Get(flags.FlagHome)), "data", "snapshots") + snapshotDB, err := sdk.NewLevelDB("metadata", snapshotDir) + if err != nil { + panic(err) + } + snapshotStore, err := snapshots.NewStore(snapshotDB, snapshotDir) + if err != nil { + panic(err) + } + + return ap.newApp( + logger, db, traceStore, true, skipUpgradeHeights, + cast.ToString(appOpts.Get(flags.FlagHome)), + cast.ToUint(appOpts.Get(server.FlagInvCheckPeriod)), + appOpts, + baseapp.SetPruning(pruningOpts), + baseapp.SetMinGasPrices(cast.ToString(appOpts.Get(server.FlagMinGasPrices))), + baseapp.SetHaltHeight(cast.ToUint64(appOpts.Get(server.FlagHaltHeight))), + baseapp.SetHaltTime(cast.ToUint64(appOpts.Get(server.FlagHaltTime))), + baseapp.SetMinRetainBlocks(cast.ToUint64(appOpts.Get(server.FlagMinRetainBlocks))), + baseapp.SetInterBlockCache(cache), + baseapp.SetTrace(cast.ToBool(appOpts.Get(server.FlagTrace))), + baseapp.SetIndexEvents(cast.ToStringSlice(appOpts.Get(server.FlagIndexEvents))), + baseapp.SetSnapshotStore(snapshotStore), + baseapp.SetSnapshotInterval(cast.ToUint64(appOpts.Get(server.FlagStateSyncSnapshotInterval))), + baseapp.SetSnapshotKeepRecent(cast.ToUint32(appOpts.Get(server.FlagStateSyncSnapshotKeepRecent))), + ) +} + +func (ap *AppProvider) newApp( + logger log.Logger, db dbm.DB, traceStore io.Writer, loadLatest bool, skipUpgradeHeights map[int64]bool, + homePath string, invCheckPeriod uint, + appOpts servertypes.AppOptions, baseAppOptions ...func(*baseapp.BaseApp), +) *theApp { + return &theApp{} +} + +// AppExport creates a new app (optionally at a given height) and exports state. +func (ap *AppProvider) AppExportor( + logger log.Logger, db dbm.DB, traceStore io.Writer, height int64, forZeroHeight bool, jailAllowedAddrs []string, + appOpts servertypes.AppOptions) (servertypes.ExportedApp, error) { + + var a *theApp + homePath, ok := appOpts.Get(flags.FlagHome).(string) + if !ok || homePath == "" { + return servertypes.ExportedApp{}, errors.New("application home not set") + } + + if height != -1 { + a = ap.newApp(logger, db, traceStore, false, map[int64]bool{}, homePath, uint(1), appOpts) + + if err := a.LoadVersion(height); err != nil { + return servertypes.ExportedApp{}, err + } + } else { + a = ap.newApp(logger, db, traceStore, true, map[int64]bool{}, homePath, uint(1), appOpts) + } + + return a.exportAppStateAndValidators(forZeroHeight, jailAllowedAddrs) +} + +type theApp struct { *baseapp.BaseApp appProvider *AppProvider mm module.Manager } -var _ servertypes.Application = &app{} +var _ servertypes.Application = &theApp{} + +func (a *theApp) RegisterAPIRoutes(server *api.Server, config config.APIConfig) { + panic("implement me") +} -func (a *app) exportAppStateAndValidators( +func (a *theApp) RegisterTxService(clientCtx client.Context) { + panic("implement me") +} + +func (a *theApp) RegisterTendermintService(clientCtx client.Context) { + panic("implement me") +} + +func (a *theApp) exportAppStateAndValidators( forZeroHeight bool, jailAllowedAddrs []string, ) (servertypes.ExportedApp, error) { //// as if they could withdraw from the start of the next block @@ -54,75 +159,7 @@ func (a *app) exportAppStateAndValidators( //}, err } -func (a *app) Info(info abci.RequestInfo) abci.ResponseInfo { - panic("implement me") -} - -func (a *app) SetOption(option abci.RequestSetOption) abci.ResponseSetOption { - panic("implement me") -} - -func (a *app) Query(query abci.RequestQuery) abci.ResponseQuery { - panic("implement me") -} - -func (a *app) CheckTx(checkTx abci.RequestCheckTx) abci.ResponseCheckTx { - panic("implement me") -} - -func (a *app) InitChain(chain abci.RequestInitChain) abci.ResponseInitChain { - panic("implement me") -} - -func (a *app) BeginBlock(block abci.RequestBeginBlock) abci.ResponseBeginBlock { - panic("implement me") -} - -func (a *app) DeliverTx(deliverTx abci.RequestDeliverTx) abci.ResponseDeliverTx { - panic("implement me") -} - -func (a *app) EndBlock(block abci.RequestEndBlock) abci.ResponseEndBlock { - panic("implement me") -} - -func (a *app) Commit() abci.ResponseCommit { - panic("implement me") -} - -func (a *app) ListSnapshots(listSnapshots abci.RequestListSnapshots) abci.ResponseListSnapshots { - panic("implement me") -} - -func (a *app) OfferSnapshot(snapshot abci.RequestOfferSnapshot) abci.ResponseOfferSnapshot { - panic("implement me") -} - -func (a *app) LoadSnapshotChunk(chunk abci.RequestLoadSnapshotChunk) abci.ResponseLoadSnapshotChunk { - panic("implement me") -} - -func (a *app) ApplySnapshotChunk(chunk abci.RequestApplySnapshotChunk) abci.ResponseApplySnapshotChunk { - panic("implement me") -} - -func (a *app) RegisterAPIRoutes(a2 *api.Server, config config.APIConfig) { - panic("implement me") -} - -func (a *app) RegisterGRPCServer(context client.Context, g grpc1.Server) { - panic("implement me") -} - -func (a *app) RegisterTxService(clientCtx client.Context) { - panic("implement me") -} - -func (a *app) RegisterTendermintService(clientCtx client.Context) { - panic("implement me") -} - -func (a *app) prepForZeroHeightGenesis(ctx sdk.Context, jailAllowedAddrs []string) { +func (a *theApp) prepForZeroHeightGenesis(ctx sdk.Context, jailAllowedAddrs []string) { panic("TODO") //applyAllowedAddrs := false // diff --git a/app/internal/app_provider.go b/app/internal/app_provider.go new file mode 100644 index 000000000000..2add076bce22 --- /dev/null +++ b/app/internal/app_provider.go @@ -0,0 +1,110 @@ +package internal + +import ( + "fmt" + "reflect" + + "github.com/gogo/protobuf/proto" + + "github.com/cosmos/cosmos-sdk/app" + + "github.com/cosmos/cosmos-sdk/container" + + "github.com/cosmos/cosmos-sdk/x/auth/tx" + + "github.com/cosmos/cosmos-sdk/client" + "github.com/cosmos/cosmos-sdk/codec" + codecTypes "github.com/cosmos/cosmos-sdk/codec/types" +) + +type AppProvider struct { + config *app.Config + container *container.Container + interfaceRegistry codecTypes.InterfaceRegistry + codec codec.Codec + txConfig client.TxConfig + amino *codec.LegacyAmino + configMap map[string]interface{} + moduleConfigMap map[string]*app.ModuleConfig +} + +func (ap *AppProvider) InterfaceRegistry() codecTypes.InterfaceRegistry { + return ap.interfaceRegistry +} + +func (ap *AppProvider) Codec() codec.Codec { + return ap.codec +} + +func (ap *AppProvider) TxConfig() client.TxConfig { + return ap.txConfig +} + +func (ap *AppProvider) Amino() *codec.LegacyAmino { + return ap.amino +} + +func NewApp(config *app.Config) (*AppProvider, error) { + // create container + ctr := container.NewContainer() + + // provide encoding configs + interfaceRegistry := codecTypes.NewInterfaceRegistry() + marshaler := codec.NewProtoCodec(interfaceRegistry) + txConfig := tx.NewTxConfig(marshaler, tx.DefaultSignModes) + amino := codec.NewLegacyAmino() + err := ctr.Provide(func() (codecTypes.InterfaceRegistry, codec.Codec, client.TxConfig, *codec.LegacyAmino) { + return interfaceRegistry, marshaler, txConfig, amino + }) + if err != nil { + return nil, err + } + + // load configs + cfgMap := map[string]interface{}{} + moduleConfigMap := map[string]*app.ModuleConfig{} + + for _, modConfig := range config.Modules { + // unpack Any + msgTyp := proto.MessageType(modConfig.Config.TypeUrl) + cfg := reflect.New(msgTyp).Interface().(proto.Message) + if err := proto.Unmarshal(modConfig.Config.Value, cfg); err != nil { + return nil, err + } + + // resolve module name + name := modConfig.Name + if name == "" { + if named, ok := cfg.(Named); ok { + name = named.Name() + } else { + return nil, fmt.Errorf("unnamed module config %+v", modConfig) + } + } + + // save in config map + cfgMap[name] = cfg + moduleConfigMap[name] = modConfig + + // register types + if typeProvider, ok := cfg.(TypeProvider); ok { + typeProvider.RegisterInterfaces(interfaceRegistry) + } + + // register DI providers + if provisioner, ok := cfg.(Provisioner); ok { + provisioner.Provision(ctr) + } + } + + return &AppProvider{ + config: config, + container: ctr, + interfaceRegistry: interfaceRegistry, + codec: marshaler, + txConfig: txConfig, + amino: amino, + configMap: cfgMap, + moduleConfigMap: moduleConfigMap, + }, nil +} diff --git a/app/internal/module.go b/app/internal/module.go new file mode 100644 index 000000000000..647b3af4e9a7 --- /dev/null +++ b/app/internal/module.go @@ -0,0 +1,23 @@ +package internal + +import ( + "github.com/cosmos/cosmos-sdk/codec/types" + "github.com/cosmos/cosmos-sdk/container" + "github.com/cosmos/cosmos-sdk/types/module" +) + +type Named interface { + Name() string +} + +type TypeProvider interface { + RegisterInterfaces(registry types.InterfaceRegistry) +} + +type Handler interface { + RegisterServices(configurator module.Configurator) +} + +type Provisioner interface { + Provision(registrar container.Registrar) +} diff --git a/container/container.go b/container/container.go index 6302487dbf6e..39be8066f0fb 100644 --- a/container/container.go +++ b/container/container.go @@ -9,7 +9,7 @@ func NewContainer() *Container { panic("TODO") } -func (c *Container) RegisterProvider(fn interface{}) error { +func (c *Container) Provide(fn interface{}) error { panic("implement me") } diff --git a/container/registrar.go b/container/registrar.go index 1d09df746495..d9e9e37b2b80 100644 --- a/container/registrar.go +++ b/container/registrar.go @@ -1,5 +1,5 @@ package container type Registrar interface { - RegisterProvider(fn interface{}) error + Provide(fn interface{}) error } diff --git a/x/params/module/module.go b/x/params/module/module.go index b33a15262e0f..74130682053c 100644 --- a/x/params/module/module.go +++ b/x/params/module/module.go @@ -32,8 +32,8 @@ func (m Module) NewAppModule(inputs Inputs) (module.AppModule, Outputs, error) { return appMod, Outputs{Keeper: keeper}, nil } -func (m Module) Provide(registrar container.Registrar) error { - return registrar.RegisterProvider(func(scope container.Scope, keeper paramskeeper.Keeper) types.Subspace { +func (m Module) Provision(registrar container.Registrar) error { + return registrar.Provide(func(scope container.Scope, keeper paramskeeper.Keeper) types.Subspace { return keeper.Subspace(string(scope)) }) } From 252453f7518bb6d7724e33aaca87af45c672ef93 Mon Sep 17 00:00:00 2001 From: Aaron Craelius Date: Wed, 2 Jun 2021 16:48:22 -0400 Subject: [PATCH 06/24] wire up gov proposal handlers --- app/config.pb.go | 381 +++++++++++++++++++++++- app/internal/app_provider.go | 2 +- app/internal/module.go | 5 - app/provisioner.go | 7 + app/visitor.go | 9 + docs/core/proto-docs.md | 48 +++ proto/cosmos/gov/module/v1/module.proto | 8 + x/gov/module/module.go | 57 ++++ x/gov/module/module.pb.go | 262 ++++++++++++++++ x/gov/types/router.go | 7 +- x/params/module/module.go | 12 +- 11 files changed, 774 insertions(+), 24 deletions(-) create mode 100644 app/provisioner.go create mode 100644 app/visitor.go create mode 100644 proto/cosmos/gov/module/v1/module.proto create mode 100644 x/gov/module/module.go create mode 100644 x/gov/module/module.pb.go diff --git a/app/config.pb.go b/app/config.pb.go index 608f2f427e22..2aeed21caedb 100644 --- a/app/config.pb.go +++ b/app/config.pb.go @@ -25,6 +25,7 @@ const _ = proto.GoGoProtoPackageIsVersion3 // please upgrade the proto package type Config struct { Modules []*ModuleConfig `protobuf:"bytes,1,rep,name=modules,proto3" json:"modules,omitempty"` + Abci *ABCIHandlers `protobuf:"bytes,2,opt,name=abci,proto3" json:"abci,omitempty"` } func (m *Config) Reset() { *m = Config{} } @@ -67,6 +68,13 @@ func (m *Config) GetModules() []*ModuleConfig { return nil } +func (m *Config) GetAbci() *ABCIHandlers { + if m != nil { + return m.Abci + } + return nil +} + type ModuleConfig struct { Config *types.Any `protobuf:"bytes,1,opt,name=config,proto3" json:"config,omitempty"` Name string `protobuf:"bytes,2,opt,name=name,proto3" json:"name,omitempty"` @@ -119,30 +127,96 @@ func (m *ModuleConfig) GetName() string { return "" } +type ABCIHandlers struct { + InitGenesis []string `protobuf:"bytes,1,rep,name=init_genesis,json=initGenesis,proto3" json:"init_genesis,omitempty"` + BeginBlock []string `protobuf:"bytes,2,rep,name=begin_block,json=beginBlock,proto3" json:"begin_block,omitempty"` + EndBlock []string `protobuf:"bytes,3,rep,name=end_block,json=endBlock,proto3" json:"end_block,omitempty"` +} + +func (m *ABCIHandlers) Reset() { *m = ABCIHandlers{} } +func (m *ABCIHandlers) String() string { return proto.CompactTextString(m) } +func (*ABCIHandlers) ProtoMessage() {} +func (*ABCIHandlers) Descriptor() ([]byte, []int) { + return fileDescriptor_9c5c7e08cb1a0bd9, []int{2} +} +func (m *ABCIHandlers) XXX_Unmarshal(b []byte) error { + return m.Unmarshal(b) +} +func (m *ABCIHandlers) XXX_Marshal(b []byte, deterministic bool) ([]byte, error) { + if deterministic { + return xxx_messageInfo_ABCIHandlers.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 *ABCIHandlers) XXX_Merge(src proto.Message) { + xxx_messageInfo_ABCIHandlers.Merge(m, src) +} +func (m *ABCIHandlers) XXX_Size() int { + return m.Size() +} +func (m *ABCIHandlers) XXX_DiscardUnknown() { + xxx_messageInfo_ABCIHandlers.DiscardUnknown(m) +} + +var xxx_messageInfo_ABCIHandlers proto.InternalMessageInfo + +func (m *ABCIHandlers) GetInitGenesis() []string { + if m != nil { + return m.InitGenesis + } + return nil +} + +func (m *ABCIHandlers) GetBeginBlock() []string { + if m != nil { + return m.BeginBlock + } + return nil +} + +func (m *ABCIHandlers) GetEndBlock() []string { + if m != nil { + return m.EndBlock + } + return nil +} + func init() { proto.RegisterType((*Config)(nil), "cosmos.app.v1.Config") proto.RegisterType((*ModuleConfig)(nil), "cosmos.app.v1.ModuleConfig") + proto.RegisterType((*ABCIHandlers)(nil), "cosmos.app.v1.ABCIHandlers") } func init() { proto.RegisterFile("cosmos/app/v1/config.proto", fileDescriptor_9c5c7e08cb1a0bd9) } var fileDescriptor_9c5c7e08cb1a0bd9 = []byte{ - // 227 bytes of a gzipped FileDescriptorProto - 0x1f, 0x8b, 0x08, 0x00, 0x00, 0x00, 0x00, 0x00, 0x02, 0xff, 0xe2, 0x92, 0x4a, 0xce, 0x2f, 0xce, - 0xcd, 0x2f, 0xd6, 0x4f, 0x2c, 0x28, 0xd0, 0x2f, 0x33, 0xd4, 0x4f, 0xce, 0xcf, 0x4b, 0xcb, 0x4c, - 0xd7, 0x2b, 0x28, 0xca, 0x2f, 0xc9, 0x17, 0xe2, 0x85, 0xc8, 0xe9, 0x25, 0x16, 0x14, 0xe8, 0x95, - 0x19, 0x4a, 0x49, 0xa6, 0xe7, 0xe7, 0xa7, 0xe7, 0xa4, 0xea, 0x83, 0x25, 0x93, 0x4a, 0xd3, 0xf4, - 0x13, 0xf3, 0x2a, 0x21, 0x2a, 0x95, 0xec, 0xb9, 0xd8, 0x9c, 0xc1, 0x3a, 0x85, 0x4c, 0xb9, 0xd8, - 0x73, 0xf3, 0x53, 0x4a, 0x73, 0x52, 0x8b, 0x25, 0x18, 0x15, 0x98, 0x35, 0xb8, 0x8d, 0xa4, 0xf5, - 0x50, 0x4c, 0xd1, 0xf3, 0x05, 0xcb, 0x42, 0x54, 0x07, 0xc1, 0xd4, 0x2a, 0x05, 0x70, 0xf1, 0x20, - 0x4b, 0x08, 0xe9, 0x70, 0xb1, 0x41, 0x9c, 0x22, 0xc1, 0xa8, 0xc0, 0xa8, 0xc1, 0x6d, 0x24, 0xa2, - 0x07, 0xb1, 0x5c, 0x0f, 0x66, 0xb9, 0x9e, 0x63, 0x5e, 0x65, 0x10, 0x54, 0x8d, 0x90, 0x10, 0x17, - 0x4b, 0x5e, 0x62, 0x6e, 0xaa, 0x04, 0x93, 0x02, 0xa3, 0x06, 0x67, 0x10, 0x98, 0xed, 0x64, 0x75, - 0xe2, 0x91, 0x1c, 0xe3, 0x85, 0x47, 0x72, 0x8c, 0x0f, 0x1e, 0xc9, 0x31, 0x4e, 0x78, 0x2c, 0xc7, - 0x70, 0xe1, 0xb1, 0x1c, 0xc3, 0x8d, 0xc7, 0x72, 0x0c, 0x51, 0x0a, 0xe9, 0x99, 0x25, 0x19, 0xa5, - 0x49, 0x7a, 0xc9, 0xf9, 0xb9, 0xfa, 0x50, 0xdf, 0x43, 0x28, 0xdd, 0xe2, 0x94, 0x6c, 0x50, 0x40, - 0x24, 0xb1, 0x81, 0x6d, 0x31, 0x06, 0x04, 0x00, 0x00, 0xff, 0xff, 0x52, 0x6f, 0xad, 0x11, 0x1d, - 0x01, 0x00, 0x00, + // 316 bytes of a gzipped FileDescriptorProto + 0x1f, 0x8b, 0x08, 0x00, 0x00, 0x00, 0x00, 0x00, 0x02, 0xff, 0x6c, 0x91, 0x31, 0x4f, 0x02, 0x31, + 0x14, 0xc7, 0x39, 0x20, 0x28, 0x0f, 0x5c, 0x1a, 0x87, 0x13, 0x92, 0x13, 0x99, 0x1c, 0xb4, 0x0d, + 0x1a, 0x17, 0x37, 0x60, 0x50, 0x07, 0x13, 0x73, 0xa3, 0x0b, 0xb9, 0xde, 0x95, 0xda, 0x70, 0xd7, + 0x36, 0x14, 0x48, 0xf8, 0x16, 0x7e, 0x2c, 0x47, 0x46, 0x47, 0x03, 0x5f, 0xc4, 0xf0, 0x7a, 0x24, + 0x98, 0x38, 0xb5, 0xf9, 0xff, 0x7f, 0xef, 0xbd, 0xff, 0xcb, 0x83, 0x4e, 0x6a, 0x5c, 0x61, 0x1c, + 0x4b, 0xac, 0x65, 0xab, 0x01, 0x4b, 0x8d, 0x9e, 0x2a, 0x49, 0xed, 0xdc, 0x2c, 0x0c, 0x39, 0xf3, + 0x1e, 0x4d, 0xac, 0xa5, 0xab, 0x41, 0xe7, 0x42, 0x1a, 0x23, 0x73, 0xc1, 0xd0, 0xe4, 0xcb, 0x29, + 0x4b, 0xf4, 0xda, 0x93, 0x7d, 0x0b, 0x8d, 0x31, 0x56, 0x92, 0x07, 0x38, 0x29, 0x4c, 0xb6, 0xcc, + 0x85, 0x0b, 0x83, 0x5e, 0xed, 0xba, 0x75, 0xd7, 0xa5, 0x7f, 0xba, 0xd0, 0x57, 0x74, 0x3d, 0x1d, + 0x1f, 0x58, 0xc2, 0xa0, 0x9e, 0xf0, 0x54, 0x85, 0xd5, 0x5e, 0xf0, 0x4f, 0xcd, 0x70, 0x34, 0x7e, + 0x79, 0x4e, 0x74, 0x96, 0x8b, 0xb9, 0x8b, 0x11, 0xec, 0xbf, 0x41, 0xfb, 0xb8, 0x13, 0xb9, 0x81, + 0x86, 0xcf, 0x1e, 0x06, 0xd8, 0xe2, 0x9c, 0xfa, 0xb4, 0xf4, 0x90, 0x96, 0x0e, 0xf5, 0x3a, 0x2e, + 0x19, 0x42, 0xa0, 0xae, 0x93, 0x42, 0xe0, 0xb8, 0x66, 0x8c, 0xff, 0xbe, 0x81, 0xf6, 0xf1, 0x1c, + 0x72, 0x05, 0x6d, 0xa5, 0xd5, 0x62, 0x22, 0x85, 0x16, 0x4e, 0xf9, 0x75, 0x9a, 0x71, 0x6b, 0xaf, + 0x3d, 0x79, 0x89, 0x5c, 0x42, 0x8b, 0x0b, 0xa9, 0xf4, 0x84, 0xe7, 0x26, 0x9d, 0x85, 0x55, 0x24, + 0x00, 0xa5, 0xd1, 0x5e, 0x21, 0x5d, 0x68, 0x0a, 0x9d, 0x95, 0x76, 0x0d, 0xed, 0x53, 0xa1, 0x33, + 0x34, 0x47, 0x8f, 0x5f, 0xdb, 0x28, 0xd8, 0x6c, 0xa3, 0xe0, 0x67, 0x1b, 0x05, 0x9f, 0xbb, 0xa8, + 0xb2, 0xd9, 0x45, 0x95, 0xef, 0x5d, 0x54, 0x79, 0xef, 0x49, 0xb5, 0xf8, 0x58, 0x72, 0x9a, 0x9a, + 0x82, 0x95, 0xf7, 0xf1, 0xcf, 0xad, 0xcb, 0x66, 0xfb, 0x53, 0xf1, 0x06, 0xae, 0x75, 0xff, 0x1b, + 0x00, 0x00, 0xff, 0xff, 0x7b, 0xf5, 0x60, 0xab, 0xbf, 0x01, 0x00, 0x00, } func (m *Config) Marshal() (dAtA []byte, err error) { @@ -165,6 +239,18 @@ func (m *Config) MarshalToSizedBuffer(dAtA []byte) (int, error) { _ = i var l int _ = l + if m.Abci != nil { + { + size, err := m.Abci.MarshalToSizedBuffer(dAtA[:i]) + if err != nil { + return 0, err + } + i -= size + i = encodeVarintConfig(dAtA, i, uint64(size)) + } + i-- + dAtA[i] = 0x12 + } if len(m.Modules) > 0 { for iNdEx := len(m.Modules) - 1; iNdEx >= 0; iNdEx-- { { @@ -224,6 +310,56 @@ func (m *ModuleConfig) MarshalToSizedBuffer(dAtA []byte) (int, error) { return len(dAtA) - i, nil } +func (m *ABCIHandlers) 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 *ABCIHandlers) MarshalTo(dAtA []byte) (int, error) { + size := m.Size() + return m.MarshalToSizedBuffer(dAtA[:size]) +} + +func (m *ABCIHandlers) MarshalToSizedBuffer(dAtA []byte) (int, error) { + i := len(dAtA) + _ = i + var l int + _ = l + if len(m.EndBlock) > 0 { + for iNdEx := len(m.EndBlock) - 1; iNdEx >= 0; iNdEx-- { + i -= len(m.EndBlock[iNdEx]) + copy(dAtA[i:], m.EndBlock[iNdEx]) + i = encodeVarintConfig(dAtA, i, uint64(len(m.EndBlock[iNdEx]))) + i-- + dAtA[i] = 0x1a + } + } + if len(m.BeginBlock) > 0 { + for iNdEx := len(m.BeginBlock) - 1; iNdEx >= 0; iNdEx-- { + i -= len(m.BeginBlock[iNdEx]) + copy(dAtA[i:], m.BeginBlock[iNdEx]) + i = encodeVarintConfig(dAtA, i, uint64(len(m.BeginBlock[iNdEx]))) + i-- + dAtA[i] = 0x12 + } + } + if len(m.InitGenesis) > 0 { + for iNdEx := len(m.InitGenesis) - 1; iNdEx >= 0; iNdEx-- { + i -= len(m.InitGenesis[iNdEx]) + copy(dAtA[i:], m.InitGenesis[iNdEx]) + i = encodeVarintConfig(dAtA, i, uint64(len(m.InitGenesis[iNdEx]))) + i-- + dAtA[i] = 0xa + } + } + return len(dAtA) - i, nil +} + func encodeVarintConfig(dAtA []byte, offset int, v uint64) int { offset -= sovConfig(v) base := offset @@ -247,6 +383,10 @@ func (m *Config) Size() (n int) { n += 1 + l + sovConfig(uint64(l)) } } + if m.Abci != nil { + l = m.Abci.Size() + n += 1 + l + sovConfig(uint64(l)) + } return n } @@ -267,6 +407,33 @@ func (m *ModuleConfig) Size() (n int) { return n } +func (m *ABCIHandlers) Size() (n int) { + if m == nil { + return 0 + } + var l int + _ = l + if len(m.InitGenesis) > 0 { + for _, s := range m.InitGenesis { + l = len(s) + n += 1 + l + sovConfig(uint64(l)) + } + } + if len(m.BeginBlock) > 0 { + for _, s := range m.BeginBlock { + l = len(s) + n += 1 + l + sovConfig(uint64(l)) + } + } + if len(m.EndBlock) > 0 { + for _, s := range m.EndBlock { + l = len(s) + n += 1 + l + sovConfig(uint64(l)) + } + } + return n +} + func sovConfig(x uint64) (n int) { return (math_bits.Len64(x|1) + 6) / 7 } @@ -336,6 +503,42 @@ func (m *Config) Unmarshal(dAtA []byte) error { return err } iNdEx = postIndex + case 2: + if wireType != 2 { + return fmt.Errorf("proto: wrong wireType = %d for field Abci", wireType) + } + var msglen int + for shift := uint(0); ; shift += 7 { + if shift >= 64 { + return ErrIntOverflowConfig + } + if iNdEx >= l { + return io.ErrUnexpectedEOF + } + b := dAtA[iNdEx] + iNdEx++ + msglen |= int(b&0x7F) << shift + if b < 0x80 { + break + } + } + if msglen < 0 { + return ErrInvalidLengthConfig + } + postIndex := iNdEx + msglen + if postIndex < 0 { + return ErrInvalidLengthConfig + } + if postIndex > l { + return io.ErrUnexpectedEOF + } + if m.Abci == nil { + m.Abci = &ABCIHandlers{} + } + if err := m.Abci.Unmarshal(dAtA[iNdEx:postIndex]); err != nil { + return err + } + iNdEx = postIndex default: iNdEx = preIndex skippy, err := skipConfig(dAtA[iNdEx:]) @@ -475,6 +678,152 @@ func (m *ModuleConfig) Unmarshal(dAtA []byte) error { } return nil } +func (m *ABCIHandlers) 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 ErrIntOverflowConfig + } + 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: ABCIHandlers: wiretype end group for non-group") + } + if fieldNum <= 0 { + return fmt.Errorf("proto: ABCIHandlers: illegal tag %d (wire type %d)", fieldNum, wire) + } + switch fieldNum { + case 1: + if wireType != 2 { + return fmt.Errorf("proto: wrong wireType = %d for field InitGenesis", wireType) + } + var stringLen uint64 + for shift := uint(0); ; shift += 7 { + if shift >= 64 { + return ErrIntOverflowConfig + } + 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 ErrInvalidLengthConfig + } + postIndex := iNdEx + intStringLen + if postIndex < 0 { + return ErrInvalidLengthConfig + } + if postIndex > l { + return io.ErrUnexpectedEOF + } + m.InitGenesis = append(m.InitGenesis, string(dAtA[iNdEx:postIndex])) + iNdEx = postIndex + case 2: + if wireType != 2 { + return fmt.Errorf("proto: wrong wireType = %d for field BeginBlock", wireType) + } + var stringLen uint64 + for shift := uint(0); ; shift += 7 { + if shift >= 64 { + return ErrIntOverflowConfig + } + 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 ErrInvalidLengthConfig + } + postIndex := iNdEx + intStringLen + if postIndex < 0 { + return ErrInvalidLengthConfig + } + if postIndex > l { + return io.ErrUnexpectedEOF + } + m.BeginBlock = append(m.BeginBlock, string(dAtA[iNdEx:postIndex])) + iNdEx = postIndex + case 3: + if wireType != 2 { + return fmt.Errorf("proto: wrong wireType = %d for field EndBlock", wireType) + } + var stringLen uint64 + for shift := uint(0); ; shift += 7 { + if shift >= 64 { + return ErrIntOverflowConfig + } + 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 ErrInvalidLengthConfig + } + postIndex := iNdEx + intStringLen + if postIndex < 0 { + return ErrInvalidLengthConfig + } + if postIndex > l { + return io.ErrUnexpectedEOF + } + m.EndBlock = append(m.EndBlock, string(dAtA[iNdEx:postIndex])) + iNdEx = postIndex + default: + iNdEx = preIndex + skippy, err := skipConfig(dAtA[iNdEx:]) + if err != nil { + return err + } + if (skippy < 0) || (iNdEx+skippy) < 0 { + return ErrInvalidLengthConfig + } + if (iNdEx + skippy) > l { + return io.ErrUnexpectedEOF + } + iNdEx += skippy + } + } + + if iNdEx > l { + return io.ErrUnexpectedEOF + } + return nil +} func skipConfig(dAtA []byte) (n int, err error) { l := len(dAtA) iNdEx := 0 diff --git a/app/internal/app_provider.go b/app/internal/app_provider.go index 2add076bce22..be49d09b415d 100644 --- a/app/internal/app_provider.go +++ b/app/internal/app_provider.go @@ -92,7 +92,7 @@ func NewApp(config *app.Config) (*AppProvider, error) { } // register DI providers - if provisioner, ok := cfg.(Provisioner); ok { + if provisioner, ok := cfg.(app.Provisioner); ok { provisioner.Provision(ctr) } } diff --git a/app/internal/module.go b/app/internal/module.go index 647b3af4e9a7..c123427f9020 100644 --- a/app/internal/module.go +++ b/app/internal/module.go @@ -2,7 +2,6 @@ package internal import ( "github.com/cosmos/cosmos-sdk/codec/types" - "github.com/cosmos/cosmos-sdk/container" "github.com/cosmos/cosmos-sdk/types/module" ) @@ -17,7 +16,3 @@ type TypeProvider interface { type Handler interface { RegisterServices(configurator module.Configurator) } - -type Provisioner interface { - Provision(registrar container.Registrar) -} diff --git a/app/provisioner.go b/app/provisioner.go new file mode 100644 index 000000000000..19370eb4c26b --- /dev/null +++ b/app/provisioner.go @@ -0,0 +1,7 @@ +package app + +import "github.com/cosmos/cosmos-sdk/container" + +type Provisioner interface { + Provision(registrar container.Registrar) error +} diff --git a/app/visitor.go b/app/visitor.go new file mode 100644 index 000000000000..cd522c3f7ecc --- /dev/null +++ b/app/visitor.go @@ -0,0 +1,9 @@ +package app + +type HandlerVisitor interface { + VisitAppHandler(info HandlerInfo, handler interface{}) +} + +type HandlerInfo struct { + Name string +} diff --git a/docs/core/proto-docs.md b/docs/core/proto-docs.md index 8b9701673ade..7ca920804077 100644 --- a/docs/core/proto-docs.md +++ b/docs/core/proto-docs.md @@ -5,6 +5,7 @@ ## Table of Contents - [cosmos/app/v1/config.proto](#cosmos/app/v1/config.proto) + - [ABCIHandlers](#cosmos.app.v1.ABCIHandlers) - [Config](#cosmos.app.v1.Config) - [ModuleConfig](#cosmos.app.v1.ModuleConfig) @@ -348,6 +349,9 @@ - [cosmos/genutil/v1beta1/genesis.proto](#cosmos/genutil/v1beta1/genesis.proto) - [GenesisState](#cosmos.genutil.v1beta1.GenesisState) +- [cosmos/gov/module/v1/module.proto](#cosmos/gov/module/v1/module.proto) + - [Module](#cosmos.gov.module.v1.Module) + - [cosmos/gov/v1beta1/gov.proto](#cosmos/gov/v1beta1/gov.proto) - [Deposit](#cosmos.gov.v1beta1.Deposit) - [DepositParams](#cosmos.gov.v1beta1.DepositParams) @@ -612,6 +616,23 @@ + + +### ABCIHandlers + + + +| Field | Type | Label | Description | +| ----- | ---- | ----- | ----------- | +| `init_genesis` | [string](#string) | repeated | | +| `begin_block` | [string](#string) | repeated | | +| `end_block` | [string](#string) | repeated | | + + + + + + ### Config @@ -621,6 +642,7 @@ | Field | Type | Label | Description | | ----- | ---- | ----- | ----------- | | `modules` | [ModuleConfig](#cosmos.app.v1.ModuleConfig) | repeated | | +| `abci` | [ABCIHandlers](#cosmos.app.v1.ABCIHandlers) | | | @@ -5012,6 +5034,32 @@ GenesisState defines the raw genesis transaction in JSON. + + + + + + + + + + + +

Top

+ +## cosmos/gov/module/v1/module.proto + + + + + +### Module + + + + + + diff --git a/proto/cosmos/gov/module/v1/module.proto b/proto/cosmos/gov/module/v1/module.proto new file mode 100644 index 000000000000..fcf4e6240da3 --- /dev/null +++ b/proto/cosmos/gov/module/v1/module.proto @@ -0,0 +1,8 @@ +syntax = "proto3"; +package cosmos.gov.module.v1; + +option go_package = "github.com/cosmos/cosmos-sdk/x/gov/module"; + +message Module { + +} diff --git a/x/gov/module/module.go b/x/gov/module/module.go new file mode 100644 index 000000000000..3b0d4f2a9653 --- /dev/null +++ b/x/gov/module/module.go @@ -0,0 +1,57 @@ +package module + +import ( + "github.com/cosmos/cosmos-sdk/app" + "github.com/cosmos/cosmos-sdk/codec" + "github.com/cosmos/cosmos-sdk/container" + sdk "github.com/cosmos/cosmos-sdk/types" + "github.com/cosmos/cosmos-sdk/types/module" + "github.com/cosmos/cosmos-sdk/x/gov" + govkeeper "github.com/cosmos/cosmos-sdk/x/gov/keeper" + govtypes "github.com/cosmos/cosmos-sdk/x/gov/types" + paramtypes "github.com/cosmos/cosmos-sdk/x/params/types" +) + +var ( + _ app.Provisioner = &Module{} +) + +func (m *Module) Provision(registrar container.Registrar) error { + return registrar.Provide(func() govtypes.Router { + return govtypes.NewRouter() + }) +} + +type Inputs struct { + container.StructArgs + + Router govtypes.Router + Codec codec.Codec + Key *sdk.KVStoreKey + ParamStore paramtypes.Subspace + + // TODO: use keepers defined in their respective modules + AuthKeeper govtypes.AccountKeeper + BankKeeper govtypes.BankKeeper + StakingKeeper govtypes.StakingKeeper +} + +type Outputs struct { + container.StructArgs +} + +func (m *Module) NewAppHandler(inputs Inputs) (module.AppModule, Outputs) { + k := govkeeper.NewKeeper( + inputs.Codec, + inputs.Key, + inputs.ParamStore, + inputs.AuthKeeper, + inputs.BankKeeper, + inputs.StakingKeeper, + inputs.Router, + ) + + am := gov.NewAppModule(inputs.Codec, k, inputs.AuthKeeper, inputs.BankKeeper) + + return am, Outputs{} +} diff --git a/x/gov/module/module.pb.go b/x/gov/module/module.pb.go new file mode 100644 index 000000000000..e42abcc86ad3 --- /dev/null +++ b/x/gov/module/module.pb.go @@ -0,0 +1,262 @@ +// Code generated by protoc-gen-gogo. DO NOT EDIT. +// source: cosmos/gov/module/v1/module.proto + +package module + +import ( + fmt "fmt" + proto "github.com/gogo/protobuf/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 + +type Module struct { +} + +func (m *Module) Reset() { *m = Module{} } +func (m *Module) String() string { return proto.CompactTextString(m) } +func (*Module) ProtoMessage() {} +func (*Module) Descriptor() ([]byte, []int) { + return fileDescriptor_ff104e9858c6f1e6, []int{0} +} +func (m *Module) XXX_Unmarshal(b []byte) error { + return m.Unmarshal(b) +} +func (m *Module) XXX_Marshal(b []byte, deterministic bool) ([]byte, error) { + if deterministic { + return xxx_messageInfo_Module.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 *Module) XXX_Merge(src proto.Message) { + xxx_messageInfo_Module.Merge(m, src) +} +func (m *Module) XXX_Size() int { + return m.Size() +} +func (m *Module) XXX_DiscardUnknown() { + xxx_messageInfo_Module.DiscardUnknown(m) +} + +var xxx_messageInfo_Module proto.InternalMessageInfo + +func init() { + proto.RegisterType((*Module)(nil), "cosmos.gov.module.v1.Module") +} + +func init() { proto.RegisterFile("cosmos/gov/module/v1/module.proto", fileDescriptor_ff104e9858c6f1e6) } + +var fileDescriptor_ff104e9858c6f1e6 = []byte{ + // 131 bytes of a gzipped FileDescriptorProto + 0x1f, 0x8b, 0x08, 0x00, 0x00, 0x00, 0x00, 0x00, 0x02, 0xff, 0xe2, 0x52, 0x4c, 0xce, 0x2f, 0xce, + 0xcd, 0x2f, 0xd6, 0x4f, 0xcf, 0x2f, 0xd3, 0xcf, 0xcd, 0x4f, 0x29, 0xcd, 0x49, 0xd5, 0x2f, 0x33, + 0x84, 0xb2, 0xf4, 0x0a, 0x8a, 0xf2, 0x4b, 0xf2, 0x85, 0x44, 0x20, 0x4a, 0xf4, 0xd2, 0xf3, 0xcb, + 0xf4, 0xa0, 0x12, 0x65, 0x86, 0x4a, 0x1c, 0x5c, 0x6c, 0xbe, 0x60, 0x8e, 0x93, 0xf3, 0x89, 0x47, + 0x72, 0x8c, 0x17, 0x1e, 0xc9, 0x31, 0x3e, 0x78, 0x24, 0xc7, 0x38, 0xe1, 0xb1, 0x1c, 0xc3, 0x85, + 0xc7, 0x72, 0x0c, 0x37, 0x1e, 0xcb, 0x31, 0x44, 0x69, 0xa6, 0x67, 0x96, 0x64, 0x94, 0x26, 0xe9, + 0x25, 0xe7, 0xe7, 0xea, 0x43, 0xed, 0x81, 0x50, 0xba, 0xc5, 0x29, 0xd9, 0xfa, 0x15, 0x48, 0x96, + 0x26, 0xb1, 0x81, 0xed, 0x32, 0x06, 0x04, 0x00, 0x00, 0xff, 0xff, 0xdd, 0x5b, 0x71, 0xf1, 0x90, + 0x00, 0x00, 0x00, +} + +func (m *Module) 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 *Module) MarshalTo(dAtA []byte) (int, error) { + size := m.Size() + return m.MarshalToSizedBuffer(dAtA[:size]) +} + +func (m *Module) MarshalToSizedBuffer(dAtA []byte) (int, error) { + i := len(dAtA) + _ = i + var l int + _ = l + return len(dAtA) - i, nil +} + +func encodeVarintModule(dAtA []byte, offset int, v uint64) int { + offset -= sovModule(v) + base := offset + for v >= 1<<7 { + dAtA[offset] = uint8(v&0x7f | 0x80) + v >>= 7 + offset++ + } + dAtA[offset] = uint8(v) + return base +} +func (m *Module) Size() (n int) { + if m == nil { + return 0 + } + var l int + _ = l + return n +} + +func sovModule(x uint64) (n int) { + return (math_bits.Len64(x|1) + 6) / 7 +} +func sozModule(x uint64) (n int) { + return sovModule(uint64((x << 1) ^ uint64((int64(x) >> 63)))) +} +func (m *Module) 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 ErrIntOverflowModule + } + 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: Module: wiretype end group for non-group") + } + if fieldNum <= 0 { + return fmt.Errorf("proto: Module: illegal tag %d (wire type %d)", fieldNum, wire) + } + switch fieldNum { + default: + iNdEx = preIndex + skippy, err := skipModule(dAtA[iNdEx:]) + if err != nil { + return err + } + if (skippy < 0) || (iNdEx+skippy) < 0 { + return ErrInvalidLengthModule + } + if (iNdEx + skippy) > l { + return io.ErrUnexpectedEOF + } + iNdEx += skippy + } + } + + if iNdEx > l { + return io.ErrUnexpectedEOF + } + return nil +} +func skipModule(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, ErrIntOverflowModule + } + 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, ErrIntOverflowModule + } + 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, ErrIntOverflowModule + } + 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, ErrInvalidLengthModule + } + iNdEx += length + case 3: + depth++ + case 4: + if depth == 0 { + return 0, ErrUnexpectedEndOfGroupModule + } + depth-- + case 5: + iNdEx += 4 + default: + return 0, fmt.Errorf("proto: illegal wireType %d", wireType) + } + if iNdEx < 0 { + return 0, ErrInvalidLengthModule + } + if depth == 0 { + return iNdEx, nil + } + } + return 0, io.ErrUnexpectedEOF +} + +var ( + ErrInvalidLengthModule = fmt.Errorf("proto: negative length found during unmarshaling") + ErrIntOverflowModule = fmt.Errorf("proto: integer overflow") + ErrUnexpectedEndOfGroupModule = fmt.Errorf("proto: unexpected end of group") +) diff --git a/x/gov/types/router.go b/x/gov/types/router.go index bc4d51251d56..abb59e7a72e0 100644 --- a/x/gov/types/router.go +++ b/x/gov/types/router.go @@ -12,12 +12,17 @@ var _ Router = (*router)(nil) // // TODO: Use generic router (ref #3976). type Router interface { - AddRoute(r string, h Handler) (rtr Router) + Registrar + HasRoute(r string) bool GetRoute(path string) (h Handler) Seal() } +type Registrar interface { + AddRoute(r string, h Handler) (rtr Router) +} + type router struct { routes map[string]Handler sealed bool diff --git a/x/params/module/module.go b/x/params/module/module.go index 74130682053c..d8c27dfb454b 100644 --- a/x/params/module/module.go +++ b/x/params/module/module.go @@ -1,13 +1,20 @@ package module import ( + "github.com/cosmos/cosmos-sdk/app" "github.com/cosmos/cosmos-sdk/codec" "github.com/cosmos/cosmos-sdk/container" sdk "github.com/cosmos/cosmos-sdk/types" "github.com/cosmos/cosmos-sdk/types/module" + govtypes "github.com/cosmos/cosmos-sdk/x/gov/types" "github.com/cosmos/cosmos-sdk/x/params" paramskeeper "github.com/cosmos/cosmos-sdk/x/params/keeper" "github.com/cosmos/cosmos-sdk/x/params/types" + paramproposal "github.com/cosmos/cosmos-sdk/x/params/types/proposal" +) + +var ( + _ app.Provisioner = &Module{} ) type Inputs struct { @@ -17,6 +24,7 @@ type Inputs struct { LegacyAmino *codec.LegacyAmino Key *sdk.KVStoreKey TransientKey *sdk.TransientStoreKey + GovRouter govtypes.Router } type Outputs struct { @@ -25,10 +33,12 @@ type Outputs struct { Keeper paramskeeper.Keeper `security-role:"admin"` } -func (m Module) NewAppModule(inputs Inputs) (module.AppModule, Outputs, error) { +func (m Module) NewAppHandler(inputs Inputs) (module.AppModule, Outputs, error) { keeper := paramskeeper.NewKeeper(inputs.Codec, inputs.LegacyAmino, inputs.Key, inputs.TransientKey) appMod := params.NewAppModule(keeper) + inputs.GovRouter.AddRoute(paramproposal.RouterKey, params.NewParamChangeProposalHandler(keeper)) + return appMod, Outputs{Keeper: keeper}, nil } From e2f01845a3ebf40ba386edc21dbdad48c3c181d4 Mon Sep 17 00:00:00 2001 From: Aaron Craelius Date: Wed, 2 Jun 2021 16:51:24 -0400 Subject: [PATCH 07/24] update simapp2 --- simapp/v2/app.go | 7 ++++++- simapp/v2/app.yaml | 4 +++- 2 files changed, 9 insertions(+), 2 deletions(-) diff --git a/simapp/v2/app.go b/simapp/v2/app.go index 179fdb8c1d59..01ecec2f5c7a 100644 --- a/simapp/v2/app.go +++ b/simapp/v2/app.go @@ -3,9 +3,14 @@ package main import ( _ "embed" + "github.com/cosmos/cosmos-sdk/app" "github.com/cosmos/cosmos-sdk/app/cli" - "github.com/cosmos/cosmos-sdk/app" + // Load Modules + _ "github.com/cosmos/cosmos-sdk/x/auth/module" + _ "github.com/cosmos/cosmos-sdk/x/bank/module" + _ "github.com/cosmos/cosmos-sdk/x/gov/module" + _ "github.com/cosmos/cosmos-sdk/x/params/module" ) //go:embed app.yaml diff --git a/simapp/v2/app.yaml b/simapp/v2/app.yaml index 399cd481883e..e125eb690702 100644 --- a/simapp/v2/app.yaml +++ b/simapp/v2/app.yaml @@ -4,4 +4,6 @@ modules: - config: @type: cosmos.bank.module.v1.Module - config: - @type: cosmos.params.module.v1.Module \ No newline at end of file + @type: cosmos.params.module.v1.Module + - config: + @type: cosmos.gov.module.v1.Module From ac35b56ede018e893a828f0e7281ba1e332fb827 Mon Sep 17 00:00:00 2001 From: Aaron Craelius Date: Wed, 2 Jun 2021 18:24:41 -0400 Subject: [PATCH 08/24] approach 2 --- app/cli/configurator.go | 17 ++++ app/cli/run.go | 29 +++---- app/compat/adapter.go | 46 +++++++++++ app/configurator.go | 33 ++++++++ app/internal/app.go | 15 +++- app/internal/app_provider.go | 9 ++- app/internal/module.go | 5 -- app/internal/providers.go | 15 ++++ app/type_provider.go | 7 ++ app/visitor.go | 9 --- x/auth/module/module.go | 153 ++++++++++++++++++++--------------- x/auth/module/module.pb.go | 5 +- x/auth/module/view_keeper.go | 38 +++++++++ x/gov/module/module.go | 47 ++++++----- x/gov/module/module.pb.go | 3 +- x/params/module/module.go | 21 +++-- 16 files changed, 327 insertions(+), 125 deletions(-) create mode 100644 app/cli/configurator.go create mode 100644 app/compat/adapter.go create mode 100644 app/configurator.go create mode 100644 app/internal/providers.go create mode 100644 app/type_provider.go delete mode 100644 app/visitor.go create mode 100644 x/auth/module/view_keeper.go diff --git a/app/cli/configurator.go b/app/cli/configurator.go new file mode 100644 index 000000000000..287855172e69 --- /dev/null +++ b/app/cli/configurator.go @@ -0,0 +1,17 @@ +package cli + +import ( + "github.com/spf13/cobra" + + "github.com/cosmos/cosmos-sdk/app" +) + +type Configurator interface { + SetGenesisHandler(handler app.GenesisBasicHandler) + SetTxCommand(command *cobra.Command) + SetQueryCommand(command *cobra.Command) + + RootCommand() *cobra.Command + RootTxCommand() *cobra.Command + RootQueryCommand() *cobra.Command +} diff --git a/app/cli/run.go b/app/cli/run.go index f88e7c1aa0c2..b2130de4de9a 100644 --- a/app/cli/run.go +++ b/app/cli/run.go @@ -19,7 +19,6 @@ import ( svrcmd "github.com/cosmos/cosmos-sdk/server/cmd" "github.com/cosmos/cosmos-sdk/simapp" sdk "github.com/cosmos/cosmos-sdk/types" - authcmd "github.com/cosmos/cosmos-sdk/x/auth/client/cli" "github.com/cosmos/cosmos-sdk/x/auth/types" vestingcli "github.com/cosmos/cosmos-sdk/x/auth/vesting/client/cli" banktypes "github.com/cosmos/cosmos-sdk/x/bank/types" @@ -137,11 +136,12 @@ func queryCommand() *cobra.Command { } cmd.AddCommand( - authcmd.GetAccountCmd(), + // NOTE: moved these to the auth module: + //authcmd.GetAccountCmd(), rpc.ValidatorCommand(), rpc.BlockCommand(), - authcmd.QueryTxsByEventsCmd(), - authcmd.QueryTxCmd(), + //authcmd.QueryTxsByEventsCmd(), + //authcmd.QueryTxCmd(), ) simapp.ModuleBasics.AddQueryCommands(cmd) @@ -160,16 +160,17 @@ func txCommand() *cobra.Command { } cmd.AddCommand( - authcmd.GetSignCommand(), - authcmd.GetSignBatchCommand(), - authcmd.GetMultiSignCommand(), - authcmd.GetMultiSignBatchCmd(), - authcmd.GetValidateSignaturesCommand(), - flags.LineBreak, - authcmd.GetBroadcastCommand(), - authcmd.GetEncodeCommand(), - authcmd.GetDecodeCommand(), - flags.LineBreak, + // NOTE: moved these to the auth module: + //authcmd.GetSignCommand(), + //authcmd.GetSignBatchCommand(), + //authcmd.GetMultiSignCommand(), + //authcmd.GetMultiSignBatchCmd(), + //authcmd.GetValidateSignaturesCommand(), + //flags.LineBreak, + //authcmd.GetBroadcastCommand(), + //authcmd.GetEncodeCommand(), + //authcmd.GetDecodeCommand(), + //flags.LineBreak, vestingcli.GetTxCmd(), ) diff --git a/app/compat/adapter.go b/app/compat/adapter.go new file mode 100644 index 000000000000..02bea74c3f4e --- /dev/null +++ b/app/compat/adapter.go @@ -0,0 +1,46 @@ +package compat + +import ( + "context" + "encoding/json" + + "github.com/cosmos/cosmos-sdk/app/cli" + + abci "github.com/tendermint/tendermint/abci/types" + + "github.com/cosmos/cosmos-sdk/app" + "github.com/cosmos/cosmos-sdk/codec" + "github.com/cosmos/cosmos-sdk/types" + "github.com/cosmos/cosmos-sdk/types/module" +) + +func RegisterAppModuleBasic(configurator cli.Configurator, module module.AppModuleBasic) { + configurator.SetTxCommand(module.GetTxCmd()) + configurator.SetQueryCommand(module.GetQueryCmd()) + configurator.SetGenesisHandler(module) +} + +func RegisterAppModule(configurator app.Configurator, module module.AppModule) { + module.RegisterServices(configurator) + configurator.RegisterBeginBlocker(func(ctx context.Context, req abci.RequestBeginBlock) { + module.BeginBlock(types.UnwrapSDKContext(ctx), req) + }) + configurator.RegisterEndBlocker(func(ctx context.Context, req abci.RequestEndBlock) []abci.ValidatorUpdate { + return module.EndBlock(types.UnwrapSDKContext(ctx), req) + }) + configurator.RegisterGenesisHandler(genesisWrapper{module}) +} + +type genesisWrapper struct { + module.AppModule +} + +func (g genesisWrapper) InitGenesis(ctx context.Context, codec codec.JSONCodec, message json.RawMessage) []abci.ValidatorUpdate { + return g.AppModule.InitGenesis(types.UnwrapSDKContext(ctx), codec, message) +} + +func (g genesisWrapper) ExportGenesis(ctx context.Context, codec codec.JSONCodec) json.RawMessage { + return g.AppModule.ExportGenesis(types.UnwrapSDKContext(ctx), codec) +} + +var _ app.GenesisHandler = genesisWrapper{} diff --git a/app/configurator.go b/app/configurator.go new file mode 100644 index 000000000000..5d42ef9e75e1 --- /dev/null +++ b/app/configurator.go @@ -0,0 +1,33 @@ +package app + +import ( + "context" + "encoding/json" + + "github.com/cosmos/cosmos-sdk/client" + + abci "github.com/tendermint/tendermint/abci/types" + + "github.com/cosmos/cosmos-sdk/codec" + "github.com/cosmos/cosmos-sdk/types/module" +) + +type Configurator interface { + module.Configurator + + RegisterBeginBlocker(func(context.Context, abci.RequestBeginBlock)) + RegisterEndBlocker(func(context.Context, abci.RequestEndBlock) []abci.ValidatorUpdate) + RegisterGenesisHandler(handler GenesisHandler) +} + +type GenesisBasicHandler interface { + DefaultGenesis(codec.JSONCodec) json.RawMessage + ValidateGenesis(codec.JSONCodec, client.TxEncodingConfig, json.RawMessage) error +} + +type GenesisHandler interface { + GenesisBasicHandler + + InitGenesis(context.Context, codec.JSONCodec, json.RawMessage) []abci.ValidatorUpdate + ExportGenesis(context.Context, codec.JSONCodec) json.RawMessage +} diff --git a/app/internal/app.go b/app/internal/app.go index fabd0eceddb8..303f247d3c62 100644 --- a/app/internal/app.go +++ b/app/internal/app.go @@ -7,6 +7,9 @@ import ( "github.com/tendermint/tendermint/libs/log" + "github.com/spf13/cast" + dbm "github.com/tendermint/tm-db" + "github.com/cosmos/cosmos-sdk/client" "github.com/cosmos/cosmos-sdk/client/flags" "github.com/cosmos/cosmos-sdk/server" @@ -15,8 +18,6 @@ import ( "github.com/cosmos/cosmos-sdk/snapshots" "github.com/cosmos/cosmos-sdk/store" "github.com/cosmos/cosmos-sdk/types/module" - "github.com/spf13/cast" - dbm "github.com/tendermint/tm-db" sdk "github.com/cosmos/cosmos-sdk/types" @@ -32,6 +33,16 @@ func (ap *AppProvider) AppCreator( traceStore io.Writer, appOpts servertypes.AppOptions, ) servertypes.Application { + err := ap.container.Provide(KVStoreKeyProvider) + if err != nil { + panic(err) + } + + err = ap.container.Provide(ConfiguratorProvider) + if err != nil { + panic(err) + } + var cache sdk.MultiStorePersistentCache if cast.ToBool(appOpts.Get(server.FlagInterBlockCache)) { diff --git a/app/internal/app_provider.go b/app/internal/app_provider.go index be49d09b415d..6c5a97e881bc 100644 --- a/app/internal/app_provider.go +++ b/app/internal/app_provider.go @@ -87,13 +87,16 @@ func NewApp(config *app.Config) (*AppProvider, error) { moduleConfigMap[name] = modConfig // register types - if typeProvider, ok := cfg.(TypeProvider); ok { - typeProvider.RegisterInterfaces(interfaceRegistry) + if typeProvider, ok := cfg.(app.TypeProvider); ok { + typeProvider.RegisterTypes(interfaceRegistry) } // register DI providers if provisioner, ok := cfg.(app.Provisioner); ok { - provisioner.Provision(ctr) + err = provisioner.Provision(ctr) + if err != nil { + return nil, err + } } } diff --git a/app/internal/module.go b/app/internal/module.go index c123427f9020..0e19890606ee 100644 --- a/app/internal/module.go +++ b/app/internal/module.go @@ -1,7 +1,6 @@ package internal import ( - "github.com/cosmos/cosmos-sdk/codec/types" "github.com/cosmos/cosmos-sdk/types/module" ) @@ -9,10 +8,6 @@ type Named interface { Name() string } -type TypeProvider interface { - RegisterInterfaces(registry types.InterfaceRegistry) -} - type Handler interface { RegisterServices(configurator module.Configurator) } diff --git a/app/internal/providers.go b/app/internal/providers.go new file mode 100644 index 000000000000..cefba0c995d4 --- /dev/null +++ b/app/internal/providers.go @@ -0,0 +1,15 @@ +package internal + +import ( + "github.com/cosmos/cosmos-sdk/app" + "github.com/cosmos/cosmos-sdk/container" + "github.com/cosmos/cosmos-sdk/types" +) + +func KVStoreKeyProvider(scope container.Scope) *types.KVStoreKey { + return types.NewKVStoreKey(string(scope)) +} + +func ConfiguratorProvider(scope container.Scope) app.Configurator { + panic("TODO") +} diff --git a/app/type_provider.go b/app/type_provider.go new file mode 100644 index 000000000000..ccf559a3f74d --- /dev/null +++ b/app/type_provider.go @@ -0,0 +1,7 @@ +package app + +import "github.com/cosmos/cosmos-sdk/codec/types" + +type TypeProvider interface { + RegisterTypes(registry types.InterfaceRegistry) +} diff --git a/app/visitor.go b/app/visitor.go deleted file mode 100644 index cd522c3f7ecc..000000000000 --- a/app/visitor.go +++ /dev/null @@ -1,9 +0,0 @@ -package app - -type HandlerVisitor interface { - VisitAppHandler(info HandlerInfo, handler interface{}) -} - -type HandlerInfo struct { - Name string -} diff --git a/x/auth/module/module.go b/x/auth/module/module.go index 404e8bedc766..5bc11d1308bc 100644 --- a/x/auth/module/module.go +++ b/x/auth/module/module.go @@ -1,17 +1,29 @@ package module import ( + "github.com/cosmos/cosmos-sdk/app" + "github.com/cosmos/cosmos-sdk/app/cli" + "github.com/cosmos/cosmos-sdk/app/compat" + "github.com/cosmos/cosmos-sdk/client" + "github.com/cosmos/cosmos-sdk/client/flags" "github.com/cosmos/cosmos-sdk/codec" + codectypes "github.com/cosmos/cosmos-sdk/codec/types" "github.com/cosmos/cosmos-sdk/container" sdk "github.com/cosmos/cosmos-sdk/types" "github.com/cosmos/cosmos-sdk/types/module" "github.com/cosmos/cosmos-sdk/x/auth" + authcmd "github.com/cosmos/cosmos-sdk/x/auth/client/cli" authkeeper "github.com/cosmos/cosmos-sdk/x/auth/keeper" "github.com/cosmos/cosmos-sdk/x/auth/simulation" "github.com/cosmos/cosmos-sdk/x/auth/types" paramtypes "github.com/cosmos/cosmos-sdk/x/params/types" ) +var ( + _ app.TypeProvider = Module{} + _ app.Provisioner = Module{} +) + type Inputs struct { container.StructArgs @@ -27,76 +39,91 @@ type Outputs struct { Keeper types.Keeper `security-role:"admin"` } -func (m Module) NewAppModule(inputs Inputs) (module.AppModule, Outputs, error) { - var accCtr types.AccountConstructor - if m.AccountConstructor != nil { - err := inputs.Codec.UnpackAny(m.AccountConstructor, &accCtr) - if err != nil { - return nil, Outputs{}, err - } - } else { - accCtr = DefaultAccountConstructor{} - } - - perms := map[string][]string{} - for _, perm := range m.Permissions { - perms[perm.Address] = perm.Permissions - } +func (m Module) RegisterTypes(registry codectypes.InterfaceRegistry) { + types.RegisterInterfaces(registry) +} - var randomGenesisAccountsProvider types.RandomGenesisAccountsProvider - if m.RandomGenesisAccountsProvider != nil { - err := inputs.Codec.UnpackAny(m.RandomGenesisAccountsProvider, &randomGenesisAccountsProvider) - if err != nil { - return nil, Outputs{}, err - } - } else { - randomGenesisAccountsProvider = DefaultRandomGenesisAccountsProvider{} +func (m Module) Provision(registrar container.Registrar) error { + // provide AccountRetriever + err := registrar.Provide(func() client.AccountRetriever { + return types.AccountRetriever{} + }) + if err != nil { + return err } - keeper := authkeeper.NewAccountKeeper(inputs.Codec, inputs.Key, inputs.ParamStore, func() types.AccountI { - return accCtr.NewAccount() - }, perms) - appMod := auth.NewAppModule(inputs.Codec, keeper, func(simState *module.SimulationState) types.GenesisAccounts { - return randomGenesisAccountsProvider.RandomGenesisAccounts(simState) + // provide CLI handlers + err = registrar.Provide(func(configurator cli.Configurator) { + configurator.RootQueryCommand().AddCommand( + authcmd.GetAccountCmd(), + authcmd.QueryTxsByEventsCmd(), + authcmd.QueryTxCmd(), + ) + + configurator.RootTxCommand().AddCommand( + authcmd.GetSignCommand(), + authcmd.GetSignBatchCommand(), + authcmd.GetMultiSignCommand(), + authcmd.GetMultiSignBatchCmd(), + authcmd.GetValidateSignaturesCommand(), + flags.LineBreak, + authcmd.GetBroadcastCommand(), + authcmd.GetEncodeCommand(), + authcmd.GetDecodeCommand(), + flags.LineBreak, + ) + + compat.RegisterAppModuleBasic(configurator, auth.AppModuleBasic{}) }) + if err != nil { + return err + } - return appMod, Outputs{ - ViewKeeper: viewOnlyKeeper{keeper}, - Keeper: keeper, - }, nil -} - -// viewOnlyKeeper wraps the full keeper in a view-only interface which can't be easily type cast to the full keeper interface -type viewOnlyKeeper struct { - k authkeeper.AccountKeeper -} - -func (v viewOnlyKeeper) GetAccount(ctx sdk.Context, addr sdk.AccAddress) types.AccountI { - return v.k.GetAccount(ctx, addr) -} - -func (v viewOnlyKeeper) GetModuleAddress(moduleName string) sdk.AccAddress { - return v.k.GetModuleAddress(moduleName) -} - -func (v viewOnlyKeeper) ValidatePermissions(macc types.ModuleAccountI) error { - return v.k.ValidatePermissions(macc) -} - -func (v viewOnlyKeeper) GetModuleAddressAndPermissions(moduleName string) (addr sdk.AccAddress, permissions []string) { - return v.GetModuleAddressAndPermissions(moduleName) -} - -func (v viewOnlyKeeper) GetModuleAccountAndPermissions(ctx sdk.Context, moduleName string) (types.ModuleAccountI, []string) { - return v.GetModuleAccountAndPermissions(ctx, moduleName) -} - -func (v viewOnlyKeeper) GetModuleAccount(ctx sdk.Context, moduleName string) types.ModuleAccountI { - return v.k.GetModuleAccount(ctx, moduleName) + // provide app handlers + return registrar.Provide( + func(configurator app.Configurator, inputs Inputs) (Outputs, error) { + var accCtr types.AccountConstructor + if m.AccountConstructor != nil { + err := inputs.Codec.UnpackAny(m.AccountConstructor, &accCtr) + if err != nil { + return Outputs{}, err + } + } else { + accCtr = DefaultAccountConstructor{} + } + + perms := map[string][]string{} + for _, perm := range m.Permissions { + perms[perm.Address] = perm.Permissions + } + + var randomGenesisAccountsProvider types.RandomGenesisAccountsProvider + if m.RandomGenesisAccountsProvider != nil { + err := inputs.Codec.UnpackAny(m.RandomGenesisAccountsProvider, &randomGenesisAccountsProvider) + if err != nil { + return Outputs{}, err + } + } else { + randomGenesisAccountsProvider = DefaultRandomGenesisAccountsProvider{} + } + + keeper := authkeeper.NewAccountKeeper(inputs.Codec, inputs.Key, inputs.ParamStore, func() types.AccountI { + return accCtr.NewAccount() + }, perms) + appMod := auth.NewAppModule(inputs.Codec, keeper, func(simState *module.SimulationState) types.GenesisAccounts { + return randomGenesisAccountsProvider.RandomGenesisAccounts(simState) + }) + + compat.RegisterAppModule(configurator, appMod) + + return Outputs{ + ViewKeeper: viewOnlyKeeper{keeper}, + Keeper: keeper, + }, nil + }, + ) } -var _ types.ViewKeeper = viewOnlyKeeper{} - func (m DefaultAccountConstructor) NewAccount() types.AccountI { return &types.BaseAccount{} } diff --git a/x/auth/module/module.pb.go b/x/auth/module/module.pb.go index fa167689aa1c..459b74172b49 100644 --- a/x/auth/module/module.pb.go +++ b/x/auth/module/module.pb.go @@ -5,11 +5,12 @@ package module import ( fmt "fmt" - types "github.com/cosmos/cosmos-sdk/codec/types" - proto "github.com/gogo/protobuf/proto" io "io" math "math" math_bits "math/bits" + + types "github.com/cosmos/cosmos-sdk/codec/types" + proto "github.com/gogo/protobuf/proto" ) // Reference imports to suppress errors if they are not otherwise used. diff --git a/x/auth/module/view_keeper.go b/x/auth/module/view_keeper.go new file mode 100644 index 000000000000..cf9a961c060c --- /dev/null +++ b/x/auth/module/view_keeper.go @@ -0,0 +1,38 @@ +package module + +import ( + sdk "github.com/cosmos/cosmos-sdk/types" + authkeeper "github.com/cosmos/cosmos-sdk/x/auth/keeper" + "github.com/cosmos/cosmos-sdk/x/auth/types" +) + +// viewOnlyKeeper wraps the full keeper in a view-only interface which can't be easily type cast to the full keeper interface +type viewOnlyKeeper struct { + k authkeeper.AccountKeeper +} + +func (v viewOnlyKeeper) GetAccount(ctx sdk.Context, addr sdk.AccAddress) types.AccountI { + return v.k.GetAccount(ctx, addr) +} + +func (v viewOnlyKeeper) GetModuleAddress(moduleName string) sdk.AccAddress { + return v.k.GetModuleAddress(moduleName) +} + +func (v viewOnlyKeeper) ValidatePermissions(macc types.ModuleAccountI) error { + return v.k.ValidatePermissions(macc) +} + +func (v viewOnlyKeeper) GetModuleAddressAndPermissions(moduleName string) (addr sdk.AccAddress, permissions []string) { + return v.GetModuleAddressAndPermissions(moduleName) +} + +func (v viewOnlyKeeper) GetModuleAccountAndPermissions(ctx sdk.Context, moduleName string) (types.ModuleAccountI, []string) { + return v.GetModuleAccountAndPermissions(ctx, moduleName) +} + +func (v viewOnlyKeeper) GetModuleAccount(ctx sdk.Context, moduleName string) types.ModuleAccountI { + return v.k.GetModuleAccount(ctx, moduleName) +} + +var _ types.ViewKeeper = viewOnlyKeeper{} diff --git a/x/gov/module/module.go b/x/gov/module/module.go index 3b0d4f2a9653..5c3a896d46d3 100644 --- a/x/gov/module/module.go +++ b/x/gov/module/module.go @@ -2,10 +2,11 @@ package module import ( "github.com/cosmos/cosmos-sdk/app" + "github.com/cosmos/cosmos-sdk/app/compat" "github.com/cosmos/cosmos-sdk/codec" + "github.com/cosmos/cosmos-sdk/codec/types" "github.com/cosmos/cosmos-sdk/container" sdk "github.com/cosmos/cosmos-sdk/types" - "github.com/cosmos/cosmos-sdk/types/module" "github.com/cosmos/cosmos-sdk/x/gov" govkeeper "github.com/cosmos/cosmos-sdk/x/gov/keeper" govtypes "github.com/cosmos/cosmos-sdk/x/gov/types" @@ -13,13 +14,12 @@ import ( ) var ( - _ app.Provisioner = &Module{} + _ app.TypeProvider = &Module{} + _ app.Provisioner = &Module{} ) -func (m *Module) Provision(registrar container.Registrar) error { - return registrar.Provide(func() govtypes.Router { - return govtypes.NewRouter() - }) +func (m *Module) RegisterTypes(registry types.InterfaceRegistry) { + govtypes.RegisterInterfaces(registry) } type Inputs struct { @@ -40,18 +40,29 @@ type Outputs struct { container.StructArgs } -func (m *Module) NewAppHandler(inputs Inputs) (module.AppModule, Outputs) { - k := govkeeper.NewKeeper( - inputs.Codec, - inputs.Key, - inputs.ParamStore, - inputs.AuthKeeper, - inputs.BankKeeper, - inputs.StakingKeeper, - inputs.Router, - ) +func (m *Module) Provision(registrar container.Registrar) error { + err := registrar.Provide(func(configurator app.Configurator, inputs Inputs) Outputs { + k := govkeeper.NewKeeper( + inputs.Codec, + inputs.Key, + inputs.ParamStore, + inputs.AuthKeeper, + inputs.BankKeeper, + inputs.StakingKeeper, + inputs.Router, + ) - am := gov.NewAppModule(inputs.Codec, k, inputs.AuthKeeper, inputs.BankKeeper) + am := gov.NewAppModule(inputs.Codec, k, inputs.AuthKeeper, inputs.BankKeeper) + compat.RegisterAppModule(configurator, am) - return am, Outputs{} + return Outputs{} + }) + + if err != nil { + return err + } + + return registrar.Provide(func() govtypes.Router { + return govtypes.NewRouter() + }) } diff --git a/x/gov/module/module.pb.go b/x/gov/module/module.pb.go index e42abcc86ad3..95a5bcc2c0d7 100644 --- a/x/gov/module/module.pb.go +++ b/x/gov/module/module.pb.go @@ -5,10 +5,11 @@ package module import ( fmt "fmt" - proto "github.com/gogo/protobuf/proto" io "io" math "math" math_bits "math/bits" + + proto "github.com/gogo/protobuf/proto" ) // Reference imports to suppress errors if they are not otherwise used. diff --git a/x/params/module/module.go b/x/params/module/module.go index d8c27dfb454b..75492957713e 100644 --- a/x/params/module/module.go +++ b/x/params/module/module.go @@ -2,10 +2,10 @@ package module import ( "github.com/cosmos/cosmos-sdk/app" + "github.com/cosmos/cosmos-sdk/app/compat" "github.com/cosmos/cosmos-sdk/codec" "github.com/cosmos/cosmos-sdk/container" sdk "github.com/cosmos/cosmos-sdk/types" - "github.com/cosmos/cosmos-sdk/types/module" govtypes "github.com/cosmos/cosmos-sdk/x/gov/types" "github.com/cosmos/cosmos-sdk/x/params" paramskeeper "github.com/cosmos/cosmos-sdk/x/params/keeper" @@ -33,16 +33,21 @@ type Outputs struct { Keeper paramskeeper.Keeper `security-role:"admin"` } -func (m Module) NewAppHandler(inputs Inputs) (module.AppModule, Outputs, error) { - keeper := paramskeeper.NewKeeper(inputs.Codec, inputs.LegacyAmino, inputs.Key, inputs.TransientKey) - appMod := params.NewAppModule(keeper) +func (m Module) Provision(registrar container.Registrar) error { + err := registrar.Provide(func(configurator app.Configurator, inputs Inputs) Outputs { + keeper := paramskeeper.NewKeeper(inputs.Codec, inputs.LegacyAmino, inputs.Key, inputs.TransientKey) + appMod := params.NewAppModule(keeper) - inputs.GovRouter.AddRoute(paramproposal.RouterKey, params.NewParamChangeProposalHandler(keeper)) + compat.RegisterAppModule(configurator, appMod) - return appMod, Outputs{Keeper: keeper}, nil -} + inputs.GovRouter.AddRoute(paramproposal.RouterKey, params.NewParamChangeProposalHandler(keeper)) + + return Outputs{Keeper: keeper} + }) + if err != nil { + return err + } -func (m Module) Provision(registrar container.Registrar) error { return registrar.Provide(func(scope container.Scope, keeper paramskeeper.Keeper) types.Subspace { return keeper.Subspace(string(scope)) }) From d5c0fa2f81b7af33f53aa7532862e63d9c0d12e4 Mon Sep 17 00:00:00 2001 From: Aaron Craelius Date: Wed, 2 Jun 2021 18:35:52 -0400 Subject: [PATCH 09/24] add docs --- container/scope.go | 12 ++++++++++++ 1 file changed, 12 insertions(+) diff --git a/container/scope.go b/container/scope.go index 503ba778ce61..0bf37b277918 100644 --- a/container/scope.go +++ b/container/scope.go @@ -1,3 +1,15 @@ package container +// Scope is a special type of provider argument which provider's can use to provide +// "scoped" dependency. A scoped dependency is one which is dependent on the scope. +// A scoped provider should have a first argument of type Scope and return a (possibly) +// different dependency for each scope. This can be used to configure things like +// scoped store access where the requesting scope gets a private store key that cannot +// be accessed by providers in other scopes. Scopes can also be used to configure +// security. +// +// Ex: +// func KVStoreKeyProvider(scope Scope) *sdk.KVStoreKey { +// return sdk.NewKVStoreKey(string(scope)) +// } type Scope string From 860157e396a0a2d9995f1350ec462a11dea9e717 Mon Sep 17 00:00:00 2001 From: Aaron Craelius Date: Wed, 2 Jun 2021 18:39:19 -0400 Subject: [PATCH 10/24] add docs --- container/container.go | 12 ++++++++++++ 1 file changed, 12 insertions(+) diff --git a/container/container.go b/container/container.go index 39be8066f0fb..10c16f56110d 100644 --- a/container/container.go +++ b/container/container.go @@ -13,6 +13,18 @@ func (c *Container) Provide(fn interface{}) error { panic("implement me") } +func (c *Container) ProvideWithScope(fn interface{}, scope Scope) error { + panic("implement me") +} + func (c *Container) Invoke(fn interface{}) error { panic("TODO") } + +// InitializeAll attempts to initialize all registered providers in the container. +// It returns an error if a provider returns an error. If a given provider has +// dependencies which cannot be resolved, an error is not returned and instead +// that provider is not called. +func (c *Container) InitializeAll() error { + panic("TODO") +} From 4b431fe18cf4f71d63f9c5e1cf9c9d83cce0dc70 Mon Sep 17 00:00:00 2001 From: Aaron Craelius Date: Wed, 2 Jun 2021 21:12:36 -0400 Subject: [PATCH 11/24] WIP --- app/config.pb.go | 109 ++++++-- app/internal/app_provider.go | 103 +------ app/internal/module.go | 13 - app/internal/module_set.go | 85 ++++++ app/type_provider.go | 2 +- codec/types/interface_registry.go | 2 + container/docs.go | 3 + docs/core/proto-docs.md | 35 +++ proto/cosmos/app/v1/config.proto | 1 + proto/cosmos/tx/module/v1/module.proto | 13 + simapp/v2/app.yaml | 17 +- x/auth/module/module.pb.go | 5 +- x/auth/tx/module/module.go | 24 ++ x/auth/tx/module/module.pb.go | 372 +++++++++++++++++++++++++ x/gov/module/module.pb.go | 3 +- 15 files changed, 651 insertions(+), 136 deletions(-) delete mode 100644 app/internal/module.go create mode 100644 app/internal/module_set.go create mode 100644 container/docs.go create mode 100644 proto/cosmos/tx/module/v1/module.proto create mode 100644 x/auth/tx/module/module.go create mode 100644 x/auth/tx/module/module.pb.go diff --git a/app/config.pb.go b/app/config.pb.go index 2aeed21caedb..06525afecbfd 100644 --- a/app/config.pb.go +++ b/app/config.pb.go @@ -128,9 +128,10 @@ func (m *ModuleConfig) GetName() string { } type ABCIHandlers struct { - InitGenesis []string `protobuf:"bytes,1,rep,name=init_genesis,json=initGenesis,proto3" json:"init_genesis,omitempty"` - BeginBlock []string `protobuf:"bytes,2,rep,name=begin_block,json=beginBlock,proto3" json:"begin_block,omitempty"` - EndBlock []string `protobuf:"bytes,3,rep,name=end_block,json=endBlock,proto3" json:"end_block,omitempty"` + InitGenesis []string `protobuf:"bytes,1,rep,name=init_genesis,json=initGenesis,proto3" json:"init_genesis,omitempty"` + BeginBlock []string `protobuf:"bytes,2,rep,name=begin_block,json=beginBlock,proto3" json:"begin_block,omitempty"` + EndBlock []string `protobuf:"bytes,3,rep,name=end_block,json=endBlock,proto3" json:"end_block,omitempty"` + TxHandler *types.Any `protobuf:"bytes,4,opt,name=tx_handler,json=txHandler,proto3" json:"tx_handler,omitempty"` } func (m *ABCIHandlers) Reset() { *m = ABCIHandlers{} } @@ -187,6 +188,13 @@ func (m *ABCIHandlers) GetEndBlock() []string { return nil } +func (m *ABCIHandlers) GetTxHandler() *types.Any { + if m != nil { + return m.TxHandler + } + return nil +} + func init() { proto.RegisterType((*Config)(nil), "cosmos.app.v1.Config") proto.RegisterType((*ModuleConfig)(nil), "cosmos.app.v1.ModuleConfig") @@ -196,27 +204,28 @@ func init() { func init() { proto.RegisterFile("cosmos/app/v1/config.proto", fileDescriptor_9c5c7e08cb1a0bd9) } var fileDescriptor_9c5c7e08cb1a0bd9 = []byte{ - // 316 bytes of a gzipped FileDescriptorProto - 0x1f, 0x8b, 0x08, 0x00, 0x00, 0x00, 0x00, 0x00, 0x02, 0xff, 0x6c, 0x91, 0x31, 0x4f, 0x02, 0x31, - 0x14, 0xc7, 0x39, 0x20, 0x28, 0x0f, 0x5c, 0x1a, 0x87, 0x13, 0x92, 0x13, 0x99, 0x1c, 0xb4, 0x0d, - 0x1a, 0x17, 0x37, 0x60, 0x50, 0x07, 0x13, 0x73, 0xa3, 0x0b, 0xb9, 0xde, 0x95, 0xda, 0x70, 0xd7, - 0x36, 0x14, 0x48, 0xf8, 0x16, 0x7e, 0x2c, 0x47, 0x46, 0x47, 0x03, 0x5f, 0xc4, 0xf0, 0x7a, 0x24, - 0x98, 0x38, 0xb5, 0xf9, 0xff, 0x7f, 0xef, 0xbd, 0xff, 0xcb, 0x83, 0x4e, 0x6a, 0x5c, 0x61, 0x1c, - 0x4b, 0xac, 0x65, 0xab, 0x01, 0x4b, 0x8d, 0x9e, 0x2a, 0x49, 0xed, 0xdc, 0x2c, 0x0c, 0x39, 0xf3, - 0x1e, 0x4d, 0xac, 0xa5, 0xab, 0x41, 0xe7, 0x42, 0x1a, 0x23, 0x73, 0xc1, 0xd0, 0xe4, 0xcb, 0x29, - 0x4b, 0xf4, 0xda, 0x93, 0x7d, 0x0b, 0x8d, 0x31, 0x56, 0x92, 0x07, 0x38, 0x29, 0x4c, 0xb6, 0xcc, - 0x85, 0x0b, 0x83, 0x5e, 0xed, 0xba, 0x75, 0xd7, 0xa5, 0x7f, 0xba, 0xd0, 0x57, 0x74, 0x3d, 0x1d, - 0x1f, 0x58, 0xc2, 0xa0, 0x9e, 0xf0, 0x54, 0x85, 0xd5, 0x5e, 0xf0, 0x4f, 0xcd, 0x70, 0x34, 0x7e, - 0x79, 0x4e, 0x74, 0x96, 0x8b, 0xb9, 0x8b, 0x11, 0xec, 0xbf, 0x41, 0xfb, 0xb8, 0x13, 0xb9, 0x81, - 0x86, 0xcf, 0x1e, 0x06, 0xd8, 0xe2, 0x9c, 0xfa, 0xb4, 0xf4, 0x90, 0x96, 0x0e, 0xf5, 0x3a, 0x2e, - 0x19, 0x42, 0xa0, 0xae, 0x93, 0x42, 0xe0, 0xb8, 0x66, 0x8c, 0xff, 0xbe, 0x81, 0xf6, 0xf1, 0x1c, - 0x72, 0x05, 0x6d, 0xa5, 0xd5, 0x62, 0x22, 0x85, 0x16, 0x4e, 0xf9, 0x75, 0x9a, 0x71, 0x6b, 0xaf, - 0x3d, 0x79, 0x89, 0x5c, 0x42, 0x8b, 0x0b, 0xa9, 0xf4, 0x84, 0xe7, 0x26, 0x9d, 0x85, 0x55, 0x24, - 0x00, 0xa5, 0xd1, 0x5e, 0x21, 0x5d, 0x68, 0x0a, 0x9d, 0x95, 0x76, 0x0d, 0xed, 0x53, 0xa1, 0x33, - 0x34, 0x47, 0x8f, 0x5f, 0xdb, 0x28, 0xd8, 0x6c, 0xa3, 0xe0, 0x67, 0x1b, 0x05, 0x9f, 0xbb, 0xa8, - 0xb2, 0xd9, 0x45, 0x95, 0xef, 0x5d, 0x54, 0x79, 0xef, 0x49, 0xb5, 0xf8, 0x58, 0x72, 0x9a, 0x9a, - 0x82, 0x95, 0xf7, 0xf1, 0xcf, 0xad, 0xcb, 0x66, 0xfb, 0x53, 0xf1, 0x06, 0xae, 0x75, 0xff, 0x1b, - 0x00, 0x00, 0xff, 0xff, 0x7b, 0xf5, 0x60, 0xab, 0xbf, 0x01, 0x00, 0x00, + // 336 bytes of a gzipped FileDescriptorProto + 0x1f, 0x8b, 0x08, 0x00, 0x00, 0x00, 0x00, 0x00, 0x02, 0xff, 0x7c, 0x91, 0xbd, 0x4e, 0x02, 0x41, + 0x14, 0x85, 0x19, 0x20, 0xe8, 0x5e, 0xb0, 0x99, 0x58, 0xac, 0x90, 0xac, 0x48, 0x65, 0xa1, 0x33, + 0x41, 0x62, 0x63, 0x07, 0x14, 0x6a, 0x61, 0x62, 0xb6, 0xb4, 0x21, 0xfb, 0x33, 0x2c, 0x13, 0x76, + 0x67, 0x26, 0xcc, 0x42, 0xe0, 0x2d, 0x7c, 0x08, 0x1f, 0xc6, 0x92, 0xd2, 0xd2, 0xc0, 0x8b, 0x98, + 0x9d, 0x59, 0x12, 0x4c, 0x8c, 0xd5, 0x6e, 0xce, 0xf9, 0xee, 0xb9, 0x67, 0x72, 0xa1, 0x1d, 0x49, + 0x9d, 0x49, 0x4d, 0x03, 0xa5, 0xe8, 0xaa, 0x4f, 0x23, 0x29, 0xa6, 0x3c, 0x21, 0x6a, 0x21, 0x73, + 0x89, 0xcf, 0xac, 0x47, 0x02, 0xa5, 0xc8, 0xaa, 0xdf, 0xbe, 0x48, 0xa4, 0x4c, 0x52, 0x46, 0x8d, + 0x19, 0x2e, 0xa7, 0x34, 0x10, 0x1b, 0x4b, 0xf6, 0x14, 0x34, 0xc6, 0x66, 0x12, 0xdf, 0xc3, 0x49, + 0x26, 0xe3, 0x65, 0xca, 0xb4, 0x8b, 0xba, 0xb5, 0xeb, 0xe6, 0x5d, 0x87, 0xfc, 0x4a, 0x21, 0x2f, + 0xc6, 0xb5, 0xb4, 0x7f, 0x60, 0x31, 0x85, 0x7a, 0x10, 0x46, 0xdc, 0xad, 0x76, 0xd1, 0x1f, 0x33, + 0xc3, 0xd1, 0xf8, 0xf9, 0x29, 0x10, 0x71, 0xca, 0x16, 0xda, 0x37, 0x60, 0xef, 0x15, 0x5a, 0xc7, + 0x49, 0xf8, 0x06, 0x1a, 0xb6, 0xbb, 0x8b, 0x4c, 0xc4, 0x39, 0xb1, 0x6d, 0xc9, 0xa1, 0x2d, 0x19, + 0x8a, 0x8d, 0x5f, 0x32, 0x18, 0x43, 0x5d, 0x04, 0x19, 0x33, 0xeb, 0x1c, 0xdf, 0xfc, 0xf7, 0x3e, + 0x10, 0xb4, 0x8e, 0x17, 0xe1, 0x2b, 0x68, 0x71, 0xc1, 0xf3, 0x49, 0xc2, 0x04, 0xd3, 0xdc, 0xbe, + 0xc7, 0xf1, 0x9b, 0x85, 0xf6, 0x68, 0x25, 0x7c, 0x09, 0xcd, 0x90, 0x25, 0x5c, 0x4c, 0xc2, 0x54, + 0x46, 0x73, 0xb7, 0x6a, 0x08, 0x30, 0xd2, 0xa8, 0x50, 0x70, 0x07, 0x1c, 0x26, 0xe2, 0xd2, 0xae, + 0x19, 0xfb, 0x94, 0x89, 0xd8, 0x9a, 0x03, 0x80, 0x7c, 0x3d, 0x99, 0xd9, 0x7d, 0x6e, 0xfd, 0x9f, + 0xde, 0x4e, 0xbe, 0x2e, 0x6b, 0x8d, 0x1e, 0x3e, 0x77, 0x1e, 0xda, 0xee, 0x3c, 0xf4, 0xbd, 0xf3, + 0xd0, 0xfb, 0xde, 0xab, 0x6c, 0xf7, 0x5e, 0xe5, 0x6b, 0xef, 0x55, 0xde, 0xba, 0x09, 0xcf, 0x67, + 0xcb, 0x90, 0x44, 0x32, 0xa3, 0xe5, 0x55, 0xed, 0xe7, 0x56, 0xc7, 0xf3, 0xe2, 0xc0, 0x61, 0xc3, + 0x84, 0x0e, 0x7e, 0x02, 0x00, 0x00, 0xff, 0xff, 0x8b, 0x28, 0xcd, 0xee, 0xf5, 0x01, 0x00, 0x00, } func (m *Config) Marshal() (dAtA []byte, err error) { @@ -330,6 +339,18 @@ func (m *ABCIHandlers) MarshalToSizedBuffer(dAtA []byte) (int, error) { _ = i var l int _ = l + if m.TxHandler != nil { + { + size, err := m.TxHandler.MarshalToSizedBuffer(dAtA[:i]) + if err != nil { + return 0, err + } + i -= size + i = encodeVarintConfig(dAtA, i, uint64(size)) + } + i-- + dAtA[i] = 0x22 + } if len(m.EndBlock) > 0 { for iNdEx := len(m.EndBlock) - 1; iNdEx >= 0; iNdEx-- { i -= len(m.EndBlock[iNdEx]) @@ -431,6 +452,10 @@ func (m *ABCIHandlers) Size() (n int) { n += 1 + l + sovConfig(uint64(l)) } } + if m.TxHandler != nil { + l = m.TxHandler.Size() + n += 1 + l + sovConfig(uint64(l)) + } return n } @@ -803,6 +828,42 @@ func (m *ABCIHandlers) Unmarshal(dAtA []byte) error { } m.EndBlock = append(m.EndBlock, string(dAtA[iNdEx:postIndex])) iNdEx = postIndex + case 4: + if wireType != 2 { + return fmt.Errorf("proto: wrong wireType = %d for field TxHandler", wireType) + } + var msglen int + for shift := uint(0); ; shift += 7 { + if shift >= 64 { + return ErrIntOverflowConfig + } + if iNdEx >= l { + return io.ErrUnexpectedEOF + } + b := dAtA[iNdEx] + iNdEx++ + msglen |= int(b&0x7F) << shift + if b < 0x80 { + break + } + } + if msglen < 0 { + return ErrInvalidLengthConfig + } + postIndex := iNdEx + msglen + if postIndex < 0 { + return ErrInvalidLengthConfig + } + if postIndex > l { + return io.ErrUnexpectedEOF + } + if m.TxHandler == nil { + m.TxHandler = &types.Any{} + } + if err := m.TxHandler.Unmarshal(dAtA[iNdEx:postIndex]); err != nil { + return err + } + iNdEx = postIndex default: iNdEx = preIndex skippy, err := skipConfig(dAtA[iNdEx:]) diff --git a/app/internal/app_provider.go b/app/internal/app_provider.go index 6c5a97e881bc..509f7c5d2ba6 100644 --- a/app/internal/app_provider.go +++ b/app/internal/app_provider.go @@ -1,113 +1,38 @@ package internal import ( - "fmt" - "reflect" - - "github.com/gogo/protobuf/proto" - "github.com/cosmos/cosmos-sdk/app" - "github.com/cosmos/cosmos-sdk/container" - - "github.com/cosmos/cosmos-sdk/x/auth/tx" - - "github.com/cosmos/cosmos-sdk/client" - "github.com/cosmos/cosmos-sdk/codec" - codecTypes "github.com/cosmos/cosmos-sdk/codec/types" ) type AppProvider struct { - config *app.Config - container *container.Container - interfaceRegistry codecTypes.InterfaceRegistry - codec codec.Codec - txConfig client.TxConfig - amino *codec.LegacyAmino - configMap map[string]interface{} - moduleConfigMap map[string]*app.ModuleConfig -} - -func (ap *AppProvider) InterfaceRegistry() codecTypes.InterfaceRegistry { - return ap.interfaceRegistry -} - -func (ap *AppProvider) Codec() codec.Codec { - return ap.codec -} - -func (ap *AppProvider) TxConfig() client.TxConfig { - return ap.txConfig + config *app.Config + container *ModuleContainer + moduleConfigMap map[string]*app.ModuleConfig } -func (ap *AppProvider) Amino() *codec.LegacyAmino { - return ap.amino -} +const txModuleScope container.Scope = "tx" -func NewApp(config *app.Config) (*AppProvider, error) { - // create container - ctr := container.NewContainer() +func NewAppProvider(config *app.Config) (*AppProvider, error) { + ctr := NewModuleContainer() + moduleConfigMap := map[string]*app.ModuleConfig{} - // provide encoding configs - interfaceRegistry := codecTypes.NewInterfaceRegistry() - marshaler := codec.NewProtoCodec(interfaceRegistry) - txConfig := tx.NewTxConfig(marshaler, tx.DefaultSignModes) - amino := codec.NewLegacyAmino() - err := ctr.Provide(func() (codecTypes.InterfaceRegistry, codec.Codec, client.TxConfig, *codec.LegacyAmino) { - return interfaceRegistry, marshaler, txConfig, amino - }) + err := ctr.AddModule(txModuleScope, config.Abci.TxHandler) if err != nil { return nil, err } - // load configs - cfgMap := map[string]interface{}{} - moduleConfigMap := map[string]*app.ModuleConfig{} - for _, modConfig := range config.Modules { - // unpack Any - msgTyp := proto.MessageType(modConfig.Config.TypeUrl) - cfg := reflect.New(msgTyp).Interface().(proto.Message) - if err := proto.Unmarshal(modConfig.Config.Value, cfg); err != nil { + err = ctr.AddModule(container.Scope(modConfig.Name), modConfig.Config) + if err != nil { return nil, err } - - // resolve module name - name := modConfig.Name - if name == "" { - if named, ok := cfg.(Named); ok { - name = named.Name() - } else { - return nil, fmt.Errorf("unnamed module config %+v", modConfig) - } - } - - // save in config map - cfgMap[name] = cfg - moduleConfigMap[name] = modConfig - - // register types - if typeProvider, ok := cfg.(app.TypeProvider); ok { - typeProvider.RegisterTypes(interfaceRegistry) - } - - // register DI providers - if provisioner, ok := cfg.(app.Provisioner); ok { - err = provisioner.Provision(ctr) - if err != nil { - return nil, err - } - } + moduleConfigMap[modConfig.Name] = modConfig } return &AppProvider{ - config: config, - container: ctr, - interfaceRegistry: interfaceRegistry, - codec: marshaler, - txConfig: txConfig, - amino: amino, - configMap: cfgMap, - moduleConfigMap: moduleConfigMap, + config: config, + container: ctr, + moduleConfigMap: moduleConfigMap, }, nil } diff --git a/app/internal/module.go b/app/internal/module.go deleted file mode 100644 index 0e19890606ee..000000000000 --- a/app/internal/module.go +++ /dev/null @@ -1,13 +0,0 @@ -package internal - -import ( - "github.com/cosmos/cosmos-sdk/types/module" -) - -type Named interface { - Name() string -} - -type Handler interface { - RegisterServices(configurator module.Configurator) -} diff --git a/app/internal/module_set.go b/app/internal/module_set.go new file mode 100644 index 000000000000..5dcbb0b684ab --- /dev/null +++ b/app/internal/module_set.go @@ -0,0 +1,85 @@ +package internal + +import ( + "reflect" + + "github.com/cosmos/cosmos-sdk/app" + "github.com/cosmos/cosmos-sdk/codec" + codecTypes "github.com/cosmos/cosmos-sdk/codec/types" + "github.com/cosmos/cosmos-sdk/container" + "github.com/gogo/protobuf/proto" +) + +type ModuleContainer struct { + *container.Container + typeRegistry codecTypes.TypeRegistry + codec codec.Codec + modules map[container.Scope]interface{} +} + +func NewModuleContainer() *ModuleContainer { + typeRegistry := codecTypes.NewInterfaceRegistry() + cdc := codec.NewProtoCodec(typeRegistry) + amino := codec.NewLegacyAmino() + ctr := container.NewContainer() + err := ctr.Provide(func() ( + codecTypes.TypeRegistry, + codec.Codec, + codec.BinaryCodec, + codec.JSONCodec, + *codec.LegacyAmino, + ) { + return typeRegistry, cdc, cdc, cdc, amino + }) + if err != nil { + panic(err) + } + + return &ModuleContainer{ + Container: ctr, + typeRegistry: typeRegistry, + codec: cdc, + modules: map[container.Scope]interface{}{}, + } +} + +func (mc ModuleContainer) AddModule(scope container.Scope, config *codecTypes.Any) error { + // unpack Any + msgTyp := proto.MessageType(config.TypeUrl) + mod := reflect.New(msgTyp).Interface().(proto.Message) + if err := proto.Unmarshal(config.Value, mod); err != nil { + return err + } + + mc.modules[scope] = mod + + // register types + if typeProvider, ok := mod.(app.TypeProvider); ok { + typeProvider.RegisterTypes(mc.typeRegistry) + } + + // register DI providers + if provisioner, ok := mod.(app.Provisioner); ok { + registrar := scopedRegistrar{ + ctr: mc.Container, + scope: scope, + } + err := provisioner.Provision(registrar) + if err != nil { + return err + } + } + + return nil +} + +type scopedRegistrar struct { + ctr *container.Container + scope container.Scope +} + +var _ container.Registrar = scopedRegistrar{} + +func (s scopedRegistrar) Provide(fn interface{}) error { + return s.ctr.ProvideWithScope(fn, s.scope) +} diff --git a/app/type_provider.go b/app/type_provider.go index ccf559a3f74d..2dfca6973cc1 100644 --- a/app/type_provider.go +++ b/app/type_provider.go @@ -3,5 +3,5 @@ package app import "github.com/cosmos/cosmos-sdk/codec/types" type TypeProvider interface { - RegisterTypes(registry types.InterfaceRegistry) + RegisterTypes(registry types.TypeRegistry) } diff --git a/codec/types/interface_registry.go b/codec/types/interface_registry.go index 5d7e72e890c0..720a5b3eebb4 100644 --- a/codec/types/interface_registry.go +++ b/codec/types/interface_registry.go @@ -22,6 +22,8 @@ type AnyUnpacker interface { UnpackAny(any *Any, iface interface{}) error } +type TypeRegistry = InterfaceRegistry + // InterfaceRegistry provides a mechanism for registering interfaces and // implementations that can be safely unpacked from Any type InterfaceRegistry interface { diff --git a/container/docs.go b/container/docs.go new file mode 100644 index 000000000000..40b7ad40d264 --- /dev/null +++ b/container/docs.go @@ -0,0 +1,3 @@ +/*Package container + */ +package container diff --git a/docs/core/proto-docs.md b/docs/core/proto-docs.md index 7ca920804077..85ab1780a5ab 100644 --- a/docs/core/proto-docs.md +++ b/docs/core/proto-docs.md @@ -546,6 +546,9 @@ - [SignMode](#cosmos.tx.signing.v1beta1.SignMode) +- [cosmos/tx/module/v1/module.proto](#cosmos/tx/module/v1/module.proto) + - [Module](#cosmos.tx.module.v1.Module) + - [cosmos/tx/v1beta1/tx.proto](#cosmos/tx/v1beta1/tx.proto) - [AuthInfo](#cosmos.tx.v1beta1.AuthInfo) - [Fee](#cosmos.tx.v1beta1.Fee) @@ -627,6 +630,7 @@ | `init_genesis` | [string](#string) | repeated | | | `begin_block` | [string](#string) | repeated | | | `end_block` | [string](#string) | repeated | | +| `tx_handler` | [google.protobuf.Any](#google.protobuf.Any) | | | @@ -7675,6 +7679,37 @@ SignMode represents a signing mode with its own security guarantees. + +

Top

+ +## cosmos/tx/module/v1/module.proto + + + + + +### Module + + + +| Field | Type | Label | Description | +| ----- | ---- | ----- | ----------- | +| `enabled_sign_modes` | [cosmos.tx.signing.v1beta1.SignMode](#cosmos.tx.signing.v1beta1.SignMode) | repeated | enabled_sign_modes is the list of enabled sign modes. It will fallback to the default value of [SIGN_MODE_DIRECT, SIGN_MODE_LEGACY_AMINO_JSON] if left empty. | + + + + + + + + + + + + + + +

Top

diff --git a/proto/cosmos/app/v1/config.proto b/proto/cosmos/app/v1/config.proto index 5b098fffd359..454da287b825 100644 --- a/proto/cosmos/app/v1/config.proto +++ b/proto/cosmos/app/v1/config.proto @@ -19,4 +19,5 @@ message ABCIHandlers { repeated string init_genesis = 1; repeated string begin_block = 2; repeated string end_block = 3; + google.protobuf.Any tx_handler = 4; } diff --git a/proto/cosmos/tx/module/v1/module.proto b/proto/cosmos/tx/module/v1/module.proto new file mode 100644 index 000000000000..4be56baaf4a9 --- /dev/null +++ b/proto/cosmos/tx/module/v1/module.proto @@ -0,0 +1,13 @@ +syntax = "proto3"; +package cosmos.tx.module.v1; + +import "cosmos/tx/signing/v1beta1/signing.proto"; + +option go_package = "github.com/cosmos/cosmos-sdk/x/auth/tx/module"; + +message Module { + // enabled_sign_modes is the list of enabled sign modes. It will fallback + // to the default value of [SIGN_MODE_DIRECT, SIGN_MODE_LEGACY_AMINO_JSON] + // if left empty. + repeated cosmos.tx.signing.v1beta1.SignMode enabled_sign_modes = 1; +} diff --git a/simapp/v2/app.yaml b/simapp/v2/app.yaml index e125eb690702..183f47686960 100644 --- a/simapp/v2/app.yaml +++ b/simapp/v2/app.yaml @@ -1,9 +1,18 @@ modules: - - config: + - name: auth + config: @type: cosmos.auth.module.v1.Module - - config: + - name: bank + config: @type: cosmos.bank.module.v1.Module - - config: + - name: params + config: @type: cosmos.params.module.v1.Module - - config: + - name: gov + config: @type: cosmos.gov.module.v1.Module +abci: + begin_block: [auth, bank] + end_block: [gov] + tx_handler: + @type: cosmos.tx.module.v1.Module diff --git a/x/auth/module/module.pb.go b/x/auth/module/module.pb.go index 459b74172b49..fa167689aa1c 100644 --- a/x/auth/module/module.pb.go +++ b/x/auth/module/module.pb.go @@ -5,12 +5,11 @@ package module import ( fmt "fmt" + types "github.com/cosmos/cosmos-sdk/codec/types" + proto "github.com/gogo/protobuf/proto" io "io" math "math" math_bits "math/bits" - - types "github.com/cosmos/cosmos-sdk/codec/types" - proto "github.com/gogo/protobuf/proto" ) // Reference imports to suppress errors if they are not otherwise used. diff --git a/x/auth/tx/module/module.go b/x/auth/tx/module/module.go new file mode 100644 index 000000000000..2710071dded8 --- /dev/null +++ b/x/auth/tx/module/module.go @@ -0,0 +1,24 @@ +package module + +import ( + "github.com/cosmos/cosmos-sdk/app" + "github.com/cosmos/cosmos-sdk/client" + "github.com/cosmos/cosmos-sdk/codec" + "github.com/cosmos/cosmos-sdk/container" + "github.com/cosmos/cosmos-sdk/x/auth/tx" +) + +var ( + _ app.Provisioner = Module{} +) + +func (m Module) Provision(registrar container.Registrar) error { + return registrar.Provide(func(marshaler codec.ProtoCodecMarshaler) client.TxConfig { + signModes := m.EnabledSignModes + if signModes == nil { + signModes = tx.DefaultSignModes + } + + return tx.NewTxConfig(marshaler, signModes) + }) +} diff --git a/x/auth/tx/module/module.pb.go b/x/auth/tx/module/module.pb.go new file mode 100644 index 000000000000..ac29aa65ce35 --- /dev/null +++ b/x/auth/tx/module/module.pb.go @@ -0,0 +1,372 @@ +// Code generated by protoc-gen-gogo. DO NOT EDIT. +// source: cosmos/tx/module/v1/module.proto + +package module + +import ( + fmt "fmt" + signing "github.com/cosmos/cosmos-sdk/types/tx/signing" + proto "github.com/gogo/protobuf/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 + +type Module struct { + // enabled_sign_modes is the list of enabled sign modes. It will fallback + // to the default value of [SIGN_MODE_DIRECT, SIGN_MODE_LEGACY_AMINO_JSON] + // if left empty. + EnabledSignModes []signing.SignMode `protobuf:"varint,1,rep,packed,name=enabled_sign_modes,json=enabledSignModes,proto3,enum=cosmos.tx.signing.v1beta1.SignMode" json:"enabled_sign_modes,omitempty"` +} + +func (m *Module) Reset() { *m = Module{} } +func (m *Module) String() string { return proto.CompactTextString(m) } +func (*Module) ProtoMessage() {} +func (*Module) Descriptor() ([]byte, []int) { + return fileDescriptor_af10febde24b7359, []int{0} +} +func (m *Module) XXX_Unmarshal(b []byte) error { + return m.Unmarshal(b) +} +func (m *Module) XXX_Marshal(b []byte, deterministic bool) ([]byte, error) { + if deterministic { + return xxx_messageInfo_Module.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 *Module) XXX_Merge(src proto.Message) { + xxx_messageInfo_Module.Merge(m, src) +} +func (m *Module) XXX_Size() int { + return m.Size() +} +func (m *Module) XXX_DiscardUnknown() { + xxx_messageInfo_Module.DiscardUnknown(m) +} + +var xxx_messageInfo_Module proto.InternalMessageInfo + +func (m *Module) GetEnabledSignModes() []signing.SignMode { + if m != nil { + return m.EnabledSignModes + } + return nil +} + +func init() { + proto.RegisterType((*Module)(nil), "cosmos.tx.module.v1.Module") +} + +func init() { proto.RegisterFile("cosmos/tx/module/v1/module.proto", fileDescriptor_af10febde24b7359) } + +var fileDescriptor_af10febde24b7359 = []byte{ + // 208 bytes of a gzipped FileDescriptorProto + 0x1f, 0x8b, 0x08, 0x00, 0x00, 0x00, 0x00, 0x00, 0x02, 0xff, 0xe2, 0x52, 0x48, 0xce, 0x2f, 0xce, + 0xcd, 0x2f, 0xd6, 0x2f, 0xa9, 0xd0, 0xcf, 0xcd, 0x4f, 0x29, 0xcd, 0x49, 0xd5, 0x2f, 0x33, 0x84, + 0xb2, 0xf4, 0x0a, 0x8a, 0xf2, 0x4b, 0xf2, 0x85, 0x84, 0x21, 0x2a, 0xf4, 0x4a, 0x2a, 0xf4, 0xa0, + 0xe2, 0x65, 0x86, 0x52, 0xea, 0x08, 0x6d, 0xc5, 0x99, 0xe9, 0x79, 0x99, 0x79, 0xe9, 0xfa, 0x65, + 0x86, 0x49, 0xa9, 0x25, 0x89, 0x86, 0x30, 0x3e, 0x44, 0xb7, 0x52, 0x34, 0x17, 0x9b, 0x2f, 0x58, + 0x97, 0x50, 0x20, 0x97, 0x50, 0x6a, 0x5e, 0x62, 0x52, 0x4e, 0x6a, 0x4a, 0x3c, 0x48, 0x49, 0x7c, + 0x6e, 0x7e, 0x4a, 0x6a, 0xb1, 0x04, 0xa3, 0x02, 0xb3, 0x06, 0x9f, 0x91, 0xb2, 0x1e, 0xc2, 0x12, + 0x98, 0x7e, 0xa8, 0x79, 0x7a, 0xc1, 0x99, 0xe9, 0x79, 0xbe, 0xf9, 0x29, 0xa9, 0x41, 0x02, 0x50, + 0xed, 0x30, 0x81, 0x62, 0x27, 0xf7, 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, + 0xd2, 0x4d, 0xcf, 0x2c, 0xc9, 0x28, 0x4d, 0xd2, 0x4b, 0xce, 0xcf, 0xd5, 0x87, 0x3a, 0x15, 0x42, + 0xe9, 0x16, 0xa7, 0x64, 0xeb, 0x57, 0xe8, 0x27, 0x96, 0x96, 0x64, 0x20, 0xfc, 0x9c, 0xc4, 0x06, + 0x76, 0xac, 0x31, 0x20, 0x00, 0x00, 0xff, 0xff, 0xb2, 0x75, 0x07, 0x44, 0x0e, 0x01, 0x00, 0x00, +} + +func (m *Module) 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 *Module) MarshalTo(dAtA []byte) (int, error) { + size := m.Size() + return m.MarshalToSizedBuffer(dAtA[:size]) +} + +func (m *Module) MarshalToSizedBuffer(dAtA []byte) (int, error) { + i := len(dAtA) + _ = i + var l int + _ = l + if len(m.EnabledSignModes) > 0 { + dAtA2 := make([]byte, len(m.EnabledSignModes)*10) + var j1 int + for _, num := range m.EnabledSignModes { + for num >= 1<<7 { + dAtA2[j1] = uint8(uint64(num)&0x7f | 0x80) + num >>= 7 + j1++ + } + dAtA2[j1] = uint8(num) + j1++ + } + i -= j1 + copy(dAtA[i:], dAtA2[:j1]) + i = encodeVarintModule(dAtA, i, uint64(j1)) + i-- + dAtA[i] = 0xa + } + return len(dAtA) - i, nil +} + +func encodeVarintModule(dAtA []byte, offset int, v uint64) int { + offset -= sovModule(v) + base := offset + for v >= 1<<7 { + dAtA[offset] = uint8(v&0x7f | 0x80) + v >>= 7 + offset++ + } + dAtA[offset] = uint8(v) + return base +} +func (m *Module) Size() (n int) { + if m == nil { + return 0 + } + var l int + _ = l + if len(m.EnabledSignModes) > 0 { + l = 0 + for _, e := range m.EnabledSignModes { + l += sovModule(uint64(e)) + } + n += 1 + sovModule(uint64(l)) + l + } + return n +} + +func sovModule(x uint64) (n int) { + return (math_bits.Len64(x|1) + 6) / 7 +} +func sozModule(x uint64) (n int) { + return sovModule(uint64((x << 1) ^ uint64((int64(x) >> 63)))) +} +func (m *Module) 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 ErrIntOverflowModule + } + 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: Module: wiretype end group for non-group") + } + if fieldNum <= 0 { + return fmt.Errorf("proto: Module: illegal tag %d (wire type %d)", fieldNum, wire) + } + switch fieldNum { + case 1: + if wireType == 0 { + var v signing.SignMode + for shift := uint(0); ; shift += 7 { + if shift >= 64 { + return ErrIntOverflowModule + } + if iNdEx >= l { + return io.ErrUnexpectedEOF + } + b := dAtA[iNdEx] + iNdEx++ + v |= signing.SignMode(b&0x7F) << shift + if b < 0x80 { + break + } + } + m.EnabledSignModes = append(m.EnabledSignModes, v) + } else if wireType == 2 { + var packedLen int + for shift := uint(0); ; shift += 7 { + if shift >= 64 { + return ErrIntOverflowModule + } + if iNdEx >= l { + return io.ErrUnexpectedEOF + } + b := dAtA[iNdEx] + iNdEx++ + packedLen |= int(b&0x7F) << shift + if b < 0x80 { + break + } + } + if packedLen < 0 { + return ErrInvalidLengthModule + } + postIndex := iNdEx + packedLen + if postIndex < 0 { + return ErrInvalidLengthModule + } + if postIndex > l { + return io.ErrUnexpectedEOF + } + var elementCount int + if elementCount != 0 && len(m.EnabledSignModes) == 0 { + m.EnabledSignModes = make([]signing.SignMode, 0, elementCount) + } + for iNdEx < postIndex { + var v signing.SignMode + for shift := uint(0); ; shift += 7 { + if shift >= 64 { + return ErrIntOverflowModule + } + if iNdEx >= l { + return io.ErrUnexpectedEOF + } + b := dAtA[iNdEx] + iNdEx++ + v |= signing.SignMode(b&0x7F) << shift + if b < 0x80 { + break + } + } + m.EnabledSignModes = append(m.EnabledSignModes, v) + } + } else { + return fmt.Errorf("proto: wrong wireType = %d for field EnabledSignModes", wireType) + } + default: + iNdEx = preIndex + skippy, err := skipModule(dAtA[iNdEx:]) + if err != nil { + return err + } + if (skippy < 0) || (iNdEx+skippy) < 0 { + return ErrInvalidLengthModule + } + if (iNdEx + skippy) > l { + return io.ErrUnexpectedEOF + } + iNdEx += skippy + } + } + + if iNdEx > l { + return io.ErrUnexpectedEOF + } + return nil +} +func skipModule(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, ErrIntOverflowModule + } + 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, ErrIntOverflowModule + } + 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, ErrIntOverflowModule + } + 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, ErrInvalidLengthModule + } + iNdEx += length + case 3: + depth++ + case 4: + if depth == 0 { + return 0, ErrUnexpectedEndOfGroupModule + } + depth-- + case 5: + iNdEx += 4 + default: + return 0, fmt.Errorf("proto: illegal wireType %d", wireType) + } + if iNdEx < 0 { + return 0, ErrInvalidLengthModule + } + if depth == 0 { + return iNdEx, nil + } + } + return 0, io.ErrUnexpectedEOF +} + +var ( + ErrInvalidLengthModule = fmt.Errorf("proto: negative length found during unmarshaling") + ErrIntOverflowModule = fmt.Errorf("proto: integer overflow") + ErrUnexpectedEndOfGroupModule = fmt.Errorf("proto: unexpected end of group") +) diff --git a/x/gov/module/module.pb.go b/x/gov/module/module.pb.go index 95a5bcc2c0d7..e42abcc86ad3 100644 --- a/x/gov/module/module.pb.go +++ b/x/gov/module/module.pb.go @@ -5,11 +5,10 @@ package module import ( fmt "fmt" + proto "github.com/gogo/protobuf/proto" io "io" math "math" math_bits "math/bits" - - proto "github.com/gogo/protobuf/proto" ) // Reference imports to suppress errors if they are not otherwise used. From 05de1527746abf4e2903ccb6a8e099c1b5c07484 Mon Sep 17 00:00:00 2001 From: Aaron Craelius Date: Wed, 2 Jun 2021 21:29:18 -0400 Subject: [PATCH 12/24] WIP --- app/cli/run.go | 33 ++++++++++++++++++++++++--------- app/internal/app_provider.go | 2 +- 2 files changed, 25 insertions(+), 10 deletions(-) diff --git a/app/cli/run.go b/app/cli/run.go index b2130de4de9a..1b42110ed7bd 100644 --- a/app/cli/run.go +++ b/app/cli/run.go @@ -3,6 +3,9 @@ package cli import ( "os" + "github.com/cosmos/cosmos-sdk/codec" + codectypes "github.com/cosmos/cosmos-sdk/codec/types" + "github.com/cosmos/cosmos-sdk/app/internal" "github.com/spf13/cobra" @@ -47,21 +50,33 @@ func Run(options Options) { } func newRootCmd(options Options) *cobra.Command { - a, err := internal.NewApp(options.DefaultAppConfig) + a, err := internal.NewAppProvider(options.DefaultAppConfig) if err != nil { panic(err) } initClientCtx := client.Context{}. - WithJSONCodec(a.Codec()). - WithInterfaceRegistry(a.InterfaceRegistry()). - WithTxConfig(a.TxConfig()). - WithLegacyAmino(a.Amino()). WithInput(os.Stdin). WithAccountRetriever(types.AccountRetriever{}). WithHomeDir(options.DefaultHome). WithViper("") // In simapp, we don't use any prefix for env variables. + err = a.Invoke(func( + codec codec.JSONCodec, + registry codectypes.InterfaceRegistry, + txConfig client.TxConfig, + amino *codec.LegacyAmino, + ) { + initClientCtx = initClientCtx. + WithJSONCodec(codec). + WithInterfaceRegistry(registry). + WithTxConfig(txConfig). + WithLegacyAmino(amino) + }) + if err != nil { + panic(err) + } + rootCmd := &cobra.Command{ Use: "simd", Short: "simulation app", @@ -85,12 +100,12 @@ func newRootCmd(options Options) *cobra.Command { }, } - initRootCmd(options, rootCmd, a) + initRootCmd(options, rootCmd, a, initClientCtx) return rootCmd } -func initRootCmd(options Options, rootCmd *cobra.Command, a *internal.AppProvider) { +func initRootCmd(options Options, rootCmd *cobra.Command, a *internal.AppProvider, clientCtx client.Context) { cfg := sdk.GetConfig() cfg.Seal() @@ -98,7 +113,7 @@ func initRootCmd(options Options, rootCmd *cobra.Command, a *internal.AppProvide genutilcli.InitCmd(simapp.ModuleBasics, options.DefaultHome), genutilcli.CollectGenTxsCmd(banktypes.GenesisBalancesIterator{}, options.DefaultHome), genutilcli.MigrateGenesisCmd(), - genutilcli.GenTxCmd(simapp.ModuleBasics, a.TxConfig(), banktypes.GenesisBalancesIterator{}, options.DefaultHome), + genutilcli.GenTxCmd(simapp.ModuleBasics, clientCtx.TxConfig, banktypes.GenesisBalancesIterator{}, options.DefaultHome), genutilcli.ValidateGenesisCmd(simapp.ModuleBasics), //AddGenesisAccountCmd(options.DefaultHome), tmcli.NewCompletionCmd(rootCmd, true), @@ -118,7 +133,7 @@ func initRootCmd(options Options, rootCmd *cobra.Command, a *internal.AppProvide ) // add rosetta - rootCmd.AddCommand(server.RosettaCommand(a.InterfaceRegistry(), a.Codec())) + rootCmd.AddCommand(server.RosettaCommand(clientCtx.InterfaceRegistry, clientCtx.JSONCodec)) } func addModuleInitFlags(startCmd *cobra.Command) { diff --git a/app/internal/app_provider.go b/app/internal/app_provider.go index 509f7c5d2ba6..339921788d72 100644 --- a/app/internal/app_provider.go +++ b/app/internal/app_provider.go @@ -6,8 +6,8 @@ import ( ) type AppProvider struct { + *ModuleContainer config *app.Config - container *ModuleContainer moduleConfigMap map[string]*app.ModuleConfig } From 00e4c0cdef641ed9fc432fc84b5fb05b39b356c5 Mon Sep 17 00:00:00 2001 From: Aaron Craelius Date: Thu, 3 Jun 2021 10:06:37 -0400 Subject: [PATCH 13/24] WIP --- app/cli/run.go | 4 ++-- app/internal/app_provider.go | 2 +- container/container.go | 9 ++++++++- 3 files changed, 11 insertions(+), 4 deletions(-) diff --git a/app/cli/run.go b/app/cli/run.go index 1b42110ed7bd..ea09da9417db 100644 --- a/app/cli/run.go +++ b/app/cli/run.go @@ -132,8 +132,8 @@ func initRootCmd(options Options, rootCmd *cobra.Command, a *internal.AppProvide keys.Commands(options.DefaultHome), ) - // add rosetta - rootCmd.AddCommand(server.RosettaCommand(clientCtx.InterfaceRegistry, clientCtx.JSONCodec)) + // TODO: add rosetta + // rootCmd.AddCommand(server.RosettaCommand(clientCtx.InterfaceRegistry, clientCtx.JSONCodec)) } func addModuleInitFlags(startCmd *cobra.Command) { diff --git a/app/internal/app_provider.go b/app/internal/app_provider.go index 339921788d72..f3bd01becae1 100644 --- a/app/internal/app_provider.go +++ b/app/internal/app_provider.go @@ -31,8 +31,8 @@ func NewAppProvider(config *app.Config) (*AppProvider, error) { } return &AppProvider{ + ModuleContainer: ctr, config: config, - container: ctr, moduleConfigMap: moduleConfigMap, }, nil } diff --git a/container/container.go b/container/container.go index 10c16f56110d..109b1807b7c9 100644 --- a/container/container.go +++ b/container/container.go @@ -21,10 +21,17 @@ func (c *Container) Invoke(fn interface{}) error { panic("TODO") } -// InitializeAll attempts to initialize all registered providers in the container. +// TryInitializeAll attempts to initialize all registered providers in the container. // It returns an error if a provider returns an error. If a given provider has // dependencies which cannot be resolved, an error is not returned and instead // that provider is not called. +func (c *Container) TryInitializeAll() error { + panic("TODO") +} + +// InitializeAll attempts to initialize all registered providers in the container. +// It returns an error if a provider returns an error or a dependency in the graph +// cannot be satisfied. func (c *Container) InitializeAll() error { panic("TODO") } From 76e9af25d03e1402cd7aa633ba5a051fa3a4d16b Mon Sep 17 00:00:00 2001 From: Aaron Craelius Date: Mon, 14 Jun 2021 15:39:51 -0400 Subject: [PATCH 14/24] WIP --- x/params/module/module.go | 6 ++++-- 1 file changed, 4 insertions(+), 2 deletions(-) diff --git a/x/params/module/module.go b/x/params/module/module.go index 75492957713e..b017e62078fd 100644 --- a/x/params/module/module.go +++ b/x/params/module/module.go @@ -24,7 +24,7 @@ type Inputs struct { LegacyAmino *codec.LegacyAmino Key *sdk.KVStoreKey TransientKey *sdk.TransientStoreKey - GovRouter govtypes.Router + GovRouter govtypes.Router `optional:true` } type Outputs struct { @@ -40,7 +40,9 @@ func (m Module) Provision(registrar container.Registrar) error { compat.RegisterAppModule(configurator, appMod) - inputs.GovRouter.AddRoute(paramproposal.RouterKey, params.NewParamChangeProposalHandler(keeper)) + if inputs.GovRouter != nil { + inputs.GovRouter.AddRoute(paramproposal.RouterKey, params.NewParamChangeProposalHandler(keeper)) + } return Outputs{Keeper: keeper} }) From b0ce058a269b3e31827df5aff98775871c46dd45 Mon Sep 17 00:00:00 2001 From: Aaron Craelius Date: Wed, 16 Jun 2021 15:57:17 -0400 Subject: [PATCH 15/24] POC module wiring with uber-go dig --- app/cli/configurator.go | 17 -------- app/cli/handler.go | 12 ++++++ app/compat/adapter.go | 79 +++++++++++++++++++++++++--------- app/configurator.go | 33 --------------- app/handler.go | 32 ++++++++++++++ app/internal/module_set.go | 2 +- app/key.go | 6 +++ app/provisioner.go | 8 +++- go.mod | 1 + go.sum | 3 ++ x/auth/module/module.go | 87 ++++++++++++++++++++++---------------- x/auth/tx/module/module.go | 2 +- x/gov/module/module.go | 42 +++++++++++------- x/params/module/module.go | 53 +++++++++++------------ 14 files changed, 226 insertions(+), 151 deletions(-) delete mode 100644 app/cli/configurator.go create mode 100644 app/cli/handler.go delete mode 100644 app/configurator.go create mode 100644 app/handler.go create mode 100644 app/key.go diff --git a/app/cli/configurator.go b/app/cli/configurator.go deleted file mode 100644 index 287855172e69..000000000000 --- a/app/cli/configurator.go +++ /dev/null @@ -1,17 +0,0 @@ -package cli - -import ( - "github.com/spf13/cobra" - - "github.com/cosmos/cosmos-sdk/app" -) - -type Configurator interface { - SetGenesisHandler(handler app.GenesisBasicHandler) - SetTxCommand(command *cobra.Command) - SetQueryCommand(command *cobra.Command) - - RootCommand() *cobra.Command - RootTxCommand() *cobra.Command - RootQueryCommand() *cobra.Command -} diff --git a/app/cli/handler.go b/app/cli/handler.go new file mode 100644 index 000000000000..32675a5ea6bd --- /dev/null +++ b/app/cli/handler.go @@ -0,0 +1,12 @@ +package cli + +import ( + "github.com/cosmos/cosmos-sdk/app" + "github.com/spf13/cobra" +) + +type Handler struct { + app.BasicGenesisHandler + TxCommand *cobra.Command + QueryCommand *cobra.Command +} diff --git a/app/compat/adapter.go b/app/compat/adapter.go index 02bea74c3f4e..5b6cd7ea51a6 100644 --- a/app/compat/adapter.go +++ b/app/compat/adapter.go @@ -5,6 +5,8 @@ import ( "encoding/json" "github.com/cosmos/cosmos-sdk/app/cli" + grpc1 "github.com/gogo/protobuf/grpc" + "google.golang.org/grpc" abci "github.com/tendermint/tendermint/abci/types" @@ -14,33 +16,70 @@ import ( "github.com/cosmos/cosmos-sdk/types/module" ) -func RegisterAppModuleBasic(configurator cli.Configurator, module module.AppModuleBasic) { - configurator.SetTxCommand(module.GetTxCmd()) - configurator.SetQueryCommand(module.GetQueryCmd()) - configurator.SetGenesisHandler(module) +func AppModuleBasicHandler(module module.AppModuleBasic) cli.Handler { + return cli.Handler{ + BasicGenesisHandler: app.BasicGenesisHandler{ + DefaultGenesis: module.DefaultGenesis, + ValidateGenesis: module.ValidateGenesis, + }, + TxCommand: module.GetTxCmd(), + QueryCommand: module.GetQueryCmd(), + } } -func RegisterAppModule(configurator app.Configurator, module module.AppModule) { - module.RegisterServices(configurator) - configurator.RegisterBeginBlocker(func(ctx context.Context, req abci.RequestBeginBlock) { - module.BeginBlock(types.UnwrapSDKContext(ctx), req) - }) - configurator.RegisterEndBlocker(func(ctx context.Context, req abci.RequestEndBlock) []abci.ValidatorUpdate { - return module.EndBlock(types.UnwrapSDKContext(ctx), req) - }) - configurator.RegisterGenesisHandler(genesisWrapper{module}) +func AppModuleHandler(module module.AppModule) app.Handler { + cfg := &configurator{} + module.RegisterServices(cfg) + return app.Handler{ + BasicGenesisHandler: app.BasicGenesisHandler{ + DefaultGenesis: module.DefaultGenesis, + ValidateGenesis: module.ValidateGenesis, + }, + InitGenesis: func(ctx context.Context, jsonCodec codec.JSONCodec, message json.RawMessage) []abci.ValidatorUpdate { + return module.InitGenesis(types.UnwrapSDKContext(ctx), jsonCodec, message) + }, + ExportGenesis: func(ctx context.Context, jsonCodec codec.JSONCodec) json.RawMessage { + return module.ExportGenesis(types.UnwrapSDKContext(ctx), jsonCodec) + }, + BeginBlocker: func(ctx context.Context, req abci.RequestBeginBlock) { + module.BeginBlock(types.UnwrapSDKContext(ctx), req) + }, + EndBlocker: func(ctx context.Context, req abci.RequestEndBlock) []abci.ValidatorUpdate { + return module.EndBlock(types.UnwrapSDKContext(ctx), req) + }, + MsgServices: cfg.msgServices, + QueryServices: cfg.queryServices, + } +} + +type configurator struct { + msgServices []app.ServiceImpl + queryServices []app.ServiceImpl +} + +func (c *configurator) MsgServer() grpc1.Server { + return &serviceRegistrar{impls: c.msgServices} } -type genesisWrapper struct { - module.AppModule +func (c *configurator) QueryServer() grpc1.Server { + return &serviceRegistrar{impls: c.queryServices} } -func (g genesisWrapper) InitGenesis(ctx context.Context, codec codec.JSONCodec, message json.RawMessage) []abci.ValidatorUpdate { - return g.AppModule.InitGenesis(types.UnwrapSDKContext(ctx), codec, message) +func (c *configurator) RegisterMigration(moduleName string, forVersion uint64, handler module.MigrationHandler) error { + return nil } -func (g genesisWrapper) ExportGenesis(ctx context.Context, codec codec.JSONCodec) json.RawMessage { - return g.AppModule.ExportGenesis(types.UnwrapSDKContext(ctx), codec) +var _ module.Configurator = &configurator{} + +type serviceRegistrar struct { + impls []app.ServiceImpl +} + +func (s *serviceRegistrar) RegisterService(desc *grpc.ServiceDesc, impl interface{}) { + s.impls = append(s.impls, app.ServiceImpl{ + Desc: desc, + Impl: impl, + }) } -var _ app.GenesisHandler = genesisWrapper{} +var _ grpc.ServiceRegistrar = &serviceRegistrar{} diff --git a/app/configurator.go b/app/configurator.go deleted file mode 100644 index 5d42ef9e75e1..000000000000 --- a/app/configurator.go +++ /dev/null @@ -1,33 +0,0 @@ -package app - -import ( - "context" - "encoding/json" - - "github.com/cosmos/cosmos-sdk/client" - - abci "github.com/tendermint/tendermint/abci/types" - - "github.com/cosmos/cosmos-sdk/codec" - "github.com/cosmos/cosmos-sdk/types/module" -) - -type Configurator interface { - module.Configurator - - RegisterBeginBlocker(func(context.Context, abci.RequestBeginBlock)) - RegisterEndBlocker(func(context.Context, abci.RequestEndBlock) []abci.ValidatorUpdate) - RegisterGenesisHandler(handler GenesisHandler) -} - -type GenesisBasicHandler interface { - DefaultGenesis(codec.JSONCodec) json.RawMessage - ValidateGenesis(codec.JSONCodec, client.TxEncodingConfig, json.RawMessage) error -} - -type GenesisHandler interface { - GenesisBasicHandler - - InitGenesis(context.Context, codec.JSONCodec, json.RawMessage) []abci.ValidatorUpdate - ExportGenesis(context.Context, codec.JSONCodec) json.RawMessage -} diff --git a/app/handler.go b/app/handler.go new file mode 100644 index 000000000000..03ca28c977c2 --- /dev/null +++ b/app/handler.go @@ -0,0 +1,32 @@ +package app + +import ( + "context" + "encoding/json" + + "github.com/cosmos/cosmos-sdk/client" + + "github.com/cosmos/cosmos-sdk/codec" + abci "github.com/tendermint/tendermint/abci/types" + "google.golang.org/grpc" +) + +type Handler struct { + BasicGenesisHandler + InitGenesis func(context.Context, codec.JSONCodec, json.RawMessage) []abci.ValidatorUpdate + ExportGenesis func(context.Context, codec.JSONCodec) json.RawMessage + BeginBlocker func(context.Context, abci.RequestBeginBlock) + EndBlocker func(context.Context, abci.RequestEndBlock) []abci.ValidatorUpdate + MsgServices []ServiceImpl + QueryServices []ServiceImpl +} + +type ServiceImpl struct { + Desc *grpc.ServiceDesc + Impl interface{} +} + +type BasicGenesisHandler struct { + DefaultGenesis func(codec.JSONCodec) json.RawMessage + ValidateGenesis func(codec.JSONCodec, client.TxEncodingConfig, json.RawMessage) error +} diff --git a/app/internal/module_set.go b/app/internal/module_set.go index 5dcbb0b684ab..0b7533a2736f 100644 --- a/app/internal/module_set.go +++ b/app/internal/module_set.go @@ -64,7 +64,7 @@ func (mc ModuleContainer) AddModule(scope container.Scope, config *codecTypes.An ctr: mc.Container, scope: scope, } - err := provisioner.Provision(registrar) + err := provisioner.Provision(nil, registrar) if err != nil { return err } diff --git a/app/key.go b/app/key.go new file mode 100644 index 000000000000..b6625b504f0d --- /dev/null +++ b/app/key.go @@ -0,0 +1,6 @@ +package app + +import "github.com/cosmos/cosmos-sdk/types" + +type KVStoreKeyProvider func(ModuleKey) *types.KVStoreKey +type TransientStoreKeyProvider func(ModuleKey) *types.TransientStoreKey diff --git a/app/provisioner.go b/app/provisioner.go index 19370eb4c26b..3b866a893ba5 100644 --- a/app/provisioner.go +++ b/app/provisioner.go @@ -3,5 +3,11 @@ package app import "github.com/cosmos/cosmos-sdk/container" type Provisioner interface { - Provision(registrar container.Registrar) error + Provision(key ModuleKey, registrar container.Registrar) error +} + +type ModuleKey interface { + moduleKey() + + Name() string } diff --git a/go.mod b/go.mod index 54b122aa9af1..f60dda3c168b 100644 --- a/go.mod +++ b/go.mod @@ -50,6 +50,7 @@ require ( github.com/tendermint/go-amino v0.16.0 github.com/tendermint/tendermint v0.34.10 github.com/tendermint/tm-db v0.6.4 + go.uber.org/dig v1.11.0 // indirect golang.org/x/crypto v0.0.0-20201221181555-eec23a3978ad golang.org/x/sys v0.0.0-20210510120138-977fb7262007 // indirect google.golang.org/genproto v0.0.0-20210114201628-6edceaf6022f diff --git a/go.sum b/go.sum index 1f651db3f9f5..475fe6c53fb3 100644 --- a/go.sum +++ b/go.sum @@ -732,6 +732,8 @@ go.opencensus.io v0.22.2/go.mod h1:yxeiOL68Rb0Xd1ddK5vPZ/oVn4vY4Ynel7k9FzqtOIw= go.uber.org/atomic v1.3.2/go.mod h1:gD2HeocX3+yG+ygLZcrzQJaqmWj9AIm7n08wl/qW/PE= go.uber.org/atomic v1.4.0/go.mod h1:gD2HeocX3+yG+ygLZcrzQJaqmWj9AIm7n08wl/qW/PE= go.uber.org/atomic v1.5.0/go.mod h1:sABNBOSYdrvTF6hTgEIbc7YasKWGhgEQZyfxyTvoXHQ= +go.uber.org/dig v1.11.0 h1:tGTnPJE8TIozwn2VdsAsK7yr7sxtI5IHFYHujIeLf1w= +go.uber.org/dig v1.11.0/go.mod h1:X34SnWGr8Fyla9zQNO2GSO2D+TIuqB14OS8JhYocIyw= go.uber.org/multierr v1.1.0/go.mod h1:wR5kodmAFQ0UK8QlbwjlSNy0Z68gJhDJUG5sjR94q/0= go.uber.org/multierr v1.3.0/go.mod h1:VgVr7evmIr6uPjLBxg28wmKNXyqE9akIJ5XnfpiKl+4= go.uber.org/tools v0.0.0-20190618225709-2cfd321de3ee/go.mod h1:vJERXedbb3MVM5f9Ejo0C68/HhF8uaILCdgjnY+goOA= @@ -904,6 +906,7 @@ golang.org/x/tools v0.0.0-20190911174233-4f2ddba30aff/go.mod h1:b+2E5dAYhXwXZwtn golang.org/x/tools v0.0.0-20191012152004-8de300cfc20a/go.mod h1:b+2E5dAYhXwXZwtnZ6UAqBI28+e2cm9otk0dWdXHAEo= golang.org/x/tools v0.0.0-20191029041327-9cc4af7d6b2c/go.mod h1:b+2E5dAYhXwXZwtnZ6UAqBI28+e2cm9otk0dWdXHAEo= golang.org/x/tools v0.0.0-20191029190741-b9c20aec41a5/go.mod h1:b+2E5dAYhXwXZwtnZ6UAqBI28+e2cm9otk0dWdXHAEo= +golang.org/x/tools v0.0.0-20191030062658-86caa796c7ab/go.mod h1:b+2E5dAYhXwXZwtnZ6UAqBI28+e2cm9otk0dWdXHAEo= golang.org/x/tools v0.0.0-20191112195655-aa38f8e97acc/go.mod h1:b+2E5dAYhXwXZwtnZ6UAqBI28+e2cm9otk0dWdXHAEo= golang.org/x/tools v0.0.0-20191119224855-298f0cb1881e/go.mod h1:b+2E5dAYhXwXZwtnZ6UAqBI28+e2cm9otk0dWdXHAEo= golang.org/x/tools v0.0.0-20191130070609-6e064ea0cf2d/go.mod h1:b+2E5dAYhXwXZwtnZ6UAqBI28+e2cm9otk0dWdXHAEo= diff --git a/x/auth/module/module.go b/x/auth/module/module.go index 5bc11d1308bc..6335e7a1af16 100644 --- a/x/auth/module/module.go +++ b/x/auth/module/module.go @@ -5,18 +5,16 @@ import ( "github.com/cosmos/cosmos-sdk/app/cli" "github.com/cosmos/cosmos-sdk/app/compat" "github.com/cosmos/cosmos-sdk/client" - "github.com/cosmos/cosmos-sdk/client/flags" "github.com/cosmos/cosmos-sdk/codec" codectypes "github.com/cosmos/cosmos-sdk/codec/types" "github.com/cosmos/cosmos-sdk/container" - sdk "github.com/cosmos/cosmos-sdk/types" "github.com/cosmos/cosmos-sdk/types/module" "github.com/cosmos/cosmos-sdk/x/auth" - authcmd "github.com/cosmos/cosmos-sdk/x/auth/client/cli" authkeeper "github.com/cosmos/cosmos-sdk/x/auth/keeper" "github.com/cosmos/cosmos-sdk/x/auth/simulation" "github.com/cosmos/cosmos-sdk/x/auth/types" - paramtypes "github.com/cosmos/cosmos-sdk/x/params/types" + parammodule "github.com/cosmos/cosmos-sdk/x/params/module" + "go.uber.org/dig" ) var ( @@ -25,25 +23,32 @@ var ( ) type Inputs struct { - container.StructArgs + dig.In - Codec codec.Codec - Key *sdk.KVStoreKey - ParamStore paramtypes.Subspace + Codec codec.Codec + KeyProvider app.KVStoreKeyProvider + SubspaceProvider parammodule.SubspaceProvider } type Outputs struct { - container.StructArgs + dig.Out + Handler app.Handler `group:"app.handler"` ViewKeeper types.ViewKeeper Keeper types.Keeper `security-role:"admin"` } +type CLIOutputs struct { + dig.Out + + Handler cli.Handler `group:"cli.handler"` +} + func (m Module) RegisterTypes(registry codectypes.InterfaceRegistry) { types.RegisterInterfaces(registry) } -func (m Module) Provision(registrar container.Registrar) error { +func (m Module) Provision(key app.ModuleKey, registrar container.Registrar) error { // provide AccountRetriever err := registrar.Provide(func() client.AccountRetriever { return types.AccountRetriever{} @@ -53,27 +58,30 @@ func (m Module) Provision(registrar container.Registrar) error { } // provide CLI handlers - err = registrar.Provide(func(configurator cli.Configurator) { - configurator.RootQueryCommand().AddCommand( - authcmd.GetAccountCmd(), - authcmd.QueryTxsByEventsCmd(), - authcmd.QueryTxCmd(), - ) - - configurator.RootTxCommand().AddCommand( - authcmd.GetSignCommand(), - authcmd.GetSignBatchCommand(), - authcmd.GetMultiSignCommand(), - authcmd.GetMultiSignBatchCmd(), - authcmd.GetValidateSignaturesCommand(), - flags.LineBreak, - authcmd.GetBroadcastCommand(), - authcmd.GetEncodeCommand(), - authcmd.GetDecodeCommand(), - flags.LineBreak, - ) - - compat.RegisterAppModuleBasic(configurator, auth.AppModuleBasic{}) + err = registrar.Provide(func() CLIOutputs { + // TODO + //configurator.RootQueryCommand().AddCommand( + // authcmd.GetAccountCmd(), + // authcmd.QueryTxsByEventsCmd(), + // authcmd.QueryTxCmd(), + //) + // + //configurator.RootTxCommand().AddCommand( + // authcmd.GetSignCommand(), + // authcmd.GetSignBatchCommand(), + // authcmd.GetMultiSignCommand(), + // authcmd.GetMultiSignBatchCmd(), + // authcmd.GetValidateSignaturesCommand(), + // flags.LineBreak, + // authcmd.GetBroadcastCommand(), + // authcmd.GetEncodeCommand(), + // authcmd.GetDecodeCommand(), + // flags.LineBreak, + //) + + return CLIOutputs{ + Handler: compat.AppModuleBasicHandler(auth.AppModuleBasic{}), + } }) if err != nil { return err @@ -81,7 +89,7 @@ func (m Module) Provision(registrar container.Registrar) error { // provide app handlers return registrar.Provide( - func(configurator app.Configurator, inputs Inputs) (Outputs, error) { + func(inputs Inputs) (Outputs, error) { var accCtr types.AccountConstructor if m.AccountConstructor != nil { err := inputs.Codec.UnpackAny(m.AccountConstructor, &accCtr) @@ -107,18 +115,23 @@ func (m Module) Provision(registrar container.Registrar) error { randomGenesisAccountsProvider = DefaultRandomGenesisAccountsProvider{} } - keeper := authkeeper.NewAccountKeeper(inputs.Codec, inputs.Key, inputs.ParamStore, func() types.AccountI { - return accCtr.NewAccount() - }, perms) + keeper := authkeeper.NewAccountKeeper( + inputs.Codec, + inputs.KeyProvider(key), + inputs.SubspaceProvider(key), + func() types.AccountI { + return accCtr.NewAccount() + }, + perms, + ) appMod := auth.NewAppModule(inputs.Codec, keeper, func(simState *module.SimulationState) types.GenesisAccounts { return randomGenesisAccountsProvider.RandomGenesisAccounts(simState) }) - compat.RegisterAppModule(configurator, appMod) - return Outputs{ ViewKeeper: viewOnlyKeeper{keeper}, Keeper: keeper, + Handler: compat.AppModuleHandler(appMod), }, nil }, ) diff --git a/x/auth/tx/module/module.go b/x/auth/tx/module/module.go index 2710071dded8..94588e1da817 100644 --- a/x/auth/tx/module/module.go +++ b/x/auth/tx/module/module.go @@ -12,7 +12,7 @@ var ( _ app.Provisioner = Module{} ) -func (m Module) Provision(registrar container.Registrar) error { +func (m Module) Provision(key app.ModuleKey, registrar container.Registrar) error { return registrar.Provide(func(marshaler codec.ProtoCodecMarshaler) client.TxConfig { signModes := m.EnabledSignModes if signModes == nil { diff --git a/x/gov/module/module.go b/x/gov/module/module.go index 5c3a896d46d3..6745a29371fb 100644 --- a/x/gov/module/module.go +++ b/x/gov/module/module.go @@ -6,11 +6,11 @@ import ( "github.com/cosmos/cosmos-sdk/codec" "github.com/cosmos/cosmos-sdk/codec/types" "github.com/cosmos/cosmos-sdk/container" - sdk "github.com/cosmos/cosmos-sdk/types" "github.com/cosmos/cosmos-sdk/x/gov" govkeeper "github.com/cosmos/cosmos-sdk/x/gov/keeper" govtypes "github.com/cosmos/cosmos-sdk/x/gov/types" - paramtypes "github.com/cosmos/cosmos-sdk/x/params/types" + parammodule "github.com/cosmos/cosmos-sdk/x/params/module" + "go.uber.org/dig" ) var ( @@ -22,13 +22,18 @@ func (m *Module) RegisterTypes(registry types.InterfaceRegistry) { govtypes.RegisterInterfaces(registry) } +type Route struct { + Path string + Handler govtypes.Handler +} + type Inputs struct { - container.StructArgs + dig.In - Router govtypes.Router - Codec codec.Codec - Key *sdk.KVStoreKey - ParamStore paramtypes.Subspace + Codec codec.Codec + KeyProvider app.KVStoreKeyProvider + SubspaceProvider parammodule.SubspaceProvider + Routes []Route `group:"cosmos.gov.v1.Route"` // TODO: use keepers defined in their respective modules AuthKeeper govtypes.AccountKeeper @@ -37,25 +42,32 @@ type Inputs struct { } type Outputs struct { - container.StructArgs + dig.Out + + Handler app.Handler `group:"app.handler"` } -func (m *Module) Provision(registrar container.Registrar) error { - err := registrar.Provide(func(configurator app.Configurator, inputs Inputs) Outputs { +func (m *Module) Provision(key app.ModuleKey, registrar container.Registrar) error { + err := registrar.Provide(func(inputs Inputs) Outputs { + router := govtypes.NewRouter() + for _, route := range inputs.Routes { + router.AddRoute(route.Path, route.Handler) + } k := govkeeper.NewKeeper( inputs.Codec, - inputs.Key, - inputs.ParamStore, + inputs.KeyProvider(key), + inputs.SubspaceProvider(key), inputs.AuthKeeper, inputs.BankKeeper, inputs.StakingKeeper, - inputs.Router, + router, ) am := gov.NewAppModule(inputs.Codec, k, inputs.AuthKeeper, inputs.BankKeeper) - compat.RegisterAppModule(configurator, am) - return Outputs{} + return Outputs{ + Handler: compat.AppModuleHandler(am), + } }) if err != nil { diff --git a/x/params/module/module.go b/x/params/module/module.go index b017e62078fd..1c42a0c69f15 100644 --- a/x/params/module/module.go +++ b/x/params/module/module.go @@ -5,12 +5,12 @@ import ( "github.com/cosmos/cosmos-sdk/app/compat" "github.com/cosmos/cosmos-sdk/codec" "github.com/cosmos/cosmos-sdk/container" - sdk "github.com/cosmos/cosmos-sdk/types" - govtypes "github.com/cosmos/cosmos-sdk/x/gov/types" + govmodule "github.com/cosmos/cosmos-sdk/x/gov/module" "github.com/cosmos/cosmos-sdk/x/params" paramskeeper "github.com/cosmos/cosmos-sdk/x/params/keeper" "github.com/cosmos/cosmos-sdk/x/params/types" paramproposal "github.com/cosmos/cosmos-sdk/x/params/types/proposal" + "go.uber.org/dig" ) var ( @@ -18,39 +18,40 @@ var ( ) type Inputs struct { - container.StructArgs + dig.In - Codec codec.BinaryCodec - LegacyAmino *codec.LegacyAmino - Key *sdk.KVStoreKey - TransientKey *sdk.TransientStoreKey - GovRouter govtypes.Router `optional:true` + Codec codec.BinaryCodec + LegacyAmino *codec.LegacyAmino + KeyProvider app.KVStoreKeyProvider + TransientKeyProvider app.TransientStoreKeyProvider } type Outputs struct { - container.StructArgs + dig.Out - Keeper paramskeeper.Keeper `security-role:"admin"` + Handler app.Handler `group:"app.handler"` + GovRoute govmodule.Route `group:"cosmos.gov.v1.Route"` + Keeper paramskeeper.Keeper `security-role:"admin"` + SubspaceProvider SubspaceProvider } -func (m Module) Provision(registrar container.Registrar) error { - err := registrar.Provide(func(configurator app.Configurator, inputs Inputs) Outputs { - keeper := paramskeeper.NewKeeper(inputs.Codec, inputs.LegacyAmino, inputs.Key, inputs.TransientKey) - appMod := params.NewAppModule(keeper) +type SubspaceProvider func(app.ModuleKey) types.Subspace - compat.RegisterAppModule(configurator, appMod) +func (m Module) Provision(key app.ModuleKey, registrar container.Registrar) error { + return registrar.Provide(func(inputs Inputs) Outputs { + keeper := paramskeeper.NewKeeper(inputs.Codec, inputs.LegacyAmino, inputs.KeyProvider(key), inputs.TransientKeyProvider(key)) + appMod := params.NewAppModule(keeper) - if inputs.GovRouter != nil { - inputs.GovRouter.AddRoute(paramproposal.RouterKey, params.NewParamChangeProposalHandler(keeper)) + return Outputs{ + Handler: compat.AppModuleHandler(appMod), + Keeper: keeper, + SubspaceProvider: func(key app.ModuleKey) types.Subspace { + return keeper.Subspace(key.Name()) + }, + GovRoute: govmodule.Route{ + Path: paramproposal.RouterKey, + Handler: params.NewParamChangeProposalHandler(keeper), + }, } - - return Outputs{Keeper: keeper} - }) - if err != nil { - return err - } - - return registrar.Provide(func(scope container.Scope, keeper paramskeeper.Keeper) types.Subspace { - return keeper.Subspace(string(scope)) }) } From 9ef7b9047249cbe143489f925564818f0abc78b1 Mon Sep 17 00:00:00 2001 From: Aaron Craelius Date: Wed, 16 Jun 2021 20:53:33 -0400 Subject: [PATCH 16/24] Working CLI --- app/cli/handler.go | 12 -- app/cli/run.go | 128 +++++++-------------- app/compat/adapter.go | 22 +--- app/decode.go | 17 +-- app/handler.go | 10 +- app/internal/app.go | 10 -- app/internal/app_provider.go | 28 +++-- app/internal/key.go | 1 + app/internal/module_set.go | 84 -------------- app/internal/providers.go | 14 --- app/key.go | 33 ++++++ app/module_set.go | 89 ++++++++++++++ app/provisioner.go | 6 - app/query/provider.go | 49 ++++++++ docs/core/proto-docs.md | 4 +- go.mod | 5 +- go.sum | 6 +- proto/cosmos/params/module/v1/module.proto | 2 +- simapp/simd/cmd/root.go | 6 +- simapp/v2/app.go | 1 + simapp/v2/app.yaml | 10 +- simapp/v2/app_test.go | 7 ++ x/auth/module/module.go | 39 +++---- x/auth/tx/module/module.go | 59 +++++++++- x/bank/module/module.go | 25 ++++ x/bank/module/module.pb.go | 3 +- x/genutil/client/cli/gentx.go | 11 +- x/genutil/client/cli/init.go | 7 +- x/genutil/client/cli/validate_genesis.go | 11 +- x/genutil/provider/provider.go | 54 +++++++++ x/genutil/types/handler.go | 18 +++ x/gov/module/module.go | 23 +--- x/gov/types/router.go | 5 + x/params/module/module.go | 14 +-- x/params/module/module.pb.go | 18 +-- x/params/types/subspace.go | 4 + 36 files changed, 482 insertions(+), 353 deletions(-) delete mode 100644 app/cli/handler.go create mode 100644 app/internal/key.go create mode 100644 app/module_set.go create mode 100644 app/query/provider.go create mode 100644 simapp/v2/app_test.go create mode 100644 x/bank/module/module.go create mode 100644 x/genutil/provider/provider.go create mode 100644 x/genutil/types/handler.go diff --git a/app/cli/handler.go b/app/cli/handler.go deleted file mode 100644 index 32675a5ea6bd..000000000000 --- a/app/cli/handler.go +++ /dev/null @@ -1,12 +0,0 @@ -package cli - -import ( - "github.com/cosmos/cosmos-sdk/app" - "github.com/spf13/cobra" -) - -type Handler struct { - app.BasicGenesisHandler - TxCommand *cobra.Command - QueryCommand *cobra.Command -} diff --git a/app/cli/run.go b/app/cli/run.go index ea09da9417db..edb071215fc8 100644 --- a/app/cli/run.go +++ b/app/cli/run.go @@ -3,33 +3,31 @@ package cli import ( "os" + "github.com/cosmos/cosmos-sdk/client/debug" + "github.com/cosmos/cosmos-sdk/client/keys" + "github.com/cosmos/cosmos-sdk/client/rpc" + sdk "github.com/cosmos/cosmos-sdk/types" + tmcli "github.com/tendermint/tendermint/libs/cli" + + "go.uber.org/dig" + "github.com/cosmos/cosmos-sdk/codec" codectypes "github.com/cosmos/cosmos-sdk/codec/types" "github.com/cosmos/cosmos-sdk/app/internal" - "github.com/spf13/cobra" - tmcli "github.com/tendermint/tendermint/libs/cli" - "github.com/cosmos/cosmos-sdk/app" "github.com/cosmos/cosmos-sdk/client" "github.com/cosmos/cosmos-sdk/client/config" - "github.com/cosmos/cosmos-sdk/client/debug" - "github.com/cosmos/cosmos-sdk/client/flags" - "github.com/cosmos/cosmos-sdk/client/keys" - "github.com/cosmos/cosmos-sdk/client/rpc" "github.com/cosmos/cosmos-sdk/server" svrcmd "github.com/cosmos/cosmos-sdk/server/cmd" - "github.com/cosmos/cosmos-sdk/simapp" - sdk "github.com/cosmos/cosmos-sdk/types" - "github.com/cosmos/cosmos-sdk/x/auth/types" - vestingcli "github.com/cosmos/cosmos-sdk/x/auth/vesting/client/cli" - banktypes "github.com/cosmos/cosmos-sdk/x/bank/types" "github.com/cosmos/cosmos-sdk/x/crisis" - genutilcli "github.com/cosmos/cosmos-sdk/x/genutil/client/cli" + "github.com/spf13/cobra" ) type Options struct { + AppName string + Description string DefaultAppConfig *app.Config DefaultHome string EnvPrefix string @@ -49,37 +47,49 @@ func Run(options Options) { } } +type Inputs struct { + dig.In + + RootCommands []*cobra.Command `group:"cli.root"` +} + func newRootCmd(options Options) *cobra.Command { a, err := internal.NewAppProvider(options.DefaultAppConfig) if err != nil { panic(err) } + err = a.Provide(func() string { return options.DefaultHome }, dig.Name("cli.default-home")) + if err != nil { + panic(err) + } + initClientCtx := client.Context{}. WithInput(os.Stdin). - WithAccountRetriever(types.AccountRetriever{}). WithHomeDir(options.DefaultHome). - WithViper("") // In simapp, we don't use any prefix for env variables. + WithViper(options.EnvPrefix) err = a.Invoke(func( codec codec.JSONCodec, registry codectypes.InterfaceRegistry, txConfig client.TxConfig, amino *codec.LegacyAmino, + accountRetriever client.AccountRetriever, ) { initClientCtx = initClientCtx. WithJSONCodec(codec). WithInterfaceRegistry(registry). WithTxConfig(txConfig). - WithLegacyAmino(amino) + WithLegacyAmino(amino). + WithAccountRetriever(accountRetriever) }) if err != nil { panic(err) } rootCmd := &cobra.Command{ - Use: "simd", - Short: "simulation app", + Use: options.AppName, + Short: options.Description, PersistentPreRunE: func(cmd *cobra.Command, _ []string) error { // set the default command outputs cmd.SetOut(cmd.OutOrStdout()) @@ -100,22 +110,18 @@ func newRootCmd(options Options) *cobra.Command { }, } - initRootCmd(options, rootCmd, a, initClientCtx) - - return rootCmd -} - -func initRootCmd(options Options, rootCmd *cobra.Command, a *internal.AppProvider, clientCtx client.Context) { cfg := sdk.GetConfig() cfg.Seal() + err = a.Invoke(func(inputs Inputs) { + rootCmd.AddCommand(inputs.RootCommands...) + }) + if err != nil { + panic(err) + } + rootCmd.AddCommand( - genutilcli.InitCmd(simapp.ModuleBasics, options.DefaultHome), - genutilcli.CollectGenTxsCmd(banktypes.GenesisBalancesIterator{}, options.DefaultHome), - genutilcli.MigrateGenesisCmd(), - genutilcli.GenTxCmd(simapp.ModuleBasics, clientCtx.TxConfig, banktypes.GenesisBalancesIterator{}, options.DefaultHome), - genutilcli.ValidateGenesisCmd(simapp.ModuleBasics), - //AddGenesisAccountCmd(options.DefaultHome), + //TODO: AddGenesisAccountCmd(options.DefaultHome), tmcli.NewCompletionCmd(rootCmd, true), //TODO: testnetCmd(simapp.ModuleBasics, banktypes.GenesisBalancesIterator{}), debug.Cmd(), @@ -127,70 +133,14 @@ func initRootCmd(options Options, rootCmd *cobra.Command, a *internal.AppProvide // add keybase, auxiliary RPC, query, and tx child commands rootCmd.AddCommand( rpc.StatusCommand(), - queryCommand(), - txCommand(), keys.Commands(options.DefaultHome), ) - // TODO: add rosetta - // rootCmd.AddCommand(server.RosettaCommand(clientCtx.InterfaceRegistry, clientCtx.JSONCodec)) + // TODO: rootCmd.AddCommand(server.RosettaCommand(clientCtx.InterfaceRegistry, clientCtx.JSONCodec)) + + return rootCmd } func addModuleInitFlags(startCmd *cobra.Command) { crisis.AddModuleInitFlags(startCmd) } - -func queryCommand() *cobra.Command { - cmd := &cobra.Command{ - Use: "query", - Aliases: []string{"q"}, - Short: "Querying subcommands", - DisableFlagParsing: true, - SuggestionsMinimumDistance: 2, - RunE: client.ValidateCmd, - } - - cmd.AddCommand( - // NOTE: moved these to the auth module: - //authcmd.GetAccountCmd(), - rpc.ValidatorCommand(), - rpc.BlockCommand(), - //authcmd.QueryTxsByEventsCmd(), - //authcmd.QueryTxCmd(), - ) - - simapp.ModuleBasics.AddQueryCommands(cmd) - cmd.PersistentFlags().String(flags.FlagChainID, "", "The network chain ID") - - return cmd -} - -func txCommand() *cobra.Command { - cmd := &cobra.Command{ - Use: "tx", - Short: "Transactions subcommands", - DisableFlagParsing: true, - SuggestionsMinimumDistance: 2, - RunE: client.ValidateCmd, - } - - cmd.AddCommand( - // NOTE: moved these to the auth module: - //authcmd.GetSignCommand(), - //authcmd.GetSignBatchCommand(), - //authcmd.GetMultiSignCommand(), - //authcmd.GetMultiSignBatchCmd(), - //authcmd.GetValidateSignaturesCommand(), - //flags.LineBreak, - //authcmd.GetBroadcastCommand(), - //authcmd.GetEncodeCommand(), - //authcmd.GetDecodeCommand(), - //flags.LineBreak, - vestingcli.GetTxCmd(), - ) - - simapp.ModuleBasics.AddTxCommands(cmd) - cmd.PersistentFlags().String(flags.FlagChainID, "", "The network chain ID") - - return cmd -} diff --git a/app/compat/adapter.go b/app/compat/adapter.go index 5b6cd7ea51a6..1da34daa4ce5 100644 --- a/app/compat/adapter.go +++ b/app/compat/adapter.go @@ -4,7 +4,6 @@ import ( "context" "encoding/json" - "github.com/cosmos/cosmos-sdk/app/cli" grpc1 "github.com/gogo/protobuf/grpc" "google.golang.org/grpc" @@ -16,31 +15,14 @@ import ( "github.com/cosmos/cosmos-sdk/types/module" ) -func AppModuleBasicHandler(module module.AppModuleBasic) cli.Handler { - return cli.Handler{ - BasicGenesisHandler: app.BasicGenesisHandler{ - DefaultGenesis: module.DefaultGenesis, - ValidateGenesis: module.ValidateGenesis, - }, - TxCommand: module.GetTxCmd(), - QueryCommand: module.GetQueryCmd(), - } -} - -func AppModuleHandler(module module.AppModule) app.Handler { +func AppModuleHandler(id app.ModuleID, module module.AppModule) app.Handler { cfg := &configurator{} module.RegisterServices(cfg) return app.Handler{ - BasicGenesisHandler: app.BasicGenesisHandler{ - DefaultGenesis: module.DefaultGenesis, - ValidateGenesis: module.ValidateGenesis, - }, + ID: id, InitGenesis: func(ctx context.Context, jsonCodec codec.JSONCodec, message json.RawMessage) []abci.ValidatorUpdate { return module.InitGenesis(types.UnwrapSDKContext(ctx), jsonCodec, message) }, - ExportGenesis: func(ctx context.Context, jsonCodec codec.JSONCodec) json.RawMessage { - return module.ExportGenesis(types.UnwrapSDKContext(ctx), jsonCodec) - }, BeginBlocker: func(ctx context.Context, req abci.RequestBeginBlock) { module.BeginBlock(types.UnwrapSDKContext(ctx), req) }, diff --git a/app/decode.go b/app/decode.go index 89806d126fc6..4b5acca13e52 100644 --- a/app/decode.go +++ b/app/decode.go @@ -1,16 +1,13 @@ package app import ( - "encoding/json" - - "github.com/gogo/protobuf/proto" - - "gopkg.in/yaml.v2" + "github.com/gogo/protobuf/jsonpb" + "sigs.k8s.io/yaml" ) func ReadJSONConfig(bz []byte) (*Config, error) { var cfg Config - err := proto.Unmarshal(bz, &cfg) + err := jsonpb.UnmarshalString(string(bz), &cfg) if err != nil { return nil, err } @@ -19,13 +16,7 @@ func ReadJSONConfig(bz []byte) (*Config, error) { } func ReadYAMLConfig(bz []byte) (*Config, error) { - var cfg map[string]interface{} - err := yaml.Unmarshal(bz, &cfg) - if err != nil { - return nil, err - } - - jsonBz, err := json.Marshal(cfg) + jsonBz, err := yaml.YAMLToJSON(bz) if err != nil { return nil, err } diff --git a/app/handler.go b/app/handler.go index 03ca28c977c2..9a565aea7663 100644 --- a/app/handler.go +++ b/app/handler.go @@ -4,17 +4,14 @@ import ( "context" "encoding/json" - "github.com/cosmos/cosmos-sdk/client" - "github.com/cosmos/cosmos-sdk/codec" abci "github.com/tendermint/tendermint/abci/types" "google.golang.org/grpc" ) type Handler struct { - BasicGenesisHandler + ID ModuleID InitGenesis func(context.Context, codec.JSONCodec, json.RawMessage) []abci.ValidatorUpdate - ExportGenesis func(context.Context, codec.JSONCodec) json.RawMessage BeginBlocker func(context.Context, abci.RequestBeginBlock) EndBlocker func(context.Context, abci.RequestEndBlock) []abci.ValidatorUpdate MsgServices []ServiceImpl @@ -25,8 +22,3 @@ type ServiceImpl struct { Desc *grpc.ServiceDesc Impl interface{} } - -type BasicGenesisHandler struct { - DefaultGenesis func(codec.JSONCodec) json.RawMessage - ValidateGenesis func(codec.JSONCodec, client.TxEncodingConfig, json.RawMessage) error -} diff --git a/app/internal/app.go b/app/internal/app.go index 303f247d3c62..e5e1547359d9 100644 --- a/app/internal/app.go +++ b/app/internal/app.go @@ -33,16 +33,6 @@ func (ap *AppProvider) AppCreator( traceStore io.Writer, appOpts servertypes.AppOptions, ) servertypes.Application { - err := ap.container.Provide(KVStoreKeyProvider) - if err != nil { - panic(err) - } - - err = ap.container.Provide(ConfiguratorProvider) - if err != nil { - panic(err) - } - var cache sdk.MultiStorePersistentCache if cast.ToBool(appOpts.Get(server.FlagInterBlockCache)) { diff --git a/app/internal/app_provider.go b/app/internal/app_provider.go index f3bd01becae1..20952c92776d 100644 --- a/app/internal/app_provider.go +++ b/app/internal/app_provider.go @@ -1,35 +1,49 @@ package internal import ( + "fmt" + "github.com/cosmos/cosmos-sdk/app" - "github.com/cosmos/cosmos-sdk/container" + "github.com/cosmos/cosmos-sdk/app/query" + "github.com/cosmos/cosmos-sdk/x/genutil/provider" ) type AppProvider struct { - *ModuleContainer + *app.ModuleContainer config *app.Config moduleConfigMap map[string]*app.ModuleConfig } -const txModuleScope container.Scope = "tx" - func NewAppProvider(config *app.Config) (*AppProvider, error) { - ctr := NewModuleContainer() + ctr := app.NewModuleContainer() moduleConfigMap := map[string]*app.ModuleConfig{} - err := ctr.AddModule(txModuleScope, config.Abci.TxHandler) + if config.Abci.TxHandler == nil { + return nil, fmt.Errorf("missing tx handler") + } + err := ctr.AddProtoModule("tx", config.Abci.TxHandler) if err != nil { return nil, err } for _, modConfig := range config.Modules { - err = ctr.AddModule(container.Scope(modConfig.Name), modConfig.Config) + err = ctr.AddProtoModule(modConfig.Name, modConfig.Config) if err != nil { return nil, err } moduleConfigMap[modConfig.Name] = modConfig } + err = ctr.Provide(provider.Provider) + if err != nil { + return nil, err + } + + err = ctr.Provide(query.Provider) + if err != nil { + return nil, err + } + return &AppProvider{ ModuleContainer: ctr, config: config, diff --git a/app/internal/key.go b/app/internal/key.go new file mode 100644 index 000000000000..5bf0569ce8cb --- /dev/null +++ b/app/internal/key.go @@ -0,0 +1 @@ +package internal diff --git a/app/internal/module_set.go b/app/internal/module_set.go index 0b7533a2736f..5bf0569ce8cb 100644 --- a/app/internal/module_set.go +++ b/app/internal/module_set.go @@ -1,85 +1 @@ package internal - -import ( - "reflect" - - "github.com/cosmos/cosmos-sdk/app" - "github.com/cosmos/cosmos-sdk/codec" - codecTypes "github.com/cosmos/cosmos-sdk/codec/types" - "github.com/cosmos/cosmos-sdk/container" - "github.com/gogo/protobuf/proto" -) - -type ModuleContainer struct { - *container.Container - typeRegistry codecTypes.TypeRegistry - codec codec.Codec - modules map[container.Scope]interface{} -} - -func NewModuleContainer() *ModuleContainer { - typeRegistry := codecTypes.NewInterfaceRegistry() - cdc := codec.NewProtoCodec(typeRegistry) - amino := codec.NewLegacyAmino() - ctr := container.NewContainer() - err := ctr.Provide(func() ( - codecTypes.TypeRegistry, - codec.Codec, - codec.BinaryCodec, - codec.JSONCodec, - *codec.LegacyAmino, - ) { - return typeRegistry, cdc, cdc, cdc, amino - }) - if err != nil { - panic(err) - } - - return &ModuleContainer{ - Container: ctr, - typeRegistry: typeRegistry, - codec: cdc, - modules: map[container.Scope]interface{}{}, - } -} - -func (mc ModuleContainer) AddModule(scope container.Scope, config *codecTypes.Any) error { - // unpack Any - msgTyp := proto.MessageType(config.TypeUrl) - mod := reflect.New(msgTyp).Interface().(proto.Message) - if err := proto.Unmarshal(config.Value, mod); err != nil { - return err - } - - mc.modules[scope] = mod - - // register types - if typeProvider, ok := mod.(app.TypeProvider); ok { - typeProvider.RegisterTypes(mc.typeRegistry) - } - - // register DI providers - if provisioner, ok := mod.(app.Provisioner); ok { - registrar := scopedRegistrar{ - ctr: mc.Container, - scope: scope, - } - err := provisioner.Provision(nil, registrar) - if err != nil { - return err - } - } - - return nil -} - -type scopedRegistrar struct { - ctr *container.Container - scope container.Scope -} - -var _ container.Registrar = scopedRegistrar{} - -func (s scopedRegistrar) Provide(fn interface{}) error { - return s.ctr.ProvideWithScope(fn, s.scope) -} diff --git a/app/internal/providers.go b/app/internal/providers.go index cefba0c995d4..5bf0569ce8cb 100644 --- a/app/internal/providers.go +++ b/app/internal/providers.go @@ -1,15 +1 @@ package internal - -import ( - "github.com/cosmos/cosmos-sdk/app" - "github.com/cosmos/cosmos-sdk/container" - "github.com/cosmos/cosmos-sdk/types" -) - -func KVStoreKeyProvider(scope container.Scope) *types.KVStoreKey { - return types.NewKVStoreKey(string(scope)) -} - -func ConfiguratorProvider(scope container.Scope) app.Configurator { - panic("TODO") -} diff --git a/app/key.go b/app/key.go index b6625b504f0d..d4ca7eb7b206 100644 --- a/app/key.go +++ b/app/key.go @@ -2,5 +2,38 @@ package app import "github.com/cosmos/cosmos-sdk/types" +type ModuleKey interface { + moduleKey() + ID() ModuleID +} + +type ModuleID interface { + moduleID() + Name() string +} + type KVStoreKeyProvider func(ModuleKey) *types.KVStoreKey type TransientStoreKeyProvider func(ModuleKey) *types.TransientStoreKey + +type moduleKey struct { + *moduleID +} + +type moduleID struct { + name string +} + +var _ ModuleKey = &moduleKey{} + +func (m *moduleKey) moduleKey() {} + +func (m *moduleKey) ID() ModuleID { + return m.moduleID +} + +func (m *moduleID) moduleID() { +} + +func (m *moduleID) Name() string { + return m.name +} diff --git a/app/module_set.go b/app/module_set.go new file mode 100644 index 000000000000..22c5c1ed8027 --- /dev/null +++ b/app/module_set.go @@ -0,0 +1,89 @@ +package app + +import ( + "reflect" + + "github.com/cosmos/cosmos-sdk/codec" + codecTypes "github.com/cosmos/cosmos-sdk/codec/types" + "github.com/cosmos/cosmos-sdk/container" + proto "github.com/gogo/protobuf/proto" + "go.uber.org/dig" +) + +type ModuleContainer struct { + *dig.Container + typeRegistry codecTypes.TypeRegistry + codec codec.Codec + modules map[ModuleKey]interface{} +} + +func NewModuleContainer() *ModuleContainer { + typeRegistry := codecTypes.NewInterfaceRegistry() + cdc := codec.NewProtoCodec(typeRegistry) + amino := codec.NewLegacyAmino() + ctr := dig.New() + err := ctr.Provide(func() ( + codecTypes.TypeRegistry, + codec.Codec, + codec.ProtoCodecMarshaler, + codec.BinaryCodec, + codec.JSONCodec, + *codec.LegacyAmino, + ) { + return typeRegistry, cdc, cdc, cdc, cdc, amino + }) + if err != nil { + panic(err) + } + + return &ModuleContainer{ + Container: ctr, + typeRegistry: typeRegistry, + codec: cdc, + modules: map[ModuleKey]interface{}{}, + } +} + +func (mc ModuleContainer) AddProtoModule(name string, config *codecTypes.Any) error { + // unpack Any + msgTyp := proto.MessageType(config.TypeUrl) + mod := reflect.New(msgTyp.Elem()).Interface().(proto.Message) + if err := proto.Unmarshal(config.Value, mod); err != nil { + return err + } + + return mc.AddModule(name, mod) +} + +func (mc *ModuleContainer) AddModule(name string, mod interface{}) error { + key := &moduleKey{&moduleID{name}} + mc.modules[key] = mod + + // register types + if typeProvider, ok := mod.(TypeProvider); ok { + typeProvider.RegisterTypes(mc.typeRegistry) + } + + // register DI providers + if provisioner, ok := mod.(Provisioner); ok { + registrar := registrar{ + ctr: mc.Container, + } + err := provisioner.Provision(nil, registrar) + if err != nil { + return err + } + } + + return nil +} + +type registrar struct { + ctr *dig.Container +} + +var _ container.Registrar = registrar{} + +func (s registrar) Provide(fn interface{}) error { + return s.ctr.Provide(fn) +} diff --git a/app/provisioner.go b/app/provisioner.go index 3b866a893ba5..43b21d72850d 100644 --- a/app/provisioner.go +++ b/app/provisioner.go @@ -5,9 +5,3 @@ import "github.com/cosmos/cosmos-sdk/container" type Provisioner interface { Provision(key ModuleKey, registrar container.Registrar) error } - -type ModuleKey interface { - moduleKey() - - Name() string -} diff --git a/app/query/provider.go b/app/query/provider.go new file mode 100644 index 000000000000..c67df5123675 --- /dev/null +++ b/app/query/provider.go @@ -0,0 +1,49 @@ +package query + +import ( + "github.com/cosmos/cosmos-sdk/client" + "github.com/cosmos/cosmos-sdk/client/flags" + "github.com/cosmos/cosmos-sdk/client/rpc" + "github.com/spf13/cobra" + "go.uber.org/dig" +) + +type Inputs struct { + dig.In + + Commands []*cobra.Command `group:"cosmos.query.v1.Command"` +} + +type Outputs struct { + dig.Out + + Command *cobra.Command `group:"cli.root"` +} + +func Provider(inputs Inputs) Outputs { + cmd := &cobra.Command{ + Use: "query", + Aliases: []string{"q"}, + Short: "Querying subcommands", + DisableFlagParsing: true, + SuggestionsMinimumDistance: 2, + RunE: client.ValidateCmd, + } + + cmd.AddCommand( + rpc.ValidatorCommand(), + rpc.BlockCommand(), + ) + + for _, c := range inputs.Commands { + if c != nil { + cmd.AddCommand(c) + } + } + + cmd.PersistentFlags().String(flags.FlagChainID, "", "The network chain ID") + + return Outputs{ + Command: cmd, + } +} diff --git a/docs/core/proto-docs.md b/docs/core/proto-docs.md index 85ab1780a5ab..76fd7f8423e4 100644 --- a/docs/core/proto-docs.md +++ b/docs/core/proto-docs.md @@ -419,7 +419,7 @@ - [Query](#cosmos.mint.v1beta1.Query) - [cosmos/params/module/v1/module.proto](#cosmos/params/module/v1/module.proto) - - [Module](#cosmos.params.modulev1beta1.Module) + - [Module](#cosmos.params.module.v1.Module) - [cosmos/params/v1beta1/params.proto](#cosmos/params/v1beta1/params.proto) - [ParamChange](#cosmos.params.v1beta1.ParamChange) @@ -5942,7 +5942,7 @@ Query provides defines the gRPC querier service. - + ### Module diff --git a/go.mod b/go.mod index f60dda3c168b..ce292ad163be 100644 --- a/go.mod +++ b/go.mod @@ -1,4 +1,4 @@ -go 1.15 +go 1.16 module github.com/cosmos/cosmos-sdk @@ -50,7 +50,7 @@ require ( github.com/tendermint/go-amino v0.16.0 github.com/tendermint/tendermint v0.34.10 github.com/tendermint/tm-db v0.6.4 - go.uber.org/dig v1.11.0 // indirect + go.uber.org/dig v1.11.0 golang.org/x/crypto v0.0.0-20201221181555-eec23a3978ad golang.org/x/sys v0.0.0-20210510120138-977fb7262007 // indirect google.golang.org/genproto v0.0.0-20210114201628-6edceaf6022f @@ -59,6 +59,7 @@ require ( gopkg.in/ini.v1 v1.61.0 // indirect gopkg.in/yaml.v2 v2.4.0 nhooyr.io/websocket v1.8.6 // indirect + sigs.k8s.io/yaml v1.2.0 ) replace google.golang.org/grpc => google.golang.org/grpc v1.33.2 diff --git a/go.sum b/go.sum index 475fe6c53fb3..ce8fd91460a0 100644 --- a/go.sum +++ b/go.sum @@ -219,7 +219,6 @@ github.com/go-logfmt/logfmt v0.4.0/go.mod h1:3RMwSq7FuexP4Kalkev3ejPJsZTpXXBr9+V github.com/go-logfmt/logfmt v0.5.0 h1:TrB8swr/68K7m9CcGut2g3UOihhbcbiMAYiuTXdEih4= github.com/go-logfmt/logfmt v0.5.0/go.mod h1:wCYkCAKZfumFQihp8CzCvQ3paCTfi41vtzG1KdI/P7A= github.com/go-ole/go-ole v1.2.1/go.mod h1:7FAglXiTm7HKlQRDeOQ6ZNUHidzCWXuZWq/1dTyBNF8= -github.com/go-playground/assert/v2 v2.0.1 h1:MsBgLAaY856+nPRTKrp3/OZK38U/wa0CcBYNjji3q3A= github.com/go-playground/assert/v2 v2.0.1/go.mod h1:VDjEfimB/XKnb+ZQfWdccd7VUvScMdVu0Titje2rxJ4= github.com/go-playground/locales v0.13.0 h1:HyWk6mgj5qFqCT5fjGBuRArbVDfE4hi8+e8ceBS/t7Q= github.com/go-playground/locales v0.13.0/go.mod h1:taPMhCMXrRLJO55olJkUXHZBHCxTMfnGwq/HNwmWNS8= @@ -517,7 +516,6 @@ github.com/openzipkin/zipkin-go v0.2.2/go.mod h1:NaW6tEwdmWMaCDZzg8sh+IBNOxHMPnh github.com/otiai10/copy v1.6.0 h1:IinKAryFFuPONZ7cm6T6E2QX/vcJwSnlaA5lfoaXIiQ= github.com/otiai10/copy v1.6.0/go.mod h1:XWfuS3CrI0R6IE0FbgHsEazaXO8G0LpMp9o8tos0x4E= github.com/otiai10/curr v0.0.0-20150429015615-9b4961190c95/go.mod h1:9qAhocn7zKJG+0mI8eUu6xqkFDYS2kb2saOteoSB3cE= -github.com/otiai10/curr v1.0.0 h1:TJIWdbX0B+kpNagQrjgq8bCMrbhiuX73M2XwgtDMoOI= github.com/otiai10/curr v1.0.0/go.mod h1:LskTG5wDwr8Rs+nNQ+1LlxRjAtTZZjtJW4rMXl6j4vs= github.com/otiai10/mint v1.3.0/go.mod h1:F5AjcsTsWUqX+Na9fpHb52P8pcRX2CI6A3ctIT91xUo= github.com/otiai10/mint v1.3.2 h1:VYWnrP5fXmz1MXvjuUvcBrXSjGE6xjON+axB/UrpO3E= @@ -776,6 +774,7 @@ golang.org/x/lint v0.0.0-20190301231843-5614ed5bae6f/go.mod h1:UVdnD1Gm6xHRNCYTk golang.org/x/lint v0.0.0-20190313153728-d0100b6bd8b3/go.mod h1:6SW0HCj/g11FgYtHlgUYUwCkIfeOF89ocIRzGO/8vkc= golang.org/x/lint v0.0.0-20190409202823-959b441ac422/go.mod h1:6SW0HCj/g11FgYtHlgUYUwCkIfeOF89ocIRzGO/8vkc= golang.org/x/lint v0.0.0-20190909230951-414d861bb4ac/go.mod h1:6SW0HCj/g11FgYtHlgUYUwCkIfeOF89ocIRzGO/8vkc= +golang.org/x/lint v0.0.0-20190930215403-16217165b5de h1:5hukYrvBGR8/eNkX5mdUezrA6JiaEZDtJb9Ei+1LlBs= golang.org/x/lint v0.0.0-20190930215403-16217165b5de/go.mod h1:6SW0HCj/g11FgYtHlgUYUwCkIfeOF89ocIRzGO/8vkc= golang.org/x/mobile v0.0.0-20190312151609-d3739f865fa6/go.mod h1:z+o9i4GpDbdi3rU15maQ/Ox0txvL9dWGYEHz965HBQE= golang.org/x/mobile v0.0.0-20190719004257-d2bd2a29d028/go.mod h1:E/iHnbuqvinMTCcRqshq8CkpyQDoeVncDDYHnLhea+o= @@ -917,6 +916,7 @@ golang.org/x/tools v0.0.0-20200522201501-cb1345f3a375/go.mod h1:EkVYQZoAsY45+roY golang.org/x/tools v0.0.0-20200619180055-7c47624df98f/go.mod h1:EkVYQZoAsY45+roYkvgYkIh4xh/qjgUK9TdY2XT94GE= golang.org/x/tools v0.0.0-20200717024301-6ddee64345a6/go.mod h1:njjCfa9FT2d7l9Bc6FUM5FLjQPp3cFF28FI3qnDFljA= golang.org/x/tools v0.0.0-20210106214847-113979e3529a/go.mod h1:emZCQorbCU4vsT4fOWvOPXz4eW1wZW4PmDk9uLelYpA= +golang.org/x/tools v0.1.0 h1:po9/4sTYwZU9lPhi1tOrb4hCv3qrhiQ77LZfGa2OjwY= golang.org/x/tools v0.1.0/go.mod h1:xkSsbof2nBLbhDlRMhhhyNLN/zl3eTqcnHD5viDpcZ0= golang.org/x/xerrors v0.0.0-20190717185122-a985d3407aa7/go.mod h1:I/5z698sn9Ka8TeJc9MKroUUfqBBauWjQqLJ2OPfmY0= golang.org/x/xerrors v0.0.0-20191011141410-1b5146add898/go.mod h1:I/5z698sn9Ka8TeJc9MKroUUfqBBauWjQqLJ2OPfmY0= @@ -1013,4 +1013,6 @@ nhooyr.io/websocket v1.8.6 h1:s+C3xAMLwGmlI31Nyn/eAehUlZPwfYZu2JXM621Q5/k= nhooyr.io/websocket v1.8.6/go.mod h1:B70DZP8IakI65RVQ51MsWP/8jndNma26DVA/nFSCgW0= rsc.io/binaryregexp v0.2.0/go.mod h1:qTv7/COck+e2FymRvadv62gMdZztPaShugOCi3I+8D8= sigs.k8s.io/yaml v1.1.0/go.mod h1:UJmg0vDUVViEyp3mgSv9WPwZCDxu4rQW1olrI1uml+o= +sigs.k8s.io/yaml v1.2.0 h1:kr/MCeFWJWTwyaHoR9c8EjH9OumOmoF9YGiZd7lFm/Q= +sigs.k8s.io/yaml v1.2.0/go.mod h1:yfXDCHCao9+ENCvLSE62v9VSji2MKu5jeNfTrofGhJc= sourcegraph.com/sourcegraph/appdash v0.0.0-20190731080439-ebfcffb1b5c0/go.mod h1:hI742Nqp5OhwiqlzhgfbWU4mW4yO10fP+LoT9WOswdU= diff --git a/proto/cosmos/params/module/v1/module.proto b/proto/cosmos/params/module/v1/module.proto index 599458e58e52..1f5e73f1c203 100644 --- a/proto/cosmos/params/module/v1/module.proto +++ b/proto/cosmos/params/module/v1/module.proto @@ -1,5 +1,5 @@ syntax = "proto3"; -package cosmos.params.modulev1beta1; +package cosmos.params.module.v1; option go_package = "github.com/cosmos/cosmos-sdk/x/params/module"; diff --git a/simapp/simd/cmd/root.go b/simapp/simd/cmd/root.go index e40412d076f4..735f7301ae35 100644 --- a/simapp/simd/cmd/root.go +++ b/simapp/simd/cmd/root.go @@ -81,11 +81,11 @@ func initRootCmd(rootCmd *cobra.Command, encodingConfig params.EncodingConfig) { cfg.Seal() rootCmd.AddCommand( - genutilcli.InitCmd(simapp.ModuleBasics, simapp.DefaultNodeHome), + genutilcli.InitCmd(simapp.ModuleBasics.DefaultGenesis, simapp.DefaultNodeHome), genutilcli.CollectGenTxsCmd(banktypes.GenesisBalancesIterator{}, simapp.DefaultNodeHome), genutilcli.MigrateGenesisCmd(), - genutilcli.GenTxCmd(simapp.ModuleBasics, encodingConfig.TxConfig, banktypes.GenesisBalancesIterator{}, simapp.DefaultNodeHome), - genutilcli.ValidateGenesisCmd(simapp.ModuleBasics), + genutilcli.GenTxCmd(simapp.ModuleBasics.ValidateGenesis, encodingConfig.TxConfig, banktypes.GenesisBalancesIterator{}, simapp.DefaultNodeHome), + genutilcli.ValidateGenesisCmd(simapp.ModuleBasics.ValidateGenesis), AddGenesisAccountCmd(simapp.DefaultNodeHome), tmcli.NewCompletionCmd(rootCmd, true), testnetCmd(simapp.ModuleBasics, banktypes.GenesisBalancesIterator{}), diff --git a/simapp/v2/app.go b/simapp/v2/app.go index 01ecec2f5c7a..041fe8654364 100644 --- a/simapp/v2/app.go +++ b/simapp/v2/app.go @@ -8,6 +8,7 @@ import ( // Load Modules _ "github.com/cosmos/cosmos-sdk/x/auth/module" + _ "github.com/cosmos/cosmos-sdk/x/auth/tx/module" _ "github.com/cosmos/cosmos-sdk/x/bank/module" _ "github.com/cosmos/cosmos-sdk/x/gov/module" _ "github.com/cosmos/cosmos-sdk/x/params/module" diff --git a/simapp/v2/app.yaml b/simapp/v2/app.yaml index 183f47686960..0314d42965c9 100644 --- a/simapp/v2/app.yaml +++ b/simapp/v2/app.yaml @@ -1,18 +1,18 @@ modules: - name: auth config: - @type: cosmos.auth.module.v1.Module + '@type': cosmos.auth.module.v1.Module - name: bank config: - @type: cosmos.bank.module.v1.Module + '@type': cosmos.bank.module.v1.Module - name: params config: - @type: cosmos.params.module.v1.Module + '@type': cosmos.params.module.v1.Module - name: gov config: - @type: cosmos.gov.module.v1.Module + '@type': cosmos.gov.module.v1.Module abci: begin_block: [auth, bank] end_block: [gov] tx_handler: - @type: cosmos.tx.module.v1.Module + '@type': cosmos.tx.module.v1.Module diff --git a/simapp/v2/app_test.go b/simapp/v2/app_test.go new file mode 100644 index 000000000000..fed9d8ab9b93 --- /dev/null +++ b/simapp/v2/app_test.go @@ -0,0 +1,7 @@ +package main + +import "testing" + +func TestRun(t *testing.T) { + main() +} diff --git a/x/auth/module/module.go b/x/auth/module/module.go index 6335e7a1af16..82e0da521489 100644 --- a/x/auth/module/module.go +++ b/x/auth/module/module.go @@ -2,7 +2,6 @@ package module import ( "github.com/cosmos/cosmos-sdk/app" - "github.com/cosmos/cosmos-sdk/app/cli" "github.com/cosmos/cosmos-sdk/app/compat" "github.com/cosmos/cosmos-sdk/client" "github.com/cosmos/cosmos-sdk/codec" @@ -10,10 +9,12 @@ import ( "github.com/cosmos/cosmos-sdk/container" "github.com/cosmos/cosmos-sdk/types/module" "github.com/cosmos/cosmos-sdk/x/auth" + authcmd "github.com/cosmos/cosmos-sdk/x/auth/client/cli" authkeeper "github.com/cosmos/cosmos-sdk/x/auth/keeper" "github.com/cosmos/cosmos-sdk/x/auth/simulation" "github.com/cosmos/cosmos-sdk/x/auth/types" - parammodule "github.com/cosmos/cosmos-sdk/x/params/module" + types2 "github.com/cosmos/cosmos-sdk/x/params/types" + "github.com/spf13/cobra" "go.uber.org/dig" ) @@ -27,7 +28,7 @@ type Inputs struct { Codec codec.Codec KeyProvider app.KVStoreKeyProvider - SubspaceProvider parammodule.SubspaceProvider + SubspaceProvider types2.SubspaceProvider } type Outputs struct { @@ -41,7 +42,8 @@ type Outputs struct { type CLIOutputs struct { dig.Out - Handler cli.Handler `group:"cli.handler"` + TxCmd *cobra.Command `group:"cosmos.tx.v1.Command"` + QueryCmd []*cobra.Command `group:"cosmos.query.v1.Command,flatten"` } func (m Module) RegisterTypes(registry codectypes.InterfaceRegistry) { @@ -59,28 +61,13 @@ func (m Module) Provision(key app.ModuleKey, registrar container.Registrar) erro // provide CLI handlers err = registrar.Provide(func() CLIOutputs { - // TODO - //configurator.RootQueryCommand().AddCommand( - // authcmd.GetAccountCmd(), - // authcmd.QueryTxsByEventsCmd(), - // authcmd.QueryTxCmd(), - //) - // - //configurator.RootTxCommand().AddCommand( - // authcmd.GetSignCommand(), - // authcmd.GetSignBatchCommand(), - // authcmd.GetMultiSignCommand(), - // authcmd.GetMultiSignBatchCmd(), - // authcmd.GetValidateSignaturesCommand(), - // flags.LineBreak, - // authcmd.GetBroadcastCommand(), - // authcmd.GetEncodeCommand(), - // authcmd.GetDecodeCommand(), - // flags.LineBreak, - //) - + am := auth.AppModuleBasic{} return CLIOutputs{ - Handler: compat.AppModuleBasicHandler(auth.AppModuleBasic{}), + TxCmd: am.GetTxCmd(), + QueryCmd: []*cobra.Command{ + am.GetQueryCmd(), + authcmd.GetAccountCmd(), + }, } }) if err != nil { @@ -131,7 +118,7 @@ func (m Module) Provision(key app.ModuleKey, registrar container.Registrar) erro return Outputs{ ViewKeeper: viewOnlyKeeper{keeper}, Keeper: keeper, - Handler: compat.AppModuleHandler(appMod), + Handler: compat.AppModuleHandler(key.ID(), appMod), }, nil }, ) diff --git a/x/auth/tx/module/module.go b/x/auth/tx/module/module.go index 94588e1da817..ea3ca7501820 100644 --- a/x/auth/tx/module/module.go +++ b/x/auth/tx/module/module.go @@ -3,22 +3,75 @@ package module import ( "github.com/cosmos/cosmos-sdk/app" "github.com/cosmos/cosmos-sdk/client" + "github.com/cosmos/cosmos-sdk/client/flags" "github.com/cosmos/cosmos-sdk/codec" "github.com/cosmos/cosmos-sdk/container" + authcmd "github.com/cosmos/cosmos-sdk/x/auth/client/cli" "github.com/cosmos/cosmos-sdk/x/auth/tx" + "github.com/spf13/cobra" + "go.uber.org/dig" ) var ( _ app.Provisioner = Module{} ) -func (m Module) Provision(key app.ModuleKey, registrar container.Registrar) error { - return registrar.Provide(func(marshaler codec.ProtoCodecMarshaler) client.TxConfig { +type Inputs struct { + dig.In + + Commands []*cobra.Command `group:"cosmos.tx.v1.Command"` + Marshaler codec.ProtoCodecMarshaler +} + +type Outputs struct { + dig.Out + + TxConfig client.TxConfig + Command *cobra.Command `group:"cli.root"` + QueryCommands []*cobra.Command `group:"cosmos.query.v1.Command,flatten"` +} + +func (m Module) Provision(_ app.ModuleKey, registrar container.Registrar) error { + return registrar.Provide(func(inputs Inputs) Outputs { signModes := m.EnabledSignModes if signModes == nil { signModes = tx.DefaultSignModes } - return tx.NewTxConfig(marshaler, signModes) + cmd := &cobra.Command{ + Use: "tx", + Short: "Transactions subcommands", + DisableFlagParsing: true, + SuggestionsMinimumDistance: 2, + RunE: client.ValidateCmd, + } + + cmd.AddCommand( + authcmd.GetSignCommand(), + authcmd.GetSignBatchCommand(), + authcmd.GetMultiSignCommand(), + authcmd.GetMultiSignBatchCmd(), + authcmd.GetValidateSignaturesCommand(), + authcmd.GetBroadcastCommand(), + authcmd.GetEncodeCommand(), + authcmd.GetDecodeCommand(), + ) + + for _, c := range inputs.Commands { + if c != nil { + cmd.AddCommand(c) + } + } + + cmd.PersistentFlags().String(flags.FlagChainID, "", "The network chain ID") + + return Outputs{ + TxConfig: tx.NewTxConfig(inputs.Marshaler, signModes), + Command: cmd, + QueryCommands: []*cobra.Command{ + authcmd.QueryTxsByEventsCmd(), + authcmd.QueryTxCmd(), + }, + } }) } diff --git a/x/bank/module/module.go b/x/bank/module/module.go new file mode 100644 index 000000000000..ea5ead7b7e1c --- /dev/null +++ b/x/bank/module/module.go @@ -0,0 +1,25 @@ +package module + +import ( + "github.com/cosmos/cosmos-sdk/app" + "github.com/cosmos/cosmos-sdk/container" + "github.com/cosmos/cosmos-sdk/x/bank/types" + genutiltypes "github.com/cosmos/cosmos-sdk/x/genutil/types" + "go.uber.org/dig" +) + +var _ app.Provisioner = Module{} + +type Outputs struct { + dig.Out + + GenesisBalancesIterator genutiltypes.GenesisBalancesIterator +} + +func (m Module) Provision(key app.ModuleKey, registrar container.Registrar) error { + return registrar.Provide(func() Outputs { + return Outputs{ + GenesisBalancesIterator: types.GenesisBalancesIterator{}, + } + }) +} diff --git a/x/bank/module/module.pb.go b/x/bank/module/module.pb.go index 5ded78f054a2..b557657693d1 100644 --- a/x/bank/module/module.pb.go +++ b/x/bank/module/module.pb.go @@ -5,10 +5,11 @@ package module import ( fmt "fmt" - proto "github.com/gogo/protobuf/proto" io "io" math "math" math_bits "math/bits" + + proto "github.com/gogo/protobuf/proto" ) // Reference imports to suppress errors if they are not otherwise used. diff --git a/x/genutil/client/cli/gentx.go b/x/genutil/client/cli/gentx.go index 107990ed1182..2333f498e3e3 100644 --- a/x/genutil/client/cli/gentx.go +++ b/x/genutil/client/cli/gentx.go @@ -10,6 +10,8 @@ import ( "os" "path/filepath" + "github.com/cosmos/cosmos-sdk/codec" + "github.com/pkg/errors" "github.com/spf13/cobra" tmos "github.com/tendermint/tendermint/libs/os" @@ -21,7 +23,6 @@ import ( "github.com/cosmos/cosmos-sdk/crypto/keyring" "github.com/cosmos/cosmos-sdk/server" sdk "github.com/cosmos/cosmos-sdk/types" - "github.com/cosmos/cosmos-sdk/types/module" "github.com/cosmos/cosmos-sdk/version" authclient "github.com/cosmos/cosmos-sdk/x/auth/client" "github.com/cosmos/cosmos-sdk/x/genutil" @@ -30,7 +31,11 @@ import ( ) // GenTxCmd builds the application's gentx command. -func GenTxCmd(mbm module.BasicManager, txEncCfg client.TxEncodingConfig, genBalIterator types.GenesisBalancesIterator, defaultNodeHome string) *cobra.Command { +func GenTxCmd(validateGenesis func( + codec.JSONCodec, + client.TxEncodingConfig, + map[string]json.RawMessage, +) error, txEncCfg client.TxEncodingConfig, genBalIterator types.GenesisBalancesIterator, defaultNodeHome string) *cobra.Command { ipDefault, _ := server.ExternalIP() fsCreateValidator, defaultsDesc := cli.CreateValidatorMsgFlagSet(ipDefault) @@ -94,7 +99,7 @@ $ %s gentx my-key-name 1000000stake --home=/path/to/home/dir --keyring-backend=o return errors.Wrap(err, "failed to unmarshal genesis state") } - if err = mbm.ValidateGenesis(cdc, txEncCfg, genesisState); err != nil { + if err = validateGenesis(cdc, txEncCfg, genesisState); err != nil { return errors.Wrap(err, "failed to validate genesis state") } diff --git a/x/genutil/client/cli/init.go b/x/genutil/client/cli/init.go index 84a03c877dab..64d1c1eed235 100644 --- a/x/genutil/client/cli/init.go +++ b/x/genutil/client/cli/init.go @@ -7,6 +7,8 @@ import ( "os" "path/filepath" + "github.com/cosmos/cosmos-sdk/codec" + "github.com/cosmos/go-bip39" "github.com/pkg/errors" "github.com/spf13/cobra" @@ -21,7 +23,6 @@ import ( "github.com/cosmos/cosmos-sdk/client/input" "github.com/cosmos/cosmos-sdk/server" sdk "github.com/cosmos/cosmos-sdk/types" - "github.com/cosmos/cosmos-sdk/types/module" "github.com/cosmos/cosmos-sdk/x/genutil" ) @@ -64,7 +65,7 @@ func displayInfo(info printInfo) error { // InitCmd returns a command that initializes all files needed for Tendermint // and the respective application. -func InitCmd(mbm module.BasicManager, defaultNodeHome string) *cobra.Command { +func InitCmd(defaultGenesis func(codec.JSONCodec) map[string]json.RawMessage, defaultNodeHome string) *cobra.Command { cmd := &cobra.Command{ Use: "init [moniker]", Short: "Initialize private validator, p2p, genesis, and application configuration files", @@ -113,7 +114,7 @@ func InitCmd(mbm module.BasicManager, defaultNodeHome string) *cobra.Command { if !overwrite && tmos.FileExists(genFile) { return fmt.Errorf("genesis.json file already exists: %v", genFile) } - appState, err := json.MarshalIndent(mbm.DefaultGenesis(cdc), "", " ") + appState, err := json.MarshalIndent(defaultGenesis(cdc), "", " ") if err != nil { return errors.Wrap(err, "Failed to marshall default genesis state") } diff --git a/x/genutil/client/cli/validate_genesis.go b/x/genutil/client/cli/validate_genesis.go index 30102277d670..376952ce7363 100644 --- a/x/genutil/client/cli/validate_genesis.go +++ b/x/genutil/client/cli/validate_genesis.go @@ -4,18 +4,23 @@ import ( "encoding/json" "fmt" + "github.com/cosmos/cosmos-sdk/codec" + "github.com/spf13/cobra" tmtypes "github.com/tendermint/tendermint/types" "github.com/cosmos/cosmos-sdk/client" "github.com/cosmos/cosmos-sdk/server" - "github.com/cosmos/cosmos-sdk/types/module" ) const chainUpgradeGuide = "https://docs.cosmos.network/master/migrations/chain-upgrade-guide-040.html" // ValidateGenesisCmd takes a genesis file, and makes sure that it is valid. -func ValidateGenesisCmd(mbm module.BasicManager) *cobra.Command { +func ValidateGenesisCmd(validateGenesis func( + codec.JSONCodec, + client.TxEncodingConfig, + map[string]json.RawMessage, +) error) *cobra.Command { return &cobra.Command{ Use: "validate-genesis [file]", Args: cobra.RangeArgs(0, 1), @@ -44,7 +49,7 @@ func ValidateGenesisCmd(mbm module.BasicManager) *cobra.Command { return fmt.Errorf("error unmarshalling genesis doc %s: %s", genesis, err.Error()) } - if err = mbm.ValidateGenesis(cdc, clientCtx.TxConfig, genState); err != nil { + if err = validateGenesis(cdc, clientCtx.TxConfig, genState); err != nil { return fmt.Errorf("error validating genesis file %s: %s", genesis, err.Error()) } diff --git a/x/genutil/provider/provider.go b/x/genutil/provider/provider.go new file mode 100644 index 000000000000..8e401b679d7a --- /dev/null +++ b/x/genutil/provider/provider.go @@ -0,0 +1,54 @@ +package provider + +import ( + "encoding/json" + + "github.com/cosmos/cosmos-sdk/client" + "github.com/cosmos/cosmos-sdk/codec" + genutilcli "github.com/cosmos/cosmos-sdk/x/genutil/client/cli" + "github.com/cosmos/cosmos-sdk/x/genutil/types" + "github.com/spf13/cobra" + "go.uber.org/dig" +) + +type Inputs struct { + dig.In + + DefaultHome string `name:"cli.default-home"` + Handlers []types.Handler `group:"cosmos.genutil.v1.Handler"` + GenesisBalancesIterator types.GenesisBalancesIterator + TxConfig client.TxConfig +} + +type Outputs struct { + dig.Out + + RootCommands []*cobra.Command `group:"cli.root,flatten"` +} + +func Provider(inputs Inputs) Outputs { + validateGenesis := func(cdc codec.JSONCodec, txEncCfg client.TxEncodingConfig, genesis map[string]json.RawMessage) error { + for _, b := range inputs.Handlers { + if err := b.ValidateGenesis(cdc, txEncCfg, genesis[b.ID.Name()]); err != nil { + return err + } + } + return nil + } + + return Outputs{ + RootCommands: []*cobra.Command{ + genutilcli.InitCmd(func(cdc codec.JSONCodec) map[string]json.RawMessage { + genesis := make(map[string]json.RawMessage) + for _, b := range inputs.Handlers { + genesis[b.ID.Name()] = b.DefaultGenesis(cdc) + } + return genesis + }, inputs.DefaultHome), + genutilcli.CollectGenTxsCmd(inputs.GenesisBalancesIterator, inputs.DefaultHome), + genutilcli.MigrateGenesisCmd(), + genutilcli.GenTxCmd(validateGenesis, inputs.TxConfig, inputs.GenesisBalancesIterator, inputs.DefaultHome), + genutilcli.ValidateGenesisCmd(validateGenesis), + }, + } +} diff --git a/x/genutil/types/handler.go b/x/genutil/types/handler.go new file mode 100644 index 000000000000..46909941e6ec --- /dev/null +++ b/x/genutil/types/handler.go @@ -0,0 +1,18 @@ +package types + +import ( + "encoding/json" + + sdk "github.com/cosmos/cosmos-sdk/types" + + "github.com/cosmos/cosmos-sdk/app" + "github.com/cosmos/cosmos-sdk/client" + "github.com/cosmos/cosmos-sdk/codec" +) + +type Handler struct { + ID app.ModuleID + DefaultGenesis func(codec.JSONCodec) json.RawMessage + ValidateGenesis func(codec.JSONCodec, client.TxEncodingConfig, json.RawMessage) error + ExportGenesis func(sdk.Context, codec.JSONCodec) json.RawMessage +} diff --git a/x/gov/module/module.go b/x/gov/module/module.go index 6745a29371fb..0d4134f28fa9 100644 --- a/x/gov/module/module.go +++ b/x/gov/module/module.go @@ -9,7 +9,7 @@ import ( "github.com/cosmos/cosmos-sdk/x/gov" govkeeper "github.com/cosmos/cosmos-sdk/x/gov/keeper" govtypes "github.com/cosmos/cosmos-sdk/x/gov/types" - parammodule "github.com/cosmos/cosmos-sdk/x/params/module" + types2 "github.com/cosmos/cosmos-sdk/x/params/types" "go.uber.org/dig" ) @@ -22,18 +22,13 @@ func (m *Module) RegisterTypes(registry types.InterfaceRegistry) { govtypes.RegisterInterfaces(registry) } -type Route struct { - Path string - Handler govtypes.Handler -} - type Inputs struct { dig.In Codec codec.Codec KeyProvider app.KVStoreKeyProvider - SubspaceProvider parammodule.SubspaceProvider - Routes []Route `group:"cosmos.gov.v1.Route"` + SubspaceProvider types2.SubspaceProvider + Routes []govtypes.Route `group:"cosmos.gov.v1.Route"` // TODO: use keepers defined in their respective modules AuthKeeper govtypes.AccountKeeper @@ -48,7 +43,7 @@ type Outputs struct { } func (m *Module) Provision(key app.ModuleKey, registrar container.Registrar) error { - err := registrar.Provide(func(inputs Inputs) Outputs { + return registrar.Provide(func(inputs Inputs) Outputs { router := govtypes.NewRouter() for _, route := range inputs.Routes { router.AddRoute(route.Path, route.Handler) @@ -66,15 +61,7 @@ func (m *Module) Provision(key app.ModuleKey, registrar container.Registrar) err am := gov.NewAppModule(inputs.Codec, k, inputs.AuthKeeper, inputs.BankKeeper) return Outputs{ - Handler: compat.AppModuleHandler(am), + Handler: compat.AppModuleHandler(key.ID(), am), } }) - - if err != nil { - return err - } - - return registrar.Provide(func() govtypes.Router { - return govtypes.NewRouter() - }) } diff --git a/x/gov/types/router.go b/x/gov/types/router.go index abb59e7a72e0..a6a330d0141a 100644 --- a/x/gov/types/router.go +++ b/x/gov/types/router.go @@ -75,3 +75,8 @@ func (rtr *router) GetRoute(path string) Handler { return rtr.routes[path] } + +type Route struct { + Path string + Handler Handler +} diff --git a/x/params/module/module.go b/x/params/module/module.go index 1c42a0c69f15..0babaa80ee51 100644 --- a/x/params/module/module.go +++ b/x/params/module/module.go @@ -5,7 +5,7 @@ import ( "github.com/cosmos/cosmos-sdk/app/compat" "github.com/cosmos/cosmos-sdk/codec" "github.com/cosmos/cosmos-sdk/container" - govmodule "github.com/cosmos/cosmos-sdk/x/gov/module" + types2 "github.com/cosmos/cosmos-sdk/x/gov/types" "github.com/cosmos/cosmos-sdk/x/params" paramskeeper "github.com/cosmos/cosmos-sdk/x/params/keeper" "github.com/cosmos/cosmos-sdk/x/params/types" @@ -30,25 +30,23 @@ type Outputs struct { dig.Out Handler app.Handler `group:"app.handler"` - GovRoute govmodule.Route `group:"cosmos.gov.v1.Route"` + GovRoute types2.Route `group:"cosmos.gov.v1.Route"` Keeper paramskeeper.Keeper `security-role:"admin"` - SubspaceProvider SubspaceProvider + SubspaceProvider types.SubspaceProvider } -type SubspaceProvider func(app.ModuleKey) types.Subspace - func (m Module) Provision(key app.ModuleKey, registrar container.Registrar) error { return registrar.Provide(func(inputs Inputs) Outputs { keeper := paramskeeper.NewKeeper(inputs.Codec, inputs.LegacyAmino, inputs.KeyProvider(key), inputs.TransientKeyProvider(key)) appMod := params.NewAppModule(keeper) return Outputs{ - Handler: compat.AppModuleHandler(appMod), + Handler: compat.AppModuleHandler(key.ID(), appMod), Keeper: keeper, SubspaceProvider: func(key app.ModuleKey) types.Subspace { - return keeper.Subspace(key.Name()) + return keeper.Subspace(key.ID().Name()) }, - GovRoute: govmodule.Route{ + GovRoute: types2.Route{ Path: paramproposal.RouterKey, Handler: params.NewParamChangeProposalHandler(keeper), }, diff --git a/x/params/module/module.pb.go b/x/params/module/module.pb.go index fdf0567ca53f..997a6f5b55bf 100644 --- a/x/params/module/module.pb.go +++ b/x/params/module/module.pb.go @@ -59,7 +59,7 @@ func (m *Module) XXX_DiscardUnknown() { var xxx_messageInfo_Module proto.InternalMessageInfo func init() { - proto.RegisterType((*Module)(nil), "cosmos.params.modulev1beta1.Module") + proto.RegisterType((*Module)(nil), "cosmos.params.module.v1.Module") } func init() { @@ -67,16 +67,16 @@ func init() { } var fileDescriptor_b0bff310e651d184 = []byte{ - // 138 bytes of a gzipped FileDescriptorProto + // 133 bytes of a gzipped FileDescriptorProto 0x1f, 0x8b, 0x08, 0x00, 0x00, 0x00, 0x00, 0x00, 0x02, 0xff, 0xe2, 0x52, 0x49, 0xce, 0x2f, 0xce, 0xcd, 0x2f, 0xd6, 0x2f, 0x48, 0x2c, 0x4a, 0xcc, 0x2d, 0xd6, 0xcf, 0xcd, 0x4f, 0x29, 0xcd, 0x49, - 0xd5, 0x2f, 0x33, 0x84, 0xb2, 0xf4, 0x0a, 0x8a, 0xf2, 0x4b, 0xf2, 0x85, 0xa4, 0x21, 0xaa, 0xf4, - 0x20, 0xaa, 0xf4, 0x20, 0x72, 0x65, 0x86, 0x49, 0xa9, 0x25, 0x89, 0x86, 0x4a, 0x1c, 0x5c, 0x6c, - 0xbe, 0x60, 0x01, 0x27, 0xb7, 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, 0xd2, - 0x49, 0xcf, 0x2c, 0xc9, 0x28, 0x4d, 0xd2, 0x4b, 0xce, 0xcf, 0xd5, 0x87, 0xda, 0x08, 0xa1, 0x74, - 0x8b, 0x53, 0xb2, 0xf5, 0x2b, 0x50, 0xad, 0x4f, 0x62, 0x03, 0xdb, 0x6a, 0x0c, 0x08, 0x00, 0x00, - 0xff, 0xff, 0x81, 0xbe, 0x90, 0x03, 0x9d, 0x00, 0x00, 0x00, + 0xd5, 0x2f, 0x33, 0x84, 0xb2, 0xf4, 0x0a, 0x8a, 0xf2, 0x4b, 0xf2, 0x85, 0xc4, 0x21, 0xaa, 0xf4, + 0x20, 0xaa, 0xf4, 0xa0, 0x72, 0x65, 0x86, 0x4a, 0x1c, 0x5c, 0x6c, 0xbe, 0x60, 0x8e, 0x93, 0xdb, + 0x89, 0x47, 0x72, 0x8c, 0x17, 0x1e, 0xc9, 0x31, 0x3e, 0x78, 0x24, 0xc7, 0x38, 0xe1, 0xb1, 0x1c, + 0xc3, 0x85, 0xc7, 0x72, 0x0c, 0x37, 0x1e, 0xcb, 0x31, 0x44, 0xe9, 0xa4, 0x67, 0x96, 0x64, 0x94, + 0x26, 0xe9, 0x25, 0xe7, 0xe7, 0xea, 0x43, 0x6d, 0x83, 0x50, 0xba, 0xc5, 0x29, 0xd9, 0xfa, 0x15, + 0xa8, 0x56, 0x27, 0xb1, 0x81, 0x6d, 0x34, 0x06, 0x04, 0x00, 0x00, 0xff, 0xff, 0xed, 0x41, 0xd8, + 0x5f, 0x99, 0x00, 0x00, 0x00, } func (m *Module) Marshal() (dAtA []byte, err error) { diff --git a/x/params/types/subspace.go b/x/params/types/subspace.go index 42afe6cc9b21..5535d339cf69 100644 --- a/x/params/types/subspace.go +++ b/x/params/types/subspace.go @@ -4,6 +4,8 @@ import ( "fmt" "reflect" + "github.com/cosmos/cosmos-sdk/app" + "github.com/cosmos/cosmos-sdk/codec" "github.com/cosmos/cosmos-sdk/store/prefix" sdk "github.com/cosmos/cosmos-sdk/types" @@ -275,3 +277,5 @@ func (ros ReadOnlySubspace) Modified(ctx sdk.Context, key []byte) bool { func (ros ReadOnlySubspace) Name() string { return ros.s.Name() } + +type SubspaceProvider func(app.ModuleKey) Subspace From 8b5e32f523da44e847b7661477048f41cb88dcfd Mon Sep 17 00:00:00 2001 From: Aaron Craelius Date: Fri, 18 Jun 2021 16:01:34 -0400 Subject: [PATCH 17/24] Provide* approach --- app/cli/run.go | 23 ++++-- app/dig_test.go | 34 ++++++++ app/module_set.go | 16 +++- app/provisioner.go | 4 + app/query/provider.go | 9 ++- x/auth/module/module.go | 142 +++++++++++++++------------------ x/auth/tx/module/module.go | 11 +-- x/genutil/provider/provider.go | 7 +- 8 files changed, 145 insertions(+), 101 deletions(-) create mode 100644 app/dig_test.go diff --git a/app/cli/run.go b/app/cli/run.go index edb071215fc8..8d7d44226e80 100644 --- a/app/cli/run.go +++ b/app/cli/run.go @@ -3,11 +3,12 @@ package cli import ( "os" + tmcli "github.com/tendermint/tendermint/libs/cli" + "github.com/cosmos/cosmos-sdk/client/debug" "github.com/cosmos/cosmos-sdk/client/keys" "github.com/cosmos/cosmos-sdk/client/rpc" sdk "github.com/cosmos/cosmos-sdk/types" - tmcli "github.com/tendermint/tendermint/libs/cli" "go.uber.org/dig" @@ -16,13 +17,14 @@ import ( "github.com/cosmos/cosmos-sdk/app/internal" + "github.com/spf13/cobra" + "github.com/cosmos/cosmos-sdk/app" "github.com/cosmos/cosmos-sdk/client" "github.com/cosmos/cosmos-sdk/client/config" "github.com/cosmos/cosmos-sdk/server" svrcmd "github.com/cosmos/cosmos-sdk/server/cmd" "github.com/cosmos/cosmos-sdk/x/crisis" - "github.com/spf13/cobra" ) type Options struct { @@ -50,16 +52,16 @@ func Run(options Options) { type Inputs struct { dig.In - RootCommands []*cobra.Command `group:"cli.root"` + RootCommands []*cobra.Command `group:"root"` } func newRootCmd(options Options) *cobra.Command { - a, err := internal.NewAppProvider(options.DefaultAppConfig) + appProvider, err := internal.NewAppProvider(options.DefaultAppConfig) if err != nil { panic(err) } - err = a.Provide(func() string { return options.DefaultHome }, dig.Name("cli.default-home")) + err = appProvider.Provide(func() string { return options.DefaultHome }, dig.Name("cli.default-home")) if err != nil { panic(err) } @@ -69,7 +71,7 @@ func newRootCmd(options Options) *cobra.Command { WithHomeDir(options.DefaultHome). WithViper(options.EnvPrefix) - err = a.Invoke(func( + err = appProvider.Invoke(func( codec codec.JSONCodec, registry codectypes.InterfaceRegistry, txConfig client.TxConfig, @@ -113,13 +115,18 @@ func newRootCmd(options Options) *cobra.Command { cfg := sdk.GetConfig() cfg.Seal() - err = a.Invoke(func(inputs Inputs) { + err = appProvider.Invoke(func(inputs Inputs) { rootCmd.AddCommand(inputs.RootCommands...) }) if err != nil { panic(err) } + err = dig.Visualize(appProvider.Container, os.Stdout) + if err != nil { + panic(err) + } + rootCmd.AddCommand( //TODO: AddGenesisAccountCmd(options.DefaultHome), tmcli.NewCompletionCmd(rootCmd, true), @@ -128,7 +135,7 @@ func newRootCmd(options Options) *cobra.Command { config.Cmd(), ) - server.AddCommands(rootCmd, options.DefaultHome, a.AppCreator, a.AppExportor, addModuleInitFlags) + server.AddCommands(rootCmd, options.DefaultHome, appProvider.AppCreator, appProvider.AppExportor, addModuleInitFlags) // add keybase, auxiliary RPC, query, and tx child commands rootCmd.AddCommand( diff --git a/app/dig_test.go b/app/dig_test.go new file mode 100644 index 000000000000..045357bf9dbe --- /dev/null +++ b/app/dig_test.go @@ -0,0 +1,34 @@ +package app + +import ( + "testing" + + "github.com/stretchr/testify/require" + "go.uber.org/dig" +) + +type Inputs struct { + dig.In + + Ints []int `group:"abc"` + Floats []float64 `group:"abc"` +} + +func TestDig(t *testing.T) { + ctr := dig.New() + require.NoError(t, ctr.Provide(func() int { + return 4 + }, dig.Group("abc"))) + require.NoError(t, ctr.Provide(func() int { + return 5 + }, dig.Group("abc"))) + require.NoError(t, ctr.Provide(func() float64 { + return 7 + }, dig.Group("abc"))) + require.NoError(t, ctr.Provide(func() float64 { + return 10 + }, dig.Group("abc"))) + require.NoError(t, ctr.Invoke(func(in Inputs) { + t.Logf("%+v\n", in) + })) +} diff --git a/app/module_set.go b/app/module_set.go index 22c5c1ed8027..3e8eab6190af 100644 --- a/app/module_set.go +++ b/app/module_set.go @@ -2,12 +2,14 @@ package app import ( "reflect" + "strings" + + proto "github.com/gogo/protobuf/proto" + "go.uber.org/dig" "github.com/cosmos/cosmos-sdk/codec" codecTypes "github.com/cosmos/cosmos-sdk/codec/types" "github.com/cosmos/cosmos-sdk/container" - proto "github.com/gogo/protobuf/proto" - "go.uber.org/dig" ) type ModuleContainer struct { @@ -75,6 +77,16 @@ func (mc *ModuleContainer) AddModule(name string, mod interface{}) error { } } + // register DI Provide* methods + modTy := reflect.TypeOf(mod) + numMethods := modTy.NumMethod() + for i := 0; i < numMethods; i++ { + method := modTy.Method(i) + if strings.HasPrefix(method.Name, "Provide") { + // TODO wrap function and provide + } + } + return nil } diff --git a/app/provisioner.go b/app/provisioner.go index 43b21d72850d..b89c5def43b2 100644 --- a/app/provisioner.go +++ b/app/provisioner.go @@ -5,3 +5,7 @@ import "github.com/cosmos/cosmos-sdk/container" type Provisioner interface { Provision(key ModuleKey, registrar container.Registrar) error } + +type Provider interface { + Provide(key ModuleKey) ([]interface{}, error) +} diff --git a/app/query/provider.go b/app/query/provider.go index c67df5123675..63a4ec684a87 100644 --- a/app/query/provider.go +++ b/app/query/provider.go @@ -1,23 +1,24 @@ package query import ( + "github.com/spf13/cobra" + "go.uber.org/dig" + "github.com/cosmos/cosmos-sdk/client" "github.com/cosmos/cosmos-sdk/client/flags" "github.com/cosmos/cosmos-sdk/client/rpc" - "github.com/spf13/cobra" - "go.uber.org/dig" ) type Inputs struct { dig.In - Commands []*cobra.Command `group:"cosmos.query.v1.Command"` + Commands []*cobra.Command `group:"query"` } type Outputs struct { dig.Out - Command *cobra.Command `group:"cli.root"` + Command *cobra.Command `group:"root"` } func Provider(inputs Inputs) Outputs { diff --git a/x/auth/module/module.go b/x/auth/module/module.go index 82e0da521489..9c34ed46a0f4 100644 --- a/x/auth/module/module.go +++ b/x/auth/module/module.go @@ -1,26 +1,23 @@ package module import ( + "github.com/spf13/cobra" + "go.uber.org/dig" + "github.com/cosmos/cosmos-sdk/app" - "github.com/cosmos/cosmos-sdk/app/compat" "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/container" "github.com/cosmos/cosmos-sdk/types/module" "github.com/cosmos/cosmos-sdk/x/auth" authcmd "github.com/cosmos/cosmos-sdk/x/auth/client/cli" - authkeeper "github.com/cosmos/cosmos-sdk/x/auth/keeper" "github.com/cosmos/cosmos-sdk/x/auth/simulation" "github.com/cosmos/cosmos-sdk/x/auth/types" types2 "github.com/cosmos/cosmos-sdk/x/params/types" - "github.com/spf13/cobra" - "go.uber.org/dig" ) var ( _ app.TypeProvider = Module{} - _ app.Provisioner = Module{} ) type Inputs struct { @@ -39,91 +36,78 @@ type Outputs struct { Keeper types.Keeper `security-role:"admin"` } -type CLIOutputs struct { +type CLICommands struct { dig.Out - TxCmd *cobra.Command `group:"cosmos.tx.v1.Command"` - QueryCmd []*cobra.Command `group:"cosmos.query.v1.Command,flatten"` + TxCmd *cobra.Command `group:"tx"` + QueryCmd []*cobra.Command `group:"query,flatten"` } func (m Module) RegisterTypes(registry codectypes.InterfaceRegistry) { types.RegisterInterfaces(registry) } -func (m Module) Provision(key app.ModuleKey, registrar container.Registrar) error { - // provide AccountRetriever - err := registrar.Provide(func() client.AccountRetriever { - return types.AccountRetriever{} - }) - if err != nil { - return err - } - - // provide CLI handlers - err = registrar.Provide(func() CLIOutputs { - am := auth.AppModuleBasic{} - return CLIOutputs{ - TxCmd: am.GetTxCmd(), - QueryCmd: []*cobra.Command{ - am.GetQueryCmd(), - authcmd.GetAccountCmd(), - }, - } - }) - if err != nil { - return err - } - - // provide app handlers - return registrar.Provide( - func(inputs Inputs) (Outputs, error) { - var accCtr types.AccountConstructor - if m.AccountConstructor != nil { - err := inputs.Codec.UnpackAny(m.AccountConstructor, &accCtr) - if err != nil { - return Outputs{}, err - } - } else { - accCtr = DefaultAccountConstructor{} - } - - perms := map[string][]string{} - for _, perm := range m.Permissions { - perms[perm.Address] = perm.Permissions - } - - var randomGenesisAccountsProvider types.RandomGenesisAccountsProvider - if m.RandomGenesisAccountsProvider != nil { - err := inputs.Codec.UnpackAny(m.RandomGenesisAccountsProvider, &randomGenesisAccountsProvider) - if err != nil { - return Outputs{}, err - } - } else { - randomGenesisAccountsProvider = DefaultRandomGenesisAccountsProvider{} - } - - keeper := authkeeper.NewAccountKeeper( - inputs.Codec, - inputs.KeyProvider(key), - inputs.SubspaceProvider(key), - func() types.AccountI { - return accCtr.NewAccount() - }, - perms, - ) - appMod := auth.NewAppModule(inputs.Codec, keeper, func(simState *module.SimulationState) types.GenesisAccounts { - return randomGenesisAccountsProvider.RandomGenesisAccounts(simState) - }) +func (Module) ProvideAccountRetriever() client.AccountRetriever { + return types.AccountRetriever{} +} - return Outputs{ - ViewKeeper: viewOnlyKeeper{keeper}, - Keeper: keeper, - Handler: compat.AppModuleHandler(key.ID(), appMod), - }, nil +func (Module) ProvideCLICommands() CLICommands { + am := auth.AppModuleBasic{} + return CLICommands{ + TxCmd: am.GetTxCmd(), + QueryCmd: []*cobra.Command{ + am.GetQueryCmd(), + authcmd.GetAccountCmd(), }, - ) + } } +//func (m Module) ProvideAppHandler(key app.ModuleKey, inputs Inputs) (Outputs, error) { +// var accCtr types.AccountConstructor +// if m.AccountConstructor != nil { +// err := inputs.Codec.UnpackAny(m.AccountConstructor, &accCtr) +// if err != nil { +// return Outputs{}, err +// } +// } else { +// accCtr = DefaultAccountConstructor{} +// } +// +// perms := map[string][]string{} +// for _, perm := range m.Permissions { +// perms[perm.Address] = perm.Permissions +// } +// +// var randomGenesisAccountsProvider types.RandomGenesisAccountsProvider +// if m.RandomGenesisAccountsProvider != nil { +// err := inputs.Codec.UnpackAny(m.RandomGenesisAccountsProvider, &randomGenesisAccountsProvider) +// if err != nil { +// return Outputs{}, err +// } +// } else { +// randomGenesisAccountsProvider = DefaultRandomGenesisAccountsProvider{} +// } +// +// keeper := authkeeper.NewAccountKeeper( +// inputs.Codec, +// inputs.KeyProvider(key), +// inputs.SubspaceProvider(key), +// func() types.AccountI { +// return accCtr.NewAccount() +// }, +// perms, +// ) +// appMod := auth.NewAppModule(inputs.Codec, keeper, func(simState *module.SimulationState) types.GenesisAccounts { +// return randomGenesisAccountsProvider.RandomGenesisAccounts(simState) +// }) +// +// return Outputs{ +// ViewKeeper: viewOnlyKeeper{keeper}, +// Keeper: keeper, +// Handler: compat.AppModuleHandler(key.ID(), appMod), +// }, nil +//} + func (m DefaultAccountConstructor) NewAccount() types.AccountI { return &types.BaseAccount{} } diff --git a/x/auth/tx/module/module.go b/x/auth/tx/module/module.go index ea3ca7501820..66b786df46b3 100644 --- a/x/auth/tx/module/module.go +++ b/x/auth/tx/module/module.go @@ -1,6 +1,9 @@ package module import ( + "github.com/spf13/cobra" + "go.uber.org/dig" + "github.com/cosmos/cosmos-sdk/app" "github.com/cosmos/cosmos-sdk/client" "github.com/cosmos/cosmos-sdk/client/flags" @@ -8,8 +11,6 @@ import ( "github.com/cosmos/cosmos-sdk/container" authcmd "github.com/cosmos/cosmos-sdk/x/auth/client/cli" "github.com/cosmos/cosmos-sdk/x/auth/tx" - "github.com/spf13/cobra" - "go.uber.org/dig" ) var ( @@ -19,7 +20,7 @@ var ( type Inputs struct { dig.In - Commands []*cobra.Command `group:"cosmos.tx.v1.Command"` + Commands []*cobra.Command `group:"tx"` Marshaler codec.ProtoCodecMarshaler } @@ -27,8 +28,8 @@ type Outputs struct { dig.Out TxConfig client.TxConfig - Command *cobra.Command `group:"cli.root"` - QueryCommands []*cobra.Command `group:"cosmos.query.v1.Command,flatten"` + Command *cobra.Command `group:"root"` + QueryCommands []*cobra.Command `group:"query,flatten"` } func (m Module) Provision(_ app.ModuleKey, registrar container.Registrar) error { diff --git a/x/genutil/provider/provider.go b/x/genutil/provider/provider.go index 8e401b679d7a..f50f4b1bd4a0 100644 --- a/x/genutil/provider/provider.go +++ b/x/genutil/provider/provider.go @@ -3,12 +3,13 @@ package provider import ( "encoding/json" + "github.com/spf13/cobra" + "go.uber.org/dig" + "github.com/cosmos/cosmos-sdk/client" "github.com/cosmos/cosmos-sdk/codec" genutilcli "github.com/cosmos/cosmos-sdk/x/genutil/client/cli" "github.com/cosmos/cosmos-sdk/x/genutil/types" - "github.com/spf13/cobra" - "go.uber.org/dig" ) type Inputs struct { @@ -23,7 +24,7 @@ type Inputs struct { type Outputs struct { dig.Out - RootCommands []*cobra.Command `group:"cli.root,flatten"` + RootCommands []*cobra.Command `group:"root,flatten"` } func Provider(inputs Inputs) Outputs { From 7206af7a48f82ee5f06738a941111ebbfb9a4fe5 Mon Sep 17 00:00:00 2001 From: Aaron Craelius Date: Fri, 18 Jun 2021 17:45:34 -0400 Subject: [PATCH 18/24] Provide* DI --- app/module_set.go | 55 +++++++++++++++++++++++- x/auth/module/module.go | 93 +++++++++++++++++++++-------------------- 2 files changed, 102 insertions(+), 46 deletions(-) diff --git a/app/module_set.go b/app/module_set.go index 3e8eab6190af..51a175014e55 100644 --- a/app/module_set.go +++ b/app/module_set.go @@ -1,6 +1,7 @@ package app import ( + "fmt" "reflect" "strings" @@ -57,6 +58,8 @@ func (mc ModuleContainer) AddProtoModule(name string, config *codecTypes.Any) er return mc.AddModule(name, mod) } +var moduleKeyType = reflect.TypeOf((*ModuleKey)(nil)).Elem() + func (mc *ModuleContainer) AddModule(name string, mod interface{}) error { key := &moduleKey{&moduleID{name}} mc.modules[key] = mod @@ -83,7 +86,57 @@ func (mc *ModuleContainer) AddModule(name string, mod interface{}) error { for i := 0; i < numMethods; i++ { method := modTy.Method(i) if strings.HasPrefix(method.Name, "Provide") { - // TODO wrap function and provide + methTyp := method.Type + if methTyp.IsVariadic() { + return fmt.Errorf("variadic Provide methods are not supported") + } + + m := methTyp.NumIn() - 1 + if m < 0 { + return fmt.Errorf("unexpected number of method arguments %d", m) + } + + moduleKeyIdx := -1 + var in []reflect.Type + for i := 0; i < m; i++ { + ty := methTyp.In(i + 1) + if ty == moduleKeyType { + if moduleKeyIdx >= 0 { + modTy := reflect.TypeOf(mod) + if modTy.Kind() == reflect.Ptr { + modTy = modTy.Elem() + } + return fmt.Errorf("%v can only be used as a parameter in a Provide method once, used twice in %s.%s.%s", moduleKeyType, + modTy.PkgPath(), modTy.Name(), method.Name) + } + moduleKeyIdx = i + 1 + } else { + in = append(in) + } + } + + n := methTyp.NumOut() + out := make([]reflect.Type, n) + for i := 0; i < n; i++ { + out[i] = methTyp.Out(i) + } + + fnTyp := reflect.FuncOf(in, out, false) + + fn := reflect.MakeFunc(fnTyp, func(args []reflect.Value) (results []reflect.Value) { + args = append([]reflect.Value{reflect.ValueOf(mod)}, args...) + if moduleKeyIdx >= 0 { + args0 := append(args[:moduleKeyIdx], reflect.ValueOf(key)) + args = append(args0, args[moduleKeyIdx:]...) + } + fmt.Printf("modTy: %s, method: %+v, idx:%d, args:%+v\n", reflect.TypeOf(mod).Elem().PkgPath(), method, moduleKeyIdx, args) + return method.Func.Call(args) + }) + + err := mc.Provide(fn.Interface()) + if err != nil { + return err + } } } diff --git a/x/auth/module/module.go b/x/auth/module/module.go index 9c34ed46a0f4..09d4193f70b0 100644 --- a/x/auth/module/module.go +++ b/x/auth/module/module.go @@ -4,6 +4,9 @@ import ( "github.com/spf13/cobra" "go.uber.org/dig" + "github.com/cosmos/cosmos-sdk/app/compat" + authkeeper "github.com/cosmos/cosmos-sdk/x/auth/keeper" + "github.com/cosmos/cosmos-sdk/app" "github.com/cosmos/cosmos-sdk/client" "github.com/cosmos/cosmos-sdk/codec" @@ -62,51 +65,51 @@ func (Module) ProvideCLICommands() CLICommands { } } -//func (m Module) ProvideAppHandler(key app.ModuleKey, inputs Inputs) (Outputs, error) { -// var accCtr types.AccountConstructor -// if m.AccountConstructor != nil { -// err := inputs.Codec.UnpackAny(m.AccountConstructor, &accCtr) -// if err != nil { -// return Outputs{}, err -// } -// } else { -// accCtr = DefaultAccountConstructor{} -// } -// -// perms := map[string][]string{} -// for _, perm := range m.Permissions { -// perms[perm.Address] = perm.Permissions -// } -// -// var randomGenesisAccountsProvider types.RandomGenesisAccountsProvider -// if m.RandomGenesisAccountsProvider != nil { -// err := inputs.Codec.UnpackAny(m.RandomGenesisAccountsProvider, &randomGenesisAccountsProvider) -// if err != nil { -// return Outputs{}, err -// } -// } else { -// randomGenesisAccountsProvider = DefaultRandomGenesisAccountsProvider{} -// } -// -// keeper := authkeeper.NewAccountKeeper( -// inputs.Codec, -// inputs.KeyProvider(key), -// inputs.SubspaceProvider(key), -// func() types.AccountI { -// return accCtr.NewAccount() -// }, -// perms, -// ) -// appMod := auth.NewAppModule(inputs.Codec, keeper, func(simState *module.SimulationState) types.GenesisAccounts { -// return randomGenesisAccountsProvider.RandomGenesisAccounts(simState) -// }) -// -// return Outputs{ -// ViewKeeper: viewOnlyKeeper{keeper}, -// Keeper: keeper, -// Handler: compat.AppModuleHandler(key.ID(), appMod), -// }, nil -//} +func (m Module) ProvideAppHandler(key app.ModuleKey, inputs Inputs) (Outputs, error) { + var accCtr types.AccountConstructor + if m.AccountConstructor != nil { + err := inputs.Codec.UnpackAny(m.AccountConstructor, &accCtr) + if err != nil { + return Outputs{}, err + } + } else { + accCtr = DefaultAccountConstructor{} + } + + perms := map[string][]string{} + for _, perm := range m.Permissions { + perms[perm.Address] = perm.Permissions + } + + var randomGenesisAccountsProvider types.RandomGenesisAccountsProvider + if m.RandomGenesisAccountsProvider != nil { + err := inputs.Codec.UnpackAny(m.RandomGenesisAccountsProvider, &randomGenesisAccountsProvider) + if err != nil { + return Outputs{}, err + } + } else { + randomGenesisAccountsProvider = DefaultRandomGenesisAccountsProvider{} + } + + keeper := authkeeper.NewAccountKeeper( + inputs.Codec, + inputs.KeyProvider(key), + inputs.SubspaceProvider(key), + func() types.AccountI { + return accCtr.NewAccount() + }, + perms, + ) + appMod := auth.NewAppModule(inputs.Codec, keeper, func(simState *module.SimulationState) types.GenesisAccounts { + return randomGenesisAccountsProvider.RandomGenesisAccounts(simState) + }) + + return Outputs{ + ViewKeeper: viewOnlyKeeper{keeper}, + Keeper: keeper, + Handler: compat.AppModuleHandler(key.ID(), appMod), + }, nil +} func (m DefaultAccountConstructor) NewAccount() types.AccountI { return &types.BaseAccount{} From 1c174ac8e0ec944876aa66788a7cd92936243341 Mon Sep 17 00:00:00 2001 From: Aaron Craelius Date: Fri, 18 Jun 2021 23:01:59 -0400 Subject: [PATCH 19/24] WIP --- app/dig_test.go | 34 ----------- app/internal/app.go | 5 +- app/internal/app_provider.go | 50 +++++------------ app/internal/provider.go | 47 ++++++++++++++++ app/key.go | 5 -- app/module_set.go | 86 ++++++++++++---------------- app/query/provider.go | 11 ++-- app/store.go | 7 +++ app/store/provider.go | 57 +++++++++++++++++++ container/container.go | 39 ++++--------- container/docs.go | 3 - container/go.mod | 3 - container/option.go | 46 +++++++++++++++ container/scope.go | 15 ----- container/struct_args.go | 7 --- go.mod | 3 - x/auth/tx/module/module.go | 106 ++++++++++++++++++++--------------- x/auth/types/keeper.go | 5 +- 18 files changed, 296 insertions(+), 233 deletions(-) delete mode 100644 app/dig_test.go create mode 100644 app/internal/provider.go create mode 100644 app/store.go create mode 100644 app/store/provider.go delete mode 100644 container/docs.go delete mode 100644 container/go.mod create mode 100644 container/option.go delete mode 100644 container/scope.go delete mode 100644 container/struct_args.go diff --git a/app/dig_test.go b/app/dig_test.go deleted file mode 100644 index 045357bf9dbe..000000000000 --- a/app/dig_test.go +++ /dev/null @@ -1,34 +0,0 @@ -package app - -import ( - "testing" - - "github.com/stretchr/testify/require" - "go.uber.org/dig" -) - -type Inputs struct { - dig.In - - Ints []int `group:"abc"` - Floats []float64 `group:"abc"` -} - -func TestDig(t *testing.T) { - ctr := dig.New() - require.NoError(t, ctr.Provide(func() int { - return 4 - }, dig.Group("abc"))) - require.NoError(t, ctr.Provide(func() int { - return 5 - }, dig.Group("abc"))) - require.NoError(t, ctr.Provide(func() float64 { - return 7 - }, dig.Group("abc"))) - require.NoError(t, ctr.Provide(func() float64 { - return 10 - }, dig.Group("abc"))) - require.NoError(t, ctr.Invoke(func(in Inputs) { - t.Logf("%+v\n", in) - })) -} diff --git a/app/internal/app.go b/app/internal/app.go index e5e1547359d9..5af95ce71d00 100644 --- a/app/internal/app.go +++ b/app/internal/app.go @@ -17,8 +17,6 @@ import ( "github.com/cosmos/cosmos-sdk/server/config" "github.com/cosmos/cosmos-sdk/snapshots" "github.com/cosmos/cosmos-sdk/store" - "github.com/cosmos/cosmos-sdk/types/module" - sdk "github.com/cosmos/cosmos-sdk/types" "github.com/cosmos/cosmos-sdk/baseapp" @@ -26,6 +24,8 @@ import ( servertypes "github.com/cosmos/cosmos-sdk/server/types" ) +type AppProvider struct{} + // NewApp is an AppCreator func (ap *AppProvider) AppCreator( logger log.Logger, @@ -113,7 +113,6 @@ func (ap *AppProvider) AppExportor( type theApp struct { *baseapp.BaseApp appProvider *AppProvider - mm module.Manager } var _ servertypes.Application = &theApp{} diff --git a/app/internal/app_provider.go b/app/internal/app_provider.go index 20952c92776d..3d75569eb8db 100644 --- a/app/internal/app_provider.go +++ b/app/internal/app_provider.go @@ -3,50 +3,30 @@ package internal import ( "fmt" + codecTypes "github.com/cosmos/cosmos-sdk/codec/types" + "github.com/cosmos/cosmos-sdk/container" + "github.com/cosmos/cosmos-sdk/app" "github.com/cosmos/cosmos-sdk/app/query" - "github.com/cosmos/cosmos-sdk/x/genutil/provider" + genutilprovider "github.com/cosmos/cosmos-sdk/x/genutil/provider" ) -type AppProvider struct { - *app.ModuleContainer - config *app.Config - moduleConfigMap map[string]*app.ModuleConfig -} - -func NewAppProvider(config *app.Config) (*AppProvider, error) { - ctr := app.NewModuleContainer() - moduleConfigMap := map[string]*app.ModuleConfig{} +func AppConfigProvider(config *app.Config) container.Option { + moduleConfigMap := map[string]*codecTypes.Any{} if config.Abci.TxHandler == nil { - return nil, fmt.Errorf("missing tx handler") - } - err := ctr.AddProtoModule("tx", config.Abci.TxHandler) - if err != nil { - return nil, err + return container.Error(fmt.Errorf("missing tx handler")) } + moduleConfigMap["tx"] = config.Abci.TxHandler for _, modConfig := range config.Modules { - err = ctr.AddProtoModule(modConfig.Name, modConfig.Config) - if err != nil { - return nil, err - } - moduleConfigMap[modConfig.Name] = modConfig - } - - err = ctr.Provide(provider.Provider) - if err != nil { - return nil, err - } - - err = ctr.Provide(query.Provider) - if err != nil { - return nil, err + moduleConfigMap[modConfig.Name] = modConfig.Config } - return &AppProvider{ - ModuleContainer: ctr, - config: config, - moduleConfigMap: moduleConfigMap, - }, nil + return container.Options( + app.ProvideModules(moduleConfigMap), + // TODO should these be here: + container.Provide(genutilprovider.Provider), + query.Module, + ) } diff --git a/app/internal/provider.go b/app/internal/provider.go new file mode 100644 index 000000000000..0a3e4e989471 --- /dev/null +++ b/app/internal/provider.go @@ -0,0 +1,47 @@ +package internal + +import ( + io "io" + + "github.com/cosmos/cosmos-sdk/baseapp" + + "github.com/cosmos/cosmos-sdk/container" + servertypes "github.com/cosmos/cosmos-sdk/server/types" + sdk "github.com/cosmos/cosmos-sdk/types" + "github.com/tendermint/tendermint/libs/log" + dbm "github.com/tendermint/tm-db" + "go.uber.org/dig" +) + +type AppName string + +type Inputs struct { + dig.In + + Name AppName + sdk.TxDecoder + sdk.AnteHandler + Options []func(*baseapp.BaseApp) `group:"init"` +} + +func provide(inputs Inputs) servertypes.AppCreator { + return func(logger log.Logger, db dbm.DB, traceStore io.Writer, options servertypes.AppOptions) servertypes.Application { + bapp := baseapp.NewBaseApp( + string(inputs.Name), + logger, + db, + inputs.TxDecoder, + inputs.Options..., + ) + + bapp.SetAnteHandler(inputs.AnteHandler) + + bapp.SetCommitMultiStoreTracer(writer) + + return &theApp{ + BaseApp: bapp, + } + } +} + +var Module = container.Provide(provide) diff --git a/app/key.go b/app/key.go index d4ca7eb7b206..38d1719a8f4e 100644 --- a/app/key.go +++ b/app/key.go @@ -1,7 +1,5 @@ package app -import "github.com/cosmos/cosmos-sdk/types" - type ModuleKey interface { moduleKey() ID() ModuleID @@ -12,9 +10,6 @@ type ModuleID interface { Name() string } -type KVStoreKeyProvider func(ModuleKey) *types.KVStoreKey -type TransientStoreKeyProvider func(ModuleKey) *types.TransientStoreKey - type moduleKey struct { *moduleID } diff --git a/app/module_set.go b/app/module_set.go index 51a175014e55..3ab9f10fe251 100644 --- a/app/module_set.go +++ b/app/module_set.go @@ -13,41 +13,13 @@ import ( "github.com/cosmos/cosmos-sdk/container" ) -type ModuleContainer struct { - *dig.Container +type moduleContainer struct { typeRegistry codecTypes.TypeRegistry - codec codec.Codec - modules map[ModuleKey]interface{} + cdc codec.Codec + opts []container.Option } -func NewModuleContainer() *ModuleContainer { - typeRegistry := codecTypes.NewInterfaceRegistry() - cdc := codec.NewProtoCodec(typeRegistry) - amino := codec.NewLegacyAmino() - ctr := dig.New() - err := ctr.Provide(func() ( - codecTypes.TypeRegistry, - codec.Codec, - codec.ProtoCodecMarshaler, - codec.BinaryCodec, - codec.JSONCodec, - *codec.LegacyAmino, - ) { - return typeRegistry, cdc, cdc, cdc, cdc, amino - }) - if err != nil { - panic(err) - } - - return &ModuleContainer{ - Container: ctr, - typeRegistry: typeRegistry, - codec: cdc, - modules: map[ModuleKey]interface{}{}, - } -} - -func (mc ModuleContainer) AddProtoModule(name string, config *codecTypes.Any) error { +func (mc moduleContainer) AddProtoModule(name string, config *codecTypes.Any) error { // unpack Any msgTyp := proto.MessageType(config.TypeUrl) mod := reflect.New(msgTyp.Elem()).Interface().(proto.Message) @@ -60,26 +32,14 @@ func (mc ModuleContainer) AddProtoModule(name string, config *codecTypes.Any) er var moduleKeyType = reflect.TypeOf((*ModuleKey)(nil)).Elem() -func (mc *ModuleContainer) AddModule(name string, mod interface{}) error { +func (mc *moduleContainer) AddModule(name string, mod interface{}) error { key := &moduleKey{&moduleID{name}} - mc.modules[key] = mod // register types if typeProvider, ok := mod.(TypeProvider); ok { typeProvider.RegisterTypes(mc.typeRegistry) } - // register DI providers - if provisioner, ok := mod.(Provisioner); ok { - registrar := registrar{ - ctr: mc.Container, - } - err := provisioner.Provision(nil, registrar) - if err != nil { - return err - } - } - // register DI Provide* methods modTy := reflect.TypeOf(mod) numMethods := modTy.NumMethod() @@ -133,10 +93,7 @@ func (mc *ModuleContainer) AddModule(name string, mod interface{}) error { return method.Func.Call(args) }) - err := mc.Provide(fn.Interface()) - if err != nil { - return err - } + mc.opts = append(mc.opts, container.Provide(fn.Interface())) } } @@ -152,3 +109,34 @@ var _ container.Registrar = registrar{} func (s registrar) Provide(fn interface{}) error { return s.ctr.Provide(fn) } + +func ProvideModules(modules map[string]*codecTypes.Any) container.Option { + typeRegistry := codecTypes.NewInterfaceRegistry() + cdc := codec.NewProtoCodec(typeRegistry) + amino := codec.NewLegacyAmino() + cdcProvider := container.Provide(func() ( + codecTypes.TypeRegistry, + codec.Codec, + codec.ProtoCodecMarshaler, + codec.BinaryCodec, + codec.JSONCodec, + *codec.LegacyAmino, + ) { + return typeRegistry, cdc, cdc, cdc, cdc, amino + }) + + mc := moduleContainer{ + typeRegistry: typeRegistry, + cdc: cdc, + opts: []container.Option{cdcProvider}, + } + + for name, mod := range modules { + err := mc.AddProtoModule(name, mod) + if err != nil { + return container.Error(err) + } + } + + return container.Options(mc.opts...) +} diff --git a/app/query/provider.go b/app/query/provider.go index 63a4ec684a87..a739bcae93df 100644 --- a/app/query/provider.go +++ b/app/query/provider.go @@ -1,6 +1,7 @@ package query import ( + "github.com/cosmos/cosmos-sdk/container" "github.com/spf13/cobra" "go.uber.org/dig" @@ -9,19 +10,19 @@ import ( "github.com/cosmos/cosmos-sdk/client/rpc" ) -type Inputs struct { +type inputs struct { dig.In Commands []*cobra.Command `group:"query"` } -type Outputs struct { +type outputs struct { dig.Out Command *cobra.Command `group:"root"` } -func Provider(inputs Inputs) Outputs { +func provider(inputs inputs) outputs { cmd := &cobra.Command{ Use: "query", Aliases: []string{"q"}, @@ -44,7 +45,9 @@ func Provider(inputs Inputs) Outputs { cmd.PersistentFlags().String(flags.FlagChainID, "", "The network chain ID") - return Outputs{ + return outputs{ Command: cmd, } } + +var Module = container.Provide(provider) diff --git a/app/store.go b/app/store.go new file mode 100644 index 000000000000..ab9a19bfb89b --- /dev/null +++ b/app/store.go @@ -0,0 +1,7 @@ +package app + +import "github.com/cosmos/cosmos-sdk/types" + +type KVStoreKeyProvider func(ModuleKey) *types.KVStoreKey +type TransientStoreKeyProvider func(ModuleKey) *types.TransientStoreKey +type MemoryStoreKeyProvider func(ModuleKey) *types.MemoryStoreKey diff --git a/app/store/provider.go b/app/store/provider.go new file mode 100644 index 000000000000..06d75bf4c5fa --- /dev/null +++ b/app/store/provider.go @@ -0,0 +1,57 @@ +package store + +import ( + "github.com/cosmos/cosmos-sdk/app" + "github.com/cosmos/cosmos-sdk/baseapp" + "github.com/cosmos/cosmos-sdk/container" + "github.com/cosmos/cosmos-sdk/store/types" + "go.uber.org/dig" +) + +type Inputs struct { + dig.In +} + +type Outputs struct { + dig.Out + + app.KVStoreKeyProvider + app.TransientStoreKeyProvider + app.MemoryStoreKeyProvider + + BaseAppOption func(*baseapp.BaseApp) `group:"init"` +} + +func provider() Outputs { + kvStoreKeys := map[string]*types.KVStoreKey{} + transientKeys := map[string]*types.TransientStoreKey{} + memKeys := map[string]*types.MemoryStoreKey{} + + return Outputs{ + KVStoreKeyProvider: func(key app.ModuleKey) *types.KVStoreKey { + name := key.ID().Name() + storeKey := types.NewKVStoreKey(name) + kvStoreKeys[name] = storeKey + return storeKey + }, + TransientStoreKeyProvider: func(key app.ModuleKey) *types.TransientStoreKey { + name := key.ID().Name() + storeKey := types.NewTransientStoreKey(name) + transientKeys[name] = storeKey + return storeKey + }, + MemoryStoreKeyProvider: func(key app.ModuleKey) *types.MemoryStoreKey { + name := key.ID().Name() + storeKey := types.NewMemoryStoreKey(name) + memKeys[name] = storeKey + return storeKey + }, + BaseAppOption: func(baseApp *baseapp.BaseApp) { + baseApp.MountKVStores(kvStoreKeys) + baseApp.MountTransientStores(transientKeys) + baseApp.MountMemoryStores(memKeys) + }, + } +} + +var Module = container.Provide(provider) diff --git a/container/container.go b/container/container.go index 109b1807b7c9..522f341d0932 100644 --- a/container/container.go +++ b/container/container.go @@ -1,37 +1,22 @@ package container -type Container struct { -} - -var _ Registrar = &Container{} - -func NewContainer() *Container { - panic("TODO") -} +import "go.uber.org/dig" -func (c *Container) Provide(fn interface{}) error { - panic("implement me") +type Container struct { + container *dig.Container + err error } -func (c *Container) ProvideWithScope(fn interface{}, scope Scope) error { - panic("implement me") -} +func New(opts ...Option) *Container { + ctr := &Container{ + container: dig.New(), + } -func (c *Container) Invoke(fn interface{}) error { - panic("TODO") -} + Options(opts...).applyOption(ctr) -// TryInitializeAll attempts to initialize all registered providers in the container. -// It returns an error if a provider returns an error. If a given provider has -// dependencies which cannot be resolved, an error is not returned and instead -// that provider is not called. -func (c *Container) TryInitializeAll() error { - panic("TODO") + return ctr } -// InitializeAll attempts to initialize all registered providers in the container. -// It returns an error if a provider returns an error or a dependency in the graph -// cannot be satisfied. -func (c *Container) InitializeAll() error { - panic("TODO") +func (c Container) Invoke(f interface{}) error { + return c.container.Invoke(f) } diff --git a/container/docs.go b/container/docs.go deleted file mode 100644 index 40b7ad40d264..000000000000 --- a/container/docs.go +++ /dev/null @@ -1,3 +0,0 @@ -/*Package container - */ -package container diff --git a/container/go.mod b/container/go.mod deleted file mode 100644 index 5ad6ca3fb3ab..000000000000 --- a/container/go.mod +++ /dev/null @@ -1,3 +0,0 @@ -go 1.15 - -module github.com/cosmos/cosmos-sdk/container diff --git a/container/option.go b/container/option.go new file mode 100644 index 000000000000..5ee75a3ec599 --- /dev/null +++ b/container/option.go @@ -0,0 +1,46 @@ +package container + +type Option interface { + applyOption(*Container) +} + +type option struct { + f func(*Container) +} + +func (o option) applyOption(ctr *Container) { + o.f(ctr) +} + +func Provide(constructors ...interface{}) Option { + return option{ + func(container *Container) { + for _, c := range constructors { + err := container.container.Provide(c) + if err != nil { + container.err = err + return + } + } + }, + } +} + +func Error(err error) Option { + return option{func(container *Container) { + container.err = err + }} +} + +func Options(opts ...Option) Option { + return option{ + func(container *Container) { + for _, opt := range opts { + opt.applyOption(container) + if container.err != nil { + return + } + } + }, + } +} diff --git a/container/scope.go b/container/scope.go deleted file mode 100644 index 0bf37b277918..000000000000 --- a/container/scope.go +++ /dev/null @@ -1,15 +0,0 @@ -package container - -// Scope is a special type of provider argument which provider's can use to provide -// "scoped" dependency. A scoped dependency is one which is dependent on the scope. -// A scoped provider should have a first argument of type Scope and return a (possibly) -// different dependency for each scope. This can be used to configure things like -// scoped store access where the requesting scope gets a private store key that cannot -// be accessed by providers in other scopes. Scopes can also be used to configure -// security. -// -// Ex: -// func KVStoreKeyProvider(scope Scope) *sdk.KVStoreKey { -// return sdk.NewKVStoreKey(string(scope)) -// } -type Scope string diff --git a/container/struct_args.go b/container/struct_args.go deleted file mode 100644 index fb859df5ea54..000000000000 --- a/container/struct_args.go +++ /dev/null @@ -1,7 +0,0 @@ -package container - -type StructArgs struct{} - -func (StructArgs) isStructArgs() {} - -type isStructArgs interface{ isStructArgs() } diff --git a/go.mod b/go.mod index ce292ad163be..cde4fb1951e0 100644 --- a/go.mod +++ b/go.mod @@ -10,7 +10,6 @@ require ( github.com/btcsuite/btcutil v1.0.2 github.com/coinbase/rosetta-sdk-go v0.6.10 github.com/confio/ics23/go v0.6.6 - github.com/cosmos/cosmos-sdk/container v0.0.0-20210601215105-8e0f2e2ea130 github.com/cosmos/go-bip39 v1.0.0 github.com/cosmos/iavl v0.16.0 github.com/cosmos/ledger-cosmos-go v0.11.1 @@ -65,5 +64,3 @@ require ( replace google.golang.org/grpc => google.golang.org/grpc v1.33.2 replace github.com/gogo/protobuf => github.com/regen-network/protobuf v1.3.3-alpha.regen.1 - -replace github.com/cosmos/cosmos-sdk/container => ./container diff --git a/x/auth/tx/module/module.go b/x/auth/tx/module/module.go index 66b786df46b3..b807931a2432 100644 --- a/x/auth/tx/module/module.go +++ b/x/auth/tx/module/module.go @@ -1,78 +1,96 @@ package module import ( + "github.com/cosmos/cosmos-sdk/types" + "github.com/cosmos/cosmos-sdk/x/auth/ante" + auth "github.com/cosmos/cosmos-sdk/x/auth/types" + bankkeeper "github.com/cosmos/cosmos-sdk/x/bank/keeper" + feegrantkeeper "github.com/cosmos/cosmos-sdk/x/feegrant/keeper" "github.com/spf13/cobra" "go.uber.org/dig" - "github.com/cosmos/cosmos-sdk/app" "github.com/cosmos/cosmos-sdk/client" "github.com/cosmos/cosmos-sdk/client/flags" "github.com/cosmos/cosmos-sdk/codec" - "github.com/cosmos/cosmos-sdk/container" authcmd "github.com/cosmos/cosmos-sdk/x/auth/client/cli" "github.com/cosmos/cosmos-sdk/x/auth/tx" ) -var ( - _ app.Provisioner = Module{} -) - type Inputs struct { dig.In - Commands []*cobra.Command `group:"tx"` - Marshaler codec.ProtoCodecMarshaler + Commands []*cobra.Command `group:"tx"` + Marshaler codec.ProtoCodecMarshaler + AuthKeeper auth.Keeper + BankKeeper bankkeeper.Keeper + FeegrantKeeper feegrantkeeper.Keeper `optional:"true"` } type Outputs struct { dig.Out + TxDecoder types.TxDecoder TxConfig client.TxConfig Command *cobra.Command `group:"root"` QueryCommands []*cobra.Command `group:"query,flatten"` + AnteHandler types.AnteHandler } -func (m Module) Provision(_ app.ModuleKey, registrar container.Registrar) error { - return registrar.Provide(func(inputs Inputs) Outputs { - signModes := m.EnabledSignModes - if signModes == nil { - signModes = tx.DefaultSignModes - } +func (m Module) Provide(inputs Inputs) (Outputs, error) { + signModes := m.EnabledSignModes + if signModes == nil { + signModes = tx.DefaultSignModes + } - cmd := &cobra.Command{ - Use: "tx", - Short: "Transactions subcommands", - DisableFlagParsing: true, - SuggestionsMinimumDistance: 2, - RunE: client.ValidateCmd, - } + cmd := &cobra.Command{ + Use: "tx", + Short: "Transactions subcommands", + DisableFlagParsing: true, + SuggestionsMinimumDistance: 2, + RunE: client.ValidateCmd, + } - cmd.AddCommand( - authcmd.GetSignCommand(), - authcmd.GetSignBatchCommand(), - authcmd.GetMultiSignCommand(), - authcmd.GetMultiSignBatchCmd(), - authcmd.GetValidateSignaturesCommand(), - authcmd.GetBroadcastCommand(), - authcmd.GetEncodeCommand(), - authcmd.GetDecodeCommand(), - ) + cmd.AddCommand( + authcmd.GetSignCommand(), + authcmd.GetSignBatchCommand(), + authcmd.GetMultiSignCommand(), + authcmd.GetMultiSignBatchCmd(), + authcmd.GetValidateSignaturesCommand(), + authcmd.GetBroadcastCommand(), + authcmd.GetEncodeCommand(), + authcmd.GetDecodeCommand(), + ) - for _, c := range inputs.Commands { - if c != nil { - cmd.AddCommand(c) - } + for _, c := range inputs.Commands { + if c != nil { + cmd.AddCommand(c) } + } - cmd.PersistentFlags().String(flags.FlagChainID, "", "The network chain ID") + cmd.PersistentFlags().String(flags.FlagChainID, "", "The network chain ID") - return Outputs{ - TxConfig: tx.NewTxConfig(inputs.Marshaler, signModes), - Command: cmd, - QueryCommands: []*cobra.Command{ - authcmd.QueryTxsByEventsCmd(), - authcmd.QueryTxCmd(), - }, - } + txConfig := tx.NewTxConfig(inputs.Marshaler, signModes) + + anteHandler, err := ante.NewAnteHandler(ante.HandlerOptions{ + AccountKeeper: inputs.AuthKeeper, + BankKeeper: inputs.BankKeeper, + FeegrantKeeper: inputs.FeegrantKeeper, + SignModeHandler: txConfig.SignModeHandler(), + SigGasConsumer: ante.DefaultSigVerificationGasConsumer, }) + + if err != nil { + return Outputs{}, err + } + + return Outputs{ + TxDecoder: txConfig.TxDecoder(), + TxConfig: txConfig, + Command: cmd, + QueryCommands: []*cobra.Command{ + authcmd.QueryTxsByEventsCmd(), + authcmd.QueryTxCmd(), + }, + AnteHandler: anteHandler, + }, nil } diff --git a/x/auth/types/keeper.go b/x/auth/types/keeper.go index b333eab5061f..d51e3cbfa7a8 100644 --- a/x/auth/types/keeper.go +++ b/x/auth/types/keeper.go @@ -1,6 +1,8 @@ package types -import sdk "github.com/cosmos/cosmos-sdk/types" +import ( + sdk "github.com/cosmos/cosmos-sdk/types" +) type ViewKeeper interface { GetAccount(ctx sdk.Context, addr sdk.AccAddress) AccountI @@ -9,6 +11,7 @@ type ViewKeeper interface { GetModuleAddressAndPermissions(moduleName string) (addr sdk.AccAddress, permissions []string) GetModuleAccountAndPermissions(ctx sdk.Context, moduleName string) (ModuleAccountI, []string) GetModuleAccount(ctx sdk.Context, moduleName string) ModuleAccountI + GetParams(ctx sdk.Context) (params Params) } type Keeper interface { From 3edba7749e74a01998abcc49ff70501e4fea5e5c Mon Sep 17 00:00:00 2001 From: Aaron Craelius Date: Fri, 18 Jun 2021 23:26:32 -0400 Subject: [PATCH 20/24] WIP --- app/internal/app_provider.go | 100 +++++++++++++++++++++++++++++++++++ app/internal/provider.go | 42 +++++++++++++-- x/auth/module/module.go | 2 +- x/auth/module/view_keeper.go | 4 ++ x/gov/module/module.go | 5 +- x/params/module/module.go | 5 +- 6 files changed, 148 insertions(+), 10 deletions(-) diff --git a/app/internal/app_provider.go b/app/internal/app_provider.go index 3d75569eb8db..1f96db530cb3 100644 --- a/app/internal/app_provider.go +++ b/app/internal/app_provider.go @@ -1,8 +1,15 @@ package internal import ( + "context" + "encoding/json" "fmt" + abci "github.com/tendermint/tendermint/abci/types" + + "github.com/cosmos/cosmos-sdk/codec" + sdk "github.com/cosmos/cosmos-sdk/types" + codecTypes "github.com/cosmos/cosmos-sdk/codec/types" "github.com/cosmos/cosmos-sdk/container" @@ -23,10 +30,103 @@ func AppConfigProvider(config *app.Config) container.Option { moduleConfigMap[modConfig.Name] = modConfig.Config } + provideAbciMethods := container.Provide(func(in inputs) (outputs, error) { + handlerMap := map[string]app.Handler{} + for _, h := range in.Handlers { + handlerMap[h.ID.Name()] = h + } + + // InitGenesis + var initGenesis []func(context.Context, codec.JSONCodec, json.RawMessage) []abci.ValidatorUpdate + got := map[string]bool{} + for _, name := range config.Abci.InitGenesis { + h, ok := handlerMap[name] + if !ok || h.InitGenesis == nil { + return outputs{}, fmt.Errorf("missing InitGenesis for module %s", name) + } + got[name] = true + initGenesis = append(initGenesis, h.InitGenesis) + } + + for name, h := range handlerMap { + if !got[name] && h.InitGenesis != nil { + return outputs{}, fmt.Errorf("module %s is missing from init_genesis order", name) + } + } + + // BeginBlock + var beginBlock []func(context.Context, abci.RequestBeginBlock) + got = map[string]bool{} + for _, name := range config.Abci.BeginBlock { + h, ok := handlerMap[name] + if !ok || h.BeginBlocker == nil { + return outputs{}, fmt.Errorf("missing BeginBlocker for module %s", name) + } + got[name] = true + beginBlock = append(beginBlock, h.BeginBlocker) + } + + for name, h := range handlerMap { + if !got[name] && h.BeginBlocker != nil { + return outputs{}, fmt.Errorf("module %s is missing from begin_block order", name) + } + } + + // EndBlock + var endBlock []func(context.Context, abci.RequestEndBlock) []abci.ValidatorUpdate + got = map[string]bool{} + for _, name := range config.Abci.EndBlock { + h, ok := handlerMap[name] + if !ok || h.EndBlocker == nil { + return outputs{}, fmt.Errorf("missing EndBlocker for module %s", name) + } + got[name] = true + endBlock = append(endBlock, h.EndBlocker) + } + + for name, h := range handlerMap { + if !got[name] && h.EndBlocker != nil { + return outputs{}, fmt.Errorf("module %s is missing from end_block order", name) + } + } + + return outputs{ + InitGenesis: func(goCtx context.Context, jsonCodec codec.JSONCodec, message json.RawMessage) abci.ResponseInitChain { + panic("TODO") + }, + BeginBlocker: func(goCtx context.Context, req abci.RequestBeginBlock) abci.ResponseBeginBlock { + ctx := sdk.UnwrapSDKContext(goCtx) + ctx = ctx.WithEventManager(sdk.NewEventManager()) + + for _, f := range beginBlock { + f(sdk.WrapSDKContext(ctx), req) + } + + return abci.ResponseBeginBlock{ + Events: ctx.EventManager().ABCIEvents(), + } + }, + EndBlocker: func(ctx context.Context, block abci.RequestEndBlock) abci.ResponseEndBlock { + panic("TODO") + }, + }, nil + }) + return container.Options( + provideAbciMethods, app.ProvideModules(moduleConfigMap), // TODO should these be here: container.Provide(genutilprovider.Provider), query.Module, ) } + +type inputs struct { + Handlers []app.Handler `group:"app"` +} + +type outputs struct { + InitGenesis func(context.Context, codec.JSONCodec, json.RawMessage) abci.ResponseInitChain + BeginBlocker func(context.Context, abci.RequestBeginBlock) abci.ResponseBeginBlock + EndBlocker func(context.Context, abci.RequestEndBlock) abci.ResponseEndBlock +} diff --git a/app/internal/provider.go b/app/internal/provider.go index 0a3e4e989471..688ca376b7fe 100644 --- a/app/internal/provider.go +++ b/app/internal/provider.go @@ -1,16 +1,25 @@ package internal import ( + "context" + "encoding/json" io "io" + abci "github.com/tendermint/tendermint/abci/types" + + "github.com/cosmos/cosmos-sdk/codec" + + "github.com/cosmos/cosmos-sdk/app" + "github.com/cosmos/cosmos-sdk/baseapp" - "github.com/cosmos/cosmos-sdk/container" - servertypes "github.com/cosmos/cosmos-sdk/server/types" - sdk "github.com/cosmos/cosmos-sdk/types" "github.com/tendermint/tendermint/libs/log" dbm "github.com/tendermint/tm-db" "go.uber.org/dig" + + "github.com/cosmos/cosmos-sdk/container" + servertypes "github.com/cosmos/cosmos-sdk/server/types" + sdk "github.com/cosmos/cosmos-sdk/types" ) type AppName string @@ -21,7 +30,11 @@ type Inputs struct { Name AppName sdk.TxDecoder sdk.AnteHandler - Options []func(*baseapp.BaseApp) `group:"init"` + Options []func(*baseapp.BaseApp) `group:"init"` + Handlers []app.Handler `group:"app"` + InitGenesis func(context.Context, codec.JSONCodec, json.RawMessage) abci.ResponseInitChain + BeginBlocker func(context.Context, abci.RequestBeginBlock) abci.ResponseBeginBlock + EndBlocker func(context.Context, abci.RequestEndBlock) abci.ResponseEndBlock } func provide(inputs Inputs) servertypes.AppCreator { @@ -35,8 +48,27 @@ func provide(inputs Inputs) servertypes.AppCreator { ) bapp.SetAnteHandler(inputs.AnteHandler) + bapp.SetInitChainer(func(ctx sdk.Context, req abci.RequestInitChain) abci.ResponseInitChain { + panic("TODO") + }) + bapp.SetBeginBlocker(func(ctx sdk.Context, req abci.RequestBeginBlock) abci.ResponseBeginBlock { + return inputs.BeginBlocker(sdk.WrapSDKContext(ctx), req) + }) + bapp.SetEndBlocker(func(ctx sdk.Context, req abci.RequestEndBlock) abci.ResponseEndBlock { + return inputs.EndBlocker(sdk.WrapSDKContext(ctx), req) + }) - bapp.SetCommitMultiStoreTracer(writer) + bapp.SetCommitMultiStoreTracer(traceStore) + + for _, handler := range inputs.Handlers { + for _, svc := range handler.MsgServices { + bapp.MsgServiceRouter().RegisterService(svc.Desc, svc.Impl) + } + + for _, svc := range handler.QueryServices { + bapp.GRPCQueryRouter().RegisterService(svc.Desc, svc.Impl) + } + } return &theApp{ BaseApp: bapp, diff --git a/x/auth/module/module.go b/x/auth/module/module.go index 09d4193f70b0..66942f80a5d6 100644 --- a/x/auth/module/module.go +++ b/x/auth/module/module.go @@ -34,7 +34,7 @@ type Inputs struct { type Outputs struct { dig.Out - Handler app.Handler `group:"app.handler"` + Handler app.Handler `group:"tx"` ViewKeeper types.ViewKeeper Keeper types.Keeper `security-role:"admin"` } diff --git a/x/auth/module/view_keeper.go b/x/auth/module/view_keeper.go index cf9a961c060c..0b260ffaada9 100644 --- a/x/auth/module/view_keeper.go +++ b/x/auth/module/view_keeper.go @@ -35,4 +35,8 @@ func (v viewOnlyKeeper) GetModuleAccount(ctx sdk.Context, moduleName string) typ return v.k.GetModuleAccount(ctx, moduleName) } +func (v viewOnlyKeeper) GetParams(ctx sdk.Context) (params types.Params) { + return v.k.GetParams(ctx) +} + var _ types.ViewKeeper = viewOnlyKeeper{} diff --git a/x/gov/module/module.go b/x/gov/module/module.go index 0d4134f28fa9..b3b5b3945e2d 100644 --- a/x/gov/module/module.go +++ b/x/gov/module/module.go @@ -1,6 +1,8 @@ package module import ( + "go.uber.org/dig" + "github.com/cosmos/cosmos-sdk/app" "github.com/cosmos/cosmos-sdk/app/compat" "github.com/cosmos/cosmos-sdk/codec" @@ -10,7 +12,6 @@ import ( govkeeper "github.com/cosmos/cosmos-sdk/x/gov/keeper" govtypes "github.com/cosmos/cosmos-sdk/x/gov/types" types2 "github.com/cosmos/cosmos-sdk/x/params/types" - "go.uber.org/dig" ) var ( @@ -39,7 +40,7 @@ type Inputs struct { type Outputs struct { dig.Out - Handler app.Handler `group:"app.handler"` + Handler app.Handler `group:"tx"` } func (m *Module) Provision(key app.ModuleKey, registrar container.Registrar) error { diff --git a/x/params/module/module.go b/x/params/module/module.go index 0babaa80ee51..5feededea329 100644 --- a/x/params/module/module.go +++ b/x/params/module/module.go @@ -1,6 +1,8 @@ package module import ( + "go.uber.org/dig" + "github.com/cosmos/cosmos-sdk/app" "github.com/cosmos/cosmos-sdk/app/compat" "github.com/cosmos/cosmos-sdk/codec" @@ -10,7 +12,6 @@ import ( paramskeeper "github.com/cosmos/cosmos-sdk/x/params/keeper" "github.com/cosmos/cosmos-sdk/x/params/types" paramproposal "github.com/cosmos/cosmos-sdk/x/params/types/proposal" - "go.uber.org/dig" ) var ( @@ -29,7 +30,7 @@ type Inputs struct { type Outputs struct { dig.Out - Handler app.Handler `group:"app.handler"` + Handler app.Handler `group:"tx"` GovRoute types2.Route `group:"cosmos.gov.v1.Route"` Keeper paramskeeper.Keeper `security-role:"admin"` SubspaceProvider types.SubspaceProvider From 28d53c272e64176b8f433cefa1f2eeea01e47b4e Mon Sep 17 00:00:00 2001 From: Aaron Craelius Date: Mon, 21 Jun 2021 16:28:24 -0400 Subject: [PATCH 21/24] WIP --- app/provisioner.go | 2 +- container/container.go | 14 +++++++------- container/option.go | 12 ++++++------ x/auth/module/module.pb.go | 5 +++-- x/bank/module/module.go | 19 ++++++------------- x/gov/module/module.go | 11 ++++++----- x/params/module/module.go | 7 ++++--- 7 files changed, 33 insertions(+), 37 deletions(-) diff --git a/app/provisioner.go b/app/provisioner.go index b89c5def43b2..6604438c2831 100644 --- a/app/provisioner.go +++ b/app/provisioner.go @@ -3,7 +3,7 @@ package app import "github.com/cosmos/cosmos-sdk/container" type Provisioner interface { - Provision(key ModuleKey, registrar container.Registrar) error + Provision(key ModuleKey) container.Option } type Provider interface { diff --git a/container/container.go b/container/container.go index 522f341d0932..d6cb703c11e0 100644 --- a/container/container.go +++ b/container/container.go @@ -2,21 +2,21 @@ package container import "go.uber.org/dig" -type Container struct { +type container struct { container *dig.Container err error } -func New(opts ...Option) *Container { - ctr := &Container{ +func Compose(invoker interface{}, opts ...Option) error { + ctr := &container{ container: dig.New(), } Options(opts...).applyOption(ctr) - return ctr -} + if ctr.err != nil { + return ctr.err + } -func (c Container) Invoke(f interface{}) error { - return c.container.Invoke(f) + return ctr.container.Invoke(invoker) } diff --git a/container/option.go b/container/option.go index 5ee75a3ec599..80975a001235 100644 --- a/container/option.go +++ b/container/option.go @@ -1,20 +1,20 @@ package container type Option interface { - applyOption(*Container) + applyOption(*container) } type option struct { - f func(*Container) + f func(*container) } -func (o option) applyOption(ctr *Container) { +func (o option) applyOption(ctr *container) { o.f(ctr) } func Provide(constructors ...interface{}) Option { return option{ - func(container *Container) { + func(container *container) { for _, c := range constructors { err := container.container.Provide(c) if err != nil { @@ -27,14 +27,14 @@ func Provide(constructors ...interface{}) Option { } func Error(err error) Option { - return option{func(container *Container) { + return option{func(container *container) { container.err = err }} } func Options(opts ...Option) Option { return option{ - func(container *Container) { + func(container *container) { for _, opt := range opts { opt.applyOption(container) if container.err != nil { diff --git a/x/auth/module/module.pb.go b/x/auth/module/module.pb.go index fa167689aa1c..459b74172b49 100644 --- a/x/auth/module/module.pb.go +++ b/x/auth/module/module.pb.go @@ -5,11 +5,12 @@ package module import ( fmt "fmt" - types "github.com/cosmos/cosmos-sdk/codec/types" - proto "github.com/gogo/protobuf/proto" io "io" math "math" math_bits "math/bits" + + types "github.com/cosmos/cosmos-sdk/codec/types" + proto "github.com/gogo/protobuf/proto" ) // Reference imports to suppress errors if they are not otherwise used. diff --git a/x/bank/module/module.go b/x/bank/module/module.go index ea5ead7b7e1c..ebf61ac882e7 100644 --- a/x/bank/module/module.go +++ b/x/bank/module/module.go @@ -5,21 +5,14 @@ import ( "github.com/cosmos/cosmos-sdk/container" "github.com/cosmos/cosmos-sdk/x/bank/types" genutiltypes "github.com/cosmos/cosmos-sdk/x/genutil/types" - "go.uber.org/dig" ) var _ app.Provisioner = Module{} -type Outputs struct { - dig.Out - - GenesisBalancesIterator genutiltypes.GenesisBalancesIterator -} - -func (m Module) Provision(key app.ModuleKey, registrar container.Registrar) error { - return registrar.Provide(func() Outputs { - return Outputs{ - GenesisBalancesIterator: types.GenesisBalancesIterator{}, - } - }) +func (m Module) Provision(app.ModuleKey) container.Option { + return container.Provide( + func() genutiltypes.GenesisBalancesIterator { + return types.GenesisBalancesIterator{} + }, + ) } diff --git a/x/gov/module/module.go b/x/gov/module/module.go index b3b5b3945e2d..a359ac90a920 100644 --- a/x/gov/module/module.go +++ b/x/gov/module/module.go @@ -3,13 +3,14 @@ package module import ( "go.uber.org/dig" - "github.com/cosmos/cosmos-sdk/app" "github.com/cosmos/cosmos-sdk/app/compat" + "github.com/cosmos/cosmos-sdk/x/gov" + govkeeper "github.com/cosmos/cosmos-sdk/x/gov/keeper" + + "github.com/cosmos/cosmos-sdk/app" "github.com/cosmos/cosmos-sdk/codec" "github.com/cosmos/cosmos-sdk/codec/types" "github.com/cosmos/cosmos-sdk/container" - "github.com/cosmos/cosmos-sdk/x/gov" - govkeeper "github.com/cosmos/cosmos-sdk/x/gov/keeper" govtypes "github.com/cosmos/cosmos-sdk/x/gov/types" types2 "github.com/cosmos/cosmos-sdk/x/params/types" ) @@ -43,8 +44,8 @@ type Outputs struct { Handler app.Handler `group:"tx"` } -func (m *Module) Provision(key app.ModuleKey, registrar container.Registrar) error { - return registrar.Provide(func(inputs Inputs) Outputs { +func (m *Module) Provision(key app.ModuleKey) container.Option { + return container.Provide(func(inputs Inputs) Outputs { router := govtypes.NewRouter() for _, route := range inputs.Routes { router.AddRoute(route.Path, route.Handler) diff --git a/x/params/module/module.go b/x/params/module/module.go index 5feededea329..f7aa9aa2ee0c 100644 --- a/x/params/module/module.go +++ b/x/params/module/module.go @@ -3,6 +3,8 @@ package module import ( "go.uber.org/dig" + paramproposal "github.com/cosmos/cosmos-sdk/x/params/types/proposal" + "github.com/cosmos/cosmos-sdk/app" "github.com/cosmos/cosmos-sdk/app/compat" "github.com/cosmos/cosmos-sdk/codec" @@ -11,7 +13,6 @@ import ( "github.com/cosmos/cosmos-sdk/x/params" paramskeeper "github.com/cosmos/cosmos-sdk/x/params/keeper" "github.com/cosmos/cosmos-sdk/x/params/types" - paramproposal "github.com/cosmos/cosmos-sdk/x/params/types/proposal" ) var ( @@ -36,8 +37,8 @@ type Outputs struct { SubspaceProvider types.SubspaceProvider } -func (m Module) Provision(key app.ModuleKey, registrar container.Registrar) error { - return registrar.Provide(func(inputs Inputs) Outputs { +func (m Module) Provision(key app.ModuleKey) container.Option { + return container.Provide(func(inputs Inputs) Outputs { keeper := paramskeeper.NewKeeper(inputs.Codec, inputs.LegacyAmino, inputs.KeyProvider(key), inputs.TransientKeyProvider(key)) appMod := params.NewAppModule(keeper) From 16246a9b20575a027e01a016f008edafbb33dbf7 Mon Sep 17 00:00:00 2001 From: Aaron Craelius Date: Mon, 21 Jun 2021 16:46:17 -0400 Subject: [PATCH 22/24] WIP --- app/internal/app_provider.go | 2 +- app/module_set.go | 2 +- container/container.go | 8 +++++ x/auth/module/module.go | 18 +++++------ x/gov/module/module.go | 63 +++++++++++++++++++++++------------- 5 files changed, 59 insertions(+), 34 deletions(-) diff --git a/app/internal/app_provider.go b/app/internal/app_provider.go index 1f96db530cb3..cd9b2b1e0977 100644 --- a/app/internal/app_provider.go +++ b/app/internal/app_provider.go @@ -114,7 +114,7 @@ func AppConfigProvider(config *app.Config) container.Option { return container.Options( provideAbciMethods, - app.ProvideModules(moduleConfigMap), + app.ComposeModules(moduleConfigMap), // TODO should these be here: container.Provide(genutilprovider.Provider), query.Module, diff --git a/app/module_set.go b/app/module_set.go index 3ab9f10fe251..5c23c947e164 100644 --- a/app/module_set.go +++ b/app/module_set.go @@ -110,7 +110,7 @@ func (s registrar) Provide(fn interface{}) error { return s.ctr.Provide(fn) } -func ProvideModules(modules map[string]*codecTypes.Any) container.Option { +func ComposeModules(modules map[string]*codecTypes.Any) container.Option { typeRegistry := codecTypes.NewInterfaceRegistry() cdc := codec.NewProtoCodec(typeRegistry) amino := codec.NewLegacyAmino() diff --git a/container/container.go b/container/container.go index d6cb703c11e0..4324e53fa3d5 100644 --- a/container/container.go +++ b/container/container.go @@ -20,3 +20,11 @@ func Compose(invoker interface{}, opts ...Option) error { return ctr.container.Invoke(invoker) } + +type In struct { + dig.In +} + +type Out struct { + dig.Out +} diff --git a/x/auth/module/module.go b/x/auth/module/module.go index 66942f80a5d6..b2ba3a1534ee 100644 --- a/x/auth/module/module.go +++ b/x/auth/module/module.go @@ -23,7 +23,7 @@ var ( _ app.TypeProvider = Module{} ) -type Inputs struct { +type inputs struct { dig.In Codec codec.Codec @@ -31,7 +31,7 @@ type Inputs struct { SubspaceProvider types2.SubspaceProvider } -type Outputs struct { +type outputs struct { dig.Out Handler app.Handler `group:"tx"` @@ -39,7 +39,7 @@ type Outputs struct { Keeper types.Keeper `security-role:"admin"` } -type CLICommands struct { +type cliCommands struct { dig.Out TxCmd *cobra.Command `group:"tx"` @@ -54,9 +54,9 @@ func (Module) ProvideAccountRetriever() client.AccountRetriever { return types.AccountRetriever{} } -func (Module) ProvideCLICommands() CLICommands { +func (Module) ProvideCLICommands() cliCommands { am := auth.AppModuleBasic{} - return CLICommands{ + return cliCommands{ TxCmd: am.GetTxCmd(), QueryCmd: []*cobra.Command{ am.GetQueryCmd(), @@ -65,12 +65,12 @@ func (Module) ProvideCLICommands() CLICommands { } } -func (m Module) ProvideAppHandler(key app.ModuleKey, inputs Inputs) (Outputs, error) { +func (m Module) ProvideAppHandler(key app.ModuleKey, inputs inputs) (outputs, error) { var accCtr types.AccountConstructor if m.AccountConstructor != nil { err := inputs.Codec.UnpackAny(m.AccountConstructor, &accCtr) if err != nil { - return Outputs{}, err + return outputs{}, err } } else { accCtr = DefaultAccountConstructor{} @@ -85,7 +85,7 @@ func (m Module) ProvideAppHandler(key app.ModuleKey, inputs Inputs) (Outputs, er if m.RandomGenesisAccountsProvider != nil { err := inputs.Codec.UnpackAny(m.RandomGenesisAccountsProvider, &randomGenesisAccountsProvider) if err != nil { - return Outputs{}, err + return outputs{}, err } } else { randomGenesisAccountsProvider = DefaultRandomGenesisAccountsProvider{} @@ -104,7 +104,7 @@ func (m Module) ProvideAppHandler(key app.ModuleKey, inputs Inputs) (Outputs, er return randomGenesisAccountsProvider.RandomGenesisAccounts(simState) }) - return Outputs{ + return outputs{ ViewKeeper: viewOnlyKeeper{keeper}, Keeper: keeper, Handler: compat.AppModuleHandler(key.ID(), appMod), diff --git a/x/gov/module/module.go b/x/gov/module/module.go index a359ac90a920..d2afb65d242d 100644 --- a/x/gov/module/module.go +++ b/x/gov/module/module.go @@ -1,6 +1,7 @@ package module import ( + "github.com/spf13/cobra" "go.uber.org/dig" "github.com/cosmos/cosmos-sdk/app/compat" @@ -24,8 +25,8 @@ func (m *Module) RegisterTypes(registry types.InterfaceRegistry) { govtypes.RegisterInterfaces(registry) } -type Inputs struct { - dig.In +type inputs struct { + container.In Codec codec.Codec KeyProvider app.KVStoreKeyProvider @@ -38,32 +39,48 @@ type Inputs struct { StakingKeeper govtypes.StakingKeeper } -type Outputs struct { - dig.Out +type outputs struct { + container.Out Handler app.Handler `group:"tx"` } +type cliCommands struct { + dig.Out + + TxCmd *cobra.Command `group:"tx"` + QueryCmd *cobra.Command `group:"query"` +} + func (m *Module) Provision(key app.ModuleKey) container.Option { - return container.Provide(func(inputs Inputs) Outputs { - router := govtypes.NewRouter() - for _, route := range inputs.Routes { - router.AddRoute(route.Path, route.Handler) - } - k := govkeeper.NewKeeper( - inputs.Codec, - inputs.KeyProvider(key), - inputs.SubspaceProvider(key), - inputs.AuthKeeper, - inputs.BankKeeper, - inputs.StakingKeeper, - router, - ) + return container.Provide( + func(inputs inputs) outputs { + router := govtypes.NewRouter() + for _, route := range inputs.Routes { + router.AddRoute(route.Path, route.Handler) + } + k := govkeeper.NewKeeper( + inputs.Codec, + inputs.KeyProvider(key), + inputs.SubspaceProvider(key), + inputs.AuthKeeper, + inputs.BankKeeper, + inputs.StakingKeeper, + router, + ) - am := gov.NewAppModule(inputs.Codec, k, inputs.AuthKeeper, inputs.BankKeeper) + am := gov.NewAppModule(inputs.Codec, k, inputs.AuthKeeper, inputs.BankKeeper) - return Outputs{ - Handler: compat.AppModuleHandler(key.ID(), am), - } - }) + return outputs{ + Handler: compat.AppModuleHandler(key.ID(), am), + } + }, + func() cliCommands { + amb := gov.AppModuleBasic{} + return cliCommands{ + TxCmd: amb.GetTxCmd(), + QueryCmd: amb.GetQueryCmd(), + } + }, + ) } From a4359d603c6022a2b5378568aea9ff87ad6730be Mon Sep 17 00:00:00 2001 From: Aaron Craelius Date: Mon, 21 Jun 2021 17:54:00 -0400 Subject: [PATCH 23/24] WIP --- app/cli/run.go | 109 +++++++++++++++++---------------- app/internal/app_provider.go | 2 +- app/module_set.go | 109 ++++++++++++++++++--------------- client/utils.go | 2 + container/option.go | 6 ++ x/genutil/provider/provider.go | 61 +++++++++--------- 6 files changed, 159 insertions(+), 130 deletions(-) diff --git a/app/cli/run.go b/app/cli/run.go index 8d7d44226e80..9ea774256339 100644 --- a/app/cli/run.go +++ b/app/cli/run.go @@ -1,8 +1,15 @@ package cli import ( + "fmt" "os" + "github.com/cosmos/cosmos-sdk/app/internal" + + "github.com/cosmos/cosmos-sdk/app/query" + + "github.com/cosmos/cosmos-sdk/container" + tmcli "github.com/tendermint/tendermint/libs/cli" "github.com/cosmos/cosmos-sdk/client/debug" @@ -15,8 +22,6 @@ import ( "github.com/cosmos/cosmos-sdk/codec" codectypes "github.com/cosmos/cosmos-sdk/codec/types" - "github.com/cosmos/cosmos-sdk/app/internal" - "github.com/spf13/cobra" "github.com/cosmos/cosmos-sdk/app" @@ -36,57 +41,64 @@ type Options struct { } func Run(options Options) { - rootCmd := newRootCmd(options) - - if err := svrcmd.Execute(rootCmd, options.DefaultHome); err != nil { - switch e := err.(type) { - case server.ErrorCode: - os.Exit(e.Code) + err := container.Compose( + func(in inputs) { + rootCmd := makeRootCmd(in, options) + if err := svrcmd.Execute(rootCmd, string(in.DefaultHome)); err != nil { + switch e := err.(type) { + case server.ErrorCode: + os.Exit(e.Code) + + default: + os.Exit(1) + } + } + }, - default: - os.Exit(1) - } + // Provide default home + container.Provide(func() client.DefaultHome { return client.DefaultHome(options.DefaultHome) }), + // Provide codec + app.CodecProvider, + query.Module, + internal.AppConfigProvider(options.DefaultAppConfig), + ) + if err != nil { + fmt.Printf("ERROR: %v\n", err) + os.Exit(-1) } } -type Inputs struct { +type inputs struct { dig.In - RootCommands []*cobra.Command `group:"root"` + DefaultHome client.DefaultHome + RootCommands []*cobra.Command `group:"root"` + Codec codec.JSONCodec `optional:"true"` + InterfaceRegistry codectypes.InterfaceRegistry `optional:"true"` + Amino *codec.LegacyAmino `optional:"true"` + TxConfig client.TxConfig `optional:"true"` + AccountRetriever client.AccountRetriever `optional:"true"` } -func newRootCmd(options Options) *cobra.Command { - appProvider, err := internal.NewAppProvider(options.DefaultAppConfig) - if err != nil { - panic(err) - } - - err = appProvider.Provide(func() string { return options.DefaultHome }, dig.Name("cli.default-home")) - if err != nil { - panic(err) - } - +func makeRootCmd(in inputs, options Options) *cobra.Command { initClientCtx := client.Context{}. WithInput(os.Stdin). WithHomeDir(options.DefaultHome). WithViper(options.EnvPrefix) - - err = appProvider.Invoke(func( - codec codec.JSONCodec, - registry codectypes.InterfaceRegistry, - txConfig client.TxConfig, - amino *codec.LegacyAmino, - accountRetriever client.AccountRetriever, - ) { - initClientCtx = initClientCtx. - WithJSONCodec(codec). - WithInterfaceRegistry(registry). - WithTxConfig(txConfig). - WithLegacyAmino(amino). - WithAccountRetriever(accountRetriever) - }) - if err != nil { - panic(err) + if in.Codec != nil { + initClientCtx = initClientCtx.WithJSONCodec(in.Codec) + } + if in.InterfaceRegistry != nil { + initClientCtx = initClientCtx.WithInterfaceRegistry(in.InterfaceRegistry) + } + if in.TxConfig != nil { + initClientCtx = initClientCtx.WithTxConfig(in.TxConfig) + } + if in.AccountRetriever != nil { + initClientCtx = initClientCtx.WithAccountRetriever(in.AccountRetriever) + } + if in.Amino != nil { + initClientCtx = initClientCtx.WithLegacyAmino(in.Amino) } rootCmd := &cobra.Command{ @@ -115,17 +127,7 @@ func newRootCmd(options Options) *cobra.Command { cfg := sdk.GetConfig() cfg.Seal() - err = appProvider.Invoke(func(inputs Inputs) { - rootCmd.AddCommand(inputs.RootCommands...) - }) - if err != nil { - panic(err) - } - - err = dig.Visualize(appProvider.Container, os.Stdout) - if err != nil { - panic(err) - } + rootCmd.AddCommand(in.RootCommands...) rootCmd.AddCommand( //TODO: AddGenesisAccountCmd(options.DefaultHome), @@ -135,7 +137,8 @@ func newRootCmd(options Options) *cobra.Command { config.Cmd(), ) - server.AddCommands(rootCmd, options.DefaultHome, appProvider.AppCreator, appProvider.AppExportor, addModuleInitFlags) + // TODO: + //server.AddCommands(rootCmd, options.DefaultHome, appProvider.AppCreator, appProvider.AppExportor, addModuleInitFlags) // add keybase, auxiliary RPC, query, and tx child commands rootCmd.AddCommand( diff --git a/app/internal/app_provider.go b/app/internal/app_provider.go index cd9b2b1e0977..048d084f8e93 100644 --- a/app/internal/app_provider.go +++ b/app/internal/app_provider.go @@ -116,7 +116,7 @@ func AppConfigProvider(config *app.Config) container.Option { provideAbciMethods, app.ComposeModules(moduleConfigMap), // TODO should these be here: - container.Provide(genutilprovider.Provider), + genutilprovider.Module, query.Module, ) } diff --git a/app/module_set.go b/app/module_set.go index 5c23c947e164..89c45e0a50a5 100644 --- a/app/module_set.go +++ b/app/module_set.go @@ -9,37 +9,45 @@ import ( "go.uber.org/dig" "github.com/cosmos/cosmos-sdk/codec" - codecTypes "github.com/cosmos/cosmos-sdk/codec/types" + codectypes "github.com/cosmos/cosmos-sdk/codec/types" "github.com/cosmos/cosmos-sdk/container" ) -type moduleContainer struct { - typeRegistry codecTypes.TypeRegistry - cdc codec.Codec - opts []container.Option -} - -func (mc moduleContainer) AddProtoModule(name string, config *codecTypes.Any) error { +func addProtoModule(name string, config *codectypes.Any) container.Option { // unpack Any msgTyp := proto.MessageType(config.TypeUrl) mod := reflect.New(msgTyp.Elem()).Interface().(proto.Message) if err := proto.Unmarshal(config.Value, mod); err != nil { - return err + return container.Error(err) } - return mc.AddModule(name, mod) + return addModule(name, mod) } var moduleKeyType = reflect.TypeOf((*ModuleKey)(nil)).Elem() -func (mc *moduleContainer) AddModule(name string, mod interface{}) error { - key := &moduleKey{&moduleID{name}} +type codecClosureOutput struct { + container.Out + + CodecClosure codecClosure `group:"codec"` +} + +func addModule(name string, mod interface{}) container.Option { + var opts []container.Option - // register types if typeProvider, ok := mod.(TypeProvider); ok { - typeProvider.RegisterTypes(mc.typeRegistry) + opts = append(opts, container.Provide(func() codecClosureOutput { + return codecClosureOutput{ + CodecClosure: func(registry codectypes.TypeRegistry) { + typeProvider.RegisterTypes(registry) + }, + } + })) } + key := &moduleKey{&moduleID{name}} + + // register types // register DI Provide* methods modTy := reflect.TypeOf(mod) numMethods := modTy.NumMethod() @@ -48,30 +56,32 @@ func (mc *moduleContainer) AddModule(name string, mod interface{}) error { if strings.HasPrefix(method.Name, "Provide") { methTyp := method.Type if methTyp.IsVariadic() { - return fmt.Errorf("variadic Provide methods are not supported") + return container.Error(fmt.Errorf("variadic Provide methods are not supported")) } m := methTyp.NumIn() - 1 + fmt.Printf("method: %+v, m:%d\n", method, m) if m < 0 { - return fmt.Errorf("unexpected number of method arguments %d", m) + return container.Error(fmt.Errorf("unexpected number of method arguments %d", m)) } moduleKeyIdx := -1 var in []reflect.Type for i := 0; i < m; i++ { ty := methTyp.In(i + 1) + fmt.Printf("i:%d, ty:%+v\n", i, ty) if ty == moduleKeyType { if moduleKeyIdx >= 0 { modTy := reflect.TypeOf(mod) if modTy.Kind() == reflect.Ptr { modTy = modTy.Elem() } - return fmt.Errorf("%v can only be used as a parameter in a Provide method once, used twice in %s.%s.%s", moduleKeyType, - modTy.PkgPath(), modTy.Name(), method.Name) + return container.Error(fmt.Errorf("%v can only be used as a parameter in a Provide method once, used twice in %s.%s.%s", moduleKeyType, + modTy.PkgPath(), modTy.Name(), method.Name)) } moduleKeyIdx = i + 1 } else { - in = append(in) + in = append(in, ty) } } @@ -89,15 +99,15 @@ func (mc *moduleContainer) AddModule(name string, mod interface{}) error { args0 := append(args[:moduleKeyIdx], reflect.ValueOf(key)) args = append(args0, args[moduleKeyIdx:]...) } - fmt.Printf("modTy: %s, method: %+v, idx:%d, args:%+v\n", reflect.TypeOf(mod).Elem().PkgPath(), method, moduleKeyIdx, args) + fmt.Printf("method: %+v, args:%+v, fnTy: %+v\n", method, args, fnTyp) return method.Func.Call(args) }) - mc.opts = append(mc.opts, container.Provide(fn.Interface())) + opts = append(opts, container.Provide(fn.Interface())) } } - return nil + return container.Options(opts...) } type registrar struct { @@ -110,33 +120,36 @@ func (s registrar) Provide(fn interface{}) error { return s.ctr.Provide(fn) } -func ComposeModules(modules map[string]*codecTypes.Any) container.Option { - typeRegistry := codecTypes.NewInterfaceRegistry() - cdc := codec.NewProtoCodec(typeRegistry) - amino := codec.NewLegacyAmino() - cdcProvider := container.Provide(func() ( - codecTypes.TypeRegistry, - codec.Codec, - codec.ProtoCodecMarshaler, - codec.BinaryCodec, - codec.JSONCodec, - *codec.LegacyAmino, - ) { - return typeRegistry, cdc, cdc, cdc, cdc, amino - }) - - mc := moduleContainer{ - typeRegistry: typeRegistry, - cdc: cdc, - opts: []container.Option{cdcProvider}, - } - +func ComposeModules(modules map[string]*codectypes.Any) container.Option { + var opts []container.Option for name, mod := range modules { - err := mc.AddProtoModule(name, mod) - if err != nil { - return container.Error(err) - } + opts = append(opts, addProtoModule(name, mod)) } + return container.Options(opts...) +} + +type codecInputs struct { + container.In - return container.Options(mc.opts...) + CodecClosures []codecClosure `group:"codec"` } + +type codecClosure func(codectypes.TypeRegistry) + +var CodecProvider = container.Provide(func(inputs codecInputs) ( + codectypes.TypeRegistry, + codec.Codec, + codec.ProtoCodecMarshaler, + codec.BinaryCodec, + codec.JSONCodec, + *codec.LegacyAmino, +) { + + typeRegistry := codectypes.NewInterfaceRegistry() + for _, closure := range inputs.CodecClosures { + closure(typeRegistry) + } + cdc := codec.NewProtoCodec(typeRegistry) + amino := codec.NewLegacyAmino() + return typeRegistry, cdc, cdc, cdc, cdc, amino +}) diff --git a/client/utils.go b/client/utils.go index 944471bc90bd..4fee91b16b80 100644 --- a/client/utils.go +++ b/client/utils.go @@ -78,3 +78,5 @@ func ReadPageRequest(flagSet *pflag.FlagSet) (*query.PageRequest, error) { func NewClientFromNode(nodeURI string) (*rpchttp.HTTP, error) { return rpchttp.New(nodeURI, "/websocket") } + +type DefaultHome string diff --git a/container/option.go b/container/option.go index 80975a001235..f0cc03ae5fed 100644 --- a/container/option.go +++ b/container/option.go @@ -1,5 +1,7 @@ package container +import "fmt" + type Option interface { applyOption(*container) } @@ -36,6 +38,10 @@ func Options(opts ...Option) Option { return option{ func(container *container) { for _, opt := range opts { + if opt == nil { + container.err = fmt.Errorf("unexpected nil option") + return + } opt.applyOption(container) if container.err != nil { return diff --git a/x/genutil/provider/provider.go b/x/genutil/provider/provider.go index f50f4b1bd4a0..322d2ad6de4a 100644 --- a/x/genutil/provider/provider.go +++ b/x/genutil/provider/provider.go @@ -3,6 +3,8 @@ package provider import ( "encoding/json" + "github.com/cosmos/cosmos-sdk/container" + "github.com/spf13/cobra" "go.uber.org/dig" @@ -12,44 +14,47 @@ import ( "github.com/cosmos/cosmos-sdk/x/genutil/types" ) -type Inputs struct { +type inputs struct { dig.In - DefaultHome string `name:"cli.default-home"` - Handlers []types.Handler `group:"cosmos.genutil.v1.Handler"` + DefaultHome client.DefaultHome + Handlers []types.Handler `group:"app"` GenesisBalancesIterator types.GenesisBalancesIterator TxConfig client.TxConfig } -type Outputs struct { +type outputs struct { dig.Out RootCommands []*cobra.Command `group:"root,flatten"` } -func Provider(inputs Inputs) Outputs { - validateGenesis := func(cdc codec.JSONCodec, txEncCfg client.TxEncodingConfig, genesis map[string]json.RawMessage) error { - for _, b := range inputs.Handlers { - if err := b.ValidateGenesis(cdc, txEncCfg, genesis[b.ID.Name()]); err != nil { - return err +var Module = container.Provide( + func(inputs inputs) outputs { + validateGenesis := func(cdc codec.JSONCodec, txEncCfg client.TxEncodingConfig, genesis map[string]json.RawMessage) error { + for _, b := range inputs.Handlers { + if err := b.ValidateGenesis(cdc, txEncCfg, genesis[b.ID.Name()]); err != nil { + return err + } } + return nil } - return nil - } - - return Outputs{ - RootCommands: []*cobra.Command{ - genutilcli.InitCmd(func(cdc codec.JSONCodec) map[string]json.RawMessage { - genesis := make(map[string]json.RawMessage) - for _, b := range inputs.Handlers { - genesis[b.ID.Name()] = b.DefaultGenesis(cdc) - } - return genesis - }, inputs.DefaultHome), - genutilcli.CollectGenTxsCmd(inputs.GenesisBalancesIterator, inputs.DefaultHome), - genutilcli.MigrateGenesisCmd(), - genutilcli.GenTxCmd(validateGenesis, inputs.TxConfig, inputs.GenesisBalancesIterator, inputs.DefaultHome), - genutilcli.ValidateGenesisCmd(validateGenesis), - }, - } -} + + defaultHome := string(inputs.DefaultHome) + + return outputs{ + RootCommands: []*cobra.Command{ + genutilcli.InitCmd(func(cdc codec.JSONCodec) map[string]json.RawMessage { + genesis := make(map[string]json.RawMessage) + for _, b := range inputs.Handlers { + genesis[b.ID.Name()] = b.DefaultGenesis(cdc) + } + return genesis + }, defaultHome), + genutilcli.CollectGenTxsCmd(inputs.GenesisBalancesIterator, defaultHome), + genutilcli.MigrateGenesisCmd(), + genutilcli.GenTxCmd(validateGenesis, inputs.TxConfig, inputs.GenesisBalancesIterator, defaultHome), + genutilcli.ValidateGenesisCmd(validateGenesis), + }, + } + }) From cf53939a1623e9262b9dda8efe9122f8ba940ae7 Mon Sep 17 00:00:00 2001 From: Aaron Craelius Date: Fri, 25 Jun 2021 11:08:34 -0400 Subject: [PATCH 24/24] WIP --- x/auth/module/module.go | 2 +- x/auth/module/module.pb.go | 5 ++--- x/bank/module/module.pb.go | 3 +-- 3 files changed, 4 insertions(+), 6 deletions(-) diff --git a/x/auth/module/module.go b/x/auth/module/module.go index b2ba3a1534ee..a42464322ce0 100644 --- a/x/auth/module/module.go +++ b/x/auth/module/module.go @@ -34,7 +34,7 @@ type inputs struct { type outputs struct { dig.Out - Handler app.Handler `group:"tx"` + Handler app.Handler `group:"app"` ViewKeeper types.ViewKeeper Keeper types.Keeper `security-role:"admin"` } diff --git a/x/auth/module/module.pb.go b/x/auth/module/module.pb.go index 459b74172b49..fa167689aa1c 100644 --- a/x/auth/module/module.pb.go +++ b/x/auth/module/module.pb.go @@ -5,12 +5,11 @@ package module import ( fmt "fmt" + types "github.com/cosmos/cosmos-sdk/codec/types" + proto "github.com/gogo/protobuf/proto" io "io" math "math" math_bits "math/bits" - - types "github.com/cosmos/cosmos-sdk/codec/types" - proto "github.com/gogo/protobuf/proto" ) // Reference imports to suppress errors if they are not otherwise used. diff --git a/x/bank/module/module.pb.go b/x/bank/module/module.pb.go index b557657693d1..5ded78f054a2 100644 --- a/x/bank/module/module.pb.go +++ b/x/bank/module/module.pb.go @@ -5,11 +5,10 @@ package module import ( fmt "fmt" + proto "github.com/gogo/protobuf/proto" io "io" math "math" math_bits "math/bits" - - proto "github.com/gogo/protobuf/proto" ) // Reference imports to suppress errors if they are not otherwise used.